@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.
- package/CHANGELOG.md +22 -0
- package/LICENSE.txt +15 -0
- package/README.md +403 -3
- package/dist/armdesk-connect.js +23 -0
- package/dist/esm/browser.d.ts +3 -0
- package/dist/esm/browser.js +18 -0
- package/dist/esm/client.d.ts +44 -0
- package/dist/esm/client.js +298 -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 +307 -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 +18 -0
- package/dist/esm/index.js +15 -0
- package/dist/esm/mount.d.ts +8 -0
- package/dist/esm/mount.js +170 -0
- package/dist/esm/protocol.d.ts +18 -0
- package/dist/esm/protocol.js +31 -0
- package/dist/esm/react.d.ts +61 -0
- package/dist/esm/react.js +199 -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 +298 -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,298 @@
|
|
|
1
|
+
import { ArmDeskError } from "./errors.js";
|
|
2
|
+
import { getDefaultDesk, setCurrentClient } from "./defaults.js";
|
|
3
|
+
import { readJson, send } from "./http.js";
|
|
4
|
+
import { mount } from "./mount.js";
|
|
5
|
+
import { CSRF_HEADER, DEFAULT_SESSION_PATH, deskOrigin, JWT_BEARER_GRANT, MAX_TOKEN_LENGTH } from "./protocol.js";
|
|
6
|
+
const EXPIRY_MARGIN_MS = 30000;
|
|
7
|
+
const DEFAULT_TOKEN_TTL_S = 840;
|
|
8
|
+
const V1 = "/connect/v1";
|
|
9
|
+
/**
|
|
10
|
+
* The headless client: typed, Promise-based, no endpoint strings for the caller. It signs in with the `auth` option,
|
|
11
|
+
* keeps the connect token in memory only, renews it before it expires, retries 429 / 5xx with backoff and throws
|
|
12
|
+
* `ArmDeskError` for everything else.
|
|
13
|
+
*/
|
|
14
|
+
export function createClient(options) {
|
|
15
|
+
var _a, _b, _c, _d, _e, _f;
|
|
16
|
+
if (!options || !options.orgKey)
|
|
17
|
+
throw new ArmDeskError("config", "ArmDeskConnect: orgKey is required");
|
|
18
|
+
if (!options.auth || typeof options.auth !== "object")
|
|
19
|
+
throw new ArmDeskError("config", "ArmDeskConnect: auth is required");
|
|
20
|
+
const deskUrl = (_a = options.desk) !== null && _a !== void 0 ? _a : getDefaultDesk();
|
|
21
|
+
if (!deskUrl)
|
|
22
|
+
throw new ArmDeskError("config", "ArmDeskConnect: desk is required (it is detected only when the script tag is used)");
|
|
23
|
+
const desk = deskOrigin(deskUrl);
|
|
24
|
+
const doFetch = (_b = options.fetch) !== null && _b !== void 0 ? _b : (_c = globalThis.fetch) === null || _c === void 0 ? void 0 : _c.bind(globalThis);
|
|
25
|
+
if (typeof doFetch !== "function")
|
|
26
|
+
throw new ArmDeskError("config", "fetch is not available");
|
|
27
|
+
const http = { fetch: doFetch, retries: (_d = options.retries) !== null && _d !== void 0 ? _d : 2, retryDelayMs: (_e = options.retryDelayMs) !== null && _e !== void 0 ? _e : 400, timeoutMs: (_f = options.timeoutMs) !== null && _f !== void 0 ? _f : 20000 };
|
|
28
|
+
const auth = options.auth;
|
|
29
|
+
const listeners = new Map();
|
|
30
|
+
const emit = (event, payload) => {
|
|
31
|
+
var _a;
|
|
32
|
+
(_a = listeners.get(event)) === null || _a === void 0 ? void 0 : _a.forEach((cb) => {
|
|
33
|
+
try {
|
|
34
|
+
cb(payload);
|
|
35
|
+
}
|
|
36
|
+
catch (_a) {
|
|
37
|
+
// a throwing host listener must not break the client
|
|
38
|
+
}
|
|
39
|
+
});
|
|
40
|
+
};
|
|
41
|
+
// ---- where the API lives ------------------------------------------------
|
|
42
|
+
let apiPromise = null;
|
|
43
|
+
const fallbackApi = `${desk}/api/proxy`;
|
|
44
|
+
// The desk's bootstrap answers with the versioned base (`…/api/connect/v1`); every call
|
|
45
|
+
// below appends V1 itself, so accept both spellings and keep the unversioned root.
|
|
46
|
+
const root = (u) => u.replace(/\/+$/, "").replace(/\/connect\/v1$/, "");
|
|
47
|
+
const apiBase = () => {
|
|
48
|
+
if (options.apiBase)
|
|
49
|
+
return Promise.resolve(root(options.apiBase));
|
|
50
|
+
apiPromise !== null && apiPromise !== void 0 ? apiPromise : (apiPromise = (async () => {
|
|
51
|
+
try {
|
|
52
|
+
const res = await send({ ...http, retries: 0 }, `${fallbackApi}${V1}/bootstrap?org=${encodeURIComponent(options.orgKey)}`, { method: "GET", headers: { Accept: "application/json" } });
|
|
53
|
+
const b = await readJson(res);
|
|
54
|
+
if (typeof b.apiBase === "string" && b.apiBase)
|
|
55
|
+
return root(new URL(b.apiBase, desk).toString());
|
|
56
|
+
}
|
|
57
|
+
catch (_a) {
|
|
58
|
+
// an older desk without bootstrap: use the web proxy
|
|
59
|
+
}
|
|
60
|
+
return fallbackApi;
|
|
61
|
+
})());
|
|
62
|
+
return apiPromise;
|
|
63
|
+
};
|
|
64
|
+
// ---- sign-in and the token cache ---------------------------------------
|
|
65
|
+
let grant = null;
|
|
66
|
+
let inflight = null;
|
|
67
|
+
const keep = (g) => {
|
|
68
|
+
if (typeof g.token !== "string" || !g.token || g.token.length > MAX_TOKEN_LENGTH)
|
|
69
|
+
throw new ArmDeskError("bad_response", "ARM Desk returned an invalid token");
|
|
70
|
+
grant = { token: g.token, expiresAt: Date.now() + (Number.isFinite(g.expiresIn) ? g.expiresIn : DEFAULT_TOKEN_TTL_S) * 1000 };
|
|
71
|
+
return g.token;
|
|
72
|
+
};
|
|
73
|
+
const exchange = async () => {
|
|
74
|
+
var _a, _b, _c, _d;
|
|
75
|
+
const api = await apiBase();
|
|
76
|
+
if ("userToken" in auth) {
|
|
77
|
+
const assertion = await auth.userToken();
|
|
78
|
+
if (typeof assertion !== "string" || !assertion)
|
|
79
|
+
throw new ArmDeskError("config", "userToken() must return the signed user token");
|
|
80
|
+
const form = new URLSearchParams({ grant_type: JWT_BEARER_GRANT, assertion });
|
|
81
|
+
const res = await send(http, `${api}${V1}/oauth/token`, { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded", Accept: "application/json" }, body: form.toString() });
|
|
82
|
+
const r = await readJson(res);
|
|
83
|
+
if (typeof r.access_token !== "string")
|
|
84
|
+
throw new ArmDeskError("bad_response", "ARM Desk returned no access_token", res.status);
|
|
85
|
+
return { token: r.access_token, expiresIn: (_a = r.expires_in) !== null && _a !== void 0 ? _a : DEFAULT_TOKEN_TTL_S };
|
|
86
|
+
}
|
|
87
|
+
if ("idToken" in auth) {
|
|
88
|
+
const idToken = await auth.idToken();
|
|
89
|
+
const body = { orgKey: options.orgKey, idToken };
|
|
90
|
+
if (auth.nonce)
|
|
91
|
+
body.nonce = auth.nonce;
|
|
92
|
+
const res = await send(http, `${api}${V1}/sessions/browser`, { method: "POST", headers: { "Content-Type": "application/json", Accept: "application/json" }, body: JSON.stringify(body) });
|
|
93
|
+
const r = await readJson(res);
|
|
94
|
+
return { token: r.token, expiresIn: (_b = r.expiresIn) !== null && _b !== void 0 ? _b : DEFAULT_TOKEN_TTL_S };
|
|
95
|
+
}
|
|
96
|
+
if ("getToken" in auth) {
|
|
97
|
+
return { token: await auth.getToken(), expiresIn: DEFAULT_TOKEN_TTL_S };
|
|
98
|
+
}
|
|
99
|
+
// server mode: YOUR route, created by createConnectHandler
|
|
100
|
+
const res = await send(http, (_c = auth.sessionUrl) !== null && _c !== void 0 ? _c : DEFAULT_SESSION_PATH, {
|
|
101
|
+
method: "POST",
|
|
102
|
+
headers: { [CSRF_HEADER]: "1", Accept: "application/json" },
|
|
103
|
+
credentials: "same-origin",
|
|
104
|
+
});
|
|
105
|
+
const r = await readJson(res);
|
|
106
|
+
return { token: r.token, expiresIn: (_d = r.expiresIn) !== null && _d !== void 0 ? _d : DEFAULT_TOKEN_TTL_S };
|
|
107
|
+
};
|
|
108
|
+
/** Browser OIDC mode renews with the still-valid (or just expired) token first, so the host is asked for an ID token only when that fails. */
|
|
109
|
+
const refresh = async () => {
|
|
110
|
+
var _a;
|
|
111
|
+
if (!("idToken" in auth) || !grant)
|
|
112
|
+
return null;
|
|
113
|
+
try {
|
|
114
|
+
const api = await apiBase();
|
|
115
|
+
const res = await send(http, `${api}${V1}/sessions/refresh`, { method: "POST", headers: { Authorization: `Bearer ${grant.token}`, Accept: "application/json" } });
|
|
116
|
+
const r = await readJson(res);
|
|
117
|
+
return { token: r.token, expiresIn: (_a = r.expiresIn) !== null && _a !== void 0 ? _a : DEFAULT_TOKEN_TTL_S };
|
|
118
|
+
}
|
|
119
|
+
catch (_b) {
|
|
120
|
+
return null;
|
|
121
|
+
}
|
|
122
|
+
};
|
|
123
|
+
const signIn = () => {
|
|
124
|
+
inflight !== null && inflight !== void 0 ? inflight : (inflight = (async () => {
|
|
125
|
+
var _a;
|
|
126
|
+
try {
|
|
127
|
+
const g = (_a = (await refresh())) !== null && _a !== void 0 ? _a : (await exchange());
|
|
128
|
+
return keep(g);
|
|
129
|
+
}
|
|
130
|
+
catch (err) {
|
|
131
|
+
const hadSession = grant !== null;
|
|
132
|
+
grant = null;
|
|
133
|
+
const e = err instanceof ArmDeskError ? err : new ArmDeskError("session_expired", err instanceof Error ? err.message : "Could not sign in");
|
|
134
|
+
if (hadSession)
|
|
135
|
+
emit("session.expired", { code: e.code, message: e.message, status: e.status });
|
|
136
|
+
emit("error", { code: e.code, message: e.message, status: e.status });
|
|
137
|
+
throw e;
|
|
138
|
+
}
|
|
139
|
+
finally {
|
|
140
|
+
inflight = null;
|
|
141
|
+
}
|
|
142
|
+
})());
|
|
143
|
+
return inflight;
|
|
144
|
+
};
|
|
145
|
+
const getAccessToken = async () => {
|
|
146
|
+
if (grant && grant.expiresAt - EXPIRY_MARGIN_MS > Date.now())
|
|
147
|
+
return grant.token;
|
|
148
|
+
return signIn();
|
|
149
|
+
};
|
|
150
|
+
const call = async (r, retried = false) => {
|
|
151
|
+
const token = await getAccessToken();
|
|
152
|
+
const api = await apiBase();
|
|
153
|
+
const qs = r.query ? Object.entries(r.query).filter(([, v]) => v !== undefined && v !== "") : [];
|
|
154
|
+
const url = `${api}${V1}${r.path}${qs.length ? `?${new URLSearchParams(qs.map(([k, v]) => [k, String(v)])).toString()}` : ""}`;
|
|
155
|
+
const headers = { Authorization: `Bearer ${token}`, Accept: "application/json" };
|
|
156
|
+
let body;
|
|
157
|
+
if (r.form)
|
|
158
|
+
body = r.form;
|
|
159
|
+
else if (r.json !== undefined) {
|
|
160
|
+
headers["Content-Type"] = "application/json";
|
|
161
|
+
body = JSON.stringify(r.json);
|
|
162
|
+
}
|
|
163
|
+
const res = await send(http, url, { method: r.method, headers, body });
|
|
164
|
+
if (res.status === 401 && !retried) {
|
|
165
|
+
grant = null; // the token was refused (revoked / expired early): sign in once more
|
|
166
|
+
return call(r, true);
|
|
167
|
+
}
|
|
168
|
+
try {
|
|
169
|
+
return await readJson(res);
|
|
170
|
+
}
|
|
171
|
+
catch (err) {
|
|
172
|
+
if (err instanceof ArmDeskError && !(retried && err.status === 401))
|
|
173
|
+
emit("error", { code: err.code, message: err.message, status: err.status });
|
|
174
|
+
if (err instanceof ArmDeskError && err.status === 401)
|
|
175
|
+
emit("session.expired", { code: err.code, message: err.message, status: 401 });
|
|
176
|
+
throw err;
|
|
177
|
+
}
|
|
178
|
+
};
|
|
179
|
+
const withFiles = (fields, files, fileField = "files") => {
|
|
180
|
+
var _a;
|
|
181
|
+
const clean = Object.fromEntries(Object.entries(fields).filter(([, v]) => v !== undefined && v !== ""));
|
|
182
|
+
if (!files || files.length === 0)
|
|
183
|
+
return { json: clean };
|
|
184
|
+
const form = new FormData();
|
|
185
|
+
for (const [k, v] of Object.entries(clean))
|
|
186
|
+
form.append(k, v);
|
|
187
|
+
for (const f of files)
|
|
188
|
+
form.append(fileField, f, (_a = f.name) !== null && _a !== void 0 ? _a : "file");
|
|
189
|
+
return { form };
|
|
190
|
+
};
|
|
191
|
+
const id = (v) => {
|
|
192
|
+
if (!v || typeof v !== "string")
|
|
193
|
+
throw new ArmDeskError("validation", "An id is required");
|
|
194
|
+
return encodeURIComponent(v);
|
|
195
|
+
};
|
|
196
|
+
const client = {
|
|
197
|
+
orgKey: options.orgKey,
|
|
198
|
+
desk,
|
|
199
|
+
me: () => call({ method: "GET", path: "/me" }),
|
|
200
|
+
config: () => call({ method: "GET", path: "/config", query: { locale: options.locale } }),
|
|
201
|
+
categories: async () => {
|
|
202
|
+
var _a;
|
|
203
|
+
const d = await call({ method: "GET", path: "/categories" });
|
|
204
|
+
return Array.isArray(d) ? d : (_a = d.items) !== null && _a !== void 0 ? _a : [];
|
|
205
|
+
},
|
|
206
|
+
tickets: {
|
|
207
|
+
list: (p = {}) => call({
|
|
208
|
+
method: "GET",
|
|
209
|
+
path: "/tickets",
|
|
210
|
+
query: { status: Array.isArray(p.status) ? p.status.join(",") : p.status, search: p.search, page: p.page, limit: p.limit },
|
|
211
|
+
}),
|
|
212
|
+
get: async (tid) => call({ method: "GET", path: `/tickets/${id(tid)}` }),
|
|
213
|
+
async create(input) {
|
|
214
|
+
const t = await call({
|
|
215
|
+
method: "POST",
|
|
216
|
+
path: "/tickets",
|
|
217
|
+
...withFiles({ subject: input.subject, description: input.description, priority: input.priority, categoryId: input.categoryId }, input.files),
|
|
218
|
+
});
|
|
219
|
+
emit("ticket.created", t);
|
|
220
|
+
return t;
|
|
221
|
+
},
|
|
222
|
+
async reply(tid, input) {
|
|
223
|
+
const reply = await call({ method: "POST", path: `/tickets/${id(tid)}/replies`, ...withFiles({ body: input.body }, input.files) });
|
|
224
|
+
emit("ticket.replied", { ticketId: tid, reply });
|
|
225
|
+
return reply;
|
|
226
|
+
},
|
|
227
|
+
close: async (tid) => call({ method: "POST", path: `/tickets/${id(tid)}/close` }),
|
|
228
|
+
},
|
|
229
|
+
catalog: {
|
|
230
|
+
list: (p = {}) => call({ method: "GET", path: "/catalog", query: { search: p.search, categoryId: p.categoryId } }),
|
|
231
|
+
async request(itemId, answers = {}, o = {}) {
|
|
232
|
+
var _a;
|
|
233
|
+
const fields = { answers: JSON.stringify(answers), quantity: o.quantity === undefined ? undefined : String(o.quantity), requestedForId: o.requestedForId };
|
|
234
|
+
const files = o.files ? Object.entries(o.files) : [];
|
|
235
|
+
if (files.length === 0) {
|
|
236
|
+
const json = { answers };
|
|
237
|
+
if (o.quantity !== undefined)
|
|
238
|
+
json.quantity = o.quantity;
|
|
239
|
+
if (o.requestedForId)
|
|
240
|
+
json.requestedForId = o.requestedForId;
|
|
241
|
+
return call({ method: "POST", path: `/catalog/${id(itemId)}/requests`, json });
|
|
242
|
+
}
|
|
243
|
+
const form = new FormData();
|
|
244
|
+
for (const [k, v] of Object.entries(fields))
|
|
245
|
+
if (v !== undefined)
|
|
246
|
+
form.append(k, v);
|
|
247
|
+
for (const [variable, f] of files)
|
|
248
|
+
form.append(`file:${variable}`, f, (_a = f.name) !== null && _a !== void 0 ? _a : "file");
|
|
249
|
+
return call({ method: "POST", path: `/catalog/${id(itemId)}/requests`, form });
|
|
250
|
+
},
|
|
251
|
+
},
|
|
252
|
+
on(event, cb) {
|
|
253
|
+
let set = listeners.get(event);
|
|
254
|
+
if (!set)
|
|
255
|
+
listeners.set(event, (set = new Set()));
|
|
256
|
+
set.add(cb);
|
|
257
|
+
return () => set.delete(cb);
|
|
258
|
+
},
|
|
259
|
+
mount(el, o = {}) {
|
|
260
|
+
var _a, _b, _c;
|
|
261
|
+
return mount(el, {
|
|
262
|
+
baseUrl: desk,
|
|
263
|
+
orgKey: options.orgKey,
|
|
264
|
+
getToken: getAccessToken,
|
|
265
|
+
view: o.view,
|
|
266
|
+
theme: (_a = o.theme) !== null && _a !== void 0 ? _a : options.theme,
|
|
267
|
+
features: (_b = o.features) !== null && _b !== void 0 ? _b : options.features,
|
|
268
|
+
locale: (_c = o.locale) !== null && _c !== void 0 ? _c : options.locale,
|
|
269
|
+
height: o.height,
|
|
270
|
+
onEvent: (e) => {
|
|
271
|
+
var _a;
|
|
272
|
+
if (e.name === "ticket.created")
|
|
273
|
+
emit("ticket.created", e.data);
|
|
274
|
+
if (e.name === "ticket.replied")
|
|
275
|
+
emit("ticket.replied", e.data);
|
|
276
|
+
(_a = o.onEvent) === null || _a === void 0 ? void 0 : _a.call(o, e);
|
|
277
|
+
},
|
|
278
|
+
onError: (e) => {
|
|
279
|
+
var _a;
|
|
280
|
+
emit("error", e);
|
|
281
|
+
(_a = o.onError) === null || _a === void 0 ? void 0 : _a.call(o, e);
|
|
282
|
+
},
|
|
283
|
+
});
|
|
284
|
+
},
|
|
285
|
+
getAccessToken,
|
|
286
|
+
signOut() {
|
|
287
|
+
grant = null;
|
|
288
|
+
inflight = null;
|
|
289
|
+
},
|
|
290
|
+
};
|
|
291
|
+
return client;
|
|
292
|
+
}
|
|
293
|
+
/** `ArmDeskConnect.init(...)`: createClient, and make it the client the web components use. */
|
|
294
|
+
export function init(options) {
|
|
295
|
+
const client = createClient(options);
|
|
296
|
+
setCurrentClient(client);
|
|
297
|
+
return client;
|
|
298
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type { ArmDeskClient } from "./client.js";
|
|
2
|
+
/** The IIFE build records the origin its script tag was loaded from, so only `orgKey` is needed. */
|
|
3
|
+
export declare function setDefaultDesk(origin: string | undefined): void;
|
|
4
|
+
export declare function getDefaultDesk(): string | undefined;
|
|
5
|
+
/** The client the web components use when they are not given one (the last `init()`). */
|
|
6
|
+
export declare function setCurrentClient(client: ArmDeskClient | null): void;
|
|
7
|
+
export declare function getCurrentClient(): ArmDeskClient | null;
|
|
8
|
+
export declare function onCurrentClient(cb: (c: ArmDeskClient | null) => void): () => void;
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
let defaultDesk;
|
|
2
|
+
let current = null;
|
|
3
|
+
const listeners = new Set();
|
|
4
|
+
/** The IIFE build records the origin its script tag was loaded from, so only `orgKey` is needed. */
|
|
5
|
+
export function setDefaultDesk(origin) {
|
|
6
|
+
defaultDesk = origin;
|
|
7
|
+
}
|
|
8
|
+
export function getDefaultDesk() {
|
|
9
|
+
return defaultDesk;
|
|
10
|
+
}
|
|
11
|
+
/** The client the web components use when they are not given one (the last `init()`). */
|
|
12
|
+
export function setCurrentClient(client) {
|
|
13
|
+
current = client;
|
|
14
|
+
listeners.forEach((l) => l(client));
|
|
15
|
+
}
|
|
16
|
+
export function getCurrentClient() {
|
|
17
|
+
return current;
|
|
18
|
+
}
|
|
19
|
+
export function onCurrentClient(cb) {
|
|
20
|
+
listeners.add(cb);
|
|
21
|
+
return () => listeners.delete(cb);
|
|
22
|
+
}
|
|
@@ -0,0 +1,307 @@
|
|
|
1
|
+
import { getCurrentClient, onCurrentClient } from "./defaults.js";
|
|
2
|
+
import { setSafeHtml } from "./sanitize.js";
|
|
3
|
+
import { themeCss } from "./theme.js";
|
|
4
|
+
function h(tag, attrs = {}, ...kids) {
|
|
5
|
+
const el = document.createElement(tag);
|
|
6
|
+
for (const [k, v] of Object.entries(attrs)) {
|
|
7
|
+
if (v === undefined || v === false)
|
|
8
|
+
continue;
|
|
9
|
+
if (typeof v === "function")
|
|
10
|
+
el.addEventListener(k.replace(/^on/, ""), v);
|
|
11
|
+
else if (v === true)
|
|
12
|
+
el.setAttribute(k, "");
|
|
13
|
+
else
|
|
14
|
+
el.setAttribute(k, v);
|
|
15
|
+
}
|
|
16
|
+
for (const kid of kids)
|
|
17
|
+
if (kid)
|
|
18
|
+
el.append(kid);
|
|
19
|
+
return el;
|
|
20
|
+
}
|
|
21
|
+
const CSS = `
|
|
22
|
+
*{box-sizing:border-box}
|
|
23
|
+
.ad{font-family:var(--ad-font);color:var(--ad-text);background:var(--ad-bg);font-size:14px;line-height:1.45}
|
|
24
|
+
.ad h3{margin:0 0 8px;font-size:16px}
|
|
25
|
+
.card{background:var(--ad-surface);border:1px solid var(--ad-border);border-radius:var(--ad-radius);padding:var(--ad-pad);margin:0 0 8px}
|
|
26
|
+
.row{display:flex;gap:8px;align-items:center;justify-content:space-between;width:100%;text-align:left;font:inherit;color:inherit;cursor:pointer}
|
|
27
|
+
.muted{color:var(--ad-muted);font-size:12px}
|
|
28
|
+
.badge{border:1px solid var(--ad-border);border-radius:999px;padding:0 8px;font-size:12px;color:var(--ad-muted);white-space:nowrap}
|
|
29
|
+
button,input,select,textarea{font:inherit;color:inherit}
|
|
30
|
+
input,select,textarea{width:100%;background:var(--ad-bg);border:1px solid var(--ad-border);border-radius:var(--ad-radius);padding:var(--ad-pad)}
|
|
31
|
+
.btn{background:var(--ad-primary);color:#fff;border:0;border-radius:var(--ad-radius);padding:var(--ad-pad);cursor:pointer}
|
|
32
|
+
.btn.ghost{background:transparent;color:var(--ad-primary);border:1px solid var(--ad-border)}
|
|
33
|
+
.btn[disabled]{opacity:.6;cursor:default}
|
|
34
|
+
label{display:block;margin:0 0 10px}
|
|
35
|
+
.err{color:#b91c1c}
|
|
36
|
+
.agent{border-left:3px solid var(--ad-primary)}
|
|
37
|
+
.body a{color:var(--ad-primary)}.body pre{white-space:pre-wrap;overflow:auto}
|
|
38
|
+
.bar{display:flex;gap:8px;justify-content:space-between;align-items:center}
|
|
39
|
+
.fab{position:fixed;bottom:20px;z-index:2147483000}
|
|
40
|
+
.fab.right{right:20px}.fab.left{left:20px}
|
|
41
|
+
.panel{position:fixed;bottom:76px;width:min(400px,calc(100vw - 24px));height:min(640px,calc(100vh - 100px));background:var(--ad-bg);border:1px solid var(--ad-border);border-radius:var(--ad-radius);overflow:hidden;z-index:2147483000;box-shadow:0 8px 30px rgba(0,0,0,.25)}
|
|
42
|
+
.panel.right{right:20px}.panel.left{left:20px}
|
|
43
|
+
`;
|
|
44
|
+
export const ELEMENT_TAGS = ["armdesk-tickets", "armdesk-new-ticket", "armdesk-ticket", "armdesk-launcher"];
|
|
45
|
+
function readTheme(attr) {
|
|
46
|
+
if (!attr)
|
|
47
|
+
return undefined;
|
|
48
|
+
try {
|
|
49
|
+
const v = JSON.parse(attr);
|
|
50
|
+
return v && typeof v === "object" ? v : undefined;
|
|
51
|
+
}
|
|
52
|
+
catch (_a) {
|
|
53
|
+
return undefined;
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
/** Registers the four custom elements (idempotent; a no-op without a browser). */
|
|
57
|
+
export function defineElements() {
|
|
58
|
+
if (typeof customElements === "undefined" || typeof HTMLElement === "undefined")
|
|
59
|
+
return;
|
|
60
|
+
class ArmBase extends HTMLElement {
|
|
61
|
+
constructor() {
|
|
62
|
+
super(...arguments);
|
|
63
|
+
/** Set to use a specific client; otherwise the one from the last `ArmDeskConnect.init()`. */
|
|
64
|
+
this.client = null;
|
|
65
|
+
this.unsub = null;
|
|
66
|
+
this.bound = null;
|
|
67
|
+
this.offEvents = [];
|
|
68
|
+
}
|
|
69
|
+
static get observedAttributes() {
|
|
70
|
+
return ["theme", "ticket-id", "status", "limit", "view", "label", "position"];
|
|
71
|
+
}
|
|
72
|
+
get c() {
|
|
73
|
+
var _a;
|
|
74
|
+
return (_a = this.client) !== null && _a !== void 0 ? _a : getCurrentClient();
|
|
75
|
+
}
|
|
76
|
+
connectedCallback() {
|
|
77
|
+
if (!this.root) {
|
|
78
|
+
this.root = this.attachShadow({ mode: "open" });
|
|
79
|
+
this.styleEl = document.createElement("style");
|
|
80
|
+
this.box = h("div", { class: "ad", part: "root" });
|
|
81
|
+
this.root.append(this.styleEl, this.box);
|
|
82
|
+
}
|
|
83
|
+
this.paintTheme();
|
|
84
|
+
this.unsub = onCurrentClient(() => this.start());
|
|
85
|
+
this.start();
|
|
86
|
+
}
|
|
87
|
+
disconnectedCallback() {
|
|
88
|
+
var _a;
|
|
89
|
+
(_a = this.unsub) === null || _a === void 0 ? void 0 : _a.call(this);
|
|
90
|
+
this.unsub = null;
|
|
91
|
+
this.offEvents.forEach((f) => f());
|
|
92
|
+
this.offEvents = [];
|
|
93
|
+
this.bound = null;
|
|
94
|
+
this.teardown();
|
|
95
|
+
}
|
|
96
|
+
attributeChangedCallback() {
|
|
97
|
+
if (!this.isConnected || !this.root)
|
|
98
|
+
return;
|
|
99
|
+
this.paintTheme();
|
|
100
|
+
void this.load();
|
|
101
|
+
}
|
|
102
|
+
/** The theme in effect: the organisation's, then the `theme` attribute (JSON) on top. */
|
|
103
|
+
paintTheme() {
|
|
104
|
+
const theme = { ...this.cfgTheme, ...readTheme(this.getAttribute("theme")) };
|
|
105
|
+
this.styleEl.textContent = themeCss(theme) + CSS;
|
|
106
|
+
}
|
|
107
|
+
start() {
|
|
108
|
+
const c = this.c;
|
|
109
|
+
if (!c) {
|
|
110
|
+
this.box.replaceChildren(h("p", { class: "muted" }, "ARM Desk is not initialised yet."));
|
|
111
|
+
return;
|
|
112
|
+
}
|
|
113
|
+
if (c !== this.bound) {
|
|
114
|
+
this.offEvents.forEach((f) => f());
|
|
115
|
+
this.offEvents = this.watch(c);
|
|
116
|
+
this.bound = c;
|
|
117
|
+
void c.config().then((cfg) => {
|
|
118
|
+
this.cfgTheme = cfg.theme;
|
|
119
|
+
this.paintTheme();
|
|
120
|
+
}, () => undefined);
|
|
121
|
+
}
|
|
122
|
+
void this.load();
|
|
123
|
+
}
|
|
124
|
+
watch(_c) {
|
|
125
|
+
return [];
|
|
126
|
+
}
|
|
127
|
+
async load() { }
|
|
128
|
+
teardown() { }
|
|
129
|
+
fail(err, retry) {
|
|
130
|
+
this.box.replaceChildren(h("p", { class: "err", role: "alert" }, err instanceof Error ? err.message : "Something went wrong."), h("button", { class: "btn ghost", onclick: retry }, "Try again"));
|
|
131
|
+
}
|
|
132
|
+
emit(name, detail) {
|
|
133
|
+
this.dispatchEvent(new CustomEvent(name, { detail, bubbles: true, composed: true }));
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
const when = (iso) => (iso ? new Date(iso).toLocaleString() : "");
|
|
137
|
+
class ArmTickets extends ArmBase {
|
|
138
|
+
constructor() {
|
|
139
|
+
super(...arguments);
|
|
140
|
+
this.page = 1;
|
|
141
|
+
}
|
|
142
|
+
watch(c) {
|
|
143
|
+
return [c.on("ticket.created", () => void this.load()), c.on("ticket.replied", () => void this.load())];
|
|
144
|
+
}
|
|
145
|
+
async load() {
|
|
146
|
+
const c = this.c;
|
|
147
|
+
if (!c)
|
|
148
|
+
return;
|
|
149
|
+
const limit = Math.min(100, Math.max(1, Number(this.getAttribute("limit")) || 10));
|
|
150
|
+
this.box.replaceChildren(h("p", { class: "muted" }, "Loading..."));
|
|
151
|
+
try {
|
|
152
|
+
const res = await c.tickets.list({ status: this.getAttribute("status") || undefined, page: this.page, limit });
|
|
153
|
+
this.draw(res, limit);
|
|
154
|
+
}
|
|
155
|
+
catch (e) {
|
|
156
|
+
this.fail(e, () => void this.load());
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
draw(res, limit) {
|
|
160
|
+
const pages = Math.max(1, Math.ceil(res.total / limit));
|
|
161
|
+
const items = res.items.map((t) => {
|
|
162
|
+
var _a;
|
|
163
|
+
return h("div", { class: "card" }, h("button", { class: "row", style: "background:none;border:0;padding:0", onclick: () => this.emit("armdesk-ticket-select", { id: t.id, number: t.number }) }, h("span", {}, h("strong", {}, t.number), " ", t.subject, h("div", { class: "muted" }, when((_a = t.lastReplyAt) !== null && _a !== void 0 ? _a : t.updatedAt))), h("span", { class: "badge" }, t.status.replace(/_/g, " "))));
|
|
164
|
+
});
|
|
165
|
+
this.box.replaceChildren(h("h3", {}, "My tickets"), ...(items.length ? items : [h("p", { class: "muted" }, "No tickets yet.")]), h("div", { class: "bar" }, h("button", { class: "btn ghost", disabled: this.page <= 1, onclick: () => { this.page--; void this.load(); } }, "Previous"), h("span", { class: "muted" }, `${this.page} / ${pages}`), h("button", { class: "btn ghost", disabled: this.page >= pages, onclick: () => { this.page++; void this.load(); } }, "Next")));
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
class ArmNewTicket extends ArmBase {
|
|
169
|
+
async load() {
|
|
170
|
+
var _a, _b;
|
|
171
|
+
const c = this.c;
|
|
172
|
+
if (!c)
|
|
173
|
+
return;
|
|
174
|
+
let cats = [];
|
|
175
|
+
let attachments = true;
|
|
176
|
+
let newTicket = true;
|
|
177
|
+
try {
|
|
178
|
+
const cfg = await c.config();
|
|
179
|
+
attachments = ((_a = cfg.features) === null || _a === void 0 ? void 0 : _a.attachments) !== false;
|
|
180
|
+
newTicket = ((_b = cfg.features) === null || _b === void 0 ? void 0 : _b.newTicket) !== false;
|
|
181
|
+
cats = await c.categories();
|
|
182
|
+
}
|
|
183
|
+
catch (_d) {
|
|
184
|
+
// the form still works without categories
|
|
185
|
+
}
|
|
186
|
+
if (!newTicket) {
|
|
187
|
+
this.box.replaceChildren(h("p", { class: "muted" }, "Raising tickets is turned off."));
|
|
188
|
+
return;
|
|
189
|
+
}
|
|
190
|
+
const subject = h("input", { name: "subject", required: true, minlength: "5", maxlength: "255" });
|
|
191
|
+
const description = h("textarea", { name: "description", required: true, minlength: "10", maxlength: "20000", rows: "6" });
|
|
192
|
+
const priority = h("select", { name: "priority" }, ...["NORMAL", "LOW", "HIGH", "URGENT"].map((p) => h("option", { value: p }, p.charAt(0) + p.slice(1).toLowerCase())));
|
|
193
|
+
const category = h("select", { name: "categoryId" }, h("option", { value: "" }, "None"), ...cats.map((k) => h("option", { value: k.id }, k.name)));
|
|
194
|
+
const files = h("input", { type: "file", multiple: true });
|
|
195
|
+
const msg = h("p", { role: "status", class: "muted" });
|
|
196
|
+
const submit = h("button", { class: "btn", type: "submit" }, "Submit ticket");
|
|
197
|
+
const form = h("form", {
|
|
198
|
+
onsubmit: (e) => {
|
|
199
|
+
var _a;
|
|
200
|
+
e.preventDefault();
|
|
201
|
+
submit.disabled = true;
|
|
202
|
+
msg.className = "muted";
|
|
203
|
+
msg.textContent = "Sending...";
|
|
204
|
+
c.tickets
|
|
205
|
+
.create({ subject: subject.value, description: description.value, priority: priority.value, categoryId: category.value || undefined, files: Array.from((_a = files.files) !== null && _a !== void 0 ? _a : []) })
|
|
206
|
+
.then((t) => {
|
|
207
|
+
msg.textContent = `Ticket ${t.number} created.`;
|
|
208
|
+
form.reset();
|
|
209
|
+
this.emit("armdesk-ticket-created", t);
|
|
210
|
+
})
|
|
211
|
+
.catch((err) => {
|
|
212
|
+
msg.className = "err";
|
|
213
|
+
msg.textContent = err instanceof Error ? err.message : "Could not create the ticket.";
|
|
214
|
+
})
|
|
215
|
+
.finally(() => (submit.disabled = false));
|
|
216
|
+
},
|
|
217
|
+
}, h("label", {}, "Subject", subject), h("label", {}, "Description", description), h("label", {}, "Priority", priority), cats.length ? h("label", {}, "Category", category) : null, attachments ? h("label", {}, "Attachments", files) : null, submit, msg);
|
|
218
|
+
this.box.replaceChildren(h("h3", {}, "New ticket"), form);
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
class ArmTicket extends ArmBase {
|
|
222
|
+
watch(c) {
|
|
223
|
+
return [c.on("ticket.replied", (p) => p.ticketId === this.getAttribute("ticket-id") && void this.load())];
|
|
224
|
+
}
|
|
225
|
+
async load() {
|
|
226
|
+
const c = this.c;
|
|
227
|
+
const id = this.getAttribute("ticket-id");
|
|
228
|
+
if (!c)
|
|
229
|
+
return;
|
|
230
|
+
if (!id) {
|
|
231
|
+
this.box.replaceChildren(h("p", { class: "muted" }, "Set the ticket-id attribute."));
|
|
232
|
+
return;
|
|
233
|
+
}
|
|
234
|
+
try {
|
|
235
|
+
this.draw(c, await c.tickets.get(id));
|
|
236
|
+
}
|
|
237
|
+
catch (e) {
|
|
238
|
+
this.fail(e, () => void this.load());
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
draw(c, t) {
|
|
242
|
+
const threads = t.threads.map((th) => {
|
|
243
|
+
var _a;
|
|
244
|
+
const body = h("div", { class: "body" });
|
|
245
|
+
setSafeHtml(body, th.body);
|
|
246
|
+
const files = ((_a = th.attachments) !== null && _a !== void 0 ? _a : []).filter((a) => a.url && /^(https?:\/|\/)/.test(a.url)).map((a) => h("a", { href: a.url, target: "_blank", rel: "noopener noreferrer" }, a.name));
|
|
247
|
+
return h("div", { class: `card${th.author.isAgent ? " agent" : ""}` }, h("div", { class: "muted" }, `${th.author.name} - ${when(th.createdAt)}`), body, ...(files.length ? [h("div", { class: "muted" }, "Files: ", ...files.flatMap((f) => [f, " "]))] : []));
|
|
248
|
+
});
|
|
249
|
+
const reply = h("textarea", { rows: "4", required: true, minlength: "1", "aria-label": "Reply" });
|
|
250
|
+
const msg = h("p", { role: "status", class: "err" });
|
|
251
|
+
const send = h("button", { class: "btn", type: "submit" }, "Send reply");
|
|
252
|
+
const form = h("form", {
|
|
253
|
+
onsubmit: (e) => {
|
|
254
|
+
e.preventDefault();
|
|
255
|
+
send.disabled = true;
|
|
256
|
+
c.tickets.reply(t.id, { body: reply.value }).then(() => this.emit("armdesk-ticket-replied", { id: t.id }), (err) => {
|
|
257
|
+
msg.textContent = err instanceof Error ? err.message : "Could not send the reply.";
|
|
258
|
+
send.disabled = false;
|
|
259
|
+
});
|
|
260
|
+
},
|
|
261
|
+
}, reply, send, msg);
|
|
262
|
+
const close = t.canClose ? h("button", { class: "btn ghost", onclick: () => void c.tickets.close(t.id).then(() => this.load(), (e) => this.fail(e, () => void this.load())) }, "Mark as solved") : null;
|
|
263
|
+
this.box.replaceChildren(h("div", { class: "bar" }, h("h3", {}, `${t.number} ${t.subject}`), h("span", { class: "badge" }, t.status.replace(/_/g, " "))), ...threads, ...[t.canReply ? form : null, close].filter((n) => n !== null));
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
class ArmLauncher extends ArmBase {
|
|
267
|
+
constructor() {
|
|
268
|
+
super(...arguments);
|
|
269
|
+
this.handle = null;
|
|
270
|
+
this.open = false;
|
|
271
|
+
}
|
|
272
|
+
teardown() {
|
|
273
|
+
var _a;
|
|
274
|
+
(_a = this.handle) === null || _a === void 0 ? void 0 : _a.destroy();
|
|
275
|
+
this.handle = null;
|
|
276
|
+
}
|
|
277
|
+
async load() {
|
|
278
|
+
const side = this.getAttribute("position") === "left" ? "left" : "right";
|
|
279
|
+
const panel = h("div", { class: `panel ${side}`, role: "dialog", "aria-label": this.getAttribute("label") || "Support", hidden: true });
|
|
280
|
+
const btn = h("button", {
|
|
281
|
+
class: `btn fab ${side}`,
|
|
282
|
+
"aria-expanded": "false",
|
|
283
|
+
onclick: () => {
|
|
284
|
+
this.open = !this.open;
|
|
285
|
+
panel.hidden = !this.open;
|
|
286
|
+
btn.setAttribute("aria-expanded", String(this.open));
|
|
287
|
+
const c = this.c;
|
|
288
|
+
if (this.open && !this.handle && c) {
|
|
289
|
+
const view = (this.getAttribute("view") || "tickets");
|
|
290
|
+
this.handle = c.mount(panel, { view, theme: readTheme(this.getAttribute("theme")), height: 640 });
|
|
291
|
+
}
|
|
292
|
+
},
|
|
293
|
+
}, this.getAttribute("label") || "Support");
|
|
294
|
+
this.teardown();
|
|
295
|
+
this.box.replaceChildren(btn, panel);
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
const defs = [
|
|
299
|
+
["armdesk-tickets", ArmTickets],
|
|
300
|
+
["armdesk-new-ticket", ArmNewTicket],
|
|
301
|
+
["armdesk-ticket", ArmTicket],
|
|
302
|
+
["armdesk-launcher", ArmLauncher],
|
|
303
|
+
];
|
|
304
|
+
for (const [name, ctor] of defs)
|
|
305
|
+
if (!customElements.get(name))
|
|
306
|
+
customElements.define(name, ctor);
|
|
307
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/** Every failure of the headless client. `status` is the HTTP status (0 when none). */
|
|
2
|
+
export type ArmDeskErrorCode = "unauthorized" | "forbidden" | "not_found" | "conflict" | "validation" | "rate_limited" | "server" | "network" | "bad_response" | "session_expired" | "config" | (string & {});
|
|
3
|
+
export declare class ArmDeskError extends Error {
|
|
4
|
+
readonly code: ArmDeskErrorCode;
|
|
5
|
+
readonly status: number;
|
|
6
|
+
/** Seconds the desk asked us to wait (Retry-After), when it did. */
|
|
7
|
+
readonly retryAfter?: number;
|
|
8
|
+
constructor(code: ArmDeskErrorCode, message: string, status?: number, retryAfter?: number);
|
|
9
|
+
}
|
|
10
|
+
export declare function codeForStatus(status: number): ArmDeskErrorCode;
|
|
11
|
+
/** Builds the typed error for a non-2xx answer (Nest `{message}` or RFC 6749 `{error, error_description}`). */
|
|
12
|
+
export declare function errorFromBody(status: number, body: unknown, retryAfter?: number): ArmDeskError;
|