kmw-sdk 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +9 -0
- package/LICENSE +21 -0
- package/README.md +273 -2
- package/dist/index.cjs +965 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +3619 -0
- package/dist/index.d.ts +3619 -0
- package/dist/index.js +938 -0
- package/dist/index.js.map +1 -0
- package/package.json +84 -4
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,965 @@
|
|
|
1
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
+
// src/auth.ts
|
|
3
|
+
const base64Utf8 = (text) => btoa(Array.from(new TextEncoder().encode(text), (byte) => String.fromCharCode(byte)).join(""));
|
|
4
|
+
const nonEmptyString = (value, name) => {
|
|
5
|
+
if (typeof value !== "string" || value.trim() === "") throw new TypeError(`${name} must be a non-empty string`);
|
|
6
|
+
return value;
|
|
7
|
+
};
|
|
8
|
+
/**
|
|
9
|
+
* Turns the client options into the header to send. Error messages never
|
|
10
|
+
* contain the credentials.
|
|
11
|
+
* @internal
|
|
12
|
+
*/
|
|
13
|
+
function resolveCredentials(apiKey, auth, envApiKey) {
|
|
14
|
+
const key = apiKey?.trim();
|
|
15
|
+
if (auth === void 0) {
|
|
16
|
+
const resolved = key || envApiKey();
|
|
17
|
+
return resolved ? {
|
|
18
|
+
header: "X-API-Key",
|
|
19
|
+
value: resolved
|
|
20
|
+
} : void 0;
|
|
21
|
+
}
|
|
22
|
+
if (key) throw new TypeError("Pass either `apiKey` or `auth`, not both");
|
|
23
|
+
if (typeof auth !== "object" || auth === null) throw new TypeError("auth must be an object");
|
|
24
|
+
switch (auth.type) {
|
|
25
|
+
case "basic": {
|
|
26
|
+
const username = nonEmptyString(auth.username, "auth.username");
|
|
27
|
+
if (username.includes(":")) throw new TypeError("auth.username must not contain a colon");
|
|
28
|
+
if (typeof auth.password !== "string") throw new TypeError("auth.password must be a string");
|
|
29
|
+
return {
|
|
30
|
+
header: "Authorization",
|
|
31
|
+
value: `Basic ${base64Utf8(`${username}:${auth.password}`)}`
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
case "bearer": {
|
|
35
|
+
const token = nonEmptyString(auth.token, "auth.token").trim();
|
|
36
|
+
if (!/^[\x21-\x7e]+$/.test(token)) throw new TypeError("auth.token must not contain whitespace or non-ASCII characters");
|
|
37
|
+
return {
|
|
38
|
+
header: "Authorization",
|
|
39
|
+
value: `Bearer ${token}`
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
default: throw new TypeError(`auth.type must be "basic" or "bearer", got ${String(auth.type)}`);
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
// src/errors.ts
|
|
46
|
+
/**
|
|
47
|
+
* Base class of every error thrown by this SDK.
|
|
48
|
+
*
|
|
49
|
+
* Aborts triggered by your own `AbortSignal` are not wrapped: the signal's
|
|
50
|
+
* reason is re-thrown unchanged, exactly like `fetch` does.
|
|
51
|
+
*/
|
|
52
|
+
var KachelmannError = class extends Error {
|
|
53
|
+
name = "KachelmannError";
|
|
54
|
+
};
|
|
55
|
+
const isProblem = (body) => typeof body === "object" && body !== null && ("title" in body || "detail" in body);
|
|
56
|
+
/** The API answered with a non-2xx status code. */
|
|
57
|
+
var ApiError = class extends KachelmannError {
|
|
58
|
+
name = "ApiError";
|
|
59
|
+
/** HTTP status code. */
|
|
60
|
+
status;
|
|
61
|
+
method;
|
|
62
|
+
/** Request URL (without credentials). */
|
|
63
|
+
url;
|
|
64
|
+
/** Parsed problem details, if the response body contained any. */
|
|
65
|
+
problem;
|
|
66
|
+
/** Raw response body (parsed JSON, or text). */
|
|
67
|
+
body;
|
|
68
|
+
/** Rate-limit headers of the failed response, if present. */
|
|
69
|
+
rateLimit;
|
|
70
|
+
/**
|
|
71
|
+
* @param init - Status, request and response body.
|
|
72
|
+
* @param hint - Extra explanation appended to the message.
|
|
73
|
+
*/
|
|
74
|
+
constructor(init, hint) {
|
|
75
|
+
const problem = isProblem(init.body) ? init.body : void 0;
|
|
76
|
+
const reason = [problem?.title, problem?.detail].filter(Boolean).join(": ");
|
|
77
|
+
super(`${init.method} ${init.url} failed with HTTP ${init.status}${reason ? ` (${reason})` : ""}${hint ? `. ${hint}` : ""}`);
|
|
78
|
+
this.status = init.status;
|
|
79
|
+
this.method = init.method;
|
|
80
|
+
this.url = init.url;
|
|
81
|
+
this.problem = problem;
|
|
82
|
+
this.body = init.body;
|
|
83
|
+
this.rateLimit = init.rateLimit;
|
|
84
|
+
}
|
|
85
|
+
};
|
|
86
|
+
/** HTTP 400: a parameter is invalid or out of bounds. */
|
|
87
|
+
var BadRequestError = class extends ApiError {
|
|
88
|
+
name = "BadRequestError";
|
|
89
|
+
};
|
|
90
|
+
/** HTTP 401: the API key is missing or wrong. */
|
|
91
|
+
var AuthenticationError = class extends ApiError {
|
|
92
|
+
name = "AuthenticationError";
|
|
93
|
+
};
|
|
94
|
+
/**
|
|
95
|
+
* Appended to the message of every {@link PermissionDeniedError}.
|
|
96
|
+
* @internal
|
|
97
|
+
*/
|
|
98
|
+
const PERMISSION_DENIED_HINT = "Your API key does not cover this request. Keys of some plans (e.g. Hobby, Smart-Home) only work for the API locations set under \"Manage API locations\" at https://accounts.meteologix.com/subscriptions. Other causes: an endpoint or station outside your plan, or a station search radius above 25 km.";
|
|
99
|
+
/**
|
|
100
|
+
* HTTP 403: your subscription does not cover this resource. Typical causes:
|
|
101
|
+
* a location or station outside the API locations set in the account portal
|
|
102
|
+
* (Hobby plans allow two), an endpoint your plan lacks, or a station search
|
|
103
|
+
* radius above 25 km. `problem` contains the API's explanation; `message`
|
|
104
|
+
* contains it too, followed by a hint about these causes.
|
|
105
|
+
*/
|
|
106
|
+
var PermissionDeniedError = class extends ApiError {
|
|
107
|
+
name = "PermissionDeniedError";
|
|
108
|
+
constructor(init) {
|
|
109
|
+
super(init, PERMISSION_DENIED_HINT);
|
|
110
|
+
}
|
|
111
|
+
};
|
|
112
|
+
/** HTTP 404: the resource does not exist (e.g. an unknown weather symbol). */
|
|
113
|
+
var NotFoundError = class extends ApiError {
|
|
114
|
+
name = "NotFoundError";
|
|
115
|
+
};
|
|
116
|
+
/** HTTP 429: the per-minute or per-day request limit was exceeded. */
|
|
117
|
+
var RateLimitError = class extends ApiError {
|
|
118
|
+
name = "RateLimitError";
|
|
119
|
+
/** When requests are allowed again (from `x-ratelimit-retry-after`), if known. */
|
|
120
|
+
get retryAfter() {
|
|
121
|
+
return this.rateLimit?.retryAfter;
|
|
122
|
+
}
|
|
123
|
+
};
|
|
124
|
+
/** HTTP 5xx: the API had an internal problem. */
|
|
125
|
+
var ServerError = class extends ApiError {
|
|
126
|
+
name = "ServerError";
|
|
127
|
+
};
|
|
128
|
+
/** The request did not complete within the configured timeout. */
|
|
129
|
+
var RequestTimeoutError = class extends KachelmannError {
|
|
130
|
+
name = "RequestTimeoutError";
|
|
131
|
+
timeout;
|
|
132
|
+
constructor(timeout, options) {
|
|
133
|
+
super(`Request timed out after ${timeout} ms`, options);
|
|
134
|
+
this.timeout = timeout;
|
|
135
|
+
}
|
|
136
|
+
};
|
|
137
|
+
/** The request failed before a response arrived (DNS, TCP, TLS, ...). See `cause`. */
|
|
138
|
+
var ConnectionError = class extends KachelmannError {
|
|
139
|
+
name = "ConnectionError";
|
|
140
|
+
};
|
|
141
|
+
/**
|
|
142
|
+
* A request needs an API key, but none was configured (neither `apiKey`,
|
|
143
|
+
* `KACHELMANN_API_KEY` nor enterprise `auth`). Thrown before any network
|
|
144
|
+
* traffic.
|
|
145
|
+
*/
|
|
146
|
+
var MissingApiKeyError = class extends KachelmannError {
|
|
147
|
+
name = "MissingApiKeyError";
|
|
148
|
+
constructor(options) {
|
|
149
|
+
super("No API key configured. Pass `apiKey` to `new Kachelmann()` or set the KACHELMANN_API_KEY environment variable.", options);
|
|
150
|
+
}
|
|
151
|
+
};
|
|
152
|
+
/** The API answered with 2xx, but the body could not be parsed or has an unexpected shape. */
|
|
153
|
+
var InvalidResponseError = class extends KachelmannError {
|
|
154
|
+
name = "InvalidResponseError";
|
|
155
|
+
};
|
|
156
|
+
/** Maps an HTTP status code to the most specific error class. */
|
|
157
|
+
function createApiError(init) {
|
|
158
|
+
switch (init.status) {
|
|
159
|
+
case 400: return new BadRequestError(init);
|
|
160
|
+
case 401: return new AuthenticationError(init);
|
|
161
|
+
case 403: return new PermissionDeniedError(init);
|
|
162
|
+
case 404: return new NotFoundError(init);
|
|
163
|
+
case 429: return new RateLimitError(init);
|
|
164
|
+
default: return init.status >= 500 ? new ServerError(init) : new ApiError(init);
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
// src/rate-limit.ts
|
|
168
|
+
const toInt = (value) => {
|
|
169
|
+
if (value === null || value.trim() === "") return void 0;
|
|
170
|
+
const n = Number(value);
|
|
171
|
+
return Number.isFinite(n) ? n : void 0;
|
|
172
|
+
};
|
|
173
|
+
const toDate = (value) => {
|
|
174
|
+
if (value === null || value.trim() === "") return void 0;
|
|
175
|
+
const seconds = Number(value);
|
|
176
|
+
const date = Number.isFinite(seconds) ? new Date(Date.now() + seconds * 1e3) : new Date(value);
|
|
177
|
+
return Number.isNaN(date.getTime()) ? void 0 : date;
|
|
178
|
+
};
|
|
179
|
+
/** Reads the `x-ratelimit-*` headers. Returns `undefined` if none of them is present. */
|
|
180
|
+
function parseRateLimit(headers) {
|
|
181
|
+
const limit = toInt(headers.get("x-ratelimit-limit"));
|
|
182
|
+
const remaining = toInt(headers.get("x-ratelimit-remaining"));
|
|
183
|
+
const retryAfter = toDate(headers.get("x-ratelimit-retry-after"));
|
|
184
|
+
if (limit === void 0 && remaining === void 0 && retryAfter === void 0) return void 0;
|
|
185
|
+
return {
|
|
186
|
+
...limit !== void 0 && { limit },
|
|
187
|
+
...remaining !== void 0 && { remaining },
|
|
188
|
+
...retryAfter !== void 0 && { retryAfter }
|
|
189
|
+
};
|
|
190
|
+
}
|
|
191
|
+
// src/http.ts
|
|
192
|
+
/** Default API base URL. */
|
|
193
|
+
const DEFAULT_BASE_URL = "https://api.kachelmannwetter.com/v02";
|
|
194
|
+
/** Default per-attempt timeout in milliseconds. */
|
|
195
|
+
const DEFAULT_TIMEOUT = 1e4;
|
|
196
|
+
const sleep = (ms, signal) => new Promise((resolve, reject) => {
|
|
197
|
+
if (signal?.aborted) return reject(signal.reason);
|
|
198
|
+
const timer = setTimeout(() => {
|
|
199
|
+
signal?.removeEventListener("abort", onAbort);
|
|
200
|
+
resolve();
|
|
201
|
+
}, ms);
|
|
202
|
+
const onAbort = () => {
|
|
203
|
+
clearTimeout(timer);
|
|
204
|
+
reject(signal?.reason);
|
|
205
|
+
};
|
|
206
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
207
|
+
});
|
|
208
|
+
function appendQuery(params, key, value) {
|
|
209
|
+
if (value === void 0) return;
|
|
210
|
+
if (Array.isArray(value)) value.forEach((item, index) => {
|
|
211
|
+
appendQuery(params, `${key}[${index}]`, item);
|
|
212
|
+
});
|
|
213
|
+
else if (typeof value === "object") for (const [k, v] of Object.entries(value)) appendQuery(params, `${key}[${k}]`, v);
|
|
214
|
+
else params.append(key, String(value));
|
|
215
|
+
}
|
|
216
|
+
/** Encodes a query object. `undefined` values are skipped. */
|
|
217
|
+
function buildQuery(query) {
|
|
218
|
+
if (!query) return "";
|
|
219
|
+
const params = new URLSearchParams();
|
|
220
|
+
for (const [key, value] of Object.entries(query)) appendQuery(params, key, value);
|
|
221
|
+
const qs = params.toString();
|
|
222
|
+
return qs ? `?${qs}` : "";
|
|
223
|
+
}
|
|
224
|
+
/**
|
|
225
|
+
* Thin `fetch` wrapper: auth header, timeout, abort, retries and error mapping.
|
|
226
|
+
* @internal
|
|
227
|
+
*/
|
|
228
|
+
var HttpClient = class {
|
|
229
|
+
#config;
|
|
230
|
+
#rateLimit;
|
|
231
|
+
constructor(config) {
|
|
232
|
+
this.#config = config;
|
|
233
|
+
}
|
|
234
|
+
/** Rate-limit headers of the most recent response, if the API sent any. */
|
|
235
|
+
get rateLimit() {
|
|
236
|
+
return this.#rateLimit;
|
|
237
|
+
}
|
|
238
|
+
/** Absolute URL for a path, without credentials. */
|
|
239
|
+
url(path, query) {
|
|
240
|
+
return `${this.#config.baseUrl}${path}${buildQuery(query)}`;
|
|
241
|
+
}
|
|
242
|
+
async get(request) {
|
|
243
|
+
const { retries, minDelay, maxDelay } = this.#config.retry;
|
|
244
|
+
for (let attempt = 0;; attempt++) try {
|
|
245
|
+
return await this.#attempt(request);
|
|
246
|
+
} catch (error) {
|
|
247
|
+
const delay = attempt < retries ? retryDelay(error, attempt, minDelay, maxDelay) : void 0;
|
|
248
|
+
if (delay === void 0) throw error;
|
|
249
|
+
await sleep(delay, request.signal);
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
async #attempt(request) {
|
|
253
|
+
const url = this.url(request.path, request.query);
|
|
254
|
+
const timeout = request.timeout ?? this.#config.timeout;
|
|
255
|
+
const userSignal = request.signal;
|
|
256
|
+
userSignal?.throwIfAborted();
|
|
257
|
+
const headers = {};
|
|
258
|
+
for (const [name, value] of Object.entries(this.#config.headers)) if (!/^(x-api-key|authorization)$/i.test(name)) headers[name] = value;
|
|
259
|
+
headers.Accept = request.accept ?? "application/json";
|
|
260
|
+
const auth = request.auth ?? "required";
|
|
261
|
+
const credentials = this.#config.credentials;
|
|
262
|
+
if (auth === "required" && !credentials) throw new MissingApiKeyError();
|
|
263
|
+
if (auth !== "none" && credentials) headers[credentials.header] = credentials.value;
|
|
264
|
+
const controller = new AbortController();
|
|
265
|
+
let timedOut = false;
|
|
266
|
+
const timer = setTimeout(() => {
|
|
267
|
+
timedOut = true;
|
|
268
|
+
controller.abort();
|
|
269
|
+
}, timeout);
|
|
270
|
+
const onUserAbort = () => controller.abort(userSignal?.reason);
|
|
271
|
+
userSignal?.addEventListener("abort", onUserAbort, { once: true });
|
|
272
|
+
try {
|
|
273
|
+
let response;
|
|
274
|
+
try {
|
|
275
|
+
response = await this.#config.fetch(url, {
|
|
276
|
+
method: "GET",
|
|
277
|
+
headers,
|
|
278
|
+
signal: controller.signal
|
|
279
|
+
});
|
|
280
|
+
} catch (cause) {
|
|
281
|
+
if (userSignal?.aborted) throw userSignal.reason;
|
|
282
|
+
if (timedOut) throw new RequestTimeoutError(timeout, { cause });
|
|
283
|
+
throw new ConnectionError(`GET ${url} failed: ${describe(cause)}`, { cause });
|
|
284
|
+
}
|
|
285
|
+
const rateLimit = parseRateLimit(response.headers);
|
|
286
|
+
if (rateLimit) this.#rateLimit = rateLimit;
|
|
287
|
+
if (!response.ok) throw createApiError({
|
|
288
|
+
status: response.status,
|
|
289
|
+
method: "GET",
|
|
290
|
+
url,
|
|
291
|
+
body: await readBody(response),
|
|
292
|
+
rateLimit
|
|
293
|
+
});
|
|
294
|
+
if (request.responseType === "text") return await response.text();
|
|
295
|
+
const text = await response.text();
|
|
296
|
+
try {
|
|
297
|
+
return JSON.parse(text);
|
|
298
|
+
} catch (cause) {
|
|
299
|
+
throw new InvalidResponseError(`GET ${url} returned a body that is not valid JSON`, { cause });
|
|
300
|
+
}
|
|
301
|
+
} catch (error) {
|
|
302
|
+
if (userSignal?.aborted) throw userSignal.reason;
|
|
303
|
+
if (timedOut && !(error instanceof KachelmannError)) throw new RequestTimeoutError(timeout, { cause: error });
|
|
304
|
+
throw error;
|
|
305
|
+
} finally {
|
|
306
|
+
clearTimeout(timer);
|
|
307
|
+
userSignal?.removeEventListener("abort", onUserAbort);
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
};
|
|
311
|
+
const describe = (error) => {
|
|
312
|
+
if (!(error instanceof Error)) return String(error);
|
|
313
|
+
const cause = error.cause instanceof Error ? `: ${error.cause.message}` : "";
|
|
314
|
+
return `${error.message}${cause}`;
|
|
315
|
+
};
|
|
316
|
+
async function readBody(response) {
|
|
317
|
+
try {
|
|
318
|
+
const text = await response.text();
|
|
319
|
+
if (!text) return void 0;
|
|
320
|
+
try {
|
|
321
|
+
return JSON.parse(text);
|
|
322
|
+
} catch {
|
|
323
|
+
return text.length > 2e3 ? `${text.slice(0, 2e3)}…` : text;
|
|
324
|
+
}
|
|
325
|
+
} catch {
|
|
326
|
+
return;
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
const RETRYABLE_STATUS = /* @__PURE__ */ new Set([
|
|
330
|
+
500,
|
|
331
|
+
502,
|
|
332
|
+
503,
|
|
333
|
+
504
|
|
334
|
+
]);
|
|
335
|
+
/** Delay before the next attempt, or `undefined` if the error must not be retried. */
|
|
336
|
+
function retryDelay(error, attempt, minDelay, maxDelay) {
|
|
337
|
+
const backoff = Math.min(maxDelay, minDelay * 2 ** attempt) * (.5 + Math.random() * .5);
|
|
338
|
+
if (error instanceof RateLimitError) {
|
|
339
|
+
const retryAfter = error.retryAfter;
|
|
340
|
+
if (!retryAfter) return backoff;
|
|
341
|
+
const wait = retryAfter.getTime() - Date.now();
|
|
342
|
+
return wait <= maxDelay ? Math.max(0, wait) : void 0;
|
|
343
|
+
}
|
|
344
|
+
if (error instanceof ServerError) return RETRYABLE_STATUS.has(error.status) ? backoff : void 0;
|
|
345
|
+
if (error instanceof ConnectionError || error instanceof RequestTimeoutError) return backoff;
|
|
346
|
+
}
|
|
347
|
+
// src/internal.ts
|
|
348
|
+
/**
|
|
349
|
+
* Throws a `RangeError` unless `location` holds valid WGS 84 coordinates, and a
|
|
350
|
+
* `TypeError` if it has both `lon` and `lng` with different values. @internal
|
|
351
|
+
*/
|
|
352
|
+
function coordinatesPath(location) {
|
|
353
|
+
const { lat, lon, lng } = location ?? {};
|
|
354
|
+
if (lon !== void 0 && lng !== void 0 && lon !== lng) throw new TypeError(`location has both lon (${String(lon)}) and lng (${String(lng)})`);
|
|
355
|
+
const longitude = lon ?? lng;
|
|
356
|
+
if (typeof lat !== "number" || !Number.isFinite(lat) || lat < -90 || lat > 90) throw new RangeError(`lat must be a number between -90 and 90, got ${String(lat)}`);
|
|
357
|
+
if (typeof longitude !== "number" || !Number.isFinite(longitude) || longitude < -180 || longitude > 180) throw new RangeError(`lon must be a number between -180 and 180, got ${String(longitude)}`);
|
|
358
|
+
return `/${lat}/${longitude}`;
|
|
359
|
+
}
|
|
360
|
+
/** Encodes a path segment and rejects empty values. @internal */
|
|
361
|
+
function segment(value, name) {
|
|
362
|
+
const text = String(value).trim();
|
|
363
|
+
if (text === "") throw new TypeError(`${name} must not be empty`);
|
|
364
|
+
return encodeURIComponent(text);
|
|
365
|
+
}
|
|
366
|
+
/** Throws unless one of `allowed` was given. @internal */
|
|
367
|
+
function oneOf(value, allowed, name) {
|
|
368
|
+
if (!allowed.includes(value)) throw new TypeError(`${name} must be one of ${allowed.join(", ")}, got ${String(value)}`);
|
|
369
|
+
return value;
|
|
370
|
+
}
|
|
371
|
+
/** Ensures the API answered with a JSON object. @internal */
|
|
372
|
+
function expectObject(value, what) {
|
|
373
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) throw new InvalidResponseError(`Unexpected ${what} response: expected a JSON object`);
|
|
374
|
+
return value;
|
|
375
|
+
}
|
|
376
|
+
/** Ensures the API answered with a JSON array or object map. @internal */
|
|
377
|
+
function expectCollection(value, what) {
|
|
378
|
+
if (typeof value !== "object" || value === null) throw new InvalidResponseError(`Unexpected ${what} response: expected a JSON array`);
|
|
379
|
+
return value;
|
|
380
|
+
}
|
|
381
|
+
/** Picks `signal` and `timeout` from call options. @internal */
|
|
382
|
+
function requestOptions(options) {
|
|
383
|
+
return {
|
|
384
|
+
signal: options?.signal,
|
|
385
|
+
timeout: options?.timeout
|
|
386
|
+
};
|
|
387
|
+
}
|
|
388
|
+
// src/normalize.ts
|
|
389
|
+
/**
|
|
390
|
+
* The API is served by a PHP backend: a list may be serialized as a JSON
|
|
391
|
+
* array or as an object with numeric keys, and an empty map as `[]`. The spec
|
|
392
|
+
* documents this as `oneOf: [array, object]` on almost every collection.
|
|
393
|
+
* These helpers give every collection one stable shape.
|
|
394
|
+
* @internal
|
|
395
|
+
*/
|
|
396
|
+
const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
397
|
+
/** Array or object-map → array. `null`/`undefined` → `[]`. */
|
|
398
|
+
function toArray(value) {
|
|
399
|
+
if (Array.isArray(value)) return value;
|
|
400
|
+
if (isObject(value)) return Object.values(value);
|
|
401
|
+
return [];
|
|
402
|
+
}
|
|
403
|
+
/**
|
|
404
|
+
* Object-map or array → map keyed by `name`. An empty array (PHP's empty map)
|
|
405
|
+
* becomes `{}`; array items are keyed by their `name` property.
|
|
406
|
+
*/
|
|
407
|
+
function toRecordByName(value) {
|
|
408
|
+
if (isObject(value)) return value;
|
|
409
|
+
const record = {};
|
|
410
|
+
if (Array.isArray(value)) {
|
|
411
|
+
for (const item of value) if (isObject(item) && typeof item.name === "string") record[item.name] = item;
|
|
412
|
+
}
|
|
413
|
+
return record;
|
|
414
|
+
}
|
|
415
|
+
/** Numeric strings → numbers; other values are passed through. */
|
|
416
|
+
function toNumberish(value) {
|
|
417
|
+
if (typeof value !== "string" || value.trim() === "") return value;
|
|
418
|
+
const n = Number(value);
|
|
419
|
+
return Number.isFinite(n) ? n : value;
|
|
420
|
+
}
|
|
421
|
+
/** Numbers and numeric strings → number; anything else → `null`. */
|
|
422
|
+
function toNumberOrNull(value) {
|
|
423
|
+
if (typeof value === "number") return Number.isFinite(value) ? value : null;
|
|
424
|
+
const n = toNumberish(value);
|
|
425
|
+
return typeof n === "number" ? n : null;
|
|
426
|
+
}
|
|
427
|
+
// src/resources/climate.ts
|
|
428
|
+
const BASE$1 = "/_frontend";
|
|
429
|
+
const PARAMETERS = [
|
|
430
|
+
"tlmean",
|
|
431
|
+
"rrsum",
|
|
432
|
+
"shsum"
|
|
433
|
+
];
|
|
434
|
+
/** The website allows at most this many compared years. */
|
|
435
|
+
const MAX_COMPARED_YEARS = 5;
|
|
436
|
+
/**
|
|
437
|
+
* **Experimental.** Climate time series (warming stripes, heatmaps, daily
|
|
438
|
+
* curves) of long-term stations. Access via `client.experimental.climate`.
|
|
439
|
+
*
|
|
440
|
+
* These endpoints are **not part of the documented v02 API**: they power the
|
|
441
|
+
* climate pages of kachelmannwetter.com and may change or disappear at any
|
|
442
|
+
* time. They are called with *your* API key. In a live test (November 2026)
|
|
443
|
+
* a regular customer key was rejected with `PermissionDeniedError` (403).
|
|
444
|
+
*
|
|
445
|
+
* @experimental
|
|
446
|
+
*/
|
|
447
|
+
var ClimateResource = class {
|
|
448
|
+
#http;
|
|
449
|
+
/** @internal */
|
|
450
|
+
constructor(http) {
|
|
451
|
+
this.#http = http;
|
|
452
|
+
}
|
|
453
|
+
/** Climate stations of a country, plus large cities for orientation. */
|
|
454
|
+
async stations(country, options) {
|
|
455
|
+
if (typeof country !== "string" || !/^[A-Za-z]{2}$/.test(country)) throw new TypeError("country must be an ISO 3166-1 alpha-2 code, e.g. \"DE\"");
|
|
456
|
+
const raw = expectObject(await this.#http.get({
|
|
457
|
+
path: `${BASE$1}/v2/climate/map`,
|
|
458
|
+
query: { country: country.toUpperCase() },
|
|
459
|
+
...requestOptions(options)
|
|
460
|
+
}), "climate stations");
|
|
461
|
+
return {
|
|
462
|
+
stations: toArray(raw.stations),
|
|
463
|
+
cities: toArray(raw.cities)
|
|
464
|
+
};
|
|
465
|
+
}
|
|
466
|
+
/** Finds climate stations by station or place name. */
|
|
467
|
+
async search(query, options) {
|
|
468
|
+
if (typeof query !== "string" || query.trim() === "") throw new TypeError("query must not be empty");
|
|
469
|
+
return toArray(expectCollection(await this.#http.get({
|
|
470
|
+
path: `${BASE$1}/climate/search`,
|
|
471
|
+
query: { query: query.trim() },
|
|
472
|
+
...requestOptions(options)
|
|
473
|
+
}), "climate search"));
|
|
474
|
+
}
|
|
475
|
+
/** Station details, supported charts, data availability and records. */
|
|
476
|
+
async station(stationId, options) {
|
|
477
|
+
return expectObject(await this.#http.get({
|
|
478
|
+
path: `${BASE$1}/climate/${segment(stationId, "stationId")}`,
|
|
479
|
+
...requestOptions(options)
|
|
480
|
+
}), "climate station");
|
|
481
|
+
}
|
|
482
|
+
/** Warming stripes: one value per year (or per season of each year). */
|
|
483
|
+
async stripes(stationId, options) {
|
|
484
|
+
const by = oneOf(options.by ?? "byYear", ["byYear", "bySeason"], "by");
|
|
485
|
+
const raw = await this.#chart(stationId, `stripes/${by}`, options, { seasons: options.season });
|
|
486
|
+
return {
|
|
487
|
+
...raw,
|
|
488
|
+
categories: toArray(raw.categories),
|
|
489
|
+
matrix: toArray(raw.matrix)
|
|
490
|
+
};
|
|
491
|
+
}
|
|
492
|
+
/** Heatmap of monthly, seasonal and yearly values. */
|
|
493
|
+
async heatmap(stationId, options) {
|
|
494
|
+
const by = oneOf(options.by ?? "byYear", ["byYear", "byMonth"], "by");
|
|
495
|
+
return await this.#chart(stationId, `heatmap/${by}`, options, { year: options.year });
|
|
496
|
+
}
|
|
497
|
+
/** Daily values of each year ("spaghetti" chart) plus the reference period. */
|
|
498
|
+
async spaghetti(stationId, options) {
|
|
499
|
+
const years = options.comparedYears;
|
|
500
|
+
if (years && years.length > MAX_COMPARED_YEARS) throw new RangeError(`comparedYears accepts at most ${MAX_COMPARED_YEARS} years`);
|
|
501
|
+
const raw = await this.#chart(stationId, "spaghetti/daily", options, { comparedYear: years ? [...years] : void 0 });
|
|
502
|
+
return {
|
|
503
|
+
...raw,
|
|
504
|
+
series: toArray(raw.series)
|
|
505
|
+
};
|
|
506
|
+
}
|
|
507
|
+
async #chart(stationId, chart, options, extra) {
|
|
508
|
+
return expectObject(await this.#http.get({
|
|
509
|
+
path: `${BASE$1}/climate/${segment(stationId, "stationId")}/${chart}`,
|
|
510
|
+
query: {
|
|
511
|
+
param: oneOf(options.param, PARAMETERS, "param"),
|
|
512
|
+
start: options.start,
|
|
513
|
+
end: options.end,
|
|
514
|
+
reference: options.reference,
|
|
515
|
+
type: options.type,
|
|
516
|
+
...extra
|
|
517
|
+
},
|
|
518
|
+
...requestOptions(options)
|
|
519
|
+
}), `climate ${chart}`);
|
|
520
|
+
}
|
|
521
|
+
};
|
|
522
|
+
// src/resources/forecast.ts
|
|
523
|
+
const TIME_STEPS$1 = [
|
|
524
|
+
"1h",
|
|
525
|
+
"3h",
|
|
526
|
+
"6h"
|
|
527
|
+
];
|
|
528
|
+
const withRisks = (item) => ({
|
|
529
|
+
...item,
|
|
530
|
+
risks: toArray(item.risks)
|
|
531
|
+
});
|
|
532
|
+
/** Forecast endpoints. Access via `client.forecast`. */
|
|
533
|
+
var ForecastResource = class {
|
|
534
|
+
#http;
|
|
535
|
+
#units;
|
|
536
|
+
/** @internal */
|
|
537
|
+
constructor(http, units) {
|
|
538
|
+
this.#http = http;
|
|
539
|
+
this.#units = units;
|
|
540
|
+
}
|
|
541
|
+
async standard(location, timeSteps, options) {
|
|
542
|
+
return this.#series(location, "standard", timeSteps, options);
|
|
543
|
+
}
|
|
544
|
+
async advanced(location, timeSteps, options) {
|
|
545
|
+
return this.#series(location, "advanced", timeSteps, options);
|
|
546
|
+
}
|
|
547
|
+
async threeDay(location, options) {
|
|
548
|
+
const units = options?.units ?? this.#units;
|
|
549
|
+
const body = await this.#http.get({
|
|
550
|
+
path: `/forecast${coordinatesPath(location)}/3day`,
|
|
551
|
+
query: {
|
|
552
|
+
units,
|
|
553
|
+
minDays: options?.minDays,
|
|
554
|
+
model: options?.model
|
|
555
|
+
},
|
|
556
|
+
accept: "application/vnd.kmw.v2+json",
|
|
557
|
+
...requestOptions(options)
|
|
558
|
+
});
|
|
559
|
+
if (options?.raw) return body;
|
|
560
|
+
const raw = expectObject(body, "3-day forecast");
|
|
561
|
+
const data = toArray(raw.data).map((day) => ({
|
|
562
|
+
...withRisks(day),
|
|
563
|
+
timeOfDay: toArray(day.timeOfDay).map(withRisks)
|
|
564
|
+
}));
|
|
565
|
+
return {
|
|
566
|
+
...raw,
|
|
567
|
+
systemOfUnits: raw.systemOfUnits ?? units,
|
|
568
|
+
data
|
|
569
|
+
};
|
|
570
|
+
}
|
|
571
|
+
async trend14Days(location, options) {
|
|
572
|
+
const units = options?.units ?? this.#units;
|
|
573
|
+
const body = await this.#http.get({
|
|
574
|
+
path: `/forecast${coordinatesPath(location)}/trend14days`,
|
|
575
|
+
query: { units },
|
|
576
|
+
...requestOptions(options)
|
|
577
|
+
});
|
|
578
|
+
if (options?.raw) return body;
|
|
579
|
+
const raw = expectObject(body, "14-day trend");
|
|
580
|
+
return {
|
|
581
|
+
...raw,
|
|
582
|
+
systemOfUnits: raw.systemOfUnits ?? units,
|
|
583
|
+
data: toArray(raw.data).map(withRisks)
|
|
584
|
+
};
|
|
585
|
+
}
|
|
586
|
+
async #series(location, kind, timeSteps, options) {
|
|
587
|
+
const units = options?.units ?? this.#units;
|
|
588
|
+
const path = `/forecast${coordinatesPath(location)}/${kind}/${oneOf(timeSteps, TIME_STEPS$1, "timeSteps")}`;
|
|
589
|
+
const body = await this.#http.get({
|
|
590
|
+
path,
|
|
591
|
+
query: { units },
|
|
592
|
+
...requestOptions(options)
|
|
593
|
+
});
|
|
594
|
+
if (options?.raw) return body;
|
|
595
|
+
const raw = expectObject(body, `${kind} forecast`);
|
|
596
|
+
return {
|
|
597
|
+
...raw,
|
|
598
|
+
systemOfUnits: raw.systemOfUnits ?? units,
|
|
599
|
+
data: toArray(raw.data)
|
|
600
|
+
};
|
|
601
|
+
}
|
|
602
|
+
};
|
|
603
|
+
// src/resources/photos.ts
|
|
604
|
+
const BASE = "/community/weatherphotos";
|
|
605
|
+
const DATE_PATTERN = /^\d{4}-\d{2}-\d{2}$/;
|
|
606
|
+
const toDateString = (value, name) => {
|
|
607
|
+
if (value instanceof Date) {
|
|
608
|
+
if (Number.isNaN(value.getTime())) throw new RangeError(`${name} is an invalid Date`);
|
|
609
|
+
return value.toISOString().slice(0, 10);
|
|
610
|
+
}
|
|
611
|
+
if (typeof value !== "string" || !DATE_PATTERN.test(value)) throw new RangeError(`${name} must be a YYYY-MM-DD string or a Date`);
|
|
612
|
+
return value;
|
|
613
|
+
};
|
|
614
|
+
const expectSuccess = (value, what) => {
|
|
615
|
+
const raw = expectObject(value, what);
|
|
616
|
+
if (raw.status !== "success") throw new InvalidResponseError(`Unexpected ${what} response: status ${String(raw.status)}`);
|
|
617
|
+
return raw;
|
|
618
|
+
};
|
|
619
|
+
/**
|
|
620
|
+
* **Experimental.** Read-only access to the community weather photos of
|
|
621
|
+
* kachelmannwetter.com. Access via `client.photos`.
|
|
622
|
+
*
|
|
623
|
+
* These endpoints are **not part of the documented v02 API** and may change
|
|
624
|
+
* at any time. They are public: no API key is sent. Liking, uploading and
|
|
625
|
+
* view counting need a user account and are not supported.
|
|
626
|
+
*
|
|
627
|
+
* Photos are licensed to Kachelmann GmbH and contain personal data (uploader
|
|
628
|
+
* names, locations): respect copyright and data protection law.
|
|
629
|
+
*
|
|
630
|
+
* @experimental
|
|
631
|
+
*/
|
|
632
|
+
var PhotosResource = class {
|
|
633
|
+
#http;
|
|
634
|
+
/** @internal */
|
|
635
|
+
constructor(http) {
|
|
636
|
+
this.#http = http;
|
|
637
|
+
}
|
|
638
|
+
/** Number of photos per day, keyed by `YYYY-MM-DD`. */
|
|
639
|
+
async counts(options) {
|
|
640
|
+
return expectObject(expectSuccess(await this.#http.get({
|
|
641
|
+
path: `${BASE}/counts`,
|
|
642
|
+
auth: "none",
|
|
643
|
+
...requestOptions(options)
|
|
644
|
+
}), "photo counts").counts, "photo counts");
|
|
645
|
+
}
|
|
646
|
+
/** Photos taken between two days. */
|
|
647
|
+
async list(options) {
|
|
648
|
+
const lengthUnit = options.units === void 0 ? void 0 : options.units === "imperial" ? "anglo" : "metrisch";
|
|
649
|
+
return toArray(expectObject(await this.#http.get({
|
|
650
|
+
path: `${BASE}/list`,
|
|
651
|
+
query: {
|
|
652
|
+
startDate: toDateString(options.from, "from"),
|
|
653
|
+
endDate: toDateString(options.to, "to"),
|
|
654
|
+
format: "geojson",
|
|
655
|
+
windUnit: options.windUnit,
|
|
656
|
+
lengthUnit
|
|
657
|
+
},
|
|
658
|
+
auth: "none",
|
|
659
|
+
...requestOptions(options)
|
|
660
|
+
}), "photo list").features).map((feature) => feature?.properties).filter((props) => typeof props === "object" && props !== null).map((props) => props);
|
|
661
|
+
}
|
|
662
|
+
/** A single photo. Throws `NotFoundError` if it does not exist. */
|
|
663
|
+
async get(id, options) {
|
|
664
|
+
return expectObject(expectSuccess(await this.#http.get({
|
|
665
|
+
path: `${BASE}/${segment(id, "id")}`,
|
|
666
|
+
auth: "none",
|
|
667
|
+
...requestOptions(options)
|
|
668
|
+
}), "photo").photo, "photo");
|
|
669
|
+
}
|
|
670
|
+
};
|
|
671
|
+
// src/resources/stations.ts
|
|
672
|
+
const TIME_STEPS = [
|
|
673
|
+
"10min",
|
|
674
|
+
"1h",
|
|
675
|
+
"1d"
|
|
676
|
+
];
|
|
677
|
+
/** Station coordinates may arrive as strings. @internal */
|
|
678
|
+
const normalizeStation = (raw) => ({
|
|
679
|
+
...raw,
|
|
680
|
+
lat: toNumberOrNull(raw.lat) ?? raw.lat,
|
|
681
|
+
lon: toNumberOrNull(raw.lon) ?? raw.lon
|
|
682
|
+
});
|
|
683
|
+
const header = (raw) => ({
|
|
684
|
+
...raw,
|
|
685
|
+
lat: toNumberOrNull(raw.lat),
|
|
686
|
+
lon: toNumberOrNull(raw.lon),
|
|
687
|
+
ele: toNumberOrNull(raw.ele)
|
|
688
|
+
});
|
|
689
|
+
const observation = (raw) => {
|
|
690
|
+
const entry = {
|
|
691
|
+
...raw,
|
|
692
|
+
thresholds: toRecordByName(raw.thresholds)
|
|
693
|
+
};
|
|
694
|
+
if ("snowHeight" in raw) entry.snowHeight = toNumberOrNull(raw.snowHeight);
|
|
695
|
+
return entry;
|
|
696
|
+
};
|
|
697
|
+
/** Weather station endpoints. Access via `client.stations`. */
|
|
698
|
+
var StationsResource = class {
|
|
699
|
+
#http;
|
|
700
|
+
/** @internal */
|
|
701
|
+
constructor(http) {
|
|
702
|
+
this.#http = http;
|
|
703
|
+
}
|
|
704
|
+
async search(location, options) {
|
|
705
|
+
const body = await this.#http.get({
|
|
706
|
+
path: `/station/search${coordinatesPath(location)}`,
|
|
707
|
+
query: { radius: options?.radius },
|
|
708
|
+
...requestOptions(options)
|
|
709
|
+
});
|
|
710
|
+
if (options?.raw) return body;
|
|
711
|
+
return toArray(expectCollection(body, "station search")).map(normalizeStation);
|
|
712
|
+
}
|
|
713
|
+
async latest(stationId, options) {
|
|
714
|
+
const body = await this.#http.get({
|
|
715
|
+
path: `/station/${segment(stationId, "stationId")}/observations/latest`,
|
|
716
|
+
...requestOptions(options)
|
|
717
|
+
});
|
|
718
|
+
if (options?.raw) return body;
|
|
719
|
+
const raw = expectObject(body, "latest observations");
|
|
720
|
+
return {
|
|
721
|
+
...header(raw),
|
|
722
|
+
data: toRecordByName(raw.data)
|
|
723
|
+
};
|
|
724
|
+
}
|
|
725
|
+
async observations(stationId, timeSteps, options) {
|
|
726
|
+
const body = await this.#http.get({
|
|
727
|
+
path: `/station/${segment(stationId, "stationId")}/observations/${oneOf(timeSteps, TIME_STEPS, "timeSteps")}`,
|
|
728
|
+
query: { threshold: options?.threshold },
|
|
729
|
+
...requestOptions(options)
|
|
730
|
+
});
|
|
731
|
+
if (options?.raw) return body;
|
|
732
|
+
const raw = expectObject(body, "observations");
|
|
733
|
+
return {
|
|
734
|
+
...header(raw),
|
|
735
|
+
data: toArray(raw.data).map(observation)
|
|
736
|
+
};
|
|
737
|
+
}
|
|
738
|
+
};
|
|
739
|
+
// src/resources/tools.ts
|
|
740
|
+
const SYMBOL_PATTERN = /^[A-Za-z0-9_-]+$/;
|
|
741
|
+
const symbolPath = (symbol) => {
|
|
742
|
+
if (typeof symbol !== "string" || !SYMBOL_PATTERN.test(symbol)) throw new TypeError(`Invalid weather symbol: ${String(symbol)}`);
|
|
743
|
+
return `/tools/weatherSymbol/${symbol}.svg`;
|
|
744
|
+
};
|
|
745
|
+
/** Tool endpoints (astronomy, weather symbols). Access via `client.tools`. */
|
|
746
|
+
var ToolsResource = class {
|
|
747
|
+
#http;
|
|
748
|
+
/** @internal */
|
|
749
|
+
constructor(http) {
|
|
750
|
+
this.#http = http;
|
|
751
|
+
}
|
|
752
|
+
async astronomy(location, options) {
|
|
753
|
+
const body = await this.#http.get({
|
|
754
|
+
path: `/tools/astronomy${coordinatesPath(location)}`,
|
|
755
|
+
...requestOptions(options)
|
|
756
|
+
});
|
|
757
|
+
if (options?.raw) return body;
|
|
758
|
+
const raw = expectObject(body, "astronomy");
|
|
759
|
+
return {
|
|
760
|
+
...raw,
|
|
761
|
+
dailyData: toArray(raw.dailyData)
|
|
762
|
+
};
|
|
763
|
+
}
|
|
764
|
+
/**
|
|
765
|
+
* Downloads the SVG markup of a weather symbol, e.g. `"partlycloudy_night"`.
|
|
766
|
+
* The API key is sent if one is configured. The endpoint also works
|
|
767
|
+
* without one (checked live, November 2026).
|
|
768
|
+
*/
|
|
769
|
+
async weatherSymbol(symbol, options) {
|
|
770
|
+
return this.#http.get({
|
|
771
|
+
path: symbolPath(symbol),
|
|
772
|
+
accept: "image/svg+xml",
|
|
773
|
+
responseType: "text",
|
|
774
|
+
auth: "optional",
|
|
775
|
+
...requestOptions(options)
|
|
776
|
+
});
|
|
777
|
+
}
|
|
778
|
+
/**
|
|
779
|
+
* URL of a weather symbol SVG, e.g. for an `<img src>`. The URL contains no
|
|
780
|
+
* credentials; the endpoint answered without an API key in a live test
|
|
781
|
+
* (November 2026).
|
|
782
|
+
*/
|
|
783
|
+
weatherSymbolUrl(symbol) {
|
|
784
|
+
return this.#http.url(symbolPath(symbol));
|
|
785
|
+
}
|
|
786
|
+
};
|
|
787
|
+
// src/client.ts
|
|
788
|
+
const envApiKey = () => {
|
|
789
|
+
const key = globalThis.process?.env?.KACHELMANN_API_KEY;
|
|
790
|
+
return key?.trim() ? key.trim() : void 0;
|
|
791
|
+
};
|
|
792
|
+
const nonNegative = (value, fallback, name) => {
|
|
793
|
+
if (value === void 0) return fallback;
|
|
794
|
+
if (!Number.isFinite(value) || value < 0) throw new RangeError(`${name} must be a non-negative number`);
|
|
795
|
+
return value;
|
|
796
|
+
};
|
|
797
|
+
const resolveRetry = (retry) => {
|
|
798
|
+
const options = typeof retry === "number" ? { retries: retry } : retry ?? {};
|
|
799
|
+
return {
|
|
800
|
+
retries: Math.floor(nonNegative(options.retries, 0, "retry.retries")),
|
|
801
|
+
minDelay: nonNegative(options.minDelay, 500, "retry.minDelay"),
|
|
802
|
+
maxDelay: nonNegative(options.maxDelay, 1e4, "retry.maxDelay")
|
|
803
|
+
};
|
|
804
|
+
};
|
|
805
|
+
/**
|
|
806
|
+
* Client for the Kachelmannwetter API v02.
|
|
807
|
+
*
|
|
808
|
+
* @typeParam U - Default system of units, inferred from `options.units`.
|
|
809
|
+
* @example
|
|
810
|
+
* import { Kachelmann } from "kmw-sdk";
|
|
811
|
+
*
|
|
812
|
+
* const client = new Kachelmann({ apiKey: process.env.KACHELMANN_API_KEY });
|
|
813
|
+
* const forecast = await client.forecast.threeDay({ lat: 50.1, lon: 8.7 });
|
|
814
|
+
*/
|
|
815
|
+
var Kachelmann = class {
|
|
816
|
+
/** Forecasts: standard/advanced time series, 3-day summary and 14-day trend. */
|
|
817
|
+
forecast;
|
|
818
|
+
/** Weather stations: search, latest values and observation history. */
|
|
819
|
+
stations;
|
|
820
|
+
/** Astronomy data and weather symbols. */
|
|
821
|
+
tools;
|
|
822
|
+
/**
|
|
823
|
+
* Endpoints that are known not to work with regular API keys yet. Not
|
|
824
|
+
* covered by semver. See {@link ExperimentalApi}.
|
|
825
|
+
* @experimental
|
|
826
|
+
*/
|
|
827
|
+
experimental;
|
|
828
|
+
/**
|
|
829
|
+
* **Experimental**, undocumented: community weather photos (read-only, no key needed).
|
|
830
|
+
* @experimental
|
|
831
|
+
*/
|
|
832
|
+
photos;
|
|
833
|
+
#http;
|
|
834
|
+
#units;
|
|
835
|
+
constructor(options = {}) {
|
|
836
|
+
const fetchImpl = options.fetch ?? globalThis.fetch;
|
|
837
|
+
if (typeof fetchImpl !== "function") throw new TypeError("No fetch implementation available. Use Node.js 20+ or pass `fetch`.");
|
|
838
|
+
const units = options.units ?? "metric";
|
|
839
|
+
if (units !== "metric" && units !== "imperial") throw new TypeError(`units must be "metric" or "imperial", got ${String(units)}`);
|
|
840
|
+
this.#units = units;
|
|
841
|
+
this.#http = new HttpClient({
|
|
842
|
+
credentials: resolveCredentials(options.apiKey, options.auth, envApiKey),
|
|
843
|
+
baseUrl: (options.baseUrl ?? "https://api.kachelmannwetter.com/v02").replace(/\/+$/, ""),
|
|
844
|
+
timeout: nonNegative(options.timeout, DEFAULT_TIMEOUT, "timeout"),
|
|
845
|
+
retry: resolveRetry(options.retry),
|
|
846
|
+
fetch: (input, init) => fetchImpl(input, init),
|
|
847
|
+
headers: { ...options.headers }
|
|
848
|
+
});
|
|
849
|
+
this.forecast = new ForecastResource(this.#http, units);
|
|
850
|
+
this.stations = new StationsResource(this.#http);
|
|
851
|
+
this.tools = new ToolsResource(this.#http);
|
|
852
|
+
this.experimental = Object.freeze({ climate: new ClimateResource(this.#http) });
|
|
853
|
+
this.photos = new PhotosResource(this.#http);
|
|
854
|
+
}
|
|
855
|
+
/**
|
|
856
|
+
* Rate-limit headers of the most recent response (`x-ratelimit-*`), if the
|
|
857
|
+
* API sent any.
|
|
858
|
+
*/
|
|
859
|
+
get rateLimit() {
|
|
860
|
+
return this.#http.rateLimit;
|
|
861
|
+
}
|
|
862
|
+
async current(location, options) {
|
|
863
|
+
const units = options?.units ?? this.#units;
|
|
864
|
+
const body = await this.#http.get({
|
|
865
|
+
path: `/current${coordinatesPath(location)}`,
|
|
866
|
+
query: { units },
|
|
867
|
+
...requestOptions(options)
|
|
868
|
+
});
|
|
869
|
+
if (options?.raw) return body;
|
|
870
|
+
const raw = expectObject(body, "current weather");
|
|
871
|
+
const data = {};
|
|
872
|
+
for (const [name, value] of Object.entries(toRecordByName(raw.data))) {
|
|
873
|
+
const normalized = {
|
|
874
|
+
...value,
|
|
875
|
+
value: value.value ?? null
|
|
876
|
+
};
|
|
877
|
+
if (value.station && typeof value.station === "object") Object.assign(normalized, { station: normalizeStation(value.station) });
|
|
878
|
+
data[name] = normalized;
|
|
879
|
+
}
|
|
880
|
+
return {
|
|
881
|
+
...raw,
|
|
882
|
+
systemOfUnits: raw.systemOfUnits ?? units,
|
|
883
|
+
data
|
|
884
|
+
};
|
|
885
|
+
}
|
|
886
|
+
};
|
|
887
|
+
// src/units.ts
|
|
888
|
+
/**
|
|
889
|
+
* Small unit conversion helpers. Forecasts use m/s for wind (metric), station
|
|
890
|
+
* observations use knots, and most people expect km/h.
|
|
891
|
+
* @module
|
|
892
|
+
*/
|
|
893
|
+
const round = (value, digits) => {
|
|
894
|
+
if (digits === void 0) return value;
|
|
895
|
+
const factor = 10 ** digits;
|
|
896
|
+
return Math.round(value * factor) / factor;
|
|
897
|
+
};
|
|
898
|
+
/** Knots → km/h. */
|
|
899
|
+
const knotsToKmh = (kn, digits) => round(kn * 1.852, digits);
|
|
900
|
+
/** Knots → m/s. */
|
|
901
|
+
const knotsToMps = (kn, digits) => round(kn * 1852 / 3600, digits);
|
|
902
|
+
/** Knots → mph. */
|
|
903
|
+
const knotsToMph = (kn, digits) => round(kn * 1.852 / 1.609344, digits);
|
|
904
|
+
/** m/s → km/h. */
|
|
905
|
+
const mpsToKmh = (mps, digits) => round(mps * 3.6, digits);
|
|
906
|
+
/** m/s → knots. */
|
|
907
|
+
const mpsToKnots = (mps, digits) => round(mps * 3600 / 1852, digits);
|
|
908
|
+
/** mph → km/h. */
|
|
909
|
+
const mphToKmh = (mph, digits) => round(mph * 1.609344, digits);
|
|
910
|
+
/** km/h → m/s. */
|
|
911
|
+
const kmhToMps = (kmh, digits) => round(kmh / 3.6, digits);
|
|
912
|
+
/** °C → °F. */
|
|
913
|
+
const celsiusToFahrenheit = (c, digits) => round(c * 9 / 5 + 32, digits);
|
|
914
|
+
/** °F → °C. */
|
|
915
|
+
const fahrenheitToCelsius = (f, digits) => round((f - 32) * 5 / 9, digits);
|
|
916
|
+
/** Millimetres → inches. */
|
|
917
|
+
const mmToInch = (mm, digits) => round(mm / 25.4, digits);
|
|
918
|
+
/** Inches → millimetres. */
|
|
919
|
+
const inchToMm = (inch, digits) => round(inch * 25.4, digits);
|
|
920
|
+
/** Groups a WMO 4677 present weather code. Returns `undefined` for values outside 0–99. */
|
|
921
|
+
function classifyWmoCode(code) {
|
|
922
|
+
if (!Number.isInteger(code) || code < 0 || code > 99) return void 0;
|
|
923
|
+
if (code <= 3) return "none";
|
|
924
|
+
if (code <= 9) return "haze";
|
|
925
|
+
if (code <= 12) return "mist";
|
|
926
|
+
if (code <= 19) return "nearby";
|
|
927
|
+
if (code <= 29) return "recent";
|
|
928
|
+
if (code <= 35) return "duststorm";
|
|
929
|
+
if (code <= 39) return "blowingSnow";
|
|
930
|
+
if (code <= 49) return "fog";
|
|
931
|
+
if (code <= 59) return "drizzle";
|
|
932
|
+
if (code <= 69) return "rain";
|
|
933
|
+
if (code <= 79) return "snow";
|
|
934
|
+
if (code <= 90) return "showers";
|
|
935
|
+
return "thunderstorm";
|
|
936
|
+
}
|
|
937
|
+
exports.ApiError = ApiError;
|
|
938
|
+
exports.AuthenticationError = AuthenticationError;
|
|
939
|
+
exports.BadRequestError = BadRequestError;
|
|
940
|
+
exports.ConnectionError = ConnectionError;
|
|
941
|
+
exports.DEFAULT_BASE_URL = DEFAULT_BASE_URL;
|
|
942
|
+
exports.DEFAULT_TIMEOUT = DEFAULT_TIMEOUT;
|
|
943
|
+
exports.InvalidResponseError = InvalidResponseError;
|
|
944
|
+
exports.Kachelmann = Kachelmann;
|
|
945
|
+
exports.KachelmannError = KachelmannError;
|
|
946
|
+
exports.MissingApiKeyError = MissingApiKeyError;
|
|
947
|
+
exports.NotFoundError = NotFoundError;
|
|
948
|
+
exports.PermissionDeniedError = PermissionDeniedError;
|
|
949
|
+
exports.RateLimitError = RateLimitError;
|
|
950
|
+
exports.RequestTimeoutError = RequestTimeoutError;
|
|
951
|
+
exports.ServerError = ServerError;
|
|
952
|
+
exports.celsiusToFahrenheit = celsiusToFahrenheit;
|
|
953
|
+
exports.classifyWmoCode = classifyWmoCode;
|
|
954
|
+
exports.fahrenheitToCelsius = fahrenheitToCelsius;
|
|
955
|
+
exports.inchToMm = inchToMm;
|
|
956
|
+
exports.kmhToMps = kmhToMps;
|
|
957
|
+
exports.knotsToKmh = knotsToKmh;
|
|
958
|
+
exports.knotsToMph = knotsToMph;
|
|
959
|
+
exports.knotsToMps = knotsToMps;
|
|
960
|
+
exports.mmToInch = mmToInch;
|
|
961
|
+
exports.mphToKmh = mphToKmh;
|
|
962
|
+
exports.mpsToKmh = mpsToKmh;
|
|
963
|
+
exports.mpsToKnots = mpsToKnots;
|
|
964
|
+
|
|
965
|
+
//# sourceMappingURL=index.cjs.map
|