@telia-ace/conversational-hub-bot-provider 1.3.14 → 1.3.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.
@@ -0,0 +1,146 @@
1
+ import { jsx as k } from "react/jsx-runtime";
2
+ import z from "@emotion/styled";
3
+ import { DataClient as A, DataType as R } from "@telia-ace/knowledge-data-client";
4
+ import { ContactMethod as _ } from "@telia-ace/knowledge-widget-adapters";
5
+ import { useContainer as j, useDispatch as G, useConversation as I } from "@telia-ace/knowledge-widget-ui";
6
+ import { FormBuilder as V } from "@telia-ace/widget-forms";
7
+ import { appendClassNames as q } from "@telia-ace/widget-utilities";
8
+ import { useState as H, useRef as J, useEffect as B, useCallback as K } from "react";
9
+ import { u as D } from "./index-17638994.mjs";
10
+ import "@telia-ace/widget-conversation";
11
+ import "@telia-ace/widget-services";
12
+ import "@webprovisions/platform";
13
+ const nt = ({
14
+ contactMethodId: a,
15
+ guideId: e,
16
+ groupId: u,
17
+ className: E
18
+ }) => {
19
+ var C, v, g, w, M, T, S;
20
+ const [t, n] = H(), d = j(), F = G(), f = J(!0), b = I();
21
+ B(() => {
22
+ const { events: s } = d.get("$widget"), c = s.subscribe(
23
+ "conversational-hub-provider:form-submitted",
24
+ async (y, r) => {
25
+ var $;
26
+ if ((($ = r.form.meta) == null ? void 0 : $.groupId) !== u || r.id !== (t == null ? void 0 : t.id))
27
+ return;
28
+ b && (r.form.meta || (r.form.meta = {}), r.form.meta.conversation = b);
29
+ const l = await d.getAsync(
30
+ "contactMethods"
31
+ ), o = {
32
+ ...t,
33
+ body: {
34
+ ...t.body,
35
+ form: r.form
36
+ }
37
+ }, { errors: m, valid: p, errorTypes: O } = await l.validate(
38
+ o
39
+ );
40
+ if (!p) {
41
+ const x = new V(t.body.form);
42
+ n(void 0), x.setValidationErrors(m), o.body = {
43
+ ...o.body,
44
+ form: x.get()
45
+ }, n({ ...o });
46
+ return;
47
+ }
48
+ const N = await l.submit(o);
49
+ o.confirmation = N, n(o);
50
+ }
51
+ ), i = s.subscribe(
52
+ "bot-provider:evaluate",
53
+ async (y, r) => {
54
+ if (r.id !== a)
55
+ return;
56
+ const o = await (await d.getAsync(
57
+ "contactMethods"
58
+ )).evaluate(t);
59
+ let m = {
60
+ ...t,
61
+ body: {
62
+ ...t.body,
63
+ form: o
64
+ }
65
+ };
66
+ const p = D(m, {
67
+ submit: "Submit",
68
+ errors: {},
69
+ meta: { groupId: u }
70
+ });
71
+ m = {
72
+ ...m,
73
+ body: p
74
+ }, n(m);
75
+ }
76
+ );
77
+ return () => {
78
+ c(), i();
79
+ };
80
+ }, [d, t, n, b]);
81
+ const h = K(
82
+ async (s) => {
83
+ const i = await (await A.getInstance(d)).fetch(
84
+ R.ContactMethod,
85
+ {
86
+ contactMethodId: s,
87
+ guideId: e
88
+ },
89
+ { noCache: !0, isBot: !0 }
90
+ ), y = D(i, {
91
+ submit: "Submit",
92
+ errors: {},
93
+ meta: { groupId: u }
94
+ });
95
+ if (i.body = y, i.body.guideId = e, !f.current)
96
+ return null;
97
+ n(i);
98
+ },
99
+ // eslint-disable-next-line react-hooks/exhaustive-deps
100
+ [f]
101
+ );
102
+ if (B(() => (h(a), () => {
103
+ f.current = !1;
104
+ }), [a, h]), !t)
105
+ return null;
106
+ if (t.clientName === "ace.callback" && ((C = t.body) != null && C.entrance) && ((w = (g = (v = t.body) == null ? void 0 : v.form) == null ? void 0 : g.layout["group[0]"]) != null && w.startTime)) {
107
+ const { startTime: s } = t.body.form.layout["group[0]"], c = {
108
+ ...s,
109
+ "ui:bot": !0,
110
+ "ui:entrance": t.body.entrance
111
+ };
112
+ t.body.form.layout["group[0]"].startTime = c;
113
+ }
114
+ return /* @__PURE__ */ k(
115
+ L,
116
+ {
117
+ ...t,
118
+ body: {
119
+ ...t.body,
120
+ form: t.body.form ? {
121
+ ...t.body.form,
122
+ data: (M = t.body.form) == null ? void 0 : M.data,
123
+ layout: { ...t.body.form.layout },
124
+ meta: (T = t.body.form) == null ? void 0 : T.meta,
125
+ schema: (S = t.body.form) == null ? void 0 : S.schema
126
+ } : void 0,
127
+ guideId: t.body.guideId
128
+ },
129
+ inline: !0,
130
+ expanded: !0,
131
+ dispatch: F,
132
+ className: q("humany-bot-contact-method", E)
133
+ }
134
+ );
135
+ }, L = z(_)`
136
+ padding: ${(a) => {
137
+ var e;
138
+ return (e = a.theme.sizes) == null ? void 0 : e.normal;
139
+ }} ${(a) => {
140
+ var e;
141
+ return (e = a.theme.sizes) == null ? void 0 : e.medium;
142
+ }};
143
+ `;
144
+ export {
145
+ nt as default
146
+ };
@@ -0,0 +1,3 @@
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const N=require("react/jsx-runtime"),R=require("@emotion/styled"),D=require("@telia-ace/knowledge-data-client"),$=require("@telia-ace/knowledge-widget-adapters"),h=require("@telia-ace/knowledge-widget-ui"),z=require("@telia-ace/widget-forms"),U=require("@telia-ace/widget-utilities"),c=require("react"),E=require("./index-8b5af599.js");require("@telia-ace/widget-conversation");require("@telia-ace/widget-services");require("@webprovisions/platform");const W=({contactMethodId:n,guideId:o,groupId:b,className:j})=>{var v,w,q,M,S,T,k;const[e,a]=c.useState(),u=h.useContainer(),A=h.useDispatch(),l=c.useRef(!0),f=h.useConversation();c.useEffect(()=>{const{events:s}=u.get("$widget"),m=s.subscribe("conversational-hub-provider:form-submitted",async(y,r)=>{var F;if(((F=r.form.meta)==null?void 0:F.groupId)!==b||r.id!==(e==null?void 0:e.id))return;f&&(r.form.meta||(r.form.meta={}),r.form.meta.conversation=f);const p=await u.getAsync("contactMethods"),t={...e,body:{...e.body,form:r.form}},{errors:d,valid:g,errorTypes:G}=await p.validate(t);if(!g){const x=new z.FormBuilder(e.body.form);a(void 0),x.setValidationErrors(d),t.body={...t.body,form:x.get()},a({...t});return}const B=await p.submit(t);t.confirmation=B,a(t)}),i=s.subscribe("bot-provider:evaluate",async(y,r)=>{if(r.id!==n)return;const t=await(await u.getAsync("contactMethods")).evaluate(e);let d={...e,body:{...e.body,form:t}};const g=E.updateForm(d,{submit:"Submit",errors:{},meta:{groupId:b}});d={...d,body:g},a(d)});return()=>{m(),i()}},[u,e,a,f]);const C=c.useCallback(async s=>{const i=await(await D.DataClient.getInstance(u)).fetch(D.DataType.ContactMethod,{contactMethodId:s,guideId:o},{noCache:!0,isBot:!0}),y=E.updateForm(i,{submit:"Submit",errors:{},meta:{groupId:b}});if(i.body=y,i.body.guideId=o,!l.current)return null;a(i)},[l]);if(c.useEffect(()=>(C(n),()=>{l.current=!1}),[n,C]),!e)return null;if(e.clientName==="ace.callback"&&((v=e.body)!=null&&v.entrance)&&((M=(q=(w=e.body)==null?void 0:w.form)==null?void 0:q.layout["group[0]"])!=null&&M.startTime)){const{startTime:s}=e.body.form.layout["group[0]"],m={...s,"ui:bot":!0,"ui:entrance":e.body.entrance};e.body.form.layout["group[0]"].startTime=m}return N.jsx(_,{...e,body:{...e.body,form:e.body.form?{...e.body.form,data:(S=e.body.form)==null?void 0:S.data,layout:{...e.body.form.layout},meta:(T=e.body.form)==null?void 0:T.meta,schema:(k=e.body.form)==null?void 0:k.schema}:void 0,guideId:e.body.guideId},inline:!0,expanded:!0,dispatch:A,className:U.appendClassNames("humany-bot-contact-method",j)})},_=R($.ContactMethod)`
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
+ `;exports.default=W;
@@ -3,11 +3,11 @@ import m from "@emotion/styled";
3
3
  import { ContactList as M, ContactMethod as b } from "@telia-ace/knowledge-widget-adapters";
4
4
  import { useDispatch as $, useContainer as k } from "@telia-ace/knowledge-widget-ui";
5
5
  import { useState as f, useEffect as E } from "react";
6
- import S from "./contact-method-e0b87a2a.mjs";
6
+ import S from "./contact-method-d552cfd5.mjs";
7
7
  import "@telia-ace/knowledge-data-client";
8
8
  import "@telia-ace/widget-forms";
9
9
  import "@telia-ace/widget-utilities";
10
- import "./index-06b06645.mjs";
10
+ import "./index-17638994.mjs";
11
11
  import "@telia-ace/widget-conversation";
12
12
  import "@telia-ace/widget-services";
13
13
  import "@webprovisions/platform";
@@ -1,4 +1,4 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const a=require("react/jsx-runtime"),u=require("@emotion/styled"),y=require("@telia-ace/knowledge-widget-adapters"),g=require("@telia-ace/knowledge-widget-ui"),l=require("react"),b=require("./contact-method-f1b2fed9.js");require("@telia-ace/knowledge-data-client");require("@telia-ace/widget-forms");require("@telia-ace/widget-utilities");require("./index-bc0e69f0.js");require("@telia-ace/widget-conversation");require("@telia-ace/widget-services");require("@webprovisions/platform");const k=({actions:e,entryId:t,groupId:x})=>{const q=g.useDispatch(),o=g.useContainer(),[h,C]=l.useState([]),[d,M]=l.useState([]);return l.useEffect(()=>{o.getAsync("contactMethods").then(n=>{if(!n)return;const c=e.map(async i=>{var m;if(!((m=i.data)!=null&&m.clientName))return null;const s=await n.handleAdapters(i.data);return{...s,...i.data,description:i.data.description?i.data.description:s.description,onClick:(p,r)=>{if(typeof s.onClick=="function"&&s.onClick(p,r),!p.defaultPrevented)if(r.inline&&!r.expanded)M([...d,r.id]);else{const{events:f}=o.get("$widget");f.dispatch("conversational-hub-provider:open-contact-method",{entryId:t,contactMethod:r,actionKey:i.actionKey}),f.dispatch("tracking:contact-method-list-item-clicked",r)}}}});Promise.all(c).then(i=>{C(i.filter(s=>!!s))})})},[e,o,t,d]),h.length?a.jsx(j,{className:"humany-bot-contact-list",contactMethods:h,dispatch:q,itemRenderer:(n,c)=>(d.includes(n.id)||n.expanded)&&n.inline||n.clientName==="custom.link"?a.jsx(S,{contactMethodId:n.id,groupId:x,guideId:n.body.guideId}):a.jsx($,{...n,...c})}):null},j=u(y.ContactList)`
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const a=require("react/jsx-runtime"),u=require("@emotion/styled"),y=require("@telia-ace/knowledge-widget-adapters"),g=require("@telia-ace/knowledge-widget-ui"),l=require("react"),b=require("./contact-method-e77006cb.js");require("@telia-ace/knowledge-data-client");require("@telia-ace/widget-forms");require("@telia-ace/widget-utilities");require("./index-8b5af599.js");require("@telia-ace/widget-conversation");require("@telia-ace/widget-services");require("@webprovisions/platform");const k=({actions:e,entryId:t,groupId:x})=>{const q=g.useDispatch(),o=g.useContainer(),[h,C]=l.useState([]),[d,M]=l.useState([]);return l.useEffect(()=>{o.getAsync("contactMethods").then(n=>{if(!n)return;const c=e.map(async i=>{var m;if(!((m=i.data)!=null&&m.clientName))return null;const s=await n.handleAdapters(i.data);return{...s,...i.data,description:i.data.description?i.data.description:s.description,onClick:(p,r)=>{if(typeof s.onClick=="function"&&s.onClick(p,r),!p.defaultPrevented)if(r.inline&&!r.expanded)M([...d,r.id]);else{const{events:f}=o.get("$widget");f.dispatch("conversational-hub-provider:open-contact-method",{entryId:t,contactMethod:r,actionKey:i.actionKey}),f.dispatch("tracking:contact-method-list-item-clicked",r)}}}});Promise.all(c).then(i=>{C(i.filter(s=>!!s))})})},[e,o,t,d]),h.length?a.jsx(j,{className:"humany-bot-contact-list",contactMethods:h,dispatch:q,itemRenderer:(n,c)=>(d.includes(n.id)||n.expanded)&&n.inline||n.clientName==="custom.link"?a.jsx(S,{contactMethodId:n.id,groupId:x,guideId:n.body.guideId}):a.jsx($,{...n,...c})}):null},j=u(y.ContactList)`
2
2
  > ul > li {
3
3
  a {
4
4
  display: flex;
@@ -1,6 +1,6 @@
1
1
  var tt = Object.defineProperty;
2
2
  var et = (i, e, n) => e in i ? tt(i, e, { enumerable: !0, configurable: !0, writable: !0, value: n }) : i[e] = n;
3
- var M = (i, e, n) => (et(i, typeof e != "symbol" ? e + "" : e, n), n);
3
+ var O = (i, e, n) => (et(i, typeof e != "symbol" ? e + "" : e, n), n);
4
4
  import { ConversationMessageListItemType as A, registerCustomMessageComponent as q, ConversationPlatform as nt } from "@telia-ace/widget-conversation";
5
5
  import { readStorage as W, createStorageWriter as Q, StorageCategory as X } from "@telia-ace/widget-services";
6
6
  import { uuid as j, Logger as V } from "@telia-ace/widget-utilities";
@@ -8,12 +8,12 @@ import { FormBuilder as G, submitButton as it } from "@telia-ace/widget-forms";
8
8
  import { createConfigurationApi as ot } from "@webprovisions/platform";
9
9
  class st {
10
10
  constructor(e) {
11
- M(this, "enabled", !0);
11
+ O(this, "enabled", !0);
12
12
  // set whether or not to store data
13
- M(this, "botProviderGlobalStateKey", "bot-provider-global-state");
14
- M(this, "botProviderLocalStateKey", "bot-provider-local-state");
15
- M(this, "botProviderEntriesKey", "bot-provider-entries");
16
- M(this, "botProviderMetaStateKey", "bot-provider-conversation-meta");
13
+ O(this, "botProviderGlobalStateKey", "bot-provider-global-state");
14
+ O(this, "botProviderLocalStateKey", "bot-provider-local-state");
15
+ O(this, "botProviderEntriesKey", "bot-provider-entries");
16
+ O(this, "botProviderMetaStateKey", "bot-provider-conversation-meta");
17
17
  this.container = e;
18
18
  }
19
19
  getKey(e) {
@@ -50,7 +50,7 @@ class st {
50
50
  ))(e);
51
51
  }
52
52
  }
53
- var K = /* @__PURE__ */ ((i) => (i.ContactMethod = "ace-conversational-hub-contact-method", i.ContactList = "ace-conversational-hub-contact-list", i))(K || {});
53
+ var $ = /* @__PURE__ */ ((i) => (i.ContactMethod = "ace-conversational-hub-contact-method", i.ContactList = "ace-conversational-hub-contact-list", i))($ || {});
54
54
  const at = (i) => {
55
55
  if (i) {
56
56
  const { type: e, content: n } = i;
@@ -113,7 +113,7 @@ const at = (i) => {
113
113
  ).get(), f || (g.expanded = g.inline = !1), g.body = dt(g, { submit: "Submit" })), a.guideId && (g.body.guideId = a.guideId), g;
114
114
  }, lt = (i) => {
115
115
  const { localState: e } = i;
116
- return i.tags.includes("category") && i.tags.includes("contact") ? A.ItemList : i.tags.includes("suggestion") ? A.LinkList : (e == null ? void 0 : e.$type) === "Humany.Matching.Bots.Conversations.States.ContactState, Humany.Matching" ? K.ContactList : A.ButtonList;
116
+ return i.tags.includes("category") && i.tags.includes("contact") ? A.ItemList : i.tags.includes("suggestion") ? A.LinkList : (e == null ? void 0 : e.$type) === "Humany.Matching.Bots.Conversations.States.ContactState, Humany.Matching" ? $.ContactList : A.ButtonList;
117
117
  }, dt = (i, {
118
118
  submit: e,
119
119
  errors: n,
@@ -130,7 +130,7 @@ const at = (i) => {
130
130
  return (i == null ? void 0 : i.body) || {};
131
131
  }, ut = async (i, e, n) => {
132
132
  (await (await i.getAsync("dataClient")).getClient()).parameters.set(e, n);
133
- }, $ = ({
133
+ }, N = ({
134
134
  messageId: i,
135
135
  message: e,
136
136
  group: n
@@ -156,12 +156,12 @@ const at = (i) => {
156
156
  };
157
157
  if (y.data) {
158
158
  const x = l.actions[y.actionKey];
159
- a === K.ContactList ? (m.push(y.data.id), g.data = ct(y.data, {
159
+ a === $.ContactList ? (m.push(y.data.id), g.data = ct(y.data, {
160
160
  guideId: (h = x == null ? void 0 : x.guideId) == null ? void 0 : h.toString()
161
161
  })) : g.data = y.data;
162
162
  }
163
163
  return g;
164
- }), a === K.ContactList && (b.contactMethodIds = m), b;
164
+ }), a === $.ContactList && (b.contactMethodIds = m), b;
165
165
  }, d = async (a, l, u = [], b) => {
166
166
  var y, g;
167
167
  const m = j();
@@ -173,16 +173,16 @@ const at = (i) => {
173
173
  case "List": {
174
174
  if (!a.content)
175
175
  return [];
176
- const { items: h, html: x } = a.content, O = [];
176
+ const { items: h, html: x } = a.content, M = [];
177
177
  let C = {
178
178
  actions: [],
179
179
  entryId: a.id,
180
180
  groupId: l.id
181
181
  };
182
182
  if ((h == null ? void 0 : h.length) > 0) {
183
- const N = lt(a);
183
+ const K = lt(a);
184
184
  if (C = t(
185
- N,
185
+ K,
186
186
  a,
187
187
  l.id,
188
188
  C
@@ -204,26 +204,26 @@ const at = (i) => {
204
204
  });
205
205
  }));
206
206
  }
207
- O.unshift(
208
- $({
207
+ M.unshift(
208
+ N({
209
209
  messageId: m,
210
- message: [N, C],
210
+ message: [K, C],
211
211
  group: l
212
212
  })
213
213
  );
214
214
  }
215
- return x && O.unshift(
216
- $({
215
+ return x && M.unshift(
216
+ N({
217
217
  messageId: m,
218
218
  message: [A.HTML, { body: x }],
219
219
  group: l
220
220
  })
221
- ), O;
221
+ ), M;
222
222
  }
223
223
  case "Text": {
224
224
  const h = [];
225
225
  if (h.push(
226
- $({
226
+ N({
227
227
  messageId: m,
228
228
  message: [
229
229
  A.HTML,
@@ -234,33 +234,33 @@ const at = (i) => {
234
234
  ), u.length) {
235
235
  const x = u.find(
236
236
  (C) => {
237
- var N;
238
- return C.type === "List" && ((N = C.localState) == null ? void 0 : N.$type) === "Humany.Matching.Bots.Conversations.States.ContactState, Humany.Matching";
237
+ var K;
238
+ return C.type === "List" && ((K = C.localState) == null ? void 0 : K.$type) === "Humany.Matching.Bots.Conversations.States.ContactState, Humany.Matching";
239
239
  }
240
- ), O = u.find(
240
+ ), M = u.find(
241
241
  (C) => C.tags.includes("contact") && C.type === "Contact"
242
242
  );
243
- if (O && h.push(
244
- $({
243
+ if (M && h.push(
244
+ N({
245
245
  messageId: m,
246
246
  message: [
247
- K.ContactMethod,
247
+ $.ContactMethod,
248
248
  {
249
- contactMethodId: O.content.id,
249
+ contactMethodId: M.content.id,
250
250
  groupId: l.id,
251
- guideId: O.content.guideId
251
+ guideId: M.content.guideId
252
252
  }
253
253
  ],
254
254
  group: l
255
255
  })
256
256
  ), x) {
257
257
  const C = t(
258
- K.ContactList,
258
+ $.ContactList,
259
259
  x,
260
260
  l.id
261
261
  );
262
262
  h.push(
263
- $({
263
+ N({
264
264
  messageId: m,
265
265
  message: [
266
266
  A.Separator,
@@ -269,9 +269,9 @@ const at = (i) => {
269
269
  group: l
270
270
  })
271
271
  ), h.push(
272
- $({
272
+ N({
273
273
  messageId: m,
274
- message: [K.ContactList, C],
274
+ message: [$.ContactList, C],
275
275
  group: l
276
276
  })
277
277
  );
@@ -281,10 +281,10 @@ const at = (i) => {
281
281
  }
282
282
  case "Contact":
283
283
  return [
284
- $({
284
+ N({
285
285
  messageId: m,
286
286
  message: [
287
- K.ContactMethod,
287
+ $.ContactMethod,
288
288
  {
289
289
  contactMethodId: a.content.id,
290
290
  groupId: l.id,
@@ -296,7 +296,7 @@ const at = (i) => {
296
296
  ];
297
297
  case "Error":
298
298
  return [
299
- $({
299
+ N({
300
300
  messageId: m,
301
301
  message: [
302
302
  A.HTML,
@@ -330,10 +330,10 @@ const at = (i) => {
330
330
  };
331
331
  class mt {
332
332
  constructor(e, n, t, d) {
333
- M(this, "globalState");
334
- M(this, "localState");
335
- M(this, "clientId");
336
- M(this, "entries");
333
+ O(this, "globalState");
334
+ O(this, "localState");
335
+ O(this, "clientId");
336
+ O(this, "entries");
337
337
  this.endpoint = e, this.events = n, this.store = t, this.container = d, this.clientId = j(), this.entries = [];
338
338
  }
339
339
  async fetchGuide(e) {
@@ -433,12 +433,12 @@ const ft = "@telia-ace/conversational-hub-bot-provider", pt = "0.0.16", ht = "./
433
433
  let d, p, f, k = (t == null ? void 0 : t.connectionAttempts) ?? 5, P, a, l;
434
434
  V.info((H == null ? void 0 : H.name) + " version: " + (H == null ? void 0 : H.version)), q(
435
435
  i,
436
- K.ContactMethod,
437
- import("./contact-method-e0b87a2a.mjs")
436
+ $.ContactMethod,
437
+ import("./contact-method-d552cfd5.mjs")
438
438
  ), q(
439
439
  i,
440
- K.ContactList,
441
- import("./contact-method-list-818567d0.mjs")
440
+ $.ContactList,
441
+ import("./contact-method-list-d8df0f00.mjs")
442
442
  );
443
443
  const u = await Q(
444
444
  i,
@@ -458,7 +458,7 @@ const ft = "@telia-ace/conversational-hub-bot-provider", pt = "0.0.16", ht = "./
458
458
  const o = r.target;
459
459
  if ((s = o.getAttribute("class")) != null && s.includes("dialog-option-cx")) {
460
460
  const c = o.getAttribute("value");
461
- N(c), d.user.print(
461
+ K(c), d.user.print(
462
462
  c.replace(/</g, "&lt;").replace(/>/g, "&gt;")
463
463
  );
464
464
  }
@@ -472,7 +472,7 @@ const ft = "@telia-ace/conversational-hub-bot-provider", pt = "0.0.16", ht = "./
472
472
  avatar: t == null ? void 0 : t.avatar
473
473
  }), l = b(i, s);
474
474
  const { events: o } = i.get("$widget"), c = new st(i);
475
- a = new mt(l, o, c, i), O();
475
+ a = new mt(l, o, c, i), M();
476
476
  const [v] = i.get("widgetDOMElements");
477
477
  v.querySelectorAll(".humany-bot-contact-method").forEach((I) => {
478
478
  var w;
@@ -485,7 +485,7 @@ const ft = "@telia-ace/conversational-hub-bot-provider", pt = "0.0.16", ht = "./
485
485
  }), s.actions.watch("conversation.action", (I, w) => (S() && C(I), w(I))), s.actions.watch("conversation.user-submit", (I, w) => {
486
486
  if (!S())
487
487
  return w(I);
488
- N(I.text), d.user.print(
488
+ K(I.text), d.user.print(
489
489
  I.text.replace(/</g, "&lt;").replace(/>/g, "&gt;")
490
490
  );
491
491
  }), n.events.subscribe(
@@ -519,7 +519,7 @@ const ft = "@telia-ace/conversational-hub-bot-provider", pt = "0.0.16", ht = "./
519
519
  }
520
520
  return s.toString();
521
521
  }
522
- async function O(r = !0) {
522
+ async function M(r = !0) {
523
523
  const s = await W(
524
524
  i,
525
525
  "conversational-hub-session"
@@ -528,9 +528,12 @@ const ft = "@telia-ace/conversational-hub-bot-provider", pt = "0.0.16", ht = "./
528
528
  delete o.silentStart, n.events.dispatch("conversational-hub-provider:started", {});
529
529
  else if (s != null && s.sessionId && r)
530
530
  P = s == null ? void 0 : s.sessionId;
531
- else if (t != null && t.welcomeMessage)
532
- h != null && h.length || f.print(t == null ? void 0 : t.welcomeMessage);
533
- else {
531
+ else if (t != null && t.welcomeMessage) {
532
+ if (!(h != null && h.length)) {
533
+ const c = t.welcomeMessage.replaceAll("$lt;", "<").replaceAll("$gt;", ">");
534
+ f.print(c);
535
+ }
536
+ } else {
534
537
  const c = {
535
538
  extension: t.extension
536
539
  };
@@ -554,7 +557,7 @@ const ft = "@telia-ace/conversational-hub-bot-provider", pt = "0.0.16", ht = "./
554
557
  `{"type":"button_click","language":"${t.language}","content":{"button_text":"${r.label}","value":"${r.actionKey}"}}`
555
558
  );
556
559
  }
557
- async function N(r) {
560
+ async function K(r) {
558
561
  const s = { text: r };
559
562
  if (!P) {
560
563
  const o = {
@@ -595,9 +598,9 @@ const ft = "@telia-ace/conversational-hub-bot-provider", pt = "0.0.16", ht = "./
595
598
  if (V.error(`HTTP ${v == null ? void 0 : v.status}.`, JSON.stringify(S)), c(), !!((I = S == null ? void 0 : S.errors) != null && I.filter(
596
599
  (E) => E.code === "1003"
597
600
  ).length) && k > 0) {
598
- k--, await new Promise((Z) => setTimeout(Z, 500)), await O(!1);
601
+ k--, await new Promise((Z) => setTimeout(Z, 500)), await M(!1);
599
602
  const E = JSON.parse(s);
600
- (w = E == null ? void 0 : E.content) != null && w.text ? await N(E.content.text) : (B = E == null ? void 0 : E.content) != null && B.action && await C((F = E == null ? void 0 : E.content) == null ? void 0 : F.action);
603
+ (w = E == null ? void 0 : E.content) != null && w.text ? await K(E.content.text) : (B = E == null ? void 0 : E.content) != null && B.action && await C((F = E == null ? void 0 : E.content) == null ? void 0 : F.action);
601
604
  } else
602
605
  f.print(t.errorMessage || "An error occurred");
603
606
  return;
@@ -1 +1 @@
1
- "use strict";var X=Object.defineProperty;var Y=(i,e,n)=>e in i?X(i,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):i[e]=n;var O=(i,e,n)=>(Y(i,typeof e!="symbol"?e+"":e,n),n);const $=require("@telia-ace/widget-conversation"),j=require("@telia-ace/widget-services"),N=require("@telia-ace/widget-utilities"),F=require("@telia-ace/widget-forms"),Z=require("@webprovisions/platform");class tt{constructor(e){O(this,"enabled",!0);O(this,"botProviderGlobalStateKey","bot-provider-global-state");O(this,"botProviderLocalStateKey","bot-provider-local-state");O(this,"botProviderEntriesKey","bot-provider-entries");O(this,"botProviderMetaStateKey","bot-provider-conversation-meta");this.container=e}getKey(e){let n;switch(e){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(e){const n=this.getKey(e);if(!(!this.enabled||!n))return j.readStorage(this.container,n)}async write(e,n){const t=this.getKey(n);if(!this.enabled||!t)return;(await j.createStorageWriter(this.container,t,j.StorageCategory.Necessary))(e)}}var T=(i=>(i.ContactMethod="ace-conversational-hub-contact-method",i.ContactList="ace-conversational-hub-contact-list",i))(T||{});const et=i=>{if(i){const{type:e,content:n}=i;if(e&&n)return{type:e,content:n}}},nt=({isUser:i,items:e=[],meta:n={}})=>{const t=N.uuid();return{id:t,isUser:i,items:e.map(p=>({id:p.id||N.uuid(),isUser:i,groupId:t,message:p.message||[]})),meta:n}},it=({id:i,title:e,defaultIcon:n,exits:[t],exitType:d,confirmationText:p,expandFormAutomatically:f,form:M,description:P},a={})=>{const{adapter:l}=t||{Adapter:{}},{clientName:u="",settings:y={},customClientName:m=""}=l,{validation:b}=a,g={id:i.toString(),title:e,description:P,symbol:et(n),clientName:u==="custom.adapter"?m:u,expanded:!0,inline:!0,body:{}};if(u.indexOf("phone")>-1||u.indexOf("freetext")>-1){const{displayTextBeforeClick:h,textBeforeClick:L}=y;h==="true"&&(g.expanded=!1,g.title=L),u.indexOf("phone.text")>-1?g.body.phoneNumber=y.phoneNumber:g.body.freetext=y.freetext}return(u.indexOf("chat.popup")>-1||u.indexOf("link")>-1||u==="custom.adapter"&&d==="custom")&&(g.body=y,g.body.confirmationFallback=p),u.indexOf("ace")>-1&&(g.body=y),M&&M.hasValueComponents&&(b?g.body.form=F.FormBuilder.fromLegacyForm(i.toString(),M,b).get():g.body.form=F.FormBuilder.fromLegacyForm(i.toString(),M).get(),f||(g.expanded=g.inline=!1),g.body=z(g,{submit:"Submit"})),a.guideId&&(g.body.guideId=a.guideId),g},ot=i=>{const{localState:e}=i;return i.tags.includes("category")&&i.tags.includes("contact")?$.ConversationMessageListItemType.ItemList:i.tags.includes("suggestion")?$.ConversationMessageListItemType.LinkList:(e==null?void 0:e.$type)==="Humany.Matching.Bots.Conversations.States.ContactState, Humany.Matching"?T.ContactList:$.ConversationMessageListItemType.ButtonList},z=(i,{submit:e,errors:n,meta:t})=>{var d;if((d=i==null?void 0:i.body)!=null&&d.form){const{body:p}=i,f=new F.FormBuilder(p.form);return p.form.layout.submit||f.createComponent(F.submitButton(e,"submit")),n&&f.setValidationErrors(n),t&&f.setMeta(t),{...p,form:f.get()}}return(i==null?void 0:i.body)||{}},st=async(i,e,n)=>{(await(await i.getAsync("dataClient")).getClient()).parameters.set(e,n)},A=({messageId:i,message:e,group:n})=>({id:i,message:e,groupId:n.id,isUser:n.isUser}),at=async(i,e,n)=>{const t=(a,l,u,y={actions:[],entryId:l.id,groupId:u})=>{const m=[];return y.actions=l.content.items.map(b=>{var h;const g={label:b.title,actionKey:b.actionKey,symbol:b.symbol?b.symbol:void 0,description:b.description||void 0};if(b.data){const L=l.actions[b.actionKey];a===T.ContactList?(m.push(b.data.id),g.data=it(b.data,{guideId:(h=L==null?void 0:L.guideId)==null?void 0:h.toString()})):g.data=b.data}return g}),a===T.ContactList&&(y.contactMethodIds=m),y},d=async(a,l,u=[],y)=>{var b,g;const m=N.uuid();switch(a.type!=="List"&&a.tags.includes("guide")&&((g=(b=a.content.hints)==null?void 0:b[0])!=null&&g.id)&&await st(i,"LastGuideId",a.content.hints[0].id),a.type){case"List":{if(!a.content)return[];const{items:h,html:L}=a.content,k=[];let C={actions:[],entryId:a.id,groupId:l.id};if((h==null?void 0:h.length)>0){const K=ot(a);if(C=t(K,a,l.id,C),u.length){const x=u.find(H=>H.tags.includes("paging"));x!=null&&x.content&&(l.meta.paging={actions:x.actions,items:x.content.items,localState:x.localState},x.content.items.forEach(H=>{C.actions.push({label:H.title,actionKey:H.actionKey,data:{groupId:y?y.id:l.id}})}))}k.unshift(A({messageId:m,message:[K,C],group:l}))}return L&&k.unshift(A({messageId:m,message:[$.ConversationMessageListItemType.HTML,{body:L}],group:l})),k}case"Text":{const h=[];if(h.push(A({messageId:m,message:[$.ConversationMessageListItemType.HTML,{body:a.content.html}],group:l})),u.length){const L=u.find(C=>{var K;return C.type==="List"&&((K=C.localState)==null?void 0:K.$type)==="Humany.Matching.Bots.Conversations.States.ContactState, Humany.Matching"}),k=u.find(C=>C.tags.includes("contact")&&C.type==="Contact");if(k&&h.push(A({messageId:m,message:[T.ContactMethod,{contactMethodId:k.content.id,groupId:l.id,guideId:k.content.guideId}],group:l})),L){const C=t(T.ContactList,L,l.id);h.push(A({messageId:m,message:[$.ConversationMessageListItemType.Separator,void 0],group:l})),h.push(A({messageId:m,message:[T.ContactList,C],group:l}))}}return h}case"Contact":return[A({messageId:m,message:[T.ContactMethod,{contactMethodId:a.content.id,groupId:l.id,guideId:a.content.guideId}],group:l})];case"Error":return[A({messageId:m,message:[$.ConversationMessageListItemType.HTML,{body:a.content.message||"Something went wrong."}],group:l})];default:return[]}},p=new Map([["Text",1],["List",2],["Contact",3]]),f=[],M=e.sort((a,l)=>{const y=p.get(a.type)||20,m=p.get(l.type)||20;return y-m}).filter(a=>!a.relation).reduce((a,l)=>a.concat(l),[]),P=a=>typeof a.actions.selector<"u";for(const a of M){const l=e.filter(m=>m.relation===a.id&&!P(m)),u=nt({isUser:!1});(await d(a,u,l,n)).forEach(m=>{u.items.push(m)}),u.items.length&&f.push(u)}return f};class rt{constructor(e,n,t,d){O(this,"globalState");O(this,"localState");O(this,"clientId");O(this,"entries");this.endpoint=e,this.events=n,this.store=t,this.container=d,this.clientId=N.uuid(),this.entries=[]}async fetchGuide(e){const n={command:{guide:{id:e}},globalState:this.globalState,clientId:this.clientId};return await this.postEnvelope(n)}async postEnvelope(e,n){try{const t=await fetch(this.endpoint,this.getHttpOptions(e));if(!t.ok)throw t;const d=await t.json();return this.handleResponse(d,n)}catch(t){process.env.NODE_ENV!=="production"&&console.warn("Something went wrong when posting the envelope.");let d="Something went wrong";return(t.message==="Failed to fetch"||t.message==="NetworkError when attempting to fetch resource.")&&(d="Lost connection... Please try again."),this.events.dispatch("tracking:http-client-error",{message:d,error:t}),this.handleResponse({entries:[{id:N.uuid(),type:"Error",timestamp:new Date().toISOString(),content:{message:d},actions:{},tags:[]}]})}}async handleResponse(e,n){this.entries=this.entries.concat(e.entries),this.store.write(this.entries,"entries");const t=e.entries.find(p=>p.type==="Widget");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((p,f)=>f.localState?f.localState:p,void 0),this.store.write(this.localState,"localState"),await at(this.container,e.entries,n)}getHttpOptions(e){const n={method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"}};return e.funnel=this.container.get("$widget").name,e.localState=e.localState||this.localState,Object.assign({},n,{body:JSON.stringify(e),credentials:"same-origin"})}}const ct="@telia-ace/conversational-hub-bot-provider",lt="0.0.16",dt="./index.js",ut="./index.d.ts",gt={".":{import:"./index.mjs",require:"./index.js"}},mt={"@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":"*"},ft={"@emotion/react":"11.11.1","@emotion/styled":"11.11.0",react:"18.2.0"},B={name:ct,version:lt,main:dt,types:ut,exports:gt,dependencies:mt,peerDependencies:ft},pt=async i=>{var V,G,U,J,D;const e="chub-plugin",n=i.get("$widget"),t=(D=(J=(U=(G=(V=n==null?void 0:n.container)==null?void 0:V.get("$settings"))==null?void 0:G.components)==null?void 0:U.conversation)==null?void 0:J.properties)==null?void 0:D.conversationalHubPluginSettings;let d,p,f,M=(t==null?void 0:t.connectionAttempts)??5,P,a,l;N.Logger.info((B==null?void 0:B.name)+" version: "+(B==null?void 0:B.version)),$.registerCustomMessageComponent(i,T.ContactMethod,Promise.resolve().then(()=>require("./contact-method-f1b2fed9.js"))),$.registerCustomMessageComponent(i,T.ContactList,Promise.resolve().then(()=>require("./contact-method-list-8b65c06e.js")));const u=await j.createStorageWriter(i,"conversational-hub-session",j.StorageCategory.Necessary),y=(r,s)=>{const{knowledgeBotEndpoint:o}=s.properties();if(o)return`${o}/conversations`;const{data:c}=r.get("$settings");if(!c||!c.projection)throw new Error("Missing Knowledge Bot endpoint");return`${c.projection}/conversations`},m=r=>{var s;if(r.target instanceof HTMLButtonElement){const o=r.target;if((s=o.getAttribute("class"))!=null&&s.includes("dialog-option-cx")){const c=o.getAttribute("value");K(c),d.user.print(c.replace(/</g,"&lt;").replace(/>/g,"&gt;"))}}};(await $.ConversationPlatform.getInstance(i)).registerProvider(e,(r,s)=>{d=r,p=d.controller,f=d.createAgent({name:t==null?void 0:t.botName,avatar:t==null?void 0:t.avatar}),l=y(i,s);const{events:o}=i.get("$widget"),c=new tt(i);a=new rt(l,o,c,i),k();const[v]=i.get("widgetDOMElements");v.querySelectorAll(".humany-bot-contact-method").forEach(I=>{var w;(w=I.closest(".humany-conversation-entry"))==null||w.remove()}),v.removeEventListener("click",m),v.addEventListener("click",m);const S=()=>p.providers.includes(e);s.actions.create("submit",I=>{const{events:w}=i.get("$widget");w.dispatch("conversational-hub-provider:form-submitted",I)}),s.actions.watch("conversation.action",(I,w)=>(S()&&C(I),w(I))),s.actions.watch("conversation.user-submit",(I,w)=>{if(!S())return w(I);K(I.text),d.user.print(I.text.replace(/</g,"&lt;").replace(/>/g,"&gt;"))}),n.events.subscribe("conversational-hub-provider:fetch-guide",async(I,w)=>{if(!(w!=null&&w.guideId))return;const _=await a.fetchGuide(parseInt(w.guideId));_&&g(_)})});async function g(r){r.forEach(s=>{const o=s.items.map(c=>c.message);s.writer=f.print(o)})}const h=sessionStorage.getItem(`humany_${L(n.implementation.tenant+n.implementation.name+n.name)}`);function L(r){let s=0;if(r.length===0)return s.toString();for(let o=0;o<r.length;o++){const c=r.charCodeAt(o);s=(s<<5)-s+c,s=s&s}return s.toString()}async function k(r=!0){const s=await j.readStorage(i,"conversational-hub-session"),o=i.get("dialogflowSettings");if(o!=null&&o.silentStart)delete o.silentStart,n.events.dispatch("conversational-hub-provider:started",{});else if(s!=null&&s.sessionId&&r)P=s==null?void 0:s.sessionId;else if(t!=null&&t.welcomeMessage)h!=null&&h.length||f.print(t==null?void 0:t.welcomeMessage);else{const c={extension:t.extension};o!=null&&o.initCommand&&(c.input={type:"event",language:t.language,content:{name:o.initCommand,parameters:o.initParameters||{}}}),await x(t.baseUrl+"/initialize",JSON.stringify(c),r)}}async function C(r){await x(`${t.baseUrl}/input/${P}`,`{"type":"button_click","language":"${t.language}","content":{"button_text":"${r.label}","value":"${r.actionKey}"}}`)}async function K(r){const s={text:r};if(!P){const o={extension:t.extension},c=i.get("dialogflowSettings");c!=null&&c.initCommand&&(o.input={type:"event",language:t.language,content:{name:c.initCommand,parameters:c.initParameters||{}}}),await x(t.baseUrl+"/initialize",JSON.stringify(o),!1)}await x(`${t.baseUrl}/input/${P}`,`{"type":"text","language":"${t.language}","content":${JSON.stringify(s)}}`)}async function x(r,s,o=!0){var I,w,_,R;const c=d.loading();let v,S;try{v=await fetch(r,{method:"POST",body:s}),S=await(v==null?void 0:v.json())}catch(q){q instanceof SyntaxError?N.Logger.error("Incorrect JSON format.",q):N.Logger.error("Network error: check connection or baseUrl.",q),c(),f.print(t.errorMessage||"An error occurred");return}if(!(v!=null&&v.ok)){if(N.Logger.error(`HTTP ${v==null?void 0:v.status}.`,JSON.stringify(S)),c(),!!((I=S==null?void 0:S.errors)!=null&&I.filter(E=>E.code==="1003").length)&&M>0){M--,await new Promise(Q=>setTimeout(Q,500)),await k(!1);const E=JSON.parse(s);(w=E==null?void 0:E.content)!=null&&w.text?await K(E.content.text):(_=E==null?void 0:E.content)!=null&&_.action&&await C((R=E==null?void 0:E.content)==null?void 0:R.action)}else f.print(t.errorMessage||"An error occurred");return}c(),M=(t==null?void 0:t.connectionAttempts)??5,S!=null&&S.action_payload&&H(S.action_payload),P=S==null?void 0:S.session_id,u({sessionId:P}),o&&W(S)}async function H(r){var v;const s=(v=r==null?void 0:r.transfer_parameters)==null?void 0:v.contactGuide,o=d.loading(),c=await a.fetchGuide(parseInt(s));o(),c&&g(c)}function W(r){var s;r==null||r.agent_response.forEach(o=>{f.print(o.payload.text)}),(s=r==null?void 0:r.prompt)!=null&&s.items&&f.print(["button-list",{actions:r.prompt.items.map(o=>{let c;return o.type==="button"&&(c={actionKey:o.value,label:o.text}),o.type==="link"&&(c={actionKey:o.value,label:o.text,data:{href:o.url,target:(t==null?void 0:t.linkTarget)??"_blank"}}),c})}])}},ht=Z.createConfigurationApi(i=>{i.createCommand("dialogflow",e=>n=>{const t={initCommand:n.initCommand};n.initParameters&&(t.initParameters=n.initParameters),n.silentStart&&(t.silentStart=n.silentStart),e.container.register("dialogflowSettings",t)})});exports.ConversationalHubPlugin=pt;exports.dialogflowConfigurationApi=ht;exports.updateForm=z;
1
+ "use strict";var X=Object.defineProperty;var Y=(i,e,n)=>e in i?X(i,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):i[e]=n;var O=(i,e,n)=>(Y(i,typeof e!="symbol"?e+"":e,n),n);const T=require("@telia-ace/widget-conversation"),j=require("@telia-ace/widget-services"),N=require("@telia-ace/widget-utilities"),F=require("@telia-ace/widget-forms"),Z=require("@webprovisions/platform");class tt{constructor(e){O(this,"enabled",!0);O(this,"botProviderGlobalStateKey","bot-provider-global-state");O(this,"botProviderLocalStateKey","bot-provider-local-state");O(this,"botProviderEntriesKey","bot-provider-entries");O(this,"botProviderMetaStateKey","bot-provider-conversation-meta");this.container=e}getKey(e){let n;switch(e){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(e){const n=this.getKey(e);if(!(!this.enabled||!n))return j.readStorage(this.container,n)}async write(e,n){const t=this.getKey(n);if(!this.enabled||!t)return;(await j.createStorageWriter(this.container,t,j.StorageCategory.Necessary))(e)}}var $=(i=>(i.ContactMethod="ace-conversational-hub-contact-method",i.ContactList="ace-conversational-hub-contact-list",i))($||{});const et=i=>{if(i){const{type:e,content:n}=i;if(e&&n)return{type:e,content:n}}},nt=({isUser:i,items:e=[],meta:n={}})=>{const t=N.uuid();return{id:t,isUser:i,items:e.map(p=>({id:p.id||N.uuid(),isUser:i,groupId:t,message:p.message||[]})),meta:n}},it=({id:i,title:e,defaultIcon:n,exits:[t],exitType:d,confirmationText:p,expandFormAutomatically:f,form:M,description:P},a={})=>{const{adapter:l}=t||{Adapter:{}},{clientName:u="",settings:y={},customClientName:m=""}=l,{validation:b}=a,g={id:i.toString(),title:e,description:P,symbol:et(n),clientName:u==="custom.adapter"?m:u,expanded:!0,inline:!0,body:{}};if(u.indexOf("phone")>-1||u.indexOf("freetext")>-1){const{displayTextBeforeClick:h,textBeforeClick:L}=y;h==="true"&&(g.expanded=!1,g.title=L),u.indexOf("phone.text")>-1?g.body.phoneNumber=y.phoneNumber:g.body.freetext=y.freetext}return(u.indexOf("chat.popup")>-1||u.indexOf("link")>-1||u==="custom.adapter"&&d==="custom")&&(g.body=y,g.body.confirmationFallback=p),u.indexOf("ace")>-1&&(g.body=y),M&&M.hasValueComponents&&(b?g.body.form=F.FormBuilder.fromLegacyForm(i.toString(),M,b).get():g.body.form=F.FormBuilder.fromLegacyForm(i.toString(),M).get(),f||(g.expanded=g.inline=!1),g.body=z(g,{submit:"Submit"})),a.guideId&&(g.body.guideId=a.guideId),g},ot=i=>{const{localState:e}=i;return i.tags.includes("category")&&i.tags.includes("contact")?T.ConversationMessageListItemType.ItemList:i.tags.includes("suggestion")?T.ConversationMessageListItemType.LinkList:(e==null?void 0:e.$type)==="Humany.Matching.Bots.Conversations.States.ContactState, Humany.Matching"?$.ContactList:T.ConversationMessageListItemType.ButtonList},z=(i,{submit:e,errors:n,meta:t})=>{var d;if((d=i==null?void 0:i.body)!=null&&d.form){const{body:p}=i,f=new F.FormBuilder(p.form);return p.form.layout.submit||f.createComponent(F.submitButton(e,"submit")),n&&f.setValidationErrors(n),t&&f.setMeta(t),{...p,form:f.get()}}return(i==null?void 0:i.body)||{}},st=async(i,e,n)=>{(await(await i.getAsync("dataClient")).getClient()).parameters.set(e,n)},A=({messageId:i,message:e,group:n})=>({id:i,message:e,groupId:n.id,isUser:n.isUser}),at=async(i,e,n)=>{const t=(a,l,u,y={actions:[],entryId:l.id,groupId:u})=>{const m=[];return y.actions=l.content.items.map(b=>{var h;const g={label:b.title,actionKey:b.actionKey,symbol:b.symbol?b.symbol:void 0,description:b.description||void 0};if(b.data){const L=l.actions[b.actionKey];a===$.ContactList?(m.push(b.data.id),g.data=it(b.data,{guideId:(h=L==null?void 0:L.guideId)==null?void 0:h.toString()})):g.data=b.data}return g}),a===$.ContactList&&(y.contactMethodIds=m),y},d=async(a,l,u=[],y)=>{var b,g;const m=N.uuid();switch(a.type!=="List"&&a.tags.includes("guide")&&((g=(b=a.content.hints)==null?void 0:b[0])!=null&&g.id)&&await st(i,"LastGuideId",a.content.hints[0].id),a.type){case"List":{if(!a.content)return[];const{items:h,html:L}=a.content,k=[];let C={actions:[],entryId:a.id,groupId:l.id};if((h==null?void 0:h.length)>0){const K=ot(a);if(C=t(K,a,l.id,C),u.length){const x=u.find(H=>H.tags.includes("paging"));x!=null&&x.content&&(l.meta.paging={actions:x.actions,items:x.content.items,localState:x.localState},x.content.items.forEach(H=>{C.actions.push({label:H.title,actionKey:H.actionKey,data:{groupId:y?y.id:l.id}})}))}k.unshift(A({messageId:m,message:[K,C],group:l}))}return L&&k.unshift(A({messageId:m,message:[T.ConversationMessageListItemType.HTML,{body:L}],group:l})),k}case"Text":{const h=[];if(h.push(A({messageId:m,message:[T.ConversationMessageListItemType.HTML,{body:a.content.html}],group:l})),u.length){const L=u.find(C=>{var K;return C.type==="List"&&((K=C.localState)==null?void 0:K.$type)==="Humany.Matching.Bots.Conversations.States.ContactState, Humany.Matching"}),k=u.find(C=>C.tags.includes("contact")&&C.type==="Contact");if(k&&h.push(A({messageId:m,message:[$.ContactMethod,{contactMethodId:k.content.id,groupId:l.id,guideId:k.content.guideId}],group:l})),L){const C=t($.ContactList,L,l.id);h.push(A({messageId:m,message:[T.ConversationMessageListItemType.Separator,void 0],group:l})),h.push(A({messageId:m,message:[$.ContactList,C],group:l}))}}return h}case"Contact":return[A({messageId:m,message:[$.ContactMethod,{contactMethodId:a.content.id,groupId:l.id,guideId:a.content.guideId}],group:l})];case"Error":return[A({messageId:m,message:[T.ConversationMessageListItemType.HTML,{body:a.content.message||"Something went wrong."}],group:l})];default:return[]}},p=new Map([["Text",1],["List",2],["Contact",3]]),f=[],M=e.sort((a,l)=>{const y=p.get(a.type)||20,m=p.get(l.type)||20;return y-m}).filter(a=>!a.relation).reduce((a,l)=>a.concat(l),[]),P=a=>typeof a.actions.selector<"u";for(const a of M){const l=e.filter(m=>m.relation===a.id&&!P(m)),u=nt({isUser:!1});(await d(a,u,l,n)).forEach(m=>{u.items.push(m)}),u.items.length&&f.push(u)}return f};class rt{constructor(e,n,t,d){O(this,"globalState");O(this,"localState");O(this,"clientId");O(this,"entries");this.endpoint=e,this.events=n,this.store=t,this.container=d,this.clientId=N.uuid(),this.entries=[]}async fetchGuide(e){const n={command:{guide:{id:e}},globalState:this.globalState,clientId:this.clientId};return await this.postEnvelope(n)}async postEnvelope(e,n){try{const t=await fetch(this.endpoint,this.getHttpOptions(e));if(!t.ok)throw t;const d=await t.json();return this.handleResponse(d,n)}catch(t){process.env.NODE_ENV!=="production"&&console.warn("Something went wrong when posting the envelope.");let d="Something went wrong";return(t.message==="Failed to fetch"||t.message==="NetworkError when attempting to fetch resource.")&&(d="Lost connection... Please try again."),this.events.dispatch("tracking:http-client-error",{message:d,error:t}),this.handleResponse({entries:[{id:N.uuid(),type:"Error",timestamp:new Date().toISOString(),content:{message:d},actions:{},tags:[]}]})}}async handleResponse(e,n){this.entries=this.entries.concat(e.entries),this.store.write(this.entries,"entries");const t=e.entries.find(p=>p.type==="Widget");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((p,f)=>f.localState?f.localState:p,void 0),this.store.write(this.localState,"localState"),await at(this.container,e.entries,n)}getHttpOptions(e){const n={method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"}};return e.funnel=this.container.get("$widget").name,e.localState=e.localState||this.localState,Object.assign({},n,{body:JSON.stringify(e),credentials:"same-origin"})}}const ct="@telia-ace/conversational-hub-bot-provider",lt="0.0.16",dt="./index.js",ut="./index.d.ts",gt={".":{import:"./index.mjs",require:"./index.js"}},mt={"@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":"*"},ft={"@emotion/react":"11.11.1","@emotion/styled":"11.11.0",react:"18.2.0"},B={name:ct,version:lt,main:dt,types:ut,exports:gt,dependencies:mt,peerDependencies:ft},pt=async i=>{var V,G,U,J,D;const e="chub-plugin",n=i.get("$widget"),t=(D=(J=(U=(G=(V=n==null?void 0:n.container)==null?void 0:V.get("$settings"))==null?void 0:G.components)==null?void 0:U.conversation)==null?void 0:J.properties)==null?void 0:D.conversationalHubPluginSettings;let d,p,f,M=(t==null?void 0:t.connectionAttempts)??5,P,a,l;N.Logger.info((B==null?void 0:B.name)+" version: "+(B==null?void 0:B.version)),T.registerCustomMessageComponent(i,$.ContactMethod,Promise.resolve().then(()=>require("./contact-method-e77006cb.js"))),T.registerCustomMessageComponent(i,$.ContactList,Promise.resolve().then(()=>require("./contact-method-list-e6eb0d69.js")));const u=await j.createStorageWriter(i,"conversational-hub-session",j.StorageCategory.Necessary),y=(r,s)=>{const{knowledgeBotEndpoint:o}=s.properties();if(o)return`${o}/conversations`;const{data:c}=r.get("$settings");if(!c||!c.projection)throw new Error("Missing Knowledge Bot endpoint");return`${c.projection}/conversations`},m=r=>{var s;if(r.target instanceof HTMLButtonElement){const o=r.target;if((s=o.getAttribute("class"))!=null&&s.includes("dialog-option-cx")){const c=o.getAttribute("value");K(c),d.user.print(c.replace(/</g,"&lt;").replace(/>/g,"&gt;"))}}};(await T.ConversationPlatform.getInstance(i)).registerProvider(e,(r,s)=>{d=r,p=d.controller,f=d.createAgent({name:t==null?void 0:t.botName,avatar:t==null?void 0:t.avatar}),l=y(i,s);const{events:o}=i.get("$widget"),c=new tt(i);a=new rt(l,o,c,i),k();const[v]=i.get("widgetDOMElements");v.querySelectorAll(".humany-bot-contact-method").forEach(I=>{var w;(w=I.closest(".humany-conversation-entry"))==null||w.remove()}),v.removeEventListener("click",m),v.addEventListener("click",m);const S=()=>p.providers.includes(e);s.actions.create("submit",I=>{const{events:w}=i.get("$widget");w.dispatch("conversational-hub-provider:form-submitted",I)}),s.actions.watch("conversation.action",(I,w)=>(S()&&C(I),w(I))),s.actions.watch("conversation.user-submit",(I,w)=>{if(!S())return w(I);K(I.text),d.user.print(I.text.replace(/</g,"&lt;").replace(/>/g,"&gt;"))}),n.events.subscribe("conversational-hub-provider:fetch-guide",async(I,w)=>{if(!(w!=null&&w.guideId))return;const _=await a.fetchGuide(parseInt(w.guideId));_&&g(_)})});async function g(r){r.forEach(s=>{const o=s.items.map(c=>c.message);s.writer=f.print(o)})}const h=sessionStorage.getItem(`humany_${L(n.implementation.tenant+n.implementation.name+n.name)}`);function L(r){let s=0;if(r.length===0)return s.toString();for(let o=0;o<r.length;o++){const c=r.charCodeAt(o);s=(s<<5)-s+c,s=s&s}return s.toString()}async function k(r=!0){const s=await j.readStorage(i,"conversational-hub-session"),o=i.get("dialogflowSettings");if(o!=null&&o.silentStart)delete o.silentStart,n.events.dispatch("conversational-hub-provider:started",{});else if(s!=null&&s.sessionId&&r)P=s==null?void 0:s.sessionId;else if(t!=null&&t.welcomeMessage){if(!(h!=null&&h.length)){const c=t.welcomeMessage.replaceAll("$lt;","<").replaceAll("$gt;",">");f.print(c)}}else{const c={extension:t.extension};o!=null&&o.initCommand&&(c.input={type:"event",language:t.language,content:{name:o.initCommand,parameters:o.initParameters||{}}}),await x(t.baseUrl+"/initialize",JSON.stringify(c),r)}}async function C(r){await x(`${t.baseUrl}/input/${P}`,`{"type":"button_click","language":"${t.language}","content":{"button_text":"${r.label}","value":"${r.actionKey}"}}`)}async function K(r){const s={text:r};if(!P){const o={extension:t.extension},c=i.get("dialogflowSettings");c!=null&&c.initCommand&&(o.input={type:"event",language:t.language,content:{name:c.initCommand,parameters:c.initParameters||{}}}),await x(t.baseUrl+"/initialize",JSON.stringify(o),!1)}await x(`${t.baseUrl}/input/${P}`,`{"type":"text","language":"${t.language}","content":${JSON.stringify(s)}}`)}async function x(r,s,o=!0){var I,w,_,R;const c=d.loading();let v,S;try{v=await fetch(r,{method:"POST",body:s}),S=await(v==null?void 0:v.json())}catch(q){q instanceof SyntaxError?N.Logger.error("Incorrect JSON format.",q):N.Logger.error("Network error: check connection or baseUrl.",q),c(),f.print(t.errorMessage||"An error occurred");return}if(!(v!=null&&v.ok)){if(N.Logger.error(`HTTP ${v==null?void 0:v.status}.`,JSON.stringify(S)),c(),!!((I=S==null?void 0:S.errors)!=null&&I.filter(E=>E.code==="1003").length)&&M>0){M--,await new Promise(Q=>setTimeout(Q,500)),await k(!1);const E=JSON.parse(s);(w=E==null?void 0:E.content)!=null&&w.text?await K(E.content.text):(_=E==null?void 0:E.content)!=null&&_.action&&await C((R=E==null?void 0:E.content)==null?void 0:R.action)}else f.print(t.errorMessage||"An error occurred");return}c(),M=(t==null?void 0:t.connectionAttempts)??5,S!=null&&S.action_payload&&H(S.action_payload),P=S==null?void 0:S.session_id,u({sessionId:P}),o&&W(S)}async function H(r){var v;const s=(v=r==null?void 0:r.transfer_parameters)==null?void 0:v.contactGuide,o=d.loading(),c=await a.fetchGuide(parseInt(s));o(),c&&g(c)}function W(r){var s;r==null||r.agent_response.forEach(o=>{f.print(o.payload.text)}),(s=r==null?void 0:r.prompt)!=null&&s.items&&f.print(["button-list",{actions:r.prompt.items.map(o=>{let c;return o.type==="button"&&(c={actionKey:o.value,label:o.text}),o.type==="link"&&(c={actionKey:o.value,label:o.text,data:{href:o.url,target:(t==null?void 0:t.linkTarget)??"_blank"}}),c})}])}},ht=Z.createConfigurationApi(i=>{i.createCommand("dialogflow",e=>n=>{const t={initCommand:n.initCommand};n.initParameters&&(t.initParameters=n.initParameters),n.silentStart&&(t.silentStart=n.silentStart),e.container.register("dialogflowSettings",t)})});exports.ConversationalHubPlugin=pt;exports.dialogflowConfigurationApi=ht;exports.updateForm=z;
package/index.js CHANGED
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./index-bc0e69f0.js");require("@telia-ace/widget-conversation");require("@telia-ace/widget-services");require("@telia-ace/widget-utilities");require("@telia-ace/widget-forms");require("@webprovisions/platform");exports.ConversationalHubPlugin=e.ConversationalHubPlugin;exports.dialogflowConfigurationApi=e.dialogflowConfigurationApi;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./index-8b5af599.js");require("@telia-ace/widget-conversation");require("@telia-ace/widget-services");require("@telia-ace/widget-utilities");require("@telia-ace/widget-forms");require("@webprovisions/platform");exports.ConversationalHubPlugin=e.ConversationalHubPlugin;exports.dialogflowConfigurationApi=e.dialogflowConfigurationApi;
package/index.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { C as n, d as l } from "./index-06b06645.mjs";
1
+ import { C as n, d as l } from "./index-17638994.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.14",
3
+ "version": "1.3.16",
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.14",
13
+ "@telia-ace/widget-conversation": "^1.3.16",
14
14
  "@webprovisions/platform": "^1.1.4",
15
- "@telia-ace/knowledge-widget-core": "^1.3.14",
16
- "@telia-ace/widget-utilities": "^1.3.14",
17
- "@telia-ace/widget-services": "^1.3.14",
18
- "@telia-ace/widget-core": "^1.3.14",
19
- "@telia-ace/knowledge-data-client": "^1.3.14",
20
- "@telia-ace/knowledge-widget-adapters": "^1.3.14",
21
- "@telia-ace/knowledge-widget-ui": "^1.3.14",
22
- "@telia-ace/widget-forms": "^1.3.14"
15
+ "@telia-ace/knowledge-widget-core": "^1.3.16",
16
+ "@telia-ace/widget-utilities": "^1.3.16",
17
+ "@telia-ace/widget-services": "^1.3.16",
18
+ "@telia-ace/widget-core": "^1.3.16",
19
+ "@telia-ace/knowledge-data-client": "^1.3.16",
20
+ "@telia-ace/knowledge-widget-adapters": "^1.3.16",
21
+ "@telia-ace/knowledge-widget-ui": "^1.3.16",
22
+ "@telia-ace/widget-forms": "^1.3.16"
23
23
  },
24
24
  "peerDependencies": {
25
25
  "@emotion/react": "11.11.1",
@@ -1,136 +0,0 @@
1
- import { jsx as E } from "react/jsx-runtime";
2
- import F from "@emotion/styled";
3
- import { DataClient as z, DataType as A } from "@telia-ace/knowledge-data-client";
4
- import { ContactMethod as N } from "@telia-ace/knowledge-widget-adapters";
5
- import { useContainer as R, useDispatch as T, useConversation as _ } from "@telia-ace/knowledge-widget-ui";
6
- import { FormBuilder as j } from "@telia-ace/widget-forms";
7
- import { appendClassNames as k } from "@telia-ace/widget-utilities";
8
- import { useState as G, useRef as I, useEffect as S, useCallback as V } from "react";
9
- import { u as $ } from "./index-06b06645.mjs";
10
- import "@telia-ace/widget-conversation";
11
- import "@telia-ace/widget-services";
12
- import "@webprovisions/platform";
13
- const ot = ({
14
- contactMethodId: a,
15
- guideId: e,
16
- groupId: c,
17
- className: x
18
- }) => {
19
- var h, C, v;
20
- const [t, n] = G(), m = R(), B = T(), u = I(!0), f = _();
21
- S(() => {
22
- const { events: d } = m.get("$widget"), w = d.subscribe(
23
- "conversational-hub-provider:form-submitted",
24
- async (b, r) => {
25
- var M;
26
- if (((M = r.form.meta) == null ? void 0 : M.groupId) !== c || r.id !== (t == null ? void 0 : t.id))
27
- return;
28
- f && (r.form.meta || (r.form.meta = {}), r.form.meta.conversation = f);
29
- const l = await m.getAsync(
30
- "contactMethods"
31
- ), o = {
32
- ...t,
33
- body: {
34
- ...t.body,
35
- form: r.form
36
- }
37
- }, { errors: i, valid: y, errorTypes: H } = await l.validate(
38
- o
39
- );
40
- if (!y) {
41
- const g = new j(t.body.form);
42
- n(void 0), g.setValidationErrors(i), o.body = {
43
- ...o.body,
44
- form: g.get()
45
- }, n({ ...o });
46
- return;
47
- }
48
- const D = await l.submit(o);
49
- o.confirmation = D, n(o);
50
- }
51
- ), s = d.subscribe(
52
- "bot-provider:evaluate",
53
- async (b, r) => {
54
- if (r.id !== a)
55
- return;
56
- const o = await (await m.getAsync(
57
- "contactMethods"
58
- )).evaluate(t);
59
- let i = {
60
- ...t,
61
- body: {
62
- ...t.body,
63
- form: o
64
- }
65
- };
66
- const y = $(i, {
67
- submit: "Submit",
68
- errors: {},
69
- meta: { groupId: c }
70
- });
71
- i = {
72
- ...i,
73
- body: y
74
- }, n(i);
75
- }
76
- );
77
- return () => {
78
- w(), s();
79
- };
80
- }, [m, t, n, f]);
81
- const p = V(
82
- async (d) => {
83
- const s = await (await z.getInstance(m)).fetch(
84
- A.ContactMethod,
85
- {
86
- contactMethodId: d,
87
- guideId: e
88
- },
89
- { noCache: !0, isBot: !0 }
90
- ), b = $(s, {
91
- submit: "Submit",
92
- errors: {},
93
- meta: { groupId: c }
94
- });
95
- if (s.body = b, s.body.guideId = e, !u.current)
96
- return null;
97
- n(s);
98
- },
99
- // eslint-disable-next-line react-hooks/exhaustive-deps
100
- [u]
101
- );
102
- return S(() => (p(a), () => {
103
- u.current = !1;
104
- }), [a, p]), t ? /* @__PURE__ */ E(
105
- q,
106
- {
107
- ...t,
108
- body: {
109
- ...t.body,
110
- form: t.body.form ? {
111
- ...t.body.form,
112
- data: (h = t.body.form) == null ? void 0 : h.data,
113
- layout: { ...t.body.form.layout },
114
- meta: (C = t.body.form) == null ? void 0 : C.meta,
115
- schema: (v = t.body.form) == null ? void 0 : v.schema
116
- } : void 0,
117
- guideId: t.body.guideId
118
- },
119
- inline: !0,
120
- expanded: !0,
121
- dispatch: B,
122
- className: k("humany-bot-contact-method", x)
123
- }
124
- ) : null;
125
- }, q = F(N)`
126
- padding: ${(a) => {
127
- var e;
128
- return (e = a.theme.sizes) == null ? void 0 : e.normal;
129
- }} ${(a) => {
130
- var e;
131
- return (e = a.theme.sizes) == null ? void 0 : e.medium;
132
- }};
133
- `;
134
- export {
135
- ot as default
136
- };
@@ -1,3 +0,0 @@
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"),B=require("@telia-ace/knowledge-widget-adapters"),p=require("@telia-ace/knowledge-widget-ui"),R=require("@telia-ace/widget-forms"),T=require("@telia-ace/widget-utilities"),u=require("react"),k=require("./index-bc0e69f0.js");require("@telia-ace/widget-conversation");require("@telia-ace/widget-services");require("@webprovisions/platform");const $=({contactMethodId:n,guideId:o,groupId:m,className:x})=>{var C,v,w;const[e,s]=u.useState(),d=p.useContainer(),D=p.useDispatch(),b=u.useRef(!0),l=p.useConversation();u.useEffect(()=>{const{events:c}=d.get("$widget"),q=c.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 R.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=c.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=u.useCallback(async c=>{const a=await(await F.DataClient.getInstance(d)).fetch(F.DataType.ContactMethod,{contactMethodId:c,guideId:o},{noCache:!0,isBot:!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 u.useEffect(()=>(g(n),()=>{b.current=!1}),[n,g]),e?j.jsx(z,{...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:T.appendClassNames("humany-bot-contact-method",x)}):null},z=A(B.ContactMethod)`
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
- `;exports.default=$;