@cobbai/react-native-sdk 1.0.0-beta.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/CobbaiMobileRnSdk.podspec +22 -0
- package/LICENSE +32 -0
- package/README.md +386 -0
- package/dist/ChatPlaceholder.d.ts +13 -0
- package/dist/ChatPlaceholder.d.ts.map +1 -0
- package/dist/ChatPlaceholder.js +87 -0
- package/dist/CobbaiChatScreen.d.ts +4 -0
- package/dist/CobbaiChatScreen.d.ts.map +1 -0
- package/dist/CobbaiChatScreen.js +196 -0
- package/dist/CobbaiInAppBanner.d.ts +15 -0
- package/dist/CobbaiInAppBanner.d.ts.map +1 -0
- package/dist/CobbaiInAppBanner.js +159 -0
- package/dist/CobbaiLauncher.d.ts +19 -0
- package/dist/CobbaiLauncher.d.ts.map +1 -0
- package/dist/CobbaiLauncher.js +149 -0
- package/dist/CobbaiWebView.d.ts +28 -0
- package/dist/CobbaiWebView.d.ts.map +1 -0
- package/dist/CobbaiWebView.js +141 -0
- package/dist/adapters/expoAdapter.d.ts +85 -0
- package/dist/adapters/expoAdapter.d.ts.map +1 -0
- package/dist/adapters/expoAdapter.js +152 -0
- package/dist/adapters/firebaseAdapter.d.ts +41 -0
- package/dist/adapters/firebaseAdapter.d.ts.map +1 -0
- package/dist/adapters/firebaseAdapter.js +139 -0
- package/dist/adapters/iosRelayAdapter.d.ts +26 -0
- package/dist/adapters/iosRelayAdapter.d.ts.map +1 -0
- package/dist/adapters/iosRelayAdapter.js +101 -0
- package/dist/androidKeyboardFrame.d.ts +16 -0
- package/dist/androidKeyboardFrame.d.ts.map +1 -0
- package/dist/androidKeyboardFrame.js +34 -0
- package/dist/bridge/messages.d.ts +20 -0
- package/dist/bridge/messages.d.ts.map +1 -0
- package/dist/bridge/messages.js +20 -0
- package/dist/bridge/nativeEvent.d.ts +10 -0
- package/dist/bridge/nativeEvent.d.ts.map +1 -0
- package/dist/bridge/nativeEvent.js +15 -0
- package/dist/bridge/parser.d.ts +29 -0
- package/dist/bridge/parser.d.ts.map +1 -0
- package/dist/bridge/parser.js +109 -0
- package/dist/chatPresentation.d.ts +19 -0
- package/dist/chatPresentation.d.ts.map +1 -0
- package/dist/chatPresentation.js +51 -0
- package/dist/chatScreen/useInAppBannerQueue.d.ts +22 -0
- package/dist/chatScreen/useInAppBannerQueue.d.ts.map +1 -0
- package/dist/chatScreen/useInAppBannerQueue.js +60 -0
- package/dist/chatScreen/useKeyboardFrame.d.ts +14 -0
- package/dist/chatScreen/useKeyboardFrame.d.ts.map +1 -0
- package/dist/chatScreen/useKeyboardFrame.js +63 -0
- package/dist/chatScreen/useLauncherPresentation.d.ts +20 -0
- package/dist/chatScreen/useLauncherPresentation.d.ts.map +1 -0
- package/dist/chatScreen/useLauncherPresentation.js +76 -0
- package/dist/chatScreen/useNativeToWebSync.d.ts +17 -0
- package/dist/chatScreen/useNativeToWebSync.d.ts.map +1 -0
- package/dist/chatScreen/useNativeToWebSync.js +36 -0
- package/dist/chatScreen/usePushIntegration.d.ts +19 -0
- package/dist/chatScreen/usePushIntegration.d.ts.map +1 -0
- package/dist/chatScreen/usePushIntegration.js +129 -0
- package/dist/chatScreen/useReadyLifecycle.d.ts +33 -0
- package/dist/chatScreen/useReadyLifecycle.d.ts.map +1 -0
- package/dist/chatScreen/useReadyLifecycle.js +138 -0
- package/dist/chatScreen/useSheetPresentation.d.ts +25 -0
- package/dist/chatScreen/useSheetPresentation.d.ts.map +1 -0
- package/dist/chatScreen/useSheetPresentation.js +98 -0
- package/dist/chatUnavailable.d.ts +23 -0
- package/dist/chatUnavailable.d.ts.map +1 -0
- package/dist/chatUnavailable.js +36 -0
- package/dist/externalLinks.d.ts +4 -0
- package/dist/externalLinks.d.ts.map +1 -0
- package/dist/externalLinks.js +48 -0
- package/dist/host/buildHostHtml.d.ts +7 -0
- package/dist/host/buildHostHtml.d.ts.map +1 -0
- package/dist/host/buildHostHtml.js +101 -0
- package/dist/host/hostPageKey.d.ts +7 -0
- package/dist/host/hostPageKey.d.ts.map +1 -0
- package/dist/host/hostPageKey.js +18 -0
- package/dist/inAppBanner.d.ts +19 -0
- package/dist/inAppBanner.d.ts.map +1 -0
- package/dist/inAppBanner.js +42 -0
- package/dist/index.d.ts +10 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +32 -0
- package/dist/launcher.d.ts +25 -0
- package/dist/launcher.d.ts.map +1 -0
- package/dist/launcher.js +55 -0
- package/dist/launcherGlyph.d.ts +2 -0
- package/dist/launcherGlyph.d.ts.map +1 -0
- package/dist/launcherGlyph.js +5 -0
- package/dist/openChatScreen.d.ts +13 -0
- package/dist/openChatScreen.d.ts.map +1 -0
- package/dist/openChatScreen.js +63 -0
- package/dist/push.d.ts +59 -0
- package/dist/push.d.ts.map +1 -0
- package/dist/push.js +309 -0
- package/dist/pushIntegration.d.ts +76 -0
- package/dist/pushIntegration.d.ts.map +1 -0
- package/dist/pushIntegration.js +244 -0
- package/dist/pushLogout.d.ts +57 -0
- package/dist/pushLogout.d.ts.map +1 -0
- package/dist/pushLogout.js +225 -0
- package/dist/types.d.ts +42 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +2 -0
- package/dist/version.d.ts +8 -0
- package/dist/version.d.ts.map +1 -0
- package/dist/version.js +10 -0
- package/ios/CobbaiPush.m +96 -0
- package/ios/CobbaiPushRelay.h +59 -0
- package/ios/CobbaiPushRelay.m +364 -0
- package/package.json +69 -0
- package/src/ChatPlaceholder.tsx +132 -0
- package/src/CobbaiChatScreen.tsx +348 -0
- package/src/CobbaiInAppBanner.tsx +237 -0
- package/src/CobbaiLauncher.tsx +223 -0
- package/src/CobbaiWebView.tsx +242 -0
- package/src/adapters/expoAdapter.ts +227 -0
- package/src/adapters/firebaseAdapter.ts +201 -0
- package/src/adapters/iosRelayAdapter.ts +137 -0
- package/src/androidKeyboardFrame.ts +56 -0
- package/src/bridge/messages.ts +24 -0
- package/src/bridge/nativeEvent.ts +12 -0
- package/src/bridge/parser.ts +159 -0
- package/src/chatPresentation.ts +73 -0
- package/src/chatScreen/useInAppBannerQueue.ts +91 -0
- package/src/chatScreen/useKeyboardFrame.ts +89 -0
- package/src/chatScreen/useLauncherPresentation.ts +121 -0
- package/src/chatScreen/useNativeToWebSync.ts +54 -0
- package/src/chatScreen/usePushIntegration.ts +191 -0
- package/src/chatScreen/useReadyLifecycle.ts +186 -0
- package/src/chatScreen/useSheetPresentation.ts +147 -0
- package/src/chatUnavailable.ts +58 -0
- package/src/externalLinks.ts +56 -0
- package/src/host/buildHostHtml.ts +117 -0
- package/src/host/hostPageKey.ts +17 -0
- package/src/inAppBanner.ts +58 -0
- package/src/index.ts +53 -0
- package/src/launcher.ts +79 -0
- package/src/launcherGlyph.ts +3 -0
- package/src/openChatScreen.ts +78 -0
- package/src/push.ts +424 -0
- package/src/pushIntegration.ts +338 -0
- package/src/pushLogout.ts +277 -0
- package/src/types.ts +46 -0
- package/src/version.ts +8 -0
|
@@ -0,0 +1,338 @@
|
|
|
1
|
+
import { Platform } from 'react-native';
|
|
2
|
+
import { getNativeCobbaiPush, iosRelayAdapter } from './adapters/iosRelayAdapter';
|
|
3
|
+
import { setPushLogoutStorage, type CobbaiPushStorage } from './pushLogout';
|
|
4
|
+
import {
|
|
5
|
+
clearPushToken,
|
|
6
|
+
handleCobbaiPushInForeground,
|
|
7
|
+
handleCobbaiPushTap,
|
|
8
|
+
setPushToken,
|
|
9
|
+
type CobbaiForegroundPush,
|
|
10
|
+
type CobbaiPushToken,
|
|
11
|
+
} from './push';
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Push integration: the app hands its notification library to the SDK
|
|
15
|
+
* through an adapter, once at start-up, and the SDK does the rest — token, taps (the launching one
|
|
16
|
+
* included), foreground pushes, permission status.
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* - `not-asked`: the user has not answered the permission prompt yet.
|
|
21
|
+
* - `granted` / `denied`: the user's answer.
|
|
22
|
+
* - `stopped`: granted, but the app turned Cobbai pushes off (`setCobbaiPushEnabled(false)`).
|
|
23
|
+
* - `unavailable`: no adapter, or the notification library is not set up (e.g. Firebase config
|
|
24
|
+
* missing).
|
|
25
|
+
*/
|
|
26
|
+
export type CobbaiPushStatus = 'not-asked' | 'granted' | 'denied' | 'stopped' | 'unavailable';
|
|
27
|
+
|
|
28
|
+
/** What an adapter reports to the SDK. */
|
|
29
|
+
export type CobbaiPushAdapterHandlers = {
|
|
30
|
+
/** The device token, when known and whenever it changes. */
|
|
31
|
+
token: (token: CobbaiPushToken) => void;
|
|
32
|
+
/** A tap on any notification, the one that launched the app included; non-Cobbai ones are ignored. */
|
|
33
|
+
tap: (data: unknown) => void;
|
|
34
|
+
/** A notification received while the app is open. Returns true when it was a Cobbai push. */
|
|
35
|
+
foreground: (push: CobbaiForegroundPush) => boolean;
|
|
36
|
+
/** The permission status, at start and whenever the adapter learns it changed. */
|
|
37
|
+
status: (status: CobbaiPushStatus) => void;
|
|
38
|
+
};
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Bridges one notification library to the SDK. The SDK ships `firebaseAdapter`; an app with
|
|
42
|
+
* another library can write its own.
|
|
43
|
+
*/
|
|
44
|
+
export type CobbaiPushAdapter = {
|
|
45
|
+
name: string;
|
|
46
|
+
/** Subscribes to the library and reports through `handlers`. Returns the unsubscribe function. */
|
|
47
|
+
start: (handlers: CobbaiPushAdapterHandlers) => () => void;
|
|
48
|
+
/** Asks the user through the library (never called by the SDK on its own). */
|
|
49
|
+
requestPermission: () => Promise<CobbaiPushStatus>;
|
|
50
|
+
};
|
|
51
|
+
|
|
52
|
+
export type CobbaiPushConfiguration = {
|
|
53
|
+
adapter: CobbaiPushAdapter;
|
|
54
|
+
/**
|
|
55
|
+
* Keeps the logout secrets and the pending logouts across app restarts, e.g.
|
|
56
|
+
* `@react-native-async-storage/async-storage`. Optional: without it they live in memory.
|
|
57
|
+
*/
|
|
58
|
+
storage?: CobbaiPushStorage;
|
|
59
|
+
};
|
|
60
|
+
|
|
61
|
+
type StatusListener = (status: CobbaiPushStatus) => void;
|
|
62
|
+
|
|
63
|
+
type IntegrationState = {
|
|
64
|
+
/** The adapter the app configured. */
|
|
65
|
+
adapter: CobbaiPushAdapter | null;
|
|
66
|
+
/** What runs: the app's adapter, joined on iPhone by the native relay. */
|
|
67
|
+
runningAdapter: CobbaiPushAdapter | null;
|
|
68
|
+
stopAdapter: (() => void) | null;
|
|
69
|
+
/** Bumped on every configure, so that a stale adapter's late reports are ignored. */
|
|
70
|
+
generation: number;
|
|
71
|
+
adapterStatus: CobbaiPushStatus;
|
|
72
|
+
enabled: boolean;
|
|
73
|
+
lastToken: CobbaiPushToken | null;
|
|
74
|
+
statusListeners: Set<StatusListener>;
|
|
75
|
+
};
|
|
76
|
+
|
|
77
|
+
const STATE_KEY = '__COBBAI_PUSH_INTEGRATION__';
|
|
78
|
+
|
|
79
|
+
function getState(): IntegrationState {
|
|
80
|
+
const globalObject = globalThis as typeof globalThis & { [STATE_KEY]?: IntegrationState };
|
|
81
|
+
|
|
82
|
+
if (!globalObject[STATE_KEY]) {
|
|
83
|
+
globalObject[STATE_KEY] = {
|
|
84
|
+
adapter: null,
|
|
85
|
+
runningAdapter: null,
|
|
86
|
+
stopAdapter: null,
|
|
87
|
+
generation: 0,
|
|
88
|
+
adapterStatus: 'unavailable',
|
|
89
|
+
enabled: true,
|
|
90
|
+
lastToken: null,
|
|
91
|
+
statusListeners: new Set<StatusListener>(),
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
return globalObject[STATE_KEY];
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function effectiveStatus(state: IntegrationState): CobbaiPushStatus {
|
|
99
|
+
if (!state.enabled && state.adapterStatus === 'granted') {
|
|
100
|
+
return 'stopped';
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
return state.adapterStatus;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
function setAdapterStatus(state: IntegrationState, status: CobbaiPushStatus): void {
|
|
107
|
+
const previous = effectiveStatus(state);
|
|
108
|
+
state.adapterStatus = status;
|
|
109
|
+
const next = effectiveStatus(state);
|
|
110
|
+
|
|
111
|
+
if (next !== previous) {
|
|
112
|
+
state.statusListeners.forEach((listener) => listener(next));
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
function notifyStatus(state: IntegrationState): void {
|
|
117
|
+
const status = effectiveStatus(state);
|
|
118
|
+
state.statusListeners.forEach((listener) => listener(status));
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
function errorMessage(error: unknown): string {
|
|
122
|
+
return error instanceof Error ? error.message : String(error);
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
function stopCurrentAdapter(state: IntegrationState): void {
|
|
126
|
+
const stop = state.stopAdapter;
|
|
127
|
+
state.adapter = null;
|
|
128
|
+
state.runningAdapter = null;
|
|
129
|
+
state.stopAdapter = null;
|
|
130
|
+
state.generation += 1;
|
|
131
|
+
|
|
132
|
+
if (stop) {
|
|
133
|
+
try {
|
|
134
|
+
stop();
|
|
135
|
+
} catch (error) {
|
|
136
|
+
if (__DEV__) {
|
|
137
|
+
console.warn(`[cobbai][push] adapter stop failed: ${errorMessage(error)}`);
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/**
|
|
144
|
+
* On iPhone the SDK's native relay is the source of the token, taps, foreground
|
|
145
|
+
* pushes and permission: Cobbai pushes go to APNs directly and only the relay is sure to see them.
|
|
146
|
+
* The app's adapter runs beside it (Expo sees Cobbai pushes too: taps are handled once anyway) and
|
|
147
|
+
* its status reports are ignored.
|
|
148
|
+
*/
|
|
149
|
+
function withIosRelay(adapter: CobbaiPushAdapter): CobbaiPushAdapter {
|
|
150
|
+
const native = getNativeCobbaiPush();
|
|
151
|
+
if (!native) {
|
|
152
|
+
if (Platform.OS === 'ios' && __DEV__) {
|
|
153
|
+
console.warn(
|
|
154
|
+
'[cobbai][push][ios] the native relay is missing (run `pod install`): Cobbai pushes are not handled on iPhone',
|
|
155
|
+
);
|
|
156
|
+
}
|
|
157
|
+
return adapter;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
const relay = iosRelayAdapter(native);
|
|
161
|
+
return {
|
|
162
|
+
name: `${adapter.name}+${relay.name}`,
|
|
163
|
+
start(handlers) {
|
|
164
|
+
const stopRelay = relay.start(handlers);
|
|
165
|
+
let stopAppAdapter = (): void => {};
|
|
166
|
+
try {
|
|
167
|
+
stopAppAdapter = adapter.start({ ...handlers, status: () => {} });
|
|
168
|
+
} catch (error) {
|
|
169
|
+
if (__DEV__) {
|
|
170
|
+
console.warn(
|
|
171
|
+
`[cobbai][push] ${adapter.name} adapter failed to start: ${errorMessage(error)}`,
|
|
172
|
+
);
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
return () => {
|
|
176
|
+
stopAppAdapter();
|
|
177
|
+
stopRelay();
|
|
178
|
+
};
|
|
179
|
+
},
|
|
180
|
+
requestPermission: () => relay.requestPermission(),
|
|
181
|
+
};
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/**
|
|
185
|
+
* Hands the app's notification library to the SDK. Call it once at start-up, outside any screen
|
|
186
|
+
* (the tap that launched the app must not be missed). Calling it again with the same adapter does
|
|
187
|
+
* nothing; with another adapter, the previous one is stopped. Returns a function that stops it.
|
|
188
|
+
*/
|
|
189
|
+
export function configureCobbaiPush({ adapter, storage }: CobbaiPushConfiguration): () => void {
|
|
190
|
+
const state = getState();
|
|
191
|
+
// Also retries the logouts that could not be sent before.
|
|
192
|
+
void setPushLogoutStorage(storage ?? null);
|
|
193
|
+
|
|
194
|
+
if (state.adapter === adapter) {
|
|
195
|
+
const generation = state.generation;
|
|
196
|
+
return () => {
|
|
197
|
+
if (getState().generation === generation) {
|
|
198
|
+
stopCurrentAdapter(getState());
|
|
199
|
+
}
|
|
200
|
+
};
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
stopCurrentAdapter(state);
|
|
204
|
+
state.adapter = adapter;
|
|
205
|
+
const runningAdapter = withIosRelay(adapter);
|
|
206
|
+
state.runningAdapter = runningAdapter;
|
|
207
|
+
const generation = state.generation;
|
|
208
|
+
const isCurrent = (): boolean => getState().generation === generation;
|
|
209
|
+
|
|
210
|
+
const handlers: CobbaiPushAdapterHandlers = {
|
|
211
|
+
token: (token) => {
|
|
212
|
+
if (!isCurrent()) return;
|
|
213
|
+
state.lastToken = { ...token };
|
|
214
|
+
if (state.enabled) {
|
|
215
|
+
setPushToken(token);
|
|
216
|
+
}
|
|
217
|
+
},
|
|
218
|
+
tap: (data) => {
|
|
219
|
+
if (!isCurrent()) return;
|
|
220
|
+
handleCobbaiPushTap(data);
|
|
221
|
+
},
|
|
222
|
+
foreground: (push) => {
|
|
223
|
+
if (!isCurrent()) return false;
|
|
224
|
+
return handleCobbaiPushInForeground(push);
|
|
225
|
+
},
|
|
226
|
+
status: (status) => {
|
|
227
|
+
if (!isCurrent()) return;
|
|
228
|
+
setAdapterStatus(state, status);
|
|
229
|
+
},
|
|
230
|
+
};
|
|
231
|
+
|
|
232
|
+
try {
|
|
233
|
+
state.stopAdapter = runningAdapter.start(handlers);
|
|
234
|
+
} catch (error) {
|
|
235
|
+
if (__DEV__) {
|
|
236
|
+
console.warn(
|
|
237
|
+
`[cobbai][push] ${adapter.name} adapter failed to start: ${errorMessage(error)}`,
|
|
238
|
+
);
|
|
239
|
+
}
|
|
240
|
+
setAdapterStatus(state, 'unavailable');
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
return () => {
|
|
244
|
+
if (isCurrent()) {
|
|
245
|
+
stopCurrentAdapter(getState());
|
|
246
|
+
}
|
|
247
|
+
};
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
/**
|
|
251
|
+
* Asks the user for permission through the app's notification library, and turns Cobbai pushes
|
|
252
|
+
* back on. The SDK never calls it on its own.
|
|
253
|
+
*/
|
|
254
|
+
export async function requestCobbaiPushPermission(): Promise<CobbaiPushStatus> {
|
|
255
|
+
const state = getState();
|
|
256
|
+
const adapter = state.runningAdapter;
|
|
257
|
+
|
|
258
|
+
if (!adapter) {
|
|
259
|
+
return 'unavailable';
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
setCobbaiPushEnabled(true);
|
|
263
|
+
|
|
264
|
+
let status: CobbaiPushStatus;
|
|
265
|
+
try {
|
|
266
|
+
status = await adapter.requestPermission();
|
|
267
|
+
} catch (error) {
|
|
268
|
+
if (__DEV__) {
|
|
269
|
+
console.warn(`[cobbai][push] permission request failed: ${errorMessage(error)}`);
|
|
270
|
+
}
|
|
271
|
+
status = 'denied';
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
if (state.runningAdapter === adapter) {
|
|
275
|
+
setAdapterStatus(state, status);
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
return effectiveStatus(state);
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
/**
|
|
282
|
+
* Turns Cobbai pushes off or back on for this device while the user stays logged in (the app's
|
|
283
|
+
* "stop chat notifications" switch). Off unregisters the token from Cobbai only: the device keeps
|
|
284
|
+
* its other notifications. Kept in memory.
|
|
285
|
+
*/
|
|
286
|
+
export function setCobbaiPushEnabled(enabled: boolean): void {
|
|
287
|
+
const state = getState();
|
|
288
|
+
if (state.enabled === enabled) {
|
|
289
|
+
return;
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
state.enabled = enabled;
|
|
293
|
+
|
|
294
|
+
if (enabled) {
|
|
295
|
+
if (state.lastToken) {
|
|
296
|
+
setPushToken(state.lastToken);
|
|
297
|
+
}
|
|
298
|
+
} else {
|
|
299
|
+
clearPushToken();
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
notifyStatus(state);
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
/**
|
|
306
|
+
* iPhone: installs the SDK's notification relay again, after a library that took the
|
|
307
|
+
* notification-centre delegate without chaining (the SDK warns about it in development builds), or
|
|
308
|
+
* when the app turned the automatic install off (`CobbaiPushAutoInstall` = NO). Resolves with
|
|
309
|
+
* whether the relay is in place; false on Android.
|
|
310
|
+
*/
|
|
311
|
+
export async function reinstallCobbaiPushRelay(): Promise<boolean> {
|
|
312
|
+
const native = getNativeCobbaiPush();
|
|
313
|
+
return native ? native.reinstallRelay() : false;
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
export function getCobbaiPushStatus(): CobbaiPushStatus {
|
|
317
|
+
return effectiveStatus(getState());
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
/** Calls `listener` with the current status, then on every change. Returns the unsubscribe function. */
|
|
321
|
+
export function subscribeCobbaiPushStatus(listener: StatusListener): () => void {
|
|
322
|
+
const state = getState();
|
|
323
|
+
state.statusListeners.add(listener);
|
|
324
|
+
listener(effectiveStatus(state));
|
|
325
|
+
|
|
326
|
+
return () => {
|
|
327
|
+
state.statusListeners.delete(listener);
|
|
328
|
+
};
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
export function __resetPushIntegrationForTests(): void {
|
|
332
|
+
const state = getState();
|
|
333
|
+
stopCurrentAdapter(state);
|
|
334
|
+
state.adapterStatus = 'unavailable';
|
|
335
|
+
state.enabled = true;
|
|
336
|
+
state.lastToken = null;
|
|
337
|
+
state.statusListeners.clear();
|
|
338
|
+
}
|
|
@@ -0,0 +1,277 @@
|
|
|
1
|
+
import { normalizeBaseUrl } from './host/buildHostHtml';
|
|
2
|
+
import type { CobbaiPushProvider } from './push';
|
|
3
|
+
import { SDK_VERSION } from './version';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Logout without the WebView: every register answers an unregister secret,
|
|
7
|
+
* relayed to native; at logout the SDK sends `DELETE {baseUrl}/connectors/chats/push_tokens` with
|
|
8
|
+
* it, and keeps the request on the device until the server answers.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Where the SDK keeps the secrets and the pending logouts across app restarts. Shaped like
|
|
13
|
+
* `@react-native-async-storage/async-storage`, which can be passed as is. Without it, they live in
|
|
14
|
+
* memory: a logout still works while the app runs, but not after a restart for a chat that has not
|
|
15
|
+
* been opened since.
|
|
16
|
+
*/
|
|
17
|
+
export type CobbaiPushStorage = {
|
|
18
|
+
getItem(key: string): Promise<string | null>;
|
|
19
|
+
setItem(key: string, value: string): Promise<void>;
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
type Registration = {
|
|
23
|
+
baseUrl: string;
|
|
24
|
+
chatId: string;
|
|
25
|
+
token: string;
|
|
26
|
+
provider: CobbaiPushProvider;
|
|
27
|
+
secret: string;
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
type LogoutState = {
|
|
31
|
+
storage: CobbaiPushStorage | null;
|
|
32
|
+
loaded: Promise<void> | null;
|
|
33
|
+
/** The latest secret per chat and token. */
|
|
34
|
+
registrations: Registration[];
|
|
35
|
+
/** Logouts not answered yet. */
|
|
36
|
+
pending: Registration[];
|
|
37
|
+
flushing: Promise<void> | null;
|
|
38
|
+
};
|
|
39
|
+
|
|
40
|
+
const STATE_KEY = '__COBBAI_PUSH_LOGOUT__';
|
|
41
|
+
/**
|
|
42
|
+
* A logout that got no answer by then is kept and retried later. Without it, a server or captive
|
|
43
|
+
* portal that never answers would hold this request, every logout queued behind it, and
|
|
44
|
+
* `logoutCobbai()`, forever (React Native's fetch has no default timeout).
|
|
45
|
+
*/
|
|
46
|
+
export const PUSH_LOGOUT_TIMEOUT_MS = 15_000;
|
|
47
|
+
export const PUSH_LOGOUT_STORAGE_KEY = 'cobbai.push.logout.v1';
|
|
48
|
+
const PUSH_TOKENS_PATH = '/connectors/chats/push_tokens';
|
|
49
|
+
|
|
50
|
+
function getState(): LogoutState {
|
|
51
|
+
const globalObject = globalThis as typeof globalThis & { [STATE_KEY]?: LogoutState };
|
|
52
|
+
|
|
53
|
+
if (!globalObject[STATE_KEY]) {
|
|
54
|
+
globalObject[STATE_KEY] = {
|
|
55
|
+
storage: null,
|
|
56
|
+
loaded: null,
|
|
57
|
+
registrations: [],
|
|
58
|
+
pending: [],
|
|
59
|
+
flushing: null,
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
return globalObject[STATE_KEY];
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function registrationKey(registration: Registration): string {
|
|
67
|
+
return [
|
|
68
|
+
registration.baseUrl,
|
|
69
|
+
registration.chatId,
|
|
70
|
+
registration.provider,
|
|
71
|
+
registration.token,
|
|
72
|
+
].join('|');
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** Keeps the last entry per key, in the order of their last appearance. */
|
|
76
|
+
function uniqueLatest(registrations: Registration[]): Registration[] {
|
|
77
|
+
const byKey = new Map<string, Registration>();
|
|
78
|
+
registrations.forEach((registration) => {
|
|
79
|
+
const key = registrationKey(registration);
|
|
80
|
+
byKey.delete(key);
|
|
81
|
+
byKey.set(key, registration);
|
|
82
|
+
});
|
|
83
|
+
return [...byKey.values()];
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
function isRegistration(value: unknown): value is Registration {
|
|
87
|
+
if (!value || typeof value !== 'object') return false;
|
|
88
|
+
const record = value as Record<string, unknown>;
|
|
89
|
+
return (
|
|
90
|
+
typeof record.baseUrl === 'string' &&
|
|
91
|
+
typeof record.chatId === 'string' &&
|
|
92
|
+
typeof record.token === 'string' &&
|
|
93
|
+
(record.provider === 'apns' || record.provider === 'fcm') &&
|
|
94
|
+
typeof record.secret === 'string'
|
|
95
|
+
);
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function warn(message: string): void {
|
|
99
|
+
if (__DEV__) {
|
|
100
|
+
console.warn(`[cobbai][push][logout] ${message}`);
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
function errorMessage(error: unknown): string {
|
|
105
|
+
return error instanceof Error ? error.message : String(error);
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** Merges what the storage holds into memory, once per storage. */
|
|
109
|
+
function load(state: LogoutState): Promise<void> {
|
|
110
|
+
if (state.loaded) return state.loaded;
|
|
111
|
+
|
|
112
|
+
const storage = state.storage;
|
|
113
|
+
state.loaded = (async () => {
|
|
114
|
+
if (!storage) return;
|
|
115
|
+
|
|
116
|
+
try {
|
|
117
|
+
const raw = await storage.getItem(PUSH_LOGOUT_STORAGE_KEY);
|
|
118
|
+
if (!raw) return;
|
|
119
|
+
|
|
120
|
+
const stored = JSON.parse(raw) as { registrations?: unknown[]; pending?: unknown[] };
|
|
121
|
+
const storedRegistrations = (stored.registrations ?? []).filter(isRegistration);
|
|
122
|
+
const storedPending = (stored.pending ?? []).filter(isRegistration);
|
|
123
|
+
|
|
124
|
+
// Memory is newer than the storage.
|
|
125
|
+
state.registrations = uniqueLatest([...storedRegistrations, ...state.registrations]);
|
|
126
|
+
state.pending = uniqueLatest([...storedPending, ...state.pending]);
|
|
127
|
+
} catch (error) {
|
|
128
|
+
warn(`could not read the stored logout state: ${errorMessage(error)}`);
|
|
129
|
+
}
|
|
130
|
+
})();
|
|
131
|
+
|
|
132
|
+
return state.loaded;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
async function persist(state: LogoutState): Promise<void> {
|
|
136
|
+
if (!state.storage) return;
|
|
137
|
+
|
|
138
|
+
try {
|
|
139
|
+
await state.storage.setItem(
|
|
140
|
+
PUSH_LOGOUT_STORAGE_KEY,
|
|
141
|
+
JSON.stringify({ registrations: state.registrations, pending: state.pending }),
|
|
142
|
+
);
|
|
143
|
+
} catch (error) {
|
|
144
|
+
warn(`could not store the logout state: ${errorMessage(error)}`);
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/** The server answered for good: a network error, 429 or 5xx is tried again later. */
|
|
149
|
+
function isFinalAnswer(status: number): boolean {
|
|
150
|
+
return status !== 429 && status < 500;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
async function sendLogout(registration: Registration): Promise<boolean> {
|
|
154
|
+
const controller = typeof AbortController === 'function' ? new AbortController() : null;
|
|
155
|
+
let timer: ReturnType<typeof setTimeout> | null = null;
|
|
156
|
+
// Settles even where fetch ignores the abort signal.
|
|
157
|
+
const timeout = new Promise<null>((resolve) => {
|
|
158
|
+
timer = setTimeout(() => {
|
|
159
|
+
controller?.abort();
|
|
160
|
+
resolve(null);
|
|
161
|
+
}, PUSH_LOGOUT_TIMEOUT_MS);
|
|
162
|
+
});
|
|
163
|
+
|
|
164
|
+
try {
|
|
165
|
+
const request = fetch(`${registration.baseUrl}${PUSH_TOKENS_PATH}`, {
|
|
166
|
+
method: 'DELETE',
|
|
167
|
+
// No cookies: on Android the native HTTP client shares the WebView's cookie jar, and the chat
|
|
168
|
+
// session cookie must not travel with another User-Agent (the secret is the only proof).
|
|
169
|
+
credentials: 'omit',
|
|
170
|
+
headers: { Accept: 'application/json', 'Content-Type': 'application/json' },
|
|
171
|
+
body: JSON.stringify({
|
|
172
|
+
chat_id: registration.chatId,
|
|
173
|
+
token: registration.token,
|
|
174
|
+
provider: registration.provider,
|
|
175
|
+
unregister_secret: registration.secret,
|
|
176
|
+
sdk_version: SDK_VERSION,
|
|
177
|
+
}),
|
|
178
|
+
signal: controller?.signal,
|
|
179
|
+
});
|
|
180
|
+
// An abort or network error after the timeout must not surface as an unhandled rejection.
|
|
181
|
+
request.catch(() => {});
|
|
182
|
+
|
|
183
|
+
const response = await Promise.race([request, timeout]);
|
|
184
|
+
return response !== null && isFinalAnswer(response.status);
|
|
185
|
+
} catch {
|
|
186
|
+
return false;
|
|
187
|
+
} finally {
|
|
188
|
+
if (timer) clearTimeout(timer);
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/** Sends the pending logouts. Runs one after the other, so a logout added during a run is sent too. */
|
|
193
|
+
function flush(state: LogoutState): Promise<void> {
|
|
194
|
+
const run = (state.flushing ?? Promise.resolve()).then(() => sendPending(state));
|
|
195
|
+
state.flushing = run;
|
|
196
|
+
return run.finally(() => {
|
|
197
|
+
if (state.flushing === run) state.flushing = null;
|
|
198
|
+
});
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
async function sendPending(state: LogoutState): Promise<void> {
|
|
202
|
+
await load(state);
|
|
203
|
+
if (state.pending.length === 0) return;
|
|
204
|
+
|
|
205
|
+
const answered: string[] = [];
|
|
206
|
+
for (const registration of [...state.pending]) {
|
|
207
|
+
if (await sendLogout(registration)) {
|
|
208
|
+
answered.push(registrationKey(registration));
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
if (answered.length > 0) {
|
|
213
|
+
state.pending = state.pending.filter((item) => !answered.includes(registrationKey(item)));
|
|
214
|
+
await persist(state);
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
/** Called by `configureCobbaiPush`: loads what the storage holds and retries pending logouts. */
|
|
219
|
+
export function setPushLogoutStorage(storage: CobbaiPushStorage | null): Promise<void> {
|
|
220
|
+
const state = getState();
|
|
221
|
+
if (state.storage !== storage) {
|
|
222
|
+
state.storage = storage;
|
|
223
|
+
state.loaded = null;
|
|
224
|
+
}
|
|
225
|
+
return flush(state);
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/** A register the server accepted, with its secret (`cobbai:push-token-registered`). */
|
|
229
|
+
export function rememberUnregisterSecret(registration: Registration): void {
|
|
230
|
+
const state = getState();
|
|
231
|
+
const entry: Registration = { ...registration, baseUrl: normalizeBaseUrl(registration.baseUrl) };
|
|
232
|
+
|
|
233
|
+
state.registrations = uniqueLatest([...state.registrations, entry]);
|
|
234
|
+
void load(state)
|
|
235
|
+
.then(() => {
|
|
236
|
+
state.registrations = uniqueLatest([...state.registrations, entry]);
|
|
237
|
+
return persist(state);
|
|
238
|
+
})
|
|
239
|
+
// A register means the device is online: a good time to retry a pending logout.
|
|
240
|
+
.then(() => flush(state));
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
/**
|
|
244
|
+
* Call it when the user logs out of your app: unregisters this device's push token from Cobbai,
|
|
245
|
+
* without the chat. Your app's own notifications are not affected. Then give the chat
|
|
246
|
+
* screen the next user's config (or the anonymous one): on its next ready, the SDK registers the token
|
|
247
|
+
* again for whoever the chat user is then.
|
|
248
|
+
*
|
|
249
|
+
* Resolves once every logout got an answer or was kept to be retried (no network, or no answer
|
|
250
|
+
* within PUSH_LOGOUT_TIMEOUT_MS): it never rejects.
|
|
251
|
+
*/
|
|
252
|
+
export async function logoutCobbai(): Promise<void> {
|
|
253
|
+
const state = getState();
|
|
254
|
+
await load(state);
|
|
255
|
+
|
|
256
|
+
if (state.registrations.length > 0) {
|
|
257
|
+
state.pending = uniqueLatest([...state.pending, ...state.registrations]);
|
|
258
|
+
state.registrations = [];
|
|
259
|
+
await persist(state);
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
await flush(state);
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
export function __resetPushLogoutForTests(): void {
|
|
266
|
+
const state = getState();
|
|
267
|
+
state.storage = null;
|
|
268
|
+
state.loaded = null;
|
|
269
|
+
state.registrations = [];
|
|
270
|
+
state.pending = [];
|
|
271
|
+
state.flushing = null;
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
export function __getPushLogoutStateForTests(): Pick<LogoutState, 'registrations' | 'pending'> {
|
|
275
|
+
const state = getState();
|
|
276
|
+
return { registrations: [...state.registrations], pending: [...state.pending] };
|
|
277
|
+
}
|
package/src/types.ts
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
export type CobbaiMetadata = Record<string, string | number | boolean | null>;
|
|
2
|
+
|
|
3
|
+
export type CobbaiError = {
|
|
4
|
+
code: string;
|
|
5
|
+
message: string;
|
|
6
|
+
};
|
|
7
|
+
|
|
8
|
+
/** CSS pixels, integers, non-negative. */
|
|
9
|
+
export type CobbaiSafeAreaInsets = {
|
|
10
|
+
top: number;
|
|
11
|
+
right: number;
|
|
12
|
+
bottom: number;
|
|
13
|
+
left: number;
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
export type CobbaiNewMessageEvent = {
|
|
17
|
+
conversationId: number;
|
|
18
|
+
messageId: number;
|
|
19
|
+
speaker: 'agent' | 'auto';
|
|
20
|
+
senderName?: string;
|
|
21
|
+
preview?: string;
|
|
22
|
+
/** True while the chat surface is open (between openChatScreen() and the close request). */
|
|
23
|
+
chatVisible: boolean;
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
export type CobbaiChatConfig = {
|
|
27
|
+
baseUrl: string;
|
|
28
|
+
chatId: string;
|
|
29
|
+
authToken?: string;
|
|
30
|
+
userId?: string;
|
|
31
|
+
metadata?: CobbaiMetadata;
|
|
32
|
+
locale?: string;
|
|
33
|
+
onReady?: () => void;
|
|
34
|
+
onClose?: () => void;
|
|
35
|
+
onError?: (error: CobbaiError) => void;
|
|
36
|
+
onNewMessage?: (event: CobbaiNewMessageEvent) => void;
|
|
37
|
+
onUnreadCountChange?: (total: number) => void;
|
|
38
|
+
};
|
|
39
|
+
|
|
40
|
+
export type CobbaiChatScreenProps = {
|
|
41
|
+
config: CobbaiChatConfig;
|
|
42
|
+
prewarm?: boolean;
|
|
43
|
+
launcherVisible?: boolean;
|
|
44
|
+
launcherBottomOffset?: number;
|
|
45
|
+
inAppBanner?: boolean;
|
|
46
|
+
};
|
package/src/version.ts
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Version of this package, sent to the Cobbai server so that it stays compatible with this release.
|
|
3
|
+
* Must equal `version` in package.json (checked by a test): bump both together.
|
|
4
|
+
*/
|
|
5
|
+
export const SDK_VERSION = '1.0.0-beta.0';
|
|
6
|
+
|
|
7
|
+
/** Version of the protocol between the SDK and the Cobbai server that this release implements. Internal: not exported. */
|
|
8
|
+
export const CONTRACT_VERSION = '1.16';
|