@edgespark/web 0.0.1 → 0.0.2

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.
package/dist/index.cjs CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const ke=require("better-auth/client");class D extends Error{constructor(e,s){super(s),this.name="EdgeSparkError",this.code=e}}class p extends D{constructor(e){super("CONFIG_ERROR",e),this.name="EdgeSparkConfigError"}}class ue extends D{constructor(e){super("RUNTIME_ERROR",e),this.name="EdgeSparkRuntimeError"}}class v extends D{constructor(e,s){super((s==null?void 0:s.code)??"AUTH_ERROR",e),this.name="EdgeSparkAuthError",this.cause=s==null?void 0:s.cause,this.status=s==null?void 0:s.status}}function Ee(t,e="Authentication failed.",s){if(t instanceof v)return t;if(typeof t=="object"&&t!==null){const i=t;return new v(i.message||e,{code:i.code??s,status:i.status,cause:t})}return typeof t=="string"?new v(t,{code:s}):new v(e,{code:s,cause:t})}function Pe(){if(typeof window>"u"||typeof document>"u")throw new ue("@edgespark/web is browser-only. Create the client from a real browser runtime.")}function ee(){return Pe(),window.location.origin}function Me(t){return t instanceof URL?t:typeof t=="string"?new URL(t,window.location.href):new URL(t.url,window.location.href)}function Oe(t){if(t.origin!==ee())throw new p(`Cross-origin requests are not supported by this SDK. Received ${t.origin}, expected ${ee()}.`)}function Ve(){return{async fetch(t,e){const s=Me(t);return Oe(s),fetch(t,{...e,credentials:"include"})}}}const Le="/api/_es/auth",Ne="edgespark-auth-session",_e="__edgespark_auth_sync__",q="__edgespark_auth_pending_sign_in__",Re=Symbol("edgespark.notifyAuthTabs"),Fe=10*60*1e3,ze=new Set(["signOut","revokeSession","revokeSessions","revokeOtherSessions"]),De=new Map([["changeEmail","changeEmail() is not currently supported by EdgeSpark platform auth."],["deleteUser","deleteUser() is not currently supported by EdgeSpark platform auth."],["deleteUserCallback","deleteUserCallback() is not currently supported by EdgeSpark platform auth."]]);class qe{constructor(e){this.value=e}deref(){return this.value}}const fe=globalThis.WeakRef,we=globalThis.FinalizationRegistry;let H,pe=!1;const $=new Map,j=we?new we(t=>{$.delete(t)}):null;function Te(t){return ke.createAuthClient({baseURL:ee(),basePath:Le,...t!=null&&t.disableDefaultRedirectPlugin?{disableDefaultFetchPlugins:!0}:{},fetchOptions:{credentials:"include"}})}function U(t){var e,s;return(s=(e=t.$store)==null?void 0:e.atoms)==null?void 0:s.session}function He(t){return JSON.stringify({source:t,timestamp:Date.now()})}function je(t){if(typeof t!="string")return null;try{const e=JSON.parse(t);return e&&typeof e=="object"?e:null}catch{return null}}function xe(t){return t.join(".")}function We(t){const e=xe(t),s=De.get(e);return s?new v(s,{code:"UNSUPPORTED_AUTH_METHOD"}):null}async function te(t){var e;try{return await((e=U(t))==null?void 0:e.get().refetch()),!0}catch{return!1}}function Ce(){return H===void 0&&(H=typeof BroadcastChannel<"u"?new BroadcastChannel(Ne):null),H}function ge(t){const e=je(t);if(e)for(const[s,i]of $){if(s===e.source)continue;const n=i.deref();if(!n){$.delete(s);continue}te(n)}}function Ge(){var t;pe||(pe=!0,(t=Ce())==null||t.addEventListener("message",e=>{ge(e.data)}),typeof window<"u"&&window.addEventListener("storage",e=>{e.key!==_e||e.newValue===null||ge(e.newValue)}))}function Ke(t,e){fe?$.set(t,new fe(e)):($.clear(),$.set(t,new qe(e))),j==null||j.register(e,t),Ge()}function I(t){const e=He(t),s=Ce();let i=!1;if(s)try{s.postMessage(e),i=!0}catch{}if(!i)try{window.localStorage.setItem(_e,e)}catch{}}function x(t){if(!(typeof window>"u"))try{window.sessionStorage.setItem(q,JSON.stringify({path:t,createdAt:Date.now()}))}catch{}}function A(){if(!(typeof window>"u"))try{window.sessionStorage.removeItem(q)}catch{}}function Ye(t){return!!(t!=null&&t.session&&(t!=null&&t.user))}function h(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 Je(t){return t?JSON.stringify({session:{createdAt:h(t.session.createdAt),expiresAt:h(t.session.expiresAt),id:h(t.session.id),impersonatedBy:h(t.session.impersonatedBy),ipAddress:h(t.session.ipAddress),token:h(t.session.token),updatedAt:h(t.session.updatedAt),userAgent:h(t.session.userAgent),userId:h(t.session.userId)},user:{banExpires:h(t.user.banExpires),banReason:h(t.user.banReason),banned:h(t.user.banned),createdAt:h(t.user.createdAt),email:h(t.user.email),emailVerified:h(t.user.emailVerified),id:h(t.user.id),image:h(t.user.image),lastLoginAt:h(t.user.lastLoginAt),name:h(t.user.name),role:h(t.user.role),updatedAt:h(t.user.updatedAt)}}):"__null__"}function Ie(){if(typeof window>"u")return null;try{const t=window.sessionStorage.getItem(q);if(!t)return null;const e=JSON.parse(t);return!e||typeof e!="object"||typeof e.createdAt!="number"||Date.now()-e.createdAt>Fe?null:{createdAt:e.createdAt}}catch{return null}}function be(){if(!Ie())return!1;try{window.sessionStorage.removeItem(q)}catch{}return!0}function Ze(){return Ie()!==null}function Qe(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 Xe(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 et(t){if(L(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 tt(t,e){if(t.length!==1||t[0]!=="changePassword")return!1;const[s]=e;return!!(s&&typeof s=="object"&&"revokeOtherSessions"in s&&s.revokeOtherSessions===!0)}function L(t){return!!(t&&typeof t=="object"&&"error"in t&&t.error)}function st(t){if(L(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 it(t){return!!(t&&(typeof t=="object"||typeof t=="function")&&"then"in t&&typeof t.then=="function")}function W(t){return Ee(t,"Failed to load the current session.","SESSION_LOOKUP_FAILED")}async function nt(t){var s,i;let e=null;try{await((s=U(t))==null?void 0:s.get().refetch())}catch(n){e=n}finally{(i=t[Re])==null||i.call(t)}if(e)throw e}function rt(){const t=Te(),e=`${Date.now()}-${Math.random().toString(36).slice(2)}`;Ke(e,t);const s=2,i=500;let n=null,a=!1,m;const b=o=>(m=o,o),_=()=>{var c;const o=(c=U(t))==null?void 0:c.get();return o!=null&&o.error&&!o.data&&m!==void 0?m:(o==null?void 0:o.data)??m??null},R=()=>a?Promise.resolve(_()):(n||(n=(async()=>{var l,u,y;let o=!1,c=null;try{for(let g=0;g<=s;g++){let d=null;try{d=await t.getSession()}catch(S){c=S}const w=((l=U(t))==null?void 0:l.get().data)??null;if((u=d==null?void 0:d.data)!=null&&u.session&&((y=d.data)!=null&&y.user))return a=!0,be()&&I(e),b(d.data);if(w!=null&&w.session&&(w!=null&&w.user))return a=!0,be()&&I(e),b(w);if(d!=null&&d.error?c=d.error:d&&(o=!0),d&&!d.error&&Ze()&&g<s){await new Promise(S=>setTimeout(S,i));continue}if(d&&!d.error){const S=_();return a=!0,b(S)}g<s&&await new Promise(S=>setTimeout(S,i))}if(!o)throw n=null,new v("Failed to load the current session.",{code:"SESSION_LOOKUP_FAILED",cause:c});const f=_();return a=!0,b(f)}catch(f){throw n=null,W(f)}})()),n);R().catch(()=>{});const T=async()=>{var o,c;try{const l=await t.getSession();if((o=l.data)!=null&&o.session&&((c=l.data)!=null&&c.user))return l.data;throw l.error?W(l.error):new v("No authenticated session is available.",{code:"UNAUTHENTICATED"})}catch(l){throw W(l)}},C=async()=>{await te(t),I(e)},Ue=async()=>{var l;const o=await te(t),c=((l=U(t))==null?void 0:l.get().data)??null;Ye(c)?(A(),I(e)):o||I(e)},$e=o=>{let c=!1,l=!1,u;const y=d=>{const w=Je(d);w!==u&&(u=w,o(d))};R().then(d=>{c||(l=!0,y(b(d)))}).catch(()=>{c||(l=!0)});const f=U(t);if(!f)return()=>{c=!0};const g=f.subscribe(d=>{if(c||!l||d.error&&!d.data)return;const w=d.data??null;y(b(w))});return()=>{c=!0,g()}},Be=async(o,c,l)=>{const u=o[0],y=o.length>=2&&u==="emailOtp"&&o[1]==="verifyEmail",f=o.length>=2&&u==="emailOtp"&&o[1]==="resetPassword",g=o.length>=2&&u==="resetPassword"&&o[1]==="emailOtp";return o.length===1&&(u==="deleteUser"||u==="deleteUserCallback")?(A(),st(l)&&await C(),l):o.length===1&&u&&ze.has(u)?(A(),L(l)||await C(),l):tt(o,c)&&!L(l)?(A(),await C(),l):(f||g)&&!L(l)?(A(),await C(),l):o.length===1&&u==="changeEmail"&&!L(l)?(await C(),l):((u==="signIn"||u==="signUp"||y)&&Qe(l)?(A(),await C()):(u==="signIn"||u==="signUp")&&Xe(l)||u==="signUp"&&et(l)?x(o):u==="verifyEmail"&&!L(l)&&(x(o),await Ue()),l)},he=new WeakMap,me=(o,c)=>{if(!o||typeof o!="object"&&typeof o!="function")return o;const l=he.get(o);if(l)return l;const u=new Proxy(o,{get(y,f,g){if(c.length===0){if(f==="requireSession")return T;if(f==="onSessionChange")return $e;if(f===Re)return()=>{I(e)}}const d=Reflect.get(y,f,g);return typeof f!="string"?d:me(d,[...c,f])},apply(y,f,g){const d=We(c);if(d)throw d;const w=Reflect.apply(y,f,g);return it(w)?Promise.resolve(w).then(S=>Be(c,g,S)):w}});return he.set(o,u),u};return me(t,[])}function ot(){return Te({disableDefaultRedirectPlugin:!0})}function at(t){const e=(()=>{if(t instanceof URL)return t;const s=t.trim();if(!s)throw new p("redirectTo must not be an empty string.");try{return new URL(s,window.location.href)}catch{throw new p(`redirectTo must be a valid relative path or URL. Received: ${JSON.stringify(t)}`)}})();if(e.protocol!=="http:"&&e.protocol!=="https:")throw new p(`redirectTo must resolve to an http(s) URL. Received protocol: ${e.protocol}`);return e}function lt(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 k={common:{loading:"Loading sign-in…",redirecting:"Redirecting…",backToSignIn:"Back to sign in"},signIn:{title:"Welcome back",subtitle:"Sign in to continue",emailLabel:"Email",passwordLabel:"Password",submitButton:"Sign in",forgotPassword:"Forgot password?",switchToSignUp:"Create an account",signUpPrompt:"Don’t have an account?"},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:{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."}},F={common:{loading:"加载中…",redirecting:"跳转中…",backToSignIn:"返回登录"},signIn:{title:"欢迎回来",subtitle:"登录以继续",emailLabel:"邮箱",passwordLabel:"密码",submitButton:"登录",forgotPassword:"忘记密码?",switchToSignUp:"立即注册",signUpPrompt:"没有账号?"},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:{dividerText:"或",continueWith:"使用"},errors:{invalidEmail:"请输入有效的邮箱地址",requiredField:"此项为必填",passwordTooShort:"密码至少需要 {min} 个字符",passwordMismatch:"两次密码输入不一致",invalidCode:"请输入 6 位验证码",generic:"出现错误,请稍后重试"}},se={common:{loading:"サインインを読み込み中…",redirecting:"リダイレクト中…",backToSignIn:"サインインに戻る"},signIn:{title:"おかえりなさい",subtitle:"サインインして続行",emailLabel:"メールアドレス",passwordLabel:"パスワード",submitButton:"サインイン",forgotPassword:"パスワードをお忘れですか?",switchToSignUp:"アカウントを作成",signUpPrompt:"アカウントをお持ちでない方"},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:{dividerText:"または",continueWith:"で続行"},errors:{invalidEmail:"有効なメールアドレスを入力してください",requiredField:"この項目は必須です",passwordTooShort:"パスワードは {min} 文字以上で入力してください",passwordMismatch:"パスワードが一致しません",invalidCode:"6桁の認証コードを入力してください",generic:"エラーが発生しました。もう一度お試しください"}},ie={common:{loading:"로그인 로딩 중…",redirecting:"리디렉션 중…",backToSignIn:"로그인으로 돌아가기"},signIn:{title:"다시 오신 것을 환영합니다",subtitle:"로그인하여 계속하기",emailLabel:"이메일",passwordLabel:"비밀번호",submitButton:"로그인",forgotPassword:"비밀번호를 잊으셨나요?",switchToSignUp:"계정 만들기",signUpPrompt:"계정이 없으신가요?"},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:{dividerText:"또는",continueWith:"으로 계속"},errors:{invalidEmail:"올바른 이메일 주소를 입력해 주세요",requiredField:"필수 입력 항목입니다",passwordTooShort:"비밀번호는 최소 {min}자 이상이어야 합니다",passwordMismatch:"비밀번호가 일치하지 않습니다",invalidCode:"6자리 인증 코드를 입력해 주세요",generic:"문제가 발생했습니다. 다시 시도해 주세요"}},z={common:{loading:"Cargando inicio de sesión…",redirecting:"Redirigiendo…",backToSignIn:"Volver a iniciar sesión"},signIn:{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?"},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:{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."}},ne={common:{loading:"Carregando login…",redirecting:"Redirecionando…",backToSignIn:"Voltar para o login"},signIn:{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?"},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:{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."}},re={common:{loading:"Chargement de la connexion…",redirecting:"Redirection…",backToSignIn:"Retour à la connexion"},signIn:{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 ?"},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:{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."}},oe={common:{loading:"Anmeldung wird geladen…",redirecting:"Weiterleitung…",backToSignIn:"Zurück zur Anmeldung"},signIn:{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?"},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:{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."}},ae={common:{loading:"Caricamento accesso…",redirecting:"Reindirizzamento…",backToSignIn:"Torna all’accesso"},signIn:{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?"},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:{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."}},le={common:{loading:"Загрузка входа…",redirecting:"Перенаправление…",backToSignIn:"Вернуться ко входу"},signIn:{title:"С возвращением",subtitle:"Войдите, чтобы продолжить",emailLabel:"Электронная почта",passwordLabel:"Пароль",submitButton:"Войти",forgotPassword:"Забыли пароль?",switchToSignUp:"Создать аккаунт",signUpPrompt:"Нет аккаунта?"},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:{dividerText:"или",continueWith:"Продолжить через"},errors:{invalidEmail:"Введите корректный адрес электронной почты.",requiredField:"Это поле обязательно.",passwordTooShort:"Пароль должен содержать не менее {min} символов.",passwordMismatch:"Пароли не совпадают.",invalidCode:"Введите 6-значный код подтверждения.",generic:"Произошла ошибка. Пожалуйста, попробуйте снова."}},de={common:{loading:"جارٍ تحميل تسجيل الدخول…",redirecting:"جارٍ إعادة التوجيه…",backToSignIn:"العودة إلى تسجيل الدخول"},signIn:{title:"مرحبًا بعودتك",subtitle:"سجّل الدخول للمتابعة",emailLabel:"البريد الإلكتروني",passwordLabel:"كلمة المرور",submitButton:"تسجيل الدخول",forgotPassword:"هل نسيت كلمة المرور؟",switchToSignUp:"إنشاء حساب",signUpPrompt:"ليس لديك حساب؟"},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:{dividerText:"أو",continueWith:"المتابعة باستخدام"},errors:{invalidEmail:"يرجى إدخال عنوان بريد إلكتروني صالح.",requiredField:"هذا الحقل مطلوب.",passwordTooShort:"يجب أن تتكوّن كلمة المرور من {min} حرفًا على الأقل.",passwordMismatch:"كلمتا المرور غير متطابقتين.",invalidCode:"يرجى إدخال رمز التحقّق المكوّن من 6 أرقام.",generic:"حدث خطأ. يرجى المحاولة مرة أخرى."}},ce={common:{loading:"सधाइन की जुलातीअ लोड हो रही है…",redirecting:"रीडायरेक्ट हो रहا है…",backToSignIn:"साइन इन पर वापस जाएँ"},signIn:{title:"वापसी आपका स्वागत है",subtitle:"जारी रखने के लिए साइन इन करें",emailLabel:"ईमेल",passwordLabel:"पासवर्ड",submitButton:"साइन इन",forgotPassword:"पासवर्ड भूल गए?",switchToSignUp:"खाता बनाएँ",signUpPrompt:"खाता नहीं है?"},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:{dividerText:"या",continueWith:"से जारी रखें"},errors:{invalidEmail:"कृपया एक वैध ईमेल पता दर्ज करें।",requiredField:"यह फ़ील्ड आवश्यक है।",passwordTooShort:"पासवर्ड कम से कम {min} अक्षरों का होना चाहिए।",passwordMismatch:"पासवर्ड मेल नहीं खाते।",invalidCode:"कृपया 6 अंकों का सत्यापन कोड दर्ज करें।",generic:"कुछ गलत हो गई। कृपया फिर से प्रयास करें।"}},ye={en:k,"en-US":k,zh:F,"zh-CN":F,"zh-TW":F,ja:se,"ja-JP":se,ko:ie,"ko-KR":ie,es:z,"es-ES":z,"es-MX":z,pt:ne,"pt-BR":ne,fr:re,"fr-FR":re,de:oe,"de-DE":oe,it:ae,"it-IT":ae,ru:le,"ru-RU":le,ar:de,"ar-SA":de,hi:ce,"hi-IN":ce};function Ae(){if(typeof navigator>"u")return k;const t=navigator.languages??[navigator.language];for(const e of t){const s=ye[e]??ye[e.split("-")[0]];if(s)return s}return k}function G(t,e="Authentication failed."){return Ee(t,e)}async function M(t){var s,i;const e=await t.getSession();if(e.error)throw new v(e.error.message||"Failed to load the current session.",{code:e.error.code??"SESSION_LOOKUP_FAILED",status:e.error.status,cause:e.error});return(s=e.data)!=null&&s.user&&((i=e.data)!=null&&i.session)?{user:e.data.user,session:e.data}:{user:null,session:null}}const dt="data-edgespark-auth",r="edgespark-auth",K="es_auth_completion",O="es_auth_email",Y="oauth",B="verify-sign-in",E="verify-sign-up",ve=200,J=2,ct={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},Z={google:"Google",apple:"Apple",microsoft:"Microsoft",github:"GitHub",gitlab:"GitLab",discord:"Discord"};function P(t){return"redirectTo"in t}function Q(t){return"onSuccess"in t&&!("redirectTo"in t)}function X(t){return!t||typeof t!="string"?!1:/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(t.trim())}function ut(t){return/^\d{6}$/.test(t.trim())}function ht(t){return t==="email"||t==="name"||t==="password"||t==="confirmPassword"||t==="code"||t==="newPassword"}function mt(t){return!!(t.error||t.errorDescription)}class ft{constructor(e,s,i,n,a){this.container=e,this.auth=s,this.options=i,this.loadConfig=n,this.runtimeOptions=a,this.state={view:"loading",busy:!0,busyLabel:void 0,error:null,notice:null,email:"",name:"",password:"",confirmPassword:"",code:"",newPassword:""},this.destroyed=!1,this.terminalActionInProgress=!1,this.config=null,this.countdownUntil=null,this.countdownTimer=null,this.pendingFocusSnapshot=null,this.focusRestoreTimer=null,this.verificationCompletionAction=null,this.labels=lt(Ae(),i.labels),this.root=document.createElement("div"),this.root.setAttribute(dt,""),e.innerHTML="",e.appendChild(this.root),this.render(),this.initialize()}destroy(){this.destroyed||(this.destroyed=!0,this.clearCountdown(),this.clearFocusRestoreTimer(),this.container.innerHTML="")}async initialize(){const e=this.consumeManagedReturnContext();try{const[s,i]=await Promise.allSettled([this.loadConfig(),this.readMountSession(e)]);if(this.destroyed)return;if(i.status==="rejected"){if(e.marker&&!mt(e)&&P(this.options)){this.redirectAfterManagedReturnLookupFailure();return}}else{const a=i.value;if(a.user&&a.session){switch(e.marker){case Y:case B:await this.completeAuth("sign-in",a);return;case E:await this.completeAuth("sign-up",a);return;default:break}this.handleExistingSessionOnMount();return}}if(s.status==="rejected")throw i.status==="rejected"?i.reason:s.reason;if(this.config=s.value,this.handleSessionlessManagedReturn(e))return;if(i.status==="rejected")throw i.reason;const n=i.value;this.state.view="sign-in",this.state.busy=!1,this.state.busyLabel=void 0,this.render()}catch(s){this.handleError(s,"Failed to load the authentication UI.")}}redirectAfterManagedReturnLookupFailure(){P(this.options)&&this.navigateToRedirect()}navigateToRedirect(){P(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 M(this.auth);let s=null;for(let i=0;i<=J;i++){try{const n=await M(this.auth);if(n.user&&n.session)return n}catch(n){s=n}i<J&&await new Promise(n=>setTimeout(n,ve))}if(s)throw s;return{user:null,session:null}}render(){if(this.destroyed)return;const e=this.captureFocusSnapshot();if(e&&(this.pendingFocusSnapshot=e),!this.config){this.root.innerHTML=this.renderLoading();return}this.root.innerHTML=`
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const Fe=require("better-auth/client");class F extends Error{constructor(e,s){super(s),this.name="EdgeSparkError",this.code=e}}class m extends F{constructor(e){super("CONFIG_ERROR",e),this.name="EdgeSparkConfigError"}}class ue extends F{constructor(e){super("RUNTIME_ERROR",e),this.name="EdgeSparkRuntimeError"}}class v extends F{constructor(e,s){super((s==null?void 0:s.code)??"AUTH_ERROR",e),this.name="EdgeSparkAuthError",this.cause=s==null?void 0:s.cause,this.status=s==null?void 0:s.status}}function Le(t,e="Authentication failed.",s){if(t instanceof v)return t;if(typeof t=="object"&&t!==null){const i=t;return new v(i.message||e,{code:i.code??s,status:i.status,cause:t})}return typeof t=="string"?new v(t,{code:s}):new v(e,{code:s,cause:t})}function Ae(){if(typeof window>"u"||typeof document>"u")throw new ue("@edgespark/web is browser-only. Create the client from a real browser runtime.")}function ee(){return Ae(),window.location.origin}function ze(t){return t instanceof URL?t:typeof t=="string"?new URL(t,window.location.href):new URL(t.url,window.location.href)}function je(t){if(t.origin!==ee())throw new m(`Cross-origin requests are not supported by this SDK. Received ${t.origin}, expected ${ee()}.`)}function qe(){return{async fetch(t,e){const s=ze(t);return je(s),fetch(t,{...e,credentials:"include"})}}}const Te="/api/_es/auth",xe="edgespark-auth-session",Re="__edgespark_auth_sync__",z="__edgespark_auth_pending_sign_in__",Ie=Symbol("edgespark.notifyAuthTabs"),Ge=10*60*1e3,Ke=new Set(["signOut","revokeSession","revokeSessions","revokeOtherSessions"]),We=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 Ye{constructor(e){this.value=e}deref(){return this.value}}const ge=globalThis.WeakRef,be=globalThis.FinalizationRegistry;let j,ye=!1;const $=new Map,q=be?new be(t=>{$.delete(t)}):null;function Ue(t){return Fe.createAuthClient({baseURL:ee(),basePath:Te,...t!=null&&t.disableDefaultRedirectPlugin?{disableDefaultFetchPlugins:!0}:{},fetchOptions:{credentials:"include"}})}function C(t){var e,s;return(s=(e=t.$store)==null?void 0:e.atoms)==null?void 0:s.session}function Je(t){return JSON.stringify({source:t,timestamp:Date.now()})}function Xe(t){if(typeof t!="string")return null;try{const e=JSON.parse(t);return e&&typeof e=="object"?e:null}catch{return null}}function Ze(t){return t.join(".")}function Qe(t){const e=Ze(t),s=We.get(e);return s?new v(s,{code:"UNSUPPORTED_AUTH_METHOD"}):null}async function te(t){var e;try{return await((e=C(t))==null?void 0:e.get().refetch()),!0}catch{return!1}}function Ce(){return j===void 0&&(j=typeof BroadcastChannel<"u"?new BroadcastChannel(xe):null),j}function ve(t){const e=Xe(t);if(e)for(const[s,i]of $){if(s===e.source)continue;const n=i.deref();if(!n){$.delete(s);continue}te(n)}}function et(){var t;ye||(ye=!0,(t=Ce())==null||t.addEventListener("message",e=>{ve(e.data)}),typeof window<"u"&&window.addEventListener("storage",e=>{e.key!==Re||e.newValue===null||ve(e.newValue)}))}function tt(t,e){ge?$.set(t,new ge(e)):($.clear(),$.set(t,new Ye(e))),q==null||q.register(e,t),et()}function I(t){const e=Je(t),s=Ce();let i=!1;if(s)try{s.postMessage(e),i=!0}catch{}if(!i)try{window.localStorage.setItem(Re,e)}catch{}}function x(t){if(!(typeof window>"u"))try{window.sessionStorage.setItem(z,JSON.stringify({path:t,createdAt:Date.now()}))}catch{}}function U(){if(!(typeof window>"u"))try{window.sessionStorage.removeItem(z)}catch{}}function st(t){return!!(t!=null&&t.session&&(t!=null&&t.user))}function f(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 it(t){return t?JSON.stringify({session:{createdAt:f(t.session.createdAt),expiresAt:f(t.session.expiresAt),id:f(t.session.id),impersonatedBy:f(t.session.impersonatedBy),ipAddress:f(t.session.ipAddress),token:f(t.session.token),updatedAt:f(t.session.updatedAt),userAgent:f(t.session.userAgent),userId:f(t.session.userId)},user:{banExpires:f(t.user.banExpires),banReason:f(t.user.banReason),banned:f(t.user.banned),createdAt:f(t.user.createdAt),email:f(t.user.email),emailVerified:f(t.user.emailVerified),id:f(t.user.id),image:f(t.user.image),lastLoginAt:f(t.user.lastLoginAt),name:f(t.user.name),role:f(t.user.role),updatedAt:f(t.user.updatedAt)}}):"__null__"}function $e(){if(typeof window>"u")return null;try{const t=window.sessionStorage.getItem(z);if(!t)return null;const e=JSON.parse(t);return!e||typeof e!="object"||typeof e.createdAt!="number"||Date.now()-e.createdAt>Ge?null:{createdAt:e.createdAt}}catch{return null}}function Ee(){if(!$e())return!1;try{window.sessionStorage.removeItem(z)}catch{}return!0}function nt(){return $e()!==null}function rt(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 ot(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 at(t){if(L(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 lt(t,e){if(t.length!==1||t[0]!=="changePassword")return!1;const[s]=e;return!!(s&&typeof s=="object"&&"revokeOtherSessions"in s&&s.revokeOtherSessions===!0)}function L(t){return!!(t&&typeof t=="object"&&"error"in t&&t.error)}function dt(t){if(L(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 ct(t){return!!(t&&(typeof t=="object"||typeof t=="function")&&"then"in t&&typeof t.then=="function")}function G(t){return Le(t,"Failed to load the current session.","SESSION_LOOKUP_FAILED")}async function ut(t){var s,i;let e=null;try{await((s=C(t))==null?void 0:s.get().refetch())}catch(n){e=n}finally{(i=t[Ie])==null||i.call(t)}if(e)throw e}function ht(){const t=Ue(),e=`${Date.now()}-${Math.random().toString(36).slice(2)}`;tt(e,t);const s=2,i=500;let n=null,a=!1,u;const g=o=>(u=o,o),E=()=>{var c;const o=(c=C(t))==null?void 0:c.get();return o!=null&&o.error&&!o.data&&u!==void 0?u:(o==null?void 0:o.data)??u??null},A=()=>a?Promise.resolve(E()):(n||(n=(async()=>{var l,h,y;let o=!1,c=null;try{for(let b=0;b<=s;b++){let d=null;try{d=await t.getSession()}catch(S){c=S}const p=((l=C(t))==null?void 0:l.get().data)??null;if((h=d==null?void 0:d.data)!=null&&h.session&&((y=d.data)!=null&&y.user))return a=!0,Ee()&&I(e),g(d.data);if(p!=null&&p.session&&(p!=null&&p.user))return a=!0,Ee()&&I(e),g(p);if(d!=null&&d.error?c=d.error:d&&(o=!0),d&&!d.error&&nt()&&b<s){await new Promise(S=>setTimeout(S,i));continue}if(d&&!d.error){const S=E();return a=!0,g(S)}b<s&&await new Promise(S=>setTimeout(S,i))}if(!o)throw n=null,new v("Failed to load the current session.",{code:"SESSION_LOOKUP_FAILED",cause:c});const w=E();return a=!0,g(w)}catch(w){throw n=null,G(w)}})()),n);A().catch(()=>{});const T=async()=>{var o,c;try{const l=await t.getSession();if((o=l.data)!=null&&o.session&&((c=l.data)!=null&&c.user))return l.data;throw l.error?G(l.error):new v("No authenticated session is available.",{code:"UNAUTHENTICATED"})}catch(l){throw G(l)}},R=async()=>{await te(t),I(e)},Ve=async()=>{var l;const o=await te(t),c=((l=C(t))==null?void 0:l.get().data)??null;st(c)?(U(),I(e)):o||I(e)},De=o=>{let c=!1,l=!1,h;const y=d=>{const p=it(d);p!==h&&(h=p,o(d))};A().then(d=>{c||(l=!0,y(g(d)))}).catch(()=>{c||(l=!0)});const w=C(t);if(!w)return()=>{c=!0};const b=w.subscribe(d=>{if(c||!l||d.error&&!d.data)return;const p=d.data??null;y(g(p))});return()=>{c=!0,b()}},He=async(o,c,l)=>{const h=o[0],y=o.length>=2&&h==="emailOtp"&&o[1]==="verifyEmail",w=o.length>=2&&h==="emailOtp"&&o[1]==="resetPassword",b=o.length>=2&&h==="resetPassword"&&o[1]==="emailOtp";return o.length===1&&(h==="deleteUser"||h==="deleteUserCallback")?(U(),dt(l)&&await R(),l):o.length===1&&h&&Ke.has(h)?(U(),L(l)||await R(),l):lt(o,c)&&!L(l)?(U(),await R(),l):(w||b)&&!L(l)?(U(),await R(),l):o.length===1&&h==="changeEmail"&&!L(l)?(await R(),l):((h==="signIn"||h==="signUp"||y)&&rt(l)?(U(),await R()):(h==="signIn"||h==="signUp")&&ot(l)||h==="signUp"&&at(l)?x(o):h==="verifyEmail"&&!L(l)&&(x(o),await Ve()),l)},we=new WeakMap,pe=(o,c)=>{if(!o||typeof o!="object"&&typeof o!="function")return o;const l=we.get(o);if(l)return l;const h=new Proxy(o,{get(y,w,b){if(c.length===0){if(w==="requireSession")return T;if(w==="onSessionChange")return De;if(w===Ie)return()=>{I(e)}}const d=Reflect.get(y,w,b);return typeof w!="string"?d:pe(d,[...c,w])},apply(y,w,b){const d=Qe(c);if(d)throw d;const p=Reflect.apply(y,w,b);return ct(p)?Promise.resolve(p).then(S=>He(c,b,S)):p}});return we.set(o,h),h};return pe(t,[])}function mt(){return Ue({disableDefaultRedirectPlugin:!0})}function ft(t){const e=(()=>{if(t instanceof URL)return t;const s=t.trim();if(!s)throw new m("redirectTo must not be an empty string.");try{return new URL(s,window.location.href)}catch{throw new m(`redirectTo must be a valid relative path or URL. Received: ${JSON.stringify(t)}`)}})();if(e.protocol!=="http:"&&e.protocol!=="https:")throw new m(`redirectTo must resolve to an http(s) URL. Received protocol: ${e.protocol}`);return e}function wt(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 B={common:{loading:"Loading sign-in…",redirecting:"Redirecting…",backToSignIn:"Back to sign in"},signIn:{title:"Welcome back",subtitle:"Sign in to continue",emailLabel:"Email",passwordLabel:"Password",submitButton:"Sign in",forgotPassword:"Forgot password?",switchToSignUp:"Create an account",signUpPrompt:"Don’t have an account?"},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:{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."}},D={common:{loading:"加载中…",redirecting:"跳转中…",backToSignIn:"返回登录"},signIn:{title:"欢迎回来",subtitle:"登录以继续",emailLabel:"邮箱",passwordLabel:"密码",submitButton:"登录",forgotPassword:"忘记密码?",switchToSignUp:"立即注册",signUpPrompt:"没有账号?"},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:{dividerText:"或",continueWith:"使用"},errors:{invalidEmail:"请输入有效的邮箱地址",requiredField:"此项为必填",passwordTooShort:"密码至少需要 {min} 个字符",passwordMismatch:"两次密码输入不一致",invalidCode:"请输入 6 位验证码",generic:"出现错误,请稍后重试"}},se={common:{loading:"サインインを読み込み中…",redirecting:"リダイレクト中…",backToSignIn:"サインインに戻る"},signIn:{title:"おかえりなさい",subtitle:"サインインして続行",emailLabel:"メールアドレス",passwordLabel:"パスワード",submitButton:"サインイン",forgotPassword:"パスワードをお忘れですか?",switchToSignUp:"アカウントを作成",signUpPrompt:"アカウントをお持ちでない方"},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:{dividerText:"または",continueWith:"で続行"},errors:{invalidEmail:"有効なメールアドレスを入力してください",requiredField:"この項目は必須です",passwordTooShort:"パスワードは {min} 文字以上で入力してください",passwordMismatch:"パスワードが一致しません",invalidCode:"6桁の認証コードを入力してください",generic:"エラーが発生しました。もう一度お試しください"}},ie={common:{loading:"로그인 로딩 중…",redirecting:"리디렉션 중…",backToSignIn:"로그인으로 돌아가기"},signIn:{title:"다시 오신 것을 환영합니다",subtitle:"로그인하여 계속하기",emailLabel:"이메일",passwordLabel:"비밀번호",submitButton:"로그인",forgotPassword:"비밀번호를 잊으셨나요?",switchToSignUp:"계정 만들기",signUpPrompt:"계정이 없으신가요?"},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:{dividerText:"또는",continueWith:"으로 계속"},errors:{invalidEmail:"올바른 이메일 주소를 입력해 주세요",requiredField:"필수 입력 항목입니다",passwordTooShort:"비밀번호는 최소 {min}자 이상이어야 합니다",passwordMismatch:"비밀번호가 일치하지 않습니다",invalidCode:"6자리 인증 코드를 입력해 주세요",generic:"문제가 발생했습니다. 다시 시도해 주세요"}},H={common:{loading:"Cargando inicio de sesión…",redirecting:"Redirigiendo…",backToSignIn:"Volver a iniciar sesión"},signIn:{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?"},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:{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."}},ne={common:{loading:"Carregando login…",redirecting:"Redirecionando…",backToSignIn:"Voltar para o login"},signIn:{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?"},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:{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."}},re={common:{loading:"Chargement de la connexion…",redirecting:"Redirection…",backToSignIn:"Retour à la connexion"},signIn:{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 ?"},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:{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."}},oe={common:{loading:"Anmeldung wird geladen…",redirecting:"Weiterleitung…",backToSignIn:"Zurück zur Anmeldung"},signIn:{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?"},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:{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."}},ae={common:{loading:"Caricamento accesso…",redirecting:"Reindirizzamento…",backToSignIn:"Torna all’accesso"},signIn:{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?"},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:{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."}},le={common:{loading:"Загрузка входа…",redirecting:"Перенаправление…",backToSignIn:"Вернуться ко входу"},signIn:{title:"С возвращением",subtitle:"Войдите, чтобы продолжить",emailLabel:"Электронная почта",passwordLabel:"Пароль",submitButton:"Войти",forgotPassword:"Забыли пароль?",switchToSignUp:"Создать аккаунт",signUpPrompt:"Нет аккаунта?"},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:{dividerText:"или",continueWith:"Продолжить через"},errors:{invalidEmail:"Введите корректный адрес электронной почты.",requiredField:"Это поле обязательно.",passwordTooShort:"Пароль должен содержать не менее {min} символов.",passwordMismatch:"Пароли не совпадают.",invalidCode:"Введите 6-значный код подтверждения.",generic:"Произошла ошибка. Пожалуйста, попробуйте снова."}},de={common:{loading:"جارٍ تحميل تسجيل الدخول…",redirecting:"جارٍ إعادة التوجيه…",backToSignIn:"العودة إلى تسجيل الدخول"},signIn:{title:"مرحبًا بعودتك",subtitle:"سجّل الدخول للمتابعة",emailLabel:"البريد الإلكتروني",passwordLabel:"كلمة المرور",submitButton:"تسجيل الدخول",forgotPassword:"هل نسيت كلمة المرور؟",switchToSignUp:"إنشاء حساب",signUpPrompt:"ليس لديك حساب؟"},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:{dividerText:"أو",continueWith:"المتابعة باستخدام"},errors:{invalidEmail:"يرجى إدخال عنوان بريد إلكتروني صالح.",requiredField:"هذا الحقل مطلوب.",passwordTooShort:"يجب أن تتكوّن كلمة المرور من {min} حرفًا على الأقل.",passwordMismatch:"كلمتا المرور غير متطابقتين.",invalidCode:"يرجى إدخال رمز التحقّق المكوّن من 6 أرقام.",generic:"حدث خطأ. يرجى المحاولة مرة أخرى."}},ce={common:{loading:"सधाइन की जुलातीअ लोड हो रही है…",redirecting:"रीडायरेक्ट हो रहا है…",backToSignIn:"साइन इन पर वापस जाएँ"},signIn:{title:"वापसी आपका स्वागत है",subtitle:"जारी रखने के लिए साइन इन करें",emailLabel:"ईमेल",passwordLabel:"पासवर्ड",submitButton:"साइन इन",forgotPassword:"पासवर्ड भूल गए?",switchToSignUp:"खाता बनाएँ",signUpPrompt:"खाता नहीं है?"},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:{dividerText:"या",continueWith:"से जारी रखें"},errors:{invalidEmail:"कृपया एक वैध ईमेल पता दर्ज करें।",requiredField:"यह फ़ील्ड आवश्यक है।",passwordTooShort:"पासवर्ड कम से कम {min} अक्षरों का होना चाहिए।",passwordMismatch:"पासवर्ड मेल नहीं खाते।",invalidCode:"कृपया 6 अंकों का सत्यापन कोड दर्ज करें।",generic:"कुछ गलत हो गई। कृपया फिर से प्रयास करें।"}},Se={en:B,"en-US":B,zh:D,"zh-CN":D,"zh-TW":D,ja:se,"ja-JP":se,ko:ie,"ko-KR":ie,es:H,"es-ES":H,"es-MX":H,pt:ne,"pt-BR":ne,fr:re,"fr-FR":re,de:oe,"de-DE":oe,it:ae,"it-IT":ae,ru:le,"ru-RU":le,ar:de,"ar-SA":de,hi:ce,"hi-IN":ce};function ke(){if(typeof navigator>"u")return B;const t=navigator.languages??[navigator.language];for(const e of t){const s=Se[e]??Se[e.split("-")[0]];if(s)return s}return B}const he={LIGHT:"light",DARK:"dark"},me=he.LIGHT,Be=he.DARK,fe=[me,Be],Me=me,Oe={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"},Ne=Object.values(Oe);function pt(t){return typeof t=="string"&&fe.includes(t)}function gt(t){return Ne.includes(t)}function bt(t){var e;return{theme:(t==null?void 0:t.theme)??Me,className:((e=t==null?void 0:t.className)==null?void 0:e.trim())??"",variables:{...(t==null?void 0:t.variables)??{}}}}function K(t,e="Authentication failed."){return Le(t,e)}async function M(t){var s,i;const e=await t.getSession();if(e.error)throw new v(e.error.message||"Failed to load the current session.",{code:e.error.code??"SESSION_LOOKUP_FAILED",status:e.error.status,cause:e.error});return(s=e.data)!=null&&s.user&&((i=e.data)!=null&&i.session)?{user:e.data.user,session:e.data}:{user:null,session:null}}const yt="data-edgespark-auth",vt="data-edgespark-auth-theme",r="edgespark-auth",W="es_auth_completion",O="es_auth_email",Y="oauth",k="verify-sign-in",P="verify-sign-up",Pe=200,J=2,Et={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},X={google:"Google",apple:"Apple",microsoft:"Microsoft",github:"GitHub",gitlab:"GitLab",discord:"Discord"};function _(t){return"redirectTo"in t}function Z(t){return"onSuccess"in t&&!("redirectTo"in t)}function Q(t){return!t||typeof t!="string"?!1:/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(t.trim())}function St(t){return/^\d{6}$/.test(t.trim())}function Pt(t){return t==="email"||t==="name"||t==="password"||t==="confirmPassword"||t==="code"||t==="newPassword"}function _t(t){return!!(t.error||t.errorDescription)}class Lt{constructor(e,s,i,n,a){this.container=e,this.auth=s,this.options=i,this.loadConfig=n,this.runtimeOptions=a,this.state={view:"loading",busy:!0,busyLabel:void 0,error:null,notice:null,email:"",name:"",password:"",confirmPassword:"",code:"",newPassword:""},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 u=bt(i.appearance);this.labels=wt(ke(),i.labels),this.root=document.createElement("div"),this.root.className=u.className?`${r} ${u.className}`:r,this.root.setAttribute(yt,""),this.root.setAttribute(vt,u.theme);for(const[g,E]of Object.entries(u.variables))E!==void 0&&this.root.style.setProperty(g,E);e.innerHTML="",e.appendChild(this.root),this.render(),this.initialize()}destroy(){this.destroyed||(this.destroyed=!0,this.clearCountdown(),this.clearFocusRestoreTimer(),this.container.innerHTML="")}async initialize(){const e=this.consumeManagedReturnContext();try{const[s,i]=await Promise.allSettled([this.loadConfig(),this.readMountSession(e)]);if(this.destroyed)return;if(i.status==="rejected"){if(e.marker&&!_t(e)&&_(this.options)){this.redirectAfterManagedReturnLookupFailure();return}}else{const a=i.value;if(a.user&&a.session){switch(e.marker){case Y:case k:await this.completeAuth("sign-in",a);return;case P:await this.completeAuth("sign-up",a);return;default:break}this.handleExistingSessionOnMount();return}}if(s.status==="rejected")throw i.status==="rejected"?i.reason:s.reason;if(this.config=s.value,this.handleSessionlessManagedReturn(e))return;if(i.status==="rejected")throw i.reason;const n=i.value;this.state.view="sign-in",this.state.busy=!1,this.state.busyLabel=void 0,this.render()}catch(s){this.handleError(s,"Failed to load the authentication UI.")}}redirectAfterManagedReturnLookupFailure(){_(this.options)&&this.navigateToRedirect()}navigateToRedirect(){_(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(ft(this.options.redirectTo).toString()))}async readMountSession(e){if(!e.marker)return M(this.auth);let s=null;for(let i=0;i<=J;i++){try{const n=await M(this.auth);if(n.user&&n.session)return n}catch(n){s=n}i<J&&await new Promise(n=>setTimeout(n,Pe))}if(s)throw s;return{user:null,session:null}}render(){if(this.destroyed)return;const e=this.captureFocusSnapshot();if(e&&(this.pendingFocusSnapshot=e),!this.config){this.root.innerHTML=this.renderLoading();return}this.root.innerHTML=`
2
2
  <div class="${r}__shell">
3
3
  <div class="${r}__card">
4
4
  ${this.renderStatus()}
@@ -128,7 +128,7 @@
128
128
  <div class="${r}__stack">
129
129
  ${e.map(i=>`
130
130
  <button class="${r}__button ${r}__button--secondary" type="button" data-action="oauth" data-provider="${i}" ${this.state.busy?"disabled":""}>
131
- ${this.escape(`${this.labels.oauth.continueWith} ${Z[i]}`)}
131
+ ${this.escape(`${this.labels.oauth.continueWith} ${X[i]}`)}
132
132
  </button>
133
133
  `).join("")}
134
134
  </div>
@@ -144,4 +144,4 @@
144
144
  ${this.state.busy?"disabled":""}
145
145
  />
146
146
  </label>
147
- `}bindDOM(){this.root.querySelectorAll("form[data-view]").forEach(n=>{n.addEventListener("submit",a=>{a.preventDefault();const m=n.dataset.view;m==="sign-in"&&this.handleSignIn(),m==="sign-up"&&this.handleSignUp(),m==="forgot-password"&&this.handleForgotPassword(),m==="reset-password"&&this.handleResetPassword()})}),this.root.querySelectorAll("input[name]").forEach(n=>{n.addEventListener("input",()=>{ht(n.name)&&(this.state[n.name]=n.value)})}),this.root.querySelectorAll("[data-action]").forEach(n=>{n.addEventListener("click",()=>{const a=n.dataset.action;a==="switch-sign-up"&&this.switchView("sign-up"),a==="switch-sign-in"&&this.switchView("sign-in"),a==="forgot-password"&&this.switchView("forgot-password"),a==="resend-verification"&&this.resendVerificationEmail(),a==="use-different-email"&&this.switchView(this.verificationCompletionAction==="sign-in"?"sign-in":"sign-up"),a==="resend-reset-code"&&this.resendResetCode(),a==="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(){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("Signing in…",async()=>{const e=await this.auth.signIn.email({email:this.state.email.trim(),password:this.state.password,callbackURL:this.getManagedReturnURL(B,this.state.email.trim())});if(e.error)throw e.error;await this.completeAuth("sign-in")})}async handleSignUp(){var e,s;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(((s=this.config)==null?void 0:s.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 i=await this.auth.signUp.email({name:this.state.name.trim(),email:this.state.email.trim(),password:this.state.password,callbackURL:this.getManagedReturnURL(E,this.state.email.trim())});if(i.error)throw i.error;if((n=this.config)!=null&&n.requireEmailVerification){this.verificationCompletionAction="sign-up",this.state.view="verify-email",this.state.notice="Check your inbox to verify your email address.",this.startCountdown();return}await this.completeAuth("sign-up",await this.resolveAuthCompletionData(i.data))})}async handleOAuthSignIn(e){await this.runAction(`Redirecting to ${Z[e]}…`,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 i=this.extractRedirectURL(s.data);if(!i)throw new p(`OAuth sign-in did not return a redirect URL for provider "${e}".`);this.terminalActionInProgress=!0,this.state.busy=!0,this.state.busyLabel=`Opening ${Z[e]}…`,this.state.error=null,this.state.notice=null,this.render(),window.location.assign(i)})}async handleForgotPassword(){if(!this.canUsePasswordResetEmailOtp()){this.handleError(new p("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()=>{const e=await this.passwordResetEndpoints().forgetPassword.emailOtp({email:this.state.email.trim()});if(e.error)throw e.error;this.state.view="reset-password",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,s;if(!this.canUsePasswordResetEmailOtp()){this.handleError(new p("Password reset via email OTP is not enabled for this project."));return}if(!ut(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(((s=this.config)==null?void 0:s.minPasswordLength)??8)));return}if(this.state.newPassword!==this.state.confirmPassword){this.failValidation(this.labels.errors.passwordMismatch);return}await this.runAction("Updating password…",async()=>{const i=await this.passwordResetEndpoints().emailOtp.resetPassword({email:this.state.email.trim(),otp:this.state.code.trim(),password:this.state.newPassword});if(i.error)throw i.error;await this.completePasswordReset()})}async resendVerificationEmail(){await this.sendVerificationEmail(!1)}async sendVerificationEmail(e){!e&&this.isCountdownActive()||await this.runAction("Sending verification email…",async()=>{const s=await this.auth.sendVerificationEmail({email:this.state.email.trim(),callbackURL:this.getManagedReturnURL(this.verificationCompletionAction==="sign-up"?E:B,this.state.email.trim())});if(s.error)throw s.error;this.handleVerificationEmailSent(this.state.email.trim(),!0)})}async completeAuth(e,s){const i=await this.retryAuthCompletionDataIfNeeded(s??await this.resolveAuthCompletionData());if(this.destroyed)return;if(!i.user||!i.session){if(this.destroyed)return;if(i.lookupError&&P(this.options)){this.navigateToRedirect();return}if(e==="sign-in")throw i.lookupError??new ue("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:i.user,session:i.session};if(await this.syncPublicSessionBestEffort(),!this.destroyed){if(P(this.options)){this.invokeRedirectModeSuccessHook(n),this.navigateToRedirect();return}if(Q(this.options)){this.options.onSuccess(n),this.terminalActionInProgress=!0;return}}}async retryAuthCompletionDataIfNeeded(e){if(e.session)return e;let s=e.lookupError;for(let i=0;i<J;i++){await new Promise(n=>setTimeout(n,ve));try{const n=await M(this.auth);if(n.user&&n.session)return{user:n.user,session:n.session}}catch(n){s=n}}return{...e,lookupError:s??e.lookupError}}async syncPublicSessionBestEffort(){var e,s;try{await((s=(e=this.runtimeOptions)==null?void 0:e.syncPublicSession)==null?void 0:s.call(e))}catch{}}async resolveAuthCompletionData(e){try{const s=await M(this.auth),i=this.extractUser(e);return{user:s.user??i,session:s.session}}catch(s){return{user:this.extractUser(e),session:null,lookupError:s}}}async completePasswordReset(){const e={action:"password-reset",user:null,session:null};if(await this.syncPublicSessionBestEffort(),!this.destroyed){if(Q(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(P(this.options)){this.navigateToRedirect();return}if(Q(this.options))throw this.state.view="sign-in",this.state.busy=!1,this.state.busyLabel=void 0,this.state.notice=null,new p("authUI.mount(container, { onSuccess }) cannot run while a session already exists. Check es.auth.getSession() before mounting controlled auth UI.")}async runAction(e,s){this.state.busy=!0,this.state.busyLabel=e,this.state.error=null,this.state.notice=null,this.render();try{await s()}catch(i){if(this.maybeHandleVerificationRequired(i))return;this.handleError(i);return}!this.destroyed&&!this.terminalActionInProgress&&(this.state.busy=!1,this.state.busyLabel=void 0,this.render())}maybeHandleVerificationRequired(e){return G(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,s){this.state.notice=s?`We sent another verification email to ${e}.`:`We sent a verification email to ${e}.`,this.startCountdown()}invokeRedirectModeSuccessHook(e){var s,i;if(!(!P(this.options)||!this.options.onSuccess))try{this.options.onSuccess(e)}catch(n){const a=G(n,"Post-auth callback failed.");try{(i=(s=this.options).onError)==null||i.call(s,a)}catch{}}}handleError(e,s){var n,a;const i=G(e,s);this.state.busy=!1,this.state.busyLabel=void 0,this.state.error=i.message,this.render(),(a=(n=this.options).onError)==null||a.call(n,i)}failValidation(e){this.state.error=e,this.state.notice=null,this.render()}getManagedReturnURL(e,s){if(!e)return window.location.href;const i=new URL(window.location.href);return i.searchParams.set(K,e),s?i.searchParams.set(O,s):i.searchParams.delete(O),i.toString()}consumeManagedReturnContext(){const e=new URL(window.location.href),s=e.searchParams.get(K),i=s===Y||s===B||s===E?s:null,n=e.searchParams.get(O),a=i?e.searchParams.get("error"):null,m=i?e.searchParams.get("error_description"):null;return(i||n)&&(e.searchParams.delete(K),e.searchParams.delete(O),i&&(e.searchParams.delete("error"),e.searchParams.delete("error_description")),window.history.replaceState(null,"",e.toString())),{marker:i,email:n,error:a,errorDescription:m}}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.render();return}this.render()},1e3)}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,s=`input[name="${this.escape(e.name)}"][type="${this.escape(e.type)}"]`,i=this.root.querySelector(s);if(!(!i||i.disabled)){if(i.focus(),e.selectionStart!==null&&e.selectionEnd!==null)try{i.setSelectionRange(e.selectionStart,e.selectionEnd)}catch{const n=i.value.length;i.setSelectionRange(n,n)}this.pendingFocusSnapshot=null}},0))}clearFocusRestoreTimer(){this.focusRestoreTimer!==null&&(window.clearTimeout(this.focusRestoreTimer),this.focusRestoreTimer=null)}passwordResetEndpoints(){return this.auth}extractRedirectURL(e){if(!e||typeof e!="object")return null;const s=e;return s.redirect&&typeof s.url=="string"&&s.url.length>0?s.url:null}extractUser(e){if(!e||typeof e!="object")return null;const s=e;return s.user&&typeof s.user=="object"?s.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&&!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===B||e.marker===E?(this.verificationCompletionAction=e.marker===E?"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 v(e.errorDescription??"Verification failed. Request a new verification email and try again.",{code:e.error??"VERIFY_EMAIL_ERROR"})):this.render(),!0):e.marker===Y&&(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 v(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,s){const i=this.getCountdownSecondsRemaining();return i<=0?e:s.replace("{seconds}",String(i))}escape(e){return e.replace(/[&<>"']/g,s=>ct[s])}}function wt(t){return"data"in t&&t.data?t.data:t}const pt=[{id:"google",key:"providerGoogle"},{id:"apple",key:"providerApple"},{id:"microsoft",key:"providerMicrosoft"},{id:"github",key:"providerGithub"},{id:"gitlab",key:"providerGitlab"},{id:"discord",key:"providerDiscord"}],Se=2,gt=500;async function bt(){const t=`${window.location.origin}${Le}/config`;let e;for(let s=0;s<=Se;s++)try{const i=await fetch(t,{method:"GET",credentials:"include"});if(!i.ok)throw new p(`Failed to load auth config: HTTP ${i.status}`);const n=await i.json();return vt(wt(n))}catch(i){e=i,s<Se&&await new Promise(n=>setTimeout(n,gt))}throw e}let V=null;async function yt(){return V||(V=bt().catch(t=>{throw V=null,t})),V}function vt(t){var s,i,n,a,m,b,_;const e=pt.filter(({key:R})=>{const T=t[R];return typeof T=="object"&&T!==null&&"enabled"in T&&!!T.enabled}).map(({id:R})=>R);return{disableSignUp:!!t.disableSignUp,emailPasswordEnabled:!!((s=t.providerEmailPassword)!=null&&s.enabled),minPasswordLength:((n=(i=t.providerEmailPassword)==null?void 0:i.config)==null?void 0:n.minPasswordLength)??8,requireEmailVerification:!!((m=(a=t.providerEmailPassword)==null?void 0:a.config)!=null&&m.requireEmailVerification),passwordResetEmailOtpEnabled:!!((_=(b=t.providerEmailPassword)==null?void 0:b.config)!=null&&_.requirePasswordResetEmailVerification),oauthProviders:e}}const N=new WeakMap;function St(t){if(!t)throw new p("authUI.mount(container, options) requires either { redirectTo } or { onSuccess }.");const e="redirectTo"in t,s="onSuccess"in t&&typeof t.onSuccess=="function";if(!e&&!s)throw new p("authUI.mount(container, options) requires either { redirectTo } or { onSuccess }.");if("redirectTo"in t){const i=t.redirectTo;if(!(typeof i=="string"||i instanceof URL))throw new p("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 p("authUI.mount(container, options) expected onSuccess to be a function.");if("onError"in t&&t.onError!==void 0&&typeof t.onError!="function")throw new p("authUI.mount(container, options) expected onError to be a function.")}function Et(t){if(!(t instanceof HTMLElement))throw new p("authUI.mount(container, options) requires a real HTMLElement container.")}function Pt(t,e){return{mount(s,i){var b;St(i),Et(s),(b=N.get(s))==null||b.destroy();const n=new ft(s,t,i,yt,e),a=n.destroy.bind(n),m={destroy(){a(),N.get(s)===m&&N.delete(s)}};return N.set(s,m),m}}}function Lt(){Pe();const t=rt(),e=ot(),s=Ve(),i=Pt(e,{syncPublicSession:async()=>{await nt(t)}});return{auth:t,api:s,authUI:i}}exports.EdgeSparkAuthError=v;exports.EdgeSparkConfigError=p;exports.EdgeSparkError=D;exports.EdgeSparkRuntimeError=ue;exports.ar=de;exports.createEdgeSpark=Lt;exports.de=oe;exports.detectLocale=Ae;exports.enUS=k;exports.es=z;exports.fr=re;exports.hi=ce;exports.it=ae;exports.ja=se;exports.ko=ie;exports.ptBR=ne;exports.ru=le;exports.zhCN=F;
147
+ `}bindDOM(){this.root.querySelectorAll("form[data-view]").forEach(n=>{n.addEventListener("submit",a=>{a.preventDefault();const u=n.dataset.view;u==="sign-in"&&this.handleSignIn(),u==="sign-up"&&this.handleSignUp(),u==="forgot-password"&&this.handleForgotPassword(),u==="reset-password"&&this.handleResetPassword()})}),this.root.querySelectorAll("input[name]").forEach(n=>{n.addEventListener("input",()=>{Pt(n.name)&&(this.state[n.name]=n.value)})}),this.root.querySelectorAll("[data-action]").forEach(n=>{n.addEventListener("click",()=>{const a=n.dataset.action;a==="switch-sign-up"&&this.switchView("sign-up"),a==="switch-sign-in"&&this.switchView("sign-in"),a==="forgot-password"&&this.switchView("forgot-password"),a==="resend-verification"&&this.resendVerificationEmail(),a==="use-different-email"&&this.switchView(this.verificationCompletionAction==="sign-in"?"sign-in":"sign-up"),a==="resend-reset-code"&&this.resendResetCode(),a==="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(){if(!Q(this.state.email)){this.failValidation(this.labels.errors.invalidEmail);return}if(!this.state.password){this.failValidation(this.labels.errors.requiredField);return}await this.runAction("Signing in…",async()=>{const e=await this.auth.signIn.email({email:this.state.email.trim(),password:this.state.password,callbackURL:this.getManagedReturnURL(k,this.state.email.trim())});if(e.error)throw e.error;await this.completeAuth("sign-in")})}async handleSignUp(){var e,s;if(!this.state.name.trim()){this.failValidation(this.labels.errors.requiredField);return}if(!Q(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(((s=this.config)==null?void 0:s.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 i=await this.auth.signUp.email({name:this.state.name.trim(),email:this.state.email.trim(),password:this.state.password,callbackURL:this.getManagedReturnURL(P,this.state.email.trim())});if(i.error)throw i.error;if((n=this.config)!=null&&n.requireEmailVerification){this.verificationCompletionAction="sign-up",this.state.view="verify-email",this.state.notice="Check your inbox to verify your email address.",this.startCountdown();return}await this.completeAuth("sign-up",await this.resolveAuthCompletionData(i.data))})}async handleOAuthSignIn(e){await this.runAction(`Redirecting to ${X[e]}…`,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 i=this.extractRedirectURL(s.data);if(!i)throw new m(`OAuth sign-in did not return a redirect URL for provider "${e}".`);this.terminalActionInProgress=!0,this.state.busy=!0,this.state.busyLabel=`Opening ${X[e]}…`,this.state.error=null,this.state.notice=null,this.render(),window.location.assign(i)})}async handleForgotPassword(){if(!this.canUsePasswordResetEmailOtp()){this.handleError(new m("Password reset via email OTP is not enabled for this project."));return}if(!Q(this.state.email)){this.failValidation(this.labels.errors.invalidEmail);return}await this.runAction("Sending reset code…",async()=>{const e=await this.passwordResetEndpoints().forgetPassword.emailOtp({email:this.state.email.trim()});if(e.error)throw e.error;this.state.view="reset-password",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,s;if(!this.canUsePasswordResetEmailOtp()){this.handleError(new m("Password reset via email OTP is not enabled for this project."));return}if(!St(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(((s=this.config)==null?void 0:s.minPasswordLength)??8)));return}if(this.state.newPassword!==this.state.confirmPassword){this.failValidation(this.labels.errors.passwordMismatch);return}await this.runAction("Updating password…",async()=>{const i=await this.passwordResetEndpoints().emailOtp.resetPassword({email:this.state.email.trim(),otp:this.state.code.trim(),password:this.state.newPassword});if(i.error)throw i.error;await this.completePasswordReset()})}async resendVerificationEmail(){await this.sendVerificationEmail(!1)}async sendVerificationEmail(e){!e&&this.isCountdownActive()||await this.runAction("Sending verification email…",async()=>{const s=await this.auth.sendVerificationEmail({email:this.state.email.trim(),callbackURL:this.getManagedReturnURL(this.verificationCompletionAction==="sign-up"?P:k,this.state.email.trim())});if(s.error)throw s.error;this.handleVerificationEmailSent(this.state.email.trim(),!0)})}async completeAuth(e,s){const i=await this.retryAuthCompletionDataIfNeeded(s??await this.resolveAuthCompletionData());if(this.destroyed)return;if(!i.user||!i.session){if(this.destroyed)return;if(i.lookupError&&_(this.options)){this.navigateToRedirect();return}if(e==="sign-in")throw i.lookupError??new ue("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:i.user,session:i.session};if(await this.syncPublicSessionBestEffort(),!this.destroyed){if(_(this.options)){this.invokeRedirectModeSuccessHook(n),this.navigateToRedirect();return}if(Z(this.options)){this.options.onSuccess(n),this.terminalActionInProgress=!0;return}}}async retryAuthCompletionDataIfNeeded(e){if(e.session)return e;let s=e.lookupError;for(let i=0;i<J;i++){await new Promise(n=>setTimeout(n,Pe));try{const n=await M(this.auth);if(n.user&&n.session)return{user:n.user,session:n.session}}catch(n){s=n}}return{...e,lookupError:s??e.lookupError}}async syncPublicSessionBestEffort(){var e,s;try{await((s=(e=this.runtimeOptions)==null?void 0:e.syncPublicSession)==null?void 0:s.call(e))}catch{}}async resolveAuthCompletionData(e){try{const s=await M(this.auth),i=this.extractUser(e);return{user:s.user??i,session:s.session}}catch(s){return{user:this.extractUser(e),session:null,lookupError:s}}}async completePasswordReset(){const e={action:"password-reset",user:null,session:null};if(await this.syncPublicSessionBestEffort(),!this.destroyed){if(Z(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(_(this.options)){this.navigateToRedirect();return}if(Z(this.options))throw this.state.view="sign-in",this.state.busy=!1,this.state.busyLabel=void 0,this.state.notice=null,new m("authUI.mount(container, { onSuccess }) cannot run while a session already exists. Check es.auth.getSession() before mounting controlled auth UI.")}async runAction(e,s){this.state.busy=!0,this.state.busyLabel=e,this.state.error=null,this.state.notice=null,this.render();try{await s()}catch(i){if(this.maybeHandleVerificationRequired(i))return;this.handleError(i);return}!this.destroyed&&!this.terminalActionInProgress&&(this.state.busy=!1,this.state.busyLabel=void 0,this.render())}maybeHandleVerificationRequired(e){return K(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,s){this.state.notice=s?`We sent another verification email to ${e}.`:`We sent a verification email to ${e}.`,this.startCountdown()}invokeRedirectModeSuccessHook(e){var s,i;if(!(!_(this.options)||!this.options.onSuccess))try{this.options.onSuccess(e)}catch(n){const a=K(n,"Post-auth callback failed.");try{(i=(s=this.options).onError)==null||i.call(s,a)}catch{}}}handleError(e,s){var n,a;const i=K(e,s);this.state.busy=!1,this.state.busyLabel=void 0,this.state.error=i.message,this.render(),(a=(n=this.options).onError)==null||a.call(n,i)}failValidation(e){this.state.error=e,this.state.notice=null,this.render()}getManagedReturnURL(e,s){if(!e)return window.location.href;const i=new URL(window.location.href);return i.searchParams.set(W,e),s?i.searchParams.set(O,s):i.searchParams.delete(O),i.toString()}consumeManagedReturnContext(){const e=new URL(window.location.href),s=e.searchParams.get(W),i=s===Y||s===k||s===P?s:null,n=e.searchParams.get(O),a=i?e.searchParams.get("error"):null,u=i?e.searchParams.get("error_description"):null;return(i||n)&&(e.searchParams.delete(W),e.searchParams.delete(O),i&&(e.searchParams.delete("error"),e.searchParams.delete("error_description")),window.history.replaceState(null,"",e.toString())),{marker:i,email:n,error:a,errorDescription:u}}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.render();return}this.render()},1e3)}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,s=`input[name="${this.escape(e.name)}"][type="${this.escape(e.type)}"]`,i=this.root.querySelector(s);if(!(!i||i.disabled)){if(i.focus(),e.selectionStart!==null&&e.selectionEnd!==null)try{i.setSelectionRange(e.selectionStart,e.selectionEnd)}catch{const n=i.value.length;i.setSelectionRange(n,n)}this.pendingFocusSnapshot=null}},0))}clearFocusRestoreTimer(){this.focusRestoreTimer!==null&&(window.clearTimeout(this.focusRestoreTimer),this.focusRestoreTimer=null)}passwordResetEndpoints(){return this.auth}extractRedirectURL(e){if(!e||typeof e!="object")return null;const s=e;return s.redirect&&typeof s.url=="string"&&s.url.length>0?s.url:null}extractUser(e){if(!e||typeof e!="object")return null;const s=e;return s.user&&typeof s.user=="object"?s.user:null}canUsePasswordResetEmailOtp(){var e;return!!((e=this.config)!=null&&e.passwordResetEmailOtpEnabled)}handleSessionlessManagedReturn(e){return e.email&&(this.state.email=e.email),e.marker===P&&!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===k||e.marker===P?(this.verificationCompletionAction=e.marker===P?"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 v(e.errorDescription??"Verification failed. Request a new verification email and try again.",{code:e.error??"VERIFY_EMAIL_ERROR"})):this.render(),!0):e.marker===Y&&(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 v(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,s){const i=this.getCountdownSecondsRemaining();return i<=0?e:s.replace("{seconds}",String(i))}escape(e){return e.replace(/[&<>"']/g,s=>Et[s])}}function At(t){return"data"in t&&t.data?t.data:t}const Tt=[{id:"google",key:"providerGoogle"},{id:"apple",key:"providerApple"},{id:"microsoft",key:"providerMicrosoft"},{id:"github",key:"providerGithub"},{id:"gitlab",key:"providerGitlab"},{id:"discord",key:"providerDiscord"}],_e=2,Rt=500;async function It(){const t=`${window.location.origin}${Te}/config`;let e;for(let s=0;s<=_e;s++)try{const i=await fetch(t,{method:"GET",credentials:"include"});if(!i.ok)throw new m(`Failed to load auth config: HTTP ${i.status}`);const n=await i.json();return Ct(At(n))}catch(i){e=i,s<_e&&await new Promise(n=>setTimeout(n,Rt))}throw e}let N=null;async function Ut(){return N||(N=It().catch(t=>{throw N=null,t})),N}function Ct(t){var s,i,n,a,u,g,E;const e=Tt.filter(({key:A})=>{const T=t[A];return typeof T=="object"&&T!==null&&"enabled"in T&&!!T.enabled}).map(({id:A})=>A);return{disableSignUp:!!t.disableSignUp,emailPasswordEnabled:!!((s=t.providerEmailPassword)!=null&&s.enabled),minPasswordLength:((n=(i=t.providerEmailPassword)==null?void 0:i.config)==null?void 0:n.minPasswordLength)??8,requireEmailVerification:!!((u=(a=t.providerEmailPassword)==null?void 0:a.config)!=null&&u.requireEmailVerification),passwordResetEmailOtpEnabled:!!((E=(g=t.providerEmailPassword)==null?void 0:g.config)!=null&&E.requirePasswordResetEmailVerification),oauthProviders:e}}const V=new WeakMap;function $t(t){if(!t)throw new m("authUI.mount(container, options) requires either { redirectTo } or { onSuccess }.");const e="redirectTo"in t,s="onSuccess"in t&&typeof t.onSuccess=="function";if(!e&&!s)throw new m("authUI.mount(container, options) requires either { redirectTo } or { onSuccess }.");if("redirectTo"in t){const i=t.redirectTo;if(!(typeof i=="string"||i instanceof URL))throw new m("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 m("authUI.mount(container, options) expected onSuccess to be a function.");if("onError"in t&&t.onError!==void 0&&typeof t.onError!="function")throw new m("authUI.mount(container, options) expected onError to be a function.");if("appearance"in t&&t.appearance!==void 0){const i=t.appearance;if(!i||typeof i!="object"||Array.isArray(i))throw new m("authUI.mount(container, options) expected appearance to be an object.");if("theme"in i&&i.theme!==void 0&&!pt(i.theme))throw new m(`authUI.mount(container, options) expected appearance.theme to be one of: ${fe.join(", ")}.`);if("className"in i&&i.className!==void 0&&typeof i.className!="string")throw new m("authUI.mount(container, options) expected appearance.className to be a string.");if("variables"in i&&i.variables!==void 0){if(!i.variables||typeof i.variables!="object"||Array.isArray(i.variables))throw new m("authUI.mount(container, options) expected appearance.variables to be an object.");for(const[n,a]of Object.entries(i.variables)){if(!gt(n))throw new m(`authUI.mount(container, options) received unsupported appearance.variables key "${n}".`);if(a!==void 0&&typeof a!="string")throw new m(`authUI.mount(container, options) expected appearance.variables["${n}"] to be a string.`)}}}}function kt(t){if(!(t instanceof HTMLElement))throw new m("authUI.mount(container, options) requires a real HTMLElement container.")}function Bt(t,e){return{mount(s,i){var g;$t(i),kt(s),(g=V.get(s))==null||g.destroy();const n=new Lt(s,t,i,Ut,e),a=n.destroy.bind(n),u={destroy(){a(),V.get(s)===u&&V.delete(s)}};return V.set(s,u),u}}}function Mt(){Ae();const t=ht(),e=mt(),s=qe(),i=Bt(e,{syncPublicSession:async()=>{await ut(t)}});return{auth:t,api:s,authUI:i}}exports.AUTH_UI_APPEARANCE_VARIABLE=Oe;exports.AUTH_UI_APPEARANCE_VARIABLE_NAMES=Ne;exports.AUTH_UI_DEFAULT_THEME=Me;exports.AUTH_UI_THEME=he;exports.AUTH_UI_THEMES=fe;exports.AUTH_UI_THEME_DARK=Be;exports.AUTH_UI_THEME_LIGHT=me;exports.EdgeSparkAuthError=v;exports.EdgeSparkConfigError=m;exports.EdgeSparkError=F;exports.EdgeSparkRuntimeError=ue;exports.ar=de;exports.createEdgeSpark=Mt;exports.de=oe;exports.detectLocale=ke;exports.enUS=B;exports.es=H;exports.fr=re;exports.hi=ce;exports.it=ae;exports.ja=se;exports.ko=ie;exports.ptBR=ne;exports.ru=le;exports.zhCN=D;
package/dist/index.d.ts CHANGED
@@ -4,6 +4,8 @@ export type { AuthSession, AuthUser, BetterAuthClientInstance, EdgeSparkAuth, Se
4
4
  export type { EdgeSparkApi, EdgeSparkRequestInit } from './api/types';
5
5
  export type { DeepPartial } from './shared/types';
6
6
  export type { RedirectTarget } from './redirect';
7
+ 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';
8
+ export type { AuthUIAppearance, AuthUIAppearanceVariableName, AuthUIAppearanceVariables, AuthUITheme, } from './auth-ui/appearance';
7
9
  export type { AuthSuccessEvent, AuthUILabelOverrides, AuthUILabels, ControlledAuthUIOptions, EdgeSparkAuthUI, MountAuthUIOptions, MountedAuthUI, RedirectAuthUIOptions, } from './auth-ui/types';
8
10
  export { EdgeSparkAuthError, EdgeSparkConfigError, EdgeSparkError, EdgeSparkRuntimeError, } from './errors';
9
11
  /**