@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.
@@ -2,6 +2,40 @@ import { asChatError, ChatError } from "./chatError.js";
2
2
  import { isOffline, isOfflineNetworkFailure } from "./connectivity.js";
3
3
  import { IndexedDbResponseCache, isResponseCacheAuthorityError, assertResponseCacheAccess } from "./responseCache.js";
4
4
  import { messageScopeKey } from "./messageStore.js";
5
+ const requestId = () => crypto.randomUUID();
6
+ const safeId = (value) => value && /^[a-zA-Z0-9_.:@-]{1,128}$/.test(value) ? value : undefined;
7
+ // Error bodies are untrusted; never retain their text, scope, or arbitrary fields.
8
+ async function failureCode(response) {
9
+ if (response.bodyUsed || response.body?.locked)
10
+ return;
11
+ const reader = response.body?.getReader();
12
+ if (!reader)
13
+ return;
14
+ let timer;
15
+ try {
16
+ const deadline = new Promise((_, reject) => { timer = setTimeout(() => reject(new Error("READ_COUNTS_DIAGNOSTIC_TIMEOUT")), 250); });
17
+ let text = "", bytes = 0;
18
+ const decoder = new TextDecoder();
19
+ while (true) {
20
+ const part = await Promise.race([reader.read(), deadline]);
21
+ if (part.done)
22
+ break;
23
+ bytes += part.value.byteLength;
24
+ if (bytes > 4096)
25
+ return;
26
+ text += decoder.decode(part.value, { stream: true });
27
+ }
28
+ const code = JSON.parse(text + decoder.decode())?.message;
29
+ return typeof code === "string" && /^(SOCIAL_READ_(UNAVAILABLE|IDENTITY_UNAVAILABLE|FORBIDDEN)|INVALID_READ_COUNTS|UNAUTHORIZED|INVALID_SOCIAL_READ_IDENTITY|READ_RECEIVER_NOT_READY)$/.test(code) ? code : undefined;
30
+ }
31
+ catch {
32
+ return undefined;
33
+ }
34
+ finally {
35
+ clearTimeout(timer);
36
+ void reader.cancel().catch(() => { });
37
+ }
38
+ }
5
39
  let subscriptionSequence = 0;
6
40
  function nextSubscriptionSequence() { subscriptionSequence = Math.max(Date.now() * 1000, subscriptionSequence + 1); return subscriptionSequence; }
7
41
  /** One active conversation; fixed event window, bounded batches, no count polling. */
@@ -13,6 +47,7 @@ export class ReadCountsClient {
13
47
  heartbeat;
14
48
  controller;
15
49
  generation = 0;
50
+ operationId = requestId();
16
51
  retries = 0;
17
52
  closed = false;
18
53
  closing;
@@ -54,15 +89,29 @@ export class ReadCountsClient {
54
89
  }
55
90
  async post(path, body, signal) {
56
91
  const scopeVersion = this.options.access ? await assertResponseCacheAccess(this.options.access) : undefined;
57
- const response = await (this.options.fetch ?? fetch)(`${this.options.hubHttpUrl.replace(/\/$/, "")}${path}`, { method: "POST", headers: { authorization: `Bearer ${this.options.token}`, "content-type": "application/json" }, body: JSON.stringify(body), signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(8000)]) : AbortSignal.timeout(8000), redirect: "error" });
58
- if (!response.ok)
59
- throw Object.assign(new Error(`READ_COUNTS_HTTP_${response.status}`), { status: response.status });
60
- const envelope = await response.json();
61
- if (envelope.success !== true)
62
- throw new Error("INVALID_READ_COUNTS_RESPONSE");
63
- if (this.options.access)
64
- await assertResponseCacheAccess(this.options.access, scopeVersion);
65
- return envelope.data;
92
+ const clientRequestId = requestId(), started = performance.now();
93
+ const diagnostic = { source: "read-counts", route: path, method: "POST", operationId: this.operationId, clientRequestId, attempt: path.endsWith("/counts") ? this.retries + 1 : 1 };
94
+ try {
95
+ const response = await (this.options.fetch ?? fetch)(`${this.options.hubHttpUrl.replace(/\/$/, "")}${path}`, { method: "POST", headers: { authorization: `Bearer ${this.options.token}`, "content-type": "application/json", "x-request-id": clientRequestId }, body: JSON.stringify(body), signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(8000)]) : AbortSignal.timeout(8000), redirect: "error" });
96
+ diagnostic.status = response.status;
97
+ diagnostic.serverRequestId = safeId(response.headers.get("x-request-id"));
98
+ if (!response.ok) {
99
+ diagnostic.serverCode = await failureCode(response);
100
+ throw Object.assign(new Error(`READ_COUNTS_HTTP_${response.status}`), { status: response.status });
101
+ }
102
+ const envelope = await response.json();
103
+ if (envelope.success !== true)
104
+ throw new Error("INVALID_READ_COUNTS_RESPONSE");
105
+ diagnostic.durationMs = Math.round(performance.now() - started);
106
+ // Keep validation and retry behavior unchanged; add only transport diagnostics.
107
+ if (this.options.access)
108
+ await assertResponseCacheAccess(this.options.access, scopeVersion);
109
+ return envelope.data;
110
+ }
111
+ catch (error) {
112
+ diagnostic.durationMs = Math.round(performance.now() - started);
113
+ throw Object.assign(error instanceof Error ? error : new Error("READ_COUNTS_REQUEST_FAILED"), { diagnostic });
114
+ }
66
115
  }
67
116
  subscription(threadId, release) {
68
117
  if (release && isOffline())
@@ -126,6 +175,7 @@ export class ReadCountsClient {
126
175
  return;
127
176
  }
128
177
  const old = this.thread;
178
+ this.operationId = requestId();
129
179
  this.generation++;
130
180
  this.controller?.abort();
131
181
  clearTimeout(this.timer);
@@ -1,5 +1,7 @@
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;
@@ -15,9 +17,13 @@ export declare class ReadSyncClient {
15
17
  private readonly controller;
16
18
  private inFlight?;
17
19
  private readAfter;
20
+ private inboxApplying?;
21
+ private inboxDirty;
18
22
  constructor(options: ReadSyncOptions);
19
23
  loadLocal(): Promise<ReadIndexState>;
20
24
  stop(): void;
25
+ applyInboxLocal(): Promise<ReadIndexState>;
26
+ private installInboxLocal;
21
27
  synchronize(): Promise<ReadIndexState>;
22
28
  private request;
23
29
  private repairLegacyDiscussion;
@@ -5,10 +5,14 @@ export class ReadSyncClient {
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() {
14
+ if (this.options.inbox)
15
+ return this.applyInboxLocal();
12
16
  const { appId, profileId, persistence, metadataOnly } = this.options;
13
17
  const state = await persistence.load(appId, profileId) ?? createReadIndex(appId, profileId);
14
18
  const normalize = (current) => {
@@ -20,6 +24,37 @@ export class ReadSyncClient {
20
24
  return persistence.update(appId, profileId, normalize);
21
25
  }
22
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
+ }
23
58
  synchronize() {
24
59
  if (this.inFlight)
25
60
  return this.inFlight;
@@ -60,7 +95,7 @@ export class ReadSyncClient {
60
95
  return false;
61
96
  const { appId, profileId, persistence } = this.options;
62
97
  const query = new URLSearchParams({ appId, profileId, ...(this.options.metadataOnly ? { metadataOnly: "true" } : {}) });
63
- const snapshot = await this.request(`/api/social/reading/snapshot?${query}`);
98
+ const snapshot = this.options.inbox ? await this.options.inbox.store.readingSnapshot() : await this.request(`/api/social/reading/snapshot?${query}`);
64
99
  // Validate the complete response before changing any durable operation.
65
100
  installReadSnapshot(createReadIndex(appId, profileId), snapshot);
66
101
  const thread = snapshot.threads.find(thread => thread.id === operation.threadId);
@@ -91,6 +126,8 @@ export class ReadSyncClient {
91
126
  return repaired;
92
127
  }
93
128
  async run(repairedLegacy = false) {
129
+ if (this.options.inbox?.offlineMode())
130
+ return this.applyInboxLocal();
94
131
  const { appId, profileId, persistence } = this.options;
95
132
  const loaded = persistence.loadVersioned ? await persistence.loadVersioned(appId, profileId) : { state: await persistence.load(appId, profileId), versions: {} };
96
133
  const current = loaded.state ?? createReadIndex(appId, profileId);
@@ -129,6 +166,10 @@ export class ReadSyncClient {
129
166
  throw new Error("INVALID_READING_RECEIPT");
130
167
  this.readAfter = Math.max(this.readAfter, receipt.acceptedAt);
131
168
  }
169
+ if (this.options.inbox) {
170
+ await this.options.inbox.synchronize();
171
+ return this.applyInboxLocal();
172
+ }
132
173
  const query = new URLSearchParams({ appId, profileId });
133
174
  if (this.options.metadataOnly)
134
175
  query.set("metadataOnly", "true");
@@ -1,6 +1,8 @@
1
1
  import { type ConversationReadMessage } from "./conversationRead.js";
2
2
  import { type ReadIndexPersistence, type ReadIndexState } from "./readIndex.js";
3
+ import type { InboxClient } from "./inboxClient.js";
3
4
  export type ReadingClientOptions = {
5
+ inbox?: InboxClient;
4
6
  appId: string;
5
7
  profileId: string;
6
8
  sessionToken: string;
@@ -34,6 +36,7 @@ export declare class ReadingClient {
34
36
  private retry?;
35
37
  private retryDelay;
36
38
  private offWake?;
39
+ private offInbox?;
37
40
  private generation;
38
41
  constructor(options: ReadingClientOptions);
39
42
  getSnapshot: () => ReadIndexState | undefined;
@@ -25,6 +25,7 @@ export class ReadingClient {
25
25
  retry;
26
26
  retryDelay = 1000;
27
27
  offWake;
28
+ offInbox;
28
29
  generation = 0;
29
30
  constructor(options) {
30
31
  this.options = options;
@@ -35,6 +36,12 @@ export class ReadingClient {
35
36
  this.persistence = new BatchedReadIndex(storage);
36
37
  this.tasks = new WindowedTasks(1000, error => this.failed(error));
37
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
+ });
38
45
  }
39
46
  getSnapshot = () => this.state;
40
47
  subscribe = (listener) => { this.listeners.add(listener); return () => { this.listeners.delete(listener); }; };
@@ -65,10 +72,11 @@ export class ReadingClient {
65
72
  window.addEventListener("focus", wake);
66
73
  this.offWake = () => { window.removeEventListener("online", wake); window.removeEventListener("focus", wake); };
67
74
  }
68
- this.refresh();
75
+ if (!this.options.inbox || this.state?.pending.length)
76
+ this.refresh();
69
77
  }
70
78
  refresh = () => {
71
- if (!this.closed && !isOffline())
79
+ if (!this.closed && !isOffline() && !this.options.inbox?.offlineMode())
72
80
  this.tasks.schedule("reading", async () => { if (!isOffline())
73
81
  await this.synchronize(); });
74
82
  };
@@ -180,6 +188,7 @@ export class ReadingClient {
180
188
  this.closed = true;
181
189
  this.generation++;
182
190
  this.offWake?.();
191
+ this.offInbox?.();
183
192
  this.tasks.close();
184
193
  clearTimeout(this.retry);
185
194
  this.sync.stop();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pmate/chat-sdk",
3
- "version": "0.12.0-next.87",
3
+ "version": "0.12.0-next.89",
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",