@cognitiv-traits/traitos-ui 0.0.0-stage → 0.2.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.
@@ -0,0 +1,247 @@
1
+ (()=>{var Js=Object.defineProperty;var Zt=(n,e)=>{for(var t in e)Js(n,t,{get:e[t],enumerable:!0})};var Wt={};Zt(Wt,{CORNERS:()=>At,CallLog:()=>W,DAYS:()=>Lt,DEFAULT_SOUND:()=>ge,DEFAULT_STRINGS:()=>se,DIGITS:()=>B,DTMF_FREQ:()=>Le,FlowBuilderController:()=>de,KEYS:()=>Re,KEY_TONES:()=>be,MIN_DIGITS:()=>es,PhoneBase:()=>K,RINGTONES:()=>ne,SECTIONS:()=>N,SOFTPHONE_HEARTBEAT_MS:()=>as,SettingsController:()=>le,SoftphoneController:()=>ie,TARGET_LABEL:()=>Mt,TARGET_TYPES:()=>et,TokenManager:()=>rt,TraitElement:()=>O,TraitOSDialerWidget:()=>ke,TraitOSFlowBuilder:()=>Ae,TraitOSKeypad:()=>ye,TraitOSSettings:()=>Te,TraitOSSoftphone:()=>we,addRoute:()=>Ht,baseCss:()=>Ie,callerLabel:()=>re,canCall:()=>qe,capsFromLines:()=>Me,cleanDialInput:()=>De,createDialpad:()=>te,createOpenState:()=>Je,createSound:()=>ae,defaultChannel:()=>vt,define:()=>A,defineAll:()=>Nn,describeFlow:()=>Ft,digitsOf:()=>me,emptyFlow:()=>tt,enabledChannels:()=>ee,escapeHtml:()=>bt,formatDuration:()=>_e,html:()=>d,iconLabel:()=>Ye,isE164:()=>z,loadPrefs:()=>Fe,moveRoute:()=>Cn,nextFreeDigit:()=>ps,normalizeFlow:()=>Ce,normalizePrefs:()=>U,normalizeSound:()=>Y,panelSide:()=>Ge,placementOf:()=>Be,raw:()=>k,registrationFor:()=>We,removeRoute:()=>Ut,renderCallControls:()=>xe,renderFlowBuilder:()=>zt,renderKeypad:()=>H,renderRecentCalls:()=>$e,renderSettings:()=>Rt,renderSoftphone:()=>Ot,renderSoundOptions:()=>oe,renderWidget:()=>Nt,sanitizeNumber:()=>_t,savePrefs:()=>ze,setDefaultStrings:()=>ss,setGreeting:()=>Dt,setHours:()=>G,setMenu:()=>Ee,setRoute:()=>nt,setSpam:()=>st,softphoneLabel:()=>St,stateForCall:()=>kt,storedPrefs:()=>Ke,stringsFor:()=>q,t:()=>R,telnyxAdapter:()=>hs,toggleDay:()=>jt,validateFlow:()=>Oe});var Ys={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},bt=n=>String(n!=null?n:"").replace(/[&<>"']/g,e=>Ys[e]),fe=class{constructor(e){this.value=e}toString(){return this.value}},k=n=>new fe(String(n)),Qt=n=>n instanceof fe?n.value:Array.isArray(n)?n.map(Qt).join(""):n===!1||n===null||n===void 0?"":bt(n);function d(n,...e){let t=n[0];for(let s=0;s<e.length;s++)t+=Qt(e[s])+n[s+1];return new fe(t)}var Ie=`
2
+ :host { display: block; font: var(--traitos-font, 14px/1.45 system-ui, -apple-system, 'Segoe UI', sans-serif); color: var(--traitos-text, var(--_text));
3
+ --_text: #1b1f24; --_accent: var(--traitos-accent, #4f46e5); --_bg: var(--traitos-bg, #fff); --_alt: var(--traitos-key-bg, #f4f6f8); --_muted: var(--traitos-muted, #5b6470); --_line: var(--traitos-line, #d8dde3);
4
+ --_ok: var(--traitos-ok, #137a3d); --_warn: var(--traitos-warn, #a15c00); --_bad: var(--traitos-danger, #b3261e); --_r: var(--traitos-radius, 10px); --_wa: var(--traitos-whatsapp, #137a3d); --_ph: var(--traitos-phone, #0b6bb5);
5
+ --_accfill: var(--traitos-accent, #4f46e5); --_okfill: var(--traitos-ok, #137a3d); --_badfill: var(--traitos-danger, #b3261e); }
6
+ @media (prefers-color-scheme: dark) { :host(:not([theme=light])) { --_text: #e8ebef; --_accent: var(--traitos-accent, #8b87ff); --_bg: var(--traitos-bg, #181b20); --_alt: var(--traitos-key-bg, #232830); --_muted: var(--traitos-muted, #a4adb9); --_line: var(--traitos-line, #343b45);
7
+ --_ok: var(--traitos-ok, #4cc57e); --_warn: var(--traitos-warn, #e0a23a); --_bad: var(--traitos-danger, #ff7a70); --_wa: var(--traitos-whatsapp, #1f8a4d); --_ph: var(--traitos-phone, #2b7fc9);
8
+ --_accfill: var(--traitos-accent, #5b57d6); --_okfill: var(--traitos-ok, #1b7f45); --_badfill: var(--traitos-danger, #c9372c); } }
9
+ :host([theme=dark]) { --_text: #e8ebef; --_accent: var(--traitos-accent, #8b87ff); --_bg: var(--traitos-bg, #181b20); --_alt: var(--traitos-key-bg, #232830); --_muted: var(--traitos-muted, #a4adb9); --_line: var(--traitos-line, #343b45);
10
+ --_ok: var(--traitos-ok, #4cc57e); --_warn: var(--traitos-warn, #e0a23a); --_bad: var(--traitos-danger, #ff7a70); --_wa: var(--traitos-whatsapp, #1f8a4d); --_ph: var(--traitos-phone, #2b7fc9);
11
+ --_accfill: var(--traitos-accent, #5b57d6); --_okfill: var(--traitos-ok, #1b7f45); --_badfill: var(--traitos-danger, #c9372c); }
12
+ * { box-sizing: border-box; }
13
+ .card { background: var(--_bg); border: 1px solid var(--_line); border-radius: var(--_r); padding: 16px; }
14
+ h2 { font-size: 15px; margin: 0 0 4px; } h3 { font-size: 13px; margin: 16px 0 6px; color: var(--_muted); text-transform: uppercase; letter-spacing: .04em; }
15
+ p.hint, .hint { color: var(--_muted); font-size: 12.5px; margin: 2px 0 8px; }
16
+ label { display: block; font-weight: 600; font-size: 13px; margin: 10px 0 4px; }
17
+ input, select, textarea { width: 100%; font: inherit; color: inherit; background: var(--_bg); border: 1px solid var(--_line); border-radius: calc(var(--_r) - 4px); padding: 7px 9px; }
18
+ input:focus-visible, select:focus-visible, textarea:focus-visible, button:focus-visible, a:focus-visible { outline: 3px solid var(--_accent); outline-offset: 2px; }
19
+ input[aria-invalid="true"], select[aria-invalid="true"] { border-color: var(--_bad); }
20
+ input[type=checkbox], input[type=radio] { width: auto; margin-right: 6px; }
21
+ .row { display: flex; gap: 8px; align-items: flex-end; flex-wrap: wrap; } .row > * { flex: 1 1 120px; } .row > .fixed { flex: 0 0 auto; }
22
+ button { font: inherit; cursor: pointer; border-radius: calc(var(--_r) - 4px); border: 1px solid var(--_line); background: var(--_bg); color: inherit; padding: 7px 12px; }
23
+ button.primary { background: var(--_accfill); border-color: var(--_accfill); color: #fff; }
24
+ button.danger { background: var(--_badfill); border-color: var(--_badfill); color: #fff; }
25
+ button.ok { background: var(--_okfill); border-color: var(--_okfill); color: #fff; }
26
+ button:disabled { opacity: .5; cursor: not-allowed; }
27
+ @media (pointer: coarse) { button, select, input:not([type=checkbox]):not([type=radio]) { min-height: 44px; } }
28
+ .err { color: var(--_bad); font-size: 12.5px; margin: 3px 0 0; }
29
+ .status { padding: 8px 10px; border-radius: calc(var(--_r) - 4px); background: color-mix(in srgb, var(--_accent) 8%, transparent); }
30
+ .status.bad { background: color-mix(in srgb, var(--_bad) 10%, transparent); color: var(--_bad); }
31
+ .status.ok { background: color-mix(in srgb, var(--_ok) 10%, transparent); color: var(--_ok); }
32
+ .pill { display: inline-block; padding: 1px 8px; border-radius: 99px; font-size: 12px; border: 1px solid var(--_line); color: var(--_muted); }
33
+ .bar { height: 8px; border-radius: 99px; background: var(--_line); overflow: hidden; } .bar > i { display: block; height: 100%; background: var(--_accent); }
34
+ .actions { display: flex; gap: 8px; justify-content: flex-end; margin-top: 16px; }
35
+ .sr { position: absolute; width: 1px; height: 1px; overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; }
36
+ @media (prefers-reduced-motion: reduce) { *, *::before, *::after { animation: none !important; transition: none !important; } }
37
+ `,Q=`
38
+ .kp { display: flex; flex-direction: column; gap: 8px; }
39
+ .kp-row { display: flex; align-items: center; gap: 6px; }
40
+ .kp-num { flex: 1; min-width: 0; font-size: 18px; letter-spacing: .5px; text-align: center; min-height: 44px; }
41
+ .kp-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 6px; }
42
+ .kp-key { min-height: 52px; min-width: 44px; display: flex; flex-direction: column; align-items: center; justify-content: center; line-height: 1.1; background: var(--_alt); border-radius: var(--_r); touch-action: manipulation; }
43
+ .kp-key b { font-size: 20px; font-weight: 600; } .kp-key i { font-style: normal; font-size: 9px; letter-spacing: 1px; color: var(--_muted); min-height: 10px; }
44
+ .kp-back { min-width: 44px; min-height: 44px; }
45
+ .kp-calls { display: flex; gap: 6px; } .kp-call { flex: 1; min-height: 46px; color: #fff; font-weight: 600; border: 0; }
46
+ .kp-call[data-channel=whatsapp] { background: var(--_wa); } .kp-call[data-channel=phone] { background: var(--_ph); }
47
+ .kp-note { font-size: 12px; text-align: center; color: var(--_muted); margin: 0; } .kp-note.warn { color: var(--_warn); }
48
+ .btns { display: flex; gap: 8px; margin-top: 12px; } .btns button { flex: 1; min-height: 44px; padding: 10px; }
49
+ .who { font-size: 18px; font-weight: 600; margin: 10px 0 2px; overflow-wrap: anywhere; } .timer { font-variant-numeric: tabular-nums; color: var(--_muted); }
50
+ .recent-list { list-style: none; margin: 6px 0 0; padding: 0; } .recent-list li { display: flex; align-items: center; justify-content: space-between; gap: 8px; border-top: 1px solid var(--_line); }
51
+ .recent-list button { min-height: 44px; flex: 1; text-align: left; border: 0; background: none; padding: 4px 2px; } .recent-list .miss { color: var(--_bad); }
52
+ `;var Xs=typeof HTMLElement!="undefined"?HTMLElement:class{},O=class extends Xs{constructor(){if(super(),this._painted=!1,this._queued=!1,this.attachShadow){this.attachShadow({mode:"open"}),this.shadowRoot.addEventListener("click",s=>{var r,i,o;if(this._held){this._held=!1;return}let a=(i=(r=s.target).closest)==null?void 0:i.call(r,"[data-action]");a&&!a.disabled&&((o=this.onClick)==null||o.call(this,a.dataset.action,a,s))}),this.shadowRoot.addEventListener("input",s=>{var a,r;(a=s.target.dataset)!=null&&a.key&&((r=this.onInput)==null||r.call(this,s.target,s))}),this.shadowRoot.addEventListener("change",s=>{var a,r;(a=s.target.dataset)!=null&&a.key&&((r=this.onChange)==null||r.call(this,s.target,s))}),this.shadowRoot.addEventListener("keydown",s=>{var a;return(a=this.onKey)==null?void 0:a.call(this,s)});let e=null,t=()=>{clearTimeout(e),e=null};this.shadowRoot.addEventListener("pointerdown",s=>{var r,i;let a=(i=(r=s.target).closest)==null?void 0:i.call(r,"[data-hold]");a&&(t(),this._held=!1,e=setTimeout(()=>{var o;e=null,this._held=!0,(o=this.onHold)==null||o.call(this,a.dataset.hold,a)},500))});for(let s of["pointerup","pointerleave","pointercancel"])this.shadowRoot.addEventListener(s,t);this.shadowRoot.addEventListener("submit",s=>{var r,i;s.preventDefault();let a=(r=s.target.dataset)==null?void 0:r.submit;a&&((i=this.onClick)==null||i.call(this,a,s.target,s))})}}connectedCallback(){var e;this._connected=!0,(e=this.mounted)==null||e.call(this),this.requestRender()}disconnectedCallback(){var e;this._connected=!1,(e=this.unmounted)==null||e.call(this)}requestRender(){this._queued||!this.shadowRoot||(this._queued=!0,queueMicrotask(()=>{this._queued=!1,this._connected!==!1&&this.paint()}))}paint(){var i,o,l,c;let e=this.shadowRoot,t=e.activeElement,s=(i=t==null?void 0:t.dataset)==null?void 0:i.key,a=!s&&(t!=null&&t.id)?t.id:null,r=t&&"selectionStart"in t?[t.selectionStart,t.selectionEnd]:null;if(e.innerHTML=`<style>${Ie}${(o=this.css)!=null?o:""}</style>${this.render()}`,s){let g=e.querySelector(`[data-key="${CSS.escape(s)}"]`);if(g&&(g.focus(),r&&g.setSelectionRange))try{g.setSelectionRange(r[0],r[1])}catch{}}else a&&((c=(l=e.getElementById)==null?void 0:l.call(e,a))==null||c.focus());this._painted=!0}emit(e,t,{cancelable:s=!1}={}){return this.dispatchEvent(new CustomEvent(e,{detail:t,bubbles:!0,composed:!0,cancelable:s}))}};function A(n,e){typeof customElements!="undefined"&&!customElements.get(n)&&customElements.define(n,e)}var es=7;var Re=Object.freeze([{d:"1",l:""},{d:"2",l:"ABC"},{d:"3",l:"DEF"},{d:"4",l:"GHI"},{d:"5",l:"JKL"},{d:"6",l:"MNO"},{d:"7",l:"PQRS"},{d:"8",l:"TUV"},{d:"9",l:"WXYZ"},{d:"*",l:""},{d:"0",l:"+"},{d:"#",l:""}]),yt=Object.freeze([{id:"whatsapp",labelKey:"whatsapp",capKey:"whatsappCallingEnabled"},{id:"phone",labelKey:"phoneChannel",capKey:"phoneCallingEnabled"}]),_t=n=>String(n!=null?n:"").replace(/[^0-9+*#\s-]/g,"").slice(0,24),me=n=>String(n!=null?n:"").replace(/\D/g,""),qe=n=>me(n).length>=7,ee=n=>yt.filter(e=>n&&n[e.capKey]).map(e=>e.id);function vt(n,e){var s;let t=ee(n);return e&&t.includes(e)?e:t.includes("whatsapp")?"whatsapp":(s=t[0])!=null?s:null}function Me(n){let e=t=>(n||[]).some(s=>Array.isArray(s==null?void 0:s.channels)&&s.channels.includes(t));return{whatsappCallingEnabled:e("whatsapp_calling"),phoneCallingEnabled:e("voice")}}function te(n={}){let e="",t=n.caps||{},s=n.onCall,a=new Set,r=o=>{e=_t(o),a.forEach(l=>l())},i={get number(){return e},get caps(){return t},get digits(){return me(e)},get canCall(){return qe(e)},get channels(){return ee(t)},get nothingEnabled(){return ee(t).length===0},setNumber:r,press:o=>r(e+o),pressZeroLong:()=>r(e?e+"0":"+"),backspace:()=>r(e.slice(0,-1)),clear:()=>r(""),setCaps(o){t=o||{},a.forEach(l=>l())},setOnCall(o){s=o},call(o){if(!qe(e)||!ee(t).includes(o)||typeof s!="function")return!1;let l={number:me(e),channel:o};return n.clearOnCall!==!1&&(e=""),a.forEach(c=>c()),s(l),!0},submit(){let o=vt(t,n.defaultChannel);return o?i.call(o):!1},subscribe(o){return a.add(o),()=>a.delete(o)}};return i}var se=Object.freeze({softphone:"Softphone",phone:"Phone",off:"Softphone off",connecting:"Connecting\u2026",ready:"Ready for calls",ringing:"Incoming call",inCall:"On a call",error:"Softphone error",goOnline:"Go online",goOffline:"Go offline",tryAgain:"Try again",goOnlineHint:"Go online to receive calls in this browser. Allow microphone access when asked.",waiting:"Waiting for calls",waitingAs:"Waiting for calls as {name}.",isCalling:"is calling",answer:"Answer",decline:"Decline",hangUp:"Hang up",mute:"Mute",unmute:"Unmute",hold:"Hold",resume:"Resume",onHold:"On hold",onACall:"On a call",showKeypad:"Keypad",hideKeypad:"Hide keypad",sendingDigits:"Tap a key to send it to the caller",callEnded:"Call ended",callEndedFor:"Call ended \xB7 {time}",missedCall:"Missed call",placing:"Calling {number}\u2026 your browser will ring when the line connects.",numberLabel:"Number to call",numberPlaceholder:"Number with country code",backspace:"Delete last digit",keypad:"Keypad",callOn:"Call on {channel}",whatsapp:"WhatsApp",phoneChannel:"Phone",callingOff:"Calling is off for this workspace.",needCountryCode:"Include the country code, e.g. 1876\u2026",keyZero:"0, hold for plus",keyStar:"star",keyHash:"hash",recent:"Recent calls",noRecent:"No recent calls yet.",redial:"Call {who} again",incoming:"Incoming",outgoing:"Outgoing",missed:"Missed",openPhone:"Open phone",closePhone:"Close phone",missedBadge:"{n} missed calls",dialogLabel:"Phone",needSetup:"Set the client and adapter properties first.",goOnlineFirst:"Go online first to place calls.",badNumber:"Enter the number as +, then country code and number.",whatsappNotConfigured:"WhatsApp calling is not set up for this page (set the whatsapp property).",micBlocked:"Microphone access is blocked. Allow it in your browser settings, then try again.",sessionExpired:"Your session expired. Reload the page or sign in again.",connectionLost:"Connection lost. Try again.",unstable:"Connection to TraitOS is unstable.",sound:"Sound",soundOn:"Sounds on",volume:"Volume",keyTone:"Key sound",keyToneDtmf:"Phone tones",keyToneClick:"Click",keyToneOff:"None",ringtone:"Ringtone",ringClassic:"Classic",ringSoft:"Soft",ringOff:"Silent",speakDigits:"Say each digit aloud",voice:"Voice",voiceDefault:"Browser default",voiceRate:"Speaking speed",soundTest:"Test sound",couldNotCall:"Could not place the call",noIdentity:"This account has no softphone identity yet.",couldNotLoad:"Could not load this section."}),ts={};function ss(n){ts={...n||{}}}var q=n=>({...se,...ts,...n||{}});function R(n,e,t){var a,r;let s=(r=(a=n==null?void 0:n[e])!=null?a:se[e])!=null?r:e;return t?String(s).replace(/\{(\w+)\}/g,(i,o)=>{var l;return(l=t[o])!=null?l:i}):String(s)}var Le=Object.freeze({1:[697,1209],2:[697,1336],3:[697,1477],4:[770,1209],5:[770,1336],6:[770,1477],7:[852,1209],8:[852,1336],9:[852,1477],"*":[941,1209],0:[941,1336],"#":[941,1477]}),be=Object.freeze(["dtmf","click","off"]),ne=Object.freeze({classic:[[440,480],2e3,4e3],soft:[[523,659],1e3,3e3],off:null}),ge=Object.freeze({enabled:!0,volume:.5,keyTone:"dtmf",ringtone:"classic",speak:!1,voice:"",rate:1}),ns="traitos.sound",Vs={"*":"star","#":"pound","+":"plus"};function Y(n={}){let e=Number(n==null?void 0:n.volume),t=Number(n==null?void 0:n.rate);return{enabled:(n==null?void 0:n.enabled)!==!1,volume:Number.isFinite(e)?Math.min(1,Math.max(0,e)):ge.volume,keyTone:be.includes(n==null?void 0:n.keyTone)?n.keyTone:ge.keyTone,ringtone:Object.prototype.hasOwnProperty.call(ne,n==null?void 0:n.ringtone)?n.ringtone:ge.ringtone,speak:(n==null?void 0:n.speak)===!0,voice:typeof(n==null?void 0:n.voice)=="string"?n.voice:"",rate:Number.isFinite(t)?Math.min(2,Math.max(.5,t)):1}}function Zs(n){try{return Y(JSON.parse((n==null?void 0:n.getItem(ns))||"{}"))}catch{return Y()}}function Qs(n,e){try{n==null||n.setItem(ns,JSON.stringify(Y(e)))}catch{}}function ae({storage:n,audio:e,speech:t,Utterance:s,settings:a}={}){let r=a?Y(a):Zs(n),i=null,o=null,l=new Set,c=t!=null?t:globalThis.speechSynthesis,g=s!=null?s:globalThis.SpeechSynthesisUtterance,b=()=>{var h,m,$;if(i)return i;try{i=(e!=null?e:(()=>new(globalThis.AudioContext||globalThis.webkitAudioContext)))()}catch{i=null}return(i==null?void 0:i.state)==="suspended"&&(($=(h=i.resume)==null?void 0:(m=h.call(i)).catch)==null||$.call(m,()=>{})),i};function f(h,m,$=1){let w=b();if(!w)return()=>{};let x=w.createGain(),T=w.currentTime,I=T+m/1e3,S=.25*r.volume*$;x.gain.setValueAtTime(1e-4,T),x.gain.linearRampToValueAtTime(S,T+.008),x.gain.setValueAtTime(S,Math.max(T+.008,I-.02)),x.gain.linearRampToValueAtTime(1e-4,I),x.connect(w.destination);let V=h.map(J=>{let E=w.createOscillator();return E.type="sine",E.frequency.value=J,E.connect(x),E.start(T),E.stop(I+.02),E});return()=>{try{V.forEach(J=>J.stop()),x.disconnect()}catch{}}}let v=()=>r.enabled&&r.volume>0,y={get settings(){return{...r}},update(h){r=Y({...r,...h}),Qs(n,r),v()||y.stopRing(),l.forEach(m=>m())},subscribe(h){return l.add(h),()=>l.delete(h)},key(h){var m;v()&&(r.keyTone==="dtmf"&&Le[h]?f(Le[h],120):(r.keyTone==="click"||r.keyTone==="dtmf")&&y.click(),r.speak&&y.say((m=Vs[h])!=null?m:h))},click(){v()&&r.keyTone!=="off"&&f([1800],14,.9)},say(h){var m,$;if(!r.enabled||!c||!g)return!1;try{(m=c.cancel)==null||m.call(c);let w=new g(String(h));w.volume=Math.max(.05,r.volume),w.rate=r.rate;let x=r.voice&&(($=c.getVoices)==null?void 0:$.call(c).find(T=>T.voiceURI===r.voice));return x&&(w.voice=x,w.lang=x.lang),c.speak(w),!0}catch{return!1}},voices(){var h,m;try{return((m=(h=c==null?void 0:c.getVoices)==null?void 0:h.call(c))!=null?m:[]).map($=>({id:$.voiceURI,label:`${$.name} (${$.lang})`}))}catch{return[]}},startRing(){if(o||!v())return;let h=ne[r.ringtone];if(!h)return;let[m,$,w]=h,x={stop:()=>{},timer:null},T=()=>{x.stop=f(m,$,.8),x.timer=setTimeout(T,$+w)};o=x,T()},stopRing(){o&&(clearTimeout(o.timer),o.stop(),o=null)},get ringing(){return!!o},end(){v()&&(f([480],140,.8),setTimeout(()=>f([380],200,.8),170))},test(){y.key("5"),r.speak&&y.say("Five")}};return y}var en=(n,e)=>e==="0"?n.keyZero:e==="*"?n.keyStar:e==="#"?n.keyHash:e;function H(n,{S:e=q(),mode:t="dial",busy:s=!1}={}){let a=t==="dtmf",r=yt.filter(o=>n.channels.includes(o.id)),i=a?d`<p class="kp-note" role="status">${e.sendingDigits}</p>`:n.nothingEnabled?d`<p class="kp-note warn" role="status">${e.callingOff}</p>`:n.number&&!n.canCall?d`<p class="kp-note" role="status">${e.needCountryCode}</p>`:"";return d`<div class="kp" role="group" aria-label="${e.keypad}" data-at="dial-pad">
53
+ ${a?"":d`<div class="kp-row"><input class="kp-num" id="kp-number" data-key="dialpad-number" type="tel" inputmode="tel" autocomplete="off" maxlength="24" placeholder="${e.numberPlaceholder}" aria-label="${e.numberLabel}" value="${n.number}" data-at="dial-pad-input" />
54
+ <button type="button" class="kp-back" data-action="kp-back" aria-label="${e.backspace}" ${n.number?"":"disabled"} data-at="dial-pad-backspace">⌫</button></div>`}
55
+ <div class="kp-grid">${Re.map(o=>d`<button type="button" class="kp-key" data-action="${a?"kp-dtmf":"kp-key"}" data-d="${o.d}" ${o.d==="0"&&!a?k('data-hold="zero"'):""} aria-label="${en(e,o.d)}" data-at="dial-pad-key-${o.d}"><b aria-hidden="true">${o.d}</b><i aria-hidden="true">${o.l}</i></button>`)}</div>
56
+ ${a||!r.length?"":d`<div class="kp-calls">${r.map(o=>d`<button type="button" class="kp-call" data-action="kp-call" data-channel="${o.id}" aria-label="${R(e,"callOn",{channel:e[o.labelKey]})}" ${n.canCall&&!s?"":"disabled"} data-at="dial-pad-call-${o.id}">${e[o.labelKey]}</button>`)}</div>`}
57
+ ${i}
58
+ </div>`}function wt(n,e,t,{onDtmf:s}={}){return e==="kp-key"?(n.press(t.dataset.d),!0):e==="kp-back"?(n.backspace(),!0):e==="kp-call"?(n.call(t.dataset.channel),!0):e==="kp-dtmf"?(s==null||s(t.dataset.d),!0):!1}function $t(n,e){var t;return((t=e.dataset)==null?void 0:t.key)!=="dialpad-number"?!1:(n.setNumber(e.value),!0)}function tn(n,e){var t,s;return e.key==="Enter"&&((s=(t=e.target)==null?void 0:t.dataset)==null?void 0:s.key)==="dialpad-number"?(e.preventDefault(),n.submit(),!0):!1}function xt(n,e){return e==="zero"?(n.pressZeroLong(),!0):!1}var ye=class extends O{static get observedAttributes(){return["whatsapp-calling","phone-calling","theme"]}constructor(){super(),this.dp=te({onCall:e=>this.emit("traitos-call",e)}),this.dp.subscribe(()=>this.requestRender())}get css(){return Q+":host{max-width:280px}"}get caps(){var e;return(e=this._caps)!=null?e:this._attrCaps()}set caps(e){this._caps=e,this.dp.setCaps(e)}set strings(e){this._strings=e,this.requestRender()}_attrCaps(){return{whatsappCallingEnabled:this.hasAttribute("whatsapp-calling"),phoneCallingEnabled:this.hasAttribute("phone-calling")}}mounted(){this.dp.setCaps(this.caps)}attributeChangedCallback(){this._caps||this.dp.setCaps(this._attrCaps()),this.requestRender()}render(){return`<div class="card">${H(this.dp,{S:q(this._strings)})}</div>`}get sound(){var e;return(e=this._sound)!=null?e:this._sound=ae({storage:typeof localStorage!="undefined"?localStorage:void 0})}set sound(e){this._sound=e}onClick(e,t){e==="kp-key"?this.sound.key(t.dataset.d):(e==="kp-back"||e==="kp-call")&&this.sound.click(),wt(this.dp,e,t)}onInput(e){$t(this.dp,e)}onKey(e){var t,s;((s=(t=e.target)==null?void 0:t.dataset)==null?void 0:s.key)==="dialpad-number"&&e.key.length===1&&/[0-9*#]/.test(e.key)&&!e.ctrlKey&&!e.metaKey&&this.sound.key(e.key),tn(this.dp,e)}onHold(e){xt(this.dp,e)&&this.sound.key("+")}};A("traitos-keypad",ye);var as=6e4;function kt(n,e){switch(e){case"ringing":return n==="inbound"?"ringing":null;case"answering":case"active":case"held":case"early":return"in-call";case"hangup":case"destroy":case"done":return"ready";default:return null}}var St={off:"Softphone off",connecting:"Connecting\u2026",ready:"Ready for calls",ringing:"Incoming call","in-call":"On a call",error:"Softphone error"};function re(n){let e=((n==null?void 0:n.remoteCallerName)||(n==null?void 0:n.callerName)||"").trim(),t=((n==null?void 0:n.remoteCallerNumber)||(n==null?void 0:n.callerNumber)||"").trim();return e&&t&&e!==t?`${e} (${t})`:e||t||"Unknown caller"}function _e(n){let e=Math.max(0,Math.floor(n/1e3)),t=Math.floor(e/3600),s=Math.floor(e%3600/60),a=e%60,r=t?String(s).padStart(2,"0"):String(s);return`${t?`${t}:`:""}${r}:${String(a).padStart(2,"0")}`}function De(n){let e=String(n!=null?n:"").replace(/[^\d+]/g,"");return(e.startsWith("+")?"+":"")+e.replace(/\+/g,"")}var z=n=>/^\+[1-9]\d{6,14}$/.test(String(n!=null?n:""));var He="traitos.calllog",W=class{constructor({storage:e,max:t=10,now:s=Date.now}={}){this.storage=e,this.max=t,this.now=s,this.listeners=new Set,this.entries=this._read(),this.seenAt=this._seen()}_read(){var e;try{let t=JSON.parse(((e=this.storage)==null?void 0:e.getItem(He))||"[]");return Array.isArray(t)?t.slice(0,this.max):[]}catch{return[]}}_seen(){var e;try{return Number((e=this.storage)==null?void 0:e.getItem(`${He}.seen`))||0}catch{return 0}}_save(){var e,t;try{(e=this.storage)==null||e.setItem(He,JSON.stringify(this.entries)),(t=this.storage)==null||t.setItem(`${He}.seen`,String(this.seenAt))}catch{}}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}add(e){this.entries=[{...e,at:this.now()},...this.entries].slice(0,this.max),this._save(),this.listeners.forEach(t=>t())}list(){return this.entries.map(e=>({...e}))}missedCount(){return this.entries.filter(e=>e.outcome==="missed"&&e.at>this.seenAt).length}markSeen(){this.seenAt=this.now(),this._save(),this.listeners.forEach(e=>e())}clear(){this.entries=[],this._save(),this.listeners.forEach(e=>e())}};var sn=45e3,nn=/^[0-9A-D*#]$/i,an=n=>(n==null?void 0:n.name)==="NotAllowedError"||(n==null?void 0:n.name)==="SecurityError"||/permission denied|microphone.*(denied|blocked)|not allowed/i.test((n==null?void 0:n.message)||""),ie=class{constructor({client:e,adapter:t,numbers:s,ringTimeoutSeconds:a,liveEvents:r=!1,heartbeatMs:i=6e4,timers:o,now:l=Date.now,whatsapp:c,log:g,media:b,strings:f}){var v,y;this.client=e,this.adapter=t,this.numbers=s,this.ringTimeoutSeconds=a,this.liveEvents=r,this.heartbeatMs=i,this.timers={setTimeout:(h,m)=>setTimeout(h,m),clearTimeout:h=>clearTimeout(h),...o!=null?o:{setInterval:(h,m)=>setInterval(h,m),clearInterval:h=>clearInterval(h)}},this.now=l,this.whatsapp=c,this.log=g!=null?g:new W({now:l}),this.media=b===void 0?(y=(v=globalThis.navigator)==null?void 0:v.mediaDevices)!=null?y:null:b,this.S={...se,...f||{}},this.state={status:"off",caller:null,muted:!1,held:!1,error:null,errorCode:null,warning:null,sipUsername:null,startedAt:null,dialing:!1,placing:null,lastCall:null,recent:[]},this._call=null,this._listeners=new Set,this._heartbeat=null,this._sub=null,this._wired=!1,this._gen=0,this._failures=0,this._placingTimer=null,this._current=null}snapshot(){return{...this.state,recent:[...this.state.recent]}}subscribe(e){return this._listeners.add(e),()=>this._listeners.delete(e)}_set(e){this.state={...this.state,...e};for(let t of[...this._listeners])try{t(this.snapshot())}catch{}}_wire(){this._wired||(this._wired=!0,this.adapter.on("ready",()=>{this.state.status==="connecting"&&this._set({status:"ready"})}),this.adapter.on("error",e=>this._fail(e)),this.adapter.on("close",()=>{this.state.status!=="off"&&this.state.status!=="error"&&(this._teardown(),this._fail(Object.assign(new Error(this.S.connectionLost),{code:"connection-lost"})))}),this.adapter.on("call",e=>this._onCall(e)))}async _checkMic(){var t,s;if(!((t=this.media)!=null&&t.getUserMedia))return;let e=await this.media.getUserMedia({audio:!0});(s=e==null?void 0:e.getTracks)==null||s.call(e).forEach(a=>a.stop())}async start(){if(this.state.status!=="off"&&this.state.status!=="error")return;let e=++this._gen;this._set({status:"connecting",error:null,errorCode:null,warning:null});try{await this._checkMic();let{token:t,sipUsername:s}=await this.client.softphone.token();if(e!==this._gen)return;if(!t||!s)throw new Error(this.S.noIdentity);if(this._wire(),this._set({sipUsername:s}),await this.adapter.connect({token:t,sipUsername:s}),e!==this._gen||(await this._register(),e!==this._gen))return;this._failures=0,this._heartbeat=this.timers.setInterval(()=>this._beat(),this.heartbeatMs),this.liveEvents&&this._watchEvents()}catch(t){if(e!==this._gen)return;this._teardown();try{await this.adapter.disconnect()}catch{}this._fail(t)}}async stop(){var t,s;this._gen++;let e=this.state.sipUsername;this._teardown();try{(s=(t=this._call)==null?void 0:t.hangup)==null||s.call(t)}catch{}try{await this.adapter.disconnect()}catch{}e&&await this.client.softphone.unregister(e).catch(()=>{}),this._call=null,this._current=null,this._set({status:"off",caller:null,muted:!1,held:!1,startedAt:null,placing:null,warning:null})}_teardown(){var e,t;this._heartbeat&&this.timers.clearInterval(this._heartbeat),this._heartbeat=null,(t=(e=this._sub)==null?void 0:e.close)==null||t.call(e),this._sub=null,this._clearPlacing()}_register(){let e=this.numbers;return this.client.softphone.register({sipUsername:this.state.sipUsername,...e&&e.length?{numbers:e}:{},...this.ringTimeoutSeconds?{ringTimeoutSeconds:this.ringTimeoutSeconds}:{}})}async _beat(){try{await this._register(),this._failures=0,this.state.warning&&this._set({warning:null})}catch(e){if((e==null?void 0:e.status)===401||(e==null?void 0:e.status)===403){this._teardown();try{await this.adapter.disconnect()}catch{}this._fail(Object.assign(new Error(this.S.sessionExpired),{code:"session-expired"}))}else++this._failures>=3&&!this.state.warning&&this._set({warning:this.S.unstable})}}_watchEvents(){this._sub=this.client.events.subscribe(e=>{let t=[{type:e.type,at:e.created_at,id:e.id},...this.state.recent].slice(0,5);this._set({recent:t})},{types:["call.*"],onError:()=>{}})}_fail(e){var s;let t=an(e);this._set({status:"error",error:t?this.S.micBlocked:(e==null?void 0:e.message)||this.S.error,errorCode:t?"mic-denied":(s=e==null?void 0:e.code)!=null?s:null,caller:null,held:!1,muted:!1,startedAt:null,dialing:!1})}_clearPlacing(){this._placingTimer&&this.timers.clearTimeout(this._placingTimer),this._placingTimer=null,this.state.placing&&(this.state={...this.state,placing:null})}_finish(e){let t=this._current;if(this._current=null,!t)return;let s=t.answeredAt?this.now()-t.answeredAt:0,a=t.answeredAt?"answered":"missed";this.log.add({who:t.who,number:t.number,direction:t.direction==="inbound"?"in":"out",outcome:e!=null?e:a,durationMs:s}),this._set({lastCall:{who:t.who,durationMs:s,outcome:e!=null?e:a,at:this.now()}})}_onCall(e){var s,a,r,i,o;this._call=e;let t=kt(e.direction,e.state);t&&(this.state.placing&&this._clearPlacing(),t==="ringing"?(this._current={who:re(e),number:e.remoteCallerNumber||null,direction:"inbound",answeredAt:null},this._set({status:"ringing",caller:re(e),muted:!1,held:!1,lastCall:null,placing:null})):t==="in-call"?((s=this._current)!=null||(this._current={who:re(e),number:e.remoteCallerNumber||null,direction:e.direction,answeredAt:null}),(r=(a=this._current).answeredAt)!=null||(a.answeredAt=this.now()),this._set({status:"in-call",startedAt:(i=this.state.startedAt)!=null?i:this.now(),caller:(o=this.state.caller)!=null?o:re(e),held:e.state==="held",lastCall:null,placing:null})):(this._call=null,this._finish(),this._set({status:"ready",caller:null,muted:!1,held:!1,startedAt:null})))}applyCallUpdate(e){this._onCall(e)}answer(){var e,t;this.state.status==="ringing"&&((t=(e=this._call)==null?void 0:e.answer)==null||t.call(e))}hangup(){var e,t;(t=(e=this._call)==null?void 0:e.hangup)==null||t.call(e)}mute(){var t,s;if(!this._call)return;let e=!this.state.muted;try{(s=(t=this._call).mute)==null||s.call(t,e)}catch{return}this._set({muted:e})}hold(){if(!this._call||typeof this._call.hold!="function"||this.state.status!=="in-call")return!1;let e=!this.state.held;try{this._call.hold(e)}catch{return!1}return this._set({held:e}),!0}dtmf(e){var s;let t=String(e!=null?e:"");if(!nn.test(t)||this.state.status!=="in-call"||typeof((s=this._call)==null?void 0:s.dtmf)!="function")return!1;try{return this._call.dtmf(t.toUpperCase()),!0}catch{return!1}}get canHold(){var e;return typeof((e=this._call)==null?void 0:e.hold)=="function"}get canDtmf(){var e;return typeof((e=this._call)==null?void 0:e.dtmf)=="function"}async dial(e,t="phone"){var r;let s=String(e!=null?e:""),a=/^\d+$/.test(s)?`+${s}`:s;if(this.state.dialing)return!1;if(!z(a))return this._set({error:this.S.badNumber,errorCode:"bad-number"}),!1;if(this.state.status!=="ready")return this._set({error:this.S.goOnlineFirst,errorCode:"offline"}),!1;if(t==="whatsapp"&&!this.whatsapp)return this._set({error:this.S.whatsappNotConfigured,errorCode:"whatsapp-not-configured"}),!1;this._set({dialing:!0,error:null,errorCode:null});try{return await this.client.calls.create(t==="whatsapp"?{channel:"whatsapp",to:a,agentSipUsername:this.state.sipUsername,...this.whatsapp}:{channel:"phone",to:a,agentSipUsername:this.state.sipUsername}),this._set({placing:{number:a,channel:t}}),this._placingTimer=this.timers.setTimeout(()=>{this._placingTimer=null,this.state.placing&&this._set({placing:null})},sn),!0}catch(i){return this._set({error:(i==null?void 0:i.message)||this.S.couldNotCall,errorCode:(r=i==null?void 0:i.code)!=null?r:null}),!1}finally{this._set({dialing:!1})}}};var rn={dtmf:"keyToneDtmf",click:"keyToneClick",off:"keyToneOff"},on={classic:"ringClassic",soft:"ringSoft",off:"ringOff"};function oe(n,e,{open:t=!1,voices:s=[],idPrefix:a="snd"}={}){let r=n.settings,i=o=>`${a}-${o}`;return d`<div class="snd">
59
+ <button type="button" class="snd-toggle" data-action="snd-toggle" aria-expanded="${String(!!t)}" aria-controls="${i("panel")}">${r.enabled?"\u{1F50A}":"\u{1F507}"} ${e.sound}</button>
60
+ ${t?d`<div class="snd-panel" id="${i("panel")}" role="group" aria-label="${e.sound}">
61
+ <label class="snd-check"><input type="checkbox" data-key="snd-enabled" ${r.enabled?"checked":""} />${e.soundOn}</label>
62
+ <label for="${i("vol")}">${e.volume}</label>
63
+ <input id="${i("vol")}" type="range" min="0" max="1" step="0.05" data-key="snd-volume" value="${r.volume}" aria-valuetext="${Math.round(r.volume*100)}%" />
64
+ <label for="${i("key")}">${e.keyTone}</label>
65
+ <select id="${i("key")}" data-key="snd-keyTone">${be.map(o=>d`<option value="${o}" ${r.keyTone===o?"selected":""}>${e[rn[o]]}</option>`)}</select>
66
+ <label for="${i("ring")}">${e.ringtone}</label>
67
+ <select id="${i("ring")}" data-key="snd-ringtone">${Object.keys(ne).map(o=>d`<option value="${o}" ${r.ringtone===o?"selected":""}>${e[on[o]]}</option>`)}</select>
68
+ <label class="snd-check"><input type="checkbox" data-key="snd-speak" ${r.speak?"checked":""} />${e.speakDigits}</label>
69
+ ${r.speak?d`<label for="${i("voice")}">${e.voice}</label>
70
+ <select id="${i("voice")}" data-key="snd-voice"><option value="">${e.voiceDefault}</option>${s.map(o=>d`<option value="${o.id}" ${r.voice===o.id?"selected":""}>${o.label}</option>`)}</select>
71
+ <label for="${i("rate")}">${e.voiceRate}</label>
72
+ <input id="${i("rate")}" type="range" min="0.5" max="2" step="0.1" data-key="snd-rate" value="${r.rate}" aria-valuetext="${r.rate}×" />`:""}
73
+ <div class="btns"><button type="button" data-action="snd-test">${e.soundTest}</button></div>
74
+ </div>`:""}
75
+ </div>`}function Tt(n,e){var r;let t=(r=e==null?void 0:e.dataset)==null?void 0:r.key;if(!t||!t.startsWith("snd-"))return!1;let s=t.slice(4),a=e.type==="checkbox"?!!e.checked:s==="volume"||s==="rate"?Number(e.value):e.value;return n.update({[s]:a}),!0}var ln=(n,e)=>({method:n,body:JSON.stringify(e!=null?e:{})}),Ue=n=>{var e;return(e=n._request)==null?void 0:e.bind(n)};async function je(n){var e,t,s,a,r;return typeof((e=n.phoneNumbers)==null?void 0:e.list)=="function"?(s=(t=await n.phoneNumbers.list())==null?void 0:t.numbers)!=null?s:[]:(r=(a=await Ue(n)("/telephony/numbers"))==null?void 0:a.numbers)!=null?r:[]}async function rs(n){var e,t,s,a,r,i;return typeof((t=(e=n.calls)==null?void 0:e.outboundSettings)==null?void 0:t.get)=="function"?(a=(s=await n.calls.outboundSettings.get())==null?void 0:s.mode)!=null?a:"direct":(i=(r=await Ue(n)("/telephony/outbound-call-settings"))==null?void 0:r.mode)!=null?i:"direct"}async function is(n,e){var t,s;return typeof((s=(t=n.calls)==null?void 0:t.outboundSettings)==null?void 0:s.update)=="function"?n.calls.outboundSettings.update({mode:e}):Ue(n)("/telephony/outbound-call-settings",ln("PUT",{mode:e}))}async function os(n,e=10){var t,s,a,r,i;return typeof((t=n.calls)==null?void 0:t.list)=="function"?(a=(s=await n.calls.list({limit:e}))==null?void 0:s.calls)!=null?a:[]:(i=(r=await Ue(n)(`/calls?limit=${e}`))==null?void 0:r.calls)!=null?i:[]}var ls=n=>String(n!=null?n:"").replace(/\D/g,"");function dn(n){let e=n.direction==="inbound",t=(e?n.from:n.to)||null,s=n.startedAt?Date.parse(n.startedAt):0,a=Number(n.durationSeconds)>0?Number(n.durationSeconds)*1e3:0;return{who:t!=null?t:"Unknown",number:t,direction:e?"in":"out",outcome:a?"answered":"missed",durationMs:a,at:s,id:n.id}}function ds(n=[],e=[],t=10){let s=[...n];for(let a of e.map(dn))s.some(i=>ls(i.number)===ls(a.number)&&Math.abs((i.at||0)-a.at)<=12e4)||s.push(a);return s.sort((a,r)=>(r.at||0)-(a.at||0)).slice(0,t)}var Ct="traitos.dialer.prefs",cn=Object.freeze({ringTimeoutSeconds:20,ringChannels:{whatsapp:!0,phone:!0},callerId:null});function U(n={}){var t,s;let e=Math.round(Number(n==null?void 0:n.ringTimeoutSeconds));return{ringTimeoutSeconds:(n==null?void 0:n.ringTimeoutSeconds)===""||(n==null?void 0:n.ringTimeoutSeconds)==null||!Number.isFinite(e)?cn.ringTimeoutSeconds:Math.min(60,Math.max(0,e)),ringChannels:{whatsapp:((t=n==null?void 0:n.ringChannels)==null?void 0:t.whatsapp)!==!1,phone:((s=n==null?void 0:n.ringChannels)==null?void 0:s.phone)!==!1},callerId:typeof(n==null?void 0:n.callerId)=="string"&&n.callerId?n.callerId:null}}function Fe(n){try{return U(JSON.parse((n==null?void 0:n.getItem(Ct))||"{}"))}catch{return U()}}function ze(n,e){try{n==null||n.setItem(Ct,JSON.stringify(U(e)))}catch{}}function We(n,e){let t=U(n);if(!(e!=null&&e.length))return{ringTimeoutSeconds:t.ringTimeoutSeconds};let s=e.filter(a=>{let r=Array.isArray(a.channels)?a.channels:[];return r.includes("whatsapp_calling")&&t.ringChannels.whatsapp||r.includes("voice")&&t.ringChannels.phone}).map(a=>a.number).filter(Boolean);return{ringTimeoutSeconds:t.ringTimeoutSeconds,numbers:s}}function Ke(n){try{let e=n==null?void 0:n.getItem(Ct);return e?U(JSON.parse(e)):null}catch{return null}}var ve="traitos-dialer-prefs";var un=()=>{try{return typeof localStorage!="undefined"?localStorage:null}catch{return null}},K=class extends O{static get observedAttributes(){return["allow-dial","live-events","auto-start","theme","position","inline"]}constructor(){super(),this.dp=te({clearOnCall:!1,onCall:e=>this._placeCall(e.number,e.channel)}),this.dp.subscribe(()=>this.requestRender()),this.keypadOpen=!1}set client(e){this._client=e,this._lines=null,this._init()}get client(){return this._client}set adapter(e){this._adapter=e,this._init()}get adapter(){return this._adapter}set numbers(e){this._numbers=e,this.controller&&(this.controller.numbers=e)}set whatsapp(e){this._whatsapp=e,this.controller&&(this.controller.whatsapp=e),this.requestRender()}get whatsapp(){return this._whatsapp}set strings(e){this._strings=e,this.requestRender()}get S(){return q(this._strings)}get caps(){return this.dp.caps}set caps(e){this._caps=e,this.dp.setCaps(e)}set storage(e){this._storage=e}get sound(){return this._sound||(this._sound=ae({storage:this._store}),this._unsound=this._sound.subscribe(()=>this.requestRender())),this._sound}set sound(e){this._sound=e,this.requestRender()}get _store(){var e;return(e=this._storage)!=null?e:un()}mounted(){var e,t,s;this._onPrefs=()=>this._applyPrefs(),this._onVoices=()=>this.requestRender(),(t=(e=globalThis.speechSynthesis)==null?void 0:e.addEventListener)==null||t.call(e,"voiceschanged",this._onVoices),(s=globalThis.addEventListener)==null||s.call(globalThis,ve,this._onPrefs),this._init()}unmounted(){var e,t,s,a,r,i,o,l;(e=globalThis.removeEventListener)==null||e.call(globalThis,ve,this._onPrefs),(s=(t=globalThis.speechSynthesis)==null?void 0:t.removeEventListener)==null||s.call(t,"voiceschanged",this._onVoices),(a=this._sound)==null||a.stopRing(),(r=this._unsound)==null||r.call(this),this._unsound=null,clearInterval(this._tick),(i=this._unsub)==null||i.call(this),this._unsub=null,(o=this._unlog)==null||o.call(this),this._unlog=null,(l=this.controller)==null||l.stop(),this.controller=null,this._capsLoaded=!1}attributeChangedCallback(){this.requestRender()}_init(){if(this._connected){if(this._initCaps(),this.controller||!this._client||!this._adapter){this.requestRender();return}this.log=new W({storage:this._store}),this._unlog=this.log.subscribe(()=>this.requestRender()),this.controller=new ie({client:this._client,adapter:this._adapter,numbers:this._numbers,whatsapp:this._whatsapp,liveEvents:this.hasAttribute("live-events"),log:this.log,strings:this._strings}),this._applyPrefs(),this._unsub=this.controller.subscribe(e=>{var t;this.emit("traitos-state",e),e.status==="error"&&this.emit("traitos-error",{message:e.error,code:e.errorCode}),clearInterval(this._tick),e.status==="in-call"&&(this._tick=setInterval(()=>this.requestRender(),1e3)),e.status!=="in-call"&&(this.keypadOpen=!1),this._stateSound(e),(t=this.onState)==null||t.call(this,e),this.requestRender()}),this.hasAttribute("auto-start")&&this.controller.start(),this.requestRender()}}recentCalls(){var e,t,s;return ds((t=(e=this.log)==null?void 0:e.list())!=null?t:[],(s=this._serverCalls)!=null?s:[])}async _loadHistory(){if(!(!this._client||this._historyBusy)){this._historyBusy=!0;try{this._serverCalls=await os(this._client,10),this.requestRender()}catch{}this._historyBusy=!1}}_stateSound(e){let t=this._prevStatus;this._prevStatus=e.status,e.status==="ringing"?this.sound.startRing():this.sound.stopRing(),e.status==="ready"&&(t==="in-call"||t==="ringing")&&(this.sound.end(),setTimeout(()=>this._loadHistory(),1500)),e.status==="ready"&&t!=="ready"&&!this._serverCalls&&this._loadHistory()}async _initCaps(){if(!(this._caps||this._capsLoaded||!this._client)){this._capsLoaded=!0;try{this._lines=await je(this._client),this._caps||this.dp.setCaps(Me(this._lines)),this._applyPrefs()}catch{this._caps||this.dp.setCaps({phoneCallingEnabled:!0})}}}_applyPrefs(){let e=Ke(this._store);if(!e||!this.controller)return;let t=We(e,this._lines);this.controller.ringTimeoutSeconds=t.ringTimeoutSeconds||void 0,!this._numbers&&t.numbers&&(this.controller.numbers=t.numbers)}_placeCall(e,t){let s=this.emit("traitos-call",{number:e,channel:t},{cancelable:!0});s&&this.controller?this.controller.dial(e,t).then(a=>{a&&this.dp.clear(),this.requestRender()}):(!this.controller||!s)&&this.dp.clear()}dial(e,t="phone"){return this.dp.channels.includes(t)?(this.dp.setNumber(String(e)),this.dp.call(t)):!1}phoneClick(e,t){let s=this.controller;if(e==="kp-key"||e==="kp-dtmf"?this.sound.key(t.dataset.d):e==="snd-test"?this.sound.test():e!=="snd-toggle"&&e!=="start"&&e!=="stop"&&this.sound.click(),e==="snd-toggle")return this._sndOpen=!this._sndOpen,this.requestRender(),!0;if(e==="snd-test"||wt(this.dp,e,t,{onDtmf:a=>s==null?void 0:s.dtmf(a)}))return!0;if(!s)return!1;if(e==="start")s.start();else if(e==="stop")s.stop();else if(e==="answer")s.answer();else if(e==="hangup")s.hangup();else if(e==="mute")s.mute();else if(e==="hold")s.hold();else if(e==="toggle-keypad")this.keypadOpen=!this.keypadOpen,this.requestRender();else if(e==="redial"){let a=this.recentCalls()[Number(t.dataset.i)];a!=null&&a.number&&this.dial(a.number.replace(/\D/g,""),this.dp.channels.includes("phone")?"phone":this.dp.channels[0])}else return!1;return!0}onClick(e,t){this.phoneClick(e,t)}onInput(e){var t,s;if((s=(t=e.dataset)==null?void 0:t.key)!=null&&s.startsWith("snd-")){e.type==="range"&&Tt(this.sound,e);return}$t(this.dp,e)}onChange(e){Tt(this.sound,e)}onHold(e){xt(this.dp,e)&&this.sound.key("+")}onKey(e){var t,s;((s=(t=e.target)==null?void 0:t.dataset)==null?void 0:s.key)==="dialpad-number"&&(e.key==="Enter"?(e.preventDefault(),this.dp.submit()):e.key.length===1&&/[0-9*#]/.test(e.key)&&!e.ctrlKey&&!e.metaKey&&this.sound.key(e.key))}};var pn=Q+`
76
+ .snd { margin-top: 10px; } .snd-panel { display: grid; gap: 4px; margin-top: 6px; } .snd-check { display: flex; align-items: center; gap: 6px; margin: 4px 0; } .snd-toggle { width: 100%; text-align: left; } .snd input[type=range] { padding: 0; }
77
+ .phone { max-width: 340px; } .head { display: flex; align-items: center; justify-content: space-between; gap: 8px; }
78
+ .dot { width: 9px; height: 9px; border-radius: 50%; background: var(--_line); display: inline-block; margin-right: 6px; }
79
+ .dot.ready { background: var(--_ok); } .dot.ringing { background: var(--_warn); animation: pulse 1s infinite; } .dot.in-call { background: var(--_accent); } .dot.error { background: var(--_bad); }
80
+ .recent { list-style: none; margin: 6px 0 0; padding: 0; font-size: 12.5px; color: var(--_muted); }
81
+ @keyframes pulse { 50% { opacity: .35; } }
82
+ `,hn={off:"off",connecting:"connecting",ready:"ready",ringing:"ringing","in-call":"inCall",error:"error"};function $e(n,e,{canRedial:t=!0}={}){return n!=null&&n.length?d`<ul class="recent-list">${n.map((s,a)=>d`<li><button type="button" data-action="redial" data-i="${a}" ${t&&s.number?"":"disabled"} aria-label="${R(e,"redial",{who:s.who})}">
83
+ <span class="${s.outcome==="missed"&&s.direction==="in"?"miss":""}">${s.who}</span> <span class="hint">${s.direction==="in"?s.outcome==="missed"?e.missed:e.incoming:e.outgoing}${s.durationMs?` \xB7 ${_e(s.durationMs)}`:""}</span></button></li>`)}</ul>`:d`<p class="hint">${e.noRecent}</p>`}function xe(n,{S:e,now:t,canHold:s,canDtmf:a,keypadOpen:r}){var i;return d`<div class="who">${(i=n.caller)!=null?i:e.onACall}</div><div class="timer" aria-hidden="true">${n.startedAt?_e(t-n.startedAt):""}${n.held?d` · ${e.onHold}`:""}</div>
84
+ <div class="btns"><button type="button" data-action="mute" aria-pressed="${String(!!n.muted)}">${n.muted?e.unmute:e.mute}</button>${s?d`<button type="button" data-action="hold" aria-pressed="${String(!!n.held)}">${n.held?e.resume:e.hold}</button>`:""}${a?d`<button type="button" data-action="toggle-keypad" aria-pressed="${String(!!r)}">${r?e.hideKeypad:e.showKeypad}</button>`:""}<button type="button" class="danger" data-action="hangup">${e.hangUp}</button></div>`}function Et(n,e){if(!n.lastCall)return"";let t=n.lastCall;return d`<p class="status" role="status">${t.outcome==="missed"?d`${e.missedCall}: ${t.who}`:R(e,"callEndedFor",{time:_e(t.durationMs)})}</p>`}function Ot(n,{allowDial:e=!1,now:t=Date.now(),dial:s="",title:a,S:r=q(),dp:i,canHold:o=!1,canDtmf:l=!1,keypadOpen:c=!1,calls:g=[],sound:b,soundOpen:f=!1,voices:v=[]}={}){var m,$,w;let y=a!=null?a:r.softphone,h=($=(m=r[hn[n.status]])!=null?m:St[n.status])!=null?$:n.status;return d`<div class="card phone" role="region" aria-label="${y}">
85
+ <div class="head"><h2>${y}</h2><span class="pill"><i class="dot ${n.status}"></i>${h}</span></div>
86
+ <div class="sr" role="status" aria-live="polite">${h}${n.caller?`: ${n.caller}`:""}</div>
87
+ ${n.error?d`<p class="err" role="alert">${n.error}</p>`:""}
88
+ ${n.warning?d`<p class="status bad" role="status">${n.warning}</p>`:""}
89
+ ${n.status==="off"||n.status==="error"?d`<div class="btns"><button class="primary" data-action="start">${n.status==="error"?r.tryAgain:r.goOnline}</button></div>
90
+ <p class="hint">${r.goOnlineHint}</p>`:""}
91
+ ${n.status==="connecting"?d`<p class="hint">${r.connecting}</p>`:""}
92
+ ${n.status==="ready"?d`
93
+ ${Et(n,r)}
94
+ <p class="hint">${n.sipUsername?d`${r.waiting} · <b>${n.sipUsername}</b>`:r.waiting}</p>
95
+ ${n.placing?d`<p class="status" role="status">${R(r,"placing",{number:n.placing.number})}</p>`:""}
96
+ ${e&&i?H(i,{S:r,busy:n.dialing}):""}
97
+ ${e&&!i?d`<form data-submit="dial"><label for="dial">${r.numberLabel}</label>
98
+ <div class="row"><input id="dial" data-key="dial" type="tel" inputmode="tel" autocomplete="off" placeholder="+18765550100" value="${s}" /><button class="primary fixed" type="submit" ${n.dialing?"disabled":""}>${n.dialing?"\u2026":r.phone}</button></div></form>`:""}
99
+ ${g.length?d`<h3>${r.recent}</h3>${$e(g,r)}`:""}
100
+ ${b?oe(b,r,{open:f,voices:v,idPrefix:"sp-snd"}):""}
101
+ <div class="btns"><button data-action="stop">${r.goOffline}</button></div>`:""}
102
+ ${n.status==="ringing"?d`<div class="who">${n.caller}</div><div class="hint">${r.isCalling}</div>
103
+ <div class="btns"><button class="ok" data-action="answer">${r.answer}</button><button class="danger" data-action="hangup">${r.decline}</button></div>`:""}
104
+ ${n.status==="in-call"?d`${xe(n,{S:r,now:t,canHold:o,canDtmf:l,keypadOpen:c})}${c&&i?H(i,{S:r,mode:"dtmf"}):""}`:""}
105
+ ${(w=n.recent)!=null&&w.length?d`<h3>${r.recent}</h3><ul class="recent">${n.recent.map(x=>d`<li>${x.type}</li>`)}</ul>`:""}
106
+ </div>`.toString()}var we=class extends K{get css(){return pn}render(){var a,r;let e=this.S,t=this.controller,s=(a=t==null?void 0:t.snapshot())!=null?a:{status:"off",error:this._client&&this._adapter?null:e.needSetup,recent:[]};return Ot(s,{allowDial:this.hasAttribute("allow-dial"),dial:(r=this._dial)!=null?r:"",S:e,dp:this.dp,now:Date.now(),canHold:!!(t!=null&&t.canHold),canDtmf:!!(t!=null&&t.canDtmf),keypadOpen:this.keypadOpen,calls:this.recentCalls(),sound:this.sound,soundOpen:this._sndOpen,voices:this.sound.voices()})}onClick(e,t){var a,r,i;if(this.phoneClick(e,t))return;let s=this.controller;if(s&&e==="dial"){let o=De((i=(r=(a=t.querySelector)==null?void 0:a.call(t,'[data-key="dial"]'))==null?void 0:r.value)!=null?i:this._dial);this._dial=o,s.dial(o).then(l=>{l&&(this._dial=""),this.requestRender()})}}onInput(e){e.dataset.key==="dial"?this._dial=De(e.value):super.onInput(e)}};A("traitos-softphone",we);var At=Object.freeze(["bottom-right","bottom-left","top-right","top-left"]);function Be({position:n,inline:e}={}){return e?{mode:"inline",corner:null}:n&&At.includes(n)?{mode:"floating",corner:n}:{mode:"header",corner:null}}function Ge(n,e,t={}){var b,f;let s=(b=t.width)!=null?b:300,a=(f=t.height)!=null?f:460,r=e.width-n.left,i=n.right,o=r>=s||r>=i?"left":"right",l=e.height-n.bottom,c=n.top,g=l>=a||l>=c?"down":"up";return{h:o,v:g}}function Je({inline:n=!1,onChange:e}={}){let t=n,s=a=>{let r=n?!0:!!a;return r===t?!1:(t=r,e==null||e(t),!0)};return{get open(){return t},openIt:()=>s(!0),close:()=>s(!1),toggle:()=>s(!t),setInline(a){n=!!a,n&&!t&&(t=!0,e==null||e(!0))},onKey(a){return a==="Escape"&&t&&!n?s(!1):!1},onOutside(a,r){return t&&!n&&!a.includes(r)?s(!1):!1}}}function Ye(n,{status:e,missed:t,open:s}){let a=s?n.closePhone:n.openPhone,r=e==="ringing"?n.ringing:e==="in-call"?n.inCall:t>0?n.missedBadge.replace("{n}",String(t)):"";return r?`${a} \u2014 ${r}`:a}var fn='<svg viewBox="0 0 24 24" width="22" height="22" aria-hidden="true" focusable="false"><path fill="currentColor" d="M6.6 10.8a15 15 0 0 0 6.6 6.6l2.2-2.2a1 1 0 0 1 1-.25 11.4 11.4 0 0 0 3.6.57 1 1 0 0 1 1 1V20a1 1 0 0 1-1 1A17 17 0 0 1 3 4a1 1 0 0 1 1-1h3.5a1 1 0 0 1 1 1c0 1.25.2 2.45.57 3.6a1 1 0 0 1-.25 1z"/></svg>',mn=Q+`
107
+ :host { display: inline-block; position: relative; }
108
+ :host([inline]) { display: block; }
109
+ :host([position]) { position: fixed; z-index: var(--traitos-z, 2147483000); }
110
+ :host([position="bottom-right"]) { right: max(16px, env(safe-area-inset-right)); bottom: max(16px, env(safe-area-inset-bottom)); }
111
+ :host([position="bottom-left"]) { left: max(16px, env(safe-area-inset-left)); bottom: max(16px, env(safe-area-inset-bottom)); }
112
+ :host([position="top-right"]) { right: max(16px, env(safe-area-inset-right)); top: max(16px, env(safe-area-inset-top)); }
113
+ :host([position="top-left"]) { left: max(16px, env(safe-area-inset-left)); top: max(16px, env(safe-area-inset-top)); }
114
+ .fab { position: relative; width: 44px; height: 44px; min-width: 44px; padding: 0; border-radius: 50%; display: inline-flex; align-items: center; justify-content: center; background: var(--_bg); color: inherit; border: 1px solid var(--_line); }
115
+ :host([position]) .fab { width: 56px; height: 56px; background: var(--_accent); border-color: var(--_accent); color: #fff; box-shadow: 0 4px 14px rgba(0,0,0,.25); }
116
+ .fab.ringing, .fab.in-call { background: var(--_accent); border-color: var(--_accent); color: #fff; }
117
+ .fab.ringing { animation: ring 1s infinite; } .fab.in-call { box-shadow: 0 0 0 3px color-mix(in srgb, var(--_ok) 55%, transparent); }
118
+ .badge { position: absolute; top: -4px; right: -4px; min-width: 18px; height: 18px; padding: 0 5px; border-radius: 9px; background: var(--_bad); color: #fff; font-size: 11px; line-height: 18px; text-align: center; font-weight: 700; }
119
+ .panel, .mini { position: absolute; z-index: 1; width: min(320px, calc(100vw - 16px)); max-height: calc(100vh - 80px); overflow: auto; background: var(--_bg); border: 1px solid var(--_line); border-radius: var(--_r); padding: 14px; box-shadow: 0 10px 30px rgba(0,0,0,.22); }
120
+ .panel[data-v="down"], .mini[data-v="down"] { top: calc(100% + 8px); } .panel[data-v="up"], .mini[data-v="up"] { bottom: calc(100% + 8px); }
121
+ .panel[data-h="left"], .mini[data-h="left"] { left: 0; } .panel[data-h="right"], .mini[data-h="right"] { right: 0; }
122
+ .panel.inline { position: static; width: 100%; max-height: none; box-shadow: none; } .mini { width: min(300px, calc(100vw - 16px)); }
123
+ .snd { margin-top: 10px; } .snd-panel { display: grid; gap: 4px; margin-top: 6px; } .snd-check { display: flex; align-items: center; gap: 6px; margin: 4px 0; } .snd-toggle { width: 100%; text-align: left; } .snd input[type=range] { padding: 0; }
124
+ .panel h2 { margin-bottom: 6px; } .panel .hint:empty { display: none; }
125
+ @keyframes ring { 0%,100% { box-shadow: 0 0 0 0 color-mix(in srgb, var(--_accent) 60%, transparent); } 50% { box-shadow: 0 0 0 9px transparent; } }
126
+ `,cs={inline:{h:"left",v:"down"}};function Nt(n,{S:e=q(),dp:t,open:s=!1,inline:a=!1,side:r={h:"left",v:"down"},calls:i=[],missed:o=0,now:l=Date.now(),canHold:c=!1,canDtmf:g=!1,keypadOpen:b=!1,hasController:f=!1,sound:v,soundOpen:y=!1,voices:h=[]}={}){var J;let m=n.status==="ringing"||n.status==="in-call",$=Ye(e,{status:n.status,missed:o,open:s}),w=n.status==="ringing"?`${e.ringing}: ${(J=n.caller)!=null?J:""}`:n.status==="in-call"?e.inCall:"",x=n.status==="ringing"?d`<div class="who">${n.caller}</div><div class="hint">${e.isCalling}</div><div class="btns"><button class="ok" data-action="answer">${e.answer}</button><button class="danger" data-action="hangup">${e.decline}</button></div>`:d`${xe(n,{S:e,now:l,canHold:c,canDtmf:g,keypadOpen:b})}${b&&t?H(t,{S:e,mode:"dtmf"}):""}`,T=!f||n.status==="ready",I=m?x:d`
127
+ ${n.error?d`<p class="err" role="alert">${n.error}</p>`:""}
128
+ ${n.warning?d`<p class="status bad" role="status">${n.warning}</p>`:""}
129
+ ${f&&(n.status==="off"||n.status==="error")?d`<div class="btns"><button class="primary" data-action="start">${n.status==="error"?e.tryAgain:e.goOnline}</button></div><p class="hint">${e.goOnlineHint}</p>`:""}
130
+ ${f&&n.status==="connecting"?d`<p class="hint" role="status">${e.connecting}</p>`:""}
131
+ ${f&&n.status==="ready"?Et(n,e):""}
132
+ ${n.placing?d`<p class="status" role="status">${R(e,"placing",{number:n.placing.number})}</p>`:""}
133
+ ${T&&t?H(t,{S:e,busy:n.dialing}):""}
134
+ ${f&&n.status==="ready"?d`<h3>${e.recent}</h3>${$e(i,e)}`:""}
135
+ ${v&&T?oe(v,e,{open:y,voices:h,idPrefix:"w-snd"}):""}`,S=d`<div class="panel ${a?"inline":""}" id="panel" role="dialog" aria-modal="false" aria-label="${e.dialogLabel}" data-h="${r.h}" data-v="${r.v}">${I}</div>`,V=d`<div class="mini" role="region" aria-label="${e.dialogLabel}" data-h="${r.h}" data-v="${r.v}">${x}</div>`;return d`<div class="w">
136
+ ${a?"":d`<button type="button" class="fab ${n.status}" id="fab" data-action="toggle" aria-haspopup="dialog" aria-expanded="${String(!!s)}" aria-controls="panel" aria-label="${$}"><slot name="icon">${k(fn)}</slot>${o>0&&!m?d`<span class="badge" aria-hidden="true">${o>9?"9+":o}</span>`:""}</button>`}
137
+ ${s||a?S:m?V:""}
138
+ <div class="sr" role="status" aria-live="polite">${w}</div>
139
+ </div>`.toString()}var ke=class extends K{static get observedAttributes(){return[...super.observedAttributes,"open"]}constructor(){super(),this.pop=Je({onChange:e=>this._opened(e)})}get css(){return mn}get isOpen(){return this.pop.open}open(){return this.pop.openIt()}close(){return this.pop.close()}toggle(){return this.pop.toggle()}mounted(){super.mounted(),this.pop.setInline(this.hasAttribute("inline")),this.hasAttribute("open")&&this.pop.openIt(),this._onDocPointer=e=>this.pop.onOutside(e.composedPath(),this),this._onDocKey=e=>{this.pop.onKey(e.key)&&this._focusIcon()},document.addEventListener("pointerdown",this._onDocPointer,!0),document.addEventListener("keydown",this._onDocKey)}unmounted(){document.removeEventListener("pointerdown",this._onDocPointer,!0),document.removeEventListener("keydown",this._onDocKey),super.unmounted()}attributeChangedCallback(e){e==="inline"&&this.pop.setInline(this.hasAttribute("inline")),e==="open"&&(this.hasAttribute("open")?this.pop.openIt():this.pop.close()),this.requestRender()}_opened(e){var t;e&&((t=this.log)==null||t.markSeen()),this.emit("traitos-toggle",{open:e}),this.requestRender(),e&&!this.hasAttribute("inline")&&setTimeout(()=>{var s,a;return(a=(s=this.shadowRoot)==null?void 0:s.getElementById("kp-number"))==null?void 0:a.focus()},0)}_focusIcon(){setTimeout(()=>{var e,t;return(t=(e=this.shadowRoot)==null?void 0:e.getElementById("fab"))==null?void 0:t.focus()},0)}_side(){var s;let e=Be({position:this.getAttribute("position"),inline:this.hasAttribute("inline")});if(e.mode==="floating")return{h:e.corner.endsWith("right")?"right":"left",v:e.corner.startsWith("bottom")?"up":"down"};if(e.mode==="inline")return cs.inline;let t=(s=this.getBoundingClientRect)==null?void 0:s.call(this);return t?Ge(t,{width:window.innerWidth,height:window.innerHeight}):cs.inline}render(){var a,r,i;let e=this.controller,t=this.S,s=(a=e==null?void 0:e.snapshot())!=null?a:{status:"off",recent:[],error:null};return Nt(s,{S:t,dp:this.dp,open:this.pop.open,inline:this.hasAttribute("inline"),side:this._side(),calls:this.recentCalls(),missed:(i=(r=this.log)==null?void 0:r.missedCount())!=null?i:0,now:Date.now(),canHold:!!(e!=null&&e.canHold),canDtmf:!!(e!=null&&e.canDtmf),keypadOpen:this.keypadOpen,hasController:!!e,sound:this.sound,soundOpen:this._sndOpen,voices:this.sound.voices()})}onClick(e,t){if(e==="toggle"){this.pop.toggle();return}this.phoneClick(e,t)}};A("traitos-dialer-widget",ke);var gn=/^[A-Za-z0-9._-]{3,64}$/,Se=4,M={min:5,max:60,softphone:15,phone:30},Pt=["gt","gte","lt","lte","eq","neq","contains"],us={gt:"is more than",gte:"is at least",lt:"is less than",lte:"is at most",eq:"is",neq:"is not",contains:"contains"},Ze=n=>JSON.parse(JSON.stringify(n)),It=(n,e)=>JSON.stringify(n)===JSON.stringify(e),Ve=(n,e,t)=>Number.isInteger(Number(n))&&String(n).trim()!==""&&Number(n)>=e&&Number(n)<=t,bn={id:"handoff",label:"Human handoff",description:"Who is rung, in order, when an agent passes a conversation to a person. If nobody answers, the AI carries on.",needsAgent:!0,async load(n,{agentId:e}){var s,a,r,i,o;let t=await n.agents.handoffSettings.get(e);return{transferNumber:(s=t.transferNumber)!=null?s:"",callerId:(r=(a=t.routing)==null?void 0:a.callerId)!=null?r:"customer",steps:((o=(i=t.routing)==null?void 0:i.steps)!=null?o:[]).map(l=>{var c,g;return{kind:l.kind,target:l.target,ringSecs:(g=(c=l.ringSecs)!=null?c:M[l.kind])!=null?g:M.phone}})}},validate(n){let e={};return n.transferNumber&&!z(n.transferNumber)&&(e.transferNumber="Use + then country code and number, like +18765550100."),n.steps.length>Se&&(e.steps=`At most ${Se} people can be rung.`),n.steps.forEach((t,s)=>{var a;t.kind!=="softphone"&&t.kind!=="phone"?e[`steps.${s}.kind`]="Choose softphone or phone.":t.kind==="phone"&&!z(t.target)?e[`steps.${s}.target`]="Use + then country code and number.":t.kind==="softphone"&&!gn.test(String((a=t.target)!=null?a:""))&&(e[`steps.${s}.target`]="A softphone name has 3 to 64 letters, numbers, dots, dashes or underscores."),Ve(t.ringSecs,M.min,M.max)||(e[`steps.${s}.ringSecs`]=`Ring for ${M.min} to ${M.max} seconds.`)}),n.callerId!=="customer"&&n.callerId!=="platform"&&(e.callerId="Choose which number the person sees."),e},toPatch(n,e){let t={};n.transferNumber!==e.transferNumber&&(t.transferNumber=e.transferNumber||null);let s=a=>({steps:a.steps.map(r=>({kind:r.kind,target:String(r.target).trim(),ringSecs:Number(r.ringSecs)})),callerId:a.callerId});return It(s(n),s(e))||(t.routing=e.steps.length?s(e):null),Object.keys(t).length?t:null},save:(n,{agentId:e},t)=>n.agents.handoffSettings.update(e,t),addStep(n,e="phone"){n.steps.length<Se&&n.steps.push({kind:e,target:"",ringSecs:M[e]})},removeStep(n,e){n.steps.splice(e,1)},moveStep(n,e,t){let s=e+t;s>=0&&s<n.steps.length&&([n.steps[e],n.steps[s]]=[n.steps[s],n.steps[e]])},setStep(n,e,t,s){var r;let a=n.steps[e];a&&(a[t]=t==="ringSecs"?s===""?"":Number(s):s,t==="kind"&&(a.ringSecs=(r=M[s])!=null?r:a.ringSecs))}},yn={id:"approvals",label:"Approvals",description:"When an agent must ask a person first, how long it waits, and what happens if nobody answers.",needsAgent:!1,async load(n,{agentId:e}){var a,r,i,o;let[t,s]=await Promise.all([n.approvals.settings(),e?n.approvals.rules.list(e):Promise.resolve({rules:[]})]);return{timeoutMinutes:(a=t.timeoutMinutes)!=null?a:60,onTimeout:(r=t.onTimeout)!=null?r:"escalate",liveWaitSeconds:(i=t.liveWaitSeconds)!=null?i:0,notifyEmail:!!t.notifyEmail,rules:((o=s.rules)!=null?o:[]).map(l=>{var c;return{tool:l.tool,action:l.action,note:(c=l.note)!=null?c:"",...l.when?{when:{...l.when}}:{}}})}},validate(n){let e={};return Ve(n.timeoutMinutes,1,1440*14)||(e.timeoutMinutes="Choose between 1 minute and 14 days (20160)."),n.onTimeout!=="escalate"&&n.onTimeout!=="deny"&&(e.onTimeout="Choose what happens when nobody answers."),Ve(n.liveWaitSeconds,0,600)||(e.liveWaitSeconds="Choose between 0 and 600 seconds."),n.rules.forEach((t,s)=>{var a,r,i;String((a=t.tool)!=null?a:"").trim()||(e[`rules.${s}.tool`]="Name a tool, like refund.create or refund.*."),["ask","allow","deny"].includes(t.action)||(e[`rules.${s}.action`]="Choose ask, allow or deny."),t.when&&(String((r=t.when.field)!=null?r:"").trim()||(e[`rules.${s}.when.field`]="Name the field to check."),Pt.includes(t.when.op)||(e[`rules.${s}.when.op`]="Choose a comparison."),String((i=t.when.value)!=null?i:"")===""&&(e[`rules.${s}.when.value`]="Give a value to compare with."))}),e},toPatch(n,e){let t={},s={};for(let r of["timeoutMinutes","onTimeout","liveWaitSeconds","notifyEmail"])n[r]!==e[r]&&(s[r]=r==="onTimeout"||r==="notifyEmail"?e[r]:Number(e[r]));Object.keys(s).length&&(t.settings=s);let a=r=>r.rules.map(i=>({tool:i.tool.trim(),action:i.action,...i.note?{note:i.note}:{},...i.when?{when:{field:i.when.field.trim(),op:i.when.op,value:Number.isFinite(Number(i.when.value))&&String(i.when.value).trim()!==""?Number(i.when.value):i.when.value}}:{}}));return It(a(n),a(e))||(t.rules=a(e)),Object.keys(t).length?t:null},async save(n,{agentId:e},t){if(t.settings&&await n.approvals.updateSettings(t.settings),t.rules){if(!e)throw new Error("Choose an agent to change its approval rules.");await n.approvals.rules.set(e,t.rules)}},addRule(n){n.rules.push({tool:"",action:"ask",note:""})},removeRule(n,e){n.rules.splice(e,1)},setRule(n,e,t,s){n.rules[e]&&(n.rules[e][t]=s)},toggleCondition(n,e,t){var a;let s=n.rules[e];s&&(t?s.when=(a=s.when)!=null?a:{field:"",op:"gt",value:""}:delete s.when)},setCondition(n,e,t,s){let a=n.rules[e];a!=null&&a.when&&(a.when[t]=s)}},_n={id:"usage",label:"Usage and spend cap",description:"This month against your plan. Set a cap and conversations pause (with your message) instead of running up overage.",needsAgent:!1,async load(n){var s,a,r,i,o,l,c;let e=await n.usage.current(),t=(s=e.overage)==null?void 0:s.spendCapCents;return{meters:(a=e.meters)!=null?a:[],period:e.period,status:e.status,plan:(i=(r=e.plan)==null?void 0:r.name)!=null?i:"",overageCents:(l=(o=e.overage)==null?void 0:o.cents)!=null?l:0,spendCap:t==null?"":String(t/100),fallbackMessage:(c=e.fallbackMessage)!=null?c:""}},validate(n){let e={};return n.spendCap!==""&&!(Number.isFinite(Number(n.spendCap))&&Number(n.spendCap)>=0)&&(e.spendCap="Enter an amount in dollars, or leave blank for no cap."),String(n.fallbackMessage).length>500&&(e.fallbackMessage="Keep this under 500 characters."),e},toPatch(n,e){let t={};return n.spendCap!==e.spendCap&&(t.spendCapCents=e.spendCap===""?null:Math.round(Number(e.spendCap)*100)),n.fallbackMessage!==e.fallbackMessage&&(t.fallbackMessage=e.fallbackMessage||null),Object.keys(t).length?t:null},save:(n,e,t)=>n.usage.updateSettings(t)},qt=[{id:"direct",label:"Direct",hint:"Place the call straight to the customer."},{id:"agent-first",label:"Agent first",hint:"Ring the agent first, then connect the customer."}],vn={id:"dialer",label:"Dialer",description:"Your phone lines, how outbound calls are placed, and how this browser rings.",needsAgent:!1,async load(n,{storage:e}){var o;let[t,s]=await Promise.allSettled([je(n),rs(n)]);if(t.status==="rejected"&&s.status==="rejected")throw s.reason;let a=Fe(e),r=t.status==="fulfilled"?t.value:[],i=l=>Array.isArray(l.channels)?l.channels:[];return{mode:s.status==="fulfilled"?s.value:null,lines:r.map(l=>{var c;return{number:l.number,name:(c=l.name)!=null?c:"",whatsapp:i(l).includes("whatsapp_calling"),phone:i(l).includes("voice")}}),whatsappEnabled:r.some(l=>i(l).includes("whatsapp_calling")),phoneEnabled:r.some(l=>i(l).includes("voice")),ringTimeoutSeconds:a.ringTimeoutSeconds,ringWhatsapp:a.ringChannels.whatsapp,ringPhone:a.ringChannels.phone,callerId:(o=a.callerId)!=null?o:""}},validate(n){let e={};return n.mode!==null&&!qt.some(t=>t.id===n.mode)&&(e.mode="Choose how outbound calls are placed."),Ve(n.ringTimeoutSeconds,0,60)||(e.ringTimeoutSeconds=`Ring for 0 to ${60} seconds.`),e},toPatch(n,e){let t={};e.mode!==null&&n.mode!==e.mode&&(t.mode=e.mode);let s=a=>U({ringTimeoutSeconds:a.ringTimeoutSeconds,ringChannels:{whatsapp:a.ringWhatsapp,phone:a.ringPhone},callerId:a.callerId});return It(s(n),s(e))||(t.prefs=s(e)),Object.keys(t).length?t:null},async save(n,{storage:e},t){var s;t.mode&&await is(n,t.mode),t.prefs&&(ze(e,t.prefs),(s=globalThis.dispatchEvent)==null||s.call(globalThis,new CustomEvent(ve)))}},N=Object.freeze({handoff:bn,approvals:yn,usage:_n,dialer:vn});var le=class{constructor({client:e,agentId:t,sections:s=["handoff","approvals","usage"],storage:a}){this.client=e,this.storage=a,this.agentId=t,this.ids=s.filter(r=>N[r]),this._listeners=new Set,this._seq={},this.state=Object.fromEntries(this.ids.map(r=>[r,this._blank(r)]))}_blank(e){let t=N[e].needsAgent&&!this.agentId;return{id:e,status:t?"needs-agent":"idle",original:null,draft:null,errors:{},message:null,dirty:!1}}snapshot(){return Object.fromEntries(this.ids.map(e=>[e,{...this.state[e]}]))}subscribe(e){return this._listeners.add(e),()=>this._listeners.delete(e)}_patch(e,t){this.state[e]={...this.state[e],...t};for(let s of[...this._listeners])try{s(this.snapshot())}catch{}}setAgent(e){this.agentId=e;for(let t of this.ids)this.state[t]=this._blank(t);return this.loadAll()}loadAll(){return Promise.all(this.ids.map(e=>this.load(e)))}async load(e){var a;let t=N[e];if(t.needsAgent&&!this.agentId)return this._patch(e,{status:"needs-agent"});let s=this._seq[e]=((a=this._seq[e])!=null?a:0)+1;this._patch(e,{status:"loading",message:null});try{let r=await t.load(this.client,{agentId:this.agentId,storage:this.storage});if(s!==this._seq[e])return;this._patch(e,{status:"ready",original:r,draft:Ze(r),errors:{},dirty:!1})}catch(r){if(s!==this._seq[e])return;this._patch(e,{status:"error",message:(r==null?void 0:r.message)||"Could not load this section."})}}edit(e,t){let s=this.state[e];if(!s.draft||s.status==="saving")return;let a=Ze(s.draft);t(a,N[e]);let r=N[e].validate(a);this._patch(e,{draft:a,errors:r,dirty:N[e].toPatch(s.original,a)!==null,message:null,status:s.status==="saved"?"ready":s.status})}set(e,t,s){this.edit(e,a=>{a[t]=s})}reset(e){let t=this.state[e];t.original&&this._patch(e,{draft:Ze(t.original),errors:{},dirty:!1,message:null,status:"ready"})}async save(e){let t=N[e],s=this.state[e];if(!s.draft||s.status==="saving")return!1;let a=t.validate(s.draft);if(Object.keys(a).length)return this._patch(e,{errors:a,message:"Fix the highlighted fields first."}),!1;let r=t.toPatch(s.original,s.draft);if(!r)return this._patch(e,{message:"Nothing to save."}),!1;this._patch(e,{status:"saving",message:null});try{return await t.save(this.client,{agentId:this.agentId,storage:this.storage},r),await this.load(e),this._patch(e,{status:"saved",message:"Saved."}),!0}catch(i){return this._patch(e,{status:"ready",message:(i==null?void 0:i.message)||"Could not save."}),!1}}};var wn=`
140
+ section.card { margin-bottom: 14px; } .steps { list-style: none; margin: 0; padding: 0; } .steps > li, .rule { border: 1px solid var(--_line); border-radius: calc(var(--_r) - 4px); padding: 8px 10px; margin: 6px 0; }
141
+ .meter { margin: 8px 0; } .meter .top { display: flex; justify-content: space-between; font-size: 13px; }
142
+ .linkish { background: none; border: 0; color: var(--_accent); padding: 2px 4px; }
143
+ `,P=(n,e)=>n[e]?d`<p class="err" id="e-${e}" role="alert">${n[e]}</p>`:"",X=(n,e)=>n[e]?'aria-invalid="true"':"";function Qe(n,e,t,s,{type:a="text",hint:r="",attrs:i="",section:o,f:l,i:c}){let g=`${o}-${e}`;return d`<label for="${g}">${t}</label>
144
+ <input id="${g}" data-key="${e}" data-s="${o}" data-f="${l!=null?l:e}" ${c!==void 0?k(`data-i="${c}"`):""} type="${a}" value="${s!=null?s:""}" ${k(i)} ${k(X(n,e))} />
145
+ ${r?d`<p class="hint">${r}</p>`:""}${P(n,e)}`}function $n(n){let{draft:e,errors:t}=n;return d`
146
+ ${Qe(t,"transferNumber","Transfer number",e.transferNumber,{type:"tel",hint:"A phone number to transfer to. Leave empty for none.",section:"handoff"})}
147
+ <h3>Who to ring, in order</h3>
148
+ ${P(t,"steps")}
149
+ <ol class="steps">${e.steps.map((s,a)=>d`<li>
150
+ <div class="row">
151
+ <div><label for="h-kind-${a}">Ring a</label><select id="h-kind-${a}" data-key="steps.${a}.kind" data-s="handoff" data-i="${a}" data-f="kind"><option value="softphone" ${s.kind==="softphone"?"selected":""}>Browser softphone</option><option value="phone" ${s.kind==="phone"?"selected":""}>Phone number</option></select></div>
152
+ <div><label for="h-target-${a}">${s.kind==="phone"?"Number":"Softphone name"}</label><input id="h-target-${a}" data-key="steps.${a}.target" data-s="handoff" data-i="${a}" data-f="target" value="${s.target}" placeholder="${s.kind==="phone"?"+18765550100":"agent_01"}" ${k(X(t,`steps.${a}.target`))} />${P(t,`steps.${a}.target`)}</div>
153
+ <div class="fixed" style="width:96px"><label for="h-ring-${a}">Seconds</label><input id="h-ring-${a}" data-key="steps.${a}.ringSecs" data-s="handoff" data-i="${a}" data-f="ringSecs" type="number" min="${M.min}" max="${M.max}" value="${s.ringSecs}" ${k(X(t,`steps.${a}.ringSecs`))} />${P(t,`steps.${a}.ringSecs`)}</div>
154
+ <div class="fixed"><button type="button" data-action="step-up" data-s="handoff" data-i="${a}" aria-label="Move step ${a+1} up" ${a===0?"disabled":""}>↑</button> <button type="button" data-action="step-down" data-s="handoff" data-i="${a}" aria-label="Move step ${a+1} down" ${a===e.steps.length-1?"disabled":""}>↓</button> <button type="button" class="linkish" data-action="step-remove" data-s="handoff" data-i="${a}" aria-label="Remove step ${a+1}">Remove</button></div>
155
+ </div></li>`)}</ol>
156
+ <button type="button" data-action="step-add" data-s="handoff" ${e.steps.length>=Se?"disabled":""}>Add someone to ring</button>
157
+ <label for="h-caller">The person sees</label>
158
+ <select id="h-caller" data-key="callerId" data-s="handoff" data-f="callerId"><option value="customer" ${e.callerId==="customer"?"selected":""}>The customer's number</option><option value="platform" ${e.callerId==="platform"?"selected":""}>Your company number</option></select>${P(t,"callerId")}`}function xn(n,e){let{draft:t,errors:s}=n;return d`
159
+ <div class="row">
160
+ <div>${Qe(s,"timeoutMinutes","Wait for an answer (minutes)",t.timeoutMinutes,{type:"number",section:"approvals",attrs:'min="1" max="20160"'})}</div>
161
+ <div><label for="a-on">If nobody answers</label><select id="a-on" data-key="onTimeout" data-s="approvals" data-f="onTimeout"><option value="escalate" ${t.onTimeout==="escalate"?"selected":""}>Escalate to a person</option><option value="deny" ${t.onTimeout==="deny"?"selected":""}>Deny the request</option></select>${P(s,"onTimeout")}</div>
162
+ <div>${Qe(s,"liveWaitSeconds","Live chat wait (seconds)",t.liveWaitSeconds,{type:"number",section:"approvals",attrs:'min="0" max="600"'})}</div>
163
+ </div>
164
+ <label><input type="checkbox" data-key="notifyEmail" data-s="approvals" data-f="notifyEmail" ${t.notifyEmail?"checked":""} />Email admins when something needs approval</label>
165
+ <h3>Rules for this agent</h3>
166
+ ${e?"":d`<p class="hint">Choose an agent to edit its rules.</p>`}
167
+ ${e?d`${t.rules.map((a,r)=>d`<div class="rule">
168
+ <div class="row">
169
+ <div><label for="r-tool-${r}">Tool</label><input id="r-tool-${r}" data-key="rules.${r}.tool" data-s="approvals" data-i="${r}" data-f="tool" value="${a.tool}" placeholder="refund.create or refund.*" ${k(X(s,`rules.${r}.tool`))} />${P(s,`rules.${r}.tool`)}</div>
170
+ <div class="fixed"><label for="r-act-${r}">Then</label><select id="r-act-${r}" data-key="rules.${r}.action" data-s="approvals" data-i="${r}" data-f="action">${["ask","allow","deny"].map(i=>d`<option value="${i}" ${a.action===i?"selected":""}>${i==="ask"?"Ask a person":i==="allow"?"Allow":"Deny"}</option>`)}</select></div>
171
+ <div class="fixed"><button type="button" class="linkish" data-action="rule-remove" data-s="approvals" data-i="${r}" aria-label="Remove rule ${r+1}">Remove</button></div>
172
+ </div>
173
+ <label><input type="checkbox" data-key="rules.${r}.cond" data-s="approvals" data-i="${r}" data-f="cond" ${a.when?"checked":""} />Only when a value matches</label>
174
+ ${a.when?d`<div class="row">
175
+ <div><input aria-label="Field" data-key="rules.${r}.when.field" data-s="approvals" data-i="${r}" data-f="when.field" value="${a.when.field}" placeholder="amount" ${k(X(s,`rules.${r}.when.field`))} />${P(s,`rules.${r}.when.field`)}</div>
176
+ <div class="fixed"><select aria-label="Comparison" data-key="rules.${r}.when.op" data-s="approvals" data-i="${r}" data-f="when.op">${Pt.map(i=>d`<option value="${i}" ${a.when.op===i?"selected":""}>${us[i]}</option>`)}</select></div>
177
+ <div><input aria-label="Value" data-key="rules.${r}.when.value" data-s="approvals" data-i="${r}" data-f="when.value" value="${a.when.value}" placeholder="100" ${k(X(s,`rules.${r}.when.value`))} />${P(s,`rules.${r}.when.value`)}</div>
178
+ </div>`:""}</div>`)}
179
+ <button type="button" data-action="rule-add" data-s="approvals">Add a rule</button>`:""}`}function kn(n){let{draft:e,errors:t}=n;return d`
180
+ <p class="hint">${e.plan?d`<b>${e.plan}</b> plan, `:""}${e.period}${e.status==="paused"?" \u2014 conversations are paused (cap reached)":""}</p>
181
+ ${e.meters.map(s=>{var a,r;return d`<div class="meter"><div class="top"><span>${s.label}</span><span>${s.used}${s.included===null?" (unlimited)":` of ${s.included}`}</span></div>
182
+ <div class="bar" role="progressbar" aria-label="${s.label}" aria-valuemin="0" aria-valuemax="100" aria-valuenow="${(a=s.percent)!=null?a:0}"><i style="width:${Math.min(100,(r=s.percent)!=null?r:0)}%"></i></div></div>`})}
183
+ ${Qe(t,"spendCap","Monthly spend cap (USD)",e.spendCap,{type:"number",hint:"Blank means no cap. Past the cap, conversations pause instead of billing overage.",section:"usage",attrs:'min="0" step="0.01"'})}
184
+ <label for="u-msg">Message customers see while paused</label>
185
+ <textarea id="u-msg" rows="2" data-key="fallbackMessage" data-s="usage" data-f="fallbackMessage">${e.fallbackMessage}</textarea>${P(t,"fallbackMessage")}`}function Sn(n){let{draft:e,errors:t}=n,s=a=>a.name?`${a.name} \xB7 ${a.number}`:a.number;return d`
186
+ <h3>Lines</h3>
187
+ ${e.lines.length?d`<ul class="steps">${e.lines.map(a=>d`<li>${s(a)} <span class="hint">${[a.whatsapp&&"WhatsApp",a.phone&&"Phone"].filter(Boolean).join(" \xB7 ")}</span></li>`)}</ul>`:d`<p class="hint">No phone lines yet.</p>`}
188
+ <p class="hint">Enabled for calling: ${[e.whatsappEnabled&&"WhatsApp",e.phoneEnabled&&"Phone"].filter(Boolean).join(", ")||"none"}</p>
189
+ <h3>How outbound calls are placed</h3>
190
+ ${e.mode===null?d`<p class="hint">Not available to this account.</p>`:d`<fieldset style="border:0;padding:0;margin:0"><legend class="sr">How outbound calls are placed</legend>${qt.map(a=>d`<label><input type="radio" name="d-mode" data-key="mode.${a.id}" data-s="dialer" data-f="mode" value="${a.id}" ${e.mode===a.id?"checked":""} />${a.label} <span class="hint">${a.hint}</span></label>`)}</fieldset><p class="hint">Changing this needs an organization admin.</p>${P(t,"mode")}`}
191
+ <h3>This browser</h3>
192
+ <p class="hint">Saved in this browser only; the server does not store these.</p>
193
+ <label for="d-ring">Ring timeout (seconds, 0 for the default)</label>
194
+ <input id="d-ring" type="number" min="0" max="${60}" data-key="ringTimeoutSeconds" data-s="dialer" data-f="ringTimeoutSeconds" value="${e.ringTimeoutSeconds}" ${k(X(t,"ringTimeoutSeconds"))} />${P(t,"ringTimeoutSeconds")}
195
+ <label><input type="checkbox" data-key="ringWhatsapp" data-s="dialer" data-f="ringWhatsapp" ${e.ringWhatsapp?"checked":""} ${e.whatsappEnabled?"":"disabled"} />Ring this browser for WhatsApp calls${e.whatsappEnabled?"":" (not enabled)"}</label>
196
+ <label><input type="checkbox" data-key="ringPhone" data-s="dialer" data-f="ringPhone" ${e.ringPhone?"checked":""} ${e.phoneEnabled?"":"disabled"} />Ring this browser for phone calls${e.phoneEnabled?"":" (not enabled)"}</label>
197
+ <label for="d-caller">Caller ID line</label>
198
+ <select id="d-caller" data-key="callerId" data-s="dialer" data-f="callerId"><option value="">Default line</option>${e.lines.map(a=>d`<option value="${a.number}" ${e.callerId===a.number?"selected":""}>${s(a)}</option>`)}</select>
199
+ <p class="hint">Pass the saved line as <code>from</code> when your page places a call.</p>`}function Rt(n,{agentId:e,ids:t=Object.keys(n)}={}){return d`${t.map(s=>{let a=n[s],r=N[s],i=a.status==="needs-agent"?d`<p class="hint">Choose an agent to edit this section.</p>`:a.status==="loading"||a.status==="idle"?d`<p class="hint" role="status">Loading…</p>`:a.status==="error"?d`<p class="err" role="alert">${a.message}</p><button data-action="reload" data-s="${s}">Try again</button>`:d`<form data-submit="save" data-s="${s}" novalidate>
200
+ ${s==="handoff"?$n(a):s==="approvals"?xn(a,e):s==="dialer"?Sn(a):kn(a)}
201
+ ${a.message?d`<p class="${a.status==="saved"?"status ok":"status bad"}" role="status">${a.message}</p>`:""}
202
+ <div class="actions"><button type="button" data-action="reset" data-s="${s}" ${a.dirty?"":"disabled"}>Discard changes</button><button type="submit" class="primary" ${!a.dirty||a.status==="saving"?"disabled":""}>${a.status==="saving"?"Saving\u2026":"Save"}</button></div></form>`;return d`<section class="card" aria-labelledby="t-${s}"><h2 id="t-${s}">${r.label}</h2><p class="hint">${r.description}</p>${i}</section>`})}`.toString()}var Te=class extends O{static get observedAttributes(){return["agent-id","sections"]}get css(){return wn}set client(e){this._client=e,this._init()}get client(){return this._client}set storage(e){this._storage=e}mounted(){this._init()}unmounted(){var e;(e=this._unsub)==null||e.call(this),this.controller=null}attributeChangedCallback(e,t,s){var a;t!==s&&(e==="agent-id"&&this.controller&&this.controller.setAgent(s||void 0),e==="sections"&&(this.controller=null,(a=this._unsub)==null||a.call(this),this._init()))}_init(){var t,s;if(this.controller||!this._connected||!this._client)return;let e=((t=this.getAttribute("sections"))!=null?t:"handoff,approvals,usage").split(",").map(a=>a.trim()).filter(Boolean);this.controller=new le({client:this._client,agentId:this.getAttribute("agent-id")||void 0,sections:e,storage:(s=this._storage)!=null?s:typeof localStorage!="undefined"?localStorage:void 0}),this._unsub=this.controller.subscribe(()=>this.requestRender()),this.controller.loadAll(),this.requestRender()}render(){return this.controller?Rt(this.controller.snapshot(),{agentId:this.controller.agentId,ids:this.controller.ids}):d`<div class="card"><p class="hint">Set the <code>client</code> property to load settings.</p></div>`.toString()}async onClick(e,t){let s=this.controller,a=t.dataset.s,r=t.dataset.i===void 0?void 0:Number(t.dataset.i);!s||!a||(e==="save"?await s.save(a)?this.emit("traitos-saved",{section:a}):s.state[a].status!=="saving"&&s.state[a].message&&this.emit("traitos-error",{section:a,message:s.state[a].message}):e==="reset"?s.reset(a):e==="reload"?s.load(a):e==="step-add"?s.edit(a,(i,o)=>o.addStep(i)):e==="step-remove"?s.edit(a,(i,o)=>o.removeStep(i,r)):e==="step-up"?s.edit(a,(i,o)=>o.moveStep(i,r,-1)):e==="step-down"?s.edit(a,(i,o)=>o.moveStep(i,r,1)):e==="rule-add"?s.edit(a,(i,o)=>o.addRule(i)):e==="rule-remove"&&s.edit(a,(i,o)=>o.removeRule(i,r)))}_edit(e){let t=this.controller,s=e.dataset.s,a=e.dataset.f,r=e.dataset.i===void 0?void 0:Number(e.dataset.i);if(!t||!s||!a)return;let i=e.type==="checkbox"?e.checked:e.value;s==="dialer"&&e.type==="radio"&&!e.checked||t.edit(s,(o,l)=>{s==="handoff"&&r!==void 0?l.setStep(o,r,a,i):s==="approvals"&&r!==void 0?a==="cond"?l.toggleCondition(o,r,i):a.startsWith("when.")?l.setCondition(o,r,a.slice(5),i):l.setRule(o,r,a,i):o[a]=i})}onInput(e){e.type!=="checkbox"&&e.type!=="radio"&&e.tagName!=="SELECT"&&this._edit(e)}onChange(e){(e.type==="checkbox"||e.type==="radio"||e.tagName==="SELECT")&&this._edit(e)}};A("traitos-settings",Te);var et=["agent","team_member","department","external"],Mt={agent:"AI agent",team_member:"Team member",department:"Department",external:"Phone number"},B=["1","2","3","4","5","6","7","8","9","0"],Lt=[{n:0,label:"Sun"},{n:1,label:"Mon"},{n:2,label:"Tue"},{n:3,label:"Wed"},{n:4,label:"Thu"},{n:5,label:"Fri"},{n:6,label:"Sat"}],tt=()=>({greeting:"Thanks for calling.",menu:{prompt:"For sales press 1. For support press 2.",timeoutSec:6,maxDigits:1,routes:{},fallbackAgentId:null},spam:{rateLimitPer10Min:5,press1ScreenUnverified:!1},hours:{enabled:!1,timezone:"UTC",openHour:9,closeHour:17,days:[1,2,3,4,5],afterHoursAction:"voicemail",afterHoursAgentId:null,voicemailPrompt:""}}),Tn=n=>JSON.parse(JSON.stringify(n)),j=(n,e)=>{let t=Tn(n);return e(t),t};function Ce(n){var s,a,r,i,o;let e=tt(),t=n!=null?n:{};return{...e,...t,menu:{...e.menu,...(s=t.menu)!=null?s:{},routes:{...(r=(a=t.menu)==null?void 0:a.routes)!=null?r:{}}},spam:{...e.spam,...(i=t.spam)!=null?i:{}},hours:{...e.hours,...(o=t.hours)!=null?o:{}}}}var Dt=(n,e)=>j(n,t=>{t.greeting=e}),Ee=(n,e)=>j(n,t=>{Object.assign(t.menu,e)}),st=(n,e)=>j(n,t=>{Object.assign(t.spam,e)}),G=(n,e)=>j(n,t=>{Object.assign(t.hours,e)}),ps=n=>{var e;return(e=B.find(t=>!(t in n.menu.routes)))!=null?e:null};function Ht(n,e){let t=e!=null?e:ps(n);return!t||t in n.menu.routes?n:j(n,s=>{s.menu.routes[t]={extension:t,label:"",targetType:"agent",targetAgentId:null,ringTimeoutSec:20,enabled:!0}})}var Ut=(n,e)=>j(n,t=>{delete t.menu.routes[e]});function nt(n,e,t){return e in n.menu.routes?j(n,s=>{let a=Object.assign(s.menu.routes[e],t);t.targetType&&(a.targetType!=="agent"&&(a.targetAgentId=null),a.targetType!=="team_member"&&(a.teamMemberId=null),a.targetType!=="department"&&(a.departmentTargets=null),a.targetType!=="external"&&(a.externalNumber=null))}):n}function Cn(n,e,t){return e===t||!(e in n.menu.routes)||t in n.menu.routes?n:j(n,s=>{let a=s.menu.routes[e];delete s.menu.routes[e],a.extension=t,s.menu.routes[t]=a})}var jt=(n,e)=>j(n,t=>{let s=new Set(t.hours.days);s.has(e)?s.delete(e):s.add(e),t.hours.days=[...s].sort()});function Oe(n){var a,r,i,o,l,c,g,b,f;let e={};String((a=n.greeting)!=null?a:"").trim()||(e.greeting="Say something when the call connects."),String((i=(r=n.menu)==null?void 0:r.prompt)!=null?i:"").trim()||(e["menu.prompt"]="Tell callers what each number does.");let t=Number((o=n.menu)==null?void 0:o.timeoutSec);t>=1&&t<=30||(e["menu.timeoutSec"]="Wait between 1 and 30 seconds.");for(let[v,y]of Object.entries((c=(l=n.menu)==null?void 0:l.routes)!=null?c:{}))String((g=y.label)!=null?g:"").trim()||(e[`routes.${v}.label`]="Give this choice a name."),y.targetType==="agent"&&!y.targetAgentId?e[`routes.${v}.target`]="Choose an AI agent.":y.targetType==="team_member"&&!y.teamMemberId?e[`routes.${v}.target`]="Choose a team member.":y.targetType==="department"&&!((b=y.departmentTargets)!=null&&b.length)?e[`routes.${v}.target`]="Choose at least one person in the department.":y.targetType==="external"&&!z(y.externalNumber)?e[`routes.${v}.target`]="Use + then country code and number.":et.includes(y.targetType)||(e[`routes.${v}.target`]="Choose who answers.");let s=n.hours;return s!=null&&s.enabled&&(Number.isInteger(+s.openHour)&&+s.openHour>=0&&+s.openHour<=23||(e["hours.openHour"]="Opening hour is 0 to 23."),Number.isInteger(+s.closeHour)&&+s.closeHour>=1&&+s.closeHour<=24?+s.closeHour<=+s.openHour&&(e["hours.closeHour"]="Closing time must be after opening time."):e["hours.closeHour"]="Closing hour is 1 to 24.",(f=s.days)!=null&&f.length||(e["hours.days"]="Pick at least one open day."),s.afterHoursAction==="agent"&&!s.afterHoursAgentId&&(e["hours.afterHoursAgentId"]="Choose who answers after hours.")),e}function Ft(n,e={}){var a;let t=(r,i)=>{var o,l,c;return(c=(l=(o=(r!=null?r:[]).find(g=>g.id===i))==null?void 0:o.name)!=null?l:i)!=null?c:"?"},s=Object.entries(n.menu.routes).sort(([r],[i])=>B.indexOf(r)-B.indexOf(i)).map(([r,i])=>{var o,l;return{digit:r,label:i.label||"(unnamed)",kind:i.targetType,target:i.targetType==="agent"?t(e.agents,i.targetAgentId):i.targetType==="team_member"?t(e.team,i.teamMemberId):i.targetType==="department"?`${(l=(o=i.departmentTargets)==null?void 0:o.length)!=null?l:0} people`:i.externalNumber||"?"}});return{steps:[{kind:"caller",text:"Caller dials"},...(a=n.hours)!=null&&a.enabled?[{kind:"hours",text:`Open ${n.hours.openHour}:00 to ${n.hours.closeHour}:00; after hours: ${n.hours.afterHoursAction==="agent"?t(e.agents,n.hours.afterHoursAgentId):"voicemail"}`}]:[],{kind:"greeting",text:n.greeting},{kind:"menu",text:n.menu.prompt}],routes:s,fallback:n.menu.fallbackAgentId?t(e.agents,n.menu.fallbackAgentId):null}}var de=class{constructor({client:e,phoneNumberId:t,agents:s=[],team:a=[]}){this.client=e,this.phoneNumberId=t,this.lookup={agents:s,team:a},this._listeners=new Set,this._history=[],this._future=[],this.state={status:"idle",flow:tt(),saved:null,enabled:!0,localErrors:{},serverCheck:null,simulation:null,message:null,dirty:!1,busy:!1}}snapshot(){return{...this.state,canUndo:this._history.length>0,canRedo:this._future.length>0}}subscribe(e){return this._listeners.add(e),()=>this._listeners.delete(e)}_set(e){this.state={...this.state,...e};for(let t of[...this._listeners])try{t(this.snapshot())}catch{}}async load(){this._set({status:"loading",message:null});try{let e=await this.client.phoneNumbers.flow.get(this.phoneNumberId),t=Ce(e.flow);this._history=[],this._future=[],this._set({status:"ready",flow:t,saved:e.flow?t:null,enabled:e.enabled!==!1,localErrors:Oe(t),dirty:!1,serverCheck:null,simulation:null})}catch(e){this._set({status:"error",message:(e==null?void 0:e.message)||"Could not load this flow."})}}apply(e){let t=e(this.state.flow);!t||t===this.state.flow||(this._history.push(this.state.flow),this._history.length>100&&this._history.shift(),this._future=[],this._commit(t))}undo(){this._history.length&&(this._future.push(this.state.flow),this._commit(this._history.pop()))}redo(){this._future.length&&(this._history.push(this.state.flow),this._commit(this._future.pop()))}_commit(e){this._set({flow:e,localErrors:Oe(e),dirty:JSON.stringify(e)!==JSON.stringify(this.state.saved),serverCheck:null,message:null})}setEnabled(e){this._set({enabled:e,dirty:!0})}async check(){this._set({busy:!0});try{let e=await this.client.flows.validate(this.state.flow);return this._set({serverCheck:e,busy:!1}),e}catch(e){return this._set({busy:!1,message:(e==null?void 0:e.message)||"Could not check the flow."}),{valid:!1,error:e==null?void 0:e.message}}}async simulate(e={}){this._set({busy:!0,simulation:null});try{let t=await this.client.flows.simulate(this.state.flow,{...e,phoneNumber:this.phoneNumberId});return this._set({simulation:t,busy:!1}),t}catch(t){return this._set({busy:!1,message:(t==null?void 0:t.message)||"Could not run the simulation."}),null}}async generate(e){var t;if(!String(e!=null?e:"").trim())return!1;this._set({busy:!0,message:null});try{let s=await this.client.flows.generate(e,{currentFlow:this.state.flow,agents:this.lookup.agents.map(({id:r,name:i})=>({id:r,name:i}))}),a=(t=s.flow)!=null?t:s.draft;return a?(this._set({busy:!1}),this.apply(()=>Ce(a)),!0):(this._set({busy:!1,message:"No draft came back. Try describing it differently."}),!1)}catch(s){return this._set({busy:!1,message:(s==null?void 0:s.message)||"Could not draft a flow."}),!1}}async save(){var t;let e=Oe(this.state.flow);if(Object.keys(e).length)return this._set({localErrors:e,message:"Fix the highlighted fields first."}),!1;this._set({busy:!0,message:null});try{let s=await this.client.phoneNumbers.flow.save(this.phoneNumberId,this.state.flow,{enabled:this.state.enabled}),a=Ce((t=s==null?void 0:s.flow)!=null?t:this.state.flow);return this._history=[],this._future=[],this._set({busy:!1,flow:a,saved:a,dirty:!1,message:"Saved. New calls use this flow.",serverCheck:null}),!0}catch(s){return this._set({busy:!1,message:(s==null?void 0:s.message)||"Could not save the flow."}),!1}}};var En=`
203
+ .grid { display: grid; grid-template-columns: minmax(0, 3fr) minmax(0, 2fr); gap: 16px; } @media (max-width: 760px) { .grid { grid-template-columns: 1fr; } }
204
+ .route { border: 1px solid var(--_line); border-radius: calc(var(--_r) - 4px); padding: 8px 10px; margin: 8px 0; } .digit { font-weight: 700; font-size: 18px; width: 2ch; }
205
+ .toolbar { display: flex; gap: 8px; flex-wrap: wrap; margin-bottom: 10px; } .linkish { background: none; border: 0; color: var(--_accent); padding: 2px 4px; }
206
+ .map { list-style: none; margin: 0; padding: 0; } .map > li { border-left: 3px solid var(--_accent); padding: 4px 10px; margin: 0 0 8px 6px; background: color-mix(in srgb, var(--_accent) 5%, transparent); }
207
+ .map ul { margin: 4px 0 0; padding-left: 16px; } .days label { display: inline-block; margin: 0 8px 0 0; font-weight: 400; }
208
+ `,F=(n,e)=>n[e]?d`<p class="err" role="alert">${n[e]}</p>`:"",D=(n,e)=>k(n[e]?'aria-invalid="true"':""),at=(n,e,t)=>d`${t?d`<option value="">${t}</option>`:""}${n.map(s=>d`<option value="${s.id}" ${s.id===e?"selected":""}>${s.name}</option>`)}`;function On(n,e,t,s){var i;let a=`routes.${n}`,r=e.targetType==="agent"?d`<select aria-label="AI agent" data-key="${a}.agent" data-d="${n}" data-f="targetAgentId" ${D(t,`${a}.target`)}>${at(s.agents,e.targetAgentId,"Choose an agent")}</select>`:e.targetType==="team_member"?d`<select aria-label="Team member" data-key="${a}.member" data-d="${n}" data-f="teamMemberId" ${D(t,`${a}.target`)}>${at(s.team,e.teamMemberId,"Choose a person")}</select>`:e.targetType==="department"?d`<div role="group" aria-label="People in this department">${s.team.map(o=>{var l;return d`<label style="font-weight:400"><input type="checkbox" data-action="dept-toggle" data-d="${n}" data-id="${o.id}" ${((l=e.departmentTargets)!=null?l:[]).includes(o.id)?"checked":""} />${o.name}</label>`})}</div>`:d`<input aria-label="Phone number" type="tel" data-key="${a}.number" data-d="${n}" data-f="externalNumber" value="${(i=e.externalNumber)!=null?i:""}" placeholder="+18765550100" ${D(t,`${a}.target`)} />`;return d`<div class="route"><div class="row">
209
+ <div class="fixed digit" aria-label="Press ${n}">${n}</div>
210
+ <div><label for="l-${n}">Name</label><input id="l-${n}" data-key="${a}.label" data-d="${n}" data-f="label" value="${e.label}" placeholder="Sales" ${D(t,`${a}.label`)} />${F(t,`${a}.label`)}</div>
211
+ <div><label for="t-${n}">Who answers</label><select id="t-${n}" data-key="${a}.type" data-d="${n}" data-f="targetType">${et.map(o=>d`<option value="${o}" ${o===e.targetType?"selected":""}>${Mt[o]}</option>`)}</select></div>
212
+ <div class="fixed"><button type="button" class="linkish" data-action="route-remove" data-d="${n}" aria-label="Remove choice ${n}">Remove</button></div>
213
+ </div><div style="margin-top:6px">${r}${F(t,`${a}.target`)}</div></div>`}function An(n,e){let t=Ft(n,e);return d`<ol class="map" aria-label="How a call flows">${t.steps.map(s=>d`<li><b>${s.kind==="caller"?"\u260E":s.kind==="hours"?"\u{1F558}":s.kind==="greeting"?"\u{1F4AC}":"\u{1F522}"}</b> ${s.text}</li>`)}
214
+ <li>Caller presses a number<ul>${t.routes.length?t.routes.map(s=>d`<li><b>${s.digit}</b> ${s.label} → ${s.target}</li>`):d`<li>No choices yet</li>`}${t.fallback?d`<li>No answer → ${t.fallback}</li>`:""}</ul></li></ol>`}function zt(n,e={agents:[],team:[]},{prompt:t=""}={}){var o;if(n.status==="loading"||n.status==="idle")return d`<div class="card"><p class="hint" role="status">Loading…</p></div>`.toString();if(n.status==="error")return d`<div class="card"><p class="err" role="alert">${n.message}</p><button data-action="reload">Try again</button></div>`.toString();let s=n.flow,a=n.localErrors,r=s.hours,i=n.simulation;return d`<div class="card">
215
+ <div class="toolbar" role="toolbar" aria-label="Flow actions">
216
+ <button data-action="undo" ${n.canUndo?"":"disabled"}>Undo</button><button data-action="redo" ${n.canRedo?"":"disabled"}>Redo</button>
217
+ <button data-action="check" ${n.busy?"disabled":""}>Check with server</button><button data-action="simulate" ${n.busy?"disabled":""}>Try a call</button>
218
+ <button class="primary" data-action="save" ${!n.dirty||n.busy?"disabled":""}>${n.busy?"Working\u2026":"Save"}</button>
219
+ </div>
220
+ ${n.message?d`<p class="status ${n.message.startsWith("Saved")?"ok":"bad"}" role="status">${n.message}</p>`:""}
221
+ ${n.serverCheck?d`<p class="status ${n.serverCheck.valid?"ok":"bad"}" role="status">${n.serverCheck.valid?"The server accepts this flow.":`The server found a problem: ${(o=n.serverCheck.error)!=null?o:"invalid flow"}`}</p>`:""}
222
+ <div class="grid"><div>
223
+ <label for="draft">Describe it in words</label><div class="row"><input id="draft" data-key="draft" value="${t}" placeholder="Press 1 for sales, 2 for support; closed on Sundays" /><button class="fixed" data-action="generate" ${n.busy?"disabled":""}>Draft it</button></div>
224
+ <label for="greeting">Greeting</label><textarea id="greeting" rows="2" data-key="greeting" data-f="greeting" ${D(a,"greeting")}>${s.greeting}</textarea>${F(a,"greeting")}
225
+ <label for="prompt">Menu prompt</label><textarea id="prompt" rows="2" data-key="menu.prompt" data-f="menu.prompt" ${D(a,"menu.prompt")}>${s.menu.prompt}</textarea>${F(a,"menu.prompt")}
226
+ <div class="row"><div><label for="timeout">Wait for a key (seconds)</label><input id="timeout" type="number" min="1" max="30" data-key="menu.timeoutSec" data-f="menu.timeoutSec" value="${s.menu.timeoutSec}" ${D(a,"menu.timeoutSec")} />${F(a,"menu.timeoutSec")}</div>
227
+ <div><label for="fallback">If nobody answers</label><select id="fallback" data-key="menu.fallback" data-f="menu.fallbackAgentId">${at(e.agents,s.menu.fallbackAgentId,"Hang up")}</select></div></div>
228
+ <h3>Choices</h3>
229
+ ${Object.entries(s.menu.routes).sort(([l],[c])=>B.indexOf(l)-B.indexOf(c)).map(([l,c])=>On(l,c,a,e))}
230
+ <button data-action="route-add" ${B.every(l=>l in s.menu.routes)?"disabled":""}>Add a choice</button>
231
+ <h3>Opening hours</h3>
232
+ <label style="font-weight:400"><input type="checkbox" data-key="hours.enabled" data-f="hours.enabled" ${r.enabled?"checked":""} />Use opening hours</label>
233
+ ${r.enabled?d`<div class="row"><div><label for="open">Opens (hour)</label><input id="open" type="number" min="0" max="23" data-key="hours.openHour" data-f="hours.openHour" value="${r.openHour}" ${D(a,"hours.openHour")} />${F(a,"hours.openHour")}</div>
234
+ <div><label for="close">Closes (hour)</label><input id="close" type="number" min="1" max="24" data-key="hours.closeHour" data-f="hours.closeHour" value="${r.closeHour}" ${D(a,"hours.closeHour")} />${F(a,"hours.closeHour")}</div>
235
+ <div><label for="tz">Time zone</label><input id="tz" data-key="hours.timezone" data-f="hours.timezone" value="${r.timezone}" placeholder="America/Jamaica" /></div></div>
236
+ <div class="days" role="group" aria-label="Open days">${Lt.map(l=>d`<label><input type="checkbox" data-action="day-toggle" data-n="${l.n}" ${r.days.includes(l.n)?"checked":""} />${l.label}</label>`)}</div>${F(a,"hours.days")}
237
+ <label for="after">After hours</label><select id="after" data-key="hours.after" data-f="hours.afterHoursAction"><option value="voicemail" ${r.afterHoursAction==="voicemail"?"selected":""}>Take a voicemail</option><option value="agent" ${r.afterHoursAction==="agent"?"selected":""}>Let an AI agent answer</option></select>
238
+ ${r.afterHoursAction==="agent"?d`<select aria-label="After-hours agent" data-key="hours.afterAgent" data-f="hours.afterHoursAgentId" ${D(a,"hours.afterHoursAgentId")}>${at(e.agents,r.afterHoursAgentId,"Choose an agent")}</select>${F(a,"hours.afterHoursAgentId")}`:""}`:""}
239
+ <h3>Spam</h3>
240
+ <div class="row"><div><label for="rate">Calls per number, per 10 minutes</label><input id="rate" type="number" min="1" data-key="spam.rate" data-f="spam.rateLimitPer10Min" value="${s.spam.rateLimitPer10Min}" /></div></div>
241
+ <label style="font-weight:400"><input type="checkbox" data-key="spam.press1" data-f="spam.press1ScreenUnverified" ${s.spam.press1ScreenUnverified?"checked":""} />Ask unverified callers to press 1 first</label>
242
+ <label style="font-weight:400"><input type="checkbox" data-key="enabled" data-f="enabled" ${n.enabled?"checked":""} />This flow answers calls</label>
243
+ </div><div><h3>Call map</h3>${An(s,e)}
244
+ ${i?d`<h3>Test call</h3><pre style="white-space:pre-wrap;font-size:12.5px" aria-label="Simulation result">${JSON.stringify(i,null,2)}</pre>`:""}
245
+ </div></div></div>`.toString()}var Ae=class extends O{static get observedAttributes(){return["phone-number-id"]}get css(){return En}set client(e){this._client=e,this._init()}get client(){return this._client}set agents(e){this._agents=e!=null?e:[],this._rebuild()}set team(e){this._team=e!=null?e:[],this._rebuild()}mounted(){this._init()}unmounted(){var e;(e=this._unsub)==null||e.call(this),this.controller=null}attributeChangedCallback(e,t,s){var a;t!==s&&this.controller&&(this.controller=null,(a=this._unsub)==null||a.call(this),this._init())}_rebuild(){var e,t;this.controller&&(this.controller.lookup={agents:(e=this._agents)!=null?e:[],team:(t=this._team)!=null?t:[]},this.requestRender())}_init(){var t,s;let e=this.getAttribute("phone-number-id");this.controller||!this._connected||!this._client||!e||(this.controller=new de({client:this._client,phoneNumberId:e,agents:(t=this._agents)!=null?t:[],team:(s=this._team)!=null?s:[]}),this._unsub=this.controller.subscribe(()=>this.requestRender()),this.controller.load(),this.requestRender())}render(){var e;return this.controller?zt(this.controller.snapshot(),this.controller.lookup,{prompt:(e=this._prompt)!=null?e:""}):d`<div class="card"><p class="hint">Set the <code>client</code> property and a <code>phone-number-id</code> to edit a flow.</p></div>`.toString()}async onClick(e,t){let s=this.controller;if(!s)return;let a=t.dataset.d;if(e==="save"){let r=await s.save();this.emit(r?"traitos-saved":"traitos-error",{phoneNumberId:s.phoneNumberId,message:s.state.message})}else e==="undo"?s.undo():e==="redo"?s.redo():e==="reload"?s.load():e==="check"?s.check():e==="simulate"?s.simulate():e==="generate"?await s.generate(this._prompt)&&(this._prompt=""):e==="route-add"?s.apply(r=>Ht(r)):e==="route-remove"?s.apply(r=>Ut(r,a)):e==="day-toggle"?s.apply(r=>jt(r,Number(t.dataset.n))):e==="dept-toggle"&&s.apply(r=>{var l,c;let i=(c=(l=r.menu.routes[a])==null?void 0:l.departmentTargets)!=null?c:[],o=t.dataset.id;return nt(r,a,{departmentTargets:i.includes(o)?i.filter(g=>g!==o):[...i,o]})})}_edit(e){let t=this.controller,s=e.dataset.key,a=e.dataset.f;if(s==="draft"){this._prompt=e.value;return}if(!t||!a)return;let r=e.type==="checkbox"?e.checked:e.value;if(a==="enabled")return t.setEnabled(r);if(e.dataset.d)return t.apply(l=>nt(l,e.dataset.d,{[a]:r===""&&a.endsWith("Id")?null:r}));let i=l=>l===""?l:Number(l),o={greeting:()=>Dt(t.state.flow,r),"menu.prompt":()=>Ee(t.state.flow,{prompt:r}),"menu.timeoutSec":()=>Ee(t.state.flow,{timeoutSec:i(r)}),"menu.fallbackAgentId":()=>Ee(t.state.flow,{fallbackAgentId:r||null}),"spam.rateLimitPer10Min":()=>st(t.state.flow,{rateLimitPer10Min:i(r)}),"spam.press1ScreenUnverified":()=>st(t.state.flow,{press1ScreenUnverified:r}),"hours.enabled":()=>G(t.state.flow,{enabled:r}),"hours.openHour":()=>G(t.state.flow,{openHour:i(r)}),"hours.closeHour":()=>G(t.state.flow,{closeHour:i(r)}),"hours.timezone":()=>G(t.state.flow,{timezone:r}),"hours.afterHoursAction":()=>G(t.state.flow,{afterHoursAction:r}),"hours.afterHoursAgentId":()=>G(t.state.flow,{afterHoursAgentId:r||null})};o[a]&&t.apply(()=>o[a]())}onInput(e){e.type!=="checkbox"&&e.tagName!=="SELECT"&&this._edit(e)}onChange(e){(e.type==="checkbox"||e.tagName==="SELECT")&&this._edit(e)}};A("traitos-flow-builder",Ae);function hs(n,{remoteElement:e}={}){let t=null,s={ready:[],error:[],close:[],call:[]},a=(i,o)=>s[i].forEach(l=>l(o)),r=i=>({direction:i.direction,state:i.state,remoteCallerName:i.remoteCallerName,remoteCallerNumber:i.remoteCallerNumber,answer:()=>i.answer(),hangup:()=>i.hangup(),mute:o=>o?i.muteAudio():i.unmuteAudio(),hold:o=>o?i.hold():i.unhold(),dtmf:o=>i.dtmf(o)});return{on(i,o){var l;(l=s[i])==null||l.push(o)},async connect({token:i}){t=new n({login_token:i}),e&&(t.remoteElement=e),t.on("telnyx.ready",()=>a("ready")),t.on("telnyx.error",o=>a("error",o instanceof Error?o:new Error((o==null?void 0:o.message)||"Telnyx error"))),t.on("telnyx.socket.close",()=>a("close")),t.on("telnyx.notification",o=>{(o==null?void 0:o.type)==="callUpdate"&&o.call&&a("call",r(o.call))}),t.connect()},async disconnect(){t==null||t.disconnect(),t=null}}}var rt=class{constructor(e,t,{refreshAt:s=.8,minDelayMs:a=5e3,retryMs:r=5e3,onError:i,now:o=Date.now,timers:l}={}){this.client=e,this.provider=t,this.refreshAt=s,this.minDelayMs=a,this.retryMs=r,this.onError=i,this.now=o,this.timers=l!=null?l:{set:(c,g)=>setTimeout(c,g),clear:c=>clearTimeout(c)},this._timer=null,this._stopped=!1,this.expiresAt=null}async start(){this._stopped=!1,await this.refresh()}async refresh(){let e=await this.provider(),t=typeof e=="string"?e:e==null?void 0:e.token;if(!t)throw new Error("The token provider did not return a token.");this.client.setToken(t);let s=typeof e=="object"&&e?Number.isFinite(e.expiresIn)?e.expiresIn*1e3:e.expiresAt?Date.parse(e.expiresAt)-this.now():null:null;return this.expiresAt=s?this.now()+s:null,s&&!this._stopped&&this._schedule(Math.max(this.minDelayMs,s*this.refreshAt)),t}_schedule(e){this._timer&&this.timers.clear(this._timer),this._timer=this.timers.set(async()=>{var t;if(this._timer=null,!this._stopped)try{await this.refresh()}catch(s){(t=this.onError)==null||t.call(this,s),this._stopped||this._schedule(this.retryMs)}},e)}stop(){this._stopped=!0,this._timer&&this.timers.clear(this._timer),this._timer=null}};function Nn(){}var Xt={};Zt(Xt,{AuthenticationError:()=>ce,CallSession:()=>gt,ConflictError:()=>lt,ConnectionError:()=>pe,HybridAgent:()=>he,NotFoundError:()=>ot,PermissionError:()=>ue,RateLimitError:()=>ct,ServerError:()=>ut,SseParser:()=>Ne,TraitOSClient:()=>Yt,TraitOSError:()=>C,ValidationError:()=>dt,WebhookSignatureError:()=>L,constructWebhookEvent:()=>ft,errorClassFor:()=>pt,mapServerStatus:()=>Jt,normalizeBaseUrl:()=>it,paginate:()=>ht,safeCalculate:()=>Gt,signWebhook:()=>mt,verifyWebhook:()=>Pe});var Pn=new Set(["localhost","127.0.0.1","[::1]","::1"]);function it(n,{allowInsecureHttp:e=!1}={}){let t;try{t=new URL(String(n))}catch{throw new Error(`Invalid baseUrl: ${JSON.stringify(String(n).slice(0,80))}`)}if(t.username||t.password)throw new Error("baseUrl must not contain a user name or password. Pass the token separately.");let s=Pn.has(t.hostname)||t.hostname.endsWith(".localhost")||/^127\./.test(t.hostname);if(t.protocol==="http:"){if(!s&&!e)throw new Error(`Refusing to send credentials over plain http to ${t.host}. Use https, or pass allowInsecureHttp: true on a trusted network.`)}else if(t.protocol!=="https:")throw new Error(`baseUrl must start with https:// (got ${t.protocol})`);return`${t.origin}${t.pathname}`.replace(/\/+$/,"")}var C=class extends Error{constructor(e,{status:t,code:s=null,body:a,retryAfter:r=null,requestId:i=null}={}){super(e),this.name=new.target.name,this.status=t,this.code=s,this.body=a,this.retryAfter=r,this.requestId=i}},ce=class extends C{},ue=class extends C{},ot=class extends C{},lt=class extends C{},dt=class extends C{},ct=class extends C{},ut=class extends C{},pe=class extends C{},L=class extends C{};function pt(n){return n===401?ce:n===403?ue:n===404?ot:n===409?lt:n===400||n===422?dt:n===429?ct:n>=500?ut:C}var In=new Set([429,502,503,504]),fs=new Set(["GET","HEAD","PUT","DELETE","OPTIONS"]),qn=8e3,Rn=n=>new Promise(e=>setTimeout(e,n));function ms(n,e=Date.now()){if(n==null||n==="")return null;let t=Number(n);if(Number.isFinite(t))return Math.max(0,t);let s=Date.parse(n);return Number.isFinite(s)?Math.max(0,(s-e)/1e3):null}function gs(n,e=null,t=Math.random){if(e!==null)return Math.min(e*1e3,3e4);let s=Math.min(qn,500*2**n);return Math.round(s/2+t()*(s/2))}function bs(n){var r;let e=(r=n.sleep)!=null?r:Rn,t=i=>{let o=typeof FormData!="undefined"&&i.body instanceof FormData,l=n.getToken();return{...o?{}:{"Content-Type":"application/json"},...l?{Authorization:`Bearer ${l}`}:{},...n.headers,...i.headers}};async function s(i,o={}){var g,b;let l={Accept:"text/event-stream",...t({...o,body:void 0}),...o.headers};delete l["Content-Type"];let c;try{c=await fetch(`${n.baseUrl}${n.apiPath}${i}`,{...o,headers:l})}catch(f){throw(f==null?void 0:f.name)==="AbortError"?f:new pe((f==null?void 0:f.message)||"Network error",{code:"network_error"})}if(!c.ok){let f=await c.json().catch(()=>({error:"Request failed"})),v=pt(c.status);throw new v(f.message||f.error||`HTTP error! status: ${c.status}`,{status:c.status,code:typeof f.error=="string"&&/^[a-z][a-z0-9_]*$/.test(f.error)?f.error:null,body:f,retryAfter:ms((b=(g=c.headers)==null?void 0:g.get)==null?void 0:b.call(g,"retry-after"))})}return c}async function a(i,o={}){var y,h,m,$,w,x,T;let l=String((y=o.method)!=null?y:"GET").toUpperCase(),c=t(o),g=`${n.baseUrl}${n.apiPath}${i}`,{retries:b,...f}=o,v=b!=null?b:n.maxRetries;for(let I=0;;I++){let S;try{S=await fetch(g,{signal:AbortSignal.timeout(n.timeoutMs),...f,headers:c})}catch(Z){if(I<v&&fs.has(l)&&!((h=f.signal)!=null&&h.aborted)){await e(gs(I));continue}let Vt=(Z==null?void 0:Z.name)==="TimeoutError";throw new pe(Vt?`Request timed out after ${n.timeoutMs}ms`:(Z==null?void 0:Z.message)||"Network error",{code:Vt?"timeout":"network_error"})}if(S.ok)return S.status===204?null:S.json();let V=ms(($=(m=S.headers)==null?void 0:m.get)==null?void 0:$.call(m,"retry-after"));if(In.has(S.status)&&I<v&&(fs.has(l)||S.status===429)){await e(gs(I,V));continue}let E=await S.json().catch(()=>({error:"Request failed"})),Gs=pt(S.status);throw new Gs(E.message||E.error||`HTTP error! status: ${S.status}`,{status:S.status,code:typeof E.error=="string"&&/^[a-z][a-z0-9_]*$/.test(E.error)?E.error:null,body:E,retryAfter:V,requestId:(T=(x=(w=S.headers)==null?void 0:w.get)==null?void 0:x.call(w,"x-request-id"))!=null?T:null})}}return a.raw=s,a}function _(n={}){let e=new URLSearchParams;for(let[s,a]of Object.entries(n))a==null||a===""||e.set(s,Array.isArray(a)?a.join(","):String(a));let t=e.toString();return t?`?${t}`:""}var p=encodeURIComponent,u=(n,e)=>({method:n,body:JSON.stringify(e!=null?e:{})});function ys(n){let e=(s,a)=>n._request(s,a);return{login:async(s,a)=>{let r=await e("/auth/login",{method:"POST",body:JSON.stringify({email:s,password:a})});return r.token&&n.setToken(r.token),r},register:async({email:s,password:a,organizationName:r,organizationId:i})=>{let o=await e("/auth/register",{method:"POST",body:JSON.stringify({email:s,password:a,organizationName:r,organizationId:i})});return o.token&&n.setToken(o.token),o},createBrowserToken:({scopes:s,ttlSeconds:a})=>e("/auth/browser-tokens",u("POST",{scopes:s,...a?{ttlSeconds:a}:{}}))}}function _s(n){let e=(s,a)=>n._request(s,a);return{list:()=>e("/agents"),get:s=>e(`/agents/${p(s)}`),create:(s,a,r=null,i=[])=>e("/agents",{method:"POST",body:JSON.stringify({name:s,description:a,model:r,skills:i})}),configure:(s,{name:a,description:r,model:i,skills:o}={})=>e(`/agents/${p(s)}/configure`,{method:"POST",body:JSON.stringify({name:a,description:r,model:i,skills:o})}),delete:s=>e(`/agents/${p(s)}`,{method:"DELETE"}),chat:(s,a,r="default",i=null)=>e(`/agents/${p(s)}/chat`,{method:"POST",body:JSON.stringify({prompt:a,conversationId:r,skillName:i})}),updateSkills:(s,a=[])=>e(`/agents/${p(s)}/skills`,{method:"POST",body:JSON.stringify({skills:a})}),getModelSettings:s=>e(`/agents/${p(s)}/model-settings`),setModelSettings:(s,a)=>e(`/agents/${p(s)}/model-settings`,u("PUT",a)),handoffSettings:{get:s=>e(`/agents/${p(s)}/handoff-settings`),update:(s,a)=>e(`/agents/${p(s)}/handoff-settings`,u("PUT",a))},getMemory:s=>e(`/agents/${p(s)}/memory`),getTraces:s=>e(`/agents/${p(s)}/traces`),getGoals:s=>e(`/agents/${p(s)}/goals`),connect:(s,a={})=>{let r=a.WebSocketClass||(typeof WebSocket!="undefined"?WebSocket:null);if(!r)throw new Error('WebSocket is not defined in this environment. Please pass options.WebSocketClass (e.g., import ws from "ws").');let i=n.baseUrl.replace(/^http/,"ws")+`/agents/trait-agent/${p(s)}?token=${p(n.token||"")}`;return new r(i)}}}function vs(n){let e=(s,a)=>n._request(s,a);return{list:()=>e("/skills"),register:s=>e("/skills/register",{method:"POST",body:JSON.stringify(s)}),stats:()=>e("/skills/stats")}}function ws(n){let e=(s,a)=>n._request(s,a);return{run:(s,a={},r=null)=>e("/tasks",{method:"POST",body:JSON.stringify({task:s,payload:a,...r?{agentId:r}:{}})}),pending:()=>e("/tasks/pending")}}function $s(n){let e=(s,a)=>n._request(s,a);return{list:(s={})=>e(`/approvals${_(s)}`),count:()=>e("/approvals/count"),get:s=>e(`/approvals/${p(s)}`),approve:(s,a)=>e(`/approvals/${p(s)}/approve`,u("POST",a?{reason:a}:{})),deny:(s,a)=>e(`/approvals/${p(s)}/deny`,u("POST",a?{reason:a}:{})),settings:()=>e("/approvals/settings"),updateSettings:s=>e("/approvals/settings",u("PUT",s)),ruleTemplates:()=>e("/approvals/rule-templates"),rules:{list:s=>e(`/approvals/agents/${p(s)}/rules`),set:(s,a)=>e(`/approvals/agents/${p(s)}/rules`,u("PUT",{rules:a})),preview:(s,a)=>e(`/approvals/agents/${p(s)}/rules/preview`,u("POST",a))}}}function xs(n){let e=(s,a)=>n._request(s,a);return{summary:(s={})=>e(`/reports/summary${_(s)}`),traces:(s={})=>e(`/reports/traces${_(s)}`),trace:s=>e(`/reports/traces/${p(s)}`),feedback:(s,a)=>e(`/reports/traces/${p(s)}/feedback`,u("POST",{feedback:a})),replay:(s,a)=>e(`/reports/traces/${p(s)}/replay`,u("POST",a)),replays:(s={})=>e(`/reports/replays${_(s)}`),getReplay:s=>e(`/reports/replays/${p(s)}`),settings:()=>e("/reports/settings"),updateSettings:s=>e("/reports/settings",u("PUT",s))}}function ks(n){let e=(s,a)=>n._request(s,a);return{suites:(s={})=>e(`/evals/suites${_(s)}`),getSuite:s=>e(`/evals/suites/${p(s)}`),createSuite:s=>e("/evals/suites",u("POST",s)),updateSuite:(s,a)=>e(`/evals/suites/${p(s)}`,u("PUT",a)),deleteSuite:s=>e(`/evals/suites/${p(s)}`,{method:"DELETE"}),run:(s,a={})=>e(`/evals/suites/${p(s)}/run`,u("POST",a)),runs:(s,a={})=>e(`/evals/suites/${p(s)}/runs${_(a)}`),results:s=>e(`/evals/runs/${p(s)}`)}}function Ss(n){let e=(s,a)=>n._request(s,a);return{current:()=>e("/billing/usage"),history:()=>e("/billing/usage/history"),limits:()=>e("/billing/my-limits"),updateSettings:s=>e("/billing/usage/settings",u("PUT",s)),invoices:()=>e("/billing/invoices")}}function Ts(n){let e=(s,a)=>n._request(s,a),t={list:(s={})=>e(`/handoffs${_(s)}`),summary:()=>e("/handoffs/summary"),claim:s=>e(`/handoffs/${p(s)}/claim`,u("POST")),release:s=>e(`/handoffs/${p(s)}/release`,u("POST")),assign:(s,a)=>e(`/handoffs/${p(s)}/assign`,u("POST",{assigneeId:a})),resolve:s=>e(`/handoffs/${p(s)}/resolve`,u("POST")),settings:s=>e(`/telephony/handoff-settings/${p(s)}`),updateSettings:(s,a)=>e(`/telephony/handoff-settings/${p(s)}`,u("PUT",a)),getRouting:async s=>{var a;return(a=(await t.settings(s)).routing)!=null?a:null},setRouting:(s,a)=>t.updateSettings(s,{routing:a})};return t}function Cs(n){let e=(t,s="")=>`/calls/${p(t)}${s}`;return{list:({limit:t}={})=>n._request(`/calls${_({limit:t})}`),outboundSettings:{get:()=>n._request("/telephony/outbound-call-settings"),update:t=>n._request("/telephony/outbound-call-settings",u("PUT",t))},create:t=>n._request("/calls",u("POST",t)),get:t=>n._request(e(t)),hangup:t=>n._request(e(t,"/hangup"),u("POST")),handoff:(t,s={})=>n._request(e(t,"/handoff"),u("POST",s)),endHandoff:(t,{resumeAi:s=!0}={})=>n._request(e(t,"/handoff"),u("DELETE",{resumeAi:s})),muteAi:(t,s)=>n._request(e(t,"/ai-mute"),u("POST",{muted:s})),audioToken:t=>n._request(e(t,"/audio-token"),u("POST")),webrtc:(t,{sdp:s,type:a="offer"}={})=>n._request(e(t,"/webrtc"),u("POST",{sdp:s,type:a}))}}function Es(n){return{callPermissions:{get:(e,{agentId:t,from:s}={})=>n._request(`/whatsapp/call-permissions${_({to:e,agentId:t,from:s})}`),request:(e,{agentId:t,from:s,text:a}={})=>n._request("/whatsapp/call-permissions",u("POST",{to:e,agentId:t,from:s,text:a}))}}}function Os(n){return{list:()=>n._request("/telephony/numbers"),flow:{get:e=>n._request(`/phone-numbers/${p(e)}/flow`),save:(e,t,{enabled:s=!0}={})=>n._request(`/phone-numbers/${p(e)}/flow`,u("PUT",{flow:t,enabled:s}))}}}function As(n){return{token:()=>n._request("/softphone/token",u("POST")),register:e=>n._request("/softphone/registrations",u("POST",e)),unregister:e=>n._request("/softphone/registrations",u("DELETE",{sipUsername:e}))}}function Ns(n){return{get:e=>n.phoneNumbers.flow.get(e),save:(e,t,s)=>n.phoneNumbers.flow.save(e,t,s),validate:async e=>{var t;try{return await n._request("/flows/validate",u("POST",{flow:e}))}catch(s){if(s.status===400&&((t=s.body)==null?void 0:t.valid)===!1)return s.body;throw s}},generate:(e,t={})=>n._request("/flows/generate",u("POST",{prompt:e,...t})),simulate:(e,t={})=>n._request("/flows/simulate",u("POST",{flow:e,...t}))}}async function*ht(n,{start:e,maxItems:t=1/0}={}){var r;let s=e,a=0;for(;;){let i=await n(s);for(let o of(r=i.data)!=null?r:[]){if(a++>=t)return;yield o}if(!i.hasMore||i.nextCursor===null||i.nextCursor===void 0||i.nextCursor===s)return;s=i.nextCursor}}var Ne=class{constructor(){this.buf="",this.cur={data:[]},this.lastId=void 0}push(e){var a;this.buf+=e;let t=[],s;for(;(s=this.buf.search(/\r\n|\n|\r/))!==-1;){let r=this.buf.slice(0,s),i=this.buf.slice(s).startsWith(`\r
246
+ `)?2:1;if(this.buf[s]==="\r"&&s+1===this.buf.length)break;if(this.buf=this.buf.slice(s+i),r===""){(this.cur.data.length||this.cur.event)&&t.push({id:this.cur.id,event:(a=this.cur.event)!=null?a:"message",data:this.cur.data.join(`
247
+ `),retry:this.cur.retry}),this.cur={data:[]};continue}if(r.startsWith(":"))continue;let o=r.indexOf(":"),l=o===-1?r:r.slice(0,o),c=o===-1?"":r.slice(o+1);c.startsWith(" ")&&(c=c.slice(1)),l==="data"?this.cur.data.push(c):l==="event"?this.cur.event=c:l==="id"?(this.cur.id=c,this.lastId=c):l==="retry"&&/^\d+$/.test(c)&&(this.cur.retry=Number(c))}return t}},Kt=(n,e)=>new Promise(t=>{var r;if(e!=null&&e.aborted)return t();let s=setTimeout(a,n);function a(){var i;(i=e==null?void 0:e.removeEventListener)==null||i.call(e,"abort",a),clearTimeout(s),t()}(r=e==null?void 0:e.addEventListener)==null||r.call(e,"abort",a,{once:!0})});async function*Ps(n,{types:e=[],after:t,signal:s,reconnectDelayMs:a=250,maxRetryDelayMs:r=1e4}={}){let i=t,o=0,l=new TextDecoder;for(;!(s!=null&&s.aborted);){let c=new URLSearchParams;e.length&&c.set("types",e.join(",")),i!=null&&c.set("after",String(i));let g;try{g=await n(`/events/stream${c.size?`?${c}`:""}`,{signal:s,headers:i!=null?{"Last-Event-ID":String(i)}:{}})}catch(f){if(s!=null&&s.aborted||(f==null?void 0:f.name)==="AbortError")return;if(f instanceof ce||f instanceof ue||f instanceof C&&f.status&&f.status<500&&f.status!==429)throw f;o++,await Kt(Math.min(r,a*2**o),s);continue}o=0;let b=new Ne;try{let f=g.body.getReader();for(;;){let{done:v,value:y}=await f.read();if(v)break;let h=b.push(l.decode(y,{stream:!0}));!h.length&&b.lastId&&(i=Number(b.lastId));for(let m of h){if(!m.data)continue;let $;try{$=JSON.parse(m.data)}catch{continue}let w=m.id!==void 0&&m.id!==""?Number(m.id):void 0;w!==void 0&&(i=w),yield{seq:w,...$}}}}catch(f){if(s!=null&&s.aborted||(f==null?void 0:f.name)==="AbortError")return;o++,await Kt(Math.min(r,a*2**o),s);continue}await Kt(a,s)}}function Is(n){let e={list:(t={})=>n._request(`/events${_({after:t.after,types:t.types,limit:t.limit})}`),iterate:({maxItems:t,...s}={})=>{var a;return ht(r=>e.list({...s,after:r}),{start:(a=s.after)!=null?a:0,maxItems:t})},types:()=>n._request("/events/types"),stream:(t={})=>Ps(n._open,t),subscribe(t,{onError:s,...a}={}){let r=new AbortController,i=(async()=>{try{for await(let o of e.stream({...a,signal:r.signal}))t(o)}catch(o){if(s)s(o);else throw o}})();return{close:()=>r.abort(),done:i}}};return e}var Mn=300,qs=new TextEncoder,Ln=n=>Array.from(new Uint8Array(n),e=>e.toString(16).padStart(2,"0")).join("");function Dn(n,e){if(typeof n!="string"||typeof e!="string"||n.length!==e.length)return!1;let t=0;for(let s=0;s<n.length;s++)t|=n.charCodeAt(s)^e.charCodeAt(s);return t===0}async function Bt(n,e){let t=await crypto.subtle.importKey("raw",qs.encode(n),{name:"HMAC",hash:"SHA-256"},!1,["sign"]);return Ln(await crypto.subtle.sign("HMAC",t,qs.encode(e)))}function Rs(n,e){var s;if(!n)return;if(typeof n.get=="function")return(s=n.get(e))!=null?s:void 0;let t=e.toLowerCase();for(let[a,r]of Object.entries(n))if(a.toLowerCase()===t)return Array.isArray(r)?r[0]:r}async function Pe(n,e,t,{toleranceSeconds:s=Mn,now:a=Date.now()}={}){if(typeof n!="string")throw new L("Pass the raw request body as a string, not parsed JSON.",{code:"invalid_body"});if(!t)throw new L("No webhook secret was given.",{code:"missing_secret"});let r=Rs(e,"x-traitos-signature-v2"),i=Rs(e,"x-traitos-timestamp");if(!r||!i)throw new L("Missing X-TraitOS-Signature-V2 or X-TraitOS-Timestamp header.",{code:"missing_signature"});let o=Number(i);if(!Number.isFinite(o))throw new L("Invalid X-TraitOS-Timestamp.",{code:"invalid_timestamp"});if(s>0&&Math.abs(a/1e3-o)>s)throw new L("The webhook timestamp is outside the allowed window (possible replay).",{code:"timestamp_out_of_range"});let l=await Bt(t,`${i}.${n}`);if(!Dn(l,r.trim().toLowerCase()))throw new L("Signature does not match.",{code:"signature_mismatch"});return!0}async function ft(n,e,t,s){await Pe(n,e,t,s);try{return JSON.parse(n)}catch{throw new L("The body is not valid JSON.",{code:"invalid_body"})}}async function mt(n,e,{timestamp:t=Math.floor(Date.now()/1e3),eventId:s}={}){let a=String(t);return{"X-TraitOS-Signature":await Bt(e,n),"X-TraitOS-Timestamp":a,"X-TraitOS-Signature-V2":await Bt(e,`${a}.${n}`),...s?{"X-TraitOS-Event-Id":s}:{}}}function Ms(n){return{list:()=>n._request("/webhooks"),create:({url:e,events:t})=>n._request("/webhooks",u("POST",{url:e,events:t})),delete:e=>n._request(`/webhooks/${p(e)}`,{method:"DELETE"}),test:e=>n._request("/webhooks/test",u("POST",e)),verify:Pe,constructEvent:ft,sign:mt}}function Ls(n){return{scopes:()=>n._request("/apikeys/scopes"),list:()=>n._request("/apikeys"),create:e=>n._request("/apikeys",u("POST",e)),revoke:e=>n._request(`/apikeys/${p(e)}`,{method:"DELETE"})}}function Ds(n){return{list:(t={})=>n._request(`/contacts${_(t)}`),get:t=>n._request(`/contacts/${p(t)}`),create:t=>n._request("/contacts",u("POST",t)),update:(t,s)=>n._request(`/contacts/${p(t)}`,u("PUT",s)),delete:t=>n._request(`/contacts/${p(t)}`,{method:"DELETE"}),history:t=>n._request(`/contacts/${p(t)}/history`),block:(t,s)=>n._request(`/contacts/${p(t)}/block`,u("POST",s?{reason:s}:{})),lookup:({phone:t,email:s,externalId:a,system:r}={})=>n._request(`/contacts/lookup${_({phone:t,email:s,externalId:a,system:r})}`),resolve:t=>n._request("/contacts/resolve",u("POST",t)),linkExternalId:(t,s,a)=>n._request(`/contacts/${p(t)}/external-ids/${p(s)}`,u("PUT",{externalId:a})),unlinkExternalId:(t,s)=>n._request(`/contacts/${p(t)}/external-ids/${p(s)}`,{method:"DELETE"}),profile:t=>n._request(`/contacts/${p(t)}/profile`),mergeDuplicates:(t={})=>n._request("/contacts/merge-duplicates",u("POST",t)),companies:{list:(t={})=>n._request(`/contacts/companies${_(t)}`),create:t=>n._request("/contacts/companies",u("POST",t)),update:(t,s)=>n._request(`/contacts/companies/${p(t)}`,u("PUT",s)),delete:t=>n._request(`/contacts/companies/${p(t)}`,{method:"DELETE"})}}}function Hs(n){let e=t=>`/agents/${p(t)}/sms`;return{status:t=>n._request(`${e(t)}/status`),threads:t=>n._request(e(t)),thread:(t,s)=>n._request(`${e(t)}/${p(s)}`),send:(t,{to:s,body:a,contactName:r,from:i})=>n._request(`${e(t)}/send`,u("POST",{to:s,body:a,contact_name:r,from:i})),reply:(t,s,a)=>n._request(`${e(t)}/${p(s)}/reply`,u("POST",{body:a})),deleteThread:(t,s)=>n._request(`${e(t)}/${p(s)}`,{method:"DELETE"})}}function Us(n){let e=s=>`/knowledge/${p(s)}`,t=(s,a)=>`${e(s)}/sources/${p(a)}`;return{sources:s=>n._request(`${e(s)}/sources`),chunks:(s,a)=>n._request(`${t(s,a)}/chunks`),ingest:(s,a)=>n._request(`${e(s)}/ingest`,u("POST",a)),ingestUrl:(s,a)=>n._request(`${e(s)}/ingest/url`,u("POST",a)),ingestApi:(s,a)=>n._request(`${e(s)}/ingest/api`,u("POST",a)),ingestBucketPrefix:(s,a={})=>n._request(`${e(s)}/ingest/r2-prefix`,u("POST",a)),upload:(s,a)=>n._request(`${e(s)}/ingest/upload`,{method:"POST",body:a}),preview:(s,a)=>n._request(`${e(s)}/preview`,u("POST",a)),reingest:(s,a)=>n._request(`${t(s,a)}/reingest`,u("POST")),updateSource:(s,a,r)=>n._request(t(s,a),u("PATCH",r)),deleteSource:(s,a)=>n._request(t(s,a),{method:"DELETE"})}}function js(n){let e=(s,a)=>n._request(s,a);return{outbound:s=>e("/telephony/calls/whatsapp-outbound",u("POST",s)),webrtc:(s,{sdp:a,type:r="offer"}={})=>e("/telephony/calls/whatsapp-webrtc",u("POST",{id:s,sdp:a,type:r})),status:s=>e(`/telephony/calls/whatsapp-status${_({id:s})}`),audioToken:s=>e("/telephony/calls/whatsapp-audio-token",u("POST",{id:s})),handoff:(s,a={})=>e("/telephony/calls/whatsapp-bridge",u("POST",{id:s,...a})),endHandoff:(s,{resumeAi:a=!0}={})=>e("/telephony/calls/whatsapp-bridge/hangup",u("POST",{id:s,resumeAi:a})),muteAi:(s,a)=>e("/telephony/calls/whatsapp-bridge/ai-mute",u("POST",{id:s,muted:a})),hangup:s=>e("/telephony/calls/whatsapp-hangup",u("POST",{id:s})),permission:(s,{agentId:a,from:r}={})=>e(`/telephony/whatsapp/call-permission${_({to:s,agentId:a,from:r})}`),requestPermission:(s,{agentId:a,from:r,text:i}={})=>e("/telephony/whatsapp/call-permission/request",u("POST",{to:s,agentId:a,from:r,text:i}))}}function Fs(n){let e=(s,a)=>n._request(s,a);return{outbound:s=>e("/telephony/calls/pstn-outbound",u("POST",s))}}function zs(n){return{tenants:{list:e=>n._request(`/partner/orgs${_(e)}`),create:e=>n._request("/partner/orgs",u("POST",e)),get:e=>n._request(`/partner/orgs/${p(e)}`),update:(e,t)=>n._request(`/partner/orgs/${p(e)}`,u("PATCH",t)),createApiKey:(e,t={})=>n._request(`/partner/orgs/${p(e)}/api-keys`,u("POST",t))},usage:e=>n._request(`/partner/usage${_(e)}`),billing:e=>n._request(`/partner/billing${_(e)}`),syncSkills:e=>n._request("/partner/skills/sync",u("POST",e))}}function Ws(n){return{capabilities:()=>n._request("/larynx/capabilities"),getSettings:()=>n._request("/larynx/settings"),updateSettings:e=>n._request("/larynx/settings",u("PUT",e)),enroll:e=>n._request("/larynx/enroll",u("POST",e)),listProfiles:()=>n._request("/larynx/profiles"),getProfile:e=>n._request(`/larynx/profiles/${p(e)}`),updateProfile:(e,t)=>n._request(`/larynx/profiles/${p(e)}`,u("PATCH",t)),deleteProfile:e=>n._request(`/larynx/profiles/${p(e)}`,{method:"DELETE"}),verify:e=>n._request("/larynx/verify",u("POST",e)),identify:e=>n._request("/larynx/identify",u("POST",e)),challenge:(e={})=>n._request("/larynx/challenge",u("POST",e)),diarize:e=>n._request("/larynx/diarize",u("POST",e)),listVerifications:(e={})=>n._request(`/larynx/verifications${_(e)}`),forCall:e=>n._request(`/larynx/calls/${p(e)}`)}}function Gt(n){let e=String(n!=null?n:"");if(e.length>200)throw new Error("Expression is too long");let t=[],s=/\s*(?:(\d+\.?\d*|\.\d+)|(\*\*|[-+*/()]))/y,a=0;for(;a<e.trimEnd().length;){s.lastIndex=a;let h=s.exec(e);if(!h)throw new Error("Invalid expression");t.push(h[1]!==void 0?{n:Number(h[1])}:{op:h[2]}),a=s.lastIndex}if(!t.length)throw new Error("Invalid expression");let r=0,i=()=>t[r],o=()=>t[r++],l=(h,...m)=>h&&h.op!==void 0&&m.includes(h.op),c=h=>{if(h>50)throw new Error("Expression is too deeply nested");let m=g(h);for(;l(i(),"+","-");)m=o().op==="+"?m+g(h):m-g(h);return m},g=h=>{let m=b(h);for(;l(i(),"*","/");)m=o().op==="*"?m*b(h):m/b(h);return m},b=h=>{let m=f(h);return l(i(),"**")?(o(),m**b(h)):m},f=h=>l(i(),"+","-")?o().op==="-"?-f(h+1):f(h+1):v(h),v=h=>{let m=o();if(m&&m.n!==void 0)return m.n;if(l(m,"(")){let $=c(h+1);if(!l(o(),")"))throw new Error("Invalid expression");return $}throw new Error("Invalid expression")},y=c(0);if(r!==t.length)throw new Error("Invalid expression");if(!Number.isFinite(y))throw new Error("Result is not a finite number");return y}var he=class{constructor(e,t,{localTools:s={},localMemory:a={}}={}){this.client=e,this.agentId=t,this.localTools={calculate:r=>({result:Gt(r==null?void 0:r.expression)}),...s},this.localMemory={preferences:[],...a}}setLocalMemory(e,t){this.localMemory[e]||(this.localMemory[e]=[]),this.localMemory[e].push({text:t,timestamp:Date.now()})}async chat(e,t="default",s=null){let a=e.toLowerCase(),r=a.match(/(?:calculate|math|compute)\s+(.+)/);if(r&&this.localTools.calculate)try{return{response:`[Local Hybrid Engine] I resolved this using your local hardware. Result: ${this.localTools.calculate({expression:r[1]}).result}`,source:"local_execution",toolUsed:"calculate"}}catch{}if(a.includes("local preference")||a.includes("what do you remember about me")){let o=this.localMemory.preferences.map(l=>l.text).join(", ");if(o)return{response:`[Local Hybrid Engine] Reading from local memory: I remember that ${o}.`,source:"local_memory"}}let i=await this.client.agents.chat(this.agentId,e,t,s);return i.response&&(i.response.includes("prefer")||i.response.includes("always"))&&this.setLocalMemory("preferences",i.response),{...i,source:"edge_delegation"}}};var Ks={idle:0,connecting:1,ringing:2,active:3,ended:4},Hn=new Set(["connected","active","accepted","connect","answer","answered","in-call"]),Un=new Set(["completed","stopped","ended","terminated","hangup","rejected","missed","canceled","cancelled"]);function Jt(n,e=null){let t=String(n!=null?n:"").toLowerCase();return t?e==="call_permission_required"?{state:"ended",reason:"call_permission_required"}:t==="ringing"||t==="in-progress"||t==="dialing"?{state:"ringing"}:Hn.has(t)?{state:"active"}:t==="failed"?{state:"ended",reason:"failed"}:t==="no_answer"||t==="no-answer"?{state:"ended",reason:"no_answer"}:Un.has(t)?{state:"ended",reason:t==="completed"||t==="stopped"?"completed":t}:null:null}var gt=class{constructor(e,{rtc:t=null,pollMs:s=2e3,ringTimeoutSecs:a=45,iceWaitMs:r=2e3}={}){this.client=e,this.rtc=t,this.pollMs=s,this.ringTimeoutSecs=a,this.iceWaitMs=r,this.state="idle",this.id=null,this.endReason=null,this.mode="direct",this.muted=!1,this.startedAt=null,this._listeners=new Set,this._cancelled=!1,this._pc=null,this._stream=null,this._poll=null,this._ringTimer=null}on(e,t){if(e!=="state")throw new Error(`Unknown event: ${e}`);return this._listeners.add(t),()=>this._listeners.delete(t)}snapshot(){return{state:this.state,id:this.id,mode:this.mode,muted:this.muted,endReason:this.endReason,startedAt:this.startedAt}}_emit(){for(let e of[...this._listeners])try{e(this.snapshot())}catch{}}_transition(e,t=null){var s;return Ks[e]<=Ks[this.state]?!1:(this.state=e,e==="active"&&(this.startedAt=(s=this.startedAt)!=null?s:Date.now(),this._clearRingTimer()),e==="ended"&&(this.endReason=t||"completed",this._cleanup()),this._emit(),!0)}applyServerEvent(e={}){var s,a,r,i;if(e.callId&&this.id&&e.callId!==this.id)return!1;let t=Jt((a=(s=e.status)!=null?s:e.callState)!=null?a:e.state,(i=(r=e.failureCode)!=null?r:e.failure_code)!=null?i:null);return t?this._transition(t.state,t.reason):!1}async dial({mode:e="direct",...t}={}){var s,a,r,i,o;if(this.state!=="idle")throw new Error("This session already placed a call; create a new CallSession.");if(e!=="direct"&&e!=="agent-first")throw new Error("mode must be 'direct' or 'agent-first'");this.mode=e,this._transition("connecting");try{let l=this.rtc&&e==="direct"?await this._offer():void 0,c=await this.client.calls.create({...t,channel:"whatsapp",softphoneFirst:e==="agent-first",...l?{sdp:l,sdpType:"offer"}:{}}),g=(i=(r=(s=c==null?void 0:c.id)!=null?s:c==null?void 0:c.call_id)!=null?r:(a=c==null?void 0:c.data)==null?void 0:a.id)!=null?i:null;if(this.id=g,this._cancelled||this.state==="ended")return g&&await this.client.calls.hangup(g).catch(()=>{}),this.snapshot();let b=(o=c==null?void 0:c.session)==null?void 0:o.sdp;return b&&this._pc&&await this._pc.setRemoteDescription({type:c.session.type||"answer",sdp:b}),this._transition("ringing"),this._startPolling(),this._startRingTimer(),this.snapshot()}catch(l){throw this._transition("ended","failed"),l}}async hangup(e="hangup"){this._cancelled=!0;let t=this.id;this._transition("ended",e),t&&await this.client.calls.hangup(t).catch(()=>{})}mute(e=!0){var t,s,a;this.muted=!!e;for(let r of(a=(s=(t=this._stream)==null?void 0:t.getAudioTracks)==null?void 0:s.call(t))!=null?a:[])r.enabled=!this.muted;this._emit()}async _offer(){var i;let{RTCPeerConnection:e,getUserMedia:t,onRemoteStream:s,iceServers:a}=this.rtc;this._stream=await t();let r=new e(a?{iceServers:a}:void 0);this._pc=r;for(let o of this._stream.getTracks())r.addTrack(o,this._stream);return s&&(r.ontrack=o=>{var l;return s((l=o.streams)==null?void 0:l[0])}),await r.setLocalDescription(await r.createOffer()),await new Promise(o=>{var b;if(r.iceGatheringState==="complete")return o();let l=()=>{var f;clearTimeout(g),(f=r.removeEventListener)==null||f.call(r,"icegatheringstatechange",c),o()},c=()=>{r.iceGatheringState==="complete"&&l()},g=setTimeout(l,this.iceWaitMs);(b=r.addEventListener)==null||b.call(r,"icegatheringstatechange",c)}),(i=r.localDescription)==null?void 0:i.sdp}_startPolling(){!this.id||this._poll||this.pollMs<=0||(this._poll=setInterval(async()=>{if(this.state==="ended")return;let e=await this.client.calls.get(this.id).catch(()=>null);e&&this.applyServerEvent(e)},this.pollMs))}_startRingTimer(){this.ringTimeoutSecs<=0||this.state!=="ringing"||(this._ringTimer=setTimeout(()=>{this.state==="ringing"&&this.hangup("no_answer")},this.ringTimeoutSecs*1e3))}_clearRingTimer(){this._ringTimer&&(clearTimeout(this._ringTimer),this._ringTimer=null)}_cleanup(){var e,t,s,a;this._clearRingTimer(),this._poll&&(clearInterval(this._poll),this._poll=null);try{(e=this._pc)==null||e.close()}catch{}for(let r of(a=(s=(t=this._stream)==null?void 0:t.getTracks)==null?void 0:s.call(t))!=null?a:[])try{r.stop()}catch{}this._pc=null,this._stream=null}};var jn=3e4,Fn=2,Yt=class n{constructor({baseUrl:e="http://localhost:8788",token:t,timeoutMs:s=jn,maxRetries:a=Fn,allowInsecureHttp:r=!1,apiVersion:i="v1",orgId:o,sleep:l}={}){this.baseUrl=it(e,{allowInsecureHttp:r}),this.timeoutMs=s,this.maxRetries=a,this.apiVersion=i,this.orgId=o!=null?o:null,Object.defineProperty(this,"_config",{value:{baseUrl:this.baseUrl,timeoutMs:s,maxRetries:a,allowInsecureHttp:r,apiVersion:i,sleep:l},enumerable:!1}),Object.defineProperty(this,"token",{value:t,writable:!0,enumerable:!1,configurable:!0});let c=bs({baseUrl:this.baseUrl,apiPath:i?`/api/${i}`:"/api",getToken:()=>this.token,timeoutMs:s,maxRetries:a,headers:o?{"X-TraitOS-Org-Id":String(o)}:void 0,sleep:l});Object.defineProperty(this,"_request",{value:c,enumerable:!1}),Object.defineProperty(this,"_open",{value:c.raw,enumerable:!1}),this.auth=ys(this),this.agents=_s(this),this.skills=vs(this),this.tasks=ws(this),this.approvals=$s(this),this.reports=xs(this),this.evals=ks(this),this.usage=Ss(this),this.handoffs=Ts(this),this.calls=Cs(this),this.whatsapp=Es(this),this.phoneNumbers=Os(this),this.softphone=As(this),this.flows=Ns(this),this.sms=Hs(this),this.knowledge=Us(this),this.contacts=Ds(this),this.larynx=Ws(this),this.events=Is(this),this.webhooks=Ms(this),this.apiKeys=Ls(this),this.partners=zs(this),this.whatsappCalls=js(this),this.phoneCalls=Fs(this)}setToken(e){this.token=e}asOrg(e){if(!e||typeof e!="string")throw new TypeError("asOrg(orgId) needs a child organization id");return new n({...this._config,token:this.token,orgId:e})}createHybridAgent(e,t={}){return new he(this,e,t)}};var Bs;typeof window!="undefined"&&(window.TraitOSUI=Wt,window.TraitOS={...(Bs=window.TraitOS)!=null?Bs:{},...Xt});})();
package/package.json CHANGED
@@ -1,6 +1,34 @@
1
1
  {
2
2
  "name": "@cognitiv-traits/traitos-ui",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
4
+ "description": "Drop-in TraitOS UI: a browser softphone, a dialer widget with keypad, settings forms and a visual call-flow builder, as framework-free web components.",
5
+ "keywords": ["traitos", "web-components", "softphone", "dialer", "keypad", "ai-agents", "call-flow"],
6
+ "homepage": "https://os.cognitivtraits.us",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/cognitivtraits/trait-os.git",
10
+ "directory": "ui"
11
+ },
12
+ "license": "Apache-2.0",
13
+ "author": "Cognitiv Traits <hello@cognitivtraits.us>",
14
+ "type": "module",
15
+ "main": "src/index.js",
16
+ "files": ["src", "dist", "README.md", "CHANGELOG.md", "!src/**/*.test.js"],
17
+ "engines": { "node": ">=18" },
18
+ "publishConfig": { "access": "public" },
19
+ "exports": {
20
+ ".": { "import": "./src/index.js", "default": "./src/index.js" },
21
+ "./browser": "./dist/traitos-ui.global.min.js",
22
+ "./package.json": "./package.json"
23
+ },
24
+ "scripts": {
25
+ "build": "node scripts/build.mjs",
26
+ "prepublishOnly": "npm run build"
27
+ },
28
+ "peerDependencies": {
29
+ "@cognitiv-traits/traitos-sdk": "^0.7.0"
30
+ },
31
+ "devDependencies": {
32
+ "esbuild": "^0.28.0"
33
+ }
34
+ }