@deliverd/sdk 0.35.0 → 0.37.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/README.md +32 -0
- package/dist/adapters/index.d.ts +2 -2
- package/dist/adapters/index.d.ts.map +1 -1
- package/dist/adapters/index.js +1 -1
- package/dist/adapters/ui-sdk.d.ts +43 -5
- package/dist/adapters/ui-sdk.d.ts.map +1 -1
- package/dist/adapters/ui-sdk.js +54 -8
- package/dist/elements.d.ts +96 -0
- package/dist/elements.d.ts.map +1 -0
- package/dist/elements.js +94 -0
- package/dist/react.d.ts +40 -0
- package/dist/react.d.ts.map +1 -0
- package/dist/react.js +73 -0
- package/dist/released.d.ts +1 -1
- package/dist/released.d.ts.map +1 -1
- package/dist/released.js +3014 -0
- package/package.json +19 -1
- package/src/adapters/index.ts +2 -2
- package/src/adapters/ui-sdk.ts +77 -13
- package/src/elements.ts +160 -0
- package/src/react.ts +104 -0
- package/src/released.ts +3016 -0
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@deliverd/sdk",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.37.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
|
},
|
package/src/adapters/index.ts
CHANGED
|
@@ -43,7 +43,7 @@ export type {
|
|
|
43
43
|
MuseToolMessage,
|
|
44
44
|
MuseToolRunner,
|
|
45
45
|
} from "./muse-spark.js";
|
|
46
|
-
export { deliverdAllow, describeStep, uiSdkApprovalRoute, UI_SDK_DEFAULT_TIMEOUT } from "./ui-sdk.js";
|
|
47
|
-
export type { DeliverdAllowOptions, UiSdkApprovalAnswer, UiSdkApprovalRouteOptions, UiSdkStep } from "./ui-sdk.js";
|
|
46
|
+
export { deliverdAllow, deliverdWebMcpAllow, describeStep, uiSdkApprovalRoute, UI_SDK_DEFAULT_TIMEOUT } from "./ui-sdk.js";
|
|
47
|
+
export type { DeliverdAllowOptions, UiSdkApprovalAnswer, UiSdkApprovalRouteOptions, UiSdkAskContext, UiSdkStep } from "./ui-sdk.js";
|
|
48
48
|
export { defaultDescription, DEFAULT_TOOL_EXPIRY } from "./shared.js";
|
|
49
49
|
export type { Approver, CallDescription, CallOutcome, ToolApprovalOptions } from "./shared.js";
|
package/src/adapters/ui-sdk.ts
CHANGED
|
@@ -39,8 +39,13 @@ import { askAboutCall, type CallDescription, type ToolApprovalOptions } from "./
|
|
|
39
39
|
* out is a no, and the request expires with it, so nobody approves a step the
|
|
40
40
|
* agent has stopped waiting for.
|
|
41
41
|
*
|
|
42
|
-
*
|
|
43
|
-
*
|
|
42
|
+
* When the browser's own agent can use the page too (WebMCP, through UI SDK's
|
|
43
|
+
* `registerTools`), pass `deliverdWebMcpAllow` as that `allow`. UI SDK runs it
|
|
44
|
+
* after the bridge's for each step the browser's agent asks for, inside the
|
|
45
|
+
* same `timeout`.
|
|
46
|
+
*
|
|
47
|
+
* Shapes follow `AgentAction`, `createAgent`'s `allow` option and
|
|
48
|
+
* `registerTools` in `@ui-sdk/core`'s agent docs (0.1.0-beta.1 and beta.2).
|
|
44
49
|
*/
|
|
45
50
|
|
|
46
51
|
/** The step UI SDK hands to `allow`: its `AgentAction`. */
|
|
@@ -69,9 +74,23 @@ export interface DeliverdAllowOptions {
|
|
|
69
74
|
headers?: Record<string, string> | (() => Record<string, string>);
|
|
70
75
|
/** Told each answer, so the page can show a person's reason. */
|
|
71
76
|
onAnswer?: (answer: UiSdkApprovalAnswer, step: UiSdkStep) => void;
|
|
77
|
+
/**
|
|
78
|
+
* Which agent asked, sent to your route so the approver can tell. `"webmcp"`
|
|
79
|
+
* means the browser's own agent, through `registerTools`. Letters, digits
|
|
80
|
+
* and dashes, up to 40.
|
|
81
|
+
*/
|
|
82
|
+
via?: string;
|
|
72
83
|
fetch?: typeof globalThis.fetch;
|
|
73
84
|
}
|
|
74
85
|
|
|
86
|
+
/**
|
|
87
|
+
* Steps a person has already approved through Deliverd, by identity. UI SDK
|
|
88
|
+
* hands the same step object to the bridge's `allow` and then to the one
|
|
89
|
+
* `registerTools` was given, so the second can tell that the person was
|
|
90
|
+
* already asked about this very step and not ask them twice.
|
|
91
|
+
*/
|
|
92
|
+
const approvedSteps = new WeakSet<object>();
|
|
93
|
+
|
|
75
94
|
/**
|
|
76
95
|
* UI SDK's `allow` hook, answered by a person through Deliverd.
|
|
77
96
|
*
|
|
@@ -83,6 +102,7 @@ export function deliverdAllow(
|
|
|
83
102
|
options: DeliverdAllowOptions
|
|
84
103
|
): (step: UiSdkStep, context?: { signal?: AbortSignal }) => Promise<boolean> {
|
|
85
104
|
const needsPerson = options.when ?? ((step: UiSdkStep) => Boolean(step.confirm));
|
|
105
|
+
const via = options.via !== undefined && VIA.test(options.via) ? options.via : undefined;
|
|
86
106
|
return async (step, context) => {
|
|
87
107
|
if (!needsPerson(step)) return true;
|
|
88
108
|
const doFetch = options.fetch ?? globalThis.fetch;
|
|
@@ -92,7 +112,7 @@ export function deliverdAllow(
|
|
|
92
112
|
const response = await doFetch(options.endpoint, {
|
|
93
113
|
method: "POST",
|
|
94
114
|
headers: { "content-type": "application/json", ...headers },
|
|
95
|
-
body: JSON.stringify({ step: pickStep(step), nonce: nonce() }),
|
|
115
|
+
body: JSON.stringify({ step: pickStep(step), nonce: nonce(), ...(via ? { via } : {}) }),
|
|
96
116
|
signal: context?.signal,
|
|
97
117
|
});
|
|
98
118
|
const body = (await response.json().catch(() => null)) as Partial<UiSdkApprovalAnswer> | null;
|
|
@@ -111,10 +131,42 @@ export function deliverdAllow(
|
|
|
111
131
|
answer = { allowed: false, reason: "The approval route could not be reached, so the step was not run." };
|
|
112
132
|
}
|
|
113
133
|
options.onAnswer?.(answer, step);
|
|
134
|
+
if (answer.allowed && typeof step === "object" && step !== null) approvedSteps.add(step);
|
|
114
135
|
return answer.allowed;
|
|
115
136
|
};
|
|
116
137
|
}
|
|
117
138
|
|
|
139
|
+
/**
|
|
140
|
+
* The `allow` that UI SDK's `registerTools` asks for, answered by a person
|
|
141
|
+
* through Deliverd. Use it when the browser's own agent (ChatGPT's site tools,
|
|
142
|
+
* or any browser with WebMCP) can use your page:
|
|
143
|
+
*
|
|
144
|
+
* ```ts
|
|
145
|
+
* registerTools(agent, {
|
|
146
|
+
* allow: deliverdWebMcpAllow({ endpoint: "/api/deliverd/ui-approval" }),
|
|
147
|
+
* });
|
|
148
|
+
* ```
|
|
149
|
+
*
|
|
150
|
+
* It asks about marked steps by default, as `deliverdAllow` does, and tells
|
|
151
|
+
* your route the browser's agent asked (`via: "webmcp"`). A step the bridge's
|
|
152
|
+
* own `deliverdAllow` already put to a person is not asked about again.
|
|
153
|
+
*
|
|
154
|
+
* Do not pass `allow: () => true` to `registerTools` unless the bridge has an
|
|
155
|
+
* `allow` that asks a person: with no bridge `allow`, UI SDK lets the browser's
|
|
156
|
+
* agent through a `data-agent-confirm` mark on that `true` alone.
|
|
157
|
+
*/
|
|
158
|
+
export function deliverdWebMcpAllow(
|
|
159
|
+
options: DeliverdAllowOptions
|
|
160
|
+
): (step: UiSdkStep, context?: { signal?: AbortSignal }) => Promise<boolean> {
|
|
161
|
+
const ask = deliverdAllow({ ...options, via: options.via ?? "webmcp" });
|
|
162
|
+
return async (step, context) => {
|
|
163
|
+
// The bridge's own deliverdAllow said yes to this very step a moment ago.
|
|
164
|
+
// Used once: the same object never counts for a later step.
|
|
165
|
+
if (typeof step === "object" && step !== null && approvedSteps.delete(step)) return true;
|
|
166
|
+
return ask(step, context);
|
|
167
|
+
};
|
|
168
|
+
}
|
|
169
|
+
|
|
118
170
|
export interface UiSdkApprovalRouteOptions extends Omit<ToolApprovalOptions, "when" | "describe"> {
|
|
119
171
|
/**
|
|
120
172
|
* Which steps go to a person, decided on the server. Default: those on a
|
|
@@ -122,9 +174,9 @@ export interface UiSdkApprovalRouteOptions extends Omit<ToolApprovalOptions, "wh
|
|
|
122
174
|
* the browser only sends steps it wants a person for, so anything else
|
|
123
175
|
* arriving here was not sent by `deliverdAllow`.
|
|
124
176
|
*/
|
|
125
|
-
when?: (step: UiSdkStep, request: Request) => boolean | Promise<boolean>;
|
|
177
|
+
when?: (step: UiSdkStep, request: Request, context: UiSdkAskContext) => boolean | Promise<boolean>;
|
|
126
178
|
/** What the approver reads. Built from the mark's sentence, the control and its values when omitted. */
|
|
127
|
-
describe?: (step: UiSdkStep) => CallDescription;
|
|
179
|
+
describe?: (step: UiSdkStep, context: UiSdkAskContext) => CallDescription;
|
|
128
180
|
/**
|
|
129
181
|
* How long to wait for the person. Default four minutes, inside UI SDK's
|
|
130
182
|
* own five-minute wait and a typical function limit. Raise all three together.
|
|
@@ -134,6 +186,12 @@ export interface UiSdkApprovalRouteOptions extends Omit<ToolApprovalOptions, "wh
|
|
|
134
186
|
expiresIn?: Duration;
|
|
135
187
|
}
|
|
136
188
|
|
|
189
|
+
/** What the page said about who asked. The page says it; nothing checks it. */
|
|
190
|
+
export interface UiSdkAskContext {
|
|
191
|
+
/** `"webmcp"` when the browser's own agent asked, through `deliverdWebMcpAllow`. */
|
|
192
|
+
via?: string;
|
|
193
|
+
}
|
|
194
|
+
|
|
137
195
|
export const UI_SDK_DEFAULT_TIMEOUT: Duration = "4m";
|
|
138
196
|
|
|
139
197
|
/**
|
|
@@ -160,8 +218,9 @@ export function uiSdkApprovalRoute(options: UiSdkApprovalRouteOptions): (request
|
|
|
160
218
|
}
|
|
161
219
|
const parsed = readBody(raw);
|
|
162
220
|
if (!parsed) return json({ allowed: false, reason: "The step could not be read." }, 400);
|
|
163
|
-
const { step, nonce: id } = parsed;
|
|
164
|
-
|
|
221
|
+
const { step, nonce: id, via } = parsed;
|
|
222
|
+
const context: UiSdkAskContext = via ? { via } : {};
|
|
223
|
+
if (!(await needsPerson(step, request, context))) {
|
|
165
224
|
return json({ allowed: false, reason: "This step is not one this route asks a person about." }, 403);
|
|
166
225
|
}
|
|
167
226
|
const name = stepName(step);
|
|
@@ -172,10 +231,10 @@ export function uiSdkApprovalRoute(options: UiSdkApprovalRouteOptions): (request
|
|
|
172
231
|
{
|
|
173
232
|
...options,
|
|
174
233
|
when: undefined,
|
|
175
|
-
describe: () => describe(step),
|
|
234
|
+
describe: () => describe(step, context),
|
|
176
235
|
timeout,
|
|
177
236
|
expiresIn: options.expiresIn ?? timeout,
|
|
178
|
-
metadata: { ...options.metadata, source: "ui-sdk" },
|
|
237
|
+
metadata: { ...options.metadata, source: "ui-sdk", ...(via ? { via } : {}) },
|
|
179
238
|
},
|
|
180
239
|
request.signal
|
|
181
240
|
);
|
|
@@ -187,13 +246,16 @@ export function uiSdkApprovalRoute(options: UiSdkApprovalRouteOptions): (request
|
|
|
187
246
|
}
|
|
188
247
|
|
|
189
248
|
/** What an approver reads about a step, when the app did not write it. */
|
|
190
|
-
export function describeStep(step: UiSdkStep): CallDescription {
|
|
249
|
+
export function describeStep(step: UiSdkStep, context: UiSdkAskContext = {}): CallDescription {
|
|
191
250
|
const target = step.label ? `"${step.label}"` : `the ${step.component}`;
|
|
192
251
|
const verb = step.action === "press" ? "press" : step.action === "setValue" ? "set" : step.action;
|
|
193
252
|
const values = (step.args ?? []).map((arg) => (typeof arg === "string" ? arg : JSON.stringify(arg))).join(", ");
|
|
194
253
|
const lines = [
|
|
195
254
|
step.confirm ? `The app says this: ${step.confirm}` : undefined,
|
|
196
255
|
`An agent wants to ${verb} ${target}${values ? ` (${truncate(values, 500)})` : ""} in the app.`,
|
|
256
|
+
context.via === "webmcp"
|
|
257
|
+
? "It is the browser's own agent, using the page through WebMCP, not an agent the app runs."
|
|
258
|
+
: undefined,
|
|
197
259
|
].filter(Boolean);
|
|
198
260
|
return {
|
|
199
261
|
title: truncate(step.confirm ?? `Let the agent ${verb} ${target}`, 200),
|
|
@@ -203,6 +265,7 @@ export function describeStep(step: UiSdkStep): CallDescription {
|
|
|
203
265
|
}
|
|
204
266
|
|
|
205
267
|
const BODY_MAX = 16_000;
|
|
268
|
+
const VIA = /^[a-z0-9-]{1,40}$/;
|
|
206
269
|
|
|
207
270
|
function stepName(step: UiSdkStep): string {
|
|
208
271
|
return step.label ? `${step.action} "${step.label}"` : `${step.action} ${step.component}`;
|
|
@@ -220,9 +283,10 @@ function pickStep(step: UiSdkStep): UiSdkStep {
|
|
|
220
283
|
};
|
|
221
284
|
}
|
|
222
285
|
|
|
223
|
-
function readBody(raw: unknown): { step: UiSdkStep; nonce: string } | null {
|
|
286
|
+
function readBody(raw: unknown): { step: UiSdkStep; nonce: string; via?: string } | null {
|
|
224
287
|
if (typeof raw !== "object" || raw === null) return null;
|
|
225
|
-
const { step, nonce: id } = raw as { step?: unknown; nonce?: unknown };
|
|
288
|
+
const { step, nonce: id, via } = raw as { step?: unknown; nonce?: unknown; via?: unknown };
|
|
289
|
+
if (via !== undefined && (typeof via !== "string" || !VIA.test(via))) return null;
|
|
226
290
|
if (typeof id !== "string" || id.length === 0 || id.length > 100) return null;
|
|
227
291
|
if (typeof step !== "object" || step === null) return null;
|
|
228
292
|
const s = step as Record<string, unknown>;
|
|
@@ -231,7 +295,7 @@ function readBody(raw: unknown): { step: UiSdkStep; nonce: string } | null {
|
|
|
231
295
|
if (s.label !== undefined && !str(s.label)) return null;
|
|
232
296
|
if (s.confirm !== undefined && !str(s.confirm)) return null;
|
|
233
297
|
if (s.args !== undefined && !Array.isArray(s.args)) return null;
|
|
234
|
-
return { step: pickStep(s as unknown as UiSdkStep), nonce: id };
|
|
298
|
+
return { step: pickStep(s as unknown as UiSdkStep), nonce: id, ...(typeof via === "string" ? { via } : {}) };
|
|
235
299
|
}
|
|
236
300
|
|
|
237
301
|
function json(body: UiSdkApprovalAnswer | { allowed: false; reason: string }, status: number): Response {
|
package/src/elements.ts
ADDED
|
@@ -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
|
+
}
|