@ui-calling/react 0.0.0-stage → 0.1.0-preview.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 San Pau
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,18 @@
1
- # Temporary Holding Version
1
+ # @ui-calling/react
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ React bindings for ui-calling screens: typed data and events from the contract, and lifecycle tracking (opened, left, completed) for free.
4
+
5
+ ```tsx
6
+ import { SurfaceProvider, useSurface } from "@ui-calling/react";
7
+
8
+ <SurfaceProvider token={token} returnUrl="https://wa.me/<your number>">
9
+ <ShiftPicker />
10
+ </SurfaceProvider>
11
+
12
+ function ShiftPicker() {
13
+ const { status, data, emit, complete } = useSurface(shiftPicker);
14
+ // ...
15
+ }
16
+ ```
17
+
18
+ Also `useSurfaceSteps` (steps in the browser's history) and `useSurfaceSession` (route between screens). `npx ui-calling new <name>` writes a screen that handles every state; the guide: `npx ui-calling guide designing`.
@@ -0,0 +1,109 @@
1
+ import * as react from 'react';
2
+ import { ReactNode } from 'react';
3
+ import { AnySurface, SurfaceData, SurfaceEventName, SurfaceEventPayload, SurfaceFileSlot, UiFileRef } from '@ui-calling/core';
4
+
5
+ /**
6
+ * `completed`: the user already finished on this screen, so its link no longer works.
7
+ * `verify`: the surface sets `verify: true` and the user hasn't typed their PIN or code yet; `SurfaceProvider`
8
+ * shows its own step for it (or your `verifyScreen`) instead of the screen.
9
+ */
10
+ type Status = "loading" | "verify" | "ready" | "expired" | "completed" | "error";
11
+ /** What a `verify` surface asks before showing anything: a PIN the user knows, or a code sent to them. */
12
+ type VerifyPrompt = {
13
+ kind: "pin" | "code";
14
+ attemptsLeft: number;
15
+ };
16
+ /** What `verifyScreen` gets to draw your own verify step. */
17
+ type VerifyStepProps = {
18
+ prompt: VerifyPrompt;
19
+ locale: string;
20
+ /** Check what the user typed. Resolves when it's right (the screen then loads); rejects with a `SurfaceActionError`: `reason: "wrong_code"`, or `code: "verification_locked"`. */
21
+ submit: (typed: string) => Promise<void>;
22
+ /** For `kind: "code"`: send a code (again). Resolves with the verifier's hint, e.g. "SMS to •••• 42". */
23
+ sendCode: () => Promise<{
24
+ hint?: string;
25
+ }>;
26
+ };
27
+ /**
28
+ * Error thrown by `emit` and `reload`. For `code === "upstream_error"`, `reason` is the server's
29
+ * `SurfaceError` code (e.g. "shift_full"): map it to a message in the user's language.
30
+ * `retryable` says whether trying the same thing again can work; `code === "network"` always is.
31
+ */
32
+ declare class SurfaceActionError extends Error {
33
+ code?: string | undefined;
34
+ retryable: boolean;
35
+ reason?: string | undefined;
36
+ constructor(message: string, code?: string | undefined, retryable?: boolean, reason?: string | undefined);
37
+ }
38
+ declare function SurfaceProvider(props: {
39
+ token: string;
40
+ endpoint?: string;
41
+ returnUrl?: string;
42
+ /** Your own verify step for `verify` surfaces. Without it, a plain one in the user's language (en/es) styled with your tokens. */
43
+ verifyScreen?: (props: VerifyStepProps) => ReactNode;
44
+ children: ReactNode;
45
+ }): react.JSX.Element;
46
+ /** The built-in verify step: one field, big enough to tap, in the user's language. Wrap it in your `verifyScreen` to add to it. */
47
+ declare function VerifyStep({ prompt, locale, submit, sendCode, note }: VerifyStepProps & {
48
+ note?: ReactNode;
49
+ }): react.JSX.Element;
50
+ /** Typed access to a surface's data and events. */
51
+ declare function useSurface<S extends AnySurface>(surface: S): {
52
+ status: Status;
53
+ error: string | undefined;
54
+ errorCode: string | undefined;
55
+ errorReason: string | undefined;
56
+ reload: () => Promise<void>;
57
+ reportError: (err: unknown, context?: string) => void;
58
+ locale: string;
59
+ data: SurfaceData<S> | undefined;
60
+ returnUrl: string | undefined;
61
+ /** Report an event. Resolves with the screen's fresh data when the handler returned some (else undefined). */
62
+ emit: <K extends SurfaceEventName<S>>(type: K, payload: SurfaceEventPayload<S, K>) => Promise<SurfaceData<S> | undefined>;
63
+ complete: () => Promise<undefined>;
64
+ upload: (slot: SurfaceFileSlot<S>, file: File) => Promise<UiFileRef>;
65
+ removeFile: (id: string) => Promise<void>;
66
+ fileUrl: (id: string) => string;
67
+ };
68
+ /** The link's state (status, surface, locale, errorCode, errorReason, returnUrl), before you know which screen it is: for routing between surfaces on one page. */
69
+ declare function useSurfaceSession(): {
70
+ status: Status;
71
+ surface: string | undefined;
72
+ locale: string | undefined;
73
+ error: string | undefined;
74
+ errorCode: string | undefined;
75
+ errorReason: string | undefined;
76
+ returnUrl: string | undefined;
77
+ };
78
+ /** @deprecated Renamed to `useSurfaceSession`: it returns the link's whole state, not just a name. */
79
+ declare const useSurfaceName: typeof useSurfaceSession;
80
+ /**
81
+ * The steps of a screen with several steps, kept in the browser's history so the phone's back button
82
+ * goes to the previous step instead of closing the screen.
83
+ *
84
+ * - `steps` is the path the user will see now (leave out steps that don't apply). If the current step
85
+ * drops out of it, the step that took its place is shown.
86
+ * - `initial` is where to start, usually the furthest step saved in your draft (`data.draft.step`).
87
+ * - After a reload the step comes back from history. Opened fresh on a later step, the earlier steps are
88
+ * added behind it, so Back goes to them.
89
+ *
90
+ * const { step, index, count, go, next, back } = useSurfaceSteps(path, { initial: data.draft.step });
91
+ */
92
+ declare function useSurfaceSteps<S extends string>(steps: readonly S[], options: {
93
+ initial: S;
94
+ key?: string;
95
+ }): {
96
+ step: S;
97
+ index: number;
98
+ count: number;
99
+ isFirst: boolean;
100
+ isLast: boolean;
101
+ /** Show a step and add it to history. */
102
+ go: (to: S) => void;
103
+ next: () => void;
104
+ /** Like the phone's back button: the previous step in history. */
105
+ back: () => void;
106
+ };
107
+
108
+ export { SurfaceActionError, SurfaceProvider, VerifyStep, useSurface, useSurfaceName, useSurfaceSession, useSurfaceSteps };
109
+ export type { VerifyPrompt, VerifyStepProps };
package/dist/index.js ADDED
@@ -0,0 +1,461 @@
1
+ "use client";
2
+
3
+ // src/index.tsx
4
+ import {
5
+ Component,
6
+ createContext,
7
+ useCallback,
8
+ useContext,
9
+ useEffect,
10
+ useMemo,
11
+ useRef,
12
+ useState
13
+ } from "react";
14
+ import { Fragment, jsx, jsxs } from "react/jsx-runtime";
15
+ var SurfaceActionError = class extends Error {
16
+ constructor(message, code, retryable = false, reason) {
17
+ super(message);
18
+ this.code = code;
19
+ this.retryable = retryable;
20
+ this.reason = reason;
21
+ }
22
+ code;
23
+ retryable;
24
+ reason;
25
+ };
26
+ function eventKey() {
27
+ if (typeof crypto.randomUUID === "function") return crypto.randomUUID();
28
+ return Array.from(crypto.getRandomValues(new Uint8Array(16)), (b) => b.toString(16).padStart(2, "0")).join("");
29
+ }
30
+ var SurfaceContext = createContext(null);
31
+ function onComputer() {
32
+ return typeof matchMedia === "function" && matchMedia("(hover: hover) and (pointer: fine)").matches;
33
+ }
34
+ function CloseTabHint({ locale }) {
35
+ const text = locale.toLowerCase().startsWith("es") ? "Ya est\xE1. Cierra esta pesta\xF1a para volver al chat." : "All done. Close this tab to go back to the chat.";
36
+ return /* @__PURE__ */ jsx(
37
+ "p",
38
+ {
39
+ role: "status",
40
+ style: {
41
+ position: "fixed",
42
+ insetInline: 16,
43
+ bottom: "calc(16px + env(safe-area-inset-bottom, 0px))",
44
+ margin: "0 auto",
45
+ maxWidth: 420,
46
+ padding: "12px 16px",
47
+ borderRadius: 8,
48
+ background: "var(--foreground, #111)",
49
+ color: "var(--background, #fff)",
50
+ fontSize: 14,
51
+ textAlign: "center",
52
+ zIndex: 50
53
+ },
54
+ children: text
55
+ }
56
+ );
57
+ }
58
+ function SurfaceProvider(props) {
59
+ const base = `${props.endpoint ?? "/api/ui"}/sessions/${encodeURIComponent(props.token)}`;
60
+ const [state, setState] = useState({ status: "loading" });
61
+ const opened = useRef(false);
62
+ const send = useCallback(async (url, init) => {
63
+ const res = await fetch(url, init).catch(() => {
64
+ throw new SurfaceActionError("Couldn't reach the server", "network", true);
65
+ });
66
+ const json = await res.json().catch(() => ({}));
67
+ if (!res.ok) {
68
+ if (json.error === "completed") setState((s) => ({ status: "completed", locale: s.locale }));
69
+ throw new SurfaceActionError(json.message ?? json.error ?? res.statusText, json.error, json.retryable, json.reason);
70
+ }
71
+ return json;
72
+ }, []);
73
+ const unsettled = useRef(void 0);
74
+ const emit = useCallback(
75
+ async (type, payload = {}) => {
76
+ const sig = JSON.stringify([type, payload]);
77
+ const key = unsettled.current?.sig === sig ? unsettled.current.key : eventKey();
78
+ let json;
79
+ for (let attempt = 0; ; attempt++) {
80
+ try {
81
+ json = await send(`${base}/events`, {
82
+ method: "POST",
83
+ headers: { "Content-Type": "application/json" },
84
+ body: JSON.stringify({ type, payload, key }),
85
+ // `complete()` usually runs as the user follows "Back to chat": let it finish after the page goes.
86
+ keepalive: true
87
+ });
88
+ unsettled.current = void 0;
89
+ break;
90
+ } catch (err) {
91
+ const code = err.code;
92
+ if (code !== "network" && code !== "in_progress" && code !== "internal") {
93
+ unsettled.current = void 0;
94
+ throw err;
95
+ }
96
+ unsettled.current = { sig, key };
97
+ if (code === "internal" || attempt === 2) throw err;
98
+ await new Promise((r) => setTimeout(r, attempt ? 1500 : 500));
99
+ }
100
+ }
101
+ if (type === "completed") {
102
+ setState((s) => ({ status: "completed", locale: s.locale }));
103
+ return void 0;
104
+ }
105
+ if (json.data !== void 0 && json.data !== null) setState((s) => ({ ...s, data: json.data }));
106
+ return json.data ?? void 0;
107
+ },
108
+ [base, send]
109
+ );
110
+ const upload = useCallback(
111
+ async (slot, file) => {
112
+ const body = new FormData();
113
+ body.append("file", file);
114
+ const json = await send(`${base}/files/${encodeURIComponent(slot)}`, { method: "POST", body });
115
+ return json.file;
116
+ },
117
+ [base, send]
118
+ );
119
+ const removeFile = useCallback(
120
+ async (id) => void await send(`${base}/files/${encodeURIComponent(id)}`, { method: "DELETE" }),
121
+ [base, send]
122
+ );
123
+ const fileUrl = useCallback((id) => `${base}/files/${encodeURIComponent(id)}`, [base]);
124
+ const reload = useCallback(async () => {
125
+ const json = await send(base, {});
126
+ setState((s) => ({ ...s, data: json.data }));
127
+ }, [base, send]);
128
+ const reportError = useCallback(
129
+ (err, context, source = "client") => {
130
+ const e = err;
131
+ const payload = {
132
+ source,
133
+ code: String(typeof e?.code === "string" ? e.code : e?.name ?? "client_error").slice(0, 60),
134
+ message: String(e?.message ?? err).slice(0, 500),
135
+ retryable: e?.retryable === true,
136
+ context: context?.slice(0, 200)
137
+ };
138
+ void emit("error", payload).catch(() => {
139
+ });
140
+ },
141
+ [emit]
142
+ );
143
+ const ready = useCallback(
144
+ (json) => {
145
+ setState({ status: "ready", surface: json.surface, locale: json.locale, data: json.data });
146
+ if (!opened.current) {
147
+ opened.current = true;
148
+ void emit("opened").catch(() => {
149
+ });
150
+ }
151
+ },
152
+ [emit]
153
+ );
154
+ const submitVerify = useCallback(
155
+ async (typed) => {
156
+ try {
157
+ ready(await send(`${base}/verify`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ code: typed }) }));
158
+ } catch (err) {
159
+ if (err instanceof SurfaceActionError && err.reason === "wrong_code") {
160
+ setState((s) => s.verify ? { ...s, verify: { ...s.verify, attemptsLeft: Math.max(0, s.verify.attemptsLeft - 1) } } : s);
161
+ }
162
+ throw err;
163
+ }
164
+ },
165
+ [base, send, ready]
166
+ );
167
+ const sendCode = useCallback(async () => await send(`${base}/verify/send`, { method: "POST" }), [base, send]);
168
+ useEffect(() => {
169
+ let cancelled = false;
170
+ fetch(base).then(async (res) => {
171
+ const json = await res.json().catch(() => ({ error: "network" }));
172
+ if (cancelled) return;
173
+ const { locale: locale2 } = json;
174
+ if (json.error === "completed") return setState({ status: "completed", locale: locale2 });
175
+ if (res.status === 410) return setState({ status: "expired", locale: locale2, error: json.message });
176
+ if (!res.ok) {
177
+ const errorCode = res.status >= 500 && !json.surface ? "network" : json.error ?? "network";
178
+ return setState({ status: "error", surface: json.surface, locale: locale2, error: json.message ?? json.error, errorCode, errorReason: json.reason });
179
+ }
180
+ if (json.verify) return setState({ status: "verify", surface: json.surface, locale: json.locale, verify: json.verify });
181
+ ready(json);
182
+ }).catch((e) => !cancelled && setState({ status: "error", error: String(e), errorCode: "network" }));
183
+ return () => {
184
+ cancelled = true;
185
+ };
186
+ }, [base, ready]);
187
+ useEffect(() => {
188
+ if (state.status !== "ready") return;
189
+ const onVisibility = () => {
190
+ if (document.visibilityState === "hidden") {
191
+ const blob = new Blob([JSON.stringify({ type: "left", payload: {} })], { type: "application/json" });
192
+ navigator.sendBeacon(`${base}/events`, blob);
193
+ } else {
194
+ void emit("opened").catch(() => {
195
+ });
196
+ }
197
+ };
198
+ document.addEventListener("visibilitychange", onVisibility);
199
+ return () => document.removeEventListener("visibilitychange", onVisibility);
200
+ }, [state.status, base, emit]);
201
+ const locale = state.locale ?? (typeof navigator === "undefined" ? "en" : navigator.language);
202
+ useEffect(() => {
203
+ document.documentElement.lang = locale;
204
+ }, [locale]);
205
+ const [ownTab] = useState(() => typeof window !== "undefined" && (window.history.length <= 1 || Boolean(window.opener)));
206
+ const [closeHint, setCloseHint] = useState(false);
207
+ useEffect(() => {
208
+ const target = props.returnUrl;
209
+ if (!target || !ownTab) return;
210
+ const onClick = (e) => {
211
+ const link = e.target?.closest?.("a");
212
+ if (!link || link.getAttribute("href") !== target || !onComputer()) return;
213
+ e.preventDefault();
214
+ window.close();
215
+ setTimeout(() => !window.closed && setCloseHint(true), 300);
216
+ };
217
+ document.addEventListener("click", onClick, true);
218
+ return () => document.removeEventListener("click", onClick, true);
219
+ }, [props.returnUrl, ownTab]);
220
+ const value = useMemo(
221
+ () => ({ ...state, locale, data: state.data, emit, reload, reportError, upload, removeFile, fileUrl, returnUrl: props.returnUrl }),
222
+ [state, locale, emit, reload, reportError, upload, removeFile, fileUrl, props.returnUrl]
223
+ );
224
+ return /* @__PURE__ */ jsx(SurfaceContext.Provider, { value, children: /* @__PURE__ */ jsxs(SurfaceErrorBoundary, { report: (err, info) => reportError(err, info, "render"), locale, returnUrl: props.returnUrl, children: [
225
+ state.status === "verify" && state.verify ? (props.verifyScreen ?? ((p) => /* @__PURE__ */ jsx(VerifyStep, { ...p })))({ prompt: state.verify, locale, submit: submitVerify, sendCode }) : props.children,
226
+ closeHint && /* @__PURE__ */ jsx(CloseTabHint, { locale })
227
+ ] }) });
228
+ }
229
+ var VERIFY_TEXT = {
230
+ en: {
231
+ pinTitle: "Enter your PIN",
232
+ pinHelp: "This screen has personal details. Enter your PIN to see them.",
233
+ codeTitle: "Enter the code we sent you",
234
+ codeHelp: "This screen has personal details. We've sent you a code to check it's you.",
235
+ label: "PIN or code",
236
+ submit: "Continue",
237
+ resend: "Send a new code",
238
+ wrong: (n) => n === 1 ? "That's not right. You have 1 try left." : `That's not right. You have ${n} tries left.`,
239
+ locked: "Too many wrong tries. Go back to the chat to ask for help.",
240
+ noCode: "We couldn't send a code. Go back to the chat to ask for help.",
241
+ failed: "Something went wrong. Check your connection and try again."
242
+ },
243
+ es: {
244
+ pinTitle: "Introduce tu PIN",
245
+ pinHelp: "Esta pantalla tiene datos personales. Introduce tu PIN para verlos.",
246
+ codeTitle: "Introduce el c\xF3digo que te hemos enviado",
247
+ codeHelp: "Esta pantalla tiene datos personales. Te hemos enviado un c\xF3digo para comprobar que eres t\xFA.",
248
+ label: "PIN o c\xF3digo",
249
+ submit: "Continuar",
250
+ resend: "Enviar otro c\xF3digo",
251
+ wrong: (n) => n === 1 ? "No es correcto. Te queda 1 intento." : `No es correcto. Te quedan ${n} intentos.`,
252
+ locked: "Demasiados intentos. Vuelve al chat para pedir ayuda.",
253
+ noCode: "No hemos podido enviarte un c\xF3digo. Vuelve al chat para pedir ayuda.",
254
+ failed: "Algo ha fallado. Comprueba tu conexi\xF3n e int\xE9ntalo de nuevo."
255
+ }
256
+ };
257
+ function VerifyStep({ prompt, locale, submit, sendCode, note }) {
258
+ const t = VERIFY_TEXT[locale.toLowerCase().startsWith("es") ? "es" : "en"];
259
+ const [typed, setTyped] = useState("");
260
+ const [busy, setBusy] = useState(false);
261
+ const [message, setMessage] = useState(prompt.attemptsLeft <= 0 ? t.locked : void 0);
262
+ const [hint, setHint] = useState();
263
+ const [locked, setLocked] = useState(prompt.attemptsLeft <= 0);
264
+ const sent = useRef(false);
265
+ const requestCode = useCallback(() => {
266
+ sendCode().then(
267
+ (r) => setHint(r.hint),
268
+ (err) => setMessage(err.code === "network" ? t.failed : t.noCode)
269
+ );
270
+ }, [sendCode, t]);
271
+ useEffect(() => {
272
+ if (prompt.kind === "code" && !sent.current && prompt.attemptsLeft > 0) {
273
+ sent.current = true;
274
+ requestCode();
275
+ }
276
+ }, [prompt.kind, requestCode]);
277
+ const onSubmit = async (e) => {
278
+ e.preventDefault();
279
+ if (!typed.trim() || busy) return;
280
+ setBusy(true);
281
+ setMessage(void 0);
282
+ try {
283
+ await submit(typed);
284
+ } catch (err) {
285
+ const a = err;
286
+ if (a.code === "verification_locked") {
287
+ setLocked(true);
288
+ setMessage(t.locked);
289
+ } else setMessage(a.reason === "wrong_code" ? t.wrong(Math.max(0, prompt.attemptsLeft - 1)) : t.failed);
290
+ setTyped("");
291
+ } finally {
292
+ setBusy(false);
293
+ }
294
+ };
295
+ const field = { width: "100%", boxSizing: "border-box", minHeight: 48, padding: "10px 12px", fontSize: 20, letterSpacing: 4, textAlign: "center", borderRadius: 8, border: "1px solid var(--border, #ccc)", background: "var(--background, #fff)", color: "var(--foreground, #111)" };
296
+ return /* @__PURE__ */ jsx("main", { style: { minHeight: "100dvh", maxWidth: 420, margin: "0 auto", padding: "32px 16px", fontFamily: "inherit", color: "var(--foreground, #111)" }, children: /* @__PURE__ */ jsxs("form", { onSubmit, style: { display: "grid", gap: 12 }, children: [
297
+ /* @__PURE__ */ jsx("h1", { style: { fontSize: 20, fontWeight: 600, margin: 0 }, children: prompt.kind === "pin" ? t.pinTitle : t.codeTitle }),
298
+ /* @__PURE__ */ jsxs("p", { style: { margin: 0, color: "var(--muted-foreground, #555)" }, children: [
299
+ prompt.kind === "pin" ? t.pinHelp : t.codeHelp,
300
+ hint && /* @__PURE__ */ jsxs(Fragment, { children: [
301
+ " (",
302
+ hint,
303
+ ")"
304
+ ] })
305
+ ] }),
306
+ /* @__PURE__ */ jsx(
307
+ "input",
308
+ {
309
+ "aria-label": t.label,
310
+ value: typed,
311
+ onChange: (e) => setTyped(e.target.value),
312
+ inputMode: "numeric",
313
+ autoComplete: prompt.kind === "code" ? "one-time-code" : "off",
314
+ type: prompt.kind === "pin" ? "password" : "text",
315
+ maxLength: 12,
316
+ autoFocus: true,
317
+ disabled: locked,
318
+ style: field
319
+ }
320
+ ),
321
+ message && /* @__PURE__ */ jsx("p", { role: "alert", style: { margin: 0, color: "var(--destructive, #b42318)" }, children: message }),
322
+ /* @__PURE__ */ jsx(
323
+ "button",
324
+ {
325
+ type: "submit",
326
+ disabled: busy || locked || !typed.trim(),
327
+ style: { minHeight: 48, borderRadius: 8, border: 0, fontSize: 16, fontWeight: 600, background: "var(--primary, #111)", color: "var(--primary-foreground, #fff)", opacity: busy || locked || !typed.trim() ? 0.6 : 1 },
328
+ children: t.submit
329
+ }
330
+ ),
331
+ prompt.kind === "code" && !locked && /* @__PURE__ */ jsx("button", { type: "button", onClick: requestCode, style: { minHeight: 44, border: 0, background: "none", color: "var(--primary, #111)", fontSize: 15, textDecoration: "underline" }, children: t.resend }),
332
+ note
333
+ ] }) });
334
+ }
335
+ var CRASH_TEXT = {
336
+ en: ["Something went wrong on this page", "Your assistant has been notified. You can go back to the chat."],
337
+ es: ["Algo ha fallado en esta p\xE1gina", "Tu asistente ya lo sabe. Puedes volver al chat."]
338
+ };
339
+ var SurfaceErrorBoundary = class extends Component {
340
+ state = { crashed: false };
341
+ static getDerivedStateFromError() {
342
+ return { crashed: true };
343
+ }
344
+ componentDidCatch(error, info) {
345
+ const where = info.componentStack?.trim().split("\n")[0]?.trim();
346
+ this.props.report(error, where ? `rendering ${where}` : "rendering the screen");
347
+ }
348
+ render() {
349
+ if (!this.state.crashed) return this.props.children;
350
+ const [title, body] = CRASH_TEXT[this.props.locale.split("-")[0]] ?? CRASH_TEXT.en;
351
+ return /* @__PURE__ */ jsxs("div", { role: "alert", style: { padding: 24, maxWidth: 420, margin: "0 auto", fontFamily: "system-ui, sans-serif" }, children: [
352
+ /* @__PURE__ */ jsx("p", { style: { fontWeight: 600, margin: 0 }, children: title }),
353
+ /* @__PURE__ */ jsx("p", { style: { margin: "6px 0 0", opacity: 0.7 }, children: body }),
354
+ this.props.returnUrl && /* @__PURE__ */ jsx("a", { href: this.props.returnUrl, style: { display: "inline-block", marginTop: 12 }, children: "\u2190" })
355
+ ] });
356
+ }
357
+ };
358
+ function useSurface(surface) {
359
+ const ctx = useContext(SurfaceContext);
360
+ if (!ctx) throw new Error("useSurface must be used inside <SurfaceProvider>");
361
+ if (ctx.surface && ctx.surface !== surface.name) {
362
+ throw new Error(`This link is for "${ctx.surface}", not "${surface.name}"`);
363
+ }
364
+ return {
365
+ status: ctx.status,
366
+ error: ctx.error,
367
+ errorCode: ctx.errorCode,
368
+ errorReason: ctx.errorReason,
369
+ reload: ctx.reload,
370
+ reportError: ctx.reportError,
371
+ locale: ctx.locale,
372
+ data: ctx.data,
373
+ returnUrl: ctx.returnUrl,
374
+ /** Report an event. Resolves with the screen's fresh data when the handler returned some (else undefined). */
375
+ emit: ctx.emit,
376
+ complete: () => ctx.emit("completed").then(() => void 0),
377
+ upload: ctx.upload,
378
+ removeFile: ctx.removeFile,
379
+ fileUrl: ctx.fileUrl
380
+ };
381
+ }
382
+ function useSurfaceSession() {
383
+ const ctx = useContext(SurfaceContext);
384
+ return {
385
+ status: ctx?.status ?? "loading",
386
+ surface: ctx?.surface,
387
+ locale: ctx?.locale,
388
+ error: ctx?.error,
389
+ errorCode: ctx?.errorCode,
390
+ errorReason: ctx?.errorReason,
391
+ returnUrl: ctx?.returnUrl
392
+ };
393
+ }
394
+ var useSurfaceName = useSurfaceSession;
395
+ function useSurfaceSteps(steps, options) {
396
+ const key = options.key ?? "uiCallingStep";
397
+ const [pos, setPos] = useState(() => {
398
+ const restored = typeof window === "undefined" ? void 0 : historyStep(key);
399
+ const step2 = restored ?? options.initial;
400
+ return { step: step2, index: Math.max(0, steps.indexOf(step2)) };
401
+ });
402
+ const found = steps.indexOf(pos.step);
403
+ const index = found === -1 ? Math.min(pos.index, steps.length - 1) : found;
404
+ const step = steps[index];
405
+ const path = useRef(steps);
406
+ useEffect(() => {
407
+ path.current = steps;
408
+ });
409
+ const opened = useRef(index);
410
+ useEffect(() => {
411
+ if (!historyStep(key)) {
412
+ const at = opened.current;
413
+ window.history.replaceState({ ...window.history.state, [key]: path.current[0] }, "");
414
+ for (const s of path.current.slice(1, at + 1)) window.history.pushState({ ...window.history.state, [key]: s }, "");
415
+ }
416
+ const onPop = () => {
417
+ const s = historyStep(key);
418
+ if (!s) return;
419
+ const found2 = path.current.indexOf(s);
420
+ setPos((prev) => ({ step: s, index: found2 === -1 ? Math.max(0, prev.index - 1) : found2 }));
421
+ };
422
+ window.addEventListener("popstate", onPop);
423
+ return () => window.removeEventListener("popstate", onPop);
424
+ }, [key]);
425
+ const go = useCallback(
426
+ (to) => {
427
+ setPos({ step: to, index: Math.max(0, path.current.indexOf(to)) });
428
+ window.history.pushState({ ...window.history.state, [key]: to }, "");
429
+ },
430
+ [key]
431
+ );
432
+ return {
433
+ step,
434
+ index,
435
+ count: steps.length,
436
+ isFirst: index === 0,
437
+ isLast: index === steps.length - 1,
438
+ /** Show a step and add it to history. */
439
+ go,
440
+ next: () => {
441
+ if (index < steps.length - 1) go(steps[index + 1]);
442
+ },
443
+ /** Like the phone's back button: the previous step in history. */
444
+ back: () => {
445
+ if (index > 0) window.history.back();
446
+ }
447
+ };
448
+ }
449
+ function historyStep(key) {
450
+ return window.history.state?.[key];
451
+ }
452
+ export {
453
+ SurfaceActionError,
454
+ SurfaceProvider,
455
+ VerifyStep,
456
+ useSurface,
457
+ useSurfaceName,
458
+ useSurfaceSession,
459
+ useSurfaceSteps
460
+ };
461
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.tsx"],"sourcesContent":["import {\n Component,\n createContext,\n useCallback,\n useContext,\n useEffect,\n useMemo,\n useRef,\n useState,\n type ErrorInfo,\n type ReactNode,\n} from \"react\";\nimport type { AnySurface, SurfaceData, SurfaceEventName, SurfaceEventPayload, SurfaceFileSlot, UiFileRef } from \"@ui-calling/core\";\n\n/**\n * `completed`: the user already finished on this screen, so its link no longer works.\n * `verify`: the surface sets `verify: true` and the user hasn't typed their PIN or code yet; `SurfaceProvider`\n * shows its own step for it (or your `verifyScreen`) instead of the screen.\n */\ntype Status = \"loading\" | \"verify\" | \"ready\" | \"expired\" | \"completed\" | \"error\";\n\n/** What a `verify` surface asks before showing anything: a PIN the user knows, or a code sent to them. */\nexport type VerifyPrompt = { kind: \"pin\" | \"code\"; attemptsLeft: number };\n\n/** What `verifyScreen` gets to draw your own verify step. */\nexport type VerifyStepProps = {\n prompt: VerifyPrompt;\n locale: string;\n /** Check what the user typed. Resolves when it's right (the screen then loads); rejects with a `SurfaceActionError`: `reason: \"wrong_code\"`, or `code: \"verification_locked\"`. */\n submit: (typed: string) => Promise<void>;\n /** For `kind: \"code\"`: send a code (again). Resolves with the verifier's hint, e.g. \"SMS to •••• 42\". */\n sendCode: () => Promise<{ hint?: string }>;\n};\n\ntype ContextValue = {\n status: Status;\n surface?: string;\n /** The session's language; the browser's until the session has loaded. */\n locale: string;\n data: unknown;\n error?: string;\n /** e.g. \"upstream_error\" when the data source failed (the agent already knows), \"not_found\" for a bad\n * link, or \"network\" when the server couldn't be reached. */\n errorCode?: string;\n /** For `errorCode === \"upstream_error\"` or `\"refused\"`: `resolve`'s `SurfaceError` code (e.g. \"account_not_linked\"). */\n errorReason?: string;\n emit: (type: string, payload?: unknown) => Promise<unknown>;\n reload: () => Promise<void>;\n reportError: (err: unknown, context?: string) => void;\n upload: (slot: string, file: File) => Promise<UiFileRef>;\n removeFile: (id: string) => Promise<void>;\n fileUrl: (id: string) => string;\n returnUrl?: string;\n};\n\n/**\n * Error thrown by `emit` and `reload`. For `code === \"upstream_error\"`, `reason` is the server's\n * `SurfaceError` code (e.g. \"shift_full\"): map it to a message in the user's language.\n * `retryable` says whether trying the same thing again can work; `code === \"network\"` always is.\n */\nexport class SurfaceActionError extends Error {\n constructor(\n message: string,\n public code?: string,\n public retryable = false,\n public reason?: string,\n ) {\n super(message);\n }\n}\n\n/** A fresh idempotency key for one action. `randomUUID` needs a secure context, which a phone on the LAN in dev isn't. */\nfunction eventKey() {\n if (typeof crypto.randomUUID === \"function\") return crypto.randomUUID();\n return Array.from(crypto.getRandomValues(new Uint8Array(16)), (b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\nconst SurfaceContext = createContext<ContextValue | null>(null);\n\n/**\n * Loads the session behind `token` and tracks lifecycle automatically:\n * `opened` on load, `left` when the tab is hidden or closed, `opened` again on return\n * (recorded server-side as `returned`). After `complete()` the link is closed: a tab left open\n * switches to `status: \"completed\"` as soon as it's used again.\n */\n/** A mouse, not a touch screen: the chat is in another tab of this browser, not an app to switch back to. */\nfunction onComputer() {\n return typeof matchMedia === \"function\" && matchMedia(\"(hover: hover) and (pointer: fine)\").matches;\n}\n\nfunction CloseTabHint({ locale }: { locale: string }) {\n const text = locale.toLowerCase().startsWith(\"es\")\n ? \"Ya está. Cierra esta pestaña para volver al chat.\"\n : \"All done. Close this tab to go back to the chat.\";\n return (\n <p\n role=\"status\"\n style={{\n position: \"fixed\",\n insetInline: 16,\n bottom: \"calc(16px + env(safe-area-inset-bottom, 0px))\",\n margin: \"0 auto\",\n maxWidth: 420,\n padding: \"12px 16px\",\n borderRadius: 8,\n background: \"var(--foreground, #111)\",\n color: \"var(--background, #fff)\",\n fontSize: 14,\n textAlign: \"center\",\n zIndex: 50,\n }}\n >\n {text}\n </p>\n );\n}\n\nexport function SurfaceProvider(props: {\n token: string;\n endpoint?: string;\n returnUrl?: string;\n /** Your own verify step for `verify` surfaces. Without it, a plain one in the user's language (en/es) styled with your tokens. */\n verifyScreen?: (props: VerifyStepProps) => ReactNode;\n children: ReactNode;\n}) {\n const base = `${props.endpoint ?? \"/api/ui\"}/sessions/${encodeURIComponent(props.token)}`;\n const [state, setState] = useState<{\n status: Status;\n surface?: string;\n locale?: string;\n data?: unknown;\n error?: string;\n errorCode?: string;\n errorReason?: string;\n verify?: VerifyPrompt;\n }>({ status: \"loading\" });\n const opened = useRef(false);\n\n /** Every request after the first load: turns failures into `SurfaceActionError`s, and notices a closed link. */\n const send = useCallback(async (url: string, init: RequestInit) => {\n const res = await fetch(url, init).catch(() => {\n throw new SurfaceActionError(\"Couldn't reach the server\", \"network\", true);\n });\n const json = await res.json().catch(() => ({}));\n if (!res.ok) {\n if (json.error === \"completed\") setState((s) => ({ status: \"completed\", locale: s.locale }));\n throw new SurfaceActionError(json.message ?? json.error ?? res.statusText, json.error, json.retryable, json.reason);\n }\n return json;\n }, []);\n\n // An action whose outcome the screen never learned (the connection dropped, the server was still on it or failed\n // midway) keeps its key: retrying it, or the user tapping again with the same choices, sends the same key, and the\n // server answers with what the first try did instead of doing it twice.\n const unsettled = useRef<{ sig: string; key: string } | undefined>(undefined);\n const emit = useCallback(\n async (type: string, payload: unknown = {}) => {\n const sig = JSON.stringify([type, payload]);\n const key = unsettled.current?.sig === sig ? unsettled.current.key : eventKey();\n let json: { data?: unknown };\n for (let attempt = 0; ; attempt++) {\n try {\n json = await send(`${base}/events`, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ type, payload, key }),\n // `complete()` usually runs as the user follows \"Back to chat\": let it finish after the page goes.\n keepalive: true,\n });\n unsettled.current = undefined;\n break;\n } catch (err) {\n const code = (err as SurfaceActionError).code;\n // Any other answer is final: the action was refused or failed, and the server already freed the key.\n if (code !== \"network\" && code !== \"in_progress\" && code !== \"internal\") {\n unsettled.current = undefined;\n throw err;\n }\n unsettled.current = { sig, key };\n if (code === \"internal\" || attempt === 2) throw err;\n await new Promise((r) => setTimeout(r, attempt ? 1500 : 500));\n }\n }\n // The link is closed now: show the \"done\" screen if the user is still here.\n if (type === \"completed\") {\n setState((s) => ({ status: \"completed\", locale: s.locale }));\n return undefined;\n }\n if (json.data !== undefined && json.data !== null) setState((s) => ({ ...s, data: json.data }));\n // Also returned, so the caller can show the outcome of *this* action (a new ticket number) right away.\n return json.data ?? undefined;\n },\n [base, send],\n );\n\n /** Upload into one of the contract's file slots. Rejections are `invalid_file`, with `reason` e.g. \"file_too_large\". */\n const upload = useCallback(\n async (slot: string, file: File) => {\n const body = new FormData();\n body.append(\"file\", file);\n const json = await send(`${base}/files/${encodeURIComponent(slot)}`, { method: \"POST\", body });\n return json.file as UiFileRef;\n },\n [base, send],\n );\n const removeFile = useCallback(\n async (id: string) => void (await send(`${base}/files/${encodeURIComponent(id)}`, { method: \"DELETE\" })),\n [base, send],\n );\n /** Where to show an uploaded file, e.g. as an <img> src. Only works through this link. */\n const fileUrl = useCallback((id: string) => `${base}/files/${encodeURIComponent(id)}`, [base]);\n\n /** Fetch fresh data, e.g. after a failed action when what's on screen may be stale. */\n const reload = useCallback(async () => {\n const json = await send(base, {});\n setState((s) => ({ ...s, data: json.data }));\n }, [base, send]);\n\n /**\n * Tell the agent something failed on the screen, e.g. a third-party API called from the browser.\n * Server-side failures (in `resolve` or event handlers) are reported automatically.\n */\n const reportError = useCallback(\n (err: unknown, context?: string, source: \"client\" | \"render\" = \"client\") => {\n const e = err as { name?: string; code?: unknown; message?: unknown; retryable?: unknown };\n const payload = {\n source,\n code: String(typeof e?.code === \"string\" ? e.code : (e?.name ?? \"client_error\")).slice(0, 60),\n message: String(e?.message ?? err).slice(0, 500),\n retryable: e?.retryable === true,\n context: context?.slice(0, 200),\n };\n void emit(\"error\", payload).catch(() => {});\n },\n [emit],\n );\n\n /** The data is in: show the screen, and record `opened` once (a verify surface only gets here after the PIN). */\n const ready = useCallback(\n (json: { surface: string; locale: string; data: unknown }) => {\n setState({ status: \"ready\", surface: json.surface, locale: json.locale, data: json.data });\n if (!opened.current) {\n opened.current = true;\n void emit(\"opened\").catch(() => {});\n }\n },\n [emit],\n );\n\n const submitVerify = useCallback(\n async (typed: string) => {\n try {\n ready(await send(`${base}/verify`, { method: \"POST\", headers: { \"Content-Type\": \"application/json\" }, body: JSON.stringify({ code: typed }) }));\n } catch (err) {\n if (err instanceof SurfaceActionError && err.reason === \"wrong_code\") {\n setState((s) => (s.verify ? { ...s, verify: { ...s.verify, attemptsLeft: Math.max(0, s.verify.attemptsLeft - 1) } } : s));\n }\n throw err;\n }\n },\n [base, send, ready],\n );\n const sendCode = useCallback(async () => (await send(`${base}/verify/send`, { method: \"POST\" })) as { hint?: string }, [base, send]);\n\n useEffect(() => {\n let cancelled = false;\n fetch(base)\n .then(async (res) => {\n // A proxy or host error page isn't JSON: treat it like an unreachable server.\n const json = await res.json().catch(() => ({ error: \"network\" }));\n if (cancelled) return;\n // Errors for a known link carry its surface and language, so the screen can explain in the user's words.\n const { locale } = json;\n if (json.error === \"completed\") return setState({ status: \"completed\", locale });\n if (res.status === 410) return setState({ status: \"expired\", locale, error: json.message });\n if (!res.ok) {\n const errorCode = res.status >= 500 && !json.surface ? \"network\" : (json.error ?? \"network\");\n return setState({ status: \"error\", surface: json.surface, locale, error: json.message ?? json.error, errorCode, errorReason: json.reason });\n }\n if (json.verify) return setState({ status: \"verify\", surface: json.surface, locale: json.locale, verify: json.verify });\n ready(json);\n })\n .catch((e) => !cancelled && setState({ status: \"error\", error: String(e), errorCode: \"network\" }));\n return () => {\n cancelled = true;\n };\n }, [base, ready]);\n\n useEffect(() => {\n if (state.status !== \"ready\") return;\n const onVisibility = () => {\n if (document.visibilityState === \"hidden\") {\n // sendBeacon survives the tab closing; fetch might not.\n const blob = new Blob([JSON.stringify({ type: \"left\", payload: {} })], { type: \"application/json\" });\n navigator.sendBeacon(`${base}/events`, blob);\n } else {\n // Fails once the session is completed; emit has already switched the screen.\n void emit(\"opened\").catch(() => {});\n }\n };\n document.addEventListener(\"visibilitychange\", onVisibility);\n return () => document.removeEventListener(\"visibilitychange\", onVisibility);\n }, [state.status, base, emit]);\n\n const locale = state.locale ?? (typeof navigator === \"undefined\" ? \"en\" : navigator.language);\n useEffect(() => {\n document.documentElement.lang = locale;\n }, [locale]);\n\n // \"Back to chat\" on a computer, when the screen opened in a tab of its own: the chat (WhatsApp Web, a web chat)\n // is still open in the tab it came from, and following a wa.me link there lands on WhatsApp's \"open the app\"\n // page. So close this tab instead, whichever link points at returnUrl. A screen opened in the chat's own tab\n // follows the link back, as phones do. A new tab starts with one history entry; read it before steps add more.\n const [ownTab] = useState(() => typeof window !== \"undefined\" && (window.history.length <= 1 || Boolean(window.opener)));\n const [closeHint, setCloseHint] = useState(false);\n useEffect(() => {\n const target = props.returnUrl;\n if (!target || !ownTab) return;\n const onClick = (e: MouseEvent) => {\n const link = (e.target as Element | null)?.closest?.(\"a\");\n if (!link || link.getAttribute(\"href\") !== target || !onComputer()) return;\n e.preventDefault(); // the link's own onClick (e.g. complete()) still runs\n window.close();\n // Browsers only let a script close a tab with a single history entry (screens with steps add more).\n setTimeout(() => !window.closed && setCloseHint(true), 300);\n };\n document.addEventListener(\"click\", onClick, true);\n return () => document.removeEventListener(\"click\", onClick, true);\n }, [props.returnUrl, ownTab]);\n\n const value = useMemo<ContextValue>(\n () => ({ ...state, locale, data: state.data, emit, reload, reportError, upload, removeFile, fileUrl, returnUrl: props.returnUrl }),\n [state, locale, emit, reload, reportError, upload, removeFile, fileUrl, props.returnUrl],\n );\n return (\n <SurfaceContext.Provider value={value}>\n <SurfaceErrorBoundary report={(err, info) => reportError(err, info, \"render\")} locale={locale} returnUrl={props.returnUrl}>\n {state.status === \"verify\" && state.verify\n ? (props.verifyScreen ?? ((p: VerifyStepProps) => <VerifyStep {...p} />))({ prompt: state.verify, locale, submit: submitVerify, sendCode })\n : props.children}\n {closeHint && <CloseTabHint locale={locale} />}\n </SurfaceErrorBoundary>\n </SurfaceContext.Provider>\n );\n}\n\nconst VERIFY_TEXT = {\n en: {\n pinTitle: \"Enter your PIN\",\n pinHelp: \"This screen has personal details. Enter your PIN to see them.\",\n codeTitle: \"Enter the code we sent you\",\n codeHelp: \"This screen has personal details. We've sent you a code to check it's you.\",\n label: \"PIN or code\",\n submit: \"Continue\",\n resend: \"Send a new code\",\n wrong: (n: number) => (n === 1 ? \"That's not right. You have 1 try left.\" : `That's not right. You have ${n} tries left.`),\n locked: \"Too many wrong tries. Go back to the chat to ask for help.\",\n noCode: \"We couldn't send a code. Go back to the chat to ask for help.\",\n failed: \"Something went wrong. Check your connection and try again.\",\n },\n es: {\n pinTitle: \"Introduce tu PIN\",\n pinHelp: \"Esta pantalla tiene datos personales. Introduce tu PIN para verlos.\",\n codeTitle: \"Introduce el código que te hemos enviado\",\n codeHelp: \"Esta pantalla tiene datos personales. Te hemos enviado un código para comprobar que eres tú.\",\n label: \"PIN o código\",\n submit: \"Continuar\",\n resend: \"Enviar otro código\",\n wrong: (n: number) => (n === 1 ? \"No es correcto. Te queda 1 intento.\" : `No es correcto. Te quedan ${n} intentos.`),\n locked: \"Demasiados intentos. Vuelve al chat para pedir ayuda.\",\n noCode: \"No hemos podido enviarte un código. Vuelve al chat para pedir ayuda.\",\n failed: \"Algo ha fallado. Comprueba tu conexión e inténtalo de nuevo.\",\n },\n};\n\n/** The built-in verify step: one field, big enough to tap, in the user's language. Wrap it in your `verifyScreen` to add to it. */\nexport function VerifyStep({ prompt, locale, submit, sendCode, note }: VerifyStepProps & { note?: ReactNode }) {\n const t = VERIFY_TEXT[locale.toLowerCase().startsWith(\"es\") ? \"es\" : \"en\"];\n const [typed, setTyped] = useState(\"\");\n const [busy, setBusy] = useState(false);\n const [message, setMessage] = useState<string | undefined>(prompt.attemptsLeft <= 0 ? t.locked : undefined);\n const [hint, setHint] = useState<string>();\n const [locked, setLocked] = useState(prompt.attemptsLeft <= 0);\n const sent = useRef(false);\n const requestCode = useCallback(() => {\n sendCode().then(\n (r) => setHint(r.hint),\n (err: SurfaceActionError) => setMessage(err.code === \"network\" ? t.failed : t.noCode),\n );\n }, [sendCode, t]);\n // A code is sent once, when the step first shows; a reload within the same link sends another (at most 3).\n useEffect(() => {\n if (prompt.kind === \"code\" && !sent.current && prompt.attemptsLeft > 0) {\n sent.current = true;\n requestCode();\n }\n }, [prompt.kind, requestCode]);\n\n const onSubmit = async (e: { preventDefault(): void }) => {\n e.preventDefault();\n if (!typed.trim() || busy) return;\n setBusy(true);\n setMessage(undefined);\n try {\n await submit(typed);\n } catch (err) {\n const a = err as SurfaceActionError;\n if (a.code === \"verification_locked\") {\n setLocked(true);\n setMessage(t.locked);\n } else setMessage(a.reason === \"wrong_code\" ? t.wrong(Math.max(0, prompt.attemptsLeft - 1)) : t.failed);\n setTyped(\"\");\n } finally {\n setBusy(false);\n }\n };\n\n const field = { width: \"100%\", boxSizing: \"border-box\", minHeight: 48, padding: \"10px 12px\", fontSize: 20, letterSpacing: 4, textAlign: \"center\", borderRadius: 8, border: \"1px solid var(--border, #ccc)\", background: \"var(--background, #fff)\", color: \"var(--foreground, #111)\" } as const;\n return (\n <main style={{ minHeight: \"100dvh\", maxWidth: 420, margin: \"0 auto\", padding: \"32px 16px\", fontFamily: \"inherit\", color: \"var(--foreground, #111)\" }}>\n <form onSubmit={onSubmit} style={{ display: \"grid\", gap: 12 }}>\n <h1 style={{ fontSize: 20, fontWeight: 600, margin: 0 }}>{prompt.kind === \"pin\" ? t.pinTitle : t.codeTitle}</h1>\n <p style={{ margin: 0, color: \"var(--muted-foreground, #555)\" }}>\n {prompt.kind === \"pin\" ? t.pinHelp : t.codeHelp}\n {hint && <> ({hint})</>}\n </p>\n <input\n aria-label={t.label}\n value={typed}\n onChange={(e) => setTyped(e.target.value)}\n inputMode=\"numeric\"\n autoComplete={prompt.kind === \"code\" ? \"one-time-code\" : \"off\"}\n type={prompt.kind === \"pin\" ? \"password\" : \"text\"}\n maxLength={12}\n autoFocus\n disabled={locked}\n style={field}\n />\n {message && (\n <p role=\"alert\" style={{ margin: 0, color: \"var(--destructive, #b42318)\" }}>\n {message}\n </p>\n )}\n <button\n type=\"submit\"\n disabled={busy || locked || !typed.trim()}\n style={{ minHeight: 48, borderRadius: 8, border: 0, fontSize: 16, fontWeight: 600, background: \"var(--primary, #111)\", color: \"var(--primary-foreground, #fff)\", opacity: busy || locked || !typed.trim() ? 0.6 : 1 }}\n >\n {t.submit}\n </button>\n {prompt.kind === \"code\" && !locked && (\n <button type=\"button\" onClick={requestCode} style={{ minHeight: 44, border: 0, background: \"none\", color: \"var(--primary, #111)\", fontSize: 15, textDecoration: \"underline\" }}>\n {t.resend}\n </button>\n )}\n {note}\n </form>\n </main>\n );\n}\n\nconst CRASH_TEXT: Record<string, [string, string]> = {\n en: [\"Something went wrong on this page\", \"Your assistant has been notified. You can go back to the chat.\"],\n es: [\"Algo ha fallado en esta página\", \"Tu asistente ya lo sabe. Puedes volver al chat.\"],\n};\n\n/** Reports render crashes to the agent and shows a minimal fallback instead of a blank page. */\nclass SurfaceErrorBoundary extends Component<\n { children: ReactNode; report: (err: unknown, where?: string) => void; locale: string; returnUrl?: string },\n { crashed: boolean }\n> {\n state = { crashed: false };\n\n static getDerivedStateFromError() {\n return { crashed: true };\n }\n\n componentDidCatch(error: unknown, info: ErrorInfo) {\n const where = info.componentStack?.trim().split(\"\\n\")[0]?.trim();\n this.props.report(error, where ? `rendering ${where}` : \"rendering the screen\");\n }\n\n render() {\n if (!this.state.crashed) return this.props.children;\n const [title, body] = CRASH_TEXT[this.props.locale.split(\"-\")[0]] ?? CRASH_TEXT.en;\n return (\n <div role=\"alert\" style={{ padding: 24, maxWidth: 420, margin: \"0 auto\", fontFamily: \"system-ui, sans-serif\" }}>\n <p style={{ fontWeight: 600, margin: 0 }}>{title}</p>\n <p style={{ margin: \"6px 0 0\", opacity: 0.7 }}>{body}</p>\n {this.props.returnUrl && (\n <a href={this.props.returnUrl} style={{ display: \"inline-block\", marginTop: 12 }}>\n ←\n </a>\n )}\n </div>\n );\n }\n}\n\n/** Typed access to a surface's data and events. */\nexport function useSurface<S extends AnySurface>(surface: S) {\n const ctx = useContext(SurfaceContext);\n if (!ctx) throw new Error(\"useSurface must be used inside <SurfaceProvider>\");\n if (ctx.surface && ctx.surface !== surface.name) {\n throw new Error(`This link is for \"${ctx.surface}\", not \"${surface.name}\"`);\n }\n return {\n status: ctx.status,\n error: ctx.error,\n errorCode: ctx.errorCode,\n errorReason: ctx.errorReason,\n reload: ctx.reload,\n reportError: ctx.reportError,\n locale: ctx.locale,\n data: ctx.data as SurfaceData<S> | undefined,\n returnUrl: ctx.returnUrl,\n /** Report an event. Resolves with the screen's fresh data when the handler returned some (else undefined). */\n emit: ctx.emit as <K extends SurfaceEventName<S>>(type: K, payload: SurfaceEventPayload<S, K>) => Promise<SurfaceData<S> | undefined>,\n complete: () => ctx.emit(\"completed\").then(() => undefined),\n upload: ctx.upload as (slot: SurfaceFileSlot<S>, file: File) => Promise<UiFileRef>,\n removeFile: ctx.removeFile,\n fileUrl: ctx.fileUrl,\n };\n}\n\n/** The link's state (status, surface, locale, errorCode, errorReason, returnUrl), before you know which screen it is: for routing between surfaces on one page. */\nexport function useSurfaceSession() {\n const ctx = useContext(SurfaceContext);\n return {\n status: ctx?.status ?? \"loading\",\n surface: ctx?.surface,\n locale: ctx?.locale,\n error: ctx?.error,\n errorCode: ctx?.errorCode,\n errorReason: ctx?.errorReason,\n returnUrl: ctx?.returnUrl,\n };\n}\n\n/** @deprecated Renamed to `useSurfaceSession`: it returns the link's whole state, not just a name. */\nexport const useSurfaceName = useSurfaceSession;\n\n/**\n * The steps of a screen with several steps, kept in the browser's history so the phone's back button\n * goes to the previous step instead of closing the screen.\n *\n * - `steps` is the path the user will see now (leave out steps that don't apply). If the current step\n * drops out of it, the step that took its place is shown.\n * - `initial` is where to start, usually the furthest step saved in your draft (`data.draft.step`).\n * - After a reload the step comes back from history. Opened fresh on a later step, the earlier steps are\n * added behind it, so Back goes to them.\n *\n * const { step, index, count, go, next, back } = useSurfaceSteps(path, { initial: data.draft.step });\n */\nexport function useSurfaceSteps<S extends string>(steps: readonly S[], options: { initial: S; key?: string }) {\n const key = options.key ?? \"uiCallingStep\";\n // The step, and where it sat in the path: if the step drops out of the path, its place is shown instead.\n const [pos, setPos] = useState(() => {\n const restored = typeof window === \"undefined\" ? undefined : historyStep<S>(key);\n const step = restored ?? options.initial;\n return { step, index: Math.max(0, steps.indexOf(step)) };\n });\n const found = steps.indexOf(pos.step);\n const index = found === -1 ? Math.min(pos.index, steps.length - 1) : found;\n const step = steps[index];\n\n const path = useRef(steps);\n useEffect(() => {\n path.current = steps;\n });\n // Where the screen opened, for the mount effect below (only read there).\n const opened = useRef(index);\n useEffect(() => {\n if (!historyStep(key)) {\n const at = opened.current;\n window.history.replaceState({ ...window.history.state, [key]: path.current[0] }, \"\");\n for (const s of path.current.slice(1, at + 1)) window.history.pushState({ ...window.history.state, [key]: s }, \"\");\n }\n const onPop = () => {\n const s = historyStep<S>(key);\n if (!s) return;\n // A step that no longer applies (say, photos after the reason changed) gives way to the one before it.\n const found = path.current.indexOf(s);\n setPos((prev) => ({ step: s, index: found === -1 ? Math.max(0, prev.index - 1) : found }));\n };\n window.addEventListener(\"popstate\", onPop);\n return () => window.removeEventListener(\"popstate\", onPop);\n }, [key]);\n\n const go = useCallback(\n (to: S) => {\n setPos({ step: to, index: Math.max(0, path.current.indexOf(to)) });\n window.history.pushState({ ...window.history.state, [key]: to }, \"\");\n },\n [key],\n );\n\n return {\n step,\n index,\n count: steps.length,\n isFirst: index === 0,\n isLast: index === steps.length - 1,\n /** Show a step and add it to history. */\n go,\n next: () => {\n if (index < steps.length - 1) go(steps[index + 1]);\n },\n /** Like the phone's back button: the previous step in history. */\n back: () => {\n if (index > 0) window.history.back();\n },\n };\n}\n\nfunction historyStep<S extends string>(key: string) {\n return (window.history.state as Record<string, unknown> | null)?.[key] as S | undefined;\n}\n"],"mappings":";;;AAAA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAGK;AAoFH,SAyUe,UAzUf,KAiPE,YAjPF;AAnCG,IAAM,qBAAN,cAAiC,MAAM;AAAA,EAC5C,YACE,SACO,MACA,YAAY,OACZ,QACP;AACA,UAAM,OAAO;AAJN;AACA;AACA;AAAA,EAGT;AAAA,EALS;AAAA,EACA;AAAA,EACA;AAIX;AAGA,SAAS,WAAW;AAClB,MAAI,OAAO,OAAO,eAAe,WAAY,QAAO,OAAO,WAAW;AACtE,SAAO,MAAM,KAAK,OAAO,gBAAgB,IAAI,WAAW,EAAE,CAAC,GAAG,CAAC,MAAM,EAAE,SAAS,EAAE,EAAE,SAAS,GAAG,GAAG,CAAC,EAAE,KAAK,EAAE;AAC/G;AAEA,IAAM,iBAAiB,cAAmC,IAAI;AAS9D,SAAS,aAAa;AACpB,SAAO,OAAO,eAAe,cAAc,WAAW,oCAAoC,EAAE;AAC9F;AAEA,SAAS,aAAa,EAAE,OAAO,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0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0-preview.1",
4
+ "description": "React bindings for ui-calling surfaces: typed data, semantic events, automatic lifecycle tracking.",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/pausanchez/ui-calling.git",
9
+ "directory": "packages/react"
10
+ },
11
+ "homepage": "https://github.com/pausanchez/ui-calling#readme",
12
+ "bugs": {
13
+ "url": "https://github.com/pausanchez/ui-calling/issues"
14
+ },
15
+ "keywords": [
16
+ "ui-calling",
17
+ "react",
18
+ "agents",
19
+ "ui"
20
+ ],
21
+ "type": "module",
22
+ "exports": {
23
+ ".": {
24
+ "ui-calling-source": "./src/index.tsx",
25
+ "types": "./dist/index.d.ts",
26
+ "default": "./dist/index.js"
27
+ }
28
+ },
29
+ "types": "./dist/index.d.ts",
30
+ "files": [
31
+ "dist",
32
+ "LICENSE"
33
+ ],
34
+ "sideEffects": false,
35
+ "scripts": {
36
+ "build": "tsup"
37
+ },
38
+ "tsup": {
39
+ "entry": {
40
+ "index": "src/index.tsx"
41
+ },
42
+ "format": [
43
+ "esm"
44
+ ],
45
+ "dts": true,
46
+ "clean": true,
47
+ "sourcemap": true,
48
+ "target": "es2022",
49
+ "banner": {
50
+ "js": "\"use client\";"
51
+ },
52
+ "removeNodeProtocol": false
53
+ },
54
+ "dependencies": {
55
+ "@ui-calling/core": "^0.1.0-preview.1"
56
+ },
57
+ "peerDependencies": {
58
+ "react": ">=18"
59
+ },
60
+ "publishConfig": {
61
+ "access": "public"
62
+ }
63
+ }