### Copy Example Environment File Source: https://github.com/litestar-org/litestar-fullstack-inertia/blob/main/docs/usage/installation.rst Copies the example environment file to .env, which is used for local configuration. Developers should edit this file to set crucial variables like SECRET_KEY, DATABASE_URI, and REDIS_URL. ```bash cp .env.local.example .env ``` -------------------------------- ### Async Test Example with Litestar Client Source: https://github.com/litestar-org/litestar-fullstack-inertia/blob/main/specs/guides/testing.md Demonstrates how to write an asynchronous test function using Litestar's `AsyncClient`. This example shows a typical POST request to create a user and asserts the response status code. ```python async def test_user_creation(client: AsyncClient) -> None: response = await client.post("/users", json={...}) assert response.status_code == 201 ``` -------------------------------- ### Litestar Vite Plugin Setup (After Migration) Source: https://github.com/litestar-org/litestar-fullstack-inertia/blob/main/specs/active/litestar-vite-upgrade/prd.md Demonstrates the simplified plugin setup after migrating to the integrated VitePlugin. The Inertia integration is now handled within the main VitePlugin, reducing the number of plugins to configure and simplifying the setup. ```python from app import config vite = config.vite # VitePlugin with Inertia integrated # Single plugin handles everything ``` -------------------------------- ### Manual Railway CLI Setup and Configuration Source: https://github.com/litestar-org/litestar-fullstack-inertia/blob/main/docs/deployment/railway.md This section outlines the manual steps to deploy the application using the Railway CLI. It includes installing the CLI, logging in, initializing a new Railway project, provisioning a PostgreSQL database, setting essential environment variables (including secret key and email configuration), linking the local project to the Railway project, deploying the application, and running database migrations. ```bash # Install Railway CLI npm install -g @railway/cli # Authenticate with Railway railway login # Create a new Railway project # From the project root directory railway init --name litestar-fullstack-demo # Provision a PostgreSQL database railway add --database postgres # Generate a secret key SECRET_KEY=$(openssl rand -base64 32) # Set essential environment variables railway variables set SECRET_KEY="${SECRET_KEY}" railway variables set LITESTAR_DEBUG=false railway variables set VITE_DEV_MODE=false # Configure email using Resend railway variables --set "EMAIL_ENABLED=true" railway variables --set "EMAIL_BACKEND=resend" railway variables --set "EMAIL_FROM=noreply@yourdomain.com" railway variables --set "RESEND_API_KEY=re_xxxxxxxxxxxx" # Link local project and deploy railway link railway up # Run database migrations railway run litestar database upgrade --no-prompt ``` -------------------------------- ### Install Dependencies (Bash) Source: https://github.com/litestar-org/litestar-fullstack-inertia/blob/main/GEMINI.md Installs all project dependencies using the make command. This is a prerequisite for running any other development commands. ```bash make install # Install all dependencies ``` -------------------------------- ### Litestar Vite Plugin Setup (Before Migration) Source: https://github.com/litestar-org/litestar-fullstack-inertia/blob/main/specs/active/litestar-vite-upgrade/prd.md Illustrates the plugin setup for Litestar Vite before the migration to an integrated approach. This required registering separate VitePlugin and InertiaPlugin instances, leading to more verbose configuration. ```python from litestar_vite import VitePlugin from litestar_vite.inertia import InertiaPlugin vite = VitePlugin(config=config.vite) inertia = InertiaPlugin(config=config.inertia) # Must register both in plugins list ``` -------------------------------- ### Deploy Database Migrations with App CLI Source: https://github.com/litestar-org/litestar-fullstack-inertia/blob/main/docs/usage/installation.rst Applies database migrations using the integrated CLI tool. This command ensures the database schema is up-to-date with the application's requirements. It assumes transactional DDL for PostgreSQL. ```bash app database upgrade ``` -------------------------------- ### Install Dependencies with Make Source: https://github.com/litestar-org/litestar-fullstack-inertia/blob/main/CLAUDE.md Installs all project dependencies using the make command. This is a common task for setting up the development environment. ```bash make install ``` -------------------------------- ### Environment Variables Example (.env) Source: https://context7.com/litestar-org/litestar-fullstack-inertia/llms.txt An example .env file demonstrating how to set environment variables for database connection, application secrets, debug mode, registration, MFA, email, and storage configurations. ```bash # .env example DATABASE_URL=postgresql+asyncpg://user:pass@localhost:5432/app SECRET_KEY=your-secret-key-here LITESTAR_DEBUG=true REGISTRATION_ENABLED=true MFA_ENABLED=true MUST_VERIFY_EMAIL=false # OAuth GITHUB_OAUTH2_CLIENT_ID=your-github-client-id GITHUB_OAUTH2_CLIENT_SECRET=your-github-client-secret GOOGLE_OAUTH2_CLIENT_ID=your-google-client-id GOOGLE_OAUTH2_CLIENT_SECRET=your-google-client-secret # Email EMAIL_BACKEND=resend EMAIL_FROM=noreply@yourapp.com RESEND_API_KEY=re_xxxxx # Storage STORAGE_BACKEND=s3 STORAGE_BUCKET=your-bucket AWS_ACCESS_KEY_ID=AKIA... AWS_SECRET_ACCESS_KEY=... AWS_REGION=us-east-1 ``` -------------------------------- ### Start Frontend Development Server (Bash) Source: https://github.com/litestar-org/litestar-fullstack-inertia/blob/main/GEMINI.md Starts the Vite development server for the frontend. This command uses bun as the package manager and provides hot-reloading for rapid development. ```bash # Frontend (use bun, not npm) bun run dev # Start Vite dev server ``` -------------------------------- ### Start Docker Infrastructure (Bash) Source: https://github.com/litestar-org/litestar-fullstack-inertia/blob/main/GEMINI.md Starts the necessary Docker containers, including PostgreSQL and Redis, for the application's infrastructure. This is required for local development and testing. ```bash make start-infra # Start Docker containers (PostgreSQL, Redis) ``` -------------------------------- ### Quick Start Deployment Script for Railway Source: https://github.com/litestar-org/litestar-fullstack-inertia/blob/main/docs/deployment/railway.md This bash script automates the deployment process to Railway. It navigates to the deployment directory, runs a setup script to create the project and provision a database, optionally configures email using Resend, and finally deploys the application. After deployment, it provides a command to open the Railway dashboard. ```bash # Navigate to the railway deployment directory cd tools/deploy/railway # Run the setup script (creates project, provisions database) ./setup.sh my-demo-app # Configure Resend for email (optional, interactive) ./env-setup.sh --email # Deploy the application ./deploy.sh # Open your Railway dashboard after deployment railway open ``` -------------------------------- ### Start Docker Infrastructure with Make Source: https://github.com/litestar-org/litestar-fullstack-inertia/blob/main/CLAUDE.md Starts the necessary Docker containers, including PostgreSQL and Redis. This command is used to set up the required services for development. ```bash make start-infra ``` -------------------------------- ### Database Management CLI Commands (Bash) Source: https://github.com/litestar-org/litestar-fullstack-inertia/blob/main/README.md Provides commands for managing database migrations and operations using the application's CLI. It includes examples for creating migrations and applying them. ```bash uv run app database --help # Examples: uv run app database make-migrations -m "add_user_field" # Create migration uv run app database upgrade # Apply migrations ``` -------------------------------- ### Essential Railway Setup Commands Source: https://github.com/litestar-org/litestar-fullstack-inertia/blob/main/docs/deployment/railway.md A collection of essential commands for setting up a new project on Railway, including authentication, project initialization, adding services, and linking to existing projects. ```bash railway login # Authenticate railway init # Create project railway add --database postgres # Add PostgreSQL railway link # Link to existing project ``` -------------------------------- ### Start Vite Development Server Source: https://github.com/litestar-org/litestar-fullstack-inertia/blob/main/CLAUDE.md Starts the Vite development server for the frontend. This command is used for local frontend development and hot-reloading. ```bash bun run dev ``` -------------------------------- ### User Registration API (Python & Bash) Source: https://context7.com/litestar-org/litestar-fullstack-inertia/llms.txt Creates a new user account with email and password. Requires AccountRegister schema for request body. On success, it redirects to /dashboard/ and emits a "user_created" event. Curl example shows how to register a new user. ```python # POST /register/ # Request body: AccountRegister schema from app.domain.accounts.schemas import AccountRegister register_data = AccountRegister( email="newuser@example.com", password="securepassword123", name="John Doe" ) # Response: InertiaRedirect to /dashboard/ on success # Emits "user_created" event with user_id ``` ```bash curl -X POST http://localhost:8000/register/ \ -H "Content-Type: application/json" \ -H "X-XSRF-TOKEN: " \ -d '{"email": "newuser@example.com", "password": "securepassword123", "name": "John Doe"}' ``` -------------------------------- ### Inertia Page Controller with Litestar Source: https://github.com/litestar-org/litestar-fullstack-inertia/blob/main/CLAUDE.md Demonstrates how to use the `component` kwarg in Litestar route decorators for Inertia page rendering. This approach simplifies page handling by directly associating routes with Inertia components. It includes examples for GET and POST requests, handling data retrieval and redirects. ```python from litestar import Controller, get, post from litestar_vite.inertia import InertiaRedirect class FeatureController(Controller): path = "/feature" @get(component="feature/list", path="/", name="feature.list") async def list(self, service: FeatureService) -> dict: items = await service.list() return {"items": items} @post(component="feature/create", path="/", name="feature.create") async def create(self, request: Request, data: CreateSchema, service: FeatureService) -> InertiaRedirect: await service.create(data.to_dict()) return InertiaRedirect(request, request.url_for("feature.list")) ``` -------------------------------- ### Check Installed Python Packages Source: https://github.com/litestar-org/litestar-fullstack-inertia/blob/main/docs/deployment/railway.md Lists all installed Python packages within the container's environment. This is helpful for diagnosing dependency-related issues. ```bash railway run pip list ``` -------------------------------- ### Confirm Multi-Factor Authentication (MFA) Setup Source: https://context7.com/litestar-org/litestar-fullstack-inertia/llms.txt Confirms the Multi-Factor Authentication setup by validating a provided TOTP code. Upon successful confirmation, it returns a list of backup codes for account recovery. The endpoint is POST /mfa/confirm and expects an MfaConfirm object with a 'code'. ```python # POST /mfa/confirm from app.domain.accounts.schemas import MfaConfirm, MfaBackupCodes confirm_data = MfaConfirm(code="123456") # Response: MfaBackupCodes(codes=["A1B2C3D4", "E5F6G7H8", ...]) # 8 backup codes returned for account recovery ``` ```bash curl -X POST http://localhost:8000/mfa/confirm \ -H "Content-Type: application/json" \ -H "X-XSRF-TOKEN: " \ -b "session=" \ -d '{"code": "123456"}' # Response: {"codes": ["A1B2C3D4", "E5F6G7H8", "I9J0K1L2", ...] } ``` -------------------------------- ### User Login API (Python & Bash) Source: https://context7.com/litestar-org/litestar-fullstack-inertia/llms.txt Authenticates a user with email and password. Handles MFA challenges and email verification. Requires AccountLogin schema for request body. Responses include redirects to dashboard, MFA challenge, or verification page. Curl example demonstrates POST request. ```python # POST /login/ # Request body: AccountLogin schema from app.domain.accounts.schemas import AccountLogin login_data = AccountLogin( username="user@example.com", password="securepassword123" ) # Response: InertiaRedirect to dashboard, MFA challenge, or verification page # On success: Session contains user_id, redirects to /dashboard/ # On MFA enabled: Redirects to /mfa-challenge/ # On unverified email: Redirects to /verify-email/ ``` ```bash # curl example curl -X POST http://localhost:8000/login/ \ -H "Content-Type: application/json" \ -H "X-XSRF-TOKEN: " \ -d '{"username": "user@example.com", "password": "securepassword123"}' ``` -------------------------------- ### Google OAuth Flow (Python & Bash) Source: https://context7.com/litestar-org/litestar-fullstack-inertia/llms.txt Initiates the Google OAuth flow for authentication. The POST request to /register/google/ redirects to Google's authorization page. The GET request to /o/google/complete/ handles the callback, creating or linking user accounts, and redirects to /dashboard/. ```python # POST /register/google/ # Redirects to Google authorization page # GET /o/google/complete/ # Callback handler - creates or links user account # Response: InertiaRedirect to /dashboard/ ``` ```bash # Initiate Google OAuth curl -X POST http://localhost:8000/register/google/ \ -H "X-XSRF-TOKEN: " ``` -------------------------------- ### MCP Context7 Library Docs Retrieval Source: https://github.com/litestar-org/litestar-fullstack-inertia/blob/main/CLAUDE.md Demonstrates how to use the `mcp__context7__get-library-docs` tool to fetch documentation for a specific library. This function allows developers to retrieve code examples or documentation topics for integrated libraries like Litestar, SQLAlchemy, React, and Inertia.js directly within their workflow. ```python mcp__context7__get-library-docs( context7CompatibleLibraryID="/litestar-org/litestar", topic="controllers", mode="code" ) ``` -------------------------------- ### GitHub OAuth Flow (Python & Bash) Source: https://context7.com/litestar-org/litestar-fullstack-inertia/llms.txt Initiates the GitHub OAuth flow for authentication. The POST request to /register/github/ redirects to GitHub's authorization page. The GET request to /o/github/complete/ handles the callback, creating or linking user accounts, and redirects to /dashboard/. ```python # POST /register/github/ # Redirects to GitHub authorization page # GET /o/github/complete/ # Callback handler - creates or links user account # Response: InertiaRedirect to /dashboard/ ``` ```bash # Initiate GitHub OAuth curl -X POST http://localhost:8000/register/github/ \ -H "X-XSRF-TOKEN: " # Response: External redirect to GitHub OAuth authorization URL ``` -------------------------------- ### Flash Message Example Source: https://github.com/litestar-org/litestar-fullstack-inertia/blob/main/specs/active/litestar-vite-upgrade/research/plan.md This Python snippet shows a basic usage of the FlashPlugin to display a success message after authentication. It demonstrates how flash messages are triggered. ```python flash(request, "Your account was successfully authenticated.", category="info") ``` -------------------------------- ### Enable Multi-Factor Authentication (MFA) Source: https://context7.com/litestar-org/litestar-fullstack-inertia/llms.txt Enables Multi-Factor Authentication by generating a Time-based One-Time Password (TOTP) secret and a QR code for setup. The endpoint is POST /mfa/enable. It returns an MfaSetup object containing the secret and a base64 encoded QR code. ```python # POST /mfa/enable from app.domain.accounts.schemas import MfaSetup # Response: MfaSetup with secret and base64 QR code # MfaSetup(secret="JBSWY3DPEHPK3PXP", qr_code="base64_png_data...") ``` ```bash curl -X POST http://localhost:8000/mfa/enable \ -H "X-XSRF-TOKEN: " \ -b "session=" # Response: {"secret": "JBSWY3DPEHPK3PXP", "qrCode": "iVBORw0KGgo..."} ``` -------------------------------- ### Generate Secret Key Source: https://github.com/litestar-org/litestar-fullstack-inertia/blob/main/docs/usage/installation.rst Generates a random base64 encoded secret key suitable for use in the .env file. This key is essential for security purposes, particularly for session management and data encryption. ```bash openssl rand -base64 32 ``` -------------------------------- ### AI Agent Slash Command: Implement Feature Source: https://github.com/litestar-org/litestar-fullstack-inertia/blob/main/AGENTS.md Starts a pattern-guided implementation process for a given feature slug using the `/implement [slug]` command. This command guides the AI in generating code based on established patterns. ```bash /implement [slug] # Pattern-guided implementation ``` -------------------------------- ### Backend Configuration Migration - Phase 1 Source: https://github.com/litestar-org/litestar-fullstack-inertia/blob/main/specs/active/litestar-vite-upgrade/prd.md Outlines the backend configuration changes required for Phase 1 of the migration. This involves updating imports, restructuring Vite configuration, creating a VitePlugin instance, and simplifying ViteSettings. ```python # app/config.py # Update imports # Restructure ViteConfig # Create VitePlugin instance # Remove InertiaConfig/TemplateConfig # app/server/plugins.py # Reference config.vite # Remove InertiaPlugin # app/server/core.py # Update plugin list # Remove template config assignment # app/lib/settings.py # Simplify ViteSettings ``` -------------------------------- ### CLI Commands for User Management Source: https://context7.com/litestar-org/litestar-fullstack-inertia/llms.txt These bash commands utilize the 'uv' tool to manage users via the command line. They cover creating users interactively or with specific options, promoting existing users to superuser, and creating default application roles. ```bash # Interactive mode uv run app users create-user # With options uv run app users create-user \ --email admin@example.com \ --name "Admin User" \ --password securepassword \ --superuser uv run app users promote-to-superuser --email user@example.com uv run app users create-roles ``` -------------------------------- ### Backup Database using pg_dump Source: https://github.com/litestar-org/litestar-fullstack-inertia/blob/main/docs/deployment/railway.md Demonstrates how to perform a manual backup of the PostgreSQL database using the `pg_dump` command. It requires the `DATABASE_URL` environment variable to be set, which can be retrieved using the Railway CLI. ```bash # Get connection details railway variables # Backup using pg_dump pg_dump $DATABASE_URL > backup.sql ``` -------------------------------- ### CLI Commands for Database Operations Source: https://context7.com/litestar-org/litestar-fullstack-inertia/llms.txt This section provides bash commands for managing database migrations and schema using the 'uv' tool. It includes applying migrations, creating new migration files, and checking the current migration status. ```bash # Apply all pending migrations uv run app database upgrade # Create a new migration uv run app database make-migrations -m "add_user_field" # Show migration status uv run app database current ``` -------------------------------- ### Get Team Details API (cURL) Source: https://context7.com/litestar-org/litestar-fullstack-inertia/llms.txt Retrieves detailed information about a specific team using cURL. This command sends a GET request to the /teams/{team_slug}/ endpoint and requires a session cookie for authentication. ```bash curl -X GET http://localhost:8000/teams/engineering-team/ \ -b "session=" ``` -------------------------------- ### Get User Profile Source: https://context7.com/litestar-org/litestar-fullstack-inertia/llms.txt Retrieves the current authenticated user's profile information. The endpoint is GET /profile/. It returns a User schema containing details such as ID, email, name, and MFA status. ```python # GET /profile/ from app.domain.accounts.schemas import User # Response: User schema with all user details # User(id=UUID, email="user@example.com", name="John Doe", # is_superuser=False, is_active=True, is_verified=True, # has_password=True, is_two_factor_enabled=False, # teams=[...], roles=[...], oauth_accounts=[...], avatar_url="...") ``` ```bash curl -X GET http://localhost:8000/profile/ \ -b "session=" ``` -------------------------------- ### Get Team Invitations API (cURL) Source: https://context7.com/litestar-org/litestar-fullstack-inertia/llms.txt Retrieves a list of pending team invitations using cURL. This command sends a GET request to the /teams/{team_slug}/invitations/ endpoint and requires a session cookie for authentication. ```bash curl -X GET http://localhost:8000/teams/engineering-team/invitations/ \ -b "session=" ``` -------------------------------- ### Create User (Admin) via Python and cURL Source: https://context7.com/litestar-org/litestar-fullstack-inertia/llms.txt Creates a new user account with specified details. The Python code shows the data structure for user creation using Pydantic, and the cURL command illustrates the corresponding HTTP POST request. Requires CSRF token and session cookie. ```python # POST /admin/users/ from app.domain.admin.schemas import AdminUserCreate user_data = AdminUserCreate( email="newuser@example.com", password="temppassword123", name="New User", is_superuser=False, is_active=True, is_verified=True ) # Response: InertiaRedirect to user detail page # Logs USER_CREATED audit event ``` ```bash curl -X POST http://localhost:8000/admin/users/ \ -H "Content-Type: application/json" \ -H "X-XSRF-TOKEN: " \ -b "session=" \ -d '{"email": "newuser@example.com", "password": "temppassword123", "name": "New User", "isActive": true, "isVerified": true}' ``` -------------------------------- ### Package JSON Scripts and Dependencies Source: https://github.com/litestar-org/litestar-fullstack-inertia/blob/main/specs/active/litestar-vite-upgrade/prd.md Defines the scripts for development, building, and previewing the application, as well as managing project dependencies. It includes commands for Vite, TypeScript compilation, and OpenAPI type generation. Key dependencies like Zod and development dependencies like Litestar Vite plugin are listed. ```json { "scripts": { "dev": "vite", "build": "vite build && tsc -b --noEmit", "preview": "vite preview", "generate-types": "openapi-ts --config openapi-ts.config.ts" }, "dependencies": { "zod": "^4.0.0" }, "devDependencies": { "litestar-vite-plugin": "latest", "@hey-api/openapi-ts": "^0.88.0", "@tailwindcss/vite": "^4.1.17" } } ``` -------------------------------- ### Litestar Controller Pattern for HTTP Requests Source: https://github.com/litestar-org/litestar-fullstack-inertia/blob/main/specs/guides/architecture.md Handles HTTP requests and returns Inertia responses. It defines routes for GET and POST requests, specifying the Inertia component to render and handling data retrieval or form submission. Dependencies include Litestar's Controller, get, post, and InertiaRedirect. ```python from litestar import Controller, get, post from litestar_vite.inertia import InertiaRedirect class FeatureController(Controller): path = "/feature" @get(component="feature/index", name="feature.index") async def index(self, service: FeatureService) -> dict: """Inertia page - returns props as dict.""" items = await service.list() return {"items": items} @post(path="/", name="feature.create") async def create( self, request: Request, data: CreateSchema, service: FeatureService, ) -> InertiaRedirect: """Handle form submission - redirect on success.""" await service.create(data.to_dict()) return InertiaRedirect(request, request.url_for("feature.index")) ``` -------------------------------- ### Add Team Member via Python and cURL Source: https://context7.com/litestar-org/litestar-fullstack-inertia/llms.txt Adds an existing user to a team or sends an invitation to a new user. The Python example uses Pydantic schemas for data validation, while the cURL example demonstrates the HTTP request with JSON payload. Requires CSRF token and session cookie. ```python # POST /api/teams/{team_slug}/members/add from app.domain.teams.schemas import TeamMemberModify from app.lib.schema import Message member_data = TeamMemberModify(user_name="existing@example.com") # Response: Message with result # If user exists: Message(message="existing@example.com is already registered and was added to Engineering Team.") # If user doesn't exist: Message(message="new@example.com was invited to sign up and join Engineering Team.") ``` ```bash curl -X POST http://localhost:8000/api/teams/engineering-team/members/add \ -H "Content-Type: application/json" \ -H "X-XSRF-TOKEN: " \ -b "session=" \ -d '{"userName": "newmember@example.com"}' ``` -------------------------------- ### Frontend Restructuring - Phase 3 Source: https://github.com/litestar-org/litestar-fullstack-inertia/blob/main/specs/active/litestar-vite-upgrade/prd.md Describes the frontend file structure changes for Phase 3 of the migration. This involves creating a new generated directory for API-related files, updating Vite configuration, and creating the OpenAPI TypeScript configuration file. ```shell # src/lib/generated/ (create) # routes.ts (auto-generated) # routes.json (auto-generated) # openapi.json (auto-generated) # api/ (SDK output) vite.config.ts (update) package.json (update) openapi-ts.config.ts (create) ``` -------------------------------- ### Configure Vite and Inertia Plugins in Python Source: https://github.com/litestar-org/litestar-fullstack-inertia/blob/main/specs/active/litestar-vite-upgrade/prd.md This snippet shows the 'Before' state of configuring Vite and Inertia plugins using Litestar. It imports necessary components and defines configurations for Vite and Inertia separately. ```python from litestar.contrib.jinja import JinjaTemplateEngine from litestar.template import TemplateConfig from litestar_vite import ViteConfig from litestar_vite.inertia import InertiaConfig vite = ViteConfig( bundle_dir=settings.vite.BUNDLE_DIR, resource_dir=settings.vite.RESOURCE_DIR, use_server_lifespan=settings.vite.USE_SERVER_LIFESPAN, dev_mode=settings.vite.DEV_MODE, hot_reload=settings.vite.HOT_RELOAD, is_react=settings.vite.ENABLE_REACT_HELPERS, port=settings.vite.PORT, host=settings.vite.HOST, ) inertia = InertiaConfig( root_template="site/index.html.j2", redirect_unauthorized_to="/login", extra_static_page_props={...}, extra_session_page_props={"currentTeam"}, ) templates = TemplateConfig(engine=JinjaTemplateEngine(directory=settings.vite.TEMPLATE_DIR)) ``` -------------------------------- ### Run Litestar Application with Granian Source: https://github.com/litestar-org/litestar-fullstack-inertia/blob/main/CLAUDE.md Starts the Litestar application server using Granian. This command is used to run the backend in a production-like environment. ```bash uv run app run ``` -------------------------------- ### Frontend Structure: Layouts and Entry Point Source: https://github.com/litestar-org/litestar-fullstack-inertia/blob/main/AGENTS.md Details the 'layouts' directory for application layout components and the 'main.tsx' file as the frontend entry point. ```typescript ├── layouts/ │ ├── app-layout.tsx │ └── guest-layout.tsx └── main.tsx # Entry point ``` -------------------------------- ### Litestar Vite Configuration Before Upgrade Source: https://github.com/litestar-org/litestar-fullstack-inertia/blob/main/specs/active/litestar-vite-upgrade/RECOVERY.md This snippet shows the previous configuration for Vite and Inertia in a Litestar application, utilizing separate configurations and Jinja2 for templates. ```python from litestar_vite import ViteConfig from litestar_vite.inertia import InertiaConfig vite = ViteConfig(bundle_dir=..., resource_dir=..., ...) inertia = InertiaConfig(root_template="site/index.html.j2", ...) templates = TemplateConfig(engine=JinjaTemplateEngine(...)) ``` -------------------------------- ### Python Timezone-Aware Datetime Source: https://github.com/litestar-org/litestar-fullstack-inertia/blob/main/CLAUDE.md Illustrates the correct way to get the current time in a timezone-aware manner using UTC. This is crucial for consistent date and time handling. ```python from datetime import datetime, timezone current_time_utc = datetime.now(timezone.utc) print(current_time_utc) ``` -------------------------------- ### Python UserService Operations Source: https://context7.com/litestar-org/litestar-fullstack-inertia/llms.txt This Python code demonstrates various operations using the UserService, including authentication, user creation, password updates (with and without current password verification), and MFA verification. It assumes the 'alchemy' configuration is available. ```python from app.domain.accounts.services import UserService from app.config import alchemy # Authenticate user async with UserService.new(config=alchemy) as users_service: user = await users_service.authenticate("user@example.com", "password123") # Create user async with UserService.new(config=alchemy) as users_service: user = await users_service.create({ "email": "new@example.com", "password": "securepassword", "name": "New User" }) # Update password (with current password verification) async with UserService.new(config=alchemy) as users_service: await users_service.update_password( data={"current_password": "old", "new_password": "new"}, db_obj=user ) # Reset password (without current password - for email token flows) async with UserService.new(config=alchemy) as users_service: await users_service.reset_password("newpassword", db_obj=user) # Verify MFA async with UserService.new(config=alchemy) as users_service: result = await users_service.verify_mfa( email="user@example.com", code="123456", # TOTP code # or recovery_code="A1B2C3D4" ) if result.verified: # MFA verified successfully pass if result.used_backup_code: # Warn user about remaining backup codes print(f"Remaining codes: {result.remaining_backup_codes}") ``` -------------------------------- ### Create Database Migrations (Bash) Source: https://github.com/litestar-org/litestar-fullstack-inertia/blob/main/GEMINI.md Creates a new database migration file. This command is used when schema changes are introduced and need to be tracked. ```bash uv run app database make-migrations # Create migration ``` -------------------------------- ### Template Migration - Phase 2 Source: https://github.com/litestar-org/litestar-fullstack-inertia/blob/main/specs/active/litestar-vite-upgrade/prd.md Details the template file changes for Phase 2 of the migration. This includes creating a new index.html file for Inertia and deleting the old Jinja2 template. ```shell # resources/ # index.html (create) # app/domain/web/templates/site/ # index.html.j2 (delete) ``` -------------------------------- ### Current Litestar Vite and Inertia Plugin Setup Source: https://github.com/litestar-org/litestar-fullstack-inertia/blob/main/specs/active/litestar-vite-upgrade/research/analysis.md Shows the current implementation of Vite and Inertia plugins in the litestar-fullstack-inertia project, where both are initialized as separate plugins. The upgrade aims to unify this. ```python from litestar_vite import VitePlugin from litestar_vite.inertia import InertiaPlugin vite = VitePlugin(config=config.vite) inertia = InertiaPlugin(config=config.inertia) ``` -------------------------------- ### React Functional Component with TypeScript Source: https://github.com/litestar-org/litestar-fullstack-inertia/blob/main/CLAUDE.md Example of a functional React component written in TypeScript, utilizing interfaces for props. This follows the project's standard for component definition. ```typescript import React from 'react'; interface GreetingProps { name: string; } const Greeting: React.FC = ({ name }) => { return (

Hello, {name}!

); }; export default Greeting; ``` -------------------------------- ### Run Type Checking with Make Source: https://github.com/litestar-org/litestar-fullstack-inertia/blob/main/CLAUDE.md Runs static type checking using mypy and pyright. This helps catch type-related errors early in the development cycle. ```bash make type-check ``` -------------------------------- ### Python Application Configuration Access Source: https://context7.com/litestar-org/litestar-fullstack-inertia/llms.txt This Python snippet shows how to access application settings, which are configured via environment variables or a .env file. It demonstrates retrieving database connection URL and pool size from the settings object. ```python # app/lib/settings.py from app.lib.settings import get_settings settings = get_settings() # Database configuration settings.db.URL # DATABASE_URL (default: sqlite+aiosqlite:///db.sqlite3) settings.db.POOL_SIZE # DATABASE_POOL_SIZE (default: 5) ``` -------------------------------- ### List Teams API (cURL) Source: https://context7.com/litestar-org/litestar-fullstack-inertia/llms.txt Lists all teams accessible by the current user using cURL. This command sends a GET request to the /teams/ endpoint and requires a session cookie for authentication. ```bash curl -X GET http://localhost:8000/teams/ \ -b "session=" ``` -------------------------------- ### Run Tests and Linting Source: https://github.com/litestar-org/litestar-fullstack-inertia/blob/main/specs/active/litestar-vite-upgrade/prd.md Commands to execute tests, linting, and biome checks for the project. These are crucial for maintaining code quality and ensuring functionality. ```shell make test make lint npx biome check resources/ ``` -------------------------------- ### Get Team Details API Source: https://context7.com/litestar-org/litestar-fullstack-inertia/llms.txt Retrieves detailed information about a specific team, including its members, pending invitations, and user permissions. This endpoint requires the team's slug and a session cookie for authentication. ```python # GET /teams/{team_slug}/ from app.domain.teams.schemas import TeamDetailPage # Response: TeamDetailPage with team, members, pending_invitations, and permissions # TeamDetailPage( # team=TeamDetail(id=UUID, name="Engineering Team", slug="engineering-team", ...), # members=[TeamPageMember(id=UUID, user_id=UUID, email="user@example.com", role="owner", name="John", avatar_url="...")], # pending_invitations=[TeamInvitationItem(id=UUID, email="new@example.com", role="member", ...)], # permissions=TeamPermissions(can_add_team_members=True, can_delete_team=True, ...) # ) ``` -------------------------------- ### Add generate-types script to package.json Source: https://github.com/litestar-org/litestar-fullstack-inertia/blob/main/specs/active/litestar-vite-upgrade/tasks.md This script is used to generate API types and SDKs from an OpenAPI specification. It relies on the 'openapi-ts' package and a configuration file named 'openapi-ts.config.ts'. Ensure 'openapi-ts' is installed as a dev dependency. ```json { "name": "your-project", "version": "0.1.0", "scripts": { "generate-types": "openapi-ts --config openapi-ts.config.ts" }, "devDependencies": { "@hey-api/openapi-ts": "^x.y.z", "litestar-vite-plugin": "^a.b.c" }, "dependencies": { "zod": "^p.q.r" } } ``` -------------------------------- ### Storage Settings Configuration Source: https://context7.com/litestar-org/litestar-fullstack-inertia/llms.txt Configures the file storage backend (local, s3, gcs, azure), the upload directory for local storage, and the bucket name for cloud storage. ```python settings.storage.BACKEND # STORAGE_BACKEND: 'local', 's3', 'gcs', or 'azure' settings.storage.UPLOAD_DIR # STORAGE_UPLOAD_DIR (default: uploads) settings.storage.BUCKET # STORAGE_BUCKET (for cloud storage) ``` -------------------------------- ### Build Frontend Production Assets (Bash) Source: https://github.com/litestar-org/litestar-fullstack-inertia/blob/main/GEMINI.md Builds the production-ready assets for the frontend using Vite. This command optimizes the code for deployment. ```bash bun run build # Build production assets ``` -------------------------------- ### Inertia Page Controller with Litestar Source: https://github.com/litestar-org/litestar-fullstack-inertia/blob/main/GEMINI.md Defines Litestar controllers for handling Inertia.js pages. Uses the `component` kwarg in route decorators to specify the Inertia component and path. Supports GET and POST requests, returning data or InertiaRedirect. ```python from litestar import Controller, get, post from litestar_vite.inertia import InertiaRedirect from litestar.request import Request from app.domain.feature.schemas import CreateSchema from app.domain.feature.services import FeatureService class FeatureController(Controller): path = "/feature" @get(component="feature/list", path="/", name="feature.list") async def list(self, service: FeatureService) -> dict: items = await service.list() return {"items": items} @post(component="feature/create", path="/", name="feature.create") async def create(self, request: Request, data: CreateSchema, service: FeatureService) -> InertiaRedirect: await service.create(data.to_dict()) return InertiaRedirect(request, request.url_for("feature.list")) ``` -------------------------------- ### Refactor Vite Plugin Configuration in Python Source: https://github.com/litestar-org/litestar-fullstack-inertia/blob/main/specs/active/litestar-vite-upgrade/prd.md This snippet demonstrates the 'After' state of configuring the Vite plugin in Litestar, integrating Inertia configuration directly within ViteConfig. It utilizes new classes like VitePlugin, PathConfig, RuntimeConfig, and TypeGenConfig for a more streamlined setup. The root template is simplified to 'index.html'. ```python from pathlib import Path from litestar_vite import ( VitePlugin, ViteConfig, PathConfig, RuntimeConfig, TypeGenConfig, InertiaConfig, ) from app.lib.settings import get_settings, BASE_DIR settings = get_settings() vite = VitePlugin( config=ViteConfig( dev_mode=settings.vite.DEV_MODE, paths=PathConfig( root=BASE_DIR.parent, resource_dir=Path("resources"), bundle_dir=Path("public"), asset_url=settings.vite.ASSET_URL, ), runtime=RuntimeConfig( host=settings.vite.HOST, port=settings.vite.PORT, is_react=True, ), inertia=InertiaConfig( root_template="index.html", redirect_unauthorized_to="/login", extra_static_page_props={ "canResetPassword": True, "hasTermsAndPrivacyPolicyFeature": True, "mustVerifyEmail": True, }, extra_session_page_props={"currentTeam"}, ), types=TypeGenConfig( output=BASE_DIR.parent / "src" / "lib" / "generated", generate_zod=True, generate_sdk=True, generate_routes=True, ), ) ) ``` -------------------------------- ### Simplify Vite Settings in Python Source: https://github.com/litestar-org/litestar-fullstack-inertia/blob/main/specs/active/litestar-vite-upgrade/tasks.md This Python code snippet demonstrates simplifying the ViteSettings class by removing deprecated fields related to hot reloading, server lifespan, React helpers, and directory configurations. It retains only essential settings like development mode, host, port, and asset URL. ```python # Remove deprecated ViteSettings fields: # HOT_RELOAD # USE_SERVER_LIFESPAN # ENABLE_REACT_HELPERS # BUNDLE_DIR # RESOURCE_DIR # TEMPLATE_DIR # Keep essential fields: # DEV_MODE # HOST # PORT # ASSET_URL ``` -------------------------------- ### Python Future Annotations Import Source: https://github.com/litestar-org/litestar-fullstack-inertia/blob/main/CLAUDE.md Shows the necessary import for enabling future annotations in Python files. This allows for cleaner type hint syntax. ```python from __future__ import annotations # Rest of your Python code ``` -------------------------------- ### Configure SAQ with PostgreSQL Broker Source: https://github.com/litestar-org/litestar-fullstack-inertia/blob/main/specs/active/litestar-vite-upgrade/research/plan.md Sets up the SAQ (Simple Asynchronous Queue) configuration to use PostgreSQL as the broker for background tasks. This includes defining queue configurations, DSN for the database connection, and options for managing task queue tables. ```python from litestar.contrib.saq import SAQConfig, QueueConfig saq = SAQConfig( queue_configs=[ QueueConfig( name="background-tasks", dsn=settings.db.URL.replace("postgresql+psycopg", "postgresql"), broker_options={ "stats_table": "task_queue_stats", "jobs_table": "task_queue", "versions_table": "task_queue_ddl_version", }, ) ], ) ``` -------------------------------- ### Litestar Vite Configuration After Upgrade Source: https://github.com/litestar-org/litestar-fullstack-inertia/blob/main/specs/active/litestar-vite-upgrade/RECOVERY.md This snippet illustrates the updated configuration for Vite and Inertia using the new Litestar-Vite structure. It incorporates a single VitePlugin with nested configurations for paths, runtime, types, and Inertia, supporting hybrid mode and type generation. ```python from litestar_vite import VitePlugin, ViteConfig, PathConfig, RuntimeConfig, TypeGenConfig, InertiaConfig vite = VitePlugin( config=ViteConfig( dev_mode=..., paths=PathConfig(...), runtime=RuntimeConfig(...), inertia=InertiaConfig(root_template="index.html", ...), types=TypeGenConfig(output=Path("src/lib/generated"), ...), ) ) ``` -------------------------------- ### Forgot Password Request API (Python & Bash) Source: https://context7.com/litestar-org/litestar-fullstack-inertia/llms.txt Requests a password reset email for a given email address. Requires ForgotPasswordRequest schema. Always returns success to prevent email enumeration and emits a "password_reset_requested" event. Curl example shows the POST request. ```python # POST /forgot-password/ from app.domain.accounts.schemas import ForgotPasswordRequest forgot_data = ForgotPasswordRequest(email="user@example.com") # Response: EmailSent(email_sent=True) # Always returns success to prevent email enumeration # Emits "password_reset_requested" event ``` ```bash curl -X POST http://localhost:8000/forgot-password/ \ -H "Content-Type: application/json" \ -H "X-XSRF-TOKEN: " \ -d '{"email": "user@example.com"}' # Response: {"emailSent": true} ``` -------------------------------- ### Update Vite Plugin Initialization in Python Source: https://github.com/litestar-org/litestar-fullstack-inertia/blob/main/specs/active/litestar-vite-upgrade/prd.md This snippet shows the 'After' state of initializing the Vite plugin in Litestar. The VitePlugin is now created in config.py with Inertia integrated, and the separate InertiaPlugin initialization is removed. ```python from app import config # VitePlugin is now created in config.py with Inertia integrated vite = config.vite # Remove: inertia = InertiaPlugin(config=config.inertia) ```