@cometchat/chat-uikit-react-native 5.5.4 → 5.6.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.
Files changed (98) hide show
  1. package/android/src/main/java/com/reactnativecometchatuikit/FileManager.java +78 -3
  2. package/android/src/main/java/com/reactnativecometchatuikit/SafeFileName.java +78 -0
  3. package/ios/CCLocalFileGuard.h +19 -0
  4. package/ios/CCLocalFileGuard.m +34 -0
  5. package/ios/FileManager.m +70 -6
  6. package/ios/VideoManager.m +1 -1
  7. package/package.json +18 -3
  8. package/src/CometChatCompactMessageComposer/CometChatCompactMessageComposer.tsx +124 -55
  9. package/src/CometChatConversations/CometChatConversations.tsx +240 -117
  10. package/src/CometChatGroupMembers/CometChatGroupMembers.tsx +4 -0
  11. package/src/CometChatGroups/CometChatGroups.tsx +61 -52
  12. package/src/CometChatMessageComposer/CometChatMessageComposer.tsx +146 -66
  13. package/src/CometChatMessageHeader/CometChatMessageHeader.tsx +7 -3
  14. package/src/CometChatMessageHeader/listners.ts +76 -56
  15. package/src/CometChatMessageList/CometChatMessageList.tsx +1371 -188
  16. package/src/CometChatNotificationFeed/CometChatNotificationFeed.tsx +71 -7
  17. package/src/CometChatPinnedMessages/CometChatPinnedMessages.tsx +74 -2
  18. package/src/CometChatSavedMessages/CometChatSavedMessages.tsx +69 -4
  19. package/src/CometChatSearch/CometChatSearch.tsx +353 -101
  20. package/src/CometChatThreadHeader/CometChatThreadHeader.tsx +23 -1
  21. package/src/CometChatUsers/CometChatUsers.tsx +2 -0
  22. package/src/calls/CometChatCallButtons/CometChatCallButtons.tsx +19 -0
  23. package/src/extensions/Stickers/StickersExtensionDecorator.tsx +2 -0
  24. package/src/index.ts +6 -0
  25. package/src/shared/CometChatUiKit/CometChatUIKit.ts +85 -2
  26. package/src/shared/CometChatUiKit/UIKitSettings.ts +20 -0
  27. package/src/shared/events/CometChatUIEventHandler/Listener.ts +10 -0
  28. package/src/shared/events/index.ts +4 -0
  29. package/src/shared/events/offline.ts +28 -0
  30. package/src/shared/formatters/CometChatMentionsFormatter/CometChatMentionsFormatter.tsx +5 -3
  31. package/src/shared/framework/MessageDataSource.tsx +34 -14
  32. package/src/shared/index.ts +2 -0
  33. package/src/shared/offline/OfflineHub.ts +651 -0
  34. package/src/shared/offline/OfflineMediaBubble.tsx +49 -0
  35. package/src/shared/offline/OfflineViews.tsx +218 -0
  36. package/src/shared/offline/conversationPins.ts +137 -0
  37. package/src/shared/offline/conversations.ts +325 -0
  38. package/src/shared/offline/frameProbe.ts +24 -0
  39. package/src/shared/offline/gate.ts +94 -0
  40. package/src/shared/offline/groupActions.ts +81 -0
  41. package/src/shared/offline/identity.ts +162 -0
  42. package/src/shared/offline/index.ts +76 -0
  43. package/src/shared/offline/media.ts +247 -0
  44. package/src/shared/offline/notices.ts +90 -0
  45. package/src/shared/offline/reconcile.ts +296 -0
  46. package/src/shared/offline/searchOutcome.ts +62 -0
  47. package/src/shared/offline/send.ts +430 -0
  48. package/src/shared/offline/stateContract.ts +85 -0
  49. package/src/shared/offline/threadReplies.ts +125 -0
  50. package/src/shared/offline/twoPhase.ts +372 -0
  51. package/src/shared/offline/unsentActions.ts +168 -0
  52. package/src/shared/offline/useOfflineMediaUri.ts +87 -0
  53. package/src/shared/offline/useOfflineReconnect.ts +25 -0
  54. package/src/shared/offline/useOfflineSessionEnded.ts +22 -0
  55. package/src/shared/offline/useOfflineUploadTray.ts +76 -0
  56. package/src/shared/offline/usePresenceHidden.ts +33 -0
  57. package/src/shared/resources/CometChatLocalizeNew/resources/de/translation.json +24 -1
  58. package/src/shared/resources/CometChatLocalizeNew/resources/en/translation.json +24 -1
  59. package/src/shared/resources/CometChatLocalizeNew/resources/es/translation.json +24 -1
  60. package/src/shared/resources/CometChatLocalizeNew/resources/fr/translation.json +24 -1
  61. package/src/shared/resources/CometChatLocalizeNew/resources/hi/translation.json +24 -1
  62. package/src/shared/resources/CometChatLocalizeNew/resources/hu/translation.json +24 -1
  63. package/src/shared/resources/CometChatLocalizeNew/resources/it/translation.json +24 -1
  64. package/src/shared/resources/CometChatLocalizeNew/resources/ja/translation.json +24 -1
  65. package/src/shared/resources/CometChatLocalizeNew/resources/ko/translation.json +24 -1
  66. package/src/shared/resources/CometChatLocalizeNew/resources/lt/translation.json +24 -1
  67. package/src/shared/resources/CometChatLocalizeNew/resources/ms/translation.json +24 -1
  68. package/src/shared/resources/CometChatLocalizeNew/resources/nl/translation.json +24 -1
  69. package/src/shared/resources/CometChatLocalizeNew/resources/pt/translation.json +24 -1
  70. package/src/shared/resources/CometChatLocalizeNew/resources/ru/translation.json +24 -1
  71. package/src/shared/resources/CometChatLocalizeNew/resources/sv/translation.json +24 -1
  72. package/src/shared/resources/CometChatLocalizeNew/resources/tr/translation.json +24 -1
  73. package/src/shared/resources/CometChatLocalizeNew/resources/zh/translation.json +24 -1
  74. package/src/shared/resources/CometChatLocalizeNew/resources/zh-tw/translation.json +24 -1
  75. package/src/shared/services/UploadQueueService.ts +106 -1
  76. package/src/shared/utils/MessageReceiptUtils.ts +8 -0
  77. package/src/shared/utils/SavedMessagesHelper.ts +18 -1
  78. package/src/shared/utils/catchUpCursor.ts +36 -0
  79. package/src/shared/utils/failedMessageRetry.ts +73 -0
  80. package/src/shared/utils/messageIdentity.ts +38 -0
  81. package/src/shared/views/CometChatAttachmentViewer/CometChatAttachmentViewer.tsx +34 -5
  82. package/src/shared/views/CometChatAudiosBubble/CometChatAudiosBubble.tsx +10 -2
  83. package/src/shared/views/CometChatFileBubble/CometChatFileBubble.tsx +13 -27
  84. package/src/shared/views/CometChatFilesBubble/CometChatFilesBubble.tsx +60 -11
  85. package/src/shared/views/CometChatImagesBubble/CometChatImagesBubble.tsx +27 -2
  86. package/src/shared/views/CometChatList/CometChatList.tsx +468 -7
  87. package/src/shared/views/CometChatMediaViewer/CometChatMediaViewer.tsx +27 -5
  88. package/src/shared/views/CometChatMessageInput/CometChatMessageInput.tsx +1 -0
  89. package/src/shared/views/CometChatReactionList/CometChatReactionList.tsx +56 -10
  90. package/src/shared/views/CometChatStatusIndicator/CometChatStatusIndicator.tsx +4 -0
  91. package/src/shared/views/CometChatVideosBubble/CometChatVideosBubble.tsx +36 -2
  92. package/src/shared/views/CometChatVoiceNoteBubble/CometChatVoiceNoteBubble.tsx +24 -12
  93. package/src/theme/type.ts +17 -0
  94. package/android/.gradle/7.4/checksums/checksums.lock +0 -0
  95. package/android/.gradle/7.4/fileChanges/last-build.bin +0 -0
  96. package/android/.gradle/7.4/fileHashes/fileHashes.lock +0 -0
  97. package/android/.gradle/7.4/gc.properties +0 -0
  98. package/android/.gradle/vcs-1/gc.properties +0 -0
@@ -0,0 +1,651 @@
1
+ /**
2
+ * OfflineHub: the kit's single bridge from the Chat SDK's offline listeners to the screens that
3
+ * are mounted (README §3.5).
4
+ *
5
+ * - Started by `CometChatUIKit.init()` / `initFromSettings()` inside the SDK init's `.then`, never
6
+ * at import. Idempotent.
7
+ * - Registers each SDK listener once, under its own id, and only those the installed SDK has.
8
+ * They are inert while offline is off: the SDK never fires them.
9
+ * - Never unregistered on logout (SDK registrations survive logout/login). A logout or user switch
10
+ * clears the hub's own bookkeeping and bumps `gen`, so late callbacks of the old session are
11
+ * dropped by every screen.
12
+ * - Fans out on private subjects, never on the kit's public event bus. Integrators get only the
13
+ * additive public events (`ccMessageSendStateChanged`, `ccOfflineCacheReset`) and the existing
14
+ * `ccMessageSent`, emitted once per transition per `localMessageId`.
15
+ *
16
+ * @internal
17
+ */
18
+ import { Subject } from "rxjs";
19
+ import { CometChat } from "@cometchat/chat-sdk-react-native";
20
+ import { CometChatUIEventHandler } from "../events/CometChatUIEventHandler/CometChatUIEventHandler";
21
+ import { hasSdkFunction, offlineSdk } from "./gate";
22
+ import { conversationIdOf, localIdOf, muidOf, OfflineFailureReason } from "./identity";
23
+ import { isGroupMemberAction } from "./groupActions";
24
+
25
+ import { MessageSendState, OfflineMessageEvents } from "../events/offline";
26
+
27
+ export type { MessageSendState };
28
+ export { OfflineMessageEvents };
29
+
30
+ export interface SendStateEvent {
31
+ gen: number;
32
+ localMessageId: string;
33
+ message: any;
34
+ state: MessageSendState;
35
+ /** `MessageFailureReason` for `failed` / `discarded`. */
36
+ reason?: string;
37
+ /** A failure the outbox does not hold: its Retry is a fresh send. */
38
+ direct?: boolean;
39
+ }
40
+
41
+ export interface MessageSyncEvent { gen: number; messages: any[]; outcome: string }
42
+ export interface ConversationSyncEvent { gen: number; conversations: any[] }
43
+ export interface MessagesUpdatedEvent { gen: number; messages: any[] }
44
+ export interface CacheResetEvent { gen: number; reason: string; pendingMessagesLost: number | null }
45
+ export interface MediaReadyEvent { gen: number; messageKey: string; urlKey: string; localPath: string }
46
+ export interface SyncFailedEvent { gen: number; phase: "conversation" | "message"; error: unknown }
47
+ /** A conversation pinned or unpinned on another device or by an admin (SDK `ConversationListener`). */
48
+ export interface ConversationPinEvent { gen: number; pinned: boolean; conversation: any }
49
+ /** One group-member action the catch-up sweep delivered (no GroupListener callback fires for it). */
50
+ export interface GroupActionSweptEvent { gen: number; message: any }
51
+
52
+ export type OfflineNoticeKind =
53
+ | "unsent_message_removed"
54
+ | "queue_full"
55
+ | "file_too_large_offline"
56
+ | "messages_not_sent"
57
+ | "unsent_messages_lost"
58
+ | "unsent_messages_maybe_lost"
59
+ /** Retry or Delete tapped while the send is under way (R162): try again shortly. */
60
+ | "send_in_flight"
61
+ /** Download / Share on media the device has no copy of, while offline (BEH-MEDIA-18). */
62
+ | "media_available_when_online";
63
+
64
+ export interface OfflineNotice {
65
+ gen: number;
66
+ kind: OfflineNoticeKind;
67
+ count?: number;
68
+ /** The removed message, for Copy (text only). */
69
+ message?: any;
70
+ /** Conversation the notice belongs to, when it belongs to one. */
71
+ conversationId?: string;
72
+ /** About chat-list previews only: an open chat, which has its own count, does not show it. */
73
+ previewsOnly?: boolean;
74
+ }
75
+
76
+ export const OFFLINE_LISTENER_IDS = Object.freeze({
77
+ outbox: "uikit_offline_hub_outbox",
78
+ sync: "uikit_offline_hub_sync",
79
+ cacheReset: "uikit_offline_hub_cache_reset",
80
+ media: "uikit_offline_hub_media",
81
+ messagesSynced: "uikit_offline_hub_messages_synced",
82
+ login: "uikit_offline_hub_login",
83
+ conversationPin: "uikit_offline_hub_conversation_pin",
84
+ connection: "uikit_offline_hub_connection",
85
+ });
86
+
87
+ const MAX_TRACKED_SENDS = 500;
88
+
89
+ /** Forward-only transitions; `failed → sending` is a retry, anything may become `sent`. */
90
+ function isForward(from: MessageSendState | undefined, to: MessageSendState): boolean {
91
+ if (from === undefined) return true;
92
+ if (from === to) return false;
93
+ if (to === "sent") return from !== "discarded";
94
+ if (from === "sent" || from === "discarded") return false;
95
+ if (from === "failed") return to === "sending" || to === "discarded";
96
+ return true;
97
+ }
98
+
99
+ function normalizeReason(raw: unknown): string {
100
+ if (typeof raw === "string") return raw;
101
+ const code = (raw as any)?.code ?? (raw as any)?.reason;
102
+ return typeof code === "string" ? code : "";
103
+ }
104
+
105
+ function safeEmit(name: string, payload: object): void {
106
+ try {
107
+ CometChatUIEventHandler.emitMessageEvent(name, payload);
108
+ } catch (e) {
109
+ console.warn(`[CometChatUIKit] ${name} listener threw:`, e);
110
+ }
111
+ }
112
+
113
+ const MAX_UNDELIVERED_NOTICES = 8;
114
+
115
+ export class OfflineHub {
116
+ private static instance: OfflineHub | null = null;
117
+
118
+ static getInstance(): OfflineHub {
119
+ if (!OfflineHub.instance) OfflineHub.instance = new OfflineHub();
120
+ return OfflineHub.instance;
121
+ }
122
+
123
+ /** Tests only: drop the singleton so each test starts clean. */
124
+ static resetForTests(): void {
125
+ OfflineHub.instance = null;
126
+ }
127
+
128
+ readonly sendState$ = new Subject<SendStateEvent>();
129
+ readonly messageSync$ = new Subject<MessageSyncEvent>();
130
+ readonly syncFailed$ = new Subject<SyncFailedEvent>();
131
+ readonly conversationSync$ = new Subject<ConversationSyncEvent>();
132
+ readonly messagesUpdated$ = new Subject<MessagesUpdatedEvent>();
133
+ readonly cacheReset$ = new Subject<CacheResetEvent>();
134
+ readonly mediaReady$ = new Subject<MediaReadyEvent>();
135
+ readonly notice$ = new Subject<OfflineNotice>();
136
+ /** Remote conversation pin / unpin (UIK-CONV-01). Screens gate it per event. */
137
+ readonly conversationPin$ = new Subject<ConversationPinEvent>();
138
+ /** Swept group-member actions, after `messageSync$` (UIT-SYNC-13). */
139
+ readonly groupActionSwept$ = new Subject<GroupActionSweptEvent>();
140
+ /** Emits the new `gen` after a logout, user switch or cache reset. */
141
+ readonly session$ = new Subject<number>();
142
+ /**
143
+ * Emits the new `gen` after a logout or a user switch only (not a cache reset, which also fires
144
+ * `session$`). A send still waiting for the SDK is settled by it (Android `SessionEnded`).
145
+ */
146
+ readonly sessionEnd$ = new Subject<number>();
147
+ /**
148
+ * The SDK's realtime connection came up. A plain SDK listener, so it fires with offline off too;
149
+ * screens read the gate before acting on it.
150
+ */
151
+ readonly connected$ = new Subject<number>();
152
+ /** The SDK's realtime connection went down. Same listener as `connected$`; screens read the gate. */
153
+ readonly disconnected$ = new Subject<number>();
154
+
155
+ private started = false;
156
+ private cacheResetRegistered = false;
157
+ private undeliveredNotices: OfflineNotice[] = [];
158
+ private startAnnouncementsRegistered = false;
159
+ private genValue = 0;
160
+ private sessionUid: string | null = null;
161
+ /** Last state emitted, per `localMessageId` (ON path only). */
162
+ private readonly lastState = new Map<string, MessageSendState>();
163
+ /** Conversations whose read could not reach the server while offline (AC-7.4). */
164
+ private readonly readWhileOffline = new Map<string, { id: string; type: string }>();
165
+ /** Own messages that failed without entering the outbox ("direct"), by muid, for the session. */
166
+ private readonly directFailures = new Map<string, string>();
167
+ /** Retries handed to the SDK and not answered yet; further taps are ignored. */
168
+ private readonly retriesInFlight = new Set<string>();
169
+ /** The `MessageFailureReason` of the last failure, per `localMessageId` (BEH-SEND-35/37). */
170
+ private readonly failureReasons = new Map<string, string>();
171
+ /**
172
+ * Own messages whose refusal (queue full, file too large offline) already raised its notice, by
173
+ * `localMessageId` (else muid): the notice shows once per message.
174
+ */
175
+ private readonly refusalNotices = new Set<string>();
176
+ /** Server id of an own message once it was reported sent, per `localMessageId` (Delete race). */
177
+ private readonly sentIds = new Map<string, number>();
178
+ /**
179
+ * Own messages the user deleted while the SDK no longer held them, by `localMessageId`: if a
180
+ * sent copy still arrives, it is deleted on the server.
181
+ */
182
+ private readonly deleteOnSent = new Set<string>();
183
+
184
+ get gen(): number {
185
+ return this.genValue;
186
+ }
187
+
188
+ get isStarted(): boolean {
189
+ return this.started;
190
+ }
191
+
192
+ /** The signed-in uid as last reported by the SDK (scopes per-user files such as playable copies). */
193
+ get currentUid(): string | null {
194
+ return this.sessionUid;
195
+ }
196
+
197
+ /**
198
+ * The two listeners for what the SDK announces about a start go in before the SDK's init. A start
199
+ * can wipe a bad store (cache reset) and lose queued sends (`DISCARDED`), and the SDK tells only the
200
+ * listeners registered when it delivers them: during init, or just after it resolves. A listener
201
+ * added later never hears them, so these cannot wait for the rest of `start()`, which needs the
202
+ * SDK initialized. Registering stores a callback and nothing else, so they are inert while offline
203
+ * is off; a no-op on an SDK without them. Idempotent.
204
+ */
205
+ listenForStartAnnouncements(): void {
206
+ if (this.startAnnouncementsRegistered) return;
207
+ this.startAnnouncementsRegistered = true;
208
+ this.register("addOfflineCacheResetListener", OFFLINE_LISTENER_IDS.cacheReset, {
209
+ onOfflineCacheReset: (reason: unknown, lost: unknown) => this.onCacheReset(reason, lost),
210
+ });
211
+ this.register("addOfflineMessageListener", OFFLINE_LISTENER_IDS.outbox, {
212
+ onOutboxMessagePending: (m: any) => this.onOutboxPending(m),
213
+ onOutboxMessageSent: (m: any) => this.onOutboxSent(m),
214
+ onOutboxMessageFailed: (m: any, reason: unknown) => this.onOutboxFailed(m, reason),
215
+ });
216
+ }
217
+
218
+ /** Register the SDK listeners. Safe from every init entry point; only the first call registers. */
219
+ start(): void {
220
+ if (this.started) return;
221
+ this.started = true;
222
+ // An SDK without the offline surface gets nothing registered, so a kit on an older SDK
223
+ // behaves exactly as before.
224
+ if (!hasSdkFunction("isOfflineEnabled")) return;
225
+ this.listenForStartAnnouncements();
226
+ this.register("addSyncListener", OFFLINE_LISTENER_IDS.sync, {
227
+ onConversationSyncCompleted: (list: any[]) =>
228
+ this.conversationSync$.next({ gen: this.genValue, conversations: Array.isArray(list) ? list : [] }),
229
+ onConversationSyncError: (error: unknown) =>
230
+ this.syncFailed$.next({ gen: this.genValue, phase: "conversation", error }),
231
+ onMessageSyncCompleted: (list: any[], outcome: unknown) => this.onMessageSyncCompleted(list, outcome),
232
+ onMessageSyncError: (error: unknown) => this.syncFailed$.next({ gen: this.genValue, phase: "message", error }),
233
+ });
234
+ this.register("addMediaDownloadListener", OFFLINE_LISTENER_IDS.media, {
235
+ onMediaDownloaded: (messageKey: unknown, urlKey: unknown, localPath: unknown) =>
236
+ this.mediaReady$.next({
237
+ gen: this.genValue,
238
+ messageKey: String(messageKey ?? ""),
239
+ urlKey: String(urlKey ?? ""),
240
+ localPath: String(localPath ?? ""),
241
+ }),
242
+ });
243
+ try {
244
+ CometChat.addMessageListener(
245
+ OFFLINE_LISTENER_IDS.messagesSynced,
246
+ new CometChat.MessageListener({
247
+ onMessagesSynced: (list: any[]) =>
248
+ this.messagesUpdated$.next({ gen: this.genValue, messages: Array.isArray(list) ? list : [] }),
249
+ } as any)
250
+ );
251
+ } catch (e) {
252
+ console.warn("[CometChatUIKit] OfflineHub: could not register the synced-messages listener", e);
253
+ }
254
+ this.registerConversationPinListener();
255
+ try {
256
+ CometChat.addConnectionListener(
257
+ OFFLINE_LISTENER_IDS.connection,
258
+ new CometChat.ConnectionListener({
259
+ onConnected: () => this.connected$.next(this.genValue),
260
+ onDisconnected: () => this.disconnected$.next(this.genValue),
261
+ })
262
+ );
263
+ } catch (e) {
264
+ console.warn("[CometChatUIKit] OfflineHub: could not register the connection listener", e);
265
+ }
266
+ try {
267
+ CometChat.addLoginListener(
268
+ OFFLINE_LISTENER_IDS.login,
269
+ new CometChat.LoginListener({
270
+ loginSuccess: (user: any) => this.onLogin(user),
271
+ logoutSuccess: () => this.endSession(),
272
+ } as any)
273
+ );
274
+ } catch (e) {
275
+ console.warn("[CometChatUIKit] OfflineHub: could not register the login listener", e);
276
+ }
277
+ }
278
+
279
+ /**
280
+ * Conversation pin / unpin from the user's other devices and from admin pins
281
+ * (`CometChat.addConversationListener`, feature-detected: older SDKs have none). The SDK fires it
282
+ * whether offline is on or not, so the conversation list reads the gate per event and ignores it
283
+ * with offline off, as the release before it did.
284
+ */
285
+ private registerConversationPinListener(): void {
286
+ if (!hasSdkFunction("addConversationListener")) return;
287
+ const handlers = {
288
+ onConversationPinned: (conversation: any) =>
289
+ this.conversationPin$.next({ gen: this.genValue, pinned: true, conversation }),
290
+ onConversationUnpinned: (conversation: any) =>
291
+ this.conversationPin$.next({ gen: this.genValue, pinned: false, conversation }),
292
+ };
293
+ try {
294
+ const sdk = offlineSdk();
295
+ const ListenerClass = sdk.ConversationListener;
296
+ const listener = typeof ListenerClass === "function" ? new ListenerClass(handlers) : handlers;
297
+ sdk.addConversationListener(OFFLINE_LISTENER_IDS.conversationPin, listener);
298
+ } catch (e) {
299
+ console.warn("[CometChatUIKit] OfflineHub: could not register the conversation pin listener", e);
300
+ }
301
+ }
302
+
303
+ private register(method: string, id: string, handlers: Record<string, Function>): void {
304
+ if (!hasSdkFunction(method)) return;
305
+ try {
306
+ const result = offlineSdk()[method](id, handlers);
307
+ // addMediaDownloadListener is async on RN.
308
+ if (result && typeof result.then === "function") result.then(undefined, () => {});
309
+ } catch (e) {
310
+ console.warn(`[CometChatUIKit] OfflineHub: could not register ${method}`, e);
311
+ }
312
+ }
313
+
314
+ // ── Session ───────────────────────────────────────────────────────────────
315
+
316
+ /** Record who is signed in; a different uid ends the previous session first (AC-2.3). */
317
+ onLogin(user: any): void {
318
+ const uid = typeof user?.getUid === "function" ? user.getUid() : user?.uid ?? null;
319
+ if (this.sessionUid !== null && uid !== this.sessionUid) this.endSession();
320
+ this.sessionUid = uid ?? null;
321
+ }
322
+
323
+ /** Logout or user switch: forget every per-session mark and bump `gen`. Never clears the SDK cache. */
324
+ endSession(): void {
325
+ this.lastState.clear();
326
+ this.readWhileOffline.clear();
327
+ this.directFailures.clear();
328
+ this.retriesInFlight.clear();
329
+ this.failureReasons.clear();
330
+ this.sentIds.clear();
331
+ this.deleteOnSent.clear();
332
+ this.refusalNotices.clear();
333
+ this.undeliveredNotices = [];
334
+ this.sessionUid = null;
335
+ this.genValue++;
336
+ this.session$.next(this.genValue);
337
+ this.sessionEnd$.next(this.genValue);
338
+ }
339
+
340
+ // ── Sends ─────────────────────────────────────────────────────────────────
341
+
342
+ /**
343
+ * Report one transition of an own message's send. The per-send listener and the outbox
344
+ * listener both funnel through here, so each transition reaches the screens and the public
345
+ * events exactly once per `localMessageId`. `announced` marks a `sending` the caller already
346
+ * announced publicly (the composer emits `inprogress` at compose time).
347
+ */
348
+ reportSendState(
349
+ message: any,
350
+ state: MessageSendState,
351
+ options: { reason?: string; direct?: boolean; announced?: boolean } = {}
352
+ ): boolean {
353
+ const localMessageId = localIdOf(message);
354
+ if (state === "failed" && options.direct) this.markDirectFailed(message, options.reason ?? "");
355
+ else if (state !== "failed") this.clearDirectFailed(message);
356
+ if (state !== "sending" && localMessageId) this.retriesInFlight.delete(localMessageId);
357
+ if (!localMessageId) {
358
+ // Nothing to dedupe on; a direct failure the SDK never queued still has to reach the screen.
359
+ if (state === "failed") {
360
+ this.sendState$.next({ gen: this.genValue, localMessageId: "", message, state, reason: options.reason, direct: true });
361
+ this.emitPublic(message, state, options.reason);
362
+ }
363
+ return state === "failed";
364
+ }
365
+ const previous = this.lastState.get(localMessageId);
366
+ if (state === "sent") this.rememberSentId(localMessageId, message);
367
+ if (!isForward(previous, state)) return false;
368
+ this.track(localMessageId, state);
369
+ if (state === "failed") this.remember(this.failureReasons, localMessageId, options.reason ?? "");
370
+ else this.failureReasons.delete(localMessageId);
371
+ this.sendState$.next({ gen: this.genValue, localMessageId, message, state, reason: options.reason, direct: options.direct });
372
+ if (state === "sending" && (options.announced || previous === undefined)) {
373
+ this.emitStateChanged(message, state, options.reason);
374
+ } else {
375
+ this.emitPublic(message, state, options.reason);
376
+ }
377
+ return true;
378
+ }
379
+
380
+ stateOf(localMessageId: string): MessageSendState | undefined {
381
+ return this.lastState.get(localMessageId);
382
+ }
383
+
384
+ /** The reason the last failure of `localMessageId` reported, `""` when unknown (R95). */
385
+ failureReasonFor(localMessageId: string): string {
386
+ return (localMessageId && this.failureReasons.get(localMessageId)) || "";
387
+ }
388
+
389
+ /** The server id `localMessageId` was sent under, if this session saw it sent. */
390
+ sentIdFor(localMessageId: string): number | undefined {
391
+ return localMessageId ? this.sentIds.get(localMessageId) : undefined;
392
+ }
393
+
394
+ /** Whether a retry of `localMessageId` is handed to the SDK and not answered yet. */
395
+ isRetrying(localMessageId: string): boolean {
396
+ return !!localMessageId && this.retriesInFlight.has(localMessageId);
397
+ }
398
+
399
+ private rememberSentId(localMessageId: string, message: any): void {
400
+ const raw = typeof message?.getId === "function" ? message.getId() : message?.id;
401
+ const id = Number(raw);
402
+ if (!Number.isFinite(id) || id <= 0) return;
403
+ this.remember(this.sentIds, localMessageId, id);
404
+ if (this.deleteOnSent.delete(localMessageId)) {
405
+ CometChat.deleteMessage(String(id)).catch((error: unknown) =>
406
+ console.warn("[CometChatUIKit] deleting a removed message on the server failed", error)
407
+ );
408
+ }
409
+ }
410
+
411
+ /** Delete the sent copy of `localMessageId` on the server if it still arrives. */
412
+ deleteWhenSent(localMessageId: string): void {
413
+ if (localMessageId) this.deleteOnSent.add(localMessageId);
414
+ }
415
+
416
+ private remember<V>(map: Map<string, V>, key: string, value: V): void {
417
+ map.delete(key);
418
+ map.set(key, value);
419
+ if (map.size > MAX_TRACKED_SENDS) {
420
+ const oldest = map.keys().next().value;
421
+ if (oldest !== undefined) map.delete(oldest);
422
+ }
423
+ }
424
+
425
+ markDirectFailed(message: any, reason: string): void {
426
+ const muid = muidOf(message);
427
+ if (muid) this.directFailures.set(muid, reason);
428
+ }
429
+
430
+ clearDirectFailed(message: any): void {
431
+ const muid = muidOf(message);
432
+ if (muid) this.directFailures.delete(muid);
433
+ }
434
+
435
+ /** The failure reason when `message` failed direct this session, else `undefined`. */
436
+ directFailureOf(message: any): string | undefined {
437
+ const muid = muidOf(message);
438
+ return muid ? this.directFailures.get(muid) : undefined;
439
+ }
440
+
441
+ /** Claim a retry for `localMessageId`; false while one is already in flight. */
442
+ beginRetry(localMessageId: string): boolean {
443
+ if (!localMessageId || this.retriesInFlight.has(localMessageId)) return false;
444
+ this.retriesInFlight.add(localMessageId);
445
+ return true;
446
+ }
447
+
448
+ endRetry(localMessageId: string): void {
449
+ this.retriesInFlight.delete(localMessageId);
450
+ }
451
+
452
+ /**
453
+ * The SDK answered `ERROR_OFFLINE_MESSAGE_IN_FLIGHT` to a Retry or a Delete (BEH-SEND-20/36): the
454
+ * message's send is under way and nothing changed. The user gets the short "Sending… try again
455
+ * in a moment" notice (R162 / S73). Screens show one at a time and it dismisses itself.
456
+ */
457
+ raiseSendInFlightNotice(message: any): void {
458
+ this.notify({ kind: "send_in_flight", message, conversationId: conversationIdOf(message) });
459
+ }
460
+
461
+ notify(notice: Omit<OfflineNotice, "gen">): void {
462
+ const stamped = { gen: this.genValue, ...notice };
463
+ // No screen is mounted yet (the SDK reported it during or just after init): keep it for the first.
464
+ // A chat's notice is also kept while screens are mounted, until that chat's list shows it
465
+ // (`claimNotice`): raised while the chat list is up, it shows when the chat is opened.
466
+ // The short "Sending…" answer to one tap is never kept: it would show later, on another screen.
467
+ const forOneChat = !!notice.conversationId && !notice.previewsOnly;
468
+ if (notice.kind !== "send_in_flight" && (!this.notice$.observed || forOneChat)) {
469
+ // Full: a newer chat notice replaces the oldest chat one (never a session-wide one).
470
+ const oldestChat = this.undeliveredNotices.findIndex((kept) => !!kept.conversationId);
471
+ if (forOneChat && this.undeliveredNotices.length >= MAX_UNDELIVERED_NOTICES && oldestChat >= 0) {
472
+ this.undeliveredNotices.splice(oldestChat, 1);
473
+ }
474
+ if (this.undeliveredNotices.length < MAX_UNDELIVERED_NOTICES) this.undeliveredNotices.push(stamped);
475
+ }
476
+ this.notice$.next(stamped);
477
+ }
478
+
479
+ /** A mounted screen showed this notice: it is no longer kept for a later one. */
480
+ claimNotice(notice: OfflineNotice): void {
481
+ this.undeliveredNotices = this.undeliveredNotices.filter((kept) => kept !== notice);
482
+ }
483
+
484
+ /** The notices that fired before any screen was listening and belong to this screen, oldest first. */
485
+ takeUndeliveredNotices(belongsHere: (notice: OfflineNotice) => boolean): OfflineNotice[] {
486
+ const mine = this.undeliveredNotices.filter((notice) => belongsHere(notice));
487
+ this.undeliveredNotices = this.undeliveredNotices.filter((notice) => !mine.includes(notice));
488
+ return mine;
489
+ }
490
+
491
+ private track(localMessageId: string, state: MessageSendState): void {
492
+ this.lastState.delete(localMessageId);
493
+ this.lastState.set(localMessageId, state);
494
+ if (this.lastState.size > MAX_TRACKED_SENDS) {
495
+ const oldest = this.lastState.keys().next().value;
496
+ if (oldest !== undefined) this.lastState.delete(oldest);
497
+ }
498
+ }
499
+
500
+ private emitPublic(message: any, state: MessageSendState, reason?: string): void {
501
+ const status = state === "sent" ? "success" : state === "sending" ? "inprogress" : "error";
502
+ safeEmit("ccMessageSent", { message, status });
503
+ this.emitStateChanged(message, state, reason);
504
+ }
505
+
506
+ private emitStateChanged(message: any, state: MessageSendState, reason?: string): void {
507
+ safeEmit(OfflineMessageEvents.ccMessageSendStateChanged, { message, state, reason });
508
+ }
509
+
510
+ private onOutboxPending(message: any): void {
511
+ // A retry turns a failed row back into a sending one; a fresh send was already announced.
512
+ this.reportSendState(message, "sending", { announced: this.lastState.get(localIdOf(message)) !== "failed" });
513
+ }
514
+
515
+ private onOutboxSent(message: any): void {
516
+ this.reportSendState(message, "sent");
517
+ }
518
+
519
+ private onOutboxFailed(message: any, rawReason: unknown): void {
520
+ this.reportFailure(message, rawReason);
521
+ }
522
+
523
+ /**
524
+ * A final failure, from the per-send `onError` or the outbox `onOutboxMessageFailed` (whichever
525
+ * comes first; the other is deduped). `DISCARDED` / `QUEUE_OVERFLOW` remove the row with a
526
+ * notice; `QUEUE_FULL` / `BYTE_OVERFLOW` are failed (direct) whatever came before, with a
527
+ * notice; anything else is failed (outbox), retried with `retryMessage`.
528
+ */
529
+ reportFailure(message: any, rawReason: unknown, options: { direct?: boolean } = {}): boolean {
530
+ const reason = normalizeReason(rawReason);
531
+ if (reason === OfflineFailureReason.discarded || reason === OfflineFailureReason.queueOverflow) {
532
+ const removed = this.reportSendState(message, "discarded", { reason });
533
+ if (removed) {
534
+ this.notify({ kind: "unsent_message_removed", count: 1, message, conversationId: conversationIdOf(message) });
535
+ }
536
+ return removed;
537
+ }
538
+ const refusal = reason === OfflineFailureReason.queueFull || reason === OfflineFailureReason.byteOverflow;
539
+ const direct = !!options.direct || refusal;
540
+ // A refused message may carry no local id; the per-send and global callbacks both report it.
541
+ if (direct && !localIdOf(message) && this.directFailureOf(message) === reason && this.directFailureOf(message) !== undefined) {
542
+ return false;
543
+ }
544
+ const reported = this.reportSendState(message, "failed", { reason, direct });
545
+ if (!refusal) return reported;
546
+ if (!reported) {
547
+ // The send's own onError reported the failure first and did not name the refusal; the
548
+ // outbox's callback names it for certain, so the row keeps that reason.
549
+ this.markDirectFailed(message, reason);
550
+ const localMessageId = localIdOf(message);
551
+ if (localMessageId) this.remember(this.failureReasons, localMessageId, reason);
552
+ }
553
+ this.raiseRefusalNotice(message, reason);
554
+ return reported;
555
+ }
556
+
557
+ /**
558
+ * The notice for a send the outbox refused (`QUEUE_FULL`, `BYTE_OVERFLOW`), raised once per
559
+ * message whichever SDK callback reports the refusal first (UIK-SEND-03): the SDK reports one
560
+ * refusal twice, to the send's own `onError` and to the global `onOutboxMessageFailed`. Any
561
+ * other reason raises nothing.
562
+ */
563
+ raiseRefusalNotice(message: any, reason: string): void {
564
+ if (reason !== OfflineFailureReason.queueFull && reason !== OfflineFailureReason.byteOverflow) return;
565
+ const key = localIdOf(message) || muidOf(message);
566
+ if (key) {
567
+ if (this.refusalNotices.has(key)) return;
568
+ this.refusalNotices.add(key);
569
+ if (this.refusalNotices.size > MAX_TRACKED_SENDS) {
570
+ const oldest = this.refusalNotices.values().next().value;
571
+ if (oldest !== undefined) this.refusalNotices.delete(oldest);
572
+ }
573
+ }
574
+ this.notify({
575
+ kind: reason === OfflineFailureReason.queueFull ? "queue_full" : "file_too_large_offline",
576
+ message,
577
+ conversationId: conversationIdOf(message),
578
+ });
579
+ }
580
+
581
+ /** A user removed an unsent row (Delete): tell screens and integrators, no legacy error event. */
582
+ reportDiscardedByUser(message: any): void {
583
+ this.clearDirectFailed(message);
584
+ const localMessageId = localIdOf(message);
585
+ if (localMessageId) {
586
+ if (!isForward(this.lastState.get(localMessageId), "discarded")) return;
587
+ this.track(localMessageId, "discarded");
588
+ }
589
+ this.sendState$.next({ gen: this.genValue, localMessageId, message, state: "discarded", reason: OfflineFailureReason.discarded });
590
+ this.emitStateChanged(message, "discarded", OfflineFailureReason.discarded);
591
+ }
592
+
593
+ // ── Sync, reset ───────────────────────────────────────────────────────────
594
+
595
+ private onMessageSyncCompleted(list: any[], outcome: unknown): void {
596
+ const messages = Array.isArray(list) ? list : [];
597
+ this.messageSync$.next({ gen: this.genValue, messages, outcome: String(outcome ?? "") });
598
+ // The rows are in; now the screens run their live group handlers for each swept action.
599
+ for (const message of messages) {
600
+ if (isGroupMemberAction(message)) this.groupActionSwept$.next({ gen: this.genValue, message });
601
+ }
602
+ this.flushReadsMadeOffline();
603
+ }
604
+
605
+ private onCacheReset(rawReason: unknown, rawLost: unknown): void {
606
+ const reason = String(rawReason ?? "");
607
+ const lostNumber = typeof rawLost === "number" ? rawLost : rawLost == null ? null : Number(rawLost);
608
+ const pendingMessagesLost =
609
+ lostNumber === null || !Number.isFinite(lostNumber) || lostNumber < 0 ? null : lostNumber;
610
+ // Everything on screen came from the old cache: every list reloads.
611
+ this.lastState.clear();
612
+ this.directFailures.clear();
613
+ this.retriesInFlight.clear();
614
+ this.failureReasons.clear();
615
+ this.sentIds.clear();
616
+ this.genValue++;
617
+ // A reset announced together with a lost send must not take that send's notice with it.
618
+ this.undeliveredNotices = this.undeliveredNotices.map((notice) => ({ ...notice, gen: this.genValue }));
619
+ this.session$.next(this.genValue);
620
+ this.cacheReset$.next({ gen: this.genValue, reason, pendingMessagesLost });
621
+ safeEmit(OfflineMessageEvents.ccOfflineCacheReset, { reason, pendingMessagesLost });
622
+ // ENCRYPTION_CHANGED already reported each lost send as DISCARDED, with its own notice (BEH-ENC-16).
623
+ if (reason === "ENCRYPTION_CHANGED") return;
624
+ if (pendingMessagesLost !== null && pendingMessagesLost > 0) {
625
+ this.notify({ kind: "unsent_messages_lost", count: pendingMessagesLost });
626
+ } else if (pendingMessagesLost === null) {
627
+ this.notify({ kind: "unsent_messages_maybe_lost" });
628
+ }
629
+ }
630
+
631
+ // ── Reads made offline (AC-7.4) ───────────────────────────────────────────
632
+
633
+ rememberReadWhileOffline(receiverId: string, receiverType: string): void {
634
+ if (!receiverId || !receiverType) return;
635
+ this.readWhileOffline.set(`${receiverType}:${receiverId}`, { id: receiverId, type: receiverType });
636
+ }
637
+
638
+ private flushReadsMadeOffline(): void {
639
+ if (this.readWhileOffline.size === 0) return;
640
+ const pending = Array.from(this.readWhileOffline.values());
641
+ this.readWhileOffline.clear();
642
+ for (const { id, type } of pending) {
643
+ try {
644
+ const result: any = (CometChat as any).markConversationAsRead?.(id, type);
645
+ if (result && typeof result.catch === "function") result.catch(() => this.rememberReadWhileOffline(id, type));
646
+ } catch {
647
+ this.rememberReadWhileOffline(id, type);
648
+ }
649
+ }
650
+ }
651
+ }