watchfor 0.14.0 → 0.15.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/README.md CHANGED
@@ -61,6 +61,24 @@ if (page.next_cursor) {
61
61
 
62
62
  // Delete a contact group that alert rules still use (409 without force).
63
63
  await wf.contactGroups.delete("<group-id>", { force: true });
64
+
65
+ // What the alerting engine sees right now: alerted, recovering 1/3, confirming 2 of 3…
66
+ const { alerting_state } = await wf.monitors.get(monitor.id!);
67
+
68
+ // Response times on a real time axis (5-min buckets for 24h, 15 min for 7d).
69
+ const uptime = await wf.monitors.uptime(monitor.id!, "24h", { series: true });
70
+ for (const b of uptime.response_time_series ?? []) console.log(b.at, b.avg_ms);
71
+
72
+ // Pause up to 100 monitors at once; post a status-page announcement.
73
+ await wf.monitors.bulk("pause", ["<id-1>", "<id-2>"]);
74
+ const notice = await wf.statusPages.createAnnouncement("<page-id>", {
75
+ title: "Checkout errors",
76
+ body: "We are looking into failed payments.",
77
+ });
78
+ await wf.statusPages.updateAnnouncement("<page-id>", notice.id!, {
79
+ body: "Fixed.",
80
+ status: "resolved",
81
+ });
64
82
  ```
65
83
 
66
84
  ### Live diagnostics
@@ -112,6 +130,32 @@ Toolbox. Details: https://watchfor.io/docs/api/diagnostics
112
130
  - `WatchForError` carries `status`, `code` and `retryAfterSeconds`
113
131
  - Pass an idempotency key as the second argument of any `create` call for safe retries
114
132
 
133
+ ## Organizations
134
+
135
+ An API key belongs to one organization. An **OAuth access token** acts as
136
+ the user who approved it, so it reaches every organization that user
137
+ belongs to; choose one with `organization` — the SDK sends it as the
138
+ `X-WatchFor-Organization` header on every request:
139
+
140
+ ```ts
141
+ const acme = new WatchFor({ apiKey: oauthAccessToken, organization: "<organization-id>" });
142
+ await acme.me(); // { organization: { id, name, slug }, scope }
143
+ const other = acme.withOrganization("<another-organization-id>"); // new client, same token
144
+ await other.monitors.list();
145
+ ```
146
+
147
+ - Without `organization`, an OAuth token acts on the user's oldest owned
148
+ organization (else their oldest membership).
149
+ - The user must be a member of that organization (otherwise `403
150
+ forbidden`), and their role there applies: members read, acknowledge
151
+ incidents and run diagnostics; changes need owner or admin.
152
+ - With an API key leave it unset; it may only repeat the key's own
153
+ organization id, and any other id is `403 forbidden` (a key never
154
+ switches organization).
155
+ - `withOrganization(null)` drops the header again.
156
+
157
+ Details: https://watchfor.io/docs/api/authentication#how-oauth-maps-to-your-data
158
+
115
159
  ## Prometheus metrics (Pro plan and above)
116
160
 
117
161
  ```ts
@@ -129,6 +173,12 @@ npx watchfor incidents --status firing
129
173
  npx watchfor monitors example.com
130
174
  npx watchfor checks <monitor-id> --failed # add --cursor <next_cursor> for older pages
131
175
  npx watchfor report --period 30d
176
+ npx watchfor me # which organization + scope
177
+
178
+ # OAuth token: pick the organization per call or via the environment
179
+ export WATCHFOR_API_KEY=<oauth-access-token>
180
+ npx watchfor --organization <organization-id> monitors
181
+ WATCHFOR_ORGANIZATION=<organization-id> npx watchfor summary
132
182
  ```
133
183
 
134
184
  ## Links
package/dist/cli.js CHANGED
@@ -8,10 +8,15 @@ import { WatchFor, WatchForError } from "./client.js";
8
8
  * watchfor incidents --status firing
9
9
  * watchfor monitors [search]
10
10
  * watchfor checks <monitor-id> --failed
11
+ * watchfor --organization <org-id> monitors (OAuth tokens)
11
12
  */
12
13
  const HELP = `watchfor — WatchFor monitoring CLI (https://watchfor.io)
13
14
 
14
15
  Usage:
16
+ watchfor [--organization <id>] <command> [options]
17
+
18
+ Commands:
19
+ watchfor me Which organization and scope the credential acts with
15
20
  watchfor summary Org snapshot: what's up/down right now
16
21
  watchfor incidents [--status s] List incidents (firing|acknowledged|resolved)
17
22
  watchfor monitors [query] List monitors (optional name/target search)
@@ -23,9 +28,15 @@ Usage:
23
28
  Prometheus text format (Pro plan and above)
24
29
  watchfor help
25
30
 
31
+ Global options:
32
+ --organization <id> Organization to act on (X-WatchFor-Organization). OAuth
33
+ tokens reach every organization their user belongs to;
34
+ an API key only accepts its own organization's id.
35
+
26
36
  Environment:
27
- WATCHFOR_API_KEY API key (dashboard → Settings → API keys)
28
- WATCHFOR_BASE_URL Override (default https://watchfor.io)
37
+ WATCHFOR_API_KEY API key (dashboard → Settings → API keys) or an OAuth access token
38
+ WATCHFOR_ORGANIZATION Default for --organization
39
+ WATCHFOR_BASE_URL Override (default https://watchfor.io)
29
40
  `;
30
41
  function flag(args, name) {
31
42
  const i = args.indexOf(`--${name}`);
@@ -33,8 +44,29 @@ function flag(args, name) {
33
44
  return undefined;
34
45
  return args[i + 1] && !args[i + 1].startsWith("--") ? args[i + 1] : "true";
35
46
  }
47
+ /** Removes a global `--name <value>` / `--name=<value>` from argv, wherever
48
+ * it appears, and returns its value. */
49
+ function takeGlobal(argv, name) {
50
+ let value;
51
+ for (let i = 0; i < argv.length; i++) {
52
+ const a = argv[i];
53
+ if (a === `--${name}`) {
54
+ value = argv[i + 1] ?? "";
55
+ argv.splice(i, 2);
56
+ i--;
57
+ }
58
+ else if (a.startsWith(`--${name}=`)) {
59
+ value = a.slice(name.length + 3);
60
+ argv.splice(i, 1);
61
+ i--;
62
+ }
63
+ }
64
+ return value;
65
+ }
36
66
  async function main() {
37
- const [cmd, ...args] = process.argv.slice(2);
67
+ const argv = process.argv.slice(2);
68
+ const organizationFlag = takeGlobal(argv, "organization");
69
+ const [cmd, ...args] = argv;
38
70
  if (!cmd || cmd === "help" || cmd === "--help" || cmd === "-h") {
39
71
  process.stdout.write(HELP);
40
72
  return 0;
@@ -44,11 +76,23 @@ async function main() {
44
76
  console.error("WATCHFOR_API_KEY is not set. Create a key in the dashboard (Settings → API keys).");
45
77
  return 1;
46
78
  }
79
+ const organization = organizationFlag ?? process.env.WATCHFOR_ORGANIZATION ?? undefined;
80
+ if (organizationFlag !== undefined && !organizationFlag.trim()) {
81
+ console.error("--organization needs an organization id");
82
+ return 1;
83
+ }
47
84
  const wf = new WatchFor({
48
85
  apiKey,
86
+ organization,
49
87
  baseUrl: process.env.WATCHFOR_BASE_URL,
50
88
  });
51
89
  switch (cmd) {
90
+ case "me": {
91
+ const me = await wf.me();
92
+ const org = me.organization;
93
+ console.log(`organization: ${org ? `${org.name} (${org.id})` : "none"} · scope ${me.scope ?? "?"}`);
94
+ return 0;
95
+ }
52
96
  case "summary": {
53
97
  const s = await wf.summary();
54
98
  const m = s.monitors;
package/dist/client.d.ts CHANGED
@@ -5,16 +5,29 @@ import type { components } from "./schema.js";
5
5
  *
6
6
  * const wf = new WatchFor({ apiKey: process.env.WATCHFOR_API_KEY! });
7
7
  * const summary = await wf.summary();
8
+ *
9
+ * An OAuth access token reaches every organization its user belongs to;
10
+ * pick one with `organization` (sent as `X-WatchFor-Organization`):
11
+ *
12
+ * const acme = new WatchFor({ apiKey: oauthToken, organization: "<org id>" });
13
+ * const other = acme.withOrganization("<another org id>");
8
14
  */
15
+ /** The request header that selects the organization an OAuth token acts on. */
16
+ export declare const ORGANIZATION_HEADER = "X-WatchFor-Organization";
9
17
  export type Monitor = components["schemas"]["Monitor"];
10
- /** Monitor + `available_metrics` (GET /monitors/{id} only). */
18
+ /** Monitor + `available_metrics` and `alerting_state` — what the alerting
19
+ * engine sees right now (GET /monitors/{id} only). */
11
20
  export type MonitorDetail = components["schemas"]["MonitorDetail"];
21
+ /** `alerting_state` of a monitor detail: alerted / recovering (n of m) /
22
+ * failing below the confirmation threshold (confirming n of m), or null. */
23
+ export type AlertingState = NonNullable<Monitor["alerting_state"]>;
24
+ /** Result of `monitors.bulk()` — which ids were acted on, which skipped. */
25
+ export type BulkResult = components["schemas"]["BulkResult"];
12
26
  export type MonitorReset = components["schemas"]["MonitorReset"];
13
27
  export type IntegrityBaseline = components["schemas"]["IntegrityBaseline"];
14
28
  export type IntegrityBaselineAccept = components["schemas"]["IntegrityBaselineAccept"];
15
29
  /** A fresh accept whose check has not landed yet (HTTP 202). */
16
30
  export type IntegrityBaselineAcceptPending = components["schemas"]["IntegrityBaselineAcceptPending"];
17
- export type PlaywrightTestRunRequest = components["schemas"]["PlaywrightTestRunRequest"];
18
31
  export type PlaywrightTestRunAccepted = components["schemas"]["PlaywrightTestRunAccepted"];
19
32
  export type PlaywrightTestRun = components["schemas"]["PlaywrightTestRun"];
20
33
  export type PlaywrightRun = components["schemas"]["PlaywrightRun"];
@@ -28,15 +41,51 @@ export type AlertRule = components["schemas"]["AlertRule"];
28
41
  export type Contact = components["schemas"]["Contact"];
29
42
  export type ContactGroup = components["schemas"]["ContactGroup"];
30
43
  export type MaintenanceWindow = components["schemas"]["MaintenanceWindow"];
44
+ /** `incidents.markMaintenance()` — the window that now covers the outage. */
45
+ export interface MaintenanceMarking {
46
+ object: "maintenance_marking";
47
+ incident_id: number;
48
+ maintenance_window: MaintenanceWindow;
49
+ }
31
50
  export type Host = components["schemas"]["Host"];
32
51
  export type HostMetrics = components["schemas"]["HostMetrics"];
33
52
  export type StatusPage = components["schemas"]["StatusPage"];
53
+ /** Request bodies: fields the server defaults may be left out (the
54
+ * generated types mark every defaulted field as required). */
55
+ type Defaulted<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;
56
+ type RawStatusPageCreate = components["schemas"]["StatusPageCreate"];
57
+ /** A status-page component — `monitorIds` / `monitorTags` default to []. */
58
+ export type StatusPageComponentCreate = Defaulted<RawStatusPageCreate["components"][number], "monitorIds" | "monitorTags">;
59
+ export type StatusPageCreate = Defaulted<Omit<RawStatusPageCreate, "components">, "isPublic" | "autoPublishIncidents" | "dimUntrackedDays" | "theme"> & {
60
+ components?: StatusPageComponentCreate[];
61
+ };
62
+ export type StatusPageUpdate = components["schemas"]["StatusPageUpdate"];
63
+ export type Announcement = components["schemas"]["Announcement"];
64
+ /** `retry` defaults on the server, so it may be left out. */
65
+ export type PlaywrightTestRunRequest = Defaulted<components["schemas"]["PlaywrightTestRunRequest"], "retry">;
66
+ export type AnnouncementCreate = Defaulted<components["schemas"]["AnnouncementCreate"], "status" | "severity" | "affectedComponentIds">;
67
+ export type AnnouncementUpdate = components["schemas"]["AnnouncementUpdate"];
68
+ /** Uptime stats; with `series: true` also `response_time_series` and
69
+ * `series_bucket_seconds` (periods up to 7d). */
34
70
  export type Uptime = components["schemas"]["Uptime"];
71
+ /** One bucket of `Uptime.response_time_series`. */
72
+ export type ResponseTimeBucket = NonNullable<Uptime["response_time_series"]>[number];
35
73
  export type Check = components["schemas"]["Check"];
36
74
  export type CheckList = components["schemas"]["CheckList"];
37
75
  export type CheckNowAck = components["schemas"]["CheckNowAck"];
38
76
  export type Plan = components["schemas"]["Plan"];
39
77
  export type Summary = components["schemas"]["Summary"];
78
+ /** The credential's identity: scope + the organization it acts on. */
79
+ export type Me = components["schemas"]["Me"];
80
+ /** `batch()` results, in request order: `{ status, body }` per operation. */
81
+ export type BatchResult = components["schemas"]["BatchResult"];
82
+ /** One operation of a `batch()` call — a relative /api/v1 path. */
83
+ export interface BatchOperation {
84
+ method: "GET" | "POST" | "PATCH" | "PUT" | "DELETE";
85
+ /** Relative /api/v1 sub-path, e.g. `/monitors/{id}`. */
86
+ path: string;
87
+ body?: Record<string, unknown>;
88
+ }
40
89
  export type IncidentStats = components["schemas"]["IncidentStats"];
41
90
  export type ActivityEvent = components["schemas"]["ActivityEvent"];
42
91
  export type Notification = components["schemas"]["Notification"];
@@ -72,20 +121,68 @@ export declare class WatchForError extends Error {
72
121
  constructor(status: number, code: string, message: string, retryAfterSeconds?: number);
73
122
  }
74
123
  export interface WatchForOptions {
75
- /** API key (wf_live_…) — dashboard Settings → API keys. */
124
+ /** API key (wf_live_…, dashboard Settings → API keys) or an OAuth
125
+ * access token. */
76
126
  apiKey: string;
127
+ /**
128
+ * Organization id to act on, sent as `X-WatchFor-Organization`. For
129
+ * OAuth tokens, which reach every organization their user belongs to
130
+ * (omitted: the user's oldest owned organization, else their oldest
131
+ * membership). An API key belongs to one organization: leave it unset,
132
+ * or set that same id — any other id is 403 `forbidden`.
133
+ */
134
+ organization?: string;
77
135
  /** Override for self-hosted / testing. Default https://watchfor.io */
78
136
  baseUrl?: string;
79
137
  fetch?: typeof fetch;
80
138
  }
139
+ /** Optional scoping/shape filters of `report()`; lists may be arrays or
140
+ * comma-separated strings. */
141
+ export interface ReportFilters {
142
+ /** Scope to these monitors (union with `tags`). */
143
+ monitor_ids?: string | string[];
144
+ /** Scope to monitors carrying these tags. */
145
+ tags?: string | string[];
146
+ /** Subset of type-aware sections: locations, ssl, domains, cwv,
147
+ * heartbeat, blacklist, mcp, hosts (omit for all). */
148
+ sections?: string | string[];
149
+ /** false drops the response-time block. */
150
+ response_time?: boolean;
151
+ /** false drops the per-monitor table. */
152
+ monitors_table?: boolean;
153
+ /** false drops the insights block. */
154
+ insights?: boolean;
155
+ /** Incident aggregates only over these states: acknowledged, resolved,
156
+ * open (or all). */
157
+ incident_status?: string | string[];
158
+ }
81
159
  export declare class WatchFor {
160
+ /** The organization id this client sends, or undefined (the
161
+ * credential's default organization). */
162
+ readonly organization: string | undefined;
163
+ private readonly options;
82
164
  private readonly apiKey;
83
165
  private readonly base;
84
166
  private readonly fetchImpl;
85
167
  constructor(opts: WatchForOptions);
168
+ /**
169
+ * A new client acting on another organization (same credential and
170
+ * settings); `null` drops the header so the credential's default
171
+ * organization applies. This client is left unchanged.
172
+ */
173
+ withOrganization(organization: string | null): WatchFor;
86
174
  private request;
87
- /** Current API key + organization. */
88
- me(): Promise<unknown>;
175
+ /** The credential's scope and the organization it acts on — with an
176
+ * OAuth token, the one `organization` selected. */
177
+ me(): Promise<Me>;
178
+ /**
179
+ * Run up to 20 operations in one request. Each runs against /api/v1 with
180
+ * the same credential and organization, so scopes, validation and rate
181
+ * limits apply per operation; results come back in request order.
182
+ */
183
+ batch(operations: BatchOperation[]): Promise<BatchResult>;
184
+ /** The OpenAPI 3.1 document this client is built from (no key needed). */
185
+ openApiSpec(): Promise<Record<string, unknown>>;
89
186
  /** One-call org snapshot: monitor status counts + active incidents. */
90
187
  summary(): Promise<Summary>;
91
188
  /**
@@ -108,14 +205,15 @@ export declare class WatchFor {
108
205
  * Org report for a period vs the previous one: uptime, incidents,
109
206
  * MTTR/MTBF, response-time trend, per-monitor rows, type-aware
110
207
  * sections and plain-language insights. Custom from/to (ISO 8601)
111
- * needs the advanced-reports plan capability.
208
+ * needs the advanced-reports plan capability, as do the scoping
209
+ * filters (`monitor_ids`, `tags`, `sections`, `incident_status`).
112
210
  */
113
- report(opts?: {
211
+ report(opts?: ({
114
212
  period?: "7d" | "30d";
115
213
  } | {
116
214
  from: string | Date;
117
215
  to: string | Date;
118
- }): Promise<Record<string, unknown>>;
216
+ }) & ReportFilters): Promise<Record<string, unknown>>;
119
217
  /** The org's two report-email cadences (weekly + monthly). */
120
218
  reportSchedules(): Promise<List<Record<string, unknown>>>;
121
219
  /**
@@ -141,8 +239,13 @@ export declare class WatchFor {
141
239
  cursor?: string;
142
240
  }) => Promise<List<Monitor>>;
143
241
  /** The monitor plus `available_metrics` — the alert metrics valid for
144
- * its type. */
242
+ * its type — and `alerting_state`: what the alerting engine sees right
243
+ * now (alerted, recovering n of m, failing/confirming n of m; null
244
+ * when every rule is healthy). */
145
245
  get: (id: string) => Promise<MonitorDetail>;
246
+ /** Pause, resume or delete up to 100 monitors in one call; ids that
247
+ * are not yours or need no change come back in `skipped`. */
248
+ bulk: (action: "pause" | "resume" | "delete", ids: string[], idempotencyKey?: string) => Promise<BulkResult>;
146
249
  /** Create a monitor; `config` keys per type come from `monitorTypes()`.
147
250
  * Credentials (catalog fields marked `secret` — mailbox/SMTP/FTP
148
251
  * passwords, SSH keys, HTTP/API/MCP auth passwords and bearer
@@ -154,7 +257,9 @@ export declare class WatchFor {
154
257
  * removes). A `"[redacted]"` credential is kept when omitted or sent
155
258
  * back unchanged; changing the server, port, TLS mode or login it is
156
259
  * used with (HTTP: the URL's host, port or scheme) needs it again in
157
- * the same call (else 400). */
260
+ * the same call (else 400). `check_queued: true` in the result means
261
+ * the change (target, port, credentials, TLS, request…) dispatched one
262
+ * immediate check, outside the Run-now budget. */
158
263
  update: (id: string, body: Record<string, unknown>) => Promise<Monitor>;
159
264
  delete: (id: string) => Promise<Deleted>;
160
265
  pause: (id: string) => Promise<Monitor>;
@@ -201,7 +306,13 @@ export declare class WatchFor {
201
306
  data: ScriptVersionSummary[];
202
307
  }>;
203
308
  scriptVersion: (id: string, version: number) => Promise<ScriptVersion>;
204
- uptime: (id: string, period?: "1h" | "24h" | "7d" | "30d" | "90d") => Promise<Uptime>;
309
+ /** Uptime (confirmed critical incidents only), check success and
310
+ * response-time stats. `series: true` (periods up to 7d) adds
311
+ * `response_time_series` — buckets of `series_bucket_seconds` (300
312
+ * for 24h, 900 for 7d) on a real time axis, oldest first. */
313
+ uptime: (id: string, period?: "1h" | "24h" | "7d" | "30d" | "90d", opts?: {
314
+ series?: boolean;
315
+ }) => Promise<Uptime>;
205
316
  /** Recent probe results, newest first. Page with `next_cursor` →
206
317
  * `cursor` (keep the same `hours`/`success`); `locations` is the
207
318
  * per-location breakdown for the whole window. */
@@ -211,9 +322,11 @@ export declare class WatchFor {
211
322
  success?: boolean;
212
323
  cursor?: string;
213
324
  }) => Promise<CheckList>;
325
+ /** One probe run in full, redacted server-side — run_id from checks(). */
326
+ checkDetail: (id: string, runId: string) => Promise<Record<string, unknown>>;
214
327
  };
215
328
  readonly alertRules: {
216
- /** One probe run in full, redacted server-side — run_id from checks(). */
329
+ /** @deprecated Use `monitors.checkDetail()` — same call. */
217
330
  checkDetail: (id: string, runId: string) => Promise<Record<string, unknown>>;
218
331
  list: (monitorId: string) => Promise<List<AlertRule>>;
219
332
  get: (monitorId: string, ruleId: string) => Promise<AlertRule>;
@@ -267,6 +380,11 @@ export declare class WatchFor {
267
380
  }) => Promise<Incident>;
268
381
  /** Undo `exclude` — the incident counts as downtime again. */
269
382
  include: (id: number) => Promise<Incident>;
383
+ /** Retroactively count a RESOLVED incident as planned maintenance: it
384
+ * leaves uptime and SLA. Returns the maintenance window recorded for
385
+ * it (marking again returns the same one); delete that window to
386
+ * undo. */
387
+ markMaintenance: (id: number, idempotencyKey?: string) => Promise<MaintenanceMarking>;
270
388
  };
271
389
  readonly statusPages: {
272
390
  list: (q?: {
@@ -274,10 +392,26 @@ export declare class WatchFor {
274
392
  cursor?: string;
275
393
  }) => Promise<List<StatusPage>>;
276
394
  get: (id: string) => Promise<StatusPage>;
395
+ /** Create a page, optionally with components. Password protection,
396
+ * logo upload and custom subdomains are dashboard-only. */
397
+ create: (body: StatusPageCreate, idempotencyKey?: string) => Promise<StatusPage>;
398
+ /** Partial update; a slug change frees the old URL at once. */
399
+ update: (id: string, body: StatusPageUpdate) => Promise<StatusPage>;
400
+ delete: (id: string) => Promise<Deleted>;
401
+ /** Announcements, newest first. */
277
402
  announcements: (id: string, q?: {
278
403
  limit?: number;
279
404
  cursor?: string;
280
- }) => Promise<List<Record<string, unknown>>>;
405
+ }) => Promise<List<Announcement>>;
406
+ getAnnouncement: (id: string, announcementId: string) => Promise<Announcement>;
407
+ /** Publish an incident notice; `body` becomes the first timeline
408
+ * entry. */
409
+ createAnnouncement: (id: string, body: AnnouncementCreate, idempotencyKey?: string) => Promise<Announcement>;
410
+ /** Post an update: appends to the public timeline and moves the
411
+ * status; `resolved` closes it. */
412
+ updateAnnouncement: (id: string, announcementId: string, body: AnnouncementUpdate) => Promise<Announcement>;
413
+ /** Remove from the public page (soft delete). */
414
+ deleteAnnouncement: (id: string, announcementId: string) => Promise<Deleted>;
281
415
  };
282
416
  readonly onCall: {
283
417
  get: () => Promise<Record<string, unknown>>;
@@ -300,9 +434,11 @@ export declare class WatchFor {
300
434
  metrics: (id: string, metrics: string[], range?: "1h" | "6h" | "24h" | "7d" | "30d") => Promise<HostMetrics>;
301
435
  };
302
436
  readonly maintenanceWindows: {
437
+ /** `state` keeps only live windows (active now / upcoming). */
303
438
  list: (q?: {
304
439
  limit?: number;
305
440
  cursor?: string;
441
+ state?: "active" | "upcoming";
306
442
  }) => Promise<List<MaintenanceWindow>>;
307
443
  get: (id: string) => Promise<MaintenanceWindow>;
308
444
  create: (body: Record<string, unknown>, idempotencyKey?: string) => Promise<MaintenanceWindow>;
@@ -392,3 +528,4 @@ export declare class WatchFor {
392
528
  cursor?: string;
393
529
  }): Promise<List<ActivityEvent>>;
394
530
  }
531
+ export {};
package/dist/client.js CHANGED
@@ -1,3 +1,18 @@
1
+ /**
2
+ * WatchFor API client — a thin, zero-dependency typed wrapper over
3
+ * https://watchfor.io/api/v1 (spec: https://watchfor.io/openapi.json).
4
+ *
5
+ * const wf = new WatchFor({ apiKey: process.env.WATCHFOR_API_KEY! });
6
+ * const summary = await wf.summary();
7
+ *
8
+ * An OAuth access token reaches every organization its user belongs to;
9
+ * pick one with `organization` (sent as `X-WatchFor-Organization`):
10
+ *
11
+ * const acme = new WatchFor({ apiKey: oauthToken, organization: "<org id>" });
12
+ * const other = acme.withOrganization("<another org id>");
13
+ */
14
+ /** The request header that selects the organization an OAuth token acts on. */
15
+ export const ORGANIZATION_HEADER = "X-WatchFor-Organization";
1
16
  export class WatchForError extends Error {
2
17
  status;
3
18
  code;
@@ -11,16 +26,33 @@ export class WatchForError extends Error {
11
26
  }
12
27
  }
13
28
  export class WatchFor {
29
+ /** The organization id this client sends, or undefined (the
30
+ * credential's default organization). */
31
+ organization;
32
+ options;
14
33
  apiKey;
15
34
  base;
16
35
  fetchImpl;
17
36
  constructor(opts) {
18
37
  if (!opts.apiKey)
19
38
  throw new Error("WatchFor: apiKey is required");
39
+ this.options = opts;
20
40
  this.apiKey = opts.apiKey;
41
+ this.organization = opts.organization?.trim() || undefined;
21
42
  this.base = (opts.baseUrl ?? "https://watchfor.io").replace(/\/$/, "");
22
43
  this.fetchImpl = opts.fetch ?? fetch;
23
44
  }
45
+ /**
46
+ * A new client acting on another organization (same credential and
47
+ * settings); `null` drops the header so the credential's default
48
+ * organization applies. This client is left unchanged.
49
+ */
50
+ withOrganization(organization) {
51
+ return new WatchFor({
52
+ ...this.options,
53
+ organization: organization ?? undefined,
54
+ });
55
+ }
24
56
  async request(method, path, opts = {}) {
25
57
  const url = new URL(`${this.base}/api/v1${path}`);
26
58
  for (const [k, v] of Object.entries(opts.query ?? {})) {
@@ -35,6 +67,8 @@ export class WatchFor {
35
67
  headers["Content-Type"] = "application/json";
36
68
  if (opts.idempotencyKey)
37
69
  headers["Idempotency-Key"] = opts.idempotencyKey;
70
+ if (this.organization)
71
+ headers[ORGANIZATION_HEADER] = this.organization;
38
72
  const res = await this.fetchImpl(url, {
39
73
  method,
40
74
  headers,
@@ -60,10 +94,23 @@ export class WatchFor {
60
94
  return json;
61
95
  }
62
96
  // ── Org overview ──────────────────────────────────────────────
63
- /** Current API key + organization. */
97
+ /** The credential's scope and the organization it acts on — with an
98
+ * OAuth token, the one `organization` selected. */
64
99
  me() {
65
100
  return this.request("GET", "/me");
66
101
  }
102
+ /**
103
+ * Run up to 20 operations in one request. Each runs against /api/v1 with
104
+ * the same credential and organization, so scopes, validation and rate
105
+ * limits apply per operation; results come back in request order.
106
+ */
107
+ batch(operations) {
108
+ return this.request("POST", "/batch", { body: { operations } });
109
+ }
110
+ /** The OpenAPI 3.1 document this client is built from (no key needed). */
111
+ openApiSpec() {
112
+ return this.request("GET", "/openapi.json");
113
+ }
67
114
  /** One-call org snapshot: monitor status counts + active incidents. */
68
115
  summary() {
69
116
  return this.request("GET", "/summary");
@@ -89,10 +136,20 @@ export class WatchFor {
89
136
  * Org report for a period vs the previous one: uptime, incidents,
90
137
  * MTTR/MTBF, response-time trend, per-monitor rows, type-aware
91
138
  * sections and plain-language insights. Custom from/to (ISO 8601)
92
- * needs the advanced-reports plan capability.
139
+ * needs the advanced-reports plan capability, as do the scoping
140
+ * filters (`monitor_ids`, `tags`, `sections`, `incident_status`).
93
141
  */
94
142
  report(opts) {
95
- const query = {};
143
+ const list = (v) => Array.isArray(v) ? v.join(",") : v;
144
+ const query = {
145
+ monitor_ids: list(opts?.monitor_ids),
146
+ tags: list(opts?.tags),
147
+ sections: list(opts?.sections),
148
+ incident_status: list(opts?.incident_status),
149
+ response_time: opts?.response_time,
150
+ monitors_table: opts?.monitors_table,
151
+ insights: opts?.insights,
152
+ };
96
153
  if (opts && "from" in opts) {
97
154
  query.from =
98
155
  opts.from instanceof Date ? opts.from.toISOString() : opts.from;
@@ -127,8 +184,16 @@ export class WatchFor {
127
184
  monitors = {
128
185
  list: (q) => this.request("GET", "/monitors", { query: q }),
129
186
  /** The monitor plus `available_metrics` — the alert metrics valid for
130
- * its type. */
187
+ * its type — and `alerting_state`: what the alerting engine sees right
188
+ * now (alerted, recovering n of m, failing/confirming n of m; null
189
+ * when every rule is healthy). */
131
190
  get: (id) => this.request("GET", `/monitors/${id}`),
191
+ /** Pause, resume or delete up to 100 monitors in one call; ids that
192
+ * are not yours or need no change come back in `skipped`. */
193
+ bulk: (action, ids, idempotencyKey) => this.request("POST", "/monitors/bulk", {
194
+ body: { action, ids },
195
+ idempotencyKey,
196
+ }),
132
197
  /** Create a monitor; `config` keys per type come from `monitorTypes()`.
133
198
  * Credentials (catalog fields marked `secret` — mailbox/SMTP/FTP
134
199
  * passwords, SSH keys, HTTP/API/MCP auth passwords and bearer
@@ -140,7 +205,9 @@ export class WatchFor {
140
205
  * removes). A `"[redacted]"` credential is kept when omitted or sent
141
206
  * back unchanged; changing the server, port, TLS mode or login it is
142
207
  * used with (HTTP: the URL's host, port or scheme) needs it again in
143
- * the same call (else 400). */
208
+ * the same call (else 400). `check_queued: true` in the result means
209
+ * the change (target, port, credentials, TLS, request…) dispatched one
210
+ * immediate check, outside the Run-now budget. */
144
211
  update: (id, body) => this.request("PATCH", `/monitors/${id}`, { body }),
145
212
  delete: (id) => this.request("DELETE", `/monitors/${id}`),
146
213
  pause: (id) => this.request("POST", `/monitors/${id}/pause`),
@@ -174,15 +241,23 @@ export class WatchFor {
174
241
  /** Browser checks: saved script versions (last 50). */
175
242
  scriptVersions: (id) => this.request("GET", `/monitors/${id}/script/versions`),
176
243
  scriptVersion: (id, version) => this.request("GET", `/monitors/${id}/script/versions/${version}`),
177
- uptime: (id, period) => this.request("GET", `/monitors/${id}/uptime`, { query: { period } }),
244
+ /** Uptime (confirmed critical incidents only), check success and
245
+ * response-time stats. `series: true` (periods up to 7d) adds
246
+ * `response_time_series` — buckets of `series_bucket_seconds` (300
247
+ * for 24h, 900 for 7d) on a real time axis, oldest first. */
248
+ uptime: (id, period, opts) => this.request("GET", `/monitors/${id}/uptime`, {
249
+ query: { period, series: opts?.series ? true : undefined },
250
+ }),
178
251
  /** Recent probe results, newest first. Page with `next_cursor` →
179
252
  * `cursor` (keep the same `hours`/`success`); `locations` is the
180
253
  * per-location breakdown for the whole window. */
181
254
  checks: (id, q) => this.request("GET", `/monitors/${id}/checks`, { query: q }),
255
+ /** One probe run in full, redacted server-side — run_id from checks(). */
256
+ checkDetail: (id, runId) => this.request("GET", `/monitors/${id}/checks/${runId}`),
182
257
  };
183
258
  // ── Alert rules ───────────────────────────────────────────────
184
259
  alertRules = {
185
- /** One probe run in full, redacted server-side — run_id from checks(). */
260
+ /** @deprecated Use `monitors.checkDetail()` — same call. */
186
261
  checkDetail: (id, runId) => this.request("GET", `/monitors/${id}/checks/${runId}`),
187
262
  list: (monitorId) => this.request("GET", `/monitors/${monitorId}/alert-rules`),
188
263
  get: (monitorId, ruleId) => this.request("GET", `/monitors/${monitorId}/alert-rules/${ruleId}`),
@@ -226,12 +301,38 @@ export class WatchFor {
226
301
  exclude: (id, body) => this.request("POST", `/incidents/${id}/exclude`, { body: body ?? {} }),
227
302
  /** Undo `exclude` — the incident counts as downtime again. */
228
303
  include: (id) => this.request("POST", `/incidents/${id}/include`),
304
+ /** Retroactively count a RESOLVED incident as planned maintenance: it
305
+ * leaves uptime and SLA. Returns the maintenance window recorded for
306
+ * it (marking again returns the same one); delete that window to
307
+ * undo. */
308
+ markMaintenance: (id, idempotencyKey) => this.request("POST", `/incidents/${id}/mark-maintenance`, {
309
+ idempotencyKey,
310
+ }),
229
311
  };
230
312
  // ── Status pages, on-call, channels ──────────────────────────
231
313
  statusPages = {
232
314
  list: (q) => this.request("GET", "/status-pages", { query: q }),
233
315
  get: (id) => this.request("GET", `/status-pages/${id}`),
316
+ /** Create a page, optionally with components. Password protection,
317
+ * logo upload and custom subdomains are dashboard-only. */
318
+ create: (body, idempotencyKey) => this.request("POST", "/status-pages", { body, idempotencyKey }),
319
+ /** Partial update; a slug change frees the old URL at once. */
320
+ update: (id, body) => this.request("PATCH", `/status-pages/${id}`, { body }),
321
+ delete: (id) => this.request("DELETE", `/status-pages/${id}`),
322
+ /** Announcements, newest first. */
234
323
  announcements: (id, q) => this.request("GET", `/status-pages/${id}/announcements`, { query: q }),
324
+ getAnnouncement: (id, announcementId) => this.request("GET", `/status-pages/${id}/announcements/${announcementId}`),
325
+ /** Publish an incident notice; `body` becomes the first timeline
326
+ * entry. */
327
+ createAnnouncement: (id, body, idempotencyKey) => this.request("POST", `/status-pages/${id}/announcements`, {
328
+ body,
329
+ idempotencyKey,
330
+ }),
331
+ /** Post an update: appends to the public timeline and moves the
332
+ * status; `resolved` closes it. */
333
+ updateAnnouncement: (id, announcementId, body) => this.request("PATCH", `/status-pages/${id}/announcements/${announcementId}`, { body }),
334
+ /** Remove from the public page (soft delete). */
335
+ deleteAnnouncement: (id, announcementId) => this.request("DELETE", `/status-pages/${id}/announcements/${announcementId}`),
235
336
  };
236
337
  onCall = {
237
338
  get: () => this.request("GET", "/on-call"),
@@ -251,6 +352,7 @@ export class WatchFor {
251
352
  };
252
353
  // ── Maintenance windows ───────────────────────────────────────
253
354
  maintenanceWindows = {
355
+ /** `state` keeps only live windows (active now / upcoming). */
254
356
  list: (q) => this.request("GET", "/maintenance-windows", { query: q }),
255
357
  get: (id) => this.request("GET", `/maintenance-windows/${id}`),
256
358
  create: (body, idempotencyKey) => this.request("POST", "/maintenance-windows", { body, idempotencyKey }),
package/dist/index.d.ts CHANGED
@@ -1 +1 @@
1
- export { type ActivityEvent, type AlertRule, type ApiErrorBody, type Check, type CheckList, type CheckNowAck, type Contact, type ContactGroup, type Deleted, type DiagnosticCatalog, type DiagnosticCatalogEntry, type DiagnosticReport, type DiagnosticRun, type DiagnosticSlug, type Incident, type IncidentStats, type IntegrityBaseline, type IntegrityBaselineAccept, type IntegrityBaselineAcceptPending, type List, type MaintenanceWindow, type Monitor, type MonitorDetail, type MonitorReset, type Notification, type Plan, type PlaywrightRun, type PlaywrightRunSummary, type PlaywrightTestRun, type PlaywrightTestRunAccepted, type PlaywrightTestRunRequest, type ScriptVersion, type ScriptVersionSummary, type StatusPage, type Summary, type Uptime, type Variable, type VariableDeleted, WatchFor, WatchForError, type WatchForGrade, type WatchForOptions, } from "./client.js";
1
+ export { type ActivityEvent, type AlertingState, type AlertRule, type Announcement, type AnnouncementCreate, type AnnouncementUpdate, type ApiErrorBody, type BatchOperation, type BatchResult, type BulkResult, type Check, type CheckList, type CheckNowAck, type Contact, type ContactGroup, type Deleted, type DiagnosticCatalog, type DiagnosticCatalogEntry, type DiagnosticReport, type DiagnosticRun, type DiagnosticSlug, type Incident, type IncidentStats, type IntegrityBaseline, type IntegrityBaselineAccept, type IntegrityBaselineAcceptPending, type List, type MaintenanceMarking, type MaintenanceWindow, type Me, type Monitor, type MonitorDetail, type MonitorReset, type Notification, ORGANIZATION_HEADER, type Plan, type PlaywrightRun, type PlaywrightRunSummary, type PlaywrightTestRun, type PlaywrightTestRunAccepted, type PlaywrightTestRunRequest, type ReportFilters, type ResponseTimeBucket, type ScriptVersion, type ScriptVersionSummary, type StatusPage, type StatusPageComponentCreate, type StatusPageCreate, type StatusPageUpdate, type Summary, type Uptime, type Variable, type VariableDeleted, WatchFor, WatchForError, type WatchForGrade, type WatchForOptions, } from "./client.js";
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- export { WatchFor, WatchForError, } from "./client.js";
1
+ export { ORGANIZATION_HEADER, WatchFor, WatchForError, } from "./client.js";
package/dist/schema.d.ts CHANGED
@@ -48,7 +48,10 @@ export interface paths {
48
48
  path?: never;
49
49
  cookie?: never;
50
50
  };
51
- /** A browser check's runs, newest first (404 for other monitor types) */
51
+ /**
52
+ * A browser check's runs, newest first (404 for other monitor types)
53
+ * @description Runs within the plan's check history (at most the 400 days runs are stored). History limits: reads follow the plan's data retention (/docs/organization/data-retention). A window reaching further is cut, not refused — the response carries X-History-Limit-Days (the plan's window or `unlimited`), X-History-Earliest (oldest timestamp returned, ISO 8601) and X-History-Clamped: true when the requested window was cut.
54
+ */
52
55
  get: operations["listMonitorRuns"];
53
56
  put?: never;
54
57
  post?: never;
@@ -65,7 +68,10 @@ export interface paths {
65
68
  path?: never;
66
69
  cookie?: never;
67
70
  };
68
- /** One browser-check run: steps, errors with code frames, Web Vitals, screenshots (presigned 15 min), trace link */
71
+ /**
72
+ * One browser-check run: steps, errors with code frames, Web Vitals, screenshots (presigned 15 min), trace link
73
+ * @description A run older than the plan's check history returns 404 not_found with a message naming the plan's window.
74
+ */
69
75
  get: operations["getMonitorRun"];
70
76
  put?: never;
71
77
  post?: never;
@@ -433,7 +439,10 @@ export interface paths {
433
439
  path?: never;
434
440
  cookie?: never;
435
441
  };
436
- /** Uptime (confirmed critical incidents only), check success (reachability, not health) and response-time stats (maintenance excluded) */
442
+ /**
443
+ * Uptime (confirmed critical incidents only), check success (reachability, not health) and response-time stats (maintenance excluded)
444
+ * @description Uptime and incidents cover any period on every plan. The check counts and response-time fields read the plan's charts & reports history. History limits: reads follow the plan's data retention (/docs/organization/data-retention). A window reaching further is cut, not refused — the response carries X-History-Limit-Days (the plan's window or `unlimited`), X-History-Earliest (oldest timestamp returned, ISO 8601) and X-History-Clamped: true when the requested window was cut.
445
+ */
437
446
  get: operations["getMonitorUptime"];
438
447
  put?: never;
439
448
  post?: never;
@@ -450,7 +459,10 @@ export interface paths {
450
459
  path?: never;
451
460
  cookie?: never;
452
461
  };
453
- /** Raw check history (cursor-paginated) + per-location breakdown */
462
+ /**
463
+ * Raw check history (cursor-paginated) + per-location breakdown
464
+ * @description History limits: reads follow the plan's data retention (/docs/organization/data-retention). A window reaching further is cut, not refused — the response carries X-History-Limit-Days (the plan's window or `unlimited`), X-History-Earliest (oldest timestamp returned, ISO 8601) and X-History-Clamped: true when the requested window was cut.
465
+ */
454
466
  get: operations["listMonitorChecks"];
455
467
  put?: never;
456
468
  post?: never;
@@ -984,7 +996,10 @@ export interface paths {
984
996
  path?: never;
985
997
  cookie?: never;
986
998
  };
987
- /** Organization audit trail (who changed what, when) */
999
+ /**
1000
+ * Organization audit trail (who changed what, when)
1001
+ * @description The log goes back as far as the plan's activity-log window; an earlier `since` is cut to it (X-History-Limit-Days, X-History-Earliest, X-History-Clamped headers).
1002
+ */
988
1003
  get: operations["listActivity"];
989
1004
  put?: never;
990
1005
  post?: never;
@@ -1055,7 +1070,10 @@ export interface paths {
1055
1070
  path?: never;
1056
1071
  cookie?: never;
1057
1072
  };
1058
- /** Org report for a period vs the previous one: uptime, incidents, MTTR/MTBF, response time, per-monitor rows, type-aware sections (SSL/domain expiry, Core Web Vitals, heartbeats, blocklists, MCP drift) and plain-language insights */
1073
+ /**
1074
+ * Org report for a period vs the previous one: uptime, incidents, MTTR/MTBF, response time, per-monitor rows, type-aware sections (SSL/domain expiry, Core Web Vitals, heartbeats, blocklists, MCP drift) and plain-language insights
1075
+ * @description Uptime and incidents cover any period. Check-based figures (check success, response time, p95, locations, host stats) read only the plan's charts & reports history: an earlier period start is counted from there, a comparison period reaching past it has no baseline, and meta.history ({chartHistoryDays, dataFromMs, clamped}) plus the X-History-* headers say so.
1076
+ */
1059
1077
  get: operations["getReport"];
1060
1078
  put?: never;
1061
1079
  post?: never;
@@ -1247,7 +1265,7 @@ export interface components {
1247
1265
  checks_updated?: number;
1248
1266
  };
1249
1267
  VariablePut: {
1250
- /** @description The value. For an existing secret, omit it to keep the stored one. */
1268
+ /** @description The value; a plain variable can't be empty (400). For an existing secret, omit it to keep the stored one. */
1251
1269
  value?: string;
1252
1270
  /**
1253
1271
  * @description Store encrypted and never show again; masked in logs, errors, traces and screenshots
@@ -1631,7 +1649,7 @@ export interface components {
1631
1649
  description?: string | null;
1632
1650
  interval_seconds?: number;
1633
1651
  /**
1634
- * @description Effective status. down = a confirmed critical incident is open (firing or acknowledged); degraded = a failed check not yet confirmed, or an open warning incident; unknown = no check data yet. paused always wins.
1652
+ * @description Effective status. down = a confirmed critical incident is open (firing or acknowledged); degraded = an open warning incident, or a check failing without a confirmed incident yet — the latest check failed or any alert rule (availability, status code, response time, content, assertions…) is failing while its confirmation is in progress; unknown = no check data yet. paused always wins.
1635
1653
  * @enum {string}
1636
1654
  */
1637
1655
  status?: "up" | "degraded" | "down" | "paused" | "unknown";
@@ -1643,11 +1661,14 @@ export interface components {
1643
1661
  */
1644
1662
  ping_url?: string;
1645
1663
  active?: boolean;
1646
- /** @enum {string} */
1664
+ /**
1665
+ * @description Which locations run each check: roundrobin = one location per check, rotating through the selection; random = one location per check, picked at random from the selection (every plan, same load as roundrobin); parallel = every selected location on every check (plan-gated — GET /plan → limits.allowed_strategies and max_parallel_monitors). A strategy the plan does not include is refused with 403 forbidden.
1666
+ * @enum {string}
1667
+ */
1647
1668
  scheduling_strategy?: "roundrobin" | "random" | "parallel";
1648
1669
  locations?: string[];
1649
1670
  /**
1650
- * @description Why `status` is what it is: critical_incident = a confirmed critical incident is open (the only way to be down); warning_incident = an open warning incident; failed_check = the latest check failed, not yet confirmed (degraded); paused; no_data = nothing reported yet (unknown); ok. Present on GET/POST/PATCH/pause/resume responses.
1671
+ * @description Why `status` is what it is: critical_incident = a confirmed critical incident is open (the only way to be down); warning_incident = an open warning incident; failed_check = a check is failing (the latest check failed, or an alert rule such as status code or response time is failing) without a confirmed incident yet (degraded); paused; no_data = nothing reported yet (unknown); ok. Present on GET/POST/PATCH/pause/resume responses.
1651
1672
  * @enum {string}
1652
1673
  */
1653
1674
  status_reason?:
@@ -1662,6 +1683,23 @@ export interface components {
1662
1683
  * @description When the open incident behind a critical_incident / warning_incident started; null otherwise.
1663
1684
  */
1664
1685
  status_since?: string | null;
1686
+ /** @description GET /monitors/{id} only: what the alerting engine sees right now. alerted = a rule's incident is still open in the engine; recovering = every such rule has had healthy checks since, but not enough to resolve yet (count of threshold — 'Recovering 1/3'); while alerted and not recovering, the rule behind the incident is still failing. failing = a rule is failing below its confirmation threshold (no incident yet), confirming = how far it is ('2 of 3'). null when the engine reports nothing (every rule healthy, or it did not answer in time). */
1687
+ alerting_state?: {
1688
+ alerted?: boolean;
1689
+ recovering?: {
1690
+ count?: number;
1691
+ threshold?: number;
1692
+ } | null;
1693
+ failing?: boolean;
1694
+ /** Format: date-time */
1695
+ failing_since?: string | null;
1696
+ confirming?: {
1697
+ count?: number;
1698
+ threshold?: number;
1699
+ } | null;
1700
+ } | null;
1701
+ /** @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. */
1702
+ check_queued?: boolean;
1665
1703
  /** @description The open (firing or acknowledged) incident, or null. When several are open: the critical one, then the earliest started. */
1666
1704
  current_incident?: components["schemas"]["MonitorCurrentIncident"] | null;
1667
1705
  /** @description A silence (dashboard Mute) suppresses notifications; incidents still open and close and checks continue. */
@@ -1807,6 +1845,7 @@ export interface components {
1807
1845
  /** @description Location ids from GET /locations; at least one is required except for heartbeat, which takes none (a non-empty list on a heartbeat is a 400) */
1808
1846
  locations?: string[];
1809
1847
  /**
1848
+ * @description Which locations run each check: roundrobin = one location per check, rotating through the selection; random = one location per check, picked at random from the selection (every plan, same load as roundrobin); parallel = every selected location on every check (plan-gated — GET /plan → limits.allowed_strategies and max_parallel_monitors). A strategy the plan does not include is refused with 403 forbidden.
1810
1849
  * @default roundrobin
1811
1850
  * @enum {string}
1812
1851
  */
@@ -1833,7 +1872,10 @@ export interface components {
1833
1872
  /** @description null clears the description */
1834
1873
  description?: string | null;
1835
1874
  interval?: number;
1836
- /** @enum {string} */
1875
+ /**
1876
+ * @description Which locations run each check: roundrobin = one location per check, rotating through the selection; random = one location per check, picked at random from the selection (every plan, same load as roundrobin); parallel = every selected location on every check (plan-gated — GET /plan → limits.allowed_strategies and max_parallel_monitors). A strategy the plan does not include is refused with 403 forbidden.
1877
+ * @enum {string}
1878
+ */
1837
1879
  schedulingStrategy?: "roundrobin" | "random" | "parallel";
1838
1880
  locations?: string[];
1839
1881
  tags?: string[];
@@ -1867,8 +1909,11 @@ export interface components {
1867
1909
  total_checks?: number;
1868
1910
  successful_checks?: number;
1869
1911
  failed_checks?: number;
1912
+ /** @description Latency over successful checks only (a failed check has no response time); null when no check succeeded */
1870
1913
  avg_response_time_ms?: number | null;
1914
+ /** @description Latency over successful checks only (a failed check has no response time); null when no check succeeded */
1871
1915
  min_response_time_ms?: number | null;
1916
+ /** @description Latency over successful checks only (a failed check has no response time); null when no check succeeded */
1872
1917
  max_response_time_ms?: number | null;
1873
1918
  last_failure_at?: string | null;
1874
1919
  /** @description Incident-based headline uptime for the last 24 hours */
@@ -1888,6 +1933,17 @@ export interface components {
1888
1933
  resolved_at?: string | null;
1889
1934
  downtime_ms?: number;
1890
1935
  }[];
1936
+ /** @description Only with series=true: the width of each response_time_series bucket (300 for 24h, 900 for 7d). */
1937
+ series_bucket_seconds?: number;
1938
+ /** @description Only with series=true (periods up to 7d): the period on a real time axis, oldest first. Only buckets that held checks appear. avg_ms / max_ms cover the bucket's successful checks; null when every check in it failed (draw a gap). */
1939
+ response_time_series?: {
1940
+ /** Format: date-time */
1941
+ at?: string;
1942
+ checks?: number;
1943
+ failed?: number;
1944
+ avg_ms?: number | null;
1945
+ max_ms?: number | null;
1946
+ }[];
1891
1947
  };
1892
1948
  /** @description One probe run. Type-specific fields appear only when the probe recorded them (packet loss for ICMP, rcode and answer count for DNS, connect / TLS handshake times for TCP, relay and PTR checks for SMTP, sitemap counts). */
1893
1949
  Check: {
@@ -1953,7 +2009,7 @@ export interface components {
1953
2009
  sitemap_url_count?: number;
1954
2010
  sitemap_broken_urls?: number;
1955
2011
  sitemap_broken_percent?: number;
1956
- /** @description The stored output, redacted: a JSON object whose shape depends on the monitor type; a string when the probe recorded plain text; null when stored is false */
2012
+ /** @description The stored output, redacted: a JSON object whose shape depends on the monitor type; a string when the probe recorded plain text; null when stored is false. Failed checks always keep their output. For successful http, smtp, mtr, brotli and favicon checks the output is kept as a short-lived sample — about one successful check every 10 minutes per location, the last ~8 per location, for at most 2 days; other successful checks of those types return stored: false. */
1957
2013
  result?: Record<string, never> | string | null;
1958
2014
  /** @description Size of the stored output before redaction (0 when nothing is stored) */
1959
2015
  result_bytes?: number;
@@ -2329,6 +2385,12 @@ export interface components {
2329
2385
  /** Format: date-time */
2330
2386
  updated_at?: string;
2331
2387
  };
2388
+ MaintenanceMarking: {
2389
+ /** @enum {string} */
2390
+ object: "maintenance_marking";
2391
+ incident_id: number;
2392
+ maintenance_window: components["schemas"]["MaintenanceWindow"];
2393
+ };
2332
2394
  MaintenanceWindow: {
2333
2395
  /** Format: uuid */
2334
2396
  id?: string;
@@ -2465,7 +2527,10 @@ export interface components {
2465
2527
  * @default true
2466
2528
  */
2467
2529
  autoPublishIncidents: boolean;
2468
- /** @default false */
2530
+ /**
2531
+ * @description Days before a component's monitor existed show as no data instead of 100 % uptime
2532
+ * @default true
2533
+ */
2469
2534
  dimUntrackedDays: boolean;
2470
2535
  /**
2471
2536
  * @default auto
@@ -2836,7 +2901,7 @@ export interface components {
2836
2901
  Summary: {
2837
2902
  /** @constant */
2838
2903
  object?: "summary";
2839
- /** @description Effective-status counts — same rule as the dashboard: an open critical incident flips a stale up/unknown to down; an open warning incident or an unconfirmed failed check counts as degraded; paused always wins. health_score is 0-100 (share of active, non-paused monitors that are up). */
2904
+ /** @description Effective-status counts — same rule as the dashboard: an open critical incident flips a stale up/unknown to down; an open warning incident or a failing check or alert rule without a confirmed incident counts as degraded; paused always wins. health_score is 0-100 (share of active, non-paused monitors that are up). */
2840
2905
  monitors?: {
2841
2906
  total?: number;
2842
2907
  up?: number;
@@ -3093,9 +3158,12 @@ export interface components {
3093
3158
  * @description Alias of success_percent
3094
3159
  */
3095
3160
  uptime_percent?: number;
3096
- avg_response_time_ms?: number;
3097
- min_response_time_ms?: number;
3098
- max_response_time_ms?: number;
3161
+ /** @description Latency over successful checks only (a failed check has no response time); null when no check succeeded at this location */
3162
+ avg_response_time_ms?: number | null;
3163
+ /** @description Latency over successful checks only (a failed check has no response time); null when no check succeeded at this location */
3164
+ min_response_time_ms?: number | null;
3165
+ /** @description Latency over successful checks only (a failed check has no response time); null when no check succeeded at this location */
3166
+ max_response_time_ms?: number | null;
3099
3167
  }[];
3100
3168
  /** @description Pass as ?cursor= for the next (older) page; null on the last page */
3101
3169
  next_cursor?: string | null;
@@ -3362,7 +3430,10 @@ export interface components {
3362
3430
  };
3363
3431
  };
3364
3432
  responses: never;
3365
- parameters: never;
3433
+ parameters: {
3434
+ /** @description OAuth tokens only: the id of the organization to act on. The token's user must be a member (otherwise 403 forbidden), and their role there applies — members can read, acknowledge incidents and run diagnostics; creating, changing and deleting needs owner or admin, as in the dashboard. Omitted: the user's oldest owned organization, else their oldest membership. With an API key the header may only repeat the key's own organization id (anything else is 403). */
3435
+ OrganizationHeader: string;
3436
+ };
3366
3437
  requestBodies: never;
3367
3438
  headers: never;
3368
3439
  pathItems: never;
@@ -3912,7 +3983,7 @@ export interface operations {
3912
3983
  /** @description Opaque cursor from the previous page's next_cursor */
3913
3984
  cursor?: string;
3914
3985
  type?: string;
3915
- /** @description Effective status: down = confirmed critical incident open; degraded = failed check not yet confirmed, or an open warning incident */
3986
+ /** @description Effective status, the same value the rows carry: down = confirmed critical incident open; degraded = a failing check or alert rule not yet confirmed, or an open warning incident */
3916
3987
  status?: "up" | "degraded" | "down" | "paused" | "unknown";
3917
3988
  tag?: string;
3918
3989
  /** @description Case-insensitive substring search over name and target */
@@ -4347,6 +4418,8 @@ export interface operations {
4347
4418
  parameters: {
4348
4419
  query?: {
4349
4420
  period?: "1h" | "24h" | "7d" | "30d" | "90d";
4421
+ /** @description true adds response_time_series (bucketed response times on a real time axis) — periods up to 7d */
4422
+ series?: boolean;
4350
4423
  };
4351
4424
  header?: never;
4352
4425
  path: {
@@ -4380,6 +4453,7 @@ export interface operations {
4380
4453
  listMonitorChecks: {
4381
4454
  parameters: {
4382
4455
  query?: {
4456
+ /** @description Window in hours, cut to the plan's check history when it reaches further (see X-History-Clamped) */
4383
4457
  hours?: number;
4384
4458
  /** @description Page size, 1–100 (default 50). Any other value — 0, negative, non-integer — returns 400. A `sort` query parameter is not supported and returns 400 naming the fixed order. */
4385
4459
  limit?: number;
@@ -4424,7 +4498,7 @@ export interface operations {
4424
4498
  path: {
4425
4499
  /** @description Resource id (UUID) */
4426
4500
  id: string;
4427
- /** @description The check's run_id as listed by GET /monitors/{id}/checks (opaque; malformed → 400, unknown for this monitor → 404) */
4501
+ /** @description The check's run_id as listed by GET /monitors/{id}/checks (opaque; malformed → 400, unknown for this monitor or older than the plan's check history → 404) */
4428
4502
  run_id: string;
4429
4503
  };
4430
4504
  cookie?: never;
@@ -4911,21 +4985,23 @@ export interface operations {
4911
4985
  };
4912
4986
  requestBody?: never;
4913
4987
  responses: {
4914
- /** @description Incident marked as maintenance */
4988
+ /** @description Already marked: the existing maintenance window */
4915
4989
  200: {
4916
4990
  headers: {
4917
4991
  [name: string]: unknown;
4918
4992
  };
4919
4993
  content: {
4920
- "application/json": components["schemas"]["Incident"];
4994
+ "application/json": components["schemas"]["MaintenanceMarking"];
4921
4995
  };
4922
4996
  };
4923
- /** @description Marked; returns the maintenance window */
4997
+ /** @description Marked: the maintenance window created for it */
4924
4998
  201: {
4925
4999
  headers: {
4926
5000
  [name: string]: unknown;
4927
5001
  };
4928
- content?: never;
5002
+ content: {
5003
+ "application/json": components["schemas"]["MaintenanceMarking"];
5004
+ };
4929
5005
  };
4930
5006
  /** @description Error */
4931
5007
  default: {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "watchfor",
3
- "version": "0.14.0",
3
+ "version": "0.15.0",
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",