@pmate/chat-sdk 0.12.0-next.8 → 0.12.0-next.81

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.
Files changed (111) hide show
  1. package/README.md +170 -83
  2. package/lib/advanced.d.ts +10 -0
  3. package/lib/advanced.js +10 -0
  4. package/lib/chat.d.ts +5 -0
  5. package/lib/chat.js +11 -0
  6. package/lib/chatContract.d.ts +151 -0
  7. package/lib/chatContract.js +1 -0
  8. package/lib/chatError.d.ts +14 -0
  9. package/lib/chatError.js +16 -0
  10. package/lib/chatTypes.d.ts +127 -0
  11. package/lib/chatTypes.js +1 -0
  12. package/lib/commands.d.ts +20 -0
  13. package/lib/commands.js +12 -0
  14. package/lib/components/ChatInputDesktop.js +5 -4
  15. package/lib/components/ChatInputMobile.js +5 -4
  16. package/lib/components/CommandMenu.d.ts +15 -0
  17. package/lib/components/CommandMenu.js +10 -0
  18. package/lib/credentials.d.ts +26 -0
  19. package/lib/credentials.js +110 -0
  20. package/lib/fileMetadata.d.ts +9 -0
  21. package/lib/fileMetadata.js +18 -0
  22. package/lib/framework.d.ts +11 -0
  23. package/lib/framework.js +12 -0
  24. package/lib/history.d.ts +4 -0
  25. package/lib/history.js +8 -0
  26. package/lib/hooks/useChatSnapshot.d.ts +4 -0
  27. package/lib/hooks/useChatSnapshot.js +9 -0
  28. package/lib/hooks/useComposerSuggestions.d.ts +50 -0
  29. package/lib/hooks/useComposerSuggestions.js +70 -0
  30. package/lib/index.d.ts +5 -0
  31. package/lib/index.js +5 -0
  32. package/lib/internal/chatEngine.d.ts +130 -0
  33. package/lib/internal/chatEngine.js +284 -0
  34. package/lib/internal/chatRegistry.d.ts +4 -0
  35. package/lib/internal/chatRegistry.js +4 -0
  36. package/lib/internal/createPublicChat.d.ts +4 -0
  37. package/lib/internal/createPublicChat.js +52 -0
  38. package/lib/messageView.d.ts +6 -0
  39. package/lib/messageView.js +103 -0
  40. package/lib/runtime/batchedReadIndex.d.ts +16 -3
  41. package/lib/runtime/batchedReadIndex.js +50 -4
  42. package/lib/runtime/cachedMessage.d.ts +12 -0
  43. package/lib/runtime/cachedMessage.js +18 -0
  44. package/lib/runtime/chatClient.d.ts +7 -0
  45. package/lib/runtime/chatClient.js +14 -3
  46. package/lib/runtime/chatError.d.ts +5 -0
  47. package/lib/runtime/chatError.js +20 -0
  48. package/lib/runtime/chatSession.d.ts +128 -13
  49. package/lib/runtime/chatSession.js +759 -48
  50. package/lib/runtime/connectivity.d.ts +4 -0
  51. package/lib/runtime/connectivity.js +8 -0
  52. package/lib/runtime/conversationDirectory.d.ts +37 -0
  53. package/lib/runtime/conversationDirectory.js +116 -0
  54. package/lib/runtime/conversationRead.d.ts +13 -0
  55. package/lib/runtime/conversationRead.js +34 -0
  56. package/lib/runtime/conversationReading.d.ts +28 -0
  57. package/lib/runtime/conversationReading.js +47 -0
  58. package/lib/runtime/createChat.d.ts +11 -7
  59. package/lib/runtime/createChat.js +46 -23
  60. package/lib/runtime/durableSender.d.ts +97 -14
  61. package/lib/runtime/durableSender.js +786 -71
  62. package/lib/runtime/groupClient.d.ts +91 -0
  63. package/lib/runtime/groupClient.js +380 -0
  64. package/lib/runtime/groupDenial.d.ts +2 -0
  65. package/lib/runtime/groupDenial.js +4 -0
  66. package/lib/runtime/index.d.ts +7 -0
  67. package/lib/runtime/index.js +5 -0
  68. package/lib/runtime/indexedDbRecovery.d.ts +4 -0
  69. package/lib/runtime/indexedDbRecovery.js +27 -0
  70. package/lib/runtime/messageClient.d.ts +35 -8
  71. package/lib/runtime/messageClient.js +364 -66
  72. package/lib/runtime/messageControls.d.ts +19 -0
  73. package/lib/runtime/messageControls.js +44 -0
  74. package/lib/runtime/messageLaunch.d.ts +44 -0
  75. package/lib/runtime/messageLaunch.js +137 -0
  76. package/lib/runtime/messageQuotes.d.ts +3 -0
  77. package/lib/runtime/messageQuotes.js +17 -0
  78. package/lib/runtime/messageReaders.d.ts +5 -1
  79. package/lib/runtime/messageReaders.js +16 -5
  80. package/lib/runtime/messageStore.d.ts +43 -2
  81. package/lib/runtime/messageStore.js +248 -14
  82. package/lib/runtime/messageTimeline.d.ts +50 -0
  83. package/lib/runtime/messageTimeline.js +120 -0
  84. package/lib/runtime/outboxSchema.d.ts +5 -0
  85. package/lib/runtime/outboxSchema.js +59 -0
  86. package/lib/runtime/outgoingContent.d.ts +94 -0
  87. package/lib/runtime/outgoingContent.js +118 -0
  88. package/lib/runtime/readBatchJournal.d.ts +35 -0
  89. package/lib/runtime/readBatchJournal.js +210 -0
  90. package/lib/runtime/readCounts.d.ts +15 -1
  91. package/lib/runtime/readCounts.js +97 -9
  92. package/lib/runtime/readIndex.d.ts +68 -7
  93. package/lib/runtime/readIndex.js +460 -22
  94. package/lib/runtime/readSchema.d.ts +2 -0
  95. package/lib/runtime/readSchema.js +58 -0
  96. package/lib/runtime/readSync.d.ts +1 -0
  97. package/lib/runtime/readSync.js +26 -9
  98. package/lib/runtime/readingClient.d.ts +19 -0
  99. package/lib/runtime/readingClient.js +131 -19
  100. package/lib/runtime/readingContent.d.ts +5 -0
  101. package/lib/runtime/readingContent.js +23 -0
  102. package/lib/runtime/responseCache.d.ts +40 -5
  103. package/lib/runtime/responseCache.js +182 -44
  104. package/lib/runtime/socialReadClient.d.ts +9 -4
  105. package/lib/runtime/socialReadClient.js +12 -8
  106. package/lib/runtime/voiceUpload.d.ts +2 -0
  107. package/lib/runtime/voiceUpload.js +27 -0
  108. package/lib/snapshot.d.ts +36 -0
  109. package/lib/snapshot.js +52 -0
  110. package/lib/types/chatInput.d.ts +3 -0
  111. package/package.json +32 -2
@@ -1,4 +1,4 @@
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;
@@ -9,8 +9,15 @@ export class ReadSyncClient {
9
9
  this.options = options;
10
10
  }
11
11
  async loadLocal() {
12
- return await this.options.persistence.load(this.options.appId, this.options.profileId)
13
- ?? createReadIndex(this.options.appId, this.options.profileId);
12
+ const { appId, profileId, persistence, metadataOnly } = this.options;
13
+ const state = await persistence.load(appId, profileId) ?? createReadIndex(appId, profileId);
14
+ const normalize = (current) => {
15
+ const next = metadataOnly ? readingMetadata(current) : current;
16
+ return next.observedReadIntents?.length ? resolveObservedReads(next) : next;
17
+ };
18
+ if (normalize(state) === state)
19
+ return state;
20
+ return persistence.update(appId, profileId, normalize);
14
21
  }
15
22
  stop() { this.controller.abort(); }
16
23
  synchronize() {
@@ -33,7 +40,7 @@ export class ReadSyncClient {
33
40
  ...init, signal: timeout.signal, headers: { ...init.headers, authorization: `Bearer ${this.options.sessionToken}` },
34
41
  });
35
42
  if (!response.ok)
36
- throw new Error(`READ_SYNC_HTTP_${response.status}`);
43
+ throw Object.assign(new Error(`READ_SYNC_HTTP_${response.status}`), { status: response.status });
37
44
  const envelope = await response.json();
38
45
  if (envelope.success !== true || envelope.data === undefined)
39
46
  throw new Error("INVALID_READ_SYNC_RESPONSE");
@@ -46,7 +53,9 @@ export class ReadSyncClient {
46
53
  }
47
54
  async run() {
48
55
  const { appId, profileId, persistence } = this.options;
49
- const current = await this.loadLocal();
56
+ const loaded = persistence.loadVersioned ? await persistence.loadVersioned(appId, profileId) : { state: await persistence.load(appId, profileId), versions: {} };
57
+ const current = loaded.state ?? createReadIndex(appId, profileId);
58
+ const versions = loaded.versions;
50
59
  // Ordinary reads are monotonic: only the furthest position per thread needs
51
60
  // sending. Keep every original operation in storage until the projection
52
61
  // confirms it, and never rewrite an operation ID's payload during retries.
@@ -60,6 +69,8 @@ export class ReadSyncClient {
60
69
  }
61
70
  const outgoing = current.pending.filter(operation => operation.explicitReadMessageIds.length || operation.readThroughSeq <= 0 || latest.get(operation.threadId) === operation);
62
71
  for (const operation of outgoing) {
72
+ if (persistence.loadVersions)
73
+ assertReadIndexVersions(versions, await persistence.loadVersions(appId, profileId));
63
74
  const receipt = await this.request("/api/social/reading", {
64
75
  method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ ...operation, appId, profileId }),
65
76
  });
@@ -69,8 +80,10 @@ export class ReadSyncClient {
69
80
  this.readAfter = Math.max(this.readAfter, receipt.acceptedAt);
70
81
  }
71
82
  const query = new URLSearchParams({ appId, profileId });
83
+ if (this.options.metadataOnly)
84
+ query.set("metadataOnly", "true");
72
85
  if (!this.readAfter && current.syncCursor !== "0") {
73
- const delta = await this.request(`/api/social/reading/changes?${new URLSearchParams({ appId, profileId, after: current.syncCursor })}`);
86
+ const delta = await this.request(`/api/social/reading/changes?${new URLSearchParams({ appId, profileId, after: current.syncCursor, ...(this.options.metadataOnly ? { metadataOnly: "true" } : {}) })}`);
74
87
  if (delta.appId !== appId || delta.profileId !== profileId || typeof delta.syncCursor !== "string"
75
88
  || typeof delta.snapshotRequired !== "boolean" || !Array.isArray(delta.changes))
76
89
  throw new Error("INVALID_READ_DELTA");
@@ -78,8 +91,9 @@ export class ReadSyncClient {
78
91
  try {
79
92
  if (this.controller.signal.aborted)
80
93
  throw new Error("READ_SYNC_STOPPED");
81
- const next = await persistence.update(appId, profileId, state => {
82
- const applied = delta.changes.reduce(applyReadChange, state);
94
+ const next = await persistence.update(appId, profileId, (state, currentVersions) => {
95
+ assertReadIndexVersions(versions, currentVersions);
96
+ 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
97
  if (applied.syncCursor !== delta.syncCursor)
84
98
  throw new ReadSyncGap(applied.syncCursor);
85
99
  return applied;
@@ -100,7 +114,10 @@ export class ReadSyncClient {
100
114
  if (this.controller.signal.aborted)
101
115
  throw new Error("READ_SYNC_STOPPED");
102
116
  // Merge into the latest transaction, including reads made while HTTP was pending.
103
- const next = await persistence.update(appId, profileId, state => installReadSnapshot(state, snapshot));
117
+ const next = await persistence.update(appId, profileId, (state, currentVersions) => {
118
+ assertReadIndexVersions(versions, currentVersions);
119
+ return installReadSnapshot(state, this.options.metadataOnly ? readingMetadata(snapshot) : snapshot);
120
+ });
104
121
  if (!next.pending.length)
105
122
  this.readAfter = 0;
106
123
  if (!this.controller.signal.aborted)
@@ -1,11 +1,15 @@
1
+ import { type ConversationReadMessage } from "./conversationRead.js";
1
2
  import { type ReadIndexPersistence, type ReadIndexState } from "./readIndex.js";
2
3
  export type ReadingClientOptions = {
3
4
  appId: string;
4
5
  profileId: string;
5
6
  sessionToken: string;
6
7
  hubHttpUrl: string;
8
+ teamId?: string;
9
+ metadataOnly?: boolean;
7
10
  persistence?: ReadIndexPersistence;
8
11
  storageScope?: string;
12
+ migrateLegacy?: boolean;
9
13
  fetch?: typeof fetch;
10
14
  onError?: (error: unknown) => void;
11
15
  onRecovered?: () => void;
@@ -15,6 +19,12 @@ export type ReadingClientOptions = {
15
19
  export declare class ReadingClient {
16
20
  private options;
17
21
  private storage;
22
+ private backing;
23
+ private closing?;
24
+ private revoking?;
25
+ private versions?;
26
+ private prepared;
27
+ private accepted;
18
28
  private persistence;
19
29
  private sync;
20
30
  private tasks;
@@ -34,8 +44,17 @@ export declare class ReadingClient {
34
44
  refresh: () => void;
35
45
  synchronize(targetCursor?: string, profileId?: string): Promise<ReadIndexState>;
36
46
  update(transform: (state: ReadIndexState) => ReadIndexState): Promise<ReadIndexState>;
47
+ private updateScoped;
48
+ prepareTeam(teamId: string, version: number): Promise<void>;
49
+ private assertThreadTeam;
50
+ markRead(threadId: string, messages?: readonly ConversationReadMessage[]): Promise<ReadIndexState>;
37
51
  recordVisible(threadId: string, messageIds: string[]): Promise<ReadIndexState>;
38
52
  recordExplicit(threadId: string, messageIds: string[]): Promise<ReadIndexState>;
39
53
  private record;
54
+ withdraw(): void;
55
+ private stop;
56
+ /** This client is retired permanently. Drain accepted local observations
57
+ * before deleting one team's profile-wide projection; sibling teams survive. */
58
+ revokeTeam(teamId: string, version: number, knownThreadIds?: readonly string[]): Promise<void>;
40
59
  close(): Promise<void>;
41
60
  }
@@ -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;
@@ -19,7 +28,10 @@ export class ReadingClient {
19
28
  generation = 0;
20
29
  constructor(options) {
21
30
  this.options = options;
22
- const storage = options.persistence ?? (this.storage = new IndexedDbReadIndex(globalThis.indexedDB, "pmate-social-read-index", options.storageScope));
31
+ if (options.teamId !== undefined && !isValidChatTeamId(options.teamId))
32
+ throw new Error("INVALID_READ_TEAM");
33
+ const storage = options.persistence ?? (this.storage = new IndexedDbReadIndex(globalThis.indexedDB, "pmate-social-read-index", options.storageScope, options.migrateLegacy, options.metadataOnly));
34
+ this.backing = storage;
23
35
  this.persistence = new BatchedReadIndex(storage);
24
36
  this.tasks = new WindowedTasks(1000, error => this.failed(error));
25
37
  this.sync = new ReadSyncClient({ ...options, persistence: this.persistence, onChange: state => this.publish(state) });
@@ -27,13 +39,13 @@ export class ReadingClient {
27
39
  getSnapshot = () => this.state;
28
40
  subscribe = (listener) => { this.listeners.add(listener); return () => { this.listeners.delete(listener); }; };
29
41
  publish(state) {
30
- if (this.closed || JSON.stringify(state) === JSON.stringify(this.state))
42
+ if (this.closed || state === this.state || JSON.stringify(state) === JSON.stringify(this.state))
31
43
  return;
32
44
  this.state = state;
33
45
  this.listeners.forEach(listener => listener());
34
46
  }
35
47
  failed(error) {
36
- if (this.closed)
48
+ if (this.closed || isOfflineNetworkFailure(error))
37
49
  return;
38
50
  this.options.onError?.(error);
39
51
  if (/HTTP_(400|401|403)/.test(String(error)) || (typeof navigator !== "undefined" && !navigator.onLine) || this.retry)
@@ -56,8 +68,9 @@ export class ReadingClient {
56
68
  this.refresh();
57
69
  }
58
70
  refresh = () => {
59
- if (!this.closed)
60
- this.tasks.schedule("reading", async () => { await this.synchronize(); });
71
+ if (!this.closed && !isOffline())
72
+ this.tasks.schedule("reading", async () => { if (!isOffline())
73
+ await this.synchronize(); });
61
74
  };
62
75
  async synchronize(targetCursor, profileId) {
63
76
  if (this.closed)
@@ -84,32 +97,131 @@ export class ReadingClient {
84
97
  }
85
98
  throw new Error("Reading projection has not reached the announced version");
86
99
  }
87
- async update(transform) {
100
+ update(transform) {
101
+ // Advanced transforms may replace profile-wide state. Typed observation
102
+ // methods below only derive changes for their configured team.
103
+ return this.updateScoped(transform);
104
+ }
105
+ updateScoped(transform, teamId, observation) {
88
106
  if (this.closed)
89
- throw new Error("READING_CLIENT_CLOSED");
90
- const next = await this.persistence.update(this.options.appId, this.options.profileId, transform);
91
- if (!this.closed) {
92
- this.publish(next);
93
- if (next.pending.length || next.observedReadIntents?.length)
94
- this.refresh();
95
- }
96
- return next;
107
+ return Promise.reject(new Error("READING_CLIENT_CLOSED"));
108
+ // One shared metadata read per local authority generation, rather than one
109
+ // IndexedDB lookup for every viewport observation.
110
+ const versions = this.versions ??= this.persistence.loadVersions(this.options.appId, this.options.profileId);
111
+ const task = (async () => {
112
+ const expected = await versions;
113
+ const next = await this.persistence.update(this.options.appId, this.options.profileId, (state, currentVersions) => {
114
+ assertReadIndexVersions(expected, currentVersions, teamId);
115
+ const next = transform(state);
116
+ return this.options.metadataOnly ? readingMetadata(next) : next;
117
+ }, observation);
118
+ if (!this.closed) {
119
+ this.publish(next);
120
+ if (next.pending.length || next.observedReadIntents?.length)
121
+ this.refresh();
122
+ }
123
+ return next;
124
+ })().catch(error => {
125
+ if (String(error).includes("READ_SCOPE_CHANGED")) {
126
+ if (teamId !== undefined)
127
+ this.withdraw();
128
+ else
129
+ this.versions = undefined;
130
+ }
131
+ throw error;
132
+ });
133
+ this.accepted.add(task);
134
+ void task.finally(() => this.accepted.delete(task)).catch(() => { });
135
+ return task;
136
+ }
137
+ prepareTeam(teamId, version) {
138
+ if (this.closed)
139
+ return Promise.reject(new Error("READING_CLIENT_CLOSED"));
140
+ if (!isValidChatTeamId(teamId) || !Number.isSafeInteger(version) || version < 0)
141
+ return Promise.reject(new Error("INVALID_READ_SCOPE_VERSION"));
142
+ const previous = this.prepared.get(teamId);
143
+ if (previous && previous.version >= version)
144
+ return previous.task;
145
+ const task = (async () => {
146
+ if (version > 0)
147
+ await this.persistence.invalidateTeam(this.options.appId, this.options.profileId, teamId, version);
148
+ this.versions = undefined;
149
+ })().catch(error => { if (this.prepared.get(teamId)?.task === task)
150
+ this.prepared.delete(teamId); throw error; });
151
+ this.prepared.set(teamId, { version, task });
152
+ return task;
153
+ }
154
+ assertThreadTeam(state, threadId) {
155
+ if (this.options.teamId !== undefined && state.threads.some(thread => (thread.id === threadId || thread.conversationId === threadId) && thread.teamId !== undefined && thread.teamId !== this.options.teamId))
156
+ throw new Error("READ_CONVERSATION_TEAM_MISMATCH");
157
+ }
158
+ markRead(threadId, messages = []) {
159
+ return this.updateScoped(state => { this.assertThreadTeam(state, threadId); return recordConversationRead(state, threadId, messages); }, this.options.teamId);
97
160
  }
98
161
  recordVisible(threadId, messageIds) { return this.record(threadId, messageIds, "visible"); }
99
162
  recordExplicit(threadId, messageIds) { return this.record(threadId, messageIds, "explicit"); }
100
163
  record(threadId, ids, readPolicy) {
101
164
  const messageIds = [...new Set(ids)];
102
- return this.update(state => messageIds.reduce((next, messageId) => recordReadIntent(next, { threadId, messageId, readPolicy, operationId: crypto.randomUUID() }), state));
165
+ if (!messageIds.length && this.state) {
166
+ try {
167
+ this.assertThreadTeam(this.state, threadId);
168
+ return Promise.resolve(this.state);
169
+ }
170
+ catch (error) {
171
+ return Promise.reject(error);
172
+ }
173
+ }
174
+ 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
175
  }
104
- async close() {
176
+ withdraw() { this.stop(); }
177
+ stop() {
178
+ if (this.closed)
179
+ return;
105
180
  this.closed = true;
106
181
  this.generation++;
107
182
  this.offWake?.();
108
183
  this.tasks.close();
109
184
  clearTimeout(this.retry);
110
185
  this.sync.stop();
186
+ this.state = undefined;
187
+ this.listeners.forEach(listener => listener());
111
188
  this.listeners.clear();
112
- await this.persistence.close();
113
- await this.storage?.close();
189
+ }
190
+ /** This client is retired permanently. Drain accepted local observations
191
+ * before deleting one team's profile-wide projection; sibling teams survive. */
192
+ revokeTeam(teamId, version, knownThreadIds = []) {
193
+ if (this.revoking)
194
+ return this.revoking;
195
+ if (this.closing)
196
+ return Promise.reject(new Error("READING_CLIENT_CLOSED"));
197
+ this.stop();
198
+ return this.revoking = (async () => {
199
+ try {
200
+ await Promise.allSettled([...this.accepted]);
201
+ await this.persistence.close();
202
+ if (!this.backing.invalidateTeam)
203
+ throw new Error("READ_SCOPE_INVALIDATION_UNAVAILABLE");
204
+ await this.backing.invalidateTeam(this.options.appId, this.options.profileId, teamId, version, knownThreadIds);
205
+ }
206
+ finally {
207
+ await this.storage?.close();
208
+ }
209
+ })();
210
+ }
211
+ close() {
212
+ if (this.revoking)
213
+ return this.revoking;
214
+ if (this.closing)
215
+ return this.closing;
216
+ this.stop();
217
+ return this.closing = (async () => {
218
+ try {
219
+ await Promise.allSettled([...this.accepted]);
220
+ await this.persistence.close();
221
+ }
222
+ finally {
223
+ await this.storage?.close();
224
+ }
225
+ })();
114
226
  }
115
227
  }
@@ -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
+ }
@@ -1,18 +1,40 @@
1
+ export type ResponseCacheAccess = () => Promise<{
2
+ version: number;
3
+ allowed: boolean;
4
+ }>;
5
+ export declare function isResponseCacheAuthorityError(error: unknown): boolean;
6
+ export declare function assertResponseCacheAccess(access?: ResponseCacheAccess, expectedVersion?: number): Promise<number | undefined>;
7
+ export type ResponseCacheOptions<T> = {
8
+ indexedDB?: IDBFactory;
9
+ name?: string;
10
+ access?: ResponseCacheAccess;
11
+ /** Immutable identity metadata must survive ordinary response-window eviction. */
12
+ retainAll?: boolean;
13
+ recordBytes?: number;
14
+ entries?: number;
15
+ batchRecords?: number;
16
+ revision?: (value: T) => string;
17
+ };
1
18
  /** Small response windows, isolated by identity. Epochs fence late writes after
2
19
  * access withdrawal. No localStorage or synchronous writes on the read path. */
3
20
  export declare class IndexedDbResponseCache<T> {
4
21
  private scope;
22
+ private options;
23
+ private transact;
5
24
  private db;
6
25
  private rows;
7
26
  private epochs;
8
27
  private pending;
9
28
  private tasks;
10
29
  private running?;
30
+ private invalidations;
11
31
  private closed;
12
- constructor(scope: string, options?: {
13
- indexedDB?: IDBFactory;
14
- name?: string;
15
- });
32
+ private closing?;
33
+ constructor(scope: string, options?: ResponseCacheOptions<T>);
34
+ /** Resolve shared message-scope authority before opening our transaction.
35
+ * A newer authority version retires response windows exactly once; delayed
36
+ * callers can never roll the authority backwards or delete recovered data. */
37
+ private synchronizeAccess;
16
38
  read(key: string): Promise<{
17
39
  epoch: number;
18
40
  cached: {
@@ -20,7 +42,20 @@ export declare class IndexedDbResponseCache<T> {
20
42
  time: number;
21
43
  } | undefined;
22
44
  }>;
23
- write(key: string, value: T, epoch: number): Promise<void>;
45
+ /** Key-only callers can share one bounded metadata read transaction. */
46
+ readMany(keys: readonly string[]): Promise<Map<string, {
47
+ epoch: number;
48
+ cached: {
49
+ value: T;
50
+ time: number;
51
+ } | undefined;
52
+ }>>;
53
+ write(key: string, value: T, epoch: number, expectedRevision?: string | null): Promise<void>;
54
+ /** Forget one response without invalidating unrelated cached conversations. */
55
+ remove(key: string): Promise<void>;
56
+ /** Idempotent shared-scope retirement: an old cleanup cannot erase windows
57
+ * created after the same authority version was already recovered. */
58
+ retire(version: number): Promise<void>;
24
59
  invalidate(): Promise<void>;
25
60
  flush(): Promise<void>;
26
61
  close(): Promise<void>;