@deliverd/sdk 0.34.0 → 0.36.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@deliverd/sdk",
3
- "version": "0.34.0",
3
+ "version": "0.36.0",
4
4
  "description": "Add human approval to any AI agent. Ask a person, wait for the answer, act on it. Start free at deliverd.dev.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -17,6 +17,14 @@
17
17
  "./verify": {
18
18
  "types": "./dist/verify.d.ts",
19
19
  "default": "./dist/verify.js"
20
+ },
21
+ "./elements": {
22
+ "types": "./dist/elements.d.ts",
23
+ "default": "./dist/elements.js"
24
+ },
25
+ "./react": {
26
+ "types": "./dist/react.d.ts",
27
+ "default": "./dist/react.js"
20
28
  }
21
29
  },
22
30
  "files": [
@@ -34,8 +42,18 @@
34
42
  "typecheck": "tsc --noEmit",
35
43
  "prepublishOnly": "npm run build"
36
44
  },
45
+ "peerDependencies": {
46
+ "react": ">=18"
47
+ },
48
+ "peerDependenciesMeta": {
49
+ "react": {
50
+ "optional": true
51
+ }
52
+ },
37
53
  "devDependencies": {
38
54
  "@types/node": "^20",
55
+ "@types/react": "^19",
56
+ "react": "^19",
39
57
  "typescript": "^5",
40
58
  "vitest": "^4.1.11"
41
59
  },
@@ -0,0 +1,293 @@
1
+ import { DeliverdTimeoutError } from "../errors.js";
2
+ import { durationMs, type Duration } from "../duration.js";
3
+ import type { FieldChange } from "../types.js";
4
+ import { DEFAULT_TOOL_EXPIRY, defaultDescription, refusalReason, structuredInput, type ToolApprovalOptions } from "./shared.js";
5
+
6
+ /**
7
+ * Claude Managed Agents, hosted by Anthropic or self-hosted: a person answers
8
+ * the tool calls a permission policy holds for confirmation.
9
+ *
10
+ * Give the agent a toolset with `permission_policy: { type: "always_ask" }`
11
+ * (MCP toolsets ask by default) and the session pauses on each such call with
12
+ * `session.status_idle`, `stop_reason.type: "requires_action"`. These answer
13
+ * the pause with a person's decision, as `user.tool_confirmation` events:
14
+ *
15
+ * ```ts
16
+ * import Anthropic from "@anthropic-ai/sdk";
17
+ * import { Deliverd } from "@deliverd/sdk";
18
+ * import { watchManagedAgentSessions } from "@deliverd/sdk/adapters";
19
+ *
20
+ * // Self-hosted: ANTHROPIC_BASE_URL is your server, ANTHROPIC_API_KEY its key.
21
+ * const client = new Anthropic();
22
+ * await watchManagedAgentSessions(client, {
23
+ * deliverd: new Deliverd(),
24
+ * approvers: ["platform-team"],
25
+ * });
26
+ * ```
27
+ *
28
+ * A self-hosted server sends no webhooks, so something has to look. The
29
+ * watcher polls for idle sessions and answers the ones waiting on a
30
+ * confirmation; `followManagedAgentSession` follows one session's stream; and
31
+ * `answerManagedAgentConfirmations` does one pass over one session, for a loop
32
+ * you own. Each call is one request in Deliverd keyed by its event id
33
+ * (`managed-agents:<id>`), so a second pass finds the request it already made
34
+ * rather than asking twice.
35
+ *
36
+ * - **Approved**, the call runs.
37
+ * - **Declined**, it does not, and the person's reason reaches the model as
38
+ * the `deny_message`.
39
+ * - **Approved only with changes**, it is declined: a confirmation is a yes or
40
+ * a no and cannot carry corrected input. The model is told the approved
41
+ * values, so it can call again with them.
42
+ * - **Undecided** before `timeout`, nothing is sent. The session waits
43
+ * indefinitely, so a later pass picks the same request up.
44
+ *
45
+ * Only calls the server marked `evaluated_permission: "ask"` are answered.
46
+ * A call `auto` already ran or denied, a worker-run tool on a self-hosted
47
+ * environment and a custom tool (your own code, where `deliverd.approve()`
48
+ * belongs) are left alone.
49
+ *
50
+ * Shapes follow `client.beta.sessions` in `@anthropic-ai/sdk` 1.8 (beta
51
+ * header `managed-agents-2026-04-01`), which self-hosted servers serve too.
52
+ * Nothing is imported from it.
53
+ */
54
+
55
+ /** The events this reads. Every other event passes through untouched. */
56
+ export interface ManagedAgentsEvent {
57
+ id: string;
58
+ type: string;
59
+ /** `agent.tool_use` and `agent.mcp_tool_use`: the tool. */
60
+ name?: string;
61
+ input?: Record<string, unknown>;
62
+ /** `agent.mcp_tool_use`: the server that offers the tool. */
63
+ mcp_server_name?: string;
64
+ /** `"ask"` on a call that is waiting for a confirmation. */
65
+ evaluated_permission?: string;
66
+ /** `session.status_idle`: why it stopped. */
67
+ stop_reason?: { type: string; event_ids?: string[] } | null;
68
+ }
69
+
70
+ /** What a stream carries: the events above, and `event_start` / `event_delta` frames with no id. */
71
+ export type ManagedAgentsStreamEvent = Omit<ManagedAgentsEvent, "id"> & { id?: string };
72
+
73
+ export interface ManagedAgentsToolConfirmation {
74
+ type: "user.tool_confirmation";
75
+ tool_use_id: string;
76
+ result: "allow" | "deny";
77
+ deny_message?: string;
78
+ }
79
+
80
+ /** The part of `new Anthropic()` these use. */
81
+ export interface ManagedAgentsClient {
82
+ beta: {
83
+ sessions: {
84
+ list(params?: { statuses?: Array<"rescheduling" | "running" | "idle" | "terminated">; agent_id?: string }): AsyncIterable<{
85
+ id: string;
86
+ }>;
87
+ events: {
88
+ list(sessionId: string, params?: { order?: "asc" | "desc"; types?: Array<"session.status_idle" | "agent.tool_use" | "agent.mcp_tool_use"> }): AsyncIterable<ManagedAgentsEvent>;
89
+ send(sessionId: string, params: { events: ManagedAgentsToolConfirmation[] }): PromiseLike<unknown>;
90
+ stream(sessionId: string): PromiseLike<AsyncIterable<ManagedAgentsStreamEvent>>;
91
+ };
92
+ };
93
+ };
94
+ }
95
+
96
+ export interface ManagedAgentsApprovalOptions extends ToolApprovalOptions {
97
+ /**
98
+ * Stop waiting on a person after this and leave the call for a later pass.
99
+ * The session waits indefinitely, so nothing is refused for being slow.
100
+ */
101
+ timeout?: Duration;
102
+ /** Cancels the wait. */
103
+ signal?: AbortSignal;
104
+ }
105
+
106
+ /** What one pass over a session came to. */
107
+ export interface ManagedAgentsResolution {
108
+ /** The confirmations sent, in the order the calls were asked about. */
109
+ sent: ManagedAgentsToolConfirmation[];
110
+ /** Event ids nobody decided before `timeout`. Still open in Deliverd and in the session. */
111
+ pending: string[];
112
+ /** Why each declined call was declined, by event id. */
113
+ reasons: Record<string, string>;
114
+ }
115
+
116
+ const PREFIX = "managed-agents:";
117
+ const TOOL_USE: Array<"agent.tool_use" | "agent.mcp_tool_use"> = ["agent.tool_use", "agent.mcp_tool_use"];
118
+
119
+ /** The event ids the session is blocked on, from its latest idle event; none when it is not. */
120
+ async function blockingIds(client: ManagedAgentsClient, sessionId: string): Promise<string[]> {
121
+ for await (const event of client.beta.sessions.events.list(sessionId, { order: "desc", types: ["session.status_idle"] })) {
122
+ return event.stop_reason?.type === "requires_action" ? [...(event.stop_reason.event_ids ?? [])] : [];
123
+ }
124
+ return [];
125
+ }
126
+
127
+ /** The tool-use events behind those ids, newest first, stopping once all are found. */
128
+ async function toolUses(client: ManagedAgentsClient, sessionId: string, ids: string[]): Promise<ManagedAgentsEvent[]> {
129
+ const wanted = new Set(ids);
130
+ const found = new Map<string, ManagedAgentsEvent>();
131
+ for await (const event of client.beta.sessions.events.list(sessionId, { order: "desc", types: TOOL_USE })) {
132
+ if (wanted.has(event.id)) found.set(event.id, event);
133
+ if (found.size === wanted.size) break;
134
+ }
135
+ return ids.flatMap((id) => (found.has(id) ? [found.get(id)!] : []));
136
+ }
137
+
138
+ function changedReason(tool: string, changes: FieldChange[]): string {
139
+ const parts = changes.map((c) => `${c.field} from ${JSON.stringify(c.from)} to ${JSON.stringify(c.to)}`);
140
+ return `A person approved ${tool} only with changes: ${parts.join("; ")}. It was not run as proposed. If it is still needed, call it again with those values.`;
141
+ }
142
+
143
+ function toolLabel(event: ManagedAgentsEvent): string {
144
+ const name = event.name ?? "a tool";
145
+ return event.mcp_server_name ? `${name} on ${event.mcp_server_name}` : name;
146
+ }
147
+
148
+ type Answer = { kind: "allow" } | { kind: "deny"; reason: string } | { kind: "pending" };
149
+
150
+ async function decideCall(event: ManagedAgentsEvent, sessionId: string, options: ManagedAgentsApprovalOptions): Promise<Answer> {
151
+ const tool = event.name ?? "a tool";
152
+ const input = event.input ?? {};
153
+ if (options.when && !(await options.when(tool, input))) return { kind: "allow" };
154
+ const described = (options.describe ?? defaultDescription)(toolLabel(event), input);
155
+ const structured = structuredInput(input);
156
+ try {
157
+ const decision = await options.deliverd.approve({
158
+ ...described,
159
+ approvers: options.approvers,
160
+ externalId: PREFIX + event.id,
161
+ flowId: options.flowId,
162
+ metadata: {
163
+ ...options.metadata,
164
+ tool,
165
+ session: sessionId,
166
+ ...(event.mcp_server_name ? { mcp_server: event.mcp_server_name } : {}),
167
+ },
168
+ ...(structured ? { input: structured } : {}),
169
+ expiresIn: options.expiresIn ?? DEFAULT_TOOL_EXPIRY,
170
+ timeout: options.timeout,
171
+ signal: options.signal,
172
+ });
173
+ if (decision.approved) {
174
+ return decision.changes?.length ? { kind: "deny", reason: changedReason(tool, decision.changes) } : { kind: "allow" };
175
+ }
176
+ return { kind: "deny", reason: refusalReason(tool, decision) };
177
+ } catch (err) {
178
+ if (err instanceof DeliverdTimeoutError) return { kind: "pending" };
179
+ throw err;
180
+ }
181
+ }
182
+
183
+ /**
184
+ * One pass over one session: if it is waiting on confirmations, ask a person
185
+ * about each and send the answers that came back.
186
+ */
187
+ export async function answerManagedAgentConfirmations(
188
+ client: ManagedAgentsClient,
189
+ sessionId: string,
190
+ options: ManagedAgentsApprovalOptions,
191
+ /** The ids from a `requires_action` you already hold, to skip looking them up. */
192
+ eventIds?: string[]
193
+ ): Promise<ManagedAgentsResolution> {
194
+ const resolution: ManagedAgentsResolution = { sent: [], pending: [], reasons: {} };
195
+ const ids = eventIds ?? (await blockingIds(client, sessionId));
196
+ if (ids.length === 0) return resolution;
197
+ const calls = (await toolUses(client, sessionId, ids)).filter((e) => e.evaluated_permission === "ask");
198
+ const answers = await Promise.all(calls.map((event) => decideCall(event, sessionId, options)));
199
+ calls.forEach((event, i) => {
200
+ const answer = answers[i]!;
201
+ if (answer.kind === "pending") {
202
+ resolution.pending.push(event.id);
203
+ } else if (answer.kind === "allow") {
204
+ resolution.sent.push({ type: "user.tool_confirmation", tool_use_id: event.id, result: "allow" });
205
+ } else {
206
+ resolution.reasons[event.id] = answer.reason;
207
+ resolution.sent.push({ type: "user.tool_confirmation", tool_use_id: event.id, result: "deny", deny_message: answer.reason });
208
+ }
209
+ });
210
+ if (resolution.sent.length > 0) await client.beta.sessions.events.send(sessionId, { events: resolution.sent });
211
+ return resolution;
212
+ }
213
+
214
+ /**
215
+ * Follow one session's stream, answering each confirmation it pauses on,
216
+ * until its turn ends, it stops for another reason, or it terminates.
217
+ * Open it before you send the message that starts the turn: a stream carries
218
+ * only what happens after it opens.
219
+ */
220
+ export async function followManagedAgentSession(
221
+ client: ManagedAgentsClient,
222
+ sessionId: string,
223
+ options: ManagedAgentsApprovalOptions & {
224
+ /** Every event, for printing the agent's messages as they arrive. */
225
+ onEvent?: (event: ManagedAgentsStreamEvent) => void;
226
+ }
227
+ ): Promise<void> {
228
+ const stream = await client.beta.sessions.events.stream(sessionId);
229
+ for await (const event of stream) {
230
+ options.onEvent?.(event);
231
+ if (event.type === "session.status_terminated") return;
232
+ if (event.type !== "session.status_idle") continue;
233
+ if (event.stop_reason?.type !== "requires_action") return;
234
+ await answerManagedAgentConfirmations(client, sessionId, options, event.stop_reason.event_ids ?? []);
235
+ }
236
+ }
237
+
238
+ /**
239
+ * Keep answering, for every idle session the key can see (or one agent's,
240
+ * with `agentId`), until `signal` aborts. For a self-hosted server, which
241
+ * sends no webhooks; it works the same against Anthropic's API.
242
+ *
243
+ * Each pass waits on a person for at most `timeout` per call (default ten
244
+ * seconds), so one slow decision does not hold up another session. An
245
+ * undecided call is picked up again next pass, from the same request.
246
+ */
247
+ export async function watchManagedAgentSessions(
248
+ client: ManagedAgentsClient,
249
+ options: ManagedAgentsApprovalOptions & {
250
+ agentId?: string;
251
+ /** Time between passes. Default five seconds. */
252
+ interval?: Duration;
253
+ /** A session that could not be answered this pass; the watcher carries on. */
254
+ onError?: (error: unknown, sessionId: string) => void;
255
+ }
256
+ ): Promise<void> {
257
+ const interval = options.interval === undefined ? 5_000 : durationMs(options.interval);
258
+ const perPass: ManagedAgentsApprovalOptions = { ...options, timeout: options.timeout ?? "10s" };
259
+ while (!options.signal?.aborted) {
260
+ const idle: string[] = [];
261
+ for await (const session of client.beta.sessions.list({
262
+ statuses: ["idle"],
263
+ ...(options.agentId ? { agent_id: options.agentId } : {}),
264
+ })) {
265
+ idle.push(session.id);
266
+ }
267
+ await Promise.all(
268
+ idle.map(async (id) => {
269
+ try {
270
+ await answerManagedAgentConfirmations(client, id, perPass);
271
+ } catch (err) {
272
+ if (options.signal?.aborted) return;
273
+ if (options.onError) options.onError(err, id);
274
+ else throw err;
275
+ }
276
+ })
277
+ );
278
+ await sleep(interval, options.signal);
279
+ }
280
+ }
281
+
282
+ function sleep(ms: number, signal?: AbortSignal): Promise<void> {
283
+ return new Promise((resolve) => {
284
+ if (signal?.aborted) return resolve();
285
+ const timer = setTimeout(done, ms);
286
+ function done() {
287
+ clearTimeout(timer);
288
+ signal?.removeEventListener("abort", done);
289
+ resolve();
290
+ }
291
+ signal?.addEventListener("abort", done, { once: true });
292
+ });
293
+ }
@@ -13,6 +13,19 @@ export type {
13
13
  ClaudePermissionResult,
14
14
  ClaudeToolApprovalOptions,
15
15
  } from "./claude-agent-sdk.js";
16
+ export {
17
+ answerManagedAgentConfirmations,
18
+ followManagedAgentSession,
19
+ watchManagedAgentSessions,
20
+ } from "./claude-managed-agents.js";
21
+ export type {
22
+ ManagedAgentsApprovalOptions,
23
+ ManagedAgentsClient,
24
+ ManagedAgentsEvent,
25
+ ManagedAgentsResolution,
26
+ ManagedAgentsStreamEvent,
27
+ ManagedAgentsToolConfirmation,
28
+ } from "./claude-managed-agents.js";
16
29
  export { deliverdToolApproval } from "./ai-sdk.js";
17
30
  export type { AiSdkApprovalCall, AiSdkApprovalStatus } from "./ai-sdk.js";
18
31
  export { resolveInterruptions, runWithDeliverdApprovals } from "./openai-agents.js";
@@ -0,0 +1,160 @@
1
+ /**
2
+ * Deliverd Elements from a bundler: load the script, mount a decision.
3
+ *
4
+ * `https://deliverd.dev/elements/v1.js` is the element. This module does not
5
+ * reimplement it; it loads it, once, and hands back the same `mountDecision`
6
+ * a `<script>` tag would. Keeping one copy is the point: the frame, the
7
+ * origin checks on its messages and the sizing all live in that script, so a
8
+ * fix there reaches every page without anybody upgrading a package.
9
+ *
10
+ * Browser only. On a server there is no page to put a frame in, so
11
+ * `loadElements()` rejects there rather than pretending.
12
+ *
13
+ * ```ts
14
+ * import { loadElements } from "@deliverd/sdk/elements";
15
+ *
16
+ * const elements = await loadElements();
17
+ * const decision = elements.mountDecision("#decision", {
18
+ * clientSecret, // from your server: approvals.createSession(id, { mode: "embedded", origin })
19
+ * onDecided(event) {
20
+ * // Tell your server, which reads decisionSessions.get(event.sessionId) before acting.
21
+ * },
22
+ * });
23
+ * // later: decision.unmount();
24
+ * ```
25
+ */
26
+
27
+ /** Where Elements is served from, unless you say otherwise. */
28
+ export const ELEMENTS_ORIGIN = "https://deliverd.dev";
29
+
30
+ /** The path of the script on that origin. Versioned: v1 keeps working. */
31
+ export const ELEMENTS_PATH = "/elements/v1.js";
32
+
33
+ /** What every event hands your handler. */
34
+ export interface DecisionEvent {
35
+ type: "ready" | "verified" | "decided" | "expired";
36
+ sessionId: string;
37
+ approvalId: string;
38
+ /** Set on `decided`: what the approver chose. */
39
+ decision: "approved" | "rejected" | "changes_requested" | null;
40
+ /** Set on `decided`: the request's own status, which other approvers may still be part of. */
41
+ approvalStatus: string | null;
42
+ }
43
+
44
+ export interface MountDecisionOptions {
45
+ /**
46
+ * The session's `clientSecret`, from `approvals.createSession(id, { mode: "embedded", origin })`
47
+ * on your server. Required unless `demo` is set.
48
+ */
49
+ clientSecret?: string;
50
+ /**
51
+ * Show the demo request instead of a real one: sample data, a code shown on
52
+ * screen, and nothing recorded. Needs no account and frames on any site, so
53
+ * you can see the element and its events before writing server code.
54
+ */
55
+ demo?: boolean;
56
+ /** The frame's accessible title. "Decision" when omitted. */
57
+ title?: string;
58
+ /** The frame's height before it reports its own, in pixels. 320 when omitted. */
59
+ minHeight?: number;
60
+ /** Set `false` to size the frame yourself instead of letting it fit its content. */
61
+ autoResize?: boolean;
62
+ onReady?: (event: DecisionEvent) => void;
63
+ onVerified?: (event: DecisionEvent) => void;
64
+ /** The browser's word only: confirm with `decisionSessions.get(id)` from your server before acting. */
65
+ onDecided?: (event: DecisionEvent) => void;
66
+ onExpired?: (event: DecisionEvent) => void;
67
+ }
68
+
69
+ export interface MountedDecision {
70
+ frame: HTMLIFrameElement;
71
+ unmount(): void;
72
+ }
73
+
74
+ /** What the script puts on `window.Deliverd`. */
75
+ export interface DeliverdElements {
76
+ mountDecision(target: string | Element, options: MountDecisionOptions): MountedDecision;
77
+ elementsVersion: number;
78
+ }
79
+
80
+ export interface LoadElementsOptions {
81
+ /**
82
+ * Another Deliverd origin, such as your own self-hosted deployment. Must be
83
+ * the origin the session was made on: the frame only talks to the script
84
+ * that came from its own origin.
85
+ */
86
+ origin?: string;
87
+ }
88
+
89
+ type Loaded = Window & { Deliverd?: Partial<DeliverdElements> };
90
+
91
+ const loading = new Map<string, Promise<DeliverdElements>>();
92
+
93
+ function ready(w: Loaded): DeliverdElements | null {
94
+ const api = w.Deliverd;
95
+ return api && typeof api.mountDecision === "function" ? (api as DeliverdElements) : null;
96
+ }
97
+
98
+ /**
99
+ * Loads Elements into the page once, and resolves to its API.
100
+ *
101
+ * Safe to call as often as you like: a second call, from anywhere, waits on
102
+ * the same script rather than adding another. If the page already loaded the
103
+ * script with a `<script>` tag, that one is used.
104
+ */
105
+ export function loadElements(options: LoadElementsOptions = {}): Promise<DeliverdElements> {
106
+ if (typeof window === "undefined" || typeof document === "undefined") {
107
+ return Promise.reject(new Error("Deliverd Elements runs in a browser. Call loadElements() from client code."));
108
+ }
109
+ const origin = new URL(options.origin ?? ELEMENTS_ORIGIN).origin;
110
+ const w = window as Loaded;
111
+ const existing = ready(w);
112
+ if (existing) return Promise.resolve(existing);
113
+
114
+ const cached = loading.get(origin);
115
+ if (cached) return cached;
116
+
117
+ const src = origin + ELEMENTS_PATH;
118
+ const promise = new Promise<DeliverdElements>((resolve, reject) => {
119
+ const fail = (message: string) => {
120
+ loading.delete(origin);
121
+ reject(new Error(message));
122
+ };
123
+ const done = () => {
124
+ const api = ready(w);
125
+ if (api) resolve(api);
126
+ else fail(`Deliverd Elements loaded from ${src} but did not start.`);
127
+ };
128
+ let script = document.querySelector<HTMLScriptElement>(`script[src="${src}"]`);
129
+ if (!script) {
130
+ script = document.createElement("script");
131
+ script.src = src;
132
+ script.async = true;
133
+ document.head.appendChild(script);
134
+ }
135
+ script.addEventListener("load", done, { once: true });
136
+ script.addEventListener("error", () => fail(`Could not load Deliverd Elements from ${src}.`), { once: true });
137
+ });
138
+ loading.set(origin, promise);
139
+ return promise;
140
+ }
141
+
142
+ /**
143
+ * Loads Elements and mounts a decision into `host`, unless `cancelled()` says
144
+ * the caller went away first. Resolves to the mounted decision, or `null`
145
+ * when it was cancelled. What the React component does in an effect, kept
146
+ * here so it can be used, and tested, without React.
147
+ */
148
+ export async function mountWhenLoaded(
149
+ host: Element,
150
+ options: MountDecisionOptions,
151
+ load: () => Promise<DeliverdElements>,
152
+ cancelled: () => boolean
153
+ ): Promise<MountedDecision | null> {
154
+ if (!options.demo && !options.clientSecret) {
155
+ throw new Error("Deliverd: pass clientSecret (from an embedded session), or demo: true.");
156
+ }
157
+ const elements = await load();
158
+ if (cancelled()) return null;
159
+ return elements.mountDecision(host, options);
160
+ }
package/src/react.ts ADDED
@@ -0,0 +1,104 @@
1
+ "use client";
2
+
3
+ /**
4
+ * `<DeliverdDecision>`: a decision session in a React page.
5
+ *
6
+ * A thin wrapper over Deliverd Elements (`@deliverd/sdk/elements`): it loads
7
+ * the script once, mounts the frame into a `<div>` it renders, passes your
8
+ * handlers through, and unmounts the frame when the component goes away or
9
+ * the secret changes. The frame is still served from Deliverd's origin, so
10
+ * your page cannot read it or press its buttons, and the approver still
11
+ * proves who they are before deciding.
12
+ *
13
+ * ```tsx
14
+ * import { DeliverdDecision } from "@deliverd/sdk/react";
15
+ *
16
+ * <DeliverdDecision
17
+ * clientSecret={clientSecret} // from your server
18
+ * onDecided={(event) => confirmOnServer(event.sessionId)}
19
+ * />
20
+ *
21
+ * // No account yet? See it with sample data, nothing recorded:
22
+ * <DeliverdDecision demo onDecided={(event) => console.log(event)} />
23
+ * ```
24
+ *
25
+ * React 18 or later. Written without JSX so the package needs no build step
26
+ * of its own for it; `react` is an optional peer dependency, needed only if
27
+ * you import this entry.
28
+ */
29
+
30
+ import { createElement, useEffect, useRef, type CSSProperties, type ReactElement } from "react";
31
+ import {
32
+ loadElements,
33
+ mountWhenLoaded,
34
+ type DecisionEvent,
35
+ type MountDecisionOptions,
36
+ type MountedDecision,
37
+ } from "./elements.js";
38
+
39
+ export type { DecisionEvent } from "./elements.js";
40
+
41
+ export interface DeliverdDecisionProps
42
+ extends Pick<
43
+ MountDecisionOptions,
44
+ "clientSecret" | "demo" | "title" | "minHeight" | "autoResize" | "onReady" | "onVerified" | "onDecided" | "onExpired"
45
+ > {
46
+ /** Another Deliverd origin, such as a self-hosted deployment. https://deliverd.dev when omitted. */
47
+ origin?: string;
48
+ /** Called when the script cannot load or the options are refused. Thrown to the console otherwise. */
49
+ onError?: (error: Error) => void;
50
+ className?: string;
51
+ style?: CSSProperties;
52
+ id?: string;
53
+ }
54
+
55
+ export function DeliverdDecision(props: DeliverdDecisionProps): ReactElement {
56
+ const host = useRef<HTMLDivElement>(null);
57
+ // Handlers read through a ref, so a new arrow function on every render does not remount the frame.
58
+ const latest = useRef(props);
59
+ latest.current = props;
60
+
61
+ const { clientSecret, demo, title, minHeight, autoResize, origin } = props;
62
+
63
+ useEffect(() => {
64
+ const el = host.current;
65
+ if (!el) return;
66
+ let cancelled = false;
67
+ let mounted: MountedDecision | null = null;
68
+ const relay = (name: "onReady" | "onVerified" | "onDecided" | "onExpired") => (event: DecisionEvent) =>
69
+ latest.current[name]?.(event);
70
+
71
+ mountWhenLoaded(
72
+ el,
73
+ {
74
+ clientSecret,
75
+ demo,
76
+ title,
77
+ minHeight,
78
+ autoResize,
79
+ onReady: relay("onReady"),
80
+ onVerified: relay("onVerified"),
81
+ onDecided: relay("onDecided"),
82
+ onExpired: relay("onExpired"),
83
+ },
84
+ () => loadElements({ origin }),
85
+ () => cancelled
86
+ )
87
+ .then((result) => {
88
+ if (cancelled) result?.unmount();
89
+ else mounted = result;
90
+ })
91
+ .catch((err: unknown) => {
92
+ const error = err instanceof Error ? err : new Error(String(err));
93
+ if (latest.current.onError) latest.current.onError(error);
94
+ else console.error(error);
95
+ });
96
+
97
+ return () => {
98
+ cancelled = true;
99
+ mounted?.unmount();
100
+ };
101
+ }, [clientSecret, demo, title, minHeight, autoResize, origin]);
102
+
103
+ return createElement("div", { ref: host, className: props.className, style: props.style, id: props.id });
104
+ }