@telia-ace/conversational-hub-bot-provider 1.3.9 → 1.3.10

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.
@@ -6,7 +6,7 @@ import { useContainer as R, useDispatch as T, useConversation as _ } from "@teli
6
6
  import { FormBuilder as j } from "@telia-ace/widget-forms";
7
7
  import { appendClassNames as k } from "@telia-ace/widget-utilities";
8
8
  import { useState as G, useRef as I, useEffect as S, useCallback as V } from "react";
9
- import { u as $ } from "./index-25ab09c8.mjs";
9
+ import { u as $ } from "./index-735998e7.mjs";
10
10
  import "@telia-ace/widget-conversation";
11
11
  import "@telia-ace/widget-services";
12
12
  const tt = ({
@@ -1,3 +1,3 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const j=require("react/jsx-runtime"),A=require("@emotion/styled"),F=require("@telia-ace/knowledge-data-client"),R=require("@telia-ace/knowledge-widget-adapters"),p=require("@telia-ace/knowledge-widget-ui"),T=require("@telia-ace/widget-forms"),$=require("@telia-ace/widget-utilities"),c=require("react"),k=require("./index-21624a6d.js");require("@telia-ace/widget-conversation");require("@telia-ace/widget-services");const z=({contactMethodId:n,guideId:o,groupId:m,className:x})=>{var C,v,w;const[e,s]=c.useState(),d=p.useContainer(),D=p.useDispatch(),b=c.useRef(!0),l=p.useConversation();c.useEffect(()=>{const{events:u}=d.get("$widget"),q=u.subscribe("conversational-hub-provider:form-submitted",async(f,r)=>{var M;if(((M=r.form.meta)==null?void 0:M.groupId)!==m||r.id!==(e==null?void 0:e.id))return;l&&(r.form.meta||(r.form.meta={}),r.form.meta.conversation=l);const y=await d.getAsync("contactMethods"),t={...e,body:{...e.body,form:r.form}},{errors:i,valid:h,errorTypes:N}=await y.validate(t);if(!h){const S=new T.FormBuilder(e.body.form);s(void 0),S.setValidationErrors(i),t.body={...t.body,form:S.get()},s({...t});return}const E=await y.submit(t);t.confirmation=E,s(t)}),a=u.subscribe("bot-provider:evaluate",async(f,r)=>{if(r.id!==n)return;const t=await(await d.getAsync("contactMethods")).evaluate(e);let i={...e,body:{...e.body,form:t}};const h=k.updateForm(i,{submit:"Submit",errors:{},meta:{groupId:m}});i={...i,body:h},s(i)});return()=>{q(),a()}},[d,e,s,l]);const g=c.useCallback(async u=>{const a=await(await F.DataClient.getInstance(d)).fetch(F.DataType.ContactMethod,{contactMethodId:u,guideId:o},{noCache:!0}),f=k.updateForm(a,{submit:"Submit",errors:{},meta:{groupId:m}});if(a.body=f,a.body.guideId=o,!b.current)return null;s(a)},[b]);return c.useEffect(()=>(g(n),()=>{b.current=!1}),[n,g]),e?j.jsx(B,{...e,body:{...e.body,form:e.body.form?{...e.body.form,data:(C=e.body.form)==null?void 0:C.data,layout:{...e.body.form.layout},meta:(v=e.body.form)==null?void 0:v.meta,schema:(w=e.body.form)==null?void 0:w.schema}:void 0,guideId:e.body.guideId},inline:!0,expanded:!0,dispatch:D,className:$.appendClassNames("humany-bot-contact-method",x)}):null},B=A(R.ContactMethod)`
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const j=require("react/jsx-runtime"),A=require("@emotion/styled"),F=require("@telia-ace/knowledge-data-client"),R=require("@telia-ace/knowledge-widget-adapters"),p=require("@telia-ace/knowledge-widget-ui"),T=require("@telia-ace/widget-forms"),$=require("@telia-ace/widget-utilities"),c=require("react"),k=require("./index-02b60805.js");require("@telia-ace/widget-conversation");require("@telia-ace/widget-services");const z=({contactMethodId:n,guideId:o,groupId:m,className:x})=>{var C,v,w;const[e,s]=c.useState(),d=p.useContainer(),D=p.useDispatch(),b=c.useRef(!0),l=p.useConversation();c.useEffect(()=>{const{events:u}=d.get("$widget"),q=u.subscribe("conversational-hub-provider:form-submitted",async(f,r)=>{var M;if(((M=r.form.meta)==null?void 0:M.groupId)!==m||r.id!==(e==null?void 0:e.id))return;l&&(r.form.meta||(r.form.meta={}),r.form.meta.conversation=l);const y=await d.getAsync("contactMethods"),t={...e,body:{...e.body,form:r.form}},{errors:i,valid:h,errorTypes:N}=await y.validate(t);if(!h){const S=new T.FormBuilder(e.body.form);s(void 0),S.setValidationErrors(i),t.body={...t.body,form:S.get()},s({...t});return}const E=await y.submit(t);t.confirmation=E,s(t)}),a=u.subscribe("bot-provider:evaluate",async(f,r)=>{if(r.id!==n)return;const t=await(await d.getAsync("contactMethods")).evaluate(e);let i={...e,body:{...e.body,form:t}};const h=k.updateForm(i,{submit:"Submit",errors:{},meta:{groupId:m}});i={...i,body:h},s(i)});return()=>{q(),a()}},[d,e,s,l]);const g=c.useCallback(async u=>{const a=await(await F.DataClient.getInstance(d)).fetch(F.DataType.ContactMethod,{contactMethodId:u,guideId:o},{noCache:!0}),f=k.updateForm(a,{submit:"Submit",errors:{},meta:{groupId:m}});if(a.body=f,a.body.guideId=o,!b.current)return null;s(a)},[b]);return c.useEffect(()=>(g(n),()=>{b.current=!1}),[n,g]),e?j.jsx(B,{...e,body:{...e.body,form:e.body.form?{...e.body.form,data:(C=e.body.form)==null?void 0:C.data,layout:{...e.body.form.layout},meta:(v=e.body.form)==null?void 0:v.meta,schema:(w=e.body.form)==null?void 0:w.schema}:void 0,guideId:e.body.guideId},inline:!0,expanded:!0,dispatch:D,className:$.appendClassNames("humany-bot-contact-method",x)}):null},B=A(R.ContactMethod)`
2
2
  padding: ${n=>{var o;return(o=n.theme.sizes)==null?void 0:o.normal}} ${n=>{var o;return(o=n.theme.sizes)==null?void 0:o.medium}};
3
3
  `;exports.default=z;
@@ -0,0 +1 @@
1
+ "use strict";var D=Object.defineProperty;var z=(i,t,n)=>t in i?D(i,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):i[t]=n;var y=(i,t,n)=>(z(i,typeof t!="symbol"?t+"":t,n),n);const O=require("@telia-ace/widget-conversation"),x=require("@telia-ace/widget-services"),S=require("@telia-ace/widget-utilities"),B=require("@telia-ace/widget-forms");class F{constructor(t){y(this,"enabled",!0);y(this,"botProviderGlobalStateKey","bot-provider-global-state");y(this,"botProviderLocalStateKey","bot-provider-local-state");y(this,"botProviderEntriesKey","bot-provider-entries");y(this,"botProviderMetaStateKey","bot-provider-conversation-meta");this.container=t}getKey(t){let n;switch(t){case"localState":n=this.botProviderLocalStateKey;break;case"globalState":n=this.botProviderGlobalStateKey;break;case"entries":n=this.botProviderEntriesKey;break;case"meta":n=this.botProviderMetaStateKey;break}return n}async read(t){const n=this.getKey(t);if(!(!this.enabled||!n))return x.readStorage(this.container,n)}async write(t,n){const e=this.getKey(n);if(!this.enabled||!e)return;(await x.createStorageWriter(this.container,e,x.StorageCategory.Necessary))(t)}}var T=(i=>(i.ContactMethod="ace-conversational-hub-contact-method",i))(T||{});const W=({isUser:i,items:t=[],meta:n={}})=>{const e=S.uuid();return{id:e,isUser:i,items:t.map(d=>({id:d.id||S.uuid(),isUser:i,groupId:e,message:d.message||[]})),meta:n}},Q=(i,{submit:t,errors:n,meta:e})=>{var a;if((a=i==null?void 0:i.body)!=null&&a.form){const{body:d}=i,u=new B.FormBuilder(d.form);return d.form.layout.submit||u.createComponent(B.submitButton(t,"submit")),n&&u.setValidationErrors(n),e&&u.setMeta(e),{...d,form:u.get()}}return(i==null?void 0:i.body)||{}},X=async(i,t,n)=>{(await(await i.getAsync("dataClient")).getClient()).parameters.set(t,n)},N=({messageId:i,message:t,group:n})=>({id:i,message:t,groupId:n.id,isUser:n.isUser}),Y=async(i,t,n)=>{const e=async(o,h,f=[],P)=>{var A,k;const m=S.uuid();switch(o.type!=="List"&&o.tags.includes("guide")&&((k=(A=o.content.hints)==null?void 0:A[0])!=null&&k.id)&&await X(i,"LastGuideId",o.content.hints[0].id),o.type){case"Text":{const C=[];if(C.push(N({messageId:m,message:[O.ConversationMessageListItemType.HTML,{body:o.content.html}],group:h})),f.length){f.find(b=>{var K;return b.type==="List"&&((K=b.localState)==null?void 0:K.$type)==="Humany.Matching.Bots.Conversations.States.ContactState, Humany.Matching"});const I=f.find(b=>b.tags.includes("contact")&&b.type==="Contact");I&&C.push(N({messageId:m,message:[T.ContactMethod,{contactMethodId:I.content.id,groupId:h.id,guideId:I.content.guideId}],group:h}))}return C}case"Contact":return[N({messageId:m,message:[T.ContactMethod,{contactMethodId:o.content.id,groupId:h.id,guideId:o.content.guideId}],group:h})];case"Error":return[N({messageId:m,message:[O.ConversationMessageListItemType.HTML,{body:o.content.message||"Something went wrong."}],group:h})];default:return[]}},a=new Map([["Text",1],["Contact",2]]),d=[],u=t.sort((o,h)=>{const P=a.get(o.type)||20,m=a.get(h.type)||20;return P-m}).filter(o=>!o.relation).reduce((o,h)=>o.concat(h),[]),$=o=>typeof o.actions.selector<"u";for(const o of u){const h=t.filter(m=>m.relation===o.id&&!$(m)),f=W({isUser:!1});(await e(o,f,h)).forEach(m=>{f.items.push(m)}),f.items.length&&d.push(f)}return d};class Z{constructor(t,n,e,a){y(this,"globalState");y(this,"localState");y(this,"clientId");y(this,"entries");this.endpoint=t,this.events=n,this.store=e,this.container=a,this.clientId=S.uuid(),this.entries=[]}async fetchGuide(t){const n={command:{guide:{id:t}},globalState:this.globalState,clientId:this.clientId};return await this.postEnvelope(n)}async postEnvelope(t,n){try{const e=await fetch(this.endpoint,this.getHttpOptions(t));if(!e.ok)throw e;const a=await e.json();return this.handleResponse(a,n)}catch(e){process.env.NODE_ENV!=="production"&&console.warn("Something went wrong when posting the envelope.");let a="Something went wrong";return(e.message==="Failed to fetch"||e.message==="NetworkError when attempting to fetch resource.")&&(a="Lost connection... Please try again."),this.handleResponse({entries:[{id:S.uuid(),type:"Error",timestamp:new Date().toISOString(),content:{message:a},actions:{},tags:[]}]})}}async handleResponse(t,n){this.entries=this.entries.concat(t.entries),this.store.write(this.entries,"entries");const e=t.entries.find(d=>d.type==="Widget");return e&&this.events.dispatch("provider:widget-entry",e.content),t.globalState&&(this.globalState=t.globalState,this.store.write(t.globalState,"globalState")),this.localState=t.entries.reduce((d,u)=>u.localState?u.localState:d,void 0),this.store.write(this.localState,"localState"),await Y(this.container,t.entries)}getHttpOptions(t){const n={method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"}};return t.funnel=this.container.get("$widget").name,t.localState=t.localState||this.localState,Object.assign({},n,{body:JSON.stringify(t),credentials:"same-origin"})}}const ee="@telia-ace/conversational-hub-bot-provider",te="0.0.16",ne="./index.js",ie="./index.d.ts",oe={".":{import:"./index.mjs",require:"./index.js"}},se={"@telia-ace/widget-conversation":"*","@webprovisions/platform":"^1.1.4","@telia-ace/knowledge-widget-core":"*","@telia-ace/widget-utilities":"*","@telia-ace/widget-services":"*","@telia-ace/widget-core":"*","@telia-ace/knowledge-data-client":"*","@telia-ace/knowledge-widget-adapters":"*","@telia-ace/knowledge-widget-ui":"*","@telia-ace/widget-forms":"*"},re={"@emotion/react":"11.11.1","@emotion/styled":"11.11.0",react:"18.2.0"},E={name:ee,version:te,main:ne,types:ie,exports:oe,dependencies:se,peerDependencies:re},ae=async i=>{var G,H,j,_,U;const t="chub-plugin",n=i.get("$widget"),e=(U=(_=(j=(H=(G=n==null?void 0:n.container)==null?void 0:G.get("$settings"))==null?void 0:H.components)==null?void 0:j.conversation)==null?void 0:_.properties)==null?void 0:U.conversationalHubPluginSettings;let a,d,u,$=(e==null?void 0:e.connectionAttempts)??5,o,h,f;S.Logger.info((E==null?void 0:E.name)+" version: "+(E==null?void 0:E.version)),O.registerCustomMessageComponent(i,T.ContactMethod,Promise.resolve().then(()=>require("./contact-method-b3890fe6.js")));const P=await x.createStorageWriter(i,"conversational-hub-session",x.StorageCategory.Necessary),m=(r,c)=>{const{knowledgeBotEndpoint:l}=c.properties();if(l)return`${l}/conversations`;const{data:g}=r.get("$settings");if(!g||!g.projection)throw new Error("Missing Knowledge Bot endpoint");return`${g.projection}/conversations`};(await O.ConversationPlatform.getInstance(i)).registerProvider(t,(r,c)=>{a=r,d=a.controller,u=a.createAgent({name:e==null?void 0:e.botName,avatar:e==null?void 0:e.avatar}),f=m(i,c);const{events:l}=i.get("$widget"),g=new F(i);h=new Z(f,l,g,i),k();const p=()=>d.providers.includes(t);window.controller=d,c.actions.create("submit",s=>{const{events:v}=i.get("$widget");v.dispatch("conversational-hub-provider:form-submitted",s)}),c.actions.watch("conversation.action",(s,v)=>(p()&&C(s),v(s))),c.actions.watch("conversation.user-submit",(s,v)=>{if(!p())return v(s);I(s.text),a.user.print(s.text.replace(/</g,"&lt;").replace(/>/g,"&gt;"))})});async function k(r=!0){const c=await x.readStorage(i,"conversational-hub-session");c!=null&&c.sessionId&&r?o=c==null?void 0:c.sessionId:e!=null&&e.welcomeMessage?u.print(e==null?void 0:e.welcomeMessage):await b(e.baseUrl+"/initialize",`{"extension": "${e.extension}"}`,r)}async function C(r){await b(`${e.baseUrl}/input/${o}`,`{"type":"button_click","language":"${e.language}","content":{"button_text":"${r.label}","value":"${r.actionKey}"}}`)}async function I(r){const c={text:r};o||await b(e.baseUrl+"/initialize",`{"extension": "${e.extension}"}`,!1),await b(`${e.baseUrl}/input/${o}`,`{"type":"text","language":"${e.language}","content":${JSON.stringify(c)}}`)}async function b(r,c,l=!0){var v,L,V,q;const g=a.loading();let p,s;try{p=await fetch(r,{method:"POST",body:c}),s=await(p==null?void 0:p.json())}catch(M){M instanceof SyntaxError?S.Logger.error("Incorrect JSON format.",M):S.Logger.error("Network error: check connection or baseUrl.",M),g(),u.print(e.errorMessage||"An error occurred");return}if(!(p!=null&&p.ok)){if(S.Logger.error(`HTTP ${p==null?void 0:p.status}.`,JSON.stringify(s)),g(),!!((v=s==null?void 0:s.errors)!=null&&v.filter(w=>w.code==="1003").length)&&$>0){$--,await new Promise(R=>setTimeout(R,500)),await k(!1);const w=JSON.parse(c);(L=w==null?void 0:w.content)!=null&&L.text?await I(w.content.text):(V=w==null?void 0:w.content)!=null&&V.action&&await C((q=w==null?void 0:w.content)==null?void 0:q.action)}else u.print(e.errorMessage||"An error occurred");return}g(),$=(e==null?void 0:e.connectionAttempts)??5,s!=null&&s.action_payload&&K(s.action_payload),o=s==null?void 0:s.session_id,P({sessionId:o}),l&&J(s)}async function K(r){var p;const c=(p=r==null?void 0:r.transfer_parameters)==null?void 0:p.contactGuide,l=a.loading(),g=await h.fetchGuide(parseInt(c));if(l(),g){const s=g.concat(g);if(s.length){const v=s[0].items.map(L=>L.message);u.print(v)}}}function J(r){var c;r==null||r.agent_response.forEach(l=>{u.print(l.payload.text)}),(c=r==null?void 0:r.prompt)!=null&&c.items&&u.print(["button-list",{actions:r.prompt.items.map(l=>{let g;return l.type==="button"&&(g={actionKey:l.value,label:l.text}),l.type==="link"&&(g={actionKey:l.value,label:l.text,data:{href:l.url,target:(e==null?void 0:e.linkTarget)??"_blank"}}),g})}])}};exports.ConversationalHubPlugin=ae;exports.updateForm=Q;
@@ -1,23 +1,23 @@
1
1
  var q = Object.defineProperty;
2
- var F = (o, t, n) => t in o ? q(o, t, { enumerable: !0, configurable: !0, writable: !0, value: n }) : o[t] = n;
3
- var v = (o, t, n) => (F(o, typeof t != "symbol" ? t + "" : t, n), n);
4
- import { ConversationMessageListItemType as U, registerCustomMessageComponent as Q, ConversationPlatform as X } from "@telia-ace/widget-conversation";
2
+ var F = (i, e, n) => e in i ? q(i, e, { enumerable: !0, configurable: !0, writable: !0, value: n }) : i[e] = n;
3
+ var y = (i, e, n) => (F(i, typeof e != "symbol" ? e + "" : e, n), n);
4
+ import { ConversationMessageListItemType as B, registerCustomMessageComponent as Q, ConversationPlatform as X } from "@telia-ace/widget-conversation";
5
5
  import { readStorage as J, createStorageWriter as R, StorageCategory as D } from "@telia-ace/widget-services";
6
6
  import { uuid as P, Logger as O } from "@telia-ace/widget-utilities";
7
7
  import { FormBuilder as Y, submitButton as Z } from "@telia-ace/widget-forms";
8
8
  class tt {
9
- constructor(t) {
10
- v(this, "enabled", !0);
9
+ constructor(e) {
10
+ y(this, "enabled", !0);
11
11
  // set whether or not to store data
12
- v(this, "botProviderGlobalStateKey", "bot-provider-global-state");
13
- v(this, "botProviderLocalStateKey", "bot-provider-local-state");
14
- v(this, "botProviderEntriesKey", "bot-provider-entries");
15
- v(this, "botProviderMetaStateKey", "bot-provider-conversation-meta");
16
- this.container = t;
12
+ y(this, "botProviderGlobalStateKey", "bot-provider-global-state");
13
+ y(this, "botProviderLocalStateKey", "bot-provider-local-state");
14
+ y(this, "botProviderEntriesKey", "bot-provider-entries");
15
+ y(this, "botProviderMetaStateKey", "bot-provider-conversation-meta");
16
+ this.container = e;
17
17
  }
18
- getKey(t) {
18
+ getKey(e) {
19
19
  let n;
20
- switch (t) {
20
+ switch (e) {
21
21
  case "localState":
22
22
  n = this.botProviderLocalStateKey;
23
23
  break;
@@ -33,100 +33,100 @@ class tt {
33
33
  }
34
34
  return n;
35
35
  }
36
- async read(t) {
37
- const n = this.getKey(t);
36
+ async read(e) {
37
+ const n = this.getKey(e);
38
38
  if (!(!this.enabled || !n))
39
39
  return J(this.container, n);
40
40
  }
41
- async write(t, n) {
42
- const e = this.getKey(n);
43
- if (!this.enabled || !e)
41
+ async write(e, n) {
42
+ const t = this.getKey(n);
43
+ if (!this.enabled || !t)
44
44
  return;
45
45
  (await R(
46
46
  this.container,
47
- e,
47
+ t,
48
48
  D.Necessary
49
- ))(t);
49
+ ))(e);
50
50
  }
51
51
  }
52
- var A = /* @__PURE__ */ ((o) => (o.ContactMethod = "ace-conversational-hub-contact-method", o))(A || {});
52
+ var T = /* @__PURE__ */ ((i) => (i.ContactMethod = "ace-conversational-hub-contact-method", i))(T || {});
53
53
  const et = ({
54
- isUser: o,
55
- items: t = [],
54
+ isUser: i,
55
+ items: e = [],
56
56
  meta: n = {}
57
57
  }) => {
58
- const e = P();
58
+ const t = P();
59
59
  return {
60
- id: e,
61
- isUser: o,
62
- items: t.map((d) => ({
60
+ id: t,
61
+ isUser: i,
62
+ items: e.map((d) => ({
63
63
  id: d.id || P(),
64
- isUser: o,
65
- groupId: e,
64
+ isUser: i,
65
+ groupId: t,
66
66
  message: d.message || []
67
67
  })),
68
68
  meta: n
69
69
  };
70
- }, wt = (o, {
71
- submit: t,
70
+ }, wt = (i, {
71
+ submit: e,
72
72
  errors: n,
73
- meta: e
73
+ meta: t
74
74
  }) => {
75
75
  var a;
76
- if ((a = o == null ? void 0 : o.body) != null && a.form) {
77
- const { body: d } = o, g = new Y(d.form);
78
- return d.form.layout.submit || g.createComponent(Z(t, "submit")), n && g.setValidationErrors(n), e && g.setMeta(e), {
76
+ if ((a = i == null ? void 0 : i.body) != null && a.form) {
77
+ const { body: d } = i, u = new Y(d.form);
78
+ return d.form.layout.submit || u.createComponent(Z(e, "submit")), n && u.setValidationErrors(n), t && u.setMeta(t), {
79
79
  ...d,
80
- form: g.get()
80
+ form: u.get()
81
81
  };
82
82
  }
83
- return (o == null ? void 0 : o.body) || {};
84
- }, nt = async (o, t, n) => {
85
- (await (await o.getAsync("dataClient")).getClient()).parameters.set(t, n);
86
- }, T = ({
87
- messageId: o,
88
- message: t,
83
+ return (i == null ? void 0 : i.body) || {};
84
+ }, nt = async (i, e, n) => {
85
+ (await (await i.getAsync("dataClient")).getClient()).parameters.set(e, n);
86
+ }, M = ({
87
+ messageId: i,
88
+ message: e,
89
89
  group: n
90
90
  }) => ({
91
- id: o,
92
- message: t,
91
+ id: i,
92
+ message: e,
93
93
  groupId: n.id,
94
94
  isUser: n.isUser
95
- }), ot = async (o, t, n) => {
96
- const e = async (i, h, f = [], x) => {
97
- var G, $;
95
+ }), it = async (i, e, n) => {
96
+ const t = async (o, h, f = [], E) => {
97
+ var A, $;
98
98
  const m = P();
99
- switch (i.type !== "List" && i.tags.includes("guide") && (($ = (G = i.content.hints) == null ? void 0 : G[0]) != null && $.id) && await nt(
100
- o,
99
+ switch (o.type !== "List" && o.tags.includes("guide") && (($ = (A = o.content.hints) == null ? void 0 : A[0]) != null && $.id) && await nt(
100
+ i,
101
101
  "LastGuideId",
102
- i.content.hints[0].id
103
- ), i.type) {
102
+ o.content.hints[0].id
103
+ ), o.type) {
104
104
  case "Text": {
105
105
  const S = [];
106
106
  if (S.push(
107
- T({
107
+ M({
108
108
  messageId: m,
109
109
  message: [
110
- U.HTML,
111
- { body: i.content.html }
110
+ B.HTML,
111
+ { body: o.content.html }
112
112
  ],
113
113
  group: h
114
114
  })
115
115
  ), f.length) {
116
116
  f.find(
117
- (y) => {
117
+ (v) => {
118
118
  var k;
119
- return y.type === "List" && ((k = y.localState) == null ? void 0 : k.$type) === "Humany.Matching.Bots.Conversations.States.ContactState, Humany.Matching";
119
+ return v.type === "List" && ((k = v.localState) == null ? void 0 : k.$type) === "Humany.Matching.Bots.Conversations.States.ContactState, Humany.Matching";
120
120
  }
121
121
  );
122
122
  const I = f.find(
123
- (y) => y.tags.includes("contact") && y.type === "Contact"
123
+ (v) => v.tags.includes("contact") && v.type === "Contact"
124
124
  );
125
125
  I && S.push(
126
- T({
126
+ M({
127
127
  messageId: m,
128
128
  message: [
129
- A.ContactMethod,
129
+ T.ContactMethod,
130
130
  {
131
131
  contactMethodId: I.content.id,
132
132
  groupId: h.id,
@@ -141,14 +141,14 @@ const et = ({
141
141
  }
142
142
  case "Contact":
143
143
  return [
144
- T({
144
+ M({
145
145
  messageId: m,
146
146
  message: [
147
- A.ContactMethod,
147
+ T.ContactMethod,
148
148
  {
149
- contactMethodId: i.content.id,
149
+ contactMethodId: o.content.id,
150
150
  groupId: h.id,
151
- guideId: i.content.guideId
151
+ guideId: o.content.guideId
152
152
  }
153
153
  ],
154
154
  group: h
@@ -156,12 +156,12 @@ const et = ({
156
156
  ];
157
157
  case "Error":
158
158
  return [
159
- T({
159
+ M({
160
160
  messageId: m,
161
161
  message: [
162
- U.HTML,
162
+ B.HTML,
163
163
  {
164
- body: i.content.message || "Something went wrong."
164
+ body: o.content.message || "Something went wrong."
165
165
  }
166
166
  ],
167
167
  group: h
@@ -173,50 +173,50 @@ const et = ({
173
173
  }, a = /* @__PURE__ */ new Map([
174
174
  ["Text", 1],
175
175
  ["Contact", 2]
176
- ]), d = [], g = t.sort((i, h) => {
177
- const x = a.get(i.type) || 20, m = a.get(h.type) || 20;
178
- return x - m;
179
- }).filter((i) => !i.relation).reduce((i, h) => i.concat(h), []), E = (i) => typeof i.actions.selector < "u";
180
- for (const i of g) {
181
- const h = t.filter(
182
- (m) => m.relation === i.id && !E(m)
176
+ ]), d = [], u = e.sort((o, h) => {
177
+ const E = a.get(o.type) || 20, m = a.get(h.type) || 20;
178
+ return E - m;
179
+ }).filter((o) => !o.relation).reduce((o, h) => o.concat(h), []), x = (o) => typeof o.actions.selector < "u";
180
+ for (const o of u) {
181
+ const h = e.filter(
182
+ (m) => m.relation === o.id && !x(m)
183
183
  ), f = et({ isUser: !1 });
184
- (await e(i, f, h)).forEach((m) => {
184
+ (await t(o, f, h)).forEach((m) => {
185
185
  f.items.push(m);
186
186
  }), f.items.length && d.push(f);
187
187
  }
188
188
  return d;
189
189
  };
190
- class it {
191
- constructor(t, n, e, a) {
192
- v(this, "globalState");
193
- v(this, "localState");
194
- v(this, "clientId");
195
- v(this, "entries");
196
- this.endpoint = t, this.events = n, this.store = e, this.container = a, this.clientId = P(), this.entries = [];
190
+ class ot {
191
+ constructor(e, n, t, a) {
192
+ y(this, "globalState");
193
+ y(this, "localState");
194
+ y(this, "clientId");
195
+ y(this, "entries");
196
+ this.endpoint = e, this.events = n, this.store = t, this.container = a, this.clientId = P(), this.entries = [];
197
197
  }
198
- async fetchGuide(t) {
198
+ async fetchGuide(e) {
199
199
  const n = {
200
- command: { guide: { id: t } },
200
+ command: { guide: { id: e } },
201
201
  globalState: this.globalState,
202
202
  clientId: this.clientId
203
203
  };
204
204
  return await this.postEnvelope(n);
205
205
  }
206
- async postEnvelope(t, n) {
206
+ async postEnvelope(e, n) {
207
207
  try {
208
- const e = await fetch(
208
+ const t = await fetch(
209
209
  this.endpoint,
210
- this.getHttpOptions(t)
210
+ this.getHttpOptions(e)
211
211
  );
212
- if (!e.ok)
213
- throw e;
214
- const a = await e.json();
212
+ if (!t.ok)
213
+ throw t;
214
+ const a = await t.json();
215
215
  return this.handleResponse(a, n);
216
- } catch (e) {
216
+ } catch (t) {
217
217
  process.env.NODE_ENV !== "production" && console.warn("Something went wrong when posting the envelope.");
218
218
  let a = "Something went wrong";
219
- return (e.message === "Failed to fetch" || e.message === "NetworkError when attempting to fetch resource.") && (a = "Lost connection... Please try again."), this.handleResponse({
219
+ return (t.message === "Failed to fetch" || t.message === "NetworkError when attempting to fetch resource.") && (a = "Lost connection... Please try again."), this.handleResponse({
220
220
  entries: [
221
221
  {
222
222
  id: P(),
@@ -232,18 +232,18 @@ class it {
232
232
  });
233
233
  }
234
234
  }
235
- async handleResponse(t, n) {
236
- this.entries = this.entries.concat(t.entries), this.store.write(this.entries, "entries");
237
- const e = t.entries.find((d) => d.type === "Widget");
238
- return e && this.events.dispatch("provider:widget-entry", e.content), t.globalState && (this.globalState = t.globalState, this.store.write(t.globalState, "globalState")), this.localState = t.entries.reduce(
239
- (d, g) => g.localState ? g.localState : d,
235
+ async handleResponse(e, n) {
236
+ this.entries = this.entries.concat(e.entries), this.store.write(this.entries, "entries");
237
+ const t = e.entries.find((d) => d.type === "Widget");
238
+ return t && this.events.dispatch("provider:widget-entry", t.content), e.globalState && (this.globalState = e.globalState, this.store.write(e.globalState, "globalState")), this.localState = e.entries.reduce(
239
+ (d, u) => u.localState ? u.localState : d,
240
240
  void 0
241
- ), this.store.write(this.localState, "localState"), await ot(
241
+ ), this.store.write(this.localState, "localState"), await it(
242
242
  this.container,
243
- t.entries
243
+ e.entries
244
244
  );
245
245
  }
246
- getHttpOptions(t) {
246
+ getHttpOptions(e) {
247
247
  const n = {
248
248
  method: "POST",
249
249
  headers: {
@@ -251,8 +251,8 @@ class it {
251
251
  "Content-Type": "application/json"
252
252
  }
253
253
  };
254
- return t.funnel = this.container.get("$widget").name, t.localState = t.localState || this.localState, Object.assign({}, n, {
255
- body: JSON.stringify(t),
254
+ return e.funnel = this.container.get("$widget").name, e.localState = e.localState || this.localState, Object.assign({}, n, {
255
+ body: JSON.stringify(e),
256
256
  credentials: "same-origin"
257
257
  });
258
258
  }
@@ -285,40 +285,40 @@ const st = "@telia-ace/conversational-hub-bot-provider", rt = "0.0.16", at = "./
285
285
  exports: lt,
286
286
  dependencies: dt,
287
287
  peerDependencies: ut
288
- }, bt = async (o) => {
289
- var M, j, H, L, _;
290
- const t = "chub-plugin", n = o.get("$widget"), e = (_ = (L = (H = (j = (M = n == null ? void 0 : n.container) == null ? void 0 : M.get("$settings")) == null ? void 0 : j.components) == null ? void 0 : H.conversation) == null ? void 0 : L.properties) == null ? void 0 : _.conversationalHubPluginSettings;
291
- let a, d, g, E = (e == null ? void 0 : e.connectionAttempts) ?? 5, i, h, f;
288
+ }, bt = async (i) => {
289
+ var G, j, H, L, _;
290
+ const e = "chub-plugin", n = i.get("$widget"), t = (_ = (L = (H = (j = (G = n == null ? void 0 : n.container) == null ? void 0 : G.get("$settings")) == null ? void 0 : j.components) == null ? void 0 : H.conversation) == null ? void 0 : L.properties) == null ? void 0 : _.conversationalHubPluginSettings;
291
+ let a, d, u, x = (t == null ? void 0 : t.connectionAttempts) ?? 5, o, h, f;
292
292
  O.info((C == null ? void 0 : C.name) + " version: " + (C == null ? void 0 : C.version)), Q(
293
- o,
294
- A.ContactMethod,
295
- import("./contact-method-d1bf5b87.mjs")
293
+ i,
294
+ T.ContactMethod,
295
+ import("./contact-method-65f71f64.mjs")
296
296
  );
297
- const x = await R(
298
- o,
297
+ const E = await R(
298
+ i,
299
299
  "conversational-hub-session",
300
300
  D.Necessary
301
301
  ), m = (r, c) => {
302
302
  const { knowledgeBotEndpoint: l } = c.properties();
303
303
  if (l)
304
304
  return `${l}/conversations`;
305
- const { data: u } = r.get("$settings");
306
- if (!u || !u.projection)
305
+ const { data: g } = r.get("$settings");
306
+ if (!g || !g.projection)
307
307
  throw new Error("Missing Knowledge Bot endpoint");
308
- return `${u.projection}/conversations`;
308
+ return `${g.projection}/conversations`;
309
309
  };
310
310
  (await X.getInstance(
311
- o
312
- )).registerProvider(t, (r, c) => {
313
- a = r, d = a.controller, g = a.createAgent({
314
- name: e == null ? void 0 : e.botName,
315
- avatar: e == null ? void 0 : e.avatar
316
- }), f = m(o, c);
317
- const { events: l } = o.get("$widget"), u = new tt(o);
318
- h = new it(f, l, u, o), $();
319
- const p = () => d.providers.includes(t);
311
+ i
312
+ )).registerProvider(e, (r, c) => {
313
+ a = r, d = a.controller, u = a.createAgent({
314
+ name: t == null ? void 0 : t.botName,
315
+ avatar: t == null ? void 0 : t.avatar
316
+ }), f = m(i, c);
317
+ const { events: l } = i.get("$widget"), g = new tt(i);
318
+ h = new ot(f, l, g, i), $();
319
+ const p = () => d.providers.includes(e);
320
320
  window.controller = d, c.actions.create("submit", (s) => {
321
- const { events: b } = o.get("$widget");
321
+ const { events: b } = i.get("$widget");
322
322
  b.dispatch("conversational-hub-provider:form-submitted", s);
323
323
  }), c.actions.watch("conversation.action", (s, b) => (p() && S(s), b(s))), c.actions.watch("conversation.user-submit", (s, b) => {
324
324
  if (!p())
@@ -330,31 +330,35 @@ const st = "@telia-ace/conversational-hub-bot-provider", rt = "0.0.16", at = "./
330
330
  });
331
331
  async function $(r = !0) {
332
332
  const c = await J(
333
- o,
333
+ i,
334
334
  "conversational-hub-session"
335
335
  );
336
- c != null && c.sessionId && r ? i = c == null ? void 0 : c.sessionId : await y(
337
- e.baseUrl + "/initialize",
338
- `{"extension": "${e.extension}"}`,
336
+ c != null && c.sessionId && r ? o = c == null ? void 0 : c.sessionId : t != null && t.welcomeMessage ? u.print(t == null ? void 0 : t.welcomeMessage) : await v(
337
+ t.baseUrl + "/initialize",
338
+ `{"extension": "${t.extension}"}`,
339
339
  r
340
340
  );
341
341
  }
342
342
  async function S(r) {
343
- await y(
344
- `${e.baseUrl}/input/${i}`,
345
- `{"type":"button_click","language":"${e.language}","content":{"button_text":"${r.label}","value":"${r.actionKey}"}}`
343
+ await v(
344
+ `${t.baseUrl}/input/${o}`,
345
+ `{"type":"button_click","language":"${t.language}","content":{"button_text":"${r.label}","value":"${r.actionKey}"}}`
346
346
  );
347
347
  }
348
348
  async function I(r) {
349
349
  const c = { text: r };
350
- await y(
351
- `${e.baseUrl}/input/${i}`,
352
- `{"type":"text","language":"${e.language}","content":${JSON.stringify(c)}}`
350
+ o || await v(
351
+ t.baseUrl + "/initialize",
352
+ `{"extension": "${t.extension}"}`,
353
+ !1
354
+ ), await v(
355
+ `${t.baseUrl}/input/${o}`,
356
+ `{"type":"text","language":"${t.language}","content":${JSON.stringify(c)}}`
353
357
  );
354
358
  }
355
- async function y(r, c, l = !0) {
356
- var b, K, V, B;
357
- const u = a.loading();
359
+ async function v(r, c, l = !0) {
360
+ var b, K, V, U;
361
+ const g = a.loading();
358
362
  let p, s;
359
363
  try {
360
364
  p = await fetch(r, {
@@ -362,50 +366,50 @@ const st = "@telia-ace/conversational-hub-bot-provider", rt = "0.0.16", at = "./
362
366
  body: c
363
367
  }), s = await (p == null ? void 0 : p.json());
364
368
  } catch (N) {
365
- N instanceof SyntaxError ? O.error("Incorrect JSON format.", N) : O.error("Network error: check connection or baseUrl.", N), u(), g.print(e.errorMessage || "An error occurred");
369
+ N instanceof SyntaxError ? O.error("Incorrect JSON format.", N) : O.error("Network error: check connection or baseUrl.", N), g(), u.print(t.errorMessage || "An error occurred");
366
370
  return;
367
371
  }
368
372
  if (!(p != null && p.ok)) {
369
- if (O.error(`HTTP ${p == null ? void 0 : p.status}.`, JSON.stringify(s)), u(), !!((b = s == null ? void 0 : s.errors) != null && b.filter(
373
+ if (O.error(`HTTP ${p == null ? void 0 : p.status}.`, JSON.stringify(s)), g(), !!((b = s == null ? void 0 : s.errors) != null && b.filter(
370
374
  (w) => w.code === "1003"
371
- ).length) && E > 0) {
372
- E--, await new Promise((W) => setTimeout(W, 500)), await $(!1);
375
+ ).length) && x > 0) {
376
+ x--, await new Promise((W) => setTimeout(W, 500)), await $(!1);
373
377
  const w = JSON.parse(c);
374
- (K = w == null ? void 0 : w.content) != null && K.text ? await I(w.content.text) : (V = w == null ? void 0 : w.content) != null && V.action && await S((B = w == null ? void 0 : w.content) == null ? void 0 : B.action);
378
+ (K = w == null ? void 0 : w.content) != null && K.text ? await I(w.content.text) : (V = w == null ? void 0 : w.content) != null && V.action && await S((U = w == null ? void 0 : w.content) == null ? void 0 : U.action);
375
379
  } else
376
- g.print(e.errorMessage || "An error occurred");
380
+ u.print(t.errorMessage || "An error occurred");
377
381
  return;
378
382
  }
379
- u(), E = (e == null ? void 0 : e.connectionAttempts) ?? 5, s != null && s.action_payload && k(s.action_payload), i = s == null ? void 0 : s.session_id, x({ sessionId: i }), l && z(s);
383
+ g(), x = (t == null ? void 0 : t.connectionAttempts) ?? 5, s != null && s.action_payload && k(s.action_payload), o = s == null ? void 0 : s.session_id, E({ sessionId: o }), l && z(s);
380
384
  }
381
385
  async function k(r) {
382
386
  var p;
383
- const c = (p = r == null ? void 0 : r.transfer_parameters) == null ? void 0 : p.contactGuide, l = a.loading(), u = await h.fetchGuide(parseInt(c));
384
- if (l(), u) {
385
- const s = u.concat(u);
387
+ const c = (p = r == null ? void 0 : r.transfer_parameters) == null ? void 0 : p.contactGuide, l = a.loading(), g = await h.fetchGuide(parseInt(c));
388
+ if (l(), g) {
389
+ const s = g.concat(g);
386
390
  if (s.length) {
387
391
  const b = s[0].items.map((K) => K.message);
388
- g.print(b);
392
+ u.print(b);
389
393
  }
390
394
  }
391
395
  }
392
396
  function z(r) {
393
397
  var c;
394
398
  r == null || r.agent_response.forEach((l) => {
395
- g.print(l.payload.text);
396
- }), (c = r == null ? void 0 : r.prompt) != null && c.items && g.print([
399
+ u.print(l.payload.text);
400
+ }), (c = r == null ? void 0 : r.prompt) != null && c.items && u.print([
397
401
  "button-list",
398
402
  {
399
403
  actions: r.prompt.items.map((l) => {
400
- let u;
401
- return l.type === "button" && (u = { actionKey: l.value, label: l.text }), l.type === "link" && (u = {
404
+ let g;
405
+ return l.type === "button" && (g = { actionKey: l.value, label: l.text }), l.type === "link" && (g = {
402
406
  actionKey: l.value,
403
407
  label: l.text,
404
408
  data: {
405
409
  href: l.url,
406
- target: (e == null ? void 0 : e.linkTarget) ?? "_blank"
410
+ target: (t == null ? void 0 : t.linkTarget) ?? "_blank"
407
411
  }
408
- }), u;
412
+ }), g;
409
413
  })
410
414
  }
411
415
  ]);
package/index.js CHANGED
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./index-21624a6d.js");require("@telia-ace/widget-conversation");require("@telia-ace/widget-services");require("@telia-ace/widget-utilities");require("@telia-ace/widget-forms");exports.ConversationalHubPlugin=e.ConversationalHubPlugin;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./index-02b60805.js");require("@telia-ace/widget-conversation");require("@telia-ace/widget-services");require("@telia-ace/widget-utilities");require("@telia-ace/widget-forms");exports.ConversationalHubPlugin=e.ConversationalHubPlugin;
package/index.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { C as a } from "./index-25ab09c8.mjs";
1
+ import { C as a } from "./index-735998e7.mjs";
2
2
  import "@telia-ace/widget-conversation";
3
3
  import "@telia-ace/widget-services";
4
4
  import "@telia-ace/widget-utilities";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@telia-ace/conversational-hub-bot-provider",
3
- "version": "1.3.9",
3
+ "version": "1.3.10",
4
4
  "main": "./index.js",
5
5
  "types": "./index.d.ts",
6
6
  "exports": {
@@ -10,16 +10,16 @@
10
10
  }
11
11
  },
12
12
  "dependencies": {
13
- "@telia-ace/widget-conversation": "^1.3.9",
13
+ "@telia-ace/widget-conversation": "^1.3.10",
14
14
  "@webprovisions/platform": "^1.1.4",
15
- "@telia-ace/knowledge-widget-core": "^1.3.9",
16
- "@telia-ace/widget-utilities": "^1.3.9",
17
- "@telia-ace/widget-services": "^1.3.9",
18
- "@telia-ace/widget-core": "^1.3.9",
19
- "@telia-ace/knowledge-data-client": "^1.3.9",
20
- "@telia-ace/knowledge-widget-adapters": "^1.3.9",
21
- "@telia-ace/knowledge-widget-ui": "^1.3.9",
22
- "@telia-ace/widget-forms": "^1.3.9"
15
+ "@telia-ace/knowledge-widget-core": "^1.3.10",
16
+ "@telia-ace/widget-utilities": "^1.3.10",
17
+ "@telia-ace/widget-services": "^1.3.10",
18
+ "@telia-ace/widget-core": "^1.3.10",
19
+ "@telia-ace/knowledge-data-client": "^1.3.10",
20
+ "@telia-ace/knowledge-widget-adapters": "^1.3.10",
21
+ "@telia-ace/knowledge-widget-ui": "^1.3.10",
22
+ "@telia-ace/widget-forms": "^1.3.10"
23
23
  },
24
24
  "peerDependencies": {
25
25
  "@emotion/react": "11.11.1",
package/index-21624a6d.js DELETED
@@ -1 +0,0 @@
1
- "use strict";var D=Object.defineProperty;var F=(i,t,n)=>t in i?D(i,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):i[t]=n;var b=(i,t,n)=>(F(i,typeof t!="symbol"?t+"":t,n),n);const T=require("@telia-ace/widget-conversation"),x=require("@telia-ace/widget-services"),S=require("@telia-ace/widget-utilities"),B=require("@telia-ace/widget-forms");class W{constructor(t){b(this,"enabled",!0);b(this,"botProviderGlobalStateKey","bot-provider-global-state");b(this,"botProviderLocalStateKey","bot-provider-local-state");b(this,"botProviderEntriesKey","bot-provider-entries");b(this,"botProviderMetaStateKey","bot-provider-conversation-meta");this.container=t}getKey(t){let n;switch(t){case"localState":n=this.botProviderLocalStateKey;break;case"globalState":n=this.botProviderGlobalStateKey;break;case"entries":n=this.botProviderEntriesKey;break;case"meta":n=this.botProviderMetaStateKey;break}return n}async read(t){const n=this.getKey(t);if(!(!this.enabled||!n))return x.readStorage(this.container,n)}async write(t,n){const e=this.getKey(n);if(!this.enabled||!e)return;(await x.createStorageWriter(this.container,e,x.StorageCategory.Necessary))(t)}}var M=(i=>(i.ContactMethod="ace-conversational-hub-contact-method",i))(M||{});const z=({isUser:i,items:t=[],meta:n={}})=>{const e=S.uuid();return{id:e,isUser:i,items:t.map(d=>({id:d.id||S.uuid(),isUser:i,groupId:e,message:d.message||[]})),meta:n}},Q=(i,{submit:t,errors:n,meta:e})=>{var a;if((a=i==null?void 0:i.body)!=null&&a.form){const{body:d}=i,g=new B.FormBuilder(d.form);return d.form.layout.submit||g.createComponent(B.submitButton(t,"submit")),n&&g.setValidationErrors(n),e&&g.setMeta(e),{...d,form:g.get()}}return(i==null?void 0:i.body)||{}},X=async(i,t,n)=>{(await(await i.getAsync("dataClient")).getClient()).parameters.set(t,n)},O=({messageId:i,message:t,group:n})=>({id:i,message:t,groupId:n.id,isUser:n.isUser}),Y=async(i,t,n)=>{const e=async(o,h,f=[],$)=>{var A,k;const m=S.uuid();switch(o.type!=="List"&&o.tags.includes("guide")&&((k=(A=o.content.hints)==null?void 0:A[0])!=null&&k.id)&&await X(i,"LastGuideId",o.content.hints[0].id),o.type){case"Text":{const C=[];if(C.push(O({messageId:m,message:[T.ConversationMessageListItemType.HTML,{body:o.content.html}],group:h})),f.length){f.find(y=>{var K;return y.type==="List"&&((K=y.localState)==null?void 0:K.$type)==="Humany.Matching.Bots.Conversations.States.ContactState, Humany.Matching"});const I=f.find(y=>y.tags.includes("contact")&&y.type==="Contact");I&&C.push(O({messageId:m,message:[M.ContactMethod,{contactMethodId:I.content.id,groupId:h.id,guideId:I.content.guideId}],group:h}))}return C}case"Contact":return[O({messageId:m,message:[M.ContactMethod,{contactMethodId:o.content.id,groupId:h.id,guideId:o.content.guideId}],group:h})];case"Error":return[O({messageId:m,message:[T.ConversationMessageListItemType.HTML,{body:o.content.message||"Something went wrong."}],group:h})];default:return[]}},a=new Map([["Text",1],["Contact",2]]),d=[],g=t.sort((o,h)=>{const $=a.get(o.type)||20,m=a.get(h.type)||20;return $-m}).filter(o=>!o.relation).reduce((o,h)=>o.concat(h),[]),P=o=>typeof o.actions.selector<"u";for(const o of g){const h=t.filter(m=>m.relation===o.id&&!P(m)),f=z({isUser:!1});(await e(o,f,h)).forEach(m=>{f.items.push(m)}),f.items.length&&d.push(f)}return d};class Z{constructor(t,n,e,a){b(this,"globalState");b(this,"localState");b(this,"clientId");b(this,"entries");this.endpoint=t,this.events=n,this.store=e,this.container=a,this.clientId=S.uuid(),this.entries=[]}async fetchGuide(t){const n={command:{guide:{id:t}},globalState:this.globalState,clientId:this.clientId};return await this.postEnvelope(n)}async postEnvelope(t,n){try{const e=await fetch(this.endpoint,this.getHttpOptions(t));if(!e.ok)throw e;const a=await e.json();return this.handleResponse(a,n)}catch(e){process.env.NODE_ENV!=="production"&&console.warn("Something went wrong when posting the envelope.");let a="Something went wrong";return(e.message==="Failed to fetch"||e.message==="NetworkError when attempting to fetch resource.")&&(a="Lost connection... Please try again."),this.handleResponse({entries:[{id:S.uuid(),type:"Error",timestamp:new Date().toISOString(),content:{message:a},actions:{},tags:[]}]})}}async handleResponse(t,n){this.entries=this.entries.concat(t.entries),this.store.write(this.entries,"entries");const e=t.entries.find(d=>d.type==="Widget");return e&&this.events.dispatch("provider:widget-entry",e.content),t.globalState&&(this.globalState=t.globalState,this.store.write(t.globalState,"globalState")),this.localState=t.entries.reduce((d,g)=>g.localState?g.localState:d,void 0),this.store.write(this.localState,"localState"),await Y(this.container,t.entries)}getHttpOptions(t){const n={method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"}};return t.funnel=this.container.get("$widget").name,t.localState=t.localState||this.localState,Object.assign({},n,{body:JSON.stringify(t),credentials:"same-origin"})}}const tt="@telia-ace/conversational-hub-bot-provider",et="0.0.16",nt="./index.js",it="./index.d.ts",ot={".":{import:"./index.mjs",require:"./index.js"}},st={"@telia-ace/widget-conversation":"*","@webprovisions/platform":"^1.1.4","@telia-ace/knowledge-widget-core":"*","@telia-ace/widget-utilities":"*","@telia-ace/widget-services":"*","@telia-ace/widget-core":"*","@telia-ace/knowledge-data-client":"*","@telia-ace/knowledge-widget-adapters":"*","@telia-ace/knowledge-widget-ui":"*","@telia-ace/widget-forms":"*"},rt={"@emotion/react":"11.11.1","@emotion/styled":"11.11.0",react:"18.2.0"},E={name:tt,version:et,main:nt,types:it,exports:ot,dependencies:st,peerDependencies:rt},at=async i=>{var G,H,j,_,V;const t="chub-plugin",n=i.get("$widget"),e=(V=(_=(j=(H=(G=n==null?void 0:n.container)==null?void 0:G.get("$settings"))==null?void 0:H.components)==null?void 0:j.conversation)==null?void 0:_.properties)==null?void 0:V.conversationalHubPluginSettings;let a,d,g,P=(e==null?void 0:e.connectionAttempts)??5,o,h,f;S.Logger.info((E==null?void 0:E.name)+" version: "+(E==null?void 0:E.version)),T.registerCustomMessageComponent(i,M.ContactMethod,Promise.resolve().then(()=>require("./contact-method-800cf649.js")));const $=await x.createStorageWriter(i,"conversational-hub-session",x.StorageCategory.Necessary),m=(r,c)=>{const{knowledgeBotEndpoint:l}=c.properties();if(l)return`${l}/conversations`;const{data:u}=r.get("$settings");if(!u||!u.projection)throw new Error("Missing Knowledge Bot endpoint");return`${u.projection}/conversations`};(await T.ConversationPlatform.getInstance(i)).registerProvider(t,(r,c)=>{a=r,d=a.controller,g=a.createAgent({name:e==null?void 0:e.botName,avatar:e==null?void 0:e.avatar}),f=m(i,c);const{events:l}=i.get("$widget"),u=new W(i);h=new Z(f,l,u,i),k();const p=()=>d.providers.includes(t);window.controller=d,c.actions.create("submit",s=>{const{events:v}=i.get("$widget");v.dispatch("conversational-hub-provider:form-submitted",s)}),c.actions.watch("conversation.action",(s,v)=>(p()&&C(s),v(s))),c.actions.watch("conversation.user-submit",(s,v)=>{if(!p())return v(s);I(s.text),a.user.print(s.text.replace(/</g,"&lt;").replace(/>/g,"&gt;"))})});async function k(r=!0){const c=await x.readStorage(i,"conversational-hub-session");c!=null&&c.sessionId&&r?o=c==null?void 0:c.sessionId:await y(e.baseUrl+"/initialize",`{"extension": "${e.extension}"}`,r)}async function C(r){await y(`${e.baseUrl}/input/${o}`,`{"type":"button_click","language":"${e.language}","content":{"button_text":"${r.label}","value":"${r.actionKey}"}}`)}async function I(r){const c={text:r};await y(`${e.baseUrl}/input/${o}`,`{"type":"text","language":"${e.language}","content":${JSON.stringify(c)}}`)}async function y(r,c,l=!0){var v,L,U,q;const u=a.loading();let p,s;try{p=await fetch(r,{method:"POST",body:c}),s=await(p==null?void 0:p.json())}catch(N){N instanceof SyntaxError?S.Logger.error("Incorrect JSON format.",N):S.Logger.error("Network error: check connection or baseUrl.",N),u(),g.print(e.errorMessage||"An error occurred");return}if(!(p!=null&&p.ok)){if(S.Logger.error(`HTTP ${p==null?void 0:p.status}.`,JSON.stringify(s)),u(),!!((v=s==null?void 0:s.errors)!=null&&v.filter(w=>w.code==="1003").length)&&P>0){P--,await new Promise(R=>setTimeout(R,500)),await k(!1);const w=JSON.parse(c);(L=w==null?void 0:w.content)!=null&&L.text?await I(w.content.text):(U=w==null?void 0:w.content)!=null&&U.action&&await C((q=w==null?void 0:w.content)==null?void 0:q.action)}else g.print(e.errorMessage||"An error occurred");return}u(),P=(e==null?void 0:e.connectionAttempts)??5,s!=null&&s.action_payload&&K(s.action_payload),o=s==null?void 0:s.session_id,$({sessionId:o}),l&&J(s)}async function K(r){var p;const c=(p=r==null?void 0:r.transfer_parameters)==null?void 0:p.contactGuide,l=a.loading(),u=await h.fetchGuide(parseInt(c));if(l(),u){const s=u.concat(u);if(s.length){const v=s[0].items.map(L=>L.message);g.print(v)}}}function J(r){var c;r==null||r.agent_response.forEach(l=>{g.print(l.payload.text)}),(c=r==null?void 0:r.prompt)!=null&&c.items&&g.print(["button-list",{actions:r.prompt.items.map(l=>{let u;return l.type==="button"&&(u={actionKey:l.value,label:l.text}),l.type==="link"&&(u={actionKey:l.value,label:l.text,data:{href:l.url,target:(e==null?void 0:e.linkTarget)??"_blank"}}),u})}])}};exports.ConversationalHubPlugin=at;exports.updateForm=Q;