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