@figoailabs/figochat-react-native 0.0.0-stage → 1.0.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/CHANGELOG.md +10 -0
- package/LICENSE +21 -0
- package/README.md +124 -2
- package/lib/FigoChat.d.ts +24 -0
- package/lib/FigoChat.js +76 -0
- package/lib/FigoChatView.d.ts +26 -0
- package/lib/FigoChatView.js +417 -0
- package/lib/client.d.ts +49 -0
- package/lib/client.js +211 -0
- package/lib/colors.d.ts +4 -0
- package/lib/colors.js +27 -0
- package/lib/crypto.d.ts +13 -0
- package/lib/crypto.js +58 -0
- package/lib/html.d.ts +6 -0
- package/lib/html.js +23 -0
- package/lib/icons.d.ts +17 -0
- package/lib/icons.js +48 -0
- package/lib/index.d.ts +9 -0
- package/lib/index.js +17 -0
- package/lib/messages.d.ts +8 -0
- package/lib/messages.js +37 -0
- package/lib/realtime.d.ts +36 -0
- package/lib/realtime.js +81 -0
- package/lib/types.d.ts +77 -0
- package/lib/types.js +2 -0
- package/package.json +56 -4
- package/src/FigoChat.ts +92 -0
- package/src/FigoChatView.tsx +650 -0
- package/src/client.ts +246 -0
- package/src/colors.ts +24 -0
- package/src/crypto.ts +58 -0
- package/src/html.ts +20 -0
- package/src/icons.tsx +64 -0
- package/src/index.ts +17 -0
- package/src/messages.ts +40 -0
- package/src/realtime.ts +91 -0
- package/src/types.ts +85 -0
package/src/client.ts
ADDED
|
@@ -0,0 +1,246 @@
|
|
|
1
|
+
import type {
|
|
2
|
+
DefaultServiceResponse,
|
|
3
|
+
FigoChatConfig,
|
|
4
|
+
FigoChatReply,
|
|
5
|
+
FigoLocalFile,
|
|
6
|
+
FigoRealtimeConfig,
|
|
7
|
+
} from './types';
|
|
8
|
+
|
|
9
|
+
export const DEFAULT_BASE_URL = 'https://api.figolabs.ai';
|
|
10
|
+
|
|
11
|
+
const RESPONSE_CODE_SUCCESS = '00';
|
|
12
|
+
const RESPONSE_CODE_LIMIT_REACHED = '49';
|
|
13
|
+
const HEADER_THREAD_ID = 'x-thread-id';
|
|
14
|
+
const HEADER_THREAD_MODE = 'x-thread-mode';
|
|
15
|
+
|
|
16
|
+
/** Error thrown by every SDK call. `code` is the API response code or the HTTP status. */
|
|
17
|
+
export class FigoChatError extends Error {
|
|
18
|
+
readonly code: string;
|
|
19
|
+
/** The underlying error (e.g. the fetch failure), when there is one. */
|
|
20
|
+
readonly cause?: unknown;
|
|
21
|
+
constructor(message: string, code: string, cause?: unknown) {
|
|
22
|
+
super(message);
|
|
23
|
+
this.name = 'FigoChatError';
|
|
24
|
+
this.code = code;
|
|
25
|
+
this.cause = cause;
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Thin client over the Figo AI public REST APIs:
|
|
31
|
+
* - POST /api/v1/chat/assistant/{assistantId} chat with the assistant
|
|
32
|
+
* - POST /api/v1/stt speech to text (multipart, field `audio`)
|
|
33
|
+
* - POST /api/v1/cdn/upload/ocr/{assistantId} upload files to the CDN (images are OCR'd)
|
|
34
|
+
*/
|
|
35
|
+
export class FigoChatClient {
|
|
36
|
+
private threadId?: string;
|
|
37
|
+
private threadMode?: string;
|
|
38
|
+
|
|
39
|
+
constructor(private readonly config: FigoChatConfig) {
|
|
40
|
+
this.threadId = config.threadId;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** Thread id of the current conversation, once the first reply has arrived. */
|
|
44
|
+
getThreadId(): string | undefined {
|
|
45
|
+
return this.threadId;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** `ai` or `liveagent`. */
|
|
49
|
+
getThreadMode(): string | undefined {
|
|
50
|
+
return this.threadMode;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** Forget the current thread so the next message starts a new conversation. */
|
|
54
|
+
resetThread(): void {
|
|
55
|
+
this.threadId = undefined;
|
|
56
|
+
this.threadMode = undefined;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Sends a message to the assistant. CDN urls of uploaded files are appended to the question
|
|
61
|
+
* so the assistant can read them (the API adds the OCR text of uploaded images).
|
|
62
|
+
*/
|
|
63
|
+
async sendMessage(text: string, attachmentUrls: string[] = []): Promise<FigoChatReply> {
|
|
64
|
+
const question = [text.trim(), ...attachmentUrls].filter(Boolean).join('\n');
|
|
65
|
+
if (!question) throw new FigoChatError('Message is empty.', 'EMPTY');
|
|
66
|
+
|
|
67
|
+
const res = await this.request(
|
|
68
|
+
`/api/v1/chat/assistant/${encodeURIComponent(this.config.assistantId)}`,
|
|
69
|
+
{
|
|
70
|
+
method: 'POST',
|
|
71
|
+
headers: { 'Content-Type': 'application/json' },
|
|
72
|
+
body: JSON.stringify({
|
|
73
|
+
question,
|
|
74
|
+
threadId: this.threadId,
|
|
75
|
+
fullName: this.config.fullName,
|
|
76
|
+
emailAddress: this.config.emailAddress,
|
|
77
|
+
phoneNumber: this.config.mobilePhone,
|
|
78
|
+
}),
|
|
79
|
+
},
|
|
80
|
+
);
|
|
81
|
+
|
|
82
|
+
const body = await this.parse<string>(res);
|
|
83
|
+
const threadId = res.headers.get(HEADER_THREAD_ID) ?? undefined;
|
|
84
|
+
const threadMode = res.headers.get(HEADER_THREAD_MODE) ?? undefined;
|
|
85
|
+
if (threadId) this.threadId = threadId;
|
|
86
|
+
if (threadMode) this.threadMode = threadMode;
|
|
87
|
+
|
|
88
|
+
return { answer: body.responseData ?? '', threadId: this.threadId, threadMode: this.threadMode };
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** Transcribes a recorded audio file (e.g. the .m4a from the recorder) to text. */
|
|
92
|
+
async transcribe(file: FigoLocalFile): Promise<string> {
|
|
93
|
+
const mimeType = file.mimeType || 'audio/mp4';
|
|
94
|
+
const form = new FormData();
|
|
95
|
+
// React Native's FormData uploads a local file from {uri, name, type}
|
|
96
|
+
form.append('audio', { uri: file.uri, name: file.name, type: mimeType } as unknown as Blob);
|
|
97
|
+
|
|
98
|
+
// Sent with XMLHttpRequest, not fetch: Expo replaces the global fetch with an implementation that
|
|
99
|
+
// rejects {uri, name, type} file parts ("Unsupported FormDataPart implementation"); RN's native
|
|
100
|
+
// XMLHttpRequest still uploads them, in Expo and bare apps alike.
|
|
101
|
+
const { status, raw } = await this.upload(`/api/v1/stt?mimetype=${encodeURIComponent(mimeType)}`, form);
|
|
102
|
+
const body = this.parseRaw<string>(status, raw);
|
|
103
|
+
return (body.responseData ?? '').trim();
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* Uploads files to the CDN. Images are OCR'd by the API, so sending their urls in a chat message
|
|
108
|
+
* lets the assistant read them. Returns one url per file, in order.
|
|
109
|
+
*/
|
|
110
|
+
async uploadFiles(files: FigoLocalFile[]): Promise<string[]> {
|
|
111
|
+
if (files.length === 0) return [];
|
|
112
|
+
|
|
113
|
+
const payload = await Promise.all(
|
|
114
|
+
files.map(async (f) => ({ extension: extensionOf(f), base64String: await readAsBase64(f.uri) })),
|
|
115
|
+
);
|
|
116
|
+
|
|
117
|
+
const res = await this.request(
|
|
118
|
+
`/api/v1/cdn/upload/ocr/${encodeURIComponent(this.config.assistantId)}`,
|
|
119
|
+
{
|
|
120
|
+
method: 'POST',
|
|
121
|
+
headers: { 'Content-Type': 'application/json' },
|
|
122
|
+
body: JSON.stringify(payload),
|
|
123
|
+
},
|
|
124
|
+
);
|
|
125
|
+
// a partial failure still returns the urls that did upload, with null in the failed slots
|
|
126
|
+
const body = await this.parse<(string | null)[]>(res, true);
|
|
127
|
+
const urls = body.responseData ?? [];
|
|
128
|
+
if (urls.length === 0 || urls.some((u) => !u)) {
|
|
129
|
+
throw new FigoChatError(body.responseMessage || 'Upload failed.', body.responseCode);
|
|
130
|
+
}
|
|
131
|
+
return urls as string[];
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/** Public Pusher settings used to subscribe to the thread channel for live agent messages. */
|
|
135
|
+
async getRealtimeConfig(): Promise<FigoRealtimeConfig> {
|
|
136
|
+
const res = await this.request('/api/v1/realtime/config', { method: 'GET' });
|
|
137
|
+
const body = await this.parse<FigoRealtimeConfig>(res);
|
|
138
|
+
if (!body.responseData?.key || !body.responseData?.cluster) {
|
|
139
|
+
throw new FigoChatError('Realtime is not configured on the server.', 'REALTIME');
|
|
140
|
+
}
|
|
141
|
+
return body.responseData;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
private async request(path: string, init: RequestInit): Promise<Response> {
|
|
145
|
+
const base = (this.config.baseUrl || DEFAULT_BASE_URL).replace(/\/+$/, '');
|
|
146
|
+
const controller = new AbortController();
|
|
147
|
+
const timer = setTimeout(() => controller.abort(), this.config.timeoutMs ?? 120000);
|
|
148
|
+
try {
|
|
149
|
+
return await fetch(`${base}${path}`, {
|
|
150
|
+
...init,
|
|
151
|
+
headers: {
|
|
152
|
+
Accept: 'application/json',
|
|
153
|
+
...(init.headers as Record<string, string>),
|
|
154
|
+
Authorization: `Bearer ${this.config.apiKey}`,
|
|
155
|
+
},
|
|
156
|
+
signal: controller.signal,
|
|
157
|
+
});
|
|
158
|
+
} catch (e) {
|
|
159
|
+
const aborted = (e as Error)?.name === 'AbortError';
|
|
160
|
+
throw new FigoChatError(
|
|
161
|
+
aborted ? 'The request timed out. Please try again.' : 'Network error. Check your connection and try again.',
|
|
162
|
+
aborted ? 'TIMEOUT' : 'NETWORK',
|
|
163
|
+
e,
|
|
164
|
+
);
|
|
165
|
+
} finally {
|
|
166
|
+
clearTimeout(timer);
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/** POSTs multipart form data with XMLHttpRequest and returns the status and body text. */
|
|
171
|
+
private upload(path: string, form: FormData): Promise<{ status: number; raw: string }> {
|
|
172
|
+
const base = (this.config.baseUrl || DEFAULT_BASE_URL).replace(/\/+$/, '');
|
|
173
|
+
return new Promise((resolve, reject) => {
|
|
174
|
+
const xhr = new XMLHttpRequest();
|
|
175
|
+
xhr.open('POST', `${base}${path}`);
|
|
176
|
+
xhr.setRequestHeader('Accept', 'application/json');
|
|
177
|
+
xhr.setRequestHeader('Authorization', `Bearer ${this.config.apiKey}`);
|
|
178
|
+
xhr.timeout = this.config.timeoutMs ?? 120000;
|
|
179
|
+
xhr.onload = () => resolve({ status: xhr.status, raw: xhr.responseText ?? '' });
|
|
180
|
+
xhr.ontimeout = () => reject(new FigoChatError('The request timed out. Please try again.', 'TIMEOUT'));
|
|
181
|
+
xhr.onerror = () =>
|
|
182
|
+
reject(new FigoChatError('Network error. Check your connection and try again.', 'NETWORK', new Error('XMLHttpRequest failed')));
|
|
183
|
+
xhr.send(form);
|
|
184
|
+
});
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
private async parse<T>(res: Response, allowFailureCode = false): Promise<DefaultServiceResponse<T>> {
|
|
188
|
+
return this.parseRaw<T>(res.status, await res.text(), allowFailureCode);
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
private parseRaw<T>(status: number, raw: string, allowFailureCode = false): DefaultServiceResponse<T> {
|
|
192
|
+
if (status < 200 || status >= 300) {
|
|
193
|
+
// ApiAccessKeyAuthorize returns a plain string such as "Invalid api-key was passed"
|
|
194
|
+
const message = status === 401 ? `Unauthorized: ${stripQuotes(raw) || 'check your API key.'}` : stripQuotes(raw);
|
|
195
|
+
throw new FigoChatError(message || `Request failed (${status}).`, String(status));
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
let body: DefaultServiceResponse<T>;
|
|
199
|
+
try {
|
|
200
|
+
body = JSON.parse(raw);
|
|
201
|
+
} catch {
|
|
202
|
+
throw new FigoChatError('Unexpected response from the server.', 'PARSE');
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
if (body.responseCode === RESPONSE_CODE_LIMIT_REACHED) {
|
|
206
|
+
throw new FigoChatError(body.responseMessage || 'Usage limit reached.', body.responseCode);
|
|
207
|
+
}
|
|
208
|
+
if (body.responseCode !== RESPONSE_CODE_SUCCESS && !allowFailureCode) {
|
|
209
|
+
throw new FigoChatError(body.responseMessage || 'Something went wrong.', body.responseCode);
|
|
210
|
+
}
|
|
211
|
+
return body;
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
function stripQuotes(s: string): string {
|
|
216
|
+
return s.trim().replace(/^"(.*)"$/, '$1');
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
export function extensionOf(file: FigoLocalFile): string {
|
|
220
|
+
const fromName = file.name?.split('.').pop();
|
|
221
|
+
if (fromName && fromName !== file.name) return fromName.toLowerCase();
|
|
222
|
+
const fromMime = file.mimeType?.split('/').pop();
|
|
223
|
+
if (fromMime === 'jpeg') return 'jpg';
|
|
224
|
+
return fromMime?.toLowerCase() || 'txt';
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/** Reads a local file uri (file:// or content://) as raw base64, without a data: prefix. */
|
|
228
|
+
export function readAsBase64(uri: string): Promise<string> {
|
|
229
|
+
return new Promise((resolve, reject) => {
|
|
230
|
+
const xhr = new XMLHttpRequest();
|
|
231
|
+
xhr.onload = () => {
|
|
232
|
+
const reader = new FileReader();
|
|
233
|
+
reader.onloadend = () => {
|
|
234
|
+
const result = String(reader.result ?? '');
|
|
235
|
+
const comma = result.indexOf(',');
|
|
236
|
+
resolve(comma >= 0 ? result.slice(comma + 1) : result);
|
|
237
|
+
};
|
|
238
|
+
reader.onerror = () => reject(new FigoChatError('Could not read the file.', 'FILE_READ'));
|
|
239
|
+
reader.readAsDataURL(xhr.response);
|
|
240
|
+
};
|
|
241
|
+
xhr.onerror = () => reject(new FigoChatError('Could not read the file.', 'FILE_READ'));
|
|
242
|
+
xhr.responseType = 'blob';
|
|
243
|
+
xhr.open('GET', uri, true);
|
|
244
|
+
xhr.send(null);
|
|
245
|
+
});
|
|
246
|
+
}
|
package/src/colors.ts
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
function parseHex(hex: string): [number, number, number] {
|
|
2
|
+
let h = hex.replace('#', '');
|
|
3
|
+
if (h.length === 3) h = h.split('').map((c) => c + c).join('');
|
|
4
|
+
h = h.slice(0, 6);
|
|
5
|
+
return [parseInt(h.slice(0, 2), 16), parseInt(h.slice(2, 4), 16), parseInt(h.slice(4, 6), 16)];
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
/** Black or white, whichever reads better on the given background. */
|
|
9
|
+
export function contrastText(bg: string): string {
|
|
10
|
+
const [r, g, b] = parseHex(bg).map((v) => {
|
|
11
|
+
const c = v / 255;
|
|
12
|
+
return c <= 0.03928 ? c / 12.92 : Math.pow((c + 0.055) / 1.055, 2.4);
|
|
13
|
+
});
|
|
14
|
+
const luminance = 0.2126 * r + 0.7152 * g + 0.0722 * b;
|
|
15
|
+
return luminance > 0.45 ? '#111111' : '#FFFFFF';
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** Blends `a` towards `b` by `amount` (0..1). */
|
|
19
|
+
export function mix(a: string, b: string, amount: number): string {
|
|
20
|
+
const ca = parseHex(a);
|
|
21
|
+
const cb = parseHex(b);
|
|
22
|
+
const out = ca.map((v, i) => Math.round(v + (cb[i] - v) * amount));
|
|
23
|
+
return `#${out.map((v) => v.toString(16).padStart(2, '0')).join('')}`;
|
|
24
|
+
}
|
package/src/crypto.ts
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import CryptoJS from 'crypto-js';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* AES-256-CBC encrypt/decrypt util. Every instance makes its own random 256-bit key, held only in memory,
|
|
5
|
+
* and every encrypt() call uses a fresh random IV. Output is "<iv base64>:<ciphertext base64>".
|
|
6
|
+
*
|
|
7
|
+
* The SDK uses it to keep the realtime settings returned by GET /api/v1/realtime/config encrypted while
|
|
8
|
+
* they sit in memory; they are decrypted only at the moment a thread channel is subscribed.
|
|
9
|
+
*/
|
|
10
|
+
export class FigoCrypto {
|
|
11
|
+
private readonly key: CryptoJS.lib.WordArray;
|
|
12
|
+
|
|
13
|
+
constructor() {
|
|
14
|
+
this.key = randomWords(32);
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
encrypt(plainText: string): string {
|
|
18
|
+
const iv = randomWords(16);
|
|
19
|
+
const encrypted = CryptoJS.AES.encrypt(CryptoJS.enc.Utf8.parse(plainText), this.key, {
|
|
20
|
+
iv,
|
|
21
|
+
mode: CryptoJS.mode.CBC,
|
|
22
|
+
padding: CryptoJS.pad.Pkcs7,
|
|
23
|
+
});
|
|
24
|
+
return `${CryptoJS.enc.Base64.stringify(iv)}:${encrypted.ciphertext.toString(CryptoJS.enc.Base64)}`;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
decrypt(cipherText: string): string {
|
|
28
|
+
const [ivPart, dataPart] = cipherText.split(':');
|
|
29
|
+
if (!ivPart || !dataPart) throw new Error('FigoCrypto: value is not in "<iv>:<ciphertext>" form.');
|
|
30
|
+
const decrypted = CryptoJS.AES.decrypt(
|
|
31
|
+
CryptoJS.lib.CipherParams.create({ ciphertext: CryptoJS.enc.Base64.parse(dataPart) }),
|
|
32
|
+
this.key,
|
|
33
|
+
{ iv: CryptoJS.enc.Base64.parse(ivPart), mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7 },
|
|
34
|
+
);
|
|
35
|
+
return decrypted.toString(CryptoJS.enc.Utf8);
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Random bytes from crypto.getRandomValues when the runtime has it (Expo with expo-crypto, RN with
|
|
41
|
+
* react-native-get-random-values, web). crypto-js's own random source throws on React Native without
|
|
42
|
+
* a polyfill, so it is never used here; without getRandomValues this falls back to Math.random.
|
|
43
|
+
*/
|
|
44
|
+
function randomWords(byteCount: number): CryptoJS.lib.WordArray {
|
|
45
|
+
const bytes = new Uint8Array(byteCount);
|
|
46
|
+
const webCrypto = (globalThis as { crypto?: { getRandomValues?: (a: Uint8Array) => Uint8Array } }).crypto;
|
|
47
|
+
if (webCrypto?.getRandomValues) {
|
|
48
|
+
webCrypto.getRandomValues(bytes);
|
|
49
|
+
} else {
|
|
50
|
+
for (let i = 0; i < byteCount; i++) bytes[i] = Math.floor(Math.random() * 256);
|
|
51
|
+
}
|
|
52
|
+
// 4 bytes per big-endian word, the layout crypto-js uses
|
|
53
|
+
const words: number[] = [];
|
|
54
|
+
for (let i = 0; i < byteCount; i += 4) {
|
|
55
|
+
words.push(((bytes[i] << 24) | (bytes[i + 1] << 16) | (bytes[i + 2] << 8) | bytes[i + 3]) | 0);
|
|
56
|
+
}
|
|
57
|
+
return CryptoJS.lib.WordArray.create(words, byteCount);
|
|
58
|
+
}
|
package/src/html.ts
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Live agent replies are published in the web widget's HTML form ("<b>Name</b> says:<br/>text", HTML-encoded).
|
|
3
|
+
* Turns that into the SDK's text form: <b> becomes **bold**, <br> a line break, other tags are dropped
|
|
4
|
+
* and entities are decoded.
|
|
5
|
+
*/
|
|
6
|
+
export function htmlToText(html: string): string {
|
|
7
|
+
return html
|
|
8
|
+
.replace(/<br\s*\/?>/gi, '\n')
|
|
9
|
+
.replace(/<\/?(b|strong)>/gi, '**')
|
|
10
|
+
.replace(/<[^>]+>/g, '')
|
|
11
|
+
.replace(/&#x([0-9a-f]+);/gi, (_, h) => String.fromCodePoint(parseInt(h, 16)))
|
|
12
|
+
.replace(/&#(\d+);/g, (_, d) => String.fromCodePoint(parseInt(d, 10)))
|
|
13
|
+
.replace(/"/g, '"')
|
|
14
|
+
.replace(/'|'/g, "'")
|
|
15
|
+
.replace(/</g, '<')
|
|
16
|
+
.replace(/>/g, '>')
|
|
17
|
+
.replace(/ /g, ' ')
|
|
18
|
+
.replace(/&/g, '&')
|
|
19
|
+
.trim();
|
|
20
|
+
}
|
package/src/icons.tsx
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import React from 'react';
|
|
2
|
+
import { StyleSheet, View } from 'react-native';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Default icons drawn with plain views, so the SDK needs no icon font. Apps can replace any of them
|
|
6
|
+
* through FigoChatView's `icons` prop.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
/** Microphone: a capsule on a U-shaped stand with a short stem. */
|
|
10
|
+
export function MicIcon({ color }: { color: string }) {
|
|
11
|
+
return (
|
|
12
|
+
<View style={styles.box}>
|
|
13
|
+
<View style={[styles.micHead, { borderColor: color, backgroundColor: color }]} />
|
|
14
|
+
<View style={[styles.micStand, { borderColor: color }]} />
|
|
15
|
+
<View style={[styles.micStem, { backgroundColor: color }]} />
|
|
16
|
+
</View>
|
|
17
|
+
);
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** Attach: a plus sign. */
|
|
21
|
+
export function AttachIcon({ color }: { color: string }) {
|
|
22
|
+
return (
|
|
23
|
+
<View style={styles.box}>
|
|
24
|
+
<View style={[styles.plusH, { backgroundColor: color }]} />
|
|
25
|
+
<View style={[styles.plusV, { backgroundColor: color }]} />
|
|
26
|
+
</View>
|
|
27
|
+
);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** Send: an upward arrow (triangle head on a shaft). */
|
|
31
|
+
export function SendIcon({ color }: { color: string }) {
|
|
32
|
+
return (
|
|
33
|
+
<View style={styles.box}>
|
|
34
|
+
<View style={[styles.arrowHead, { borderBottomColor: color }]} />
|
|
35
|
+
<View style={[styles.arrowShaft, { backgroundColor: color }]} />
|
|
36
|
+
</View>
|
|
37
|
+
);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
const styles = StyleSheet.create({
|
|
41
|
+
box: { width: 22, height: 22, alignItems: 'center', justifyContent: 'center' },
|
|
42
|
+
micHead: { width: 8, height: 12, borderRadius: 4, borderWidth: 2, marginBottom: -3 },
|
|
43
|
+
micStand: {
|
|
44
|
+
width: 14,
|
|
45
|
+
height: 8,
|
|
46
|
+
borderWidth: 2,
|
|
47
|
+
borderTopWidth: 0,
|
|
48
|
+
borderBottomLeftRadius: 7,
|
|
49
|
+
borderBottomRightRadius: 7,
|
|
50
|
+
},
|
|
51
|
+
micStem: { width: 2, height: 3 },
|
|
52
|
+
plusH: { position: 'absolute', width: 16, height: 2, borderRadius: 1 },
|
|
53
|
+
plusV: { position: 'absolute', width: 2, height: 16, borderRadius: 1 },
|
|
54
|
+
arrowHead: {
|
|
55
|
+
width: 0,
|
|
56
|
+
height: 0,
|
|
57
|
+
borderLeftWidth: 7,
|
|
58
|
+
borderRightWidth: 7,
|
|
59
|
+
borderBottomWidth: 8,
|
|
60
|
+
borderLeftColor: 'transparent',
|
|
61
|
+
borderRightColor: 'transparent',
|
|
62
|
+
},
|
|
63
|
+
arrowShaft: { width: 3, height: 9, borderRadius: 1 },
|
|
64
|
+
});
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
export { FigoChat } from './FigoChat';
|
|
2
|
+
export { FigoChatView } from './FigoChatView';
|
|
3
|
+
export type { FigoChatViewProps } from './FigoChatView';
|
|
4
|
+
export { FigoChatClient, FigoChatError, DEFAULT_BASE_URL } from './client';
|
|
5
|
+
export { FigoCrypto } from './crypto';
|
|
6
|
+
export { htmlToText } from './html';
|
|
7
|
+
export { friendlyMessage } from './messages';
|
|
8
|
+
export type { FigoErrorContext } from './messages';
|
|
9
|
+
export type {
|
|
10
|
+
FigoChatConfig,
|
|
11
|
+
FigoChatMessage,
|
|
12
|
+
FigoChatReply,
|
|
13
|
+
FigoAttachment,
|
|
14
|
+
FigoLocalFile,
|
|
15
|
+
FigoMessageRole,
|
|
16
|
+
FigoRealtimeConfig,
|
|
17
|
+
} from './types';
|
package/src/messages.ts
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { FigoChatError } from './client';
|
|
2
|
+
|
|
3
|
+
/** What the user was doing when the error happened; picks the fallback wording. */
|
|
4
|
+
export type FigoErrorContext = 'chat' | 'voice' | 'recording' | 'upload';
|
|
5
|
+
|
|
6
|
+
const UNAVAILABLE = "Chat isn't available right now. Please try again later.";
|
|
7
|
+
const OFFLINE = "You seem to be offline. Check your internet connection and try again.";
|
|
8
|
+
const SLOW = 'This is taking longer than usual. Please try again.';
|
|
9
|
+
|
|
10
|
+
const FALLBACK: Record<FigoErrorContext, string> = {
|
|
11
|
+
chat: "Your message couldn't be sent. Please try again.",
|
|
12
|
+
voice: "We couldn't process your voice message. Please try again.",
|
|
13
|
+
recording: "The microphone couldn't start. Please try again.",
|
|
14
|
+
upload: "We couldn't upload that file. Please try again.",
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Turns an SDK error into a message that is safe to show to the app's users. Setup problems the user
|
|
19
|
+
* can't fix (invalid or expired API key, no credits, plan limit) all read as "chat isn't available";
|
|
20
|
+
* the technical message stays on the error, which `onError` receives for logging.
|
|
21
|
+
*/
|
|
22
|
+
export function friendlyMessage(error: unknown, context: FigoErrorContext = 'chat'): string {
|
|
23
|
+
const code = error instanceof FigoChatError ? error.code : '';
|
|
24
|
+
switch (code) {
|
|
25
|
+
case '401':
|
|
26
|
+
case '403':
|
|
27
|
+
case '49':
|
|
28
|
+
case 'CONFIG':
|
|
29
|
+
case 'NOT_INITIALIZED':
|
|
30
|
+
return UNAVAILABLE;
|
|
31
|
+
case 'NETWORK':
|
|
32
|
+
return OFFLINE;
|
|
33
|
+
case 'TIMEOUT':
|
|
34
|
+
return SLOW;
|
|
35
|
+
case 'FILE_READ':
|
|
36
|
+
return "We couldn't open that file. Please choose it again.";
|
|
37
|
+
default:
|
|
38
|
+
return FALLBACK[context];
|
|
39
|
+
}
|
|
40
|
+
}
|
package/src/realtime.ts
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
import Pusher from 'pusher-js/react-native';
|
|
2
|
+
import type { Channel } from 'pusher-js/react-native';
|
|
3
|
+
|
|
4
|
+
import type { FigoChatClient } from './client';
|
|
5
|
+
import { FigoCrypto } from './crypto';
|
|
6
|
+
import { htmlToText } from './html';
|
|
7
|
+
|
|
8
|
+
/** Realtime settings as kept in memory: key and cluster are encrypted with the SDK's FigoCrypto instance. */
|
|
9
|
+
export interface EncryptedRealtimeConfig {
|
|
10
|
+
key: string;
|
|
11
|
+
cluster: string;
|
|
12
|
+
eventName: string;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Fetches GET /api/v1/realtime/config once and keeps the result encrypted in memory.
|
|
17
|
+
* Shared by every chat view of the current FigoChat session.
|
|
18
|
+
*/
|
|
19
|
+
export class FigoRealtimeConfigStore {
|
|
20
|
+
private cached?: Promise<EncryptedRealtimeConfig>;
|
|
21
|
+
|
|
22
|
+
constructor(
|
|
23
|
+
private readonly client: FigoChatClient,
|
|
24
|
+
readonly crypto: FigoCrypto,
|
|
25
|
+
) {}
|
|
26
|
+
|
|
27
|
+
get(): Promise<EncryptedRealtimeConfig> {
|
|
28
|
+
if (!this.cached) {
|
|
29
|
+
this.cached = this.client.getRealtimeConfig().then((c) => ({
|
|
30
|
+
key: this.crypto.encrypt(c.key),
|
|
31
|
+
cluster: this.crypto.encrypt(c.cluster),
|
|
32
|
+
eventName: c.eventName,
|
|
33
|
+
}));
|
|
34
|
+
// a failed fetch is retried on the next subscribe
|
|
35
|
+
this.cached.catch(() => (this.cached = undefined));
|
|
36
|
+
}
|
|
37
|
+
return this.cached;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Subscribes to the Pusher channel named after the thread id (the X-Thread-Id value) and passes each
|
|
43
|
+
* message published on it (live agent replies, live agent handoff notices) to `onMessage` as plain text.
|
|
44
|
+
* The key and cluster are decrypted only here, right before connecting, and are not kept decrypted.
|
|
45
|
+
*/
|
|
46
|
+
export class FigoRealtimeSubscription {
|
|
47
|
+
private pusher?: Pusher;
|
|
48
|
+
private channel?: Channel;
|
|
49
|
+
private closed = false;
|
|
50
|
+
|
|
51
|
+
constructor(
|
|
52
|
+
private readonly store: FigoRealtimeConfigStore,
|
|
53
|
+
private readonly threadId: string,
|
|
54
|
+
private readonly onMessage: (text: string) => void,
|
|
55
|
+
private readonly onError?: (error: unknown) => void,
|
|
56
|
+
) {}
|
|
57
|
+
|
|
58
|
+
async start(): Promise<void> {
|
|
59
|
+
try {
|
|
60
|
+
const config = await this.store.get();
|
|
61
|
+
if (this.closed) return;
|
|
62
|
+
|
|
63
|
+
this.pusher = new Pusher(this.store.crypto.decrypt(config.key), {
|
|
64
|
+
cluster: this.store.crypto.decrypt(config.cluster),
|
|
65
|
+
forceTLS: true,
|
|
66
|
+
});
|
|
67
|
+
this.channel = this.pusher.subscribe(this.threadId);
|
|
68
|
+
this.channel.bind(config.eventName, (data: { message?: string } | string) => {
|
|
69
|
+
const raw = typeof data === 'string' ? data : data?.message;
|
|
70
|
+
const text = raw ? htmlToText(raw) : '';
|
|
71
|
+
if (text && !this.closed) this.onMessage(text);
|
|
72
|
+
});
|
|
73
|
+
this.pusher.connection.bind('error', (e: unknown) => this.onError?.(e));
|
|
74
|
+
} catch (e) {
|
|
75
|
+
this.onError?.(e);
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
stop(): void {
|
|
80
|
+
this.closed = true;
|
|
81
|
+
try {
|
|
82
|
+
this.channel?.unbind_all();
|
|
83
|
+
this.pusher?.unsubscribe(this.threadId);
|
|
84
|
+
this.pusher?.disconnect();
|
|
85
|
+
} catch {
|
|
86
|
+
// already disconnected
|
|
87
|
+
}
|
|
88
|
+
this.channel = undefined;
|
|
89
|
+
this.pusher = undefined;
|
|
90
|
+
}
|
|
91
|
+
}
|
package/src/types.ts
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
/** Options passed to `FigoChat.initialize`. */
|
|
2
|
+
export interface FigoChatConfig {
|
|
3
|
+
/** API key created in the Figo AI dashboard (Settings → API Keys). Sent as `Authorization: Bearer <apiKey>`. */
|
|
4
|
+
apiKey: string;
|
|
5
|
+
/** Id of the assistant the user chats with. */
|
|
6
|
+
assistantId: string;
|
|
7
|
+
/** Full name of the signed-in user of the host app. */
|
|
8
|
+
fullName: string;
|
|
9
|
+
/** Email address of the signed-in user of the host app. */
|
|
10
|
+
emailAddress: string;
|
|
11
|
+
/** Mobile phone number of the signed-in user, ideally in international format (e.g. +2348012345678). */
|
|
12
|
+
mobilePhone: string;
|
|
13
|
+
/** Brand color for the header, user bubbles and buttons, as a hex string such as `#F97316`. */
|
|
14
|
+
primaryColor: string;
|
|
15
|
+
|
|
16
|
+
/** API base url. Defaults to `https://api.figolabs.ai`. */
|
|
17
|
+
baseUrl?: string;
|
|
18
|
+
/** Title shown in the chat header. Defaults to `Chat`. */
|
|
19
|
+
title?: string;
|
|
20
|
+
/** First assistant message shown before the user writes anything. */
|
|
21
|
+
welcomeMessage?: string;
|
|
22
|
+
/** Continue an earlier conversation by passing the thread id from `FigoChat.getThreadId()`. */
|
|
23
|
+
threadId?: string;
|
|
24
|
+
/** Most files per message. Defaults to 5. */
|
|
25
|
+
maxFiles?: number;
|
|
26
|
+
/** Largest file accepted, in megabytes. Defaults to 10. */
|
|
27
|
+
maxFileSizeMB?: number;
|
|
28
|
+
/** Send the transcribed text straight away after a voice note. When false it is placed in the input for editing. Defaults to true. */
|
|
29
|
+
autoSendVoice?: boolean;
|
|
30
|
+
/** Request timeout in milliseconds. Defaults to 120000. */
|
|
31
|
+
timeoutMs?: number;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** A file picked by the user, ready to upload. */
|
|
35
|
+
export interface FigoLocalFile {
|
|
36
|
+
uri: string;
|
|
37
|
+
name: string;
|
|
38
|
+
mimeType?: string;
|
|
39
|
+
size?: number;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** An attachment on a chat message. */
|
|
43
|
+
export interface FigoAttachment {
|
|
44
|
+
/** CDN url returned by the upload. */
|
|
45
|
+
url: string;
|
|
46
|
+
name: string;
|
|
47
|
+
mimeType?: string;
|
|
48
|
+
/** Local uri, used for image previews before the CDN copy loads. */
|
|
49
|
+
localUri?: string;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export type FigoMessageRole = 'user' | 'assistant' | 'system';
|
|
53
|
+
|
|
54
|
+
export interface FigoChatMessage {
|
|
55
|
+
id: string;
|
|
56
|
+
role: FigoMessageRole;
|
|
57
|
+
text: string;
|
|
58
|
+
attachments?: FigoAttachment[];
|
|
59
|
+
createdAt: Date;
|
|
60
|
+
/** `sending` while the request is in flight, `error` when it failed. */
|
|
61
|
+
status?: 'sending' | 'sent' | 'error';
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export interface FigoChatReply {
|
|
65
|
+
answer: string;
|
|
66
|
+
threadId?: string;
|
|
67
|
+
/** `ai` normally, `liveagent` once the conversation has been handed to a human. */
|
|
68
|
+
threadMode?: string;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** Public realtime settings from GET /api/v1/realtime/config. */
|
|
72
|
+
export interface FigoRealtimeConfig {
|
|
73
|
+
provider: string;
|
|
74
|
+
key: string;
|
|
75
|
+
cluster: string;
|
|
76
|
+
/** Event bound on the thread channel; its payload is { message: string }. */
|
|
77
|
+
eventName: string;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** Standard envelope returned by the Figo AI REST APIs. */
|
|
81
|
+
export interface DefaultServiceResponse<T> {
|
|
82
|
+
responseCode: string;
|
|
83
|
+
responseMessage: string;
|
|
84
|
+
responseData: T;
|
|
85
|
+
}
|