Skip to content

Latest commit

 

History

History
524 lines (423 loc) · 12.2 KB

File metadata and controls

524 lines (423 loc) · 12.2 KB

VibeBuilder Architecture Documentation

This document provides a comprehensive overview of the VibeBuilder application architecture, design patterns, and technical decisions.

High-Level Overview

VibeBuilder is a React Native application built with Expo that enables users to create other React Native applications using AI. The architecture follows clean code principles with clear separation of concerns.

┌─────────────────────────────────────────────────┐
│                  User Interface                  │
│            (React Native Components)             │
└────────────┬────────────────────────────────────┘
             │
┌────────────▼────────────────────────────────────┐
│             Navigation Layer                     │
│        (React Navigation Stack/Tabs)             │
└────────────┬────────────────────────────────────┘
             │
┌────────────▼────────────────────────────────────┐
│           State Management                       │
│         (Zustand Stores)                         │
└────┬───────┬────────┬──────────────────────────┘
     │       │        │
┌────▼───┐ ┌▼────┐ ┌─▼──────┐
│  Auth  │ │ App │ │   UI   │
│  Store │ │Store│ │  Store │
└────┬───┘ └┬────┘ └─┬──────┘
     │      │       │
┌────▼──────▼───────▼──────────────────────────────┐
│              Service Layer                        │
│   (AI, GitHub, Storage, Code Generation)         │
└────────────┬──────────────────────────────────────┘
             │
┌────────────▼────────────────────────────────────┐
│          External Services                       │
│   (GitHub API, AI API, AsyncStorage, SecureStore)│
└──────────────────────────────────────────────────┘

Core Layers

1. Presentation Layer (/src/components, /src/screens)

Purpose: Handle UI rendering and user interaction

Components Structure:

  • Common Components: Reusable UI elements (Button, Card, Input, etc.)
  • Feature Components: Domain-specific components (TemplateCard, AppCard, PhoneMockup)
  • Screens: Full-screen views with business logic

Key Principles:

  • Components are pure and functional
  • Props are fully typed with TypeScript
  • Theme-aware using useTheme() hook
  • Accessibility considerations built-in

2. Navigation Layer (/src/navigation)

Purpose: Manage app routing and screen transitions

Structure:

  • Stack Navigator: For screens requiring back navigation
  • Tab Navigator: For main app sections
  • Nested Navigation: Tabs within Stack for complex flows

Key Features:

  • Type-safe navigation with TypeScript
  • Authentication-aware routing
  • Deep linking support ready
  • Screen-specific options and headers

3. State Management Layer (/src/store)

Purpose: Manage global application state

Stores:

AuthStore

  • User authentication state
  • Session management
  • GitHub connection status
  • Secure token storage

AppStore

  • Generated apps collection
  • Template library
  • Current app selection
  • CRUD operations for apps

UIStore

  • Theme preference (light/dark/system)
  • Toast notifications
  • Modal state
  • Loading states

State Architecture:

Store
├── State (data)
├── Computed Values (derived state)
└── Actions (state modifiers)

4. Service Layer (/src/services)

Purpose: Business logic and external integrations

AI Service (/services/ai)

  • App code generation
  • Template customization
  • Code enhancement
  • Prompt processing

Current Implementation: Mock responses for development Production: Replace with actual AI API integration

GitHub Service (/services/github)

  • Repository creation
  • Code commits
  • Organization management
  • Authentication

Security: Uses Octokit with secure token storage

Storage Service (/services/storage)

  • Secure credential storage (expo-secure-store)
  • App data caching (AsyncStorage)
  • Type-safe storage operations

Code Generator (/services/ai/codeGenerator)

  • React Native code generation
  • Expo configuration creation
  • Dependency management
  • File structure generation

5. Utility Layer (/src/utils, /src/hooks)

Purpose: Shared utilities and custom hooks

Utils:

  • validation.ts: Input validation and sanitization
  • helpers.ts: Common helper functions (date formatting, text truncation, etc.)

Hooks:

  • useTheme(): Theme access and management
  • useAppGeneration(): App generation workflow
  • Standard React hooks for component logic

Data Flow

App Generation Flow

User Input (Prompt)
    │
    ▼
Validation & Sanitization
    │
    ▼
AI Service (generateApp)
    │
    ├──▶ Code Generation
    │    └──▶ AppCode object
    │
    ├──▶ Preview Generation
    │    └──▶ PreviewData object
    │
    └──▶ Suggestions Generation
         └──▶ String array
    │
    ▼
GitHub Service (optional)
    │
    ├──▶ Create Repository
    └──▶ Commit Code
    │
    ▼
AppStore (addApp)
    │
    └──▶ Persist to AsyncStorage
    │
    ▼
Navigation to AppDetail

Template Remix Flow

Template Selection
    │
    ▼
Template Data Retrieval
    │
    ▼
User Customization (optional)
    │
    ▼
AI Service (remixApp)
    │
    ├──▶ Base Template Code
    └──▶ Apply Modifications
    │
    ▼
[Same as App Generation Flow]

Security Architecture

Authentication

User Credentials
    │
    ▼
Validation (client-side)
    │
    ▼
Hash/Encrypt (in production)
    │
    ▼
Secure Storage (expo-secure-store)
    │
    ├──▶ USER_TOKEN
    ├──▶ GITHUB_TOKEN
    └──▶ USER_DATA (AsyncStorage)

Data Protection

  1. Sensitive Data:

    • Stored in expo-secure-store (encrypted)
    • Never logged or exposed
    • Auto-cleared on logout
  2. User Input:

    • Validated with strict rules
    • Sanitized to prevent injection
    • Length limits enforced
  3. GitHub Tokens:

    • Encrypted at rest
    • Used only in secure context
    • Revocable through settings

Type System

Core Types

// User and Authentication
User
AuthState

// Apps and Templates
GeneratedApp
AppTemplate
AppCode
AppPreviewData

// Navigation
RootStackParamList
MainTabParamList

// API
AIGenerationRequest
AIGenerationResponse
APIResponse<T>

// Store
AppState
UIState

Type Safety Flow

User Input
    │
    ▼
Runtime Validation
    │
    ▼
TypeScript Compilation
    │
    ▼
Type-Safe State Update
    │
    ▼
Type-Safe Rendering

Component Patterns

Container/Presenter Pattern

// Container (Screen)
export function HomeScreen() {
  const { generateApp, isGenerating } = useAppGeneration();
  const [prompt, setPrompt] = useState('');

  const handleGenerate = async () => {
    await generateApp(prompt);
  };

  return <HomeView {...{ prompt, setPrompt, handleGenerate, isGenerating }} />;
}

// Presenter (Component)
function HomeView({ prompt, setPrompt, handleGenerate, isGenerating }) {
  return (
    <View>
      <Input value={prompt} onChangeText={setPrompt} />
      <Button onPress={handleGenerate} loading={isGenerating} />
    </View>
  );
}

Custom Hook Pattern

export function useAppGeneration() {
  const [isGenerating, setIsGenerating] = useState(false);
  const { addApp } = useAppStore();

  const generateApp = useCallback(async (prompt: string) => {
    setIsGenerating(true);
    try {
      const result = await aiService.generateApp({ prompt });
      await addApp(result);
      return result;
    } finally {
      setIsGenerating(false);
    }
  }, [addApp]);

  return { generateApp, isGenerating };
}

Performance Considerations

Optimization Strategies

  1. State Updates:

    • Zustand for efficient re-renders
    • Selective subscriptions
    • Computed values cached
  2. Navigation:

    • Native stack for performance
    • Lazy loading of screens
    • Optimized transitions
  3. Lists:

    • FlatList for large datasets
    • Proper keyExtractor
    • Item separation
  4. Images:

    • Lazy loading
    • Proper resizeMode
    • Cached network images
  5. Code Generation:

    • Async operations
    • Progress indicators
    • Cancelable operations

Error Handling

Error Flow

Error Occurs
    │
    ▼
Caught in try/catch
    │
    ▼
Logged (console.error)
    │
    ▼
User-Friendly Message
    │
    ├──▶ Toast Notification
    └──▶ Error State in UI
    │
    ▼
Recovery Options Offered

Error Categories

  1. Network Errors: Retry with exponential backoff
  2. Validation Errors: Inline form feedback
  3. GitHub Errors: Fallback to local storage
  4. Generation Errors: Offer retry or template alternative

Scalability Considerations

Current Scale

  • Single user device
  • Local data storage
  • Client-side generation

Production Scale

  • Multi-user backend
  • Cloud storage
  • Server-side generation
  • Caching layer
  • Load balancing

Database Schema (Future)

users
  - id, email, name, github_username, created_at

apps
  - id, user_id, name, description, code_json, status, created_at

templates
  - id, name, category, code_json, remix_count, rating

app_versions
  - id, app_id, version, code_json, created_at

Testing Strategy

Unit Tests

  • Utility functions
  • Validation logic
  • Store actions
  • Service methods

Integration Tests

  • Component with hooks
  • Store with services
  • Navigation flows
  • API integrations

E2E Tests

  • User registration
  • App generation
  • Template remix
  • GitHub integration

Future Enhancements

Technical Debt

  1. Implement proper error boundaries
  2. Add crash reporting (Sentry)
  3. Implement analytics
  4. Add performance monitoring
  5. Implement proper logging

Feature Additions

  1. Real-time collaboration
  2. Version control for apps
  3. App preview in WebView
  4. Export to Expo Snack
  5. Template marketplace
  6. Cloud sync

Architecture Improvements

  1. Backend API layer
  2. GraphQL for data fetching
  3. WebSocket for real-time features
  4. CDN for assets
  5. Microservices for scaling

Deployment Architecture

Development

Local Machine
    │
    ▼
Expo Dev Server
    │
    ▼
Expo Go App

Production

EAS Build
    │
    ├──▶ iOS Build → App Store
    └──▶ Android Build → Google Play

Monitoring and Observability

Metrics to Track

  • App generation success rate
  • Template remix frequency
  • GitHub connection rate
  • Error rates by type
  • User engagement metrics
  • Performance metrics (load times, render times)

Logging Strategy

  • Info: User actions
  • Warn: Recoverable errors
  • Error: Critical failures
  • Debug: Development only

Conclusion

This architecture provides a solid foundation for building and scaling VibeBuilder. The clean separation of concerns, type safety, and security considerations make it maintainable and extensible.

Key Strengths:

  • Type-safe with TypeScript
  • Modular and testable
  • Security-first approach
  • Scalable patterns
  • Clear data flow

For questions or clarifications, refer to the codebase or contact the development team.