export async function login(email, password) { const csrf = await fetch('/sanctum/csrf-cookie', { credentials: 'same-origin', headers: { Accept: 'application/json' }, }); if (!csrf.ok) throw new Error('Could not initialize the login session.'); const cookie = document.cookie.split('; ') .find((part) => part.startsWith('XSRF-TOKEN=')); if (!cookie) throw new Error('The CSRF cookie is unavailable.'); const response = await fetch('/login', { method: 'POST', credentials: 'same-origin', headers: { Accept: 'application/json', 'Content-Type': 'application/json', 'X-XSRF-TOKEN': decodeURIComponent(cookie.slice('XSRF-TOKEN='.length)), }, body: JSON.stringify({ email, password }), }); if (response.status === 419) throw new Error('Session expired. Please try again.'); if (response.status === 422) throw new Error('Check your login details.'); if (response.status === 429) throw new Error('Too many attempts. Try again later.'); if (!response.ok) throw new Error('Login failed. Please try again.'); }