/** * Slidev API Client * * Client for communicating with the Slidev backend (hosted on Railway) * that generates and controls presentations published to GitHub Pages. */ import type { GenerateDeckRequest, GenerateDeckResponse, } from '../../types/slidev'; // Control command type export type ControlCommand = 'next' | 'prev' | 'goto'; // Control command request interface export interface ControlCommandRequest { deckId: string; command: ControlCommand; slideId?: string; } // API error response interface export interface SlidevApiError { error: string; details?: string; statusCode?: number; } // Retry configuration interface export interface RetryConfig { maxRetries: number; baseDelay: number; maxDelay: number; } // API Configuration from environment variables const MOTIA_API_URL = import.meta.env.VITE_MOTIA_API_URL; const SLIDEV_API_KEY = import.meta.env.VITE_SLIDEV_API_KEY; // Default retry configuration const DEFAULT_RETRY_CONFIG: RetryConfig = { maxRetries: 3, baseDelay: 1000, // 1 second maxDelay: 10000, // 10 seconds }; /** * Custom error class for Slidev API errors */ export class SlidevApiException extends Error { constructor( message: string, public statusCode?: number, public details?: string ) { super(message); this.name = 'SlidevApiException'; } } /** * Sleep utility for retry delays */ const sleep = (ms: number): Promise => { return new Promise((resolve) => setTimeout(resolve, ms)); }; /** * Calculate exponential backoff delay */ const calculateBackoff = (attempt: number, config: RetryConfig): number => { const delay = Math.min( config.baseDelay * Math.pow(2, attempt), config.maxDelay ); // Add jitter to prevent thundering herd return delay + Math.random() * 1000; }; /** * Fetch wrapper with retry logic for network failures */ async function fetchWithRetry( url: string, options: RequestInit, config: RetryConfig = DEFAULT_RETRY_CONFIG ): Promise { let lastError: Error | null = null; for (let attempt = 0; attempt <= config.maxRetries; attempt++) { try { const response = await fetch(url, options); // If successful or client error (4xx), return immediately // Only retry on 5xx server errors or network failures if (response.ok || (response.status >= 400 && response.status < 500)) { return response; } // Server error - prepare to retry lastError = new Error(`Server error: ${response.status}`); if (attempt < config.maxRetries) { const delay = calculateBackoff(attempt, config); console.warn( `Request failed (attempt ${attempt + 1}/${config.maxRetries + 1}). ` + `Retrying in ${Math.round(delay)}ms...` ); await sleep(delay); } } catch (error) { // Network error - prepare to retry lastError = error as Error; if (attempt < config.maxRetries) { const delay = calculateBackoff(attempt, config); console.warn( `Network error (attempt ${attempt + 1}/${config.maxRetries + 1}). ` + `Retrying in ${Math.round(delay)}ms...`, error ); await sleep(delay); } } } // All retries exhausted throw new SlidevApiException( `Failed after ${config.maxRetries + 1} attempts: ${lastError?.message}`, undefined, lastError?.message ); } /** * Parse error response from API */ async function parseErrorResponse(response: Response): Promise { try { const error: SlidevApiError = await response.json(); return { error: error.error || 'Unknown error', details: error.details, statusCode: response.status, }; } catch { // If JSON parsing fails, use status text return { error: response.statusText || 'Unknown error', statusCode: response.status, }; } } /** * Generate a new Slidev deck and publish to GitHub Pages * * @param request - Deck generation request with session ID, template, and data * @returns Promise resolving to the deck ID and GitHub Pages URL * @throws {SlidevApiException} If generation fails or API returns an error * * @example * ```typescript * const result = await generateDeck({ * sessionId: 'demo-123', * templateId: 'starter', * data: { * company: 'Acme Corp', * industry: 'SaaS' * } * }); * console.log(result.deckUrl); // https://buzztrail.github.io/buzztrail-presentations/deck-id/ * ``` */ export async function generateDeck( request: GenerateDeckRequest ): Promise { if (!MOTIA_API_URL) { throw new SlidevApiException( 'VITE_MOTIA_API_URL is not configured', undefined, 'Please set the VITE_MOTIA_API_URL environment variable' ); } try { const response = await fetchWithRetry( `${MOTIA_API_URL}/api/slidev/generate`, { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(request), } ); if (!response.ok) { const error = await parseErrorResponse(response); throw new SlidevApiException( error.error || 'Failed to generate deck', error.statusCode, error.details ); } const data: GenerateDeckResponse = await response.json(); // Validate response structure if (!data.deckId || !data.deckUrl) { throw new SlidevApiException( 'Invalid response from server: missing deckId or deckUrl', undefined, 'The API response did not contain the expected fields' ); } // Ensure deck URL is in correct GitHub Pages format if (!data.deckUrl.includes('buzztrail.github.io/buzztrail-presentations/decks/')) { console.warn( 'Deck URL does not match expected GitHub Pages format (should include /decks/):', data.deckUrl ); } return data; } catch (error) { if (error instanceof SlidevApiException) { throw error; } // Wrap unexpected errors throw new SlidevApiException( 'An unexpected error occurred while generating the deck', undefined, error instanceof Error ? error.message : String(error) ); } } /** * Send a control command to navigate a Slidev presentation * * @param deckId - Unique identifier of the deck to control * @param command - Navigation command ('next', 'prev', or 'goto') * @param slideId - Optional slide ID for 'goto' command * @throws {SlidevApiException} If command fails or API returns an error * * @example * ```typescript * // Navigate to next slide * await sendControlCommand('deck-123', 'next'); * * // Navigate to previous slide * await sendControlCommand('deck-123', 'prev'); * * // Go to specific slide * await sendControlCommand('deck-123', 'goto', 'slide-5'); * ``` */ export async function sendControlCommand( deckId: string, command: ControlCommand, slideId?: string ): Promise { if (!MOTIA_API_URL) { throw new SlidevApiException( 'VITE_MOTIA_API_URL is not configured', undefined, 'Please set the VITE_MOTIA_API_URL environment variable' ); } if (!SLIDEV_API_KEY) { throw new SlidevApiException( 'VITE_SLIDEV_API_KEY is not configured', undefined, 'Please set the VITE_SLIDEV_API_KEY environment variable' ); } // Validate command if (!['next', 'prev', 'goto'].includes(command)) { throw new SlidevApiException( `Invalid command: ${command}`, 400, 'Command must be "next", "prev", or "goto"' ); } // Validate slideId for goto command if (command === 'goto' && !slideId) { throw new SlidevApiException( 'slideId is required for "goto" command', 400, 'Please provide a slideId when using the "goto" command' ); } const requestBody: ControlCommandRequest = { deckId, command, slideId, }; try { const response = await fetchWithRetry( `${MOTIA_API_URL}/api/slidev/control`, { method: 'POST', headers: { 'Content-Type': 'application/json', 'x-api-key': SLIDEV_API_KEY, }, body: JSON.stringify(requestBody), } ); if (!response.ok) { const error = await parseErrorResponse(response); throw new SlidevApiException( error.error || 'Failed to send control command', error.statusCode, error.details ); } // Success - command sent } catch (error) { if (error instanceof SlidevApiException) { throw error; } // Wrap unexpected errors throw new SlidevApiException( 'An unexpected error occurred while sending the control command', undefined, error instanceof Error ? error.message : String(error) ); } } /** * Validate that the API is properly configured * * @returns Object with configuration status */ export function validateApiConfig(): { isValid: boolean; errors: string[]; } { const errors: string[] = []; if (!MOTIA_API_URL) { errors.push('VITE_MOTIA_API_URL is not configured'); } if (!SLIDEV_API_KEY) { errors.push('VITE_SLIDEV_API_KEY is not configured'); } return { isValid: errors.length === 0, errors, }; }