### Implement Login Form Action with Effect Source: https://context7.com/mateoroldos/sveltekit-effect-template/llms.txt Defines the Zod schema, the Effect-based action logic, and the SvelteKit server integration for a login form. ```typescript // src/routes/_actions/login-action/login-action-schema.ts import { z } from 'zod'; export const loginActionSchema = z.object({ username: z.string().min(2, 'Username must be at least 2 characters').max(50) }); export type LoginActionSchema = typeof loginActionSchema; // src/routes/_actions/login-action/login-action.ts import { superValidateActionForm } from '$lib/server/super-validate.server'; import { Effect } from 'effect'; import { loginActionSchema } from './login-action-schema'; import { CustomInputError, Redirect, ServerError } from '$lib/server/responses'; export const loginAction = Effect.gen(function* () { // Validate the form - fails automatically if invalid const form = yield* superValidateActionForm(loginActionSchema); // Simulate async operation (database lookup) yield* Effect.promise(() => new Promise((resolve) => setTimeout(resolve, 1000))); // Example: Check credentials (simulated) const user = yield* Effect.tryPromise({ try: () => authenticateUser(form.data.username), catch: () => new ServerError({ errors: ['Authentication service unavailable'], message: 'Unable to verify credentials. Please try again.' }) }); if (!user) { yield* Effect.fail( new CustomInputError({ form, field: 'username', message: 'Invalid username or password' }) ); } // Successful login - redirect with welcome message return new Redirect({ to: '/welcome', code: 302, message: `Welcome ${form.data.username}!` }); }); // src/routes/+page.server.ts import { runLoader } from '$lib/server/run-loader'; import { runAction } from '$lib/server/run-action'; import { Effect } from 'effect'; import { OkLoader } from '$lib/server/responses'; import { superValidateLoader } from '$lib/server/super-validate.server'; import { zod } from 'sveltekit-superforms/adapters'; import { loginActionSchema } from './_actions/login-action/login-action-schema'; import { loginAction } from './_actions/login-action/login-action'; export const load = () => runLoader( Effect.gen(function* () { return new OkLoader({ data: { loginActioForm: yield* superValidateLoader(zod(loginActionSchema)) } }); }) ); export const actions = { login: runAction(loginAction) }; ``` -------------------------------- ### Implement flash messages for toast notifications Source: https://context7.com/mateoroldos/sveltekit-effect-template/llms.txt Provides server-side utilities to set flash messages via cookies and client-side logic to display them as toasts using svelte-sonner. ```typescript // src/lib/utils/set-flash.server.ts import type { Cookies } from '@sveltejs/kit'; import { setFlash } from 'sveltekit-flash-message/server'; export const setFlashSuccess = (message: string, cookies: Cookies) => { setFlash({ type: 'success', message }, cookies); }; export const setFlashError = (message: string, cookies: Cookies) => { setFlash({ type: 'error', message }, cookies); }; // Usage in custom action handlers import { ActionArgs } from '$lib/server/run-action'; import { setFlashSuccess } from '$lib/utils/set-flash.server'; const customAction = Effect.gen(function* () { const event = yield* ActionArgs; // Manually set flash message setFlashSuccess('Operation completed!', event.cookies); // Flash messages are automatically set by: // - OkAction with message property // - Redirect with message property // - BadRequest, ServerError, Forbidden with message property }); // Client-side flash message handling (src/routes/+layout.svelte) // ``` -------------------------------- ### Implement superValidateLoader in SvelteKit Loaders Source: https://context7.com/mateoroldos/sveltekit-effect-template/llms.txt Initializes Superforms validated form objects within Effect-based loaders, handling errors consistently. ```typescript // src/routes/contact/+page.server.ts import { runLoader } from '$lib/server/run-loader'; import { Effect } from 'effect'; import { OkLoader } from '$lib/server/responses'; import { superValidateLoader, superValidateLoaderWithData } from '$lib/server/super-validate.server'; import { zod } from 'sveltekit-superforms/adapters'; import { z } from 'zod'; const contactSchema = z.object({ name: z.string().min(2).max(100), email: z.string().email(), subject: z.string().min(5).max(200), message: z.string().min(10).max(5000) }); export const load = () => runLoader( Effect.gen(function* () { // Initialize empty form const contactForm = yield* superValidateLoader(zod(contactSchema)); // Or initialize with default/existing data const prefillData = { name: 'John', email: 'john@example.com', subject: '', message: '' }; const prefilledForm = yield* superValidateLoaderWithData( prefillData, zod(contactSchema) ); return new OkLoader({ data: { contactForm, prefilledForm } }); }) ); ``` -------------------------------- ### Execute Effects in SvelteKit Load Functions Source: https://context7.com/mateoroldos/sveltekit-effect-template/llms.txt Use `runLoader` to execute Effect-TS effects within SvelteKit's load functions. It maps Effect outcomes to SvelteKit loader responses, handling success, redirects, and various error types. Requires Effect-TS and custom response types like `OkLoader`, `Redirect`, and `ServerError`. ```typescript // src/routes/+page.server.ts import { runLoader } from '$lib/server/run-loader'; import { Effect } from 'effect'; import { OkLoader, Redirect, ServerError } from '$lib/server/responses'; import { superValidateLoader } from '$lib/server/super-validate.server'; import { zod } from 'sveltekit-superforms/adapters'; import { z } from 'zod'; import type { PageServerLoadEvent } from './$types'; const userSchema = z.object({ email: z.string().email(), name: z.string().min(2) }); export const load = (event: PageServerLoadEvent) => runLoader( Effect.gen(function* () { // Initialize form with validation schema const userForm = yield* superValidateLoader(zod(userSchema)); // Fetch data from database (example) const user = yield* Effect.tryPromise({ try: () => fetchUserFromDb(event.locals.userId), catch: () => new ServerError({ errors: ['Failed to fetch user'] }) }); // Conditional redirect if (!user.isVerified) { yield* Effect.fail(new Redirect({ to: '/verify-email', code: 302 })); } // Return successful loader data return new OkLoader({ data: { userForm, user: { name: user.name, email: user.email } } }); }) ); ``` -------------------------------- ### Execute Effects in SvelteKit Form Actions Source: https://context7.com/mateoroldos/sveltekit-effect-template/llms.txt Use `runAction` to wrap Effect-TS effects for SvelteKit form actions. It provides access to `RequestEvent`, handles form validation errors, and supports redirects with flash messages. Integrates with Superforms for returning form state on errors. Requires Effect-TS and custom response types like `OkAction`, `Redirect`, `ServerError`, `BadRequest`, `Forbidden`, and `CustomInputError`. ```typescript // src/routes/+page.server.ts import { runAction, ActionArgs } from '$lib/server/run-action'; import { Effect } from 'effect'; import { OkAction, Redirect, ServerError, BadRequest, Forbidden, CustomInputError } from '$lib/server/responses'; import { superValidateActionForm } from '$lib/server/super-validate.server'; import { z } from 'zod'; const registerSchema = z.object({ username: z.string().min(3).max(20), email: z.string().email(), password: z.string().min(8) }); const registerAction = Effect.gen(function* () { // Validate form data from request - automatically fails with FormValidationError if invalid const form = yield* superValidateActionForm(registerSchema); // Access the RequestEvent for cookies, locals, etc. const event = yield* ActionArgs; // Check for existing user const existingUser = yield* Effect.tryPromise({ try: () => checkUserExists(form.data.email), catch: () => new ServerError({ message: 'Database connection failed' }) }); if (existingUser) { // Custom field-level error yield* Effect.fail( new CustomInputError({ form, field: 'email', message: 'This email is already registered' }) ); } // Create user yield* Effect.tryPromise({ try: () => createUser(form.data), catch: () => new ServerError({ message: 'Failed to create account' }) }); // Redirect with success flash message return new Redirect({ to: '/dashboard', code: 302, message: `Welcome ${form.data.username}!` }); }); export const actions = { register: runAction(registerAction) }; ``` -------------------------------- ### Define TaggedClass Response Types Source: https://context7.com/mateoroldos/sveltekit-effect-template/llms.txt Defines discriminated union types for success, error, and redirect responses to enable exhaustive pattern matching. ```typescript // src/lib/server/responses.ts import { Data } from 'effect'; import type { SuperValidated } from 'sveltekit-superforms'; // Success response for loaders - wraps arbitrary data export class OkLoader extends Data.TaggedClass('OkLoader')<{ readonly data: T; }> {} // Success response for actions - includes form state and optional message export class OkAction extends Data.TaggedClass('OkAction')<{ readonly form: T; readonly message?: string; // Displays as success toast }> {} // Redirect response - works for both success and error flows export class Redirect extends Data.TaggedClass('Redirect')<{ readonly to: string; readonly code: number; // HTTP status code (301, 302, 307, etc.) readonly message?: string; // Flash message shown after redirect }> {} // Error responses export class BadRequest extends Data.TaggedClass('BadRequest')<{ readonly errors: Array; readonly message?: string; // Displays as error toast }> {} export class Forbidden extends Data.TaggedClass('Forbidden')<{ readonly errors: Array; readonly message?: string; }> {} export class ServerError extends Data.TaggedClass('ServerError')<{ readonly errors?: Array; readonly message?: string; }> {} // Form-specific errors for Superforms integration export class FormValidationError extends Data.TaggedClass('FormValidationError')<{ readonly form: SuperValidated>; }> {} export class CustomInputError> extends Data.TaggedClass( 'CustomInputError' )<{ readonly form: SuperValidated; readonly field: keyof T; // Field to attach error to readonly message: string; // Error message for the field }> {} // Usage in Effects Effect.gen(function* () { yield* Effect.fail(new BadRequest({ errors: ['Invalid input'], message: 'Please check your input and try again' })); yield* Effect.fail(new Forbidden({ errors: ['Insufficient permissions'], message: 'You do not have access to this resource' })); }); ``` -------------------------------- ### Validate form data with superValidateActionForm Source: https://context7.com/mateoroldos/sveltekit-effect-template/llms.txt Validates incoming POST request data against a Zod schema within an Effect action. Automatically triggers a FormValidationError if the data is invalid. ```typescript // src/routes/api/subscribe/+page.server.ts import { runAction, ActionArgs } from '$lib/server/run-action'; import { Effect } from 'effect'; import { OkAction, CustomInputError, ServerError } from '$lib/server/responses'; import { superValidateActionForm } from '$lib/server/super-validate.server'; import { z } from 'zod'; const subscribeSchema = z.object({ email: z.string().email('Please enter a valid email'), plan: z.enum(['basic', 'pro', 'enterprise']), agreeToTerms: z.boolean().refine(val => val === true, { message: 'You must agree to the terms' }) }); const subscribeAction = Effect.gen(function* () { // Validates request body against schema // Automatically fails with FormValidationError if invalid const form = yield* superValidateActionForm(subscribeSchema); const { email, plan } = form.data; // Check if email already subscribed const isSubscribed = yield* Effect.tryPromise({ try: () => checkSubscription(email), catch: () => new ServerError({ message: 'Service unavailable' }) }); if (isSubscribed) { yield* Effect.fail( new CustomInputError({ form, field: 'email', message: 'This email is already subscribed' }) ); } // Create subscription yield* Effect.tryPromise({ try: () => createSubscription(email, plan), catch: () => new ServerError({ message: 'Failed to create subscription' }) }); // Return success with flash message return new OkAction({ form, message: `Successfully subscribed to the ${plan} plan!` }); }); export const actions = { subscribe: runAction(subscribeAction) }; ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.