@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.
Files changed (49) hide show
  1. package/CHANGELOG.md +41 -0
  2. package/LICENSE.txt +15 -0
  3. package/README.md +525 -3
  4. package/dist/armdesk-connect.js +41 -0
  5. package/dist/esm/browser.d.ts +3 -0
  6. package/dist/esm/browser.js +18 -0
  7. package/dist/esm/client.d.ts +46 -0
  8. package/dist/esm/client.js +307 -0
  9. package/dist/esm/defaults.d.ts +8 -0
  10. package/dist/esm/defaults.js +22 -0
  11. package/dist/esm/elements.d.ts +3 -0
  12. package/dist/esm/elements.js +368 -0
  13. package/dist/esm/errors.d.ts +12 -0
  14. package/dist/esm/errors.js +34 -0
  15. package/dist/esm/handler.d.ts +40 -0
  16. package/dist/esm/handler.js +106 -0
  17. package/dist/esm/http.d.ts +22 -0
  18. package/dist/esm/http.js +66 -0
  19. package/dist/esm/index.d.ts +30 -0
  20. package/dist/esm/index.js +30 -0
  21. package/dist/esm/messenger.d.ts +8 -0
  22. package/dist/esm/messenger.js +269 -0
  23. package/dist/esm/mount.d.ts +8 -0
  24. package/dist/esm/mount.js +213 -0
  25. package/dist/esm/protocol.d.ts +37 -0
  26. package/dist/esm/protocol.js +57 -0
  27. package/dist/esm/react.d.ts +89 -0
  28. package/dist/esm/react.js +311 -0
  29. package/dist/esm/register.d.ts +1 -0
  30. package/dist/esm/register.js +5 -0
  31. package/dist/esm/sanitize.d.ts +8 -0
  32. package/dist/esm/sanitize.js +57 -0
  33. package/dist/esm/server.d.ts +17 -0
  34. package/dist/esm/server.js +93 -0
  35. package/dist/esm/sign.d.ts +54 -0
  36. package/dist/esm/sign.js +77 -0
  37. package/dist/esm/theme.d.ts +8 -0
  38. package/dist/esm/theme.js +46 -0
  39. package/dist/esm/types.d.ts +375 -0
  40. package/dist/esm/types.js +1 -0
  41. package/examples/express-server/package.json +10 -0
  42. package/examples/express-server/server.mjs +35 -0
  43. package/examples/mock-idp.mjs +30 -0
  44. package/examples/react-vite/index.html +11 -0
  45. package/examples/react-vite/package.json +15 -0
  46. package/examples/react-vite/src/main.jsx +25 -0
  47. package/examples/react-vite/vite.config.js +4 -0
  48. package/examples/wso2-browser.html +86 -0
  49. package/package.json +59 -4
@@ -0,0 +1,41 @@
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
+ *{box-sizing:border-box}
3
+ .ad{font-family:var(--ad-font);color:var(--ad-text);background:var(--ad-bg);font-size:14px;line-height:1.45}
4
+ .ad h3{margin:0 0 8px;font-size:16px}
5
+ .card{background:var(--ad-surface);border:1px solid var(--ad-border);border-radius:var(--ad-radius);padding:var(--ad-pad);margin:0 0 8px}
6
+ .row{display:flex;gap:8px;align-items:center;justify-content:space-between;width:100%;text-align:left;font:inherit;color:inherit;cursor:pointer}
7
+ .muted{color:var(--ad-muted);font-size:12px}
8
+ .badge{border:1px solid var(--ad-border);border-radius:999px;padding:0 8px;font-size:12px;color:var(--ad-muted);white-space:nowrap}
9
+ button,input,select,textarea{font:inherit;color:inherit}
10
+ input,select,textarea{width:100%;background:var(--ad-bg);border:1px solid var(--ad-border);border-radius:var(--ad-radius);padding:var(--ad-pad)}
11
+ .btn{background:var(--ad-primary);color:#fff;border:0;border-radius:var(--ad-radius);padding:var(--ad-pad);cursor:pointer}
12
+ .btn.ghost{background:transparent;color:var(--ad-primary);border:1px solid var(--ad-border)}
13
+ .btn[disabled]{opacity:.6;cursor:default}
14
+ label{display:block;margin:0 0 10px}
15
+ .err{color:#b91c1c}
16
+ .agent{border-left:3px solid var(--ad-primary)}
17
+ .body a{color:var(--ad-primary)}.body pre{white-space:pre-wrap;overflow:auto}
18
+ .bar{display:flex;gap:8px;justify-content:space-between;align-items:center}
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}({});
@@ -0,0 +1,3 @@
1
+ import { defineElements } from "./elements.js";
2
+ export { init, createClient, messenger, mount, ArmDeskError, VERSION as version } from "./index.js";
3
+ export { defineElements };
@@ -0,0 +1,18 @@
1
+ // Entry of the script-tag build: window.ArmDeskConnect = { init, createClient, messenger, mount, version, ... }.
2
+ // The desk URL defaults to the origin this script was loaded from, and the web components register themselves.
3
+ import { setDefaultDesk } from "./defaults.js";
4
+ import { defineElements } from "./elements.js";
5
+ if (typeof document !== "undefined") {
6
+ const script = document.currentScript;
7
+ if (script && script.src) {
8
+ try {
9
+ setDefaultDesk(new URL(script.src).origin);
10
+ }
11
+ catch (_a) {
12
+ // keep the explicit `desk` option as the only way
13
+ }
14
+ }
15
+ defineElements();
16
+ }
17
+ export { init, createClient, messenger, mount, ArmDeskError, VERSION as version } from "./index.js";
18
+ export { defineElements };
@@ -0,0 +1,46 @@
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
+ type Listener<K extends keyof ClientEventMap> = (payload: ClientEventMap[K]) => void;
3
+ export interface ArmDeskClient {
4
+ readonly orgKey: string;
5
+ /** The desk's origin. */
6
+ readonly desk: string;
7
+ me(): Promise<Me>;
8
+ config(): Promise<DeskConfig>;
9
+ categories(): Promise<Category[]>;
10
+ tickets: {
11
+ list(params?: ListTicketsParams): Promise<TicketList>;
12
+ get(id: string): Promise<TicketDetail>;
13
+ create(input: CreateTicketInput): Promise<CreatedTicket>;
14
+ reply(id: string, input: ReplyInput): Promise<Reply>;
15
+ close(id: string): Promise<{
16
+ id: string;
17
+ number: string;
18
+ status: string;
19
+ }>;
20
+ };
21
+ catalog: {
22
+ list(params?: {
23
+ search?: string;
24
+ categoryId?: string;
25
+ }): Promise<unknown>;
26
+ request(itemId: string, answers?: Record<string, unknown>, options?: CatalogRequestOptions): Promise<unknown>;
27
+ };
28
+ on<K extends keyof ClientEventMap>(event: K, cb: Listener<K>): Unsubscribe;
29
+ /** Mounts the iframe embed (the full ARM Desk portal UI) into an element. */
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;
33
+ /** A valid ARM Desk connect token (cached in memory, renewed shortly before it expires). */
34
+ getAccessToken(): Promise<string>;
35
+ /** Forget the token and stop; the next call signs in again. */
36
+ signOut(): void;
37
+ }
38
+ /**
39
+ * The headless client: typed, Promise-based, no endpoint strings for the caller. It signs in with the `auth` option,
40
+ * keeps the connect token in memory only, renews it before it expires, retries 429 / 5xx with backoff and throws
41
+ * `ArmDeskError` for everything else.
42
+ */
43
+ export declare function createClient(options: ClientOptions): ArmDeskClient;
44
+ /** `ArmDeskConnect.init(...)`: createClient, and make it the client the web components use. */
45
+ export declare function init(options: ClientOptions): ArmDeskClient;
46
+ export {};
@@ -0,0 +1,307 @@
1
+ import { ArmDeskError } from "./errors.js";
2
+ import { getDefaultDesk, setCurrentClient } from "./defaults.js";
3
+ import { readJson, send } from "./http.js";
4
+ import { createMessenger } from "./messenger.js";
5
+ import { mount } from "./mount.js";
6
+ import { CSRF_HEADER, DEFAULT_SESSION_PATH, deskOrigin, JWT_BEARER_GRANT, MAX_TOKEN_LENGTH } from "./protocol.js";
7
+ const EXPIRY_MARGIN_MS = 30000;
8
+ const DEFAULT_TOKEN_TTL_S = 840;
9
+ const V1 = "/connect/v1";
10
+ /**
11
+ * The headless client: typed, Promise-based, no endpoint strings for the caller. It signs in with the `auth` option,
12
+ * keeps the connect token in memory only, renews it before it expires, retries 429 / 5xx with backoff and throws
13
+ * `ArmDeskError` for everything else.
14
+ */
15
+ export function createClient(options) {
16
+ var _a, _b, _c, _d, _e, _f;
17
+ if (!options || !options.orgKey)
18
+ throw new ArmDeskError("config", "ArmDeskConnect: orgKey is required");
19
+ if (!options.auth || typeof options.auth !== "object")
20
+ throw new ArmDeskError("config", "ArmDeskConnect: auth is required");
21
+ const deskUrl = (_a = options.desk) !== null && _a !== void 0 ? _a : getDefaultDesk();
22
+ if (!deskUrl)
23
+ throw new ArmDeskError("config", "ArmDeskConnect: desk is required (it is detected only when the script tag is used)");
24
+ const desk = deskOrigin(deskUrl);
25
+ const doFetch = (_b = options.fetch) !== null && _b !== void 0 ? _b : (_c = globalThis.fetch) === null || _c === void 0 ? void 0 : _c.bind(globalThis);
26
+ if (typeof doFetch !== "function")
27
+ throw new ArmDeskError("config", "fetch is not available");
28
+ const http = { fetch: doFetch, retries: (_d = options.retries) !== null && _d !== void 0 ? _d : 2, retryDelayMs: (_e = options.retryDelayMs) !== null && _e !== void 0 ? _e : 400, timeoutMs: (_f = options.timeoutMs) !== null && _f !== void 0 ? _f : 20000 };
29
+ const auth = options.auth;
30
+ const listeners = new Map();
31
+ const emit = (event, payload) => {
32
+ var _a;
33
+ (_a = listeners.get(event)) === null || _a === void 0 ? void 0 : _a.forEach((cb) => {
34
+ try {
35
+ cb(payload);
36
+ }
37
+ catch (_a) {
38
+ // a throwing host listener must not break the client
39
+ }
40
+ });
41
+ };
42
+ // ---- where the API lives ------------------------------------------------
43
+ let apiPromise = null;
44
+ const fallbackApi = `${desk}/api/proxy`;
45
+ // The desk's bootstrap answers with the versioned base (`…/api/connect/v1`); every call
46
+ // below appends V1 itself, so accept both spellings and keep the unversioned root.
47
+ const root = (u) => u.replace(/\/+$/, "").replace(/\/connect\/v1$/, "");
48
+ const apiBase = () => {
49
+ if (options.apiBase)
50
+ return Promise.resolve(root(options.apiBase));
51
+ apiPromise !== null && apiPromise !== void 0 ? apiPromise : (apiPromise = (async () => {
52
+ try {
53
+ const res = await send({ ...http, retries: 0 }, `${fallbackApi}${V1}/bootstrap?org=${encodeURIComponent(options.orgKey)}`, { method: "GET", headers: { Accept: "application/json" } });
54
+ const b = await readJson(res);
55
+ if (typeof b.apiBase === "string" && b.apiBase)
56
+ return root(new URL(b.apiBase, desk).toString());
57
+ }
58
+ catch (_a) {
59
+ // an older desk without bootstrap: use the web proxy
60
+ }
61
+ return fallbackApi;
62
+ })());
63
+ return apiPromise;
64
+ };
65
+ // ---- sign-in and the token cache ---------------------------------------
66
+ let grant = null;
67
+ let inflight = null;
68
+ const keep = (g) => {
69
+ if (typeof g.token !== "string" || !g.token || g.token.length > MAX_TOKEN_LENGTH)
70
+ throw new ArmDeskError("bad_response", "ARM Desk returned an invalid token");
71
+ grant = { token: g.token, expiresAt: Date.now() + (Number.isFinite(g.expiresIn) ? g.expiresIn : DEFAULT_TOKEN_TTL_S) * 1000 };
72
+ return g.token;
73
+ };
74
+ const exchange = async () => {
75
+ var _a, _b, _c, _d;
76
+ const api = await apiBase();
77
+ if ("userToken" in auth) {
78
+ const assertion = await auth.userToken();
79
+ if (typeof assertion !== "string" || !assertion)
80
+ throw new ArmDeskError("config", "userToken() must return the signed user token");
81
+ const form = new URLSearchParams({ grant_type: JWT_BEARER_GRANT, assertion });
82
+ const res = await send(http, `${api}${V1}/oauth/token`, { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded", Accept: "application/json" }, body: form.toString() });
83
+ const r = await readJson(res);
84
+ if (typeof r.access_token !== "string")
85
+ throw new ArmDeskError("bad_response", "ARM Desk returned no access_token", res.status);
86
+ return { token: r.access_token, expiresIn: (_a = r.expires_in) !== null && _a !== void 0 ? _a : DEFAULT_TOKEN_TTL_S };
87
+ }
88
+ if ("idToken" in auth) {
89
+ const idToken = await auth.idToken();
90
+ const body = { orgKey: options.orgKey, idToken };
91
+ if (auth.nonce)
92
+ body.nonce = auth.nonce;
93
+ const res = await send(http, `${api}${V1}/sessions/browser`, { method: "POST", headers: { "Content-Type": "application/json", Accept: "application/json" }, body: JSON.stringify(body) });
94
+ const r = await readJson(res);
95
+ return { token: r.token, expiresIn: (_b = r.expiresIn) !== null && _b !== void 0 ? _b : DEFAULT_TOKEN_TTL_S };
96
+ }
97
+ if ("getToken" in auth) {
98
+ return { token: await auth.getToken(), expiresIn: DEFAULT_TOKEN_TTL_S };
99
+ }
100
+ // server mode: YOUR route, created by createConnectHandler
101
+ const res = await send(http, (_c = auth.sessionUrl) !== null && _c !== void 0 ? _c : DEFAULT_SESSION_PATH, {
102
+ method: "POST",
103
+ headers: { [CSRF_HEADER]: "1", Accept: "application/json" },
104
+ credentials: "same-origin",
105
+ });
106
+ const r = await readJson(res);
107
+ return { token: r.token, expiresIn: (_d = r.expiresIn) !== null && _d !== void 0 ? _d : DEFAULT_TOKEN_TTL_S };
108
+ };
109
+ /** Browser OIDC mode renews with the still-valid (or just expired) token first, so the host is asked for an ID token only when that fails. */
110
+ const refresh = async () => {
111
+ var _a;
112
+ if (!("idToken" in auth) || !grant)
113
+ return null;
114
+ try {
115
+ const api = await apiBase();
116
+ const res = await send(http, `${api}${V1}/sessions/refresh`, { method: "POST", headers: { Authorization: `Bearer ${grant.token}`, Accept: "application/json" } });
117
+ const r = await readJson(res);
118
+ return { token: r.token, expiresIn: (_a = r.expiresIn) !== null && _a !== void 0 ? _a : DEFAULT_TOKEN_TTL_S };
119
+ }
120
+ catch (_b) {
121
+ return null;
122
+ }
123
+ };
124
+ const signIn = () => {
125
+ inflight !== null && inflight !== void 0 ? inflight : (inflight = (async () => {
126
+ var _a;
127
+ try {
128
+ const g = (_a = (await refresh())) !== null && _a !== void 0 ? _a : (await exchange());
129
+ return keep(g);
130
+ }
131
+ catch (err) {
132
+ const hadSession = grant !== null;
133
+ grant = null;
134
+ const e = err instanceof ArmDeskError ? err : new ArmDeskError("session_expired", err instanceof Error ? err.message : "Could not sign in");
135
+ if (hadSession)
136
+ emit("session.expired", { code: e.code, message: e.message, status: e.status });
137
+ emit("error", { code: e.code, message: e.message, status: e.status });
138
+ throw e;
139
+ }
140
+ finally {
141
+ inflight = null;
142
+ }
143
+ })());
144
+ return inflight;
145
+ };
146
+ const getAccessToken = async () => {
147
+ if (grant && grant.expiresAt - EXPIRY_MARGIN_MS > Date.now())
148
+ return grant.token;
149
+ return signIn();
150
+ };
151
+ const call = async (r, retried = false) => {
152
+ const token = await getAccessToken();
153
+ const api = await apiBase();
154
+ const qs = r.query ? Object.entries(r.query).filter(([, v]) => v !== undefined && v !== "") : [];
155
+ const url = `${api}${V1}${r.path}${qs.length ? `?${new URLSearchParams(qs.map(([k, v]) => [k, String(v)])).toString()}` : ""}`;
156
+ const headers = { Authorization: `Bearer ${token}`, Accept: "application/json" };
157
+ let body;
158
+ if (r.form)
159
+ body = r.form;
160
+ else if (r.json !== undefined) {
161
+ headers["Content-Type"] = "application/json";
162
+ body = JSON.stringify(r.json);
163
+ }
164
+ const res = await send(http, url, { method: r.method, headers, body });
165
+ if (res.status === 401 && !retried) {
166
+ grant = null; // the token was refused (revoked / expired early): sign in once more
167
+ return call(r, true);
168
+ }
169
+ try {
170
+ return await readJson(res);
171
+ }
172
+ catch (err) {
173
+ if (err instanceof ArmDeskError && !(retried && err.status === 401))
174
+ emit("error", { code: err.code, message: err.message, status: err.status });
175
+ if (err instanceof ArmDeskError && err.status === 401)
176
+ emit("session.expired", { code: err.code, message: err.message, status: 401 });
177
+ throw err;
178
+ }
179
+ };
180
+ const withFiles = (fields, files, fileField = "files") => {
181
+ var _a;
182
+ const clean = Object.fromEntries(Object.entries(fields).filter(([, v]) => v !== undefined && v !== ""));
183
+ if (!files || files.length === 0)
184
+ return { json: clean };
185
+ const form = new FormData();
186
+ for (const [k, v] of Object.entries(clean))
187
+ form.append(k, v);
188
+ for (const f of files)
189
+ form.append(fileField, f, (_a = f.name) !== null && _a !== void 0 ? _a : "file");
190
+ return { form };
191
+ };
192
+ const id = (v) => {
193
+ if (!v || typeof v !== "string")
194
+ throw new ArmDeskError("validation", "An id is required");
195
+ return encodeURIComponent(v);
196
+ };
197
+ const client = {
198
+ orgKey: options.orgKey,
199
+ desk,
200
+ me: () => call({ method: "GET", path: "/me" }),
201
+ config: () => call({ method: "GET", path: "/config", query: { locale: options.locale } }),
202
+ categories: async () => {
203
+ var _a;
204
+ const d = await call({ method: "GET", path: "/categories" });
205
+ return Array.isArray(d) ? d : (_a = d.items) !== null && _a !== void 0 ? _a : [];
206
+ },
207
+ tickets: {
208
+ list: (p = {}) => call({
209
+ method: "GET",
210
+ path: "/tickets",
211
+ query: { status: Array.isArray(p.status) ? p.status.join(",") : p.status, search: p.search, page: p.page, limit: p.limit },
212
+ }),
213
+ get: async (tid) => call({ method: "GET", path: `/tickets/${id(tid)}` }),
214
+ async create(input) {
215
+ const t = await call({
216
+ method: "POST",
217
+ path: "/tickets",
218
+ ...withFiles({ subject: input.subject, description: input.description, priority: input.priority, categoryId: input.categoryId }, input.files),
219
+ });
220
+ emit("ticket.created", t);
221
+ return t;
222
+ },
223
+ async reply(tid, input) {
224
+ const reply = await call({ method: "POST", path: `/tickets/${id(tid)}/replies`, ...withFiles({ body: input.body }, input.files) });
225
+ emit("ticket.replied", { ticketId: tid, reply });
226
+ return reply;
227
+ },
228
+ close: async (tid) => call({ method: "POST", path: `/tickets/${id(tid)}/close` }),
229
+ },
230
+ catalog: {
231
+ list: (p = {}) => call({ method: "GET", path: "/catalog", query: { search: p.search, categoryId: p.categoryId } }),
232
+ async request(itemId, answers = {}, o = {}) {
233
+ var _a;
234
+ const fields = { answers: JSON.stringify(answers), quantity: o.quantity === undefined ? undefined : String(o.quantity), requestedForId: o.requestedForId };
235
+ const files = o.files ? Object.entries(o.files) : [];
236
+ if (files.length === 0) {
237
+ const json = { answers };
238
+ if (o.quantity !== undefined)
239
+ json.quantity = o.quantity;
240
+ if (o.requestedForId)
241
+ json.requestedForId = o.requestedForId;
242
+ return call({ method: "POST", path: `/catalog/${id(itemId)}/requests`, json });
243
+ }
244
+ const form = new FormData();
245
+ for (const [k, v] of Object.entries(fields))
246
+ if (v !== undefined)
247
+ form.append(k, v);
248
+ for (const [variable, f] of files)
249
+ form.append(`file:${variable}`, f, (_a = f.name) !== null && _a !== void 0 ? _a : "file");
250
+ return call({ method: "POST", path: `/catalog/${id(itemId)}/requests`, form });
251
+ },
252
+ },
253
+ on(event, cb) {
254
+ let set = listeners.get(event);
255
+ if (!set)
256
+ listeners.set(event, (set = new Set()));
257
+ set.add(cb);
258
+ return () => set.delete(cb);
259
+ },
260
+ mount(el, o = {}) {
261
+ var _a, _b, _c;
262
+ return mount(el, {
263
+ baseUrl: desk,
264
+ orgKey: options.orgKey,
265
+ getToken: getAccessToken,
266
+ view: o.view,
267
+ theme: (_a = o.theme) !== null && _a !== void 0 ? _a : options.theme,
268
+ features: (_b = o.features) !== null && _b !== void 0 ? _b : options.features,
269
+ locale: (_c = o.locale) !== null && _c !== void 0 ? _c : options.locale,
270
+ height: o.height,
271
+ host: o.host,
272
+ title: o.title,
273
+ onUnread: o.onUnread,
274
+ onClose: o.onClose,
275
+ onEvent: (e) => {
276
+ var _a;
277
+ if (e.name === "ticket.created")
278
+ emit("ticket.created", e.data);
279
+ if (e.name === "ticket.replied")
280
+ emit("ticket.replied", e.data);
281
+ (_a = o.onEvent) === null || _a === void 0 ? void 0 : _a.call(o, e);
282
+ },
283
+ onError: (e) => {
284
+ var _a;
285
+ emit("error", e);
286
+ (_a = o.onError) === null || _a === void 0 ? void 0 : _a.call(o, e);
287
+ },
288
+ });
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
+ },
294
+ getAccessToken,
295
+ signOut() {
296
+ grant = null;
297
+ inflight = null;
298
+ },
299
+ };
300
+ return client;
301
+ }
302
+ /** `ArmDeskConnect.init(...)`: createClient, and make it the client the web components use. */
303
+ export function init(options) {
304
+ const client = createClient(options);
305
+ setCurrentClient(client);
306
+ return client;
307
+ }
@@ -0,0 +1,8 @@
1
+ import type { ArmDeskClient } from "./client.js";
2
+ /** The IIFE build records the origin its script tag was loaded from, so only `orgKey` is needed. */
3
+ export declare function setDefaultDesk(origin: string | undefined): void;
4
+ export declare function getDefaultDesk(): string | undefined;
5
+ /** The client the web components use when they are not given one (the last `init()`). */
6
+ export declare function setCurrentClient(client: ArmDeskClient | null): void;
7
+ export declare function getCurrentClient(): ArmDeskClient | null;
8
+ export declare function onCurrentClient(cb: (c: ArmDeskClient | null) => void): () => void;
@@ -0,0 +1,22 @@
1
+ let defaultDesk;
2
+ let current = null;
3
+ const listeners = new Set();
4
+ /** The IIFE build records the origin its script tag was loaded from, so only `orgKey` is needed. */
5
+ export function setDefaultDesk(origin) {
6
+ defaultDesk = origin;
7
+ }
8
+ export function getDefaultDesk() {
9
+ return defaultDesk;
10
+ }
11
+ /** The client the web components use when they are not given one (the last `init()`). */
12
+ export function setCurrentClient(client) {
13
+ current = client;
14
+ listeners.forEach((l) => l(client));
15
+ }
16
+ export function getCurrentClient() {
17
+ return current;
18
+ }
19
+ export function onCurrentClient(cb) {
20
+ listeners.add(cb);
21
+ return () => listeners.delete(cb);
22
+ }
@@ -0,0 +1,3 @@
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
+ export declare function defineElements(): void;