watchfor 0.17.1 → 0.17.2

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/README.md CHANGED
@@ -102,7 +102,8 @@ const dns = await wf.diagnostics.run("dns-lookup", {
102
102
  target: "example.com",
103
103
  options: { recordType: "A", resolver: "8.8.8.8" },
104
104
  });
105
- // A closed port / NXDOMAIN / failed handshake does NOT throw:
105
+ // A closed port, NXDOMAIN, expired certificate or unresolvable host does NOT
106
+ // throw — `success` is false and `error` says why (`result` keeps the raw answer):
106
107
  if (!dns.success) console.log("finding:", dns.error);
107
108
  console.log("runs left this hour:", dns.remaining);
108
109
 
@@ -133,7 +134,13 @@ Toolbox. Details: https://watchfor.io/docs/api/diagnostics
133
134
 
134
135
  - Fully typed from the [OpenAPI spec](https://watchfor.io/openapi.json)
135
136
  - Zero runtime dependencies (uses global `fetch`, Node ≥ 18)
136
- - `WatchForError` carries `status`, `code` and `retryAfterSeconds`
137
+ - `WatchForError` carries `status`, `code` and `retryAfterSeconds`; a
138
+ non-JSON answer (an HTML page from a wrong base URL or a proxy) is a
139
+ short `http_error` / `invalid_response` pointing at the base URL
140
+ - `baseUrl` (and the CLI's `WATCHFOR_BASE_URL`) takes the origin
141
+ (`https://watchfor.io`) or the full base (`https://watchfor.io/api/v1`) —
142
+ the same value works for the Python and Ruby SDKs
143
+ - CLI: `watchfor --version`; `report --period` accepts only `7d` or `30d`
137
144
  - Pass an idempotency key as the second argument of any `create` call for safe retries
138
145
 
139
146
  ## Organizations
package/dist/cli.js CHANGED
@@ -1,5 +1,9 @@
1
1
  #!/usr/bin/env node
2
+ import { createRequire } from "node:module";
2
3
  import { WatchFor, WatchForError } from "./client.js";
4
+ /** The package version (dist/cli.js and src/cli.ts both sit next to
5
+ * ../package.json, which npm always ships). */
6
+ const VERSION = createRequire(import.meta.url)("../package.json").version;
3
7
  /**
4
8
  * `watchfor` CLI — quick terminal access to the monitoring API.
5
9
  *
@@ -29,6 +33,7 @@ Commands:
29
33
  watchfor metrics [--tag t] [--type t]
30
34
  Prometheus text format (Pro plan and above)
31
35
  watchfor help
36
+ watchfor --version Print the CLI/SDK version
32
37
 
33
38
  Global options:
34
39
  --organization <id> Organization to act on (X-WatchFor-Organization). OAuth
@@ -38,7 +43,7 @@ Global options:
38
43
  Environment:
39
44
  WATCHFOR_API_KEY API key (dashboard → Settings → API keys) or an OAuth access token
40
45
  WATCHFOR_ORGANIZATION Default for --organization
41
- WATCHFOR_BASE_URL Override (default https://watchfor.io)
46
+ WATCHFOR_BASE_URL Override (default https://watchfor.io; the origin or …/api/v1)
42
47
  `;
43
48
  function flag(args, name) {
44
49
  const i = args.indexOf(`--${name}`);
@@ -73,6 +78,10 @@ async function main() {
73
78
  process.stdout.write(HELP);
74
79
  return 0;
75
80
  }
81
+ if (cmd === "--version" || cmd === "-v" || cmd === "version") {
82
+ console.log(`watchfor ${VERSION}`);
83
+ return 0;
84
+ }
76
85
  const apiKey = process.env.WATCHFOR_API_KEY;
77
86
  if (!apiKey) {
78
87
  console.error("WATCHFOR_API_KEY is not set. Create a key in the dashboard (Settings → API keys).");
@@ -129,10 +138,14 @@ async function main() {
129
138
  return 0;
130
139
  }
131
140
  case "report": {
132
- const idx = args.indexOf("--period");
133
- const period = idx !== -1 && (args[idx + 1] === "30d" || args[idx + 1] === "7d")
134
- ? args[idx + 1]
135
- : "7d";
141
+ // An invalid --period is an error, never silently replaced (same
142
+ // as the Python and Ruby CLIs).
143
+ const given = flag(args, "period");
144
+ if (given !== undefined && given !== "7d" && given !== "30d") {
145
+ console.error(`--period must be 7d or 30d (got "${given === "true" ? "" : given}")`);
146
+ return 2;
147
+ }
148
+ const period = (given ?? "7d");
136
149
  const r = (await wf.report({ period }));
137
150
  const sm = r.summary ?? {};
138
151
  const up = sm.uptimePct?.current;
package/dist/client.d.ts CHANGED
@@ -125,6 +125,13 @@ export interface List<T> {
125
125
  next_cursor?: string | null;
126
126
  total?: number;
127
127
  }
128
+ /**
129
+ * The API origin, whichever form was given: `https://watchfor.io`,
130
+ * `https://watchfor.io/`, `https://watchfor.io/api/v1` and
131
+ * `https://watchfor.io/api/v1/` all normalise to `https://watchfor.io`
132
+ * (the client appends `/api/v1`). Exported for tests.
133
+ */
134
+ export declare function normalizeBaseUrl(baseUrl?: string): string;
128
135
  export declare class WatchForError extends Error {
129
136
  readonly status: number;
130
137
  readonly code: string;
@@ -143,7 +150,12 @@ export interface WatchForOptions {
143
150
  * or set that same id — any other id is 403 `forbidden`.
144
151
  */
145
152
  organization?: string;
146
- /** Override for self-hosted / testing. Default https://watchfor.io */
153
+ /**
154
+ * Override for self-hosted / testing. Default https://watchfor.io —
155
+ * the origin or the full API base: `https://watchfor.io` and
156
+ * `https://watchfor.io/api/v1` are the same (as in the Python and Ruby
157
+ * SDKs).
158
+ */
147
159
  baseUrl?: string;
148
160
  fetch?: typeof fetch;
149
161
  }
package/dist/client.js CHANGED
@@ -13,6 +13,20 @@
13
13
  */
14
14
  /** The request header that selects the organization an OAuth token acts on. */
15
15
  export const ORGANIZATION_HEADER = "X-WatchFor-Organization";
16
+ /**
17
+ * The API origin, whichever form was given: `https://watchfor.io`,
18
+ * `https://watchfor.io/`, `https://watchfor.io/api/v1` and
19
+ * `https://watchfor.io/api/v1/` all normalise to `https://watchfor.io`
20
+ * (the client appends `/api/v1`). Exported for tests.
21
+ */
22
+ export function normalizeBaseUrl(baseUrl) {
23
+ const trimmed = (baseUrl?.trim() || "https://watchfor.io").replace(/\/+$/, "");
24
+ return trimmed.replace(/\/api\/v1$/i, "");
25
+ }
26
+ /** A short, actionable message for a response that isn't API JSON. */
27
+ function notApiMessage(status, url) {
28
+ return `HTTP ${status} from ${url} — the response is not WatchFor API JSON. Is the base URL right? Use the origin, e.g. https://watchfor.io (WATCHFOR_BASE_URL).`;
29
+ }
16
30
  export class WatchForError extends Error {
17
31
  status;
18
32
  code;
@@ -39,7 +53,7 @@ export class WatchFor {
39
53
  this.options = opts;
40
54
  this.apiKey = opts.apiKey;
41
55
  this.organization = opts.organization?.trim() || undefined;
42
- this.base = (opts.baseUrl ?? "https://watchfor.io").replace(/\/$/, "");
56
+ this.base = normalizeBaseUrl(opts.baseUrl);
43
57
  this.fetchImpl = opts.fetch ?? fetch;
44
58
  }
45
59
  /**
@@ -78,18 +92,29 @@ export class WatchFor {
78
92
  return undefined;
79
93
  if (opts.text && res.ok)
80
94
  return (await res.text());
95
+ const raw = await res.text();
81
96
  let json = null;
82
- try {
83
- json = await res.json();
84
- }
85
- catch {
86
- /* non-JSON body */
97
+ let parsed = raw.trim() === "";
98
+ if (!parsed) {
99
+ try {
100
+ json = JSON.parse(raw);
101
+ parsed = true;
102
+ }
103
+ catch {
104
+ /* non-JSON body — an HTML page from a wrong base URL or a proxy */
105
+ }
87
106
  }
88
107
  if (!res.ok) {
89
108
  const err = json
90
109
  ?.error;
91
110
  const retry = res.headers.get("Retry-After");
92
- throw new WatchForError(res.status, err?.code ?? "http_error", err?.message ?? `HTTP ${res.status}`, retry ? Number(retry) : undefined);
111
+ throw new WatchForError(res.status, err?.code ?? "http_error", err?.message ??
112
+ (parsed
113
+ ? `HTTP ${res.status}`
114
+ : notApiMessage(res.status, url.toString())), retry ? Number(retry) : undefined);
115
+ }
116
+ if (!parsed) {
117
+ throw new WatchForError(res.status, "invalid_response", notApiMessage(res.status, url.toString()));
93
118
  }
94
119
  return json;
95
120
  }
package/dist/schema.d.ts CHANGED
@@ -398,7 +398,10 @@ export interface paths {
398
398
  };
399
399
  get?: never;
400
400
  put?: never;
401
- /** Dispatch one immediate check (plan-budgeted per hour) */
401
+ /**
402
+ * Dispatch one immediate check (plan-budgeted per hour)
403
+ * @description Asynchronous: 202, and the result lands in GET /monitors/{id}/checks within the probe timeout. Budgeted per monitor by the plan's check-now allowance (shared with the dashboard). Over that budget → 429 `rate_limited` whose `error.next_allowed_at` (and `Retry-After`) say when the next check-now is allowed — distinct from the API rate limit the X-RateLimit-* headers describe. Send an `Idempotency-Key` to retry safely: a retry with the same key replays the original 202 (with `Idempotency-Replay: true`) instead of spending, or being refused by, the hourly budget.
404
+ */
402
405
  post: operations["runMonitorCheckNow"];
403
406
  delete?: never;
404
407
  options?: never;
@@ -1862,6 +1865,10 @@ export interface components {
1862
1865
  object: "playwright_run";
1863
1866
  /** Format: uuid */
1864
1867
  run_id: string;
1868
+ /**
1869
+ * Format: date-time
1870
+ * @description When the run happened — RFC 3339 / ISO 8601 UTC, e.g. 2026-10-17T14:31:29.000Z
1871
+ */
1865
1872
  timestamp?: string;
1866
1873
  location?: string;
1867
1874
  /** @enum {string} */
@@ -1891,6 +1898,10 @@ export interface components {
1891
1898
  object: "playwright_run";
1892
1899
  /** Format: uuid */
1893
1900
  run_id: string;
1901
+ /**
1902
+ * Format: date-time
1903
+ * @description When the run happened — RFC 3339 / ISO 8601 UTC, e.g. 2026-10-17T14:31:29.000Z
1904
+ */
1894
1905
  timestamp: string;
1895
1906
  status: string;
1896
1907
  duration_ms?: number;
@@ -2171,8 +2182,9 @@ export interface components {
2171
2182
  | "ntp-test"
2172
2183
  | "email-health";
2173
2184
  target: string;
2174
- /** @description Whether the check itself succeeded. false is a normal, billable answer (e.g. a closed port, NXDOMAIN, a failed handshake) — read `error` for what happened. */
2185
+ /** @description Whether the check itself succeeded — the finding, not the transport. false is a normal, billable answer: a closed port, an NXDOMAIN, an expired or untrusted certificate, a host that doesn't resolve, a failed handshake, or a target the prober refuses (an internal address). Read `error` for what happened; `result` keeps the probe's raw answer. */
2175
2186
  success: boolean;
2187
+ /** @description Readable reason when `success` is false (e.g. "No records found (NXDOMAIN)", "The certificate … has expired"); null when the check succeeded. */
2176
2188
  error: string | null;
2177
2189
  location: components["schemas"]["DiagnosticLocation"];
2178
2190
  duration_ms: number;
@@ -2219,7 +2231,10 @@ export interface components {
2219
2231
  | "ntp-test"
2220
2232
  | "email-health";
2221
2233
  label: string;
2222
- /** @enum {string} */
2234
+ /**
2235
+ * @description ok = the check ran and answered (read `success` for what it found); failed = it could not run or the probe did not answer; skipped = see `reason`.
2236
+ * @enum {string}
2237
+ */
2223
2238
  status: "ok" | "failed" | "skipped";
2224
2239
  /**
2225
2240
  * @description Why the check was skipped, when it was.
@@ -2229,6 +2244,7 @@ export interface components {
2229
2244
  detail?: string;
2230
2245
  location?: components["schemas"]["DiagnosticLocation"];
2231
2246
  duration_ms?: number | null;
2247
+ /** @description Whether the check succeeded (same meaning as DiagnosticRun.success); null when skipped. */
2232
2248
  success?: boolean | null;
2233
2249
  error?: string | null;
2234
2250
  result?: unknown;
@@ -2398,6 +2414,8 @@ export interface components {
2398
2414
  } | null;
2399
2415
  /** @description PATCH /monitors/{id} responses only: true when the update changed how the check connects (target, port, credentials, TLS, request, record type, script…) and one immediate check was dispatched, so the result reflects the new settings within seconds instead of after a full interval. It does not use the plan's Run-now budget; saves are capped at 10 such checks per monitor per hour. false for alert-rule-only or cosmetic changes and for paused, heartbeat and host monitors. */
2400
2416
  check_queued?: boolean;
2417
+ /** @description POST /monitors and PATCH /monitors/{id} responses only: the `config` keys you sent that this monitor type doesn't use — dropped, not stored ([] when everything was kept). Check it after every write: a misspelt key otherwise leaves the setting unset. Obvious aliases are renamed instead of dropped: `login` / `user` → `username` and `pass` → `password` on imap, pop3, smtp, ftp and sftp; `username` / `login` / `user` → `authUsername` and `password` / `pass` → `authPassword` on http and api; a snake_case spelling of a camelCase key (`timeout_seconds` → `timeoutSeconds`) on every type. Config keys per type: GET /meta/monitor-types. */
2418
+ ignored_config_keys?: string[];
2401
2419
  /** @description The open (firing or acknowledged) incident, or null. When several are open: the critical one, then the earliest started. */
2402
2420
  current_incident?: components["schemas"]["MonitorCurrentIncident"] | null;
2403
2421
  /** @description A silence (dashboard Mute) suppresses notifications; incidents still open and close and checks continue. */
@@ -2472,6 +2490,7 @@ export interface components {
2472
2490
  latest?: components["schemas"]["MonitorLatest"] | null;
2473
2491
  available_metrics: components["schemas"]["CatalogAlertMetric"][];
2474
2492
  };
2493
+ /** @description Unknown top-level fields are rejected with 400 naming the accepted ones (like PATCH) — type-specific settings go in `config`. */
2475
2494
  MonitorCreate: {
2476
2495
  name: string;
2477
2496
  /**
@@ -2509,7 +2528,7 @@ export interface components {
2509
2528
  | "imap"
2510
2529
  | "pop3"
2511
2530
  | "email_roundtrip";
2512
- /** @description Format per type (see GET /meta/monitor-types). Targets in private, loopback, link-local or cloud-metadata address space (and internal hostnames such as localhost, *.internal) are rejected with 400. */
2531
+ /** @description Format per type (see GET /meta/monitor-types). Targets in private, loopback, link-local or cloud-metadata address space (and internal hostnames such as localhost, *.internal) are rejected with 400. heartbeat: the server assigns the ping path — send any placeholder (or omit target); read ping_url from the response. smtp: hostname only, the port goes in config.port. */
2513
2532
  target: string;
2514
2533
  /** @description Seconds; validated against the plan's per-type minimum */
2515
2534
  interval: number;
@@ -2524,7 +2543,7 @@ export interface components {
2524
2543
  /** @description Lowercase alphanumeric with hyphens or colons, e.g. prod, team:web */
2525
2544
  tags?: string[];
2526
2545
  description?: string | null;
2527
- /** @description Type-specific settings — the keys and types are listed per type under config_fields in GET /meta/monitor-types. Validated against the monitor type: a wrong value returns 400 naming the field (e.g. `config.timeoutSeconds`); keys the type does not use are dropped. Config that drives an alert preset (dns expectedValues, cdn expectedProvider, cms expectedCms, tcp/udp expectMatchRegexp, websocket expectPattern, mcp expectedProtocolVersion, http failIfBody*Regexp) also creates that preset's alert rule. Credential keys (marked secret in the catalog: password, smtpPassword, receivePassword, privateKey, …) are write-only and stored encrypted; responses return them as "[redacted]". */
2546
+ /** @description Type-specific settings — the keys and types are listed per type under config_fields in GET /meta/monitor-types. Validated against the monitor type: a wrong value returns 400 naming the field (e.g. `config.timeoutSeconds`); keys the type does not use are dropped and listed in the response's `ignored_config_keys` (obvious aliases such as `login` → `username` are renamed instead). Config that drives an alert preset (dns expectedValues, cdn expectedProvider, cms expectedCms, tcp/udp expectMatchRegexp, websocket expectPattern, mcp expectedProtocolVersion, http failIfBody*Regexp) also creates that preset's alert rule. Credential keys (marked secret in the catalog: password, smtpPassword, receivePassword, privateKey, …) are write-only and stored encrypted; responses return them as "[redacted]". */
2528
2547
  config?: {
2529
2548
  [key: string]: unknown;
2530
2549
  };
@@ -2586,6 +2605,10 @@ export interface components {
2586
2605
  min_response_time_ms?: number | null;
2587
2606
  /** @description Latency over successful checks only (a failed check has no response time); null when no check succeeded */
2588
2607
  max_response_time_ms?: number | null;
2608
+ /**
2609
+ * Format: date-time
2610
+ * @description The newest failed check in the window (RFC 3339 / ISO 8601 UTC); null when none failed
2611
+ */
2589
2612
  last_failure_at?: string | null;
2590
2613
  /** @description Incident-based headline uptime for the last 24 hours */
2591
2614
  uptime_24h?: number | null;
@@ -2622,6 +2645,10 @@ export interface components {
2622
2645
  object?: "check";
2623
2646
  /** @description Addresses this exact probe run */
2624
2647
  run_id?: string;
2648
+ /**
2649
+ * Format: date-time
2650
+ * @description When the check ran — RFC 3339 / ISO 8601 UTC, e.g. 2026-10-17T14:31:29.000Z
2651
+ */
2625
2652
  timestamp?: string;
2626
2653
  success?: boolean;
2627
2654
  duration_ms?: number;
@@ -2660,6 +2687,10 @@ export interface components {
2660
2687
  run_id?: string;
2661
2688
  /** Format: uuid */
2662
2689
  monitor_id?: string;
2690
+ /**
2691
+ * Format: date-time
2692
+ * @description When the check ran — RFC 3339 / ISO 8601 UTC, e.g. 2026-10-17T14:31:29.000Z
2693
+ */
2663
2694
  timestamp?: string;
2664
2695
  location?: string;
2665
2696
  target?: string;
@@ -3547,7 +3578,14 @@ export interface components {
3547
3578
  name?: string;
3548
3579
  /** @description -1 = unlimited, 0 = feature disabled */
3549
3580
  limits?: Record<string, never> | null;
3550
- usage?: Record<string, never>;
3581
+ /** @description Live usage. `monitors_by_type` counts monitors per type and matches `limits.max_monitors_by_type` (`browser` = page-speed / Core Web Vitals monitors, `playwright` = scripted browser checks). `browser_checks` is kept for compatibility and equals the playwright count. */
3582
+ usage?: {
3583
+ monitors_by_type?: {
3584
+ [key: string]: number;
3585
+ };
3586
+ /** @description Playwright (scripted browser check) monitors */
3587
+ browser_checks?: number;
3588
+ };
3551
3589
  };
3552
3590
  Notification: {
3553
3591
  id?: number;
@@ -3589,7 +3627,8 @@ export interface components {
3589
3627
  /** @description Current display name of the entity (from the create/delete snapshot when it no longer exists) */
3590
3628
  entity_name?: string | null;
3591
3629
  action?: string;
3592
- changes?: Record<string, never>;
3630
+ /** @description What changed, as recorded with the event (e.g. {field: {from, to}} for updates, a snapshot for creates/deletes); null for events that record no details (post-mortem created/deleted/completed, incident acknowledged…) */
3631
+ changes?: Record<string, never> | null;
3593
3632
  actor?: {
3594
3633
  name?: string | null;
3595
3634
  email?: string | null;
@@ -3830,7 +3869,12 @@ export interface components {
3830
3869
  toMs?: number;
3831
3870
  label?: string;
3832
3871
  };
3833
- previousPeriod?: Record<string, never>;
3872
+ /** @description The equal-length period before `period` that compared values are measured against */
3873
+ previousPeriod?: {
3874
+ fromMs?: number;
3875
+ toMs?: number;
3876
+ label?: string;
3877
+ };
3834
3878
  /** @enum {string} */
3835
3879
  depth?: "basic" | "advanced";
3836
3880
  typesPresent?: string[];
@@ -3844,8 +3888,9 @@ export interface components {
3844
3888
  monitorId?: string;
3845
3889
  name?: string;
3846
3890
  type?: string;
3891
+ target?: string;
3847
3892
  /** @description Incident-based, same formula as the monitor's Uptime card */
3848
- uptimePct?: Record<string, never>;
3893
+ uptimePct?: components["schemas"]["ReportCompared"];
3849
3894
  downtimeMs?: number;
3850
3895
  /** @description Reachability, not health: share of this monitor's checks that reached the target and got a response; null when the period has no checks */
3851
3896
  checkSuccessPct?: number | null;
@@ -3877,6 +3922,14 @@ export interface components {
3877
3922
  /** @description Insights withheld beyond the plan's cap (0 on advanced depth) */
3878
3923
  gatedInsightCount?: number;
3879
3924
  };
3925
+ /** @description A report value paired with its previous-period counterpart */
3926
+ ReportCompared: {
3927
+ current: number;
3928
+ /** @description null when the previous period has no data */
3929
+ previous: number | null;
3930
+ /** @description current - previous; null when no baseline */
3931
+ delta: number | null;
3932
+ };
3880
3933
  /** @description name/email are null for a member who has since left the organization */
3881
3934
  OncallPerson: {
3882
3935
  id?: string;
@@ -4239,7 +4292,7 @@ export interface components {
4239
4292
  DiagnosticOptionsCdnCheck: Record<string, never>;
4240
4293
  /** @description Options for the `sitemap-check` diagnostic. Does this domain publish a valid sitemap, is it reachable from robots.txt, and do its URLs resolve? */
4241
4294
  DiagnosticOptionsSitemapCheck: Record<string, never>;
4242
- /** @description Options for the `brotli-check` diagnostic. Does this domain serve Brotli or gzip compression, and how much bandwidth is it saving? */
4295
+ /** @description Options for the `brotli-check` diagnostic. Does this domain serve Brotli and gzip compression — which Content-Encoding comes back when a client offers only br, and when it offers only gzip? */
4243
4296
  DiagnosticOptionsBrotliCheck: Record<string, never>;
4244
4297
  /** @description Options for the `redirect-chain` diagnostic. Where does this URL end up — every redirect hop with its status code and Location, the final URL, and whether the chain is longer, slower or less secure than it should be? */
4245
4298
  DiagnosticOptionsRedirectChain: {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "watchfor",
3
- "version": "0.17.1",
3
+ "version": "0.17.2",
4
4
  "description": "Official TypeScript SDK + CLI for WatchFor — uptime & infrastructure monitoring (monitors, alert rules, incidents, maintenance windows) over the REST API.",
5
5
  "keywords": [
6
6
  "watchfor",