diff --git a/opensaas-sh/blog/src/assets/ai/llm-full-cursor.webp b/opensaas-sh/blog/src/assets/ai/llm-full-cursor.webp new file mode 100644 index 00000000..36db1dea Binary files /dev/null and b/opensaas-sh/blog/src/assets/ai/llm-full-cursor.webp differ diff --git a/opensaas-sh/blog/src/assets/ai/llm-txt-chat.webp b/opensaas-sh/blog/src/assets/ai/llm-txt-chat.webp new file mode 100644 index 00000000..74a248d8 Binary files /dev/null and b/opensaas-sh/blog/src/assets/ai/llm-txt-chat.webp differ diff --git a/opensaas-sh/blog/src/assets/ai/vibe-boi.png b/opensaas-sh/blog/src/assets/ai/vibe-boi.png new file mode 100644 index 00000000..421e6b4f Binary files /dev/null and b/opensaas-sh/blog/src/assets/ai/vibe-boi.png differ diff --git a/opensaas-sh/blog/src/content/docs/guides/vibe-coding.mdx b/opensaas-sh/blog/src/content/docs/guides/vibe-coding.mdx new file mode 100644 index 00000000..62ebe5a4 --- /dev/null +++ b/opensaas-sh/blog/src/content/docs/guides/vibe-coding.mdx @@ -0,0 +1,49 @@ +--- +title: Vibe Coding with Open SaaS +banner: + content: | + Have an Open SaaS app in production? We'll send you some swag! 👕 +--- +import { Image } from 'astro:assets'; +import llmsFullCursor from '@assets/ai/llm-full-cursor.webp'; +import llmsTextChat from '@assets/ai/llm-txt-chat.webp'; +import vibeBoi from '@assets/ai/vibe-boi.png'; + +vibe boi + +If you're looking to use AI to help build (or "vibe code") your SaaS app, this guide is for you. + +## Coding with AI, Open SaaS, & Wasp + +Wasp is particularly well suited to coding with AI due to its central config file which gives LLMs context about the entire full-stack app, and its ability to manage boilerplate code so AI doesn't have to. + +Regardless, there are still some shortcomings to using AI to code with Wasp, as well as a learning curve to using it effectively. + +Luckily, we did the work for you and put together a bunch of resources to help you use Wasp & Open SaaS with AI as effectively as possible. + +### AI Resources in the Template + +The template comes with: +- A full set of rules files, `app/.cursor/rules`, to be used with Cursor or adapted to your coding tool of choice (Windsurf, Claude Code, etc.). +- A set of example prompts, `app/.cursor/example-prompts.md`, to help you get started. + +### LLM-Friendly Documentation + +We've also created a bunch of LLM-friendly documentation: +- [Open SaaS Docs - LLMs.txt](https://docs.opensaas.sh/llms.txt) - Links to the raw text docs. +- [Open SaaS Docs - LLMs-full.txt](https://docs.opensaas.sh/llms-full.txt) - Complete docs as one text file. +- [Wasp Docs - LLMs.txt](https://wasp.sh/llms.txt) - Links to the raw text docs. +- [Wasp Docs - LLMs-full.txt](https://wasp.sh/llms-full.txt) - Complete docs as one text file. + +Add these to your AI-assisted IDE settings so you can easily reference them in your chat sessions with the LLM. +**In most cases, you'll want to pass the `llms-full.txt` url to the LLM and ask it to help you with a specific task.** + +add llms-full.txt to settings + +add llms.txt to settings + +### More AI-assisted Coding Learning Resources + +Here's a list of articles and tutorials we've made: +- [3hr YouTube tutorial: Vibe Coding a Personal Finance App w/ Wasp & Cursor](https://www.youtube.com/watch?v=WYzEROo7reY) +- [Article: A Structured Workflow for "Vibe Coding" Full-Stack Apps](https://dev.to/wasp/a-structured-workflow-for-vibe-coding-full-stack-apps-352l) \ No newline at end of file diff --git a/template/app/.cursor/example-prompts.md b/template/app/.cursor/example-prompts.md new file mode 100644 index 00000000..923d9e22 --- /dev/null +++ b/template/app/.cursor/example-prompts.md @@ -0,0 +1,14 @@ +## Example Prompts + +### PRD / initial prompt + +I want to create a `` app with the current SaaS boilerplate template project I'm in which uses Wasp and already has payment processing, AWS S3 file upload, a landing page, an admin dashboard, and authentication already setup. Leveraging Wasp's full-stack features (such as Auth), let's build the app based on the following spec: + - `` + - `` + - `` + +With this in mind, I want you to first evaluate the project template and think about a few possible PRD approaches before landing on the best one. Provide reasoning why this would be the best approach. Remember we're using Wasp, a full-stack framework with batteries included, that can do some of the heavy lifting for us, and we want to use a modified vertical slice implementation approach for LLM-assisted coding so we can start with basic implementations of features first, and add on complexity from there. + +### Plan prompt + +From this PRD, create an actionable, step-by-step plan that we can use as a guide for LLM-assisted coding. Remember that this project is a SaaS boilerplate template with many features already implemented. Each feature is organized into its own folder (e.g. `src/payment`) with its client and server code split into subfolders and files. Before you create the plan, think about a few different plan styles that would be suitable for this project and the implmentation style before selecting the best one. Give your reasoning for why you think we should use this plan style. Remember that we will constantly refer to this plan to guide our coding implementation so it should be well structured, concise, and actionable, while still providing enough information to guide the LLM. diff --git a/template/app/.cursor/rules/advanced-troubleshooting.mdc b/template/app/.cursor/rules/advanced-troubleshooting.mdc new file mode 100644 index 00000000..35529a9a --- /dev/null +++ b/template/app/.cursor/rules/advanced-troubleshooting.mdc @@ -0,0 +1,109 @@ +--- +description: +globs: +alwaysApply: true +--- +# 6. Advanced Features & Troubleshooting + +This document covers advanced Wasp capabilities like Jobs, API Routes, and Middleware, along with performance optimization tips and common troubleshooting steps. + +## Advanced Features ( [main.wasp](mdc:main.wasp) ) + +These features are configured in [main.wasp](mdc:main.wasp). + +### Jobs and Workers + +- Wasp supports background jobs, useful for tasks like sending emails, processing data, or scheduled operations. +- Jobs require a job executor like PgBoss (which requires PostgreSQL, see [database-operations.mdc](mdc:template/app/.cursor/rules/database-operations.mdc)). +- Example Job definition in [main.wasp](mdc:main.wasp): + ```wasp + job emailSender { + executor: PgBoss, // Requires PostgreSQL + // Define the function that performs the job + perform: { + fn: import { sendEmail } from "@src/server/jobs/emailSender.js" + }, + // Grant access to necessary entities + entities: [User, EmailQueue] + } + ``` +- Jobs can be scheduled or triggered programmatically from Wasp actions or other jobs. +- See the Wasp Recurring Jobs Docs for more info [wasp-overview.mdc](mdc:template/app/.cursor/rules/wasp-overview.mdc) + +### Custom HTTP API Endpoints + +- Define custom server API endpoints, often used for external integrations (webhooks, third-party services) where Wasp Operations are not suitable. +- Example API route definition in [main.wasp](mdc:main.wasp): + ```wasp + api stripeWebhook { + // Implementation function in server code + fn: import { handleStripeWebhook } from "@src/server/apis/stripe.js", + // Define the HTTP method and path + httpRoute: (POST, "/webhooks/stripe"), + // Optional: Grant entity access + entities: [User, Payment], + // Optional: Apply middleware config function + // middlewareConfigFn: import { apiMiddleware } from "@src/apis" + // Optional: If auth is enabled, this will default to true and provide a context.user + // object. If you do not wish to attempt to parse the JWT in the Authorization Header + // you should set this to false. + // auth: false + } + ``` +- See the Wasp Custom HTTP API Endpoints docs for more info [wasp-overview.mdc](mdc:template/app/.cursor/rules/wasp-overview.mdc) + +### Middleware + +- Wasp supports custom middleware functions that can run before API route handlers or Page components. +- Useful for logging, custom checks, request transformation, etc. +- Example Middleware definition in [main.wasp](mdc:main.wasp): + ```wasp + // Customize global middleware + app todoApp { + // ... + server: { + middlewareConfigFn: import { serverMiddlewareFn } from "@src/serverSetup" + }, + } + ``` +- See the Wasp Middleware Docs for more info [wasp-overview.mdc](mdc:template/app/.cursor/rules/wasp-overview.mdc) + +## Performance Optimization + +- **Operation Dependencies:** Use specific entity dependencies (`entities: [Task]`) in your Wasp operations ([main.wasp](mdc:main.wasp)) to ensure queries are automatically refetched only when relevant data changes. +- **Pagination:** For queries returning large lists of data, implement pagination logic in your server operation and corresponding UI controls on the client. +- **React Optimization:** + - Use `React.memo` for components that re-render often with the same props. + - Use `useMemo` to memoize expensive calculations within components. + - Use `useCallback` to memoize functions passed down as props to child components (especially event handlers). +- **Optimistic UI Updates (Actions):** + - For actions where perceived speed is critical (e.g., deleting an item, marking as complete), consider using Wasp's `useAction` hook (from `wasp/client/operations`) with `optimisticUpdates`. + - This updates the client-side cache (affecting relevant `useQuery` results) *before* the action completes on the server, providing instant feedback. + - **Use Sparingly:** Only implement optimistic updates where the action is highly likely to succeed and the instant feedback significantly improves UX. Remember to handle potential server-side failures gracefully (Wasp helps revert optimistic updates on error). + - See the Wasp Actions docs for more info [wasp-overview.mdc](mdc:template/app/.cursor/rules/wasp-overview.mdc) + +## Troubleshooting + +- **Wasp Type/Import Errors:** If you encounter TypeScript errors related to missing Wasp imports (e.g., from `wasp/client/operations`, `wasp/entities`, `wasp/server`) or unexpected type mismatches after modifying [main.wasp](mdc:main.wasp) or [schema.prisma](mdc:schema.prisma) , **prompt the user to restart the Wasp development server** (`wasp start`) before further debugging. Wasp needs to regenerate code based on these changes. +- **Operations Not Working:** + - Check that all required `entities` are listed in the operation's definition in [main.wasp](mdc:main.wasp). + - Verify the import path (`fn: import { ... } from "@src/..."`) in [main.wasp](mdc:main.wasp) is correct. + - Check for runtime errors in the Wasp server console where `wasp start` is running. + - Ensure client-side calls match the expected arguments and types. +- **Auth Not Working:** + - Verify the `auth` configuration in [main.wasp](mdc:main.wasp) (correct `userEntity`, `methods`, `onAuthFailedRedirectTo`). + - Ensure `userEntity` in [main.wasp](mdc:main.wasp) matches the actual `User` model name in [schema.prisma](mdc:schema.prisma). + - Check Wasp server logs for auth-related errors. + - If using social auth, confirm environment variables (e.g., `GOOGLE_CLIENT_ID`) are correctly set (e.g., in a `.env.server` file) and loaded by Wasp. +- **Database Issues:** + - Ensure your [schema.prisma](mdc:schema.prisma) syntax is correct. + - Run `wasp db migrate-dev "Migration description"` after schema changes to apply them. + - If using PostgreSQL, ensure the database server is running. + - Check the `.env.server` file for the correct `DATABASE_URL`. +- **Build/Runtime Errors:** + - Check import paths carefully (Wasp vs. relative vs. `@src/` rules, see [project-conventions.mdc](mdc:template/app/.cursor/rules/project-conventions.mdc)). + - Ensure all dependencies are installed (`npm install`). + - Check the Wasp server console and the browser's developer console for specific error messages. + + ### Referencing Wasp Documentation + - Search for and reference applicable LLM-optimized docs, available in [wasp-overview.mdc](mdc:template/app/.cursor/rules/wasp-overview.mdc) diff --git a/template/app/.cursor/rules/authentication.mdc b/template/app/.cursor/rules/authentication.mdc new file mode 100644 index 00000000..cf8e7add --- /dev/null +++ b/template/app/.cursor/rules/authentication.mdc @@ -0,0 +1,167 @@ +--- +description: +globs: +alwaysApply: true +--- +# 4. Authentication + +This document gives a quick rundown on how authentication is configured and used within the Wasp application. + +See the Wasp Auth docs for available methods and complete guides [wasp-overview.mdc](mdc:template/app/.cursor/rules/wasp-overview.mdc) + +## Wasp Auth Setup + +- Wasp provides built-in authentication with minimal configuration via the Wasp config file. +- Wasp generates all necessary auth routes, middleware, and UI components based on the configuration. +- Example auth configuration in [main.wasp](mdc:main.wasp): + ```wasp + app myApp { + // ... other config + auth: { + // Links Wasp auth to your User model in @schema.prisma + userEntity: User, + methods: { + // Enable username/password login + usernameAndPassword: {}, + // Enable Google OAuth login + // Requires setting GOOGLE_CLIENT_ID and GOOGLE_CLIENT_SECRET env vars + google: {}, + // Enable email/password login with verification + email: { + // Set up an email sender (Dummy prints to console) + // See https://wasp-lang.com/docs/auth/email-auth#email-sending + fromField: { + name: "Budgeting Vibe", + email: "noreply@budgetingvibe.com" + }, + emailVerification: { + clientRoute: EmailVerificationRoute + }, + passwordReset: { + clientRoute: PasswordResetRoute + } + } + }, + // Route to redirect to if auth fails + onAuthFailedRedirectTo: "/login", + // Optional: Route after successful signup/login + // onAuthSucceededRedirectTo: "/dashboard" + } + emailSender: { + provider: Dummy // Use Dummy for local dev (prints emails to console) + // provider: SMTP // For production, configure SMTP + } + } + + // Define the routes needed by email auth methods + route EmailVerificationRoute { path: "/auth/verify-email", to: EmailVerificationPage } + page EmailVerificationPage { component: import { EmailVerification } from "@src/features/auth/EmailVerificationPage.tsx" } + + route PasswordResetRoute { path: "/auth/reset-password", to: PasswordResetPage } + page PasswordResetPage { component: import { PasswordReset } from "@src/features/auth/PasswordResetPage.tsx" } + ``` + +- **Dummy Email Provider Note:** When `emailSender: { provider: Dummy }` is configured in [main.wasp](mdc:main.wasp), Wasp does not send actual emails. Instead, the content of verification/password reset emails, including the clickable link, will be printed directly to the server console where `wasp start` is running. + +## Wasp Auth Rules + +- **User Model ( [schema.prisma](mdc:schema.prisma) ):** + - Wasp Auth methods handle essential identity fields (like `email`, `password hash`, `provider IDs`, `isVerified`) internally. These are stored in separate Prisma models managed by Wasp (`AuthProvider`, `AuthProviderData`). + - Your Prisma `User` model (specified in [main.wasp](mdc:main.wasp) as `auth.userEntity`) typically **only needs the `id` field** for Wasp to link the auth identity. + ```prisma + // Minimal User model in @schema.prisma + model User { + id Int @id @default(autoincrement()) + // Add other *non-auth* related fields as needed + // e.g., profile info, preferences, relations to other models + // profileImageUrl String? + // timeZone String? @default("UTC") + } + ``` + - **Avoid adding** `email`, `emailVerified`, `password`, `username`, or provider-specific ID fields directly to *your* `User` model in [schema.prisma](mdc:schema.prisma) unless you have very specific customization needs that require overriding Wasp's default behavior and managing these fields manually. + - If you need frequent access to an identity field like `email` or `username` for *any* user (not just the logged-in one), see the **Recommendation** in the "Wasp Auth User Fields" section below. + +- **Auth Pages:** + - When initially creating Auth pages (Login, Signup), use the pre-built components provided by Wasp for simplicity: + - `import { LoginForm, SignupForm } from 'wasp/client/auth';` + - These components work with the configured auth methods in [main.wasp](mdc:main.wasp). + - You can customize their appearance or build completely custom forms if needed. + +- **Protected Routes/Pages:** + - Use the `useAuth` hook from `wasp/client/auth` to access the current user's data and check authentication status. + - Redirect or show alternative content if the user is not authenticated. + ```typescript + import { useAuth } from 'wasp/client/auth'; + import { Redirect } from 'wasp/client/router'; // Or use Link + + const MyProtectedPage = () => { + const { data: user, isLoading, error } = useAuth(); // Returns AuthUser | null + + if (isLoading) return
Loading...
; + // If error, it likely means the auth session is invalid/expired + if (error || !user) { + // Redirect to login page defined in main.wasp (auth.onAuthFailedRedirectTo) + // Or return ; + return
Please log in to access this page.
; + } + + // User is authenticated, render the page content + // Use helpers like getEmail(user) or getUsername(user) if needed + return
Welcome back!
; // Access user.id if needed + }; + ``` + +## Wasp Auth User Fields (`AuthUser`) + +- The `user` object returned by `useAuth()` hook on the client, or accessed via `context.user` in server operations/APIs, is an `AuthUser` object (type imported from `wasp/auth`). +- **Auth-specific fields** (email, username, verification status, provider IDs) live under the nested `identities` property based on the auth method used. + - e.g., `user.identities.email?.email` + - e.g., `user.identities.username?.username` + - e.g., `user.identities.google?.providerUserId` + - **Always check for `null` or `undefined`** before accessing these nested properties, as a user might not have used all configured auth methods. +- **Helpers:** Wasp provides helper functions from `wasp/auth` for easier access to common identity fields on the `AuthUser` object: + - `import { getEmail, getUsername } from 'wasp/auth';` + - `const email = getEmail(user); // Returns string | null` + - `const username = getUsername(user); // Returns string | null` +- **Standard User Entities:** Remember that standard `User` entities fetched via `context.entities.User.findMany()` or similar in server code **DO NOT** automatically include these auth identity fields (`email`, `username`, etc.) by default. They only contain the fields defined directly in your [schema.prisma](mdc:schema.prisma) `User` model. +- **Recommendation:** + - If you need *frequent* access to an identity field like `email` or `username` for *any* user (not just the currently logged-in one accessed via `context.user` or `useAuth`) and want to query it easily via `context.entities.User`, consider this approach: + 1. **Add the field directly** to your `User` model in [schema.prisma](mdc:schema.prisma). + ```prisma + model User { + id Int @id @default(autoincrement()) + email String? @unique // Add if needed frequently + // other fields... + } + ``` + 2. **Ensure this field is populated correctly** when the user signs up or updates their profile. You can do this through the `userSignupFields` property in the wasp config file for each auth method. + ```wasp + //main.wasp + auth: { + userEntity: User, + methods: { + email: { + //... + userSignupFields: import { getEmailUserFields } from "@src/auth/userSignupFields" + }, + } + } + ``` + ```ts + //userSignupFields.ts + import { defineUserSignupFields } from 'wasp/auth/providers/types'; + + const userDataSchema = z.object({ + email: z.string(), + }); + + export const getEmailUserFields = defineUserSignupFields({ + email: (data) => { + const userData = userDataSchema.parse(data); + return userData.email; + } + }) + ``` + 3. This makes the field (`email` in this example) a standard, queryable field on your `User` entity, accessible via `context.entities.User`, separate from the `AuthUser`'s identity structure. + +- **Common Issue:** If auth isn't working, first verify the `auth` configuration in [main.wasp](mdc:main.wasp) is correct and matches your intent (correct `userEntity`, enabled `methods`, `onAuthFailedRedirectTo`). Ensure environment variables for social providers are set if applicable. Check the Wasp server logs for errors. diff --git a/template/app/.cursor/rules/database-operations.mdc b/template/app/.cursor/rules/database-operations.mdc new file mode 100644 index 00000000..ce48bbb1 --- /dev/null +++ b/template/app/.cursor/rules/database-operations.mdc @@ -0,0 +1,158 @@ +--- +description: +globs: +alwaysApply: true +--- +# 3. Database, Entities, and Operations + +This document gives a quick rundown on how Wasp interacts with the database using Prisma, defines Wasp Entities, and explains the rules for creating and using Wasp Operations (Queries and Actions). + +See the Wasp Data Model docs for more info [wasp-overview.mdc](mdc:template/app/.cursor/rules/wasp-overview.mdc) + +## Wasp Database and Entities + +- Wasp uses Prisma for database access, with models defined in [schema.prisma](mdc:schema.prisma). +- Prisma models defined in [schema.prisma](mdc:schema.prisma) automatically become Wasp Entities that can be used in operations. +- Wasp reads the [schema.prisma](mdc:schema.prisma) file to understand your data model and generate appropriate code (e.g., types in `wasp/entities`). +- Example Prisma model in [schema.prisma](mdc:schema.prisma) : + ```prisma + model Task { + id Int @id @default(autoincrement()) + description String + isDone Boolean @default(false) + user User @relation(fields: [userId], references: [id]) + userId Int + } + ``` + +## Wasp DB Schema Rules (@schema.prisma) + +- Add database models directly to the [schema.prisma](mdc:schema.prisma) file, NOT to [main.wasp](mdc:main.wasp) as entities. +- Generally avoid adding `db.system` or `db.prisma` properties to the [main.wasp](mdc:main.wasp) config file; configure the database provider within [schema.prisma](mdc:schema.prisma) instead. + ```prisma + // Example in schema.prisma + datasource db { + provider = "postgresql" // or "sqlite" + url = env("DATABASE_URL") + } + ``` +- Keep the [schema.prisma](mdc:schema.prisma) file in the root of the project. +- **Applying Changes:** After updating [schema.prisma](mdc:schema.prisma), run `wasp db migrate-dev` in the terminal to generate and apply SQL migrations. +- **Database Choice:** While 'sqlite' is the default, it lacks support for features like Prisma enums or PgBoss scheduled jobs. Use 'postgresql' for such cases. If using PostgreSQL locally, ensure it's running (e.g., via `wasp db start` if using Wasp's built-in Docker setup, or ensure your own instance is running). +- Define all model relationships (`@relation`) within [schema.prisma](mdc:schema.prisma). + +## Wasp Operations (Queries & Actions) + +- Operations are how Wasp handles client-server communication, defined in [main.wasp](mdc:main.wasp). +- **Queries:** Read operations (fetch data). +- **Actions:** Write operations (create, update, delete data). +- Operations automatically handle data fetching, caching (for queries), and updates. +- Operations reference Entities (defined in [schema.prisma](mdc:schema.prisma) ) to establish proper data access patterns and dependencies. +- Example definitions in [main.wasp](mdc:main.wasp): + ```wasp + query getTasks { + // Points to the implementation function + fn: import { getTasks } from "@src/features/tasks/operations.ts", // Convention: operations.ts + // Grants access to the Task entity within the operation's context + entities: [Task] + } + + action createTask { + fn: import { createTask } from "@src/features/tasks/operations.ts", + entities: [Task] // Needs access to Task to create one + } + ``` + +## Wasp Operations Rules & Implementation + +- **Operation File:** Implement query and action functions together in a single `operations.ts` file within the relevant feature directory (e.g., `src/features/tasks/operations.ts`). +- **Generated Types:** Wasp auto-generates TypeScript types for your operations based on their definitions in [main.wasp](mdc:main.wasp) and the functions' signatures. + - Import operation types using `import type { MyQuery, MyAction } from 'wasp/server/operations';` + - If types aren't updated after changing [main.wasp](mdc:main.wasp) or the function signature, restart the Wasp dev server (`wasp start`). +- **Entity Types:** Wasp generates types for your Prisma models from [schema.prisma](mdc:schema.prisma). + - Import entity types using `import type { MyModel } from 'wasp/entities';` +- **Entity Access:** Ensure all Entities needed within an operation's logic are listed in its `entities: [...]` definition in [main.wasp](mdc:main.wasp). This makes `context.entities.YourModel` available. +- **Internal Communication:** Prioritize Wasp operations for client-server communication within the app. Use Custom HTTP API Endpoints (see [advanced-troubleshooting.mdc](mdc:template/app/.cursor/rules/advanced-troubleshooting.mdc)) primarily for external integrations (webhooks, etc.). +- **Client-Side Query Usage:** Use Wasp's `useQuery` hook from `wasp/client/operations` to fetch data. + - `import { useQuery } from 'wasp/client/operations';` + - `const { data, isLoading, error } = useQuery(getQueryName, { queryArgs });` +- **Client-Side Action Usage:** Call actions *directly* using `async`/`await`. **DO NOT USE** the `useAction` hook unless you specifically need optimistic UI updates (see [advanced-troubleshooting.mdc](mdc:template/app/.cursor/rules/advanced-troubleshooting.mdc)). + - `import { myAction } from 'wasp/client/operations';` + - `const result = await myAction({ actionArgs });` +- **Example Operation Implementation (`src/features/tasks/operations.ts`): + ```typescript + import { HttpError } from 'wasp/server' + import type { GetTasks, CreateTask } from 'wasp/server/operations' + import type { Task } from 'wasp/entities' + + // Type annotations come from Wasp based on main.wasp definitions + export const getTasks: GetTasks = async (_args, context) => { + if (!context.user) { + throw new HttpError(401, 'Not authorized'); + } + // Access entities via context + return context.entities.Task.findMany({ + where: { userId: context.user.id } + }); + } + + type CreateTaskInput = Pick + export const createTask: CreateTask = async (args, context) => { + if (!context.user) { + throw new HttpError(401, 'Not authorized'); + } + + return context.entities.Task.create({ + data: { + description: args.description, + userId: context.user.id, + } + }); + } + ``` + +## Prisma Enum Value Imports + +- **Rule:** When you need to use Prisma enum members as *values* (e.g., `MyEnum.VALUE` in logic or comparisons) in your server or client code, import the enum directly from `@prisma/client`, not from `wasp/entities`. + - ✅ `import { TransactionType } from '@prisma/client';` (Use as `TransactionType.EXPENSE`) + - ❌ `import { TransactionType } from 'wasp/entities';` (This only imports the *type* for annotations, not the runtime *value*) + +## Server-Side Error Handling + +- Throw `HttpError` from `wasp/server` for expected errors (e.g., unauthorized, not found, bad input) to send structured responses to the client. +- Log unexpected errors for debugging. +- Example: + ```typescript + import { HttpError } from 'wasp/server' + import type { UpdateTask } from 'wasp/server/operations' + import type { Task } from 'wasp/entities' + + export const updateTask: UpdateTask<{ id: number; data: Partial }, Task> = async (args, context) => { + if (!context.user) { + throw new HttpError(401, 'Not authorized'); + } + + try { + const task = await context.entities.Task.findFirst({ + where: { id: args.id, userId: context.user.id }, + }); + + if (!task) { + throw new HttpError(404, 'Task not found'); + } + + return context.entities.Task.update({ + where: { id: args.id }, + data: args.data, + }); + } catch (error) { + if (error instanceof HttpError) { + throw error; // Re-throw known HttpErrors + } + // Log unexpected errors + console.error('Failed to update task:', error); + // Throw a generic server error for unexpected issues + throw new HttpError(500, 'Failed to update task due to an internal error.'); + } + } + ``` diff --git a/template/app/.cursor/rules/deployment.mdc b/template/app/.cursor/rules/deployment.mdc new file mode 100644 index 00000000..46abda3d --- /dev/null +++ b/template/app/.cursor/rules/deployment.mdc @@ -0,0 +1,87 @@ +--- +description: Deploying full-stack wasp apps via the CLI +globs: +alwaysApply: false +--- +# 7. Deployment (Fly.io via Wasp CLI) + +This document outlines the steps to deploy the Wasp application using the Wasp CLI, targeting the Fly.io hosting provider. + +For more info on deployments, see the Wasp deployment docs as mentioned in [wasp-overview.mdc](mdc:template/app/.cursor/rules/wasp-overview.mdc) + +## 1. Prerequisites + +Before deploying, ensure the following prerequisites are met: + +* **Fly.io Account:** You need an account with Fly.io (https://fly.io/docs/). +* **Billing Information:** Fly.io requires credit card information to be added to your account before you can deploy apps, even if you plan to stay within the free tier limits. Add this via your Fly.io account's billing page. +* **Install `flyctl` CLI:** The Fly.io command-line interface (`flyctl`) must be installed on your local machine. Follow the installation instructions here: https://fly.io/docs/flyctl/install/ +* **Login to `flyctl`:** Authenticate the CLI with your Fly.io account by running: + ```bash + fly auth login + ``` + +## 2. Deployment Steps + +The Wasp CLI simplifies deployment to a single command. + +1. **Choose App Name and Region:** + * Decide on a **unique base name** for your application (e.g., `my-budget-app`). This name must be unique across all Fly.io applications. + * Select a Fly.io **region** for deployment (e.g., `mia` for Miami, `ams` for Amsterdam). See Fly.io's regions for a list of available regions. + +2. **Run the Deployment Command:** + * Open your terminal in the root directory of your Wasp project. + * Execute the `wasp deploy fly launch` command, replacing `` and `` with your choices: + ```bash + wasp deploy fly launch + ``` + *Example:* + ```bash + wasp deploy fly launch my-budget-app mia + ``` + * **Important:** Do **NOT** interrupt (e.g., Ctrl+C) the process while the command is running. It performs multiple steps: setting up the Fly app configuration, creating the database, building the project, and deploying the client and server components. + +3. **Specify Fly.io Organization (If Necessary):** + * If your Fly.io account belongs to multiple organizations, you must specify which one to use by adding the `--org ` flag to the command. + * Find your organization slugs by running: `fly orgs list` + * *Example with organization:* + ```bash + wasp deploy fly launch my-budget-app mia --org my-fly-org-slug + ``` + +## 3. Post-Deployment + +* **Generated Files:** The deployment command creates two configuration files in your project root: + * `fly-server.toml` + * `fly-client.toml` + * **Commit these files** to your version control system (e.g., Git). They contain the deployment configuration and are needed for future updates. +* **Accessing Your App:** Once deployment is complete, the CLI will output the URLs for your deployed client and server. The client URL is your main application entry point. +* **Updating Your App:** To redeploy changes after committing the `.toml` files, you can simply run: + ```bash + wasp deploy fly deploy + ``` + +* **Setting Environment Variables (Secrets):** + * If your application requires environment variables beyond the ones Wasp/Fly set automatically (like `DATABASE_URL`), such as API keys or third-party service credentials (e.g., `SENDGRID_API_KEY`, OAuth client secrets), you need to set them as secrets on Fly.io. + * Use the `wasp deploy fly cmd` command to interact with the `flyctl` CLI in the context of your deployed server app. + * **Command:** + ```bash + wasp deploy fly cmd --context server secrets set VARIABLE_NAME="VALUE" + ``` + *Replace `VARIABLE_NAME` with the name of your environment variable and `VALUE` with its value. Use quotes around the value if it contains special characters.* + * **Example:** + ```bash + wasp deploy fly cmd --context server secrets set SENDGRID_API_KEY="SG.your_actual_api_key" + ``` + * You can list currently set secrets (values will be masked) using: + ```bash + wasp deploy fly cmd --context server secrets list + ``` + * **Important:** Set these secrets *after* the initial `launch` command completes but *before* your application fully relies on them. If you add new variables later, you might need to redeploy the server for it to pick them up (`wasp deploy fly deploy`). + +## 4. Troubleshooting + +* **Unique Name Error:** If deployment fails due to a non-unique name, choose a different `` and run the `launch` command again. +* **Billing Error:** Ensure you have added valid billing information to your Fly.io account. +* **Build Failures:** Check the output logs from the `wasp deploy` command for any build errors in your Wasp project code. Fix the errors and attempt deployment again. +* **Check Fly.io Dashboard:** Monitor the status and logs of your applications (`-client`, `-server`, `-db`) directly in the Fly.io dashboard. diff --git a/template/app/.cursor/rules/possible-solutions-thinking.mdc b/template/app/.cursor/rules/possible-solutions-thinking.mdc new file mode 100644 index 00000000..37217b9c --- /dev/null +++ b/template/app/.cursor/rules/possible-solutions-thinking.mdc @@ -0,0 +1,6 @@ +--- +description: +globs: +alwaysApply: false +--- +Think about a few possible scenarios or solutions to this problem. Present the one you think is best suited to solve this issue and provide rationale for why you think it's the best one. diff --git a/template/app/.cursor/rules/project-conventions.mdc b/template/app/.cursor/rules/project-conventions.mdc new file mode 100644 index 00000000..c8056d38 --- /dev/null +++ b/template/app/.cursor/rules/project-conventions.mdc @@ -0,0 +1,84 @@ +--- +description: +globs: +alwaysApply: true +--- +# 2. Project Conventions and Rules + +This document outlines the specific conventions, file structures, and general rules for this Wasp project. + +## Quick Reference + +### Common Patterns + +- Define app structure in the Wasp config file: [main.wasp](mdc:main.wasp) or `main.wasp.ts`. +- Define data models ("entities") in [schema.prisma](mdc:schema.prisma). +- Group feature code in `src/features/{featureName}` directories. +- Group feature config definitions (e.g. routes, pages, operations, etc.) into sections within the Wasp config file ([main.wasp](mdc:main.wasp)) using the `//#region` directive: + ```wasp + // Example in @main.wasp + // #region {FeatureName} + // ... feature-specific declarations ... + // #endregion + ``` +- Use Wasp operations (queries/actions) for client-server communication (See [database-operations.mdc](mdc:template/app/.cursor/rules/database-operations.mdc)). +- **Wasp Imports:** Import from `wasp/...` not `@wasp/...` in `.ts`/`.tsx` files. + +### Common Issues & Import Rules + +- **Wasp Imports in `.ts`/`.tsx`:** Always use the `wasp/...` prefix. + - ✅ `import { Task } from 'wasp/entities'` + - ✅ `import type { GetTasks } from 'wasp/server/operations'` + - ✅ `import { getTasks, useQuery } from 'wasp/client/operations'` + - ❌ `import { ... } from '@wasp/...'` + - ❌ `import { ... } from '@src/features/...'` (Use relative paths for non-Wasp imports within `src`) + - If you see "Cannot find module 'wasp/...'": Double-check the import path prefix. +- **Wasp Config Imports in [main.wasp](mdc:main.wasp) :** Imports of your code *must* start with `@src/`. + - ✅ `component: import { LoginPage } from "@src/features/auth/LoginPage.tsx"` + - ❌ `component: import { LoginPage } from "../src/features/auth/LoginPage.tsx"` + - ❌ `component: import { LoginPage } from "client/pages/auth/LoginPage.tsx"` +- **General Imports in `.ts`/`.tsx`:** Use relative paths for imports within the `src/` directory. Avoid using the `@src/` alias directly in `.ts`/`.tsx` files. + - If you see "Cannot find module '@src/...'": Use a relative path instead. +- **Prisma Enum *Value* Imports:** Import directly from `@prisma/client`. See [database-operations.mdc](mdc:template/app/.cursor/rules/database-operations.mdc). +- **Wasp Actions Client-Side:** Call actions directly using `async/await`. DO NOT USE the `useAction` hook unless optimistic updates are needed. See [database-operations.mdc](mdc:template/app/.cursor/rules/database-operations.mdc). + - ✅ `import { deleteTask } from 'wasp/client/operations'; await deleteTask({ taskId });` +- Root Component (`src/App.tsx` or similar): + - Ensure the root component defined in @main.wasp (usually via `app.client.rootComponent`) renders the `` component from `react-router-dom` to display nested page content. + ```tsx + // Example Root Component + import React from 'react'; + import { Outlet } from 'react-router-dom'; + import Header from './Header'; // Example shared component + + function App() { + return ( +
+
+
+ {/* Outlet renders the content of the matched route/page */} + +
+
+ ); + } + export default App; + ``` + +## Rules + +### General Rules + +- Always reference the Wasp config file ([main.wasp](mdc:main.wasp) or `main.wasp.ts`) as your source of truth for the app's configuration and structure. +- Group feature config definitions in the Wasp config file using `//#region` (as noted above). +- Group feature code into feature directories (e.g. `src/features/transactions`). +- Use the latest Wasp version, as defined in the Wasp configl file. +- Combine Wasp operations (queries and actions) into an `operations.ts` file within the feature directory (e.g., `src/features/transactions/operations.ts`). +- Always use TypeScript for Wasp code (`.ts`/`.tsx`). + +### Wasp Dependencies + +- Avoid adding dependencies directly to the [main.wasp](mdc:main.wasp) config file. +- Install dependencies via `npm install` instead. This updates [package.json](mdc:package.json) and [package-lock.json](mdc:package-lock.json) + +### Referencing Documentation +- Make sure the user has added the applicable LLM-optimized docs, available in [wasp-overview.mdc](mdc:template/app/.cursor/rules/wasp-overview.mdc), in the chat context or settings when using AI-assisted coding tools. diff --git a/template/app/.cursor/rules/wasp-overview.mdc b/template/app/.cursor/rules/wasp-overview.mdc new file mode 100644 index 00000000..7dc2e934 --- /dev/null +++ b/template/app/.cursor/rules/wasp-overview.mdc @@ -0,0 +1,56 @@ +--- +description: +globs: +alwaysApply: true +--- +# 1. Wasp Overview and Core Concepts + +This document covers the fundamental concepts of the Wasp framework and the basic project structure. + +## Background Information + +### What is Wasp + +- Wasp (Web Application SPecification language) is a declarative, statically typed, domain-specific language (DSL) for building modern, full-stack web applications. +- Unlike traditional frameworks that are sets of libraries, Wasp is a simple programming language that understands web app concepts and generates code for you. +- Wasp integrates with React (frontend), Node.js (backend), and Prisma (database ORM) to create full-stack web applications with minimal boilerplate. +- The Wasp compiler reads your declarative configuration in the config file ([main.wasp](mdc:main.wasp) or `main.wasp.ts`) and generates all the necessary code for a working web application. +- For the most up-to-date and comprehensive information, always refer to the Wasp Documenation (linked below). + +### Wasp Project Structure + +- A Wasp project consists of a [main.wasp](mdc:main.wasp) (or `main.wasp.ts`) file in the root directory that defines the app's configuration. +- The [schema.prisma](mdc:schema.prisma) file in the root directory defines your database models ("entities"). +- Your custom code lives in the `src/` directory (e.g. `src/features/`), which contains client-side and server-side code. +- Wasp generates additional code that connects everything together when you run your app. + +### The Wasp Config File + +- The main Wasp Config File ([main.wasp](mdc:main.wasp) or `main.wasp.ts`) is the central configuration file that defines your application structure. +- It contains declarations for app settings, pages, routes, authentication, database entities, and operations (queries and actions). +- Example structure: + ```main.wasp + app myApp { + wasp: { + version: "^0.16.0" // Check @main.wasp for the actual version + }, + title: "My App", + } + + route HomeRoute { path: "/", to: HomePage } + page HomePage { + component: import { HomePage } from "@src/client/pages/HomePage.tsx" // Example import path + } + + // Operations are defined here, see 3-database-operations.mdc + query getTasks { + fn: import { getTasks } from "@src/server/queries.js", + entities: [Task] + } + ``` + +### Wasp Documentation +More info on all of Wasp's features can be found in the Wasp documentation (NOTE: You can follow these links, instruct the user to add these docs to Cursor's settings, or have the user manually include them in the chat context): +- Links to Wasp documentation sections (LLM-optimized): https://wasp.sh/llms.txt +- Complete Wasp documentation (LLM-optimized): https://wasp.sh/llms-full.txt +- Wasp Docs homepage (human-readable): https://wasp.sh/docs diff --git a/template/app/.cursorrules b/template/app/.cursorrules deleted file mode 100644 index eee00945..00000000 --- a/template/app/.cursorrules +++ /dev/null @@ -1,52 +0,0 @@ -// Wasp Import Rules -- Path to Wasp functions within .ts files must come from 'wasp', not '@wasp'! - ✓ import { Task } from 'wasp/entities' - ✓ import type { GetTasks } from 'wasp/server/operations' - ✓ import { getTasks, useQuery } from 'wasp/client/operations' - ✗ import { getTasks, useQuery } from '@wasp/...' - ✗ import { getTasks, useQuery } from '@src/feature/operations.ts' - -- Path to external imports within 'main.wasp' must start with "@src/"! - ✓ component: import { LoginPage } from "@src/client/pages/auth/LoginPage.tsx" - ✗ component: import { LoginPage } from "@client/pages/auth/LoginPage.tsx" -- In the client's root component, use the Outlet component rather than children - ✓ import { Outlet } from 'react-router-dom'; - -// Wasp DB Schema Rules -- Add databse models to the 'schema.prisma' file, NOT to 'main.wasp' as "entities" -- Do NOT add a db.system nor a db.prisma property to 'main.wasp'. This is taken care of in 'schema.prisma' -- Keep the 'schema.prisma' within the root of the project - -// Wasp Operations -- Types are generated automatically from the function definition in 'main.wasp', - ✓ import type { GetTimeLogs, CreateTimeLog, UpdateTimeLog } from 'wasp/server/operations' -- Wasp also generates entity types based on the models in 'schema.prisma' - ✓ import type { Project, TimeLog } from 'wasp/entities' -- Make sure that all Entities that should be included in the operations context are defined in its definition in 'main.wasp' - ✓ action createTimeLog { fn: import { createTimeLog } from "@src/server/timeLogs/operations.js", entities: [TimeLog, Project] } - -// Wasp Auth -- When creating Auth pages, use the LoginForm and SignupForm components provided by Wasp - ✓ import { LoginForm } from 'wasp/client/auth' -- Wasp takes care of creating the user's auth model id, username, and password for a user, so a user model DOES NOT need these properties - ✓ model User { id Int @id @default(autoincrement()) } - -// Wasp Dependencies -- Do NOT add dependencies to 'main.wasp' -- Install dependencies via 'npm install' instead - -// Wasp -- Use the latest Wasp version, ^0.16.0 -- Always use typescript for Wasp code. -- When creating Wasp operations (queries and actions) combine them into an operations.ts file within the feature directory rather than into separate queries.ts and actions.ts files - -// React -- Use relative imports for other react components -- If importing a function from an operations file, defer to the wasp import rules - -// CSS -- Use Tailwind CSS for styling. -- Do not use inline styles unless necessary - -// General -- Use single quotes \ No newline at end of file