@firebreak/vitals 1.2.2 → 1.3.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/dist/index.mjs CHANGED
@@ -23,7 +23,7 @@ function statusFromString(value) {
23
23
  return mapping[value.toLowerCase()] ?? Status.OUTAGE;
24
24
  }
25
25
  function toJson(response) {
26
- return {
26
+ const json = {
27
27
  status: statusToLabel(response.status),
28
28
  timestamp: response.timestamp,
29
29
  checks: Object.fromEntries(
@@ -33,6 +33,10 @@ function toJson(response) {
33
33
  ])
34
34
  )
35
35
  };
36
+ if (response.cachedAt !== void 0) {
37
+ json.cachedAt = response.cachedAt;
38
+ }
39
+ return json;
36
40
  }
37
41
  function httpStatusCode(status) {
38
42
  return status === Status.HEALTHY ? 200 : 503;
@@ -43,8 +47,11 @@ import { performance } from "perf_hooks";
43
47
  var HealthcheckRegistry = class {
44
48
  checks = [];
45
49
  defaultTimeout;
50
+ cacheTtlMs;
51
+ cache = null;
46
52
  constructor(options) {
47
53
  this.defaultTimeout = options?.defaultTimeout ?? 5e3;
54
+ this.cacheTtlMs = options?.cacheTtlMs ?? 0;
48
55
  }
49
56
  add(name, fn, options) {
50
57
  if (this.checks.some((c) => c.name === name)) {
@@ -69,6 +76,27 @@ var HealthcheckRegistry = class {
69
76
  };
70
77
  }
71
78
  async run() {
79
+ if (this.cacheTtlMs <= 0) {
80
+ return this.executeChecks();
81
+ }
82
+ if (this.cache !== null && Date.now() < this.cache.expiresAt) {
83
+ return {
84
+ status: this.cache.status,
85
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
86
+ checks: structuredClone(this.cache.checks),
87
+ cachedAt: this.cache.cachedAt
88
+ };
89
+ }
90
+ const response = await this.executeChecks();
91
+ this.cache = {
92
+ checks: structuredClone(response.checks),
93
+ status: response.status,
94
+ cachedAt: response.timestamp,
95
+ expiresAt: Date.now() + this.cacheTtlMs
96
+ };
97
+ return response;
98
+ }
99
+ async executeChecks() {
72
100
  if (this.checks.length === 0) {
73
101
  return {
74
102
  status: Status.HEALTHY,
@@ -154,32 +182,52 @@ function extractToken(options) {
154
182
  }
155
183
 
156
184
  // src/handler.ts
157
- var RESERVED_METADATA_KEYS = ["status", "timestamp", "checks"];
185
+ var RESERVED_METADATA_KEYS = ["status", "timestamp", "checks", "cachedAt"];
158
186
  function createHealthcheckHandler(options) {
159
- const { registry, token = null, queryParamName = "token", metadata = {} } = options;
187
+ const { registry, token: rawToken, deep = false, queryParamName = "token", metadata = {} } = options;
188
+ const isEmptyToken = typeof rawToken === "string" && rawToken.trim() === "";
189
+ if (deep && isEmptyToken) {
190
+ throw new Error(
191
+ "Cannot use `deep: true` with an empty string token. This would expose deep healthcheck data without authentication. Either set a non-empty token or explicitly set `token: null`."
192
+ );
193
+ }
194
+ const token = rawToken == null || isEmptyToken ? null : rawToken;
160
195
  for (const key of Object.keys(metadata)) {
161
196
  if (RESERVED_METADATA_KEYS.includes(key)) {
162
197
  throw new Error(`Metadata key '${key}' is reserved. Use a different key name.`);
163
198
  }
164
199
  }
165
200
  return async (req) => {
166
- if (token !== null) {
167
- const provided = extractToken({
168
- queryParams: req.queryParams,
169
- authorizationHeader: req.authorizationHeader,
170
- queryParamName
171
- });
172
- if (provided === null) {
173
- const body = {
174
- status: "ok",
175
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
176
- ...metadata
201
+ if (token === null) {
202
+ if (deep) {
203
+ const response2 = await registry.run();
204
+ return {
205
+ status: httpStatusCode(response2.status),
206
+ body: { ...metadata, ...toJson(response2) }
177
207
  };
178
- return { status: 200, body };
179
- }
180
- if (!verifyToken(provided, token)) {
181
- return { status: 403, body: { error: "Forbidden" } };
182
208
  }
209
+ const body = {
210
+ status: "ok",
211
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
212
+ ...metadata
213
+ };
214
+ return { status: 200, body };
215
+ }
216
+ const provided = extractToken({
217
+ queryParams: req.queryParams,
218
+ authorizationHeader: req.authorizationHeader,
219
+ queryParamName
220
+ });
221
+ if (provided === null) {
222
+ const body = {
223
+ status: "ok",
224
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
225
+ ...metadata
226
+ };
227
+ return { status: 200, body };
228
+ }
229
+ if (!verifyToken(provided, token)) {
230
+ return { status: 403, body: { error: "Forbidden" } };
183
231
  }
184
232
  const response = await registry.run();
185
233
  return {
@@ -188,12 +236,247 @@ function createHealthcheckHandler(options) {
188
236
  };
189
237
  };
190
238
  }
239
+
240
+ // src/html.ts
241
+ function escapeHtml(str) {
242
+ return str.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
243
+ }
244
+ function statusColor(status) {
245
+ switch (status) {
246
+ case "healthy":
247
+ case "ok":
248
+ return "#22C55E";
249
+ case "degraded":
250
+ return "#F59E0B";
251
+ case "outage":
252
+ return "#ED1C24";
253
+ default:
254
+ return "#ED1C24";
255
+ }
256
+ }
257
+ var DEEP_KNOWN_KEYS = /* @__PURE__ */ new Set(["status", "timestamp", "checks", "cachedAt"]);
258
+ function isDeepResponse(body) {
259
+ return "checks" in body && "status" in body && body.status !== "ok";
260
+ }
261
+ function isShallowResponse(body) {
262
+ return "status" in body && body.status === "ok";
263
+ }
264
+ function isErrorResponse(body) {
265
+ return "error" in body && !("status" in body);
266
+ }
267
+ function renderStatusBadge(label, color) {
268
+ return `<span style="
269
+ display: inline-flex;
270
+ align-items: center;
271
+ gap: 8px;
272
+ padding: 4px 12px;
273
+ border-radius: 9999px;
274
+ background: ${color}1A;
275
+ font-family: 'Inter', system-ui, sans-serif;
276
+ font-size: 12px;
277
+ font-weight: 600;
278
+ letter-spacing: 0.05em;
279
+ text-transform: uppercase;
280
+ color: ${color};
281
+ "><span style="
282
+ width: 8px;
283
+ height: 8px;
284
+ border-radius: 50%;
285
+ background: ${color};
286
+ box-shadow: 0 0 6px ${color}80;
287
+ "></span>${escapeHtml(label)}</span>`;
288
+ }
289
+ function renderMetadataItems(items) {
290
+ if (items.length === 0) return "";
291
+ return `<div style="
292
+ display: flex;
293
+ flex-wrap: wrap;
294
+ gap: 24px;
295
+ margin-top: 16px;
296
+ ">${items.map(
297
+ ([label, value]) => `<div>
298
+ <div style="
299
+ font-family: 'Inter', system-ui, sans-serif;
300
+ font-size: 10px;
301
+ font-weight: 600;
302
+ letter-spacing: 0.05em;
303
+ text-transform: uppercase;
304
+ color: #A1A1AA;
305
+ margin-bottom: 4px;
306
+ ">${escapeHtml(label)}</div>
307
+ <div style="
308
+ font-family: 'JetBrains Mono', monospace;
309
+ font-size: 13px;
310
+ color: #E4E4E7;
311
+ ">${escapeHtml(value)}</div>
312
+ </div>`
313
+ ).join("")}</div>`;
314
+ }
315
+ function renderCheckRow(name, check) {
316
+ const color = statusColor(check.status);
317
+ return `<div style="
318
+ display: flex;
319
+ align-items: center;
320
+ gap: 12px;
321
+ padding: 12px 0;
322
+ border-top: 1px solid #27272A;
323
+ ">
324
+ <span style="
325
+ width: 8px;
326
+ height: 8px;
327
+ border-radius: 50%;
328
+ background: ${color};
329
+ box-shadow: 0 0 6px ${color}80;
330
+ flex-shrink: 0;
331
+ "></span>
332
+ <span style="
333
+ font-family: 'Inter', system-ui, sans-serif;
334
+ font-size: 12px;
335
+ text-transform: uppercase;
336
+ letter-spacing: 0.05em;
337
+ color: ${color};
338
+ font-weight: 600;
339
+ min-width: 72px;
340
+ ">${escapeHtml(check.status)}</span>
341
+ <span style="
342
+ font-family: 'Inter', system-ui, sans-serif;
343
+ font-size: 14px;
344
+ font-weight: 500;
345
+ color: #E4E4E7;
346
+ flex: 1;
347
+ ">${escapeHtml(name)}</span>
348
+ <span style="
349
+ font-family: 'JetBrains Mono', monospace;
350
+ font-size: 12px;
351
+ color: #A1A1AA;
352
+ min-width: 60px;
353
+ text-align: right;
354
+ ">${escapeHtml(String(check.latencyMs))}ms</span>
355
+ <span style="
356
+ font-family: 'JetBrains Mono', monospace;
357
+ font-size: 12px;
358
+ color: #71717A;
359
+ max-width: 200px;
360
+ overflow: hidden;
361
+ text-overflow: ellipsis;
362
+ white-space: nowrap;
363
+ ">${escapeHtml(check.message)}</span>
364
+ </div>`;
365
+ }
366
+ function renderPage(borderColor, content) {
367
+ return `<!DOCTYPE html>
368
+ <html lang="en">
369
+ <head>
370
+ <meta charset="utf-8">
371
+ <meta name="viewport" content="width=device-width, initial-scale=1">
372
+ <title>Healthcheck</title>
373
+ <style></style>
374
+ </head>
375
+ <body style="
376
+ margin: 0;
377
+ padding: 40px 20px;
378
+ background: #08080A;
379
+ min-height: 100vh;
380
+ display: flex;
381
+ justify-content: center;
382
+ align-items: flex-start;
383
+ box-sizing: border-box;
384
+ ">
385
+ <div style="
386
+ width: 100%;
387
+ max-width: 560px;
388
+ background: #18181B;
389
+ border: 1px solid #27272A;
390
+ border-left: 3px solid ${borderColor};
391
+ border-radius: 8px;
392
+ padding: 24px;
393
+ ">
394
+ ${content}
395
+ </div>
396
+ </body>
397
+ </html>`;
398
+ }
399
+ function renderHealthcheckHtml(body) {
400
+ if (isErrorResponse(body)) {
401
+ const color = "#ED1C24";
402
+ return renderPage(
403
+ color,
404
+ `<div style="display: flex; align-items: center; justify-content: space-between;">
405
+ <span style="
406
+ font-family: 'Inter', system-ui, sans-serif;
407
+ font-size: 18px;
408
+ font-weight: 700;
409
+ color: #E4E4E7;
410
+ ">Healthcheck</span>
411
+ ${renderStatusBadge("ERROR", color)}
412
+ </div>
413
+ <div style="
414
+ margin-top: 16px;
415
+ font-family: 'JetBrains Mono', monospace;
416
+ font-size: 13px;
417
+ color: #EF4444;
418
+ ">${escapeHtml(body.error)}</div>`
419
+ );
420
+ }
421
+ if (isShallowResponse(body)) {
422
+ const color = statusColor("ok");
423
+ const { status: _, timestamp, ...rest } = body;
424
+ const metadataItems = Object.entries(rest).map(
425
+ ([k, v]) => [k, String(v)]
426
+ );
427
+ const allItems = [
428
+ ["timestamp", timestamp],
429
+ ...metadataItems
430
+ ];
431
+ return renderPage(
432
+ color,
433
+ `<div style="display: flex; align-items: center; justify-content: space-between;">
434
+ <span style="
435
+ font-family: 'Inter', system-ui, sans-serif;
436
+ font-size: 18px;
437
+ font-weight: 700;
438
+ color: #E4E4E7;
439
+ ">Healthcheck</span>
440
+ ${renderStatusBadge("OK", color)}
441
+ </div>
442
+ ${renderMetadataItems(allItems)}`
443
+ );
444
+ }
445
+ if (isDeepResponse(body)) {
446
+ const color = statusColor(body.status);
447
+ const { timestamp, checks } = body;
448
+ const metadataItems = Object.entries(body).filter(([k]) => !DEEP_KNOWN_KEYS.has(k)).map(([k, v]) => [k, String(v)]);
449
+ const allItems = [
450
+ ["timestamp", timestamp],
451
+ ...metadataItems
452
+ ];
453
+ const checkRows = Object.entries(checks).sort(([a], [b]) => a.localeCompare(b)).map(([name, check]) => renderCheckRow(name, check)).join("");
454
+ return renderPage(
455
+ color,
456
+ `<div style="display: flex; align-items: center; justify-content: space-between;">
457
+ <span style="
458
+ font-family: 'Inter', system-ui, sans-serif;
459
+ font-size: 18px;
460
+ font-weight: 700;
461
+ color: #E4E4E7;
462
+ ">Healthcheck</span>
463
+ ${renderStatusBadge(body.status, color)}
464
+ </div>
465
+ ${renderMetadataItems(allItems)}
466
+ <div style="margin-top: 20px;">
467
+ ${checkRows}
468
+ </div>`
469
+ );
470
+ }
471
+ return renderPage("#ED1C24", `<pre style="color: #E4E4E7; font-family: 'JetBrains Mono', monospace;">${escapeHtml(JSON.stringify(body, null, 2))}</pre>`);
472
+ }
191
473
  export {
192
474
  HealthcheckRegistry,
193
475
  Status,
194
476
  createHealthcheckHandler,
195
477
  extractToken,
196
478
  httpStatusCode,
479
+ renderHealthcheckHtml,
197
480
  statusFromString,
198
481
  statusToLabel,
199
482
  syncCheck,