import { authQueryKeys } from "@better-auth-ui/core" import { usernameMutationKeys } from "@better-auth-ui/core/plugins" import { mutationOptions, type QueryClient, useMutation } from "@tanstack/react-query" import type { BetterFetchError } from "better-auth/react" import type { UsernameAuthClient } from "../../lib/auth-client" export type SignInUsernameParams = Parameters[0] export type SignInUsernameOptions = Omit< ReturnType>, "mutationKey" | "mutationFn" | "meta" > /** * Mutation options factory for username/password sign-in. * * @param authClient - The Better Auth client. */ export function signInUsernameOptions( authClient: TAuthClient ) { const mutationKey = usernameMutationKeys.signIn const mutationFn = (params: SignInUsernameParams) => authClient.signIn.username({ ...params, fetchOptions: { ...params?.fetchOptions, throw: true } }) return mutationOptions< Awaited>, BetterFetchError, Parameters[0] >({ mutationKey, mutationFn }) } /** * Create a mutation for username/password sign-in. * * On success, `MutationInvalidator` awaits invalidation of the session * query so the new session is refetched (see `meta.awaits`). * * @param authClient - The Better Auth client with the username plugin. * @param options - React Query options forwarded to `useMutation`. */ export function useSignInUsername( authClient: TAuthClient, options?: SignInUsernameOptions, queryClient?: QueryClient ) { return useMutation( { ...signInUsernameOptions(authClient), ...options, meta: { awaits: [authQueryKeys.session] } }, queryClient ) }