# Shared Types Library

Cross-language type definitions for the BuzzTrail monorepo, providing type safety across TypeScript and Python codebases.

## Overview

This library contains type definitions for:
- **Database schema** (Supabase tables)
- **API contracts** (Request/response types)
- **Bot configuration** (Bot management types)

Types are defined in TypeScript (canonical source) and mirrored in Python TypedDict format for cross-language consistency.

## Installation & Setup

### TypeScript

```bash
# Install via npm workspace (if using npm workspaces)
npm install @buzztrail/shared-types

# Or reference directly in tsconfig.json
{
  "compilerOptions": {
    "paths": {
      "@buzztrail/shared/types/*": ["libs/shared/types/src/lib/*"]
    }
  }
}
```

### Python

```bash
# Add to requirements.txt or install directly
cd libs/shared/types
pip install -e .

# Or add to pyproject.toml dependencies
# See pyproject.toml for configuration
```

## Usage Examples

### TypeScript Usage

#### Importing Types

```typescript
// Database types
import {
  ConversationSession,
  SlidevDeck,
  ActiveBotRow,
  Database
} from '@buzztrail/shared/types/supabase';

// API types
import {
  GenerateCustomDeckRequest,
  GenerateCustomDeckResponse,
  SpawnScreenshareBotRequest,
  SpawnBotResponse
} from '@buzztrail/shared/types/api';

// Bot types
import {
  BotSpawnConfig,
  ScreenshareBotConfig,
  ActiveBot,
  BotType,
  BotStatus
} from '@buzztrail/shared/types/bot';
```

#### Using Types

```typescript
// Type-safe API request
async function generateDeck(request: GenerateCustomDeckRequest): Promise<GenerateCustomDeckResponse> {
  const response = await fetch('/api/generate-deck', {
    method: 'POST',
    body: JSON.stringify(request)
  });
  return response.json();
}

// Type-safe database query with Supabase
import { createClient } from '@supabase/supabase-js';

const supabase = createClient<Database>(url, key);

const { data, error } = await supabase
  .from('conversation_sessions')
  .select('*')
  .eq('id', sessionId)
  .single();

// data is typed as ConversationSession

// Type-safe bot spawning
const config: BotSpawnConfig = {
  roomUrl: 'https://example.daily.co/room',
  deckUrl: 'https://slides.example.com/deck',
  sessionId: 'session-123',
  botType: 'screenshare'
};
```

### Python Usage

#### Importing Types

```python
# Import all types
from shared_types import (
    # Database types
    ConversationSession,
    SlidevDeck,
    ActiveBotRow,
    ConversationSessionStatus,

    # API types
    GenerateCustomDeckRequest,
    GenerateCustomDeckResponse,
    SpawnScreenshareBotRequest,
    SpawnBotResponse,

    # Bot types
    BotSpawnConfig,
    ScreenshareBotConfig,
    ActiveBot,
    BotType,
    BotStatus
)

# Or import from package
from buzztrail_shared_types import ConversationSession, BotSpawnConfig
```

#### Using Types

```python
# Type-safe function with mypy checking
def create_session(data: ConversationSession) -> str:
    """Create a new conversation session."""
    # mypy will verify all required fields are present
    return data['id']

# Type-safe API request handler
def generate_deck(request: GenerateCustomDeckRequest) -> GenerateCustomDeckResponse:
    """Generate a custom Slidev deck."""
    company = request['company']
    slides = request['slides']

    # ... deck generation logic ...

    return {
        'deck_id': 'deck-123',
        'github_url': 'https://pages.github.com/deck-123',
        'created_at': '2025-10-14T12:00:00Z'
    }

# Type-safe bot configuration
config: BotSpawnConfig = {
    'roomUrl': 'https://example.daily.co/room',
    'deckUrl': 'https://slides.example.com/deck',
    'sessionId': 'session-123',
    'botType': 'screenshare'
}

# Using Literal types for validation
def update_status(session: ConversationSession, new_status: ConversationSessionStatus) -> None:
    """Update session status. mypy will ensure new_status is a valid literal."""
    session['status'] = new_status
    # Valid: 'generating_deck', 'deck_ready', 'bot_active', 'completed', 'error'
    # Invalid: 'other_status' (mypy error)
```

## Import Patterns

### For TypeScript Bots

```typescript
// In tool-forwarder bot
import {
  SpawnTavusToolForwarderRequest,
  BotLifecycleEventPayload,
  TavusToolForwarderBotConfig
} from '@buzztrail/shared/types';

// In screenshare bot
import {
  ScreenshareBotConfig,
  SlideControlCommand,
  ActiveBot
} from '@buzztrail/shared/types';
```

### For Python Bots

```python
# In Python bot services
from shared_types import (
    SpawnTavusToolForwarderRequest,
    BotLifecycleEventPayload,
    TavusToolForwarderBotConfig
)

# Or use relative imports within the package
from .shared_types import ScreenshareBotConfig, SlideControlCommand
```

## Common Patterns

### 1. Database Operations

**TypeScript with Supabase:**
```typescript
import { Database, ConversationSession } from '@buzztrail/shared/types/supabase';
import { createClient } from '@supabase/supabase-js';

const supabase = createClient<Database>(url, key);

// Insert
const newSession: Database['public']['Tables']['conversation_sessions']['Insert'] = {
  tavus_conversation_id: 'tavus-123',
  daily_room_url: 'https://example.daily.co/room',
  status: 'generating_deck'
};

const { data } = await supabase.from('conversation_sessions').insert(newSession);

// Query
const { data: sessions } = await supabase
  .from('conversation_sessions')
  .select('*')
  .eq('status', 'bot_active');
```

**Python with Supabase:**
```python
from shared_types import ConversationSession, ConversationSessionStatus
from supabase import create_client

supabase = create_client(url, key)

# Insert
new_session = {
    'tavus_conversation_id': 'tavus-123',
    'daily_room_url': 'https://example.daily.co/room',
    'status': 'generating_deck'
}

result = supabase.table('conversation_sessions').insert(new_session).execute()

# Query with type annotation
sessions: list[ConversationSession] = (
    supabase.table('conversation_sessions')
    .select('*')
    .eq('status', 'bot_active')
    .execute()
    .data
)
```

### 2. API Request Validation

**TypeScript with Zod:**
```typescript
import { z } from 'zod';
import { GenerateCustomDeckRequest } from '@buzztrail/shared/types/api';

// Create runtime validator from type
const requestSchema = z.object({
  company: z.string(),
  slides: z.array(z.object({
    title: z.string(),
    content: z.string(),
    layout: z.string().optional()
  })),
  template_id: z.string().optional(),
  session_id: z.string().optional()
}) satisfies z.ZodType<GenerateCustomDeckRequest>;

// Validate request
const validated = requestSchema.parse(request);
```

**Python with Pydantic:**
```python
from pydantic import BaseModel
from shared_types import GenerateCustomDeckRequest, SlideData

# Convert TypedDict to Pydantic model for runtime validation
class SlideDataModel(BaseModel):
    title: str
    content: str
    layout: str | None = None

class GenerateCustomDeckRequestModel(BaseModel):
    company: str
    slides: list[SlideDataModel]
    template_id: str | None = None
    session_id: str | None = None

# Validate request
request_data = GenerateCustomDeckRequestModel.model_validate(request)
```

### 3. Bot Lifecycle Management

**TypeScript:**
```typescript
import { ActiveBot, BotStatus, BotLifecycleEvent } from '@buzztrail/shared/types/bot';

class BotTracker {
  private bots: Map<string, ActiveBot> = new Map();

  trackBot(bot: ActiveBot): void {
    this.bots.set(bot.botId, bot);
  }

  updateStatus(botId: string, status: BotStatus): void {
    const bot = this.bots.get(botId);
    if (bot) {
      bot.status = status;
      if (status === 'stopped') {
        bot.stoppedAt = new Date();
      }
    }
  }
}
```

**Python:**
```python
from shared_types import ActiveBot, BotStatus, BotLifecycleEvent
from datetime import datetime

class BotTracker:
    def __init__(self):
        self.bots: dict[str, ActiveBot] = {}

    def track_bot(self, bot: ActiveBot) -> None:
        self.bots[bot['botId']] = bot

    def update_status(self, bot_id: str, status: BotStatus) -> None:
        bot = self.bots.get(bot_id)
        if bot:
            bot['status'] = status
            if status == 'stopped':
                bot['stoppedAt'] = datetime.now()
```

## Best Practices

### 1. Always Use Types
- Import and use shared types for all cross-service communication
- Enable strict type checking (TypeScript: `strict: true`, Python: `mypy --strict`)
- Never use `any` or `Any` unless absolutely necessary

### 2. Keep Types Synchronized
- When modifying types, update BOTH TypeScript and Python versions
- Follow the synchronization process in `TYPES.md`
- Commit TypeScript and Python changes together

### 3. Optional Fields
- Use `?` in TypeScript, `total=False` in Python for optional fields
- Document which fields are required in Python TypedDict classes
- Be explicit about optionality - don't assume

### 4. Literal Types for Constants
- Use Literal types for fixed string/number values
- Better than plain strings - provides autocomplete and validation
- Example: `BotStatus = Literal['spawning', 'running', 'stopping', 'stopped', 'error']`

### 5. Type Exports
- Export all types from index files for easy importing
- Use consistent naming across languages
- Document any language-specific differences

## Type Safety Benefits

### Compile-Time Guarantees
- **TypeScript:** Catch type errors before runtime with `tsc`
- **Python:** Catch type errors before runtime with `mypy`

### IDE Support
- Autocomplete for all fields
- Inline documentation
- Refactoring support
- Jump to definition

### Runtime Safety
- Combine with runtime validators (Zod, Pydantic)
- Validate API requests/responses
- Ensure database schema compliance

## Troubleshooting

### TypeScript Errors

**Error:** `Cannot find module '@buzztrail/shared/types'`
- Check `tsconfig.json` paths configuration
- Verify package is installed in `node_modules`
- Run `npm install` in workspace root

**Error:** `Type 'X' is not assignable to type 'Y'`
- Check field names match exactly (case-sensitive)
- Verify all required fields are present
- Check for optional vs required field mismatches

### Python Errors

**Error:** `ModuleNotFoundError: No module named 'shared_types'`
- Install package: `pip install -e libs/shared/types`
- Check Python path includes package directory
- Verify `__init__.py` exists
- Note: The module was renamed from `types` to `shared_types` to avoid conflicts with Python's built-in `types` module

**Error:** mypy error about incompatible types
- Check field names match TypedDict definition
- Use `total=False` for optional fields
- Verify Literal values match exactly

## Contributing

When adding new types:

1. Define in TypeScript first (canonical source)
2. Create equivalent Python TypedDict
3. Update `TYPES.md` with any special considerations
4. Add usage examples to this README
5. Run validation: `npx tsc --noEmit` and `mypy shared_types.py --strict`
6. Commit both TypeScript and Python changes together

## Links

- [TypeScript Documentation](https://www.typescriptlang.org/docs/)
- [Python TypedDict Documentation](https://docs.python.org/3/library/typing.html#typing.TypedDict)
- [Supabase TypeScript Support](https://supabase.com/docs/guides/api/generating-types)
- [mypy Documentation](https://mypy.readthedocs.io/)

## Version

Current version: **1.0.0**

See `TYPES.md` for version history and synchronization details.
