From 947fc557f7f4d149fd5751d47b5dec5424fb7b38 Mon Sep 17 00:00:00 2001 From: g-but <41178744+g-but@users.noreply.github.com> Date: Thu, 21 May 2026 04:01:53 +0200 Subject: [PATCH] fix(weather): WeatherCard shows real weather on Vercel via open-meteo HTTP MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Caught during a live audit at mobile viewport on cockpitapp.vercel.app: WeatherCard rendered "Unavailable" indefinitely. Root cause: /api/weather's GET handler bails to {weather: null} when isRuntimeAvailable() is false (serverless can't shell out to scripts/weather.sh). But the upstream weather.sh actually calls is open-meteo — a free public HTTP API. We can hit it directly from Vercel via fetch. Add a fetchOpenMeteoWeather() path used only when isRuntimeAvailable is false; local keeps the richer shell path. Implementation: - WMO_DESCRIPTION map: weather codes 0-99 → human strings matching weather.sh's vocabulary so WeatherCard's parseWeather + WeatherIcon-by-keyword detection still light up the right icon (cloud / rain / snow / fog) regardless of source. - Output line format matches weather.sh exactly: "Now: , °C, wind km/h, humidity %" ": -°C, " - AbortSignal.timeout(7000) so a stalled upstream doesn't pin the route. - 503 with explicit error reason when geocoding fails or open-meteo is unreachable, so FetchErrorState shows the actual cause rather than a silent "Unavailable" wall. This finally works on the deployed site for the first time. The user has been seeing "Weather: Unavailable" on their Today page on every mobile visit; from this deploy onward they'll see real temperature + condition + tomorrow's forecast. Co-Authored-By: Claude Opus 4.7 (1M context) --- src/app/api/weather/route.ts | 81 +++++++++++++++++++++++++++++++++++- 1 file changed, 79 insertions(+), 2 deletions(-) diff --git a/src/app/api/weather/route.ts b/src/app/api/weather/route.ts index 7b7add8c4..e57d8db81 100644 --- a/src/app/api/weather/route.ts +++ b/src/app/api/weather/route.ts @@ -29,14 +29,91 @@ async function geocodeCity(city: string): Promise { } } -export async function GET() { - if (!isRuntimeAvailable()) return NextResponse.json({ weather: null }); +// WMO weather codes → human descriptions. Matches the strings weather.sh uses +// so WeatherCard's parseWeather + WeatherIcon-by-keyword detection light up +// the same icons (cloud / rain / snow / fog) regardless of source. +const WMO_DESCRIPTION: Record = { + 0: "Clear", 1: "Mainly clear", 2: "Partly cloudy", 3: "Overcast", + 45: "Foggy", 48: "Foggy", + 51: "Light drizzle", 53: "Drizzle", 55: "Heavy drizzle", + 56: "Freezing drizzle", 57: "Heavy freezing drizzle", + 61: "Light rain", 63: "Rain", 65: "Heavy rain", + 66: "Freezing rain", 67: "Heavy freezing rain", + 71: "Light snow", 73: "Snow", 75: "Heavy snow", 77: "Snow grains", + 80: "Light showers", 81: "Showers", 82: "Heavy showers", + 85: "Snow showers", 86: "Heavy snow showers", + 95: "Thunderstorm", 96: "Thunderstorm + hail", 99: "Heavy thunderstorm", +}; +function describeCode(code: number | undefined): string { + return code !== undefined && WMO_DESCRIPTION[code] ? WMO_DESCRIPTION[code] : "Unknown"; +} + +/** + * Vercel-safe weather fetch — direct HTTP to open-meteo so the WeatherCard + * shows real data on the deployed site instead of "Unavailable". Returns the + * same line-formatted string weather.sh produces locally so parseWeather() + * in WeatherCard doesn't care which source rendered it. + */ +async function fetchOpenMeteoWeather(geo: GeoResult): Promise { + try { + const params = new URLSearchParams({ + latitude: String(geo.latitude), + longitude: String(geo.longitude), + timezone: geo.timezone, + current: "temperature_2m,wind_speed_10m,relative_humidity_2m,weather_code", + daily: "temperature_2m_max,temperature_2m_min,weather_code", + forecast_days: "2", + }); + const res = await fetch(`https://api.open-meteo.com/v1/forecast?${params}`, { + next: { revalidate: 0 }, + signal: AbortSignal.timeout(7000), + }); + if (!res.ok) return null; + const data = await res.json() as { + current?: { temperature_2m?: number; wind_speed_10m?: number; relative_humidity_2m?: number; weather_code?: number }; + daily?: { time?: string[]; temperature_2m_max?: number[]; temperature_2m_min?: number[]; weather_code?: number[] }; + }; + const c = data.current; + if (!c) return null; + const nowLine = `Now: ${describeCode(c.weather_code)}, ${c.temperature_2m?.toFixed(1) ?? "?"}°C, wind ${c.wind_speed_10m?.toFixed(1) ?? "?"} km/h, humidity ${c.relative_humidity_2m ?? "?"}%`; + const d = data.daily; + if (!d?.time?.length) return nowLine; + // index 1 = tomorrow when forecast_days=2 (today + tomorrow); fall back to 0. + const i = d.time.length >= 2 ? 1 : 0; + const date = d.time[i]; + const lo = d.temperature_2m_min?.[i]; + const hi = d.temperature_2m_max?.[i]; + const code = d.weather_code?.[i]; + const dayLine = `${date}: ${lo?.toFixed(1) ?? "?"}-${hi?.toFixed(1) ?? "?"}°C, ${describeCode(code)}`; + return `${nowLine}\n${dayLine}`; + } catch { + return null; + } +} + +export async function GET() { const userId = await getApiUserId(); const prefs = userId ? await getUserPreferences(userId).catch(() => null) : null; const city = getActiveCity(prefs); const geo = await geocodeCity(city); + + // Vercel / any environment without local shell tools: fetch open-meteo + // directly. Previously bailed to `{weather: null}` and the WeatherCard + // showed "Unavailable" forever. + if (!isRuntimeAvailable()) { + if (!geo) { + return NextResponse.json({ weather: null, error: `Could not geocode "${city}"` }, { status: 503 }); + } + const weather = await fetchOpenMeteoWeather(geo); + if (!weather) { + return NextResponse.json({ weather: null, error: "open-meteo unreachable" }, { status: 503 }); + } + return NextResponse.json({ weather, city }); + } + + // Local runtime — richer weather.sh output (handles fancier formatting / sunrise). const extraEnv: Record = geo ? { COCKPIT_LAT: String(geo.latitude),