@deliverd/sdk 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/dev.ts ADDED
@@ -0,0 +1,213 @@
1
+ import type { ApprovalData } from "./types.js";
2
+
3
+ /**
4
+ * Development mode: the whole loop, on your machine, with nobody in it.
5
+ *
6
+ * ```ts
7
+ * const deliverd = new Deliverd({ mode: "development" });
8
+ * const decision = await deliverd.approve({ title: "Deploy production" });
9
+ * ```
10
+ *
11
+ * No key, no network, no colleague to interrupt — and the four things that
12
+ * can happen to a real request all reachable before you have an account:
13
+ * approved, rejected, nobody answered, and somebody asked you a question.
14
+ * That last one is the path people forget to write, which is exactly why it
15
+ * should be one line to try.
16
+ *
17
+ * Implemented as a stand-in `fetch` rather than a branch inside the client,
18
+ * so development mode runs the *same* code as production — the same retries,
19
+ * the same error mapping, the same polling in `wait()`. A simulator that
20
+ * bypassed all that would prove your integration works against the simulator.
21
+ */
22
+
23
+ export type DevelopmentOutcome = "approved" | "rejected" | "timeout" | "question";
24
+
25
+ export interface DevelopmentOptions {
26
+ /**
27
+ * What the imaginary approver does. Default `approved`, or the value of
28
+ * `DELIVERD_DEV_OUTCOME`, so a whole test suite can be flipped from the
29
+ * command line without touching the code.
30
+ */
31
+ outcome?: DevelopmentOutcome | ((request: ApprovalData) => DevelopmentOutcome);
32
+ /** How long they take to do it, in milliseconds. Default 0. */
33
+ delay?: number;
34
+ /** What they say. Defaults suit the outcome. */
35
+ note?: string;
36
+ /** What they ask, when the outcome is `question`. */
37
+ question?: string;
38
+ /** Print what the approver would have seen. Default true. */
39
+ log?: boolean;
40
+ }
41
+
42
+ const DEFAULT_QUESTION = "Has this been through staging?";
43
+
44
+ let counter = 0;
45
+
46
+ interface Stored {
47
+ data: ApprovalData;
48
+ /** When the imaginary approver acts. */
49
+ decideAt: number;
50
+ outcome: DevelopmentOutcome;
51
+ options: DevelopmentOptions;
52
+ }
53
+
54
+ /**
55
+ * A `fetch` that serves the approvals API from memory.
56
+ *
57
+ * Deliberately narrow: it answers the calls the primitives make and 501s the
58
+ * rest, with a message saying so, rather than pretending to be the whole API
59
+ * and quietly returning something plausible.
60
+ */
61
+ export function developmentFetch(options: DevelopmentOptions = {}): typeof globalThis.fetch {
62
+ const store = new Map<string, Stored>();
63
+
64
+ return (async (input: string | URL | Request, init?: RequestInit) => {
65
+ const url = new URL(String(input));
66
+ const path = url.pathname.replace(/^\/api\/v1/, "");
67
+ const method = (init?.method ?? "GET").toUpperCase();
68
+ const body = init?.body ? (JSON.parse(String(init.body)) as Record<string, unknown>) : {};
69
+
70
+ const json = (payload: unknown, status = 200) =>
71
+ new Response(JSON.stringify(payload), {
72
+ status,
73
+ headers: { "content-type": "application/json" },
74
+ });
75
+
76
+ if (method === "POST" && path === "/approvals") {
77
+ const id = `apr_dev_${++counter}`;
78
+ const outcome = resolveOutcome(options.outcome, body);
79
+ const data: ApprovalData = {
80
+ id,
81
+ status: "pending",
82
+ url: `https://deliverd.dev/approve/${id}`,
83
+ title: String(body.title ?? "Untitled"),
84
+ description: (body.description as string | undefined) ?? null,
85
+ risk: (body.risk as ApprovalData["risk"] | undefined) ?? "medium",
86
+ factors: (body.factors as ApprovalData["factors"]) ?? [],
87
+ links: (body.links as ApprovalData["links"]) ?? [],
88
+ reportId: (body.reportId as string | undefined) ?? null,
89
+ externalId: (body.externalId as string | undefined) ?? null,
90
+ metadata: (body.metadata as Record<string, unknown>) ?? {},
91
+ requestedBy: "You (development mode)",
92
+ approvers: (body.approvers as string[] | undefined) ?? [],
93
+ decidedBy: null,
94
+ decidedAt: null,
95
+ note: null,
96
+ expiresAt: (body.expiresAt as string | undefined) ?? null,
97
+ questions:
98
+ outcome === "question"
99
+ ? [
100
+ {
101
+ id: `q_dev_${counter}`,
102
+ question: options.question ?? DEFAULT_QUESTION,
103
+ answer: null,
104
+ askedAt: new Date().toISOString(),
105
+ answeredAt: null,
106
+ },
107
+ ]
108
+ : [],
109
+ createdAt: new Date().toISOString(),
110
+ };
111
+ store.set(id, {
112
+ data,
113
+ decideAt: Date.now() + (options.delay ?? 0),
114
+ outcome,
115
+ options,
116
+ });
117
+ if (options.log !== false) announce(data, outcome);
118
+ return json(data, 201);
119
+ }
120
+
121
+ const match = /^\/approvals\/([^/]+)(\/answers|\/cancel)?$/.exec(path);
122
+ if (match) {
123
+ const stored = store.get(match[1]!);
124
+ if (!stored) {
125
+ return json({ error: { code: "not_found", message: "No such approval in this development session." } }, 404);
126
+ }
127
+ if (match[2] === "/answers") {
128
+ const question = stored.data.questions.find((q) => q.id === body.questionId);
129
+ if (!question) {
130
+ return json({ error: { code: "question_not_found", message: "No such question." } }, 404);
131
+ }
132
+ question.answer = String(body.answer);
133
+ question.answeredAt = new Date().toISOString();
134
+ // Answered: the imaginary approver is satisfied and approves.
135
+ stored.outcome = "approved";
136
+ stored.decideAt = Date.now() + (stored.options.delay ?? 0);
137
+ if (stored.options.log !== false) {
138
+ console.log(` ↳ answered: ${question.answer}\n`);
139
+ }
140
+ return json(stored.data);
141
+ }
142
+ if (match[2] === "/cancel") {
143
+ stored.data.status = "cancelled";
144
+ return json(stored.data);
145
+ }
146
+ settle(stored);
147
+ return json(stored.data);
148
+ }
149
+
150
+ return json(
151
+ {
152
+ error: {
153
+ code: "not_in_development_mode",
154
+ message: `Development mode simulates approvals only, and something called ${method} ${path}. Use a real API key for the rest of the API.`,
155
+ },
156
+ },
157
+ 501
158
+ );
159
+ }) as typeof globalThis.fetch;
160
+ }
161
+
162
+ function resolveOutcome(
163
+ outcome: DevelopmentOptions["outcome"],
164
+ body: Record<string, unknown>
165
+ ): DevelopmentOutcome {
166
+ const fromEnv = process.env.DELIVERD_DEV_OUTCOME as DevelopmentOutcome | undefined;
167
+ const chosen = outcome ?? fromEnv ?? "approved";
168
+ return typeof chosen === "function" ? chosen(body as unknown as ApprovalData) : chosen;
169
+ }
170
+
171
+ /** Move a pending request to its outcome once the imaginary approver has had time. */
172
+ function settle(stored: Stored): void {
173
+ if (stored.data.status !== "pending") return;
174
+ if (Date.now() < stored.decideAt) return;
175
+ if (stored.outcome === "timeout") return;
176
+ if (stored.outcome === "question" && stored.data.questions.some((q) => !q.answer)) return;
177
+
178
+ stored.data.status = stored.outcome === "rejected" ? "rejected" : "approved";
179
+ stored.data.decidedBy = "approver@development.invalid";
180
+ stored.data.decidedAt = new Date().toISOString();
181
+ stored.data.note =
182
+ stored.options.note ??
183
+ (stored.data.status === "rejected" ? "Not yet — development mode says no." : null);
184
+ }
185
+
186
+ /**
187
+ * What the approver would have seen, in the terminal.
188
+ *
189
+ * The reason this is worth the lines: the title and the factors are copy
190
+ * somebody has to read on a phone at nine at night, and the only way to know
191
+ * whether it reads well is to see it written out.
192
+ */
193
+ function announce(data: ApprovalData, outcome: DevelopmentOutcome): void {
194
+ const lines = [
195
+ "",
196
+ " ┌─ Deliverd · development mode ─────────────────────────",
197
+ ` │ ${data.title}`,
198
+ ];
199
+ if (data.description) lines.push(` │ ${data.description}`);
200
+ lines.push(` │ Risk: ${data.risk}`);
201
+ for (const factor of data.factors) {
202
+ const mark = factor.status === "ok" ? "✓" : factor.status === "warning" ? "⚠" : "·";
203
+ lines.push(` │ ${mark} ${factor.label}`);
204
+ }
205
+ if (data.approvers.length > 0) lines.push(` │ To: ${data.approvers.join(", ")}`);
206
+ lines.push(
207
+ " │",
208
+ ` │ Simulating: ${outcome}${outcome === "question" ? " (needs an onQuestion handler)" : ""}`,
209
+ " └───────────────────────────────────────────────────────",
210
+ ""
211
+ );
212
+ console.log(lines.join("\n"));
213
+ }
@@ -0,0 +1,21 @@
1
+ /**
2
+ * `expiresIn: "4h"` rather than an ISO timestamp the caller has to compute.
3
+ *
4
+ * Milliseconds are accepted too, because a number is what a timer takes and
5
+ * making somebody write `"3600000ms"` would be the kind of ceremony this SDK
6
+ * exists to remove.
7
+ */
8
+ export type Duration = number | `${number}${"s" | "m" | "h" | "d"}`;
9
+
10
+ const UNITS = { s: 1_000, m: 60_000, h: 3_600_000, d: 86_400_000 } as const;
11
+
12
+ export function durationMs(value: Duration): number {
13
+ if (typeof value === "number") return value;
14
+ const match = /^(\d+(?:\.\d+)?)([smhd])$/.exec(value.trim());
15
+ if (!match) {
16
+ throw new TypeError(
17
+ `Could not read "${value}" as a duration. Use a number of milliseconds, or a string like "30m", "4h" or "2d".`
18
+ );
19
+ }
20
+ return Number(match[1]) * UNITS[match[2] as keyof typeof UNITS];
21
+ }
package/src/errors.ts ADDED
@@ -0,0 +1,62 @@
1
+ import { explain } from "./messages.js";
2
+
3
+ /**
4
+ * Every failure the SDK raises, with the API's own code on it.
5
+ *
6
+ * One class rather than a hierarchy: callers branch on `code`, which is the
7
+ * string the API document lists, and a `instanceof` tree would make that the
8
+ * second way to ask the same question. The helpers below name the handful of
9
+ * cases worth branching on so nobody has to memorise the codes.
10
+ */
11
+ export class DeliverdError extends Error {
12
+ /** The one thing to do next, when we know it. Also the tail of `message`. */
13
+ readonly hint?: string;
14
+
15
+ constructor(
16
+ /** HTTP status, or 0 when the request never got a response. */
17
+ public readonly status: number,
18
+ /** The API's error code: `not_found`, `rate_limited`, `self_approval`… */
19
+ public readonly code: string,
20
+ message: string,
21
+ /** Whatever the API attached — validation issues, the unknown approvers. */
22
+ public readonly details?: unknown,
23
+ options?: { cause?: unknown }
24
+ ) {
25
+ const explained = explain(code, message);
26
+ super(explained.message, options);
27
+ this.name = "DeliverdError";
28
+ this.hint = explained.hint;
29
+ }
30
+
31
+ /** The key is missing, wrong, or lacks the scope the call needs. */
32
+ get isAuth(): boolean {
33
+ return this.status === 401 || this.status === 403;
34
+ }
35
+
36
+ /** Slow down; the client already retried and gave up. */
37
+ get isRateLimit(): boolean {
38
+ return this.status === 429;
39
+ }
40
+
41
+ /** Nothing there, or nothing this key may see. */
42
+ get isNotFound(): boolean {
43
+ return this.status === 404;
44
+ }
45
+
46
+ /**
47
+ * The request was fine and the state was not: someone published between
48
+ * your read and your write, a version is awaiting approval, a question was
49
+ * already answered. Re-read and try again.
50
+ */
51
+ get isConflict(): boolean {
52
+ return this.status === 409;
53
+ }
54
+ }
55
+
56
+ /** Thrown when a wait is abandoned rather than answered. */
57
+ export class DeliverdTimeoutError extends DeliverdError {
58
+ constructor(message: string) {
59
+ super(0, "timeout", message);
60
+ this.name = "DeliverdTimeoutError";
61
+ }
62
+ }
package/src/http.ts ADDED
@@ -0,0 +1,185 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { DeliverdError } from "./errors.js";
3
+
4
+ /**
5
+ * The one place a request is made.
6
+ *
7
+ * No dependencies: Node 20 has `fetch`, and an SDK that drags a request
8
+ * library into every agent runtime for the sake of four verbs is a tax on
9
+ * everyone who installs it.
10
+ *
11
+ * Retries are deliberately narrow. A 429 or a 5xx or a dropped connection is
12
+ * worth repeating; a 4xx is the API saying the request itself is wrong, and it
13
+ * will be just as wrong in a second. `Retry-After` is honoured when the server
14
+ * sends one, because guessing against a server that has told you the answer is
15
+ * how a client turns a rate limit into an outage.
16
+ */
17
+
18
+ export interface ClientOptions {
19
+ /** A `dlv_` key from Settings → API tokens, or an OAuth access token. */
20
+ apiKey: string;
21
+ /** Override for self-hosted or preview deployments. */
22
+ baseUrl?: string;
23
+ /** Attempts for a retryable failure, the first included. Default 3. */
24
+ maxRetries?: number;
25
+ /** Per-request timeout in milliseconds. Default 30000. */
26
+ timeout?: number;
27
+ /** Swapped in tests; defaults to the global. */
28
+ fetch?: typeof globalThis.fetch;
29
+ }
30
+
31
+ export const DEFAULT_BASE_URL = "https://deliverd.dev";
32
+
33
+ interface RequestOptions {
34
+ method: string;
35
+ path: string;
36
+ body?: unknown;
37
+ query?: Record<string, string | number | undefined>;
38
+ signal?: AbortSignal;
39
+ }
40
+
41
+ const sleep = (ms: number, signal?: AbortSignal) =>
42
+ new Promise<void>((resolve, reject) => {
43
+ if (signal?.aborted) return reject(abortError(signal));
44
+ const timer = setTimeout(() => {
45
+ signal?.removeEventListener("abort", onAbort);
46
+ resolve();
47
+ }, ms);
48
+ const onAbort = () => {
49
+ clearTimeout(timer);
50
+ reject(abortError(signal!));
51
+ };
52
+ signal?.addEventListener("abort", onAbort, { once: true });
53
+ });
54
+
55
+ function abortError(signal: AbortSignal): DeliverdError {
56
+ return new DeliverdError(0, "aborted", "The request was aborted.", undefined, {
57
+ cause: signal.reason,
58
+ });
59
+ }
60
+
61
+ /** Exponential from 500ms with jitter, so a fleet of agents does not resonate. */
62
+ function backoffMs(attempt: number): number {
63
+ const base = Math.min(8000, 500 * 2 ** (attempt - 1));
64
+ return base / 2 + Math.random() * (base / 2);
65
+ }
66
+
67
+ export class HttpClient {
68
+ readonly baseUrl: string;
69
+ private readonly apiKey: string;
70
+ private readonly maxRetries: number;
71
+ private readonly timeout: number;
72
+ private readonly doFetch: typeof globalThis.fetch;
73
+
74
+ constructor(options: ClientOptions) {
75
+ if (!options.apiKey) {
76
+ throw new DeliverdError(0, "no_api_key", "An apiKey is required.");
77
+ }
78
+ this.apiKey = options.apiKey;
79
+ this.baseUrl = (options.baseUrl ?? DEFAULT_BASE_URL).replace(/\/+$/, "");
80
+ this.maxRetries = Math.max(1, options.maxRetries ?? 3);
81
+ this.timeout = options.timeout ?? 30_000;
82
+ this.doFetch = options.fetch ?? globalThis.fetch;
83
+ }
84
+
85
+ async request<T>(options: RequestOptions): Promise<T> {
86
+ const url = new URL(`${this.baseUrl}/api/v1${options.path}`);
87
+ for (const [key, value] of Object.entries(options.query ?? {})) {
88
+ if (value !== undefined) url.searchParams.set(key, String(value));
89
+ }
90
+
91
+ const correlationId = randomUUID();
92
+ let lastError: DeliverdError | undefined;
93
+ for (let attempt = 1; attempt <= this.maxRetries; attempt++) {
94
+ if (attempt > 1) await sleep(lastError ? retryDelay(lastError, attempt) : backoffMs(attempt), options.signal);
95
+
96
+ // The caller's signal and our own timeout, whichever fires first.
97
+ const timer = AbortSignal.timeout(this.timeout);
98
+ const signal = options.signal ? AbortSignal.any([options.signal, timer]) : timer;
99
+
100
+ let response: Response;
101
+ try {
102
+ response = await this.doFetch(url, {
103
+ method: options.method,
104
+ headers: {
105
+ Authorization: `Bearer ${this.apiKey}`,
106
+ Accept: "application/json",
107
+ "User-Agent": USER_AGENT,
108
+ // One id per logical request, kept across retries: it is the
109
+ // thing to quote when something went wrong, and generating it
110
+ // here means nobody has to remember to.
111
+ "deliverd-correlation-id": correlationId,
112
+ ...(options.body !== undefined ? { "Content-Type": "application/json" } : {}),
113
+ },
114
+ body: options.body !== undefined ? JSON.stringify(options.body) : undefined,
115
+ signal,
116
+ });
117
+ } catch (cause) {
118
+ if (options.signal?.aborted) throw abortError(options.signal);
119
+ lastError = new DeliverdError(0, "network_error", describeNetworkError(cause), undefined, { cause });
120
+ if (attempt === this.maxRetries) throw lastError;
121
+ continue;
122
+ }
123
+
124
+ if (response.status === 204) return undefined as T;
125
+
126
+ const text = await response.text();
127
+ let json: unknown;
128
+ try {
129
+ json = text ? JSON.parse(text) : {};
130
+ } catch {
131
+ lastError = new DeliverdError(
132
+ response.status,
133
+ "invalid_response",
134
+ `Expected JSON from ${url.pathname} and got ${text.slice(0, 120)}`
135
+ );
136
+ if (isRetryable(response.status) && attempt < this.maxRetries) continue;
137
+ throw lastError;
138
+ }
139
+
140
+ if (response.ok) return json as T;
141
+
142
+ const envelope = (json as { error?: { code?: string; message?: string; details?: unknown } }).error;
143
+ lastError = new DeliverdError(
144
+ response.status,
145
+ envelope?.code ?? "error",
146
+ envelope?.message ?? `Request failed (${response.status})`,
147
+ envelope?.details
148
+ );
149
+ (lastError as { retryAfter?: number }).retryAfter = parseRetryAfter(response.headers.get("retry-after"));
150
+ if (isRetryable(response.status) && attempt < this.maxRetries) continue;
151
+ throw lastError;
152
+ }
153
+ throw lastError ?? new DeliverdError(0, "error", "Request failed.");
154
+ }
155
+ }
156
+
157
+ export const USER_AGENT = "deliverd-sdk";
158
+
159
+ /** 429 and 5xx only: a 4xx will be just as wrong on the next attempt. */
160
+ function isRetryable(status: number): boolean {
161
+ return status === 429 || status >= 500;
162
+ }
163
+
164
+ function parseRetryAfter(header: string | null): number | undefined {
165
+ if (!header) return undefined;
166
+ const seconds = Number(header);
167
+ if (Number.isFinite(seconds)) return seconds * 1000;
168
+ const date = Date.parse(header);
169
+ return Number.isFinite(date) ? Math.max(0, date - Date.now()) : undefined;
170
+ }
171
+
172
+ function retryDelay(error: DeliverdError, attempt: number): number {
173
+ const after = (error as { retryAfter?: number }).retryAfter;
174
+ return after !== undefined ? after : backoffMs(attempt);
175
+ }
176
+
177
+ /**
178
+ * A dropped connection says nothing useful on its own, and the first thing
179
+ * anyone wonders is whether they typed the host wrong.
180
+ */
181
+ function describeNetworkError(cause: unknown): string {
182
+ const message = cause instanceof Error ? cause.message : String(cause);
183
+ if (/timed? ?out|TimeoutError/i.test(message)) return `The request timed out: ${message}`;
184
+ return `Could not reach Deliverd: ${message}`;
185
+ }
package/src/index.ts ADDED
@@ -0,0 +1,212 @@
1
+ import { HttpClient, type ClientOptions } from "./http.js";
2
+ import { Approvals, FAST_POLL_SCHEDULE, type WaitOptions } from "./approvals.js";
3
+ import { Comments, Reports } from "./reports.js";
4
+ import { Webhooks } from "./webhooks.js";
5
+ import { developmentFetch, type DevelopmentOptions } from "./dev.js";
6
+ import { durationMs, type Duration } from "./duration.js";
7
+ import { DeliverdError } from "./errors.js";
8
+ import type {
9
+ CreateApprovalInput,
10
+ Decision,
11
+ PublishReportInput,
12
+ PublishResult,
13
+ } from "./types.js";
14
+
15
+ export { Approval, Approvals, POLL_SCHEDULE, type WaitOptions } from "./approvals.js";
16
+ export { Comments, Reports } from "./reports.js";
17
+ export {
18
+ constructEvent,
19
+ DELIVERY_HEADER,
20
+ EVENT_HEADER,
21
+ SIGNATURE_HEADER,
22
+ TOLERANCE_SECONDS,
23
+ verifySignature,
24
+ Webhooks,
25
+ } from "./webhooks.js";
26
+ export { DeliverdError, DeliverdTimeoutError } from "./errors.js";
27
+ export { DEFAULT_BASE_URL, type ClientOptions } from "./http.js";
28
+ export { durationMs, type Duration } from "./duration.js";
29
+ export type { DevelopmentOptions, DevelopmentOutcome } from "./dev.js";
30
+ export type * from "./types.js";
31
+
32
+ /** How long a request waits for a person before it expires, unless you say. */
33
+ export const DEFAULT_EXPIRY: Duration = "24h";
34
+
35
+ export interface DeliverdOptions extends Partial<ClientOptions> {
36
+ /**
37
+ * `development` runs the whole loop on this machine: no key, no network,
38
+ * nobody interrupted. Defaults to `development` when `DELIVERD_MODE` says
39
+ * so, and to `live` otherwise.
40
+ */
41
+ mode?: "live" | "development";
42
+ development?: DevelopmentOptions;
43
+ }
44
+
45
+ /** Everything `approve()` takes, plus the conveniences it adds on top. */
46
+ export interface ApproveOptions extends Omit<CreateApprovalInput, "expiresAt"> {
47
+ /** `"4h"`, `"30m"`, `"2d"`, or milliseconds. Default 24 hours. */
48
+ expiresIn?: Duration;
49
+ /** An exact moment instead, if you have one. */
50
+ expiresAt?: string;
51
+ /**
52
+ * Answer a question the approver asks, without leaving the wait. Return a
53
+ * string and it is posted; return null to leave it for a person.
54
+ */
55
+ onQuestion?: WaitOptions["onQuestion"];
56
+ /** Called after each poll — a progress line in a CLI. */
57
+ onPoll?: WaitOptions["onPoll"];
58
+ /** Give up waiting after this. The request stays open until it expires. */
59
+ timeout?: Duration;
60
+ signal?: AbortSignal;
61
+ /**
62
+ * With an `externalId`, reuse an existing request rather than filing a
63
+ * second one. On by default, so restarting a crashed agent does not ask
64
+ * twice. See `approvals.findByExternalId` for exactly how far that goes.
65
+ */
66
+ reuse?: boolean;
67
+ }
68
+
69
+ /**
70
+ * Deliverd: you build the action, Deliverd handles the human.
71
+ *
72
+ * ```ts
73
+ * import { deliverd } from "@deliverd/sdk";
74
+ *
75
+ * const decision = await deliverd.approve({ title: "Deploy to production" });
76
+ * if (decision.approved) await deploy();
77
+ * ```
78
+ *
79
+ * That is the whole integration. What it stands in for: an approval page, the
80
+ * emails and the reminders, identity and single sign-on, who is allowed to
81
+ * decide, a table to keep it in, an audit trail, and the dashboard somebody
82
+ * uses to do it. None of that is yours to build.
83
+ *
84
+ * With no arguments the key comes from `DELIVERD_API_KEY`. Before you have
85
+ * one, `new Deliverd({ mode: "development" })` runs the same code with an
86
+ * imaginary approver.
87
+ */
88
+ export class Deliverd {
89
+ readonly approvals: Approvals;
90
+ readonly reports: Reports;
91
+ readonly comments: Comments;
92
+ readonly webhooks: Webhooks;
93
+ readonly http: HttpClient;
94
+ /** Whether an imaginary approver is deciding these. */
95
+ readonly development: boolean;
96
+
97
+ constructor(options: DeliverdOptions = {}) {
98
+ const mode = options.mode ?? (process.env.DELIVERD_MODE === "development" ? "development" : "live");
99
+ this.development = mode === "development";
100
+
101
+ this.http = new HttpClient({
102
+ ...options,
103
+ // A key is not needed when nothing leaves the machine.
104
+ apiKey: options.apiKey ?? process.env.DELIVERD_API_KEY ?? (this.development ? "dlv_development" : ""),
105
+ baseUrl: options.baseUrl ?? process.env.DELIVERD_BASE_URL,
106
+ fetch: this.development ? developmentFetch(options.development) : options.fetch,
107
+ });
108
+
109
+ this.approvals = new Approvals(this.http);
110
+ this.reports = new Reports(this.http);
111
+ this.comments = new Comments(this.http);
112
+ this.webhooks = new Webhooks();
113
+ }
114
+
115
+ /**
116
+ * Ask a person, and wait for the answer.
117
+ *
118
+ * Resolves when they decide — including when they say no, because a refusal
119
+ * is an answer and `if (decision.approved)` is the line that follows. It
120
+ * throws only when the wait itself failed: a timeout, an abort, or an API
121
+ * that could not be reached.
122
+ *
123
+ * Requests expire after a day unless you say otherwise, so a wait always
124
+ * ends.
125
+ */
126
+ async approve(options: ApproveOptions): Promise<Decision> {
127
+ const { expiresIn, timeout, onQuestion, onPoll, signal, reuse, ...input } = options;
128
+
129
+ if (input.externalId && reuse !== false) {
130
+ const existing = await this.approvals.findByExternalId(input.externalId, signal);
131
+ if (existing) {
132
+ const settled = await existing.wait({
133
+ onQuestion,
134
+ onPoll,
135
+ signal,
136
+ timeout: durationOrUndefined(timeout),
137
+ ...(this.development ? { pollIntervals: FAST_POLL_SCHEDULE } : {}),
138
+ });
139
+ return settled.toDecision();
140
+ }
141
+ }
142
+
143
+ const approval = await this.approvals.create(
144
+ {
145
+ ...input,
146
+ expiresAt: options.expiresAt ?? new Date(Date.now() + durationMs(expiresIn ?? DEFAULT_EXPIRY)).toISOString(),
147
+ },
148
+ signal
149
+ );
150
+ const settled = await approval.wait({
151
+ onQuestion,
152
+ onPoll,
153
+ signal,
154
+ /*
155
+ * In development the approver is imaginary and instant, so a wait still
156
+ * running after a moment is a path that will never settle — a question
157
+ * with nothing to answer it, usually. Ending it quickly turns that into
158
+ * a message; leaving it turns it into a hung test suite. Two seconds
159
+ * rather than five, because five is what a test runner gives a whole
160
+ * test and losing the race to it reports the wrong failure.
161
+ */
162
+ timeout: durationOrUndefined(timeout) ?? (this.development ? 2_000 : undefined),
163
+ ...(this.development ? { pollIntervals: FAST_POLL_SCHEDULE } : {}),
164
+ });
165
+ return settled.toDecision();
166
+ }
167
+
168
+ /**
169
+ * A yes or no on something small: same mechanism, lower ceremony.
170
+ *
171
+ * Low risk and an hour to answer, because that is what "are you sure?"
172
+ * means — if it deserves a day and a paragraph of evidence, it deserves
173
+ * `approve()`.
174
+ */
175
+ async confirm(options: ApproveOptions): Promise<boolean> {
176
+ const decision = await this.approve({ risk: "low", expiresIn: "1h", ...options });
177
+ return decision.approved;
178
+ }
179
+
180
+ /** Publish HTML to a secure URL. The other half of the product, one call in. */
181
+ publish(input: PublishReportInput, signal?: AbortSignal): Promise<PublishResult> {
182
+ return this.reports.publish(input, signal);
183
+ }
184
+ }
185
+
186
+ function durationOrUndefined(value: Duration | undefined): number | undefined {
187
+ return value === undefined ? undefined : durationMs(value);
188
+ }
189
+
190
+ /**
191
+ * A client that builds itself from the environment the first time you touch
192
+ * it, so the shortest integration has no setup line at all:
193
+ *
194
+ * ```ts
195
+ * import { deliverd } from "@deliverd/sdk";
196
+ * await deliverd.approve({ title: "Deploy production" });
197
+ * ```
198
+ *
199
+ * Lazy rather than eager: a module that threw at import time because an
200
+ * environment variable was missing would take a whole process down for a call
201
+ * nobody made yet.
202
+ */
203
+ let singleton: Deliverd | undefined;
204
+ export const deliverd: Deliverd = new Proxy({} as Deliverd, {
205
+ get(_target, property, receiver) {
206
+ singleton ??= new Deliverd();
207
+ const value = Reflect.get(singleton, property, singleton);
208
+ return typeof value === "function" ? value.bind(singleton) : value;
209
+ },
210
+ });
211
+
212
+ export default Deliverd;