korero-chat 0.1.0 → 0.1.2

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/dist/types.d.ts CHANGED
@@ -1,7 +1,10 @@
1
1
  export interface Account {
2
2
  id: string;
3
3
  displayName: string;
4
+ /** The highest-ranked held role, used for display. */
4
5
  role: string;
6
+ /** Every held role, highest rank first. Servers without multiple roles omit it. */
7
+ roles?: string[];
5
8
  badge?: string | null;
6
9
  avatarId?: string | null;
7
10
  }
@@ -19,6 +22,13 @@ export interface ChannelData {
19
22
  canDelete?: boolean;
20
23
  /** The account may delete other members' messages in this channel. */
21
24
  canDeleteMessages?: boolean;
25
+ /** The server supports pins in this channel. */
26
+ messagePins?: boolean;
27
+ /** The server can search this channel's stored messages with `message.search`. */
28
+ messageSearch?: boolean;
29
+ canPinMessages?: boolean;
30
+ /** The server stores reactions on this channel's messages. */
31
+ messageReactions?: boolean;
22
32
  /**
23
33
  * The account may read and send this channel's messages, even without joining it.
24
34
  * Servers that predate outside chat omit this; chat then needs membership.
@@ -46,6 +56,7 @@ export interface Member {
46
56
  adminMuted: boolean;
47
57
  adminDeafened?: boolean;
48
58
  role?: string;
59
+ roles?: string[];
49
60
  badge?: string | null;
50
61
  speaking?: boolean;
51
62
  }
@@ -66,11 +77,17 @@ export interface Snapshot {
66
77
  serverPermissions: string[];
67
78
  lowerRoles?: string[];
68
79
  assignableRoles?: string[];
80
+ /** Sent to role managers. Changes whenever any account's roles change. */
81
+ accountsRevision?: number;
69
82
  bannerImageUrl?: string | null;
70
83
  motd?: string;
84
+ /** Formatted MOTD in the chat markup allowlist, when the message has formatting. */
85
+ motdHtml?: string;
71
86
  targetAudioBitrate?: number;
72
87
  maxAttachmentBytes?: number;
73
88
  canReorderChannels?: boolean;
89
+ /** Roles that messages may mention. */
90
+ mentionableRoles?: string[];
74
91
  canSendText?: boolean;
75
92
  canAttachFiles?: boolean;
76
93
  directMessages?: {
@@ -117,12 +134,18 @@ export type MemberRequest = {
117
134
  deafened: boolean;
118
135
  };
119
136
  } | {
120
- kind: "moderation.kick" | "moderation.ban" | "moderation.unban";
137
+ kind: "moderation.ban";
121
138
  payload: {
122
139
  accountId: string;
140
+ expiresInSeconds?: number;
123
141
  };
124
142
  } | {
125
- kind: "role.set";
143
+ kind: "moderation.kick" | "moderation.unban";
144
+ payload: {
145
+ accountId: string;
146
+ };
147
+ } | {
148
+ kind: "role.add" | "role.remove";
126
149
  payload: {
127
150
  accountId: string;
128
151
  role: string;
@@ -133,14 +156,78 @@ export interface Message {
133
156
  channelId: string | null;
134
157
  recipientId?: string | null;
135
158
  senderId: string;
159
+ senderName?: string;
136
160
  createdAt: number;
137
161
  text: string;
138
162
  html?: string;
139
163
  editedAt?: number | null;
164
+ pinnedAt?: number | null;
140
165
  attachment?: {
141
166
  name: string;
142
167
  size: number;
143
168
  };
169
+ /** The message this one answers. `missing` once the original is deleted or expires. */
170
+ replyTo?: ReplyPreview | {
171
+ id: string;
172
+ missing: true;
173
+ };
174
+ mentions?: MessageMentions;
175
+ /** Present only on stored messages with reactions; `me` reflects the reading account. */
176
+ reactions?: MessageReaction[];
177
+ }
178
+ export interface ReplyPreview {
179
+ id: string;
180
+ senderId: string;
181
+ senderName: string;
182
+ /** Up to 120 characters of the original text. */
183
+ text: string;
184
+ attachmentName?: string;
185
+ }
186
+ export interface MessageMentions {
187
+ accounts: string[];
188
+ roles: string[];
189
+ }
190
+ export interface MessageReaction {
191
+ emoji: string;
192
+ count: number;
193
+ me: boolean;
194
+ }
195
+ /** Sent to each mentioned reader, including those not following the channel. */
196
+ export interface MessageMention {
197
+ channelId: string;
198
+ messageId: string;
199
+ senderId: string;
200
+ senderName: string;
201
+ text: string;
202
+ }
203
+ export interface ReactionChange {
204
+ channelId: string;
205
+ messageId: string;
206
+ emoji: string;
207
+ count: number;
208
+ accountId: string;
209
+ reacted: boolean;
210
+ }
211
+ export interface PinCursor {
212
+ id: string;
213
+ pinnedAt: number;
214
+ }
215
+ export interface PinnedMessagePage {
216
+ messages: (PinCursor & Pick<Message, "senderId" | "senderName" | "createdAt" | "text"> & {
217
+ attachmentName: string | null;
218
+ })[];
219
+ next: PinCursor | null;
220
+ }
221
+ export interface SearchCursor {
222
+ id: string;
223
+ createdAt: number;
224
+ }
225
+ export interface MessageSearchPage {
226
+ /** `text` is a preview of up to 240 characters around the first match, with "…" where it was cut. */
227
+ messages: (SearchCursor & Pick<Message, "senderId" | "senderName" | "text"> & {
228
+ attachmentName: string | null;
229
+ })[];
230
+ next: SearchCursor | null;
144
231
  }
145
232
  export interface DirectMessageReference {
146
233
  id: string;
@@ -173,16 +260,31 @@ export interface Poke {
173
260
  message?: string;
174
261
  }
175
262
  export type DirectOperation = "direct.peer" | "direct.inbox" | "direct.history" | "direct.send" | "direct.edit" | "direct.delete" | "direct.poke";
263
+ /** A received typing ping. `channelId` is absent for direct messages; `at` is the receiver's clock. */
264
+ export interface TypingEntry {
265
+ channelId?: string;
266
+ accountId: string;
267
+ displayName: string;
268
+ at: number;
269
+ }
270
+ /** How long a typing indicator lasts after its most recent ping. */
271
+ export declare const typingExpiryMs = 6000;
176
272
  export interface VoiceState {
177
273
  /** Server origin of the desktop session that produced this state. */
178
274
  origin?: string;
179
275
  phase: "offline" | "connecting" | "online" | "reconnecting" | "error";
180
276
  snapshot: Snapshot | null;
181
277
  messages: Message[];
278
+ /** Changes when a channel's stored messages are edited, deleted, pinned or unpinned. */
279
+ messageRevisions?: Record<string, number>;
182
280
  directMessages?: DirectMessage[];
183
281
  /** A live change to apply to any history the client has already loaded. */
184
282
  directChange?: DirectMessageChange;
185
283
  lastPoke?: Poke | null;
284
+ /** The latest message that mentioned this account or one of its roles. */
285
+ lastMention?: MessageMention | null;
286
+ /** Recent typing pings from other accounts; filter by `at` against `typingExpiryMs` when showing them. */
287
+ typing?: TypingEntry[];
186
288
  speaking: string[];
187
289
  voice: "idle" | "active" | "muted" | "deafened" | "error";
188
290
  voiceError: string | null;
@@ -199,6 +301,7 @@ export interface ServerInfo {
199
301
  profilePictures?: boolean;
200
302
  maxAttachmentBytes?: number;
201
303
  richChat?: boolean;
304
+ typingIndicators?: boolean;
202
305
  maxWebSocketBytes?: number;
203
306
  screenSharing?: boolean;
204
307
  channelAudioQuality?: boolean;
package/dist/types.js CHANGED
@@ -1,6 +1,8 @@
1
1
  export function isSameDirectMessage(a, b) {
2
2
  return a.id === b.id && a.senderId === b.senderId && a.recipientId === b.recipientId;
3
3
  }
4
+ /** How long a typing indicator lasts after its most recent ping. */
5
+ export const typingExpiryMs = 6000;
4
6
  export const offline = {
5
7
  phase: "offline",
6
8
  snapshot: null,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "korero-chat",
3
- "version": "0.1.0",
3
+ "version": "0.1.2",
4
4
  "description": "TypeScript client for the Korero.chat v1 protocol",
5
5
  "license": "AGPL-3.0-only",
6
6
  "type": "module",
package/src/channel.ts CHANGED
@@ -1,7 +1,16 @@
1
1
  import type { KoreroClient } from "./session.js";
2
- import type { ChannelData, Message } from "./types.js";
2
+ import type { ChannelData, Message, MessageMentions, PinCursor, SearchCursor } from "./types.js";
3
3
 
4
- export type MessageContent = string | { text: string; html?: string };
4
+ export interface MessageBody {
5
+ text: string;
6
+ html?: string;
7
+ /** Accounts and mentionable roles the message mentions. */
8
+ mentions?: Partial<MessageMentions>;
9
+ }
10
+ export type MessageContent = string | MessageBody;
11
+ /** `replyTo` is the ID of a message in the same channel. */
12
+ export type SendContent = string | (MessageBody & { replyTo?: string });
13
+ const body = <T extends MessageBody>(value: string | T): T | MessageBody => typeof value === "string" ? { text: value } : value;
5
14
 
6
15
  export interface ChannelOptions {
7
16
  name?: string;
@@ -23,9 +32,9 @@ export class Channel {
23
32
  return this.client.state.snapshot?.channels.find(({ id }) => id === this.id);
24
33
  }
25
34
 
26
- send(content: MessageContent) {
27
- const { text, html } = typeof content === "string" ? { text: content } : content;
28
- return this.client.sendMessage(this.id, text, html);
35
+ send(value: SendContent) {
36
+ const { text, html, mentions, replyTo } = body(value) as MessageBody & { replyTo?: string };
37
+ return this.client.sendMessage(this.id, text, html, { mentions, replyTo });
29
38
  }
30
39
 
31
40
  history(before?: number) {
@@ -33,6 +42,14 @@ export class Channel {
33
42
  .then((messages) => messages.map((message) => new ChannelMessage(message, this, this.client)));
34
43
  }
35
44
 
45
+ pins(before?: PinCursor) {
46
+ return this.client.pinnedMessages(this.id, before);
47
+ }
48
+
49
+ search(query: string, before?: SearchCursor) {
50
+ return this.client.searchMessages(this.id, query, before);
51
+ }
52
+
36
53
  async follow() {
37
54
  const connectionId = this.client.connectionId;
38
55
  if (!connectionId) throw new Error("Connect to a server first.");
@@ -59,13 +76,27 @@ export class ChannelMessage {
59
76
  get id() { return this.data.id; }
60
77
  get text() { return this.data.text; }
61
78
  get senderId() { return this.data.senderId; }
79
+ get senderName() { return this.data.senderName; }
62
80
 
63
- edit(content: MessageContent) {
64
- const { text, html } = typeof content === "string" ? { text: content } : content;
65
- return this.client.editMessage(this.id, text, html);
81
+ /** Passing `mentions` replaces the message's mentions; omitting it keeps them. */
82
+ edit(value: MessageContent) {
83
+ const { text, html, mentions } = body(value);
84
+ return this.client.editMessage(this.id, text, html, mentions);
85
+ }
86
+
87
+ reply(value: MessageContent) {
88
+ return this.channel.send({ ...body(value), replyTo: this.id });
89
+ }
90
+
91
+ react(emoji: string, reacted = true) {
92
+ return this.client.reactToMessage(this.channel.id, this.id, emoji, reacted);
66
93
  }
67
94
 
68
95
  delete() {
69
96
  return this.client.deleteMessage(this.id);
70
97
  }
98
+
99
+ setPinned(pinned: boolean) {
100
+ return this.client.setMessagePin(this.channel.id, this.id, pinned);
101
+ }
71
102
  }
package/src/http.ts CHANGED
@@ -11,7 +11,7 @@ export type ApiResult<T> =
11
11
  | { data: null; error: { status: number; value: unknown }; status: number };
12
12
 
13
13
  export type ChannelPermission = "join" | "speak" | "text" | "deleteChannels" | "mute" |
14
- "attachFiles" | "shareScreen" | "useCamera" | "whisper";
14
+ "attachFiles" | "shareScreen" | "useCamera" | "whisper" | "pinMessages";
15
15
  export type Permission = ChannelPermission | "createChannels" | "editChannels" | "move" | "kick" |
16
16
  "ban" | "manageRoles" | "manageInvitations" | "manageSettings" | "viewAdmin" | "sendDirectMessages" | "removeChannels";
17
17
 
@@ -21,9 +21,11 @@ export interface ChannelPermissionTable {
21
21
  }
22
22
 
23
23
  export interface AccountPage {
24
- accounts: (Account & { editable: boolean; bannable: boolean; banned: boolean })[];
24
+ accounts: (Account & { editable: boolean; bannable: boolean; banned: boolean; bannedUntil?: number | null })[];
25
25
  next: string | null;
26
26
  roles: string[];
27
+ /** Every role on the server, including those the caller cannot assign. */
28
+ allRoles: string[];
27
29
  builtInRoles: (RoleDefinition & { editable: boolean; defaultPermissions: Permission[] })[];
28
30
  customRoles: RoleDefinition[];
29
31
  assignablePermissions: Permission[];
@@ -32,7 +34,20 @@ export interface AccountPage {
32
34
  registrationPermissions: Permission[];
33
35
  }
34
36
 
35
- export interface RoleDefinition { name: string; permissions: Permission[] }
37
+ export type AccountQuery = {
38
+ after?: string;
39
+ /** Matches part of the display name or the start of the account ID. */
40
+ search?: string;
41
+ role?: string;
42
+ status?: "banned" | "active";
43
+ };
44
+
45
+ export interface RoleDefinition {
46
+ name: string;
47
+ permissions: Permission[];
48
+ /** Messages may @mention the role. Omit when saving to keep the current setting. */
49
+ mentionable?: boolean;
50
+ }
36
51
 
37
52
  export interface AuditPage {
38
53
  events: {
@@ -50,6 +65,7 @@ export interface AuditPage {
50
65
 
51
66
  export interface ServerPreferences {
52
67
  motd: string;
68
+ motdHtml: string;
53
69
  defaultRole: string;
54
70
  canSetDefaultRole: boolean;
55
71
  defaultRoles: string[];
@@ -66,6 +82,34 @@ export interface Invitation {
66
82
  expiresAt: number | null;
67
83
  usesLeft: number | null;
68
84
  revokedAt: number | null;
85
+ /** Accounts that registered through this invitation. */
86
+ uses: number;
87
+ }
88
+
89
+ export interface InvitationAnalytics {
90
+ /** Everyone who created a visible invitation, most uses first. */
91
+ inviters: { accountId: string; displayName: string; invitations: number; uses: number }[];
92
+ /** The most recent registrations through an invitation, newest first. */
93
+ redemptions: {
94
+ invitationId: string; redeemedAt: number; accountId: string; displayName: string;
95
+ invitedBy: string; invitedByName: string;
96
+ }[];
97
+ }
98
+
99
+ export interface StorageBudget { used: number; limit: number }
100
+
101
+ export interface ServerMetrics {
102
+ sampledAt: number;
103
+ connections: { users: number; connections: number; voiceChannels: number; maxUsers: number };
104
+ /** Live RTP bitrates in bits per second, summed over every open media transport. */
105
+ bandwidth: { inboundBitrate: number; outboundBitrate: number; transports: number; egressLimit: number };
106
+ /** Bytes used against each configured storage budget. */
107
+ storage: {
108
+ messages: StorageBudget;
109
+ attachments: StorageBudget & { enabled: boolean };
110
+ hostedAccounts: StorageBudget & { accounts: number; accountLimit: number; registration: "open" | "closed" };
111
+ database: { bytes: number };
112
+ };
69
113
  }
70
114
 
71
115
  export interface ConnectionDetails {
@@ -92,6 +136,8 @@ export interface AttachmentUpload {
92
136
  channelId: string;
93
137
  text: string;
94
138
  html?: string;
139
+ replyTo?: string;
140
+ mentions?: { accounts?: string[]; roles?: string[] };
95
141
  name: string;
96
142
  data: string;
97
143
  }
@@ -158,6 +204,7 @@ export function createApi(origin: string, send: Requester = (request) => webTran
158
204
  },
159
205
  {
160
206
  get: () => request<{ invitations: Invitation[] }>("GET", "admin/invitations"),
207
+ analytics: { get: () => request<InvitationAnalytics>("GET", "admin/invitations/analytics") },
161
208
  post: (body: { expiresAt?: number; expiresInSeconds?: number; uses?: number }) =>
162
209
  request<Pick<Invitation, "id" | "expiresAt" | "usesLeft"> & { token: string }>("POST", "admin/invitations", body),
163
210
  },
@@ -183,10 +230,15 @@ export function createApi(origin: string, send: Requester = (request) => webTran
183
230
  channels,
184
231
  chat: { attachments },
185
232
  admin: {
186
- accounts: { get: (options?: QueryOptions<{ after?: string }>) => request<AccountPage>("GET", "admin/accounts", undefined, options?.query) },
233
+ accounts: {
234
+ get: (options?: QueryOptions<AccountQuery>) => request<AccountPage>("GET", "admin/accounts", undefined, options?.query),
235
+ roles: {
236
+ post: (body: { accountId: string; role: string }) => request<{ roles: string[] }>("POST", "admin/accounts/roles", body),
237
+ delete: (body: { accountId: string; role: string }) => request<{ roles: string[] }>("DELETE", "admin/accounts/roles", body),
238
+ },
239
+ },
187
240
  badges: { patch: (body: { accountId: string; badge: string | null }) => request<{ badge: string | null }>("PATCH", "admin/badges", body) },
188
241
  roles: {
189
- patch: (body: { accountId: string; role: string }) => request<{ role: string }>("PATCH", "admin/roles", body),
190
242
  post: (body: RoleDefinition) => request<RoleDefinition>("POST", "admin/roles", body),
191
243
  definition: {
192
244
  patch: (body: RoleDefinition) => request<RoleDefinition>("PATCH", "admin/roles/definition", body),
@@ -195,9 +247,10 @@ export function createApi(origin: string, send: Requester = (request) => webTran
195
247
  },
196
248
  audit: { get: (options?: QueryOptions<{ before?: number; prefix?: string; actorId?: string }>) =>
197
249
  request<AuditPage>("GET", "admin/audit", undefined, options?.query) },
250
+ metrics: { get: () => request<ServerMetrics>("GET", "admin/metrics") },
198
251
  preferences: {
199
252
  get: () => request<ServerPreferences>("GET", "admin/preferences"),
200
- patch: (body: Partial<Pick<ServerPreferences, "motd" | "defaultRole" | "defaultAudioBitrate" | "maxAttachmentMiB">>) =>
253
+ patch: (body: Partial<Pick<ServerPreferences, "motd" | "motdHtml" | "defaultRole" | "defaultAudioBitrate" | "maxAttachmentMiB">>) =>
201
254
  request<ServerPreferences>("PATCH", "admin/preferences", body),
202
255
  },
203
256
  banner: { patch: (body: { bannerImageUrl: string | null }) => request<typeof body>("PATCH", "admin/banner", body) },
package/src/index.ts CHANGED
@@ -1,11 +1,11 @@
1
1
  export { Channel, ChannelMessage } from "./channel.js";
2
- export type { ChannelOptions, MessageContent } from "./channel.js";
2
+ export type { ChannelOptions, MessageBody, MessageContent, SendContent } from "./channel.js";
3
3
  export { KoreroClient } from "./session.js";
4
4
  export type { ClientEvents, ConnectOptions, SessionOptions, SessionMedia, SessionMediaAdapter } from "./session.js";
5
5
  export { createApi, serverApi } from "./http.js";
6
6
  export type {
7
7
  AccountPage, ApiResult, AttachmentUpload, AuditPage, ChannelOrder, ChannelPermission, ChannelPermissionTable,
8
- ConnectionDetails, Invitation, Permission, RoleDefinition, ServerCapabilities, ServerPreferences,
8
+ ConnectionDetails, Invitation, InvitationAnalytics, Permission, RoleDefinition, ServerCapabilities, ServerMetrics, ServerPreferences, StorageBudget,
9
9
  } from "./http.js";
10
10
  export { serverOrigin, webTransport } from "./transport.js";
11
11
  export type { ServerSocket, Transport } from "./transport.js";
package/src/session.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { offline, isSameDirectMessage, type DirectMessage, type DirectMessageChange, type DirectMessageReference, type DirectOperation, type Member, type MemberRequest, type Message, type Poke, type RelayResponse, type ScreenShare, type Snapshot, type VoiceState } from "./types.js";
1
+ import { offline, typingExpiryMs, type TypingEntry, isSameDirectMessage, type DirectMessage, type DirectMessageChange, type DirectMessageReference, type DirectOperation, type Member, type MemberRequest, type Message, type MessageMention, type MessageMentions, type MessageReaction, type PinCursor, type ReactionChange, type PinnedMessagePage, type MessageSearchPage, type SearchCursor, type Poke, type RelayResponse, type ScreenShare, type Snapshot, type VoiceState } from "./types.js";
2
2
  import { messageFrom, requestError } from "./errors.js";
3
3
  import { authenticateIdentity, type IdentityAuthentication } from "./auth.js";
4
4
  import { createApi } from "./http.js";
@@ -42,15 +42,29 @@ export interface ClientEvents {
42
42
  messageCreate: ChannelMessage;
43
43
  messageUpdate: { id: string; text: string; html?: string; editedAt: number };
44
44
  messageDelete: { id: string };
45
+ /** Another member mentioned this account or one of its roles. */
46
+ mention: MessageMention;
47
+ reaction: ReactionChange;
45
48
  directMessage: DirectMessage;
46
49
  directMessageChange: DirectMessageChange;
47
50
  poke: Poke;
51
+ /** Another account is typing in a followed channel or a direct conversation. */
52
+ typing: TypingEntry;
48
53
  raw: { type: string; payload: unknown };
49
54
  }
50
55
 
51
56
  export type ConnectOptions = Omit<IdentityAuthentication, "serverId" | "action"> &
52
57
  Partial<Pick<IdentityAuthentication, "serverId" | "action">>;
53
58
 
59
+ /** Applies a live reaction change; `me` only changes when the reacting account is this one. */
60
+ function applyReaction(reactions: MessageReaction[] = [], change: ReactionChange, mine: boolean) {
61
+ const current = reactions.find(({ emoji }) => emoji === change.emoji);
62
+ const me = mine ? change.reacted : current?.me ?? false;
63
+ const next = current ? reactions.map((entry) => entry === current ? { ...entry, count: change.count, me } : entry)
64
+ : [...reactions, { emoji: change.emoji, count: change.count, me }];
65
+ return next.filter(({ count }) => count > 0);
66
+ }
67
+
54
68
  /** Direct messages kept in the view while connected. Older ones remain in server history. */
55
69
  const directMessageLimit = 200;
56
70
  const channelMessageLimit = 200;
@@ -74,8 +88,11 @@ export class KoreroClient {
74
88
  private pending = new Map<number, (reply: Frame | null) => void>();
75
89
  private snapshot: Snapshot | null = null;
76
90
  private messages: Message[] = [];
91
+ private messageRevisions: Record<string, number> = {};
77
92
  private directMessages: DirectMessage[] = [];
78
93
  private lastPoke?: Poke;
94
+ private lastMention?: MessageMention;
95
+ private typingEntries: TypingEntry[] = [];
79
96
  /** A channel whose chat is followed without joining it. */
80
97
  private viewedChannelId: string | null = null;
81
98
  private viewRequest?: { channelId: string | null };
@@ -428,8 +445,12 @@ export class KoreroClient {
428
445
  }
429
446
 
430
447
  private show(directChange?: DirectMessageChange) {
431
- this.update({ ...offline, phase: "online", snapshot: this.snapshot, messages: this.messages, directMessages: this.directMessages,
432
- directChange, lastPoke: this.lastPoke, voice: this.voice?.voice ?? "idle", voiceError: this.voice?.error ?? null });
448
+ this.update({ ...offline, phase: "online", snapshot: this.snapshot, messages: this.messages, messageRevisions: this.messageRevisions, directMessages: this.directMessages,
449
+ directChange, lastPoke: this.lastPoke, lastMention: this.lastMention, typing: this.typingEntries, voice: this.voice?.voice ?? "idle", voiceError: this.voice?.error ?? null });
450
+ }
451
+
452
+ private reviseMessages(channelId?: string) {
453
+ if (channelId) this.messageRevisions = { ...this.messageRevisions, [channelId]: (this.messageRevisions[channelId] ?? 0) + 1 };
433
454
  }
434
455
 
435
456
  private event({ type, payload }: Frame) {
@@ -459,6 +480,7 @@ export class KoreroClient {
459
480
  const message = payload as Message;
460
481
  if (!message.channelId || !this.chatChannels().has(message.channelId) || this.messages.some(({ id }) => id === message.id)) return;
461
482
  this.messages = [...this.messages, message];
483
+ this.clearTyping(message.channelId, message.senderId);
462
484
  const inChannel = this.messages.filter(({ channelId }) => channelId === message.channelId);
463
485
  if (inChannel.length > channelMessageLimit) {
464
486
  const oldest = new Set(inChannel.slice(0, inChannel.length - channelMessageLimit));
@@ -469,16 +491,45 @@ export class KoreroClient {
469
491
  } else if (type === "direct.created") {
470
492
  const message = payload as DirectMessage;
471
493
  if (message.senderId !== snapshot.account.id && message.recipientId !== snapshot.account.id) return;
494
+ const typed = this.clearTyping(undefined, message.senderId);
472
495
  if (this.addDirectMessage(message)) {
473
496
  this.show();
474
497
  this.emit("directMessage", message);
475
- }
498
+ } else if (typed) this.show();
499
+ } else if (type === "chat.typing") {
500
+ const ping = payload as Omit<TypingEntry, "at">;
501
+ if (ping.accountId === snapshot.account.id) return;
502
+ const now = Date.now();
503
+ const entry: TypingEntry = { ...ping, at: now };
504
+ this.typingEntries = [...this.typingEntries.filter((current) => now - current.at <= typingExpiryMs &&
505
+ !(current.accountId === entry.accountId && current.channelId === entry.channelId)), entry];
506
+ this.show();
507
+ this.emit("typing", entry);
476
508
  } else if (type === "message.edited") {
477
- const edit = payload as { messageId: string; text: string; html?: string; editedAt: number };
509
+ const edit = payload as { channelId?: string; messageId: string; text: string; html?: string; editedAt: number; mentions?: MessageMentions };
478
510
  this.messages = this.messages.map((message) => message.id === edit.messageId
479
- ? { ...message, text: edit.text, html: edit.html, editedAt: edit.editedAt } : message);
511
+ ? { ...message, text: edit.text, html: edit.html, editedAt: edit.editedAt,
512
+ ...(edit.mentions ? { mentions: edit.mentions.accounts.length || edit.mentions.roles.length ? edit.mentions : undefined } : {}) } : message);
513
+ this.reviseMessages(edit.channelId);
480
514
  this.show();
481
515
  this.emit("messageUpdate", { id: edit.messageId, text: edit.text, html: edit.html, editedAt: edit.editedAt });
516
+ } else if (type === "message.reactionsChanged") {
517
+ const change = payload as ReactionChange;
518
+ const mine = change.accountId === snapshot.account.id;
519
+ this.messages = this.messages.map((message) => message.id === change.messageId
520
+ ? { ...message, reactions: applyReaction(message.reactions, change, mine) } : message);
521
+ this.reviseMessages(change.channelId);
522
+ this.show();
523
+ this.emit("reaction", change);
524
+ } else if (type === "message.mentioned") {
525
+ this.lastMention = payload as MessageMention;
526
+ this.show();
527
+ this.emit("mention", this.lastMention);
528
+ } else if (type === "message.pinChanged") {
529
+ const { channelId, messageId, pinnedAt } = payload as { channelId: string; messageId: string; pinnedAt: number | null };
530
+ this.messages = this.messages.map((message) => message.id === messageId ? { ...message, pinnedAt } : message);
531
+ this.reviseMessages(channelId);
532
+ this.show();
482
533
  } else if (type === "direct.edited") {
483
534
  const edit = payload as Partial<DirectMessage> & Pick<DirectMessage, "id" | "senderId" | "recipientId" | "nonce" | "ciphertext" | "signature" | "editedAt">;
484
535
  if (edit.senderId !== snapshot.account.id && edit.recipientId !== snapshot.account.id) return;
@@ -506,9 +557,10 @@ export class KoreroClient {
506
557
  this.show();
507
558
  this.emit("poke", poke);
508
559
  } else if (type === "message.deleted") {
509
- const { messageId } = payload as { messageId: string };
560
+ const { channelId, messageId } = payload as { channelId?: string; messageId: string };
510
561
  for (const deleted of this.loadedHistory.values()) deleted?.add(messageId);
511
562
  this.messages = this.messages.filter(({ id }) => id !== messageId);
563
+ this.reviseMessages(channelId);
512
564
  this.show();
513
565
  this.emit("messageDelete", { id: messageId });
514
566
  } else if (type === "media.reset") {
@@ -553,18 +605,40 @@ export class KoreroClient {
553
605
  this.voice?.setVolume(accountId, level);
554
606
  }
555
607
 
556
- async sendMessage(channelId: string, text: string, html?: string) {
557
- return this.rpc<{ messageId: string }>("message.send", { channelId, text, html });
608
+ async sendMessage(channelId: string, text: string, html?: string,
609
+ options: { replyTo?: string; mentions?: Partial<MessageMentions> } = {}) {
610
+ return this.rpc<{ messageId: string }>("message.send", { channelId, text, html, ...options });
558
611
  }
559
612
 
560
- async editMessage(messageId: string, text: string, html?: string) {
561
- await this.rpc("message.edit", { messageId, text, html });
613
+ async editMessage(messageId: string, text: string, html?: string, mentions?: Partial<MessageMentions>) {
614
+ await this.rpc("message.edit", { messageId, text, html, mentions });
615
+ }
616
+
617
+ async reactToMessage(channelId: string, messageId: string, emoji: string, reacted: boolean) {
618
+ await this.rpc("message.react", { channelId, messageId, emoji, reacted });
562
619
  }
563
620
 
564
621
  async deleteMessage(messageId: string) {
565
622
  await this.rpc("message.delete", { messageId });
566
623
  }
567
624
 
625
+ pinnedMessages(channelId: string, before?: PinCursor) {
626
+ return this.rpc<PinnedMessagePage>("message.pins", { channelId, before });
627
+ }
628
+
629
+ /** Searches a channel's stored messages, newest first. Pass the page's `next` as `before` to continue. */
630
+ searchMessages(channelId: string, query: string, before?: SearchCursor) {
631
+ return this.rpc<MessageSearchPage>("message.search", { channelId, query, before });
632
+ }
633
+
634
+ messageContext(channelId: string, messageId: string) {
635
+ return this.rpc<Message[]>("message.context", { channelId, messageId });
636
+ }
637
+
638
+ async setMessagePin(channelId: string, messageId: string, pinned: boolean) {
639
+ await this.rpc("message.pin", { channelId, messageId, pinned });
640
+ }
641
+
568
642
  screenRequest<T>(connectionId: string, channelId: string, kind: string, payload: unknown) {
569
643
  if (this.snapshot?.connectionId !== connectionId || this.snapshot?.channelId !== channelId) {
570
644
  return Promise.reject(new Error("The active channel changed."));
@@ -601,6 +675,19 @@ export class KoreroClient {
601
675
  return this.rpc("direct.delete", { accountId, id });
602
676
  }
603
677
 
678
+ /** Tells a channel's readers or a direct conversation partner that this account is typing. */
679
+ typing(target: { channelId: string } | { accountId: string }) {
680
+ return this.rpc("chat.typing", target);
681
+ }
682
+
683
+ /** Removes a typing entry once that account's message arrives; returns whether one was removed. */
684
+ private clearTyping(channelId: string | undefined, accountId: string) {
685
+ const remaining = this.typingEntries.filter((entry) => entry.accountId !== accountId || entry.channelId !== channelId);
686
+ if (remaining.length === this.typingEntries.length) return false;
687
+ this.typingEntries = remaining;
688
+ return true;
689
+ }
690
+
604
691
  poke(accountId: string, message?: string) {
605
692
  return this.rpc("direct.poke", { accountId, message });
606
693
  }
@@ -627,8 +714,11 @@ export class KoreroClient {
627
714
  this.media?.stop();
628
715
  this.snapshot = null;
629
716
  this.messages = [];
717
+ this.messageRevisions = {};
630
718
  this.directMessages = [];
631
719
  this.lastPoke = undefined;
720
+ this.lastMention = undefined;
721
+ this.typingEntries = [];
632
722
  this.viewedChannelId = null;
633
723
  this.viewRequest = undefined;
634
724
  this.loadedHistory.clear();