From 233fdbf66cfa9bff921e2c8f77ea3feb4ccdd90d Mon Sep 17 00:00:00 2001 From: Noel Sabia Date: Sat, 14 Nov 2026 06:59:07 +0100 Subject: [PATCH] feat: live SSE stage, phone view and presenter control - proxy Go /api/stream through Nitro; drive /stage, /live, /plan and /forecast from scenario events - fall back to 5 s polling after SSE failures or heartbeat silence; show Live/Polling/Offline - authenticate /control and POST /api/scenario in Nitro with server-side control credentials - add big-screen stage with local QR and a no-login phone recommendation view - add SSE unit tests and a live smoke test; refresh README/Makefile --- Makefile | 7 +- README.md | 74 +++- app/app.vue | 7 +- app/components/LiveStatusBadge.vue | 37 ++ app/composables/useLiveScenario.ts | 276 ++++++++++++++ app/pages/about.vue | 6 +- app/pages/control.vue | 264 ++++++++++++++ app/pages/forecast.vue | 74 +++- app/pages/live.vue | 324 +++++++++++++++++ app/pages/plan.vue | 30 +- app/pages/simulate.vue | 7 +- app/pages/stage.vue | 560 +++++++++++++++++++++++++++++ app/utils/api-error.ts | 27 ++ package-lock.json | 325 +++++++++++++++++ package.json | 5 +- scripts/smoke-live.mjs | 387 ++++++++++++++++++++ server/api/qr.get.ts | 35 ++ server/api/scenario.get.ts | 4 +- server/api/scenario.post.ts | 11 +- server/api/stream.get.ts | 24 ++ server/middleware/control-auth.ts | 101 ++++++ server/utils/mock-scenario.ts | 24 ++ shared/live.ts | 101 ++++++ test/live.test.ts | 96 +++++ 24 files changed, 2757 insertions(+), 49 deletions(-) create mode 100644 app/components/LiveStatusBadge.vue create mode 100644 app/composables/useLiveScenario.ts create mode 100644 app/pages/control.vue create mode 100644 app/pages/live.vue create mode 100644 app/pages/stage.vue create mode 100644 app/utils/api-error.ts create mode 100644 scripts/smoke-live.mjs create mode 100644 server/api/qr.get.ts create mode 100644 server/api/stream.get.ts create mode 100644 server/middleware/control-auth.ts create mode 100644 server/utils/mock-scenario.ts create mode 100644 shared/live.ts create mode 100644 test/live.test.ts diff --git a/Makefile b/Makefile index 7dd6469..1c77a2b 100644 --- a/Makefile +++ b/Makefile @@ -1,6 +1,6 @@ NPM ?= npm -.PHONY: install dev build test check preview docker-build smoke +.PHONY: install dev build test check preview docker-build smoke smoke-live install: $(NPM) ci @@ -26,3 +26,8 @@ docker-build: # Requires a running web server (npm run preview or node .output/server/index.mjs). smoke: node scripts/smoke-api.mjs + +# Requires Go on 18080, ML on 18000 and this app on 13000. +# See README "Live stack" for the exact environment. +smoke-live: + node scripts/smoke-live.mjs diff --git a/README.md b/README.md index e1cd1b2..2d6a0d2 100644 --- a/README.md +++ b/README.md @@ -35,6 +35,50 @@ NUXT_API_INTERNAL_BASE=http://localhost:8080 \ PORT=3000 node .output/server/index.mjs ``` +## Live demo: `/stage`, `/live`, `/control` + +```text +browser ──GET /api/stream──► Nuxt Nitro ──proxy──► Go /api/stream + ◄── scenario/ping ── ◄────────── SSE hub +presenter ──POST /api/scenario──► Nitro (Basic auth + control secret) ──► Go +``` + +- `app/composables/useLiveScenario.ts` opens one `EventSource` per tab. On a + `scenario` event it updates the shared state and tells the page to refetch; + `ping` heartbeats keep the connection marked **Live**. +- After two SSE errors, or when no heartbeat arrives for 32 s (a buffering + proxy), the client closes ranks and polls `GET /api/scenario` every 5 s. The + badge shows **Live**, **Polling** or **Offline**, never a silent stale plan. +- `POST /api/scenario` goes through Nitro; the Go control credentials stay in + the Node process. `/control` itself requires HTTP Basic auth + (`CONTROL_USER`/`CONTROL_PASS`); a signed cookie lets the page POST without + re-prompting. `/stage`, `/live` and all public GETs stay open. +- `/stage` renders a local SVG QR code (`/api/qr`) pointing at `/live`; no + third-party QR service is called. + +### Live stack (read-only Go/ML worktrees) + +```bash +# 1. ML on 18000 (from ML-py.git/main) +PYTHONPATH=src CONTROL_TOKEN=replace-me-token \ + .venv/bin/uvicorn pulsecast.server:app --host 127.0.0.1 --port 18000 + +# 2. Go on 18080 (from api-go.git/main) +PORT=18080 FASTAPI_URL=http://127.0.0.1:18000 \ + CONTROL_USER=control CONTROL_PASS=replace-me-pass CONTROL_TOKEN=replace-me-token \ + go run ./cmd/api + +# 3. Web preview on 13000 (from this worktree, after npm run build) +PORT=13000 NUXT_API_INTERNAL_BASE=http://127.0.0.1:18080 \ + CONTROL_USER=control CONTROL_PASS=replace-me-pass CONTROL_TOKEN=replace-me-token \ + node .output/server/index.mjs + +# 4. Live smoke: auth boundary, /stage + /live SSR, QR, SSE event, +# polling read, and a staffing/forecast plan that differs from base. +CONTROL_USER=control CONTROL_PASS=replace-me-pass WEB_URL=http://127.0.0.1:13000 \ + node scripts/smoke-live.mjs +``` + ## API wiring Every route in `server/api/` is a proxy to the Go service. The default is the @@ -51,7 +95,9 @@ real API; mock JSON is an explicit dev fallback only. | `GET /api/forecast` | `GET /api/forecast` | | `GET /api/staffing` | `GET /api/staffing` | | `GET /api/scenario` | `GET /api/scenario` | +| `GET /api/stream` | `GET /api/stream`, streamed chunk-by-chunk (SSE) | | `POST /api/scenario` | `POST /api/scenario` with server-side control auth | +| `GET /api/qr?text=` | Local SVG QR generation, no upstream call | | `POST /api/train` | `POST /api/train` with server-side control auth | | `GET /api/train/:job_id` | `GET /api/train/{job_id}` with server-side control auth | | `GET /api/scenarios` | Local UI metadata only (labels/descriptions) | @@ -72,14 +118,16 @@ heuristic is tested against a captured Go response in | `NUXT_PUBLIC_API_BASE` | — | Fallback base; also exposed to the browser | | `NUXT_API_TIMEOUT_MS` | `8000` | Upstream request timeout | | `NUXT_PUBLIC_USE_MOCK` / `NUXT_USE_MOCK` | unset | `1` enables the mock fallback | -| `CONTROL_USER` / `CONTROL_PASS` | unset | Basic auth for `/api/scenario` and `/api/train` | +| `NUXT_DISABLE_SSE` | unset | `1` forces the polling fallback (SSE failure drill) | +| `CONTROL_USER` / `CONTROL_PASS` | unset | Basic auth for `/control` and `POST /api/scenario`; also attached to Go `/api/train` | | `CONTROL_TOKEN` | unset | Optional Bearer token for future control auth | | `NUXT_PUBLIC_DEMO_NOW` | `2026-11-14T08:12:00Z` | Replay clock used for labels | Control credentials are read only in the Nitro process. They are never placed -in `runtimeConfig.public` and never reach the browser bundle. If they are -unset, Go returns `503 control_auth_unconfigured` / `401`; the UI surfaces that -error instead of exposing anything. +in `runtimeConfig.public` and never reach the browser bundle. `/control` and +`POST /api/scenario` require Basic auth at Nitro, and Nitro then attaches the +same credentials to Go. If `CONTROL_USER`/`CONTROL_PASS` are unset, the control +surface returns `503 control_auth_unconfigured`; public screens keep working. The K8s web Deployment must mount the same `control-auth` secret as the API Deployment: @@ -110,6 +158,9 @@ deployed path are the real API. | `/forecast` | 7-day daily forecast, uncertainty band, weather strip | | `/plan` | **Hero.** Peak decision, shift blocks, coverage, cost, why, assumptions | | `/simulate` | Base vs scenario plan, both read from Go `/api/staffing` | +| `/stage` | Big-screen decision: headline, peak staff, cost, coverage, QR to `/live` | +| `/live` | Phone view: current recommendation, peak shift, scenario, last update | +| `/control` | Presenter preset buttons; authenticated POST through Nitro | | `/about` | Method, metrics, limits, privacy, train form | The layout is checked at **390 px** (single column, mobile Onyx nav, day cards) @@ -134,8 +185,9 @@ hours instead of hiding them. ## Checks and CI ```bash -make check # npm ci, npm run build, npm test -make smoke # against a running web server (WEB_URL=...) +make check # npm ci, npm run build, npm test +make smoke # Nitro -> Go API contract, against a running web server +make smoke-live # SSE + control + /stage + /live, against the 18080/18000/13000 stack ``` The same `make check` runs in Gitea Actions (`.gitea/workflows/ci.yml`). The @@ -145,6 +197,13 @@ workflow needs no secrets, no registry push and no cluster access. context, meta, series, base and scenario forecasts, standard and premium staffing, local presets, and 404/400 propagation. +`scripts/smoke-live.mjs` proves the live path: unauthorised POST is rejected, +`/control` authenticates, `/stage` and `/live` render server-side, `/api/qr` +returns SVG, the SSE proxy emits `retry: 3000` and the initial scenario, a +presenter POST produces a `scenario` event (with matching `id` and version) in +well under 2 s, polling reads the same version, and the target staffing and +forecast responses differ from base. It restores the base scenario at the end. + ## Docker ```bash @@ -164,5 +223,6 @@ numeric UID/GID **`10001:10001`**, uses `COPY --chown=10001:10001` and runs - No POS, sales, queue or payroll data. Cost is an assumption. - Forecast is model output; the plan is decision support, not an optimizer. - Eight sensors in a 580 m cluster; no city-wide heatmap claim. -- SSE (`/api/stream`), `/live` and `/stage` are the next worktree. +- SSE state is in memory in the single Go pod. A pod restart drops streams; + clients reconnect via `retry: 3000` or fall back to 5 s polling. - Raw CSV, secrets and kubeconfig never enter this repository. diff --git a/app/app.vue b/app/app.vue index c3adce4..bd056fa 100644 --- a/app/app.vue +++ b/app/app.vue @@ -5,6 +5,8 @@ import { iconCircleInformation, iconFlash, iconHome, + iconMobileSignal, + iconPresentionBoard, } from '@sit-onyx/icons' const route = useRoute() @@ -21,11 +23,14 @@ const navigation = [ { to: '/forecast', label: 'Forecast', icon: iconChart }, { to: '/plan', label: 'Plan', icon: iconCalendar }, { to: '/simulate', label: 'Simulate', icon: iconFlash }, + { to: '/stage', label: 'Stage', icon: iconPresentionBoard }, + { to: '/live', label: 'Live', icon: iconMobileSignal }, { to: '/about', label: 'About', icon: iconCircleInformation }, ] +const hiddenPageLabels: Record = { '/control': 'Control' } const activeLabel = computed( - () => navigation.find((item) => item.to === route.path)?.label ?? 'PulseCast', + () => navigation.find((item) => item.to === route.path)?.label ?? hiddenPageLabels[route.path] ?? 'PulseCast', ) diff --git a/app/components/LiveStatusBadge.vue b/app/components/LiveStatusBadge.vue new file mode 100644 index 0000000..9b4fbd9 --- /dev/null +++ b/app/components/LiveStatusBadge.vue @@ -0,0 +1,37 @@ + + + + + diff --git a/app/composables/useLiveScenario.ts b/app/composables/useLiveScenario.ts new file mode 100644 index 0000000..e092f3c --- /dev/null +++ b/app/composables/useLiveScenario.ts @@ -0,0 +1,276 @@ +import { + LIVE_LABELS, + liveStatus, + parseScenarioEvent, + scenarioChanged, + SCENARIO_POLL_MS, + SSE_FAILURES_BEFORE_POLLING, + SSE_STALE_MS, +} from '#shared/live' +import type { LiveConnection } from '#shared/live' +import type { ScenarioState } from '#shared/types' + +interface LiveStore { + status: LiveConnection + serverScenario: ScenarioState | null + lastEventAt: string + lastPollAt: string + sseFailures: number + pollFailures: number + revision: number + error: string +} + +// One stream per browser tab. The module-level store survives page navigation +// and is only mutated from onMounted/EventSource callbacks (never during SSR). +const store = reactive({ + status: 'connecting', + serverScenario: null, + lastEventAt: '', + lastPollAt: '', + sseFailures: 0, + pollFailures: 0, + revision: 0, + error: '', +}) + +let source: EventSource | null = null +let pollTimer: ReturnType | null = null +let staleTimer: ReturnType | null = null +let reconnectTimer: ReturnType | null = null +let subscribers = 0 +let started = false +let lastStaleRetry = 0 + +function nowIso(): string { + return new Date().toISOString() +} + +function refreshStatus() { + store.status = liveStatus({ + online: import.meta.client ? navigator.onLine !== false : true, + sseOpen: source?.readyState === EventSource.OPEN, + sseFailures: store.sseFailures, + polling: pollTimer !== null, + pollFailures: store.pollFailures, + }) +} + +function clearPolling() { + if (pollTimer) clearInterval(pollTimer) + pollTimer = null +} + +function applyScenario(next: ScenarioState, origin: 'sse' | 'poll') { + const changed = scenarioChanged(store.serverScenario, next) + store.serverScenario = next + store.lastEventAt = nowIso() + store.error = '' + if (origin === 'poll') store.lastPollAt = store.lastEventAt + if (changed) store.revision += 1 +} + +async function pollScenario(): Promise { + if (!import.meta.client) return + try { + const next = await $fetch('/api/scenario', { + headers: { accept: 'application/json' }, + timeout: 5000, + }) + store.pollFailures = 0 + applyScenario(next, 'poll') + // A successful poll proves the API is reachable; stay "Polling" until SSE + // opens again, so the audience can see the fallback is active. + if (store.status === 'offline') store.status = 'polling' + } catch (error) { + store.pollFailures += 1 + store.error = (error as { statusMessage?: string })?.statusMessage ?? 'Scenario polling failed' + } + refreshStatus() +} + +function startPolling() { + if (!import.meta.client || pollTimer) return + void pollScenario() + pollTimer = setInterval(() => void pollScenario(), SCENARIO_POLL_MS) + refreshStatus() +} + +function closeSource() { + if (source) { + source.close() + source = null + } + if (reconnectTimer) clearTimeout(reconnectTimer) + reconnectTimer = null +} + +function connectSse() { + if (!import.meta.client) return + closeSource() + + if (navigator.onLine === false) { + store.status = 'offline' + startPolling() + return + } + + const eventSource = new EventSource('/api/stream') + source = eventSource + + eventSource.onopen = () => { + if (source !== eventSource) return + store.sseFailures = 0 + store.pollFailures = 0 + store.error = '' + // Start the stale watchdog now: a proxy can accept the SSE headers and + // then buffer the body, so "open" does not prove events are flowing. + store.lastEventAt = nowIso() + clearPolling() + refreshStatus() + } + + eventSource.addEventListener('scenario', (event) => { + if (source !== eventSource) return + const parsed = parseScenarioEvent((event as MessageEvent).data) + if (!parsed) { + store.error = 'Ignored a malformed scenario event' + return + } + store.sseFailures = 0 + applyScenario(parsed, 'sse') + refreshStatus() + }) + + eventSource.addEventListener('ping', () => { + if (source !== eventSource) return + store.sseFailures = 0 + store.lastEventAt = nowIso() + if (pollTimer && eventSource.readyState === EventSource.OPEN) clearPolling() + refreshStatus() + }) + + eventSource.onerror = () => { + if (source !== eventSource) return + store.sseFailures += 1 + + // A non-200 response (Nitro 502/503, proxy error) leaves EventSource in + // CLOSED and the browser will not retry it. Treat that as a definitive + // failure: start polling now and try the stream again on a timer. Network + // errors while CONNECTING still use the browser's own retry loop. + const fatal = eventSource.readyState === EventSource.CLOSED + if (fatal) { + store.sseFailures = Math.max(store.sseFailures, SSE_FAILURES_BEFORE_POLLING) + if (!reconnectTimer) { + reconnectTimer = setTimeout(() => { + if (!started) return + connectSse() + }, 5000) + } + } + + if (store.sseFailures >= SSE_FAILURES_BEFORE_POLLING) startPolling() + refreshStatus() + } +} + +function checkStale() { + if (!import.meta.client || !started) return + const sseOpen = source?.readyState === EventSource.OPEN + if (sseOpen && store.lastEventAt) { + const age = Date.now() - Date.parse(store.lastEventAt) + if (age > SSE_STALE_MS) { + // Connection is open but no ping arrived: Cloudflare/path buffering. + // Polling is the contract fallback; retry SSE once a minute. + store.sseFailures = Math.max(store.sseFailures, SSE_FAILURES_BEFORE_POLLING) + startPolling() + refreshStatus() + if (Date.now() - lastStaleRetry > 60000) { + lastStaleRetry = Date.now() + connectSse() + } + } + } + if (store.pollFailures > 0) refreshStatus() +} + +function start() { + if (!import.meta.client || started) return + started = true + store.sseFailures = 0 + store.pollFailures = 0 + store.lastEventAt = '' + store.error = '' + store.status = 'connecting' + window.addEventListener('online', handleOnline) + window.addEventListener('offline', handleOffline) + staleTimer = setInterval(checkStale, 5000) + connectSse() +} + +function stop() { + if (!import.meta.client) return + started = false + closeSource() + clearPolling() + if (staleTimer) clearInterval(staleTimer) + staleTimer = null + window.removeEventListener('online', handleOnline) + window.removeEventListener('offline', handleOffline) + store.status = 'connecting' +} + +function handleOnline() { + if (!started) return + store.pollFailures = 0 + connectSse() + void pollScenario() +} + +function handleOffline() { + if (!started) return + store.status = 'offline' + if (pollTimer) clearInterval(pollTimer) + pollTimer = null +} + +/** + * Subscribe the current page to the Go scenario stream through Nitro. + * + * The first render uses `initial` from SSR; after mount the composable opens + * `/api/stream`, shows Live/Polling/Offline, and falls back to GET + * /api/scenario every 5 s when SSE fails or is buffered. + */ +export function useLiveScenario(initial?: ScenarioState | null) { + const initialScenario = initial ?? null + + const current = computed(() => store.serverScenario ?? initialScenario) + const scenarioId = computed(() => current.value?.scenario.scenario ?? 'base') + const status = computed(() => store.status) + const statusLabel = computed(() => LIVE_LABELS[store.status]) + + onMounted(() => { + // Seed after hydration so the first client paint matches the SSR HTML. + if (initialScenario && !store.serverScenario) store.serverScenario = initialScenario + subscribers += 1 + start() + }) + onBeforeUnmount(() => { + subscribers = Math.max(0, subscribers - 1) + if (subscribers === 0) stop() + }) + + return reactive({ + scenario: current, + scenarioId, + version: computed(() => current.value?.version ?? 0), + scenarioAt: computed(() => current.value?.at ?? ''), + status, + statusLabel, + lastEventAt: computed(() => store.lastEventAt), + lastPollAt: computed(() => store.lastPollAt), + error: computed(() => store.error), + revision: computed(() => store.revision), + pollNow: pollScenario, + }) +} diff --git a/app/pages/about.vue b/app/pages/about.vue index 36f494c..e6a91f5 100644 --- a/app/pages/about.vue +++ b/app/pages/about.vue @@ -8,7 +8,7 @@ useHead({ title: 'About the data and limits — PulseCast' }) const { data: meta } = await useFetch('/api/meta') const config = useRuntimeConfig() -const usingMock = computed(() => Boolean(config.public.useMock)) +const usingMock = computed(() => ['1', 'true'].includes(String(config.public.useMock).toLowerCase()))

@@ -426,6 +442,10 @@ function exportPlan() { The staffing API could not be loaded. Check that the Go API is running and that NUXT_API_INTERNAL_BASE points to it. {{ error.statusMessage }} +
+ + No open hours are available for this store and scenario yet. Pick another sensor or check the data window. +
Plan inputs

- Store, service standard and scenario are sent to Go `/api/staffing`. Local assumption edits render a + Store, service standard and scenario are sent to Go /api/staffing. Local assumption edits render a preview from the API forecast.

@@ -555,7 +575,7 @@ function exportPlan() { message="Assumption only. No payroll or POS data exists." />

- These four values are not query inputs of Go `/api/staffing`. Changing them shows a local preview; + These four values are not query inputs of Go /api/staffing. Changing them shows a local preview; “Use API plan” restores the server values.

@@ -720,7 +740,7 @@ function exportPlan() {

Weather during the plan week

- The weather forecast from `/api/context` does not cover this plan window yet. + The weather forecast from /api/context does not cover this plan window yet.

{{ activeScenario?.description ?? 'Base scenario uses the API forecast weather.' }} diff --git a/app/pages/simulate.vue b/app/pages/simulate.vue index e3de88c..c6261a1 100644 --- a/app/pages/simulate.vue +++ b/app/pages/simulate.vue @@ -136,8 +136,9 @@ const days = computed(() =>

- The base and scenario plans are generated by Go `/api/staffing`. SSE broadcast to /stage and - phones is the next slice; this page makes the recommendation change visible on one screen. + The base and scenario plans are generated by Go /api/staffing. The presenter broadcasts from + /control; /stage and + /live follow the scenario over SSE with a 5 s polling fallback.
@@ -246,7 +247,7 @@ const days = computed(() =>

Scenario perturbations are produced by the Go/ML stack. This page reads the base and scenario plans from - `/api/staffing`; it does not invent its own multipliers. + /api/staffing; it does not invent its own multipliers.

diff --git a/app/pages/stage.vue b/app/pages/stage.vue new file mode 100644 index 0000000..e37ea00 --- /dev/null +++ b/app/pages/stage.vue @@ -0,0 +1,560 @@ + + + + + diff --git a/app/utils/api-error.ts b/app/utils/api-error.ts new file mode 100644 index 0000000..be2b380 --- /dev/null +++ b/app/utils/api-error.ts @@ -0,0 +1,27 @@ +interface ApiErrorLike { + status?: number + statusCode?: number + statusMessage?: string + message?: string + data?: { + error?: { message?: string; code?: string } + message?: string + } +} + +/** Human-readable message from a Nuxt/$fetch error, without leaking tokens. */ +export function apiErrorMessage(error: unknown, fallback: string): string { + const value = error as ApiErrorLike | undefined + return ( + value?.data?.error?.message ?? + value?.data?.message ?? + value?.statusMessage ?? + value?.message ?? + fallback + ) +} + +export function apiErrorStatus(error: unknown): number | undefined { + const value = error as ApiErrorLike | undefined + return value?.status ?? value?.statusCode +} diff --git a/package-lock.json b/package-lock.json index 70be9ad..8edd813 100644 --- a/package-lock.json +++ b/package-lock.json @@ -13,9 +13,11 @@ "chart.js": "4.6.1", "maplibre-gl": "6.18.0", "nuxt": "4.6.4", + "qrcode": "1.5.4", "sit-onyx": "1.22.0" }, "devDependencies": { + "@types/qrcode": "1.5.5", "typescript": "5.9.3", "vitest": "3.2.4" } @@ -2669,6 +2671,26 @@ "integrity": "sha512-6C8nqWur3j98U6+lXDfTUWIfgvZU+EumvpHKcYjujKH7woYyLj2sUmff0tRhrqM7BohUw7Pz3ZB1jj2gW9Fvmg==", "license": "MIT" }, + "node_modules/@types/node": { + "version": "26.6.6", + "resolved": "https://registry.npmjs.org/@types/node/-/node-26.6.6.tgz", + "integrity": "sha512-MzQj+8Kx3XI40OmUAE6Qoh58ZMNstNNMwn2nfd3qWsfe7nDNSqJNzes4njhz6AHwrSHOffSLwXU6yb474Q4aog==", + "devOptional": true, + "license": "MIT", + "dependencies": { + "undici-types": "~8.9.0" + } + }, + "node_modules/@types/qrcode": { + "version": "1.5.5", + "resolved": "https://registry.npmjs.org/@types/qrcode/-/qrcode-1.5.5.tgz", + "integrity": "sha512-CdfBi/e3Qk+3Z/fXYShipBT13OJ2fDO2Q2w5CIP5anLTLIndQG9z6P1cnm+8zCWSpm5dnxMFd/uREtb0EXuQzg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, "node_modules/@types/resolve": { "version": "1.20.2", "resolved": "https://registry.npmjs.org/@types/resolve/-/resolve-1.20.2.tgz", @@ -3835,6 +3857,15 @@ "node": ">=20.19.0" } }, + "node_modules/camelcase": { + "version": "5.3.1", + "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-5.3.1.tgz", + "integrity": "sha512-L28STB170nwWS63UjtlEOE3dldQApaJXZkOI1uMFfzf3rRuPegHaHesyee+YxQ+W6SvRDQV6UrdOdRiR153wJg==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, "node_modules/caniuse-api": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/caniuse-api/-/caniuse-api-4.0.0.tgz", @@ -3983,6 +4014,24 @@ "node": ">=0.10.0" } }, + "node_modules/color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "license": "MIT", + "dependencies": { + "color-name": "~1.1.4" + }, + "engines": { + "node": ">=7.0.0" + } + }, + "node_modules/color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "license": "MIT" + }, "node_modules/commander": { "version": "2.20.3", "resolved": "https://registry.npmjs.org/commander/-/commander-2.20.3.tgz", @@ -4230,6 +4279,15 @@ } } }, + "node_modules/decamelize": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/decamelize/-/decamelize-1.2.0.tgz", + "integrity": "sha512-z2S+W9X73hAUUki+N+9Za2lBlun89zigOyGrsax+KUQ6wKW4ZoWpEYBkGhQjwAjjDCkWxhY0VKEhk8wzY7F5cA==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, "node_modules/deep-eql": { "version": "5.0.2", "resolved": "https://registry.npmjs.org/deep-eql/-/deep-eql-5.0.2.tgz", @@ -4346,6 +4404,12 @@ "node": ">=0.3.1" } }, + "node_modules/dijkstrajs": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/dijkstrajs/-/dijkstrajs-1.0.3.tgz", + "integrity": "sha512-qiSlmBq9+BCdCA/L46dw8Uy93mloxsPSbwnm5yrKn2vMPiy8KyAskTF6zuV/j5BMsmOGZDPs7KjU+mjb670kfA==", + "license": "MIT" + }, "node_modules/dot-prop": { "version": "10.2.0", "resolved": "https://registry.npmjs.org/dot-prop/-/dot-prop-10.2.0.tgz", @@ -4718,6 +4782,19 @@ "node": ">=8" } }, + "node_modules/find-up": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-4.1.0.tgz", + "integrity": "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==", + "license": "MIT", + "dependencies": { + "locate-path": "^5.0.0", + "path-exists": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, "node_modules/flru": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/flru/-/flru-1.0.2.tgz", @@ -5186,6 +5263,15 @@ "node": ">=0.10.0" } }, + "node_modules/is-fullwidth-code-point": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", + "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, "node_modules/is-glob": { "version": "4.0.3", "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz", @@ -5795,6 +5881,18 @@ "url": "https://github.com/sponsors/antfu" } }, + "node_modules/locate-path": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-5.0.0.tgz", + "integrity": "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==", + "license": "MIT", + "dependencies": { + "p-locate": "^4.1.0" + }, + "engines": { + "node": ">=8" + } + }, "node_modules/loupe": { "version": "3.2.1", "resolved": "https://registry.npmjs.org/loupe/-/loupe-3.2.1.tgz", @@ -6684,6 +6782,42 @@ } } }, + "node_modules/p-limit": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.3.0.tgz", + "integrity": "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==", + "license": "MIT", + "dependencies": { + "p-try": "^2.0.0" + }, + "engines": { + "node": ">=6" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/p-locate": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-4.1.0.tgz", + "integrity": "sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==", + "license": "MIT", + "dependencies": { + "p-limit": "^2.2.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/p-try": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/p-try/-/p-try-2.2.0.tgz", + "integrity": "sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, "node_modules/package-manager-detector": { "version": "1.9.0", "resolved": "https://registry.npmjs.org/package-manager-detector/-/package-manager-detector-1.9.0.tgz", @@ -6699,6 +6833,15 @@ "node": ">= 0.8" } }, + "node_modules/path-exists": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", + "integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, "node_modules/path-key": { "version": "3.1.1", "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", @@ -6802,6 +6945,15 @@ "pathe": "^2.0.3" } }, + "node_modules/pngjs": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/pngjs/-/pngjs-5.0.0.tgz", + "integrity": "sha512-40QW5YalBNfQo5yRYmiw7Yz6TKKVr3h6970B2YE+3fQpsWcrbj1PzJgxeJ19DRQjhMbKPIuMY8rFaXc8moolVw==", + "license": "MIT", + "engines": { + "node": ">=10.13.0" + } + }, "node_modules/postcss": { "version": "8.5.33", "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.33.tgz", @@ -6919,6 +7071,145 @@ "integrity": "sha512-VG2K63Igkiv9p76tk1lilczEK1cT+kCjKtkdhw1dQZV3k3IXJbd3o6Ho8b9zJZaHSnT2hKe4I+ObmX9w6m5SmQ==", "license": "MIT" }, + "node_modules/qrcode": { + "version": "1.5.4", + "resolved": "https://registry.npmjs.org/qrcode/-/qrcode-1.5.4.tgz", + "integrity": "sha512-1ca71Zgiu6ORjHqFBDpnSMTR2ReToX4l1Au1VFLyVeBTFavzQnv5JxMFr3ukHVKpSrSA2MCk0lNJSykjUfz7Zg==", + "license": "MIT", + "dependencies": { + "dijkstrajs": "^1.0.1", + "pngjs": "^5.0.0", + "yargs": "^15.3.1" + }, + "bin": { + "qrcode": "bin/qrcode" + }, + "engines": { + "node": ">=10.13.0" + } + }, + "node_modules/qrcode/node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/qrcode/node_modules/ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "license": "MIT", + "dependencies": { + "color-convert": "^2.0.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/qrcode/node_modules/cliui": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/cliui/-/cliui-6.0.0.tgz", + "integrity": "sha512-t6wbgtoCXvAzst7QgXxJYqPt0usEfbgQdftEPbLL/cvv6HPE5VgvqCuAIDR0NgU52ds6rFwqrgakNLrHEjCbrQ==", + "license": "ISC", + "dependencies": { + "string-width": "^4.2.0", + "strip-ansi": "^6.0.0", + "wrap-ansi": "^6.2.0" + } + }, + "node_modules/qrcode/node_modules/emoji-regex": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", + "license": "MIT" + }, + "node_modules/qrcode/node_modules/string-width": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", + "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "license": "MIT", + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/qrcode/node_modules/strip-ansi": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "license": "MIT", + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/qrcode/node_modules/wrap-ansi": { + "version": "6.2.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-6.2.0.tgz", + "integrity": "sha512-r6lPcBGxZXlIcymEu7InxDMhdW0KDxpLgoFLcguasxCaJ/SOIZwINatK9KY/tf+ZrlywOKU0UDj3ATXUBfxJXA==", + "license": "MIT", + "dependencies": { + "ansi-styles": "^4.0.0", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/qrcode/node_modules/y18n": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/y18n/-/y18n-4.0.3.tgz", + "integrity": "sha512-JKhqTOwSrqNA1NY5lSztJ1GrBiUodLMmIZuLiDaMRJ+itFd+ABVE8XBjOvIWL+rSqNDC74LCSFmlb/U4UZ4hJQ==", + "license": "ISC" + }, + "node_modules/qrcode/node_modules/yargs": { + "version": "15.4.1", + "resolved": "https://registry.npmjs.org/yargs/-/yargs-15.4.1.tgz", + "integrity": "sha512-aePbxDmcYW++PaqBsJ+HYUFwCdv4LVvdnhBy78E57PIor8/OVvhMrADFFEDh8DHDFRv/O9i3lPhsENjO7QX0+A==", + "license": "MIT", + "dependencies": { + "cliui": "^6.0.0", + "decamelize": "^1.2.0", + "find-up": "^4.1.0", + "get-caller-file": "^2.0.1", + "require-directory": "^2.1.1", + "require-main-filename": "^2.0.0", + "set-blocking": "^2.0.0", + "string-width": "^4.2.0", + "which-module": "^2.0.0", + "y18n": "^4.0.0", + "yargs-parser": "^18.1.2" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/qrcode/node_modules/yargs-parser": { + "version": "18.1.3", + "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-18.1.3.tgz", + "integrity": "sha512-o50j0JeToy/4K6OZcaQmW6lyXXKhq7csREXcDwk2omFPJEwUNOVtJKvmDr9EI1fAJZUyZcRF7kxGBWmRXudrCQ==", + "license": "ISC", + "dependencies": { + "camelcase": "^5.0.0", + "decamelize": "^1.2.0" + }, + "engines": { + "node": ">=6" + } + }, "node_modules/quansync": { "version": "0.2.11", "resolved": "https://registry.npmjs.org/quansync/-/quansync-0.2.11.tgz", @@ -7070,6 +7361,15 @@ "node": ">=4" } }, + "node_modules/require-directory": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz", + "integrity": "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, "node_modules/require-from-string": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz", @@ -7079,6 +7379,12 @@ "node": ">=0.10.0" } }, + "node_modules/require-main-filename": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/require-main-filename/-/require-main-filename-2.0.0.tgz", + "integrity": "sha512-NKN5kMDylKuldxYLSUfrbo5Tuzh4hd+2E8NPPX02mZtn1VuREQToYe/ZdlJy+J3uCpfaiGF05e7B8W0iXbQHmg==", + "license": "ISC" + }, "node_modules/resolve": { "version": "1.22.14", "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.14.tgz", @@ -7429,6 +7735,12 @@ "url": "https://opencollective.com/express" } }, + "node_modules/set-blocking": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/set-blocking/-/set-blocking-2.0.0.tgz", + "integrity": "sha512-KiKBS8AnWGEyLzofFfmvKwpdPzqiy16LvQfK3yv/fVH7Bj13/wl3JSR1J+rfgRE9q7xUJK4qvgS8raSOeLUehw==", + "license": "ISC" + }, "node_modules/setprototypeof": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz", @@ -8031,6 +8343,13 @@ "node": ">=22.19.0" } }, + "node_modules/undici-types": { + "version": "8.9.0", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.9.0.tgz", + "integrity": "sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg==", + "devOptional": true, + "license": "MIT" + }, "node_modules/unenv": { "version": "2.0.0-rc.25", "resolved": "https://registry.npmjs.org/unenv/-/unenv-2.0.0-rc.25.tgz", @@ -9170,6 +9489,12 @@ "node": "^20.17.0 || >=22.9.0" } }, + "node_modules/which-module": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/which-module/-/which-module-2.0.1.tgz", + "integrity": "sha512-iBdZ57RDvnOR9AGBhML2vFZf7h8vmBjhoaZqODJBFWHVtKkDmKuHai3cx5PgVMrX5YDNp27AofYbAwctSS+vhQ==", + "license": "ISC" + }, "node_modules/why-is-node-running": { "version": "2.3.0", "resolved": "https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-2.3.0.tgz", diff --git a/package.json b/package.json index 411937f..f285bda 100644 --- a/package.json +++ b/package.json @@ -8,7 +8,8 @@ "preview": "nuxt preview", "postinstall": "nuxt prepare", "test": "vitest run", - "mock": "node scripts/generate-mock.mjs" + "mock": "node scripts/generate-mock.mjs", + "smoke:live": "node scripts/smoke-live.mjs" }, "dependencies": { "@sit-onyx/chartjs-plugin": "1.0.1", @@ -17,9 +18,11 @@ "chart.js": "4.6.1", "maplibre-gl": "6.18.0", "nuxt": "4.6.4", + "qrcode": "1.5.4", "sit-onyx": "1.22.0" }, "devDependencies": { + "@types/qrcode": "1.5.5", "typescript": "5.9.3", "vitest": "3.2.4" } diff --git a/scripts/smoke-live.mjs b/scripts/smoke-live.mjs new file mode 100644 index 0000000..2c8c1a9 --- /dev/null +++ b/scripts/smoke-live.mjs @@ -0,0 +1,387 @@ +#!/usr/bin/env node +/** + * End-to-end live smoke test. + * + * Prerequisites (read-only use of the Go/ML worktrees): + * - Go API on http://127.0.0.1:18080 with CONTROL_USER/CONTROL_PASS + * - FastAPI ML on http://127.0.0.1:18000 (so Go can answer /api/readyz) + * - Built Nuxt server on http://127.0.0.1:13000 with + * NUXT_API_INTERNAL_BASE=http://127.0.0.1:18080 + * CONTROL_USER=control CONTROL_PASS=secret + * + * What it proves: the presenter POST reaches Go through Nitro, a `scenario` + * SSE event arrives through the Nitro stream proxy, and the staffing/forecast + * APIs return the new scenario. It also checks /stage, /live, the QR route and + * the control-auth boundary. + */ +import assert from 'node:assert/strict' + +const WEB_URL = (process.env.WEB_URL ?? 'http://127.0.0.1:13000').replace(/\/+$/, '') +const CONTROL_USER = process.env.CONTROL_USER ?? 'control' +const CONTROL_PASS = process.env.CONTROL_PASS ?? 'secret' +const SENSOR = process.env.SENSOR ?? 'hn-stadtgalerie-01' +const SSE_TIMEOUT_MS = Number(process.env.SSE_TIMEOUT_MS ?? 8000) +const EXPECT_HEARTBEAT = process.env.EXPECT_HEARTBEAT === '1' +const verbose = process.env.VERBOSE === '1' + +const AUTHORIZATION = `Basic ${Buffer.from(`${CONTROL_USER}:${CONTROL_PASS}`).toString('base64')}` + +function url(path) { + return new URL(path, `${WEB_URL}/`).toString() +} + +function log(message) { + console.log(` ${message}`) +} + +function pass(message) { + console.log(`PASS ${message}`) +} + +function fail(message) { + console.error(`FAIL ${message}`) +} + +async function fetchText(path, options = {}) { + const response = await fetch(url(path), options) + const text = await response.text() + if (verbose) log(`${options.method ?? 'GET'} ${path} -> ${response.status}`) + return { response, text } +} + +async function fetchJson(path, options = {}) { + const { response, text } = await fetchText(path, { + ...options, + headers: { accept: 'application/json', ...(options.headers ?? {}) }, + }) + let body + try { + body = JSON.parse(text) + } catch { + throw new Error(`${path} returned non-JSON (${response.status}): ${text.slice(0, 200)}`) + } + return { response, body } +} + +async function expectJson(path, options, status = 200) { + const { response, body } = await fetchJson(path, options) + assert.equal(response.status, status, `${path} status ${response.status}, expected ${status}: ${JSON.stringify(body)}`) + return body +} + +function parseFrame(frame) { + let name = 'message' + let id = '' + let retry = '' + const data = [] + for (const line of frame.split('\n')) { + if (!line || line.startsWith(':')) continue + const separator = line.indexOf(':') + const field = separator < 0 ? line : line.slice(0, separator) + const value = separator < 0 ? '' : line.slice(separator + 1).replace(/^ /, '') + if (field === 'event') name = value + else if (field === 'id') id = value + else if (field === 'data') data.push(value) + else if (field === 'retry') retry = value + } + if (!data.length && name === 'message' && !retry) return null + return { name: data.length || name !== 'message' ? name : 'retry', id, retry, data: data.join('\n') } +} + +/** Minimal incremental SSE reader over fetch (Node has no EventSource). */ +function openSse(path) { + const controller = new AbortController() + const events = [] + const waiters = new Set() + let raw = '' + let buffer = '' + let finished = false + + const notify = () => { + for (const waiter of [...waiters]) waiter() + } + + const consume = () => { + while (true) { + const match = buffer.match(/\r?\n\r?\n/) + if (!match || match.index === undefined) break + const frame = buffer.slice(0, match.index) + buffer = buffer.slice(match.index + match[0].length) + const event = parseFrame(frame) + if (event) { + events.push(event) + notify() + } + } + } + + const responsePromise = fetch(url(path), { + headers: { accept: 'text/event-stream' }, + signal: controller.signal, + }).then(async (response) => { + assert.equal(response.status, 200, `SSE status ${response.status}`) + const contentType = response.headers.get('content-type') ?? '' + assert.match(contentType, /text\/event-stream/, `SSE content-type: ${contentType}`) + const reader = response.body.getReader() + const decoder = new TextDecoder() + ;(async () => { + try { + while (true) { + const { done, value } = await reader.read() + if (done) break + const chunk = decoder.decode(value, { stream: true }) + raw += chunk + buffer += chunk.replace(/\r\n/g, '\n') + consume() + } + } catch (error) { + if (error?.name !== 'AbortError') throw error + } finally { + finished = true + notify() + } + })() + return response + }) + + function waitFor(predicate, timeoutMs, label) { + const existing = events.find(predicate) + if (existing) return Promise.resolve(existing) + if (finished) return Promise.reject(new Error(`SSE closed before ${label}`)) + return new Promise((resolve, reject) => { + const timer = setTimeout(() => { + waiters.delete(check) + reject(new Error(`Timed out after ${timeoutMs} ms waiting for ${label}`)) + }, timeoutMs) + const check = () => { + const match = events.find(predicate) + if (!match) return + clearTimeout(timer) + waiters.delete(check) + resolve(match) + } + waiters.add(check) + }) + } + + return { + responsePromise, + waitFor, + get raw() { + return raw + }, + close() { + controller.abort() + }, + } +} + +function decisionShape(plan) { + return JSON.stringify({ + scenario: plan.scenario, + summary: plan.summary, + footfall: plan.hours.map((hour) => [hour.t, hour.footfall, hour.required_staff, hour.scheduled_staff]), + }) +} + +async function main() { + console.log(`PulseCast live smoke test -> ${WEB_URL}`) + + const health = await expectJson('/api/healthz') + assert.equal(health.ok, true, 'healthz.ok') + pass('Nitro health endpoint') + + const ready = await expectJson('/api/readyz') + assert.equal(ready.ok, true, 'readyz.ok') + assert.equal(ready.data, true, 'readyz.data (Go bootstrap snapshot)') + assert.equal(ready.model, true, 'readyz.model (FastAPI)') + pass('Go API ready with ML snapshot') + + const initial = await expectJson('/api/scenario') + assert.equal(typeof initial.version, 'number', 'scenario.version') + assert.ok(initial.scenario?.scenario, 'scenario.scenario') + pass(`scenario state v${initial.version} (${initial.scenario.scenario})`) + + const basePlan = await expectJson( + `/api/staffing?sensor=${encodeURIComponent(SENSOR)}&scenario=base&standard=standard`, + ) + assert.equal(basePlan.sensor, SENSOR) + assert.equal(basePlan.scenario, 'base') + assert.ok(basePlan.hours.length > 0, 'base plan has open hours') + assert.ok(basePlan.shifts.length > 0, 'base plan has shift blocks') + pass(`base plan: ${basePlan.hours.length} hours, ${basePlan.shifts.length} shifts`) + + const baseForecast = await expectJson( + `/api/forecast?sensor=${encodeURIComponent(SENSOR)}&horizon=7d&scenario=base`, + ) + assert.ok(baseForecast.points.length > 0, 'base forecast has points') + pass(`base forecast: ${baseForecast.points.length} hourly points`) + + const unauthenticated = await fetchJson('/api/scenario', { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ scenario: 'rainy-saturday' }), + }) + assert.equal(unauthenticated.response.status, 401, 'POST without presenter auth must be 401') + pass('unauthenticated scenario POST is rejected') + + const controlPage = await fetchText('/control') + assert.equal(controlPage.response.status, 401, '/control without auth must be 401') + assert.match(controlPage.response.headers.get('www-authenticate') ?? '', /Basic/i) + pass('/control is presenter-protected') + + const controlAuthed = await fetchText('/control', { headers: { authorization: AUTHORIZATION } }) + assert.equal(controlAuthed.response.status, 200, '/control with auth') + assert.match(controlAuthed.text, /Presenter control/i) + pass('/control authenticates and renders') + + for (const [path, needle] of [ + ['/stage', 'Scan for the phone view'], + ['/live', 'The plan on your phone'], + ]) { + const page = await fetchText(path) + assert.equal(page.response.status, 200, `${path} status`) + assert.match(page.response.headers.get('content-type') ?? '', /text\/html/i, `${path} content-type`) + assert.ok(page.text.includes(needle), `${path} contains "${needle}"`) + assert.ok(page.text.includes('PulseCast'), `${path} contains the app shell`) + pass(`${path} renders server-side`) + } + + const qr = await fetchText(`/api/qr?text=${encodeURIComponent(`${WEB_URL}/live`)}`) + assert.equal(qr.response.status, 200, 'QR status') + assert.match(qr.response.headers.get('content-type') ?? '', /image\/svg\+xml/i, 'QR content-type') + assert.match(qr.text, / event.name === 'scenario' || event.name === 'retry', + 5000, + 'the initial SSE frame', + ) + assert.ok(initialEvent, 'initial SSE frame') + if (EXPECT_HEARTBEAT) { + await sse.waitFor((event) => event.name === 'ping', SSE_TIMEOUT_MS, 'a heartbeat ping') + pass('SSE heartbeat observed') + } + assert.match(sse.raw, /retry:\s*3000/, 'SSE retry hint') + + const initialScenarioEvent = await sse.waitFor( + (event) => event.name === 'scenario', + 5000, + 'the initial scenario event', + ) + const initialPayload = JSON.parse(initialScenarioEvent.data) + assert.equal(typeof initialPayload.version, 'number', 'SSE initial version') + pass(`SSE connected: retry:3000, initial scenario v${initialPayload.version}`) + + const target = initialPayload.scenario === 'rainy-saturday' ? 'sunny-saturday-market' : 'rainy-saturday' + const body = + target === 'sunny-saturday-market' + ? { + scenario: target, + weather: { temp_delta_c: 4, precip_mm: 0 }, + event: { type: 'market', uplift: 0.2 }, + } + : { + scenario: target, + weather: { temp_delta_c: -2, precip_mm: 3.2 }, + } + + const started = performance.now() + const posted = await expectJson('/api/scenario', { + method: 'POST', + headers: { authorization: AUTHORIZATION, 'content-type': 'application/json' }, + body: JSON.stringify(body), + }) + assert.equal(posted.scenario.scenario, target, 'POST response scenario') + const postMs = performance.now() - started + + const event = await sse.waitFor( + (candidate) => { + if (candidate.name !== 'scenario') return false + try { + const payload = JSON.parse(candidate.data) + return payload.version >= posted.version && payload.scenario?.scenario === target + } catch { + return false + } + }, + 5000, + `a scenario SSE event for ${target}`, + ) + const elapsed = performance.now() - started + const payload = JSON.parse(event.data) + assert.equal(payload.scenario.scenario, target, 'SSE scenario id') + assert.equal(event.id, String(payload.version), 'SSE id equals the scenario version') + assert.ok(elapsed < 5000, `scenario event took ${elapsed.toFixed(0)} ms (max 5000)`) + if (elapsed >= 2000) { + console.warn(`WARN scenario propagated in ${elapsed.toFixed(0)} ms; contract target is <2000 ms`) + } + pass(`scenario POST -> SSE event in ${elapsed.toFixed(0)} ms (POST ${postMs.toFixed(0)} ms)`) + + const polled = await expectJson('/api/scenario') + assert.equal(polled.version, posted.version, 'GET /api/scenario polling version') + assert.equal(polled.scenario.scenario, target, 'GET /api/scenario polling scenario') + pass(`polling fallback reads v${polled.version} (${target})`) + + const targetPlan = await expectJson( + `/api/staffing?sensor=${encodeURIComponent(SENSOR)}&scenario=${target}&standard=standard`, + ) + assert.equal(targetPlan.scenario, target, 'target plan scenario') + assert.ok(targetPlan.hours.length > 0, 'target plan has hours') + assert.notEqual( + decisionShape(targetPlan), + decisionShape(basePlan), + `${target} plan must differ from base`, + ) + if (targetPlan.cached) { + console.warn('WARN Go served a cached plan; ML was not used for this request') + } else { + pass('target plan is live and differs from base') + } + + const targetForecast = await expectJson( + `/api/forecast?sensor=${encodeURIComponent(SENSOR)}&horizon=7d&scenario=${target}`, + ) + assert.equal(targetForecast.scenario, target, 'target forecast scenario') + assert.ok(targetForecast.points.length > 0, 'target forecast has points') + assert.notEqual( + JSON.stringify(targetForecast.points), + JSON.stringify(baseForecast.points), + `${target} forecast must differ from base`, + ) + pass('target forecast is live and differs from base') + + const stageAfter = await fetchText('/stage') + assert.equal(stageAfter.response.status, 200, 'stage after scenario') + const expectedLabel = target === 'rainy-saturday' ? 'Rainy Saturday' : 'Sunny Saturday' + assert.ok(stageAfter.text.includes(expectedLabel), `stage renders ${expectedLabel}`) + pass(`/stage server-renders the new scenario (${expectedLabel})`) + + const liveAfter = await fetchText('/live') + assert.equal(liveAfter.response.status, 200, 'live after scenario') + assert.ok(liveAfter.text.includes(expectedLabel), `live renders ${expectedLabel}`) + pass(`/live server-renders the new scenario (${expectedLabel})`) + + // Leave the demo in the base state so the next run is deterministic. + const restored = await expectJson('/api/scenario', { + method: 'POST', + headers: { authorization: AUTHORIZATION, 'content-type': 'application/json' }, + body: JSON.stringify({ scenario: 'base', weather: { temp_delta_c: 0, precip_mm: 0 } }), + }) + assert.equal(restored.scenario.scenario, 'base') + pass(`restored base (v${restored.version})`) + } finally { + sse.close() + } + + console.log('\nAll live smoke checks passed.') +} + +main().catch((error) => { + fail(error?.stack ?? String(error)) + process.exitCode = 1 +}) diff --git a/server/api/qr.get.ts b/server/api/qr.get.ts new file mode 100644 index 0000000..69c98a1 --- /dev/null +++ b/server/api/qr.get.ts @@ -0,0 +1,35 @@ +import QRCode from 'qrcode' + +/** + * Generate the /stage QR code locally. No third-party QR image service is + * called at runtime, so the big screen keeps working without internet access. + */ +export default defineEventHandler(async (event) => { + const query = getQuery(event) + const text = typeof query.text === 'string' ? query.text.trim() : '' + if (!text) { + throw createError({ statusCode: 400, statusMessage: 'text is required' }) + } + if (text.length > 1024) { + throw createError({ statusCode: 400, statusMessage: 'text is too long for a QR code' }) + } + + let svg: string + try { + svg = await QRCode.toString(text, { + type: 'svg', + margin: 1, + width: 320, + errorCorrectionLevel: 'M', + color: { dark: '#0f172a', light: '#ffffff' }, + }) + } catch { + throw createError({ statusCode: 400, statusMessage: 'could not encode text as a QR code' }) + } + + setResponseHeaders(event, { + 'content-type': 'image/svg+xml; charset=utf-8', + 'cache-control': 'public, max-age=300', + }) + return svg +}) diff --git a/server/api/scenario.get.ts b/server/api/scenario.get.ts index 1b53483..97d89b1 100644 --- a/server/api/scenario.get.ts +++ b/server/api/scenario.get.ts @@ -1,8 +1,8 @@ import type { ScenarioState } from '../../shared/types' import { apiRequest, isMockMode } from '../utils/api' -import { mockScenario } from '../utils/mock-data' +import { getMockScenario } from '../utils/mock-scenario' export default defineEventHandler(async () => { - if (isMockMode()) return mockScenario + if (isMockMode()) return getMockScenario() return apiRequest('/api/scenario') }) diff --git a/server/api/scenario.post.ts b/server/api/scenario.post.ts index d6b3b7e..296b2ee 100644 --- a/server/api/scenario.post.ts +++ b/server/api/scenario.post.ts @@ -1,9 +1,7 @@ import { SCENARIOS } from '../../shared/types' import type { Scenario, ScenarioDefinition, ScenarioState } from '../../shared/types' import { apiRequest, isMockMode } from '../utils/api' -import { mockScenario } from '../utils/mock-data' - -let version = mockScenario.version +import { setMockScenario } from '../utils/mock-scenario' export default defineEventHandler(async (event) => { const body = await readBody(event) @@ -16,12 +14,7 @@ export default defineEventHandler(async (event) => { } if (isMockMode()) { - version += 1 - return { - version, - scenario: body, - at: new Date().toISOString(), - } + return setMockScenario(body) } // Control credentials are attached in the server process, never in the diff --git a/server/api/stream.get.ts b/server/api/stream.get.ts new file mode 100644 index 0000000..ab4dc80 --- /dev/null +++ b/server/api/stream.get.ts @@ -0,0 +1,24 @@ +import { apiBaseUrl, isMockMode } from '../utils/api' + +/** + * Same-origin SSE proxy. The browser never talks to Go directly, so the + * Cloudflare/K8s CORS surface stays closed and the stream can be cached or + * authenticated at one edge only. + * + * h3's proxyRequest pipes response chunks as they arrive (it does not await + * the full body), which preserves the 15 s heartbeat and `retry: 3000`. + */ +export default defineEventHandler(async (event) => { + if (isMockMode() || process.env.NUXT_DISABLE_SSE === '1') { + // Failure drill: make the client prove the 5 s polling fallback. Mock mode + // has no upstream stream either, so both paths fail fast and visibly. + throw createError({ + statusCode: 503, + statusMessage: 'SSE is disabled; the scenario polling fallback is active.', + }) + } + + return proxyRequest(event, `${apiBaseUrl()}/api/stream`, { + headers: { accept: 'text/event-stream' }, + }) +}) diff --git a/server/middleware/control-auth.ts b/server/middleware/control-auth.ts new file mode 100644 index 0000000..2160b51 --- /dev/null +++ b/server/middleware/control-auth.ts @@ -0,0 +1,101 @@ +import { createHash, createHmac, timingSafeEqual } from 'node:crypto' +import { isMockMode } from '../utils/api' + +const COOKIE_NAME = 'pulsecast_control' +const COOKIE_CONTEXT = 'pulsecast-control-v1' + +function digest(value: string): Buffer { + return createHash('sha256').update(value).digest() +} + +/** Constant-time compare that works for unequal-length strings. */ +function safeEqual(a: string, b: string): boolean { + return timingSafeEqual(digest(a), digest(b)) +} + +function expectedCookie(pass: string): string { + return createHmac('sha256', pass).update(COOKIE_CONTEXT).digest('base64url') +} + +function basicCredentials(event: import('h3').H3Event): { user: string; pass: string } | null { + const header = getHeader(event, 'authorization') ?? '' + if (!header.startsWith('Basic ')) return null + let decoded: string + try { + decoded = Buffer.from(header.slice('Basic '.length), 'base64').toString('utf8') + } catch { + return null + } + const separator = decoded.indexOf(':') + if (separator < 0) return null + return { user: decoded.slice(0, separator), pass: decoded.slice(separator + 1) } +} + +function isProtected(event: import('h3').H3Event): boolean { + const path = getRequestURL(event).pathname.replace(/\/+$/, '') || '/' + if (path === '/control') return true + if (path === '/api/scenario' && getMethod(event) === 'POST') return true + return false +} + +/** + * Presenter-only control surface. Basic auth is checked in Nitro; on success + * an HMAC cookie (signed with CONTROL_PASS) lets the page POST /api/scenario + * without re-prompting. The browser never receives the Go credentials, and + * /stage, /live and all public GETs stay open. + */ +export default defineEventHandler((event) => { + if (!isProtected(event)) return + if (isMockMode()) return + + const user = process.env.CONTROL_USER ?? process.env.NUXT_CONTROL_USER ?? '' + const pass = process.env.CONTROL_PASS ?? process.env.NUXT_CONTROL_PASS ?? '' + const isApi = getRequestURL(event).pathname.startsWith('/api/') + setResponseHeader(event, 'cache-control', 'no-store') + + if (!user || !pass) { + setResponseStatus(event, 503) + if (isApi) { + setResponseHeader(event, 'content-type', 'application/json; charset=utf-8') + return { + error: { + code: 'control_auth_unconfigured', + message: 'CONTROL_USER and CONTROL_PASS are not configured in the web server.', + }, + } + } + setResponseHeader(event, 'content-type', 'text/plain; charset=utf-8') + return 'Control credentials are not configured. Set CONTROL_USER and CONTROL_PASS on the web server.' + } + + const expected = expectedCookie(pass) + const cookie = getCookie(event, COOKIE_NAME) + const cookieValid = Boolean(cookie && safeEqual(cookie, expected)) + + let basicValid = false + const basic = basicCredentials(event) + if (basic && safeEqual(basic.user, user) && safeEqual(basic.pass, pass)) { + basicValid = true + const forwardedProto = (getHeader(event, 'x-forwarded-proto') ?? '').split(',')[0]?.trim() + setCookie(event, COOKIE_NAME, expected, { + httpOnly: true, + sameSite: 'lax', + path: '/', + maxAge: 60 * 60 * 8, + secure: (forwardedProto || getRequestProtocol(event)) === 'https', + }) + } + + if (cookieValid || basicValid) return + + setResponseStatus(event, 401) + setResponseHeader(event, 'www-authenticate', 'Basic realm="PulseCast presenter"') + if (isApi) { + setResponseHeader(event, 'content-type', 'application/json; charset=utf-8') + return { + error: { code: 'unauthorized', message: 'Presenter credentials are required to change the scenario.' }, + } + } + setResponseHeader(event, 'content-type', 'text/plain; charset=utf-8') + return 'Authentication required.' +}) diff --git a/server/utils/mock-scenario.ts b/server/utils/mock-scenario.ts new file mode 100644 index 0000000..2dd632d --- /dev/null +++ b/server/utils/mock-scenario.ts @@ -0,0 +1,24 @@ +import type { ScenarioDefinition, ScenarioState } from '../../shared/types' +import { mockScenario } from './mock-data' + +// Mock mode has no Go process, but the presenter controls and the 5 s polling +// fallback should still observe a version change. Nitro keeps this per-process +// state, exactly like the single Go pod keeps its in-memory scenario. +let current: ScenarioState = clone(mockScenario) + +function clone(value: T): T { + return JSON.parse(JSON.stringify(value)) as T +} + +export function getMockScenario(): ScenarioState { + return clone(current) +} + +export function setMockScenario(input: ScenarioDefinition): ScenarioState { + current = { + version: current.version + 1, + scenario: clone(input), + at: new Date().toISOString(), + } + return clone(current) +} diff --git a/shared/live.ts b/shared/live.ts new file mode 100644 index 0000000..ddc76b7 --- /dev/null +++ b/shared/live.ts @@ -0,0 +1,101 @@ +import { SCENARIOS } from './types' +import type { Scenario, ScenarioState } from './types' + +/** Client connection modes shown on /stage, /live and /plan. */ +export type LiveConnection = 'connecting' | 'live' | 'polling' | 'offline' + +/** Poll the public scenario endpoint every 5 s while SSE is unavailable. */ +export const SCENARIO_POLL_MS = 5000 +/** Two consecutive SSE errors are enough to start the polling fallback. */ +export const SSE_FAILURES_BEFORE_POLLING = 2 +/** The Go hub pings every 15 s; two missed pings mean the stream is buffered. */ +export const SSE_STALE_MS = 32000 + +export const LIVE_LABELS: Record = { + connecting: 'Connecting', + live: 'Live', + polling: 'Polling', + offline: 'Offline', +} + +export const LIVE_COLORS: Record = { + connecting: 'neutral', + live: 'success', + polling: 'warning', + offline: 'danger', +} + +export interface LiveStatusInput { + online: boolean + sseOpen: boolean + sseFailures: number + polling: boolean + pollFailures: number +} + +/** + * Resolve the visible connection state. Live means an open SSE stream, + * Polling means the 5 s fallback is working, Offline means neither path works. + */ +export function liveStatus(input: LiveStatusInput): LiveConnection { + if (!input.online) return 'offline' + if (input.sseOpen) return 'live' + if (input.polling) return input.pollFailures > 0 ? 'offline' : 'polling' + if (input.sseFailures >= SSE_FAILURES_BEFORE_POLLING) { + return input.pollFailures > 0 ? 'offline' : 'polling' + } + return 'connecting' +} + +/** Parse and validate one `event: scenario` payload from Go /api/stream. */ +export function parseScenarioEvent(raw: string): ScenarioState | null { + let value: unknown + try { + value = JSON.parse(raw) + } catch { + return null + } + if (!value || typeof value !== 'object') return null + const candidate = value as Partial + if (typeof candidate.version !== 'number' || !Number.isFinite(candidate.version)) return null + if (typeof candidate.at !== 'string' || !candidate.at) return null + if (!candidate.scenario || typeof candidate.scenario !== 'object') return null + const scenario = candidate.scenario as { scenario?: unknown } + if (typeof scenario.scenario !== 'string') return null + if (!SCENARIOS.includes(scenario.scenario as Scenario)) return null + return candidate as ScenarioState +} + +/** A new server version, or a changed scenario id, is a reason to refetch. */ +export function scenarioChanged( + previous: ScenarioState | null | undefined, + next: ScenarioState, +): boolean { + if (!previous) return true + return previous.version !== next.version || previous.scenario.scenario !== next.scenario.scenario +} + +export function scenarioLabel(scenario: Scenario | string | undefined): string { + switch (scenario) { + case 'sunny-saturday-market': + return 'Sunny Saturday + market' + case 'rainy-saturday': + return 'Rainy Saturday' + case 'weekday-event': + return 'Wednesday evening event' + default: + return 'Base week' + } +} + +/** Small, dependency-free age label for the last SSE/poll event. */ +export function liveAge(lastEventAt: string, now = Date.now()): string { + if (!lastEventAt) return 'no event yet' + const time = Date.parse(lastEventAt) + if (Number.isNaN(time)) return 'no event yet' + const seconds = Math.max(0, Math.round((now - time) / 1000)) + if (seconds < 5) return 'just now' + if (seconds < 60) return `${seconds}s ago` + const minutes = Math.round(seconds / 60) + return `${minutes} min ago` +} diff --git a/test/live.test.ts b/test/live.test.ts new file mode 100644 index 0000000..03c88e8 --- /dev/null +++ b/test/live.test.ts @@ -0,0 +1,96 @@ +import { describe, expect, it } from 'vitest' +import { + liveAge, + liveStatus, + parseScenarioEvent, + scenarioChanged, + scenarioLabel, + SSE_FAILURES_BEFORE_POLLING, +} from '../shared/live' +import type { ScenarioState } from '../shared/types' + +const state = (version: number, scenario: ScenarioState['scenario']['scenario'] = 'base'): ScenarioState => ({ + version, + scenario: { scenario }, + at: '2026-11-14T09:12:00Z', +}) + +describe('parseScenarioEvent', () => { + it('accepts the Go /api/stream scenario shape', () => { + expect(parseScenarioEvent(JSON.stringify(state(7, 'rainy-saturday')))).toEqual( + state(7, 'rainy-saturday'), + ) + }) + + it('rejects malformed JSON, missing versions and unknown scenarios', () => { + expect(parseScenarioEvent('{')).toBeNull() + expect(parseScenarioEvent(JSON.stringify({ scenario: { scenario: 'base' }, at: 'x' }))).toBeNull() + expect( + parseScenarioEvent(JSON.stringify({ version: 1, at: 'x', scenario: { scenario: 'party' } })), + ).toBeNull() + }) +}) + +describe('scenarioChanged', () => { + it('refreshes on a new version or a new scenario id', () => { + expect(scenarioChanged(null, state(1))).toBe(true) + expect(scenarioChanged(state(1), state(1))).toBe(false) + expect(scenarioChanged(state(1), state(2))).toBe(true) + expect(scenarioChanged(state(1, 'base'), state(1, 'rainy-saturday'))).toBe(true) + }) +}) + +describe('liveStatus', () => { + const base = { + online: true, + sseOpen: false, + sseFailures: 0, + polling: false, + pollFailures: 0, + } + + it('shows connecting before the first event and live once SSE opens', () => { + expect(liveStatus(base)).toBe('connecting') + expect(liveStatus({ ...base, sseOpen: true })).toBe('live') + }) + + it('switches to polling after repeated SSE failures', () => { + expect( + liveStatus({ + ...base, + sseFailures: SSE_FAILURES_BEFORE_POLLING, + polling: true, + }), + ).toBe('polling') + }) + + it('reports offline when the browser or both transports are down', () => { + expect(liveStatus({ ...base, online: false, sseOpen: true })).toBe('offline') + expect( + liveStatus({ + ...base, + sseFailures: SSE_FAILURES_BEFORE_POLLING, + polling: true, + pollFailures: 1, + }), + ).toBe('offline') + }) +}) + +describe('scenarioLabel and liveAge', () => { + it('labels every contract enum', () => { + expect(scenarioLabel('sunny-saturday-market')).toBe('Sunny Saturday + market') + expect(scenarioLabel('rainy-saturday')).toBe('Rainy Saturday') + expect(scenarioLabel('weekday-event')).toBe('Wednesday evening event') + expect(scenarioLabel('base')).toBe('Base week') + expect(scenarioLabel('unknown')).toBe('Base week') + }) + + it('renders a short age without a date library', () => { + const now = Date.parse('2026-11-14T09:12:10Z') + expect(liveAge('', now)).toBe('no event yet') + expect(liveAge('2026-11-14T09:12:08Z', now)).toBe('just now') + expect(liveAge('2026-11-14T09:11:40Z', now)).toBe('30s ago') + expect(liveAge('2026-11-14T09:07:10Z', now)).toBe('5 min ago') + }) +})