@deliverd/sdk 0.9.0 → 0.10.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/index.ts CHANGED
@@ -1,444 +1,444 @@
1
- import { HttpClient, type ClientOptions } from "./http.js";
2
- import { Approvals, FAST_POLL_SCHEDULE, type WaitOptions } from "./approvals.js";
3
- import { Gates, type GateOptions } from "./gates.js";
4
- import { Comments, Reports, Schedules } from "./reports.js";
5
- import { Reviews, type ReviewWaitOptions } from "./reviews.js";
6
- import { Collections, type CollectWaitOptions } from "./collections.js";
7
- import { Flows } from "./flows.js";
8
- import { Webhooks } from "./webhooks.js";
9
- import { developmentFetch, type DevelopmentOptions } from "./dev.js";
10
- import { durationMs, type Duration } from "./duration.js";
11
- import { DeliverdError } from "./errors.js";
12
- import type {
13
- CollectedAnswers,
14
- CreateApprovalInput,
15
- CreateCollectionInput,
16
- CreateReviewInput,
17
- Decision,
18
- GateDecision,
19
- PublishReportInput,
20
- PublishResult,
21
- ReviewOutcome,
22
- } from "./types.js";
23
-
24
- export { Approval, Approvals, POLL_SCHEDULE, type WaitOptions } from "./approvals.js";
25
- export { Gate, Gates, type GateOptions, type GateWaitOptions } from "./gates.js";
26
- export { Comments, Reports, Schedules } from "./reports.js";
27
- export { Review, Reviews, type ReviewWaitOptions } from "./reviews.js";
28
- export { Collection, Collections, type CollectWaitOptions } from "./collections.js";
29
- export { Flow, Flows, type FlowPrimitives } from "./flows.js";
30
- export {
31
- constructCallback,
32
- constructEvent,
33
- DELIVERY_HEADER,
34
- EVENT_HEADER,
35
- SIGNATURE_HEADER,
36
- TOLERANCE_SECONDS,
37
- verifySignature,
38
- Webhooks,
39
- } from "./webhooks.js";
40
- export { DeliverdError, DeliverdTimeoutError } from "./errors.js";
41
- export { DEFAULT_BASE_URL, type ClientOptions } from "./http.js";
42
- export { durationMs, type Duration } from "./duration.js";
43
- export type { DevelopmentOptions, DevelopmentOutcome } from "./dev.js";
44
- export type * from "./types.js";
45
-
46
- /** How long a request waits for a person before it expires, unless you say. */
47
- export const DEFAULT_EXPIRY: Duration = "24h";
48
-
49
- export interface DeliverdOptions extends Partial<ClientOptions> {
50
- /**
51
- * `development` runs the whole loop on this machine: no key, no network,
52
- * nobody interrupted. Defaults to `development` when `DELIVERD_MODE` says
53
- * so, and to `live` otherwise.
54
- */
55
- mode?: "live" | "development";
56
- development?: DevelopmentOptions;
57
- }
58
-
59
- /** Everything `approve()` takes, plus the conveniences it adds on top. */
60
- export interface ApproveOptions extends Omit<CreateApprovalInput, "expiresAt"> {
61
- /** `"4h"`, `"30m"`, `"2d"`, or milliseconds. Default 24 hours. */
62
- expiresIn?: Duration;
63
- /** An exact moment instead, if you have one. */
64
- expiresAt?: string;
65
- /**
66
- * Answer a question the approver asks, without leaving the wait. Return a
67
- * string and it is posted; return null to leave it for a person.
68
- */
69
- onQuestion?: WaitOptions["onQuestion"];
70
- /** Called after each poll — a progress line in a CLI. */
71
- onPoll?: WaitOptions["onPoll"];
72
- /** Give up waiting after this. The request stays open until it expires. */
73
- timeout?: Duration;
74
- signal?: AbortSignal;
75
- /**
76
- * With an `externalId`, reuse an existing request rather than filing a
77
- * second one. On by default, so restarting a crashed agent does not ask
78
- * twice. See `approvals.findByExternalId` for exactly how far that goes.
79
- */
80
- reuse?: boolean;
81
- }
82
-
83
- /** Everything `review()` takes, plus the conveniences it adds on top. */
84
- export interface ReviewOptions extends Omit<CreateReviewInput, "expiresAt"> {
85
- /** `"4h"`, `"30m"`, `"2d"`, or milliseconds. Default 24 hours. */
86
- expiresIn?: Duration;
87
- /** An exact moment instead, if you have one. */
88
- expiresAt?: string;
89
- /** Called after each poll — a progress line in a CLI. */
90
- onPoll?: ReviewWaitOptions["onPoll"];
91
- /** Give up waiting after this. The review stays open until it expires. */
92
- timeout?: Duration;
93
- signal?: AbortSignal;
94
- /**
95
- * With an `externalId`, reuse an existing review rather than filing a
96
- * second one, so a restarted agent does not ask the same people twice.
97
- */
98
- reuse?: boolean;
99
- }
100
-
101
- /** Everything `collect()` takes, plus the conveniences it adds on top. */
102
- export interface CollectOptions extends Omit<CreateCollectionInput, "expiresAt"> {
103
- /** `"4h"`, `"30m"`, `"2d"`, or milliseconds. Default 24 hours. */
104
- expiresIn?: Duration;
105
- /** An exact moment instead, if you have one. */
106
- expiresAt?: string;
107
- /** Called after each poll — a progress line in a CLI. */
108
- onPoll?: CollectWaitOptions["onPoll"];
109
- /** Give up waiting after this. The request stays open until it expires. */
110
- timeout?: Duration;
111
- signal?: AbortSignal;
112
- /**
113
- * With an `externalId`, reuse an existing request rather than filing a
114
- * second one, so a restarted agent does not ask the same people twice.
115
- */
116
- reuse?: boolean;
117
- }
118
-
119
- /**
120
- * Deliverd: you build the action, Deliverd handles the human.
121
- *
122
- * ```ts
123
- * import { deliverd } from "@deliverd/sdk";
124
- *
125
- * const decision = await deliverd.approve({ title: "Deploy to production" });
126
- * if (decision.approved) await deploy();
127
- * ```
128
- *
129
- * That is the whole integration. What it stands in for: an approval page, the
130
- * emails and the reminders, identity and single sign-on, who is allowed to
131
- * decide, a table to keep it in, an audit trail, and the dashboard somebody
132
- * uses to do it. None of that is yours to build.
133
- *
134
- * With no arguments the key comes from `DELIVERD_API_KEY`. Before you have
135
- * one, `new Deliverd({ mode: "development" })` runs the same code with an
136
- * imaginary approver.
137
- */
138
- export class Deliverd {
139
- readonly approvals: Approvals;
140
- readonly gates: Gates;
141
- readonly reviews: Reviews;
142
- readonly collections: Collections;
143
- readonly flows: Flows;
144
- readonly reports: Reports;
145
- readonly comments: Comments;
146
- readonly schedules: Schedules;
147
- readonly webhooks: Webhooks;
148
- readonly http: HttpClient;
149
- /** Whether an imaginary approver is deciding these. */
150
- readonly development: boolean;
151
-
152
- constructor(options: DeliverdOptions = {}) {
153
- const mode = options.mode ?? (process.env.DELIVERD_MODE === "development" ? "development" : "live");
154
- this.development = mode === "development";
155
-
156
- this.http = new HttpClient({
157
- ...options,
158
- // A key is not needed when nothing leaves the machine.
159
- apiKey: options.apiKey ?? process.env.DELIVERD_API_KEY ?? (this.development ? "dlv_development" : ""),
160
- baseUrl: options.baseUrl ?? process.env.DELIVERD_BASE_URL,
161
- fetch: this.development ? developmentFetch(options.development) : options.fetch,
162
- });
163
-
164
- this.approvals = new Approvals(this.http);
165
- this.gates = new Gates(this.http);
166
- this.reviews = new Reviews(this.http);
167
- this.collections = new Collections(this.http);
168
- /*
169
- * The handle takes the client so `flow.approve()` is the same call as
170
- * `deliverd.approve()` with the flow filled in, rather than a second
171
- * implementation that can drift from it.
172
- */
173
- this.flows = new Flows(this.http, this);
174
- this.reports = new Reports(this.http);
175
- this.comments = new Comments(this.http);
176
- this.schedules = new Schedules(this.http);
177
- this.webhooks = new Webhooks();
178
- }
179
-
180
- /**
181
- * Ask a person, and wait for the answer.
182
- *
183
- * Resolves when they decide — including when they say no, because a refusal
184
- * is an answer and `if (decision.approved)` is the line that follows. It
185
- * throws only when the wait itself failed: a timeout, an abort, or an API
186
- * that could not be reached.
187
- *
188
- * Requests expire after a day unless you say otherwise, so a wait always
189
- * ends.
190
- */
191
- async approve(options: ApproveOptions): Promise<Decision> {
192
- const { expiresIn, timeout, onQuestion, onPoll, signal, reuse, ...input } = options;
193
-
194
- if (input.externalId && reuse !== false) {
195
- const existing = await this.approvals.findByExternalId(input.externalId, signal);
196
- if (existing) {
197
- const settled = await existing.wait({
198
- onQuestion,
199
- onPoll,
200
- signal,
201
- timeout: durationOrUndefined(timeout),
202
- ...(this.development ? { pollIntervals: FAST_POLL_SCHEDULE } : {}),
203
- });
204
- return settled.toDecision();
205
- }
206
- }
207
-
208
- const approval = await this.approvals.create(
209
- {
210
- ...input,
211
- expiresAt: options.expiresAt ?? new Date(Date.now() + durationMs(expiresIn ?? DEFAULT_EXPIRY)).toISOString(),
212
- },
213
- signal
214
- );
215
- const settled = await approval.wait({
216
- onQuestion,
217
- onPoll,
218
- signal,
219
- /*
220
- * In development the approver is imaginary and instant, so a wait still
221
- * running after a moment is a path that will never settle — a question
222
- * with nothing to answer it, usually. Ending it quickly turns that into
223
- * a message; leaving it turns it into a hung test suite. Two seconds
224
- * rather than five, because five is what a test runner gives a whole
225
- * test and losing the race to it reports the wrong failure.
226
- */
227
- timeout: durationOrUndefined(timeout) ?? (this.development ? 2_000 : undefined),
228
- ...(this.development ? { pollIntervals: FAST_POLL_SCHEDULE } : {}),
229
- });
230
- return settled.toDecision();
231
- }
232
-
233
- /**
234
- * Ask whether to act, and wait if a person has to decide.
235
- *
236
- * The other primitives ask a person to look at work already done. This one
237
- * asks first, and the answer comes from **policy the developer does not
238
- * own** — which is the whole point: what needs a human is an organisation's
239
- * decision, not a line in your code. Most calls never reach a person at all,
240
- * because a rule already settles them.
241
- *
242
- * ```ts
243
- * const decision = await deliverd.gate({
244
- * action: "finance.refund",
245
- * externalId: `refund:${order.id}`,
246
- * input: { customer_id: order.customerId, amount: 1240, currency: "GBP" },
247
- * });
248
- * if (!decision.allowed) return;
249
- * await stripe.refunds.create(decision.input);
250
- * ```
251
- *
252
- * **Execute with `decision.input`, not your own object.** It is what the
253
- * action's schema validated and what an approver actually saw. Passing the
254
- * original works right up until somebody edits a value before approving, and
255
- * then it spends an approval for £1200 on a refund of £1240.
256
- *
257
- * It does not throw on a refusal — a no is an answer, and `if
258
- * (decision.allowed)` is the line that follows. It throws when the action is
259
- * not registered, when the input does not match its schema, or when the wait
260
- * itself failed.
261
- *
262
- * `wait: false` returns a pending decision immediately; `deliverd.gates`
263
- * is the same thing with the handle exposed.
264
- */
265
- async gate(options: GateOptions): Promise<GateDecision> {
266
- const { action, timeout, onPoll, signal, wait, pollIntervals, ...rest } = options;
267
- const gate = await this.gates.create({ actionId: action, ...rest }, signal);
268
-
269
- /*
270
- * No wait when the caller said not to, and none when there is nothing to
271
- * wait for — a rule that allowed or denied it has already answered, which
272
- * is the common case and must not cost a poll.
273
- */
274
- if (wait === false || !gate.pending) return gate.toDecision();
275
-
276
- const settled = await gate.wait({
277
- onPoll,
278
- signal,
279
- /* The same reasoning as `approve()`: an imaginary approver is instant, so
280
- * a wait still running after a moment is one that never settles. */
281
- timeout: durationOrUndefined(timeout) ?? (this.development ? 2_000 : undefined),
282
- ...(pollIntervals ? { pollIntervals } : this.development ? { pollIntervals: FAST_POLL_SCHEDULE } : {}),
283
- });
284
- return settled.toDecision();
285
- }
286
-
287
- /**
288
- * A yes or no on something small: same mechanism, lower ceremony.
289
- *
290
- * Low risk and an hour to answer, because that is what "are you sure?"
291
- * means — if it deserves a day and a paragraph of evidence, it deserves
292
- * `approve()`.
293
- */
294
- async confirm(options: ApproveOptions): Promise<boolean> {
295
- const decision = await this.approve({ risk: "low", expiresIn: "1h", ...options });
296
- return decision.approved;
297
- }
298
-
299
- /**
300
- * Ask people to read what you made, and wait for their answer.
301
- *
302
- * The other half of judgement. `approve()` asks permission before you act;
303
- * this asks whether what you already produced is right, and comes back with
304
- * the reviewers' verdicts and a count of the comment threads they opened.
305
- *
306
- * ```ts
307
- * const outcome = await deliverd.review({
308
- * title: "Q3 board pack",
309
- * reportId: report.id,
310
- * instructions: "Check the figures against the ledger.",
311
- * reviewers: ["partner@firm.example"],
312
- * });
313
- * if (!outcome.approved) await revise(outcome.verdicts);
314
- * ```
315
- *
316
- * Resolves on changes requested as well as approval, because that is an
317
- * answer — usually the more useful one. Reviews expire after a day unless
318
- * you say otherwise, so a wait always ends.
319
- */
320
- async review(options: ReviewOptions): Promise<ReviewOutcome> {
321
- const { expiresIn, timeout, onPoll, signal, reuse, ...input } = options;
322
-
323
- if (input.externalId && reuse !== false) {
324
- const existing = await this.reviews.findByExternalId(input.externalId, signal);
325
- if (existing) {
326
- const settled = await existing.wait({
327
- onPoll,
328
- signal,
329
- timeout: durationOrUndefined(timeout),
330
- ...(this.development ? { pollIntervals: FAST_POLL_SCHEDULE } : {}),
331
- });
332
- return settled.toOutcome();
333
- }
334
- }
335
-
336
- const review = await this.reviews.create(
337
- {
338
- ...input,
339
- expiresAt:
340
- options.expiresAt ??
341
- new Date(Date.now() + durationMs(expiresIn ?? DEFAULT_EXPIRY)).toISOString(),
342
- },
343
- signal
344
- );
345
- const settled = await review.wait({
346
- onPoll,
347
- signal,
348
- // Same reasoning as approve(): in development the reviewer is imaginary
349
- // and instant, so a wait still running after a moment will never settle.
350
- timeout: durationOrUndefined(timeout) ?? (this.development ? 2_000 : undefined),
351
- ...(this.development ? { pollIntervals: FAST_POLL_SCHEDULE } : {}),
352
- });
353
- return settled.toOutcome();
354
- }
355
-
356
- /**
357
- * Ask people for what you do not have, and wait for it.
358
- *
359
- * `approve()` asks permission, `review()` asks judgement, and this asks for
360
- * a fact — a figure, a date, a choice between options, the sentence only
361
- * they can write.
362
- *
363
- * ```ts
364
- * const { answers } = await deliverd.collect({
365
- * title: "Before I file the Q3 return",
366
- * respondents: ["finance@firm.example"],
367
- * questions: [
368
- * { prompt: "Headcount at 30 September", kind: "number" },
369
- * { prompt: "Any disposals in the quarter?", kind: "boolean" },
370
- * ],
371
- * });
372
- * ```
373
- *
374
- * `answers` is keyed by the question you asked. Check `complete` before you
375
- * use it: a request that expired has whatever arrived and no more, and the
376
- * thing you do without the figure is usually not the thing you do with it.
377
- */
378
- async collect(options: CollectOptions): Promise<CollectedAnswers> {
379
- const { expiresIn, timeout, onPoll, signal, reuse, ...input } = options;
380
-
381
- if (input.externalId && reuse !== false) {
382
- const existing = await this.collections.findByExternalId(input.externalId, signal);
383
- if (existing) {
384
- const settled = await existing.wait({
385
- onPoll,
386
- signal,
387
- timeout: durationOrUndefined(timeout),
388
- ...(this.development ? { pollIntervals: FAST_POLL_SCHEDULE } : {}),
389
- });
390
- return settled.toCollected();
391
- }
392
- }
393
-
394
- const collection = await this.collections.create(
395
- {
396
- ...input,
397
- expiresAt:
398
- options.expiresAt ??
399
- new Date(Date.now() + durationMs(expiresIn ?? DEFAULT_EXPIRY)).toISOString(),
400
- },
401
- signal
402
- );
403
- const settled = await collection.wait({
404
- onPoll,
405
- signal,
406
- timeout: durationOrUndefined(timeout) ?? (this.development ? 2_000 : undefined),
407
- ...(this.development ? { pollIntervals: FAST_POLL_SCHEDULE } : {}),
408
- });
409
- return settled.toCollected();
410
- }
411
-
412
- /** Publish HTML to a secure URL. The other half of the product, one call in. */
413
- publish(input: PublishReportInput, signal?: AbortSignal): Promise<PublishResult> {
414
- return this.reports.publish(input, signal);
415
- }
416
- }
417
-
418
- function durationOrUndefined(value: Duration | undefined): number | undefined {
419
- return value === undefined ? undefined : durationMs(value);
420
- }
421
-
422
- /**
423
- * A client that builds itself from the environment the first time you touch
424
- * it, so the shortest integration has no setup line at all:
425
- *
426
- * ```ts
427
- * import { deliverd } from "@deliverd/sdk";
428
- * await deliverd.approve({ title: "Deploy production" });
429
- * ```
430
- *
431
- * Lazy rather than eager: a module that threw at import time because an
432
- * environment variable was missing would take a whole process down for a call
433
- * nobody made yet.
434
- */
435
- let singleton: Deliverd | undefined;
436
- export const deliverd: Deliverd = new Proxy({} as Deliverd, {
437
- get(_target, property, receiver) {
438
- singleton ??= new Deliverd();
439
- const value = Reflect.get(singleton, property, singleton);
440
- return typeof value === "function" ? value.bind(singleton) : value;
441
- },
442
- });
443
-
444
- export default Deliverd;
1
+ import { HttpClient, type ClientOptions } from "./http.js";
2
+ import { Approvals, FAST_POLL_SCHEDULE, type WaitOptions } from "./approvals.js";
3
+ import { Gates, type GateOptions } from "./gates.js";
4
+ import { Comments, Reports, Schedules } from "./reports.js";
5
+ import { Reviews, type ReviewWaitOptions } from "./reviews.js";
6
+ import { Collections, type CollectWaitOptions } from "./collections.js";
7
+ import { Flows } from "./flows.js";
8
+ import { Webhooks } from "./webhooks.js";
9
+ import { developmentFetch, type DevelopmentOptions } from "./dev.js";
10
+ import { durationMs, type Duration } from "./duration.js";
11
+ import { DeliverdError } from "./errors.js";
12
+ import type {
13
+ CollectedAnswers,
14
+ CreateApprovalInput,
15
+ CreateCollectionInput,
16
+ CreateReviewInput,
17
+ Decision,
18
+ GateDecision,
19
+ PublishReportInput,
20
+ PublishResult,
21
+ ReviewOutcome,
22
+ } from "./types.js";
23
+
24
+ export { Approval, Approvals, POLL_SCHEDULE, type WaitOptions } from "./approvals.js";
25
+ export { Gate, Gates, type GateOptions, type GateWaitOptions } from "./gates.js";
26
+ export { Comments, Reports, Schedules } from "./reports.js";
27
+ export { Review, Reviews, type ReviewWaitOptions } from "./reviews.js";
28
+ export { Collection, Collections, type CollectWaitOptions } from "./collections.js";
29
+ export { Flow, Flows, type FlowPrimitives } from "./flows.js";
30
+ export {
31
+ constructCallback,
32
+ constructEvent,
33
+ DELIVERY_HEADER,
34
+ EVENT_HEADER,
35
+ SIGNATURE_HEADER,
36
+ TOLERANCE_SECONDS,
37
+ verifySignature,
38
+ Webhooks,
39
+ } from "./webhooks.js";
40
+ export { DeliverdError, DeliverdTimeoutError } from "./errors.js";
41
+ export { DEFAULT_BASE_URL, type ClientOptions } from "./http.js";
42
+ export { durationMs, type Duration } from "./duration.js";
43
+ export type { DevelopmentOptions, DevelopmentOutcome } from "./dev.js";
44
+ export type * from "./types.js";
45
+
46
+ /** How long a request waits for a person before it expires, unless you say. */
47
+ export const DEFAULT_EXPIRY: Duration = "24h";
48
+
49
+ export interface DeliverdOptions extends Partial<ClientOptions> {
50
+ /**
51
+ * `development` runs the whole loop on this machine: no key, no network,
52
+ * nobody interrupted. Defaults to `development` when `DELIVERD_MODE` says
53
+ * so, and to `live` otherwise.
54
+ */
55
+ mode?: "live" | "development";
56
+ development?: DevelopmentOptions;
57
+ }
58
+
59
+ /** Everything `approve()` takes, plus the conveniences it adds on top. */
60
+ export interface ApproveOptions extends Omit<CreateApprovalInput, "expiresAt"> {
61
+ /** `"4h"`, `"30m"`, `"2d"`, or milliseconds. Default 24 hours. */
62
+ expiresIn?: Duration;
63
+ /** An exact moment instead, if you have one. */
64
+ expiresAt?: string;
65
+ /**
66
+ * Answer a question the approver asks, without leaving the wait. Return a
67
+ * string and it is posted; return null to leave it for a person.
68
+ */
69
+ onQuestion?: WaitOptions["onQuestion"];
70
+ /** Called after each poll — a progress line in a CLI. */
71
+ onPoll?: WaitOptions["onPoll"];
72
+ /** Give up waiting after this. The request stays open until it expires. */
73
+ timeout?: Duration;
74
+ signal?: AbortSignal;
75
+ /**
76
+ * With an `externalId`, reuse an existing request rather than filing a
77
+ * second one. On by default, so restarting a crashed agent does not ask
78
+ * twice. See `approvals.findByExternalId` for exactly how far that goes.
79
+ */
80
+ reuse?: boolean;
81
+ }
82
+
83
+ /** Everything `review()` takes, plus the conveniences it adds on top. */
84
+ export interface ReviewOptions extends Omit<CreateReviewInput, "expiresAt"> {
85
+ /** `"4h"`, `"30m"`, `"2d"`, or milliseconds. Default 24 hours. */
86
+ expiresIn?: Duration;
87
+ /** An exact moment instead, if you have one. */
88
+ expiresAt?: string;
89
+ /** Called after each poll — a progress line in a CLI. */
90
+ onPoll?: ReviewWaitOptions["onPoll"];
91
+ /** Give up waiting after this. The review stays open until it expires. */
92
+ timeout?: Duration;
93
+ signal?: AbortSignal;
94
+ /**
95
+ * With an `externalId`, reuse an existing review rather than filing a
96
+ * second one, so a restarted agent does not ask the same people twice.
97
+ */
98
+ reuse?: boolean;
99
+ }
100
+
101
+ /** Everything `collect()` takes, plus the conveniences it adds on top. */
102
+ export interface CollectOptions extends Omit<CreateCollectionInput, "expiresAt"> {
103
+ /** `"4h"`, `"30m"`, `"2d"`, or milliseconds. Default 24 hours. */
104
+ expiresIn?: Duration;
105
+ /** An exact moment instead, if you have one. */
106
+ expiresAt?: string;
107
+ /** Called after each poll — a progress line in a CLI. */
108
+ onPoll?: CollectWaitOptions["onPoll"];
109
+ /** Give up waiting after this. The request stays open until it expires. */
110
+ timeout?: Duration;
111
+ signal?: AbortSignal;
112
+ /**
113
+ * With an `externalId`, reuse an existing request rather than filing a
114
+ * second one, so a restarted agent does not ask the same people twice.
115
+ */
116
+ reuse?: boolean;
117
+ }
118
+
119
+ /**
120
+ * Deliverd: you build the action, Deliverd handles the human.
121
+ *
122
+ * ```ts
123
+ * import { deliverd } from "@deliverd/sdk";
124
+ *
125
+ * const decision = await deliverd.approve({ title: "Deploy to production" });
126
+ * if (decision.approved) await deploy();
127
+ * ```
128
+ *
129
+ * That is the whole integration. What it stands in for: an approval page, the
130
+ * emails and the reminders, identity and single sign-on, who is allowed to
131
+ * decide, a table to keep it in, an audit trail, and the dashboard somebody
132
+ * uses to do it. None of that is yours to build.
133
+ *
134
+ * With no arguments the key comes from `DELIVERD_API_KEY`. Before you have
135
+ * one, `new Deliverd({ mode: "development" })` runs the same code with an
136
+ * imaginary approver.
137
+ */
138
+ export class Deliverd {
139
+ readonly approvals: Approvals;
140
+ readonly gates: Gates;
141
+ readonly reviews: Reviews;
142
+ readonly collections: Collections;
143
+ readonly flows: Flows;
144
+ readonly reports: Reports;
145
+ readonly comments: Comments;
146
+ readonly schedules: Schedules;
147
+ readonly webhooks: Webhooks;
148
+ readonly http: HttpClient;
149
+ /** Whether an imaginary approver is deciding these. */
150
+ readonly development: boolean;
151
+
152
+ constructor(options: DeliverdOptions = {}) {
153
+ const mode = options.mode ?? (process.env.DELIVERD_MODE === "development" ? "development" : "live");
154
+ this.development = mode === "development";
155
+
156
+ this.http = new HttpClient({
157
+ ...options,
158
+ // A key is not needed when nothing leaves the machine.
159
+ apiKey: options.apiKey ?? process.env.DELIVERD_API_KEY ?? (this.development ? "dlv_development" : ""),
160
+ baseUrl: options.baseUrl ?? process.env.DELIVERD_BASE_URL,
161
+ fetch: this.development ? developmentFetch(options.development) : options.fetch,
162
+ });
163
+
164
+ this.approvals = new Approvals(this.http);
165
+ this.gates = new Gates(this.http);
166
+ this.reviews = new Reviews(this.http);
167
+ this.collections = new Collections(this.http);
168
+ /*
169
+ * The handle takes the client so `flow.approve()` is the same call as
170
+ * `deliverd.approve()` with the flow filled in, rather than a second
171
+ * implementation that can drift from it.
172
+ */
173
+ this.flows = new Flows(this.http, this);
174
+ this.reports = new Reports(this.http);
175
+ this.comments = new Comments(this.http);
176
+ this.schedules = new Schedules(this.http);
177
+ this.webhooks = new Webhooks();
178
+ }
179
+
180
+ /**
181
+ * Ask a person, and wait for the answer.
182
+ *
183
+ * Resolves when they decide — including when they say no, because a refusal
184
+ * is an answer and `if (decision.approved)` is the line that follows. It
185
+ * throws only when the wait itself failed: a timeout, an abort, or an API
186
+ * that could not be reached.
187
+ *
188
+ * Requests expire after a day unless you say otherwise, so a wait always
189
+ * ends.
190
+ */
191
+ async approve(options: ApproveOptions): Promise<Decision> {
192
+ const { expiresIn, timeout, onQuestion, onPoll, signal, reuse, ...input } = options;
193
+
194
+ if (input.externalId && reuse !== false) {
195
+ const existing = await this.approvals.findByExternalId(input.externalId, signal);
196
+ if (existing) {
197
+ const settled = await existing.wait({
198
+ onQuestion,
199
+ onPoll,
200
+ signal,
201
+ timeout: durationOrUndefined(timeout),
202
+ ...(this.development ? { pollIntervals: FAST_POLL_SCHEDULE } : {}),
203
+ });
204
+ return settled.toDecision();
205
+ }
206
+ }
207
+
208
+ const approval = await this.approvals.create(
209
+ {
210
+ ...input,
211
+ expiresAt: options.expiresAt ?? new Date(Date.now() + durationMs(expiresIn ?? DEFAULT_EXPIRY)).toISOString(),
212
+ },
213
+ signal
214
+ );
215
+ const settled = await approval.wait({
216
+ onQuestion,
217
+ onPoll,
218
+ signal,
219
+ /*
220
+ * In development the approver is imaginary and instant, so a wait still
221
+ * running after a moment is a path that will never settle — a question
222
+ * with nothing to answer it, usually. Ending it quickly turns that into
223
+ * a message; leaving it turns it into a hung test suite. Two seconds
224
+ * rather than five, because five is what a test runner gives a whole
225
+ * test and losing the race to it reports the wrong failure.
226
+ */
227
+ timeout: durationOrUndefined(timeout) ?? (this.development ? 2_000 : undefined),
228
+ ...(this.development ? { pollIntervals: FAST_POLL_SCHEDULE } : {}),
229
+ });
230
+ return settled.toDecision();
231
+ }
232
+
233
+ /**
234
+ * Ask whether to act, and wait if a person has to decide.
235
+ *
236
+ * The other primitives ask a person to look at work already done. This one
237
+ * asks first, and the answer comes from **policy the developer does not
238
+ * own** — which is the whole point: what needs a human is an organisation's
239
+ * decision, not a line in your code. Most calls never reach a person at all,
240
+ * because a rule already settles them.
241
+ *
242
+ * ```ts
243
+ * const decision = await deliverd.gate({
244
+ * action: "finance.refund",
245
+ * externalId: `refund:${order.id}`,
246
+ * input: { customer_id: order.customerId, amount: 1240, currency: "GBP" },
247
+ * });
248
+ * if (!decision.allowed) return;
249
+ * await stripe.refunds.create(decision.input);
250
+ * ```
251
+ *
252
+ * **Execute with `decision.input`, not your own object.** It is what the
253
+ * action's schema validated and what an approver actually saw. Passing the
254
+ * original works right up until somebody edits a value before approving, and
255
+ * then it spends an approval for £1200 on a refund of £1240.
256
+ *
257
+ * It does not throw on a refusal — a no is an answer, and `if
258
+ * (decision.allowed)` is the line that follows. It throws when the action is
259
+ * not registered, when the input does not match its schema, or when the wait
260
+ * itself failed.
261
+ *
262
+ * `wait: false` returns a pending decision immediately; `deliverd.gates`
263
+ * is the same thing with the handle exposed.
264
+ */
265
+ async gate(options: GateOptions): Promise<GateDecision> {
266
+ const { action, timeout, onPoll, signal, wait, pollIntervals, ...rest } = options;
267
+ const gate = await this.gates.create({ actionId: action, ...rest }, signal);
268
+
269
+ /*
270
+ * No wait when the caller said not to, and none when there is nothing to
271
+ * wait for — a rule that allowed or denied it has already answered, which
272
+ * is the common case and must not cost a poll.
273
+ */
274
+ if (wait === false || !gate.pending) return gate.toDecision();
275
+
276
+ const settled = await gate.wait({
277
+ onPoll,
278
+ signal,
279
+ /* The same reasoning as `approve()`: an imaginary approver is instant, so
280
+ * a wait still running after a moment is one that never settles. */
281
+ timeout: durationOrUndefined(timeout) ?? (this.development ? 2_000 : undefined),
282
+ ...(pollIntervals ? { pollIntervals } : this.development ? { pollIntervals: FAST_POLL_SCHEDULE } : {}),
283
+ });
284
+ return settled.toDecision();
285
+ }
286
+
287
+ /**
288
+ * A yes or no on something small: same mechanism, lower ceremony.
289
+ *
290
+ * Low risk and an hour to answer, because that is what "are you sure?"
291
+ * means — if it deserves a day and a paragraph of evidence, it deserves
292
+ * `approve()`.
293
+ */
294
+ async confirm(options: ApproveOptions): Promise<boolean> {
295
+ const decision = await this.approve({ risk: "low", expiresIn: "1h", ...options });
296
+ return decision.approved;
297
+ }
298
+
299
+ /**
300
+ * Ask people to read what you made, and wait for their answer.
301
+ *
302
+ * The other half of judgement. `approve()` asks permission before you act;
303
+ * this asks whether what you already produced is right, and comes back with
304
+ * the reviewers' verdicts and a count of the comment threads they opened.
305
+ *
306
+ * ```ts
307
+ * const outcome = await deliverd.review({
308
+ * title: "Q3 board pack",
309
+ * reportId: report.id,
310
+ * instructions: "Check the figures against the ledger.",
311
+ * reviewers: ["partner@firm.example"],
312
+ * });
313
+ * if (!outcome.approved) await revise(outcome.verdicts);
314
+ * ```
315
+ *
316
+ * Resolves on changes requested as well as approval, because that is an
317
+ * answer — usually the more useful one. Reviews expire after a day unless
318
+ * you say otherwise, so a wait always ends.
319
+ */
320
+ async review(options: ReviewOptions): Promise<ReviewOutcome> {
321
+ const { expiresIn, timeout, onPoll, signal, reuse, ...input } = options;
322
+
323
+ if (input.externalId && reuse !== false) {
324
+ const existing = await this.reviews.findByExternalId(input.externalId, signal);
325
+ if (existing) {
326
+ const settled = await existing.wait({
327
+ onPoll,
328
+ signal,
329
+ timeout: durationOrUndefined(timeout),
330
+ ...(this.development ? { pollIntervals: FAST_POLL_SCHEDULE } : {}),
331
+ });
332
+ return settled.toOutcome();
333
+ }
334
+ }
335
+
336
+ const review = await this.reviews.create(
337
+ {
338
+ ...input,
339
+ expiresAt:
340
+ options.expiresAt ??
341
+ new Date(Date.now() + durationMs(expiresIn ?? DEFAULT_EXPIRY)).toISOString(),
342
+ },
343
+ signal
344
+ );
345
+ const settled = await review.wait({
346
+ onPoll,
347
+ signal,
348
+ // Same reasoning as approve(): in development the reviewer is imaginary
349
+ // and instant, so a wait still running after a moment will never settle.
350
+ timeout: durationOrUndefined(timeout) ?? (this.development ? 2_000 : undefined),
351
+ ...(this.development ? { pollIntervals: FAST_POLL_SCHEDULE } : {}),
352
+ });
353
+ return settled.toOutcome();
354
+ }
355
+
356
+ /**
357
+ * Ask people for what you do not have, and wait for it.
358
+ *
359
+ * `approve()` asks permission, `review()` asks judgement, and this asks for
360
+ * a fact — a figure, a date, a choice between options, the sentence only
361
+ * they can write.
362
+ *
363
+ * ```ts
364
+ * const { answers } = await deliverd.collect({
365
+ * title: "Before I file the Q3 return",
366
+ * respondents: ["finance@firm.example"],
367
+ * questions: [
368
+ * { prompt: "Headcount at 30 September", kind: "number" },
369
+ * { prompt: "Any disposals in the quarter?", kind: "boolean" },
370
+ * ],
371
+ * });
372
+ * ```
373
+ *
374
+ * `answers` is keyed by the question you asked. Check `complete` before you
375
+ * use it: a request that expired has whatever arrived and no more, and the
376
+ * thing you do without the figure is usually not the thing you do with it.
377
+ */
378
+ async collect(options: CollectOptions): Promise<CollectedAnswers> {
379
+ const { expiresIn, timeout, onPoll, signal, reuse, ...input } = options;
380
+
381
+ if (input.externalId && reuse !== false) {
382
+ const existing = await this.collections.findByExternalId(input.externalId, signal);
383
+ if (existing) {
384
+ const settled = await existing.wait({
385
+ onPoll,
386
+ signal,
387
+ timeout: durationOrUndefined(timeout),
388
+ ...(this.development ? { pollIntervals: FAST_POLL_SCHEDULE } : {}),
389
+ });
390
+ return settled.toCollected();
391
+ }
392
+ }
393
+
394
+ const collection = await this.collections.create(
395
+ {
396
+ ...input,
397
+ expiresAt:
398
+ options.expiresAt ??
399
+ new Date(Date.now() + durationMs(expiresIn ?? DEFAULT_EXPIRY)).toISOString(),
400
+ },
401
+ signal
402
+ );
403
+ const settled = await collection.wait({
404
+ onPoll,
405
+ signal,
406
+ timeout: durationOrUndefined(timeout) ?? (this.development ? 2_000 : undefined),
407
+ ...(this.development ? { pollIntervals: FAST_POLL_SCHEDULE } : {}),
408
+ });
409
+ return settled.toCollected();
410
+ }
411
+
412
+ /** Publish HTML to a secure URL. The other half of the product, one call in. */
413
+ publish(input: PublishReportInput, signal?: AbortSignal): Promise<PublishResult> {
414
+ return this.reports.publish(input, signal);
415
+ }
416
+ }
417
+
418
+ function durationOrUndefined(value: Duration | undefined): number | undefined {
419
+ return value === undefined ? undefined : durationMs(value);
420
+ }
421
+
422
+ /**
423
+ * A client that builds itself from the environment the first time you touch
424
+ * it, so the shortest integration has no setup line at all:
425
+ *
426
+ * ```ts
427
+ * import { deliverd } from "@deliverd/sdk";
428
+ * await deliverd.approve({ title: "Deploy production" });
429
+ * ```
430
+ *
431
+ * Lazy rather than eager: a module that threw at import time because an
432
+ * environment variable was missing would take a whole process down for a call
433
+ * nobody made yet.
434
+ */
435
+ let singleton: Deliverd | undefined;
436
+ export const deliverd: Deliverd = new Proxy({} as Deliverd, {
437
+ get(_target, property, receiver) {
438
+ singleton ??= new Deliverd();
439
+ const value = Reflect.get(singleton, property, singleton);
440
+ return typeof value === "function" ? value.bind(singleton) : value;
441
+ },
442
+ });
443
+
444
+ export default Deliverd;