@pmate/chat-sdk 0.12.0-next.9 → 0.12.0-next.90
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/README.md +216 -83
- package/lib/advanced.d.ts +10 -0
- package/lib/advanced.js +10 -0
- package/lib/chat.d.ts +5 -0
- package/lib/chat.js +11 -0
- package/lib/chatContract.d.ts +158 -0
- package/lib/chatContract.js +1 -0
- package/lib/chatError.d.ts +31 -0
- package/lib/chatError.js +18 -0
- package/lib/chatTypes.d.ts +128 -0
- package/lib/chatTypes.js +1 -0
- package/lib/commands.d.ts +20 -0
- package/lib/commands.js +12 -0
- package/lib/components/ChatInputDesktop.js +5 -4
- package/lib/components/ChatInputMobile.js +5 -4
- package/lib/components/CommandMenu.d.ts +15 -0
- package/lib/components/CommandMenu.js +10 -0
- package/lib/credentials.d.ts +26 -0
- package/lib/credentials.js +110 -0
- package/lib/fileMetadata.d.ts +9 -0
- package/lib/fileMetadata.js +18 -0
- package/lib/framework.d.ts +11 -0
- package/lib/framework.js +12 -0
- package/lib/history.d.ts +4 -0
- package/lib/history.js +8 -0
- package/lib/hooks/useChatSnapshot.d.ts +4 -0
- package/lib/hooks/useChatSnapshot.js +9 -0
- package/lib/hooks/useComposerSuggestions.d.ts +50 -0
- package/lib/hooks/useComposerSuggestions.js +70 -0
- package/lib/index.d.ts +6 -0
- package/lib/index.js +6 -0
- package/lib/internal/chatEngine.d.ts +131 -0
- package/lib/internal/chatEngine.js +306 -0
- package/lib/internal/chatRegistry.d.ts +4 -0
- package/lib/internal/chatRegistry.js +4 -0
- package/lib/internal/createPublicChat.d.ts +4 -0
- package/lib/internal/createPublicChat.js +62 -0
- package/lib/messageView.d.ts +6 -0
- package/lib/messageView.js +103 -0
- package/lib/runtime/batchedReadIndex.d.ts +16 -3
- package/lib/runtime/batchedReadIndex.js +50 -4
- package/lib/runtime/cachedMessage.d.ts +12 -0
- package/lib/runtime/cachedMessage.js +18 -0
- package/lib/runtime/chatClient.d.ts +8 -1
- package/lib/runtime/chatClient.js +18 -6
- package/lib/runtime/chatError.d.ts +5 -0
- package/lib/runtime/chatError.js +20 -0
- package/lib/runtime/chatSession.d.ts +141 -13
- package/lib/runtime/chatSession.js +797 -48
- package/lib/runtime/connectivity.d.ts +4 -0
- package/lib/runtime/connectivity.js +8 -0
- package/lib/runtime/conversationDirectory.d.ts +37 -0
- package/lib/runtime/conversationDirectory.js +116 -0
- package/lib/runtime/conversationRead.d.ts +14 -0
- package/lib/runtime/conversationRead.js +34 -0
- package/lib/runtime/conversationReading.d.ts +30 -0
- package/lib/runtime/conversationReading.js +47 -0
- package/lib/runtime/createChat.d.ts +14 -7
- package/lib/runtime/createChat.js +67 -24
- package/lib/runtime/durableSender.d.ts +97 -14
- package/lib/runtime/durableSender.js +787 -71
- package/lib/runtime/groupClient.d.ts +92 -0
- package/lib/runtime/groupClient.js +380 -0
- package/lib/runtime/groupDenial.d.ts +2 -0
- package/lib/runtime/groupDenial.js +4 -0
- package/lib/runtime/groupIdentity.d.ts +4 -0
- package/lib/runtime/groupIdentity.js +26 -0
- package/lib/runtime/inboxClient.d.ts +65 -0
- package/lib/runtime/inboxClient.js +268 -0
- package/lib/runtime/inboxGroup.d.ts +4 -0
- package/lib/runtime/inboxGroup.js +51 -0
- package/lib/runtime/inboxStore.d.ts +194 -0
- package/lib/runtime/inboxStore.js +321 -0
- package/lib/runtime/inboxTransport.d.ts +6 -0
- package/lib/runtime/inboxTransport.js +76 -0
- package/lib/runtime/index.d.ts +10 -0
- package/lib/runtime/index.js +8 -0
- package/lib/runtime/indexedDbRecovery.d.ts +6 -0
- package/lib/runtime/indexedDbRecovery.js +42 -0
- package/lib/runtime/messageClient.d.ts +37 -8
- package/lib/runtime/messageClient.js +366 -68
- package/lib/runtime/messageControls.d.ts +19 -0
- package/lib/runtime/messageControls.js +44 -0
- package/lib/runtime/messageDiscussionStore.d.ts +63 -0
- package/lib/runtime/messageDiscussionStore.js +147 -0
- package/lib/runtime/messageLaunch.d.ts +44 -0
- package/lib/runtime/messageLaunch.js +137 -0
- package/lib/runtime/messageQuotes.d.ts +3 -0
- package/lib/runtime/messageQuotes.js +17 -0
- package/lib/runtime/messageReaders.d.ts +5 -1
- package/lib/runtime/messageReaders.js +16 -5
- package/lib/runtime/messageStore.d.ts +51 -2
- package/lib/runtime/messageStore.js +264 -14
- package/lib/runtime/messageThread.d.ts +9 -0
- package/lib/runtime/messageThread.js +17 -0
- package/lib/runtime/messageTimeline.d.ts +51 -0
- package/lib/runtime/messageTimeline.js +121 -0
- package/lib/runtime/outboxSchema.d.ts +5 -0
- package/lib/runtime/outboxSchema.js +59 -0
- package/lib/runtime/outgoingContent.d.ts +95 -0
- package/lib/runtime/outgoingContent.js +121 -0
- package/lib/runtime/readBatchJournal.d.ts +35 -0
- package/lib/runtime/readBatchJournal.js +210 -0
- package/lib/runtime/readCounts.d.ts +7 -1
- package/lib/runtime/readCounts.js +108 -21
- package/lib/runtime/readIndex.d.ts +74 -7
- package/lib/runtime/readIndex.js +488 -33
- package/lib/runtime/readSchema.d.ts +2 -0
- package/lib/runtime/readSchema.js +58 -0
- package/lib/runtime/readSync.d.ts +8 -0
- package/lib/runtime/readSync.js +125 -17
- package/lib/runtime/readingClient.d.ts +22 -0
- package/lib/runtime/readingClient.js +141 -20
- package/lib/runtime/readingContent.d.ts +5 -0
- package/lib/runtime/readingContent.js +23 -0
- package/lib/runtime/responseCache.d.ts +41 -5
- package/lib/runtime/responseCache.js +182 -44
- package/lib/runtime/socialReadClient.d.ts +30 -4
- package/lib/runtime/socialReadClient.js +34 -8
- package/lib/runtime/voiceUpload.d.ts +2 -0
- package/lib/runtime/voiceUpload.js +27 -0
- package/lib/snapshot.d.ts +36 -0
- package/lib/snapshot.js +52 -0
- package/lib/types/chatInput.d.ts +3 -0
- package/package.json +32 -2
|
@@ -1,3 +1,15 @@
|
|
|
1
|
+
import { messageThreadRoot } from "./messageThread.js";
|
|
2
|
+
import { asChatError } from "./chatError.js";
|
|
3
|
+
import { scopedGroupDenial, isScopedGroupDenial } from "./groupDenial.js";
|
|
4
|
+
import { threadChatError } from "./chatError.js";
|
|
5
|
+
import { ConversationDirectory } from "./conversationDirectory.js";
|
|
6
|
+
import { groupThreadId } from "./thread.js";
|
|
7
|
+
import { GroupClient } from "./groupClient.js";
|
|
8
|
+
import { isReadingControl } from "./readingContent.js";
|
|
9
|
+
import { outgoingContent, validateConversation } from "./outgoingContent.js";
|
|
10
|
+
import { projectMessageTimeline } from "./messageTimeline.js";
|
|
11
|
+
import { projectConversationReading } from "./conversationReading.js";
|
|
12
|
+
import { ReadCountsClient } from "./readCounts.js";
|
|
1
13
|
import { WindowedTasks } from "./coalescer.js";
|
|
2
14
|
import { MessageReadersClient } from "./messageReaders.js";
|
|
3
15
|
import { MessageClient } from "./messageClient.js";
|
|
@@ -8,23 +20,48 @@ import { unreadInConversation } from "./readIndex.js";
|
|
|
8
20
|
/** Owns all browser message clients. Hosts subscribe to stable thread snapshots. */
|
|
9
21
|
export class ChatSession {
|
|
10
22
|
options;
|
|
23
|
+
conversations;
|
|
11
24
|
messages;
|
|
12
25
|
connection;
|
|
13
26
|
reading;
|
|
14
27
|
readers;
|
|
28
|
+
groups;
|
|
29
|
+
counts;
|
|
30
|
+
countsReceiver;
|
|
31
|
+
countsThread;
|
|
32
|
+
countSnapshots = new Map();
|
|
33
|
+
countClosings = new Set();
|
|
34
|
+
countTasks;
|
|
35
|
+
controlTails = new Map();
|
|
36
|
+
acceptedControls = new Set();
|
|
37
|
+
controlCount = 0;
|
|
38
|
+
controlBytes = 0;
|
|
15
39
|
sender;
|
|
16
40
|
listeners = new Map();
|
|
17
41
|
snapshots = new Map();
|
|
42
|
+
timelineDecoded = new WeakMap();
|
|
43
|
+
decodeTimeline = (message) => { if (!this.timelineDecoded.has(message))
|
|
44
|
+
this.timelineDecoded.set(message, this.options.decode(message)); return this.timelineDecoded.get(message); };
|
|
18
45
|
historyEdges = new Map();
|
|
19
46
|
earlierReads = new Map();
|
|
20
47
|
off = [];
|
|
21
48
|
globalListeners = new Set();
|
|
22
49
|
globalSnapshot;
|
|
50
|
+
closedThread = { messages: [], timeline: [], outgoing: [], hasEarlier: false, resetVersion: 0, complete: false, unread: undefined, messageReading: {} };
|
|
51
|
+
closedSummary = { threads: [], unreadMessageCount: undefined, badgeCount: undefined, connection: "closed" };
|
|
23
52
|
connectionState = "closed";
|
|
24
53
|
catchUp;
|
|
54
|
+
readingAllowed = false;
|
|
55
|
+
readingListeners = new Set();
|
|
56
|
+
acceptedReading = new Set();
|
|
57
|
+
readingAccess;
|
|
25
58
|
readingStarted = false;
|
|
59
|
+
readingStarting;
|
|
60
|
+
withdrawn = false;
|
|
61
|
+
revoking;
|
|
26
62
|
closed = false;
|
|
27
63
|
starting;
|
|
64
|
+
initializing;
|
|
28
65
|
closing;
|
|
29
66
|
constructor(options) {
|
|
30
67
|
this.options = options;
|
|
@@ -36,20 +73,114 @@ export class ChatSession {
|
|
|
36
73
|
if (shared.appId !== scope.appId || shared.profileId !== scope.profileId || (shared.accountId !== undefined && shared.accountId !== scope.accountId) || (shared.teamId !== undefined && shared.teamId !== scope.teamId))
|
|
37
74
|
throw new Error("CHAT_SESSION_SCOPE_MISMATCH");
|
|
38
75
|
}
|
|
39
|
-
this.messages = new MessageClient(options.messages)
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
76
|
+
this.messages = new MessageClient({ ...options.messages, onError: (error, thread) => {
|
|
77
|
+
if (thread && error?.status === 403)
|
|
78
|
+
void this.conversationFailure(error, thread).then(failure => options.onError(failure));
|
|
79
|
+
else
|
|
80
|
+
options.messages.onError?.(error, thread);
|
|
81
|
+
} });
|
|
82
|
+
this.conversations = new ConversationDirectory(scope, () => this.messages.scopeAccess());
|
|
83
|
+
this.connection = options.sharedConnection ?? new ChatClient({ ...options.connection, onReach: async (event) => {
|
|
84
|
+
const handled = await this.handleReach(event);
|
|
85
|
+
if (handled)
|
|
86
|
+
return handled;
|
|
87
|
+
if (options.connection.onReach)
|
|
88
|
+
return options.connection.onReach(event);
|
|
89
|
+
throw new Error("REACH_HANDLER_UNAVAILABLE");
|
|
90
|
+
} });
|
|
91
|
+
this.reading = new ReadingClient({ ...options.reading, teamId: scope.teamId, storageScope: JSON.stringify([scope.accountId]), migrateLegacy: true, metadataOnly: true });
|
|
92
|
+
this.readers = new MessageReadersClient({ appId: scope.appId, profileId: scope.profileId, token: options.reading.sessionToken, scope, access: () => this.messages.scopeAccess(), onError: options.onError, hubHttpUrl: options.reading.hubHttpUrl, fetch: options.reading.fetch });
|
|
93
|
+
if (options.loadGroup) {
|
|
94
|
+
this.groups = new GroupClient({ local: !!options.inbox, scope, access: () => this.messages.scopeAccess(), load: options.loadGroup, onError: options.onError, onDenied: async (error, _threadId, signal) => {
|
|
95
|
+
if (error?.status === 403 && options.messages.transport.authorizeScope) {
|
|
96
|
+
try {
|
|
97
|
+
await options.messages.transport.authorizeScope(signal ?? new AbortController().signal);
|
|
98
|
+
this.assertOpen();
|
|
99
|
+
if ((await this.messages.scopeAccess()).allowed)
|
|
100
|
+
return true;
|
|
101
|
+
}
|
|
102
|
+
catch { }
|
|
103
|
+
}
|
|
104
|
+
void this.revokeAccess().catch(error => options.onError(error));
|
|
105
|
+
return false;
|
|
106
|
+
} });
|
|
107
|
+
this.off.push(this.groups.subscribe(thread => this.publish(thread)));
|
|
108
|
+
}
|
|
109
|
+
this.sender = new DurableChatSender(this.connection, scope, options.onError, { access: () => this.messages.scopeAccess(), uploadVoice: options.uploadVoice, reconcile: async (record, signal) => {
|
|
110
|
+
const cached = await this.messages.cachedMessage(record.threadId, record.message.hash);
|
|
111
|
+
if (cached && cached.from === scope.profileId && cached.to === record.message.to)
|
|
112
|
+
return true;
|
|
113
|
+
if (!options.reconcileOutgoing)
|
|
114
|
+
throw new Error("OUTBOX_RECONCILIATION_UNAVAILABLE");
|
|
115
|
+
try {
|
|
116
|
+
return await options.reconcileOutgoing(record, signal);
|
|
117
|
+
}
|
|
118
|
+
catch (error) {
|
|
119
|
+
if ([401, 403].includes(error?.status ?? 0))
|
|
120
|
+
await this.messages.revoke(record.threadId);
|
|
121
|
+
throw error;
|
|
122
|
+
}
|
|
123
|
+
} });
|
|
44
124
|
this.catchUp = new WindowedTasks(1000, error => { if (!this.closed)
|
|
45
125
|
options.onError(error); });
|
|
126
|
+
this.countTasks = new WindowedTasks(50, error => { if (!this.closed)
|
|
127
|
+
options.onError(error); });
|
|
128
|
+
if (typeof window !== "undefined") {
|
|
129
|
+
const wake = () => {
|
|
130
|
+
if (typeof document !== "undefined" && document.hidden)
|
|
131
|
+
return;
|
|
132
|
+
this.wakeCounts();
|
|
133
|
+
this.groups?.wake();
|
|
134
|
+
this.scheduleCatchUp();
|
|
135
|
+
};
|
|
136
|
+
for (const type of ["online", "focus", "pageshow"])
|
|
137
|
+
window.addEventListener(type, wake);
|
|
138
|
+
if (typeof document !== "undefined")
|
|
139
|
+
document.addEventListener("visibilitychange", wake);
|
|
140
|
+
this.off.push(() => {
|
|
141
|
+
for (const type of ["online", "focus", "pageshow"])
|
|
142
|
+
window.removeEventListener(type, wake);
|
|
143
|
+
if (typeof document !== "undefined")
|
|
144
|
+
document.removeEventListener("visibilitychange", wake);
|
|
145
|
+
});
|
|
146
|
+
}
|
|
147
|
+
this.off.push(this.messages.subscribeAccessRevoked(() => { if (!this.withdrawn && !this.closed)
|
|
148
|
+
void this.revokeAccess().catch(error => options.onError(error)); }));
|
|
46
149
|
this.off.push(this.messages.subscribeAll(thread => this.publish(thread)));
|
|
47
|
-
|
|
150
|
+
if (options.inbox)
|
|
151
|
+
this.off.push(options.inbox.subscribe(threads => {
|
|
152
|
+
for (const thread of threads)
|
|
153
|
+
this.messages.invalidate(thread);
|
|
154
|
+
this.groups?.wake();
|
|
155
|
+
}));
|
|
156
|
+
this.off.push(this.sender.subscribe(() => this.publishAll()), this.reading.subscribe(() => { this.publishAll(); if (this.readingAllowed)
|
|
157
|
+
this.readingListeners.forEach(listener => listener()); }));
|
|
48
158
|
this.off.push(this.connection.watchMessages(message => {
|
|
159
|
+
// Inbox is the only authoritative incoming message source in this mode.
|
|
160
|
+
// The shared socket still owns calls, presence and outgoing ACKs.
|
|
161
|
+
if (options.inbox)
|
|
162
|
+
return;
|
|
49
163
|
try {
|
|
164
|
+
const body = message.body;
|
|
165
|
+
if (body?.kind === "group" && body.payload?.appId === scope.appId && body.payload.teamId === scope.teamId && body.payload.groupId === message.to) {
|
|
166
|
+
this.groups?.hint({ id: groupThreadId(scope.appId, message.to, scope.teamId), kind: "group", targetId: message.to, teamId: scope.teamId }, Number.isSafeInteger(body.payload.versionNumber) ? body.payload.versionNumber : undefined);
|
|
167
|
+
}
|
|
50
168
|
const decoded = options.decode(message);
|
|
169
|
+
// A peer can react before history returns our own ACKed source message.
|
|
170
|
+
// Discussion windows store controls against canonical target IDs; retain
|
|
171
|
+
// the known sent local target in the same atomic receive batch so the
|
|
172
|
+
// reaction is visible without waiting for another network history read.
|
|
173
|
+
const control = message.body?.content;
|
|
174
|
+
const targetId = control?.reaction?.messageId ?? control?.recall?.messageId;
|
|
175
|
+
const outgoing = decoded && targetId ? this.sender.snapshot(decoded.threadId).find(record => record.hash === targetId && record.status === 'sent' && record.message.from === scope.profileId) : undefined;
|
|
176
|
+
const localTarget = outgoing && options.decode(outgoing.message);
|
|
51
177
|
if (decoded)
|
|
52
|
-
void this.messages.receive(decoded.threadId, [decoded]
|
|
178
|
+
void this.messages.receive(decoded.threadId, localTarget ? [localTarget, decoded] : [decoded]).then(async () => {
|
|
179
|
+
if (!this.closed && this.readingStarted)
|
|
180
|
+
this.reading.refresh();
|
|
181
|
+
if (message.from === scope.profileId)
|
|
182
|
+
await this.sender.confirm([message.hash]);
|
|
183
|
+
}).catch(error => { if (String(error).includes("MESSAGE_PROJECTION_CHANGED"))
|
|
53
184
|
this.messages.invalidate(decoded.threadId);
|
|
54
185
|
else if (!this.closed)
|
|
55
186
|
options.onError(error); });
|
|
@@ -62,24 +193,125 @@ export class ChatSession {
|
|
|
62
193
|
this.connectionState = state;
|
|
63
194
|
this.publishGlobal();
|
|
64
195
|
if (state === "connected") {
|
|
65
|
-
|
|
66
|
-
this.catchUp.schedule("scope", () => this.messages.restore(since));
|
|
196
|
+
this.scheduleCatchUp();
|
|
67
197
|
if (this.readingStarted)
|
|
68
198
|
this.reading.refresh();
|
|
199
|
+
this.wakeCounts();
|
|
200
|
+
this.groups?.wake();
|
|
69
201
|
}
|
|
70
202
|
}));
|
|
71
203
|
}
|
|
204
|
+
scheduleCatchUp() {
|
|
205
|
+
if (this.connectionState !== "connected" || this.closed || this.withdrawn)
|
|
206
|
+
return;
|
|
207
|
+
const since = Date.now();
|
|
208
|
+
this.catchUp.schedule("scope", async () => {
|
|
209
|
+
if (this.connectionState === "connected" && !this.closed && !this.withdrawn)
|
|
210
|
+
await this.messages.restore(since, this.options.activeThreadId);
|
|
211
|
+
});
|
|
212
|
+
}
|
|
72
213
|
start() {
|
|
73
214
|
this.assertOpen();
|
|
74
215
|
return this.starting ??= (async () => {
|
|
75
|
-
await this.
|
|
76
|
-
this.readingStarted = true;
|
|
77
|
-
await this.reading.start();
|
|
216
|
+
await this.initialize();
|
|
78
217
|
this.assertOpen();
|
|
79
218
|
await this.connection.connect();
|
|
80
219
|
})().catch(error => { this.starting = undefined; throw error; });
|
|
81
220
|
}
|
|
82
|
-
|
|
221
|
+
/** Initializes local state and background reading sync without opening a
|
|
222
|
+
* second transport when the host already owns calls/presence. */
|
|
223
|
+
initialize() {
|
|
224
|
+
this.assertOpen();
|
|
225
|
+
return this.initializing ??= (async () => {
|
|
226
|
+
await this.options.inbox?.start();
|
|
227
|
+
await this.sender.initialize();
|
|
228
|
+
this.assertOpen();
|
|
229
|
+
await this.startReading();
|
|
230
|
+
this.assertOpen();
|
|
231
|
+
})().catch(error => { this.initializing = undefined; throw error; });
|
|
232
|
+
}
|
|
233
|
+
startReading() {
|
|
234
|
+
if (this.readingStarted)
|
|
235
|
+
return Promise.resolve();
|
|
236
|
+
return this.readingStarting ??= (async () => {
|
|
237
|
+
const access = await this.messages.scopeAccess();
|
|
238
|
+
if (!access.allowed)
|
|
239
|
+
return;
|
|
240
|
+
this.assertOpen();
|
|
241
|
+
await this.reading.prepareTeam(this.options.messages.scope.teamId, access.version);
|
|
242
|
+
this.setReadingAllowed(true);
|
|
243
|
+
await this.reading.start();
|
|
244
|
+
this.assertOpen();
|
|
245
|
+
this.readingStarted = true;
|
|
246
|
+
})().finally(() => { this.readingStarting = undefined; });
|
|
247
|
+
}
|
|
248
|
+
/** One-time migration only: never establishes trusted history coverage. */
|
|
249
|
+
importLegacyMessages(threadId, messages) { this.assertOpen(); return this.messages.importLegacy(threadId, messages); }
|
|
250
|
+
getReadingSnapshot() { return this.closed || this.withdrawn || !this.readingAllowed ? undefined : this.reading.getSnapshot(); }
|
|
251
|
+
subscribeReading(listener) { if (this.closed || this.withdrawn)
|
|
252
|
+
return () => { }; this.readingListeners.add(listener); return () => { this.readingListeners.delete(listener); }; }
|
|
253
|
+
setReadingAllowed(allowed) {
|
|
254
|
+
if (this.readingAllowed === allowed)
|
|
255
|
+
return;
|
|
256
|
+
const previous = this.getReadingSnapshot();
|
|
257
|
+
this.readingAllowed = allowed;
|
|
258
|
+
if (previous !== this.getReadingSnapshot())
|
|
259
|
+
this.readingListeners.forEach(listener => listener());
|
|
260
|
+
this.publishAll();
|
|
261
|
+
}
|
|
262
|
+
readingAuthority() {
|
|
263
|
+
return this.readingAccess ??= this.messages.scopeAccess().then(access => { if (!access.allowed)
|
|
264
|
+
this.setReadingAllowed(false); return access; }).finally(() => { this.readingAccess = undefined; });
|
|
265
|
+
}
|
|
266
|
+
async authorizeReading() {
|
|
267
|
+
const access = await this.readingAuthority();
|
|
268
|
+
if (this.withdrawn || !access.allowed)
|
|
269
|
+
throw new Error("CHAT_ACCESS_REVOKED");
|
|
270
|
+
await this.reading.prepareTeam(this.options.messages.scope.teamId, access.version);
|
|
271
|
+
this.setReadingAllowed(true);
|
|
272
|
+
}
|
|
273
|
+
readingOperation(run, durable = true) {
|
|
274
|
+
if (this.closed || this.withdrawn)
|
|
275
|
+
return Promise.reject(new Error(this.withdrawn ? "CHAT_ACCESS_REVOKED" : "CHAT_SESSION_CLOSED"));
|
|
276
|
+
const task = (async () => {
|
|
277
|
+
await this.authorizeReading();
|
|
278
|
+
if (this.withdrawn)
|
|
279
|
+
throw new Error("CHAT_ACCESS_REVOKED");
|
|
280
|
+
if (!durable)
|
|
281
|
+
this.assertOpen();
|
|
282
|
+
const next = await run();
|
|
283
|
+
if (this.withdrawn || !(await this.readingAuthority()).allowed)
|
|
284
|
+
throw new Error("CHAT_ACCESS_REVOKED");
|
|
285
|
+
return next;
|
|
286
|
+
})();
|
|
287
|
+
if (durable) {
|
|
288
|
+
this.acceptedReading.add(task);
|
|
289
|
+
void task.finally(() => this.acceptedReading.delete(task)).catch(() => { });
|
|
290
|
+
}
|
|
291
|
+
return task;
|
|
292
|
+
}
|
|
293
|
+
refreshReading() {
|
|
294
|
+
if (this.closed || this.withdrawn)
|
|
295
|
+
return;
|
|
296
|
+
void this.authorizeReading().then(() => { if (!this.closed && !this.withdrawn)
|
|
297
|
+
this.reading.refresh(); }).catch(error => { if (!this.closed && !this.withdrawn)
|
|
298
|
+
this.options.onError(error); });
|
|
299
|
+
}
|
|
300
|
+
synchronizeReading(cursor, profileId) { return this.readingOperation(() => this.reading.synchronize(cursor, profileId), false); }
|
|
301
|
+
/** Explicit text-history acknowledgement; unheard audio stays unread. */
|
|
302
|
+
async markRead(threadId, messages) {
|
|
303
|
+
this.assertOpen();
|
|
304
|
+
const cached = messages ?? this.getSnapshot(threadId).timeline.flatMap(item => {
|
|
305
|
+
if (item.recalled || !item.message)
|
|
306
|
+
return [];
|
|
307
|
+
const candidate = this.options.readingCandidate?.(item.message);
|
|
308
|
+
return candidate ? [{ id: item.id, threadId, threadRootId: item.threadRootId, from: item.from, mine: item.mine, recalled: item.recalled, readPolicy: candidate.readPolicy }] : [];
|
|
309
|
+
});
|
|
310
|
+
return this.readingOperation(() => this.reading.markRead(threadId, cached, this.options.discussion?.threadRootId));
|
|
311
|
+
}
|
|
312
|
+
updateReading(transform) { return this.readingOperation(() => this.reading.update(transform)); }
|
|
313
|
+
assertOpen() { if (this.withdrawn)
|
|
314
|
+
throw new Error("CHAT_ACCESS_REVOKED"); if (this.closed)
|
|
83
315
|
throw new Error("CHAT_SESSION_CLOSED"); }
|
|
84
316
|
async getMessages(threadId, options = {}) {
|
|
85
317
|
this.assertOpen();
|
|
@@ -92,18 +324,31 @@ export class ChatSession {
|
|
|
92
324
|
throw new Error("INVALID_MESSAGE_QUERY");
|
|
93
325
|
// Explicit authoritative changes (for example history assignment) can invalidate
|
|
94
326
|
// even a recently cached empty window. Keep this on the existing read surface.
|
|
95
|
-
|
|
96
|
-
await this.messages.read(threadId, options.limit ?? 100, true);
|
|
327
|
+
const refreshed = options.refresh ? await this.messages.read(threadId, options.limit ?? 100, true) : undefined;
|
|
97
328
|
if (options.all) {
|
|
98
329
|
return this.readAll(threadId);
|
|
99
330
|
}
|
|
100
|
-
const page = await (options.before ? this.messages.earlier(threadId, options.before, options.limit) : this.messages.read(threadId, options.limit));
|
|
101
|
-
|
|
331
|
+
const page = await (options.before ? this.messages.earlier(threadId, options.before, options.limit) : refreshed ?? this.messages.read(threadId, options.limit));
|
|
332
|
+
this.assertOpen();
|
|
333
|
+
await this.confirmMessages(page.messages);
|
|
334
|
+
if (this.initializing && !this.readingStarted && page.complete)
|
|
335
|
+
await this.startReading();
|
|
336
|
+
this.assertOpen();
|
|
102
337
|
const edge = this.historyEdges.get(threadId);
|
|
103
338
|
if (!options.before && page.complete && (!edge || edge.version !== page.resetVersion))
|
|
104
339
|
this.rememberHistoryEdge(threadId, page);
|
|
105
340
|
return page;
|
|
106
341
|
}
|
|
342
|
+
async confirmMessages(messages) {
|
|
343
|
+
await this.sender.initialize();
|
|
344
|
+
// Only this profile can create its outgoing wire hashes. Keep the legacy
|
|
345
|
+
// fallback when a generic host has not supplied an author on stored rows.
|
|
346
|
+
const hashes = messages.filter(message => {
|
|
347
|
+
const from = message.from;
|
|
348
|
+
return typeof from !== "string" || !from || from === this.options.messages.scope.profileId;
|
|
349
|
+
}).map(message => message.id);
|
|
350
|
+
return hashes.length ? this.sender.confirm(hashes) : Promise.resolve();
|
|
351
|
+
}
|
|
107
352
|
rememberHistoryEdge(threadId, page) {
|
|
108
353
|
const first = page.messages[0];
|
|
109
354
|
this.historyEdges.set(threadId, { before: first ? { timestamp: first.timestamp, id: first.id } : undefined, version: page.resetVersion, hasEarlier: page.hasEarlier });
|
|
@@ -113,7 +358,12 @@ export class ChatSession {
|
|
|
113
358
|
if (running)
|
|
114
359
|
return running;
|
|
115
360
|
const task = (async () => {
|
|
116
|
-
const
|
|
361
|
+
const cached = this.messages.getSnapshot(threadId), known = this.historyEdges.get(threadId);
|
|
362
|
+
// The earlier-page path validates its own durable scope and coverage.
|
|
363
|
+
// A known boundary does not require rereading/reconfirming the newest
|
|
364
|
+
// message bodies before loading older messages.
|
|
365
|
+
const recent = cached?.complete && known?.hasEarlier && known.version === cached.resetVersion
|
|
366
|
+
? cached : await this.getMessages(threadId);
|
|
117
367
|
if (!recent.complete)
|
|
118
368
|
throw new Error("MESSAGE_WINDOW_INCOMPLETE");
|
|
119
369
|
const edge = this.historyEdges.get(threadId);
|
|
@@ -121,7 +371,8 @@ export class ChatSession {
|
|
|
121
371
|
return { ...recent, messages: [], hasEarlier: false };
|
|
122
372
|
if (!edge.before)
|
|
123
373
|
throw new Error("MESSAGE_SYNC_NO_PROGRESS");
|
|
124
|
-
const page = await this.
|
|
374
|
+
const page = await this.messages.earlier(threadId, edge.before, 100, true);
|
|
375
|
+
await this.confirmMessages(page.messages);
|
|
125
376
|
this.assertOpen();
|
|
126
377
|
this.rememberHistoryEdge(threadId, page);
|
|
127
378
|
return page;
|
|
@@ -151,12 +402,18 @@ export class ChatSession {
|
|
|
151
402
|
break;
|
|
152
403
|
}
|
|
153
404
|
pages.push(page.messages);
|
|
405
|
+
if (!page.complete)
|
|
406
|
+
return { messages: pages.reverse().flat(), hasEarlier: true, complete: false, resetVersion: version };
|
|
154
407
|
}
|
|
155
408
|
if (restart)
|
|
156
409
|
continue;
|
|
157
|
-
|
|
410
|
+
const result = { messages: pages.reverse().flat(), hasEarlier: false, complete: true, resetVersion: version };
|
|
411
|
+
await this.messages.expandWindow(threadId, result);
|
|
412
|
+
this.rememberHistoryEdge(threadId, result);
|
|
413
|
+
return result;
|
|
158
414
|
}
|
|
159
415
|
catch (error) {
|
|
416
|
+
this.assertOpen();
|
|
160
417
|
if ([401, 403].includes(error?.status ?? 0))
|
|
161
418
|
throw error;
|
|
162
419
|
if (String(error).includes("MESSAGE_PROJECTION_CHANGED"))
|
|
@@ -168,20 +425,339 @@ export class ChatSession {
|
|
|
168
425
|
}
|
|
169
426
|
throw new Error("MESSAGE_SYNC_RESET_REQUIRED");
|
|
170
427
|
}
|
|
171
|
-
|
|
428
|
+
/** Reads trusted local group metadata immediately; SDK refreshes it in the background. */
|
|
429
|
+
async getGroup(thread, options = {}) {
|
|
430
|
+
this.assertOpen();
|
|
431
|
+
if (!this.groups)
|
|
432
|
+
throw new Error("GROUP_METADATA_UNAVAILABLE");
|
|
433
|
+
return this.groups.get(typeof thread === "string" ? await this.resolveConversation(thread) : thread, options);
|
|
434
|
+
}
|
|
435
|
+
async createGroup(thread, content) {
|
|
436
|
+
this.assertOpen();
|
|
437
|
+
if (!this.groups)
|
|
438
|
+
throw new Error("GROUP_METADATA_UNAVAILABLE");
|
|
439
|
+
await this.sendMessage(thread, { groupCreate: content }, { waitFor: "delivered" });
|
|
440
|
+
return this.groups.after(thread, 1);
|
|
441
|
+
}
|
|
442
|
+
async updateGroup(target, changes) {
|
|
443
|
+
const thread = typeof target === "string" ? await this.resolveConversation(target) : target;
|
|
444
|
+
const previous = await this.getGroup(thread);
|
|
445
|
+
if (previous.versionNumber >= Number.MAX_SAFE_INTEGER)
|
|
446
|
+
throw new Error("INVALID_GROUP_VERSION");
|
|
447
|
+
await this.sendMessage(thread, { groupUpdate: { ...changes, expectedRevision: changes.expectedRevision ?? previous.revision } }, { waitFor: "delivered" });
|
|
448
|
+
return this.groups.after(thread, previous.versionNumber + 1);
|
|
449
|
+
}
|
|
450
|
+
async dissolveGroup(target, options = {}) {
|
|
451
|
+
const thread = typeof target === "string" ? await this.resolveConversation(target) : target;
|
|
452
|
+
const previous = await this.getGroup(thread);
|
|
453
|
+
if (previous.status === "dissolved")
|
|
454
|
+
return previous;
|
|
455
|
+
if (previous.versionNumber >= Number.MAX_SAFE_INTEGER)
|
|
456
|
+
throw new Error("INVALID_GROUP_VERSION");
|
|
457
|
+
await this.sendMessage(thread, { groupDissolve: { expectedRevision: options.expectedRevision ?? previous.revision } }, { waitFor: "delivered" });
|
|
458
|
+
return this.groups.after(thread, previous.versionNumber + 1);
|
|
459
|
+
}
|
|
460
|
+
sendMessage(thread, input, options = {}) {
|
|
461
|
+
this.assertOpen();
|
|
462
|
+
if (options.waitFor !== undefined && !["accepted", "delivered"].includes(options.waitFor))
|
|
463
|
+
throw new Error("INVALID_MESSAGE_WAIT");
|
|
464
|
+
if (typeof thread === "string" && Object.hasOwn(input, "body"))
|
|
465
|
+
return this.sendWire(thread, input, options.waitFor === "delivered");
|
|
466
|
+
return this.sendContent(thread, input, options.waitFor === "delivered");
|
|
467
|
+
}
|
|
468
|
+
sharedTransport() { this.assertOpen(); return this.connection; }
|
|
469
|
+
async getMessageThreads(threadId, roots, signal) {
|
|
470
|
+
this.assertOpen();
|
|
471
|
+
if (!this.options.messageThreads)
|
|
472
|
+
throw new Error("MESSAGE_THREADS_UNAVAILABLE");
|
|
473
|
+
return this.options.messageThreads(threadId, roots, signal);
|
|
474
|
+
}
|
|
475
|
+
sendWire(threadId, wire, delivered) {
|
|
476
|
+
return (delivered ? this.sender.send(threadId, wire) : this.sender.enqueue(threadId, wire)).then(next => { if (this.withdrawn)
|
|
477
|
+
throw new Error("CHAT_ACCESS_REVOKED"); return next; });
|
|
478
|
+
}
|
|
479
|
+
async getConversation(target) {
|
|
480
|
+
this.assertOpen();
|
|
481
|
+
try {
|
|
482
|
+
return await this.conversations.create(target);
|
|
483
|
+
}
|
|
484
|
+
catch (error) {
|
|
485
|
+
if (error?.message !== "CHAT_ACCESS_REVOKED")
|
|
486
|
+
throw error;
|
|
487
|
+
await this.messages.authorizeScope();
|
|
488
|
+
this.assertOpen();
|
|
489
|
+
return this.conversations.create(target);
|
|
490
|
+
}
|
|
491
|
+
}
|
|
492
|
+
async sendContent(target, input, delivered) {
|
|
493
|
+
if (this.options.discussion?.threadRootId !== undefined) {
|
|
494
|
+
if (input.threadRootId !== undefined && input.threadRootId !== this.options.discussion.threadRootId)
|
|
495
|
+
throw new Error("MESSAGE_THREAD_SCOPE_MISMATCH");
|
|
496
|
+
input = { ...input, threadRootId: this.options.discussion.threadRootId };
|
|
497
|
+
}
|
|
498
|
+
let thread = typeof target === "string" ? await this.resolveConversation(target) : target;
|
|
499
|
+
validateConversation(this.options.messages.scope, thread);
|
|
500
|
+
await this.conversations.put(thread);
|
|
501
|
+
this.assertOpen();
|
|
502
|
+
// Recipients are SDK-owned metadata, never an App-supplied roster.
|
|
503
|
+
if (thread.kind === "group" && !input.groupCreate && !input.groupUpdate && !input.groupDissolve) {
|
|
504
|
+
const group = await this.getGroup(thread);
|
|
505
|
+
if (group.status === "dissolved")
|
|
506
|
+
throw new Error("GROUP_DISSOLVED");
|
|
507
|
+
this.assertOpen();
|
|
508
|
+
thread = { ...thread, memberIds: group.memberIds };
|
|
509
|
+
}
|
|
510
|
+
const wire = outgoingContent(this.options.messages.scope, thread, input);
|
|
511
|
+
if (input.recall || input.reaction)
|
|
512
|
+
return this.sendControl({ ...thread, memberIds: wire.recipients }, wire, delivered);
|
|
513
|
+
return this.sendWire(thread.id, wire, delivered);
|
|
514
|
+
}
|
|
515
|
+
async resolveConversation(threadId) {
|
|
516
|
+
const known = await this.conversations.get(threadId);
|
|
517
|
+
if (known)
|
|
518
|
+
return known;
|
|
519
|
+
const inferred = this.getConversationTarget(threadId);
|
|
520
|
+
if (!inferred)
|
|
521
|
+
throw new Error("MESSAGE_CONVERSATION_UNKNOWN");
|
|
522
|
+
return inferred;
|
|
523
|
+
}
|
|
524
|
+
/** Validated target identity survives content redaction; no roster is exposed. */
|
|
525
|
+
getConversationTarget(threadId) {
|
|
526
|
+
const scope = this.options.messages.scope;
|
|
527
|
+
const snapshot = this.getSnapshot(threadId), group = snapshot.group;
|
|
528
|
+
if (group)
|
|
529
|
+
return { id: threadId, kind: "group", targetId: group.groupId, teamId: scope.teamId };
|
|
530
|
+
const infer = (row) => {
|
|
531
|
+
const kind = row.threadKind ?? row.body?.threadKind;
|
|
532
|
+
if ((kind !== "group" && kind !== "dm") || !row.to || !row.from)
|
|
533
|
+
return undefined;
|
|
534
|
+
const thread = { id: threadId, kind, targetId: kind === "group" || row.from === scope.profileId ? row.to : row.from, teamId: scope.teamId };
|
|
535
|
+
try {
|
|
536
|
+
validateConversation(scope, thread);
|
|
537
|
+
return thread;
|
|
538
|
+
}
|
|
539
|
+
catch {
|
|
540
|
+
return undefined;
|
|
541
|
+
}
|
|
542
|
+
};
|
|
543
|
+
for (const value of snapshot.messages) {
|
|
544
|
+
const thread = infer(value);
|
|
545
|
+
if (thread)
|
|
546
|
+
return thread;
|
|
547
|
+
}
|
|
548
|
+
// Older integrations may have a durable send but no registered target or indexed history yet.
|
|
549
|
+
for (const value of snapshot.outgoing) {
|
|
550
|
+
const thread = infer(value.message);
|
|
551
|
+
if (thread)
|
|
552
|
+
return thread;
|
|
553
|
+
}
|
|
554
|
+
return undefined;
|
|
555
|
+
}
|
|
556
|
+
sendControl(thread, wire, delivered = false) {
|
|
557
|
+
const content = wire.body.content;
|
|
558
|
+
const recall = content.recall, reaction = content.reaction;
|
|
559
|
+
const id = recall?.messageId ?? reaction.messageId, key = JSON.stringify([thread.id, id, reaction?.emojiId ?? "recall"]);
|
|
560
|
+
const bytes = JSON.stringify(wire).length * 3 + 1024;
|
|
561
|
+
if (this.controlCount >= 4096 || this.controlBytes + bytes > 64 * 1024 * 1024)
|
|
562
|
+
return Promise.reject(new Error("MESSAGE_CONTROL_BACKPRESSURE"));
|
|
563
|
+
this.controlCount++;
|
|
564
|
+
this.controlBytes += bytes;
|
|
565
|
+
const previous = this.controlTails.get(key) ?? Promise.resolve();
|
|
566
|
+
let delivery;
|
|
567
|
+
const validated = previous.catch(() => { }).then(async () => {
|
|
568
|
+
this.assertOpen();
|
|
569
|
+
const item = this.getSnapshot(thread.id).timeline.find(item => item.id === id);
|
|
570
|
+
const target = (item?.message ?? await this.messages.cachedMessage(thread.id, id));
|
|
571
|
+
this.assertOpen();
|
|
572
|
+
const scope = this.options.messages.scope, from = item?.from ?? target?.from, body = target?.body;
|
|
573
|
+
const wrongScope = target?.threadId !== thread.id || target.appId !== undefined && target.appId !== scope.appId || body?.content?.appId !== undefined && body.content.appId !== scope.appId || body?.threadKind !== undefined && body.threadKind !== thread.kind;
|
|
574
|
+
const unavailable = !target || !from || id.startsWith("local-") || target.recalled || item?.recalled || target.legacyDisplay?.kind === "system" || item?.status === "failed" || item?.status === "sending";
|
|
575
|
+
const ordinary = body && ["message", "quote"].includes(String(body.kind)) && !isReadingControl(body, scope.appId);
|
|
576
|
+
if (wrongScope || unavailable || !ordinary)
|
|
577
|
+
throw new Error("MESSAGE_CONTROL_TARGET_UNAVAILABLE");
|
|
578
|
+
if (recall && from !== scope.profileId)
|
|
579
|
+
throw new Error("MESSAGE_RECALL_NOT_OWNED");
|
|
580
|
+
if (thread.kind === "dm" && from !== scope.profileId && from !== thread.targetId || thread.kind === "group" && (!wire.recipients?.includes(scope.profileId) || !wire.recipients.includes(from)))
|
|
581
|
+
throw new Error("MESSAGE_CONTROL_TARGET_UNAVAILABLE");
|
|
582
|
+
if (reaction) {
|
|
583
|
+
let floor = 0;
|
|
584
|
+
const events = item?.reactionEvents ?? target.reactionEvents ?? target.legacyDisplay?.reactionEvents ?? [];
|
|
585
|
+
for (const event of events)
|
|
586
|
+
if (event.from === scope.profileId && event.messageId === id && event.emojiId === reaction.emojiId && Number.isSafeInteger(event.revision) && event.revision > floor)
|
|
587
|
+
floor = event.revision;
|
|
588
|
+
for (const record of this.sender.snapshot(thread.id)) {
|
|
589
|
+
const envelope = record.message.body, event = envelope?.content?.reaction;
|
|
590
|
+
if (record.message.from === scope.profileId && envelope?.content?.appId === scope.appId && event?.messageId === id && event.emojiId === reaction.emojiId && Number.isSafeInteger(event.revision) && event.revision > floor)
|
|
591
|
+
floor = event.revision;
|
|
592
|
+
}
|
|
593
|
+
wire = { ...wire, reactionRevisionFloor: floor };
|
|
594
|
+
}
|
|
595
|
+
delivery = delivered ? this.sender.send(thread.id, wire) : this.sender.enqueue(thread.id, wire);
|
|
596
|
+
void delivery.catch(() => { });
|
|
597
|
+
});
|
|
598
|
+
const tail = validated.finally(() => { if (this.controlTails.get(key) === tail)
|
|
599
|
+
this.controlTails.delete(key); });
|
|
600
|
+
const task = tail.then(() => delivery).then(message => { if (this.withdrawn)
|
|
601
|
+
throw new Error("CHAT_ACCESS_REVOKED"); return message; }).finally(() => { this.controlCount--; this.controlBytes -= bytes; this.acceptedControls.delete(task); });
|
|
602
|
+
this.controlTails.set(key, tail);
|
|
603
|
+
this.acceptedControls.add(task);
|
|
604
|
+
return task;
|
|
605
|
+
}
|
|
606
|
+
async getReaders(threadId, messageId, page = {}, signal) {
|
|
172
607
|
this.assertOpen();
|
|
173
|
-
|
|
608
|
+
const result = await this.readers.getReaders({ ...page, threadId, messageId }, signal);
|
|
609
|
+
this.assertOpen();
|
|
610
|
+
if (!result.resetRequired) {
|
|
611
|
+
const previous = this.countSnapshots.get(threadId);
|
|
612
|
+
if (!previous || previous.revision <= result.revision) {
|
|
613
|
+
this.publishCounts({ appId: result.appId, threadId, revision: result.revision, counts: { ...previous?.counts, [messageId]: result.total } });
|
|
614
|
+
this.counts?.changed(threadId, result.revision);
|
|
615
|
+
}
|
|
616
|
+
}
|
|
617
|
+
return result;
|
|
174
618
|
}
|
|
175
|
-
|
|
619
|
+
/** Resolve voice media uniformly; pending local bytes are loaded only on demand. */
|
|
620
|
+
async getVoiceAttachment(threadId, messageId) {
|
|
176
621
|
this.assertOpen();
|
|
177
|
-
|
|
622
|
+
const item = this.getSnapshot(threadId).timeline.find(item => item.id === messageId);
|
|
623
|
+
if (!item || item.recalled)
|
|
624
|
+
throw new Error("VOICE_ATTACHMENT_UNAVAILABLE");
|
|
625
|
+
const local = await this.sender.acquireVoice(messageId, threadId);
|
|
626
|
+
try {
|
|
627
|
+
this.assertOpen();
|
|
628
|
+
}
|
|
629
|
+
catch (error) {
|
|
630
|
+
local?.release();
|
|
631
|
+
throw error;
|
|
632
|
+
}
|
|
633
|
+
const stillVisible = this.getSnapshot(threadId).timeline.find(item => item.id === messageId);
|
|
634
|
+
if (!stillVisible || stillVisible.recalled) {
|
|
635
|
+
local?.release();
|
|
636
|
+
throw new Error("VOICE_ATTACHMENT_UNAVAILABLE");
|
|
637
|
+
}
|
|
638
|
+
if (local)
|
|
639
|
+
return local;
|
|
640
|
+
const current = this.getSnapshot(threadId).timeline.find(item => item.id === messageId);
|
|
641
|
+
const body = current?.message?.body;
|
|
642
|
+
const value = body?.content?.voice?.url;
|
|
643
|
+
if (!current || current.recalled || typeof value !== "string")
|
|
644
|
+
throw new Error("VOICE_ATTACHMENT_UNAVAILABLE");
|
|
645
|
+
const url = new URL(value);
|
|
646
|
+
if (!["http:", "https:"].includes(url.protocol) || url.username || url.password)
|
|
647
|
+
throw new Error("INVALID_VOICE_ATTACHMENT_URL");
|
|
648
|
+
return { url: value, release: () => { } };
|
|
178
649
|
}
|
|
179
650
|
retryMessage(messageId) { this.assertOpen(); return this.sender.retry(messageId); }
|
|
180
|
-
observeMessages(threadId, ids, event) {
|
|
651
|
+
observeMessages(threadId, ids, event, clientInstanceId) {
|
|
652
|
+
if (this.closed || this.withdrawn) {
|
|
653
|
+
if (event === "receipts" && !threadId)
|
|
654
|
+
return Promise.resolve();
|
|
655
|
+
return Promise.reject(new Error(this.withdrawn ? "CHAT_ACCESS_REVOKED" : "CHAT_SESSION_CLOSED"));
|
|
656
|
+
}
|
|
657
|
+
if (event === "receipts") {
|
|
658
|
+
this.watchCounts(threadId, ids, clientInstanceId);
|
|
659
|
+
return Promise.resolve();
|
|
660
|
+
}
|
|
661
|
+
if (!threadId)
|
|
662
|
+
throw new Error("INVALID_READING_THREAD");
|
|
663
|
+
return this.readingOperation(() => event === "played" ? this.reading.recordExplicit(threadId, ids) : this.reading.recordVisible(threadId, ids));
|
|
664
|
+
}
|
|
665
|
+
/** Bridge transports can delegate social events without maintaining clients. */
|
|
666
|
+
async handleReach(event) {
|
|
181
667
|
this.assertOpen();
|
|
182
|
-
|
|
668
|
+
if (!["social.readCountsChanged", "social.readStateChanged"].includes(event.eventType))
|
|
669
|
+
return undefined;
|
|
670
|
+
if (event.appId !== this.options.messages.scope.appId)
|
|
671
|
+
throw new Error("UNEXPECTED_READING_APPLICATION");
|
|
672
|
+
if (this.options.inbox && event.eventType === "social.readStateChanged") {
|
|
673
|
+
if (event.payload.profileId !== this.options.messages.scope.profileId)
|
|
674
|
+
throw new Error("Reading reach identity mismatch");
|
|
675
|
+
return "handled";
|
|
676
|
+
}
|
|
677
|
+
if (event.eventType === "social.readCountsChanged") {
|
|
678
|
+
if (typeof event.payload.threadId !== "string" || !Number.isSafeInteger(event.payload.revision) || Number(event.payload.revision) < 0)
|
|
679
|
+
throw new Error("INVALID_READ_COUNTS_EVENT");
|
|
680
|
+
this.counts?.changed(event.payload.threadId, Number(event.payload.revision));
|
|
681
|
+
}
|
|
682
|
+
else {
|
|
683
|
+
if (typeof event.payload.syncCursor !== "string" || !/^v1:\d+$/.test(event.payload.syncCursor) || typeof event.payload.profileId !== "string")
|
|
684
|
+
throw new Error("INVALID_READING_EVENT");
|
|
685
|
+
if (event.payload.profileId !== this.options.messages.scope.profileId)
|
|
686
|
+
throw new Error("Reading reach identity mismatch");
|
|
687
|
+
await this.initialize();
|
|
688
|
+
await this.synchronizeReading(event.payload.syncCursor, event.payload.profileId);
|
|
689
|
+
this.assertOpen();
|
|
690
|
+
}
|
|
691
|
+
return "handled";
|
|
692
|
+
}
|
|
693
|
+
wakeCounts() {
|
|
694
|
+
if (this.counts && this.countsThread && !this.closed)
|
|
695
|
+
this.countTasks.schedule("counts", async () => { this.counts?.reconnect(); });
|
|
696
|
+
}
|
|
697
|
+
publishCountSnapshot(thread) {
|
|
698
|
+
const previous = this.snapshots.get(thread);
|
|
699
|
+
if (!previous) {
|
|
700
|
+
this.publish(thread, false);
|
|
701
|
+
return;
|
|
702
|
+
}
|
|
703
|
+
// Receipt-only updates never serialize or rebuild message bodies.
|
|
704
|
+
this.snapshots.set(thread, { ...previous, readCounts: this.countSnapshots.get(thread) });
|
|
705
|
+
this.listeners.get(thread)?.forEach(listener => listener());
|
|
706
|
+
}
|
|
707
|
+
publishCounts(value) {
|
|
708
|
+
if (this.closed || this.withdrawn)
|
|
709
|
+
return;
|
|
710
|
+
const previous = this.countSnapshots.get(value.threadId);
|
|
711
|
+
if ((previous && previous.revision > value.revision) || JSON.stringify(previous) === JSON.stringify(value))
|
|
712
|
+
return;
|
|
713
|
+
this.countSnapshots.delete(value.threadId);
|
|
714
|
+
this.countSnapshots.set(value.threadId, value);
|
|
715
|
+
if (this.countSnapshots.size > 128) {
|
|
716
|
+
const oldest = this.countSnapshots.keys().next().value;
|
|
717
|
+
this.countSnapshots.delete(oldest);
|
|
718
|
+
this.publishCountSnapshot(oldest);
|
|
719
|
+
}
|
|
720
|
+
this.publishCountSnapshot(value.threadId);
|
|
721
|
+
}
|
|
722
|
+
watchCounts(threadId, ids, receiver = this.connection.identityScope().clientInstanceId) {
|
|
723
|
+
if (!threadId || !ids.length) {
|
|
724
|
+
this.countsThread = undefined;
|
|
725
|
+
this.counts?.watch(undefined, []);
|
|
726
|
+
return;
|
|
727
|
+
}
|
|
728
|
+
if (!receiver || receiver.length > 512 || /[\x00-\x1f]/.test(receiver))
|
|
729
|
+
throw new Error("INVALID_READ_COUNTS_RECEIVER");
|
|
730
|
+
if (!this.counts || this.countsReceiver !== receiver) {
|
|
731
|
+
if (this.counts) {
|
|
732
|
+
const closing = this.counts.close().finally(() => this.countClosings.delete(closing));
|
|
733
|
+
this.countClosings.add(closing);
|
|
734
|
+
}
|
|
735
|
+
const scope = this.options.messages.scope;
|
|
736
|
+
const client = new ReadCountsClient({ appId: scope.appId, profileId: scope.profileId, scope, access: () => this.messages.scopeAccess(), token: this.options.reading.sessionToken, clientInstanceId: receiver, hubHttpUrl: this.options.reading.hubHttpUrl, fetch: this.options.reading.fetch,
|
|
737
|
+
onChange: value => { if (!this.closed && this.counts === client)
|
|
738
|
+
this.publishCounts(value); },
|
|
739
|
+
onError: error => {
|
|
740
|
+
if (this.closed || this.counts !== client)
|
|
741
|
+
return;
|
|
742
|
+
if (/READ_COUNTS_HTTP_(401|403)|RESPONSE_CACHE_(ACCESS_REVOKED|SCOPE_CHANGED|INVALIDATED)/.test(String(error))) {
|
|
743
|
+
const threads = [...this.countSnapshots.keys()];
|
|
744
|
+
this.countSnapshots.clear();
|
|
745
|
+
threads.forEach(thread => this.publishCountSnapshot(thread));
|
|
746
|
+
}
|
|
747
|
+
this.options.onError(error);
|
|
748
|
+
} });
|
|
749
|
+
this.counts = client;
|
|
750
|
+
this.countsReceiver = receiver;
|
|
751
|
+
}
|
|
752
|
+
this.countsThread = threadId;
|
|
753
|
+
this.counts.watch(threadId, ids);
|
|
183
754
|
}
|
|
184
755
|
getSnapshot(threadId) {
|
|
756
|
+
if (this.closed || this.withdrawn) {
|
|
757
|
+
if (threadId === undefined)
|
|
758
|
+
return this.closedSummary;
|
|
759
|
+
return this.closedThread;
|
|
760
|
+
}
|
|
185
761
|
if (threadId === undefined) {
|
|
186
762
|
if (!this.globalSnapshot)
|
|
187
763
|
this.globalSnapshot = this.buildGlobal();
|
|
@@ -189,56 +765,122 @@ export class ChatSession {
|
|
|
189
765
|
}
|
|
190
766
|
let snapshot = this.snapshots.get(threadId);
|
|
191
767
|
if (!snapshot) {
|
|
192
|
-
|
|
193
|
-
const state = this.reading.getSnapshot();
|
|
194
|
-
snapshot = { messages: messages?.messages ?? [], hasEarlier: messages?.hasEarlier ?? false, resetVersion: messages?.resetVersion ?? 0, complete: messages?.complete ?? false, outgoing: this.sender.snapshot(threadId), unread: state?.threads.some(thread => (thread.conversationId ?? thread.id) === threadId) ? unreadInConversation(state, threadId) : { unreadMessageCount: 0, unreadMentionCount: 0, badgeCount: 0 } };
|
|
768
|
+
snapshot = this.buildThreadSnapshot(threadId);
|
|
195
769
|
this.snapshots.set(threadId, snapshot);
|
|
196
770
|
}
|
|
197
771
|
return snapshot;
|
|
198
772
|
}
|
|
199
|
-
|
|
200
|
-
this.
|
|
773
|
+
buildThreadSnapshot(threadId, previous) {
|
|
774
|
+
const source = this.messages.getSnapshot(threadId), raw = source?.messages ?? [];
|
|
775
|
+
const messages = previous && previous.messages.length === raw.length && previous.messages.every((message, index) => message === raw[index]) ? previous.messages : raw;
|
|
776
|
+
const allOutgoing = this.sender.snapshot(threadId);
|
|
777
|
+
const outgoing = this.options.discussion ? allOutgoing.filter(record => messageThreadRoot(record.message.body) === this.options.discussion.threadRootId) : allOutgoing;
|
|
778
|
+
const sameSource = previous && previous.messages === messages && previous.outgoing.length === outgoing.length && previous.outgoing.every((record, index) => record === outgoing[index]);
|
|
779
|
+
const candidates = new Map(messages.flatMap(message => { const candidate = this.options.readingCandidate?.(message); return candidate ? [[candidate.id, candidate]] : []; }));
|
|
780
|
+
const semanticReading = previous?.messageReading ?? {};
|
|
781
|
+
const semantics = sameSource ? previous.timeline : projectMessageTimeline({ appId: this.options.messages.scope.appId, profileId: this.options.messages.scope.profileId, threadId, messages, outgoing, candidates, decode: this.decodeTimeline, reading: semanticReading, previous: previous?.timeline });
|
|
782
|
+
for (const item of semantics)
|
|
783
|
+
if (item.recalled)
|
|
784
|
+
candidates.set(item.id, { ...candidates.get(item.id), id: item.id, threadId, from: item.from, mine: item.mine, recalled: true });
|
|
785
|
+
const state = this.getReadingSnapshot();
|
|
786
|
+
const kind = state?.threads.find(thread => (thread.conversationId ?? thread.id) === threadId)?.kind ?? "dm";
|
|
787
|
+
const view = projectConversationReading(state, { id: threadId, kind, threadRootId: this.options.discussion?.threadRootId }, [...candidates.values()]);
|
|
788
|
+
const unread = previous && JSON.stringify(previous.unread) === JSON.stringify(view.unread) ? previous.unread : view.unread;
|
|
789
|
+
const messageReading = previous && JSON.stringify(previous.messageReading) === JSON.stringify(view.messageReading) ? previous.messageReading : view.messageReading;
|
|
790
|
+
const timeline = messageReading === semanticReading ? semantics : projectMessageTimeline({ appId: this.options.messages.scope.appId, profileId: this.options.messages.scope.profileId, threadId, messages, outgoing, candidates, decode: this.decodeTimeline, reading: messageReading, previous: previous?.timeline });
|
|
791
|
+
return { group: this.groups?.snapshot(threadId).data, timeline, messages, hasEarlier: source?.hasEarlier ?? false, resetVersion: source?.resetVersion ?? 0, complete: source?.complete ?? false, outgoing, readCounts: this.countSnapshots.get(threadId), unread, messageReading };
|
|
792
|
+
}
|
|
793
|
+
subscribe(target, listener, fields) {
|
|
794
|
+
if (typeof target === "function") {
|
|
795
|
+
const notify = () => target(this.getSnapshot());
|
|
796
|
+
const off = this.subscribeChanges(notify);
|
|
797
|
+
try {
|
|
798
|
+
notify();
|
|
799
|
+
}
|
|
800
|
+
catch (error) {
|
|
801
|
+
off();
|
|
802
|
+
throw error;
|
|
803
|
+
}
|
|
804
|
+
return off;
|
|
805
|
+
}
|
|
806
|
+
const notify = () => listener(this.getSnapshot(target));
|
|
807
|
+
const off = this.subscribeChanges(target, notify, fields);
|
|
808
|
+
// The deprecated field-array form retains change-only behavior during migration.
|
|
809
|
+
if (!fields) {
|
|
810
|
+
try {
|
|
811
|
+
notify();
|
|
812
|
+
}
|
|
813
|
+
catch (error) {
|
|
814
|
+
off();
|
|
815
|
+
throw error;
|
|
816
|
+
}
|
|
817
|
+
}
|
|
818
|
+
return off;
|
|
819
|
+
}
|
|
820
|
+
subscribeChanges(target, listener, fields) {
|
|
821
|
+
if (this.closed || this.withdrawn)
|
|
822
|
+
return () => { };
|
|
201
823
|
if (typeof target === "function") {
|
|
202
824
|
this.globalListeners.add(target);
|
|
203
825
|
return () => { this.globalListeners.delete(target); };
|
|
204
826
|
}
|
|
205
827
|
const threadId = target;
|
|
206
|
-
const
|
|
828
|
+
const selected = fields ? [...fields] : undefined;
|
|
829
|
+
let values = selected?.map(field => this.getSnapshot(threadId)[field]);
|
|
830
|
+
const equal = (a, b) => a === b || (Array.isArray(a) && Array.isArray(b) && a.length === b.length && a.every((value, index) => value === b[index]));
|
|
831
|
+
const notify = selected ? () => {
|
|
832
|
+
const next = selected.map(field => this.getSnapshot(threadId)[field]);
|
|
833
|
+
const changed = next.some((value, index) => !equal(value, values[index]));
|
|
834
|
+
values = next;
|
|
835
|
+
if (changed)
|
|
836
|
+
listener();
|
|
837
|
+
} : listener;
|
|
207
838
|
let listeners = this.listeners.get(threadId);
|
|
208
839
|
if (!listeners) {
|
|
209
840
|
listeners = new Set();
|
|
210
841
|
this.listeners.set(threadId, listeners);
|
|
211
842
|
}
|
|
212
843
|
listeners.add(notify);
|
|
213
|
-
const off = this.messages.subscribe(threadId, () => { });
|
|
844
|
+
const off = this.messages.subscribe(threadId, () => { }), unpin = (!selected || selected.includes("group")) ? this.groups?.pin(threadId) : undefined;
|
|
214
845
|
return () => {
|
|
215
846
|
off();
|
|
847
|
+
unpin?.();
|
|
216
848
|
listeners.delete(notify);
|
|
217
849
|
if (!listeners.size)
|
|
218
850
|
this.listeners.delete(threadId);
|
|
219
851
|
};
|
|
220
852
|
}
|
|
221
853
|
publishAll() {
|
|
854
|
+
if (this.closed || this.withdrawn)
|
|
855
|
+
return;
|
|
222
856
|
for (const threadId of [...this.snapshots.keys()])
|
|
223
857
|
this.publish(threadId, false);
|
|
224
858
|
this.publishGlobal();
|
|
225
859
|
}
|
|
226
860
|
buildGlobal() {
|
|
227
861
|
const ids = new Set(this.snapshots.keys());
|
|
228
|
-
for (const thread of this.
|
|
862
|
+
for (const thread of this.getReadingSnapshot()?.threads ?? [])
|
|
229
863
|
if (thread.teamId === this.options.messages.scope.teamId)
|
|
230
864
|
ids.add(thread.conversationId ?? thread.id);
|
|
231
865
|
for (const outgoing of this.sender.snapshot())
|
|
232
866
|
ids.add(outgoing.threadId);
|
|
233
867
|
const threads = [...ids].sort().map(threadId => {
|
|
234
868
|
const snapshot = this.getSnapshot(threadId);
|
|
235
|
-
return { threadId, lastMessage: snapshot.
|
|
869
|
+
return { threadId, group: snapshot.group, lastMessage: snapshot.timeline.at(-1)?.message, lastItem: snapshot.timeline.at(-1), unread: snapshot.unread, outgoingCount: snapshot.outgoing.length };
|
|
236
870
|
});
|
|
237
|
-
|
|
871
|
+
const state = this.getReadingSnapshot();
|
|
872
|
+
const known = Boolean(state && state.syncCursor !== "0" && threads.every(thread => thread.unread !== undefined));
|
|
873
|
+
return { threads, unreadMessageCount: known ? threads.reduce((sum, t) => sum + (t.unread?.unreadMessageCount ?? 0), 0) : undefined, badgeCount: known ? threads.reduce((sum, t) => sum + (t.unread?.badgeCount ?? 0), 0) : undefined, connection: this.connectionState };
|
|
238
874
|
}
|
|
239
875
|
publishGlobal() {
|
|
876
|
+
if (this.closed || this.withdrawn)
|
|
877
|
+
return;
|
|
240
878
|
const next = this.buildGlobal();
|
|
241
|
-
|
|
879
|
+
const previous = this.globalSnapshot;
|
|
880
|
+
if (previous && previous.connection === next.connection && previous.unreadMessageCount === next.unreadMessageCount && previous.badgeCount === next.badgeCount && previous.threads.length === next.threads.length && previous.threads.every((thread, index) => {
|
|
881
|
+
const other = next.threads[index];
|
|
882
|
+
return thread.threadId === other.threadId && thread.group === other.group && thread.lastMessage === other.lastMessage && thread.lastItem === other.lastItem && thread.outgoingCount === other.outgoingCount && JSON.stringify(thread.unread) === JSON.stringify(other.unread);
|
|
883
|
+
}))
|
|
242
884
|
return;
|
|
243
885
|
this.globalSnapshot = next;
|
|
244
886
|
this.globalListeners.forEach(listener => listener());
|
|
@@ -246,8 +888,9 @@ export class ChatSession {
|
|
|
246
888
|
publish(threadId, notifyGlobal = true) {
|
|
247
889
|
const previous = this.snapshots.get(threadId);
|
|
248
890
|
this.snapshots.delete(threadId);
|
|
249
|
-
const next = this.
|
|
250
|
-
|
|
891
|
+
const next = this.buildThreadSnapshot(threadId, previous);
|
|
892
|
+
this.snapshots.set(threadId, next);
|
|
893
|
+
if (previous && previous.group === next.group && previous.messages === next.messages && previous.timeline === next.timeline && previous.outgoing.length === next.outgoing.length && previous.outgoing.every((record, index) => record === next.outgoing[index]) && previous.hasEarlier === next.hasEarlier && previous.resetVersion === next.resetVersion && previous.complete === next.complete && previous.readCounts === next.readCounts && JSON.stringify(previous.unread) === JSON.stringify(next.unread) && JSON.stringify(previous.messageReading) === JSON.stringify(next.messageReading)) {
|
|
251
894
|
this.snapshots.set(threadId, previous);
|
|
252
895
|
return;
|
|
253
896
|
}
|
|
@@ -255,21 +898,127 @@ export class ChatSession {
|
|
|
255
898
|
if (notifyGlobal)
|
|
256
899
|
this.publishGlobal();
|
|
257
900
|
}
|
|
258
|
-
|
|
901
|
+
async conversationFailure(error, threadId) {
|
|
902
|
+
const failure = asChatError(error);
|
|
903
|
+
if (failure.code !== "access-denied" && failure.status !== 401)
|
|
904
|
+
return failure;
|
|
905
|
+
if (isScopedGroupDenial(error))
|
|
906
|
+
return scopedGroupDenial(threadChatError(error, threadId));
|
|
907
|
+
if (failure.status === 403 && this.active && this.options.messages.transport.authorizeScope) {
|
|
908
|
+
try {
|
|
909
|
+
await this.options.messages.transport.authorizeScope(new AbortController().signal);
|
|
910
|
+
this.assertOpen();
|
|
911
|
+
if ((await this.messages.scopeAccess()).allowed)
|
|
912
|
+
return scopedGroupDenial(threadChatError(error, threadId));
|
|
913
|
+
}
|
|
914
|
+
catch { }
|
|
915
|
+
}
|
|
916
|
+
void this.revokeAccess().catch(error => this.options.onError(error));
|
|
917
|
+
return failure;
|
|
918
|
+
}
|
|
919
|
+
/** Withdraw one conversation without retiring sibling conversations. */
|
|
920
|
+
async revokeThread(threadId) { try {
|
|
921
|
+
await Promise.all([this.messages.revoke(threadId), this.groups?.revoke(threadId)]);
|
|
922
|
+
}
|
|
923
|
+
catch (error) {
|
|
924
|
+
void this.revokeAccess().catch(failure => this.options.onError(failure));
|
|
925
|
+
throw error;
|
|
926
|
+
} }
|
|
927
|
+
/** Permanently retire this identity/team session. UI withdrawal is immediate;
|
|
928
|
+
* completion means all durable stores have crossed the same authority epoch. */
|
|
929
|
+
revokeAccess() {
|
|
930
|
+
if (this.revoking)
|
|
931
|
+
return this.revoking;
|
|
932
|
+
if (this.closed)
|
|
933
|
+
return Promise.reject(new Error("CHAT_SESSION_CLOSED"));
|
|
934
|
+
this.withdrawn = true;
|
|
935
|
+
const knownThreads = [...new Set([...this.snapshots.keys(), ...this.historyEdges.keys()])];
|
|
936
|
+
this.catchUp.close();
|
|
937
|
+
this.countTasks.close();
|
|
938
|
+
this.off.splice(0).forEach(off => off());
|
|
939
|
+
this.sender.withdraw();
|
|
940
|
+
this.reading.withdraw();
|
|
941
|
+
this.readers.withdraw();
|
|
942
|
+
this.groups?.withdraw();
|
|
943
|
+
this.counts?.watch(undefined, []);
|
|
944
|
+
this.countSnapshots.clear();
|
|
945
|
+
this.snapshots.clear();
|
|
946
|
+
this.timelineDecoded = new WeakMap();
|
|
947
|
+
this.historyEdges.clear();
|
|
948
|
+
this.earlierReads.clear();
|
|
949
|
+
this.controlTails.clear();
|
|
950
|
+
this.globalSnapshot = undefined;
|
|
951
|
+
this.listeners.forEach(listeners => listeners.forEach(listener => listener()));
|
|
952
|
+
this.globalListeners.forEach(listener => listener());
|
|
953
|
+
this.readingListeners.forEach(listener => listener());
|
|
954
|
+
if (!this.options.sharedConnection)
|
|
955
|
+
this.connection.close();
|
|
956
|
+
return this.revoking = Promise.resolve().then(async () => {
|
|
957
|
+
const failures = [];
|
|
958
|
+
let version;
|
|
959
|
+
try {
|
|
960
|
+
version = await this.messages.revokeScope();
|
|
961
|
+
}
|
|
962
|
+
catch (error) {
|
|
963
|
+
failures.push(error);
|
|
964
|
+
version = 1;
|
|
965
|
+
try {
|
|
966
|
+
version = Math.max(1, (await this.messages.scopeAccess()).version);
|
|
967
|
+
}
|
|
968
|
+
catch (failure) {
|
|
969
|
+
failures.push(failure);
|
|
970
|
+
}
|
|
971
|
+
}
|
|
972
|
+
const results = await Promise.allSettled([
|
|
973
|
+
this.sender.revoke(version),
|
|
974
|
+
this.reading.revokeTeam(this.options.messages.scope.teamId, version, knownThreads),
|
|
975
|
+
this.readers.retireScope(version), this.counts?.retireScope(version), this.groups?.retire(version), this.conversations.retire(version),
|
|
976
|
+
]);
|
|
977
|
+
for (const result of results)
|
|
978
|
+
if (result.status === "rejected")
|
|
979
|
+
failures.push(result.reason);
|
|
980
|
+
try {
|
|
981
|
+
await this.dispose();
|
|
982
|
+
}
|
|
983
|
+
catch (error) {
|
|
984
|
+
failures.push(error);
|
|
985
|
+
}
|
|
986
|
+
if (failures.length)
|
|
987
|
+
throw new AggregateError(failures, "CHAT_ACCESS_CLEANUP_FAILED");
|
|
988
|
+
});
|
|
989
|
+
}
|
|
990
|
+
get active() { return !this.closed && !this.withdrawn; }
|
|
991
|
+
close() { return this.revoking ?? this.dispose(); }
|
|
992
|
+
dispose() {
|
|
259
993
|
return this.closing ??= (async () => {
|
|
260
994
|
this.closed = true;
|
|
261
995
|
this.catchUp.close();
|
|
996
|
+
this.countTasks.close();
|
|
262
997
|
this.off.splice(0).forEach(off => off());
|
|
263
998
|
if (!this.options.sharedConnection)
|
|
264
999
|
this.connection.close();
|
|
265
|
-
this.
|
|
266
|
-
|
|
267
|
-
this.
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
1000
|
+
const senderClosing = this.sender.close(), groupsClosing = this.groups?.close();
|
|
1001
|
+
const readingBarrier = Promise.allSettled([...this.acceptedReading, ...this.acceptedControls]);
|
|
1002
|
+
const readingClosing = readingBarrier.then(() => this.reading.close());
|
|
1003
|
+
try {
|
|
1004
|
+
const results = await Promise.allSettled([this.counts?.close(), ...this.countClosings, this.readers.close(), this.conversations.close(), groupsClosing, senderClosing, readingClosing, this.messages.close(Promise.allSettled([senderClosing, groupsClosing, readingBarrier]))]);
|
|
1005
|
+
const failed = results.find((result) => result.status === "rejected");
|
|
1006
|
+
if (failed)
|
|
1007
|
+
throw failed.reason;
|
|
1008
|
+
}
|
|
1009
|
+
finally {
|
|
1010
|
+
this.options.onDispose?.();
|
|
1011
|
+
this.listeners.clear();
|
|
1012
|
+
this.globalListeners.clear();
|
|
1013
|
+
this.readingListeners.clear();
|
|
1014
|
+
this.snapshots.clear();
|
|
1015
|
+
this.timelineDecoded = new WeakMap();
|
|
1016
|
+
this.countSnapshots.clear();
|
|
1017
|
+
this.historyEdges.clear();
|
|
1018
|
+
this.earlierReads.clear();
|
|
1019
|
+
this.controlTails.clear();
|
|
1020
|
+
this.globalSnapshot = undefined;
|
|
1021
|
+
}
|
|
273
1022
|
})();
|
|
274
1023
|
}
|
|
275
1024
|
}
|