stream-chat 10.0.0-rc.2 → 10.0.0-rc.21

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 (298) hide show
  1. package/README.md +11 -8
  2. package/dist/cjs/index.browser.js +15397 -12090
  3. package/dist/cjs/index.browser.js.map +4 -4
  4. package/dist/cjs/index.node.js +15349 -11991
  5. package/dist/cjs/index.node.js.map +4 -4
  6. package/dist/esm/index.mjs +15164 -11880
  7. package/dist/esm/index.mjs.map +4 -4
  8. package/dist/types/ChannelManager.d.ts +246 -6
  9. package/dist/types/CooldownTimer.d.ts +22 -8
  10. package/dist/types/EventHandlerPipeline.d.ts +12 -16
  11. package/dist/types/LiveLocationManager.d.ts +69 -6
  12. package/dist/types/api-client.d.ts +22 -9
  13. package/dist/types/channel.d.ts +550 -300
  14. package/dist/types/channel_state.d.ts +167 -22
  15. package/dist/types/client.d.ts +325 -305
  16. package/dist/types/configuration/ConfigController.d.ts +172 -0
  17. package/dist/types/configuration/InstanceConfigurationRegistry.d.ts +192 -0
  18. package/dist/types/configuration/index.d.ts +3 -0
  19. package/dist/types/configuration/keys.d.ts +31 -0
  20. package/dist/types/configuration/shape.d.ts +58 -0
  21. package/dist/types/configuration/types.d.ts +206 -50
  22. package/dist/types/configuration/utils/applyInstanceConfiguration.d.ts +59 -0
  23. package/dist/types/configuration/utils/copyConfigPatch.d.ts +1 -0
  24. package/dist/types/configuration/utils/declarativeSlices.d.ts +24 -0
  25. package/dist/types/configuration/utils/deepFreezeConfig.d.ts +22 -0
  26. package/dist/types/configuration/utils/index.d.ts +1 -0
  27. package/dist/types/configuration/utils/serverAuthority.d.ts +49 -0
  28. package/dist/types/connection/ConnectionIdManager.d.ts +67 -0
  29. package/dist/types/connection/ConnectionRecoveryManager.d.ts +164 -0
  30. package/dist/types/connection/index.d.ts +4 -0
  31. package/dist/types/connection/networkConnection/NetworkConnectionObserver.d.ts +153 -0
  32. package/dist/types/connection/networkConnection/index.d.ts +3 -0
  33. package/dist/types/connection/networkConnection/reporters.d.ts +43 -0
  34. package/dist/types/connection/networkConnection/types.d.ts +55 -0
  35. package/dist/types/connection/wsConnection/StableWSConnection.d.ts +204 -0
  36. package/dist/types/connection/wsConnection/WSConnection.d.ts +168 -0
  37. package/dist/types/connection/wsConnection/WSConnectionFallback.d.ts +55 -0
  38. package/dist/types/connection/wsConnection/config.d.ts +51 -0
  39. package/dist/types/connection/wsConnection/index.d.ts +4 -0
  40. package/dist/types/connection/wsConnection/types.d.ts +99 -0
  41. package/dist/types/constants.d.ts +3 -1
  42. package/dist/types/entityStore/EntityStore.d.ts +160 -40
  43. package/dist/types/entityStore/StoreBackedItemIndex.d.ts +48 -29
  44. package/dist/types/entityStore/index.d.ts +0 -1
  45. package/dist/types/errors.d.ts +24 -4
  46. package/dist/types/formatMessageMemo.d.ts +5 -0
  47. package/dist/types/gen/chat/ChannelApi.d.ts +51 -23
  48. package/dist/types/gen/chat/ChatApi.d.ts +215 -168
  49. package/dist/types/gen/models/index.d.ts +2164 -557
  50. package/dist/types/gen/models/timestamp-guard.d.ts +22 -0
  51. package/dist/types/gen/moderation/ModerationApi.d.ts +39 -32
  52. package/dist/types/gen-imports.d.ts +1 -0
  53. package/dist/types/index.d.ts +20 -7
  54. package/dist/types/languageNames.d.ts +97 -0
  55. package/dist/types/logger.d.ts +1 -1
  56. package/dist/types/messageComposer/CustomDataManager.d.ts +7 -1
  57. package/dist/types/messageComposer/LocationComposer.d.ts +10 -4
  58. package/dist/types/messageComposer/attachmentIdentity.d.ts +11 -0
  59. package/dist/types/messageComposer/attachmentManager.d.ts +48 -10
  60. package/dist/types/messageComposer/attachmentUtils.d.ts +34 -0
  61. package/dist/types/messageComposer/configuration/commands.configuration.d.ts +1 -3
  62. package/dist/types/messageComposer/configuration/configuration.d.ts +9 -1
  63. package/dist/types/messageComposer/configuration/index.d.ts +0 -1
  64. package/dist/types/messageComposer/configuration/types.d.ts +57 -1
  65. package/dist/types/messageComposer/index.d.ts +1 -0
  66. package/dist/types/messageComposer/linkPreviewsManager.d.ts +10 -4
  67. package/dist/types/messageComposer/messageComposer.d.ts +210 -14
  68. package/dist/types/messageComposer/middleware/attachmentManager/postUpload/attachmentEnrichment.d.ts +20 -1
  69. package/dist/types/messageComposer/middleware/messageComposer/attachments.d.ts +11 -0
  70. package/dist/types/messageComposer/middleware/messageComposer/types.d.ts +2 -2
  71. package/dist/types/messageComposer/middleware/pollComposer/index.d.ts +1 -0
  72. package/dist/types/messageComposer/middleware/pollComposer/state.d.ts +3 -2
  73. package/dist/types/messageComposer/middleware/pollComposer/types.d.ts +9 -2
  74. package/dist/types/messageComposer/middleware/pollComposer/validation.d.ts +44 -0
  75. package/dist/types/messageComposer/middleware/textComposer/commands.d.ts +2 -2
  76. package/dist/types/messageComposer/middleware/textComposer/mentions.d.ts +94 -229
  77. package/dist/types/messageComposer/pollComposer.d.ts +8 -3
  78. package/dist/types/messageComposer/textComposer.d.ts +9 -1
  79. package/dist/types/messageComposer/types.d.ts +7 -3
  80. package/dist/types/messageDelivery/MessageDeliveryReporter.d.ts +64 -8
  81. package/dist/types/messageDelivery/MessageReceiptsTracker.d.ts +48 -11
  82. package/dist/types/messageOperations/FailedSendCache.d.ts +34 -0
  83. package/dist/types/messageOperations/MessageOperationStatePolicy.d.ts +52 -6
  84. package/dist/types/messageOperations/MessageOperations.d.ts +94 -11
  85. package/dist/types/{entityStore → messageOperations}/applyReactionLocally.d.ts +8 -2
  86. package/dist/types/messageOperations/createMessageOperations.d.ts +11 -0
  87. package/dist/types/messageOperations/index.d.ts +7 -1
  88. package/dist/types/messageOperations/reflectReactionEvent.d.ts +24 -0
  89. package/dist/types/messageOperations/sendOrdering.d.ts +17 -0
  90. package/dist/types/messageOperations/settlePendingAttachmentUploads.d.ts +28 -0
  91. package/dist/types/messageOperations/types.d.ts +66 -1
  92. package/dist/types/middleware.d.ts +8 -0
  93. package/dist/types/moderation.d.ts +18 -4
  94. package/dist/types/notifications/NotificationManager.d.ts +43 -2
  95. package/dist/types/notifications/types.d.ts +55 -42
  96. package/dist/types/offline-support/offline_support_api.d.ts +128 -12
  97. package/dist/types/offline-support/offline_sync_manager.d.ts +26 -5
  98. package/dist/types/offline-support/queueableOperations.d.ts +106 -0
  99. package/dist/types/offline-support/types.d.ts +77 -28
  100. package/dist/types/pagination/FilterBuilder.d.ts +1 -18
  101. package/dist/types/pagination/cursorDerivation/createdAtAroundPaginationFlags.d.ts +2 -1
  102. package/dist/types/pagination/cursorDerivation/linearPaginationFlags.d.ts +21 -3
  103. package/dist/types/pagination/filterCompiler.d.ts +5 -0
  104. package/dist/types/pagination/paginators/BasePaginator.d.ts +331 -7
  105. package/dist/types/pagination/paginators/ChannelPaginator.d.ts +54 -11
  106. package/dist/types/pagination/paginators/MessageIntervalPaginator.d.ts +283 -66
  107. package/dist/types/pagination/paginators/MessagePaginator.d.ts +10 -9
  108. package/dist/types/pagination/paginators/PinnedMessagePaginator.d.ts +17 -1
  109. package/dist/types/pagination/paginators/ReminderPaginator.d.ts +8 -8
  110. package/dist/types/pagination/paginators/ThreadPaginator.d.ts +57 -0
  111. package/dist/types/pagination/paginators/index.d.ts +1 -0
  112. package/dist/types/pagination/utility.normalization.d.ts +29 -2
  113. package/dist/types/poll.d.ts +41 -14
  114. package/dist/types/poll_manager.d.ts +3 -2
  115. package/dist/types/poll_optimistic_votes.d.ts +61 -0
  116. package/dist/types/reminders/Reminder.d.ts +17 -7
  117. package/dist/types/reminders/ReminderManager.d.ts +34 -6
  118. package/dist/types/search/BaseSearchSource.d.ts +50 -25
  119. package/dist/types/search/ChannelMemberSearchSource.d.ts +11 -6
  120. package/dist/types/search/ChannelSearchSource.d.ts +27 -5
  121. package/dist/types/search/MessageSearchSource.d.ts +36 -6
  122. package/dist/types/search/SearchController.d.ts +44 -11
  123. package/dist/types/search/UserSearchSource.d.ts +11 -5
  124. package/dist/types/search/types.d.ts +14 -1
  125. package/dist/types/signing.d.ts +0 -157
  126. package/dist/types/thread.d.ts +118 -62
  127. package/dist/types/thread_manager.d.ts +124 -35
  128. package/dist/types/token_manager.d.ts +5 -8
  129. package/dist/types/types.d.ts +138 -562
  130. package/dist/types/types.utility.d.ts +8 -0
  131. package/dist/types/upload-utils.d.ts +20 -0
  132. package/dist/types/uploadManager.d.ts +50 -2
  133. package/dist/types/utils/FixedSizeQueueCache.d.ts +2 -0
  134. package/dist/types/utils/WithSubscriptions.d.ts +1 -1
  135. package/dist/types/utils/objectPath.d.ts +49 -0
  136. package/dist/types/utils/time.d.ts +85 -0
  137. package/dist/types/utils.d.ts +63 -40
  138. package/package.json +22 -33
  139. package/src/ChannelManager.ts +561 -109
  140. package/src/CooldownTimer.ts +55 -45
  141. package/src/EventHandlerPipeline.ts +13 -23
  142. package/src/LiveLocationManager.ts +191 -37
  143. package/src/api-client.ts +144 -53
  144. package/src/channel.ts +1573 -1050
  145. package/src/channel_state.ts +239 -129
  146. package/src/client.ts +843 -892
  147. package/src/client_state.ts +2 -2
  148. package/src/configuration/ConfigController.ts +298 -0
  149. package/src/configuration/InstanceConfigurationRegistry.ts +430 -0
  150. package/src/configuration/index.ts +7 -0
  151. package/src/configuration/keys.ts +86 -0
  152. package/src/configuration/shape.ts +776 -0
  153. package/src/configuration/types.ts +218 -60
  154. package/src/configuration/utils/applyInstanceConfiguration.ts +184 -0
  155. package/src/configuration/utils/copyConfigPatch.ts +61 -0
  156. package/src/configuration/utils/declarativeSlices.ts +81 -0
  157. package/src/configuration/utils/deepFreezeConfig.ts +33 -0
  158. package/src/configuration/utils/index.ts +5 -0
  159. package/src/configuration/utils/serverAuthority.ts +146 -0
  160. package/src/connection/ConnectionIdManager.ts +153 -0
  161. package/src/connection/ConnectionRecoveryManager.ts +371 -0
  162. package/src/connection/index.ts +4 -0
  163. package/src/connection/networkConnection/NetworkConnectionObserver.ts +281 -0
  164. package/src/connection/networkConnection/index.ts +3 -0
  165. package/src/connection/networkConnection/reporters.ts +85 -0
  166. package/src/connection/networkConnection/types.ts +60 -0
  167. package/src/{connection.ts → connection/wsConnection/StableWSConnection.ts} +242 -151
  168. package/src/connection/wsConnection/WSConnection.ts +345 -0
  169. package/src/connection/wsConnection/WSConnectionFallback.ts +259 -0
  170. package/src/connection/wsConnection/config.ts +108 -0
  171. package/src/connection/wsConnection/index.ts +4 -0
  172. package/src/connection/wsConnection/types.ts +101 -0
  173. package/src/constants.ts +5 -3
  174. package/src/entityStore/EntityStore.ts +350 -10
  175. package/src/entityStore/StoreBackedItemIndex.ts +66 -37
  176. package/src/entityStore/index.ts +0 -1
  177. package/src/errors.ts +40 -7
  178. package/src/formatMessageMemo.ts +23 -0
  179. package/src/gen/chat/ChannelApi.ts +230 -44
  180. package/src/gen/chat/ChatApi.ts +1047 -1745
  181. package/src/gen/models/index.ts +2378 -3721
  182. package/src/gen/models/timestamp-guard.ts +27 -0
  183. package/src/gen/moderation/ModerationApi.ts +218 -388
  184. package/src/gen-imports.ts +1 -0
  185. package/src/index.ts +82 -6
  186. package/src/languageNames.ts +103 -0
  187. package/src/logger.ts +1 -1
  188. package/src/messageComposer/CustomDataManager.ts +10 -1
  189. package/src/messageComposer/LocationComposer.ts +68 -20
  190. package/src/messageComposer/attachmentIdentity.ts +39 -0
  191. package/src/messageComposer/attachmentManager.ts +191 -68
  192. package/src/messageComposer/attachmentUtils.ts +58 -0
  193. package/src/messageComposer/configuration/commands.configuration.ts +1 -26
  194. package/src/messageComposer/configuration/configuration.ts +22 -3
  195. package/src/messageComposer/configuration/index.ts +0 -1
  196. package/src/messageComposer/configuration/types.ts +58 -1
  197. package/src/messageComposer/index.ts +1 -0
  198. package/src/messageComposer/linkPreviewsManager.ts +16 -10
  199. package/src/messageComposer/messageComposer.ts +487 -98
  200. package/src/messageComposer/middleware/attachmentManager/postUpload/AttachmentPostUploadMiddlewareExecutor.ts +1 -1
  201. package/src/messageComposer/middleware/attachmentManager/postUpload/attachmentEnrichment.ts +58 -33
  202. package/src/messageComposer/middleware/attachmentManager/postUpload/uploadErrorHandler.ts +7 -2
  203. package/src/messageComposer/middleware/attachmentManager/preUpload/blockedUploadNotification.ts +3 -2
  204. package/src/messageComposer/middleware/messageComposer/attachments.ts +98 -1
  205. package/src/messageComposer/middleware/messageComposer/linkPreviews.ts +20 -10
  206. package/src/messageComposer/middleware/messageComposer/sharedLocation.ts +7 -2
  207. package/src/messageComposer/middleware/messageComposer/types.ts +2 -7
  208. package/src/messageComposer/middleware/messageComposer/userDataInjection.ts +11 -6
  209. package/src/messageComposer/middleware/pollComposer/index.ts +1 -0
  210. package/src/messageComposer/middleware/pollComposer/state.ts +43 -11
  211. package/src/messageComposer/middleware/pollComposer/types.ts +9 -2
  212. package/src/messageComposer/middleware/pollComposer/validation.ts +76 -0
  213. package/src/messageComposer/middleware/textComposer/commandUtils.ts +3 -2
  214. package/src/messageComposer/middleware/textComposer/commands.ts +1 -2
  215. package/src/messageComposer/middleware/textComposer/mentions.ts +91 -39
  216. package/src/messageComposer/pollComposer.ts +11 -3
  217. package/src/messageComposer/textComposer.ts +36 -4
  218. package/src/messageComposer/types.ts +19 -14
  219. package/src/messageDelivery/MessageDeliveryReporter.ts +154 -53
  220. package/src/messageDelivery/MessageReceiptsTracker.ts +136 -64
  221. package/src/messageOperations/FailedSendCache.ts +90 -0
  222. package/src/messageOperations/MessageOperationStatePolicy.ts +269 -27
  223. package/src/messageOperations/MessageOperations.ts +340 -136
  224. package/src/{entityStore → messageOperations}/applyReactionLocally.ts +10 -3
  225. package/src/messageOperations/createMessageOperations.ts +192 -0
  226. package/src/messageOperations/index.ts +7 -0
  227. package/src/messageOperations/reflectReactionEvent.ts +51 -0
  228. package/src/messageOperations/sendOrdering.ts +28 -0
  229. package/src/messageOperations/settlePendingAttachmentUploads.ts +110 -0
  230. package/src/messageOperations/types.ts +74 -0
  231. package/src/middleware.ts +11 -0
  232. package/src/moderation.ts +47 -24
  233. package/src/notifications/NotificationManager.ts +73 -3
  234. package/src/notifications/configuration.ts +10 -8
  235. package/src/notifications/types.ts +58 -42
  236. package/src/offline-support/offline_support_api.ts +380 -197
  237. package/src/offline-support/offline_sync_manager.ts +105 -32
  238. package/src/offline-support/queueableOperations.ts +270 -0
  239. package/src/offline-support/types.ts +85 -39
  240. package/src/pagination/FilterBuilder.ts +1 -22
  241. package/src/pagination/cursorDerivation/createdAtAroundPaginationFlags.ts +11 -7
  242. package/src/pagination/cursorDerivation/linearPaginationFlags.ts +25 -7
  243. package/src/pagination/filterCompiler.ts +17 -0
  244. package/src/pagination/paginators/BasePaginator.ts +731 -81
  245. package/src/pagination/paginators/ChannelPaginator.ts +210 -102
  246. package/src/pagination/paginators/MessageIntervalPaginator.ts +703 -193
  247. package/src/pagination/paginators/MessagePaginator.ts +45 -36
  248. package/src/pagination/paginators/PinnedMessagePaginator.ts +74 -28
  249. package/src/pagination/paginators/ReminderPaginator.ts +15 -13
  250. package/src/pagination/paginators/ThreadPaginator.ts +181 -0
  251. package/src/pagination/paginators/UserGroupPaginator.ts +8 -1
  252. package/src/pagination/paginators/index.ts +1 -0
  253. package/src/pagination/utility.normalization.ts +37 -9
  254. package/src/poll.ts +189 -112
  255. package/src/poll_manager.ts +14 -8
  256. package/src/poll_optimistic_votes.ts +335 -0
  257. package/src/reminders/Reminder.ts +34 -16
  258. package/src/reminders/ReminderManager.ts +68 -41
  259. package/src/reminders/ReminderTimer.ts +7 -6
  260. package/src/search/BaseSearchSource.ts +133 -40
  261. package/src/search/ChannelMemberSearchSource.ts +27 -18
  262. package/src/search/ChannelSearchSource.ts +61 -7
  263. package/src/search/MessageSearchSource.ts +133 -28
  264. package/src/search/SearchController.ts +93 -16
  265. package/src/search/UserSearchSource.ts +27 -13
  266. package/src/search/types.ts +14 -1
  267. package/src/signing.ts +1 -315
  268. package/src/thread.ts +503 -511
  269. package/src/thread_manager.ts +339 -204
  270. package/src/token_manager.ts +12 -32
  271. package/src/types.ts +159 -780
  272. package/src/types.utility.ts +14 -0
  273. package/src/upload-utils.ts +53 -0
  274. package/src/uploadManager.ts +85 -7
  275. package/src/utils/FixedSizeQueueCache.ts +5 -0
  276. package/src/utils/WithSubscriptions.ts +1 -1
  277. package/src/utils/objectPath.ts +67 -0
  278. package/src/utils/time.ts +104 -0
  279. package/src/utils.ts +209 -157
  280. package/dist/types/base64.d.ts +0 -2
  281. package/dist/types/configuration/InstanceConfigurationService.d.ts +0 -26
  282. package/dist/types/connection.d.ts +0 -146
  283. package/dist/types/connection_fallback.d.ts +0 -42
  284. package/dist/types/gen/model-decoders/decoders.d.ts +0 -3
  285. package/dist/types/gen/model-decoders/event-decoder-mapping.d.ts +0 -6
  286. package/dist/types/insights.d.ts +0 -58
  287. package/dist/types/pagination/utility.queryChannel.d.ts +0 -26
  288. package/dist/types/permissions.d.ts +0 -55
  289. package/dist/types/store.d.ts +0 -125
  290. package/src/base64.ts +0 -78
  291. package/src/configuration/InstanceConfigurationService.ts +0 -73
  292. package/src/connection_fallback.ts +0 -215
  293. package/src/gen/model-decoders/decoders.ts +0 -2680
  294. package/src/gen/model-decoders/event-decoder-mapping.ts +0 -198
  295. package/src/insights.ts +0 -83
  296. package/src/pagination/utility.queryChannel.ts +0 -84
  297. package/src/permissions.ts +0 -102
  298. package/src/store.ts +0 -304
@@ -1,20 +1,30 @@
1
+ import { CORE_NOTIFICATION_TYPE } from '../notifications';
2
+ import type { CoreNotificationType } from '../notifications';
1
3
  import { AttachmentManager } from './attachmentManager';
4
+ import { isFailedUpload, isFinishedUpload, isPendingUpload } from './attachmentIdentity';
2
5
  import { CustomDataManager } from './CustomDataManager';
3
6
  import { LinkPreviewsManager } from './linkPreviewsManager';
4
7
  import { LocationComposer } from './LocationComposer';
5
8
  import { MessageComposerEffectHandlers } from './MessageComposerEffectHandlers';
6
9
  import { PollComposer } from './pollComposer';
7
10
  import { TextComposer } from './textComposer';
8
- import { applyCommandValidatorOverride, DEFAULT_COMPOSER_CONFIG } from './configuration';
11
+ import { DEFAULT_COMPOSER_CONFIG } from './configuration';
9
12
  import type { MessageComposerMiddlewareValue } from './middleware';
10
13
  import {
11
14
  MessageComposerMiddlewareExecutor,
12
15
  MessageDraftComposerMiddlewareExecutor,
13
16
  } from './middleware';
14
- import type { Unsubscribe } from '../store';
15
- import { StateStore } from '../store';
17
+ import type { Unsubscribe } from '@stream-io/state-store';
18
+ import { StateStore } from '@stream-io/state-store';
16
19
  import { formatMessage, generateUUIDv4, isLocalMessage } from '../utils';
17
- import { mergeWith } from '../utils/mergeWith';
20
+ import { nowNs } from '../utils/time';
21
+ import { ConfigController } from '../configuration/ConfigController';
22
+ import { deepFreezeConfig } from '../configuration/utils/deepFreezeConfig';
23
+ import { mergeServerRestrictions } from '../configuration/utils/serverAuthority';
24
+ import type {
25
+ ServerRestrictions,
26
+ ServerUpperBounds,
27
+ } from '../configuration/utils/serverAuthority';
18
28
  import { Channel } from '../channel';
19
29
  import { Thread } from '../thread';
20
30
  import type {
@@ -26,9 +36,11 @@ import type {
26
36
  EventType,
27
37
  LocalMessage,
28
38
  MessageResponse,
39
+ TimestampNS,
29
40
  UserResponse,
30
41
  } from '../types';
31
42
  import { chatLoggerSystem } from '../logger';
43
+ import { applyInstanceConfiguration } from '../configuration/utils/applyInstanceConfiguration';
32
44
  import { WithSubscriptions } from '../utils/WithSubscriptions';
33
45
  import type { StreamChat } from '../client';
34
46
  import type { CommandSendability, MessageComposerConfig } from './configuration/types';
@@ -44,7 +56,6 @@ import type { LocationComposerSnapshot } from './LocationComposer';
44
56
  import type { PollComposerSnapshot } from './pollComposer';
45
57
  import type { TextComposerSnapshot } from './textComposer';
46
58
  import type { DeepPartial } from '../types.utility';
47
- import type { MergeWithCustomizer } from '../utils/mergeWith/mergeWithCore';
48
59
  import {
49
60
  getMentionedUsersInText,
50
61
  stripCommandFromText,
@@ -52,7 +63,15 @@ import {
52
63
 
53
64
  type UnregisterSubscriptions = Unsubscribe;
54
65
 
55
- export type LastComposerChange = { draftUpdate: number | null; stateUpdate: number };
66
+ /**
67
+ * Composer edit-audit clock. Both values are unix nanoseconds, so a locally stamped change and a
68
+ * server-derived `created_at` / `updated_at` are directly comparable — which is the whole point of
69
+ * this state.
70
+ */
71
+ export type LastComposerChange = {
72
+ draftUpdate: TimestampNS | null;
73
+ stateUpdate: TimestampNS;
74
+ };
56
75
 
57
76
  export type EditingAuditState = {
58
77
  lastChange: LastComposerChange;
@@ -83,9 +102,23 @@ export type MessageComposerSnapshot = {
83
102
  textComposer: TextComposerSnapshot;
84
103
  };
85
104
 
86
- export type LocalMessageWithLegacyThreadId = LocalMessage & { legacyThreadId?: string };
87
- // todo: remove LocalMessageWithLegacyThreadId
88
- export type CompositionContext = Channel | Thread | LocalMessageWithLegacyThreadId;
105
+ export type CompositionContext = Channel | Thread | LocalMessage;
106
+
107
+ /**
108
+ * What a submit did, and by implication where the content now is.
109
+ *
110
+ * - `sent` - it went out.
111
+ * - `nothing-to-send` - there was nothing to compose, or a middleware discarded the composition
112
+ * (a command that is not ready, one disabled by the quoted or edited message, an upload still
113
+ * running). **The composer keeps its contents**, and the reason has already been reported through
114
+ * `client.notifications`.
115
+ * - `failed` - the request failed. **The composer has been released**; the content is in the
116
+ * message list marked `failed`, where the user retries it.
117
+ *
118
+ * The distinction matters because the last two leave the composer in opposite states, so a caller
119
+ * that reopens or restores UI has to tell them apart.
120
+ */
121
+ export type MessageComposerSubmitResult = 'sent' | 'nothing-to-send' | 'failed';
89
122
 
90
123
  export type MessageComposerState = {
91
124
  id: string;
@@ -116,11 +149,11 @@ const initEditingAuditState = (
116
149
  composition?: DraftResponse | MessageResponse | LocalMessage,
117
150
  ): EditingAuditState => {
118
151
  let draftUpdate = null;
119
- let stateUpdate = new Date().getTime();
152
+ let stateUpdate = nowNs();
120
153
  if (compositionIsDraftResponse(composition)) {
121
- stateUpdate = draftUpdate = new Date(composition.created_at).getTime();
154
+ stateUpdate = draftUpdate = composition.created_at;
122
155
  } else if (composition && isLocalMessage(composition)) {
123
- stateUpdate = new Date(composition.updated_at).getTime();
156
+ stateUpdate = composition.updated_at;
124
157
  }
125
158
  return {
126
159
  lastChange: {
@@ -176,7 +209,15 @@ export class MessageComposer extends WithSubscriptions {
176
209
  readonly channel: Channel;
177
210
  readonly state: StateStore<MessageComposerState>;
178
211
  readonly editingAuditState: StateStore<EditingAuditState>;
179
- readonly configState: StateStore<MessageComposerConfig>;
212
+
213
+ /**
214
+ * Resolved configuration, as a store — the shape every configurable class exposes
215
+ * (`configState` / `config` / `updateConfig`). Delegates rather than holding a copy, so the field and
216
+ * the controller's store cannot drift.
217
+ */
218
+ get configState(): StateStore<MessageComposerConfig> {
219
+ return this.configController.state;
220
+ }
180
221
  readonly compositionContext: CompositionContext;
181
222
  readonly compositionMiddlewareExecutor: MessageComposerMiddlewareExecutor;
182
223
  readonly draftCompositionMiddlewareExecutor: MessageDraftComposerMiddlewareExecutor;
@@ -189,6 +230,20 @@ export class MessageComposer extends WithSubscriptions {
189
230
  customDataManager: CustomDataManager;
190
231
  private snapshots: MessageComposerSnapshot[] = [];
191
232
  private effectHandlers: MessageComposerEffectHandlers;
233
+ /**
234
+ * The shared configuration machinery, with the three hooks this entity is the only one to need:
235
+ * `retainPatches` so an `updateConfig` request is *retained* and re-applied rather than written
236
+ * into the result (**DV-18**), and `applyAuthority` for the server's last word.
237
+ *
238
+ * A third hook, `finalizeRequest`, was added here for `commands.sendValidator` and then removed: the
239
+ * deep merge assigns function values directly and skips `undefined`, so the override it called reached
240
+ * the same answer on every layer shape — a later layer that stays silent cannot erase an earlier
241
+ * choice, because a merge only writes keys that are present.
242
+ */
243
+ private readonly configController: ConfigController<
244
+ MessageComposerConfig,
245
+ DeepPartial<MessageComposerConfig>
246
+ >;
192
247
  // todo: mediaRecorder: MediaRecorderController;
193
248
 
194
249
  constructor({
@@ -208,50 +263,32 @@ export class MessageComposer extends WithSubscriptions {
208
263
  this.channel = compositionContext.channel;
209
264
  } else if (compositionContext.cid) {
210
265
  const [type, id] = compositionContext.cid.split(':');
211
- this.channel = client.channel(type, id);
266
+ this.channel = client.channelManager.ensure({ type, id });
212
267
  } else {
213
268
  throw new Error(
214
269
  'MessageComposer requires composition context pointing to channel (channel or context.cid)',
215
270
  );
216
271
  }
217
272
 
218
- /**
219
- * Customizes config merges for the composer constructor.
220
- *
221
- * It catches two scalar override cases that should not use the default deep merge:
222
- * - client-disabled `enabled` flags stay disabled even if the channel config tries to re-enable them
223
- * - scalar channel-config values replace client defaults for matching config keys
224
- *
225
- * All other values fall back to the normal `mergeWith` behavior.
226
- */
227
- const mergeMessageComposerConfigCustomizer: MergeWithCustomizer<
273
+ this.configController = new ConfigController<
274
+ MessageComposerConfig,
228
275
  DeepPartial<MessageComposerConfig>
229
- > = (originalVal, channelConfigVal, key) =>
230
- typeof originalVal === 'object'
231
- ? undefined
232
- : originalVal === false && key === 'enabled' // prevent enabling features that are disabled client-side
233
- ? false
234
- : ['string', 'number', 'bigint', 'boolean', 'symbol'].includes(
235
- // prevent enabling features that are disabled server-side
236
- typeof channelConfigVal,
237
- )
238
- ? channelConfigVal // scalar values get overridden by server-side config
239
- : originalVal;
240
-
241
- this.configState = new StateStore<MessageComposerConfig>(
242
- applyCommandValidatorOverride(
243
- mergeWith(
244
- mergeWith(DEFAULT_COMPOSER_CONFIG, config ?? {}),
245
- {
246
- location: {
247
- enabled: this.channel.getConfig()?.shared_locations,
248
- },
249
- },
250
- mergeMessageComposerConfigCustomizer,
251
- ),
252
- config,
253
- ),
254
- );
276
+ >({
277
+ defaults: DEFAULT_COMPOSER_CONFIG,
278
+ constructorOptions: config as Partial<MessageComposerConfig> | undefined,
279
+ initialSlice: this.declarativeConfig as Partial<MessageComposerConfig> | undefined,
280
+ mergeSlice: 'deep',
281
+ // Stages 4 and 5 both arrive through `updateConfig`, and both have to outlive a re-resolution.
282
+ retainPatches: true,
283
+ applyAuthority: (requested) =>
284
+ deepFreezeConfig(
285
+ mergeServerRestrictions(
286
+ requested,
287
+ this.serverRestrictionsFor(requested),
288
+ this.serverUpperBounds,
289
+ ),
290
+ ) as MessageComposerConfig,
291
+ });
255
292
 
256
293
  let message: LocalMessage | DraftMessage | undefined = undefined;
257
294
  if (compositionIsDraftResponse(composition)) {
@@ -290,10 +327,6 @@ export class MessageComposer extends WithSubscriptions {
290
327
  return 'thread';
291
328
  }
292
329
 
293
- if (typeof compositionContext.legacyThreadId === 'string') {
294
- return 'legacy_thread';
295
- }
296
-
297
330
  return 'message';
298
331
  }
299
332
 
@@ -305,7 +338,15 @@ export class MessageComposer extends WithSubscriptions {
305
338
 
306
339
  static generateId = generateUUIDv4;
307
340
 
308
- get config(): MessageComposerConfig {
341
+ /**
342
+ * The current resolved configuration.
343
+ *
344
+ * `Readonly` for the same reason every other configurable class's getter is: the value is the store's
345
+ * live object, so assigning to a field would change state while notifying nobody. Use
346
+ * {@link updateConfig}. `Readonly` is shallow, so nested writes are caught at runtime instead — the
347
+ * whole resolution is deep-frozen by {@link resolvedConfig}, not only the untouched defaults.
348
+ */
349
+ get config(): Readonly<MessageComposerConfig> {
309
350
  return this.configState.getLatestValue();
310
351
  }
311
352
 
@@ -347,10 +388,6 @@ export class MessageComposer extends WithSubscriptions {
347
388
  return this.compositionContext.id;
348
389
  }
349
390
 
350
- if (typeof this.compositionContext.legacyThreadId === 'string') {
351
- return this.compositionContext.legacyThreadId;
352
- }
353
-
354
391
  // check if the message is a reply, get parentMessageId
355
392
  if (typeof this.compositionContext.parent_id === 'string') {
356
393
  return this.compositionContext.parent_id;
@@ -434,16 +471,73 @@ export class MessageComposer extends WithSubscriptions {
434
471
  return !currentCommand || this.validateCommandSendability(currentCommand).ready;
435
472
  }
436
473
 
474
+ /**
475
+ * Whether a message may be sent while its attachments are still uploading — see
476
+ * {@link AttachmentManagerConfig.pendingUploadsEnabled}.
477
+ */
478
+ get allowsPendingUploads() {
479
+ return this.attachmentManager.config.pendingUploadsEnabled;
480
+ }
481
+
482
+ /**
483
+ * Where a composed message goes: the thread when this composer belongs to one, the channel
484
+ * otherwise.
485
+ *
486
+ * Thread replies live in `thread.messagePaginator`, which is independent of the channel's, so
487
+ * dispatching to the wrong one leaves the reply invisible where it was written. An edit composer
488
+ * is built from the message rather than from its thread, so it finds the thread only when
489
+ * `client.threads` has it registered — listed, or active (open somewhere).
490
+ */
491
+ get defaultSubmitTarget(): Channel | Thread {
492
+ if (this.compositionContext instanceof Thread) return this.compositionContext;
493
+
494
+ const { threadId } = this;
495
+ return (threadId && this.client.threads.get(threadId)) || this.channel;
496
+ }
497
+
498
+ /**
499
+ * Whether submitting keeps the composer's contents rather than clearing them - see
500
+ * {@link MessageComposerConfig.retainCompositionOnSubmit}.
501
+ *
502
+ * Read by the attachments composition step too: content the composer keeps must not also ride
503
+ * along on the submitted message, or one `localMetadata.id` ends up owned in two places.
504
+ */
505
+ get retainsCompositionOnSubmit() {
506
+ return this.config.retainCompositionOnSubmit(this);
507
+ }
508
+
437
509
  get hasSendableData() {
438
- return (
439
- this.isCommandSendable &&
440
- !!(
441
- (!this.attachmentManager.uploadsInProgressCount &&
442
- (!this.textComposer.textIsEmpty ||
443
- this.attachmentManager.successfulUploadsCount > 0)) ||
510
+ if (!this.isCommandSendable) return false;
511
+
512
+ if (this.allowsPendingUploads) {
513
+ // An upload in flight is no longer a blocker, and a pending attachment counts as content
514
+ // in its own right — otherwise an attachment-only message could never be sent before its
515
+ // upload finished, which is the point of the flow. A `failed` one counts too: it rides
516
+ // along on the optimistic message, where `settlePendingAttachmentUploads` retries it.
517
+ // `blocked` still does not — the server's upload configuration refused it, so no retry can
518
+ // settle it, and a message whose only attachment was rejected outright must not look
519
+ // sendable.
520
+ const hasSendableAttachment = this.attachmentManager.attachments.some(
521
+ (attachment) =>
522
+ isFinishedUpload(attachment) ||
523
+ isPendingUpload(attachment) ||
524
+ isFailedUpload(attachment),
525
+ );
526
+
527
+ return !!(
528
+ !this.textComposer.textIsEmpty ||
529
+ hasSendableAttachment ||
444
530
  this.pollId ||
445
- !!this.locationComposer.validLocation
446
- )
531
+ this.locationComposer.validLocation
532
+ );
533
+ }
534
+
535
+ return !!(
536
+ (!this.attachmentManager.uploadsInProgressCount &&
537
+ (!this.textComposer.textIsEmpty ||
538
+ this.attachmentManager.successfulUploadsCount > 0)) ||
539
+ this.pollId ||
540
+ !!this.locationComposer.validLocation
447
541
  );
448
542
  }
449
543
 
@@ -466,8 +560,8 @@ export class MessageComposer extends WithSubscriptions {
466
560
 
467
561
  // does not mean that the original edited message is different from the current state
468
562
  const editedMessageWasUpdated =
469
- !!this.editedMessage?.updated_at &&
470
- new Date(this.editedMessage.updated_at).getTime() < this.lastChange.stateUpdate;
563
+ this.editedMessage?.updated_at != null &&
564
+ this.editedMessage.updated_at < this.lastChange.stateUpdate;
471
565
 
472
566
  const draftWasChanged =
473
567
  !!this.lastChange.draftUpdate &&
@@ -476,12 +570,152 @@ export class MessageComposer extends WithSubscriptions {
476
570
  return editedMessageWasUpdated || draftWasChanged || composingMessageFromScratch;
477
571
  }
478
572
 
573
+ /**
574
+ * Records a configuration change as something *you* asked for, then republishes.
575
+ *
576
+ * The patch is kept — see {@link imperativeConfig} — rather than merged into the published result and
577
+ * forgotten. That is what makes the request survive a later re-resolution, including one triggered by
578
+ * the server changing its mind.
579
+ */
479
580
  updateConfig(config: DeepPartial<MessageComposerConfig>) {
480
- this.configState.partialNext(
481
- applyCommandValidatorOverride(mergeWith(this.config, config), config),
482
- );
581
+ this.configController.patch(config as Partial<MessageComposerConfig>);
582
+ }
583
+
584
+ /**
585
+ * What this composer has been **asked** for, before the server has any say — stages 1 to 5 of
586
+ * `docs/instance-configuration.md` §3.
587
+ *
588
+ * Available on every entity that retains its patches, not just this one: it is the controller's, and
589
+ * the split it exposes is what **FU-35** would extend elsewhere by switching on `retainPatches`.
590
+ */
591
+ get requestedConfig(): Readonly<MessageComposerConfig> {
592
+ return this.configController.requested;
593
+ }
594
+
595
+ /** The declarative slice for this composer, re-read live so a change is picked up. */
596
+ private get declarativeConfig(): DeepPartial<MessageComposerConfig> {
597
+ return (this.client.config.getConfig('messageComposer') ??
598
+ {}) as DeepPartial<MessageComposerConfig>;
599
+ }
600
+
601
+ /**
602
+ * The configuration fields this composer's channel decides server-side.
603
+ *
604
+ * Reading them is the composer's job rather than the shared helper's: only the composer knows that
605
+ * `location.enabled` is gated on `shared_locations`, and only an existing composer has a channel to
606
+ * ask. `serverConfig` is re-read on every call, so a restriction that changes mid-session is picked up
607
+ * rather than captured once.
608
+ *
609
+ * Every entry here is a boolean gate, so `mergeServerRestrictions` ANDs it with what was requested and
610
+ * either side may switch the feature off — a client asking for less than the server grants is always
611
+ * legitimate. That is the whole point of mirroring these flags into configuration rather than leaving
612
+ * consumers to read `serverConfig` themselves: a raw server flag answers only the server's half, so a UI
613
+ * reading it offers features the composer has already disabled and would refuse to compose.
614
+ *
615
+ * `commands` is deliberately absent. The server sends a *list* of commands rather than a gate, so there
616
+ * is nothing to AND and no integrator intent to mirror; consumers read it from the channel's config.
617
+ *
618
+ * Takes the requested configuration because one restriction is conditional — see `uploads` below.
619
+ */
620
+ private serverRestrictionsFor(
621
+ requested: MessageComposerConfig,
622
+ ): ServerRestrictions<MessageComposerConfig> {
623
+ const channelConfig = this.channel.serverConfig;
624
+
625
+ return {
626
+ /**
627
+ * `uploads` describes **Stream's upload endpoint**, not the concept of attaching files. Setting
628
+ * `attachments.customCdn` says the bytes go to storage Stream neither hosts nor charges for, and
629
+ * the flag says nothing about whether that can work — applying it there would make "turn uploads
630
+ * on in Stream" a precondition for uploading to your own CDN, which is not this SDK's to require.
631
+ *
632
+ * Keyed on `customCdn` rather than on the presence of `doUploadRequest`: a custom upload function
633
+ * says how files are sent, not where, and one that still posts to Stream must stay subject to
634
+ * Stream's rules.
635
+ *
636
+ * `undefined` rather than `true`: the server is not asserting the opposite either, it simply has
637
+ * no say. `mergeServerRestrictions` leaves the request standing for a field it states nothing
638
+ * about, so the integrator's `attachments.enabled` decides alone — the same way an unset
639
+ * `shared_locations` behaves.
640
+ */
641
+ attachments: {
642
+ enabled: requested.attachments.customCdn ? undefined : channelConfig?.uploads,
643
+ },
644
+ linkPreviews: { enabled: channelConfig?.url_enrichment },
645
+ location: { enabled: channelConfig?.shared_locations },
646
+ polls: { enabled: channelConfig?.polls },
647
+ };
648
+ }
649
+
650
+ /**
651
+ * Ceilings this composer's channel imposes server-side.
652
+ *
653
+ * `max_message_length` caps both length limits rather than setting them: a composer asking for something
654
+ * shorter keeps its own number, and one asking for nothing at all inherits the server's — which is the
655
+ * default, and the case worth having. Left unlimited, the composer happily accepts text the send endpoint
656
+ * then rejects, so the limit is enforced late and as an API error instead of in the editor.
657
+ */
658
+ private get serverUpperBounds(): ServerUpperBounds<MessageComposerConfig> {
659
+ const maxMessageLength = this.channel.serverConfig?.max_message_length;
660
+
661
+ return {
662
+ text: { maxLengthOnEdit: maxMessageLength, maxLengthOnSend: maxMessageLength },
663
+ };
483
664
  }
484
665
 
666
+ /**
667
+ * Resolves the configuration and publishes it, unless the result is deep-equal to what is already there.
668
+ *
669
+ * The guard is needed because `StateStore.next`'s own `===` no-op can never apply here: every resolution
670
+ * allocates a new object, so without a comparison *every* publish notifies, whether or not any value
671
+ * moved.
672
+ *
673
+ * Worth the walk: `isEqual` over a resolved composer config measures ~1.7µs, against a resolution at
674
+ * ~3.5µs plus every subscriber's work. The dominant source of no-op publishes is fixed upstream in
675
+ * `StreamChat._addChannelConfig`, which stops a repeated channel query from waking that channel's
676
+ * composer at all; this
677
+ * catches the rest — re-registering a declarative value that has not changed, a `reset` with nothing
678
+ * registered, an empty `updateConfig({})`.
679
+ */
680
+ private publishConfig = () => {
681
+ this.configController.rederive(this.declarativeConfig);
682
+ };
683
+
684
+ /**
685
+ * Rebuilds the configuration from its inputs and **discards imperative changes** — every
686
+ * {@link updateConfig} patch, including those made through a sub-composer setter such as
687
+ * `textComposer.defaultValue` or `attachmentManager.maxNumberOfFilesPerMessage`.
688
+ *
689
+ * Called by the constructor and by `client.config.reset()`, where dropping them is the point: a reset
690
+ * means "back to what is registered". Anything that merely needs the configuration re-resolved — the
691
+ * server's answer arriving, a declarative change — must use {@link publishConfig} or
692
+ * {@link applyServerRestrictions}, which keep them.
693
+ */
694
+ initializeConfig = () => {
695
+ this.configController.initialize(this.declarativeConfig);
696
+ };
697
+
698
+ /**
699
+ * Re-resolves the configuration against the channel's current server-side restrictions.
700
+ *
701
+ * Call this when the server's answer may have changed — its config has just arrived, or it was updated.
702
+ * Safe in both directions, which is the whole reason it exists: a feature you disabled stays disabled
703
+ * when the server permits it, and a feature the server *stops* restricting goes back to whatever you
704
+ * asked for, because the restriction is applied to your request rather than to the previous result.
705
+ *
706
+ * Reachable rather than public: `Channel.query` is the only caller, covering a composer that has not
707
+ * registered subscriptions and so cannot hear the answer change through
708
+ * {@link subscribeChannelConfigChanged}. Nothing outside this package needs it — registering subscriptions
709
+ * is the supported way to stay current, and a composer that has done so is already covered. Marked
710
+ * `@internal` so it is not read as a supported extension point; the name is kept because what it does
711
+ * is* re-assert the server's restrictions, even though the whole resolution is what performs that.
712
+ *
713
+ * @internal
714
+ */
715
+ applyServerRestrictions = () => {
716
+ this.publishConfig();
717
+ };
718
+
485
719
  refreshId = () => {
486
720
  this.state.partialNext({ id: MessageComposer.generateId() });
487
721
  };
@@ -552,6 +786,26 @@ export class MessageComposer extends WithSubscriptions {
552
786
  this.textComposer.restoreSnapshot(snapshot.textComposer);
553
787
  };
554
788
 
789
+ /**
790
+ * Moves this composition into `target`, replacing what `target` held, and clears this composer
791
+ * locally: the text, attachments, poll, location, link previews, custom data, quoted message and
792
+ * reply-in-channel choice. An upload still running keeps running and its result lands in `target`
793
+ * (see {@link AttachmentManager.takeOver}). Nothing is sent.
794
+ *
795
+ * @internal
796
+ */
797
+ transferTo = (target: MessageComposer) => {
798
+ target.textComposer.takeOver(this.textComposer);
799
+ target.attachmentManager.takeOver(this.attachmentManager);
800
+ target.linkPreviewsManager.takeOver(this.linkPreviewsManager);
801
+ target.locationComposer.takeOver(this.locationComposer);
802
+ target.pollComposer.takeOver(this.pollComposer);
803
+ target.customDataManager.takeOver(this.customDataManager);
804
+ const { pollId, quotedMessage, showReplyInChannel } = this.state.getLatestValue();
805
+ target.state.partialNext({ pollId, quotedMessage, showReplyInChannel });
806
+ this.clear();
807
+ };
808
+
555
809
  captureSnapshot = (snapshot = this.getSnapshot()) => {
556
810
  if (this.snapshots.length) return;
557
811
  this.snapshots.push(snapshot);
@@ -572,13 +826,13 @@ export class MessageComposer extends WithSubscriptions {
572
826
 
573
827
  private logStateUpdateTimestamp() {
574
828
  this.editingAuditState.partialNext({
575
- lastChange: { ...this.lastChange, stateUpdate: new Date().getTime() },
829
+ lastChange: { ...this.lastChange, stateUpdate: nowNs() },
576
830
  });
577
831
  }
578
832
 
579
833
  private logDraftUpdateTimestamp() {
580
834
  if (!this.config.drafts.enabled) return;
581
- const timestamp = new Date().getTime();
835
+ const timestamp = nowNs();
582
836
  this.editingAuditState.partialNext({
583
837
  lastChange: { draftUpdate: timestamp, stateUpdate: timestamp },
584
838
  });
@@ -597,6 +851,7 @@ export class MessageComposer extends WithSubscriptions {
597
851
  public registerSubscriptions = (): UnregisterSubscriptions => {
598
852
  if (!this.hasSubscriptions) {
599
853
  this.addUnsubscribeFunction(this.subscribeMessageComposerSetupStateChange());
854
+ this.addUnsubscribeFunction(this.subscribeChannelConfigChanged());
600
855
  this.addUnsubscribeFunction(this.subscribeMessageUpdated());
601
856
  this.addUnsubscribeFunction(this.subscribeMessageDeleted());
602
857
 
@@ -640,24 +895,34 @@ export class MessageComposer extends WithSubscriptions {
640
895
  return () => unsubscribeFunctions.forEach((unsubscribe) => unsubscribe());
641
896
  };
642
897
 
643
- private subscribeMessageComposerSetupStateChange = () => {
644
- let tearDown: (() => void) | null = null;
645
- const unsubscribe =
646
- this.client.instanceConfigurationService.MessageComposer.subscribeWithSelector(
647
- ({ setupFunction: setup }) => ({
648
- setup,
649
- }),
650
- ({ setup }) => {
651
- tearDown?.();
652
- tearDown = setup?.({ composer: this }) ?? null;
653
- },
654
- );
898
+ private subscribeMessageComposerSetupStateChange = () =>
899
+ applyInstanceConfiguration({
900
+ args: { composer: this },
901
+ config: this.client.config,
902
+ key: 'messageComposer',
903
+ // Re-resolve rather than merge the slice in. `requestedConfig` reads the declarative slice live, so
904
+ // there is nothing to copy — and copying it through `updateConfig` would file it under *imperative*
905
+ // changes, letting a later declarative change override an imperative one. That inverts stages 2 and
906
+ // 5 of the documented order, which says the more specific, later request wins.
907
+ applyConfig: () => this.publishConfig(),
908
+ reinitializeConfig: this.initializeConfig,
909
+ });
655
910
 
656
- return () => {
657
- tearDown?.();
658
- unsubscribe();
659
- };
660
- };
911
+ /**
912
+ * The channel's server-side config (`client.channelServerConfigs[cid]`) is populated by `query`/`watch`,
913
+ * which for a channel opened via `client.channelManager.ensure({ type, id })` happens *after* this composer was
914
+ * constructed. Left unwatched, the composer would keep the defaults it derived when `serverConfig` was
915
+ * still undefined — so `location.enabled` would stay `true` for an app that disables `shared_locations`
916
+ * server-side. Re-deriving when the config lands keeps the server authoritative.
917
+ *
918
+ * Selected by cid, matching the store's key space: `shared_locations` and `max_message_length` are both
919
+ * overridable per channel, so a sibling channel's config is not this composer's answer.
920
+ */
921
+ private subscribeChannelConfigChanged = () =>
922
+ this.client.channelServerConfigsStore.subscribeWithSelector(
923
+ ({ configs }) => ({ channelConfig: configs[this.channel.cid] }),
924
+ () => this.applyServerRestrictions(),
925
+ );
661
926
 
662
927
  private subscribeMessageDeleted = () =>
663
928
  this.client.on('message.deleted', (event) => {
@@ -855,7 +1120,7 @@ export class MessageComposer extends WithSubscriptions {
855
1120
  };
856
1121
 
857
1122
  compose = async (): Promise<MessageComposerMiddlewareValue['state'] | undefined> => {
858
- const created_at = this.editedMessage?.created_at ?? new Date();
1123
+ const created_at = this.editedMessage?.created_at ?? nowNs();
859
1124
 
860
1125
  const text = '';
861
1126
  const result = await this.compositionMiddlewareExecutor.execute({
@@ -875,7 +1140,7 @@ export class MessageComposer extends WithSubscriptions {
875
1140
  id: this.id,
876
1141
  mentioned_users: [] as UserResponse[],
877
1142
  parent_id: this.threadId ?? undefined,
878
- pinned_at: this.editedMessage?.pinned_at || undefined,
1143
+ pinned_at: this.editedMessage?.pinned_at ?? undefined,
879
1144
  reaction_groups: undefined,
880
1145
  status: this.editedMessage ? this.editedMessage.status : 'sending',
881
1146
  text,
@@ -911,7 +1176,9 @@ export class MessageComposer extends WithSubscriptions {
911
1176
  createDraft = async () => {
912
1177
  // server-side drafts are not stored on message level but on thread and channel level
913
1178
  // therefore we don't need to create a draft if the message is edited
914
- if (this.editedMessage || !this.config.drafts.enabled) return;
1179
+ // nor for a channel without an id yet: there is nothing to save it for (see `isProvisional`)
1180
+ if (this.editedMessage || !this.config.drafts.enabled || this.channel.isProvisional)
1181
+ return;
915
1182
  const composition = await this.composeDraft();
916
1183
  if (!composition) return;
917
1184
  const { draft } = composition;
@@ -920,7 +1187,7 @@ export class MessageComposer extends WithSubscriptions {
920
1187
  try {
921
1188
  const optimisticDraftResponse = {
922
1189
  channel_cid: this.channel.cid,
923
- created_at: new Date(),
1190
+ created_at: nowNs(),
924
1191
  message: draft as DraftMessage,
925
1192
  parent_id: draft.parent_id,
926
1193
  quoted_message: this.quotedMessage ?? undefined,
@@ -937,7 +1204,13 @@ export class MessageComposer extends WithSubscriptions {
937
1204
  };
938
1205
 
939
1206
  deleteDraft = async () => {
940
- if (this.editedMessage || !this.config.drafts.enabled || !this.draftId) return;
1207
+ if (
1208
+ this.editedMessage ||
1209
+ !this.config.drafts.enabled ||
1210
+ !this.draftId ||
1211
+ this.channel.isProvisional
1212
+ )
1213
+ return;
941
1214
  this.state.partialNext({ draftId: null }); // todo: should we clear the whole state?
942
1215
  const parentId = this.threadId ?? undefined;
943
1216
  if (this.client.offlineDb) {
@@ -1008,7 +1281,7 @@ export class MessageComposer extends WithSubscriptions {
1008
1281
  context: { composer: this },
1009
1282
  },
1010
1283
  options: {
1011
- type: 'api:poll:create:failed',
1284
+ type: CORE_NOTIFICATION_TYPE.pollCreateFailed,
1012
1285
  metadata: {
1013
1286
  reason: (error as Error).message,
1014
1287
  },
@@ -1019,6 +1292,122 @@ export class MessageComposer extends WithSubscriptions {
1019
1292
  }
1020
1293
  };
1021
1294
 
1295
+ /**
1296
+ * Lets go of what the submitted message took with it.
1297
+ *
1298
+ * A poll message carries no text or attachments of its own, so the composer keeps whatever else
1299
+ * was drafted and releases only the poll. Everything else is a full clear.
1300
+ */
1301
+ private releaseSubmittedComposition = () => {
1302
+ if (this.retainsCompositionOnSubmit) {
1303
+ this.state.partialNext({
1304
+ id: MessageComposer.generateId(),
1305
+ // Unconditional, and safe whatever decided to retain: a poll that exists is always a poll
1306
+ // that just went out, because `createMessageComposerStateCompositionMiddleware` copies a
1307
+ // set `pollId` onto every composition - threads and edits included, where the poll-only
1308
+ // middleware forwards. There is no state where this detaches one the submission did not
1309
+ // carry.
1310
+ //
1311
+ // Detaching it is also not optional. While `pollId` is set, `hasSendableData` counts it as
1312
+ // content on its own and `createPollOnlyCompositionMiddleware` turns every composition
1313
+ // into a poll-only message, so a composer left bound to a spent poll nullifies whatever is
1314
+ // typed next and re-sends the same poll.
1315
+ pollId: null,
1316
+ });
1317
+ return;
1318
+ }
1319
+
1320
+ this.clear();
1321
+ };
1322
+
1323
+ private reportSubmitFailure = (
1324
+ type: CoreNotificationType,
1325
+ message: string,
1326
+ error: unknown,
1327
+ ) => {
1328
+ this.client.notifications.addError({
1329
+ message,
1330
+ origin: {
1331
+ emitter: 'MessageComposer',
1332
+ context: { composer: this },
1333
+ },
1334
+ options: {
1335
+ type,
1336
+ metadata: { reason: (error as Error).message },
1337
+ originalError: error instanceof Error ? error : undefined,
1338
+ },
1339
+ });
1340
+ };
1341
+
1342
+ /**
1343
+ * Composes the message and sends it, releasing the composer as it goes.
1344
+ *
1345
+ * Never rejects - see {@link MessageComposerSubmitResult} for what each outcome means and where
1346
+ * the content ends up. A failure is reported through `client.notifications`, and the message
1347
+ * stays in the list marked `failed`, which is where the user retries it. Callers rendering their
1348
+ * own post-send feedback have to check the result.
1349
+ */
1350
+ send = async (): Promise<MessageComposerSubmitResult> => {
1351
+ const composition = await this.compose();
1352
+ if (!composition?.message) return 'nothing-to-send';
1353
+
1354
+ const { localMessage, message, sendOptions } = composition;
1355
+
1356
+ // Released before the request, not after. The request lasts a round trip - longer still when it
1357
+ // waits for an upload to settle - and clearing at the end leaves that whole window for the
1358
+ // user's next keystrokes to race the clear.
1359
+ this.releaseSubmittedComposition();
1360
+
1361
+ try {
1362
+ await this.defaultSubmitTarget.messageOperations.send({
1363
+ localMessage,
1364
+ message,
1365
+ options: sendOptions,
1366
+ });
1367
+ return 'sent';
1368
+ } catch (error) {
1369
+ // Nothing is put back. The message is already in the list marked `failed` with a retry
1370
+ // affordance, so restoring here would leave the same content - and the same attachment upload
1371
+ // ids - owned in two places, where sending either copy corrupts the other.
1372
+ this.reportSubmitFailure(
1373
+ CORE_NOTIFICATION_TYPE.messageSendFailed,
1374
+ 'Send message request failed',
1375
+ error,
1376
+ );
1377
+ return 'failed';
1378
+ }
1379
+ };
1380
+
1381
+ /**
1382
+ * Composes the edit and saves it, on the same terms as {@link send} - including releasing the
1383
+ * composer before the request rather than after it.
1384
+ */
1385
+ update = async (): Promise<MessageComposerSubmitResult> => {
1386
+ const composition = await this.compose();
1387
+ if (!composition?.message) return 'nothing-to-send';
1388
+
1389
+ const { localMessage, sendOptions } = composition;
1390
+
1391
+ this.releaseSubmittedComposition();
1392
+
1393
+ try {
1394
+ await this.defaultSubmitTarget.messageOperations.update({
1395
+ localMessage,
1396
+ options: sendOptions,
1397
+ });
1398
+ return 'sent';
1399
+ } catch (error) {
1400
+ // As in `send`: the edit is kept on the message and marked failed, so there is nothing to
1401
+ // restore here.
1402
+ this.reportSubmitFailure(
1403
+ CORE_NOTIFICATION_TYPE.messageUpdateFailed,
1404
+ 'Edit message request failed',
1405
+ error,
1406
+ );
1407
+ return 'failed';
1408
+ }
1409
+ };
1410
+
1022
1411
  sendLocation = async () => {
1023
1412
  const location = this.locationComposer.validLocation;
1024
1413
  if (this.threadId || !location) return;
@@ -1034,7 +1423,7 @@ export class MessageComposer extends WithSubscriptions {
1034
1423
  context: { composer: this },
1035
1424
  },
1036
1425
  options: {
1037
- type: 'api:location:create:failed',
1426
+ type: CORE_NOTIFICATION_TYPE.locationCreateFailed,
1038
1427
  metadata: {
1039
1428
  reason: (error as Error).message,
1040
1429
  },