@armdesk/connect-sdk 1.0.0 → 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 CHANGED
@@ -1,5 +1,24 @@
1
1
  # Changelog
2
2
 
3
+ ## 1.1.0
4
+
5
+ The messenger: a chat bubble that opens the support panel (Home, Messages, Help). Backward compatible.
6
+
7
+ - `client.messenger(options)` / `ArmDeskConnect.messenger(...)` returns a controller `{ open(view?), close(), toggle(),
8
+ navigate(view), setTheme(theme), isOpen(), unread(), on("unread" | "open" | "close"), destroy() }`. Bubble position,
9
+ offset, label, custom https icon, unread badge, z-index; 380 x 640 panel, full screen under 480 px; Esc closes and focus
10
+ returns to the bubble; ARIA dialog semantics; no animation under `prefers-reduced-motion`. `theme.primaryColor` (or the
11
+ organisation's theme) colours the bubble.
12
+ - `<armdesk-messenger position view open label icon-url offset>` web component (two-way `open` attribute, events
13
+ `armdesk-messenger-open` / `-close` / `-unread`). `<armdesk-launcher>` is now the messenger (opens at `tickets` by default).
14
+ - React: `<ArmDeskMessenger />` and `useMessenger()`.
15
+ - Embed protocol: views `home`, `messages`, `help`, `chat:<id>`, `article:<id>`; host to frame `open { view? }`; frame to
16
+ host `unread { count }` and `close`; `init` carries `host: "messenger"` inside the panel. `mount()` gains `onUnread`,
17
+ `onClose` and `handle.open(view?)`.
18
+ - Features `chat`, `helpCenter`, `aiAnswers`.
19
+ - README: "Your docs in the AI answers" (the org-backend knowledge sources API).
20
+ - IIFE about 12.5 kB gzipped (budget unchanged at 25 kB).
21
+
3
22
  ## 1.0.0
4
23
 
5
24
  The complete library. An integrating product needs only this package; it never calls an ARM Desk endpoint itself.
package/README.md CHANGED
@@ -17,9 +17,94 @@ never read an API reference.
17
17
  into your page.
18
18
  3. Your **page** gives that token to the library. Done.
19
19
 
20
- Contents: [Quick starts](#quick-starts) | [Signing without Node](#signing-the-user-token-without-node) |
21
- [Client API](#client-api) | [UI](#ui) | [Server helpers](#server-helpers) | [Theme](#theme-keys) | [Errors](#errors) |
22
- [Security](#security-notes) | [Embed protocol](#embed-protocol)
20
+ Contents: [Messenger](#messenger-quick-start) | [Quick starts](#quick-starts) |
21
+ [Signing without Node](#signing-the-user-token-without-node) | [Client API](#client-api) | [UI](#ui) |
22
+ [Your docs in the AI answers](#your-docs-in-the-ai-answers) | [Server helpers](#server-helpers) | [Theme](#theme-keys) |
23
+ [Errors](#errors) | [Security](#security-notes) | [Embed protocol](#embed-protocol)
24
+
25
+ ## Messenger quick start
26
+
27
+ The headline experience (1.1): a chat bubble in the corner of your product. It opens a panel with **Home** (greeting,
28
+ team availability, recent conversations, help search), **Messages** (live chat with your support team plus the user's
29
+ tickets) and **Help** (AI answers from your docs and the knowledge base, with "Talk to a person").
30
+
31
+ ```js
32
+ // your server, while rendering the page the user is signed in to (no network call)
33
+ import { signUserToken } from "@armdesk/connect-sdk/server";
34
+ const userToken = signUserToken({ orgKey: process.env.ARMDESK_ORG_KEY, orgSecret: process.env.ARMDESK_ORG_SECRET, user: { id: user.id, email: user.email, name: user.name } });
35
+ // render it: <meta name="armdesk-user-token" content="...">
36
+ ```
37
+
38
+ ```html
39
+ <script src="https://<your-desk>/connect/armdesk-connect.js"></script>
40
+ <script>
41
+ const messenger = ArmDeskConnect.messenger({
42
+ orgKey: "org_xxxxxxxxxxxxxxxxxxxxxxxx",
43
+ auth: { userToken: () => document.querySelector('meta[name="armdesk-user-token"]').content },
44
+ position: "bottom-right",
45
+ theme: { primaryColor: "#0f766e" }, // optional: defaults to the organisation's theme
46
+ });
47
+ messenger.on("unread", (n) => console.log(n, "unread"));
48
+ document.querySelector("#help-link").onclick = () => messenger.open("help");
49
+ </script>
50
+ ```
51
+
52
+ Or, with no script of your own beyond `init`: `<armdesk-messenger position="bottom-left"></armdesk-messenger>`.
53
+
54
+ React:
55
+
56
+ ```tsx
57
+ import { ArmDeskProvider, ArmDeskMessenger, useMessenger } from "@armdesk/connect-sdk/react";
58
+
59
+ function HelpButton() {
60
+ const { open, unread } = useMessenger();
61
+ return <button onClick={() => open("help")}>Help {unread > 0 ? `(${unread})` : null}</button>;
62
+ }
63
+
64
+ export function App({ userToken }: { userToken: () => string }) {
65
+ return (
66
+ <ArmDeskProvider desk="https://desk.example.com" orgKey="org_xxx" auth={{ userToken }}>
67
+ <HelpButton />
68
+ <ArmDeskMessenger position="bottom-right" onUnread={(n) => (document.title = n ? `(${n}) My app` : "My app")} />
69
+ </ArmDeskProvider>
70
+ );
71
+ }
72
+ ```
73
+
74
+ ### Messenger options
75
+
76
+ `client.messenger(options)`, `ArmDeskConnect.messenger(options)` (also accepts `orgKey` / `auth` / `desk` to sign in
77
+ first, or uses the client from the last `init()`), `<ArmDeskMessenger {...options} />`.
78
+
79
+ | Option | Default | Notes |
80
+ |---|---|---|
81
+ | `position` | `"bottom-right"` | or `"bottom-left"` |
82
+ | `offset` | `20` | px from the edges: a number or `{ x, y }` |
83
+ | `label` | none | text next to the icon (the bubble becomes a pill) |
84
+ | `ariaLabel` | `"Support"` | accessible name of the bubble and the panel |
85
+ | `iconUrl` | chat glyph | an https image URL |
86
+ | `view` | `"home"` | `home`, `messages`, `help`, `chat:<id>`, `article:<id>`, or the ticket views |
87
+ | `open` | `false` | open on creation |
88
+ | `lazy` | `false` | load the panel only on first open (no unread badge until then) |
89
+ | `theme`, `features`, `locale` | the client's | `theme.primaryColor` colours the bubble; features can only narrow (`chat`, `helpCenter`, `aiAnswers`, ...) |
90
+ | `zIndex` | `2147483000` | |
91
+ | `container` | `document.body` | where the bubble is attached |
92
+ | `onEvent`, `onError` | | as for `mount` |
93
+
94
+ The controller: `open(view?)`, `close()`, `toggle()`, `navigate(view)`, `setTheme(theme)`, `isOpen()`, `unread()`,
95
+ `on("unread" | "open" | "close", cb)` (returns an unsubscribe), `destroy()`.
96
+
97
+ `<armdesk-messenger>` attributes: `position`, `view`, `open` (two-way: set it to open; it is present while open), `label`,
98
+ `aria-label`, `icon-url`, `offset`, `theme` (JSON). Events: `armdesk-messenger-open`, `armdesk-messenger-close`,
99
+ `armdesk-messenger-unread` (detail: count). Methods: `open(view?)`, `close()`, `toggle()`.
100
+
101
+ React: `<ArmDeskMessenger />` takes the options plus `open` (controlled), `onOpen`, `onClose`, `onUnread`, `client`.
102
+ `useMessenger()` (anywhere under the provider) returns `{ open, close, toggle, isOpen, unread, ready, controller }` for the
103
+ mounted messenger.
104
+
105
+ Behaviour: a 380 x 640 panel with rounded corners above the bubble, full screen below 480 px wide; Esc (or the panel's
106
+ close button) closes it and returns focus to the bubble; the bubble shows an unread badge (99+); animations are off when
107
+ the visitor prefers reduced motion. The panel is the same origin-checked iframe as `client.mount`.
23
108
 
24
109
  ## Install
25
110
 
@@ -30,7 +115,8 @@ Script tag (served by your ARM Desk; it detects the desk from its own URL, so on
30
115
  ```
31
116
 
32
117
  npm: `pnpm add @armdesk/connect-sdk`. Entries: `.` (browser client), `/server` (Node 18+), `/react` (React 17+, optional
33
- peer), `/elements` (web components). The IIFE has no dependencies (about 9 kB gzipped, web components included).
118
+ peer), `/elements` (web components). The IIFE has no dependencies (about 12.5 kB gzipped, web components and the
119
+ messenger included).
34
120
 
35
121
  ## Quick starts
36
122
 
@@ -285,7 +371,8 @@ components use.
285
371
  | `categories()` | help topics |
286
372
  | `catalog.list({ search?, categoryId? })`, `catalog.request(itemId, answers, { quantity?, requestedForId?, files? })` | service catalog |
287
373
  | `on(event, cb)` | `ticket.created`, `ticket.replied`, `session.expired`, `error`; returns an unsubscribe function |
288
- | `mount(el, { view, theme, features, height, onEvent, onError })` | the iframe embed; returns `{ navigate, setTheme, refreshToken, destroy }` |
374
+ | `mount(el, { view, theme, features, height, onEvent, onError, onUnread, onClose })` | the iframe embed; returns `{ navigate, open, setTheme, refreshToken, destroy }` |
375
+ | `messenger(options)` | the messenger bubble; see [Messenger options](#messenger-options) |
289
376
  | `getAccessToken()`, `signOut()` | the cached session token; forget it |
290
377
 
291
378
  Files are `File` or `Blob`. The token lives in memory only, is renewed 30 seconds before it expires, and a rejected token
@@ -313,17 +400,47 @@ Two ways, same data layer:
313
400
  <armdesk-tickets limit="10" status="OPEN,PENDING"></armdesk-tickets>
314
401
  <armdesk-new-ticket></armdesk-new-ticket>
315
402
  <armdesk-ticket ticket-id="..."></armdesk-ticket>
316
- <armdesk-launcher label="Help" view="tickets" position="right"></armdesk-launcher>
403
+ <armdesk-messenger position="bottom-right"></armdesk-messenger>
404
+ <armdesk-launcher label="Help" view="tickets" position="right"></armdesk-launcher> <!-- 1.0 tag: now the messenger, opening at tickets -->
317
405
  ```
318
406
 
319
407
  Why Shadow DOM rather than iframe wrappers: the elements are for hosts that want tickets to be part of their page (their
320
408
  layout and scrolling, no frame, no cross-origin resize), and they run on the same headless client, so there is one
321
409
  contract. Shadow DOM isolates our CSS from yours. Everything is built from DOM nodes and `textContent`; the only HTML
322
- (ticket threads) goes through an allow-list sanitiser. `<armdesk-launcher>` is the exception on purpose: it opens the full
323
- iframe embed in a floating panel. Elements emit `armdesk-ticket-select`, `armdesk-ticket-created` and
410
+ (ticket threads) goes through an allow-list sanitiser. `<armdesk-messenger>` / `<armdesk-launcher>` are the exception on
411
+ purpose: they open the full iframe embed in the messenger panel. Elements emit `armdesk-ticket-select`, `armdesk-ticket-created` and
324
412
  `armdesk-ticket-replied` events (bubbling, composed), take a `theme` attribute (JSON), and a `client` property when you do
325
413
  not want the global one.
326
414
 
415
+ ## Your docs in the AI answers
416
+
417
+ The messenger's **Help** tab answers questions with AI, citing its sources: the desk's knowledge base and, if you add
418
+ them, **your own documentation**. Pages from your docs are crawled by ARM Desk and used **only for your organisation's
419
+ users**: never for another organisation and never for the desk's own staff answers. An admin can manage them in ARM Desk
420
+ (Admin > Developer > Connect > your organization > Knowledge), or your backend can manage them server to server with
421
+ the organisation's key and secret (HTTP Basic `orgKey:orgSecret`, like `POST /connect/v1/sessions`). Keep this on your
422
+ server: it uses the secret.
423
+
424
+ | Method | Path | Body / notes |
425
+ |---|---|---|
426
+ | `GET` | `/connect/v1/knowledge/sources` | your sources (status, pages, last / next crawl) |
427
+ | `POST` | `/connect/v1/knowledge/sources` | `{ name, startUrls[], allowedDomains[], maxDepth (0-5), maxPages (1-500), refreshHours }`; at most **5** sources |
428
+ | `PATCH` | `/connect/v1/knowledge/sources/:id` | any of the fields above |
429
+ | `DELETE` | `/connect/v1/knowledge/sources/:id` | removes the source and its pages |
430
+ | `POST` | `/connect/v1/knowledge/sources/:id/crawl` | crawl now |
431
+
432
+ ```bash
433
+ curl -u "$ARMDESK_ORG_KEY:$ARMDESK_ORG_SECRET" \
434
+ -H "Content-Type: application/json" \
435
+ -X POST "https://<your-desk>/api/proxy/connect/v1/knowledge/sources" \
436
+ -d '{"name":"Product docs","startUrls":["https://docs.example.com/"],"allowedDomains":["docs.example.com"],"maxDepth":2,"maxPages":200,"refreshHours":24}'
437
+ ```
438
+
439
+ Your docs appear in Help search and AI answers while the desk's AI knowledge assistant is on and the organisation's
440
+ `aiAnswers` feature is on (Help search itself needs `helpCenter`). Only public pages on the allowed domains are fetched
441
+ (robots.txt is honoured). Requests are rate-limited and audited.
442
+ The admin decides whether the AI may also use the workspace's shared sources for your users (Messenger settings).
443
+
327
444
  ## Server helpers
328
445
 
329
446
  `@armdesk/connect-sdk/server`: `signUserToken(options)`, `createConnectHandler(options)` (`.express()`, `.next()`,
@@ -346,7 +463,7 @@ variables (`--ad-primary`, `--ad-bg`, ...) in the web components and style the i
346
463
  | `mode` | `light` \| `dark` \| `auto` (follows the visitor's system) |
347
464
 
348
465
  Features (can only narrow what the organisation allows): `newTicket`, `attachments`, `catalog`, `orgTickets`, `replies`,
349
- `closeTicket`.
466
+ `closeTicket`, and since 1.1 `chat`, `helpCenter`, `aiAnswers`.
350
467
 
351
468
  ## Errors
352
469
 
@@ -384,10 +501,15 @@ Only for custom hosts of the iframe. The URL is `<desk>/embed/itsm?org=<orgKey>&
384
501
  | Direction | type | payload |
385
502
  |---|---|---|
386
503
  | frame to host | `ready` | none (sent first) |
387
- | host to frame | `init` | `{ token, theme, features }` |
504
+ | host to frame | `init` | `{ token, theme, features, host? }` (`host: "messenger"` inside the messenger panel) |
388
505
  | frame to host | `request-token` | none |
389
506
  | host to frame | `token` / `navigate` / `theme` | `{ token }` / `{ view }` / `{ theme }` |
507
+ | host to frame | `open` (1.1) | `{ view? }`: the messenger panel became visible |
390
508
  | frame to host | `resize` / `event` / `error` | `{ height }` / `{ name, data }` / `{ code, message }` |
509
+ | frame to host | `unread` (1.1) / `close` (1.1) | `{ count }` (badge) / none (the user closed the panel from inside) |
510
+
511
+ Views: `tickets`, `new`, `ticket:<id>`, and since 1.1 `home`, `messages`, `help`, `chat:<conversationId>`,
512
+ `article:<id>` (ids: 1 to 64 of `A-Z a-z 0-9 _ -`).
391
513
 
392
514
  ## Legacy
393
515
 
@@ -1,4 +1,4 @@
1
- var ArmDeskConnect=function(C){"use strict";var Je=Object.defineProperty,Xe=Object.defineProperties;var Ve=Object.getOwnPropertyDescriptors;var fe=Object.getOwnPropertySymbols;var Ye=Object.prototype.hasOwnProperty,Ze=Object.prototype.propertyIsEnumerable;var me=(C,_,I)=>_ in C?Je(C,_,{enumerable:!0,configurable:!0,writable:!0,value:I}):C[_]=I,U=(C,_)=>{for(var I in _||(_={}))Ye.call(_,I)&&me(C,I,_[I]);if(fe)for(var I of fe(_))Ze.call(_,I)&&me(C,I,_[I]);return C},pe=(C,_)=>Xe(C,Ve(_));let _,I=null;const B=new Set;function be(e){_=e}function ge(){return _}function ye(e){I=e,B.forEach(t=>t(e))}function ke(){return I}function we(e){return B.add(e),()=>B.delete(e)}const ve=new Set(["p","br","b","strong","i","em","u","s","ul","ol","li","a","code","pre","blockquote","span","div","h1","h2","h3","h4","h5","h6","hr"]),xe=new Set(["script","style","iframe","object","embed","template","noscript","svg","math","form","textarea","select","head","title"]);function Te(e){const t=e.trim();return/^(https?:|mailto:)/i.test(t)?t:null}function W(e,t,s){e.childNodes.forEach(l=>{var f,n;if(l.nodeType===3){t.appendChild(s.createTextNode((f=l.textContent)!=null?f:""));return}if(l.nodeType!==1)return;const c=l,h=c.tagName.toLowerCase();if(xe.has(h))return;if(!ve.has(h)){W(c,t,s);return}const S=s.createElement(h);if(h==="a"){const i=Te((n=c.getAttribute("href"))!=null?n:"");i&&(S.setAttribute("href",i),S.setAttribute("target","_blank"),S.setAttribute("rel","noopener noreferrer nofollow"))}W(c,S,s),t.appendChild(S)})}function Ae(e){if(typeof DOMParser=="undefined")return e.replace(/<[^>]*>/g,"");const t=new DOMParser().parseFromString(e,"text/html"),s=t.createElement("div");return W(t.body,s,t),s.innerHTML}function Ee(e,t){const s=e.ownerDocument.createElement("div");s.innerHTML=Ae(t),e.replaceChildren(...Array.from(s.childNodes))}const Ce=/^#[0-9a-fA-F]{6}$/,J={system:'system-ui, -apple-system, "Segoe UI", Roboto, sans-serif',inter:'Inter, system-ui, -apple-system, "Segoe UI", sans-serif',roboto:'Roboto, system-ui, "Segoe UI", sans-serif',"open-sans":'"Open Sans", system-ui, "Segoe UI", sans-serif',lato:'Lato, system-ui, "Segoe UI", sans-serif'},Se={"--ad-bg":"#ffffff","--ad-surface":"#f8f9fb","--ad-text":"#1a1d23","--ad-muted":"#6b7280","--ad-border":"#e5e7eb","--ad-primary":"#2563eb"},V={"--ad-bg":"#0f1115","--ad-surface":"#181b21","--ad-text":"#f3f4f6","--ad-muted":"#9ca3af","--ad-border":"#2a2f38","--ad-primary":"#60a5fa"},Me=[["backgroundColor","--ad-bg"],["surfaceColor","--ad-surface"],["textColor","--ad-text"],["mutedColor","--ad-muted"],["borderColor","--ad-border"],["primaryColor","--ad-primary"]],X=e=>Object.entries(e).map(([t,s])=>`${t}:${s};`).join("");function $e(e){const t={},s=e!=null?e:{};for(const[l,c]of Me){const h=s[l];typeof h=="string"&&Ce.test(h)&&(t[c]=h.toLowerCase())}return typeof s.fontFamily=="string"&&J[s.fontFamily]&&(t["--ad-font"]=J[s.fontFamily]),typeof s.radius=="number"&&Number.isFinite(s.radius)&&(t["--ad-radius"]=`${Math.min(24,Math.max(0,Math.round(s.radius)))}px`),t["--ad-pad"]=s.density==="compact"?"6px 10px":"10px 14px",t}function De(e){var c;const t=(c=e==null?void 0:e.mode)!=null?c:"auto",s=`:host{display:block;--ad-font:${J.system};--ad-radius:8px;--ad-pad:10px 14px;${X(t==="dark"?V:Se)}}`,l=t==="auto"?`@media (prefers-color-scheme:dark){:host{${X(V)}}}`:"";return`${s}${l}:host{${X($e(e))}}`}function a(e,t={},...s){const l=document.createElement(e);for(const[c,h]of Object.entries(t))h===void 0||h===!1||(typeof h=="function"?l.addEventListener(c.replace(/^on/,""),h):h===!0?l.setAttribute(c,""):l.setAttribute(c,h));for(const c of s)c&&l.append(c);return l}const Oe=`
1
+ var ArmDeskConnect=function(A){"use strict";var gt=Object.defineProperty,yt=Object.defineProperties;var wt=Object.getOwnPropertyDescriptors;var ne=Object.getOwnPropertySymbols;var $e=Object.prototype.hasOwnProperty,Me=Object.prototype.propertyIsEnumerable;var Se=(A,I,U)=>I in A?gt(A,I,{enumerable:!0,configurable:!0,writable:!0,value:U}):A[I]=U,H=(A,I)=>{for(var U in I||(I={}))$e.call(I,U)&&Se(A,U,I[U]);if(ne)for(var U of ne(I))Me.call(I,U)&&Se(A,U,I[U]);return A},ie=(A,I)=>yt(A,wt(I));var De=(A,I)=>{var U={};for(var K in A)$e.call(A,K)&&I.indexOf(K)<0&&(U[K]=A[K]);if(A!=null&&ne)for(var K of ne(A))I.indexOf(K)<0&&Me.call(A,K)&&(U[K]=A[K]);return U};let I,U=null;const K=new Set;function Ne(t){I=t}function Le(){return I}function Oe(t){U=t,K.forEach(e=>e(t))}function ce(){return U}function Ie(t){return K.add(t),()=>K.delete(t)}const le="armdesk-connect",te=/^(tickets|new|home|messages|help|(ticket|chat|article):[A-Za-z0-9_-]{1,64})$/,_e=["en","es","ar"],de=8192,je=9999;function Re(t){if(typeof t!="object"||t===null)return!1;const e=t;return e.source===le&&typeof e.type=="string"}function Q(t){return typeof t=="string"&&te.test(t)}function Ue(t){const e=Number(t==null?void 0:t.count);return!Number.isFinite(e)||e<0?null:Math.min(je,Math.floor(e))}function ue(t){let e;try{e=new URL(t)}catch(c){throw new Error("ArmDeskConnect: baseUrl must be an absolute URL")}const s=e.hostname==="localhost"||e.hostname==="127.0.0.1"||e.hostname==="[::1]";if(e.protocol!=="https:"&&!(e.protocol==="http:"&&s))throw new Error("ArmDeskConnect: baseUrl must be https (http is allowed for localhost only)");return e.origin}const qe="X-ArmDesk-Csrf",Fe="/armdesk/session",Pe="urn:ietf:params:oauth:grant-type:jwt-bearer",Ke=new Set(["p","br","b","strong","i","em","u","s","ul","ol","li","a","code","pre","blockquote","span","div","h1","h2","h3","h4","h5","h6","hr"]),He=new Set(["script","style","iframe","object","embed","template","noscript","svg","math","form","textarea","select","head","title"]);function ze(t){const e=t.trim();return/^(https?:|mailto:)/i.test(e)?e:null}function se(t,e,s){t.childNodes.forEach(c=>{var b,k;if(c.nodeType===3){e.appendChild(s.createTextNode((b=c.textContent)!=null?b:""));return}if(c.nodeType!==1)return;const u=c,h=u.tagName.toLowerCase();if(He.has(h))return;if(!Ke.has(h)){se(u,e,s);return}const E=s.createElement(h);if(h==="a"){const n=ze((k=u.getAttribute("href"))!=null?k:"");n&&(E.setAttribute("href",n),E.setAttribute("target","_blank"),E.setAttribute("rel","noopener noreferrer nofollow"))}se(u,E,s),e.appendChild(E)})}function Be(t){if(typeof DOMParser=="undefined")return t.replace(/<[^>]*>/g,"");const e=new DOMParser().parseFromString(t,"text/html"),s=e.createElement("div");return se(e.body,s,e),s.innerHTML}function Ge(t,e){const s=t.ownerDocument.createElement("div");s.innerHTML=Be(e),t.replaceChildren(...Array.from(s.childNodes))}const Ve=/^#[0-9a-fA-F]{6}$/,ae={system:'system-ui, -apple-system, "Segoe UI", Roboto, sans-serif',inter:'Inter, system-ui, -apple-system, "Segoe UI", sans-serif',roboto:'Roboto, system-ui, "Segoe UI", sans-serif',"open-sans":'"Open Sans", system-ui, "Segoe UI", sans-serif',lato:'Lato, system-ui, "Segoe UI", sans-serif'},We={"--ad-bg":"#ffffff","--ad-surface":"#f8f9fb","--ad-text":"#1a1d23","--ad-muted":"#6b7280","--ad-border":"#e5e7eb","--ad-primary":"#2563eb"},fe={"--ad-bg":"#0f1115","--ad-surface":"#181b21","--ad-text":"#f3f4f6","--ad-muted":"#9ca3af","--ad-border":"#2a2f38","--ad-primary":"#60a5fa"},Xe=[["backgroundColor","--ad-bg"],["surfaceColor","--ad-surface"],["textColor","--ad-text"],["mutedColor","--ad-muted"],["borderColor","--ad-border"],["primaryColor","--ad-primary"]],oe=t=>Object.entries(t).map(([e,s])=>`${e}:${s};`).join("");function Je(t){const e={},s=t!=null?t:{};for(const[c,u]of Xe){const h=s[c];typeof h=="string"&&Ve.test(h)&&(e[u]=h.toLowerCase())}return typeof s.fontFamily=="string"&&ae[s.fontFamily]&&(e["--ad-font"]=ae[s.fontFamily]),typeof s.radius=="number"&&Number.isFinite(s.radius)&&(e["--ad-radius"]=`${Math.min(24,Math.max(0,Math.round(s.radius)))}px`),e["--ad-pad"]=s.density==="compact"?"6px 10px":"10px 14px",e}function he(t){var u;const e=(u=t==null?void 0:t.mode)!=null?u:"auto",s=`:host{display:block;--ad-font:${ae.system};--ad-radius:8px;--ad-pad:10px 14px;${oe(e==="dark"?fe:We)}}`,c=e==="auto"?`@media (prefers-color-scheme:dark){:host{${oe(fe)}}}`:"";return`${s}${c}:host{${oe(Je(t))}}`}function d(t,e={},...s){const c=document.createElement(t);for(const[u,h]of Object.entries(e))h===void 0||h===!1||(typeof h=="function"?c.addEventListener(u.replace(/^on/,""),h):h===!0?c.setAttribute(u,""):c.setAttribute(u,h));for(const u of s)u&&c.append(u);return c}const Ye=`
2
2
  *{box-sizing:border-box}
3
3
  .ad{font-family:var(--ad-font);color:var(--ad-text);background:var(--ad-bg);font-size:14px;line-height:1.45}
4
4
  .ad h3{margin:0 0 8px;font-size:16px}
@@ -16,8 +16,26 @@ label{display:block;margin:0 0 10px}
16
16
  .agent{border-left:3px solid var(--ad-primary)}
17
17
  .body a{color:var(--ad-primary)}.body pre{white-space:pre-wrap;overflow:auto}
18
18
  .bar{display:flex;gap:8px;justify-content:space-between;align-items:center}
19
- .fab{position:fixed;bottom:20px;z-index:2147483000}
20
- .fab.right{right:20px}.fab.left{left:20px}
21
- .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)}
22
- .panel.right{right:20px}.panel.left{left:20px}
23
- `;function Y(e){if(e)try{const t=JSON.parse(e);return t&&typeof t=="object"?t:void 0}catch(t){return}}function Z(){if(typeof customElements=="undefined"||typeof HTMLElement=="undefined")return;class e extends HTMLElement{constructor(){super(...arguments),this.client=null,this.unsub=null,this.bound=null,this.offEvents=[]}static get observedAttributes(){return["theme","ticket-id","status","limit","view","label","position"]}get c(){var n;return(n=this.client)!=null?n:ke()}connectedCallback(){this.root||(this.root=this.attachShadow({mode:"open"}),this.styleEl=document.createElement("style"),this.box=a("div",{class:"ad",part:"root"}),this.root.append(this.styleEl,this.box)),this.paintTheme(),this.unsub=we(()=>this.start()),this.start()}disconnectedCallback(){var n;(n=this.unsub)==null||n.call(this),this.unsub=null,this.offEvents.forEach(i=>i()),this.offEvents=[],this.bound=null,this.teardown()}attributeChangedCallback(){!this.isConnected||!this.root||(this.paintTheme(),this.load())}paintTheme(){const n=U(U({},this.cfgTheme),Y(this.getAttribute("theme")));this.styleEl.textContent=De(n)+Oe}start(){const n=this.c;if(!n){this.box.replaceChildren(a("p",{class:"muted"},"ARM Desk is not initialised yet."));return}n!==this.bound&&(this.offEvents.forEach(i=>i()),this.offEvents=this.watch(n),this.bound=n,n.config().then(i=>{this.cfgTheme=i.theme,this.paintTheme()},()=>{})),this.load()}watch(n){return[]}async load(){}teardown(){}fail(n,i){this.box.replaceChildren(a("p",{class:"err",role:"alert"},n instanceof Error?n.message:"Something went wrong."),a("button",{class:"btn ghost",onclick:i},"Try again"))}emit(n,i){this.dispatchEvent(new CustomEvent(n,{detail:i,bubbles:!0,composed:!0}))}}const t=f=>f?new Date(f).toLocaleString():"";class s extends e{constructor(){super(...arguments),this.page=1}watch(n){return[n.on("ticket.created",()=>void this.load()),n.on("ticket.replied",()=>void this.load())]}async load(){const n=this.c;if(!n)return;const i=Math.min(100,Math.max(1,Number(this.getAttribute("limit"))||10));this.box.replaceChildren(a("p",{class:"muted"},"Loading..."));try{const u=await n.tickets.list({status:this.getAttribute("status")||void 0,page:this.page,limit:i});this.draw(u,i)}catch(u){this.fail(u,()=>void this.load())}}draw(n,i){const u=Math.max(1,Math.ceil(n.total/i)),T=n.items.map(b=>{var M;return a("div",{class:"card"},a("button",{class:"row",style:"background:none;border:0;padding:0",onclick:()=>this.emit("armdesk-ticket-select",{id:b.id,number:b.number})},a("span",{},a("strong",{},b.number)," ",b.subject,a("div",{class:"muted"},t((M=b.lastReplyAt)!=null?M:b.updatedAt))),a("span",{class:"badge"},b.status.replace(/_/g," "))))});this.box.replaceChildren(a("h3",{},"My tickets"),...T.length?T:[a("p",{class:"muted"},"No tickets yet.")],a("div",{class:"bar"},a("button",{class:"btn ghost",disabled:this.page<=1,onclick:()=>{this.page--,this.load()}},"Previous"),a("span",{class:"muted"},`${this.page} / ${u}`),a("button",{class:"btn ghost",disabled:this.page>=u,onclick:()=>{this.page++,this.load()}},"Next")))}}class l extends e{async load(){var p,w;const n=this.c;if(!n)return;let i=[],u=!0,T=!0;try{const y=await n.config();u=((p=y.features)==null?void 0:p.attachments)!==!1,T=((w=y.features)==null?void 0:w.newTicket)!==!1,i=await n.categories()}catch(y){}if(!T){this.box.replaceChildren(a("p",{class:"muted"},"Raising tickets is turned off."));return}const b=a("input",{name:"subject",required:!0,minlength:"5",maxlength:"255"}),M=a("textarea",{name:"description",required:!0,minlength:"10",maxlength:"20000",rows:"6"}),q=a("select",{name:"priority"},...["NORMAL","LOW","HIGH","URGENT"].map(y=>a("option",{value:y},y.charAt(0)+y.slice(1).toLowerCase()))),R=a("select",{name:"categoryId"},a("option",{value:""},"None"),...i.map(y=>a("option",{value:y.id},y.name))),A=a("input",{type:"file",multiple:!0}),D=a("p",{role:"status",class:"muted"}),j=a("button",{class:"btn",type:"submit"},"Submit ticket"),d=a("form",{onsubmit:y=>{var F;y.preventDefault(),j.disabled=!0,D.className="muted",D.textContent="Sending...",n.tickets.create({subject:b.value,description:M.value,priority:q.value,categoryId:R.value||void 0,files:Array.from((F=A.files)!=null?F:[])}).then(L=>{D.textContent=`Ticket ${L.number} created.`,d.reset(),this.emit("armdesk-ticket-created",L)}).catch(L=>{D.className="err",D.textContent=L instanceof Error?L.message:"Could not create the ticket."}).finally(()=>j.disabled=!1)}},a("label",{},"Subject",b),a("label",{},"Description",M),a("label",{},"Priority",q),i.length?a("label",{},"Category",R):null,u?a("label",{},"Attachments",A):null,j,D);this.box.replaceChildren(a("h3",{},"New ticket"),d)}}class c extends e{watch(n){return[n.on("ticket.replied",i=>i.ticketId===this.getAttribute("ticket-id")&&void this.load())]}async load(){const n=this.c,i=this.getAttribute("ticket-id");if(n){if(!i){this.box.replaceChildren(a("p",{class:"muted"},"Set the ticket-id attribute."));return}try{this.draw(n,await n.tickets.get(i))}catch(u){this.fail(u,()=>void this.load())}}}draw(n,i){const u=i.threads.map(A=>{var d;const D=a("div",{class:"body"});Ee(D,A.body);const j=((d=A.attachments)!=null?d:[]).filter(p=>p.url&&/^(https?:\/|\/)/.test(p.url)).map(p=>a("a",{href:p.url,target:"_blank",rel:"noopener noreferrer"},p.name));return a("div",{class:`card${A.author.isAgent?" agent":""}`},a("div",{class:"muted"},`${A.author.name} - ${t(A.createdAt)}`),D,...j.length?[a("div",{class:"muted"},"Files: ",...j.flatMap(p=>[p," "]))]:[])}),T=a("textarea",{rows:"4",required:!0,minlength:"1","aria-label":"Reply"}),b=a("p",{role:"status",class:"err"}),M=a("button",{class:"btn",type:"submit"},"Send reply"),q=a("form",{onsubmit:A=>{A.preventDefault(),M.disabled=!0,n.tickets.reply(i.id,{body:T.value}).then(()=>this.emit("armdesk-ticket-replied",{id:i.id}),D=>{b.textContent=D instanceof Error?D.message:"Could not send the reply.",M.disabled=!1})}},T,M,b),R=i.canClose?a("button",{class:"btn ghost",onclick:()=>void n.tickets.close(i.id).then(()=>this.load(),A=>this.fail(A,()=>void this.load()))},"Mark as solved"):null;this.box.replaceChildren(a("div",{class:"bar"},a("h3",{},`${i.number} ${i.subject}`),a("span",{class:"badge"},i.status.replace(/_/g," "))),...u,...[i.canReply?q:null,R].filter(A=>A!==null))}}class h extends e{constructor(){super(...arguments),this.handle=null,this.open=!1}teardown(){var n;(n=this.handle)==null||n.destroy(),this.handle=null}async load(){const n=this.getAttribute("position")==="left"?"left":"right",i=a("div",{class:`panel ${n}`,role:"dialog","aria-label":this.getAttribute("label")||"Support",hidden:!0}),u=a("button",{class:`btn fab ${n}`,"aria-expanded":"false",onclick:()=>{this.open=!this.open,i.hidden=!this.open,u.setAttribute("aria-expanded",String(this.open));const T=this.c;if(this.open&&!this.handle&&T){const b=this.getAttribute("view")||"tickets";this.handle=T.mount(i,{view:b,theme:Y(this.getAttribute("theme")),height:640})}}},this.getAttribute("label")||"Support");this.teardown(),this.box.replaceChildren(u,i)}}const S=[["armdesk-tickets",s],["armdesk-new-ticket",l],["armdesk-ticket",c],["armdesk-launcher",h]];for(const[f,n]of S)customElements.get(f)||customElements.define(f,n)}class $ extends Error{constructor(t,s,l=0,c){super(s),this.name="ArmDeskError",this.code=t,this.status=l,this.retryAfter=c}}function _e(e){return e===401?"unauthorized":e===403?"forbidden":e===404?"not_found":e===409?"conflict":e===429?"rate_limited":e>=500?"server":"validation"}function Ie(e,t,s){const l=t&&typeof t=="object"?t:{};if(typeof l.error=="string"){const h=typeof l.error_description=="string"?l.error_description:l.error;return new $(l.error,h,e,s)}const c=Array.isArray(l.message)?l.message.join("; "):typeof l.message=="string"?l.message:`ARM Desk answered ${e}`;return new $(_e(e),c,e,s)}const Q=3e4,ee=e=>new Promise(t=>setTimeout(t,e));function te(e){const t=e.headers.get("Retry-After");if(!t)return;const s=Number(t);if(Number.isFinite(s))return Math.max(0,s*1e3);const l=Date.parse(t);return Number.isNaN(l)?void 0:Math.max(0,l-Date.now())}async function H(e,t,s){const l=c=>c===429||(s.method==="GET"?c>=500:c===503);for(let c=0;;c++){const h=new AbortController,S=setTimeout(()=>h.abort(),e.timeoutMs);let f=null,n=null;try{f=await e.fetch(t,{method:s.method,headers:s.headers,body:s.body,credentials:s.credentials,signal:h.signal})}catch(u){n=u}finally{clearTimeout(S)}const i=c>=e.retries;if(f){if(f.ok||!l(f.status)||i)return f;const u=te(f);await ee(Math.min(Q,u!=null?u:e.retryDelayMs*2**c));continue}if(s.method!=="GET"||i)throw new $("network",n instanceof Error?`Could not reach ARM Desk: ${n.message}`:"Could not reach ARM Desk");await ee(Math.min(Q,e.retryDelayMs*2**c))}}async function K(e){let t=null;try{t=await e.json()}catch(s){}if(!e.ok){const s=te(e);throw Ie(e.status,t,s===void 0?void 0:Math.ceil(s/1e3))}if(t==null)throw new $("bad_response","ARM Desk returned an empty response",e.status);return t}const re="armdesk-connect",ne=/^(tickets|new|ticket:[A-Za-z0-9_-]{1,64})$/,je=["en","es","ar"],se=8192;function Ne(e){if(typeof e!="object"||e===null)return!1;const t=e;return t.source===re&&typeof t.type=="string"}function ae(e){let t;try{t=new URL(e)}catch(l){throw new Error("ArmDeskConnect: baseUrl must be an absolute URL")}const s=t.hostname==="localhost"||t.hostname==="127.0.0.1"||t.hostname==="[::1]";if(t.protocol!=="https:"&&!(t.protocol==="http:"&&s))throw new Error("ArmDeskConnect: baseUrl must be https (http is allowed for localhost only)");return t.origin}const Re="X-ArmDesk-Csrf",Le="/armdesk/session",qe="urn:ietf:params:oauth:grant-type:jwt-bearer",Fe=2e4,oe=4,Pe=400,Ue=120,He=2e4;function Ke(e){const t=typeof e=="string"?document.querySelector(e):e;if(!t)throw new Error("ArmDeskConnect: container not found");return t}const Ge=e=>new Promise(t=>setTimeout(t,e));function ie(e,t){var D,j;const s=Ke(e),l=ae(t.baseUrl);if(!t.orgKey)throw new Error("ArmDeskConnect: orgKey is required");if(typeof t.getToken!="function")throw new Error("ArmDeskConnect: getToken is required");if(t.view!==void 0&&!ne.test(t.view))throw new Error("ArmDeskConnect: invalid view");let c=(D=t.view)!=null?D:"tickets",h=U({},(j=t.theme)!=null?j:{}),S=!1,f=!1,n=null;const i=new URLSearchParams({org:t.orgKey,view:c});t.locale&&je.includes(t.locale)&&i.set("locale",t.locale);const u=document.createElement("iframe");u.src=`${l}/embed/itsm?${i.toString()}`,u.title="Support tickets",u.setAttribute("referrerpolicy","strict-origin"),u.setAttribute("loading","lazy"),u.setAttribute("data-armdesk-connect",""),Object.assign(u.style,{width:"100%",border:"0",display:"block",colorScheme:"normal"}),u.style.height=typeof t.height=="number"?`${t.height}px`:"480px";const T=(d,p)=>{const w=u.contentWindow;f||!w||w.postMessage({source:re,type:d,payload:p},l)},b=(d,p)=>{var w;try{(w=t.onError)==null||w.call(t,{code:d,message:p})}catch(y){}},M=()=>n||(n=(async()=>{for(let d=0;d<oe&&!f;d++)try{const p=await t.getToken();if(typeof p=="string"&&p.length>0&&p.length<=se)return p;throw new Error("getToken returned an invalid token")}catch(p){if(d===oe-1){b("token_failed",p instanceof Error?p.message:"Could not get a token");break}await Ge(Pe*2**d)}return null})().finally(()=>{n=null}),n),q=async d=>{var w;const p=await M();!p||f||T(d,d==="init"?{token:p,theme:h,features:(w=t.features)!=null?w:{}}:{token:p})};let R=setTimeout(()=>{S||b("timeout","The embed did not respond. Check baseUrl and the organisation's allowed origins.")},Fe);const A=d=>{var F;if(f||d.origin!==l||d.source!==u.contentWindow||!Ne(d.data))return;const{type:p,payload:w}=d.data,y=typeof w=="object"&&w!==null?w:{};switch(p){case"ready":S=!0,R&&clearTimeout(R),R=null,q("init");break;case"request-token":q("token");break;case"resize":{const L=Number(y.height);(t.height===void 0||t.height==="auto")&&Number.isFinite(L)&&(u.style.height=`${Math.min(He,Math.max(Ue,Math.ceil(L)))}px`);break}case"event":if(typeof y.name=="string")try{(F=t.onEvent)==null||F.call(t,{name:y.name,data:y.data})}catch(L){}break;case"error":b(typeof y.code=="string"?y.code:"error",typeof y.message=="string"?y.message:"Embed error");break}};return window.addEventListener("message",A),s.appendChild(u),{navigate(d){if(!ne.test(d))throw new Error("ArmDeskConnect: invalid view");c=d,S&&T("navigate",{view:c})},setTheme(d){h=U({},d),S&&T("theme",{theme:h})},refreshToken:()=>q("token"),destroy(){f||(f=!0,R&&clearTimeout(R),window.removeEventListener("message",A),u.remove())}}}const ze=3e4,G=840,z="/connect/v1";function ce(e){var F,L,le,de,ue,he;if(!e||!e.orgKey)throw new $("config","ArmDeskConnect: orgKey is required");if(!e.auth||typeof e.auth!="object")throw new $("config","ArmDeskConnect: auth is required");const t=(F=e.desk)!=null?F:ge();if(!t)throw new $("config","ArmDeskConnect: desk is required (it is detected only when the script tag is used)");const s=ae(t),l=(le=e.fetch)!=null?le:(L=globalThis.fetch)==null?void 0:L.bind(globalThis);if(typeof l!="function")throw new $("config","fetch is not available");const c={fetch:l,retries:(de=e.retries)!=null?de:2,retryDelayMs:(ue=e.retryDelayMs)!=null?ue:400,timeoutMs:(he=e.timeoutMs)!=null?he:2e4},h=e.auth,S=new Map,f=(r,o)=>{var m;(m=S.get(r))==null||m.forEach(g=>{try{g(o)}catch(O){}})};let n=null;const i=`${s}/api/proxy`,u=r=>r.replace(/\/+$/,"").replace(/\/connect\/v1$/,""),T=()=>e.apiBase?Promise.resolve(u(e.apiBase)):(n!=null||(n=(async()=>{try{const r=await H(pe(U({},c),{retries:0}),`${i}${z}/bootstrap?org=${encodeURIComponent(e.orgKey)}`,{method:"GET",headers:{Accept:"application/json"}}),o=await K(r);if(typeof o.apiBase=="string"&&o.apiBase)return u(new URL(o.apiBase,s).toString())}catch(r){}return i})()),n);let b=null,M=null;const q=r=>{if(typeof r.token!="string"||!r.token||r.token.length>se)throw new $("bad_response","ARM Desk returned an invalid token");return b={token:r.token,expiresAt:Date.now()+(Number.isFinite(r.expiresIn)?r.expiresIn:G)*1e3},r.token},R=async()=>{var g,O,v,k;const r=await T();if("userToken"in h){const E=await h.userToken();if(typeof E!="string"||!E)throw new $("config","userToken() must return the signed user token");const N=new URLSearchParams({grant_type:qe,assertion:E}),x=await H(c,`${r}${z}/oauth/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:N.toString()}),P=await K(x);if(typeof P.access_token!="string")throw new $("bad_response","ARM Desk returned no access_token",x.status);return{token:P.access_token,expiresIn:(g=P.expires_in)!=null?g:G}}if("idToken"in h){const E=await h.idToken(),N={orgKey:e.orgKey,idToken:E};h.nonce&&(N.nonce=h.nonce);const x=await H(c,`${r}${z}/sessions/browser`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(N)}),P=await K(x);return{token:P.token,expiresIn:(O=P.expiresIn)!=null?O:G}}if("getToken"in h)return{token:await h.getToken(),expiresIn:G};const o=await H(c,(v=h.sessionUrl)!=null?v:Le,{method:"POST",headers:{[Re]:"1",Accept:"application/json"},credentials:"same-origin"}),m=await K(o);return{token:m.token,expiresIn:(k=m.expiresIn)!=null?k:G}},A=async()=>{var r;if(!("idToken"in h)||!b)return null;try{const o=await T(),m=await H(c,`${o}${z}/sessions/refresh`,{method:"POST",headers:{Authorization:`Bearer ${b.token}`,Accept:"application/json"}}),g=await K(m);return{token:g.token,expiresIn:(r=g.expiresIn)!=null?r:G}}catch(o){return null}},D=()=>(M!=null||(M=(async()=>{var r;try{const o=(r=await A())!=null?r:await R();return q(o)}catch(o){const m=b!==null;b=null;const g=o instanceof $?o:new $("session_expired",o instanceof Error?o.message:"Could not sign in");throw m&&f("session.expired",{code:g.code,message:g.message,status:g.status}),f("error",{code:g.code,message:g.message,status:g.status}),g}finally{M=null}})()),M),j=async()=>b&&b.expiresAt-ze>Date.now()?b.token:D(),d=async(r,o=!1)=>{const m=await j(),g=await T(),O=r.query?Object.entries(r.query).filter(([,x])=>x!==void 0&&x!==""):[],v=`${g}${z}${r.path}${O.length?`?${new URLSearchParams(O.map(([x,P])=>[x,String(P)])).toString()}`:""}`,k={Authorization:`Bearer ${m}`,Accept:"application/json"};let E;r.form?E=r.form:r.json!==void 0&&(k["Content-Type"]="application/json",E=JSON.stringify(r.json));const N=await H(c,v,{method:r.method,headers:k,body:E});if(N.status===401&&!o)return b=null,d(r,!0);try{return await K(N)}catch(x){throw x instanceof $&&!(o&&x.status===401)&&f("error",{code:x.code,message:x.message,status:x.status}),x instanceof $&&x.status===401&&f("session.expired",{code:x.code,message:x.message,status:401}),x}},p=(r,o,m="files")=>{var v;const g=Object.fromEntries(Object.entries(r).filter(([,k])=>k!==void 0&&k!==""));if(!o||o.length===0)return{json:g};const O=new FormData;for(const[k,E]of Object.entries(g))O.append(k,E);for(const k of o)O.append(m,k,(v=k.name)!=null?v:"file");return{form:O}},w=r=>{if(!r||typeof r!="string")throw new $("validation","An id is required");return encodeURIComponent(r)};return{orgKey:e.orgKey,desk:s,me:()=>d({method:"GET",path:"/me"}),config:()=>d({method:"GET",path:"/config",query:{locale:e.locale}}),categories:async()=>{var o;const r=await d({method:"GET",path:"/categories"});return Array.isArray(r)?r:(o=r.items)!=null?o:[]},tickets:{list:(r={})=>d({method:"GET",path:"/tickets",query:{status:Array.isArray(r.status)?r.status.join(","):r.status,search:r.search,page:r.page,limit:r.limit}}),get:async r=>d({method:"GET",path:`/tickets/${w(r)}`}),async create(r){const o=await d(U({method:"POST",path:"/tickets"},p({subject:r.subject,description:r.description,priority:r.priority,categoryId:r.categoryId},r.files)));return f("ticket.created",o),o},async reply(r,o){const m=await d(U({method:"POST",path:`/tickets/${w(r)}/replies`},p({body:o.body},o.files)));return f("ticket.replied",{ticketId:r,reply:m}),m},close:async r=>d({method:"POST",path:`/tickets/${w(r)}/close`})},catalog:{list:(r={})=>d({method:"GET",path:"/catalog",query:{search:r.search,categoryId:r.categoryId}}),async request(r,o={},m={}){var k;const g={answers:JSON.stringify(o),quantity:m.quantity===void 0?void 0:String(m.quantity),requestedForId:m.requestedForId},O=m.files?Object.entries(m.files):[];if(O.length===0){const E={answers:o};return m.quantity!==void 0&&(E.quantity=m.quantity),m.requestedForId&&(E.requestedForId=m.requestedForId),d({method:"POST",path:`/catalog/${w(r)}/requests`,json:E})}const v=new FormData;for(const[E,N]of Object.entries(g))N!==void 0&&v.append(E,N);for(const[E,N]of O)v.append(`file:${E}`,N,(k=N.name)!=null?k:"file");return d({method:"POST",path:`/catalog/${w(r)}/requests`,form:v})}},on(r,o){let m=S.get(r);return m||S.set(r,m=new Set),m.add(o),()=>m.delete(o)},mount(r,o={}){var m,g,O;return ie(r,{baseUrl:s,orgKey:e.orgKey,getToken:j,view:o.view,theme:(m=o.theme)!=null?m:e.theme,features:(g=o.features)!=null?g:e.features,locale:(O=o.locale)!=null?O:e.locale,height:o.height,onEvent:v=>{var k;v.name==="ticket.created"&&f("ticket.created",v.data),v.name==="ticket.replied"&&f("ticket.replied",v.data),(k=o.onEvent)==null||k.call(o,v)},onError:v=>{var k;f("error",v),(k=o.onError)==null||k.call(o,v)}})},getAccessToken:j,signOut(){b=null,M=null}}}function Be(e){const t=ce(e);return ye(t),t}const We="1.0.0";if(typeof document!="undefined"){const e=document.currentScript;if(e&&e.src)try{be(new URL(e.src).origin)}catch(t){}Z()}return C.ArmDeskError=$,C.createClient=ce,C.defineElements=Z,C.init=Be,C.mount=ie,C.version=We,Object.defineProperty(C,Symbol.toStringTag,{value:"Module"}),C}({});
19
+ `;function me(t){if(t)try{const e=JSON.parse(t);return e&&typeof e=="object"?e:void 0}catch(e){return}}function pe(){if(typeof customElements=="undefined"||typeof HTMLElement=="undefined")return;class t extends HTMLElement{constructor(){super(...arguments),this.client=null,this.unsub=null,this.bound=null,this.offEvents=[]}static get observedAttributes(){return["theme","ticket-id","status","limit","view","label","position"]}get c(){var n;return(n=this.client)!=null?n:ce()}connectedCallback(){this.root||(this.root=this.attachShadow({mode:"open"}),this.styleEl=document.createElement("style"),this.box=d("div",{class:"ad",part:"root"}),this.root.append(this.styleEl,this.box)),this.paintTheme(),this.unsub=Ie(()=>this.start()),this.start()}disconnectedCallback(){var n;(n=this.unsub)==null||n.call(this),this.unsub=null,this.offEvents.forEach(a=>a()),this.offEvents=[],this.bound=null,this.teardown()}attributeChangedCallback(n){!this.isConnected||!this.root||(this.paintTheme(),this.load())}paintTheme(){const n=H(H({},this.cfgTheme),me(this.getAttribute("theme")));this.styleEl.textContent=he(n)+Ye}start(){const n=this.c;if(!n){this.box.replaceChildren(d("p",{class:"muted"},"ARM Desk is not initialised yet."));return}n!==this.bound&&(this.offEvents.forEach(a=>a()),this.offEvents=this.watch(n),this.bound=n,n.config().then(a=>{this.cfgTheme=a.theme,this.paintTheme()},()=>{})),this.load()}watch(n){return[]}async load(){}teardown(){}fail(n,a){this.box.replaceChildren(d("p",{class:"err",role:"alert"},n instanceof Error?n.message:"Something went wrong."),d("button",{class:"btn ghost",onclick:a},"Try again"))}emit(n,a){this.dispatchEvent(new CustomEvent(n,{detail:a,bubbles:!0,composed:!0}))}}const e=k=>k?new Date(k).toLocaleString():"";class s extends t{constructor(){super(...arguments),this.page=1}watch(n){return[n.on("ticket.created",()=>void this.load()),n.on("ticket.replied",()=>void this.load())]}async load(){const n=this.c;if(!n)return;const a=Math.min(100,Math.max(1,Number(this.getAttribute("limit"))||10));this.box.replaceChildren(d("p",{class:"muted"},"Loading..."));try{const v=await n.tickets.list({status:this.getAttribute("status")||void 0,page:this.page,limit:a});this.draw(v,a)}catch(v){this.fail(v,()=>void this.load())}}draw(n,a){const v=Math.max(1,Math.ceil(n.total/a)),f=n.items.map(l=>{var j;return d("div",{class:"card"},d("button",{class:"row",style:"background:none;border:0;padding:0",onclick:()=>this.emit("armdesk-ticket-select",{id:l.id,number:l.number})},d("span",{},d("strong",{},l.number)," ",l.subject,d("div",{class:"muted"},e((j=l.lastReplyAt)!=null?j:l.updatedAt))),d("span",{class:"badge"},l.status.replace(/_/g," "))))});this.box.replaceChildren(d("h3",{},"My tickets"),...f.length?f:[d("p",{class:"muted"},"No tickets yet.")],d("div",{class:"bar"},d("button",{class:"btn ghost",disabled:this.page<=1,onclick:()=>{this.page--,this.load()}},"Previous"),d("span",{class:"muted"},`${this.page} / ${v}`),d("button",{class:"btn ghost",disabled:this.page>=v,onclick:()=>{this.page++,this.load()}},"Next")))}}class c extends t{async load(){var y,g;const n=this.c;if(!n)return;let a=[],v=!0,f=!0;try{const m=await n.config();v=((y=m.features)==null?void 0:y.attachments)!==!1,f=((g=m.features)==null?void 0:g.newTicket)!==!1,a=await n.categories()}catch(m){}if(!f){this.box.replaceChildren(d("p",{class:"muted"},"Raising tickets is turned off."));return}const l=d("input",{name:"subject",required:!0,minlength:"5",maxlength:"255"}),j=d("textarea",{name:"description",required:!0,minlength:"10",maxlength:"20000",rows:"6"}),F=d("select",{name:"priority"},...["NORMAL","LOW","HIGH","URGENT"].map(m=>d("option",{value:m},m.charAt(0)+m.slice(1).toLowerCase()))),z=d("select",{name:"categoryId"},d("option",{value:""},"None"),...a.map(m=>d("option",{value:m.id},m.name))),C=d("input",{type:"file",multiple:!0}),T=d("p",{role:"status",class:"muted"}),S=d("button",{class:"btn",type:"submit"},"Submit ticket"),R=d("form",{onsubmit:m=>{var w;m.preventDefault(),S.disabled=!0,T.className="muted",T.textContent="Sending...",n.tickets.create({subject:l.value,description:j.value,priority:F.value,categoryId:z.value||void 0,files:Array.from((w=C.files)!=null?w:[])}).then($=>{T.textContent=`Ticket ${$.number} created.`,R.reset(),this.emit("armdesk-ticket-created",$)}).catch($=>{T.className="err",T.textContent=$ instanceof Error?$.message:"Could not create the ticket."}).finally(()=>S.disabled=!1)}},d("label",{},"Subject",l),d("label",{},"Description",j),d("label",{},"Priority",F),a.length?d("label",{},"Category",z):null,v?d("label",{},"Attachments",C):null,S,T);this.box.replaceChildren(d("h3",{},"New ticket"),R)}}class u extends t{watch(n){return[n.on("ticket.replied",a=>a.ticketId===this.getAttribute("ticket-id")&&void this.load())]}async load(){const n=this.c,a=this.getAttribute("ticket-id");if(n){if(!a){this.box.replaceChildren(d("p",{class:"muted"},"Set the ticket-id attribute."));return}try{this.draw(n,await n.tickets.get(a))}catch(v){this.fail(v,()=>void this.load())}}}draw(n,a){const v=a.threads.map(C=>{var R;const T=d("div",{class:"body"});Ge(T,C.body);const S=((R=C.attachments)!=null?R:[]).filter(y=>y.url&&/^(https?:\/|\/)/.test(y.url)).map(y=>d("a",{href:y.url,target:"_blank",rel:"noopener noreferrer"},y.name));return d("div",{class:`card${C.author.isAgent?" agent":""}`},d("div",{class:"muted"},`${C.author.name} - ${e(C.createdAt)}`),T,...S.length?[d("div",{class:"muted"},"Files: ",...S.flatMap(y=>[y," "]))]:[])}),f=d("textarea",{rows:"4",required:!0,minlength:"1","aria-label":"Reply"}),l=d("p",{role:"status",class:"err"}),j=d("button",{class:"btn",type:"submit"},"Send reply"),F=d("form",{onsubmit:C=>{C.preventDefault(),j.disabled=!0,n.tickets.reply(a.id,{body:f.value}).then(()=>this.emit("armdesk-ticket-replied",{id:a.id}),T=>{l.textContent=T instanceof Error?T.message:"Could not send the reply.",j.disabled=!1})}},f,j,l),z=a.canClose?d("button",{class:"btn ghost",onclick:()=>void n.tickets.close(a.id).then(()=>this.load(),C=>this.fail(C,()=>void this.load()))},"Mark as solved"):null;this.box.replaceChildren(d("div",{class:"bar"},d("h3",{},`${a.number} ${a.subject}`),d("span",{class:"badge"},a.status.replace(/_/g," "))),...v,...[a.canReply?F:null,z].filter(C=>C!==null))}}class h extends t{constructor(){super(...arguments),this.ctl=null}static get observedAttributes(){return[...t.observedAttributes,"open","icon-url","offset","aria-label"]}defaultView(){return"home"}get controller(){return this.ctl}open(n){var a;(a=this.ctl)==null||a.open(n)}close(){var n;(n=this.ctl)==null||n.close()}toggle(){var n;(n=this.ctl)==null||n.toggle()}attributeChangedCallback(n){var a,v;if(!(!this.isConnected||!this.root)){if(n==="open"){this.hasAttribute("open")?(a=this.ctl)==null||a.open():(v=this.ctl)==null||v.close();return}if(n==="view"&&this.ctl){const f=this.getAttribute("view");Q(f)&&this.ctl.navigate(f);return}super.attributeChangedCallback(n)}}teardown(){var n;(n=this.ctl)==null||n.destroy(),this.ctl=null}async load(){const n=this.c;if(!n)return;this.teardown(),this.box.replaceChildren();const a=this.getAttribute("view"),v=Number(this.getAttribute("offset")),f=n.messenger({container:this.box,position:this.getAttribute("position")==="left"||this.getAttribute("position")==="bottom-left"?"bottom-left":"bottom-right",label:this.getAttribute("label")||void 0,ariaLabel:this.getAttribute("aria-label")||void 0,iconUrl:this.getAttribute("icon-url")||void 0,offset:this.hasAttribute("offset")&&Number.isFinite(v)?v:void 0,view:Q(a)?a:this.defaultView(),theme:me(this.getAttribute("theme")),open:this.hasAttribute("open")});f.on("open",l=>{this.hasAttribute("open")||this.setAttribute("open",""),this.emit("armdesk-messenger-open",l)}),f.on("close",()=>{this.hasAttribute("open")&&this.removeAttribute("open"),this.emit("armdesk-messenger-close",null)}),f.on("unread",l=>this.emit("armdesk-messenger-unread",l)),this.ctl=f}}class E extends h{defaultView(){return"tickets"}}const b=[["armdesk-tickets",s],["armdesk-new-ticket",c],["armdesk-ticket",u],["armdesk-launcher",E],["armdesk-messenger",h]];for(const[k,n]of b)customElements.get(k)||customElements.define(k,n)}class _ extends Error{constructor(e,s,c=0,u){super(s),this.name="ArmDeskError",this.code=e,this.status=c,this.retryAfter=u}}function Ze(t){return t===401?"unauthorized":t===403?"forbidden":t===404?"not_found":t===409?"conflict":t===429?"rate_limited":t>=500?"server":"validation"}function Qe(t,e,s){const c=e&&typeof e=="object"?e:{};if(typeof c.error=="string"){const h=typeof c.error_description=="string"?c.error_description:c.error;return new _(c.error,h,t,s)}const u=Array.isArray(c.message)?c.message.join("; "):typeof c.message=="string"?c.message:`ARM Desk answered ${t}`;return new _(Ze(t),u,t,s)}const be=3e4,ge=t=>new Promise(e=>setTimeout(e,t));function ye(t){const e=t.headers.get("Retry-After");if(!e)return;const s=Number(e);if(Number.isFinite(s))return Math.max(0,s*1e3);const c=Date.parse(e);return Number.isNaN(c)?void 0:Math.max(0,c-Date.now())}async function X(t,e,s){const c=u=>u===429||(s.method==="GET"?u>=500:u===503);for(let u=0;;u++){const h=new AbortController,E=setTimeout(()=>h.abort(),t.timeoutMs);let b=null,k=null;try{b=await t.fetch(e,{method:s.method,headers:s.headers,body:s.body,credentials:s.credentials,signal:h.signal})}catch(a){k=a}finally{clearTimeout(E)}const n=u>=t.retries;if(b){if(b.ok||!c(b.status)||n)return b;const a=ye(b);await ge(Math.min(be,a!=null?a:t.retryDelayMs*2**u));continue}if(s.method!=="GET"||n)throw new _("network",k instanceof Error?`Could not reach ARM Desk: ${k.message}`:"Could not reach ARM Desk");await ge(Math.min(be,t.retryDelayMs*2**u))}}async function J(t){let e=null;try{e=await t.json()}catch(s){}if(!t.ok){const s=ye(t);throw Qe(t.status,e,s===void 0?void 0:Math.ceil(s/1e3))}if(e==null)throw new _("bad_response","ARM Desk returned an empty response",t.status);return e}const et=380,we=640,Y=56,ke=16,tt=`
20
+ *{box-sizing:border-box}
21
+ .bubble{position:fixed;display:inline-flex;align-items:center;justify-content:center;gap:8px;min-width:${Y}px;height:${Y}px;padding:0 16px;border:0;border-radius:999px;background:var(--ad-primary);color:#fff;font:600 15px/1 var(--ad-font);cursor:pointer;box-shadow:0 6px 20px rgba(0,0,0,.22);transition:transform .2s ease,box-shadow .2s ease}
22
+ .bubble.round{width:${Y}px;padding:0}
23
+ .bubble:hover{transform:scale(1.05);box-shadow:0 8px 26px rgba(0,0,0,.28)}
24
+ .bubble:focus-visible{outline:3px solid var(--ad-primary);outline-offset:3px}
25
+ .bubble svg{width:26px;height:26px;fill:none;stroke:currentColor;stroke-width:2;stroke-linecap:round;stroke-linejoin:round}
26
+ .bubble img{width:28px;height:28px;object-fit:contain}
27
+ .ico{display:inline-flex;transition:transform .2s ease,opacity .2s ease}
28
+ .x{position:absolute;opacity:0;transform:rotate(-90deg)}
29
+ .is-open .ico.main{opacity:0;transform:rotate(90deg)}
30
+ .is-open .x{opacity:1;transform:none}
31
+ .is-open .lbl{display:none}
32
+ .is-open.bubble{width:${Y}px;padding:0}
33
+ .badge{position:absolute;top:-4px;right:-4px;min-width:20px;height:20px;padding:0 6px;border-radius:999px;background:#dc2626;color:#fff;font:700 11px/20px var(--ad-font);text-align:center;border:2px solid #fff}
34
+ .badge[hidden],.is-open .badge{display:none}
35
+ .panel{position:fixed;width:${et}px;height:${we}px;max-height:calc(100vh - var(--ad-y) - ${Y+ke*2}px);background:var(--ad-bg);border:1px solid var(--ad-border);border-radius:16px;overflow:hidden;box-shadow:0 12px 48px rgba(0,0,0,.24);visibility:hidden;opacity:0;transform:translateY(12px) scale(.98);pointer-events:none;transition:opacity .2s ease,transform .2s ease,visibility 0s linear .2s}
36
+ .panel.open{visibility:visible;opacity:1;transform:none;pointer-events:auto;transition-delay:0s}
37
+ .right .panel{transform-origin:bottom right}.left .panel{transform-origin:bottom left}
38
+ .panel iframe{width:100%;height:100% !important;border:0;display:block}
39
+ @media (max-width:480px){.panel{inset:0 !important;width:100%;height:100%;max-height:none;border:0;border-radius:0}.wrap.is-open .bubble{display:none}}
40
+ @media (prefers-reduced-motion:reduce){.bubble,.panel,.ico{transition:none !important}.bubble:hover{transform:none}}
41
+ `,ve="http://www.w3.org/2000/svg";function xe(t){const e=document.createElementNS(ve,"svg");e.setAttribute("viewBox","0 0 24 24"),e.setAttribute("aria-hidden","true");for(const s of t){const c=document.createElementNS(ve,"path");c.setAttribute("d",s),e.appendChild(c)}return e}const rt=["M21 12a8 8 0 0 1-11.6 7.1L4 20.5l1.4-4.9A8 8 0 1 1 21 12z"],nt=["M6 6l12 12","M18 6L6 18"];function re(t,...e){const s=document.createElement("span");return s.className=t,s.append(...e),s}const st=t=>{if(typeof t!="string")return!1;try{return new URL(t).protocol==="https:"}catch(e){return!1}};let at=0;function ot(t,e={}){var x,O,M,D,L,q,N;if(typeof document=="undefined")throw new Error("ArmDeskConnect: the messenger needs a browser");if(e.view!==void 0&&!Q(e.view))throw new Error("ArmDeskConnect: invalid view");const s=e.position==="bottom-left"||e.position==="left"?"left":"right",c=typeof e.offset=="number"?{x:e.offset,y:e.offset}:(x=e.offset)!=null?x:{},u=Math.max(0,Math.round((O=c.x)!=null?O:20)),h=Math.max(0,Math.round((M=c.y)!=null?M:20)),E=Number.isFinite(e.zIndex)?Math.round(e.zIndex):2147483e3,b=e.ariaLabel||e.label||"Support",k=`armdesk-messenger-${++at}`;let n=H({},(D=e.theme)!=null?D:{}),a=!1,v=0,f=!1,l=null,j=(L=e.view)!=null?L:"home";const F=new Map,z=(i,B)=>{var W;(W=F.get(i))==null||W.forEach(bt=>{try{bt(B)}catch(vt){}})},C=document.createElement("div");C.setAttribute("data-armdesk-messenger","");const T=C.attachShadow({mode:"open"}),S=document.createElement("style"),R=document.createElement("div");R.className=`wrap ${s}`,R.setAttribute("part","messenger");const y=document.createElement("button");y.type="button",y.className=`bubble${e.label?"":" round"}`,y.setAttribute("part","bubble"),y.setAttribute("aria-controls",k),y.setAttribute("aria-expanded","false"),y.setAttribute("aria-haspopup","dialog");let g=xe(rt);if(st(e.iconUrl)){const i=document.createElement("img");i.src=e.iconUrl,i.alt="",g=i}const m=re("badge");m.hidden=!0,m.setAttribute("aria-hidden","true"),y.append(re("ico main",g),re("ico x",xe(nt)),...e.label?[re("lbl",document.createTextNode(e.label))]:[],m),y.style.cssText=`${s}:${u}px;bottom:${h}px;z-index:${E}`;const w=document.createElement("div");w.id=k,w.className="panel",w.setAttribute("part","panel"),w.setAttribute("role","dialog"),w.setAttribute("aria-label",b),w.setAttribute("aria-hidden","true"),w.style.cssText=`${s}:${u}px;bottom:${h+Y+ke}px;z-index:${E}`,R.append(w,y),T.append(S,R);const $=()=>{S.textContent=`${he(n)}:host{display:contents;--ad-y:${h}px}${tt}`},G=()=>{const i=a?`Close ${b}`:`Open ${b}`;y.setAttribute("aria-label",v>0&&!a?`${i}, ${v} unread`:i)};$(),G();const P=()=>{l||f||(l=t.mount(w,{view:j,theme:e.theme,features:e.features,locale:e.locale,height:we,host:"messenger",title:b,onEvent:e.onEvent,onError:e.onError,onUnread:i=>V(i),onClose:()=>p()}))},V=i=>{i!==v&&(v=i,m.textContent=i>99?"99+":String(i),m.hidden=i<=0,G(),z("unread",i))},r=i=>{i.key==="Escape"&&a&&(i.stopPropagation(),p())};function o(i){if(f)return;if(i!==void 0&&!Q(i))throw new Error("ArmDeskConnect: invalid view");if(i&&(j=i),P(),a){i&&(l==null||l.open(i));return}a=!0,w.classList.add("open"),R.classList.add("is-open"),y.classList.add("is-open"),w.setAttribute("aria-hidden","false"),y.setAttribute("aria-expanded","true"),G(),l==null||l.open(i),document.addEventListener("keydown",r,!0);const B=w.querySelector("iframe");setTimeout(()=>a&&(B==null?void 0:B.focus()),0),z("open",{view:i!=null?i:null})}function p(){if(f||!a)return;const i=T.activeElement!==null&&w.contains(T.activeElement);a=!1,w.classList.remove("open"),R.classList.remove("is-open"),y.classList.remove("is-open"),w.setAttribute("aria-hidden","true"),y.setAttribute("aria-expanded","false"),G(),document.removeEventListener("keydown",r,!0),i&&y.focus(),z("close",void 0)}return y.addEventListener("click",()=>a?p():o()),w.addEventListener("keydown",r),((q=e.container)!=null?q:document.body).appendChild(C),e.lazy||P(),t.loadTheme&&!((N=e.theme)!=null&&N.primaryColor)&&t.loadTheme().then(i=>{var B;f||!i||(n=H(H({},i),(B=e.theme)!=null?B:{}),$())},()=>{}),e.open&&o(),{open:o,close:p,toggle:()=>a?p():o(),navigate(i){if(!Q(i))throw new Error("ArmDeskConnect: invalid view");j=i,l==null||l.navigate(i)},setTheme(i){n=H({},i),$(),l==null||l.setTheme(i)},isOpen:()=>a,unread:()=>v,on(i,B){let W=F.get(i);return W||F.set(i,W=new Set),W.add(B),()=>W.delete(B)},destroy(){f||(document.removeEventListener("keydown",r,!0),l==null||l.destroy(),l=null,f=!0,F.clear(),C.remove())}}}const it=2e4,Ae=4,ct=400,lt=120,dt=2e4;function ut(t){const e=typeof t=="string"?document.querySelector(t):t;if(!e)throw new Error("ArmDeskConnect: container not found");return e}const ft=t=>new Promise(e=>setTimeout(e,t));function Ee(t,e){var R,y;const s=ut(t),c=ue(e.baseUrl);if(!e.orgKey)throw new Error("ArmDeskConnect: orgKey is required");if(typeof e.getToken!="function")throw new Error("ArmDeskConnect: getToken is required");if(e.view!==void 0&&!te.test(e.view))throw new Error("ArmDeskConnect: invalid view");let u=(R=e.view)!=null?R:"tickets",h=H({},(y=e.theme)!=null?y:{}),E=!1,b=!1,k=null,n=!1,a=null;const v=new URLSearchParams({org:e.orgKey,view:u});e.locale&&_e.includes(e.locale)&&v.set("locale",e.locale);const f=document.createElement("iframe");f.src=`${c}/embed/itsm?${v.toString()}`,f.title=e.title||"Support tickets",f.setAttribute("referrerpolicy","strict-origin"),f.setAttribute("loading","lazy"),f.setAttribute("data-armdesk-connect",""),Object.assign(f.style,{width:"100%",border:"0",display:"block",colorScheme:"normal"}),f.style.height=typeof e.height=="number"?`${e.height}px`:"480px";const l=(g,m)=>{const w=f.contentWindow;b||!w||w.postMessage({source:le,type:g,payload:m},c)},j=g=>{try{g()}catch(m){}},F=(g,m)=>{var w;try{(w=e.onError)==null||w.call(e,{code:g,message:m})}catch($){}},z=()=>k||(k=(async()=>{for(let g=0;g<Ae&&!b;g++)try{const m=await e.getToken();if(typeof m=="string"&&m.length>0&&m.length<=de)return m;throw new Error("getToken returned an invalid token")}catch(m){if(g===Ae-1){F("token_failed",m instanceof Error?m.message:"Could not get a token");break}await ft(ct*2**g)}return null})().finally(()=>{k=null}),k),C=async g=>{var $;const m=await z();if(!m||b)return;if(g==="token"){l("token",{token:m});return}const w={token:m,theme:h,features:($=e.features)!=null?$:{}};e.host&&(w.host=e.host),l("init",w),n=!0,a&&(l("open",a),a=null)};let T=setTimeout(()=>{E||F("timeout","The embed did not respond. Check baseUrl and the organisation's allowed origins.")},it);const S=g=>{var G;if(b||g.origin!==c||g.source!==f.contentWindow||!Re(g.data))return;const{type:m,payload:w}=g.data,$=typeof w=="object"&&w!==null?w:{};switch(m){case"ready":E=!0,T&&clearTimeout(T),T=null,C("init");break;case"request-token":C("token");break;case"resize":{const P=Number($.height);(e.height===void 0||e.height==="auto")&&Number.isFinite(P)&&(f.style.height=`${Math.min(dt,Math.max(lt,Math.ceil(P)))}px`);break}case"event":if(typeof $.name=="string")try{(G=e.onEvent)==null||G.call(e,{name:$.name,data:$.data})}catch(P){}break;case"unread":{const P=Ue(w);P!==null&&j(()=>{var V;return(V=e.onUnread)==null?void 0:V.call(e,P)});break}case"close":j(()=>{var P;return(P=e.onClose)==null?void 0:P.call(e)});break;case"error":F(typeof $.code=="string"?$.code:"error",typeof $.message=="string"?$.message:"Embed error");break}};return window.addEventListener("message",S),s.appendChild(f),{navigate(g){if(!te.test(g))throw new Error("ArmDeskConnect: invalid view");u=g,E&&l("navigate",{view:u})},open(g){if(g!==void 0&&!te.test(g))throw new Error("ArmDeskConnect: invalid view");g&&(u=g);const m=g?{view:g}:{};n?l("open",m):a=m},setTheme(g){h=H({},g),E&&l("theme",{theme:h})},refreshToken:()=>C("token"),destroy(){b||(b=!0,T&&clearTimeout(T),window.removeEventListener("message",S),f.remove())}}}const ht=3e4,Z=840,ee="/connect/v1";function Te(t){var m,w,$,G,P,V;if(!t||!t.orgKey)throw new _("config","ArmDeskConnect: orgKey is required");if(!t.auth||typeof t.auth!="object")throw new _("config","ArmDeskConnect: auth is required");const e=(m=t.desk)!=null?m:Le();if(!e)throw new _("config","ArmDeskConnect: desk is required (it is detected only when the script tag is used)");const s=ue(e),c=($=t.fetch)!=null?$:(w=globalThis.fetch)==null?void 0:w.bind(globalThis);if(typeof c!="function")throw new _("config","fetch is not available");const u={fetch:c,retries:(G=t.retries)!=null?G:2,retryDelayMs:(P=t.retryDelayMs)!=null?P:400,timeoutMs:(V=t.timeoutMs)!=null?V:2e4},h=t.auth,E=new Map,b=(r,o)=>{var p;(p=E.get(r))==null||p.forEach(x=>{try{x(o)}catch(O){}})};let k=null;const n=`${s}/api/proxy`,a=r=>r.replace(/\/+$/,"").replace(/\/connect\/v1$/,""),v=()=>t.apiBase?Promise.resolve(a(t.apiBase)):(k!=null||(k=(async()=>{try{const r=await X(ie(H({},u),{retries:0}),`${n}${ee}/bootstrap?org=${encodeURIComponent(t.orgKey)}`,{method:"GET",headers:{Accept:"application/json"}}),o=await J(r);if(typeof o.apiBase=="string"&&o.apiBase)return a(new URL(o.apiBase,s).toString())}catch(r){}return n})()),k);let f=null,l=null;const j=r=>{if(typeof r.token!="string"||!r.token||r.token.length>de)throw new _("bad_response","ARM Desk returned an invalid token");return f={token:r.token,expiresAt:Date.now()+(Number.isFinite(r.expiresIn)?r.expiresIn:Z)*1e3},r.token},F=async()=>{var x,O,M,D;const r=await v();if("userToken"in h){const L=await h.userToken();if(typeof L!="string"||!L)throw new _("config","userToken() must return the signed user token");const q=new URLSearchParams({grant_type:Pe,assertion:L}),N=await X(u,`${r}${ee}/oauth/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:q.toString()}),i=await J(N);if(typeof i.access_token!="string")throw new _("bad_response","ARM Desk returned no access_token",N.status);return{token:i.access_token,expiresIn:(x=i.expires_in)!=null?x:Z}}if("idToken"in h){const L=await h.idToken(),q={orgKey:t.orgKey,idToken:L};h.nonce&&(q.nonce=h.nonce);const N=await X(u,`${r}${ee}/sessions/browser`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(q)}),i=await J(N);return{token:i.token,expiresIn:(O=i.expiresIn)!=null?O:Z}}if("getToken"in h)return{token:await h.getToken(),expiresIn:Z};const o=await X(u,(M=h.sessionUrl)!=null?M:Fe,{method:"POST",headers:{[qe]:"1",Accept:"application/json"},credentials:"same-origin"}),p=await J(o);return{token:p.token,expiresIn:(D=p.expiresIn)!=null?D:Z}},z=async()=>{var r;if(!("idToken"in h)||!f)return null;try{const o=await v(),p=await X(u,`${o}${ee}/sessions/refresh`,{method:"POST",headers:{Authorization:`Bearer ${f.token}`,Accept:"application/json"}}),x=await J(p);return{token:x.token,expiresIn:(r=x.expiresIn)!=null?r:Z}}catch(o){return null}},C=()=>(l!=null||(l=(async()=>{var r;try{const o=(r=await z())!=null?r:await F();return j(o)}catch(o){const p=f!==null;f=null;const x=o instanceof _?o:new _("session_expired",o instanceof Error?o.message:"Could not sign in");throw p&&b("session.expired",{code:x.code,message:x.message,status:x.status}),b("error",{code:x.code,message:x.message,status:x.status}),x}finally{l=null}})()),l),T=async()=>f&&f.expiresAt-ht>Date.now()?f.token:C(),S=async(r,o=!1)=>{const p=await T(),x=await v(),O=r.query?Object.entries(r.query).filter(([,N])=>N!==void 0&&N!==""):[],M=`${x}${ee}${r.path}${O.length?`?${new URLSearchParams(O.map(([N,i])=>[N,String(i)])).toString()}`:""}`,D={Authorization:`Bearer ${p}`,Accept:"application/json"};let L;r.form?L=r.form:r.json!==void 0&&(D["Content-Type"]="application/json",L=JSON.stringify(r.json));const q=await X(u,M,{method:r.method,headers:D,body:L});if(q.status===401&&!o)return f=null,S(r,!0);try{return await J(q)}catch(N){throw N instanceof _&&!(o&&N.status===401)&&b("error",{code:N.code,message:N.message,status:N.status}),N instanceof _&&N.status===401&&b("session.expired",{code:N.code,message:N.message,status:401}),N}},R=(r,o,p="files")=>{var M;const x=Object.fromEntries(Object.entries(r).filter(([,D])=>D!==void 0&&D!==""));if(!o||o.length===0)return{json:x};const O=new FormData;for(const[D,L]of Object.entries(x))O.append(D,L);for(const D of o)O.append(p,D,(M=D.name)!=null?M:"file");return{form:O}},y=r=>{if(!r||typeof r!="string")throw new _("validation","An id is required");return encodeURIComponent(r)},g={orgKey:t.orgKey,desk:s,me:()=>S({method:"GET",path:"/me"}),config:()=>S({method:"GET",path:"/config",query:{locale:t.locale}}),categories:async()=>{var o;const r=await S({method:"GET",path:"/categories"});return Array.isArray(r)?r:(o=r.items)!=null?o:[]},tickets:{list:(r={})=>S({method:"GET",path:"/tickets",query:{status:Array.isArray(r.status)?r.status.join(","):r.status,search:r.search,page:r.page,limit:r.limit}}),get:async r=>S({method:"GET",path:`/tickets/${y(r)}`}),async create(r){const o=await S(H({method:"POST",path:"/tickets"},R({subject:r.subject,description:r.description,priority:r.priority,categoryId:r.categoryId},r.files)));return b("ticket.created",o),o},async reply(r,o){const p=await S(H({method:"POST",path:`/tickets/${y(r)}/replies`},R({body:o.body},o.files)));return b("ticket.replied",{ticketId:r,reply:p}),p},close:async r=>S({method:"POST",path:`/tickets/${y(r)}/close`})},catalog:{list:(r={})=>S({method:"GET",path:"/catalog",query:{search:r.search,categoryId:r.categoryId}}),async request(r,o={},p={}){var D;const x={answers:JSON.stringify(o),quantity:p.quantity===void 0?void 0:String(p.quantity),requestedForId:p.requestedForId},O=p.files?Object.entries(p.files):[];if(O.length===0){const L={answers:o};return p.quantity!==void 0&&(L.quantity=p.quantity),p.requestedForId&&(L.requestedForId=p.requestedForId),S({method:"POST",path:`/catalog/${y(r)}/requests`,json:L})}const M=new FormData;for(const[L,q]of Object.entries(x))q!==void 0&&M.append(L,q);for(const[L,q]of O)M.append(`file:${L}`,q,(D=q.name)!=null?D:"file");return S({method:"POST",path:`/catalog/${y(r)}/requests`,form:M})}},on(r,o){let p=E.get(r);return p||E.set(r,p=new Set),p.add(o),()=>p.delete(o)},mount(r,o={}){var p,x,O;return Ee(r,{baseUrl:s,orgKey:t.orgKey,getToken:T,view:o.view,theme:(p=o.theme)!=null?p:t.theme,features:(x=o.features)!=null?x:t.features,locale:(O=o.locale)!=null?O:t.locale,height:o.height,host:o.host,title:o.title,onUnread:o.onUnread,onClose:o.onClose,onEvent:M=>{var D;M.name==="ticket.created"&&b("ticket.created",M.data),M.name==="ticket.replied"&&b("ticket.replied",M.data),(D=o.onEvent)==null||D.call(o,M)},onError:M=>{var D;b("error",M),(D=o.onError)==null||D.call(o,M)}})},messenger(r={}){var o,p,x;return ot({mount:(O,M)=>g.mount(O,M),loadTheme:async()=>(await g.config()).theme},ie(H({},r),{theme:(o=r.theme)!=null?o:t.theme,features:(p=r.features)!=null?p:t.features,locale:(x=r.locale)!=null?x:t.locale}))},getAccessToken:T,signOut(){f=null,l=null}};return g}function Ce(t){const e=Te(t);return Oe(e),e}const mt="1.1.0";function pt(t={}){const k=t,{client:e,orgKey:s,auth:c,desk:u,apiBase:h}=k,E=De(k,["client","orgKey","auth","desk","apiBase"]);let b=e!=null?e:null;if(!b&&s&&c&&(b=Ce({orgKey:s,auth:c,desk:u,apiBase:h,theme:E.theme,features:E.features,locale:E.locale})),b!=null||(b=ce()),!b)throw new _("config","ArmDeskConnect.messenger: call init({ orgKey, auth }) first, or pass orgKey and auth");return b.messenger(E)}if(typeof document!="undefined"){const t=document.currentScript;if(t&&t.src)try{Ne(new URL(t.src).origin)}catch(e){}pe()}return A.ArmDeskError=_,A.createClient=Te,A.defineElements=pe,A.init=Ce,A.messenger=pt,A.mount=Ee,A.version=mt,Object.defineProperty(A,Symbol.toStringTag,{value:"Module"}),A}({});
@@ -1,3 +1,3 @@
1
1
  import { defineElements } from "./elements.js";
2
- export { init, createClient, mount, ArmDeskError, VERSION as version } from "./index.js";
2
+ export { init, createClient, messenger, mount, ArmDeskError, VERSION as version } from "./index.js";
3
3
  export { defineElements };
@@ -1,4 +1,4 @@
1
- // Entry of the script-tag build: window.ArmDeskConnect = { init, createClient, mount, version, ... }.
1
+ // Entry of the script-tag build: window.ArmDeskConnect = { init, createClient, messenger, mount, version, ... }.
2
2
  // The desk URL defaults to the origin this script was loaded from, and the web components register themselves.
3
3
  import { setDefaultDesk } from "./defaults.js";
4
4
  import { defineElements } from "./elements.js";
@@ -14,5 +14,5 @@ if (typeof document !== "undefined") {
14
14
  }
15
15
  defineElements();
16
16
  }
17
- export { init, createClient, mount, ArmDeskError, VERSION as version } from "./index.js";
17
+ export { init, createClient, messenger, mount, ArmDeskError, VERSION as version } from "./index.js";
18
18
  export { defineElements };
@@ -1,4 +1,4 @@
1
- import type { Category, ClientEventMap, ClientMountOptions, ClientOptions, ConnectHandle, CatalogRequestOptions, CreatedTicket, CreateTicketInput, DeskConfig, ListTicketsParams, Me, Reply, ReplyInput, TicketDetail, TicketList, Unsubscribe } from "./types.js";
1
+ import type { Category, ClientEventMap, ClientMountOptions, ClientOptions, ConnectHandle, CatalogRequestOptions, CreatedTicket, CreateTicketInput, DeskConfig, ListTicketsParams, Me, MessengerController, MessengerOptions, Reply, ReplyInput, TicketDetail, TicketList, Unsubscribe } from "./types.js";
2
2
  type Listener<K extends keyof ClientEventMap> = (payload: ClientEventMap[K]) => void;
3
3
  export interface ArmDeskClient {
4
4
  readonly orgKey: string;
@@ -28,6 +28,8 @@ export interface ArmDeskClient {
28
28
  on<K extends keyof ClientEventMap>(event: K, cb: Listener<K>): Unsubscribe;
29
29
  /** Mounts the iframe embed (the full ARM Desk portal UI) into an element. */
30
30
  mount(el: HTMLElement | string, options?: ClientMountOptions): ConnectHandle;
31
+ /** The messenger: a floating bubble that opens the support panel (Home, Messages, Help). */
32
+ messenger(options?: MessengerOptions): MessengerController;
31
33
  /** A valid ARM Desk connect token (cached in memory, renewed shortly before it expires). */
32
34
  getAccessToken(): Promise<string>;
33
35
  /** Forget the token and stop; the next call signs in again. */
@@ -1,6 +1,7 @@
1
1
  import { ArmDeskError } from "./errors.js";
2
2
  import { getDefaultDesk, setCurrentClient } from "./defaults.js";
3
3
  import { readJson, send } from "./http.js";
4
+ import { createMessenger } from "./messenger.js";
4
5
  import { mount } from "./mount.js";
5
6
  import { CSRF_HEADER, DEFAULT_SESSION_PATH, deskOrigin, JWT_BEARER_GRANT, MAX_TOKEN_LENGTH } from "./protocol.js";
6
7
  const EXPIRY_MARGIN_MS = 30000;
@@ -267,6 +268,10 @@ export function createClient(options) {
267
268
  features: (_b = o.features) !== null && _b !== void 0 ? _b : options.features,
268
269
  locale: (_c = o.locale) !== null && _c !== void 0 ? _c : options.locale,
269
270
  height: o.height,
271
+ host: o.host,
272
+ title: o.title,
273
+ onUnread: o.onUnread,
274
+ onClose: o.onClose,
270
275
  onEvent: (e) => {
271
276
  var _a;
272
277
  if (e.name === "ticket.created")
@@ -282,6 +287,10 @@ export function createClient(options) {
282
287
  },
283
288
  });
284
289
  },
290
+ messenger(o = {}) {
291
+ var _a, _b, _c;
292
+ return createMessenger({ mount: (el, mo) => client.mount(el, mo), loadTheme: async () => (await client.config()).theme }, { ...o, theme: (_a = o.theme) !== null && _a !== void 0 ? _a : options.theme, features: (_b = o.features) !== null && _b !== void 0 ? _b : options.features, locale: (_c = o.locale) !== null && _c !== void 0 ? _c : options.locale });
293
+ },
285
294
  getAccessToken,
286
295
  signOut() {
287
296
  grant = null;
@@ -1,3 +1,3 @@
1
- export declare const ELEMENT_TAGS: readonly ["armdesk-tickets", "armdesk-new-ticket", "armdesk-ticket", "armdesk-launcher"];
2
- /** Registers the four custom elements (idempotent; a no-op without a browser). */
1
+ export declare const ELEMENT_TAGS: readonly ["armdesk-tickets", "armdesk-new-ticket", "armdesk-ticket", "armdesk-launcher", "armdesk-messenger"];
2
+ /** Registers the custom elements (idempotent; a no-op without a browser). */
3
3
  export declare function defineElements(): void;