@armdesk/connect-sdk 0.0.0-stage → 1.1.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/CHANGELOG.md +41 -0
- package/LICENSE.txt +15 -0
- package/README.md +525 -3
- package/dist/armdesk-connect.js +41 -0
- package/dist/esm/browser.d.ts +3 -0
- package/dist/esm/browser.js +18 -0
- package/dist/esm/client.d.ts +46 -0
- package/dist/esm/client.js +307 -0
- package/dist/esm/defaults.d.ts +8 -0
- package/dist/esm/defaults.js +22 -0
- package/dist/esm/elements.d.ts +3 -0
- package/dist/esm/elements.js +368 -0
- package/dist/esm/errors.d.ts +12 -0
- package/dist/esm/errors.js +34 -0
- package/dist/esm/handler.d.ts +40 -0
- package/dist/esm/handler.js +106 -0
- package/dist/esm/http.d.ts +22 -0
- package/dist/esm/http.js +66 -0
- package/dist/esm/index.d.ts +30 -0
- package/dist/esm/index.js +30 -0
- package/dist/esm/messenger.d.ts +8 -0
- package/dist/esm/messenger.js +269 -0
- package/dist/esm/mount.d.ts +8 -0
- package/dist/esm/mount.js +213 -0
- package/dist/esm/protocol.d.ts +37 -0
- package/dist/esm/protocol.js +57 -0
- package/dist/esm/react.d.ts +89 -0
- package/dist/esm/react.js +311 -0
- package/dist/esm/register.d.ts +1 -0
- package/dist/esm/register.js +5 -0
- package/dist/esm/sanitize.d.ts +8 -0
- package/dist/esm/sanitize.js +57 -0
- package/dist/esm/server.d.ts +17 -0
- package/dist/esm/server.js +93 -0
- package/dist/esm/sign.d.ts +54 -0
- package/dist/esm/sign.js +77 -0
- package/dist/esm/theme.d.ts +8 -0
- package/dist/esm/theme.js +46 -0
- package/dist/esm/types.d.ts +375 -0
- package/dist/esm/types.js +1 -0
- package/examples/express-server/package.json +10 -0
- package/examples/express-server/server.mjs +35 -0
- package/examples/mock-idp.mjs +30 -0
- package/examples/react-vite/index.html +11 -0
- package/examples/react-vite/package.json +15 -0
- package/examples/react-vite/src/main.jsx +25 -0
- package/examples/react-vite/vite.config.js +4 -0
- package/examples/wso2-browser.html +86 -0
- package/package.json +59 -4
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import { type ReactNode } from "react";
|
|
2
|
+
import { type ArmDeskClient } from "./client.js";
|
|
3
|
+
import type { AuthOption, ClientMountOptions, ConnectHandle, ConnectTheme, ConnectView, CreatedTicket, CreateTicketInput, ListTicketsParams, MessengerController, MessengerEventMap, MessengerOptions, MountOptions, TicketDetail, TicketList } from "./types.js";
|
|
4
|
+
export interface ArmDeskProviderProps {
|
|
5
|
+
orgKey: string;
|
|
6
|
+
auth: AuthOption;
|
|
7
|
+
/** The desk URL (React has no script tag to detect it from). */
|
|
8
|
+
desk?: string;
|
|
9
|
+
theme?: ConnectTheme;
|
|
10
|
+
/** Bring your own client (tests, custom fetch). */
|
|
11
|
+
client?: ArmDeskClient;
|
|
12
|
+
children?: ReactNode;
|
|
13
|
+
}
|
|
14
|
+
/** `<ArmDeskProvider orgKey auth desk>`: one client for the subtree. `auth` callbacks may change every render. */
|
|
15
|
+
export declare function ArmDeskProvider({ orgKey, auth, desk, theme, client, children }: ArmDeskProviderProps): import("react").FunctionComponentElement<import("react").ProviderProps<ArmDeskClient | null>>;
|
|
16
|
+
/** The client of the nearest provider. */
|
|
17
|
+
export declare function useArmDesk(): ArmDeskClient;
|
|
18
|
+
interface Async<T> {
|
|
19
|
+
data: T | null;
|
|
20
|
+
loading: boolean;
|
|
21
|
+
error: Error | null;
|
|
22
|
+
refetch: () => void;
|
|
23
|
+
}
|
|
24
|
+
/** `const { data, loading, error, refetch } = useTickets({ status: "OPEN", page: 1 })`; refetches on ticket events. */
|
|
25
|
+
export declare function useTickets(params?: ListTicketsParams): Async<TicketList>;
|
|
26
|
+
export declare function useTicket(id: string | null | undefined): Async<TicketDetail>;
|
|
27
|
+
export declare function useCreateTicket(): {
|
|
28
|
+
loading: boolean;
|
|
29
|
+
error: Error | null;
|
|
30
|
+
ticket: CreatedTicket | null;
|
|
31
|
+
create: (input: CreateTicketInput) => Promise<CreatedTicket>;
|
|
32
|
+
};
|
|
33
|
+
export type ArmDeskEmbedProps = (ClientMountOptions | MountOptions) & {
|
|
34
|
+
className?: string;
|
|
35
|
+
};
|
|
36
|
+
/**
|
|
37
|
+
* `<ArmDeskEmbed view="tickets" />` inside a provider mounts the full portal in an iframe. The legacy form
|
|
38
|
+
* `<ArmDeskEmbed baseUrl orgKey getToken />` (no provider) still works.
|
|
39
|
+
*/
|
|
40
|
+
export declare function ArmDeskEmbed(props: ArmDeskEmbedProps): import("react").DetailedReactHTMLElement<{
|
|
41
|
+
ref: import("react").MutableRefObject<HTMLDivElement | null>;
|
|
42
|
+
className: string | undefined;
|
|
43
|
+
}, HTMLDivElement>;
|
|
44
|
+
/** A ticket list. `onSelect` receives the ticket id (open your own route, or render <ArmDeskTicket />). */
|
|
45
|
+
export declare function ArmDeskTickets({ onSelect, status, limit, className }: {
|
|
46
|
+
onSelect?: (id: string) => void;
|
|
47
|
+
status?: string;
|
|
48
|
+
limit?: number;
|
|
49
|
+
className?: string;
|
|
50
|
+
}): import("react/jsx-runtime").JSX.Element;
|
|
51
|
+
/** One ticket: conversation (sanitised), reply box, mark as solved. */
|
|
52
|
+
export declare function ArmDeskTicket({ ticketId, className }: {
|
|
53
|
+
ticketId: string;
|
|
54
|
+
className?: string;
|
|
55
|
+
}): import("react/jsx-runtime").JSX.Element;
|
|
56
|
+
/** The new-ticket form. */
|
|
57
|
+
export declare function ArmDeskNewTicket({ onCreated, className }: {
|
|
58
|
+
onCreated?: (t: CreatedTicket) => void;
|
|
59
|
+
className?: string;
|
|
60
|
+
}): import("react/jsx-runtime").JSX.Element;
|
|
61
|
+
export type ArmDeskMessengerProps = Omit<MessengerOptions, "open" | "container" | "onEvent" | "onError"> & {
|
|
62
|
+
/** Controlled open state. Omit it to let the user (and useMessenger) drive the panel. */
|
|
63
|
+
open?: boolean;
|
|
64
|
+
onOpen?: (e: MessengerEventMap["open"]) => void;
|
|
65
|
+
onClose?: () => void;
|
|
66
|
+
onUnread?: (count: number) => void;
|
|
67
|
+
onEvent?: MessengerOptions["onEvent"];
|
|
68
|
+
onError?: MessengerOptions["onError"];
|
|
69
|
+
/** Bring your own client instead of the provider's. */
|
|
70
|
+
client?: ArmDeskClient;
|
|
71
|
+
};
|
|
72
|
+
/**
|
|
73
|
+
* `<ArmDeskMessenger position="bottom-right" />` inside <ArmDeskProvider>: the floating bubble and panel. It renders
|
|
74
|
+
* nothing in place (the bubble is fixed to the viewport) and is removed on unmount.
|
|
75
|
+
*/
|
|
76
|
+
export declare function ArmDeskMessenger(props: ArmDeskMessengerProps): null;
|
|
77
|
+
export interface UseMessenger {
|
|
78
|
+
open: (view?: ConnectView) => void;
|
|
79
|
+
close: () => void;
|
|
80
|
+
toggle: () => void;
|
|
81
|
+
isOpen: boolean;
|
|
82
|
+
unread: number;
|
|
83
|
+
/** False until an <ArmDeskMessenger /> is mounted. */
|
|
84
|
+
ready: boolean;
|
|
85
|
+
controller: MessengerController | null;
|
|
86
|
+
}
|
|
87
|
+
/** Drive the page's <ArmDeskMessenger /> from anywhere: `const { open, unread } = useMessenger()`. */
|
|
88
|
+
export declare function useMessenger(): UseMessenger;
|
|
89
|
+
export type { ConnectHandle, ConnectTheme, MountOptions, ArmDeskClient, MessengerController, MessengerOptions };
|
|
@@ -0,0 +1,311 @@
|
|
|
1
|
+
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
2
|
+
import { createContext, createElement, useCallback, useContext, useEffect, useMemo, useRef, useState } from "react";
|
|
3
|
+
import { createClient } from "./client.js";
|
|
4
|
+
import { setCurrentClient } from "./defaults.js";
|
|
5
|
+
import { mount } from "./mount.js";
|
|
6
|
+
import { sanitizeHtml } from "./sanitize.js";
|
|
7
|
+
import { themeVars } from "./theme.js";
|
|
8
|
+
const Ctx = createContext(null);
|
|
9
|
+
/** `<ArmDeskProvider orgKey auth desk>`: one client for the subtree. `auth` callbacks may change every render. */
|
|
10
|
+
export function ArmDeskProvider({ orgKey, auth, desk, theme, client, children }) {
|
|
11
|
+
const latestAuth = useRef(auth);
|
|
12
|
+
latestAuth.current = auth;
|
|
13
|
+
const kind = Object.keys(auth)[0];
|
|
14
|
+
const sessionUrl = "sessionUrl" in auth ? auth.sessionUrl : undefined;
|
|
15
|
+
const made = useMemo(() => {
|
|
16
|
+
if (client)
|
|
17
|
+
return client;
|
|
18
|
+
// stable wrappers: the latest callback is always used and the client is not rebuilt per render
|
|
19
|
+
const stable = { ...latestAuth.current };
|
|
20
|
+
for (const k of ["userToken", "idToken", "getToken"]) {
|
|
21
|
+
if (typeof stable[k] === "function")
|
|
22
|
+
stable[k] = () => latestAuth.current[k]();
|
|
23
|
+
}
|
|
24
|
+
return createClient({ orgKey, desk, auth: stable, theme });
|
|
25
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
26
|
+
}, [client, orgKey, desk, kind, sessionUrl]);
|
|
27
|
+
useEffect(() => {
|
|
28
|
+
setCurrentClient(made);
|
|
29
|
+
return () => made.signOut();
|
|
30
|
+
}, [made]);
|
|
31
|
+
return createElement(Ctx.Provider, { value: made }, children);
|
|
32
|
+
}
|
|
33
|
+
/** The client of the nearest provider. */
|
|
34
|
+
export function useArmDesk() {
|
|
35
|
+
const c = useContext(Ctx);
|
|
36
|
+
if (!c)
|
|
37
|
+
throw new Error("useArmDesk must be used inside <ArmDeskProvider>");
|
|
38
|
+
return c;
|
|
39
|
+
}
|
|
40
|
+
function useLoad(load, deps, events) {
|
|
41
|
+
const client = useArmDesk();
|
|
42
|
+
const [state, setState] = useState({ data: null, loading: true, error: null });
|
|
43
|
+
const [tick, setTick] = useState(0);
|
|
44
|
+
const refetch = useCallback(() => setTick((t) => t + 1), []);
|
|
45
|
+
useEffect(() => {
|
|
46
|
+
let live = true;
|
|
47
|
+
setState((s) => ({ ...s, loading: true, error: null }));
|
|
48
|
+
load(client).then((data) => live && setState({ data, loading: false, error: null }), (error) => live && setState((s) => ({ ...s, loading: false, error })));
|
|
49
|
+
return () => {
|
|
50
|
+
live = false;
|
|
51
|
+
};
|
|
52
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
53
|
+
}, [client, tick, ...deps]);
|
|
54
|
+
useEffect(() => {
|
|
55
|
+
const offs = events.map((e) => client.on(e, () => refetch()));
|
|
56
|
+
return () => offs.forEach((f) => f());
|
|
57
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
58
|
+
}, [client, refetch]);
|
|
59
|
+
return { ...state, refetch };
|
|
60
|
+
}
|
|
61
|
+
/** `const { data, loading, error, refetch } = useTickets({ status: "OPEN", page: 1 })`; refetches on ticket events. */
|
|
62
|
+
export function useTickets(params = {}) {
|
|
63
|
+
const status = Array.isArray(params.status) ? params.status.join(",") : params.status;
|
|
64
|
+
return useLoad((c) => c.tickets.list(params), [status, params.search, params.page, params.limit], ["ticket.created", "ticket.replied"]);
|
|
65
|
+
}
|
|
66
|
+
export function useTicket(id) {
|
|
67
|
+
return useLoad((c) => (id ? c.tickets.get(id) : Promise.reject(new Error("No ticket id"))), [id], ["ticket.replied"]);
|
|
68
|
+
}
|
|
69
|
+
export function useCreateTicket() {
|
|
70
|
+
const client = useArmDesk();
|
|
71
|
+
const [state, setState] = useState({ loading: false, error: null, ticket: null });
|
|
72
|
+
const create = useCallback(async (input) => {
|
|
73
|
+
setState({ loading: true, error: null, ticket: null });
|
|
74
|
+
try {
|
|
75
|
+
const ticket = await client.tickets.create(input);
|
|
76
|
+
setState({ loading: false, error: null, ticket });
|
|
77
|
+
return ticket;
|
|
78
|
+
}
|
|
79
|
+
catch (e) {
|
|
80
|
+
setState({ loading: false, error: e, ticket: null });
|
|
81
|
+
throw e;
|
|
82
|
+
}
|
|
83
|
+
}, [client]);
|
|
84
|
+
return { create, ...state };
|
|
85
|
+
}
|
|
86
|
+
// ---- components -----------------------------------------------------------
|
|
87
|
+
function useThemeStyle() {
|
|
88
|
+
const client = useArmDesk();
|
|
89
|
+
const [theme, setTheme] = useState();
|
|
90
|
+
useEffect(() => {
|
|
91
|
+
let live = true;
|
|
92
|
+
client.config().then((c) => live && setTheme(c.theme), () => undefined);
|
|
93
|
+
return () => {
|
|
94
|
+
live = false;
|
|
95
|
+
};
|
|
96
|
+
}, [client]);
|
|
97
|
+
return themeVars(theme);
|
|
98
|
+
}
|
|
99
|
+
/**
|
|
100
|
+
* `<ArmDeskEmbed view="tickets" />` inside a provider mounts the full portal in an iframe. The legacy form
|
|
101
|
+
* `<ArmDeskEmbed baseUrl orgKey getToken />` (no provider) still works.
|
|
102
|
+
*/
|
|
103
|
+
export function ArmDeskEmbed(props) {
|
|
104
|
+
var _a;
|
|
105
|
+
const provided = useContext(Ctx);
|
|
106
|
+
const ref = useRef(null);
|
|
107
|
+
const handle = useRef(null);
|
|
108
|
+
const latest = useRef(props);
|
|
109
|
+
latest.current = props;
|
|
110
|
+
const legacy = "getToken" in props && typeof props.getToken === "function";
|
|
111
|
+
const key = legacy ? `${props.baseUrl}|${props.orgKey}` : "client";
|
|
112
|
+
useEffect(() => {
|
|
113
|
+
if (!ref.current)
|
|
114
|
+
return;
|
|
115
|
+
const p = latest.current;
|
|
116
|
+
const common = {
|
|
117
|
+
onEvent: (e) => { var _a, _b; return (_b = (_a = latest.current).onEvent) === null || _b === void 0 ? void 0 : _b.call(_a, e); },
|
|
118
|
+
onError: (e) => { var _a, _b; return (_b = (_a = latest.current).onError) === null || _b === void 0 ? void 0 : _b.call(_a, e); },
|
|
119
|
+
};
|
|
120
|
+
if (legacy) {
|
|
121
|
+
handle.current = mount(ref.current, { ...p, ...common, getToken: () => latest.current.getToken() });
|
|
122
|
+
}
|
|
123
|
+
else {
|
|
124
|
+
if (!provided)
|
|
125
|
+
throw new Error("<ArmDeskEmbed> needs <ArmDeskProvider> (or the legacy baseUrl / orgKey / getToken props)");
|
|
126
|
+
handle.current = provided.mount(ref.current, { view: p.view, theme: p.theme, features: p.features, locale: p.locale, height: p.height, ...common });
|
|
127
|
+
}
|
|
128
|
+
return () => {
|
|
129
|
+
var _a;
|
|
130
|
+
(_a = handle.current) === null || _a === void 0 ? void 0 : _a.destroy();
|
|
131
|
+
handle.current = null;
|
|
132
|
+
};
|
|
133
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
134
|
+
}, [key, provided, props.locale, props.height]);
|
|
135
|
+
const themeKey = JSON.stringify((_a = props.theme) !== null && _a !== void 0 ? _a : null);
|
|
136
|
+
useEffect(() => {
|
|
137
|
+
var _a;
|
|
138
|
+
if (props.theme)
|
|
139
|
+
(_a = handle.current) === null || _a === void 0 ? void 0 : _a.setTheme(props.theme);
|
|
140
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
141
|
+
}, [themeKey]);
|
|
142
|
+
useEffect(() => {
|
|
143
|
+
var _a;
|
|
144
|
+
if (props.view)
|
|
145
|
+
(_a = handle.current) === null || _a === void 0 ? void 0 : _a.navigate(props.view);
|
|
146
|
+
}, [props.view]);
|
|
147
|
+
return createElement("div", { ref, className: props.className });
|
|
148
|
+
}
|
|
149
|
+
const cardStyle = { border: "1px solid var(--ad-border, #e5e7eb)", borderRadius: "var(--ad-radius, 8px)", padding: "10px 14px", marginBottom: 8 };
|
|
150
|
+
/** A ticket list. `onSelect` receives the ticket id (open your own route, or render <ArmDeskTicket />). */
|
|
151
|
+
export function ArmDeskTickets({ onSelect, status, limit = 10, className }) {
|
|
152
|
+
const [page, setPage] = useState(1);
|
|
153
|
+
const { data, loading, error, refetch } = useTickets({ status, page, limit });
|
|
154
|
+
const style = useThemeStyle();
|
|
155
|
+
const pages = data ? Math.max(1, Math.ceil(data.total / limit)) : 1;
|
|
156
|
+
return (_jsxs("div", { className: className, style: style, children: [_jsx("h3", { children: "My tickets" }), loading && !data ? _jsx("p", { children: "Loading..." }) : null, error ? _jsxs("p", { role: "alert", children: [error.message, " ", _jsx("button", { onClick: refetch, children: "Try again" })] }) : null, data && data.items.length === 0 ? _jsx("p", { children: "No tickets yet." }) : null, data === null || data === void 0 ? void 0 : data.items.map((t) => (_jsxs("button", { type: "button", style: { ...cardStyle, display: "block", width: "100%", textAlign: "left", cursor: "pointer" }, onClick: () => onSelect === null || onSelect === void 0 ? void 0 : onSelect(t.id), children: [_jsx("strong", { children: t.number }), " ", t.subject, " ", _jsxs("small", { children: ["(", t.status, ")"] })] }, t.id))), _jsxs("div", { children: [_jsx("button", { type: "button", disabled: page <= 1, onClick: () => setPage(page - 1), children: "Previous" }), _jsxs("span", { children: [" ", page, " / ", pages, " "] }), _jsx("button", { type: "button", disabled: page >= pages, onClick: () => setPage(page + 1), children: "Next" })] })] }));
|
|
157
|
+
}
|
|
158
|
+
/** One ticket: conversation (sanitised), reply box, mark as solved. */
|
|
159
|
+
export function ArmDeskTicket({ ticketId, className }) {
|
|
160
|
+
var _a;
|
|
161
|
+
const client = useArmDesk();
|
|
162
|
+
const { data, loading, error, refetch } = useTicket(ticketId);
|
|
163
|
+
const [text, setText] = useState("");
|
|
164
|
+
const [busy, setBusy] = useState(false);
|
|
165
|
+
const style = useThemeStyle();
|
|
166
|
+
const send = async (e) => {
|
|
167
|
+
e.preventDefault();
|
|
168
|
+
setBusy(true);
|
|
169
|
+
try {
|
|
170
|
+
await client.tickets.reply(ticketId, { body: text });
|
|
171
|
+
setText("");
|
|
172
|
+
}
|
|
173
|
+
finally {
|
|
174
|
+
setBusy(false);
|
|
175
|
+
}
|
|
176
|
+
};
|
|
177
|
+
if (loading && !data)
|
|
178
|
+
return _jsx("p", { children: "Loading..." });
|
|
179
|
+
if (error || !data)
|
|
180
|
+
return _jsx("p", { role: "alert", children: (_a = error === null || error === void 0 ? void 0 : error.message) !== null && _a !== void 0 ? _a : "Not found" });
|
|
181
|
+
return (_jsxs("div", { className: className, style: style, children: [_jsxs("h3", { children: [data.number, " ", data.subject, " ", _jsxs("small", { children: ["(", data.status, ")"] })] }), data.threads.map((t) => (_jsxs("div", { style: cardStyle, children: [_jsxs("small", { children: [t.author.name, " - ", new Date(t.createdAt).toLocaleString()] }), _jsx("div", { dangerouslySetInnerHTML: { __html: sanitizeHtml(t.body) } })] }, t.id))), data.canReply ? (_jsxs("form", { onSubmit: send, children: [_jsx("textarea", { "aria-label": "Reply", value: text, onChange: (e) => setText(e.target.value), required: true, rows: 4, style: { width: "100%" } }), _jsx("button", { type: "submit", disabled: busy || !text.trim(), children: "Send reply" })] })) : null, data.canClose ? _jsx("button", { type: "button", onClick: () => void client.tickets.close(ticketId).then(refetch), children: "Mark as solved" }) : null] }));
|
|
182
|
+
}
|
|
183
|
+
/** The new-ticket form. */
|
|
184
|
+
export function ArmDeskNewTicket({ onCreated, className }) {
|
|
185
|
+
const { create, loading, error } = useCreateTicket();
|
|
186
|
+
const [subject, setSubject] = useState("");
|
|
187
|
+
const [description, setDescription] = useState("");
|
|
188
|
+
const style = useThemeStyle();
|
|
189
|
+
const submit = async (e) => {
|
|
190
|
+
e.preventDefault();
|
|
191
|
+
const t = await create({ subject, description }).catch(() => null);
|
|
192
|
+
if (t) {
|
|
193
|
+
setSubject("");
|
|
194
|
+
setDescription("");
|
|
195
|
+
onCreated === null || onCreated === void 0 ? void 0 : onCreated(t);
|
|
196
|
+
}
|
|
197
|
+
};
|
|
198
|
+
return (_jsxs("form", { className: className, style: style, onSubmit: submit, children: [_jsx("h3", { children: "New ticket" }), _jsxs("label", { children: ["Subject ", _jsx("input", { value: subject, onChange: (e) => setSubject(e.target.value), required: true, minLength: 5, maxLength: 255, style: { width: "100%" } })] }), _jsxs("label", { children: ["Description ", _jsx("textarea", { value: description, onChange: (e) => setDescription(e.target.value), required: true, minLength: 10, maxLength: 20000, rows: 6, style: { width: "100%" } })] }), _jsx("button", { type: "submit", disabled: loading, children: "Submit ticket" }), error ? _jsx("p", { role: "alert", children: error.message }) : null] }));
|
|
199
|
+
}
|
|
200
|
+
// ---- messenger --------------------------------------------------------------
|
|
201
|
+
/** The messenger <ArmDeskMessenger /> created most recently (one per page is the norm); useMessenger() reads it. */
|
|
202
|
+
let activeMessenger = null;
|
|
203
|
+
const messengerSubs = new Set();
|
|
204
|
+
const announce = () => messengerSubs.forEach((f) => f());
|
|
205
|
+
/**
|
|
206
|
+
* `<ArmDeskMessenger position="bottom-right" />` inside <ArmDeskProvider>: the floating bubble and panel. It renders
|
|
207
|
+
* nothing in place (the bubble is fixed to the viewport) and is removed on unmount.
|
|
208
|
+
*/
|
|
209
|
+
export function ArmDeskMessenger(props) {
|
|
210
|
+
var _a, _b;
|
|
211
|
+
const provided = useContext(Ctx);
|
|
212
|
+
const client = (_a = props.client) !== null && _a !== void 0 ? _a : provided;
|
|
213
|
+
if (!client)
|
|
214
|
+
throw new Error("<ArmDeskMessenger> needs <ArmDeskProvider> (or a client prop)");
|
|
215
|
+
const latest = useRef(props);
|
|
216
|
+
latest.current = props;
|
|
217
|
+
const ctl = useRef(null);
|
|
218
|
+
const shape = JSON.stringify([props.position, props.offset, props.label, props.ariaLabel, props.iconUrl, props.lazy, props.zIndex, props.locale, props.features]);
|
|
219
|
+
useEffect(() => {
|
|
220
|
+
const p = latest.current;
|
|
221
|
+
const m = client.messenger({
|
|
222
|
+
position: p.position,
|
|
223
|
+
offset: p.offset,
|
|
224
|
+
label: p.label,
|
|
225
|
+
ariaLabel: p.ariaLabel,
|
|
226
|
+
iconUrl: p.iconUrl,
|
|
227
|
+
view: p.view,
|
|
228
|
+
lazy: p.lazy,
|
|
229
|
+
zIndex: p.zIndex,
|
|
230
|
+
theme: p.theme,
|
|
231
|
+
features: p.features,
|
|
232
|
+
locale: p.locale,
|
|
233
|
+
open: p.open,
|
|
234
|
+
onEvent: (e) => { var _a, _b; return (_b = (_a = latest.current).onEvent) === null || _b === void 0 ? void 0 : _b.call(_a, e); },
|
|
235
|
+
onError: (e) => { var _a, _b; return (_b = (_a = latest.current).onError) === null || _b === void 0 ? void 0 : _b.call(_a, e); },
|
|
236
|
+
});
|
|
237
|
+
const offs = [
|
|
238
|
+
m.on("open", (d) => {
|
|
239
|
+
var _a, _b;
|
|
240
|
+
(_b = (_a = latest.current).onOpen) === null || _b === void 0 ? void 0 : _b.call(_a, d);
|
|
241
|
+
announce();
|
|
242
|
+
}),
|
|
243
|
+
m.on("close", () => {
|
|
244
|
+
var _a, _b;
|
|
245
|
+
(_b = (_a = latest.current).onClose) === null || _b === void 0 ? void 0 : _b.call(_a);
|
|
246
|
+
announce();
|
|
247
|
+
}),
|
|
248
|
+
m.on("unread", (n) => {
|
|
249
|
+
var _a, _b;
|
|
250
|
+
(_b = (_a = latest.current).onUnread) === null || _b === void 0 ? void 0 : _b.call(_a, n);
|
|
251
|
+
announce();
|
|
252
|
+
}),
|
|
253
|
+
];
|
|
254
|
+
ctl.current = m;
|
|
255
|
+
activeMessenger = m;
|
|
256
|
+
announce();
|
|
257
|
+
return () => {
|
|
258
|
+
offs.forEach((f) => f());
|
|
259
|
+
m.destroy();
|
|
260
|
+
ctl.current = null;
|
|
261
|
+
if (activeMessenger === m)
|
|
262
|
+
activeMessenger = null;
|
|
263
|
+
announce();
|
|
264
|
+
};
|
|
265
|
+
}, [client, shape]);
|
|
266
|
+
useEffect(() => {
|
|
267
|
+
if (props.open === undefined || !ctl.current)
|
|
268
|
+
return;
|
|
269
|
+
if (props.open)
|
|
270
|
+
ctl.current.open();
|
|
271
|
+
else
|
|
272
|
+
ctl.current.close();
|
|
273
|
+
}, [props.open]);
|
|
274
|
+
useEffect(() => {
|
|
275
|
+
var _a, _b;
|
|
276
|
+
if (props.view && ((_a = ctl.current) === null || _a === void 0 ? void 0 : _a.isOpen()))
|
|
277
|
+
ctl.current.open(props.view);
|
|
278
|
+
else if (props.view)
|
|
279
|
+
(_b = ctl.current) === null || _b === void 0 ? void 0 : _b.navigate(props.view);
|
|
280
|
+
}, [props.view]);
|
|
281
|
+
const themeKey = JSON.stringify((_b = props.theme) !== null && _b !== void 0 ? _b : null);
|
|
282
|
+
useEffect(() => {
|
|
283
|
+
var _a;
|
|
284
|
+
if (props.theme)
|
|
285
|
+
(_a = ctl.current) === null || _a === void 0 ? void 0 : _a.setTheme(props.theme);
|
|
286
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
287
|
+
}, [themeKey]);
|
|
288
|
+
return null;
|
|
289
|
+
}
|
|
290
|
+
/** Drive the page's <ArmDeskMessenger /> from anywhere: `const { open, unread } = useMessenger()`. */
|
|
291
|
+
export function useMessenger() {
|
|
292
|
+
var _a, _b;
|
|
293
|
+
const [, force] = useState(0);
|
|
294
|
+
useEffect(() => {
|
|
295
|
+
const f = () => force((n) => n + 1);
|
|
296
|
+
messengerSubs.add(f);
|
|
297
|
+
return () => {
|
|
298
|
+
messengerSubs.delete(f);
|
|
299
|
+
};
|
|
300
|
+
}, []);
|
|
301
|
+
const m = activeMessenger;
|
|
302
|
+
return {
|
|
303
|
+
open: useCallback((view) => activeMessenger === null || activeMessenger === void 0 ? void 0 : activeMessenger.open(view), []),
|
|
304
|
+
close: useCallback(() => activeMessenger === null || activeMessenger === void 0 ? void 0 : activeMessenger.close(), []),
|
|
305
|
+
toggle: useCallback(() => activeMessenger === null || activeMessenger === void 0 ? void 0 : activeMessenger.toggle(), []),
|
|
306
|
+
isOpen: (_a = m === null || m === void 0 ? void 0 : m.isOpen()) !== null && _a !== void 0 ? _a : false,
|
|
307
|
+
unread: (_b = m === null || m === void 0 ? void 0 : m.unread()) !== null && _b !== void 0 ? _b : 0,
|
|
308
|
+
ready: m !== null,
|
|
309
|
+
controller: m,
|
|
310
|
+
};
|
|
311
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { defineElements, ELEMENT_TAGS } from "./elements.js";
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
// `@armdesk/connect-sdk/elements`: importing it registers <armdesk-tickets>, <armdesk-new-ticket>,
|
|
2
|
+
// <armdesk-ticket ticket-id>, <armdesk-messenger> and <armdesk-launcher> (the messenger, opening at `tickets`).
|
|
3
|
+
import { defineElements } from "./elements.js";
|
|
4
|
+
defineElements();
|
|
5
|
+
export { defineElements, ELEMENT_TAGS } from "./elements.js";
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Allow-list sanitiser for the (already server-sanitised) thread HTML: a small set of text tags, no attributes
|
|
3
|
+
* except a safe `href`, no scripts, styles, event handlers, images or frames. Returns a DocumentFragment-free
|
|
4
|
+
* HTML string built from DOM nodes, so it never re-parses attacker markup.
|
|
5
|
+
*/
|
|
6
|
+
export declare function sanitizeHtml(html: string): string;
|
|
7
|
+
/** Fills `el` with sanitised HTML using DOM nodes only. */
|
|
8
|
+
export declare function setSafeHtml(el: HTMLElement, html: string): void;
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
const ALLOWED = new Set(["p", "br", "b", "strong", "i", "em", "u", "s", "ul", "ol", "li", "a", "code", "pre", "blockquote", "span", "div", "h1", "h2", "h3", "h4", "h5", "h6", "hr"]);
|
|
2
|
+
const DROP_WITH_CONTENT = new Set(["script", "style", "iframe", "object", "embed", "template", "noscript", "svg", "math", "form", "textarea", "select", "head", "title"]);
|
|
3
|
+
function safeHref(value) {
|
|
4
|
+
const v = value.trim();
|
|
5
|
+
if (/^(https?:|mailto:)/i.test(v))
|
|
6
|
+
return v;
|
|
7
|
+
return null;
|
|
8
|
+
}
|
|
9
|
+
function clean(node, out, doc) {
|
|
10
|
+
node.childNodes.forEach((child) => {
|
|
11
|
+
var _a, _b;
|
|
12
|
+
if (child.nodeType === 3) {
|
|
13
|
+
out.appendChild(doc.createTextNode((_a = child.textContent) !== null && _a !== void 0 ? _a : ""));
|
|
14
|
+
return;
|
|
15
|
+
}
|
|
16
|
+
if (child.nodeType !== 1)
|
|
17
|
+
return;
|
|
18
|
+
const el = child;
|
|
19
|
+
const tag = el.tagName.toLowerCase();
|
|
20
|
+
if (DROP_WITH_CONTENT.has(tag))
|
|
21
|
+
return;
|
|
22
|
+
if (!ALLOWED.has(tag)) {
|
|
23
|
+
clean(el, out, doc); // unknown tag: keep its text, drop the tag
|
|
24
|
+
return;
|
|
25
|
+
}
|
|
26
|
+
const copy = doc.createElement(tag);
|
|
27
|
+
if (tag === "a") {
|
|
28
|
+
const href = safeHref((_b = el.getAttribute("href")) !== null && _b !== void 0 ? _b : "");
|
|
29
|
+
if (href) {
|
|
30
|
+
copy.setAttribute("href", href);
|
|
31
|
+
copy.setAttribute("target", "_blank");
|
|
32
|
+
copy.setAttribute("rel", "noopener noreferrer nofollow");
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
clean(el, copy, doc);
|
|
36
|
+
out.appendChild(copy);
|
|
37
|
+
});
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* Allow-list sanitiser for the (already server-sanitised) thread HTML: a small set of text tags, no attributes
|
|
41
|
+
* except a safe `href`, no scripts, styles, event handlers, images or frames. Returns a DocumentFragment-free
|
|
42
|
+
* HTML string built from DOM nodes, so it never re-parses attacker markup.
|
|
43
|
+
*/
|
|
44
|
+
export function sanitizeHtml(html) {
|
|
45
|
+
if (typeof DOMParser === "undefined")
|
|
46
|
+
return html.replace(/<[^>]*>/g, "");
|
|
47
|
+
const parsed = new DOMParser().parseFromString(html, "text/html");
|
|
48
|
+
const wrap = parsed.createElement("div");
|
|
49
|
+
clean(parsed.body, wrap, parsed);
|
|
50
|
+
return wrap.innerHTML;
|
|
51
|
+
}
|
|
52
|
+
/** Fills `el` with sanitised HTML using DOM nodes only. */
|
|
53
|
+
export function setSafeHtml(el, html) {
|
|
54
|
+
const tpl = el.ownerDocument.createElement("div");
|
|
55
|
+
tpl.innerHTML = sanitizeHtml(html);
|
|
56
|
+
el.replaceChildren(...Array.from(tpl.childNodes));
|
|
57
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import type { ConnectSession, CreateConnectSessionOptions } from "./types.js";
|
|
2
|
+
export * from "./sign.js";
|
|
3
|
+
export * from "./handler.js";
|
|
4
|
+
export type { ConnectSession, ConnectUser, CreateConnectSessionOptions } from "./types.js";
|
|
5
|
+
export type ConnectErrorCode = "invalid_credentials" | "forbidden" | "conflict" | "validation" | "rate_limited" | "server" | "network" | "bad_response";
|
|
6
|
+
/** Thrown by createConnectSession. `status` is the HTTP status (0 when none). */
|
|
7
|
+
export declare class ConnectError extends Error {
|
|
8
|
+
readonly code: ConnectErrorCode;
|
|
9
|
+
readonly status: number;
|
|
10
|
+
constructor(code: ConnectErrorCode, message: string, status?: number);
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* Server-to-server: exchange the organisation's credentials and a signed-in
|
|
14
|
+
* user (or their OIDC ID token) for a short-lived connect token. Call this
|
|
15
|
+
* from YOUR backend only - orgSecret must never reach a browser.
|
|
16
|
+
*/
|
|
17
|
+
export declare function createConnectSession(options: CreateConnectSessionOptions): Promise<ConnectSession>;
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
export * from "./sign.js";
|
|
2
|
+
export * from "./handler.js";
|
|
3
|
+
/** Thrown by createConnectSession. `status` is the HTTP status (0 when none). */
|
|
4
|
+
export class ConnectError extends Error {
|
|
5
|
+
constructor(code, message, status = 0) {
|
|
6
|
+
super(message);
|
|
7
|
+
this.name = "ConnectError";
|
|
8
|
+
this.code = code;
|
|
9
|
+
this.status = status;
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
function codeFor(status) {
|
|
13
|
+
if (status === 401)
|
|
14
|
+
return "invalid_credentials";
|
|
15
|
+
if (status === 403)
|
|
16
|
+
return "forbidden";
|
|
17
|
+
if (status === 409)
|
|
18
|
+
return "conflict";
|
|
19
|
+
if (status === 429)
|
|
20
|
+
return "rate_limited";
|
|
21
|
+
if (status >= 500)
|
|
22
|
+
return "server";
|
|
23
|
+
return "validation";
|
|
24
|
+
}
|
|
25
|
+
function basicAuth(key, secret) {
|
|
26
|
+
// orgKey / orgSecret are ASCII (org_ / cos_ + alphanumerics); btoa is global in Node 16+.
|
|
27
|
+
return `Basic ${btoa(`${key}:${secret}`)}`;
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Server-to-server: exchange the organisation's credentials and a signed-in
|
|
31
|
+
* user (or their OIDC ID token) for a short-lived connect token. Call this
|
|
32
|
+
* from YOUR backend only - orgSecret must never reach a browser.
|
|
33
|
+
*/
|
|
34
|
+
export async function createConnectSession(options) {
|
|
35
|
+
var _a, _b;
|
|
36
|
+
const { baseUrl, apiUrl, tenantSlug, orgKey, orgSecret, user, idToken, features, timeoutMs = 10000 } = options;
|
|
37
|
+
if (!baseUrl || !orgKey || !orgSecret)
|
|
38
|
+
throw new ConnectError("validation", "baseUrl, orgKey and orgSecret are required");
|
|
39
|
+
if (!user && !idToken)
|
|
40
|
+
throw new ConnectError("validation", "Pass user or idToken");
|
|
41
|
+
const doFetch = (_a = options.fetch) !== null && _a !== void 0 ? _a : globalThis.fetch;
|
|
42
|
+
if (typeof doFetch !== "function")
|
|
43
|
+
throw new ConnectError("network", "fetch is not available (Node 18+ required)");
|
|
44
|
+
// The desk's web app forwards /api/proxy/* to its API; pass apiUrl to call the API directly.
|
|
45
|
+
const api = apiUrl ? apiUrl.replace(/\/+$/, "") : `${baseUrl.replace(/\/+$/, "")}/api/proxy`;
|
|
46
|
+
const url = `${api}/connect/v1/sessions`;
|
|
47
|
+
const body = {};
|
|
48
|
+
if (user)
|
|
49
|
+
body.user = user;
|
|
50
|
+
if (idToken)
|
|
51
|
+
body.idToken = idToken;
|
|
52
|
+
if (features)
|
|
53
|
+
body.features = features;
|
|
54
|
+
const controller = new AbortController();
|
|
55
|
+
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
56
|
+
let res;
|
|
57
|
+
try {
|
|
58
|
+
res = await doFetch(url, {
|
|
59
|
+
method: "POST",
|
|
60
|
+
headers: {
|
|
61
|
+
"Content-Type": "application/json",
|
|
62
|
+
Accept: "application/json",
|
|
63
|
+
Authorization: basicAuth(orgKey, orgSecret),
|
|
64
|
+
...(tenantSlug ? { "X-Tenant-Slug": tenantSlug } : {}),
|
|
65
|
+
},
|
|
66
|
+
body: JSON.stringify(body),
|
|
67
|
+
signal: controller.signal,
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
catch (err) {
|
|
71
|
+
throw new ConnectError("network", err instanceof Error ? `Could not reach ARM Desk: ${err.message}` : "Could not reach ARM Desk");
|
|
72
|
+
}
|
|
73
|
+
finally {
|
|
74
|
+
clearTimeout(timer);
|
|
75
|
+
}
|
|
76
|
+
let json = null;
|
|
77
|
+
try {
|
|
78
|
+
json = await res.json();
|
|
79
|
+
}
|
|
80
|
+
catch (_c) {
|
|
81
|
+
// non-JSON body - handled below
|
|
82
|
+
}
|
|
83
|
+
if (!res.ok) {
|
|
84
|
+
const msg = json === null || json === void 0 ? void 0 : json.message;
|
|
85
|
+
const text = Array.isArray(msg) ? msg.join("; ") : typeof msg === "string" ? msg : `ARM Desk answered ${res.status}`;
|
|
86
|
+
throw new ConnectError(codeFor(res.status), text, res.status);
|
|
87
|
+
}
|
|
88
|
+
const s = json;
|
|
89
|
+
if (!s || typeof s.token !== "string" || typeof s.expiresIn !== "number" || !s.user) {
|
|
90
|
+
throw new ConnectError("bad_response", "ARM Desk returned an unexpected session response", res.status);
|
|
91
|
+
}
|
|
92
|
+
return { token: s.token, expiresIn: s.expiresIn, user: s.user, contactId: (_b = s.contactId) !== null && _b !== void 0 ? _b : null };
|
|
93
|
+
}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { type KeyObject } from "node:crypto";
|
|
2
|
+
/** The user as your system knows them. `id` is your stable user id (WSO2 `sub`, a database key ...). */
|
|
3
|
+
export interface SignedUser {
|
|
4
|
+
id?: string;
|
|
5
|
+
/** Alias of `id`. */
|
|
6
|
+
uid?: string;
|
|
7
|
+
email?: string;
|
|
8
|
+
name?: string;
|
|
9
|
+
firstName?: string;
|
|
10
|
+
lastName?: string;
|
|
11
|
+
phone?: string;
|
|
12
|
+
/** Your role name; the organisation's role mappings turn it into a CRM contact role. */
|
|
13
|
+
role?: string;
|
|
14
|
+
department?: string;
|
|
15
|
+
/** Free-form extras (<= 4 KB as JSON). */
|
|
16
|
+
attributes?: Record<string, unknown>;
|
|
17
|
+
/** You vouch the e-mail is verified (default: not stated). false = never link an existing account by it. */
|
|
18
|
+
emailVerified?: boolean;
|
|
19
|
+
}
|
|
20
|
+
interface SignBase {
|
|
21
|
+
orgKey: string;
|
|
22
|
+
user: SignedUser;
|
|
23
|
+
/** Lifetime in seconds. Default 300, at most 600. */
|
|
24
|
+
expiresIn?: number;
|
|
25
|
+
/** Test seam: the current time in ms. */
|
|
26
|
+
now?: number;
|
|
27
|
+
}
|
|
28
|
+
export interface SignHmacOptions extends SignBase {
|
|
29
|
+
/** The organisation secret (cos_...). Never leaves your server. */
|
|
30
|
+
orgSecret: string;
|
|
31
|
+
/** The secret's version, taken from the key id ARM Desk shows next to it. Default 1; bump it after a rotation. */
|
|
32
|
+
secretVersion?: number | string;
|
|
33
|
+
privateKey?: undefined;
|
|
34
|
+
}
|
|
35
|
+
export interface SignAsymmetricOptions extends SignBase {
|
|
36
|
+
/** PEM (PKCS8 / PKCS1 / SEC1) or a KeyObject: the private half of the key registered for the organisation. */
|
|
37
|
+
privateKey: string | KeyObject;
|
|
38
|
+
/** The key id registered with ARM Desk. */
|
|
39
|
+
kid: string;
|
|
40
|
+
alg?: "RS256" | "ES256";
|
|
41
|
+
orgSecret?: undefined;
|
|
42
|
+
}
|
|
43
|
+
export type SignUserTokenOptions = SignHmacOptions | SignAsymmetricOptions;
|
|
44
|
+
export declare const MAX_EXPIRES_IN = 600;
|
|
45
|
+
export declare const DEFAULT_EXPIRES_IN = 300;
|
|
46
|
+
/** HMAC-SHA256(orgSecret, "armdesk-connect-assertion-v1"): the signing key, so the raw secret is never the JWT key. */
|
|
47
|
+
export declare function deriveAssertionKey(orgSecret: string): Buffer;
|
|
48
|
+
/**
|
|
49
|
+
* Mints the signed user token (OAuth 2.0 JWT bearer assertion, RFC 7523) your page hands to the browser library as
|
|
50
|
+
* `auth: { userToken }`. Local: no network call, no endpoint of yours. HS256 with the key derived from the org
|
|
51
|
+
* secret, or RS256 / ES256 with your own registered private key.
|
|
52
|
+
*/
|
|
53
|
+
export declare function signUserToken(options: SignUserTokenOptions): string;
|
|
54
|
+
export {};
|