@talqui-oss/talqui-sdk-reactnative 0.0.0-stage → 0.1.1
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/AGENT_INSTRUCTIONS.md +182 -0
- package/LICENSE.md +21 -0
- package/README.md +280 -2
- package/dist/index.d.mts +150 -0
- package/dist/index.d.ts +150 -0
- package/dist/index.js +613 -0
- package/dist/index.mjs +581 -0
- package/package.json +83 -4
- package/src/TalquiChat.tsx +40 -0
- package/src/TalquiProvider.tsx +509 -0
- package/src/TalquiWebView.tsx +153 -0
- package/src/identity.ts +40 -0
- package/src/index.ts +13 -0
- package/src/protocol.ts +101 -0
- package/src/types.ts +70 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,613 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __create = Object.create;
|
|
3
|
+
var __defProp = Object.defineProperty;
|
|
4
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
7
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
+
var __export = (target, all) => {
|
|
9
|
+
for (var name in all)
|
|
10
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
11
|
+
};
|
|
12
|
+
var __copyProps = (to, from, except, desc) => {
|
|
13
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
14
|
+
for (let key2 of __getOwnPropNames(from))
|
|
15
|
+
if (!__hasOwnProp.call(to, key2) && key2 !== except)
|
|
16
|
+
__defProp(to, key2, { get: () => from[key2], enumerable: !(desc = __getOwnPropDesc(from, key2)) || desc.enumerable });
|
|
17
|
+
}
|
|
18
|
+
return to;
|
|
19
|
+
};
|
|
20
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
21
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
22
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
23
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
24
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
25
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
26
|
+
mod
|
|
27
|
+
));
|
|
28
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
29
|
+
|
|
30
|
+
// src/index.ts
|
|
31
|
+
var index_exports = {};
|
|
32
|
+
__export(index_exports, {
|
|
33
|
+
TalquiChat: () => TalquiChat,
|
|
34
|
+
TalquiProvider: () => TalquiProvider,
|
|
35
|
+
useTalqui: () => useTalqui,
|
|
36
|
+
useTalquiEvent: () => useTalquiEvent
|
|
37
|
+
});
|
|
38
|
+
module.exports = __toCommonJS(index_exports);
|
|
39
|
+
|
|
40
|
+
// src/TalquiProvider.tsx
|
|
41
|
+
var import_react2 = require("react");
|
|
42
|
+
var import_react_native2 = require("react-native");
|
|
43
|
+
|
|
44
|
+
// src/identity.ts
|
|
45
|
+
var import_async_storage = __toESM(require("@react-native-async-storage/async-storage"));
|
|
46
|
+
|
|
47
|
+
// src/protocol.ts
|
|
48
|
+
var PROTOCOL = 1;
|
|
49
|
+
var DEFAULT_BASE_URL = "https://webchat.talqui.chat";
|
|
50
|
+
var SDK_LABEL = "react-native@0.1.1";
|
|
51
|
+
var UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
|
|
52
|
+
var IDENTITY_PATTERN = /^[A-Za-z0-9_-]{8,128}$/;
|
|
53
|
+
var USER_HASH_PATTERN = /^[A-Za-z0-9_-]{32,128}$/;
|
|
54
|
+
var META_KEY = /^[a-z0-9_-]{1,60}$/;
|
|
55
|
+
var UNSAFE_KEYS = ["__proto__", "constructor", "prototype"];
|
|
56
|
+
function isUuid(value) {
|
|
57
|
+
return UUID.test(value);
|
|
58
|
+
}
|
|
59
|
+
function buildChatUrl(options) {
|
|
60
|
+
const query = new URLSearchParams({
|
|
61
|
+
T_ID: options.tenantId,
|
|
62
|
+
PC_ID: options.connectionId,
|
|
63
|
+
EMBED: "1",
|
|
64
|
+
SDK: SDK_LABEL
|
|
65
|
+
});
|
|
66
|
+
if (options.identity) {
|
|
67
|
+
query.set(options.identity.kind === "identified" ? "S_ID" : "A_ID", options.identity.id);
|
|
68
|
+
}
|
|
69
|
+
return `${options.baseUrl.replace(/\/+$/, "")}/#/chat?${query.toString()}`;
|
|
70
|
+
}
|
|
71
|
+
function commandScript(name, payload, id) {
|
|
72
|
+
const json = JSON.stringify({ talqui: PROTOCOL, kind: "command", name, id, payload });
|
|
73
|
+
return `window.TalquiBridge&&window.TalquiBridge.receive(${JSON.stringify(json)});true;`;
|
|
74
|
+
}
|
|
75
|
+
function parseEvent(raw) {
|
|
76
|
+
let message;
|
|
77
|
+
try {
|
|
78
|
+
message = JSON.parse(raw);
|
|
79
|
+
} catch {
|
|
80
|
+
return null;
|
|
81
|
+
}
|
|
82
|
+
if (typeof message !== "object" || message === null) return null;
|
|
83
|
+
const { talqui, kind, name, payload } = message;
|
|
84
|
+
if (talqui !== PROTOCOL || kind !== "event" || typeof name !== "string") return null;
|
|
85
|
+
return { name, payload: typeof payload === "object" && payload !== null ? payload : {} };
|
|
86
|
+
}
|
|
87
|
+
function normalizeMeta(meta, warn) {
|
|
88
|
+
const out = {};
|
|
89
|
+
if (typeof meta !== "object" || meta === null || Array.isArray(meta)) {
|
|
90
|
+
warn("metadata must be an object of key/value pairs; ignored.");
|
|
91
|
+
return out;
|
|
92
|
+
}
|
|
93
|
+
for (const rawKey of Object.getOwnPropertyNames(meta)) {
|
|
94
|
+
const key2 = rawKey.trim().toLowerCase().replace(/\s+/g, "_");
|
|
95
|
+
if (key2 !== rawKey) warn(`metadata key "${rawKey}" was sent as "${key2}".`);
|
|
96
|
+
if (!META_KEY.test(key2) || UNSAFE_KEYS.includes(key2)) {
|
|
97
|
+
warn(`metadata key "${rawKey}" ignored: use lowercase letters, digits, "_" and "-" (max 60 chars).`);
|
|
98
|
+
continue;
|
|
99
|
+
}
|
|
100
|
+
const value = meta[rawKey];
|
|
101
|
+
if (value === null) {
|
|
102
|
+
out[key2] = null;
|
|
103
|
+
} else if (typeof value === "string") {
|
|
104
|
+
out[key2] = value.trim().slice(0, 255);
|
|
105
|
+
} else if (typeof value === "number" && Number.isFinite(value)) {
|
|
106
|
+
out[key2] = String(value);
|
|
107
|
+
} else if (typeof value === "boolean") {
|
|
108
|
+
out[key2] = String(value);
|
|
109
|
+
} else {
|
|
110
|
+
warn(`metadata "${rawKey}" ignored: values are strings, numbers, booleans or null.`);
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
return out;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
// src/identity.ts
|
|
117
|
+
var key = (tenantId) => `talqui:identity:${tenantId}`;
|
|
118
|
+
async function readIdentity(tenantId) {
|
|
119
|
+
try {
|
|
120
|
+
const raw = await import_async_storage.default.getItem(key(tenantId));
|
|
121
|
+
const parsed = raw ? JSON.parse(raw) : null;
|
|
122
|
+
if (parsed && (parsed.kind === "anonymous" || parsed.kind === "identified") && IDENTITY_PATTERN.test(parsed.id)) {
|
|
123
|
+
return parsed;
|
|
124
|
+
}
|
|
125
|
+
} catch {
|
|
126
|
+
}
|
|
127
|
+
return null;
|
|
128
|
+
}
|
|
129
|
+
async function writeIdentity(tenantId, identity) {
|
|
130
|
+
try {
|
|
131
|
+
await import_async_storage.default.setItem(key(tenantId), JSON.stringify(identity));
|
|
132
|
+
} catch {
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
async function clearIdentity(tenantId) {
|
|
136
|
+
try {
|
|
137
|
+
await import_async_storage.default.removeItem(key(tenantId));
|
|
138
|
+
} catch {
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
// src/TalquiWebView.tsx
|
|
143
|
+
var import_react = require("react");
|
|
144
|
+
var import_react_native = require("react-native");
|
|
145
|
+
var import_react_native_webview = require("react-native-webview");
|
|
146
|
+
var import_jsx_runtime = require("react/jsx-runtime");
|
|
147
|
+
var READY_TIMEOUT_MS = 15e3;
|
|
148
|
+
var BACKGROUND = "#FFFFFF";
|
|
149
|
+
var TalquiWebView = (0, import_react.forwardRef)(function TalquiWebView2(props, ref) {
|
|
150
|
+
const { url, allowedOrigin, isReady, onMessage, onLoadStart, onOpenUrl, renderLoading, renderError, style, debug } = props;
|
|
151
|
+
const webview = (0, import_react.useRef)(null);
|
|
152
|
+
const [attempt, setAttempt] = (0, import_react.useState)(0);
|
|
153
|
+
const [failed, setFailed] = (0, import_react.useState)(false);
|
|
154
|
+
(0, import_react.useImperativeHandle)(ref, () => ({ inject: (script) => webview.current?.injectJavaScript(script) }), []);
|
|
155
|
+
(0, import_react.useEffect)(() => {
|
|
156
|
+
if (isReady || failed) return void 0;
|
|
157
|
+
const timer = setTimeout(() => {
|
|
158
|
+
if (attempt === 0) {
|
|
159
|
+
if (debug) console.log("[talqui] chat did not become ready, reloading once");
|
|
160
|
+
setAttempt(1);
|
|
161
|
+
webview.current?.reload();
|
|
162
|
+
} else {
|
|
163
|
+
setFailed(true);
|
|
164
|
+
}
|
|
165
|
+
}, READY_TIMEOUT_MS);
|
|
166
|
+
return () => clearTimeout(timer);
|
|
167
|
+
}, [isReady, failed, attempt, url, debug]);
|
|
168
|
+
(0, import_react.useEffect)(() => {
|
|
169
|
+
setAttempt(0);
|
|
170
|
+
setFailed(false);
|
|
171
|
+
}, [url]);
|
|
172
|
+
const retry = (0, import_react.useCallback)(() => {
|
|
173
|
+
setAttempt(0);
|
|
174
|
+
setFailed(false);
|
|
175
|
+
webview.current?.reload();
|
|
176
|
+
}, []);
|
|
177
|
+
const openOutside = (0, import_react.useCallback)(
|
|
178
|
+
(target) => {
|
|
179
|
+
if (onOpenUrl) onOpenUrl(target);
|
|
180
|
+
else void import_react_native.Linking.openURL(target).catch(() => void 0);
|
|
181
|
+
},
|
|
182
|
+
[onOpenUrl]
|
|
183
|
+
);
|
|
184
|
+
const shouldStart = (0, import_react.useCallback)(
|
|
185
|
+
(request) => {
|
|
186
|
+
if (request.isTopFrame === false) return true;
|
|
187
|
+
if (request.url === "about:blank" || request.url.startsWith(allowedOrigin)) return true;
|
|
188
|
+
openOutside(request.url);
|
|
189
|
+
return false;
|
|
190
|
+
},
|
|
191
|
+
[allowedOrigin, openOutside]
|
|
192
|
+
);
|
|
193
|
+
const reloadAfterCrash = (0, import_react.useCallback)(() => webview.current?.reload(), []);
|
|
194
|
+
return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_react_native.View, { style: [styles.root, style], children: [
|
|
195
|
+
/* @__PURE__ */ (0, import_jsx_runtime.jsx)(
|
|
196
|
+
import_react_native_webview.WebView,
|
|
197
|
+
{
|
|
198
|
+
ref: webview,
|
|
199
|
+
source: { uri: url },
|
|
200
|
+
originWhitelist: ["*"],
|
|
201
|
+
onShouldStartLoadWithRequest: shouldStart,
|
|
202
|
+
onMessage: (event) => onMessage(event.nativeEvent.data),
|
|
203
|
+
onLoadStart,
|
|
204
|
+
onContentProcessDidTerminate: reloadAfterCrash,
|
|
205
|
+
onRenderProcessGone: () => {
|
|
206
|
+
reloadAfterCrash();
|
|
207
|
+
return true;
|
|
208
|
+
},
|
|
209
|
+
javaScriptEnabled: true,
|
|
210
|
+
domStorageEnabled: true,
|
|
211
|
+
allowsInlineMediaPlayback: true,
|
|
212
|
+
mediaPlaybackRequiresUserAction: false,
|
|
213
|
+
mediaCapturePermissionGrantType: "grantIfSameHostElsePrompt",
|
|
214
|
+
allowFileAccess: true,
|
|
215
|
+
setSupportMultipleWindows: false,
|
|
216
|
+
keyboardDisplayRequiresUserAction: false,
|
|
217
|
+
contentInsetAdjustmentBehavior: "never",
|
|
218
|
+
automaticallyAdjustContentInsets: false,
|
|
219
|
+
bounces: false,
|
|
220
|
+
overScrollMode: "never",
|
|
221
|
+
style: styles.webview,
|
|
222
|
+
webviewDebuggingEnabled: debug === true
|
|
223
|
+
}
|
|
224
|
+
),
|
|
225
|
+
!isReady && !failed && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_react_native.View, { style: styles.cover, pointerEvents: "none", children: renderLoading ? renderLoading() : /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_react_native.ActivityIndicator, {}) }),
|
|
226
|
+
failed && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_react_native.View, { style: styles.cover, children: renderError ? renderError(retry) : /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_react_native.View, { style: styles.error, children: [
|
|
227
|
+
/* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_react_native.Text, { style: styles.errorText, children: "N\xE3o foi poss\xEDvel carregar o chat." }),
|
|
228
|
+
/* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_react_native.Pressable, { accessibilityRole: "button", onPress: retry, style: styles.retry, hitSlop: 8, children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_react_native.Text, { style: styles.retryText, children: "Tentar de novo" }) })
|
|
229
|
+
] }) })
|
|
230
|
+
] });
|
|
231
|
+
});
|
|
232
|
+
var styles = import_react_native.StyleSheet.create({
|
|
233
|
+
root: { flex: 1, backgroundColor: BACKGROUND },
|
|
234
|
+
webview: { flex: 1, backgroundColor: BACKGROUND },
|
|
235
|
+
cover: { position: "absolute", top: 0, right: 0, bottom: 0, left: 0, alignItems: "center", justifyContent: "center", backgroundColor: BACKGROUND },
|
|
236
|
+
error: { alignItems: "center", gap: 12, padding: 24 },
|
|
237
|
+
errorText: { fontSize: 15, color: "#353849", textAlign: "center" },
|
|
238
|
+
retry: { paddingHorizontal: 16, paddingVertical: 10, borderRadius: 8, backgroundColor: "#1A66FF", minHeight: 44, justifyContent: "center" },
|
|
239
|
+
retryText: { color: "#FFFFFF", fontSize: 15, fontWeight: import_react_native.Platform.OS === "ios" ? "600" : "bold" }
|
|
240
|
+
});
|
|
241
|
+
|
|
242
|
+
// src/TalquiProvider.tsx
|
|
243
|
+
var import_jsx_runtime2 = require("react/jsx-runtime");
|
|
244
|
+
var RESET_TIMEOUT_MS = 2e3;
|
|
245
|
+
var TalquiContext = (0, import_react2.createContext)(null);
|
|
246
|
+
var emptyReplay = () => ({ contact: null, contactMeta: {}, sessionMeta: {}, prefill: null });
|
|
247
|
+
function TalquiProvider(props) {
|
|
248
|
+
const { tenantId, connectionId, onOpenUrl, renderLoading, renderError, debug, children } = props;
|
|
249
|
+
const baseUrl = props.__unstableBaseUrl ?? DEFAULT_BASE_URL;
|
|
250
|
+
const supported = import_react_native2.Platform.OS === "ios" || import_react_native2.Platform.OS === "android";
|
|
251
|
+
const log = (0, import_react2.useCallback)((...args) => debug && console.log("[talqui]", ...args), [debug]);
|
|
252
|
+
const warn = (0, import_react2.useCallback)((message) => console.warn(`[talqui] ${message}`), []);
|
|
253
|
+
const [identityLoaded, setIdentityLoaded] = (0, import_react2.useState)(false);
|
|
254
|
+
const [bootIdentity, setBootIdentity] = (0, import_react2.useState)(null);
|
|
255
|
+
const [pageKey, setPageKey] = (0, import_react2.useState)(0);
|
|
256
|
+
const identity = (0, import_react2.useRef)(null);
|
|
257
|
+
(0, import_react2.useEffect)(() => {
|
|
258
|
+
if (!isUuid(tenantId) || !isUuid(connectionId)) {
|
|
259
|
+
warn("tenantId and connectionId must be the UUIDs shown on the WebChat installation screen.");
|
|
260
|
+
}
|
|
261
|
+
let active = true;
|
|
262
|
+
void readIdentity(tenantId).then((stored) => {
|
|
263
|
+
if (!active) return;
|
|
264
|
+
identity.current = stored;
|
|
265
|
+
setBootIdentity(stored);
|
|
266
|
+
setIdentityLoaded(true);
|
|
267
|
+
});
|
|
268
|
+
return () => {
|
|
269
|
+
active = false;
|
|
270
|
+
};
|
|
271
|
+
}, [tenantId, connectionId, warn]);
|
|
272
|
+
const url = (0, import_react2.useMemo)(
|
|
273
|
+
() => buildChatUrl({ baseUrl, tenantId, connectionId, identity: bootIdentity }),
|
|
274
|
+
[baseUrl, tenantId, connectionId, bootIdentity]
|
|
275
|
+
);
|
|
276
|
+
const allowedOrigin = (0, import_react2.useMemo)(() => /^https?:\/\/[^/]+/.exec(baseUrl)?.[0] ?? baseUrl, [baseUrl]);
|
|
277
|
+
const [isOpen, setIsOpen] = (0, import_react2.useState)(false);
|
|
278
|
+
const [overlayMounted, setOverlayMounted] = (0, import_react2.useState)(false);
|
|
279
|
+
const [inline, setInline] = (0, import_react2.useState)(null);
|
|
280
|
+
const [owner, setOwner] = (0, import_react2.useState)("overlay");
|
|
281
|
+
const [appActive, setAppActive] = (0, import_react2.useState)(import_react_native2.AppState.currentState === "active");
|
|
282
|
+
(0, import_react2.useEffect)(() => {
|
|
283
|
+
const subscription = import_react_native2.AppState.addEventListener("change", (state) => setAppActive(state === "active"));
|
|
284
|
+
return () => subscription.remove();
|
|
285
|
+
}, []);
|
|
286
|
+
const [isReady, setIsReady] = (0, import_react2.useState)(false);
|
|
287
|
+
const [unreadCount, setUnreadCount] = (0, import_react2.useState)(0);
|
|
288
|
+
const webview = (0, import_react2.useRef)(null);
|
|
289
|
+
const replay = (0, import_react2.useRef)(emptyReplay());
|
|
290
|
+
const commandSeq = (0, import_react2.useRef)(0);
|
|
291
|
+
const listeners = (0, import_react2.useRef)(/* @__PURE__ */ new Map());
|
|
292
|
+
const readyRef = (0, import_react2.useRef)(false);
|
|
293
|
+
const send = (0, import_react2.useCallback)(
|
|
294
|
+
(name, payload) => {
|
|
295
|
+
if (!readyRef.current || !webview.current) return;
|
|
296
|
+
const id = `c-${++commandSeq.current}`;
|
|
297
|
+
log("\u2192", name, payload);
|
|
298
|
+
webview.current.inject(commandScript(name, payload, id));
|
|
299
|
+
},
|
|
300
|
+
[log]
|
|
301
|
+
);
|
|
302
|
+
(0, import_react2.useEffect)(() => {
|
|
303
|
+
if (!inline) setOwner("overlay");
|
|
304
|
+
else if (inline.visible && !isOpen) setOwner("inline");
|
|
305
|
+
}, [inline, isOpen]);
|
|
306
|
+
const inlineOwns = owner === "inline" && inline !== null;
|
|
307
|
+
const visible = appActive && (inlineOwns ? inline.visible : isOpen);
|
|
308
|
+
const visibleRef = (0, import_react2.useRef)(visible);
|
|
309
|
+
visibleRef.current = visible;
|
|
310
|
+
(0, import_react2.useEffect)(() => {
|
|
311
|
+
send("setVisibility", { visible });
|
|
312
|
+
}, [visible, send]);
|
|
313
|
+
const closeButtonVisible = !(inlineOwns && inline.hideCloseButton);
|
|
314
|
+
const closeButtonRef = (0, import_react2.useRef)(closeButtonVisible);
|
|
315
|
+
closeButtonRef.current = closeButtonVisible;
|
|
316
|
+
const pageCloseButton = (0, import_react2.useRef)(true);
|
|
317
|
+
const syncCloseButton = (0, import_react2.useCallback)(() => {
|
|
318
|
+
if (!readyRef.current || pageCloseButton.current === closeButtonRef.current) return;
|
|
319
|
+
send("setCloseButton", { visible: closeButtonRef.current });
|
|
320
|
+
pageCloseButton.current = closeButtonRef.current;
|
|
321
|
+
}, [send]);
|
|
322
|
+
(0, import_react2.useEffect)(() => {
|
|
323
|
+
syncCloseButton();
|
|
324
|
+
}, [closeButtonVisible, syncCloseButton]);
|
|
325
|
+
const emit = (0, import_react2.useCallback)((name, payload) => {
|
|
326
|
+
listeners.current.get(name)?.forEach((listener) => {
|
|
327
|
+
try {
|
|
328
|
+
listener(payload);
|
|
329
|
+
} catch (error) {
|
|
330
|
+
console.error("[talqui] event listener failed", error);
|
|
331
|
+
}
|
|
332
|
+
});
|
|
333
|
+
}, []);
|
|
334
|
+
const replayAll = (0, import_react2.useCallback)(() => {
|
|
335
|
+
const state = replay.current;
|
|
336
|
+
if (state.contact) send("setContact", state.contact);
|
|
337
|
+
if (Object.keys(state.contactMeta).length) send("setContactMeta", state.contactMeta);
|
|
338
|
+
if (Object.keys(state.sessionMeta).length) send("setSessionMeta", state.sessionMeta);
|
|
339
|
+
send("setVisibility", { visible: visibleRef.current });
|
|
340
|
+
pageCloseButton.current = true;
|
|
341
|
+
syncCloseButton();
|
|
342
|
+
if (state.prefill) {
|
|
343
|
+
send("prefill", { text: state.prefill });
|
|
344
|
+
state.prefill = null;
|
|
345
|
+
}
|
|
346
|
+
}, [send, syncCloseButton]);
|
|
347
|
+
const closeOverlay = (0, import_react2.useCallback)(() => setIsOpen(false), []);
|
|
348
|
+
const inlineRef = (0, import_react2.useRef)(inline);
|
|
349
|
+
inlineRef.current = inline;
|
|
350
|
+
const inlineOwnsRef = (0, import_react2.useRef)(inlineOwns);
|
|
351
|
+
inlineOwnsRef.current = inlineOwns;
|
|
352
|
+
const handleMessage = (0, import_react2.useCallback)(
|
|
353
|
+
(raw) => {
|
|
354
|
+
const event = parseEvent(raw);
|
|
355
|
+
if (!event) return;
|
|
356
|
+
log("\u2190", event.name, event.payload);
|
|
357
|
+
switch (event.name) {
|
|
358
|
+
case "ready": {
|
|
359
|
+
readyRef.current = true;
|
|
360
|
+
setIsReady(true);
|
|
361
|
+
const minted = event.payload.identity?.anonymousId;
|
|
362
|
+
if (minted && !identity.current) {
|
|
363
|
+
identity.current = { kind: "anonymous", id: minted };
|
|
364
|
+
void writeIdentity(tenantId, identity.current);
|
|
365
|
+
}
|
|
366
|
+
replayAll();
|
|
367
|
+
break;
|
|
368
|
+
}
|
|
369
|
+
case "unreadChanged":
|
|
370
|
+
setUnreadCount(event.payload.count);
|
|
371
|
+
break;
|
|
372
|
+
case "openUrl":
|
|
373
|
+
if (onOpenUrl) onOpenUrl(event.payload.url);
|
|
374
|
+
else void import_react_native2.Linking.openURL(event.payload.url).catch(() => void 0);
|
|
375
|
+
break;
|
|
376
|
+
case "closeRequested":
|
|
377
|
+
if (inlineOwnsRef.current) inlineRef.current?.onCloseRequested?.();
|
|
378
|
+
else closeOverlay();
|
|
379
|
+
break;
|
|
380
|
+
case "error":
|
|
381
|
+
warn(`${event.payload.code}: ${event.payload.message}`);
|
|
382
|
+
break;
|
|
383
|
+
default:
|
|
384
|
+
break;
|
|
385
|
+
}
|
|
386
|
+
emit(event.name, event.payload);
|
|
387
|
+
},
|
|
388
|
+
[log, tenantId, replayAll, onOpenUrl, closeOverlay, warn, emit]
|
|
389
|
+
);
|
|
390
|
+
const handleLoadStart = (0, import_react2.useCallback)(() => {
|
|
391
|
+
readyRef.current = false;
|
|
392
|
+
setIsReady(false);
|
|
393
|
+
}, []);
|
|
394
|
+
const remount = (0, import_react2.useCallback)((next) => {
|
|
395
|
+
readyRef.current = false;
|
|
396
|
+
setIsReady(false);
|
|
397
|
+
setUnreadCount(0);
|
|
398
|
+
setBootIdentity(next);
|
|
399
|
+
setPageKey((key2) => key2 + 1);
|
|
400
|
+
}, []);
|
|
401
|
+
(0, import_react2.useEffect)(() => {
|
|
402
|
+
if (!isOpen) return void 0;
|
|
403
|
+
const subscription = import_react_native2.BackHandler.addEventListener("hardwareBackPress", () => {
|
|
404
|
+
closeOverlay();
|
|
405
|
+
return true;
|
|
406
|
+
});
|
|
407
|
+
return () => subscription.remove();
|
|
408
|
+
}, [isOpen, closeOverlay]);
|
|
409
|
+
const setContact = (0, import_react2.useCallback)(
|
|
410
|
+
(contact) => {
|
|
411
|
+
const next = { ...replay.current.contact, ...contact };
|
|
412
|
+
replay.current.contact = next;
|
|
413
|
+
send("setContact", next);
|
|
414
|
+
},
|
|
415
|
+
[send]
|
|
416
|
+
);
|
|
417
|
+
const setMeta = (0, import_react2.useCallback)(
|
|
418
|
+
(target, meta) => {
|
|
419
|
+
const normalized = normalizeMeta(meta, warn);
|
|
420
|
+
if (!Object.keys(normalized).length) return;
|
|
421
|
+
replay.current[target] = { ...replay.current[target], ...normalized };
|
|
422
|
+
send(target === "contactMeta" ? "setContactMeta" : "setSessionMeta", normalized);
|
|
423
|
+
},
|
|
424
|
+
[send, warn]
|
|
425
|
+
);
|
|
426
|
+
const logout = (0, import_react2.useCallback)(async () => {
|
|
427
|
+
if (readyRef.current && webview.current) {
|
|
428
|
+
await new Promise((resolve) => {
|
|
429
|
+
const timer = setTimeout(done, RESET_TIMEOUT_MS);
|
|
430
|
+
const unsubscribe = subscribeRef.current("resetDone", done);
|
|
431
|
+
function done() {
|
|
432
|
+
clearTimeout(timer);
|
|
433
|
+
unsubscribe();
|
|
434
|
+
resolve();
|
|
435
|
+
}
|
|
436
|
+
send("reset", {});
|
|
437
|
+
});
|
|
438
|
+
}
|
|
439
|
+
await clearIdentity(tenantId);
|
|
440
|
+
identity.current = null;
|
|
441
|
+
replay.current = emptyReplay();
|
|
442
|
+
remount(null);
|
|
443
|
+
}, [send, tenantId, remount]);
|
|
444
|
+
const identify = (0, import_react2.useCallback)(
|
|
445
|
+
async (user) => {
|
|
446
|
+
const { userHash, name, email, phone } = user;
|
|
447
|
+
if (userHash !== void 0) {
|
|
448
|
+
if (!USER_HASH_PATTERN.test(userHash)) {
|
|
449
|
+
warn("identify: userHash must be 32 to 128 chars of A-Z a-z 0-9 _ - (compute it on your backend). Ignored.");
|
|
450
|
+
} else if (identity.current?.kind !== "identified" || identity.current.id !== userHash) {
|
|
451
|
+
const next = { kind: "identified", id: userHash };
|
|
452
|
+
identity.current = next;
|
|
453
|
+
await writeIdentity(tenantId, next);
|
|
454
|
+
replay.current = emptyReplay();
|
|
455
|
+
remount(next);
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
const contact = {};
|
|
459
|
+
if (name) contact.name = name;
|
|
460
|
+
if (email) contact.email = email;
|
|
461
|
+
if (phone) contact.phone = phone;
|
|
462
|
+
if (Object.keys(contact).length) setContact(contact);
|
|
463
|
+
},
|
|
464
|
+
[tenantId, warn, remount, setContact]
|
|
465
|
+
);
|
|
466
|
+
const subscribe = (0, import_react2.useCallback)((name, listener) => {
|
|
467
|
+
const set = listeners.current.get(name) ?? /* @__PURE__ */ new Set();
|
|
468
|
+
set.add(listener);
|
|
469
|
+
listeners.current.set(name, set);
|
|
470
|
+
return () => {
|
|
471
|
+
set.delete(listener);
|
|
472
|
+
};
|
|
473
|
+
}, []);
|
|
474
|
+
const subscribeRef = (0, import_react2.useRef)(subscribe);
|
|
475
|
+
subscribeRef.current = subscribe;
|
|
476
|
+
const api = (0, import_react2.useMemo)(() => {
|
|
477
|
+
if (!supported) {
|
|
478
|
+
const unsupported = () => warn("the chat SDK runs on iOS and Android only; on the web use the WebChat snippet.");
|
|
479
|
+
return {
|
|
480
|
+
open: unsupported,
|
|
481
|
+
close: unsupported,
|
|
482
|
+
preload: unsupported,
|
|
483
|
+
identify: async () => unsupported(),
|
|
484
|
+
setContact: unsupported,
|
|
485
|
+
setContactMeta: unsupported,
|
|
486
|
+
setSessionMeta: unsupported,
|
|
487
|
+
prefill: unsupported,
|
|
488
|
+
logout: async () => unsupported(),
|
|
489
|
+
unreadCount: 0,
|
|
490
|
+
isReady: false,
|
|
491
|
+
isOpen: false
|
|
492
|
+
};
|
|
493
|
+
}
|
|
494
|
+
return {
|
|
495
|
+
open: () => {
|
|
496
|
+
if (inlineRef.current?.visible) {
|
|
497
|
+
warn("open() ignored: <TalquiChat /> is on screen and already shows the chat.");
|
|
498
|
+
return;
|
|
499
|
+
}
|
|
500
|
+
setOwner("overlay");
|
|
501
|
+
setOverlayMounted(true);
|
|
502
|
+
setIsOpen(true);
|
|
503
|
+
},
|
|
504
|
+
close: closeOverlay,
|
|
505
|
+
preload: () => setOverlayMounted(true),
|
|
506
|
+
identify,
|
|
507
|
+
setContact,
|
|
508
|
+
setContactMeta: (meta) => setMeta("contactMeta", meta),
|
|
509
|
+
setSessionMeta: (meta) => setMeta("sessionMeta", meta),
|
|
510
|
+
prefill: (text) => {
|
|
511
|
+
const trimmed = typeof text === "string" ? text.trim().slice(0, 1e3) : "";
|
|
512
|
+
if (!trimmed) return;
|
|
513
|
+
if (readyRef.current) send("prefill", { text: trimmed });
|
|
514
|
+
else replay.current.prefill = trimmed;
|
|
515
|
+
},
|
|
516
|
+
logout,
|
|
517
|
+
unreadCount,
|
|
518
|
+
isReady,
|
|
519
|
+
isOpen
|
|
520
|
+
};
|
|
521
|
+
}, [supported, warn, closeOverlay, identify, setContact, setMeta, send, logout, unreadCount, isReady, isOpen]);
|
|
522
|
+
const renderWebView = (0, import_react2.useCallback)(
|
|
523
|
+
(style) => identityLoaded ? /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
|
|
524
|
+
TalquiWebView,
|
|
525
|
+
{
|
|
526
|
+
ref: webview,
|
|
527
|
+
url,
|
|
528
|
+
allowedOrigin,
|
|
529
|
+
isReady,
|
|
530
|
+
onMessage: handleMessage,
|
|
531
|
+
onLoadStart: handleLoadStart,
|
|
532
|
+
onOpenUrl,
|
|
533
|
+
renderLoading,
|
|
534
|
+
renderError,
|
|
535
|
+
style,
|
|
536
|
+
debug
|
|
537
|
+
},
|
|
538
|
+
pageKey
|
|
539
|
+
) : null,
|
|
540
|
+
[identityLoaded, pageKey, url, allowedOrigin, isReady, handleMessage, handleLoadStart, onOpenUrl, renderLoading, renderError, debug]
|
|
541
|
+
);
|
|
542
|
+
const internals = (0, import_react2.useMemo)(
|
|
543
|
+
() => ({
|
|
544
|
+
renderInline: (style) => inlineOwns ? renderWebView(style) : null,
|
|
545
|
+
registerInline: (host) => {
|
|
546
|
+
setInline(host);
|
|
547
|
+
if (host.visible) setIsOpen(false);
|
|
548
|
+
return () => setInline(null);
|
|
549
|
+
},
|
|
550
|
+
updateInline: (host) => setInline(host)
|
|
551
|
+
}),
|
|
552
|
+
[renderWebView, inlineOwns]
|
|
553
|
+
);
|
|
554
|
+
const value = (0, import_react2.useMemo)(() => ({ api, internals, subscribe }), [api, internals, subscribe]);
|
|
555
|
+
return /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(TalquiContext.Provider, { value, children: [
|
|
556
|
+
children,
|
|
557
|
+
supported && overlayMounted && !inlineOwns && /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(import_react_native2.View, { style: [styles2.overlay, !isOpen && styles2.hidden], pointerEvents: isOpen ? "auto" : "none", children: renderWebView(void 0) })
|
|
558
|
+
] });
|
|
559
|
+
}
|
|
560
|
+
function useTalqui() {
|
|
561
|
+
return useTalquiContext().api;
|
|
562
|
+
}
|
|
563
|
+
function useTalquiEvent(name, listener) {
|
|
564
|
+
const { subscribe } = useTalquiContext();
|
|
565
|
+
const latest = (0, import_react2.useRef)(listener);
|
|
566
|
+
latest.current = listener;
|
|
567
|
+
(0, import_react2.useEffect)(() => subscribe(name, (payload) => latest.current(payload)), [subscribe, name]);
|
|
568
|
+
}
|
|
569
|
+
function useTalquiContext() {
|
|
570
|
+
const context = (0, import_react2.useContext)(TalquiContext);
|
|
571
|
+
if (!context) {
|
|
572
|
+
throw new Error("[talqui] useTalqui must be used inside <TalquiProvider>.");
|
|
573
|
+
}
|
|
574
|
+
return context;
|
|
575
|
+
}
|
|
576
|
+
var styles2 = import_react_native2.StyleSheet.create({
|
|
577
|
+
overlay: {
|
|
578
|
+
position: "absolute",
|
|
579
|
+
top: 0,
|
|
580
|
+
right: 0,
|
|
581
|
+
bottom: 0,
|
|
582
|
+
left: 0,
|
|
583
|
+
zIndex: 1e3,
|
|
584
|
+
elevation: 1e3,
|
|
585
|
+
backgroundColor: "#FFFFFF",
|
|
586
|
+
// Android draws the app under the status bar; the page only knows about the iOS safe areas.
|
|
587
|
+
paddingTop: import_react_native2.Platform.OS === "android" ? import_react_native2.StatusBar.currentHeight ?? 0 : 0
|
|
588
|
+
},
|
|
589
|
+
// Hidden, not unmounted: the conversation keeps running so unread messages are counted.
|
|
590
|
+
hidden: { opacity: 0, transform: [{ translateY: 1e5 }] }
|
|
591
|
+
});
|
|
592
|
+
|
|
593
|
+
// src/TalquiChat.tsx
|
|
594
|
+
var import_react3 = require("react");
|
|
595
|
+
var import_jsx_runtime3 = require("react/jsx-runtime");
|
|
596
|
+
function TalquiChat({ style, visible = true, onCloseRequested, hideCloseButton = false }) {
|
|
597
|
+
const { internals } = useTalquiContext();
|
|
598
|
+
const host = (0, import_react3.useRef)({ visible, onCloseRequested, hideCloseButton });
|
|
599
|
+
host.current = { visible, onCloseRequested, hideCloseButton };
|
|
600
|
+
(0, import_react3.useEffect)(() => internals.registerInline(host.current), [internals]);
|
|
601
|
+
(0, import_react3.useEffect)(
|
|
602
|
+
() => internals.updateInline({ visible, onCloseRequested, hideCloseButton }),
|
|
603
|
+
[internals, visible, onCloseRequested, hideCloseButton]
|
|
604
|
+
);
|
|
605
|
+
return /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(import_jsx_runtime3.Fragment, { children: internals.renderInline(style) });
|
|
606
|
+
}
|
|
607
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
608
|
+
0 && (module.exports = {
|
|
609
|
+
TalquiChat,
|
|
610
|
+
TalquiProvider,
|
|
611
|
+
useTalqui,
|
|
612
|
+
useTalquiEvent
|
|
613
|
+
});
|