# Nyx Domain - Developer Guide

Nyx is the Cosmic Observatory Platform domain. It provides a full-stack
astronomical education and observation platform with ephemeris computation,
coordinate transformations, celestial catalogs, sky visualization, telescope
control, and real-time satellite tracking. The platform serves data through a
Hono-based REST/WebSocket API and renders interactive sky charts via WebGL and
WebXR applications.

---

## Prerequisites

### Required Software

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

### Optional Software

| Software          | Purpose                                                   |
| ----------------- | --------------------------------------------------------- |
| NVIDIA GPU + CUDA | Accelerated WebGL rendering during development            |
| VR headset        | Testing WebXR planetarium and AR sky apps                 |
| Python 3.11+      | Building the Python client SDK (`libs/nyx/client-python`) |

---

## Project Structure

```
apps/nyx/
  api/               # REST + WebSocket API server (Hono + OpenAPI)
  star-map/          # Interactive WebGL sky chart (Vite)
  vr-planetarium/    # Immersive WebXR planetarium (Vite + WebXR)
  ar-sky/            # Augmented reality sky finder (Vite + WebXR/AR)
  mobile/            # Mobile astronomical companion (Vite)
  pipelines/         # Background data pipelines (TLE, catalogs, ephemeris, events)
  education/         # Educational content and guided tours
  tools/             # Command-line astronomical utilities

libs/nyx/
  types/             # TypeScript type definitions
  constants/         # IAU/CODATA astronomical constants
  coordinates/       # Coordinate system transforms (equatorial, horizontal, galactic, ecliptic)
  time/              # Time systems (JD, MJD, sidereal, TDB, Delta-T)
  database/          # PostgreSQL schema definitions (pgvector)
  utils/             # Common utility functions
  client/            # TypeScript API client SDK
  client-python/     # Python API client SDK
  ephemeris/         # Planetary/solar/lunar position calculations
  orbital/           # Keplerian orbital element processing
  events/            # Eclipse, conjunction, transit predictions
  positional/        # Rise/set/transit time calculations
  analysis/          # Spectral analysis and photometry
  realtime/          # Real-time position streaming engine
  time-travel/       # Animated time progression for sky simulation
  catalogs/          # Star catalog integrations (Gaia DR3, Hipparcos, Yale)
  constellations/    # Constellation boundaries, lines, mythology
  mythology/         # Cultural stories and educational content
  education/         # Guided tours and lesson plans
  integrations/      # External service integrations (weather, JPL)
  renderer/          # WebGL sky chart rendering engine
  visualization/     # 3D solar system and DSO visualization
  widgets/           # Reusable UI components for astronomical data
  audio/             # Audio narration and ambient sound for planetarium
  lilith-integration/# Cross-domain bridge to Lilith consciousness platform
  docs/              # Library-level documentation
```

### Application Overview

| Application        | Directory                 | Type    | Port | Framework       |
| ------------------ | ------------------------- | ------- | ---- | --------------- |
| **API**            | `apps/nyx/api`            | Server  | 3000 | Hono + OpenAPI  |
| **Star Map**       | `apps/nyx/star-map`       | Web App | 5173 | Vite + WebGL    |
| **VR Planetarium** | `apps/nyx/vr-planetarium` | Web App | 5174 | Vite + WebXR    |
| **AR Sky**         | `apps/nyx/ar-sky`         | Web App | 5175 | Vite + WebXR/AR |
| **Mobile**         | `apps/nyx/mobile`         | Mobile  | --   | Vite            |
| **Pipelines**      | `apps/nyx/pipelines`      | Worker  | 9090 | Node.js         |
| **Education**      | `apps/nyx/education`      | Web App | --   | --              |
| **Tools**          | `apps/nyx/tools`          | CLI     | --   | --              |

---

## Local Development Setup

### 1. Start Infrastructure

Nyx requires PostgreSQL (with pgvector) and Redis.

```bash
# Start all core infrastructure
docker compose -f docker/docker-compose.dev.yml up -d
```

This starts:

- PostgreSQL (port 5432) -- with pgvector extension for spatial celestial
  queries
- Redis (port 6379) -- for ephemeris caching and real-time subscriptions

### 2. Install Dependencies

```bash
pnpm install
```

### 3. Set Environment Variables

The root `.env` file provides defaults for local development. Nyx-specific
variables:

| Variable                | Default                                           | Used By              |
| ----------------------- | ------------------------------------------------- | -------------------- |
| `NYX_DATABASE_URL`      | `postgresql://oshun:oshun_dev@localhost:5432/nyx` | database, API        |
| `REDIS_URL`             | `redis://localhost:6379`                          | API, pipelines       |
| `PORT`                  | `3000`                                            | API                  |
| `HOST`                  | `0.0.0.0`                                         | API                  |
| `WS_PATH`               | `/ws`                                             | API WebSocket        |
| `NYX_GAIA_CATALOG_PATH` | `/data/catalogs/gaia_dr3`                         | catalogs (optional)  |
| `NYX_HIPPARCOS_PATH`    | `/data/catalogs/hipparcos`                        | catalogs (optional)  |
| `NYX_EPHEMERIS_PATH`    | `/data/ephemeris/de440.bsp`                       | ephemeris (optional) |
| `NYX_WEATHER_API_KEY`   | --                                                | weather integration  |
| `METRICS_ENABLED`       | `true`                                            | pipelines            |

The catalog and ephemeris path variables are optional -- bundled data is used by
default. Set them only if you have full catalog files available locally.

### 4. Database Setup

Nyx uses Drizzle-style schema definitions in `libs/nyx/database/`. The database
schema is managed through the `@nyx/database` library.

```bash
# Apply the schema to local database
pnpm nx build @nyx/database
```

---

## Running Services

### API Server

The central API providing REST endpoints and WebSocket channels for all
astronomical data. Built with Hono and `@hono/zod-openapi`.

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

# Build for production
pnpm nx build @nyx/api
```

Once running, the API is available at:

- REST endpoints: `http://localhost:3000/api/v1/`
- WebSocket: `ws://localhost:3000/ws`
- Swagger UI: `http://localhost:3000/api/docs`
- OpenAPI spec: `http://localhost:3000/api/v1/openapi.json`

**API routes:**

| Route File      | Path Prefix          | Description                         |
| --------------- | -------------------- | ----------------------------------- |
| `objects.ts`    | `/api/v1/objects`    | Celestial object catalog and search |
| `ephemeris.ts`  | `/api/v1/ephemeris`  | Position calculations               |
| `events.ts`     | `/api/v1/events`     | Astronomical event predictions      |
| `satellites.ts` | `/api/v1/satellites` | Satellite tracking (TLE-based)      |

**Middleware chain:**
`secureHeaders -> CORS -> logger -> timing -> prettyJSON -> requestId -> errorHandler -> rateLimit -> apiKeyAuth -> routes`

### Star Map (WebGL)

Interactive sky chart rendering millions of stars with real-time position
updates.

```bash
# Development with hot reload
pnpm nx dev @nyx/star-map

# Production build
pnpm nx build @nyx/star-map

# Preview production build
pnpm nx preview @nyx/star-map
```

### VR Planetarium (WebXR)

Immersive 3D planetarium experience with stereoscopic projection for VR
headsets.

```bash
# Development
pnpm nx dev @nyx/vr-planetarium

# Production build
pnpm nx build @nyx/vr-planetarium
```

### AR Sky (WebXR/AR)

Augmented reality overlay for identifying celestial objects using device camera
and orientation sensors.

```bash
# Development
pnpm nx dev @nyx/ar-sky

# Production build
pnpm nx build @nyx/ar-sky
```

### Mobile App

Mobile astronomical companion application.

```bash
# Development
pnpm nx dev @nyx/mobile

# Production build
pnpm nx build @nyx/mobile
```

### Data Pipelines

Background data pipeline service with four independent modules:

| Pipeline                | Schedule | Purpose                                          |
| ----------------------- | -------- | ------------------------------------------------ |
| **TLE Updater**         | Every 4h | Fetches satellite TLE data from CelesTrak/NORAD  |
| **Catalog Syncer**      | Daily    | Synchronizes star/DSO catalogs (Gaia, Hipparcos) |
| **Ephemeris Generator** | Every 6h | Pre-computes planet positions for fast lookup    |
| **Event Calculator**    | Daily    | Calculates upcoming eclipses, conjunctions, etc. |

```bash
# Build pipelines
pnpm nx build @nyx/pipelines

# Run pipelines (each runs as independent Node.js process)
pnpm nx serve @nyx/pipelines
```

In production, pipelines are orchestrated as Kubernetes CronJobs. A shared
health server on port 9090 provides `/health` and `/metrics` endpoints.

---

## Building

### Build All Nyx Projects

```bash
pnpm nx run-many -t build --projects=tag:scope:nyx
```

### Build Individual Projects

```bash
# API (tsc)
pnpm nx build @nyx/api

# Star Map (Vite)
pnpm nx build @nyx/star-map

# VR Planetarium (Vite)
pnpm nx build @nyx/vr-planetarium

# AR Sky (Vite)
pnpm nx build @nyx/ar-sky

# Pipelines (esbuild)
pnpm nx build @nyx/pipelines

# Individual libraries (tsup or tsc)
pnpm nx build @nyx/ephemeris
pnpm nx build @nyx/coordinates
pnpm nx build @nyx/renderer
```

---

## Testing

### Test Runner

All Nyx projects use Vitest via the `@nx/vite:test` executor.

### Running Tests

```bash
# All Nyx projects
pnpm nx run-many -t test --projects=tag:scope:nyx

# Individual library
pnpm nx test @nyx/ephemeris
pnpm nx test @nyx/coordinates
pnpm nx test @nyx/time

# With coverage
pnpm nx test @nyx/ephemeris --coverage

# Watch mode
pnpm nx test @nyx/coordinates --watch
```

### Linting and Formatting

```bash
# Lint all Nyx projects
pnpm nx run-many -t lint --projects=tag:scope:nyx

# Lint individual project
pnpm nx lint @nyx/api

# Fix lint issues
pnpm nx lint @nyx/api --fix

# Format with Prettier
pnpm prettier --write "libs/nyx/**/*.ts"
pnpm prettier --write "apps/nyx/**/*.ts"
```

### Type Checking

```bash
# Type check individual projects
pnpm nx typecheck @nyx/database
pnpm tsc --noEmit -p libs/nyx/ephemeris/tsconfig.lib.json
```

---

## Common Development Tasks

### Adding a New Library

1. Create the directory structure:

   ```bash
   mkdir -p libs/nyx/my-feature/src
   ```

2. Create `project.json`:

   ```json
   {
     "name": "@nyx/my-feature",
     "$schema": "../../../node_modules/nx/schemas/project-schema.json",
     "sourceRoot": "libs/nyx/my-feature/src",
     "projectType": "library",
     "tags": ["scope:nyx", "type:lib"],
     "targets": {
       "build": {
         "executor": "nx:run-commands",
         "options": {
           "command": "tsup",
           "cwd": "libs/nyx/my-feature"
         },
         "outputs": ["{projectRoot}/dist"]
       },
       "lint": {
         "executor": "@nx/eslint:lint",
         "options": {
           "lintFilePatterns": ["libs/nyx/my-feature/src/**/*.ts"]
         }
       },
       "test": {
         "executor": "@nx/vite:test",
         "options": {
           "config": "libs/nyx/my-feature/vitest.config.ts"
         }
       }
     }
   }
   ```

3. Create `package.json`:

   ```json
   {
     "name": "@nyx/my-feature",
     "version": "0.0.1",
     "type": "module",
     "main": "./src/index.ts",
     "types": "./src/index.ts",
     "dependencies": {
       "@nyx/types": "workspace:*"
     }
   }
   ```

4. Add a path mapping to `tsconfig.base.json`:

   ```json
   {
     "compilerOptions": {
       "paths": {
         "@nyx/my-feature": ["libs/nyx/my-feature/src/index.ts"]
       }
     }
   }
   ```

5. Implement the library in `libs/nyx/my-feature/src/index.ts`.

### Adding a New API Endpoint

1. Create the route file in `apps/nyx/api/src/routes/`:

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

   const myRouter = new OpenAPIHono();

   const myRoute = createRoute({
     method: 'get',
     path: '/',
     tags: ['MyResource'],
     summary: 'Get my resource',
     responses: {
       200: {
         description: 'Success',
         content: {
           'application/json': {
             schema: z.object({
               success: z.literal(true),
               data: z.object({
                 /* schema */
               }),
             }),
           },
         },
       },
     },
   });

   myRouter.openapi(myRoute, (c) => {
     return c.json({
       success: true,
       data: {
         /* response */
       },
     });
   });

   export { myRouter };
   ```

2. Register the router in `apps/nyx/api/src/routes/index.ts`.

3. Create corresponding Zod schemas in `apps/nyx/api/src/schemas/`.

4. Add service logic in `apps/nyx/api/src/services/`.

### Adding a New WebSocket Channel

The WebSocket server at `/ws` uses the `ws` library. To add a new channel:

1. Define the channel type in `apps/nyx/api/src/websocket/types.ts`.

2. Add a handler in `apps/nyx/api/src/websocket/handlers.ts`.

3. Register the computation loop in `apps/nyx/api/src/websocket/services.ts`
   within the `UpdateScheduler` class.

### Adding a New Pipeline

1. Create a pipeline module in `apps/nyx/pipelines/src/`:

   ```typescript
   export async function runMyPipeline(): Promise<void> {
     // Fetch data from external source
     // Transform and validate
     // Upsert into PostgreSQL or Redis cache
   }
   ```

2. Register it in `apps/nyx/pipelines/src/index.ts` with its schedule.

3. Add a health check endpoint for the pipeline.

### Working with Coordinate Systems

The `@nyx/coordinates` library provides transforms between systems:

- **Equatorial** (RA/Dec) -- standard celestial reference frame (ICRS/J2000.0)
- **Horizontal** (Alt/Az) -- observer-relative sky position
- **Galactic** (l/b) -- galactic coordinate system
- **Ecliptic** (lon/lat) -- ecliptic reference frame

All transforms account for precession, nutation, and atmospheric refraction when
an observer location is provided.

### Working with Time Systems

The `@nyx/time` library provides conversions between:

- UTC, Julian Date (JD), Modified Julian Date (MJD)
- Greenwich Sidereal Time (GST), Local Sidereal Time (LST)
- Barycentric Dynamical Time (TDB), Terrestrial Time (TT)
- Delta-T corrections

---

## Debugging

### API Not Starting

- Verify PostgreSQL is running:
  `docker compose -f docker/docker-compose.dev.yml ps`
- Check `NYX_DATABASE_URL` is set correctly
- Ensure Redis is available at `REDIS_URL`
- Check port 3000 is not in use: `lsof -i :3000`

### WebSocket Connection Issues

- The WebSocket server runs on the same port as the REST API at path `/ws`
- Verify API key authentication -- anonymous connections have limited channels
- Ping/pong keepalive runs at 30-second intervals with a 10-second timeout
- Check rate limit tier for subscription limits

### Ephemeris Accuracy Issues

- Nyx uses peer-reviewed algorithms (Meeus, IAU 2006, VSOP87, JPL DE440-derived)
- Verify time system conversions -- input times must be in UTC
- Check observer coordinates -- latitude/longitude must be in decimal degrees
- Light-time correction is applied iteratively for outer solar system objects
- See `docs/domains/nyx/accuracy.md` for precision standards

### Pipeline Not Running

- Pipelines use Node.js timers in development, Kubernetes CronJobs in production
- Health endpoint: `http://localhost:9090/health`
- Metrics endpoint: `http://localhost:9090/metrics`
- Check network access to external data sources (CelesTrak, Gaia Archive, JPL)

### Star Map Rendering Issues

- Star map uses WebGL -- verify browser supports WebGL 2.0
- For VR/AR apps, a WebXR-compatible browser and device are required
- Large catalog data (millions of stars) may require throttling on low-end
  devices
- Check browser console for shader compilation errors

### Performance

- API uses Redis caching for frequently accessed ephemeris data
- Pipelines pre-compute planet positions to avoid real-time calculation overhead
- Star map uses level-of-detail (LOD) rendering for large star fields
- WebSocket update frequency: 1 second for positions, 60 seconds for events

---

## Dependency Graph

```
@nyx/client  @nyx/renderer  @nyx/visualization
    |              |               |
    v              v               v
@nyx/ephemeris  @nyx/catalogs  @nyx/constellations
    |              |               |
    +---           +---------------+
    v              v
@nyx/coordinates  @nyx/orbital  @nyx/events
    |              |               |
    +---           +---------------+
    v              v
@nyx/time  @nyx/constants  @nyx/types
    |              |               |
    +---           +---------------+
                   v
            @oshun/shared libraries
            (@oshun/logging, @oshun/config, @oshun/database)
```

---

## Quick Reference

| Task                      | Command                                                 |
| ------------------------- | ------------------------------------------------------- |
| Start infrastructure      | `docker compose -f docker/docker-compose.dev.yml up -d` |
| Install dependencies      | `pnpm install`                                          |
| Start API server          | `pnpm nx serve @nyx/api`                                |
| Start star map            | `pnpm nx dev @nyx/star-map`                             |
| Start VR planetarium      | `pnpm nx dev @nyx/vr-planetarium`                       |
| Start AR sky              | `pnpm nx dev @nyx/ar-sky`                               |
| Build all Nyx             | `pnpm nx run-many -t build --projects=tag:scope:nyx`    |
| Test all Nyx              | `pnpm nx run-many -t test --projects=tag:scope:nyx`     |
| Lint all Nyx              | `pnpm nx run-many -t lint --projects=tag:scope:nyx`     |
| View dependency graph     | `pnpm nx graph --focus=@nyx/api`                        |
| Check affected by changes | `pnpm nx affected -t test`                              |
| Reset Nx cache            | `pnpm nx reset`                                         |
