forked from xiaoyuque-wati/next-supabase-ai-templates
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path.windsurfrules
225 lines (190 loc) · 5.72 KB
/
.windsurfrules
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
# Makerkit Guidelines
## Project Stack
- Framework: Next.js 15 App Router, TypeScript, React, Node.js
- Backend: Supabase with Postgres
- UI: Shadcn UI, Tailwind CSS
- Key libraries: React Hook Form, React Query, Zod, Lucide React
- Focus: Code clarity, Readability, Best practices, Maintainability
## Project Structure
```
/apps/web/
/app
/home # protected routes
/(user) # user workspace
/[account] # team workspace
/(marketing) # marketing pages
/auth # auth pages
/components # global components
/config # global config
/lib # global utils
/content # markdoc content
/supabase # supabase root
```
## Core Principles
### Data Flow
1. Server Components
- Use Supabase Client directly via `getSupabaseServerClient`
- Handle errors with proper boundaries
- Example:
```tsx
async function ServerComponent() {
const client = getSupabaseServerClient();
const { data, error } = await client.from('notes').select('*');
if (error) return <ErrorComponent error={error} />;
return <ClientComponent data={data} />;
}
```
2. Client Components
- Use React Query for data fetching
- Implement proper loading states
- Example:
```tsx
function useNotes() {
const { data, isLoading } = useQuery({
queryKey: ['notes'],
queryFn: async () => {
const { data } = await fetch('/api/notes');
return data;
}
});
return { data, isLoading };
}
```
### Server Actions
- Name files as "server-actions.ts" in `_lib/server` folder
- Export with "Action" suffix
- Use `enhanceAction` with proper typing
- Example:
```tsx
export const createNoteAction = enhanceAction(
async function (data, user) {
const client = getSupabaseServerClient();
const { error } = await client
.from('notes')
.insert({ ...data, user_id: user.id });
if (error) throw error;
return { success: true };
},
{
auth: true,
schema: NoteSchema,
}
);
```
### Route Handlers
- Use `enhanceRouteHandler` to wrap route handlers
- Use Route Handlers when data fetching from Client Components
## Database & Security
### RLS Policies
- Strive to create a safe, robust, secure and consistent database schema
- Always consider the compromises you need to make and explain them so I can make an educated decision. Follow up with the considerations make and explain them.
- Enable RLS by default and propose the required RLS policies
- `public.accounts` are the root tables for the application
- Implement cascading deletes when appropriate
- Ensure strong consistency considering triggers and constraints
- Always use Postgres schemas explicitly (e.g., `public.accounts`)
## Forms Pattern
### 1. Schema Definition
```tsx
// schema/note.schema.ts
import { z } from 'zod';
export const NoteSchema = z.object({
title: z.string().min(1).max(100),
content: z.string().min(1),
category: z.enum(['work', 'personal']),
});
```
### 2. Form Component
```tsx
'use client';
export function NoteForm() {
const [pending, startTransition] = useTransition();
const form = useForm({
resolver: zodResolver(NoteSchema),
defaultValues: { title: '', content: '', category: 'personal' }
});
const onSubmit = (data: z.infer<typeof NoteSchema>) => {
startTransition(async () => {
try {
await createNoteAction(data);
form.reset();
} catch (error) {
// Handle error
}
});
};
return (
<Form {...form}>
<FormField name="title" render={({ field }) => (
<FormItem>
<FormLabel>Title</FormLabel>
<FormControl>
<Input {...field} />
</FormControl>
<FormMessage />
</FormItem>
)} />
{/* Other fields */}
</Form>
);
}
```
## Error Handling
- Consider logging asynchronous requests in server code using the `@kit/shared/logger`
- Handle promises and async/await gracefully
- Consider the unhappy path and handle errors appropriately
### Structured Logging
```tsx
const ctx = {
name: 'create-note',
userId: user.id,
noteId: note.id
};
logger.info(ctx, 'Creating new note...');
try {
await createNote();
logger.info(ctx, 'Note created successfully');
} catch (error) {
logger.error(ctx, 'Failed to create note', { error });
throw error;
}
```
## Context Management
In client components, we can use the `useUserWorkspace` hook to access the user's workspace data.
### Personal Account
```tsx
'use client';
function PersonalDashboard() {
const { workspace, user } = useUserWorkspace();
if (!workspace) return null;
return (
<div>
<h1>Welcome, {user.email}</h1>
<SubscriptionStatus status={workspace.subscription_status} />
</div>
);
}
```
### Team Account
In client components, we can use the `useTeamAccountWorkspace` hook to access the team account's workspace data. It only works under the `/home/[account]` route.
```tsx
'use client';
function TeamDashboard() {
const { account, user } = useTeamAccountWorkspace();
return (
<div>
<h1>{account.name}</h1>
<RoleDisplay role={account.role} />
<PermissionsList permissions={account.permissions} />
</div>
);
}
```
## UI Components
- Reusable UI components are defined in the "packages/ui" package named "@kit/ui".
- By exporting the component from the "exports" field, we can import it using the "@kit/ui/{component-name}" format.
## Creating Pages
When creating new pages ensure:
- The page is exported using `withI18n(Page)` to enable i18n.
- The page has the required and correct metadata using the `metadata` or `generateMetadata` function.
- Don't worry about authentication, it's handled in the middleware.