@deliverd/sdk 0.8.2 → 0.9.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.
Files changed (68) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +654 -562
  3. package/dist/adapters/ai-sdk.d.ts +48 -0
  4. package/dist/adapters/ai-sdk.d.ts.map +1 -0
  5. package/dist/adapters/ai-sdk.js +12 -0
  6. package/dist/adapters/claude-agent-sdk.d.ts +55 -0
  7. package/dist/adapters/claude-agent-sdk.d.ts.map +1 -0
  8. package/dist/adapters/claude-agent-sdk.js +24 -0
  9. package/dist/adapters/index.d.ts +19 -0
  10. package/dist/adapters/index.d.ts.map +1 -0
  11. package/dist/adapters/index.js +13 -0
  12. package/dist/adapters/langgraph.d.ts +145 -0
  13. package/dist/adapters/langgraph.d.ts.map +1 -0
  14. package/dist/adapters/langgraph.js +69 -0
  15. package/dist/adapters/openai-agents.d.ts +68 -0
  16. package/dist/adapters/openai-agents.d.ts.map +1 -0
  17. package/dist/adapters/openai-agents.js +55 -0
  18. package/dist/adapters/shared.d.ts +91 -0
  19. package/dist/adapters/shared.d.ts.map +1 -0
  20. package/dist/adapters/shared.js +98 -0
  21. package/dist/approvals.d.ts +15 -1
  22. package/dist/approvals.d.ts.map +1 -1
  23. package/dist/approvals.js +19 -1
  24. package/dist/collections.d.ts +8 -0
  25. package/dist/collections.d.ts.map +1 -1
  26. package/dist/collections.js +11 -1
  27. package/dist/dev.d.ts +6 -0
  28. package/dist/dev.d.ts.map +1 -1
  29. package/dist/dev.js +11 -0
  30. package/dist/gates.d.ts.map +1 -1
  31. package/dist/gates.js +1 -0
  32. package/dist/index.d.ts +1 -1
  33. package/dist/index.d.ts.map +1 -1
  34. package/dist/index.js +1 -1
  35. package/dist/released.d.ts +1 -1
  36. package/dist/released.d.ts.map +1 -1
  37. package/dist/released.js +451 -0
  38. package/dist/reviews.d.ts +8 -0
  39. package/dist/reviews.d.ts.map +1 -1
  40. package/dist/reviews.js +11 -1
  41. package/dist/types.d.ts +73 -1
  42. package/dist/types.d.ts.map +1 -1
  43. package/dist/webhooks.d.ts +15 -1
  44. package/dist/webhooks.d.ts.map +1 -1
  45. package/dist/webhooks.js +13 -0
  46. package/package.json +59 -55
  47. package/src/adapters/ai-sdk.ts +59 -0
  48. package/src/adapters/claude-agent-sdk.ts +90 -0
  49. package/src/adapters/index.ts +23 -0
  50. package/src/adapters/langgraph.ts +202 -0
  51. package/src/adapters/openai-agents.ts +112 -0
  52. package/src/adapters/shared.ts +179 -0
  53. package/src/approvals.ts +342 -322
  54. package/src/collections.ts +247 -236
  55. package/src/dev.ts +780 -761
  56. package/src/duration.ts +21 -21
  57. package/src/errors.ts +62 -62
  58. package/src/flows.ts +222 -222
  59. package/src/gates.ts +231 -230
  60. package/src/http.ts +217 -217
  61. package/src/index.ts +444 -443
  62. package/src/messages.ts +161 -161
  63. package/src/paging.ts +64 -64
  64. package/src/released.ts +2523 -2072
  65. package/src/reports.ts +490 -490
  66. package/src/reviews.ts +236 -225
  67. package/src/types.ts +921 -838
  68. package/src/webhooks.ts +117 -98
package/src/dev.ts CHANGED
@@ -1,761 +1,780 @@
1
- import type {
2
- ApprovalData,
3
- CollectionData,
4
- EvidencePack,
5
- FlowData,
6
- GateData,
7
- ReviewData,
8
- } from "./types.js";
9
-
10
- /**
11
- * Development mode: the whole loop, on your machine, with nobody in it.
12
- *
13
- * ```ts
14
- * const deliverd = new Deliverd({ mode: "development" });
15
- * const decision = await deliverd.approve({ title: "Deploy production" });
16
- * ```
17
- *
18
- * No key, no network, no colleague to interrupt — and the four things that
19
- * can happen to a real request all reachable before you have an account:
20
- * approved, rejected, nobody answered, and somebody asked you a question.
21
- * That last one is the path people forget to write, which is exactly why it
22
- * should be one line to try.
23
- *
24
- * Implemented as a stand-in `fetch` rather than a branch inside the client,
25
- * so development mode runs the *same* code as production — the same retries,
26
- * the same error mapping, the same polling in `wait()`. A simulator that
27
- * bypassed all that would prove your integration works against the simulator.
28
- */
29
-
30
- /**
31
- * What development mode makes happen.
32
- *
33
- * Four for the primitives that ask a person, and a fifth for the gate:
34
- * `denied` is a **policy** refusal, which nothing else can have — an approval
35
- * cannot be refused without somebody refusing it. It is the outcome an agent
36
- * must handle by not retrying, and rehearsing that offline is worth a word of
37
- * its own. The four that involve a person mean the same thing everywhere;
38
- * `denied` on an approval is treated as `rejected`, because a request nobody
39
- * was asked about is not a thing that surface can represent.
40
- */
41
- export type DevelopmentOutcome = "approved" | "rejected" | "denied" | "timeout" | "question";
42
-
43
- export interface DevelopmentOptions {
44
- /**
45
- * What the imaginary approver does. Default `approved`, or the value of
46
- * `DELIVERD_DEV_OUTCOME`, so a whole test suite can be flipped from the
47
- * command line without touching the code.
48
- */
49
- outcome?: DevelopmentOutcome | ((request: ApprovalData) => DevelopmentOutcome);
50
- /** How long they take to do it, in milliseconds. Default 0. */
51
- delay?: number;
52
- /** What they say. Defaults suit the outcome. */
53
- note?: string;
54
- /** What they ask, when the outcome is `question`. */
55
- question?: string;
56
- /** Print what the approver would have seen. Default true. */
57
- log?: boolean;
58
- }
59
-
60
- const DEFAULT_QUESTION = "Has this been through staging?";
61
-
62
- let counter = 0;
63
-
64
- interface Stored {
65
- data: ApprovalData;
66
- /** When the imaginary approver acts. */
67
- decideAt: number;
68
- outcome: DevelopmentOutcome;
69
- options: DevelopmentOptions;
70
- }
71
-
72
- /**
73
- * A `fetch` that serves the approvals, reviews and collections APIs from memory.
74
- *
75
- * Deliberately narrow: it answers the calls the primitives make and 501s the
76
- * rest, with a message saying so, rather than pretending to be the whole API
77
- * and quietly returning something plausible.
78
- */
79
- export function developmentFetch(options: DevelopmentOptions = {}): typeof globalThis.fetch {
80
- const store = new Map<string, Stored>();
81
- const reviewStore = new Map<string, StoredReview>();
82
- const gateStore = new Map<string, StoredGate>();
83
- const collectionStore = new Map<string, StoredCollection>();
84
- const flowStore = new Map<string, FlowData>();
85
-
86
- return (async (input: string | URL | Request, init?: RequestInit) => {
87
- const url = new URL(String(input));
88
- const path = url.pathname.replace(/^\/api\/v1/, "");
89
- const method = (init?.method ?? "GET").toUpperCase();
90
- const body = init?.body ? (JSON.parse(String(init.body)) as Record<string, unknown>) : {};
91
-
92
- const json = (payload: unknown, status = 200) =>
93
- new Response(JSON.stringify(payload), {
94
- status,
95
- headers: { "content-type": "application/json" },
96
- });
97
-
98
- if (method === "POST" && path === "/approvals") {
99
- const id = `apr_dev_${++counter}`;
100
- const outcome = resolveOutcome(options.outcome, body);
101
- const data: ApprovalData = {
102
- id,
103
- status: "pending",
104
- url: `https://deliverd.dev/approve/${id}`,
105
- title: String(body.title ?? "Untitled"),
106
- description: (body.description as string | undefined) ?? null,
107
- risk: (body.risk as ApprovalData["risk"] | undefined) ?? "medium",
108
- factors: (body.factors as ApprovalData["factors"]) ?? [],
109
- links: (body.links as ApprovalData["links"]) ?? [],
110
- reportId: (body.reportId as string | undefined) ?? null,
111
- externalId: (body.externalId as string | undefined) ?? null,
112
- metadata: (body.metadata as Record<string, unknown>) ?? {},
113
- requestedBy: "You (development mode)",
114
- approvers: (body.approvers as string[] | undefined) ?? [],
115
- /*
116
- * One, always. A standing rule could raise it on a real organisation,
117
- * but development mode has no rules to read and an imaginary approver
118
- * cannot be two people — pretending otherwise would let a caller test
119
- * an escalation that never happened.
120
- */
121
- requiredApprovals: 1,
122
- approvalsSoFar: 0,
123
- decidedBy: null,
124
- decidedById: null,
125
- decidedAt: null,
126
- note: null,
127
- expiresAt: (body.expiresAt as string | undefined) ?? null,
128
- questions:
129
- outcome === "question"
130
- ? [
131
- {
132
- id: `q_dev_${counter}`,
133
- question: options.question ?? DEFAULT_QUESTION,
134
- answer: null,
135
- askedAt: new Date().toISOString(),
136
- answeredAt: null,
137
- },
138
- ]
139
- : [],
140
- createdAt: new Date().toISOString(),
141
- };
142
- store.set(id, {
143
- data,
144
- decideAt: Date.now() + (options.delay ?? 0),
145
- outcome,
146
- options,
147
- });
148
- if (options.log !== false) announce(data, outcome);
149
- return json(data, 201);
150
- }
151
-
152
- const match = /^\/approvals\/([^/]+)(\/answers|\/cancel)?$/.exec(path);
153
- if (match) {
154
- const stored = store.get(match[1]!);
155
- if (!stored) {
156
- return json({ error: { code: "not_found", message: "No such approval in this development session." } }, 404);
157
- }
158
- if (match[2] === "/answers") {
159
- const question = stored.data.questions.find((q) => q.id === body.questionId);
160
- if (!question) {
161
- return json({ error: { code: "question_not_found", message: "No such question." } }, 404);
162
- }
163
- question.answer = String(body.answer);
164
- question.answeredAt = new Date().toISOString();
165
- // Answered: the imaginary approver is satisfied and approves.
166
- stored.outcome = "approved";
167
- stored.decideAt = Date.now() + (stored.options.delay ?? 0);
168
- if (stored.options.log !== false) {
169
- console.log(` ↳ answered: ${question.answer}\n`);
170
- }
171
- return json(stored.data);
172
- }
173
- if (match[2] === "/cancel") {
174
- stored.data.status = "cancelled";
175
- return json(stored.data);
176
- }
177
- settle(stored);
178
- return json(stored.data);
179
- }
180
-
181
- if (method === "POST" && path === "/reviews") {
182
- const id = `rev_dev_${++counter}`;
183
- /*
184
- * The same outcome switch as approvals, mapped onto a review's endings:
185
- * a rejection is "changes requested", because that is what saying no to
186
- * a piece of work means. A simulated question has nothing to ask about
187
- * here — there is no question mechanism on a review — so it approves.
188
- */
189
- const outcome = resolveOutcome(options.outcome, body);
190
- const verdict = outcome === "rejected" ? "changes_requested" : "approved";
191
- const reviewers = ((body.reviewers as string[] | undefined) ?? []).map((email, i) => ({
192
- kind: "user" as const,
193
- id: `usr_dev_${i + 1}`,
194
- label: email,
195
- }));
196
- const data: ReviewData = {
197
- id,
198
- status: "pending",
199
- url: `https://deliverd.dev/reviews/${id}`,
200
- title: String(body.title ?? "Untitled"),
201
- instructions: (body.instructions as string | undefined) ?? null,
202
- reportId: (body.reportId as string | undefined) ?? null,
203
- versionId: (body.versionId as string | undefined) ?? null,
204
- externalId: (body.externalId as string | undefined) ?? null,
205
- metadata: (body.metadata as Record<string, unknown>) ?? {},
206
- requestedBy: "You (development mode)",
207
- requiredApprovals: (body.requiredApprovals as number | undefined) ?? 1,
208
- reviewers,
209
- verdicts: [],
210
- /*
211
- * A review that asks for changes has something to read, and the count
212
- * is what the caller acts on. Zero made the one path that matters read
213
- * as "changes requested — 0 threads", which tells somebody running
214
- * this for the first time that the feature does not work.
215
- */
216
- threadCount: verdict === "changes_requested" ? 2 : 0,
217
- settledAt: null,
218
- expiresAt: (body.expiresAt as string | undefined) ?? null,
219
- createdAt: new Date().toISOString(),
220
- };
221
- reviewStore.set(id, {
222
- data,
223
- settleAt: Date.now() + (options.delay ?? 0),
224
- verdict,
225
- timeout: outcome === "timeout",
226
- });
227
- if (options.log !== false) announceReview(data, verdict, outcome === "timeout");
228
- return json(data, 201);
229
- }
230
-
231
- /*
232
- * The gate, offline.
233
- *
234
- * `DELIVERD_DEV_OUTCOME` means the same thing here as everywhere else, with
235
- * one addition: `denied` is a *policy* refusal, which has no equivalent on
236
- * the other primitives because nothing else can be refused without a person
237
- * being asked. The default stays `approved`, so `gate()` runs green out of
238
- * the box and the interesting cases are the ones you opt into.
239
- *
240
- * `allowed` and `denied` settle instantly, as a real rule does. `approved`
241
- * and `rejected` go through `pending` first, because that is the path with
242
- * a `wait()` in it and the one worth being able to rehearse.
243
- */
244
- if (method === "POST" && path === "/gates") {
245
- const id = `gat_dev_${++counter}`;
246
- const externalId = String(body.externalId ?? "");
247
-
248
- /*
249
- * Server-side reuse, which the real endpoint enforces in the database.
250
- * Offline it is a map lookup, and it is here rather than left out
251
- * because the one thing `gate()` promises over `approve()` is that a
252
- * retry re-reads its decision — testing that without an account is the
253
- * whole point of this file.
254
- */
255
- for (const stored of gateStore.values()) {
256
- if (stored.data.externalId === externalId) {
257
- settleGate(stored);
258
- return json({ ...stored.data.gate, reused: true });
259
- }
260
- }
261
-
262
- const outcome = resolveOutcome(options.outcome, body);
263
- /*
264
- * `denied` is settled by a rule and reaches nobody; everything else goes
265
- * through a person, which is where `wait()` earns its place. The default
266
- * `approved` therefore rehearses the escalation path rather than the
267
- * auto-allow — the opposite of production's common case, and the right
268
- * default here, because the path with a wait in it is the one worth
269
- * being able to run before you have an account.
270
- */
271
- const byRule = outcome === "denied";
272
- const gate: GateData = {
273
- id,
274
- status: byRule ? "denied" : "pending",
275
- allowed: false,
276
- input: (body.input as Record<string, unknown>) ?? {},
277
- basis: byRule ? "policy" : "human",
278
- reason: byRule
279
- ? "Development mode refused it. A real rule would say which one and why."
280
- : "No rule covers this action yet, so it needs a person.",
281
- rule: byRule ? "Development mode" : null,
282
- policyVersionId: null,
283
- approvalId: byRule ? null : `apr_dev_${id}`,
284
- approvalUrl: byRule ? null : `https://deliverd.dev/approve/apr_dev_${id}`,
285
- outcome: null,
286
- settledAt: null,
287
- reused: false,
288
- };
289
- gateStore.set(id, {
290
- data: { gate, externalId },
291
- outcome,
292
- decideAt: Date.now() + (options.delay ?? 0),
293
- });
294
- return json(gate, 201);
295
- }
296
-
297
- const gateMatch = /^\/gates\/([^/]+)$/.exec(path);
298
- if (gateMatch && method === "GET") {
299
- const stored = gateStore.get(gateMatch[1]!);
300
- if (!stored) {
301
- return json(
302
- { error: { code: "not_found", message: "No such gate in this development session." } },
303
- 404
304
- );
305
- }
306
- settleGate(stored);
307
- return json(stored.data.gate);
308
- }
309
-
310
- const reviewMatch = /^\/reviews\/([^/]+)(\/cancel)?$/.exec(path);
311
- if (reviewMatch) {
312
- const stored = reviewStore.get(reviewMatch[1]!);
313
- if (!stored) {
314
- return json(
315
- { error: { code: "not_found", message: "No such review in this development session." } },
316
- 404
317
- );
318
- }
319
- if (reviewMatch[2] === "/cancel") {
320
- stored.data.status = "cancelled";
321
- return json(stored.data);
322
- }
323
- settleReview(stored);
324
- return json(stored.data);
325
- }
326
-
327
- /*
328
- * Listing approvals, which `findByExternalId` needs.
329
- *
330
- * Missing until an example used `externalId` for retry safety and got a
331
- * 501 instead. Reviews, collections and flows all had their list route
332
- * from the start; approvals — the primitive the feature is most documented
333
- * on — did not, so the one thing that stops a restarted agent asking twice
334
- * was the one thing you could not try without an account.
335
- */
336
- if (method === "GET" && path === "/approvals") {
337
- const externalId = url.searchParams.get("externalId");
338
- const status = url.searchParams.get("status");
339
- // Settle first: a caller listing before polling should see the same
340
- // state a poll would have shown it, not a stale `pending`.
341
- for (const stored of store.values()) settle(stored);
342
- let all = [...store.values()].map((a) => a.data);
343
- if (externalId) all = all.filter((a) => a.externalId === externalId);
344
- if (status) all = all.filter((a) => a.status === status);
345
- return json({ approvals: all });
346
- }
347
-
348
- if (method === "GET" && path === "/reviews") {
349
- const externalId = url.searchParams.get("externalId");
350
- const all = [...reviewStore.values()].map((r) => r.data);
351
- return json({
352
- reviews: externalId ? all.filter((r) => r.externalId === externalId) : all,
353
- });
354
- }
355
-
356
- if (method === "POST" && path === "/collections") {
357
- const id = `col_dev_${++counter}`;
358
- const outcome = resolveOutcome(options.outcome, body);
359
- const asked = ((body.respondents as string[] | undefined) ?? []).map(String);
360
- const questions = ((body.questions as Record<string, unknown>[] | undefined) ?? []).map(
361
- (q, i) => ({
362
- id: `q_dev_${i + 1}`,
363
- prompt: String(q.prompt ?? "Question"),
364
- help: (q.help as string | undefined) ?? null,
365
- kind: (q.kind as CollectionData["questions"][number]["kind"]) ?? "text",
366
- required: q.required !== false,
367
- options: (q.options as string[] | undefined) ?? [],
368
- })
369
- );
370
- const data: CollectionData = {
371
- id,
372
- status: "pending",
373
- url: `https://deliverd.dev/collect/${id}`,
374
- title: String(body.title ?? "Untitled"),
375
- instructions: (body.instructions as string | undefined) ?? null,
376
- reportId: (body.reportId as string | undefined) ?? null,
377
- externalId: (body.externalId as string | undefined) ?? null,
378
- metadata: (body.metadata as Record<string, unknown>) ?? {},
379
- requestedBy: "You (development mode)",
380
- requiredResponses: (body.requiredResponses as number | undefined) ?? (asked.length || 1),
381
- questions,
382
- responses: asked.map((who) => ({
383
- respondent: who,
384
- status: "pending" as const,
385
- submittedAt: null,
386
- answers: [],
387
- })),
388
- submittedCount: 0,
389
- askedCount: asked.length,
390
- settledAt: null,
391
- dueAt: (body.dueAt as string | undefined) ?? null,
392
- expiresAt: (body.expiresAt as string | undefined) ?? null,
393
- createdAt: new Date().toISOString(),
394
- };
395
- collectionStore.set(id, {
396
- data,
397
- settleAt: Date.now() + (options.delay ?? 0),
398
- /*
399
- * A simulated rejection becomes an expiry here: there is no way to
400
- * say no to a question, only to leave it unanswered, and that is the
401
- * ending a caller most needs to have thought about.
402
- */
403
- expire: outcome === "rejected",
404
- timeout: outcome === "timeout",
405
- });
406
- if (options.log !== false) announceCollection(data, outcome);
407
- return json(data, 201);
408
- }
409
-
410
- const collectionMatch = /^\/collections\/([^/]+)(\/cancel)?$/.exec(path);
411
- if (collectionMatch) {
412
- const stored = collectionStore.get(collectionMatch[1]!);
413
- if (!stored) {
414
- return json(
415
- { error: { code: "not_found", message: "No such request in this development session." } },
416
- 404
417
- );
418
- }
419
- if (collectionMatch[2] === "/cancel") {
420
- stored.data.status = "cancelled";
421
- return json(stored.data);
422
- }
423
- settleCollection(stored);
424
- return json(stored.data);
425
- }
426
-
427
- if (method === "GET" && path === "/collections") {
428
- const externalId = url.searchParams.get("externalId");
429
- const all = [...collectionStore.values()].map((c) => c.data);
430
- return json({
431
- collections: externalId ? all.filter((c) => c.externalId === externalId) : all,
432
- });
433
- }
434
-
435
- /*
436
- * Flows in development are real objects with no simulation attached:
437
- * there is nobody to imagine, and the thing worth exercising offline is
438
- * that `flow.approve()` reaches the same code as `deliverd.approve()`.
439
- * Members are not tracked here — the server derives them from rows this
440
- * store does not keep — so a development flow reports what it knows and
441
- * does not invent a membership.
442
- */
443
- if (method === "POST" && path === "/flows") {
444
- const id = `flw_dev_${++counter}`;
445
- const data: FlowData = {
446
- id,
447
- status: "open",
448
- url: `https://deliverd.dev/flows/${id}`,
449
- title: String(body.title ?? "Untitled"),
450
- description: (body.description as string | undefined) ?? null,
451
- externalId: (body.externalId as string | undefined) ?? null,
452
- metadata: (body.metadata as Record<string, unknown>) ?? {},
453
- startedBy: "You (development mode)",
454
- members: [],
455
- memberCount: 0,
456
- openCount: 0,
457
- allSettled: false,
458
- timeline: [],
459
- settledAt: null,
460
- createdAt: new Date().toISOString(),
461
- };
462
- flowStore.set(id, data);
463
- if (options.log !== false) {
464
- console.log(`\n \u25B8 Flow started: ${data.title}\n ${data.url}\n`);
465
- }
466
- return json(data, 201);
467
- }
468
-
469
- /*
470
- * Evidence in development is the shape and not the substance: this store
471
- * holds no audit rows, so the pack comes back with the subject and an
472
- * empty record rather than an invented one. What it proves is that
473
- * `flow.evidence()` reaches the right path and returns something a caller
474
- * can destructure — an imaginary approval trail would be worse than none.
475
- */
476
- const evidenceMatch = /^\/(flows|reports)\/([^/]+)\/evidence$/.exec(path);
477
- if (evidenceMatch && method === "GET") {
478
- const kind = evidenceMatch[1] === "flows" ? "flow" : "report";
479
- const id = evidenceMatch[2]!;
480
- const title = kind === "flow" ? (flowStore.get(id)?.title ?? "A flow") : "A report";
481
- const now = new Date().toISOString();
482
- const pack: EvidencePack = {
483
- packVersion: 2,
484
- generatedAt: now,
485
- generatedBy: "You (development mode)",
486
- organisation: { id: "org_dev", name: "Development" },
487
- subject: {
488
- kind,
489
- id,
490
- title,
491
- url: `https://deliverd.dev/${evidenceMatch[1]}/${id}`,
492
- status: "open",
493
- startedBy: "You (development mode)",
494
- startedAt: now,
495
- },
496
- summary: { steps: 0, events: 0, firstEventAt: null, lastEventAt: null },
497
- steps: [],
498
- timeline: [],
499
- integrity: {
500
- algorithm: "sha256",
501
- digest: "development",
502
- covers: "Nothing: this pack was produced in development mode and holds no records.",
503
- doesNotCover: "Everything. Do not hand this to anybody.",
504
- recordsAreInsertOnly: true,
505
- },
506
- };
507
- return json(pack);
508
- }
509
-
510
- const flowMatch = /^\/flows\/([^/]+)(\/complete|\/cancel)?$/.exec(path);
511
- if (flowMatch) {
512
- const flow = flowStore.get(flowMatch[1]!);
513
- if (!flow) {
514
- return json(
515
- { error: { code: "not_found", message: "No such flow in this development session." } },
516
- 404
517
- );
518
- }
519
- if (flowMatch[2] === "/complete" || flowMatch[2] === "/cancel") {
520
- if (flow.status !== "open") {
521
- return json(
522
- { error: { code: "not_open", message: `This flow is already ${flow.status}.` } },
523
- 409
524
- );
525
- }
526
- flow.status = flowMatch[2] === "/complete" ? "complete" : "cancelled";
527
- flow.settledAt = new Date().toISOString();
528
- }
529
- return json(flow);
530
- }
531
-
532
- if (method === "GET" && path === "/flows") {
533
- const externalId = url.searchParams.get("externalId");
534
- const all = [...flowStore.values()];
535
- return json({ flows: externalId ? all.filter((f) => f.externalId === externalId) : all });
536
- }
537
-
538
- return json(
539
- {
540
- error: {
541
- code: "not_in_development_mode",
542
- 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.`,
543
- },
544
- },
545
- 501
546
- );
547
- }) as typeof globalThis.fetch;
548
- }
549
-
550
- function resolveOutcome(
551
- outcome: DevelopmentOptions["outcome"],
552
- body: Record<string, unknown>
553
- ): DevelopmentOutcome {
554
- const fromEnv = process.env.DELIVERD_DEV_OUTCOME as DevelopmentOutcome | undefined;
555
- const chosen = outcome ?? fromEnv ?? "approved";
556
- return typeof chosen === "function" ? chosen(body as unknown as ApprovalData) : chosen;
557
- }
558
-
559
- /** Move a pending request to its outcome once the imaginary approver has had time. */
560
- function settle(stored: Stored): void {
561
- if (stored.data.status !== "pending") return;
562
- if (Date.now() < stored.decideAt) return;
563
- if (stored.outcome === "timeout") return;
564
- if (stored.outcome === "question" && stored.data.questions.some((q) => !q.answer)) return;
565
-
566
- stored.data.status = stored.outcome === "rejected" ? "rejected" : "approved";
567
- /*
568
- * The same shape production sends: a person's name in `decidedBy` and the
569
- * key in `decidedById`. It used to be an email-shaped string alone, so the
570
- * offline loop taught a shape a real organisation never delivers.
571
- */
572
- stored.data.decidedBy = "Development approver";
573
- stored.data.decidedById = "00000000-0000-0000-0000-00000000dev0";
574
- stored.data.decidedAt = new Date().toISOString();
575
- stored.data.note =
576
- stored.options.note ??
577
- (stored.data.status === "rejected" ? "Not yet — development mode says no." : null);
578
- }
579
-
580
- /**
581
- * What the approver would have seen, in the terminal.
582
- *
583
- * The reason this is worth the lines: the title and the factors are copy
584
- * somebody has to read on a phone at nine at night, and the only way to know
585
- * whether it reads well is to see it written out.
586
- */
587
- function announce(data: ApprovalData, outcome: DevelopmentOutcome): void {
588
- const lines = [
589
- "",
590
- " ┌─ Deliverd · development mode ─────────────────────────",
591
- ` │ ${data.title}`,
592
- ];
593
- if (data.description) lines.push(` │ ${data.description}`);
594
- lines.push(` │ Risk: ${data.risk}`);
595
- for (const factor of data.factors) {
596
- const mark = factor.status === "ok" ? "✓" : factor.status === "warning" ? "⚠" : "·";
597
- lines.push(` │ ${mark} ${factor.label}`);
598
- }
599
- if (data.approvers.length > 0) lines.push(` │ To: ${data.approvers.join(", ")}`);
600
- lines.push(
601
- " │",
602
- ` │ Simulating: ${outcome}${outcome === "question" ? " (needs an onQuestion handler)" : ""}`,
603
- " └───────────────────────────────────────────────────────",
604
- ""
605
- );
606
- console.log(lines.join("\n"));
607
- }
608
-
609
-
610
- interface StoredGate {
611
- /** The decision, plus the caller's id kept beside it for the reuse lookup. */
612
- data: { gate: GateData; externalId: string };
613
- outcome: DevelopmentOutcome;
614
- decideAt: number;
615
- }
616
-
617
- /**
618
- * A gate that went to a person, once that person has answered.
619
- *
620
- * Only the two outcomes that involve one. `allowed` and `denied` were settled
621
- * by a rule at creation and have nothing to wait for — which is the honest
622
- * shape, because in production most gated calls never reach a human either.
623
- */
624
- function settleGate(stored: StoredGate): void {
625
- const gate = stored.data.gate;
626
- if (gate.status !== "pending") return;
627
- if (Date.now() < stored.decideAt) return;
628
- if (stored.outcome === "timeout" || stored.outcome === "question") return;
629
- if (stored.outcome === "denied") return;
630
-
631
- const approved = stored.outcome === "approved";
632
- gate.status = approved ? "approved" : "rejected";
633
- gate.allowed = approved;
634
- gate.outcome = approved ? "approved" : "rejected";
635
- gate.settledAt = new Date().toISOString();
636
- gate.basis = "human";
637
- gate.reason = approved
638
- ? "A development approver agreed to it."
639
- : "A development approver refused it.";
640
- }
641
-
642
- interface StoredReview {
643
- data: ReviewData;
644
- settleAt: number;
645
- verdict: "approved" | "changes_requested";
646
- timeout: boolean;
647
- }
648
-
649
- /** Settle it once its moment has passed, unless it is meant to hang. */
650
- function settleReview(stored: StoredReview): void {
651
- if (stored.timeout || stored.data.status !== "pending") return;
652
- if (Date.now() < stored.settleAt) return;
653
- stored.data.verdicts = [
654
- {
655
- verdict: stored.verdict,
656
- by: stored.data.reviewers[0]?.label ?? "A reviewer (development mode)",
657
- note:
658
- stored.verdict === "changes_requested"
659
- ? "Simulated: the figures on page two do not tie back."
660
- : null,
661
- at: new Date().toISOString(),
662
- },
663
- ];
664
- stored.data.status = stored.verdict;
665
- stored.data.settledAt = new Date().toISOString();
666
- }
667
-
668
- function announceReview(
669
- data: ReviewData,
670
- verdict: "approved" | "changes_requested",
671
- willHang: boolean
672
- ): void {
673
- const lines = [
674
- ` ┌─ Deliverd · development mode ─────────────────────────`,
675
- ` │ ${data.title}`,
676
- ...(data.instructions ? [` │ Check: ${data.instructions}`] : []),
677
- ` │ Reviewers: ${data.reviewers.map((r) => r.label).join(", ") || "nobody named"}`,
678
- ` │`,
679
- ` │ Simulating: ${willHang ? "nobody reviews it" : verdict.replace("_", " ")}`,
680
- ` └───────────────────────────────────────────────────────`,
681
- "",
682
- ];
683
- console.log(lines.join("\n"));
684
- }
685
-
686
-
687
- interface StoredCollection {
688
- data: CollectionData;
689
- settleAt: number;
690
- expire: boolean;
691
- timeout: boolean;
692
- }
693
-
694
- /**
695
- * Everyone answers, at the same moment, with a plausible value for the kind
696
- * of question asked. Plausible rather than empty, because a caller writing
697
- * `answers["Headcount at 30 September"] + 1` should find out here that it is
698
- * a number, not in production.
699
- */
700
- function settleCollection(stored: StoredCollection): void {
701
- if (stored.timeout || stored.data.status !== "pending") return;
702
- if (Date.now() < stored.settleAt) return;
703
- if (stored.expire) {
704
- stored.data.status = "expired";
705
- stored.data.settledAt = new Date().toISOString();
706
- return;
707
- }
708
- const at = new Date().toISOString();
709
- stored.data.responses = stored.data.responses.map((r) => ({
710
- ...r,
711
- status: "submitted" as const,
712
- submittedAt: at,
713
- answers: stored.data.questions.map((q) => ({
714
- question: q.prompt,
715
- kind: q.kind,
716
- value: sampleAnswer(q),
717
- })),
718
- }));
719
- stored.data.submittedCount = stored.data.responses.length;
720
- stored.data.status = "complete";
721
- stored.data.settledAt = at;
722
- }
723
-
724
- function sampleAnswer(q: CollectionData["questions"][number]): string | number | boolean | string[] {
725
- switch (q.kind) {
726
- case "number":
727
- return 42;
728
- case "boolean":
729
- return true;
730
- case "date":
731
- return new Date().toISOString().slice(0, 10);
732
- case "choice":
733
- return q.options[0] ?? "";
734
- case "multi_choice":
735
- return q.options.slice(0, 1);
736
- case "long_text":
737
- return "Simulated: a longer answer than a line.";
738
- default:
739
- return "Simulated answer";
740
- }
741
- }
742
-
743
- function announceCollection(data: CollectionData, outcome: string): void {
744
- const lines = [
745
- ` ┌─ Deliverd · development mode ─────────────────────────`,
746
- ` │ ${data.title}`,
747
- ` │ Asking: ${data.questions.map((q) => q.prompt).join(" · ") || "nothing"}`,
748
- ` │ Of: ${data.responses.map((r) => r.respondent).join(", ") || "nobody named"}`,
749
- ` │`,
750
- ` │ Simulating: ${
751
- outcome === "timeout"
752
- ? "nobody answers"
753
- : outcome === "rejected"
754
- ? "it expires unanswered"
755
- : "everyone answers"
756
- }`,
757
- ` └───────────────────────────────────────────────────────`,
758
- "",
759
- ];
760
- console.log(lines.join("\n"));
761
- }
1
+ import type {
2
+ ApprovalData,
3
+ CollectionData,
4
+ EvidencePack,
5
+ FlowData,
6
+ GateData,
7
+ ReviewData,
8
+ } from "./types.js";
9
+
10
+ /**
11
+ * Development mode: the whole loop, on your machine, with nobody in it.
12
+ *
13
+ * ```ts
14
+ * const deliverd = new Deliverd({ mode: "development" });
15
+ * const decision = await deliverd.approve({ title: "Deploy production" });
16
+ * ```
17
+ *
18
+ * No key, no network, no colleague to interrupt — and the four things that
19
+ * can happen to a real request all reachable before you have an account:
20
+ * approved, rejected, nobody answered, and somebody asked you a question.
21
+ * That last one is the path people forget to write, which is exactly why it
22
+ * should be one line to try.
23
+ *
24
+ * Implemented as a stand-in `fetch` rather than a branch inside the client,
25
+ * so development mode runs the *same* code as production — the same retries,
26
+ * the same error mapping, the same polling in `wait()`. A simulator that
27
+ * bypassed all that would prove your integration works against the simulator.
28
+ */
29
+
30
+ /**
31
+ * What development mode makes happen.
32
+ *
33
+ * Four for the primitives that ask a person, and a fifth for the gate:
34
+ * `denied` is a **policy** refusal, which nothing else can have — an approval
35
+ * cannot be refused without somebody refusing it. It is the outcome an agent
36
+ * must handle by not retrying, and rehearsing that offline is worth a word of
37
+ * its own. The four that involve a person mean the same thing everywhere;
38
+ * `denied` on an approval is treated as `rejected`, because a request nobody
39
+ * was asked about is not a thing that surface can represent.
40
+ */
41
+ export type DevelopmentOutcome = "approved" | "rejected" | "denied" | "timeout" | "question";
42
+
43
+ export interface DevelopmentOptions {
44
+ /**
45
+ * What the imaginary approver does. Default `approved`, or the value of
46
+ * `DELIVERD_DEV_OUTCOME`, so a whole test suite can be flipped from the
47
+ * command line without touching the code.
48
+ */
49
+ outcome?: DevelopmentOutcome | ((request: ApprovalData) => DevelopmentOutcome);
50
+ /** How long they take to do it, in milliseconds. Default 0. */
51
+ delay?: number;
52
+ /** What they say. Defaults suit the outcome. */
53
+ note?: string;
54
+ /**
55
+ * Corrections the imaginary approver makes when approving a request that
56
+ * sent an `input`, so the approve-with-changes path can be run offline.
57
+ * Only fields you named in `editableFields` are applied, as in production.
58
+ */
59
+ edits?: Record<string, unknown>;
60
+ /** What they ask, when the outcome is `question`. */
61
+ question?: string;
62
+ /** Print what the approver would have seen. Default true. */
63
+ log?: boolean;
64
+ }
65
+
66
+ const DEFAULT_QUESTION = "Has this been through staging?";
67
+
68
+ let counter = 0;
69
+
70
+ interface Stored {
71
+ data: ApprovalData;
72
+ /** When the imaginary approver acts. */
73
+ decideAt: number;
74
+ outcome: DevelopmentOutcome;
75
+ options: DevelopmentOptions;
76
+ }
77
+
78
+ /**
79
+ * A `fetch` that serves the approvals, reviews and collections APIs from memory.
80
+ *
81
+ * Deliberately narrow: it answers the calls the primitives make and 501s the
82
+ * rest, with a message saying so, rather than pretending to be the whole API
83
+ * and quietly returning something plausible.
84
+ */
85
+ export function developmentFetch(options: DevelopmentOptions = {}): typeof globalThis.fetch {
86
+ const store = new Map<string, Stored>();
87
+ const reviewStore = new Map<string, StoredReview>();
88
+ const gateStore = new Map<string, StoredGate>();
89
+ const collectionStore = new Map<string, StoredCollection>();
90
+ const flowStore = new Map<string, FlowData>();
91
+
92
+ return (async (input: string | URL | Request, init?: RequestInit) => {
93
+ const url = new URL(String(input));
94
+ const path = url.pathname.replace(/^\/api\/v1/, "");
95
+ const method = (init?.method ?? "GET").toUpperCase();
96
+ const body = init?.body ? (JSON.parse(String(init.body)) as Record<string, unknown>) : {};
97
+
98
+ const json = (payload: unknown, status = 200) =>
99
+ new Response(JSON.stringify(payload), {
100
+ status,
101
+ headers: { "content-type": "application/json" },
102
+ });
103
+
104
+ if (method === "POST" && path === "/approvals") {
105
+ const id = `apr_dev_${++counter}`;
106
+ const outcome = resolveOutcome(options.outcome, body);
107
+ const data: ApprovalData = {
108
+ id,
109
+ status: "pending",
110
+ url: `https://deliverd.dev/approve/${id}`,
111
+ title: String(body.title ?? "Untitled"),
112
+ description: (body.description as string | undefined) ?? null,
113
+ risk: (body.risk as ApprovalData["risk"] | undefined) ?? "medium",
114
+ factors: (body.factors as ApprovalData["factors"]) ?? [],
115
+ links: (body.links as ApprovalData["links"]) ?? [],
116
+ reportId: (body.reportId as string | undefined) ?? null,
117
+ externalId: (body.externalId as string | undefined) ?? null,
118
+ metadata: (body.metadata as Record<string, unknown>) ?? {},
119
+ input: (body.input as Record<string, unknown> | undefined) ?? null,
120
+ editableFields: (body.editableFields as string[] | undefined) ?? [],
121
+ approvedInput: null,
122
+ changes: [],
123
+ requestedBy: "You (development mode)",
124
+ approvers: (body.approvers as string[] | undefined) ?? [],
125
+ /*
126
+ * One, always. A standing rule could raise it on a real organisation,
127
+ * but development mode has no rules to read and an imaginary approver
128
+ * cannot be two people — pretending otherwise would let a caller test
129
+ * an escalation that never happened.
130
+ */
131
+ requiredApprovals: 1,
132
+ approvalsSoFar: 0,
133
+ decidedBy: null,
134
+ decidedById: null,
135
+ decidedAt: null,
136
+ note: null,
137
+ expiresAt: (body.expiresAt as string | undefined) ?? null,
138
+ questions:
139
+ outcome === "question"
140
+ ? [
141
+ {
142
+ id: `q_dev_${counter}`,
143
+ question: options.question ?? DEFAULT_QUESTION,
144
+ answer: null,
145
+ askedAt: new Date().toISOString(),
146
+ answeredAt: null,
147
+ },
148
+ ]
149
+ : [],
150
+ createdAt: new Date().toISOString(),
151
+ };
152
+ store.set(id, {
153
+ data,
154
+ decideAt: Date.now() + (options.delay ?? 0),
155
+ outcome,
156
+ options,
157
+ });
158
+ if (options.log !== false) announce(data, outcome);
159
+ return json(data, 201);
160
+ }
161
+
162
+ const match = /^\/approvals\/([^/]+)(\/answers|\/cancel)?$/.exec(path);
163
+ if (match) {
164
+ const stored = store.get(match[1]!);
165
+ if (!stored) {
166
+ return json({ error: { code: "not_found", message: "No such approval in this development session." } }, 404);
167
+ }
168
+ if (match[2] === "/answers") {
169
+ const question = stored.data.questions.find((q) => q.id === body.questionId);
170
+ if (!question) {
171
+ return json({ error: { code: "question_not_found", message: "No such question." } }, 404);
172
+ }
173
+ question.answer = String(body.answer);
174
+ question.answeredAt = new Date().toISOString();
175
+ // Answered: the imaginary approver is satisfied and approves.
176
+ stored.outcome = "approved";
177
+ stored.decideAt = Date.now() + (stored.options.delay ?? 0);
178
+ if (stored.options.log !== false) {
179
+ console.log(` ↳ answered: ${question.answer}\n`);
180
+ }
181
+ return json(stored.data);
182
+ }
183
+ if (match[2] === "/cancel") {
184
+ stored.data.status = "cancelled";
185
+ return json(stored.data);
186
+ }
187
+ settle(stored);
188
+ return json(stored.data);
189
+ }
190
+
191
+ if (method === "POST" && path === "/reviews") {
192
+ const id = `rev_dev_${++counter}`;
193
+ /*
194
+ * The same outcome switch as approvals, mapped onto a review's endings:
195
+ * a rejection is "changes requested", because that is what saying no to
196
+ * a piece of work means. A simulated question has nothing to ask about
197
+ * here — there is no question mechanism on a review — so it approves.
198
+ */
199
+ const outcome = resolveOutcome(options.outcome, body);
200
+ const verdict = outcome === "rejected" ? "changes_requested" : "approved";
201
+ const reviewers = ((body.reviewers as string[] | undefined) ?? []).map((email, i) => ({
202
+ kind: "user" as const,
203
+ id: `usr_dev_${i + 1}`,
204
+ label: email,
205
+ }));
206
+ const data: ReviewData = {
207
+ id,
208
+ status: "pending",
209
+ url: `https://deliverd.dev/reviews/${id}`,
210
+ title: String(body.title ?? "Untitled"),
211
+ instructions: (body.instructions as string | undefined) ?? null,
212
+ reportId: (body.reportId as string | undefined) ?? null,
213
+ versionId: (body.versionId as string | undefined) ?? null,
214
+ externalId: (body.externalId as string | undefined) ?? null,
215
+ metadata: (body.metadata as Record<string, unknown>) ?? {},
216
+ requestedBy: "You (development mode)",
217
+ requiredApprovals: (body.requiredApprovals as number | undefined) ?? 1,
218
+ reviewers,
219
+ verdicts: [],
220
+ /*
221
+ * A review that asks for changes has something to read, and the count
222
+ * is what the caller acts on. Zero made the one path that matters read
223
+ * as "changes requested — 0 threads", which tells somebody running
224
+ * this for the first time that the feature does not work.
225
+ */
226
+ threadCount: verdict === "changes_requested" ? 2 : 0,
227
+ settledAt: null,
228
+ expiresAt: (body.expiresAt as string | undefined) ?? null,
229
+ createdAt: new Date().toISOString(),
230
+ };
231
+ reviewStore.set(id, {
232
+ data,
233
+ settleAt: Date.now() + (options.delay ?? 0),
234
+ verdict,
235
+ timeout: outcome === "timeout",
236
+ });
237
+ if (options.log !== false) announceReview(data, verdict, outcome === "timeout");
238
+ return json(data, 201);
239
+ }
240
+
241
+ /*
242
+ * The gate, offline.
243
+ *
244
+ * `DELIVERD_DEV_OUTCOME` means the same thing here as everywhere else, with
245
+ * one addition: `denied` is a *policy* refusal, which has no equivalent on
246
+ * the other primitives because nothing else can be refused without a person
247
+ * being asked. The default stays `approved`, so `gate()` runs green out of
248
+ * the box and the interesting cases are the ones you opt into.
249
+ *
250
+ * `allowed` and `denied` settle instantly, as a real rule does. `approved`
251
+ * and `rejected` go through `pending` first, because that is the path with
252
+ * a `wait()` in it and the one worth being able to rehearse.
253
+ */
254
+ if (method === "POST" && path === "/gates") {
255
+ const id = `gat_dev_${++counter}`;
256
+ const externalId = String(body.externalId ?? "");
257
+
258
+ /*
259
+ * Server-side reuse, which the real endpoint enforces in the database.
260
+ * Offline it is a map lookup, and it is here rather than left out
261
+ * because the one thing `gate()` promises over `approve()` is that a
262
+ * retry re-reads its decision — testing that without an account is the
263
+ * whole point of this file.
264
+ */
265
+ for (const stored of gateStore.values()) {
266
+ if (stored.data.externalId === externalId) {
267
+ settleGate(stored);
268
+ return json({ ...stored.data.gate, reused: true });
269
+ }
270
+ }
271
+
272
+ const outcome = resolveOutcome(options.outcome, body);
273
+ /*
274
+ * `denied` is settled by a rule and reaches nobody; everything else goes
275
+ * through a person, which is where `wait()` earns its place. The default
276
+ * `approved` therefore rehearses the escalation path rather than the
277
+ * auto-allow — the opposite of production's common case, and the right
278
+ * default here, because the path with a wait in it is the one worth
279
+ * being able to run before you have an account.
280
+ */
281
+ const byRule = outcome === "denied";
282
+ const gate: GateData = {
283
+ id,
284
+ status: byRule ? "denied" : "pending",
285
+ allowed: false,
286
+ input: (body.input as Record<string, unknown>) ?? {},
287
+ changes: [],
288
+ basis: byRule ? "policy" : "human",
289
+ reason: byRule
290
+ ? "Development mode refused it. A real rule would say which one and why."
291
+ : "No rule covers this action yet, so it needs a person.",
292
+ rule: byRule ? "Development mode" : null,
293
+ policyVersionId: null,
294
+ approvalId: byRule ? null : `apr_dev_${id}`,
295
+ approvalUrl: byRule ? null : `https://deliverd.dev/approve/apr_dev_${id}`,
296
+ outcome: null,
297
+ settledAt: null,
298
+ reused: false,
299
+ };
300
+ gateStore.set(id, {
301
+ data: { gate, externalId },
302
+ outcome,
303
+ decideAt: Date.now() + (options.delay ?? 0),
304
+ });
305
+ return json(gate, 201);
306
+ }
307
+
308
+ const gateMatch = /^\/gates\/([^/]+)$/.exec(path);
309
+ if (gateMatch && method === "GET") {
310
+ const stored = gateStore.get(gateMatch[1]!);
311
+ if (!stored) {
312
+ return json(
313
+ { error: { code: "not_found", message: "No such gate in this development session." } },
314
+ 404
315
+ );
316
+ }
317
+ settleGate(stored);
318
+ return json(stored.data.gate);
319
+ }
320
+
321
+ const reviewMatch = /^\/reviews\/([^/]+)(\/cancel)?$/.exec(path);
322
+ if (reviewMatch) {
323
+ const stored = reviewStore.get(reviewMatch[1]!);
324
+ if (!stored) {
325
+ return json(
326
+ { error: { code: "not_found", message: "No such review in this development session." } },
327
+ 404
328
+ );
329
+ }
330
+ if (reviewMatch[2] === "/cancel") {
331
+ stored.data.status = "cancelled";
332
+ return json(stored.data);
333
+ }
334
+ settleReview(stored);
335
+ return json(stored.data);
336
+ }
337
+
338
+ /*
339
+ * Listing approvals, which `findByExternalId` needs.
340
+ *
341
+ * Missing until an example used `externalId` for retry safety and got a
342
+ * 501 instead. Reviews, collections and flows all had their list route
343
+ * from the start; approvals — the primitive the feature is most documented
344
+ * on — did not, so the one thing that stops a restarted agent asking twice
345
+ * was the one thing you could not try without an account.
346
+ */
347
+ if (method === "GET" && path === "/approvals") {
348
+ const externalId = url.searchParams.get("externalId");
349
+ const status = url.searchParams.get("status");
350
+ // Settle first: a caller listing before polling should see the same
351
+ // state a poll would have shown it, not a stale `pending`.
352
+ for (const stored of store.values()) settle(stored);
353
+ let all = [...store.values()].map((a) => a.data);
354
+ if (externalId) all = all.filter((a) => a.externalId === externalId);
355
+ if (status) all = all.filter((a) => a.status === status);
356
+ return json({ approvals: all });
357
+ }
358
+
359
+ if (method === "GET" && path === "/reviews") {
360
+ const externalId = url.searchParams.get("externalId");
361
+ const all = [...reviewStore.values()].map((r) => r.data);
362
+ return json({
363
+ reviews: externalId ? all.filter((r) => r.externalId === externalId) : all,
364
+ });
365
+ }
366
+
367
+ if (method === "POST" && path === "/collections") {
368
+ const id = `col_dev_${++counter}`;
369
+ const outcome = resolveOutcome(options.outcome, body);
370
+ const asked = ((body.respondents as string[] | undefined) ?? []).map(String);
371
+ const questions = ((body.questions as Record<string, unknown>[] | undefined) ?? []).map(
372
+ (q, i) => ({
373
+ id: `q_dev_${i + 1}`,
374
+ prompt: String(q.prompt ?? "Question"),
375
+ help: (q.help as string | undefined) ?? null,
376
+ kind: (q.kind as CollectionData["questions"][number]["kind"]) ?? "text",
377
+ required: q.required !== false,
378
+ options: (q.options as string[] | undefined) ?? [],
379
+ })
380
+ );
381
+ const data: CollectionData = {
382
+ id,
383
+ status: "pending",
384
+ url: `https://deliverd.dev/collect/${id}`,
385
+ title: String(body.title ?? "Untitled"),
386
+ instructions: (body.instructions as string | undefined) ?? null,
387
+ reportId: (body.reportId as string | undefined) ?? null,
388
+ externalId: (body.externalId as string | undefined) ?? null,
389
+ metadata: (body.metadata as Record<string, unknown>) ?? {},
390
+ requestedBy: "You (development mode)",
391
+ requiredResponses: (body.requiredResponses as number | undefined) ?? (asked.length || 1),
392
+ questions,
393
+ responses: asked.map((who) => ({
394
+ respondent: who,
395
+ status: "pending" as const,
396
+ submittedAt: null,
397
+ answers: [],
398
+ })),
399
+ submittedCount: 0,
400
+ askedCount: asked.length,
401
+ settledAt: null,
402
+ dueAt: (body.dueAt as string | undefined) ?? null,
403
+ expiresAt: (body.expiresAt as string | undefined) ?? null,
404
+ createdAt: new Date().toISOString(),
405
+ };
406
+ collectionStore.set(id, {
407
+ data,
408
+ settleAt: Date.now() + (options.delay ?? 0),
409
+ /*
410
+ * A simulated rejection becomes an expiry here: there is no way to
411
+ * say no to a question, only to leave it unanswered, and that is the
412
+ * ending a caller most needs to have thought about.
413
+ */
414
+ expire: outcome === "rejected",
415
+ timeout: outcome === "timeout",
416
+ });
417
+ if (options.log !== false) announceCollection(data, outcome);
418
+ return json(data, 201);
419
+ }
420
+
421
+ const collectionMatch = /^\/collections\/([^/]+)(\/cancel)?$/.exec(path);
422
+ if (collectionMatch) {
423
+ const stored = collectionStore.get(collectionMatch[1]!);
424
+ if (!stored) {
425
+ return json(
426
+ { error: { code: "not_found", message: "No such request in this development session." } },
427
+ 404
428
+ );
429
+ }
430
+ if (collectionMatch[2] === "/cancel") {
431
+ stored.data.status = "cancelled";
432
+ return json(stored.data);
433
+ }
434
+ settleCollection(stored);
435
+ return json(stored.data);
436
+ }
437
+
438
+ if (method === "GET" && path === "/collections") {
439
+ const externalId = url.searchParams.get("externalId");
440
+ const all = [...collectionStore.values()].map((c) => c.data);
441
+ return json({
442
+ collections: externalId ? all.filter((c) => c.externalId === externalId) : all,
443
+ });
444
+ }
445
+
446
+ /*
447
+ * Flows in development are real objects with no simulation attached:
448
+ * there is nobody to imagine, and the thing worth exercising offline is
449
+ * that `flow.approve()` reaches the same code as `deliverd.approve()`.
450
+ * Members are not tracked here — the server derives them from rows this
451
+ * store does not keep — so a development flow reports what it knows and
452
+ * does not invent a membership.
453
+ */
454
+ if (method === "POST" && path === "/flows") {
455
+ const id = `flw_dev_${++counter}`;
456
+ const data: FlowData = {
457
+ id,
458
+ status: "open",
459
+ url: `https://deliverd.dev/flows/${id}`,
460
+ title: String(body.title ?? "Untitled"),
461
+ description: (body.description as string | undefined) ?? null,
462
+ externalId: (body.externalId as string | undefined) ?? null,
463
+ metadata: (body.metadata as Record<string, unknown>) ?? {},
464
+ startedBy: "You (development mode)",
465
+ members: [],
466
+ memberCount: 0,
467
+ openCount: 0,
468
+ allSettled: false,
469
+ timeline: [],
470
+ settledAt: null,
471
+ createdAt: new Date().toISOString(),
472
+ };
473
+ flowStore.set(id, data);
474
+ if (options.log !== false) {
475
+ console.log(`\n \u25B8 Flow started: ${data.title}\n ${data.url}\n`);
476
+ }
477
+ return json(data, 201);
478
+ }
479
+
480
+ /*
481
+ * Evidence in development is the shape and not the substance: this store
482
+ * holds no audit rows, so the pack comes back with the subject and an
483
+ * empty record rather than an invented one. What it proves is that
484
+ * `flow.evidence()` reaches the right path and returns something a caller
485
+ * can destructure — an imaginary approval trail would be worse than none.
486
+ */
487
+ const evidenceMatch = /^\/(flows|reports)\/([^/]+)\/evidence$/.exec(path);
488
+ if (evidenceMatch && method === "GET") {
489
+ const kind = evidenceMatch[1] === "flows" ? "flow" : "report";
490
+ const id = evidenceMatch[2]!;
491
+ const title = kind === "flow" ? (flowStore.get(id)?.title ?? "A flow") : "A report";
492
+ const now = new Date().toISOString();
493
+ const pack: EvidencePack = {
494
+ packVersion: 2,
495
+ generatedAt: now,
496
+ generatedBy: "You (development mode)",
497
+ organisation: { id: "org_dev", name: "Development" },
498
+ subject: {
499
+ kind,
500
+ id,
501
+ title,
502
+ url: `https://deliverd.dev/${evidenceMatch[1]}/${id}`,
503
+ status: "open",
504
+ startedBy: "You (development mode)",
505
+ startedAt: now,
506
+ },
507
+ summary: { steps: 0, events: 0, firstEventAt: null, lastEventAt: null },
508
+ steps: [],
509
+ timeline: [],
510
+ integrity: {
511
+ algorithm: "sha256",
512
+ digest: "development",
513
+ covers: "Nothing: this pack was produced in development mode and holds no records.",
514
+ doesNotCover: "Everything. Do not hand this to anybody.",
515
+ recordsAreInsertOnly: true,
516
+ },
517
+ };
518
+ return json(pack);
519
+ }
520
+
521
+ const flowMatch = /^\/flows\/([^/]+)(\/complete|\/cancel)?$/.exec(path);
522
+ if (flowMatch) {
523
+ const flow = flowStore.get(flowMatch[1]!);
524
+ if (!flow) {
525
+ return json(
526
+ { error: { code: "not_found", message: "No such flow in this development session." } },
527
+ 404
528
+ );
529
+ }
530
+ if (flowMatch[2] === "/complete" || flowMatch[2] === "/cancel") {
531
+ if (flow.status !== "open") {
532
+ return json(
533
+ { error: { code: "not_open", message: `This flow is already ${flow.status}.` } },
534
+ 409
535
+ );
536
+ }
537
+ flow.status = flowMatch[2] === "/complete" ? "complete" : "cancelled";
538
+ flow.settledAt = new Date().toISOString();
539
+ }
540
+ return json(flow);
541
+ }
542
+
543
+ if (method === "GET" && path === "/flows") {
544
+ const externalId = url.searchParams.get("externalId");
545
+ const all = [...flowStore.values()];
546
+ return json({ flows: externalId ? all.filter((f) => f.externalId === externalId) : all });
547
+ }
548
+
549
+ return json(
550
+ {
551
+ error: {
552
+ code: "not_in_development_mode",
553
+ 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.`,
554
+ },
555
+ },
556
+ 501
557
+ );
558
+ }) as typeof globalThis.fetch;
559
+ }
560
+
561
+ function resolveOutcome(
562
+ outcome: DevelopmentOptions["outcome"],
563
+ body: Record<string, unknown>
564
+ ): DevelopmentOutcome {
565
+ const fromEnv = process.env.DELIVERD_DEV_OUTCOME as DevelopmentOutcome | undefined;
566
+ const chosen = outcome ?? fromEnv ?? "approved";
567
+ return typeof chosen === "function" ? chosen(body as unknown as ApprovalData) : chosen;
568
+ }
569
+
570
+ /** Move a pending request to its outcome once the imaginary approver has had time. */
571
+ function settle(stored: Stored): void {
572
+ if (stored.data.status !== "pending") return;
573
+ if (Date.now() < stored.decideAt) return;
574
+ if (stored.outcome === "timeout") return;
575
+ if (stored.outcome === "question" && stored.data.questions.some((q) => !q.answer)) return;
576
+
577
+ stored.data.status = stored.outcome === "rejected" ? "rejected" : "approved";
578
+ /*
579
+ * The same shape production sends: a person's name in `decidedBy` and the
580
+ * key in `decidedById`. It used to be an email-shaped string alone, so the
581
+ * offline loop taught a shape a real organisation never delivers.
582
+ */
583
+ stored.data.decidedBy = "Development approver";
584
+ stored.data.decidedById = "00000000-0000-0000-0000-00000000dev0";
585
+ stored.data.decidedAt = new Date().toISOString();
586
+ stored.data.note =
587
+ stored.options.note ??
588
+ (stored.data.status === "rejected" ? "Not yet — development mode says no." : null);
589
+ if (stored.data.status === "approved" && stored.data.input) {
590
+ const proposed = stored.data.input;
591
+ const edits = Object.entries(stored.options.edits ?? {}).filter(
592
+ ([field, value]) => stored.data.editableFields.includes(field) && !Object.is(proposed[field], value)
593
+ );
594
+ stored.data.approvedInput = { ...proposed, ...Object.fromEntries(edits) };
595
+ stored.data.changes = edits.map(([field, to]) => ({ field, from: proposed[field] ?? null, to }));
596
+ }
597
+ }
598
+
599
+ /**
600
+ * What the approver would have seen, in the terminal.
601
+ *
602
+ * The reason this is worth the lines: the title and the factors are copy
603
+ * somebody has to read on a phone at nine at night, and the only way to know
604
+ * whether it reads well is to see it written out.
605
+ */
606
+ function announce(data: ApprovalData, outcome: DevelopmentOutcome): void {
607
+ const lines = [
608
+ "",
609
+ " ┌─ Deliverd · development mode ─────────────────────────",
610
+ ` │ ${data.title}`,
611
+ ];
612
+ if (data.description) lines.push(` │ ${data.description}`);
613
+ lines.push(` │ Risk: ${data.risk}`);
614
+ for (const factor of data.factors) {
615
+ const mark = factor.status === "ok" ? "✓" : factor.status === "warning" ? "⚠" : "·";
616
+ lines.push(` │ ${mark} ${factor.label}`);
617
+ }
618
+ if (data.approvers.length > 0) lines.push(` │ To: ${data.approvers.join(", ")}`);
619
+ lines.push(
620
+ " │",
621
+ ` │ Simulating: ${outcome}${outcome === "question" ? " (needs an onQuestion handler)" : ""}`,
622
+ " └───────────────────────────────────────────────────────",
623
+ ""
624
+ );
625
+ console.log(lines.join("\n"));
626
+ }
627
+
628
+
629
+ interface StoredGate {
630
+ /** The decision, plus the caller's id kept beside it for the reuse lookup. */
631
+ data: { gate: GateData; externalId: string };
632
+ outcome: DevelopmentOutcome;
633
+ decideAt: number;
634
+ }
635
+
636
+ /**
637
+ * A gate that went to a person, once that person has answered.
638
+ *
639
+ * Only the two outcomes that involve one. `allowed` and `denied` were settled
640
+ * by a rule at creation and have nothing to wait for — which is the honest
641
+ * shape, because in production most gated calls never reach a human either.
642
+ */
643
+ function settleGate(stored: StoredGate): void {
644
+ const gate = stored.data.gate;
645
+ if (gate.status !== "pending") return;
646
+ if (Date.now() < stored.decideAt) return;
647
+ if (stored.outcome === "timeout" || stored.outcome === "question") return;
648
+ if (stored.outcome === "denied") return;
649
+
650
+ const approved = stored.outcome === "approved";
651
+ gate.status = approved ? "approved" : "rejected";
652
+ gate.allowed = approved;
653
+ gate.outcome = approved ? "approved" : "rejected";
654
+ gate.settledAt = new Date().toISOString();
655
+ gate.basis = "human";
656
+ gate.reason = approved
657
+ ? "A development approver agreed to it."
658
+ : "A development approver refused it.";
659
+ }
660
+
661
+ interface StoredReview {
662
+ data: ReviewData;
663
+ settleAt: number;
664
+ verdict: "approved" | "changes_requested";
665
+ timeout: boolean;
666
+ }
667
+
668
+ /** Settle it once its moment has passed, unless it is meant to hang. */
669
+ function settleReview(stored: StoredReview): void {
670
+ if (stored.timeout || stored.data.status !== "pending") return;
671
+ if (Date.now() < stored.settleAt) return;
672
+ stored.data.verdicts = [
673
+ {
674
+ verdict: stored.verdict,
675
+ by: stored.data.reviewers[0]?.label ?? "A reviewer (development mode)",
676
+ note:
677
+ stored.verdict === "changes_requested"
678
+ ? "Simulated: the figures on page two do not tie back."
679
+ : null,
680
+ at: new Date().toISOString(),
681
+ },
682
+ ];
683
+ stored.data.status = stored.verdict;
684
+ stored.data.settledAt = new Date().toISOString();
685
+ }
686
+
687
+ function announceReview(
688
+ data: ReviewData,
689
+ verdict: "approved" | "changes_requested",
690
+ willHang: boolean
691
+ ): void {
692
+ const lines = [
693
+ ` ┌─ Deliverd · development mode ─────────────────────────`,
694
+ ` │ ${data.title}`,
695
+ ...(data.instructions ? [` │ Check: ${data.instructions}`] : []),
696
+ ` │ Reviewers: ${data.reviewers.map((r) => r.label).join(", ") || "nobody named"}`,
697
+ ` │`,
698
+ ` │ Simulating: ${willHang ? "nobody reviews it" : verdict.replace("_", " ")}`,
699
+ ` └───────────────────────────────────────────────────────`,
700
+ "",
701
+ ];
702
+ console.log(lines.join("\n"));
703
+ }
704
+
705
+
706
+ interface StoredCollection {
707
+ data: CollectionData;
708
+ settleAt: number;
709
+ expire: boolean;
710
+ timeout: boolean;
711
+ }
712
+
713
+ /**
714
+ * Everyone answers, at the same moment, with a plausible value for the kind
715
+ * of question asked. Plausible rather than empty, because a caller writing
716
+ * `answers["Headcount at 30 September"] + 1` should find out here that it is
717
+ * a number, not in production.
718
+ */
719
+ function settleCollection(stored: StoredCollection): void {
720
+ if (stored.timeout || stored.data.status !== "pending") return;
721
+ if (Date.now() < stored.settleAt) return;
722
+ if (stored.expire) {
723
+ stored.data.status = "expired";
724
+ stored.data.settledAt = new Date().toISOString();
725
+ return;
726
+ }
727
+ const at = new Date().toISOString();
728
+ stored.data.responses = stored.data.responses.map((r) => ({
729
+ ...r,
730
+ status: "submitted" as const,
731
+ submittedAt: at,
732
+ answers: stored.data.questions.map((q) => ({
733
+ question: q.prompt,
734
+ kind: q.kind,
735
+ value: sampleAnswer(q),
736
+ })),
737
+ }));
738
+ stored.data.submittedCount = stored.data.responses.length;
739
+ stored.data.status = "complete";
740
+ stored.data.settledAt = at;
741
+ }
742
+
743
+ function sampleAnswer(q: CollectionData["questions"][number]): string | number | boolean | string[] {
744
+ switch (q.kind) {
745
+ case "number":
746
+ return 42;
747
+ case "boolean":
748
+ return true;
749
+ case "date":
750
+ return new Date().toISOString().slice(0, 10);
751
+ case "choice":
752
+ return q.options[0] ?? "";
753
+ case "multi_choice":
754
+ return q.options.slice(0, 1);
755
+ case "long_text":
756
+ return "Simulated: a longer answer than a line.";
757
+ default:
758
+ return "Simulated answer";
759
+ }
760
+ }
761
+
762
+ function announceCollection(data: CollectionData, outcome: string): void {
763
+ const lines = [
764
+ ` ┌─ Deliverd · development mode ─────────────────────────`,
765
+ ` │ ${data.title}`,
766
+ ` │ Asking: ${data.questions.map((q) => q.prompt).join(" · ") || "nothing"}`,
767
+ ` │ Of: ${data.responses.map((r) => r.respondent).join(", ") || "nobody named"}`,
768
+ ` │`,
769
+ ` │ Simulating: ${
770
+ outcome === "timeout"
771
+ ? "nobody answers"
772
+ : outcome === "rejected"
773
+ ? "it expires unanswered"
774
+ : "everyone answers"
775
+ }`,
776
+ ` └───────────────────────────────────────────────────────`,
777
+ "",
778
+ ];
779
+ console.log(lines.join("\n"));
780
+ }