watchfor 0.14.0 → 0.16.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,40 @@ 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 wf = new WatchFor({ apiKey: oauthAccessToken });
142
+ const { data } = await wf.organizations.list();
143
+ // [{ id, name, slug, role: "owner", plan: "Pro", is_default: true, is_current: true }, …]
144
+
145
+ const acme = new WatchFor({ apiKey: oauthAccessToken, organization: "<organization-id>" });
146
+ await acme.me(); // { organization: { id, name, slug }, scope }
147
+ const other = acme.withOrganization("<another-organization-id>"); // new client, same token
148
+ await other.monitors.list();
149
+ ```
150
+
151
+ - `organizations.list()` returns the ids to use: every organization of the
152
+ token's user with their `role`, `is_default` (used without `organization`)
153
+ and `is_current` (what this client acts on). With an API key it returns just
154
+ the key's own organization (`role: null`).
155
+ - Without `organization`, an OAuth token acts on the user's oldest owned
156
+ organization (else their oldest membership).
157
+ - The user must be a member of that organization (otherwise `403
158
+ forbidden`), and their role there applies: members read, acknowledge
159
+ incidents and run diagnostics; changes need owner or admin.
160
+ - With an API key leave it unset; it may only repeat the key's own
161
+ organization id, and any other id is `403 forbidden` (a key never
162
+ switches organization).
163
+ - `withOrganization(null)` drops the header again.
164
+
165
+ Details: https://watchfor.io/docs/api/authentication#how-oauth-maps-to-your-data
166
+
115
167
  ## Prometheus metrics (Pro plan and above)
116
168
 
117
169
  ```ts
@@ -129,6 +181,13 @@ npx watchfor incidents --status firing
129
181
  npx watchfor monitors example.com
130
182
  npx watchfor checks <monitor-id> --failed # add --cursor <next_cursor> for older pages
131
183
  npx watchfor report --period 30d
184
+ npx watchfor me # which organization + scope
185
+ npx watchfor organizations # ids for --organization
186
+
187
+ # OAuth token: pick the organization per call or via the environment
188
+ export WATCHFOR_API_KEY=<oauth-access-token>
189
+ npx watchfor --organization <organization-id> monitors
190
+ WATCHFOR_ORGANIZATION=<organization-id> npx watchfor summary
132
191
  ```
133
192
 
134
193
  ## Links
package/dist/cli.js CHANGED
@@ -8,10 +8,17 @@ 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 organizations (ids for --organization)
12
+ * watchfor --organization <org-id> monitors (OAuth tokens)
11
13
  */
12
14
  const HELP = `watchfor — WatchFor monitoring CLI (https://watchfor.io)
13
15
 
14
16
  Usage:
17
+ watchfor [--organization <id>] <command> [options]
18
+
19
+ Commands:
20
+ watchfor me Which organization and scope the credential acts with
21
+ watchfor organizations Organizations the credential can act on (ids for --organization)
15
22
  watchfor summary Org snapshot: what's up/down right now
16
23
  watchfor incidents [--status s] List incidents (firing|acknowledged|resolved)
17
24
  watchfor monitors [query] List monitors (optional name/target search)
@@ -23,9 +30,15 @@ Usage:
23
30
  Prometheus text format (Pro plan and above)
24
31
  watchfor help
25
32
 
33
+ Global options:
34
+ --organization <id> Organization to act on (X-WatchFor-Organization). OAuth
35
+ tokens reach every organization their user belongs to;
36
+ an API key only accepts its own organization's id.
37
+
26
38
  Environment:
27
- WATCHFOR_API_KEY API key (dashboard → Settings → API keys)
28
- WATCHFOR_BASE_URL Override (default https://watchfor.io)
39
+ WATCHFOR_API_KEY API key (dashboard → Settings → API keys) or an OAuth access token
40
+ WATCHFOR_ORGANIZATION Default for --organization
41
+ WATCHFOR_BASE_URL Override (default https://watchfor.io)
29
42
  `;
30
43
  function flag(args, name) {
31
44
  const i = args.indexOf(`--${name}`);
@@ -33,8 +46,29 @@ function flag(args, name) {
33
46
  return undefined;
34
47
  return args[i + 1] && !args[i + 1].startsWith("--") ? args[i + 1] : "true";
35
48
  }
49
+ /** Removes a global `--name <value>` / `--name=<value>` from argv, wherever
50
+ * it appears, and returns its value. */
51
+ function takeGlobal(argv, name) {
52
+ let value;
53
+ for (let i = 0; i < argv.length; i++) {
54
+ const a = argv[i];
55
+ if (a === `--${name}`) {
56
+ value = argv[i + 1] ?? "";
57
+ argv.splice(i, 2);
58
+ i--;
59
+ }
60
+ else if (a.startsWith(`--${name}=`)) {
61
+ value = a.slice(name.length + 3);
62
+ argv.splice(i, 1);
63
+ i--;
64
+ }
65
+ }
66
+ return value;
67
+ }
36
68
  async function main() {
37
- const [cmd, ...args] = process.argv.slice(2);
69
+ const argv = process.argv.slice(2);
70
+ const organizationFlag = takeGlobal(argv, "organization");
71
+ const [cmd, ...args] = argv;
38
72
  if (!cmd || cmd === "help" || cmd === "--help" || cmd === "-h") {
39
73
  process.stdout.write(HELP);
40
74
  return 0;
@@ -44,11 +78,39 @@ async function main() {
44
78
  console.error("WATCHFOR_API_KEY is not set. Create a key in the dashboard (Settings → API keys).");
45
79
  return 1;
46
80
  }
81
+ const organization = organizationFlag ?? process.env.WATCHFOR_ORGANIZATION ?? undefined;
82
+ if (organizationFlag !== undefined && !organizationFlag.trim()) {
83
+ console.error("--organization needs an organization id");
84
+ return 1;
85
+ }
47
86
  const wf = new WatchFor({
48
87
  apiKey,
88
+ organization,
49
89
  baseUrl: process.env.WATCHFOR_BASE_URL,
50
90
  });
51
91
  switch (cmd) {
92
+ case "me": {
93
+ const me = await wf.me();
94
+ const org = me.organization;
95
+ console.log(`organization: ${org ? `${org.name} (${org.id})` : "none"} · scope ${me.scope ?? "?"}`);
96
+ return 0;
97
+ }
98
+ case "organizations":
99
+ case "orgs": {
100
+ const res = await wf.organizations.list();
101
+ for (const o of res.data) {
102
+ const marks = [
103
+ o.is_current ? "current" : "",
104
+ o.is_default ? "default" : "",
105
+ ]
106
+ .filter(Boolean)
107
+ .join(", ");
108
+ console.log(`${o.id} ${String(o.role ?? "api key").padEnd(7)} ${String(o.plan).padEnd(10)} ${o.name}${marks ? ` (${marks})` : ""}`);
109
+ }
110
+ if (res.data.length === 0)
111
+ console.log("(no organizations)");
112
+ return 0;
113
+ }
52
114
  case "summary": {
53
115
  const s = await wf.summary();
54
116
  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,58 @@ 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
+ /**
81
+ * An organization the credential can act on (`organizations.list()`):
82
+ * `role` is the token user's membership role (null for an API key),
83
+ * `is_default` marks the one used without `organization`, `is_current` the one
84
+ * the request acted on.
85
+ */
86
+ export type Organization = components["schemas"]["Organization"];
87
+ /** `batch()` results, in request order: `{ status, body }` per operation. */
88
+ export type BatchResult = components["schemas"]["BatchResult"];
89
+ /** One operation of a `batch()` call — a relative /api/v1 path. */
90
+ export interface BatchOperation {
91
+ method: "GET" | "POST" | "PATCH" | "PUT" | "DELETE";
92
+ /** Relative /api/v1 sub-path, e.g. `/monitors/{id}`. */
93
+ path: string;
94
+ body?: Record<string, unknown>;
95
+ }
40
96
  export type IncidentStats = components["schemas"]["IncidentStats"];
41
97
  export type ActivityEvent = components["schemas"]["ActivityEvent"];
42
98
  export type Notification = components["schemas"]["Notification"];
@@ -72,20 +128,68 @@ export declare class WatchForError extends Error {
72
128
  constructor(status: number, code: string, message: string, retryAfterSeconds?: number);
73
129
  }
74
130
  export interface WatchForOptions {
75
- /** API key (wf_live_…) — dashboard Settings → API keys. */
131
+ /** API key (wf_live_…, dashboard Settings → API keys) or an OAuth
132
+ * access token. */
76
133
  apiKey: string;
134
+ /**
135
+ * Organization id to act on, sent as `X-WatchFor-Organization`. For
136
+ * OAuth tokens, which reach every organization their user belongs to
137
+ * (omitted: the user's oldest owned organization, else their oldest
138
+ * membership). An API key belongs to one organization: leave it unset,
139
+ * or set that same id — any other id is 403 `forbidden`.
140
+ */
141
+ organization?: string;
77
142
  /** Override for self-hosted / testing. Default https://watchfor.io */
78
143
  baseUrl?: string;
79
144
  fetch?: typeof fetch;
80
145
  }
146
+ /** Optional scoping/shape filters of `report()`; lists may be arrays or
147
+ * comma-separated strings. */
148
+ export interface ReportFilters {
149
+ /** Scope to these monitors (union with `tags`). */
150
+ monitor_ids?: string | string[];
151
+ /** Scope to monitors carrying these tags. */
152
+ tags?: string | string[];
153
+ /** Subset of type-aware sections: locations, ssl, domains, cwv,
154
+ * heartbeat, blacklist, mcp, hosts (omit for all). */
155
+ sections?: string | string[];
156
+ /** false drops the response-time block. */
157
+ response_time?: boolean;
158
+ /** false drops the per-monitor table. */
159
+ monitors_table?: boolean;
160
+ /** false drops the insights block. */
161
+ insights?: boolean;
162
+ /** Incident aggregates only over these states: acknowledged, resolved,
163
+ * open (or all). */
164
+ incident_status?: string | string[];
165
+ }
81
166
  export declare class WatchFor {
167
+ /** The organization id this client sends, or undefined (the
168
+ * credential's default organization). */
169
+ readonly organization: string | undefined;
170
+ private readonly options;
82
171
  private readonly apiKey;
83
172
  private readonly base;
84
173
  private readonly fetchImpl;
85
174
  constructor(opts: WatchForOptions);
175
+ /**
176
+ * A new client acting on another organization (same credential and
177
+ * settings); `null` drops the header so the credential's default
178
+ * organization applies. This client is left unchanged.
179
+ */
180
+ withOrganization(organization: string | null): WatchFor;
86
181
  private request;
87
- /** Current API key + organization. */
88
- me(): Promise<unknown>;
182
+ /** The credential's scope and the organization it acts on — with an
183
+ * OAuth token, the one `organization` selected. */
184
+ me(): Promise<Me>;
185
+ /**
186
+ * Run up to 20 operations in one request. Each runs against /api/v1 with
187
+ * the same credential and organization, so scopes, validation and rate
188
+ * limits apply per operation; results come back in request order.
189
+ */
190
+ batch(operations: BatchOperation[]): Promise<BatchResult>;
191
+ /** The OpenAPI 3.1 document this client is built from (no key needed). */
192
+ openApiSpec(): Promise<Record<string, unknown>>;
89
193
  /** One-call org snapshot: monitor status counts + active incidents. */
90
194
  summary(): Promise<Summary>;
91
195
  /**
@@ -108,14 +212,15 @@ export declare class WatchFor {
108
212
  * Org report for a period vs the previous one: uptime, incidents,
109
213
  * MTTR/MTBF, response-time trend, per-monitor rows, type-aware
110
214
  * sections and plain-language insights. Custom from/to (ISO 8601)
111
- * needs the advanced-reports plan capability.
215
+ * needs the advanced-reports plan capability, as do the scoping
216
+ * filters (`monitor_ids`, `tags`, `sections`, `incident_status`).
112
217
  */
113
- report(opts?: {
218
+ report(opts?: ({
114
219
  period?: "7d" | "30d";
115
220
  } | {
116
221
  from: string | Date;
117
222
  to: string | Date;
118
- }): Promise<Record<string, unknown>>;
223
+ }) & ReportFilters): Promise<Record<string, unknown>>;
119
224
  /** The org's two report-email cadences (weekly + monthly). */
120
225
  reportSchedules(): Promise<List<Record<string, unknown>>>;
121
226
  /**
@@ -131,6 +236,15 @@ export declare class WatchFor {
131
236
  locations(): Promise<List<Record<string, unknown>>>;
132
237
  /** Every monitor type with its exact alert metrics + config fields. */
133
238
  monitorTypes(): Promise<List<Record<string, unknown>>>;
239
+ readonly organizations: {
240
+ /**
241
+ * The organizations this credential can act on — the ids
242
+ * `organization` / `withOrganization()` accept. An OAuth token lists
243
+ * every organization of its user; an API key only its own. Works
244
+ * whatever `organization` is set to (a foreign id is still 403).
245
+ */
246
+ list: () => Promise<List<Organization>>;
247
+ };
134
248
  readonly monitors: {
135
249
  list: (q?: {
136
250
  q?: string;
@@ -141,8 +255,13 @@ export declare class WatchFor {
141
255
  cursor?: string;
142
256
  }) => Promise<List<Monitor>>;
143
257
  /** The monitor plus `available_metrics` — the alert metrics valid for
144
- * its type. */
258
+ * its type — and `alerting_state`: what the alerting engine sees right
259
+ * now (alerted, recovering n of m, failing/confirming n of m; null
260
+ * when every rule is healthy). */
145
261
  get: (id: string) => Promise<MonitorDetail>;
262
+ /** Pause, resume or delete up to 100 monitors in one call; ids that
263
+ * are not yours or need no change come back in `skipped`. */
264
+ bulk: (action: "pause" | "resume" | "delete", ids: string[], idempotencyKey?: string) => Promise<BulkResult>;
146
265
  /** Create a monitor; `config` keys per type come from `monitorTypes()`.
147
266
  * Credentials (catalog fields marked `secret` — mailbox/SMTP/FTP
148
267
  * passwords, SSH keys, HTTP/API/MCP auth passwords and bearer
@@ -154,7 +273,9 @@ export declare class WatchFor {
154
273
  * removes). A `"[redacted]"` credential is kept when omitted or sent
155
274
  * back unchanged; changing the server, port, TLS mode or login it is
156
275
  * used with (HTTP: the URL's host, port or scheme) needs it again in
157
- * the same call (else 400). */
276
+ * the same call (else 400). `check_queued: true` in the result means
277
+ * the change (target, port, credentials, TLS, request…) dispatched one
278
+ * immediate check, outside the Run-now budget. */
158
279
  update: (id: string, body: Record<string, unknown>) => Promise<Monitor>;
159
280
  delete: (id: string) => Promise<Deleted>;
160
281
  pause: (id: string) => Promise<Monitor>;
@@ -201,7 +322,13 @@ export declare class WatchFor {
201
322
  data: ScriptVersionSummary[];
202
323
  }>;
203
324
  scriptVersion: (id: string, version: number) => Promise<ScriptVersion>;
204
- uptime: (id: string, period?: "1h" | "24h" | "7d" | "30d" | "90d") => Promise<Uptime>;
325
+ /** Uptime (confirmed critical incidents only), check success and
326
+ * response-time stats. `series: true` (periods up to 7d) adds
327
+ * `response_time_series` — buckets of `series_bucket_seconds` (300
328
+ * for 24h, 900 for 7d) on a real time axis, oldest first. */
329
+ uptime: (id: string, period?: "1h" | "24h" | "7d" | "30d" | "90d", opts?: {
330
+ series?: boolean;
331
+ }) => Promise<Uptime>;
205
332
  /** Recent probe results, newest first. Page with `next_cursor` →
206
333
  * `cursor` (keep the same `hours`/`success`); `locations` is the
207
334
  * per-location breakdown for the whole window. */
@@ -211,9 +338,11 @@ export declare class WatchFor {
211
338
  success?: boolean;
212
339
  cursor?: string;
213
340
  }) => Promise<CheckList>;
341
+ /** One probe run in full, redacted server-side — run_id from checks(). */
342
+ checkDetail: (id: string, runId: string) => Promise<Record<string, unknown>>;
214
343
  };
215
344
  readonly alertRules: {
216
- /** One probe run in full, redacted server-side — run_id from checks(). */
345
+ /** @deprecated Use `monitors.checkDetail()` — same call. */
217
346
  checkDetail: (id: string, runId: string) => Promise<Record<string, unknown>>;
218
347
  list: (monitorId: string) => Promise<List<AlertRule>>;
219
348
  get: (monitorId: string, ruleId: string) => Promise<AlertRule>;
@@ -267,6 +396,11 @@ export declare class WatchFor {
267
396
  }) => Promise<Incident>;
268
397
  /** Undo `exclude` — the incident counts as downtime again. */
269
398
  include: (id: number) => Promise<Incident>;
399
+ /** Retroactively count a RESOLVED incident as planned maintenance: it
400
+ * leaves uptime and SLA. Returns the maintenance window recorded for
401
+ * it (marking again returns the same one); delete that window to
402
+ * undo. */
403
+ markMaintenance: (id: number, idempotencyKey?: string) => Promise<MaintenanceMarking>;
270
404
  };
271
405
  readonly statusPages: {
272
406
  list: (q?: {
@@ -274,10 +408,26 @@ export declare class WatchFor {
274
408
  cursor?: string;
275
409
  }) => Promise<List<StatusPage>>;
276
410
  get: (id: string) => Promise<StatusPage>;
411
+ /** Create a page, optionally with components. Password protection,
412
+ * logo upload and custom subdomains are dashboard-only. */
413
+ create: (body: StatusPageCreate, idempotencyKey?: string) => Promise<StatusPage>;
414
+ /** Partial update; a slug change frees the old URL at once. */
415
+ update: (id: string, body: StatusPageUpdate) => Promise<StatusPage>;
416
+ delete: (id: string) => Promise<Deleted>;
417
+ /** Announcements, newest first. */
277
418
  announcements: (id: string, q?: {
278
419
  limit?: number;
279
420
  cursor?: string;
280
- }) => Promise<List<Record<string, unknown>>>;
421
+ }) => Promise<List<Announcement>>;
422
+ getAnnouncement: (id: string, announcementId: string) => Promise<Announcement>;
423
+ /** Publish an incident notice; `body` becomes the first timeline
424
+ * entry. */
425
+ createAnnouncement: (id: string, body: AnnouncementCreate, idempotencyKey?: string) => Promise<Announcement>;
426
+ /** Post an update: appends to the public timeline and moves the
427
+ * status; `resolved` closes it. */
428
+ updateAnnouncement: (id: string, announcementId: string, body: AnnouncementUpdate) => Promise<Announcement>;
429
+ /** Remove from the public page (soft delete). */
430
+ deleteAnnouncement: (id: string, announcementId: string) => Promise<Deleted>;
281
431
  };
282
432
  readonly onCall: {
283
433
  get: () => Promise<Record<string, unknown>>;
@@ -300,9 +450,11 @@ export declare class WatchFor {
300
450
  metrics: (id: string, metrics: string[], range?: "1h" | "6h" | "24h" | "7d" | "30d") => Promise<HostMetrics>;
301
451
  };
302
452
  readonly maintenanceWindows: {
453
+ /** `state` keeps only live windows (active now / upcoming). */
303
454
  list: (q?: {
304
455
  limit?: number;
305
456
  cursor?: string;
457
+ state?: "active" | "upcoming";
306
458
  }) => Promise<List<MaintenanceWindow>>;
307
459
  get: (id: string) => Promise<MaintenanceWindow>;
308
460
  create: (body: Record<string, unknown>, idempotencyKey?: string) => Promise<MaintenanceWindow>;
@@ -392,3 +544,4 @@ export declare class WatchFor {
392
544
  cursor?: string;
393
545
  }): Promise<List<ActivityEvent>>;
394
546
  }
547
+ 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;
@@ -123,12 +180,30 @@ export class WatchFor {
123
180
  monitorTypes() {
124
181
  return this.request("GET", "/meta/monitor-types");
125
182
  }
183
+ // ── Organizations ─────────────────────────────────────────────
184
+ organizations = {
185
+ /**
186
+ * The organizations this credential can act on — the ids
187
+ * `organization` / `withOrganization()` accept. An OAuth token lists
188
+ * every organization of its user; an API key only its own. Works
189
+ * whatever `organization` is set to (a foreign id is still 403).
190
+ */
191
+ list: () => this.request("GET", "/organizations"),
192
+ };
126
193
  // ── Monitors ──────────────────────────────────────────────────
127
194
  monitors = {
128
195
  list: (q) => this.request("GET", "/monitors", { query: q }),
129
196
  /** The monitor plus `available_metrics` — the alert metrics valid for
130
- * its type. */
197
+ * its type — and `alerting_state`: what the alerting engine sees right
198
+ * now (alerted, recovering n of m, failing/confirming n of m; null
199
+ * when every rule is healthy). */
131
200
  get: (id) => this.request("GET", `/monitors/${id}`),
201
+ /** Pause, resume or delete up to 100 monitors in one call; ids that
202
+ * are not yours or need no change come back in `skipped`. */
203
+ bulk: (action, ids, idempotencyKey) => this.request("POST", "/monitors/bulk", {
204
+ body: { action, ids },
205
+ idempotencyKey,
206
+ }),
132
207
  /** Create a monitor; `config` keys per type come from `monitorTypes()`.
133
208
  * Credentials (catalog fields marked `secret` — mailbox/SMTP/FTP
134
209
  * passwords, SSH keys, HTTP/API/MCP auth passwords and bearer
@@ -140,7 +215,9 @@ export class WatchFor {
140
215
  * removes). A `"[redacted]"` credential is kept when omitted or sent
141
216
  * back unchanged; changing the server, port, TLS mode or login it is
142
217
  * used with (HTTP: the URL's host, port or scheme) needs it again in
143
- * the same call (else 400). */
218
+ * the same call (else 400). `check_queued: true` in the result means
219
+ * the change (target, port, credentials, TLS, request…) dispatched one
220
+ * immediate check, outside the Run-now budget. */
144
221
  update: (id, body) => this.request("PATCH", `/monitors/${id}`, { body }),
145
222
  delete: (id) => this.request("DELETE", `/monitors/${id}`),
146
223
  pause: (id) => this.request("POST", `/monitors/${id}/pause`),
@@ -174,15 +251,23 @@ export class WatchFor {
174
251
  /** Browser checks: saved script versions (last 50). */
175
252
  scriptVersions: (id) => this.request("GET", `/monitors/${id}/script/versions`),
176
253
  scriptVersion: (id, version) => this.request("GET", `/monitors/${id}/script/versions/${version}`),
177
- uptime: (id, period) => this.request("GET", `/monitors/${id}/uptime`, { query: { period } }),
254
+ /** Uptime (confirmed critical incidents only), check success and
255
+ * response-time stats. `series: true` (periods up to 7d) adds
256
+ * `response_time_series` — buckets of `series_bucket_seconds` (300
257
+ * for 24h, 900 for 7d) on a real time axis, oldest first. */
258
+ uptime: (id, period, opts) => this.request("GET", `/monitors/${id}/uptime`, {
259
+ query: { period, series: opts?.series ? true : undefined },
260
+ }),
178
261
  /** Recent probe results, newest first. Page with `next_cursor` →
179
262
  * `cursor` (keep the same `hours`/`success`); `locations` is the
180
263
  * per-location breakdown for the whole window. */
181
264
  checks: (id, q) => this.request("GET", `/monitors/${id}/checks`, { query: q }),
265
+ /** One probe run in full, redacted server-side — run_id from checks(). */
266
+ checkDetail: (id, runId) => this.request("GET", `/monitors/${id}/checks/${runId}`),
182
267
  };
183
268
  // ── Alert rules ───────────────────────────────────────────────
184
269
  alertRules = {
185
- /** One probe run in full, redacted server-side — run_id from checks(). */
270
+ /** @deprecated Use `monitors.checkDetail()` — same call. */
186
271
  checkDetail: (id, runId) => this.request("GET", `/monitors/${id}/checks/${runId}`),
187
272
  list: (monitorId) => this.request("GET", `/monitors/${monitorId}/alert-rules`),
188
273
  get: (monitorId, ruleId) => this.request("GET", `/monitors/${monitorId}/alert-rules/${ruleId}`),
@@ -226,12 +311,38 @@ export class WatchFor {
226
311
  exclude: (id, body) => this.request("POST", `/incidents/${id}/exclude`, { body: body ?? {} }),
227
312
  /** Undo `exclude` — the incident counts as downtime again. */
228
313
  include: (id) => this.request("POST", `/incidents/${id}/include`),
314
+ /** Retroactively count a RESOLVED incident as planned maintenance: it
315
+ * leaves uptime and SLA. Returns the maintenance window recorded for
316
+ * it (marking again returns the same one); delete that window to
317
+ * undo. */
318
+ markMaintenance: (id, idempotencyKey) => this.request("POST", `/incidents/${id}/mark-maintenance`, {
319
+ idempotencyKey,
320
+ }),
229
321
  };
230
322
  // ── Status pages, on-call, channels ──────────────────────────
231
323
  statusPages = {
232
324
  list: (q) => this.request("GET", "/status-pages", { query: q }),
233
325
  get: (id) => this.request("GET", `/status-pages/${id}`),
326
+ /** Create a page, optionally with components. Password protection,
327
+ * logo upload and custom subdomains are dashboard-only. */
328
+ create: (body, idempotencyKey) => this.request("POST", "/status-pages", { body, idempotencyKey }),
329
+ /** Partial update; a slug change frees the old URL at once. */
330
+ update: (id, body) => this.request("PATCH", `/status-pages/${id}`, { body }),
331
+ delete: (id) => this.request("DELETE", `/status-pages/${id}`),
332
+ /** Announcements, newest first. */
234
333
  announcements: (id, q) => this.request("GET", `/status-pages/${id}/announcements`, { query: q }),
334
+ getAnnouncement: (id, announcementId) => this.request("GET", `/status-pages/${id}/announcements/${announcementId}`),
335
+ /** Publish an incident notice; `body` becomes the first timeline
336
+ * entry. */
337
+ createAnnouncement: (id, body, idempotencyKey) => this.request("POST", `/status-pages/${id}/announcements`, {
338
+ body,
339
+ idempotencyKey,
340
+ }),
341
+ /** Post an update: appends to the public timeline and moves the
342
+ * status; `resolved` closes it. */
343
+ updateAnnouncement: (id, announcementId, body) => this.request("PATCH", `/status-pages/${id}/announcements/${announcementId}`, { body }),
344
+ /** Remove from the public page (soft delete). */
345
+ deleteAnnouncement: (id, announcementId) => this.request("DELETE", `/status-pages/${id}/announcements/${announcementId}`),
235
346
  };
236
347
  onCall = {
237
348
  get: () => this.request("GET", "/on-call"),
@@ -251,6 +362,7 @@ export class WatchFor {
251
362
  };
252
363
  // ── Maintenance windows ───────────────────────────────────────
253
364
  maintenanceWindows = {
365
+ /** `state` keeps only live windows (active now / upcoming). */
254
366
  list: (q) => this.request("GET", "/maintenance-windows", { query: q }),
255
367
  get: (id) => this.request("GET", `/maintenance-windows/${id}`),
256
368
  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 Organization, 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;
@@ -221,6 +227,26 @@ export interface paths {
221
227
  patch?: never;
222
228
  trace?: never;
223
229
  };
230
+ "/organizations": {
231
+ parameters: {
232
+ query?: never;
233
+ header?: never;
234
+ path?: never;
235
+ cookie?: never;
236
+ };
237
+ /**
238
+ * List the organizations this credential can act on
239
+ * @description OAuth token: every organization the token's user belongs to (oldest membership first, up to 500), with their role in each — send an id as X-WatchFor-Organization to act on it. `is_default` marks the organization used without the header, `is_current` the one this request acted on. API key: exactly its own organization (role null). AI Agent token: only the organization it was issued for. Works without the header and is not plan-gated, so a client can always discover the ids; a header naming an organization the user doesn't belong to is still 403. Not paginated (has_more is always false).
240
+ */
241
+ get: operations["listOrganizations"];
242
+ put?: never;
243
+ post?: never;
244
+ delete?: never;
245
+ options?: never;
246
+ head?: never;
247
+ patch?: never;
248
+ trace?: never;
249
+ };
224
250
  "/openapi.json": {
225
251
  parameters: {
226
252
  query?: never;
@@ -433,7 +459,10 @@ export interface paths {
433
459
  path?: never;
434
460
  cookie?: never;
435
461
  };
436
- /** Uptime (confirmed critical incidents only), check success (reachability, not health) and response-time stats (maintenance excluded) */
462
+ /**
463
+ * Uptime (confirmed critical incidents only), check success (reachability, not health) and response-time stats (maintenance excluded)
464
+ * @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.
465
+ */
437
466
  get: operations["getMonitorUptime"];
438
467
  put?: never;
439
468
  post?: never;
@@ -450,7 +479,10 @@ export interface paths {
450
479
  path?: never;
451
480
  cookie?: never;
452
481
  };
453
- /** Raw check history (cursor-paginated) + per-location breakdown */
482
+ /**
483
+ * Raw check history (cursor-paginated) + per-location breakdown
484
+ * @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.
485
+ */
454
486
  get: operations["listMonitorChecks"];
455
487
  put?: never;
456
488
  post?: never;
@@ -984,7 +1016,10 @@ export interface paths {
984
1016
  path?: never;
985
1017
  cookie?: never;
986
1018
  };
987
- /** Organization audit trail (who changed what, when) */
1019
+ /**
1020
+ * Organization audit trail (who changed what, when)
1021
+ * @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).
1022
+ */
988
1023
  get: operations["listActivity"];
989
1024
  put?: never;
990
1025
  post?: never;
@@ -1055,7 +1090,10 @@ export interface paths {
1055
1090
  path?: never;
1056
1091
  cookie?: never;
1057
1092
  };
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 */
1093
+ /**
1094
+ * 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
1095
+ * @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.
1096
+ */
1059
1097
  get: operations["getReport"];
1060
1098
  put?: never;
1061
1099
  post?: never;
@@ -1247,7 +1285,7 @@ export interface components {
1247
1285
  checks_updated?: number;
1248
1286
  };
1249
1287
  VariablePut: {
1250
- /** @description The value. For an existing secret, omit it to keep the stored one. */
1288
+ /** @description The value; a plain variable can't be empty (400). For an existing secret, omit it to keep the stored one. */
1251
1289
  value?: string;
1252
1290
  /**
1253
1291
  * @description Store encrypted and never show again; masked in logs, errors, traces and screenshots
@@ -1631,7 +1669,7 @@ export interface components {
1631
1669
  description?: string | null;
1632
1670
  interval_seconds?: number;
1633
1671
  /**
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.
1672
+ * @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
1673
  * @enum {string}
1636
1674
  */
1637
1675
  status?: "up" | "degraded" | "down" | "paused" | "unknown";
@@ -1643,11 +1681,14 @@ export interface components {
1643
1681
  */
1644
1682
  ping_url?: string;
1645
1683
  active?: boolean;
1646
- /** @enum {string} */
1684
+ /**
1685
+ * @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.
1686
+ * @enum {string}
1687
+ */
1647
1688
  scheduling_strategy?: "roundrobin" | "random" | "parallel";
1648
1689
  locations?: string[];
1649
1690
  /**
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.
1691
+ * @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
1692
  * @enum {string}
1652
1693
  */
1653
1694
  status_reason?:
@@ -1662,6 +1703,23 @@ export interface components {
1662
1703
  * @description When the open incident behind a critical_incident / warning_incident started; null otherwise.
1663
1704
  */
1664
1705
  status_since?: string | null;
1706
+ /** @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). */
1707
+ alerting_state?: {
1708
+ alerted?: boolean;
1709
+ recovering?: {
1710
+ count?: number;
1711
+ threshold?: number;
1712
+ } | null;
1713
+ failing?: boolean;
1714
+ /** Format: date-time */
1715
+ failing_since?: string | null;
1716
+ confirming?: {
1717
+ count?: number;
1718
+ threshold?: number;
1719
+ } | null;
1720
+ } | null;
1721
+ /** @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. */
1722
+ check_queued?: boolean;
1665
1723
  /** @description The open (firing or acknowledged) incident, or null. When several are open: the critical one, then the earliest started. */
1666
1724
  current_incident?: components["schemas"]["MonitorCurrentIncident"] | null;
1667
1725
  /** @description A silence (dashboard Mute) suppresses notifications; incidents still open and close and checks continue. */
@@ -1807,6 +1865,7 @@ export interface components {
1807
1865
  /** @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
1866
  locations?: string[];
1809
1867
  /**
1868
+ * @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
1869
  * @default roundrobin
1811
1870
  * @enum {string}
1812
1871
  */
@@ -1833,7 +1892,10 @@ export interface components {
1833
1892
  /** @description null clears the description */
1834
1893
  description?: string | null;
1835
1894
  interval?: number;
1836
- /** @enum {string} */
1895
+ /**
1896
+ * @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.
1897
+ * @enum {string}
1898
+ */
1837
1899
  schedulingStrategy?: "roundrobin" | "random" | "parallel";
1838
1900
  locations?: string[];
1839
1901
  tags?: string[];
@@ -1867,8 +1929,11 @@ export interface components {
1867
1929
  total_checks?: number;
1868
1930
  successful_checks?: number;
1869
1931
  failed_checks?: number;
1932
+ /** @description Latency over successful checks only (a failed check has no response time); null when no check succeeded */
1870
1933
  avg_response_time_ms?: number | null;
1934
+ /** @description Latency over successful checks only (a failed check has no response time); null when no check succeeded */
1871
1935
  min_response_time_ms?: number | null;
1936
+ /** @description Latency over successful checks only (a failed check has no response time); null when no check succeeded */
1872
1937
  max_response_time_ms?: number | null;
1873
1938
  last_failure_at?: string | null;
1874
1939
  /** @description Incident-based headline uptime for the last 24 hours */
@@ -1888,6 +1953,17 @@ export interface components {
1888
1953
  resolved_at?: string | null;
1889
1954
  downtime_ms?: number;
1890
1955
  }[];
1956
+ /** @description Only with series=true: the width of each response_time_series bucket (300 for 24h, 900 for 7d). */
1957
+ series_bucket_seconds?: number;
1958
+ /** @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). */
1959
+ response_time_series?: {
1960
+ /** Format: date-time */
1961
+ at?: string;
1962
+ checks?: number;
1963
+ failed?: number;
1964
+ avg_ms?: number | null;
1965
+ max_ms?: number | null;
1966
+ }[];
1891
1967
  };
1892
1968
  /** @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
1969
  Check: {
@@ -1953,7 +2029,7 @@ export interface components {
1953
2029
  sitemap_url_count?: number;
1954
2030
  sitemap_broken_urls?: number;
1955
2031
  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 */
2032
+ /** @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
2033
  result?: Record<string, never> | string | null;
1958
2034
  /** @description Size of the stored output before redaction (0 when nothing is stored) */
1959
2035
  result_bytes?: number;
@@ -2329,6 +2405,12 @@ export interface components {
2329
2405
  /** Format: date-time */
2330
2406
  updated_at?: string;
2331
2407
  };
2408
+ MaintenanceMarking: {
2409
+ /** @enum {string} */
2410
+ object: "maintenance_marking";
2411
+ incident_id: number;
2412
+ maintenance_window: components["schemas"]["MaintenanceWindow"];
2413
+ };
2332
2414
  MaintenanceWindow: {
2333
2415
  /** Format: uuid */
2334
2416
  id?: string;
@@ -2465,7 +2547,10 @@ export interface components {
2465
2547
  * @default true
2466
2548
  */
2467
2549
  autoPublishIncidents: boolean;
2468
- /** @default false */
2550
+ /**
2551
+ * @description Days before a component's monitor existed show as no data instead of 100 % uptime
2552
+ * @default true
2553
+ */
2469
2554
  dimUntrackedDays: boolean;
2470
2555
  /**
2471
2556
  * @default auto
@@ -2777,6 +2862,31 @@ export interface components {
2777
2862
  /** @enum {string} */
2778
2863
  scope?: "read" | "write";
2779
2864
  };
2865
+ /** @description An organization the credential can act on. Send its id as X-WatchFor-Organization to act on it with an OAuth token. */
2866
+ Organization: {
2867
+ /** Format: uuid */
2868
+ id: string;
2869
+ /** @constant */
2870
+ object: "organization";
2871
+ name: string;
2872
+ slug: string | null;
2873
+ /**
2874
+ * Format: uri
2875
+ * @description Absolute URL of the organization's logo, or null.
2876
+ */
2877
+ logo: string | null;
2878
+ /**
2879
+ * @description The token user's membership role there (decides what they may change, as in the dashboard). null for an API key, which acts for its organization without being a member.
2880
+ * @enum {string|null}
2881
+ */
2882
+ role: "owner" | "admin" | "member" | null;
2883
+ /** @description Name of the organization's current plan. */
2884
+ plan: string;
2885
+ /** @description The organization requests act on when X-WatchFor-Organization is omitted (OAuth: the user's oldest owned organization, else their oldest membership). Always true for an API key's own organization. */
2886
+ is_default: boolean;
2887
+ /** @description The organization THIS request acted on — the one X-WatchFor-Organization named, else the default. */
2888
+ is_current: boolean;
2889
+ };
2780
2890
  MonitorType: {
2781
2891
  /** @constant */
2782
2892
  object?: "monitor_type";
@@ -2836,7 +2946,7 @@ export interface components {
2836
2946
  Summary: {
2837
2947
  /** @constant */
2838
2948
  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). */
2949
+ /** @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
2950
  monitors?: {
2841
2951
  total?: number;
2842
2952
  up?: number;
@@ -3063,6 +3173,12 @@ export interface components {
3063
3173
  /** @description Names checks read that no variable defines */
3064
3174
  undefined_refs?: string[];
3065
3175
  };
3176
+ OrganizationList: {
3177
+ /** @constant */
3178
+ object: "list";
3179
+ data: components["schemas"]["Organization"][];
3180
+ has_more: boolean;
3181
+ };
3066
3182
  MonitorTypeList: {
3067
3183
  /** @constant */
3068
3184
  object: "list";
@@ -3093,9 +3209,12 @@ export interface components {
3093
3209
  * @description Alias of success_percent
3094
3210
  */
3095
3211
  uptime_percent?: number;
3096
- avg_response_time_ms?: number;
3097
- min_response_time_ms?: number;
3098
- max_response_time_ms?: number;
3212
+ /** @description Latency over successful checks only (a failed check has no response time); null when no check succeeded at this location */
3213
+ avg_response_time_ms?: number | null;
3214
+ /** @description Latency over successful checks only (a failed check has no response time); null when no check succeeded at this location */
3215
+ min_response_time_ms?: number | null;
3216
+ /** @description Latency over successful checks only (a failed check has no response time); null when no check succeeded at this location */
3217
+ max_response_time_ms?: number | null;
3099
3218
  }[];
3100
3219
  /** @description Pass as ?cursor= for the next (older) page; null on the last page */
3101
3220
  next_cursor?: string | null;
@@ -3362,7 +3481,10 @@ export interface components {
3362
3481
  };
3363
3482
  };
3364
3483
  responses: never;
3365
- parameters: never;
3484
+ parameters: {
3485
+ /** @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). */
3486
+ OrganizationHeader: string;
3487
+ };
3366
3488
  requestBodies: never;
3367
3489
  headers: never;
3368
3490
  pathItems: never;
@@ -3823,6 +3945,35 @@ export interface operations {
3823
3945
  };
3824
3946
  };
3825
3947
  };
3948
+ listOrganizations: {
3949
+ parameters: {
3950
+ query?: never;
3951
+ header?: never;
3952
+ path?: never;
3953
+ cookie?: never;
3954
+ };
3955
+ requestBody?: never;
3956
+ responses: {
3957
+ /** @description OK */
3958
+ 200: {
3959
+ headers: {
3960
+ [name: string]: unknown;
3961
+ };
3962
+ content: {
3963
+ "application/json": components["schemas"]["OrganizationList"];
3964
+ };
3965
+ };
3966
+ /** @description Error */
3967
+ default: {
3968
+ headers: {
3969
+ [name: string]: unknown;
3970
+ };
3971
+ content: {
3972
+ "application/json": components["schemas"]["Error"];
3973
+ };
3974
+ };
3975
+ };
3976
+ };
3826
3977
  getOpenApiSpec: {
3827
3978
  parameters: {
3828
3979
  query?: never;
@@ -3912,7 +4063,7 @@ export interface operations {
3912
4063
  /** @description Opaque cursor from the previous page's next_cursor */
3913
4064
  cursor?: string;
3914
4065
  type?: string;
3915
- /** @description Effective status: down = confirmed critical incident open; degraded = failed check not yet confirmed, or an open warning incident */
4066
+ /** @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
4067
  status?: "up" | "degraded" | "down" | "paused" | "unknown";
3917
4068
  tag?: string;
3918
4069
  /** @description Case-insensitive substring search over name and target */
@@ -4347,6 +4498,8 @@ export interface operations {
4347
4498
  parameters: {
4348
4499
  query?: {
4349
4500
  period?: "1h" | "24h" | "7d" | "30d" | "90d";
4501
+ /** @description true adds response_time_series (bucketed response times on a real time axis) — periods up to 7d */
4502
+ series?: boolean;
4350
4503
  };
4351
4504
  header?: never;
4352
4505
  path: {
@@ -4380,6 +4533,7 @@ export interface operations {
4380
4533
  listMonitorChecks: {
4381
4534
  parameters: {
4382
4535
  query?: {
4536
+ /** @description Window in hours, cut to the plan's check history when it reaches further (see X-History-Clamped) */
4383
4537
  hours?: number;
4384
4538
  /** @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
4539
  limit?: number;
@@ -4424,7 +4578,7 @@ export interface operations {
4424
4578
  path: {
4425
4579
  /** @description Resource id (UUID) */
4426
4580
  id: string;
4427
- /** @description The check's run_id as listed by GET /monitors/{id}/checks (opaque; malformed → 400, unknown for this monitor → 404) */
4581
+ /** @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
4582
  run_id: string;
4429
4583
  };
4430
4584
  cookie?: never;
@@ -4911,21 +5065,23 @@ export interface operations {
4911
5065
  };
4912
5066
  requestBody?: never;
4913
5067
  responses: {
4914
- /** @description Incident marked as maintenance */
5068
+ /** @description Already marked: the existing maintenance window */
4915
5069
  200: {
4916
5070
  headers: {
4917
5071
  [name: string]: unknown;
4918
5072
  };
4919
5073
  content: {
4920
- "application/json": components["schemas"]["Incident"];
5074
+ "application/json": components["schemas"]["MaintenanceMarking"];
4921
5075
  };
4922
5076
  };
4923
- /** @description Marked; returns the maintenance window */
5077
+ /** @description Marked: the maintenance window created for it */
4924
5078
  201: {
4925
5079
  headers: {
4926
5080
  [name: string]: unknown;
4927
5081
  };
4928
- content?: never;
5082
+ content: {
5083
+ "application/json": components["schemas"]["MaintenanceMarking"];
5084
+ };
4929
5085
  };
4930
5086
  /** @description Error */
4931
5087
  default: {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "watchfor",
3
- "version": "0.14.0",
3
+ "version": "0.16.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",