@deliverd/sdk 0.1.0 → 0.3.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 CHANGED
@@ -1,4 +1,4 @@
1
- import type { ApprovalData } from "./types.js";
1
+ import type { ApprovalData, CollectionData, ReviewData } from "./types.js";
2
2
 
3
3
  /**
4
4
  * Development mode: the whole loop, on your machine, with nobody in it.
@@ -52,7 +52,7 @@ interface Stored {
52
52
  }
53
53
 
54
54
  /**
55
- * A `fetch` that serves the approvals API from memory.
55
+ * A `fetch` that serves the approvals, reviews and collections APIs from memory.
56
56
  *
57
57
  * Deliberately narrow: it answers the calls the primitives make and 501s the
58
58
  * rest, with a message saying so, rather than pretending to be the whole API
@@ -60,6 +60,8 @@ interface Stored {
60
60
  */
61
61
  export function developmentFetch(options: DevelopmentOptions = {}): typeof globalThis.fetch {
62
62
  const store = new Map<string, Stored>();
63
+ const reviewStore = new Map<string, StoredReview>();
64
+ const collectionStore = new Map<string, StoredCollection>();
63
65
 
64
66
  return (async (input: string | URL | Request, init?: RequestInit) => {
65
67
  const url = new URL(String(input));
@@ -147,11 +149,159 @@ export function developmentFetch(options: DevelopmentOptions = {}): typeof globa
147
149
  return json(stored.data);
148
150
  }
149
151
 
152
+ if (method === "POST" && path === "/reviews") {
153
+ const id = `rev_dev_${++counter}`;
154
+ /*
155
+ * The same outcome switch as approvals, mapped onto a review's endings:
156
+ * a rejection is "changes requested", because that is what saying no to
157
+ * a piece of work means. A simulated question has nothing to ask about
158
+ * here — there is no question mechanism on a review — so it approves.
159
+ */
160
+ const outcome = resolveOutcome(options.outcome, body);
161
+ const verdict = outcome === "rejected" ? "changes_requested" : "approved";
162
+ const reviewers = ((body.reviewers as string[] | undefined) ?? []).map((email, i) => ({
163
+ kind: "user" as const,
164
+ id: `usr_dev_${i + 1}`,
165
+ label: email,
166
+ }));
167
+ const data: ReviewData = {
168
+ id,
169
+ status: "pending",
170
+ url: `https://deliverd.dev/reviews/${id}`,
171
+ title: String(body.title ?? "Untitled"),
172
+ instructions: (body.instructions as string | undefined) ?? null,
173
+ reportId: (body.reportId as string | undefined) ?? null,
174
+ versionId: (body.versionId as string | undefined) ?? null,
175
+ externalId: (body.externalId as string | undefined) ?? null,
176
+ metadata: (body.metadata as Record<string, unknown>) ?? {},
177
+ requestedBy: "You (development mode)",
178
+ requiredApprovals: (body.requiredApprovals as number | undefined) ?? 1,
179
+ reviewers,
180
+ verdicts: [],
181
+ threadCount: 0,
182
+ settledAt: null,
183
+ expiresAt: (body.expiresAt as string | undefined) ?? null,
184
+ createdAt: new Date().toISOString(),
185
+ };
186
+ reviewStore.set(id, {
187
+ data,
188
+ settleAt: Date.now() + (options.delay ?? 0),
189
+ verdict,
190
+ timeout: outcome === "timeout",
191
+ });
192
+ if (options.log !== false) announceReview(data, verdict, outcome === "timeout");
193
+ return json(data, 201);
194
+ }
195
+
196
+ const reviewMatch = /^\/reviews\/([^/]+)(\/cancel)?$/.exec(path);
197
+ if (reviewMatch) {
198
+ const stored = reviewStore.get(reviewMatch[1]!);
199
+ if (!stored) {
200
+ return json(
201
+ { error: { code: "not_found", message: "No such review in this development session." } },
202
+ 404
203
+ );
204
+ }
205
+ if (reviewMatch[2] === "/cancel") {
206
+ stored.data.status = "cancelled";
207
+ return json(stored.data);
208
+ }
209
+ settleReview(stored);
210
+ return json(stored.data);
211
+ }
212
+
213
+ if (method === "GET" && path === "/reviews") {
214
+ const externalId = url.searchParams.get("externalId");
215
+ const all = [...reviewStore.values()].map((r) => r.data);
216
+ return json({
217
+ reviews: externalId ? all.filter((r) => r.externalId === externalId) : all,
218
+ });
219
+ }
220
+
221
+ if (method === "POST" && path === "/collections") {
222
+ const id = `col_dev_${++counter}`;
223
+ const outcome = resolveOutcome(options.outcome, body);
224
+ const asked = ((body.respondents as string[] | undefined) ?? []).map(String);
225
+ const questions = ((body.questions as Record<string, unknown>[] | undefined) ?? []).map(
226
+ (q, i) => ({
227
+ id: `q_dev_${i + 1}`,
228
+ prompt: String(q.prompt ?? "Question"),
229
+ help: (q.help as string | undefined) ?? null,
230
+ kind: (q.kind as CollectionData["questions"][number]["kind"]) ?? "text",
231
+ required: q.required !== false,
232
+ options: (q.options as string[] | undefined) ?? [],
233
+ })
234
+ );
235
+ const data: CollectionData = {
236
+ id,
237
+ status: "pending",
238
+ url: `https://deliverd.dev/collect/${id}`,
239
+ title: String(body.title ?? "Untitled"),
240
+ instructions: (body.instructions as string | undefined) ?? null,
241
+ reportId: (body.reportId as string | undefined) ?? null,
242
+ externalId: (body.externalId as string | undefined) ?? null,
243
+ metadata: (body.metadata as Record<string, unknown>) ?? {},
244
+ requestedBy: "You (development mode)",
245
+ requiredResponses: (body.requiredResponses as number | undefined) ?? (asked.length || 1),
246
+ questions,
247
+ responses: asked.map((who) => ({
248
+ respondent: who,
249
+ status: "pending" as const,
250
+ submittedAt: null,
251
+ answers: [],
252
+ })),
253
+ submittedCount: 0,
254
+ askedCount: asked.length,
255
+ settledAt: null,
256
+ dueAt: (body.dueAt as string | undefined) ?? null,
257
+ expiresAt: (body.expiresAt as string | undefined) ?? null,
258
+ createdAt: new Date().toISOString(),
259
+ };
260
+ collectionStore.set(id, {
261
+ data,
262
+ settleAt: Date.now() + (options.delay ?? 0),
263
+ /*
264
+ * A simulated rejection becomes an expiry here: there is no way to
265
+ * say no to a question, only to leave it unanswered, and that is the
266
+ * ending a caller most needs to have thought about.
267
+ */
268
+ expire: outcome === "rejected",
269
+ timeout: outcome === "timeout",
270
+ });
271
+ if (options.log !== false) announceCollection(data, outcome);
272
+ return json(data, 201);
273
+ }
274
+
275
+ const collectionMatch = /^\/collections\/([^/]+)(\/cancel)?$/.exec(path);
276
+ if (collectionMatch) {
277
+ const stored = collectionStore.get(collectionMatch[1]!);
278
+ if (!stored) {
279
+ return json(
280
+ { error: { code: "not_found", message: "No such request in this development session." } },
281
+ 404
282
+ );
283
+ }
284
+ if (collectionMatch[2] === "/cancel") {
285
+ stored.data.status = "cancelled";
286
+ return json(stored.data);
287
+ }
288
+ settleCollection(stored);
289
+ return json(stored.data);
290
+ }
291
+
292
+ if (method === "GET" && path === "/collections") {
293
+ const externalId = url.searchParams.get("externalId");
294
+ const all = [...collectionStore.values()].map((c) => c.data);
295
+ return json({
296
+ collections: externalId ? all.filter((c) => c.externalId === externalId) : all,
297
+ });
298
+ }
299
+
150
300
  return json(
151
301
  {
152
302
  error: {
153
303
  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.`,
304
+ message: `Development mode simulates approvals, reviews and collections only, and something called ${method} ${path}. Use a real API key for the rest of the API.`,
155
305
  },
156
306
  },
157
307
  501
@@ -211,3 +361,125 @@ function announce(data: ApprovalData, outcome: DevelopmentOutcome): void {
211
361
  );
212
362
  console.log(lines.join("\n"));
213
363
  }
364
+
365
+
366
+ interface StoredReview {
367
+ data: ReviewData;
368
+ settleAt: number;
369
+ verdict: "approved" | "changes_requested";
370
+ timeout: boolean;
371
+ }
372
+
373
+ /** Settle it once its moment has passed, unless it is meant to hang. */
374
+ function settleReview(stored: StoredReview): void {
375
+ if (stored.timeout || stored.data.status !== "pending") return;
376
+ if (Date.now() < stored.settleAt) return;
377
+ stored.data.verdicts = [
378
+ {
379
+ verdict: stored.verdict,
380
+ by: stored.data.reviewers[0]?.label ?? "A reviewer (development mode)",
381
+ note:
382
+ stored.verdict === "changes_requested"
383
+ ? "Simulated: the figures on page two do not tie back."
384
+ : null,
385
+ at: new Date().toISOString(),
386
+ },
387
+ ];
388
+ stored.data.status = stored.verdict;
389
+ stored.data.settledAt = new Date().toISOString();
390
+ }
391
+
392
+ function announceReview(
393
+ data: ReviewData,
394
+ verdict: "approved" | "changes_requested",
395
+ willHang: boolean
396
+ ): void {
397
+ const lines = [
398
+ ` ┌─ Deliverd · development mode ─────────────────────────`,
399
+ ` │ ${data.title}`,
400
+ ...(data.instructions ? [` │ Check: ${data.instructions}`] : []),
401
+ ` │ Reviewers: ${data.reviewers.map((r) => r.label).join(", ") || "nobody named"}`,
402
+ ` │`,
403
+ ` │ Simulating: ${willHang ? "nobody reviews it" : verdict.replace("_", " ")}`,
404
+ ` └───────────────────────────────────────────────────────`,
405
+ "",
406
+ ];
407
+ console.log(lines.join("\n"));
408
+ }
409
+
410
+
411
+ interface StoredCollection {
412
+ data: CollectionData;
413
+ settleAt: number;
414
+ expire: boolean;
415
+ timeout: boolean;
416
+ }
417
+
418
+ /**
419
+ * Everyone answers, at the same moment, with a plausible value for the kind
420
+ * of question asked. Plausible rather than empty, because a caller writing
421
+ * `answers["Headcount at 30 September"] + 1` should find out here that it is
422
+ * a number, not in production.
423
+ */
424
+ function settleCollection(stored: StoredCollection): void {
425
+ if (stored.timeout || stored.data.status !== "pending") return;
426
+ if (Date.now() < stored.settleAt) return;
427
+ if (stored.expire) {
428
+ stored.data.status = "expired";
429
+ stored.data.settledAt = new Date().toISOString();
430
+ return;
431
+ }
432
+ const at = new Date().toISOString();
433
+ stored.data.responses = stored.data.responses.map((r) => ({
434
+ ...r,
435
+ status: "submitted" as const,
436
+ submittedAt: at,
437
+ answers: stored.data.questions.map((q) => ({
438
+ question: q.prompt,
439
+ kind: q.kind,
440
+ value: sampleAnswer(q),
441
+ })),
442
+ }));
443
+ stored.data.submittedCount = stored.data.responses.length;
444
+ stored.data.status = "complete";
445
+ stored.data.settledAt = at;
446
+ }
447
+
448
+ function sampleAnswer(q: CollectionData["questions"][number]): string | number | boolean | string[] {
449
+ switch (q.kind) {
450
+ case "number":
451
+ return 42;
452
+ case "boolean":
453
+ return true;
454
+ case "date":
455
+ return new Date().toISOString().slice(0, 10);
456
+ case "choice":
457
+ return q.options[0] ?? "";
458
+ case "multi_choice":
459
+ return q.options.slice(0, 1);
460
+ case "long_text":
461
+ return "Simulated: a longer answer than a line.";
462
+ default:
463
+ return "Simulated answer";
464
+ }
465
+ }
466
+
467
+ function announceCollection(data: CollectionData, outcome: string): void {
468
+ const lines = [
469
+ ` ┌─ Deliverd · development mode ─────────────────────────`,
470
+ ` │ ${data.title}`,
471
+ ` │ Asking: ${data.questions.map((q) => q.prompt).join(" · ") || "nothing"}`,
472
+ ` │ Of: ${data.responses.map((r) => r.respondent).join(", ") || "nobody named"}`,
473
+ ` │`,
474
+ ` │ Simulating: ${
475
+ outcome === "timeout"
476
+ ? "nobody answers"
477
+ : outcome === "rejected"
478
+ ? "it expires unanswered"
479
+ : "everyone answers"
480
+ }`,
481
+ ` └───────────────────────────────────────────────────────`,
482
+ "",
483
+ ];
484
+ console.log(lines.join("\n"));
485
+ }
package/src/index.ts CHANGED
@@ -1,19 +1,27 @@
1
1
  import { HttpClient, type ClientOptions } from "./http.js";
2
2
  import { Approvals, FAST_POLL_SCHEDULE, type WaitOptions } from "./approvals.js";
3
3
  import { Comments, Reports } from "./reports.js";
4
+ import { Reviews, type ReviewWaitOptions } from "./reviews.js";
5
+ import { Collections, type CollectWaitOptions } from "./collections.js";
4
6
  import { Webhooks } from "./webhooks.js";
5
7
  import { developmentFetch, type DevelopmentOptions } from "./dev.js";
6
8
  import { durationMs, type Duration } from "./duration.js";
7
9
  import { DeliverdError } from "./errors.js";
8
10
  import type {
11
+ CollectedAnswers,
9
12
  CreateApprovalInput,
13
+ CreateCollectionInput,
14
+ CreateReviewInput,
10
15
  Decision,
11
16
  PublishReportInput,
12
17
  PublishResult,
18
+ ReviewOutcome,
13
19
  } from "./types.js";
14
20
 
15
21
  export { Approval, Approvals, POLL_SCHEDULE, type WaitOptions } from "./approvals.js";
16
22
  export { Comments, Reports } from "./reports.js";
23
+ export { Review, Reviews, type ReviewWaitOptions } from "./reviews.js";
24
+ export { Collection, Collections, type CollectWaitOptions } from "./collections.js";
17
25
  export {
18
26
  constructEvent,
19
27
  DELIVERY_HEADER,
@@ -66,6 +74,42 @@ export interface ApproveOptions extends Omit<CreateApprovalInput, "expiresAt"> {
66
74
  reuse?: boolean;
67
75
  }
68
76
 
77
+ /** Everything `review()` takes, plus the conveniences it adds on top. */
78
+ export interface ReviewOptions extends Omit<CreateReviewInput, "expiresAt"> {
79
+ /** `"4h"`, `"30m"`, `"2d"`, or milliseconds. Default 24 hours. */
80
+ expiresIn?: Duration;
81
+ /** An exact moment instead, if you have one. */
82
+ expiresAt?: string;
83
+ /** Called after each poll — a progress line in a CLI. */
84
+ onPoll?: ReviewWaitOptions["onPoll"];
85
+ /** Give up waiting after this. The review stays open until it expires. */
86
+ timeout?: Duration;
87
+ signal?: AbortSignal;
88
+ /**
89
+ * With an `externalId`, reuse an existing review rather than filing a
90
+ * second one, so a restarted agent does not ask the same people twice.
91
+ */
92
+ reuse?: boolean;
93
+ }
94
+
95
+ /** Everything `collect()` takes, plus the conveniences it adds on top. */
96
+ export interface CollectOptions extends Omit<CreateCollectionInput, "expiresAt"> {
97
+ /** `"4h"`, `"30m"`, `"2d"`, or milliseconds. Default 24 hours. */
98
+ expiresIn?: Duration;
99
+ /** An exact moment instead, if you have one. */
100
+ expiresAt?: string;
101
+ /** Called after each poll — a progress line in a CLI. */
102
+ onPoll?: CollectWaitOptions["onPoll"];
103
+ /** Give up waiting after this. The request stays open until it expires. */
104
+ timeout?: Duration;
105
+ signal?: AbortSignal;
106
+ /**
107
+ * With an `externalId`, reuse an existing request rather than filing a
108
+ * second one, so a restarted agent does not ask the same people twice.
109
+ */
110
+ reuse?: boolean;
111
+ }
112
+
69
113
  /**
70
114
  * Deliverd: you build the action, Deliverd handles the human.
71
115
  *
@@ -87,6 +131,8 @@ export interface ApproveOptions extends Omit<CreateApprovalInput, "expiresAt"> {
87
131
  */
88
132
  export class Deliverd {
89
133
  readonly approvals: Approvals;
134
+ readonly reviews: Reviews;
135
+ readonly collections: Collections;
90
136
  readonly reports: Reports;
91
137
  readonly comments: Comments;
92
138
  readonly webhooks: Webhooks;
@@ -107,6 +153,8 @@ export class Deliverd {
107
153
  });
108
154
 
109
155
  this.approvals = new Approvals(this.http);
156
+ this.reviews = new Reviews(this.http);
157
+ this.collections = new Collections(this.http);
110
158
  this.reports = new Reports(this.http);
111
159
  this.comments = new Comments(this.http);
112
160
  this.webhooks = new Webhooks();
@@ -177,6 +225,119 @@ export class Deliverd {
177
225
  return decision.approved;
178
226
  }
179
227
 
228
+ /**
229
+ * Ask people to read what you made, and wait for their answer.
230
+ *
231
+ * The other half of judgement. `approve()` asks permission before you act;
232
+ * this asks whether what you already produced is right, and comes back with
233
+ * the reviewers' verdicts and a count of the comment threads they opened.
234
+ *
235
+ * ```ts
236
+ * const outcome = await deliverd.review({
237
+ * title: "Q3 board pack",
238
+ * reportId: report.id,
239
+ * instructions: "Check the figures against the ledger.",
240
+ * reviewers: ["partner@firm.example"],
241
+ * });
242
+ * if (!outcome.approved) await revise(outcome.verdicts);
243
+ * ```
244
+ *
245
+ * Resolves on changes requested as well as approval, because that is an
246
+ * answer — usually the more useful one. Reviews expire after a day unless
247
+ * you say otherwise, so a wait always ends.
248
+ */
249
+ async review(options: ReviewOptions): Promise<ReviewOutcome> {
250
+ const { expiresIn, timeout, onPoll, signal, reuse, ...input } = options;
251
+
252
+ if (input.externalId && reuse !== false) {
253
+ const existing = await this.reviews.findByExternalId(input.externalId, signal);
254
+ if (existing) {
255
+ const settled = await existing.wait({
256
+ onPoll,
257
+ signal,
258
+ timeout: durationOrUndefined(timeout),
259
+ ...(this.development ? { pollIntervals: FAST_POLL_SCHEDULE } : {}),
260
+ });
261
+ return settled.toOutcome();
262
+ }
263
+ }
264
+
265
+ const review = await this.reviews.create(
266
+ {
267
+ ...input,
268
+ expiresAt:
269
+ options.expiresAt ??
270
+ new Date(Date.now() + durationMs(expiresIn ?? DEFAULT_EXPIRY)).toISOString(),
271
+ },
272
+ signal
273
+ );
274
+ const settled = await review.wait({
275
+ onPoll,
276
+ signal,
277
+ // Same reasoning as approve(): in development the reviewer is imaginary
278
+ // and instant, so a wait still running after a moment will never settle.
279
+ timeout: durationOrUndefined(timeout) ?? (this.development ? 2_000 : undefined),
280
+ ...(this.development ? { pollIntervals: FAST_POLL_SCHEDULE } : {}),
281
+ });
282
+ return settled.toOutcome();
283
+ }
284
+
285
+ /**
286
+ * Ask people for what you do not have, and wait for it.
287
+ *
288
+ * `approve()` asks permission, `review()` asks judgement, and this asks for
289
+ * a fact — a figure, a date, a choice between options, the sentence only
290
+ * they can write.
291
+ *
292
+ * ```ts
293
+ * const { answers } = await deliverd.collect({
294
+ * title: "Before I file the Q3 return",
295
+ * respondents: ["finance@firm.example"],
296
+ * questions: [
297
+ * { prompt: "Headcount at 30 September", kind: "number" },
298
+ * { prompt: "Any disposals in the quarter?", kind: "boolean" },
299
+ * ],
300
+ * });
301
+ * ```
302
+ *
303
+ * `answers` is keyed by the question you asked. Check `complete` before you
304
+ * use it: a request that expired has whatever arrived and no more, and the
305
+ * thing you do without the figure is usually not the thing you do with it.
306
+ */
307
+ async collect(options: CollectOptions): Promise<CollectedAnswers> {
308
+ const { expiresIn, timeout, onPoll, signal, reuse, ...input } = options;
309
+
310
+ if (input.externalId && reuse !== false) {
311
+ const existing = await this.collections.findByExternalId(input.externalId, signal);
312
+ if (existing) {
313
+ const settled = await existing.wait({
314
+ onPoll,
315
+ signal,
316
+ timeout: durationOrUndefined(timeout),
317
+ ...(this.development ? { pollIntervals: FAST_POLL_SCHEDULE } : {}),
318
+ });
319
+ return settled.toCollected();
320
+ }
321
+ }
322
+
323
+ const collection = await this.collections.create(
324
+ {
325
+ ...input,
326
+ expiresAt:
327
+ options.expiresAt ??
328
+ new Date(Date.now() + durationMs(expiresIn ?? DEFAULT_EXPIRY)).toISOString(),
329
+ },
330
+ signal
331
+ );
332
+ const settled = await collection.wait({
333
+ onPoll,
334
+ signal,
335
+ timeout: durationOrUndefined(timeout) ?? (this.development ? 2_000 : undefined),
336
+ ...(this.development ? { pollIntervals: FAST_POLL_SCHEDULE } : {}),
337
+ });
338
+ return settled.toCollected();
339
+ }
340
+
180
341
  /** Publish HTML to a secure URL. The other half of the product, one call in. */
181
342
  publish(input: PublishReportInput, signal?: AbortSignal): Promise<PublishResult> {
182
343
  return this.reports.publish(input, signal);