@lynkoria/client 0.1.1 → 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,49 @@
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
+
27
+ ## 0.2.0
28
+
29
+ ### Minor Changes
30
+
31
+ - 0ee4045: SDKs no longer need an API URL.
32
+
33
+ - `@lynkoria/server`: `baseUrl` is optional and defaults to `https://api.lynkoria.com` (exported as `DEFAULT_API_URL`); `createLynkoriaServer({ serviceKey })` is enough. It now throws in a browser or React Native app, where the service key would reach every user.
34
+ - `sessions.messagingToken()` returns `apiUrl` next to the token. Return the whole result from your token endpoint to the client: `@lynkoria/client` then needs no `baseUrl`, and only accepts an `https:` `apiUrl` (plain `http:` for localhost).
35
+ - `@lynkoria/client`: `getMessagingToken` is optional for calls-only apps; without it `connect()` does nothing and messaging methods reject with a clear error.
36
+
37
+ **Upgrade:** remove `baseUrl` from `createLynkoria` and `createLynkoriaServer` (existing values keep working), and return the full `messagingToken()` result instead of only `token`.
38
+
39
+ **Breaking for type users:** `MessagingTokenResponse` in `@lynkoria/contracts` has a required `apiUrl`. Code that constructs that type by hand (test mocks, fakes) must add it.
40
+
41
+ ### Patch Changes
42
+
43
+ - Updated dependencies [e96fe9d]
44
+ - Updated dependencies [0ee4045]
45
+ - @lynkoria/contracts@0.2.0
46
+
3
47
  ## 0.1.1
4
48
 
5
49
  ### Patch 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
@@ -26,7 +31,7 @@ apps do not download the media engine.
26
31
  import { createLynkoria } from '@lynkoria/client';
27
32
 
28
33
  const rtc = createLynkoria({
29
- baseUrl: 'https://api.lynkoria.com',
34
+ // Return your backend's whole messagingToken() result; it carries the API URL.
30
35
  getMessagingToken: () => myBackend.fetchLynkoriaMessagingToken(),
31
36
  });
32
37
 
@@ -50,16 +55,19 @@ await session.setMicrophoneEnabled(false);
50
55
  await session.startScreenShare();
51
56
  ```
52
57
 
58
+ Calls-only apps need no messaging token: `createLynkoria()` with no options can join calls, and
59
+ `connect()` does nothing until you add `getMessagingToken`.
60
+
53
61
  ## What it covers
54
62
 
55
- | Area | API | Guide |
56
- | ------------- | ---------------------------------------------------------------------------------------- | ---------------------------------------------------------------------- |
57
- | Connection | `connect`, `disconnect`, `onConnectionState`, `onError` | [Client SDK](https://lynkoria.com/docs/client-sdk/) |
58
- | Messages | `messages.history`, `send`, `edit`, `delete`, `react`, `markRead`, `onMessage`, `onRead` | [Messaging](https://lynkoria.com/docs/messaging/) |
59
- | Conversations | `conversations.list`, `track`, `untrack`, `resync`, `onConversationUpdated` | [Messaging](https://lynkoria.com/docs/messaging/) |
60
- | Presence | `presence.subscribe`, `get`, `setStatus`, `typing.start`, `stop`, `onTyping` | [Presence](https://lynkoria.com/docs/presence/) |
61
- | Attachments | `attachments.upload`, `downloadUrl` | [File security](https://lynkoria.com/docs/file-security-and-scanning/) |
62
- | 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/) |
63
71
 
64
72
  ## Delivery guarantees
65
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,22 +95,42 @@ 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
+ };
129
+ /** What `getMessagingToken` resolves to: the token, or your backend's whole `messagingToken()` result. */
47
130
  type TokenResult = string | {
48
131
  token: string;
49
132
  expiresAt?: string;
133
+ apiUrl?: string;
50
134
  };
51
135
  /** Reads `exp` from a JWT without verifying it (verification happens on the server). */
52
136
  export declare function jwtExpiry(token: string): number | null;
@@ -65,11 +149,17 @@ export declare class SequenceTracker {
65
149
  decide(conversationId: string, seq: number): SequenceDecision;
66
150
  }
67
151
  export type ConnectionState = 'idle' | 'connecting' | 'connected' | 'reconnecting' | 'disconnected';
152
+ /** The Lynkoria API, used until a messaging token reports its `apiUrl`. */
153
+ export declare const DEFAULT_API_URL = "https://api.lynkoria.com";
68
154
  export type LynkoriaClientOptions = {
69
- /** e.g. https://api.lynkoria.com */
70
- baseUrl: string;
71
- /** Calls your product backend, which mints a Lynkoria messaging token with its service key. */
72
- getMessagingToken: () => Promise<TokenResult>;
155
+ /** Overrides the API origin from the token response; for local development and tests. */
156
+ baseUrl?: string;
157
+ /**
158
+ * Calls your product backend, which mints a Lynkoria messaging token with its service key.
159
+ * Return the whole `messagingToken()` result so the client also learns `apiUrl`. Required for
160
+ * messaging, presence, attachments and push; calls-only apps can omit it.
161
+ */
162
+ getMessagingToken?: () => Promise<TokenResult>;
73
163
  /** Injectable platform adapters (React Native: no `window`, maybe no `crypto.randomUUID`). */
74
164
  ids?: {
75
165
  create(): string;
@@ -83,9 +173,22 @@ type IdempotentSend = {
83
173
  text?: string;
84
174
  attachmentIds?: string[];
85
175
  parentMessageId?: string;
176
+ /** User IDs mentioned in the text; each must be a member of the conversation. */
177
+ mentions?: string[];
86
178
  /** Stable per logical message; reuse it when retrying. Generated if omitted. */
87
179
  clientMessageId?: string;
88
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
+ };
89
192
  export type LynkoriaClient = ReturnType<typeof createLynkoria>;
90
193
  export declare function createLynkoria(opts: LynkoriaClientOptions): {
91
194
  connect: () => void;
@@ -106,9 +209,15 @@ export declare function createLynkoria(opts: LynkoriaClientOptions): {
106
209
  create(): string;
107
210
  };
108
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
+ */
109
216
  list: (params?: {
110
217
  limit?: number;
111
218
  cursor?: string;
219
+ scope?: 'member' | 'public';
220
+ query?: string;
112
221
  }) => Promise<{
113
222
  items: {
114
223
  id: string;
@@ -116,13 +225,74 @@ export declare function createLynkoria(opts: LynkoriaClientOptions): {
116
225
  type: "channel" | "dm" | "group" | "session";
117
226
  productConversationId: string | null;
118
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;
119
242
  lastSeq: number;
120
243
  lastMessageAt: string | null;
121
244
  createdAt: string;
122
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;
123
291
  }[];
124
292
  nextCursor: string | null;
125
293
  }>;
294
+ /** The user's own notification level: `all`, `mentions` or `none`. */
295
+ setNotificationLevel: (conversationId: string, level: NotificationLevel) => Promise<void>;
126
296
  /** Start realtime ordering for a conversation from a known seq (e.g. after loading history). */
127
297
  track: (conversationId: string, lastSeq: number) => void;
128
298
  untrack: (conversationId: string) => void;
@@ -130,12 +300,9 @@ export declare function createLynkoria(opts: LynkoriaClientOptions): {
130
300
  };
131
301
  messages: {
132
302
  /** Latest history page (or older, with `beforeSeq`). Also starts tracking the conversation. */
133
- history(conversationId: string, params?: {
134
- beforeSeq?: number;
135
- limit?: number;
136
- }): Promise<ConversationEventPage>;
303
+ history(conversationId: string, params?: HistoryOptions): Promise<ConversationEventPage>;
137
304
  send(input: IdempotentSend): Promise<Message>;
138
- edit: (messageId: string, text: string) => Promise<{
305
+ get: (messageId: string) => Promise<{
139
306
  id: string;
140
307
  conversationId: string;
141
308
  seq: number;
@@ -155,11 +322,134 @@ export declare function createLynkoria(opts: LynkoriaClientOptions): {
155
322
  userId: string;
156
323
  emoji: string;
157
324
  }[];
325
+ mentions: string[];
158
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;
159
334
  createdAt: string;
160
335
  editedAt: string | null;
161
336
  deletedAt: string | null;
162
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
+ }>;
163
453
  delete: (messageId: string) => Promise<void>;
164
454
  react: (messageId: string, emoji: string) => Promise<void>;
165
455
  unreact: (messageId: string, emoji: string) => Promise<void>;
@@ -192,6 +482,8 @@ export declare function createLynkoria(opts: LynkoriaClientOptions): {
192
482
  };
193
483
  calls: {
194
484
  join: (options: JoinCallOptions) => Promise<CallSession>;
485
+ /** Camera/microphone preview before joining; pass it to `join({ preview })`. */
486
+ preview: (options?: CallPreviewOptions) => Promise<CallPreview>;
195
487
  };
196
488
  /** Device push registration for native apps (React Native uses this client for messaging). */
197
489
  push: {
@@ -218,4 +510,4 @@ export declare function createLynkoria(opts: LynkoriaClientOptions): {
218
510
  setPreferences: (prefs: NotificationPreferences) => Promise<void>;
219
511
  };
220
512
  };
221
- 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
  };
@@ -140,11 +420,29 @@ function jwtExpiry(token) {
140
420
  return null;
141
421
  }
142
422
  }
423
+ /** The token is sent to this origin, so only accept https (plain http for local development). */
424
+ function checkedApiUrl(value) {
425
+ let url;
426
+ try {
427
+ url = new URL(value);
428
+ } catch {
429
+ throw new Error(`Invalid apiUrl from the messaging token response: ${value}`);
430
+ }
431
+ const local = [
432
+ "localhost",
433
+ "127.0.0.1",
434
+ "[::1]"
435
+ ].includes(url.hostname);
436
+ if (url.protocol !== "https:" && !(url.protocol === "http:" && local)) throw new Error(`apiUrl must use https: ${value}`);
437
+ return value;
438
+ }
143
439
  /** Caches the messaging token from the product backend; refreshes it within 60 s of expiry. */
144
440
  var TokenSource = class {
145
441
  fetchToken;
146
442
  cached = null;
147
443
  inflight = null;
444
+ /** API origin reported with the most recent token, if the backend passed it through. */
445
+ apiUrl = null;
148
446
  constructor(fetchToken) {
149
447
  this.fetchToken = fetchToken;
150
448
  }
@@ -160,6 +458,7 @@ var TokenSource = class {
160
458
  try {
161
459
  const res = await this.fetchToken();
162
460
  const token = typeof res === "string" ? res : res.token;
461
+ if (typeof res === "object" && res.apiUrl) this.apiUrl = checkedApiUrl(res.apiUrl);
163
462
  const explicitExpiry = typeof res === "object" && res.expiresAt ? Date.parse(res.expiresAt) : NaN;
164
463
  const expiresAt = Number.isFinite(explicitExpiry) ? explicitExpiry : jwtExpiry(token) ?? Date.now() + 3e5;
165
464
  this.cached = {
@@ -175,6 +474,8 @@ var TokenSource = class {
175
474
  }
176
475
  };
177
476
  // src/index.ts
477
+ /** The Lynkoria API, used until a messaging token reports its `apiUrl`. */
478
+ const DEFAULT_API_URL = "https://api.lynkoria.com";
178
479
  function defaultIds() {
179
480
  return { create: () => {
180
481
  const c = globalThis.crypto;
@@ -186,12 +487,14 @@ function defaultIds() {
186
487
  } };
187
488
  }
188
489
  const conv = (id) => `/v1/conversations/${encodeURIComponent(id)}`;
490
+ const msg = (id) => `/v1/messages/${encodeURIComponent(id)}`;
189
491
  const jitter = (ms) => ms * (.8 + Math.random() * .4);
190
492
  function createLynkoria(opts) {
191
- const base = opts.baseUrl.replace(/\/+$/, "");
192
493
  const doFetch = opts.fetch ?? ((...args) => fetch(...args));
193
494
  const ids = opts.ids ?? defaultIds();
194
- const tokens = new TokenSource(opts.getMessagingToken);
495
+ const tokens = new TokenSource(opts.getMessagingToken ?? (() => Promise.reject(new LynkoriaError$1(ErrorCode$1.BadRequest, "createLynkoria: pass getMessagingToken to use messaging, presence, attachments or push"))));
496
+ /** Resolved after the first token, so clients need no endpoint configuration. */
497
+ const base = () => (opts.baseUrl ?? tokens.apiUrl ?? "https://api.lynkoria.com").replace(/\/+$/, "");
195
498
  const tracker = new SequenceTracker();
196
499
  const media = new LiveKitMediaProvider();
197
500
  const connectionState = new Emitter();
@@ -220,7 +523,7 @@ function createLynkoria(opts) {
220
523
  const token = await tokens.token();
221
524
  let res;
222
525
  try {
223
- res = await doFetch(`${base}${path}`, {
526
+ res = await doFetch(`${base()}${path}`, {
224
527
  method,
225
528
  headers: {
226
529
  authorization: `Bearer ${token}`,
@@ -297,7 +600,7 @@ function createLynkoria(opts) {
297
600
  }
298
601
  function ensureSocket() {
299
602
  if (socket) return socket;
300
- const s = io(base, {
603
+ const s = io(base(), {
301
604
  path: opts.socketPath ?? "/socket.io/",
302
605
  transports: ["websocket"],
303
606
  autoConnect: false,
@@ -352,6 +655,8 @@ function createLynkoria(opts) {
352
655
  "message:created",
353
656
  "message:updated",
354
657
  "message:deleted",
658
+ "message:pinned",
659
+ "message:unpinned",
355
660
  "reaction:added",
356
661
  "reaction:removed"
357
662
  ]) s.on(name, deliver);
@@ -380,10 +685,21 @@ function createLynkoria(opts) {
380
685
  return s;
381
686
  }
382
687
  function connect() {
688
+ if (!opts.getMessagingToken) return;
383
689
  wantConnected = true;
690
+ if (!socket && !opts.baseUrl && !tokens.apiUrl) {
691
+ if (state === "idle") setState("connecting");
692
+ tokens.token().catch(() => void 0).finally(() => {
693
+ if (wantConnected) openSocket();
694
+ });
695
+ return;
696
+ }
697
+ openSocket();
698
+ }
699
+ function openSocket() {
384
700
  const s = ensureSocket();
385
701
  if (!s.connected && !s.active) {
386
- setState(state === "idle" ? "connecting" : "reconnecting");
702
+ setState(state === "idle" || state === "connecting" ? "connecting" : "reconnecting");
387
703
  s.connect();
388
704
  }
389
705
  }
@@ -431,12 +747,27 @@ function createLynkoria(opts) {
431
747
  onConversationUpdated: (l) => conversationEvents.on(l),
432
748
  ids,
433
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
+ */
434
754
  list: (params = {}) => {
435
755
  const q = new URLSearchParams();
436
756
  if (params.limit) q.set("limit", String(params.limit));
437
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);
438
760
  return request("GET", `/v1/conversations${q.size ? `?${q}` : ""}`);
439
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 }),
440
771
  /** Start realtime ordering for a conversation from a known seq (e.g. after loading history). */
441
772
  track: (conversationId, lastSeq) => tracker.set(conversationId, lastSeq),
442
773
  untrack: (conversationId) => tracker.forget(conversationId),
@@ -447,6 +778,9 @@ function createLynkoria(opts) {
447
778
  async history(conversationId, params = {}) {
448
779
  const q = new URLSearchParams({ limit: String(params.limit ?? 50) });
449
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");
450
784
  const page = await request("GET", `${conv(conversationId)}/messages?${q}`);
451
785
  if (params.beforeSeq === void 0) tracker.set(conversationId, page.lastSeq);
452
786
  return page;
@@ -456,7 +790,8 @@ function createLynkoria(opts) {
456
790
  clientMessageId: input.clientMessageId ?? ids.create(),
457
791
  text: input.text ?? "",
458
792
  attachmentIds: input.attachmentIds ?? [],
459
- ...input.parentMessageId ? { parentMessageId: input.parentMessageId } : {}
793
+ ...input.parentMessageId ? { parentMessageId: input.parentMessageId } : {},
794
+ ...input.mentions?.length ? { mentions: input.mentions } : {}
460
795
  };
461
796
  if (socket?.connected) try {
462
797
  return (await emitAck((s) => s.timeout(1e4).emitWithAck("message:send", {
@@ -468,7 +803,25 @@ function createLynkoria(opts) {
468
803
  }
469
804
  return (await request("POST", `${conv(input.conversationId)}/messages`, body)).message;
470
805
  },
471
- 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
+ },
472
825
  delete: (messageId) => request("DELETE", `/v1/messages/${encodeURIComponent(messageId)}`),
473
826
  react: (messageId, emoji) => request("POST", `/v1/messages/${encodeURIComponent(messageId)}/reactions`, { emoji }),
474
827
  unreact: (messageId, emoji) => request("DELETE", `/v1/messages/${encodeURIComponent(messageId)}/reactions/${encodeURIComponent(emoji)}`),
@@ -528,7 +881,11 @@ function createLynkoria(opts) {
528
881
  },
529
882
  downloadUrl: (attachmentId) => request("GET", `/v1/attachments/${encodeURIComponent(attachmentId)}/url`)
530
883
  },
531
- 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
+ },
532
889
  /** Device push registration for native apps (React Native uses this client for messaging). */
533
890
  push: {
534
891
  /** Call on every FCM/APNs/PushKit token refresh; idempotent. */
@@ -543,4 +900,4 @@ function createLynkoria(opts) {
543
900
  }
544
901
  };
545
902
  }
546
- export { 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.1.1",
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,8 +23,8 @@
23
23
  "access": "public"
24
24
  },
25
25
  "dependencies": {
26
- "@lynkoria/contracts": "^0.1.1",
27
- "livekit-client": "^2.24.0",
26
+ "@lynkoria/contracts": "^0.4.0",
27
+ "livekit-client": "^2.24.1",
28
28
  "socket.io-client": "^4.8.4"
29
29
  },
30
30
  "devDependencies": {