Tech Stack
Framework
Styling
Data
Animation
AI
Deployment
Key Dependencies
Project Structure
Architecture Overview
Data Flow
Component Interaction Flow
Core Components
1. API Routes (app/api/)
The API layer handles all server-side logic.
/api/analyze - Main Analysis Endpoint
/api/analyze - Main Analysis Endpoint
app/api/analyze/route.tsPurpose: Analyzes GitHub repositories using AIKey files:route.ts- Main POST handler with streamingconfig.ts- API configuration & OpenRouter setuptypes.ts- Request/Response type definitionsvalidators.ts- Input validation with Zodrate-limit.ts- Rate limiting middlewarestream-handler.ts- Server-Sent Events streamingcode-analyzer.ts- Score calculation logicautomation-generator.ts- Automation suggestionsrefactor-generator.ts- Refactoring suggestionsprompt-builder.ts- AI prompt construction
- Validate input (URL, branch)
- Check rate limits (per-minute + daily tier-based)
- Check cache for existing results
- Fetch repo metadata from GitHub
- Fetch file tree and important files
- Analyze code metrics (calculate scores)
- Stream AI analysis via SSE
- Generate automations & refactors
- Cache results
- Burst: In-memory, per IP, 10 requests/minute
- Daily: DB-backed, tier-based (1/3/44 per day for anon/free/pro)
- Server-side LRU cache (100 entries, 1-hour TTL)
- Deduplication for in-flight requests
/api/branches - Branch Fetching
/api/branches - Branch Fetching
app/api/branches/route.tsPurpose: Fetches all branches for a repositoryRequest: GET /api/branches?repo=owner/nameResponse:/api/auth - Authentication
/api/auth - Authentication
app/api/auth/[...nextauth]/route.tsPurpose: NextAuth.js authentication with GitHub OAuthFeatures:- GitHub OAuth login
- Session management
- User account creation via Prisma
- Integration with Polar for subscriptions
2. Main Components
RepoAnalyzer - Main Entry Point
RepoAnalyzer - Main Entry Point
components/repo-analyzer/index.tsxPurpose: Orchestrates the entire analysis UIKey features:- URL input with validation
- Branch selection
- Analysis state management via
useAnalysishook - Tab-based navigation (Overview, Architecture, etc.)
- Loading states and error handling
- Recent analyses tracking
UrlInput- Repository URL inputLoadingSkeleton- Loading state animationAnalysisHeader- Results header with actionsScoreCard- Score visualizationAIInsights- AI-generated insightsFileTree- Repository structure viewerArchitectureDiagram- Architecture visualizationDataFlowDiagram- Mermaid diagramsRefactorsPanel- Refactoring suggestionsAutomationsPanel- Automation suggestions
AnalysisHeader - Results Header
AnalysisHeader - Results Header
components/analysis-header/index.tsxPurpose: Displays repository metadata and actionsFeatures:- Repository name, description, stats
- Branch selector dropdown
- Export actions (PDF, Markdown, Plain Text)
- Share modal trigger
- Tech stack badges
- Folder structure overview
branch-selector.tsx- Branch dropdownsummary-actions.tsx- Export buttonstech-badge.tsx- Technology badgesfolder-card.tsx- Folder stats cardscopy-button.tsx- Copy to clipboard
FileTree - Repository Structure Viewer
FileTree - Repository Structure Viewer
components/file-tree/index.tsxPurpose: Interactive file/folder tree visualizationFeatures:- Collapsible folders
- File icons by language
- Line count & size display
- Language tags
- Syntax highlighting indicators
index.tsx- Main tree containertree-node.tsx- Individual nodes (recursive)file-icon.tsx- File type iconslanguage-tags.tsx- Language badgestypes.ts- Tree data structuresutils.ts- Tree manipulation utilities
ShareModal - Export & Share
ShareModal - Export & Share
3. Context & State Management
AnalysisContext - Global Analysis State
AnalysisContext - Global Analysis State
context/analysis-context.tsxPurpose: Manages analysis state across the appProvides:analyze(url)- Start new analysisanalyzeBranch(branch)- Analyze different branchreset()- Clear current analysisrefresh()- Force re-analysisstatus- Current state (idle, loading, complete, error)result- Analysis resultstier- User subscription tierisCached- Whether result came from cache
ThemeProvider - Dark/Light Mode
ThemeProvider - Dark/Light Mode
context/theme-provider.tsxPurpose: Manages theme state using next-themesFeatures:- System preference detection
- Manual theme toggle
- Persistent theme selection
- CSS variable updates
4. Utilities (lib/)
github.ts - GitHub API Wrapper
github.ts - GitHub API Wrapper
fetchRepoMetadata()- Get repo infofetchRepoTree()- Get file treefetchImportantFiles()- Fetch key files for analysisfetchRepoBranches()- List branchescalculateFileStats()- Calculate metricscreateCompactTreeString()- Format tree for AI
GITHUB_TOKEN env variablepdf-export.ts - PDF Generation
pdf-export.ts - PDF Generation
- Custom styling with brand colors
- Multi-page support
- Embedded charts and diagrams
- Score visualizations
- Insights and recommendations
- File tree rendering
storage.ts - LocalStorage Helpers
storage.ts - LocalStorage Helpers
- Recent analyses tracking (last 10)
- Cache validation with TTL
- Type-safe storage operations
- Automatic cleanup of expired entries
saveToStorage()- Save analysis resultgetFromStorage()- Retrieve cached resultgetRecentAnalyses()- Get recent reposclearStorage()- Clear all cache
server-cache.ts - Server-Side Caching
server-cache.ts - Server-Side Caching
- Max entries: 100
- TTL: 1 hour (3600s)
- Size limit: 50MB
validators.ts - Input Validation
validators.ts - Input Validation
GitHubUrlSchema- Validates GitHub URLsBranchNameSchema- Validates branch namesAnalyzeRequestSchema- API request validation
validateGitHubUrl()- Parse and validate URLextractRepoInfo()- Extract owner/repo from URL
Database Schema
Prisma Schema
Prisma Schema
prisma/schema.prismaModels:User:- Stores authenticated users
- Links to NextAuth Account/Session
- Tracks subscription tier
- Tracks all analysis requests
- Used for rate limiting
- Links to User (if authenticated)
- NextAuth.js OAuth data
- GitHub account linking
Authentication Flow
Rate Limiting Strategy
Burst Rate Limiting (In-Memory)
Burst Rate Limiting (In-Memory)
app/api/analyze/rate-limit.tsLimits:- 10 requests per minute per IP
- Sliding window implementation
- In-memory Map storage
Daily Tier-Based Limiting (Database)
Daily Tier-Based Limiting (Database)
lib/analysis-rate-limit.tsLimits:- Anonymous: 1 analysis/day
- Free tier: 3 analyses/day
- Pro tier: 44 analyses/day
- Counts AnalysisRequest records in last 24h
- Authenticated users tracked by userId
- Anonymous users tracked by IP
- Automatic cleanup of old requests
Performance Optimizations
Server-Side Caching
Request Deduplication
Streaming Responses
Client-Side Cache
Key Patterns
1. Server-Sent Events (SSE) Streaming
The analysis endpoint uses SSE to stream progress updates:2. Custom Hooks Pattern
TheuseAnalysis hook encapsulates all analysis logic:
3. Type-Safe API Responses
All API responses use Zod schemas:Testing Approach
While the current codebase doesn’t include automated tests, here’s the recommended approach for future testing:Component Tests
- Test React components with React Testing Library
- Test user interactions
- Test error states
Common Tasks
Adding a New Score Metric
Adding a New Score Metric
- Update the score calculation in
app/api/analyze/code-analyzer.ts - Add the new score to the
ScoreDatatype inlib/types.ts - Update the
ScoreCardcomponent to display it - Update the PDF export to include it
Adding a New API Endpoint
Adding a New API Endpoint
- Create a new directory in
app/api/ - Add a
route.tsfile with your handler - Define request/response types in
types.ts - Add validation schemas in
validators.ts - Test with curl or Postman
Adding a New UI Component
Adding a New UI Component
- Create component file in appropriate
components/subdirectory - Define prop types interface
- Use Tailwind for styling
- Import and use in parent component
- Add to relevant tab in
RepoAnalyzer
Modifying the AI Prompt
Modifying the AI Prompt
- Edit
app/api/analyze/prompt-builder.ts - Update the
buildPrompt()function - Test with various repository types
- Ensure response format matches expectations