feeddo-react-native 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.
Files changed (225) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +401 -2
  3. package/android/build.gradle +39 -0
  4. package/android/src/main/AndroidManifest.xml +1 -0
  5. package/android/src/main/java/dev/feeddo/reactnative/FeeddoReactNativeModule.java +380 -0
  6. package/android/src/main/java/dev/feeddo/reactnative/FeeddoReactNativePackage.java +25 -0
  7. package/dist/Feeddo.d.ts +131 -0
  8. package/dist/Feeddo.d.ts.map +1 -0
  9. package/dist/Feeddo.js +176 -0
  10. package/dist/Feeddo.js.map +1 -0
  11. package/dist/FeeddoClient.d.ts +151 -0
  12. package/dist/FeeddoClient.d.ts.map +1 -0
  13. package/dist/FeeddoClient.js +690 -0
  14. package/dist/FeeddoClient.js.map +1 -0
  15. package/dist/FeeddoProvider.d.ts +23 -0
  16. package/dist/FeeddoProvider.d.ts.map +1 -0
  17. package/dist/FeeddoProvider.js +76 -0
  18. package/dist/FeeddoProvider.js.map +1 -0
  19. package/dist/config/FeeddoConfig.d.ts +10 -0
  20. package/dist/config/FeeddoConfig.d.ts.map +1 -0
  21. package/dist/config/FeeddoConfig.js +10 -0
  22. package/dist/config/FeeddoConfig.js.map +1 -0
  23. package/dist/index.d.ts +36 -0
  24. package/dist/index.d.ts.map +1 -0
  25. package/dist/index.js +38 -0
  26. package/dist/index.js.map +1 -0
  27. package/dist/models/Conversation.d.ts +27 -0
  28. package/dist/models/Conversation.d.ts.map +1 -0
  29. package/dist/models/Conversation.js +24 -0
  30. package/dist/models/Conversation.js.map +1 -0
  31. package/dist/models/EndUser.d.ts +49 -0
  32. package/dist/models/EndUser.d.ts.map +1 -0
  33. package/dist/models/EndUser.js +2 -0
  34. package/dist/models/EndUser.js.map +1 -0
  35. package/dist/models/FeeddoNotification.d.ts +15 -0
  36. package/dist/models/FeeddoNotification.d.ts.map +1 -0
  37. package/dist/models/FeeddoNotification.js +15 -0
  38. package/dist/models/FeeddoNotification.js.map +1 -0
  39. package/dist/models/HomeData.d.ts +16 -0
  40. package/dist/models/HomeData.d.ts.map +1 -0
  41. package/dist/models/HomeData.js +19 -0
  42. package/dist/models/HomeData.js.map +1 -0
  43. package/dist/models/Message.d.ts +12 -0
  44. package/dist/models/Message.d.ts.map +1 -0
  45. package/dist/models/Message.js +25 -0
  46. package/dist/models/Message.js.map +1 -0
  47. package/dist/models/PushProvider.d.ts +14 -0
  48. package/dist/models/PushProvider.d.ts.map +1 -0
  49. package/dist/models/PushProvider.js +9 -0
  50. package/dist/models/PushProvider.js.map +1 -0
  51. package/dist/models/Task.d.ts +17 -0
  52. package/dist/models/Task.d.ts.map +1 -0
  53. package/dist/models/Task.js +22 -0
  54. package/dist/models/Task.js.map +1 -0
  55. package/dist/models/TaskComment.d.ts +11 -0
  56. package/dist/models/TaskComment.d.ts.map +1 -0
  57. package/dist/models/TaskComment.js +27 -0
  58. package/dist/models/TaskComment.js.map +1 -0
  59. package/dist/models/Ticket.d.ts +13 -0
  60. package/dist/models/Ticket.d.ts.map +1 -0
  61. package/dist/models/Ticket.js +14 -0
  62. package/dist/models/Ticket.js.map +1 -0
  63. package/dist/native/FeeddoNative.d.ts +58 -0
  64. package/dist/native/FeeddoNative.d.ts.map +1 -0
  65. package/dist/native/FeeddoNative.js +22 -0
  66. package/dist/native/FeeddoNative.js.map +1 -0
  67. package/dist/push/FeeddoPushNotificationApns.d.ts +73 -0
  68. package/dist/push/FeeddoPushNotificationApns.d.ts.map +1 -0
  69. package/dist/push/FeeddoPushNotificationApns.js +301 -0
  70. package/dist/push/FeeddoPushNotificationApns.js.map +1 -0
  71. package/dist/services/ApiService.d.ts +64 -0
  72. package/dist/services/ApiService.d.ts.map +1 -0
  73. package/dist/services/ApiService.js +406 -0
  74. package/dist/services/ApiService.js.map +1 -0
  75. package/dist/services/ConversationService.d.ts +45 -0
  76. package/dist/services/ConversationService.d.ts.map +1 -0
  77. package/dist/services/ConversationService.js +259 -0
  78. package/dist/services/ConversationService.js.map +1 -0
  79. package/dist/services/WebSocketService.d.ts +26 -0
  80. package/dist/services/WebSocketService.d.ts.map +1 -0
  81. package/dist/services/WebSocketService.js +157 -0
  82. package/dist/services/WebSocketService.js.map +1 -0
  83. package/dist/theme/FeeddoTheme.d.ts +31 -0
  84. package/dist/theme/FeeddoTheme.d.ts.map +1 -0
  85. package/dist/theme/FeeddoTheme.js +60 -0
  86. package/dist/theme/FeeddoTheme.js.map +1 -0
  87. package/dist/ui/FeeddoFeedbackCard.d.ts +15 -0
  88. package/dist/ui/FeeddoFeedbackCard.d.ts.map +1 -0
  89. package/dist/ui/FeeddoFeedbackCard.js +188 -0
  90. package/dist/ui/FeeddoFeedbackCard.js.map +1 -0
  91. package/dist/ui/FeeddoModal.d.ts +20 -0
  92. package/dist/ui/FeeddoModal.d.ts.map +1 -0
  93. package/dist/ui/FeeddoModal.js +180 -0
  94. package/dist/ui/FeeddoModal.js.map +1 -0
  95. package/dist/ui/components/AttachmentPreview.d.ts +10 -0
  96. package/dist/ui/components/AttachmentPreview.d.ts.map +1 -0
  97. package/dist/ui/components/AttachmentPreview.js +143 -0
  98. package/dist/ui/components/AttachmentPreview.js.map +1 -0
  99. package/dist/ui/components/ChatInputArea.d.ts +16 -0
  100. package/dist/ui/components/ChatInputArea.d.ts.map +1 -0
  101. package/dist/ui/components/ChatInputArea.js +85 -0
  102. package/dist/ui/components/ChatInputArea.js.map +1 -0
  103. package/dist/ui/components/FeeddoIcon.d.ts +10 -0
  104. package/dist/ui/components/FeeddoIcon.d.ts.map +1 -0
  105. package/dist/ui/components/FeeddoIcon.js +690 -0
  106. package/dist/ui/components/FeeddoIcon.js.map +1 -0
  107. package/dist/ui/components/FeeddoNotificationBadge.d.ts +14 -0
  108. package/dist/ui/components/FeeddoNotificationBadge.d.ts.map +1 -0
  109. package/dist/ui/components/FeeddoNotificationBadge.js +171 -0
  110. package/dist/ui/components/FeeddoNotificationBadge.js.map +1 -0
  111. package/dist/ui/components/MessageBubble.d.ts +13 -0
  112. package/dist/ui/components/MessageBubble.d.ts.map +1 -0
  113. package/dist/ui/components/MessageBubble.js +163 -0
  114. package/dist/ui/components/MessageBubble.js.map +1 -0
  115. package/dist/ui/components/NotificationsSheet.d.ts +10 -0
  116. package/dist/ui/components/NotificationsSheet.d.ts.map +1 -0
  117. package/dist/ui/components/NotificationsSheet.js +252 -0
  118. package/dist/ui/components/NotificationsSheet.js.map +1 -0
  119. package/dist/ui/components/RatingWidget.d.ts +11 -0
  120. package/dist/ui/components/RatingWidget.d.ts.map +1 -0
  121. package/dist/ui/components/RatingWidget.js +34 -0
  122. package/dist/ui/components/RatingWidget.js.map +1 -0
  123. package/dist/ui/components/TaskCard.d.ts +12 -0
  124. package/dist/ui/components/TaskCard.d.ts.map +1 -0
  125. package/dist/ui/components/TaskCard.js +210 -0
  126. package/dist/ui/components/TaskCard.js.map +1 -0
  127. package/dist/ui/components/TaskDetailsSheet.d.ts +15 -0
  128. package/dist/ui/components/TaskDetailsSheet.d.ts.map +1 -0
  129. package/dist/ui/components/TaskDetailsSheet.js +577 -0
  130. package/dist/ui/components/TaskDetailsSheet.js.map +1 -0
  131. package/dist/ui/components/TicketCard.d.ts +11 -0
  132. package/dist/ui/components/TicketCard.d.ts.map +1 -0
  133. package/dist/ui/components/TicketCard.js +100 -0
  134. package/dist/ui/components/TicketCard.js.map +1 -0
  135. package/dist/ui/components/TicketDetailsSheet.d.ts +14 -0
  136. package/dist/ui/components/TicketDetailsSheet.d.ts.map +1 -0
  137. package/dist/ui/components/TicketDetailsSheet.js +254 -0
  138. package/dist/ui/components/TicketDetailsSheet.js.map +1 -0
  139. package/dist/ui/components/TypingIndicator.d.ts +10 -0
  140. package/dist/ui/components/TypingIndicator.d.ts.map +1 -0
  141. package/dist/ui/components/TypingIndicator.js +77 -0
  142. package/dist/ui/components/TypingIndicator.js.map +1 -0
  143. package/dist/ui/screens/FeeddoChatScreen.d.ts +13 -0
  144. package/dist/ui/screens/FeeddoChatScreen.d.ts.map +1 -0
  145. package/dist/ui/screens/FeeddoChatScreen.js +681 -0
  146. package/dist/ui/screens/FeeddoChatScreen.js.map +1 -0
  147. package/dist/ui/screens/FeeddoHomeScreen.d.ts +15 -0
  148. package/dist/ui/screens/FeeddoHomeScreen.d.ts.map +1 -0
  149. package/dist/ui/screens/FeeddoHomeScreen.js +653 -0
  150. package/dist/ui/screens/FeeddoHomeScreen.js.map +1 -0
  151. package/dist/ui/screens/FeeddoMessagesScreen.d.ts +12 -0
  152. package/dist/ui/screens/FeeddoMessagesScreen.d.ts.map +1 -0
  153. package/dist/ui/screens/FeeddoMessagesScreen.js +326 -0
  154. package/dist/ui/screens/FeeddoMessagesScreen.js.map +1 -0
  155. package/dist/ui/screens/FeeddoTasksScreen.d.ts +13 -0
  156. package/dist/ui/screens/FeeddoTasksScreen.d.ts.map +1 -0
  157. package/dist/ui/screens/FeeddoTasksScreen.js +517 -0
  158. package/dist/ui/screens/FeeddoTasksScreen.js.map +1 -0
  159. package/dist/ui/screens/FeeddoTicketsScreen.d.ts +10 -0
  160. package/dist/ui/screens/FeeddoTicketsScreen.d.ts.map +1 -0
  161. package/dist/ui/screens/FeeddoTicketsScreen.js +112 -0
  162. package/dist/ui/screens/FeeddoTicketsScreen.js.map +1 -0
  163. package/dist/utils/DeviceInfoHelper.d.ts +29 -0
  164. package/dist/utils/DeviceInfoHelper.d.ts.map +1 -0
  165. package/dist/utils/DeviceInfoHelper.js +190 -0
  166. package/dist/utils/DeviceInfoHelper.js.map +1 -0
  167. package/dist/utils/MediaHelper.d.ts +20 -0
  168. package/dist/utils/MediaHelper.d.ts.map +1 -0
  169. package/dist/utils/MediaHelper.js +92 -0
  170. package/dist/utils/MediaHelper.js.map +1 -0
  171. package/dist/utils/NotificationSupport.d.ts +22 -0
  172. package/dist/utils/NotificationSupport.d.ts.map +1 -0
  173. package/dist/utils/NotificationSupport.js +211 -0
  174. package/dist/utils/NotificationSupport.js.map +1 -0
  175. package/dist/utils/StorageHelper.d.ts +65 -0
  176. package/dist/utils/StorageHelper.d.ts.map +1 -0
  177. package/dist/utils/StorageHelper.js +273 -0
  178. package/dist/utils/StorageHelper.js.map +1 -0
  179. package/feeddo-react-native.podspec +26 -0
  180. package/ios/FeeddoReactNativeModule.h +8 -0
  181. package/ios/FeeddoReactNativeModule.m +831 -0
  182. package/package.json +56 -4
  183. package/src/Feeddo.ts +247 -0
  184. package/src/FeeddoClient.ts +895 -0
  185. package/src/FeeddoProvider.tsx +139 -0
  186. package/src/config/FeeddoConfig.ts +9 -0
  187. package/src/index.ts +67 -0
  188. package/src/models/Conversation.ts +50 -0
  189. package/src/models/EndUser.ts +65 -0
  190. package/src/models/FeeddoNotification.ts +29 -0
  191. package/src/models/HomeData.ts +33 -0
  192. package/src/models/Message.ts +36 -0
  193. package/src/models/PushProvider.ts +15 -0
  194. package/src/models/Task.ts +40 -0
  195. package/src/models/TaskComment.ts +36 -0
  196. package/src/models/Ticket.ts +25 -0
  197. package/src/native/FeeddoNative.ts +80 -0
  198. package/src/push/FeeddoPushNotificationApns.ts +362 -0
  199. package/src/services/ApiService.ts +456 -0
  200. package/src/services/ConversationService.ts +305 -0
  201. package/src/services/WebSocketService.ts +185 -0
  202. package/src/theme/FeeddoTheme.ts +85 -0
  203. package/src/ui/FeeddoFeedbackCard.tsx +245 -0
  204. package/src/ui/FeeddoModal.tsx +309 -0
  205. package/src/ui/components/AttachmentPreview.tsx +192 -0
  206. package/src/ui/components/ChatInputArea.tsx +154 -0
  207. package/src/ui/components/FeeddoIcon.tsx +903 -0
  208. package/src/ui/components/FeeddoNotificationBadge.tsx +234 -0
  209. package/src/ui/components/MessageBubble.tsx +223 -0
  210. package/src/ui/components/NotificationsSheet.tsx +324 -0
  211. package/src/ui/components/RatingWidget.tsx +64 -0
  212. package/src/ui/components/TaskCard.tsx +259 -0
  213. package/src/ui/components/TaskDetailsSheet.tsx +747 -0
  214. package/src/ui/components/TicketCard.tsx +128 -0
  215. package/src/ui/components/TicketDetailsSheet.tsx +324 -0
  216. package/src/ui/components/TypingIndicator.tsx +104 -0
  217. package/src/ui/screens/FeeddoChatScreen.tsx +877 -0
  218. package/src/ui/screens/FeeddoHomeScreen.tsx +824 -0
  219. package/src/ui/screens/FeeddoMessagesScreen.tsx +414 -0
  220. package/src/ui/screens/FeeddoTasksScreen.tsx +671 -0
  221. package/src/ui/screens/FeeddoTicketsScreen.tsx +164 -0
  222. package/src/utils/DeviceInfoHelper.ts +209 -0
  223. package/src/utils/MediaHelper.ts +105 -0
  224. package/src/utils/NotificationSupport.ts +233 -0
  225. package/src/utils/StorageHelper.ts +305 -0
@@ -0,0 +1,895 @@
1
+ import { Platform } from 'react-native';
2
+ import { ApiService, UnreadData } from './services/ApiService';
3
+ import { WebSocketService } from './services/WebSocketService';
4
+ import { ConversationService } from './services/ConversationService';
5
+ import { FeeddoConfig } from './config/FeeddoConfig';
6
+ import { FeeddoTheme } from './theme/FeeddoTheme';
7
+ import { EndUser } from './models/EndUser';
8
+ import { Conversation, parseConversation } from './models/Conversation';
9
+ import { HomeData } from './models/HomeData';
10
+ import { Ticket } from './models/Ticket';
11
+ import { TaskComment } from './models/TaskComment';
12
+ import { FeeddoPushProviderType } from './models/PushProvider';
13
+ import { StorageHelper, StorageAdapter } from './utils/StorageHelper';
14
+ import { DeviceInfoHelper } from './utils/DeviceInfoHelper';
15
+ import { getFeeddoNativeModule } from './native/FeeddoNative';
16
+ import {
17
+ NotificationDeduplicator,
18
+ buildNotificationDedupKey,
19
+ intValue,
20
+ isConversationNotification,
21
+ isTaskNotification,
22
+ normalizeNotificationPayload,
23
+ stringValue,
24
+ } from './utils/NotificationSupport';
25
+
26
+ export interface InitResult {
27
+ userId: string;
28
+ recentConversation?: Conversation;
29
+ hasUnreadMessages: boolean;
30
+ }
31
+
32
+ export interface DesktopConstraints {
33
+ maxWidth?: number;
34
+ maxHeight?: number;
35
+ }
36
+
37
+ export interface ModalState {
38
+ visible: boolean;
39
+ initialScreen: 'home' | 'chat' | 'messages' | 'tickets' | 'tasks';
40
+ initialConversation?: Conversation | null;
41
+ initialChatMessage?: string;
42
+ initialTaskId?: string;
43
+ theme?: FeeddoTheme;
44
+ useSmallWindowOnDesktop?: boolean;
45
+ desktopConstraints?: DesktopConstraints;
46
+ navigationId?: number;
47
+ }
48
+
49
+ export interface InAppNotificationState {
50
+ visible: boolean;
51
+ title: string;
52
+ body: string;
53
+ timestamp?: number;
54
+ data?: Record<string, any>;
55
+ theme?: FeeddoTheme;
56
+ duration?: number;
57
+ onTap?: () => void;
58
+ }
59
+
60
+ export class FeeddoInternal {
61
+ private static _instance: FeeddoInternal | null = null;
62
+ private static unreadListeners: Set<(count: number) => void> = new Set();
63
+ private static modalStateListeners: Set<(state: ModalState) => void> = new Set();
64
+ private static inAppNotificationListeners: Set<(state: InAppNotificationState) => void> =
65
+ new Set();
66
+ private static clearNotificationsListeners: Set<() => void> = new Set();
67
+ private static pendingBanners: InAppNotificationState[] = [];
68
+ private static pendingNotificationTap: {
69
+ data: Record<string, any>;
70
+ theme?: FeeddoTheme;
71
+ } | null = null;
72
+ private static currentModalState: ModalState = {
73
+ visible: false,
74
+ initialScreen: 'home',
75
+ };
76
+
77
+ public readonly apiService: ApiService;
78
+ public readonly webSocketService: WebSocketService;
79
+ public readonly conversationService: ConversationService;
80
+
81
+ private _cachedUserId: string | null = null;
82
+ private _chatBotName: string = 'Feeddo';
83
+ private _recentConversation: Conversation | null = null;
84
+ private _isInAppNotificationOn: boolean = true;
85
+ private _notificationTheme: FeeddoTheme = FeeddoTheme.dark();
86
+ private _notificationDuration: number = 10000;
87
+
88
+ private initLock: Promise<string> | null = null;
89
+ private notificationListeners: Set<(data: Record<string, any>) => void> = new Set();
90
+ private notificationDeduplicator = new NotificationDeduplicator();
91
+ private unsubscribeWsNotifications?: () => void;
92
+ private unsubscribeConvUnread?: () => void;
93
+
94
+ private constructor(apiKey: string) {
95
+ this.apiService = new ApiService(FeeddoConfig.apiUrl, apiKey);
96
+ this.webSocketService = new WebSocketService(this.apiService.apiUrl, this.apiService.apiKey);
97
+ this.conversationService = new ConversationService(this.apiService, this.webSocketService);
98
+
99
+ this.unsubscribeWsNotifications = this.webSocketService.subscribe(
100
+ this.handleWebSocketNotification.bind(this)
101
+ );
102
+ this.unsubscribeConvUnread = this.conversationService.onUnreadCountChange((count) => {
103
+ FeeddoInternal.notifyUnreadListeners(count);
104
+ });
105
+ }
106
+
107
+ public static get instance(): FeeddoInternal {
108
+ if (!this._instance) {
109
+ throw new Error('Feeddo not initialized. Call Feeddo.init() first.');
110
+ }
111
+ return this._instance;
112
+ }
113
+
114
+ public static get isInitialized(): boolean {
115
+ return Boolean(this._instance && this._instance.apiService.apiKey);
116
+ }
117
+
118
+ private static notifyUnreadListeners(count: number): void {
119
+ this.unreadListeners.forEach((l) => {
120
+ try {
121
+ l(count);
122
+ } catch (_) {}
123
+ });
124
+ }
125
+
126
+ public static addUnreadCountListener(listener: (count: number) => void): () => void {
127
+ this.unreadListeners.add(listener);
128
+ if (this._instance) {
129
+ try {
130
+ listener(this._instance.conversationService.unreadMessageCount);
131
+ } catch (_) {}
132
+ }
133
+ return () => {
134
+ this.unreadListeners.delete(listener);
135
+ };
136
+ }
137
+
138
+ public get userId(): string | null {
139
+ return this._cachedUserId;
140
+ }
141
+
142
+ public get chatBotName(): string {
143
+ return this._chatBotName;
144
+ }
145
+
146
+ public get recentConversation(): Conversation | null {
147
+ return this._recentConversation;
148
+ }
149
+
150
+ public get isInAppNotificationOn(): boolean {
151
+ return this._isInAppNotificationOn;
152
+ }
153
+
154
+ public get notificationTheme(): FeeddoTheme {
155
+ return this._notificationTheme;
156
+ }
157
+
158
+ public get notificationDuration(): number {
159
+ return this._notificationDuration;
160
+ }
161
+
162
+ public subscribeNotifications(listener: (data: Record<string, any>) => void): () => void {
163
+ this.notificationListeners.add(listener);
164
+ return () => {
165
+ this.notificationListeners.delete(listener);
166
+ };
167
+ }
168
+
169
+ public static onModalStateChange(listener: (state: ModalState) => void): () => void {
170
+ this.modalStateListeners.add(listener);
171
+ listener(this.currentModalState);
172
+ return () => {
173
+ this.modalStateListeners.delete(listener);
174
+ };
175
+ }
176
+
177
+ public onModalStateChange(listener: (state: ModalState) => void): () => void {
178
+ return FeeddoInternal.onModalStateChange(listener);
179
+ }
180
+
181
+ public static onInAppNotification(
182
+ listener: (state: InAppNotificationState) => void
183
+ ): () => void {
184
+ this.inAppNotificationListeners.add(listener);
185
+ if (this.pendingBanners.length > 0) {
186
+ const queued = [...this.pendingBanners];
187
+ this.pendingBanners = [];
188
+ for (const banner of queued) {
189
+ try {
190
+ listener(banner);
191
+ } catch (_) {}
192
+ }
193
+ }
194
+ return () => {
195
+ this.inAppNotificationListeners.delete(listener);
196
+ };
197
+ }
198
+
199
+ public onInAppNotification(listener: (state: InAppNotificationState) => void): () => void {
200
+ return FeeddoInternal.onInAppNotification(listener);
201
+ }
202
+
203
+ public static onClearNotifications(listener: () => void): () => void {
204
+ this.clearNotificationsListeners.add(listener);
205
+ return () => {
206
+ this.clearNotificationsListeners.delete(listener);
207
+ };
208
+ }
209
+
210
+ private static modalNavigationCounter = 0;
211
+
212
+ public static setModalState(state: Partial<ModalState>): void {
213
+ const nextNavId =
214
+ state.visible === true
215
+ ? ++this.modalNavigationCounter
216
+ : this.currentModalState.navigationId;
217
+ this.currentModalState = {
218
+ ...this.currentModalState,
219
+ ...state,
220
+ navigationId: nextNavId,
221
+ };
222
+ this.modalStateListeners.forEach((l) => {
223
+ try {
224
+ l(this.currentModalState);
225
+ } catch (_) {}
226
+ });
227
+ }
228
+
229
+ public setModalState(state: Partial<ModalState>): void {
230
+ FeeddoInternal.setModalState(state);
231
+ }
232
+
233
+ public static showInAppNotificationBanner(state: InAppNotificationState): void {
234
+ if (this.inAppNotificationListeners.size === 0) {
235
+ this.pendingBanners.push(state);
236
+ return;
237
+ }
238
+ this.inAppNotificationListeners.forEach((l) => {
239
+ try {
240
+ l(state);
241
+ } catch (_) {}
242
+ });
243
+ }
244
+
245
+ public showInAppNotificationBanner(state: InAppNotificationState): void {
246
+ FeeddoInternal.showInAppNotificationBanner(state);
247
+ }
248
+
249
+ public static clearAllNotifications(): void {
250
+ this.pendingBanners = [];
251
+ this.clearNotificationsListeners.forEach((l) => {
252
+ try {
253
+ l();
254
+ } catch (_) {}
255
+ });
256
+ }
257
+
258
+ public static async init(options: {
259
+ apiKey: string;
260
+ externalUserId?: string;
261
+ userName?: string;
262
+ email?: string;
263
+ userSegment?: string;
264
+ subscriptionStatus?: string;
265
+ customAttributes?: Record<string, any>;
266
+ isInAppNotificationOn?: boolean;
267
+ theme?: FeeddoTheme;
268
+ notificationDuration?: number;
269
+ pushToken?: string;
270
+ pushProvider?: FeeddoPushProviderType;
271
+ storageAdapter?: StorageAdapter;
272
+ }): Promise<InitResult> {
273
+ if (options.storageAdapter) {
274
+ StorageHelper.setStorageAdapter(options.storageAdapter);
275
+ }
276
+
277
+ await StorageHelper.recordFirstAppOpenAt();
278
+ await DeviceInfoHelper.loadDeviceInfo().catch(() => {});
279
+
280
+ if (!this._instance || this._instance.apiService.apiKey !== options.apiKey) {
281
+ if (this._instance) {
282
+ this._instance.cleanupResources();
283
+ }
284
+ this._instance = new FeeddoInternal(options.apiKey);
285
+ }
286
+
287
+ const inst = this._instance;
288
+ inst._isInAppNotificationOn = options.isInAppNotificationOn ?? true;
289
+ inst._notificationTheme = options.theme ?? FeeddoTheme.dark();
290
+ if (options.notificationDuration !== undefined) {
291
+ inst._notificationDuration = options.notificationDuration;
292
+ }
293
+
294
+ // Check if user identity or attributes changed
295
+ const existingExtId = await StorageHelper.getExternalUserId();
296
+ const existingName = await StorageHelper.getUserName();
297
+ const existingEmail = await StorageHelper.getEmail();
298
+ const existingPush = await StorageHelper.getPendingPushToken();
299
+
300
+ const hasChanges =
301
+ (options.externalUserId !== undefined && options.externalUserId !== existingExtId) ||
302
+ (options.userName !== undefined && options.userName !== existingName) ||
303
+ (options.email !== undefined && options.email !== existingEmail) ||
304
+ (options.pushToken !== undefined && options.pushToken !== existingPush);
305
+
306
+ if (hasChanges) {
307
+ await StorageHelper.setSyncedWithBackend(false);
308
+ }
309
+
310
+ // Save locally
311
+ await StorageHelper.saveUserData({
312
+ externalUserId: options.externalUserId,
313
+ userName: options.userName,
314
+ email: options.email,
315
+ userSegment: options.userSegment,
316
+ subscriptionStatus: options.subscriptionStatus,
317
+ customAttributes: options.customAttributes,
318
+ });
319
+
320
+ if (options.pushToken) {
321
+ await StorageHelper.savePendingPushToken(options.pushToken, options.pushProvider);
322
+ if (Platform.OS === 'android') {
323
+ getFeeddoNativeModule()
324
+ ?.createNotificationChannel(
325
+ 'feeddo_notifications_channel',
326
+ 'Feeddo Notifications',
327
+ 'Feeddo notifications for support messages and community updates'
328
+ )
329
+ .catch(() => {});
330
+ }
331
+ }
332
+
333
+ const localUserId = await StorageHelper.getOrCreateLocalUserId();
334
+ inst._cachedUserId = localUserId;
335
+ inst.webSocketService.setUserId(localUserId);
336
+
337
+ // Setup real-time notification listener for WebSocket chat messages
338
+ if (inst._isInAppNotificationOn) {
339
+ inst.setupNotificationListener();
340
+ } else {
341
+ inst.conversationService.onNewMessage = undefined;
342
+ }
343
+
344
+ const pendingTap = this.pendingNotificationTap;
345
+ this.pendingNotificationTap = null;
346
+
347
+ // Check for unread notifications if active conversation exists (3s timeout matching Flutter)
348
+ let recentConv: Conversation | undefined;
349
+ const hasActiveConv = await StorageHelper.hasActiveConversation();
350
+ if (hasActiveConv && inst._isInAppNotificationOn) {
351
+ try {
352
+ const unreadData: UnreadData | null = await inst.apiService.getUnreadData(localUserId, 3000);
353
+ if (unreadData) {
354
+ await StorageHelper.setHasActiveConversation(unreadData.hasActiveConversation);
355
+ if (unreadData.recentConversation) {
356
+ recentConv = unreadData.recentConversation;
357
+ inst._recentConversation = recentConv;
358
+ inst.conversationService.updateConversation(recentConv);
359
+
360
+ if (recentConv.unreadMessages > 0 && !pendingTap) {
361
+ inst.showInAppNotificationBanner({
362
+ visible: true,
363
+ title: recentConv.displayName || inst.chatBotName,
364
+ body: recentConv.lastMessagePreview || '',
365
+ timestamp: recentConv.lastMessageAt,
366
+ theme: inst._notificationTheme,
367
+ duration: inst._notificationDuration,
368
+ onTap: () => {
369
+ inst.setModalState({
370
+ visible: true,
371
+ initialScreen: 'chat',
372
+ initialConversation: recentConv,
373
+ theme: inst._notificationTheme,
374
+ });
375
+ },
376
+ });
377
+ }
378
+ }
379
+ if (unreadData.unreadMessageCount > inst.conversationService.unreadMessageCount) {
380
+ inst.conversationService.setTotalUnreadCount(unreadData.unreadMessageCount);
381
+ }
382
+ }
383
+ } catch (_) {}
384
+ }
385
+
386
+ if (pendingTap) {
387
+ await inst.handleNotificationTap(pendingTap.data, pendingTap.theme).catch(() => {});
388
+ }
389
+
390
+ return {
391
+ userId: localUserId,
392
+ recentConversation: recentConv,
393
+ hasUnreadMessages: Boolean(recentConv && recentConv.unreadMessages > 0),
394
+ };
395
+ }
396
+
397
+ public async ensureUserInitialized(): Promise<string> {
398
+ if (this.initLock) {
399
+ return await this.initLock;
400
+ }
401
+
402
+ this.initLock = this.performUserSync();
403
+ try {
404
+ const id = await this.initLock;
405
+ return id;
406
+ } finally {
407
+ this.initLock = null;
408
+ }
409
+ }
410
+
411
+ private async performUserSync(): Promise<string> {
412
+ const isSynced = await StorageHelper.isSyncedWithBackend();
413
+ if (!this._cachedUserId) {
414
+ this._cachedUserId = await StorageHelper.getUserId();
415
+ }
416
+
417
+ if (isSynced && this._cachedUserId && this._cachedUserId.length > 0) {
418
+ this.webSocketService.setUserId(this._cachedUserId);
419
+ return this._cachedUserId;
420
+ }
421
+
422
+ const id = await this.upsertUser();
423
+ this.webSocketService.setUserId(id);
424
+ return id;
425
+ }
426
+
427
+ private async upsertUser(params?: Partial<EndUser>): Promise<string> {
428
+ if (!this._cachedUserId) {
429
+ this._cachedUserId = await StorageHelper.getUserId();
430
+ }
431
+
432
+ const externalUserId =
433
+ params?.externalUserId ?? (await StorageHelper.getExternalUserId()) ?? undefined;
434
+ const userName = params?.userName ?? (await StorageHelper.getUserName()) ?? undefined;
435
+ const email = params?.email ?? (await StorageHelper.getEmail()) ?? undefined;
436
+ const userSegment =
437
+ params?.userSegment ?? (await StorageHelper.getUserSegment()) ?? undefined;
438
+ const subscriptionStatus =
439
+ params?.subscriptionStatus ?? (await StorageHelper.getSubscriptionStatus()) ?? undefined;
440
+ const customAttributes =
441
+ params?.customAttributes ?? (await StorageHelper.getCustomAttributes()) ?? undefined;
442
+
443
+ let pushToken = params?.pushToken;
444
+ let pushProvider = params?.pushProvider;
445
+ if (!pushToken) {
446
+ pushToken = (await StorageHelper.getPendingPushToken()) ?? undefined;
447
+ const prov = await StorageHelper.getPendingPushProvider();
448
+ if (prov) pushProvider = prov as FeeddoPushProviderType;
449
+ }
450
+
451
+ const firstSeenAt = (await StorageHelper.getFirstAppOpenAt()) ?? undefined;
452
+ const deviceInfo = await DeviceInfoHelper.loadDeviceInfo();
453
+
454
+ const endUser: EndUser = {
455
+ userId: this._cachedUserId ?? undefined,
456
+ externalUserId,
457
+ userName,
458
+ email,
459
+ platform: deviceInfo.platform,
460
+ deviceModel: deviceInfo.deviceModel,
461
+ osVersion: deviceInfo.osVersion,
462
+ appVersion: deviceInfo.appVersion,
463
+ userSegment,
464
+ subscriptionStatus,
465
+ customAttributes,
466
+ pushToken,
467
+ pushProvider,
468
+ firstSeenAt,
469
+ };
470
+
471
+ const res = await this.apiService.upsertEndUser(endUser);
472
+ this._cachedUserId = res.userId;
473
+
474
+ if (res.recentConversation) {
475
+ try {
476
+ this._recentConversation = parseConversation(res.recentConversation);
477
+ this.conversationService.updateConversation(this._recentConversation);
478
+ if (this._recentConversation.status !== 'resolved') {
479
+ await StorageHelper.setHasActiveConversation(true);
480
+ }
481
+ } catch (_) {}
482
+ }
483
+
484
+ await StorageHelper.saveUserId(res.userId);
485
+ await StorageHelper.saveUserData({
486
+ externalUserId: externalUserId ?? res.externalUserId,
487
+ userName,
488
+ email,
489
+ userSegment,
490
+ subscriptionStatus,
491
+ customAttributes,
492
+ });
493
+ await StorageHelper.setSyncedWithBackend(true);
494
+
495
+ return res.userId;
496
+ }
497
+
498
+ public async updateUser(data: {
499
+ externalUserId?: string;
500
+ userName?: string;
501
+ email?: string;
502
+ userSegment?: string;
503
+ subscriptionStatus?: string;
504
+ customAttributes?: Record<string, any>;
505
+ pushToken?: string;
506
+ pushProvider?: FeeddoPushProviderType;
507
+ }): Promise<string> {
508
+ await StorageHelper.saveUserData(data);
509
+ if (data.pushToken) {
510
+ await StorageHelper.savePendingPushToken(data.pushToken, data.pushProvider);
511
+ }
512
+
513
+ const isSynced = await StorageHelper.isSyncedWithBackend();
514
+ if (isSynced) {
515
+ return await this.upsertUser(data);
516
+ } else {
517
+ if (!this._cachedUserId) {
518
+ this._cachedUserId = await StorageHelper.getOrCreateLocalUserId();
519
+ }
520
+ return this._cachedUserId;
521
+ }
522
+ }
523
+
524
+ public async registerPushToken(
525
+ pushToken: string,
526
+ pushProvider: FeeddoPushProviderType
527
+ ): Promise<void> {
528
+ await StorageHelper.savePendingPushToken(pushToken, pushProvider);
529
+ if (Platform.OS === 'android') {
530
+ getFeeddoNativeModule()
531
+ ?.createNotificationChannel(
532
+ 'feeddo_notifications_channel',
533
+ 'Feeddo Notifications',
534
+ 'Feeddo notifications for support messages and community updates'
535
+ )
536
+ .catch(() => {});
537
+ }
538
+ const isSynced = await StorageHelper.isSyncedWithBackend();
539
+ if (isSynced) {
540
+ try {
541
+ await this.upsertUser({ pushToken, pushProvider });
542
+ } catch (e) {
543
+ console.warn('Feeddo: Failed to register push token:', e);
544
+ }
545
+ }
546
+ }
547
+
548
+ private setupNotificationListener(): void {
549
+ this.conversationService.onNewMessage = (conversation) => {
550
+ if (this.conversationService.activeConversationId === conversation.id) {
551
+ return;
552
+ }
553
+
554
+ if (!this._isInAppNotificationOn || conversation.unreadMessages === 0) {
555
+ return;
556
+ }
557
+
558
+ const dedupKey = buildNotificationDedupKey(
559
+ {
560
+ type: 'chat_message',
561
+ conversationId: conversation.id,
562
+ body: conversation.lastMessagePreview,
563
+ },
564
+ conversation.lastMessagePreview
565
+ );
566
+ if (dedupKey && !this.notificationDeduplicator.markIfNew(dedupKey)) {
567
+ return;
568
+ }
569
+
570
+ this.showInAppNotificationBanner({
571
+ visible: true,
572
+ title: conversation.displayName || this.chatBotName,
573
+ body: conversation.lastMessagePreview || '',
574
+ timestamp: conversation.lastMessageAt,
575
+ data: { type: 'chat_message', conversationId: conversation.id },
576
+ theme: this._notificationTheme,
577
+ duration: this._notificationDuration,
578
+ onTap: () => {
579
+ this.setModalState({
580
+ visible: true,
581
+ initialScreen: 'chat',
582
+ initialConversation: conversation,
583
+ theme: this._notificationTheme,
584
+ });
585
+ },
586
+ });
587
+ };
588
+ }
589
+
590
+ private handleWebSocketNotification(data: Record<string, any>): void {
591
+ if (data.type !== 'notification') return;
592
+
593
+ this.notificationListeners.forEach((l) => {
594
+ try {
595
+ l(data);
596
+ } catch (_) {}
597
+ });
598
+
599
+ if (!this._isInAppNotificationOn) return;
600
+
601
+ const title = stringValue(data.title) || this.chatBotName;
602
+ const body = stringValue(data.body) || '';
603
+ const payloadData =
604
+ data.data && typeof data.data === 'object' ? (data.data as Record<string, any>) : undefined;
605
+
606
+ this.showInAppNotification({
607
+ title,
608
+ message: body,
609
+ data: payloadData,
610
+ theme: this._notificationTheme,
611
+ duration: this._notificationDuration,
612
+ });
613
+ }
614
+
615
+ public showInAppNotification(options: {
616
+ title: string;
617
+ message: string;
618
+ data?: Record<string, any>;
619
+ theme?: FeeddoTheme;
620
+ duration?: number;
621
+ }): void {
622
+ const normalized = options.data ? normalizeNotificationPayload(options.data) : undefined;
623
+ const convId = normalized ? stringValue(normalized.conversationId) : undefined;
624
+ const type = normalized ? stringValue(normalized.type) : undefined;
625
+
626
+ if (convId && (!type || type === 'chat_message' || type === 'new_message')) {
627
+ const activeId = this.conversationService.activeConversationId;
628
+ if (activeId && activeId === convId) {
629
+ return;
630
+ }
631
+ }
632
+
633
+ if (normalized) {
634
+ const dedupKey = buildNotificationDedupKey(normalized, options.message);
635
+ if (dedupKey && !this.notificationDeduplicator.markIfNew(dedupKey)) {
636
+ return;
637
+ }
638
+ }
639
+
640
+ this.showInAppNotificationBanner({
641
+ visible: true,
642
+ title: options.title,
643
+ body: options.message,
644
+ timestamp: Date.now(),
645
+ data: normalized ?? options.data,
646
+ theme: options.theme ?? this._notificationTheme,
647
+ duration: options.duration ?? this._notificationDuration,
648
+ onTap: () => {
649
+ if (normalized ?? options.data) {
650
+ this.handleNotificationTap(normalized ?? options.data!, options.theme);
651
+ }
652
+ },
653
+ });
654
+ }
655
+
656
+ public handleForegroundNotification(
657
+ rawData: Record<string, any>,
658
+ options?: {
659
+ title?: string;
660
+ message?: string;
661
+ theme?: FeeddoTheme;
662
+ }
663
+ ): void {
664
+ try {
665
+ const normalized = normalizeNotificationPayload(rawData);
666
+ const convId = stringValue(normalized.conversationId);
667
+ const type = stringValue(normalized.type);
668
+ const activeId = this.conversationService.activeConversationId;
669
+ const isViewingActiveChat = Boolean(
670
+ convId &&
671
+ activeId === convId &&
672
+ (!type || type === 'chat_message' || type === 'new_message')
673
+ );
674
+
675
+ const notifTitle =
676
+ stringValue(options?.title) ?? stringValue(normalized.title) ?? this.chatBotName;
677
+ const notifBody = stringValue(options?.message) ?? stringValue(normalized.body) ?? '';
678
+
679
+ const dedupKey = buildNotificationDedupKey(normalized, notifBody);
680
+ const isDuplicate = dedupKey ? !this.notificationDeduplicator.markIfNew(dedupKey) : false;
681
+
682
+ if (!isDuplicate && !isViewingActiveChat) {
683
+ if (convId && (!type || type === 'chat_message' || type === 'new_message')) {
684
+ this.conversationService.incrementUnreadCount(convId);
685
+ } else {
686
+ const badge = intValue(normalized.badge);
687
+ if (badge !== undefined) {
688
+ this.conversationService.setTotalUnreadCount(badge);
689
+ }
690
+ }
691
+ }
692
+
693
+ if (isViewingActiveChat || isDuplicate || !this._isInAppNotificationOn) {
694
+ return;
695
+ }
696
+
697
+ this.showInAppNotificationBanner({
698
+ visible: true,
699
+ title: notifTitle,
700
+ body: notifBody,
701
+ timestamp: Date.now(),
702
+ data: normalized,
703
+ theme: options?.theme ?? this._notificationTheme,
704
+ duration: this._notificationDuration,
705
+ onTap: () => {
706
+ this.handleNotificationTap(normalized, options?.theme);
707
+ },
708
+ });
709
+ } catch (e) {
710
+ console.warn('Feeddo: Error handling foreground notification:', e);
711
+ }
712
+ }
713
+
714
+ public static queueOrHandleNotificationTap(
715
+ data: Record<string, any>,
716
+ theme?: FeeddoTheme
717
+ ): Promise<void> {
718
+ if (!this.isInitialized) {
719
+ this.pendingNotificationTap = { data, theme };
720
+ return Promise.resolve();
721
+ }
722
+ return this.instance.handleNotificationTap(data, theme);
723
+ }
724
+
725
+ public async handleNotificationTap(
726
+ rawData: Record<string, any>,
727
+ theme?: FeeddoTheme
728
+ ): Promise<void> {
729
+ const normalized = normalizeNotificationPayload(rawData);
730
+ try {
731
+ await this.ensureUserInitialized();
732
+ } catch (e) {
733
+ console.warn('Feeddo: Failed to sync user before notification tap:', e);
734
+ }
735
+
736
+ const type = stringValue(normalized.type);
737
+ const effectiveTheme = theme ?? this._notificationTheme;
738
+
739
+ if (isTaskNotification(type, normalized)) {
740
+ const taskId = stringValue(normalized.taskId);
741
+ if (taskId) {
742
+ this.setModalState({
743
+ visible: true,
744
+ initialScreen: 'tasks',
745
+ initialTaskId: taskId,
746
+ theme: effectiveTheme,
747
+ });
748
+ } else {
749
+ this.setModalState({
750
+ visible: true,
751
+ initialScreen: 'tasks',
752
+ initialTaskId: undefined,
753
+ theme: effectiveTheme,
754
+ });
755
+ }
756
+ } else if (isConversationNotification(type, normalized)) {
757
+ const conversationId = stringValue(normalized.conversationId);
758
+ if (conversationId) {
759
+ if (this.conversationService.activeConversationId === conversationId) {
760
+ return;
761
+ }
762
+ try {
763
+ const conv = await this.apiService.getConversation(conversationId);
764
+ this.setModalState({
765
+ visible: true,
766
+ initialScreen: 'chat',
767
+ initialConversation: conv,
768
+ initialTaskId: undefined,
769
+ theme: effectiveTheme,
770
+ });
771
+ } catch (e) {
772
+ console.warn('Feeddo: Failed to load conversation:', e);
773
+ }
774
+ } else {
775
+ this.setModalState({
776
+ visible: true,
777
+ initialScreen: 'home',
778
+ initialTaskId: undefined,
779
+ theme: effectiveTheme,
780
+ });
781
+ }
782
+ }
783
+ }
784
+
785
+ public async getHomeData(): Promise<HomeData> {
786
+ await this.ensureUserInitialized();
787
+ if (!this.userId) {
788
+ throw new Error('User not identified');
789
+ }
790
+ const homeData = await this.apiService.getHomeData(this.userId);
791
+ if (homeData.chatbotName) {
792
+ this._chatBotName = homeData.chatbotName;
793
+ }
794
+ if (homeData.recentConversation && homeData.recentConversation.status !== 'resolved') {
795
+ await StorageHelper.setHasActiveConversation(true);
796
+ } else {
797
+ await StorageHelper.setHasActiveConversation(false);
798
+ }
799
+ return homeData;
800
+ }
801
+
802
+ public static async getConversations(userId?: string): Promise<Conversation[]> {
803
+ const inst = FeeddoInternal.instance;
804
+ await inst.ensureUserInitialized();
805
+ const targetUserId = userId ?? inst.userId;
806
+ if (!targetUserId) throw new Error('User not identified');
807
+ await inst.conversationService.loadConversations(targetUserId);
808
+ return inst.conversationService.conversations;
809
+ }
810
+
811
+ public static async createConversation(options?: {
812
+ agentName?: string;
813
+ }): Promise<Conversation> {
814
+ const inst = FeeddoInternal.instance;
815
+ await inst.ensureUserInitialized();
816
+ if (!inst.userId) throw new Error('User not identified');
817
+ const conv = await inst.conversationService.createConversation(
818
+ inst.userId,
819
+ options?.agentName ?? 'support_agent'
820
+ );
821
+ await StorageHelper.setHasActiveConversation(true);
822
+ return conv;
823
+ }
824
+
825
+ public async getTickets(): Promise<Ticket[]> {
826
+ await this.ensureUserInitialized();
827
+ if (!this.userId) throw new Error('User not identified');
828
+ return await this.apiService.getTickets(this.userId);
829
+ }
830
+
831
+ public async getTicket(ticketId: string): Promise<Ticket> {
832
+ await this.ensureUserInitialized();
833
+ return await this.apiService.getTicket(ticketId, this.userId ?? undefined);
834
+ }
835
+
836
+ public async addTaskComment(
837
+ taskId: string,
838
+ content: string,
839
+ options?: { attachments?: Array<Record<string, any>> }
840
+ ): Promise<TaskComment> {
841
+ await this.ensureUserInitialized();
842
+ return await this.apiService.addTaskComment(taskId, content, {
843
+ userId: this.userId ?? undefined,
844
+ attachments: options?.attachments,
845
+ });
846
+ }
847
+
848
+ public async voteTask(
849
+ taskId: string,
850
+ voteType: string
851
+ ): Promise<{ success: boolean; upvoteCount?: number }> {
852
+ await this.ensureUserInitialized();
853
+ return await this.apiService.voteTask(taskId, voteType, {
854
+ userId: this.userId ?? undefined,
855
+ });
856
+ }
857
+
858
+ public async connectWebSocket(conversationId?: string): Promise<void> {
859
+ const id = await this.ensureUserInitialized();
860
+ this.webSocketService.setUserId(id);
861
+ await this.webSocketService.connect(id, conversationId);
862
+ }
863
+
864
+ public disconnectWebSocket(): void {
865
+ this.webSocketService.disconnect();
866
+ }
867
+
868
+ private cleanupResources(): void {
869
+ this.conversationService.onNewMessage = undefined;
870
+ this.unsubscribeWsNotifications?.();
871
+ this.unsubscribeConvUnread?.();
872
+ this.notificationListeners.clear();
873
+ this.notificationDeduplicator.clear();
874
+ this.disconnectWebSocket();
875
+ this.webSocketService.dispose();
876
+ this.conversationService.dispose();
877
+ }
878
+
879
+ public static dispose(): void {
880
+ if (this._instance) {
881
+ this._instance.cleanupResources();
882
+ this._instance = null;
883
+ }
884
+ this.pendingNotificationTap = null;
885
+ this.clearAllNotifications();
886
+ this.setModalState({
887
+ visible: false,
888
+ initialScreen: 'home',
889
+ initialConversation: null,
890
+ initialChatMessage: undefined,
891
+ initialTaskId: undefined,
892
+ });
893
+ this.notifyUnreadListeners(0);
894
+ }
895
+ }