@pmate/chat-sdk 0.14.0-seq.5 → 0.14.0-seq.7

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.
@@ -56,6 +56,8 @@ export type GroupChanges = {
56
56
  removeMembers?: readonly string[];
57
57
  title?: string;
58
58
  avatar?: string;
59
+ description?: string;
60
+ background?: string;
59
61
  };
60
62
  export type VoiceAttachment = Readonly<{
61
63
  url: string;
@@ -25,15 +25,7 @@ export type ReadersQuery = {
25
25
  afterProfileId?: string;
26
26
  revision?: number;
27
27
  };
28
- export type GroupChanges = {
29
- expectedRevision?: string;
30
- addMembers?: readonly string[];
31
- removeMembers?: readonly string[];
32
- title?: string;
33
- avatar?: string;
34
- background?: string;
35
- description?: string;
36
- };
28
+ export type GroupChanges = import("../chatContract.js").GroupChanges;
37
29
  export type SendOptions = {
38
30
  waitFor?: "accepted" | "delivered";
39
31
  };
@@ -0,0 +1,7 @@
1
+ export declare function inboxDeletion(fact: Record<string, unknown>): {
2
+ threadId: string;
3
+ teamId: string;
4
+ messageIds: Set<string>;
5
+ };
6
+ export declare function hideDeletedQuote<T>(body: T, deleted: ReadonlySet<string>): T;
7
+ export declare function recallTarget(body: unknown): string | undefined;
@@ -0,0 +1,21 @@
1
+ function identifier(value) {
2
+ return typeof value === "string" && value.length > 0 && value.length <= 256 && !/[\p{Cc}]/u.test(value);
3
+ }
4
+ export function inboxDeletion(fact) {
5
+ if (!identifier(fact.threadId) || !identifier(fact.teamId) || !Array.isArray(fact.messageIds)
6
+ || fact.messageIds.length < 1 || fact.messageIds.length > 1000 || !fact.messageIds.every(identifier)) {
7
+ throw Error("INVALID_INBOX_MESSAGE_DELETION");
8
+ }
9
+ return { threadId: fact.threadId, teamId: fact.teamId, messageIds: new Set(fact.messageIds) };
10
+ }
11
+ export function hideDeletedQuote(body, deleted) {
12
+ const message = body;
13
+ const quote = message?.content?.quote;
14
+ if (!message || !quote?.messageId || !deleted.has(quote.messageId))
15
+ return body;
16
+ return { ...message, content: { ...message.content, quote: { ...quote, content: "[消息已删除]" } } };
17
+ }
18
+ export function recallTarget(body) {
19
+ const wire = body;
20
+ return wire?.kind === "recall" ? wire.targetMessageId : wire?.content?.recall?.messageId;
21
+ }
@@ -1,3 +1,4 @@
1
+ import { hideDeletedQuote, inboxDeletion, recallTarget } from "./inboxDeletion.js";
1
2
  import { INBOX_PROJECTION_VERSIONS, validateInboxReceipt } from "./inboxProjections.js";
2
3
  import { Dexie } from "dexie";
3
4
  import { messageRequiresPlayback, isReadingControl } from "./readingContent.js";
@@ -237,11 +238,19 @@ export class IndexedDbInbox {
237
238
  throw new Error("INBOX_FACT_IDENTITY_MISMATCH");
238
239
  switch (event.kind) {
239
240
  case "messageAdded": {
240
- const message = data, thread = message.threadId;
241
- if (!thread || !message.messageId || !message.from || typeof message.seq !== "number" || !Number.isSafeInteger(message.seq) || message.seq < 1 || !["dm", "group"].includes(message.threadKind))
241
+ let message = data;
242
+ const thread = message.threadId, sequence = message.seq;
243
+ if (!thread || !message.messageId || !message.from || typeof sequence !== "number" || !Number.isSafeInteger(sequence) || sequence < 1 || !["dm", "group"].includes(message.threadKind))
242
244
  throw new Error("INVALID_INBOX_MESSAGE");
243
245
  if (message.from !== this.scope.profileId && !message.recipients?.includes(this.scope.profileId) && !(message.threadKind === "dm" && message.to === this.scope.profileId))
244
246
  throw new Error("INBOX_MESSAGE_INACCESSIBLE");
247
+ const scope = JSON.stringify([thread, message.teamId]);
248
+ const deleted = new Set((await this.facts.get([owner, "messageDeleted", scope]))?.value.messageIds ?? []);
249
+ const targetOfRecall = recallTarget(message.body);
250
+ if (deleted.has(message.messageId) || (targetOfRecall && deleted.has(targetOfRecall)))
251
+ return;
252
+ if (deleted.size)
253
+ message = { ...message, body: hideDeletedQuote(message.body, deleted) };
245
254
  await this.threads.put({ owner, id: thread, kind: message.threadKind, teamId: message.teamId, targetId: message.to });
246
255
  const body = message.body;
247
256
  if (body?.kind === "group") {
@@ -255,7 +264,7 @@ export class IndexedDbInbox {
255
264
  return thread;
256
265
  const root = messageThreadRoot(message.body) ?? "";
257
266
  const recalls = await this.facts.get([owner, "recall", JSON.stringify([thread, message.messageId])]);
258
- await this.messages.put({ owner, thread, id: message.messageId, acceptedAt: sourceAcceptedAt, time: message.serverCreatedAt, seq: message.seq, changeSeq: event.inboxSeq.padStart(19, "0"), root, recalled: recalls?.value.from === message.from, value: message });
267
+ await this.messages.put({ owner, thread, id: message.messageId, acceptedAt: sourceAcceptedAt, time: message.serverCreatedAt, seq: sequence, changeSeq: event.inboxSeq.padStart(19, "0"), root, recalled: recalls?.value.from === message.from, value: message });
259
268
  const target = body?.kind === "recall" ? body.targetMessageId : body?.kind === "message" && body.content?.appId === this.scope.appId ? body.content?.recall?.messageId : undefined;
260
269
  if (typeof target === "string") {
261
270
  const key = JSON.stringify([thread, target]);
@@ -266,6 +275,27 @@ export class IndexedDbInbox {
266
275
  }
267
276
  return thread;
268
277
  }
278
+ case "messageDeleted": {
279
+ const { threadId: thread, teamId, messageIds } = inboxDeletion(data), scope = JSON.stringify([thread, teamId]);
280
+ const old = await this.facts.get([owner, event.kind, scope]);
281
+ const deleted = new Set([...(old?.value.messageIds ?? []), ...messageIds]);
282
+ await this.facts.put({ owner, kind: event.kind, id: scope, thread, value: { threadId: thread, teamId, messageIds: [...deleted] } });
283
+ await this.facts.put({ owner, kind: "structure", id: thread, thread, value: { seq: event.inboxSeq } });
284
+ const rows = await this.messages.where("[owner+thread]").equals([owner, thread]).toArray();
285
+ for (const row of rows) {
286
+ if (row.value.teamId !== teamId)
287
+ continue;
288
+ const target = recallTarget(row.value.body);
289
+ if (deleted.has(row.id) || (target && deleted.has(target)))
290
+ await this.messages.delete([owner, thread, row.id]);
291
+ else {
292
+ const body = hideDeletedQuote(row.value.body, deleted);
293
+ if (body !== row.value.body)
294
+ await this.messages.update([owner, thread, row.id], { value: { ...row.value, body }, changeSeq: event.inboxSeq.padStart(19, "0") });
295
+ }
296
+ }
297
+ return thread;
298
+ }
269
299
  case "readingUpdated": {
270
300
  if (data.receiptOnly === true) {
271
301
  await this.writeReceipts([event]);
@@ -28,6 +28,7 @@ export declare class ProfileDatabase extends Dexie {
28
28
  threads?: ProfileThread[];
29
29
  windows?: ProfileWindow[];
30
30
  messages?: ProfileMessage[];
31
+ deleteMessages?: string[];
31
32
  }): Promise<void>;
32
33
  /** Bounded maintenance on the serial Worker queue. Building
33
34
  * and validated generations remain resumable; outbox is never involved. */
@@ -110,6 +110,8 @@ export class ProfileDatabase extends Dexie {
110
110
  const current = await this.inboxState.get("current");
111
111
  if (current?.activeGeneration === build.generation)
112
112
  throw Error("PROFILE_BUILD_IS_ACTIVE");
113
+ if (rows.deleteMessages?.length)
114
+ await this.messages.bulkDelete(rows.deleteMessages.map(id => [build.generation, id]));
113
115
  if (rows.messages?.length)
114
116
  await this.messages.bulkPut(rows.messages);
115
117
  if (rows.windows?.length)
@@ -102,7 +102,7 @@ export async function migrateLegacyInbox(owner, options = {}) {
102
102
  readThroughSeq: 0, explicitReadMessageIds: [row.id] }, `explicit:${row.id}`));
103
103
  }
104
104
  for (const row of rows.facts)
105
- if (["threadOrganized", "threadAssigned", "relationshipUpdated"].includes(row.kind))
105
+ if (["threadOrganized", "threadAssigned", "relationshipUpdated", "messageDeleted"].includes(row.kind))
106
106
  await push(restore(row.kind, row.value, row.id));
107
107
  for (const row of rows.receipts)
108
108
  await push({ type: "restoreReceipt", data: { appId: identity.appId, profileId: identity.profileId,
@@ -186,7 +186,7 @@ export class ProfileOwner {
186
186
  const prepared = this.projection.prepare(events);
187
187
  // A replayed cursor or already-observed reading candidate must not even
188
188
  // open a readwrite transaction. Only small sync metadata is compared here.
189
- const unchanged = ![prepared.messages, prepared.windows, prepared.threads, prepared.outbox, prepared.deleteOutbox].some(rows => rows.length) &&
189
+ const unchanged = ![prepared.messages, prepared.windows, prepared.threads, prepared.outbox, prepared.deleteMessages, prepared.deleteOutbox].some(rows => rows.length) &&
190
190
  JSON.stringify({ ...prepared.current, commitRevision: fromRevision }) === JSON.stringify(this.current);
191
191
  if (unchanged)
192
192
  return prepared.rejected;
@@ -196,7 +196,7 @@ export class ProfileOwner {
196
196
  if (committed.commitRevision === fromRevision)
197
197
  return prepared.rejected;
198
198
  prepared.current = committed;
199
- const delta = { current: committed, threads: prepared.threads, windows: prepared.windows, messages: prepared.messages,
199
+ const delta = { deleteMessages: prepared.deleteMessages, current: committed, threads: prepared.threads, windows: prepared.windows, messages: prepared.messages,
200
200
  protocolVersion: PROFILE_PROTOCOL_VERSION, generation: committed.activeGeneration,
201
201
  fromRevision, toRevision: committed.commitRevision };
202
202
  this.projection.accept(prepared);
@@ -102,6 +102,7 @@ export type PreparedProfileProjection = {
102
102
  messages: ProfileMessage[];
103
103
  readingIndices: Map<string, ProfileReadingIndex>;
104
104
  outbox: ProfileOutboxCommand[];
105
+ deleteMessages: string[];
105
106
  deleteOutbox: string[];
106
107
  rejected?: readonly (Error | undefined)[];
107
108
  };
@@ -128,6 +129,7 @@ export declare class ProfileProjection {
128
129
  messages: ProfileMessage[];
129
130
  readingIndices: Map<string, ProfileReadingIndex>;
130
131
  outbox: ProfileOutboxCommand[];
132
+ deleteMessages: string[];
131
133
  deleteOutbox: string[];
132
134
  };
133
135
  prepareBasis(bootstrap: InboxBootstrap): PreparedProfileProjection;
@@ -1,3 +1,4 @@
1
+ import { hideDeletedQuote, inboxDeletion, recallTarget } from "./inboxDeletion.js";
1
2
  import { inboxSequence } from "./inboxStore.js";
2
3
  import { messageMentionsProfile, messageRequiresPlayback } from "./readingContent.js";
3
4
  import { messageThreadRoot } from "./messageThread.js";
@@ -95,6 +96,8 @@ export class ProfileProjection {
95
96
  this.children.set(row.parentThreadId, children);
96
97
  }
97
98
  }
99
+ for (const id of prepared.deleteMessages)
100
+ this.messages.delete(id);
98
101
  for (const row of prepared.messages) {
99
102
  this.messages.set(row.messageId, row);
100
103
  }
@@ -127,6 +130,7 @@ class ProfileProjectionDraft {
127
130
  windows = new Map();
128
131
  readingIndices = new Map();
129
132
  outbox = new Map();
133
+ deleteMessages = new Set();
130
134
  deleteOutbox = new Set();
131
135
  seq;
132
136
  revision;
@@ -178,7 +182,7 @@ class ProfileProjectionDraft {
178
182
  return Error("INVALID_MESSAGE_REACTION");
179
183
  }
180
184
  }
181
- message(id) { return this.messages.get(id) ?? this.base.messages.get(id); }
185
+ message(id) { return this.deleteMessages.has(id) ? undefined : this.messages.get(id) ?? this.base.messages.get(id); }
182
186
  thread(id) { return this.threads.get(id) ?? this.base.threads.get(id); }
183
187
  ensure(id, kind = "group", extra = {}) {
184
188
  const previous = this.thread(id);
@@ -349,6 +353,9 @@ class ProfileProjectionDraft {
349
353
  case "readingUpdated":
350
354
  this.reading(event);
351
355
  break;
356
+ case "messageDeleted":
357
+ this.deleteInboxMessages(event);
358
+ break;
352
359
  case "threadOrganized":
353
360
  this.organize(event);
354
361
  break;
@@ -593,12 +600,66 @@ class ProfileProjectionDraft {
593
600
  this.reading(eventForLocalReading(this.base.identity, sourceId, thread.rootMessageId, values), false);
594
601
  }
595
602
  }
603
+ deleteInboxMessages(event) {
604
+ const { threadId, teamId, messageIds } = inboxDeletion(event.fact);
605
+ const source = this.ensure(threadId, "group", { teamId });
606
+ const key = JSON.stringify(teamId);
607
+ const deleted = new Set([...(source.internal?.deletedMessageIds?.[key] ?? []), ...messageIds]);
608
+ this.putThread({ ...source, internal: {
609
+ ...source.internal, deletedMessageIds: { ...source.internal?.deletedMessageIds, [key]: [...deleted] },
610
+ } });
611
+ for (const id of messageIds) {
612
+ const message = this.message(id);
613
+ if (!message || message.sourceThreadId !== threadId || this.thread(message.threadId)?.teamId !== teamId)
614
+ continue;
615
+ const thread = this.thread(message.threadId);
616
+ const before = this.contribution(message);
617
+ const unknown = this.unknownReading(message);
618
+ const directory = this.directory(message.threadId);
619
+ const change = directory.remove(id, this.revision);
620
+ directory.accept(change);
621
+ for (const row of change.windows)
622
+ this.windows.set(JSON.stringify([row.threadId, row.windowId]), row);
623
+ this.readingIndex(message.threadId).remove(message);
624
+ this.messages.delete(id);
625
+ this.deleteMessages.add(id);
626
+ const last = directory.readPage(undefined, 1)[0];
627
+ const participantCounts = { ...thread.internal?.participantCounts, [message.from]: Math.max(0, (thread.internal?.participantCounts?.[message.from] ?? 1) - 1) };
628
+ this.putThread({ ...this.thread(message.threadId), messageCount: directory.count, windowCount: change.windowCount,
629
+ lastMessageId: last?.messageId, lastActivityAt: last?.orderKey[0] ?? 0, internal: { ...this.thread(message.threadId)?.internal, participantCounts },
630
+ participantProfileIds: Object.keys(participantCounts).filter(profile => participantCounts[profile] > 0).sort() });
631
+ this.updateSummary(message.threadId, -before.unread, -before.mentions, -unknown);
632
+ }
633
+ for (const id of new Set([...this.base.messages.keys(), ...this.messages.keys()])) {
634
+ const row = this.message(id);
635
+ if (!row || row.sourceThreadId !== threadId || this.thread(row.threadId)?.teamId !== teamId)
636
+ continue;
637
+ const content = hideDeletedQuote(row.content, deleted);
638
+ const quote = row.presentation?.quote;
639
+ if (content === row.content && (!quote?.messageId || !deleted.has(quote.messageId)))
640
+ continue;
641
+ const presentation = row.presentation && {
642
+ ...row.presentation,
643
+ quote: quote?.messageId && deleted.has(quote.messageId) ? { ...quote, content: "[消息已删除]" } : quote,
644
+ richContent: hideDeletedQuote({ content: row.presentation.richContent }, deleted).content,
645
+ };
646
+ this.messages.set(id, { ...row, content, presentation, revision: this.revision });
647
+ }
648
+ }
596
649
  add(event) {
597
- const wire = event.fact;
650
+ let wire = event.fact;
598
651
  if (!wire.messageId || !wire.threadId || !wire.from || !Number.isSafeInteger(wire.seq) || wire.seq < 1 || !["dm", "group"].includes(wire.threadKind))
599
652
  throw Error("INVALID_INBOX_MESSAGE");
600
653
  if (wire.from !== this.base.identity.profileId && !wire.recipients?.includes(this.base.identity.profileId) && !(wire.threadKind === "dm" && wire.to === this.base.identity.profileId))
601
654
  throw Error("INBOX_MESSAGE_INACCESSIBLE");
655
+ const deleted = this.thread(wire.threadId)?.internal?.deletedMessageIds?.[JSON.stringify(wire.teamId)];
656
+ if (deleted?.length) {
657
+ const ids = new Set(deleted);
658
+ const target = recallTarget(wire.body);
659
+ if (ids.has(wire.messageId) || (target && ids.has(target)))
660
+ return;
661
+ wire = { ...wire, body: hideDeletedQuote(wire.body, ids) };
662
+ }
602
663
  let source = this.ensure(wire.threadId, wire.threadKind, { teamId: wire.teamId, internal: { targetId: wire.to } });
603
664
  const targetId = wire.threadKind === "dm" && wire.from !== this.base.identity.profileId ? wire.from : wire.to;
604
665
  if (source.kind !== wire.threadKind || source.teamId !== wire.teamId || source.internal?.targetId !== targetId) {
@@ -941,7 +1002,7 @@ class ProfileProjectionDraft {
941
1002
  return { current: { ...this.base.current, committedSeq: this.seq.toString(), commitRevision: this.revision, receiptsReady: this.receiptsReady,
942
1003
  localMigrations: this.localMigrations ?? this.base.current.localMigrations, revokedTeamIds: this.revokedTeamIds ?? this.base.current.revokedTeamIds, teamAccessRevision: this.teamAccessRevision ?? this.base.current.teamAccessRevision },
943
1004
  threads: [...this.threads.values()], windows: [...this.windows.values()], messages: [...this.messages.values()], readingIndices: this.readingIndices,
944
- outbox: [...this.outbox.values()].filter(command => !this.deleteOutbox.has(command.commandId)), deleteOutbox: [...this.deleteOutbox] };
1005
+ deleteMessages: [...this.deleteMessages], outbox: [...this.outbox.values()].filter(command => !this.deleteOutbox.has(command.commandId)), deleteOutbox: [...this.deleteOutbox] };
945
1006
  }
946
1007
  }
947
1008
  function eventForLocalReading(identity, threadId, root, values) {
@@ -47,6 +47,7 @@ export type ProfileThread = {
47
47
  groupControls?: Record<string, unknown>;
48
48
  organizationRevisions?: Record<string, number>;
49
49
  assignments?: Record<string, string>;
50
+ deletedMessageIds?: Record<string, string[]>;
50
51
  pendingControls?: Record<string, unknown[]>;
51
52
  messageRoots?: Record<string, string>;
52
53
  pendingReceipts?: Record<string, string[]>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pmate/chat-sdk",
3
- "version": "0.14.0-seq.5",
3
+ "version": "0.14.0-seq.7",
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",
@@ -68,6 +68,14 @@
68
68
  "publishConfig": {
69
69
  "access": "public"
70
70
  },
71
+ "scripts": {
72
+ "preview:component": "merry-plugin browser open --plugin react-preview",
73
+ "clean": "rimraf lib",
74
+ "build": "pnpm run clean && tsc -p tsconfig.build.json && cp src/voice/recorder-processor.js lib/voice/recorder-processor.js",
75
+ "prepack": "pnpm run build",
76
+ "npm:publish": "pnpm publish --access public --registry https://registry.npmjs.org/",
77
+ "test": "vitest run"
78
+ },
71
79
  "dependencies": {
72
80
  "@emoji-mart/data": "^1.2.1",
73
81
  "@emoji-mart/react": "^1.1.1",
@@ -84,22 +92,15 @@
84
92
  "esbuild": "0.25.12",
85
93
  "@tailwindcss/node": "4.1.18",
86
94
  "@tailwindcss/oxide": "4.1.18",
87
- "@tailwindcss/vite": "^4.1.3",
88
- "@types/react": "^19.2.7",
89
- "@types/react-dom": "^19.2.3",
95
+ "@tailwindcss/vite": "catalog:",
96
+ "@types/react": "catalog:",
97
+ "@types/react-dom": "catalog:",
90
98
  "fake-indexeddb": "^6.2.5",
91
- "react": "^19.1.1",
92
- "react-dom": "^19.1.1",
99
+ "react": "catalog:",
100
+ "react-dom": "catalog:",
93
101
  "rimraf": "^6.1.2",
94
- "tailwindcss": "^4.0.14",
102
+ "tailwindcss": "catalog:",
95
103
  "typescript": "5.9.2",
96
104
  "vitest": "^4.0.17"
97
- },
98
- "scripts": {
99
- "preview:component": "merry-plugin browser open --plugin react-preview",
100
- "clean": "rimraf lib",
101
- "build": "pnpm run clean && tsc -p tsconfig.build.json && cp src/voice/recorder-processor.js lib/voice/recorder-processor.js",
102
- "npm:publish": "pnpm publish --access public --registry https://registry.npmjs.org/",
103
- "test": "vitest run"
104
105
  }
105
- }
106
+ }