@armdesk/connect-sdk 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/LICENSE.txt +15 -0
  3. package/README.md +403 -3
  4. package/dist/armdesk-connect.js +23 -0
  5. package/dist/esm/browser.d.ts +3 -0
  6. package/dist/esm/browser.js +18 -0
  7. package/dist/esm/client.d.ts +44 -0
  8. package/dist/esm/client.js +298 -0
  9. package/dist/esm/defaults.d.ts +8 -0
  10. package/dist/esm/defaults.js +22 -0
  11. package/dist/esm/elements.d.ts +3 -0
  12. package/dist/esm/elements.js +307 -0
  13. package/dist/esm/errors.d.ts +12 -0
  14. package/dist/esm/errors.js +34 -0
  15. package/dist/esm/handler.d.ts +40 -0
  16. package/dist/esm/handler.js +106 -0
  17. package/dist/esm/http.d.ts +22 -0
  18. package/dist/esm/http.js +66 -0
  19. package/dist/esm/index.d.ts +18 -0
  20. package/dist/esm/index.js +15 -0
  21. package/dist/esm/mount.d.ts +8 -0
  22. package/dist/esm/mount.js +170 -0
  23. package/dist/esm/protocol.d.ts +18 -0
  24. package/dist/esm/protocol.js +31 -0
  25. package/dist/esm/react.d.ts +61 -0
  26. package/dist/esm/react.js +199 -0
  27. package/dist/esm/register.d.ts +1 -0
  28. package/dist/esm/register.js +5 -0
  29. package/dist/esm/sanitize.d.ts +8 -0
  30. package/dist/esm/sanitize.js +57 -0
  31. package/dist/esm/server.d.ts +17 -0
  32. package/dist/esm/server.js +93 -0
  33. package/dist/esm/sign.d.ts +54 -0
  34. package/dist/esm/sign.js +77 -0
  35. package/dist/esm/theme.d.ts +8 -0
  36. package/dist/esm/theme.js +46 -0
  37. package/dist/esm/types.d.ts +298 -0
  38. package/dist/esm/types.js +1 -0
  39. package/examples/express-server/package.json +10 -0
  40. package/examples/express-server/server.mjs +35 -0
  41. package/examples/mock-idp.mjs +30 -0
  42. package/examples/react-vite/index.html +11 -0
  43. package/examples/react-vite/package.json +15 -0
  44. package/examples/react-vite/src/main.jsx +25 -0
  45. package/examples/react-vite/vite.config.js +4 -0
  46. package/examples/wso2-browser.html +86 -0
  47. package/package.json +59 -4
@@ -0,0 +1,34 @@
1
+ export class ArmDeskError extends Error {
2
+ constructor(code, message, status = 0, retryAfter) {
3
+ super(message);
4
+ this.name = "ArmDeskError";
5
+ this.code = code;
6
+ this.status = status;
7
+ this.retryAfter = retryAfter;
8
+ }
9
+ }
10
+ export function codeForStatus(status) {
11
+ if (status === 401)
12
+ return "unauthorized";
13
+ if (status === 403)
14
+ return "forbidden";
15
+ if (status === 404)
16
+ return "not_found";
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
+ /** Builds the typed error for a non-2xx answer (Nest `{message}` or RFC 6749 `{error, error_description}`). */
26
+ export function errorFromBody(status, body, retryAfter) {
27
+ const b = (body && typeof body === "object" ? body : {});
28
+ if (typeof b.error === "string") {
29
+ const text = typeof b.error_description === "string" ? b.error_description : b.error;
30
+ return new ArmDeskError(b.error, text, status, retryAfter);
31
+ }
32
+ const text = Array.isArray(b.message) ? b.message.join("; ") : typeof b.message === "string" ? b.message : `ARM Desk answered ${status}`;
33
+ return new ArmDeskError(codeForStatus(status), text, status, retryAfter);
34
+ }
@@ -0,0 +1,40 @@
1
+ import type { ConnectFeatures, ConnectUser } from "./types.js";
2
+ /** The signed-in user of YOUR product. `id` (or `uid`) is your stable user id. */
3
+ export type HandlerUser = Omit<ConnectUser, "uid"> & {
4
+ id?: string;
5
+ uid?: string;
6
+ };
7
+ export interface ConnectHandlerOptions {
8
+ orgKey: string;
9
+ /** Server only. */
10
+ orgSecret: string;
11
+ /** The desk, e.g. https://desk.example.com. */
12
+ desk: string;
13
+ /** The API's own base when you do not go through the desk's web proxy. */
14
+ apiUrl?: string;
15
+ tenantSlug?: string;
16
+ /**
17
+ * Who is signed in? Receives the framework's own request (Express req, Next/fetch Request, Node IncomingMessage)
18
+ * and returns the user, or null/undefined when nobody is signed in (the browser then gets 401).
19
+ */
20
+ getUser: (req: any) => HandlerUser | null | undefined | Promise<HandlerUser | null | undefined>;
21
+ /** Extra origins allowed to call the route, besides the route's own origin. */
22
+ allowedOrigins?: string[];
23
+ /** Switch features off for the sessions this route mints. */
24
+ features?: ConnectFeatures;
25
+ fetch?: typeof fetch;
26
+ }
27
+ /**
28
+ * Server mode. Mount the returned handler on `/armdesk/session` (the browser library's default `sessionUrl`). It reads
29
+ * YOUR signed-in user through `getUser`, asks ARM Desk for a connect token with the org credentials and returns only
30
+ * `{ token, expiresIn }`. The org secret never reaches the browser.
31
+ */
32
+ export declare function createConnectHandler(options: ConnectHandlerOptions): {
33
+ /** `app.post("/armdesk/session", handler.express())` (Express, Connect, Fastify with middie). */
34
+ express: () => (req: any, res: any, next?: (err?: unknown) => void) => void;
35
+ /** `export const POST = handler.next();` in `app/armdesk/session/route.ts`. */
36
+ next: () => (req: Request) => Promise<Response>;
37
+ fetch: (req: Request) => Promise<Response>;
38
+ /** `http.createServer((req, res) => handler.node(req, res))`. */
39
+ node: (req: any, res: any) => Promise<void>;
40
+ };
@@ -0,0 +1,106 @@
1
+ import { CSRF_HEADER } from "./protocol.js";
2
+ import { ConnectError, createConnectSession } from "./server.js";
3
+ const hostOf = (origin) => {
4
+ try {
5
+ return new URL(origin).host;
6
+ }
7
+ catch (_a) {
8
+ return null;
9
+ }
10
+ };
11
+ /** CSRF: the custom header must be present (a cross-site form cannot send it) and a given Origin must be this site's own. */
12
+ function csrfRefusal(r, allowed) {
13
+ var _a;
14
+ if (r.header(CSRF_HEADER.toLowerCase()) !== "1")
15
+ return { status: 403, body: { error: "csrf", message: `Missing ${CSRF_HEADER} header` } };
16
+ const origin = r.header("origin");
17
+ if (origin && origin !== "null") {
18
+ const own = (_a = r.header("x-forwarded-host")) !== null && _a !== void 0 ? _a : r.header("host");
19
+ const ok = (own && hostOf(origin) === own.split(",")[0].trim()) || allowed.some((a) => a === origin);
20
+ if (!ok)
21
+ return { status: 403, body: { error: "csrf", message: "Cross-origin request refused" } };
22
+ }
23
+ else if (origin === "null") {
24
+ return { status: 403, body: { error: "csrf", message: "Cross-origin request refused" } };
25
+ }
26
+ const site = r.header("sec-fetch-site");
27
+ if (site === "cross-site")
28
+ return { status: 403, body: { error: "csrf", message: "Cross-site request refused" } };
29
+ return null;
30
+ }
31
+ /**
32
+ * Server mode. Mount the returned handler on `/armdesk/session` (the browser library's default `sessionUrl`). It reads
33
+ * YOUR signed-in user through `getUser`, asks ARM Desk for a connect token with the org credentials and returns only
34
+ * `{ token, expiresIn }`. The org secret never reaches the browser.
35
+ */
36
+ export function createConnectHandler(options) {
37
+ if (!options.orgKey || !options.orgSecret || !options.desk)
38
+ throw new Error("createConnectHandler: orgKey, orgSecret and desk are required");
39
+ if (typeof options.getUser !== "function")
40
+ throw new Error("createConnectHandler: getUser is required");
41
+ async function core(r) {
42
+ var _a, _b;
43
+ if (r.method !== "POST")
44
+ return { status: 405, body: { error: "method_not_allowed" } };
45
+ const refusal = csrfRefusal(r, (_a = options.allowedOrigins) !== null && _a !== void 0 ? _a : []);
46
+ if (refusal)
47
+ return refusal;
48
+ let user;
49
+ try {
50
+ user = await options.getUser(r.native);
51
+ }
52
+ catch (_c) {
53
+ return { status: 500, body: { error: "get_user_failed" } };
54
+ }
55
+ const uid = (_b = user === null || user === void 0 ? void 0 : user.id) !== null && _b !== void 0 ? _b : user === null || user === void 0 ? void 0 : user.uid;
56
+ if (!user || !uid)
57
+ return { status: 401, body: { error: "unauthenticated" } };
58
+ const { id: _id, uid: _uid, ...profile } = user;
59
+ try {
60
+ const s = await createConnectSession({
61
+ baseUrl: options.desk,
62
+ apiUrl: options.apiUrl,
63
+ tenantSlug: options.tenantSlug,
64
+ orgKey: options.orgKey,
65
+ orgSecret: options.orgSecret,
66
+ features: options.features,
67
+ fetch: options.fetch,
68
+ user: { ...profile, uid },
69
+ });
70
+ return { status: 200, body: { token: s.token, expiresIn: s.expiresIn } };
71
+ }
72
+ catch (err) {
73
+ if (err instanceof ConnectError) {
74
+ // credentials / org problems are OUR configuration, not the visitor's fault: 502, with a code only
75
+ const status = err.code === "rate_limited" ? 429 : err.code === "conflict" || err.code === "validation" ? 422 : 502;
76
+ return { status, body: { error: err.code } };
77
+ }
78
+ return { status: 502, body: { error: "unexpected" } };
79
+ }
80
+ }
81
+ const NO_STORE = { "Cache-Control": "no-store", "Content-Type": "application/json" };
82
+ /** Standard Request -> Response: Next.js App Router (`export const POST = handler.fetch`), Workers, Deno, Bun. */
83
+ const fetchHandler = async (req) => {
84
+ const out = await core({ method: req.method, header: (n) => { var _a; return (_a = req.headers.get(n)) !== null && _a !== void 0 ? _a : undefined; }, native: req });
85
+ return new Response(JSON.stringify(out.body), { status: out.status, headers: NO_STORE });
86
+ };
87
+ const nodeHandler = async (req, res) => {
88
+ var _a;
89
+ const out = await core({ method: (_a = req.method) !== null && _a !== void 0 ? _a : "GET", header: (n) => { var _a, _b; return (Array.isArray((_a = req.headers) === null || _a === void 0 ? void 0 : _a[n]) ? req.headers[n][0] : (_b = req.headers) === null || _b === void 0 ? void 0 : _b[n]); }, native: req });
90
+ res.statusCode = out.status;
91
+ for (const [k, v] of Object.entries(NO_STORE))
92
+ res.setHeader(k, v);
93
+ res.end(JSON.stringify(out.body));
94
+ };
95
+ return {
96
+ /** `app.post("/armdesk/session", handler.express())` (Express, Connect, Fastify with middie). */
97
+ express: () => (req, res, next) => {
98
+ nodeHandler(req, res).catch((err) => (next ? next(err) : res.end()));
99
+ },
100
+ /** `export const POST = handler.next();` in `app/armdesk/session/route.ts`. */
101
+ next: () => fetchHandler,
102
+ fetch: fetchHandler,
103
+ /** `http.createServer((req, res) => handler.node(req, res))`. */
104
+ node: nodeHandler,
105
+ };
106
+ }
@@ -0,0 +1,22 @@
1
+ export interface HttpConfig {
2
+ fetch: typeof fetch;
3
+ retries: number;
4
+ retryDelayMs: number;
5
+ timeoutMs: number;
6
+ }
7
+ export interface SendInit {
8
+ method: "GET" | "POST";
9
+ headers?: Record<string, string>;
10
+ body?: BodyInit;
11
+ credentials?: RequestCredentials;
12
+ }
13
+ /** Retry-After as milliseconds (seconds or an HTTP date); undefined when absent or unreadable. */
14
+ export declare function retryAfterMs(res: Response): number | undefined;
15
+ /**
16
+ * One HTTP call with timeout and retries. 429 and 5xx are retried with exponential backoff (Retry-After wins);
17
+ * 4xx other than 429 never. A POST is retried only on 429 and 503 (the request was refused, not half-done);
18
+ * network errors are retried for GET only.
19
+ */
20
+ export declare function send(cfg: HttpConfig, url: string, init: SendInit): Promise<Response>;
21
+ /** Reads the JSON body and throws the typed error for a non-2xx answer. */
22
+ export declare function readJson<T>(res: Response): Promise<T>;
@@ -0,0 +1,66 @@
1
+ import { ArmDeskError, errorFromBody } from "./errors.js";
2
+ const MAX_RETRY_WAIT_MS = 30000;
3
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
4
+ /** Retry-After as milliseconds (seconds or an HTTP date); undefined when absent or unreadable. */
5
+ export function retryAfterMs(res) {
6
+ const raw = res.headers.get("Retry-After");
7
+ if (!raw)
8
+ return undefined;
9
+ const secs = Number(raw);
10
+ if (Number.isFinite(secs))
11
+ return Math.max(0, secs * 1000);
12
+ const at = Date.parse(raw);
13
+ return Number.isNaN(at) ? undefined : Math.max(0, at - Date.now());
14
+ }
15
+ /**
16
+ * One HTTP call with timeout and retries. 429 and 5xx are retried with exponential backoff (Retry-After wins);
17
+ * 4xx other than 429 never. A POST is retried only on 429 and 503 (the request was refused, not half-done);
18
+ * network errors are retried for GET only.
19
+ */
20
+ export async function send(cfg, url, init) {
21
+ const retriable = (status) => status === 429 || (init.method === "GET" ? status >= 500 : status === 503);
22
+ for (let attempt = 0;; attempt++) {
23
+ const controller = new AbortController();
24
+ const timer = setTimeout(() => controller.abort(), cfg.timeoutMs);
25
+ let res = null;
26
+ let netErr = null;
27
+ try {
28
+ res = await cfg.fetch(url, { method: init.method, headers: init.headers, body: init.body, credentials: init.credentials, signal: controller.signal });
29
+ }
30
+ catch (err) {
31
+ netErr = err;
32
+ }
33
+ finally {
34
+ clearTimeout(timer);
35
+ }
36
+ const last = attempt >= cfg.retries;
37
+ if (res) {
38
+ if (res.ok || !retriable(res.status) || last)
39
+ return res;
40
+ const wait = retryAfterMs(res);
41
+ await sleep(Math.min(MAX_RETRY_WAIT_MS, wait !== null && wait !== void 0 ? wait : cfg.retryDelayMs * 2 ** attempt));
42
+ continue;
43
+ }
44
+ if (init.method !== "GET" || last) {
45
+ throw new ArmDeskError("network", netErr instanceof Error ? `Could not reach ARM Desk: ${netErr.message}` : "Could not reach ARM Desk");
46
+ }
47
+ await sleep(Math.min(MAX_RETRY_WAIT_MS, cfg.retryDelayMs * 2 ** attempt));
48
+ }
49
+ }
50
+ /** Reads the JSON body and throws the typed error for a non-2xx answer. */
51
+ export async function readJson(res) {
52
+ let body = null;
53
+ try {
54
+ body = await res.json();
55
+ }
56
+ catch (_a) {
57
+ // not JSON
58
+ }
59
+ if (!res.ok) {
60
+ const ra = retryAfterMs(res);
61
+ throw errorFromBody(res.status, body, ra === undefined ? undefined : Math.ceil(ra / 1000));
62
+ }
63
+ if (body === null || body === undefined)
64
+ throw new ArmDeskError("bad_response", "ARM Desk returned an empty response", res.status);
65
+ return body;
66
+ }
@@ -0,0 +1,18 @@
1
+ import { createClient, init } from "./client.js";
2
+ import { mount } from "./mount.js";
3
+ import type { ConnectHandle, MountOptions } from "./types.js";
4
+ export declare const VERSION = "1.0.0";
5
+ /** The IIFE's global: `ArmDeskConnect.init({ orgKey, auth })`. `mount(el, { getToken })` still works (deprecated). */
6
+ export declare const ArmDeskConnect: {
7
+ version: string;
8
+ init: typeof init;
9
+ createClient: typeof createClient;
10
+ /** @deprecated Use `init({ orgKey, auth })` and `client.mount(el)`. */
11
+ mount: (container: HTMLElement | string, options: MountOptions) => ConnectHandle;
12
+ };
13
+ export { init, createClient, mount };
14
+ export type { ArmDeskClient } from "./client.js";
15
+ export { ArmDeskError, type ArmDeskErrorCode } from "./errors.js";
16
+ export { sanitizeHtml } from "./sanitize.js";
17
+ export { themeCss, themeVars } from "./theme.js";
18
+ export type * from "./types.js";
@@ -0,0 +1,15 @@
1
+ import { createClient, init } from "./client.js";
2
+ import { mount } from "./mount.js";
3
+ export const VERSION = "1.0.0";
4
+ /** The IIFE's global: `ArmDeskConnect.init({ orgKey, auth })`. `mount(el, { getToken })` still works (deprecated). */
5
+ export const ArmDeskConnect = {
6
+ version: VERSION,
7
+ init,
8
+ createClient,
9
+ /** @deprecated Use `init({ orgKey, auth })` and `client.mount(el)`. */
10
+ mount: (container, options) => mount(container, options),
11
+ };
12
+ export { init, createClient, mount };
13
+ export { ArmDeskError } from "./errors.js";
14
+ export { sanitizeHtml } from "./sanitize.js";
15
+ export { themeCss, themeVars } from "./theme.js";
@@ -0,0 +1,8 @@
1
+ import type { ConnectHandle, MountOptions } from "./types.js";
2
+ /**
3
+ * Mounts the ARM Desk ITSM embed into `container` and speaks the embed
4
+ * protocol with it. The token travels only by postMessage to the desk's exact
5
+ * origin - never in the iframe URL - and every incoming message must come from
6
+ * that iframe window AND that origin.
7
+ */
8
+ export declare function mount(container: HTMLElement | string, options: MountOptions): ConnectHandle;
@@ -0,0 +1,170 @@
1
+ import { deskOrigin, isProtocolMessage, LOCALES, MAX_TOKEN_LENGTH, PROTOCOL_SOURCE, VIEW_PATTERN } from "./protocol.js";
2
+ const READY_TIMEOUT_MS = 20000;
3
+ const TOKEN_ATTEMPTS = 4;
4
+ const TOKEN_BACKOFF_MS = 400;
5
+ const MIN_HEIGHT = 120;
6
+ const MAX_HEIGHT = 20000;
7
+ function resolveContainer(target) {
8
+ const el = typeof target === "string" ? document.querySelector(target) : target;
9
+ if (!el)
10
+ throw new Error("ArmDeskConnect: container not found");
11
+ return el;
12
+ }
13
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
14
+ /**
15
+ * Mounts the ARM Desk ITSM embed into `container` and speaks the embed
16
+ * protocol with it. The token travels only by postMessage to the desk's exact
17
+ * origin - never in the iframe URL - and every incoming message must come from
18
+ * that iframe window AND that origin.
19
+ */
20
+ export function mount(container, options) {
21
+ var _a, _b;
22
+ const host = resolveContainer(container);
23
+ const origin = deskOrigin(options.baseUrl);
24
+ if (!options.orgKey)
25
+ throw new Error("ArmDeskConnect: orgKey is required");
26
+ if (typeof options.getToken !== "function")
27
+ throw new Error("ArmDeskConnect: getToken is required");
28
+ if (options.view !== undefined && !VIEW_PATTERN.test(options.view))
29
+ throw new Error("ArmDeskConnect: invalid view");
30
+ let view = (_a = options.view) !== null && _a !== void 0 ? _a : "tickets";
31
+ let theme = { ...((_b = options.theme) !== null && _b !== void 0 ? _b : {}) };
32
+ let ready = false;
33
+ let destroyed = false;
34
+ let tokenInFlight = null;
35
+ const params = new URLSearchParams({ org: options.orgKey, view });
36
+ if (options.locale && LOCALES.includes(options.locale))
37
+ params.set("locale", options.locale);
38
+ const frame = document.createElement("iframe");
39
+ frame.src = `${origin}/embed/itsm?${params.toString()}`;
40
+ frame.title = "Support tickets";
41
+ frame.setAttribute("referrerpolicy", "strict-origin");
42
+ frame.setAttribute("loading", "lazy");
43
+ frame.setAttribute("data-armdesk-connect", "");
44
+ Object.assign(frame.style, { width: "100%", border: "0", display: "block", colorScheme: "normal" });
45
+ frame.style.height = typeof options.height === "number" ? `${options.height}px` : "480px";
46
+ const post = (type, payload) => {
47
+ const win = frame.contentWindow;
48
+ if (destroyed || !win)
49
+ return;
50
+ win.postMessage({ source: PROTOCOL_SOURCE, type, payload }, origin);
51
+ };
52
+ const fail = (code, message) => {
53
+ var _a;
54
+ try {
55
+ (_a = options.onError) === null || _a === void 0 ? void 0 : _a.call(options, { code, message });
56
+ }
57
+ catch (_b) {
58
+ // a throwing host callback must not break the protocol loop
59
+ }
60
+ };
61
+ /** getToken with retry and exponential backoff; one request at a time. */
62
+ const fetchToken = () => {
63
+ if (tokenInFlight)
64
+ return tokenInFlight;
65
+ tokenInFlight = (async () => {
66
+ for (let attempt = 0; attempt < TOKEN_ATTEMPTS && !destroyed; attempt++) {
67
+ try {
68
+ const token = await options.getToken();
69
+ if (typeof token === "string" && token.length > 0 && token.length <= MAX_TOKEN_LENGTH)
70
+ return token;
71
+ throw new Error("getToken returned an invalid token");
72
+ }
73
+ catch (err) {
74
+ if (attempt === TOKEN_ATTEMPTS - 1) {
75
+ fail("token_failed", err instanceof Error ? err.message : "Could not get a token");
76
+ break;
77
+ }
78
+ await sleep(TOKEN_BACKOFF_MS * 2 ** attempt);
79
+ }
80
+ }
81
+ return null;
82
+ })().finally(() => {
83
+ tokenInFlight = null;
84
+ });
85
+ return tokenInFlight;
86
+ };
87
+ const sendToken = async (type) => {
88
+ var _a;
89
+ const token = await fetchToken();
90
+ if (!token || destroyed)
91
+ return;
92
+ post(type, type === "init" ? { token, theme, features: (_a = options.features) !== null && _a !== void 0 ? _a : {} } : { token });
93
+ };
94
+ let readyTimer = setTimeout(() => {
95
+ if (!ready)
96
+ fail("timeout", "The embed did not respond. Check baseUrl and the organisation's allowed origins.");
97
+ }, READY_TIMEOUT_MS);
98
+ const onMessage = (event) => {
99
+ var _a;
100
+ if (destroyed)
101
+ return;
102
+ if (event.origin !== origin || event.source !== frame.contentWindow)
103
+ return;
104
+ if (!isProtocolMessage(event.data))
105
+ return;
106
+ const { type, payload } = event.data;
107
+ const body = (typeof payload === "object" && payload !== null ? payload : {});
108
+ switch (type) {
109
+ case "ready":
110
+ ready = true;
111
+ if (readyTimer)
112
+ clearTimeout(readyTimer);
113
+ readyTimer = null;
114
+ void sendToken("init");
115
+ break;
116
+ case "request-token":
117
+ void sendToken("token");
118
+ break;
119
+ case "resize": {
120
+ const h = Number(body.height);
121
+ if (options.height === undefined || options.height === "auto") {
122
+ if (Number.isFinite(h))
123
+ frame.style.height = `${Math.min(MAX_HEIGHT, Math.max(MIN_HEIGHT, Math.ceil(h)))}px`;
124
+ }
125
+ break;
126
+ }
127
+ case "event":
128
+ if (typeof body.name === "string") {
129
+ try {
130
+ (_a = options.onEvent) === null || _a === void 0 ? void 0 : _a.call(options, { name: body.name, data: body.data });
131
+ }
132
+ catch (_b) {
133
+ // host callback errors stay the host's
134
+ }
135
+ }
136
+ break;
137
+ case "error":
138
+ fail(typeof body.code === "string" ? body.code : "error", typeof body.message === "string" ? body.message : "Embed error");
139
+ break;
140
+ default:
141
+ break;
142
+ }
143
+ };
144
+ window.addEventListener("message", onMessage);
145
+ host.appendChild(frame);
146
+ return {
147
+ navigate(next) {
148
+ if (!VIEW_PATTERN.test(next))
149
+ throw new Error("ArmDeskConnect: invalid view");
150
+ view = next;
151
+ if (ready)
152
+ post("navigate", { view });
153
+ },
154
+ setTheme(next) {
155
+ theme = { ...next };
156
+ if (ready)
157
+ post("theme", { theme });
158
+ },
159
+ refreshToken: () => sendToken("token"),
160
+ destroy() {
161
+ if (destroyed)
162
+ return;
163
+ destroyed = true;
164
+ if (readyTimer)
165
+ clearTimeout(readyTimer);
166
+ window.removeEventListener("message", onMessage);
167
+ frame.remove();
168
+ },
169
+ };
170
+ }
@@ -0,0 +1,18 @@
1
+ /** The embed protocol shared by the SDK and the embed page (apps/web components/connect-embed). */
2
+ export declare const PROTOCOL_SOURCE = "armdesk-connect";
3
+ export declare const VIEW_PATTERN: RegExp;
4
+ export declare const LOCALES: readonly ["en", "es", "ar"];
5
+ export declare const MAX_TOKEN_LENGTH = 8192;
6
+ export interface ProtocolMessage {
7
+ source: typeof PROTOCOL_SOURCE;
8
+ type: string;
9
+ payload?: unknown;
10
+ }
11
+ export declare function isProtocolMessage(data: unknown): data is ProtocolMessage;
12
+ /** The origin of a desk URL: https, or http for localhost only. Throws for anything else. */
13
+ export declare function deskOrigin(baseUrl: string): string;
14
+ /** Sent by the library to a server-mode session route; a custom header a cross-site form cannot add. */
15
+ export declare const CSRF_HEADER = "X-ArmDesk-Csrf";
16
+ export declare const DEFAULT_SESSION_PATH = "/armdesk/session";
17
+ export declare const JWT_BEARER_GRANT = "urn:ietf:params:oauth:grant-type:jwt-bearer";
18
+ export declare const ASSERTION_AUDIENCE = "armdesk-connect";
@@ -0,0 +1,31 @@
1
+ /** The embed protocol shared by the SDK and the embed page (apps/web components/connect-embed). */
2
+ export const PROTOCOL_SOURCE = "armdesk-connect";
3
+ export const VIEW_PATTERN = /^(tickets|new|ticket:[A-Za-z0-9_-]{1,64})$/;
4
+ export const LOCALES = ["en", "es", "ar"];
5
+ export const MAX_TOKEN_LENGTH = 8192;
6
+ export function isProtocolMessage(data) {
7
+ if (typeof data !== "object" || data === null)
8
+ return false;
9
+ const d = data;
10
+ return d.source === PROTOCOL_SOURCE && typeof d.type === "string";
11
+ }
12
+ /** The origin of a desk URL: https, or http for localhost only. Throws for anything else. */
13
+ export function deskOrigin(baseUrl) {
14
+ let url;
15
+ try {
16
+ url = new URL(baseUrl);
17
+ }
18
+ catch (_a) {
19
+ throw new Error("ArmDeskConnect: baseUrl must be an absolute URL");
20
+ }
21
+ const local = url.hostname === "localhost" || url.hostname === "127.0.0.1" || url.hostname === "[::1]";
22
+ if (url.protocol !== "https:" && !(url.protocol === "http:" && local)) {
23
+ throw new Error("ArmDeskConnect: baseUrl must be https (http is allowed for localhost only)");
24
+ }
25
+ return url.origin;
26
+ }
27
+ /** Sent by the library to a server-mode session route; a custom header a cross-site form cannot add. */
28
+ export const CSRF_HEADER = "X-ArmDesk-Csrf";
29
+ export const DEFAULT_SESSION_PATH = "/armdesk/session";
30
+ export const JWT_BEARER_GRANT = "urn:ietf:params:oauth:grant-type:jwt-bearer";
31
+ export const ASSERTION_AUDIENCE = "armdesk-connect";
@@ -0,0 +1,61 @@
1
+ import { type ReactNode } from "react";
2
+ import { type ArmDeskClient } from "./client.js";
3
+ import type { AuthOption, ClientMountOptions, ConnectHandle, ConnectTheme, CreatedTicket, CreateTicketInput, ListTicketsParams, 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 { ConnectHandle, ConnectTheme, MountOptions, ArmDeskClient };