# @bigscreen/api

The shared library of domain handlers used by `apps/api` (public) and `apps/admin_api` (private). Where `@bigscreen/auth` owns identity, this library owns everything else that isn't multiplayer: accounts (admin operations), analytics, Beyond, channels, media, moderation, reporting, Shopify, fabricator, inventory, shipping, eye-tracking, topics, and so on.

**Path:** [api/](../../api).
**Package name:** `@bigscreen/api`.
**Source root:** [api/src/](../../api/src).

## Handler-to-Server Binding

A handler module becomes a route when a service imports its function and `app.use(...)`s / `.get(...)`s it. Most modules are registered on both `apps/api` and `apps/admin_api`, but some are one-sided (e.g. `RDC`, `FabricatorAdminApi` — admin-only; `PublicApi`, `ReportingApi` — mixed).

```mermaid
flowchart LR
    subgraph Servers
        API[apps/api]
        ADMIN[apps/admin_api]
    end

    subgraph TopLevel["api/src (top-level modules)"]
        Admin
        Analytics
        ApiClients
        Beyond
        Channels
        Discord
        EyeTracking
        ImageUtils
        Moderator
        OAuthApi
        OAuthClientsApi
        RDC
        ReportingApi
        Shopify
        Topics
        UnityApi
        UploadHandler
        FeatureFlags
        RateLimiter
    end

    subgraph Fabricator["api/src/fabricator"]
        FabAdm[FabricatorAdminApi]
        FabDB[FabricatorDatabase]
        Ship[ShippingAdminApi]
        Inv[InventoryAdminApi]
        DHL[DHLInvoiceApi]
    end

    subgraph Media["api/src/media"]
        MediaM[Media]
        MediaDB[MediaDatabase]
        Twitch
        Brightcove
    end

    API --> Analytics
    API --> Beyond
    API --> Channels
    API --> EyeTracking
    API --> MediaM
    API --> OAuthApi
    API --> PublicApi[PublicApi/info]
    API --> ReportingApi
    API --> Shopify
    API --> Topics
    API --> UploadHandler

    ADMIN --> Admin
    ADMIN --> Analytics
    ADMIN --> Beyond
    ADMIN --> Channels
    ADMIN --> Moderator
    ADMIN --> MediaM
    ADMIN --> OAuthClientsApi
    ADMIN --> RDC
    ADMIN --> Topics
    ADMIN --> UploadHandler
    ADMIN --> FabAdm
    ADMIN --> Ship
    ADMIN --> Inv
    ADMIN --> DHL
```

## Top-Level Modules

Every module lives at `api/src/<Name>.ts`. One-line descriptions:

| Module | Purpose |
|--------|---------|
| **Admin** | Staff account creation, onboarding, access-policy management, admin logging |
| **Analytics** | Event ingestion, stats queries, telemetry |
| **ApiClients** | Shared HTTP clients for cross-service calls |
| **Beyond** | 3D scanning flows, Beyond big orders, Multipass (Shopify) |
| **Channels** | TV channels + channel groups, streaming events |
| **Database.V2** | Legacy DB abstraction used by a subset of handlers |
| **DataUtils** | Data-shape helpers shared across modules |
| **Discord** | Discord-facing interactions (distinct from `@bigscreen/lib`'s DiscordLogger) |
| **EyeTracking** | Eye-tracking model storage, file serving, custom JWT middleware |
| **FeatureFlags** | Simple feature-flag lookups used by route handlers |
| **ImageUtils** | `sharp`-based image processing |
| **LegacySchemas** | Deprecated schemas retained for backwards compatibility |
| **Moderator** | Bans, device history, IP reputation, disabled accounts, admin notes |
| **OAuthApi** | OAuth 2.0 public endpoints on `apps/api`: `/oauth/token`, `/.well-known/jwks.json`, `/.well-known/oauth-authorization-server`. See [services/oauth.md](../services/oauth.md). |
| **OAuthClientsApi** | OAuth client CRUD + grants + audit endpoints on `apps/admin_api` (`/admin/oauth/*`). Called by arda's consent UI and by SuperUser admins managing clients. |
| **RateLimiter** | Rate-limit middleware (currently unused — see `apps/api` middleware comments) |
| **RDC** | Remote Desktop Connection builds (S3-stored binaries) |
| **ReportingApi** | User / room reporting |
| **Schemas** | Zod schemas for request / response validation |
| **Shopify** | Shopify webhooks, admin API, product sync (~75 KB — the core e-commerce integration) |
| **Topics** | Pub/sub topic subscriptions |
| **UnityApi** | Unity-app-specific endpoints |
| **UploadHandler** | Multer-style upload pipeline factory used by both servers |

## The Fabricator Subsystem

Fabricator is the name for the Beyond order pipeline: Shopify → factory → shipping → customer. It's the heaviest subsystem in this library.

```mermaid
flowchart LR
    SH["Shopify<br/>(webhook → orders)"] --> FabAdm
    FabAdm["FabricatorAdminApi<br/>(orchestrator)"]
    FabDB[("FabricatorDatabase<br/>on Postgres")]
    Ship[ShippingAdminApi]
    Inv[InventoryAdminApi]
    DHL[DHLInvoiceApi]
    Schemas[FabricatorSchemas]

    FabAdm --> FabDB
    Ship --> FabDB
    Inv --> FabDB
    DHL --> FabDB
    FabAdm --> Schemas
    Ship --> Schemas
    Inv --> Schemas
```

Files in [api/src/fabricator/](../../api/src/fabricator):

| File | Notes |
|------|-------|
| `FabricatorAdminApi.ts` | The orchestrator — order creation, fulfilment, test orders, Fusion/CNC glue |
| `FabricatorDatabase.ts` | Postgres access for all Fabricator tables |
| `FabricatorSchemas.ts` | Zod schemas for orders, line items, jobs, batches |
| `ShippingAdminApi.ts` | Label generation, BigShipper queues, pickup scheduling ([shipment group + box-size reference](../services/shipping-configurations.md)) |
| `InventoryAdminApi.ts` | Inventory CRUD, stock reports, ingestion |
| `DHLInvoiceApi.ts` | DHL invoice reconciliation (CSV upload → match shipments) |
| `preprocessor/` | Python mesh preprocessor (separate lifecycle, documented in its own README) |
| `legacy/` | Older code paths retained during migrations |
| `shopify-data/` | Shopify-sourced data helpers |

`FabricatorAdminApi.initialize()` runs at `apps/admin_api` startup and warms caches.

## The Media Subsystem

[api/src/media/](../../api/src/media) holds everything about cinema / TV / streaming media:

| File | Notes |
|------|-------|
| `Media.ts` | Main handler — products, entitlements, orders (Stripe + Oculus IAP), playback |
| `MediaDatabase.ts` | Postgres access for media-related tables |
| `MediaAnalytics.ts` | Playback / purchase analytics |
| `Twitch.ts` | Twitch stream URL resolution (m3u8) |
| `Brightcove.ts` | Brightcove player / stream integration |

## Where to read next

- For admin-side endpoint wiring → [services/admin-api.md](../services/admin-api.md)
- For public-side endpoint wiring → [services/api.md](../services/api.md)
- For the Shopify flow end-to-end → [data-flows.md#5-shopify-webhook--order](../data-flows.md#5-shopify-webhook--order)
