@pmate/chat-sdk 0.12.0-next.87 → 0.12.0-next.89

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.
@@ -9,6 +9,14 @@ export declare class ChatError extends Error {
9
9
  tables?: string;
10
10
  mode?: string;
11
11
  attempt?: number;
12
+ route?: string;
13
+ method?: string;
14
+ operationId?: string;
15
+ clientRequestId?: string;
16
+ serverRequestId?: string;
17
+ serverCode?: string;
18
+ status?: number;
19
+ durationMs?: number;
12
20
  };
13
21
  readonly retryable: boolean;
14
22
  readonly status?: number;
@@ -74,6 +74,7 @@ export declare class ChatEngine {
74
74
  private threadSubscribers;
75
75
  private openQueue;
76
76
  private opening;
77
+ private threadRecovery;
77
78
  private drainOpens;
78
79
  /** Listen first, then open the local window; concurrent consumers share the initial read. */
79
80
  subscribeThread(threadId: string, listener: (snapshot: ChatThreadSnapshot) => void, options?: SubscribeOptions<ChatThreadSnapshot>): () => void;
@@ -108,15 +108,18 @@ export class ChatEngine {
108
108
  }
109
109
  threadSubscribers = new Map();
110
110
  openQueue = new Set();
111
- opening = 0;
111
+ opening = new Set();
112
+ threadRecovery = new Map();
112
113
  drainOpens() {
113
- while (!this.closed && this.opening < 4 && this.openQueue.size) {
114
- const id = this.openQueue.values().next().value;
114
+ while (!this.closed && this.opening.size < 4 && this.openQueue.size) {
115
+ const id = [...this.openQueue].find(id => !this.opening.has(id));
116
+ if (id === undefined)
117
+ break;
115
118
  this.openQueue.delete(id);
116
119
  if (!this.threadSubscribers.has(id))
117
120
  continue;
118
- this.opening++;
119
- void this.getThread(id).catch(() => { }).finally(() => { this.opening--; this.drainOpens(); });
121
+ this.opening.add(id);
122
+ void this.getThread(id).catch(() => { }).finally(() => { this.opening.delete(id); this.drainOpens(); });
120
123
  }
121
124
  }
122
125
  /** Listen first, then open the local window; concurrent consumers share the initial read. */
@@ -124,6 +127,20 @@ export class ChatEngine {
124
127
  const off = this.subscribe(threadId, listener, options), count = this.threadSubscribers.get(threadId) ?? 0;
125
128
  this.threadSubscribers.set(threadId, count + 1);
126
129
  if (!count) {
130
+ // Track coverage independently of consumer field filters. A canonical history
131
+ // reset also invalidates open discussion windows sharing that source epoch.
132
+ let complete = this.advanced.getSnapshot(threadId).complete;
133
+ this.threadRecovery.set(threadId, this.advanced.subscribeChanges(threadId, () => {
134
+ const next = this.advanced.getSnapshot(threadId).complete, lost = complete && !next;
135
+ complete = next;
136
+ if (lost)
137
+ queueMicrotask(() => {
138
+ if (this.closed || !this.advanced.active || !this.threadSubscribers.has(threadId) || this.getSnapshot(threadId).status !== "pending")
139
+ return;
140
+ this.openQueue.add(threadId);
141
+ this.drainOpens();
142
+ });
143
+ }, ["complete"]));
127
144
  this.openQueue.add(threadId);
128
145
  this.drainOpens();
129
146
  }
@@ -139,6 +156,8 @@ export class ChatEngine {
139
156
  else {
140
157
  this.threadSubscribers.delete(threadId);
141
158
  this.openQueue.delete(threadId);
159
+ this.threadRecovery.get(threadId)?.();
160
+ this.threadRecovery.delete(threadId);
142
161
  }
143
162
  };
144
163
  }
@@ -283,5 +302,5 @@ export class ChatEngine {
283
302
  updateGroup(threadId, changes) { return this.threadOperation(threadId, async () => this.group(await this.advanced.updateGroup(threadId, changes))); }
284
303
  dissolveGroup(threadId, options = {}) { return this.threadOperation(threadId, async () => this.group(await this.advanced.dissolveGroup(threadId, options))); }
285
304
  revokeAccess() { return this.operation(() => this.advanced.revokeAccess()); }
286
- close() { this.closed = true; return this.operation(() => this.advanced.close()).finally(() => { this.errors.clear(); this.targets.clear(); this.listeners.clear(); this.threadSubscribers.clear(); this.openQueue.clear(); this.views.clear(); this.summary = undefined; this.present = createMessagePresenter(); this.messageLists = new WeakMap(); this.groups = new WeakMap(); this.redactedQuotes = new WeakMap(); }); }
305
+ close() { this.closed = true; this.threadRecovery.forEach(off => off()); this.threadRecovery.clear(); return this.operation(() => this.advanced.close()).finally(() => { this.errors.clear(); this.targets.clear(); this.listeners.clear(); this.threadSubscribers.clear(); this.openQueue.clear(); this.views.clear(); this.summary = undefined; this.present = createMessagePresenter(); this.messageLists = new WeakMap(); this.groups = new WeakMap(); this.redactedQuotes = new WeakMap(); }); }
287
306
  }
@@ -16,7 +16,9 @@ import { ChatClient, type ChatClientOptions, type ChatConnectionState } from "./
16
16
  import { unreadInConversation } from "./readIndex.js";
17
17
  import type { StoredMessage } from "./messageStore.js";
18
18
  import type { ChatRuntimeMessage } from "./protocol.js";
19
+ import type { InboxClient } from "./inboxClient.js";
19
20
  export type ChatSessionOptions<T extends StoredMessage> = {
21
+ inbox?: InboxClient;
20
22
  discussion?: MessageThreadScope;
21
23
  messageThreads?: (threadId: string, roots: readonly string[], signal?: AbortSignal) => Promise<{
22
24
  items: import("./socialReadClient.js").MessageThreadSummary[];
@@ -91,7 +91,7 @@ export class ChatSession {
91
91
  this.reading = new ReadingClient({ ...options.reading, teamId: scope.teamId, storageScope: JSON.stringify([scope.accountId]), migrateLegacy: true, metadataOnly: true });
92
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
93
  if (options.loadGroup) {
94
- this.groups = new GroupClient({ scope, access: () => this.messages.scopeAccess(), load: options.loadGroup, onError: options.onError, onDenied: async (error, _threadId, signal) => {
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
95
  if (error?.status === 403 && options.messages.transport.authorizeScope) {
96
96
  try {
97
97
  await options.messages.transport.authorizeScope(signal ?? new AbortController().signal);
@@ -147,9 +147,19 @@ export class ChatSession {
147
147
  this.off.push(this.messages.subscribeAccessRevoked(() => { if (!this.withdrawn && !this.closed)
148
148
  void this.revokeAccess().catch(error => options.onError(error)); }));
149
149
  this.off.push(this.messages.subscribeAll(thread => this.publish(thread)));
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
+ }));
150
156
  this.off.push(this.sender.subscribe(() => this.publishAll()), this.reading.subscribe(() => { this.publishAll(); if (this.readingAllowed)
151
157
  this.readingListeners.forEach(listener => listener()); }));
152
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;
153
163
  try {
154
164
  const body = message.body;
155
165
  if (body?.kind === "group" && body.payload?.appId === scope.appId && body.payload.teamId === scope.teamId && body.payload.groupId === message.to) {
@@ -213,6 +223,7 @@ export class ChatSession {
213
223
  initialize() {
214
224
  this.assertOpen();
215
225
  return this.initializing ??= (async () => {
226
+ await this.options.inbox?.start();
216
227
  await this.sender.initialize();
217
228
  this.assertOpen();
218
229
  await this.startReading();
@@ -658,6 +669,11 @@ export class ChatSession {
658
669
  return undefined;
659
670
  if (event.appId !== this.options.messages.scope.appId)
660
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
+ }
661
677
  if (event.eventType === "social.readCountsChanged") {
662
678
  if (typeof event.payload.threadId !== "string" || !Number.isSafeInteger(event.payload.revision) || Number(event.payload.revision) < 0)
663
679
  throw new Error("INVALID_READ_COUNTS_EVENT");
@@ -1,9 +1,11 @@
1
1
  import { type TokenProvider } from "../credentials.js";
2
2
  import { ChatSession } from "./chatSession.js";
3
3
  import type { ChatClient, ChatClientOptions } from "./chatClient.js";
4
+ import type { InboxClient } from "./inboxClient.js";
4
5
  import { type CachedChatMessage } from "./cachedMessage.js";
5
6
  export type { CachedChatMessage } from "./cachedMessage.js";
6
7
  export type CreateChatOptions = {
8
+ inbox?: InboxClient;
7
9
  appId: string;
8
10
  accountId: string;
9
11
  profileId: string;
@@ -8,10 +8,13 @@ import { isReadingControl, messageRequiresPlayback, messageMentionsProfile } fro
8
8
  import { ChatSession } from "./chatSession.js";
9
9
  import { SocialReadClient } from "./socialReadClient.js";
10
10
  import { isValidChatTeamId } from "./thread.js";
11
+ import { inboxMessageTransport } from "./inboxTransport.js";
11
12
  import { decodeCachedChatMessage } from "./cachedMessage.js";
12
13
  /** Standard browser entry: storage, paging, realtime and reading share one identity. */
13
14
  export function createChatSession(options) {
14
15
  const { appId, accountId, profileId, teamId, onError } = options;
16
+ if (options.inbox && ["appId", "accountId", "profileId"].some(key => options.inbox.store.scope[key] !== options[key]))
17
+ throw new Error("CHAT_INBOX_SCOPE_MISMATCH");
15
18
  if (options.threadRootId !== undefined && !options.threadId)
16
19
  throw new Error("MESSAGE_THREAD_CONVERSATION_REQUIRED");
17
20
  const token = options.token ?? "";
@@ -29,9 +32,10 @@ export function createChatSession(options) {
29
32
  return { ...result, messages: result.messages.map(message => ({ ...message, id: message.messageId, timestamp: message.serverCreatedAt })) };
30
33
  };
31
34
  return new ChatSession({
35
+ inbox: options.inbox,
32
36
  sharedConnection: options.connection,
33
37
  discussion: { threadRootId: options.threadRootId },
34
- messageThreads: (threadId, roots, signal) => reader.messageThreads({ threadId, teamId, rootMessageIds: roots }, signal),
38
+ messageThreads: (threadId, roots, signal) => options.inbox ? options.inbox.store.discussionSummaries(threadId, teamId, roots) : reader.messageThreads({ threadId, teamId, rootMessageIds: roots }, signal),
35
39
  onDispose: () => credentials?.close(),
36
40
  uploadVoice: voiceUploader(profileId, options.uploadEndpoint, fetcher),
37
41
  reconcileOutgoing: async (record, signal) => {
@@ -46,10 +50,19 @@ export function createChatSession(options) {
46
50
  return true;
47
51
  });
48
52
  },
49
- loadGroup: (groupId, signal) => reader.group({ groupId, teamId }, signal),
53
+ loadGroup: async (groupId, signal) => {
54
+ if (options.inbox) {
55
+ const group = await options.inbox.store.group(groupId, teamId);
56
+ if (group)
57
+ return group;
58
+ if (options.inbox.offlineMode() || isOffline())
59
+ throw new Error("GROUP_METADATA_OFFLINE");
60
+ }
61
+ return reader.group({ groupId, teamId }, signal);
62
+ },
50
63
  activeThreadId: options.threadId,
51
- messages: { scope: { appId, accountId, profileId, teamId }, storage: new IndexedDbDiscussionStore({ appId, accountId, profileId, teamId }, mergeStoredMessage, { threadRootId: options.threadRootId }), transport: { authorizeScope: async (signal) => { await reader.contacts(teamId, signal); }, load: (thread, signal) => page(thread, signal), changes: (thread, after, signal) => page(thread, signal, { after }), older: (thread, before, signal) => page(thread, signal, { before }) }, onError },
52
- reading: { appId, profileId, sessionToken: token, hubHttpUrl: http, fetch: fetcher, onError },
64
+ messages: { scope: { appId, accountId, profileId, teamId }, storage: new IndexedDbDiscussionStore({ appId, accountId, profileId, teamId }, mergeStoredMessage, { threadRootId: options.threadRootId }), transport: options.inbox ? { ...inboxMessageTransport(options.inbox, teamId, options.threadRootId), authorizeScope: async (signal) => { await reader.contacts(teamId, signal); } } : { authorizeScope: async (signal) => { await reader.contacts(teamId, signal); }, load: (thread, signal) => page(thread, signal), changes: (thread, after, signal) => page(thread, signal, { after }), older: (thread, before, signal) => page(thread, signal, { before }) }, onError },
65
+ reading: { appId, profileId, sessionToken: token, hubHttpUrl: http, fetch: fetcher, onError, inbox: options.inbox },
53
66
  connection: { appId, profileId, teamId, hubUrl: ws, clientInstanceId: options.clientInstanceId, fetchImpl: fetcher,
54
67
  getToken: credentials?.getToken,
55
68
  session: { token, identity: { accountId, app: appId, profileId } }, onNotification: options.onNotification, onReach: options.onReach },
@@ -30,6 +30,7 @@ export type GroupSnapshot = {
30
30
  error?: unknown;
31
31
  };
32
32
  export type GroupClientOptions = {
33
+ local?: boolean;
33
34
  scope: MessageScope;
34
35
  access: ResponseCacheAccess;
35
36
  load: (groupId: string, signal: AbortSignal) => Promise<SocialGroup>;
@@ -191,15 +191,15 @@ export class GroupClient {
191
191
  else if (this.denied.has(thread.id))
192
192
  throw entry.snapshot.error ?? scopedGroupDenial(Object.assign(new Error("GROUP_ACCESS_DENIED"), { status: 403, threadId: thread.id }));
193
193
  if (entry.snapshot.data && !options.refresh) {
194
- if (!entry.checked && !isOffline())
194
+ if (!entry.checked && (!isOffline() || this.options.local))
195
195
  this.schedule(entry);
196
196
  return entry.snapshot.data;
197
197
  }
198
- if (isOffline())
198
+ if (isOffline() && !this.options.local)
199
199
  throw entry.snapshot.error ?? new Error("GROUP_METADATA_OFFLINE");
200
200
  return this.request(entry);
201
201
  }
202
- schedule(entry) { if (!this.closed && !this.withdrawn && !this.denied.has(entry.thread.id) && !isOffline())
202
+ schedule(entry) { if (!this.closed && !this.withdrawn && !this.denied.has(entry.thread.id) && (!isOffline() || this.options.local))
203
203
  this.tasks.schedule(entry.thread.id, async () => { await this.get(entry.thread, { refresh: true }); }); }
204
204
  async denyGroup(entry, error) {
205
205
  const value = { status: "access-denied", revision: crypto.randomUUID() };
@@ -0,0 +1,63 @@
1
+ import { IndexedDbInbox, type InboxScope, type InboxEvent } from "./inboxStore.js";
2
+ export type InboxProgress = {
3
+ stage: "loading" | "syncing" | "ready" | "offline" | "error";
4
+ percent: number;
5
+ processed: string;
6
+ total: string;
7
+ error?: unknown;
8
+ };
9
+ export type InboxClientOptions = InboxScope & {
10
+ sessionToken: string;
11
+ getToken?: () => string | Promise<string>;
12
+ hubHttpUrl: string;
13
+ fetch?: typeof fetch;
14
+ store?: IndexedDbInbox;
15
+ onError?: (error: unknown) => void;
16
+ onProgress?: (progress: InboxProgress) => void;
17
+ onChange?: (threads: readonly string[]) => void;
18
+ live?: boolean;
19
+ };
20
+ /** Push full facts normally; range catch-up repairs gaps and silent push loss.
21
+ * One persisted lease owns live/check traffic across tabs and team sessions. */
22
+ export declare class InboxClient {
23
+ private options;
24
+ readonly store: IndexedDbInbox;
25
+ private closed;
26
+ private controller;
27
+ private streamController?;
28
+ private timer?;
29
+ private running?;
30
+ private liveTask?;
31
+ private reconnectTimer?;
32
+ private token;
33
+ private channel?;
34
+ private listeners;
35
+ private progressListeners;
36
+ private progress;
37
+ private wake?;
38
+ private starting?;
39
+ private offlineAllowed;
40
+ private initializedOnce;
41
+ private eventListeners;
42
+ constructor(options: InboxClientOptions);
43
+ snapshot: () => InboxProgress;
44
+ subscribeProgress: (listener: () => void) => () => void;
45
+ subscribeEvents(listener: (events: readonly InboxEvent[]) => void): () => void;
46
+ private facts;
47
+ subscribe(listener: (threads: readonly string[]) => void): () => void;
48
+ private publish;
49
+ private notify;
50
+ private credentials;
51
+ private request;
52
+ start(): Promise<void>;
53
+ readyForDisplay(): boolean;
54
+ offlineMode(): boolean;
55
+ allowOffline(): Promise<void>;
56
+ private initialize;
57
+ synchronize(): Promise<void>;
58
+ private catchUp;
59
+ private tick;
60
+ private listen;
61
+ private failed;
62
+ close(): Promise<void>;
63
+ }
@@ -0,0 +1,259 @@
1
+ import { IndexedDbInbox, inboxSequence } from "./inboxStore.js";
2
+ import { isOffline } from "./connectivity.js";
3
+ /** Push full facts normally; range catch-up repairs gaps and silent push loss.
4
+ * One persisted lease owns live/check traffic across tabs and team sessions. */
5
+ export class InboxClient {
6
+ options;
7
+ store;
8
+ closed = false;
9
+ controller = new AbortController();
10
+ streamController;
11
+ timer;
12
+ running;
13
+ liveTask;
14
+ reconnectTimer;
15
+ token = crypto.randomUUID();
16
+ channel;
17
+ listeners = new Set();
18
+ progressListeners = new Set();
19
+ progress = { stage: "loading", percent: 0, processed: "0", total: "0" };
20
+ wake;
21
+ starting;
22
+ offlineAllowed = false;
23
+ initializedOnce = false;
24
+ eventListeners = new Set();
25
+ constructor(options) {
26
+ this.options = options;
27
+ this.store = options.store ?? new IndexedDbInbox(options);
28
+ if (typeof BroadcastChannel !== "undefined" && typeof window !== "undefined") {
29
+ this.channel = new BroadcastChannel(`pmate-inbox:${this.store.owner}`);
30
+ this.channel.onmessage = event => { if (Array.isArray(event.data?.threads))
31
+ this.notify(event.data.threads, false); if (this.initializedOnce && Array.isArray(event.data?.events))
32
+ this.eventListeners.forEach(listener => listener(event.data.events)); };
33
+ }
34
+ }
35
+ snapshot = () => this.progress;
36
+ subscribeProgress = (listener) => { this.progressListeners.add(listener); return () => { this.progressListeners.delete(listener); }; };
37
+ subscribeEvents(listener) { this.eventListeners.add(listener); return () => { this.eventListeners.delete(listener); }; }
38
+ facts(events, after) { if (this.initializedOnce) {
39
+ const fresh = events.filter(event => inboxSequence(event.inboxSeq) > inboxSequence(after));
40
+ if (fresh.length) {
41
+ this.eventListeners.forEach(listener => listener(fresh));
42
+ this.channel?.postMessage({ events: fresh });
43
+ }
44
+ } }
45
+ subscribe(listener) { this.listeners.add(listener); return () => { this.listeners.delete(listener); }; }
46
+ publish(progress) { if (this.closed)
47
+ return; if (progress.stage === "syncing" && this.progress.stage === "syncing")
48
+ progress = { ...progress, percent: Math.max(progress.percent, this.progress.percent) }; this.progress = progress; this.options.onProgress?.(progress); this.progressListeners.forEach(listener => listener()); }
49
+ notify(threads, broadcast = true) { if (this.closed)
50
+ return; this.options.onChange?.(threads); this.listeners.forEach(listener => listener(threads)); if (broadcast)
51
+ this.channel?.postMessage({ threads }); }
52
+ async credentials() { const token = await this.options.getToken?.() ?? this.options.sessionToken; if (!token)
53
+ throw new Error("INBOX_CREDENTIALS_UNAVAILABLE"); return token; }
54
+ async request(action, params = {}, signal) {
55
+ const query = new URLSearchParams({ appId: this.options.appId, profileId: this.options.profileId, ...params });
56
+ const response = await (this.options.fetch ?? fetch)(`${this.options.hubHttpUrl.replace(/\/$/, "")}/api/social/inbox/${action}?${query}`, { headers: { authorization: `Bearer ${await this.credentials()}` }, cache: "no-store", redirect: "error", signal: AbortSignal.any([this.controller.signal, ...(signal ? [signal] : []), AbortSignal.timeout(20000)]) });
57
+ const result = await response.json();
58
+ if (!response.ok || result.success !== true || result.data === undefined)
59
+ throw Object.assign(new Error(`INBOX_HTTP_${response.status}`), { status: response.status });
60
+ return result.data;
61
+ }
62
+ start() { return this.starting ??= this.initialize().catch(error => { this.starting = undefined; throw error; }); }
63
+ readyForDisplay() { return this.initializedOnce || this.offlineAllowed; }
64
+ offlineMode() { return this.offlineAllowed && this.progress.stage !== "ready"; }
65
+ async allowOffline() {
66
+ const cursor = await this.store.cursor();
67
+ if (!cursor?.initialized)
68
+ throw new Error("INBOX_OFFLINE_CACHE_UNAVAILABLE");
69
+ this.offlineAllowed = true;
70
+ this.publish({ ...this.progress, stage: "offline", percent: 100 });
71
+ }
72
+ async initialize() {
73
+ if (this.options.live === false) {
74
+ await this.synchronize();
75
+ return;
76
+ }
77
+ if (this.closed)
78
+ throw new Error("INBOX_CLIENT_CLOSED");
79
+ if (!this.timer)
80
+ this.timer = setInterval(() => { void this.tick().catch(error => this.failed(error)); }, 10000);
81
+ if (typeof window !== "undefined" && !this.wake) {
82
+ this.wake = () => {
83
+ if (typeof document !== "undefined" && document.hidden) {
84
+ this.streamController?.abort();
85
+ void this.store.releaseLease(this.token);
86
+ return;
87
+ }
88
+ void this.tick().catch(error => this.failed(error));
89
+ };
90
+ for (const event of ["online", "focus", "pageshow"])
91
+ window.addEventListener(event, this.wake);
92
+ if (typeof document !== "undefined")
93
+ document.addEventListener("visibilitychange", this.wake);
94
+ }
95
+ if (this.offlineAllowed && (await this.store.cursor())?.initialized)
96
+ return;
97
+ await this.synchronize();
98
+ await this.tick(false);
99
+ }
100
+ synchronize() {
101
+ if (this.closed)
102
+ return Promise.reject(new Error("INBOX_CLIENT_CLOSED"));
103
+ return this.running ??= this.catchUp().catch(error => { this.failed(error); throw error; }).finally(() => { this.running = undefined; });
104
+ }
105
+ async catchUp() {
106
+ if (isOffline())
107
+ throw new Error("INBOX_OFFLINE");
108
+ let cursor = await this.store.cursor(), initial;
109
+ if (cursor)
110
+ initial = await this.request("check", { afterSeq: cursor.seq, epoch: cursor.epoch });
111
+ if (!cursor || initial?.resetRequired) {
112
+ const bootstrap = await this.request("bootstrap");
113
+ cursor = await this.store.bootstrap(bootstrap);
114
+ this.notify([]);
115
+ initial = undefined;
116
+ const target = inboxSequence(bootstrap.headSeq), start = inboxSequence(cursor.seq);
117
+ this.publish({ stage: "syncing", percent: 0, processed: "0", total: (target - start).toString() });
118
+ do {
119
+ const page = await this.request("events", { afterSeq: cursor.seq, throughSeq: target.toString(), epoch: cursor.epoch });
120
+ const previous = cursor.seq, applied = await this.store.apply(page);
121
+ cursor = applied.cursor;
122
+ this.notify(applied.threads);
123
+ this.facts(page.events, previous);
124
+ const processed = inboxSequence(cursor.seq) - start, total = target - start;
125
+ this.publish({ stage: "syncing", percent: total === 0n ? 99 : Number(processed * 9900n / total) / 100, processed: processed.toString(), total: total.toString() });
126
+ } while (inboxSequence(cursor.seq) < target);
127
+ // Capture one more committed head after the fixed initial target, then
128
+ // connect the live stream from the durable cursor so startup has no gap.
129
+ initial = await this.request("check", { afterSeq: cursor.seq, epoch: cursor.epoch });
130
+ }
131
+ const start = inboxSequence(cursor.seq), target = inboxSequence(initial.headSeq);
132
+ let page = initial;
133
+ do {
134
+ const previous = cursor.seq, applied = await this.store.apply(page);
135
+ cursor = applied.cursor;
136
+ this.notify(applied.threads);
137
+ this.facts(page.events, previous);
138
+ const processed = inboxSequence(cursor.seq) - start, total = target - start;
139
+ this.publish({ stage: "syncing", percent: total === 0n ? 99 : Number(processed * 9900n / total) / 100, processed: processed.toString(), total: total.toString() });
140
+ if (inboxSequence(cursor.seq) >= target)
141
+ break;
142
+ page = await this.request("events", { afterSeq: cursor.seq, throughSeq: target.toString(), epoch: cursor.epoch });
143
+ } while (!this.closed);
144
+ if (!this.closed) {
145
+ this.initializedOnce = true;
146
+ this.publish({ stage: "ready", percent: 100, processed: (target - start).toString(), total: (target - start).toString() });
147
+ this.notify([]);
148
+ }
149
+ }
150
+ async tick(check = true) {
151
+ if (this.closed || isOffline() || typeof document !== "undefined" && document.hidden)
152
+ return;
153
+ if (!await this.store.claimLease(this.token)) {
154
+ this.streamController?.abort();
155
+ return;
156
+ }
157
+ if (check)
158
+ await this.synchronize();
159
+ if (!this.liveTask) {
160
+ let failed = false;
161
+ const task = this.listen().catch(error => { failed = true; if (!this.closed && error?.name !== "AbortError")
162
+ this.failed(error); }).finally(() => {
163
+ if (this.liveTask === task)
164
+ this.liveTask = undefined;
165
+ if (!this.closed)
166
+ this.reconnectTimer = setTimeout(() => { void this.tick(false).catch(error => this.failed(error)); }, failed ? 1000 : 0);
167
+ });
168
+ this.liveTask = task;
169
+ }
170
+ }
171
+ async listen() {
172
+ const cursor = await this.store.cursor();
173
+ if (!cursor || this.closed)
174
+ return;
175
+ const query = new URLSearchParams({ appId: this.options.appId, profileId: this.options.profileId, afterSeq: cursor.seq, epoch: cursor.epoch });
176
+ const controller = this.streamController = new AbortController();
177
+ const response = await (this.options.fetch ?? fetch)(`${this.options.hubHttpUrl.replace(/\/$/, "")}/api/social/inbox/live?${query}`, { headers: { authorization: `Bearer ${await this.credentials()}` }, cache: "no-store", redirect: "error", signal: AbortSignal.any([this.controller.signal, controller.signal]) });
178
+ if (!response.ok || !response.body)
179
+ throw Object.assign(new Error(`INBOX_LIVE_HTTP_${response.status}`), { status: response.status });
180
+ const reader = response.body.getReader(), decoder = new TextDecoder();
181
+ let buffer = "";
182
+ try {
183
+ for (;;) {
184
+ const part = await reader.read();
185
+ if (part.done)
186
+ break;
187
+ buffer += decoder.decode(part.value, { stream: true });
188
+ buffer = buffer.replace(/\r\n/g, "\n");
189
+ if (buffer.length > 16 * 1024 * 1024)
190
+ throw new Error("INBOX_LIVE_TOO_LARGE");
191
+ let boundary;
192
+ while ((boundary = buffer.indexOf("\n\n")) >= 0) {
193
+ const frame = buffer.slice(0, boundary);
194
+ buffer = buffer.slice(boundary + 2);
195
+ const type = frame.split("\n").find(line => line.startsWith("event:"))?.slice(6).trim();
196
+ const data = frame.split("\n").filter(line => line.startsWith("data:")).map(line => line.slice(5).replace(/^ /, "")).join("\n");
197
+ if (type === "error")
198
+ throw new Error("INBOX_LIVE_UNAVAILABLE");
199
+ if (type !== "inbox" || !data)
200
+ continue;
201
+ const page = JSON.parse(data);
202
+ if (page.resetRequired) {
203
+ await this.synchronize();
204
+ return;
205
+ }
206
+ try {
207
+ const previous = (await this.store.cursor())?.seq ?? "0", applied = await this.store.apply(page);
208
+ if (applied.threads.length)
209
+ this.notify(applied.threads);
210
+ this.facts(page.events, previous);
211
+ }
212
+ catch (error) {
213
+ if (String(error).includes("INBOX_SEQUENCE_GAP")) {
214
+ await this.synchronize();
215
+ }
216
+ else
217
+ throw error;
218
+ }
219
+ }
220
+ }
221
+ }
222
+ finally {
223
+ await reader.cancel().catch(() => { });
224
+ reader.releaseLock();
225
+ if (this.streamController === controller)
226
+ this.streamController = undefined;
227
+ }
228
+ }
229
+ failed(error) {
230
+ if (this.closed)
231
+ return;
232
+ this.publish({ ...this.progress, stage: isOffline() ? "offline" : "error", error });
233
+ if (!isOffline())
234
+ this.options.onError?.(error);
235
+ }
236
+ async close() {
237
+ if (this.closed)
238
+ return;
239
+ this.closed = true;
240
+ this.controller.abort();
241
+ this.streamController?.abort();
242
+ clearInterval(this.timer);
243
+ clearTimeout(this.reconnectTimer);
244
+ if (this.wake && typeof window !== "undefined") {
245
+ for (const event of ["online", "focus", "pageshow"])
246
+ window.removeEventListener(event, this.wake);
247
+ if (typeof document !== "undefined")
248
+ document.removeEventListener("visibilitychange", this.wake);
249
+ }
250
+ await Promise.allSettled([this.running, this.liveTask]);
251
+ await this.store.releaseLease(this.token);
252
+ this.channel?.close();
253
+ this.eventListeners.clear();
254
+ this.listeners.clear();
255
+ this.progressListeners.clear();
256
+ if (!this.options.store)
257
+ this.store.close();
258
+ }
259
+ }
@@ -0,0 +1,4 @@
1
+ import type { SocialGroup } from "./socialReadClient.js";
2
+ /** Replay structural source facts using the same causal revisions as the Hub.
3
+ * Message order or a late control cannot independently dissolve a group. */
4
+ export declare function projectInboxGroup(appId: string, groupId: string, teamId: string | undefined, events: readonly Record<string, any>[]): SocialGroup | undefined;
@@ -0,0 +1,51 @@
1
+ /** Replay structural source facts using the same causal revisions as the Hub.
2
+ * Message order or a late control cannot independently dissolve a group. */
3
+ export function projectInboxGroup(appId, groupId, teamId, events) {
4
+ const controls = events.filter(event => event.appId === appId && event.to === groupId && event.teamId === teamId && event.threadKind === "group" && event.body?.kind === "group");
5
+ const creates = controls.filter(event => event.body.action === "groupCreate");
6
+ if (creates.length !== 1)
7
+ return;
8
+ const creation = creates[0], owner = creation.from;
9
+ const members = (value) => Array.isArray(value) && value.length <= 256 && value.every(id => typeof id === "string" && id.length > 0 && id.length <= 256) ? [...new Set(value)] : undefined;
10
+ const initial = members(creation.body.payload?.members);
11
+ if (!owner || !creation.messageId || !initial)
12
+ return;
13
+ const initialMembers = [...new Set([...initial, owner])];
14
+ if (initialMembers.length > 256)
15
+ return;
16
+ let group = { appId, groupId, teamId, ownerId: owner, members: initialMembers, title: typeof creation.body.payload.title === "string" ? creation.body.payload.title : "", avatar: typeof creation.body.payload.avatar === "string" ? creation.body.payload.avatar : null, revision: creation.messageId, versionNumber: 1, status: "active" };
17
+ const updates = new Map();
18
+ for (const event of controls)
19
+ if (["groupUpdate", "groupDissolve"].includes(event.body.action) && typeof event.body.payload?.previousRevision === "string") {
20
+ const key = event.body.payload.previousRevision;
21
+ updates.set(key, [...(updates.get(key) ?? []), event]);
22
+ }
23
+ const seen = new Set();
24
+ for (;;) {
25
+ if (seen.has(group.revision))
26
+ return;
27
+ seen.add(group.revision);
28
+ const next = updates.get(group.revision);
29
+ if (!next)
30
+ return group;
31
+ if (next.length !== 1 || group.status === "dissolved")
32
+ return;
33
+ const event = next[0], payload = event.body.payload, actor = event.from;
34
+ if (!actor || !event.messageId)
35
+ return;
36
+ if (event.body.action === "groupDissolve") {
37
+ if (actor !== owner)
38
+ return;
39
+ group = { ...group, revision: event.messageId, versionNumber: group.versionNumber + 1, status: "dissolved", dissolvedBy: actor, dissolvedAt: event.serverCreatedAt };
40
+ }
41
+ else {
42
+ const ids = members(payload.members);
43
+ if (!ids || !ids.includes(owner) || !group.members?.includes(actor))
44
+ return;
45
+ if (actor !== owner && (group.members.some(id => !ids.includes(id)) || typeof payload.avatar === "string" && payload.avatar !== group.avatar || typeof payload.title === "string" && payload.title !== group.title))
46
+ return;
47
+ group = { ...group, members: ids, revision: event.messageId, versionNumber: group.versionNumber + 1,
48
+ ...(typeof payload.title === "string" ? { title: payload.title } : {}), ...(typeof payload.avatar === "string" ? { avatar: payload.avatar } : {}) };
49
+ }
50
+ }
51
+ }