# Tara Domain - Developer Guide

Tara is a meditation and mindfulness platform providing guided meditations,
structured courses, ambient sounds, progress tracking, achievements, and
subscription management. The platform consists of a RESTful API server, a
Next.js progressive web application, and an Expo/React Native mobile
application, all backed by a PostgreSQL database and Redis cache.

---

## Prerequisites

### Required Software

| Software   | Minimum Version | Purpose                              |
| ---------- | --------------- | ------------------------------------ |
| Node.js    | >= 20.0.0       | Runtime for API and web server       |
| pnpm       | >= 10.0.0       | Package manager (monorepo workspace) |
| Docker     | >= 24.0         | Infrastructure (PostgreSQL, Redis)   |
| TypeScript | ^6.0.3          | Type checking and compilation        |
| Git        | >= 2.40         | Version control                      |

### For Mobile Development

| Software       | Version | Purpose              | Installation                                           |
| -------------- | ------- | -------------------- | ------------------------------------------------------ |
| Expo CLI       | Latest  | React Native tooling | `npm install -g expo-cli`                              |
| EAS CLI        | >= 7.0  | Expo build service   | `npm install -g eas-cli`                               |
| Xcode          | 15+     | iOS Simulator        | Mac App Store                                          |
| Android Studio | Latest  | Android Emulator     | [developer.android.com](https://developer.android.com) |
| Maestro        | Latest  | Mobile E2E testing   | `brew install maestro`                                 |

### For Testing

| Software   | Version | Purpose          | Installation                    |
| ---------- | ------- | ---------------- | ------------------------------- |
| Playwright | Latest  | Web E2E testing  | `pnpm nx e2e:install @tara/web` |
| k6         | Latest  | API load testing | `brew install k6`               |

---

## Project Structure

```
apps/tara/
  api/                 # REST API server (Hono + Drizzle ORM)
  web/                 # Next.js 14 PWA with i18n (next-intl)
  mobile/              # Expo/React Native app (iOS + Android)
  content/             # Static content catalog (meditations, courses, sounds, teachers)
  docs/                # App store checklists, legal docs, marketing copy

libs/tara/
  analytics/           # Analytics event tracking (@tara/analytics)
  config/              # Configuration
  content/             # Content hooks and helpers (@tara/content)
  database/            # Prisma schema and client (@tara/database)
  features/            # Feature flags
  monitoring/          # Application monitoring (@tara/monitoring)
  ui/                  # Shared UI components (@tara/ui)

libs/meditation/       # Cross-platform meditation libraries
  analytics/           # Meditation-specific analytics
  breathing/           # Breathing exercise engine (@oshun/meditation-breathing)
  core/                # Core meditation types and utilities
  offline/             # Offline download manager (@oshun/meditation-offline)
  player/              # Audio player abstraction (@oshun/meditation-player)
  progress/            # Progress tracking (@oshun/meditation-progress)
  session/             # Session management (@oshun/meditation-session)
  timer/               # Meditation timer (@oshun/meditation-timer)
```

### Application Roles

| Application | Framework          | Purpose                                     |
| ----------- | ------------------ | ------------------------------------------- |
| `api`       | Hono 4 + Drizzle   | REST API with OpenAPI docs and JWT auth     |
| `web`       | Next.js 14 + React | SSR/PWA web client with i18n                |
| `mobile`    | Expo 51 + RN 0.74  | Native iOS and Android mobile app           |
| `content`   | Static JSON/YAML   | Content catalog for meditations and courses |

### Library Roles

| Library            | Package Name                  | Layer  | Purpose                                    |
| ------------------ | ----------------------------- | ------ | ------------------------------------------ |
| `@tara/database`   | `libs/tara/database`          | data   | Prisma schema, client, and generated types |
| `@tara/ui`         | `libs/tara/ui`                | ui     | Shared React components and design tokens  |
| `@tara/content`    | `libs/tara/content`           | domain | Content hooks (collections, courses)       |
| `@tara/analytics`  | `libs/tara/analytics`         | domain | Event tracking and analytics               |
| `@tara/monitoring` | `libs/tara/monitoring`        | infra  | Application monitoring and observability   |
| Breathing          | `@oshun/meditation-breathing` | core   | Breathing exercise patterns and engine     |
| Player             | `@oshun/meditation-player`    | core   | Cross-platform audio player                |
| Timer              | `@oshun/meditation-timer`     | core   | Meditation timer with intervals            |
| Session            | `@oshun/meditation-session`   | domain | Session lifecycle management               |
| Offline            | `@oshun/meditation-offline`   | domain | Download manager for offline access        |
| Progress           | `@oshun/meditation-progress`  | domain | Streak and progress calculations           |

---

## Local Development Setup

### 1. Start Infrastructure

Tara requires PostgreSQL and Redis. Both are provided by the monorepo Docker
Compose configuration.

```bash
# Start core infrastructure (PostgreSQL + Redis)
docker compose -f docker/docker-compose.dev.yml up -d

# Verify services are running
docker compose -f docker/docker-compose.dev.yml ps
```

This starts:

- **PostgreSQL** (port 5432) with the `oshun_dev` database (used by Tara)
- **Redis** (port 6379) for session caching, rate limiting, and feature flags
- **MinIO** (ports 9000/9001) for S3-compatible audio/image storage

### 2. Install Dependencies

```bash
pnpm install
```

### 3. Set Environment Variables

The root `.env` file contains defaults for local development. Key variables used
by Tara services:

| Variable                   | Default                                                 | Used By          |
| -------------------------- | ------------------------------------------------------- | ---------------- |
| `TARA_DATABASE_URL`        | `postgresql://oshun:oshun_dev@localhost:5432/oshun_dev` | `@tara/database` |
| `DATABASE_URL`             | `postgresql://oshun:oshun_dev@localhost:5432/oshun_dev` | API (Drizzle)    |
| `REDIS_URL`                | `redis://localhost:6379`                                | API cache        |
| `PORT`                     | `3001`                                                  | API server       |
| `HOST`                     | `0.0.0.0`                                               | API server       |
| `CORS_ORIGIN`              | `*`                                                     | API CORS         |
| `NODE_ENV`                 | `development`                                           | All services     |
| `NEXT_PUBLIC_API_BASE_URL` | `http://localhost:8080`                                 | Web client       |
| `NEXT_PUBLIC_WS_URL`       | `ws://localhost:8080`                                   | Web WebSocket    |
| `NEXT_PUBLIC_CDN_URL`      | (empty)                                                 | Web CDN prefix   |
| `EXPO_PUBLIC_API_URL`      | `https://api.tara.app`                                  | Mobile client    |

### 4. Database Setup (Prisma)

The Tara database uses Prisma ORM with a PostgreSQL schema defined at
`libs/tara/database/prisma/schema.prisma`.

```bash
# Generate the Prisma client
pnpm nx run @tara/database:prisma:generate

# Run database migrations (development mode - creates migration if needed)
pnpm nx run @tara/database:prisma:migrate:dev

# Or push the schema directly for rapid iteration (no migration file created)
cd libs/tara/database && npx prisma db push

# Open Prisma Studio to browse data
pnpm nx run @tara/database:prisma:studio
```

### 5. Seed the Database

```bash
# Seed with standard content (meditations, courses, teachers, sounds)
pnpm nx run @tara/database:db:seed

# Seed with test fixtures
pnpm nx run @tara/database:db:seed:test
```

---

## Running Services

### API Server

The Tara API is a Hono-based REST server running on port 3001.

```bash
# Development with hot reload (tsx watch)
pnpm nx serve @tara/api

# Alternative: run directly from the app directory
cd apps/tara/api && pnpm dev
```

Once running, the following endpoints are available:

| URL                                         | Description               |
| ------------------------------------------- | ------------------------- |
| `http://localhost:3001/`                    | API root (service info)   |
| `http://localhost:3001/health`              | Health check (DB + Redis) |
| `http://localhost:3001/ready`               | Readiness probe           |
| `http://localhost:3001/api/docs`            | Swagger UI                |
| `http://localhost:3001/api/v1/openapi.json` | OpenAPI 3.1 specification |
| `http://localhost:3001/api/v1`              | API version info          |

**API Route Summary:**

| Route Prefix              | Auth Required | Description                              |
| ------------------------- | ------------- | ---------------------------------------- |
| `/api/v1/auth`            | No            | Registration, login, password reset      |
| `/api/v1/users`           | Yes           | User profile and preferences             |
| `/api/v1/meditations`     | Optional      | Meditation content catalog               |
| `/api/v1/courses`         | Partial       | Course listing (public), progress (auth) |
| `/api/v1/teachers`        | No            | Teacher profiles                         |
| `/api/v1/collections`     | No            | Curated content collections              |
| `/api/v1/search`          | No            | Full-text content search                 |
| `/api/v1/sessions`        | Yes           | Meditation session tracking              |
| `/api/v1/progress`        | Yes           | User stats, streaks, milestones          |
| `/api/v1/achievements`    | Yes           | Achievement badges                       |
| `/api/v1/favorites`       | Yes           | Favorite meditations and courses         |
| `/api/v1/history`         | Yes           | Listening history                        |
| `/api/v1/downloads`       | Yes           | Offline content management               |
| `/api/v1/subscription`    | Partial       | Subscription management + webhook        |
| `/api/v1/notifications`   | Yes           | Push notification preferences            |
| `/api/v1/analytics`       | Partial       | Event tracking and experiments           |
| `/api/v1/recommendations` | No            | Personalized suggestions                 |

**Key middleware stack (applied in order):**

1. `secureHeaders` - Security response headers
2. `cors` - CORS with configurable origin
3. `logger` - Request logging
4. `timing` - Server-Timing headers
5. `prettyJSON` - Pretty-printed JSON (development only)
6. `requestIdMiddleware` - Unique request ID (`tara_` prefix)
7. `rateLimitMiddleware` - Rate limiting on `/api/*` routes
8. `authMiddleware` - JWT authentication (per-route)

### Web Application

The Tara web client is a Next.js 14 application with SSR, PWA support, and
internationalization via `next-intl`.

```bash
# Development server (port 3001)
pnpm nx dev @tara/web

# Or run directly
cd apps/tara/web && pnpm dev
```

**Key features:**

- Server-side rendering with Next.js App Router
- Internationalization with `next-intl` (locale-based routing: `/en/`, `/es/`,
  etc.)
- UI built with Radix UI primitives, Tailwind CSS, and `@tara/ui` components
- State management with Zustand and TanStack Query
- Animations with Framer Motion
- PWA with offline support and service worker
- Storybook for component development (port 6007)

**Web app pages:**

| Route                             | Description                         |
| --------------------------------- | ----------------------------------- |
| `/[locale]/`                      | Landing / home page                 |
| `/[locale]/meditate`              | Meditation catalog                  |
| `/[locale]/meditate/[id]`         | Individual meditation detail        |
| `/[locale]/play/[id]`             | Audio player page                   |
| `/[locale]/courses`               | Course catalog                      |
| `/[locale]/courses/[id]`          | Individual course detail            |
| `/[locale]/timer`                 | Meditation timer                    |
| `/[locale]/library`               | User library (favorites, downloads) |
| `/[locale]/progress`              | Progress dashboard                  |
| `/[locale]/search`                | Content search                      |
| `/[locale]/teachers/[id]`         | Teacher profile                     |
| `/[locale]/settings/profile`      | Profile settings                    |
| `/[locale]/settings/security`     | Security settings                   |
| `/[locale]/settings/subscription` | Subscription settings               |
| `/[locale]/subscription`          | Subscription plans and billing      |
| `/[locale]/login`                 | Login                               |
| `/[locale]/signup`                | Registration                        |

### Mobile Application

The Tara mobile app is built with Expo 51 and React Native 0.74, using Expo
Router for file-based navigation.

```bash
# Start the Expo development server
cd apps/tara/mobile && pnpm start

# Start with iOS Simulator
cd apps/tara/mobile && pnpm ios

# Start with Android Emulator
cd apps/tara/mobile && pnpm android
```

**Mobile app screens (Expo Router file-based routing):**

| Tab / Route       | Description          |
| ----------------- | -------------------- |
| `(tabs)/index`    | Home feed            |
| `(tabs)/meditate` | Meditation catalog   |
| `(tabs)/timer`    | Meditation timer     |
| `(tabs)/progress` | Progress and streaks |
| `(tabs)/profile`  | User profile         |
| `meditation/[id]` | Meditation detail    |
| `player/[id]`     | Audio player         |
| `courses`         | Course catalog       |
| `course/*`        | Course detail        |
| `search`          | Content search       |
| `library`         | User library         |
| `breathing`       | Breathing exercises  |
| `settings`        | App settings         |
| `storage`         | Download management  |
| `(onboarding)/*`  | Onboarding flow      |

**Key mobile dependencies:**

- `expo-av` for audio playback
- `expo-file-system` for offline downloads
- `expo-notifications` for push notifications
- `react-native-purchases` (RevenueCat) for in-app subscriptions
- `react-native-reanimated` for animations
- `zustand` for state management

**EAS Build Profiles:**

| Profile       | Distribution | iOS             | Android       |
| ------------- | ------------ | --------------- | ------------- |
| `development` | internal     | Simulator build | APK (debug)   |
| `preview`     | internal     | Device build    | APK (release) |
| `production`  | store        | App Store build | AAB (release) |

---

## Building

### Build All Tara Projects

```bash
pnpm nx run-many --target=build --projects=tag:scope:tara
```

### Build Individual Projects

```bash
# API (TypeScript via @nx/js:tsc)
pnpm nx build @tara/api
# Output: dist/apps/tara/api/

# Web (Next.js build)
pnpm nx build @tara/web
# Output: apps/tara/web/.next/ and apps/tara/web/out/

# Database library (requires Prisma generate first)
pnpm nx build @tara/database
# Output: dist/libs/tara/database/

# UI library
pnpm nx build @tara/ui
# Output: dist/libs/tara/ui/

# Analytics library
pnpm nx build @tara/analytics
# Output: dist/libs/tara/analytics/

# Content library
pnpm nx build @tara/content
# Output: dist/libs/tara/content/
```

### Build Mobile (EAS)

```bash
cd apps/tara/mobile

# Development build (for simulators)
eas build --profile development --platform ios
eas build --profile development --platform android

# Preview build (for internal testing)
eas build --profile preview --platform all

# Production build (for app stores)
eas build --profile production --platform all
```

---

## Testing

### Test Runner Configuration

| Project           | Runner | Executor          | Config File                            |
| ----------------- | ------ | ----------------- | -------------------------------------- |
| `@tara/api`       | Vitest | `nx:run-commands` | `apps/tara/api/vitest.config.ts`       |
| `@tara/web`       | Vitest | `nx:run-commands` | `apps/tara/web/vitest.config.ts`       |
| `@tara/mobile`    | Jest   | (package script)  | `jest-expo` preset                     |
| `@tara/database`  | Vitest | `@nx/vite:test`   | `libs/tara/database/vitest.config.ts`  |
| `@tara/ui`        | Vitest | `@nx/vite:test`   | `libs/tara/ui/vitest.config.ts`        |
| `@tara/analytics` | Vitest | `@nx/vite:test`   | `libs/tara/analytics/vitest.config.ts` |

### Running Tests

```bash
# Run all Tara tests
pnpm nx run-many --target=test --projects=tag:scope:tara

# Individual project tests
pnpm nx test @tara/api
pnpm nx test @tara/web
pnpm nx test @tara/database
pnpm nx test @tara/ui

# Mobile tests
cd apps/tara/mobile && pnpm test

# Watch mode
cd apps/tara/api && pnpm test:watch
cd apps/tara/web && pnpm test:watch

# Coverage
cd apps/tara/web && pnpm test:coverage
```

**API test coverage thresholds** (configured in `vitest.config.ts`):

- Lines: 70%
- Functions: 70%
- Branches: 70%
- Statements: 70%

### Integration Tests

```bash
# API integration tests (requires running database and Redis)
cd apps/tara/api && pnpm test:integration

# Run both unit and integration tests
cd apps/tara/api && pnpm test:all
```

### E2E Tests (Web)

The web application uses Playwright for end-to-end testing.

```bash
# Install Playwright browsers (first time)
pnpm nx e2e:install @tara/web

# Run all E2E tests
pnpm nx e2e @tara/web

# Run with UI mode (interactive)
pnpm nx e2e:ui @tara/web

# Run in debug mode
pnpm nx e2e @tara/web --configuration=debug

# Run headed (visible browser)
pnpm nx e2e @tara/web --configuration=headed

# View test report
pnpm nx e2e:report @tara/web

# Generate test code
cd apps/tara/web && pnpm e2e:codegen
```

**E2E page objects** are located in `apps/tara/web/e2e/pages/`:

- `auth.page.ts` - Authentication flows
- `meditation.page.ts` - Meditation browsing
- `progress.page.ts` - Progress dashboard
- `subscription.page.ts` - Subscription management
- `timer.page.ts` - Meditation timer

### E2E Tests (Mobile)

The mobile application uses Maestro for end-to-end testing.

```bash
cd apps/tara/mobile

# Run all mobile E2E flows
pnpm e2e

# Run smoke suite
pnpm e2e:smoke

# Run regression suite
pnpm e2e:regression

# Run specific flow suites
pnpm e2e:auth
pnpm e2e:meditation
pnpm e2e:offline

# Interactive test recording
pnpm e2e:studio
```

### Load Testing

The API includes k6 load test scripts in `apps/tara/api/test/load/`.

```bash
# Run default load test scenario
pnpm nx load-test @tara/api

# Smoke test (quick validation)
pnpm nx load-test:smoke @tara/api

# Stress test (high load)
pnpm nx load-test:stress @tara/api
```

### Linting

```bash
# Lint all Tara projects
pnpm nx run-many --target=lint --projects=tag:scope:tara

# Lint individual projects
pnpm nx lint @tara/api
pnpm nx lint @tara/web
pnpm nx lint @tara/ui

# Type checking (web)
pnpm nx typecheck @tara/web
```

### Storybook (UI Development)

```bash
# Start Storybook dev server (port 6007)
pnpm nx storybook @tara/web

# Build static Storybook
pnpm nx storybook:build @tara/web
```

### Lighthouse (Performance)

```bash
# Run Lighthouse CI audit
pnpm nx lighthouse @tara/web

# Collect Lighthouse metrics
pnpm nx lighthouse:collect @tara/web

# Assert performance thresholds
pnpm nx lighthouse:assert @tara/web

# Run performance tests
pnpm nx test:performance @tara/web
```

---

## Common Development Tasks

### Adding a New API Route

1. Create a route directory under `apps/tara/api/src/routes/<name>/`.

2. Define the route file with Hono route handlers:

   ```typescript
   import { OpenAPIHono } from '@hono/zod-openapi';

   const router = new OpenAPIHono();

   router.get('/', async (c) => {
     // Implementation
     return c.json({ success: true, data: [] });
   });

   export { router as myRouter };
   ```

3. Create an `index.ts` barrel export in the route directory.

4. Mount the router in `apps/tara/api/src/app.ts`:

   ```typescript
   import { myRouter } from './routes/my-route/index.js';
   app.route('/api/v1/my-route', myRouter);
   ```

5. Apply authentication middleware if needed:

   ```typescript
   app.use('/api/v1/my-route/*', authMiddleware());
   ```

### Adding a New Database Model

1. Edit the Prisma schema at `libs/tara/database/prisma/schema.prisma`.

2. Regenerate the Prisma client:

   ```bash
   pnpm nx run @tara/database:prisma:generate
   ```

3. Create a migration:

   ```bash
   pnpm nx run @tara/database:prisma:migrate:dev
   ```

4. Export the new types from `libs/tara/database/src/index.ts`.

5. If the API uses Drizzle ORM for this model, also update
   `apps/tara/api/src/db/schema.ts` with the Drizzle table definition.

### Adding a New Web Page

1. Create a page file under the App Router directory:

   ```
   apps/tara/web/src/app/[locale]/(app)/<name>/page.tsx
   ```

2. The page automatically gets locale-based routing via `next-intl`.

3. Add translations to the relevant message files.

4. Use `@tara/ui` components and `@tara/content` hooks for content fetching.

### Adding Content to the Catalog

The content catalog is stored as static files in `apps/tara/content/`:

- `meditations/` - Guided meditation definitions
- `courses/` - Multi-lesson course definitions
- `teachers/` - Teacher profiles
- `sounds/` - Ambient sound definitions
- `collections/` - Curated content collections
- `schemas/` - Validation schemas for content files

Add new content files following the schema format, then seed the database:

```bash
pnpm nx run @tara/database:db:seed
```

### Working with Subscriptions

The subscription system supports three platforms:

- **Web** (Stripe) - Handled via `/api/v1/subscription/checkout` and webhook
- **iOS** (App Store) - Verified via `/api/v1/subscription/ios/verify`
- **Android** (Google Play) - Verified via `/api/v1/subscription/android/verify`
- **Mobile** (RevenueCat) - The mobile app uses `react-native-purchases`

The webhook endpoint (`/api/v1/subscription/webhook`) is public (no auth) to
allow Stripe to deliver payment events.

---

## Debugging Tips

### API Not Starting

- Verify PostgreSQL is running: `docker ps | grep postgres`
- Verify Redis is running: `docker ps | grep redis`
- Check the `DATABASE_URL` environment variable points to a valid database
- Check that the Prisma client is generated:
  `pnpm nx run @tara/database:prisma:generate`
- Review the `/health` endpoint response for service-level status

### Database Issues

- If migrations are out of sync, reset:
  ```bash
  cd libs/tara/database && npx prisma migrate reset
  ```
- For schema drift during development:
  ```bash
  cd libs/tara/database && npx prisma db push
  ```
- View the database with Prisma Studio:
  ```bash
  pnpm nx run @tara/database:prisma:studio
  ```

### Web Application Issues

- The web app uses `output: 'standalone'` in Next.js config (not static export)
- Ensure workspace packages are listed in `transpilePackages` in
  `next.config.js`
- i18n routing issues: check that the locale prefix matches a supported locale
- CDN/asset issues: verify `NEXT_PUBLIC_CDN_URL` is set correctly (or empty for
  local development)
- Security headers are configured in `next.config.js` `headers()` function

### Mobile Application Issues

- Clear Expo cache: `expo start --clear`
- Reset Metro bundler cache: `npx react-native start --reset-cache`
- If native dependencies change, rebuild the development client:
  ```bash
  eas build --profile development --platform <ios|android>
  ```
- Check EAS build logs on `https://expo.dev` for build failures
- For purchase testing, use RevenueCat sandbox environments

### Rate Limiting

The API implements tiered rate limiting:

| Tier      | Requests/min |
| --------- | ------------ |
| Anonymous | 60           |
| Free      | 300          |
| Premium   | 1000         |

Rate limit headers are included in all API responses:

- `X-RateLimit-Limit` - Maximum requests per window
- `X-RateLimit-Remaining` - Requests remaining
- `X-RateLimit-Reset` - Unix timestamp when the limit resets

### Authentication Flow

The API uses JWT tokens with refresh token rotation:

1. Client authenticates via `/api/v1/auth/login` (email/password) or OAuth
   (Apple/Google)
2. Server returns an access token and refresh token
3. Access tokens are short-lived; include in `Authorization: Bearer <token>`
4. Refresh tokens are used to obtain new access tokens without re-authentication
5. Protected routes use `authMiddleware()` which validates the JWT

### Error Response Format

All API errors follow RFC 7807 Problem Details:

```json
{
  "type": "https://api.tara-app.com/problems/validation-error",
  "title": "Validation Error",
  "status": 400,
  "detail": "Invalid email format",
  "instance": "/api/v1/auth/register",
  "requestId": "tara_abc123",
  "timestamp": "2024-01-15T12:00:00Z"
}
```

### Performance Considerations

- The API uses Drizzle ORM for query building alongside Prisma for schema
  management and type generation
- Denormalized counters (`playCount`, `completionCount`, `favoriteCount`) on the
  `Meditation` model avoid expensive JOINs for catalog listings
- Redis is used for session caching, rate limit state, and feature flag storage
- The web app uses `next/image` with WebP/AVIF formats and CDN-based caching
- Static assets (`/_next/static/`) are cached with `max-age=31536000, immutable`
- Audio files are cached for 7 days via `Cache-Control` headers
