@telia-ace/ace-chat-flamingo 1.1.123-rc.14 → 1.1.123-rc.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/index.js +2 -2
  2. package/index.mjs +14 -7
  3. package/package.json +3 -3
package/index.js CHANGED
@@ -1352,7 +1352,7 @@ Please report this to https://github.com/markedjs/marked.`,n){const i="<p>An err
1352
1352
  width: 100%;
1353
1353
  }
1354
1354
  }
1355
- `];let ne=Fs;pe([T()],ne.prototype,"platform");pe([T()],ne.prototype,"entries");pe([T()],ne.prototype,"typing");pe([T()],ne.prototype,"message");pe([T()],ne.prototype,"disabledInput");pe([T()],ne.prototype,"disabledSkipToLatest");pe([T()],ne.prototype,"disabledSubmit");pe([T()],ne.prototype,"chatOverlayActive");pe([T()],ne.prototype,"textAreaLength");pe([T()],ne.prototype,"showAuthBanner");pe([T()],ne.prototype,"authenticated");var Te=(n=>(n.Tunnistus="tunnistus",n.BankId="bankid",n.Freja="freja",n))(Te||{}),H=(n=>(n.Pending="pending",n.Authenticated="authenticated",n.Error="error",n))(H||{});class Bt{constructor(e){this.orderRef="",e={...e,idHubEidType:typeof(e==null?void 0:e.idHubEidType)=="string"?e.idHubEidType.toLowerCase():e.idHubEidType},this.config=e,this.url=`${e==null?void 0:e.idHubUrl}/${e==null?void 0:e.idHubCustomerKey}/${e==null?void 0:e.idHubOrgKey}/${e==null?void 0:e.idHubEidType}`,this.maxRetries=e.idHubMaxRetries??300}async auth(){try{const e=await fetch(`${this.url}/auth`,{headers:Bt.getHeaders(),body:JSON.stringify({clientName:"idhub-web-1.0.0",register:{clientType:"ACEWIDGET",agentId:"ACEWIDGET",userName:"ACEWIDGET"}}),method:"POST"});if(!e.ok)return{status:H.Error,errorMessage:`Auth failed with response: ${e.status} ${e.statusText}`};const t=await e.json();switch(this.orderRef=t.orderRef,this.config.idHubEidType){case Te.Tunnistus:return{tunnistusURL:t.tunnistusURL,status:H.Pending};case Te.BankId:return{autoStartToken:t.autoStartToken,status:H.Pending};case Te.Freja:throw new Error(`${Te.Freja} is not implemented`);default:throw new Error(`The service ${this.config.idHubEidType} is not implemented`)}}catch(e){return{status:H.Error,errorMessage:`Auth failed. Error: ${e}`}}}async collect(){for(let e=0;e<this.maxRetries;e++){await new Promise(i=>setTimeout(i,1e3));const t=await this.collectOnce();if(t&&t.status!==H.Pending)return t}return{status:H.Error}}async cancel(){try{return this.orderRef?(await fetch(`${this.url}/cancel`,{headers:Bt.getHeaders(),body:JSON.stringify({clientName:"idhub-web-1.0.0",orderRef:this.orderRef,method:"auth"}),method:"POST"}),{}):{status:H.Error,errorMessage:"Missing order reference."}}catch(e){return{status:H.Error,errorMessage:`Cancel failed. Error: ${e}`}}}static getHeaders(){return{accept:"application/json","accept-language":"sv-SE,sv;q=0.9,en-US;q=0.8,en;q=0.7","content-type":"application/json"}}async collectOnce(){try{if(!this.orderRef)return{status:H.Error,errorMessage:"Missing order reference."};const e=await fetch(`${this.url}/collect`,{headers:Bt.getHeaders(),body:JSON.stringify({clientName:"idhub-web-1.0.0",orderRef:this.orderRef,method:"auth"}),method:"POST"});if(!e.ok)return{status:H.Error,errorMessage:`Collect failed with response: ${e.status} ${e.statusText}`};const t=await e.json();return t.status===H.Error?{status:H.Error,subStatus:t.subStatus??void 0}:t}catch(e){return{status:H.Error,errorMessage:`Collect failed. Error: ${e}`}}}}const Se=n=>n.objectType==="info",Id=n=>n.objectType==="chatEntry",Pd=n=>n.objectType==="pen",Md=n=>n.objectType==="chatButtonClicked",Nd=n=>n.objectType==="endVideoButtonClicked",Ud=n=>n.type==="queue-status",Dd=n=>n.type==="established",zd=n=>n.type==="pen-status",Hd=n=>n.type==="prepareVideo",jd=n=>n.type==="videoPrepared",Fd=n=>n.type==="chatButtonClicked",Bd=n=>n.type==="endVideoButtonClicked",qd=n=>n.type==="chat-ended";var Ze=(n=>(n.Initial="initial",n.Error="error",n.Retry="retry",n))(Ze||{});class Fn extends Error{constructor(e){super(e),this.name="EngineException"}}class Es{constructor(e,t){this.endpoint=e,this.timeout=t,this.protocolVersion="A",this.penStatusJustSent=!1}async chatJoin(e){var i,s,r;const t=await this.sendRequest("chatJoin",{invitationUid:e.invitationUid,uid:e.uid,instance:e.instance,protocolVersion:this.protocolVersion,videoChatMode:e.videoChatMode,customerName:e.customerName});if(!((i=t==null?void 0:t.dataObjects)!=null&&i.length)||((s=t==null?void 0:t.dataObjects[0])==null?void 0:s.infoType)==="error")throw t.dataObjects?new Error(`chatRequest - ${(r=t==null?void 0:t.dataObjects[0])==null?void 0:r.text}`):new Error("chatRequest - unknown error")}async chatRequest(e){var i,s,r,o,a;const t=await this.sendRequest("chatRequest",{...e.customData,uid:e.uid,instance:e.instance,queueMessageInterval:e.queueMessageInterval.toString(),protocolVersion:this.protocolVersion,entrance:e.entrance,errand:e.errand.length?e.errand:"997",videoChatMode:e.videoChatMode,customerName:e.customerName,customerEmailAddress:e.customerEmailAddress,visitorQuestion:e.visitorQuestion,visitorUserAgent:((i=window==null?void 0:window.navigator)==null?void 0:i.userAgent)||"",sourceUrl:((s=window==null?void 0:window.location)==null?void 0:s.href)||"",...e.authToken&&{authToken:e.authToken}});if(!((r=t==null?void 0:t.dataObjects)!=null&&r.length)||((o=t==null?void 0:t.dataObjects[0])==null?void 0:o.infoType)==="error")throw t.dataObjects?new Error(`chatRequest - ${(a=t==null?void 0:t.dataObjects[0])==null?void 0:a.text}`):new Error("chatRequest - unknown error")}async videoPrepared(e){await this.sendRequest("videoPrepared",{uid:e.uid,instance:e.instance,result:e.result,protocolVersion:this.protocolVersion})}chatRead(e){return this.sendRequest("chatRead",{uid:e.uid,instance:e.instance,entrance:e.entrance,maxObjectId:`${e.maxObjectId}`,protocolVersion:this.protocolVersion})}sendPenStatusOn(e){if(this.penStatusTimer&&clearTimeout(this.penStatusTimer),e.key==="Enter"){this.penStatusJustSent=!1;return}this.penStatusJustSent||(this.sendRequest("chatPenStatus",{uid:e.uid,instance:e.instance,penStatus:"on",protocolVersion:this.protocolVersion}),this.penStatusJustSent=!0,setTimeout(()=>{this.penStatusJustSent=!1},5e3)),this.penStatusTimer=setTimeout(()=>this.sendPenStatusOff(e),5e3)}sendPenStatusOff(e){this.penStatusJustSent&&clearTimeout(this.penStatusTimer),this.sendRequest("chatPenStatus",{uid:e.uid,instance:e.instance,penStatus:"off",protocolVersion:this.protocolVersion})}chatWrite(e){return this.sendPenStatusOff(e),this.sendRequest("chatWrite",{uid:e.uid,instance:e.instance,clockstamp:e.clockstamp,message:e.message,protocolVersion:this.protocolVersion})}async chatQuit(e){this.sendPenStatusOff(e),await this.sendRequest("chatQuit",{uid:e.uid,instance:e.instance,protocolVersion:this.protocolVersion})}async chatCheckSession(e){var i;const t=await this.sendRequest("chatCheckSession",{uid:e.uid,instance:e.instance,protocolVersion:this.protocolVersion});return Object.keys(t).length===0?null:((i=t.dataObjects)==null||i.sort((s,r)=>s.objectId-r.objectId),t)}async chatEmailSession(e){return this.sendRequest("chatEmailSession",{uid:e.uid,instance:e.instance,emailAddress:e.emailAddress,protocolVersion:this.protocolVersion})}async sendRequest(e,t){const i=this.endpoint.includes("engine-simulator")?"include":void 0,s=`${Es.removeTrailingSlashes(this.endpoint)}/${e}`,r=await fetch(s,{body:new URLSearchParams(t),method:"POST",credentials:i,headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"*/*"},signal:this.timeout?AbortSignal.timeout(this.timeout):void 0});return Number(r.headers.get("content-length"))>0?r.json():{}}static removeTrailingSlashes(e){return e.replace(/\/+$/,"")}}const Vd=()=>"10000000-1000-4000-8000-100000000000".replace(/[018]/g,n=>(+n^crypto.getRandomValues(new Uint8Array(1))[0]&15>>+n/4).toString(16)),Ki=()=>typeof crypto.randomUUID=="function"?crypto.randomUUID():Vd();function Ji(n){return/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(n)}function Ya(n){return n.replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}function Wd(n){return decodeURIComponent(atob(n).split("").map(e=>"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2)).join(""))}class Gd{constructor(e,t){this.config=e,this.messageSubject$=new P,this.actionsSubject$=new P,this.messages=()=>this.messageSubject$.asObservable(),this.actions=()=>this.actionsSubject$.asObservable(),this.sessionId="",this.lastObjectId=0,this.sessionId=t??Ki(),this.client=new Es(this.config.engineUrl,this.config.engineTimeout)}chatJoin(e){return Ye(this.client.chatJoin({invitationUid:e.invitationUid,uid:this.sessionId,customerName:e.customerName,instance:this.config.instance,videoChatMode:this.config.videoChatMode})).pipe(Pi(t=>(console.error(t),this.messageSubject$.next({text:this.config.errorMessage??"An error occured",source:"system"}),new j)),Oe(()=>this.poll().pipe(mi(()=>this.poll()),vi())))}chatRequest(e){return Ye(this.client.chatRequest({uid:this.sessionId,customerName:e.customerName,customerEmailAddress:e.customerEmailAddress,visitorQuestion:e.visitorQuestion,instance:this.config.instance,queueMessageInterval:this.config.queueMessageInterval,entrance:this.config.entrance,errand:e.errand,videoChatMode:this.config.videoChatMode,customData:e.customData,...e.authToken&&{authToken:e.authToken}})).pipe(Pi(t=>(console.error(t),this.messageSubject$.next({text:this.config.errorMessage??"An error occured",source:"system"}),new j)),Oe(()=>this.poll().pipe(mi(()=>this.poll()),vi())))}reconnect(){return this.poll().pipe(mi(()=>this.poll()),vi())}poll(){return ac(()=>Ye(this.client.chatRead({uid:this.sessionId,instance:this.config.instance,entrance:this.config.entrance,maxObjectId:this.lastObjectId})).pipe(gc(e=>{this.processMessages(e)})))}async chatWrite(e){const t=await this.client.chatWrite({uid:this.sessionId,instance:this.config.instance,clockstamp:Date.now().toString(),message:e}),i=((t==null?void 0:t.dataObjects)||[]).find(s=>Se(s)&&s.infoType==="error");if(i)throw new Fn(i.text||"Unable to send message")}sendPenStatusOn(e){this.client.sendPenStatusOn({uid:this.sessionId,instance:this.config.instance,key:e})}async videoPrepared(e){await this.client.videoPrepared({uid:this.sessionId,instance:this.config.instance,result:e})}async chatQuit(){await this.client.chatQuit({uid:this.sessionId,instance:this.config.instance})}async chatEmailSession(e){const t=await this.client.chatEmailSession({uid:this.sessionId,instance:this.config.instance,emailAddress:e});if(((t==null?void 0:t.dataObjects)||[]).find(s=>Se(s)&&s.infoType==="error"))throw new Fn("Unable to send email with conversation")}processMessages(e){e.dataObjects.forEach(t=>{Id(t)&&t.source&&t.objectId>=this.lastObjectId&&this.messageSubject$.next({text:t.message,source:t.source,invitationNo:t.invitationNo.toString(),alias:t.alias||t.agentAlias}),Pd(t)&&this.actionsSubject$.next({penStatus:t.penStatus,type:"pen-status"}),Se(t)&&t.infoType==="queue"&&this.actionsSubject$.next({text:t.text,type:"queue-status"}),Se(t)&&t.infoType==="established"&&this.actionsSubject$.next({text:t.text,agentAlias:t.agentAlias,type:"established",videoEnded:t.videoEnded,contactId:t.contactId,agentUsername:t.agentUsername,entrance:t.entrance,errand:t.errand}),Se(t)&&t.infoType==="prepareVideo"&&this.actionsSubject$.next({type:"prepareVideo"}),Se(t)&&t.infoType==="videoPrepared"&&this.actionsSubject$.next({text:t.text,agent:t.agent,type:"videoPrepared",userUrl:t.userUrl}),Md(t)&&this.actionsSubject$.next({guestId:t.guestId,type:"chatButtonClicked"}),Nd(t)&&this.actionsSubject$.next({guestId:t.guestId,type:"endVideoButtonClicked"}),Se(t)&&["afterChat","finished"].includes(t.infoType)&&this.actionsSubject$.next({text:t.text,type:"chat-ended",showForm:t.infoType==="afterChat",contactId:t.contactId})}),this.lastObjectId=e.maxObjectId}async getChatStatus(){const e=await this.client.chatCheckSession({uid:this.sessionId,instance:this.config.instance});if(!e)return"noSession";const t=e.dataObjects;for(const i of t)if(Se(i))switch(i.infoType){case"finished":case"afterChat":return"finished";case"noSession":return"noSession"}return"active"}async rehydrate(){const e=await this.client.chatCheckSession({uid:this.sessionId,instance:this.config.instance});return!e||(e.dataObjects||[]).find(t=>Se(t)&&t.infoType==="noSession")?null:(this.processMessages(e),e)}}class Ne{constructor(e){this._email="",this._host=e,e.addController(this)}static getInstance(e){return Ne.instance?Ne.instance.updateHost(e):Ne.instance=new Ne(e),Ne.instance}updateHost(e){this._host=e,e.addController(this)}hostConnected(){}set email(e){this._email=e,this._host.requestUpdate()}get email(){return this._email}clearData(){this._email="",this._host.requestUpdate()}}var Zd=Object.defineProperty,Et=(n,e,t,i)=>{for(var s=void 0,r=n.length-1,o;r>=0;r--)(o=n[r])&&(s=o(e,t,s)||s);return s&&Zd(e,t,s),s},bt;let it=(bt=class extends A{constructor(){super(),this.submitted=!1,this.customData=[],this.customerName="",this.validationErrors=[],this.showValidationWarning=!1,this.emailController=Ne.getInstance(this),this.emailController.clearData()}connectedCallback(){var i,s;super.connectedCallback();const e=this.application.settings.components.conversation,t=((s=(i=e==null?void 0:e.properties)==null?void 0:i.chat)==null?void 0:s.customData)??[];this.customData=t.map(r=>{let o;switch(r.entryType){case"text":case"dropdown":o="";break;case"number":o=0;break;case"boolean":o=!1;break}return{...r,value:o}})}_onStartChat(e){if(e.preventDefault(),this.showValidationWarning=!1,this.customData.forEach(l=>{this.validateCustomDataEntry(l)}),this.validationErrors.length>0){this.showValidationWarning=!0;return}this.submitted=!0;const t=this.customData.find(l=>l.name==="customerEmailAddress");t&&(this.emailController.email=t.value);const i=this.customData.reduce((l,u)=>(l[u.name]=u.value,l),{}),{customerName:s,customerEmailAddress:r,visitorQuestion:o,...a}=i,c=new CustomEvent("action",{bubbles:!0,composed:!0,detail:{key:"submitted",data:{name:s,email:r,question:o,customData:a}}});this.dispatchEvent(c)}_customDataValueChanged(e,t){this.customData=this.customData.map(i=>(i.name===t.name&&(i.value=e),i))}validateCustomDataEntry(e){e.required&&(e.name==="customerEmailAddress"&&!Ji(e.value)||!e.value?this.validationErrors.includes(e.name)||this.validationErrors.push(e.name):this.validationErrors=this.validationErrors.filter(t=>t!==e.name))}render(){if(this.submitted)return w;const e=this.application.texts;return y`<div class="container">
1355
+ `];let ne=Fs;pe([T()],ne.prototype,"platform");pe([T()],ne.prototype,"entries");pe([T()],ne.prototype,"typing");pe([T()],ne.prototype,"message");pe([T()],ne.prototype,"disabledInput");pe([T()],ne.prototype,"disabledSkipToLatest");pe([T()],ne.prototype,"disabledSubmit");pe([T()],ne.prototype,"chatOverlayActive");pe([T()],ne.prototype,"textAreaLength");pe([T()],ne.prototype,"showAuthBanner");pe([T()],ne.prototype,"authenticated");var Te=(n=>(n.Tunnistus="tunnistus",n.BankId="bankid",n.Freja="freja",n))(Te||{}),H=(n=>(n.Pending="pending",n.Authenticated="authenticated",n.Error="error",n))(H||{});class Bt{constructor(e){this.orderRef="",e={...e,idHubEidType:typeof(e==null?void 0:e.idHubEidType)=="string"?e.idHubEidType.toLowerCase():e.idHubEidType},this.config=e,this.url=`${e==null?void 0:e.idHubUrl}/${e==null?void 0:e.idHubCustomerKey}/${e==null?void 0:e.idHubOrgKey}/${e==null?void 0:e.idHubEidType}`,this.maxRetries=e.idHubMaxRetries??300}async auth(){try{const e=await fetch(`${this.url}/auth`,{headers:Bt.getHeaders(),body:JSON.stringify({clientName:"idhub-web-1.0.0",register:{clientType:"ACEWIDGET",agentId:"ACEWIDGET",userName:"ACEWIDGET"}}),method:"POST"});if(!e.ok)return{status:H.Error,errorMessage:`Auth failed with response: ${e.status} ${e.statusText}`};const t=await e.json();switch(this.orderRef=t.orderRef,this.config.idHubEidType){case Te.Tunnistus:return{tunnistusURL:t.tunnistusURL,status:H.Pending};case Te.BankId:return{autoStartToken:t.autoStartToken,status:H.Pending};case Te.Freja:throw new Error(`${Te.Freja} is not implemented`);default:throw new Error(`The service ${this.config.idHubEidType} is not implemented`)}}catch(e){return{status:H.Error,errorMessage:`Auth failed. Error: ${e}`}}}async collect(){for(let e=0;e<this.maxRetries;e++){await new Promise(i=>setTimeout(i,1e3));const t=await this.collectOnce();if(t&&t.status!==H.Pending)return t}return{status:H.Error}}async cancel(){try{return this.orderRef?(await fetch(`${this.url}/cancel`,{headers:Bt.getHeaders(),body:JSON.stringify({clientName:"idhub-web-1.0.0",orderRef:this.orderRef,method:"auth"}),method:"POST"}),{}):{status:H.Error,errorMessage:"Missing order reference."}}catch(e){return{status:H.Error,errorMessage:`Cancel failed. Error: ${e}`}}}static getHeaders(){return{accept:"application/json","accept-language":"sv-SE,sv;q=0.9,en-US;q=0.8,en;q=0.7","content-type":"application/json"}}async collectOnce(){try{if(!this.orderRef)return{status:H.Error,errorMessage:"Missing order reference."};const e=await fetch(`${this.url}/collect`,{headers:Bt.getHeaders(),body:JSON.stringify({clientName:"idhub-web-1.0.0",orderRef:this.orderRef,method:"auth"}),method:"POST"});if(!e.ok)return{status:H.Error,errorMessage:`Collect failed with response: ${e.status} ${e.statusText}`};const t=await e.json();return t.status===H.Error?{status:H.Error,subStatus:t.subStatus??void 0}:t}catch(e){return{status:H.Error,errorMessage:`Collect failed. Error: ${e}`}}}}const Se=n=>n.objectType==="info",Id=n=>n.objectType==="chatEntry",Pd=n=>n.objectType==="pen",Md=n=>n.objectType==="chatButtonClicked",Nd=n=>n.objectType==="endVideoButtonClicked",Ud=n=>n.type==="queue-status",Dd=n=>n.type==="established",zd=n=>n.type==="pen-status",Hd=n=>n.type==="prepareVideo",jd=n=>n.type==="videoPrepared",Fd=n=>n.type==="chatButtonClicked",Bd=n=>n.type==="endVideoButtonClicked",qd=n=>n.type==="chat-ended";var Ze=(n=>(n.Initial="initial",n.Error="error",n.Retry="retry",n))(Ze||{});class Fn extends Error{constructor(e){super(e),this.name="EngineException"}}class Es{constructor(e,t){this.endpoint=e,this.timeout=t,this.protocolVersion="A",this.penStatusJustSent=!1}async chatJoin(e){var i,s,r;const t=await this.sendRequest("chatJoin",{invitationUid:e.invitationUid,uid:e.uid,instance:e.instance,protocolVersion:this.protocolVersion,videoChatMode:e.videoChatMode,customerName:e.customerName});if(!((i=t==null?void 0:t.dataObjects)!=null&&i.length)||((s=t==null?void 0:t.dataObjects[0])==null?void 0:s.infoType)==="error")throw t.dataObjects?new Error(`chatRequest - ${(r=t==null?void 0:t.dataObjects[0])==null?void 0:r.text}`):new Error("chatRequest - unknown error")}async chatRequest(e){var i,s,r,o,a;const t=await this.sendRequest("chatRequest",{...e.customData,uid:e.uid,instance:e.instance,queueMessageInterval:e.queueMessageInterval.toString(),protocolVersion:this.protocolVersion,entrance:e.entrance,errand:e.errand.length?e.errand:"997",videoChatMode:e.videoChatMode,customerName:e.customerName,customerEmailAddress:e.customerEmailAddress,visitorQuestion:e.visitorQuestion,visitorUserAgent:((i=window==null?void 0:window.navigator)==null?void 0:i.userAgent)||"",sourceUrl:((s=window==null?void 0:window.location)==null?void 0:s.href)||"",...e.authToken&&{authToken:e.authToken}});if(!((r=t==null?void 0:t.dataObjects)!=null&&r.length)||((o=t==null?void 0:t.dataObjects[0])==null?void 0:o.infoType)==="error")throw t.dataObjects?new Error(`chatRequest - ${(a=t==null?void 0:t.dataObjects[0])==null?void 0:a.text}`):new Error("chatRequest - unknown error")}async videoPrepared(e){await this.sendRequest("videoPrepared",{uid:e.uid,instance:e.instance,result:e.result,protocolVersion:this.protocolVersion})}chatRead(e){return this.sendRequest("chatRead",{uid:e.uid,instance:e.instance,entrance:e.entrance,maxObjectId:`${e.maxObjectId}`,protocolVersion:this.protocolVersion})}sendPenStatusOn(e){if(this.penStatusTimer&&clearTimeout(this.penStatusTimer),e.key==="Enter"){this.penStatusJustSent=!1;return}this.penStatusJustSent||(this.sendRequest("chatPenStatus",{uid:e.uid,instance:e.instance,penStatus:"on",protocolVersion:this.protocolVersion}),this.penStatusJustSent=!0,setTimeout(()=>{this.penStatusJustSent=!1},5e3)),this.penStatusTimer=setTimeout(()=>this.sendPenStatusOff(e),5e3)}sendPenStatusOff(e){this.penStatusJustSent&&clearTimeout(this.penStatusTimer),this.sendRequest("chatPenStatus",{uid:e.uid,instance:e.instance,penStatus:"off",protocolVersion:this.protocolVersion})}chatWrite(e){return this.sendPenStatusOff(e),this.sendRequest("chatWrite",{uid:e.uid,instance:e.instance,clockstamp:e.clockstamp,message:e.message,protocolVersion:this.protocolVersion})}async chatQuit(e){this.sendPenStatusOff(e),await this.sendRequest("chatQuit",{uid:e.uid,instance:e.instance,protocolVersion:this.protocolVersion})}async chatCheckSession(e){var i;const t=await this.sendRequest("chatCheckSession",{uid:e.uid,instance:e.instance,protocolVersion:this.protocolVersion});return Object.keys(t).length===0?null:((i=t.dataObjects)==null||i.sort((s,r)=>s.objectId-r.objectId),t)}async chatEmailSession(e){return this.sendRequest("chatEmailSession",{uid:e.uid,instance:e.instance,emailAddress:e.emailAddress,protocolVersion:this.protocolVersion})}async sendRequest(e,t){const i=this.endpoint.includes("engine-simulator")?"include":void 0,s=`${Es.removeTrailingSlashes(this.endpoint)}/${e}`,r=await fetch(s,{body:new URLSearchParams(t),method:"POST",credentials:i,headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"*/*"},signal:this.timeout?AbortSignal.timeout(this.timeout):void 0});return Number(r.headers.get("content-length"))>0?r.json():{}}static removeTrailingSlashes(e){return e.replace(/\/+$/,"")}}const Vd=()=>"10000000-1000-4000-8000-100000000000".replace(/[018]/g,n=>(+n^crypto.getRandomValues(new Uint8Array(1))[0]&15>>+n/4).toString(16)),Ki=()=>typeof crypto.randomUUID=="function"?crypto.randomUUID():Vd();function Ji(n){return/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(n)}function Ya(n){return n.replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}function Wd(n){return decodeURIComponent(atob(n).split("").map(e=>"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2)).join(""))}class Gd{constructor(e,t){this.config=e,this.messageSubject$=new P,this.actionsSubject$=new P,this.messages=()=>this.messageSubject$.asObservable(),this.actions=()=>this.actionsSubject$.asObservable(),this.sessionId="",this.lastObjectId=0,this.sessionId=t??Ki(),this.client=new Es(this.config.engineUrl,this.config.engineTimeout)}chatJoin(e){return Ye(this.client.chatJoin({invitationUid:e.invitationUid,uid:this.sessionId,customerName:e.customerName,instance:this.config.instance,videoChatMode:this.config.videoChatMode})).pipe(Pi(t=>(console.error(t),this.messageSubject$.next({text:this.config.errorMessage??"An error occured",source:"system"}),new j)),Oe(()=>this.poll().pipe(mi(()=>this.poll()),vi())))}chatRequest(e){return Ye(this.client.chatRequest({uid:this.sessionId,customerName:e.customerName,customerEmailAddress:e.customerEmailAddress,visitorQuestion:e.visitorQuestion,instance:this.config.instance,queueMessageInterval:this.config.queueMessageInterval,entrance:this.config.entrance,errand:e.errand,videoChatMode:this.config.videoChatMode,customData:e.customData,...e.authToken&&{authToken:e.authToken}})).pipe(Pi(t=>(console.error(t),this.messageSubject$.next({text:this.config.errorMessage??"An error occured",source:"system"}),new j)),Oe(()=>this.poll().pipe(mi(()=>this.poll()),vi())))}reconnect(){return this.poll().pipe(mi(()=>this.poll()),vi())}poll(){return ac(()=>Ye(this.client.chatRead({uid:this.sessionId,instance:this.config.instance,entrance:this.config.entrance,maxObjectId:this.lastObjectId})).pipe(gc(e=>{this.processMessages(e)})))}async chatWrite(e){const t=await this.client.chatWrite({uid:this.sessionId,instance:this.config.instance,clockstamp:Date.now().toString(),message:e}),i=((t==null?void 0:t.dataObjects)||[]).find(s=>Se(s)&&s.infoType==="error");if(i)throw new Fn(i.text||"Unable to send message")}sendPenStatusOn(e){this.client.sendPenStatusOn({uid:this.sessionId,instance:this.config.instance,key:e})}async videoPrepared(e){await this.client.videoPrepared({uid:this.sessionId,instance:this.config.instance,result:e})}async chatQuit(){await this.client.chatQuit({uid:this.sessionId,instance:this.config.instance})}async chatEmailSession(e){const t=await this.client.chatEmailSession({uid:this.sessionId,instance:this.config.instance,emailAddress:e});if(((t==null?void 0:t.dataObjects)||[]).find(s=>Se(s)&&s.infoType==="error"))throw new Fn("Unable to send email with conversation")}processMessages(e){e.dataObjects.forEach(t=>{Id(t)&&t.source&&t.objectId>=this.lastObjectId&&this.messageSubject$.next({text:t.message,source:t.source,invitationNo:t.invitationNo.toString(),alias:t.alias||t.agentAlias}),Pd(t)&&this.actionsSubject$.next({penStatus:t.penStatus,type:"pen-status"}),Se(t)&&t.infoType==="queue"&&this.actionsSubject$.next({text:t.text,type:"queue-status"}),Se(t)&&t.infoType==="established"&&this.actionsSubject$.next({text:t.text,agentAlias:t.agentAlias,type:"established",videoEnded:t.videoEnded,contactId:t.contactId,agentUsername:t.agentUsername,entrance:t.entrance,errand:t.errand}),Se(t)&&t.infoType==="prepareVideo"&&this.actionsSubject$.next({type:"prepareVideo"}),Se(t)&&t.infoType==="videoPrepared"&&this.actionsSubject$.next({text:t.text,agent:t.agent,type:"videoPrepared",userUrl:t.userUrl}),Md(t)&&this.actionsSubject$.next({guestId:t.guestId,type:"chatButtonClicked"}),Nd(t)&&this.actionsSubject$.next({guestId:t.guestId,type:"endVideoButtonClicked"}),Se(t)&&["afterChat","finished"].includes(t.infoType)&&this.actionsSubject$.next({text:t.text,type:"chat-ended",showForm:t.infoType==="afterChat",contactId:t.contactId})}),this.lastObjectId=e.maxObjectId}async getChatStatus(){const e=await this.client.chatCheckSession({uid:this.sessionId,instance:this.config.instance});if(!e)return"noSession";const t=e.dataObjects;for(const i of t)if(Se(i))switch(i.infoType){case"finished":case"afterChat":return"finished";case"noSession":return"noSession"}return"active"}async rehydrate(){const e=await this.client.chatCheckSession({uid:this.sessionId,instance:this.config.instance});return!e||(e.dataObjects||[]).find(t=>Se(t)&&t.infoType==="noSession")?null:(this.processMessages(e),e)}}class Ne{constructor(e){this._email="",this._host=e,e.addController(this)}static getInstance(e){return Ne.instance?Ne.instance.updateHost(e):Ne.instance=new Ne(e),Ne.instance}updateHost(e){this._host=e,e.addController(this)}hostConnected(){}set email(e){this._email=e,this._host.requestUpdate()}get email(){return this._email}clearData(){this._email="",this._host.requestUpdate()}}var Zd=Object.defineProperty,Et=(n,e,t,i)=>{for(var s=void 0,r=n.length-1,o;r>=0;r--)(o=n[r])&&(s=o(e,t,s)||s);return s&&Zd(e,t,s),s},bt;let it=(bt=class extends A{constructor(){super(),this.submitted=!1,this.customData=[],this.customerName="",this.validationErrors=[],this.showValidationWarning=!1,this.emailController=Ne.getInstance(this),this.emailController.clearData()}connectedCallback(){var i,s;super.connectedCallback();const e=this.application.settings.components.conversation,t=((s=(i=e==null?void 0:e.properties)==null?void 0:i.chat)==null?void 0:s.customData)??[];this.customData=t.map(r=>{let o;switch(r.entryType){case"text":case"dropdown":o="";break;case"number":o=0;break;case"boolean":o=!1;break}return{...r,value:o}})}_onStartChat(e){if(e.preventDefault(),this.showValidationWarning=!1,this.customData.forEach(l=>{this.validateCustomDataEntry(l)}),this.validationErrors.length>0){this.showValidationWarning=!0;return}this.submitted=!0;const t=this.customData.find(l=>l.name==="customerEmailAddress");t&&(this.emailController.email=t.value);const i=this.customData.reduce((l,u)=>(l[u.name]=u.value,l),{}),{customerName:s,customerEmailAddress:r,visitorQuestion:o,...a}=i,c=new CustomEvent("action",{bubbles:!0,composed:!0,detail:{key:"submitted",data:{name:s,email:r,question:o,customData:a}}});this.dispatchEvent(c)}_customDataValueChanged(e,t){this.customData=this.customData.map(i=>(i.name===t.name&&(i.value=e),i))}validateCustomDataEntry(e){let t=!1;e.name==="customerEmailAddress"&&e.value&&(Ji(e.value)||(t=!0)),e.required&&!e.value&&(t=!0),t?this.validationErrors.includes(e.name)||this.validationErrors.push(e.name):this.validationErrors=this.validationErrors.filter(i=>i!==e.name)}render(){if(this.submitted)return w;const e=this.application.texts;return y`<div class="container">
1356
1356
  <form class="form" @submit=${this._onStartChat}>
1357
1357
  <div class="header-row">
1358
1358
  <telia-icon class="header-icon" svg=${ta.svg}></telia-icon>
@@ -2239,4 +2239,4 @@ Please report this to https://github.com/markedjs/marked.`,n){const i="<p>An err
2239
2239
  border: 1px solid var(--border-color-medium);
2240
2240
  box-sizing: border-box;
2241
2241
  }
2242
- `];let en=Xs;hp([de({context:ae}),k({attribute:!1})],en.prototype,"application");window.customElements.get("ace-video-iframe")||window.customElements.define("ace-video-iframe",en);class Ts extends wc{constructor(e,t){var i,s,r,o,a,c;super(e,t),this.pendingMessages=[],this.texts=this.component.application.texts,this.headerComponent=this.component.application.getComponent("widget-header"),this.isThirdPartyParticipant=this.component.properties.chat.isThirdPartyWidget,this.agent=this.createAgent(((i=this.component.application.storage.get("agentInfo"))==null?void 0:i.name)||""),this.user=this.createUser(((s=this.component.application.storage.get("userInfo"))==null?void 0:s.name)||""),this.params=new URLSearchParams(document.location.search),this.invitationUid=this.params.get("invitationUid"),this.customerName=this.params.get("customerName")||void 0,this.idHubUrl="https://idhub.dev-se.telia-ck8s.com/idhub-gateway/public",this.disconnected$=new P,this.agentUsername=null,this.conversationOption=null,this._conversationOptions={},this.sessionId=null,this.contactId=null,this.errand=null,this.entrance=null,this.guestId=null,this.chatOverlayActive=!1,this.inVideoCall=!1,this.onQueueStatusReceived=l=>{this.setQueueStatus(l.text||null)},this.onEstablished=l=>{this.contactId=l.contactId,this.errand=l.errand,this.entrance=l.entrance,this.agentUsername=l.agentUsername;const u={contactId:this.contactId,errand:this.errand,entrance:this.entrance,agentUsername:this.agentUsername};this.save({survey:u}),this.setQueueStatus(null),this.agent.name=l.agentAlias,this.component.application.storage.set("agentInfo",{name:this.agent.name}),l.videoEnded&&this.removeVideo()},this.onPrepareVideo=()=>{this.showVideoConfirmDialog()},this.onVideoPrepared=l=>{this.showVideoIFrame(l.userUrl)},this.onChatButtonClicked=l=>{this.showChatOverVideo(l.guestId)},this.onEndVideoButtonClicked=l=>{this.guestId&&(l==null?void 0:l.guestId)===this.guestId&&this.removeVideo()},this.onPenStatusChange=l=>{l.penStatus==="on"?this.setTypingState(!0):this.setTypingState(!1)},this.onChatEnded=async l=>{var p,d;this.shouldUseAuth&&this.endAuthenticatedSession(),this.setToastMessage(null),this.setTypingState(!1),this.videoConfirmDialogEntry&&this.videoConfirmDialogEntry.remove(),this.component.disableInput(),l.showForm&&this.showConversationEndedForm();const u=this.component.application.settings;(p=u==null?void 0:u.survey)!=null&&p.shouldUseSurvey&&((d=u==null?void 0:u.survey)!=null&&d.surveyBaseUrl)&&this.showSurvey(),this.isThirdPartyParticipant?this.removeHeaderOptions():this.setStartNewChatOption(),this.complete()},this.properties=t.properties,this.shouldUseAuth=(o=(r=this.component.application.settings)==null?void 0:r.auth)==null?void 0:o.shouldUseAuth,this.idHubEidType=(c=(a=this.component.application.settings)==null?void 0:a.auth)==null?void 0:c.idHubEidType.toLowerCase()}connect(e={}){super.connect(),this.setupAuthenticationListeners(),this._conversationOptions=e;const t={...this.properties.chat??{},...e},i=!!this.sessionId;if(!i){const r=Ki();this.setSessionId(r)}this.save({chatSessionId:this.sessionId}),this.engine=new Gd(t,this.sessionId),this.engine.messages().subscribe(r=>{switch(r.source){case"agent":this.printAgent(r.text);break;case"customer":this.clearPendingMessages(),this.isThirdPartyParticipant?r.source==="customer"&&r.invitationNo==="0"?this.printAgent(r.text,r.alias):this.printUser(r.text):r.source==="customer"&&Number(r.invitationNo)>0?this.printAgent(r.text,r.alias):this.printUser(r.text);break;case"system":this.printSystem(r.text);break}}),this.engine.actions().pipe(z(this.disconnected$),J(Ud)).subscribe(this.onQueueStatusReceived),this.engine.actions().pipe(z(this.disconnected$),J(Dd)).subscribe(this.onEstablished),this.engine.actions().pipe(z(this.disconnected$),J(Hd)).subscribe(this.onPrepareVideo),this.engine.actions().pipe(z(this.disconnected$),J(jd)).subscribe(this.onVideoPrepared),this.engine.actions().pipe(z(this.disconnected$),J(Fd)).subscribe(this.onChatButtonClicked),this.engine.actions().pipe(z(this.disconnected$),J(Bd)).subscribe(this.onEndVideoButtonClicked),this.engine.actions().pipe(z(this.disconnected$),J(zd)).subscribe(this.onPenStatusChange),this.engine.actions().pipe(z(this.disconnected$),J(qd)).subscribe(this.onChatEnded),this.setHeaderOption();const s=this.component.application.trigger;s&&s.widgetActive$.pipe(z(s.componentIsDestroyed$)).subscribe(r=>{r&&(this.conversationOption=null,this.setHeaderOption())}),this.component.userTyping$.pipe(z(this.disconnected$)).subscribe(r=>{var o;(o=this.engine)==null||o.sendPenStatusOn(r)}),i?this.engine.rehydrate().then(r=>{var o;r?(o=this.engine)==null||o.reconnect().pipe(z(this.disconnected$)).subscribe({error:a=>{console.error("Failed to reconnect to the engine:",a)}}):this.initializeChat(t).catch(a=>{console.error("Failed to initialize chat during rehydration:",a)})}):this.initializeChat(t).catch(r=>{console.error("Failed to initialize chat:",r)})}disconnected(){super.disconnected(),this.disconnected$.next()}onUserSubmit(e){const t=this.printUser(e.text);t.setStatus("pending"),this.pendingMessages.push(t),(async()=>{var i;try{await((i=this.engine)==null?void 0:i.chatWrite(e.text))}catch(s){s instanceof Fn?t.setStatus("failed"):(t.setStatus("failed"),console.warn("Unhandled error:",s))}})()}save(e){this.component.stateMachine.session().pipe(Oe(t=>(t==null?void 0:t.data$)||tt),Ee(1)).subscribe(t=>{this.saveToCurrentSession$.next({...t,...e})})}async rehydrate(e){if(e.chatSessionId&&this.setSessionId(e.chatSessionId),e.survey&&(this.contactId=e.survey.contactId,this.errand=e.survey.errand,this.entrance=e.survey.entrance,this.agentUsername=e.survey.agentUsername),this.shouldUseAuth){const t=this.component.application.storage.get("auth");t!=null&&t.authenticated?this.component.setAuthenticationBannerStatus(ee.Authenticated):this.component.setAuthenticationBannerStatus(ee.NonAuthenticated)}}static getInstance(e,t){return t.providerInstance??(t.providerInstance=new Ts(e,t)),t.providerInstance}async initializeChat(e){this.shouldUseAuth&&this.idHubEidType?(this.component.setAuthenticationBannerStatus(ee.NonAuthenticated),this.setupIDHubAuth(),this.idHubClient&&await this.startAuthenticationFlow()):this.handleWelcomeForm(e)}setupAuthenticationListeners(){var e;this.shouldUseAuth&&this.headerComponent&&this.headerComponent.actions$&&((e=this.headerComponent)==null||e.actions$.pipe(J(t=>t.key==="start-auth"),z(this.disconnected$)).subscribe(t=>{t.key==="start-auth"&&this.handleAuthentication()}))}setupIDHubAuth(){var e;this.idHubClient=new Bt({...(e=this.component.application.settings)==null?void 0:e.auth,idHubUrl:this.idHubUrl})}async startAuthenticationFlow(){this.component.disableInput(),this.resetAuthState(ee.NonAuthenticated);const e=await this.idHubClient.auth();if(e.status===H.Error){this.printSystem(this.texts.getOrFallback("auth.setup.error-message","An error occurred while setting up authentication.")),this.headerComponent.showAuthOptions=!1;return}switch(this.idHubEidType){case Te.Tunnistus:if(!e.tunnistusURL){this.printSystem(this.texts.getOrFallback("auth.setup.tunnistus.url-error-message","Unable to retrieve the Tunnistus authentication URL.")),this.headerComponent.showAuthOptions=!1;return}this.authURL=e.tunnistusURL,this.headerComponent.authUrl=e.tunnistusURL,this.headerComponent.authState=ee.NonAuthenticated,this.authenticationCardEntry=this.showTunnistusAuthCard(Ze.Initial,e.tunnistusURL),this.authenticationCardEntry.actions$.pipe(J(t=>t.key==="start-auth"),Ee(1)).subscribe(()=>{this.handleAuthentication()});break;case Te.BankId:break}}async handleWelcomeForm(e,t){let i=!0;e.webApiUrl&&(i=await this.isEntranceOpen(e.webApiUrl,e.entrance)),i?this.customerName?(this.user.name=this.customerName,this.startChat({customerName:this.customerName,customData:{}},t)):this.showWelcomeForm(t):this.showEntranceClosedDialog()}startChat(e,t){if(!this.engine)return;const i=e.customData.errand??this.engine.config.defaultErrand;if(!i)throw new Error("Errand is required but was not configured");this.isThirdPartyParticipant?(this.component.application.root.style.visibility="visible",this.engine.chatJoin({invitationUid:this.invitationUid,customerName:this.customerName??e.customerName}).pipe(z(this.disconnected$)).subscribe()):this.engine.chatRequest({customerName:e.customerName,customerEmailAddress:e.customerEmailAddress??"",visitorQuestion:e.visitorQuestion??"",customData:e.customData,errand:i,...t&&{authToken:t}}).pipe(z(this.disconnected$)).subscribe(),this.component.enableInput(),this.component.enableSkipToLatestMessage(),this.setEndConversationOption()}restartNewChat(){this.engine&&(this.setSessionId(null),this.component.clearMessages(),this.removeHeaderOptions(),this.connect(this._conversationOptions))}setQueueStatus(e){this.setToastMessage(e)}async endConversation(){var e;this.shouldUseAuth&&this.resetAuthState(ee.ChatEnded),await((e=this.engine)==null?void 0:e.chatQuit())}async sendConversationEmail(e){var t;try{await((t=this.engine)==null?void 0:t.chatEmailSession(e)),this.printSystem(this.texts.getOrFallback("email-form.email-sent-label","An email with the conversation was sent."))}catch(i){this.printSystem(this.texts.getOrFallback("email-form.error-message","Unable to send email with the conversation.")),i instanceof Fn||console.warn("Unhandled error:",i)}}clearPendingMessages(){this.pendingMessages.forEach(e=>{e.remove()})}setSessionId(e){this.sessionId=e}async isEntranceOpen(e,t){var s;let i=!1;try{const r=await fetch(`${e}/1/entrances/${t}/is-open`),o=await r.json();r.ok?i=(s=o==null?void 0:o.resultData)==null?void 0:s.isOpen:console.log(`Problem when fetching open status for entrance ${t}:`,o==null?void 0:o.resultMessage)}catch(r){console.log(`Failed to fetch open status for ${t}:`,r)}return i}resetAuthState(e){this.headerComponent.authState=e,this.headerComponent.userName="",this.headerComponent.authUrl="",this.authURL="",this.component.application.storage.removeItem("auth")}unescapeHtml(e){const t=document.createElement("textarea");return t.innerHTML=e,t.value}async handleAuthentication(){var t,i,s,r;this.headerComponent.userName=this.texts.getOrFallback("widget-header.authenticating","Authenticating..."),this.headerComponent.authState=ee.Authenticating;const e=await this.idHubClient.collect();switch(this.authenticationCardEntry&&this.authenticationCardEntry.remove(),this.idHubEidType){case Te.Tunnistus:if(e.status===H.Error){this.headerComponent.userName=this.texts.getOrFallback("widget-header.not-authenticated","Not authenticated"),this.headerComponent.authState=ee.NonAuthenticated,this.authenticationCardEntry=this.showTunnistusAuthCard(Ze.Error,this.authURL);return}else if(e.status===H.Authenticated){const o=Wd(((t=e==null?void 0:e.idhubEIDToken)==null?void 0:t.split(".")[1])??""),a=JSON.parse(o),c=((s=(i=a==null?void 0:a.completionData)==null?void 0:i.user)==null?void 0:s.name)??"";this.headerComponent.userName=c,this.headerComponent.authState=ee.Authenticated,this.component.application.storage.set("auth",{name:c,authenticated:!0}),this.component.setAuthenticationBannerStatus(ee.Authenticated),(r=this.authenticationCardEntry)==null||r.remove(),this.handleWelcomeForm(this.engine.config,e.idhubEIDToken)}break;case Te.BankId:break}}printAgent(e,t=""){const i=t.length>0?this.agent.print(e,"markdown",t):this.agent.print(e,"markdown");return this.setTypingState(!1),i}printUser(e){const t=this.unescapeHtml(e),i=Ni(Or(t));return this.user.print(i)}printSystem(e){const t=Ni(Or(e));return this.system.print(t)}showSurvey(){const e=new ie(q.System,{name:""},[{items:[["ace-survey",{content:""},{agentUsername:this.agentUsername??"",entrance:this.entrance??this.engine.config.entrance,errand:this.errand??this.engine.config.defaultErrand,contactId:this.contactId??""}]]}]);this.printEntry(e)}showTunnistusAuthCard(e,t,i){const s=new ie(q.System,{name:""},[{items:[["ace-tunnistus-auth-card",{content:""},{state:e,tunnistusURL:t??"",errorMessage:i??""}]]}]);return this.printEntry(s),s}showWelcomeForm(e){this.component.disableInput(),this.component.disableSkipToLatestMessage();let t;this.isThirdPartyParticipant?t=new ie(q.System,{name:""},[{items:[["ace-welcome-form-third-party",{content:""}]]}]):t=new ie(q.System,{name:""},[{items:[["ace-welcome-form",{content:""}]]}]),this.printEntry(t),t.actions$.pipe(J(i=>i.key==="submitted"),Ee(1)).subscribe(i=>{t.remove(),this.user.name=i.data.name,this.component.application.storage.set("userInfo",{name:this.user.name}),this.startChat({customerName:i.data.name,customerEmailAddress:i.data.email,visitorQuestion:i.data.question,customData:i.data.customData},e)})}showEntranceClosedDialog(){this.component.disableInput();const e=new ie(q.System,{name:""},[{items:[["ace-entrance-closed-dialog",{content:""}]]}]);this.printEntry(e)}showQuitConfirmDialog(){var e;(e=this.quitConfirmDialogEntry)==null||e.remove(),this.quitConfirmDialogEntry=new ie(q.System,{name:""},[{items:[["ace-quit-confirm-dialog",{content:""}]]}]),this.printEntry(this.quitConfirmDialogEntry),this.quitConfirmDialogEntry.actions$.pipe(J(t=>t.key==="quit-chat"),Ee(1)).subscribe(t=>{var i,s,r,o;((i=t.data)==null?void 0:i.result)==="quit"?(this.endConversation(),(s=this.quitConfirmDialogEntry)==null||s.remove()):((r=t.data)==null?void 0:r.result)==="cancel"&&((o=this.quitConfirmDialogEntry)==null||o.remove())})}showConversationEndedForm(){const e=new ie(q.System,{name:""},[{items:[["ace-conversation-ended-form",{content:""}]]}]);this.printEntry(e),e.actions$.pipe(J(t=>t.key==="submitted"),Ee(1)).subscribe(t=>{e.remove(),t.data.email&&this.sendConversationEmail(t.data.email)})}showVideoConfirmDialog(){this.videoConfirmDialogEntry=new ie(q.System,{name:""},[{items:[["ace-video-confirm-dialog",{content:""}]]}]),this.printEntry(this.videoConfirmDialogEntry),this.videoConfirmDialogEntry.actions$.pipe(J(e=>e.key==="video-confirm"),Ee(1)).subscribe(e=>{var t;this.videoConfirmDialogEntry&&this.videoConfirmDialogEntry.remove(),e.data.result==="declined"&&(this.guestId=null),(t=this.engine)==null||t.videoPrepared(e.data.result),this.printSystem(e.data.text)})}showVideoIFrame(e){var i;this.guestId=Ki(),this.videoIFrameElement=new en(e,this.guestId);const t=this.component.application.root;(i=t==null?void 0:t.shadowRoot)==null||i.prepend(this.videoIFrameElement),this.inVideoCall=!0,this.setHeaderOption()}showChatOverVideo(e){this.guestId&&e===this.guestId&&(this.chatOverlayActive=!0,this.showChatOverlay$.next(this.chatOverlayActive))}async endAuthenticatedSession(){this.component.setAuthenticationBannerStatus(ee.NonAuthenticated),await this.engine.getChatStatus()==="noSession"?(this.resetAuthState(ee.NonAuthenticated),this.setSessionId(null),this.component.clearMessages(),this.shouldUseAuth&&this.startAuthenticationFlow()):this.endConversation()}removeVideo(){var e;(e=this.videoIFrameElement)==null||e.remove(),this.guestId=null,this.chatOverlayActive&&(this.chatOverlayActive=!1,this.showChatOverlay$.next(this.chatOverlayActive)),this.inVideoCall=!1,this.setHeaderOption()}addHeaderOptions(e,t,i,s,r=!0){const o=this.component.application.getComponent("widget-header");if(o)return this.conversationOption?(this.conversationOption.label=e,this.conversationOption.key=t,this.conversationOption.icon=i,this.conversationOption.onClick=s,this.conversationOption.enabled=r,o.requestUpdate(),this.conversationOption):o.addOption({label:e,icon:i,closeOnClick:!0,key:t,onClick:s,enabled:r})}removeHeaderOptions(){const e=this.component.application.getComponent("widget-header");e&&e.removeOption(this.conversationOption)}setStartNewChatOption(){this.conversationOption=this.addHeaderOptions(this.texts.getOrFallback("widget-header.start-new-chat","Start new chat"),"start-new-chat-button",sa.svg,()=>{this.restartNewChat()})}setEndConversationOption(){this.conversationOption=this.addHeaderOptions(this.texts.getOrFallback("widget-header.end-conversation","End conversation"),"end-conversation-button",us.svg,()=>{this.showQuitConfirmDialog()},!this.inVideoCall)}async setHeaderOption(){switch(await this.engine.getChatStatus()){case"finished":this.isThirdPartyParticipant?this.removeHeaderOptions():this.setStartNewChatOption();break;case"active":this.setEndConversationOption();break;case"noSession":this.conversationOption=null}}}const dp=async n=>{(await rs.getInstance(n.container)).registerProvider("ace-chat",t=>Ts.getInstance("ace-chat",t))};exports.ChatProviderPlugin=dp;
2242
+ `];let en=Xs;hp([de({context:ae}),k({attribute:!1})],en.prototype,"application");window.customElements.get("ace-video-iframe")||window.customElements.define("ace-video-iframe",en);class Ts extends wc{constructor(e,t){var i,s,r,o,a,c;super(e,t),this.pendingMessages=[],this.texts=this.component.application.texts,this.headerComponent=this.component.application.getComponent("widget-header"),this.isThirdPartyParticipant=this.component.properties.chat.isThirdPartyWidget,this.agent=this.createAgent(((i=this.component.application.storage.get("agentInfo"))==null?void 0:i.name)||""),this.user=this.createUser(((s=this.component.application.storage.get("userInfo"))==null?void 0:s.name)||""),this.params=new URLSearchParams(document.location.search),this.invitationUid=this.params.get("invitationUid"),this.customerName=this.params.get("customerName")||void 0,this.idHubUrl="https://idhub.dev-se.telia-ck8s.com/idhub-gateway/public",this.disconnected$=new P,this.agentUsername=null,this.conversationOption=null,this._conversationOptions={},this.sessionId=null,this.contactId=null,this.errand=null,this.entrance=null,this.guestId=null,this.chatOverlayActive=!1,this.inVideoCall=!1,this.onQueueStatusReceived=l=>{this.setQueueStatus(l.text||null)},this.onEstablished=l=>{this.contactId=l.contactId,this.errand=l.errand,this.entrance=l.entrance,this.agentUsername=l.agentUsername;const u={contactId:this.contactId,errand:this.errand,entrance:this.entrance,agentUsername:this.agentUsername};this.save({survey:u}),this.setQueueStatus(null),this.agent.name=l.agentAlias,this.component.application.storage.set("agentInfo",{name:this.agent.name}),l.videoEnded&&this.removeVideo()},this.onPrepareVideo=()=>{this.showVideoConfirmDialog()},this.onVideoPrepared=l=>{this.showVideoIFrame(l.userUrl)},this.onChatButtonClicked=l=>{this.showChatOverVideo(l.guestId)},this.onEndVideoButtonClicked=l=>{this.guestId&&(l==null?void 0:l.guestId)===this.guestId&&this.removeVideo()},this.onPenStatusChange=l=>{l.penStatus==="on"?this.setTypingState(!0):this.setTypingState(!1)},this.onChatEnded=async l=>{var p,d;this.shouldUseAuth&&this.endAuthenticatedSession(),this.setToastMessage(null),this.setTypingState(!1),this.videoConfirmDialogEntry&&this.videoConfirmDialogEntry.remove(),this.component.disableInput(),l.showForm&&this.showConversationEndedForm();const u=this.component.application.settings;(p=u==null?void 0:u.survey)!=null&&p.shouldUseSurvey&&((d=u==null?void 0:u.survey)!=null&&d.surveyBaseUrl)&&this.showSurvey(),this.isThirdPartyParticipant?this.removeHeaderOptions():this.setStartNewChatOption(),this.complete()},this.properties=t.properties,this.shouldUseAuth=(o=(r=this.component.application.settings)==null?void 0:r.auth)==null?void 0:o.shouldUseAuth,this.idHubEidType=(c=(a=this.component.application.settings)==null?void 0:a.auth)==null?void 0:c.idHubEidType.toLowerCase()}connect(e={}){super.connect(),this.setupAuthenticationListeners(),this._conversationOptions=e;const t={...this.properties.chat??{},...e},i=!!this.sessionId;if(!i){const r=Ki();this.setSessionId(r)}this.save({chatSessionId:this.sessionId}),this.engine=new Gd(t,this.sessionId),this.engine.messages().subscribe(r=>{switch(r.source){case"agent":this.printAgent(r.text);break;case"customer":this.clearPendingMessages(),this.isThirdPartyParticipant?r.source==="customer"&&r.invitationNo==="0"?this.printAgent(r.text,r.alias):this.printUser(r.text):r.source==="customer"&&Number(r.invitationNo)>0?this.printAgent(r.text,r.alias):this.printUser(r.text);break;case"system":this.printSystem(r.text);break}}),this.engine.actions().pipe(z(this.disconnected$),J(Ud)).subscribe(this.onQueueStatusReceived),this.engine.actions().pipe(z(this.disconnected$),J(Dd)).subscribe(this.onEstablished),this.engine.actions().pipe(z(this.disconnected$),J(Hd)).subscribe(this.onPrepareVideo),this.engine.actions().pipe(z(this.disconnected$),J(jd)).subscribe(this.onVideoPrepared),this.engine.actions().pipe(z(this.disconnected$),J(Fd)).subscribe(this.onChatButtonClicked),this.engine.actions().pipe(z(this.disconnected$),J(Bd)).subscribe(this.onEndVideoButtonClicked),this.engine.actions().pipe(z(this.disconnected$),J(zd)).subscribe(this.onPenStatusChange),this.engine.actions().pipe(z(this.disconnected$),J(qd)).subscribe(this.onChatEnded),this.setHeaderOption();const s=this.component.application.trigger;s&&s.widgetActive$.pipe(z(s.componentIsDestroyed$)).subscribe(r=>{r&&(this.conversationOption=null,this.setHeaderOption())}),this.component.userTyping$.pipe(z(this.disconnected$)).subscribe(r=>{var o;(o=this.engine)==null||o.sendPenStatusOn(r)}),i?this.engine.rehydrate().then(r=>{var o;r?(o=this.engine)==null||o.reconnect().pipe(z(this.disconnected$)).subscribe({error:a=>{console.error("Failed to reconnect to the engine:",a)}}):this.initializeChat(t).catch(a=>{console.error("Failed to initialize chat during rehydration:",a)})}):this.initializeChat(t).catch(r=>{console.error("Failed to initialize chat:",r)})}disconnected(){super.disconnected(),this.disconnected$.next()}onUserSubmit(e){const t=this.printUser(e.text);t.setStatus("pending"),this.pendingMessages.push(t),(async()=>{var i;try{await((i=this.engine)==null?void 0:i.chatWrite(e.text))}catch(s){s instanceof Fn?t.setStatus("failed"):(t.setStatus("failed"),console.warn("Unhandled error:",s))}})()}save(e){this.component.stateMachine.session().pipe(Oe(t=>(t==null?void 0:t.data$)||tt),Ee(1)).subscribe(t=>{this.saveToCurrentSession$.next({...t,...e})})}async rehydrate(e){if(e.chatSessionId&&this.setSessionId(e.chatSessionId),e.survey&&(this.contactId=e.survey.contactId,this.errand=e.survey.errand,this.entrance=e.survey.entrance,this.agentUsername=e.survey.agentUsername),this.shouldUseAuth){const t=this.component.application.storage.get("auth");t!=null&&t.authenticated?this.component.setAuthenticationBannerStatus(ee.Authenticated):this.component.setAuthenticationBannerStatus(ee.NonAuthenticated)}}static getInstance(e,t){return t.providerInstance??(t.providerInstance=new Ts(e,t)),t.providerInstance}async initializeChat(e){this.shouldUseAuth&&this.idHubEidType?(this.component.setAuthenticationBannerStatus(ee.NonAuthenticated),this.setupIDHubAuth(),this.idHubClient&&await this.startAuthenticationFlow()):this.handleWelcomeForm(e)}setupAuthenticationListeners(){var e;this.shouldUseAuth&&this.headerComponent&&this.headerComponent.actions$&&((e=this.headerComponent)==null||e.actions$.pipe(J(t=>t.key==="start-auth"),z(this.disconnected$)).subscribe(t=>{t.key==="start-auth"&&this.handleAuthentication()}))}setupIDHubAuth(){var e;this.idHubClient=new Bt({...(e=this.component.application.settings)==null?void 0:e.auth,idHubUrl:this.idHubUrl})}async startAuthenticationFlow(){this.component.disableInput(),this.resetAuthState(ee.NonAuthenticated);const e=await this.idHubClient.auth();if(e.status===H.Error){this.printSystem(this.texts.getOrFallback("auth.setup.error-message","An error occurred while setting up authentication.")),this.headerComponent.showAuthOptions=!1;return}switch(this.idHubEidType){case Te.Tunnistus:if(!e.tunnistusURL){this.printSystem(this.texts.getOrFallback("auth.setup.tunnistus.url-error-message","Unable to retrieve the Tunnistus authentication URL.")),this.headerComponent.showAuthOptions=!1;return}this.authURL=e.tunnistusURL,this.headerComponent.authUrl=e.tunnistusURL,this.headerComponent.authState=ee.NonAuthenticated,this.authenticationCardEntry=this.showTunnistusAuthCard(Ze.Initial,e.tunnistusURL),this.authenticationCardEntry.actions$.pipe(J(t=>t.key==="start-auth"),Ee(1)).subscribe(()=>{this.handleAuthentication()});break;case Te.BankId:break}}async handleWelcomeForm(e,t){let i=!0;if(e.webApiUrl)try{i=await this.isEntranceOpen(e.webApiUrl,e.entrance)}catch(s){console.error("Error checking entrance status:",s),i=!1}i?this.customerName?(this.user.name=this.customerName,this.startChat({customerName:this.customerName,customData:{}},t)):this.showWelcomeForm(t):this.showEntranceClosedDialog()}startChat(e,t){if(!this.engine)return;const i=e.customData.errand??this.engine.config.defaultErrand;if(!i)throw new Error("Errand is required but was not configured");this.isThirdPartyParticipant?(this.component.application.root.style.visibility="visible",this.engine.chatJoin({invitationUid:this.invitationUid,customerName:this.customerName??e.customerName}).pipe(z(this.disconnected$)).subscribe()):this.engine.chatRequest({customerName:e.customerName,customerEmailAddress:e.customerEmailAddress??"",visitorQuestion:e.visitorQuestion??"",customData:e.customData,errand:i,...t&&{authToken:t}}).pipe(z(this.disconnected$)).subscribe(),this.component.enableInput(),this.component.enableSkipToLatestMessage(),this.setEndConversationOption()}restartNewChat(){this.engine&&(this.setSessionId(null),this.component.clearMessages(),this.removeHeaderOptions(),this.connect(this._conversationOptions))}setQueueStatus(e){this.setToastMessage(e)}async endConversation(){var e;this.shouldUseAuth&&this.resetAuthState(ee.ChatEnded),await((e=this.engine)==null?void 0:e.chatQuit())}async sendConversationEmail(e){var t;try{await((t=this.engine)==null?void 0:t.chatEmailSession(e)),this.printSystem(this.texts.getOrFallback("email-form.email-sent-label","An email with the conversation was sent."))}catch(i){this.printSystem(this.texts.getOrFallback("email-form.error-message","Unable to send email with the conversation.")),i instanceof Fn||console.warn("Unhandled error:",i)}}clearPendingMessages(){this.pendingMessages.forEach(e=>{e.remove()})}setSessionId(e){this.sessionId=e}async isEntranceOpen(e,t){var s;let i=!1;try{const r=await fetch(`${e}/1/entrances/${t}/is-open`),o=await r.json();r.ok?i=(s=o==null?void 0:o.resultData)==null?void 0:s.isOpen:console.log(`Problem when fetching open status for entrance ${t}:`,o==null?void 0:o.resultMessage)}catch(r){console.log(`Failed to fetch open status for ${t}:`,r)}return i}resetAuthState(e){this.headerComponent.authState=e,this.headerComponent.userName="",this.headerComponent.authUrl="",this.authURL="",this.component.application.storage.removeItem("auth")}unescapeHtml(e){const t=document.createElement("textarea");return t.innerHTML=e,t.value}async handleAuthentication(){var t,i,s,r;this.headerComponent.userName=this.texts.getOrFallback("widget-header.authenticating","Authenticating..."),this.headerComponent.authState=ee.Authenticating;const e=await this.idHubClient.collect();switch(this.authenticationCardEntry&&this.authenticationCardEntry.remove(),this.idHubEidType){case Te.Tunnistus:if(e.status===H.Error){this.headerComponent.userName=this.texts.getOrFallback("widget-header.not-authenticated","Not authenticated"),this.headerComponent.authState=ee.NonAuthenticated,this.authenticationCardEntry=this.showTunnistusAuthCard(Ze.Error,this.authURL);return}else if(e.status===H.Authenticated){const o=Wd(((t=e==null?void 0:e.idhubEIDToken)==null?void 0:t.split(".")[1])??""),a=JSON.parse(o),c=((s=(i=a==null?void 0:a.completionData)==null?void 0:i.user)==null?void 0:s.name)??"";this.headerComponent.userName=c,this.headerComponent.authState=ee.Authenticated,this.component.application.storage.set("auth",{name:c,authenticated:!0}),this.component.setAuthenticationBannerStatus(ee.Authenticated),(r=this.authenticationCardEntry)==null||r.remove(),this.handleWelcomeForm(this.engine.config,e.idhubEIDToken)}break;case Te.BankId:break}}printAgent(e,t=""){const i=t.length>0?this.agent.print(e,"markdown",t):this.agent.print(e,"markdown");return this.setTypingState(!1),i}printUser(e){const t=this.unescapeHtml(e),i=Ni(Or(t));return this.user.print(i)}printSystem(e){const t=Ni(Or(e));return this.system.print(t)}showSurvey(){const e=new ie(q.System,{name:""},[{items:[["ace-survey",{content:""},{agentUsername:this.agentUsername??"",entrance:this.entrance??this.engine.config.entrance,errand:this.errand??this.engine.config.defaultErrand,contactId:this.contactId??""}]]}]);this.printEntry(e)}showTunnistusAuthCard(e,t,i){const s=new ie(q.System,{name:""},[{items:[["ace-tunnistus-auth-card",{content:""},{state:e,tunnistusURL:t??"",errorMessage:i??""}]]}]);return this.printEntry(s),s}showWelcomeForm(e){this.component.disableInput(),this.component.disableSkipToLatestMessage();let t;this.isThirdPartyParticipant?t=new ie(q.System,{name:""},[{items:[["ace-welcome-form-third-party",{content:""}]]}]):t=new ie(q.System,{name:""},[{items:[["ace-welcome-form",{content:""}]]}]),this.printEntry(t),t.actions$.pipe(J(i=>i.key==="submitted"),Ee(1)).subscribe(i=>{t.remove(),this.user.name=i.data.name,this.component.application.storage.set("userInfo",{name:this.user.name}),this.startChat({customerName:i.data.name,customerEmailAddress:i.data.email,visitorQuestion:i.data.question,customData:i.data.customData},e)})}showEntranceClosedDialog(){this.component.disableInput();const e=new ie(q.System,{name:""},[{items:[["ace-entrance-closed-dialog",{content:""}]]}]);this.printEntry(e)}showQuitConfirmDialog(){var e;(e=this.quitConfirmDialogEntry)==null||e.remove(),this.quitConfirmDialogEntry=new ie(q.System,{name:""},[{items:[["ace-quit-confirm-dialog",{content:""}]]}]),this.printEntry(this.quitConfirmDialogEntry),this.quitConfirmDialogEntry.actions$.pipe(J(t=>t.key==="quit-chat"),Ee(1)).subscribe(t=>{var i,s,r,o;((i=t.data)==null?void 0:i.result)==="quit"?(this.endConversation(),(s=this.quitConfirmDialogEntry)==null||s.remove()):((r=t.data)==null?void 0:r.result)==="cancel"&&((o=this.quitConfirmDialogEntry)==null||o.remove())})}showConversationEndedForm(){const e=new ie(q.System,{name:""},[{items:[["ace-conversation-ended-form",{content:""}]]}]);this.printEntry(e),e.actions$.pipe(J(t=>t.key==="submitted"),Ee(1)).subscribe(t=>{e.remove(),t.data.email&&this.sendConversationEmail(t.data.email)})}showVideoConfirmDialog(){this.videoConfirmDialogEntry=new ie(q.System,{name:""},[{items:[["ace-video-confirm-dialog",{content:""}]]}]),this.printEntry(this.videoConfirmDialogEntry),this.videoConfirmDialogEntry.actions$.pipe(J(e=>e.key==="video-confirm"),Ee(1)).subscribe(e=>{var t;this.videoConfirmDialogEntry&&this.videoConfirmDialogEntry.remove(),e.data.result==="declined"&&(this.guestId=null),(t=this.engine)==null||t.videoPrepared(e.data.result),this.printSystem(e.data.text)})}showVideoIFrame(e){var i;this.guestId=Ki(),this.videoIFrameElement=new en(e,this.guestId);const t=this.component.application.root;(i=t==null?void 0:t.shadowRoot)==null||i.prepend(this.videoIFrameElement),this.inVideoCall=!0,this.setHeaderOption()}showChatOverVideo(e){this.guestId&&e===this.guestId&&(this.chatOverlayActive=!0,this.showChatOverlay$.next(this.chatOverlayActive))}async endAuthenticatedSession(){this.component.setAuthenticationBannerStatus(ee.NonAuthenticated),await this.engine.getChatStatus()==="noSession"?(this.resetAuthState(ee.NonAuthenticated),this.setSessionId(null),this.component.clearMessages(),this.shouldUseAuth&&this.startAuthenticationFlow()):this.endConversation()}removeVideo(){var e;(e=this.videoIFrameElement)==null||e.remove(),this.guestId=null,this.chatOverlayActive&&(this.chatOverlayActive=!1,this.showChatOverlay$.next(this.chatOverlayActive)),this.inVideoCall=!1,this.setHeaderOption()}addHeaderOptions(e,t,i,s,r=!0){const o=this.component.application.getComponent("widget-header");if(o)return this.conversationOption?(this.conversationOption.label=e,this.conversationOption.key=t,this.conversationOption.icon=i,this.conversationOption.onClick=s,this.conversationOption.enabled=r,o.requestUpdate(),this.conversationOption):o.addOption({label:e,icon:i,closeOnClick:!0,key:t,onClick:s,enabled:r})}removeHeaderOptions(){const e=this.component.application.getComponent("widget-header");e&&e.removeOption(this.conversationOption)}setStartNewChatOption(){this.conversationOption=this.addHeaderOptions(this.texts.getOrFallback("widget-header.start-new-chat","Start new chat"),"start-new-chat-button",sa.svg,()=>{this.restartNewChat()})}setEndConversationOption(){this.conversationOption=this.addHeaderOptions(this.texts.getOrFallback("widget-header.end-conversation","End conversation"),"end-conversation-button",us.svg,()=>{this.showQuitConfirmDialog()},!this.inVideoCall)}async setHeaderOption(){switch(await this.engine.getChatStatus()){case"finished":this.isThirdPartyParticipant?this.removeHeaderOptions():this.setStartNewChatOption();break;case"active":this.setEndConversationOption();break;case"noSession":this.conversationOption=null}}}const dp=async n=>{(await rs.getInstance(n.container)).registerProvider("ace-chat",t=>Ts.getInstance("ace-chat",t))};exports.ChatProviderPlugin=dp;
package/index.mjs CHANGED
@@ -8381,9 +8381,10 @@ let it = (bt = class extends A {
8381
8381
  this.customData = this.customData.map((i) => (i.name === t.name && (i.value = e), i));
8382
8382
  }
8383
8383
  validateCustomDataEntry(e) {
8384
- e.required && (e.name === "customerEmailAddress" && !Ji(e.value) || !e.value ? this.validationErrors.includes(e.name) || this.validationErrors.push(e.name) : this.validationErrors = this.validationErrors.filter(
8385
- (t) => t !== e.name
8386
- ));
8384
+ let t = !1;
8385
+ e.name === "customerEmailAddress" && e.value && (Ji(e.value) || (t = !0)), e.required && !e.value && (t = !0), t ? this.validationErrors.includes(e.name) || this.validationErrors.push(e.name) : this.validationErrors = this.validationErrors.filter(
8386
+ (i) => i !== e.name
8387
+ );
8387
8388
  }
8388
8389
  render() {
8389
8390
  if (this.submitted)
@@ -9999,10 +10000,16 @@ class Ts extends xc {
9999
10000
  }
10000
10001
  async handleWelcomeForm(e, t) {
10001
10002
  let i = !0;
10002
- e.webApiUrl && (i = await this.isEntranceOpen(
10003
- e.webApiUrl,
10004
- e.entrance
10005
- )), i ? this.customerName ? (this.user.name = this.customerName, this.startChat(
10003
+ if (e.webApiUrl)
10004
+ try {
10005
+ i = await this.isEntranceOpen(
10006
+ e.webApiUrl,
10007
+ e.entrance
10008
+ );
10009
+ } catch (s) {
10010
+ console.error("Error checking entrance status:", s), i = !1;
10011
+ }
10012
+ i ? this.customerName ? (this.user.name = this.customerName, this.startChat(
10006
10013
  {
10007
10014
  customerName: this.customerName,
10008
10015
  customData: {}
package/package.json CHANGED
@@ -1,9 +1,9 @@
1
1
  {
2
2
  "name": "@telia-ace/ace-chat-flamingo",
3
- "version": "1.1.123-rc.14",
3
+ "version": "1.1.123-rc.16",
4
4
  "dependencies": {
5
- "@telia-ace/widget-core-flamingo": "1.1.123-rc.14",
6
- "@telia-ace/widget-conversation-flamingo": "1.1.123-rc.14",
5
+ "@telia-ace/widget-core-flamingo": "1.1.123-rc.16",
6
+ "@telia-ace/widget-conversation-flamingo": "1.1.123-rc.16",
7
7
  "rxjs": "^7.8.2",
8
8
  "lit": "^3.0.2",
9
9
  "@teliads/icons": "^8.4.0",