UNPKG

@better-auth-ui/core

Version:

Authentication components and data utilities for [Better Auth](https://better-auth.com), available for React and Solid.

341 lines (340 loc) 12.1 kB
import { viewPaths as e } from "./lib/view-paths.js"; //#region src/lib/localization.ts var t = { auth: { callbackAccountLinkedTitle: "Account linked", callbackAccountLinkedDescription: "Your account is now connected.", callbackAccountLinkConflictTitle: "This account is already connected", callbackAccountLinkConflictDescription: "The provider account belongs to a different user or cannot be linked safely.", callbackCancelledTitle: "Authentication was cancelled", callbackCancelledDescription: "No changes were made. You can try again when you are ready.", callbackFailedTitle: "We could not complete authentication", callbackFailedDescription: "The callback could not be verified. Return to sign in and try again.", callbackContinue: "Continue", callbackEmailVerifiedTitle: "Email verified", callbackEmailVerifiedDescription: "Your email address is verified. You can continue to your account.", callbackEmailNotVerifiedTitle: "Verify your email first", callbackEmailNotVerifiedDescription: "Check your inbox for a verification link before you sign in.", callbackExpiredLinkTitle: "This link has expired", callbackExpiredLinkDescription: "Request a new link and use the most recent message in your inbox.", callbackGenericErrorTitle: "Something went wrong", callbackGenericErrorDescription: "We could not finish this request. Return to sign in and try again.", callbackGenericSuccessTitle: "All set", callbackGenericSuccessDescription: "Authentication completed successfully.", callbackMissingEmailTitle: "Email address unavailable", callbackMissingEmailDescription: "The provider did not share an email address. Try another sign-in method.", callbackPasswordResetTitle: "Password reset", callbackPasswordResetDescription: "Your password was reset. Sign in with your new password.", callbackSignupCompleteTitle: "Account created", callbackSignupCompleteDescription: "Your account is ready. You can continue.", callbackSignupDisabledTitle: "Sign-up is unavailable", callbackSignupDisabledDescription: "New accounts cannot be created with this sign-in method. Try signing in instead.", callbackViewAccountSettings: "Account settings", account: "Account", alreadyHaveAnAccount: "Already have an account?", alreadyVerifiedYourEmail: "Already verified your email?", confirmPassword: "Confirm password", confirmPasswordPlaceholder: "Confirm your password", checkYourEmail: "Check your email for a verification link", checkYourEmailTitle: "Check your email", continueWith: "Continue with {{provider}}", email: "Email", emailPlaceholder: "m@example.com", fieldRequired: "This field is required", forgotPassword: "Forgot Password", forgotPasswordLink: "Forgot password?", hidePassword: "Hide password", invalidEmail: "Please enter a valid email address", invalidResetPasswordToken: "Invalid reset password token", name: "Name", namePlaceholder: "Name", needToCreateAnAccount: "Need to create an account?", newPassword: "New password", newPasswordPlaceholder: "New password", openEmailProvider: "Open {{provider}}", or: "OR", optional: " (optional)", password: "Password", passwordCompromised: "This password has appeared in a data breach. Pick a different one.", passwordFair: "Fair", passwordGood: "Good", passwordPlaceholder: "Password", passwordResetEmailSent: "Password reset email sent", passwordResetErrorDescription: "Unable to reset your password. Try again.", passwordResetSuccess: "Password reset successfully", passwordResetSuccessDescription: "Password reset successfully. You can sign in with your new password.", passwordStrength: "Password strength", passwordStrong: "Strong", passwordWeak: "Weak", passwordsDoNotMatch: "Passwords do not match", rememberMe: "Remember me", tooLong: "Must be at most {{max}} characters", tooShort: "Must be at least {{min}} characters", rememberYourPassword: "Remember your password?", resend: "Resend", resendIn: "Resend in {{seconds}}s", resetLinkSentTo: "We sent a password reset link to {{email}}", resetPassword: "Reset Password", sendResetLink: "Send reset link", scanToOpenEmailProvider: "Scan to open {{provider}} on your phone", showPassword: "Show password", signIn: "Sign In", signOut: "Sign Out", signUp: "Sign Up", verificationEmailSent: "Verification email sent!", verifyEmail: "Verify Email" }, settings: { account: "Account", accountUnlinked: "Account unlinked", active: "Active", activeSessions: "Active sessions", reauthenticationTitle: "Sign in again", reauthenticationDescription: "Please sign in again to verify it’s you before continuing.", reauthenticationAction: "Sign in again", avatar: "Avatar", currentSession: "Current session", avatarChangedSuccess: "Avatar changed successfully", avatarDeletedSuccess: "Avatar deleted successfully", changeAvatar: "Change avatar", deleteAvatar: "Delete avatar", link: "Link", linkedAccounts: "Linked accounts", lastAccountUnlinkingDisabled: "Link another sign-in method before unlinking this account.", linkProvider: "Link your {{provider}} account", cancel: "Cancel", copyToClipboard: "Copy to clipboard", copiedToClipboard: "Copied to clipboard", changeEmail: "Change email", changeEmailSuccess: "Check your email to confirm the change", changePassword: "Change password", changePasswordSuccess: "Password changed successfully", currentPassword: "Current password", currentPasswordPlaceholder: "Enter your current password", dangerZone: "Danger zone", delete: "Delete", optional: "Optional", profileUpdatedSuccess: "Profile updated successfully", revoke: "Revoke", revokeSession: "Revoke session", revokeSessionSuccess: "Session revoked successfully", signOutOtherDevices: "Sign out other devices", signOutOtherDevicesDescription: "This signs you out on every device except this one.", signOutOtherDevicesSuccess: "Other devices signed out successfully", signOutEverywhere: "Sign out everywhere", signOutEverywhereDescription: "This signs you out on this device and every other device.", saveChanges: "Save changes", setPassword: "Set password", setPasswordDescription: "You don't have a password yet. Request a reset link to set one up.", security: "Security", settings: "Settings", time: "Time", unlinkProvider: "Unlink {{provider}}", updateEmail: "Update email", updatePassword: "Update password", uploadAvatar: "Upload avatar", userProfile: "User profile" } }, n = 4096, r = 96, i = 16, a = [ .82, .68, .54, .4 ]; function o(e) { return typeof e == "object" && !!e && !Array.isArray(e); } function s(e) { return !(!o(e) || e instanceof Date || e instanceof RegExp); } function c(e, t = 256, n = "png") { let r = t, i = n === "inherit" ? e.name.split(".").pop() : n, a = n === "inherit" ? e.type : `image/${n === "jpg" ? "jpeg" : n}`; return new Promise((t, n) => { let o = new Image(), s = URL.createObjectURL(e); o.onload = () => { URL.revokeObjectURL(s); let { naturalWidth: c, naturalHeight: l } = o, u = Math.min(c, l), d = (c - u) / 2, f = (l - u) / 2, p = Math.min(u, r), m = document.createElement("canvas"); m.width = p, m.height = p; let h = m.getContext("2d"); if (!h) { n(/* @__PURE__ */ Error("Could not get canvas context")); return; } h.drawImage(o, d, f, u, u, 0, 0, p, p), m.toBlob((r) => { if (!r) { n(/* @__PURE__ */ Error("Could not create blob from canvas")); return; } t(new File([r], e.name.replace(/\.[^.]+$/, `.${i}`), { type: a })); }, a, 1); }, o.onerror = () => { URL.revokeObjectURL(s), n(/* @__PURE__ */ Error("Failed to load image")); }, o.src = s; }); } function l(e) { return u(e); } function u(e) { return new Promise((t, n) => { let r = new FileReader(); r.onload = () => { if (typeof r.result == "string") { t(r.result); return; } n(/* @__PURE__ */ Error("Failed to read file")); }, r.onerror = () => n(/* @__PURE__ */ Error("Failed to read file")), r.readAsDataURL(e); }); } function d(e, t, n) { return new Promise((r, i) => { e.toBlob((e) => { if (e) { r(e); return; } i(/* @__PURE__ */ Error("Could not encode avatar")); }, t, n); }); } function f(e) { let t = [], n = e; for (; n > i;) t.push(n), n = Math.floor(n * .75); return t.push(Math.min(e, i)), t; } async function p(e) { let t = URL.createObjectURL(e), i = new Image(); try { await new Promise((e, n) => { i.onload = () => e(), i.onerror = () => n(/* @__PURE__ */ Error("Failed to load avatar")), i.src = t; }); let e = Math.min(i.naturalWidth, i.naturalHeight), o = Math.min(e, r), s = (i.naturalWidth - e) / 2, c = (i.naturalHeight - e) / 2, l = document.createElement("canvas"), p = l.getContext("2d"); if (!p) throw Error("Could not get canvas context"); for (let t of f(o)) { l.width = t, l.height = t, p.clearRect(0, 0, t, t), p.drawImage(i, s, c, e, e, 0, 0, t, t); for (let e of a) { let t = await u(await d(l, "image/webp", e)); if (t.length <= n) return t; } } throw Error("Could not reduce avatar to a safe embedded size"); } finally { URL.revokeObjectURL(t); } } function m(e, t) { if (s(e) && s(t)) { let n = { ...e }; for (let [r, i] of Object.entries(t)) i !== void 0 && (n[r] = r in e ? m(e[r], i) : i); return n; } return t; } //#endregion //#region src/lib/auth-locale.ts var h = { languageTag: "en-US", direction: "ltr", localization: t }; function g(e) { return e; } function _(e) { try { return Intl.getCanonicalLocales(e)[0]; } catch { return; } } function v(e) { return (Array.isArray(e) ? e : typeof e == "string" ? e.split(",") : []).map((e, t) => { let [n, ...r] = e.trim().split(";"), i = r.find((e) => e.trim().toLowerCase().startsWith("q=")), a = i ? Number.parseFloat(i.trim().slice(2)) : 1; return { index: t, languageTag: _(n), quality: Number.isFinite(a) ? a : 0 }; }).filter((e) => !!e.languageTag && e.quality > 0 && e.quality <= 1).sort((e, t) => t.quality - e.quality || e.index - t.index).map((e) => e.languageTag); } function y({ requested: e, supported: t, fallback: n }) { let r = t.map((e) => ({ locale: e, languageTag: _(e.languageTag) })).filter((e) => !!e.languageTag); for (let t of v(e)) { let e = r.find((e) => e.languageTag === t); if (e) return e.locale; let n = t.split("-")[0], i = r.find((e) => e.languageTag.split("-")[0] === n); if (i) return i.locale; } return n; } function b(e, t) { return e.map((e) => { let n = t.plugins?.[e.id] ?? {}, r = e._localizationResolver; if (Object.keys(n).length === 0 && !r) return e; let i = m(m(e.localization ?? {}, n), e._localizationOverrides ?? {}), a = { ...e, localization: i }; return r?.(a, { direction: t.direction ?? "ltr", languageTag: t.languageTag, localization: i }) ?? a; }); } //#endregion //#region src/lib/base-paths.ts var x = { admin: "/admin", auth: "/auth", settings: "/settings", organization: "/organization" }, S = { allowUnlinkingAllAccounts: !1, avatar: { enabled: !0, resize: c, size: 256, extension: "png" }, basePaths: x, baseURL: "", emailAndPassword: { enabled: !0, forgotPassword: !0, name: !0, rememberMe: !1, strengthMeter: !0, minPasswordLength: 8, maxPasswordLength: 128 }, plugins: [], redirectTo: "/", socialSignInMode: "redirect", viewPaths: e, localization: t, locale: h, navigate: ({ to: e, replace: t }) => { t ? window.location.replace(e) : window.location.href = e; } }; function C(e) { let n = e.locale ?? h, r = m(m(t, n.localization), e.localization ?? {}), i = b(e.plugins ?? [], n), a = m(S, { ...e, locale: n, localization: r, plugins: i }), o = /* @__PURE__ */ new Map(); for (let e of i) for (let t of e.additionalFields ?? []) o.set(t.name, t); for (let e of a.additionalFields ?? []) o.set(e.name, e); return a.additionalFields = Array.from(o.values()), { ...a, authClient: e.authClient }; } //#endregion export { g as a, m as c, c as d, t as f, h as i, p as l, C as n, b as o, x as r, y as s, S as t, l as u };