TypeScript SDK Reference¶
Overview¶
The HG Content Generation System frontend provides a comprehensive TypeScript SDK for building content generation applications. The SDK includes React hooks, state management, authentication, and API integration utilities.
Architecture Overview¶
The frontend follows a modern React/Next.js architecture with the following key components:
- Hooks: Custom React hooks for data fetching and state management
- Stores: Zustand-based global state management
- Context: React context providers for authentication and app-wide state
- API Routes: Next.js API routes for backend integration
- Types: TypeScript type definitions and interfaces
Key Features¶
- 🔐 Authentication - Supabase-based authentication with session management
- 🏪 State Management - Zustand store with persistence and optimistic updates
- 🪝 Custom Hooks - React Query-based hooks for data fetching
- 🛡️ Type Safety - Comprehensive TypeScript types and validation
- 📡 API Integration - Full integration with CPM, IM, and SMM services
- 🔄 Real-time Updates - WebSocket integration for job status updates
Quick Start¶
Installation¶
The frontend is part of the monorepo and includes all necessary dependencies:
Basic Usage¶
import { useAuth } from '@/src/contexts/AuthContext'
import { useContentStore } from '@/src/stores/useContentStore'
import { useCreateContentRequest } from '@/src/hooks/useCreateContentRequest'
function ContentGenerator() {
const { user } = useAuth()
const { currentClient } = useContentStore()
const createContent = useCreateContentRequest()
const handleGenerate = () => {
createContent.mutate({
topic: "React Best Practices",
content_type: "blog",
keywords: ["react", "javascript", "web development"],
client_id: currentClient.id,
length: "medium",
tone: "professional"
})
}
return (
<button
onClick={handleGenerate}
disabled={createContent.isLoading}
>
{createContent.isLoading ? 'Generating...' : 'Generate Content'}
</button>
)
}
Core Modules¶
1. Authentication (/src/contexts/AuthContext
)¶
Provides authentication state management using Supabase Auth.
Key Components: - useAuth()
- Hook to access authentication state - AuthProvider
- Context provider component - AuthContextType
- TypeScript interface for auth state
Example:
2. Content Store (/src/stores/useContentStore
)¶
Global state management for clients, jobs, and content generation.
Key Features: - Client management and switching - Job tracking and status updates - Persistent client selection - Error handling and loading states
Example:
3. Content Request Hook (/src/hooks/useCreateContentRequest
)¶
React Query mutation hook for creating content generation requests.
Key Features: - Form submission handling - Success/error notifications - Cache invalidation - Navigation to results
Example:
const mutation = useCreateContentRequest()
mutation.mutate({
topic: "AI in Web Development",
content_type: "blog",
keywords: ["ai", "web", "development"],
client_id: "client-id"
})
4. Supabase Client (/lib/supabase
)¶
Configured Supabase clients for different environments and use cases.
Components: - supabase
- Client-side operations with RLS - supabaseAdmin
- Server-side operations with elevated privileges - getUserIdFromRequest()
- Extract user ID from API requests - verifyClientAccess()
- Check user permissions for clients
API Routes¶
Content Generation (/api/content/generate
)¶
Method: POST
Purpose: Create new content generation jobs
Request Body:
{
client_id: string // UUID of the client
content_type: 'blog' | 'social' | 'local' | 'email' | 'landing'
topic: string // Content topic (1-500 chars)
keywords: string[] // SEO keywords (1-10 items)
length?: 'short' | 'medium' | 'long'
tone?: 'professional' | 'casual' | 'friendly' | 'authoritative'
llm_provider?: 'openai' | 'anthropic' | 'google' | 'groq' | 'ollama'
additional_instructions?: string // Max 1000 chars
}
Response:
{
job_id: string // UUID of the created job
status: 'pending' | 'processing' | 'completed'
message?: string // Optional status message
}
Error Responses: - 400
- Invalid request data - 401
- User not authenticated - 403
- Access denied to client - 500
- Internal server error - 502
- External service error - 503
- Service not configured
Type Definitions¶
Core Types (/src/types/index
)¶
interface Client {
id: string
name: string
description?: string
email?: string
company?: string
contact_person?: string
phone?: string
created_at: string
updated_at: string
}
interface Job {
id: string
client_id: string
client_name?: string
content_type: string
topic: string
keywords: string[]
additional_instructions?: string
status: 'pending' | 'processing' | 'completed' | 'failed'
result?: {
content: string
metadata: {
word_count: number
model_used: string
processing_time_ms: number
cost_estimate?: number
}
}
error?: string
created_at: string
updated_at: string
completed_at?: string
}
Error Handling¶
The SDK includes comprehensive error handling patterns:
Hook-Level Error Handling¶
const mutation = useCreateContentRequest()
if (mutation.error) {
console.error('Content generation failed:', mutation.error.message)
}
Store-Level Error Handling¶
const { error, clearError } = useContentStore()
useEffect(() => {
if (error) {
toast.error(error)
clearError()
}
}, [error, clearError])
API Error Responses¶
All API routes return consistent error responses:
Best Practices¶
1. Authentication Checks¶
Always check authentication state before making requests:
2. Error Boundaries¶
Wrap components with error boundaries for graceful error handling:
3. Loading States¶
Provide clear loading indicators during async operations:
4. Optimistic Updates¶
Use store methods for optimistic UI updates:
const { addJob, updateJob } = useContentStore()
// Add job optimistically, then sync with server
addJob(optimisticJob)
Development Setup¶
Environment Variables¶
Required environment variables for the frontend:
# Supabase Configuration
NEXT_PUBLIC_SUPABASE_URL=your_supabase_url
NEXT_PUBLIC_SUPABASE_ANON_KEY=your_anon_key
SUPABASE_SERVICE_KEY=your_service_key
# Service URLs
CPM_SERVICE_URL=http://localhost:8002
OLLAMA_URL=http://localhost:11434
OLLAMA_MODEL=mistral
OLLAMA_ENABLED=false
# Development
NODE_ENV=development
Development Commands¶
# Start development server
npm run dev
# Run tests
npm run test
# Generate TypeScript documentation
npm run docs:generate
# Build for production
npm run build
Generated Documentation¶
This page provides an overview of the TypeScript SDK. For detailed API documentation generated from the codebase, see:
The generated documentation includes: - Detailed function signatures - Parameter descriptions - Return types - Usage examples - Source code links
Support¶
For questions about the TypeScript SDK:
- Check the generated API documentation
- Review the source code and inline comments
- See the test files for usage examples
- Refer to the main system documentation