@devanachat/sdk 0.11.0 → 0.13.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 (38) hide show
  1. package/CHANGELOG.md +85 -0
  2. package/README.md +15 -7
  3. package/build/index.cjs.js +436 -144
  4. package/build/index.cjs.js.map +1 -1
  5. package/build/index.mjs +436 -145
  6. package/build/index.mjs.map +1 -1
  7. package/build/index.umd.js +1 -1
  8. package/build/index.umd.js.map +1 -1
  9. package/build/types/AbstractChatClient.d.ts +18 -3
  10. package/build/types/Permissions.d.ts +5 -1
  11. package/build/types/WebSocketChatClient.d.ts +29 -2
  12. package/build/types/index.d.ts +2 -2
  13. package/build/types/protocol/index.d.ts +15 -3
  14. package/build/types/protocol/schemes/Message.d.ts +4 -0
  15. package/build/types/protocol/schemes/MessageEmbed.d.ts +83 -0
  16. package/build/types/protocol/schemes/commands/AckInteraction.d.ts +10 -0
  17. package/build/types/protocol/schemes/commands/CreateMessage.d.ts +9 -0
  18. package/build/types/protocol/schemes/commands/GetGifCategories.d.ts +3 -0
  19. package/build/types/protocol/schemes/commands/GetMessages.d.ts +1 -0
  20. package/build/types/protocol/schemes/commands/Interact.d.ts +5 -0
  21. package/build/types/protocol/schemes/commands/SearchGifs.d.ts +5 -0
  22. package/build/types/protocol/schemes/commands/UpdateMessage.d.ts +8 -0
  23. package/build/types/protocol/schemes/events/Bye.d.ts +1 -0
  24. package/build/types/protocol/schemes/events/Error.d.ts +1 -0
  25. package/build/types/protocol/schemes/events/FoundGifs.d.ts +14 -0
  26. package/build/types/protocol/schemes/events/GifCategories.d.ts +8 -0
  27. package/build/types/protocol/schemes/events/Interacted.d.ts +4 -0
  28. package/build/types/protocol/schemes/events/InteractionResolved.d.ts +7 -0
  29. package/build/types/protocol/schemes/events/MessageUpdated.d.ts +6 -0
  30. package/build/types/protocol/schemes/events/Messages.d.ts +6 -2
  31. package/build/types/protocol/schemes/events/NewInteraction.d.ts +10 -0
  32. package/build/types/protocol/schemes/events/NewMessage.d.ts +3 -0
  33. package/build/types/state-tracker/RoomMessagesHistory.d.ts +7 -2
  34. package/build/types/state-tracker/RoomsManager.d.ts +12 -1
  35. package/build/types/state-tracker/StateSnapshot.d.ts +5 -1
  36. package/build/types/state-tracker/TopicHistoryWindow.d.ts +29 -2
  37. package/build/types/state-tracker/functions.d.ts +8 -1
  38. package/package.json +1 -1
package/build/index.mjs CHANGED
@@ -402,8 +402,116 @@ class PromiseRegistry {
402
402
  this.promises.deleteAll();
403
403
  }
404
404
  }
405
+ ;// ./src/protocol/schemes/PmParticipant.ts
406
+ let PmParticipantFlag = /*#__PURE__*/function (PmParticipantFlag) {
407
+ PmParticipantFlag[PmParticipantFlag["IgnoresRoom"] = 1] = "IgnoresRoom";
408
+ return PmParticipantFlag;
409
+ }({});
410
+ ;// ./src/state-tracker/functions.ts
411
+
412
+
413
+ /**
414
+ * @return New objects of the other roles whose priority has to move; the given roles are left intact.
415
+ */
416
+ function reorderRolesOnPriorityUpdate(allRoles, oldRole, updatedRole) {
417
+ // If the priority has changed, adjust the rest of roles
418
+ const increased = updatedRole.priority - oldRole.priority > 0;
419
+ const decreased = !increased;
420
+ const changedRoles = [];
421
+ allRoles.forEach(role => {
422
+ if (role.id === updatedRole.id) {
423
+ // Skip the updated role
424
+ return;
425
+ }
426
+ if (increased && oldRole.priority <= role.priority) {
427
+ changedRoles.push({
428
+ ...role,
429
+ priority: role.priority - 1
430
+ });
431
+ }
432
+ if (decreased && updatedRole.priority <= role.priority) {
433
+ changedRoles.push({
434
+ ...role,
435
+ priority: role.priority + 1
436
+ });
437
+ }
438
+ });
439
+ return changedRoles;
440
+ }
441
+ function extractUserFromMember(member) {
442
+ return member.user ?? member.spaceMember?.user;
443
+ }
444
+
445
+ /**
446
+ * Whether the room is a private group conversation - 3 or more participants, including the ones ignoring it.
447
+ */
448
+ function isGroupPm(room) {
449
+ return room.type === 'Pm' && (room.participants?.length ?? 0) >= 3;
450
+ }
451
+
452
+ /**
453
+ * Participants of a private conversation taking part in it: without the ones ignoring it and without the user
454
+ * `meId`. Empty for notes and for rooms of spaces.
455
+ */
456
+ function getPmPeers(room, meId) {
457
+ return getActivePmParticipants(room).filter(participant => participant.user.id !== meId);
458
+ }
459
+ function getActivePmParticipants(room) {
460
+ return (room.participants ?? []).filter(participant => !(participant.flags & PmParticipantFlag.IgnoresRoom));
461
+ }
462
+ function isSameUser(a, b) {
463
+ const keys = Object.keys(a);
464
+ if (keys.length !== Object.keys(b).length) {
465
+ return false;
466
+ }
467
+ return keys.every(key => {
468
+ const valueA = a[key];
469
+ const valueB = b[key];
470
+ if (Array.isArray(valueA) && Array.isArray(valueB)) {
471
+ return valueA.length === valueB.length && valueA.every((item, index) => item === valueB[index]);
472
+ }
473
+ return valueA === valueB;
474
+ });
475
+ }
476
+
477
+ /**
478
+ * The counter arrives as the global source of truth - only it is overwritten, and a reaction nobody holds any more
479
+ * (count 0) leaves the message.
480
+ * @return Null when the reactions stay as they are.
481
+ */
482
+ function applyReactionCounter(reactions, counter) {
483
+ const index = reactions.findIndex(reaction => reaction.type === counter.type && reaction.value === counter.value);
484
+ if (index === -1 && !counter.count) {
485
+ return null;
486
+ }
487
+ const next = [...reactions];
488
+ if (index === -1) {
489
+ next.push(counter);
490
+ } else if (counter.count) {
491
+ next[index] = counter; // In place - a pill must not jump around as its counter moves
492
+ } else {
493
+ next.splice(index, 1);
494
+ }
495
+ return next;
496
+ }
497
+ function applyToggledReaction(own, toggled) {
498
+ const {
499
+ type,
500
+ value,
501
+ isAdded
502
+ } = toggled;
503
+ const next = own.filter(reaction => reaction.type !== type || reaction.value !== value);
504
+ if (isAdded) {
505
+ next.push({
506
+ type,
507
+ value
508
+ });
509
+ }
510
+ return next;
511
+ }
405
512
  ;// ./src/state-tracker/TopicHistoryWindow.ts
406
513
 
514
+
407
515
  let WindowState = /*#__PURE__*/function (WindowState) {
408
516
  /**
409
517
  * The latest messages (those received live) are available in the history window, history has not been fetched.
@@ -781,6 +889,8 @@ class TopicHistoryWindow extends TraversableRemoteCollection {
781
889
  this.internalState.traverseLock = false;
782
890
  this.internalState.includeMyReactions = !preview;
783
891
  this.internalState.myReactions = {};
892
+ this.internalState.includeRepliedMessages = true;
893
+ this.internalState.repliedMessages = new Map();
784
894
  this.internalState.liveLimit = 50;
785
895
  }
786
896
  createMirror() {
@@ -820,6 +930,32 @@ class TopicHistoryWindow extends TraversableRemoteCollection {
820
930
  this.internalState.includeMyReactions = value;
821
931
  }
822
932
 
933
+ /**
934
+ * Whether the history is fetched together with the messages its messages reply to.
935
+ * Turn it off only where replies are never shown with what they reply to.
936
+ */
937
+ get includeRepliedMessages() {
938
+ return this.internalState.includeRepliedMessages;
939
+ }
940
+ set includeRepliedMessages(value) {
941
+ this.internalState.includeRepliedMessages = value;
942
+ }
943
+
944
+ /**
945
+ * The message the given one replies to: null when it replies to nothing or the replied message is gone,
946
+ * undefined when the window does not know it (replied messages are not fetched).
947
+ */
948
+ getRepliedMessage(message) {
949
+ if (!message.replyTo) {
950
+ return null;
951
+ }
952
+ const replied = this.get(message.replyTo) ?? this.internalState.repliedMessages.get(message.replyTo);
953
+ if (replied) {
954
+ return replied;
955
+ }
956
+ return this.internalState.includeRepliedMessages ? null : undefined;
957
+ }
958
+
823
959
  /**
824
960
  * Maximum number of items a window that has not been fetched yet (LIVE state) collects from the incoming
825
961
  * messages. Null for the same as {@link limit}. It keeps the windows of topics nobody looks at small;
@@ -884,14 +1020,21 @@ class TopicHistoryWindow extends TraversableRemoteCollection {
884
1020
  const continuousFrom = Math.max(0, ...this.internalState.gaps.map(id => items.findIndex(item => item.id === id)));
885
1021
  const messages = items.slice(Math.max(continuousFrom, items.length - Math.max(limit, this.fetchLimit)));
886
1022
  const myReactions = {};
1023
+ const exportedIds = new Set(messages.map(message => message.id));
1024
+ const repliedMessages = new Map();
887
1025
  for (const message of messages) {
888
1026
  if (this.internalState.myReactions[message.id]) {
889
1027
  myReactions[message.id] = this.internalState.myReactions[message.id];
890
1028
  }
1029
+ const replied = this.getRepliedMessage(message);
1030
+ if (replied && !exportedIds.has(replied.id)) {
1031
+ repliedMessages.set(replied.id, replied);
1032
+ }
891
1033
  }
892
1034
  return {
893
1035
  messages,
894
- myReactions
1036
+ myReactions,
1037
+ repliedMessages: [...repliedMessages.values()]
895
1038
  };
896
1039
  }
897
1040
 
@@ -900,12 +1043,13 @@ class TopicHistoryWindow extends TraversableRemoteCollection {
900
1043
  * them.
901
1044
  * @internal
902
1045
  */
903
- _restoreLatest(messages, myReactions) {
1046
+ _restoreLatest(messages, myReactions, repliedMessages) {
904
1047
  const originalState = this.state;
905
1048
  this.replaceItems(messages);
906
1049
  this.internalState.myReactions = {
907
1050
  ...myReactions
908
1051
  };
1052
+ this.storeRepliedMessages(messages, repliedMessages);
909
1053
  this.internalState.current = WindowState.LATEST;
910
1054
  this.emitChangeWithDiff(true, originalState);
911
1055
  }
@@ -956,12 +1100,14 @@ class TopicHistoryWindow extends TraversableRemoteCollection {
956
1100
  },
957
1101
  limit: this.internalState.fetchLimit,
958
1102
  includeMyReactions: this.internalState.includeMyReactions,
1103
+ includeRepliedMessages: this.internalState.includeRepliedMessages,
959
1104
  ...criteria
960
1105
  });
961
1106
  if (result.error) {
962
1107
  throw new Error(`Cannot fetch messages: ${result.error.message}`);
963
1108
  }
964
- this.storeMyReactions(result.data.messages, result.data.myReactions);
1109
+ this.storeMyReactions(result.data.messages, result.data.myReactions ?? []);
1110
+ this.storeRepliedMessages(result.data.messages, result.data.repliedMessages ?? []);
965
1111
  return result.data.messages;
966
1112
  }
967
1113
 
@@ -977,15 +1123,63 @@ class TopicHistoryWindow extends TraversableRemoteCollection {
977
1123
  ...this.internalState.myReactions
978
1124
  };
979
1125
  for (const message of messages) {
980
- const own = myReactions?.[message.id];
981
- if (own?.length) {
982
- next[message.id] = own;
983
- } else {
984
- delete next[message.id];
1126
+ delete next[message.id];
1127
+ }
1128
+ for (const own of myReactions) {
1129
+ if (own.reactions.length) {
1130
+ next[own.messageId] = own.reactions;
985
1131
  }
986
1132
  }
987
1133
  this.internalState.myReactions = next;
988
1134
  }
1135
+
1136
+ /**
1137
+ * The response is the truth for its replies: an original it leaves out is gone. The originals the page holds
1138
+ * itself are kept too, as the window may drop them while their replies stay.
1139
+ */
1140
+ storeRepliedMessages(incoming, repliedMessages) {
1141
+ if (!this.internalState.includeRepliedMessages) {
1142
+ return;
1143
+ }
1144
+ const fromResponse = new Map();
1145
+ for (const message of [...incoming, ...repliedMessages]) {
1146
+ fromResponse.set(message.id, message);
1147
+ }
1148
+ const stored = this.internalState.repliedMessages;
1149
+ const kept = new Map();
1150
+ for (const message of incoming) {
1151
+ const replied = message.replyTo ? fromResponse.get(message.replyTo) : undefined;
1152
+ if (replied) {
1153
+ kept.set(replied.id, replied);
1154
+ }
1155
+ }
1156
+ for (const message of this.items) {
1157
+ if (!message.replyTo || fromResponse.has(message.id) || kept.has(message.replyTo)) {
1158
+ continue;
1159
+ }
1160
+ const replied = stored.get(message.replyTo) ?? this.get(message.replyTo);
1161
+ if (replied) {
1162
+ kept.set(replied.id, replied);
1163
+ }
1164
+ }
1165
+ this.internalState.repliedMessages = kept;
1166
+ }
1167
+ emitChange(setItems) {
1168
+ if (setItems.length) {
1169
+ this.eventTarget.emit('change', {
1170
+ setItems
1171
+ });
1172
+ }
1173
+ }
1174
+ repliesTo(repliedIds) {
1175
+ const replyIds = [];
1176
+ for (const message of this.items) {
1177
+ if (message.replyTo && repliedIds.has(message.replyTo)) {
1178
+ replyIds.push(message.id);
1179
+ }
1180
+ }
1181
+ return replyIds;
1182
+ }
989
1183
  async getTopic() {
990
1184
  if (this.preview) {
991
1185
  // The tracker holds the topics of the joined rooms only
@@ -1017,7 +1211,15 @@ class TopicHistoryWindow extends TraversableRemoteCollection {
1017
1211
  return;
1018
1212
  }
1019
1213
  const limit = this.state === WindowState.LIVE && !this.internalState.traverseLock ? this.internalState.liveLimit ?? this.limit : this.limit;
1214
+ if (ev.repliedMessage && this.internalState.includeRepliedMessages) {
1215
+ this.internalState.repliedMessages.set(ev.repliedMessage.id, ev.repliedMessage);
1216
+ }
1020
1217
  const deletedItems = this.addItems([ev.message], 'tail', limit);
1218
+
1219
+ // Pruned only once the store outgrows the window, not on every message that pushes one out
1220
+ if (deletedItems.length && this.internalState.repliedMessages.size > this.length) {
1221
+ this.storeRepliedMessages([], []);
1222
+ }
1021
1223
  this.eventTarget.emit('change', deletedItems.length ? {
1022
1224
  setItems: [ev.message.id],
1023
1225
  deletedItems
@@ -1034,25 +1236,13 @@ class TopicHistoryWindow extends TraversableRemoteCollection {
1034
1236
  */
1035
1237
  _handleReactionUpdated(ev) {
1036
1238
  const message = this.get(ev.messageId);
1037
- if (!message) {
1038
- return;
1039
- }
1040
- const index = message.reactions.findIndex(reaction => reaction.type === ev.reaction.type && reaction.value === ev.reaction.value);
1041
- if (index === -1 && !ev.reaction.count) {
1042
- return;
1043
- }
1044
- const reactions = [...message.reactions];
1045
- if (index === -1) {
1046
- reactions.push(ev.reaction);
1047
- } else if (ev.reaction.count) {
1048
- reactions[index] = ev.reaction; // In place - a pill must not jump around as its counter moves
1049
- } else {
1050
- reactions.splice(index, 1);
1239
+ const reactions = message ? applyReactionCounter(message.reactions, ev.reaction) : null;
1240
+ if (reactions) {
1241
+ this.set({
1242
+ ...message,
1243
+ reactions
1244
+ });
1051
1245
  }
1052
- this.set({
1053
- ...message,
1054
- reactions
1055
- });
1056
1246
  }
1057
1247
 
1058
1248
  /**
@@ -1063,18 +1253,7 @@ class TopicHistoryWindow extends TraversableRemoteCollection {
1063
1253
  if (!this.has(ev.messageId)) {
1064
1254
  return;
1065
1255
  }
1066
- const {
1067
- type,
1068
- value,
1069
- isAdded
1070
- } = ev.reaction;
1071
- const own = (this.internalState.myReactions[ev.messageId] ?? []).filter(reaction => reaction.type !== type || reaction.value !== value);
1072
- if (isAdded) {
1073
- own.push({
1074
- type,
1075
- value
1076
- });
1077
- }
1256
+ const own = applyToggledReaction(this.internalState.myReactions[ev.messageId] ?? [], ev.reaction);
1078
1257
 
1079
1258
  // Not `{[ev.messageId]: _, ...rest}` - Babel's loose object rest drops the key when the binding is unused (babel/babel#18196)
1080
1259
  const myReactions = {
@@ -1090,13 +1269,39 @@ class TopicHistoryWindow extends TraversableRemoteCollection {
1090
1269
  });
1091
1270
  }
1092
1271
 
1272
+ /**
1273
+ * Replaces a loaded message, also where it is kept as a replied one.
1274
+ * For internal use.
1275
+ * @internal
1276
+ */
1277
+ _handleMessageUpdated(ev) {
1278
+ const {
1279
+ message
1280
+ } = ev;
1281
+ const loaded = this.has(message.id);
1282
+ const kept = this.internalState.repliedMessages.has(message.id);
1283
+ if (loaded) {
1284
+ this.set(message);
1285
+ }
1286
+ if (kept) {
1287
+ this.internalState.repliedMessages.set(message.id, message);
1288
+ }
1289
+ if (loaded || kept) {
1290
+ this.emitChange(this.repliesTo(new Set([message.id])));
1291
+ }
1292
+ }
1293
+
1093
1294
  /**
1094
1295
  * For internal use.
1095
1296
  * @internal
1096
1297
  */
1097
1298
  async _handleMessagesRedacted(ev) {
1098
1299
  const refTopicIds = this.items.filter(msg => msg.topicRef && ev.ids.includes(msg.id)).map(msg => msg.topicRef);
1300
+ const redactedOriginals = new Set(ev.ids.filter(id => this.internalState.repliedMessages.delete(id) || this.has(id)));
1099
1301
  this.delete(...ev.ids);
1302
+ if (redactedOriginals.size) {
1303
+ this.emitChange(this.repliesTo(redactedOriginals));
1304
+ }
1100
1305
  if (this.length === 0) {
1101
1306
  await this.resetToLatest();
1102
1307
  }
@@ -1220,9 +1425,9 @@ class RoomMessagesHistory {
1220
1425
  * For internal use.
1221
1426
  * @internal
1222
1427
  */
1223
- _restoreWindow(topic, messages, myReactions) {
1428
+ _restoreWindow(topic, messages, myReactions, repliedMessages) {
1224
1429
  this.createHistoryWindowForTopic(topic);
1225
- this.historyWindows.get(topic.id)._restoreLatest(messages, myReactions);
1430
+ this.historyWindows.get(topic.id)._restoreLatest(messages, myReactions, repliedMessages);
1226
1431
  }
1227
1432
 
1228
1433
  /**
@@ -1272,6 +1477,14 @@ class RoomMessagesHistory {
1272
1477
  void this.historyWindows.get(ev.location.topicId)?._handleMessagesRedacted(ev);
1273
1478
  }
1274
1479
 
1480
+ /**
1481
+ * For internal use.
1482
+ * @internal
1483
+ */
1484
+ _handleMessageUpdated(ev) {
1485
+ this.historyWindows.get(ev.message.location.topicId)?._handleMessageUpdated(ev);
1486
+ }
1487
+
1275
1488
  /**
1276
1489
  * For internal use.
1277
1490
  * @internal
@@ -1343,6 +1556,7 @@ class MessagesManager {
1343
1556
  this.tracker.client.on('NewTopic', ev => this.roomHistories.get(ev.roomId)?._handleNewTopic(ev));
1344
1557
  this.tracker.client.on('TopicDeleted', ev => this.roomHistories.get(ev.location.roomId)?._handleTopicDeleted(ev));
1345
1558
  this.tracker.client.on('NewMessage', ev => this.roomHistories.get(ev.message.location.roomId)?._handleNewMessage(ev));
1559
+ this.tracker.client.on('MessageUpdated', ev => this.roomHistories.get(ev.message.location.roomId)?._handleMessageUpdated(ev));
1346
1560
  this.tracker.client.on('MessagesRedacted', ev => this.roomHistories.get(ev.location.roomId)?._handleMessagesRedacted(ev));
1347
1561
  this.tracker.client.on('ReactionUpdated', ev => this.forEachRoomHistory(history => history._handleReactionUpdated(ev)));
1348
1562
  this.tracker.client.on('Reacted', ev => this.forEachRoomHistory(history => history._handleReacted(ev)));
@@ -1418,7 +1632,7 @@ class MessagesManager {
1418
1632
  const history = this.roomHistories.get(roomId);
1419
1633
  if (history && !history._isEphemeral) {
1420
1634
  const messages = snapshot.messages.filter(message => message.location.roomId === roomId && message.location.topicId === topic.id);
1421
- history._restoreWindow(topic, messages, snapshot.myReactions);
1635
+ history._restoreWindow(topic, messages, snapshot.myReactions, snapshot.repliedMessages);
1422
1636
  }
1423
1637
  }
1424
1638
  forEachRoomHistory(callback) {
@@ -2026,7 +2240,7 @@ let UserStatus = /*#__PURE__*/function (UserStatus) {
2026
2240
  /**
2027
2241
  * Version of the {@link StateSnapshot} format. A snapshot of any other version is rejected on import.
2028
2242
  */
2029
- const STATE_SNAPSHOT_VERSION = 2;
2243
+ const STATE_SNAPSHOT_VERSION = 3;
2030
2244
 
2031
2245
  /**
2032
2246
  * Plain, JSON-serializable copy of the state tracked by {@link ChatStateTracker}, made to restore the state at the
@@ -2136,7 +2350,7 @@ function isUserReactions(value) {
2136
2350
  return isObject(value) && Object.values(value).every(reactions => isArrayOf(reactions, isObject));
2137
2351
  }
2138
2352
  function isTopicHistory(value) {
2139
- return isObject(value) && isString(value.roomId) && isString(value.topicId) && isArrayOf(value.messages, isFullMessage) && isUserReactions(value.myReactions) && isArrayOf(value.topics, isTopic);
2353
+ return isObject(value) && isString(value.roomId) && isString(value.topicId) && isArrayOf(value.messages, isFullMessage) && isUserReactions(value.myReactions) && isArrayOf(value.repliedMessages, isFullMessage) && isArrayOf(value.topics, isTopic);
2140
2354
  }
2141
2355
  function isRoomMember(value) {
2142
2356
  return isObject(value) && (isUser(value.user) || isObject(value.spaceMember) && isUser(value.spaceMember.user));
@@ -2144,77 +2358,6 @@ function isRoomMember(value) {
2144
2358
  function isRoomMembers(value) {
2145
2359
  return isObject(value) && isString(value.roomId) && isArrayOf(value.members, isRoomMember);
2146
2360
  }
2147
- ;// ./src/protocol/schemes/PmParticipant.ts
2148
- let PmParticipantFlag = /*#__PURE__*/function (PmParticipantFlag) {
2149
- PmParticipantFlag[PmParticipantFlag["IgnoresRoom"] = 1] = "IgnoresRoom";
2150
- return PmParticipantFlag;
2151
- }({});
2152
- ;// ./src/state-tracker/functions.ts
2153
-
2154
-
2155
- /**
2156
- * @return New objects of the other roles whose priority has to move; the given roles are left intact.
2157
- */
2158
- function reorderRolesOnPriorityUpdate(allRoles, oldRole, updatedRole) {
2159
- // If the priority has changed, adjust the rest of roles
2160
- const increased = updatedRole.priority - oldRole.priority > 0;
2161
- const decreased = !increased;
2162
- const changedRoles = [];
2163
- allRoles.forEach(role => {
2164
- if (role.id === updatedRole.id) {
2165
- // Skip the updated role
2166
- return;
2167
- }
2168
- if (increased && oldRole.priority <= role.priority) {
2169
- changedRoles.push({
2170
- ...role,
2171
- priority: role.priority - 1
2172
- });
2173
- }
2174
- if (decreased && updatedRole.priority <= role.priority) {
2175
- changedRoles.push({
2176
- ...role,
2177
- priority: role.priority + 1
2178
- });
2179
- }
2180
- });
2181
- return changedRoles;
2182
- }
2183
- function extractUserFromMember(member) {
2184
- return member.user ?? member.spaceMember?.user;
2185
- }
2186
-
2187
- /**
2188
- * Whether the room is a private group conversation - 3 or more participants, including the ones ignoring it.
2189
- */
2190
- function isGroupPm(room) {
2191
- return room.type === 'Pm' && (room.participants?.length ?? 0) >= 3;
2192
- }
2193
-
2194
- /**
2195
- * Participants of a private conversation taking part in it: without the ones ignoring it and without the user
2196
- * `meId`. Empty for notes and for rooms of spaces.
2197
- */
2198
- function getPmPeers(room, meId) {
2199
- return getActivePmParticipants(room).filter(participant => participant.user.id !== meId);
2200
- }
2201
- function getActivePmParticipants(room) {
2202
- return (room.participants ?? []).filter(participant => !(participant.flags & PmParticipantFlag.IgnoresRoom));
2203
- }
2204
- function isSameUser(a, b) {
2205
- const keys = Object.keys(a);
2206
- if (keys.length !== Object.keys(b).length) {
2207
- return false;
2208
- }
2209
- return keys.every(key => {
2210
- const valueA = a[key];
2211
- const valueB = b[key];
2212
- if (Array.isArray(valueA) && Array.isArray(valueB)) {
2213
- return valueA.length === valueB.length && valueA.every((item, index) => item === valueB[index]);
2214
- }
2215
- return valueA === valueB;
2216
- });
2217
- }
2218
2361
  ;// ./src/state-tracker/RoomsManager.ts
2219
2362
 
2220
2363
 
@@ -2234,6 +2377,8 @@ class RoomsManager {
2234
2377
  membersPromises = new PromiseRegistry();
2235
2378
  topicsPromises = new PromiseRegistry();
2236
2379
  importedTopicIds = new Map();
2380
+ stickyMyReactions = new ObservableIndexedObjectCollection('messageId');
2381
+ stickyMyReactionsPromises = new PromiseRegistry();
2237
2382
  constructor(tracker) {
2238
2383
  this.tracker = tracker;
2239
2384
  this.messages = new MessagesManager(tracker);
@@ -2241,6 +2386,9 @@ class RoomsManager {
2241
2386
  this.typing = new TypingManager(tracker);
2242
2387
  this.tracker.client.on('NewMessage', ev => this.handleNewMessage(ev));
2243
2388
  this.tracker.client.on('MessagesRedacted', ev => this.handleMessagesRedacted(ev));
2389
+ this.tracker.client.on('MessageUpdated', ev => this.handleMessageUpdated(ev));
2390
+ this.tracker.client.on('ReactionUpdated', ev => this.handleReactionUpdated(ev));
2391
+ this.tracker.client.on('Reacted', ev => this.handleReacted(ev));
2244
2392
  this.tracker.client.on('NewTopic', ev => this.handleNewTopic(ev));
2245
2393
  this.tracker.client.on('TopicDeleted', ev => this.handleTopicDeleted(ev));
2246
2394
  this.tracker.client.on('RoomJoined', ev => this.handleRoomJoined(ev));
@@ -2279,6 +2427,34 @@ class RoomsManager {
2279
2427
  return this.members.get(roomId);
2280
2428
  }
2281
2429
 
2430
+ /**
2431
+ * Get the reactions of the connected user on sticky messages, keyed by message id. A sticky message comes with its
2432
+ * topic, outside of the message history, so the reactions of the given one are fetched once and then follow
2433
+ * the reactions of the user.
2434
+ */
2435
+ async getStickyMyReactions(location, messageId) {
2436
+ if (this.stickyMyReactionsPromises.notExist(messageId)) {
2437
+ this.stickyMyReactionsPromises.registerByFunction(async () => {
2438
+ const result = await this.tracker.client.send('GetMessages', {
2439
+ location,
2440
+ around: messageId,
2441
+ limit: 1,
2442
+ includeMyReactions: true
2443
+ });
2444
+ if (result.error) {
2445
+ throw result.error;
2446
+ }
2447
+ const own = result.data.myReactions?.find(item => item.messageId === messageId);
2448
+ this.stickyMyReactions.set({
2449
+ messageId,
2450
+ reactions: own?.reactions ?? []
2451
+ });
2452
+ }, messageId);
2453
+ }
2454
+ await this.stickyMyReactionsPromises.get(messageId);
2455
+ return this.stickyMyReactions;
2456
+ }
2457
+
2282
2458
  /**
2283
2459
  * Get a room member representing the current user.
2284
2460
  */
@@ -2404,6 +2580,7 @@ class RoomsManager {
2404
2580
  topicId,
2405
2581
  messages: latest.messages.map(messageWithoutPresence),
2406
2582
  myReactions: latest.myReactions,
2583
+ repliedMessages: latest.repliedMessages.map(messageWithoutPresence),
2407
2584
  topics: Array.from(topicIds).filter(id => topics?.has(id)).map(id => topics.get(id))
2408
2585
  });
2409
2586
  }
@@ -2680,6 +2857,8 @@ class RoomsManager {
2680
2857
  // so bound views refresh in place without blanking.
2681
2858
  this.membersPromises.forgetAll();
2682
2859
  this.topicsPromises.forgetAll();
2860
+ // Reactions could change meanwhile, and missed changes never arrive
2861
+ this.stickyMyReactionsPromises.forgetAll();
2683
2862
 
2684
2863
  // Upsert surviving/new rooms from the authoritative snapshot.
2685
2864
  this.addJoinedRooms(...ev.state.rooms);
@@ -2722,6 +2901,10 @@ class RoomsManager {
2722
2901
  this.list.set(...newRooms);
2723
2902
  }
2724
2903
  handleNewMessage(ev) {
2904
+ // Shown to one user and never stored, so it is neither counted nor the last message of the topic
2905
+ if (ev.message.type === 'Ephemeral') {
2906
+ return;
2907
+ }
2725
2908
  const topics = this.topics.get(ev.message.location.roomId);
2726
2909
  const topic = topics?.get(ev.message.location.topicId);
2727
2910
  if (!topic) {
@@ -2736,7 +2919,59 @@ class RoomsManager {
2736
2919
  topics.set(newTopic);
2737
2920
  this.updatePmDefaultTopic(ev.message.location.roomId, newTopic);
2738
2921
  }
2922
+ handleMessageUpdated(ev) {
2923
+ const topics = this.topics.get(ev.message.location.roomId);
2924
+ const refTopic = ev.message.topicRef ? topics?.get(ev.message.topicRef) : undefined;
2925
+ if (refTopic?.refMessage?.id === ev.message.id) {
2926
+ topics.set({
2927
+ ...refTopic,
2928
+ refMessage: ev.message
2929
+ });
2930
+ }
2931
+ const topic = topics?.get(ev.message.location.topicId);
2932
+ const isLast = topic?.lastMessage?.id === ev.message.id;
2933
+ const isSticky = topic?.stickyMessage?.id === ev.message.id;
2934
+ if (!topic || !isLast && !isSticky) {
2935
+ return;
2936
+ }
2937
+ const newTopic = {
2938
+ ...topic,
2939
+ lastMessage: isLast ? ev.message : topic.lastMessage,
2940
+ stickyMessage: isSticky ? ev.message : topic.stickyMessage
2941
+ };
2942
+ topics.set(newTopic);
2943
+ this.updatePmDefaultTopic(ev.message.location.roomId, newTopic);
2944
+ }
2945
+ handleReactionUpdated(ev) {
2946
+ for (const [roomId, topics] of this.topics.items) {
2947
+ for (const topic of topics.items) {
2948
+ const reactions = topic.stickyMessage?.id === ev.messageId ? applyReactionCounter(topic.stickyMessage.reactions, ev.reaction) : null;
2949
+ if (reactions) {
2950
+ const newTopic = {
2951
+ ...topic,
2952
+ stickyMessage: {
2953
+ ...topic.stickyMessage,
2954
+ reactions
2955
+ }
2956
+ };
2957
+ topics.set(newTopic);
2958
+ this.updatePmDefaultTopic(roomId, newTopic);
2959
+ }
2960
+ }
2961
+ }
2962
+ }
2963
+ handleReacted(ev) {
2964
+ const own = this.stickyMyReactions.get(ev.messageId);
2965
+ if (own) {
2966
+ this.stickyMyReactions.set({
2967
+ messageId: own.messageId,
2968
+ reactions: applyToggledReaction(own.reactions, ev.reaction)
2969
+ });
2970
+ }
2971
+ }
2739
2972
  async handleMessagesRedacted(ev) {
2973
+ this.stickyMyReactions.delete(...ev.ids);
2974
+
2740
2975
  // Remove redacted messages from topic and update metadata
2741
2976
  const topics = this.topics.get(ev.location.roomId);
2742
2977
  const topic = topics?.get(ev.location.topicId);
@@ -3204,7 +3439,7 @@ class Permissions {
3204
3439
  value: 1 << 18,
3205
3440
  maxLayer: Layer.Room
3206
3441
  },
3207
- RedactMessages: {
3442
+ ManageMessages: {
3208
3443
  value: 1 << 19,
3209
3444
  maxLayer: Layer.Topic
3210
3445
  },
@@ -3243,6 +3478,10 @@ class Permissions {
3243
3478
  SendAttachments: {
3244
3479
  value: 1 << 28,
3245
3480
  maxLayer: Layer.Topic
3481
+ },
3482
+ EditMessages: {
3483
+ value: 1 << 29,
3484
+ maxLayer: Layer.Topic
3246
3485
  }
3247
3486
  };
3248
3487
  static getNames() {
@@ -3948,6 +4187,12 @@ class ChatStateTracker {
3948
4187
  ;// ./src/WebSocketChatClient.ts
3949
4188
 
3950
4189
 
4190
+ const MAX_RETRY_AFTER_MS = 60000;
4191
+ // Going Away, Service Restart, Try Again Later
4192
+ const SERVER_CLOSE_CODES = [1001, 1012, 1013];
4193
+ function normalizeRetryAfter(retryAfterMs) {
4194
+ return typeof retryAfterMs === 'number' && Number.isFinite(retryAfterMs) && retryAfterMs > 0 ? Math.min(retryAfterMs, MAX_RETRY_AFTER_MS) : undefined;
4195
+ }
3951
4196
  var WebSocketChatClientEvent = /*#__PURE__*/function (WebSocketChatClientEvent) {
3952
4197
  WebSocketChatClientEvent["connect"] = "connect";
3953
4198
  WebSocketChatClientEvent["disconnect"] = "disconnect";
@@ -3970,6 +4215,10 @@ class WebSocketChatClient extends AbstractChatClient {
3970
4215
  reconnectEnabled = false;
3971
4216
  reconnectTimeoutId;
3972
4217
  reconnectAttempts = 0;
4218
+ serverClosedSinceStable = false;
4219
+ byeReceived = false;
4220
+ byeRetryAfterMs;
4221
+ stableConnectionTimeoutId;
3973
4222
  constructor(options) {
3974
4223
  super();
3975
4224
  this.options = options;
@@ -4006,7 +4255,7 @@ class WebSocketChatClient extends AbstractChatClient {
4006
4255
  disconnect() {
4007
4256
  const wasActive = this.ws !== null || this.reconnectTimeoutId !== undefined;
4008
4257
  this.reconnectEnabled = false;
4009
- this.reconnectAttempts = 0;
4258
+ this.resetBackoff();
4010
4259
  this.cancelScheduledReconnect();
4011
4260
  this.releaseSocket(1000); // Normal closure
4012
4261
  this.failPendingCommands(new Error('Client disconnected before the command was answered'));
@@ -4048,9 +4297,16 @@ class WebSocketChatClient extends AbstractChatClient {
4048
4297
  // Not every implementation follows a failed handshake with a close
4049
4298
  // event (e.g. Node.js), so an error alone means the connection is lost.
4050
4299
  ws.onerror = () => ws === this.ws && this.handleConnectionLoss(true);
4300
+ ws.onopen = () => ws === this.ws && this.startConnectingTimeout(this.options.sessionTimeoutMs ?? 60000);
4051
4301
  this.ws = ws;
4052
4302
  this.authenticated = false;
4053
- this.connectingTimeoutId = setTimeout(() => this.triggerConnectionTimeout(), this.options.connectingTimeoutMs ?? 10000);
4303
+ this.byeReceived = false;
4304
+ this.byeRetryAfterMs = undefined;
4305
+ this.startConnectingTimeout(this.options.connectingTimeoutMs ?? 10000);
4306
+ }
4307
+ startConnectingTimeout(timeoutMs) {
4308
+ clearTimeout(this.connectingTimeoutId);
4309
+ this.connectingTimeoutId = setTimeout(() => this.triggerConnectionTimeout(), timeoutMs);
4054
4310
  }
4055
4311
  sendEnvelope(envelope) {
4056
4312
  if (this.isReady) {
@@ -4062,34 +4318,52 @@ class WebSocketChatClient extends AbstractChatClient {
4062
4318
  onMessage(event) {
4063
4319
  this.lastReceivedMessageAt = Date.now();
4064
4320
  const envelope = JSON.parse(event.data);
4321
+ const ws = this.ws;
4065
4322
  this.handleIncomingEnvelope(envelope);
4066
4323
  this.emit(envelope.type, envelope.data);
4067
4324
  this.emit(this.Event.message, envelope);
4068
4325
 
4326
+ // A listener has called disconnect() or connect(), which settled this socket already.
4327
+ if (ws !== this.ws) {
4328
+ return;
4329
+ }
4330
+ if (envelope.type === 'Bye') {
4331
+ this.onBye(envelope.data);
4332
+ return;
4333
+ }
4334
+
4069
4335
  // Login successfully
4070
4336
  if (!this.authenticated) {
4071
- const isAuthenticated = envelope.type !== 'Bye';
4072
- this.authenticated = isAuthenticated;
4073
- if (isAuthenticated) {
4074
- this.reconnectAttempts = 0;
4075
- this.startConnectionMonitor();
4076
- this.settleConnect();
4077
- this.emit(this.Event.connect);
4078
- this.sendFromQueue();
4079
- } else {
4080
- this.settleConnect(envelope.data);
4081
- const error = envelope.data?.reason?.error;
4082
- if (error?.code === 'AuthenticationException') {
4083
- // Invalid token - retrying would be rejected the same way.
4084
- this.handleConnectionLoss(false);
4085
- this.emit(this.Event.error, new Error(`Authentication rejected: ${error.message}`));
4086
- }
4087
- }
4337
+ this.authenticated = true;
4338
+ this.stableConnectionTimeoutId = setTimeout(() => this.resetBackoff(), this.options.reconnect?.stableConnectionMs ?? 30000);
4339
+ this.startConnectionMonitor();
4340
+ this.settleConnect();
4341
+ this.emit(this.Event.connect);
4342
+ this.sendFromQueue();
4343
+ }
4344
+ }
4345
+ onBye(bye) {
4346
+ this.byeReceived = true;
4347
+ this.byeRetryAfterMs = normalizeRetryAfter(bye?.retryAfterMs);
4348
+ if (bye?.reason?.type === 'Service' || bye?.reason?.error?.code === 'ServiceUnavailableException') {
4349
+ // Not left to the close code: the server may close with 1000 and some platforms rewrite the code.
4350
+ this.handleConnectionLoss(true, true);
4351
+ return;
4352
+ }
4353
+ if (this.authenticated) {
4354
+ return;
4355
+ }
4356
+ this.settleConnect(bye);
4357
+ const error = bye?.reason?.error;
4358
+ if (error?.code === 'AuthenticationException') {
4359
+ // Invalid token - retrying would be rejected the same way.
4360
+ this.handleConnectionLoss(false);
4361
+ this.emit(this.Event.error, new Error(`Authentication rejected: ${error.message}`));
4088
4362
  }
4089
4363
  }
4090
4364
  onClose(event) {
4091
4365
  // Connection was closed because of error
4092
- this.handleConnectionLoss(event.code !== 1000);
4366
+ this.handleConnectionLoss(event.code !== 1000, this.byeReceived || SERVER_CLOSE_CODES.includes(event.code));
4093
4367
  }
4094
4368
 
4095
4369
  /**
@@ -4097,7 +4371,7 @@ class WebSocketChatClient extends AbstractChatClient {
4097
4371
  * may never come, or take minutes on a dead TCP connection), settle
4098
4372
  * everything that depended on it and schedule a retry when requested.
4099
4373
  */
4100
- handleConnectionLoss(reconnect) {
4374
+ handleConnectionLoss(reconnect, closedByServer = false) {
4101
4375
  this.releaseSocket(reconnect ? 3000 : 1000);
4102
4376
 
4103
4377
  // The server can no longer answer anything that was queued or in
@@ -4107,7 +4381,7 @@ class WebSocketChatClient extends AbstractChatClient {
4107
4381
  if (reconnect) {
4108
4382
  // Keep a pending connect() promise unsettled - the retry below is
4109
4383
  // expected to authenticate and will resolve it.
4110
- this.scheduleReconnect();
4384
+ this.scheduleReconnect(closedByServer);
4111
4385
  } else {
4112
4386
  this.reconnectEnabled = false;
4113
4387
  this.settleConnect(new Error('Connection closed before authentication'));
@@ -4123,13 +4397,15 @@ class WebSocketChatClient extends AbstractChatClient {
4123
4397
  this.stopConnectionMonitor();
4124
4398
  clearTimeout(this.connectingTimeoutId);
4125
4399
  this.connectingTimeoutId = undefined;
4400
+ clearTimeout(this.stableConnectionTimeoutId);
4401
+ this.stableConnectionTimeoutId = undefined;
4126
4402
  this.authenticated = false;
4127
4403
  const ws = this.ws;
4128
4404
  this.ws = null;
4129
4405
  if (!ws) {
4130
4406
  return;
4131
4407
  }
4132
- ws.onmessage = ws.onclose = ws.onerror = null;
4408
+ ws.onmessage = ws.onclose = ws.onerror = ws.onopen = null;
4133
4409
  if (ws.readyState === ws.CONNECTING || ws.readyState === ws.OPEN) {
4134
4410
  try {
4135
4411
  ws.close(closeCode);
@@ -4138,19 +4414,27 @@ class WebSocketChatClient extends AbstractChatClient {
4138
4414
  }
4139
4415
  }
4140
4416
  }
4141
- scheduleReconnect() {
4417
+ scheduleReconnect(closedByServer) {
4142
4418
  this.cancelScheduledReconnect();
4143
- const minDelay = Math.max(0, this.options.reconnect?.minDelayMs ?? 1000);
4144
- const maxDelay = Math.max(minDelay, this.options.reconnect?.maxDelayMs ?? 30000);
4419
+
4420
+ // Once the server has closed a connection, the attempts that fail while it is still down
4421
+ // keep the longer backoff.
4422
+ this.serverClosedSinceStable ||= closedByServer;
4423
+ const reconnectOptions = this.options.reconnect;
4424
+ const minDelay = Math.max(0, this.serverClosedSinceStable ? reconnectOptions?.serverCloseMinDelayMs ?? 5000 : reconnectOptions?.minDelayMs ?? 1000);
4425
+ const maxDelay = Math.max(minDelay, reconnectOptions?.maxDelayMs ?? 30000);
4145
4426
  const delay = Math.min(maxDelay, minDelay * 2 ** Math.min(this.reconnectAttempts, 30));
4146
4427
  this.reconnectAttempts++;
4147
4428
 
4148
- // Random jitter (50-100% of the delay) keeps clients from reconnecting
4149
- // in lockstep after a server restart.
4429
+ // Full jitter spreads the clients dropped together over the whole delay; the server jitters its own hint.
4150
4430
  this.reconnectTimeoutId = setTimeout(() => {
4151
4431
  this.reconnectTimeoutId = undefined;
4152
4432
  this.connect().catch(() => undefined);
4153
- }, delay / 2 + Math.random() * delay / 2);
4433
+ }, this.byeRetryAfterMs ?? Math.random() * delay);
4434
+ }
4435
+ resetBackoff() {
4436
+ this.reconnectAttempts = 0;
4437
+ this.serverClosedSinceStable = false;
4154
4438
  }
4155
4439
  cancelScheduledReconnect() {
4156
4440
  clearTimeout(this.reconnectTimeoutId);
@@ -4425,6 +4709,7 @@ let ErrorCode = /*#__PURE__*/function (ErrorCode) {
4425
4709
  ErrorCode["InvalidSearchQuery"] = "InvalidSearchQueryException";
4426
4710
  ErrorCode["MessageSearchUnavailable"] = "MessageSearchUnavailableException";
4427
4711
  ErrorCode["MessageNotFound"] = "MessageNotFoundException";
4712
+ ErrorCode["ReactionExistsAlready"] = "ReactionExistsAlreadyException";
4428
4713
  ErrorCode["RoomIgnored"] = "RoomIgnoredException";
4429
4714
  ErrorCode["RoomNotFound"] = "RoomNotFoundException";
4430
4715
  ErrorCode["SpaceJoinRestricted"] = "SpaceJoinRestrictedException";
@@ -4432,6 +4717,12 @@ let ErrorCode = /*#__PURE__*/function (ErrorCode) {
4432
4717
  ErrorCode["UserNotFound"] = "UserNotFoundException";
4433
4718
  return ErrorCode;
4434
4719
  }({});
4720
+ ;// ./src/protocol/schemes/MessageEmbed.ts
4721
+ let MessageEmbedFlag = /*#__PURE__*/function (MessageEmbedFlag) {
4722
+ MessageEmbedFlag[MessageEmbedFlag["HideContent"] = 1] = "HideContent";
4723
+ MessageEmbedFlag[MessageEmbedFlag["Suppressed"] = 2] = "Suppressed";
4724
+ return MessageEmbedFlag;
4725
+ }({});
4435
4726
  ;// ./src/protocol/schemes/Role.ts
4436
4727
  /**
4437
4728
  * Bit flags of a role, stored in {@link Role.flags}.
@@ -4566,6 +4857,6 @@ let SpaceIntent = /*#__PURE__*/function (SpaceIntent) {
4566
4857
 
4567
4858
 
4568
4859
 
4569
- export { AbstractRestClient, ErrorCode, FilesClient, HistoryRotation, IndexedCollection, IndexedObjectCollection, Layer, NO_LIMIT, ObservableIndexedCollection, ObservableIndexedObjectCollection, PermissionDefinition, Permissions, PmParticipantFlag, RoleFlag, STATE_SNAPSHOT_VERSION, STORAGE_UNIT_BYTES, SearchRange, SpaceFeature, SpaceIntent, TYPING_INTERVAL_MS, TYPING_TIMEOUT_MS, UiPurpose, UserFeature, UserStatus, WebApiChatClient, WebSocketChatClient, extractUserFromMember, getPmPeers, isGroupPm };
4860
+ export { AbstractRestClient, ErrorCode, FilesClient, HistoryRotation, IndexedCollection, IndexedObjectCollection, Layer, MessageEmbedFlag, NO_LIMIT, ObservableIndexedCollection, ObservableIndexedObjectCollection, PermissionDefinition, Permissions, PmParticipantFlag, RoleFlag, STATE_SNAPSHOT_VERSION, STORAGE_UNIT_BYTES, SearchRange, SpaceFeature, SpaceIntent, TYPING_INTERVAL_MS, TYPING_TIMEOUT_MS, UiPurpose, UserFeature, UserStatus, WebApiChatClient, WebSocketChatClient, extractUserFromMember, getPmPeers, isGroupPm };
4570
4861
 
4571
4862
  //# sourceMappingURL=index.mjs.map