# phuc-nt/my-epidemic-monitor architecture

> Architecture diagram of the GitHub repository phuc-nt/my-epidemic-monitor, generated by GitDiagram from its file tree, README and a sample of source files (last updated 2026-04-11). It is an AI-made overview: check details against the source.

- Interactive diagram: https://gitdiagram.com/phuc-nt/my-epidemic-monitor
- Repository: https://github.com/phuc-nt/my-epidemic-monitor

## Overview

1. **High-level shape**
   - This repo is a **public single-page app plus serverless API** for epidemic risk monitoring in Vietnam.
   - The browser UI is built with **Vanilla TypeScript + Vite**, rendered on **Cloudflare Pages**, and backed by **Cloudflare Pages Functions** and **D1** for data.

2. **Primary runtime boundaries**
   - **Client/browser**: map, panels, chat, local UI state, and data fetching.
   - **Cloudflare edge/serverless**: `/api/health/v1/*` and `/api/chat` endpoints, plus shared caching/CORS helpers.
   - **External services**: LLM inference via **OpenRouter** and optional local/provider abstractions (`mlx`, `ollama`, proxy).
   - **Upstream data pipeline**: the README says crawl/extract runs separately on a Mac Mini and pushes snapshots into D1 every 6 hours, so the frontend does not depend on crawler uptime.

3. **Frontend application shell**
   - `src/main.ts` boots the app.
   - `src/app/*` (`app-init`, `app-context`, `app-layout`) establishes global state and overall page composition.
   - The app is organized around a map-centric layout with side panels, a mobile tab bar, banners, and a disclaimer flow.

4. **Map and geospatial visualization subsystem**
   - `src/components/map-shell.ts` is the main map container.
   - `src/components/map-layers/*` defines layered risk visualizations:
     - country choropleth
     - district choropleth
     - outbreak markers
     - early warning layer
     - severity heatmap
   - The app uses **MapLibre GL** for basemap rendering and **deck.gl** for overlay layers.
   - Geospatial boundary data includes `public/data/vietnam-districts.geojson`.

5. **Health risk content panels**
   - The left/right informational panels are split by topic:
     - `breaking-news-banner`
     - `top-diseases-panel`
     - `disease-outbreaks-panel`
     - `climate-alerts-panel`
     - `case-report-panel-data`
     - `chat-panel`
   - `panel-base` and `panel-persistence` provide shared panel behavior and remembered UI state.
   - On mobile, `mobile-tab-bar` swaps the desktop panel affordance into a tabbed navigation pattern.

6. **Data access layer in the client**
   - `src/services/api-client.ts` is the common API entry point.
   - Domain-specific clients separate concerns:
     - `bulk-data-service`
     - `climate-service`
     - `disease-outbreak-service`
     - `news-feed-service`
   - `fetch-cache.ts` adds client-side request caching behavior.
   - `snapshot-store.ts`, `trend-calculator.ts`, and related services suggest the UI is fed by time-series snapshots and precomputed trend data rather than live scraping.

7. **Serverless API surface**
   - The Cloudflare Functions entry points are under `functions/api/`.
   - Health data is exposed through:
     - `functions/api/health/v1/all.ts`
     - `functions/api/health/v1/climate.ts`
     - `functions/api/health/v1/news.ts`
     - `functions/api/health/v1/outbreaks.ts`
   - `functions/api/chat.ts` handles the conversational AI endpoint.
   - `functions/_middleware.ts` and shared helpers manage cross-cutting behavior such as CORS, caching, and request shaping.

8. **Shared server-side data normalization**
   - `functions/_shared/*` contains data/lookup logic reused across endpoints:
     - outbreak query helpers
     - disease label mapping
     - Vietnam province population data
     - cache utilities
     - CORS utilities
   - This indicates the API is not just pass-through; it also normalizes and enriches raw health records before returning them to the UI.

9. **LLM/chat architecture**
   - Chat is abstracted behind a provider/router layer in `src/services/llm-*`.
   - Providers include:
     - `llm-provider-openrouter`
     - `llm-provider-ollama`
     - `llm-provider-mlx`
     - `llm-provider-proxy`
   - `llm-router` selects the backend, `llm-context-builder` assembles grounded prompt context from app data, and `llm-sse-stream-reader` handles streamed responses.
   - `llm-data-pipeline` and `news-dedup-rules` show the AI experience is designed around curated, deduplicated news and health snapshots rather than generic chat.

10. **Presentation and UX utilities**
   - Styling is split by concern in `src/styles/*` rather than one global stylesheet.
   - Small utilities cover DOM helpers, sanitization, sparkline rendering, and storage.
   - `map-popup` and `breaking-news.css`/`climate.css` etc. suggest the UI is strongly data-card driven with visual emphasis on alerts and trends.

11. **External data model and enrichment**
   - The app appears to combine several data classes into one health-risk view:
     - outbreak events
     - climate-related alerts
     - news-derived signals
     - province/district population context
   - Population normalization matters because per-capita comparisons and choropleth severity depend on regional context, not just raw counts.

12. **Deployment and operational boundary**
   - `wrangler.toml`, `public/_headers`, `public/_redirects`, and `public/_routes.json` show deployment is tuned for Cloudflare Pages/Workers routing and static delivery.
   - `dev-api-middleware.ts` supports local development by bridging the frontend to the API layer.
   - The README’s note that data ingestion happens on a separate machine is important architecturally: the repo is the **presentation + API + AI layer**, not the crawler itself.

13. **Quality and verification**
   - `e2e/app-smoke.spec.ts` with Playwright covers a smoke path for the integrated app.
   - This suggests the critical system contract is: static app loads, API endpoints respond, and key map/panel flows render against seeded data.

14. **How to diagram it**
   - Draw three main zones: **browser UI**, **Cloudflare serverless/API**, and **external LLM/data sources**.
   - Show the browser consuming health/news/climate snapshots from the API, rendering them on a map and in panels.
   - Show chat as a separate request path that goes through the serverless endpoint into an LLM provider.
   - Show the upstream crawler/Mac Mini feeding D1 as an off-repo ingestion pipeline that populates what the API serves.

Main entry points: [`src/app/app-layout.ts`](https://github.com/phuc-nt/my-epidemic-monitor/blob/main/src/app/app-layout.ts) (Layout), [`src/services/api-client.ts`](https://github.com/phuc-nt/my-epidemic-monitor/blob/main/src/services/api-client.ts) (API client), [`functions/_middleware.ts`](https://github.com/phuc-nt/my-epidemic-monitor/blob/main/functions/_middleware.ts) (Middleware), [`src/components/map-layers/index.ts`](https://github.com/phuc-nt/my-epidemic-monitor/blob/main/src/components/map-layers/index.ts) (Map layers)

## Diagram (Mermaid)

```mermaid
flowchart TD

subgraph group_browser["Browser UI"]
  node_main(("App boot<br/>bootstrap<br/>[main.ts]"))
  node_app_init["App init<br/>shell<br/>[app-init.ts]"]
  node_app_layout["Layout<br/>shell<br/>[app-layout.ts]"]
  node_app_context["App context<br/>state<br/>[app-context.ts]"]
  node_map_shell["Map shell<br/>map-ui<br/>[map-shell.ts]"]
  node_map_layers["Map layers<br/>geospatial overlays<br/>[index.ts]"]
  node_panels["Info panels<br/>[index.ts]"]
  node_chat_panel["Chat panel<br/>ai-ui<br/>[chat-panel.ts]"]
  node_mobile_tabs["Mobile tabs<br/>navigation<br/>[mobile-tab-bar.ts]"]
  node_panel_state["Panel state<br/>ui-state<br/>[panel-base.ts]"]
  node_api_client["API client<br/>data access<br/>[api-client.ts]"]
  node_snapshot_store["Snapshots<br/>client data<br/>[snapshot-store.ts]"]
  node_trend_calc["Trend calc<br/>analytics"]
  node_llm_router["LLM router<br/>ai orchestration<br/>[llm-router.ts]"]
  node_llm_context["Prompt context<br/>ai context"]
end

subgraph group_edge["Cloudflare Edge"]
  node_functions_mw["Middleware<br/>[_middleware.ts]"]
  node_health_api["Health API<br/>edge api<br/>[all.ts]"]
  node_news_api["News API<br/>edge api<br/>[news.ts]"]
  node_climate_api["Climate API<br/>edge api<br/>[climate.ts]"]
  node_outbreak_api["Outbreak API<br/>edge api<br/>[outbreaks.ts]"]
  node_chat_api["Chat API<br/>edge api<br/>[chat.ts]"]
  node_shared_norm["Shared data<br/>edge helpers<br/>[outbreak-query.ts]"]
end

subgraph group_data["Data Sources"]
  node_d1_snapshots[("D1 snapshots<br/>database")]
  node_crawler_pipeline["Crawler pipeline<br/>upstream ingestion"]
  node_openrouter(("OpenRouter<br/>llm provider"))
  node_local_llms(("Local providers<br/>llm backends"))
  node_geojson["District geojson<br/>boundary data"]
end

node_main -->|"boots"| node_app_init
node_app_init -->|"creates"| node_app_context
node_app_init -->|"mounts"| node_app_layout
node_app_layout -->|"contains"| node_map_shell
node_app_layout -->|"contains"| node_panels
node_app_layout -->|"includes"| node_chat_panel
node_app_layout -->|"adapts"| node_mobile_tabs
node_panels -->|"shares"| node_panel_state
node_map_shell -->|"renders"| node_map_layers
node_map_layers -->|"reads boundaries"| node_geojson
node_panels -->|"fetches data"| node_api_client
node_map_layers -->|"consumes"| node_snapshot_store
node_trend_calc -->|"feeds trends"| node_map_layers
node_api_client -->|"requests"| node_health_api
node_api_client -->|"requests"| node_news_api
node_api_client -->|"requests"| node_climate_api
node_api_client -->|"requests"| node_outbreak_api
node_functions_mw -->|"wraps"| node_health_api
node_functions_mw -->|"wraps"| node_news_api
node_functions_mw -->|"wraps"| node_climate_api
node_functions_mw -->|"wraps"| node_outbreak_api
node_health_api -->|"uses"| node_shared_norm
node_news_api -->|"uses"| node_shared_norm
node_climate_api -->|"uses"| node_shared_norm
node_outbreak_api -->|"uses"| node_shared_norm
node_health_api -->|"reads"| node_d1_snapshots
node_news_api -->|"reads"| node_d1_snapshots
node_climate_api -->|"reads"| node_d1_snapshots
node_outbreak_api -->|"reads"| node_d1_snapshots
node_crawler_pipeline -.->|"writes"| node_d1_snapshots
node_chat_panel -->|"calls"| node_chat_api
node_chat_api -->|"routes"| node_llm_router
node_llm_router -->|"uses"| node_openrouter
node_llm_router -.->|"falls back to"| node_local_llms
node_chat_api -->|"builds context"| node_llm_context

click node_main "https://github.com/phuc-nt/my-epidemic-monitor/blob/main/src/main.ts"
click node_app_init "https://github.com/phuc-nt/my-epidemic-monitor/blob/main/src/app/app-init.ts"
click node_app_layout "https://github.com/phuc-nt/my-epidemic-monitor/blob/main/src/app/app-layout.ts"
click node_app_context "https://github.com/phuc-nt/my-epidemic-monitor/blob/main/src/app/app-context.ts"
click node_map_shell "https://github.com/phuc-nt/my-epidemic-monitor/blob/main/src/components/map-shell.ts"
click node_map_layers "https://github.com/phuc-nt/my-epidemic-monitor/blob/main/src/components/map-layers/index.ts"
click node_panels "https://github.com/phuc-nt/my-epidemic-monitor/blob/main/src/components/index.ts"
click node_chat_panel "https://github.com/phuc-nt/my-epidemic-monitor/blob/main/src/components/chat-panel.ts"
click node_mobile_tabs "https://github.com/phuc-nt/my-epidemic-monitor/blob/main/src/components/mobile-tab-bar.ts"
click node_panel_state "https://github.com/phuc-nt/my-epidemic-monitor/blob/main/src/components/panel-base.ts"
click node_api_client "https://github.com/phuc-nt/my-epidemic-monitor/blob/main/src/services/api-client.ts"
click node_snapshot_store "https://github.com/phuc-nt/my-epidemic-monitor/blob/main/src/services/snapshot-store.ts"
click node_trend_calc "https://github.com/phuc-nt/my-epidemic-monitor/blob/main/src/services/trend-calculator.ts"
click node_llm_router "https://github.com/phuc-nt/my-epidemic-monitor/blob/main/src/services/llm-router.ts"
click node_llm_context "https://github.com/phuc-nt/my-epidemic-monitor/blob/main/src/services/llm-context-builder.ts"
click node_functions_mw "https://github.com/phuc-nt/my-epidemic-monitor/blob/main/functions/_middleware.ts"
click node_health_api "https://github.com/phuc-nt/my-epidemic-monitor/blob/main/functions/api/health/v1/all.ts"
click node_news_api "https://github.com/phuc-nt/my-epidemic-monitor/blob/main/functions/api/health/v1/news.ts"
click node_climate_api "https://github.com/phuc-nt/my-epidemic-monitor/blob/main/functions/api/health/v1/climate.ts"
click node_outbreak_api "https://github.com/phuc-nt/my-epidemic-monitor/blob/main/functions/api/health/v1/outbreaks.ts"
click node_chat_api "https://github.com/phuc-nt/my-epidemic-monitor/blob/main/functions/api/chat.ts"
click node_shared_norm "https://github.com/phuc-nt/my-epidemic-monitor/blob/main/functions/_shared/outbreak-query.ts"
click node_geojson "https://github.com/phuc-nt/my-epidemic-monitor/blob/main/public/data/vietnam-districts.geojson"

classDef toneNeutral fill:#f8fafc,stroke:#334155,stroke-width:1.5px,color:#0f172a
classDef toneBlue fill:#dbeafe,stroke:#2563eb,stroke-width:1.5px,color:#172554
classDef toneAmber fill:#fef3c7,stroke:#d97706,stroke-width:1.5px,color:#78350f
classDef toneMint fill:#dcfce7,stroke:#16a34a,stroke-width:1.5px,color:#14532d
classDef toneRose fill:#ffe4e6,stroke:#e11d48,stroke-width:1.5px,color:#881337
classDef toneIndigo fill:#e0e7ff,stroke:#4f46e5,stroke-width:1.5px,color:#312e81
classDef toneTeal fill:#ccfbf1,stroke:#0f766e,stroke-width:1.5px,color:#134e4a
class node_main,node_app_init,node_app_layout,node_app_context,node_map_shell,node_map_layers,node_panels,node_chat_panel,node_mobile_tabs,node_panel_state,node_api_client,node_snapshot_store,node_trend_calc,node_llm_router,node_llm_context toneBlue
class node_functions_mw,node_health_api,node_news_api,node_climate_api,node_outbreak_api,node_chat_api,node_shared_norm toneAmber
class node_d1_snapshots,node_crawler_pipeline,node_openrouter,node_local_llms,node_geojson toneMint
```

## Components

### Browser UI

Client-side single-page app, map, panels, and local state.

- [App boot](https://github.com/phuc-nt/my-epidemic-monitor/blob/main/src/main.ts): bootstrap · Entry point that starts the client application. · `src/main.ts`
- [App init](https://github.com/phuc-nt/my-epidemic-monitor/blob/main/src/app/app-init.ts): shell · Initializes global app state and wiring. · `src/app/app-init.ts`
- [Layout](https://github.com/phuc-nt/my-epidemic-monitor/blob/main/src/app/app-layout.ts): shell · Composes the map-centric page structure and responsive regions. · `src/app/app-layout.ts`
- [App context](https://github.com/phuc-nt/my-epidemic-monitor/blob/main/src/app/app-context.ts): state · Shared client state and context for the UI. · `src/app/app-context.ts`
- [Map shell](https://github.com/phuc-nt/my-epidemic-monitor/blob/main/src/components/map-shell.ts): map-ui · Main map container and interaction surface. · `src/components/map-shell.ts`
- [Map layers](https://github.com/phuc-nt/my-epidemic-monitor/blob/main/src/components/map-layers/index.ts): geospatial overlays · Country, district, outbreak, early-warning, and severity overlays. · `src/components/map-layers/index.ts`
- [Info panels](https://github.com/phuc-nt/my-epidemic-monitor/blob/main/src/components/index.ts): panels · Disease, climate, news, and case-report panels shown alongside the map. · `src/components/index.ts`
- [Chat panel](https://github.com/phuc-nt/my-epidemic-monitor/blob/main/src/components/chat-panel.ts): ai-ui · Conversational UI for asking questions about health risk signals. · `src/components/chat-panel.ts`
- [Mobile tabs](https://github.com/phuc-nt/my-epidemic-monitor/blob/main/src/components/mobile-tab-bar.ts): navigation · Mobile affordance that replaces desktop panel navigation. · `src/components/mobile-tab-bar.ts`
- [Panel state](https://github.com/phuc-nt/my-epidemic-monitor/blob/main/src/components/panel-base.ts): ui-state · Shared panel behavior and persistence across visits. · `src/components/panel-base.ts`
- [API client](https://github.com/phuc-nt/my-epidemic-monitor/blob/main/src/services/api-client.ts): data access · Common client entry point for fetching health data. · `src/services/api-client.ts`
- [Snapshots](https://github.com/phuc-nt/my-epidemic-monitor/blob/main/src/services/snapshot-store.ts): client data · Client-side view of precomputed time-series and cached snapshots. · `src/services/snapshot-store.ts`
- [Trend calc](https://github.com/phuc-nt/my-epidemic-monitor/blob/main/src/services/trend-calculator.ts): analytics · Derives trend signals used in map layers and panels. · `src/services/trend-calculator.ts`
- [LLM router](https://github.com/phuc-nt/my-epidemic-monitor/blob/main/src/services/llm-router.ts): ai orchestration · Selects and drives chat model backends. · `src/services/llm-router.ts`
- [Prompt context](https://github.com/phuc-nt/my-epidemic-monitor/blob/main/src/services/llm-context-builder.ts): ai context · Builds grounded context for chat from app data. · `src/services/llm-context-builder.ts`

### Cloudflare Edge

Serverless API and shared middleware deployed on Cloudflare Pages/Workers.

- [Middleware](https://github.com/phuc-nt/my-epidemic-monitor/blob/main/functions/_middleware.ts): edge middleware · Cross-cutting request handling such as CORS and caching. · `functions/_middleware.ts`
- [Health API](https://github.com/phuc-nt/my-epidemic-monitor/blob/main/functions/api/health/v1/all.ts): edge api · Aggregated health data endpoints served from Cloudflare Functions. · `functions/api/health/v1/all.ts`
- [News API](https://github.com/phuc-nt/my-epidemic-monitor/blob/main/functions/api/health/v1/news.ts): edge api · News signal endpoint for the UI. · `functions/api/health/v1/news.ts`
- [Climate API](https://github.com/phuc-nt/my-epidemic-monitor/blob/main/functions/api/health/v1/climate.ts): edge api · Climate alert endpoint for the UI. · `functions/api/health/v1/climate.ts`
- [Outbreak API](https://github.com/phuc-nt/my-epidemic-monitor/blob/main/functions/api/health/v1/outbreaks.ts): edge api · Outbreak endpoint for disease events and normalization. · `functions/api/health/v1/outbreaks.ts`
- [Chat API](https://github.com/phuc-nt/my-epidemic-monitor/blob/main/functions/api/chat.ts): edge api · Serverless conversational endpoint that streams AI responses. · `functions/api/chat.ts`
- [Shared data](https://github.com/phuc-nt/my-epidemic-monitor/blob/main/functions/_shared/outbreak-query.ts): edge helpers · Lookup, cache, CORS, and outbreak normalization helpers. · `functions/_shared/outbreak-query.ts`

### Data Sources

External model providers and upstream data ingestion feeding the app.

- **D1 snapshots**: database · Persisted health snapshots and precomputed data served by the API.
- **Crawler pipeline**: upstream ingestion · Separate crawl/extract pipeline on a Mac Mini that refreshes D1.
- **OpenRouter**: llm provider · Primary external model gateway for chat inference.
- **Local providers**: llm backends · Optional Ollama, MLX, and proxy backends for chat.
- [District geojson](https://github.com/phuc-nt/my-epidemic-monitor/blob/main/public/data/vietnam-districts.geojson): boundary data · Vietnam district boundaries used for choropleths and map overlays. · `public/data/vietnam-districts.geojson`

## Connections

- App boot → App init: boots · Starts the application shell.
- App init → App context: creates · Initializes shared state.
- App init → Layout: mounts · Composes the page structure.
- Layout → Map shell: contains · Places the map as the central workspace.
- Layout → Info panels: contains · Places health panels around the map.
- Layout → Chat panel: includes · Exposes the AI chat surface.
- Layout → Mobile tabs: adapts · Switches panel navigation on small screens.
- Info panels → Panel state: shares · Uses common panel persistence and behavior.
- Map shell → Map layers: renders · Adds choropleths, markers, and heat overlays.
- Map layers → District geojson: reads boundaries · Uses district geometry for geographic visualization.
- Info panels → API client: fetches data · Loads health, climate, news, and outbreak content.
- Map layers → Snapshots: consumes · Uses snapshot-backed metrics for visualization.
- Trend calc → Map layers: feeds trends · Provides derived signals for overlays.
- API client → Health API: requests · Fetches aggregated health data.
- API client → News API: requests · Fetches news signals.
- API client → Climate API: requests · Fetches climate alerts.
- API client → Outbreak API: requests · Fetches outbreak records.
- Middleware → Health API: wraps · Applies cross-cutting request handling.
- Middleware → News API: wraps · Applies cross-cutting request handling.
- Middleware → Climate API: wraps · Applies cross-cutting request handling.
- Middleware → Outbreak API: wraps · Applies cross-cutting request handling.
- Health API → Shared data: uses · Normalizes and enriches returned records.
- News API → Shared data: uses · Shares cache and lookup helpers.
- Climate API → Shared data: uses · Shares cache and lookup helpers.
- Outbreak API → Shared data: uses · Shares outbreak and population helpers.
- Health API → D1 snapshots: reads · Serves persisted health snapshots.
- News API → D1 snapshots: reads · Serves news-backed snapshots.
- Climate API → D1 snapshots: reads · Serves climate-backed snapshots.
- Outbreak API → D1 snapshots: reads · Serves outbreak-backed snapshots.
- Crawler pipeline → D1 snapshots: writes · Refreshes the stored dataset out of band.
- Chat panel → Chat API: calls · Sends chat requests to the serverless endpoint.
- Chat API → LLM router: routes · Chooses the active inference backend.
- LLM router → OpenRouter: uses · Primary hosted model path.
- LLM router → Local providers: falls back to · Optional local or proxy providers.
- Chat API → Prompt context: builds context · Assembles grounded prompt context from app data.
