@botpress/webchat-client 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.eslintrc.cjs +11 -0
- package/.turbo/turbo-build.log +28 -0
- package/dist/index.d.ts +2685 -0
- package/dist/webchat-client.js +5 -0
- package/dist/webchat-client2.js +84 -0
- package/dist/webchat-client3.js +116 -0
- package/dist/webchat-client4.js +8 -0
- package/dist/webchat-client5.js +272 -0
- package/dist/webchat-client6.js +23 -0
- package/dist/webchat-client7.js +11 -0
- package/dist/webchat-client8.js +105 -0
- package/dist/webchat-client9.js +218 -0
- package/openapi-ts.config.ts +8 -0
- package/package.json +41 -0
- package/src/client/client.ts +193 -0
- package/src/client/config.ts +15 -0
- package/src/client/eventEmitter.ts +36 -0
- package/src/client/index.ts +2 -0
- package/src/client/types/index.ts +0 -0
- package/src/client/types/signals/custom.ts +8 -0
- package/src/client/types/signals/index.ts +16 -0
- package/src/client/types/signals/messageCreated.ts +201 -0
- package/src/client/types/signals/messageUpdated.ts +201 -0
- package/src/client/types/signals/typingStarted.ts +6 -0
- package/src/client/types/signals/typingStopped.ts +4 -0
- package/src/client/types/signals/webchatConfig.ts +8 -0
- package/src/client/types/signals/webchatVisibility.ts +6 -0
- package/src/index.ts +2 -0
- package/tsconfig.json +12 -0
- package/vite.config.ts +19 -0
@@ -0,0 +1,218 @@
|
|
1
|
+
var R = Object.defineProperty;
|
2
|
+
var T = (t, r, e) => r in t ? R(t, r, { enumerable: !0, configurable: !0, writable: !0, value: e }) : t[r] = e;
|
3
|
+
var j = (t, r, e) => T(t, typeof r != "symbol" ? r + "" : r, e);
|
4
|
+
var U = async (t, r) => {
|
5
|
+
let e = typeof r == "function" ? await r(t) : r;
|
6
|
+
if (e) return t.scheme === "bearer" ? `Bearer ${e}` : t.scheme === "basic" ? `Basic ${btoa(e)}` : e;
|
7
|
+
}, A = { bodySerializer: (t) => JSON.stringify(t, (r, e) => typeof e == "bigint" ? e.toString() : e) }, _ = (t) => {
|
8
|
+
switch (t) {
|
9
|
+
case "label":
|
10
|
+
return ".";
|
11
|
+
case "matrix":
|
12
|
+
return ";";
|
13
|
+
case "simple":
|
14
|
+
return ",";
|
15
|
+
default:
|
16
|
+
return "&";
|
17
|
+
}
|
18
|
+
}, z = (t) => {
|
19
|
+
switch (t) {
|
20
|
+
case "form":
|
21
|
+
return ",";
|
22
|
+
case "pipeDelimited":
|
23
|
+
return "|";
|
24
|
+
case "spaceDelimited":
|
25
|
+
return "%20";
|
26
|
+
default:
|
27
|
+
return ",";
|
28
|
+
}
|
29
|
+
}, E = (t) => {
|
30
|
+
switch (t) {
|
31
|
+
case "label":
|
32
|
+
return ".";
|
33
|
+
case "matrix":
|
34
|
+
return ";";
|
35
|
+
case "simple":
|
36
|
+
return ",";
|
37
|
+
default:
|
38
|
+
return "&";
|
39
|
+
}
|
40
|
+
}, x = ({ allowReserved: t, explode: r, name: e, style: l, value: n }) => {
|
41
|
+
if (!r) {
|
42
|
+
let s = (t ? n : n.map((i) => encodeURIComponent(i))).join(z(l));
|
43
|
+
switch (l) {
|
44
|
+
case "label":
|
45
|
+
return `.${s}`;
|
46
|
+
case "matrix":
|
47
|
+
return `;${e}=${s}`;
|
48
|
+
case "simple":
|
49
|
+
return s;
|
50
|
+
default:
|
51
|
+
return `${e}=${s}`;
|
52
|
+
}
|
53
|
+
}
|
54
|
+
let o = _(l), a = n.map((s) => l === "label" || l === "simple" ? t ? s : encodeURIComponent(s) : b({ allowReserved: t, name: e, value: s })).join(o);
|
55
|
+
return l === "label" || l === "matrix" ? o + a : a;
|
56
|
+
}, b = ({ allowReserved: t, name: r, value: e }) => {
|
57
|
+
if (e == null) return "";
|
58
|
+
if (typeof e == "object") throw new Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");
|
59
|
+
return `${r}=${t ? e : encodeURIComponent(e)}`;
|
60
|
+
}, $ = ({ allowReserved: t, explode: r, name: e, style: l, value: n }) => {
|
61
|
+
if (n instanceof Date) return `${e}=${n.toISOString()}`;
|
62
|
+
if (l !== "deepObject" && !r) {
|
63
|
+
let s = [];
|
64
|
+
Object.entries(n).forEach(([d, f]) => {
|
65
|
+
s = [...s, d, t ? f : encodeURIComponent(f)];
|
66
|
+
});
|
67
|
+
let i = s.join(",");
|
68
|
+
switch (l) {
|
69
|
+
case "form":
|
70
|
+
return `${e}=${i}`;
|
71
|
+
case "label":
|
72
|
+
return `.${i}`;
|
73
|
+
case "matrix":
|
74
|
+
return `;${e}=${i}`;
|
75
|
+
default:
|
76
|
+
return i;
|
77
|
+
}
|
78
|
+
}
|
79
|
+
let o = E(l), a = Object.entries(n).map(([s, i]) => b({ allowReserved: t, name: l === "deepObject" ? `${e}[${s}]` : s, value: i })).join(o);
|
80
|
+
return l === "label" || l === "matrix" ? o + a : a;
|
81
|
+
}, W = /\{[^{}]+\}/g, D = ({ path: t, url: r }) => {
|
82
|
+
let e = r, l = r.match(W);
|
83
|
+
if (l) for (let n of l) {
|
84
|
+
let o = !1, a = n.substring(1, n.length - 1), s = "simple";
|
85
|
+
a.endsWith("*") && (o = !0, a = a.substring(0, a.length - 1)), a.startsWith(".") ? (a = a.substring(1), s = "label") : a.startsWith(";") && (a = a.substring(1), s = "matrix");
|
86
|
+
let i = t[a];
|
87
|
+
if (i == null) continue;
|
88
|
+
if (Array.isArray(i)) {
|
89
|
+
e = e.replace(n, x({ explode: o, name: a, style: s, value: i }));
|
90
|
+
continue;
|
91
|
+
}
|
92
|
+
if (typeof i == "object") {
|
93
|
+
e = e.replace(n, $({ explode: o, name: a, style: s, value: i }));
|
94
|
+
continue;
|
95
|
+
}
|
96
|
+
if (s === "matrix") {
|
97
|
+
e = e.replace(n, `;${b({ name: a, value: i })}`);
|
98
|
+
continue;
|
99
|
+
}
|
100
|
+
let d = encodeURIComponent(s === "label" ? `.${i}` : i);
|
101
|
+
e = e.replace(n, d);
|
102
|
+
}
|
103
|
+
return e;
|
104
|
+
}, q = ({ allowReserved: t, array: r, object: e } = {}) => (l) => {
|
105
|
+
let n = [];
|
106
|
+
if (l && typeof l == "object") for (let o in l) {
|
107
|
+
let a = l[o];
|
108
|
+
if (a != null) {
|
109
|
+
if (Array.isArray(a)) {
|
110
|
+
n = [...n, x({ allowReserved: t, explode: !0, name: o, style: "form", value: a, ...r })];
|
111
|
+
continue;
|
112
|
+
}
|
113
|
+
if (typeof a == "object") {
|
114
|
+
n = [...n, $({ allowReserved: t, explode: !0, name: o, style: "deepObject", value: a, ...e })];
|
115
|
+
continue;
|
116
|
+
}
|
117
|
+
n = [...n, b({ allowReserved: t, name: o, value: a })];
|
118
|
+
}
|
119
|
+
}
|
120
|
+
return n.join("&");
|
121
|
+
}, I = (t) => {
|
122
|
+
var e;
|
123
|
+
if (!t) return "stream";
|
124
|
+
let r = (e = t.split(";")[0]) == null ? void 0 : e.trim();
|
125
|
+
if (r) {
|
126
|
+
if (r.startsWith("application/json") || r.endsWith("+json")) return "json";
|
127
|
+
if (r === "multipart/form-data") return "formData";
|
128
|
+
if (["application/", "audio/", "image/", "video/"].some((l) => r.startsWith(l))) return "blob";
|
129
|
+
if (r.startsWith("text/")) return "text";
|
130
|
+
}
|
131
|
+
}, k = async ({ security: t, ...r }) => {
|
132
|
+
for (let e of t) {
|
133
|
+
let l = await U(e, r.auth);
|
134
|
+
if (!l) continue;
|
135
|
+
let n = e.name ?? "Authorization";
|
136
|
+
switch (e.in) {
|
137
|
+
case "query":
|
138
|
+
r.query || (r.query = {}), r.query[n] = l;
|
139
|
+
break;
|
140
|
+
case "cookie":
|
141
|
+
r.headers.append("Cookie", `${n}=${l}`);
|
142
|
+
break;
|
143
|
+
case "header":
|
144
|
+
default:
|
145
|
+
r.headers.set(n, l);
|
146
|
+
break;
|
147
|
+
}
|
148
|
+
return;
|
149
|
+
}
|
150
|
+
}, v = (t) => N({ baseUrl: t.baseUrl, path: t.path, query: t.query, querySerializer: typeof t.querySerializer == "function" ? t.querySerializer : q(t.querySerializer), url: t.url }), N = ({ baseUrl: t, path: r, query: e, querySerializer: l, url: n }) => {
|
151
|
+
let o = n.startsWith("/") ? n : `/${n}`, a = (t ?? "") + o;
|
152
|
+
r && (a = D({ path: r, url: a }));
|
153
|
+
let s = e ? l(e) : "";
|
154
|
+
return s.startsWith("?") && (s = s.substring(1)), s && (a += `?${s}`), a;
|
155
|
+
}, g = (t, r) => {
|
156
|
+
var l;
|
157
|
+
let e = { ...t, ...r };
|
158
|
+
return (l = e.baseUrl) != null && l.endsWith("/") && (e.baseUrl = e.baseUrl.substring(0, e.baseUrl.length - 1)), e.headers = C(t.headers, r.headers), e;
|
159
|
+
}, C = (...t) => {
|
160
|
+
let r = new Headers();
|
161
|
+
for (let e of t) {
|
162
|
+
if (!e || typeof e != "object") continue;
|
163
|
+
let l = e instanceof Headers ? e.entries() : Object.entries(e);
|
164
|
+
for (let [n, o] of l) if (o === null) r.delete(n);
|
165
|
+
else if (Array.isArray(o)) for (let a of o) r.append(n, a);
|
166
|
+
else o !== void 0 && r.set(n, typeof o == "object" ? JSON.stringify(o) : o);
|
167
|
+
}
|
168
|
+
return r;
|
169
|
+
}, w = class {
|
170
|
+
constructor() {
|
171
|
+
j(this, "_fns");
|
172
|
+
this._fns = [];
|
173
|
+
}
|
174
|
+
clear() {
|
175
|
+
this._fns = [];
|
176
|
+
}
|
177
|
+
exists(t) {
|
178
|
+
return this._fns.indexOf(t) !== -1;
|
179
|
+
}
|
180
|
+
eject(t) {
|
181
|
+
let r = this._fns.indexOf(t);
|
182
|
+
r !== -1 && (this._fns = [...this._fns.slice(0, r), ...this._fns.slice(r + 1)]);
|
183
|
+
}
|
184
|
+
use(t) {
|
185
|
+
this._fns = [...this._fns, t];
|
186
|
+
}
|
187
|
+
}, P = () => ({ error: new w(), request: new w(), response: new w() }), H = /* @__PURE__ */ q({ allowReserved: !1, array: { explode: !0, style: "form" }, object: { explode: !0, style: "deepObject" } }), J = { "Content-Type": "application/json" }, O = (t = {}) => ({ ...A, headers: J, parseAs: "auto", querySerializer: H, ...t }), B = (t = {}) => {
|
188
|
+
let r = g(O(), t), e = () => ({ ...r }), l = (a) => (r = g(r, a), e()), n = P(), o = async (a) => {
|
189
|
+
let s = { ...r, ...a, fetch: a.fetch ?? r.fetch ?? globalThis.fetch, headers: C(r.headers, a.headers) };
|
190
|
+
s.security && await k({ ...s, security: s.security }), s.body && s.bodySerializer && (s.body = s.bodySerializer(s.body)), (s.body === void 0 || s.body === "") && s.headers.delete("Content-Type");
|
191
|
+
let i = v(s), d = { redirect: "follow", ...s }, f = new Request(i, d);
|
192
|
+
for (let c of n.request._fns) f = await c(f, s);
|
193
|
+
let S = s.fetch, u = await S(f);
|
194
|
+
for (let c of n.response._fns) u = await c(u, f, s);
|
195
|
+
let h = { request: f, response: u };
|
196
|
+
if (u.ok) {
|
197
|
+
if (u.status === 204 || u.headers.get("Content-Length") === "0") return { data: {}, ...h };
|
198
|
+
let c = (s.parseAs === "auto" ? I(u.headers.get("Content-Type")) : s.parseAs) ?? "json";
|
199
|
+
if (c === "stream") return { data: u.body, ...h };
|
200
|
+
let m = await u[c]();
|
201
|
+
return c === "json" && (s.responseValidator && await s.responseValidator(m), s.responseTransformer && (m = await s.responseTransformer(m))), { data: m, ...h };
|
202
|
+
}
|
203
|
+
let y = await u.text();
|
204
|
+
try {
|
205
|
+
y = JSON.parse(y);
|
206
|
+
} catch {
|
207
|
+
}
|
208
|
+
let p = y;
|
209
|
+
for (let c of n.error._fns) p = await c(y, u, f, s);
|
210
|
+
if (p = p || {}, s.throwOnError) throw p;
|
211
|
+
return { error: p, ...h };
|
212
|
+
};
|
213
|
+
return { buildUrl: v, connect: (a) => o({ ...a, method: "CONNECT" }), delete: (a) => o({ ...a, method: "DELETE" }), get: (a) => o({ ...a, method: "GET" }), getConfig: e, head: (a) => o({ ...a, method: "HEAD" }), interceptors: n, options: (a) => o({ ...a, method: "OPTIONS" }), patch: (a) => o({ ...a, method: "PATCH" }), post: (a) => o({ ...a, method: "POST" }), put: (a) => o({ ...a, method: "PUT" }), request: o, setConfig: l, trace: (a) => o({ ...a, method: "TRACE" }) };
|
214
|
+
}, V = B, G = O;
|
215
|
+
export {
|
216
|
+
V as createClient,
|
217
|
+
G as createConfig
|
218
|
+
};
|
@@ -0,0 +1,8 @@
|
|
1
|
+
import { defineConfig } from '@hey-api/openapi-ts'
|
2
|
+
import openapi from '@bpinternal/webchat-http-client/src/gen/openapi.json'
|
3
|
+
|
4
|
+
export default defineConfig({
|
5
|
+
input: openapi,
|
6
|
+
output: 'src/gen/client',
|
7
|
+
plugins: [{ name: '@hey-api/client-fetch', bundle: true, runtimeConfigPath: './src/client/config.ts' }],
|
8
|
+
})
|
package/package.json
ADDED
@@ -0,0 +1,41 @@
|
|
1
|
+
{
|
2
|
+
"name": "@botpress/webchat-client",
|
3
|
+
"version": "0.1.0",
|
4
|
+
"description": "",
|
5
|
+
"main": "src/index.ts",
|
6
|
+
"type": "module",
|
7
|
+
"sideEffects": false,
|
8
|
+
"scripts": {
|
9
|
+
"build": "openapi-ts && vite build",
|
10
|
+
"check:lint": "eslint .",
|
11
|
+
"fix:lint": "eslint --fix .",
|
12
|
+
"check:type": "tsc --noEmit"
|
13
|
+
},
|
14
|
+
"types": "./dist/index.d.ts",
|
15
|
+
"module": "./dist/webchat-client.js",
|
16
|
+
"exports": {
|
17
|
+
".": {
|
18
|
+
"import": "./dist/webchat-client.js",
|
19
|
+
"types": "./dist/index.d.ts"
|
20
|
+
}
|
21
|
+
},
|
22
|
+
"keywords": [],
|
23
|
+
"author": "",
|
24
|
+
"license": "ISC",
|
25
|
+
"dependencies": {
|
26
|
+
"eventsource": "^3.0.6"
|
27
|
+
},
|
28
|
+
"devDependencies": {
|
29
|
+
"@bpinternal/webchat-http-client": "0.2.6",
|
30
|
+
"@hey-api/client-fetch": "^0.10.0",
|
31
|
+
"@hey-api/openapi-ts": "^0.66.4",
|
32
|
+
"@repo/eslint-config": "workspace:*",
|
33
|
+
"@repo/typescript-config": "workspace:*",
|
34
|
+
"@types/event-source-polyfill": "^1.0.2",
|
35
|
+
"esbuild": "^0.16.12",
|
36
|
+
"glob": "^11.0.1",
|
37
|
+
"rollup-plugin-tree-shakeable": "^1.0.3",
|
38
|
+
"vite": "^5.4.8",
|
39
|
+
"vite-plugin-dts": "^3.5.4"
|
40
|
+
}
|
41
|
+
}
|
@@ -0,0 +1,193 @@
|
|
1
|
+
import type * as ClientTypes from '../gen/client'
|
2
|
+
import * as sdk from '../gen/client/sdk.gen'
|
3
|
+
import { client as baseClient } from '../gen/client/client.gen'
|
4
|
+
import { EventSource } from 'eventsource'
|
5
|
+
import type { Signal } from './types/signals'
|
6
|
+
import { EventEmitter } from './eventEmitter'
|
7
|
+
|
8
|
+
type ConversationIdParam = {
|
9
|
+
conversationId: string
|
10
|
+
}
|
11
|
+
|
12
|
+
type NextTokenParam = {
|
13
|
+
nextToken?: string
|
14
|
+
}
|
15
|
+
|
16
|
+
type UserIdParam = {
|
17
|
+
userId: string
|
18
|
+
}
|
19
|
+
|
20
|
+
type MessageIdParam = {
|
21
|
+
messageId: string
|
22
|
+
}
|
23
|
+
|
24
|
+
type EventIdParam = {
|
25
|
+
eventId: string
|
26
|
+
}
|
27
|
+
|
28
|
+
const extractData = <T>(res: { data: T }): T => res.data
|
29
|
+
|
30
|
+
type Event =
|
31
|
+
| Signal
|
32
|
+
| {
|
33
|
+
type: 'error'
|
34
|
+
data: any
|
35
|
+
}
|
36
|
+
| {
|
37
|
+
type: 'open'
|
38
|
+
data: any
|
39
|
+
}
|
40
|
+
|
41
|
+
export type Client = {
|
42
|
+
createConversation: () => Promise<ClientTypes.CreateConversationResponse>
|
43
|
+
getConversation: (params: ConversationIdParam) => Promise<ClientTypes.GetConversationResponse>
|
44
|
+
deleteConversation: (params: ConversationIdParam) => Promise<ClientTypes.DeleteConversationResponse>
|
45
|
+
listConversations: (params: NextTokenParam) => Promise<ClientTypes.ListConversationsResponse>
|
46
|
+
listConversationMessages: (
|
47
|
+
params: ConversationIdParam & NextTokenParam
|
48
|
+
) => Promise<ClientTypes.ListConversationMessagesResponse>
|
49
|
+
addParticipant: (params: ConversationIdParam & UserIdParam) => Promise<ClientTypes.AddParticipantResponse>
|
50
|
+
removeParticipant: (params: ConversationIdParam & UserIdParam) => Promise<ClientTypes.RemoveParticipantResponse>
|
51
|
+
getParticipant: (params: ConversationIdParam & UserIdParam) => Promise<ClientTypes.GetParticipantResponse>
|
52
|
+
listParticipants: (params: ConversationIdParam & NextTokenParam) => Promise<ClientTypes.ListParticipantsResponse>
|
53
|
+
createMessage: (params: ClientTypes.CreateMessageBody) => Promise<ClientTypes.CreateMessageResponse>
|
54
|
+
updateMessage: (params: MessageIdParam & ClientTypes.UpdateMessageBody) => Promise<ClientTypes.UpdateMessageResponse>
|
55
|
+
getMessage: (params: MessageIdParam) => Promise<ClientTypes.GetMessageResponse>
|
56
|
+
deleteMessage: (params: MessageIdParam) => Promise<ClientTypes.DeleteMessageResponse>
|
57
|
+
createFile: (params: ClientTypes.CreateFileBody) => Promise<ClientTypes.CreateFileResponse>
|
58
|
+
createUser: (params: ClientTypes.CreateUserBody) => Promise<ClientTypes.CreateUserResponse>
|
59
|
+
getUser: (params: UserIdParam) => Promise<ClientTypes.GetUserResponse>
|
60
|
+
updateUser: (params: ClientTypes.CreateUserBody) => Promise<ClientTypes.UpdateUserResponse>
|
61
|
+
deleteUser: (params: UserIdParam) => Promise<ClientTypes.DeleteUserResponse>
|
62
|
+
createEvent: (params: ClientTypes.CreateEventBody) => Promise<ClientTypes.CreateEventResponse>
|
63
|
+
getEvent: (params: EventIdParam) => Promise<ClientTypes.GetEventResponse>
|
64
|
+
listenConversation: (params: ConversationIdParam) => EventEmitter<Record<Event['type'], Event['data']>>['on']
|
65
|
+
}
|
66
|
+
const baseConfigs = {
|
67
|
+
throwOnError: true,
|
68
|
+
} as const satisfies sdk.Options
|
69
|
+
|
70
|
+
export const createUser = ({ clientId, apiUrl }: { clientId: string; apiUrl?: string }) => {
|
71
|
+
const baseUrl = `${apiUrl || baseClient.getConfig().baseUrl}/${clientId}`
|
72
|
+
|
73
|
+
const configs = {
|
74
|
+
...baseConfigs,
|
75
|
+
baseUrl,
|
76
|
+
}
|
77
|
+
return sdk.createUser({ ...configs, body: {} }).then(extractData)
|
78
|
+
}
|
79
|
+
|
80
|
+
export const createClient = ({
|
81
|
+
userKey,
|
82
|
+
clientId,
|
83
|
+
apiUrl,
|
84
|
+
}: {
|
85
|
+
userKey: string
|
86
|
+
clientId: string
|
87
|
+
apiUrl?: string
|
88
|
+
}): Client => {
|
89
|
+
const headers = {
|
90
|
+
'x-user-key': userKey,
|
91
|
+
}
|
92
|
+
|
93
|
+
const baseUrl = `${apiUrl || baseClient.getConfig().baseUrl}/${clientId}`
|
94
|
+
const configs = {
|
95
|
+
...baseConfigs,
|
96
|
+
baseUrl,
|
97
|
+
}
|
98
|
+
|
99
|
+
return {
|
100
|
+
createConversation: () => sdk.createConversation({ ...configs, headers, body: {} }).then(extractData),
|
101
|
+
getConversation: ({ conversationId }) =>
|
102
|
+
sdk.getConversation({ ...configs, headers, path: { id: conversationId } }).then(extractData),
|
103
|
+
deleteConversation: ({ conversationId }) =>
|
104
|
+
sdk.deleteConversation({ ...configs, headers, path: { id: conversationId } }).then(extractData),
|
105
|
+
listConversations: ({ nextToken }) =>
|
106
|
+
sdk.listConversations({ ...configs, headers, query: { nextToken } }).then(extractData),
|
107
|
+
listConversationMessages: ({ conversationId, nextToken }) =>
|
108
|
+
sdk
|
109
|
+
.listConversationMessages({
|
110
|
+
...configs,
|
111
|
+
headers,
|
112
|
+
path: { id: conversationId },
|
113
|
+
query: { nextToken },
|
114
|
+
})
|
115
|
+
.then(extractData),
|
116
|
+
addParticipant: ({ conversationId, userId }) =>
|
117
|
+
sdk.addParticipant({ ...configs, headers, path: { id: conversationId }, body: { userId } }).then(extractData),
|
118
|
+
removeParticipant: ({ conversationId, userId }) =>
|
119
|
+
sdk.removeParticipant({ ...configs, headers, path: { id: conversationId, userId } }).then(extractData),
|
120
|
+
getParticipant: ({ conversationId, userId }) =>
|
121
|
+
sdk.getParticipant({ ...configs, headers, path: { id: conversationId, userId } }).then(extractData),
|
122
|
+
listParticipants: ({ conversationId, nextToken }) =>
|
123
|
+
sdk
|
124
|
+
.listParticipants({ ...configs, headers, path: { id: conversationId }, query: { nextToken } })
|
125
|
+
.then(extractData),
|
126
|
+
createMessage: (body) => sdk.createMessage({ ...configs, headers, body }).then(extractData),
|
127
|
+
updateMessage: ({ messageId, ...body }) =>
|
128
|
+
sdk.updateMessage({ ...configs, headers, path: { id: messageId }, body }).then(extractData),
|
129
|
+
getMessage: ({ messageId }) => sdk.getMessage({ ...configs, headers, path: { id: messageId } }).then(extractData),
|
130
|
+
deleteMessage: ({ messageId }) =>
|
131
|
+
sdk.deleteMessage({ ...configs, headers, path: { id: messageId } }).then(extractData),
|
132
|
+
createFile: (body) => sdk.createFile({ ...configs, headers, body }).then(extractData),
|
133
|
+
createUser: (body) => sdk.createUser({ ...configs, headers, body }).then(extractData),
|
134
|
+
getUser: () => sdk.getUser({ ...configs, headers }).then(extractData),
|
135
|
+
updateUser: (body) => sdk.updateUser({ ...configs, headers, body }).then(extractData),
|
136
|
+
deleteUser: () => sdk.deleteUser({ ...configs, headers }).then(extractData),
|
137
|
+
createEvent: (body) => sdk.createEvent({ ...configs, headers, body }).then(extractData),
|
138
|
+
getEvent: ({ eventId }) => sdk.getEvent({ ...configs, headers, path: { id: eventId } }).then(extractData),
|
139
|
+
listenConversation: ({ conversationId }) => {
|
140
|
+
const MAX_RETRIES = 5
|
141
|
+
const RETRY_INTERVAL = 3000 // ms
|
142
|
+
let retryCount = 0
|
143
|
+
let eventSource: EventSource | null = null
|
144
|
+
const eventEmitter = new EventEmitter<Record<Event['type'], Event['data']>>()
|
145
|
+
|
146
|
+
const connect = () => {
|
147
|
+
if (eventSource) {
|
148
|
+
eventSource.close()
|
149
|
+
}
|
150
|
+
|
151
|
+
const url = `${baseUrl}/conversations/${conversationId}/listen`
|
152
|
+
|
153
|
+
eventSource = new EventSource(url, {
|
154
|
+
fetch: (input, init) =>
|
155
|
+
fetch(input, {
|
156
|
+
...init,
|
157
|
+
headers: {
|
158
|
+
...init?.headers,
|
159
|
+
...headers,
|
160
|
+
timeout: '60_000',
|
161
|
+
},
|
162
|
+
}),
|
163
|
+
})
|
164
|
+
|
165
|
+
eventSource.onopen = () => eventEmitter.emit('open')
|
166
|
+
eventSource.onerror = (err) => {
|
167
|
+
eventEmitter.emit('error', err)
|
168
|
+
|
169
|
+
// Attempt reconnect with limit
|
170
|
+
if (retryCount < MAX_RETRIES) {
|
171
|
+
retryCount++
|
172
|
+
// todo: fix this
|
173
|
+
// setTimeout(() => connect(), RETRY_INTERVAL)
|
174
|
+
}
|
175
|
+
}
|
176
|
+
eventSource.onmessage = (ev) => {
|
177
|
+
const event = safeJsonParse(ev.data) as Signal
|
178
|
+
eventEmitter.emit(event.type, event.data)
|
179
|
+
}
|
180
|
+
}
|
181
|
+
connect()
|
182
|
+
return eventEmitter.on.bind(eventEmitter)
|
183
|
+
},
|
184
|
+
}
|
185
|
+
}
|
186
|
+
|
187
|
+
const safeJsonParse = (data: any) => {
|
188
|
+
try {
|
189
|
+
return JSON.parse(data)
|
190
|
+
} catch {
|
191
|
+
return data
|
192
|
+
}
|
193
|
+
}
|
@@ -0,0 +1,15 @@
|
|
1
|
+
import type { CreateClientConfig } from '../gen/client/client.gen'
|
2
|
+
|
3
|
+
const _100mb = 100 * 1024 * 1024
|
4
|
+
const maxBodyLength = _100mb
|
5
|
+
const maxContentLength = _100mb
|
6
|
+
const defaultHttpTimeout = 60_000
|
7
|
+
|
8
|
+
export const createClientConfig: CreateClientConfig = (config) => ({
|
9
|
+
...config,
|
10
|
+
withCredentials: true,
|
11
|
+
timeout: defaultHttpTimeout,
|
12
|
+
maxBodyLength,
|
13
|
+
maxContentLength,
|
14
|
+
throwOnError: true,
|
15
|
+
})
|
@@ -0,0 +1,36 @@
|
|
1
|
+
type CallbackFn<T> = (args: T) => void
|
2
|
+
|
3
|
+
export class EventEmitter<T extends Record<string, any>> {
|
4
|
+
private readonly eventMap: Partial<Record<keyof T, Set<CallbackFn<any>>>>
|
5
|
+
|
6
|
+
constructor() {
|
7
|
+
this.eventMap = {}
|
8
|
+
}
|
9
|
+
|
10
|
+
on<U extends keyof T>(event: U, callback: CallbackFn<T[U]>): () => void {
|
11
|
+
if (!this.eventMap[event]) {
|
12
|
+
this.eventMap[event] = new Set<CallbackFn<T[U]>>()
|
13
|
+
}
|
14
|
+
this.eventMap[event]?.add(callback)
|
15
|
+
|
16
|
+
return () => {
|
17
|
+
this.eventMap[event]?.delete(callback)
|
18
|
+
}
|
19
|
+
}
|
20
|
+
|
21
|
+
emit<U extends keyof T>(event: U, arg?: T[U]): void {
|
22
|
+
this.eventMap[event]?.forEach((callback) => {
|
23
|
+
callback(arg)
|
24
|
+
})
|
25
|
+
|
26
|
+
this.eventMap['*']?.forEach((callback) => {
|
27
|
+
callback({ type: event, payload: arg })
|
28
|
+
})
|
29
|
+
}
|
30
|
+
}
|
31
|
+
|
32
|
+
export type Events = {
|
33
|
+
[key: string]: undefined
|
34
|
+
}
|
35
|
+
|
36
|
+
export const eventEmitter = new EventEmitter<Events>()
|
File without changes
|
@@ -0,0 +1,16 @@
|
|
1
|
+
import type { Custom } from './custom'
|
2
|
+
import type { MessageCreated } from './messageCreated'
|
3
|
+
import type { MessageUpdated } from './messageUpdated'
|
4
|
+
import type { TypingStarted } from './typingStarted'
|
5
|
+
import type { TypingStopped } from './typingStopped'
|
6
|
+
import type { WebchatConfig } from './webchatConfig'
|
7
|
+
import type { WebchatVisibility } from './webchatVisibility'
|
8
|
+
|
9
|
+
export type Signal =
|
10
|
+
| MessageCreated
|
11
|
+
| MessageUpdated
|
12
|
+
| WebchatVisibility
|
13
|
+
| WebchatConfig
|
14
|
+
| Custom
|
15
|
+
| TypingStarted
|
16
|
+
| TypingStopped
|