@antzsoft/chat-core 1.4.3 → 1.4.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -13,6 +13,7 @@ import {
13
13
  encryptPayload,
14
14
  fetchServerKeys,
15
15
  generateEphemeralKey,
16
+ generateUUID,
16
17
  getApiClient,
17
18
  getCompressionStrategy,
18
19
  getSessionId,
@@ -299,363 +300,6 @@ function resolveSystemMessageText(message, currentUserId) {
299
300
  }
300
301
  }
301
302
 
302
- // src/api/messages.ts
303
- var MAX_FORWARD_TARGETS = 5;
304
- var HIGHLY_FORWARDED_DEPTH_THRESHOLD = 5;
305
- var messagesApi = {
306
- async list(conversationId, params = {}) {
307
- const { cursor, direction, ...rest } = params;
308
- const serverParams = { ...rest };
309
- if (cursor) {
310
- serverParams[direction === "after" ? "after" : "before"] = cursor;
311
- }
312
- const { data } = await getApiClient().get(
313
- `/conversations/${conversationId}/messages`,
314
- { params: serverParams }
315
- );
316
- const currentUserId = getAuthStore().useAuthStore.getState().user?.id;
317
- if (!currentUserId) return data;
318
- return {
319
- ...data,
320
- data: data.data.map(
321
- (m) => m.content.type === "system" ? { ...m, content: { ...m.content, text: resolveSystemMessageText(m, currentUserId) } } : m
322
- )
323
- };
324
- },
325
- async get(messageId) {
326
- const { data } = await getApiClient().get(`/messages/${messageId}`);
327
- return data;
328
- },
329
- async send(conversationId, payload) {
330
- const { data } = await getApiClient().post(
331
- `/conversations/${conversationId}/messages`,
332
- payload
333
- );
334
- return data;
335
- },
336
- async update(messageId, text) {
337
- const { data } = await getApiClient().post(`/messages/${messageId}/update`, { text });
338
- return data;
339
- },
340
- async delete(messageId) {
341
- await getApiClient().post(`/messages/${messageId}/delete`);
342
- },
343
- async deleteForMe(messageId) {
344
- await getApiClient().post(`/messages/${messageId}/delete-for-me`);
345
- },
346
- async addReaction(messageId, emoji) {
347
- const { data } = await getApiClient().post(`/messages/${messageId}/reactions`, { emoji });
348
- return data;
349
- },
350
- async removeReaction(messageId, emoji) {
351
- const { data } = await getApiClient().post(
352
- `/messages/${messageId}/reactions/${encodeURIComponent(emoji)}/remove`
353
- );
354
- return data;
355
- },
356
- async getReactions(messageId) {
357
- const { data } = await getApiClient().post(`/messages/${messageId}/reactions/list`);
358
- return data;
359
- },
360
- async star(messageId) {
361
- await getApiClient().post(`/messages/${messageId}/star`);
362
- },
363
- async unstar(messageId) {
364
- await getApiClient().post(`/messages/${messageId}/unstar`);
365
- },
366
- async getStarred(params = {}) {
367
- const { data } = await getApiClient().get("/messages/starred", { params });
368
- return data;
369
- },
370
- async search(params) {
371
- const { data } = await getApiClient().get("/messages/search", { params });
372
- return data;
373
- },
374
- async getLastRead(conversationId) {
375
- const { data } = await getApiClient().get(
376
- `/conversations/${conversationId}/read-receipt`
377
- );
378
- return data;
379
- },
380
- async markAsRead(conversationId, messageId) {
381
- await getApiClient().post(`/conversations/${conversationId}/read`, messageId ? { messageId } : {});
382
- },
383
- async pin(messageId) {
384
- const { data } = await getApiClient().post(`/messages/${messageId}/pin`);
385
- return data;
386
- },
387
- async unpin(messageId) {
388
- const { data } = await getApiClient().post(`/messages/${messageId}/unpin`);
389
- return data;
390
- },
391
- async getPinned(conversationId) {
392
- const { data } = await getApiClient().get(`/conversations/${conversationId}/pinned-messages`);
393
- return data;
394
- },
395
- async getReceipts(messageId) {
396
- const { data } = await getApiClient().get(`/messages/${messageId}/receipts`);
397
- return data;
398
- },
399
- /**
400
- * Forwards a message into one or more target conversations (max MAX_FORWARD_TARGETS
401
- * per call, also enforced server-side). Each target is independent — one failing
402
- * (e.g. no longer a participant) does not block the others; check `success`/`error`
403
- * per entry in the returned array.
404
- *
405
- * Pass `attachmentIds` to forward only a subset of the source message's attachments
406
- * (e.g. one image out of a multi-image message) — omit it to forward the whole
407
- * message, including all its attachments, unchanged. An ID not present on the
408
- * source message is ignored server-side.
409
- */
410
- async forward(messageId, targetConversationIds, attachmentIds) {
411
- const { data } = await getApiClient().post(
412
- `/messages/${messageId}/forward`,
413
- { targetConversationIds, ...attachmentIds ? { attachmentIds } : {} }
414
- );
415
- return data;
416
- }
417
- };
418
-
419
- // src/api/conversations.ts
420
- function normalizeParticipant(p) {
421
- const hasUserDetails = p.displayName || p.username || p.avatarUrl;
422
- return {
423
- userId: p.userId,
424
- externalId: p.externalId ?? p.user?.externalId,
425
- role: p.role,
426
- joinedAt: p.joinedAt,
427
- isActive: p.isActive,
428
- user: hasUserDetails ? {
429
- id: p.userId,
430
- externalId: p.externalId,
431
- tenantId: "",
432
- email: "",
433
- username: p.username ?? "",
434
- displayName: p.displayName ?? p.username ?? "",
435
- avatarUrl: p.avatarUrl,
436
- status: "offline",
437
- createdAt: p.joinedAt ?? "",
438
- updatedAt: p.joinedAt ?? ""
439
- } : p.user
440
- };
441
- }
442
- function normalizeLastMessage(lastMsg) {
443
- if (!lastMsg) return void 0;
444
- if (lastMsg.content !== void 0) return lastMsg;
445
- return {
446
- id: lastMsg.messageId ?? "",
447
- tenantId: "",
448
- conversationId: "",
449
- senderId: lastMsg.senderId ?? "",
450
- content: {
451
- type: lastMsg.hasAttachments ? "attachment" : "text",
452
- text: lastMsg.contentPreview
453
- },
454
- reactions: [],
455
- lastReaction: lastMsg.lastReaction ?? null,
456
- status: lastMsg.status ?? "active",
457
- deliveryStatus: lastMsg.deliveryStatus ?? "sent",
458
- isEdited: false,
459
- sentAt: lastMsg.sentAt ?? "",
460
- createdAt: lastMsg.sentAt ?? "",
461
- ...lastMsg.senderName && { senderName: lastMsg.senderName },
462
- ...lastMsg.attachmentType && { attachmentType: lastMsg.attachmentType }
463
- };
464
- }
465
- function normalizeConversation(conv) {
466
- return {
467
- ...conv,
468
- id: conv.id ?? conv.conversationId,
469
- participants: (conv.participants ?? []).map(normalizeParticipant),
470
- lastMessage: normalizeLastMessage(conv.lastMessage)
471
- };
472
- }
473
- var conversationsApi = {
474
- async list(params = {}) {
475
- const { data } = await getApiClient().get("/conversations", { params });
476
- return { ...data, data: data.data.map(normalizeConversation) };
477
- },
478
- async get(conversationId) {
479
- const { data } = await getApiClient().get(`/conversations/${conversationId}`);
480
- return normalizeConversation(data);
481
- },
482
- async createGroup(payload) {
483
- const { data } = await getApiClient().post("/conversations", payload);
484
- return normalizeConversation(data);
485
- },
486
- async createDirect(payload) {
487
- const { data } = await getApiClient().post("/conversations/direct", payload);
488
- return normalizeConversation(data);
489
- },
490
- async update(conversationId, payload) {
491
- const { data } = await getApiClient().post(`/conversations/${conversationId}/update`, payload);
492
- return normalizeConversation(data);
493
- },
494
- async delete(conversationId) {
495
- await getApiClient().post(`/conversations/${conversationId}/delete`);
496
- },
497
- async addParticipants(conversationId, userIds, role) {
498
- const { data } = await getApiClient().post(
499
- `/conversations/${conversationId}/participants`,
500
- { userIds, ...role && { role } }
501
- );
502
- return normalizeConversation(data);
503
- },
504
- async removeParticipant(conversationId, userId) {
505
- const { data } = await getApiClient().post(
506
- `/conversations/${conversationId}/participants/${userId}/remove`
507
- );
508
- return normalizeConversation(data);
509
- },
510
- async updateParticipantRole(conversationId, userId, role) {
511
- const { data } = await getApiClient().post(
512
- `/conversations/${conversationId}/participants/${userId}/role`,
513
- { role }
514
- );
515
- return normalizeConversation(data);
516
- },
517
- async mute(conversationId, mutedUntil) {
518
- await getApiClient().post(`/conversations/${conversationId}/mute`, mutedUntil ? { mutedUntil } : {});
519
- },
520
- async unmute(conversationId) {
521
- await getApiClient().post(`/conversations/${conversationId}/unmute`);
522
- },
523
- async pin(conversationId) {
524
- await getApiClient().post(`/conversations/${conversationId}/pin`);
525
- },
526
- async unpin(conversationId) {
527
- await getApiClient().post(`/conversations/${conversationId}/unpin`);
528
- },
529
- async markUnread(conversationId) {
530
- await getApiClient().post(`/conversations/${conversationId}/unread`);
531
- },
532
- async markRead(conversationId) {
533
- await getApiClient().post(`/conversations/${conversationId}/unread/clear`);
534
- },
535
- async leave(conversationId, andDelete) {
536
- const url = andDelete ? `/conversations/${conversationId}/leave?delete=true` : `/conversations/${conversationId}/leave`;
537
- await getApiClient().post(url);
538
- },
539
- async getMembers(conversationId, filter) {
540
- const { data } = await getApiClient().get(
541
- `/conversations/${conversationId}/participants`,
542
- filter ? { params: { filter } } : void 0
543
- );
544
- return (data ?? []).map(normalizeParticipant);
545
- },
546
- /**
547
- * Get unread message count for a single conversation.
548
- * Use this after app foreground or socket reconnect to refresh a specific count.
549
- */
550
- async getUnreadCount(conversationId) {
551
- const { data } = await getApiClient().get(
552
- `/conversations/${conversationId}/unread`
553
- );
554
- return data;
555
- },
556
- /**
557
- * Get total unread count across all conversations + per-conversation breakdown.
558
- * Use on app cold start, foreground resume, or after socket reconnect.
559
- * The socket keeps counts live while connected — this is the source of truth
560
- * when the socket was down.
561
- */
562
- async getUnreadSummary() {
563
- const { data } = await getApiClient().get("/conversations/unread");
564
- return data;
565
- },
566
- /**
567
- * Set the group icon from an already-uploaded file (admin only).
568
- * The fileId comes from uploadBatch() / client.uploadFiles() — same as attachments.
569
- * Server copies storageKey into conversation.iconMeta and deletes the chat_files record.
570
- */
571
- async uploadIcon(conversationId, fileId) {
572
- const { data } = await getApiClient().post(
573
- `/conversations/${conversationId}/icon`,
574
- { fileId }
575
- );
576
- return normalizeConversation(data);
577
- },
578
- async removeIcon(conversationId) {
579
- const { data } = await getApiClient().post(`/conversations/${conversationId}/icon/remove`);
580
- return normalizeConversation(data);
581
- },
582
- async clearChat(conversationId) {
583
- await getApiClient().post(`/conversations/${conversationId}/clear-for-me`);
584
- }
585
- };
586
-
587
- // src/api/devices.ts
588
- var devicesApi = {
589
- /**
590
- * Register or update a device push token with the chat server.
591
- *
592
- * Upserts by `deviceId` — calling this multiple times with the same deviceId
593
- * simply refreshes the token value (tokens can rotate silently on some platforms).
594
- *
595
- * The SDK never calls this automatically. The parent app or the `tokenProvider`
596
- * option in `pushNotifications` config is responsible for calling it after
597
- * obtaining the token from the OS / browser.
598
- */
599
- async register(payload) {
600
- await getApiClient().post("/users/me/devices", payload);
601
- },
602
- /**
603
- * Remove a device token from the chat server.
604
- * Call this on logout so the user stops receiving push notifications on this device.
605
- */
606
- async remove(deviceId) {
607
- await getApiClient().post(`/users/me/devices/${deviceId}/remove`);
608
- }
609
- };
610
-
611
- // src/api/users.ts
612
- var usersApi = {
613
- async list(params = {}) {
614
- const { data } = await getApiClient().get("/users", { params });
615
- return data;
616
- },
617
- async getById(userId) {
618
- const { data } = await getApiClient().get(`/users/${userId}`);
619
- return data;
620
- },
621
- async getLastSeen(userId) {
622
- const { data } = await getApiClient().get(`/users/${userId}`);
623
- return { lastSeenAt: data.lastSeenAt ?? null };
624
- },
625
- /**
626
- * Update basic profile fields for the current user.
627
- * Works in both builtin and non-builtin modes. Use this to push an immediate
628
- * profile update to the chat server when the host app knows a change just
629
- * happened — without waiting for the next 2-hour sync cycle.
630
- */
631
- async updateProfile(payload) {
632
- const { data } = await getApiClient().post("/users/me/update", payload);
633
- return data;
634
- },
635
- /**
636
- * Update notification preferences for the current user.
637
- * Partial update — only send fields you want to change.
638
- * A prefs record is automatically created with defaults when a device
639
- * token is first registered, so this never fails with "not found".
640
- */
641
- async updatePreferences(prefs) {
642
- const { data } = await getApiClient().post("/users/me/preferences", prefs);
643
- return data;
644
- },
645
- /**
646
- * Fetch current notification preferences for the current user.
647
- * Returns null if no prefs record exists yet (all defaults apply).
648
- */
649
- async getPreferences() {
650
- try {
651
- const { data } = await getApiClient().get("/users/me/preferences");
652
- return data;
653
- } catch {
654
- return null;
655
- }
656
- }
657
- };
658
-
659
303
  // src/socket/socket.ts
660
304
  import { io } from "socket.io-client";
661
305
  var _socket = null;
@@ -1026,74 +670,468 @@ async function withAck(event, payload) {
1026
670
  }).catch(reject);
1027
671
  });
1028
672
  }
1029
- function fireAndForget(event, payload) {
1030
- const socket = tryGetSocket();
1031
- if (!socket) return;
1032
- secureEmit(socket, event, payload);
673
+ function fireAndForget(event, payload) {
674
+ const socket = tryGetSocket();
675
+ if (!socket) return;
676
+ secureEmit(socket, event, payload);
677
+ }
678
+ var socketEmit = {
679
+ joinRoom(conversationId) {
680
+ fireAndForget("join_room", { conversationId });
681
+ },
682
+ leaveRoom(conversationId) {
683
+ fireAndForget("leave_room", { conversationId });
684
+ },
685
+ sendMessage(payload) {
686
+ return queueSendMessage({ ...payload, sentAt: Date.now() });
687
+ },
688
+ // Not queued like sendMessage — forward targets are independent conversations,
689
+ // not the single conversation ordering that queueSendMessage protects, and each
690
+ // target's own new_message/push already fires server-side via MessagesService.forward()'s
691
+ // internal create() calls, so there's nothing here that needs in-order draining.
692
+ forwardMessage(payload) {
693
+ return withAck("forward_message", payload);
694
+ },
695
+ updateMessage(messageId, text) {
696
+ return withAck("update_message", { messageId, text });
697
+ },
698
+ deleteMessage(messageId) {
699
+ return withAck("delete_message", { messageId });
700
+ },
701
+ deleteMessageForMe(messageId) {
702
+ return withAck("delete_message_for_me", { messageId });
703
+ },
704
+ clearChat(conversationId) {
705
+ return withAck("clear_chat_for_me", { conversationId });
706
+ },
707
+ addReaction(messageId, emoji) {
708
+ return withAck("add_reaction", { messageId, emoji });
709
+ },
710
+ removeReaction(messageId, emoji) {
711
+ return withAck("remove_reaction", { messageId, emoji });
712
+ },
713
+ pinMessage(messageId) {
714
+ return withAck("pin_message", { messageId });
715
+ },
716
+ unpinMessage(messageId) {
717
+ return withAck("unpin_message", { messageId });
718
+ },
719
+ // markRead and typing are best-effort — silently dropped if socket not ready
720
+ typing(conversationId, isTyping) {
721
+ fireAndForget("typing", { conversationId, isTyping });
722
+ },
723
+ markRead(conversationId, messageId) {
724
+ fireAndForget("mark_read", { conversationId, ...messageId ? { messageId } : {} });
725
+ },
726
+ getOnlineUsers(userIds) {
727
+ const socket = tryGetSocket();
728
+ if (!socket) return Promise.resolve([]);
729
+ return new Promise((resolve, reject) => {
730
+ let timer;
731
+ secureEmit(socket, "get_online_users", { userIds }, (response) => {
732
+ clearTimeout(timer);
733
+ if (response && typeof response === "object" && "onlineStatus" in response) {
734
+ const status = response.onlineStatus;
735
+ resolve(Object.entries(status).filter(([, v]) => v).map(([k]) => k));
736
+ } else if (Array.isArray(response)) {
737
+ resolve(response);
738
+ } else {
739
+ resolve([]);
740
+ }
741
+ }).then(() => {
742
+ timer = setTimeout(() => reject(new AntzChatNetworkError("Socket ack timeout: get_online_users", "SOCKET_TIMEOUT", { event: "get_online_users" })), ACK_TIMEOUT);
743
+ }).catch(reject);
744
+ });
745
+ },
746
+ getTypingUsers(conversationId) {
747
+ return withAck("get_typing_users", { conversationId });
748
+ }
749
+ };
750
+
751
+ // src/api/messages.ts
752
+ var MAX_FORWARD_TARGETS = 5;
753
+ var HIGHLY_FORWARDED_DEPTH_THRESHOLD = 5;
754
+ var messagesApi = {
755
+ async list(conversationId, params = {}) {
756
+ const { cursor, direction, ...rest } = params;
757
+ const serverParams = { ...rest };
758
+ if (cursor) {
759
+ serverParams[direction === "after" ? "after" : "before"] = cursor;
760
+ }
761
+ const { data } = await getApiClient().get(
762
+ `/conversations/${conversationId}/messages`,
763
+ { params: serverParams }
764
+ );
765
+ const currentUserId = getAuthStore().useAuthStore.getState().user?.id;
766
+ if (!currentUserId) return data;
767
+ return {
768
+ ...data,
769
+ data: data.data.map(
770
+ (m) => m.content.type === "system" ? { ...m, content: { ...m.content, text: resolveSystemMessageText(m, currentUserId) } } : m
771
+ )
772
+ };
773
+ },
774
+ async get(messageId) {
775
+ const { data } = await getApiClient().get(`/messages/${messageId}`);
776
+ return data;
777
+ },
778
+ /**
779
+ * Sends a message via REST. For real-time delivery use `socketEmit.sendMessage`
780
+ * instead — this is a lower-level entry point (used e.g. by the socket path's
781
+ * REST-mirror flows). Pass `payload.tempId` and reuse the SAME value on retry to
782
+ * make a retry-after-timeout safe — see `SendData.tempId`.
783
+ */
784
+ async send(conversationId, payload) {
785
+ const { data } = await getApiClient().post(
786
+ `/conversations/${conversationId}/messages`,
787
+ payload
788
+ );
789
+ return data;
790
+ },
791
+ async update(messageId, text) {
792
+ const { data } = await getApiClient().post(`/messages/${messageId}/update`, { text });
793
+ return data;
794
+ },
795
+ async delete(messageId) {
796
+ await getApiClient().post(`/messages/${messageId}/delete`);
797
+ },
798
+ async deleteForMe(messageId) {
799
+ await getApiClient().post(`/messages/${messageId}/delete-for-me`);
800
+ },
801
+ async addReaction(messageId, emoji) {
802
+ const { data } = await getApiClient().post(`/messages/${messageId}/reactions`, { emoji });
803
+ return data;
804
+ },
805
+ async removeReaction(messageId, emoji) {
806
+ const { data } = await getApiClient().post(
807
+ `/messages/${messageId}/reactions/${encodeURIComponent(emoji)}/remove`
808
+ );
809
+ return data;
810
+ },
811
+ async getReactions(messageId) {
812
+ const { data } = await getApiClient().post(`/messages/${messageId}/reactions/list`);
813
+ return data;
814
+ },
815
+ async star(messageId) {
816
+ await getApiClient().post(`/messages/${messageId}/star`);
817
+ },
818
+ async unstar(messageId) {
819
+ await getApiClient().post(`/messages/${messageId}/unstar`);
820
+ },
821
+ async getStarred(params = {}) {
822
+ const { data } = await getApiClient().get("/messages/starred", { params });
823
+ return data;
824
+ },
825
+ async search(params) {
826
+ const { data } = await getApiClient().get("/messages/search", { params });
827
+ return data;
828
+ },
829
+ async getLastRead(conversationId) {
830
+ const { data } = await getApiClient().get(
831
+ `/conversations/${conversationId}/read-receipt`
832
+ );
833
+ return data;
834
+ },
835
+ async markAsRead(conversationId, messageId) {
836
+ await getApiClient().post(`/conversations/${conversationId}/read`, messageId ? { messageId } : {});
837
+ },
838
+ async pin(messageId) {
839
+ const { data } = await getApiClient().post(`/messages/${messageId}/pin`);
840
+ return data;
841
+ },
842
+ async unpin(messageId) {
843
+ const { data } = await getApiClient().post(`/messages/${messageId}/unpin`);
844
+ return data;
845
+ },
846
+ async getPinned(conversationId) {
847
+ const { data } = await getApiClient().get(`/conversations/${conversationId}/pinned-messages`);
848
+ return data;
849
+ },
850
+ async getReceipts(messageId) {
851
+ const { data } = await getApiClient().get(`/messages/${messageId}/receipts`);
852
+ return data;
853
+ },
854
+ /**
855
+ * Forwards a message into one or more target conversations (max MAX_FORWARD_TARGETS
856
+ * per call, also enforced server-side). Each target is independent — one failing
857
+ * (e.g. no longer a participant) does not block the others; check `success`/`error`
858
+ * per entry in the returned array.
859
+ *
860
+ * Pass `attachmentIds` to forward only a subset of the source message's attachments
861
+ * (e.g. one image out of a multi-image message) — omit it to forward the whole
862
+ * message, including all its attachments, unchanged. An ID not present on the
863
+ * source message is ignored server-side.
864
+ *
865
+ * Idempotency: pass `tempId` — generate ONE value per forward action (e.g. via
866
+ * `generateUUID` from '@antzsoft/chat-core/internal') and reuse that SAME value if
867
+ * you retry this exact forward (e.g. after a client-side timeout). The server then
868
+ * recognizes the retry per target and returns the already-created message instead
869
+ * of creating a duplicate. Never mint a new tempId for a retry — only when the user
870
+ * initiates a genuinely new forward action. If omitted, a fresh one is generated
871
+ * per call, which means a retry without an explicit tempId gets NO dedup protection.
872
+ *
873
+ * Transport: uses the 'forward_message' socket event when a socket is connected
874
+ * (lower latency, same server-side MessagesService.forward() path, so broadcast/
875
+ * push notification behavior is identical either way) and transparently falls back
876
+ * to the REST endpoint when no socket is available.
877
+ */
878
+ async forward(messageId, targetConversationIds, attachmentIds, tempId) {
879
+ const resolvedTempId = tempId ?? generateUUID();
880
+ if (tryGetSocket()) {
881
+ const ack = await socketEmit.forwardMessage({
882
+ messageId,
883
+ targetConversationIds,
884
+ ...attachmentIds ? { attachmentIds } : {},
885
+ tempId: resolvedTempId
886
+ });
887
+ if (ack.error) throw new Error(ack.error);
888
+ return ack.results;
889
+ }
890
+ const { data } = await getApiClient().post(
891
+ `/messages/${messageId}/forward`,
892
+ { targetConversationIds, ...attachmentIds ? { attachmentIds } : {}, tempId: resolvedTempId }
893
+ );
894
+ return data;
895
+ }
896
+ };
897
+
898
+ // src/api/conversations.ts
899
+ function normalizeParticipant(p) {
900
+ const hasUserDetails = p.displayName || p.username || p.avatarUrl;
901
+ return {
902
+ userId: p.userId,
903
+ externalId: p.externalId ?? p.user?.externalId,
904
+ role: p.role,
905
+ joinedAt: p.joinedAt,
906
+ isActive: p.isActive,
907
+ user: hasUserDetails ? {
908
+ id: p.userId,
909
+ externalId: p.externalId,
910
+ tenantId: "",
911
+ email: "",
912
+ username: p.username ?? "",
913
+ displayName: p.displayName ?? p.username ?? "",
914
+ avatarUrl: p.avatarUrl,
915
+ status: "offline",
916
+ createdAt: p.joinedAt ?? "",
917
+ updatedAt: p.joinedAt ?? ""
918
+ } : p.user
919
+ };
920
+ }
921
+ function normalizeLastMessage(lastMsg) {
922
+ if (!lastMsg) return void 0;
923
+ if (lastMsg.content !== void 0) return lastMsg;
924
+ return {
925
+ id: lastMsg.messageId ?? "",
926
+ tenantId: "",
927
+ conversationId: "",
928
+ senderId: lastMsg.senderId ?? "",
929
+ content: {
930
+ type: lastMsg.hasAttachments ? "attachment" : "text",
931
+ text: lastMsg.contentPreview
932
+ },
933
+ reactions: [],
934
+ lastReaction: lastMsg.lastReaction ?? null,
935
+ status: lastMsg.status ?? "active",
936
+ deliveryStatus: lastMsg.deliveryStatus ?? "sent",
937
+ isEdited: false,
938
+ sentAt: lastMsg.sentAt ?? "",
939
+ createdAt: lastMsg.sentAt ?? "",
940
+ ...lastMsg.senderName && { senderName: lastMsg.senderName },
941
+ ...lastMsg.attachmentType && { attachmentType: lastMsg.attachmentType }
942
+ };
1033
943
  }
1034
- var socketEmit = {
1035
- joinRoom(conversationId) {
1036
- fireAndForget("join_room", { conversationId });
944
+ function normalizeConversation(conv) {
945
+ return {
946
+ ...conv,
947
+ id: conv.id ?? conv.conversationId,
948
+ participants: (conv.participants ?? []).map(normalizeParticipant),
949
+ lastMessage: normalizeLastMessage(conv.lastMessage)
950
+ };
951
+ }
952
+ var conversationsApi = {
953
+ async list(params = {}) {
954
+ const { data } = await getApiClient().get("/conversations", { params });
955
+ return { ...data, data: data.data.map(normalizeConversation) };
1037
956
  },
1038
- leaveRoom(conversationId) {
1039
- fireAndForget("leave_room", { conversationId });
957
+ async get(conversationId) {
958
+ const { data } = await getApiClient().get(`/conversations/${conversationId}`);
959
+ return normalizeConversation(data);
1040
960
  },
1041
- sendMessage(payload) {
1042
- return queueSendMessage({ ...payload, sentAt: Date.now() });
961
+ async createGroup(payload) {
962
+ const { data } = await getApiClient().post("/conversations", payload);
963
+ return normalizeConversation(data);
1043
964
  },
1044
- updateMessage(messageId, text) {
1045
- return withAck("update_message", { messageId, text });
965
+ async createDirect(payload) {
966
+ const { data } = await getApiClient().post("/conversations/direct", payload);
967
+ return normalizeConversation(data);
1046
968
  },
1047
- deleteMessage(messageId) {
1048
- return withAck("delete_message", { messageId });
969
+ async update(conversationId, payload) {
970
+ const { data } = await getApiClient().post(`/conversations/${conversationId}/update`, payload);
971
+ return normalizeConversation(data);
1049
972
  },
1050
- deleteMessageForMe(messageId) {
1051
- return withAck("delete_message_for_me", { messageId });
973
+ async delete(conversationId) {
974
+ await getApiClient().post(`/conversations/${conversationId}/delete`);
1052
975
  },
1053
- clearChat(conversationId) {
1054
- return withAck("clear_chat_for_me", { conversationId });
976
+ async addParticipants(conversationId, userIds, role) {
977
+ const { data } = await getApiClient().post(
978
+ `/conversations/${conversationId}/participants`,
979
+ { userIds, ...role && { role } }
980
+ );
981
+ return normalizeConversation(data);
1055
982
  },
1056
- addReaction(messageId, emoji) {
1057
- return withAck("add_reaction", { messageId, emoji });
983
+ async removeParticipant(conversationId, userId) {
984
+ const { data } = await getApiClient().post(
985
+ `/conversations/${conversationId}/participants/${userId}/remove`
986
+ );
987
+ return normalizeConversation(data);
1058
988
  },
1059
- removeReaction(messageId, emoji) {
1060
- return withAck("remove_reaction", { messageId, emoji });
989
+ async updateParticipantRole(conversationId, userId, role) {
990
+ const { data } = await getApiClient().post(
991
+ `/conversations/${conversationId}/participants/${userId}/role`,
992
+ { role }
993
+ );
994
+ return normalizeConversation(data);
1061
995
  },
1062
- pinMessage(messageId) {
1063
- return withAck("pin_message", { messageId });
996
+ async mute(conversationId, mutedUntil) {
997
+ await getApiClient().post(`/conversations/${conversationId}/mute`, mutedUntil ? { mutedUntil } : {});
1064
998
  },
1065
- unpinMessage(messageId) {
1066
- return withAck("unpin_message", { messageId });
999
+ async unmute(conversationId) {
1000
+ await getApiClient().post(`/conversations/${conversationId}/unmute`);
1067
1001
  },
1068
- // markRead and typing are best-effort — silently dropped if socket not ready
1069
- typing(conversationId, isTyping) {
1070
- fireAndForget("typing", { conversationId, isTyping });
1002
+ async pin(conversationId) {
1003
+ await getApiClient().post(`/conversations/${conversationId}/pin`);
1071
1004
  },
1072
- markRead(conversationId, messageId) {
1073
- fireAndForget("mark_read", { conversationId, ...messageId ? { messageId } : {} });
1005
+ async unpin(conversationId) {
1006
+ await getApiClient().post(`/conversations/${conversationId}/unpin`);
1074
1007
  },
1075
- getOnlineUsers(userIds) {
1076
- const socket = tryGetSocket();
1077
- if (!socket) return Promise.resolve([]);
1078
- return new Promise((resolve, reject) => {
1079
- let timer;
1080
- secureEmit(socket, "get_online_users", { userIds }, (response) => {
1081
- clearTimeout(timer);
1082
- if (response && typeof response === "object" && "onlineStatus" in response) {
1083
- const status = response.onlineStatus;
1084
- resolve(Object.entries(status).filter(([, v]) => v).map(([k]) => k));
1085
- } else if (Array.isArray(response)) {
1086
- resolve(response);
1087
- } else {
1088
- resolve([]);
1089
- }
1090
- }).then(() => {
1091
- timer = setTimeout(() => reject(new AntzChatNetworkError("Socket ack timeout: get_online_users", "SOCKET_TIMEOUT", { event: "get_online_users" })), ACK_TIMEOUT);
1092
- }).catch(reject);
1093
- });
1008
+ async markUnread(conversationId) {
1009
+ await getApiClient().post(`/conversations/${conversationId}/unread`);
1094
1010
  },
1095
- getTypingUsers(conversationId) {
1096
- return withAck("get_typing_users", { conversationId });
1011
+ async markRead(conversationId) {
1012
+ await getApiClient().post(`/conversations/${conversationId}/unread/clear`);
1013
+ },
1014
+ async leave(conversationId, andDelete) {
1015
+ const url = andDelete ? `/conversations/${conversationId}/leave?delete=true` : `/conversations/${conversationId}/leave`;
1016
+ await getApiClient().post(url);
1017
+ },
1018
+ async getMembers(conversationId, filter) {
1019
+ const { data } = await getApiClient().get(
1020
+ `/conversations/${conversationId}/participants`,
1021
+ filter ? { params: { filter } } : void 0
1022
+ );
1023
+ return (data ?? []).map(normalizeParticipant);
1024
+ },
1025
+ /**
1026
+ * Get unread message count for a single conversation.
1027
+ * Use this after app foreground or socket reconnect to refresh a specific count.
1028
+ */
1029
+ async getUnreadCount(conversationId) {
1030
+ const { data } = await getApiClient().get(
1031
+ `/conversations/${conversationId}/unread`
1032
+ );
1033
+ return data;
1034
+ },
1035
+ /**
1036
+ * Get total unread count across all conversations + per-conversation breakdown.
1037
+ * Use on app cold start, foreground resume, or after socket reconnect.
1038
+ * The socket keeps counts live while connected — this is the source of truth
1039
+ * when the socket was down.
1040
+ */
1041
+ async getUnreadSummary() {
1042
+ const { data } = await getApiClient().get("/conversations/unread");
1043
+ return data;
1044
+ },
1045
+ /**
1046
+ * Set the group icon from an already-uploaded file (admin only).
1047
+ * The fileId comes from uploadBatch() / client.uploadFiles() — same as attachments.
1048
+ * Server copies storageKey into conversation.iconMeta and deletes the chat_files record.
1049
+ */
1050
+ async uploadIcon(conversationId, fileId) {
1051
+ const { data } = await getApiClient().post(
1052
+ `/conversations/${conversationId}/icon`,
1053
+ { fileId }
1054
+ );
1055
+ return normalizeConversation(data);
1056
+ },
1057
+ async removeIcon(conversationId) {
1058
+ const { data } = await getApiClient().post(`/conversations/${conversationId}/icon/remove`);
1059
+ return normalizeConversation(data);
1060
+ },
1061
+ async clearChat(conversationId) {
1062
+ await getApiClient().post(`/conversations/${conversationId}/clear-for-me`);
1063
+ }
1064
+ };
1065
+
1066
+ // src/api/devices.ts
1067
+ var devicesApi = {
1068
+ /**
1069
+ * Register or update a device push token with the chat server.
1070
+ *
1071
+ * Upserts by `deviceId` — calling this multiple times with the same deviceId
1072
+ * simply refreshes the token value (tokens can rotate silently on some platforms).
1073
+ *
1074
+ * The SDK never calls this automatically. The parent app or the `tokenProvider`
1075
+ * option in `pushNotifications` config is responsible for calling it after
1076
+ * obtaining the token from the OS / browser.
1077
+ */
1078
+ async register(payload) {
1079
+ await getApiClient().post("/users/me/devices", payload);
1080
+ },
1081
+ /**
1082
+ * Remove a device token from the chat server.
1083
+ * Call this on logout so the user stops receiving push notifications on this device.
1084
+ */
1085
+ async remove(deviceId) {
1086
+ await getApiClient().post(`/users/me/devices/${deviceId}/remove`);
1087
+ }
1088
+ };
1089
+
1090
+ // src/api/users.ts
1091
+ var usersApi = {
1092
+ async list(params = {}) {
1093
+ const { data } = await getApiClient().get("/users", { params });
1094
+ return data;
1095
+ },
1096
+ async getById(userId) {
1097
+ const { data } = await getApiClient().get(`/users/${userId}`);
1098
+ return data;
1099
+ },
1100
+ async getLastSeen(userId) {
1101
+ const { data } = await getApiClient().get(`/users/${userId}`);
1102
+ return { lastSeenAt: data.lastSeenAt ?? null };
1103
+ },
1104
+ /**
1105
+ * Update basic profile fields for the current user.
1106
+ * Works in both builtin and non-builtin modes. Use this to push an immediate
1107
+ * profile update to the chat server when the host app knows a change just
1108
+ * happened — without waiting for the next 2-hour sync cycle.
1109
+ */
1110
+ async updateProfile(payload) {
1111
+ const { data } = await getApiClient().post("/users/me/update", payload);
1112
+ return data;
1113
+ },
1114
+ /**
1115
+ * Update notification preferences for the current user.
1116
+ * Partial update — only send fields you want to change.
1117
+ * A prefs record is automatically created with defaults when a device
1118
+ * token is first registered, so this never fails with "not found".
1119
+ */
1120
+ async updatePreferences(prefs) {
1121
+ const { data } = await getApiClient().post("/users/me/preferences", prefs);
1122
+ return data;
1123
+ },
1124
+ /**
1125
+ * Fetch current notification preferences for the current user.
1126
+ * Returns null if no prefs record exists yet (all defaults apply).
1127
+ */
1128
+ async getPreferences() {
1129
+ try {
1130
+ const { data } = await getApiClient().get("/users/me/preferences");
1131
+ return data;
1132
+ } catch {
1133
+ return null;
1134
+ }
1097
1135
  }
1098
1136
  };
1099
1137