@pmate/chat-sdk 0.12.0-next.2 → 0.12.0-next.20

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 CHANGED
@@ -137,6 +137,52 @@ sends and reading synchronization independently. The runtime now provides local
137
137
  IndexedDB storage and fixed-window scheduling primitives so those operations can
138
138
  share bounded I/O, durable confirmation and scoped subscriptions.
139
139
 
140
+ The browser entry point is `createChat` from `@pmate/chat-sdk/runtime`:
141
+
142
+ ```ts
143
+ const chat = createChat({ appId, accountId, profileId, teamId, token, onError })
144
+ await chat.start()
145
+ const page = await chat.getMessages(threadId)
146
+ // SDK owns the page size and history boundary; hosts need not construct a cursor.
147
+ const earlier = await chat.getMessages(threadId, { earlier: true })
148
+ // After an authoritative mutation (e.g. history assignment), await reconciliation.
149
+ // Concurrent refreshes share transport; errors do not masquerade as fresh cache.
150
+ const reconciled = await chat.getMessages(threadId, { refresh: true })
151
+ // Explicit full-history queries reuse cached pages and internally rebase expired cursors.
152
+ const history = await chat.getMessages(threadId, { all: true })
153
+ const off = chat.subscribe(threadId, () => render(chat.getSnapshot(threadId)))
154
+ const offSummary = chat.subscribe(() => renderSummary(chat.getSnapshot()))
155
+ await chat.observeMessages(threadId, visibleIds, "visible")
156
+ // Report only the actual audio `playing` event.
157
+ await chat.observeMessages(threadId, [voiceId], "played")
158
+ await chat.sendMessage(threadId, { to, body, recipients })
159
+ const readers = await chat.getReaders(threadId, messageId)
160
+ off(); offSummary()
161
+ await chat.close()
162
+ ```
163
+
164
+ The facade owns all clients below. Message reads transparently restore IndexedDB
165
+ windows and fetch missing ranges through the authenticated Hub. Its normalized
166
+ messages retain the protocol body; product rendering remains with the host.
167
+ `sendMessage` resolves after local persistence, while `outgoing` in the thread
168
+ snapshot reports transport progress and failure. Retry uses the original message
169
+ hash. The subscribed recent window remains 100 records regardless of individual
170
+ query limits; history requests return their own pages and do not replace it.
171
+ Global snapshots contain thread summaries and totals, not complete message arrays.
172
+ Message pages report `complete`; unavailable older pages return cached records with
173
+ `complete: false`. Authorization failures throw and never fall back to denied
174
+ records. Thread snapshots expose `resetVersion`; hosts discard retained rows when
175
+ it changes. Reset epochs are durable, so late cross-tab writes cannot restore a
176
+ pre-reset payload.
177
+ Voice visibility never acknowledges playback, including observations that arrive
178
+ before metadata. Create a new instance and close the previous owner when the
179
+ account or active Team changes.
180
+
181
+ This facade is still under integration. Reader details currently require network
182
+ access, global summaries do not yet replace the host's contact/thread metadata,
183
+ and Merry's message-list/send migration and production validation are unfinished.
184
+ The lower-level primitives remain available for custom transports:
185
+
140
186
  `MessageClient` reads a trusted recent window locally, coalesces concurrent misses,
141
187
  subscribes per conversation, and accepts incremental event batches. Its transport
142
188
  supplies authoritative `load`, `changes` and `older` pages. `nextBefore` tracks
@@ -157,6 +203,11 @@ legacy cleanup happens after durable migration. Normal reads use memory and writ
157
203
  are merged into bounded IndexedDB transactions. Cache errors must be surfaced by
158
204
  the host, and pending operations are not reported as saved before their promise
159
205
  resolves.
206
+ Control-event batches are bounded by both 128 records and 1 MiB per transaction;
207
+ the queue includes in-flight writes and is limited to 4096 records / 8 MiB.
208
+ `transactionBytes` and `queueBytes` can lower these limits. Oversized operations
209
+ fail before changing the memory snapshot. Repeating an in-flight write waits for
210
+ that physical write, including its failure, rather than acknowledging it early.
160
211
 
161
212
  `DurableChatSender` saves the exact message created by `ChatClient.prepareChat`
162
213
  before transmitting it. `retry(hash)` uses `sendPrepared` with the original hash
@@ -165,7 +216,7 @@ when the connection returns. Call `confirm(hashes)` only after authoritative
165
216
  messages have been durably merged. Confirmation tombstones prevent another tab's
166
217
  late transport failure from recreating an outgoing message.
167
218
 
168
- These APIs are runtime primitives; applications must initialize them with the
169
- same authenticated scope, dispose them on identity changes, and wire their
170
- transport to an authorized server. The Merry migration and production validation
219
+ Custom primitive integrations must initialize them with the same authenticated
220
+ scope, dispose them on identity changes, and wire their transport to an authorized
221
+ server. Standard browser integrations should use the facade instead. The Merry migration and production validation
171
222
  are tracked in the unified message layer proposal.
@@ -56,6 +56,14 @@ export declare class ChatClient {
56
56
  private initialize;
57
57
  close(): void;
58
58
  connectionState(): ChatConnectionState;
59
+ /** Non-secret identity used to validate a shared browser transport. */
60
+ identityScope(): {
61
+ appId: string;
62
+ profileId: string | undefined;
63
+ accountId: string | undefined;
64
+ teamId: string | undefined;
65
+ clientInstanceId: string;
66
+ };
59
67
  watchConnection(handler: (state: ChatConnectionState) => void): () => void;
60
68
  private setConnection;
61
69
  private rejectPending;
@@ -120,6 +120,11 @@ export class ChatClient {
120
120
  this.rejectPending(new Error("ChatClient closed"));
121
121
  }
122
122
  connectionState() { return this.connection; }
123
+ /** Non-secret identity used to validate a shared browser transport. */
124
+ identityScope() {
125
+ const identity = this.session?.identity ?? this.session?.session?.identity;
126
+ return { appId: this.options.appId, profileId: this.profileIdValue ?? this.options.profileId, accountId: identity?.accountId, teamId: this.options.teamId, clientInstanceId: this.instanceId };
127
+ }
123
128
  watchConnection(handler) {
124
129
  this.connectionHandlers.add(handler);
125
130
  handler(this.connection);
@@ -423,10 +428,11 @@ export class ChatClient {
423
428
  return profileId;
424
429
  }
425
430
  profileId() {
426
- if (!this.profileIdValue) {
431
+ const profileId = this.profileIdValue ?? this.options.profileId;
432
+ if (!profileId) {
427
433
  throw new Error("ChatClient is missing profile id; call connect() first");
428
434
  }
429
- return this.profileIdValue;
435
+ return profileId;
430
436
  }
431
437
  async fetchProfiles(appId, accountId, token) {
432
438
  const fetcher = this.options.fetchImpl ?? fetch;
@@ -1,14 +1,19 @@
1
+ import type { ConversationReadMessage } from "./conversationRead.js";
2
+ import { type ReadCountsResult } from "./readCounts.js";
3
+ import type { OnlineReachEvent } from "./reach.js";
1
4
  import { type MessageReadersQuery } from "./messageReaders.js";
2
- import { type MessageClientOptions } from "./messageClient.js";
5
+ import { type MessageClientOptions, type MessageSnapshot } from "./messageClient.js";
3
6
  import { DurableChatSender } from "./durableSender.js";
4
- import { type ReadingClientOptions } from "./readingClient.js";
5
- import { type ChatClientOptions } from "./chatClient.js";
7
+ import { ReadingClient, type ReadingClientOptions } from "./readingClient.js";
8
+ import { ChatClient, type ChatClientOptions, type ChatConnectionState } from "./chatClient.js";
6
9
  import { unreadInConversation } from "./readIndex.js";
7
10
  import type { StoredMessage } from "./messageStore.js";
8
11
  import type { ChatBody, ChatRuntimeMessage } from "./protocol.js";
9
12
  export type ChatSessionOptions<T extends StoredMessage> = {
10
13
  messages: MessageClientOptions<T>;
11
14
  connection: ChatClientOptions;
15
+ sharedConnection?: ChatClient;
16
+ activeThreadId?: string;
12
17
  reading: ReadingClientOptions;
13
18
  decode: (message: ChatRuntimeMessage) => T | undefined;
14
19
  onError: (error: unknown) => void;
@@ -17,7 +22,21 @@ export type ChatThreadSnapshot<T> = {
17
22
  messages: readonly T[];
18
23
  outgoing: ReturnType<DurableChatSender["snapshot"]>;
19
24
  hasEarlier: boolean;
20
- unread: ReturnType<typeof unreadInConversation>;
25
+ resetVersion: number;
26
+ complete: boolean;
27
+ readCounts?: ReadCountsResult;
28
+ unread: ReturnType<typeof unreadInConversation> | undefined;
29
+ };
30
+ export type ChatSummarySnapshot<T> = {
31
+ threads: readonly {
32
+ threadId: string;
33
+ lastMessage?: T;
34
+ unread: ChatThreadSnapshot<T>["unread"];
35
+ outgoingCount: number;
36
+ }[];
37
+ unreadMessageCount: number | undefined;
38
+ badgeCount: number | undefined;
39
+ connection: ChatConnectionState;
21
40
  };
22
41
  /** Owns all browser message clients. Hosts subscribe to stable thread snapshots. */
23
42
  export declare class ChatSession<T extends StoredMessage> {
@@ -26,15 +45,41 @@ export declare class ChatSession<T extends StoredMessage> {
26
45
  private connection;
27
46
  private reading;
28
47
  private readers;
48
+ private counts?;
49
+ private countsReceiver?;
50
+ private countsThread?;
51
+ private countSnapshots;
52
+ private countClosings;
53
+ private countTasks;
29
54
  private sender;
30
55
  private listeners;
31
56
  private snapshots;
57
+ private historyEdges;
58
+ private earlierReads;
32
59
  private off;
60
+ private globalListeners;
61
+ private globalSnapshot?;
62
+ private connectionState;
63
+ private catchUp;
64
+ private readingStarted;
33
65
  private closed;
34
66
  private starting?;
67
+ private initializing?;
35
68
  private closing?;
36
69
  constructor(options: ChatSessionOptions<T>);
37
70
  start(): Promise<void>;
71
+ /** Initializes local state and background reading sync without opening a
72
+ * second transport when the host already owns calls/presence. */
73
+ initialize(): Promise<void>;
74
+ /** One-time migration only: never establishes trusted history coverage. */
75
+ importLegacyMessages(threadId: string, messages: T[]): Promise<void>;
76
+ getReadingSnapshot(): import("./readIndex.js").ReadIndexState | undefined;
77
+ subscribeReading(listener: () => void): () => void;
78
+ refreshReading(): void;
79
+ synchronizeReading(cursor?: string, profileId?: string): Promise<import("./readIndex.js").ReadIndexState>;
80
+ /** Explicit text-history acknowledgement; unheard audio stays unread. */
81
+ markRead(threadId: string, messages?: readonly ConversationReadMessage[]): Promise<import("./readIndex.js").ReadIndexState>;
82
+ updateReading(transform: Parameters<ReadingClient["update"]>[0]): Promise<import("./readIndex.js").ReadIndexState>;
38
83
  private assertOpen;
39
84
  getMessages(threadId: string, options?: {
40
85
  limit?: number;
@@ -42,7 +87,13 @@ export declare class ChatSession<T extends StoredMessage> {
42
87
  timestamp: number;
43
88
  id: string;
44
89
  };
45
- }): Promise<import("./messageClient.js").MessageSnapshot<T>>;
90
+ earlier?: boolean;
91
+ all?: boolean;
92
+ refresh?: boolean;
93
+ }): Promise<MessageSnapshot<T>>;
94
+ private rememberHistoryEdge;
95
+ private readEarlier;
96
+ private readAll;
46
97
  sendMessage(threadId: string, input: {
47
98
  to: string;
48
99
  body: ChatBody;
@@ -50,10 +101,21 @@ export declare class ChatSession<T extends StoredMessage> {
50
101
  }): Promise<ChatRuntimeMessage>;
51
102
  getReaders(threadId: string, messageId: string, page?: Omit<MessageReadersQuery, "threadId" | "messageId">, signal?: AbortSignal): Promise<import("./messageReaders.js").MessageReadersPage>;
52
103
  retryMessage(messageId: string): Promise<ChatRuntimeMessage>;
53
- observeMessages(threadId: string, ids: string[], event: "visible" | "played"): Promise<import("./readIndex.js").ReadIndexState>;
104
+ observeMessages(threadId: string, ids: string[], event: "visible" | "played"): ReturnType<ReadingClient["recordVisible"]>;
105
+ observeMessages(threadId: string | undefined, ids: string[], event: "receipts", clientInstanceId?: string): Promise<void>;
106
+ /** Bridge transports can delegate social events without maintaining clients. */
107
+ handleReach(event: OnlineReachEvent): Promise<"handled" | undefined>;
108
+ private wakeCounts;
109
+ private publishCountSnapshot;
110
+ private publishCounts;
111
+ private watchCounts;
112
+ getSnapshot(): ChatSummarySnapshot<T>;
54
113
  getSnapshot(threadId: string): ChatThreadSnapshot<T>;
55
- subscribe(threadId: string, listener: () => void): () => void;
114
+ subscribe(listener: () => void): () => void;
115
+ subscribe(threadId: string, listener: () => void, fields?: readonly (keyof ChatThreadSnapshot<T>)[]): () => void;
56
116
  private publishAll;
117
+ private buildGlobal;
118
+ private publishGlobal;
57
119
  private publish;
58
120
  close(): Promise<void>;
59
121
  }