diff --git a/.claude/commands/commit.md b/.claude/commands/commit.md new file mode 100644 index 0000000..14b2a60 --- /dev/null +++ b/.claude/commands/commit.md @@ -0,0 +1,36 @@ +# Commit + +변경사항을 분석하여 Conventional Commits 형식으로 커밋을 생성한다. + +## 절차 + +1. `git status`와 `git diff`로 변경사항 확인 +2. 변경사항을 논리적 단위로 분리 +3. 각 단위별로 커밋 생성 + +## 커밋 메시지 형식 + +``` +{type}: {subject} + +{body} +``` + +### 타입 + +- `feat` - 새로운 기능 +- `fix` - 버그 수정 +- `refactor` - 코드 리팩토링 +- `style` - 코드 포맷팅 (동작 변경 없음) +- `docs` - 문서 변경 +- `test` - 테스트 추가/수정 +- `chore` - 빌드, 설정 변경 +- `perf` - 성능 개선 + +### 규칙 + +- 제목은 한국어, 50자 이내 +- 이모지 사용 금지 +- 한꺼번에 커밋하지 않고 작은 작업 단위로 분리 +- body는 선택사항이며, 필요시 "왜" 변경했는지 설명 +- 커밋 후 `git status`로 결과 확인 diff --git a/.claude/commands/create-pr.md b/.claude/commands/create-pr.md new file mode 100644 index 0000000..1ef16bc --- /dev/null +++ b/.claude/commands/create-pr.md @@ -0,0 +1,46 @@ +# Create PR + +현재 브랜치의 변경사항으로 Pull Request를 생성한다. + +## 절차 + +1. `git log main..HEAD --oneline`으로 커밋 이력 확인 +2. `git diff main...HEAD`로 전체 변경사항 파악 +3. PR 제목과 본문 작성 +4. `gh pr create`로 PR 생성 + +## 브랜치 컨벤션 + +``` +{type}/{description} +``` + +- `feat/` - 새 기능 +- `fix/` - 버그 수정 +- `refactor/` - 리팩토링 +- `chore/` - 설정/빌드 +- `docs/` - 문서 + +예: `feat/timeline-page`, `fix/search-filter` + +## PR 형식 + +```markdown +## Summary + +- 변경사항 1~3줄 요약 + +## Changes + +- 주요 변경 항목 나열 + +## Test Plan + +- [ ] 검증 항목 +``` + +## 규칙 + +- PR 제목은 70자 이내 +- base 브랜치는 `main` +- push 전 `pnpm lint && pnpm type:check && pnpm format:check` 확인 diff --git a/.claude/commands/self-review.md b/.claude/commands/self-review.md new file mode 100644 index 0000000..ffdf9a2 --- /dev/null +++ b/.claude/commands/self-review.md @@ -0,0 +1,54 @@ +# Self Review + +현재 변경사항을 다각도로 리뷰한다. + +## 절차 + +1. `git diff`로 변경사항 확인 +2. 아래 관점별로 리뷰 수행 +3. 발견된 이슈를 심각도별로 분류하여 보고 + +## 리뷰 관점 + +### Frontend Architecture + +- Server/Client Component 경계가 적절한가 +- feature 간 순환 의존이 없는가 +- `app/`에 비즈니스 로직이 들어가지 않았는가 +- import 경로가 `@/*` 절대 경로를 사용하는가 (상대 경로 `../`, `./` 사용 금지, barrel file `index.ts` 내부 re-export 제외) +- barrel file(`index.ts`)을 경유하여 import하는가 (내부 파일 직접 접근 금지) + +### UX/UI + +- 로딩/빈/에러 상태가 모두 처리되었는가 +- 모바일 반응형이 적용되었는가 +- 시맨틱 HTML을 사용했는가 +- 접근성 속성이 적절한가 + +### Code Quality + +- TypeScript strict mode 에러가 없는가 +- 미사용 변수/import가 없는가 +- `import type`이 적절히 사용되었는가 +- 불필요한 주석이 없는가 + +### Security + +- 사용자 입력을 적절히 검증하는가 +- XSS 취약점이 없는가 +- 민감 정보가 클라이언트에 노출되지 않는가 + +## 보고 형식 + +``` +## 리뷰 결과 + +### 심각 (즉시 수정) +- ... + +### 권장 (개선 사항) +- ... + +### 참고 +- ... +``` diff --git a/.claude/hooks/mark-lint-needed.sh b/.claude/hooks/mark-lint-needed.sh new file mode 100755 index 0000000..d3254dc --- /dev/null +++ b/.claude/hooks/mark-lint-needed.sh @@ -0,0 +1,12 @@ +#!/bin/bash +# 파일 수정 시 플래그만 생성하고, 실제 lint는 나중에 한 번만 실행 + +SESSION_ID=${CLAUDE_SESSION_ID:-default} +PROJECT_DIR="${CLAUDE_PROJECT_DIR:-.}" +FLAG_FILE="${PROJECT_DIR}/.claude/.lint-needed-${SESSION_ID}" + +# 플래그 파일 생성 (lint 필요함을 표시) +touch "$FLAG_FILE" + +# 조용히 종료 (사용자 경험 방해 안 함) +exit 0 diff --git a/.claude/hooks/post-stop-lint.sh b/.claude/hooks/post-stop-lint.sh new file mode 100755 index 0000000..2f301a0 --- /dev/null +++ b/.claude/hooks/post-stop-lint.sh @@ -0,0 +1,30 @@ +#!/bin/bash +# 대화 종료 시 실행: 누적된 lint 작업을 한 번에 실행 +# 성능 최적화: 여러 파일 수정 시에도 lint는 단 1회만 실행 + +SESSION_ID=${CLAUDE_SESSION_ID:-default} +PROJECT_DIR="${CLAUDE_PROJECT_DIR:-.}" +FLAG_FILE="${PROJECT_DIR}/.claude/.lint-needed-${SESSION_ID}" + +# 플래그 파일 확인 +if [ -f "$FLAG_FILE" ]; then + echo "🔍 [Deferred Linting] 파일 수정이 감지되었습니다. Lint & Format 실행 중..." + + # 프로젝트 루트에서 실행 + cd "$PROJECT_DIR" || exit 1 + + # Lint 자동 수정 + pnpm lint:fix 2>/dev/null || echo "⚠️ lint:fix 스킵됨" + + # Prettier 포맷팅 + pnpm format 2>/dev/null || echo "⚠️ format 스킵됨" + + # 플래그 파일 제거 + rm "$FLAG_FILE" + + echo "✅ Lint & Format 완료!" +else + echo "✨ [Deferred Linting] 변경사항 없음. 스킵." +fi + +exit 0 diff --git a/.claude/settings.json b/.claude/settings.json new file mode 100644 index 0000000..265dd85 --- /dev/null +++ b/.claude/settings.json @@ -0,0 +1,28 @@ +{ + "$schema": "https://json.schemastore.org/claude-code-settings.json", + "hooks": { + "PostToolUse": [ + { + "matcher": "Edit|Write", + "hooks": [ + { + "type": "command", + "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/mark-lint-needed.sh", + "timeout": 5 + } + ] + } + ], + "Stop": [ + { + "hooks": [ + { + "type": "command", + "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/post-stop-lint.sh", + "timeout": 120 + } + ] + } + ] + } +} diff --git a/.claude/skills/code-review/SKILL.md b/.claude/skills/code-review/SKILL.md new file mode 100644 index 0000000..c1e8f58 --- /dev/null +++ b/.claude/skills/code-review/SKILL.md @@ -0,0 +1,132 @@ +--- +name: code-review +description: Provides structured code review guidelines for TypeScript projects. Use when reviewing pull requests, analyzing code quality, or suggesting improvements. +license: MIT +--- + +# Code Review Guidelines + +## Overview + +This skill provides structured guidelines for reviewing TypeScript code. Apply these standards when reviewing pull requests, analyzing code quality, or suggesting improvements. + +**Keywords**: code review, pull request, PR review, TypeScript, code quality, best practices, refactoring + +## Review Checklist + +### 1. Code Correctness + +**Before approving, verify:** + +- [ ] Logic is correct and handles edge cases +- [ ] Error handling is appropriate +- [ ] No obvious bugs or race conditions +- [ ] Tests cover the changes adequately + +### 2. Code Quality + +**Check for:** + +- [ ] Clear, descriptive variable and function names +- [ ] Functions do one thing well (single responsibility) +- [ ] No excessive nesting (max 3 levels) +- [ ] DRY - no unnecessary duplication +- [ ] YAGNI - no speculative features + +### 3. TypeScript Specific + +**Ensure:** + +- [ ] Proper type annotations (avoid `any`) +- [ ] Interfaces/types defined for complex objects +- [ ] Generics used appropriately +- [ ] Null/undefined handled safely +- [ ] `strict` mode compatible + +### 4. Performance + +**Look for:** + +- [ ] Unnecessary re-renders (React) +- [ ] Missing memoization for expensive operations +- [ ] Inefficient loops or data structures +- [ ] Memory leaks (event listeners, subscriptions) + +## Review Comments + +### Comment Format + +Use this format for review comments: + +``` +[severity]: brief description + +Why: explanation of the issue +Suggestion: how to fix it (with code if helpful) +``` + +**Severity levels:** + +- `[critical]` - Must fix before merge +- `[suggestion]` - Recommended improvement +- `[nit]` - Minor style preference +- `[question]` - Need clarification + +### Example Comments + +**Good comment:** + +``` +[suggestion]: Consider extracting this validation logic + +Why: This 15-line validation block is hard to test in isolation +Suggestion: Move to a `validateUserInput(data)` function +``` + +**Bad comment:** + +``` +This is wrong, fix it. +``` + +## Common Issues + +### Anti-patterns to Flag + +1. **God functions** - Functions over 50 lines doing multiple things +2. **Prop drilling** - Passing props through 3+ component levels +3. **Magic numbers** - Unexplained literal values +4. **Catch-all error handling** - `catch(e) { console.log(e) }` +5. **Implicit any** - Missing type annotations on function parameters + +### Security Concerns + +Always flag: + +- SQL/NoSQL injection vulnerabilities +- XSS opportunities (unsanitized user input in DOM) +- Hardcoded secrets or API keys +- Insecure randomness for security contexts +- Missing input validation on API endpoints + +## Approval Guidelines + +### Approve When + +- All critical issues resolved +- Tests pass +- Code meets team standards +- No security concerns + +### Request Changes When + +- Critical bugs found +- Security vulnerabilities present +- Missing required tests +- Significant performance issues + +### Leave Comments When + +- Minor improvements possible +- Design alternatives worth discussing +- Documentation could be clearer diff --git a/.claude/skills/frontend-design/LICENSE.txt b/.claude/skills/frontend-design/LICENSE.txt new file mode 100644 index 0000000..f433b1a --- /dev/null +++ b/.claude/skills/frontend-design/LICENSE.txt @@ -0,0 +1,177 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS diff --git a/.claude/skills/frontend-design/SKILL.md b/.claude/skills/frontend-design/SKILL.md new file mode 100644 index 0000000..f709fde --- /dev/null +++ b/.claude/skills/frontend-design/SKILL.md @@ -0,0 +1,45 @@ +--- +name: frontend-design +description: Create distinctive, production-grade frontend interfaces with high design quality. Use this skill when the user asks to build web components, pages, artifacts, posters, or applications (examples include websites, landing pages, dashboards, React components, HTML/CSS layouts, or when styling/beautifying any web UI). Generates creative, polished code and UI design that avoids generic AI aesthetics. +license: Complete terms in LICENSE.txt +--- + +This skill guides creation of distinctive, production-grade frontend interfaces that avoid generic "AI slop" aesthetics. Implement real working code with exceptional attention to aesthetic details and creative choices. + +The user provides frontend requirements: a component, page, application, or interface to build. They may include context about the purpose, audience, or technical constraints. + +## Design Thinking + +Before coding, understand the context and commit to a BOLD aesthetic direction: + +- **Purpose**: What problem does this interface solve? Who uses it? +- **Tone**: Pick an extreme: brutally minimal, maximalist chaos, retro-futuristic, organic/natural, luxury/refined, playful/toy-like, editorial/magazine, brutalist/raw, art deco/geometric, soft/pastel, industrial/utilitarian, etc. There are so many flavors to choose from. Use these for inspiration but design one that is true to the aesthetic direction. +- **Constraints**: Technical requirements (framework, performance, accessibility). +- **Differentiation**: What makes this UNFORGETTABLE? What's the one thing someone will remember? + +**CRITICAL**: Choose a clear conceptual direction and execute it with precision. Bold maximalism and refined minimalism both work - the key is intentionality, not intensity. + +Then implement working code (HTML/CSS/JS, React, Vue, etc.) that is: + +- Production-grade and functional +- Visually striking and memorable +- Cohesive with a clear aesthetic point-of-view +- Meticulously refined in every detail + +## Frontend Aesthetics Guidelines + +Focus on: + +- **Typography**: Choose fonts that are beautiful, unique, and interesting. Avoid generic fonts like Arial and Inter; opt instead for distinctive choices that elevate the frontend's aesthetics; unexpected, characterful font choices. Pair a distinctive display font with a refined body font. +- **Color & Theme**: Commit to a cohesive aesthetic. Use CSS variables for consistency. Dominant colors with sharp accents outperform timid, evenly-distributed palettes. +- **Motion**: Use animations for effects and micro-interactions. Prioritize CSS-only solutions for HTML. Use Motion library for React when available. Focus on high-impact moments: one well-orchestrated page load with staggered reveals (animation-delay) creates more delight than scattered micro-interactions. Use scroll-triggering and hover states that surprise. +- **Spatial Composition**: Unexpected layouts. Asymmetry. Overlap. Diagonal flow. Grid-breaking elements. Generous negative space OR controlled density. +- **Backgrounds & Visual Details**: Create atmosphere and depth rather than defaulting to solid colors. Add contextual effects and textures that match the overall aesthetic. Apply creative forms like gradient meshes, noise textures, geometric patterns, layered transparencies, dramatic shadows, decorative borders, custom cursors, and grain overlays. + +NEVER use generic AI-generated aesthetics like overused font families (Inter, Roboto, Arial, system fonts), cliched color schemes (particularly purple gradients on white backgrounds), predictable layouts and component patterns, and cookie-cutter design that lacks context-specific character. + +Interpret creatively and make unexpected choices that feel genuinely designed for the context. No design should be the same. Vary between light and dark themes, different fonts, different aesthetics. NEVER converge on common choices (Space Grotesk, for example) across generations. + +**IMPORTANT**: Match implementation complexity to the aesthetic vision. Maximalist designs need elaborate code with extensive animations and effects. Minimalist or refined designs need restraint, precision, and careful attention to spacing, typography, and subtle details. Elegance comes from executing the vision well. + +Remember: Claude is capable of extraordinary creative work. Don't hold back, show what can truly be created when thinking outside the box and committing fully to a distinctive vision. diff --git a/.claude/skills/nextjs-best-practices/SKILL.md b/.claude/skills/nextjs-best-practices/SKILL.md new file mode 100644 index 0000000..f2128cf --- /dev/null +++ b/.claude/skills/nextjs-best-practices/SKILL.md @@ -0,0 +1,203 @@ +--- +name: nextjs-best-practices +description: Next.js App Router principles. Server Components, data fetching, routing patterns. +allowed-tools: Read, Write, Edit, Glob, Grep +--- + +# Next.js Best Practices + +> Principles for Next.js App Router development. + +--- + +## 1. Server vs Client Components + +### Decision Tree + +``` +Does it need...? +│ +├── useState, useEffect, event handlers +│ └── Client Component ('use client') +│ +├── Direct data fetching, no interactivity +│ └── Server Component (default) +│ +└── Both? + └── Split: Server parent + Client child +``` + +### By Default + +| Type | Use | +| ---------- | ------------------------------------- | +| **Server** | Data fetching, layout, static content | +| **Client** | Forms, buttons, interactive UI | + +--- + +## 2. Data Fetching Patterns + +### Fetch Strategy + +| Pattern | Use | +| -------------- | ------------------------ | +| **Default** | Static (cached at build) | +| **Revalidate** | ISR (time-based refresh) | +| **No-store** | Dynamic (every request) | + +### Data Flow + +| Source | Pattern | +| ---------- | ---------------------------- | +| Database | Server Component fetch | +| API | fetch with caching | +| User input | Client state + server action | + +--- + +## 3. Routing Principles + +### File Conventions + +| File | Purpose | +| --------------- | -------------- | +| `page.tsx` | Route UI | +| `layout.tsx` | Shared layout | +| `loading.tsx` | Loading state | +| `error.tsx` | Error boundary | +| `not-found.tsx` | 404 page | + +### Route Organization + +| Pattern | Use | +| ----------------------- | ------------------------- | +| Route groups `(name)` | Organize without URL | +| Parallel routes `@slot` | Multiple same-level pages | +| Intercepting `(.)` | Modal overlays | + +--- + +## 4. API Routes + +### Route Handlers + +| Method | Use | +| --------- | ----------- | +| GET | Read data | +| POST | Create data | +| PUT/PATCH | Update data | +| DELETE | Remove data | + +### Best Practices + +- Validate input with Zod +- Return proper status codes +- Handle errors gracefully +- Use Edge runtime when possible + +--- + +## 5. Performance Principles + +### Image Optimization + +- Use next/image component +- Set priority for above-fold +- Provide blur placeholder +- Use responsive sizes + +### Bundle Optimization + +- Dynamic imports for heavy components +- Route-based code splitting (automatic) +- Analyze with bundle analyzer + +--- + +## 6. Metadata + +### Static vs Dynamic + +| Type | Use | +| ---------------- | ----------------- | +| Static export | Fixed metadata | +| generateMetadata | Dynamic per-route | + +### Essential Tags + +- title (50-60 chars) +- description (150-160 chars) +- Open Graph images +- Canonical URL + +--- + +## 7. Caching Strategy + +### Cache Layers + +| Layer | Control | +| ---------- | --------------- | +| Request | fetch options | +| Data | revalidate/tags | +| Full route | route config | + +### Revalidation + +| Method | Use | +| ---------- | -------------------- | +| Time-based | `revalidate: 60` | +| On-demand | `revalidatePath/Tag` | +| No cache | `no-store` | + +--- + +## 8. Server Actions + +### Use Cases + +- Form submissions +- Data mutations +- Revalidation triggers + +### Best Practices + +- Mark with 'use server' +- Validate all inputs +- Return typed responses +- Handle errors + +--- + +## 9. Anti-Patterns + +| ❌ Don't | ✅ Do | +| -------------------------- | ----------------- | +| 'use client' everywhere | Server by default | +| Fetch in client components | Fetch in server | +| Skip loading states | Use loading.tsx | +| Ignore error boundaries | Use error.tsx | +| Large client bundles | Dynamic imports | + +--- + +## 10. Project Structure + +``` +app/ +├── (marketing)/ # Route group +│ └── page.tsx +├── (dashboard)/ +│ ├── layout.tsx # Dashboard layout +│ └── page.tsx +├── api/ +│ └── [resource]/ +│ └── route.ts +└── components/ + └── ui/ +``` + +--- + +> **Remember:** Server Components are the default for a reason. Start there, add client only when needed. diff --git a/.claude/skills/react-19/SKILL.md b/.claude/skills/react-19/SKILL.md new file mode 100644 index 0000000..519ae9f --- /dev/null +++ b/.claude/skills/react-19/SKILL.md @@ -0,0 +1,124 @@ +--- +name: react-19 +description: > + React 19 patterns with React Compiler. + Trigger: When writing React 19 components/hooks in .tsx (React Compiler rules, hook patterns, refs as props). If using Next.js App Router/Server Actions, also use nextjs-15. +license: Apache-2.0 +metadata: + author: prowler-cloud + version: "1.0" + scope: [root, ui] + auto_invoke: "Writing React components" +allowed-tools: Read, Edit, Write, Glob, Grep, Bash, WebFetch, WebSearch, Task +--- + +## No Manual Memoization (REQUIRED) + +```typescript +// ✅ React Compiler handles optimization automatically +function Component({ items }) { + const filtered = items.filter(x => x.active); + const sorted = filtered.sort((a, b) => a.name.localeCompare(b.name)); + + const handleClick = (id) => { + console.log(id); + }; + + return ; +} + +// ❌ NEVER: Manual memoization +const filtered = useMemo(() => items.filter(x => x.active), [items]); +const handleClick = useCallback((id) => console.log(id), []); +``` + +## Imports (REQUIRED) + +```typescript +// ✅ ALWAYS: Named imports +import { useState, useEffect, useRef } from "react"; + +// ❌ NEVER +import React from "react"; +import * as React from "react"; +``` + +## Server Components First + +```typescript +// ✅ Server Component (default) - no directive +export default async function Page() { + const data = await fetchData(); + return ; +} + +// ✅ Client Component - only when needed +"use client"; +export function Interactive() { + const [state, setState] = useState(false); + return ; +} +``` + +## When to use "use client" + +- useState, useEffect, useRef, useContext +- Event handlers (onClick, onChange) +- Browser APIs (window, localStorage) + +## use() Hook + +```typescript +import { use } from "react"; + +// Read promises (suspends until resolved) +function Comments({ promise }) { + const comments = use(promise); + return comments.map(c =>
{c.text}
); +} + +// Conditional context (not possible with useContext!) +function Theme({ showTheme }) { + if (showTheme) { + const theme = use(ThemeContext); + return
Themed
; + } + return
Plain
; +} +``` + +## Actions & useActionState + +```typescript +"use server"; +async function submitForm(formData: FormData) { + await saveToDatabase(formData); + revalidatePath("/"); +} + +// With pending state +import { useActionState } from "react"; + +function Form() { + const [state, action, isPending] = useActionState(submitForm, null); + return ( +
+ +
+ ); +} +``` + +## ref as Prop (No forwardRef) + +```typescript +// ✅ React 19: ref is just a prop +function Input({ ref, ...props }) { + return ; +} + +// ❌ Old way (unnecessary now) +const Input = forwardRef((props, ref) => ); +``` diff --git a/.claude/skills/tailwind-4/SKILL.md b/.claude/skills/tailwind-4/SKILL.md new file mode 100644 index 0000000..66c4f4e --- /dev/null +++ b/.claude/skills/tailwind-4/SKILL.md @@ -0,0 +1,199 @@ +--- +name: tailwind-4 +description: > + Tailwind CSS 4 patterns and best practices. + Trigger: When styling with Tailwind (className, variants, cn()), especially when dynamic styling or CSS variables are involved (no var() in className). +license: Apache-2.0 +metadata: + author: prowler-cloud + version: "1.0" + scope: [root, ui] + auto_invoke: "Working with Tailwind classes" +allowed-tools: Read, Edit, Write, Glob, Grep, Bash, WebFetch, WebSearch, Task +--- + +## Styling Decision Tree + +``` +Tailwind class exists? → className="..." +Dynamic value? → style={{ width: `${x}%` }} +Conditional styles? → cn("base", condition && "variant") +Static only? → className="..." (no cn() needed) +Library can't use class?→ style prop with var() constants +``` + +## Critical Rules + +### Never Use var() in className + +```typescript +// ❌ NEVER: var() in className +
+
+ +// ✅ ALWAYS: Use Tailwind semantic classes +
+
+``` + +### Never Use Hex Colors + +```typescript +// ❌ NEVER: Hex colors in className +

+

+ +// ✅ ALWAYS: Use Tailwind color classes +

+

+``` + +## The cn() Utility + +```typescript +import { clsx } from "clsx"; +import { twMerge } from "tailwind-merge"; + +export function cn(...inputs: ClassValue[]) { + return twMerge(clsx(inputs)); +} +``` + +### When to Use cn() + +```typescript +// ✅ Conditional classes +
+ +// ✅ Merging with potential conflicts + + ); +} +``` + +**Example: preload when feature flag is enabled** + +```tsx +function FlagsProvider({ children, flags }: Props) { + useEffect(() => { + if (flags.editorEnabled && typeof window !== "undefined") { + void import("./monaco-editor").then((mod) => mod.init()); + } + }, [flags.editorEnabled]); + + return {children}; +} +``` + +The `typeof window !== 'undefined'` check prevents bundling preloaded modules for SSR, optimizing server bundle size and build speed. + +--- + +## 3. Server-Side Performance + +**Impact: HIGH** + +Optimizing server-side rendering and data fetching eliminates server-side waterfalls and reduces response times. + +### 3.1 Cross-Request LRU Caching + +**Impact: HIGH (caches across requests)** + +`React.cache()` only works within one request. For data shared across sequential requests (user clicks button A then button B), use an LRU cache. + +**Implementation:** + +```typescript +import { LRUCache } from "lru-cache"; + +const cache = new LRUCache({ + max: 1000, + ttl: 5 * 60 * 1000 // 5 minutes +}); + +export async function getUser(id: string) { + const cached = cache.get(id); + if (cached) return cached; + + const user = await db.user.findUnique({ where: { id } }); + cache.set(id, user); + return user; +} + +// Request 1: DB query, result cached +// Request 2: cache hit, no DB query +``` + +Use when sequential user actions hit multiple endpoints needing the same data within seconds. + +**With Vercel's [Fluid Compute](https://vercel.com/docs/fluid-compute):** LRU caching is especially effective because multiple concurrent requests can share the same function instance and cache. This means the cache persists across requests without needing external storage like Redis. + +**In traditional serverless:** Each invocation runs in isolation, so consider Redis for cross-process caching. + +Reference: + +### 3.2 Minimize Serialization at RSC Boundaries + +**Impact: HIGH (reduces data transfer size)** + +The React Server/Client boundary serializes all object properties into strings and embeds them in the HTML response and subsequent RSC requests. This serialized data directly impacts page weight and load time, so **size matters a lot**. Only pass fields that the client actually uses. + +**Incorrect: serializes all 50 fields** + +```tsx +async function Page() { + const user = await fetchUser(); // 50 fields + return ; +} + +("use client"); +function Profile({ user }: { user: User }) { + return
{user.name}
; // uses 1 field +} +``` + +**Correct: serializes only 1 field** + +```tsx +async function Page() { + const user = await fetchUser(); + return ; +} + +("use client"); +function Profile({ name }: { name: string }) { + return
{name}
; +} +``` + +### 3.3 Parallel Data Fetching with Component Composition + +**Impact: CRITICAL (eliminates server-side waterfalls)** + +React Server Components execute sequentially within a tree. Restructure with composition to parallelize data fetching. + +**Incorrect: Sidebar waits for Page's fetch to complete** + +```tsx +export default async function Page() { + const header = await fetchHeader(); + return ( +
+
{header}
+ +
+ ); +} + +async function Sidebar() { + const items = await fetchSidebarItems(); + return ; +} +``` + +**Correct: both fetch simultaneously** + +```tsx +async function Header() { + const data = await fetchHeader(); + return
{data}
; +} + +async function Sidebar() { + const items = await fetchSidebarItems(); + return ; +} + +export default function Page() { + return ( +
+
+ +
+ ); +} +``` + +**Alternative with children prop:** + +```tsx +async function Header() { + const data = await fetchHeader(); + return
{data}
; +} + +async function Sidebar() { + const items = await fetchSidebarItems(); + return ; +} + +function Layout({ children }: { children: ReactNode }) { + return ( +
+
+ {children} +
+ ); +} + +export default function Page() { + return ( + + + + ); +} +``` + +### 3.4 Per-Request Deduplication with React.cache() + +**Impact: MEDIUM (deduplicates within request)** + +Use `React.cache()` for server-side request deduplication. Authentication and database queries benefit most. + +**Usage:** + +```typescript +import { cache } from "react"; + +export const getCurrentUser = cache(async () => { + const session = await auth(); + if (!session?.user?.id) return null; + return await db.user.findUnique({ + where: { id: session.user.id } + }); +}); +``` + +Within a single request, multiple calls to `getCurrentUser()` execute the query only once. + +**Avoid inline objects as arguments:** + +`React.cache()` uses shallow equality (`Object.is`) to determine cache hits. Inline objects create new references each call, preventing cache hits. + +**Incorrect: always cache miss** + +```typescript +const getUser = cache(async (params: { uid: number }) => { + return await db.user.findUnique({ where: { id: params.uid } }); +}); + +// Each call creates new object, never hits cache +getUser({ uid: 1 }); +getUser({ uid: 1 }); // Cache miss, runs query again +``` + +**Correct: cache hit** + +```typescript +const params = { uid: 1 }; +getUser(params); // Query runs +getUser(params); // Cache hit (same reference) +``` + +If you must pass objects, pass the same reference: + +**Next.js-Specific Note:** + +In Next.js, the `fetch` API is automatically extended with request memoization. Requests with the same URL and options are automatically deduplicated within a single request, so you don't need `React.cache()` for `fetch` calls. However, `React.cache()` is still essential for other async tasks: + +- Database queries (Prisma, Drizzle, etc.) + +- Heavy computations + +- Authentication checks + +- File system operations + +- Any non-fetch async work + +Use `React.cache()` to deduplicate these operations across your component tree. + +Reference: + +### 3.5 Use after() for Non-Blocking Operations + +**Impact: MEDIUM (faster response times)** + +Use Next.js's `after()` to schedule work that should execute after a response is sent. This prevents logging, analytics, and other side effects from blocking the response. + +**Incorrect: blocks response** + +```tsx +import { logUserAction } from "@/app/utils"; + +export async function POST(request: Request) { + // Perform mutation + await updateDatabase(request); + + // Logging blocks the response + const userAgent = request.headers.get("user-agent") || "unknown"; + await logUserAction({ userAgent }); + + return new Response(JSON.stringify({ status: "success" }), { + status: 200, + headers: { "Content-Type": "application/json" } + }); +} +``` + +**Correct: non-blocking** + +```tsx +import { after } from "next/server"; +import { headers, cookies } from "next/headers"; +import { logUserAction } from "@/app/utils"; + +export async function POST(request: Request) { + // Perform mutation + await updateDatabase(request); + + // Log after response is sent + after(async () => { + const userAgent = (await headers()).get("user-agent") || "unknown"; + const sessionCookie = (await cookies()).get("session-id")?.value || "anonymous"; + + logUserAction({ sessionCookie, userAgent }); + }); + + return new Response(JSON.stringify({ status: "success" }), { + status: 200, + headers: { "Content-Type": "application/json" } + }); +} +``` + +The response is sent immediately while logging happens in the background. + +**Common use cases:** + +- Analytics tracking + +- Audit logging + +- Sending notifications + +- Cache invalidation + +- Cleanup tasks + +**Important notes:** + +- `after()` runs even if the response fails or redirects + +- Works in Server Actions, Route Handlers, and Server Components + +Reference: + +--- + +## 4. Client-Side Data Fetching + +**Impact: MEDIUM-HIGH** + +Automatic deduplication and efficient data fetching patterns reduce redundant network requests. + +### 4.1 Deduplicate Global Event Listeners + +**Impact: LOW (single listener for N components)** + +Use `useSWRSubscription()` to share global event listeners across component instances. + +**Incorrect: N instances = N listeners** + +```tsx +function useKeyboardShortcut(key: string, callback: () => void) { + useEffect(() => { + const handler = (e: KeyboardEvent) => { + if (e.metaKey && e.key === key) { + callback(); + } + }; + window.addEventListener("keydown", handler); + return () => window.removeEventListener("keydown", handler); + }, [key, callback]); +} +``` + +When using the `useKeyboardShortcut` hook multiple times, each instance will register a new listener. + +**Correct: N instances = 1 listener** + +```tsx +import useSWRSubscription from "swr/subscription"; + +// Module-level Map to track callbacks per key +const keyCallbacks = new Map void>>(); + +function useKeyboardShortcut(key: string, callback: () => void) { + // Register this callback in the Map + useEffect(() => { + if (!keyCallbacks.has(key)) { + keyCallbacks.set(key, new Set()); + } + keyCallbacks.get(key)!.add(callback); + + return () => { + const set = keyCallbacks.get(key); + if (set) { + set.delete(callback); + if (set.size === 0) { + keyCallbacks.delete(key); + } + } + }; + }, [key, callback]); + + useSWRSubscription("global-keydown", () => { + const handler = (e: KeyboardEvent) => { + if (e.metaKey && keyCallbacks.has(e.key)) { + keyCallbacks.get(e.key)!.forEach((cb) => cb()); + } + }; + window.addEventListener("keydown", handler); + return () => window.removeEventListener("keydown", handler); + }); +} + +function Profile() { + // Multiple shortcuts will share the same listener + useKeyboardShortcut("p", () => { + /* ... */ + }); + useKeyboardShortcut("k", () => { + /* ... */ + }); + // ... +} +``` + +### 4.2 Use Passive Event Listeners for Scrolling Performance + +**Impact: MEDIUM (eliminates scroll delay caused by event listeners)** + +Add `{ passive: true }` to touch and wheel event listeners to enable immediate scrolling. Browsers normally wait for listeners to finish to check if `preventDefault()` is called, causing scroll delay. + +**Incorrect:** + +```typescript +useEffect(() => { + const handleTouch = (e: TouchEvent) => console.log(e.touches[0].clientX); + const handleWheel = (e: WheelEvent) => console.log(e.deltaY); + + document.addEventListener("touchstart", handleTouch); + document.addEventListener("wheel", handleWheel); + + return () => { + document.removeEventListener("touchstart", handleTouch); + document.removeEventListener("wheel", handleWheel); + }; +}, []); +``` + +**Correct:** + +```typescript +useEffect(() => { + const handleTouch = (e: TouchEvent) => console.log(e.touches[0].clientX); + const handleWheel = (e: WheelEvent) => console.log(e.deltaY); + + document.addEventListener("touchstart", handleTouch, { passive: true }); + document.addEventListener("wheel", handleWheel, { passive: true }); + + return () => { + document.removeEventListener("touchstart", handleTouch); + document.removeEventListener("wheel", handleWheel); + }; +}, []); +``` + +**Use passive when:** tracking/analytics, logging, any listener that doesn't call `preventDefault()`. + +**Don't use passive when:** implementing custom swipe gestures, custom zoom controls, or any listener that needs `preventDefault()`. + +### 4.3 Use SWR for Automatic Deduplication + +**Impact: MEDIUM-HIGH (automatic deduplication)** + +SWR enables request deduplication, caching, and revalidation across component instances. + +**Incorrect: no deduplication, each instance fetches** + +```tsx +function UserList() { + const [users, setUsers] = useState([]); + useEffect(() => { + fetch("/api/users") + .then((r) => r.json()) + .then(setUsers); + }, []); +} +``` + +**Correct: multiple instances share one request** + +```tsx +import useSWR from "swr"; + +function UserList() { + const { data: users } = useSWR("/api/users", fetcher); +} +``` + +**For immutable data:** + +```tsx +import { useImmutableSWR } from "@/lib/swr"; + +function StaticContent() { + const { data } = useImmutableSWR("/api/config", fetcher); +} +``` + +**For mutations:** + +```tsx +import { useSWRMutation } from "swr/mutation"; + +function UpdateButton() { + const { trigger } = useSWRMutation("/api/user", updateUser); + return ; +} +``` + +Reference: + +### 4.4 Version and Minimize localStorage Data + +**Impact: MEDIUM (prevents schema conflicts, reduces storage size)** + +Add version prefix to keys and store only needed fields. Prevents schema conflicts and accidental storage of sensitive data. + +**Incorrect:** + +```typescript +// No version, stores everything, no error handling +localStorage.setItem("userConfig", JSON.stringify(fullUserObject)); +const data = localStorage.getItem("userConfig"); +``` + +**Correct:** + +```typescript +const VERSION = "v2"; + +function saveConfig(config: { theme: string; language: string }) { + try { + localStorage.setItem(`userConfig:${VERSION}`, JSON.stringify(config)); + } catch { + // Throws in incognito/private browsing, quota exceeded, or disabled + } +} + +function loadConfig() { + try { + const data = localStorage.getItem(`userConfig:${VERSION}`); + return data ? JSON.parse(data) : null; + } catch { + return null; + } +} + +// Migration from v1 to v2 +function migrate() { + try { + const v1 = localStorage.getItem("userConfig:v1"); + if (v1) { + const old = JSON.parse(v1); + saveConfig({ theme: old.darkMode ? "dark" : "light", language: old.lang }); + localStorage.removeItem("userConfig:v1"); + } + } catch {} +} +``` + +**Store minimal fields from server responses:** + +```typescript +// User object has 20+ fields, only store what UI needs +function cachePrefs(user: FullUser) { + try { + localStorage.setItem( + "prefs:v1", + JSON.stringify({ + theme: user.preferences.theme, + notifications: user.preferences.notifications + }) + ); + } catch {} +} +``` + +**Always wrap in try-catch:** `getItem()` and `setItem()` throw in incognito/private browsing (Safari, Firefox), when quota exceeded, or when disabled. + +**Benefits:** Schema evolution via versioning, reduced storage size, prevents storing tokens/PII/internal flags. + +--- + +## 5. Re-render Optimization + +**Impact: MEDIUM** + +Reducing unnecessary re-renders minimizes wasted computation and improves UI responsiveness. + +### 5.1 Defer State Reads to Usage Point + +**Impact: MEDIUM (avoids unnecessary subscriptions)** + +Don't subscribe to dynamic state (searchParams, localStorage) if you only read it inside callbacks. + +**Incorrect: subscribes to all searchParams changes** + +```tsx +function ShareButton({ chatId }: { chatId: string }) { + const searchParams = useSearchParams(); + + const handleShare = () => { + const ref = searchParams.get("ref"); + shareChat(chatId, { ref }); + }; + + return ; +} +``` + +**Correct: reads on demand, no subscription** + +```tsx +function ShareButton({ chatId }: { chatId: string }) { + const handleShare = () => { + const params = new URLSearchParams(window.location.search); + const ref = params.get("ref"); + shareChat(chatId, { ref }); + }; + + return ; +} +``` + +### 5.2 Extract to Memoized Components + +**Impact: MEDIUM (enables early returns)** + +Extract expensive work into memoized components to enable early returns before computation. + +**Incorrect: computes avatar even when loading** + +```tsx +function Profile({ user, loading }: Props) { + const avatar = useMemo(() => { + const id = computeAvatarId(user); + return ; + }, [user]); + + if (loading) return ; + return
{avatar}
; +} +``` + +**Correct: skips computation when loading** + +```tsx +const UserAvatar = memo(function UserAvatar({ user }: { user: User }) { + const id = useMemo(() => computeAvatarId(user), [user]); + return ; +}); + +function Profile({ user, loading }: Props) { + if (loading) return ; + return ( +
+ +
+ ); +} +``` + +**Note:** If your project has [React Compiler](https://react.dev/learn/react-compiler) enabled, manual memoization with `memo()` and `useMemo()` is not necessary. The compiler automatically optimizes re-renders. + +### 5.3 Narrow Effect Dependencies + +**Impact: LOW (minimizes effect re-runs)** + +Specify primitive dependencies instead of objects to minimize effect re-runs. + +**Incorrect: re-runs on any user field change** + +```tsx +useEffect(() => { + console.log(user.id); +}, [user]); +``` + +**Correct: re-runs only when id changes** + +```tsx +useEffect(() => { + console.log(user.id); +}, [user.id]); +``` + +**For derived state, compute outside effect:** + +```tsx +// Incorrect: runs on width=767, 766, 765... +useEffect(() => { + if (width < 768) { + enableMobileMode(); + } +}, [width]); + +// Correct: runs only on boolean transition +const isMobile = width < 768; +useEffect(() => { + if (isMobile) { + enableMobileMode(); + } +}, [isMobile]); +``` + +### 5.4 Subscribe to Derived State + +**Impact: MEDIUM (reduces re-render frequency)** + +Subscribe to derived boolean state instead of continuous values to reduce re-render frequency. + +**Incorrect: re-renders on every pixel change** + +```tsx +function Sidebar() { + const width = useWindowWidth(); // updates continuously + const isMobile = width < 768; + return