@viewberapp/chat 0.0.106 → 0.0.107

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 (66) hide show
  1. package/LICENSE +20 -20
  2. package/dist/API.d.ts +83 -83
  3. package/dist/API.js +216 -216
  4. package/dist/CachedChat.d.ts +59 -59
  5. package/dist/CachedChat.js +220 -220
  6. package/dist/Chat.d.ts +64 -64
  7. package/dist/Chat.js +267 -267
  8. package/dist/ChatError.d.ts +4 -4
  9. package/dist/ChatError.js +2 -2
  10. package/dist/ChatSubscription.d.ts +79 -79
  11. package/dist/ChatSubscription.js +119 -119
  12. package/dist/Message.d.ts +25 -25
  13. package/dist/Message.js +35 -35
  14. package/dist/OnlineUser.d.ts +8 -8
  15. package/dist/OnlineUser.js +9 -9
  16. package/dist/PendingMessage.d.ts +23 -23
  17. package/dist/PendingMessage.js +23 -23
  18. package/dist/index.d.ts +8 -8
  19. package/dist/index.js +27 -27
  20. package/dist/logger/ConsoleLogger.d.ts +8 -8
  21. package/dist/logger/ConsoleLogger.js +20 -20
  22. package/dist/logger/NullLogger.d.ts +8 -8
  23. package/dist/logger/NullLogger.js +10 -10
  24. package/dist/logger/RollbarLogger.d.ts +11 -11
  25. package/dist/logger/RollbarLogger.js +23 -23
  26. package/dist/logger/index.d.ts +12 -12
  27. package/dist/logger/index.js +12 -12
  28. package/dist/react/components/AdminMessage.d.ts +6 -6
  29. package/dist/react/components/AdminMessage.js +59 -59
  30. package/dist/react/components/ConnectionAndChannelStatusLabel.d.ts +7 -7
  31. package/dist/react/components/ConnectionAndChannelStatusLabel.js +59 -59
  32. package/dist/react/components/Message.d.ts +23 -23
  33. package/dist/react/components/Message.js +87 -87
  34. package/dist/react/components/MessageDateTime.d.ts +8 -8
  35. package/dist/react/components/MessageDateTime.js +31 -31
  36. package/dist/react/components/MessageList.d.ts +46 -46
  37. package/dist/react/components/MessageList.js +107 -107
  38. package/dist/react/components/MessageRow.d.ts +5 -5
  39. package/dist/react/components/MessageRow.js +34 -34
  40. package/dist/react/components/index.d.ts +6 -6
  41. package/dist/react/components/index.js +13 -13
  42. package/dist/react/index.d.ts +3 -3
  43. package/dist/react/index.js +16 -16
  44. package/dist/react/useAppointmentChat.d.ts +3 -3
  45. package/dist/react/useAppointmentChat.js +10 -10
  46. package/dist/react/useChat.d.ts +36 -36
  47. package/dist/react/useChat.js +123 -123
  48. package/dist/react/useRealtimeTotalUserUnreadChatMessages.d.ts +12 -12
  49. package/dist/react/useRealtimeTotalUserUnreadChatMessages.js +137 -139
  50. package/dist/react/useRealtimeTotalUserUnreadChatMessages.js.map +1 -1
  51. package/dist/util/getLatestMessage.d.ts +3 -3
  52. package/dist/util/getLatestMessage.js +17 -17
  53. package/dist/util/groupMessages.d.ts +8 -8
  54. package/dist/util/groupMessages.js +30 -30
  55. package/dist/util/index.d.ts +4 -4
  56. package/dist/util/index.js +9 -9
  57. package/dist/util/isNil.d.ts +1 -1
  58. package/dist/util/isNil.js +7 -7
  59. package/dist/util/jwtTokenChanged.d.ts +1 -1
  60. package/dist/util/jwtTokenChanged.js +10 -10
  61. package/dist/util/useIsMounted.d.ts +1 -1
  62. package/dist/util/useIsMounted.js +13 -13
  63. package/package.json +2 -2
  64. package/dist/util/getLatestMessageId.d.ts +0 -3
  65. package/dist/util/getLatestMessageId.js +0 -18
  66. package/dist/util/getLatestMessageId.js.map +0 -1
package/dist/Chat.d.ts CHANGED
@@ -1,64 +1,64 @@
1
- import * as Ably from 'ably';
2
- import ChatError from "./ChatError";
3
- import { AxiosInstance } from 'axios';
4
- import API, { ConstructApiParams } from "./API";
5
- import { Logger } from "./logger";
6
- import ChatSubscription from "./ChatSubscription";
7
- export interface ChatOptions {
8
- axios: AxiosInstance;
9
- logger?: Logger;
10
- jwtToken?: string;
11
- routes: Routes;
12
- debug?: DebugOptions;
13
- }
14
- export interface Routes {
15
- getChatMessagesRoute: ConstructApiParams['getChatMessagesRoute'];
16
- getChatAblyTokenRoute: ConstructApiParams['getChatAblyTokenRoute'];
17
- getChatStoreMessageRoute: ConstructApiParams['getChatStoreMessageRoute'];
18
- getChatForAppointmentRoute: ConstructApiParams['getChatForAppointmentRoute'];
19
- markChatMessagesReadUpToRoute: ConstructApiParams['markChatMessagesReadUpToRoute'];
20
- getUserChatUnreadMessageCountRoute: ConstructApiParams['getUserChatUnreadMessageCountRoute'];
21
- }
22
- export interface DebugOptions {
23
- apiResponses: boolean;
24
- apiErrors: boolean;
25
- inboundAblyMessages: boolean;
26
- }
27
- export declare type ConnectionStatus = 'initialized' | 'connecting' | 'connected' | 'disconnected' | 'suspended' | 'closing' | 'closed' | 'failed';
28
- export declare type ChannelStatus = 'initialized' | 'attaching' | 'attached' | 'detaching' | 'detached' | 'suspended' | 'failed';
29
- export interface ChatEvents {
30
- initialized: boolean;
31
- }
32
- export declare type ChatEventCallbacks = {
33
- [Event in keyof ChatEvents]: (data: ChatEvents[Event]) => void;
34
- };
35
- export declare type ChatEventListeners = {
36
- [Event in keyof ChatEvents]: ChatEventCallbacks[Event][];
37
- };
38
- declare const Chat: {
39
- init: (options: ChatOptions) => void;
40
- isInitialized: () => boolean;
41
- setJwtToken: (_jwtToken?: string) => void;
42
- api: () => API;
43
- get: (id: number) => Promise<{
44
- subscription: ChatSubscription;
45
- error?: undefined;
46
- } | {
47
- subscription?: undefined;
48
- error: ChatError;
49
- }>;
50
- appointment: (appointmentId: number) => Promise<{
51
- subscription: ChatSubscription;
52
- error?: undefined;
53
- } | {
54
- subscription?: undefined;
55
- error: ChatError;
56
- }>;
57
- connect: () => void;
58
- close: () => void;
59
- channel: (channelName: string) => Ably.Types.RealtimeChannelCallbacks;
60
- addEventListener: <Event_1 extends "initialized">(event: Event_1, listener: ChatEventCallbacks[Event_1]) => void;
61
- removeEventListener: <Event_2 extends "initialized">(event: Event_2, listener: ChatEventCallbacks[Event_2]) => void;
62
- logout: () => void;
63
- };
64
- export default Chat;
1
+ import * as Ably from 'ably';
2
+ import ChatError from "./ChatError";
3
+ import { AxiosInstance } from 'axios';
4
+ import API, { ConstructApiParams } from "./API";
5
+ import { Logger } from "./logger";
6
+ import ChatSubscription from "./ChatSubscription";
7
+ export interface ChatOptions {
8
+ axios: AxiosInstance;
9
+ logger?: Logger;
10
+ jwtToken?: string;
11
+ routes: Routes;
12
+ debug?: DebugOptions;
13
+ }
14
+ export interface Routes {
15
+ getChatMessagesRoute: ConstructApiParams['getChatMessagesRoute'];
16
+ getChatAblyTokenRoute: ConstructApiParams['getChatAblyTokenRoute'];
17
+ getChatStoreMessageRoute: ConstructApiParams['getChatStoreMessageRoute'];
18
+ getChatForAppointmentRoute: ConstructApiParams['getChatForAppointmentRoute'];
19
+ markChatMessagesReadUpToRoute: ConstructApiParams['markChatMessagesReadUpToRoute'];
20
+ getUserChatUnreadMessageCountRoute: ConstructApiParams['getUserChatUnreadMessageCountRoute'];
21
+ }
22
+ export interface DebugOptions {
23
+ apiResponses: boolean;
24
+ apiErrors: boolean;
25
+ inboundAblyMessages: boolean;
26
+ }
27
+ export declare type ConnectionStatus = 'initialized' | 'connecting' | 'connected' | 'disconnected' | 'suspended' | 'closing' | 'closed' | 'failed';
28
+ export declare type ChannelStatus = 'initialized' | 'attaching' | 'attached' | 'detaching' | 'detached' | 'suspended' | 'failed';
29
+ export interface ChatEvents {
30
+ initialized: boolean;
31
+ }
32
+ export declare type ChatEventCallbacks = {
33
+ [Event in keyof ChatEvents]: (data: ChatEvents[Event]) => void;
34
+ };
35
+ export declare type ChatEventListeners = {
36
+ [Event in keyof ChatEvents]: ChatEventCallbacks[Event][];
37
+ };
38
+ declare const Chat: {
39
+ init: (options: ChatOptions) => void;
40
+ isInitialized: () => boolean;
41
+ setJwtToken: (_jwtToken?: string) => void;
42
+ api: () => API;
43
+ get: (id: number) => Promise<{
44
+ subscription: ChatSubscription;
45
+ error?: undefined;
46
+ } | {
47
+ subscription?: undefined;
48
+ error: ChatError;
49
+ }>;
50
+ appointment: (appointmentId: number) => Promise<{
51
+ subscription: ChatSubscription;
52
+ error?: undefined;
53
+ } | {
54
+ subscription?: undefined;
55
+ error: ChatError;
56
+ }>;
57
+ connect: () => void;
58
+ close: () => void;
59
+ channel: (channelName: string) => Ably.Types.RealtimeChannelCallbacks;
60
+ addEventListener: <Event_1 extends "initialized">(event: Event_1, listener: ChatEventCallbacks[Event_1]) => void;
61
+ removeEventListener: <Event_2 extends "initialized">(event: Event_2, listener: ChatEventCallbacks[Event_2]) => void;
62
+ logout: () => void;
63
+ };
64
+ export default Chat;
package/dist/Chat.js CHANGED
@@ -1,268 +1,268 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __importStar = (this && this.__importStar) || function (mod) {
19
- if (mod && mod.__esModule) return mod;
20
- var result = {};
21
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
- __setModuleDefault(result, mod);
23
- return result;
24
- };
25
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
26
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
27
- return new (P || (P = Promise))(function (resolve, reject) {
28
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
29
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
30
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
31
- step((generator = generator.apply(thisArg, _arguments || [])).next());
32
- });
33
- };
34
- var __importDefault = (this && this.__importDefault) || function (mod) {
35
- return (mod && mod.__esModule) ? mod : { "default": mod };
36
- };
37
- Object.defineProperty(exports, "__esModule", { value: true });
38
- const Ably = __importStar(require("ably"));
39
- const util_1 = require("./util");
40
- const CachedChat_1 = __importDefault(require("./CachedChat"));
41
- const API_1 = __importDefault(require("./API"));
42
- const logger_1 = require("./logger");
43
- const ChatSubscription_1 = __importDefault(require("./ChatSubscription"));
44
- const jwtTokenChanged_1 = require("./util/jwtTokenChanged");
45
- const Chat = (function () {
46
- let initialized = false;
47
- let axios;
48
- let jwtToken;
49
- let routes;
50
- let logger;
51
- let debugLogger;
52
- let debug;
53
- let _api;
54
- let ably;
55
- let connectionStatus;
56
- const eventListeners = {
57
- initialized: []
58
- };
59
- const chats = {};
60
- const init = (options) => {
61
- if (initialized) {
62
- console.warn('Chat.init() was called more than once. Ignoring.');
63
- return;
64
- }
65
- axios = options.axios;
66
- jwtToken = options.jwtToken;
67
- routes = options.routes;
68
- logger = options.logger || new logger_1.ConsoleLogger;
69
- debugLogger = new logger_1.ConsoleLogger;
70
- debug = options.debug;
71
- _api = makeApi();
72
- ably = new Ably.Realtime({
73
- autoConnect: false,
74
- authCallback(tokenParams, callback) {
75
- api().getAblyToken(Object.keys(chats).map(id => Number(id))).then(result => {
76
- if (result.error) {
77
- callback(result.error.code, undefined);
78
- if (result.error.code === 'no_authorized_chats_given'
79
- || result.error.code === 'unauthorized') {
80
- ably.close();
81
- }
82
- }
83
- else {
84
- callback(null, result.token);
85
- }
86
- }).catch(err => {
87
- callback(err, undefined);
88
- });
89
- },
90
- });
91
- connectionStatus = ably.connection.state;
92
- ably.connection.on(handleAblyConnectionStateChange);
93
- initialized = true;
94
- fireEvent('initialized', initialized);
95
- };
96
- const isInitialized = () => {
97
- return initialized;
98
- };
99
- const setJwtToken = (_jwtToken) => {
100
- if (!(0, jwtTokenChanged_1.jwtTokenChanged)(_jwtToken, jwtToken)) {
101
- return;
102
- }
103
- jwtToken = _jwtToken;
104
- for (const chatId in chats) {
105
- if (Object.prototype.hasOwnProperty.call(chats, chatId)) {
106
- const chat = chats[chatId];
107
- if ((0, util_1.isNil)(chat)) {
108
- continue;
109
- }
110
- chat.cancelAllSubscriptions();
111
- delete chats[chatId];
112
- chat.detachChannel(function (err) {
113
- if (err)
114
- logger.error(err);
115
- ably.channels.release(getChatChannelName(Number(chatId)));
116
- });
117
- }
118
- }
119
- _api = makeApi();
120
- ably.close();
121
- };
122
- const api = () => {
123
- return _api;
124
- };
125
- const get = (id) => new Promise((resolve, reject) => {
126
- getChat(id).then(({ chat, isFirstFetch, error }) => {
127
- if (error) {
128
- return resolve({ error });
129
- }
130
- const subscription = new ChatSubscription_1.default(chat, {
131
- status: 'active',
132
- channelStatus: chat.getChannelStatus(),
133
- connectionStatus: chat.getConnectionStatus(),
134
- getLatestMessagesStatus: chat.getGetLatestMessagesStatus()
135
- });
136
- chat.addSubscription(subscription);
137
- if (isFirstFetch) {
138
- chat.getLatestMessages();
139
- }
140
- resolve({ subscription });
141
- }).catch(err => {
142
- return resolve({ error: {
143
- message: 'Failed to resolve the chat',
144
- code: 'error'
145
- } });
146
- });
147
- });
148
- const appointment = (appointmentId) => __awaiter(this, void 0, void 0, function* () {
149
- try {
150
- const { chatId, error } = yield api().getChatIdFromAppointmentId(appointmentId);
151
- if (error) {
152
- return { error };
153
- }
154
- return yield get(chatId);
155
- }
156
- catch (err) {
157
- return { error: {
158
- message: 'Error',
159
- code: 'error'
160
- } };
161
- }
162
- });
163
- const getChat = (chatId) => new Promise((resolve, reject) => {
164
- if (!(chatId.toString() in chats)) {
165
- chats[chatId] = undefined;
166
- ably.auth.authorize(function (err, tokenDetails) {
167
- if (err) {
168
- return resolve({ error: {
169
- message: err.toString(),
170
- code: 'error'
171
- } });
172
- }
173
- let chat = new CachedChat_1.default({
174
- id: chatId,
175
- api: api(),
176
- channel: ably.channels.get(getChatChannelName(chatId)),
177
- connectionStatus,
178
- logger,
179
- debugLogger,
180
- debug
181
- });
182
- chats[chatId] = chat;
183
- return resolve({
184
- chat,
185
- isFirstFetch: true
186
- });
187
- });
188
- }
189
- else {
190
- let chat = chats[chatId];
191
- if (!(0, util_1.isNil)(chat)) {
192
- return resolve({
193
- chat,
194
- isFirstFetch: true
195
- });
196
- }
197
- else {
198
- return resolve({ error: {
199
- message: 'Error resolving to the chat.',
200
- code: 'error'
201
- } });
202
- }
203
- }
204
- });
205
- const connect = () => {
206
- ably.connect();
207
- };
208
- const close = () => {
209
- ably.close();
210
- };
211
- const channel = (channelName) => {
212
- return ably.channels.get(channelName);
213
- };
214
- const handleAblyConnectionStateChange = (event) => {
215
- connectionStatus = event.current;
216
- Object.values(chats).forEach(chat => {
217
- if (!(0, util_1.isNil)(chat)) {
218
- chat.setConnectionStatus(connectionStatus);
219
- }
220
- });
221
- };
222
- const makeApi = () => new API_1.default({
223
- axios,
224
- jwtToken,
225
- logger,
226
- debugLogger,
227
- debug,
228
- getChatMessagesRoute: routes.getChatMessagesRoute,
229
- getChatAblyTokenRoute: routes.getChatAblyTokenRoute,
230
- getChatStoreMessageRoute: routes.getChatStoreMessageRoute,
231
- getChatForAppointmentRoute: routes.getChatForAppointmentRoute,
232
- markChatMessagesReadUpToRoute: routes.markChatMessagesReadUpToRoute,
233
- getUserChatUnreadMessageCountRoute: routes.getUserChatUnreadMessageCountRoute,
234
- });
235
- const fireEvent = (event, data) => {
236
- eventListeners[event].forEach(listener => listener(data));
237
- };
238
- const addEventListener = (event, listener) => {
239
- eventListeners[event].push(listener);
240
- };
241
- const removeEventListener = (event, listener) => {
242
- eventListeners[event] = eventListeners[event].filter(l => {
243
- return l !== listener;
244
- });
245
- };
246
- const logout = () => {
247
- setJwtToken(undefined);
248
- };
249
- const getChatChannelName = (chatId) => {
250
- return `viewber:chat:${chatId}`;
251
- };
252
- return {
253
- init,
254
- isInitialized,
255
- setJwtToken,
256
- api,
257
- get,
258
- appointment,
259
- connect,
260
- close,
261
- channel,
262
- addEventListener,
263
- removeEventListener,
264
- logout
265
- };
266
- })();
267
- exports.default = Chat;
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
26
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
27
+ return new (P || (P = Promise))(function (resolve, reject) {
28
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
29
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
30
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
31
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
32
+ });
33
+ };
34
+ var __importDefault = (this && this.__importDefault) || function (mod) {
35
+ return (mod && mod.__esModule) ? mod : { "default": mod };
36
+ };
37
+ Object.defineProperty(exports, "__esModule", { value: true });
38
+ const Ably = __importStar(require("ably"));
39
+ const util_1 = require("./util");
40
+ const CachedChat_1 = __importDefault(require("./CachedChat"));
41
+ const API_1 = __importDefault(require("./API"));
42
+ const logger_1 = require("./logger");
43
+ const ChatSubscription_1 = __importDefault(require("./ChatSubscription"));
44
+ const jwtTokenChanged_1 = require("./util/jwtTokenChanged");
45
+ const Chat = (function () {
46
+ let initialized = false;
47
+ let axios;
48
+ let jwtToken;
49
+ let routes;
50
+ let logger;
51
+ let debugLogger;
52
+ let debug;
53
+ let _api;
54
+ let ably;
55
+ let connectionStatus;
56
+ const eventListeners = {
57
+ initialized: []
58
+ };
59
+ const chats = {};
60
+ const init = (options) => {
61
+ if (initialized) {
62
+ console.warn('Chat.init() was called more than once. Ignoring.');
63
+ return;
64
+ }
65
+ axios = options.axios;
66
+ jwtToken = options.jwtToken;
67
+ routes = options.routes;
68
+ logger = options.logger || new logger_1.ConsoleLogger;
69
+ debugLogger = new logger_1.ConsoleLogger;
70
+ debug = options.debug;
71
+ _api = makeApi();
72
+ ably = new Ably.Realtime({
73
+ autoConnect: false,
74
+ authCallback(tokenParams, callback) {
75
+ api().getAblyToken(Object.keys(chats).map(id => Number(id))).then(result => {
76
+ if (result.error) {
77
+ callback(result.error.code, undefined);
78
+ if (result.error.code === 'no_authorized_chats_given'
79
+ || result.error.code === 'unauthorized') {
80
+ ably.close();
81
+ }
82
+ }
83
+ else {
84
+ callback(null, result.token);
85
+ }
86
+ }).catch(err => {
87
+ callback(err, undefined);
88
+ });
89
+ },
90
+ });
91
+ connectionStatus = ably.connection.state;
92
+ ably.connection.on(handleAblyConnectionStateChange);
93
+ initialized = true;
94
+ fireEvent('initialized', initialized);
95
+ };
96
+ const isInitialized = () => {
97
+ return initialized;
98
+ };
99
+ const setJwtToken = (_jwtToken) => {
100
+ if (!(0, jwtTokenChanged_1.jwtTokenChanged)(_jwtToken, jwtToken)) {
101
+ return;
102
+ }
103
+ jwtToken = _jwtToken;
104
+ for (const chatId in chats) {
105
+ if (Object.prototype.hasOwnProperty.call(chats, chatId)) {
106
+ const chat = chats[chatId];
107
+ if ((0, util_1.isNil)(chat)) {
108
+ continue;
109
+ }
110
+ chat.cancelAllSubscriptions();
111
+ delete chats[chatId];
112
+ chat.detachChannel(function (err) {
113
+ if (err)
114
+ logger.error(err);
115
+ ably.channels.release(getChatChannelName(Number(chatId)));
116
+ });
117
+ }
118
+ }
119
+ _api = makeApi();
120
+ ably.close();
121
+ };
122
+ const api = () => {
123
+ return _api;
124
+ };
125
+ const get = (id) => new Promise((resolve, reject) => {
126
+ getChat(id).then(({ chat, isFirstFetch, error }) => {
127
+ if (error) {
128
+ return resolve({ error });
129
+ }
130
+ const subscription = new ChatSubscription_1.default(chat, {
131
+ status: 'active',
132
+ channelStatus: chat.getChannelStatus(),
133
+ connectionStatus: chat.getConnectionStatus(),
134
+ getLatestMessagesStatus: chat.getGetLatestMessagesStatus()
135
+ });
136
+ chat.addSubscription(subscription);
137
+ if (isFirstFetch) {
138
+ chat.getLatestMessages();
139
+ }
140
+ resolve({ subscription });
141
+ }).catch(err => {
142
+ return resolve({ error: {
143
+ message: 'Failed to resolve the chat',
144
+ code: 'error'
145
+ } });
146
+ });
147
+ });
148
+ const appointment = (appointmentId) => __awaiter(this, void 0, void 0, function* () {
149
+ try {
150
+ const { chatId, error } = yield api().getChatIdFromAppointmentId(appointmentId);
151
+ if (error) {
152
+ return { error };
153
+ }
154
+ return yield get(chatId);
155
+ }
156
+ catch (err) {
157
+ return { error: {
158
+ message: 'Error',
159
+ code: 'error'
160
+ } };
161
+ }
162
+ });
163
+ const getChat = (chatId) => new Promise((resolve, reject) => {
164
+ if (!(chatId.toString() in chats)) {
165
+ chats[chatId] = undefined;
166
+ ably.auth.authorize(function (err, tokenDetails) {
167
+ if (err) {
168
+ return resolve({ error: {
169
+ message: err.toString(),
170
+ code: 'error'
171
+ } });
172
+ }
173
+ let chat = new CachedChat_1.default({
174
+ id: chatId,
175
+ api: api(),
176
+ channel: ably.channels.get(getChatChannelName(chatId)),
177
+ connectionStatus,
178
+ logger,
179
+ debugLogger,
180
+ debug
181
+ });
182
+ chats[chatId] = chat;
183
+ return resolve({
184
+ chat,
185
+ isFirstFetch: true
186
+ });
187
+ });
188
+ }
189
+ else {
190
+ let chat = chats[chatId];
191
+ if (!(0, util_1.isNil)(chat)) {
192
+ return resolve({
193
+ chat,
194
+ isFirstFetch: true
195
+ });
196
+ }
197
+ else {
198
+ return resolve({ error: {
199
+ message: 'Error resolving to the chat.',
200
+ code: 'error'
201
+ } });
202
+ }
203
+ }
204
+ });
205
+ const connect = () => {
206
+ ably.connect();
207
+ };
208
+ const close = () => {
209
+ ably.close();
210
+ };
211
+ const channel = (channelName) => {
212
+ return ably.channels.get(channelName);
213
+ };
214
+ const handleAblyConnectionStateChange = (event) => {
215
+ connectionStatus = event.current;
216
+ Object.values(chats).forEach(chat => {
217
+ if (!(0, util_1.isNil)(chat)) {
218
+ chat.setConnectionStatus(connectionStatus);
219
+ }
220
+ });
221
+ };
222
+ const makeApi = () => new API_1.default({
223
+ axios,
224
+ jwtToken,
225
+ logger,
226
+ debugLogger,
227
+ debug,
228
+ getChatMessagesRoute: routes.getChatMessagesRoute,
229
+ getChatAblyTokenRoute: routes.getChatAblyTokenRoute,
230
+ getChatStoreMessageRoute: routes.getChatStoreMessageRoute,
231
+ getChatForAppointmentRoute: routes.getChatForAppointmentRoute,
232
+ markChatMessagesReadUpToRoute: routes.markChatMessagesReadUpToRoute,
233
+ getUserChatUnreadMessageCountRoute: routes.getUserChatUnreadMessageCountRoute,
234
+ });
235
+ const fireEvent = (event, data) => {
236
+ eventListeners[event].forEach(listener => listener(data));
237
+ };
238
+ const addEventListener = (event, listener) => {
239
+ eventListeners[event].push(listener);
240
+ };
241
+ const removeEventListener = (event, listener) => {
242
+ eventListeners[event] = eventListeners[event].filter(l => {
243
+ return l !== listener;
244
+ });
245
+ };
246
+ const logout = () => {
247
+ setJwtToken(undefined);
248
+ };
249
+ const getChatChannelName = (chatId) => {
250
+ return `viewber:chat:${chatId}`;
251
+ };
252
+ return {
253
+ init,
254
+ isInitialized,
255
+ setJwtToken,
256
+ api,
257
+ get,
258
+ appointment,
259
+ connect,
260
+ close,
261
+ channel,
262
+ addEventListener,
263
+ removeEventListener,
264
+ logout
265
+ };
266
+ })();
267
+ exports.default = Chat;
268
268
  //# sourceMappingURL=Chat.js.map