@lynkoria/client 0.2.0 → 0.3.1

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/CHANGELOG.md CHANGED
@@ -1,5 +1,29 @@
1
1
  # @lynkoria/client
2
2
 
3
+ ## 0.3.1
4
+
5
+ ### Patch Changes
6
+
7
+ - Updated dependencies
8
+ - @lynkoria/contracts@0.4.0
9
+
10
+ ## 0.3.0
11
+
12
+ ### Minor Changes
13
+
14
+ - Provider-neutral call media lifecycle in `@lynkoria/client`: `calls.preview()` gives a camera/microphone preview (level meter, device switching, self-view) that `calls.join({ preview })` publishes without asking for devices again; `session.attach(identity, source, element)` keeps participant video bound across republishing and reconnects; remote audio plays automatically (`canPlayAudio`/`startAudio()` handle autoplay blocking); `onDisconnected(reason)` reports `left`, `removed`, `ended`, `replaced` or `connection_lost`; `onLocalTrackEnded` reports devices that stop on their own; `startScreenShare(options)` takes audio, frame-rate and content-hint options; participants include `userId`, `deviceId` and `audioLevel`. `@lynkoria/react-native` picks up the messaging additions through its `@lynkoria/client` dependency.
15
+ - General-purpose messaging primitives. Conversations gain `description`, product `metadata`, `visibility` (`private` | `public`) and a read-only archive state; members gain `owner` | `admin` | `member` | `viewer` roles (viewers are read-only) and a per-user `notificationLevel`. Messages carry `mentions` (validated against current members), pins with sequenced `message.pinned`/`message.unpinned` events, one-level `thread` summaries, and events report their `actorId`. Conversation views include member counts, dm members, a `memberPreview` (up to 5 members for avatars), a `lastMessage` preview, and the caller's role, `unreadCount` and `mentionCount`.
16
+
17
+ - `@lynkoria/client`: `conversations.get`, `conversations.members`, `conversations.list({ scope: 'public', query })`, `conversations.setNotificationLevel`, `messages.get`, `messages.pin`/`unpin`/`pins`, `messages.search`, mentions on `send`/`edit`, and `history` filters (`threadId`, `topLevel`, `withAttachments`).
18
+ - `@lynkoria/server`: `conversations.get`/`update`/`members`/`setRole`, `addMembers(..., { role })`, `sessions.revoke`, `users.setPresence`, `users.removeFromTenant`, and an auto-batching, idempotent `import` API (`messages`, `readPositions`, `attachment`) for keys with the new `messaging:import` scope.
19
+ - `@lynkoria/react`: `useConversation(id, { threadId | topLevel })` keeps thread summaries current and shares ordering state between views; `send` accepts mentions; new `useConversationList` hook with live unread and mention badges.
20
+ - Messaging tokens accept `scopes` (`presence`, `public_conversations`) so products can mint restricted guest tokens.
21
+
22
+ ### Patch Changes
23
+
24
+ - Updated dependencies
25
+ - @lynkoria/contracts@0.3.0
26
+
3
27
  ## 0.2.0
4
28
 
5
29
  ### Minor Changes
package/README.md CHANGED
@@ -8,9 +8,14 @@ Your app never holds a service key. It gets short-lived tokens from **your** bac
8
8
  user and asks Lynkoria for them with [`@lynkoria/server`](https://www.npmjs.com/package/@lynkoria/server).
9
9
 
10
10
  **[Documentation](https://lynkoria.com/docs/)** · [Client SDK guide](https://lynkoria.com/docs/client-sdk/) ·
11
- [Quickstart](https://lynkoria.com/docs/quickstart/) · [Messaging](https://lynkoria.com/docs/messaging/) ·
11
+ [Getting started](https://lynkoria.com/docs/getting-started/) · [Messaging](https://lynkoria.com/docs/messaging/) ·
12
12
  [Calls](https://lynkoria.com/docs/calls/)
13
13
 
14
+ **Before you start:** your backend needs a Lynkoria project and service key from the
15
+ [Lynkoria Console](https://console.lynkoria.com), and your app's origin must be listed in the environment's
16
+ allowed origins. [Getting started](https://lynkoria.com/docs/getting-started/) walks through the setup and a
17
+ first test.
18
+
14
19
  ## Install
15
20
 
16
21
  ```bash
@@ -55,14 +60,14 @@ Calls-only apps need no messaging token: `createLynkoria()` with no options can
55
60
 
56
61
  ## What it covers
57
62
 
58
- | Area | API | Guide |
59
- | ------------- | ---------------------------------------------------------------------------------------- | ---------------------------------------------------------------------- |
60
- | Connection | `connect`, `disconnect`, `onConnectionState`, `onError` | [Client SDK](https://lynkoria.com/docs/client-sdk/) |
61
- | Messages | `messages.history`, `send`, `edit`, `delete`, `react`, `markRead`, `onMessage`, `onRead` | [Messaging](https://lynkoria.com/docs/messaging/) |
62
- | Conversations | `conversations.list`, `track`, `untrack`, `resync`, `onConversationUpdated` | [Messaging](https://lynkoria.com/docs/messaging/) |
63
- | Presence | `presence.subscribe`, `get`, `setStatus`, `typing.start`, `stop`, `onTyping` | [Presence](https://lynkoria.com/docs/presence/) |
64
- | Attachments | `attachments.upload`, `downloadUrl` | [File security](https://lynkoria.com/docs/file-security-and-scanning/) |
65
- | Calls | `calls.join`, mute, camera, screen share, devices, participants | [Calls](https://lynkoria.com/docs/calls/) |
63
+ | Area | API | Guide |
64
+ | ------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------- |
65
+ | Connection | `connect`, `disconnect`, `onConnectionState`, `onError` | [Client SDK](https://lynkoria.com/docs/client-sdk/) |
66
+ | Messages | `messages.history` (thread, top-level and file filters), `get`, `send` (mentions), `edit`, `delete`, `react`, `pin`, `unpin`, `pins`, `search`, `markRead`, `onMessage`, `onRead` | [Messaging](https://lynkoria.com/docs/messaging/) |
67
+ | Conversations | `conversations.list` (badges, public scope), `get`, `members`, `setNotificationLevel`, `track`, `untrack`, `resync`, `onConversationUpdated` | [Messaging](https://lynkoria.com/docs/messaging/) |
68
+ | Presence | `presence.subscribe`, `get`, `setStatus`, `typing.start`, `stop`, `onTyping` | [Presence](https://lynkoria.com/docs/presence/) |
69
+ | Attachments | `attachments.upload`, `downloadUrl` | [File security](https://lynkoria.com/docs/file-security-and-scanning/) |
70
+ | Calls | `calls.preview`, `calls.join`, mute, camera, screen share, devices, participants, `attach`, automatic audio, disconnect reasons | [Calls](https://lynkoria.com/docs/calls/) |
66
71
 
67
72
  ## Delivery guarantees
68
73
 
package/dist/index.d.ts CHANGED
@@ -1,27 +1,91 @@
1
- import { Attachment, CallSignalEvent, ConversationEvent, ConversationEventPage, ConversationReadEvent, ConversationUpdatedEvent, ErrorCode, LynkoriaError, LynkoriaError as LynkoriaError$1, ManualStatus, Message, NotificationPreferences, Presence, PushProvider, TypingEvent } from "@lynkoria/contracts";
1
+ import { Attachment, CallSignalEvent, ConversationEvent, ConversationEventPage, ConversationReadEvent, ConversationUpdatedEvent, ErrorCode, LynkoriaError, LynkoriaError as LynkoriaError$1, ManualStatus, Message, NotificationLevel, NotificationPreferences, Presence, PushProvider, TypingEvent } from "@lynkoria/contracts";
2
2
  import { Room, RoomConnectOptions, RoomOptions } from "livekit-client";
3
3
  export type * from "@lynkoria/contracts";
4
4
  type CallConnectionState = 'connecting' | 'connected' | 'reconnecting' | 'disconnected';
5
5
  type CallDeviceKind = 'audioinput' | 'audiooutput' | 'videoinput';
6
6
  type ConnectionQuality = 'excellent' | 'good' | 'poor' | 'lost' | 'unknown';
7
+ /** Video a participant can show: their camera or a shared screen. */
8
+ type CallVideoSource = 'camera' | 'screen_share';
9
+ /** Local capture that stopped on its own (device unplugged, permission revoked, capture ended). */
10
+ type CallLocalSource = 'camera' | 'microphone' | 'screen_share';
11
+ /**
12
+ * Why this device left the call. `left`: `leave()` was called. `removed`: the product removed the
13
+ * participant. `ended`: the call ended for everyone. `replaced`: the same identity joined elsewhere.
14
+ * `connection_lost`: network or server failure after reconnect attempts.
15
+ */
16
+ type CallEndReason = 'left' | 'removed' | 'ended' | 'replaced' | 'connection_lost';
7
17
  /** A snapshot of one participant, local or remote. */
8
18
  type CallParticipant = {
9
19
  /** Lynkoria media identity: `project:user:device`. */
10
20
  identity: string;
21
+ /** Your product's user ID (from the identity). */
22
+ userId: string;
23
+ /** The device ID the join token was issued for. */
24
+ deviceId: string;
11
25
  name: string;
12
26
  isLocal: boolean;
13
27
  isMicrophoneEnabled: boolean;
14
28
  isCameraEnabled: boolean;
15
29
  isScreenShareEnabled: boolean;
16
30
  isSpeaking: boolean;
31
+ /** 0–1, smoothed by the media server; 0 when muted. */
32
+ audioLevel: number;
17
33
  connectionQuality: ConnectionQuality;
18
34
  };
35
+ type ScreenShareOptions = {
36
+ /** Also share tab or system audio where the browser offers it. Default false. */
37
+ audio?: boolean;
38
+ /** Default 15. Lower values save bandwidth for documents; raise it for video. */
39
+ maxFrameRate?: number;
40
+ /** Default `detail` (text stays sharp); use `motion` for video. */
41
+ contentHint?: 'detail' | 'motion';
42
+ };
43
+ type CallPreviewOptions = {
44
+ /** Start with the microphone on (optionally a specific device). Default off. */
45
+ audio?: boolean | {
46
+ deviceId?: string;
47
+ };
48
+ /** Start with the camera on (optionally a specific device). Default off. */
49
+ video?: boolean | {
50
+ deviceId?: string;
51
+ };
52
+ };
53
+ /**
54
+ * Local camera and microphone before joining: show a self-view, a level meter and device pickers,
55
+ * then pass the preview to `join` so the same tracks are published without asking again.
56
+ */
57
+ type CallPreview = {
58
+ readonly isMicrophoneEnabled: boolean;
59
+ readonly isCameraEnabled: boolean;
60
+ /** Turns the device on or off. Rejects with the browser's NotAllowedError/NotFoundError. */
61
+ setMicrophoneEnabled(enabled: boolean, deviceId?: string): Promise<void>;
62
+ setCameraEnabled(enabled: boolean, deviceId?: string): Promise<void>;
63
+ switchDevice(kind: 'audioinput' | 'videoinput', deviceId: string): Promise<void>;
64
+ listDevices(kind: CallDeviceKind): Promise<MediaDeviceInfo[]>;
65
+ /** Current microphone input level, 0–1 (0 when off). Poll it for a meter. */
66
+ microphoneLevel(): number;
67
+ /** Shows the camera in a video element; returns a function that detaches it. */
68
+ attachCamera(element: HTMLVideoElement): () => void;
69
+ /** Fires when a device stops on its own (unplugged or permission revoked). */
70
+ onTrackEnded(listener: (source: 'camera' | 'microphone') => void): () => void;
71
+ /** Fires whenever the enabled state of the camera or microphone changes. */
72
+ onChange(listener: () => void): () => void;
73
+ /** Releases the devices. A preview passed to `join` is owned by the call afterwards. */
74
+ stop(): void;
75
+ };
19
76
  type JoinCallOptions = {
20
77
  /** Calls your product backend, which authorizes the user and asks Lynkoria for a join token. */
21
78
  getJoinToken: () => Promise<{
22
79
  url: string;
23
80
  token: string;
24
81
  }>;
82
+ /** Publish these preview tracks on join; a device that fails to publish is turned off, not fatal. */
83
+ preview?: CallPreview;
84
+ /**
85
+ * Play remote audio automatically through hidden audio elements (default true). When the
86
+ * browser blocks autoplay, `canPlayAudio` turns false until `startAudio()` runs from a user gesture.
87
+ */
88
+ autoPlayAudio?: boolean;
25
89
  roomOptions?: RoomOptions;
26
90
  connectOptions?: RoomConnectOptions;
27
91
  };
@@ -31,19 +95,37 @@ type CallSession = {
31
95
  readonly state: CallConnectionState;
32
96
  setMicrophoneEnabled(enabled: boolean): Promise<void>;
33
97
  setCameraEnabled(enabled: boolean): Promise<void>;
34
- startScreenShare(): Promise<void>;
98
+ startScreenShare(options?: ScreenShareOptions): Promise<void>;
35
99
  stopScreenShare(): Promise<void>;
36
100
  onStateChange(listener: (state: CallConnectionState) => void): () => void;
37
101
  /** Local participant first, then remote participants in join order. */
38
102
  readonly participants: CallParticipant[];
39
103
  /** Fires on joins, leaves, mute/camera/screen changes, active speakers and connection quality. */
40
104
  onParticipantsChange(listener: (participants: CallParticipant[]) => void): () => void;
105
+ /**
106
+ * Shows a participant's camera or screen in a video element and keeps it attached across
107
+ * republishing and reconnects. Returns a function that detaches it.
108
+ */
109
+ attach(identity: string, source: CallVideoSource, element: HTMLVideoElement): () => void;
110
+ /** False while the browser blocks audio autoplay; call `startAudio()` from a click. */
111
+ readonly canPlayAudio: boolean;
112
+ startAudio(): Promise<void>;
113
+ onAudioPlaybackChange(listener: (canPlay: boolean) => void): () => void;
114
+ /** Fires when local capture stops on its own; the source is already turned off. */
115
+ onLocalTrackEnded(listener: (source: CallLocalSource) => void): () => void;
116
+ /** Fires once when this device leaves the call, with the reason. */
117
+ onDisconnected(listener: (reason: CallEndReason) => void): () => void;
41
118
  /** Available devices of a kind (asks for permission first if labels are hidden). */
42
119
  listDevices(kind: CallDeviceKind): Promise<MediaDeviceInfo[]>;
43
120
  /** Switches the active microphone, camera or speaker for this call. */
44
121
  switchDevice(kind: CallDeviceKind, deviceId: string): Promise<void>;
45
122
  leave(): Promise<void>;
46
123
  };
124
+ /** `project:user:device`; product IDs never contain `:`. */
125
+ export declare function parseIdentity(identity: string): {
126
+ userId: string;
127
+ deviceId: string;
128
+ };
47
129
  /** What `getMessagingToken` resolves to: the token, or your backend's whole `messagingToken()` result. */
48
130
  type TokenResult = string | {
49
131
  token: string;
@@ -91,9 +173,22 @@ type IdempotentSend = {
91
173
  text?: string;
92
174
  attachmentIds?: string[];
93
175
  parentMessageId?: string;
176
+ /** User IDs mentioned in the text; each must be a member of the conversation. */
177
+ mentions?: string[];
94
178
  /** Stable per logical message; reuse it when retrying. Generated if omitted. */
95
179
  clientMessageId?: string;
96
180
  };
181
+ /** Narrows a history page; applies to scroll-back history (not to `after_seq` resync). */
182
+ export type HistoryOptions = {
183
+ beforeSeq?: number;
184
+ limit?: number;
185
+ /** Replies of one top-level message. */
186
+ threadId?: string;
187
+ /** Only top-level messages (no thread replies). */
188
+ topLevel?: boolean;
189
+ /** Only messages with ready attachments (a file gallery). */
190
+ withAttachments?: boolean;
191
+ };
97
192
  export type LynkoriaClient = ReturnType<typeof createLynkoria>;
98
193
  export declare function createLynkoria(opts: LynkoriaClientOptions): {
99
194
  connect: () => void;
@@ -114,9 +209,15 @@ export declare function createLynkoria(opts: LynkoriaClientOptions): {
114
209
  create(): string;
115
210
  };
116
211
  conversations: {
212
+ /**
213
+ * The user's conversations by recent activity, with unread and mention badges. With
214
+ * `scope: 'public'`, the tenant's public conversations (token needs `public_conversations`).
215
+ */
117
216
  list: (params?: {
118
217
  limit?: number;
119
218
  cursor?: string;
219
+ scope?: 'member' | 'public';
220
+ query?: string;
120
221
  }) => Promise<{
121
222
  items: {
122
223
  id: string;
@@ -124,13 +225,74 @@ export declare function createLynkoria(opts: LynkoriaClientOptions): {
124
225
  type: "channel" | "dm" | "group" | "session";
125
226
  productConversationId: string | null;
126
227
  title: string | null;
228
+ description: string | null;
229
+ metadata: Record<string, unknown>;
230
+ visibility: "private" | "public";
231
+ archivedAt: string | null;
232
+ memberCount: number;
233
+ memberIds?: string[] | undefined;
234
+ memberPreview: string[];
235
+ lastMessage: {
236
+ id: string;
237
+ senderId: string;
238
+ body: string | null;
239
+ hasAttachments: boolean;
240
+ createdAt: string;
241
+ } | null;
127
242
  lastSeq: number;
128
243
  lastMessageAt: string | null;
129
244
  createdAt: string;
130
245
  readSeq?: number | undefined;
246
+ role?: "admin" | "member" | "owner" | "viewer" | null | undefined;
247
+ notificationLevel?: "all" | "mentions" | "none" | undefined;
248
+ unreadCount?: number | undefined;
249
+ mentionCount?: number | undefined;
250
+ }[];
251
+ nextCursor: string | null;
252
+ }>;
253
+ get: (conversationId: string) => Promise<{
254
+ id: string;
255
+ tenantId: string;
256
+ type: "channel" | "dm" | "group" | "session";
257
+ productConversationId: string | null;
258
+ title: string | null;
259
+ description: string | null;
260
+ metadata: Record<string, unknown>;
261
+ visibility: "private" | "public";
262
+ archivedAt: string | null;
263
+ memberCount: number;
264
+ memberIds?: string[] | undefined;
265
+ memberPreview: string[];
266
+ lastMessage: {
267
+ id: string;
268
+ senderId: string;
269
+ body: string | null;
270
+ hasAttachments: boolean;
271
+ createdAt: string;
272
+ } | null;
273
+ lastSeq: number;
274
+ lastMessageAt: string | null;
275
+ createdAt: string;
276
+ readSeq?: number | undefined;
277
+ role?: "admin" | "member" | "owner" | "viewer" | null | undefined;
278
+ notificationLevel?: "all" | "mentions" | "none" | undefined;
279
+ unreadCount?: number | undefined;
280
+ mentionCount?: number | undefined;
281
+ }>;
282
+ members: (conversationId: string, params?: {
283
+ limit?: number;
284
+ cursor?: string;
285
+ }) => Promise<{
286
+ items: {
287
+ userId: string;
288
+ role: "admin" | "member" | "owner" | "viewer";
289
+ joinedAt: string;
290
+ readSeq: number;
131
291
  }[];
132
292
  nextCursor: string | null;
133
293
  }>;
294
+ /** The user's own notification level: `all`, `mentions` or `none`. */
295
+ setNotificationLevel: (conversationId: string, level: NotificationLevel) => Promise<void>;
134
296
  /** Start realtime ordering for a conversation from a known seq (e.g. after loading history). */
135
297
  track: (conversationId: string, lastSeq: number) => void;
136
298
  untrack: (conversationId: string) => void;
@@ -138,12 +300,9 @@ export declare function createLynkoria(opts: LynkoriaClientOptions): {
138
300
  };
139
301
  messages: {
140
302
  /** Latest history page (or older, with `beforeSeq`). Also starts tracking the conversation. */
141
- history(conversationId: string, params?: {
142
- beforeSeq?: number;
143
- limit?: number;
144
- }): Promise<ConversationEventPage>;
303
+ history(conversationId: string, params?: HistoryOptions): Promise<ConversationEventPage>;
145
304
  send(input: IdempotentSend): Promise<Message>;
146
- edit: (messageId: string, text: string) => Promise<{
305
+ get: (messageId: string) => Promise<{
147
306
  id: string;
148
307
  conversationId: string;
149
308
  seq: number;
@@ -163,11 +322,134 @@ export declare function createLynkoria(opts: LynkoriaClientOptions): {
163
322
  userId: string;
164
323
  emoji: string;
165
324
  }[];
325
+ mentions: string[];
166
326
  parentMessageId: string | null;
327
+ thread: {
328
+ replyCount: number;
329
+ lastReplyAt: string | null;
330
+ participantIds: string[];
331
+ } | null;
332
+ pinnedAt: string | null;
333
+ pinnedBy: string | null;
167
334
  createdAt: string;
168
335
  editedAt: string | null;
169
336
  deletedAt: string | null;
170
337
  }>;
338
+ /** Replaces the text; pass `mentions` to replace them too (omitted keeps them). */
339
+ edit: (messageId: string, text: string, options?: {
340
+ mentions?: string[];
341
+ }) => Promise<{
342
+ id: string;
343
+ conversationId: string;
344
+ seq: number;
345
+ senderId: string;
346
+ clientMessageId: string;
347
+ kind: "system" | "text";
348
+ body: string | null;
349
+ attachments: {
350
+ id: string;
351
+ fileName: string;
352
+ mediaType: string;
353
+ size: number;
354
+ status: "pending" | "ready" | "rejected";
355
+ scanStatus?: "clean" | "failed" | "infected" | "not_scanned" | "pending" | "rejected" | undefined;
356
+ }[];
357
+ reactions: {
358
+ userId: string;
359
+ emoji: string;
360
+ }[];
361
+ mentions: string[];
362
+ parentMessageId: string | null;
363
+ thread: {
364
+ replyCount: number;
365
+ lastReplyAt: string | null;
366
+ participantIds: string[];
367
+ } | null;
368
+ pinnedAt: string | null;
369
+ pinnedBy: string | null;
370
+ createdAt: string;
371
+ editedAt: string | null;
372
+ deletedAt: string | null;
373
+ }>;
374
+ pin: (messageId: string) => Promise<void>;
375
+ unpin: (messageId: string) => Promise<void>;
376
+ /** Pinned messages of a conversation, most recently pinned first. */
377
+ pins: (conversationId: string) => Promise<{
378
+ id: string;
379
+ conversationId: string;
380
+ seq: number;
381
+ senderId: string;
382
+ clientMessageId: string;
383
+ kind: "system" | "text";
384
+ body: string | null;
385
+ attachments: {
386
+ id: string;
387
+ fileName: string;
388
+ mediaType: string;
389
+ size: number;
390
+ status: "pending" | "ready" | "rejected";
391
+ scanStatus?: "clean" | "failed" | "infected" | "not_scanned" | "pending" | "rejected" | undefined;
392
+ }[];
393
+ reactions: {
394
+ userId: string;
395
+ emoji: string;
396
+ }[];
397
+ mentions: string[];
398
+ parentMessageId: string | null;
399
+ thread: {
400
+ replyCount: number;
401
+ lastReplyAt: string | null;
402
+ participantIds: string[];
403
+ } | null;
404
+ pinnedAt: string | null;
405
+ pinnedBy: string | null;
406
+ createdAt: string;
407
+ editedAt: string | null;
408
+ deletedAt: string | null;
409
+ }[]>;
410
+ /** Full-text search across conversations the user can read, newest first. */
411
+ search: (params: {
412
+ query: string;
413
+ conversationId?: string;
414
+ senderId?: string;
415
+ cursor?: string;
416
+ limit?: number;
417
+ }) => Promise<{
418
+ items: {
419
+ id: string;
420
+ conversationId: string;
421
+ seq: number;
422
+ senderId: string;
423
+ clientMessageId: string;
424
+ kind: "system" | "text";
425
+ body: string | null;
426
+ attachments: {
427
+ id: string;
428
+ fileName: string;
429
+ mediaType: string;
430
+ size: number;
431
+ status: "pending" | "ready" | "rejected";
432
+ scanStatus?: "clean" | "failed" | "infected" | "not_scanned" | "pending" | "rejected" | undefined;
433
+ }[];
434
+ reactions: {
435
+ userId: string;
436
+ emoji: string;
437
+ }[];
438
+ mentions: string[];
439
+ parentMessageId: string | null;
440
+ thread: {
441
+ replyCount: number;
442
+ lastReplyAt: string | null;
443
+ participantIds: string[];
444
+ } | null;
445
+ pinnedAt: string | null;
446
+ pinnedBy: string | null;
447
+ createdAt: string;
448
+ editedAt: string | null;
449
+ deletedAt: string | null;
450
+ }[];
451
+ nextCursor: string | null;
452
+ }>;
171
453
  delete: (messageId: string) => Promise<void>;
172
454
  react: (messageId: string, emoji: string) => Promise<void>;
173
455
  unreact: (messageId: string, emoji: string) => Promise<void>;
@@ -200,6 +482,8 @@ export declare function createLynkoria(opts: LynkoriaClientOptions): {
200
482
  };
201
483
  calls: {
202
484
  join: (options: JoinCallOptions) => Promise<CallSession>;
485
+ /** Camera/microphone preview before joining; pass it to `join({ preview })`. */
486
+ preview: (options?: CallPreviewOptions) => Promise<CallPreview>;
203
487
  };
204
488
  /** Device push registration for native apps (React Native uses this client for messaging). */
205
489
  push: {
@@ -226,4 +510,4 @@ export declare function createLynkoria(opts: LynkoriaClientOptions): {
226
510
  setPreferences: (prefs: NotificationPreferences) => Promise<void>;
227
511
  };
228
512
  };
229
- export { type CallConnectionState, type CallDeviceKind, type CallParticipant, type CallSession, type ConnectionQuality, ErrorCode, type JoinCallOptions, LynkoriaError, type SequenceDecision };
513
+ export { type CallConnectionState, type CallDeviceKind, type CallEndReason, type CallLocalSource, type CallParticipant, type CallPreview, type CallPreviewOptions, type CallSession, type CallVideoSource, type ConnectionQuality, ErrorCode, type JoinCallOptions, LynkoriaError, type ScreenShareOptions, type SequenceDecision };
package/dist/index.js CHANGED
@@ -17,14 +17,169 @@ var Emitter = class {
17
17
  }
18
18
  };
19
19
  // src/media.ts
20
+ /** `project:user:device`; product IDs never contain `:`. */
21
+ function parseIdentity(identity) {
22
+ const [, userId = identity, deviceId = ""] = identity.split(":");
23
+ return {
24
+ userId,
25
+ deviceId
26
+ };
27
+ }
28
+ const REASONS = {
29
+ 1: "left",
30
+ 2: "replaced",
31
+ 4: "removed",
32
+ 5: "ended",
33
+ 10: "ended"
34
+ };
35
+ const endReason = (reason) => reason !== void 0 && REASONS[reason] || "connection_lost";
36
+ const deviceOption = (v) => typeof v === "object" ? v.deviceId : void 0;
37
+ var Listeners = class {
38
+ set = /* @__PURE__ */ new Set();
39
+ on(fn) {
40
+ this.set.add(fn);
41
+ return () => void this.set.delete(fn);
42
+ }
43
+ emit(value) {
44
+ for (const fn of this.set) try {
45
+ fn(value);
46
+ } catch {}
47
+ }
48
+ };
20
49
  /**
21
50
  * Internal media adapter (plan §10.3 rule 6): the only place that talks to livekit-client, loaded
22
51
  * lazily so messaging-only apps never download the media engine. The server returns the media URL
23
52
  * with every token, so no LiveKit hostname or region is baked into apps.
24
53
  */
25
54
  var LiveKitMediaProvider = class {
55
+ lk = null;
56
+ load() {
57
+ return this.lk ??= import("livekit-client");
58
+ }
59
+ async preview(options = {}) {
60
+ const lk = await this.load();
61
+ let audio = null;
62
+ let video = null;
63
+ let analyser = null;
64
+ let owned = true;
65
+ const ended = new Listeners();
66
+ const changed = new Listeners();
67
+ const elements = /* @__PURE__ */ new Set();
68
+ const releaseAudio = () => {
69
+ analyser?.cleanup();
70
+ analyser = null;
71
+ audio?.stop();
72
+ audio = null;
73
+ };
74
+ const releaseVideo = () => {
75
+ for (const el of elements) video?.detach(el);
76
+ video?.stop();
77
+ video = null;
78
+ };
79
+ const watch = (track, source) => track.once(lk.TrackEvent.Ended, () => {
80
+ if (!owned) return;
81
+ if (source === "microphone" && audio === track) releaseAudio();
82
+ if (source === "camera" && video === track) releaseVideo();
83
+ ended.emit(source);
84
+ changed.emit();
85
+ });
86
+ const preview = {
87
+ get isMicrophoneEnabled() {
88
+ return audio !== null;
89
+ },
90
+ get isCameraEnabled() {
91
+ return video !== null;
92
+ },
93
+ async setMicrophoneEnabled(enabled, deviceId) {
94
+ if (!owned) return;
95
+ if (!enabled) {
96
+ releaseAudio();
97
+ changed.emit();
98
+ return;
99
+ }
100
+ if (audio) {
101
+ if (deviceId) await audio.setDeviceId(deviceId);
102
+ return;
103
+ }
104
+ const track = await lk.createLocalAudioTrack({
105
+ ...deviceId ? { deviceId } : {},
106
+ echoCancellation: true,
107
+ noiseSuppression: true,
108
+ autoGainControl: true
109
+ });
110
+ if (!owned) return track.stop();
111
+ audio = track;
112
+ analyser = lk.createAudioAnalyser(track, { cloneTrack: true });
113
+ watch(track, "microphone");
114
+ changed.emit();
115
+ },
116
+ async setCameraEnabled(enabled, deviceId) {
117
+ if (!owned) return;
118
+ if (!enabled) {
119
+ releaseVideo();
120
+ changed.emit();
121
+ return;
122
+ }
123
+ if (video) {
124
+ if (deviceId) await video.setDeviceId(deviceId);
125
+ return;
126
+ }
127
+ const track = await lk.createLocalVideoTrack({
128
+ ...deviceId ? { deviceId } : {},
129
+ resolution: lk.VideoPresets.h720.resolution
130
+ });
131
+ if (!owned) return track.stop();
132
+ video = track;
133
+ for (const el of elements) track.attach(el);
134
+ watch(track, "camera");
135
+ changed.emit();
136
+ },
137
+ async switchDevice(kind, deviceId) {
138
+ await (kind === "audioinput" ? audio : video)?.setDeviceId(deviceId);
139
+ },
140
+ listDevices: (kind) => lk.Room.getLocalDevices(kind),
141
+ microphoneLevel: () => audio && analyser ? analyser.calculateVolume() : 0,
142
+ attachCamera(element) {
143
+ elements.add(element);
144
+ video?.attach(element);
145
+ return () => {
146
+ elements.delete(element);
147
+ video?.detach(element);
148
+ };
149
+ },
150
+ onTrackEnded: (listener) => ended.on(listener),
151
+ onChange: (listener) => changed.on(() => listener()),
152
+ stop() {
153
+ if (!owned) return;
154
+ releaseAudio();
155
+ releaseVideo();
156
+ owned = false;
157
+ },
158
+ take() {
159
+ analyser?.cleanup();
160
+ analyser = null;
161
+ for (const el of elements) video?.detach(el);
162
+ const tracks = {
163
+ audio,
164
+ video
165
+ };
166
+ audio = null;
167
+ video = null;
168
+ owned = false;
169
+ return tracks;
170
+ }
171
+ };
172
+ try {
173
+ if (options.audio) await preview.setMicrophoneEnabled(true, deviceOption(options.audio));
174
+ if (options.video) await preview.setCameraEnabled(true, deviceOption(options.video));
175
+ } catch (err) {
176
+ preview.stop();
177
+ throw err;
178
+ }
179
+ return preview;
180
+ }
26
181
  async join(opts) {
27
- const { Room, RoomEvent, ConnectionState } = await import("livekit-client");
182
+ const { Room, RoomEvent, ConnectionState, Track, TrackEvent } = await this.load();
28
183
  const { url, token } = await opts.getJoinToken();
29
184
  const room = new Room({
30
185
  adaptiveStream: true,
@@ -32,23 +187,112 @@ var LiveKitMediaProvider = class {
32
187
  ...opts.roomOptions
33
188
  });
34
189
  const map = (s) => s === ConnectionState.Connected ? "connected" : s === ConnectionState.Connecting ? "connecting" : s === ConnectionState.Reconnecting || s === ConnectionState.SignalReconnecting ? "reconnecting" : "disconnected";
190
+ const localEnded = new Listeners();
191
+ const disconnected = new Listeners();
192
+ const playback = new Listeners();
193
+ let endedWith = null;
194
+ const autoPlay = opts.autoPlayAudio !== false && typeof document !== "undefined";
195
+ const audioElements = /* @__PURE__ */ new Map();
196
+ const container = autoPlay ? document.createElement("div") : null;
197
+ if (container) {
198
+ container.hidden = true;
199
+ container.dataset.lynkoriaAudio = "";
200
+ document.body.append(container);
201
+ }
202
+ const playAudio = (track) => {
203
+ if (!container || track.kind !== Track.Kind.Audio || audioElements.has(track)) return;
204
+ const el = track.attach();
205
+ container.append(el);
206
+ audioElements.set(track, el);
207
+ };
208
+ const stopAudio = (track) => {
209
+ const el = audioElements.get(track);
210
+ if (!el) return;
211
+ track.detach(el);
212
+ el.remove();
213
+ audioElements.delete(track);
214
+ };
215
+ const bindings = /* @__PURE__ */ new Map();
216
+ const shown = /* @__PURE__ */ new Map();
217
+ const participantOf = (identity) => room.localParticipant.identity === identity ? room.localParticipant : room.remoteParticipants.get(identity);
218
+ const trackSource = (source) => source === "camera" ? Track.Source.Camera : Track.Source.ScreenShare;
219
+ const syncBindings = () => {
220
+ for (const [el, b] of bindings) {
221
+ const track = participantOf(b.identity)?.getTrackPublication(trackSource(b.source))?.track;
222
+ const current = shown.get(el);
223
+ if (current === track) continue;
224
+ current?.detach(el);
225
+ shown.delete(el);
226
+ if (track) {
227
+ track.attach(el);
228
+ shown.set(el, track);
229
+ }
230
+ }
231
+ };
232
+ const watchLocal = (track, source) => {
233
+ track?.once(TrackEvent.Ended, () => {
234
+ const lp = room.localParticipant;
235
+ (source === "microphone" ? lp.setMicrophoneEnabled(false) : source === "camera" ? lp.setCameraEnabled(false) : lp.setScreenShareEnabled(false)).catch(() => void 0).finally(() => localEnded.emit(source));
236
+ });
237
+ };
238
+ const sourceName = (s) => s === Track.Source.Microphone ? "microphone" : s === Track.Source.Camera ? "camera" : s === Track.Source.ScreenShare ? "screen_share" : null;
239
+ room.on(RoomEvent.TrackSubscribed, (track) => {
240
+ playAudio(track);
241
+ syncBindings();
242
+ }).on(RoomEvent.TrackUnsubscribed, (track) => {
243
+ stopAudio(track);
244
+ syncBindings();
245
+ }).on(RoomEvent.LocalTrackPublished, (pub) => {
246
+ const name = sourceName(pub.source);
247
+ if (name) watchLocal(pub.track, name);
248
+ syncBindings();
249
+ }).on(RoomEvent.LocalTrackUnpublished, syncBindings).on(RoomEvent.TrackMuted, syncBindings).on(RoomEvent.TrackUnmuted, syncBindings).on(RoomEvent.AudioPlaybackStatusChanged, () => playback.emit(room.canPlaybackAudio)).on(RoomEvent.Disconnected, (reason) => {
250
+ endedWith ??= endReason(reason);
251
+ for (const track of audioElements.keys()) stopAudio(track);
252
+ container?.remove();
253
+ for (const [el, track] of shown) track.detach(el);
254
+ shown.clear();
255
+ disconnected.emit(endedWith);
256
+ });
35
257
  try {
36
258
  await room.connect(url, token, opts.connectOptions);
37
259
  } catch (error) {
38
260
  await room.disconnect();
261
+ container?.remove();
39
262
  throw error;
40
263
  }
264
+ for (const p of room.remoteParticipants.values()) for (const pub of p.trackPublications.values()) if (pub.track) playAudio(pub.track);
265
+ if (opts.preview) {
266
+ const { audio, video } = opts.preview.take();
267
+ const publish = async (track, source) => {
268
+ if (!track) return;
269
+ try {
270
+ await room.localParticipant.publishTrack(track, { source });
271
+ } catch {
272
+ track.stop();
273
+ localEnded.emit(source === Track.Source.Microphone ? "microphone" : "camera");
274
+ }
275
+ };
276
+ await publish(audio, Track.Source.Microphone);
277
+ await publish(video, Track.Source.Camera);
278
+ }
41
279
  const lp = () => room.localParticipant;
42
- const snapshot = () => [room.localParticipant, ...room.remoteParticipants.values()].map((p) => ({
43
- identity: p.identity,
44
- name: p.name || p.identity,
45
- isLocal: p === room.localParticipant,
46
- isMicrophoneEnabled: p.isMicrophoneEnabled,
47
- isCameraEnabled: p.isCameraEnabled,
48
- isScreenShareEnabled: p.isScreenShareEnabled,
49
- isSpeaking: p.isSpeaking,
50
- connectionQuality: p.connectionQuality
51
- }));
280
+ const snapshot = () => [room.localParticipant, ...room.remoteParticipants.values()].map((p) => {
281
+ const { userId, deviceId } = parseIdentity(p.identity);
282
+ return {
283
+ identity: p.identity,
284
+ userId,
285
+ deviceId,
286
+ name: p.name || p.identity,
287
+ isLocal: p === room.localParticipant,
288
+ isMicrophoneEnabled: p.isMicrophoneEnabled,
289
+ isCameraEnabled: p.isCameraEnabled,
290
+ isScreenShareEnabled: p.isScreenShareEnabled,
291
+ isSpeaking: p.isSpeaking,
292
+ audioLevel: p.isMicrophoneEnabled ? p.audioLevel : 0,
293
+ connectionQuality: p.connectionQuality
294
+ };
295
+ });
52
296
  const participantEvents = [
53
297
  RoomEvent.ParticipantConnected,
54
298
  RoomEvent.ParticipantDisconnected,
@@ -69,7 +313,15 @@ var LiveKitMediaProvider = class {
69
313
  },
70
314
  setMicrophoneEnabled: async (enabled) => void await lp().setMicrophoneEnabled(enabled),
71
315
  setCameraEnabled: async (enabled) => void await lp().setCameraEnabled(enabled),
72
- startScreenShare: async () => void await lp().setScreenShareEnabled(true),
316
+ startScreenShare: async (options = {}) => void await lp().setScreenShareEnabled(true, {
317
+ audio: options.audio ?? false,
318
+ contentHint: options.contentHint ?? "detail",
319
+ resolution: {
320
+ width: 1920,
321
+ height: 1080,
322
+ frameRate: options.maxFrameRate ?? 15
323
+ }
324
+ }),
73
325
  stopScreenShare: async () => void await lp().setScreenShareEnabled(false),
74
326
  onStateChange: (listener) => {
75
327
  const handler = (s) => listener(map(s));
@@ -86,9 +338,37 @@ var LiveKitMediaProvider = class {
86
338
  for (const e of participantEvents) room.off(e, handler);
87
339
  };
88
340
  },
341
+ attach(identity, source, element) {
342
+ bindings.set(element, {
343
+ identity,
344
+ source
345
+ });
346
+ syncBindings();
347
+ return () => {
348
+ bindings.delete(element);
349
+ shown.get(element)?.detach(element);
350
+ shown.delete(element);
351
+ };
352
+ },
353
+ get canPlayAudio() {
354
+ return room.canPlaybackAudio;
355
+ },
356
+ startAudio: () => room.startAudio(),
357
+ onAudioPlaybackChange: (listener) => playback.on(listener),
358
+ onLocalTrackEnded: (listener) => localEnded.on(listener),
359
+ onDisconnected(listener) {
360
+ if (endedWith) {
361
+ listener(endedWith);
362
+ return () => void 0;
363
+ }
364
+ return disconnected.on(listener);
365
+ },
89
366
  listDevices: (kind) => Room.getLocalDevices(kind),
90
367
  switchDevice: async (kind, deviceId) => void await room.switchActiveDevice(kind, deviceId),
91
- leave: () => room.disconnect()
368
+ leave: async () => {
369
+ endedWith ??= "left";
370
+ await room.disconnect();
371
+ }
92
372
  };
93
373
  }
94
374
  };
@@ -207,6 +487,7 @@ function defaultIds() {
207
487
  } };
208
488
  }
209
489
  const conv = (id) => `/v1/conversations/${encodeURIComponent(id)}`;
490
+ const msg = (id) => `/v1/messages/${encodeURIComponent(id)}`;
210
491
  const jitter = (ms) => ms * (.8 + Math.random() * .4);
211
492
  function createLynkoria(opts) {
212
493
  const doFetch = opts.fetch ?? ((...args) => fetch(...args));
@@ -374,6 +655,8 @@ function createLynkoria(opts) {
374
655
  "message:created",
375
656
  "message:updated",
376
657
  "message:deleted",
658
+ "message:pinned",
659
+ "message:unpinned",
377
660
  "reaction:added",
378
661
  "reaction:removed"
379
662
  ]) s.on(name, deliver);
@@ -464,12 +747,27 @@ function createLynkoria(opts) {
464
747
  onConversationUpdated: (l) => conversationEvents.on(l),
465
748
  ids,
466
749
  conversations: {
750
+ /**
751
+ * The user's conversations by recent activity, with unread and mention badges. With
752
+ * `scope: 'public'`, the tenant's public conversations (token needs `public_conversations`).
753
+ */
467
754
  list: (params = {}) => {
468
755
  const q = new URLSearchParams();
469
756
  if (params.limit) q.set("limit", String(params.limit));
470
757
  if (params.cursor) q.set("cursor", params.cursor);
758
+ if (params.scope) q.set("scope", params.scope);
759
+ if (params.query) q.set("q", params.query);
471
760
  return request("GET", `/v1/conversations${q.size ? `?${q}` : ""}`);
472
761
  },
762
+ get: (conversationId) => request("GET", conv(conversationId)),
763
+ members: (conversationId, params = {}) => {
764
+ const q = new URLSearchParams();
765
+ if (params.limit) q.set("limit", String(params.limit));
766
+ if (params.cursor) q.set("cursor", params.cursor);
767
+ return request("GET", `${conv(conversationId)}/members${q.size ? `?${q}` : ""}`);
768
+ },
769
+ /** The user's own notification level: `all`, `mentions` or `none`. */
770
+ setNotificationLevel: (conversationId, level) => request("PUT", `${conv(conversationId)}/notification-level`, { level }),
473
771
  /** Start realtime ordering for a conversation from a known seq (e.g. after loading history). */
474
772
  track: (conversationId, lastSeq) => tracker.set(conversationId, lastSeq),
475
773
  untrack: (conversationId) => tracker.forget(conversationId),
@@ -480,6 +778,9 @@ function createLynkoria(opts) {
480
778
  async history(conversationId, params = {}) {
481
779
  const q = new URLSearchParams({ limit: String(params.limit ?? 50) });
482
780
  q.set("before_seq", String(params.beforeSeq ?? Number.MAX_SAFE_INTEGER));
781
+ if (params.threadId) q.set("thread", params.threadId);
782
+ if (params.topLevel) q.set("top_level", "true");
783
+ if (params.withAttachments) q.set("with_attachments", "true");
483
784
  const page = await request("GET", `${conv(conversationId)}/messages?${q}`);
484
785
  if (params.beforeSeq === void 0) tracker.set(conversationId, page.lastSeq);
485
786
  return page;
@@ -489,7 +790,8 @@ function createLynkoria(opts) {
489
790
  clientMessageId: input.clientMessageId ?? ids.create(),
490
791
  text: input.text ?? "",
491
792
  attachmentIds: input.attachmentIds ?? [],
492
- ...input.parentMessageId ? { parentMessageId: input.parentMessageId } : {}
793
+ ...input.parentMessageId ? { parentMessageId: input.parentMessageId } : {},
794
+ ...input.mentions?.length ? { mentions: input.mentions } : {}
493
795
  };
494
796
  if (socket?.connected) try {
495
797
  return (await emitAck((s) => s.timeout(1e4).emitWithAck("message:send", {
@@ -501,7 +803,25 @@ function createLynkoria(opts) {
501
803
  }
502
804
  return (await request("POST", `${conv(input.conversationId)}/messages`, body)).message;
503
805
  },
504
- edit: (messageId, text) => request("PATCH", `/v1/messages/${encodeURIComponent(messageId)}`, { text }),
806
+ get: (messageId) => request("GET", msg(messageId)),
807
+ /** Replaces the text; pass `mentions` to replace them too (omitted keeps them). */
808
+ edit: (messageId, text, options = {}) => request("PATCH", msg(messageId), {
809
+ text,
810
+ ...options.mentions ? { mentions: options.mentions } : {}
811
+ }),
812
+ pin: (messageId) => request("POST", `${msg(messageId)}/pin`),
813
+ unpin: (messageId) => request("DELETE", `${msg(messageId)}/pin`),
814
+ /** Pinned messages of a conversation, most recently pinned first. */
815
+ pins: async (conversationId) => (await request("GET", `${conv(conversationId)}/pins`)).items,
816
+ /** Full-text search across conversations the user can read, newest first. */
817
+ search: (params) => {
818
+ const q = new URLSearchParams({ q: params.query });
819
+ if (params.conversationId) q.set("conversation_id", params.conversationId);
820
+ if (params.senderId) q.set("sender_id", params.senderId);
821
+ if (params.cursor) q.set("cursor", params.cursor);
822
+ if (params.limit) q.set("limit", String(params.limit));
823
+ return request("GET", `/v1/messages/search?${q}`);
824
+ },
505
825
  delete: (messageId) => request("DELETE", `/v1/messages/${encodeURIComponent(messageId)}`),
506
826
  react: (messageId, emoji) => request("POST", `/v1/messages/${encodeURIComponent(messageId)}/reactions`, { emoji }),
507
827
  unreact: (messageId, emoji) => request("DELETE", `/v1/messages/${encodeURIComponent(messageId)}/reactions/${encodeURIComponent(emoji)}`),
@@ -561,7 +881,11 @@ function createLynkoria(opts) {
561
881
  },
562
882
  downloadUrl: (attachmentId) => request("GET", `/v1/attachments/${encodeURIComponent(attachmentId)}/url`)
563
883
  },
564
- calls: { join: (options) => media.join(options) },
884
+ calls: {
885
+ join: (options) => media.join(options),
886
+ /** Camera/microphone preview before joining; pass it to `join({ preview })`. */
887
+ preview: (options) => media.preview(options)
888
+ },
565
889
  /** Device push registration for native apps (React Native uses this client for messaging). */
566
890
  push: {
567
891
  /** Call on every FCM/APNs/PushKit token refresh; idempotent. */
@@ -576,4 +900,4 @@ function createLynkoria(opts) {
576
900
  }
577
901
  };
578
902
  }
579
- export { DEFAULT_API_URL, ErrorCode, LynkoriaError, SequenceTracker, createLynkoria, jwtExpiry };
903
+ export { DEFAULT_API_URL, ErrorCode, LynkoriaError, SequenceTracker, createLynkoria, jwtExpiry, parseIdentity };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lynkoria/client",
3
- "version": "0.2.0",
3
+ "version": "0.3.1",
4
4
  "description": "Lynkoria communications client SDK (browser, Electron, React Native)",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",
@@ -23,7 +23,7 @@
23
23
  "access": "public"
24
24
  },
25
25
  "dependencies": {
26
- "@lynkoria/contracts": "^0.2.0",
26
+ "@lynkoria/contracts": "^0.4.0",
27
27
  "livekit-client": "^2.24.1",
28
28
  "socket.io-client": "^4.8.4"
29
29
  },