@deliverd/sdk 0.8.0 → 0.8.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -21
- package/README.md +562 -562
- package/dist/messages.d.ts.map +1 -1
- package/dist/messages.js +84 -5
- package/dist/released.d.ts +1 -1
- package/dist/released.d.ts.map +1 -1
- package/dist/released.js +839 -12
- package/package.json +55 -55
- package/src/approvals.ts +322 -322
- package/src/collections.ts +236 -236
- package/src/dev.ts +761 -761
- package/src/duration.ts +21 -21
- package/src/errors.ts +62 -62
- package/src/flows.ts +222 -222
- package/src/gates.ts +230 -230
- package/src/http.ts +217 -217
- package/src/index.ts +443 -443
- package/src/messages.ts +161 -82
- package/src/paging.ts +64 -64
- package/src/released.ts +2072 -1243
- package/src/reports.ts +490 -490
- package/src/reviews.ts +225 -225
- package/src/types.ts +838 -838
- package/src/webhooks.ts +98 -98
package/src/approvals.ts
CHANGED
|
@@ -1,322 +1,322 @@
|
|
|
1
|
-
import { listOrCollect, type PageOf } from "./paging.js";
|
|
2
|
-
import { DeliverdError, DeliverdTimeoutError } from "./errors.js";
|
|
3
|
-
import type { HttpClient } from "./http.js";
|
|
4
|
-
import { durationMs, type Duration } from "./duration.js";
|
|
5
|
-
import type {
|
|
6
|
-
ApprovalData,
|
|
7
|
-
ApprovalQuestion,
|
|
8
|
-
CreateApprovalInput,
|
|
9
|
-
Decision,
|
|
10
|
-
ListApprovalsInput,
|
|
11
|
-
} from "./types.js";
|
|
12
|
-
|
|
13
|
-
/**
|
|
14
|
-
* Ask a person before you act.
|
|
15
|
-
*
|
|
16
|
-
* The point of this module is one line — `await approval.wait()` — and
|
|
17
|
-
* everything in it exists to make that line safe to write in a real agent:
|
|
18
|
-
* polling that backs off instead of hammering, a question from the approver
|
|
19
|
-
* answered without leaving the wait, and an end that is guaranteed by the
|
|
20
|
-
* request's own expiry rather than by hope.
|
|
21
|
-
*/
|
|
22
|
-
|
|
23
|
-
/**
|
|
24
|
-
* How often to ask, as the wait gets longer. Milliseconds.
|
|
25
|
-
*
|
|
26
|
-
* The first one is deliberately quick. Most approvals take minutes, but the
|
|
27
|
-
* ones that take two seconds are the ones somebody is watching — a demo, a
|
|
28
|
-
* deploy with the approver stood next to you — and a client whose first look
|
|
29
|
-
* is two seconds away makes an instant decision feel like a slow one. One
|
|
30
|
-
* cheap early request buys that, and against a limit of 120 a minute it costs
|
|
31
|
-
* nothing. After a few polls the schedule is somebody's afternoon, not a
|
|
32
|
-
* progress bar.
|
|
33
|
-
*/
|
|
34
|
-
export const POLL_SCHEDULE = [250, 750, 2_000, 4_000, 8_000, 15_000, 30_000] as const;
|
|
35
|
-
const POLL_CEILING = 60_000;
|
|
36
|
-
|
|
37
|
-
/** Development mode: the approver is imaginary and instant, so keep up. */
|
|
38
|
-
export const FAST_POLL_SCHEDULE = [10, 25, 50, 100] as const;
|
|
39
|
-
|
|
40
|
-
function pollDelay(poll: number, schedule: readonly number[]): number {
|
|
41
|
-
const base = schedule[Math.min(poll, schedule.length - 1)] ?? POLL_CEILING;
|
|
42
|
-
// Jitter, so a hundred agents started by the same cron do not arrive together.
|
|
43
|
-
return base * 0.75 + Math.random() * base * 0.5;
|
|
44
|
-
}
|
|
45
|
-
|
|
46
|
-
export interface WaitOptions {
|
|
47
|
-
/**
|
|
48
|
-
* Called when the approver asks the requester something. Return the answer
|
|
49
|
-
* and the wait posts it and carries on; return `null` to leave it for a
|
|
50
|
-
* person. Without this a question simply sits there — the approver is
|
|
51
|
-
* waiting on you, and nothing will move until it is answered or they decide
|
|
52
|
-
* anyway.
|
|
53
|
-
*/
|
|
54
|
-
onQuestion?: (question: ApprovalQuestion, approval: ApprovalData) => Promise<string | null> | string | null;
|
|
55
|
-
/** Called after every poll, for a progress line in a CLI. */
|
|
56
|
-
onPoll?: (approval: ApprovalData) => void;
|
|
57
|
-
/**
|
|
58
|
-
* Give up after this many milliseconds and throw `DeliverdTimeoutError`.
|
|
59
|
-
* Omitted, the wait ends when the request does — which, for a request with
|
|
60
|
-
* no `expiresAt`, may be never. Set one or the other.
|
|
61
|
-
*/
|
|
62
|
-
timeout?: number;
|
|
63
|
-
signal?: AbortSignal;
|
|
64
|
-
/**
|
|
65
|
-
* How long between polls, as the wait lengthens. Rarely worth changing —
|
|
66
|
-
* development mode uses it to keep up with an approver who is instant.
|
|
67
|
-
*/
|
|
68
|
-
pollIntervals?: readonly number[];
|
|
69
|
-
}
|
|
70
|
-
|
|
71
|
-
/**
|
|
72
|
-
* A request, and what you can do with it.
|
|
73
|
-
*
|
|
74
|
-
* The data is a snapshot; `wait()` and `refresh()` replace it in place, so a
|
|
75
|
-
* handle held across a wait reads the settled request rather than the one you
|
|
76
|
-
* created.
|
|
77
|
-
*/
|
|
78
|
-
export class Approval {
|
|
79
|
-
constructor(
|
|
80
|
-
private readonly http: HttpClient,
|
|
81
|
-
private data: ApprovalData
|
|
82
|
-
) {}
|
|
83
|
-
|
|
84
|
-
get id(): string { return this.data.id; }
|
|
85
|
-
get status(): ApprovalData["status"] { return this.data.status; }
|
|
86
|
-
/** The page the approver decides on. Put it in your own UI or logs. */
|
|
87
|
-
get url(): string { return this.data.url; }
|
|
88
|
-
get title(): string { return this.data.title; }
|
|
89
|
-
/** Their reason, when they gave one. */
|
|
90
|
-
get note(): string | null { return this.data.note; }
|
|
91
|
-
/** Who decided, as a name rather than an id. */
|
|
92
|
-
get decidedBy(): string | null { return this.data.decidedBy; }
|
|
93
|
-
get decidedById(): string | null { return this.data.decidedById; }
|
|
94
|
-
get decidedAt(): string | null { return this.data.decidedAt; }
|
|
95
|
-
get questions(): ApprovalQuestion[] { return this.data.questions; }
|
|
96
|
-
/** Questions the approver is still waiting on you to answer. */
|
|
97
|
-
get openQuestions(): ApprovalQuestion[] { return this.data.questions.filter((q) => !q.answer); }
|
|
98
|
-
|
|
99
|
-
/** The one to branch on. False for rejected, expired and cancelled alike. */
|
|
100
|
-
get approved(): boolean { return this.data.status === "approved"; }
|
|
101
|
-
get rejected(): boolean { return this.data.status === "rejected"; }
|
|
102
|
-
get expired(): boolean { return this.data.status === "expired"; }
|
|
103
|
-
get cancelled(): boolean { return this.data.status === "cancelled"; }
|
|
104
|
-
get pending(): boolean { return this.data.status === "pending"; }
|
|
105
|
-
|
|
106
|
-
/** Everything the API returned, if you want a field the getters do not name. */
|
|
107
|
-
toJSON(): ApprovalData { return this.data; }
|
|
108
|
-
|
|
109
|
-
/**
|
|
110
|
-
* The answer, flattened — what `approve()` hands back.
|
|
111
|
-
*
|
|
112
|
-
* `approved` is a boolean so `if (decision.approved)` reads as the sentence
|
|
113
|
-
* it is; `status` is the narrowing union for a switch. Both, because people
|
|
114
|
-
* write both and neither should be the wrong one.
|
|
115
|
-
*/
|
|
116
|
-
toDecision(): Decision {
|
|
117
|
-
const status = this.data.status === "pending" ? "expired" : this.data.status;
|
|
118
|
-
return {
|
|
119
|
-
approved: this.data.status === "approved",
|
|
120
|
-
status,
|
|
121
|
-
note: this.data.note,
|
|
122
|
-
decidedBy: this.data.decidedBy,
|
|
123
|
-
decidedById: this.data.decidedById,
|
|
124
|
-
decidedAt: this.data.decidedAt,
|
|
125
|
-
id: this.data.id,
|
|
126
|
-
url: this.data.url,
|
|
127
|
-
approval: this,
|
|
128
|
-
} as Decision;
|
|
129
|
-
}
|
|
130
|
-
|
|
131
|
-
async refresh(signal?: AbortSignal): Promise<this> {
|
|
132
|
-
this.data = await this.http.request<ApprovalData>({
|
|
133
|
-
method: "GET",
|
|
134
|
-
path: `/approvals/${this.data.id}`,
|
|
135
|
-
signal,
|
|
136
|
-
});
|
|
137
|
-
return this;
|
|
138
|
-
}
|
|
139
|
-
|
|
140
|
-
/** Answer a question the approver asked. Only the requester may. */
|
|
141
|
-
async answer(questionId: string, answer: string, signal?: AbortSignal): Promise<this> {
|
|
142
|
-
this.data = await this.http.request<ApprovalData>({
|
|
143
|
-
method: "POST",
|
|
144
|
-
path: `/approvals/${this.data.id}/answers`,
|
|
145
|
-
body: { questionId, answer },
|
|
146
|
-
signal,
|
|
147
|
-
});
|
|
148
|
-
return this;
|
|
149
|
-
}
|
|
150
|
-
|
|
151
|
-
/** Withdraw it. The row stays as evidence of what was asked and dropped. */
|
|
152
|
-
async cancel(signal?: AbortSignal): Promise<this> {
|
|
153
|
-
this.data = await this.http.request<ApprovalData>({
|
|
154
|
-
method: "POST",
|
|
155
|
-
path: `/approvals/${this.data.id}/cancel`,
|
|
156
|
-
signal,
|
|
157
|
-
});
|
|
158
|
-
return this;
|
|
159
|
-
}
|
|
160
|
-
|
|
161
|
-
/**
|
|
162
|
-
* Block until a person decides, then return.
|
|
163
|
-
*
|
|
164
|
-
* Resolves on approved, rejected, expired and cancelled — it does not throw
|
|
165
|
-
* on a no, because a refusal is an answer and `if (approval.approved)` is
|
|
166
|
-
* the line that should follow. It throws only when the wait itself failed:
|
|
167
|
-
* a timeout, an abort, or the API being unreachable.
|
|
168
|
-
*/
|
|
169
|
-
async wait(options: WaitOptions = {}): Promise<this> {
|
|
170
|
-
const deadline = options.timeout !== undefined ? Date.now() + options.timeout : undefined;
|
|
171
|
-
let poll = 0;
|
|
172
|
-
|
|
173
|
-
// Already settled, or answered between create and wait.
|
|
174
|
-
if (!this.pending) return this;
|
|
175
|
-
|
|
176
|
-
for (;;) {
|
|
177
|
-
if (options.signal?.aborted) {
|
|
178
|
-
throw new DeliverdError(0, "aborted", "The wait was aborted.", undefined, {
|
|
179
|
-
cause: options.signal.reason,
|
|
180
|
-
});
|
|
181
|
-
}
|
|
182
|
-
if (deadline !== undefined && Date.now() >= deadline) {
|
|
183
|
-
/*
|
|
184
|
-
* Say which of the two happened. An approver who asked a question and
|
|
185
|
-
* got no answer has not ignored the request — they are waiting on you,
|
|
186
|
-
* and "nobody decided in time" sends you to look at the wrong end of
|
|
187
|
-
* it. Found by running the quickstart's own instruction to set
|
|
188
|
-
* DELIVERD_DEV_OUTCOME=question, which produced exactly that message.
|
|
189
|
-
*/
|
|
190
|
-
const unanswered = this.data.questions?.find((q) => !q.answer);
|
|
191
|
-
throw new DeliverdTimeoutError(
|
|
192
|
-
unanswered
|
|
193
|
-
? `An approver asked a question about "${this.data.title}" and nothing answered it: ` +
|
|
194
|
-
`"${unanswered.question}". Pass an onQuestion handler, or answer it at ${this.data.url}.`
|
|
195
|
-
: `Nobody decided "${this.data.title}" within the timeout. It is still open at ${this.data.url}.`
|
|
196
|
-
);
|
|
197
|
-
}
|
|
198
|
-
|
|
199
|
-
const delay = pollDelay(poll++, options.pollIntervals ?? POLL_SCHEDULE);
|
|
200
|
-
const remaining = deadline === undefined ? delay : Math.min(delay, deadline - Date.now());
|
|
201
|
-
await wait(Math.max(0, remaining), options.signal);
|
|
202
|
-
|
|
203
|
-
await this.refresh(options.signal);
|
|
204
|
-
options.onPoll?.(this.data);
|
|
205
|
-
|
|
206
|
-
if (options.onQuestion) {
|
|
207
|
-
for (const question of this.openQuestions) {
|
|
208
|
-
const answer = await options.onQuestion(question, this.data);
|
|
209
|
-
if (typeof answer === "string" && answer.trim()) {
|
|
210
|
-
await this.answer(question.id, answer, options.signal);
|
|
211
|
-
}
|
|
212
|
-
}
|
|
213
|
-
}
|
|
214
|
-
|
|
215
|
-
if (!this.pending) return this;
|
|
216
|
-
}
|
|
217
|
-
}
|
|
218
|
-
}
|
|
219
|
-
|
|
220
|
-
function wait(ms: number, signal?: AbortSignal): Promise<void> {
|
|
221
|
-
return new Promise((resolve, reject) => {
|
|
222
|
-
if (signal?.aborted) {
|
|
223
|
-
return reject(new DeliverdError(0, "aborted", "The wait was aborted."));
|
|
224
|
-
}
|
|
225
|
-
const timer = setTimeout(() => {
|
|
226
|
-
signal?.removeEventListener("abort", onAbort);
|
|
227
|
-
resolve();
|
|
228
|
-
}, ms);
|
|
229
|
-
const onAbort = () => {
|
|
230
|
-
clearTimeout(timer);
|
|
231
|
-
reject(new DeliverdError(0, "aborted", "The wait was aborted."));
|
|
232
|
-
};
|
|
233
|
-
signal?.addEventListener("abort", onAbort, { once: true });
|
|
234
|
-
});
|
|
235
|
-
}
|
|
236
|
-
|
|
237
|
-
export class Approvals {
|
|
238
|
-
constructor(private readonly http: HttpClient) {}
|
|
239
|
-
|
|
240
|
-
/**
|
|
241
|
-
* Ask. Returns as soon as the request is filed — the approvers are being
|
|
242
|
-
* told while this resolves — so call `wait()` next, or keep the id and poll
|
|
243
|
-
* later.
|
|
244
|
-
*/
|
|
245
|
-
async create(input: CreateApprovalInput, signal?: AbortSignal): Promise<Approval> {
|
|
246
|
-
const data = await this.http.request<ApprovalData>({
|
|
247
|
-
method: "POST",
|
|
248
|
-
path: "/approvals",
|
|
249
|
-
body: input,
|
|
250
|
-
signal,
|
|
251
|
-
});
|
|
252
|
-
return new Approval(this.http, data);
|
|
253
|
-
}
|
|
254
|
-
|
|
255
|
-
async get(id: string, signal?: AbortSignal): Promise<Approval> {
|
|
256
|
-
const data = await this.http.request<ApprovalData>({
|
|
257
|
-
method: "GET",
|
|
258
|
-
path: `/approvals/${id}`,
|
|
259
|
-
signal,
|
|
260
|
-
});
|
|
261
|
-
return new Approval(this.http, data);
|
|
262
|
-
}
|
|
263
|
-
|
|
264
|
-
/**
|
|
265
|
-
* The organisation's approvals, newest first.
|
|
266
|
-
*
|
|
267
|
-
* With no `limit` this is every one of them: the API says where each page
|
|
268
|
-
* stopped and this follows the cursor to the end. With a `limit` it is one
|
|
269
|
-
* page of that size, and `listPage` hands back the cursor to continue from.
|
|
270
|
-
*/
|
|
271
|
-
async list(input: ListApprovalsInput = {}, signal?: AbortSignal): Promise<Approval[]> {
|
|
272
|
-
return listOrCollect(input, async (q: { limit?: number; cursor?: string }) => {
|
|
273
|
-
const page = await this.listPage({ ...input, ...q }, signal);
|
|
274
|
-
return { items: page.items, nextCursor: page.nextCursor };
|
|
275
|
-
});
|
|
276
|
-
}
|
|
277
|
-
|
|
278
|
-
/** One page, and the cursor to continue from — null when it is the end. */
|
|
279
|
-
async listPage(
|
|
280
|
-
input: ListApprovalsInput = {},
|
|
281
|
-
signal?: AbortSignal
|
|
282
|
-
): Promise<PageOf<Approval>> {
|
|
283
|
-
const { approvals, nextCursor } = await this.http.request<{
|
|
284
|
-
approvals: ApprovalData[];
|
|
285
|
-
nextCursor: string | null;
|
|
286
|
-
}>({
|
|
287
|
-
method: "GET",
|
|
288
|
-
path: "/approvals",
|
|
289
|
-
query: { status: input.status, externalId: input.externalId, limit: input.limit, cursor: input.cursor },
|
|
290
|
-
signal,
|
|
291
|
-
});
|
|
292
|
-
return { items: approvals.map((r) => new Approval(this.http, r)), nextCursor };
|
|
293
|
-
}
|
|
294
|
-
|
|
295
|
-
/**
|
|
296
|
-
* Ask and wait, for the common case where there is nothing to do in
|
|
297
|
-
* between. `const { approved } = await deliverd.approvals.request({…})`.
|
|
298
|
-
*/
|
|
299
|
-
async request(
|
|
300
|
-
input: CreateApprovalInput,
|
|
301
|
-
options: WaitOptions = {}
|
|
302
|
-
): Promise<Approval> {
|
|
303
|
-
const approval = await this.create(input, options.signal);
|
|
304
|
-
return approval.wait(options);
|
|
305
|
-
}
|
|
306
|
-
|
|
307
|
-
/**
|
|
308
|
-
* The same request as before, when there was one.
|
|
309
|
-
*
|
|
310
|
-
* Best effort, and worth being exact about what that means: it looks for a
|
|
311
|
-
* request with this `externalId` and returns it rather than filing a second.
|
|
312
|
-
* That makes an agent safe to restart — a crash between "asked" and
|
|
313
|
-
* "recorded that I asked" does not produce two notifications for one
|
|
314
|
-
* decision. Two *concurrent* calls can still both find nothing and both
|
|
315
|
-
* create; real idempotency needs a key the server enforces, and that is
|
|
316
|
-
* server work, not something a client can promise.
|
|
317
|
-
*/
|
|
318
|
-
async findByExternalId(externalId: string, signal?: AbortSignal): Promise<Approval | null> {
|
|
319
|
-
const found = await this.list({ externalId, limit: 1 }, signal);
|
|
320
|
-
return found[0] ?? null;
|
|
321
|
-
}
|
|
322
|
-
}
|
|
1
|
+
import { listOrCollect, type PageOf } from "./paging.js";
|
|
2
|
+
import { DeliverdError, DeliverdTimeoutError } from "./errors.js";
|
|
3
|
+
import type { HttpClient } from "./http.js";
|
|
4
|
+
import { durationMs, type Duration } from "./duration.js";
|
|
5
|
+
import type {
|
|
6
|
+
ApprovalData,
|
|
7
|
+
ApprovalQuestion,
|
|
8
|
+
CreateApprovalInput,
|
|
9
|
+
Decision,
|
|
10
|
+
ListApprovalsInput,
|
|
11
|
+
} from "./types.js";
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Ask a person before you act.
|
|
15
|
+
*
|
|
16
|
+
* The point of this module is one line — `await approval.wait()` — and
|
|
17
|
+
* everything in it exists to make that line safe to write in a real agent:
|
|
18
|
+
* polling that backs off instead of hammering, a question from the approver
|
|
19
|
+
* answered without leaving the wait, and an end that is guaranteed by the
|
|
20
|
+
* request's own expiry rather than by hope.
|
|
21
|
+
*/
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* How often to ask, as the wait gets longer. Milliseconds.
|
|
25
|
+
*
|
|
26
|
+
* The first one is deliberately quick. Most approvals take minutes, but the
|
|
27
|
+
* ones that take two seconds are the ones somebody is watching — a demo, a
|
|
28
|
+
* deploy with the approver stood next to you — and a client whose first look
|
|
29
|
+
* is two seconds away makes an instant decision feel like a slow one. One
|
|
30
|
+
* cheap early request buys that, and against a limit of 120 a minute it costs
|
|
31
|
+
* nothing. After a few polls the schedule is somebody's afternoon, not a
|
|
32
|
+
* progress bar.
|
|
33
|
+
*/
|
|
34
|
+
export const POLL_SCHEDULE = [250, 750, 2_000, 4_000, 8_000, 15_000, 30_000] as const;
|
|
35
|
+
const POLL_CEILING = 60_000;
|
|
36
|
+
|
|
37
|
+
/** Development mode: the approver is imaginary and instant, so keep up. */
|
|
38
|
+
export const FAST_POLL_SCHEDULE = [10, 25, 50, 100] as const;
|
|
39
|
+
|
|
40
|
+
function pollDelay(poll: number, schedule: readonly number[]): number {
|
|
41
|
+
const base = schedule[Math.min(poll, schedule.length - 1)] ?? POLL_CEILING;
|
|
42
|
+
// Jitter, so a hundred agents started by the same cron do not arrive together.
|
|
43
|
+
return base * 0.75 + Math.random() * base * 0.5;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export interface WaitOptions {
|
|
47
|
+
/**
|
|
48
|
+
* Called when the approver asks the requester something. Return the answer
|
|
49
|
+
* and the wait posts it and carries on; return `null` to leave it for a
|
|
50
|
+
* person. Without this a question simply sits there — the approver is
|
|
51
|
+
* waiting on you, and nothing will move until it is answered or they decide
|
|
52
|
+
* anyway.
|
|
53
|
+
*/
|
|
54
|
+
onQuestion?: (question: ApprovalQuestion, approval: ApprovalData) => Promise<string | null> | string | null;
|
|
55
|
+
/** Called after every poll, for a progress line in a CLI. */
|
|
56
|
+
onPoll?: (approval: ApprovalData) => void;
|
|
57
|
+
/**
|
|
58
|
+
* Give up after this many milliseconds and throw `DeliverdTimeoutError`.
|
|
59
|
+
* Omitted, the wait ends when the request does — which, for a request with
|
|
60
|
+
* no `expiresAt`, may be never. Set one or the other.
|
|
61
|
+
*/
|
|
62
|
+
timeout?: number;
|
|
63
|
+
signal?: AbortSignal;
|
|
64
|
+
/**
|
|
65
|
+
* How long between polls, as the wait lengthens. Rarely worth changing —
|
|
66
|
+
* development mode uses it to keep up with an approver who is instant.
|
|
67
|
+
*/
|
|
68
|
+
pollIntervals?: readonly number[];
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* A request, and what you can do with it.
|
|
73
|
+
*
|
|
74
|
+
* The data is a snapshot; `wait()` and `refresh()` replace it in place, so a
|
|
75
|
+
* handle held across a wait reads the settled request rather than the one you
|
|
76
|
+
* created.
|
|
77
|
+
*/
|
|
78
|
+
export class Approval {
|
|
79
|
+
constructor(
|
|
80
|
+
private readonly http: HttpClient,
|
|
81
|
+
private data: ApprovalData
|
|
82
|
+
) {}
|
|
83
|
+
|
|
84
|
+
get id(): string { return this.data.id; }
|
|
85
|
+
get status(): ApprovalData["status"] { return this.data.status; }
|
|
86
|
+
/** The page the approver decides on. Put it in your own UI or logs. */
|
|
87
|
+
get url(): string { return this.data.url; }
|
|
88
|
+
get title(): string { return this.data.title; }
|
|
89
|
+
/** Their reason, when they gave one. */
|
|
90
|
+
get note(): string | null { return this.data.note; }
|
|
91
|
+
/** Who decided, as a name rather than an id. */
|
|
92
|
+
get decidedBy(): string | null { return this.data.decidedBy; }
|
|
93
|
+
get decidedById(): string | null { return this.data.decidedById; }
|
|
94
|
+
get decidedAt(): string | null { return this.data.decidedAt; }
|
|
95
|
+
get questions(): ApprovalQuestion[] { return this.data.questions; }
|
|
96
|
+
/** Questions the approver is still waiting on you to answer. */
|
|
97
|
+
get openQuestions(): ApprovalQuestion[] { return this.data.questions.filter((q) => !q.answer); }
|
|
98
|
+
|
|
99
|
+
/** The one to branch on. False for rejected, expired and cancelled alike. */
|
|
100
|
+
get approved(): boolean { return this.data.status === "approved"; }
|
|
101
|
+
get rejected(): boolean { return this.data.status === "rejected"; }
|
|
102
|
+
get expired(): boolean { return this.data.status === "expired"; }
|
|
103
|
+
get cancelled(): boolean { return this.data.status === "cancelled"; }
|
|
104
|
+
get pending(): boolean { return this.data.status === "pending"; }
|
|
105
|
+
|
|
106
|
+
/** Everything the API returned, if you want a field the getters do not name. */
|
|
107
|
+
toJSON(): ApprovalData { return this.data; }
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* The answer, flattened — what `approve()` hands back.
|
|
111
|
+
*
|
|
112
|
+
* `approved` is a boolean so `if (decision.approved)` reads as the sentence
|
|
113
|
+
* it is; `status` is the narrowing union for a switch. Both, because people
|
|
114
|
+
* write both and neither should be the wrong one.
|
|
115
|
+
*/
|
|
116
|
+
toDecision(): Decision {
|
|
117
|
+
const status = this.data.status === "pending" ? "expired" : this.data.status;
|
|
118
|
+
return {
|
|
119
|
+
approved: this.data.status === "approved",
|
|
120
|
+
status,
|
|
121
|
+
note: this.data.note,
|
|
122
|
+
decidedBy: this.data.decidedBy,
|
|
123
|
+
decidedById: this.data.decidedById,
|
|
124
|
+
decidedAt: this.data.decidedAt,
|
|
125
|
+
id: this.data.id,
|
|
126
|
+
url: this.data.url,
|
|
127
|
+
approval: this,
|
|
128
|
+
} as Decision;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
async refresh(signal?: AbortSignal): Promise<this> {
|
|
132
|
+
this.data = await this.http.request<ApprovalData>({
|
|
133
|
+
method: "GET",
|
|
134
|
+
path: `/approvals/${this.data.id}`,
|
|
135
|
+
signal,
|
|
136
|
+
});
|
|
137
|
+
return this;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/** Answer a question the approver asked. Only the requester may. */
|
|
141
|
+
async answer(questionId: string, answer: string, signal?: AbortSignal): Promise<this> {
|
|
142
|
+
this.data = await this.http.request<ApprovalData>({
|
|
143
|
+
method: "POST",
|
|
144
|
+
path: `/approvals/${this.data.id}/answers`,
|
|
145
|
+
body: { questionId, answer },
|
|
146
|
+
signal,
|
|
147
|
+
});
|
|
148
|
+
return this;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/** Withdraw it. The row stays as evidence of what was asked and dropped. */
|
|
152
|
+
async cancel(signal?: AbortSignal): Promise<this> {
|
|
153
|
+
this.data = await this.http.request<ApprovalData>({
|
|
154
|
+
method: "POST",
|
|
155
|
+
path: `/approvals/${this.data.id}/cancel`,
|
|
156
|
+
signal,
|
|
157
|
+
});
|
|
158
|
+
return this;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* Block until a person decides, then return.
|
|
163
|
+
*
|
|
164
|
+
* Resolves on approved, rejected, expired and cancelled — it does not throw
|
|
165
|
+
* on a no, because a refusal is an answer and `if (approval.approved)` is
|
|
166
|
+
* the line that should follow. It throws only when the wait itself failed:
|
|
167
|
+
* a timeout, an abort, or the API being unreachable.
|
|
168
|
+
*/
|
|
169
|
+
async wait(options: WaitOptions = {}): Promise<this> {
|
|
170
|
+
const deadline = options.timeout !== undefined ? Date.now() + options.timeout : undefined;
|
|
171
|
+
let poll = 0;
|
|
172
|
+
|
|
173
|
+
// Already settled, or answered between create and wait.
|
|
174
|
+
if (!this.pending) return this;
|
|
175
|
+
|
|
176
|
+
for (;;) {
|
|
177
|
+
if (options.signal?.aborted) {
|
|
178
|
+
throw new DeliverdError(0, "aborted", "The wait was aborted.", undefined, {
|
|
179
|
+
cause: options.signal.reason,
|
|
180
|
+
});
|
|
181
|
+
}
|
|
182
|
+
if (deadline !== undefined && Date.now() >= deadline) {
|
|
183
|
+
/*
|
|
184
|
+
* Say which of the two happened. An approver who asked a question and
|
|
185
|
+
* got no answer has not ignored the request — they are waiting on you,
|
|
186
|
+
* and "nobody decided in time" sends you to look at the wrong end of
|
|
187
|
+
* it. Found by running the quickstart's own instruction to set
|
|
188
|
+
* DELIVERD_DEV_OUTCOME=question, which produced exactly that message.
|
|
189
|
+
*/
|
|
190
|
+
const unanswered = this.data.questions?.find((q) => !q.answer);
|
|
191
|
+
throw new DeliverdTimeoutError(
|
|
192
|
+
unanswered
|
|
193
|
+
? `An approver asked a question about "${this.data.title}" and nothing answered it: ` +
|
|
194
|
+
`"${unanswered.question}". Pass an onQuestion handler, or answer it at ${this.data.url}.`
|
|
195
|
+
: `Nobody decided "${this.data.title}" within the timeout. It is still open at ${this.data.url}.`
|
|
196
|
+
);
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
const delay = pollDelay(poll++, options.pollIntervals ?? POLL_SCHEDULE);
|
|
200
|
+
const remaining = deadline === undefined ? delay : Math.min(delay, deadline - Date.now());
|
|
201
|
+
await wait(Math.max(0, remaining), options.signal);
|
|
202
|
+
|
|
203
|
+
await this.refresh(options.signal);
|
|
204
|
+
options.onPoll?.(this.data);
|
|
205
|
+
|
|
206
|
+
if (options.onQuestion) {
|
|
207
|
+
for (const question of this.openQuestions) {
|
|
208
|
+
const answer = await options.onQuestion(question, this.data);
|
|
209
|
+
if (typeof answer === "string" && answer.trim()) {
|
|
210
|
+
await this.answer(question.id, answer, options.signal);
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
if (!this.pending) return this;
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
function wait(ms: number, signal?: AbortSignal): Promise<void> {
|
|
221
|
+
return new Promise((resolve, reject) => {
|
|
222
|
+
if (signal?.aborted) {
|
|
223
|
+
return reject(new DeliverdError(0, "aborted", "The wait was aborted."));
|
|
224
|
+
}
|
|
225
|
+
const timer = setTimeout(() => {
|
|
226
|
+
signal?.removeEventListener("abort", onAbort);
|
|
227
|
+
resolve();
|
|
228
|
+
}, ms);
|
|
229
|
+
const onAbort = () => {
|
|
230
|
+
clearTimeout(timer);
|
|
231
|
+
reject(new DeliverdError(0, "aborted", "The wait was aborted."));
|
|
232
|
+
};
|
|
233
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
234
|
+
});
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
export class Approvals {
|
|
238
|
+
constructor(private readonly http: HttpClient) {}
|
|
239
|
+
|
|
240
|
+
/**
|
|
241
|
+
* Ask. Returns as soon as the request is filed — the approvers are being
|
|
242
|
+
* told while this resolves — so call `wait()` next, or keep the id and poll
|
|
243
|
+
* later.
|
|
244
|
+
*/
|
|
245
|
+
async create(input: CreateApprovalInput, signal?: AbortSignal): Promise<Approval> {
|
|
246
|
+
const data = await this.http.request<ApprovalData>({
|
|
247
|
+
method: "POST",
|
|
248
|
+
path: "/approvals",
|
|
249
|
+
body: input,
|
|
250
|
+
signal,
|
|
251
|
+
});
|
|
252
|
+
return new Approval(this.http, data);
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
async get(id: string, signal?: AbortSignal): Promise<Approval> {
|
|
256
|
+
const data = await this.http.request<ApprovalData>({
|
|
257
|
+
method: "GET",
|
|
258
|
+
path: `/approvals/${id}`,
|
|
259
|
+
signal,
|
|
260
|
+
});
|
|
261
|
+
return new Approval(this.http, data);
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
/**
|
|
265
|
+
* The organisation's approvals, newest first.
|
|
266
|
+
*
|
|
267
|
+
* With no `limit` this is every one of them: the API says where each page
|
|
268
|
+
* stopped and this follows the cursor to the end. With a `limit` it is one
|
|
269
|
+
* page of that size, and `listPage` hands back the cursor to continue from.
|
|
270
|
+
*/
|
|
271
|
+
async list(input: ListApprovalsInput = {}, signal?: AbortSignal): Promise<Approval[]> {
|
|
272
|
+
return listOrCollect(input, async (q: { limit?: number; cursor?: string }) => {
|
|
273
|
+
const page = await this.listPage({ ...input, ...q }, signal);
|
|
274
|
+
return { items: page.items, nextCursor: page.nextCursor };
|
|
275
|
+
});
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
/** One page, and the cursor to continue from — null when it is the end. */
|
|
279
|
+
async listPage(
|
|
280
|
+
input: ListApprovalsInput = {},
|
|
281
|
+
signal?: AbortSignal
|
|
282
|
+
): Promise<PageOf<Approval>> {
|
|
283
|
+
const { approvals, nextCursor } = await this.http.request<{
|
|
284
|
+
approvals: ApprovalData[];
|
|
285
|
+
nextCursor: string | null;
|
|
286
|
+
}>({
|
|
287
|
+
method: "GET",
|
|
288
|
+
path: "/approvals",
|
|
289
|
+
query: { status: input.status, externalId: input.externalId, limit: input.limit, cursor: input.cursor },
|
|
290
|
+
signal,
|
|
291
|
+
});
|
|
292
|
+
return { items: approvals.map((r) => new Approval(this.http, r)), nextCursor };
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
/**
|
|
296
|
+
* Ask and wait, for the common case where there is nothing to do in
|
|
297
|
+
* between. `const { approved } = await deliverd.approvals.request({…})`.
|
|
298
|
+
*/
|
|
299
|
+
async request(
|
|
300
|
+
input: CreateApprovalInput,
|
|
301
|
+
options: WaitOptions = {}
|
|
302
|
+
): Promise<Approval> {
|
|
303
|
+
const approval = await this.create(input, options.signal);
|
|
304
|
+
return approval.wait(options);
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
/**
|
|
308
|
+
* The same request as before, when there was one.
|
|
309
|
+
*
|
|
310
|
+
* Best effort, and worth being exact about what that means: it looks for a
|
|
311
|
+
* request with this `externalId` and returns it rather than filing a second.
|
|
312
|
+
* That makes an agent safe to restart — a crash between "asked" and
|
|
313
|
+
* "recorded that I asked" does not produce two notifications for one
|
|
314
|
+
* decision. Two *concurrent* calls can still both find nothing and both
|
|
315
|
+
* create; real idempotency needs a key the server enforces, and that is
|
|
316
|
+
* server work, not something a client can promise.
|
|
317
|
+
*/
|
|
318
|
+
async findByExternalId(externalId: string, signal?: AbortSignal): Promise<Approval | null> {
|
|
319
|
+
const found = await this.list({ externalId, limit: 1 }, signal);
|
|
320
|
+
return found[0] ?? null;
|
|
321
|
+
}
|
|
322
|
+
}
|