@pmate/chat-sdk 0.12.0-next.89 → 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.
@@ -37,6 +37,8 @@ export declare class InboxClient {
37
37
  private wake?;
38
38
  private starting?;
39
39
  private offlineAllowed;
40
+ private enterOffline;
41
+ private offlineEntry;
40
42
  private initializedOnce;
41
43
  private eventListeners;
42
44
  constructor(options: InboxClientOptions);
@@ -20,6 +20,8 @@ export class InboxClient {
20
20
  wake;
21
21
  starting;
22
22
  offlineAllowed = false;
23
+ enterOffline = () => { };
24
+ offlineEntry = new Promise(resolve => { this.enterOffline = resolve; });
23
25
  initializedOnce = false;
24
26
  eventListeners = new Set();
25
27
  constructor(options) {
@@ -59,7 +61,7 @@ export class InboxClient {
59
61
  throw Object.assign(new Error(`INBOX_HTTP_${response.status}`), { status: response.status });
60
62
  return result.data;
61
63
  }
62
- start() { return this.starting ??= this.initialize().catch(error => { this.starting = undefined; throw error; }); }
64
+ start() { return this.starting ??= Promise.race([this.initialize(), this.offlineEntry]).catch(error => { this.starting = undefined; throw error; }); }
63
65
  readyForDisplay() { return this.initializedOnce || this.offlineAllowed; }
64
66
  offlineMode() { return this.offlineAllowed && this.progress.stage !== "ready"; }
65
67
  async allowOffline() {
@@ -67,11 +69,13 @@ export class InboxClient {
67
69
  if (!cursor?.initialized)
68
70
  throw new Error("INBOX_OFFLINE_CACHE_UNAVAILABLE");
69
71
  this.offlineAllowed = true;
72
+ this.enterOffline();
70
73
  this.publish({ ...this.progress, stage: "offline", percent: 100 });
71
74
  }
72
75
  async initialize() {
73
76
  if (this.options.live === false) {
74
- await this.synchronize();
77
+ if (!this.offlineAllowed)
78
+ await this.synchronize();
75
79
  return;
76
80
  }
77
81
  if (this.closed)
@@ -105,6 +109,7 @@ export class InboxClient {
105
109
  async catchUp() {
106
110
  if (isOffline())
107
111
  throw new Error("INBOX_OFFLINE");
112
+ const wasReady = this.progress.stage === "ready";
108
113
  let cursor = await this.store.cursor(), initial;
109
114
  if (cursor)
110
115
  initial = await this.request("check", { afterSeq: cursor.seq, epoch: cursor.epoch });
@@ -119,7 +124,8 @@ export class InboxClient {
119
124
  const page = await this.request("events", { afterSeq: cursor.seq, throughSeq: target.toString(), epoch: cursor.epoch });
120
125
  const previous = cursor.seq, applied = await this.store.apply(page);
121
126
  cursor = applied.cursor;
122
- this.notify(applied.threads);
127
+ if (cursor.seq !== previous)
128
+ this.notify(applied.threads);
123
129
  this.facts(page.events, previous);
124
130
  const processed = inboxSequence(cursor.seq) - start, total = target - start;
125
131
  this.publish({ stage: "syncing", percent: total === 0n ? 99 : Number(processed * 9900n / total) / 100, processed: processed.toString(), total: total.toString() });
@@ -133,15 +139,17 @@ export class InboxClient {
133
139
  do {
134
140
  const previous = cursor.seq, applied = await this.store.apply(page);
135
141
  cursor = applied.cursor;
136
- this.notify(applied.threads);
142
+ if (cursor.seq !== previous)
143
+ this.notify(applied.threads);
137
144
  this.facts(page.events, previous);
138
145
  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() });
146
+ if (total > 0n || !wasReady)
147
+ this.publish({ stage: "syncing", percent: total === 0n ? 99 : Number(processed * 9900n / total) / 100, processed: processed.toString(), total: total.toString() });
140
148
  if (inboxSequence(cursor.seq) >= target)
141
149
  break;
142
150
  page = await this.request("events", { afterSeq: cursor.seq, throughSeq: target.toString(), epoch: cursor.epoch });
143
151
  } while (!this.closed);
144
- if (!this.closed) {
152
+ if (!this.closed && (!wasReady || target > start)) {
145
153
  this.initializedOnce = true;
146
154
  this.publish({ stage: "ready", percent: 100, processed: (target - start).toString(), total: (target - start).toString() });
147
155
  this.notify([]);
@@ -206,7 +214,8 @@ export class InboxClient {
206
214
  try {
207
215
  const previous = (await this.store.cursor())?.seq ?? "0", applied = await this.store.apply(page);
208
216
  if (applied.threads.length)
209
- this.notify(applied.threads);
217
+ if (cursor.seq !== previous)
218
+ this.notify(applied.threads);
210
219
  this.facts(page.events, previous);
211
220
  }
212
221
  catch (error) {
@@ -162,6 +162,22 @@ export declare class IndexedDbInbox {
162
162
  serverCreatedAt: number;
163
163
  seq: number;
164
164
  }[]>;
165
+ conversationMessage(thread: string, teamId: string, id: string): Promise<{
166
+ sourceThreadId?: string;
167
+ threadId: string;
168
+ teamId?: string;
169
+ recalled: boolean;
170
+ body: any;
171
+ appId: string;
172
+ threadKind: "dm" | "group";
173
+ messageId: string;
174
+ from: string;
175
+ to: string;
176
+ recipients?: string[];
177
+ clientCreatedAt?: number;
178
+ serverCreatedAt: number;
179
+ seq: number;
180
+ } | undefined>;
165
181
  conversationChanges(thread: string, teamId: string, afterSeq: string, afterId?: string): Promise<{
166
182
  changeSeq: string;
167
183
  id: string;
@@ -214,8 +214,9 @@ export class IndexedDbInbox {
214
214
  thread.teamId = fact.value.teamId;
215
215
  }
216
216
  }
217
+ const windowStart = Math.max(cursor?.windowStart ?? 0, Date.now() - 180 * 24 * 60 * 60 * 1000);
217
218
  for (const row of rows) {
218
- if (row.acceptedAt < (cursor?.windowStart ?? 0))
219
+ if (row.acceptedAt < windowStart)
219
220
  continue;
220
221
  const thread = byThread.get(row.thread);
221
222
  if (!thread)
@@ -252,6 +253,19 @@ export class IndexedDbInbox {
252
253
  })).filter(row => row.teamId === teamId);
253
254
  return messages.sort((a, b) => a.serverCreatedAt - b.serverCreatedAt || (a.messageId < b.messageId ? -1 : a.messageId > b.messageId ? 1 : 0));
254
255
  }
256
+ async conversationMessage(thread, teamId, id) {
257
+ const assignments = (await this.facts.where("[owner+kind]").equals([this.owner, "threadAssigned"]).toArray()).filter(row => row.value.threadId === thread);
258
+ const sources = [thread, ...assignments.map(row => row.value.sourceThreadId)];
259
+ const rows = await this.messages.bulkGet(sources.map(source => [this.owner, source, id]));
260
+ for (const row of rows) {
261
+ if (!row)
262
+ continue;
263
+ const assignment = assignments.find(item => item.value.sourceThreadId === row.thread);
264
+ if ((assignment?.value.teamId ?? row.value.teamId) !== teamId)
265
+ continue;
266
+ return { ...row.value, recalled: row.recalled, body: this.annotatedBody(row), ...(assignment ? { sourceThreadId: row.thread, threadId: thread, teamId } : {}) };
267
+ }
268
+ }
255
269
  async conversationChanges(thread, teamId, afterSeq, afterId = "") {
256
270
  const assignments = (await this.facts.where("[owner+kind]").equals([this.owner, "threadAssigned"]).toArray()).filter(row => row.value.threadId === thread);
257
271
  const sources = [thread, ...assignments.map(row => row.value.sourceThreadId)];
@@ -50,9 +50,18 @@ export function inboxMessageTransport(inbox, team, root) {
50
50
  if (!valid(cursor, current) || await db.structureSequence(thread) > inboxSequence(cursor.seq))
51
51
  return { messages: [], checkpoint: encode(current), resetRequired: true };
52
52
  const changed = await db.conversationChanges(thread, team, cursor.seq, cursor.id ?? "\uffff");
53
- const selected = changed.slice(0, 100), hasMore = changed.length > selected.length, all = await rows(thread), byId = new Map(all.map(row => [row.messageId, row]));
53
+ const selected = changed.slice(0, 100), hasMore = changed.length > selected.length;
54
+ const messages = await Promise.all(selected.map(item => db.conversationMessage(thread, team, item.id)));
55
+ const visible = await Promise.all(messages.map(async (message) => {
56
+ if (!message)
57
+ return;
58
+ const content = message.body?.content, target = content?.reaction?.messageId ?? content?.recall?.messageId;
59
+ const targetMessage = typeof target === "string" ? await db.conversationMessage(thread, team, target) : undefined;
60
+ const selectedRoot = messageThreadRoot(message.body) ?? messageThreadRoot(targetMessage?.body);
61
+ return selectedRoot === root ? cached(message) : undefined;
62
+ }));
54
63
  const last = selected.at(-1);
55
- return { messages: selected.flatMap(item => { const message = byId.get(item.id); return message ? [cached(message)] : []; }), checkpoint: encode(hasMore && last ? { ...current, seq: BigInt(last.changeSeq).toString(), id: last.id } : current), hasMoreChanges: hasMore, resetRequired: false };
64
+ return { messages: visible.filter((message) => !!message), checkpoint: encode(hasMore && last ? { ...current, seq: BigInt(last.changeSeq).toString(), id: last.id } : current), hasMoreChanges: hasMore, resetRequired: false };
56
65
  }),
57
66
  older: (thread, before, signal) => read(async () => {
58
67
  signal.throwIfAborted();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pmate/chat-sdk",
3
- "version": "0.12.0-next.89",
3
+ "version": "0.12.0-next.90",
4
4
  "description": "Local-first chat SDK, message subscriptions, reading state, and shared chat UI primitives",
5
5
  "type": "module",
6
6
  "main": "./lib/index.js",