1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
|
import type { SourceModule } from "../registry";
import { getSettings } from "@/lib/store";
import {
WeatherConfig,
WeatherPayload,
type WeatherConfig as Config,
type WeatherPayload as Payload,
} from "@/lib/schemas/sources/weather";
// WMO weather interpretation codes โ short text.
const WMO: Record<number, string> = {
0: "Clear", 1: "Mainly clear", 2: "Partly cloudy", 3: "Overcast",
45: "Fog", 48: "Rime fog", 51: "Light drizzle", 53: "Drizzle", 55: "Dense drizzle",
56: "Freezing drizzle", 57: "Freezing drizzle", 61: "Light rain", 63: "Rain", 65: "Heavy rain",
66: "Freezing rain", 67: "Freezing rain", 71: "Light snow", 73: "Snow", 75: "Heavy snow",
77: "Snow grains", 80: "Light showers", 81: "Showers", 82: "Violent showers",
85: "Snow showers", 86: "Snow showers", 95: "Thunderstorm", 96: "Thunderstorm + hail",
99: "Thunderstorm + hail",
};
const codeText = (c: number) => WMO[c] ?? "โ";
function resolveLocation(config: Config): { lat: number; lon: number; label: string } | null {
if (config.lat != null && config.lon != null) {
return { lat: config.lat, lon: config.lon, label: config.label ?? "Custom" };
}
const loc = getSettings().location;
if (loc) return { lat: loc.lat, lon: loc.lon, label: loc.label || "Home" };
const envLat = process.env.WEATHER_LAT;
const envLon = process.env.WEATHER_LON;
if (envLat && envLon) return { lat: Number(envLat), lon: Number(envLon), label: "Home" };
return null;
}
function aqiCategory(v: number | null): string {
if (v == null) return "";
if (v <= 50) return "Good";
if (v <= 100) return "Moderate";
if (v <= 150) return "Unhealthy (sensitive)";
if (v <= 200) return "Unhealthy";
if (v <= 300) return "Very Unhealthy";
return "Hazardous";
}
function pollenLevel(v: number): string {
if (v < 10) return "Low";
if (v < 30) return "Moderate";
if (v < 70) return "High";
return "Very High";
}
const POLLEN_KEYS: Array<[string, string]> = [
["grass_pollen", "Grass"],
["birch_pollen", "Birch"],
["alder_pollen", "Alder"],
["ragweed_pollen", "Ragweed"],
["mugwort_pollen", "Mugwort"],
["olive_pollen", "Olive"],
];
const SEVERITY_RANK: Record<string, number> = {
Extreme: 4, Severe: 3, Moderate: 2, Minor: 1, Unknown: 0,
};
function moonPhase(date: Date): { phase: string; emoji: string } {
// Reference new moon: Jan 6 2000 18:14 UTC
const refNewMoon = Date.UTC(2000, 0, 6, 18, 14, 0);
const synodicPeriod = 29.53058867;
const days = (date.getTime() - refNewMoon) / 86_400_000;
const pos = ((days % synodicPeriod) + synodicPeriod) % synodicPeriod;
if (pos < 1.85) return { phase: "New Moon", emoji: "๐" };
if (pos < 7.38) return { phase: "Waxing Crescent", emoji: "๐" };
if (pos < 9.22) return { phase: "First Quarter", emoji: "๐" };
if (pos < 14.77) return { phase: "Waxing Gibbous", emoji: "๐" };
if (pos < 16.61) return { phase: "Full Moon", emoji: "๐" };
if (pos < 22.15) return { phase: "Waning Gibbous", emoji: "๐" };
if (pos < 23.99) return { phase: "Last Quarter", emoji: "๐" };
return { phase: "Waning Crescent", emoji: "๐" };
}
export const weatherModule: SourceModule<Config, Payload> = {
kind: "weather",
label: "Weather",
keyless: true,
defaultRefreshSeconds: 1800,
configSchema: WeatherConfig,
payloadSchema: WeatherPayload,
isConfigured: (config) => resolveLocation(config) !== null,
async fetch({ config, signal }) {
const place = resolveLocation(config);
if (!place) throw new Error("No location set โ add one in Settings.");
const units = getSettings().units;
const tempUnit = units === "metric" ? "celsius" : "fahrenheit";
const windUnit = units === "metric" ? "kmh" : "mph";
const weatherUrl = new URL("https://api.open-meteo.com/v1/forecast");
weatherUrl.searchParams.set("latitude", String(place.lat));
weatherUrl.searchParams.set("longitude", String(place.lon));
weatherUrl.searchParams.set(
"current",
"temperature_2m,apparent_temperature,weather_code,wind_speed_10m,relative_humidity_2m,uv_index",
);
weatherUrl.searchParams.set(
"daily",
"temperature_2m_max,temperature_2m_min,weather_code,precipitation_probability_max,sunrise,sunset",
);
weatherUrl.searchParams.set(
"hourly",
"temperature_2m,weather_code,precipitation_probability",
);
weatherUrl.searchParams.set("temperature_unit", tempUnit);
weatherUrl.searchParams.set("wind_speed_unit", windUnit);
weatherUrl.searchParams.set("timezone", "auto");
weatherUrl.searchParams.set("forecast_days", "3");
const aqiUrl = new URL("https://air-quality-api.open-meteo.com/v1/air-quality");
aqiUrl.searchParams.set("latitude", String(place.lat));
aqiUrl.searchParams.set("longitude", String(place.lon));
aqiUrl.searchParams.set("timezone", "auto");
aqiUrl.searchParams.set("current", "us_aqi,pm2_5");
aqiUrl.searchParams.set("hourly", POLLEN_KEYS.map(([k]) => k).join(","));
const alertsUrl =
`https://api.weather.gov/alerts/active?point=${place.lat},${place.lon}`;
const [weatherRes, aqiRes, alertsRes] = await Promise.all([
fetch(weatherUrl, { signal }),
fetch(aqiUrl, { signal }).catch(() => null),
fetch(alertsUrl, {
signal,
headers: { "User-Agent": "personal-dashboard/1.0" },
}).catch(() => null),
]);
if (!weatherRes.ok) throw new Error(`Open-Meteo ${weatherRes.status}`);
const j = (await weatherRes.json()) as {
current: {
temperature_2m: number;
apparent_temperature: number;
weather_code: number;
wind_speed_10m: number;
relative_humidity_2m: number;
uv_index: number | null;
};
daily: {
time: string[];
temperature_2m_max: number[];
temperature_2m_min: number[];
weather_code: number[];
precipitation_probability_max: (number | null)[];
sunrise: string[];
sunset: string[];
};
hourly?: {
time: string[];
temperature_2m: number[];
weather_code: number[];
precipitation_probability: (number | null)[];
};
};
// --- AQI + pollen ---
let aqi: number | null = null;
let aqiCat = "";
const pollen: Payload["pollen"] = [];
if (aqiRes?.ok) {
const aq = (await aqiRes.json()) as {
current?: { time?: string; us_aqi?: number | null; pm2_5?: number | null };
hourly?: { time: string[] } & Record<string, (number | null)[]>;
};
aqi = aq.current?.us_aqi ?? null;
aqiCat = aqiCategory(aqi);
if (aq.hourly?.time?.length) {
const nowHour = (aq.current?.time ?? aq.hourly.time[0]).slice(0, 13);
let idx = aq.hourly.time.findIndex((t) => t.slice(0, 13) === nowHour);
if (idx < 0) idx = 0;
for (const [key, label] of POLLEN_KEYS) {
const v = aq.hourly[key]?.[idx];
if (typeof v === "number" && v > 0) {
pollen.push({ label, value: Math.round(v), level: pollenLevel(v) });
}
}
}
}
// --- NWS alerts (US only; non-US locations 404 or error โ empty) ---
const alerts: Payload["alerts"] = [];
if (alertsRes?.ok) {
const al = (await alertsRes.json()) as {
features?: Array<{
properties: {
event?: string;
severity?: string;
headline?: string;
ends?: string | null;
};
}>;
};
const raw = (al.features ?? [])
.filter((f) => f.properties.event)
.map((f) => ({
event: f.properties.event!,
severity: f.properties.severity ?? "Unknown",
headline: f.properties.headline,
ends: f.properties.ends ?? null,
}));
raw.sort((a, b) => (SEVERITY_RANK[b.severity] ?? 0) - (SEVERITY_RANK[a.severity] ?? 0));
alerts.push(...raw.slice(0, 3));
}
// --- Daily ---
const daily = j.daily.time.map((date, i) => ({
date,
max: Math.round(j.daily.temperature_2m_max[i]),
min: Math.round(j.daily.temperature_2m_min[i]),
code: j.daily.weather_code[i],
text: codeText(j.daily.weather_code[i]),
precipProb: j.daily.precipitation_probability_max[i] ?? null,
}));
// --- Day-parts strip ---
const today = j.daily.time[0];
const parts: Payload["parts"] = [];
if (j.hourly && today) {
const anchors: Array<[string, number]> = [
["Morning", 8], ["Noon", 12], ["Evening", 18], ["Night", 22],
];
const hours = j.hourly.time
.map((t, i) => ({ t, i, hr: Number(t.slice(11, 13)), day: t.slice(0, 10) }))
.filter((h) => h.day === today && Number.isFinite(h.hr));
for (const [label, anchor] of anchors) {
let best: (typeof hours)[number] | null = null;
for (const h of hours) {
if (!best || Math.abs(h.hr - anchor) < Math.abs(best.hr - anchor)) best = h;
}
if (!best) continue;
const code = j.hourly.weather_code[best.i];
parts.push({
label,
temp: Math.round(j.hourly.temperature_2m[best.i]),
code,
text: codeText(code),
precipProb: j.hourly.precipitation_probability[best.i] ?? null,
});
}
}
// --- Moon phase ---
const moon = moonPhase(new Date());
return {
location: place.label,
units,
current: {
temp: Math.round(j.current.temperature_2m),
feelsLike: Math.round(j.current.apparent_temperature),
code: j.current.weather_code,
text: codeText(j.current.weather_code),
wind: Math.round(j.current.wind_speed_10m),
humidity: j.current.relative_humidity_2m ?? null,
uvIndex: j.current.uv_index != null ? Math.round(j.current.uv_index) : null,
},
daily,
parts,
sunrise: j.daily.sunrise?.[0] ?? null,
sunset: j.daily.sunset?.[0] ?? null,
moonPhase: moon.phase,
moonEmoji: moon.emoji,
aqi,
aqiCategory: aqiCat,
pollen,
alerts,
};
},
};
|