@devanachat/sdk 0.0.0-stage → 0.7.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 (196) hide show
  1. package/CHANGELOG.md +81 -0
  2. package/LICENSE +21 -0
  3. package/README.md +418 -2
  4. package/build/index.cjs.js +3656 -0
  5. package/build/index.cjs.js.map +1 -0
  6. package/build/index.mjs +3613 -0
  7. package/build/index.mjs.map +1 -0
  8. package/build/index.umd.js +2 -0
  9. package/build/index.umd.js.map +1 -0
  10. package/build/types/AbstractChatClient.d.ts +184 -0
  11. package/build/types/AbstractRestClient.d.ts +21 -0
  12. package/build/types/EventTarget.d.ts +32 -0
  13. package/build/types/FilesClient.d.ts +16 -0
  14. package/build/types/IndexedObjectCollection.d.ts +66 -0
  15. package/build/types/Permissions.d.ts +117 -0
  16. package/build/types/WebApiChatClient.d.ts +38 -0
  17. package/build/types/WebSocketChatClient.d.ts +110 -0
  18. package/build/types/index.d.ts +19 -0
  19. package/build/types/protocol/index.d.ts +165 -0
  20. package/build/types/protocol/schemes/BanObject.d.ts +14 -0
  21. package/build/types/protocol/schemes/ChatLocation.d.ts +5 -0
  22. package/build/types/protocol/schemes/Emoticon.d.ts +9 -0
  23. package/build/types/protocol/schemes/Entitlements.d.ts +92 -0
  24. package/build/types/protocol/schemes/Envelope.d.ts +5 -0
  25. package/build/types/protocol/schemes/FollowedTopic.d.ts +10 -0
  26. package/build/types/protocol/schemes/LeaveReason.d.ts +9 -0
  27. package/build/types/protocol/schemes/Message.d.ts +32 -0
  28. package/build/types/protocol/schemes/MessagePoll.d.ts +10 -0
  29. package/build/types/protocol/schemes/PermissionOverwritesTarget.d.ts +5 -0
  30. package/build/types/protocol/schemes/PermissionOverwritesValue.d.ts +4 -0
  31. package/build/types/protocol/schemes/Reaction.d.ts +13 -0
  32. package/build/types/protocol/schemes/Role.d.ts +20 -0
  33. package/build/types/protocol/schemes/Room.d.ts +17 -0
  34. package/build/types/protocol/schemes/RoomHistory.d.ts +5 -0
  35. package/build/types/protocol/schemes/RoomMember.d.ts +11 -0
  36. package/build/types/protocol/schemes/RoomStream.d.ts +5 -0
  37. package/build/types/protocol/schemes/RoomSummary.d.ts +15 -0
  38. package/build/types/protocol/schemes/SessionData.d.ts +10 -0
  39. package/build/types/protocol/schemes/Space.d.ts +19 -0
  40. package/build/types/protocol/schemes/SpaceMember.d.ts +7 -0
  41. package/build/types/protocol/schemes/SpaceSummary.d.ts +8 -0
  42. package/build/types/protocol/schemes/Topic.d.ts +8 -0
  43. package/build/types/protocol/schemes/User.d.ts +23 -0
  44. package/build/types/protocol/schemes/UserData.d.ts +10 -0
  45. package/build/types/protocol/schemes/UserInformation.d.ts +11 -0
  46. package/build/types/protocol/schemes/UserRelationship.d.ts +6 -0
  47. package/build/types/protocol/schemes/UserState.d.ts +6 -0
  48. package/build/types/protocol/schemes/commands/Ack.d.ts +5 -0
  49. package/build/types/protocol/schemes/commands/AssignRole.d.ts +6 -0
  50. package/build/types/protocol/schemes/commands/Ban.d.ts +10 -0
  51. package/build/types/protocol/schemes/commands/CreateAccessTicket.d.ts +13 -0
  52. package/build/types/protocol/schemes/commands/CreateEmoticon.d.ts +5 -0
  53. package/build/types/protocol/schemes/commands/CreateMessage.d.ts +11 -0
  54. package/build/types/protocol/schemes/commands/CreateOwner.d.ts +5 -0
  55. package/build/types/protocol/schemes/commands/CreateRelationship.d.ts +5 -0
  56. package/build/types/protocol/schemes/commands/CreateRole.d.ts +6 -0
  57. package/build/types/protocol/schemes/commands/CreateRoom.d.ts +9 -0
  58. package/build/types/protocol/schemes/commands/CreateSpace.d.ts +6 -0
  59. package/build/types/protocol/schemes/commands/CreateTopic.d.ts +11 -0
  60. package/build/types/protocol/schemes/commands/DeassignRole.d.ts +6 -0
  61. package/build/types/protocol/schemes/commands/DeleteEmoticon.d.ts +3 -0
  62. package/build/types/protocol/schemes/commands/DeleteOwner.d.ts +5 -0
  63. package/build/types/protocol/schemes/commands/DeleteRelationship.d.ts +5 -0
  64. package/build/types/protocol/schemes/commands/DeleteRole.d.ts +4 -0
  65. package/build/types/protocol/schemes/commands/DeleteRoom.d.ts +3 -0
  66. package/build/types/protocol/schemes/commands/DeleteSpace.d.ts +3 -0
  67. package/build/types/protocol/schemes/commands/DeleteTopic.d.ts +4 -0
  68. package/build/types/protocol/schemes/commands/FollowTopic.d.ts +4 -0
  69. package/build/types/protocol/schemes/commands/GetBans.d.ts +6 -0
  70. package/build/types/protocol/schemes/commands/GetClientData.d.ts +2 -0
  71. package/build/types/protocol/schemes/commands/GetComputedPermissions.d.ts +10 -0
  72. package/build/types/protocol/schemes/commands/GetDiscoverableSpaces.d.ts +2 -0
  73. package/build/types/protocol/schemes/commands/GetEmoticons.d.ts +3 -0
  74. package/build/types/protocol/schemes/commands/GetEntitlements.d.ts +8 -0
  75. package/build/types/protocol/schemes/commands/GetFollowedTopics.d.ts +4 -0
  76. package/build/types/protocol/schemes/commands/GetInvited.d.ts +3 -0
  77. package/build/types/protocol/schemes/commands/GetMessages.d.ts +13 -0
  78. package/build/types/protocol/schemes/commands/GetOwners.d.ts +4 -0
  79. package/build/types/protocol/schemes/commands/GetPermissionOverwriteTargets.d.ts +4 -0
  80. package/build/types/protocol/schemes/commands/GetPermissionOverwrites.d.ts +6 -0
  81. package/build/types/protocol/schemes/commands/GetReactionDetails.d.ts +8 -0
  82. package/build/types/protocol/schemes/commands/GetRelationships.d.ts +2 -0
  83. package/build/types/protocol/schemes/commands/GetRoomMembers.d.ts +3 -0
  84. package/build/types/protocol/schemes/commands/GetRoomSummary.d.ts +4 -0
  85. package/build/types/protocol/schemes/commands/GetSession.d.ts +2 -0
  86. package/build/types/protocol/schemes/commands/GetSessionData.d.ts +2 -0
  87. package/build/types/protocol/schemes/commands/GetSpaceMembers.d.ts +3 -0
  88. package/build/types/protocol/schemes/commands/GetSpaceRooms.d.ts +3 -0
  89. package/build/types/protocol/schemes/commands/GetSpaceSummary.d.ts +3 -0
  90. package/build/types/protocol/schemes/commands/GetTopics.d.ts +4 -0
  91. package/build/types/protocol/schemes/commands/GetUserData.d.ts +2 -0
  92. package/build/types/protocol/schemes/commands/GetUserInfo.d.ts +3 -0
  93. package/build/types/protocol/schemes/commands/Invite.d.ts +5 -0
  94. package/build/types/protocol/schemes/commands/JoinRoom.d.ts +13 -0
  95. package/build/types/protocol/schemes/commands/JoinSpace.d.ts +3 -0
  96. package/build/types/protocol/schemes/commands/Kick.d.ts +7 -0
  97. package/build/types/protocol/schemes/commands/LeaveRoom.d.ts +3 -0
  98. package/build/types/protocol/schemes/commands/LeaveSpace.d.ts +3 -0
  99. package/build/types/protocol/schemes/commands/Ping.d.ts +2 -0
  100. package/build/types/protocol/schemes/commands/React.d.ts +6 -0
  101. package/build/types/protocol/schemes/commands/RedactMessages.d.ts +3 -0
  102. package/build/types/protocol/schemes/commands/ReportAbuse.d.ts +9 -0
  103. package/build/types/protocol/schemes/commands/SearchMessages.d.ts +18 -0
  104. package/build/types/protocol/schemes/commands/SetClientData.d.ts +1 -0
  105. package/build/types/protocol/schemes/commands/SetPermissionOverwrites.d.ts +8 -0
  106. package/build/types/protocol/schemes/commands/SetSessionData.d.ts +17 -0
  107. package/build/types/protocol/schemes/commands/SetUserData.d.ts +6 -0
  108. package/build/types/protocol/schemes/commands/Unban.d.ts +3 -0
  109. package/build/types/protocol/schemes/commands/UnfollowTopic.d.ts +4 -0
  110. package/build/types/protocol/schemes/commands/Uninvite.d.ts +5 -0
  111. package/build/types/protocol/schemes/commands/Unreact.d.ts +6 -0
  112. package/build/types/protocol/schemes/commands/UpdateFollowedTopic.d.ts +6 -0
  113. package/build/types/protocol/schemes/commands/UpdateRole.d.ts +8 -0
  114. package/build/types/protocol/schemes/commands/UpdateRoom.d.ts +10 -0
  115. package/build/types/protocol/schemes/commands/UpdateRoomMember.d.ts +8 -0
  116. package/build/types/protocol/schemes/commands/UpdateSpace.d.ts +12 -0
  117. package/build/types/protocol/schemes/commands/UpdateSpaceMember.d.ts +6 -0
  118. package/build/types/protocol/schemes/commands/UpdateTopic.d.ts +5 -0
  119. package/build/types/protocol/schemes/events/AccessTicket.d.ts +14 -0
  120. package/build/types/protocol/schemes/events/Bans.d.ts +6 -0
  121. package/build/types/protocol/schemes/events/Bye.d.ts +4 -0
  122. package/build/types/protocol/schemes/events/ClientData.d.ts +1 -0
  123. package/build/types/protocol/schemes/events/ComputedPermissions.d.ts +9 -0
  124. package/build/types/protocol/schemes/events/DiscoverableSpaces.d.ts +4 -0
  125. package/build/types/protocol/schemes/events/EmoticonDeleted.d.ts +4 -0
  126. package/build/types/protocol/schemes/events/Emoticons.d.ts +6 -0
  127. package/build/types/protocol/schemes/events/EntitlementUsage.d.ts +11 -0
  128. package/build/types/protocol/schemes/events/Entitlements.d.ts +12 -0
  129. package/build/types/protocol/schemes/events/Error.d.ts +14 -0
  130. package/build/types/protocol/schemes/events/FollowedTopicUpdated.d.ts +4 -0
  131. package/build/types/protocol/schemes/events/FollowedTopics.d.ts +6 -0
  132. package/build/types/protocol/schemes/events/FoundMessages.d.ts +16 -0
  133. package/build/types/protocol/schemes/events/Invited.d.ts +10 -0
  134. package/build/types/protocol/schemes/events/Messages.d.ts +9 -0
  135. package/build/types/protocol/schemes/events/MessagesRedacted.d.ts +5 -0
  136. package/build/types/protocol/schemes/events/NewEmoticon.d.ts +4 -0
  137. package/build/types/protocol/schemes/events/NewMessage.d.ts +4 -0
  138. package/build/types/protocol/schemes/events/NewRelationship.d.ts +4 -0
  139. package/build/types/protocol/schemes/events/NewRole.d.ts +5 -0
  140. package/build/types/protocol/schemes/events/NewRoom.d.ts +5 -0
  141. package/build/types/protocol/schemes/events/NewTopic.d.ts +5 -0
  142. package/build/types/protocol/schemes/events/Ok.d.ts +2 -0
  143. package/build/types/protocol/schemes/events/Owners.d.ts +8 -0
  144. package/build/types/protocol/schemes/events/PermissionOverwriteTargets.d.ts +10 -0
  145. package/build/types/protocol/schemes/events/PermissionOverwrites.d.ts +8 -0
  146. package/build/types/protocol/schemes/events/PermissionOverwritesUpdated.d.ts +8 -0
  147. package/build/types/protocol/schemes/events/Pong.d.ts +2 -0
  148. package/build/types/protocol/schemes/events/Reacted.d.ts +9 -0
  149. package/build/types/protocol/schemes/events/ReactionDetails.d.ts +11 -0
  150. package/build/types/protocol/schemes/events/ReactionUpdated.d.ts +8 -0
  151. package/build/types/protocol/schemes/events/RelationshipDeleted.d.ts +4 -0
  152. package/build/types/protocol/schemes/events/Relationships.d.ts +4 -0
  153. package/build/types/protocol/schemes/events/RoleDeleted.d.ts +4 -0
  154. package/build/types/protocol/schemes/events/RoleUpdated.d.ts +5 -0
  155. package/build/types/protocol/schemes/events/RoomDeleted.d.ts +3 -0
  156. package/build/types/protocol/schemes/events/RoomJoined.d.ts +4 -0
  157. package/build/types/protocol/schemes/events/RoomLeft.d.ts +5 -0
  158. package/build/types/protocol/schemes/events/RoomMemberLeft.d.ts +4 -0
  159. package/build/types/protocol/schemes/events/RoomMemberUpdated.d.ts +6 -0
  160. package/build/types/protocol/schemes/events/RoomMembers.d.ts +5 -0
  161. package/build/types/protocol/schemes/events/RoomMembersJoined.d.ts +9 -0
  162. package/build/types/protocol/schemes/events/RoomSummary.d.ts +4 -0
  163. package/build/types/protocol/schemes/events/RoomSummaryUpdated.d.ts +8 -0
  164. package/build/types/protocol/schemes/events/RoomUpdated.d.ts +4 -0
  165. package/build/types/protocol/schemes/events/Session.d.ts +9 -0
  166. package/build/types/protocol/schemes/events/SpaceDeleted.d.ts +3 -0
  167. package/build/types/protocol/schemes/events/SpaceJoined.d.ts +4 -0
  168. package/build/types/protocol/schemes/events/SpaceLeft.d.ts +5 -0
  169. package/build/types/protocol/schemes/events/SpaceMemberJoined.d.ts +5 -0
  170. package/build/types/protocol/schemes/events/SpaceMemberLeft.d.ts +4 -0
  171. package/build/types/protocol/schemes/events/SpaceMemberUpdated.d.ts +6 -0
  172. package/build/types/protocol/schemes/events/SpaceMembers.d.ts +5 -0
  173. package/build/types/protocol/schemes/events/SpaceRooms.d.ts +5 -0
  174. package/build/types/protocol/schemes/events/SpaceSummary.d.ts +4 -0
  175. package/build/types/protocol/schemes/events/SpaceUpdated.d.ts +4 -0
  176. package/build/types/protocol/schemes/events/TopicDeleted.d.ts +4 -0
  177. package/build/types/protocol/schemes/events/TopicFollowed.d.ts +4 -0
  178. package/build/types/protocol/schemes/events/TopicUnfollowed.d.ts +4 -0
  179. package/build/types/protocol/schemes/events/TopicUpdated.d.ts +6 -0
  180. package/build/types/protocol/schemes/events/Topics.d.ts +6 -0
  181. package/build/types/protocol/schemes/events/UserInfo.d.ts +4 -0
  182. package/build/types/protocol/schemes/events/UserUpdated.d.ts +4 -0
  183. package/build/types/state-tracker/AsyncUtils.d.ts +15 -0
  184. package/build/types/state-tracker/ChatStateTracker.d.ts +41 -0
  185. package/build/types/state-tracker/EmoticonsManager.d.ts +15 -0
  186. package/build/types/state-tracker/FollowedTopicsManager.d.ts +85 -0
  187. package/build/types/state-tracker/MessagesManager.d.ts +27 -0
  188. package/build/types/state-tracker/PermissionsManager.d.ts +51 -0
  189. package/build/types/state-tracker/RelationshipsManager.d.ts +15 -0
  190. package/build/types/state-tracker/RoomMessagesHistory.d.ts +72 -0
  191. package/build/types/state-tracker/RoomsManager.d.ts +72 -0
  192. package/build/types/state-tracker/SpacesManager.d.ts +63 -0
  193. package/build/types/state-tracker/TopicHistoryWindow.d.ts +191 -0
  194. package/build/types/state-tracker/UsersManager.d.ts +23 -0
  195. package/build/types/state-tracker/functions.d.ts +6 -0
  196. package/package.json +67 -4
@@ -0,0 +1,3656 @@
1
+ /******/ (() => { // webpackBootstrap
2
+ /******/ "use strict";
3
+ /******/ // The require scope
4
+ /******/ var __webpack_require__ = {};
5
+ /******/
6
+ /************************************************************************/
7
+ /******/ /* webpack/runtime/define property getters */
8
+ /******/ (() => {
9
+ /******/ // define getter functions for harmony exports
10
+ /******/ __webpack_require__.d = (exports, definition) => {
11
+ /******/ for(var key in definition) {
12
+ /******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
13
+ /******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
14
+ /******/ }
15
+ /******/ }
16
+ /******/ };
17
+ /******/ })();
18
+ /******/
19
+ /******/ /* webpack/runtime/hasOwnProperty shorthand */
20
+ /******/ (() => {
21
+ /******/ __webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))
22
+ /******/ })();
23
+ /******/
24
+ /******/ /* webpack/runtime/make namespace object */
25
+ /******/ (() => {
26
+ /******/ // define __esModule on exports
27
+ /******/ __webpack_require__.r = (exports) => {
28
+ /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
29
+ /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
30
+ /******/ }
31
+ /******/ Object.defineProperty(exports, '__esModule', { value: true });
32
+ /******/ };
33
+ /******/ })();
34
+ /******/
35
+ /************************************************************************/
36
+ var __webpack_exports__ = {};
37
+ // ESM COMPAT FLAG
38
+ __webpack_require__.r(__webpack_exports__);
39
+
40
+ // EXPORTS
41
+ __webpack_require__.d(__webpack_exports__, {
42
+ AbstractRestClient: () => (/* reexport */ AbstractRestClient),
43
+ ErrorCode: () => (/* reexport */ ErrorCode),
44
+ FilesClient: () => (/* reexport */ FilesClient),
45
+ HistoryRotation: () => (/* reexport */ HistoryRotation),
46
+ IndexedCollection: () => (/* reexport */ IndexedCollection),
47
+ IndexedObjectCollection: () => (/* reexport */ IndexedObjectCollection),
48
+ Layer: () => (/* reexport */ Layer),
49
+ NO_LIMIT: () => (/* reexport */ NO_LIMIT),
50
+ ObservableIndexedCollection: () => (/* reexport */ ObservableIndexedCollection),
51
+ ObservableIndexedObjectCollection: () => (/* reexport */ ObservableIndexedObjectCollection),
52
+ PermissionDefinition: () => (/* reexport */ PermissionDefinition),
53
+ Permissions: () => (/* reexport */ Permissions),
54
+ RoleFlag: () => (/* reexport */ RoleFlag),
55
+ STORAGE_UNIT_BYTES: () => (/* reexport */ STORAGE_UNIT_BYTES),
56
+ SearchRange: () => (/* reexport */ SearchRange),
57
+ SpaceFeature: () => (/* reexport */ SpaceFeature),
58
+ SpaceIntent: () => (/* reexport */ SpaceIntent),
59
+ UiPurpose: () => (/* reexport */ UiPurpose),
60
+ UserFeature: () => (/* reexport */ UserFeature),
61
+ UserStatus: () => (/* reexport */ UserStatus),
62
+ WebApiChatClient: () => (/* reexport */ WebApiChatClient),
63
+ WebSocketChatClient: () => (/* reexport */ WebSocketChatClient),
64
+ extractUserFromMember: () => (/* reexport */ extractUserFromMember)
65
+ });
66
+
67
+ ;// ./src/EventTarget.ts
68
+ class EventTarget {
69
+ events = new Map();
70
+ onceEvents = new Map();
71
+ on(eventName, handler) {
72
+ this.addHandler(this.events, eventName, handler);
73
+ return this;
74
+ }
75
+ once(eventName, handler) {
76
+ this.addHandler(this.onceEvents, eventName, handler);
77
+ return this;
78
+ }
79
+ off(eventName, handler) {
80
+ this.removeHandler(this.events, eventName, handler);
81
+ this.removeHandler(this.onceEvents, eventName, handler);
82
+ return this;
83
+ }
84
+ emit(eventName, event) {
85
+ this.callHandlers(this.events, eventName, event);
86
+ this.callHandlers(this.onceEvents, eventName, event);
87
+ this.onceEvents.delete(eventName);
88
+ return this;
89
+ }
90
+ addHandler(map, eventName, handler) {
91
+ const handlers = map.get(eventName) ?? [];
92
+ handlers.push(handler);
93
+ map.set(eventName, handlers);
94
+ }
95
+ removeHandler(map, eventName, handler) {
96
+ const handlers = map.get(eventName);
97
+ const index = handlers?.indexOf(handler) ?? -1;
98
+ if (index >= 0) {
99
+ handlers.splice(index, 1);
100
+ }
101
+ }
102
+ callHandlers(map, eventName, event) {
103
+ map.get(eventName)?.forEach(callback => callback(event));
104
+ }
105
+ }
106
+ ;// ./src/AbstractChatClient.ts
107
+
108
+ class AbstractChatClient extends EventTarget {
109
+ awaitingResponse = new Map();
110
+ sentCounter = 0;
111
+ createEnvelope(type, data) {
112
+ return {
113
+ type,
114
+ data,
115
+ ref: (++this.sentCounter).toString()
116
+ };
117
+ }
118
+ createPromiseFromCommandEnvelope(envelope) {
119
+ return new Promise((...args) => this.awaitingResponse.set(envelope.ref, args));
120
+ }
121
+ handleIncomingEnvelope(envelope) {
122
+ if (!this.awaitingResponse.has(envelope.ref)) {
123
+ return;
124
+ }
125
+ const isError = envelope.type === 'Error';
126
+ this.awaitingResponse.get(envelope.ref)[0]({
127
+ data: isError ? null : envelope.data,
128
+ error: isError ? envelope.data : null
129
+ });
130
+ this.awaitingResponse.delete(envelope.ref);
131
+ }
132
+ handleEnvelopeSendError(envelope, error) {
133
+ if (!this.awaitingResponse.has(envelope.ref)) {
134
+ return;
135
+ }
136
+ this.awaitingResponse.get(envelope.ref)[1](error);
137
+ this.awaitingResponse.delete(envelope.ref);
138
+ }
139
+
140
+ /**
141
+ * Reject every command that is still waiting for a response.
142
+ * Call this whenever the transport can no longer deliver an answer (the
143
+ * connection dropped).
144
+ */
145
+ failAwaitingResponses(error) {
146
+ if (!this.awaitingResponse.size) {
147
+ return;
148
+ }
149
+ const pending = Array.from(this.awaitingResponse.values());
150
+ this.awaitingResponse.clear();
151
+ for (const [, reject] of pending) {
152
+ reject(error);
153
+ }
154
+ }
155
+ }
156
+
157
+ /**
158
+ * The answer to a command: either `data` or the server `error`, never both.
159
+ * Check `error` first and TypeScript knows `data` is there.
160
+ */
161
+
162
+ /**
163
+ * Map of incoming events.
164
+ */
165
+
166
+ /**
167
+ * Map of commands and their corresponding events.
168
+ */
169
+ ;// ./src/IndexedObjectCollection.ts
170
+
171
+ class IndexedCollection {
172
+ _items = new Map();
173
+ constructor(items = []) {
174
+ this.set(...items);
175
+ }
176
+ get items() {
177
+ return this._items;
178
+ }
179
+ get length() {
180
+ return this._items.size;
181
+ }
182
+ set(...items) {
183
+ for (const item of items) {
184
+ this._items.set(item[0], item[1]);
185
+ }
186
+ }
187
+ get(id) {
188
+ return this.items.get(id);
189
+ }
190
+ has(id) {
191
+ return this.items.has(id);
192
+ }
193
+ delete(...ids) {
194
+ for (const id of ids) {
195
+ this.items.delete(id);
196
+ }
197
+ }
198
+ deleteAll() {
199
+ this.items.clear();
200
+ }
201
+ findBy(field, valueToFind, limit = Infinity) {
202
+ const result = new IndexedCollection();
203
+ for (const [key, value] of this.items.entries()) {
204
+ if (result.length >= limit) {
205
+ break;
206
+ }
207
+ if (value[field] === valueToFind) {
208
+ result.set([key, value]);
209
+ }
210
+ }
211
+ return result;
212
+ }
213
+ createMirror() {
214
+ const copy = new IndexedCollection();
215
+ copy._items = this._items;
216
+ return copy;
217
+ }
218
+ }
219
+ class IndexedObjectCollection {
220
+ _items;
221
+ constructor(id, items = []) {
222
+ this.id = id;
223
+ this._items = new IndexedCollection();
224
+ this.set(...items);
225
+ }
226
+ get items() {
227
+ return Array.from(this._items.items.values());
228
+ }
229
+ get length() {
230
+ return this._items.length;
231
+ }
232
+ set(...items) {
233
+ this._items.set(...items.map(item => [this.getId(item), item]));
234
+ }
235
+ get(id) {
236
+ return this._items.get(id);
237
+ }
238
+ getAt(index) {
239
+ if (index < 0 || index >= this.length) {
240
+ return undefined;
241
+ }
242
+ let current = 0;
243
+ for (const item of this._items.items.values()) {
244
+ if (current++ === index) {
245
+ return item;
246
+ }
247
+ }
248
+ return undefined;
249
+ }
250
+ has(id) {
251
+ return this._items.has(id);
252
+ }
253
+ delete(...ids) {
254
+ this._items.delete(...ids);
255
+ }
256
+ deleteAll() {
257
+ this._items.deleteAll();
258
+ }
259
+ findBy(field, valueToFind, limit = null) {
260
+ const result = new IndexedObjectCollection(this.id);
261
+ for (const value of this.items) {
262
+ if (limit && result.length === limit) {
263
+ break;
264
+ }
265
+ if (value[field] === valueToFind) {
266
+ result.set(value);
267
+ }
268
+ }
269
+ return result;
270
+ }
271
+ createMirror() {
272
+ const copy = new IndexedObjectCollection(this.id);
273
+ copy._items = this._items;
274
+ return copy;
275
+ }
276
+ getId(item) {
277
+ return typeof this.id === 'function' ? this.id(item) : item[this.id];
278
+ }
279
+ }
280
+ class ObservableIndexedCollection extends IndexedCollection {
281
+ eventTarget;
282
+ constructor(items = []) {
283
+ super();
284
+ this.eventTarget = new EventTarget();
285
+ this.set(...items);
286
+ }
287
+ set(...items) {
288
+ if (items.length) {
289
+ super.set(...items);
290
+ this.eventTarget.emit('change', {
291
+ setItems: items.map(item => item[0])
292
+ });
293
+ }
294
+ }
295
+ delete(...ids) {
296
+ if (ids.length) {
297
+ super.delete(...ids);
298
+ this.eventTarget.emit('change', {
299
+ deletedItems: ids
300
+ });
301
+ }
302
+ }
303
+ deleteAll() {
304
+ if (this.length) {
305
+ const ids = Array.from(this._items.keys());
306
+ super.deleteAll();
307
+ this.eventTarget.emit('change', {
308
+ deletedItems: Array.from(ids)
309
+ });
310
+ }
311
+ }
312
+ createMirror() {
313
+ const copy = new ObservableIndexedCollection();
314
+ copy.eventTarget = this.eventTarget;
315
+ copy._items = this._items;
316
+ return copy;
317
+ }
318
+ on(eventName, handler) {
319
+ this.eventTarget.on(eventName, handler);
320
+ return this;
321
+ }
322
+ once(eventName, handler) {
323
+ this.eventTarget.once(eventName, handler);
324
+ return this;
325
+ }
326
+ off(eventName, handler) {
327
+ this.eventTarget.off(eventName, handler);
328
+ return this;
329
+ }
330
+ }
331
+ class ObservableIndexedObjectCollection extends IndexedObjectCollection {
332
+ eventTarget;
333
+ constructor(id, items = []) {
334
+ super(id);
335
+ this.eventTarget = new EventTarget();
336
+ this.set(...items);
337
+ }
338
+ set(...items) {
339
+ if (items.length) {
340
+ super.set(...items);
341
+ this.eventTarget.emit('change', {
342
+ setItems: items.map(item => this.getId(item))
343
+ });
344
+ }
345
+ }
346
+ delete(...ids) {
347
+ if (ids.length) {
348
+ super.delete(...ids);
349
+ this.eventTarget.emit('change', {
350
+ deletedItems: ids
351
+ });
352
+ }
353
+ }
354
+ deleteAll() {
355
+ if (this.length) {
356
+ const ids = this.items.map(item => this.getId(item));
357
+ super.deleteAll();
358
+ this.eventTarget.emit('change', {
359
+ deletedItems: ids
360
+ });
361
+ }
362
+ }
363
+
364
+ /**
365
+ * Bring the collection to exactly match the provided items: upsert every
366
+ * provided item and remove any existing item whose id is not present in the
367
+ * provided set. Emits at most a single `change` event describing both the
368
+ * set and the deleted ids, so bound consumers can update in place without
369
+ * ever observing an intermediate empty state (unlike deleteAll + set).
370
+ */
371
+ reconcile(...items) {
372
+ const incomingIds = new Set(items.map(item => this.getId(item)));
373
+ const deletedItems = [];
374
+ for (const existing of this.items) {
375
+ const id = this.getId(existing);
376
+ if (!incomingIds.has(id)) {
377
+ deletedItems.push(id);
378
+ }
379
+ }
380
+ if (!items.length && !deletedItems.length) {
381
+ return;
382
+ }
383
+ this._items.delete(...deletedItems);
384
+ super.set(...items);
385
+ this.eventTarget.emit('change', {
386
+ setItems: items.map(item => this.getId(item)),
387
+ deletedItems
388
+ });
389
+ }
390
+ createMirror() {
391
+ const copy = new ObservableIndexedObjectCollection(this.id);
392
+ copy.eventTarget = this.eventTarget;
393
+ copy._items = this._items;
394
+ return copy;
395
+ }
396
+ on(eventName, handler) {
397
+ this.eventTarget.on(eventName, handler);
398
+ return this;
399
+ }
400
+ once(eventName, handler) {
401
+ this.eventTarget.once(eventName, handler);
402
+ return this;
403
+ }
404
+ off(eventName, handler) {
405
+ this.eventTarget.off(eventName, handler);
406
+ return this;
407
+ }
408
+ }
409
+ ;// ./src/state-tracker/AsyncUtils.ts
410
+
411
+ class DeferredTask {
412
+ promise;
413
+ resolve;
414
+ constructor() {
415
+ this.promise = new Promise(resolve => this.resolve = resolve);
416
+ }
417
+ }
418
+ class PromiseRegistry {
419
+ promises = new IndexedCollection();
420
+ register(promise, key) {
421
+ this.promises.set([key, promise]);
422
+ promise.catch(() => {
423
+ if (this.promises.get(key) === promise) {
424
+ this.promises.delete(key);
425
+ }
426
+ });
427
+ }
428
+ registerByFunction(fn, key) {
429
+ this.register(fn(), key);
430
+ }
431
+ get(key) {
432
+ return this.promises.get(key);
433
+ }
434
+ has(key) {
435
+ return this.promises.has(key);
436
+ }
437
+ notExist(key) {
438
+ return !this.has(key);
439
+ }
440
+ forget(...keys) {
441
+ this.promises.delete(...keys);
442
+ }
443
+ forgetAll() {
444
+ this.promises.deleteAll();
445
+ }
446
+ }
447
+ ;// ./src/state-tracker/TopicHistoryWindow.ts
448
+
449
+ let WindowState = /*#__PURE__*/function (WindowState) {
450
+ /**
451
+ * The latest messages (those received live) are available in the history window, history has not been fetched.
452
+ */
453
+ WindowState[WindowState["LIVE"] = 0] = "LIVE";
454
+ /**
455
+ * The latest messages has been fetched and are available in the history window.
456
+ */
457
+ WindowState[WindowState["LATEST"] = 1] = "LATEST";
458
+ /**
459
+ * The historical messages have been fetched and are available in the history window.
460
+ * Latest messages are not available and will not be available.
461
+ */
462
+ WindowState[WindowState["PAST"] = 2] = "PAST";
463
+ /**
464
+ * The oldest messages have been fetched and are available in the history window.
465
+ * Next attempts to fetch previous messages will result with no-op.
466
+ */
467
+ WindowState[WindowState["OLDEST"] = 3] = "OLDEST";
468
+ return WindowState;
469
+ }({});
470
+ class TraversableRemoteCollection extends ObservableIndexedObjectCollection {
471
+ /**
472
+ * Current mode od collection window. To change mode, call one of available fetch methods.
473
+ */
474
+ get state() {
475
+ return this.internalState.current;
476
+ }
477
+ internalState = {
478
+ current: WindowState.LIVE,
479
+ ongoing: undefined,
480
+ limit: 1000,
481
+ retainRatio: 1,
482
+ fetchLimit: 50,
483
+ lastFetchCount: 0,
484
+ oldestId: null
485
+ };
486
+
487
+ /**
488
+ * Number of items to fetch per request.
489
+ */
490
+ get fetchLimit() {
491
+ return this.internalState.fetchLimit;
492
+ }
493
+
494
+ /**
495
+ * Sets number of items to fetch per request.
496
+ */
497
+ set fetchLimit(value) {
498
+ this.internalState.fetchLimit = value;
499
+ }
500
+
501
+ /**
502
+ * Maximum number of items stored in window (High Watermark).
503
+ * Null for unlimited.
504
+ */
505
+ get limit() {
506
+ return this.internalState.limit;
507
+ }
508
+
509
+ /**
510
+ * Maximum number of items stored in window (High Watermark).
511
+ * Null for unlimited. Lowering it below the current length drops the oldest items right away.
512
+ */
513
+ set limit(value) {
514
+ this.internalState.limit = value;
515
+ const deletedItems = this.trimHead(value);
516
+ if (deletedItems.length) {
517
+ this.eventTarget.emit('change', {
518
+ deletedItems
519
+ });
520
+ }
521
+ }
522
+
523
+ /**
524
+ * Percentage of limit to keep when trimming.
525
+ */
526
+ get retainRatio() {
527
+ return this.internalState.retainRatio;
528
+ }
529
+
530
+ /**
531
+ * Percentage of limit to keep when trimming.
532
+ */
533
+ set retainRatio(value) {
534
+ this.internalState.retainRatio = value;
535
+ }
536
+ get hasLatest() {
537
+ return [WindowState.LATEST, WindowState.LIVE].includes(this.state);
538
+ }
539
+ get hasOldest() {
540
+ return this.state === WindowState.OLDEST || this.state === WindowState.LATEST && this.length < this.fetchLimit || this.internalState.oldestId !== null && this.has(this.internalState.oldestId);
541
+ }
542
+ async resetToLatest(force = false) {
543
+ if (this.internalState.ongoing || !force && this.internalState.current === WindowState.LATEST) {
544
+ return;
545
+ }
546
+ let result;
547
+ const originalState = this.state;
548
+ this.internalState.ongoing = WindowState.LATEST;
549
+ try {
550
+ result = await this.fetchLatestItems();
551
+ this.internalState.lastFetchCount = result.length;
552
+ } finally {
553
+ this.internalState.ongoing = undefined;
554
+ }
555
+ this._items.deleteAll(); // Directly call deleteAll to prevent event emit.
556
+ this.addItems(result, 'tail');
557
+ this.internalState.current = WindowState.LATEST;
558
+ this.emitChangeWithDiff(true, originalState);
559
+ }
560
+ async fetchPrevious() {
561
+ if (this.internalState.ongoing || this.hasOldest) {
562
+ return;
563
+ }
564
+ let result;
565
+ const originalState = this.state;
566
+ this.internalState.ongoing = WindowState.PAST;
567
+ try {
568
+ result = await this.fetchItemsBefore();
569
+ this.internalState.lastFetchCount = result ? result.length : 0;
570
+ } finally {
571
+ this.internalState.ongoing = undefined;
572
+ }
573
+ if (!result) {
574
+ return this.resetToLatest();
575
+ }
576
+ if (!result.length) {
577
+ const firstItem = this.getAt(0);
578
+ this.internalState.oldestId = firstItem ? this.getId(firstItem) : null;
579
+ await this.refreshFetchedState();
580
+
581
+ // LATEST state has priority over OLDEST
582
+ if (this.internalState.current === WindowState.PAST) {
583
+ this.internalState.current = WindowState.OLDEST;
584
+ }
585
+ this.emitChangeWithDiff(false, originalState);
586
+ return;
587
+ }
588
+ this.addItems(result, 'head');
589
+ await this.refreshFetchedState();
590
+ this.emitChangeWithDiff(true, originalState);
591
+ }
592
+ async fetchNext() {
593
+ if (this.hasLatest) {
594
+ return;
595
+ }
596
+ return this.fetchAfterLast();
597
+ }
598
+
599
+ /**
600
+ * Append the items that follow the last one in the window; an empty window gets the latest items.
601
+ */
602
+ async fetchAfterLast() {
603
+ if (this.internalState.ongoing) {
604
+ return;
605
+ }
606
+ let result;
607
+ const originalState = this.state;
608
+ this.internalState.ongoing = WindowState.PAST;
609
+ try {
610
+ result = await this.fetchItemsAfter();
611
+ this.internalState.lastFetchCount = result ? result.length : 0;
612
+ } finally {
613
+ this.internalState.ongoing = undefined;
614
+ }
615
+ if (!result) {
616
+ await this.resetToLatest(true);
617
+ return;
618
+ }
619
+ if (result.length) {
620
+ this.addItems(result, 'tail');
621
+ await this.refreshFetchedState();
622
+ this.emitChangeWithDiff(true, originalState);
623
+ return;
624
+ }
625
+ }
626
+ async jumpTo(id) {
627
+ if (this.internalState.ongoing || this.state !== WindowState.LIVE && this._items.has(id)) {
628
+ return;
629
+ }
630
+ let result;
631
+ const originalState = this.state;
632
+ this.internalState.ongoing = WindowState.PAST;
633
+ try {
634
+ result = await this.fetchItemsAround(id);
635
+ this.internalState.lastFetchCount = result ? result.length : 0;
636
+ if (result) {
637
+ this._items.deleteAll(); // Directly call deleteAll to prevent event emit.
638
+ this.addItems(result, 'tail');
639
+ await this.refreshFetchedState();
640
+ }
641
+ } finally {
642
+ this.internalState.ongoing = undefined;
643
+ }
644
+ this.emitChangeWithDiff(!!result, originalState);
645
+ }
646
+ async refreshFetchedState() {
647
+ this.internalState.current = (await this.isLatestItemLoaded()) ? WindowState.LATEST : WindowState.PAST;
648
+ }
649
+
650
+ /**
651
+ * Add items without emitting an event, trimming the window from the opposite end using the
652
+ * High/Low Watermark strategy. An item already in the window keeps its position.
653
+ * @return Ids of the items trimmed out.
654
+ */
655
+ addItems(newItems, to, highWatermark = this.limit) {
656
+ const entries = newItems.map(item => [this.getId(item), item]);
657
+ if (to === 'tail') {
658
+ this._items.set(...entries);
659
+ return this.trimHead(this.getLowWatermark(highWatermark));
660
+ }
661
+
662
+ // Prepending has to rebuild the map; a duplicate keeps the already loaded version of the item.
663
+ const loaded = Array.from(this._items.items);
664
+ this._items.deleteAll();
665
+ this._items.set(...entries, ...loaded);
666
+ return this.trimTail(this.getLowWatermark(highWatermark));
667
+ }
668
+ emitChangeWithDiff(itemChanged, originalState) {
669
+ if (itemChanged || originalState !== this.state) {
670
+ this.eventTarget.emit('change', {
671
+ setItems: Array.from(this._items.items.keys())
672
+ });
673
+ }
674
+ }
675
+
676
+ /**
677
+ * Drop the oldest items, so that at most `keep` remain. The newest items stay, so whether the window holds the
678
+ * latest ones does not change - but the oldest it held are gone.
679
+ * @return Ids of the dropped items.
680
+ */
681
+ trimHead(keep) {
682
+ if (keep === null || this._items.length <= keep) {
683
+ return [];
684
+ }
685
+ const deletedItems = [];
686
+ const deleteCount = this._items.length - keep;
687
+ for (const id of this._items.items.keys()) {
688
+ if (deletedItems.length === deleteCount) {
689
+ break;
690
+ }
691
+ deletedItems.push(id);
692
+ }
693
+ this._items.delete(...deletedItems);
694
+ if (this.internalState.current === WindowState.OLDEST) {
695
+ this.internalState.current = WindowState.PAST;
696
+ }
697
+ return deletedItems;
698
+ }
699
+ trimTail(keep) {
700
+ if (keep === null || this._items.length <= keep) {
701
+ return [];
702
+ }
703
+ const deletedItems = Array.from(this._items.items.keys()).slice(keep);
704
+ this._items.delete(...deletedItems);
705
+ return deletedItems;
706
+ }
707
+
708
+ /**
709
+ * Number of items left after trimming a window that went over the given High Watermark.
710
+ */
711
+ getLowWatermark(highWatermark) {
712
+ if (highWatermark === null || this._items.length <= highWatermark) {
713
+ return null;
714
+ }
715
+ return Math.floor(highWatermark * this.internalState.retainRatio);
716
+ }
717
+ }
718
+ class TopicHistoryWindow extends TraversableRemoteCollection {
719
+ /**
720
+ * Reexported available window modes enum.
721
+ */
722
+ WindowState = WindowState;
723
+ /**
724
+ * The window does not subscribe to the client itself - the messages manager routes the events of its topic to it.
725
+ */
726
+ constructor(roomId, topicId, tracker, preview = false) {
727
+ super('id');
728
+ this.roomId = roomId;
729
+ this.topicId = topicId;
730
+ this.tracker = tracker;
731
+ this.preview = preview;
732
+ this.internalState.traverseLock = false;
733
+ this.internalState.includeMyReactions = !preview;
734
+ this.internalState.myReactions = {};
735
+ this.internalState.liveLimit = 50;
736
+ }
737
+ createMirror() {
738
+ const copy = new TopicHistoryWindow(this.roomId, this.topicId, this.tracker, this.preview);
739
+ copy.eventTarget = this.eventTarget;
740
+ copy._items = this._items;
741
+ copy.internalState = this.internalState;
742
+ return copy;
743
+ }
744
+
745
+ /**
746
+ * Window of a room you have not joined. It gets no live messages - at the latest ones fetchNext() fetches the newer.
747
+ */
748
+ get isPreview() {
749
+ return this.preview;
750
+ }
751
+ get isTraverseLocked() {
752
+ return this.internalState.traverseLock;
753
+ }
754
+
755
+ /**
756
+ * What the connected user has reacted with, keyed by message id. Kept apart from
757
+ * the messages, so the history itself is identical for every user.
758
+ */
759
+ get myReactions() {
760
+ return this.internalState.myReactions;
761
+ }
762
+
763
+ /**
764
+ * Whether the history is fetched together with the reactions of the connected
765
+ * user. Turn it off only where the active state of a reaction is never rendered.
766
+ */
767
+ get includeMyReactions() {
768
+ return this.internalState.includeMyReactions;
769
+ }
770
+ set includeMyReactions(value) {
771
+ this.internalState.includeMyReactions = value;
772
+ }
773
+
774
+ /**
775
+ * Maximum number of items a window that has not been fetched yet (LIVE state) collects from the incoming
776
+ * messages. Null for the same as {@link limit}. It keeps the windows of topics nobody looks at small;
777
+ * the windows of ephemeral topics are exempt, as the live messages are all the history they have.
778
+ */
779
+ get liveLimit() {
780
+ return this.internalState.liveLimit;
781
+ }
782
+ set liveLimit(value) {
783
+ this.internalState.liveLimit = value;
784
+ }
785
+ async setTraverseLock(lock) {
786
+ this.internalState.traverseLock = lock;
787
+ if (lock && this.state !== WindowState.LIVE && this.state !== WindowState.LATEST) {
788
+ await super.resetToLatest();
789
+ }
790
+ }
791
+ async resetToLatest(force = false) {
792
+ if (this.internalState.traverseLock) {
793
+ return;
794
+ }
795
+ return super.resetToLatest(force);
796
+ }
797
+ async fetchNext() {
798
+ if (this.internalState.traverseLock) {
799
+ return;
800
+ }
801
+ if (this.preview && this.hasLatest) {
802
+ return this.fetchAfterLast(); // No events reach a preview
803
+ }
804
+ return super.fetchNext();
805
+ }
806
+ async fetchPrevious() {
807
+ if (this.internalState.traverseLock) {
808
+ return;
809
+ }
810
+ return super.fetchPrevious();
811
+ }
812
+ async jumpTo(id) {
813
+ if (this.internalState.traverseLock) {
814
+ return;
815
+ }
816
+ return super.jumpTo(id);
817
+ }
818
+
819
+ /**
820
+ * For internal use.
821
+ * @internal
822
+ */
823
+ _updateMessageReference(refTopic) {
824
+ const refMessage = this.get(refTopic.refMessage.id);
825
+ if (refMessage) {
826
+ // Update referenced topic ID in message
827
+ this.set({
828
+ ...refMessage,
829
+ topicRef: refTopic.id
830
+ });
831
+ }
832
+ }
833
+ async fetchItemsAfter() {
834
+ const afterId = this.getAt(this.length - 1)?.id;
835
+
836
+ // If there is no message to refer, fetch latest
837
+ return afterId ? this.fetchMessages({
838
+ after: afterId
839
+ }) : null;
840
+ }
841
+ async fetchItemsAround(id) {
842
+ return this.fetchMessages({
843
+ around: id
844
+ });
845
+ }
846
+ async fetchItemsBefore() {
847
+ const beforeId = this.getAt(0)?.id;
848
+
849
+ // If there is no message to refer, fetch latest
850
+ return beforeId ? this.fetchMessages({
851
+ before: beforeId
852
+ }) : null;
853
+ }
854
+ async fetchLatestItems() {
855
+ return this.fetchMessages({});
856
+ }
857
+ async fetchMessages(criteria) {
858
+ const result = await this.tracker.client.send('GetMessages', {
859
+ location: {
860
+ roomId: this.roomId,
861
+ topicId: this.topicId
862
+ },
863
+ limit: this.internalState.fetchLimit,
864
+ includeMyReactions: this.internalState.includeMyReactions,
865
+ ...criteria
866
+ });
867
+ if (result.error) {
868
+ throw new Error(`Cannot fetch messages: ${result.error.message}`);
869
+ }
870
+ this.storeMyReactions(result.data.messages, result.data.myReactions);
871
+ return result.data.messages;
872
+ }
873
+
874
+ /**
875
+ * The response is the truth for every message it covers, so a message it does not
876
+ * mention has no reaction of this user left on it.
877
+ */
878
+ storeMyReactions(messages, myReactions) {
879
+ if (!this.internalState.includeMyReactions) {
880
+ return;
881
+ }
882
+ const next = {
883
+ ...this.internalState.myReactions
884
+ };
885
+ for (const message of messages) {
886
+ const own = myReactions?.[message.id];
887
+ if (own?.length) {
888
+ next[message.id] = own;
889
+ } else {
890
+ delete next[message.id];
891
+ }
892
+ }
893
+ this.internalState.myReactions = next;
894
+ }
895
+ async getTopic() {
896
+ if (this.preview) {
897
+ // The tracker holds the topics of the joined rooms only
898
+ const result = await this.tracker.client.send('GetTopics', {
899
+ roomId: this.roomId,
900
+ topicIds: [this.topicId]
901
+ });
902
+ if (result.error) {
903
+ throw new Error(`Cannot fetch topic: ${result.error.message}`);
904
+ }
905
+ return result.data.topics.find(topic => topic.id === this.topicId);
906
+ }
907
+ return (await this.tracker.rooms.getTopics(this.roomId, [this.topicId])).get(this.topicId);
908
+ }
909
+ async getLatestMessageId() {
910
+ return (await this.getTopic())?.lastMessage?.id;
911
+ }
912
+ async isLatestItemLoaded() {
913
+ const lastMessageId = await this.getLatestMessageId();
914
+ return lastMessageId ? this.has(lastMessageId) : true;
915
+ }
916
+
917
+ /**
918
+ * For internal use.
919
+ * @internal
920
+ */
921
+ _handleNewMessage(ev) {
922
+ if (!this.hasLatest) {
923
+ return;
924
+ }
925
+ const limit = this.state === WindowState.LIVE && !this.internalState.traverseLock ? this.internalState.liveLimit ?? this.limit : this.limit;
926
+ const deletedItems = this.addItems([ev.message], 'tail', limit);
927
+ this.eventTarget.emit('change', deletedItems.length ? {
928
+ setItems: [ev.message.id],
929
+ deletedItems
930
+ } : {
931
+ setItems: [ev.message.id]
932
+ });
933
+ }
934
+
935
+ /**
936
+ * The counter arrives as the global source of truth - only it is overwritten, and
937
+ * a reaction nobody holds any more (count 0) leaves the message.
938
+ * For internal use.
939
+ * @internal
940
+ */
941
+ _handleReactionUpdated(ev) {
942
+ const message = this.get(ev.messageId);
943
+ if (!message) {
944
+ return;
945
+ }
946
+ const index = message.reactions.findIndex(reaction => reaction.type === ev.reaction.type && reaction.value === ev.reaction.value);
947
+ if (index === -1 && !ev.reaction.count) {
948
+ return;
949
+ }
950
+ const reactions = [...message.reactions];
951
+ if (index === -1) {
952
+ reactions.push(ev.reaction);
953
+ } else if (ev.reaction.count) {
954
+ reactions[index] = ev.reaction; // In place - a pill must not jump around as its counter moves
955
+ } else {
956
+ reactions.splice(index, 1);
957
+ }
958
+ this.set({
959
+ ...message,
960
+ reactions
961
+ });
962
+ }
963
+
964
+ /**
965
+ * For internal use.
966
+ * @internal
967
+ */
968
+ _handleReacted(ev) {
969
+ if (!this.has(ev.messageId)) {
970
+ return;
971
+ }
972
+ const {
973
+ type,
974
+ value,
975
+ isAdded
976
+ } = ev.reaction;
977
+ const own = (this.internalState.myReactions[ev.messageId] ?? []).filter(reaction => reaction.type !== type || reaction.value !== value);
978
+ if (isAdded) {
979
+ own.push({
980
+ type,
981
+ value
982
+ });
983
+ }
984
+ const {
985
+ [ev.messageId]: _previous,
986
+ ...myReactions
987
+ } = this.internalState.myReactions;
988
+ if (own.length) {
989
+ myReactions[ev.messageId] = own;
990
+ }
991
+ this.internalState.myReactions = myReactions;
992
+ this.eventTarget.emit('change', {
993
+ setItems: [ev.messageId]
994
+ });
995
+ }
996
+
997
+ /**
998
+ * For internal use.
999
+ * @internal
1000
+ */
1001
+ async _handleMessagesRedacted(ev) {
1002
+ const refTopicIds = this.items.filter(msg => msg.topicRef && ev.ids.includes(msg.id)).map(msg => msg.topicRef);
1003
+ this.delete(...ev.ids);
1004
+ if (this.length === 0) {
1005
+ await this.resetToLatest();
1006
+ }
1007
+ if (refTopicIds.length > 0) {
1008
+ this.eventTarget.emit('reftopicsdeleted', refTopicIds);
1009
+ }
1010
+ }
1011
+ }
1012
+ ;// ./src/state-tracker/RoomMessagesHistory.ts
1013
+
1014
+
1015
+
1016
+ /**
1017
+ * Does not subscribe to the client itself - the messages manager routes the events of its room to it, so a history
1018
+ * dropped together with its room stops receiving them.
1019
+ */
1020
+ class RoomMessagesHistory {
1021
+ isPreview;
1022
+ roomId;
1023
+ historyWindows = new IndexedCollection();
1024
+ traverseLock = false;
1025
+ room;
1026
+ constructor(room, tracker) {
1027
+ this.tracker = tracker;
1028
+ this.roomId = typeof room === 'string' ? room : room.id;
1029
+ this.room = typeof room === 'string' ? null : room;
1030
+ this.isPreview = this.room === null;
1031
+ if (this.room) {
1032
+ this.updateTraverseLock(this.room);
1033
+ }
1034
+ if (this.room?.defaultTopic) {
1035
+ this.createHistoryWindowForTopic(this.room.defaultTopic);
1036
+ }
1037
+ }
1038
+
1039
+ /**
1040
+ * Returns a history window object for the given topic ID, allowing you to view message history.
1041
+ * @param topicId
1042
+ * @param peek If true, do not create a cache for this topic and do not allow it to collect new messages.
1043
+ */
1044
+ async getMessagesWindow(topicId, peek = false) {
1045
+ if (!this.historyWindows.has(topicId) && !peek) {
1046
+ if (this.isPreview) {
1047
+ this.createHistoryWindow(topicId);
1048
+ } else {
1049
+ const topic = (await this.tracker.rooms.getTopics(this.roomId, [topicId])).get(topicId);
1050
+ if (topic) {
1051
+ this.createHistoryWindowForTopic(topic);
1052
+ }
1053
+ }
1054
+ }
1055
+ return this.historyWindows.get(topicId);
1056
+ }
1057
+
1058
+ /**
1059
+ * Re-synchronise this room's history after a reconnect without discarding
1060
+ * the existing window objects (which would blank the UI and, for ephemeral
1061
+ * rooms, permanently drop live-only history).
1062
+ *
1063
+ * The window bindings are preserved; only windows that the application had
1064
+ * actually pulled to the latest page (state === LATEST) are refreshed, with
1065
+ * a single resetToLatest instead of a chain of catch-up requests. Windows
1066
+ * that were never pulled (LIVE) or belong to an ephemeral room are left
1067
+ * untouched so their in-memory context survives the reconnect.
1068
+ */
1069
+ async resync(room) {
1070
+ this.room = room;
1071
+ this.updateTraverseLock(room);
1072
+ if (this.room.defaultTopic) {
1073
+ this.createHistoryWindowForTopic(this.room.defaultTopic);
1074
+ }
1075
+ for (const [, window] of Array.from(this.historyWindows.items)) {
1076
+ try {
1077
+ await window.setTraverseLock(this.traverseLock);
1078
+
1079
+ // Ephemeral history lives only in memory (the server does not
1080
+ // persist it), so never refetch/replace it on reconnect.
1081
+ if (this.traverseLock) {
1082
+ continue;
1083
+ }
1084
+ if (window.state === WindowState.LATEST) {
1085
+ await window.resetToLatest(true);
1086
+ }
1087
+ } catch (_e) {
1088
+ // Best effort: the connection can drop again mid-resync. The
1089
+ // window keeps its current content and stays usable, so the
1090
+ // application can refresh it on demand.
1091
+ }
1092
+ }
1093
+ }
1094
+
1095
+ /**
1096
+ * For internal use.
1097
+ * @internal
1098
+ */
1099
+ async _handleRoomUpdated(ev) {
1100
+ this.room = ev.room;
1101
+ this.updateTraverseLock(ev.room);
1102
+ if (ev.room.defaultTopic) {
1103
+ this.createHistoryWindowForTopic(ev.room.defaultTopic);
1104
+ }
1105
+ for (const [, window] of Array.from(this.historyWindows.items)) {
1106
+ await window.setTraverseLock(this.traverseLock);
1107
+ }
1108
+ }
1109
+
1110
+ /**
1111
+ * For internal use.
1112
+ * @internal
1113
+ */
1114
+ _handleNewTopic(ev) {
1115
+ this.createHistoryWindowForTopic(ev.topic);
1116
+ }
1117
+
1118
+ /**
1119
+ * For internal use.
1120
+ * @internal
1121
+ */
1122
+ _handleTopicDeleted(ev) {
1123
+ this.historyWindows.delete(ev.location.topicId);
1124
+ }
1125
+
1126
+ /**
1127
+ * For internal use.
1128
+ * @internal
1129
+ */
1130
+ _handleNewMessage(ev) {
1131
+ this.historyWindows.get(ev.message.location.topicId)?._handleNewMessage(ev);
1132
+ }
1133
+
1134
+ /**
1135
+ * For internal use.
1136
+ * @internal
1137
+ */
1138
+ _handleMessagesRedacted(ev) {
1139
+ void this.historyWindows.get(ev.location.topicId)?._handleMessagesRedacted(ev);
1140
+ }
1141
+
1142
+ /**
1143
+ * For internal use.
1144
+ * @internal
1145
+ */
1146
+ _handleReactionUpdated(ev) {
1147
+ for (const window of this.historyWindows.items.values()) {
1148
+ window._handleReactionUpdated(ev);
1149
+ }
1150
+ }
1151
+
1152
+ /**
1153
+ * For internal use.
1154
+ * @internal
1155
+ */
1156
+ _handleReacted(ev) {
1157
+ for (const window of this.historyWindows.items.values()) {
1158
+ window._handleReacted(ev);
1159
+ }
1160
+ }
1161
+ createHistoryWindowForTopic(topic) {
1162
+ if (this.historyWindows.has(topic.id)) {
1163
+ return;
1164
+ }
1165
+ this.createHistoryWindow(topic.id);
1166
+
1167
+ // If new topic refers to some message from this room, update other structures
1168
+ if (topic.refMessage) {
1169
+ const refHistoryWindow = this.historyWindows.get(topic.refMessage.location.topicId);
1170
+ refHistoryWindow?._updateMessageReference(topic);
1171
+ }
1172
+ }
1173
+ createHistoryWindow(topicId) {
1174
+ const historyWindow = new TopicHistoryWindow(this.roomId, topicId, this.tracker, this.isPreview);
1175
+ void historyWindow.setTraverseLock(this.traverseLock);
1176
+ this.historyWindows.set([topicId, historyWindow]);
1177
+
1178
+ // Current behavior of deletion a message with referenced topic is to delete the whole side topic
1179
+ // So we need to listen for topic deletions here
1180
+ historyWindow.on('reftopicsdeleted', deletedTopicIds => {
1181
+ for (const topicId of deletedTopicIds) {
1182
+ this.historyWindows.delete(topicId);
1183
+ }
1184
+ this.tracker.rooms._deleteTopicsFromRoom(this.roomId, ...deletedTopicIds);
1185
+ });
1186
+ }
1187
+ updateTraverseLock(room) {
1188
+ this.traverseLock = room.history.mode === 'Ephemeral';
1189
+ }
1190
+ }
1191
+ ;// ./src/state-tracker/MessagesManager.ts
1192
+
1193
+
1194
+
1195
+ class MessagesManager {
1196
+ roomHistories = new IndexedCollection();
1197
+ previewHistories = new IndexedCollection();
1198
+ deferredSession = new DeferredTask();
1199
+ constructor(tracker) {
1200
+ this.tracker = tracker;
1201
+ this.tracker.client.on('Session', ev => this.handleSession(ev));
1202
+ this.tracker.client.on('RoomJoined', ev => this.handleRoomJoin(ev));
1203
+ this.tracker.client.on('RoomDeleted', ev => this.handleRoomDeleted(ev));
1204
+ this.tracker.client.on('RoomLeft', ev => this.handleRoomLeft(ev));
1205
+
1206
+ // One subscription for all the histories, routed by location: a message costs the same however many rooms
1207
+ // and topics are tracked, and nothing stays subscribed after its room or topic is gone.
1208
+ this.tracker.client.on('RoomUpdated', ev => void this.roomHistories.get(ev.room.id)?._handleRoomUpdated(ev));
1209
+ this.tracker.client.on('NewTopic', ev => this.roomHistories.get(ev.roomId)?._handleNewTopic(ev));
1210
+ this.tracker.client.on('TopicDeleted', ev => this.roomHistories.get(ev.location.roomId)?._handleTopicDeleted(ev));
1211
+ this.tracker.client.on('NewMessage', ev => this.roomHistories.get(ev.message.location.roomId)?._handleNewMessage(ev));
1212
+ this.tracker.client.on('MessagesRedacted', ev => this.roomHistories.get(ev.location.roomId)?._handleMessagesRedacted(ev));
1213
+ this.tracker.client.on('ReactionUpdated', ev => this.forEachRoomHistory(history => history._handleReactionUpdated(ev)));
1214
+ this.tracker.client.on('Reacted', ev => this.forEachRoomHistory(history => history._handleReacted(ev)));
1215
+ }
1216
+
1217
+ /**
1218
+ * Get history manager for given room ID. For a room you have not joined it is a preview (requires `PreviewRooms`),
1219
+ * kept until {@link forgetRoomPreview} or until you join the room.
1220
+ */
1221
+ async getRoomHistory(roomId) {
1222
+ await this.deferredSession.promise;
1223
+ if (this.roomHistories.has(roomId)) {
1224
+ return this.roomHistories.get(roomId);
1225
+ }
1226
+ if (!this.previewHistories.has(roomId)) {
1227
+ this.previewHistories.set([roomId, new RoomMessagesHistory(roomId, this.tracker)]);
1228
+ }
1229
+ return this.previewHistories.get(roomId);
1230
+ }
1231
+ forgetRoomPreview(roomId) {
1232
+ this.previewHistories.delete(roomId);
1233
+ }
1234
+
1235
+ /**
1236
+ * For internal use.
1237
+ * @internal
1238
+ */
1239
+ async _resolveLastMessage(location) {
1240
+ // Try to get last message from history window (if cached); not getRoomHistory(), it would create a preview
1241
+ await this.deferredSession.promise;
1242
+ const historyWindow = await this.roomHistories.get(location.roomId)?.getMessagesWindow(location.topicId, true);
1243
+ let message = historyWindow?.hasLatest && historyWindow.getAt(historyWindow.length - 1);
1244
+ if (!message) {
1245
+ const result = await this.tracker.client.send('GetMessages', {
1246
+ location,
1247
+ limit: 1
1248
+ });
1249
+ message = result.data?.messages[0];
1250
+ }
1251
+ return message || null;
1252
+ }
1253
+ forEachRoomHistory(callback) {
1254
+ for (const history of this.roomHistories.items.values()) {
1255
+ callback(history);
1256
+ }
1257
+ }
1258
+ createHistoryForNewRoom(room) {
1259
+ this.previewHistories.delete(room.id);
1260
+ this.roomHistories.set([room.id, new RoomMessagesHistory(room, this.tracker)]);
1261
+ }
1262
+ handleRoomDeleted(ev) {
1263
+ this.roomHistories.delete(ev.id);
1264
+ }
1265
+ handleRoomJoin(ev) {
1266
+ this.createHistoryForNewRoom(ev.room);
1267
+ }
1268
+ handleRoomLeft(ev) {
1269
+ this.roomHistories.delete(ev.id);
1270
+ }
1271
+ handleSession(ev) {
1272
+ const stateRoomIds = new Set(ev.state.rooms.map(room => room.id));
1273
+
1274
+ // Drop histories only for rooms that no longer exist server-side.
1275
+ for (const roomId of Array.from(this.roomHistories.items.keys())) {
1276
+ if (!stateRoomIds.has(roomId)) {
1277
+ this.roomHistories.delete(roomId);
1278
+ }
1279
+ }
1280
+
1281
+ // Keep existing histories (preserving loaded messages and, crucially,
1282
+ // live-only ephemeral history), create histories for newly joined
1283
+ // rooms, and resync survivors against the fresh room snapshot.
1284
+ for (const room of ev.state.rooms) {
1285
+ const history = this.roomHistories.get(room.id);
1286
+ if (history) {
1287
+ void history.resync(room);
1288
+ } else {
1289
+ this.createHistoryForNewRoom(room);
1290
+ }
1291
+ }
1292
+ this.deferredSession.resolve();
1293
+ }
1294
+ }
1295
+ ;// ./src/state-tracker/FollowedTopicsManager.ts
1296
+
1297
+
1298
+
1299
+ class FollowedTopicsManager extends EventTarget {
1300
+ followedTopics = new IndexedCollection();
1301
+ followedTopicsPromises = new PromiseRegistry();
1302
+ deferredSession = new DeferredTask();
1303
+ summariesCache = new Map();
1304
+
1305
+ /**
1306
+ * Rooms whose cached followed-topics are stale after a reconnect and must
1307
+ * be refetched (and reconciled in place) the next time they are accessed.
1308
+ */
1309
+ staleRooms = new Set();
1310
+ constructor(tracker) {
1311
+ super();
1312
+ this.tracker = tracker;
1313
+ this.tracker.client.on('Session', ev => this.handleSession(ev));
1314
+ this.tracker.client.on('RoomJoined', ev => this.handleRoomJoin(ev));
1315
+ this.tracker.client.on('NewTopic', ev => this.handleNewTopic(ev));
1316
+ this.tracker.client.on('FollowedTopicUpdated', ev => this.handleFollowedTopicUpdated(ev));
1317
+ this.tracker.client.on('TopicFollowed', ev => this.handleTopicFollowed(ev));
1318
+ this.tracker.client.on('TopicUnfollowed', ev => this.handleTopicUnfollowed(ev));
1319
+ this.tracker.client.on('NewMessage', ev => this.handleNewMessage(ev));
1320
+ this.tracker.client.on('RoomDeleted', ev => this.handleRoomDeleted(ev));
1321
+ this.tracker.client.on('RoomLeft', ev => this.handleRoomLeft(ev));
1322
+ this.tracker.client.on('TopicDeleted', ev => this.handleTopicDeleted(ev));
1323
+ }
1324
+
1325
+ /**
1326
+ * Cache followed topics for all joined rooms in a space and fetch them in bulk if necessary.
1327
+ * Then you can get them using getRoomFollowedTopics().
1328
+ * @see getForRoom
1329
+ */
1330
+ async cacheForSpace(spaceId) {
1331
+ if (spaceId && !(await this.tracker.spaces.get()).has(spaceId)) {
1332
+ throw new Error(`You are not in space ${spaceId}`);
1333
+ }
1334
+ const rooms = await this.tracker.rooms.get();
1335
+ const roomIds = spaceId ? rooms.findBy('spaceId', spaceId).items.map(r => r.id) : rooms.items.filter(r => !r.spaceId).map(r => r.id);
1336
+ if (!roomIds.length) {
1337
+ return;
1338
+ }
1339
+ const needsFetch = roomIds.some(roomId => !this.followedTopics.has(roomId) || this.staleRooms.has(roomId));
1340
+ if (!needsFetch) {
1341
+ return;
1342
+ }
1343
+ const spaceRegistryKey = `space_fetch_${spaceId || 'spaceless'}`;
1344
+ if (this.followedTopicsPromises.notExist(spaceRegistryKey)) {
1345
+ this.followedTopicsPromises.registerByFunction(async () => {
1346
+ const result = await this.tracker.client.send('GetFollowedTopics', {
1347
+ location: {
1348
+ spaceId
1349
+ }
1350
+ });
1351
+ if (result.error) throw result.error;
1352
+ this.reconcileRoomsFollowedTopics(roomIds, result.data.followedTopics);
1353
+ }, spaceRegistryKey);
1354
+ }
1355
+ await this.followedTopicsPromises.get(spaceRegistryKey);
1356
+ }
1357
+
1358
+ /**
1359
+ * Get followed topics for the given room.
1360
+ * @return Undefined if you are not in the room, collection otherwise.
1361
+ */
1362
+ async getForRoom(roomId) {
1363
+ if (!(await this.tracker.rooms.get()).has(roomId)) {
1364
+ return undefined;
1365
+ }
1366
+ if (!this.followedTopics.has(roomId) || this.staleRooms.has(roomId)) {
1367
+ if (this.followedTopicsPromises.notExist(roomId)) {
1368
+ this.followedTopicsPromises.registerByFunction(async () => {
1369
+ const result = await this.tracker.client.send('GetFollowedTopics', {
1370
+ location: {
1371
+ roomId
1372
+ }
1373
+ });
1374
+ if (result.error) {
1375
+ throw result.error;
1376
+ }
1377
+ this.applyRoomFollowedTopics(roomId, result.data.followedTopics);
1378
+ this.invalidateUnreadSummaries(roomId);
1379
+ }, roomId);
1380
+ }
1381
+ await this.followedTopicsPromises.get(roomId);
1382
+ }
1383
+ return this.followedTopics.get(roomId);
1384
+ }
1385
+
1386
+ /**
1387
+ * Batch acknowledge all messages for given room.
1388
+ */
1389
+ async ackRoom(roomId) {
1390
+ const collection = await this.getForRoom(roomId);
1391
+ if (!collection) {
1392
+ return;
1393
+ }
1394
+ for (const followedTopic of collection.items) {
1395
+ if (followedTopic.isUnread) {
1396
+ await this.tracker.client.send('Ack', {
1397
+ location: followedTopic.location
1398
+ });
1399
+ }
1400
+ }
1401
+ }
1402
+
1403
+ /**
1404
+ * Summarize all unread messages or mentions from any topic in given location.
1405
+ * This method uses an internal cache, so it's ok to call it multiple times.
1406
+ * Capture the 'change' event to determine when it's worth calling this method again due to data changes.
1407
+ * @return Undefined if you are not in room.
1408
+ */
1409
+ async summarize(location) {
1410
+ const cacheKey = location.topicId ? `topic:${location.roomId}:${location.topicId}` : location.roomId ? `room:${location.roomId}` : location.spaceId ? `space:${location.spaceId}` : 'spaceless';
1411
+ if (this.summariesCache.has(cacheKey)) {
1412
+ return this.summariesCache.get(cacheKey);
1413
+ }
1414
+ let roomIds = [];
1415
+ let targetTopicId;
1416
+ const rooms = await this.tracker.rooms.get();
1417
+ if (location.topicId) {
1418
+ if (!location.roomId) {
1419
+ throw new Error("roomId is required when querying by topicId");
1420
+ }
1421
+ roomIds = [location.roomId];
1422
+ targetTopicId = location.topicId;
1423
+ } else if (location.roomId) {
1424
+ roomIds = [location.roomId];
1425
+ } else if (location.spaceId) {
1426
+ await this.cacheForSpace(location.spaceId);
1427
+ roomIds = rooms.findBy('spaceId', location.spaceId).items.map(r => r.id);
1428
+ } else {
1429
+ await this.cacheForSpace(null);
1430
+ roomIds = rooms.items.filter(r => !r.spaceId).map(r => r.id);
1431
+ }
1432
+ let mentionCount = 0;
1433
+ let unreadTopicCount = 0;
1434
+ let unreadRoomCount = 0;
1435
+ for (const roomId of roomIds) {
1436
+ const collection = await this.getForRoom(roomId);
1437
+ if (!collection) {
1438
+ continue;
1439
+ }
1440
+ let isRoomUnreadCount = false;
1441
+ for (const topic of collection.items) {
1442
+ if (targetTopicId && topic.location.topicId !== targetTopicId) {
1443
+ continue;
1444
+ }
1445
+ if (topic.isUnread) {
1446
+ if (!isRoomUnreadCount) {
1447
+ unreadRoomCount++;
1448
+ isRoomUnreadCount = true;
1449
+ }
1450
+ unreadTopicCount++;
1451
+ }
1452
+ mentionCount += topic.mentionCount ?? 0;
1453
+ }
1454
+ }
1455
+ const result = {
1456
+ mentionCount,
1457
+ unreadTopicCount,
1458
+ unreadRoomCount,
1459
+ isUnread: unreadTopicCount > 0
1460
+ };
1461
+ this.summariesCache.set(cacheKey, result);
1462
+ return result;
1463
+ }
1464
+
1465
+ /**
1466
+ * For internal use. If you want to delete the message, execute a proper command on client object.
1467
+ * @internal
1468
+ */
1469
+ _deleteByTopicIds(roomId, ...topicIds) {
1470
+ this.followedTopics.get(roomId)?.delete(...topicIds);
1471
+ topicIds.forEach(topicId => this.invalidateUnreadSummaries(roomId, topicId));
1472
+ }
1473
+ handleSession(ev) {
1474
+ // Keep cached followed-topic collections (they drive unread indicators
1475
+ // that would otherwise blank on reconnect), but mark them stale and drop
1476
+ // the fetch guards so the next access/caching refetches and reconciles
1477
+ // them in place.
1478
+ for (const roomId of this.followedTopics.items.keys()) {
1479
+ this.staleRooms.add(roomId);
1480
+ }
1481
+ this.followedTopicsPromises.forgetAll();
1482
+ this.invalidateUnreadSummaries();
1483
+ this.deferredSession.resolve();
1484
+ }
1485
+ handleNewMessage(ev) {
1486
+ void this.updateLocallyFollowedTopicOnNewMessage(ev);
1487
+ }
1488
+ handleFollowedTopicUpdated(ev) {
1489
+ this.followedTopics.get(ev.followedTopic.location.roomId)?.set(ev.followedTopic);
1490
+ this.invalidateUnreadSummaries(ev.followedTopic.location.roomId, ev.followedTopic.location.topicId);
1491
+ }
1492
+ handleTopicFollowed(ev) {
1493
+ this.setFollowedTopicsArray([ev.followedTopic.location.roomId], [ev.followedTopic]);
1494
+ this.invalidateUnreadSummaries(ev.followedTopic.location.roomId, ev.followedTopic.location.topicId);
1495
+ }
1496
+ handleTopicUnfollowed(ev) {
1497
+ this.followedTopics.get(ev.location.roomId)?.delete(ev.location.topicId);
1498
+ this.invalidateUnreadSummaries(ev.location.roomId, ev.location.topicId);
1499
+ }
1500
+ handleRoomDeleted(ev) {
1501
+ this.clearRoomFollowedTopicsStructures(ev.id);
1502
+ }
1503
+ handleRoomJoin(ev) {
1504
+ this.clearRoomFollowedTopicsStructures(ev.room.id);
1505
+ }
1506
+ handleRoomLeft(ev) {
1507
+ this.clearRoomFollowedTopicsStructures(ev.id);
1508
+ }
1509
+ async handleNewTopic(ev) {
1510
+ if (this.followedTopics.has(ev.roomId)) {
1511
+ // Check if the new topic is followed by user
1512
+ // only if client asked for followed topics list before for this room
1513
+ const result = await this.tracker.client.send('GetFollowedTopics', {
1514
+ location: {
1515
+ roomId: ev.roomId,
1516
+ topicId: ev.topic.id
1517
+ }
1518
+ });
1519
+ const followedTopic = result.data.followedTopics[0];
1520
+ if (followedTopic) {
1521
+ this.followedTopics.get(ev.roomId).set(followedTopic);
1522
+ this.invalidateUnreadSummaries(ev.roomId, ev.topic.id);
1523
+ }
1524
+ }
1525
+ }
1526
+ handleTopicDeleted(ev) {
1527
+ this.followedTopics.get(ev.location.roomId)?.delete(ev.location.topicId);
1528
+ this.invalidateUnreadSummaries(ev.location.roomId, ev.location.topicId);
1529
+ }
1530
+
1531
+ /**
1532
+ * Invalidate the summaries cache intentionally, only for the locations affected by the change.
1533
+ */
1534
+ invalidateUnreadSummaries(roomId, topicId) {
1535
+ if (roomId) {
1536
+ this.summariesCache.delete(`room:${roomId}`);
1537
+ if (topicId) {
1538
+ this.summariesCache.delete(`topic:${roomId}:${topicId}`);
1539
+ } else {
1540
+ for (const key of this.summariesCache.keys()) {
1541
+ if (key.startsWith(`topic:${roomId}:`)) {
1542
+ this.summariesCache.delete(key);
1543
+ }
1544
+ }
1545
+ }
1546
+ const room = this.tracker.rooms?._getRoom(roomId);
1547
+ if (room) {
1548
+ this.summariesCache.delete(room.spaceId ? `space:${room.spaceId}` : 'spaceless');
1549
+ } else {
1550
+ for (const key of this.summariesCache.keys()) {
1551
+ if (key.startsWith('space:') || key === 'spaceless') {
1552
+ this.summariesCache.delete(key);
1553
+ }
1554
+ }
1555
+ }
1556
+ } else {
1557
+ this.summariesCache.clear();
1558
+ }
1559
+ this.emit('change');
1560
+ }
1561
+ invalidateUnreadSummariesForRooms(roomIds) {
1562
+ const roomIdsSet = new Set(roomIds);
1563
+ roomIds.forEach(roomId => {
1564
+ this.summariesCache.delete(`room:${roomId}`);
1565
+ });
1566
+ for (const key of this.summariesCache.keys()) {
1567
+ if (key.startsWith('space:') || key === 'spaceless') {
1568
+ this.summariesCache.delete(key);
1569
+ continue;
1570
+ }
1571
+ if (key.startsWith('topic:')) {
1572
+ const parts = key.split(':');
1573
+ if (parts.length >= 2 && roomIdsSet.has(parts[1])) {
1574
+ this.summariesCache.delete(key);
1575
+ }
1576
+ }
1577
+ }
1578
+ this.emit('change');
1579
+ }
1580
+ async updateLocallyFollowedTopicOnNewMessage(ev) {
1581
+ const roomFollowedTopics = this.followedTopics.get(ev.message.location.roomId);
1582
+ const followedTopic = roomFollowedTopics?.get(ev.message.location.topicId);
1583
+ if (!roomFollowedTopics || !followedTopic || ev.message.type === 'Ephemeral') {
1584
+ // Skip if we don't follow this room or message is ephemeral
1585
+ return;
1586
+ }
1587
+ const me = await this.tracker.getMe();
1588
+ const isMe = ev.message.author.user.id === me.id;
1589
+ let update;
1590
+ if (isMe) {
1591
+ // Reset missed messages count if new message is authored by me
1592
+ update = {
1593
+ missed: 0,
1594
+ lastAckMessageId: ev.message.id
1595
+ };
1596
+ } else if (ev.message.type === 'Text') {
1597
+ // ...check for mentions if it's text message...
1598
+ const member = await this.tracker.rooms.getMe(ev.message.location.roomId);
1599
+ const roleIds = [...(member.spaceMember?.roles ?? []), ...(member.roles ?? [])];
1600
+ const mentionHandlers = [...roleIds.map(id => `<@&${id}>`), `<@${me.id}>`];
1601
+ const mentionExists = mentionHandlers.some(handler => ev.message.content.includes(handler));
1602
+ update = {
1603
+ missed: followedTopic.missed === null ? null : followedTopic.missed + 1,
1604
+ isUnread: true,
1605
+ mentionCount: followedTopic.mentionCount + (mentionExists ? 1 : 0)
1606
+ };
1607
+ } else {
1608
+ // ...or just mark as unread.
1609
+ update = {
1610
+ missed: followedTopic.missed === null ? null : followedTopic.missed + 1,
1611
+ isUnread: true
1612
+ };
1613
+ }
1614
+ roomFollowedTopics.set({
1615
+ ...followedTopic,
1616
+ ...update
1617
+ });
1618
+ this.invalidateUnreadSummaries(ev.message.location.roomId, ev.message.location.topicId);
1619
+ }
1620
+
1621
+ /**
1622
+ * Reconcile the followed-topics collection for a single room to exactly
1623
+ * match the provided list (upsert present, drop absent) without emitting an
1624
+ * intermediate empty state, and clear its stale marker. Does not touch the
1625
+ * unread summaries cache - callers decide how to invalidate it.
1626
+ */
1627
+ applyRoomFollowedTopics(roomId, followedTopics) {
1628
+ if (!this.followedTopics.has(roomId)) {
1629
+ this.followedTopics.set([roomId, new ObservableIndexedObjectCollection(followedTopic => followedTopic.location.topicId)]);
1630
+ }
1631
+ this.followedTopics.get(roomId).reconcile(...followedTopics);
1632
+ this.staleRooms.delete(roomId);
1633
+ }
1634
+
1635
+ /**
1636
+ * Reconcile a batch of rooms from a single bulk GetFollowedTopics response.
1637
+ * Rooms with no followed topics in the response are reconciled to empty, so
1638
+ * topics unfollowed/removed during the downtime are correctly dropped.
1639
+ */
1640
+ reconcileRoomsFollowedTopics(roomIds, followedTopics) {
1641
+ const roomToTopics = {};
1642
+ followedTopics.forEach(followedTopic => {
1643
+ (roomToTopics[followedTopic.location.roomId] ??= []).push(followedTopic);
1644
+ });
1645
+ roomIds.forEach(roomId => this.applyRoomFollowedTopics(roomId, roomToTopics[roomId] ?? []));
1646
+ this.invalidateUnreadSummariesForRooms(roomIds);
1647
+ }
1648
+ setFollowedTopicsArray(roomIds, followedTopics) {
1649
+ const roomToTopics = {};
1650
+
1651
+ // Reassign followed topics to limit collection change event emit
1652
+ followedTopics.forEach(followedTopic => {
1653
+ roomToTopics[followedTopic.location.roomId] ??= [];
1654
+ roomToTopics[followedTopic.location.roomId].push(followedTopic);
1655
+ });
1656
+ roomIds.forEach(roomId => {
1657
+ if (!this.followedTopics.has(roomId)) {
1658
+ this.followedTopics.set([roomId, new ObservableIndexedObjectCollection(followedTopic => followedTopic.location.topicId)]);
1659
+ }
1660
+ if (roomToTopics[roomId]) {
1661
+ this.followedTopics.get(roomId).set(...roomToTopics[roomId]);
1662
+ }
1663
+ });
1664
+ this.invalidateUnreadSummariesForRooms(roomIds);
1665
+ }
1666
+ clearRoomFollowedTopicsStructures(roomId) {
1667
+ this.followedTopics.delete(roomId);
1668
+ this.followedTopicsPromises.forget(roomId);
1669
+ this.staleRooms.delete(roomId);
1670
+ this.invalidateUnreadSummaries(roomId);
1671
+ }
1672
+ }
1673
+ ;// ./src/state-tracker/RoomsManager.ts
1674
+
1675
+
1676
+
1677
+
1678
+ class RoomsManager {
1679
+ messages;
1680
+ followedTopics;
1681
+ list = new ObservableIndexedObjectCollection('id');
1682
+ topics = new IndexedCollection();
1683
+ members = new IndexedCollection();
1684
+ deferredSession = new DeferredTask();
1685
+ membersPromises = new PromiseRegistry();
1686
+ topicsPromises = new PromiseRegistry();
1687
+ constructor(tracker) {
1688
+ this.tracker = tracker;
1689
+ this.messages = new MessagesManager(tracker);
1690
+ this.followedTopics = new FollowedTopicsManager(tracker);
1691
+ this.tracker.client.on('NewMessage', ev => this.handleNewMessage(ev));
1692
+ this.tracker.client.on('MessagesRedacted', ev => this.handleMessagesRedacted(ev));
1693
+ this.tracker.client.on('NewTopic', ev => this.handleNewTopic(ev));
1694
+ this.tracker.client.on('TopicDeleted', ev => this.handleTopicDeleted(ev));
1695
+ this.tracker.client.on('RoomJoined', ev => this.handleRoomJoined(ev));
1696
+ this.tracker.client.on('RoomLeft', ev => this.handleRoomLeft(ev));
1697
+ this.tracker.client.on('RoomUpdated', ev => this.handleRoomUpdated(ev));
1698
+ this.tracker.client.on('RoomDeleted', ev => this.handleRoomDeleted(ev));
1699
+ this.tracker.client.on('TopicUpdated', ev => this.handleTopicUpdated(ev));
1700
+ this.tracker.client.on('RoomMembersJoined', ev => this.handleRoomMembersJoined(ev));
1701
+ this.tracker.client.on('RoomMemberLeft', ev => this.handleRoomMemberLeft(ev));
1702
+ this.tracker.client.on('RoomMembers', ev => this.handleRoomMembers(ev));
1703
+ this.tracker.client.on('RoomMemberUpdated', ev => this.handleRoomMemberUpdated(ev));
1704
+ this.tracker.client.on('SpaceMemberLeft', ev => this.handleSpaceMemberLeft(ev));
1705
+ this.tracker.client.on('SpaceMemberUpdated', ev => this.handleSpaceMemberUpdated(ev));
1706
+ this.tracker.client.on('SpaceDeleted', ev => this.handleSpaceDeleted(ev));
1707
+ this.tracker.client.on('SpaceLeft', ev => this.handleSpaceDeleted(ev));
1708
+ this.tracker.client.on('UserUpdated', ev => this.handleUserUpdated(ev));
1709
+ this.tracker.client.on('Session', ev => this.handleSession(ev));
1710
+ }
1711
+
1712
+ /**
1713
+ * Get collection of room members.
1714
+ */
1715
+ async getMembers(roomId) {
1716
+ if (this.membersPromises.notExist(roomId)) {
1717
+ this.membersPromises.registerByFunction(async () => {
1718
+ const result = await this.tracker.client.send('GetRoomMembers', {
1719
+ id: roomId
1720
+ });
1721
+ if (result.error) {
1722
+ throw result.error;
1723
+ }
1724
+ this.handleRoomMembers(result.data);
1725
+ }, roomId);
1726
+ }
1727
+ await this.membersPromises.get(roomId);
1728
+ return this.members.get(roomId);
1729
+ }
1730
+
1731
+ /**
1732
+ * Get a room member representing the current user.
1733
+ */
1734
+ async getMe(roomId) {
1735
+ const userId = (await this.tracker.getMe()).id;
1736
+ if (!this.list.has(roomId)) {
1737
+ // User is not in passed room.
1738
+ return undefined;
1739
+ }
1740
+ const members = await this.getMembers(roomId);
1741
+ return members?.items.find(member => (member.user?.id ?? member.spaceMember.user.id) === userId);
1742
+ }
1743
+
1744
+ /**
1745
+ * Get collection of all the rooms you are in.
1746
+ */
1747
+ async get() {
1748
+ await this.deferredSession.promise;
1749
+ return this.list;
1750
+ }
1751
+
1752
+ /**
1753
+ * Get a collection of locally cached Topic objects for given room.
1754
+ * You can pass topic ids as second argument, to try to fetch them from the server.
1755
+ */
1756
+ async getTopics(roomId, tryToFetchTopicIds) {
1757
+ await this.deferredSession.promise;
1758
+ if (tryToFetchTopicIds?.length) {
1759
+ // Topic can be fetched if it isn't already cached and fetch is not already in progress
1760
+ const canFetch = topicId => !this.topics.get(roomId)?.has(topicId) && !this.topicsPromises.has(roomId + topicId);
1761
+ const idsToFetch = tryToFetchTopicIds.filter(canFetch);
1762
+ if (idsToFetch.length) {
1763
+ const promise = this.tracker.client.send('GetTopics', {
1764
+ roomId,
1765
+ topicIds: idsToFetch
1766
+ }).then(result => this.topics.get(result.data.location.roomId)?.set(...result.data.topics));
1767
+ idsToFetch.forEach(topicId => this.topicsPromises.register(promise, roomId + topicId));
1768
+ }
1769
+ for (const topicId of tryToFetchTopicIds) {
1770
+ await this.topicsPromises.get(roomId + topicId);
1771
+ }
1772
+ }
1773
+ return this.topics.get(roomId);
1774
+ }
1775
+
1776
+ /**
1777
+ * For internal use.
1778
+ * @internal
1779
+ */
1780
+ _getRoom(roomId) {
1781
+ return this.list.get(roomId);
1782
+ }
1783
+
1784
+ /**
1785
+ * For internal use. If you want to delete topic, execute a proper command on client object.
1786
+ * @internal
1787
+ */
1788
+ _deleteTopicsFromRoom(roomId, ...topicIds) {
1789
+ this.topics.get(roomId)?.delete(...topicIds);
1790
+ }
1791
+ deleteRoom(...roomIds) {
1792
+ this.list.delete(...roomIds);
1793
+ this.members.delete(...roomIds);
1794
+ this.membersPromises.forget(...roomIds);
1795
+ for (const roomId of roomIds) {
1796
+ const topicIds = this.topics.get(roomId)?.items.map(topic => topic.id) ?? [];
1797
+ this.followedTopics._deleteByTopicIds(roomId, ...topicIds);
1798
+ }
1799
+ this.topics.delete(...roomIds);
1800
+ }
1801
+ deleteRoomsBySpaceId(spaceId) {
1802
+ this.deleteRoom(...this.list.findBy('spaceId', spaceId).items.map(room => room.id));
1803
+ }
1804
+ handleSpaceMemberUpdated(ev) {
1805
+ // Update members of rooms related to this space
1806
+ for (const room of this.list.findBy('spaceId', ev.spaceId).items) {
1807
+ const roomMembers = this.members.get(room.id);
1808
+ if (!roomMembers || !roomMembers.has(ev.userId)) {
1809
+ // Skip update if member list for this room is not loaded
1810
+ // or user is not in room
1811
+ continue;
1812
+ }
1813
+
1814
+ // Update space member in roomMember, but first fill the user object (it's null in event)
1815
+ const roomMember = roomMembers.get(ev.userId);
1816
+ roomMembers.set({
1817
+ ...roomMember,
1818
+ spaceMember: {
1819
+ ...ev.member,
1820
+ user: roomMember.spaceMember.user
1821
+ }
1822
+ });
1823
+ }
1824
+ }
1825
+ handleSpaceMemberLeft(ev) {
1826
+ this.list.findBy('spaceId', ev.spaceId).items.forEach(room => this.members.get(room.id)?.delete(ev.userId));
1827
+ }
1828
+ handleRoomMemberUpdated(ev) {
1829
+ if (!this.members.has(ev.roomId)) {
1830
+ // We do not track member list for this room.
1831
+ return;
1832
+ }
1833
+ const members = this.members.get(ev.roomId);
1834
+ const member = members.get(ev.userId);
1835
+ const user = member.spaceMember?.user ?? member.user;
1836
+
1837
+ // Preserving user object, because it's not included in event
1838
+ members.set(ev.member.spaceMember ? {
1839
+ ...ev.member,
1840
+ spaceMember: {
1841
+ ...ev.member.spaceMember,
1842
+ user
1843
+ }
1844
+ } : {
1845
+ ...ev.member,
1846
+ user
1847
+ });
1848
+ }
1849
+ handleSpaceDeleted(ev) {
1850
+ this.deleteRoomsBySpaceId(ev.id);
1851
+ }
1852
+ handleTopicDeleted(ev) {
1853
+ const collection = this.topics.get(ev.location.roomId);
1854
+ collection.delete(ev.location.topicId);
1855
+ const room = this.list.get(ev.location.roomId);
1856
+ if (room.defaultTopic?.id === ev.location.topicId) {
1857
+ this.list.set({
1858
+ ...room,
1859
+ defaultTopic: null
1860
+ });
1861
+ }
1862
+ }
1863
+ handleNewTopic(ev) {
1864
+ this.addJoinedRoomTopics(ev.roomId, ev.topic);
1865
+ }
1866
+ addJoinedRoomTopics(roomId, ...topics) {
1867
+ if (this.topics.has(roomId)) {
1868
+ this.topics.get(roomId).set(...topics);
1869
+ } else {
1870
+ this.topics.set([roomId, new ObservableIndexedObjectCollection('id', topics)]);
1871
+ }
1872
+ }
1873
+ handleRoomJoined(ev) {
1874
+ this.addJoinedRooms(ev.room);
1875
+ }
1876
+ handleRoomUpdated(ev) {
1877
+ if (this.list.has(ev.room.id)) {
1878
+ this.list.set(ev.room);
1879
+ }
1880
+ }
1881
+ handleRoomDeleted(ev) {
1882
+ this.deleteRoom(ev.id);
1883
+ }
1884
+ handleTopicUpdated(ev) {
1885
+ const room = this.list.get(ev.location.roomId);
1886
+ if (this.topics.get(ev.location.roomId)?.has(ev.topic.id)) {
1887
+ this.topics.get(ev.location.roomId).set(ev.topic);
1888
+ }
1889
+ if (room.defaultTopic.id === ev.topic.id) {
1890
+ const newRoom = {
1891
+ ...room
1892
+ };
1893
+ newRoom.defaultTopic = ev.topic;
1894
+ this.list.set(newRoom);
1895
+ }
1896
+ }
1897
+ addJoinedRooms(...rooms) {
1898
+ for (const room of rooms) {
1899
+ if (room.defaultTopic) {
1900
+ this.addJoinedRoomTopics(room.id, room.defaultTopic);
1901
+ }
1902
+ if (room.type === 'Pm' && room.recipients) {
1903
+ // Treat PM recipients as normal room members.
1904
+ // We are registering fake promise in `memberPromises`
1905
+ // because GetMembers are not supported for PM rooms.
1906
+ this.handleRoomMembers({
1907
+ id: room.id,
1908
+ members: room.recipients.map(user => ({
1909
+ user,
1910
+ spaceMember: null,
1911
+ roles: null,
1912
+ customColor: null,
1913
+ customNick: null,
1914
+ customAvatar: null,
1915
+ extras: ''
1916
+ }))
1917
+ });
1918
+ this.membersPromises.register(Promise.resolve(), room.id);
1919
+ }
1920
+ }
1921
+ this.list.set(...rooms);
1922
+ }
1923
+ handleRoomLeft(ev) {
1924
+ this.deleteRoom(ev.id);
1925
+ }
1926
+ handleRoomMembersJoined(ev) {
1927
+ if (this.members.has(ev.roomId)) {
1928
+ this.members.get(ev.roomId).set(...ev.members);
1929
+ }
1930
+ }
1931
+ handleRoomMemberLeft(ev) {
1932
+ if (this.members.has(ev.roomId)) {
1933
+ this.members.get(ev.roomId).delete(ev.userId);
1934
+ }
1935
+ }
1936
+ handleRoomMembers(ev) {
1937
+ if (!this.members.has(ev.id)) {
1938
+ this.members.set([ev.id, new ObservableIndexedObjectCollection(member => member.user?.id ?? member.spaceMember.user.id, ev.members)]);
1939
+ } else {
1940
+ // Reconcile into the existing (bound) collection so a reconnect
1941
+ // refetch updates it in place instead of leaving stale members.
1942
+ this.members.get(ev.id).reconcile(...ev.members);
1943
+ }
1944
+ }
1945
+ handleSession(ev) {
1946
+ const stateRoomIds = new Set(ev.state.rooms.map(room => room.id));
1947
+
1948
+ // Remove only rooms that were left/deleted on the server during the
1949
+ // downtime, reusing the cascade cleanup (members, topics, followed
1950
+ // topics). Surviving rooms keep their identity and bindings.
1951
+ const removedRoomIds = this.list.items.filter(room => !stateRoomIds.has(room.id)).map(room => room.id);
1952
+ if (removedRoomIds.length) {
1953
+ this.deleteRoom(...removedRoomIds);
1954
+ }
1955
+
1956
+ // Invalidate lazy caches so the next access refetches fresh data, but
1957
+ // keep the collection objects: handleRoomMembers reconciles into them,
1958
+ // so bound views refresh in place without blanking.
1959
+ this.membersPromises.forgetAll();
1960
+ this.topicsPromises.forgetAll();
1961
+
1962
+ // Upsert surviving/new rooms from the authoritative snapshot.
1963
+ this.addJoinedRooms(...ev.state.rooms);
1964
+ this.deferredSession.resolve();
1965
+ }
1966
+ handleUserUpdated(ev) {
1967
+ // Update room members users
1968
+ this.members.items.forEach(members => {
1969
+ const member = members.get(ev.user.id);
1970
+ if (!member) {
1971
+ // Skip room; updated user is not here
1972
+ return;
1973
+ }
1974
+ members.set(member.user ? {
1975
+ ...member,
1976
+ user: ev.user
1977
+ } : {
1978
+ ...member,
1979
+ spaceMember: {
1980
+ ...member.spaceMember,
1981
+ user: ev.user
1982
+ }
1983
+ });
1984
+ });
1985
+
1986
+ // Update recipients users
1987
+ const newRooms = [];
1988
+ this.list.items.forEach(room => {
1989
+ if (room.recipients?.some(user => user.id === ev.user.id)) {
1990
+ newRooms.push({
1991
+ ...room,
1992
+ recipients: room.recipients.map(user => user.id === ev.user.id ? ev.user : user)
1993
+ });
1994
+ }
1995
+ });
1996
+ this.list.set(...newRooms);
1997
+ }
1998
+ handleNewMessage(ev) {
1999
+ const topics = this.topics.get(ev.message.location.roomId);
2000
+ const topic = topics?.get(ev.message.location.topicId);
2001
+ if (!topic) {
2002
+ return; // No topic found, nothing to update
2003
+ }
2004
+ const newTopic = {
2005
+ ...topic,
2006
+ messageCount: topic.messageCount + 1,
2007
+ lastMessage: ev.message
2008
+ };
2009
+ topics.set(newTopic);
2010
+ this.updatePmDefaultTopic(ev.message.location.roomId, newTopic);
2011
+ }
2012
+ async handleMessagesRedacted(ev) {
2013
+ // Remove redacted messages from topic and update metadata
2014
+ const topics = this.topics.get(ev.location.roomId);
2015
+ const topic = topics?.get(ev.location.topicId);
2016
+ if (topic) {
2017
+ const messageCount = Math.max(topic.messageCount - ev.ids.length, 0);
2018
+ const lastMessage = messageCount > 0 ? await this.messages._resolveLastMessage(ev.location) : null;
2019
+ const newTopic = {
2020
+ ...topic,
2021
+ messageCount,
2022
+ lastMessage
2023
+ };
2024
+ topics.set(newTopic);
2025
+ this.updatePmDefaultTopic(ev.location.roomId, newTopic);
2026
+ }
2027
+ }
2028
+
2029
+ /**
2030
+ * The topics collection is where the message counters of a topic are kept up to date; a room in the list
2031
+ * is not replaced on every message, as everything bound to the room would be rendered anew with it.
2032
+ * Private conversations are the exception - they are listed by their last message.
2033
+ */
2034
+ updatePmDefaultTopic(roomId, topic) {
2035
+ const room = this.list.get(roomId);
2036
+ if (room?.type === 'Pm' && room.defaultTopic?.id === topic.id) {
2037
+ this.list.set({
2038
+ ...room,
2039
+ defaultTopic: topic
2040
+ });
2041
+ }
2042
+ }
2043
+ }
2044
+ ;// ./src/state-tracker/functions.ts
2045
+ /**
2046
+ * @return New objects of the other roles whose priority has to move; the given roles are left intact.
2047
+ */
2048
+ function reorderRolesOnPriorityUpdate(allRoles, oldRole, updatedRole) {
2049
+ // If the priority has changed, adjust the rest of roles
2050
+ const increased = updatedRole.priority - oldRole.priority > 0;
2051
+ const decreased = !increased;
2052
+ const changedRoles = [];
2053
+ allRoles.forEach(role => {
2054
+ if (role.id === updatedRole.id) {
2055
+ // Skip the updated role
2056
+ return;
2057
+ }
2058
+ if (increased && oldRole.priority <= role.priority) {
2059
+ changedRoles.push({
2060
+ ...role,
2061
+ priority: role.priority - 1
2062
+ });
2063
+ }
2064
+ if (decreased && updatedRole.priority <= role.priority) {
2065
+ changedRoles.push({
2066
+ ...role,
2067
+ priority: role.priority + 1
2068
+ });
2069
+ }
2070
+ });
2071
+ return changedRoles;
2072
+ }
2073
+ function extractUserFromMember(member) {
2074
+ return member.user ?? member.spaceMember?.user;
2075
+ }
2076
+ ;// ./src/state-tracker/SpacesManager.ts
2077
+
2078
+
2079
+
2080
+ class SpacesManager {
2081
+ list = new ObservableIndexedObjectCollection('id');
2082
+ roles = new IndexedCollection();
2083
+ rooms = new IndexedCollection();
2084
+ roomIdToSpaceId = new IndexedCollection();
2085
+ members = new IndexedCollection();
2086
+ deferredSession = new DeferredTask();
2087
+ roomsPromises = new PromiseRegistry();
2088
+ membersPromises = new PromiseRegistry();
2089
+ constructor(tracker) {
2090
+ this.tracker = tracker;
2091
+ this.tracker.client.on('NewRoom', ev => this.handleNewRoom(ev));
2092
+ this.tracker.client.on('RoomDeleted', ev => this.handleRoomDeleted(ev));
2093
+ this.tracker.client.on('RoomUpdated', ev => this.handleRoomUpdated(ev));
2094
+ this.tracker.client.on('SpaceDeleted', ev => this.handleSpaceDeleted(ev));
2095
+ this.tracker.client.on('SpaceUpdated', ev => this.handleSpaceUpdated(ev));
2096
+ this.tracker.client.on('SpaceJoined', ev => this.handleSpaceJoined(ev));
2097
+ this.tracker.client.on('SpaceLeft', ev => this.handleSpaceDeleted(ev));
2098
+ this.tracker.client.on('SpaceMemberJoined', ev => this.handleSpaceMemberJoined(ev));
2099
+ this.tracker.client.on('SpaceMemberLeft', ev => this.handleSpaceMemberLeft(ev));
2100
+ this.tracker.client.on('SpaceMembers', ev => this.handleSpaceMembers(ev));
2101
+ this.tracker.client.on('SpaceRooms', ev => this.handleSpaceRooms(ev));
2102
+ this.tracker.client.on('RoomSummaryUpdated', ev => this.handleRoomSummaryUpdated(ev));
2103
+ this.tracker.client.on('SpaceMemberUpdated', ev => this.handleSpaceMemberUpdated(ev));
2104
+ this.tracker.client.on('UserUpdated', ev => this.handleUserUpdated(ev));
2105
+ this.tracker.client.on('NewRole', ev => this.handleNewRole(ev));
2106
+ this.tracker.client.on('RoleDeleted', ev => this.handleRoleDeleted(ev));
2107
+ this.tracker.client.on('RoleUpdated', ev => this.handleRoleUpdated(ev));
2108
+ this.tracker.client.on('Session', ev => this.handleSession(ev));
2109
+ }
2110
+
2111
+ /**
2112
+ * Get collection of all the spaces you are in.
2113
+ */
2114
+ async get() {
2115
+ await this.deferredSession.promise;
2116
+ return this.list;
2117
+ }
2118
+
2119
+ /**
2120
+ * Get collection of space roles.
2121
+ */
2122
+ async getRoles(spaceId) {
2123
+ await this.deferredSession.promise;
2124
+ return this.roles.get(spaceId);
2125
+ }
2126
+
2127
+ /**
2128
+ * Get collection of the all available rooms inside given space.
2129
+ */
2130
+ async getRooms(spaceId) {
2131
+ if (this.roomsPromises.notExist(spaceId)) {
2132
+ this.roomsPromises.registerByFunction(async () => {
2133
+ const result = await this.tracker.client.send('GetSpaceRooms', {
2134
+ id: spaceId
2135
+ });
2136
+ if (result.error) {
2137
+ throw result.error;
2138
+ }
2139
+ this.handleSpaceRooms(result.data);
2140
+ }, spaceId);
2141
+ }
2142
+ await this.roomsPromises.get(spaceId);
2143
+ return this.rooms.get(spaceId);
2144
+ }
2145
+
2146
+ /**
2147
+ * Drop the cached room listing of the space and fetch it again from the server.
2148
+ * Room visibility depends on things this client is not notified about (invitations,
2149
+ * permission changes), so the listing needs a way to be pulled anew on demand.
2150
+ */
2151
+ async refreshRooms(spaceId) {
2152
+ this.roomsPromises.forget(spaceId);
2153
+ return this.getRooms(spaceId);
2154
+ }
2155
+
2156
+ /**
2157
+ * Get collection of space members.
2158
+ */
2159
+ async getMembers(spaceId) {
2160
+ if (this.membersPromises.notExist(spaceId)) {
2161
+ this.membersPromises.registerByFunction(async () => {
2162
+ const result = await this.tracker.client.send('GetSpaceMembers', {
2163
+ id: spaceId
2164
+ });
2165
+ if (result.error) {
2166
+ throw result.error;
2167
+ }
2168
+ this.handleSpaceMembers(result.data);
2169
+ }, spaceId);
2170
+ }
2171
+ await this.membersPromises.get(spaceId);
2172
+ return this.members.get(spaceId);
2173
+ }
2174
+
2175
+ /**
2176
+ * Get a space member representing the current user.
2177
+ */
2178
+ async getMe(spaceId) {
2179
+ const userId = (await this.tracker.getMe()).id;
2180
+ if (!this.list.has(spaceId)) {
2181
+ // User is not in passed space.
2182
+ return undefined;
2183
+ }
2184
+ const members = await this.getMembers(spaceId);
2185
+ return members?.items.find(member => member.user.id === userId);
2186
+ }
2187
+ handleNewRole(ev) {
2188
+ this.roles.get(ev.spaceId).set(ev.role);
2189
+ this.syncSpaceRoles(ev.spaceId);
2190
+ }
2191
+ handleNewRoom(ev) {
2192
+ this.rooms.get(ev.spaceId)?.set(ev.summary);
2193
+ this.roomIdToSpaceId.set([ev.summary.id, ev.spaceId]);
2194
+ }
2195
+ handleRoomUpdated(ev) {
2196
+ if (ev.room.spaceId && this.rooms.has(ev.room.spaceId)) {
2197
+ const rooms = this.rooms.get(ev.room.spaceId);
2198
+ rooms.set({
2199
+ ...rooms.get(ev.room.id),
2200
+ name: ev.room.name,
2201
+ description: ev.room.description
2202
+ });
2203
+ }
2204
+ }
2205
+ async handleRoomDeleted(ev) {
2206
+ const spaceId = this.roomIdToSpaceId.get(ev.id);
2207
+ this.roomIdToSpaceId.delete(ev.id);
2208
+ if (!spaceId) {
2209
+ return;
2210
+ }
2211
+ const space = this.list.get(spaceId);
2212
+ this.rooms.get(spaceId)?.delete(ev.id);
2213
+ if (space && (space.systemRoom === ev.id || space.defaultRooms.includes(ev.id))) {
2214
+ this.list.set({
2215
+ ...space,
2216
+ systemRoom: space.systemRoom === ev.id ? null : space.systemRoom,
2217
+ defaultRooms: space.defaultRooms.filter(roomId => roomId !== ev.id)
2218
+ });
2219
+ }
2220
+ }
2221
+ handleRoleDeleted(ev) {
2222
+ this.roles.get(ev.spaceId).delete(ev.id);
2223
+ this.syncSpaceRoles(ev.spaceId);
2224
+ }
2225
+
2226
+ /**
2227
+ * Keep the roles listed on the space object in line with the roles collection.
2228
+ */
2229
+ syncSpaceRoles(spaceId) {
2230
+ const space = this.list.get(spaceId);
2231
+ if (space) {
2232
+ this.list.set({
2233
+ ...space,
2234
+ roles: this.roles.get(spaceId).items
2235
+ });
2236
+ }
2237
+ }
2238
+ handleSpaceUpdated(ev) {
2239
+ this.list.set(ev.space);
2240
+ }
2241
+ handleSpaceDeleted(ev) {
2242
+ const roomIds = this.rooms.get(ev.id)?.items.map(item => item.id) ?? [];
2243
+ this.roomIdToSpaceId.delete(...roomIds);
2244
+ this.roles.delete(ev.id);
2245
+ this.members.delete(ev.id);
2246
+ this.membersPromises.forget(ev.id);
2247
+ this.rooms.delete(ev.id);
2248
+ this.roomsPromises.forget(ev.id);
2249
+ this.list.delete(ev.id);
2250
+ }
2251
+ handleSpaceJoined(ev) {
2252
+ this.addJoinedSpaces(ev.space);
2253
+ }
2254
+ addJoinedSpaces(...spaces) {
2255
+ this.roles.set(...spaces.map(space => [space.id, new ObservableIndexedObjectCollection('id', space.roles)]));
2256
+ this.list.set(...spaces);
2257
+ }
2258
+ handleSpaceMemberJoined(ev) {
2259
+ if (this.members.has(ev.spaceId)) {
2260
+ this.members.get(ev.spaceId).set(ev.member);
2261
+ }
2262
+ }
2263
+ handleSpaceMemberLeft(ev) {
2264
+ if (this.members.has(ev.spaceId)) {
2265
+ this.members.get(ev.spaceId).delete(ev.userId);
2266
+ }
2267
+ }
2268
+ handleSpaceMembers(ev) {
2269
+ if (!this.members.has(ev.id)) {
2270
+ this.members.set([ev.id, new ObservableIndexedObjectCollection(member => member?.user.id, ev.members)]);
2271
+ } else {
2272
+ // Reconcile into the existing (bound) collection so a reconnect
2273
+ // refetch updates it in place instead of leaving stale members.
2274
+ this.members.get(ev.id).reconcile(...ev.members);
2275
+ }
2276
+ }
2277
+ handleSpaceRooms(ev) {
2278
+ if (!this.rooms.has(ev.id)) {
2279
+ this.rooms.set([ev.id, new ObservableIndexedObjectCollection('id', ev.summaries)]);
2280
+ } else {
2281
+ this.rooms.get(ev.id).reconcile(...ev.summaries);
2282
+ }
2283
+ ev.summaries.forEach(summary => this.roomIdToSpaceId.set([summary.id, ev.id]));
2284
+ }
2285
+ async handleRoomSummaryUpdated(ev) {
2286
+ const spaceId = this.roomIdToSpaceId.get(ev.summary.id);
2287
+ const summariesPromise = this.roomsPromises.get(spaceId);
2288
+
2289
+ /**
2290
+ * Update summary only if the list was already loaded.
2291
+ * RoomSummaryUpdated event has a partial summary, so we need to update the existing summary by merging it.
2292
+ */
2293
+ if (spaceId && summariesPromise) {
2294
+ await summariesPromise;
2295
+ const summaries = this.rooms.get(spaceId);
2296
+ const oldSummary = summaries.get(ev.summary.id);
2297
+ let newSummary;
2298
+ if (oldSummary) {
2299
+ newSummary = {
2300
+ ...oldSummary,
2301
+ ...ev.summary
2302
+ };
2303
+ } else {
2304
+ newSummary = ev.summary;
2305
+ }
2306
+ summaries.set(newSummary);
2307
+ }
2308
+ }
2309
+ handleSpaceMemberUpdated(ev) {
2310
+ if (this.members.has(ev.spaceId)) {
2311
+ const members = this.members.get(ev.spaceId);
2312
+ const member = members.get(ev.userId);
2313
+ members.set({
2314
+ ...ev.member,
2315
+ user: member.user
2316
+ });
2317
+ }
2318
+ }
2319
+ handleRoleUpdated(ev) {
2320
+ const roles = this.roles.get(ev.spaceId);
2321
+ const oldRole = roles.get(ev.role.id);
2322
+ const newRole = ev.role;
2323
+ const rolesToUpdate = [newRole];
2324
+ if (oldRole.priority !== newRole.priority) {
2325
+ rolesToUpdate.push(...reorderRolesOnPriorityUpdate(roles.items, oldRole, newRole));
2326
+ }
2327
+ this.roles.get(ev.spaceId).set(...rolesToUpdate);
2328
+ this.syncSpaceRoles(ev.spaceId);
2329
+ }
2330
+ handleSession(ev) {
2331
+ const stateSpaceIds = new Set(ev.state.spaces.map(space => space.id));
2332
+
2333
+ // Remove only spaces that were left/deleted on the server during the
2334
+ // downtime, reusing the cascade cleanup (roles, rooms, members, index).
2335
+ const removedSpaceIds = this.list.items.filter(space => !stateSpaceIds.has(space.id)).map(space => space.id);
2336
+ for (const spaceId of removedSpaceIds) {
2337
+ this.handleSpaceDeleted({
2338
+ id: spaceId
2339
+ });
2340
+ }
2341
+
2342
+ // Invalidate lazy caches (rooms/members) but keep their objects so the
2343
+ // next access refetches and reconciles them in place.
2344
+ this.roomsPromises.forgetAll();
2345
+ this.membersPromises.forgetAll();
2346
+
2347
+ // Reconcile roles in place (kept, possibly bound object) and upsert the
2348
+ // spaces from the authoritative snapshot.
2349
+ for (const space of ev.state.spaces) {
2350
+ if (this.roles.has(space.id)) {
2351
+ this.roles.get(space.id).reconcile(...space.roles);
2352
+ } else {
2353
+ this.roles.set([space.id, new ObservableIndexedObjectCollection('id', space.roles)]);
2354
+ }
2355
+ }
2356
+ this.list.set(...ev.state.spaces);
2357
+ this.deferredSession.resolve();
2358
+ }
2359
+ handleUserUpdated(ev) {
2360
+ this.members.items.forEach(members => {
2361
+ const member = members.get(ev.user.id);
2362
+ if (!member) {
2363
+ // Skip space; updated user is not here
2364
+ return;
2365
+ }
2366
+ members.set({
2367
+ ...member,
2368
+ user: ev.user
2369
+ });
2370
+ });
2371
+ }
2372
+ }
2373
+ ;// ./src/Permissions.ts
2374
+ let Layer = /*#__PURE__*/function (Layer) {
2375
+ Layer[Layer["Global"] = 0] = "Global";
2376
+ Layer[Layer["Space"] = 1] = "Space";
2377
+ Layer[Layer["Room"] = 2] = "Room";
2378
+ Layer[Layer["Topic"] = 3] = "Topic";
2379
+ return Layer;
2380
+ }({});
2381
+ class PermissionDefinition {
2382
+ value;
2383
+ maxLayer;
2384
+ }
2385
+ class Permissions {
2386
+ static list = {
2387
+ Root: {
2388
+ value: 1 << 0,
2389
+ maxLayer: Layer.Room
2390
+ },
2391
+ CreateSpaces: {
2392
+ value: 1 << 1,
2393
+ maxLayer: Layer.Global
2394
+ },
2395
+ ManageSpace: {
2396
+ value: 1 << 2,
2397
+ maxLayer: Layer.Space
2398
+ },
2399
+ ManageRoles: {
2400
+ value: 1 << 3,
2401
+ maxLayer: Layer.Space
2402
+ },
2403
+ //ManageRoom: {value: 1 << 4, maxLayer: Layer.Room},
2404
+ CreateTopics: {
2405
+ value: 1 << 5,
2406
+ maxLayer: Layer.Room
2407
+ },
2408
+ ManageTopic: {
2409
+ value: 1 << 6,
2410
+ maxLayer: Layer.Topic
2411
+ },
2412
+ ManageMemberProfiles: {
2413
+ value: 1 << 7,
2414
+ maxLayer: Layer.Space
2415
+ },
2416
+ ManageMemberRoles: {
2417
+ value: 1 << 8,
2418
+ maxLayer: Layer.Room
2419
+ },
2420
+ CreateMessages: {
2421
+ value: 1 << 9,
2422
+ maxLayer: Layer.Topic
2423
+ },
2424
+ ManagePermissions: {
2425
+ value: 1 << 10,
2426
+ maxLayer: Layer.Topic
2427
+ },
2428
+ CreateRooms: {
2429
+ value: 1 << 11,
2430
+ maxLayer: Layer.Space
2431
+ },
2432
+ ManageRoom: {
2433
+ value: 1 << 12,
2434
+ maxLayer: Layer.Room
2435
+ },
2436
+ CreateEmoticons: {
2437
+ value: 1 << 13,
2438
+ maxLayer: Layer.Space
2439
+ },
2440
+ ManageEmoticons: {
2441
+ value: 1 << 14,
2442
+ maxLayer: Layer.Space
2443
+ },
2444
+ ManageBans: {
2445
+ value: 1 << 15,
2446
+ maxLayer: Layer.Room
2447
+ },
2448
+ Kick: {
2449
+ value: 1 << 16,
2450
+ maxLayer: Layer.Room
2451
+ },
2452
+ ChangeOwnProfile: {
2453
+ value: 1 << 17,
2454
+ maxLayer: Layer.Space
2455
+ },
2456
+ ChangeOwnColor: {
2457
+ value: 1 << 18,
2458
+ maxLayer: Layer.Room
2459
+ },
2460
+ RedactMessages: {
2461
+ value: 1 << 19,
2462
+ maxLayer: Layer.Topic
2463
+ },
2464
+ AddMembers: {
2465
+ value: 1 << 20,
2466
+ maxLayer: Layer.Space
2467
+ },
2468
+ React: {
2469
+ value: 1 << 21,
2470
+ maxLayer: Layer.Topic
2471
+ },
2472
+ CreatePolls: {
2473
+ value: 1 << 22,
2474
+ maxLayer: Layer.Topic
2475
+ },
2476
+ MentionAllRoles: {
2477
+ value: 1 << 23,
2478
+ maxLayer: Layer.Topic
2479
+ },
2480
+ PreviewRooms: {
2481
+ value: 1 << 24,
2482
+ maxLayer: Layer.Room
2483
+ },
2484
+ SearchMessages: {
2485
+ value: 1 << 25,
2486
+ maxLayer: Layer.Room
2487
+ }
2488
+ };
2489
+ static getNames() {
2490
+ return Object.keys(this.list);
2491
+ }
2492
+ static getByName(name) {
2493
+ return this.list[name];
2494
+ }
2495
+ static canBeDefinedOnLayer(permissionName, layer) {
2496
+ const def = this.getByName(permissionName);
2497
+ if (!def) {
2498
+ throw new Error(`Invalid permission name: ${permissionName}`);
2499
+ }
2500
+ return layer <= this.getByName(permissionName).maxLayer;
2501
+ }
2502
+ }
2503
+ ;// ./src/state-tracker/PermissionsManager.ts
2504
+
2505
+
2506
+
2507
+
2508
+ const getOvId = (location, target) => [location.spaceId, location.roomId, location.topicId, target?.type, target?.userId, target?.roleId].filter(Boolean).join('/');
2509
+ const getOvIdByObject = overwrites => getOvId(overwrites.location, overwrites.target);
2510
+ class PermissionsManager extends EventTarget {
2511
+ overwrites = new IndexedCollection();
2512
+ overwritesPromises = new PromiseRegistry();
2513
+ constructor(tracker) {
2514
+ super();
2515
+ this.tracker = tracker;
2516
+ this.tracker.client.on('PermissionOverwrites', ev => this.handlePermissionOverwrites(ev));
2517
+ this.tracker.client.on('PermissionOverwritesUpdated', ev => this.handlePermissionOverwrites(ev));
2518
+ this.tracker.client.on('SpaceDeleted', ev => this.handleSpaceDeleted(ev));
2519
+ this.tracker.client.on('SpaceLeft', ev => this.handleSpaceDeleted(ev));
2520
+ this.tracker.client.on('RoomDeleted', ev => this.handleRoomDeleted(ev));
2521
+ this.tracker.client.on('RoomLeft', ev => this.handleRoomDeleted(ev));
2522
+ this.tracker.client.on('TopicDeleted', ev => this.handleTopicDeleted(ev));
2523
+ this.tracker.client.on('RoleDeleted', ev => this.handleRoleDeleted(ev));
2524
+ this.tracker.client.on('SpaceMemberUpdated', ev => this.handleSpaceMemberUpdated(ev));
2525
+ this.tracker.client.on('RoomMemberUpdated', ev => this.handleRoomMemberUpdated(ev));
2526
+ this.tracker.client.on('Session', ev => this.handleSession(ev));
2527
+ }
2528
+ async getOverwrites(location, target) {
2529
+ this.validateLocation(location);
2530
+ const id = getOvId(location, target);
2531
+ if (this.overwritesPromises.notExist(id)) {
2532
+ this.overwritesPromises.registerByFunction(async () => {
2533
+ const result = await this.tracker.client.send('GetPermissionOverwrites', {
2534
+ location,
2535
+ target
2536
+ });
2537
+ if (result.error) {
2538
+ throw result.error;
2539
+ }
2540
+ this.handlePermissionOverwrites(result.data);
2541
+ }, id);
2542
+ }
2543
+ await this.overwritesPromises.get(id);
2544
+ return this.overwrites.get(id);
2545
+ }
2546
+ async check(permissionNames, location) {
2547
+ if (!permissionNames.length) {
2548
+ throw new Error('Permission names array cannot be empty');
2549
+ }
2550
+ const ownedPermissions = await this.calculatePermissions(location);
2551
+ const missing = [];
2552
+ permissionNames.forEach(name => {
2553
+ if (~ownedPermissions & Permissions.getByName(name).value) {
2554
+ missing.push(name);
2555
+ }
2556
+ });
2557
+ return {
2558
+ ok: missing.length === 0,
2559
+ hasAll: missing.length === 0,
2560
+ hasAny: missing.length < permissionNames.length,
2561
+ missing
2562
+ };
2563
+ }
2564
+
2565
+ /**
2566
+ * For a room or a space you have not joined the permissions are fetched from the server, on every call.
2567
+ */
2568
+ async calculatePermissions(location) {
2569
+ const room = location.roomId ? (await this.tracker.rooms.get()).get(location.roomId) : null;
2570
+ location = {
2571
+ spaceId: location.spaceId ?? room?.spaceId,
2572
+ roomId: location.roomId,
2573
+ topicId: location.topicId
2574
+ };
2575
+ this.validateLocation(location);
2576
+ if (location.roomId && !room || location.spaceId && !(await this.tracker.spaces.get())?.has(location.spaceId)) {
2577
+ return this.fetchComputedPermissions(location);
2578
+ }
2579
+ const userId = (await this.tracker.getMe()).id;
2580
+ const [spaceMember, roomMember] = await this.fetchMembersOrFail(location);
2581
+ const userRoles = [...(spaceMember?.roles ?? []), ...(roomMember?.roles ?? [])];
2582
+ const promises = [
2583
+ // Global user overwrites
2584
+ this.getOverwrites({}, {
2585
+ type: 'User',
2586
+ userId
2587
+ }).then(v => v.overwrites)];
2588
+ if (location.spaceId && (await this.tracker.spaces.get())?.has(location.spaceId)) {
2589
+ const filterLocation = {
2590
+ spaceId: location.spaceId
2591
+ };
2592
+ promises.push(this.collectRoleOverwrites(filterLocation, userRoles));
2593
+ promises.push(this.getOverwrites(filterLocation, {
2594
+ type: 'User',
2595
+ userId
2596
+ }).then(v => v.overwrites));
2597
+ }
2598
+ if (room) {
2599
+ const filterLocation = {
2600
+ spaceId: location.spaceId,
2601
+ roomId: location.roomId
2602
+ };
2603
+ if (userRoles.length) {
2604
+ promises.push(this.collectRoleOverwrites(filterLocation, userRoles));
2605
+ }
2606
+ promises.push(this.getOverwrites(filterLocation, {
2607
+ type: 'User',
2608
+ userId
2609
+ }).then(v => v.overwrites));
2610
+ }
2611
+ if (location.topicId && (await this.tracker.rooms.getTopics(location.roomId))?.has(location.topicId)) {
2612
+ if (userRoles.length) {
2613
+ promises.push(this.collectRoleOverwrites(location, userRoles));
2614
+ }
2615
+ promises.push(this.getOverwrites(location, {
2616
+ type: 'User',
2617
+ userId
2618
+ }).then(v => v.overwrites));
2619
+ }
2620
+ return this.resolveOverwritesHierarchy(await Promise.all(promises));
2621
+ }
2622
+
2623
+ /**
2624
+ * Arriving overwrites change the permissions only when they replace different ones. The first ones fetched for a
2625
+ * key have not been part of any result yet - every calculation needing them awaits their fetch - and a fetch
2626
+ * response arrives twice, as the command result and as an event.
2627
+ */
2628
+ handlePermissionOverwrites(ev) {
2629
+ const id = getOvIdByObject(ev);
2630
+ const previous = this.overwrites.get(id);
2631
+ this.overwrites.set([id, ev]);
2632
+ if (previous && (previous.overwrites.allow !== ev.overwrites.allow || previous.overwrites.deny !== ev.overwrites.deny)) {
2633
+ this.emit('change');
2634
+ }
2635
+ }
2636
+ handleSpaceDeleted(ev) {
2637
+ const ids = this.deleteOverwritesByIdPrefix(getOvId({
2638
+ spaceId: ev.id
2639
+ }));
2640
+ this.overwritesPromises.forget(...ids);
2641
+ }
2642
+ async handleRoomDeleted(ev) {
2643
+ const room = (await this.tracker.rooms.get()).get(ev.id);
2644
+ if (room) {
2645
+ const ids = this.deleteOverwritesByIdPrefix(getOvId({
2646
+ spaceId: room.spaceId,
2647
+ roomId: room.id
2648
+ }));
2649
+ this.overwritesPromises.forget(...ids);
2650
+ }
2651
+ }
2652
+ handleTopicDeleted(ev) {
2653
+ const ids = this.deleteOverwritesByIdPrefix(getOvId(ev.location));
2654
+ this.overwritesPromises.forget(...ids);
2655
+ }
2656
+ handleRoleDeleted(ev) {
2657
+ const ids = this.deleteOverwritesByIdPrefix(getOvId({
2658
+ spaceId: ev.spaceId
2659
+ }, {
2660
+ type: 'Role',
2661
+ roleId: ev.id
2662
+ }));
2663
+ this.overwritesPromises.forget(...ids);
2664
+ }
2665
+ handleSpaceMemberUpdated(ev) {
2666
+ if (ev.userId === this.tracker.me?.id) {
2667
+ // User roles in space could potentially have changed
2668
+ this.emit('change');
2669
+ }
2670
+ }
2671
+ handleRoomMemberUpdated(ev) {
2672
+ if (ev.userId === this.tracker.me?.id) {
2673
+ // User roles in room could potentially have changed
2674
+ this.emit('change');
2675
+ }
2676
+ }
2677
+
2678
+ /**
2679
+ * @return Matched and deleted ids
2680
+ */
2681
+ deleteOverwritesByIdPrefix(prefix) {
2682
+ const ids = [];
2683
+ this.overwrites.items.forEach(overwrites => {
2684
+ const id = getOvIdByObject(overwrites);
2685
+ if (id.startsWith(prefix)) {
2686
+ ids.push(id);
2687
+ this.overwrites.delete(id);
2688
+ }
2689
+ });
2690
+ return ids;
2691
+ }
2692
+ async collectRoleOverwrites(location, userRoles) {
2693
+ const roleOverwrites = await Promise.all(userRoles.map(roleId => this.getOverwrites(location, {
2694
+ type: 'Role',
2695
+ roleId
2696
+ })));
2697
+ return this.resolveOverwritesFromRolesByOrder(location.spaceId, roleOverwrites);
2698
+ }
2699
+ async resolveOverwritesFromRolesByOrder(spaceId, overwrites) {
2700
+ let allows = 0,
2701
+ denies = 0;
2702
+ const roles = await this.tracker.spaces.getRoles(spaceId);
2703
+ const sortedOverwrites = overwrites.sort((a, b) => roles.get(a.target.roleId).priority - roles.get(b.target.roleId).priority);
2704
+
2705
+ // Max length of bit word
2706
+ const permissionsLength = overwrites.reduce((previousValue, currentValue) => Math.max(previousValue, currentValue.overwrites.allow?.toString(2).length ?? 0, currentValue.overwrites.deny?.toString(2).length ?? 0), 0);
2707
+ sortedOverwrites.forEach(overwriteEvent => {
2708
+ const overwrites = overwriteEvent.overwrites;
2709
+ const revDecDenies = overwrites.deny?.toString(2).split('').reverse().join('') ?? '';
2710
+ const revDecAllows = overwrites.allow?.toString(2).split('').reverse().join('') ?? '';
2711
+ for (let i = 0; i < permissionsLength; i++) {
2712
+ const deny = parseInt(revDecDenies[i] ?? '0');
2713
+ const allow = parseInt(revDecAllows[i] ?? '0');
2714
+ if (deny) {
2715
+ denies |= 1 << i;
2716
+ }
2717
+ if (allow) {
2718
+ allows |= 1 << i;
2719
+ }
2720
+ }
2721
+ });
2722
+ return {
2723
+ allow: allows,
2724
+ deny: denies
2725
+ };
2726
+ }
2727
+ resolveOverwritesHierarchy(permissionOverwritesValues) {
2728
+ let result = 0;
2729
+ for (const value of permissionOverwritesValues) {
2730
+ if (value.allow & Permissions.getByName('Root').value) {
2731
+ return this.getRootAccessValue();
2732
+ }
2733
+ result = result & ~value.deny | value.allow;
2734
+ }
2735
+ return result;
2736
+ }
2737
+ getRootAccessValue() {
2738
+ let result = 0;
2739
+ for (const name of Permissions.getNames()) {
2740
+ result |= Permissions.getByName(name).value;
2741
+ }
2742
+ return result;
2743
+ }
2744
+ async fetchComputedPermissions(location) {
2745
+ const result = await this.tracker.client.send('GetComputedPermissions', {
2746
+ location
2747
+ });
2748
+ if (result.error) {
2749
+ throw result.error;
2750
+ }
2751
+ return result.data.permissions;
2752
+ }
2753
+ async fetchMembersOrFail(location) {
2754
+ const results = await Promise.all([location.spaceId ? this.tracker.spaces.getMe(location.spaceId) : null, location.roomId ? this.tracker.rooms.getMe(location.roomId) : null]);
2755
+ const spaceFail = location.spaceId && !results[0];
2756
+ const roomFail = location.roomId && !results[1];
2757
+ if (spaceFail || roomFail) {
2758
+ const layer = spaceFail ? `space (${location.spaceId})` : `room (${location.roomId})`;
2759
+ throw new Error(`Attempting to calculate permissions for a ${layer} that the user does not belong to`);
2760
+ }
2761
+ return results;
2762
+ }
2763
+ validateLocation(location) {
2764
+ if (location.topicId && !location.roomId) {
2765
+ throw new Error('Corrupted arguments hierarchy');
2766
+ }
2767
+ }
2768
+ handleSession(ev) {
2769
+ // Drop the fetch guards so permission checks recompute against fresh
2770
+ // overwrites (getOverwrites refetches and upserts on the next access),
2771
+ // and notify consumers to recompute so bound permission UI is never
2772
+ // left showing stale results after a reconnect.
2773
+ this.overwritesPromises.forgetAll();
2774
+ this.emit('change');
2775
+ }
2776
+ }
2777
+ ;// ./src/state-tracker/EmoticonsManager.ts
2778
+
2779
+
2780
+ const GLOBAL_KEY = 'global';
2781
+ class EmoticonsManager {
2782
+ list = new IndexedCollection();
2783
+ emoticonsPromises = new PromiseRegistry();
2784
+ constructor(tracker) {
2785
+ this.tracker = tracker;
2786
+ this.tracker.client.on('Emoticons', ev => this.handleEmoticons(ev));
2787
+ this.tracker.client.on('NewEmoticon', ev => this.handleNewEmoticon(ev));
2788
+ this.tracker.client.on('EmoticonDeleted', ev => this.handleEmoticonDeleted(ev));
2789
+ this.tracker.client.on('SpaceDeleted', ev => this.handleSpaceDeleted(ev));
2790
+ this.tracker.client.on('Session', () => this.handleSession());
2791
+ }
2792
+ async get(spaceId) {
2793
+ const key = spaceId ?? GLOBAL_KEY;
2794
+ if (this.emoticonsPromises.notExist(key)) {
2795
+ this.emoticonsPromises.registerByFunction(async () => {
2796
+ const result = await this.tracker.client.send('GetEmoticons', {
2797
+ spaceId
2798
+ });
2799
+ if (result.error) {
2800
+ throw result.error;
2801
+ }
2802
+ this.handleEmoticons(result.data);
2803
+ }, key);
2804
+ }
2805
+ await this.emoticonsPromises.get(key);
2806
+ return this.list.get(key);
2807
+ }
2808
+ handleEmoticons(event) {
2809
+ const spaceId = event.location.spaceId ?? GLOBAL_KEY;
2810
+ if (!this.list.has(spaceId)) {
2811
+ this.list.set([spaceId, new ObservableIndexedObjectCollection('id')]);
2812
+ }
2813
+
2814
+ // handleEmoticons always carries the full list for a location, so
2815
+ // reconcile in place: a reconnect refetch drops removed emoticons and
2816
+ // adds new ones without blanking a bound (visible) collection.
2817
+ this.list.get(spaceId).reconcile(...event.emoticons);
2818
+ }
2819
+ handleNewEmoticon(ev) {
2820
+ const collection = this.list.get(ev.emoticon.spaceId ?? GLOBAL_KEY);
2821
+ collection?.set(ev.emoticon);
2822
+ }
2823
+ handleEmoticonDeleted(ev) {
2824
+ const collection = this.list.get(ev.spaceId ?? GLOBAL_KEY);
2825
+ collection?.delete(ev.emoticonId);
2826
+ }
2827
+ handleSpaceDeleted(event) {
2828
+ this.list.delete(event.id);
2829
+ }
2830
+ handleSession() {
2831
+ // Keep cached emoticon collections (they may be bound to visible
2832
+ // pickers); just drop the fetch guards so the next access refetches and
2833
+ // reconciles them in place.
2834
+ this.emoticonsPromises.forgetAll();
2835
+ }
2836
+ }
2837
+ ;// ./src/state-tracker/UsersManager.ts
2838
+
2839
+
2840
+
2841
+ class UsersManager {
2842
+ onlineStatus = new EventTarget();
2843
+ users = new ObservableIndexedObjectCollection('id');
2844
+ constructor(tracker) {
2845
+ this.tracker = tracker;
2846
+ // RoomMemberUpdated & SpaceMemberUpdated events are not contains user object
2847
+ tracker.client.on('UserUpdated', event => this.handleUsers([event.user]));
2848
+ tracker.client.on('RoomMembersJoined', event => this.handleMembers(event.members));
2849
+ tracker.client.on('SpaceMemberJoined', event => this.handleMembers([event.member]));
2850
+ tracker.client.on('SpaceMembers', event => this.handleMembers(event.members));
2851
+ tracker.client.on('RoomMembers', event => this.handleMembers(event.members));
2852
+ tracker.client.on('Messages', event => this.handleUsers(event.messages.map(message => message.author.user)));
2853
+ tracker.client.on('NewMessage', event => this.handleUsers([event.message.author.user]));
2854
+ tracker.client.on('Session', event => this.handleSession(event));
2855
+ }
2856
+
2857
+ /**
2858
+ * Get all available (cached) user objects at once.
2859
+ */
2860
+ async getAvailable() {
2861
+ return this.users;
2862
+ }
2863
+ handleMembers(members) {
2864
+ this.handleUsers(members.map(extractUserFromMember));
2865
+ }
2866
+ handleSession(session) {
2867
+ // Keep the "seen users" cache across reconnects so bound user lists do
2868
+ // not blank out; just ensure our own user is present/updated. Stale
2869
+ // entries are refreshed as member/message collections refetch.
2870
+ this.handleUsers([session.user]);
2871
+ }
2872
+
2873
+ /**
2874
+ * Every message carries its author, so most of what arrives here is already known - only the users that actually
2875
+ * changed are stored, and the collection does not report a change for each message.
2876
+ */
2877
+ handleUsers(users) {
2878
+ const changedUsers = [];
2879
+ for (const newUser of users) {
2880
+ const oldUser = this.users.get(newUser.id);
2881
+ if (oldUser && isSameUser(oldUser, newUser)) {
2882
+ continue;
2883
+ }
2884
+ if (oldUser && oldUser.status !== newUser.status) {
2885
+ this.onlineStatus.emit('change', newUser);
2886
+ }
2887
+ changedUsers.push(newUser);
2888
+ }
2889
+ this.users.set(...changedUsers);
2890
+ }
2891
+ }
2892
+ function isSameUser(a, b) {
2893
+ const keys = Object.keys(a);
2894
+ if (keys.length !== Object.keys(b).length) {
2895
+ return false;
2896
+ }
2897
+ return keys.every(key => {
2898
+ const valueA = a[key];
2899
+ const valueB = b[key];
2900
+ if (Array.isArray(valueA) && Array.isArray(valueB)) {
2901
+ return valueA.length === valueB.length && valueA.every((item, index) => item === valueB[index]);
2902
+ }
2903
+ return valueA === valueB;
2904
+ });
2905
+ }
2906
+ ;// ./src/state-tracker/RelationshipsManager.ts
2907
+
2908
+
2909
+ const getId = (refUserId, type) => `${refUserId}-${type}`;
2910
+ const getIdFromRelationship = relationship => getId(relationship.refUser.id, relationship.type);
2911
+ class RelationshipsManager {
2912
+ relationships = new ObservableIndexedObjectCollection(getIdFromRelationship);
2913
+ promises = new PromiseRegistry();
2914
+ constructor(tracker) {
2915
+ this.tracker = tracker;
2916
+ this.tracker.client.on('Relationships', ev => this.handleRelationships(ev));
2917
+ this.tracker.client.on('NewRelationship', ev => this.handleNewRelationship(ev));
2918
+ this.tracker.client.on('RelationshipDeleted', ev => this.handleRelationshipDeleted(ev));
2919
+ this.tracker.client.on('Session', () => this.handleSession());
2920
+ }
2921
+ async get() {
2922
+ if (this.promises.notExist('all')) {
2923
+ this.promises.registerByFunction(async () => {
2924
+ const result = await this.tracker.client.send('GetRelationships', {});
2925
+ if (result.error) {
2926
+ throw result.error;
2927
+ }
2928
+ }, 'all');
2929
+ }
2930
+ await this.promises.get('all');
2931
+ return this.relationships;
2932
+ }
2933
+ async exists(refUserId, type) {
2934
+ await this.get();
2935
+ return this.relationships.has(getId(refUserId, type));
2936
+ }
2937
+ handleRelationships(ev) {
2938
+ // Full list from the server: reconcile in place so a reconnect refetch
2939
+ // updates a bound (visible) list without an intermediate empty state.
2940
+ this.relationships.reconcile(...ev.relationships);
2941
+ }
2942
+ handleNewRelationship(ev) {
2943
+ if (this.promises.has('all')) {
2944
+ this.relationships.set(ev.relationship);
2945
+ }
2946
+ }
2947
+ handleRelationshipDeleted(ev) {
2948
+ if (this.promises.has('all')) {
2949
+ this.relationships.delete(getIdFromRelationship(ev.relationship));
2950
+ }
2951
+ }
2952
+ handleSession() {
2953
+ // Keep the (possibly bound) collection; just drop the fetch guard so the
2954
+ // next get() refetches and reconciles it in place.
2955
+ this.promises.forgetAll();
2956
+ }
2957
+ }
2958
+ ;// ./src/state-tracker/ChatStateTracker.ts
2959
+
2960
+
2961
+
2962
+
2963
+
2964
+
2965
+
2966
+ class ChatStateTracker {
2967
+ client;
2968
+
2969
+ /**
2970
+ * State of your permissions.
2971
+ */
2972
+ permissions;
2973
+
2974
+ /**
2975
+ * State of the rooms you are in.
2976
+ */
2977
+ rooms;
2978
+
2979
+ /**
2980
+ * State of the spaces you are in.
2981
+ */
2982
+ spaces;
2983
+
2984
+ /**
2985
+ * State of the emoticons (global and space-related).
2986
+ */
2987
+ emoticons;
2988
+
2989
+ /**
2990
+ * Users related state.
2991
+ */
2992
+ users;
2993
+
2994
+ /**
2995
+ * State of relationships with other users.
2996
+ */
2997
+ relationships;
2998
+ _me = null;
2999
+ deferredSession = new DeferredTask();
3000
+ constructor(client) {
3001
+ this.client = client;
3002
+ this.client.on('Session', ev => this.handleSession(ev));
3003
+ this.permissions = new PermissionsManager(this);
3004
+ this.rooms = new RoomsManager(this);
3005
+ this.spaces = new SpacesManager(this);
3006
+ this.emoticons = new EmoticonsManager(this);
3007
+ this.users = new UsersManager(this);
3008
+ this.relationships = new RelationshipsManager(this);
3009
+ }
3010
+ get me() {
3011
+ return this._me;
3012
+ }
3013
+ async getMe() {
3014
+ await this.deferredSession.promise;
3015
+ return this._me;
3016
+ }
3017
+ handleSession(ev) {
3018
+ this._me = ev.user;
3019
+ this.deferredSession.resolve();
3020
+ }
3021
+ }
3022
+ ;// ./src/WebSocketChatClient.ts
3023
+
3024
+
3025
+ var WebSocketChatClientEvent = /*#__PURE__*/function (WebSocketChatClientEvent) {
3026
+ WebSocketChatClientEvent["connect"] = "connect";
3027
+ WebSocketChatClientEvent["disconnect"] = "disconnect";
3028
+ WebSocketChatClientEvent["message"] = "message";
3029
+ WebSocketChatClientEvent["error"] = "error";
3030
+ return WebSocketChatClientEvent;
3031
+ }(WebSocketChatClientEvent || {});
3032
+ class WebSocketChatClient extends AbstractChatClient {
3033
+ Event = WebSocketChatClientEvent;
3034
+ state;
3035
+ ws = null;
3036
+ sendQueue = [];
3037
+ connectingTimeoutId;
3038
+ authenticated;
3039
+ authenticatedResolvers = null;
3040
+ connectPromise = null;
3041
+ pingMonitorInterval;
3042
+ inFlightPingTimeout;
3043
+ lastReceivedMessageAt;
3044
+ reconnectEnabled = false;
3045
+ reconnectTimeoutId;
3046
+ reconnectAttempts = 0;
3047
+ constructor(options) {
3048
+ super();
3049
+ this.options = options;
3050
+ if (this.options.stateTracking ?? true) {
3051
+ this.state = new ChatStateTracker(this);
3052
+ }
3053
+ options.ping ??= {};
3054
+ options.ping.enabled ??= true;
3055
+ options.ping.noActivityTimeoutMs ??= 15000;
3056
+ options.ping.pongBackTimeoutMs ??= 5000;
3057
+ }
3058
+ async connect() {
3059
+ this.reconnectEnabled = true;
3060
+ // A manual call does not wait for a scheduled retry.
3061
+ this.cancelScheduledReconnect();
3062
+ if (this.isOpenWsState() || this.isConnectingWsState()) {
3063
+ return this.connectPromise ?? undefined;
3064
+ }
3065
+
3066
+ // Reuse the promise of an attempt that has not settled yet (an
3067
+ // automatic reconnect), so the caller that started connecting is
3068
+ // resolved by whichever attempt eventually authenticates.
3069
+ if (!this.connectPromise) {
3070
+ this.connectPromise = new Promise((...args) => this.authenticatedResolvers = args);
3071
+ // Automatic reconnects create this promise with no one awaiting it,
3072
+ // so its rejection must not surface as an unhandled one. Callers
3073
+ // awaiting it still receive the rejection.
3074
+ this.connectPromise.catch(() => undefined);
3075
+ }
3076
+ const connectPromise = this.connectPromise;
3077
+ this.openSocket();
3078
+ return connectPromise;
3079
+ }
3080
+ disconnect() {
3081
+ const wasActive = this.ws !== null || this.reconnectTimeoutId !== undefined;
3082
+ this.reconnectEnabled = false;
3083
+ this.reconnectAttempts = 0;
3084
+ this.cancelScheduledReconnect();
3085
+ this.releaseSocket(1000); // Normal closure
3086
+ this.failPendingCommands(new Error('Client disconnected before the command was answered'));
3087
+ this.settleConnect(new Error('Client disconnected before authentication'));
3088
+ if (wasActive) {
3089
+ this.emit(this.Event.disconnect, false);
3090
+ }
3091
+ }
3092
+ async send(commandType, commandData) {
3093
+ const envelope = this.createEnvelope(commandType, commandData);
3094
+ const promise = this.createPromiseFromCommandEnvelope(envelope);
3095
+ if (this.isConnectingWsState() || !this.authenticated && this.isOpenWsState()) {
3096
+ this.sendQueue.push(envelope);
3097
+ return promise;
3098
+ }
3099
+ this.sendEnvelope(envelope);
3100
+ return promise;
3101
+ }
3102
+ get isReady() {
3103
+ return this.isOpenWsState() && this.authenticated;
3104
+ }
3105
+ openSocket() {
3106
+ // Never leave a previous socket attached (e.g. one still closing).
3107
+ this.releaseSocket(1000);
3108
+ const params = new URLSearchParams(this.options.queryParams ?? {});
3109
+ params.set('token', this.options.token);
3110
+ let ws;
3111
+ try {
3112
+ ws = new WebSocket(`${this.options.url}?${params}`);
3113
+ } catch (error) {
3114
+ // Invalid URL - no retry can fix that.
3115
+ this.settleConnect(error);
3116
+ return;
3117
+ }
3118
+
3119
+ // Events of an abandoned socket must not touch the current connection.
3120
+ ws.onmessage = ev => ws === this.ws && this.onMessage(ev);
3121
+ ws.onclose = ev => ws === this.ws && this.onClose(ev);
3122
+ // Not every implementation follows a failed handshake with a close
3123
+ // event (e.g. Node.js), so an error alone means the connection is lost.
3124
+ ws.onerror = () => ws === this.ws && this.handleConnectionLoss(true);
3125
+ this.ws = ws;
3126
+ this.authenticated = false;
3127
+ this.connectingTimeoutId = setTimeout(() => this.triggerConnectionTimeout(), this.options.connectingTimeoutMs ?? 10000);
3128
+ }
3129
+ sendEnvelope(envelope) {
3130
+ if (this.isReady) {
3131
+ this.ws.send(JSON.stringify(envelope));
3132
+ return;
3133
+ }
3134
+ this.handleEnvelopeSendError(envelope, new Error(`Cannot send - client is not ready (state=${this.ws?.readyState ?? '[no connection]'}; authenticated=${this.authenticated})`));
3135
+ }
3136
+ onMessage(event) {
3137
+ this.lastReceivedMessageAt = Date.now();
3138
+ const envelope = JSON.parse(event.data);
3139
+ this.handleIncomingEnvelope(envelope);
3140
+ this.emit(envelope.type, envelope.data);
3141
+ this.emit(this.Event.message, envelope);
3142
+
3143
+ // Login successfully
3144
+ if (!this.authenticated) {
3145
+ const isAuthenticated = envelope.type !== 'Bye';
3146
+ this.authenticated = isAuthenticated;
3147
+ if (isAuthenticated) {
3148
+ this.reconnectAttempts = 0;
3149
+ this.startConnectionMonitor();
3150
+ this.settleConnect();
3151
+ this.emit(this.Event.connect);
3152
+ this.sendFromQueue();
3153
+ } else {
3154
+ this.settleConnect(envelope.data);
3155
+ const error = envelope.data?.reason?.error;
3156
+ if (error?.code === 'AuthenticationException') {
3157
+ // Invalid token - retrying would be rejected the same way.
3158
+ this.handleConnectionLoss(false);
3159
+ this.emit(this.Event.error, new Error(`Authentication rejected: ${error.message}`));
3160
+ }
3161
+ }
3162
+ }
3163
+ }
3164
+ onClose(event) {
3165
+ // Connection was closed because of error
3166
+ this.handleConnectionLoss(event.code !== 1000);
3167
+ }
3168
+
3169
+ /**
3170
+ * Abandon the current socket without waiting for its close event (which
3171
+ * may never come, or take minutes on a dead TCP connection), settle
3172
+ * everything that depended on it and schedule a retry when requested.
3173
+ */
3174
+ handleConnectionLoss(reconnect) {
3175
+ this.releaseSocket(reconnect ? 3000 : 1000);
3176
+
3177
+ // The server can no longer answer anything that was queued or in
3178
+ // flight, so settle those promises instead of leaving them pending.
3179
+ this.failPendingCommands(new Error('Connection closed before the command was answered'));
3180
+ reconnect &&= this.reconnectEnabled;
3181
+ if (reconnect) {
3182
+ // Keep a pending connect() promise unsettled - the retry below is
3183
+ // expected to authenticate and will resolve it.
3184
+ this.scheduleReconnect();
3185
+ } else {
3186
+ this.reconnectEnabled = false;
3187
+ this.settleConnect(new Error('Connection closed before authentication'));
3188
+ }
3189
+ this.emit(this.Event.disconnect, reconnect);
3190
+ }
3191
+
3192
+ /**
3193
+ * Detach the current socket from the client and close it if it is still
3194
+ * alive, together with all timers bound to it.
3195
+ */
3196
+ releaseSocket(closeCode) {
3197
+ this.stopConnectionMonitor();
3198
+ clearTimeout(this.connectingTimeoutId);
3199
+ this.connectingTimeoutId = undefined;
3200
+ this.authenticated = false;
3201
+ const ws = this.ws;
3202
+ this.ws = null;
3203
+ if (!ws) {
3204
+ return;
3205
+ }
3206
+ ws.onmessage = ws.onclose = ws.onerror = null;
3207
+ if (ws.readyState === ws.CONNECTING || ws.readyState === ws.OPEN) {
3208
+ try {
3209
+ ws.close(closeCode);
3210
+ } catch {
3211
+ // Nothing more can be done with a broken socket.
3212
+ }
3213
+ }
3214
+ }
3215
+ scheduleReconnect() {
3216
+ this.cancelScheduledReconnect();
3217
+ const minDelay = Math.max(0, this.options.reconnect?.minDelayMs ?? 1000);
3218
+ const maxDelay = Math.max(minDelay, this.options.reconnect?.maxDelayMs ?? 30000);
3219
+ const delay = Math.min(maxDelay, minDelay * 2 ** Math.min(this.reconnectAttempts, 30));
3220
+ this.reconnectAttempts++;
3221
+
3222
+ // Random jitter (50-100% of the delay) keeps clients from reconnecting
3223
+ // in lockstep after a server restart.
3224
+ this.reconnectTimeoutId = setTimeout(() => {
3225
+ this.reconnectTimeoutId = undefined;
3226
+ this.connect().catch(() => undefined);
3227
+ }, delay / 2 + Math.random() * delay / 2);
3228
+ }
3229
+ cancelScheduledReconnect() {
3230
+ clearTimeout(this.reconnectTimeoutId);
3231
+ this.reconnectTimeoutId = undefined;
3232
+ }
3233
+
3234
+ /**
3235
+ * Resolve (or reject, when an error is given) a pending connect() promise.
3236
+ * No-op when there is nothing pending.
3237
+ */
3238
+ settleConnect(error) {
3239
+ const resolvers = this.authenticatedResolvers;
3240
+ this.authenticatedResolvers = null;
3241
+ this.connectPromise = null;
3242
+ if (!resolvers) {
3243
+ return;
3244
+ }
3245
+ error ? resolvers[1](error) : resolvers[0]();
3246
+ }
3247
+
3248
+ /**
3249
+ * Reject every command that has not been answered yet - both the ones still
3250
+ * waiting in the send queue and the ones already sent to the server.
3251
+ */
3252
+ failPendingCommands(error) {
3253
+ const queued = this.sendQueue;
3254
+ this.sendQueue = [];
3255
+ for (const envelope of queued) {
3256
+ this.handleEnvelopeSendError(envelope, error);
3257
+ }
3258
+ this.failAwaitingResponses(error);
3259
+ }
3260
+ sendFromQueue() {
3261
+ // Send awaiting data to server
3262
+ let lastDelay = 0;
3263
+ for (const dataIndex in this.sendQueue) {
3264
+ const envelope = this.sendQueue[dataIndex];
3265
+ setTimeout(() => this.sendEnvelope(envelope), lastDelay);
3266
+ lastDelay += this.options.awaitQueueSendDelayMs ?? 500;
3267
+ }
3268
+ this.sendQueue = [];
3269
+ clearTimeout(this.connectingTimeoutId);
3270
+ }
3271
+ triggerConnectionTimeout() {
3272
+ this.handleConnectionLoss(true);
3273
+ this.emit(this.Event.error, new Error('Connection timeout'));
3274
+ }
3275
+ isConnectingWsState() {
3276
+ return this.ws && this.ws.readyState === this.ws.CONNECTING;
3277
+ }
3278
+ isOpenWsState() {
3279
+ return this.ws && this.ws.readyState === this.ws.OPEN;
3280
+ }
3281
+ startConnectionMonitor() {
3282
+ this.stopConnectionMonitor();
3283
+ if (!this.options.ping.enabled) {
3284
+ return;
3285
+ }
3286
+ this.lastReceivedMessageAt = Date.now();
3287
+ this.pingMonitorInterval = setInterval(async () => {
3288
+ if (!this.isReady || this.inFlightPingTimeout) {
3289
+ return;
3290
+ }
3291
+ if (Date.now() - this.lastReceivedMessageAt < this.options.ping.noActivityTimeoutMs) {
3292
+ return;
3293
+ }
3294
+ this.inFlightPingTimeout = setTimeout(() => {
3295
+ this.inFlightPingTimeout = undefined;
3296
+ // Closing a dead connection can hang in CLOSING for minutes,
3297
+ // so drop it right away instead of waiting for the close event.
3298
+ this.handleConnectionLoss(true);
3299
+ }, this.options.ping.pongBackTimeoutMs);
3300
+
3301
+ // A rejection here means the connection dropped while the ping was
3302
+ // in flight; the loss is already handled, so just stop waiting.
3303
+ this.send('Ping', {}).catch(() => undefined).then(() => {
3304
+ clearTimeout(this.inFlightPingTimeout);
3305
+ this.inFlightPingTimeout = undefined;
3306
+ });
3307
+ }, 1000);
3308
+ }
3309
+ stopConnectionMonitor() {
3310
+ if (this.inFlightPingTimeout) {
3311
+ clearTimeout(this.inFlightPingTimeout);
3312
+ this.inFlightPingTimeout = undefined;
3313
+ }
3314
+ if (this.pingMonitorInterval) {
3315
+ clearInterval(this.pingMonitorInterval);
3316
+ this.pingMonitorInterval = undefined;
3317
+ }
3318
+ }
3319
+ }
3320
+ ;// ./src/WebApiChatClient.ts
3321
+
3322
+ var WebApiChatClientEvent = /*#__PURE__*/function (WebApiChatClientEvent) {
3323
+ WebApiChatClientEvent["message"] = "message";
3324
+ WebApiChatClientEvent["error"] = "error";
3325
+ WebApiChatClientEvent["destroy"] = "destroy";
3326
+ return WebApiChatClientEvent;
3327
+ }(WebApiChatClientEvent || {});
3328
+ class WebApiChatClient extends AbstractChatClient {
3329
+ Event = WebApiChatClientEvent;
3330
+ sendStack = [];
3331
+ constructor(options) {
3332
+ super();
3333
+ this.options = options;
3334
+ }
3335
+ async send(commandType, commandData) {
3336
+ const envelope = this.createEnvelope(commandType, commandData);
3337
+ const item = {
3338
+ data: envelope,
3339
+ attempts: 0,
3340
+ lastTimeoutId: null
3341
+ };
3342
+ this.sendStack.push(item);
3343
+ this.makeApiCall(item);
3344
+ return this.createPromiseFromCommandEnvelope(envelope);
3345
+ }
3346
+ destroy() {
3347
+ // Cancel all awaiting requests, rejecting their promises so no caller
3348
+ // is left awaiting forever
3349
+ const pending = this.sendStack;
3350
+ this.sendStack = [];
3351
+ pending.forEach(item => {
3352
+ if (item.lastTimeoutId) {
3353
+ clearTimeout(item.lastTimeoutId);
3354
+ }
3355
+ this.handleEnvelopeSendError(item.data, new Error('Client destroyed'));
3356
+ });
3357
+ this.emit(this.Event.destroy, false);
3358
+ }
3359
+ async onMessage(item, response) {
3360
+ let envelope;
3361
+ try {
3362
+ envelope = await response.json();
3363
+ } catch (e) {
3364
+ // Non-envelope response (e.g. a proxy error page) - failed attempt
3365
+ this.onError(item, `envelope ${item.data.ref} (HTTP ${response.status}, unparsable body)`);
3366
+ return;
3367
+ }
3368
+ if (!this.removeFromStack(item)) {
3369
+ return; // Destroyed in the meantime - the promise is already rejected
3370
+ }
3371
+ this.handleIncomingEnvelope(envelope);
3372
+ this.emit(envelope.type, envelope.data);
3373
+ this.emit(this.Event.message, envelope);
3374
+ }
3375
+ onError(item, body) {
3376
+ if (!this.sendStack.includes(item)) {
3377
+ return; // Destroyed in the meantime
3378
+ }
3379
+ if (item.attempts >= (this.options.attemptsToSend ?? 10)) {
3380
+ this.removeFromStack(item);
3381
+ this.handleEnvelopeSendError(item.data, new Error(`Cannot send ${body}; aborting after reaching the maximum connection errors`));
3382
+ return;
3383
+ }
3384
+ item.lastTimeoutId = setTimeout(() => this.makeApiCall(item), this.options.attemptDelayMs ?? 3000);
3385
+ }
3386
+ makeApiCall(item) {
3387
+ if (!this.sendStack.includes(item)) {
3388
+ return; // Destroyed before this (re)try fired
3389
+ }
3390
+ item.attempts++;
3391
+ item.lastTimeoutId = null;
3392
+ const bodyJson = JSON.stringify(item.data);
3393
+ const headers = {
3394
+ 'Content-Type': 'application/json',
3395
+ Accept: 'application/json'
3396
+ };
3397
+ headers.Authorization = `Bearer ${this.options.token}`;
3398
+ const query = new URLSearchParams(this.options.queryParams ?? {}).toString();
3399
+ const url = query ? `${this.options.url}?${query}` : this.options.url;
3400
+ fetch(url, {
3401
+ headers,
3402
+ body: bodyJson,
3403
+ method: 'POST'
3404
+ }).then(response => this.onMessage(item, response)).catch(() => this.onError(item, bodyJson));
3405
+ }
3406
+ removeFromStack(item) {
3407
+ const index = this.sendStack.indexOf(item);
3408
+ if (index === -1) {
3409
+ return false;
3410
+ }
3411
+ this.sendStack.splice(index, 1);
3412
+ return true;
3413
+ }
3414
+ }
3415
+ ;// ./src/AbstractRestClient.ts
3416
+ class AbstractRestClient {
3417
+ constructor(options) {
3418
+ this.options = options;
3419
+ }
3420
+ async send(method, uri, data = undefined, additionalHeaders = {}) {
3421
+ let url = this.getUrl(uri);
3422
+ let body = undefined;
3423
+ if (data) {
3424
+ if (['GET', 'DELETE'].includes(method)) {
3425
+ url += '?' + new URLSearchParams(data).toString();
3426
+ } else {
3427
+ body = JSON.stringify(data);
3428
+ }
3429
+ }
3430
+ const headers = {
3431
+ 'Content-Type': 'application/json',
3432
+ Accept: 'application/json',
3433
+ ...additionalHeaders,
3434
+ ...this.getAuthHeaders()
3435
+ };
3436
+ const result = await fetch(url, {
3437
+ method,
3438
+ body,
3439
+ headers
3440
+ });
3441
+ return this.convertFetchResponse(result);
3442
+ }
3443
+ getAuthHeaders() {
3444
+ const headers = {};
3445
+ if (this.options.token) {
3446
+ headers.Authorization = `Bearer ${this.options.token}`;
3447
+ }
3448
+ return headers;
3449
+ }
3450
+ getUrl(uri) {
3451
+ return this.removeEndingSlash(this.options.url ?? this.defaultUrl) + '/' + this.removeStartingSlash(uri);
3452
+ }
3453
+ async convertFetchResponse(result) {
3454
+ return {
3455
+ ok: result.ok,
3456
+ status: result.status,
3457
+ data: result.headers.get('content-type')?.includes('json') ? await result.json() : await result.text()
3458
+ };
3459
+ }
3460
+ removeStartingSlash(text) {
3461
+ return text.replace(/^\/+/, '');
3462
+ }
3463
+ removeEndingSlash(text) {
3464
+ return text.replace(/\/+$/, '');
3465
+ }
3466
+ }
3467
+ ;// ./src/FilesClient.ts
3468
+
3469
+ class FilesClient extends AbstractRestClient {
3470
+ defaultUrl = 'https://files.devana.pl';
3471
+ async uploadFile(file) {
3472
+ const name = encodeURIComponent(file.name ?? '');
3473
+ let headers = {
3474
+ ...this.getAuthHeaders(),
3475
+ Accept: 'application/json',
3476
+ 'Content-Disposition': `attachment; filename="${name}"`,
3477
+ 'Content-Length': file.size
3478
+ };
3479
+ const response = await fetch(this.getUrl('files'), {
3480
+ method: 'POST',
3481
+ body: file,
3482
+ headers
3483
+ });
3484
+ return this.convertFetchResponse(response);
3485
+ }
3486
+ async getFileMeta(id) {
3487
+ return this.send('GET', 'files/' + id);
3488
+ }
3489
+ async getFileMetaBulk(ids) {
3490
+ const searchParams = new URLSearchParams();
3491
+ ids.forEach(id => searchParams.append('id[]', id));
3492
+ return this.send('GET', 'files?' + searchParams);
3493
+ }
3494
+ }
3495
+ ;// ./src/protocol/schemes/events/Error.ts
3496
+ let ErrorCode = /*#__PURE__*/function (ErrorCode) {
3497
+ ErrorCode["Authentication"] = "AuthenticationException";
3498
+ ErrorCode["CommandRateLimitExceeded"] = "CommandRateLimitExceededException";
3499
+ ErrorCode["InvalidSearchQuery"] = "InvalidSearchQueryException";
3500
+ ErrorCode["MessageSearchUnavailable"] = "MessageSearchUnavailableException";
3501
+ ErrorCode["MessageNotFound"] = "MessageNotFoundException";
3502
+ ErrorCode["RoomNotFound"] = "RoomNotFoundException";
3503
+ ErrorCode["TopicNotFound"] = "TopicNotFoundException";
3504
+ ErrorCode["UserNotFound"] = "UserNotFoundException";
3505
+ return ErrorCode;
3506
+ }({});
3507
+ ;// ./src/protocol/schemes/User.ts
3508
+ /**
3509
+ * Availability of a user, aggregated over all of their sessions.
3510
+ *
3511
+ * - `Offline` - no session is connected and none can be reached asynchronously.
3512
+ * - `Online` - at least one session holds a live connection.
3513
+ * - `OnlineAsync` - no live connection, but a push-registered device was active
3514
+ * recently, so a message will still reach the user.
3515
+ */
3516
+ let UserStatus = /*#__PURE__*/function (UserStatus) {
3517
+ UserStatus[UserStatus["Offline"] = 0] = "Offline";
3518
+ UserStatus[UserStatus["Online"] = 1] = "Online";
3519
+ UserStatus[UserStatus["OnlineAsync"] = 2] = "OnlineAsync";
3520
+ return UserStatus;
3521
+ }({});
3522
+ ;// ./src/protocol/schemes/Role.ts
3523
+ /**
3524
+ * Bit flags of a role, stored in {@link Role.flags}.
3525
+ *
3526
+ * - `SeparateOnMembersList` - available holders of the role are listed in their
3527
+ * own group of the members list, headed by the role name.
3528
+ * - `MentionableByEveryone` - anybody may mention the role with notification
3529
+ * effects; without it the mention is decorative only, unless the author holds
3530
+ * the `MentionAllRoles` permission.
3531
+ */
3532
+ let RoleFlag = /*#__PURE__*/function (RoleFlag) {
3533
+ RoleFlag[RoleFlag["SeparateOnMembersList"] = 1] = "SeparateOnMembersList";
3534
+ RoleFlag[RoleFlag["MentionableByEveryone"] = 2] = "MentionableByEveryone";
3535
+ return RoleFlag;
3536
+ }({});
3537
+ ;// ./src/protocol/schemes/Entitlements.ts
3538
+ /**
3539
+ * What a package is attached to. A space package and a user package never describe the same
3540
+ * feature, so entitlements of the two targets are never merged, summed or prioritised.
3541
+ */
3542
+
3543
+ /**
3544
+ * Subject the entitlements belong to, as the billing service knows it.
3545
+ */
3546
+
3547
+ /**
3548
+ * Value of a single entitlement: a flag, a numeric limit ({@link NO_LIMIT} means unlimited)
3549
+ * or a dictionary value. A dictionary states its numbers as strings.
3550
+ */
3551
+
3552
+ /**
3553
+ * Entitlement keys granted by the package, keyed by {@link SpaceFeature} or {@link UserFeature}.
3554
+ * A feature the package does not grant is simply absent.
3555
+ */
3556
+
3557
+ /**
3558
+ * What the modules of the chat server add to the answer of `GetEntitlements`. The package says
3559
+ * how much a subject may take, these say how much of it is already gone.
3560
+ */
3561
+
3562
+ /**
3563
+ * Value of a numeric limit that is not limited at all.
3564
+ */
3565
+ const NO_LIMIT = -1;
3566
+
3567
+ /**
3568
+ * Entitlement keys of space packages.
3569
+ */
3570
+ let SpaceFeature = /*#__PURE__*/function (SpaceFeature) {
3571
+ SpaceFeature["MembersLimit"] = "space.members.limit";
3572
+ SpaceFeature["MembersGuests"] = "space.members.guests";
3573
+ SpaceFeature["RoomsLimit"] = "space.rooms.limit";
3574
+ SpaceFeature["RoomsPrivateLimit"] = "space.rooms.private_limit";
3575
+ SpaceFeature["RoomsArchive"] = "space.rooms.archive";
3576
+ SpaceFeature["RoomsHistoryRotation"] = "space.rooms.history_rotation";
3577
+ SpaceFeature["EmoticonsLimit"] = "space.emoticons.limit";
3578
+ SpaceFeature["MessageLength"] = "space.message.length";
3579
+ SpaceFeature["StorageLimit"] = "space.storage.limit";
3580
+ SpaceFeature["StorageSingleFileLimit"] = "space.storage.single_file_limit";
3581
+ SpaceFeature["AccessWhitelist"] = "space.access.whitelist";
3582
+ SpaceFeature["SearchRange"] = "space.search.range";
3583
+ SpaceFeature["ContentExport"] = "space.content.export";
3584
+ SpaceFeature["ContentAuditLog"] = "space.content.auditlog";
3585
+ SpaceFeature["AvMemberLimit"] = "space.av.member_limit";
3586
+ SpaceFeature["AvBroadcasterLimit"] = "space.av.broadcaster_limit";
3587
+ SpaceFeature["AvQuality"] = "space.av.quality";
3588
+ SpaceFeature["UiPurpose"] = "app.ui.purpose";
3589
+ SpaceFeature["ApiAccess"] = "app.api.access";
3590
+ SpaceFeature["DataSovereignty"] = "app.data.sovereignty";
3591
+ SpaceFeature["Support"] = "app.support";
3592
+ return SpaceFeature;
3593
+ }({});
3594
+
3595
+ /**
3596
+ * Entitlement keys of user packages.
3597
+ */
3598
+ let UserFeature = /*#__PURE__*/function (UserFeature) {
3599
+ UserFeature["MessageLength"] = "user.message.length";
3600
+ UserFeature["StorageLimit"] = "user.storage.limit";
3601
+ UserFeature["StorageSingleFileLimit"] = "user.storage.single_file_limit";
3602
+ return UserFeature;
3603
+ }({});
3604
+
3605
+ /**
3606
+ * How far back a room of the space may be told to keep its history.
3607
+ */
3608
+ let HistoryRotation = /*#__PURE__*/function (HistoryRotation) {
3609
+ HistoryRotation["Low"] = "low";
3610
+ HistoryRotation["High"] = "high";
3611
+ return HistoryRotation;
3612
+ }({});
3613
+
3614
+ /**
3615
+ * What the space is for; a space for work gets the simplified interface.
3616
+ */
3617
+ let UiPurpose = /*#__PURE__*/function (UiPurpose) {
3618
+ UiPurpose["Work"] = "work";
3619
+ UiPurpose["Fun"] = "fun";
3620
+ return UiPurpose;
3621
+ }({});
3622
+
3623
+ /**
3624
+ * How much of the space search reaches.
3625
+ */
3626
+ let SearchRange = /*#__PURE__*/function (SearchRange) {
3627
+ SearchRange["JoinedRooms"] = "joined_rooms";
3628
+ SearchRange["AvailableRooms"] = "available_rooms";
3629
+ return SearchRange;
3630
+ }({});
3631
+
3632
+ /**
3633
+ * Every storage entitlement is stated in megabytes.
3634
+ */
3635
+ const STORAGE_UNIT_BYTES = 1024 * 1024;
3636
+ ;// ./src/protocol/schemes/Space.ts
3637
+ let SpaceIntent = /*#__PURE__*/function (SpaceIntent) {
3638
+ SpaceIntent["Community"] = "Community";
3639
+ SpaceIntent["Friends"] = "Friends";
3640
+ SpaceIntent["Team"] = "Team";
3641
+ return SpaceIntent;
3642
+ }({});
3643
+ ;// ./src/index.ts
3644
+
3645
+
3646
+
3647
+
3648
+
3649
+
3650
+
3651
+
3652
+
3653
+ module.exports = __webpack_exports__;
3654
+ /******/ })()
3655
+ ;
3656
+ //# sourceMappingURL=index.cjs.js.map