# Type Synchronization Documentation

## Overview

This library contains shared type definitions used across both TypeScript and Python codebases in the BuzzTrail monorepo. The types are manually synchronized between the two languages to ensure consistency.

## Canonical Source

**TypeScript is the canonical source of truth** for all type definitions.

All types are originally defined in TypeScript under `libs/shared/types/src/lib/` and then manually translated to Python TypedDict equivalents in `shared_types.py`.

## File Structure

### TypeScript Types (Source of Truth)
- `src/lib/supabase.ts` - Database schema types
- `src/lib/api.ts` - API request/response types
- `src/lib/bot.ts` - Bot configuration types

### Python Types (Derived)
- `shared_types.py` - All TypedDict equivalents
- `__init__.py` - Package initialization

## Type Mapping Reference

| TypeScript | Python | Notes |
|------------|--------|-------|
| `string` | `str` | Direct mapping |
| `number` | `int` or `float` | Use `int` for IDs/counts, `float` for decimals |
| `boolean` | `bool` | Direct mapping |
| `T[]` | `List[T]` | Requires `from typing import List` |
| `T \| null` or `T \| undefined` | `Optional[T]` | Use `total=False` in TypedDict for optional fields |
| `'a' \| 'b' \| 'c'` | `Literal['a', 'b', 'c']` | Requires `from typing import Literal` |
| `interface` | `class XYZ(TypedDict):` | Use TypedDict for structure types |
| `Record<K, V>` | `Dict[K, V]` | Generic dictionary type |
| `any` | `Any` | Requires `from typing import Any` |
| `Date` | `datetime` | Use `from datetime import datetime` |
| `void` | `None` | For return types only |

## Optional Fields in TypedDict

TypeScript allows optional fields with `?` syntax. In Python TypedDict, there are two approaches:

### Approach 1: total=False (Recommended)
```python
class MyType(TypedDict, total=False):
    required_field: str  # Still required
    optional_field: str  # Optional
```

Mark which fields are required in comments.

### Approach 2: NotRequired (Python 3.11+)
```python
from typing import Required, NotRequired

class MyType(TypedDict):
    required_field: str
    optional_field: NotRequired[str]
```

We use **Approach 1** for broader Python version compatibility.

## Synchronization Process

### When TypeScript Types Change

1. **Identify Changes**
   - Review TypeScript file diffs
   - Note added/removed/modified interfaces
   - Check for new type aliases

2. **Update Python Types**
   - Open `shared_types.py`
   - Locate corresponding TypedDict
   - Apply same changes using type mapping table
   - Preserve exact field names (including casing)
   - Match optionality exactly

3. **Update Version**
   - Increment version in `shared_types.py` docstring
   - Update "Last synced" date
   - Document changes in this file's changelog

4. **Validate**
   ```bash
   cd libs/shared/types
   mypy shared_types.py --strict
   ```

5. **Commit**
   - Commit TypeScript and Python changes together
   - Use clear commit message: "Sync types: [description of changes]"

### Manual Synchronization Checklist

- [ ] Review all TypeScript type changes since last sync
- [ ] Update corresponding Python TypedDict definitions
- [ ] Verify field name matching (case-sensitive)
- [ ] Verify type mapping correctness
- [ ] Verify optional vs required fields match
- [ ] Update version number and sync date in `shared_types.py`
- [ ] Run mypy validation: `mypy shared_types.py --strict`
- [ ] Update this TYPES.md with any new patterns or notes
- [ ] Commit TypeScript and Python changes together

## Version Tracking

Version format: `MAJOR.MINOR.PATCH`

- **MAJOR**: Breaking changes to existing types
- **MINOR**: New types or non-breaking additions
- **PATCH**: Bug fixes or clarifications

### Changelog

#### v1.0.0 (2025-10-14)
- Initial Python TypedDict definitions
- Complete mapping of all TypeScript types from:
  - `supabase.ts` (11 types)
  - `api.ts` (15 types)
  - `bot.ts` (14 types)
- Total: 40 types synchronized

## Known Differences & Limitations

### 1. Omit and Partial Utility Types

TypeScript's `Omit` and `Partial` utility types don't have direct Python equivalents. For database Insert/Update types in the TypeScript Database schema:

**TypeScript:**
```typescript
Insert: Omit<ConversationSession, 'id' | 'created_at' | 'updated_at'>
```

**Python Equivalent:**
Would require creating separate TypedDict classes for each Insert/Update variant. Currently documented but not fully implemented in Python types.

### 2. Date vs String Types

**TypeScript:** Uses `Date` objects for timestamps in application types (e.g., `ActiveBot.spawnedAt`)

**Python:** Uses `datetime` objects from Python's `datetime` module

**Database:** Both languages use ISO 8601 strings (`str`) for database timestamp fields

### 3. Interface with Methods (Protocols)

TypeScript interfaces with methods (like `BotManager`) should be implemented as Python `Protocol` or `ABC` classes, not TypedDict.

**TypeScript:**
```typescript
export interface BotManager {
  spawnBot(config: BotSpawnConfig): Promise<BotSpawnResult>;
  killBot(botId: string): Promise<void>;
}
```

**Python Equivalent:**
```python
from typing import Protocol, Optional

class BotManager(Protocol):
    def spawnBot(self, config: BotSpawnConfig) -> BotSpawnResult: ...
    def killBot(self, botId: str) -> None: ...
```

This is documented in `shared_types.py` but not included as it's not a data type.

## Validation Commands

### TypeScript
```bash
cd libs/shared/types
npm run type-check
# or
npx tsc --noEmit
```

### Python
```bash
cd libs/shared/types
mypy shared_types.py --strict
```

Both should pass with zero errors after synchronization.

## Usage Examples

See `README.md` for detailed usage examples in both TypeScript and Python.

## Future Improvements

- Consider automated synchronization tools
- Add pre-commit hooks to check for type drift
- Create JSON schema as intermediate representation
- Generate both TypeScript and Python from JSON schema
