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