@pmate/chat-sdk 0.12.0-next.9 → 0.12.0-next.91
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 +329 -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
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
/** Metadata-only store renaming fences SDKs that cannot read chunked snapshots. */
|
|
2
|
+
export async function prepareReadSchema(factory, name) {
|
|
3
|
+
const existing = await new Promise((resolve, reject) => {
|
|
4
|
+
const request = factory.open(name);
|
|
5
|
+
let fresh = false;
|
|
6
|
+
request.onupgradeneeded = event => { if (event.oldVersion === 0) {
|
|
7
|
+
fresh = true;
|
|
8
|
+
request.transaction.abort();
|
|
9
|
+
} };
|
|
10
|
+
request.onerror = event => { event.preventDefault(); if (fresh)
|
|
11
|
+
resolve(undefined);
|
|
12
|
+
else
|
|
13
|
+
reject(request.error); };
|
|
14
|
+
request.onsuccess = () => resolve(request.result);
|
|
15
|
+
});
|
|
16
|
+
if (!existing)
|
|
17
|
+
return;
|
|
18
|
+
const prepared = existing.objectStoreNames.contains("readingProfiles") && existing.objectStoreNames.contains("readingMessages");
|
|
19
|
+
const version = existing.version;
|
|
20
|
+
existing.close();
|
|
21
|
+
if (version >= 60 && prepared)
|
|
22
|
+
return;
|
|
23
|
+
await new Promise((resolve, reject) => {
|
|
24
|
+
const request = factory.open(name, Math.max(60, version + 1));
|
|
25
|
+
request.onerror = () => reject(request.error);
|
|
26
|
+
request.onupgradeneeded = () => {
|
|
27
|
+
const db = request.result, tx = request.transaction;
|
|
28
|
+
for (const [before, after] of [["profiles", "readingProfiles"], ["versions", "readingVersions"], ["readThreads", "readingThreads"], ["readMessages", "readingMessages"], ["readPositions", "readingPositions"]]) {
|
|
29
|
+
if (db.objectStoreNames.contains(before)) {
|
|
30
|
+
if (db.objectStoreNames.contains(after)) {
|
|
31
|
+
tx.abort();
|
|
32
|
+
return;
|
|
33
|
+
}
|
|
34
|
+
tx.objectStore(before).name = after;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
if (!db.objectStoreNames.contains("readingProfiles"))
|
|
38
|
+
db.createObjectStore("readingProfiles");
|
|
39
|
+
if (!db.objectStoreNames.contains("readingVersions"))
|
|
40
|
+
db.createObjectStore("readingVersions");
|
|
41
|
+
// Explicit-key writes from older SDKs must fail rather than recreate a cache
|
|
42
|
+
// beside a partially applied transition or silently return an empty history.
|
|
43
|
+
db.createObjectStore("profiles", { keyPath: "unsupportedReadingFormat" });
|
|
44
|
+
db.createObjectStore("versions", { keyPath: "unsupportedReadingFormat" });
|
|
45
|
+
const define = (name, keyPath, indexes) => {
|
|
46
|
+
const store = db.objectStoreNames.contains(name) ? tx.objectStore(name) : db.createObjectStore(name, { keyPath });
|
|
47
|
+
for (const [index, path] of Object.entries(indexes))
|
|
48
|
+
if (!store.indexNames.contains(index))
|
|
49
|
+
store.createIndex(index, path);
|
|
50
|
+
};
|
|
51
|
+
define("readingThreads", ["owner", "id"], { owner: "owner", "[owner+id+value.kind+value.teamId]": ["owner", "id", "value.kind", "value.teamId"], "[owner+value.conversationId+value.kind+value.teamId+id]": ["owner", "value.conversationId", "value.kind", "value.teamId", "id"], "[owner+id+value.conversationId]": ["owner", "id", "value.conversationId"], "[owner+id+value.kind]": ["owner", "id", "value.kind"], "[owner+value.conversationId+value.kind+id]": ["owner", "value.conversationId", "value.kind", "id"] });
|
|
52
|
+
define("readingMessages", ["owner", "thread", "id"], { owner: "owner", "[owner+thread]": ["owner", "thread"] });
|
|
53
|
+
define("readingPositions", ["owner", "id"], { owner: "owner" });
|
|
54
|
+
define("readBatches", ["owner", "key"], { owner: "owner" });
|
|
55
|
+
};
|
|
56
|
+
request.onsuccess = () => { request.result.close(); resolve(); };
|
|
57
|
+
});
|
|
58
|
+
}
|
|
@@ -1,9 +1,12 @@
|
|
|
1
1
|
import { type ReadIndexPersistence, type ReadIndexState } from "./readIndex.js";
|
|
2
|
+
import type { InboxClient } from "./inboxClient.js";
|
|
2
3
|
export type ReadSyncOptions = {
|
|
4
|
+
inbox?: InboxClient;
|
|
3
5
|
appId: string;
|
|
4
6
|
profileId: string;
|
|
5
7
|
sessionToken: string;
|
|
6
8
|
hubHttpUrl: string;
|
|
9
|
+
metadataOnly?: boolean;
|
|
7
10
|
persistence: ReadIndexPersistence;
|
|
8
11
|
fetch?: typeof globalThis.fetch;
|
|
9
12
|
onChange?: (state: ReadIndexState) => void;
|
|
@@ -14,10 +17,15 @@ export declare class ReadSyncClient {
|
|
|
14
17
|
private readonly controller;
|
|
15
18
|
private inFlight?;
|
|
16
19
|
private readAfter;
|
|
20
|
+
private inboxApplying?;
|
|
21
|
+
private inboxDirty;
|
|
17
22
|
constructor(options: ReadSyncOptions);
|
|
18
23
|
loadLocal(): Promise<ReadIndexState>;
|
|
19
24
|
stop(): void;
|
|
25
|
+
applyInboxLocal(): Promise<ReadIndexState>;
|
|
26
|
+
private installInboxLocal;
|
|
20
27
|
synchronize(): Promise<ReadIndexState>;
|
|
21
28
|
private request;
|
|
29
|
+
private repairLegacyDiscussion;
|
|
22
30
|
private run;
|
|
23
31
|
}
|
package/lib/runtime/readSync.js
CHANGED
|
@@ -1,18 +1,60 @@
|
|
|
1
|
-
import { applyReadChange, ReadSyncGap, createReadIndex, installReadSnapshot } from "./readIndex.js";
|
|
1
|
+
import { readingMetadata, resolveObservedReads, assertReadIndexVersions, applyReadChange, ReadSyncGap, createReadIndex, installReadSnapshot } from "./readIndex.js";
|
|
2
2
|
/** Keeps local operations until an authoritative projection covers them. */
|
|
3
3
|
export class ReadSyncClient {
|
|
4
4
|
options;
|
|
5
5
|
controller = new AbortController();
|
|
6
6
|
inFlight;
|
|
7
7
|
readAfter = 0;
|
|
8
|
+
inboxApplying;
|
|
9
|
+
inboxDirty = false;
|
|
8
10
|
constructor(options) {
|
|
9
11
|
this.options = options;
|
|
10
12
|
}
|
|
11
13
|
async loadLocal() {
|
|
12
|
-
|
|
13
|
-
|
|
14
|
+
if (this.options.inbox)
|
|
15
|
+
return this.applyInboxLocal();
|
|
16
|
+
const { appId, profileId, persistence, metadataOnly } = this.options;
|
|
17
|
+
const state = await persistence.load(appId, profileId) ?? createReadIndex(appId, profileId);
|
|
18
|
+
const normalize = (current) => {
|
|
19
|
+
const next = metadataOnly ? readingMetadata(current) : current;
|
|
20
|
+
return next.observedReadIntents?.length ? resolveObservedReads(next) : next;
|
|
21
|
+
};
|
|
22
|
+
if (normalize(state) === state)
|
|
23
|
+
return state;
|
|
24
|
+
return persistence.update(appId, profileId, normalize);
|
|
14
25
|
}
|
|
15
26
|
stop() { this.controller.abort(); }
|
|
27
|
+
applyInboxLocal() {
|
|
28
|
+
this.inboxDirty = true;
|
|
29
|
+
if (this.inboxApplying)
|
|
30
|
+
return this.inboxApplying;
|
|
31
|
+
return this.inboxApplying = (async () => {
|
|
32
|
+
let state;
|
|
33
|
+
do {
|
|
34
|
+
this.inboxDirty = false;
|
|
35
|
+
state = await this.installInboxLocal();
|
|
36
|
+
} while (this.inboxDirty && !this.controller.signal.aborted);
|
|
37
|
+
return state;
|
|
38
|
+
})().finally(() => { this.inboxApplying = undefined; });
|
|
39
|
+
}
|
|
40
|
+
async installInboxLocal() {
|
|
41
|
+
const { inbox, persistence, appId, profileId } = this.options;
|
|
42
|
+
if (!inbox)
|
|
43
|
+
throw new Error("INBOX_NOT_CONFIGURED");
|
|
44
|
+
const snapshot = await inbox.store.readingSnapshot();
|
|
45
|
+
const versions = persistence.loadVersions ? await persistence.loadVersions(appId, profileId) : {};
|
|
46
|
+
const next = await persistence.update(appId, profileId, (current, currentVersions) => {
|
|
47
|
+
assertReadIndexVersions(versions, currentVersions);
|
|
48
|
+
if (this.controller.signal.aborted)
|
|
49
|
+
throw new Error("READ_SYNC_STOPPED");
|
|
50
|
+
// Inbox replaces old server-derived positions. Preserve pending local
|
|
51
|
+
// observations/operations, not stale state from the retired projection.
|
|
52
|
+
return installReadSnapshot({ ...current, threads: [] }, snapshot);
|
|
53
|
+
});
|
|
54
|
+
if (!this.controller.signal.aborted)
|
|
55
|
+
this.options.onChange?.(next);
|
|
56
|
+
return next;
|
|
57
|
+
}
|
|
16
58
|
synchronize() {
|
|
17
59
|
if (this.inFlight)
|
|
18
60
|
return this.inFlight;
|
|
@@ -32,8 +74,12 @@ export class ReadSyncClient {
|
|
|
32
74
|
const response = await (this.options.fetch ?? globalThis.fetch)(`${this.options.hubHttpUrl.replace(/\/$/, "")}${path}`, {
|
|
33
75
|
...init, signal: timeout.signal, headers: { ...init.headers, authorization: `Bearer ${this.options.sessionToken}` },
|
|
34
76
|
});
|
|
35
|
-
if (!response.ok)
|
|
36
|
-
|
|
77
|
+
if (!response.ok) {
|
|
78
|
+
// Keep only a fixed domain code, never a provider response body.
|
|
79
|
+
const failure = await response.json().catch(() => undefined);
|
|
80
|
+
const code = failure?.message === "INVALID_READING_CURSOR" ? failure.message : undefined;
|
|
81
|
+
throw Object.assign(new Error(`READ_SYNC_HTTP_${response.status}`), { status: response.status, code });
|
|
82
|
+
}
|
|
37
83
|
const envelope = await response.json();
|
|
38
84
|
if (envelope.success !== true || envelope.data === undefined)
|
|
39
85
|
throw new Error("INVALID_READ_SYNC_RESPONSE");
|
|
@@ -44,9 +90,48 @@ export class ReadSyncClient {
|
|
|
44
90
|
this.controller.signal.removeEventListener("abort", abort);
|
|
45
91
|
}
|
|
46
92
|
}
|
|
47
|
-
async
|
|
93
|
+
async repairLegacyDiscussion(operation, versions) {
|
|
94
|
+
if (operation.threadRootId !== undefined || operation.readThroughSeq <= 0 || operation.explicitReadMessageIds.length)
|
|
95
|
+
return false;
|
|
96
|
+
const { appId, profileId, persistence } = this.options;
|
|
97
|
+
const query = new URLSearchParams({ appId, profileId, ...(this.options.metadataOnly ? { metadataOnly: "true" } : {}) });
|
|
98
|
+
const snapshot = this.options.inbox ? await this.options.inbox.store.readingSnapshot() : await this.request(`/api/social/reading/snapshot?${query}`);
|
|
99
|
+
// Validate the complete response before changing any durable operation.
|
|
100
|
+
installReadSnapshot(createReadIndex(appId, profileId), snapshot);
|
|
101
|
+
const thread = snapshot.threads.find(thread => thread.id === operation.threadId);
|
|
102
|
+
const message = thread?.messages.find(message => message.id === operation.readThroughMessageId
|
|
103
|
+
&& message.seq === operation.readThroughSeq && message.readPolicy === "visible" && message.threadRootId != null);
|
|
104
|
+
if (!thread || !message)
|
|
105
|
+
return false;
|
|
106
|
+
let repaired = false;
|
|
107
|
+
await persistence.update(appId, profileId, (state, currentVersions) => {
|
|
108
|
+
assertReadIndexVersions(versions, currentVersions);
|
|
109
|
+
if (this.controller.signal.aborted)
|
|
110
|
+
throw new Error("READ_SYNC_STOPPED");
|
|
111
|
+
const pending = state.pending.map(item => {
|
|
112
|
+
if (item.operationId !== operation.operationId || JSON.stringify(item) !== JSON.stringify(operation))
|
|
113
|
+
return item;
|
|
114
|
+
repaired = true;
|
|
115
|
+
// New payload, new identity: an operation ID must never change meaning.
|
|
116
|
+
return { ...item, operationId: crypto.randomUUID(), threadRootId: message.threadRootId };
|
|
117
|
+
});
|
|
118
|
+
if (!repaired)
|
|
119
|
+
return state;
|
|
120
|
+
// Undo the rejected main-conversation optimistic position, then replay all
|
|
121
|
+
// remaining operations on the authoritative snapshot in their own scopes.
|
|
122
|
+
const threads = state.threads.map(item => item.id === thread.id && item.readThroughSeq === operation.readThroughSeq
|
|
123
|
+
? { ...item, readThroughSeq: thread.readThroughSeq } : item);
|
|
124
|
+
return installReadSnapshot({ ...state, threads, pending }, snapshot);
|
|
125
|
+
});
|
|
126
|
+
return repaired;
|
|
127
|
+
}
|
|
128
|
+
async run(repairedLegacy = false) {
|
|
129
|
+
if (this.options.inbox?.offlineMode())
|
|
130
|
+
return this.applyInboxLocal();
|
|
48
131
|
const { appId, profileId, persistence } = this.options;
|
|
49
|
-
const
|
|
132
|
+
const loaded = persistence.loadVersioned ? await persistence.loadVersioned(appId, profileId) : { state: await persistence.load(appId, profileId), versions: {} };
|
|
133
|
+
const current = loaded.state ?? createReadIndex(appId, profileId);
|
|
134
|
+
const versions = loaded.versions;
|
|
50
135
|
// Ordinary reads are monotonic: only the furthest position per thread needs
|
|
51
136
|
// sending. Keep every original operation in storage until the projection
|
|
52
137
|
// confirms it, and never rewrite an operation ID's payload during retries.
|
|
@@ -54,23 +139,42 @@ export class ReadSyncClient {
|
|
|
54
139
|
for (const operation of current.pending) {
|
|
55
140
|
if (operation.explicitReadMessageIds.length || operation.readThroughSeq <= 0)
|
|
56
141
|
continue;
|
|
57
|
-
const
|
|
142
|
+
const key = JSON.stringify([operation.threadId, operation.threadRootId ?? null]);
|
|
143
|
+
const previous = latest.get(key);
|
|
58
144
|
if (!previous || operation.readThroughSeq > previous.readThroughSeq)
|
|
59
|
-
latest.set(
|
|
145
|
+
latest.set(key, operation);
|
|
60
146
|
}
|
|
61
|
-
const outgoing = current.pending.filter(operation => operation.explicitReadMessageIds.length || operation.readThroughSeq <= 0 || latest.get(operation.threadId) === operation);
|
|
147
|
+
const outgoing = current.pending.filter(operation => operation.explicitReadMessageIds.length || operation.readThroughSeq <= 0 || latest.get(JSON.stringify([operation.threadId, operation.threadRootId ?? null])) === operation);
|
|
62
148
|
for (const operation of outgoing) {
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
149
|
+
if (persistence.loadVersions)
|
|
150
|
+
assertReadIndexVersions(versions, await persistence.loadVersions(appId, profileId));
|
|
151
|
+
let receipt;
|
|
152
|
+
try {
|
|
153
|
+
receipt = await this.request("/api/social/reading", {
|
|
154
|
+
method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ ...operation, appId, profileId }),
|
|
155
|
+
});
|
|
156
|
+
}
|
|
157
|
+
catch (error) {
|
|
158
|
+
if (!repairedLegacy && error?.status === 400
|
|
159
|
+
&& error.code === "INVALID_READING_CURSOR"
|
|
160
|
+
&& await this.repairLegacyDiscussion(operation, versions))
|
|
161
|
+
return this.run(true);
|
|
162
|
+
throw error;
|
|
163
|
+
}
|
|
66
164
|
if (receipt.operationId !== operation.operationId || receipt.accepted !== true
|
|
67
165
|
|| !Number.isSafeInteger(receipt.acceptedAt) || receipt.acceptedAt <= 0)
|
|
68
166
|
throw new Error("INVALID_READING_RECEIPT");
|
|
69
167
|
this.readAfter = Math.max(this.readAfter, receipt.acceptedAt);
|
|
70
168
|
}
|
|
169
|
+
if (this.options.inbox) {
|
|
170
|
+
await this.options.inbox.synchronize();
|
|
171
|
+
return this.applyInboxLocal();
|
|
172
|
+
}
|
|
71
173
|
const query = new URLSearchParams({ appId, profileId });
|
|
174
|
+
if (this.options.metadataOnly)
|
|
175
|
+
query.set("metadataOnly", "true");
|
|
72
176
|
if (!this.readAfter && current.syncCursor !== "0") {
|
|
73
|
-
const delta = await this.request(`/api/social/reading/changes?${new URLSearchParams({ appId, profileId, after: current.syncCursor })}`);
|
|
177
|
+
const delta = await this.request(`/api/social/reading/changes?${new URLSearchParams({ appId, profileId, after: current.syncCursor, ...(this.options.metadataOnly ? { metadataOnly: "true" } : {}) })}`);
|
|
74
178
|
if (delta.appId !== appId || delta.profileId !== profileId || typeof delta.syncCursor !== "string"
|
|
75
179
|
|| typeof delta.snapshotRequired !== "boolean" || !Array.isArray(delta.changes))
|
|
76
180
|
throw new Error("INVALID_READ_DELTA");
|
|
@@ -78,8 +182,9 @@ export class ReadSyncClient {
|
|
|
78
182
|
try {
|
|
79
183
|
if (this.controller.signal.aborted)
|
|
80
184
|
throw new Error("READ_SYNC_STOPPED");
|
|
81
|
-
const next = await persistence.update(appId, profileId, state => {
|
|
82
|
-
|
|
185
|
+
const next = await persistence.update(appId, profileId, (state, currentVersions) => {
|
|
186
|
+
assertReadIndexVersions(versions, currentVersions);
|
|
187
|
+
const applied = delta.changes.reduce((current, change) => applyReadChange(current, this.options.metadataOnly ? { ...change, thread: readingMetadata({ appId, threads: [change.thread] }).threads[0] } : change), this.options.metadataOnly ? readingMetadata(state) : state);
|
|
83
188
|
if (applied.syncCursor !== delta.syncCursor)
|
|
84
189
|
throw new ReadSyncGap(applied.syncCursor);
|
|
85
190
|
return applied;
|
|
@@ -100,7 +205,10 @@ export class ReadSyncClient {
|
|
|
100
205
|
if (this.controller.signal.aborted)
|
|
101
206
|
throw new Error("READ_SYNC_STOPPED");
|
|
102
207
|
// Merge into the latest transaction, including reads made while HTTP was pending.
|
|
103
|
-
const next = await persistence.update(appId, profileId,
|
|
208
|
+
const next = await persistence.update(appId, profileId, (state, currentVersions) => {
|
|
209
|
+
assertReadIndexVersions(versions, currentVersions);
|
|
210
|
+
return installReadSnapshot(state, this.options.metadataOnly ? readingMetadata(snapshot) : snapshot);
|
|
211
|
+
});
|
|
104
212
|
if (!next.pending.length)
|
|
105
213
|
this.readAfter = 0;
|
|
106
214
|
if (!this.controller.signal.aborted)
|
|
@@ -1,11 +1,17 @@
|
|
|
1
|
+
import { type ConversationReadMessage } from "./conversationRead.js";
|
|
1
2
|
import { type ReadIndexPersistence, type ReadIndexState } from "./readIndex.js";
|
|
3
|
+
import type { InboxClient } from "./inboxClient.js";
|
|
2
4
|
export type ReadingClientOptions = {
|
|
5
|
+
inbox?: InboxClient;
|
|
3
6
|
appId: string;
|
|
4
7
|
profileId: string;
|
|
5
8
|
sessionToken: string;
|
|
6
9
|
hubHttpUrl: string;
|
|
10
|
+
teamId?: string;
|
|
11
|
+
metadataOnly?: boolean;
|
|
7
12
|
persistence?: ReadIndexPersistence;
|
|
8
13
|
storageScope?: string;
|
|
14
|
+
migrateLegacy?: boolean;
|
|
9
15
|
fetch?: typeof fetch;
|
|
10
16
|
onError?: (error: unknown) => void;
|
|
11
17
|
onRecovered?: () => void;
|
|
@@ -15,6 +21,12 @@ export type ReadingClientOptions = {
|
|
|
15
21
|
export declare class ReadingClient {
|
|
16
22
|
private options;
|
|
17
23
|
private storage;
|
|
24
|
+
private backing;
|
|
25
|
+
private closing?;
|
|
26
|
+
private revoking?;
|
|
27
|
+
private versions?;
|
|
28
|
+
private prepared;
|
|
29
|
+
private accepted;
|
|
18
30
|
private persistence;
|
|
19
31
|
private sync;
|
|
20
32
|
private tasks;
|
|
@@ -24,6 +36,7 @@ export declare class ReadingClient {
|
|
|
24
36
|
private retry?;
|
|
25
37
|
private retryDelay;
|
|
26
38
|
private offWake?;
|
|
39
|
+
private offInbox?;
|
|
27
40
|
private generation;
|
|
28
41
|
constructor(options: ReadingClientOptions);
|
|
29
42
|
getSnapshot: () => ReadIndexState | undefined;
|
|
@@ -34,8 +47,17 @@ export declare class ReadingClient {
|
|
|
34
47
|
refresh: () => void;
|
|
35
48
|
synchronize(targetCursor?: string, profileId?: string): Promise<ReadIndexState>;
|
|
36
49
|
update(transform: (state: ReadIndexState) => ReadIndexState): Promise<ReadIndexState>;
|
|
50
|
+
private updateScoped;
|
|
51
|
+
prepareTeam(teamId: string, version: number): Promise<void>;
|
|
52
|
+
private assertThreadTeam;
|
|
53
|
+
markRead(threadId: string, messages?: readonly ConversationReadMessage[], threadRootId?: string): Promise<ReadIndexState>;
|
|
37
54
|
recordVisible(threadId: string, messageIds: string[]): Promise<ReadIndexState>;
|
|
38
55
|
recordExplicit(threadId: string, messageIds: string[]): Promise<ReadIndexState>;
|
|
39
56
|
private record;
|
|
57
|
+
withdraw(): void;
|
|
58
|
+
private stop;
|
|
59
|
+
/** This client is retired permanently. Drain accepted local observations
|
|
60
|
+
* before deleting one team's profile-wide projection; sibling teams survive. */
|
|
61
|
+
revokeTeam(teamId: string, version: number, knownThreadIds?: readonly string[]): Promise<void>;
|
|
40
62
|
close(): Promise<void>;
|
|
41
63
|
}
|
|
@@ -1,12 +1,21 @@
|
|
|
1
|
+
import { isValidChatTeamId } from "./thread.js";
|
|
2
|
+
import { isOffline, isOfflineNetworkFailure } from "./connectivity.js";
|
|
3
|
+
import { recordConversationRead } from "./conversationRead.js";
|
|
1
4
|
import { BatchedReadIndex } from "./batchedReadIndex.js";
|
|
2
5
|
import { WindowedTasks } from "./coalescer.js";
|
|
3
|
-
import { IndexedDbReadIndex, recordReadIntent } from "./readIndex.js";
|
|
6
|
+
import { IndexedDbReadIndex, readingMetadata, recordReadIntent, assertReadIndexVersions } from "./readIndex.js";
|
|
4
7
|
import { ReadSyncClient } from "./readSync.js";
|
|
5
8
|
/** Owns durable local reads, network coalescing, retries and state notifications.
|
|
6
9
|
* Hosts report actual visibility; loading or subscribing never marks messages read. */
|
|
7
10
|
export class ReadingClient {
|
|
8
11
|
options;
|
|
9
12
|
storage;
|
|
13
|
+
backing;
|
|
14
|
+
closing;
|
|
15
|
+
revoking;
|
|
16
|
+
versions;
|
|
17
|
+
prepared = new Map();
|
|
18
|
+
accepted = new Set();
|
|
10
19
|
persistence;
|
|
11
20
|
sync;
|
|
12
21
|
tasks;
|
|
@@ -16,24 +25,34 @@ export class ReadingClient {
|
|
|
16
25
|
retry;
|
|
17
26
|
retryDelay = 1000;
|
|
18
27
|
offWake;
|
|
28
|
+
offInbox;
|
|
19
29
|
generation = 0;
|
|
20
30
|
constructor(options) {
|
|
21
31
|
this.options = options;
|
|
22
|
-
|
|
32
|
+
if (options.teamId !== undefined && !isValidChatTeamId(options.teamId))
|
|
33
|
+
throw new Error("INVALID_READ_TEAM");
|
|
34
|
+
const storage = options.persistence ?? (this.storage = new IndexedDbReadIndex(globalThis.indexedDB, "pmate-social-read-index", options.storageScope, options.migrateLegacy, options.metadataOnly));
|
|
35
|
+
this.backing = storage;
|
|
23
36
|
this.persistence = new BatchedReadIndex(storage);
|
|
24
37
|
this.tasks = new WindowedTasks(1000, error => this.failed(error));
|
|
25
38
|
this.sync = new ReadSyncClient({ ...options, persistence: this.persistence, onChange: state => this.publish(state) });
|
|
39
|
+
if (options.inbox)
|
|
40
|
+
this.offInbox = options.inbox.subscribe(() => {
|
|
41
|
+
if (!this.closed)
|
|
42
|
+
void this.sync.applyInboxLocal().then(state => { if (state.pending.length)
|
|
43
|
+
this.refresh(); }).catch(error => this.failed(error));
|
|
44
|
+
});
|
|
26
45
|
}
|
|
27
46
|
getSnapshot = () => this.state;
|
|
28
47
|
subscribe = (listener) => { this.listeners.add(listener); return () => { this.listeners.delete(listener); }; };
|
|
29
48
|
publish(state) {
|
|
30
|
-
if (this.closed || JSON.stringify(state) === JSON.stringify(this.state))
|
|
49
|
+
if (this.closed || state === this.state || JSON.stringify(state) === JSON.stringify(this.state))
|
|
31
50
|
return;
|
|
32
51
|
this.state = state;
|
|
33
52
|
this.listeners.forEach(listener => listener());
|
|
34
53
|
}
|
|
35
54
|
failed(error) {
|
|
36
|
-
if (this.closed)
|
|
55
|
+
if (this.closed || isOfflineNetworkFailure(error))
|
|
37
56
|
return;
|
|
38
57
|
this.options.onError?.(error);
|
|
39
58
|
if (/HTTP_(400|401|403)/.test(String(error)) || (typeof navigator !== "undefined" && !navigator.onLine) || this.retry)
|
|
@@ -53,11 +72,13 @@ export class ReadingClient {
|
|
|
53
72
|
window.addEventListener("focus", wake);
|
|
54
73
|
this.offWake = () => { window.removeEventListener("online", wake); window.removeEventListener("focus", wake); };
|
|
55
74
|
}
|
|
56
|
-
this.
|
|
75
|
+
if (!this.options.inbox || this.state?.pending.length)
|
|
76
|
+
this.refresh();
|
|
57
77
|
}
|
|
58
78
|
refresh = () => {
|
|
59
|
-
if (!this.closed)
|
|
60
|
-
this.tasks.schedule("reading", async () => {
|
|
79
|
+
if (!this.closed && !isOffline() && !this.options.inbox?.offlineMode())
|
|
80
|
+
this.tasks.schedule("reading", async () => { if (!isOffline())
|
|
81
|
+
await this.synchronize(); });
|
|
61
82
|
};
|
|
62
83
|
async synchronize(targetCursor, profileId) {
|
|
63
84
|
if (this.closed)
|
|
@@ -84,32 +105,132 @@ export class ReadingClient {
|
|
|
84
105
|
}
|
|
85
106
|
throw new Error("Reading projection has not reached the announced version");
|
|
86
107
|
}
|
|
87
|
-
|
|
108
|
+
update(transform) {
|
|
109
|
+
// Advanced transforms may replace profile-wide state. Typed observation
|
|
110
|
+
// methods below only derive changes for their configured team.
|
|
111
|
+
return this.updateScoped(transform);
|
|
112
|
+
}
|
|
113
|
+
updateScoped(transform, teamId, observation) {
|
|
88
114
|
if (this.closed)
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
115
|
+
return Promise.reject(new Error("READING_CLIENT_CLOSED"));
|
|
116
|
+
// One shared metadata read per local authority generation, rather than one
|
|
117
|
+
// IndexedDB lookup for every viewport observation.
|
|
118
|
+
const versions = this.versions ??= this.persistence.loadVersions(this.options.appId, this.options.profileId);
|
|
119
|
+
const task = (async () => {
|
|
120
|
+
const expected = await versions;
|
|
121
|
+
const next = await this.persistence.update(this.options.appId, this.options.profileId, (state, currentVersions) => {
|
|
122
|
+
assertReadIndexVersions(expected, currentVersions, teamId);
|
|
123
|
+
const next = transform(state);
|
|
124
|
+
return this.options.metadataOnly ? readingMetadata(next) : next;
|
|
125
|
+
}, observation);
|
|
126
|
+
if (!this.closed) {
|
|
127
|
+
this.publish(next);
|
|
128
|
+
if (next.pending.length || next.observedReadIntents?.length)
|
|
129
|
+
this.refresh();
|
|
130
|
+
}
|
|
131
|
+
return next;
|
|
132
|
+
})().catch(error => {
|
|
133
|
+
if (String(error).includes("READ_SCOPE_CHANGED")) {
|
|
134
|
+
if (teamId !== undefined)
|
|
135
|
+
this.withdraw();
|
|
136
|
+
else
|
|
137
|
+
this.versions = undefined;
|
|
138
|
+
}
|
|
139
|
+
throw error;
|
|
140
|
+
});
|
|
141
|
+
this.accepted.add(task);
|
|
142
|
+
void task.finally(() => this.accepted.delete(task)).catch(() => { });
|
|
143
|
+
return task;
|
|
144
|
+
}
|
|
145
|
+
prepareTeam(teamId, version) {
|
|
146
|
+
if (this.closed)
|
|
147
|
+
return Promise.reject(new Error("READING_CLIENT_CLOSED"));
|
|
148
|
+
if (!isValidChatTeamId(teamId) || !Number.isSafeInteger(version) || version < 0)
|
|
149
|
+
return Promise.reject(new Error("INVALID_READ_SCOPE_VERSION"));
|
|
150
|
+
const previous = this.prepared.get(teamId);
|
|
151
|
+
if (previous && previous.version >= version)
|
|
152
|
+
return previous.task;
|
|
153
|
+
const task = (async () => {
|
|
154
|
+
if (version > 0)
|
|
155
|
+
await this.persistence.invalidateTeam(this.options.appId, this.options.profileId, teamId, version);
|
|
156
|
+
this.versions = undefined;
|
|
157
|
+
})().catch(error => { if (this.prepared.get(teamId)?.task === task)
|
|
158
|
+
this.prepared.delete(teamId); throw error; });
|
|
159
|
+
this.prepared.set(teamId, { version, task });
|
|
160
|
+
return task;
|
|
161
|
+
}
|
|
162
|
+
assertThreadTeam(state, threadId) {
|
|
163
|
+
if (this.options.teamId !== undefined && state.threads.some(thread => (thread.id === threadId || thread.conversationId === threadId) && thread.teamId !== undefined && thread.teamId !== this.options.teamId))
|
|
164
|
+
throw new Error("READ_CONVERSATION_TEAM_MISMATCH");
|
|
165
|
+
}
|
|
166
|
+
markRead(threadId, messages = [], threadRootId) {
|
|
167
|
+
return this.updateScoped(state => { this.assertThreadTeam(state, threadId); return recordConversationRead(state, threadId, messages, undefined, threadRootId); }, this.options.teamId);
|
|
97
168
|
}
|
|
98
169
|
recordVisible(threadId, messageIds) { return this.record(threadId, messageIds, "visible"); }
|
|
99
170
|
recordExplicit(threadId, messageIds) { return this.record(threadId, messageIds, "explicit"); }
|
|
100
171
|
record(threadId, ids, readPolicy) {
|
|
101
172
|
const messageIds = [...new Set(ids)];
|
|
102
|
-
|
|
173
|
+
if (!messageIds.length && this.state) {
|
|
174
|
+
try {
|
|
175
|
+
this.assertThreadTeam(this.state, threadId);
|
|
176
|
+
return Promise.resolve(this.state);
|
|
177
|
+
}
|
|
178
|
+
catch (error) {
|
|
179
|
+
return Promise.reject(error);
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
return this.updateScoped(state => { this.assertThreadTeam(state, threadId); return messageIds.reduce((next, messageId) => recordReadIntent(next, { threadId, messageId, readPolicy, operationId: crypto.randomUUID() }), state); }, this.options.teamId, this.state && messageIds.length ? { base: this.state, targets: messageIds.map(messageId => ({ threadId, messageId })) } : undefined);
|
|
103
183
|
}
|
|
104
|
-
|
|
184
|
+
withdraw() { this.stop(); }
|
|
185
|
+
stop() {
|
|
186
|
+
if (this.closed)
|
|
187
|
+
return;
|
|
105
188
|
this.closed = true;
|
|
106
189
|
this.generation++;
|
|
107
190
|
this.offWake?.();
|
|
191
|
+
this.offInbox?.();
|
|
108
192
|
this.tasks.close();
|
|
109
193
|
clearTimeout(this.retry);
|
|
110
194
|
this.sync.stop();
|
|
195
|
+
this.state = undefined;
|
|
196
|
+
this.listeners.forEach(listener => listener());
|
|
111
197
|
this.listeners.clear();
|
|
112
|
-
|
|
113
|
-
|
|
198
|
+
}
|
|
199
|
+
/** This client is retired permanently. Drain accepted local observations
|
|
200
|
+
* before deleting one team's profile-wide projection; sibling teams survive. */
|
|
201
|
+
revokeTeam(teamId, version, knownThreadIds = []) {
|
|
202
|
+
if (this.revoking)
|
|
203
|
+
return this.revoking;
|
|
204
|
+
if (this.closing)
|
|
205
|
+
return Promise.reject(new Error("READING_CLIENT_CLOSED"));
|
|
206
|
+
this.stop();
|
|
207
|
+
return this.revoking = (async () => {
|
|
208
|
+
try {
|
|
209
|
+
await Promise.allSettled([...this.accepted]);
|
|
210
|
+
await this.persistence.close();
|
|
211
|
+
if (!this.backing.invalidateTeam)
|
|
212
|
+
throw new Error("READ_SCOPE_INVALIDATION_UNAVAILABLE");
|
|
213
|
+
await this.backing.invalidateTeam(this.options.appId, this.options.profileId, teamId, version, knownThreadIds);
|
|
214
|
+
}
|
|
215
|
+
finally {
|
|
216
|
+
await this.storage?.close();
|
|
217
|
+
}
|
|
218
|
+
})();
|
|
219
|
+
}
|
|
220
|
+
close() {
|
|
221
|
+
if (this.revoking)
|
|
222
|
+
return this.revoking;
|
|
223
|
+
if (this.closing)
|
|
224
|
+
return this.closing;
|
|
225
|
+
this.stop();
|
|
226
|
+
return this.closing = (async () => {
|
|
227
|
+
try {
|
|
228
|
+
await Promise.allSettled([...this.accepted]);
|
|
229
|
+
await this.persistence.close();
|
|
230
|
+
}
|
|
231
|
+
finally {
|
|
232
|
+
await this.storage?.close();
|
|
233
|
+
}
|
|
234
|
+
})();
|
|
114
235
|
}
|
|
115
236
|
}
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
/** Social control envelopes do not contribute to message unread counts. */
|
|
2
|
+
export declare function isReadingControl(payload: unknown, appId: string): boolean;
|
|
3
|
+
/** Mirrors the server's voice policy for ordinary and quoted wire envelopes. */
|
|
4
|
+
export declare function messageRequiresPlayback(body: unknown): boolean;
|
|
5
|
+
export declare function messageMentionsProfile(body: unknown, profileId: string): boolean;
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/** Social control envelopes do not contribute to message unread counts. */
|
|
2
|
+
export function isReadingControl(payload, appId) {
|
|
3
|
+
if (!payload || typeof payload !== "object")
|
|
4
|
+
return false;
|
|
5
|
+
const value = payload;
|
|
6
|
+
if (value.body !== undefined)
|
|
7
|
+
return isReadingControl(value.body, appId);
|
|
8
|
+
return value.kind === "message" && value.content?.appId === appId && (value.content.reaction !== undefined || value.content.recall !== undefined);
|
|
9
|
+
}
|
|
10
|
+
/** Mirrors the server's voice policy for ordinary and quoted wire envelopes. */
|
|
11
|
+
export function messageRequiresPlayback(body) {
|
|
12
|
+
if (!body || typeof body !== "object")
|
|
13
|
+
return false;
|
|
14
|
+
const value = body;
|
|
15
|
+
return value.contentKind === "voice" || value.content?.contentKind === "voice" || [value.content?.voice?.url, value.content?.content?.voice?.url].some(url => typeof url === "string" && url.length > 0);
|
|
16
|
+
}
|
|
17
|
+
export function messageMentionsProfile(body, profileId) {
|
|
18
|
+
if (!body || typeof body !== "object")
|
|
19
|
+
return false;
|
|
20
|
+
const content = body.content;
|
|
21
|
+
const mentions = content?.mentions !== undefined ? content.mentions : content?.content?.mentions;
|
|
22
|
+
return Array.isArray(mentions) && mentions.some(mention => mention?.id === profileId);
|
|
23
|
+
}
|