@amityco/ts-sdk 7.28.0 → 7.28.1-1735d08b.0

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.
Files changed (128) hide show
  1. package/dist/@types/core/errors.d.ts +4 -1
  2. package/dist/@types/core/errors.d.ts.map +1 -1
  3. package/dist/@types/core/transport.d.ts +1 -0
  4. package/dist/@types/core/transport.d.ts.map +1 -1
  5. package/dist/@types/domains/channel.d.ts +13 -1
  6. package/dist/@types/domains/channel.d.ts.map +1 -1
  7. package/dist/@types/domains/client.d.ts +86 -0
  8. package/dist/@types/domains/client.d.ts.map +1 -1
  9. package/dist/@types/domains/content.d.ts +11 -0
  10. package/dist/@types/domains/content.d.ts.map +1 -1
  11. package/dist/@types/domains/user.d.ts +31 -0
  12. package/dist/@types/domains/user.d.ts.map +1 -1
  13. package/dist/channelRepository/observers/getChannels/ChannelLiveCollectionController.d.ts.map +1 -1
  14. package/dist/channelRepository/observers/searchChannels/SearchChannelLiveCollectionController.d.ts.map +1 -1
  15. package/dist/channelRepository/observers/tests/integrations/getChannelsSortByLastMessage.integration.test.d.ts +2 -0
  16. package/dist/channelRepository/observers/tests/integrations/getChannelsSortByLastMessage.integration.test.d.ts.map +1 -0
  17. package/dist/channelRepository/utils/channelActivityOnLoginHandler.d.ts +16 -0
  18. package/dist/channelRepository/utils/channelActivityOnLoginHandler.d.ts.map +1 -0
  19. package/dist/channelRepository/utils/prepareChannelPayload.d.ts +9 -2
  20. package/dist/channelRepository/utils/prepareChannelPayload.d.ts.map +1 -1
  21. package/dist/channelRepository/utils/tests/channelPayloadGuard.test.d.ts +2 -0
  22. package/dist/channelRepository/utils/tests/channelPayloadGuard.test.d.ts.map +1 -0
  23. package/dist/channelRepository/utils/tests/integrations/channelActivity.integration.test.d.ts +2 -0
  24. package/dist/channelRepository/utils/tests/integrations/channelActivity.integration.test.d.ts.map +1 -0
  25. package/dist/channelRepository/utils/tests/updateChannelActivityTimestamps.test.d.ts +2 -0
  26. package/dist/channelRepository/utils/tests/updateChannelActivityTimestamps.test.d.ts.map +1 -0
  27. package/dist/channelRepository/utils/updateChannelActivityTimestamps.d.ts +64 -0
  28. package/dist/channelRepository/utils/updateChannelActivityTimestamps.d.ts.map +1 -0
  29. package/dist/client/api/createClient.d.ts.map +1 -1
  30. package/dist/client/api/getModuleSettings.d.ts +25 -0
  31. package/dist/client/api/getModuleSettings.d.ts.map +1 -0
  32. package/dist/client/api/index.d.ts +1 -0
  33. package/dist/client/api/index.d.ts.map +1 -1
  34. package/dist/client/api/resumeSession.d.ts.map +1 -1
  35. package/dist/client/api/setupLoginSubscriptions.d.ts.map +1 -1
  36. package/dist/client/api/tests/integration/moduleSettings.integration.test.d.ts +2 -0
  37. package/dist/client/api/tests/integration/moduleSettings.integration.test.d.ts.map +1 -0
  38. package/dist/client/index.d.ts +1 -0
  39. package/dist/client/index.d.ts.map +1 -1
  40. package/dist/client/utils/parseModuleSettings.d.ts +9 -0
  41. package/dist/client/utils/parseModuleSettings.d.ts.map +1 -0
  42. package/dist/client/utils/resolveModuleAvailability.d.ts +39 -0
  43. package/dist/client/utils/resolveModuleAvailability.d.ts.map +1 -0
  44. package/dist/client/utils/tests/resolveModuleAvailability.test.d.ts +2 -0
  45. package/dist/client/utils/tests/resolveModuleAvailability.test.d.ts.map +1 -0
  46. package/dist/commentRepository/api/flagComment.d.ts +72 -5
  47. package/dist/commentRepository/api/flagComment.d.ts.map +1 -1
  48. package/dist/commentRepository/internalApi/flagCommentWithOptions.d.ts +13 -0
  49. package/dist/commentRepository/internalApi/flagCommentWithOptions.d.ts.map +1 -0
  50. package/dist/commentRepository/internalApi/flagCommentWithReasonString.d.ts +17 -0
  51. package/dist/commentRepository/internalApi/flagCommentWithReasonString.d.ts.map +1 -0
  52. package/dist/commentRepository/internalApi/index.d.ts +2 -0
  53. package/dist/commentRepository/internalApi/index.d.ts.map +1 -1
  54. package/dist/commentRepository/internalApi/tests/integration/flagCommentWithOptions.integration.test.d.ts +2 -0
  55. package/dist/commentRepository/internalApi/tests/integration/flagCommentWithOptions.integration.test.d.ts.map +1 -0
  56. package/dist/commentRepository/internalApi/tests/integration/flagCommentWithReasonString.integration.test.d.ts +2 -0
  57. package/dist/commentRepository/internalApi/tests/integration/flagCommentWithReasonString.integration.test.d.ts.map +1 -0
  58. package/dist/core/errors.d.ts +20 -0
  59. package/dist/core/errors.d.ts.map +1 -1
  60. package/dist/core/microtasks.d.ts.map +1 -1
  61. package/dist/core/query/sorting.d.ts +10 -0
  62. package/dist/core/query/sorting.d.ts.map +1 -1
  63. package/dist/core/query/tests/sorting.test.d.ts +2 -0
  64. package/dist/core/query/tests/sorting.test.d.ts.map +1 -0
  65. package/dist/core/tests/microtasks.test.d.ts +2 -0
  66. package/dist/core/tests/microtasks.test.d.ts.map +1 -0
  67. package/dist/core/transports/tests/integration/serverErrorCodes.integration.test.d.ts +2 -0
  68. package/dist/core/transports/tests/integration/serverErrorCodes.integration.test.d.ts.map +1 -0
  69. package/dist/core/transports/tests/moduleNotEntitled.test.d.ts +2 -0
  70. package/dist/core/transports/tests/moduleNotEntitled.test.d.ts.map +1 -0
  71. package/dist/core/transports/utils.d.ts.map +1 -1
  72. package/dist/index.cjs.js +941 -75
  73. package/dist/index.d.ts +2 -0
  74. package/dist/index.d.ts.map +1 -1
  75. package/dist/index.esm.js +939 -76
  76. package/dist/index.umd.js +2 -2
  77. package/dist/messagePreview/utils/getChannelMessagePreviewWithUser.d.ts +1 -0
  78. package/dist/messagePreview/utils/getChannelMessagePreviewWithUser.d.ts.map +1 -1
  79. package/dist/messageRepository/api/createMessage.d.ts.map +1 -1
  80. package/dist/messageRepository/api/flagMessage.d.ts +73 -6
  81. package/dist/messageRepository/api/flagMessage.d.ts.map +1 -1
  82. package/dist/messageRepository/api/tests/integration/flagMessage.overloads.integration.test.d.ts +2 -0
  83. package/dist/messageRepository/api/tests/integration/flagMessage.overloads.integration.test.d.ts.map +1 -0
  84. package/dist/messageRepository/internalApi/flagMessageWithOptions.d.ts +13 -0
  85. package/dist/messageRepository/internalApi/flagMessageWithOptions.d.ts.map +1 -0
  86. package/dist/messageRepository/internalApi/flagMessageWithReasonString.d.ts +18 -0
  87. package/dist/messageRepository/internalApi/flagMessageWithReasonString.d.ts.map +1 -0
  88. package/dist/messageRepository/internalApi/tests/integration/flagMessageWithOptions.integration.test.d.ts +2 -0
  89. package/dist/messageRepository/internalApi/tests/integration/flagMessageWithOptions.integration.test.d.ts.map +1 -0
  90. package/dist/messageRepository/internalApi/tests/integration/flagMessageWithReasonString.integration.test.d.ts +2 -0
  91. package/dist/messageRepository/internalApi/tests/integration/flagMessageWithReasonString.integration.test.d.ts.map +1 -0
  92. package/dist/postRepository/api/flagPost.d.ts +73 -6
  93. package/dist/postRepository/api/flagPost.d.ts.map +1 -1
  94. package/dist/postRepository/api/tests/integration/flagPost.overloads.integration.test.d.ts +2 -0
  95. package/dist/postRepository/api/tests/integration/flagPost.overloads.integration.test.d.ts.map +1 -0
  96. package/dist/postRepository/internalApi/flagPostWithOptions.d.ts +13 -0
  97. package/dist/postRepository/internalApi/flagPostWithOptions.d.ts.map +1 -0
  98. package/dist/postRepository/internalApi/flagPostWithReasonString.d.ts +17 -0
  99. package/dist/postRepository/internalApi/flagPostWithReasonString.d.ts.map +1 -0
  100. package/dist/postRepository/internalApi/index.d.ts +2 -0
  101. package/dist/postRepository/internalApi/index.d.ts.map +1 -1
  102. package/dist/postRepository/internalApi/tests/integration/flagPostWithOptions.integration.test.d.ts +2 -0
  103. package/dist/postRepository/internalApi/tests/integration/flagPostWithOptions.integration.test.d.ts.map +1 -0
  104. package/dist/postRepository/internalApi/tests/integration/flagPostWithReasonString.integration.test.d.ts +2 -0
  105. package/dist/postRepository/internalApi/tests/integration/flagPostWithReasonString.integration.test.d.ts.map +1 -0
  106. package/dist/userRepository/api/flagUser.d.ts +50 -9
  107. package/dist/userRepository/api/flagUser.d.ts.map +1 -1
  108. package/dist/userRepository/api/flagUserBehavior.d.ts +29 -0
  109. package/dist/userRepository/api/flagUserBehavior.d.ts.map +1 -0
  110. package/dist/userRepository/api/flagUserProfile.d.ts +29 -0
  111. package/dist/userRepository/api/flagUserProfile.d.ts.map +1 -0
  112. package/dist/userRepository/api/index.d.ts +2 -0
  113. package/dist/userRepository/api/index.d.ts.map +1 -1
  114. package/dist/userRepository/api/tests/integration/flagUser.overloads.integration.test.d.ts +2 -0
  115. package/dist/userRepository/api/tests/integration/flagUser.overloads.integration.test.d.ts.map +1 -0
  116. package/dist/userRepository/api/tests/integration/flagUserBehavior.integration.test.d.ts +2 -0
  117. package/dist/userRepository/api/tests/integration/flagUserBehavior.integration.test.d.ts.map +1 -0
  118. package/dist/userRepository/api/tests/integration/flagUserProfile.integration.test.d.ts +2 -0
  119. package/dist/userRepository/api/tests/integration/flagUserProfile.integration.test.d.ts.map +1 -0
  120. package/dist/userRepository/utils/submitUserReport.d.ts +10 -0
  121. package/dist/userRepository/utils/submitUserReport.d.ts.map +1 -0
  122. package/dist/userRepository/utils/userReport.d.ts +35 -0
  123. package/dist/userRepository/utils/userReport.d.ts.map +1 -0
  124. package/dist/utils/contentFlag.d.ts +28 -0
  125. package/dist/utils/contentFlag.d.ts.map +1 -0
  126. package/dist/utils/tests/dummy/channel.d.ts +4 -0
  127. package/dist/utils/tests/dummy/channel.d.ts.map +1 -1
  128. package/package.json +1 -1
package/dist/index.cjs.js CHANGED
@@ -58,6 +58,18 @@ exports.UserReportTypeEnum = void 0;
58
58
  UserReportTypeEnum["AVATAR"] = "avatarFileId";
59
59
  UserReportTypeEnum["BEHAVIOR"] = "behavior";
60
60
  })(exports.UserReportTypeEnum || (exports.UserReportTypeEnum = {}));
61
+ /**
62
+ * The profile field a user is reported for in `UserRepository.flagUserProfile`.
63
+ * Each member is the backend `reportType` wire value. There is deliberately no
64
+ * behavior member: behavior reports need a reason and go through
65
+ * `UserRepository.flagUserBehavior`.
66
+ */
67
+ exports.UserProfileFieldEnum = void 0;
68
+ (function (UserProfileFieldEnum) {
69
+ UserProfileFieldEnum["DISPLAY_NAME"] = "displayName";
70
+ UserProfileFieldEnum["DESCRIPTION"] = "description";
71
+ UserProfileFieldEnum["AVATAR"] = "avatarFileId";
72
+ })(exports.UserProfileFieldEnum || (exports.UserProfileFieldEnum = {}));
61
73
 
62
74
  const FileType = Object.freeze({
63
75
  FILE: 'file',
@@ -812,6 +824,40 @@ class ASCConnectionError extends ASCError {
812
824
  this.event = event;
813
825
  }
814
826
  }
827
+ /**
828
+ * Thrown when the network does not own a module the call needs. Raised from
829
+ * any module endpoint under `enforce` enforcement, mapped from app code
830
+ * `400325` — never from HTTP 403 alone, which already covers a role problem
831
+ * (`400300` / `400301`), a visitor (`403999`) and a bot (`403998`).
832
+ *
833
+ * `modules` carries **every** key the refusal named, as raw strings, so a
834
+ * caller can say which entitlement is absent without a second request.
835
+ *
836
+ * @category Errors
837
+ */
838
+ class AmityModuleNotEntitledError extends ASCApiError {
839
+ /**
840
+ * @param message The server's message, e.g. `Module not entitled: chat, live`
841
+ * @param modules Every module key from the rejection's `data.modules`
842
+ */
843
+ constructor(message, modules = []) {
844
+ super(message, 400325 /* Amity.ServerError.MODULE_NOT_ENTITLED */, "error" /* Amity.ErrorLevel.ERROR */);
845
+ this.modules = modules;
846
+ this.type = 'AmityModuleNotEntitledError';
847
+ }
848
+ }
849
+ /**
850
+ * Input sanitization related error
851
+ * @category Errors
852
+ */
853
+ class ASCInvalidParameterError extends ASCError {
854
+ /**
855
+ * @param message A custom error message
856
+ */
857
+ constructor(message) {
858
+ super(message, 800110 /* Amity.ClientError.INVALID_PARAMETERS */, "error" /* Amity.ErrorLevel.ERROR */);
859
+ }
860
+ }
815
861
 
816
862
  let activeClient = null;
817
863
  /**
@@ -1585,6 +1631,24 @@ const sortByLastUpdated = ({ updatedAt: a = 0 }, { updatedAt: b = 0 }) => new Da
1585
1631
  * Sorting a collection by the items with most recent activity
1586
1632
  */
1587
1633
  const sortByLastActivity = ({ lastActivity: a }, { lastActivity: b }) => new Date(b).valueOf() - new Date(a).valueOf();
1634
+ /**
1635
+ * Sorting a channel collection by the time of its newest message (newest first).
1636
+ * Channels whose `lastMessageAt` is `null` sort last, ordered by `createdAt`
1637
+ * (newest first) among themselves, matching the server's `sortBy=lastMessage`
1638
+ * order so the local sort agrees with the page order.
1639
+ */
1640
+ const sortByLastMessage = (a, b) => {
1641
+ var _a, _b;
1642
+ const aAt = (_a = a.lastMessageAt) !== null && _a !== void 0 ? _a : null;
1643
+ const bAt = (_b = b.lastMessageAt) !== null && _b !== void 0 ? _b : null;
1644
+ if (aAt !== null && bAt !== null)
1645
+ return new Date(bAt).valueOf() - new Date(aAt).valueOf();
1646
+ if (aAt !== null)
1647
+ return -1;
1648
+ if (bAt !== null)
1649
+ return 1;
1650
+ return new Date(b.createdAt).valueOf() - new Date(a.createdAt).valueOf();
1651
+ };
1588
1652
  /**
1589
1653
  * Filter items by untilAt timestamp based on sort direction
1590
1654
  * - For 'lastCreated' (newest first): untilAt acts as lower bound, excludes items older than boundary
@@ -1669,8 +1733,13 @@ const scheduleTask = (task) => {
1669
1733
  clearTimeout(timer);
1670
1734
  tasks.push(task);
1671
1735
  timer = setTimeout(() => {
1672
- tasks.forEach(fn => fn());
1736
+ // Swap the queue out before running it. A task that schedules another task
1737
+ // while the batch runs (an event handler that fires an event) must land in
1738
+ // a fresh queue and its own timer, not in the array being drained and then
1739
+ // discarded.
1740
+ const batch = tasks;
1673
1741
  tasks = [];
1742
+ batch.forEach(fn => fn());
1674
1743
  }, 0);
1675
1744
  };
1676
1745
 
@@ -1961,6 +2030,22 @@ function computeUrl(type, region) {
1961
2030
 
1962
2031
  const uuid = () => uuid__default["default"].v4().toString();
1963
2032
 
2033
+ /**
2034
+ * Reads the module keys a `MODULE_NOT_ENTITLED` rejection named.
2035
+ *
2036
+ * Every entry is kept, as a raw string: one call can need more than one
2037
+ * module, and a key this build predates is still the only part of the
2038
+ * payload a customer can act on.
2039
+ *
2040
+ * @category Transport
2041
+ * @hidden
2042
+ */
2043
+ const extractNotEntitledModules = (data) => {
2044
+ const { modules } = data !== null && data !== void 0 ? data : {};
2045
+ if (!Array.isArray(modules))
2046
+ return [];
2047
+ return modules.filter((module) => typeof module === 'string');
2048
+ };
1964
2049
  /**
1965
2050
  * Unwraps v3 server payload (for error handling and type extraction)
1966
2051
  *
@@ -1980,6 +2065,15 @@ const unwrapPayload = (response) => {
1980
2065
  throw new ASCUnknownError(response.code);
1981
2066
  }
1982
2067
  else if (response.status === 'error') {
2068
+ /*
2069
+ * An entitlement refusal must not arrive as a generic failure: a customer
2070
+ * cannot then tell a module they have not bought from an outage. Keyed on
2071
+ * the app code, never on the HTTP status, so a role or membership problem
2072
+ * still maps to the generic error.
2073
+ */
2074
+ if (response.code === 400325 /* Amity.ServerError.MODULE_NOT_ENTITLED */) {
2075
+ throw new AmityModuleNotEntitledError(response.message, extractNotEntitledModules(response.data));
2076
+ }
1983
2077
  throw new ASCApiError(response.message, response.code, "error" /* Amity.ErrorLevel.ERROR */);
1984
2078
  }
1985
2079
  // unjust, but helps force uncast "T | undefined" to allow deconstruction without warnings
@@ -3808,24 +3902,185 @@ const handleSubChannelUpdated = async (subChannel) => {
3808
3902
  }
3809
3903
  };
3810
3904
 
3905
+ const BOTH_FIELDS = { lastActivity: true, lastMessageAt: true };
3906
+ const floorKey = (channelInternalId) => [
3907
+ 'channelActivity',
3908
+ 'confirmedMessageAt',
3909
+ channelInternalId,
3910
+ ];
3911
+ /**
3912
+ * The newest server-confirmed message time known for a channel, keyed by the
3913
+ * channel cache key (`channelInternalId`). A server channel payload never moves
3914
+ * `lastActivity` / `lastMessageAt` below it: the backend writes those fields in
3915
+ * its `message.created` handler after the send call returns, so a page fetched
3916
+ * in that window still carries the old values, and nothing else corrects them.
3917
+ * The floor lets an older server snapshot lose to a newer server fact.
3918
+ */
3919
+ const getConfirmedMessageAt = (channelInternalId) => { var _a; return (_a = pullFromCache(floorKey(channelInternalId))) === null || _a === void 0 ? void 0 : _a.data; };
3920
+ const recordConfirmedMessageAt = (channel, at) => {
3921
+ const key = getResolver('channel')(channel);
3922
+ const current = getConfirmedMessageAt(key);
3923
+ if (!current || convertDateStringToTimestamp(current) < convertDateStringToTimestamp(at)) {
3924
+ pushToCache(floorKey(key), at);
3925
+ }
3926
+ };
3927
+ /**
3928
+ * Applies the confirmed-message floor to a raw channel payload's timestamps.
3929
+ * Returns the payload's own values when no floor is known or they are newer.
3930
+ */
3931
+ const applyConfirmedMessageFloor = (channel) => {
3932
+ const floor = getConfirmedMessageAt(channel.channelInternalId);
3933
+ if (!floor)
3934
+ return { lastActivity: channel.lastActivity, lastMessageAt: channel.lastMessageAt };
3935
+ const floorTs = convertDateStringToTimestamp(floor);
3936
+ const below = (value) => !value || convertDateStringToTimestamp(value) < floorTs;
3937
+ return {
3938
+ lastActivity: below(channel.lastActivity) ? floor : channel.lastActivity,
3939
+ lastMessageAt: below(channel.lastMessageAt) ? floor : channel.lastMessageAt,
3940
+ };
3941
+ };
3942
+ /**
3943
+ * The channel cache is keyed by `channelInternalId`, but a message names its
3944
+ * channel by whichever id the producer had: the raw MQTT payload carries the
3945
+ * internal id, a converted `Amity.InternalMessage` carries the public id, and
3946
+ * the optimistic message carries the sub-channel's `channelId`. Try the direct
3947
+ * key first, then match any of the three ids.
3948
+ */
3949
+ const findCachedChannel = (channelId) => {
3950
+ var _a, _b, _c;
3951
+ const direct = (_a = pullFromCache(['channel', 'get', channelId])) === null || _a === void 0 ? void 0 : _a.data;
3952
+ if (direct)
3953
+ return direct;
3954
+ return (_c = (_b = queryCache(['channel', 'get'])) === null || _b === void 0 ? void 0 : _b.find(({ data }) => data.channelInternalId === channelId ||
3955
+ data.channelId === channelId ||
3956
+ data.channelPublicId === channelId)) === null || _c === void 0 ? void 0 : _c.data;
3957
+ };
3958
+ const isNewer = (stored, at) => !stored || convertDateStringToTimestamp(stored) < convertDateStringToTimestamp(at);
3959
+ const isSameInstant = (stored, at) => !!stored && convertDateStringToTimestamp(stored) === convertDateStringToTimestamp(at);
3960
+ /** Pushes the changed fields in one write and emits one `local.channel.updated`. */
3961
+ const commit = (channel, changes) => {
3962
+ if (Object.keys(changes).length === 0)
3963
+ return false;
3964
+ const updated = shallowClone(channel, changes);
3965
+ // Write back under the key the cache actually uses (the resolver key), not
3966
+ // under `channel.channelId`, which can differ from `channelInternalId`.
3967
+ pushToCache(['channel', 'get', getResolver('channel')(updated)], updated);
3968
+ fireEvent('local.channel.updated', {
3969
+ channels: [updated],
3970
+ channelUsers: [],
3971
+ users: [],
3972
+ files: [],
3973
+ });
3974
+ return true;
3975
+ };
3976
+ /**
3977
+ * Single owner of every local write to a channel's ordering timestamps,
3978
+ * `lastActivity` and `lastMessageAt` (ChannelActivityService v1).
3979
+ *
3980
+ * - Monotonic per field: a field moves only when `at` is newer than the stored
3981
+ * value (or the stored value is `null`), so a late or replayed event never
3982
+ * moves a channel down the list.
3983
+ * - One write: both fields are read, compared and pushed in a single cache
3984
+ * update, followed by one `local.channel.updated` event so every open channel
3985
+ * collection re-sorts once.
3986
+ * - Server channel payloads never go through here; they overwrite unguarded.
3987
+ *
3988
+ * @returns `true` when at least one field moved
3989
+ * @category private
3990
+ */
3991
+ const updateChannelActivityTimestamps = (channelId, at, fields = BOTH_FIELDS, options = {}) => {
3992
+ const client = getActiveClient();
3993
+ if (!client.cache || !channelId || !at)
3994
+ return false;
3995
+ const channel = findCachedChannel(channelId);
3996
+ if (!channel)
3997
+ return false;
3998
+ if (options.confirmed)
3999
+ recordConfirmedMessageAt(channel, at);
4000
+ const changes = {};
4001
+ if (fields.lastActivity && isNewer(channel.lastActivity, at))
4002
+ changes.lastActivity = at;
4003
+ if (fields.lastMessageAt && isNewer(channel.lastMessageAt, at))
4004
+ changes.lastMessageAt = at;
4005
+ return commit(channel, changes);
4006
+ };
4007
+ /**
4008
+ * Local correction for the current user's own send (ChannelActivityService v1
4009
+ * REQ-009, Trigger Matrix row 1b). Once the server confirms the message, each
4010
+ * field that still holds the device-clock `localAt` written at send time is
4011
+ * replaced by the server's `serverAt`, even when that is older. A field a newer
4012
+ * message has already moved is left alone. One write, one change notification,
4013
+ * nothing when neither field still holds `localAt`.
4014
+ *
4015
+ * @returns `true` when at least one field was replaced
4016
+ * @category private
4017
+ */
4018
+ const confirmOwnMessage = (channelId, localAt, serverAt) => {
4019
+ const client = getActiveClient();
4020
+ if (!client.cache || !channelId || !localAt || !serverAt)
4021
+ return false;
4022
+ const channel = findCachedChannel(channelId);
4023
+ if (!channel)
4024
+ return false;
4025
+ // The response time is a server fact, whether or not a field still holds the local time.
4026
+ recordConfirmedMessageAt(channel, serverAt);
4027
+ if (isSameInstant(localAt, serverAt))
4028
+ return false;
4029
+ const changes = {};
4030
+ if (isSameInstant(channel.lastActivity, localAt))
4031
+ changes.lastActivity = serverAt;
4032
+ if (isSameInstant(channel.lastMessageAt, localAt))
4033
+ changes.lastMessageAt = serverAt;
4034
+ return commit(channel, changes);
4035
+ };
4036
+
3811
4037
  const MARKER_INCLUDED_CHANNEL_TYPE = ['broadcast', 'conversation', 'community'];
3812
4038
  const isUnreadCountSupport = ({ type }) => MARKER_INCLUDED_CHANNEL_TYPE.includes(type);
3813
- function convertFromRaw(channel, options = { isMessagePreviewUpdated: true }) {
4039
+ /** Maps each channel's public id to the `createdAt` of the preview the payload carries for it. */
4040
+ const previewCreatedAtByChannel = (rawPayload) => {
3814
4041
  var _a;
4042
+ return ((_a = rawPayload.messagePreviews) !== null && _a !== void 0 ? _a : []).reduce((map, preview) => {
4043
+ // eslint-disable-next-line no-param-reassign
4044
+ map[preview.channelPublicId] = preview.createdAt;
4045
+ return map;
4046
+ }, {});
4047
+ };
4048
+ function convertFromRaw(channel, options = { isMessagePreviewUpdated: true }) {
4049
+ var _a, _b;
3815
4050
  let { messagePreviewId } = channel;
3816
4051
  const messagePreviewChannelCache = (_a = pullFromCache([
3817
4052
  'messagePreviewChannel',
3818
4053
  'get',
3819
4054
  channel.channelId,
3820
4055
  ])) === null || _a === void 0 ? void 0 : _a.data;
3821
- if ((messagePreviewChannelCache === null || messagePreviewChannelCache === void 0 ? void 0 : messagePreviewChannelCache.messagePreviewId) && !options.isMessagePreviewUpdated) {
3822
- messagePreviewId = messagePreviewChannelCache.messagePreviewId;
4056
+ if (messagePreviewChannelCache === null || messagePreviewChannelCache === void 0 ? void 0 : messagePreviewChannelCache.messagePreviewId) {
4057
+ if (!options.isMessagePreviewUpdated) {
4058
+ messagePreviewId = messagePreviewChannelCache.messagePreviewId;
4059
+ }
4060
+ else {
4061
+ // A server payload can predate the backend's post-message update of the
4062
+ // channel. The preview cache only ever moves forward (updateChannelMessagePreviewCache,
4063
+ // handleMessageCreated), so when the payload names no preview, or an older
4064
+ // one than the cache holds, keep the cached id: otherwise the row falls back
4065
+ // to "no message" or to the previous message right after the user sent one.
4066
+ const serverPreviewAt = (_b = options.serverPreviewCreatedAt) === null || _b === void 0 ? void 0 : _b[channel.channelId];
4067
+ const cacheIsNewer = !!serverPreviewAt &&
4068
+ convertDateStringToTimestamp(messagePreviewChannelCache.createdAt) >
4069
+ convertDateStringToTimestamp(serverPreviewAt);
4070
+ if (!messagePreviewId || cacheIsNewer) {
4071
+ messagePreviewId = messagePreviewChannelCache.messagePreviewId;
4072
+ }
4073
+ }
3823
4074
  }
3824
- return Object.assign(Object.assign({}, channel), { defaultSubChannelId: channel.channelInternalId, isUnreadCountSupport: isUnreadCountSupport(channel), messagePreviewId });
4075
+ return Object.assign(Object.assign(Object.assign({}, channel), applyConfirmedMessageFloor(channel)), { defaultSubChannelId: channel.channelInternalId, isUnreadCountSupport: isUnreadCountSupport(channel), messagePreviewId });
3825
4076
  }
3826
4077
  const preUpdateChannelCache = (rawPayload, options = { isMessagePreviewUpdated: true }) => {
4078
+ const serverPreviewCreatedAt = previewCreatedAtByChannel(rawPayload);
3827
4079
  ingestInCache({
3828
- channels: rawPayload.channels.map(channel => convertFromRaw(channel, { isMessagePreviewUpdated: options.isMessagePreviewUpdated })),
4080
+ channels: rawPayload.channels.map(channel => convertFromRaw(channel, {
4081
+ isMessagePreviewUpdated: options.isMessagePreviewUpdated,
4082
+ serverPreviewCreatedAt,
4083
+ })),
3829
4084
  });
3830
4085
  };
3831
4086
  const updateChannelUnread = ({ currentUserId, channels, channelUsers, }) => {
@@ -3913,7 +4168,11 @@ const prepareChannelPayload = async (rawPayload, options = { isMessagePreviewUpd
3913
4168
  }
3914
4169
  }
3915
4170
  // convert raw channel to internal channel
3916
- const channels = rawPayload.channels.map(payload => convertFromRaw(payload, { isMessagePreviewUpdated: options.isMessagePreviewUpdated }));
4171
+ const serverPreviewCreatedAt = previewCreatedAtByChannel(rawPayload);
4172
+ const channels = rawPayload.channels.map(payload => convertFromRaw(payload, {
4173
+ isMessagePreviewUpdated: options.isMessagePreviewUpdated,
4174
+ serverPreviewCreatedAt,
4175
+ }));
3917
4176
  // convert raw channel user to membership (add user object)
3918
4177
  const channelUsers = rawPayload.channelUsers.map(channelUser => {
3919
4178
  return convertRawMembershipToMembership(channelUser);
@@ -5476,6 +5735,95 @@ const getForYouFeedSetting = async () => {
5476
5735
  };
5477
5736
  /* end_public_function */
5478
5737
 
5738
+ const ENFORCEMENT_MODES = ['off', 'shadow', 'enforce'];
5739
+ /**
5740
+ * An unrecognised mode decodes to `off`, and so does an absent one. A mode
5741
+ * this build does not know must not withhold anything — defaulting to
5742
+ * `enforce` would let a server-side rename black out a customer's app.
5743
+ *
5744
+ * @category private
5745
+ */
5746
+ const parseEnforcement = (mode) => {
5747
+ const match = ENFORCEMENT_MODES.find(value => value === mode);
5748
+ return match !== null && match !== void 0 ? match : 'off';
5749
+ };
5750
+ const parseGrants = (modules) => {
5751
+ const grants = {};
5752
+ Object.entries(modules !== null && modules !== void 0 ? modules : {}).forEach(([key, granted]) => {
5753
+ grants[key] = granted === true;
5754
+ });
5755
+ return grants;
5756
+ };
5757
+ /**
5758
+ * Every catalog entry survives, including one whose key this build has never
5759
+ * heard of, so a module added server-side is still listable.
5760
+ *
5761
+ * @category private
5762
+ */
5763
+ const parseCatalog = (catalog) => {
5764
+ const parsed = {};
5765
+ Object.entries(catalog !== null && catalog !== void 0 ? catalog : {}).forEach(([key, definition]) => {
5766
+ const rawRequires = definition === null || definition === void 0 ? void 0 : definition.requires;
5767
+ const requires = Array.isArray(rawRequires)
5768
+ ? rawRequires.filter((entry) => typeof entry === 'string')
5769
+ : [];
5770
+ parsed[key] = {
5771
+ label: typeof (definition === null || definition === void 0 ? void 0 : definition.label) === 'string' ? definition.label : key,
5772
+ kind: (definition === null || definition === void 0 ? void 0 : definition.kind) === 'setting' ? 'setting' : 'api',
5773
+ requires,
5774
+ };
5775
+ });
5776
+ return parsed;
5777
+ };
5778
+ /**
5779
+ * Decodes `GET /api/v3/network-settings/modules`. Nothing is trimmed: the
5780
+ * catalog is the dependency table callers resolve against, and a client that
5781
+ * cannot see it has to hardcode one.
5782
+ *
5783
+ * @category private
5784
+ */
5785
+ const parseModuleSettings = (raw) => {
5786
+ var _a;
5787
+ return ({
5788
+ enforcement: parseEnforcement((_a = raw === null || raw === void 0 ? void 0 : raw.enforcement) !== null && _a !== void 0 ? _a : raw === null || raw === void 0 ? void 0 : raw.mode),
5789
+ modules: parseGrants(raw === null || raw === void 0 ? void 0 : raw.modules),
5790
+ catalog: parseCatalog(raw === null || raw === void 0 ? void 0 : raw.catalog),
5791
+ });
5792
+ };
5793
+
5794
+ /* begin_public_function
5795
+ id: client.getModuleSettings
5796
+ */
5797
+ /**
5798
+ * ```js
5799
+ * import { Client } from '@amityco/ts-sdk'
5800
+ * const moduleSettings = await Client.getModuleSettings()
5801
+ * ```
5802
+ *
5803
+ * Fetches the network's module entitlements: which modules the network was
5804
+ * granted, whether core is enforcing those grants, and the catalog of all
5805
+ * modules with their dependency chains.
5806
+ *
5807
+ * The payload is returned whole — `catalog` is the dependency table
5808
+ * {@link resolveModuleAvailability} reads, and a client that cannot see it has
5809
+ * to hardcode one.
5810
+ *
5811
+ * The read is **advisory**. It tells a host what to offer; under `enforce` the
5812
+ * backend refuses a call to an unowned module regardless of what was resolved
5813
+ * here, and that refusal arrives as `AmityModuleNotEntitledError`.
5814
+ *
5815
+ * @returns A Promise of {@link Amity.ModuleSettings} object
5816
+ *
5817
+ * @category Client API
5818
+ * @async
5819
+ */
5820
+ const getModuleSettings = async () => {
5821
+ const client = getActiveClient();
5822
+ const { data } = await client.http.get(`/api/v3/network-settings/modules`);
5823
+ return parseModuleSettings(data);
5824
+ };
5825
+ /* end_public_function */
5826
+
5479
5827
  const checkUserPermission = (userId, permission) => {
5480
5828
  var _a;
5481
5829
  const user = (_a = pullFromCache(['user', 'get', userId])) === null || _a === void 0 ? void 0 : _a.data;
@@ -7906,6 +8254,52 @@ const postCommentCountEngineOnLoginHandler = () => onSessionStateChange(state =>
7906
8254
  }
7907
8255
  });
7908
8256
 
8257
+ /**
8258
+ * Session-wide owner of the local `lastActivity` / `lastMessageAt` updates
8259
+ * (ChannelActivityService v1, Web migration rows W1 – W5).
8260
+ *
8261
+ * Registered once per session from `setupLoginSubscriptions` and
8262
+ * `resumeSession`, so the update runs whether or not a channel collection is
8263
+ * open, and exactly once per message however many collections are open.
8264
+ *
8265
+ * It listens to the raw events rather than `onMessageCreatedMqtt`, so it does
8266
+ * not duplicate that subscriber's side effects (mark-read, unread recount).
8267
+ *
8268
+ * @category private
8269
+ */
8270
+ const channelActivityOnLoginHandler = () => {
8271
+ const client = getActiveClient();
8272
+ const disposers = [
8273
+ // Any user's new message, in any message feed of the channel. The raw
8274
+ // payload's `channelId` is the channel's internal id.
8275
+ createEventSubscriber(client, 'channelActivity', 'message.created', payload => {
8276
+ payload.messages.forEach(message => {
8277
+ updateChannelActivityTimestamps(message.channelId, message.createdAt, undefined, {
8278
+ confirmed: true,
8279
+ });
8280
+ });
8281
+ }),
8282
+ // The current user's own send fires this three times: with the optimistic
8283
+ // message at send time (Syncing), on the create response (Synced), and on
8284
+ // failure (Error). The device-clock time of the Syncing / Error fires was
8285
+ // already applied synchronously in createMessageOptimistic, and replaying it
8286
+ // here could undo the server correction made on the response
8287
+ // (confirmOwnMessage). Only the server-confirmed fire goes through the guard.
8288
+ createEventSubscriber(client, 'channelActivity', 'local.message.created', payload => {
8289
+ payload.messages.forEach(message => {
8290
+ if (message.syncState !== "synced" /* Amity.SyncState.Synced */)
8291
+ return;
8292
+ updateChannelActivityTimestamps(message.channelId, message.createdAt, undefined, {
8293
+ confirmed: true,
8294
+ });
8295
+ });
8296
+ }),
8297
+ ];
8298
+ return () => {
8299
+ disposers.forEach(fn => fn());
8300
+ };
8301
+ };
8302
+
7909
8303
  const EVENTS = [
7910
8304
  'disconnected',
7911
8305
  'error',
@@ -8095,7 +8489,7 @@ const setupLoginSubscriptions = (unsubWatcher) => {
8095
8489
  // NOTE: This is a temporary solution to handle the channel marker when the user is forced to leave
8096
8490
  // the channel because currently backend can't handle this, so every time a user is banned from
8097
8491
  // a channel or the channel is deleted the channel's unread count will not be reset to zero
8098
- onChannelDeleted(removeChannelMarkerCache), onChannelMemberBanned(removeChannelMarkerCache), markReadEngineOnLoginHandler(), analyticsEngineOnLoginHandler(), objectResolverEngineOnLoginHandler(), reactionSyncEngineOnLoginHandler(), blockedUserSyncEngineOnLoginHandler(), blockingUserSyncEngineOnLoginHandler(), blockRealtimeOnLoginHandler(), resetAutoSubscriptionsOnLogout(), CursorController.clearOnLogout(), postCommentCountEngineOnLoginHandler());
8492
+ onChannelDeleted(removeChannelMarkerCache), onChannelMemberBanned(removeChannelMarkerCache), markReadEngineOnLoginHandler(), analyticsEngineOnLoginHandler(), objectResolverEngineOnLoginHandler(), reactionSyncEngineOnLoginHandler(), blockedUserSyncEngineOnLoginHandler(), blockingUserSyncEngineOnLoginHandler(), blockRealtimeOnLoginHandler(), resetAutoSubscriptionsOnLogout(), CursorController.clearOnLogout(), postCommentCountEngineOnLoginHandler(), channelActivityOnLoginHandler());
8099
8493
  if (client.useLegacyUnreadCount) {
8100
8494
  subscriptions.push(readReceiptSyncEngineOnLoginHandler());
8101
8495
  }
@@ -9200,6 +9594,7 @@ const createClient = (apiKey, apiRegion = API_REGIONS.SG, { debugSession = DEFAU
9200
9594
  getMarkerSyncConsistentMode,
9201
9595
  getProductCatalogueSetting,
9202
9596
  getForYouFeedSetting,
9597
+ getModuleSettings,
9203
9598
  /**
9204
9599
  * Prefix for the deviceId key in the local storage or async storage.
9205
9600
  * This is allow user to have multiple SDK client and Mqtt client within the same app.
@@ -9355,7 +9750,7 @@ const resumeSession = async (params, sessionHandler, config) => {
9355
9750
  // NOTE: This is a temporary solution to handle the channel marker when the user is forced to leave
9356
9751
  // the channel because currently backend can't handle this, so every time a user is banned from
9357
9752
  // a channel or the channel is deleted the channel's unread count will not be reset to zero
9358
- onChannelDeleted(removeChannelMarkerCache), onChannelMemberBanned(removeChannelMarkerCache), markReadEngineOnLoginHandler(), analyticsEngineOnLoginHandler(), objectResolverEngineOnLoginHandler());
9753
+ onChannelDeleted(removeChannelMarkerCache), onChannelMemberBanned(removeChannelMarkerCache), markReadEngineOnLoginHandler(), analyticsEngineOnLoginHandler(), objectResolverEngineOnLoginHandler(), channelActivityOnLoginHandler());
9359
9754
  if (client.useLegacyUnreadCount) {
9360
9755
  subscriptions$1.push(readReceiptSyncEngineOnLoginHandler());
9361
9756
  }
@@ -10245,6 +10640,92 @@ const getUserUnread = (callback) => {
10245
10640
  };
10246
10641
  };
10247
10642
 
10643
+ /**
10644
+ * ```js
10645
+ * import { Client, resolveModuleAvailability } from '@amityco/ts-sdk'
10646
+ *
10647
+ * const moduleSettings = await Client.getModuleSettings()
10648
+ *
10649
+ * if (resolveModuleAvailability(moduleSettings, 'live').isAvailable) {
10650
+ * // offer the Live entry point
10651
+ * }
10652
+ * ```
10653
+ *
10654
+ * Resolves whether one module is usable on this network.
10655
+ *
10656
+ * Availability is a function of all three fields of
10657
+ * {@link Amity.ModuleSettings} — the enforcement mode, the module's own grant,
10658
+ * and its prerequisite chain — combined in that order. Reading `modules`
10659
+ * directly contradicts the mode: staging answers `mode: 'off'` with
10660
+ * `modules: {}`, and every module still works.
10661
+ *
10662
+ * The dependency table comes from the payload's `catalog`, never from a
10663
+ * hardcoded copy, so a chain the backend changes takes effect without an SDK
10664
+ * release.
10665
+ *
10666
+ * The SDK does not hold the settings — the caller keeps what it fetched and
10667
+ * resolves against it. With no settings at all (a fetch that never succeeded)
10668
+ * the caller reads that as every module available: under `enforce` the backend
10669
+ * refuses the calls anyway, so the exposure is a screen that offers too much,
10670
+ * not one that withholds what a customer paid for.
10671
+ *
10672
+ * @param moduleSettings The network's module settings
10673
+ * @param moduleKey The module to resolve — an {@link Amity.ModuleKey}, so the
10674
+ * 15 keys this build knows complete and type-check while a catalog entry it
10675
+ * does not know still resolves.
10676
+ * @returns An {@link Amity.ModuleAvailability} answer
10677
+ *
10678
+ * @category Client API
10679
+ */
10680
+ const resolveModuleAvailability = (moduleSettings, moduleKey, seen = new Set()) => {
10681
+ var _a, _b, _c, _d, _e;
10682
+ const isGranted = (_a = moduleSettings.modules[moduleKey]) !== null && _a !== void 0 ? _a : false;
10683
+ /*
10684
+ * Not enforcing: nothing is withheld, and no graph walk is needed. This has
10685
+ * to come first — `off` and `shadow` resolve available whatever the grant
10686
+ * says, and a cycle would otherwise return unavailable under `off` too.
10687
+ */
10688
+ if (moduleSettings.enforcement !== 'enforce') {
10689
+ return { moduleKey, isAvailable: true, isGranted };
10690
+ }
10691
+ // A cycle in `requires` resolves unavailable rather than recursing.
10692
+ if (seen.has(moduleKey)) {
10693
+ return {
10694
+ moduleKey,
10695
+ isAvailable: false,
10696
+ isGranted,
10697
+ reason: 'prerequisiteUnavailable',
10698
+ unsatisfied: (_c = (_b = moduleSettings.catalog[moduleKey]) === null || _b === void 0 ? void 0 : _b.requires) !== null && _c !== void 0 ? _c : [],
10699
+ };
10700
+ }
10701
+ // The module's own grant is evaluated before its prerequisites, so
10702
+ // `notGranted` is reported in preference when both hold.
10703
+ if (!isGranted) {
10704
+ return { moduleKey, isAvailable: false, isGranted, reason: 'notGranted' };
10705
+ }
10706
+ const requires = (_e = (_d = moduleSettings.catalog[moduleKey]) === null || _d === void 0 ? void 0 : _d.requires) !== null && _e !== void 0 ? _e : [];
10707
+ if (requires.length === 0)
10708
+ return { moduleKey, isAvailable: true, isGranted };
10709
+ // `requires` is satisfied by any one entry, transitively.
10710
+ const isSatisfied = requires.some(dependency => resolveModuleAvailability(moduleSettings, dependency, new Set([...seen, moduleKey]))
10711
+ .isAvailable);
10712
+ if (isSatisfied)
10713
+ return { moduleKey, isAvailable: true, isGranted };
10714
+ /*
10715
+ * `unsatisfied` carries the whole `requires` list rather than one entry. Any
10716
+ * one of them would have satisfied the requirement, so naming a single
10717
+ * module misdirects: telling a Community-only customer "Comment needs post"
10718
+ * hides that Story would also have done.
10719
+ */
10720
+ return {
10721
+ moduleKey,
10722
+ isAvailable: false,
10723
+ isGranted,
10724
+ reason: 'prerequisiteUnavailable',
10725
+ unsatisfied: requires,
10726
+ };
10727
+ };
10728
+
10248
10729
  var index$t = /*#__PURE__*/Object.freeze({
10249
10730
  __proto__: null,
10250
10731
  getActiveClient: getActiveClient,
@@ -10268,6 +10749,7 @@ var index$t = /*#__PURE__*/Object.freeze({
10268
10749
  getShareableLinkConfiguration: getShareableLinkConfiguration,
10269
10750
  getProductCatalogueSetting: getProductCatalogueSetting,
10270
10751
  getForYouFeedSetting: getForYouFeedSetting,
10752
+ getModuleSettings: getModuleSettings,
10271
10753
  loginAsVisitor: loginAsVisitor,
10272
10754
  loginAsBot: loginAsBot,
10273
10755
  getCurrentUser: getCurrentUser,
@@ -10295,7 +10777,8 @@ var index$t = /*#__PURE__*/Object.freeze({
10295
10777
  startMarkerSync: startMarkerSync,
10296
10778
  startUnreadSync: startUnreadSync,
10297
10779
  stopUnreadSync: stopUnreadSync,
10298
- getMarkerSyncConsistentMode: getMarkerSyncConsistentMode
10780
+ getMarkerSyncConsistentMode: getMarkerSyncConsistentMode,
10781
+ resolveModuleAvailability: resolveModuleAvailability
10299
10782
  });
10300
10783
 
10301
10784
  /* begin_public_function
@@ -13226,7 +13709,7 @@ const getWatchSessionStorage = () => {
13226
13709
  return storageInstance;
13227
13710
  };
13228
13711
 
13229
- const privateKey = "-----BEGIN PRIVATE KEY-----\nMIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDHo80SecH7FuF2\nhFYnb+l26/VN8UMLXAQFLnxciNTEwkGVFMpdezlH8rU2HtUJL4RETogbAOLVY0XM\njs6sPn8G1nALmh9qeDpUtVqFOVtBHxEZ910TLOtQiunjqJKO5nWdqZ71EC3OFluR\niGQkO84BiIFbv37ub7xl3S8XarbtKoLcyVpkDHi+1wx1pgCAn6gtBUgckPL5NR8j\nLseabl3HAXQfhTCKo4tmOFM2Dxwl1IUMmIJrJg/aIU/U0tj/1Eoo7mG0JcNWX19l\nW3EecCbi0ncCJOrkUdwlBrcjaMayaX/ubEwyUeTGiLdyc4L3GRLHjyK8xgVNXRMH\nbZWJ2a5NAgMBAAECggEASxuE+35zTFO/XydKgmvIGcWL9FbgMlXb7Vcf0nBoG945\nbiz0NVc2paraIhJXc608xbYF3qLmtAE1MVBI0ORyRdBHNxY024l/6H6SH60Ed+uI\nM4ysp5ourY6Vj+DLwpdRiI9YDjqYAQDIUmhNxJP7XPhOMoZI6st+xZQBM34ic/bv\nAMSJm9OZphSp3+qXVkFZztr2mxD2EZSJJLYxi8BCdgM2qhazalbcJ6zDKHCZWVWm\n8RRxDGldyMb/237JxETzP40tAlzOZDmBAbUgEnurDJ93RVDIE3rbZUshwgeQd18a\nem096mWgvB1AIKYgsTAR3pw+V19YWAjq/glP6fz8wQKBgQD/oQq+ukKF0PRgBeM5\ngeTjSwsdGppQLmf5ndujvoiz/TpdjDEPu6R8kigQr1rG2t4K/yfdZoI8RdmJD1al\n3Q7N9hofooSy4rj6E3txzWZCHJjHad2cnCp/O26HiReGAl7wTcfTmNdiFHhZQzm5\nJBkvWAiwuvQMNfEbnXxw6/vIDwKBgQDH7fX8gsc77JLvAWgp1MaQN/sbqVb6JeT1\nFQfR8E/WFCSmzQBtNzd5KgYuCeelwr/8DyYytvN2BzCYZXp73gI1jF3YlW5jVn74\nOY6TwQ095digwo6Z0yuxopdIOApKgAkL9PRKgNrqAf3NAyMua6lOGifzjDojC3KU\nfylQmxMn4wKBgHp2B9O/H0dEBw5JQ8W0+JX6yWQz7mEjGiR2/1W+XXb8hQ1zr709\nw1r6Gb+EghRpnZ3fBpYGGbYOMFx8wKHM+N6qW3F0ReX8v2juFGE8aRSa5oYBrWzt\nU16Idjbv8hj84cZ1PJmdyvDtpYn9rpWHOZl4rxEbPvbqkIsOMyNVqdT5AoGAOSge\nmwIIU2le2FVeohbibXiToWTYKMuMmURZ5/r72AgKMmWJKbAPe+Q3wBG01/7FRBpQ\noU8Ma0HC8s6QJbliiEyIx9JwrJWd1vkdecBHONrtA4ibm/5zD2WcOllLF+FitLhi\n3qnX6+6F0IaFGFBPJrTzlv0P4dTz/OAdv52V7GECgYEA2TttOKBAqWllgOaZOkql\nLVMJVmgR7s6tLi1+cEP8ZcapV9aRbRzTAKXm4f8AEhtlG9F9kCOvHYCYGi6JaiWJ\nZkHjeex3T+eE6Di6y5Bm/Ift5jtVhJ4jCVwHOKTMej79NPUFTJfv8hCo29haBDv6\nRXFrv+T21KCcw8k3sJeJWWQ=\n-----END PRIVATE KEY-----";
13712
+ const privateKey = "MIIEpQIBAAKCAQEAwAEc/oZgYIvKSUG/C3mONYLR4ZPgAjMEX4bJ+xqqakUDRtqlNO+eZs2blQ1Ko0DBkqPExyQezvjibH5W2UZBV5RaBTlTcNVKTToMBEGesAfaEcM3qUyQHxdbFYZv6P4sb14dcwxTQ8usmaV8ooiR1Fcaso5ZWYcZ8Hb46FbQ7OoVumsBtPWwfZ4f003o5VCl6AIM6lcLv9UDLlFVYhE+PeXpRHtfWlGqxMvqC9oinlwhL6nWv6VjQXW4nhcib72dPBzfHT7k/PMKto2SxALYdb68ENiAGuJLWi3AUHSyYCJK2w7wIlWfJUAI0v26ub10IpExr6D5QuW2577jjP93iwIDAQABAoIBAFWfqXhwIIatkFY+9Z1+ZcbDQimgsmMIsUiQaX6Lk7e0cxOj6czDlxYtVtaPiNtow2pLkjNkjkCqiP7tEHnwdK9DvylZOTa2R15NJpK3WLcTqVIGhsn/FL5owfvFah6zSsmXZParZm5zY9NZE03ALZhOB9/cz0e3kf/EbpfeL2mW7MApyiUt5i09ycchroOpcWp73ipIxvgigtZyUGFmsQicWhUs28F0D7w4Qfk76yG3nqXeb+BAMhCaIaa/k/aAxhiZG/ygEQWQrcC8gfe+jyicMAQPDEVS9YuUMGsLjIjKuVLZzp2xirQnhc2i2zVNEIvG6soprPOBEMQugzrtX5ECgYEA3b7KAbBIbDl1e4ZSCWhHdHkiWVZHaopsR/LhqDDNhXjWjq3AesgV6k0j9EdziMn/HmmOso0bz99GTV3JZf4A9ztTLumJlkHbdVtlgOqSjrFLj12rH9KXTheyIhWSpUmm8+WB1xasFbqpvJaGo7F3pd2Fqj1XR4mp5BO7c/t7LJ0CgYEA3aouEzXQ9THRKYocdfY69EI1Il1t/d/RSqqd9BxEjxBgxkM13ZiYIn/R4WW/nCUrlmhxG44Aa2Gob4Ahfsui2xKTg/g/3Zk/rAxAEGkfOLGoenaJMD41fH4wUq3FRYwkvnaMb9Hd6f/TlBHslIRa2NN58bSBGJCyBP2b59+2+EcCgYEAixDVRXvV37GlYUOa/XVdosk5Zoe6oDGRuQm0xbNdoUBoZvDHDvme7ONWEiQha/8qtVsD+CyQ7awcPfb8kK9c0bBt+bTS6d4BkTcxkEkMgtrkBVR8Nqfu5jXsLH4VCv4G61zbMhZw8+ut+az5YX2yCN7Frj9sFlxapMRPQmzMEe0CgYEAumsAzM8ZqNv4mAK65Mnr0rhLj1cbxcKRdUYACOgtEFQpzxN/HZnTeFAe5nx3pI3uFlRHq3DFEYnT6dHMWaJQmAULYpVIwMi9L6gtyJ9fzoI6uqMtxRDMUqKdaSsTGOY/kJ6KhQ/unXi1K3XXjR+yd1+C0q+HUm1+CYxvrZYLfskCgYEArsEy+IQOiqniJ0NE2vVUF+UK/IRZaic9YKcpov5Ot7Vvzm/MnnW4N1ljVskocETBWMmPUvNSExVjPebi+rxd8fa5kY8BJScPTzMFbunZn/wjtGdcM10qdlVQ9doG61A/9P3ezFKCfS4AvF/H/59LcSx2Bh28fp3/efiVIOpVd4Y=";
13230
13713
  /*
13231
13714
  * The crypto algorithm used for importing key and signing string
13232
13715
  */
@@ -15025,18 +15508,18 @@ const buildFlagUserBody = (options) => {
15025
15508
  /**
15026
15509
  * ```js
15027
15510
  * import { UserRepository } from '@amityco/ts-sdk'
15511
+ *
15512
+ * // Typeless report (supported).
15028
15513
  * const flagged = await UserRepository.flagUser('userId')
15029
- * const flaggedBehavior = await UserRepository.flagUser('userId', {
15030
- * reportType: 'behavior',
15031
- * reason: 'Harassment or bullying',
15032
- * comment: 'optional free-text',
15033
- * })
15034
15514
  * ```
15035
15515
  *
15516
+ * Flags a user. Two call shapes are accepted (see the overloads): id-only, which
15517
+ * sends no body and stays supported, and the deprecated structured options object,
15518
+ * whose request mapping is unchanged. New code reporting a profile field or behavior
15519
+ * should use `flagUserProfile` or `flagUserBehavior`.
15520
+ *
15036
15521
  * @param userId The ID of the user to be flagged
15037
- * @param options Optional report metadata forwarded to the server as the request
15038
- * body: `reportType`, `reason`, `comment`. Only non-null fields are included.
15039
- * All validation is server-side; a bodyless call produces a typeless report.
15522
+ * @param options Deprecated report metadata; omit for a typeless report
15040
15523
  * @returns the flagged {@link Amity.User}
15041
15524
  *
15042
15525
  * @category User API
@@ -15057,6 +15540,156 @@ const flagUser = async (userId, options) => {
15057
15540
  };
15058
15541
  /* end_public_function */
15059
15542
 
15543
+ /**
15544
+ * Sends a validated split user report (`flagUserProfile` / `flagUserBehavior`) to the
15545
+ * same endpoint as `flagUser`, then persists the returned user and fires `user.flagged`
15546
+ * exactly as `flagUser` does, so all three calls share return, cache and event behaviour.
15547
+ *
15548
+ * Not exported from the public API.
15549
+ */
15550
+ const submitUserReport = async (apiName, userId, body) => {
15551
+ var _a;
15552
+ const client = getActiveClient();
15553
+ client.log(`user/${apiName}`, { userId, body });
15554
+ const { data } = await client.http.post(`/api/v4/me/flags/${encodeURIComponent(userId)}`, body);
15555
+ const payload = prepareUserPayload(data);
15556
+ if (client.cache) {
15557
+ ingestInCache(payload);
15558
+ }
15559
+ fireEvent('user.flagged', data);
15560
+ return (_a = payload.users.find(user => user.userId === userId)) !== null && _a !== void 0 ? _a : payload.users[0];
15561
+ };
15562
+
15563
+ /** Maximum `comment` length, in string length units, after trimming. */
15564
+ const USER_REPORT_COMMENT_MAX_LENGTH = 300;
15565
+ const PROFILE_FIELDS = Object.values(exports.UserProfileFieldEnum);
15566
+ const BEHAVIOR_REASONS = Object.values(exports.ContentFlagReasonEnum);
15567
+ const assertOptionsObject = (apiName, options, shape) => {
15568
+ if (typeof options !== 'object' || options === null || Array.isArray(options)) {
15569
+ throw new ASCInvalidParameterError(`${apiName}: expected an options object \`${shape}\``);
15570
+ }
15571
+ return options;
15572
+ };
15573
+ /**
15574
+ * Normalizes an optional reporter `comment`: it must be a string when supplied (`null`
15575
+ * is not a valid supplied comment); it is trimmed; a blank result is omitted (the
15576
+ * backend rejects `""`); a result longer than 300 characters is rejected before any
15577
+ * request. Otherwise the trimmed text is returned unchanged.
15578
+ *
15579
+ * @throws {ASCInvalidParameterError} `INVALID_PARAMETERS` for a non-string or over-length comment
15580
+ */
15581
+ const normalizeUserReportComment = (apiName, comment) => {
15582
+ if (comment === undefined)
15583
+ return undefined;
15584
+ if (typeof comment !== 'string') {
15585
+ throw new ASCInvalidParameterError(`${apiName}: \`comment\` must be a string when supplied`);
15586
+ }
15587
+ const trimmed = comment.trim();
15588
+ if (trimmed.length === 0)
15589
+ return undefined;
15590
+ if (trimmed.length > USER_REPORT_COMMENT_MAX_LENGTH) {
15591
+ throw new ASCInvalidParameterError(`${apiName}: \`comment\` must be at most ${USER_REPORT_COMMENT_MAX_LENGTH} characters after trimming`);
15592
+ }
15593
+ return trimmed;
15594
+ };
15595
+ const withComment = (body, comment) => comment === undefined ? body : Object.assign(Object.assign({}, body), { comment });
15596
+ /**
15597
+ * Validates `flagUserProfile` options and builds its request body. Untyped callers can
15598
+ * pass anything at runtime, so nothing is trusted from the declared type. Any `reason`
15599
+ * key is ignored and never sent.
15600
+ *
15601
+ * @throws {ASCInvalidParameterError} `INVALID_PARAMETERS` when the options are malformed
15602
+ */
15603
+ const toUserProfileReportBody = (options) => {
15604
+ const apiName = 'flagUserProfile';
15605
+ const { field, comment } = assertOptionsObject(apiName, options, '{ field, comment? }');
15606
+ if (typeof field !== 'string' || !PROFILE_FIELDS.includes(field)) {
15607
+ throw new ASCInvalidParameterError(`${apiName}: \`field\` must be a \`UserProfileFieldEnum\` value`);
15608
+ }
15609
+ return withComment({ reportType: field }, normalizeUserReportComment(apiName, comment));
15610
+ };
15611
+ /**
15612
+ * Validates `flagUserBehavior` options and builds its request body. `reason` must be one
15613
+ * of the nine `ContentFlagReasonEnum` values and is sent as that canonical label;
15614
+ * `reportType` is always `behavior`.
15615
+ *
15616
+ * @throws {ASCInvalidParameterError} `INVALID_PARAMETERS` when the options are malformed
15617
+ */
15618
+ const toUserBehaviorReportBody = (options) => {
15619
+ const apiName = 'flagUserBehavior';
15620
+ const { reason, comment } = assertOptionsObject(apiName, options, '{ reason, comment? }');
15621
+ if (typeof reason !== 'string' || !BEHAVIOR_REASONS.includes(reason)) {
15622
+ throw new ASCInvalidParameterError(`${apiName}: \`reason\` must be a \`ContentFlagReasonEnum\` value`);
15623
+ }
15624
+ return withComment({ reportType: 'behavior', reason }, normalizeUserReportComment(apiName, comment));
15625
+ };
15626
+
15627
+ /* begin_public_function
15628
+ id: user.flag_profile
15629
+ */
15630
+ /**
15631
+ * ```js
15632
+ * import { UserRepository, UserProfileFieldEnum } from '@amityco/ts-sdk'
15633
+ * const flagged = await UserRepository.flagUserProfile('userId', {
15634
+ * field: UserProfileFieldEnum.AVATAR,
15635
+ * comment: 'Nudity in profile photo',
15636
+ * })
15637
+ * ```
15638
+ *
15639
+ * Reports one of a user's profile fields (display name, description or avatar). The
15640
+ * call has no reason: profile reports never carry one, so the backend's reason rules
15641
+ * cannot be violated from here. A `reason` key passed at runtime is ignored and never sent.
15642
+ *
15643
+ * `comment` is trimmed; a blank comment is omitted from the request; a comment longer
15644
+ * than 300 characters after trimming is rejected before any request. Otherwise the
15645
+ * trimmed text is sent unchanged.
15646
+ *
15647
+ * Sends `POST /api/v4/me/flags/:userId` with `{ reportType: <field>, comment? }`.
15648
+ *
15649
+ * @param userId The ID of the user to be reported
15650
+ * @param options `field` is a `UserProfileFieldEnum` value; `comment` is optional free text
15651
+ * @returns the flagged {@link Amity.User}
15652
+ * @throws {ASCInvalidParameterError} `INVALID_PARAMETERS` when `options` is missing or malformed, or `comment` is over 300 characters, before any request is made
15653
+ *
15654
+ * @category User API
15655
+ * @async
15656
+ * */
15657
+ const flagUserProfile = async (userId, options) => submitUserReport('flagUserProfile', userId, toUserProfileReportBody(options));
15658
+ /* end_public_function */
15659
+
15660
+ /* begin_public_function
15661
+ id: user.flag_behavior
15662
+ */
15663
+ /**
15664
+ * ```js
15665
+ * import { UserRepository, ContentFlagReasonEnum } from '@amityco/ts-sdk'
15666
+ * const flagged = await UserRepository.flagUserBehavior('userId', {
15667
+ * reason: ContentFlagReasonEnum.Others,
15668
+ * comment: 'Impersonating our brand',
15669
+ * })
15670
+ * ```
15671
+ *
15672
+ * Reports a user's behavior. `reason` is required and is one of the nine
15673
+ * `ContentFlagReasonEnum` values, sent as its canonical label. Reporter text, including
15674
+ * the explanation for `Others`, always travels in `comment`; the reason never carries text.
15675
+ *
15676
+ * `comment` is trimmed; a blank comment is omitted from the request; a comment longer
15677
+ * than 300 characters after trimming is rejected before any request. Otherwise the
15678
+ * trimmed text is sent unchanged.
15679
+ *
15680
+ * Sends `POST /api/v4/me/flags/:userId` with `{ reportType: 'behavior', reason, comment? }`.
15681
+ *
15682
+ * @param userId The ID of the user to be reported
15683
+ * @param options `reason` is a `ContentFlagReasonEnum` value; `comment` is optional free text
15684
+ * @returns the flagged {@link Amity.User}
15685
+ * @throws {ASCInvalidParameterError} `INVALID_PARAMETERS` when `options` is missing or malformed, `reason` is missing or unknown, or `comment` is over 300 characters, before any request is made
15686
+ *
15687
+ * @category User API
15688
+ * @async
15689
+ * */
15690
+ const flagUserBehavior = async (userId, options) => submitUserReport('flagUserBehavior', userId, toUserBehaviorReportBody(options));
15691
+ /* end_public_function */
15692
+
15060
15693
  /* begin_public_function
15061
15694
  id: user.unflag
15062
15695
  */
@@ -16231,6 +16864,8 @@ var index$r = /*#__PURE__*/Object.freeze({
16231
16864
  getUserByIds: getUserByIds,
16232
16865
  updateUser: updateUser,
16233
16866
  flagUser: flagUser,
16867
+ flagUserProfile: flagUserProfile,
16868
+ flagUserBehavior: flagUserBehavior,
16234
16869
  unflagUser: unflagUser,
16235
16870
  isUserFlaggedByMe: isUserFlaggedByMe,
16236
16871
  getAllBlockedUsers: getAllBlockedUsers,
@@ -19269,7 +19904,7 @@ const getLocalId = () => `LOCAL_${uuid()}`;
19269
19904
  // FIXME: temp solution
19270
19905
  let uniqueId;
19271
19906
  const createMessageOptimistic = (bundle) => {
19272
- var _a, _b;
19907
+ var _a, _b, _c, _d;
19273
19908
  const client = getActiveClient();
19274
19909
  if (!client.cache)
19275
19910
  return;
@@ -19300,9 +19935,20 @@ const createMessageOptimistic = (bundle) => {
19300
19935
  }
19301
19936
  // as reused to update created and updated time, which should be the same
19302
19937
  const createdTime = new Date().toISOString();
19303
- const message = Object.assign({ creatorId: client.userId, creatorPrivateId: getActiveUser()._id, channelSegment: ((_b = subChannel === null || subChannel === void 0 ? void 0 : subChannel.data.messageCount) !== null && _b !== void 0 ? _b : 0) + 1, childrenNumber: 0, createdAt: createdTime, updatedAt: createdTime, syncState: "syncing" /* Amity.SyncState.Syncing */, isDeleted: false }, bundleWithMessageId);
19938
+ const message = Object.assign({
19939
+ // The optimistic message must name its channel (public id) so the own-send
19940
+ // update can move lastActivity / lastMessageAt at send time. Take it from the
19941
+ // cached sub-channel; when that is not cached, resolve the sub-channel id
19942
+ // through the channel cache, which for a channel's default sub-channel is
19943
+ // the channel itself (ChannelActivityService migration row I2). A thread or
19944
+ // unknown channel resolves to undefined, as before.
19945
+ channelId: (_b = subChannel === null || subChannel === void 0 ? void 0 : subChannel.data.channelId) !== null && _b !== void 0 ? _b : (_c = findCachedChannel(bundle.subChannelId)) === null || _c === void 0 ? void 0 : _c.channelId, creatorId: client.userId, creatorPrivateId: getActiveUser()._id, channelSegment: ((_d = subChannel === null || subChannel === void 0 ? void 0 : subChannel.data.messageCount) !== null && _d !== void 0 ? _d : 0) + 1, childrenNumber: 0, createdAt: createdTime, updatedAt: createdTime, syncState: "syncing" /* Amity.SyncState.Syncing */, isDeleted: false }, bundleWithMessageId);
19304
19946
  const cachedAt = UNSYNCED_OBJECT_CACHED_AT_VALUE;
19305
19947
  pushToCache(['message', 'get', message.messageId], message, { cachedAt });
19948
+ // Own-send update (ChannelActivityService row 1): move the channel at send
19949
+ // time, synchronously, so the confirmation on the send response always sees
19950
+ // this value rather than racing the scheduled local event below.
19951
+ updateChannelActivityTimestamps(message.channelId, message.createdAt);
19306
19952
  fireEvent('local.message.created', { messages: [message] });
19307
19953
  return message;
19308
19954
  };
@@ -19342,6 +19988,9 @@ const createMessage = async (bundle) => {
19342
19988
  if (client.cache) {
19343
19989
  ingestInCache(data, { cachedAt });
19344
19990
  }
19991
+ // The own-send update wrote the device-clock createdAt; replace it with the
19992
+ // server's now that the message is confirmed (ChannelActivityService REQ-009).
19993
+ confirmOwnMessage(optimisticData === null || optimisticData === void 0 ? void 0 : optimisticData.channelId, optimisticData === null || optimisticData === void 0 ? void 0 : optimisticData.createdAt, messages[0].createdAt);
19345
19994
  fireEvent('local.message.created', {
19346
19995
  messages: [Object.assign(Object.assign({}, messages[0]), { syncState: "synced" /* Amity.SyncState.Synced */ })],
19347
19996
  });
@@ -19935,23 +20584,85 @@ getDeliveredUsers.locally = (query) => {
19935
20584
  return { data: users, cachedAt, prevPage, nextPage };
19936
20585
  };
19937
20586
 
19938
- /* begin_public_function
19939
- id: message.flag
19940
- */
20587
+ const CONTENT_FLAG_REASONS = Object.values(exports.ContentFlagReasonEnum);
19941
20588
  /**
19942
- * ```js
19943
- * import { MessageRepository } from '@amityco/ts-sdk'
19944
- * const flagged = await MessageRepository.flagMessage(messageId, reason)
19945
- * ```
20589
+ * True when a public `flagX(id, input)` argument is the legacy shape (a reason string
20590
+ * or nothing). Anything else is routed to the `Amity.ContentFlagOptions` path, whose
20591
+ * validation rejects malformed values before any request is made.
20592
+ */
20593
+ const isLegacyContentFlagReason = (input) => input === undefined || typeof input === 'string';
20594
+ /**
20595
+ * Validates an `Amity.ContentFlagOptions` argument. Untyped (plain JS) callers can pass
20596
+ * anything at runtime, so the checks do not trust the declared type: the value must be a
20597
+ * plain object, `reason` must be one of the nine `ContentFlagReasonEnum` values and
20598
+ * `detail`, when supplied, must be a string (`null` is not a valid supplied detail).
19946
20599
  *
19947
- * @param messageId of the message to flag
19948
- * @param reason the reason to flag the message
19949
- * @returns the created report result
20600
+ * @param apiName used in the error message, e.g. `flagPost`
20601
+ * @throws {ASCInvalidParameterError} `INVALID_PARAMETERS` when the options are malformed
20602
+ */
20603
+ const validateContentFlagOptions = (apiName, options) => {
20604
+ if (typeof options !== 'object' || options === null || Array.isArray(options)) {
20605
+ throw new ASCInvalidParameterError(`${apiName}: expected an options object \`{ reason, detail? }\``);
20606
+ }
20607
+ const { reason, detail } = options;
20608
+ if (typeof reason !== 'string' || !CONTENT_FLAG_REASONS.includes(reason)) {
20609
+ throw new ASCInvalidParameterError(`${apiName}: \`reason\` must be a \`ContentFlagReasonEnum\` value`);
20610
+ }
20611
+ if (detail !== undefined && typeof detail !== 'string') {
20612
+ throw new ASCInvalidParameterError(`${apiName}: \`detail\` must be a string when supplied`);
20613
+ }
20614
+ return { reason: reason, detail };
20615
+ };
20616
+ /**
20617
+ * Builds the request body for validated options. `detail` is forwarded unchanged (empty
20618
+ * and whitespace-only strings included) and omitted from the body when `undefined`; the
20619
+ * backend enforces the 300-character limit.
20620
+ */
20621
+ const toContentFlagBody = ({ reason, detail }) => detail === undefined ? { reason } : { reason, detail };
20622
+
20623
+ /**
20624
+ * New `flagMessage(messageId, { reason, detail? })` implementation. Any category,
20625
+ * including `Others`, may carry a `detail`. `detail` is forwarded unchanged (empty and
20626
+ * whitespace-only strings included) and omitted from the request body when `undefined`;
20627
+ * the backend enforces the 300-character limit.
19950
20628
  *
19951
- * @category Message API
19952
- * @async
19953
- * */
19954
- const flagMessage = async (messageId, reason) => {
20629
+ * Not exported from the public API. It is reached through the
20630
+ * `MessageRepository.flagMessage(messageId, options)` overload; see `api/flagMessage.ts`.
20631
+ *
20632
+ * @throws {ASCInvalidParameterError} `INVALID_PARAMETERS` when `options` is malformed, before any request is made
20633
+ */
20634
+ const flagMessageWithOptions = async (messageId, options) => {
20635
+ // Validate first: an input error must surface as INVALID_PARAMETERS regardless of
20636
+ // whether a client is active, and validation needs nothing from the client.
20637
+ const body = toContentFlagBody(validateContentFlagOptions('flagMessage', options));
20638
+ const client = getActiveClient();
20639
+ client.log('message/flag', messageId);
20640
+ const { data: payload } = await client.http.post(`/api/v5/messages/${encodeURIComponent(messageId)}/flags`, body);
20641
+ if (client.cache) {
20642
+ const messagePayload = await prepareMessagePayload(payload);
20643
+ ingestInCache(messagePayload);
20644
+ }
20645
+ fireEvent('message.flagged', payload);
20646
+ return !!payload;
20647
+ };
20648
+
20649
+ /**
20650
+ * Legacy `flagMessage(messageId, reason?)` implementation, kept verbatim so existing
20651
+ * callers keep the exact request body they had before the options contract existed:
20652
+ *
20653
+ * - predefined `ContentFlagReasonEnum` value → `{ reason: <value>, detail: '' }`
20654
+ * - any other non-empty string (including the literal `'Others'`) → `{ reason: 'Others', detail: <string> }`
20655
+ * - `undefined` or `''` → `{ reason: 'Others', detail: '' }`
20656
+ * (for `undefined` the message body carries `detail: undefined`, which JSON serialization omits)
20657
+ *
20658
+ * Not exported from the public API. It is reached through the deprecated
20659
+ * `MessageRepository.flagMessage(messageId, reason)` overload; see `api/flagMessage.ts`.
20660
+ *
20661
+ * Not itself deprecated: it implements the deprecated legacy-string overload of the public
20662
+ * `flagMessage`, which carries the deprecation tag. New code should use `flagMessageWithOptions`
20663
+ * (the `{ reason, detail? }` contract). This path stays available throughout the current major version.
20664
+ */
20665
+ const flagMessageWithReasonString = async (messageId, reason) => {
19955
20666
  const client = getActiveClient();
19956
20667
  client.log('message/flag', messageId);
19957
20668
  const isPredefinedReason = reason &&
@@ -19968,6 +20679,42 @@ const flagMessage = async (messageId, reason) => {
19968
20679
  fireEvent('message.flagged', payload);
19969
20680
  return !!payload;
19970
20681
  };
20682
+
20683
+ /* begin_public_function
20684
+ id: message.flag
20685
+ */
20686
+ /**
20687
+ * ```js
20688
+ * import { MessageRepository, ContentFlagReasonEnum } from '@amityco/ts-sdk'
20689
+ *
20690
+ * // No reason.
20691
+ * await MessageRepository.flagMessage(messageId)
20692
+ *
20693
+ * // Category plus optional reporter context (any category, including Others).
20694
+ * await MessageRepository.flagMessage(messageId, {
20695
+ * reason: ContentFlagReasonEnum.SpamOrScams,
20696
+ * detail: 'Repeated promotional links',
20697
+ * })
20698
+ * ```
20699
+ *
20700
+ * Reports a message to moderation. Three call shapes are accepted (see the overloads):
20701
+ * id-only, an options object, and the deprecated legacy reason string. The public
20702
+ * name only dispatches on the input shape; the two implementations are kept separate
20703
+ * so the legacy path is untouched by the new contract:
20704
+ *
20705
+ * - `undefined` or a string → `flagMessageWithReasonString` (unchanged legacy mapping)
20706
+ * - anything else → `flagMessageWithOptions` (validated `{ reason, detail? }`)
20707
+ *
20708
+ * @param messageId The ID of the message to flag
20709
+ * @param input an options object `{ reason, detail? }`, a legacy reason string, or nothing
20710
+ * @returns `true` when the report was created
20711
+ *
20712
+ * @category Message API
20713
+ * @async
20714
+ * */
20715
+ const flagMessage = (messageId, input) => isLegacyContentFlagReason(input)
20716
+ ? flagMessageWithReasonString(messageId, input)
20717
+ : flagMessageWithOptions(messageId, input);
19971
20718
  /* end_public_function */
19972
20719
 
19973
20720
  /* begin_public_function
@@ -21687,6 +22434,9 @@ class ChannelLiveCollectionController extends LiveCollectionController {
21687
22434
  case 'lastCreated':
21688
22435
  channels = channels.sort(sortByLastCreated);
21689
22436
  break;
22437
+ case 'lastMessage':
22438
+ channels = channels.sort(sortByLastMessage);
22439
+ break;
21690
22440
  case 'displayName':
21691
22441
  /*
21692
22442
  * The server returns channels with empty | null displayName's first before
@@ -21747,9 +22497,8 @@ class ChannelLiveCollectionController extends LiveCollectionController {
21747
22497
  objectResolverEngine.resolve(message.channelId, "channel" /* Amity.ReferenceType.CHANNEL */);
21748
22498
  }
21749
22499
  else {
21750
- updateChannelCache(channelCache, {
21751
- lastActivity: message.createdAt,
21752
- });
22500
+ // lastActivity / lastMessageAt are moved by channelActivityOnLoginHandler
22501
+ // (session-wide, monotonic, one write). This listener only re-sorts.
21753
22502
  callback(message);
21754
22503
  }
21755
22504
  });
@@ -21767,9 +22516,7 @@ class ChannelLiveCollectionController extends LiveCollectionController {
21767
22516
  ])) === null || _a === void 0 ? void 0 : _a.data;
21768
22517
  if (!cacheData)
21769
22518
  return;
21770
- updateChannelCache(cacheData, {
21771
- lastActivity: message.createdAt,
21772
- });
22519
+ // Timestamps are moved by channelActivityOnLoginHandler; only re-sort here.
21773
22520
  callback(message);
21774
22521
  });
21775
22522
  }, 'channelId', 'channel'),
@@ -22507,9 +23254,7 @@ class SearchChannelLiveCollectionController extends LiveCollectionController {
22507
23254
  ])) === null || _a === void 0 ? void 0 : _a.data;
22508
23255
  if (!cacheData)
22509
23256
  return;
22510
- updateChannelCache(cacheData, {
22511
- lastActivity: message.createdAt,
22512
- });
23257
+ // Timestamps are moved by channelActivityOnLoginHandler; only re-sort here.
22513
23258
  callback(message);
22514
23259
  });
22515
23260
  }, 'channelId', 'channel'),
@@ -22526,9 +23271,7 @@ class SearchChannelLiveCollectionController extends LiveCollectionController {
22526
23271
  ])) === null || _a === void 0 ? void 0 : _a.data;
22527
23272
  if (!cacheData)
22528
23273
  return;
22529
- updateChannelCache(cacheData, {
22530
- lastActivity: message.createdAt,
22531
- });
23274
+ // Timestamps are moved by channelActivityOnLoginHandler; only re-sort here.
22532
23275
  callback(message);
22533
23276
  });
22534
23277
  }, 'channelId', 'channel'),
@@ -27113,23 +27856,22 @@ const declineComment = async (commentId, reason) => {
27113
27856
  };
27114
27857
  /* end_public_function */
27115
27858
 
27116
- /* begin_public_function
27117
- id: comment.flag
27118
- */
27119
27859
  /**
27120
- * ```js
27121
- * import { CommentRepository } from '@amityco/ts-sdk'
27122
- * const flagged = await CommentRepository.flagComment(commentId, reason)
27123
- * ```
27860
+ * Legacy `flagComment(commentId, reason?)` implementation, kept verbatim so existing
27861
+ * callers keep the exact request body they had before the options contract existed:
27124
27862
  *
27125
- * @param commentId The ID of the comment to flag
27126
- * @param reason the reason to flag the comment
27127
- * @returns the created report result
27863
+ * - predefined `ContentFlagReasonEnum` value → `{ reason: <value>, detail: '' }`
27864
+ * - any other non-empty string (including the literal `'Others'`) → `{ reason: 'Others', detail: <string> }`
27865
+ * - `undefined` or `''` → `{ reason: 'Others', detail: '' }`
27128
27866
  *
27129
- * @category Comment API
27130
- * @async
27131
- * */
27132
- const flagComment = async (commentId, reason) => {
27867
+ * Not exported from the public API. It is reached through the deprecated
27868
+ * `CommentRepository.flagComment(commentId, reason)` overload; see `api/flagComment.ts`.
27869
+ *
27870
+ * Not itself deprecated: it implements the deprecated legacy-string overload of the public
27871
+ * `flagComment`, which carries the deprecation tag. New code should use `flagCommentWithOptions`
27872
+ * (the `{ reason, detail? }` contract). This path stays available throughout the current major version.
27873
+ */
27874
+ const flagCommentWithReasonString = async (commentId, reason) => {
27133
27875
  const client = getActiveClient();
27134
27876
  client.log('comment/flagComment', commentId);
27135
27877
  const isPredefinedReason = reason &&
@@ -27145,6 +27887,67 @@ const flagComment = async (commentId, reason) => {
27145
27887
  fireEvent('comment.flagged', payload);
27146
27888
  return !!payload;
27147
27889
  };
27890
+
27891
+ /**
27892
+ * New `flagComment(commentId, { reason, detail? })` implementation. Any category,
27893
+ * including `Others`, may carry a `detail`. `detail` is forwarded unchanged (empty and
27894
+ * whitespace-only strings included) and omitted from the request body when `undefined`;
27895
+ * the backend enforces the 300-character limit.
27896
+ *
27897
+ * Not exported from the public API. It is reached through the
27898
+ * `CommentRepository.flagComment(commentId, options)` overload; see `api/flagComment.ts`.
27899
+ *
27900
+ * @throws {ASCInvalidParameterError} `INVALID_PARAMETERS` when `options` is malformed, before any request is made
27901
+ */
27902
+ const flagCommentWithOptions = async (commentId, options) => {
27903
+ // Validate first: an input error must surface as INVALID_PARAMETERS regardless of
27904
+ // whether a client is active, and validation needs nothing from the client.
27905
+ const body = toContentFlagBody(validateContentFlagOptions('flagComment', options));
27906
+ const client = getActiveClient();
27907
+ client.log('comment/flagComment', commentId);
27908
+ const { data: payload } = await client.http.post(`/api/v3/comments/${encodeURIComponent(commentId)}/flag`, body);
27909
+ if (client.cache) {
27910
+ ingestInCache(payload);
27911
+ }
27912
+ fireEvent('comment.flagged', payload);
27913
+ return !!payload;
27914
+ };
27915
+
27916
+ /* begin_public_function
27917
+ id: comment.flag
27918
+ */
27919
+ /**
27920
+ * ```js
27921
+ * import { CommentRepository, ContentFlagReasonEnum } from '@amityco/ts-sdk'
27922
+ *
27923
+ * // No reason: sent as Others with an empty detail.
27924
+ * await CommentRepository.flagComment(commentId)
27925
+ *
27926
+ * // Category plus optional reporter context (any category, including Others).
27927
+ * await CommentRepository.flagComment(commentId, {
27928
+ * reason: ContentFlagReasonEnum.SpamOrScams,
27929
+ * detail: 'Repeated promotional links',
27930
+ * })
27931
+ * ```
27932
+ *
27933
+ * Reports a comment to moderation. Three call shapes are accepted (see the overloads):
27934
+ * id-only, an options object, and the deprecated legacy reason string. The public
27935
+ * name only dispatches on the input shape; the two implementations are kept separate
27936
+ * so the legacy path is untouched by the new contract:
27937
+ *
27938
+ * - `undefined` or a string → `flagCommentWithReasonString` (unchanged legacy mapping)
27939
+ * - anything else → `flagCommentWithOptions` (validated `{ reason, detail? }`)
27940
+ *
27941
+ * @param commentId The ID of the comment to flag
27942
+ * @param input an options object `{ reason, detail? }`, a legacy reason string, or nothing
27943
+ * @returns `true` when the report was created
27944
+ *
27945
+ * @category Comment API
27946
+ * @async
27947
+ * */
27948
+ const flagComment = (commentId, input) => isLegacyContentFlagReason(input)
27949
+ ? flagCommentWithReasonString(commentId, input)
27950
+ : flagCommentWithOptions(commentId, input);
27148
27951
  /* end_public_function */
27149
27952
 
27150
27953
  /* begin_public_function
@@ -29498,23 +30301,47 @@ const declinePost = async (postId) => {
29498
30301
  };
29499
30302
  /* end_public_function */
29500
30303
 
29501
- /* begin_public_function
29502
- id: post.flag
29503
- */
29504
30304
  /**
29505
- * ```js
29506
- * import { PostRepository } from '@amityco/ts-sdk'
29507
- * const flagged = await PostRepository.flagPost(postId, reason)
29508
- * ```
30305
+ * New `flagPost(postId, { reason, detail? })` implementation. Any category, including
30306
+ * `Others`, may carry a `detail`. `detail` is forwarded unchanged (empty and
30307
+ * whitespace-only strings included) and omitted from the request body when `undefined`;
30308
+ * the backend enforces the 300-character limit.
29509
30309
  *
29510
- * @param postId of the post to flag
29511
- * @param reason the reason to flag the post
29512
- * @returns a boolean
30310
+ * Not exported from the public API. It is reached through the
30311
+ * `PostRepository.flagPost(postId, options)` overload; see `api/flagPost.ts`.
29513
30312
  *
29514
- * @category Post API
29515
- * @async
29516
- * */
29517
- const flagPost = async (postId, reason) => {
30313
+ * @throws {ASCInvalidParameterError} `INVALID_PARAMETERS` when `options` is malformed, before any request is made
30314
+ */
30315
+ const flagPostWithOptions = async (postId, options) => {
30316
+ // Validate first: an input error must surface as INVALID_PARAMETERS regardless of
30317
+ // whether a client is active, and validation needs nothing from the client.
30318
+ const body = toContentFlagBody(validateContentFlagOptions('flagPost', options));
30319
+ const client = getActiveClient();
30320
+ client.log('post/flagPost', postId);
30321
+ const { data: payload } = await client.http.post(`/api/v3/posts/${encodeURIComponent(postId)}/flag`, body);
30322
+ if (client.cache) {
30323
+ ingestInCache(prepareMembershipPayload(payload, 'communityUsers'));
30324
+ }
30325
+ fireEvent('post.flagged', payload);
30326
+ return !!payload;
30327
+ };
30328
+
30329
+ /**
30330
+ * Legacy `flagPost(postId, reason?)` implementation, kept verbatim so existing
30331
+ * callers keep the exact request body they had before the options contract existed:
30332
+ *
30333
+ * - predefined `ContentFlagReasonEnum` value → `{ reason: <value>, detail: '' }`
30334
+ * - any other non-empty string (including the literal `'Others'`) → `{ reason: 'Others', detail: <string> }`
30335
+ * - `undefined` or `''` → `{ reason: 'Others', detail: '' }`
30336
+ *
30337
+ * Not exported from the public API. It is reached through the deprecated
30338
+ * `PostRepository.flagPost(postId, reason)` overload; see `api/flagPost.ts`.
30339
+ *
30340
+ * Not itself deprecated: it implements the deprecated legacy-string overload of the public
30341
+ * `flagPost`, which carries the deprecation tag. New code should use `flagPostWithOptions`
30342
+ * (the `{ reason, detail? }` contract). This path stays available throughout the current major version.
30343
+ */
30344
+ const flagPostWithReasonString = async (postId, reason) => {
29518
30345
  const client = getActiveClient();
29519
30346
  client.log('post/flagPost', postId);
29520
30347
  const isPredefinedReason = reason &&
@@ -29530,6 +30357,42 @@ const flagPost = async (postId, reason) => {
29530
30357
  fireEvent('post.flagged', payload);
29531
30358
  return !!payload;
29532
30359
  };
30360
+
30361
+ /* begin_public_function
30362
+ id: post.flag
30363
+ */
30364
+ /**
30365
+ * ```js
30366
+ * import { PostRepository, ContentFlagReasonEnum } from '@amityco/ts-sdk'
30367
+ *
30368
+ * // No reason.
30369
+ * await PostRepository.flagPost(postId)
30370
+ *
30371
+ * // Category plus optional reporter context (any category, including Others).
30372
+ * await PostRepository.flagPost(postId, {
30373
+ * reason: ContentFlagReasonEnum.SpamOrScams,
30374
+ * detail: 'Repeated promotional links',
30375
+ * })
30376
+ * ```
30377
+ *
30378
+ * Reports a post to moderation. Three call shapes are accepted (see the overloads):
30379
+ * id-only, an options object, and the deprecated legacy reason string. The public
30380
+ * name only dispatches on the input shape; the two implementations are kept separate
30381
+ * so the legacy path is untouched by the new contract:
30382
+ *
30383
+ * - `undefined` or a string → `flagPostWithReasonString` (unchanged legacy mapping)
30384
+ * - anything else → `flagPostWithOptions` (validated `{ reason, detail? }`)
30385
+ *
30386
+ * @param postId The ID of the post to flag
30387
+ * @param input an options object `{ reason, detail? }`, a legacy reason string, or nothing
30388
+ * @returns `true` when the report was created
30389
+ *
30390
+ * @category Post API
30391
+ * @async
30392
+ * */
30393
+ const flagPost = (postId, input) => isLegacyContentFlagReason(input)
30394
+ ? flagPostWithReasonString(postId, input)
30395
+ : flagPostWithOptions(postId, input);
29533
30396
  /* end_public_function */
29534
30397
 
29535
30398
  /* begin_public_function
@@ -36913,6 +37776,7 @@ class AmityAttachmentProductTags {
36913
37776
  exports.API_REGIONS = API_REGIONS;
36914
37777
  exports.AdRepository = index$6;
36915
37778
  exports.AmityAttachmentProductTags = AmityAttachmentProductTags;
37779
+ exports.AmityModuleNotEntitledError = AmityModuleNotEntitledError;
36916
37780
  exports.CategoryRepository = index$g;
36917
37781
  exports.ChannelRepository = index$k;
36918
37782
  exports.Client = index$t;
@@ -37021,6 +37885,7 @@ exports.pushToCache = pushToCache;
37021
37885
  exports.queryCache = queryCache;
37022
37886
  exports.queryOptions = queryOptions;
37023
37887
  exports.queryRoles = queryRoles;
37888
+ exports.resolveModuleAvailability = resolveModuleAvailability;
37024
37889
  exports.restoreCache = restoreCache;
37025
37890
  exports.runQuery = runQuery;
37026
37891
  exports.sortByChannelSegment = sortByChannelSegment;
@@ -37029,6 +37894,7 @@ exports.sortByFirstCreated = sortByFirstCreated;
37029
37894
  exports.sortByFirstUpdated = sortByFirstUpdated;
37030
37895
  exports.sortByLastActivity = sortByLastActivity;
37031
37896
  exports.sortByLastCreated = sortByLastCreated;
37897
+ exports.sortByLastMessage = sortByLastMessage;
37032
37898
  exports.sortByLastUpdated = sortByLastUpdated;
37033
37899
  exports.sortByLocalSortingDate = sortByLocalSortingDate;
37034
37900
  exports.sortByName = sortByName;