@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,368 @@
|
|
|
1
|
+
import { getCurrentClient, onCurrentClient } from "./defaults.js";
|
|
2
|
+
import { isView } from "./protocol.js";
|
|
3
|
+
import { setSafeHtml } from "./sanitize.js";
|
|
4
|
+
import { themeCss } from "./theme.js";
|
|
5
|
+
function h(tag, attrs = {}, ...kids) {
|
|
6
|
+
const el = document.createElement(tag);
|
|
7
|
+
for (const [k, v] of Object.entries(attrs)) {
|
|
8
|
+
if (v === undefined || v === false)
|
|
9
|
+
continue;
|
|
10
|
+
if (typeof v === "function")
|
|
11
|
+
el.addEventListener(k.replace(/^on/, ""), v);
|
|
12
|
+
else if (v === true)
|
|
13
|
+
el.setAttribute(k, "");
|
|
14
|
+
else
|
|
15
|
+
el.setAttribute(k, v);
|
|
16
|
+
}
|
|
17
|
+
for (const kid of kids)
|
|
18
|
+
if (kid)
|
|
19
|
+
el.append(kid);
|
|
20
|
+
return el;
|
|
21
|
+
}
|
|
22
|
+
const CSS = `
|
|
23
|
+
*{box-sizing:border-box}
|
|
24
|
+
.ad{font-family:var(--ad-font);color:var(--ad-text);background:var(--ad-bg);font-size:14px;line-height:1.45}
|
|
25
|
+
.ad h3{margin:0 0 8px;font-size:16px}
|
|
26
|
+
.card{background:var(--ad-surface);border:1px solid var(--ad-border);border-radius:var(--ad-radius);padding:var(--ad-pad);margin:0 0 8px}
|
|
27
|
+
.row{display:flex;gap:8px;align-items:center;justify-content:space-between;width:100%;text-align:left;font:inherit;color:inherit;cursor:pointer}
|
|
28
|
+
.muted{color:var(--ad-muted);font-size:12px}
|
|
29
|
+
.badge{border:1px solid var(--ad-border);border-radius:999px;padding:0 8px;font-size:12px;color:var(--ad-muted);white-space:nowrap}
|
|
30
|
+
button,input,select,textarea{font:inherit;color:inherit}
|
|
31
|
+
input,select,textarea{width:100%;background:var(--ad-bg);border:1px solid var(--ad-border);border-radius:var(--ad-radius);padding:var(--ad-pad)}
|
|
32
|
+
.btn{background:var(--ad-primary);color:#fff;border:0;border-radius:var(--ad-radius);padding:var(--ad-pad);cursor:pointer}
|
|
33
|
+
.btn.ghost{background:transparent;color:var(--ad-primary);border:1px solid var(--ad-border)}
|
|
34
|
+
.btn[disabled]{opacity:.6;cursor:default}
|
|
35
|
+
label{display:block;margin:0 0 10px}
|
|
36
|
+
.err{color:#b91c1c}
|
|
37
|
+
.agent{border-left:3px solid var(--ad-primary)}
|
|
38
|
+
.body a{color:var(--ad-primary)}.body pre{white-space:pre-wrap;overflow:auto}
|
|
39
|
+
.bar{display:flex;gap:8px;justify-content:space-between;align-items:center}
|
|
40
|
+
`;
|
|
41
|
+
export const ELEMENT_TAGS = ["armdesk-tickets", "armdesk-new-ticket", "armdesk-ticket", "armdesk-launcher", "armdesk-messenger"];
|
|
42
|
+
function readTheme(attr) {
|
|
43
|
+
if (!attr)
|
|
44
|
+
return undefined;
|
|
45
|
+
try {
|
|
46
|
+
const v = JSON.parse(attr);
|
|
47
|
+
return v && typeof v === "object" ? v : undefined;
|
|
48
|
+
}
|
|
49
|
+
catch (_a) {
|
|
50
|
+
return undefined;
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
/** Registers the custom elements (idempotent; a no-op without a browser). */
|
|
54
|
+
export function defineElements() {
|
|
55
|
+
if (typeof customElements === "undefined" || typeof HTMLElement === "undefined")
|
|
56
|
+
return;
|
|
57
|
+
class ArmBase extends HTMLElement {
|
|
58
|
+
constructor() {
|
|
59
|
+
super(...arguments);
|
|
60
|
+
/** Set to use a specific client; otherwise the one from the last `ArmDeskConnect.init()`. */
|
|
61
|
+
this.client = null;
|
|
62
|
+
this.unsub = null;
|
|
63
|
+
this.bound = null;
|
|
64
|
+
this.offEvents = [];
|
|
65
|
+
}
|
|
66
|
+
static get observedAttributes() {
|
|
67
|
+
return ["theme", "ticket-id", "status", "limit", "view", "label", "position"];
|
|
68
|
+
}
|
|
69
|
+
get c() {
|
|
70
|
+
var _a;
|
|
71
|
+
return (_a = this.client) !== null && _a !== void 0 ? _a : getCurrentClient();
|
|
72
|
+
}
|
|
73
|
+
connectedCallback() {
|
|
74
|
+
if (!this.root) {
|
|
75
|
+
this.root = this.attachShadow({ mode: "open" });
|
|
76
|
+
this.styleEl = document.createElement("style");
|
|
77
|
+
this.box = h("div", { class: "ad", part: "root" });
|
|
78
|
+
this.root.append(this.styleEl, this.box);
|
|
79
|
+
}
|
|
80
|
+
this.paintTheme();
|
|
81
|
+
this.unsub = onCurrentClient(() => this.start());
|
|
82
|
+
this.start();
|
|
83
|
+
}
|
|
84
|
+
disconnectedCallback() {
|
|
85
|
+
var _a;
|
|
86
|
+
(_a = this.unsub) === null || _a === void 0 ? void 0 : _a.call(this);
|
|
87
|
+
this.unsub = null;
|
|
88
|
+
this.offEvents.forEach((f) => f());
|
|
89
|
+
this.offEvents = [];
|
|
90
|
+
this.bound = null;
|
|
91
|
+
this.teardown();
|
|
92
|
+
}
|
|
93
|
+
attributeChangedCallback(_name) {
|
|
94
|
+
if (!this.isConnected || !this.root)
|
|
95
|
+
return;
|
|
96
|
+
this.paintTheme();
|
|
97
|
+
void this.load();
|
|
98
|
+
}
|
|
99
|
+
/** The theme in effect: the organisation's, then the `theme` attribute (JSON) on top. */
|
|
100
|
+
paintTheme() {
|
|
101
|
+
const theme = { ...this.cfgTheme, ...readTheme(this.getAttribute("theme")) };
|
|
102
|
+
this.styleEl.textContent = themeCss(theme) + CSS;
|
|
103
|
+
}
|
|
104
|
+
start() {
|
|
105
|
+
const c = this.c;
|
|
106
|
+
if (!c) {
|
|
107
|
+
this.box.replaceChildren(h("p", { class: "muted" }, "ARM Desk is not initialised yet."));
|
|
108
|
+
return;
|
|
109
|
+
}
|
|
110
|
+
if (c !== this.bound) {
|
|
111
|
+
this.offEvents.forEach((f) => f());
|
|
112
|
+
this.offEvents = this.watch(c);
|
|
113
|
+
this.bound = c;
|
|
114
|
+
void c.config().then((cfg) => {
|
|
115
|
+
this.cfgTheme = cfg.theme;
|
|
116
|
+
this.paintTheme();
|
|
117
|
+
}, () => undefined);
|
|
118
|
+
}
|
|
119
|
+
void this.load();
|
|
120
|
+
}
|
|
121
|
+
watch(_c) {
|
|
122
|
+
return [];
|
|
123
|
+
}
|
|
124
|
+
async load() { }
|
|
125
|
+
teardown() { }
|
|
126
|
+
fail(err, retry) {
|
|
127
|
+
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"));
|
|
128
|
+
}
|
|
129
|
+
emit(name, detail) {
|
|
130
|
+
this.dispatchEvent(new CustomEvent(name, { detail, bubbles: true, composed: true }));
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
const when = (iso) => (iso ? new Date(iso).toLocaleString() : "");
|
|
134
|
+
class ArmTickets extends ArmBase {
|
|
135
|
+
constructor() {
|
|
136
|
+
super(...arguments);
|
|
137
|
+
this.page = 1;
|
|
138
|
+
}
|
|
139
|
+
watch(c) {
|
|
140
|
+
return [c.on("ticket.created", () => void this.load()), c.on("ticket.replied", () => void this.load())];
|
|
141
|
+
}
|
|
142
|
+
async load() {
|
|
143
|
+
const c = this.c;
|
|
144
|
+
if (!c)
|
|
145
|
+
return;
|
|
146
|
+
const limit = Math.min(100, Math.max(1, Number(this.getAttribute("limit")) || 10));
|
|
147
|
+
this.box.replaceChildren(h("p", { class: "muted" }, "Loading..."));
|
|
148
|
+
try {
|
|
149
|
+
const res = await c.tickets.list({ status: this.getAttribute("status") || undefined, page: this.page, limit });
|
|
150
|
+
this.draw(res, limit);
|
|
151
|
+
}
|
|
152
|
+
catch (e) {
|
|
153
|
+
this.fail(e, () => void this.load());
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
draw(res, limit) {
|
|
157
|
+
const pages = Math.max(1, Math.ceil(res.total / limit));
|
|
158
|
+
const items = res.items.map((t) => {
|
|
159
|
+
var _a;
|
|
160
|
+
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, " "))));
|
|
161
|
+
});
|
|
162
|
+
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")));
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
class ArmNewTicket extends ArmBase {
|
|
166
|
+
async load() {
|
|
167
|
+
var _a, _b;
|
|
168
|
+
const c = this.c;
|
|
169
|
+
if (!c)
|
|
170
|
+
return;
|
|
171
|
+
let cats = [];
|
|
172
|
+
let attachments = true;
|
|
173
|
+
let newTicket = true;
|
|
174
|
+
try {
|
|
175
|
+
const cfg = await c.config();
|
|
176
|
+
attachments = ((_a = cfg.features) === null || _a === void 0 ? void 0 : _a.attachments) !== false;
|
|
177
|
+
newTicket = ((_b = cfg.features) === null || _b === void 0 ? void 0 : _b.newTicket) !== false;
|
|
178
|
+
cats = await c.categories();
|
|
179
|
+
}
|
|
180
|
+
catch (_d) {
|
|
181
|
+
// the form still works without categories
|
|
182
|
+
}
|
|
183
|
+
if (!newTicket) {
|
|
184
|
+
this.box.replaceChildren(h("p", { class: "muted" }, "Raising tickets is turned off."));
|
|
185
|
+
return;
|
|
186
|
+
}
|
|
187
|
+
const subject = h("input", { name: "subject", required: true, minlength: "5", maxlength: "255" });
|
|
188
|
+
const description = h("textarea", { name: "description", required: true, minlength: "10", maxlength: "20000", rows: "6" });
|
|
189
|
+
const priority = h("select", { name: "priority" }, ...["NORMAL", "LOW", "HIGH", "URGENT"].map((p) => h("option", { value: p }, p.charAt(0) + p.slice(1).toLowerCase())));
|
|
190
|
+
const category = h("select", { name: "categoryId" }, h("option", { value: "" }, "None"), ...cats.map((k) => h("option", { value: k.id }, k.name)));
|
|
191
|
+
const files = h("input", { type: "file", multiple: true });
|
|
192
|
+
const msg = h("p", { role: "status", class: "muted" });
|
|
193
|
+
const submit = h("button", { class: "btn", type: "submit" }, "Submit ticket");
|
|
194
|
+
const form = h("form", {
|
|
195
|
+
onsubmit: (e) => {
|
|
196
|
+
var _a;
|
|
197
|
+
e.preventDefault();
|
|
198
|
+
submit.disabled = true;
|
|
199
|
+
msg.className = "muted";
|
|
200
|
+
msg.textContent = "Sending...";
|
|
201
|
+
c.tickets
|
|
202
|
+
.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 : []) })
|
|
203
|
+
.then((t) => {
|
|
204
|
+
msg.textContent = `Ticket ${t.number} created.`;
|
|
205
|
+
form.reset();
|
|
206
|
+
this.emit("armdesk-ticket-created", t);
|
|
207
|
+
})
|
|
208
|
+
.catch((err) => {
|
|
209
|
+
msg.className = "err";
|
|
210
|
+
msg.textContent = err instanceof Error ? err.message : "Could not create the ticket.";
|
|
211
|
+
})
|
|
212
|
+
.finally(() => (submit.disabled = false));
|
|
213
|
+
},
|
|
214
|
+
}, 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);
|
|
215
|
+
this.box.replaceChildren(h("h3", {}, "New ticket"), form);
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
class ArmTicket extends ArmBase {
|
|
219
|
+
watch(c) {
|
|
220
|
+
return [c.on("ticket.replied", (p) => p.ticketId === this.getAttribute("ticket-id") && void this.load())];
|
|
221
|
+
}
|
|
222
|
+
async load() {
|
|
223
|
+
const c = this.c;
|
|
224
|
+
const id = this.getAttribute("ticket-id");
|
|
225
|
+
if (!c)
|
|
226
|
+
return;
|
|
227
|
+
if (!id) {
|
|
228
|
+
this.box.replaceChildren(h("p", { class: "muted" }, "Set the ticket-id attribute."));
|
|
229
|
+
return;
|
|
230
|
+
}
|
|
231
|
+
try {
|
|
232
|
+
this.draw(c, await c.tickets.get(id));
|
|
233
|
+
}
|
|
234
|
+
catch (e) {
|
|
235
|
+
this.fail(e, () => void this.load());
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
draw(c, t) {
|
|
239
|
+
const threads = t.threads.map((th) => {
|
|
240
|
+
var _a;
|
|
241
|
+
const body = h("div", { class: "body" });
|
|
242
|
+
setSafeHtml(body, th.body);
|
|
243
|
+
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));
|
|
244
|
+
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, " "]))] : []));
|
|
245
|
+
});
|
|
246
|
+
const reply = h("textarea", { rows: "4", required: true, minlength: "1", "aria-label": "Reply" });
|
|
247
|
+
const msg = h("p", { role: "status", class: "err" });
|
|
248
|
+
const send = h("button", { class: "btn", type: "submit" }, "Send reply");
|
|
249
|
+
const form = h("form", {
|
|
250
|
+
onsubmit: (e) => {
|
|
251
|
+
e.preventDefault();
|
|
252
|
+
send.disabled = true;
|
|
253
|
+
c.tickets.reply(t.id, { body: reply.value }).then(() => this.emit("armdesk-ticket-replied", { id: t.id }), (err) => {
|
|
254
|
+
msg.textContent = err instanceof Error ? err.message : "Could not send the reply.";
|
|
255
|
+
send.disabled = false;
|
|
256
|
+
});
|
|
257
|
+
},
|
|
258
|
+
}, reply, send, msg);
|
|
259
|
+
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;
|
|
260
|
+
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));
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
/**
|
|
264
|
+
* `<armdesk-messenger position="bottom-left" view="home" open label icon-url offset>`: the messenger bubble + panel.
|
|
265
|
+
* The `open` attribute is two-way (set it to open, it is set while open). Events: `armdesk-messenger-open`,
|
|
266
|
+
* `armdesk-messenger-close`, `armdesk-messenger-unread` (detail: the count).
|
|
267
|
+
*/
|
|
268
|
+
class ArmMessenger extends ArmBase {
|
|
269
|
+
constructor() {
|
|
270
|
+
super(...arguments);
|
|
271
|
+
this.ctl = null;
|
|
272
|
+
}
|
|
273
|
+
static get observedAttributes() {
|
|
274
|
+
return [...ArmBase.observedAttributes, "open", "icon-url", "offset", "aria-label"];
|
|
275
|
+
}
|
|
276
|
+
defaultView() {
|
|
277
|
+
return "home";
|
|
278
|
+
}
|
|
279
|
+
/** The controller (null until a client is available). */
|
|
280
|
+
get controller() {
|
|
281
|
+
return this.ctl;
|
|
282
|
+
}
|
|
283
|
+
open(view) {
|
|
284
|
+
var _a;
|
|
285
|
+
(_a = this.ctl) === null || _a === void 0 ? void 0 : _a.open(view);
|
|
286
|
+
}
|
|
287
|
+
close() {
|
|
288
|
+
var _a;
|
|
289
|
+
(_a = this.ctl) === null || _a === void 0 ? void 0 : _a.close();
|
|
290
|
+
}
|
|
291
|
+
toggle() {
|
|
292
|
+
var _a;
|
|
293
|
+
(_a = this.ctl) === null || _a === void 0 ? void 0 : _a.toggle();
|
|
294
|
+
}
|
|
295
|
+
attributeChangedCallback(name) {
|
|
296
|
+
var _a, _b;
|
|
297
|
+
if (!this.isConnected || !this.root)
|
|
298
|
+
return;
|
|
299
|
+
if (name === "open") {
|
|
300
|
+
if (this.hasAttribute("open"))
|
|
301
|
+
(_a = this.ctl) === null || _a === void 0 ? void 0 : _a.open();
|
|
302
|
+
else
|
|
303
|
+
(_b = this.ctl) === null || _b === void 0 ? void 0 : _b.close();
|
|
304
|
+
return;
|
|
305
|
+
}
|
|
306
|
+
if (name === "view" && this.ctl) {
|
|
307
|
+
const v = this.getAttribute("view");
|
|
308
|
+
if (isView(v))
|
|
309
|
+
this.ctl.navigate(v);
|
|
310
|
+
return;
|
|
311
|
+
}
|
|
312
|
+
super.attributeChangedCallback(name);
|
|
313
|
+
}
|
|
314
|
+
teardown() {
|
|
315
|
+
var _a;
|
|
316
|
+
(_a = this.ctl) === null || _a === void 0 ? void 0 : _a.destroy();
|
|
317
|
+
this.ctl = null;
|
|
318
|
+
}
|
|
319
|
+
async load() {
|
|
320
|
+
const c = this.c;
|
|
321
|
+
if (!c)
|
|
322
|
+
return;
|
|
323
|
+
this.teardown();
|
|
324
|
+
this.box.replaceChildren();
|
|
325
|
+
const view = this.getAttribute("view");
|
|
326
|
+
const offset = Number(this.getAttribute("offset"));
|
|
327
|
+
const ctl = c.messenger({
|
|
328
|
+
container: this.box,
|
|
329
|
+
position: this.getAttribute("position") === "left" || this.getAttribute("position") === "bottom-left" ? "bottom-left" : "bottom-right",
|
|
330
|
+
label: this.getAttribute("label") || undefined,
|
|
331
|
+
ariaLabel: this.getAttribute("aria-label") || undefined,
|
|
332
|
+
iconUrl: this.getAttribute("icon-url") || undefined,
|
|
333
|
+
offset: this.hasAttribute("offset") && Number.isFinite(offset) ? offset : undefined,
|
|
334
|
+
view: isView(view) ? view : this.defaultView(),
|
|
335
|
+
theme: readTheme(this.getAttribute("theme")),
|
|
336
|
+
open: this.hasAttribute("open"),
|
|
337
|
+
});
|
|
338
|
+
ctl.on("open", (d) => {
|
|
339
|
+
if (!this.hasAttribute("open"))
|
|
340
|
+
this.setAttribute("open", "");
|
|
341
|
+
this.emit("armdesk-messenger-open", d);
|
|
342
|
+
});
|
|
343
|
+
ctl.on("close", () => {
|
|
344
|
+
if (this.hasAttribute("open"))
|
|
345
|
+
this.removeAttribute("open");
|
|
346
|
+
this.emit("armdesk-messenger-close", null);
|
|
347
|
+
});
|
|
348
|
+
ctl.on("unread", (n) => this.emit("armdesk-messenger-unread", n));
|
|
349
|
+
this.ctl = ctl;
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
/** 1.0's launcher, now the messenger (it still opens at `tickets` unless `view` says otherwise). */
|
|
353
|
+
class ArmLauncher extends ArmMessenger {
|
|
354
|
+
defaultView() {
|
|
355
|
+
return "tickets";
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
const defs = [
|
|
359
|
+
["armdesk-tickets", ArmTickets],
|
|
360
|
+
["armdesk-new-ticket", ArmNewTicket],
|
|
361
|
+
["armdesk-ticket", ArmTicket],
|
|
362
|
+
["armdesk-launcher", ArmLauncher],
|
|
363
|
+
["armdesk-messenger", ArmMessenger],
|
|
364
|
+
];
|
|
365
|
+
for (const [name, ctor] of defs)
|
|
366
|
+
if (!customElements.get(name))
|
|
367
|
+
customElements.define(name, ctor);
|
|
368
|
+
}
|
|
@@ -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;
|
|
@@ -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>;
|
package/dist/esm/http.js
ADDED
|
@@ -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
|
+
}
|