@devanachat/sdk 0.7.0 → 0.8.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.
package/build/index.mjs CHANGED
@@ -774,6 +774,43 @@ class TopicHistoryWindow extends TraversableRemoteCollection {
774
774
  return super.jumpTo(id);
775
775
  }
776
776
 
777
+ /**
778
+ * The latest messages (oldest first) with the reactions of the user, or null if the window does not hold them.
779
+ * @internal
780
+ */
781
+ _exportLatest(limit) {
782
+ if (this.state !== WindowState.LATEST) {
783
+ return null;
784
+ }
785
+ const messages = this.items.slice(-Math.max(limit, this.fetchLimit));
786
+ const myReactions = {};
787
+ for (const message of messages) {
788
+ if (this.internalState.myReactions[message.id]) {
789
+ myReactions[message.id] = this.internalState.myReactions[message.id];
790
+ }
791
+ }
792
+ return {
793
+ messages,
794
+ myReactions
795
+ };
796
+ }
797
+
798
+ /**
799
+ * Fill the window with saved latest messages, as if they were just fetched; the next reset to the latest replaces
800
+ * them.
801
+ * @internal
802
+ */
803
+ _restoreLatest(messages, myReactions) {
804
+ const originalState = this.state;
805
+ this._items.deleteAll(); // Directly call deleteAll to prevent event emit.
806
+ this.addItems(messages, 'tail');
807
+ this.internalState.myReactions = {
808
+ ...myReactions
809
+ };
810
+ this.internalState.current = WindowState.LATEST;
811
+ this.emitChangeWithDiff(true, originalState);
812
+ }
813
+
777
814
  /**
778
815
  * For internal use.
779
816
  * @internal
@@ -1050,6 +1087,31 @@ class RoomMessagesHistory {
1050
1087
  }
1051
1088
  }
1052
1089
 
1090
+ /**
1091
+ * For internal use.
1092
+ * @internal
1093
+ */
1094
+ get _isEphemeral() {
1095
+ return this.traverseLock;
1096
+ }
1097
+
1098
+ /**
1099
+ * The window of the topic, if created; unlike getMessagesWindow(), never creates nor fetches one.
1100
+ * @internal
1101
+ */
1102
+ _peekWindow(topicId) {
1103
+ return this.historyWindows.get(topicId);
1104
+ }
1105
+
1106
+ /**
1107
+ * For internal use.
1108
+ * @internal
1109
+ */
1110
+ _restoreWindow(topic, messages, myReactions) {
1111
+ this.createHistoryWindowForTopic(topic);
1112
+ this.historyWindows.get(topic.id)._restoreLatest(messages, myReactions);
1113
+ }
1114
+
1053
1115
  /**
1054
1116
  * For internal use.
1055
1117
  * @internal
@@ -1208,6 +1270,43 @@ class MessagesManager {
1208
1270
  }
1209
1271
  return message || null;
1210
1272
  }
1273
+
1274
+ /**
1275
+ * For internal use.
1276
+ * @internal
1277
+ */
1278
+ _importRooms(rooms) {
1279
+ for (const room of rooms) {
1280
+ this.createHistoryForNewRoom(room);
1281
+ }
1282
+ this.deferredSession.resolve();
1283
+ }
1284
+
1285
+ /**
1286
+ * For internal use.
1287
+ * @internal
1288
+ */
1289
+ _exportLatest(roomId, topicId, limit) {
1290
+ const history = this.roomHistories.get(roomId);
1291
+
1292
+ // Ephemeral history lives only in the memory of the session.
1293
+ if (!history || history._isEphemeral) {
1294
+ return null;
1295
+ }
1296
+ return history._peekWindow(topicId)?._exportLatest(limit) ?? null;
1297
+ }
1298
+
1299
+ /**
1300
+ * For internal use.
1301
+ * @internal
1302
+ */
1303
+ _importHistory(roomId, topic, snapshot) {
1304
+ const history = this.roomHistories.get(roomId);
1305
+ if (history && !history._isEphemeral) {
1306
+ const messages = snapshot.messages.filter(message => message.location.roomId === roomId && message.location.topicId === topic.id);
1307
+ history._restoreWindow(topic, messages, snapshot.myReactions);
1308
+ }
1309
+ }
1211
1310
  forEachRoomHistory(callback) {
1212
1311
  for (const history of this.roomHistories.items.values()) {
1213
1312
  callback(history);
@@ -1428,6 +1527,47 @@ class FollowedTopicsManager extends EventTarget {
1428
1527
  this.followedTopics.get(roomId)?.delete(...topicIds);
1429
1528
  topicIds.forEach(topicId => this.invalidateUnreadSummaries(roomId, topicId));
1430
1529
  }
1530
+
1531
+ /**
1532
+ * For internal use.
1533
+ * @internal
1534
+ */
1535
+ _exportFollowedTopics() {
1536
+ return Array.from(this.followedTopics.items).filter(([roomId]) => this.tracker.rooms._getRoom(roomId)).map(([roomId, followedTopics]) => ({
1537
+ roomId,
1538
+ followedTopics: followedTopics.items
1539
+ }));
1540
+ }
1541
+
1542
+ /**
1543
+ * Expects the rooms to be imported already - followed topics of other rooms are skipped.
1544
+ * @internal
1545
+ */
1546
+ _importFollowedTopics(snapshots) {
1547
+ for (const {
1548
+ roomId,
1549
+ followedTopics
1550
+ } of snapshots) {
1551
+ if (this.tracker.rooms._getRoom(roomId)) {
1552
+ this.applyRoomFollowedTopics(roomId, followedTopics);
1553
+ }
1554
+ }
1555
+ this.invalidateUnreadSummaries();
1556
+ this.deferredSession.resolve();
1557
+ }
1558
+
1559
+ /**
1560
+ * For internal use.
1561
+ * @internal
1562
+ */
1563
+ _forgetRoomsExcept(roomIds) {
1564
+ const keptRoomIds = new Set(roomIds);
1565
+ for (const roomId of Array.from(this.followedTopics.items.keys())) {
1566
+ if (!keptRoomIds.has(roomId)) {
1567
+ this.clearRoomFollowedTopicsStructures(roomId);
1568
+ }
1569
+ }
1570
+ }
1431
1571
  handleSession(ev) {
1432
1572
  // Keep cached followed-topic collections (they drive unread indicators
1433
1573
  // that would otherwise blank on reconnect), but mark them stale and drop
@@ -1628,11 +1768,148 @@ class FollowedTopicsManager extends EventTarget {
1628
1768
  this.invalidateUnreadSummaries(roomId);
1629
1769
  }
1630
1770
  }
1771
+ ;// ./src/protocol/schemes/User.ts
1772
+ /**
1773
+ * Availability of a user, aggregated over all of their sessions.
1774
+ *
1775
+ * - `Offline` - no session is connected and none can be reached asynchronously.
1776
+ * - `Online` - at least one session holds a live connection.
1777
+ * - `OnlineAsync` - no live connection, but a push-registered device was active
1778
+ * recently, so a message will still reach the user.
1779
+ */
1780
+ let UserStatus = /*#__PURE__*/function (UserStatus) {
1781
+ UserStatus[UserStatus["Offline"] = 0] = "Offline";
1782
+ UserStatus[UserStatus["Online"] = 1] = "Online";
1783
+ UserStatus[UserStatus["OnlineAsync"] = 2] = "OnlineAsync";
1784
+ return UserStatus;
1785
+ }({});
1786
+ ;// ./src/state-tracker/StateSnapshot.ts
1787
+
1788
+
1789
+ /**
1790
+ * Version of the {@link StateSnapshot} format. A snapshot of any other version is rejected on import.
1791
+ */
1792
+ const STATE_SNAPSHOT_VERSION = 1;
1793
+
1794
+ /**
1795
+ * Plain, JSON-serializable copy of the state tracked by {@link ChatStateTracker}, made to restore the state at the
1796
+ * application start (before the connection is established) - see {@link ChatStateTracker.exportSnapshot}.
1797
+ *
1798
+ * Only the data that lasts is included: the current user, the joined spaces (with roles) and rooms (with the default
1799
+ * topics), and the lazily loaded lists already fetched - rooms of spaces, followed topics, emoticons and relationships.
1800
+ * The message histories of the topics named in the {@link StateSnapshotIntent} are included too, with what their
1801
+ * display needs: the topics referenced by the messages and, optionally, the members of the rooms.
1802
+ * Left out on purpose:
1803
+ * - presence - every user status is saved as `Offline`, a status from the past would show people online who are not;
1804
+ * - members of spaces, and of rooms not asked for - large, made mostly of presence, and refetched cheaply on demand;
1805
+ * - other message histories and topics, histories of ephemeral rooms (they live only in the memory of the session),
1806
+ * permission overwrites and room previews - loaded on demand once the connection is up, as on a reconnect.
1807
+ */
1808
+
1809
+ /**
1810
+ * What {@link ChatStateTracker.exportSnapshot} should include beyond the state that is always exported.
1811
+ */
1812
+
1813
+ function withoutPresence(user) {
1814
+ return {
1815
+ ...user,
1816
+ status: UserStatus.Offline,
1817
+ online: false
1818
+ };
1819
+ }
1820
+ function messageWithoutPresence(message) {
1821
+ return {
1822
+ ...message,
1823
+ author: {
1824
+ ...message.author,
1825
+ user: withoutPresence(message.author.user)
1826
+ }
1827
+ };
1828
+ }
1829
+ function memberWithoutPresence(member) {
1830
+ return {
1831
+ ...member,
1832
+ user: member.user ? withoutPresence(member.user) : member.user,
1833
+ spaceMember: member.spaceMember ? {
1834
+ ...member.spaceMember,
1835
+ user: withoutPresence(member.spaceMember.user)
1836
+ } : member.spaceMember
1837
+ };
1838
+ }
1839
+
1840
+ /**
1841
+ * Structural check of the data restored from a storage - deep enough that importing it cannot throw, as the state
1842
+ * handlers dereference these fields without checking them.
1843
+ */
1844
+ function isValidStateSnapshot(value) {
1845
+ return isObject(value) && value.version === STATE_SNAPSHOT_VERSION && typeof value.createdAt === 'number' && isUser(value.user) && isArrayOf(value.spaces, isSpace) && isArrayOf(value.rooms, isRoom) && isArrayOf(value.spaceRooms, isSpaceRooms) && isArrayOf(value.followedTopics, isRoomFollowedTopics) && isArrayOf(value.emoticons, isEmoticons) && (value.relationships === null || isArrayOf(value.relationships, isRelationship)) && isArrayOf(value.histories, isTopicHistory) && isArrayOf(value.roomMembers, isRoomMembers);
1846
+ }
1847
+ function isObject(value) {
1848
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
1849
+ }
1850
+ function isArrayOf(value, isItem) {
1851
+ return Array.isArray(value) && value.every(isItem);
1852
+ }
1853
+ function isString(value) {
1854
+ return typeof value === 'string';
1855
+ }
1856
+ function hasId(value) {
1857
+ return isObject(value) && isString(value.id);
1858
+ }
1859
+ function isUser(value) {
1860
+ return hasId(value);
1861
+ }
1862
+ function isRole(value) {
1863
+ return hasId(value) && typeof value.priority === 'number';
1864
+ }
1865
+ function isSpace(value) {
1866
+ return hasId(value) && isArrayOf(value.roles, isRole) && isArrayOf(value.defaultRooms, isString) && (value.systemRoom === null || isString(value.systemRoom));
1867
+ }
1868
+ function isTopic(value) {
1869
+ return hasId(value) && (value.refMessage === undefined || value.refMessage === null || isMessage(value.refMessage));
1870
+ }
1871
+ function isMessage(value) {
1872
+ return hasId(value) && isObject(value.location) && isString(value.location.topicId);
1873
+ }
1874
+ function isFullMessage(value) {
1875
+ return hasId(value) && isObject(value.location) && isString(value.location.roomId) && isString(value.location.topicId) && isObject(value.author) && isUser(value.author.user) && Array.isArray(value.reactions);
1876
+ }
1877
+ function isRoom(value) {
1878
+ return hasId(value) && isString(value.type) && (value.spaceId === null || isString(value.spaceId)) && (value.defaultTopic === null || isTopic(value.defaultTopic)) && (value.recipients === null || isArrayOf(value.recipients, isUser)) && isObject(value.history) && isString(value.history.mode);
1879
+ }
1880
+ function isSpaceRooms(value) {
1881
+ return isObject(value) && isString(value.spaceId) && isArrayOf(value.summaries, hasId);
1882
+ }
1883
+ function isFollowedTopic(value) {
1884
+ return isObject(value) && isObject(value.location) && isString(value.location.roomId) && isString(value.location.topicId);
1885
+ }
1886
+ function isRoomFollowedTopics(value) {
1887
+ return isObject(value) && isString(value.roomId) && isArrayOf(value.followedTopics, isFollowedTopic);
1888
+ }
1889
+ function isEmoticons(value) {
1890
+ return isObject(value) && (value.spaceId === null || isString(value.spaceId)) && isArrayOf(value.emoticons, hasId);
1891
+ }
1892
+ function isRelationship(value) {
1893
+ return isObject(value) && isUser(value.refUser) && isString(value.type);
1894
+ }
1895
+ function isUserReactions(value) {
1896
+ return isObject(value) && Object.values(value).every(reactions => isArrayOf(reactions, isObject));
1897
+ }
1898
+ function isTopicHistory(value) {
1899
+ return isObject(value) && isString(value.roomId) && isString(value.topicId) && isArrayOf(value.messages, isFullMessage) && isUserReactions(value.myReactions) && isArrayOf(value.topics, isTopic);
1900
+ }
1901
+ function isRoomMember(value) {
1902
+ return isObject(value) && (isUser(value.user) || isObject(value.spaceMember) && isUser(value.spaceMember.user));
1903
+ }
1904
+ function isRoomMembers(value) {
1905
+ return isObject(value) && isString(value.roomId) && isArrayOf(value.members, isRoomMember);
1906
+ }
1631
1907
  ;// ./src/state-tracker/RoomsManager.ts
1632
1908
 
1633
1909
 
1634
1910
 
1635
1911
 
1912
+
1636
1913
  class RoomsManager {
1637
1914
  messages;
1638
1915
  followedTopics;
@@ -1642,6 +1919,7 @@ class RoomsManager {
1642
1919
  deferredSession = new DeferredTask();
1643
1920
  membersPromises = new PromiseRegistry();
1644
1921
  topicsPromises = new PromiseRegistry();
1922
+ importedTopicIds = new Map();
1645
1923
  constructor(tracker) {
1646
1924
  this.tracker = tracker;
1647
1925
  this.messages = new MessagesManager(tracker);
@@ -1746,6 +2024,148 @@ class RoomsManager {
1746
2024
  _deleteTopicsFromRoom(roomId, ...topicIds) {
1747
2025
  this.topics.get(roomId)?.delete(...topicIds);
1748
2026
  }
2027
+
2028
+ /**
2029
+ * For internal use.
2030
+ * @internal
2031
+ */
2032
+ _exportRooms() {
2033
+ return this.list.items.map(room => room.recipients ? {
2034
+ ...room,
2035
+ recipients: room.recipients.map(withoutPresence)
2036
+ } : room);
2037
+ }
2038
+
2039
+ /**
2040
+ * For internal use.
2041
+ * @internal
2042
+ */
2043
+ _importRooms(rooms) {
2044
+ this.messages._importRooms(rooms);
2045
+ this.addJoinedRooms(...rooms);
2046
+ this.deferredSession.resolve();
2047
+ }
2048
+
2049
+ /**
2050
+ * For internal use.
2051
+ * @internal
2052
+ */
2053
+ _exportHistories(intent) {
2054
+ const histories = [];
2055
+ const exported = new Set();
2056
+ for (const {
2057
+ roomId,
2058
+ topicId: requestedTopicId
2059
+ } of intent.histories ?? []) {
2060
+ const room = this.list.get(roomId);
2061
+ const topicId = requestedTopicId ?? room?.defaultTopic?.id;
2062
+ if (!room || !topicId || exported.has(`${roomId}/${topicId}`)) {
2063
+ continue;
2064
+ }
2065
+ const latest = this.messages._exportLatest(roomId, topicId, intent.historyLimit ?? 0);
2066
+ const topics = this.topics.get(roomId);
2067
+
2068
+ // A topic other than the default one is restored from the snapshot, so it has to be known.
2069
+ if (!latest || topicId !== room.defaultTopic?.id && !topics?.has(topicId)) {
2070
+ continue;
2071
+ }
2072
+ const topicIds = new Set([topicId, ...latest.messages.map(message => message.topicRef)]);
2073
+ topicIds.delete(room.defaultTopic?.id);
2074
+ exported.add(`${roomId}/${topicId}`);
2075
+ histories.push({
2076
+ roomId,
2077
+ topicId,
2078
+ messages: latest.messages.map(messageWithoutPresence),
2079
+ myReactions: latest.myReactions,
2080
+ topics: Array.from(topicIds).filter(id => topics?.has(id)).map(id => topics.get(id))
2081
+ });
2082
+ }
2083
+ return histories;
2084
+ }
2085
+
2086
+ /**
2087
+ * Members of private conversations are not exported - they are made of the recipients of the room.
2088
+ * @internal
2089
+ */
2090
+ _exportMembers(roomIds, limit) {
2091
+ const snapshots = [];
2092
+ if (!limit) {
2093
+ return snapshots;
2094
+ }
2095
+ for (const roomId of new Set(roomIds)) {
2096
+ const members = this.members.get(roomId);
2097
+ if (members && members.length <= limit && this.list.get(roomId)?.type !== 'Pm') {
2098
+ snapshots.push({
2099
+ roomId,
2100
+ members: members.items.map(memberWithoutPresence)
2101
+ });
2102
+ }
2103
+ }
2104
+ return snapshots;
2105
+ }
2106
+
2107
+ /**
2108
+ * Expects the rooms to be imported already - histories and members of other rooms are skipped.
2109
+ * @internal
2110
+ */
2111
+ _importHistories(histories, roomMembers) {
2112
+ for (const {
2113
+ roomId,
2114
+ members
2115
+ } of roomMembers) {
2116
+ if (this.list.has(roomId) && this.list.get(roomId).type !== 'Pm') {
2117
+ this.handleRoomMembers({
2118
+ id: roomId,
2119
+ members
2120
+ });
2121
+ // Served from the snapshot until the session invalidates it.
2122
+ this.membersPromises.register(Promise.resolve(), roomId);
2123
+ }
2124
+ }
2125
+ for (const history of histories) {
2126
+ const room = this.list.get(history.roomId);
2127
+ if (!room) {
2128
+ continue;
2129
+ }
2130
+ const topics = history.topics.filter(topic => topic.id !== room.defaultTopic?.id);
2131
+ if (topics.length) {
2132
+ this.addJoinedRoomTopics(room.id, ...topics);
2133
+ const importedTopicIds = this.importedTopicIds.get(room.id) ?? new Set();
2134
+ topics.forEach(topic => importedTopicIds.add(topic.id));
2135
+ this.importedTopicIds.set(room.id, importedTopicIds);
2136
+ }
2137
+ const topic = history.topicId === room.defaultTopic?.id ? room.defaultTopic : this.topics.get(room.id)?.get(history.topicId);
2138
+ if (topic) {
2139
+ this.messages._importHistory(room.id, topic, history);
2140
+ }
2141
+ }
2142
+ }
2143
+
2144
+ /**
2145
+ * The session carries only the default topics, so the other restored ones are fetched anew.
2146
+ * @internal
2147
+ */
2148
+ _refreshImportedTopics() {
2149
+ const importedTopicIds = Array.from(this.importedTopicIds);
2150
+ this.importedTopicIds.clear();
2151
+ for (const [roomId, ids] of importedTopicIds) {
2152
+ if (!this.list.has(roomId)) {
2153
+ continue;
2154
+ }
2155
+ const topicIds = Array.from(ids);
2156
+ const promise = this.tracker.client.send('GetTopics', {
2157
+ roomId,
2158
+ topicIds
2159
+ }).then(result => {
2160
+ if (!result.error) {
2161
+ this.topics.get(roomId)?.set(...result.data.topics);
2162
+ }
2163
+ });
2164
+ topicIds.forEach(topicId => this.topicsPromises.register(promise, roomId + topicId));
2165
+ // Best effort: on a failure the restored topics stay, as after a reconnect.
2166
+ promise.catch(() => undefined);
2167
+ }
2168
+ }
1749
2169
  deleteRoom(...roomIds) {
1750
2170
  this.list.delete(...roomIds);
1751
2171
  this.members.delete(...roomIds);
@@ -2142,6 +2562,47 @@ class SpacesManager {
2142
2562
  const members = await this.getMembers(spaceId);
2143
2563
  return members?.items.find(member => member.user.id === userId);
2144
2564
  }
2565
+
2566
+ /**
2567
+ * For internal use.
2568
+ * @internal
2569
+ */
2570
+ _exportSpaces() {
2571
+ return this.list.items;
2572
+ }
2573
+
2574
+ /**
2575
+ * Room listings of the joined spaces only - of other spaces they are fetched for a moment's look.
2576
+ * @internal
2577
+ */
2578
+ _exportSpaceRooms() {
2579
+ return Array.from(this.rooms.items).filter(([spaceId]) => this.list.has(spaceId)).map(([spaceId, summaries]) => ({
2580
+ spaceId,
2581
+ summaries: summaries.items
2582
+ }));
2583
+ }
2584
+
2585
+ /**
2586
+ * For internal use.
2587
+ * @internal
2588
+ */
2589
+ _importSpaces(spaces, spaceRooms) {
2590
+ this.addJoinedSpaces(...spaces);
2591
+ for (const {
2592
+ spaceId,
2593
+ summaries
2594
+ } of spaceRooms) {
2595
+ if (this.list.has(spaceId)) {
2596
+ this.handleSpaceRooms({
2597
+ id: spaceId,
2598
+ summaries
2599
+ });
2600
+ // Served from the snapshot until the session invalidates it.
2601
+ this.roomsPromises.register(Promise.resolve(), spaceId);
2602
+ }
2603
+ }
2604
+ this.deferredSession.resolve();
2605
+ }
2145
2606
  handleNewRole(ev) {
2146
2607
  this.roles.get(ev.spaceId).set(ev.role);
2147
2608
  this.syncSpaceRoles(ev.spaceId);
@@ -2763,6 +3224,52 @@ class EmoticonsManager {
2763
3224
  await this.emoticonsPromises.get(key);
2764
3225
  return this.list.get(key);
2765
3226
  }
3227
+
3228
+ /**
3229
+ * For internal use.
3230
+ * @internal
3231
+ */
3232
+ _exportEmoticons() {
3233
+ return Array.from(this.list.items).map(([key, emoticons]) => ({
3234
+ spaceId: key === GLOBAL_KEY ? null : key,
3235
+ emoticons: emoticons.items
3236
+ }));
3237
+ }
3238
+
3239
+ /**
3240
+ * Emoticons of spaces other than the given ones are skipped.
3241
+ * @internal
3242
+ */
3243
+ _importEmoticons(snapshots, spaceIds) {
3244
+ const joinedSpaceIds = new Set(spaceIds);
3245
+ for (const {
3246
+ spaceId,
3247
+ emoticons
3248
+ } of snapshots) {
3249
+ if (spaceId !== null && !joinedSpaceIds.has(spaceId)) {
3250
+ continue;
3251
+ }
3252
+ this.handleEmoticons({
3253
+ location: {
3254
+ spaceId: spaceId ?? undefined
3255
+ },
3256
+ emoticons
3257
+ });
3258
+ // Served from the snapshot until the session invalidates it.
3259
+ this.emoticonsPromises.register(Promise.resolve(), spaceId ?? GLOBAL_KEY);
3260
+ }
3261
+ }
3262
+
3263
+ /**
3264
+ * For internal use.
3265
+ * @internal
3266
+ */
3267
+ _forgetSpacesExcept(spaceIds) {
3268
+ const keptKeys = new Set([GLOBAL_KEY, ...spaceIds]);
3269
+ const removedKeys = Array.from(this.list.items.keys()).filter(key => !keptKeys.has(key));
3270
+ this.list.delete(...removedKeys);
3271
+ this.emoticonsPromises.forget(...removedKeys);
3272
+ }
2766
3273
  handleEmoticons(event) {
2767
3274
  const spaceId = event.location.spaceId ?? GLOBAL_KEY;
2768
3275
  if (!this.list.has(spaceId)) {
@@ -2818,6 +3325,14 @@ class UsersManager {
2818
3325
  async getAvailable() {
2819
3326
  return this.users;
2820
3327
  }
3328
+
3329
+ /**
3330
+ * For internal use.
3331
+ * @internal
3332
+ */
3333
+ _importUser(user) {
3334
+ this.handleUsers([user]);
3335
+ }
2821
3336
  handleMembers(members) {
2822
3337
  this.handleUsers(members.map(extractUserFromMember));
2823
3338
  }
@@ -2864,11 +3379,13 @@ function isSameUser(a, b) {
2864
3379
  ;// ./src/state-tracker/RelationshipsManager.ts
2865
3380
 
2866
3381
 
3382
+
2867
3383
  const getId = (refUserId, type) => `${refUserId}-${type}`;
2868
3384
  const getIdFromRelationship = relationship => getId(relationship.refUser.id, relationship.type);
2869
3385
  class RelationshipsManager {
2870
3386
  relationships = new ObservableIndexedObjectCollection(getIdFromRelationship);
2871
3387
  promises = new PromiseRegistry();
3388
+ loaded = false;
2872
3389
  constructor(tracker) {
2873
3390
  this.tracker = tracker;
2874
3391
  this.tracker.client.on('Relationships', ev => this.handleRelationships(ev));
@@ -2892,7 +3409,33 @@ class RelationshipsManager {
2892
3409
  await this.get();
2893
3410
  return this.relationships.has(getId(refUserId, type));
2894
3411
  }
3412
+
3413
+ /**
3414
+ * For internal use.
3415
+ * @internal
3416
+ */
3417
+ _exportRelationships() {
3418
+ return this.loaded ? this.relationships.items.map(relationship => ({
3419
+ ...relationship,
3420
+ refUser: withoutPresence(relationship.refUser)
3421
+ })) : null;
3422
+ }
3423
+
3424
+ /**
3425
+ * For internal use.
3426
+ * @internal
3427
+ */
3428
+ _importRelationships(relationships) {
3429
+ if (relationships) {
3430
+ this.handleRelationships({
3431
+ relationships
3432
+ });
3433
+ // Served from the snapshot until the session invalidates it.
3434
+ this.promises.register(Promise.resolve(), 'all');
3435
+ }
3436
+ }
2895
3437
  handleRelationships(ev) {
3438
+ this.loaded = true;
2896
3439
  // Full list from the server: reconcile in place so a reconnect refetch
2897
3440
  // updates a bound (visible) list without an intermediate empty state.
2898
3441
  this.relationships.reconcile(...ev.relationships);
@@ -2921,6 +3464,7 @@ class RelationshipsManager {
2921
3464
 
2922
3465
 
2923
3466
 
3467
+
2924
3468
  class ChatStateTracker {
2925
3469
  client;
2926
3470
 
@@ -2955,6 +3499,8 @@ class ChatStateTracker {
2955
3499
  relationships;
2956
3500
  _me = null;
2957
3501
  deferredSession = new DeferredTask();
3502
+ sessionReceived = false;
3503
+ snapshotImported = false;
2958
3504
  constructor(client) {
2959
3505
  this.client = client;
2960
3506
  this.client.on('Session', ev => this.handleSession(ev));
@@ -2964,6 +3510,9 @@ class ChatStateTracker {
2964
3510
  this.emoticons = new EmoticonsManager(this);
2965
3511
  this.users = new UsersManager(this);
2966
3512
  this.relationships = new RelationshipsManager(this);
3513
+
3514
+ // Registered after the managers, so it runs once they have applied the session.
3515
+ this.client.on('Session', ev => this.handleSessionAfterImport(ev));
2967
3516
  }
2968
3517
  get me() {
2969
3518
  return this._me;
@@ -2972,10 +3521,88 @@ class ChatStateTracker {
2972
3521
  await this.deferredSession.promise;
2973
3522
  return this._me;
2974
3523
  }
3524
+
3525
+ /**
3526
+ * Export the tracked state to a plain, JSON-serializable object, to be saved and restored with
3527
+ * {@link importSnapshot} at the next start of the application, before the connection is established.
3528
+ * See {@link StateSnapshot} for what is included.
3529
+ * @param intent What to include beyond the state that is always exported, e.g. the message histories.
3530
+ * @return Null if there is no state yet (no session has been received or imported).
3531
+ */
3532
+ exportSnapshot(intent = {}) {
3533
+ if (!this._me) {
3534
+ return null;
3535
+ }
3536
+ const snapshot = {
3537
+ version: STATE_SNAPSHOT_VERSION,
3538
+ createdAt: Date.now(),
3539
+ user: withoutPresence(this._me),
3540
+ spaces: this.spaces._exportSpaces(),
3541
+ rooms: this.rooms._exportRooms(),
3542
+ spaceRooms: this.spaces._exportSpaceRooms(),
3543
+ followedTopics: this.rooms.followedTopics._exportFollowedTopics(),
3544
+ emoticons: this.emoticons._exportEmoticons(),
3545
+ relationships: this.relationships._exportRelationships(),
3546
+ histories: this.rooms._exportHistories(intent),
3547
+ roomMembers: this.rooms._exportMembers((intent.histories ?? []).map(history => history.roomId), intent.roomMembersLimit ?? 0)
3548
+ };
3549
+
3550
+ // Detaches the snapshot from the live state objects and leaves nothing a JSON round trip would change.
3551
+ return JSON.parse(JSON.stringify(snapshot));
3552
+ }
3553
+
3554
+ /**
3555
+ * Restore the state exported with {@link exportSnapshot}, so it is available before the connection is
3556
+ * established. The collections emit their usual change events and the getters waiting for the session resolve.
3557
+ * The first `Session` from the server then replaces the restored state the same way it does on a reconnect:
3558
+ * removed spaces and rooms are dropped, the rest is updated in place, the restored message histories and topics
3559
+ * other than the default ones are fetched anew (as a window holding the latest messages is on a reconnect), and
3560
+ * the lazily loaded lists are refetched on their next access.
3561
+ *
3562
+ * Allowed only once and only before the first `Session`.
3563
+ * @return False if the snapshot was rejected (another version, malformed data, or a session already received) -
3564
+ * the state is not changed then.
3565
+ */
3566
+ importSnapshot(snapshot) {
3567
+ if (this.sessionReceived || this.snapshotImported || !isValidStateSnapshot(snapshot)) {
3568
+ return false;
3569
+ }
3570
+ this.snapshotImported = true;
3571
+ try {
3572
+ this._me = snapshot.user;
3573
+ this.users._importUser(snapshot.user);
3574
+ this.rooms._importRooms(snapshot.rooms);
3575
+ this.spaces._importSpaces(snapshot.spaces, snapshot.spaceRooms);
3576
+ this.rooms.followedTopics._importFollowedTopics(snapshot.followedTopics);
3577
+ this.emoticons._importEmoticons(snapshot.emoticons, snapshot.spaces.map(space => space.id));
3578
+ this.relationships._importRelationships(snapshot.relationships);
3579
+ this.rooms._importHistories(snapshot.histories, snapshot.roomMembers);
3580
+ } catch {
3581
+ // Not expected after the validation; whatever got restored is replaced by the first session anyway.
3582
+ return false;
3583
+ }
3584
+ this.deferredSession.resolve();
3585
+ return true;
3586
+ }
2975
3587
  handleSession(ev) {
2976
3588
  this._me = ev.user;
3589
+ this.sessionReceived = true;
2977
3590
  this.deferredSession.resolve();
2978
3591
  }
3592
+
3593
+ /**
3594
+ * A reconnect keeps the followed topics and emoticons of rooms and spaces that are gone; for the restored ones
3595
+ * the first session is the only chance to tell they are gone.
3596
+ */
3597
+ handleSessionAfterImport(ev) {
3598
+ if (!this.snapshotImported) {
3599
+ return;
3600
+ }
3601
+ this.snapshotImported = false;
3602
+ this.rooms.followedTopics._forgetRoomsExcept(ev.state.rooms.map(room => room.id));
3603
+ this.emoticons._forgetSpacesExcept(ev.state.spaces.map(space => space.id));
3604
+ this.rooms._refreshImportedTopics();
3605
+ }
2979
3606
  }
2980
3607
  ;// ./src/WebSocketChatClient.ts
2981
3608
 
@@ -3462,21 +4089,6 @@ let ErrorCode = /*#__PURE__*/function (ErrorCode) {
3462
4089
  ErrorCode["UserNotFound"] = "UserNotFoundException";
3463
4090
  return ErrorCode;
3464
4091
  }({});
3465
- ;// ./src/protocol/schemes/User.ts
3466
- /**
3467
- * Availability of a user, aggregated over all of their sessions.
3468
- *
3469
- * - `Offline` - no session is connected and none can be reached asynchronously.
3470
- * - `Online` - at least one session holds a live connection.
3471
- * - `OnlineAsync` - no live connection, but a push-registered device was active
3472
- * recently, so a message will still reach the user.
3473
- */
3474
- let UserStatus = /*#__PURE__*/function (UserStatus) {
3475
- UserStatus[UserStatus["Offline"] = 0] = "Offline";
3476
- UserStatus[UserStatus["Online"] = 1] = "Online";
3477
- UserStatus[UserStatus["OnlineAsync"] = 2] = "OnlineAsync";
3478
- return UserStatus;
3479
- }({});
3480
4092
  ;// ./src/protocol/schemes/Role.ts
3481
4093
  /**
3482
4094
  * Bit flags of a role, stored in {@link Role.flags}.
@@ -3608,6 +4220,7 @@ let SpaceIntent = /*#__PURE__*/function (SpaceIntent) {
3608
4220
 
3609
4221
 
3610
4222
 
3611
- export { AbstractRestClient, ErrorCode, FilesClient, HistoryRotation, IndexedCollection, IndexedObjectCollection, Layer, NO_LIMIT, ObservableIndexedCollection, ObservableIndexedObjectCollection, PermissionDefinition, Permissions, RoleFlag, STORAGE_UNIT_BYTES, SearchRange, SpaceFeature, SpaceIntent, UiPurpose, UserFeature, UserStatus, WebApiChatClient, WebSocketChatClient, extractUserFromMember };
4223
+
4224
+ export { AbstractRestClient, ErrorCode, FilesClient, HistoryRotation, IndexedCollection, IndexedObjectCollection, Layer, NO_LIMIT, ObservableIndexedCollection, ObservableIndexedObjectCollection, PermissionDefinition, Permissions, RoleFlag, STATE_SNAPSHOT_VERSION, STORAGE_UNIT_BYTES, SearchRange, SpaceFeature, SpaceIntent, UiPurpose, UserFeature, UserStatus, WebApiChatClient, WebSocketChatClient, extractUserFromMember };
3612
4225
 
3613
4226
  //# sourceMappingURL=index.mjs.map