@edgespark/web 0.0.1-beta.0 → 0.0.1-beta.1
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/README.md +42 -0
- package/dist/auth/types.d.ts +7 -4
- package/dist/auth-ui/ManagedAuthUI.d.ts +1 -0
- package/dist/client.d.ts +1 -1
- package/dist/index.cjs +8 -8
- package/dist/index.d.ts +17 -0
- package/dist/index.es.js +261 -226
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -31,6 +31,9 @@ es.authUI.mount(container, {
|
|
|
31
31
|
});
|
|
32
32
|
```
|
|
33
33
|
|
|
34
|
+
Auto-detected labels are used by default. The managed UI picks the best preset
|
|
35
|
+
from the browser's language preferences automatically.
|
|
36
|
+
|
|
34
37
|
## Public surface
|
|
35
38
|
|
|
36
39
|
```ts
|
|
@@ -105,6 +108,23 @@ const ui = es.authUI.mount(container, {
|
|
|
105
108
|
|
|
106
109
|
`ui.destroy()` removes the mounted UI and clears timers/listeners.
|
|
107
110
|
|
|
111
|
+
`onError` always receives a normalized `EdgeSparkAuthError`, so callback code
|
|
112
|
+
can safely read `error.code`, `error.message`, and `error.status` without
|
|
113
|
+
defensive `unknown` handling.
|
|
114
|
+
|
|
115
|
+
```ts
|
|
116
|
+
es.authUI.mount(container, {
|
|
117
|
+
onSuccess(event) {
|
|
118
|
+
if (event.action !== "password-reset") {
|
|
119
|
+
window.location.assign("/dashboard");
|
|
120
|
+
}
|
|
121
|
+
},
|
|
122
|
+
onError(error) {
|
|
123
|
+
console.error(error.code, error.message);
|
|
124
|
+
},
|
|
125
|
+
});
|
|
126
|
+
```
|
|
127
|
+
|
|
108
128
|
Password reset has one special rule:
|
|
109
129
|
|
|
110
130
|
- in controlled mode, `onSuccess({ action: "password-reset" })` fires and the caller owns the next step
|
|
@@ -121,6 +141,28 @@ Password reset has one special rule:
|
|
|
121
141
|
|
|
122
142
|
The forgot-password path only appears when the project config enables email-OTP password reset.
|
|
123
143
|
|
|
144
|
+
## Locale presets
|
|
145
|
+
|
|
146
|
+
Managed auth UI labels auto-detect by default, so most apps do not need to
|
|
147
|
+
import locale helpers manually.
|
|
148
|
+
|
|
149
|
+
Import a preset only when the app wants to force a specific language or build
|
|
150
|
+
on top of a known base:
|
|
151
|
+
|
|
152
|
+
```ts
|
|
153
|
+
import { createEdgeSpark, fr } from "@edgespark/web";
|
|
154
|
+
|
|
155
|
+
const es = createEdgeSpark();
|
|
156
|
+
|
|
157
|
+
es.authUI.mount(container, {
|
|
158
|
+
redirectTo: "/dashboard",
|
|
159
|
+
labels: fr,
|
|
160
|
+
});
|
|
161
|
+
```
|
|
162
|
+
|
|
163
|
+
`detectLocale()` is exported for advanced cases that want the same browser
|
|
164
|
+
language matching outside the managed auth UI.
|
|
165
|
+
|
|
124
166
|
## Design notes
|
|
125
167
|
|
|
126
168
|
- `createEdgeSpark()` takes no options
|
package/dist/auth/types.d.ts
CHANGED
|
@@ -21,7 +21,7 @@ export interface AuthEndpointResult<TData = unknown> {
|
|
|
21
21
|
*
|
|
22
22
|
* All better-auth client methods work directly. EdgeSpark adds three
|
|
23
23
|
* small conveniences on top: `requireSession`, `onSessionChange`, and
|
|
24
|
-
* a wrapped `signOut` that
|
|
24
|
+
* a wrapped `signOut` that best-effort invalidates the same-tab session.
|
|
25
25
|
*/
|
|
26
26
|
export type EdgeSparkAuth = BetterAuthClientInstance & {
|
|
27
27
|
/**
|
|
@@ -33,7 +33,7 @@ export type EdgeSparkAuth = BetterAuthClientInstance & {
|
|
|
33
33
|
/**
|
|
34
34
|
* Subscribes to session changes for the current tab.
|
|
35
35
|
*
|
|
36
|
-
* The first emission is
|
|
36
|
+
* The first emission is hydration-safe: it waits for the initial server
|
|
37
37
|
* session check to complete before firing, so subscribers never receive a
|
|
38
38
|
* premature `null` that looks like "not authenticated" while the cookie
|
|
39
39
|
* session is still being verified.
|
|
@@ -48,8 +48,11 @@ export type EdgeSparkAuth = BetterAuthClientInstance & {
|
|
|
48
48
|
* Signs out and invalidates the session for the current tab.
|
|
49
49
|
*
|
|
50
50
|
* This wraps better-auth's `signOut` and additionally forces the session
|
|
51
|
-
* atom to refetch
|
|
52
|
-
*
|
|
51
|
+
* atom to refetch after a successful sign-out so `onSessionChange`
|
|
52
|
+
* subscribers update in the same tab.
|
|
53
|
+
*
|
|
54
|
+
* The extra refetch is best-effort. If it fails, the original better-auth
|
|
55
|
+
* sign-out result is still returned unchanged.
|
|
53
56
|
*/
|
|
54
57
|
signOut(...args: Parameters<BetterAuthClientInstance["signOut"]>): ReturnType<BetterAuthClientInstance["signOut"]>;
|
|
55
58
|
};
|
|
@@ -58,6 +58,7 @@ export declare class ManagedAuthUI implements MountedAuthUI {
|
|
|
58
58
|
private runAction;
|
|
59
59
|
private maybeHandleVerificationRequired;
|
|
60
60
|
private handleVerificationEmailSent;
|
|
61
|
+
private invokeRedirectModeSuccessHook;
|
|
61
62
|
private handleError;
|
|
62
63
|
private failValidation;
|
|
63
64
|
private getManagedReturnURL;
|
package/dist/client.d.ts
CHANGED
|
@@ -7,7 +7,7 @@ export interface EdgeSparkClient {
|
|
|
7
7
|
*
|
|
8
8
|
* - `requireSession()` — resolves or throws, for route guards
|
|
9
9
|
* - `onSessionChange(cb)` — hydration-safe session subscription
|
|
10
|
-
* - `signOut()` — signs out and
|
|
10
|
+
* - `signOut()` — signs out and best-effort invalidates the same-tab session atom
|
|
11
11
|
*
|
|
12
12
|
* All other better-auth methods (`signIn.email`, `signUp.email`,
|
|
13
13
|
* `getSession`, etc.) work directly.
|
package/dist/index.cjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const Q=require("better-auth/client");class E extends Error{constructor(e,s){super(s),this.name="EdgeSparkError",this.code=e}}class d extends E{constructor(e){super("CONFIG_ERROR",e),this.name="EdgeSparkConfigError"}}class q extends E{constructor(e){super("RUNTIME_ERROR",e),this.name="EdgeSparkRuntimeError"}}class u extends E{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 K(){if(typeof window>"u"||typeof document>"u")throw new q("@edgespark/web is browser-only. Create the client from a real browser runtime.")}function R(){return K(),window.location.origin}function X(t){return t instanceof URL?t:typeof t=="string"?new URL(t,window.location.href):new URL(t.url,window.location.href)}function ee(t){if(t.origin!==R())throw new d(`Cross-origin requests are not supported by this SDK. Received ${t.origin}, expected ${R()}.`)}function te(){return{async fetch(t,e){const s=X(t);return ee(s),fetch(t,{...e,credentials:"include"})}}}const Y="/api/_es/auth";function J(t){return Q.createAuthClient({baseURL:R(),basePath:Y,...t!=null&&t.disableDefaultRedirectPlugin?{disableDefaultFetchPlugins:!0}:{},fetchOptions:{credentials:"include"}})}function I(t){var e,s;return(s=(e=t.$store)==null?void 0:e.atoms)==null?void 0:s.session}async function se(t){var e;await((e=I(t))==null?void 0:e.get().refetch())}function ie(){const t=J(),e=t.getSession().then(r=>r.data??null),s=async()=>{var o,l;const r=await t.getSession();if((o=r.data)!=null&&o.session&&((l=r.data)!=null&&l.user))return r.data;throw new u("No authenticated session is available.",{code:"UNAUTHENTICATED",cause:r.error})},i=r=>{let o=!1,l=!1,c;e.then(p=>{o||(l=!0,c=p,r(p))});const h=I(t);if(!h)return()=>{o=!0};const m=h.subscribe(p=>{if(o||!l)return;const S=p.data??null;S!==c&&(c=S,r(S))});return()=>{o=!0,m()}},a=async(...r)=>{var l;const o=await t.signOut(...r);return await((l=I(t))==null?void 0:l.get().refetch()),o};return new Proxy(t,{get(r,o,l){return o==="requireSession"?s:o==="onSessionChange"?i:o==="signOut"?a:Reflect.get(r,o,l)}})}function ne(){return J({disableDefaultRedirectPlugin:!0})}function N(t){const e=(()=>{if(t instanceof URL)return t;const s=t.trim();if(!s)throw new d("redirectTo must not be an empty string.");try{return new URL(s,window.location.href)}catch{throw new d(`redirectTo must be a valid relative path or URL. Received: ${JSON.stringify(t)}`)}})();if(e.protocol!=="http:"&&e.protocol!=="https:")throw new d(`redirectTo must resolve to an http(s) URL. Received protocol: ${e.protocol}`);return e}function ae(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."}},L={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:"出现错误,请稍后重试"}},U={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:"エラーが発生しました。もう一度お試しください"}},A={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:"문제가 발생했습니다. 다시 시도해 주세요"}},y={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."}},B={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."}},M={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."}},k={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."}},V={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."}},O={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:"جارٍ تحميل تسجيل الدخول…",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:"حدث خطأ. يرجى المحاولة مرة أخرى."}},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:"कुछ गलत हो गई। कृपया फिर से प्रयास करें।"}},x={en:b,"en-US":b,zh:L,"zh-CN":L,"zh-TW":L,ja:U,"ja-JP":U,ko:A,"ko-KR":A,es:y,"es-ES":y,"es-MX":y,pt:B,"pt-BR":B,fr:M,"fr-FR":M,de:k,"de-DE":k,it:V,"it-IT":V,ru:O,"ru-RU":O,ar:z,"ar-SA":z,hi:F,"hi-IN":F};function Z(){if(typeof navigator>"u")return b;const t=navigator.languages??[navigator.language];for(const e of t){const s=x[e]??x[e.split("-")[0]];if(s)return s}return b}function D(t,e="Authentication failed."){if(t instanceof u)return t;if(typeof t=="object"&&t!==null){const s=t;return new u(s.message||e,{code:s.code,status:s.status,cause:t})}return typeof t=="string"?new u(t):new u(e,{cause:t})}async function W(t){var s,i;const e=await t.getSession();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 re="data-edgespark-auth",n="edgespark-auth",C="es_auth_completion",g="es_auth_email",H="oauth",f="verify-sign-in",w="verify-sign-up",_={google:"Google",apple:"Apple",microsoft:"Microsoft",github:"GitHub",gitlab:"GitLab",discord:"Discord"};function j(t){return"redirectTo"in t}function $(t){return"onSuccess"in t&&!("redirectTo"in t)}function T(t){return!t||typeof t!="string"?!1:/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(t.trim())}function oe(t){return/^\d{6}$/.test(t.trim())}function le(t){return t==="email"||t==="name"||t==="password"||t==="confirmPassword"||t==="code"||t==="newPassword"}class de{constructor(e,s,i,a,r){if(this.container=e,this.auth=s,this.options=i,this.loadConfig=a,this.runtimeOptions=r,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,!(e instanceof HTMLElement))throw new d("authUI.mount(container, options) requires a real HTMLElement container.");this.labels=ae(Z(),i.labels),this.root=document.createElement("div"),this.root.setAttribute(re,""),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(){try{const e=this.consumeManagedReturnContext(),[s,i]=await Promise.all([this.loadConfig(),W(this.auth)]);if(this.destroyed)return;if(this.config=s,i.user&&i.session){switch(e.marker){case H:case f:await this.completeAuth("sign-in",i);return;case w:await this.completeAuth("sign-up",i);return;default:break}this.handleExistingSessionOnMount(i);return}if(this.handleSessionlessManagedReturn(e))return;this.state.view="sign-in",this.state.busy=!1,this.state.busyLabel=void 0,this.render()}catch(e){this.handleError(e,"Failed to load the authentication UI.")}}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 se=require("better-auth/client");class S extends Error{constructor(e,s){super(s),this.name="EdgeSparkError",this.code=e}}class c extends S{constructor(e){super("CONFIG_ERROR",e),this.name="EdgeSparkConfigError"}}class N extends S{constructor(e){super("RUNTIME_ERROR",e),this.name="EdgeSparkRuntimeError"}}class h extends S{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 J(){if(typeof window>"u"||typeof document>"u")throw new N("@edgespark/web is browser-only. Create the client from a real browser runtime.")}function U(){return J(),window.location.origin}function ie(t){return t instanceof URL?t:typeof t=="string"?new URL(t,window.location.href):new URL(t.url,window.location.href)}function ne(t){if(t.origin!==U())throw new c(`Cross-origin requests are not supported by this SDK. Received ${t.origin}, expected ${U()}.`)}function re(){return{async fetch(t,e){const s=ie(t);return ne(s),fetch(t,{...e,credentials:"include"})}}}const Z="/api/_es/auth";function Q(t){return se.createAuthClient({baseURL:U(),basePath:Z,...t!=null&&t.disableDefaultRedirectPlugin?{disableDefaultFetchPlugins:!0}:{},fetchOptions:{credentials:"include"}})}function y(t){var e,s;return(s=(e=t.$store)==null?void 0:e.atoms)==null?void 0:s.session}async function oe(t){var e;await((e=y(t))==null?void 0:e.get().refetch())}function ae(){const t=Q(),e=2,s=500;let i=null;const r=()=>(i||(i=(async()=>{for(let l=0;l<=e;l++){if(!(await t.getSession()).error)return;l<e&&await new Promise(d=>setTimeout(d,s))}i=null})()),i.then(()=>{var l;return((l=y(t))==null?void 0:l.get().data)??null}));r();const o=async()=>{var a,d;const l=await t.getSession();if((a=l.data)!=null&&a.session&&((d=l.data)!=null&&d.user))return l.data;throw new h("No authenticated session is available.",{code:"UNAUTHENTICATED",cause:l.error})},u=l=>{let a=!1,d=!1,D;const x=w=>{w!==D&&(D=w,l(w))};r().then(w=>{a||(d=!0,x(w))});const H=y(t);if(!H)return()=>{a=!0};const ee=H.subscribe(w=>{if(a||!d)return;const te=w.data??null;x(te)});return()=>{a=!0,ee()}},m=async(...l)=>{var d;const a=await t.signOut(...l);if(a&&typeof a=="object"&&"error"in a&&a.error)return a;try{await((d=y(t))==null?void 0:d.get().refetch())}catch{}return a};return new Proxy(t,{get(l,a,d){return a==="requireSession"?o:a==="onSessionChange"?u:a==="signOut"?m:Reflect.get(l,a,d)}})}function le(){return Q({disableDefaultRedirectPlugin:!0})}function W(t){const e=(()=>{if(t instanceof URL)return t;const s=t.trim();if(!s)throw new c("redirectTo must not be an empty string.");try{return new URL(s,window.location.href)}catch{throw new c(`redirectTo must be a valid relative path or URL. Received: ${JSON.stringify(t)}`)}})();if(e.protocol!=="http:"&&e.protocol!=="https:")throw new c(`redirectTo must resolve to an http(s) URL. Received protocol: ${e.protocol}`);return e}function de(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 p={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."}},L={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:"出现错误,请稍后重试"}},A={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:"エラーが発生しました。もう一度お試しください"}},B={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:"문제가 발생했습니다. 다시 시도해 주세요"}},E={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."}},k={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."}},M={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."}},V={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."}},O={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."}},z={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:"Произошла ошибка. Пожалуйста, попробуйте снова."}},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:"حدث خطأ. يرجى المحاولة مرة أخرى."}},q={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:"कुछ गलत हो गई। कृपया फिर से प्रयास करें।"}},j={en:p,"en-US":p,zh:L,"zh-CN":L,"zh-TW":L,ja:A,"ja-JP":A,ko:B,"ko-KR":B,es:E,"es-ES":E,"es-MX":E,pt:k,"pt-BR":k,fr:M,"fr-FR":M,de:V,"de-DE":V,it:O,"it-IT":O,ru:z,"ru-RU":z,ar:F,"ar-SA":F,hi:q,"hi-IN":q};function X(){if(typeof navigator>"u")return p;const t=navigator.languages??[navigator.language];for(const e of t){const s=j[e]??j[e.split("-")[0]];if(s)return s}return p}function C(t,e="Authentication failed."){if(t instanceof h)return t;if(typeof t=="object"&&t!==null){const s=t;return new h(s.message||e,{code:s.code,status:s.status,cause:t})}return typeof t=="string"?new h(t):new h(e,{cause:t})}async function G(t){var s,i;const e=await t.getSession();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 ce="data-edgespark-auth",n="edgespark-auth",_="es_auth_completion",g="es_auth_email",Y="oauth",f="verify-sign-in",b="verify-sign-up",R={google:"Google",apple:"Apple",microsoft:"Microsoft",github:"GitHub",gitlab:"GitLab",discord:"Discord"};function T(t){return"redirectTo"in t}function $(t){return"onSuccess"in t&&!("redirectTo"in t)}function I(t){return!t||typeof t!="string"?!1:/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(t.trim())}function ue(t){return/^\d{6}$/.test(t.trim())}function he(t){return t==="email"||t==="name"||t==="password"||t==="confirmPassword"||t==="code"||t==="newPassword"}class me{constructor(e,s,i,r,o){if(this.container=e,this.auth=s,this.options=i,this.loadConfig=r,this.runtimeOptions=o,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,!(e instanceof HTMLElement))throw new c("authUI.mount(container, options) requires a real HTMLElement container.");this.labels=de(X(),i.labels),this.root=document.createElement("div"),this.root.setAttribute(ce,""),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(){try{const e=this.consumeManagedReturnContext(),[s,i]=await Promise.all([this.loadConfig(),G(this.auth)]);if(this.destroyed)return;if(this.config=s,i.user&&i.session){switch(e.marker){case Y:case f:await this.completeAuth("sign-in",i);return;case b:await this.completeAuth("sign-up",i);return;default:break}this.handleExistingSessionOnMount(i);return}if(this.handleSessionlessManagedReturn(e))return;this.state.view="sign-in",this.state.busy=!1,this.state.busyLabel=void 0,this.render()}catch(e){this.handleError(e,"Failed to load the authentication UI.")}}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="${n}__shell">
|
|
3
3
|
<div class="${n}__card">
|
|
4
4
|
${this.renderStatus()}
|
|
@@ -11,7 +11,7 @@
|
|
|
11
11
|
${e||`<div class="${n}__status ${n}__status--info">${this.escape(this.labels.common.loading)}</div>`}
|
|
12
12
|
</div>
|
|
13
13
|
</div>
|
|
14
|
-
`}renderStatus(){const e=[];return this.state.error&&e.push(`<div class="${n}__status ${n}__status--error">${this.escape(this.state.error)}</div>`),this.state.notice&&e.push(`<div class="${n}__status ${n}__status--info">${this.escape(this.state.notice)}</div>`),this.state.busy&&this.state.busyLabel&&e.push(`<div class="${n}__status ${n}__status--muted">${this.escape(this.state.busyLabel)}</div>`),e.join("")}renderCurrentView(){switch(this.state.view){case"sign-in":return this.renderSignInView();case"sign-up":return this.renderSignUpView();case"verify-email":return this.renderVerifyEmailView();case"forgot-password":return this.renderForgotPasswordView();case"reset-password":return this.renderResetPasswordView();case"loading":default:return`<p class="${n}__copy">${this.escape(this.labels.common.loading)}</p>`}}renderSignInView(){var i,
|
|
14
|
+
`}renderStatus(){const e=[];return this.state.error&&e.push(`<div class="${n}__status ${n}__status--error">${this.escape(this.state.error)}</div>`),this.state.notice&&e.push(`<div class="${n}__status ${n}__status--info">${this.escape(this.state.notice)}</div>`),this.state.busy&&this.state.busyLabel&&e.push(`<div class="${n}__status ${n}__status--muted">${this.escape(this.state.busyLabel)}</div>`),e.join("")}renderCurrentView(){switch(this.state.view){case"sign-in":return this.renderSignInView();case"sign-up":return this.renderSignUpView();case"verify-email":return this.renderVerifyEmailView();case"forgot-password":return this.renderForgotPasswordView();case"reset-password":return this.renderResetPasswordView();case"loading":default:return`<p class="${n}__copy">${this.escape(this.labels.common.loading)}</p>`}}renderSignInView(){var i,r;const e=this.renderOAuthProviders(),s=((i=this.config)==null?void 0:i.emailPasswordEnabled)??!0;return`
|
|
15
15
|
<section class="${n}__section">
|
|
16
16
|
<header class="${n}__header">
|
|
17
17
|
<h1 class="${n}__title">${this.escape(this.labels.signIn.title)}</h1>
|
|
@@ -33,7 +33,7 @@
|
|
|
33
33
|
${this.escape(this.labels.signIn.forgotPassword)}
|
|
34
34
|
</button>
|
|
35
35
|
`:""}
|
|
36
|
-
${(
|
|
36
|
+
${(r=this.config)!=null&&r.disableSignUp?"":`
|
|
37
37
|
<p class="${n}__meta">
|
|
38
38
|
${this.escape(this.labels.signIn.signUpPrompt)}
|
|
39
39
|
<button class="${n}__link" type="button" data-action="switch-sign-up" ${this.state.busy?"disabled":""}>
|
|
@@ -128,20 +128,20 @@
|
|
|
128
128
|
<div class="${n}__stack">
|
|
129
129
|
${e.map(i=>`
|
|
130
130
|
<button class="${n}__button ${n}__button--secondary" type="button" data-action="oauth" data-provider="${i}" ${this.state.busy?"disabled":""}>
|
|
131
|
-
${this.escape(`${this.labels.oauth.continueWith} ${
|
|
131
|
+
${this.escape(`${this.labels.oauth.continueWith} ${R[i]}`)}
|
|
132
132
|
</button>
|
|
133
133
|
`).join("")}
|
|
134
134
|
</div>
|
|
135
|
-
`}renderInput(e,s,i,
|
|
135
|
+
`}renderInput(e,s,i,r,o){return`
|
|
136
136
|
<label class="${n}__field">
|
|
137
137
|
<span class="${n}__label">${this.escape(s)}</span>
|
|
138
138
|
<input
|
|
139
139
|
class="${n}__input"
|
|
140
140
|
name="${this.escape(e)}"
|
|
141
141
|
type="${this.escape(i)}"
|
|
142
|
-
value="${this.escape(
|
|
143
|
-
autocomplete="${this.escape(
|
|
142
|
+
value="${this.escape(r)}"
|
|
143
|
+
autocomplete="${this.escape(o)}"
|
|
144
144
|
${this.state.busy?"disabled":""}
|
|
145
145
|
/>
|
|
146
146
|
</label>
|
|
147
|
-
`}bindDOM(){this.root.querySelectorAll("form[data-view]").forEach(a=>{a.addEventListener("submit",r=>{r.preventDefault();const o=a.dataset.view;o==="sign-in"&&this.handleSignIn(),o==="sign-up"&&this.handleSignUp(),o==="forgot-password"&&this.handleForgotPassword(),o==="reset-password"&&this.handleResetPassword()})}),this.root.querySelectorAll("input[name]").forEach(a=>{a.addEventListener("input",()=>{le(a.name)&&(this.state[a.name]=a.value)})}),this.root.querySelectorAll("[data-action]").forEach(a=>{a.addEventListener("click",()=>{const r=a.dataset.action;r==="switch-sign-up"&&this.switchView("sign-up"),r==="switch-sign-in"&&this.switchView("sign-in"),r==="forgot-password"&&this.switchView("forgot-password"),r==="resend-verification"&&this.resendVerificationEmail(),r==="use-different-email"&&this.switchView(this.verificationCompletionAction==="sign-in"?"sign-in":"sign-up"),r==="resend-reset-code"&&this.resendResetCode(),r==="oauth"&&this.handleOAuthSignIn(a.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(!T(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(f,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(!T(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 a;const i=await this.auth.signUp.email({name:this.state.name.trim(),email:this.state.email.trim(),password:this.state.password,callbackURL:this.getManagedReturnURL(w,this.state.email.trim())});if(i.error)throw i.error;if((a=this.config)!=null&&a.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 ${_[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 d(`OAuth sign-in did not return a redirect URL for provider "${e}".`);this.terminalActionInProgress=!0,this.state.busy=!0,this.state.busyLabel=`Opening ${_[e]}…`,this.state.error=null,this.state.notice=null,this.render(),window.location.assign(i)})}async handleForgotPassword(){if(!this.canUsePasswordResetEmailOtp()){this.handleError(new d("Password reset via email OTP is not enabled for this project."));return}if(!T(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(){if(!this.canUsePasswordResetEmailOtp()){this.handleError(new d("Password reset via email OTP is not enabled for this project."));return}if(!oe(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!==this.state.confirmPassword){this.failValidation(this.labels.errors.passwordMismatch);return}await this.runAction("Updating password…",async()=>{const e=await this.passwordResetEndpoints().emailOtp.resetPassword({email:this.state.email.trim(),otp:this.state.code.trim(),password:this.state.newPassword});if(e.error)throw e.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"?w:f,this.state.email.trim())});if(s.error)throw s.error;this.handleVerificationEmailSent(this.state.email.trim(),!0)})}async completeAuth(e,s){var r,o,l,c;const i=s??await this.resolveAuthCompletionData();if(!i.user||!i.session){if(e==="sign-in")throw new q("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 a={action:e,user:i.user,session:i.session};if(await((o=(r=this.runtimeOptions)==null?void 0:r.syncPublicSession)==null?void 0:o.call(r)),j(this.options)){this.terminalActionInProgress=!0,(c=(l=this.options).onSuccess)==null||c.call(l,a),this.state.busy=!0,this.state.busyLabel=this.labels.common.redirecting,this.state.error=null,this.state.notice=null,this.render(),window.location.assign(N(this.options.redirectTo).toString());return}if($(this.options)){this.destroy(),this.options.onSuccess(a);return}}async resolveAuthCompletionData(e){const s=await W(this.auth),i=this.extractUser(e);return{user:s.user??i,session:s.session}}async completePasswordReset(){var s,i;const e={action:"password-reset",user:null,session:null};if($(this.options)){this.destroy(),this.options.onSuccess(e);return}(i=(s=this.options).onSuccess)==null||i.call(s,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(e){if(j(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(N(this.options.redirectTo).toString());return}if($(this.options))throw this.state.view="sign-in",this.state.busy=!1,this.state.busyLabel=void 0,this.state.notice=null,new d("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 D(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()}handleError(e,s){var a,r;const i=D(e,s);this.state.busy=!1,this.state.busyLabel=void 0,this.state.error=i.message,this.render(),(r=(a=this.options).onError)==null||r.call(a,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(C,e),s?i.searchParams.set(g,s):i.searchParams.delete(g),i.toString()}consumeManagedReturnContext(){const e=new URL(window.location.href),s=e.searchParams.get(C),i=e.searchParams.get(g),a=e.searchParams.get("error"),r=e.searchParams.get("error_description");return(s||i||a||r)&&(e.searchParams.delete(C),e.searchParams.delete(g),e.searchParams.delete("error"),e.searchParams.delete("error_description"),window.history.replaceState(null,"",e.toString())),{marker:s,email:i,error:a,errorDescription:r}}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 a=i.value.length;i.setSelectionRange(a,a)}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===w&&!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===f||e.marker===w?(this.verificationCompletionAction=e.marker===w?"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 u(e.errorDescription??"Verification failed. Request a new verification email and try again.",{code:e.error??"VERIFY_EMAIL_ERROR"})):this.render(),!0):e.marker===H&&(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 u(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,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}}function ce(t){return"data"in t&&t.data?t.data:t}const ue=[{id:"google",key:"providerGoogle"},{id:"apple",key:"providerApple"},{id:"microsoft",key:"providerMicrosoft"},{id:"github",key:"providerGithub"},{id:"gitlab",key:"providerGitlab"},{id:"discord",key:"providerDiscord"}],G=2,he=500;async function me(){const t=`${window.location.origin}${Y}/config`;let e;for(let s=0;s<=G;s++)try{const i=await fetch(t,{method:"GET",credentials:"include"});if(!i.ok)throw new d(`Failed to load auth config: HTTP ${i.status}`);const a=await i.json();return be(ce(a))}catch(i){e=i,s<G&&await new Promise(a=>setTimeout(a,he))}throw e}let v=null;async function we(){return v||(v=me().catch(t=>{throw v=null,t})),v}function be(t){var s,i,a,r,o,l,c;const e=ue.filter(({key:h})=>{const m=t[h];return typeof m=="object"&&m!==null&&"enabled"in m&&!!m.enabled}).map(({id:h})=>h);return{disableSignUp:!!t.disableSignUp,emailPasswordEnabled:!!((s=t.providerEmailPassword)!=null&&s.enabled),minPasswordLength:((a=(i=t.providerEmailPassword)==null?void 0:i.config)==null?void 0:a.minPasswordLength)??8,requireEmailVerification:!!((o=(r=t.providerEmailPassword)==null?void 0:r.config)!=null&&o.requireEmailVerification),passwordResetEmailOtpEnabled:!!((c=(l=t.providerEmailPassword)==null?void 0:l.config)!=null&&c.requirePasswordResetEmailVerification),oauthProviders:e}}const P=new WeakMap;function pe(t){if(!t)throw new d("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 d("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 d("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 d("authUI.mount(container, options) expected onSuccess to be a function.");if("onError"in t&&t.onError!==void 0&&typeof t.onError!="function")throw new d("authUI.mount(container, options) expected onError to be a function.")}function ge(t){if(!(t instanceof HTMLElement))throw new d("authUI.mount(container, options) requires a real HTMLElement container.")}function fe(t,e){return{mount(s,i){var l;pe(i),ge(s),(l=P.get(s))==null||l.destroy();const a=new de(s,t,i,we,e),r=a.destroy.bind(a),o={destroy(){r(),P.get(s)===o&&P.delete(s)}};return P.set(s,o),o}}}function ve(){K();const t=ie(),e=ne(),s=te(),i=fe(e,{syncPublicSession:async()=>{await se(t)}});return{auth:t,api:s,authUI:i}}exports.EdgeSparkAuthError=u;exports.EdgeSparkConfigError=d;exports.EdgeSparkError=E;exports.EdgeSparkRuntimeError=q;exports.ar=z;exports.createEdgeSpark=ve;exports.de=k;exports.detectLocale=Z;exports.enUS=b;exports.es=y;exports.fr=M;exports.hi=F;exports.it=V;exports.ja=U;exports.ko=A;exports.ptBR=B;exports.ru=O;exports.zhCN=L;
|
|
147
|
+
`}bindDOM(){this.root.querySelectorAll("form[data-view]").forEach(r=>{r.addEventListener("submit",o=>{o.preventDefault();const u=r.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(r=>{r.addEventListener("input",()=>{he(r.name)&&(this.state[r.name]=r.value)})}),this.root.querySelectorAll("[data-action]").forEach(r=>{r.addEventListener("click",()=>{const o=r.dataset.action;o==="switch-sign-up"&&this.switchView("sign-up"),o==="switch-sign-in"&&this.switchView("sign-in"),o==="forgot-password"&&this.switchView("forgot-password"),o==="resend-verification"&&this.resendVerificationEmail(),o==="use-different-email"&&this.switchView(this.verificationCompletionAction==="sign-in"?"sign-in":"sign-up"),o==="resend-reset-code"&&this.resendResetCode(),o==="oauth"&&this.handleOAuthSignIn(r.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(!I(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(f,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(!I(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 r;const i=await this.auth.signUp.email({name:this.state.name.trim(),email:this.state.email.trim(),password:this.state.password,callbackURL:this.getManagedReturnURL(b,this.state.email.trim())});if(i.error)throw i.error;if((r=this.config)!=null&&r.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 ${R[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 c(`OAuth sign-in did not return a redirect URL for provider "${e}".`);this.terminalActionInProgress=!0,this.state.busy=!0,this.state.busyLabel=`Opening ${R[e]}…`,this.state.error=null,this.state.notice=null,this.render(),window.location.assign(i)})}async handleForgotPassword(){if(!this.canUsePasswordResetEmailOtp()){this.handleError(new c("Password reset via email OTP is not enabled for this project."));return}if(!I(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(){if(!this.canUsePasswordResetEmailOtp()){this.handleError(new c("Password reset via email OTP is not enabled for this project."));return}if(!ue(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!==this.state.confirmPassword){this.failValidation(this.labels.errors.passwordMismatch);return}await this.runAction("Updating password…",async()=>{const e=await this.passwordResetEndpoints().emailOtp.resetPassword({email:this.state.email.trim(),otp:this.state.code.trim(),password:this.state.newPassword});if(e.error)throw e.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"?b:f,this.state.email.trim())});if(s.error)throw s.error;this.handleVerificationEmailSent(this.state.email.trim(),!0)})}async completeAuth(e,s){var o,u;const i=s??await this.resolveAuthCompletionData();if(!i.user||!i.session){if(e==="sign-in")throw new N("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 r={action:e,user:i.user,session:i.session};if(await((u=(o=this.runtimeOptions)==null?void 0:o.syncPublicSession)==null?void 0:u.call(o)),T(this.options)){this.terminalActionInProgress=!0,this.invokeRedirectModeSuccessHook(r),this.state.busy=!0,this.state.busyLabel=this.labels.common.redirecting,this.state.error=null,this.state.notice=null,this.render(),window.location.assign(W(this.options.redirectTo).toString());return}if($(this.options)){this.destroy(),this.options.onSuccess(r);return}}async resolveAuthCompletionData(e){const s=await G(this.auth),i=this.extractUser(e);return{user:s.user??i,session:s.session}}async completePasswordReset(){const e={action:"password-reset",user:null,session:null};if($(this.options)){this.destroy(),this.options.onSuccess(e);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(e){if(T(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(W(this.options.redirectTo).toString());return}if($(this.options))throw this.state.view="sign-in",this.state.busy=!1,this.state.busyLabel=void 0,this.state.notice=null,new c("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 C(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(!(!T(this.options)||!this.options.onSuccess))try{this.options.onSuccess(e)}catch(r){const o=C(r,"Post-auth callback failed.");try{(i=(s=this.options).onError)==null||i.call(s,o)}catch{}}}handleError(e,s){var r,o;const i=C(e,s);this.state.busy=!1,this.state.busyLabel=void 0,this.state.error=i.message,this.render(),(o=(r=this.options).onError)==null||o.call(r,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(_,e),s?i.searchParams.set(g,s):i.searchParams.delete(g),i.toString()}consumeManagedReturnContext(){const e=new URL(window.location.href),s=e.searchParams.get(_),i=e.searchParams.get(g),r=s?e.searchParams.get("error"):null,o=s?e.searchParams.get("error_description"):null;return(s||i)&&(e.searchParams.delete(_),e.searchParams.delete(g),s&&(e.searchParams.delete("error"),e.searchParams.delete("error_description")),window.history.replaceState(null,"",e.toString())),{marker:s,email:i,error:r,errorDescription:o}}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 r=i.value.length;i.setSelectionRange(r,r)}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===b&&!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===f||e.marker===b?(this.verificationCompletionAction=e.marker===b?"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 h(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 h(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,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}}function we(t){return"data"in t&&t.data?t.data:t}const be=[{id:"google",key:"providerGoogle"},{id:"apple",key:"providerApple"},{id:"microsoft",key:"providerMicrosoft"},{id:"github",key:"providerGithub"},{id:"gitlab",key:"providerGitlab"},{id:"discord",key:"providerDiscord"}],K=2,pe=500;async function ge(){const t=`${window.location.origin}${Z}/config`;let e;for(let s=0;s<=K;s++)try{const i=await fetch(t,{method:"GET",credentials:"include"});if(!i.ok)throw new c(`Failed to load auth config: HTTP ${i.status}`);const r=await i.json();return ve(we(r))}catch(i){e=i,s<K&&await new Promise(r=>setTimeout(r,pe))}throw e}let v=null;async function fe(){return v||(v=ge().catch(t=>{throw v=null,t})),v}function ve(t){var s,i,r,o,u,m,l;const e=be.filter(({key:a})=>{const d=t[a];return typeof d=="object"&&d!==null&&"enabled"in d&&!!d.enabled}).map(({id:a})=>a);return{disableSignUp:!!t.disableSignUp,emailPasswordEnabled:!!((s=t.providerEmailPassword)!=null&&s.enabled),minPasswordLength:((r=(i=t.providerEmailPassword)==null?void 0:i.config)==null?void 0:r.minPasswordLength)??8,requireEmailVerification:!!((u=(o=t.providerEmailPassword)==null?void 0:o.config)!=null&&u.requireEmailVerification),passwordResetEmailOtpEnabled:!!((l=(m=t.providerEmailPassword)==null?void 0:m.config)!=null&&l.requirePasswordResetEmailVerification),oauthProviders:e}}const P=new WeakMap;function Pe(t){if(!t)throw new c("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 c("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 c("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 c("authUI.mount(container, options) expected onSuccess to be a function.");if("onError"in t&&t.onError!==void 0&&typeof t.onError!="function")throw new c("authUI.mount(container, options) expected onError to be a function.")}function ye(t){if(!(t instanceof HTMLElement))throw new c("authUI.mount(container, options) requires a real HTMLElement container.")}function Le(t,e){return{mount(s,i){var m;Pe(i),ye(s),(m=P.get(s))==null||m.destroy();const r=new me(s,t,i,fe,e),o=r.destroy.bind(r),u={destroy(){o(),P.get(s)===u&&P.delete(s)}};return P.set(s,u),u}}}function Ee(){J();const t=ae(),e=le(),s=re(),i=Le(e,{syncPublicSession:async()=>{await oe(t)}});return{auth:t,api:s,authUI:i}}exports.EdgeSparkAuthError=h;exports.EdgeSparkConfigError=c;exports.EdgeSparkError=S;exports.EdgeSparkRuntimeError=N;exports.ar=F;exports.createEdgeSpark=Ee;exports.de=V;exports.detectLocale=X;exports.enUS=p;exports.es=E;exports.fr=M;exports.hi=q;exports.it=O;exports.ja=A;exports.ko=B;exports.ptBR=k;exports.ru=z;exports.zhCN=L;
|
package/dist/index.d.ts
CHANGED
|
@@ -6,4 +6,21 @@ export type { DeepPartial } from './shared/types';
|
|
|
6
6
|
export type { RedirectTarget } from './redirect';
|
|
7
7
|
export type { AuthSuccessEvent, AuthUILabelOverrides, AuthUILabels, ControlledAuthUIOptions, EdgeSparkAuthUI, MountAuthUIOptions, MountedAuthUI, RedirectAuthUIOptions, } from './auth-ui/types';
|
|
8
8
|
export { EdgeSparkAuthError, EdgeSparkConfigError, EdgeSparkError, EdgeSparkRuntimeError, } from './errors';
|
|
9
|
+
/**
|
|
10
|
+
* Locale helpers for managed auth UI labels.
|
|
11
|
+
*
|
|
12
|
+
* Auto-detection already happens by default inside `authUI.mount(...)`.
|
|
13
|
+
* Import these only when the app wants to force a preset or build a custom
|
|
14
|
+
* label object:
|
|
15
|
+
*
|
|
16
|
+
* ```ts
|
|
17
|
+
* es.authUI.mount(container, {
|
|
18
|
+
* redirectTo: "/dashboard",
|
|
19
|
+
* labels: fr,
|
|
20
|
+
* });
|
|
21
|
+
* ```
|
|
22
|
+
*
|
|
23
|
+
* `detectLocale()` is exported for advanced cases that need the same browser
|
|
24
|
+
* language matching outside the managed UI.
|
|
25
|
+
*/
|
|
9
26
|
export { detectLocale, enUS, zhCN, ja, ko, es, ptBR, fr, de, it, ru, ar, hi, } from './locales';
|