@amityco/ts-sdk-react-native 7.5.3 → 7.6.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 (383) hide show
  1. package/dist/@types/core/events.d.ts +7 -0
  2. package/dist/@types/core/events.d.ts.map +1 -1
  3. package/dist/@types/core/model.d.ts +5 -1
  4. package/dist/@types/core/model.d.ts.map +1 -1
  5. package/dist/@types/core/payload.d.ts +38 -5
  6. package/dist/@types/core/payload.d.ts.map +1 -1
  7. package/dist/@types/domains/channel.d.ts +1 -0
  8. package/dist/@types/domains/channel.d.ts.map +1 -1
  9. package/dist/@types/domains/client.d.ts +10 -0
  10. package/dist/@types/domains/client.d.ts.map +1 -1
  11. package/dist/@types/domains/community.d.ts +51 -1
  12. package/dist/@types/domains/community.d.ts.map +1 -1
  13. package/dist/@types/domains/content.d.ts +5 -2
  14. package/dist/@types/domains/content.d.ts.map +1 -1
  15. package/dist/@types/domains/group.d.ts +2 -0
  16. package/dist/@types/domains/group.d.ts.map +1 -1
  17. package/dist/@types/domains/invitation.d.ts +92 -0
  18. package/dist/@types/domains/invitation.d.ts.map +1 -0
  19. package/dist/@types/domains/joinRequest.d.ts +53 -0
  20. package/dist/@types/domains/joinRequest.d.ts.map +1 -0
  21. package/dist/@types/domains/notification.d.ts +4 -2
  22. package/dist/@types/domains/notification.d.ts.map +1 -1
  23. package/dist/@types/domains/pinnedPost.d.ts +1 -1
  24. package/dist/@types/domains/pinnedPost.d.ts.map +1 -1
  25. package/dist/@types/index.d.ts +5 -0
  26. package/dist/@types/index.d.ts.map +1 -1
  27. package/dist/channelRepository/channelMembership/observers/getMembers/ChannelMemberLiveCollectionController.d.ts.map +1 -1
  28. package/dist/channelRepository/channelMembership/observers/searchMembers/SearchChannelMemberLiveCollectionController.d.ts.map +1 -1
  29. package/dist/channelRepository/channelMembership/observers/searchMembers/SearchChannelMemberQueryStreamController.d.ts +2 -2
  30. package/dist/channelRepository/channelMembership/observers/searchMembers/SearchChannelMemberQueryStreamController.d.ts.map +1 -1
  31. package/dist/client/api/index.d.ts +1 -0
  32. package/dist/client/api/index.d.ts.map +1 -1
  33. package/dist/client/api/resumeSession.d.ts +32 -0
  34. package/dist/client/api/resumeSession.d.ts.map +1 -0
  35. package/dist/client/api/tests/resumeSession.test.d.ts +2 -0
  36. package/dist/client/api/tests/resumeSession.test.d.ts.map +1 -0
  37. package/dist/communityRepository/api/createCommunity.d.ts +3 -3
  38. package/dist/communityRepository/api/createCommunity.d.ts.map +1 -1
  39. package/dist/communityRepository/api/deleteCommunity.d.ts.map +1 -1
  40. package/dist/communityRepository/api/getCommunities.d.ts +1 -1
  41. package/dist/communityRepository/api/getCommunities.d.ts.map +1 -1
  42. package/dist/communityRepository/api/getCommunity.d.ts +2 -2
  43. package/dist/communityRepository/api/getCommunity.d.ts.map +1 -1
  44. package/dist/communityRepository/api/getRecommendedCommunities.d.ts +3 -1
  45. package/dist/communityRepository/api/getRecommendedCommunities.d.ts.map +1 -1
  46. package/dist/communityRepository/api/getTrendingCommunities.d.ts +3 -1
  47. package/dist/communityRepository/api/getTrendingCommunities.d.ts.map +1 -1
  48. package/dist/communityRepository/api/joinCommunity.d.ts +3 -0
  49. package/dist/communityRepository/api/joinCommunity.d.ts.map +1 -1
  50. package/dist/communityRepository/api/queryCommunities.d.ts.map +1 -1
  51. package/dist/communityRepository/api/updateCommunity.d.ts +3 -3
  52. package/dist/communityRepository/api/updateCommunity.d.ts.map +1 -1
  53. package/dist/communityRepository/communityMembership/events/index.d.ts +1 -0
  54. package/dist/communityRepository/communityMembership/events/index.d.ts.map +1 -1
  55. package/dist/communityRepository/communityMembership/events/onCommunityJoined.d.ts +1 -1
  56. package/dist/communityRepository/communityMembership/events/onCommunityJoined.d.ts.map +1 -1
  57. package/dist/communityRepository/communityMembership/events/onCommunityLeft.d.ts +1 -1
  58. package/dist/communityRepository/communityMembership/events/onCommunityLeft.d.ts.map +1 -1
  59. package/dist/communityRepository/communityMembership/events/onCommunityUserAdded.d.ts +1 -1
  60. package/dist/communityRepository/communityMembership/events/onCommunityUserAdded.d.ts.map +1 -1
  61. package/dist/communityRepository/communityMembership/events/onCommunityUserBanned.d.ts +1 -1
  62. package/dist/communityRepository/communityMembership/events/onCommunityUserBanned.d.ts.map +1 -1
  63. package/dist/communityRepository/communityMembership/events/onCommunityUserChanged.d.ts +1 -1
  64. package/dist/communityRepository/communityMembership/events/onCommunityUserChanged.d.ts.map +1 -1
  65. package/dist/communityRepository/communityMembership/events/onCommunityUserRemoved.d.ts +1 -1
  66. package/dist/communityRepository/communityMembership/events/onCommunityUserRemoved.d.ts.map +1 -1
  67. package/dist/communityRepository/communityMembership/events/onCommunityUserRoleAdded.d.ts +1 -1
  68. package/dist/communityRepository/communityMembership/events/onCommunityUserRoleAdded.d.ts.map +1 -1
  69. package/dist/communityRepository/communityMembership/events/onCommunityUserRoleRemoved.d.ts +1 -1
  70. package/dist/communityRepository/communityMembership/events/onCommunityUserRoleRemoved.d.ts.map +1 -1
  71. package/dist/communityRepository/communityMembership/events/onCommunityUserUnbanned.d.ts +1 -1
  72. package/dist/communityRepository/communityMembership/events/onCommunityUserUnbanned.d.ts.map +1 -1
  73. package/dist/communityRepository/communityMembership/events/onLocalCommunityJoin.d.ts +2 -0
  74. package/dist/communityRepository/communityMembership/events/onLocalCommunityJoin.d.ts.map +1 -0
  75. package/dist/communityRepository/communityMembership/events/onLocalCommunityJoined.d.ts +1 -1
  76. package/dist/communityRepository/communityMembership/events/onLocalCommunityJoined.d.ts.map +1 -1
  77. package/dist/communityRepository/communityMembership/events/onLocalCommunityLeft.d.ts +1 -1
  78. package/dist/communityRepository/communityMembership/events/onLocalCommunityLeft.d.ts.map +1 -1
  79. package/dist/communityRepository/communityMembership/events/onLocalCommunityUserAdded.d.ts +1 -1
  80. package/dist/communityRepository/communityMembership/events/onLocalCommunityUserAdded.d.ts.map +1 -1
  81. package/dist/communityRepository/communityMembership/events/onLocalCommunityUserRemoved.d.ts +1 -1
  82. package/dist/communityRepository/communityMembership/events/onLocalCommunityUserRemoved.d.ts.map +1 -1
  83. package/dist/communityRepository/communityMembership/events/onUserDeleted.d.ts +1 -1
  84. package/dist/communityRepository/communityMembership/events/onUserDeleted.d.ts.map +1 -1
  85. package/dist/communityRepository/communityMembership/events/utils.d.ts +2 -2
  86. package/dist/communityRepository/communityMembership/events/utils.d.ts.map +1 -1
  87. package/dist/communityRepository/communityMembership/observers/getMembers/CommunityMembersQueryStreamController.d.ts +2 -2
  88. package/dist/communityRepository/communityMembership/observers/getMembers/CommunityMembersQueryStreamController.d.ts.map +1 -1
  89. package/dist/communityRepository/communityMembership/observers/getMembers/enums.d.ts +2 -1
  90. package/dist/communityRepository/communityMembership/observers/getMembers/enums.d.ts.map +1 -1
  91. package/dist/communityRepository/communityMembership/observers/searchMembers/SearchCommunityMembersQueryStreamController.d.ts +2 -2
  92. package/dist/communityRepository/communityMembership/observers/searchMembers/SearchCommunityMembersQueryStreamController.d.ts.map +1 -1
  93. package/dist/communityRepository/communityMembership/observers/searchMembers/enums.d.ts +1 -0
  94. package/dist/communityRepository/communityMembership/observers/searchMembers/enums.d.ts.map +1 -1
  95. package/dist/communityRepository/communityModeration/events/onLocalCommunityRoleAdded.d.ts +1 -1
  96. package/dist/communityRepository/communityModeration/events/onLocalCommunityRoleAdded.d.ts.map +1 -1
  97. package/dist/communityRepository/communityModeration/events/onLocalCommunityRoleRemoved.d.ts +1 -1
  98. package/dist/communityRepository/communityModeration/events/onLocalCommunityRoleRemoved.d.ts.map +1 -1
  99. package/dist/communityRepository/events/onCommunityCreated.d.ts +1 -1
  100. package/dist/communityRepository/events/onCommunityCreated.d.ts.map +1 -1
  101. package/dist/communityRepository/events/onCommunityDeleted.d.ts +1 -1
  102. package/dist/communityRepository/events/onCommunityDeleted.d.ts.map +1 -1
  103. package/dist/communityRepository/events/onCommunityUpdated.d.ts +1 -1
  104. package/dist/communityRepository/events/onCommunityUpdated.d.ts.map +1 -1
  105. package/dist/communityRepository/events/utils.d.ts +1 -1
  106. package/dist/communityRepository/events/utils.d.ts.map +1 -1
  107. package/dist/communityRepository/internalAPI/getMyJoinRequest.d.ts +16 -0
  108. package/dist/communityRepository/internalAPI/getMyJoinRequest.d.ts.map +1 -0
  109. package/dist/communityRepository/internalAPI/joinCommunity.d.ts +16 -0
  110. package/dist/communityRepository/internalAPI/joinCommunity.d.ts.map +1 -0
  111. package/dist/communityRepository/joinRequest/events/index.d.ts +4 -0
  112. package/dist/communityRepository/joinRequest/events/index.d.ts.map +1 -0
  113. package/dist/communityRepository/joinRequest/events/onJoinRequestCreated.d.ts +17 -0
  114. package/dist/communityRepository/joinRequest/events/onJoinRequestCreated.d.ts.map +1 -0
  115. package/dist/communityRepository/joinRequest/events/onJoinRequestDeleted.d.ts +17 -0
  116. package/dist/communityRepository/joinRequest/events/onJoinRequestDeleted.d.ts.map +1 -0
  117. package/dist/communityRepository/joinRequest/events/onJoinRequestUpdated.d.ts +17 -0
  118. package/dist/communityRepository/joinRequest/events/onJoinRequestUpdated.d.ts.map +1 -0
  119. package/dist/communityRepository/joinRequest/internalAPI/approveJoinRequest.d.ts +16 -0
  120. package/dist/communityRepository/joinRequest/internalAPI/approveJoinRequest.d.ts.map +1 -0
  121. package/dist/communityRepository/joinRequest/internalAPI/cancelJoinRequest.d.ts +16 -0
  122. package/dist/communityRepository/joinRequest/internalAPI/cancelJoinRequest.d.ts.map +1 -0
  123. package/dist/communityRepository/joinRequest/internalAPI/rejectJoinRequest.d.ts +16 -0
  124. package/dist/communityRepository/joinRequest/internalAPI/rejectJoinRequest.d.ts.map +1 -0
  125. package/dist/communityRepository/observers/getCommunities/CommunitiesLiveCollectionController.d.ts.map +1 -1
  126. package/dist/communityRepository/observers/getCommunities/CommunitiesPaginationController.d.ts.map +1 -1
  127. package/dist/communityRepository/observers/getCommunities/CommunitiesQueryStreamController.d.ts +2 -2
  128. package/dist/communityRepository/observers/getCommunities/CommunitiesQueryStreamController.d.ts.map +1 -1
  129. package/dist/communityRepository/observers/getCommunity.d.ts.map +1 -1
  130. package/dist/communityRepository/observers/getJoinRequestList/JoinRequestListLiveCollectionController.d.ts +14 -0
  131. package/dist/communityRepository/observers/getJoinRequestList/JoinRequestListLiveCollectionController.d.ts.map +1 -0
  132. package/dist/communityRepository/observers/getJoinRequestList/JoinRequestListPaginationController.d.ts +9 -0
  133. package/dist/communityRepository/observers/getJoinRequestList/JoinRequestListPaginationController.d.ts.map +1 -0
  134. package/dist/communityRepository/observers/getJoinRequestList/JoinRequestListQueryStreamController.d.ts +15 -0
  135. package/dist/communityRepository/observers/getJoinRequestList/JoinRequestListQueryStreamController.d.ts.map +1 -0
  136. package/dist/communityRepository/observers/getJoinRequestList/enum.d.ts +6 -0
  137. package/dist/communityRepository/observers/getJoinRequestList/enum.d.ts.map +1 -0
  138. package/dist/communityRepository/observers/getJoinRequestList.d.ts +12 -0
  139. package/dist/communityRepository/observers/getJoinRequestList.d.ts.map +1 -0
  140. package/dist/communityRepository/observers/getJoinRequests/JoinRequestsLiveCollectionController.d.ts +14 -0
  141. package/dist/communityRepository/observers/getJoinRequests/JoinRequestsLiveCollectionController.d.ts.map +1 -0
  142. package/dist/communityRepository/observers/getJoinRequests/JoinRequestsPaginationController.d.ts +9 -0
  143. package/dist/communityRepository/observers/getJoinRequests/JoinRequestsPaginationController.d.ts.map +1 -0
  144. package/dist/communityRepository/observers/getJoinRequests/JoinRequestsQueryStreamController.d.ts +15 -0
  145. package/dist/communityRepository/observers/getJoinRequests/JoinRequestsQueryStreamController.d.ts.map +1 -0
  146. package/dist/communityRepository/observers/getJoinRequests/enum.d.ts +6 -0
  147. package/dist/communityRepository/observers/getJoinRequests/enum.d.ts.map +1 -0
  148. package/dist/communityRepository/observers/getJoinRequests.d.ts +12 -0
  149. package/dist/communityRepository/observers/getJoinRequests.d.ts.map +1 -0
  150. package/dist/communityRepository/observers/getRecommendedCommunities/RecommendedCommunitiesLiveCollectionController.d.ts.map +1 -1
  151. package/dist/communityRepository/observers/getRecommendedCommunities/RecommendedCommunitiesPaginationController.d.ts.map +1 -1
  152. package/dist/communityRepository/observers/getRecommendedCommunities/RecommendedCommunitiesQueryStreamController.d.ts +2 -2
  153. package/dist/communityRepository/observers/getRecommendedCommunities/RecommendedCommunitiesQueryStreamController.d.ts.map +1 -1
  154. package/dist/communityRepository/observers/getRecommendedCommunities/enums.d.ts +2 -1
  155. package/dist/communityRepository/observers/getRecommendedCommunities/enums.d.ts.map +1 -1
  156. package/dist/communityRepository/observers/getTrendingCommunities/TrendingCommunitiesLiveCollectionController.d.ts.map +1 -1
  157. package/dist/communityRepository/observers/getTrendingCommunities/TrendingCommunitiesPaginationController.d.ts.map +1 -1
  158. package/dist/communityRepository/observers/getTrendingCommunities/TrendingCommunitiesQueryStreamController.d.ts +2 -2
  159. package/dist/communityRepository/observers/getTrendingCommunities/TrendingCommunitiesQueryStreamController.d.ts.map +1 -1
  160. package/dist/communityRepository/observers/index.d.ts +1 -0
  161. package/dist/communityRepository/observers/index.d.ts.map +1 -1
  162. package/dist/communityRepository/observers/searchCommunities/SearchCommunitiesLiveCollectionController.d.ts.map +1 -1
  163. package/dist/communityRepository/observers/searchCommunities/SearchCommunitiesPaginationController.d.ts.map +1 -1
  164. package/dist/communityRepository/observers/searchCommunities/SearchCommunitiesQueryStreamController.d.ts +2 -2
  165. package/dist/communityRepository/observers/searchCommunities/SearchCommunitiesQueryStreamController.d.ts.map +1 -1
  166. package/dist/communityRepository/observers/semanticSearch/SemanticSearchCommunityLiveCollectionController.d.ts.map +1 -1
  167. package/dist/communityRepository/observers/semanticSearch/SemanticSearchCommunityPaginationController.d.ts.map +1 -1
  168. package/dist/communityRepository/observers/semanticSearch/SemanticSearchCommunityQueryStreamController.d.ts +2 -2
  169. package/dist/communityRepository/observers/semanticSearch/SemanticSearchCommunityQueryStreamController.d.ts.map +1 -1
  170. package/dist/communityRepository/utils/communityWithMembership.d.ts +1 -1
  171. package/dist/communityRepository/utils/communityWithMembership.d.ts.map +1 -1
  172. package/dist/communityRepository/utils/payload.d.ts +2 -1
  173. package/dist/communityRepository/utils/payload.d.ts.map +1 -1
  174. package/dist/core/events.d.ts +3 -3
  175. package/dist/core/events.d.ts.map +1 -1
  176. package/dist/core/model/idResolvers.d.ts.map +1 -1
  177. package/dist/core/model/index.d.ts.map +1 -1
  178. package/dist/index.cjs.js +3209 -1543
  179. package/dist/index.d.ts +1 -0
  180. package/dist/index.d.ts.map +1 -1
  181. package/dist/index.esm.js +3374 -1710
  182. package/dist/index.umd.js +3 -3
  183. package/dist/invitationRepository/events/index.d.ts +4 -0
  184. package/dist/invitationRepository/events/index.d.ts.map +1 -0
  185. package/dist/invitationRepository/events/onLocalInvitationCreated.d.ts +17 -0
  186. package/dist/invitationRepository/events/onLocalInvitationCreated.d.ts.map +1 -0
  187. package/dist/invitationRepository/events/onLocalInvitationDeleted.d.ts +17 -0
  188. package/dist/invitationRepository/events/onLocalInvitationDeleted.d.ts.map +1 -0
  189. package/dist/invitationRepository/events/onLocalInvitationUpdated.d.ts +17 -0
  190. package/dist/invitationRepository/events/onLocalInvitationUpdated.d.ts.map +1 -0
  191. package/dist/invitationRepository/index.d.ts +3 -0
  192. package/dist/invitationRepository/index.d.ts.map +1 -0
  193. package/dist/invitationRepository/internalApi/acceptInvitation.d.ts +16 -0
  194. package/dist/invitationRepository/internalApi/acceptInvitation.d.ts.map +1 -0
  195. package/dist/invitationRepository/internalApi/createInvitations.d.ts +21 -0
  196. package/dist/invitationRepository/internalApi/createInvitations.d.ts.map +1 -0
  197. package/dist/invitationRepository/internalApi/getInvitation.d.ts +17 -0
  198. package/dist/invitationRepository/internalApi/getInvitation.d.ts.map +1 -0
  199. package/dist/invitationRepository/internalApi/index.d.ts +4 -0
  200. package/dist/invitationRepository/internalApi/index.d.ts.map +1 -0
  201. package/dist/invitationRepository/internalApi/rejectInvitation.d.ts +16 -0
  202. package/dist/invitationRepository/internalApi/rejectInvitation.d.ts.map +1 -0
  203. package/dist/invitationRepository/observers/getInvitations/InvitationsLiveCollectionController.d.ts +14 -0
  204. package/dist/invitationRepository/observers/getInvitations/InvitationsLiveCollectionController.d.ts.map +1 -0
  205. package/dist/invitationRepository/observers/getInvitations/InvitationsPaginationController.d.ts +5 -0
  206. package/dist/invitationRepository/observers/getInvitations/InvitationsPaginationController.d.ts.map +1 -0
  207. package/dist/invitationRepository/observers/getInvitations/InvitationsQueryStreamController.d.ts +15 -0
  208. package/dist/invitationRepository/observers/getInvitations/InvitationsQueryStreamController.d.ts.map +1 -0
  209. package/dist/invitationRepository/observers/getInvitations/enums.d.ts +6 -0
  210. package/dist/invitationRepository/observers/getInvitations/enums.d.ts.map +1 -0
  211. package/dist/invitationRepository/observers/getInvitations.d.ts +12 -0
  212. package/dist/invitationRepository/observers/getInvitations.d.ts.map +1 -0
  213. package/dist/invitationRepository/observers/getMyCommunityInvitations.d.ts +12 -0
  214. package/dist/invitationRepository/observers/getMyCommunityInvitations.d.ts.map +1 -0
  215. package/dist/invitationRepository/observers/getMyInvitations/MyInvitationsLiveCollectionController.d.ts +14 -0
  216. package/dist/invitationRepository/observers/getMyInvitations/MyInvitationsLiveCollectionController.d.ts.map +1 -0
  217. package/dist/invitationRepository/observers/getMyInvitations/MyInvitationsPaginationController.d.ts +5 -0
  218. package/dist/invitationRepository/observers/getMyInvitations/MyInvitationsPaginationController.d.ts.map +1 -0
  219. package/dist/invitationRepository/observers/getMyInvitations/MyInvitationsQueryStreamController.d.ts +15 -0
  220. package/dist/invitationRepository/observers/getMyInvitations/MyInvitationsQueryStreamController.d.ts.map +1 -0
  221. package/dist/invitationRepository/observers/index.d.ts +2 -0
  222. package/dist/invitationRepository/observers/index.d.ts.map +1 -0
  223. package/dist/invitationRepository/utils/convertRawInvitationToInternalInvitation.d.ts +2 -0
  224. package/dist/invitationRepository/utils/convertRawInvitationToInternalInvitation.d.ts.map +1 -0
  225. package/dist/invitationRepository/utils/index.d.ts +2 -0
  226. package/dist/invitationRepository/utils/index.d.ts.map +1 -0
  227. package/dist/invitationRepository/utils/prepareInvitationPayload.d.ts +2 -0
  228. package/dist/invitationRepository/utils/prepareInvitationPayload.d.ts.map +1 -0
  229. package/dist/invitationRepository/utils/prepareMyInvitationsPayload.d.ts +2 -0
  230. package/dist/invitationRepository/utils/prepareMyInvitationsPayload.d.ts.map +1 -0
  231. package/dist/messagePreview/utils/getSubChannelMessagePreviewWithUser.d.ts +1 -1
  232. package/dist/postRepository/observers/getGlobalPinnedPosts/GlobalPinnedPostQueryStreamController.d.ts.map +1 -1
  233. package/dist/postRepository/observers/getPinnedPosts/PinnedPostQueryStreamController.d.ts.map +1 -1
  234. package/dist/subChannelRepository/utils/prepareSubChannelPayload.d.ts.map +1 -1
  235. package/dist/utils/linkedObject/channelLinkedObject.d.ts.map +1 -1
  236. package/dist/utils/linkedObject/channelMemberLinkedObject.d.ts +2 -0
  237. package/dist/utils/linkedObject/channelMemberLinkedObject.d.ts.map +1 -0
  238. package/dist/utils/linkedObject/communityLinkedObject.d.ts +2 -0
  239. package/dist/utils/linkedObject/communityLinkedObject.d.ts.map +1 -0
  240. package/dist/utils/linkedObject/index.d.ts +4 -0
  241. package/dist/utils/linkedObject/index.d.ts.map +1 -1
  242. package/dist/utils/linkedObject/invitationLinkedObject.d.ts +2 -0
  243. package/dist/utils/linkedObject/invitationLinkedObject.d.ts.map +1 -0
  244. package/dist/utils/linkedObject/joinRequestLinkedObject.d.ts +2 -0
  245. package/dist/utils/linkedObject/joinRequestLinkedObject.d.ts.map +1 -0
  246. package/dist/utils/tests/dummy/comment.d.ts +1 -1
  247. package/dist/utils/tests/dummy/community.d.ts +2 -0
  248. package/dist/utils/tests/dummy/community.d.ts.map +1 -1
  249. package/dist/utils/tests/dummy/post.d.ts +3 -3
  250. package/package.json +2 -1
  251. package/src/@types/core/events.ts +10 -0
  252. package/src/@types/core/model.ts +8 -1
  253. package/src/@types/core/payload.ts +48 -5
  254. package/src/@types/domains/channel.ts +1 -0
  255. package/src/@types/domains/client.ts +12 -0
  256. package/src/@types/domains/community.ts +82 -3
  257. package/src/@types/domains/content.ts +15 -1
  258. package/src/@types/domains/group.ts +2 -0
  259. package/src/@types/domains/invitation.ts +119 -0
  260. package/src/@types/domains/joinRequest.ts +66 -0
  261. package/src/@types/domains/notification.ts +2 -0
  262. package/src/@types/domains/pinnedPost.ts +1 -1
  263. package/src/@types/index.ts +5 -0
  264. package/src/channelRepository/channelMembership/observers/getMembers/ChannelMemberLiveCollectionController.ts +3 -1
  265. package/src/channelRepository/channelMembership/observers/searchMembers/SearchChannelMemberLiveCollectionController.ts +2 -1
  266. package/src/channelRepository/channelMembership/observers/searchMembers/SearchChannelMemberQueryStreamController.ts +2 -2
  267. package/src/client/api/index.ts +1 -0
  268. package/src/client/api/resumeSession.ts +282 -0
  269. package/src/client/api/tests/resumeSession.test.ts +173 -0
  270. package/src/communityRepository/api/createCommunity.ts +6 -3
  271. package/src/communityRepository/api/deleteCommunity.ts +2 -1
  272. package/src/communityRepository/api/getCommunities.ts +9 -2
  273. package/src/communityRepository/api/getCommunity.ts +12 -3
  274. package/src/communityRepository/api/getRecommendedCommunities.ts +11 -4
  275. package/src/communityRepository/api/getTrendingCommunities.ts +11 -4
  276. package/src/communityRepository/api/joinCommunity.ts +4 -1
  277. package/src/communityRepository/api/queryCommunities.ts +7 -1
  278. package/src/communityRepository/api/updateCommunity.ts +14 -4
  279. package/src/communityRepository/communityMembership/events/index.ts +1 -0
  280. package/src/communityRepository/communityMembership/events/onCommunityJoined.ts +1 -1
  281. package/src/communityRepository/communityMembership/events/onCommunityLeft.ts +1 -1
  282. package/src/communityRepository/communityMembership/events/onCommunityUserAdded.ts +1 -1
  283. package/src/communityRepository/communityMembership/events/onCommunityUserBanned.ts +1 -1
  284. package/src/communityRepository/communityMembership/events/onCommunityUserChanged.ts +1 -1
  285. package/src/communityRepository/communityMembership/events/onCommunityUserRemoved.ts +1 -1
  286. package/src/communityRepository/communityMembership/events/onCommunityUserRoleAdded.ts +1 -1
  287. package/src/communityRepository/communityMembership/events/onCommunityUserRoleRemoved.ts +1 -1
  288. package/src/communityRepository/communityMembership/events/onCommunityUserUnbanned.ts +1 -1
  289. package/src/communityRepository/communityMembership/events/onLocalCommunityJoin.ts +20 -0
  290. package/src/communityRepository/communityMembership/events/onLocalCommunityJoined.ts +1 -1
  291. package/src/communityRepository/communityMembership/events/onLocalCommunityLeft.ts +1 -1
  292. package/src/communityRepository/communityMembership/events/onLocalCommunityUserAdded.ts +1 -1
  293. package/src/communityRepository/communityMembership/events/onLocalCommunityUserRemoved.ts +1 -1
  294. package/src/communityRepository/communityMembership/events/onUserDeleted.ts +3 -1
  295. package/src/communityRepository/communityMembership/events/utils.ts +2 -2
  296. package/src/communityRepository/communityMembership/observers/getMembers/CommunityMembersQueryStreamController.ts +8 -2
  297. package/src/communityRepository/communityMembership/observers/getMembers/enums.ts +1 -0
  298. package/src/communityRepository/communityMembership/observers/searchMembers/SearchCommunityMembersQueryStreamController.ts +8 -2
  299. package/src/communityRepository/communityMembership/observers/searchMembers/enums.ts +1 -0
  300. package/src/communityRepository/communityModeration/events/onLocalCommunityRoleAdded.ts +1 -1
  301. package/src/communityRepository/communityModeration/events/onLocalCommunityRoleRemoved.ts +1 -1
  302. package/src/communityRepository/events/onCommunityCreated.ts +1 -1
  303. package/src/communityRepository/events/onCommunityDeleted.ts +1 -1
  304. package/src/communityRepository/events/onCommunityUpdated.ts +1 -1
  305. package/src/communityRepository/events/utils.ts +1 -1
  306. package/src/communityRepository/internalAPI/getMyJoinRequest.ts +43 -0
  307. package/src/communityRepository/internalAPI/joinCommunity.ts +66 -0
  308. package/src/communityRepository/joinRequest/events/index.ts +3 -0
  309. package/src/communityRepository/joinRequest/events/onJoinRequestCreated.ts +33 -0
  310. package/src/communityRepository/joinRequest/events/onJoinRequestDeleted.ts +33 -0
  311. package/src/communityRepository/joinRequest/events/onJoinRequestUpdated.ts +33 -0
  312. package/src/communityRepository/joinRequest/internalAPI/approveJoinRequest.ts +52 -0
  313. package/src/communityRepository/joinRequest/internalAPI/cancelJoinRequest.ts +49 -0
  314. package/src/communityRepository/joinRequest/internalAPI/rejectJoinRequest.ts +52 -0
  315. package/src/communityRepository/observers/getCommunities/CommunitiesLiveCollectionController.ts +6 -0
  316. package/src/communityRepository/observers/getCommunities/CommunitiesPaginationController.ts +1 -0
  317. package/src/communityRepository/observers/getCommunities/CommunitiesQueryStreamController.ts +2 -2
  318. package/src/communityRepository/observers/getCommunity.ts +26 -11
  319. package/src/communityRepository/observers/getJoinRequestList/JoinRequestListLiveCollectionController.ts +135 -0
  320. package/src/communityRepository/observers/getJoinRequestList/JoinRequestListPaginationController.ts +30 -0
  321. package/src/communityRepository/observers/getJoinRequestList/JoinRequestListQueryStreamController.ts +116 -0
  322. package/src/communityRepository/observers/getJoinRequestList/enum.ts +5 -0
  323. package/src/communityRepository/observers/getJoinRequestList.ts +51 -0
  324. package/src/communityRepository/observers/getJoinRequests/JoinRequestsLiveCollectionController.ts +126 -0
  325. package/src/communityRepository/observers/getJoinRequests/JoinRequestsPaginationController.ts +25 -0
  326. package/src/communityRepository/observers/getJoinRequests/JoinRequestsQueryStreamController.ts +108 -0
  327. package/src/communityRepository/observers/getJoinRequests/enum.ts +5 -0
  328. package/src/communityRepository/observers/getJoinRequests.ts +44 -0
  329. package/src/communityRepository/observers/getRecommendedCommunities/RecommendedCommunitiesLiveCollectionController.ts +8 -1
  330. package/src/communityRepository/observers/getRecommendedCommunities/RecommendedCommunitiesPaginationController.ts +6 -1
  331. package/src/communityRepository/observers/getRecommendedCommunities/RecommendedCommunitiesQueryStreamController.ts +2 -2
  332. package/src/communityRepository/observers/getRecommendedCommunities/enums.ts +1 -0
  333. package/src/communityRepository/observers/getTrendingCommunities/TrendingCommunitiesLiveCollectionController.ts +9 -1
  334. package/src/communityRepository/observers/getTrendingCommunities/TrendingCommunitiesPaginationController.ts +6 -1
  335. package/src/communityRepository/observers/getTrendingCommunities/TrendingCommunitiesQueryStreamController.ts +2 -2
  336. package/src/communityRepository/observers/index.ts +1 -0
  337. package/src/communityRepository/observers/searchCommunities/SearchCommunitiesLiveCollectionController.ts +6 -0
  338. package/src/communityRepository/observers/searchCommunities/SearchCommunitiesPaginationController.ts +1 -0
  339. package/src/communityRepository/observers/searchCommunities/SearchCommunitiesQueryStreamController.ts +2 -2
  340. package/src/communityRepository/observers/semanticSearch/SemanticSearchCommunityLiveCollectionController.ts +6 -0
  341. package/src/communityRepository/observers/semanticSearch/SemanticSearchCommunityPaginationController.ts +1 -0
  342. package/src/communityRepository/observers/semanticSearch/SemanticSearchCommunityQueryStreamController.ts +2 -2
  343. package/src/communityRepository/utils/communityWithMembership.ts +9 -5
  344. package/src/communityRepository/utils/payload.ts +28 -2
  345. package/src/core/liveCollection/PaginationController.ts +1 -1
  346. package/src/core/liveCollection/PaginationNoPageController.ts +1 -1
  347. package/src/core/model/idResolvers.ts +3 -0
  348. package/src/core/model/index.ts +3 -0
  349. package/src/index.ts +2 -0
  350. package/src/invitationRepository/events/index.ts +3 -0
  351. package/src/invitationRepository/events/onLocalInvitationCreated.ts +33 -0
  352. package/src/invitationRepository/events/onLocalInvitationDeleted.ts +33 -0
  353. package/src/invitationRepository/events/onLocalInvitationUpdated.ts +33 -0
  354. package/src/invitationRepository/index.ts +2 -0
  355. package/src/invitationRepository/internalApi/acceptInvitation.ts +45 -0
  356. package/src/invitationRepository/internalApi/createInvitations.ts +52 -0
  357. package/src/invitationRepository/internalApi/getInvitation.ts +47 -0
  358. package/src/invitationRepository/internalApi/index.ts +3 -0
  359. package/src/invitationRepository/internalApi/rejectInvitation.ts +45 -0
  360. package/src/invitationRepository/observers/getInvitations/InvitationsLiveCollectionController.ts +148 -0
  361. package/src/invitationRepository/observers/getInvitations/InvitationsPaginationController.ts +19 -0
  362. package/src/invitationRepository/observers/getInvitations/InvitationsQueryStreamController.ts +97 -0
  363. package/src/invitationRepository/observers/getInvitations/enums.ts +5 -0
  364. package/src/invitationRepository/observers/getInvitations.ts +44 -0
  365. package/src/invitationRepository/observers/getMyCommunityInvitations.ts +48 -0
  366. package/src/invitationRepository/observers/getMyInvitations/MyInvitationsLiveCollectionController.ts +148 -0
  367. package/src/invitationRepository/observers/getMyInvitations/MyInvitationsPaginationController.ts +22 -0
  368. package/src/invitationRepository/observers/getMyInvitations/MyInvitationsQueryStreamController.ts +105 -0
  369. package/src/invitationRepository/observers/index.ts +1 -0
  370. package/src/invitationRepository/utils/convertRawInvitationToInternalInvitation.ts +8 -0
  371. package/src/invitationRepository/utils/index.ts +1 -0
  372. package/src/invitationRepository/utils/prepareInvitationPayload.ts +12 -0
  373. package/src/invitationRepository/utils/prepareMyInvitationsPayload.ts +12 -0
  374. package/src/messagePreview/utils/getChannelMessagePreviewWithUser.ts +3 -3
  375. package/src/postRepository/observers/getGlobalPinnedPosts/GlobalPinnedPostQueryStreamController.ts +7 -1
  376. package/src/postRepository/observers/getPinnedPosts/PinnedPostQueryStreamController.ts +7 -1
  377. package/src/subChannelRepository/utils/prepareSubChannelPayload.ts +4 -0
  378. package/src/utils/linkedObject/channelLinkedObject.ts +19 -0
  379. package/src/utils/linkedObject/channelMemberLinkedObject.ts +20 -0
  380. package/src/utils/linkedObject/communityLinkedObject.ts +57 -0
  381. package/src/utils/linkedObject/index.ts +8 -0
  382. package/src/utils/linkedObject/invitationLinkedObject.ts +37 -0
  383. package/src/utils/linkedObject/joinRequestLinkedObject.ts +31 -0
package/dist/index.umd.js CHANGED
@@ -1,5 +1,5 @@
1
- var Amity=function(e,t,n,r,s,a,o,i,c,l,d,u){"use strict";function h(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var p=h(n),f=h(r),m=h(s),g=h(a),y=h(o),v=h(i),b=h(c),w=h(d),C=h(u);const I=Object.freeze({FILE:"file",IMAGE:"image",VIDEO:"video"}),S=Object.freeze({"1080P":"1080p","720P":"720p","480P":"480p","360P":"360p",ORIGINAL:"original"}),_=Object.freeze({UPLOADED:"uploaded",TRANSCODING:"transcoding",TRANSCODED:"transcoded",TRANSCODE_FAILED:"transcodeFailed"}),k=Object.freeze({LOW:"low",MEDIUM:"medium",HIGH:"high",ORIGINAL:"original"});var T;e.FileAccessTypeEnum=void 0,(T=e.FileAccessTypeEnum||(e.FileAccessTypeEnum={})).PUBLIC="public",T.NETWORK="network";const O=Object.freeze({ONLY_ADMIN_CAN_POST:"ONLY_ADMIN_CAN_POST",ADMIN_REVIEW_POST_REQUIRED:"ADMIN_REVIEW_POST_REQUIRED",ANYONE_CAN_POST:"ANYONE_CAN_POST"}),A=Object.freeze({ONLY_ADMIN_CAN_POST:{needApprovalOnPostCreation:!1,onlyAdminCanPost:!0},ADMIN_REVIEW_POST_REQUIRED:{needApprovalOnPostCreation:!0,onlyAdminCanPost:!1},ANYONE_CAN_POST:{needApprovalOnPostCreation:!1,onlyAdminCanPost:!1}}),E="ONLY_ADMIN_CAN_POST",M=Object.freeze({STORY:"story",CLIP:"clip",CHAT:"chat",POST:"post",MESSAGE:"message"});var R;e.ContentFlagReasonEnum=void 0,(R=e.ContentFlagReasonEnum||(e.ContentFlagReasonEnum={})).CommunityGuidelines="Against community guidelines",R.HarassmentOrBullying="Harassment or bullying",R.SelfHarmOrSuicide="Self-harm or suicide",R.ViolenceOrThreateningContent="Violence or threatening content",R.SellingRestrictedItems="Selling and promoting restricted items",R.SexualContentOrNudity="Sexual message or nudity",R.SpamOrScams="Spam or scams",R.FalseInformation="False information or misinformation",R.Others="Others";const P=Object.freeze({TEXT:"text",IMAGE:"image",FILE:"file",VIDEO:"video",AUDIO:"audio",CUSTOM:"custom"}),j=Object.freeze({TEXT:"text",IMAGE:"image",FILE:"file",VIDEO:"video",LIVESTREAM:"liveStream",POLL:"poll"});const U=function(){try{return"v7.5.3-umd"}catch(e){return"__dev__"}}(),x=5,D="cache_then_server",N="For using Live Collection feature you need to enable Cache!",B="Observing unsynced object is not supported by Live Object.",q=-5,F=1e3,L=6e5,K="dead",$=6e4,z=e=>JSON.stringify(e,((e,t)=>{return"object"==typeof t?(n=t,Object.keys(n).sort().reduce(((e,t)=>Object.assign(Object.assign({},e),{[t]:n[t]})),{})):t;var n})),Q=e=>JSON.parse(e),V=(e,t)=>e===t||!(!e||!t)&&("object"==typeof e&&Object.keys(e).every((n=>V(e[n],t[n])))),H=e=>[400400,400300].includes(e),W=e=>["skip"].some((t=>t in e)),J=e=>["after","before","first","last","limit"].some((t=>t in e)),G=e=>"limit"in e,Y=e=>(null==e?void 0:e.hasOwnProperty("data"))&&(null==e?void 0:e.hasOwnProperty("nextPage"))&&(null==e?void 0:e.hasOwnProperty("prevPage")),Z=(e,n)=>{var r;if(!e||!Object.keys(e).length)return;let s={};return"skiplimit"===n?s={skip:null!==(r=e.after)&&void 0!==r?r:0,limit:e.limit}:"afterbefore"===n&&J(e)?((null==e?void 0:e.before)&&(s=Object.assign(Object.assign({},s),{before:e.before})),(null==e?void 0:e.after)&&(s=Object.assign(Object.assign({},s),{after:e.after})),Number.isNaN(Number(null==e?void 0:e.limit))||(s=Object.assign(Object.assign({},s),{limit:e.limit}))):"afterbeforeraw"===n&&(s=e),Object.keys(s).length?t.encode(JSON.stringify(s)):void 0},X=e=>{if(!e)return;const n=JSON.parse(t.decode(e));if(W(n))return{after:n.skip,limit:n.limit};if(J(n)){if("before"in n)return{before:n.before,limit:n.last};if("after"in n)return{after:n.after,limit:n.first}}},ee=e=>"locally"in e,te=e=>"optimistically"in e,ne=e=>ee(e)||te(e),re=e=>null==e?void 0:e.hasOwnProperty("cachedAt"),se=(e,t=6e4)=>{var n;return Date.now()-(null!==(n=null==e?void 0:e.cachedAt)&&void 0!==n?n:0)<=t},ae=(e,...t)=>({func:e,args:t}),oe=(e,t=6e4)=>"cache_only"===e?{lifeSpan:1/0}:{lifeSpan:t<$?$:t},ie=({func:e,args:t},n,r=oe("cache_then_server"))=>{let s;const{lifeSpan:a}=oe("cache_then_server",r.lifeSpan);if(ne(e)){try{s=te(e)?e.optimistically(...t):e.locally(...t)}catch(e){null==n||n(ce(void 0,{origin:"local",loading:!1,error:e}))}const r=re(s)&&se(s,a);if(null==n||n(ce(s,{origin:"local",loading:!(ee(e)&&r)})),r)return}else null==n||n(ce(void 0,{origin:"local",loading:!0}));e(...t).then((e=>{null==n||n(ce(e,{origin:"server",loading:!1}))})).catch((e=>{null==n||n(ce(void 0,{origin:"server",loading:!1,error:e}))}))};function ce(e,t){return Y(e)||re(e)?Object.assign(Object.assign({},t),e):Object.assign(Object.assign({},t),{data:e})}const le={user:({userId:e})=>e,file:({fileId:e})=>e,role:({roleId:e})=>e,channel:({channelInternalId:e})=>e,subChannel:({subChannelId:e})=>e,channelUsers:({channelId:e,userId:t})=>`${e}#${t}`,message:({messageId:e,referenceId:t})=>null!=t?t:e,messagePreviewChannel:({channelId:e})=>`${e}`,messagePreviewSubChannel:({subChannelId:e})=>`${e}`,channelUnreadInfo:({channelId:e})=>e,subChannelUnreadInfo:({subChannelId:e})=>e,channelUnread:({channelId:e})=>e,channelMarker:({entityId:e,userId:t})=>`${e}#${t}`,subChannelMarker:({entityId:e,feedId:t,userId:n})=>`${e}#${t}#${n}`,messageMarker:({feedId:e,contentId:t,creatorId:n})=>`${e}#${t}#${n}`,feedMarker:({feedId:e,entityId:t})=>`${e}#${t}`,userMarker:({userId:e})=>e,community:({communityId:e})=>e,category:({categoryId:e})=>e,communityUsers:({communityId:e,userId:t})=>`${e}#${t}`,post:({postId:e})=>e,comment:({commentId:e})=>e,commentChildren:({commentId:e})=>e,poll:({pollId:e})=>e,reaction:({referenceType:e,referenceId:t})=>`${e}#${t}`,reactor:({reactionId:e})=>e,stream:({streamId:e})=>e,streamModeration:({streamId:e})=>e,follow:({from:e,to:t})=>`${e}#${t}`,followInfo:({userId:e})=>e,followCount:({userId:e})=>e,feed:({targetId:e,feedId:t})=>`${e}#${t}`,story:({referenceId:e})=>e,storyTarget:({targetId:e})=>e,ad:({adId:e})=>e,advertiser:({advertiserId:e})=>e,pin:({placement:e,referenceId:t})=>`${e}#${t}`,pinTarget:({targetId:e})=>e,notificationTrayItem:({_id:e})=>e,notificationTraySeen:({userId:e})=>e},de=e=>le[e],ue={users:"user",files:"file",roles:"role",stories:"story",storyTargets:"storyTarget",channels:"channel",messageFeeds:"subChannel",channelUsers:"channelUsers",messages:"message",messagePreviewChannel:"messagePreviewChannel",messagePreviewSubChannel:"messagePreviewSubChannel",channelUnreadInfo:"channelUnreadInfo",subChannelUnreadInfo:"subChannelUnreadInfo",userEntityMarkers:"channelMarker",userFeedMarkers:"subChannelMarker",contentMarkers:"messageMarker",feedMarkers:"feedMarker",userMarkers:"userMarker",communities:"community",categories:"category",communityUsers:"communityUsers",posts:"post",postChildren:"post",comments:"comment",commentChildren:"comment",polls:"poll",reactors:"reactor",reactions:"reaction",videoStreamings:"stream",videoStreamModerations:"streamModeration",follows:"follow",followCounts:"followCount",feeds:"feed",ads:"ad",advertisers:"advertiser",pinTargets:"pinTarget",pins:"pin",notificationTrayItems:"notificationTrayItem"};function he(e=(new Date).toISOString()){return new Date(new Date(e).getTime()+1).toISOString()}class pe extends Error{constructor(e,t,n){super(`Amity SDK (${t}): ${e}`),this.code=t,this.level=n,this.type="ASC",this.timestamp=Date.now(),Error.captureStackTrace&&Error.captureStackTrace(this,pe)}}class fe extends pe{constructor(e,t,n){super(e,t,n)}}class me extends pe{constructor(e=8e5,t="fatal"){super("Unexpected error",e,t)}}class ge extends pe{constructor(e,t="SDK client is having connection issues"){super(`${t} (${e})`,"disconnected"===e?800211:800210,"error"),this.event=e}}class ye extends pe{constructor(e){super(e,800110,"error")}}let ve=null;const be=()=>{if(!ve)throw new pe("There is no active client",8e5,"fatal");return ve},we=e=>{ve=e},Ce=e=>{const{log:t,cache:n}=be();if(n)return t("cache/api/queryCache",{key:e}),Object.keys(n.data).filter((t=>{const n=Q(t);return V(e,n)})).map((e=>n.data[e]))},Ie=e=>{const{log:t,cache:n}=be();if(!n)return;t("cache/api/pullFromCache",e);const r=z(e);return n.data[r]?n.data[r]:void 0},Se=(e,t,n={cachedAt:Date.now()})=>{const{log:r,cache:s}=be();if(!s)return!1;r("cache/api/pushToCache",{key:e,data:t,options:n}),!(null==n?void 0:n.hasOwnProperty("offline"))&&s.persistIf&&(n.offline=s.persistIf(e,t));const a=z(e);return s.data[a]=Object.assign({key:e,data:t},n),!0},_e=(e,t,n)=>{const{log:r,cache:s}=be();if(!s)return!1;r("cache/api/mergeInCache",{key:e,mutation:t});const a=Ie(e);if(!a)return!1;const o="function"==typeof t?t(a.data):Object.assign(Object.assign({},a.data),t);return i=a.data,!("updatedAt"in(c=o)&&"updatedAt"in c&&new Date(c.updatedAt)<new Date(i.updatedAt))&&(Se(e,o,n),!0);var i,c},ke=(e,t,n={cachedAt:Date.now()})=>{const{log:r,cache:s}=be();if(!s)return!1;r("cache/api/upsertInCache",{key:e,data:t,options:n});return Ie(e)?_e(e,t,n):Se(e,t,n)},Te=(e,t=!1)=>{const{log:n,cache:r}=be();if(!r)return!1;if(n("cache/api/dropFromCache",{key:e,exact:t}),!t)return Object.keys(r.data).map((e=>Q(e))).filter((t=>V(e,t))).map((e=>Te(e,!0))).every((e=>e));const s=z(e);return s in r.data&&(delete r.data[s],!0)},Oe=(e,t,n)=>void 0!==n?e.filter((e=>JSON.stringify(e[t])===JSON.stringify(n))):e,Ae=(e,t,n)=>void 0!==n?e.filter((e=>"string"==typeof e[t]&&"string"==typeof n&&String(e[t]).toLowerCase().match(n.toLowerCase()))):e,Ee=(e,t,n)=>(null==n?void 0:n.length)?e.filter((e=>Array.isArray(e[t])&&n.some((n=>e[t].includes(n))))):e,Me=(e,t,n)=>"all"===t?e:e.filter((e=>{var r;if("community"===e.type)return!0;const s=de("channelUsers")({channelId:e.channelPublicId,userId:n}),a=null===(r=Ie(["channelUsers","get",s]))||void 0===r?void 0:r.data;return"member"===t?a&&"none"!==a.membership:!a||"none"===a.membership})),Re=(e,t)=>e.filter((({targetId:e,feedId:n})=>{var r;const s=null===(r=Ie(["feed","get",de("feed")({targetId:e,feedId:n})]))||void 0===r?void 0:r.data;return s&&s.feedType===t})),Pe=(e,t,n)=>"all"===t?e:e.filter((e=>{var r;const s=de("communityUsers")({communityId:e.communityId,userId:n}),a=null===(r=Ie(["communityUsers","get",s]))||void 0===r?void 0:r.data;return"member"===t?a&&"member"===a.communityMembership:!a||"none"!==a.communityMembership})),je=(e,t)=>e.reduce(((e,n)=>{var r;if(null==t?void 0:t.includes(n.dataType))return[...e,n];if(((null==n?void 0:n.children)||[]).length>0){const s=null===(r=Ie(["post","get",n.children[0]]))||void 0===r?void 0:r.data;return(null==t?void 0:t.includes(null==s?void 0:s.dataType))?e:[...e,n]}return e}),[]),Ue=(e,t)=>{const n=new RegExp(t,"i");return e.filter((e=>{var t;return!!e.userId.match(n)||e.user&&(null===(t=e.user.displayName)||void 0===t?void 0:t.match(n))}))},xe=({displayName:e},{displayName:t})=>e&&t?e.localeCompare(t):e?-1:1,De=({name:e},{name:t})=>e&&t?e.localeCompare(t):e?-1:1,Ne=({createdAt:e},{createdAt:t})=>new Date(e).valueOf()-new Date(t).valueOf(),Be=({localSortingDate:e},{localSortingDate:t})=>new Date(t).getTime()-new Date(e).getTime(),qe=({createdAt:e},{createdAt:t})=>new Date(t).valueOf()-new Date(e).valueOf(),Fe=({updatedAt:e=0},{updatedAt:t=0})=>new Date(e).valueOf()-new Date(t).valueOf(),Le=({updatedAt:e=0},{updatedAt:t=0})=>new Date(t).valueOf()-new Date(e).valueOf(),Ke=({lastActivity:e},{lastActivity:t})=>new Date(t).valueOf()-new Date(e).valueOf();let $e=null;const ze=()=>{if(!$e)throw new pe("Connect client first",8e5,"fatal");return $e},Qe=e=>{$e={_id:e._id,userId:e.userId,path:e.path}};let Ve,He=[];const We=e=>{clearTimeout(Ve),He.push(e),Ve=setTimeout((()=>{He.forEach((e=>e())),He=[]}),0)},Je=["disconnected","error","connect_error","reconnect_error","reconnect_failed","sessionStateChange","tokenExpired"],Ge=["connect","message","disconnect","error","close","end","reconnect","video-streaming.didStart","video-streaming.didRecord","video-streaming.didStop","video-streaming.didFlag","video-streaming.didTerminate"],Ye=(e,t,n,r)=>{const{log:s,emitter:a}=e,o=Date.now();s(`${t}(tmpid: ${o}) > listen`);const i=(...e)=>{s(`${t}(tmpid: ${o}) > trigger`,e);try{r(...e)}catch(e){s(`${t}(tmpid: ${o}) > error`,e)}};return a.on(n,i),()=>{s(`${t}(tmpid: ${o}) > dispose`),a.off(n,i)}},Ze=(e,t)=>{const{emitter:n}=be();We((()=>{n.emit(e,t)}))};let Xe,et;async function tt(){var e;const{mqtt:t,emitter:n,token:r}=be();if(!t)return;const s=null!==(e=null==r?void 0:r.accessToken)&&void 0!==e?e:"",a=ze();Xe===s&&et===a._id||(Xe=s,et=a._id,await t.connect({accessToken:Xe,userId:et}),((e,t)=>{Ge.forEach((n=>{null==e||e.on(n,((...e)=>{t.emit(n,1===e.length?e[0]:e)}))})),e.on("message",((e,n)=>{const r=JSON.parse(n.toString());t.emit(r.eventType,r.data)}))})(t,n))}var nt;e.SubscriptionLevels=void 0,(nt=e.SubscriptionLevels||(e.SubscriptionLevels={})).COMMUNITY="community",nt.POST="post",nt.COMMENT="comment",nt.POST_AND_COMMENT="post_and_comment",nt.USER="user";const rt=(e,t)=>{switch(t){case"post":return`${e}/post/+`;case"comment":return`${e}/post/+/comment/+`;case"post_and_comment":return`${e}/post/#`;default:return e}},st=e=>e.path.split("/user/")[0],at=({path:t},n=e.SubscriptionLevels.USER)=>rt(n===e.SubscriptionLevels.USER?t:t.replace(/^(\w*)/,"$1/social"),n),ot=({channelId:e,subChannelId:t})=>{const n=ze();return`${st(n)}/marker/channel/${e}/message/${t}`},it=()=>{const e=ze();return`${st(e)}/marker/user/${e._id}`},ct=()=>st(ze()),lt=()=>{const e=ze();return`${st(e)}/smartfeed/${e._id}/channels`},dt=()=>{const e=ze();return`${st(e)}/smartfeed/${e._id}/messagefeeds`},ut=()=>{const e=ze();return`${st(e)}/smartfeed/${e._id}/messages`};function ht(e,t){const{mqtt:n}=be();return n?(tt(),n.subscribe(e,t)):()=>null}const pt=()=>{const e=ze();return`${st(e)}/videostreaming`};var ft;const mt="object"==typeof globalThis?globalThis:"object"==typeof global?global:window,{process:gt={}}=mt,yt="production"===(null===(ft=gt.env)||void 0===ft?void 0:ft.NODE_ENV),vt={EU:"eu",SG:"sg",US:"us"},bt={http:"https://apix.{region}.amity.co",upload:"https://upload.{region}.amity.co",mqtt:"wss://sse.{region}.amity.co:443/mqtt"};function wt(e,t){return bt[e].replace("{region}",t)}class Ct{constructor(){this._listener=new Map}onNetworkActivities(e){return this._listener.set(e,e),()=>{this._listener.delete(e)}}setNetworkActivities(e,t){this._listener.forEach((n=>n(e,t)))}destroy(){this._listener.clear()}}let It;var St,_t=()=>(It||(It=new Ct),It);!function(e){e.UserDeleted="User Deleted",e.UserGlobalBanned="User Global Banned",e.TokenExpired="Token Expired"}(St||(St={}));const kt=new AbortController,Tt=e=>{switch(e){case St.UserGlobalBanned:throw new pe(e,400312,"fatal");case St.UserDeleted:throw new pe(e,400100,"fatal");case St.TokenExpired:throw Ze("tokenExpired","tokenExpired"),new pe(e,800403,"fatal");default:throw new pe("Request Aborted",8e5,"error")}},Ot=e=>{const t={maxSockets:100,maxFreeSockets:10,timeout:6e4,freeSocketTimeout:3e4},n=m.default.create({baseURL:e,httpAgent:new g.default(t),httpsAgent:new a.HttpsAgent(t),signal:kt.signal});return n.defaults.withCredentials=!1,n.interceptors.request.use((e=>{if("/api/v5/sessions"===e.url)return e;if(e.metadata){const{tokenExpiry:t,isGlobalBanned:n,isUserDeleted:r}=e.metadata;n&&(kt.abort(),Tt(St.UserGlobalBanned)),r&&(kt.abort(),Tt(St.UserDeleted)),t&&Date.now()>=Date.parse(t)&&(kt.abort(St.UserDeleted),Tt(St.TokenExpired))}return e})),n.interceptors.response.use((e=>{const t=new Headers;return Object.entries(e.headers).forEach((([e,n])=>{"string"==typeof n&&t.append(e,n)})),_t().setNetworkActivities(new Request(e.request.url,{method:e.request.method,headers:e.request.headers,body:e.request.data}),{data:e.data,status:e.status,statusText:e.statusText,headers:t}),e}),(e=>{var t,n;const{response:r}=e;if(400100===(null==r?void 0:r.data.code)&&Ze("tokenTerminated","terminated"),(null===(t=null==r?void 0:r.data)||void 0===t?void 0:t.status)&&(e=>{if("success"===e.status)return e.data;if("fail"===e.status)throw new me(e.code);if("error"===e.status)throw new fe(e.message,e.code,"error")})(null==r?void 0:r.data),kt.signal.aborted)throw e;throw new Error(null!==(n=null==r?void 0:r.data)&&void 0!==n?n:e)})),n.defaults.paramsSerializer={encode:e=>encodeURIComponent(e)},n};var At="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function Et(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function Mt(e){throw new Error('Could not dynamically require "'+e+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var Rt={exports:{}};Rt.exports=function(){function e(t,n,r){function s(o,i){if(!n[o]){if(!t[o]){if(!i&&Mt)return Mt(o);if(a)return a(o,!0);var c=new Error("Cannot find module '"+o+"'");throw c.code="MODULE_NOT_FOUND",c}var l=n[o]={exports:{}};t[o][0].call(l.exports,(function(e){return s(t[o][1][e]||e)}),l,l.exports,e,t,n,r)}return n[o].exports}for(var a=Mt,o=0;o<r.length;o++)s(r[o]);return s}return e}()({1:[function(e,t,n){(function(n,r){(function(){const s=e("events").EventEmitter,a=e("./store"),o=e("./topic-alias-recv"),i=e("./topic-alias-send"),c=e("mqtt-packet"),l=e("./default-message-id-provider"),d=e("readable-stream").Writable,u=e("inherits"),h=e("reinterval"),p=e("rfdc/default"),f=e("./validations"),m=e("xtend"),g=e("debug")("mqttjs:client"),y=n?n.nextTick:function(e){setTimeout(e,0)},v=r.setImmediate||function(e){y(e)},b={keepalive:60,reschedulePings:!0,protocolId:"MQTT",protocolVersion:4,reconnectPeriod:1e3,connectTimeout:3e4,clean:!0,resubscribe:!0},w=["ECONNREFUSED","EADDRINUSE","ECONNRESET","ENOTFOUND"],C={0:"",1:"Unacceptable protocol version",2:"Identifier rejected",3:"Server unavailable",4:"Bad username or password",5:"Not authorized",16:"No matching subscribers",17:"No subscription existed",128:"Unspecified error",129:"Malformed Packet",130:"Protocol Error",131:"Implementation specific error",132:"Unsupported Protocol Version",133:"Client Identifier not valid",134:"Bad User Name or Password",135:"Not authorized",136:"Server unavailable",137:"Server busy",138:"Banned",139:"Server shutting down",140:"Bad authentication method",141:"Keep Alive timeout",142:"Session taken over",143:"Topic Filter invalid",144:"Topic Name invalid",145:"Packet identifier in use",146:"Packet Identifier not found",147:"Receive Maximum exceeded",148:"Topic Alias invalid",149:"Packet too large",150:"Message rate too high",151:"Quota exceeded",152:"Administrative action",153:"Payload format invalid",154:"Retain not supported",155:"QoS not supported",156:"Use another server",157:"Server moved",158:"Shared Subscriptions not supported",159:"Connection rate exceeded",160:"Maximum connect time",161:"Subscription Identifiers not supported",162:"Wildcard Subscriptions not supported"};function I(){return"mqttjs_"+Math.random().toString(16).substr(2,8)}function S(e,t){if(5===e.options.protocolVersion&&"publish"===t.cmd){let n;t.properties&&(n=t.properties.topicAlias);const r=t.topic.toString();if(e.topicAliasSend)if(n){if(0!==r.length&&(g("applyTopicAlias :: register topic: %s - alias: %d",r,n),!e.topicAliasSend.put(r,n)))return g("applyTopicAlias :: error out of range. topic: %s - alias: %d",r,n),new Error("Sending Topic Alias out of range")}else 0!==r.length&&(e.options.autoAssignTopicAlias?(n=e.topicAliasSend.getAliasByTopic(r),n?(t.topic="",t.properties={...t.properties,topicAlias:n},g("applyTopicAlias :: auto assign(use) topic: %s - alias: %d",r,n)):(n=e.topicAliasSend.getLruAlias(),e.topicAliasSend.put(r,n),t.properties={...t.properties,topicAlias:n},g("applyTopicAlias :: auto assign topic: %s - alias: %d",r,n))):e.options.autoUseTopicAlias&&(n=e.topicAliasSend.getAliasByTopic(r),n&&(t.topic="",t.properties={...t.properties,topicAlias:n},g("applyTopicAlias :: auto use topic: %s - alias: %d",r,n))));else if(n)return g("applyTopicAlias :: error out of range. topic: %s - alias: %d",r,n),new Error("Sending Topic Alias out of range")}}function _(e,t){let n;t.properties&&(n=t.properties.topicAlias);let r=t.topic.toString();if(0===r.length){if(void 0===n)return new Error("Unregistered Topic Alias");if(r=e.topicAliasSend.getTopicByAlias(n),void 0===r)return new Error("Unregistered Topic Alias");t.topic=r}n&&delete t.properties.topicAlias}function k(e,t,n){g("sendPacket :: packet: %O",t),g("sendPacket :: emitting `packetsend`"),e.emit("packetsend",t),g("sendPacket :: writing to stream");const r=c.writeToStream(t,e.stream,e.options);g("sendPacket :: writeToStream result %s",r),!r&&n&&n!==E?(g("sendPacket :: handle events on `drain` once through callback."),e.stream.once("drain",n)):n&&(g("sendPacket :: invoking cb"),n())}function T(e){e&&(g("flush: queue exists? %b",!!e),Object.keys(e).forEach((function(t){"function"==typeof e[t].cb&&(e[t].cb(new Error("Connection closed")),delete e[t])})))}function O(e){e&&(g("flushVolatile :: deleting volatile messages from the queue and setting their callbacks as error function"),Object.keys(e).forEach((function(t){e[t].volatile&&"function"==typeof e[t].cb&&(e[t].cb(new Error("Connection closed")),delete e[t])})))}function A(e,t,n,r){g("storeAndSend :: store packet with cmd %s to outgoingStore",t.cmd);let s,a=t;if("publish"===a.cmd&&(a=p(t),s=_(e,a),s))return n&&n(s);e.outgoingStore.put(a,(function(s){if(s)return n&&n(s);r(),k(e,t,n)}))}function E(e){g("nop ::",e)}function M(e,t){let n;const r=this;if(!(this instanceof M))return new M(e,t);for(n in this.options=t||{},b)void 0===this.options[n]?this.options[n]=b[n]:this.options[n]=t[n];g("MqttClient :: options.protocol",t.protocol),g("MqttClient :: options.protocolVersion",t.protocolVersion),g("MqttClient :: options.username",t.username),g("MqttClient :: options.keepalive",t.keepalive),g("MqttClient :: options.reconnectPeriod",t.reconnectPeriod),g("MqttClient :: options.rejectUnauthorized",t.rejectUnauthorized),g("MqttClient :: options.topicAliasMaximum",t.topicAliasMaximum),this.options.clientId="string"==typeof t.clientId?t.clientId:I(),g("MqttClient :: clientId",this.options.clientId),this.options.customHandleAcks=5===t.protocolVersion&&t.customHandleAcks?t.customHandleAcks:function(){arguments[3](0)},this.streamBuilder=e,this.messageIdProvider=void 0===this.options.messageIdProvider?new l:this.options.messageIdProvider,this.outgoingStore=t.outgoingStore||new a,this.incomingStore=t.incomingStore||new a,this.queueQoSZero=void 0===t.queueQoSZero||t.queueQoSZero,this._resubscribeTopics={},this.messageIdToTopic={},this.pingTimer=null,this.connected=!1,this.disconnecting=!1,this.queue=[],this.connackTimer=null,this.reconnectTimer=null,this._storeProcessing=!1,this._packetIdsDuringStoreProcessing={},this._storeProcessingQueue=[],this.outgoing={},this._firstConnection=!0,t.topicAliasMaximum>0&&(t.topicAliasMaximum>65535?g("MqttClient :: options.topicAliasMaximum is out of range"):this.topicAliasRecv=new o(t.topicAliasMaximum)),this.on("connect",(function(){const e=this.queue;function t(){const n=e.shift();g("deliver :: entry %o",n);let s=null;if(!n)return void r._resubscribe();s=n.packet,g("deliver :: call _sendPacket for %o",s);let a=!0;s.messageId&&0!==s.messageId&&(r.messageIdProvider.register(s.messageId)||(a=!1)),a?r._sendPacket(s,(function(e){n.cb&&n.cb(e),t()})):(g("messageId: %d has already used. The message is skipped and removed.",s.messageId),t())}g("connect :: sending queued packets"),t()})),this.on("close",(function(){g("close :: connected set to `false`"),this.connected=!1,g("close :: clearing connackTimer"),clearTimeout(this.connackTimer),g("close :: clearing ping timer"),null!==r.pingTimer&&(r.pingTimer.clear(),r.pingTimer=null),this.topicAliasRecv&&this.topicAliasRecv.clear(),g("close :: calling _setupReconnect"),this._setupReconnect()})),s.call(this),g("MqttClient :: setting up stream"),this._setupStream()}u(M,s),M.prototype._setupStream=function(){const e=this,t=new d,n=c.parser(this.options);let r=null;const s=[];function a(){if(s.length)y(o);else{const e=r;r=null,e()}}function o(){g("work :: getting next packet in queue");const t=s.shift();if(t)g("work :: packet pulled from queue"),e._handlePacket(t,a);else{g("work :: no packets in queue");const e=r;r=null,g("work :: done flag is %s",!!e),e&&e()}}function i(t){g("streamErrorHandler :: error",t.message),w.includes(t.code)?(g("streamErrorHandler :: emitting error"),e.emit("error",t)):E(t)}g("_setupStream :: calling method to clear reconnect"),this._clearReconnect(),g("_setupStream :: using streamBuilder provided to client to create stream"),this.stream=this.streamBuilder(this),n.on("packet",(function(e){g("parser :: on packet push to packets array."),s.push(e)})),t._write=function(e,t,s){r=s,g("writable stream :: parsing buffer"),n.parse(e),o()},g("_setupStream :: pipe stream to writable stream"),this.stream.pipe(t),this.stream.on("error",i),this.stream.on("close",(function(){g("(%s)stream :: on close",e.options.clientId),O(e.outgoing),g("stream: emit close to MqttClient"),e.emit("close")})),g("_setupStream: sending packet `connect`");const l=Object.create(this.options);if(l.cmd="connect",this.topicAliasRecv&&(l.properties||(l.properties={}),this.topicAliasRecv&&(l.properties.topicAliasMaximum=this.topicAliasRecv.max)),k(this,l),n.on("error",this.emit.bind(this,"error")),this.options.properties){if(!this.options.properties.authenticationMethod&&this.options.properties.authenticationData)return e.end((()=>this.emit("error",new Error("Packet has no Authentication Method")))),this;this.options.properties.authenticationMethod&&this.options.authPacket&&"object"==typeof this.options.authPacket&&k(this,m({cmd:"auth",reasonCode:0},this.options.authPacket))}this.stream.setMaxListeners(1e3),clearTimeout(this.connackTimer),this.connackTimer=setTimeout((function(){g("!!connectTimeout hit!! Calling _cleanUp with force `true`"),e._cleanUp(!0)}),this.options.connectTimeout)},M.prototype._handlePacket=function(e,t){const n=this.options;if(5===n.protocolVersion&&n.properties&&n.properties.maximumPacketSize&&n.properties.maximumPacketSize<e.length)return this.emit("error",new Error("exceeding packets size "+e.cmd)),this.end({reasonCode:149,properties:{reasonString:"Maximum packet size was exceeded"}}),this;switch(g("_handlePacket :: emitting packetreceive"),this.emit("packetreceive",e),e.cmd){case"publish":this._handlePublish(e,t);break;case"puback":case"pubrec":case"pubcomp":case"suback":case"unsuback":this._handleAck(e),t();break;case"pubrel":this._handlePubrel(e,t);break;case"connack":this._handleConnack(e),t();break;case"auth":this._handleAuth(e),t();break;case"pingresp":this._handlePingresp(e),t();break;case"disconnect":this._handleDisconnect(e),t()}},M.prototype._checkDisconnecting=function(e){return this.disconnecting&&(e&&e!==E?e(new Error("client disconnecting")):this.emit("error",new Error("client disconnecting"))),this.disconnecting},M.prototype.publish=function(e,t,n,r){g("publish :: message `%s` to topic `%s`",t,e);const s=this.options;if("function"==typeof n&&(r=n,n=null),n=m({qos:0,retain:!1,dup:!1},n),this._checkDisconnecting(r))return this;const a=this,o=function(){let o=0;if((1===n.qos||2===n.qos)&&(o=a._nextId(),null===o))return g("No messageId left"),!1;const i={cmd:"publish",topic:e,payload:t,qos:n.qos,retain:n.retain,messageId:o,dup:n.dup};switch(5===s.protocolVersion&&(i.properties=n.properties),g("publish :: qos",n.qos),n.qos){case 1:case 2:a.outgoing[i.messageId]={volatile:!1,cb:r||E},g("MqttClient:publish: packet cmd: %s",i.cmd),a._sendPacket(i,void 0,n.cbStorePut);break;default:g("MqttClient:publish: packet cmd: %s",i.cmd),a._sendPacket(i,r,n.cbStorePut)}return!0};return(this._storeProcessing||this._storeProcessingQueue.length>0||!o())&&this._storeProcessingQueue.push({invoke:o,cbStorePut:n.cbStorePut,callback:r}),this},M.prototype.subscribe=function(){const e=this,t=new Array(arguments.length);for(let e=0;e<arguments.length;e++)t[e]=arguments[e];const n=[];let r=t.shift();const s=r.resubscribe;let a=t.pop()||E,o=t.pop();const i=this.options.protocolVersion;delete r.resubscribe,"string"==typeof r&&(r=[r]),"function"!=typeof a&&(o=a,a=E);const c=f.validateTopics(r);if(null!==c)return v(a,new Error("Invalid topic "+c)),this;if(this._checkDisconnecting(a))return g("subscribe: discconecting true"),this;const l={qos:0};if(5===i&&(l.nl=!1,l.rap=!1,l.rh=0),o=m(l,o),Array.isArray(r)?r.forEach((function(t){if(g("subscribe: array topic %s",t),!Object.prototype.hasOwnProperty.call(e._resubscribeTopics,t)||e._resubscribeTopics[t].qos<o.qos||s){const e={topic:t,qos:o.qos};5===i&&(e.nl=o.nl,e.rap=o.rap,e.rh=o.rh,e.properties=o.properties),g("subscribe: pushing topic `%s` and qos `%s` to subs list",e.topic,e.qos),n.push(e)}})):Object.keys(r).forEach((function(t){if(g("subscribe: object topic %s",t),!Object.prototype.hasOwnProperty.call(e._resubscribeTopics,t)||e._resubscribeTopics[t].qos<r[t].qos||s){const e={topic:t,qos:r[t].qos};5===i&&(e.nl=r[t].nl,e.rap=r[t].rap,e.rh=r[t].rh,e.properties=o.properties),g("subscribe: pushing `%s` to subs list",e),n.push(e)}})),!n.length)return a(null,[]),this;const d=function(){const t=e._nextId();if(null===t)return g("No messageId left"),!1;const r={cmd:"subscribe",subscriptions:n,qos:1,retain:!1,dup:!1,messageId:t};if(o.properties&&(r.properties=o.properties),e.options.resubscribe){g("subscribe :: resubscribe true");const t=[];n.forEach((function(n){if(e.options.reconnectPeriod>0){const r={qos:n.qos};5===i&&(r.nl=n.nl||!1,r.rap=n.rap||!1,r.rh=n.rh||0,r.properties=n.properties),e._resubscribeTopics[n.topic]=r,t.push(n.topic)}})),e.messageIdToTopic[r.messageId]=t}return e.outgoing[r.messageId]={volatile:!0,cb:function(e,t){if(!e){const e=t.granted;for(let t=0;t<e.length;t+=1)n[t].qos=e[t]}a(e,n)}},g("subscribe :: call _sendPacket"),e._sendPacket(r),!0};return(this._storeProcessing||this._storeProcessingQueue.length>0||!d())&&this._storeProcessingQueue.push({invoke:d,callback:a}),this},M.prototype.unsubscribe=function(){const e=this,t=new Array(arguments.length);for(let e=0;e<arguments.length;e++)t[e]=arguments[e];let n=t.shift(),r=t.pop()||E,s=t.pop();"string"==typeof n&&(n=[n]),"function"!=typeof r&&(s=r,r=E);const a=f.validateTopics(n);if(null!==a)return v(r,new Error("Invalid topic "+a)),this;if(e._checkDisconnecting(r))return this;const o=function(){const t=e._nextId();if(null===t)return g("No messageId left"),!1;const a={cmd:"unsubscribe",qos:1,messageId:t};return"string"==typeof n?a.unsubscriptions=[n]:Array.isArray(n)&&(a.unsubscriptions=n),e.options.resubscribe&&a.unsubscriptions.forEach((function(t){delete e._resubscribeTopics[t]})),"object"==typeof s&&s.properties&&(a.properties=s.properties),e.outgoing[a.messageId]={volatile:!0,cb:r},g("unsubscribe: call _sendPacket"),e._sendPacket(a),!0};return(this._storeProcessing||this._storeProcessingQueue.length>0||!o())&&this._storeProcessingQueue.push({invoke:o,callback:r}),this},M.prototype.end=function(e,t,n){const r=this;function s(){g("end :: closeStores: closing incoming and outgoing stores"),r.disconnected=!0,r.incomingStore.close((function(e){r.outgoingStore.close((function(t){if(g("end :: closeStores: emitting end"),r.emit("end"),n){const r=e||t;g("end :: closeStores: invoking callback with args"),n(r)}}))})),r._deferredReconnect&&r._deferredReconnect()}function a(){g("end :: (%s) :: finish :: calling _cleanUp with force %s",r.options.clientId,e),r._cleanUp(e,(()=>{g("end :: finish :: calling process.nextTick on closeStores"),y(s.bind(r))}),t)}return g("end :: (%s)",this.options.clientId),null!=e&&"boolean"==typeof e||(n=t||E,t=e,e=!1,"object"!=typeof t&&(n=t,t=null,"function"!=typeof n&&(n=E))),"object"!=typeof t&&(n=t,t=null),g("end :: cb? %s",!!n),n=n||E,this.disconnecting?(n(),this):(this._clearReconnect(),this.disconnecting=!0,!e&&Object.keys(this.outgoing).length>0?(g("end :: (%s) :: calling finish in 10ms once outgoing is empty",r.options.clientId),this.once("outgoingEmpty",setTimeout.bind(null,a,10))):(g("end :: (%s) :: immediately calling finish",r.options.clientId),a()),this)},M.prototype.removeOutgoingMessage=function(e){const t=this.outgoing[e]?this.outgoing[e].cb:null;return delete this.outgoing[e],this.outgoingStore.del({messageId:e},(function(){t(new Error("Message removed"))})),this},M.prototype.reconnect=function(e){g("client reconnect");const t=this,n=function(){e?(t.options.incomingStore=e.incomingStore,t.options.outgoingStore=e.outgoingStore):(t.options.incomingStore=null,t.options.outgoingStore=null),t.incomingStore=t.options.incomingStore||new a,t.outgoingStore=t.options.outgoingStore||new a,t.disconnecting=!1,t.disconnected=!1,t._deferredReconnect=null,t._reconnect()};return this.disconnecting&&!this.disconnected?this._deferredReconnect=n:n(),this},M.prototype._reconnect=function(){g("_reconnect: emitting reconnect to client"),this.emit("reconnect"),this.connected?(this.end((()=>{this._setupStream()})),g("client already connected. disconnecting first.")):(g("_reconnect: calling _setupStream"),this._setupStream())},M.prototype._setupReconnect=function(){const e=this;!e.disconnecting&&!e.reconnectTimer&&e.options.reconnectPeriod>0?(this.reconnecting||(g("_setupReconnect :: emit `offline` state"),this.emit("offline"),g("_setupReconnect :: set `reconnecting` to `true`"),this.reconnecting=!0),g("_setupReconnect :: setting reconnectTimer for %d ms",e.options.reconnectPeriod),e.reconnectTimer=setInterval((function(){g("reconnectTimer :: reconnect triggered!"),e._reconnect()}),e.options.reconnectPeriod)):g("_setupReconnect :: doing nothing...")},M.prototype._clearReconnect=function(){g("_clearReconnect : clearing reconnect timer"),this.reconnectTimer&&(clearInterval(this.reconnectTimer),this.reconnectTimer=null)},M.prototype._cleanUp=function(e,t){const n=arguments[2];if(t&&(g("_cleanUp :: done callback provided for on stream close"),this.stream.on("close",t)),g("_cleanUp :: forced? %s",e),e)0===this.options.reconnectPeriod&&this.options.clean&&T(this.outgoing),g("_cleanUp :: (%s) :: destroying stream",this.options.clientId),this.stream.destroy();else{const e=m({cmd:"disconnect"},n);g("_cleanUp :: (%s) :: call _sendPacket with disconnect packet",this.options.clientId),this._sendPacket(e,v.bind(null,this.stream.end.bind(this.stream)))}this.disconnecting||(g("_cleanUp :: client not disconnecting. Clearing and resetting reconnect."),this._clearReconnect(),this._setupReconnect()),null!==this.pingTimer&&(g("_cleanUp :: clearing pingTimer"),this.pingTimer.clear(),this.pingTimer=null),t&&!this.connected&&(g("_cleanUp :: (%s) :: removing stream `done` callback `close` listener",this.options.clientId),this.stream.removeListener("close",t),t())},M.prototype._sendPacket=function(e,t,n){g("_sendPacket :: (%s) :: start",this.options.clientId),n=n||E,t=t||E;const r=S(this,e);if(r)t(r);else{if(!this.connected)return"auth"===e.cmd?(this._shiftPingInterval(),void k(this,e,t)):(g("_sendPacket :: client not connected. Storing packet offline."),void this._storePacket(e,t,n));switch(this._shiftPingInterval(),e.cmd){case"publish":break;case"pubrel":return void A(this,e,t,n);default:return void k(this,e,t)}switch(e.qos){case 2:case 1:A(this,e,t,n);break;default:k(this,e,t)}g("_sendPacket :: (%s) :: end",this.options.clientId)}},M.prototype._storePacket=function(e,t,n){g("_storePacket :: packet: %o",e),g("_storePacket :: cb? %s",!!t),n=n||E;let r=e;if("publish"===r.cmd){r=p(e);const n=_(this,r);if(n)return t&&t(n)}0===(r.qos||0)&&this.queueQoSZero||"publish"!==r.cmd?this.queue.push({packet:r,cb:t}):r.qos>0?(t=this.outgoing[r.messageId]?this.outgoing[r.messageId].cb:null,this.outgoingStore.put(r,(function(e){if(e)return t&&t(e);n()}))):t&&t(new Error("No connection to broker"))},M.prototype._setupPingTimer=function(){g("_setupPingTimer :: keepalive %d (seconds)",this.options.keepalive);const e=this;!this.pingTimer&&this.options.keepalive&&(this.pingResp=!0,this.pingTimer=h((function(){e._checkPing()}),1e3*this.options.keepalive))},M.prototype._shiftPingInterval=function(){this.pingTimer&&this.options.keepalive&&this.options.reschedulePings&&this.pingTimer.reschedule(1e3*this.options.keepalive)},M.prototype._checkPing=function(){g("_checkPing :: checking ping..."),this.pingResp?(g("_checkPing :: ping response received. Clearing flag and sending `pingreq`"),this.pingResp=!1,this._sendPacket({cmd:"pingreq"})):(g("_checkPing :: calling _cleanUp with force true"),this._cleanUp(!0))},M.prototype._handlePingresp=function(){this.pingResp=!0},M.prototype._handleConnack=function(e){g("_handleConnack");const t=this.options,n=5===t.protocolVersion?e.reasonCode:e.returnCode;if(clearTimeout(this.connackTimer),delete this.topicAliasSend,e.properties){if(e.properties.topicAliasMaximum){if(e.properties.topicAliasMaximum>65535)return void this.emit("error",new Error("topicAliasMaximum from broker is out of range"));e.properties.topicAliasMaximum>0&&(this.topicAliasSend=new i(e.properties.topicAliasMaximum))}e.properties.serverKeepAlive&&t.keepalive&&(t.keepalive=e.properties.serverKeepAlive,this._shiftPingInterval()),e.properties.maximumPacketSize&&(t.properties||(t.properties={}),t.properties.maximumPacketSize=e.properties.maximumPacketSize)}if(0===n)this.reconnecting=!1,this._onConnect(e);else if(n>0){const e=new Error("Connection refused: "+C[n]);e.code=n,this.emit("error",e)}},M.prototype._handleAuth=function(e){const t=this.options.protocolVersion,n=5===t?e.reasonCode:e.returnCode;if(5!==t){const e=new Error("Protocol error: Auth packets are only supported in MQTT 5. Your version:"+t);return e.code=n,void this.emit("error",e)}const r=this;this.handleAuth(e,(function(e,t){if(e)r.emit("error",e);else if(24===n)r.reconnecting=!1,r._sendPacket(t);else{const t=new Error("Connection refused: "+C[n]);e.code=n,r.emit("error",t)}}))},M.prototype.handleAuth=function(e,t){t()},M.prototype._handlePublish=function(e,t){g("_handlePublish: packet %o",e),t=void 0!==t?t:E;let n=e.topic.toString();const r=e.payload,s=e.qos,a=e.messageId,o=this,i=this.options,c=[0,16,128,131,135,144,145,151,153];if(5===this.options.protocolVersion){let t;if(e.properties&&(t=e.properties.topicAlias),void 0!==t)if(0===n.length){if(!(t>0&&t<=65535))return g("_handlePublish :: topic alias out of range. alias: %d",t),void this.emit("error",new Error("Received Topic Alias is out of range"));{const e=this.topicAliasRecv.getTopicByAlias(t);if(!e)return g("_handlePublish :: unregistered topic alias. alias: %d",t),void this.emit("error",new Error("Received unregistered Topic Alias"));n=e,g("_handlePublish :: topic complemented by alias. topic: %s - alias: %d",n,t)}}else{if(!this.topicAliasRecv.put(n,t))return g("_handlePublish :: topic alias out of range. alias: %d",t),void this.emit("error",new Error("Received Topic Alias is out of range"));g("_handlePublish :: registered topic: %s - alias: %d",n,t)}}switch(g("_handlePublish: qos %d",s),s){case 2:i.customHandleAcks(n,r,e,(function(n,r){return n instanceof Error||(r=n,n=null),n?o.emit("error",n):-1===c.indexOf(r)?o.emit("error",new Error("Wrong reason code for pubrec")):void(r?o._sendPacket({cmd:"pubrec",messageId:a,reasonCode:r},t):o.incomingStore.put(e,(function(){o._sendPacket({cmd:"pubrec",messageId:a},t)})))}));break;case 1:i.customHandleAcks(n,r,e,(function(s,i){return s instanceof Error||(i=s,s=null),s?o.emit("error",s):-1===c.indexOf(i)?o.emit("error",new Error("Wrong reason code for puback")):(i||o.emit("message",n,r,e),void o.handleMessage(e,(function(e){if(e)return t&&t(e);o._sendPacket({cmd:"puback",messageId:a,reasonCode:i},t)})))}));break;case 0:this.emit("message",n,r,e),this.handleMessage(e,t);break;default:g("_handlePublish: unknown QoS. Doing nothing.")}},M.prototype.handleMessage=function(e,t){t()},M.prototype._handleAck=function(e){const t=e.messageId,n=e.cmd;let r=null;const s=this.outgoing[t]?this.outgoing[t].cb:null,a=this;let o;if(s){switch(g("_handleAck :: packet type",n),n){case"pubcomp":case"puback":{const n=e.reasonCode;n&&n>0&&16!==n&&(o=new Error("Publish error: "+C[n]),o.code=n,s(o,e)),delete this.outgoing[t],this.outgoingStore.del(e,s),this.messageIdProvider.deallocate(t),this._invokeStoreProcessingQueue();break}case"pubrec":{r={cmd:"pubrel",qos:2,messageId:t};const n=e.reasonCode;n&&n>0&&16!==n?(o=new Error("Publish error: "+C[n]),o.code=n,s(o,e)):this._sendPacket(r);break}case"suback":delete this.outgoing[t],this.messageIdProvider.deallocate(t);for(let n=0;n<e.granted.length;n++)if(0!=(128&e.granted[n])){const e=this.messageIdToTopic[t];e&&e.forEach((function(e){delete a._resubscribeTopics[e]}))}this._invokeStoreProcessingQueue(),s(null,e);break;case"unsuback":delete this.outgoing[t],this.messageIdProvider.deallocate(t),this._invokeStoreProcessingQueue(),s(null);break;default:a.emit("error",new Error("unrecognized packet type"))}this.disconnecting&&0===Object.keys(this.outgoing).length&&this.emit("outgoingEmpty")}else g("_handleAck :: Server sent an ack in error. Ignoring.")},M.prototype._handlePubrel=function(e,t){g("handling pubrel packet"),t=void 0!==t?t:E;const n=e.messageId,r=this,s={cmd:"pubcomp",messageId:n};r.incomingStore.get(e,(function(e,n){e?r._sendPacket(s,t):(r.emit("message",n.topic,n.payload,n),r.handleMessage(n,(function(e){if(e)return t(e);r.incomingStore.del(n,E),r._sendPacket(s,t)})))}))},M.prototype._handleDisconnect=function(e){this.emit("disconnect",e)},M.prototype._nextId=function(){return this.messageIdProvider.allocate()},M.prototype.getLastMessageId=function(){return this.messageIdProvider.getLastAllocated()},M.prototype._resubscribe=function(){g("_resubscribe");const e=Object.keys(this._resubscribeTopics);if(!this._firstConnection&&(this.options.clean||5===this.options.protocolVersion&&!this.connackPacket.sessionPresent)&&e.length>0)if(this.options.resubscribe)if(5===this.options.protocolVersion){g("_resubscribe: protocolVersion 5");for(let t=0;t<e.length;t++){const n={};n[e[t]]=this._resubscribeTopics[e[t]],n.resubscribe=!0,this.subscribe(n,{properties:n[e[t]].properties})}}else this._resubscribeTopics.resubscribe=!0,this.subscribe(this._resubscribeTopics);else this._resubscribeTopics={};this._firstConnection=!1},M.prototype._onConnect=function(e){if(this.disconnected)return void this.emit("connect",e);const t=this;function n(){let r=t.outgoingStore.createStream();function s(){t._storeProcessing=!1,t._packetIdsDuringStoreProcessing={}}function a(){r.destroy(),r=null,t._flushStoreProcessingQueue(),s()}function o(){if(!r)return;t._storeProcessing=!0;const e=r.read(1);let n;e?t._packetIdsDuringStoreProcessing[e.messageId]?o():t.disconnecting||t.reconnectTimer?r.destroy&&r.destroy():(n=t.outgoing[e.messageId]?t.outgoing[e.messageId].cb:null,t.outgoing[e.messageId]={volatile:!1,cb:function(e,t){n&&n(e,t),o()}},t._packetIdsDuringStoreProcessing[e.messageId]=!0,t.messageIdProvider.register(e.messageId)?t._sendPacket(e):g("messageId: %d has already used.",e.messageId)):r.once("readable",o)}t.once("close",a),r.on("error",(function(e){s(),t._flushStoreProcessingQueue(),t.removeListener("close",a),t.emit("error",e)})),r.on("end",(function(){let r=!0;for(const e in t._packetIdsDuringStoreProcessing)if(!t._packetIdsDuringStoreProcessing[e]){r=!1;break}r?(s(),t.removeListener("close",a),t._invokeAllStoreProcessingQueue(),t.emit("connect",e)):n()})),o()}this.connackPacket=e,this.messageIdProvider.clear(),this._setupPingTimer(),this.connected=!0,n()},M.prototype._invokeStoreProcessingQueue=function(){if(this._storeProcessingQueue.length>0){const e=this._storeProcessingQueue[0];if(e&&e.invoke())return this._storeProcessingQueue.shift(),!0}return!1},M.prototype._invokeAllStoreProcessingQueue=function(){for(;this._invokeStoreProcessingQueue(););},M.prototype._flushStoreProcessingQueue=function(){for(const e of this._storeProcessingQueue)e.cbStorePut&&e.cbStorePut(new Error("Connection closed")),e.callback&&e.callback(new Error("Connection closed"));this._storeProcessingQueue.splice(0)},t.exports=M}).call(this)}).call(this,e("_process"),void 0!==At?At:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./default-message-id-provider":7,"./store":8,"./topic-alias-recv":9,"./topic-alias-send":10,"./validations":11,_process:50,debug:18,events:22,inherits:24,"mqtt-packet":40,"readable-stream":69,reinterval:70,"rfdc/default":71,xtend:81}],2:[function(e,t,n){const{Buffer:r}=e("buffer"),s=e("readable-stream").Transform,a=e("duplexify");let o,i,c,l=!1;function d(){const e=new s;return e._write=function(e,t,n){o.sendSocketMessage({data:e.buffer,success:function(){n()},fail:function(){n(new Error)}})},e._flush=function(e){o.closeSocket({success:function(){e()}})},e}function u(e){e.hostname||(e.hostname="localhost"),e.path||(e.path="/"),e.wsOptions||(e.wsOptions={})}function h(e,t){const n="alis"===e.protocol?"wss":"ws";let r=n+"://"+e.hostname+e.path;return e.port&&80!==e.port&&443!==e.port&&(r=n+"://"+e.hostname+":"+e.port+e.path),"function"==typeof e.transformWsUrl&&(r=e.transformWsUrl(r,e,t)),r}function p(){l||(l=!0,o.onSocketOpen((function(){c.setReadable(i),c.setWritable(i),c.emit("connect")})),o.onSocketMessage((function(e){if("string"==typeof e.data){const t=r.from(e.data,"base64");i.push(t)}else{const t=new FileReader;t.addEventListener("load",(function(){let e=t.result;e=e instanceof ArrayBuffer?r.from(e):r.from(e,"utf8"),i.push(e)})),t.readAsArrayBuffer(e.data)}})),o.onSocketClose((function(){c.end(),c.destroy()})),o.onSocketError((function(e){c.destroy(e)})))}function f(e,t){if(t.hostname=t.hostname||t.host,!t.hostname)throw new Error("Could not determine host. Specify host manually.");const n="MQIsdp"===t.protocolId&&3===t.protocolVersion?"mqttv3.1":"mqtt";u(t);const r=h(t,e);return o=t.my,o.connectSocket({url:r,protocols:n}),i=d(),c=a.obj(),p(),c}t.exports=f},{buffer:17,duplexify:20,"readable-stream":69}],3:[function(e,t,n){const r=e("net"),s=e("debug")("mqttjs:tcp");function a(e,t){t.port=t.port||1883,t.hostname=t.hostname||t.host||"localhost";const n=t.port,a=t.hostname;return s("port %d and host %s",n,a),r.createConnection(n,a)}t.exports=a},{debug:18,net:16}],4:[function(e,t,n){const r=e("tls"),s=e("net"),a=e("debug")("mqttjs:tls");function o(e,t){t.port=t.port||8883,t.host=t.hostname||t.host||"localhost",0===s.isIP(t.host)&&(t.servername=t.host),t.rejectUnauthorized=!1!==t.rejectUnauthorized,delete t.path,a("port %d host %s rejectUnauthorized %b",t.port,t.host,t.rejectUnauthorized);const n=r.connect(t);function o(r){t.rejectUnauthorized&&e.emit("error",r),n.end()}return n.on("secureConnect",(function(){t.rejectUnauthorized&&!n.authorized?n.emit("error",new Error("TLS not authorized")):n.removeListener("error",o)})),n.on("error",o),n}t.exports=o},{debug:18,net:16,tls:16}],5:[function(e,t,n){(function(n){(function(){const{Buffer:r}=e("buffer"),s=e("ws"),a=e("debug")("mqttjs:ws"),o=e("duplexify"),i=e("readable-stream").Transform,c=["rejectUnauthorized","ca","cert","key","pfx","passphrase"],l=void 0!==n&&"browser"===n.title||"function"==typeof __webpack_require__;function d(e,t){let n=e.protocol+"://"+e.hostname+":"+e.port+e.path;return"function"==typeof e.transformWsUrl&&(n=e.transformWsUrl(n,e,t)),n}function u(e){const t=e;return e.hostname||(t.hostname="localhost"),e.port||("wss"===e.protocol?t.port=443:t.port=80),e.path||(t.path="/"),e.wsOptions||(t.wsOptions={}),l||"wss"!==e.protocol||c.forEach((function(n){Object.prototype.hasOwnProperty.call(e,n)&&!Object.prototype.hasOwnProperty.call(e.wsOptions,n)&&(t.wsOptions[n]=e[n])})),t}function h(e){const t=u(e);if(t.hostname||(t.hostname=t.host),!t.hostname){if("undefined"==typeof document)throw new Error("Could not determine host. Specify host manually.");const e=new URL(document.URL);t.hostname=e.hostname,t.port||(t.port=e.port)}return void 0===t.objectMode&&(t.objectMode=!(!0===t.binary||void 0===t.binary)),t}function p(e,t,n){a("createWebSocket"),a("protocol: "+n.protocolId+" "+n.protocolVersion);const r="MQIsdp"===n.protocolId&&3===n.protocolVersion?"mqttv3.1":"mqtt";return a("creating new Websocket for url: "+t+" and protocol: "+r),new s(t,[r],n.wsOptions)}function f(e,t){const n="MQIsdp"===t.protocolId&&3===t.protocolVersion?"mqttv3.1":"mqtt",r=d(t,e),s=new WebSocket(r,[n]);return s.binaryType="arraybuffer",s}function m(e,t){a("streamBuilder");const n=u(t),r=d(n,e),o=p(e,r,n),i=s.createWebSocketStream(o,n.wsOptions);return i.url=r,o.on("close",(()=>{i.destroy()})),i}function g(e,t){let n;a("browserStreamBuilder");const s=h(t).browserBufferSize||524288,c=t.browserBufferTimeout||1e3,l=!t.objectMode,d=f(e,t),u=m(t,C,I);t.objectMode||(u._writev=w),u.on("close",(()=>{d.close()}));const p=void 0!==d.addEventListener;function m(e,t,n){const r=new i({objectModeMode:e.objectMode});return r._write=t,r._flush=n,r}function g(){n.setReadable(u),n.setWritable(u),n.emit("connect")}function y(){n.end(),n.destroy()}function v(e){n.destroy(e)}function b(e){let t=e.data;t=t instanceof ArrayBuffer?r.from(t):r.from(t,"utf8"),u.push(t)}function w(e,t){const n=new Array(e.length);for(let t=0;t<e.length;t++)"string"==typeof e[t].chunk?n[t]=r.from(e[t],"utf8"):n[t]=e[t].chunk;this._write(r.concat(n),"binary",t)}function C(e,t,n){d.bufferedAmount>s&&setTimeout(C,c,e,t,n),l&&"string"==typeof e&&(e=r.from(e,"utf8"));try{d.send(e)}catch(e){return n(e)}n()}function I(e){d.close(),e()}return d.readyState===d.OPEN?n=u:(n=n=o(void 0,void 0,t),t.objectMode||(n._writev=w),p?d.addEventListener("open",g):d.onopen=g),n.socket=d,p?(d.addEventListener("close",y),d.addEventListener("error",v),d.addEventListener("message",b)):(d.onclose=y,d.onerror=v,d.onmessage=b),n}t.exports=l?g:m}).call(this)}).call(this,e("_process"))},{_process:50,buffer:17,debug:18,duplexify:20,"readable-stream":69,ws:80}],6:[function(e,t,n){const{Buffer:r}=e("buffer"),s=e("readable-stream").Transform,a=e("duplexify");let o,i,c;function l(){const e=new s;return e._write=function(e,t,n){o.send({data:e.buffer,success:function(){n()},fail:function(e){n(new Error(e))}})},e._flush=function(e){o.close({success:function(){e()}})},e}function d(e){e.hostname||(e.hostname="localhost"),e.path||(e.path="/"),e.wsOptions||(e.wsOptions={})}function u(e,t){const n="wxs"===e.protocol?"wss":"ws";let r=n+"://"+e.hostname+e.path;return e.port&&80!==e.port&&443!==e.port&&(r=n+"://"+e.hostname+":"+e.port+e.path),"function"==typeof e.transformWsUrl&&(r=e.transformWsUrl(r,e,t)),r}function h(){o.onOpen((function(){c.setReadable(i),c.setWritable(i),c.emit("connect")})),o.onMessage((function(e){let t=e.data;t=t instanceof ArrayBuffer?r.from(t):r.from(t,"utf8"),i.push(t)})),o.onClose((function(){c.end(),c.destroy()})),o.onError((function(e){c.destroy(new Error(e.errMsg))}))}function p(e,t){if(t.hostname=t.hostname||t.host,!t.hostname)throw new Error("Could not determine host. Specify host manually.");const n="MQIsdp"===t.protocolId&&3===t.protocolVersion?"mqttv3.1":"mqtt";d(t);const r=u(t,e);o=wx.connectSocket({url:r,protocols:[n]}),i=l(),c=a.obj(),c._destroy=function(e,t){o.close({success:function(){t&&t(e)}})};const s=c.destroy;return c.destroy=function(){c.destroy=s;const e=this;setTimeout((function(){o.close({fail:function(){e._destroy(new Error)}})}),0)}.bind(c),h(),c}t.exports=p},{buffer:17,duplexify:20,"readable-stream":69}],7:[function(e,t,n){function r(){if(!(this instanceof r))return new r;this.nextId=Math.max(1,Math.floor(65535*Math.random()))}r.prototype.allocate=function(){const e=this.nextId++;return 65536===this.nextId&&(this.nextId=1),e},r.prototype.getLastAllocated=function(){return 1===this.nextId?65535:this.nextId-1},r.prototype.register=function(e){return!0},r.prototype.deallocate=function(e){},r.prototype.clear=function(){},t.exports=r},{}],8:[function(e,t,n){const r=e("xtend"),s=e("readable-stream").Readable,a={objectMode:!0},o={clean:!0};function i(e){if(!(this instanceof i))return new i(e);this.options=e||{},this.options=r(o,e),this._inflights=new Map}i.prototype.put=function(e,t){return this._inflights.set(e.messageId,e),t&&t(),this},i.prototype.createStream=function(){const e=new s(a),t=[];let n=!1,r=0;return this._inflights.forEach((function(e,n){t.push(e)})),e._read=function(){!n&&r<t.length?this.push(t[r++]):this.push(null)},e.destroy=function(){if(n)return;const e=this;n=!0,setTimeout((function(){e.emit("close")}),0)},e},i.prototype.del=function(e,t){return(e=this._inflights.get(e.messageId))?(this._inflights.delete(e.messageId),t(null,e)):t&&t(new Error("missing packet")),this},i.prototype.get=function(e,t){return(e=this._inflights.get(e.messageId))?t(null,e):t&&t(new Error("missing packet")),this},i.prototype.close=function(e){this.options.clean&&(this._inflights=null),e&&e()},t.exports=i},{"readable-stream":69,xtend:81}],9:[function(e,t,n){function r(e){if(!(this instanceof r))return new r(e);this.aliasToTopic={},this.max=e}r.prototype.put=function(e,t){return!(0===t||t>this.max||(this.aliasToTopic[t]=e,this.length=Object.keys(this.aliasToTopic).length,0))},r.prototype.getTopicByAlias=function(e){return this.aliasToTopic[e]},r.prototype.clear=function(){this.aliasToTopic={}},t.exports=r},{}],10:[function(e,t,n){const r=e("lru-cache"),s=e("number-allocator").NumberAllocator;function a(e){if(!(this instanceof a))return new a(e);e>0&&(this.aliasToTopic=new r({max:e}),this.topicToAlias={},this.numberAllocator=new s(1,e),this.max=e,this.length=0)}a.prototype.put=function(e,t){if(0===t||t>this.max)return!1;const n=this.aliasToTopic.get(t);return n&&delete this.topicToAlias[n],this.aliasToTopic.set(t,e),this.topicToAlias[e]=t,this.numberAllocator.use(t),this.length=this.aliasToTopic.length,!0},a.prototype.getTopicByAlias=function(e){return this.aliasToTopic.get(e)},a.prototype.getAliasByTopic=function(e){const t=this.topicToAlias[e];return void 0!==t&&this.aliasToTopic.get(t),t},a.prototype.clear=function(){this.aliasToTopic.reset(),this.topicToAlias={},this.numberAllocator.clear(),this.length=0},a.prototype.getLruAlias=function(){const e=this.numberAllocator.firstVacant();return e||this.aliasToTopic.keys()[this.aliasToTopic.length-1]},t.exports=a},{"lru-cache":37,"number-allocator":46}],11:[function(e,t,n){function r(e){const t=e.split("/");for(let e=0;e<t.length;e++)if("+"!==t[e]){if("#"===t[e])return e===t.length-1;if(-1!==t[e].indexOf("+")||-1!==t[e].indexOf("#"))return!1}return!0}function s(e){if(0===e.length)return"empty_topic_list";for(let t=0;t<e.length;t++)if(!r(e[t]))return e[t];return null}t.exports={validateTopics:s}},{}],12:[function(e,t,n){(function(n){(function(){const r=e("../client"),s=e("../store"),a=e("url"),o=e("xtend"),i=e("debug")("mqttjs"),c={};function l(e){let t;e.auth&&(t=e.auth.match(/^(.+):(.+)$/),t?(e.username=t[1],e.password=t[2]):e.username=e.auth)}function d(e,t){if(i("connecting to an MQTT broker..."),"object"!=typeof e||t||(t=e,e=null),t=t||{},e){const n=a.parse(e,!0);if(null!=n.port&&(n.port=Number(n.port)),null===(t=o(n,t)).protocol)throw new Error("Missing protocol");t.protocol=t.protocol.replace(/:$/,"")}if(l(t),t.query&&"string"==typeof t.query.clientId&&(t.clientId=t.query.clientId),t.cert&&t.key){if(!t.protocol)throw new Error("Missing secure protocol key");if(-1===["mqtts","wss","wxs","alis"].indexOf(t.protocol))switch(t.protocol){case"mqtt":t.protocol="mqtts";break;case"ws":t.protocol="wss";break;case"wx":t.protocol="wxs";break;case"ali":t.protocol="alis";break;default:throw new Error('Unknown protocol for secure connection: "'+t.protocol+'"!')}}if(!c[t.protocol]){const e=-1!==["mqtts","wss"].indexOf(t.protocol);t.protocol=["mqtt","mqtts","ws","wss","wx","wxs","ali","alis"].filter((function(t,n){return(!e||n%2!=0)&&"function"==typeof c[t]}))[0]}if(!1===t.clean&&!t.clientId)throw new Error("Missing clientId for unclean clients");function n(e){return t.servers&&(e._reconnectCount&&e._reconnectCount!==t.servers.length||(e._reconnectCount=0),t.host=t.servers[e._reconnectCount].host,t.port=t.servers[e._reconnectCount].port,t.protocol=t.servers[e._reconnectCount].protocol?t.servers[e._reconnectCount].protocol:t.defaultProtocol,t.hostname=t.host,e._reconnectCount++),i("calling streambuilder for",t.protocol),c[t.protocol](e,t)}t.protocol&&(t.defaultProtocol=t.protocol);const s=new r(n,t);return s.on("error",(function(){})),s}void 0!==n&&"browser"!==n.title||"function"!=typeof __webpack_require__?(c.mqtt=e("./tcp"),c.tcp=e("./tcp"),c.ssl=e("./tls"),c.tls=e("./tls"),c.mqtts=e("./tls")):(c.wx=e("./wx"),c.wxs=e("./wx"),c.ali=e("./ali"),c.alis=e("./ali")),c.ws=e("./ws"),c.wss=e("./ws"),t.exports=d,t.exports.connect=d,t.exports.MqttClient=r,t.exports.Store=s}).call(this)}).call(this,e("_process"))},{"../client":1,"../store":8,"./ali":2,"./tcp":3,"./tls":4,"./ws":5,"./wx":6,_process:50,debug:18,url:76,xtend:81}],13:[function(e,t,n){n.byteLength=d,n.toByteArray=h,n.fromByteArray=m;for(var r=[],s=[],a="undefined"!=typeof Uint8Array?Uint8Array:Array,o="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",i=0,c=o.length;i<c;++i)r[i]=o[i],s[o.charCodeAt(i)]=i;function l(e){var t=e.length;if(t%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var n=e.indexOf("=");return-1===n&&(n=t),[n,n===t?0:4-n%4]}function d(e){var t=l(e),n=t[0],r=t[1];return 3*(n+r)/4-r}function u(e,t,n){return 3*(t+n)/4-n}function h(e){var t,n,r=l(e),o=r[0],i=r[1],c=new a(u(e,o,i)),d=0,h=i>0?o-4:o;for(n=0;n<h;n+=4)t=s[e.charCodeAt(n)]<<18|s[e.charCodeAt(n+1)]<<12|s[e.charCodeAt(n+2)]<<6|s[e.charCodeAt(n+3)],c[d++]=t>>16&255,c[d++]=t>>8&255,c[d++]=255&t;return 2===i&&(t=s[e.charCodeAt(n)]<<2|s[e.charCodeAt(n+1)]>>4,c[d++]=255&t),1===i&&(t=s[e.charCodeAt(n)]<<10|s[e.charCodeAt(n+1)]<<4|s[e.charCodeAt(n+2)]>>2,c[d++]=t>>8&255,c[d++]=255&t),c}function p(e){return r[e>>18&63]+r[e>>12&63]+r[e>>6&63]+r[63&e]}function f(e,t,n){for(var r,s=[],a=t;a<n;a+=3)r=(e[a]<<16&16711680)+(e[a+1]<<8&65280)+(255&e[a+2]),s.push(p(r));return s.join("")}function m(e){for(var t,n=e.length,s=n%3,a=[],o=16383,i=0,c=n-s;i<c;i+=o)a.push(f(e,i,i+o>c?c:i+o));return 1===s?(t=e[n-1],a.push(r[t>>2]+r[t<<4&63]+"==")):2===s&&(t=(e[n-2]<<8)+e[n-1],a.push(r[t>>10]+r[t>>4&63]+r[t<<2&63]+"=")),a.join("")}s["-".charCodeAt(0)]=62,s["_".charCodeAt(0)]=63},{}],14:[function(e,t,n){const{Buffer:r}=e("buffer"),s=Symbol.for("BufferList");function a(e){if(!(this instanceof a))return new a(e);a._init.call(this,e)}a._init=function(e){Object.defineProperty(this,s,{value:!0}),this._bufs=[],this.length=0,e&&this.append(e)},a.prototype._new=function(e){return new a(e)},a.prototype._offset=function(e){if(0===e)return[0,0];let t=0;for(let n=0;n<this._bufs.length;n++){const r=t+this._bufs[n].length;if(e<r||n===this._bufs.length-1)return[n,e-t];t=r}},a.prototype._reverseOffset=function(e){const t=e[0];let n=e[1];for(let e=0;e<t;e++)n+=this._bufs[e].length;return n},a.prototype.get=function(e){if(e>this.length||e<0)return;const t=this._offset(e);return this._bufs[t[0]][t[1]]},a.prototype.slice=function(e,t){return"number"==typeof e&&e<0&&(e+=this.length),"number"==typeof t&&t<0&&(t+=this.length),this.copy(null,0,e,t)},a.prototype.copy=function(e,t,n,s){if(("number"!=typeof n||n<0)&&(n=0),("number"!=typeof s||s>this.length)&&(s=this.length),n>=this.length)return e||r.alloc(0);if(s<=0)return e||r.alloc(0);const a=!!e,o=this._offset(n),i=s-n;let c=i,l=a&&t||0,d=o[1];if(0===n&&s===this.length){if(!a)return 1===this._bufs.length?this._bufs[0]:r.concat(this._bufs,this.length);for(let t=0;t<this._bufs.length;t++)this._bufs[t].copy(e,l),l+=this._bufs[t].length;return e}if(c<=this._bufs[o[0]].length-d)return a?this._bufs[o[0]].copy(e,t,d,d+c):this._bufs[o[0]].slice(d,d+c);a||(e=r.allocUnsafe(i));for(let t=o[0];t<this._bufs.length;t++){const n=this._bufs[t].length-d;if(!(c>n)){this._bufs[t].copy(e,l,d,d+c),l+=n;break}this._bufs[t].copy(e,l,d),l+=n,c-=n,d&&(d=0)}return e.length>l?e.slice(0,l):e},a.prototype.shallowSlice=function(e,t){if(e=e||0,t="number"!=typeof t?this.length:t,e<0&&(e+=this.length),t<0&&(t+=this.length),e===t)return this._new();const n=this._offset(e),r=this._offset(t),s=this._bufs.slice(n[0],r[0]+1);return 0===r[1]?s.pop():s[s.length-1]=s[s.length-1].slice(0,r[1]),0!==n[1]&&(s[0]=s[0].slice(n[1])),this._new(s)},a.prototype.toString=function(e,t,n){return this.slice(t,n).toString(e)},a.prototype.consume=function(e){if(e=Math.trunc(e),Number.isNaN(e)||e<=0)return this;for(;this._bufs.length;){if(!(e>=this._bufs[0].length)){this._bufs[0]=this._bufs[0].slice(e),this.length-=e;break}e-=this._bufs[0].length,this.length-=this._bufs[0].length,this._bufs.shift()}return this},a.prototype.duplicate=function(){const e=this._new();for(let t=0;t<this._bufs.length;t++)e.append(this._bufs[t]);return e},a.prototype.append=function(e){if(null==e)return this;if(e.buffer)this._appendBuffer(r.from(e.buffer,e.byteOffset,e.byteLength));else if(Array.isArray(e))for(let t=0;t<e.length;t++)this.append(e[t]);else if(this._isBufferList(e))for(let t=0;t<e._bufs.length;t++)this.append(e._bufs[t]);else"number"==typeof e&&(e=e.toString()),this._appendBuffer(r.from(e));return this},a.prototype._appendBuffer=function(e){this._bufs.push(e),this.length+=e.length},a.prototype.indexOf=function(e,t,n){if(void 0===n&&"string"==typeof t&&(n=t,t=void 0),"function"==typeof e||Array.isArray(e))throw new TypeError('The "value" argument must be one of type string, Buffer, BufferList, or Uint8Array.');if("number"==typeof e?e=r.from([e]):"string"==typeof e?e=r.from(e,n):this._isBufferList(e)?e=e.slice():Array.isArray(e.buffer)?e=r.from(e.buffer,e.byteOffset,e.byteLength):r.isBuffer(e)||(e=r.from(e)),t=Number(t||0),isNaN(t)&&(t=0),t<0&&(t=this.length+t),t<0&&(t=0),0===e.length)return t>this.length?this.length:t;const s=this._offset(t);let a=s[0],o=s[1];for(;a<this._bufs.length;a++){const t=this._bufs[a];for(;o<t.length;)if(t.length-o>=e.length){const n=t.indexOf(e,o);if(-1!==n)return this._reverseOffset([a,n]);o=t.length-e.length+1}else{const t=this._reverseOffset([a,o]);if(this._match(t,e))return t;o++}o=0}return-1},a.prototype._match=function(e,t){if(this.length-e<t.length)return!1;for(let n=0;n<t.length;n++)if(this.get(e+n)!==t[n])return!1;return!0},function(){const e={readDoubleBE:8,readDoubleLE:8,readFloatBE:4,readFloatLE:4,readInt32BE:4,readInt32LE:4,readUInt32BE:4,readUInt32LE:4,readInt16BE:2,readInt16LE:2,readUInt16BE:2,readUInt16LE:2,readInt8:1,readUInt8:1,readIntBE:null,readIntLE:null,readUIntBE:null,readUIntLE:null};for(const t in e)!function(t){null===e[t]?a.prototype[t]=function(e,n){return this.slice(e,e+n)[t](0,n)}:a.prototype[t]=function(n=0){return this.slice(n,n+e[t])[t](0)}}(t)}(),a.prototype._isBufferList=function(e){return e instanceof a||a.isBufferList(e)},a.isBufferList=function(e){return null!=e&&e[s]},t.exports=a},{buffer:17}],15:[function(e,t,n){const r=e("readable-stream").Duplex,s=e("inherits"),a=e("./BufferList");function o(e){if(!(this instanceof o))return new o(e);if("function"==typeof e){this._callback=e;const t=function(e){this._callback&&(this._callback(e),this._callback=null)}.bind(this);this.on("pipe",(function(e){e.on("error",t)})),this.on("unpipe",(function(e){e.removeListener("error",t)})),e=null}a._init.call(this,e),r.call(this)}s(o,r),Object.assign(o.prototype,a.prototype),o.prototype._new=function(e){return new o(e)},o.prototype._write=function(e,t,n){this._appendBuffer(e),"function"==typeof n&&n()},o.prototype._read=function(e){if(!this.length)return this.push(null);e=Math.min(e,this.length),this.push(this.slice(0,e)),this.consume(e)},o.prototype.end=function(e){r.prototype.end.call(this,e),this._callback&&(this._callback(null,this.slice()),this._callback=null)},o.prototype._destroy=function(e,t){this._bufs.length=0,this.length=0,t(e)},o.prototype._isBufferList=function(e){return e instanceof o||e instanceof a||o.isBufferList(e)},o.isBufferList=a.isBufferList,t.exports=o,t.exports.BufferListStream=o,t.exports.BufferList=a},{"./BufferList":14,inherits:24,"readable-stream":69}],16:[function(e,t,n){},{}],17:[function(e,t,n){(function(t){(function(){var t=e("base64-js"),r=e("ieee754");n.Buffer=i,n.SlowBuffer=y,n.INSPECT_MAX_BYTES=50;var s=2147483647;function a(){try{var e=new Uint8Array(1);return e.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}},42===e.foo()}catch(e){return!1}}function o(e){if(e>s)throw new RangeError('The value "'+e+'" is invalid for option "size"');var t=new Uint8Array(e);return t.__proto__=i.prototype,t}function i(e,t,n){if("number"==typeof e){if("string"==typeof t)throw new TypeError('The "string" argument must be of type string. Received type number');return u(e)}return c(e,t,n)}function c(e,t,n){if("string"==typeof e)return h(e,t);if(ArrayBuffer.isView(e))return p(e);if(null==e)throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e);if(G(e,ArrayBuffer)||e&&G(e.buffer,ArrayBuffer))return f(e,t,n);if("number"==typeof e)throw new TypeError('The "value" argument must not be of type number. Received type number');var r=e.valueOf&&e.valueOf();if(null!=r&&r!==e)return i.from(r,t,n);var s=m(e);if(s)return s;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof e[Symbol.toPrimitive])return i.from(e[Symbol.toPrimitive]("string"),t,n);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e)}function l(e){if("number"!=typeof e)throw new TypeError('"size" argument must be of type number');if(e<0)throw new RangeError('The value "'+e+'" is invalid for option "size"')}function d(e,t,n){return l(e),e<=0?o(e):void 0!==t?"string"==typeof n?o(e).fill(t,n):o(e).fill(t):o(e)}function u(e){return l(e),o(e<0?0:0|g(e))}function h(e,t){if("string"==typeof t&&""!==t||(t="utf8"),!i.isEncoding(t))throw new TypeError("Unknown encoding: "+t);var n=0|v(e,t),r=o(n),s=r.write(e,t);return s!==n&&(r=r.slice(0,s)),r}function p(e){for(var t=e.length<0?0:0|g(e.length),n=o(t),r=0;r<t;r+=1)n[r]=255&e[r];return n}function f(e,t,n){if(t<0||e.byteLength<t)throw new RangeError('"offset" is outside of buffer bounds');if(e.byteLength<t+(n||0))throw new RangeError('"length" is outside of buffer bounds');var r;return(r=void 0===t&&void 0===n?new Uint8Array(e):void 0===n?new Uint8Array(e,t):new Uint8Array(e,t,n)).__proto__=i.prototype,r}function m(e){if(i.isBuffer(e)){var t=0|g(e.length),n=o(t);return 0===n.length||e.copy(n,0,0,t),n}return void 0!==e.length?"number"!=typeof e.length||Y(e.length)?o(0):p(e):"Buffer"===e.type&&Array.isArray(e.data)?p(e.data):void 0}function g(e){if(e>=s)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+s.toString(16)+" bytes");return 0|e}function y(e){return+e!=e&&(e=0),i.alloc(+e)}function v(e,t){if(i.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||G(e,ArrayBuffer))return e.byteLength;if("string"!=typeof e)throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof e);var n=e.length,r=arguments.length>2&&!0===arguments[2];if(!r&&0===n)return 0;for(var s=!1;;)switch(t){case"ascii":case"latin1":case"binary":return n;case"utf8":case"utf-8":return Q(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*n;case"hex":return n>>>1;case"base64":return W(e).length;default:if(s)return r?-1:Q(e).length;t=(""+t).toLowerCase(),s=!0}}function b(e,t,n){var r=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===n||n>this.length)&&(n=this.length),n<=0)return"";if((n>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return x(this,t,n);case"utf8":case"utf-8":return M(this,t,n);case"ascii":return j(this,t,n);case"latin1":case"binary":return U(this,t,n);case"base64":return E(this,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return D(this,t,n);default:if(r)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),r=!0}}function w(e,t,n){var r=e[t];e[t]=e[n],e[n]=r}function C(e,t,n,r,s){if(0===e.length)return-1;if("string"==typeof n?(r=n,n=0):n>2147483647?n=2147483647:n<-2147483648&&(n=-2147483648),Y(n=+n)&&(n=s?0:e.length-1),n<0&&(n=e.length+n),n>=e.length){if(s)return-1;n=e.length-1}else if(n<0){if(!s)return-1;n=0}if("string"==typeof t&&(t=i.from(t,r)),i.isBuffer(t))return 0===t.length?-1:I(e,t,n,r,s);if("number"==typeof t)return t&=255,"function"==typeof Uint8Array.prototype.indexOf?s?Uint8Array.prototype.indexOf.call(e,t,n):Uint8Array.prototype.lastIndexOf.call(e,t,n):I(e,[t],n,r,s);throw new TypeError("val must be string, number or Buffer")}function I(e,t,n,r,s){var a,o=1,i=e.length,c=t.length;if(void 0!==r&&("ucs2"===(r=String(r).toLowerCase())||"ucs-2"===r||"utf16le"===r||"utf-16le"===r)){if(e.length<2||t.length<2)return-1;o=2,i/=2,c/=2,n/=2}function l(e,t){return 1===o?e[t]:e.readUInt16BE(t*o)}if(s){var d=-1;for(a=n;a<i;a++)if(l(e,a)===l(t,-1===d?0:a-d)){if(-1===d&&(d=a),a-d+1===c)return d*o}else-1!==d&&(a-=a-d),d=-1}else for(n+c>i&&(n=i-c),a=n;a>=0;a--){for(var u=!0,h=0;h<c;h++)if(l(e,a+h)!==l(t,h)){u=!1;break}if(u)return a}return-1}function S(e,t,n,r){n=Number(n)||0;var s=e.length-n;r?(r=Number(r))>s&&(r=s):r=s;var a=t.length;r>a/2&&(r=a/2);for(var o=0;o<r;++o){var i=parseInt(t.substr(2*o,2),16);if(Y(i))return o;e[n+o]=i}return o}function _(e,t,n,r){return J(Q(t,e.length-n),e,n,r)}function k(e,t,n,r){return J(V(t),e,n,r)}function T(e,t,n,r){return k(e,t,n,r)}function O(e,t,n,r){return J(W(t),e,n,r)}function A(e,t,n,r){return J(H(t,e.length-n),e,n,r)}function E(e,n,r){return 0===n&&r===e.length?t.fromByteArray(e):t.fromByteArray(e.slice(n,r))}function M(e,t,n){n=Math.min(e.length,n);for(var r=[],s=t;s<n;){var a,o,i,c,l=e[s],d=null,u=l>239?4:l>223?3:l>191?2:1;if(s+u<=n)switch(u){case 1:l<128&&(d=l);break;case 2:128==(192&(a=e[s+1]))&&(c=(31&l)<<6|63&a)>127&&(d=c);break;case 3:a=e[s+1],o=e[s+2],128==(192&a)&&128==(192&o)&&(c=(15&l)<<12|(63&a)<<6|63&o)>2047&&(c<55296||c>57343)&&(d=c);break;case 4:a=e[s+1],o=e[s+2],i=e[s+3],128==(192&a)&&128==(192&o)&&128==(192&i)&&(c=(15&l)<<18|(63&a)<<12|(63&o)<<6|63&i)>65535&&c<1114112&&(d=c)}null===d?(d=65533,u=1):d>65535&&(d-=65536,r.push(d>>>10&1023|55296),d=56320|1023&d),r.push(d),s+=u}return P(r)}n.kMaxLength=s,i.TYPED_ARRAY_SUPPORT=a(),i.TYPED_ARRAY_SUPPORT||"undefined"==typeof console||"function"!=typeof console.error||console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support."),Object.defineProperty(i.prototype,"parent",{enumerable:!0,get:function(){if(i.isBuffer(this))return this.buffer}}),Object.defineProperty(i.prototype,"offset",{enumerable:!0,get:function(){if(i.isBuffer(this))return this.byteOffset}}),"undefined"!=typeof Symbol&&null!=Symbol.species&&i[Symbol.species]===i&&Object.defineProperty(i,Symbol.species,{value:null,configurable:!0,enumerable:!1,writable:!1}),i.poolSize=8192,i.from=function(e,t,n){return c(e,t,n)},i.prototype.__proto__=Uint8Array.prototype,i.__proto__=Uint8Array,i.alloc=function(e,t,n){return d(e,t,n)},i.allocUnsafe=function(e){return u(e)},i.allocUnsafeSlow=function(e){return u(e)},i.isBuffer=function(e){return null!=e&&!0===e._isBuffer&&e!==i.prototype},i.compare=function(e,t){if(G(e,Uint8Array)&&(e=i.from(e,e.offset,e.byteLength)),G(t,Uint8Array)&&(t=i.from(t,t.offset,t.byteLength)),!i.isBuffer(e)||!i.isBuffer(t))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(e===t)return 0;for(var n=e.length,r=t.length,s=0,a=Math.min(n,r);s<a;++s)if(e[s]!==t[s]){n=e[s],r=t[s];break}return n<r?-1:r<n?1:0},i.isEncoding=function(e){switch(String(e).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},i.concat=function(e,t){if(!Array.isArray(e))throw new TypeError('"list" argument must be an Array of Buffers');if(0===e.length)return i.alloc(0);var n;if(void 0===t)for(t=0,n=0;n<e.length;++n)t+=e[n].length;var r=i.allocUnsafe(t),s=0;for(n=0;n<e.length;++n){var a=e[n];if(G(a,Uint8Array)&&(a=i.from(a)),!i.isBuffer(a))throw new TypeError('"list" argument must be an Array of Buffers');a.copy(r,s),s+=a.length}return r},i.byteLength=v,i.prototype._isBuffer=!0,i.prototype.swap16=function(){var e=this.length;if(e%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(var t=0;t<e;t+=2)w(this,t,t+1);return this},i.prototype.swap32=function(){var e=this.length;if(e%4!=0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(var t=0;t<e;t+=4)w(this,t,t+3),w(this,t+1,t+2);return this},i.prototype.swap64=function(){var e=this.length;if(e%8!=0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(var t=0;t<e;t+=8)w(this,t,t+7),w(this,t+1,t+6),w(this,t+2,t+5),w(this,t+3,t+4);return this},i.prototype.toString=function(){var e=this.length;return 0===e?"":0===arguments.length?M(this,0,e):b.apply(this,arguments)},i.prototype.toLocaleString=i.prototype.toString,i.prototype.equals=function(e){if(!i.isBuffer(e))throw new TypeError("Argument must be a Buffer");return this===e||0===i.compare(this,e)},i.prototype.inspect=function(){var e="",t=n.INSPECT_MAX_BYTES;return e=this.toString("hex",0,t).replace(/(.{2})/g,"$1 ").trim(),this.length>t&&(e+=" ... "),"<Buffer "+e+">"},i.prototype.compare=function(e,t,n,r,s){if(G(e,Uint8Array)&&(e=i.from(e,e.offset,e.byteLength)),!i.isBuffer(e))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof e);if(void 0===t&&(t=0),void 0===n&&(n=e?e.length:0),void 0===r&&(r=0),void 0===s&&(s=this.length),t<0||n>e.length||r<0||s>this.length)throw new RangeError("out of range index");if(r>=s&&t>=n)return 0;if(r>=s)return-1;if(t>=n)return 1;if(this===e)return 0;for(var a=(s>>>=0)-(r>>>=0),o=(n>>>=0)-(t>>>=0),c=Math.min(a,o),l=this.slice(r,s),d=e.slice(t,n),u=0;u<c;++u)if(l[u]!==d[u]){a=l[u],o=d[u];break}return a<o?-1:o<a?1:0},i.prototype.includes=function(e,t,n){return-1!==this.indexOf(e,t,n)},i.prototype.indexOf=function(e,t,n){return C(this,e,t,n,!0)},i.prototype.lastIndexOf=function(e,t,n){return C(this,e,t,n,!1)},i.prototype.write=function(e,t,n,r){if(void 0===t)r="utf8",n=this.length,t=0;else if(void 0===n&&"string"==typeof t)r=t,n=this.length,t=0;else{if(!isFinite(t))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");t>>>=0,isFinite(n)?(n>>>=0,void 0===r&&(r="utf8")):(r=n,n=void 0)}var s=this.length-t;if((void 0===n||n>s)&&(n=s),e.length>0&&(n<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");r||(r="utf8");for(var a=!1;;)switch(r){case"hex":return S(this,e,t,n);case"utf8":case"utf-8":return _(this,e,t,n);case"ascii":return k(this,e,t,n);case"latin1":case"binary":return T(this,e,t,n);case"base64":return O(this,e,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return A(this,e,t,n);default:if(a)throw new TypeError("Unknown encoding: "+r);r=(""+r).toLowerCase(),a=!0}},i.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var R=4096;function P(e){var t=e.length;if(t<=R)return String.fromCharCode.apply(String,e);for(var n="",r=0;r<t;)n+=String.fromCharCode.apply(String,e.slice(r,r+=R));return n}function j(e,t,n){var r="";n=Math.min(e.length,n);for(var s=t;s<n;++s)r+=String.fromCharCode(127&e[s]);return r}function U(e,t,n){var r="";n=Math.min(e.length,n);for(var s=t;s<n;++s)r+=String.fromCharCode(e[s]);return r}function x(e,t,n){var r=e.length;(!t||t<0)&&(t=0),(!n||n<0||n>r)&&(n=r);for(var s="",a=t;a<n;++a)s+=z(e[a]);return s}function D(e,t,n){for(var r=e.slice(t,n),s="",a=0;a<r.length;a+=2)s+=String.fromCharCode(r[a]+256*r[a+1]);return s}function N(e,t,n){if(e%1!=0||e<0)throw new RangeError("offset is not uint");if(e+t>n)throw new RangeError("Trying to access beyond buffer length")}function B(e,t,n,r,s,a){if(!i.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>s||t<a)throw new RangeError('"value" argument is out of bounds');if(n+r>e.length)throw new RangeError("Index out of range")}function q(e,t,n,r,s,a){if(n+r>e.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("Index out of range")}function F(e,t,n,s,a){return t=+t,n>>>=0,a||q(e,t,n,4),r.write(e,t,n,s,23,4),n+4}function L(e,t,n,s,a){return t=+t,n>>>=0,a||q(e,t,n,8),r.write(e,t,n,s,52,8),n+8}i.prototype.slice=function(e,t){var n=this.length;(e=~~e)<0?(e+=n)<0&&(e=0):e>n&&(e=n),(t=void 0===t?n:~~t)<0?(t+=n)<0&&(t=0):t>n&&(t=n),t<e&&(t=e);var r=this.subarray(e,t);return r.__proto__=i.prototype,r},i.prototype.readUIntLE=function(e,t,n){e>>>=0,t>>>=0,n||N(e,t,this.length);for(var r=this[e],s=1,a=0;++a<t&&(s*=256);)r+=this[e+a]*s;return r},i.prototype.readUIntBE=function(e,t,n){e>>>=0,t>>>=0,n||N(e,t,this.length);for(var r=this[e+--t],s=1;t>0&&(s*=256);)r+=this[e+--t]*s;return r},i.prototype.readUInt8=function(e,t){return e>>>=0,t||N(e,1,this.length),this[e]},i.prototype.readUInt16LE=function(e,t){return e>>>=0,t||N(e,2,this.length),this[e]|this[e+1]<<8},i.prototype.readUInt16BE=function(e,t){return e>>>=0,t||N(e,2,this.length),this[e]<<8|this[e+1]},i.prototype.readUInt32LE=function(e,t){return e>>>=0,t||N(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},i.prototype.readUInt32BE=function(e,t){return e>>>=0,t||N(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},i.prototype.readIntLE=function(e,t,n){e>>>=0,t>>>=0,n||N(e,t,this.length);for(var r=this[e],s=1,a=0;++a<t&&(s*=256);)r+=this[e+a]*s;return r>=(s*=128)&&(r-=Math.pow(2,8*t)),r},i.prototype.readIntBE=function(e,t,n){e>>>=0,t>>>=0,n||N(e,t,this.length);for(var r=t,s=1,a=this[e+--r];r>0&&(s*=256);)a+=this[e+--r]*s;return a>=(s*=128)&&(a-=Math.pow(2,8*t)),a},i.prototype.readInt8=function(e,t){return e>>>=0,t||N(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},i.prototype.readInt16LE=function(e,t){e>>>=0,t||N(e,2,this.length);var n=this[e]|this[e+1]<<8;return 32768&n?4294901760|n:n},i.prototype.readInt16BE=function(e,t){e>>>=0,t||N(e,2,this.length);var n=this[e+1]|this[e]<<8;return 32768&n?4294901760|n:n},i.prototype.readInt32LE=function(e,t){return e>>>=0,t||N(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},i.prototype.readInt32BE=function(e,t){return e>>>=0,t||N(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},i.prototype.readFloatLE=function(e,t){return e>>>=0,t||N(e,4,this.length),r.read(this,e,!0,23,4)},i.prototype.readFloatBE=function(e,t){return e>>>=0,t||N(e,4,this.length),r.read(this,e,!1,23,4)},i.prototype.readDoubleLE=function(e,t){return e>>>=0,t||N(e,8,this.length),r.read(this,e,!0,52,8)},i.prototype.readDoubleBE=function(e,t){return e>>>=0,t||N(e,8,this.length),r.read(this,e,!1,52,8)},i.prototype.writeUIntLE=function(e,t,n,r){e=+e,t>>>=0,n>>>=0,r||B(this,e,t,n,Math.pow(2,8*n)-1,0);var s=1,a=0;for(this[t]=255&e;++a<n&&(s*=256);)this[t+a]=e/s&255;return t+n},i.prototype.writeUIntBE=function(e,t,n,r){e=+e,t>>>=0,n>>>=0,r||B(this,e,t,n,Math.pow(2,8*n)-1,0);var s=n-1,a=1;for(this[t+s]=255&e;--s>=0&&(a*=256);)this[t+s]=e/a&255;return t+n},i.prototype.writeUInt8=function(e,t,n){return e=+e,t>>>=0,n||B(this,e,t,1,255,0),this[t]=255&e,t+1},i.prototype.writeUInt16LE=function(e,t,n){return e=+e,t>>>=0,n||B(this,e,t,2,65535,0),this[t]=255&e,this[t+1]=e>>>8,t+2},i.prototype.writeUInt16BE=function(e,t,n){return e=+e,t>>>=0,n||B(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=255&e,t+2},i.prototype.writeUInt32LE=function(e,t,n){return e=+e,t>>>=0,n||B(this,e,t,4,4294967295,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e,t+4},i.prototype.writeUInt32BE=function(e,t,n){return e=+e,t>>>=0,n||B(this,e,t,4,4294967295,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},i.prototype.writeIntLE=function(e,t,n,r){if(e=+e,t>>>=0,!r){var s=Math.pow(2,8*n-1);B(this,e,t,n,s-1,-s)}var a=0,o=1,i=0;for(this[t]=255&e;++a<n&&(o*=256);)e<0&&0===i&&0!==this[t+a-1]&&(i=1),this[t+a]=(e/o>>0)-i&255;return t+n},i.prototype.writeIntBE=function(e,t,n,r){if(e=+e,t>>>=0,!r){var s=Math.pow(2,8*n-1);B(this,e,t,n,s-1,-s)}var a=n-1,o=1,i=0;for(this[t+a]=255&e;--a>=0&&(o*=256);)e<0&&0===i&&0!==this[t+a+1]&&(i=1),this[t+a]=(e/o>>0)-i&255;return t+n},i.prototype.writeInt8=function(e,t,n){return e=+e,t>>>=0,n||B(this,e,t,1,127,-128),e<0&&(e=255+e+1),this[t]=255&e,t+1},i.prototype.writeInt16LE=function(e,t,n){return e=+e,t>>>=0,n||B(this,e,t,2,32767,-32768),this[t]=255&e,this[t+1]=e>>>8,t+2},i.prototype.writeInt16BE=function(e,t,n){return e=+e,t>>>=0,n||B(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=255&e,t+2},i.prototype.writeInt32LE=function(e,t,n){return e=+e,t>>>=0,n||B(this,e,t,4,2147483647,-2147483648),this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4},i.prototype.writeInt32BE=function(e,t,n){return e=+e,t>>>=0,n||B(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},i.prototype.writeFloatLE=function(e,t,n){return F(this,e,t,!0,n)},i.prototype.writeFloatBE=function(e,t,n){return F(this,e,t,!1,n)},i.prototype.writeDoubleLE=function(e,t,n){return L(this,e,t,!0,n)},i.prototype.writeDoubleBE=function(e,t,n){return L(this,e,t,!1,n)},i.prototype.copy=function(e,t,n,r){if(!i.isBuffer(e))throw new TypeError("argument should be a Buffer");if(n||(n=0),r||0===r||(r=this.length),t>=e.length&&(t=e.length),t||(t=0),r>0&&r<n&&(r=n),r===n)return 0;if(0===e.length||0===this.length)return 0;if(t<0)throw new RangeError("targetStart out of bounds");if(n<0||n>=this.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("sourceEnd out of bounds");r>this.length&&(r=this.length),e.length-t<r-n&&(r=e.length-t+n);var s=r-n;if(this===e&&"function"==typeof Uint8Array.prototype.copyWithin)this.copyWithin(t,n,r);else if(this===e&&n<t&&t<r)for(var a=s-1;a>=0;--a)e[a+t]=this[a+n];else Uint8Array.prototype.set.call(e,this.subarray(n,r),t);return s},i.prototype.fill=function(e,t,n,r){if("string"==typeof e){if("string"==typeof t?(r=t,t=0,n=this.length):"string"==typeof n&&(r=n,n=this.length),void 0!==r&&"string"!=typeof r)throw new TypeError("encoding must be a string");if("string"==typeof r&&!i.isEncoding(r))throw new TypeError("Unknown encoding: "+r);if(1===e.length){var s=e.charCodeAt(0);("utf8"===r&&s<128||"latin1"===r)&&(e=s)}}else"number"==typeof e&&(e&=255);if(t<0||this.length<t||this.length<n)throw new RangeError("Out of range index");if(n<=t)return this;var a;if(t>>>=0,n=void 0===n?this.length:n>>>0,e||(e=0),"number"==typeof e)for(a=t;a<n;++a)this[a]=e;else{var o=i.isBuffer(e)?e:i.from(e,r),c=o.length;if(0===c)throw new TypeError('The value "'+e+'" is invalid for argument "value"');for(a=0;a<n-t;++a)this[a+t]=o[a%c]}return this};var K=/[^+/0-9A-Za-z-_]/g;function $(e){if((e=(e=e.split("=")[0]).trim().replace(K,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}function z(e){return e<16?"0"+e.toString(16):e.toString(16)}function Q(e,t){var n;t=t||1/0;for(var r=e.length,s=null,a=[],o=0;o<r;++o){if((n=e.charCodeAt(o))>55295&&n<57344){if(!s){if(n>56319){(t-=3)>-1&&a.push(239,191,189);continue}if(o+1===r){(t-=3)>-1&&a.push(239,191,189);continue}s=n;continue}if(n<56320){(t-=3)>-1&&a.push(239,191,189),s=n;continue}n=65536+(s-55296<<10|n-56320)}else s&&(t-=3)>-1&&a.push(239,191,189);if(s=null,n<128){if((t-=1)<0)break;a.push(n)}else if(n<2048){if((t-=2)<0)break;a.push(n>>6|192,63&n|128)}else if(n<65536){if((t-=3)<0)break;a.push(n>>12|224,n>>6&63|128,63&n|128)}else{if(!(n<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;a.push(n>>18|240,n>>12&63|128,n>>6&63|128,63&n|128)}}return a}function V(e){for(var t=[],n=0;n<e.length;++n)t.push(255&e.charCodeAt(n));return t}function H(e,t){for(var n,r,s,a=[],o=0;o<e.length&&!((t-=2)<0);++o)r=(n=e.charCodeAt(o))>>8,s=n%256,a.push(s),a.push(r);return a}function W(e){return t.toByteArray($(e))}function J(e,t,n,r){for(var s=0;s<r&&!(s+n>=t.length||s>=e.length);++s)t[s+n]=e[s];return s}function G(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}function Y(e){return e!=e}}).call(this)}).call(this,e("buffer").Buffer)},{"base64-js":13,buffer:17,ieee754:23}],18:[function(e,t,n){(function(r){(function(){function s(){return!("undefined"==typeof window||!window.process||"renderer"!==window.process.type&&!window.process.__nwjs)||("undefined"==typeof navigator||!navigator.userAgent||!navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))&&("undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/))}function a(e){if(e[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+e[0]+(this.useColors?"%c ":" ")+"+"+t.exports.humanize(this.diff),!this.useColors)return;const n="color: "+this.color;e.splice(1,0,n,"color: inherit");let r=0,s=0;e[0].replace(/%[a-zA-Z%]/g,(e=>{"%%"!==e&&(r++,"%c"===e&&(s=r))})),e.splice(s,0,n)}function o(e){try{e?n.storage.setItem("debug",e):n.storage.removeItem("debug")}catch(e){}}function i(){let e;try{e=n.storage.getItem("debug")}catch(e){}return!e&&void 0!==r&&"env"in r&&(e=r.env.DEBUG),e}function c(){try{return localStorage}catch(e){}}n.formatArgs=a,n.save=o,n.load=i,n.useColors=s,n.storage=c(),n.destroy=(()=>{let e=!1;return()=>{e||(e=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),n.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],n.log=console.debug||console.log||(()=>{}),t.exports=e("./common")(n);const{formatters:l}=t.exports;l.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}}).call(this)}).call(this,e("_process"))},{"./common":19,_process:50}],19:[function(e,t,n){function r(t){function n(e){let t=0;for(let n=0;n<e.length;n++)t=(t<<5)-t+e.charCodeAt(n),t|=0;return r.colors[Math.abs(t)%r.colors.length]}function r(e){let t,n,a,o=null;function i(...e){if(!i.enabled)return;const n=i,s=Number(new Date),a=s-(t||s);n.diff=a,n.prev=t,n.curr=s,t=s,e[0]=r.coerce(e[0]),"string"!=typeof e[0]&&e.unshift("%O");let o=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,((t,s)=>{if("%%"===t)return"%";o++;const a=r.formatters[s];if("function"==typeof a){const r=e[o];t=a.call(n,r),e.splice(o,1),o--}return t})),r.formatArgs.call(n,e),(n.log||r.log).apply(n,e)}return i.namespace=e,i.useColors=r.useColors(),i.color=r.selectColor(e),i.extend=s,i.destroy=r.destroy,Object.defineProperty(i,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==o?o:(n!==r.namespaces&&(n=r.namespaces,a=r.enabled(e)),a),set:e=>{o=e}}),"function"==typeof r.init&&r.init(i),i}function s(e,t){const n=r(this.namespace+(void 0===t?":":t)+e);return n.log=this.log,n}function a(e){let t;r.save(e),r.namespaces=e,r.names=[],r.skips=[];const n=("string"==typeof e?e:"").split(/[\s,]+/),s=n.length;for(t=0;t<s;t++)n[t]&&("-"===(e=n[t].replace(/\*/g,".*?"))[0]?r.skips.push(new RegExp("^"+e.substr(1)+"$")):r.names.push(new RegExp("^"+e+"$")))}function o(){const e=[...r.names.map(c),...r.skips.map(c).map((e=>"-"+e))].join(",");return r.enable(""),e}function i(e){if("*"===e[e.length-1])return!0;let t,n;for(t=0,n=r.skips.length;t<n;t++)if(r.skips[t].test(e))return!1;for(t=0,n=r.names.length;t<n;t++)if(r.names[t].test(e))return!0;return!1}function c(e){return e.toString().substring(2,e.toString().length-2).replace(/\.\*\?$/,"*")}function l(e){return e instanceof Error?e.stack||e.message:e}function d(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return r.debug=r,r.default=r,r.coerce=l,r.disable=o,r.enable=a,r.enabled=i,r.humanize=e("ms"),r.destroy=d,Object.keys(t).forEach((e=>{r[e]=t[e]})),r.names=[],r.skips=[],r.formatters={},r.selectColor=n,r.enable(r.load()),r}t.exports=r},{ms:45}],20:[function(e,t,n){(function(n,r){(function(){var s=e("readable-stream"),a=e("end-of-stream"),o=e("inherits"),i=e("stream-shift"),c=r.from&&r.from!==Uint8Array.from?r.from([0]):new r([0]),l=function(e,t){e._corked?e.once("uncork",t):t()},d=function(e,t){e._autoDestroy&&e.destroy(t)},u=function(e,t){return function(n){n?d(e,"premature close"===n.message?null:n):t&&!e._ended&&e.end()}},h=function(e,t){return e?e._writableState&&e._writableState.finished?t():e._writableState?e.end(t):(e.end(),void t()):t()},p=function(){},f=function(e){return new s.Readable({objectMode:!0,highWaterMark:16}).wrap(e)},m=function(e,t,n){if(!(this instanceof m))return new m(e,t,n);s.Duplex.call(this,n),this._writable=null,this._readable=null,this._readable2=null,this._autoDestroy=!n||!1!==n.autoDestroy,this._forwardDestroy=!n||!1!==n.destroy,this._forwardEnd=!n||!1!==n.end,this._corked=1,this._ondrain=null,this._drained=!1,this._forwarding=!1,this._unwrite=null,this._unread=null,this._ended=!1,this.destroyed=!1,e&&this.setWritable(e),t&&this.setReadable(t)};o(m,s.Duplex),m.obj=function(e,t,n){return n||(n={}),n.objectMode=!0,n.highWaterMark=16,new m(e,t,n)},m.prototype.cork=function(){1==++this._corked&&this.emit("cork")},m.prototype.uncork=function(){this._corked&&0==--this._corked&&this.emit("uncork")},m.prototype.setWritable=function(e){if(this._unwrite&&this._unwrite(),this.destroyed)e&&e.destroy&&e.destroy();else if(null!==e&&!1!==e){var t=this,r=a(e,{writable:!0,readable:!1},u(this,this._forwardEnd)),s=function(){var e=t._ondrain;t._ondrain=null,e&&e()},o=function(){t._writable.removeListener("drain",s),r()};this._unwrite&&n.nextTick(s),this._writable=e,this._writable.on("drain",s),this._unwrite=o,this.uncork()}else this.end()},m.prototype.setReadable=function(e){if(this._unread&&this._unread(),this.destroyed)e&&e.destroy&&e.destroy();else{if(null===e||!1===e)return this.push(null),void this.resume();var t=this,n=a(e,{writable:!1,readable:!0},u(this)),r=function(){t._forward()},s=function(){t.push(null)},o=function(){t._readable2.removeListener("readable",r),t._readable2.removeListener("end",s),n()};this._drained=!0,this._readable=e,this._readable2=e._readableState?e:f(e),this._readable2.on("readable",r),this._readable2.on("end",s),this._unread=o,this._forward()}},m.prototype._read=function(){this._drained=!0,this._forward()},m.prototype._forward=function(){if(!this._forwarding&&this._readable2&&this._drained){var e;for(this._forwarding=!0;this._drained&&null!==(e=i(this._readable2));)this.destroyed||(this._drained=this.push(e));this._forwarding=!1}},m.prototype.destroy=function(e,t){if(t||(t=p),this.destroyed)return t(null);this.destroyed=!0;var r=this;n.nextTick((function(){r._destroy(e),t(null)}))},m.prototype._destroy=function(e){if(e){var t=this._ondrain;this._ondrain=null,t?t(e):this.emit("error",e)}this._forwardDestroy&&(this._readable&&this._readable.destroy&&this._readable.destroy(),this._writable&&this._writable.destroy&&this._writable.destroy()),this.emit("close")},m.prototype._write=function(e,t,n){if(!this.destroyed)return this._corked?l(this,this._write.bind(this,e,t,n)):e===c?this._finish(n):this._writable?void(!1===this._writable.write(e)?this._ondrain=n:this.destroyed||n()):n()},m.prototype._finish=function(e){var t=this;this.emit("preend"),l(this,(function(){h(t._forwardEnd&&t._writable,(function(){!1===t._writableState.prefinished&&(t._writableState.prefinished=!0),t.emit("prefinish"),l(t,e)}))}))},m.prototype.end=function(e,t,n){return"function"==typeof e?this.end(null,null,e):"function"==typeof t?this.end(e,null,t):(this._ended=!0,e&&this.write(e),this._writableState.ending||this._writableState.destroyed||this.write(c),s.Writable.prototype.end.call(this,n))},t.exports=m}).call(this)}).call(this,e("_process"),e("buffer").Buffer)},{_process:50,buffer:17,"end-of-stream":21,inherits:24,"readable-stream":69,"stream-shift":74}],21:[function(e,t,n){(function(n){(function(){var r=e("once"),s=function(){},a=function(e){return e.setHeader&&"function"==typeof e.abort},o=function(e){return e.stdio&&Array.isArray(e.stdio)&&3===e.stdio.length},i=function(e,t,c){if("function"==typeof t)return i(e,null,t);t||(t={}),c=r(c||s);var l=e._writableState,d=e._readableState,u=t.readable||!1!==t.readable&&e.readable,h=t.writable||!1!==t.writable&&e.writable,p=!1,f=function(){e.writable||m()},m=function(){h=!1,u||c.call(e)},g=function(){u=!1,h||c.call(e)},y=function(t){c.call(e,t?new Error("exited with error code: "+t):null)},v=function(t){c.call(e,t)},b=function(){n.nextTick(w)},w=function(){if(!p)return(!u||d&&d.ended&&!d.destroyed)&&(!h||l&&l.ended&&!l.destroyed)?void 0:c.call(e,new Error("premature close"))},C=function(){e.req.on("finish",m)};return a(e)?(e.on("complete",m),e.on("abort",b),e.req?C():e.on("request",C)):h&&!l&&(e.on("end",f),e.on("close",f)),o(e)&&e.on("exit",y),e.on("end",g),e.on("finish",m),!1!==t.error&&e.on("error",v),e.on("close",b),function(){p=!0,e.removeListener("complete",m),e.removeListener("abort",b),e.removeListener("request",C),e.req&&e.req.removeListener("finish",m),e.removeListener("end",f),e.removeListener("close",f),e.removeListener("finish",m),e.removeListener("exit",y),e.removeListener("end",g),e.removeListener("error",v),e.removeListener("close",b)}};t.exports=i}).call(this)}).call(this,e("_process"))},{_process:50,once:48}],22:[function(e,t,n){var r=Object.create||_,s=Object.keys||k,a=Function.prototype.bind||T;function o(){this._events&&Object.prototype.hasOwnProperty.call(this,"_events")||(this._events=r(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0}t.exports=o,o.EventEmitter=o,o.prototype._events=void 0,o.prototype._maxListeners=void 0;var i,c=10;try{var l={};Object.defineProperty&&Object.defineProperty(l,"x",{value:0}),i=0===l.x}catch(e){i=!1}function d(e){return void 0===e._maxListeners?o.defaultMaxListeners:e._maxListeners}function u(e,t,n){if(t)e.call(n);else for(var r=e.length,s=I(e,r),a=0;a<r;++a)s[a].call(n)}function h(e,t,n,r){if(t)e.call(n,r);else for(var s=e.length,a=I(e,s),o=0;o<s;++o)a[o].call(n,r)}function p(e,t,n,r,s){if(t)e.call(n,r,s);else for(var a=e.length,o=I(e,a),i=0;i<a;++i)o[i].call(n,r,s)}function f(e,t,n,r,s,a){if(t)e.call(n,r,s,a);else for(var o=e.length,i=I(e,o),c=0;c<o;++c)i[c].call(n,r,s,a)}function m(e,t,n,r){if(t)e.apply(n,r);else for(var s=e.length,a=I(e,s),o=0;o<s;++o)a[o].apply(n,r)}function g(e,t,n,s){var a,o,i;if("function"!=typeof n)throw new TypeError('"listener" argument must be a function');if((o=e._events)?(o.newListener&&(e.emit("newListener",t,n.listener?n.listener:n),o=e._events),i=o[t]):(o=e._events=r(null),e._eventsCount=0),i){if("function"==typeof i?i=o[t]=s?[n,i]:[i,n]:s?i.unshift(n):i.push(n),!i.warned&&(a=d(e))&&a>0&&i.length>a){i.warned=!0;var c=new Error("Possible EventEmitter memory leak detected. "+i.length+' "'+String(t)+'" listeners added. Use emitter.setMaxListeners() to increase limit.');c.name="MaxListenersExceededWarning",c.emitter=e,c.type=t,c.count=i.length,"object"==typeof console&&console.warn&&console.warn("%s: %s",c.name,c.message)}}else i=o[t]=n,++e._eventsCount;return e}function y(){if(!this.fired)switch(this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length){case 0:return this.listener.call(this.target);case 1:return this.listener.call(this.target,arguments[0]);case 2:return this.listener.call(this.target,arguments[0],arguments[1]);case 3:return this.listener.call(this.target,arguments[0],arguments[1],arguments[2]);default:for(var e=new Array(arguments.length),t=0;t<e.length;++t)e[t]=arguments[t];this.listener.apply(this.target,e)}}function v(e,t,n){var r={fired:!1,wrapFn:void 0,target:e,type:t,listener:n},s=a.call(y,r);return s.listener=n,r.wrapFn=s,s}function b(e,t,n){var r=e._events;if(!r)return[];var s=r[t];return s?"function"==typeof s?n?[s.listener||s]:[s]:n?S(s):I(s,s.length):[]}function w(e){var t=this._events;if(t){var n=t[e];if("function"==typeof n)return 1;if(n)return n.length}return 0}function C(e,t){for(var n=t,r=n+1,s=e.length;r<s;n+=1,r+=1)e[n]=e[r];e.pop()}function I(e,t){for(var n=new Array(t),r=0;r<t;++r)n[r]=e[r];return n}function S(e){for(var t=new Array(e.length),n=0;n<t.length;++n)t[n]=e[n].listener||e[n];return t}function _(e){var t=function(){};return t.prototype=e,new t}function k(e){for(var t in e)Object.prototype.hasOwnProperty.call(e,t);return t}function T(e){var t=this;return function(){return t.apply(e,arguments)}}i?Object.defineProperty(o,"defaultMaxListeners",{enumerable:!0,get:function(){return c},set:function(e){if("number"!=typeof e||e<0||e!=e)throw new TypeError('"defaultMaxListeners" must be a positive number');c=e}}):o.defaultMaxListeners=c,o.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||isNaN(e))throw new TypeError('"n" argument must be a positive number');return this._maxListeners=e,this},o.prototype.getMaxListeners=function(){return d(this)},o.prototype.emit=function(e){var t,n,r,s,a,o,i="error"===e;if(o=this._events)i=i&&null==o.error;else if(!i)return!1;if(i){if(arguments.length>1&&(t=arguments[1]),t instanceof Error)throw t;var c=new Error('Unhandled "error" event. ('+t+")");throw c.context=t,c}if(!(n=o[e]))return!1;var l="function"==typeof n;switch(r=arguments.length){case 1:u(n,l,this);break;case 2:h(n,l,this,arguments[1]);break;case 3:p(n,l,this,arguments[1],arguments[2]);break;case 4:f(n,l,this,arguments[1],arguments[2],arguments[3]);break;default:for(s=new Array(r-1),a=1;a<r;a++)s[a-1]=arguments[a];m(n,l,this,s)}return!0},o.prototype.addListener=function(e,t){return g(this,e,t,!1)},o.prototype.on=o.prototype.addListener,o.prototype.prependListener=function(e,t){return g(this,e,t,!0)},o.prototype.once=function(e,t){if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');return this.on(e,v(this,e,t)),this},o.prototype.prependOnceListener=function(e,t){if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');return this.prependListener(e,v(this,e,t)),this},o.prototype.removeListener=function(e,t){var n,s,a,o,i;if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');if(!(s=this._events))return this;if(!(n=s[e]))return this;if(n===t||n.listener===t)0==--this._eventsCount?this._events=r(null):(delete s[e],s.removeListener&&this.emit("removeListener",e,n.listener||t));else if("function"!=typeof n){for(a=-1,o=n.length-1;o>=0;o--)if(n[o]===t||n[o].listener===t){i=n[o].listener,a=o;break}if(a<0)return this;0===a?n.shift():C(n,a),1===n.length&&(s[e]=n[0]),s.removeListener&&this.emit("removeListener",e,i||t)}return this},o.prototype.removeAllListeners=function(e){var t,n,a;if(!(n=this._events))return this;if(!n.removeListener)return 0===arguments.length?(this._events=r(null),this._eventsCount=0):n[e]&&(0==--this._eventsCount?this._events=r(null):delete n[e]),this;if(0===arguments.length){var o,i=s(n);for(a=0;a<i.length;++a)"removeListener"!==(o=i[a])&&this.removeAllListeners(o);return this.removeAllListeners("removeListener"),this._events=r(null),this._eventsCount=0,this}if("function"==typeof(t=n[e]))this.removeListener(e,t);else if(t)for(a=t.length-1;a>=0;a--)this.removeListener(e,t[a]);return this},o.prototype.listeners=function(e){return b(this,e,!0)},o.prototype.rawListeners=function(e){return b(this,e,!1)},o.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):w.call(e,t)},o.prototype.listenerCount=w,o.prototype.eventNames=function(){return this._eventsCount>0?Reflect.ownKeys(this._events):[]}},{}],23:[function(e,t,n){
1
+ var Amity=function(e,t,n,r,a,s,o,i,c,l,d,u,h){"use strict";function p(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var f,m=p(n),g=p(r),y=p(a),v=p(s),b=p(o),w=p(i),C=p(c),I=p(l),S=p(d),_=p(h);e.MembershipAcceptanceTypeEnum=void 0,(f=e.MembershipAcceptanceTypeEnum||(e.MembershipAcceptanceTypeEnum={})).AUTOMATIC="automatic",f.INVITATION="invitation";const k=Object.freeze({FILE:"file",IMAGE:"image",VIDEO:"video"}),O=Object.freeze({"1080P":"1080p","720P":"720p","480P":"480p","360P":"360p",ORIGINAL:"original"}),T=Object.freeze({UPLOADED:"uploaded",TRANSCODING:"transcoding",TRANSCODED:"transcoded",TRANSCODE_FAILED:"transcodeFailed"}),E=Object.freeze({LOW:"low",MEDIUM:"medium",HIGH:"high",ORIGINAL:"original"});var A;e.FileAccessTypeEnum=void 0,(A=e.FileAccessTypeEnum||(e.FileAccessTypeEnum={})).PUBLIC="public",A.NETWORK="network";const R=Object.freeze({ONLY_ADMIN_CAN_POST:"ONLY_ADMIN_CAN_POST",ADMIN_REVIEW_POST_REQUIRED:"ADMIN_REVIEW_POST_REQUIRED",ANYONE_CAN_POST:"ANYONE_CAN_POST"}),M=Object.freeze({ONLY_ADMIN_CAN_POST:{needApprovalOnPostCreation:!1,onlyAdminCanPost:!0},ADMIN_REVIEW_POST_REQUIRED:{needApprovalOnPostCreation:!0,onlyAdminCanPost:!1},ANYONE_CAN_POST:{needApprovalOnPostCreation:!1,onlyAdminCanPost:!1}}),j="ONLY_ADMIN_CAN_POST",P=Object.freeze({STORY:"story",CLIP:"clip",CHAT:"chat",POST:"post",MESSAGE:"message"});var U;e.ContentFlagReasonEnum=void 0,(U=e.ContentFlagReasonEnum||(e.ContentFlagReasonEnum={})).CommunityGuidelines="Against community guidelines",U.HarassmentOrBullying="Harassment or bullying",U.SelfHarmOrSuicide="Self-harm or suicide",U.ViolenceOrThreateningContent="Violence or threatening content",U.SellingRestrictedItems="Selling and promoting restricted items",U.SexualContentOrNudity="Sexual message or nudity",U.SpamOrScams="Spam or scams",U.FalseInformation="False information or misinformation",U.Others="Others";const x=Object.freeze({TEXT:"text",IMAGE:"image",FILE:"file",VIDEO:"video",AUDIO:"audio",CUSTOM:"custom"}),D=Object.freeze({TEXT:"text",IMAGE:"image",FILE:"file",VIDEO:"video",LIVESTREAM:"liveStream",POLL:"poll"});var q,N,B,L,F;e.InvitationTypeEnum=void 0,(q=e.InvitationTypeEnum||(e.InvitationTypeEnum={})).CommunityMemberInvite="communityMemberInvite",q.LivestreamInvite="livestreamInvite",e.InvitationStatusEnum=void 0,(N=e.InvitationStatusEnum||(e.InvitationStatusEnum={})).Pending="pending",N.Approved="approved",N.Rejected="rejected",N.Cancelled="cancelled",e.InvitationSortByEnum=void 0,(B=e.InvitationSortByEnum||(e.InvitationSortByEnum={})).FirstCreated="firstCreated",B.LastCreated="lastCreated",e.JoinRequestStatusEnum=void 0,(L=e.JoinRequestStatusEnum||(e.JoinRequestStatusEnum={})).Pending="pending",L.Approved="approved",L.Rejected="rejected",L.Cancelled="cancelled",e.JoinResultStatusEnum=void 0,(F=e.JoinResultStatusEnum||(e.JoinResultStatusEnum={})).Success="success",F.Pending="pending";const K=function(){try{return"v7.6.0-umd"}catch(e){return"__dev__"}}(),$=5,Q="cache_then_server",z="For using Live Collection feature you need to enable Cache!",V="Observing unsynced object is not supported by Live Object.",H=-5,J=1e3,W=6e5,G="dead",Y=6e4,Z=e=>JSON.stringify(e,((e,t)=>{return"object"==typeof t?(n=t,Object.keys(n).sort().reduce(((e,t)=>Object.assign(Object.assign({},e),{[t]:n[t]})),{})):t;var n})),X=e=>JSON.parse(e),ee=(e,t)=>e===t||!(!e||!t)&&("object"==typeof e&&Object.keys(e).every((n=>ee(e[n],t[n])))),te=e=>[400400,400300].includes(e),ne=e=>["skip"].some((t=>t in e)),re=e=>["after","before","first","last","limit"].some((t=>t in e)),ae=e=>"limit"in e,se=e=>(null==e?void 0:e.hasOwnProperty("data"))&&(null==e?void 0:e.hasOwnProperty("nextPage"))&&(null==e?void 0:e.hasOwnProperty("prevPage")),oe=(e,n)=>{var r;if(!e||!Object.keys(e).length)return;let a={};return"skiplimit"===n?a={skip:null!==(r=e.after)&&void 0!==r?r:0,limit:e.limit}:"afterbefore"===n&&re(e)?((null==e?void 0:e.before)&&(a=Object.assign(Object.assign({},a),{before:e.before})),(null==e?void 0:e.after)&&(a=Object.assign(Object.assign({},a),{after:e.after})),Number.isNaN(Number(null==e?void 0:e.limit))||(a=Object.assign(Object.assign({},a),{limit:e.limit}))):"afterbeforeraw"===n&&(a=e),Object.keys(a).length?t.encode(JSON.stringify(a)):void 0},ie=e=>{if(!e)return;const n=JSON.parse(t.decode(e));if(ne(n))return{after:n.skip,limit:n.limit};if(re(n)){if("before"in n)return{before:n.before,limit:n.last};if("after"in n)return{after:n.after,limit:n.first}}},ce=e=>"locally"in e,le=e=>"optimistically"in e,de=e=>ce(e)||le(e),ue=e=>null==e?void 0:e.hasOwnProperty("cachedAt"),he=(e,t=6e4)=>{var n;return Date.now()-(null!==(n=null==e?void 0:e.cachedAt)&&void 0!==n?n:0)<=t},pe=(e,...t)=>({func:e,args:t}),fe=(e,t=6e4)=>"cache_only"===e?{lifeSpan:1/0}:{lifeSpan:t<Y?Y:t},me=({func:e,args:t},n,r=fe("cache_then_server"))=>{let a;const{lifeSpan:s}=fe("cache_then_server",r.lifeSpan);if(de(e)){try{a=le(e)?e.optimistically(...t):e.locally(...t)}catch(e){null==n||n(ge(void 0,{origin:"local",loading:!1,error:e}))}const r=ue(a)&&he(a,s);if(null==n||n(ge(a,{origin:"local",loading:!(ce(e)&&r)})),r)return}else null==n||n(ge(void 0,{origin:"local",loading:!0}));e(...t).then((e=>{null==n||n(ge(e,{origin:"server",loading:!1}))})).catch((e=>{null==n||n(ge(void 0,{origin:"server",loading:!1,error:e}))}))};function ge(e,t){return se(e)||ue(e)?Object.assign(Object.assign({},t),e):Object.assign(Object.assign({},t),{data:e})}const ye={user:({userId:e})=>e,file:({fileId:e})=>e,role:({roleId:e})=>e,channel:({channelInternalId:e})=>e,subChannel:({subChannelId:e})=>e,channelUsers:({channelId:e,userId:t})=>`${e}#${t}`,message:({messageId:e,referenceId:t})=>null!=t?t:e,messagePreviewChannel:({channelId:e})=>`${e}`,messagePreviewSubChannel:({subChannelId:e})=>`${e}`,channelUnreadInfo:({channelId:e})=>e,subChannelUnreadInfo:({subChannelId:e})=>e,channelUnread:({channelId:e})=>e,channelMarker:({entityId:e,userId:t})=>`${e}#${t}`,subChannelMarker:({entityId:e,feedId:t,userId:n})=>`${e}#${t}#${n}`,messageMarker:({feedId:e,contentId:t,creatorId:n})=>`${e}#${t}#${n}`,feedMarker:({feedId:e,entityId:t})=>`${e}#${t}`,userMarker:({userId:e})=>e,community:({communityId:e})=>e,category:({categoryId:e})=>e,communityUsers:({communityId:e,userId:t})=>`${e}#${t}`,post:({postId:e})=>e,comment:({commentId:e})=>e,commentChildren:({commentId:e})=>e,poll:({pollId:e})=>e,reaction:({referenceType:e,referenceId:t})=>`${e}#${t}`,reactor:({reactionId:e})=>e,stream:({streamId:e})=>e,streamModeration:({streamId:e})=>e,follow:({from:e,to:t})=>`${e}#${t}`,followInfo:({userId:e})=>e,followCount:({userId:e})=>e,feed:({targetId:e,feedId:t})=>`${e}#${t}`,story:({referenceId:e})=>e,storyTarget:({targetId:e})=>e,ad:({adId:e})=>e,advertiser:({advertiserId:e})=>e,pin:({placement:e,referenceId:t})=>`${e}#${t}`,pinTarget:({targetId:e})=>e,notificationTrayItem:({_id:e})=>e,notificationTraySeen:({userId:e})=>e,invitation:({_id:e})=>e,joinRequest:({joinRequestId:e})=>e},ve=e=>ye[e],be={users:"user",files:"file",roles:"role",stories:"story",storyTargets:"storyTarget",channels:"channel",messageFeeds:"subChannel",channelUsers:"channelUsers",messages:"message",messagePreviewChannel:"messagePreviewChannel",messagePreviewSubChannel:"messagePreviewSubChannel",channelUnreadInfo:"channelUnreadInfo",subChannelUnreadInfo:"subChannelUnreadInfo",userEntityMarkers:"channelMarker",userFeedMarkers:"subChannelMarker",contentMarkers:"messageMarker",feedMarkers:"feedMarker",userMarkers:"userMarker",communities:"community",categories:"category",communityUsers:"communityUsers",posts:"post",postChildren:"post",comments:"comment",commentChildren:"comment",polls:"poll",reactors:"reactor",reactions:"reaction",videoStreamings:"stream",videoStreamModerations:"streamModeration",follows:"follow",followCounts:"followCount",feeds:"feed",ads:"ad",advertisers:"advertiser",pinTargets:"pinTarget",pins:"pin",notificationTrayItems:"notificationTrayItem",invitations:"invitation",joinRequests:"joinRequest"};function we(e=(new Date).toISOString()){return new Date(new Date(e).getTime()+1).toISOString()}class Ce extends Error{constructor(e,t,n){super(`Amity SDK (${t}): ${e}`),this.code=t,this.level=n,this.type="ASC",this.timestamp=Date.now(),Error.captureStackTrace&&Error.captureStackTrace(this,Ce)}}class Ie extends Ce{constructor(e,t,n){super(e,t,n)}}class Se extends Ce{constructor(e=8e5,t="fatal"){super("Unexpected error",e,t)}}class _e extends Ce{constructor(e,t="SDK client is having connection issues"){super(`${t} (${e})`,"disconnected"===e?800211:800210,"error"),this.event=e}}class ke extends Ce{constructor(e){super(e,800110,"error")}}let Oe=null;const Te=()=>{if(!Oe)throw new Ce("There is no active client",8e5,"fatal");return Oe},Ee=e=>{Oe=e},Ae=e=>{const{log:t,cache:n}=Te();if(n)return t("cache/api/queryCache",{key:e}),Object.keys(n.data).filter((t=>{const n=X(t);return ee(e,n)})).map((e=>n.data[e]))},Re=e=>{const{log:t,cache:n}=Te();if(!n)return;t("cache/api/pullFromCache",e);const r=Z(e);return n.data[r]?n.data[r]:void 0},Me=(e,t,n={cachedAt:Date.now()})=>{const{log:r,cache:a}=Te();if(!a)return!1;r("cache/api/pushToCache",{key:e,data:t,options:n}),!(null==n?void 0:n.hasOwnProperty("offline"))&&a.persistIf&&(n.offline=a.persistIf(e,t));const s=Z(e);return a.data[s]=Object.assign({key:e,data:t},n),!0},je=(e,t,n)=>{const{log:r,cache:a}=Te();if(!a)return!1;r("cache/api/mergeInCache",{key:e,mutation:t});const s=Re(e);if(!s)return!1;const o="function"==typeof t?t(s.data):Object.assign(Object.assign({},s.data),t);return i=s.data,!("updatedAt"in(c=o)&&"updatedAt"in c&&new Date(c.updatedAt)<new Date(i.updatedAt))&&(Me(e,o,n),!0);var i,c},Pe=(e,t,n={cachedAt:Date.now()})=>{const{log:r,cache:a}=Te();if(!a)return!1;r("cache/api/upsertInCache",{key:e,data:t,options:n});return Re(e)?je(e,t,n):Me(e,t,n)},Ue=(e,t=!1)=>{const{log:n,cache:r}=Te();if(!r)return!1;if(n("cache/api/dropFromCache",{key:e,exact:t}),!t)return Object.keys(r.data).map((e=>X(e))).filter((t=>ee(e,t))).map((e=>Ue(e,!0))).every((e=>e));const a=Z(e);return a in r.data&&(delete r.data[a],!0)},xe=(e,t,n)=>void 0!==n?e.filter((e=>JSON.stringify(e[t])===JSON.stringify(n))):e,De=(e,t,n)=>void 0!==n?e.filter((e=>"string"==typeof e[t]&&"string"==typeof n&&String(e[t]).toLowerCase().match(n.toLowerCase()))):e,qe=(e,t,n)=>(null==n?void 0:n.length)?e.filter((e=>Array.isArray(e[t])&&n.some((n=>e[t].includes(n))))):e,Ne=(e,t,n)=>"all"===t?e:e.filter((e=>{var r;if("community"===e.type)return!0;const a=ve("channelUsers")({channelId:e.channelPublicId,userId:n}),s=null===(r=Re(["channelUsers","get",a]))||void 0===r?void 0:r.data;return"member"===t?s&&"none"!==s.membership:!s||"none"===s.membership})),Be=(e,t)=>e.filter((({targetId:e,feedId:n})=>{var r;const a=null===(r=Re(["feed","get",ve("feed")({targetId:e,feedId:n})]))||void 0===r?void 0:r.data;return a&&a.feedType===t})),Le=(e,t,n)=>"all"===t?e:e.filter((e=>{var r;const a=ve("communityUsers")({communityId:e.communityId,userId:n}),s=null===(r=Re(["communityUsers","get",a]))||void 0===r?void 0:r.data;return"member"===t?s&&"member"===s.communityMembership:!s||"none"!==s.communityMembership})),Fe=(e,t)=>e.reduce(((e,n)=>{var r;if(null==t?void 0:t.includes(n.dataType))return[...e,n];if(((null==n?void 0:n.children)||[]).length>0){const a=null===(r=Re(["post","get",n.children[0]]))||void 0===r?void 0:r.data;return(null==t?void 0:t.includes(null==a?void 0:a.dataType))?e:[...e,n]}return e}),[]),Ke=(e,t)=>{const n=new RegExp(t,"i");return e.filter((e=>{var t;return!!e.userId.match(n)||e.user&&(null===(t=e.user.displayName)||void 0===t?void 0:t.match(n))}))},$e=({displayName:e},{displayName:t})=>e&&t?e.localeCompare(t):e?-1:1,Qe=({name:e},{name:t})=>e&&t?e.localeCompare(t):e?-1:1,ze=({createdAt:e},{createdAt:t})=>new Date(e).valueOf()-new Date(t).valueOf(),Ve=({localSortingDate:e},{localSortingDate:t})=>new Date(t).getTime()-new Date(e).getTime(),He=({createdAt:e},{createdAt:t})=>new Date(t).valueOf()-new Date(e).valueOf(),Je=({updatedAt:e=0},{updatedAt:t=0})=>new Date(e).valueOf()-new Date(t).valueOf(),We=({updatedAt:e=0},{updatedAt:t=0})=>new Date(t).valueOf()-new Date(e).valueOf(),Ge=({lastActivity:e},{lastActivity:t})=>new Date(t).valueOf()-new Date(e).valueOf();let Ye=null;const Ze=()=>{if(!Ye)throw new Ce("Connect client first",8e5,"fatal");return Ye},Xe=e=>{Ye={_id:e._id,userId:e.userId,path:e.path}};let et,tt=[];const nt=e=>{clearTimeout(et),tt.push(e),et=setTimeout((()=>{tt.forEach((e=>e())),tt=[]}),0)},rt=["disconnected","error","connect_error","reconnect_error","reconnect_failed","sessionStateChange","tokenExpired"],at=["connect","message","disconnect","error","close","end","reconnect","video-streaming.didStart","video-streaming.didRecord","video-streaming.didStop","video-streaming.didFlag","video-streaming.didTerminate"],st=(e,t)=>{rt.forEach((n=>{null==e||e.on(n,(e=>{t.emit(n,e)}))}))},ot=(e,t,n,r)=>{const{log:a,emitter:s}=e,o=Date.now();a(`${t}(tmpid: ${o}) > listen`);const i=(...e)=>{a(`${t}(tmpid: ${o}) > trigger`,e);try{r(...e)}catch(e){a(`${t}(tmpid: ${o}) > error`,e)}};return s.on(n,i),()=>{a(`${t}(tmpid: ${o}) > dispose`),s.off(n,i)}},it=(e,t)=>{const{emitter:n}=Te();nt((()=>{n.emit(e,t)}))};let ct,lt;async function dt(){var e;const{mqtt:t,emitter:n,token:r}=Te();if(!t)return;const a=null!==(e=null==r?void 0:r.accessToken)&&void 0!==e?e:"",s=Ze();ct===a&&lt===s._id||(ct=a,lt=s._id,await t.connect({accessToken:ct,userId:lt}),((e,t)=>{at.forEach((n=>{null==e||e.on(n,((...e)=>{t.emit(n,1===e.length?e[0]:e)}))})),e.on("message",((e,n)=>{const r=JSON.parse(n.toString());t.emit(r.eventType,r.data)}))})(t,n))}var ut;e.SubscriptionLevels=void 0,(ut=e.SubscriptionLevels||(e.SubscriptionLevels={})).COMMUNITY="community",ut.POST="post",ut.COMMENT="comment",ut.POST_AND_COMMENT="post_and_comment",ut.USER="user";const ht=(e,t)=>{switch(t){case"post":return`${e}/post/+`;case"comment":return`${e}/post/+/comment/+`;case"post_and_comment":return`${e}/post/#`;default:return e}},pt=e=>e.path.split("/user/")[0],ft=({path:t},n=e.SubscriptionLevels.USER)=>ht(n===e.SubscriptionLevels.USER?t:t.replace(/^(\w*)/,"$1/social"),n),mt=({channelId:e,subChannelId:t})=>{const n=Ze();return`${pt(n)}/marker/channel/${e}/message/${t}`},gt=()=>{const e=Ze();return`${pt(e)}/marker/user/${e._id}`},yt=()=>pt(Ze()),vt=()=>{const e=Ze();return`${pt(e)}/smartfeed/${e._id}/channels`},bt=()=>{const e=Ze();return`${pt(e)}/smartfeed/${e._id}/messagefeeds`},wt=()=>{const e=Ze();return`${pt(e)}/smartfeed/${e._id}/messages`};function Ct(e,t){const{mqtt:n}=Te();return n?(dt(),n.subscribe(e,t)):()=>null}const It=()=>{const e=Ze();return`${pt(e)}/videostreaming`};var St;const _t="object"==typeof globalThis?globalThis:"object"==typeof global?global:window,{process:kt={}}=_t,Ot="production"===(null===(St=kt.env)||void 0===St?void 0:St.NODE_ENV),Tt={EU:"eu",SG:"sg",US:"us"},Et={http:"https://apix.{region}.amity.co",upload:"https://upload.{region}.amity.co",mqtt:"wss://sse.{region}.amity.co:443/mqtt"};function At(e,t){return Et[e].replace("{region}",t)}class Rt{constructor(){this._listener=new Map}onNetworkActivities(e){return this._listener.set(e,e),()=>{this._listener.delete(e)}}setNetworkActivities(e,t){this._listener.forEach((n=>n(e,t)))}destroy(){this._listener.clear()}}let Mt;var jt,Pt=()=>(Mt||(Mt=new Rt),Mt);!function(e){e.UserDeleted="User Deleted",e.UserGlobalBanned="User Global Banned",e.TokenExpired="Token Expired"}(jt||(jt={}));const Ut=new AbortController,xt=e=>{switch(e){case jt.UserGlobalBanned:throw new Ce(e,400312,"fatal");case jt.UserDeleted:throw new Ce(e,400100,"fatal");case jt.TokenExpired:throw it("tokenExpired","tokenExpired"),new Ce(e,800403,"fatal");default:throw new Ce("Request Aborted",8e5,"error")}},Dt=e=>{const t={maxSockets:100,maxFreeSockets:10,timeout:6e4,freeSocketTimeout:3e4},n=y.default.create({baseURL:e,httpAgent:new v.default(t),httpsAgent:new s.HttpsAgent(t),signal:Ut.signal});return n.defaults.withCredentials=!1,n.interceptors.request.use((e=>{if("/api/v5/sessions"===e.url)return e;if(e.metadata){const{tokenExpiry:t,isGlobalBanned:n,isUserDeleted:r}=e.metadata;n&&(Ut.abort(),xt(jt.UserGlobalBanned)),r&&(Ut.abort(),xt(jt.UserDeleted)),t&&Date.now()>=Date.parse(t)&&(Ut.abort(jt.UserDeleted),xt(jt.TokenExpired))}return e})),n.interceptors.response.use((e=>{const t=new Headers;return Object.entries(e.headers).forEach((([e,n])=>{"string"==typeof n&&t.append(e,n)})),Pt().setNetworkActivities(new Request(e.request.url,{method:e.request.method,headers:e.request.headers,body:e.request.data}),{data:e.data,status:e.status,statusText:e.statusText,headers:t}),e}),(e=>{var t,n;const{response:r}=e;if(400100===(null==r?void 0:r.data.code)&&it("tokenTerminated","terminated"),(null===(t=null==r?void 0:r.data)||void 0===t?void 0:t.status)&&(e=>{if("success"===e.status)return e.data;if("fail"===e.status)throw new Se(e.code);if("error"===e.status)throw new Ie(e.message,e.code,"error")})(null==r?void 0:r.data),Ut.signal.aborted)throw e;throw new Error(null!==(n=null==r?void 0:r.data)&&void 0!==n?n:e)})),n.defaults.paramsSerializer={encode:e=>encodeURIComponent(e)},n};var qt="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function Nt(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function Bt(e){throw new Error('Could not dynamically require "'+e+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var Lt={exports:{}};Lt.exports=function(){function e(t,n,r){function a(o,i){if(!n[o]){if(!t[o]){if(!i&&Bt)return Bt(o);if(s)return s(o,!0);var c=new Error("Cannot find module '"+o+"'");throw c.code="MODULE_NOT_FOUND",c}var l=n[o]={exports:{}};t[o][0].call(l.exports,(function(e){return a(t[o][1][e]||e)}),l,l.exports,e,t,n,r)}return n[o].exports}for(var s=Bt,o=0;o<r.length;o++)a(r[o]);return a}return e}()({1:[function(e,t,n){(function(n,r){(function(){const a=e("events").EventEmitter,s=e("./store"),o=e("./topic-alias-recv"),i=e("./topic-alias-send"),c=e("mqtt-packet"),l=e("./default-message-id-provider"),d=e("readable-stream").Writable,u=e("inherits"),h=e("reinterval"),p=e("rfdc/default"),f=e("./validations"),m=e("xtend"),g=e("debug")("mqttjs:client"),y=n?n.nextTick:function(e){setTimeout(e,0)},v=r.setImmediate||function(e){y(e)},b={keepalive:60,reschedulePings:!0,protocolId:"MQTT",protocolVersion:4,reconnectPeriod:1e3,connectTimeout:3e4,clean:!0,resubscribe:!0},w=["ECONNREFUSED","EADDRINUSE","ECONNRESET","ENOTFOUND"],C={0:"",1:"Unacceptable protocol version",2:"Identifier rejected",3:"Server unavailable",4:"Bad username or password",5:"Not authorized",16:"No matching subscribers",17:"No subscription existed",128:"Unspecified error",129:"Malformed Packet",130:"Protocol Error",131:"Implementation specific error",132:"Unsupported Protocol Version",133:"Client Identifier not valid",134:"Bad User Name or Password",135:"Not authorized",136:"Server unavailable",137:"Server busy",138:"Banned",139:"Server shutting down",140:"Bad authentication method",141:"Keep Alive timeout",142:"Session taken over",143:"Topic Filter invalid",144:"Topic Name invalid",145:"Packet identifier in use",146:"Packet Identifier not found",147:"Receive Maximum exceeded",148:"Topic Alias invalid",149:"Packet too large",150:"Message rate too high",151:"Quota exceeded",152:"Administrative action",153:"Payload format invalid",154:"Retain not supported",155:"QoS not supported",156:"Use another server",157:"Server moved",158:"Shared Subscriptions not supported",159:"Connection rate exceeded",160:"Maximum connect time",161:"Subscription Identifiers not supported",162:"Wildcard Subscriptions not supported"};function I(){return"mqttjs_"+Math.random().toString(16).substr(2,8)}function S(e,t){if(5===e.options.protocolVersion&&"publish"===t.cmd){let n;t.properties&&(n=t.properties.topicAlias);const r=t.topic.toString();if(e.topicAliasSend)if(n){if(0!==r.length&&(g("applyTopicAlias :: register topic: %s - alias: %d",r,n),!e.topicAliasSend.put(r,n)))return g("applyTopicAlias :: error out of range. topic: %s - alias: %d",r,n),new Error("Sending Topic Alias out of range")}else 0!==r.length&&(e.options.autoAssignTopicAlias?(n=e.topicAliasSend.getAliasByTopic(r),n?(t.topic="",t.properties={...t.properties,topicAlias:n},g("applyTopicAlias :: auto assign(use) topic: %s - alias: %d",r,n)):(n=e.topicAliasSend.getLruAlias(),e.topicAliasSend.put(r,n),t.properties={...t.properties,topicAlias:n},g("applyTopicAlias :: auto assign topic: %s - alias: %d",r,n))):e.options.autoUseTopicAlias&&(n=e.topicAliasSend.getAliasByTopic(r),n&&(t.topic="",t.properties={...t.properties,topicAlias:n},g("applyTopicAlias :: auto use topic: %s - alias: %d",r,n))));else if(n)return g("applyTopicAlias :: error out of range. topic: %s - alias: %d",r,n),new Error("Sending Topic Alias out of range")}}function _(e,t){let n;t.properties&&(n=t.properties.topicAlias);let r=t.topic.toString();if(0===r.length){if(void 0===n)return new Error("Unregistered Topic Alias");if(r=e.topicAliasSend.getTopicByAlias(n),void 0===r)return new Error("Unregistered Topic Alias");t.topic=r}n&&delete t.properties.topicAlias}function k(e,t,n){g("sendPacket :: packet: %O",t),g("sendPacket :: emitting `packetsend`"),e.emit("packetsend",t),g("sendPacket :: writing to stream");const r=c.writeToStream(t,e.stream,e.options);g("sendPacket :: writeToStream result %s",r),!r&&n&&n!==A?(g("sendPacket :: handle events on `drain` once through callback."),e.stream.once("drain",n)):n&&(g("sendPacket :: invoking cb"),n())}function O(e){e&&(g("flush: queue exists? %b",!!e),Object.keys(e).forEach((function(t){"function"==typeof e[t].cb&&(e[t].cb(new Error("Connection closed")),delete e[t])})))}function T(e){e&&(g("flushVolatile :: deleting volatile messages from the queue and setting their callbacks as error function"),Object.keys(e).forEach((function(t){e[t].volatile&&"function"==typeof e[t].cb&&(e[t].cb(new Error("Connection closed")),delete e[t])})))}function E(e,t,n,r){g("storeAndSend :: store packet with cmd %s to outgoingStore",t.cmd);let a,s=t;if("publish"===s.cmd&&(s=p(t),a=_(e,s),a))return n&&n(a);e.outgoingStore.put(s,(function(a){if(a)return n&&n(a);r(),k(e,t,n)}))}function A(e){g("nop ::",e)}function R(e,t){let n;const r=this;if(!(this instanceof R))return new R(e,t);for(n in this.options=t||{},b)void 0===this.options[n]?this.options[n]=b[n]:this.options[n]=t[n];g("MqttClient :: options.protocol",t.protocol),g("MqttClient :: options.protocolVersion",t.protocolVersion),g("MqttClient :: options.username",t.username),g("MqttClient :: options.keepalive",t.keepalive),g("MqttClient :: options.reconnectPeriod",t.reconnectPeriod),g("MqttClient :: options.rejectUnauthorized",t.rejectUnauthorized),g("MqttClient :: options.topicAliasMaximum",t.topicAliasMaximum),this.options.clientId="string"==typeof t.clientId?t.clientId:I(),g("MqttClient :: clientId",this.options.clientId),this.options.customHandleAcks=5===t.protocolVersion&&t.customHandleAcks?t.customHandleAcks:function(){arguments[3](0)},this.streamBuilder=e,this.messageIdProvider=void 0===this.options.messageIdProvider?new l:this.options.messageIdProvider,this.outgoingStore=t.outgoingStore||new s,this.incomingStore=t.incomingStore||new s,this.queueQoSZero=void 0===t.queueQoSZero||t.queueQoSZero,this._resubscribeTopics={},this.messageIdToTopic={},this.pingTimer=null,this.connected=!1,this.disconnecting=!1,this.queue=[],this.connackTimer=null,this.reconnectTimer=null,this._storeProcessing=!1,this._packetIdsDuringStoreProcessing={},this._storeProcessingQueue=[],this.outgoing={},this._firstConnection=!0,t.topicAliasMaximum>0&&(t.topicAliasMaximum>65535?g("MqttClient :: options.topicAliasMaximum is out of range"):this.topicAliasRecv=new o(t.topicAliasMaximum)),this.on("connect",(function(){const e=this.queue;function t(){const n=e.shift();g("deliver :: entry %o",n);let a=null;if(!n)return void r._resubscribe();a=n.packet,g("deliver :: call _sendPacket for %o",a);let s=!0;a.messageId&&0!==a.messageId&&(r.messageIdProvider.register(a.messageId)||(s=!1)),s?r._sendPacket(a,(function(e){n.cb&&n.cb(e),t()})):(g("messageId: %d has already used. The message is skipped and removed.",a.messageId),t())}g("connect :: sending queued packets"),t()})),this.on("close",(function(){g("close :: connected set to `false`"),this.connected=!1,g("close :: clearing connackTimer"),clearTimeout(this.connackTimer),g("close :: clearing ping timer"),null!==r.pingTimer&&(r.pingTimer.clear(),r.pingTimer=null),this.topicAliasRecv&&this.topicAliasRecv.clear(),g("close :: calling _setupReconnect"),this._setupReconnect()})),a.call(this),g("MqttClient :: setting up stream"),this._setupStream()}u(R,a),R.prototype._setupStream=function(){const e=this,t=new d,n=c.parser(this.options);let r=null;const a=[];function s(){if(a.length)y(o);else{const e=r;r=null,e()}}function o(){g("work :: getting next packet in queue");const t=a.shift();if(t)g("work :: packet pulled from queue"),e._handlePacket(t,s);else{g("work :: no packets in queue");const e=r;r=null,g("work :: done flag is %s",!!e),e&&e()}}function i(t){g("streamErrorHandler :: error",t.message),w.includes(t.code)?(g("streamErrorHandler :: emitting error"),e.emit("error",t)):A(t)}g("_setupStream :: calling method to clear reconnect"),this._clearReconnect(),g("_setupStream :: using streamBuilder provided to client to create stream"),this.stream=this.streamBuilder(this),n.on("packet",(function(e){g("parser :: on packet push to packets array."),a.push(e)})),t._write=function(e,t,a){r=a,g("writable stream :: parsing buffer"),n.parse(e),o()},g("_setupStream :: pipe stream to writable stream"),this.stream.pipe(t),this.stream.on("error",i),this.stream.on("close",(function(){g("(%s)stream :: on close",e.options.clientId),T(e.outgoing),g("stream: emit close to MqttClient"),e.emit("close")})),g("_setupStream: sending packet `connect`");const l=Object.create(this.options);if(l.cmd="connect",this.topicAliasRecv&&(l.properties||(l.properties={}),this.topicAliasRecv&&(l.properties.topicAliasMaximum=this.topicAliasRecv.max)),k(this,l),n.on("error",this.emit.bind(this,"error")),this.options.properties){if(!this.options.properties.authenticationMethod&&this.options.properties.authenticationData)return e.end((()=>this.emit("error",new Error("Packet has no Authentication Method")))),this;this.options.properties.authenticationMethod&&this.options.authPacket&&"object"==typeof this.options.authPacket&&k(this,m({cmd:"auth",reasonCode:0},this.options.authPacket))}this.stream.setMaxListeners(1e3),clearTimeout(this.connackTimer),this.connackTimer=setTimeout((function(){g("!!connectTimeout hit!! Calling _cleanUp with force `true`"),e._cleanUp(!0)}),this.options.connectTimeout)},R.prototype._handlePacket=function(e,t){const n=this.options;if(5===n.protocolVersion&&n.properties&&n.properties.maximumPacketSize&&n.properties.maximumPacketSize<e.length)return this.emit("error",new Error("exceeding packets size "+e.cmd)),this.end({reasonCode:149,properties:{reasonString:"Maximum packet size was exceeded"}}),this;switch(g("_handlePacket :: emitting packetreceive"),this.emit("packetreceive",e),e.cmd){case"publish":this._handlePublish(e,t);break;case"puback":case"pubrec":case"pubcomp":case"suback":case"unsuback":this._handleAck(e),t();break;case"pubrel":this._handlePubrel(e,t);break;case"connack":this._handleConnack(e),t();break;case"auth":this._handleAuth(e),t();break;case"pingresp":this._handlePingresp(e),t();break;case"disconnect":this._handleDisconnect(e),t()}},R.prototype._checkDisconnecting=function(e){return this.disconnecting&&(e&&e!==A?e(new Error("client disconnecting")):this.emit("error",new Error("client disconnecting"))),this.disconnecting},R.prototype.publish=function(e,t,n,r){g("publish :: message `%s` to topic `%s`",t,e);const a=this.options;if("function"==typeof n&&(r=n,n=null),n=m({qos:0,retain:!1,dup:!1},n),this._checkDisconnecting(r))return this;const s=this,o=function(){let o=0;if((1===n.qos||2===n.qos)&&(o=s._nextId(),null===o))return g("No messageId left"),!1;const i={cmd:"publish",topic:e,payload:t,qos:n.qos,retain:n.retain,messageId:o,dup:n.dup};switch(5===a.protocolVersion&&(i.properties=n.properties),g("publish :: qos",n.qos),n.qos){case 1:case 2:s.outgoing[i.messageId]={volatile:!1,cb:r||A},g("MqttClient:publish: packet cmd: %s",i.cmd),s._sendPacket(i,void 0,n.cbStorePut);break;default:g("MqttClient:publish: packet cmd: %s",i.cmd),s._sendPacket(i,r,n.cbStorePut)}return!0};return(this._storeProcessing||this._storeProcessingQueue.length>0||!o())&&this._storeProcessingQueue.push({invoke:o,cbStorePut:n.cbStorePut,callback:r}),this},R.prototype.subscribe=function(){const e=this,t=new Array(arguments.length);for(let e=0;e<arguments.length;e++)t[e]=arguments[e];const n=[];let r=t.shift();const a=r.resubscribe;let s=t.pop()||A,o=t.pop();const i=this.options.protocolVersion;delete r.resubscribe,"string"==typeof r&&(r=[r]),"function"!=typeof s&&(o=s,s=A);const c=f.validateTopics(r);if(null!==c)return v(s,new Error("Invalid topic "+c)),this;if(this._checkDisconnecting(s))return g("subscribe: discconecting true"),this;const l={qos:0};if(5===i&&(l.nl=!1,l.rap=!1,l.rh=0),o=m(l,o),Array.isArray(r)?r.forEach((function(t){if(g("subscribe: array topic %s",t),!Object.prototype.hasOwnProperty.call(e._resubscribeTopics,t)||e._resubscribeTopics[t].qos<o.qos||a){const e={topic:t,qos:o.qos};5===i&&(e.nl=o.nl,e.rap=o.rap,e.rh=o.rh,e.properties=o.properties),g("subscribe: pushing topic `%s` and qos `%s` to subs list",e.topic,e.qos),n.push(e)}})):Object.keys(r).forEach((function(t){if(g("subscribe: object topic %s",t),!Object.prototype.hasOwnProperty.call(e._resubscribeTopics,t)||e._resubscribeTopics[t].qos<r[t].qos||a){const e={topic:t,qos:r[t].qos};5===i&&(e.nl=r[t].nl,e.rap=r[t].rap,e.rh=r[t].rh,e.properties=o.properties),g("subscribe: pushing `%s` to subs list",e),n.push(e)}})),!n.length)return s(null,[]),this;const d=function(){const t=e._nextId();if(null===t)return g("No messageId left"),!1;const r={cmd:"subscribe",subscriptions:n,qos:1,retain:!1,dup:!1,messageId:t};if(o.properties&&(r.properties=o.properties),e.options.resubscribe){g("subscribe :: resubscribe true");const t=[];n.forEach((function(n){if(e.options.reconnectPeriod>0){const r={qos:n.qos};5===i&&(r.nl=n.nl||!1,r.rap=n.rap||!1,r.rh=n.rh||0,r.properties=n.properties),e._resubscribeTopics[n.topic]=r,t.push(n.topic)}})),e.messageIdToTopic[r.messageId]=t}return e.outgoing[r.messageId]={volatile:!0,cb:function(e,t){if(!e){const e=t.granted;for(let t=0;t<e.length;t+=1)n[t].qos=e[t]}s(e,n)}},g("subscribe :: call _sendPacket"),e._sendPacket(r),!0};return(this._storeProcessing||this._storeProcessingQueue.length>0||!d())&&this._storeProcessingQueue.push({invoke:d,callback:s}),this},R.prototype.unsubscribe=function(){const e=this,t=new Array(arguments.length);for(let e=0;e<arguments.length;e++)t[e]=arguments[e];let n=t.shift(),r=t.pop()||A,a=t.pop();"string"==typeof n&&(n=[n]),"function"!=typeof r&&(a=r,r=A);const s=f.validateTopics(n);if(null!==s)return v(r,new Error("Invalid topic "+s)),this;if(e._checkDisconnecting(r))return this;const o=function(){const t=e._nextId();if(null===t)return g("No messageId left"),!1;const s={cmd:"unsubscribe",qos:1,messageId:t};return"string"==typeof n?s.unsubscriptions=[n]:Array.isArray(n)&&(s.unsubscriptions=n),e.options.resubscribe&&s.unsubscriptions.forEach((function(t){delete e._resubscribeTopics[t]})),"object"==typeof a&&a.properties&&(s.properties=a.properties),e.outgoing[s.messageId]={volatile:!0,cb:r},g("unsubscribe: call _sendPacket"),e._sendPacket(s),!0};return(this._storeProcessing||this._storeProcessingQueue.length>0||!o())&&this._storeProcessingQueue.push({invoke:o,callback:r}),this},R.prototype.end=function(e,t,n){const r=this;function a(){g("end :: closeStores: closing incoming and outgoing stores"),r.disconnected=!0,r.incomingStore.close((function(e){r.outgoingStore.close((function(t){if(g("end :: closeStores: emitting end"),r.emit("end"),n){const r=e||t;g("end :: closeStores: invoking callback with args"),n(r)}}))})),r._deferredReconnect&&r._deferredReconnect()}function s(){g("end :: (%s) :: finish :: calling _cleanUp with force %s",r.options.clientId,e),r._cleanUp(e,(()=>{g("end :: finish :: calling process.nextTick on closeStores"),y(a.bind(r))}),t)}return g("end :: (%s)",this.options.clientId),null!=e&&"boolean"==typeof e||(n=t||A,t=e,e=!1,"object"!=typeof t&&(n=t,t=null,"function"!=typeof n&&(n=A))),"object"!=typeof t&&(n=t,t=null),g("end :: cb? %s",!!n),n=n||A,this.disconnecting?(n(),this):(this._clearReconnect(),this.disconnecting=!0,!e&&Object.keys(this.outgoing).length>0?(g("end :: (%s) :: calling finish in 10ms once outgoing is empty",r.options.clientId),this.once("outgoingEmpty",setTimeout.bind(null,s,10))):(g("end :: (%s) :: immediately calling finish",r.options.clientId),s()),this)},R.prototype.removeOutgoingMessage=function(e){const t=this.outgoing[e]?this.outgoing[e].cb:null;return delete this.outgoing[e],this.outgoingStore.del({messageId:e},(function(){t(new Error("Message removed"))})),this},R.prototype.reconnect=function(e){g("client reconnect");const t=this,n=function(){e?(t.options.incomingStore=e.incomingStore,t.options.outgoingStore=e.outgoingStore):(t.options.incomingStore=null,t.options.outgoingStore=null),t.incomingStore=t.options.incomingStore||new s,t.outgoingStore=t.options.outgoingStore||new s,t.disconnecting=!1,t.disconnected=!1,t._deferredReconnect=null,t._reconnect()};return this.disconnecting&&!this.disconnected?this._deferredReconnect=n:n(),this},R.prototype._reconnect=function(){g("_reconnect: emitting reconnect to client"),this.emit("reconnect"),this.connected?(this.end((()=>{this._setupStream()})),g("client already connected. disconnecting first.")):(g("_reconnect: calling _setupStream"),this._setupStream())},R.prototype._setupReconnect=function(){const e=this;!e.disconnecting&&!e.reconnectTimer&&e.options.reconnectPeriod>0?(this.reconnecting||(g("_setupReconnect :: emit `offline` state"),this.emit("offline"),g("_setupReconnect :: set `reconnecting` to `true`"),this.reconnecting=!0),g("_setupReconnect :: setting reconnectTimer for %d ms",e.options.reconnectPeriod),e.reconnectTimer=setInterval((function(){g("reconnectTimer :: reconnect triggered!"),e._reconnect()}),e.options.reconnectPeriod)):g("_setupReconnect :: doing nothing...")},R.prototype._clearReconnect=function(){g("_clearReconnect : clearing reconnect timer"),this.reconnectTimer&&(clearInterval(this.reconnectTimer),this.reconnectTimer=null)},R.prototype._cleanUp=function(e,t){const n=arguments[2];if(t&&(g("_cleanUp :: done callback provided for on stream close"),this.stream.on("close",t)),g("_cleanUp :: forced? %s",e),e)0===this.options.reconnectPeriod&&this.options.clean&&O(this.outgoing),g("_cleanUp :: (%s) :: destroying stream",this.options.clientId),this.stream.destroy();else{const e=m({cmd:"disconnect"},n);g("_cleanUp :: (%s) :: call _sendPacket with disconnect packet",this.options.clientId),this._sendPacket(e,v.bind(null,this.stream.end.bind(this.stream)))}this.disconnecting||(g("_cleanUp :: client not disconnecting. Clearing and resetting reconnect."),this._clearReconnect(),this._setupReconnect()),null!==this.pingTimer&&(g("_cleanUp :: clearing pingTimer"),this.pingTimer.clear(),this.pingTimer=null),t&&!this.connected&&(g("_cleanUp :: (%s) :: removing stream `done` callback `close` listener",this.options.clientId),this.stream.removeListener("close",t),t())},R.prototype._sendPacket=function(e,t,n){g("_sendPacket :: (%s) :: start",this.options.clientId),n=n||A,t=t||A;const r=S(this,e);if(r)t(r);else{if(!this.connected)return"auth"===e.cmd?(this._shiftPingInterval(),void k(this,e,t)):(g("_sendPacket :: client not connected. Storing packet offline."),void this._storePacket(e,t,n));switch(this._shiftPingInterval(),e.cmd){case"publish":break;case"pubrel":return void E(this,e,t,n);default:return void k(this,e,t)}switch(e.qos){case 2:case 1:E(this,e,t,n);break;default:k(this,e,t)}g("_sendPacket :: (%s) :: end",this.options.clientId)}},R.prototype._storePacket=function(e,t,n){g("_storePacket :: packet: %o",e),g("_storePacket :: cb? %s",!!t),n=n||A;let r=e;if("publish"===r.cmd){r=p(e);const n=_(this,r);if(n)return t&&t(n)}0===(r.qos||0)&&this.queueQoSZero||"publish"!==r.cmd?this.queue.push({packet:r,cb:t}):r.qos>0?(t=this.outgoing[r.messageId]?this.outgoing[r.messageId].cb:null,this.outgoingStore.put(r,(function(e){if(e)return t&&t(e);n()}))):t&&t(new Error("No connection to broker"))},R.prototype._setupPingTimer=function(){g("_setupPingTimer :: keepalive %d (seconds)",this.options.keepalive);const e=this;!this.pingTimer&&this.options.keepalive&&(this.pingResp=!0,this.pingTimer=h((function(){e._checkPing()}),1e3*this.options.keepalive))},R.prototype._shiftPingInterval=function(){this.pingTimer&&this.options.keepalive&&this.options.reschedulePings&&this.pingTimer.reschedule(1e3*this.options.keepalive)},R.prototype._checkPing=function(){g("_checkPing :: checking ping..."),this.pingResp?(g("_checkPing :: ping response received. Clearing flag and sending `pingreq`"),this.pingResp=!1,this._sendPacket({cmd:"pingreq"})):(g("_checkPing :: calling _cleanUp with force true"),this._cleanUp(!0))},R.prototype._handlePingresp=function(){this.pingResp=!0},R.prototype._handleConnack=function(e){g("_handleConnack");const t=this.options,n=5===t.protocolVersion?e.reasonCode:e.returnCode;if(clearTimeout(this.connackTimer),delete this.topicAliasSend,e.properties){if(e.properties.topicAliasMaximum){if(e.properties.topicAliasMaximum>65535)return void this.emit("error",new Error("topicAliasMaximum from broker is out of range"));e.properties.topicAliasMaximum>0&&(this.topicAliasSend=new i(e.properties.topicAliasMaximum))}e.properties.serverKeepAlive&&t.keepalive&&(t.keepalive=e.properties.serverKeepAlive,this._shiftPingInterval()),e.properties.maximumPacketSize&&(t.properties||(t.properties={}),t.properties.maximumPacketSize=e.properties.maximumPacketSize)}if(0===n)this.reconnecting=!1,this._onConnect(e);else if(n>0){const e=new Error("Connection refused: "+C[n]);e.code=n,this.emit("error",e)}},R.prototype._handleAuth=function(e){const t=this.options.protocolVersion,n=5===t?e.reasonCode:e.returnCode;if(5!==t){const e=new Error("Protocol error: Auth packets are only supported in MQTT 5. Your version:"+t);return e.code=n,void this.emit("error",e)}const r=this;this.handleAuth(e,(function(e,t){if(e)r.emit("error",e);else if(24===n)r.reconnecting=!1,r._sendPacket(t);else{const t=new Error("Connection refused: "+C[n]);e.code=n,r.emit("error",t)}}))},R.prototype.handleAuth=function(e,t){t()},R.prototype._handlePublish=function(e,t){g("_handlePublish: packet %o",e),t=void 0!==t?t:A;let n=e.topic.toString();const r=e.payload,a=e.qos,s=e.messageId,o=this,i=this.options,c=[0,16,128,131,135,144,145,151,153];if(5===this.options.protocolVersion){let t;if(e.properties&&(t=e.properties.topicAlias),void 0!==t)if(0===n.length){if(!(t>0&&t<=65535))return g("_handlePublish :: topic alias out of range. alias: %d",t),void this.emit("error",new Error("Received Topic Alias is out of range"));{const e=this.topicAliasRecv.getTopicByAlias(t);if(!e)return g("_handlePublish :: unregistered topic alias. alias: %d",t),void this.emit("error",new Error("Received unregistered Topic Alias"));n=e,g("_handlePublish :: topic complemented by alias. topic: %s - alias: %d",n,t)}}else{if(!this.topicAliasRecv.put(n,t))return g("_handlePublish :: topic alias out of range. alias: %d",t),void this.emit("error",new Error("Received Topic Alias is out of range"));g("_handlePublish :: registered topic: %s - alias: %d",n,t)}}switch(g("_handlePublish: qos %d",a),a){case 2:i.customHandleAcks(n,r,e,(function(n,r){return n instanceof Error||(r=n,n=null),n?o.emit("error",n):-1===c.indexOf(r)?o.emit("error",new Error("Wrong reason code for pubrec")):void(r?o._sendPacket({cmd:"pubrec",messageId:s,reasonCode:r},t):o.incomingStore.put(e,(function(){o._sendPacket({cmd:"pubrec",messageId:s},t)})))}));break;case 1:i.customHandleAcks(n,r,e,(function(a,i){return a instanceof Error||(i=a,a=null),a?o.emit("error",a):-1===c.indexOf(i)?o.emit("error",new Error("Wrong reason code for puback")):(i||o.emit("message",n,r,e),void o.handleMessage(e,(function(e){if(e)return t&&t(e);o._sendPacket({cmd:"puback",messageId:s,reasonCode:i},t)})))}));break;case 0:this.emit("message",n,r,e),this.handleMessage(e,t);break;default:g("_handlePublish: unknown QoS. Doing nothing.")}},R.prototype.handleMessage=function(e,t){t()},R.prototype._handleAck=function(e){const t=e.messageId,n=e.cmd;let r=null;const a=this.outgoing[t]?this.outgoing[t].cb:null,s=this;let o;if(a){switch(g("_handleAck :: packet type",n),n){case"pubcomp":case"puback":{const n=e.reasonCode;n&&n>0&&16!==n&&(o=new Error("Publish error: "+C[n]),o.code=n,a(o,e)),delete this.outgoing[t],this.outgoingStore.del(e,a),this.messageIdProvider.deallocate(t),this._invokeStoreProcessingQueue();break}case"pubrec":{r={cmd:"pubrel",qos:2,messageId:t};const n=e.reasonCode;n&&n>0&&16!==n?(o=new Error("Publish error: "+C[n]),o.code=n,a(o,e)):this._sendPacket(r);break}case"suback":delete this.outgoing[t],this.messageIdProvider.deallocate(t);for(let n=0;n<e.granted.length;n++)if(0!=(128&e.granted[n])){const e=this.messageIdToTopic[t];e&&e.forEach((function(e){delete s._resubscribeTopics[e]}))}this._invokeStoreProcessingQueue(),a(null,e);break;case"unsuback":delete this.outgoing[t],this.messageIdProvider.deallocate(t),this._invokeStoreProcessingQueue(),a(null);break;default:s.emit("error",new Error("unrecognized packet type"))}this.disconnecting&&0===Object.keys(this.outgoing).length&&this.emit("outgoingEmpty")}else g("_handleAck :: Server sent an ack in error. Ignoring.")},R.prototype._handlePubrel=function(e,t){g("handling pubrel packet"),t=void 0!==t?t:A;const n=e.messageId,r=this,a={cmd:"pubcomp",messageId:n};r.incomingStore.get(e,(function(e,n){e?r._sendPacket(a,t):(r.emit("message",n.topic,n.payload,n),r.handleMessage(n,(function(e){if(e)return t(e);r.incomingStore.del(n,A),r._sendPacket(a,t)})))}))},R.prototype._handleDisconnect=function(e){this.emit("disconnect",e)},R.prototype._nextId=function(){return this.messageIdProvider.allocate()},R.prototype.getLastMessageId=function(){return this.messageIdProvider.getLastAllocated()},R.prototype._resubscribe=function(){g("_resubscribe");const e=Object.keys(this._resubscribeTopics);if(!this._firstConnection&&(this.options.clean||5===this.options.protocolVersion&&!this.connackPacket.sessionPresent)&&e.length>0)if(this.options.resubscribe)if(5===this.options.protocolVersion){g("_resubscribe: protocolVersion 5");for(let t=0;t<e.length;t++){const n={};n[e[t]]=this._resubscribeTopics[e[t]],n.resubscribe=!0,this.subscribe(n,{properties:n[e[t]].properties})}}else this._resubscribeTopics.resubscribe=!0,this.subscribe(this._resubscribeTopics);else this._resubscribeTopics={};this._firstConnection=!1},R.prototype._onConnect=function(e){if(this.disconnected)return void this.emit("connect",e);const t=this;function n(){let r=t.outgoingStore.createStream();function a(){t._storeProcessing=!1,t._packetIdsDuringStoreProcessing={}}function s(){r.destroy(),r=null,t._flushStoreProcessingQueue(),a()}function o(){if(!r)return;t._storeProcessing=!0;const e=r.read(1);let n;e?t._packetIdsDuringStoreProcessing[e.messageId]?o():t.disconnecting||t.reconnectTimer?r.destroy&&r.destroy():(n=t.outgoing[e.messageId]?t.outgoing[e.messageId].cb:null,t.outgoing[e.messageId]={volatile:!1,cb:function(e,t){n&&n(e,t),o()}},t._packetIdsDuringStoreProcessing[e.messageId]=!0,t.messageIdProvider.register(e.messageId)?t._sendPacket(e):g("messageId: %d has already used.",e.messageId)):r.once("readable",o)}t.once("close",s),r.on("error",(function(e){a(),t._flushStoreProcessingQueue(),t.removeListener("close",s),t.emit("error",e)})),r.on("end",(function(){let r=!0;for(const e in t._packetIdsDuringStoreProcessing)if(!t._packetIdsDuringStoreProcessing[e]){r=!1;break}r?(a(),t.removeListener("close",s),t._invokeAllStoreProcessingQueue(),t.emit("connect",e)):n()})),o()}this.connackPacket=e,this.messageIdProvider.clear(),this._setupPingTimer(),this.connected=!0,n()},R.prototype._invokeStoreProcessingQueue=function(){if(this._storeProcessingQueue.length>0){const e=this._storeProcessingQueue[0];if(e&&e.invoke())return this._storeProcessingQueue.shift(),!0}return!1},R.prototype._invokeAllStoreProcessingQueue=function(){for(;this._invokeStoreProcessingQueue(););},R.prototype._flushStoreProcessingQueue=function(){for(const e of this._storeProcessingQueue)e.cbStorePut&&e.cbStorePut(new Error("Connection closed")),e.callback&&e.callback(new Error("Connection closed"));this._storeProcessingQueue.splice(0)},t.exports=R}).call(this)}).call(this,e("_process"),void 0!==qt?qt:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./default-message-id-provider":7,"./store":8,"./topic-alias-recv":9,"./topic-alias-send":10,"./validations":11,_process:50,debug:18,events:22,inherits:24,"mqtt-packet":40,"readable-stream":69,reinterval:70,"rfdc/default":71,xtend:81}],2:[function(e,t,n){const{Buffer:r}=e("buffer"),a=e("readable-stream").Transform,s=e("duplexify");let o,i,c,l=!1;function d(){const e=new a;return e._write=function(e,t,n){o.sendSocketMessage({data:e.buffer,success:function(){n()},fail:function(){n(new Error)}})},e._flush=function(e){o.closeSocket({success:function(){e()}})},e}function u(e){e.hostname||(e.hostname="localhost"),e.path||(e.path="/"),e.wsOptions||(e.wsOptions={})}function h(e,t){const n="alis"===e.protocol?"wss":"ws";let r=n+"://"+e.hostname+e.path;return e.port&&80!==e.port&&443!==e.port&&(r=n+"://"+e.hostname+":"+e.port+e.path),"function"==typeof e.transformWsUrl&&(r=e.transformWsUrl(r,e,t)),r}function p(){l||(l=!0,o.onSocketOpen((function(){c.setReadable(i),c.setWritable(i),c.emit("connect")})),o.onSocketMessage((function(e){if("string"==typeof e.data){const t=r.from(e.data,"base64");i.push(t)}else{const t=new FileReader;t.addEventListener("load",(function(){let e=t.result;e=e instanceof ArrayBuffer?r.from(e):r.from(e,"utf8"),i.push(e)})),t.readAsArrayBuffer(e.data)}})),o.onSocketClose((function(){c.end(),c.destroy()})),o.onSocketError((function(e){c.destroy(e)})))}function f(e,t){if(t.hostname=t.hostname||t.host,!t.hostname)throw new Error("Could not determine host. Specify host manually.");const n="MQIsdp"===t.protocolId&&3===t.protocolVersion?"mqttv3.1":"mqtt";u(t);const r=h(t,e);return o=t.my,o.connectSocket({url:r,protocols:n}),i=d(),c=s.obj(),p(),c}t.exports=f},{buffer:17,duplexify:20,"readable-stream":69}],3:[function(e,t,n){const r=e("net"),a=e("debug")("mqttjs:tcp");function s(e,t){t.port=t.port||1883,t.hostname=t.hostname||t.host||"localhost";const n=t.port,s=t.hostname;return a("port %d and host %s",n,s),r.createConnection(n,s)}t.exports=s},{debug:18,net:16}],4:[function(e,t,n){const r=e("tls"),a=e("net"),s=e("debug")("mqttjs:tls");function o(e,t){t.port=t.port||8883,t.host=t.hostname||t.host||"localhost",0===a.isIP(t.host)&&(t.servername=t.host),t.rejectUnauthorized=!1!==t.rejectUnauthorized,delete t.path,s("port %d host %s rejectUnauthorized %b",t.port,t.host,t.rejectUnauthorized);const n=r.connect(t);function o(r){t.rejectUnauthorized&&e.emit("error",r),n.end()}return n.on("secureConnect",(function(){t.rejectUnauthorized&&!n.authorized?n.emit("error",new Error("TLS not authorized")):n.removeListener("error",o)})),n.on("error",o),n}t.exports=o},{debug:18,net:16,tls:16}],5:[function(e,t,n){(function(n){(function(){const{Buffer:r}=e("buffer"),a=e("ws"),s=e("debug")("mqttjs:ws"),o=e("duplexify"),i=e("readable-stream").Transform,c=["rejectUnauthorized","ca","cert","key","pfx","passphrase"],l=void 0!==n&&"browser"===n.title||"function"==typeof __webpack_require__;function d(e,t){let n=e.protocol+"://"+e.hostname+":"+e.port+e.path;return"function"==typeof e.transformWsUrl&&(n=e.transformWsUrl(n,e,t)),n}function u(e){const t=e;return e.hostname||(t.hostname="localhost"),e.port||("wss"===e.protocol?t.port=443:t.port=80),e.path||(t.path="/"),e.wsOptions||(t.wsOptions={}),l||"wss"!==e.protocol||c.forEach((function(n){Object.prototype.hasOwnProperty.call(e,n)&&!Object.prototype.hasOwnProperty.call(e.wsOptions,n)&&(t.wsOptions[n]=e[n])})),t}function h(e){const t=u(e);if(t.hostname||(t.hostname=t.host),!t.hostname){if("undefined"==typeof document)throw new Error("Could not determine host. Specify host manually.");const e=new URL(document.URL);t.hostname=e.hostname,t.port||(t.port=e.port)}return void 0===t.objectMode&&(t.objectMode=!(!0===t.binary||void 0===t.binary)),t}function p(e,t,n){s("createWebSocket"),s("protocol: "+n.protocolId+" "+n.protocolVersion);const r="MQIsdp"===n.protocolId&&3===n.protocolVersion?"mqttv3.1":"mqtt";return s("creating new Websocket for url: "+t+" and protocol: "+r),new a(t,[r],n.wsOptions)}function f(e,t){const n="MQIsdp"===t.protocolId&&3===t.protocolVersion?"mqttv3.1":"mqtt",r=d(t,e),a=new WebSocket(r,[n]);return a.binaryType="arraybuffer",a}function m(e,t){s("streamBuilder");const n=u(t),r=d(n,e),o=p(e,r,n),i=a.createWebSocketStream(o,n.wsOptions);return i.url=r,o.on("close",(()=>{i.destroy()})),i}function g(e,t){let n;s("browserStreamBuilder");const a=h(t).browserBufferSize||524288,c=t.browserBufferTimeout||1e3,l=!t.objectMode,d=f(e,t),u=m(t,C,I);t.objectMode||(u._writev=w),u.on("close",(()=>{d.close()}));const p=void 0!==d.addEventListener;function m(e,t,n){const r=new i({objectModeMode:e.objectMode});return r._write=t,r._flush=n,r}function g(){n.setReadable(u),n.setWritable(u),n.emit("connect")}function y(){n.end(),n.destroy()}function v(e){n.destroy(e)}function b(e){let t=e.data;t=t instanceof ArrayBuffer?r.from(t):r.from(t,"utf8"),u.push(t)}function w(e,t){const n=new Array(e.length);for(let t=0;t<e.length;t++)"string"==typeof e[t].chunk?n[t]=r.from(e[t],"utf8"):n[t]=e[t].chunk;this._write(r.concat(n),"binary",t)}function C(e,t,n){d.bufferedAmount>a&&setTimeout(C,c,e,t,n),l&&"string"==typeof e&&(e=r.from(e,"utf8"));try{d.send(e)}catch(e){return n(e)}n()}function I(e){d.close(),e()}return d.readyState===d.OPEN?n=u:(n=n=o(void 0,void 0,t),t.objectMode||(n._writev=w),p?d.addEventListener("open",g):d.onopen=g),n.socket=d,p?(d.addEventListener("close",y),d.addEventListener("error",v),d.addEventListener("message",b)):(d.onclose=y,d.onerror=v,d.onmessage=b),n}t.exports=l?g:m}).call(this)}).call(this,e("_process"))},{_process:50,buffer:17,debug:18,duplexify:20,"readable-stream":69,ws:80}],6:[function(e,t,n){const{Buffer:r}=e("buffer"),a=e("readable-stream").Transform,s=e("duplexify");let o,i,c;function l(){const e=new a;return e._write=function(e,t,n){o.send({data:e.buffer,success:function(){n()},fail:function(e){n(new Error(e))}})},e._flush=function(e){o.close({success:function(){e()}})},e}function d(e){e.hostname||(e.hostname="localhost"),e.path||(e.path="/"),e.wsOptions||(e.wsOptions={})}function u(e,t){const n="wxs"===e.protocol?"wss":"ws";let r=n+"://"+e.hostname+e.path;return e.port&&80!==e.port&&443!==e.port&&(r=n+"://"+e.hostname+":"+e.port+e.path),"function"==typeof e.transformWsUrl&&(r=e.transformWsUrl(r,e,t)),r}function h(){o.onOpen((function(){c.setReadable(i),c.setWritable(i),c.emit("connect")})),o.onMessage((function(e){let t=e.data;t=t instanceof ArrayBuffer?r.from(t):r.from(t,"utf8"),i.push(t)})),o.onClose((function(){c.end(),c.destroy()})),o.onError((function(e){c.destroy(new Error(e.errMsg))}))}function p(e,t){if(t.hostname=t.hostname||t.host,!t.hostname)throw new Error("Could not determine host. Specify host manually.");const n="MQIsdp"===t.protocolId&&3===t.protocolVersion?"mqttv3.1":"mqtt";d(t);const r=u(t,e);o=wx.connectSocket({url:r,protocols:[n]}),i=l(),c=s.obj(),c._destroy=function(e,t){o.close({success:function(){t&&t(e)}})};const a=c.destroy;return c.destroy=function(){c.destroy=a;const e=this;setTimeout((function(){o.close({fail:function(){e._destroy(new Error)}})}),0)}.bind(c),h(),c}t.exports=p},{buffer:17,duplexify:20,"readable-stream":69}],7:[function(e,t,n){function r(){if(!(this instanceof r))return new r;this.nextId=Math.max(1,Math.floor(65535*Math.random()))}r.prototype.allocate=function(){const e=this.nextId++;return 65536===this.nextId&&(this.nextId=1),e},r.prototype.getLastAllocated=function(){return 1===this.nextId?65535:this.nextId-1},r.prototype.register=function(e){return!0},r.prototype.deallocate=function(e){},r.prototype.clear=function(){},t.exports=r},{}],8:[function(e,t,n){const r=e("xtend"),a=e("readable-stream").Readable,s={objectMode:!0},o={clean:!0};function i(e){if(!(this instanceof i))return new i(e);this.options=e||{},this.options=r(o,e),this._inflights=new Map}i.prototype.put=function(e,t){return this._inflights.set(e.messageId,e),t&&t(),this},i.prototype.createStream=function(){const e=new a(s),t=[];let n=!1,r=0;return this._inflights.forEach((function(e,n){t.push(e)})),e._read=function(){!n&&r<t.length?this.push(t[r++]):this.push(null)},e.destroy=function(){if(n)return;const e=this;n=!0,setTimeout((function(){e.emit("close")}),0)},e},i.prototype.del=function(e,t){return(e=this._inflights.get(e.messageId))?(this._inflights.delete(e.messageId),t(null,e)):t&&t(new Error("missing packet")),this},i.prototype.get=function(e,t){return(e=this._inflights.get(e.messageId))?t(null,e):t&&t(new Error("missing packet")),this},i.prototype.close=function(e){this.options.clean&&(this._inflights=null),e&&e()},t.exports=i},{"readable-stream":69,xtend:81}],9:[function(e,t,n){function r(e){if(!(this instanceof r))return new r(e);this.aliasToTopic={},this.max=e}r.prototype.put=function(e,t){return!(0===t||t>this.max||(this.aliasToTopic[t]=e,this.length=Object.keys(this.aliasToTopic).length,0))},r.prototype.getTopicByAlias=function(e){return this.aliasToTopic[e]},r.prototype.clear=function(){this.aliasToTopic={}},t.exports=r},{}],10:[function(e,t,n){const r=e("lru-cache"),a=e("number-allocator").NumberAllocator;function s(e){if(!(this instanceof s))return new s(e);e>0&&(this.aliasToTopic=new r({max:e}),this.topicToAlias={},this.numberAllocator=new a(1,e),this.max=e,this.length=0)}s.prototype.put=function(e,t){if(0===t||t>this.max)return!1;const n=this.aliasToTopic.get(t);return n&&delete this.topicToAlias[n],this.aliasToTopic.set(t,e),this.topicToAlias[e]=t,this.numberAllocator.use(t),this.length=this.aliasToTopic.length,!0},s.prototype.getTopicByAlias=function(e){return this.aliasToTopic.get(e)},s.prototype.getAliasByTopic=function(e){const t=this.topicToAlias[e];return void 0!==t&&this.aliasToTopic.get(t),t},s.prototype.clear=function(){this.aliasToTopic.reset(),this.topicToAlias={},this.numberAllocator.clear(),this.length=0},s.prototype.getLruAlias=function(){const e=this.numberAllocator.firstVacant();return e||this.aliasToTopic.keys()[this.aliasToTopic.length-1]},t.exports=s},{"lru-cache":37,"number-allocator":46}],11:[function(e,t,n){function r(e){const t=e.split("/");for(let e=0;e<t.length;e++)if("+"!==t[e]){if("#"===t[e])return e===t.length-1;if(-1!==t[e].indexOf("+")||-1!==t[e].indexOf("#"))return!1}return!0}function a(e){if(0===e.length)return"empty_topic_list";for(let t=0;t<e.length;t++)if(!r(e[t]))return e[t];return null}t.exports={validateTopics:a}},{}],12:[function(e,t,n){(function(n){(function(){const r=e("../client"),a=e("../store"),s=e("url"),o=e("xtend"),i=e("debug")("mqttjs"),c={};function l(e){let t;e.auth&&(t=e.auth.match(/^(.+):(.+)$/),t?(e.username=t[1],e.password=t[2]):e.username=e.auth)}function d(e,t){if(i("connecting to an MQTT broker..."),"object"!=typeof e||t||(t=e,e=null),t=t||{},e){const n=s.parse(e,!0);if(null!=n.port&&(n.port=Number(n.port)),null===(t=o(n,t)).protocol)throw new Error("Missing protocol");t.protocol=t.protocol.replace(/:$/,"")}if(l(t),t.query&&"string"==typeof t.query.clientId&&(t.clientId=t.query.clientId),t.cert&&t.key){if(!t.protocol)throw new Error("Missing secure protocol key");if(-1===["mqtts","wss","wxs","alis"].indexOf(t.protocol))switch(t.protocol){case"mqtt":t.protocol="mqtts";break;case"ws":t.protocol="wss";break;case"wx":t.protocol="wxs";break;case"ali":t.protocol="alis";break;default:throw new Error('Unknown protocol for secure connection: "'+t.protocol+'"!')}}if(!c[t.protocol]){const e=-1!==["mqtts","wss"].indexOf(t.protocol);t.protocol=["mqtt","mqtts","ws","wss","wx","wxs","ali","alis"].filter((function(t,n){return(!e||n%2!=0)&&"function"==typeof c[t]}))[0]}if(!1===t.clean&&!t.clientId)throw new Error("Missing clientId for unclean clients");function n(e){return t.servers&&(e._reconnectCount&&e._reconnectCount!==t.servers.length||(e._reconnectCount=0),t.host=t.servers[e._reconnectCount].host,t.port=t.servers[e._reconnectCount].port,t.protocol=t.servers[e._reconnectCount].protocol?t.servers[e._reconnectCount].protocol:t.defaultProtocol,t.hostname=t.host,e._reconnectCount++),i("calling streambuilder for",t.protocol),c[t.protocol](e,t)}t.protocol&&(t.defaultProtocol=t.protocol);const a=new r(n,t);return a.on("error",(function(){})),a}void 0!==n&&"browser"!==n.title||"function"!=typeof __webpack_require__?(c.mqtt=e("./tcp"),c.tcp=e("./tcp"),c.ssl=e("./tls"),c.tls=e("./tls"),c.mqtts=e("./tls")):(c.wx=e("./wx"),c.wxs=e("./wx"),c.ali=e("./ali"),c.alis=e("./ali")),c.ws=e("./ws"),c.wss=e("./ws"),t.exports=d,t.exports.connect=d,t.exports.MqttClient=r,t.exports.Store=a}).call(this)}).call(this,e("_process"))},{"../client":1,"../store":8,"./ali":2,"./tcp":3,"./tls":4,"./ws":5,"./wx":6,_process:50,debug:18,url:76,xtend:81}],13:[function(e,t,n){n.byteLength=d,n.toByteArray=h,n.fromByteArray=m;for(var r=[],a=[],s="undefined"!=typeof Uint8Array?Uint8Array:Array,o="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",i=0,c=o.length;i<c;++i)r[i]=o[i],a[o.charCodeAt(i)]=i;function l(e){var t=e.length;if(t%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var n=e.indexOf("=");return-1===n&&(n=t),[n,n===t?0:4-n%4]}function d(e){var t=l(e),n=t[0],r=t[1];return 3*(n+r)/4-r}function u(e,t,n){return 3*(t+n)/4-n}function h(e){var t,n,r=l(e),o=r[0],i=r[1],c=new s(u(e,o,i)),d=0,h=i>0?o-4:o;for(n=0;n<h;n+=4)t=a[e.charCodeAt(n)]<<18|a[e.charCodeAt(n+1)]<<12|a[e.charCodeAt(n+2)]<<6|a[e.charCodeAt(n+3)],c[d++]=t>>16&255,c[d++]=t>>8&255,c[d++]=255&t;return 2===i&&(t=a[e.charCodeAt(n)]<<2|a[e.charCodeAt(n+1)]>>4,c[d++]=255&t),1===i&&(t=a[e.charCodeAt(n)]<<10|a[e.charCodeAt(n+1)]<<4|a[e.charCodeAt(n+2)]>>2,c[d++]=t>>8&255,c[d++]=255&t),c}function p(e){return r[e>>18&63]+r[e>>12&63]+r[e>>6&63]+r[63&e]}function f(e,t,n){for(var r,a=[],s=t;s<n;s+=3)r=(e[s]<<16&16711680)+(e[s+1]<<8&65280)+(255&e[s+2]),a.push(p(r));return a.join("")}function m(e){for(var t,n=e.length,a=n%3,s=[],o=16383,i=0,c=n-a;i<c;i+=o)s.push(f(e,i,i+o>c?c:i+o));return 1===a?(t=e[n-1],s.push(r[t>>2]+r[t<<4&63]+"==")):2===a&&(t=(e[n-2]<<8)+e[n-1],s.push(r[t>>10]+r[t>>4&63]+r[t<<2&63]+"=")),s.join("")}a["-".charCodeAt(0)]=62,a["_".charCodeAt(0)]=63},{}],14:[function(e,t,n){const{Buffer:r}=e("buffer"),a=Symbol.for("BufferList");function s(e){if(!(this instanceof s))return new s(e);s._init.call(this,e)}s._init=function(e){Object.defineProperty(this,a,{value:!0}),this._bufs=[],this.length=0,e&&this.append(e)},s.prototype._new=function(e){return new s(e)},s.prototype._offset=function(e){if(0===e)return[0,0];let t=0;for(let n=0;n<this._bufs.length;n++){const r=t+this._bufs[n].length;if(e<r||n===this._bufs.length-1)return[n,e-t];t=r}},s.prototype._reverseOffset=function(e){const t=e[0];let n=e[1];for(let e=0;e<t;e++)n+=this._bufs[e].length;return n},s.prototype.get=function(e){if(e>this.length||e<0)return;const t=this._offset(e);return this._bufs[t[0]][t[1]]},s.prototype.slice=function(e,t){return"number"==typeof e&&e<0&&(e+=this.length),"number"==typeof t&&t<0&&(t+=this.length),this.copy(null,0,e,t)},s.prototype.copy=function(e,t,n,a){if(("number"!=typeof n||n<0)&&(n=0),("number"!=typeof a||a>this.length)&&(a=this.length),n>=this.length)return e||r.alloc(0);if(a<=0)return e||r.alloc(0);const s=!!e,o=this._offset(n),i=a-n;let c=i,l=s&&t||0,d=o[1];if(0===n&&a===this.length){if(!s)return 1===this._bufs.length?this._bufs[0]:r.concat(this._bufs,this.length);for(let t=0;t<this._bufs.length;t++)this._bufs[t].copy(e,l),l+=this._bufs[t].length;return e}if(c<=this._bufs[o[0]].length-d)return s?this._bufs[o[0]].copy(e,t,d,d+c):this._bufs[o[0]].slice(d,d+c);s||(e=r.allocUnsafe(i));for(let t=o[0];t<this._bufs.length;t++){const n=this._bufs[t].length-d;if(!(c>n)){this._bufs[t].copy(e,l,d,d+c),l+=n;break}this._bufs[t].copy(e,l,d),l+=n,c-=n,d&&(d=0)}return e.length>l?e.slice(0,l):e},s.prototype.shallowSlice=function(e,t){if(e=e||0,t="number"!=typeof t?this.length:t,e<0&&(e+=this.length),t<0&&(t+=this.length),e===t)return this._new();const n=this._offset(e),r=this._offset(t),a=this._bufs.slice(n[0],r[0]+1);return 0===r[1]?a.pop():a[a.length-1]=a[a.length-1].slice(0,r[1]),0!==n[1]&&(a[0]=a[0].slice(n[1])),this._new(a)},s.prototype.toString=function(e,t,n){return this.slice(t,n).toString(e)},s.prototype.consume=function(e){if(e=Math.trunc(e),Number.isNaN(e)||e<=0)return this;for(;this._bufs.length;){if(!(e>=this._bufs[0].length)){this._bufs[0]=this._bufs[0].slice(e),this.length-=e;break}e-=this._bufs[0].length,this.length-=this._bufs[0].length,this._bufs.shift()}return this},s.prototype.duplicate=function(){const e=this._new();for(let t=0;t<this._bufs.length;t++)e.append(this._bufs[t]);return e},s.prototype.append=function(e){if(null==e)return this;if(e.buffer)this._appendBuffer(r.from(e.buffer,e.byteOffset,e.byteLength));else if(Array.isArray(e))for(let t=0;t<e.length;t++)this.append(e[t]);else if(this._isBufferList(e))for(let t=0;t<e._bufs.length;t++)this.append(e._bufs[t]);else"number"==typeof e&&(e=e.toString()),this._appendBuffer(r.from(e));return this},s.prototype._appendBuffer=function(e){this._bufs.push(e),this.length+=e.length},s.prototype.indexOf=function(e,t,n){if(void 0===n&&"string"==typeof t&&(n=t,t=void 0),"function"==typeof e||Array.isArray(e))throw new TypeError('The "value" argument must be one of type string, Buffer, BufferList, or Uint8Array.');if("number"==typeof e?e=r.from([e]):"string"==typeof e?e=r.from(e,n):this._isBufferList(e)?e=e.slice():Array.isArray(e.buffer)?e=r.from(e.buffer,e.byteOffset,e.byteLength):r.isBuffer(e)||(e=r.from(e)),t=Number(t||0),isNaN(t)&&(t=0),t<0&&(t=this.length+t),t<0&&(t=0),0===e.length)return t>this.length?this.length:t;const a=this._offset(t);let s=a[0],o=a[1];for(;s<this._bufs.length;s++){const t=this._bufs[s];for(;o<t.length;)if(t.length-o>=e.length){const n=t.indexOf(e,o);if(-1!==n)return this._reverseOffset([s,n]);o=t.length-e.length+1}else{const t=this._reverseOffset([s,o]);if(this._match(t,e))return t;o++}o=0}return-1},s.prototype._match=function(e,t){if(this.length-e<t.length)return!1;for(let n=0;n<t.length;n++)if(this.get(e+n)!==t[n])return!1;return!0},function(){const e={readDoubleBE:8,readDoubleLE:8,readFloatBE:4,readFloatLE:4,readInt32BE:4,readInt32LE:4,readUInt32BE:4,readUInt32LE:4,readInt16BE:2,readInt16LE:2,readUInt16BE:2,readUInt16LE:2,readInt8:1,readUInt8:1,readIntBE:null,readIntLE:null,readUIntBE:null,readUIntLE:null};for(const t in e)!function(t){null===e[t]?s.prototype[t]=function(e,n){return this.slice(e,e+n)[t](0,n)}:s.prototype[t]=function(n=0){return this.slice(n,n+e[t])[t](0)}}(t)}(),s.prototype._isBufferList=function(e){return e instanceof s||s.isBufferList(e)},s.isBufferList=function(e){return null!=e&&e[a]},t.exports=s},{buffer:17}],15:[function(e,t,n){const r=e("readable-stream").Duplex,a=e("inherits"),s=e("./BufferList");function o(e){if(!(this instanceof o))return new o(e);if("function"==typeof e){this._callback=e;const t=function(e){this._callback&&(this._callback(e),this._callback=null)}.bind(this);this.on("pipe",(function(e){e.on("error",t)})),this.on("unpipe",(function(e){e.removeListener("error",t)})),e=null}s._init.call(this,e),r.call(this)}a(o,r),Object.assign(o.prototype,s.prototype),o.prototype._new=function(e){return new o(e)},o.prototype._write=function(e,t,n){this._appendBuffer(e),"function"==typeof n&&n()},o.prototype._read=function(e){if(!this.length)return this.push(null);e=Math.min(e,this.length),this.push(this.slice(0,e)),this.consume(e)},o.prototype.end=function(e){r.prototype.end.call(this,e),this._callback&&(this._callback(null,this.slice()),this._callback=null)},o.prototype._destroy=function(e,t){this._bufs.length=0,this.length=0,t(e)},o.prototype._isBufferList=function(e){return e instanceof o||e instanceof s||o.isBufferList(e)},o.isBufferList=s.isBufferList,t.exports=o,t.exports.BufferListStream=o,t.exports.BufferList=s},{"./BufferList":14,inherits:24,"readable-stream":69}],16:[function(e,t,n){},{}],17:[function(e,t,n){(function(t){(function(){var t=e("base64-js"),r=e("ieee754");n.Buffer=i,n.SlowBuffer=y,n.INSPECT_MAX_BYTES=50;var a=2147483647;function s(){try{var e=new Uint8Array(1);return e.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}},42===e.foo()}catch(e){return!1}}function o(e){if(e>a)throw new RangeError('The value "'+e+'" is invalid for option "size"');var t=new Uint8Array(e);return t.__proto__=i.prototype,t}function i(e,t,n){if("number"==typeof e){if("string"==typeof t)throw new TypeError('The "string" argument must be of type string. Received type number');return u(e)}return c(e,t,n)}function c(e,t,n){if("string"==typeof e)return h(e,t);if(ArrayBuffer.isView(e))return p(e);if(null==e)throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e);if(G(e,ArrayBuffer)||e&&G(e.buffer,ArrayBuffer))return f(e,t,n);if("number"==typeof e)throw new TypeError('The "value" argument must not be of type number. Received type number');var r=e.valueOf&&e.valueOf();if(null!=r&&r!==e)return i.from(r,t,n);var a=m(e);if(a)return a;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof e[Symbol.toPrimitive])return i.from(e[Symbol.toPrimitive]("string"),t,n);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e)}function l(e){if("number"!=typeof e)throw new TypeError('"size" argument must be of type number');if(e<0)throw new RangeError('The value "'+e+'" is invalid for option "size"')}function d(e,t,n){return l(e),e<=0?o(e):void 0!==t?"string"==typeof n?o(e).fill(t,n):o(e).fill(t):o(e)}function u(e){return l(e),o(e<0?0:0|g(e))}function h(e,t){if("string"==typeof t&&""!==t||(t="utf8"),!i.isEncoding(t))throw new TypeError("Unknown encoding: "+t);var n=0|v(e,t),r=o(n),a=r.write(e,t);return a!==n&&(r=r.slice(0,a)),r}function p(e){for(var t=e.length<0?0:0|g(e.length),n=o(t),r=0;r<t;r+=1)n[r]=255&e[r];return n}function f(e,t,n){if(t<0||e.byteLength<t)throw new RangeError('"offset" is outside of buffer bounds');if(e.byteLength<t+(n||0))throw new RangeError('"length" is outside of buffer bounds');var r;return(r=void 0===t&&void 0===n?new Uint8Array(e):void 0===n?new Uint8Array(e,t):new Uint8Array(e,t,n)).__proto__=i.prototype,r}function m(e){if(i.isBuffer(e)){var t=0|g(e.length),n=o(t);return 0===n.length||e.copy(n,0,0,t),n}return void 0!==e.length?"number"!=typeof e.length||Y(e.length)?o(0):p(e):"Buffer"===e.type&&Array.isArray(e.data)?p(e.data):void 0}function g(e){if(e>=a)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+a.toString(16)+" bytes");return 0|e}function y(e){return+e!=e&&(e=0),i.alloc(+e)}function v(e,t){if(i.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||G(e,ArrayBuffer))return e.byteLength;if("string"!=typeof e)throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof e);var n=e.length,r=arguments.length>2&&!0===arguments[2];if(!r&&0===n)return 0;for(var a=!1;;)switch(t){case"ascii":case"latin1":case"binary":return n;case"utf8":case"utf-8":return z(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*n;case"hex":return n>>>1;case"base64":return J(e).length;default:if(a)return r?-1:z(e).length;t=(""+t).toLowerCase(),a=!0}}function b(e,t,n){var r=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===n||n>this.length)&&(n=this.length),n<=0)return"";if((n>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return x(this,t,n);case"utf8":case"utf-8":return R(this,t,n);case"ascii":return P(this,t,n);case"latin1":case"binary":return U(this,t,n);case"base64":return A(this,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return D(this,t,n);default:if(r)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),r=!0}}function w(e,t,n){var r=e[t];e[t]=e[n],e[n]=r}function C(e,t,n,r,a){if(0===e.length)return-1;if("string"==typeof n?(r=n,n=0):n>2147483647?n=2147483647:n<-2147483648&&(n=-2147483648),Y(n=+n)&&(n=a?0:e.length-1),n<0&&(n=e.length+n),n>=e.length){if(a)return-1;n=e.length-1}else if(n<0){if(!a)return-1;n=0}if("string"==typeof t&&(t=i.from(t,r)),i.isBuffer(t))return 0===t.length?-1:I(e,t,n,r,a);if("number"==typeof t)return t&=255,"function"==typeof Uint8Array.prototype.indexOf?a?Uint8Array.prototype.indexOf.call(e,t,n):Uint8Array.prototype.lastIndexOf.call(e,t,n):I(e,[t],n,r,a);throw new TypeError("val must be string, number or Buffer")}function I(e,t,n,r,a){var s,o=1,i=e.length,c=t.length;if(void 0!==r&&("ucs2"===(r=String(r).toLowerCase())||"ucs-2"===r||"utf16le"===r||"utf-16le"===r)){if(e.length<2||t.length<2)return-1;o=2,i/=2,c/=2,n/=2}function l(e,t){return 1===o?e[t]:e.readUInt16BE(t*o)}if(a){var d=-1;for(s=n;s<i;s++)if(l(e,s)===l(t,-1===d?0:s-d)){if(-1===d&&(d=s),s-d+1===c)return d*o}else-1!==d&&(s-=s-d),d=-1}else for(n+c>i&&(n=i-c),s=n;s>=0;s--){for(var u=!0,h=0;h<c;h++)if(l(e,s+h)!==l(t,h)){u=!1;break}if(u)return s}return-1}function S(e,t,n,r){n=Number(n)||0;var a=e.length-n;r?(r=Number(r))>a&&(r=a):r=a;var s=t.length;r>s/2&&(r=s/2);for(var o=0;o<r;++o){var i=parseInt(t.substr(2*o,2),16);if(Y(i))return o;e[n+o]=i}return o}function _(e,t,n,r){return W(z(t,e.length-n),e,n,r)}function k(e,t,n,r){return W(V(t),e,n,r)}function O(e,t,n,r){return k(e,t,n,r)}function T(e,t,n,r){return W(J(t),e,n,r)}function E(e,t,n,r){return W(H(t,e.length-n),e,n,r)}function A(e,n,r){return 0===n&&r===e.length?t.fromByteArray(e):t.fromByteArray(e.slice(n,r))}function R(e,t,n){n=Math.min(e.length,n);for(var r=[],a=t;a<n;){var s,o,i,c,l=e[a],d=null,u=l>239?4:l>223?3:l>191?2:1;if(a+u<=n)switch(u){case 1:l<128&&(d=l);break;case 2:128==(192&(s=e[a+1]))&&(c=(31&l)<<6|63&s)>127&&(d=c);break;case 3:s=e[a+1],o=e[a+2],128==(192&s)&&128==(192&o)&&(c=(15&l)<<12|(63&s)<<6|63&o)>2047&&(c<55296||c>57343)&&(d=c);break;case 4:s=e[a+1],o=e[a+2],i=e[a+3],128==(192&s)&&128==(192&o)&&128==(192&i)&&(c=(15&l)<<18|(63&s)<<12|(63&o)<<6|63&i)>65535&&c<1114112&&(d=c)}null===d?(d=65533,u=1):d>65535&&(d-=65536,r.push(d>>>10&1023|55296),d=56320|1023&d),r.push(d),a+=u}return j(r)}n.kMaxLength=a,i.TYPED_ARRAY_SUPPORT=s(),i.TYPED_ARRAY_SUPPORT||"undefined"==typeof console||"function"!=typeof console.error||console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support."),Object.defineProperty(i.prototype,"parent",{enumerable:!0,get:function(){if(i.isBuffer(this))return this.buffer}}),Object.defineProperty(i.prototype,"offset",{enumerable:!0,get:function(){if(i.isBuffer(this))return this.byteOffset}}),"undefined"!=typeof Symbol&&null!=Symbol.species&&i[Symbol.species]===i&&Object.defineProperty(i,Symbol.species,{value:null,configurable:!0,enumerable:!1,writable:!1}),i.poolSize=8192,i.from=function(e,t,n){return c(e,t,n)},i.prototype.__proto__=Uint8Array.prototype,i.__proto__=Uint8Array,i.alloc=function(e,t,n){return d(e,t,n)},i.allocUnsafe=function(e){return u(e)},i.allocUnsafeSlow=function(e){return u(e)},i.isBuffer=function(e){return null!=e&&!0===e._isBuffer&&e!==i.prototype},i.compare=function(e,t){if(G(e,Uint8Array)&&(e=i.from(e,e.offset,e.byteLength)),G(t,Uint8Array)&&(t=i.from(t,t.offset,t.byteLength)),!i.isBuffer(e)||!i.isBuffer(t))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(e===t)return 0;for(var n=e.length,r=t.length,a=0,s=Math.min(n,r);a<s;++a)if(e[a]!==t[a]){n=e[a],r=t[a];break}return n<r?-1:r<n?1:0},i.isEncoding=function(e){switch(String(e).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},i.concat=function(e,t){if(!Array.isArray(e))throw new TypeError('"list" argument must be an Array of Buffers');if(0===e.length)return i.alloc(0);var n;if(void 0===t)for(t=0,n=0;n<e.length;++n)t+=e[n].length;var r=i.allocUnsafe(t),a=0;for(n=0;n<e.length;++n){var s=e[n];if(G(s,Uint8Array)&&(s=i.from(s)),!i.isBuffer(s))throw new TypeError('"list" argument must be an Array of Buffers');s.copy(r,a),a+=s.length}return r},i.byteLength=v,i.prototype._isBuffer=!0,i.prototype.swap16=function(){var e=this.length;if(e%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(var t=0;t<e;t+=2)w(this,t,t+1);return this},i.prototype.swap32=function(){var e=this.length;if(e%4!=0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(var t=0;t<e;t+=4)w(this,t,t+3),w(this,t+1,t+2);return this},i.prototype.swap64=function(){var e=this.length;if(e%8!=0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(var t=0;t<e;t+=8)w(this,t,t+7),w(this,t+1,t+6),w(this,t+2,t+5),w(this,t+3,t+4);return this},i.prototype.toString=function(){var e=this.length;return 0===e?"":0===arguments.length?R(this,0,e):b.apply(this,arguments)},i.prototype.toLocaleString=i.prototype.toString,i.prototype.equals=function(e){if(!i.isBuffer(e))throw new TypeError("Argument must be a Buffer");return this===e||0===i.compare(this,e)},i.prototype.inspect=function(){var e="",t=n.INSPECT_MAX_BYTES;return e=this.toString("hex",0,t).replace(/(.{2})/g,"$1 ").trim(),this.length>t&&(e+=" ... "),"<Buffer "+e+">"},i.prototype.compare=function(e,t,n,r,a){if(G(e,Uint8Array)&&(e=i.from(e,e.offset,e.byteLength)),!i.isBuffer(e))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof e);if(void 0===t&&(t=0),void 0===n&&(n=e?e.length:0),void 0===r&&(r=0),void 0===a&&(a=this.length),t<0||n>e.length||r<0||a>this.length)throw new RangeError("out of range index");if(r>=a&&t>=n)return 0;if(r>=a)return-1;if(t>=n)return 1;if(this===e)return 0;for(var s=(a>>>=0)-(r>>>=0),o=(n>>>=0)-(t>>>=0),c=Math.min(s,o),l=this.slice(r,a),d=e.slice(t,n),u=0;u<c;++u)if(l[u]!==d[u]){s=l[u],o=d[u];break}return s<o?-1:o<s?1:0},i.prototype.includes=function(e,t,n){return-1!==this.indexOf(e,t,n)},i.prototype.indexOf=function(e,t,n){return C(this,e,t,n,!0)},i.prototype.lastIndexOf=function(e,t,n){return C(this,e,t,n,!1)},i.prototype.write=function(e,t,n,r){if(void 0===t)r="utf8",n=this.length,t=0;else if(void 0===n&&"string"==typeof t)r=t,n=this.length,t=0;else{if(!isFinite(t))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");t>>>=0,isFinite(n)?(n>>>=0,void 0===r&&(r="utf8")):(r=n,n=void 0)}var a=this.length-t;if((void 0===n||n>a)&&(n=a),e.length>0&&(n<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");r||(r="utf8");for(var s=!1;;)switch(r){case"hex":return S(this,e,t,n);case"utf8":case"utf-8":return _(this,e,t,n);case"ascii":return k(this,e,t,n);case"latin1":case"binary":return O(this,e,t,n);case"base64":return T(this,e,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return E(this,e,t,n);default:if(s)throw new TypeError("Unknown encoding: "+r);r=(""+r).toLowerCase(),s=!0}},i.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var M=4096;function j(e){var t=e.length;if(t<=M)return String.fromCharCode.apply(String,e);for(var n="",r=0;r<t;)n+=String.fromCharCode.apply(String,e.slice(r,r+=M));return n}function P(e,t,n){var r="";n=Math.min(e.length,n);for(var a=t;a<n;++a)r+=String.fromCharCode(127&e[a]);return r}function U(e,t,n){var r="";n=Math.min(e.length,n);for(var a=t;a<n;++a)r+=String.fromCharCode(e[a]);return r}function x(e,t,n){var r=e.length;(!t||t<0)&&(t=0),(!n||n<0||n>r)&&(n=r);for(var a="",s=t;s<n;++s)a+=Q(e[s]);return a}function D(e,t,n){for(var r=e.slice(t,n),a="",s=0;s<r.length;s+=2)a+=String.fromCharCode(r[s]+256*r[s+1]);return a}function q(e,t,n){if(e%1!=0||e<0)throw new RangeError("offset is not uint");if(e+t>n)throw new RangeError("Trying to access beyond buffer length")}function N(e,t,n,r,a,s){if(!i.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>a||t<s)throw new RangeError('"value" argument is out of bounds');if(n+r>e.length)throw new RangeError("Index out of range")}function B(e,t,n,r,a,s){if(n+r>e.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("Index out of range")}function L(e,t,n,a,s){return t=+t,n>>>=0,s||B(e,t,n,4),r.write(e,t,n,a,23,4),n+4}function F(e,t,n,a,s){return t=+t,n>>>=0,s||B(e,t,n,8),r.write(e,t,n,a,52,8),n+8}i.prototype.slice=function(e,t){var n=this.length;(e=~~e)<0?(e+=n)<0&&(e=0):e>n&&(e=n),(t=void 0===t?n:~~t)<0?(t+=n)<0&&(t=0):t>n&&(t=n),t<e&&(t=e);var r=this.subarray(e,t);return r.__proto__=i.prototype,r},i.prototype.readUIntLE=function(e,t,n){e>>>=0,t>>>=0,n||q(e,t,this.length);for(var r=this[e],a=1,s=0;++s<t&&(a*=256);)r+=this[e+s]*a;return r},i.prototype.readUIntBE=function(e,t,n){e>>>=0,t>>>=0,n||q(e,t,this.length);for(var r=this[e+--t],a=1;t>0&&(a*=256);)r+=this[e+--t]*a;return r},i.prototype.readUInt8=function(e,t){return e>>>=0,t||q(e,1,this.length),this[e]},i.prototype.readUInt16LE=function(e,t){return e>>>=0,t||q(e,2,this.length),this[e]|this[e+1]<<8},i.prototype.readUInt16BE=function(e,t){return e>>>=0,t||q(e,2,this.length),this[e]<<8|this[e+1]},i.prototype.readUInt32LE=function(e,t){return e>>>=0,t||q(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},i.prototype.readUInt32BE=function(e,t){return e>>>=0,t||q(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},i.prototype.readIntLE=function(e,t,n){e>>>=0,t>>>=0,n||q(e,t,this.length);for(var r=this[e],a=1,s=0;++s<t&&(a*=256);)r+=this[e+s]*a;return r>=(a*=128)&&(r-=Math.pow(2,8*t)),r},i.prototype.readIntBE=function(e,t,n){e>>>=0,t>>>=0,n||q(e,t,this.length);for(var r=t,a=1,s=this[e+--r];r>0&&(a*=256);)s+=this[e+--r]*a;return s>=(a*=128)&&(s-=Math.pow(2,8*t)),s},i.prototype.readInt8=function(e,t){return e>>>=0,t||q(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},i.prototype.readInt16LE=function(e,t){e>>>=0,t||q(e,2,this.length);var n=this[e]|this[e+1]<<8;return 32768&n?4294901760|n:n},i.prototype.readInt16BE=function(e,t){e>>>=0,t||q(e,2,this.length);var n=this[e+1]|this[e]<<8;return 32768&n?4294901760|n:n},i.prototype.readInt32LE=function(e,t){return e>>>=0,t||q(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},i.prototype.readInt32BE=function(e,t){return e>>>=0,t||q(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},i.prototype.readFloatLE=function(e,t){return e>>>=0,t||q(e,4,this.length),r.read(this,e,!0,23,4)},i.prototype.readFloatBE=function(e,t){return e>>>=0,t||q(e,4,this.length),r.read(this,e,!1,23,4)},i.prototype.readDoubleLE=function(e,t){return e>>>=0,t||q(e,8,this.length),r.read(this,e,!0,52,8)},i.prototype.readDoubleBE=function(e,t){return e>>>=0,t||q(e,8,this.length),r.read(this,e,!1,52,8)},i.prototype.writeUIntLE=function(e,t,n,r){e=+e,t>>>=0,n>>>=0,r||N(this,e,t,n,Math.pow(2,8*n)-1,0);var a=1,s=0;for(this[t]=255&e;++s<n&&(a*=256);)this[t+s]=e/a&255;return t+n},i.prototype.writeUIntBE=function(e,t,n,r){e=+e,t>>>=0,n>>>=0,r||N(this,e,t,n,Math.pow(2,8*n)-1,0);var a=n-1,s=1;for(this[t+a]=255&e;--a>=0&&(s*=256);)this[t+a]=e/s&255;return t+n},i.prototype.writeUInt8=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,1,255,0),this[t]=255&e,t+1},i.prototype.writeUInt16LE=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,2,65535,0),this[t]=255&e,this[t+1]=e>>>8,t+2},i.prototype.writeUInt16BE=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=255&e,t+2},i.prototype.writeUInt32LE=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,4,4294967295,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e,t+4},i.prototype.writeUInt32BE=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,4,4294967295,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},i.prototype.writeIntLE=function(e,t,n,r){if(e=+e,t>>>=0,!r){var a=Math.pow(2,8*n-1);N(this,e,t,n,a-1,-a)}var s=0,o=1,i=0;for(this[t]=255&e;++s<n&&(o*=256);)e<0&&0===i&&0!==this[t+s-1]&&(i=1),this[t+s]=(e/o>>0)-i&255;return t+n},i.prototype.writeIntBE=function(e,t,n,r){if(e=+e,t>>>=0,!r){var a=Math.pow(2,8*n-1);N(this,e,t,n,a-1,-a)}var s=n-1,o=1,i=0;for(this[t+s]=255&e;--s>=0&&(o*=256);)e<0&&0===i&&0!==this[t+s+1]&&(i=1),this[t+s]=(e/o>>0)-i&255;return t+n},i.prototype.writeInt8=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,1,127,-128),e<0&&(e=255+e+1),this[t]=255&e,t+1},i.prototype.writeInt16LE=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,2,32767,-32768),this[t]=255&e,this[t+1]=e>>>8,t+2},i.prototype.writeInt16BE=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=255&e,t+2},i.prototype.writeInt32LE=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,4,2147483647,-2147483648),this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4},i.prototype.writeInt32BE=function(e,t,n){return e=+e,t>>>=0,n||N(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},i.prototype.writeFloatLE=function(e,t,n){return L(this,e,t,!0,n)},i.prototype.writeFloatBE=function(e,t,n){return L(this,e,t,!1,n)},i.prototype.writeDoubleLE=function(e,t,n){return F(this,e,t,!0,n)},i.prototype.writeDoubleBE=function(e,t,n){return F(this,e,t,!1,n)},i.prototype.copy=function(e,t,n,r){if(!i.isBuffer(e))throw new TypeError("argument should be a Buffer");if(n||(n=0),r||0===r||(r=this.length),t>=e.length&&(t=e.length),t||(t=0),r>0&&r<n&&(r=n),r===n)return 0;if(0===e.length||0===this.length)return 0;if(t<0)throw new RangeError("targetStart out of bounds");if(n<0||n>=this.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("sourceEnd out of bounds");r>this.length&&(r=this.length),e.length-t<r-n&&(r=e.length-t+n);var a=r-n;if(this===e&&"function"==typeof Uint8Array.prototype.copyWithin)this.copyWithin(t,n,r);else if(this===e&&n<t&&t<r)for(var s=a-1;s>=0;--s)e[s+t]=this[s+n];else Uint8Array.prototype.set.call(e,this.subarray(n,r),t);return a},i.prototype.fill=function(e,t,n,r){if("string"==typeof e){if("string"==typeof t?(r=t,t=0,n=this.length):"string"==typeof n&&(r=n,n=this.length),void 0!==r&&"string"!=typeof r)throw new TypeError("encoding must be a string");if("string"==typeof r&&!i.isEncoding(r))throw new TypeError("Unknown encoding: "+r);if(1===e.length){var a=e.charCodeAt(0);("utf8"===r&&a<128||"latin1"===r)&&(e=a)}}else"number"==typeof e&&(e&=255);if(t<0||this.length<t||this.length<n)throw new RangeError("Out of range index");if(n<=t)return this;var s;if(t>>>=0,n=void 0===n?this.length:n>>>0,e||(e=0),"number"==typeof e)for(s=t;s<n;++s)this[s]=e;else{var o=i.isBuffer(e)?e:i.from(e,r),c=o.length;if(0===c)throw new TypeError('The value "'+e+'" is invalid for argument "value"');for(s=0;s<n-t;++s)this[s+t]=o[s%c]}return this};var K=/[^+/0-9A-Za-z-_]/g;function $(e){if((e=(e=e.split("=")[0]).trim().replace(K,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}function Q(e){return e<16?"0"+e.toString(16):e.toString(16)}function z(e,t){var n;t=t||1/0;for(var r=e.length,a=null,s=[],o=0;o<r;++o){if((n=e.charCodeAt(o))>55295&&n<57344){if(!a){if(n>56319){(t-=3)>-1&&s.push(239,191,189);continue}if(o+1===r){(t-=3)>-1&&s.push(239,191,189);continue}a=n;continue}if(n<56320){(t-=3)>-1&&s.push(239,191,189),a=n;continue}n=65536+(a-55296<<10|n-56320)}else a&&(t-=3)>-1&&s.push(239,191,189);if(a=null,n<128){if((t-=1)<0)break;s.push(n)}else if(n<2048){if((t-=2)<0)break;s.push(n>>6|192,63&n|128)}else if(n<65536){if((t-=3)<0)break;s.push(n>>12|224,n>>6&63|128,63&n|128)}else{if(!(n<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;s.push(n>>18|240,n>>12&63|128,n>>6&63|128,63&n|128)}}return s}function V(e){for(var t=[],n=0;n<e.length;++n)t.push(255&e.charCodeAt(n));return t}function H(e,t){for(var n,r,a,s=[],o=0;o<e.length&&!((t-=2)<0);++o)r=(n=e.charCodeAt(o))>>8,a=n%256,s.push(a),s.push(r);return s}function J(e){return t.toByteArray($(e))}function W(e,t,n,r){for(var a=0;a<r&&!(a+n>=t.length||a>=e.length);++a)t[a+n]=e[a];return a}function G(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}function Y(e){return e!=e}}).call(this)}).call(this,e("buffer").Buffer)},{"base64-js":13,buffer:17,ieee754:23}],18:[function(e,t,n){(function(r){(function(){function a(){return!("undefined"==typeof window||!window.process||"renderer"!==window.process.type&&!window.process.__nwjs)||("undefined"==typeof navigator||!navigator.userAgent||!navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))&&("undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/))}function s(e){if(e[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+e[0]+(this.useColors?"%c ":" ")+"+"+t.exports.humanize(this.diff),!this.useColors)return;const n="color: "+this.color;e.splice(1,0,n,"color: inherit");let r=0,a=0;e[0].replace(/%[a-zA-Z%]/g,(e=>{"%%"!==e&&(r++,"%c"===e&&(a=r))})),e.splice(a,0,n)}function o(e){try{e?n.storage.setItem("debug",e):n.storage.removeItem("debug")}catch(e){}}function i(){let e;try{e=n.storage.getItem("debug")}catch(e){}return!e&&void 0!==r&&"env"in r&&(e=r.env.DEBUG),e}function c(){try{return localStorage}catch(e){}}n.formatArgs=s,n.save=o,n.load=i,n.useColors=a,n.storage=c(),n.destroy=(()=>{let e=!1;return()=>{e||(e=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),n.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],n.log=console.debug||console.log||(()=>{}),t.exports=e("./common")(n);const{formatters:l}=t.exports;l.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}}).call(this)}).call(this,e("_process"))},{"./common":19,_process:50}],19:[function(e,t,n){function r(t){function n(e){let t=0;for(let n=0;n<e.length;n++)t=(t<<5)-t+e.charCodeAt(n),t|=0;return r.colors[Math.abs(t)%r.colors.length]}function r(e){let t,n,s,o=null;function i(...e){if(!i.enabled)return;const n=i,a=Number(new Date),s=a-(t||a);n.diff=s,n.prev=t,n.curr=a,t=a,e[0]=r.coerce(e[0]),"string"!=typeof e[0]&&e.unshift("%O");let o=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,((t,a)=>{if("%%"===t)return"%";o++;const s=r.formatters[a];if("function"==typeof s){const r=e[o];t=s.call(n,r),e.splice(o,1),o--}return t})),r.formatArgs.call(n,e),(n.log||r.log).apply(n,e)}return i.namespace=e,i.useColors=r.useColors(),i.color=r.selectColor(e),i.extend=a,i.destroy=r.destroy,Object.defineProperty(i,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==o?o:(n!==r.namespaces&&(n=r.namespaces,s=r.enabled(e)),s),set:e=>{o=e}}),"function"==typeof r.init&&r.init(i),i}function a(e,t){const n=r(this.namespace+(void 0===t?":":t)+e);return n.log=this.log,n}function s(e){let t;r.save(e),r.namespaces=e,r.names=[],r.skips=[];const n=("string"==typeof e?e:"").split(/[\s,]+/),a=n.length;for(t=0;t<a;t++)n[t]&&("-"===(e=n[t].replace(/\*/g,".*?"))[0]?r.skips.push(new RegExp("^"+e.substr(1)+"$")):r.names.push(new RegExp("^"+e+"$")))}function o(){const e=[...r.names.map(c),...r.skips.map(c).map((e=>"-"+e))].join(",");return r.enable(""),e}function i(e){if("*"===e[e.length-1])return!0;let t,n;for(t=0,n=r.skips.length;t<n;t++)if(r.skips[t].test(e))return!1;for(t=0,n=r.names.length;t<n;t++)if(r.names[t].test(e))return!0;return!1}function c(e){return e.toString().substring(2,e.toString().length-2).replace(/\.\*\?$/,"*")}function l(e){return e instanceof Error?e.stack||e.message:e}function d(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return r.debug=r,r.default=r,r.coerce=l,r.disable=o,r.enable=s,r.enabled=i,r.humanize=e("ms"),r.destroy=d,Object.keys(t).forEach((e=>{r[e]=t[e]})),r.names=[],r.skips=[],r.formatters={},r.selectColor=n,r.enable(r.load()),r}t.exports=r},{ms:45}],20:[function(e,t,n){(function(n,r){(function(){var a=e("readable-stream"),s=e("end-of-stream"),o=e("inherits"),i=e("stream-shift"),c=r.from&&r.from!==Uint8Array.from?r.from([0]):new r([0]),l=function(e,t){e._corked?e.once("uncork",t):t()},d=function(e,t){e._autoDestroy&&e.destroy(t)},u=function(e,t){return function(n){n?d(e,"premature close"===n.message?null:n):t&&!e._ended&&e.end()}},h=function(e,t){return e?e._writableState&&e._writableState.finished?t():e._writableState?e.end(t):(e.end(),void t()):t()},p=function(){},f=function(e){return new a.Readable({objectMode:!0,highWaterMark:16}).wrap(e)},m=function(e,t,n){if(!(this instanceof m))return new m(e,t,n);a.Duplex.call(this,n),this._writable=null,this._readable=null,this._readable2=null,this._autoDestroy=!n||!1!==n.autoDestroy,this._forwardDestroy=!n||!1!==n.destroy,this._forwardEnd=!n||!1!==n.end,this._corked=1,this._ondrain=null,this._drained=!1,this._forwarding=!1,this._unwrite=null,this._unread=null,this._ended=!1,this.destroyed=!1,e&&this.setWritable(e),t&&this.setReadable(t)};o(m,a.Duplex),m.obj=function(e,t,n){return n||(n={}),n.objectMode=!0,n.highWaterMark=16,new m(e,t,n)},m.prototype.cork=function(){1==++this._corked&&this.emit("cork")},m.prototype.uncork=function(){this._corked&&0==--this._corked&&this.emit("uncork")},m.prototype.setWritable=function(e){if(this._unwrite&&this._unwrite(),this.destroyed)e&&e.destroy&&e.destroy();else if(null!==e&&!1!==e){var t=this,r=s(e,{writable:!0,readable:!1},u(this,this._forwardEnd)),a=function(){var e=t._ondrain;t._ondrain=null,e&&e()},o=function(){t._writable.removeListener("drain",a),r()};this._unwrite&&n.nextTick(a),this._writable=e,this._writable.on("drain",a),this._unwrite=o,this.uncork()}else this.end()},m.prototype.setReadable=function(e){if(this._unread&&this._unread(),this.destroyed)e&&e.destroy&&e.destroy();else{if(null===e||!1===e)return this.push(null),void this.resume();var t=this,n=s(e,{writable:!1,readable:!0},u(this)),r=function(){t._forward()},a=function(){t.push(null)},o=function(){t._readable2.removeListener("readable",r),t._readable2.removeListener("end",a),n()};this._drained=!0,this._readable=e,this._readable2=e._readableState?e:f(e),this._readable2.on("readable",r),this._readable2.on("end",a),this._unread=o,this._forward()}},m.prototype._read=function(){this._drained=!0,this._forward()},m.prototype._forward=function(){if(!this._forwarding&&this._readable2&&this._drained){var e;for(this._forwarding=!0;this._drained&&null!==(e=i(this._readable2));)this.destroyed||(this._drained=this.push(e));this._forwarding=!1}},m.prototype.destroy=function(e,t){if(t||(t=p),this.destroyed)return t(null);this.destroyed=!0;var r=this;n.nextTick((function(){r._destroy(e),t(null)}))},m.prototype._destroy=function(e){if(e){var t=this._ondrain;this._ondrain=null,t?t(e):this.emit("error",e)}this._forwardDestroy&&(this._readable&&this._readable.destroy&&this._readable.destroy(),this._writable&&this._writable.destroy&&this._writable.destroy()),this.emit("close")},m.prototype._write=function(e,t,n){if(!this.destroyed)return this._corked?l(this,this._write.bind(this,e,t,n)):e===c?this._finish(n):this._writable?void(!1===this._writable.write(e)?this._ondrain=n:this.destroyed||n()):n()},m.prototype._finish=function(e){var t=this;this.emit("preend"),l(this,(function(){h(t._forwardEnd&&t._writable,(function(){!1===t._writableState.prefinished&&(t._writableState.prefinished=!0),t.emit("prefinish"),l(t,e)}))}))},m.prototype.end=function(e,t,n){return"function"==typeof e?this.end(null,null,e):"function"==typeof t?this.end(e,null,t):(this._ended=!0,e&&this.write(e),this._writableState.ending||this._writableState.destroyed||this.write(c),a.Writable.prototype.end.call(this,n))},t.exports=m}).call(this)}).call(this,e("_process"),e("buffer").Buffer)},{_process:50,buffer:17,"end-of-stream":21,inherits:24,"readable-stream":69,"stream-shift":74}],21:[function(e,t,n){(function(n){(function(){var r=e("once"),a=function(){},s=function(e){return e.setHeader&&"function"==typeof e.abort},o=function(e){return e.stdio&&Array.isArray(e.stdio)&&3===e.stdio.length},i=function(e,t,c){if("function"==typeof t)return i(e,null,t);t||(t={}),c=r(c||a);var l=e._writableState,d=e._readableState,u=t.readable||!1!==t.readable&&e.readable,h=t.writable||!1!==t.writable&&e.writable,p=!1,f=function(){e.writable||m()},m=function(){h=!1,u||c.call(e)},g=function(){u=!1,h||c.call(e)},y=function(t){c.call(e,t?new Error("exited with error code: "+t):null)},v=function(t){c.call(e,t)},b=function(){n.nextTick(w)},w=function(){if(!p)return(!u||d&&d.ended&&!d.destroyed)&&(!h||l&&l.ended&&!l.destroyed)?void 0:c.call(e,new Error("premature close"))},C=function(){e.req.on("finish",m)};return s(e)?(e.on("complete",m),e.on("abort",b),e.req?C():e.on("request",C)):h&&!l&&(e.on("end",f),e.on("close",f)),o(e)&&e.on("exit",y),e.on("end",g),e.on("finish",m),!1!==t.error&&e.on("error",v),e.on("close",b),function(){p=!0,e.removeListener("complete",m),e.removeListener("abort",b),e.removeListener("request",C),e.req&&e.req.removeListener("finish",m),e.removeListener("end",f),e.removeListener("close",f),e.removeListener("finish",m),e.removeListener("exit",y),e.removeListener("end",g),e.removeListener("error",v),e.removeListener("close",b)}};t.exports=i}).call(this)}).call(this,e("_process"))},{_process:50,once:48}],22:[function(e,t,n){var r=Object.create||_,a=Object.keys||k,s=Function.prototype.bind||O;function o(){this._events&&Object.prototype.hasOwnProperty.call(this,"_events")||(this._events=r(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0}t.exports=o,o.EventEmitter=o,o.prototype._events=void 0,o.prototype._maxListeners=void 0;var i,c=10;try{var l={};Object.defineProperty&&Object.defineProperty(l,"x",{value:0}),i=0===l.x}catch(e){i=!1}function d(e){return void 0===e._maxListeners?o.defaultMaxListeners:e._maxListeners}function u(e,t,n){if(t)e.call(n);else for(var r=e.length,a=I(e,r),s=0;s<r;++s)a[s].call(n)}function h(e,t,n,r){if(t)e.call(n,r);else for(var a=e.length,s=I(e,a),o=0;o<a;++o)s[o].call(n,r)}function p(e,t,n,r,a){if(t)e.call(n,r,a);else for(var s=e.length,o=I(e,s),i=0;i<s;++i)o[i].call(n,r,a)}function f(e,t,n,r,a,s){if(t)e.call(n,r,a,s);else for(var o=e.length,i=I(e,o),c=0;c<o;++c)i[c].call(n,r,a,s)}function m(e,t,n,r){if(t)e.apply(n,r);else for(var a=e.length,s=I(e,a),o=0;o<a;++o)s[o].apply(n,r)}function g(e,t,n,a){var s,o,i;if("function"!=typeof n)throw new TypeError('"listener" argument must be a function');if((o=e._events)?(o.newListener&&(e.emit("newListener",t,n.listener?n.listener:n),o=e._events),i=o[t]):(o=e._events=r(null),e._eventsCount=0),i){if("function"==typeof i?i=o[t]=a?[n,i]:[i,n]:a?i.unshift(n):i.push(n),!i.warned&&(s=d(e))&&s>0&&i.length>s){i.warned=!0;var c=new Error("Possible EventEmitter memory leak detected. "+i.length+' "'+String(t)+'" listeners added. Use emitter.setMaxListeners() to increase limit.');c.name="MaxListenersExceededWarning",c.emitter=e,c.type=t,c.count=i.length,"object"==typeof console&&console.warn&&console.warn("%s: %s",c.name,c.message)}}else i=o[t]=n,++e._eventsCount;return e}function y(){if(!this.fired)switch(this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length){case 0:return this.listener.call(this.target);case 1:return this.listener.call(this.target,arguments[0]);case 2:return this.listener.call(this.target,arguments[0],arguments[1]);case 3:return this.listener.call(this.target,arguments[0],arguments[1],arguments[2]);default:for(var e=new Array(arguments.length),t=0;t<e.length;++t)e[t]=arguments[t];this.listener.apply(this.target,e)}}function v(e,t,n){var r={fired:!1,wrapFn:void 0,target:e,type:t,listener:n},a=s.call(y,r);return a.listener=n,r.wrapFn=a,a}function b(e,t,n){var r=e._events;if(!r)return[];var a=r[t];return a?"function"==typeof a?n?[a.listener||a]:[a]:n?S(a):I(a,a.length):[]}function w(e){var t=this._events;if(t){var n=t[e];if("function"==typeof n)return 1;if(n)return n.length}return 0}function C(e,t){for(var n=t,r=n+1,a=e.length;r<a;n+=1,r+=1)e[n]=e[r];e.pop()}function I(e,t){for(var n=new Array(t),r=0;r<t;++r)n[r]=e[r];return n}function S(e){for(var t=new Array(e.length),n=0;n<t.length;++n)t[n]=e[n].listener||e[n];return t}function _(e){var t=function(){};return t.prototype=e,new t}function k(e){for(var t in e)Object.prototype.hasOwnProperty.call(e,t);return t}function O(e){var t=this;return function(){return t.apply(e,arguments)}}i?Object.defineProperty(o,"defaultMaxListeners",{enumerable:!0,get:function(){return c},set:function(e){if("number"!=typeof e||e<0||e!=e)throw new TypeError('"defaultMaxListeners" must be a positive number');c=e}}):o.defaultMaxListeners=c,o.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||isNaN(e))throw new TypeError('"n" argument must be a positive number');return this._maxListeners=e,this},o.prototype.getMaxListeners=function(){return d(this)},o.prototype.emit=function(e){var t,n,r,a,s,o,i="error"===e;if(o=this._events)i=i&&null==o.error;else if(!i)return!1;if(i){if(arguments.length>1&&(t=arguments[1]),t instanceof Error)throw t;var c=new Error('Unhandled "error" event. ('+t+")");throw c.context=t,c}if(!(n=o[e]))return!1;var l="function"==typeof n;switch(r=arguments.length){case 1:u(n,l,this);break;case 2:h(n,l,this,arguments[1]);break;case 3:p(n,l,this,arguments[1],arguments[2]);break;case 4:f(n,l,this,arguments[1],arguments[2],arguments[3]);break;default:for(a=new Array(r-1),s=1;s<r;s++)a[s-1]=arguments[s];m(n,l,this,a)}return!0},o.prototype.addListener=function(e,t){return g(this,e,t,!1)},o.prototype.on=o.prototype.addListener,o.prototype.prependListener=function(e,t){return g(this,e,t,!0)},o.prototype.once=function(e,t){if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');return this.on(e,v(this,e,t)),this},o.prototype.prependOnceListener=function(e,t){if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');return this.prependListener(e,v(this,e,t)),this},o.prototype.removeListener=function(e,t){var n,a,s,o,i;if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');if(!(a=this._events))return this;if(!(n=a[e]))return this;if(n===t||n.listener===t)0==--this._eventsCount?this._events=r(null):(delete a[e],a.removeListener&&this.emit("removeListener",e,n.listener||t));else if("function"!=typeof n){for(s=-1,o=n.length-1;o>=0;o--)if(n[o]===t||n[o].listener===t){i=n[o].listener,s=o;break}if(s<0)return this;0===s?n.shift():C(n,s),1===n.length&&(a[e]=n[0]),a.removeListener&&this.emit("removeListener",e,i||t)}return this},o.prototype.removeAllListeners=function(e){var t,n,s;if(!(n=this._events))return this;if(!n.removeListener)return 0===arguments.length?(this._events=r(null),this._eventsCount=0):n[e]&&(0==--this._eventsCount?this._events=r(null):delete n[e]),this;if(0===arguments.length){var o,i=a(n);for(s=0;s<i.length;++s)"removeListener"!==(o=i[s])&&this.removeAllListeners(o);return this.removeAllListeners("removeListener"),this._events=r(null),this._eventsCount=0,this}if("function"==typeof(t=n[e]))this.removeListener(e,t);else if(t)for(s=t.length-1;s>=0;s--)this.removeListener(e,t[s]);return this},o.prototype.listeners=function(e){return b(this,e,!0)},o.prototype.rawListeners=function(e){return b(this,e,!1)},o.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):w.call(e,t)},o.prototype.listenerCount=w,o.prototype.eventNames=function(){return this._eventsCount>0?Reflect.ownKeys(this._events):[]}},{}],23:[function(e,t,n){
2
2
  /*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */
3
- n.read=function(e,t,n,r,s){var a,o,i=8*s-r-1,c=(1<<i)-1,l=c>>1,d=-7,u=n?s-1:0,h=n?-1:1,p=e[t+u];for(u+=h,a=p&(1<<-d)-1,p>>=-d,d+=i;d>0;a=256*a+e[t+u],u+=h,d-=8);for(o=a&(1<<-d)-1,a>>=-d,d+=r;d>0;o=256*o+e[t+u],u+=h,d-=8);if(0===a)a=1-l;else{if(a===c)return o?NaN:1/0*(p?-1:1);o+=Math.pow(2,r),a-=l}return(p?-1:1)*o*Math.pow(2,a-r)},n.write=function(e,t,n,r,s,a){var o,i,c,l=8*a-s-1,d=(1<<l)-1,u=d>>1,h=23===s?Math.pow(2,-24)-Math.pow(2,-77):0,p=r?0:a-1,f=r?1:-1,m=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(i=isNaN(t)?1:0,o=d):(o=Math.floor(Math.log(t)/Math.LN2),t*(c=Math.pow(2,-o))<1&&(o--,c*=2),(t+=o+u>=1?h/c:h*Math.pow(2,1-u))*c>=2&&(o++,c/=2),o+u>=d?(i=0,o=d):o+u>=1?(i=(t*c-1)*Math.pow(2,s),o+=u):(i=t*Math.pow(2,u-1)*Math.pow(2,s),o=0));s>=8;e[n+p]=255&i,p+=f,i/=256,s-=8);for(o=o<<s|i,l+=s;l>0;e[n+p]=255&o,p+=f,o/=256,l-=8);e[n+p-f]|=128*m}},{}],24:[function(e,t,n){"function"==typeof Object.create?t.exports=function(e,t){t&&(e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}))}:t.exports=function(e,t){if(t){e.super_=t;var n=function(){};n.prototype=t.prototype,e.prototype=new n,e.prototype.constructor=e}}},{}],25:[function(e,t,n){Object.defineProperty(n,"__esModule",{value:!0});var r=function(){function e(e,t){this.color=!0,this.key=void 0,this.value=void 0,this.parent=void 0,this.brother=void 0,this.leftChild=void 0,this.rightChild=void 0,this.key=e,this.value=t}return e.prototype.rotateLeft=function(){var e=this.parent,t=this.brother,n=this.leftChild,r=this.rightChild;if(!r)throw new Error("unknown error");var s=r.leftChild,a=r.rightChild;return e&&(e.leftChild===this?e.leftChild=r:e.rightChild===this&&(e.rightChild=r)),r.parent=e,r.brother=t,r.leftChild=this,r.rightChild=a,t&&(t.brother=r),this.parent=r,this.brother=a,this.leftChild=n,this.rightChild=s,a&&(a.parent=r,a.brother=this),n&&(n.parent=this,n.brother=s),s&&(s.parent=this,s.brother=n),r},e.prototype.rotateRight=function(){var e=this.parent,t=this.brother,n=this.leftChild;if(!n)throw new Error("unknown error");var r=this.rightChild,s=n.leftChild,a=n.rightChild;return e&&(e.leftChild===this?e.leftChild=n:e.rightChild===this&&(e.rightChild=n)),n.parent=e,n.brother=t,n.leftChild=s,n.rightChild=this,t&&(t.brother=n),s&&(s.parent=n,s.brother=this),this.parent=n,this.brother=s,this.leftChild=a,this.rightChild=r,a&&(a.parent=this,a.brother=r),r&&(r.parent=this,r.brother=a),n},e.prototype.remove=function(){if(this.leftChild||this.rightChild)throw new Error("can only remove leaf node");this.parent&&(this===this.parent.leftChild?this.parent.leftChild=void 0:this===this.parent.rightChild&&(this.parent.rightChild=void 0)),this.brother&&(this.brother.brother=void 0),this.key=void 0,this.value=void 0,this.parent=void 0,this.brother=void 0},e.TreeNodeColorType={red:!0,black:!1},e}();Object.freeze(r),n.default=r},{}],26:[function(e,t,n){var r=this&&this.__generator||function(e,t){var n,r,s,a,o={label:0,sent:function(){if(1&s[0])throw s[1];return s[1]},trys:[],ops:[]};return a={next:i(0),throw:i(1),return:i(2)},"function"==typeof Symbol&&(a[Symbol.iterator]=function(){return this}),a;function i(e){return function(t){return c([e,t])}}function c(a){if(n)throw new TypeError("Generator is already executing.");for(;o;)try{if(n=1,r&&(s=2&a[0]?r.return:a[0]?r.throw||((s=r.return)&&s.call(r),0):r.next)&&!(s=s.call(r,a[1])).done)return s;switch(r=0,s&&(a=[2&a[0],s.value]),a[0]){case 0:case 1:s=a;break;case 4:return o.label++,{value:a[1],done:!1};case 5:o.label++,r=a[1],a=[0];continue;case 7:a=o.ops.pop(),o.trys.pop();continue;default:if(!((s=(s=o.trys).length>0&&s[s.length-1])||6!==a[0]&&2!==a[0])){o=0;continue}if(3===a[0]&&(!s||a[1]>s[0]&&a[1]<s[3])){o.label=a[1];break}if(6===a[0]&&o.label<s[1]){o.label=s[1],s=a;break}if(s&&o.label<s[2]){o.label=s[2],o.ops.push(a);break}s[2]&&o.ops.pop(),o.trys.pop();continue}a=t.call(e,o)}catch(e){a=[6,e],r=0}finally{n=s=0}if(5&a[0])throw a[1];return{value:a[0]?a[1]:void 0,done:!0}}};function s(e){var t=this;void 0===e&&(e=[]);var n=[],a=0,o=0,i=0,c=0,l=0,d=0;this.size=function(){return d},this.empty=function(){return 0===d},this.clear=function(){a=i=o=c=l=d=0,h.call(this,s.bucketSize),d=0},this.front=function(){return n[a][o]},this.back=function(){return n[i][c]},this.forEach=function(e){if(!this.empty()){var t=0;if(a!==i){for(l=o;l<s.bucketSize;++l)e(n[a][l],t++);for(l=a+1;l<i;++l)for(var r=0;r<s.bucketSize;++r)e(n[l][r],t++);for(l=0;l<=c;++l)e(n[i][l],t++)}else for(var l=o;l<=c;++l)e(n[a][l],t++)}};var u=function(e){var t=a*s.bucketSize+o,n=t+e,r=i*s.bucketSize+c;if(n<t||n>r)throw new Error("pos should more than 0 and less than queue's size");return{curNodeBucketIndex:Math.floor(n/s.bucketSize),curNodePointerIndex:n%s.bucketSize}};this.getElementByPos=function(e){var t=u(e),r=t.curNodeBucketIndex,s=t.curNodePointerIndex;return n[r][s]},this.eraseElementByPos=function(e){var t=this;if(e<0||e>d)throw new Error("pos should more than 0 and less than queue's size");if(0===e)this.popFront();else if(e===this.size())this.popBack();else{for(var n=[],r=e+1;r<d;++r)n.push(this.getElementByPos(r));this.cut(e),this.popBack(),n.forEach((function(e){return t.pushBack(e)}))}},this.eraseElementByValue=function(e){if(!this.empty()){var t=[];this.forEach((function(n){n!==e&&t.push(n)}));for(var n=t.length,r=0;r<n;++r)this.setElementByPos(r,t[r]);this.cut(n-1)}};var h=function(e){for(var t=[],r=e*s.sigma,u=Math.max(Math.ceil(r/s.bucketSize),2),h=0;h<u;++h)t.push(new Array(s.bucketSize));var p=Math.ceil(e/s.bucketSize),f=Math.floor(u/2)-Math.floor(p/2),m=f,g=0;if(this.size())for(h=0;h<p;++h){for(var y=0;y<s.bucketSize;++y)if(t[f+h][y]=this.front(),this.popFront(),this.empty()){m=f+h,g=y;break}if(this.empty())break}n=t,a=f,o=0,i=m,c=g,l=u,d=e};this.pushBack=function(e){this.empty()||(i===l-1&&c===s.bucketSize-1&&h.call(this,this.size()),c<s.bucketSize-1?++c:i<l-1&&(++i,c=0)),++d,n[i][c]=e},this.popBack=function(){this.empty()||(1!==this.size()&&(c>0?--c:a<i&&(--i,c=s.bucketSize-1)),d>0&&--d)},this.setElementByPos=function(e,t){var r=u(e),s=r.curNodeBucketIndex,a=r.curNodePointerIndex;n[s][a]=t},this.insert=function(e,t,n){var r=this;if(void 0===n&&(n=1),0===e)for(;n--;)this.pushFront(t);else if(e===this.size())for(;n--;)this.pushBack(t);else{for(var s=[],a=e;a<d;++a)s.push(this.getElementByPos(a));for(this.cut(e-1),a=0;a<n;++a)this.pushBack(t);s.forEach((function(e){return r.pushBack(e)}))}},this.find=function(e){if(a===i){for(var t=o;t<=c;++t)if(n[a][t]===e)return!0;return!1}for(t=o;t<s.bucketSize;++t)if(n[a][t]===e)return!0;for(t=a+1;t<i;++t)for(var r=0;r<s.bucketSize;++r)if(n[t][r]===e)return!0;for(t=0;t<=c;++t)if(n[i][t]===e)return!0;return!1},this.reverse=function(){for(var e=0,t=d-1;e<t;){var n=this.getElementByPos(e);this.setElementByPos(e,this.getElementByPos(t)),this.setElementByPos(t,n),++e,--t}},this.unique=function(){if(!this.empty()){var e=[],t=this.front();this.forEach((function(n,r){0!==r&&n===t||(e.push(n),t=n)}));for(var n=0;n<d;++n)this.setElementByPos(n,e[n]);this.cut(e.length-1)}},this.sort=function(e){var t=[];this.forEach((function(e){t.push(e)})),t.sort(e);for(var n=0;n<d;++n)this.setElementByPos(n,t[n])},this.pushFront=function(e){this.empty()||(0===a&&0===o&&h.call(this,this.size()),o>0?--o:a>0&&(--a,o=s.bucketSize-1)),++d,n[a][o]=e},this.popFront=function(){this.empty()||(1!==this.size()&&(o<s.bucketSize-1?++o:a<i&&(++a,o=0)),d>0&&--d)},this.shrinkToFit=function(){var e=this,t=[];this.forEach((function(e){t.push(e)}));var r=t.length;n=[];for(var a=Math.ceil(r/s.bucketSize),o=0;o<a;++o)n.push(new Array(s.bucketSize));this.clear(),t.forEach((function(t){return e.pushBack(t)}))},this.cut=function(e){if(e<0)this.clear();else{var t=u(e),n=t.curNodeBucketIndex,r=t.curNodePointerIndex;i=n,c=r,d=e+1}},this[Symbol.iterator]=function(){return function(){var e,t;return r(this,(function(r){switch(r.label){case 0:if(0===d)return[2];if(a!==i)return[3,5];t=o,r.label=1;case 1:return t<=c?[4,n[a][t]]:[3,4];case 2:r.sent(),r.label=3;case 3:return++t,[3,1];case 4:return[2];case 5:t=o,r.label=6;case 6:return t<s.bucketSize?[4,n[a][t]]:[3,9];case 7:r.sent(),r.label=8;case 8:return++t,[3,6];case 9:t=a+1,r.label=10;case 10:if(!(t<i))return[3,15];e=0,r.label=11;case 11:return e<s.bucketSize?[4,n[t][e]]:[3,14];case 12:r.sent(),r.label=13;case 13:return++e,[3,11];case 14:return++t,[3,10];case 15:t=0,r.label=16;case 16:return t<=c?[4,n[i][t]]:[3,19];case 17:r.sent(),r.label=18;case 18:return++t,[3,16];case 19:return[2]}}))}()},function(){var r=s.bucketSize;e.size?r=e.size():e.length&&(r=e.length);var o=r*s.sigma;l=Math.ceil(o/s.bucketSize),l=Math.max(l,3);for(var c=0;c<l;++c)n.push(new Array(s.bucketSize));var d=Math.ceil(r/s.bucketSize);a=Math.floor(l/2)-Math.floor(d/2),i=a,e.forEach((function(e){return t.pushBack(e)}))}(),Object.freeze(this)}Object.defineProperty(n,"__esModule",{value:!0}),s.sigma=3,s.bucketSize=5e3,Object.freeze(s),n.default=s},{}],27:[function(e,t,n){var r=this&&this.__generator||function(e,t){var n,r,s,a,o={label:0,sent:function(){if(1&s[0])throw s[1];return s[1]},trys:[],ops:[]};return a={next:i(0),throw:i(1),return:i(2)},"function"==typeof Symbol&&(a[Symbol.iterator]=function(){return this}),a;function i(e){return function(t){return c([e,t])}}function c(a){if(n)throw new TypeError("Generator is already executing.");for(;o;)try{if(n=1,r&&(s=2&a[0]?r.return:a[0]?r.throw||((s=r.return)&&s.call(r),0):r.next)&&!(s=s.call(r,a[1])).done)return s;switch(r=0,s&&(a=[2&a[0],s.value]),a[0]){case 0:case 1:s=a;break;case 4:return o.label++,{value:a[1],done:!1};case 5:o.label++,r=a[1],a=[0];continue;case 7:a=o.ops.pop(),o.trys.pop();continue;default:if(!((s=(s=o.trys).length>0&&s[s.length-1])||6!==a[0]&&2!==a[0])){o=0;continue}if(3===a[0]&&(!s||a[1]>s[0]&&a[1]<s[3])){o.label=a[1];break}if(6===a[0]&&o.label<s[1]){o.label=s[1],s=a;break}if(s&&o.label<s[2]){o.label=s[2],o.ops.push(a);break}s[2]&&o.ops.pop(),o.trys.pop();continue}a=t.call(e,o)}catch(e){a=[6,e],r=0}finally{n=s=0}if(5&a[0])throw a[1];return{value:a[0]?a[1]:void 0,done:!0}}},s=this&&this.__values||function(e){var t="function"==typeof Symbol&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(n,"__esModule",{value:!0});var a=e("../LinkList/LinkList"),o=e("../Map/Map");function i(e,t,n){var c=this;if(void 0===e&&(e=[]),void 0===t&&(t=i.initSize),n=n||function(e){var t,n,r=0,a="";if("number"==typeof e)r=((r=Math.floor(e))<<5)-r,r&=r;else{a="string"!=typeof e?JSON.stringify(e):e;try{for(var o=s(a),i=o.next();!i.done;i=o.next())r=(r<<5)-r+i.value.charCodeAt(0),r&=r}catch(e){t={error:e}}finally{try{i&&!i.done&&(n=o.return)&&n.call(o)}finally{if(t)throw t.error}}}return r^=r>>>16},0!=(t&t-1))throw new Error("initBucketNum must be 2 to the power of n");var l=0,d=[],u=Math.max(i.initSize,Math.min(i.maxSize,t));this.size=function(){return l},this.empty=function(){return 0===l},this.clear=function(){l=0,u=t,d=[]},this.forEach=function(e){var t=0;d.forEach((function(n){n.forEach((function(n){e(n,t++)}))}))};var h=function(e){if(!(e>=i.maxSize)){u=2*e;var t=[];d.forEach((function(r,s){if(!r.empty()){if(r instanceof a.default&&1===r.size()){var c=r.front(),l=c.key,h=c.value;t[n(l)&u-1]=new a.default([{key:l,value:h}])}else if(r instanceof o.default){var p=new a.default,f=new a.default;r.forEach((function(t){0==(n(t.key)&e)?p.pushBack(t):f.pushBack(t)})),p.size()>i.untreeifyThreshold?t[s]=new o.default(p):p.size()&&(t[s]=p),f.size()>i.untreeifyThreshold?t[s+e]=new o.default(f):f.size()&&(t[s+e]=f)}else{var m=new a.default,g=new a.default;r.forEach((function(t){0==(n(t.key)&e)?m.pushBack(t):g.pushBack(t)})),m.size()&&(t[s]=m),g.size()&&(t[s+e]=g)}d[s].clear()}})),d=t}};this.setElement=function(e,t){var r,c;if(null==e)throw new Error("to avoid some unnecessary errors, we don't suggest you insert null or undefined here");if(null!=t){var p=n(e)&u-1;if(d[p]){var f=d[p].size();if(d[p]instanceof a.default){try{for(var m=s(d[p]),g=m.next();!g.done;g=m.next()){var y=g.value;if(y.key===e)return void(y.value=t)}}catch(e){r={error:e}}finally{try{g&&!g.done&&(c=m.return)&&c.call(m)}finally{if(r)throw r.error}}d[p].pushBack({key:e,value:t}),d[p].size()>=i.treeifyThreshold&&(d[p]=new o.default(d[p]))}else d[p].setElement(e,t);var v=d[p].size();l+=v-f}else++l,d[p]=new a.default([{key:e,value:t}]);l>u*i.sigma&&h.call(this,u)}else this.eraseElementByKey(e)},this.getElementByKey=function(e){var t,r,a=n(e)&u-1;if(d[a]){if(d[a]instanceof o.default)return d[a].getElementByKey(e);try{for(var i=s(d[a]),c=i.next();!c.done;c=i.next()){var l=c.value;if(l.key===e)return l.value}}catch(e){t={error:e}}finally{try{c&&!c.done&&(r=i.return)&&r.call(i)}finally{if(t)throw t.error}}}},this.eraseElementByKey=function(e){var t,r,c=n(e)&u-1;if(d[c]){var h=d[c].size();if(d[c]instanceof o.default)d[c].eraseElementByKey(e),d[c].size()<=i.untreeifyThreshold&&(d[c]=new a.default(d[c]));else{var p=-1;try{for(var f=s(d[c]),m=f.next();!m.done;m=f.next()){var g=m.value;if(++p,g.key===e){d[c].eraseElementByPos(p);break}}}catch(e){t={error:e}}finally{try{m&&!m.done&&(r=f.return)&&r.call(f)}finally{if(t)throw t.error}}}var y=d[c].size();l+=y-h}},this.find=function(e){var t,r,a=n(e)&u-1;if(!d[a])return!1;if(d[a]instanceof o.default)return d[a].find(e);try{for(var i=s(d[a]),c=i.next();!c.done;c=i.next())if(c.value.key===e)return!0}catch(e){t={error:e}}finally{try{c&&!c.done&&(r=i.return)&&r.call(i)}finally{if(t)throw t.error}}return!1},this[Symbol.iterator]=function(){return function(){var e,t,n,a,o,i;return r(this,(function(r){switch(r.label){case 0:e=0,r.label=1;case 1:if(!(e<u))return[3,10];for(;e<u&&!d[e];)++e;if(e>=u)return[3,10];r.label=2;case 2:r.trys.push([2,7,8,9]),o=void 0,t=s(d[e]),n=t.next(),r.label=3;case 3:return n.done?[3,6]:[4,n.value];case 4:r.sent(),r.label=5;case 5:return n=t.next(),[3,3];case 6:return[3,9];case 7:return a=r.sent(),o={error:a},[3,9];case 8:try{n&&!n.done&&(i=t.return)&&i.call(t)}finally{if(o)throw o.error}return[7];case 9:return++e,[3,1];case 10:return[2]}}))}()},e.forEach((function(e){var t=e.key,n=e.value;return c.setElement(t,n)})),Object.freeze(this)}i.initSize=16,i.maxSize=1<<30,i.sigma=.75,i.treeifyThreshold=8,i.untreeifyThreshold=6,i.minTreeifySize=64,Object.freeze(i),n.default=i},{"../LinkList/LinkList":29,"../Map/Map":30}],28:[function(e,t,n){var r=this&&this.__generator||function(e,t){var n,r,s,a,o={label:0,sent:function(){if(1&s[0])throw s[1];return s[1]},trys:[],ops:[]};return a={next:i(0),throw:i(1),return:i(2)},"function"==typeof Symbol&&(a[Symbol.iterator]=function(){return this}),a;function i(e){return function(t){return c([e,t])}}function c(a){if(n)throw new TypeError("Generator is already executing.");for(;o;)try{if(n=1,r&&(s=2&a[0]?r.return:a[0]?r.throw||((s=r.return)&&s.call(r),0):r.next)&&!(s=s.call(r,a[1])).done)return s;switch(r=0,s&&(a=[2&a[0],s.value]),a[0]){case 0:case 1:s=a;break;case 4:return o.label++,{value:a[1],done:!1};case 5:o.label++,r=a[1],a=[0];continue;case 7:a=o.ops.pop(),o.trys.pop();continue;default:if(!((s=(s=o.trys).length>0&&s[s.length-1])||6!==a[0]&&2!==a[0])){o=0;continue}if(3===a[0]&&(!s||a[1]>s[0]&&a[1]<s[3])){o.label=a[1];break}if(6===a[0]&&o.label<s[1]){o.label=s[1],s=a;break}if(s&&o.label<s[2]){o.label=s[2],o.ops.push(a);break}s[2]&&o.ops.pop(),o.trys.pop();continue}a=t.call(e,o)}catch(e){a=[6,e],r=0}finally{n=s=0}if(5&a[0])throw a[1];return{value:a[0]?a[1]:void 0,done:!0}}},s=this&&this.__values||function(e){var t="function"==typeof Symbol&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(n,"__esModule",{value:!0});var a=e("../Set/Set"),o=e("../LinkList/LinkList");function i(e,t,n){var c=this;if(void 0===e&&(e=[]),void 0===t&&(t=i.initSize),n=n||function(e){var t=0,n="";if("number"==typeof e)t=((t=Math.floor(e))<<5)-t,t&=t;else{n="string"!=typeof e?JSON.stringify(e):e;for(var r=0;r<n.length;r++)t=(t<<5)-t+n.charCodeAt(r),t&=t}return t^=t>>>16},0!=(t&t-1))throw new Error("initBucketNum must be 2 to the power of n");var l=0,d=[],u=Math.max(i.initSize,Math.min(i.maxSize,t));this.size=function(){return l},this.empty=function(){return 0===l},this.clear=function(){l=0,u=t,d=[]},this.forEach=function(e){var t=0;d.forEach((function(n){n.forEach((function(n){e(n,t++)}))}))};var h=function(e){if(!(e>=i.maxSize)){u=2*e;var t=[];d.forEach((function(r,s){if(!r.empty()){if(r instanceof o.default&&1===r.size()){var c=r.front();if(void 0===c)throw new Error("unknown error");t[n(c)&u-1]=new o.default([c])}else if(r instanceof a.default){var l=new o.default,h=new o.default;r.forEach((function(t){0==(n(t)&e)?l.pushBack(t):h.pushBack(t)})),l.size()>i.untreeifyThreshold?t[s]=new a.default(l):l.size()&&(t[s]=l),h.size()>i.untreeifyThreshold?t[s+e]=new a.default(h):h.size()&&(t[s+e]=h)}else{var p=new o.default,f=new o.default;r.forEach((function(t){0==(n(t)&e)?p.pushBack(t):f.pushBack(t)})),p.size()&&(t[s]=p),f.size()&&(t[s+e]=f)}d[s].clear()}})),d=t}};this.insert=function(e){if(null==e)throw new Error("to avoid some unnecessary errors, we don't suggest you insert null or undefined here");var t=n(e)&u-1;if(d[t]){var r=d[t].size();if(d[t]instanceof o.default){if(d[t].find(e))return;d[t].pushBack(e),d[t].size()>=i.treeifyThreshold&&(d[t]=new a.default(d[t]))}else d[t].insert(e);var s=d[t].size();l+=s-r}else d[t]=new o.default([e]),++l;l>u*i.sigma&&h.call(this,u)},this.eraseElementByValue=function(e){var t=n(e)&u-1;if(d[t]){var r=d[t].size();d[t].eraseElementByValue(e),d[t]instanceof a.default&&d[t].size()<=i.untreeifyThreshold&&(d[t]=new o.default(d[t]));var s=d[t].size();l+=s-r}},this.find=function(e){var t=n(e)&u-1;return!!d[t]&&d[t].find(e)},this[Symbol.iterator]=function(){return function(){var e,t,n,a,o,i;return r(this,(function(r){switch(r.label){case 0:e=0,r.label=1;case 1:if(!(e<u))return[3,10];for(;e<u&&!d[e];)++e;if(e>=u)return[3,10];r.label=2;case 2:r.trys.push([2,7,8,9]),o=void 0,t=s(d[e]),n=t.next(),r.label=3;case 3:return n.done?[3,6]:[4,n.value];case 4:r.sent(),r.label=5;case 5:return n=t.next(),[3,3];case 6:return[3,9];case 7:return a=r.sent(),o={error:a},[3,9];case 8:try{n&&!n.done&&(i=t.return)&&i.call(t)}finally{if(o)throw o.error}return[7];case 9:return++e,[3,1];case 10:return[2]}}))}()},e.forEach((function(e){return c.insert(e)})),Object.freeze(this)}i.initSize=16,i.maxSize=1<<30,i.sigma=.75,i.treeifyThreshold=8,i.untreeifyThreshold=6,i.minTreeifySize=64,Object.freeze(i),n.default=i},{"../LinkList/LinkList":29,"../Set/Set":33}],29:[function(e,t,n){var r=this&&this.__generator||function(e,t){var n,r,s,a,o={label:0,sent:function(){if(1&s[0])throw s[1];return s[1]},trys:[],ops:[]};return a={next:i(0),throw:i(1),return:i(2)},"function"==typeof Symbol&&(a[Symbol.iterator]=function(){return this}),a;function i(e){return function(t){return c([e,t])}}function c(a){if(n)throw new TypeError("Generator is already executing.");for(;o;)try{if(n=1,r&&(s=2&a[0]?r.return:a[0]?r.throw||((s=r.return)&&s.call(r),0):r.next)&&!(s=s.call(r,a[1])).done)return s;switch(r=0,s&&(a=[2&a[0],s.value]),a[0]){case 0:case 1:s=a;break;case 4:return o.label++,{value:a[1],done:!1};case 5:o.label++,r=a[1],a=[0];continue;case 7:a=o.ops.pop(),o.trys.pop();continue;default:if(!((s=(s=o.trys).length>0&&s[s.length-1])||6!==a[0]&&2!==a[0])){o=0;continue}if(3===a[0]&&(!s||a[1]>s[0]&&a[1]<s[3])){o.label=a[1];break}if(6===a[0]&&o.label<s[1]){o.label=s[1],s=a;break}if(s&&o.label<s[2]){o.label=s[2],o.ops.push(a);break}s[2]&&o.ops.pop(),o.trys.pop();continue}a=t.call(e,o)}catch(e){a=[6,e],r=0}finally{n=s=0}if(5&a[0])throw a[1];return{value:a[0]?a[1]:void 0,done:!0}}};Object.defineProperty(n,"__esModule",{value:!0});var s=function(){function e(e){this.value=void 0,this.pre=void 0,this.next=void 0,this.value=e}return e}();function a(e){var t=this;void 0===e&&(e=[]);var n=0,a=void 0,o=void 0;this.size=function(){return n},this.empty=function(){return 0===n},this.clear=function(){a=o=void 0,n=0},this.front=function(){return null==a?void 0:a.value},this.back=function(){return null==o?void 0:o.value},this.forEach=function(e){for(var t=a,n=0;t;){if(void 0===t.value)throw new Error("unknown error");e(t.value,n++),t=t.next}},this.getElementByPos=function(e){if(e<0||e>=n)throw new Error("pos must more then 0 and less then the list length");for(var t=a;e--&&t;)t=t.next;if(!t||void 0===t.value)throw new Error("unknown error");return t.value},this.eraseElementByPos=function(e){if(e<0||e>=n)throw new Error("erase pos must more then 0 and less then the list length");if(0===e)this.popFront();else if(e===n-1)this.popBack();else{for(var t=a;e--;){if(!(null==t?void 0:t.next))throw new Error("unknown error");t=t.next}if(!t||!t.pre||!t.next)throw new Error("unknown error");var r=t.pre,s=t.next;s.pre=r,r.next=s,n>0&&--n}},this.eraseElementByValue=function(e){for(;a&&a.value===e;)this.popFront();for(;o&&o.value===e;)this.popBack();if(a)for(var t=a;t;){if(t.value===e){var r=t.pre,s=t.next;s&&(s.pre=r),r&&(r.next=s),n>0&&--n}t=t.next}},this.pushBack=function(e){if(null==e)throw new Error("you can't push null or undefined here");++n;var t=new s(e);o?(o.next=t,t.pre=o,o=t):a=o=t},this.popBack=function(){o&&(n>0&&--n,o&&(a===o?a=o=void 0:(o=o.pre)&&(o.next=void 0)))},this.setElementByPos=function(e,t){if(null==t)throw new Error("you can't set null or undefined here");if(e<0||e>=n)throw new Error("pos must more then 0 and less then the list length");for(var r=a;e--;){if(!r)throw new Error("unknown error");r=r.next}r&&(r.value=t)},this.insert=function(e,t,r){if(void 0===r&&(r=1),null==t)throw new Error("you can't insert null or undefined here");if(e<0||e>n)throw new Error("insert pos must more then 0 and less then or equal to the list length");if(r<0)throw new Error("insert size must more than 0");if(0===e)for(;r--;)this.pushFront(t);else if(e===n)for(;r--;)this.pushBack(t);else{for(var o=a,i=1;i<e;++i){if(!(null==o?void 0:o.next))throw new Error("unknown error");o=null==o?void 0:o.next}if(!o)throw new Error("unknown error");var c=o.next;for(n+=r;r--;)o.next=new s(t),o.next.pre=o,o=o.next;o.next=c,c&&(c.pre=o)}},this.find=function(e){for(var t=a;t;){if(t.value===e)return!0;t=t.next}return!1},this.reverse=function(){for(var e=a,t=o,r=0;e&&t&&2*r<n;){var s=e.value;e.value=t.value,t.value=s,e=e.next,t=t.pre,++r}},this.unique=function(){for(var e=a;e;){for(var t=e;t&&t.next&&t.value===t.next.value;)t=t.next,n>0&&--n;e.next=t.next,e.next&&(e.next.pre=e),e=e.next}},this.sort=function(e){var t=[];this.forEach((function(e){t.push(e)})),t.sort(e);var n=a;t.forEach((function(e){n&&(n.value=e,n=n.next)}))},this.pushFront=function(e){if(null==e)throw new Error("you can't push null or undefined here");++n;var t=new s(e);a?(t.next=a,a.pre=t,a=t):a=o=t},this.popFront=function(){a&&(n>0&&--n,a&&(a===o?a=o=void 0:(a=a.next)&&(a.pre=void 0)))},this.merge=function(e){var t=this,r=a;e.forEach((function(e){for(;r&&void 0!==r.value&&r.value<=e;)r=r.next;if(void 0===r)t.pushBack(e),r=o;else if(r===a)t.pushFront(e),r=a;else{++n;var i=r.pre;i&&(i.next=new s(e),i.next.pre=i,i.next.next=r,r&&(r.pre=i.next))}}))},this[Symbol.iterator]=function(){return function(){var e;return r(this,(function(t){switch(t.label){case 0:e=a,t.label=1;case 1:if(void 0===e)return[3,3];if(!e.value)throw new Error("unknown error");return[4,e.value];case 2:return t.sent(),e=e.next,[3,1];case 3:return[2]}}))}()},e.forEach((function(e){return t.pushBack(e)})),Object.freeze(this)}Object.freeze(a),n.default=a},{}],30:[function(e,t,n){var r=this&&this.__generator||function(e,t){var n,r,s,a,o={label:0,sent:function(){if(1&s[0])throw s[1];return s[1]},trys:[],ops:[]};return a={next:i(0),throw:i(1),return:i(2)},"function"==typeof Symbol&&(a[Symbol.iterator]=function(){return this}),a;function i(e){return function(t){return c([e,t])}}function c(a){if(n)throw new TypeError("Generator is already executing.");for(;o;)try{if(n=1,r&&(s=2&a[0]?r.return:a[0]?r.throw||((s=r.return)&&s.call(r),0):r.next)&&!(s=s.call(r,a[1])).done)return s;switch(r=0,s&&(a=[2&a[0],s.value]),a[0]){case 0:case 1:s=a;break;case 4:return o.label++,{value:a[1],done:!1};case 5:o.label++,r=a[1],a=[0];continue;case 7:a=o.ops.pop(),o.trys.pop();continue;default:if(!((s=(s=o.trys).length>0&&s[s.length-1])||6!==a[0]&&2!==a[0])){o=0;continue}if(3===a[0]&&(!s||a[1]>s[0]&&a[1]<s[3])){o.label=a[1];break}if(6===a[0]&&o.label<s[1]){o.label=s[1],s=a;break}if(s&&o.label<s[2]){o.label=s[2],o.ops.push(a);break}s[2]&&o.ops.pop(),o.trys.pop();continue}a=t.call(e,o)}catch(e){a=[6,e],r=0}finally{n=s=0}if(5&a[0])throw a[1];return{value:a[0]?a[1]:void 0,done:!0}}},s=this&&this.__values||function(e){var t="function"==typeof Symbol&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(n,"__esModule",{value:!0});var a=e("../Base/TreeNode");function o(e,t){var n=this;void 0===e&&(e=[]),t=t||function(e,t){return e<t?-1:e>t?1:0};var o=0,i=new a.default;i.color=a.default.TreeNodeColorType.black,this.size=function(){return o},this.empty=function(){return 0===o},this.clear=function(){o=0,i.key=i.value=void 0,i.leftChild=i.rightChild=i.brother=void 0};var c=function(e){if(!e||void 0===e.key)throw new Error("unknown error");return e.leftChild?c(e.leftChild):e},l=function(e){if(!e||void 0===e.key)throw new Error("unknown error");return e.rightChild?l(e.rightChild):e};this.front=function(){if(!this.empty()){var e=c(i);if(void 0===e.key||void 0===e.value)throw new Error("unknown error");return{key:e.key,value:e.value}}},this.back=function(){if(!this.empty()){var e=l(i);if(void 0===e.key||void 0===e.value)throw new Error("unknown error");return{key:e.key,value:e.value}}},this.forEach=function(e){var t,n,r=0;try{for(var a=s(this),o=a.next();!o.done;o=a.next())e(o.value,r++)}catch(e){t={error:e}}finally{try{o&&!o.done&&(n=a.return)&&n.call(a)}finally{if(t)throw t.error}}},this.getElementByPos=function(e){var t,n;if(e<0||e>=this.size())throw new Error("pos must more than 0 and less than set's size");var r=0;try{for(var a=s(this),o=a.next();!o.done;o=a.next()){var i=o.value;if(r===e)return i;++r}}catch(e){t={error:e}}finally{try{o&&!o.done&&(n=a.return)&&n.call(a)}finally{if(t)throw t.error}}throw new Error("unknown Error")};var d=function(e,n){if(e&&void 0!==e.key&&void 0!==e.value){var r=t(e.key,n);return 0===r?{key:e.key,value:e.value}:r<0?d(e.rightChild,n):d(e.leftChild,n)||{key:e.key,value:e.value}}};this.lowerBound=function(e){return d(i,e)};var u=function(e,n){if(e&&void 0!==e.key&&void 0!==e.value)return t(e.key,n)<=0?u(e.rightChild,n):u(e.leftChild,n)||{key:e.key,value:e.value}};this.upperBound=function(e){return u(i,e)};var h=function(e,n){if(e&&void 0!==e.key&&void 0!==e.value){var r=t(e.key,n);return 0===r?{key:e.key,value:e.value}:r>0?h(e.leftChild,n):h(e.rightChild,n)||{key:e.key,value:e.value}}};this.reverseLowerBound=function(e){return h(i,e)};var p=function(e,n){if(e&&void 0!==e.key&&void 0!==e.value)return t(e.key,n)>=0?p(e.leftChild,n):p(e.rightChild,n)||{key:e.key,value:e.value}};this.reverseUpperBound=function(e){return p(i,e)};var f=function(e){var t=e.parent;if(!t){if(e===i)return;throw new Error("unknown error")}if(e.color!==a.default.TreeNodeColorType.red){var n=e.brother;if(!n)throw new Error("unknown error");if(e===t.leftChild)if(n.color===a.default.TreeNodeColorType.red){n.color=a.default.TreeNodeColorType.black,t.color=a.default.TreeNodeColorType.red;var r=t.rotateLeft();i===t&&(i=r),f(e)}else n.color===a.default.TreeNodeColorType.black&&(n.rightChild&&n.rightChild.color===a.default.TreeNodeColorType.red?(n.color=t.color,t.color=a.default.TreeNodeColorType.black,n.rightChild&&(n.rightChild.color=a.default.TreeNodeColorType.black),r=t.rotateLeft(),i===t&&(i=r),e.color=a.default.TreeNodeColorType.black):n.rightChild&&n.rightChild.color!==a.default.TreeNodeColorType.black||!n.leftChild||n.leftChild.color!==a.default.TreeNodeColorType.red?n.leftChild&&n.leftChild.color!==a.default.TreeNodeColorType.black||n.rightChild&&n.rightChild.color!==a.default.TreeNodeColorType.black||(n.color=a.default.TreeNodeColorType.red,f(t)):(n.color=a.default.TreeNodeColorType.red,n.leftChild&&(n.leftChild.color=a.default.TreeNodeColorType.black),r=n.rotateRight(),i===n&&(i=r),f(e)));else e===t.rightChild&&(n.color===a.default.TreeNodeColorType.red?(n.color=a.default.TreeNodeColorType.black,t.color=a.default.TreeNodeColorType.red,r=t.rotateRight(),i===t&&(i=r),f(e)):n.color===a.default.TreeNodeColorType.black&&(n.leftChild&&n.leftChild.color===a.default.TreeNodeColorType.red?(n.color=t.color,t.color=a.default.TreeNodeColorType.black,n.leftChild&&(n.leftChild.color=a.default.TreeNodeColorType.black),r=t.rotateRight(),i===t&&(i=r),e.color=a.default.TreeNodeColorType.black):n.leftChild&&n.leftChild.color!==a.default.TreeNodeColorType.black||!n.rightChild||n.rightChild.color!==a.default.TreeNodeColorType.red?n.leftChild&&n.leftChild.color!==a.default.TreeNodeColorType.black||n.rightChild&&n.rightChild.color!==a.default.TreeNodeColorType.black||(n.color=a.default.TreeNodeColorType.red,f(t)):(n.color=a.default.TreeNodeColorType.red,n.rightChild&&(n.rightChild.color=a.default.TreeNodeColorType.black),r=n.rotateLeft(),i===n&&(i=r),f(e))))}else e.color=a.default.TreeNodeColorType.black},m=function(e){for(var t=e;t.leftChild||t.rightChild;){if(t.rightChild){t=c(t.rightChild);var n=e.key;e.key=t.key,t.key=n;var r=e.value;e.value=t.value,t.value=r,e=t}t.leftChild&&(t=l(t.leftChild),n=e.key,e.key=t.key,t.key=n,r=e.value,e.value=t.value,t.value=r,e=t)}f(t),t&&t.remove(),--o,i.color=a.default.TreeNodeColorType.black},g=function(e,t){return!(!e||void 0===e.key)&&(!!g(e.leftChild,t)||!!t(e)||g(e.rightChild,t))};this.eraseElementByPos=function(e){if(e<0||e>=o)throw new Error("pos must more than 0 and less than set's size");var t=0;g(i,(function(n){return e===t?(m(n),!0):(++t,!1)}))},this.eraseElementByKey=function(e){if(!this.empty()){var n=b(i,e);void 0!==n&&void 0!==n.key&&0===t(n.key,e)&&m(n)}};var y=function(e,n){if(!e||void 0===e.key)throw new Error("unknown error");var r=t(n,e.key);return r<0?e.leftChild?y(e.leftChild,n):(e.leftChild=new a.default,e.leftChild.parent=e,e.leftChild.brother=e.rightChild,e.rightChild&&(e.rightChild.brother=e.leftChild),e.leftChild):r>0?e.rightChild?y(e.rightChild,n):(e.rightChild=new a.default,e.rightChild.parent=e,e.rightChild.brother=e.leftChild,e.leftChild&&(e.leftChild.brother=e.rightChild),e.rightChild):e},v=function(e){var t=e.parent;if(!t){if(e===i)return;throw new Error("unknown error")}if(t.color!==a.default.TreeNodeColorType.black&&t.color===a.default.TreeNodeColorType.red){var n=t.brother,r=t.parent;if(!r)throw new Error("unknown error");if(n&&n.color===a.default.TreeNodeColorType.red)n.color=t.color=a.default.TreeNodeColorType.black,r.color=a.default.TreeNodeColorType.red,v(r);else if(!n||n.color===a.default.TreeNodeColorType.black)if(t===r.leftChild)if(e===t.leftChild){t.color=a.default.TreeNodeColorType.black,r.color=a.default.TreeNodeColorType.red;var s=r.rotateRight();r===i&&(i=s)}else e===t.rightChild&&(s=t.rotateLeft(),r===i&&(i=s),v(t));else t===r.rightChild&&(e===t.leftChild?(s=t.rotateRight(),r===i&&(i=s),v(t)):e===t.rightChild&&(t.color=a.default.TreeNodeColorType.black,r.color=a.default.TreeNodeColorType.red,s=r.rotateLeft(),r===i&&(i=s)))}};this.setElement=function(e,n){if(null==e)throw new Error("to avoid some unnecessary errors, we don't suggest you insert null or undefined here");if(null!=n){if(this.empty())return++o,i.key=e,i.value=n,void(i.color=a.default.TreeNodeColorType.black);var r=y(i,e);void 0===r.key||0!==t(r.key,e)?(++o,r.key=e,r.value=n,v(r),i.color=a.default.TreeNodeColorType.black):r.value=n}else this.eraseElementByKey(e)};var b=function(e,n){if(e&&void 0!==e.key){var r=t(n,e.key);return r<0?b(e.leftChild,n):r>0?b(e.rightChild,n):e}};this.find=function(e){return!!b(i,e)},this.getElementByKey=function(e){var t=b(i,e);if(void 0===(null==t?void 0:t.key)||void 0===(null==t?void 0:t.value))throw new Error("unknown error");return t.value},this.union=function(e){var t=this;e.forEach((function(e){var n=e.key,r=e.value;return t.setElement(n,r)}))},this.getHeight=function(){if(this.empty())return 0;var e=function(t){return t?Math.max(e(t.leftChild),e(t.rightChild))+1:1};return e(i)};var w=function(e){return r(this,(function(t){switch(t.label){case 0:return e&&void 0!==e.key&&void 0!==e.value?[5,s(w(e.leftChild))]:[2];case 1:return t.sent(),[4,{key:e.key,value:e.value}];case 2:return t.sent(),[5,s(w(e.rightChild))];case 3:return t.sent(),[2]}}))};this[Symbol.iterator]=function(){return w(i)},e.forEach((function(e){var t=e.key,r=e.value;return n.setElement(t,r)})),Object.freeze(this)}Object.freeze(o),n.default=o},{"../Base/TreeNode":25}],31:[function(e,t,n){function r(e,t){void 0===e&&(e=[]),t=t||function(e,t){return e>t?-1:e<t?1:0};var n=[];e.forEach((function(e){return n.push(e)}));var r=n.length,s=function(e,t){if(e<0||e>=r)throw new Error("unknown error");if(t<0||t>=r)throw new Error("unknown error");var s=n[e];n[e]=n[t],n[t]=s},a=function(e){if(e<0||e>=r)throw new Error("unknown error");var a=2*e+1,o=2*e+2;a<r&&t(n[e],n[a])>0&&s(e,a),o<r&&t(n[e],n[o])>0&&s(e,o)};!function(){for(var e=Math.floor((r-1)/2);e>=0;--e)for(var a=e,o=2*a+1;o<r;){var i=o+1,c=o;if(i<r&&t(n[o],n[i])>0&&(c=i),t(n[a],n[c])<=0)break;s(a,c),o=2*(a=c)+1}}(),this.size=function(){return r},this.empty=function(){return 0===r},this.clear=function(){r=0,n.length=0},this.push=function(e){if(n.push(e),1!=++r)for(var s=r-1;s>0;){var o=Math.floor((s-1)/2);if(t(n[o],e)<=0)break;a(o),s=o}},this.pop=function(){if(!this.empty())if(1!==this.size()){var e=n[r-1];--r;for(var s=0;s<this.size();){var a=2*s+1,o=2*s+2;if(a>=this.size())break;var i=a;if(o<this.size()&&t(n[a],n[o])>0&&(i=o),t(n[i],e)>=0)break;n[s]=n[i],s=i}n[s]=e}else--r},this.top=function(){return n[0]},Object.freeze(this)}Object.defineProperty(n,"__esModule",{value:!0}),Object.freeze(r),n.default=r},{}],32:[function(e,t,n){Object.defineProperty(n,"__esModule",{value:!0});var r=e("../LinkList/LinkList");function s(e){void 0===e&&(e=[]);var t=new r.default(e);this.size=function(){return t.size()},this.empty=function(){return t.empty()},this.clear=function(){t.clear()},this.push=function(e){t.pushBack(e)},this.pop=function(){t.popFront()},this.front=function(){return t.front()},Object.freeze(this)}Object.freeze(s),n.default=s},{"../LinkList/LinkList":29}],33:[function(e,t,n){var r=this&&this.__generator||function(e,t){var n,r,s,a,o={label:0,sent:function(){if(1&s[0])throw s[1];return s[1]},trys:[],ops:[]};return a={next:i(0),throw:i(1),return:i(2)},"function"==typeof Symbol&&(a[Symbol.iterator]=function(){return this}),a;function i(e){return function(t){return c([e,t])}}function c(a){if(n)throw new TypeError("Generator is already executing.");for(;o;)try{if(n=1,r&&(s=2&a[0]?r.return:a[0]?r.throw||((s=r.return)&&s.call(r),0):r.next)&&!(s=s.call(r,a[1])).done)return s;switch(r=0,s&&(a=[2&a[0],s.value]),a[0]){case 0:case 1:s=a;break;case 4:return o.label++,{value:a[1],done:!1};case 5:o.label++,r=a[1],a=[0];continue;case 7:a=o.ops.pop(),o.trys.pop();continue;default:if(!((s=(s=o.trys).length>0&&s[s.length-1])||6!==a[0]&&2!==a[0])){o=0;continue}if(3===a[0]&&(!s||a[1]>s[0]&&a[1]<s[3])){o.label=a[1];break}if(6===a[0]&&o.label<s[1]){o.label=s[1],s=a;break}if(s&&o.label<s[2]){o.label=s[2],o.ops.push(a);break}s[2]&&o.ops.pop(),o.trys.pop();continue}a=t.call(e,o)}catch(e){a=[6,e],r=0}finally{n=s=0}if(5&a[0])throw a[1];return{value:a[0]?a[1]:void 0,done:!0}}},s=this&&this.__values||function(e){var t="function"==typeof Symbol&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(n,"__esModule",{value:!0});var a=e("../Base/TreeNode");function o(e,t){var n=this;void 0===e&&(e=[]),t=t||function(e,t){return e<t?-1:e>t?1:0};var o=0,i=new a.default;i.color=a.default.TreeNodeColorType.black,this.size=function(){return o},this.empty=function(){return 0===o},this.clear=function(){o=0,i.key=void 0,i.leftChild=i.rightChild=i.brother=i.parent=void 0,i.color=a.default.TreeNodeColorType.black};var c=function(e){if(!e||void 0===e.key)throw new Error("unknown error");return e.leftChild?c(e.leftChild):e},l=function(e){if(!e||void 0===e.key)throw new Error("unknown error");return e.rightChild?l(e.rightChild):e};this.front=function(){if(!this.empty())return c(i).key},this.back=function(){if(!this.empty())return l(i).key},this.forEach=function(e){var t,n,r=0;try{for(var a=s(this),o=a.next();!o.done;o=a.next())e(o.value,r++)}catch(e){t={error:e}}finally{try{o&&!o.done&&(n=a.return)&&n.call(a)}finally{if(t)throw t.error}}},this.getElementByPos=function(e){var t,n;if(e<0||e>=this.size())throw new Error("pos must more than 0 and less than set's size");var r=0;try{for(var a=s(this),o=a.next();!o.done;o=a.next()){var i=o.value;if(r===e)return i;++r}}catch(e){t={error:e}}finally{try{o&&!o.done&&(n=a.return)&&n.call(a)}finally{if(t)throw t.error}}throw new Error("unknown error")};var d=function(e){var t=e.parent;if(!t){if(e===i)return;throw new Error("unknown error")}if(e.color!==a.default.TreeNodeColorType.red){var n=e.brother;if(!n)throw new Error("unknown error");if(e===t.leftChild)if(n.color===a.default.TreeNodeColorType.red){n.color=a.default.TreeNodeColorType.black,t.color=a.default.TreeNodeColorType.red;var r=t.rotateLeft();i===t&&(i=r),d(e)}else n.color===a.default.TreeNodeColorType.black&&(n.rightChild&&n.rightChild.color===a.default.TreeNodeColorType.red?(n.color=t.color,t.color=a.default.TreeNodeColorType.black,n.rightChild&&(n.rightChild.color=a.default.TreeNodeColorType.black),r=t.rotateLeft(),i===t&&(i=r),e.color=a.default.TreeNodeColorType.black):n.rightChild&&n.rightChild.color!==a.default.TreeNodeColorType.black||!n.leftChild||n.leftChild.color!==a.default.TreeNodeColorType.red?n.leftChild&&n.leftChild.color!==a.default.TreeNodeColorType.black||n.rightChild&&n.rightChild.color!==a.default.TreeNodeColorType.black||(n.color=a.default.TreeNodeColorType.red,d(t)):(n.color=a.default.TreeNodeColorType.red,n.leftChild&&(n.leftChild.color=a.default.TreeNodeColorType.black),r=n.rotateRight(),i===n&&(i=r),d(e)));else e===t.rightChild&&(n.color===a.default.TreeNodeColorType.red?(n.color=a.default.TreeNodeColorType.black,t.color=a.default.TreeNodeColorType.red,r=t.rotateRight(),i===t&&(i=r),d(e)):n.color===a.default.TreeNodeColorType.black&&(n.leftChild&&n.leftChild.color===a.default.TreeNodeColorType.red?(n.color=t.color,t.color=a.default.TreeNodeColorType.black,n.leftChild&&(n.leftChild.color=a.default.TreeNodeColorType.black),r=t.rotateRight(),i===t&&(i=r),e.color=a.default.TreeNodeColorType.black):n.leftChild&&n.leftChild.color!==a.default.TreeNodeColorType.black||!n.rightChild||n.rightChild.color!==a.default.TreeNodeColorType.red?n.leftChild&&n.leftChild.color!==a.default.TreeNodeColorType.black||n.rightChild&&n.rightChild.color!==a.default.TreeNodeColorType.black||(n.color=a.default.TreeNodeColorType.red,d(t)):(n.color=a.default.TreeNodeColorType.red,n.rightChild&&(n.rightChild.color=a.default.TreeNodeColorType.black),r=n.rotateLeft(),i===n&&(i=r),d(e))))}else e.color=a.default.TreeNodeColorType.black},u=function(e){for(var t=e;t.leftChild||t.rightChild;){if(t.rightChild){t=c(t.rightChild);var n=e.key;e.key=t.key,t.key=n,e=t}t.leftChild&&(t=l(t.leftChild),n=e.key,e.key=t.key,t.key=n,e=t)}d(t),t&&t.remove(),--o,i.color=a.default.TreeNodeColorType.black},h=function(e,t){return!(!e||void 0===e.key)&&(!!h(e.leftChild,t)||!!t(e)||h(e.rightChild,t))};this.eraseElementByPos=function(e){if(e<0||e>=o)throw new Error("pos must more than 0 and less than set's size");var t=0;h(i,(function(n){return e===t?(u(n),!0):(++t,!1)}))},this.eraseElementByValue=function(e){if(!this.empty()){var n=m(i,e);void 0!==n&&void 0!==n.key&&0===t(n.key,e)&&u(n)}};var p=function(e,n){if(!e||void 0===e.key)throw new Error("unknown error");var r=t(n,e.key);return r<0?e.leftChild?p(e.leftChild,n):(e.leftChild=new a.default,e.leftChild.parent=e,e.leftChild.brother=e.rightChild,e.rightChild&&(e.rightChild.brother=e.leftChild),e.leftChild):r>0?e.rightChild?p(e.rightChild,n):(e.rightChild=new a.default,e.rightChild.parent=e,e.rightChild.brother=e.leftChild,e.leftChild&&(e.leftChild.brother=e.rightChild),e.rightChild):e},f=function(e){var t=e.parent;if(!t){if(e===i)return;throw new Error("unknown error")}if(t.color!==a.default.TreeNodeColorType.black&&t.color===a.default.TreeNodeColorType.red){var n=t.brother,r=t.parent;if(!r)throw new Error("unknown error");if(n&&n.color===a.default.TreeNodeColorType.red)n.color=t.color=a.default.TreeNodeColorType.black,r.color=a.default.TreeNodeColorType.red,f(r);else if(!n||n.color===a.default.TreeNodeColorType.black)if(t===r.leftChild)if(e===t.leftChild){t.color=a.default.TreeNodeColorType.black,r.color=a.default.TreeNodeColorType.red;var s=r.rotateRight();r===i&&(i=s)}else e===t.rightChild&&(s=t.rotateLeft(),r===i&&(i=s),f(t));else t===r.rightChild&&(e===t.leftChild?(s=t.rotateRight(),r===i&&(i=s),f(t)):e===t.rightChild&&(t.color=a.default.TreeNodeColorType.black,r.color=a.default.TreeNodeColorType.red,s=r.rotateLeft(),r===i&&(i=s)))}};this.insert=function(e){if(null==e)throw new Error("to avoid some unnecessary errors, we don't suggest you insert null or undefined here");if(this.empty())return++o,i.key=e,void(i.color=a.default.TreeNodeColorType.black);var n=p(i,e);void 0!==n.key&&0===t(n.key,e)||(++o,n.key=e,f(n),i.color=a.default.TreeNodeColorType.black)};var m=function(e,n){if(e&&void 0!==e.key){var r=t(n,e.key);return r<0?m(e.leftChild,n):r>0?m(e.rightChild,n):e}};this.find=function(e){var n=m(i,e);return void 0!==n&&void 0!==n.key&&0===t(n.key,e)};var g=function(e,n){if(e&&void 0!==e.key){var r=t(e.key,n);if(0===r)return e.key;if(r<0)return g(e.rightChild,n);var s=g(e.leftChild,n);return void 0!==s?s:e.key}};this.lowerBound=function(e){return g(i,e)};var y=function(e,n){if(e&&void 0!==e.key){if(t(e.key,n)<=0)return y(e.rightChild,n);var r=y(e.leftChild,n);return void 0!==r?r:e.key}};this.upperBound=function(e){return y(i,e)};var v=function(e,n){if(e&&void 0!==e.key){var r=t(e.key,n);if(0===r)return e.key;if(r>0)return v(e.leftChild,n);var s=v(e.rightChild,n);return void 0!==s?s:e.key}};this.reverseLowerBound=function(e){return v(i,e)};var b=function(e,n){if(e&&void 0!==e.key){if(t(e.key,n)>=0)return b(e.leftChild,n);var r=b(e.rightChild,n);return void 0!==r?r:e.key}};this.reverseUpperBound=function(e){return b(i,e)},this.union=function(e){var t=this;e.forEach((function(e){return t.insert(e)}))},this.getHeight=function(){if(this.empty())return 0;var e=function(t){return t?Math.max(e(t.leftChild),e(t.rightChild))+1:1};return e(i)};var w=function(e){return r(this,(function(t){switch(t.label){case 0:return e&&void 0!==e.key?[5,s(w(e.leftChild))]:[2];case 1:return t.sent(),[4,e.key];case 2:return t.sent(),[5,s(w(e.rightChild))];case 3:return t.sent(),[2]}}))};this[Symbol.iterator]=function(){return w(i)},e.forEach((function(e){return n.insert(e)})),Object.freeze(this)}Object.freeze(o),n.default=o},{"../Base/TreeNode":25}],34:[function(e,t,n){function r(e){var t=this;void 0===e&&(e=[]);var n=0,r=[];this.size=function(){return n},this.empty=function(){return 0===n},this.clear=function(){n=0,r.length=0},this.push=function(e){r.push(e),++n},this.pop=function(){r.pop(),n>0&&--n},this.top=function(){return r[n-1]},e.forEach((function(e){return t.push(e)})),Object.freeze(this)}Object.defineProperty(n,"__esModule",{value:!0}),Object.freeze(r),n.default=r},{}],35:[function(e,t,n){var r=this&&this.__generator||function(e,t){var n,r,s,a,o={label:0,sent:function(){if(1&s[0])throw s[1];return s[1]},trys:[],ops:[]};return a={next:i(0),throw:i(1),return:i(2)},"function"==typeof Symbol&&(a[Symbol.iterator]=function(){return this}),a;function i(e){return function(t){return c([e,t])}}function c(a){if(n)throw new TypeError("Generator is already executing.");for(;o;)try{if(n=1,r&&(s=2&a[0]?r.return:a[0]?r.throw||((s=r.return)&&s.call(r),0):r.next)&&!(s=s.call(r,a[1])).done)return s;switch(r=0,s&&(a=[2&a[0],s.value]),a[0]){case 0:case 1:s=a;break;case 4:return o.label++,{value:a[1],done:!1};case 5:o.label++,r=a[1],a=[0];continue;case 7:a=o.ops.pop(),o.trys.pop();continue;default:if(!((s=(s=o.trys).length>0&&s[s.length-1])||6!==a[0]&&2!==a[0])){o=0;continue}if(3===a[0]&&(!s||a[1]>s[0]&&a[1]<s[3])){o.label=a[1];break}if(6===a[0]&&o.label<s[1]){o.label=s[1],s=a;break}if(s&&o.label<s[2]){o.label=s[2],o.ops.push(a);break}s[2]&&o.ops.pop(),o.trys.pop();continue}a=t.call(e,o)}catch(e){a=[6,e],r=0}finally{n=s=0}if(5&a[0])throw a[1];return{value:a[0]?a[1]:void 0,done:!0}}},s=this&&this.__read||function(e,t){var n="function"==typeof Symbol&&e[Symbol.iterator];if(!n)return e;var r,s,a=n.call(e),o=[];try{for(;(void 0===t||t-- >0)&&!(r=a.next()).done;)o.push(r.value)}catch(e){s={error:e}}finally{try{r&&!r.done&&(n=a.return)&&n.call(a)}finally{if(s)throw s.error}}return o},a=this&&this.__spreadArray||function(e,t,n){if(n||2===arguments.length)for(var r,s=0,a=t.length;s<a;s++)!r&&s in t||(r||(r=Array.prototype.slice.call(t,0,s)),r[s]=t[s]);return e.concat(r||Array.prototype.slice.call(t))},o=this&&this.__values||function(e){var t="function"==typeof Symbol&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")};function i(e){var t=this;void 0===e&&(e=[]);var n=0,i=[];this.size=function(){return n},this.empty=function(){return 0===n},this.clear=function(){n=0,i.length=0},this.front=function(){if(!this.empty())return i[0]},this.back=function(){if(!this.empty())return i[n-1]},this.forEach=function(e){i.forEach(e)},this.getElementByPos=function(e){if(e<0||e>=n)throw new Error("pos must more than 0 and less than vector's size");return i[e]},this.eraseElementByPos=function(e){if(e<0||e>=n)throw new Error("pos must more than 0 and less than vector's size");for(var t=e;t<n-1;++t)i[t]=i[t+1];this.popBack()},this.eraseElementByValue=function(e){var t=[];this.forEach((function(n){n!==e&&t.push(n)})),t.forEach((function(e,t){i[t]=e}));for(var r=t.length;n>r;)this.popBack()},this.pushBack=function(e){i.push(e),++n},this.popBack=function(){i.pop(),n>0&&--n},this.setElementByPos=function(e,t){if(e<0||e>=n)throw new Error("pos must more than 0 and less than vector's size");i[e]=t},this.insert=function(e,t,r){if(void 0===r&&(r=1),e<0||e>n)throw new Error("pos must more than 0 and less than or equal to vector's size");i.splice.apply(i,a([e,0],s(new Array(r).fill(t)),!1)),n+=r},this.find=function(e){return i.includes(e)},this.reverse=function(){i.reverse()},this.unique=function(){var e,t=[];this.forEach((function(n,r){0!==r&&n===e||(t.push(n),e=n)})),t.forEach((function(e,t){i[t]=e}));for(var r=t.length;n>r;)this.popBack()},this.sort=function(e){i.sort(e)},this[Symbol.iterator]=function(){return function(){return r(this,(function(e){switch(e.label){case 0:return[5,o(i)];case 1:return[2,e.sent()]}}))}()},e.forEach((function(e){return t.pushBack(e)})),Object.freeze(this)}Object.defineProperty(n,"__esModule",{value:!0}),Object.freeze(i),n.default=i},{}],36:[function(e,t,n){Object.defineProperty(n,"__esModule",{value:!0}),n.HashMap=n.HashSet=n.Map=n.Set=n.PriorityQueue=n.Deque=n.LinkList=n.Queue=n.Stack=n.Vector=void 0;var r=e("./Vector/Vector");n.Vector=r.default;var s=e("./Stack/Stack");n.Stack=s.default;var a=e("./Queue/Queue");n.Queue=a.default;var o=e("./LinkList/LinkList");n.LinkList=o.default;var i=e("./Deque/Deque");n.Deque=i.default;var c=e("./PriorityQueue/PriorityQueue");n.PriorityQueue=c.default;var l=e("./Set/Set");n.Set=l.default;var d=e("./Map/Map");n.Map=d.default;var u=e("./HashSet/HashSet");n.HashSet=u.default;var h=e("./HashMap/HashMap");n.HashMap=h.default},{"./Deque/Deque":26,"./HashMap/HashMap":27,"./HashSet/HashSet":28,"./LinkList/LinkList":29,"./Map/Map":30,"./PriorityQueue/PriorityQueue":31,"./Queue/Queue":32,"./Set/Set":33,"./Stack/Stack":34,"./Vector/Vector":35}],37:[function(e,t,n){const r=e("yallist"),s=Symbol("max"),a=Symbol("length"),o=Symbol("lengthCalculator"),i=Symbol("allowStale"),c=Symbol("maxAge"),l=Symbol("dispose"),d=Symbol("noDisposeOnSet"),u=Symbol("lruList"),h=Symbol("cache"),p=Symbol("updateAgeOnGet"),f=()=>1;class m{constructor(e){if("number"==typeof e&&(e={max:e}),e||(e={}),e.max&&("number"!=typeof e.max||e.max<0))throw new TypeError("max must be a non-negative number");this[s]=e.max||1/0;const t=e.length||f;if(this[o]="function"!=typeof t?f:t,this[i]=e.stale||!1,e.maxAge&&"number"!=typeof e.maxAge)throw new TypeError("maxAge must be a number");this[c]=e.maxAge||0,this[l]=e.dispose,this[d]=e.noDisposeOnSet||!1,this[p]=e.updateAgeOnGet||!1,this.reset()}set max(e){if("number"!=typeof e||e<0)throw new TypeError("max must be a non-negative number");this[s]=e||1/0,v(this)}get max(){return this[s]}set allowStale(e){this[i]=!!e}get allowStale(){return this[i]}set maxAge(e){if("number"!=typeof e)throw new TypeError("maxAge must be a non-negative number");this[c]=e,v(this)}get maxAge(){return this[c]}set lengthCalculator(e){"function"!=typeof e&&(e=f),e!==this[o]&&(this[o]=e,this[a]=0,this[u].forEach((e=>{e.length=this[o](e.value,e.key),this[a]+=e.length}))),v(this)}get lengthCalculator(){return this[o]}get length(){return this[a]}get itemCount(){return this[u].length}rforEach(e,t){t=t||this;for(let n=this[u].tail;null!==n;){const r=n.prev;C(this,e,n,t),n=r}}forEach(e,t){t=t||this;for(let n=this[u].head;null!==n;){const r=n.next;C(this,e,n,t),n=r}}keys(){return this[u].toArray().map((e=>e.key))}values(){return this[u].toArray().map((e=>e.value))}reset(){this[l]&&this[u]&&this[u].length&&this[u].forEach((e=>this[l](e.key,e.value))),this[h]=new Map,this[u]=new r,this[a]=0}dump(){return this[u].map((e=>!y(this,e)&&{k:e.key,v:e.value,e:e.now+(e.maxAge||0)})).toArray().filter((e=>e))}dumpLru(){return this[u]}set(e,t,n){if((n=n||this[c])&&"number"!=typeof n)throw new TypeError("maxAge must be a number");const r=n?Date.now():0,i=this[o](t,e);if(this[h].has(e)){if(i>this[s])return b(this,this[h].get(e)),!1;const o=this[h].get(e).value;return this[l]&&(this[d]||this[l](e,o.value)),o.now=r,o.maxAge=n,o.value=t,this[a]+=i-o.length,o.length=i,this.get(e),v(this),!0}const p=new w(e,t,i,r,n);return p.length>this[s]?(this[l]&&this[l](e,t),!1):(this[a]+=p.length,this[u].unshift(p),this[h].set(e,this[u].head),v(this),!0)}has(e){if(!this[h].has(e))return!1;const t=this[h].get(e).value;return!y(this,t)}get(e){return g(this,e,!0)}peek(e){return g(this,e,!1)}pop(){const e=this[u].tail;return e?(b(this,e),e.value):null}del(e){b(this,this[h].get(e))}load(e){this.reset();const t=Date.now();for(let n=e.length-1;n>=0;n--){const r=e[n],s=r.e||0;if(0===s)this.set(r.k,r.v);else{const e=s-t;e>0&&this.set(r.k,r.v,e)}}}prune(){this[h].forEach(((e,t)=>g(this,t,!1)))}}const g=(e,t,n)=>{const r=e[h].get(t);if(r){const t=r.value;if(y(e,t)){if(b(e,r),!e[i])return}else n&&(e[p]&&(r.value.now=Date.now()),e[u].unshiftNode(r));return t.value}},y=(e,t)=>{if(!t||!t.maxAge&&!e[c])return!1;const n=Date.now()-t.now;return t.maxAge?n>t.maxAge:e[c]&&n>e[c]},v=e=>{if(e[a]>e[s])for(let t=e[u].tail;e[a]>e[s]&&null!==t;){const n=t.prev;b(e,t),t=n}},b=(e,t)=>{if(t){const n=t.value;e[l]&&e[l](n.key,n.value),e[a]-=n.length,e[h].delete(n.key),e[u].removeNode(t)}};class w{constructor(e,t,n,r,s){this.key=e,this.value=t,this.length=n,this.now=r,this.maxAge=s||0}}const C=(e,t,n,r)=>{let s=n.value;y(e,s)&&(b(e,n),e[i]||(s=void 0)),s&&t.call(r,s.value,s.key,e)};t.exports=m},{yallist:83}],38:[function(e,t,n){(function(e){(function(){const n=t.exports;n.types={0:"reserved",1:"connect",2:"connack",3:"publish",4:"puback",5:"pubrec",6:"pubrel",7:"pubcomp",8:"subscribe",9:"suback",10:"unsubscribe",11:"unsuback",12:"pingreq",13:"pingresp",14:"disconnect",15:"auth"},n.codes={};for(const e in n.types){const t=n.types[e];n.codes[t]=e}n.CMD_SHIFT=4,n.CMD_MASK=240,n.DUP_MASK=8,n.QOS_MASK=3,n.QOS_SHIFT=1,n.RETAIN_MASK=1,n.VARBYTEINT_MASK=127,n.VARBYTEINT_FIN_MASK=128,n.VARBYTEINT_MAX=268435455,n.SESSIONPRESENT_MASK=1,n.SESSIONPRESENT_HEADER=e.from([n.SESSIONPRESENT_MASK]),n.CONNACK_HEADER=e.from([n.codes.connack<<n.CMD_SHIFT]),n.USERNAME_MASK=128,n.PASSWORD_MASK=64,n.WILL_RETAIN_MASK=32,n.WILL_QOS_MASK=24,n.WILL_QOS_SHIFT=3,n.WILL_FLAG_MASK=4,n.CLEAN_SESSION_MASK=2,n.CONNECT_HEADER=e.from([n.codes.connect<<n.CMD_SHIFT]),n.properties={sessionExpiryInterval:17,willDelayInterval:24,receiveMaximum:33,maximumPacketSize:39,topicAliasMaximum:34,requestResponseInformation:25,requestProblemInformation:23,userProperties:38,authenticationMethod:21,authenticationData:22,payloadFormatIndicator:1,messageExpiryInterval:2,contentType:3,responseTopic:8,correlationData:9,maximumQoS:36,retainAvailable:37,assignedClientIdentifier:18,reasonString:31,wildcardSubscriptionAvailable:40,subscriptionIdentifiersAvailable:41,sharedSubscriptionAvailable:42,serverKeepAlive:19,responseInformation:26,serverReference:28,topicAlias:35,subscriptionIdentifier:11},n.propertiesCodes={};for(const e in n.properties){const t=n.properties[e];n.propertiesCodes[t]=e}function r(t){return[0,1,2].map((r=>[0,1].map((s=>[0,1].map((a=>{const o=e.alloc(1);return o.writeUInt8(n.codes[t]<<n.CMD_SHIFT|(s?n.DUP_MASK:0)|r<<n.QOS_SHIFT|a,0,!0),o}))))))}n.propertiesTypes={sessionExpiryInterval:"int32",willDelayInterval:"int32",receiveMaximum:"int16",maximumPacketSize:"int32",topicAliasMaximum:"int16",requestResponseInformation:"byte",requestProblemInformation:"byte",userProperties:"pair",authenticationMethod:"string",authenticationData:"binary",payloadFormatIndicator:"byte",messageExpiryInterval:"int32",contentType:"string",responseTopic:"string",correlationData:"binary",maximumQoS:"int8",retainAvailable:"byte",assignedClientIdentifier:"string",reasonString:"string",wildcardSubscriptionAvailable:"byte",subscriptionIdentifiersAvailable:"byte",sharedSubscriptionAvailable:"byte",serverKeepAlive:"int16",responseInformation:"string",serverReference:"string",topicAlias:"int16",subscriptionIdentifier:"var"},n.PUBLISH_HEADER=r("publish"),n.SUBSCRIBE_HEADER=r("subscribe"),n.SUBSCRIBE_OPTIONS_QOS_MASK=3,n.SUBSCRIBE_OPTIONS_NL_MASK=1,n.SUBSCRIBE_OPTIONS_NL_SHIFT=2,n.SUBSCRIBE_OPTIONS_RAP_MASK=1,n.SUBSCRIBE_OPTIONS_RAP_SHIFT=3,n.SUBSCRIBE_OPTIONS_RH_MASK=3,n.SUBSCRIBE_OPTIONS_RH_SHIFT=4,n.SUBSCRIBE_OPTIONS_RH=[0,16,32],n.SUBSCRIBE_OPTIONS_NL=4,n.SUBSCRIBE_OPTIONS_RAP=8,n.SUBSCRIBE_OPTIONS_QOS=[0,1,2],n.UNSUBSCRIBE_HEADER=r("unsubscribe"),n.ACKS={unsuback:r("unsuback"),puback:r("puback"),pubcomp:r("pubcomp"),pubrel:r("pubrel"),pubrec:r("pubrec")},n.SUBACK_HEADER=e.from([n.codes.suback<<n.CMD_SHIFT]),n.VERSION3=e.from([3]),n.VERSION4=e.from([4]),n.VERSION5=e.from([5]),n.VERSION131=e.from([131]),n.VERSION132=e.from([132]),n.QOS=[0,1,2].map((t=>e.from([t]))),n.EMPTY={pingreq:e.from([n.codes.pingreq<<4,0]),pingresp:e.from([n.codes.pingresp<<4,0]),disconnect:e.from([n.codes.disconnect<<4,0])}}).call(this)}).call(this,e("buffer").Buffer)},{buffer:17}],39:[function(e,t,n){(function(n){(function(){const r=e("./writeToStream"),s=e("events");function a(e,t){const n=new o;return r(e,n,t),n.concat()}class o extends s{constructor(){super(),this._array=new Array(20),this._i=0}write(e){return this._array[this._i++]=e,!0}concat(){let e=0;const t=new Array(this._array.length),r=this._array;let s,a=0;for(s=0;s<r.length&&void 0!==r[s];s++)"string"!=typeof r[s]?t[s]=r[s].length:t[s]=n.byteLength(r[s]),e+=t[s];const o=n.allocUnsafe(e);for(s=0;s<r.length&&void 0!==r[s];s++)"string"!=typeof r[s]?(r[s].copy(o,a),a+=t[s]):(o.write(r[s],a),a+=t[s]);return o}}t.exports=a}).call(this)}).call(this,e("buffer").Buffer)},{"./writeToStream":44,buffer:17,events:22}],40:[function(e,t,n){n.parser=e("./parser").parser,n.generate=e("./generate"),n.writeToStream=e("./writeToStream")},{"./generate":39,"./parser":43,"./writeToStream":44}],41:[function(e,t,n){(function(e){(function(){const n=65536,r={},s=e.isBuffer(e.from([1,2]).subarray(0,1));function a(t){const n=e.allocUnsafe(2);return n.writeUInt8(t>>8,0),n.writeUInt8(255&t,1),n}function o(){for(let e=0;e<n;e++)r[e]=a(e)}function i(t){const n=4;let r=0,a=0;const o=e.allocUnsafe(n);do{r=t%128|0,(t=t/128|0)>0&&(r|=128),o.writeUInt8(r,a++)}while(t>0&&a<n);return t>0&&(a=0),s?o.subarray(0,a):o.slice(0,a)}function c(t){const n=e.allocUnsafe(4);return n.writeUInt32BE(t,0),n}t.exports={cache:r,generateCache:o,generateNumber:a,genBufVariableByteInt:i,generate4ByteBuffer:c}}).call(this)}).call(this,e("buffer").Buffer)},{buffer:17}],42:[function(e,t,n){class r{constructor(){this.cmd=null,this.retain=!1,this.qos=0,this.dup=!1,this.length=-1,this.topic=null,this.payload=null}}t.exports=r},{}],43:[function(e,t,n){const r=e("bl"),s=e("events"),a=e("./packet"),o=e("./constants"),i=e("debug")("mqtt-packet:parser");class c extends s{constructor(){super(),this.parser=this.constructor.parser}static parser(e){return this instanceof c?(this.settings=e||{},this._states=["_parseHeader","_parseLength","_parsePayload","_newPacket"],this._resetState(),this):(new c).parser(e)}_resetState(){i("_resetState: resetting packet, error, _list, and _stateCounter"),this.packet=new a,this.error=null,this._list=r(),this._stateCounter=0}parse(e){for(this.error&&this._resetState(),this._list.append(e),i("parse: current state: %s",this._states[this._stateCounter]);(-1!==this.packet.length||this._list.length>0)&&this[this._states[this._stateCounter]]()&&!this.error;)this._stateCounter++,i("parse: state complete. _stateCounter is now: %d",this._stateCounter),i("parse: packet.length: %d, buffer list length: %d",this.packet.length,this._list.length),this._stateCounter>=this._states.length&&(this._stateCounter=0);return i("parse: exited while loop. packet: %d, buffer list length: %d",this.packet.length,this._list.length),this._list.length}_parseHeader(){const e=this._list.readUInt8(0);return this.packet.cmd=o.types[e>>o.CMD_SHIFT],this.packet.retain=0!=(e&o.RETAIN_MASK),this.packet.qos=e>>o.QOS_SHIFT&o.QOS_MASK,this.packet.dup=0!=(e&o.DUP_MASK),i("_parseHeader: packet: %o",this.packet),this._list.consume(1),!0}_parseLength(){const e=this._parseVarByteNum(!0);return e&&(this.packet.length=e.value,this._list.consume(e.bytes)),i("_parseLength %d",e.value),!!e}_parsePayload(){i("_parsePayload: payload %O",this._list);let e=!1;if(0===this.packet.length||this._list.length>=this.packet.length){switch(this._pos=0,this.packet.cmd){case"connect":this._parseConnect();break;case"connack":this._parseConnack();break;case"publish":this._parsePublish();break;case"puback":case"pubrec":case"pubrel":case"pubcomp":this._parseConfirmation();break;case"subscribe":this._parseSubscribe();break;case"suback":this._parseSuback();break;case"unsubscribe":this._parseUnsubscribe();break;case"unsuback":this._parseUnsuback();break;case"pingreq":case"pingresp":break;case"disconnect":this._parseDisconnect();break;case"auth":this._parseAuth();break;default:this._emitError(new Error("Not supported"))}e=!0}return i("_parsePayload complete result: %s",e),e}_parseConnect(){let e,t,n,r;i("_parseConnect");const s={},a=this.packet,c=this._parseString();if(null===c)return this._emitError(new Error("Cannot parse protocolId"));if("MQTT"!==c&&"MQIsdp"!==c)return this._emitError(new Error("Invalid protocolId"));if(a.protocolId=c,this._pos>=this._list.length)return this._emitError(new Error("Packet too short"));if(a.protocolVersion=this._list.readUInt8(this._pos),a.protocolVersion>=128&&(a.bridgeMode=!0,a.protocolVersion=a.protocolVersion-128),3!==a.protocolVersion&&4!==a.protocolVersion&&5!==a.protocolVersion)return this._emitError(new Error("Invalid protocol version"));if(this._pos++,this._pos>=this._list.length)return this._emitError(new Error("Packet too short"));if(s.username=this._list.readUInt8(this._pos)&o.USERNAME_MASK,s.password=this._list.readUInt8(this._pos)&o.PASSWORD_MASK,s.will=this._list.readUInt8(this._pos)&o.WILL_FLAG_MASK,s.will&&(a.will={},a.will.retain=0!=(this._list.readUInt8(this._pos)&o.WILL_RETAIN_MASK),a.will.qos=(this._list.readUInt8(this._pos)&o.WILL_QOS_MASK)>>o.WILL_QOS_SHIFT),a.clean=0!=(this._list.readUInt8(this._pos)&o.CLEAN_SESSION_MASK),this._pos++,a.keepalive=this._parseNum(),-1===a.keepalive)return this._emitError(new Error("Packet too short"));if(5===a.protocolVersion){const e=this._parseProperties();Object.getOwnPropertyNames(e).length&&(a.properties=e)}const l=this._parseString();if(null===l)return this._emitError(new Error("Packet too short"));if(a.clientId=l,i("_parseConnect: packet.clientId: %s",a.clientId),s.will){if(5===a.protocolVersion){const e=this._parseProperties();Object.getOwnPropertyNames(e).length&&(a.will.properties=e)}if(e=this._parseString(),null===e)return this._emitError(new Error("Cannot parse will topic"));if(a.will.topic=e,i("_parseConnect: packet.will.topic: %s",a.will.topic),t=this._parseBuffer(),null===t)return this._emitError(new Error("Cannot parse will payload"));a.will.payload=t,i("_parseConnect: packet.will.paylaod: %s",a.will.payload)}if(s.username){if(r=this._parseString(),null===r)return this._emitError(new Error("Cannot parse username"));a.username=r,i("_parseConnect: packet.username: %s",a.username)}if(s.password){if(n=this._parseBuffer(),null===n)return this._emitError(new Error("Cannot parse password"));a.password=n}return this.settings=a,i("_parseConnect: complete"),a}_parseConnack(){i("_parseConnack");const e=this.packet;if(this._list.length<1)return null;if(e.sessionPresent=!!(this._list.readUInt8(this._pos++)&o.SESSIONPRESENT_MASK),5===this.settings.protocolVersion)this._list.length>=2?e.reasonCode=this._list.readUInt8(this._pos++):e.reasonCode=0;else{if(this._list.length<2)return null;e.returnCode=this._list.readUInt8(this._pos++)}if(-1===e.returnCode||-1===e.reasonCode)return this._emitError(new Error("Cannot parse return code"));if(5===this.settings.protocolVersion){const t=this._parseProperties();Object.getOwnPropertyNames(t).length&&(e.properties=t)}i("_parseConnack: complete")}_parsePublish(){i("_parsePublish");const e=this.packet;if(e.topic=this._parseString(),null===e.topic)return this._emitError(new Error("Cannot parse topic"));if(!(e.qos>0)||this._parseMessageId()){if(5===this.settings.protocolVersion){const t=this._parseProperties();Object.getOwnPropertyNames(t).length&&(e.properties=t)}e.payload=this._list.slice(this._pos,e.length),i("_parsePublish: payload from buffer list: %o",e.payload)}}_parseSubscribe(){i("_parseSubscribe");const e=this.packet;let t,n,r,s,a,c,l;if(1!==e.qos)return this._emitError(new Error("Wrong subscribe header"));if(e.subscriptions=[],this._parseMessageId()){if(5===this.settings.protocolVersion){const t=this._parseProperties();Object.getOwnPropertyNames(t).length&&(e.properties=t)}for(;this._pos<e.length;){if(t=this._parseString(),null===t)return this._emitError(new Error("Cannot parse topic"));if(this._pos>=e.length)return this._emitError(new Error("Malformed Subscribe Payload"));n=this._parseByte(),r=n&o.SUBSCRIBE_OPTIONS_QOS_MASK,c=0!=(n>>o.SUBSCRIBE_OPTIONS_NL_SHIFT&o.SUBSCRIBE_OPTIONS_NL_MASK),a=0!=(n>>o.SUBSCRIBE_OPTIONS_RAP_SHIFT&o.SUBSCRIBE_OPTIONS_RAP_MASK),s=n>>o.SUBSCRIBE_OPTIONS_RH_SHIFT&o.SUBSCRIBE_OPTIONS_RH_MASK,l={topic:t,qos:r},5===this.settings.protocolVersion?(l.nl=c,l.rap=a,l.rh=s):this.settings.bridgeMode&&(l.rh=0,l.rap=!0,l.nl=!0),i("_parseSubscribe: push subscription `%s` to subscription",l),e.subscriptions.push(l)}}}_parseSuback(){i("_parseSuback");const e=this.packet;if(this.packet.granted=[],this._parseMessageId()){if(5===this.settings.protocolVersion){const t=this._parseProperties();Object.getOwnPropertyNames(t).length&&(e.properties=t)}for(;this._pos<this.packet.length;)this.packet.granted.push(this._list.readUInt8(this._pos++))}}_parseUnsubscribe(){i("_parseUnsubscribe");const e=this.packet;if(e.unsubscriptions=[],this._parseMessageId()){if(5===this.settings.protocolVersion){const t=this._parseProperties();Object.getOwnPropertyNames(t).length&&(e.properties=t)}for(;this._pos<e.length;){const t=this._parseString();if(null===t)return this._emitError(new Error("Cannot parse topic"));i("_parseUnsubscribe: push topic `%s` to unsubscriptions",t),e.unsubscriptions.push(t)}}}_parseUnsuback(){i("_parseUnsuback");const e=this.packet;if(!this._parseMessageId())return this._emitError(new Error("Cannot parse messageId"));if(5===this.settings.protocolVersion){const t=this._parseProperties();for(Object.getOwnPropertyNames(t).length&&(e.properties=t),e.granted=[];this._pos<this.packet.length;)this.packet.granted.push(this._list.readUInt8(this._pos++))}}_parseConfirmation(){i("_parseConfirmation: packet.cmd: `%s`",this.packet.cmd);const e=this.packet;if(this._parseMessageId(),5===this.settings.protocolVersion&&(e.length>2?(e.reasonCode=this._parseByte(),i("_parseConfirmation: packet.reasonCode `%d`",e.reasonCode)):e.reasonCode=0,e.length>3)){const t=this._parseProperties();Object.getOwnPropertyNames(t).length&&(e.properties=t)}return!0}_parseDisconnect(){const e=this.packet;if(i("_parseDisconnect"),5===this.settings.protocolVersion){this._list.length>0?e.reasonCode=this._parseByte():e.reasonCode=0;const t=this._parseProperties();Object.getOwnPropertyNames(t).length&&(e.properties=t)}return i("_parseDisconnect result: true"),!0}_parseAuth(){i("_parseAuth");const e=this.packet;if(5!==this.settings.protocolVersion)return this._emitError(new Error("Not supported auth packet for this version MQTT"));e.reasonCode=this._parseByte();const t=this._parseProperties();return Object.getOwnPropertyNames(t).length&&(e.properties=t),i("_parseAuth: result: true"),!0}_parseMessageId(){const e=this.packet;return e.messageId=this._parseNum(),null===e.messageId?(this._emitError(new Error("Cannot parse messageId")),!1):(i("_parseMessageId: packet.messageId %d",e.messageId),!0)}_parseString(e){const t=this._parseNum(),n=t+this._pos;if(-1===t||n>this._list.length||n>this.packet.length)return null;const r=this._list.toString("utf8",this._pos,n);return this._pos+=t,i("_parseString: result: %s",r),r}_parseStringPair(){return i("_parseStringPair"),{name:this._parseString(),value:this._parseString()}}_parseBuffer(){const e=this._parseNum(),t=e+this._pos;if(-1===e||t>this._list.length||t>this.packet.length)return null;const n=this._list.slice(this._pos,t);return this._pos+=e,i("_parseBuffer: result: %o",n),n}_parseNum(){if(this._list.length-this._pos<2)return-1;const e=this._list.readUInt16BE(this._pos);return this._pos+=2,i("_parseNum: result: %s",e),e}_parse4ByteNum(){if(this._list.length-this._pos<4)return-1;const e=this._list.readUInt32BE(this._pos);return this._pos+=4,i("_parse4ByteNum: result: %s",e),e}_parseVarByteNum(e){i("_parseVarByteNum");const t=4;let n,r=0,s=1,a=0,c=!1;const l=this._pos?this._pos:0;for(;r<t&&l+r<this._list.length;){if(n=this._list.readUInt8(l+r++),a+=s*(n&o.VARBYTEINT_MASK),s*=128,0==(n&o.VARBYTEINT_FIN_MASK)){c=!0;break}if(this._list.length<=r)break}return!c&&r===t&&this._list.length>=r&&this._emitError(new Error("Invalid variable byte integer")),l&&(this._pos+=r),c=!!c&&(e?{bytes:r,value:a}:a),i("_parseVarByteNum: result: %o",c),c}_parseByte(){let e;return this._pos<this._list.length&&(e=this._list.readUInt8(this._pos),this._pos++),i("_parseByte: result: %o",e),e}_parseByType(e){switch(i("_parseByType: type: %s",e),e){case"byte":return 0!==this._parseByte();case"int8":return this._parseByte();case"int16":return this._parseNum();case"int32":return this._parse4ByteNum();case"var":return this._parseVarByteNum();case"string":return this._parseString();case"pair":return this._parseStringPair();case"binary":return this._parseBuffer()}}_parseProperties(){i("_parseProperties");const e=this._parseVarByteNum(),t=this._pos+e,n={};for(;this._pos<t;){const e=this._parseByte();if(!e)return this._emitError(new Error("Cannot parse property code type")),!1;const t=o.propertiesCodes[e];if(!t)return this._emitError(new Error("Unknown property")),!1;if("userProperties"!==t)n[t]?(Array.isArray(n[t])||(n[t]=[n[t]]),n[t].push(this._parseByType(o.propertiesTypes[t]))):n[t]=this._parseByType(o.propertiesTypes[t]);else{n[t]||(n[t]=Object.create(null));const e=this._parseByType(o.propertiesTypes[t]);if(n[t][e.name])if(Array.isArray(n[t][e.name]))n[t][e.name].push(e.value);else{const r=n[t][e.name];n[t][e.name]=[r],n[t][e.name].push(e.value)}else n[t][e.name]=e.value}}return n}_newPacket(){return i("_newPacket"),this.packet&&(this._list.consume(this.packet.length),i("_newPacket: parser emit packet: packet.cmd: %s, packet.payload: %s, packet.length: %d",this.packet.cmd,this.packet.payload,this.packet.length),this.emit("packet",this.packet)),i("_newPacket: new packet"),this.packet=new a,this._pos=0,!0}_emitError(e){i("_emitError"),this.error=e,this.emit("error",e)}}t.exports=c},{"./constants":38,"./packet":42,bl:15,debug:18,events:22}],44:[function(e,t,n){(function(n){(function(){const r=e("./constants"),s=n.allocUnsafe(0),a=n.from([0]),o=e("./numbers"),i=e("process-nextick-args").nextTick,c=e("debug")("mqtt-packet:writeToStream"),l=o.cache,d=o.generateNumber,u=o.generateCache,h=o.genBufVariableByteInt,p=o.generate4ByteBuffer;let f=j,m=!0;function g(e,t,n){switch(c("generate called"),t.cork&&(t.cork(),i(y,t)),m&&(m=!1,u()),c("generate: packet.cmd: %s",e.cmd),e.cmd){case"connect":return v(e,t);case"connack":return b(e,t,n);case"publish":return w(e,t,n);case"puback":case"pubrec":case"pubrel":case"pubcomp":return C(e,t,n);case"subscribe":return I(e,t,n);case"suback":return S(e,t,n);case"unsubscribe":return _(e,t,n);case"unsuback":return k(e,t,n);case"pingreq":case"pingresp":return T(e,t);case"disconnect":return O(e,t,n);case"auth":return A(e,t,n);default:return t.emit("error",new Error("Unknown command")),!1}}function y(e){e.uncork()}function v(e,t,s){const a=e||{},o=a.protocolId||"MQTT";let i=a.protocolVersion||4;const c=a.will;let l=a.clean;const d=a.keepalive||0,u=a.clientId||"",h=a.username,p=a.password,m=a.properties;void 0===l&&(l=!0);let g=0;if(!o||"string"!=typeof o&&!n.isBuffer(o))return t.emit("error",new Error("Invalid protocolId")),!1;if(g+=o.length+2,3!==i&&4!==i&&5!==i)return t.emit("error",new Error("Invalid protocol version")),!1;if(g+=1,("string"==typeof u||n.isBuffer(u))&&(u||i>=4)&&(u||l))g+=n.byteLength(u)+2;else{if(i<4)return t.emit("error",new Error("clientId must be supplied before 3.1.1")),!1;if(1*l==0)return t.emit("error",new Error("clientId must be given if cleanSession set to 0")),!1}if("number"!=typeof d||d<0||d>65535||d%1!=0)return t.emit("error",new Error("Invalid keepalive")),!1;if(g+=2,g+=1,5===i){var y=N(t,m);if(!y)return!1;g+=y.length}if(c){if("object"!=typeof c)return t.emit("error",new Error("Invalid will")),!1;if(!c.topic||"string"!=typeof c.topic)return t.emit("error",new Error("Invalid will topic")),!1;if(g+=n.byteLength(c.topic)+2,g+=2,c.payload){if(!(c.payload.length>=0))return t.emit("error",new Error("Invalid will payload")),!1;"string"==typeof c.payload?g+=n.byteLength(c.payload):g+=c.payload.length}var v={};if(5===i){if(!(v=N(t,c.properties)))return!1;g+=v.length}}let b=!1;if(null!=h){if(!K(h))return t.emit("error",new Error("Invalid username")),!1;b=!0,g+=n.byteLength(h)+2}if(null!=p){if(!b)return t.emit("error",new Error("Username is required to use password")),!1;if(!K(p))return t.emit("error",new Error("Invalid password")),!1;g+=L(p)+2}t.write(r.CONNECT_HEADER),M(t,g),D(t,o),a.bridgeMode&&(i+=128),t.write(131===i?r.VERSION131:132===i?r.VERSION132:4===i?r.VERSION4:5===i?r.VERSION5:r.VERSION3);let w=0;return w|=null!=h?r.USERNAME_MASK:0,w|=null!=p?r.PASSWORD_MASK:0,w|=c&&c.retain?r.WILL_RETAIN_MASK:0,w|=c&&c.qos?c.qos<<r.WILL_QOS_SHIFT:0,w|=c?r.WILL_FLAG_MASK:0,w|=l?r.CLEAN_SESSION_MASK:0,t.write(n.from([w])),f(t,d),5===i&&y.write(),D(t,u),c&&(5===i&&v.write(),R(t,c.topic),D(t,c.payload)),null!=h&&D(t,h),null!=p&&D(t,p),!0}function b(e,t,s){const o=s?s.protocolVersion:4,i=e||{},c=5===o?i.reasonCode:i.returnCode,l=i.properties;let d=2;if("number"!=typeof c)return t.emit("error",new Error("Invalid return code")),!1;let u=null;if(5===o){if(u=N(t,l),!u)return!1;d+=u.length}return t.write(r.CONNACK_HEADER),M(t,d),t.write(i.sessionPresent?r.SESSIONPRESENT_HEADER:a),t.write(n.from([c])),null!=u&&u.write(),!0}function w(e,t,a){c("publish: packet: %o",e);const o=a?a.protocolVersion:4,i=e||{},l=i.qos||0,d=i.retain?r.RETAIN_MASK:0,u=i.topic,h=i.payload||s,p=i.messageId,m=i.properties;let g=0;if("string"==typeof u)g+=n.byteLength(u)+2;else{if(!n.isBuffer(u))return t.emit("error",new Error("Invalid topic")),!1;g+=u.length+2}if(n.isBuffer(h)?g+=h.length:g+=n.byteLength(h),l&&"number"!=typeof p)return t.emit("error",new Error("Invalid messageId")),!1;l&&(g+=2);let y=null;if(5===o){if(y=N(t,m),!y)return!1;g+=y.length}return t.write(r.PUBLISH_HEADER[l][i.dup?1:0][d?1:0]),M(t,g),f(t,L(u)),t.write(u),l>0&&f(t,p),null!=y&&y.write(),c("publish: payload: %o",h),t.write(h)}function C(e,t,s){const a=s?s.protocolVersion:4,o=e||{},i=o.cmd||"puback",c=o.messageId,l=o.dup&&"pubrel"===i?r.DUP_MASK:0;let d=0;const u=o.reasonCode,h=o.properties;let p=5===a?3:2;if("pubrel"===i&&(d=1),"number"!=typeof c)return t.emit("error",new Error("Invalid messageId")),!1;let m=null;if(5===a&&"object"==typeof h){if(m=B(t,h,s,p),!m)return!1;p+=m.length}return t.write(r.ACKS[i][d][l][0]),M(t,p),f(t,c),5===a&&t.write(n.from([u])),null!==m&&m.write(),!0}function I(e,t,s){c("subscribe: packet: ");const a=s?s.protocolVersion:4,o=e||{},i=o.dup?r.DUP_MASK:0,l=o.messageId,d=o.subscriptions,u=o.properties;let h=0;if("number"!=typeof l)return t.emit("error",new Error("Invalid messageId")),!1;h+=2;let p=null;if(5===a){if(p=N(t,u),!p)return!1;h+=p.length}if("object"!=typeof d||!d.length)return t.emit("error",new Error("Invalid subscriptions")),!1;for(let e=0;e<d.length;e+=1){const r=d[e].topic,s=d[e].qos;if("string"!=typeof r)return t.emit("error",new Error("Invalid subscriptions - invalid topic")),!1;if("number"!=typeof s)return t.emit("error",new Error("Invalid subscriptions - invalid qos")),!1;if(5===a){if("boolean"!=typeof(d[e].nl||!1))return t.emit("error",new Error("Invalid subscriptions - invalid No Local")),!1;if("boolean"!=typeof(d[e].rap||!1))return t.emit("error",new Error("Invalid subscriptions - invalid Retain as Published")),!1;const n=d[e].rh||0;if("number"!=typeof n||n>2)return t.emit("error",new Error("Invalid subscriptions - invalid Retain Handling")),!1}h+=n.byteLength(r)+2+1}c("subscribe: writing to stream: %o",r.SUBSCRIBE_HEADER),t.write(r.SUBSCRIBE_HEADER[1][i?1:0][0]),M(t,h),f(t,l),null!==p&&p.write();let m=!0;for(const e of d){const s=e.topic,o=e.qos,i=+e.nl,c=+e.rap,l=e.rh;let d;R(t,s),d=r.SUBSCRIBE_OPTIONS_QOS[o],5===a&&(d|=i?r.SUBSCRIBE_OPTIONS_NL:0,d|=c?r.SUBSCRIBE_OPTIONS_RAP:0,d|=l?r.SUBSCRIBE_OPTIONS_RH[l]:0),m=t.write(n.from([d]))}return m}function S(e,t,s){const a=s?s.protocolVersion:4,o=e||{},i=o.messageId,c=o.granted,l=o.properties;let d=0;if("number"!=typeof i)return t.emit("error",new Error("Invalid messageId")),!1;if(d+=2,"object"!=typeof c||!c.length)return t.emit("error",new Error("Invalid qos vector")),!1;for(let e=0;e<c.length;e+=1){if("number"!=typeof c[e])return t.emit("error",new Error("Invalid qos vector")),!1;d+=1}let u=null;if(5===a){if(u=B(t,l,s,d),!u)return!1;d+=u.length}return t.write(r.SUBACK_HEADER),M(t,d),f(t,i),null!==u&&u.write(),t.write(n.from(c))}function _(e,t,s){const a=s?s.protocolVersion:4,o=e||{},i=o.messageId,c=o.dup?r.DUP_MASK:0,l=o.unsubscriptions,d=o.properties;let u=0;if("number"!=typeof i)return t.emit("error",new Error("Invalid messageId")),!1;if(u+=2,"object"!=typeof l||!l.length)return t.emit("error",new Error("Invalid unsubscriptions")),!1;for(let e=0;e<l.length;e+=1){if("string"!=typeof l[e])return t.emit("error",new Error("Invalid unsubscriptions")),!1;u+=n.byteLength(l[e])+2}let h=null;if(5===a){if(h=N(t,d),!h)return!1;u+=h.length}t.write(r.UNSUBSCRIBE_HEADER[1][c?1:0][0]),M(t,u),f(t,i),null!==h&&h.write();let p=!0;for(let e=0;e<l.length;e++)p=R(t,l[e]);return p}function k(e,t,s){const a=s?s.protocolVersion:4,o=e||{},i=o.messageId,c=o.dup?r.DUP_MASK:0,l=o.granted,d=o.properties,u=o.cmd,h=0;let p=2;if("number"!=typeof i)return t.emit("error",new Error("Invalid messageId")),!1;if(5===a){if("object"!=typeof l||!l.length)return t.emit("error",new Error("Invalid qos vector")),!1;for(let e=0;e<l.length;e+=1){if("number"!=typeof l[e])return t.emit("error",new Error("Invalid qos vector")),!1;p+=1}}let m=null;if(5===a){if(m=B(t,d,s,p),!m)return!1;p+=m.length}return t.write(r.ACKS[u][h][c][0]),M(t,p),f(t,i),null!==m&&m.write(),5===a&&t.write(n.from(l)),!0}function T(e,t,n){return t.write(r.EMPTY[e.cmd])}function O(e,t,s){const a=s?s.protocolVersion:4,o=e||{},i=o.reasonCode,c=o.properties;let l=5===a?1:0,d=null;if(5===a){if(d=B(t,c,s,l),!d)return!1;l+=d.length}return t.write(n.from([r.codes.disconnect<<4])),M(t,l),5===a&&t.write(n.from([i])),null!==d&&d.write(),!0}function A(e,t,s){const a=s?s.protocolVersion:4,o=e||{},i=o.reasonCode,c=o.properties;let l=5===a?1:0;5!==a&&t.emit("error",new Error("Invalid mqtt version for auth packet"));const d=B(t,c,s,l);return!!d&&(l+=d.length,t.write(n.from([r.codes.auth<<4])),M(t,l),t.write(n.from([i])),null!==d&&d.write(),!0)}Object.defineProperty(g,"cacheNumbers",{get:()=>f===j,set(e){e?(l&&0!==Object.keys(l).length||(m=!0),f=j):(m=!1,f=U)}});const E={};function M(e,t){if(t>r.VARBYTEINT_MAX)return e.emit("error",new Error(`Invalid variable byte integer: ${t}`)),!1;let n=E[t];return n||(n=h(t),t<16384&&(E[t]=n)),c("writeVarByteInt: writing to stream: %o",n),e.write(n)}function R(e,t){const r=n.byteLength(t);return f(e,r),c("writeString: %s",t),e.write(t,"utf8")}function P(e,t,n){R(e,t),R(e,n)}function j(e,t){return c("writeNumberCached: number: %d",t),c("writeNumberCached: %o",l[t]),e.write(l[t])}function U(e,t){const n=d(t);return c("writeNumberGenerated: %o",n),e.write(n)}function x(e,t){const n=p(t);return c("write4ByteNumber: %o",n),e.write(n)}function D(e,t){"string"==typeof t?R(e,t):t?(f(e,t.length),e.write(t)):f(e,0)}function N(e,t){if("object"!=typeof t||null!=t.length)return{length:1,write(){F(e,{},0)}};let s=0;function a(t,s){let a=0;switch(r.propertiesTypes[t]){case"byte":if("boolean"!=typeof s)return e.emit("error",new Error(`Invalid ${t}: ${s}`)),!1;a+=2;break;case"int8":if("number"!=typeof s||s<0||s>255)return e.emit("error",new Error(`Invalid ${t}: ${s}`)),!1;a+=2;break;case"binary":if(s&&null===s)return e.emit("error",new Error(`Invalid ${t}: ${s}`)),!1;a+=1+n.byteLength(s)+2;break;case"int16":if("number"!=typeof s||s<0||s>65535)return e.emit("error",new Error(`Invalid ${t}: ${s}`)),!1;a+=3;break;case"int32":if("number"!=typeof s||s<0||s>4294967295)return e.emit("error",new Error(`Invalid ${t}: ${s}`)),!1;a+=5;break;case"var":if("number"!=typeof s||s<0||s>268435455)return e.emit("error",new Error(`Invalid ${t}: ${s}`)),!1;a+=1+n.byteLength(h(s));break;case"string":if("string"!=typeof s)return e.emit("error",new Error(`Invalid ${t}: ${s}`)),!1;a+=3+n.byteLength(s.toString());break;case"pair":if("object"!=typeof s)return e.emit("error",new Error(`Invalid ${t}: ${s}`)),!1;a+=Object.getOwnPropertyNames(s).reduce(((e,t)=>{const r=s[t];return Array.isArray(r)?e+=r.reduce(((e,r)=>e+=3+n.byteLength(t.toString())+2+n.byteLength(r.toString())),0):e+=3+n.byteLength(t.toString())+2+n.byteLength(s[t].toString()),e}),0);break;default:return e.emit("error",new Error(`Invalid property ${t}: ${s}`)),!1}return a}if(t)for(const e in t){let n=0,r=0;const o=t[e];if(Array.isArray(o))for(let t=0;t<o.length;t++){if(r=a(e,o[t]),!r)return!1;n+=r}else{if(r=a(e,o),!r)return!1;n=r}if(!n)return!1;s+=n}return{length:n.byteLength(h(s))+s,write(){F(e,t,s)}}}function B(e,t,n,r){const s=["reasonString","userProperties"],a=n&&n.properties&&n.properties.maximumPacketSize?n.properties.maximumPacketSize:0;let o=N(e,t);if(a)for(;r+o.length>a;){const n=s.shift();if(!n||!t[n])return!1;delete t[n],o=N(e,t)}return o}function q(e,t,s){switch(r.propertiesTypes[t]){case"byte":e.write(n.from([r.properties[t]])),e.write(n.from([+s]));break;case"int8":e.write(n.from([r.properties[t]])),e.write(n.from([s]));break;case"binary":e.write(n.from([r.properties[t]])),D(e,s);break;case"int16":e.write(n.from([r.properties[t]])),f(e,s);break;case"int32":e.write(n.from([r.properties[t]])),x(e,s);break;case"var":e.write(n.from([r.properties[t]])),M(e,s);break;case"string":e.write(n.from([r.properties[t]])),R(e,s);break;case"pair":Object.getOwnPropertyNames(s).forEach((a=>{const o=s[a];Array.isArray(o)?o.forEach((s=>{e.write(n.from([r.properties[t]])),P(e,a.toString(),s.toString())})):(e.write(n.from([r.properties[t]])),P(e,a.toString(),o.toString()))}));break;default:return e.emit("error",new Error(`Invalid property ${t} value: ${s}`)),!1}}function F(e,t,n){M(e,n);for(const n in t)if(Object.prototype.hasOwnProperty.call(t,n)&&null!==t[n]){const r=t[n];if(Array.isArray(r))for(let t=0;t<r.length;t++)q(e,n,r[t]);else q(e,n,r)}}function L(e){return e?e instanceof n?e.length:n.byteLength(e):0}function K(e){return"string"==typeof e||e instanceof n}t.exports=g}).call(this)}).call(this,e("buffer").Buffer)},{"./constants":38,"./numbers":41,buffer:17,debug:18,"process-nextick-args":49}],45:[function(e,t,n){var r=1e3,s=60*r,a=60*s,o=24*a,i=7*o,c=365.25*o;function l(e){if(!((e=String(e)).length>100)){var t=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);if(t){var n=parseFloat(t[1]);switch((t[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return n*c;case"weeks":case"week":case"w":return n*i;case"days":case"day":case"d":return n*o;case"hours":case"hour":case"hrs":case"hr":case"h":return n*a;case"minutes":case"minute":case"mins":case"min":case"m":return n*s;case"seconds":case"second":case"secs":case"sec":case"s":return n*r;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return n;default:return}}}}function d(e){var t=Math.abs(e);return t>=o?Math.round(e/o)+"d":t>=a?Math.round(e/a)+"h":t>=s?Math.round(e/s)+"m":t>=r?Math.round(e/r)+"s":e+"ms"}function u(e){var t=Math.abs(e);return t>=o?h(e,t,o,"day"):t>=a?h(e,t,a,"hour"):t>=s?h(e,t,s,"minute"):t>=r?h(e,t,r,"second"):e+" ms"}function h(e,t,n,r){var s=t>=1.5*n;return Math.round(e/n)+" "+r+(s?"s":"")}t.exports=function(e,t){t=t||{};var n=typeof e;if("string"===n&&e.length>0)return l(e);if("number"===n&&isFinite(e))return t.long?u(e):d(e);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(e))}},{}],46:[function(e,t,n){const r=e("./lib/number-allocator.js");t.exports.NumberAllocator=r},{"./lib/number-allocator.js":47}],47:[function(e,t,n){const r=e("js-sdsl").Set,s=e("debug")("number-allocator:trace"),a=e("debug")("number-allocator:error");function o(e,t){this.low=e,this.high=t}function i(e,t){if(!(this instanceof i))return new i(e,t);this.min=e,this.max=t,this.ss=new r([],((e,t)=>e.compare(t))),s("Create"),this.clear()}o.prototype.equals=function(e){return this.low===e.low&&this.high===e.high},o.prototype.compare=function(e){return this.low<e.low&&this.high<e.low?-1:e.low<this.low&&e.high<this.low?1:0},i.prototype.firstVacant=function(){return 0===this.ss.size()?null:this.ss.front().low},i.prototype.alloc=function(){if(0===this.ss.size())return s("alloc():empty"),null;const e=this.ss.front(),t=e.low;return t+1<=e.high?++e.low:this.ss.eraseElementByPos(0),s("alloc():"+t),t},i.prototype.use=function(e){const t=new o(e,e),n=this.ss.lowerBound(t);if(n){if(n.equals(t))return this.ss.eraseElementByValue(n),s("use():"+e),!0;if(n.low>e)return!1;if(n.low===e)return++n.low,s("use():"+e),!0;if(n.high===e)return--n.high,s("use():"+e),!0;const r=n.low;return n.low=e+1,this.ss.insert(new o(r,e-1)),s("use():"+e),!0}return s("use():failed"),!1},i.prototype.free=function(e){if(e<this.min||e>this.max)return void a("free():"+e+" is out of range");const t=new o(e,e),n=this.ss.lowerBound(t);if(n){if(n.low<=e&&e<=n.high)return void a("free():"+e+" has already been vacant");if(n===this.ss.front())e+1===n.low?--n.low:this.ss.insert(t);else{const r=this.ss.reverseLowerBound(t);r.high+1===e?e+1===n.low?(this.ss.eraseElementByValue(r),n.low=r.low):r.high=e:e+1===n.low?n.low=e:this.ss.insert(t)}}else{if(n===this.ss.front())return void this.ss.insert(t);const r=this.ss.reverseLowerBound(t);r.high+1===e?r.high=e:this.ss.insert(t)}s("free():"+e)},i.prototype.clear=function(){s("clear()"),this.ss.clear(),this.ss.insert(new o(this.min,this.max))},i.prototype.intervalCount=function(){return this.ss.size()},i.prototype.dump=function(){console.log("length:"+this.ss.size());for(const e of this.ss)console.log(e)},t.exports=i},{debug:18,"js-sdsl":36}],48:[function(e,t,n){var r=e("wrappy");function s(e){var t=function(){return t.called?t.value:(t.called=!0,t.value=e.apply(this,arguments))};return t.called=!1,t}function a(e){var t=function(){if(t.called)throw new Error(t.onceError);return t.called=!0,t.value=e.apply(this,arguments)},n=e.name||"Function wrapped with `once`";return t.onceError=n+" shouldn't be called more than once",t.called=!1,t}t.exports=r(s),t.exports.strict=r(a),s.proto=s((function(){Object.defineProperty(Function.prototype,"once",{value:function(){return s(this)},configurable:!0}),Object.defineProperty(Function.prototype,"onceStrict",{value:function(){return a(this)},configurable:!0})}))},{wrappy:79}],49:[function(e,t,n){(function(e){(function(){function n(t,n,r,s){if("function"!=typeof t)throw new TypeError('"callback" argument must be a function');var a,o,i=arguments.length;switch(i){case 0:case 1:return e.nextTick(t);case 2:return e.nextTick((function(){t.call(null,n)}));case 3:return e.nextTick((function(){t.call(null,n,r)}));case 4:return e.nextTick((function(){t.call(null,n,r,s)}));default:for(a=new Array(i-1),o=0;o<a.length;)a[o++]=arguments[o];return e.nextTick((function(){t.apply(null,a)}))}}void 0===e||!e.version||0===e.version.indexOf("v0.")||0===e.version.indexOf("v1.")&&0!==e.version.indexOf("v1.8.")?t.exports={nextTick:n}:t.exports=e}).call(this)}).call(this,e("_process"))},{_process:50}],50:[function(e,t,n){var r,s,a=t.exports={};function o(){throw new Error("setTimeout has not been defined")}function i(){throw new Error("clearTimeout has not been defined")}function c(e){if(r===setTimeout)return setTimeout(e,0);if((r===o||!r)&&setTimeout)return r=setTimeout,setTimeout(e,0);try{return r(e,0)}catch(t){try{return r.call(null,e,0)}catch(t){return r.call(this,e,0)}}}function l(e){if(s===clearTimeout)return clearTimeout(e);if((s===i||!s)&&clearTimeout)return s=clearTimeout,clearTimeout(e);try{return s(e)}catch(t){try{return s.call(null,e)}catch(t){return s.call(this,e)}}}!function(){try{r="function"==typeof setTimeout?setTimeout:o}catch(e){r=o}try{s="function"==typeof clearTimeout?clearTimeout:i}catch(e){s=i}}();var d,u=[],h=!1,p=-1;function f(){h&&d&&(h=!1,d.length?u=d.concat(u):p=-1,u.length&&m())}function m(){if(!h){var e=c(f);h=!0;for(var t=u.length;t;){for(d=u,u=[];++p<t;)d&&d[p].run();p=-1,t=u.length}d=null,h=!1,l(e)}}function g(e,t){this.fun=e,this.array=t}function y(){}a.nextTick=function(e){var t=new Array(arguments.length-1);if(arguments.length>1)for(var n=1;n<arguments.length;n++)t[n-1]=arguments[n];u.push(new g(e,t)),1!==u.length||h||c(m)},g.prototype.run=function(){this.fun.apply(null,this.array)},a.title="browser",a.browser=!0,a.env={},a.argv=[],a.version="",a.versions={},a.on=y,a.addListener=y,a.once=y,a.off=y,a.removeListener=y,a.removeAllListeners=y,a.emit=y,a.prependListener=y,a.prependOnceListener=y,a.listeners=function(e){return[]},a.binding=function(e){throw new Error("process.binding is not supported")},a.cwd=function(){return"/"},a.chdir=function(e){throw new Error("process.chdir is not supported")},a.umask=function(){return 0}},{}],51:[function(e,t,n){(function(e){(function(){!function(r){var s="object"==typeof n&&n&&!n.nodeType&&n,a="object"==typeof t&&t&&!t.nodeType&&t,o="object"==typeof e&&e;o.global!==o&&o.window!==o&&o.self!==o||(r=o);var i,c,l=2147483647,d=36,u=1,h=26,p=38,f=700,m=72,g=128,y="-",v=/^xn--/,b=/[^\x20-\x7E]/,w=/[\x2E\u3002\uFF0E\uFF61]/g,C={overflow:"Overflow: input needs wider integers to process","not-basic":"Illegal input >= 0x80 (not a basic code point)","invalid-input":"Invalid input"},I=d-u,S=Math.floor,_=String.fromCharCode;function k(e){throw new RangeError(C[e])}function T(e,t){for(var n=e.length,r=[];n--;)r[n]=t(e[n]);return r}function O(e,t){var n=e.split("@"),r="";return n.length>1&&(r=n[0]+"@",e=n[1]),r+T((e=e.replace(w,".")).split("."),t).join(".")}function A(e){for(var t,n,r=[],s=0,a=e.length;s<a;)(t=e.charCodeAt(s++))>=55296&&t<=56319&&s<a?56320==(64512&(n=e.charCodeAt(s++)))?r.push(((1023&t)<<10)+(1023&n)+65536):(r.push(t),s--):r.push(t);return r}function E(e){return T(e,(function(e){var t="";return e>65535&&(t+=_((e-=65536)>>>10&1023|55296),e=56320|1023&e),t+=_(e)})).join("")}function M(e){return e-48<10?e-22:e-65<26?e-65:e-97<26?e-97:d}function R(e,t){return e+22+75*(e<26)-((0!=t)<<5)}function P(e,t,n){var r=0;for(e=n?S(e/f):e>>1,e+=S(e/t);e>I*h>>1;r+=d)e=S(e/I);return S(r+(I+1)*e/(e+p))}function j(e){var t,n,r,s,a,o,i,c,p,f,v=[],b=e.length,w=0,C=g,I=m;for((n=e.lastIndexOf(y))<0&&(n=0),r=0;r<n;++r)e.charCodeAt(r)>=128&&k("not-basic"),v.push(e.charCodeAt(r));for(s=n>0?n+1:0;s<b;){for(a=w,o=1,i=d;s>=b&&k("invalid-input"),((c=M(e.charCodeAt(s++)))>=d||c>S((l-w)/o))&&k("overflow"),w+=c*o,!(c<(p=i<=I?u:i>=I+h?h:i-I));i+=d)o>S(l/(f=d-p))&&k("overflow"),o*=f;I=P(w-a,t=v.length+1,0==a),S(w/t)>l-C&&k("overflow"),C+=S(w/t),w%=t,v.splice(w++,0,C)}return E(v)}function U(e){var t,n,r,s,a,o,i,c,p,f,v,b,w,C,I,T=[];for(b=(e=A(e)).length,t=g,n=0,a=m,o=0;o<b;++o)(v=e[o])<128&&T.push(_(v));for(r=s=T.length,s&&T.push(y);r<b;){for(i=l,o=0;o<b;++o)(v=e[o])>=t&&v<i&&(i=v);for(i-t>S((l-n)/(w=r+1))&&k("overflow"),n+=(i-t)*w,t=i,o=0;o<b;++o)if((v=e[o])<t&&++n>l&&k("overflow"),v==t){for(c=n,p=d;!(c<(f=p<=a?u:p>=a+h?h:p-a));p+=d)I=c-f,C=d-f,T.push(_(R(f+I%C,0))),c=S(I/C);T.push(_(R(c,0))),a=P(n,w,r==s),n=0,++r}++n,++t}return T.join("")}function x(e){return O(e,(function(e){return v.test(e)?j(e.slice(4).toLowerCase()):e}))}function D(e){return O(e,(function(e){return b.test(e)?"xn--"+U(e):e}))}if(i={version:"1.4.1",ucs2:{decode:A,encode:E},decode:j,encode:U,toASCII:D,toUnicode:x},s&&a)if(t.exports==s)a.exports=i;else for(c in i)i.hasOwnProperty(c)&&(s[c]=i[c]);else r.punycode=i}(this)}).call(this)}).call(this,void 0!==At?At:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],52:[function(e,t,n){function r(e,t){return Object.prototype.hasOwnProperty.call(e,t)}t.exports=function(e,t,n,a){t=t||"&",n=n||"=";var o={};if("string"!=typeof e||0===e.length)return o;var i=/\+/g;e=e.split(t);var c=1e3;a&&"number"==typeof a.maxKeys&&(c=a.maxKeys);var l=e.length;c>0&&l>c&&(l=c);for(var d=0;d<l;++d){var u,h,p,f,m=e[d].replace(i,"%20"),g=m.indexOf(n);g>=0?(u=m.substr(0,g),h=m.substr(g+1)):(u=m,h=""),p=decodeURIComponent(u),f=decodeURIComponent(h),r(o,p)?s(o[p])?o[p].push(f):o[p]=[o[p],f]:o[p]=f}return o};var s=Array.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)}},{}],53:[function(e,t,n){var r=function(e){switch(typeof e){case"string":return e;case"boolean":return e?"true":"false";case"number":return isFinite(e)?e:"";default:return""}};t.exports=function(e,t,n,i){return t=t||"&",n=n||"=",null===e&&(e=void 0),"object"==typeof e?a(o(e),(function(o){var i=encodeURIComponent(r(o))+n;return s(e[o])?a(e[o],(function(e){return i+encodeURIComponent(r(e))})).join(t):i+encodeURIComponent(r(e[o]))})).join(t):i?encodeURIComponent(r(i))+n+encodeURIComponent(r(e)):""};var s=Array.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)};function a(e,t){if(e.map)return e.map(t);for(var n=[],r=0;r<e.length;r++)n.push(t(e[r],r));return n}var o=Object.keys||function(e){var t=[];for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.push(n);return t}},{}],54:[function(e,t,n){n.decode=n.parse=e("./decode"),n.encode=n.stringify=e("./encode")},{"./decode":52,"./encode":53}],55:[function(e,t,n){function r(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,e.__proto__=t}var s={};function a(e,t,n){function a(e,n,r){return"string"==typeof t?t:t(e,n,r)}n||(n=Error);var o=function(e){function t(t,n,r){return e.call(this,a(t,n,r))||this}return r(t,e),t}(n);o.prototype.name=n.name,o.prototype.code=e,s[e]=o}function o(e,t){if(Array.isArray(e)){var n=e.length;return e=e.map((function(e){return String(e)})),n>2?"one of ".concat(t," ").concat(e.slice(0,n-1).join(", "),", or ")+e[n-1]:2===n?"one of ".concat(t," ").concat(e[0]," or ").concat(e[1]):"of ".concat(t," ").concat(e[0])}return"of ".concat(t," ").concat(String(e))}function i(e,t,n){return e.substr(!n||n<0?0:+n,t.length)===t}function c(e,t,n){return(void 0===n||n>e.length)&&(n=e.length),e.substring(n-t.length,n)===t}function l(e,t,n){return"number"!=typeof n&&(n=0),!(n+t.length>e.length)&&-1!==e.indexOf(t,n)}a("ERR_INVALID_OPT_VALUE",(function(e,t){return'The value "'+t+'" is invalid for option "'+e+'"'}),TypeError),a("ERR_INVALID_ARG_TYPE",(function(e,t,n){var r,s;if("string"==typeof t&&i(t,"not ")?(r="must not be",t=t.replace(/^not /,"")):r="must be",c(e," argument"))s="The ".concat(e," ").concat(r," ").concat(o(t,"type"));else{var a=l(e,".")?"property":"argument";s='The "'.concat(e,'" ').concat(a," ").concat(r," ").concat(o(t,"type"))}return s+=". Received type ".concat(typeof n)}),TypeError),a("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF"),a("ERR_METHOD_NOT_IMPLEMENTED",(function(e){return"The "+e+" method is not implemented"})),a("ERR_STREAM_PREMATURE_CLOSE","Premature close"),a("ERR_STREAM_DESTROYED",(function(e){return"Cannot call "+e+" after a stream was destroyed"})),a("ERR_MULTIPLE_CALLBACK","Callback called multiple times"),a("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable"),a("ERR_STREAM_WRITE_AFTER_END","write after end"),a("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError),a("ERR_UNKNOWN_ENCODING",(function(e){return"Unknown encoding: "+e}),TypeError),a("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event"),t.exports.codes=s},{}],56:[function(e,t,n){(function(n){(function(){var r=Object.keys||function(e){var t=[];for(var n in e)t.push(n);return t};t.exports=l;var s=e("./_stream_readable"),a=e("./_stream_writable");e("inherits")(l,s);for(var o=r(a.prototype),i=0;i<o.length;i++){var c=o[i];l.prototype[c]||(l.prototype[c]=a.prototype[c])}function l(e){if(!(this instanceof l))return new l(e);s.call(this,e),a.call(this,e),this.allowHalfOpen=!0,e&&(!1===e.readable&&(this.readable=!1),!1===e.writable&&(this.writable=!1),!1===e.allowHalfOpen&&(this.allowHalfOpen=!1,this.once("end",d)))}function d(){this._writableState.ended||n.nextTick(u,this)}function u(e){e.end()}Object.defineProperty(l.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),Object.defineProperty(l.prototype,"writableBuffer",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}}),Object.defineProperty(l.prototype,"writableLength",{enumerable:!1,get:function(){return this._writableState.length}}),Object.defineProperty(l.prototype,"destroyed",{enumerable:!1,get:function(){return void 0!==this._readableState&&void 0!==this._writableState&&this._readableState.destroyed&&this._writableState.destroyed},set:function(e){void 0!==this._readableState&&void 0!==this._writableState&&(this._readableState.destroyed=e,this._writableState.destroyed=e)}})}).call(this)}).call(this,e("_process"))},{"./_stream_readable":58,"./_stream_writable":60,_process:50,inherits:24}],57:[function(e,t,n){t.exports=s;var r=e("./_stream_transform");function s(e){if(!(this instanceof s))return new s(e);r.call(this,e)}e("inherits")(s,r),s.prototype._transform=function(e,t,n){n(null,e)}},{"./_stream_transform":59,inherits:24}],58:[function(e,t,n){(function(n,r){(function(){var s;t.exports=A,A.ReadableState=O,e("events").EventEmitter;var a=function(e,t){return e.listeners(t).length},o=e("./internal/streams/stream"),i=e("buffer").Buffer,c=r.Uint8Array||function(){};function l(e){return i.from(e)}function d(e){return i.isBuffer(e)||e instanceof c}var u,h=e("util");u=h&&h.debuglog?h.debuglog("stream"):function(){};var p,f,m,g=e("./internal/streams/buffer_list"),y=e("./internal/streams/destroy"),v=e("./internal/streams/state").getHighWaterMark,b=e("../errors").codes,w=b.ERR_INVALID_ARG_TYPE,C=b.ERR_STREAM_PUSH_AFTER_EOF,I=b.ERR_METHOD_NOT_IMPLEMENTED,S=b.ERR_STREAM_UNSHIFT_AFTER_END_EVENT;e("inherits")(A,o);var _=y.errorOrDestroy,k=["error","close","destroy","pause","resume"];function T(e,t,n){if("function"==typeof e.prependListener)return e.prependListener(t,n);e._events&&e._events[t]?Array.isArray(e._events[t])?e._events[t].unshift(n):e._events[t]=[n,e._events[t]]:e.on(t,n)}function O(t,n,r){s=s||e("./_stream_duplex"),t=t||{},"boolean"!=typeof r&&(r=n instanceof s),this.objectMode=!!t.objectMode,r&&(this.objectMode=this.objectMode||!!t.readableObjectMode),this.highWaterMark=v(this,t,"readableHighWaterMark",r),this.buffer=new g,this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=null,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.resumeScheduled=!1,this.paused=!0,this.emitClose=!1!==t.emitClose,this.autoDestroy=!!t.autoDestroy,this.destroyed=!1,this.defaultEncoding=t.defaultEncoding||"utf8",this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,t.encoding&&(p||(p=e("string_decoder/").StringDecoder),this.decoder=new p(t.encoding),this.encoding=t.encoding)}function A(t){if(s=s||e("./_stream_duplex"),!(this instanceof A))return new A(t);var n=this instanceof s;this._readableState=new O(t,this,n),this.readable=!0,t&&("function"==typeof t.read&&(this._read=t.read),"function"==typeof t.destroy&&(this._destroy=t.destroy)),o.call(this)}function E(e,t,n,r,s){u("readableAddChunk",t);var a,o=e._readableState;if(null===t)o.reading=!1,x(e,o);else if(s||(a=R(o,t)),a)_(e,a);else if(o.objectMode||t&&t.length>0)if("string"==typeof t||o.objectMode||Object.getPrototypeOf(t)===i.prototype||(t=l(t)),r)o.endEmitted?_(e,new S):M(e,o,t,!0);else if(o.ended)_(e,new C);else{if(o.destroyed)return!1;o.reading=!1,o.decoder&&!n?(t=o.decoder.write(t),o.objectMode||0!==t.length?M(e,o,t,!1):B(e,o)):M(e,o,t,!1)}else r||(o.reading=!1,B(e,o));return!o.ended&&(o.length<o.highWaterMark||0===o.length)}function M(e,t,n,r){t.flowing&&0===t.length&&!t.sync?(t.awaitDrain=0,e.emit("data",n)):(t.length+=t.objectMode?1:n.length,r?t.buffer.unshift(n):t.buffer.push(n),t.needReadable&&D(e)),B(e,t)}function R(e,t){var n;return d(t)||"string"==typeof t||void 0===t||e.objectMode||(n=new w("chunk",["string","Buffer","Uint8Array"],t)),n}Object.defineProperty(A.prototype,"destroyed",{enumerable:!1,get:function(){return void 0!==this._readableState&&this._readableState.destroyed},set:function(e){this._readableState&&(this._readableState.destroyed=e)}}),A.prototype.destroy=y.destroy,A.prototype._undestroy=y.undestroy,A.prototype._destroy=function(e,t){t(e)},A.prototype.push=function(e,t){var n,r=this._readableState;return r.objectMode?n=!0:"string"==typeof e&&((t=t||r.defaultEncoding)!==r.encoding&&(e=i.from(e,t),t=""),n=!0),E(this,e,t,!1,n)},A.prototype.unshift=function(e){return E(this,e,null,!0,!1)},A.prototype.isPaused=function(){return!1===this._readableState.flowing},A.prototype.setEncoding=function(t){p||(p=e("string_decoder/").StringDecoder);var n=new p(t);this._readableState.decoder=n,this._readableState.encoding=this._readableState.decoder.encoding;for(var r=this._readableState.buffer.head,s="";null!==r;)s+=n.write(r.data),r=r.next;return this._readableState.buffer.clear(),""!==s&&this._readableState.buffer.push(s),this._readableState.length=s.length,this};var P=1073741824;function j(e){return e>=P?e=P:(e--,e|=e>>>1,e|=e>>>2,e|=e>>>4,e|=e>>>8,e|=e>>>16,e++),e}function U(e,t){return e<=0||0===t.length&&t.ended?0:t.objectMode?1:e!=e?t.flowing&&t.length?t.buffer.head.data.length:t.length:(e>t.highWaterMark&&(t.highWaterMark=j(e)),e<=t.length?e:t.ended?t.length:(t.needReadable=!0,0))}function x(e,t){if(u("onEofChunk"),!t.ended){if(t.decoder){var n=t.decoder.end();n&&n.length&&(t.buffer.push(n),t.length+=t.objectMode?1:n.length)}t.ended=!0,t.sync?D(e):(t.needReadable=!1,t.emittedReadable||(t.emittedReadable=!0,N(e)))}}function D(e){var t=e._readableState;u("emitReadable",t.needReadable,t.emittedReadable),t.needReadable=!1,t.emittedReadable||(u("emitReadable",t.flowing),t.emittedReadable=!0,n.nextTick(N,e))}function N(e){var t=e._readableState;u("emitReadable_",t.destroyed,t.length,t.ended),t.destroyed||!t.length&&!t.ended||(e.emit("readable"),t.emittedReadable=!1),t.needReadable=!t.flowing&&!t.ended&&t.length<=t.highWaterMark,Q(e)}function B(e,t){t.readingMore||(t.readingMore=!0,n.nextTick(q,e,t))}function q(e,t){for(;!t.reading&&!t.ended&&(t.length<t.highWaterMark||t.flowing&&0===t.length);){var n=t.length;if(u("maybeReadMore read 0"),e.read(0),n===t.length)break}t.readingMore=!1}function F(e){return function(){var t=e._readableState;u("pipeOnDrain",t.awaitDrain),t.awaitDrain&&t.awaitDrain--,0===t.awaitDrain&&a(e,"data")&&(t.flowing=!0,Q(e))}}function L(e){var t=e._readableState;t.readableListening=e.listenerCount("readable")>0,t.resumeScheduled&&!t.paused?t.flowing=!0:e.listenerCount("data")>0&&e.resume()}function K(e){u("readable nexttick read 0"),e.read(0)}function $(e,t){t.resumeScheduled||(t.resumeScheduled=!0,n.nextTick(z,e,t))}function z(e,t){u("resume",t.reading),t.reading||e.read(0),t.resumeScheduled=!1,e.emit("resume"),Q(e),t.flowing&&!t.reading&&e.read(0)}function Q(e){var t=e._readableState;for(u("flow",t.flowing);t.flowing&&null!==e.read(););}function V(e,t){return 0===t.length?null:(t.objectMode?n=t.buffer.shift():!e||e>=t.length?(n=t.decoder?t.buffer.join(""):1===t.buffer.length?t.buffer.first():t.buffer.concat(t.length),t.buffer.clear()):n=t.buffer.consume(e,t.decoder),n);var n}function H(e){var t=e._readableState;u("endReadable",t.endEmitted),t.endEmitted||(t.ended=!0,n.nextTick(W,t,e))}function W(e,t){if(u("endReadableNT",e.endEmitted,e.length),!e.endEmitted&&0===e.length&&(e.endEmitted=!0,t.readable=!1,t.emit("end"),e.autoDestroy)){var n=t._writableState;(!n||n.autoDestroy&&n.finished)&&t.destroy()}}function J(e,t){for(var n=0,r=e.length;n<r;n++)if(e[n]===t)return n;return-1}A.prototype.read=function(e){u("read",e),e=parseInt(e,10);var t=this._readableState,n=e;if(0!==e&&(t.emittedReadable=!1),0===e&&t.needReadable&&((0!==t.highWaterMark?t.length>=t.highWaterMark:t.length>0)||t.ended))return u("read: emitReadable",t.length,t.ended),0===t.length&&t.ended?H(this):D(this),null;if(0===(e=U(e,t))&&t.ended)return 0===t.length&&H(this),null;var r,s=t.needReadable;return u("need readable",s),(0===t.length||t.length-e<t.highWaterMark)&&u("length less than watermark",s=!0),t.ended||t.reading?u("reading or ended",s=!1):s&&(u("do read"),t.reading=!0,t.sync=!0,0===t.length&&(t.needReadable=!0),this._read(t.highWaterMark),t.sync=!1,t.reading||(e=U(n,t))),null===(r=e>0?V(e,t):null)?(t.needReadable=t.length<=t.highWaterMark,e=0):(t.length-=e,t.awaitDrain=0),0===t.length&&(t.ended||(t.needReadable=!0),n!==e&&t.ended&&H(this)),null!==r&&this.emit("data",r),r},A.prototype._read=function(e){_(this,new I("_read()"))},A.prototype.pipe=function(e,t){var r=this,s=this._readableState;switch(s.pipesCount){case 0:s.pipes=e;break;case 1:s.pipes=[s.pipes,e];break;default:s.pipes.push(e)}s.pipesCount+=1,u("pipe count=%d opts=%j",s.pipesCount,t);var o=t&&!1===t.end||e===n.stdout||e===n.stderr?y:c;function i(e,t){u("onunpipe"),e===r&&t&&!1===t.hasUnpiped&&(t.hasUnpiped=!0,h())}function c(){u("onend"),e.end()}s.endEmitted?n.nextTick(o):r.once("end",o),e.on("unpipe",i);var l=F(r);e.on("drain",l);var d=!1;function h(){u("cleanup"),e.removeListener("close",m),e.removeListener("finish",g),e.removeListener("drain",l),e.removeListener("error",f),e.removeListener("unpipe",i),r.removeListener("end",c),r.removeListener("end",y),r.removeListener("data",p),d=!0,!s.awaitDrain||e._writableState&&!e._writableState.needDrain||l()}function p(t){u("ondata");var n=e.write(t);u("dest.write",n),!1===n&&((1===s.pipesCount&&s.pipes===e||s.pipesCount>1&&-1!==J(s.pipes,e))&&!d&&(u("false write response, pause",s.awaitDrain),s.awaitDrain++),r.pause())}function f(t){u("onerror",t),y(),e.removeListener("error",f),0===a(e,"error")&&_(e,t)}function m(){e.removeListener("finish",g),y()}function g(){u("onfinish"),e.removeListener("close",m),y()}function y(){u("unpipe"),r.unpipe(e)}return r.on("data",p),T(e,"error",f),e.once("close",m),e.once("finish",g),e.emit("pipe",r),s.flowing||(u("pipe resume"),r.resume()),e},A.prototype.unpipe=function(e){var t=this._readableState,n={hasUnpiped:!1};if(0===t.pipesCount)return this;if(1===t.pipesCount)return e&&e!==t.pipes||(e||(e=t.pipes),t.pipes=null,t.pipesCount=0,t.flowing=!1,e&&e.emit("unpipe",this,n)),this;if(!e){var r=t.pipes,s=t.pipesCount;t.pipes=null,t.pipesCount=0,t.flowing=!1;for(var a=0;a<s;a++)r[a].emit("unpipe",this,{hasUnpiped:!1});return this}var o=J(t.pipes,e);return-1===o||(t.pipes.splice(o,1),t.pipesCount-=1,1===t.pipesCount&&(t.pipes=t.pipes[0]),e.emit("unpipe",this,n)),this},A.prototype.on=function(e,t){var r=o.prototype.on.call(this,e,t),s=this._readableState;return"data"===e?(s.readableListening=this.listenerCount("readable")>0,!1!==s.flowing&&this.resume()):"readable"===e&&(s.endEmitted||s.readableListening||(s.readableListening=s.needReadable=!0,s.flowing=!1,s.emittedReadable=!1,u("on readable",s.length,s.reading),s.length?D(this):s.reading||n.nextTick(K,this))),r},A.prototype.addListener=A.prototype.on,A.prototype.removeListener=function(e,t){var r=o.prototype.removeListener.call(this,e,t);return"readable"===e&&n.nextTick(L,this),r},A.prototype.removeAllListeners=function(e){var t=o.prototype.removeAllListeners.apply(this,arguments);return"readable"!==e&&void 0!==e||n.nextTick(L,this),t},A.prototype.resume=function(){var e=this._readableState;return e.flowing||(u("resume"),e.flowing=!e.readableListening,$(this,e)),e.paused=!1,this},A.prototype.pause=function(){return u("call pause flowing=%j",this._readableState.flowing),!1!==this._readableState.flowing&&(u("pause"),this._readableState.flowing=!1,this.emit("pause")),this._readableState.paused=!0,this},A.prototype.wrap=function(e){var t=this,n=this._readableState,r=!1;for(var s in e.on("end",(function(){if(u("wrapped end"),n.decoder&&!n.ended){var e=n.decoder.end();e&&e.length&&t.push(e)}t.push(null)})),e.on("data",(function(s){u("wrapped data"),n.decoder&&(s=n.decoder.write(s)),n.objectMode&&null==s||(n.objectMode||s&&s.length)&&(t.push(s)||(r=!0,e.pause()))})),e)void 0===this[s]&&"function"==typeof e[s]&&(this[s]=function(t){return function(){return e[t].apply(e,arguments)}}(s));for(var a=0;a<k.length;a++)e.on(k[a],this.emit.bind(this,k[a]));return this._read=function(t){u("wrapped _read",t),r&&(r=!1,e.resume())},this},"function"==typeof Symbol&&(A.prototype[Symbol.asyncIterator]=function(){return void 0===f&&(f=e("./internal/streams/async_iterator")),f(this)}),Object.defineProperty(A.prototype,"readableHighWaterMark",{enumerable:!1,get:function(){return this._readableState.highWaterMark}}),Object.defineProperty(A.prototype,"readableBuffer",{enumerable:!1,get:function(){return this._readableState&&this._readableState.buffer}}),Object.defineProperty(A.prototype,"readableFlowing",{enumerable:!1,get:function(){return this._readableState.flowing},set:function(e){this._readableState&&(this._readableState.flowing=e)}}),A._fromList=V,Object.defineProperty(A.prototype,"readableLength",{enumerable:!1,get:function(){return this._readableState.length}}),"function"==typeof Symbol&&(A.from=function(t,n){return void 0===m&&(m=e("./internal/streams/from")),m(A,t,n)})}).call(this)}).call(this,e("_process"),void 0!==At?At:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"../errors":55,"./_stream_duplex":56,"./internal/streams/async_iterator":61,"./internal/streams/buffer_list":62,"./internal/streams/destroy":63,"./internal/streams/from":65,"./internal/streams/state":67,"./internal/streams/stream":68,_process:50,buffer:17,events:22,inherits:24,"string_decoder/":75,util:16}],59:[function(e,t,n){t.exports=d;var r=e("../errors").codes,s=r.ERR_METHOD_NOT_IMPLEMENTED,a=r.ERR_MULTIPLE_CALLBACK,o=r.ERR_TRANSFORM_ALREADY_TRANSFORMING,i=r.ERR_TRANSFORM_WITH_LENGTH_0,c=e("./_stream_duplex");function l(e,t){var n=this._transformState;n.transforming=!1;var r=n.writecb;if(null===r)return this.emit("error",new a);n.writechunk=null,n.writecb=null,null!=t&&this.push(t),r(e);var s=this._readableState;s.reading=!1,(s.needReadable||s.length<s.highWaterMark)&&this._read(s.highWaterMark)}function d(e){if(!(this instanceof d))return new d(e);c.call(this,e),this._transformState={afterTransform:l.bind(this),needTransform:!1,transforming:!1,writecb:null,writechunk:null,writeencoding:null},this._readableState.needReadable=!0,this._readableState.sync=!1,e&&("function"==typeof e.transform&&(this._transform=e.transform),"function"==typeof e.flush&&(this._flush=e.flush)),this.on("prefinish",u)}function u(){var e=this;"function"!=typeof this._flush||this._readableState.destroyed?h(this,null,null):this._flush((function(t,n){h(e,t,n)}))}function h(e,t,n){if(t)return e.emit("error",t);if(null!=n&&e.push(n),e._writableState.length)throw new i;if(e._transformState.transforming)throw new o;return e.push(null)}e("inherits")(d,c),d.prototype.push=function(e,t){return this._transformState.needTransform=!1,c.prototype.push.call(this,e,t)},d.prototype._transform=function(e,t,n){n(new s("_transform()"))},d.prototype._write=function(e,t,n){var r=this._transformState;if(r.writecb=n,r.writechunk=e,r.writeencoding=t,!r.transforming){var s=this._readableState;(r.needTransform||s.needReadable||s.length<s.highWaterMark)&&this._read(s.highWaterMark)}},d.prototype._read=function(e){var t=this._transformState;null===t.writechunk||t.transforming?t.needTransform=!0:(t.transforming=!0,this._transform(t.writechunk,t.writeencoding,t.afterTransform))},d.prototype._destroy=function(e,t){c.prototype._destroy.call(this,e,(function(e){t(e)}))}},{"../errors":55,"./_stream_duplex":56,inherits:24}],60:[function(e,t,n){(function(n,r){(function(){function s(e){var t=this;this.next=null,this.entry=null,this.finish=function(){z(t,e)}}var a;t.exports=O,O.WritableState=T;var o={deprecate:e("util-deprecate")},i=e("./internal/streams/stream"),c=e("buffer").Buffer,l=r.Uint8Array||function(){};function d(e){return c.from(e)}function u(e){return c.isBuffer(e)||e instanceof l}var h,p=e("./internal/streams/destroy"),f=e("./internal/streams/state").getHighWaterMark,m=e("../errors").codes,g=m.ERR_INVALID_ARG_TYPE,y=m.ERR_METHOD_NOT_IMPLEMENTED,v=m.ERR_MULTIPLE_CALLBACK,b=m.ERR_STREAM_CANNOT_PIPE,w=m.ERR_STREAM_DESTROYED,C=m.ERR_STREAM_NULL_VALUES,I=m.ERR_STREAM_WRITE_AFTER_END,S=m.ERR_UNKNOWN_ENCODING,_=p.errorOrDestroy;function k(){}function T(t,n,r){a=a||e("./_stream_duplex"),t=t||{},"boolean"!=typeof r&&(r=n instanceof a),this.objectMode=!!t.objectMode,r&&(this.objectMode=this.objectMode||!!t.writableObjectMode),this.highWaterMark=f(this,t,"writableHighWaterMark",r),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;var o=!1===t.decodeStrings;this.decodeStrings=!o,this.defaultEncoding=t.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(e){x(n,e)},this.writecb=null,this.writelen=0,this.bufferedRequest=null,this.lastBufferedRequest=null,this.pendingcb=0,this.prefinished=!1,this.errorEmitted=!1,this.emitClose=!1!==t.emitClose,this.autoDestroy=!!t.autoDestroy,this.bufferedRequestCount=0,this.corkedRequestsFree=new s(this)}function O(t){var n=this instanceof(a=a||e("./_stream_duplex"));if(!n&&!h.call(O,this))return new O(t);this._writableState=new T(t,this,n),this.writable=!0,t&&("function"==typeof t.write&&(this._write=t.write),"function"==typeof t.writev&&(this._writev=t.writev),"function"==typeof t.destroy&&(this._destroy=t.destroy),"function"==typeof t.final&&(this._final=t.final)),i.call(this)}function A(e,t){var r=new I;_(e,r),n.nextTick(t,r)}function E(e,t,r,s){var a;return null===r?a=new C:"string"==typeof r||t.objectMode||(a=new g("chunk",["string","Buffer"],r)),!a||(_(e,a),n.nextTick(s,a),!1)}function M(e,t,n){return e.objectMode||!1===e.decodeStrings||"string"!=typeof t||(t=c.from(t,n)),t}function R(e,t,n,r,s,a){if(!n){var o=M(t,r,s);r!==o&&(n=!0,s="buffer",r=o)}var i=t.objectMode?1:r.length;t.length+=i;var c=t.length<t.highWaterMark;if(c||(t.needDrain=!0),t.writing||t.corked){var l=t.lastBufferedRequest;t.lastBufferedRequest={chunk:r,encoding:s,isBuf:n,callback:a,next:null},l?l.next=t.lastBufferedRequest:t.bufferedRequest=t.lastBufferedRequest,t.bufferedRequestCount+=1}else P(e,t,!1,i,r,s,a);return c}function P(e,t,n,r,s,a,o){t.writelen=r,t.writecb=o,t.writing=!0,t.sync=!0,t.destroyed?t.onwrite(new w("write")):n?e._writev(s,t.onwrite):e._write(s,a,t.onwrite),t.sync=!1}function j(e,t,r,s,a){--t.pendingcb,r?(n.nextTick(a,s),n.nextTick(K,e,t),e._writableState.errorEmitted=!0,_(e,s)):(a(s),e._writableState.errorEmitted=!0,_(e,s),K(e,t))}function U(e){e.writing=!1,e.writecb=null,e.length-=e.writelen,e.writelen=0}function x(e,t){var r=e._writableState,s=r.sync,a=r.writecb;if("function"!=typeof a)throw new v;if(U(r),t)j(e,r,s,t,a);else{var o=q(r)||e.destroyed;o||r.corked||r.bufferProcessing||!r.bufferedRequest||B(e,r),s?n.nextTick(D,e,r,o,a):D(e,r,o,a)}}function D(e,t,n,r){n||N(e,t),t.pendingcb--,r(),K(e,t)}function N(e,t){0===t.length&&t.needDrain&&(t.needDrain=!1,e.emit("drain"))}function B(e,t){t.bufferProcessing=!0;var n=t.bufferedRequest;if(e._writev&&n&&n.next){var r=t.bufferedRequestCount,a=new Array(r),o=t.corkedRequestsFree;o.entry=n;for(var i=0,c=!0;n;)a[i]=n,n.isBuf||(c=!1),n=n.next,i+=1;a.allBuffers=c,P(e,t,!0,t.length,a,"",o.finish),t.pendingcb++,t.lastBufferedRequest=null,o.next?(t.corkedRequestsFree=o.next,o.next=null):t.corkedRequestsFree=new s(t),t.bufferedRequestCount=0}else{for(;n;){var l=n.chunk,d=n.encoding,u=n.callback;if(P(e,t,!1,t.objectMode?1:l.length,l,d,u),n=n.next,t.bufferedRequestCount--,t.writing)break}null===n&&(t.lastBufferedRequest=null)}t.bufferedRequest=n,t.bufferProcessing=!1}function q(e){return e.ending&&0===e.length&&null===e.bufferedRequest&&!e.finished&&!e.writing}function F(e,t){e._final((function(n){t.pendingcb--,n&&_(e,n),t.prefinished=!0,e.emit("prefinish"),K(e,t)}))}function L(e,t){t.prefinished||t.finalCalled||("function"!=typeof e._final||t.destroyed?(t.prefinished=!0,e.emit("prefinish")):(t.pendingcb++,t.finalCalled=!0,n.nextTick(F,e,t)))}function K(e,t){var n=q(t);if(n&&(L(e,t),0===t.pendingcb&&(t.finished=!0,e.emit("finish"),t.autoDestroy))){var r=e._readableState;(!r||r.autoDestroy&&r.endEmitted)&&e.destroy()}return n}function $(e,t,r){t.ending=!0,K(e,t),r&&(t.finished?n.nextTick(r):e.once("finish",r)),t.ended=!0,e.writable=!1}function z(e,t,n){var r=e.entry;for(e.entry=null;r;){var s=r.callback;t.pendingcb--,s(n),r=r.next}t.corkedRequestsFree.next=e}e("inherits")(O,i),T.prototype.getBuffer=function(){for(var e=this.bufferedRequest,t=[];e;)t.push(e),e=e.next;return t},function(){try{Object.defineProperty(T.prototype,"buffer",{get:o.deprecate((function(){return this.getBuffer()}),"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.","DEP0003")})}catch(e){}}(),"function"==typeof Symbol&&Symbol.hasInstance&&"function"==typeof Function.prototype[Symbol.hasInstance]?(h=Function.prototype[Symbol.hasInstance],Object.defineProperty(O,Symbol.hasInstance,{value:function(e){return!!h.call(this,e)||this===O&&e&&e._writableState instanceof T}})):h=function(e){return e instanceof this},O.prototype.pipe=function(){_(this,new b)},O.prototype.write=function(e,t,n){var r=this._writableState,s=!1,a=!r.objectMode&&u(e);return a&&!c.isBuffer(e)&&(e=d(e)),"function"==typeof t&&(n=t,t=null),a?t="buffer":t||(t=r.defaultEncoding),"function"!=typeof n&&(n=k),r.ending?A(this,n):(a||E(this,r,e,n))&&(r.pendingcb++,s=R(this,r,a,e,t,n)),s},O.prototype.cork=function(){this._writableState.corked++},O.prototype.uncork=function(){var e=this._writableState;e.corked&&(e.corked--,e.writing||e.corked||e.bufferProcessing||!e.bufferedRequest||B(this,e))},O.prototype.setDefaultEncoding=function(e){if("string"==typeof e&&(e=e.toLowerCase()),!(["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((e+"").toLowerCase())>-1))throw new S(e);return this._writableState.defaultEncoding=e,this},Object.defineProperty(O.prototype,"writableBuffer",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}}),Object.defineProperty(O.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),O.prototype._write=function(e,t,n){n(new y("_write()"))},O.prototype._writev=null,O.prototype.end=function(e,t,n){var r=this._writableState;return"function"==typeof e?(n=e,e=null,t=null):"function"==typeof t&&(n=t,t=null),null!=e&&this.write(e,t),r.corked&&(r.corked=1,this.uncork()),r.ending||$(this,r,n),this},Object.defineProperty(O.prototype,"writableLength",{enumerable:!1,get:function(){return this._writableState.length}}),Object.defineProperty(O.prototype,"destroyed",{enumerable:!1,get:function(){return void 0!==this._writableState&&this._writableState.destroyed},set:function(e){this._writableState&&(this._writableState.destroyed=e)}}),O.prototype.destroy=p.destroy,O.prototype._undestroy=p.undestroy,O.prototype._destroy=function(e,t){t(e)}}).call(this)}).call(this,e("_process"),void 0!==At?At:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"../errors":55,"./_stream_duplex":56,"./internal/streams/destroy":63,"./internal/streams/state":67,"./internal/streams/stream":68,_process:50,buffer:17,inherits:24,"util-deprecate":78}],61:[function(e,t,n){(function(n){(function(){var r;function s(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}var a=e("./end-of-stream"),o=Symbol("lastResolve"),i=Symbol("lastReject"),c=Symbol("error"),l=Symbol("ended"),d=Symbol("lastPromise"),u=Symbol("handlePromise"),h=Symbol("stream");function p(e,t){return{value:e,done:t}}function f(e){var t=e[o];if(null!==t){var n=e[h].read();null!==n&&(e[d]=null,e[o]=null,e[i]=null,t(p(n,!1)))}}function m(e){n.nextTick(f,e)}function g(e,t){return function(n,r){e.then((function(){t[l]?n(p(void 0,!0)):t[u](n,r)}),r)}}var y=Object.getPrototypeOf((function(){})),v=Object.setPrototypeOf((s(r={get stream(){return this[h]},next:function(){var e=this,t=this[c];if(null!==t)return Promise.reject(t);if(this[l])return Promise.resolve(p(void 0,!0));if(this[h].destroyed)return new Promise((function(t,r){n.nextTick((function(){e[c]?r(e[c]):t(p(void 0,!0))}))}));var r,s=this[d];if(s)r=new Promise(g(s,this));else{var a=this[h].read();if(null!==a)return Promise.resolve(p(a,!1));r=new Promise(this[u])}return this[d]=r,r}},Symbol.asyncIterator,(function(){return this})),s(r,"return",(function(){var e=this;return new Promise((function(t,n){e[h].destroy(null,(function(e){e?n(e):t(p(void 0,!0))}))}))})),r),y),b=function(e){var t,n=Object.create(v,(s(t={},h,{value:e,writable:!0}),s(t,o,{value:null,writable:!0}),s(t,i,{value:null,writable:!0}),s(t,c,{value:null,writable:!0}),s(t,l,{value:e._readableState.endEmitted,writable:!0}),s(t,u,{value:function(e,t){var r=n[h].read();r?(n[d]=null,n[o]=null,n[i]=null,e(p(r,!1))):(n[o]=e,n[i]=t)},writable:!0}),t));return n[d]=null,a(e,(function(e){if(e&&"ERR_STREAM_PREMATURE_CLOSE"!==e.code){var t=n[i];return null!==t&&(n[d]=null,n[o]=null,n[i]=null,t(e)),void(n[c]=e)}var r=n[o];null!==r&&(n[d]=null,n[o]=null,n[i]=null,r(p(void 0,!0))),n[l]=!0})),e.on("readable",m.bind(null,n)),n};t.exports=b}).call(this)}).call(this,e("_process"))},{"./end-of-stream":64,_process:50}],62:[function(e,t,n){function r(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function s(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?r(Object(n),!0).forEach((function(t){a(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):r(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}function a(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}function c(e,t,n){return t&&i(e.prototype,t),n&&i(e,n),e}var l=e("buffer").Buffer,d=e("util").inspect,u=d&&d.custom||"inspect";function h(e,t,n){l.prototype.copy.call(e,t,n)}t.exports=function(){function e(){o(this,e),this.head=null,this.tail=null,this.length=0}return c(e,[{key:"push",value:function(e){var t={data:e,next:null};this.length>0?this.tail.next=t:this.head=t,this.tail=t,++this.length}},{key:"unshift",value:function(e){var t={data:e,next:this.head};0===this.length&&(this.tail=t),this.head=t,++this.length}},{key:"shift",value:function(){if(0!==this.length){var e=this.head.data;return 1===this.length?this.head=this.tail=null:this.head=this.head.next,--this.length,e}}},{key:"clear",value:function(){this.head=this.tail=null,this.length=0}},{key:"join",value:function(e){if(0===this.length)return"";for(var t=this.head,n=""+t.data;t=t.next;)n+=e+t.data;return n}},{key:"concat",value:function(e){if(0===this.length)return l.alloc(0);for(var t=l.allocUnsafe(e>>>0),n=this.head,r=0;n;)h(n.data,t,r),r+=n.data.length,n=n.next;return t}},{key:"consume",value:function(e,t){var n;return e<this.head.data.length?(n=this.head.data.slice(0,e),this.head.data=this.head.data.slice(e)):n=e===this.head.data.length?this.shift():t?this._getString(e):this._getBuffer(e),n}},{key:"first",value:function(){return this.head.data}},{key:"_getString",value:function(e){var t=this.head,n=1,r=t.data;for(e-=r.length;t=t.next;){var s=t.data,a=e>s.length?s.length:e;if(a===s.length?r+=s:r+=s.slice(0,e),0==(e-=a)){a===s.length?(++n,t.next?this.head=t.next:this.head=this.tail=null):(this.head=t,t.data=s.slice(a));break}++n}return this.length-=n,r}},{key:"_getBuffer",value:function(e){var t=l.allocUnsafe(e),n=this.head,r=1;for(n.data.copy(t),e-=n.data.length;n=n.next;){var s=n.data,a=e>s.length?s.length:e;if(s.copy(t,t.length-e,0,a),0==(e-=a)){a===s.length?(++r,n.next?this.head=n.next:this.head=this.tail=null):(this.head=n,n.data=s.slice(a));break}++r}return this.length-=r,t}},{key:u,value:function(e,t){return d(this,s({},t,{depth:0,customInspect:!1}))}}]),e}()},{buffer:17,util:16}],63:[function(e,t,n){(function(e){(function(){function n(t,n){var a=this,i=this._readableState&&this._readableState.destroyed,c=this._writableState&&this._writableState.destroyed;return i||c?(n?n(t):t&&(this._writableState?this._writableState.errorEmitted||(this._writableState.errorEmitted=!0,e.nextTick(o,this,t)):e.nextTick(o,this,t)),this):(this._readableState&&(this._readableState.destroyed=!0),this._writableState&&(this._writableState.destroyed=!0),this._destroy(t||null,(function(t){!n&&t?a._writableState?a._writableState.errorEmitted?e.nextTick(s,a):(a._writableState.errorEmitted=!0,e.nextTick(r,a,t)):e.nextTick(r,a,t):n?(e.nextTick(s,a),n(t)):e.nextTick(s,a)})),this)}function r(e,t){o(e,t),s(e)}function s(e){e._writableState&&!e._writableState.emitClose||e._readableState&&!e._readableState.emitClose||e.emit("close")}function a(){this._readableState&&(this._readableState.destroyed=!1,this._readableState.reading=!1,this._readableState.ended=!1,this._readableState.endEmitted=!1),this._writableState&&(this._writableState.destroyed=!1,this._writableState.ended=!1,this._writableState.ending=!1,this._writableState.finalCalled=!1,this._writableState.prefinished=!1,this._writableState.finished=!1,this._writableState.errorEmitted=!1)}function o(e,t){e.emit("error",t)}function i(e,t){var n=e._readableState,r=e._writableState;n&&n.autoDestroy||r&&r.autoDestroy?e.destroy(t):e.emit("error",t)}t.exports={destroy:n,undestroy:a,errorOrDestroy:i}}).call(this)}).call(this,e("_process"))},{_process:50}],64:[function(e,t,n){var r=e("../../../errors").codes.ERR_STREAM_PREMATURE_CLOSE;function s(e){var t=!1;return function(){if(!t){t=!0;for(var n=arguments.length,r=new Array(n),s=0;s<n;s++)r[s]=arguments[s];e.apply(this,r)}}}function a(){}function o(e){return e.setHeader&&"function"==typeof e.abort}function i(e,t,n){if("function"==typeof t)return i(e,null,t);t||(t={}),n=s(n||a);var c=t.readable||!1!==t.readable&&e.readable,l=t.writable||!1!==t.writable&&e.writable,d=function(){e.writable||h()},u=e._writableState&&e._writableState.finished,h=function(){l=!1,u=!0,c||n.call(e)},p=e._readableState&&e._readableState.endEmitted,f=function(){c=!1,p=!0,l||n.call(e)},m=function(t){n.call(e,t)},g=function(){var t;return c&&!p?(e._readableState&&e._readableState.ended||(t=new r),n.call(e,t)):l&&!u?(e._writableState&&e._writableState.ended||(t=new r),n.call(e,t)):void 0},y=function(){e.req.on("finish",h)};return o(e)?(e.on("complete",h),e.on("abort",g),e.req?y():e.on("request",y)):l&&!e._writableState&&(e.on("end",d),e.on("close",d)),e.on("end",f),e.on("finish",h),!1!==t.error&&e.on("error",m),e.on("close",g),function(){e.removeListener("complete",h),e.removeListener("abort",g),e.removeListener("request",y),e.req&&e.req.removeListener("finish",h),e.removeListener("end",d),e.removeListener("close",d),e.removeListener("finish",h),e.removeListener("end",f),e.removeListener("error",m),e.removeListener("close",g)}}t.exports=i},{"../../../errors":55}],65:[function(e,t,n){t.exports=function(){throw new Error("Readable.from is not available in the browser")}},{}],66:[function(e,t,n){var r;function s(e){var t=!1;return function(){t||(t=!0,e.apply(void 0,arguments))}}var a=e("../../../errors").codes,o=a.ERR_MISSING_ARGS,i=a.ERR_STREAM_DESTROYED;function c(e){if(e)throw e}function l(e){return e.setHeader&&"function"==typeof e.abort}function d(t,n,a,o){o=s(o);var c=!1;t.on("close",(function(){c=!0})),void 0===r&&(r=e("./end-of-stream")),r(t,{readable:n,writable:a},(function(e){if(e)return o(e);c=!0,o()}));var d=!1;return function(e){if(!c&&!d)return d=!0,l(t)?t.abort():"function"==typeof t.destroy?t.destroy():void o(e||new i("pipe"))}}function u(e){e()}function h(e,t){return e.pipe(t)}function p(e){return e.length?"function"!=typeof e[e.length-1]?c:e.pop():c}function f(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];var r,s=p(t);if(Array.isArray(t[0])&&(t=t[0]),t.length<2)throw new o("streams");var a=t.map((function(e,n){var o=n<t.length-1;return d(e,o,n>0,(function(e){r||(r=e),e&&a.forEach(u),o||(a.forEach(u),s(r))}))}));return t.reduce(h)}t.exports=f},{"../../../errors":55,"./end-of-stream":64}],67:[function(e,t,n){var r=e("../../../errors").codes.ERR_INVALID_OPT_VALUE;function s(e,t,n){return null!=e.highWaterMark?e.highWaterMark:t?e[n]:null}function a(e,t,n,a){var o=s(t,a,n);if(null!=o){if(!isFinite(o)||Math.floor(o)!==o||o<0)throw new r(a?n:"highWaterMark",o);return Math.floor(o)}return e.objectMode?16:16384}t.exports={getHighWaterMark:a}},{"../../../errors":55}],68:[function(e,t,n){t.exports=e("events").EventEmitter},{events:22}],69:[function(e,t,n){(n=t.exports=e("./lib/_stream_readable.js")).Stream=n,n.Readable=n,n.Writable=e("./lib/_stream_writable.js"),n.Duplex=e("./lib/_stream_duplex.js"),n.Transform=e("./lib/_stream_transform.js"),n.PassThrough=e("./lib/_stream_passthrough.js"),n.finished=e("./lib/internal/streams/end-of-stream.js"),n.pipeline=e("./lib/internal/streams/pipeline.js")},{"./lib/_stream_duplex.js":56,"./lib/_stream_passthrough.js":57,"./lib/_stream_readable.js":58,"./lib/_stream_transform.js":59,"./lib/_stream_writable.js":60,"./lib/internal/streams/end-of-stream.js":64,"./lib/internal/streams/pipeline.js":66}],70:[function(e,t,n){function r(e,t,n){var r=this;this._callback=e,this._args=n,this._interval=setInterval(e,t,this._args),this.reschedule=function(e){e||(e=r._interval),r._interval&&clearInterval(r._interval),r._interval=setInterval(r._callback,e,r._args)},this.clear=function(){r._interval&&(clearInterval(r._interval),r._interval=void 0)},this.destroy=function(){r._interval&&clearInterval(r._interval),r._callback=void 0,r._interval=void 0,r._args=void 0}}function s(){if("function"!=typeof arguments[0])throw new Error("callback needed");if("number"!=typeof arguments[1])throw new Error("interval needed");var e;if(arguments.length>0){e=new Array(arguments.length-2);for(var t=0;t<e.length;t++)e[t]=arguments[t+2]}return new r(arguments[0],arguments[1],e)}t.exports=s},{}],71:[function(e,t,n){t.exports=e("./index.js")()},{"./index.js":72}],72:[function(e,t,n){(function(e){(function(){function n(t){return t instanceof e?e.from(t):new t.constructor(t.buffer.slice(),t.byteOffset,t.length)}function r(e){return(e=e||{}).circles?s(e):e.proto?a:r;function t(e,t){for(var r=Object.keys(e),s=new Array(r.length),a=0;a<r.length;a++){var o=r[a],i=e[o];"object"!=typeof i||null===i?s[o]=i:i instanceof Date?s[o]=new Date(i):ArrayBuffer.isView(i)?s[o]=n(i):s[o]=t(i)}return s}function r(e){if("object"!=typeof e||null===e)return e;if(e instanceof Date)return new Date(e);if(Array.isArray(e))return t(e,r);if(e instanceof Map)return new Map(t(Array.from(e),r));if(e instanceof Set)return new Set(t(Array.from(e),r));var s={};for(var a in e)if(!1!==Object.hasOwnProperty.call(e,a)){var o=e[a];"object"!=typeof o||null===o?s[a]=o:o instanceof Date?s[a]=new Date(o):o instanceof Map?s[a]=new Map(t(Array.from(o),r)):o instanceof Set?s[a]=new Set(t(Array.from(o),r)):ArrayBuffer.isView(o)?s[a]=n(o):s[a]=r(o)}return s}function a(e){if("object"!=typeof e||null===e)return e;if(e instanceof Date)return new Date(e);if(Array.isArray(e))return t(e,a);if(e instanceof Map)return new Map(t(Array.from(e),a));if(e instanceof Set)return new Set(t(Array.from(e),a));var r={};for(var s in e){var o=e[s];"object"!=typeof o||null===o?r[s]=o:o instanceof Date?r[s]=new Date(o):o instanceof Map?r[s]=new Map(t(Array.from(o),a)):o instanceof Set?r[s]=new Set(t(Array.from(o),a)):ArrayBuffer.isView(o)?r[s]=n(o):r[s]=a(o)}return r}}function s(e){var t=[],r=[];return e.proto?o:a;function s(e,s){for(var a=Object.keys(e),o=new Array(a.length),i=0;i<a.length;i++){var c=a[i],l=e[c];if("object"!=typeof l||null===l)o[c]=l;else if(l instanceof Date)o[c]=new Date(l);else if(ArrayBuffer.isView(l))o[c]=n(l);else{var d=t.indexOf(l);o[c]=-1!==d?r[d]:s(l)}}return o}function a(e){if("object"!=typeof e||null===e)return e;if(e instanceof Date)return new Date(e);if(Array.isArray(e))return s(e,a);if(e instanceof Map)return new Map(s(Array.from(e),a));if(e instanceof Set)return new Set(s(Array.from(e),a));var o={};for(var i in t.push(e),r.push(o),e)if(!1!==Object.hasOwnProperty.call(e,i)){var c=e[i];if("object"!=typeof c||null===c)o[i]=c;else if(c instanceof Date)o[i]=new Date(c);else if(c instanceof Map)o[i]=new Map(s(Array.from(c),a));else if(c instanceof Set)o[i]=new Set(s(Array.from(c),a));else if(ArrayBuffer.isView(c))o[i]=n(c);else{var l=t.indexOf(c);o[i]=-1!==l?r[l]:a(c)}}return t.pop(),r.pop(),o}function o(e){if("object"!=typeof e||null===e)return e;if(e instanceof Date)return new Date(e);if(Array.isArray(e))return s(e,o);if(e instanceof Map)return new Map(s(Array.from(e),o));if(e instanceof Set)return new Set(s(Array.from(e),o));var a={};for(var i in t.push(e),r.push(a),e){var c=e[i];if("object"!=typeof c||null===c)a[i]=c;else if(c instanceof Date)a[i]=new Date(c);else if(c instanceof Map)a[i]=new Map(s(Array.from(c),o));else if(c instanceof Set)a[i]=new Set(s(Array.from(c),o));else if(ArrayBuffer.isView(c))a[i]=n(c);else{var l=t.indexOf(c);a[i]=-1!==l?r[l]:o(c)}}return t.pop(),r.pop(),a}}t.exports=r}).call(this)}).call(this,e("buffer").Buffer)},{buffer:17}],73:[function(e,t,n){
3
+ n.read=function(e,t,n,r,a){var s,o,i=8*a-r-1,c=(1<<i)-1,l=c>>1,d=-7,u=n?a-1:0,h=n?-1:1,p=e[t+u];for(u+=h,s=p&(1<<-d)-1,p>>=-d,d+=i;d>0;s=256*s+e[t+u],u+=h,d-=8);for(o=s&(1<<-d)-1,s>>=-d,d+=r;d>0;o=256*o+e[t+u],u+=h,d-=8);if(0===s)s=1-l;else{if(s===c)return o?NaN:1/0*(p?-1:1);o+=Math.pow(2,r),s-=l}return(p?-1:1)*o*Math.pow(2,s-r)},n.write=function(e,t,n,r,a,s){var o,i,c,l=8*s-a-1,d=(1<<l)-1,u=d>>1,h=23===a?Math.pow(2,-24)-Math.pow(2,-77):0,p=r?0:s-1,f=r?1:-1,m=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(i=isNaN(t)?1:0,o=d):(o=Math.floor(Math.log(t)/Math.LN2),t*(c=Math.pow(2,-o))<1&&(o--,c*=2),(t+=o+u>=1?h/c:h*Math.pow(2,1-u))*c>=2&&(o++,c/=2),o+u>=d?(i=0,o=d):o+u>=1?(i=(t*c-1)*Math.pow(2,a),o+=u):(i=t*Math.pow(2,u-1)*Math.pow(2,a),o=0));a>=8;e[n+p]=255&i,p+=f,i/=256,a-=8);for(o=o<<a|i,l+=a;l>0;e[n+p]=255&o,p+=f,o/=256,l-=8);e[n+p-f]|=128*m}},{}],24:[function(e,t,n){"function"==typeof Object.create?t.exports=function(e,t){t&&(e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}))}:t.exports=function(e,t){if(t){e.super_=t;var n=function(){};n.prototype=t.prototype,e.prototype=new n,e.prototype.constructor=e}}},{}],25:[function(e,t,n){Object.defineProperty(n,"__esModule",{value:!0});var r=function(){function e(e,t){this.color=!0,this.key=void 0,this.value=void 0,this.parent=void 0,this.brother=void 0,this.leftChild=void 0,this.rightChild=void 0,this.key=e,this.value=t}return e.prototype.rotateLeft=function(){var e=this.parent,t=this.brother,n=this.leftChild,r=this.rightChild;if(!r)throw new Error("unknown error");var a=r.leftChild,s=r.rightChild;return e&&(e.leftChild===this?e.leftChild=r:e.rightChild===this&&(e.rightChild=r)),r.parent=e,r.brother=t,r.leftChild=this,r.rightChild=s,t&&(t.brother=r),this.parent=r,this.brother=s,this.leftChild=n,this.rightChild=a,s&&(s.parent=r,s.brother=this),n&&(n.parent=this,n.brother=a),a&&(a.parent=this,a.brother=n),r},e.prototype.rotateRight=function(){var e=this.parent,t=this.brother,n=this.leftChild;if(!n)throw new Error("unknown error");var r=this.rightChild,a=n.leftChild,s=n.rightChild;return e&&(e.leftChild===this?e.leftChild=n:e.rightChild===this&&(e.rightChild=n)),n.parent=e,n.brother=t,n.leftChild=a,n.rightChild=this,t&&(t.brother=n),a&&(a.parent=n,a.brother=this),this.parent=n,this.brother=a,this.leftChild=s,this.rightChild=r,s&&(s.parent=this,s.brother=r),r&&(r.parent=this,r.brother=s),n},e.prototype.remove=function(){if(this.leftChild||this.rightChild)throw new Error("can only remove leaf node");this.parent&&(this===this.parent.leftChild?this.parent.leftChild=void 0:this===this.parent.rightChild&&(this.parent.rightChild=void 0)),this.brother&&(this.brother.brother=void 0),this.key=void 0,this.value=void 0,this.parent=void 0,this.brother=void 0},e.TreeNodeColorType={red:!0,black:!1},e}();Object.freeze(r),n.default=r},{}],26:[function(e,t,n){var r=this&&this.__generator||function(e,t){var n,r,a,s,o={label:0,sent:function(){if(1&a[0])throw a[1];return a[1]},trys:[],ops:[]};return s={next:i(0),throw:i(1),return:i(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function i(e){return function(t){return c([e,t])}}function c(s){if(n)throw new TypeError("Generator is already executing.");for(;o;)try{if(n=1,r&&(a=2&s[0]?r.return:s[0]?r.throw||((a=r.return)&&a.call(r),0):r.next)&&!(a=a.call(r,s[1])).done)return a;switch(r=0,a&&(s=[2&s[0],a.value]),s[0]){case 0:case 1:a=s;break;case 4:return o.label++,{value:s[1],done:!1};case 5:o.label++,r=s[1],s=[0];continue;case 7:s=o.ops.pop(),o.trys.pop();continue;default:if(!((a=(a=o.trys).length>0&&a[a.length-1])||6!==s[0]&&2!==s[0])){o=0;continue}if(3===s[0]&&(!a||s[1]>a[0]&&s[1]<a[3])){o.label=s[1];break}if(6===s[0]&&o.label<a[1]){o.label=a[1],a=s;break}if(a&&o.label<a[2]){o.label=a[2],o.ops.push(s);break}a[2]&&o.ops.pop(),o.trys.pop();continue}s=t.call(e,o)}catch(e){s=[6,e],r=0}finally{n=a=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}};function a(e){var t=this;void 0===e&&(e=[]);var n=[],s=0,o=0,i=0,c=0,l=0,d=0;this.size=function(){return d},this.empty=function(){return 0===d},this.clear=function(){s=i=o=c=l=d=0,h.call(this,a.bucketSize),d=0},this.front=function(){return n[s][o]},this.back=function(){return n[i][c]},this.forEach=function(e){if(!this.empty()){var t=0;if(s!==i){for(l=o;l<a.bucketSize;++l)e(n[s][l],t++);for(l=s+1;l<i;++l)for(var r=0;r<a.bucketSize;++r)e(n[l][r],t++);for(l=0;l<=c;++l)e(n[i][l],t++)}else for(var l=o;l<=c;++l)e(n[s][l],t++)}};var u=function(e){var t=s*a.bucketSize+o,n=t+e,r=i*a.bucketSize+c;if(n<t||n>r)throw new Error("pos should more than 0 and less than queue's size");return{curNodeBucketIndex:Math.floor(n/a.bucketSize),curNodePointerIndex:n%a.bucketSize}};this.getElementByPos=function(e){var t=u(e),r=t.curNodeBucketIndex,a=t.curNodePointerIndex;return n[r][a]},this.eraseElementByPos=function(e){var t=this;if(e<0||e>d)throw new Error("pos should more than 0 and less than queue's size");if(0===e)this.popFront();else if(e===this.size())this.popBack();else{for(var n=[],r=e+1;r<d;++r)n.push(this.getElementByPos(r));this.cut(e),this.popBack(),n.forEach((function(e){return t.pushBack(e)}))}},this.eraseElementByValue=function(e){if(!this.empty()){var t=[];this.forEach((function(n){n!==e&&t.push(n)}));for(var n=t.length,r=0;r<n;++r)this.setElementByPos(r,t[r]);this.cut(n-1)}};var h=function(e){for(var t=[],r=e*a.sigma,u=Math.max(Math.ceil(r/a.bucketSize),2),h=0;h<u;++h)t.push(new Array(a.bucketSize));var p=Math.ceil(e/a.bucketSize),f=Math.floor(u/2)-Math.floor(p/2),m=f,g=0;if(this.size())for(h=0;h<p;++h){for(var y=0;y<a.bucketSize;++y)if(t[f+h][y]=this.front(),this.popFront(),this.empty()){m=f+h,g=y;break}if(this.empty())break}n=t,s=f,o=0,i=m,c=g,l=u,d=e};this.pushBack=function(e){this.empty()||(i===l-1&&c===a.bucketSize-1&&h.call(this,this.size()),c<a.bucketSize-1?++c:i<l-1&&(++i,c=0)),++d,n[i][c]=e},this.popBack=function(){this.empty()||(1!==this.size()&&(c>0?--c:s<i&&(--i,c=a.bucketSize-1)),d>0&&--d)},this.setElementByPos=function(e,t){var r=u(e),a=r.curNodeBucketIndex,s=r.curNodePointerIndex;n[a][s]=t},this.insert=function(e,t,n){var r=this;if(void 0===n&&(n=1),0===e)for(;n--;)this.pushFront(t);else if(e===this.size())for(;n--;)this.pushBack(t);else{for(var a=[],s=e;s<d;++s)a.push(this.getElementByPos(s));for(this.cut(e-1),s=0;s<n;++s)this.pushBack(t);a.forEach((function(e){return r.pushBack(e)}))}},this.find=function(e){if(s===i){for(var t=o;t<=c;++t)if(n[s][t]===e)return!0;return!1}for(t=o;t<a.bucketSize;++t)if(n[s][t]===e)return!0;for(t=s+1;t<i;++t)for(var r=0;r<a.bucketSize;++r)if(n[t][r]===e)return!0;for(t=0;t<=c;++t)if(n[i][t]===e)return!0;return!1},this.reverse=function(){for(var e=0,t=d-1;e<t;){var n=this.getElementByPos(e);this.setElementByPos(e,this.getElementByPos(t)),this.setElementByPos(t,n),++e,--t}},this.unique=function(){if(!this.empty()){var e=[],t=this.front();this.forEach((function(n,r){0!==r&&n===t||(e.push(n),t=n)}));for(var n=0;n<d;++n)this.setElementByPos(n,e[n]);this.cut(e.length-1)}},this.sort=function(e){var t=[];this.forEach((function(e){t.push(e)})),t.sort(e);for(var n=0;n<d;++n)this.setElementByPos(n,t[n])},this.pushFront=function(e){this.empty()||(0===s&&0===o&&h.call(this,this.size()),o>0?--o:s>0&&(--s,o=a.bucketSize-1)),++d,n[s][o]=e},this.popFront=function(){this.empty()||(1!==this.size()&&(o<a.bucketSize-1?++o:s<i&&(++s,o=0)),d>0&&--d)},this.shrinkToFit=function(){var e=this,t=[];this.forEach((function(e){t.push(e)}));var r=t.length;n=[];for(var s=Math.ceil(r/a.bucketSize),o=0;o<s;++o)n.push(new Array(a.bucketSize));this.clear(),t.forEach((function(t){return e.pushBack(t)}))},this.cut=function(e){if(e<0)this.clear();else{var t=u(e),n=t.curNodeBucketIndex,r=t.curNodePointerIndex;i=n,c=r,d=e+1}},this[Symbol.iterator]=function(){return function(){var e,t;return r(this,(function(r){switch(r.label){case 0:if(0===d)return[2];if(s!==i)return[3,5];t=o,r.label=1;case 1:return t<=c?[4,n[s][t]]:[3,4];case 2:r.sent(),r.label=3;case 3:return++t,[3,1];case 4:return[2];case 5:t=o,r.label=6;case 6:return t<a.bucketSize?[4,n[s][t]]:[3,9];case 7:r.sent(),r.label=8;case 8:return++t,[3,6];case 9:t=s+1,r.label=10;case 10:if(!(t<i))return[3,15];e=0,r.label=11;case 11:return e<a.bucketSize?[4,n[t][e]]:[3,14];case 12:r.sent(),r.label=13;case 13:return++e,[3,11];case 14:return++t,[3,10];case 15:t=0,r.label=16;case 16:return t<=c?[4,n[i][t]]:[3,19];case 17:r.sent(),r.label=18;case 18:return++t,[3,16];case 19:return[2]}}))}()},function(){var r=a.bucketSize;e.size?r=e.size():e.length&&(r=e.length);var o=r*a.sigma;l=Math.ceil(o/a.bucketSize),l=Math.max(l,3);for(var c=0;c<l;++c)n.push(new Array(a.bucketSize));var d=Math.ceil(r/a.bucketSize);s=Math.floor(l/2)-Math.floor(d/2),i=s,e.forEach((function(e){return t.pushBack(e)}))}(),Object.freeze(this)}Object.defineProperty(n,"__esModule",{value:!0}),a.sigma=3,a.bucketSize=5e3,Object.freeze(a),n.default=a},{}],27:[function(e,t,n){var r=this&&this.__generator||function(e,t){var n,r,a,s,o={label:0,sent:function(){if(1&a[0])throw a[1];return a[1]},trys:[],ops:[]};return s={next:i(0),throw:i(1),return:i(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function i(e){return function(t){return c([e,t])}}function c(s){if(n)throw new TypeError("Generator is already executing.");for(;o;)try{if(n=1,r&&(a=2&s[0]?r.return:s[0]?r.throw||((a=r.return)&&a.call(r),0):r.next)&&!(a=a.call(r,s[1])).done)return a;switch(r=0,a&&(s=[2&s[0],a.value]),s[0]){case 0:case 1:a=s;break;case 4:return o.label++,{value:s[1],done:!1};case 5:o.label++,r=s[1],s=[0];continue;case 7:s=o.ops.pop(),o.trys.pop();continue;default:if(!((a=(a=o.trys).length>0&&a[a.length-1])||6!==s[0]&&2!==s[0])){o=0;continue}if(3===s[0]&&(!a||s[1]>a[0]&&s[1]<a[3])){o.label=s[1];break}if(6===s[0]&&o.label<a[1]){o.label=a[1],a=s;break}if(a&&o.label<a[2]){o.label=a[2],o.ops.push(s);break}a[2]&&o.ops.pop(),o.trys.pop();continue}s=t.call(e,o)}catch(e){s=[6,e],r=0}finally{n=a=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}},a=this&&this.__values||function(e){var t="function"==typeof Symbol&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(n,"__esModule",{value:!0});var s=e("../LinkList/LinkList"),o=e("../Map/Map");function i(e,t,n){var c=this;if(void 0===e&&(e=[]),void 0===t&&(t=i.initSize),n=n||function(e){var t,n,r=0,s="";if("number"==typeof e)r=((r=Math.floor(e))<<5)-r,r&=r;else{s="string"!=typeof e?JSON.stringify(e):e;try{for(var o=a(s),i=o.next();!i.done;i=o.next())r=(r<<5)-r+i.value.charCodeAt(0),r&=r}catch(e){t={error:e}}finally{try{i&&!i.done&&(n=o.return)&&n.call(o)}finally{if(t)throw t.error}}}return r^=r>>>16},0!=(t&t-1))throw new Error("initBucketNum must be 2 to the power of n");var l=0,d=[],u=Math.max(i.initSize,Math.min(i.maxSize,t));this.size=function(){return l},this.empty=function(){return 0===l},this.clear=function(){l=0,u=t,d=[]},this.forEach=function(e){var t=0;d.forEach((function(n){n.forEach((function(n){e(n,t++)}))}))};var h=function(e){if(!(e>=i.maxSize)){u=2*e;var t=[];d.forEach((function(r,a){if(!r.empty()){if(r instanceof s.default&&1===r.size()){var c=r.front(),l=c.key,h=c.value;t[n(l)&u-1]=new s.default([{key:l,value:h}])}else if(r instanceof o.default){var p=new s.default,f=new s.default;r.forEach((function(t){0==(n(t.key)&e)?p.pushBack(t):f.pushBack(t)})),p.size()>i.untreeifyThreshold?t[a]=new o.default(p):p.size()&&(t[a]=p),f.size()>i.untreeifyThreshold?t[a+e]=new o.default(f):f.size()&&(t[a+e]=f)}else{var m=new s.default,g=new s.default;r.forEach((function(t){0==(n(t.key)&e)?m.pushBack(t):g.pushBack(t)})),m.size()&&(t[a]=m),g.size()&&(t[a+e]=g)}d[a].clear()}})),d=t}};this.setElement=function(e,t){var r,c;if(null==e)throw new Error("to avoid some unnecessary errors, we don't suggest you insert null or undefined here");if(null!=t){var p=n(e)&u-1;if(d[p]){var f=d[p].size();if(d[p]instanceof s.default){try{for(var m=a(d[p]),g=m.next();!g.done;g=m.next()){var y=g.value;if(y.key===e)return void(y.value=t)}}catch(e){r={error:e}}finally{try{g&&!g.done&&(c=m.return)&&c.call(m)}finally{if(r)throw r.error}}d[p].pushBack({key:e,value:t}),d[p].size()>=i.treeifyThreshold&&(d[p]=new o.default(d[p]))}else d[p].setElement(e,t);var v=d[p].size();l+=v-f}else++l,d[p]=new s.default([{key:e,value:t}]);l>u*i.sigma&&h.call(this,u)}else this.eraseElementByKey(e)},this.getElementByKey=function(e){var t,r,s=n(e)&u-1;if(d[s]){if(d[s]instanceof o.default)return d[s].getElementByKey(e);try{for(var i=a(d[s]),c=i.next();!c.done;c=i.next()){var l=c.value;if(l.key===e)return l.value}}catch(e){t={error:e}}finally{try{c&&!c.done&&(r=i.return)&&r.call(i)}finally{if(t)throw t.error}}}},this.eraseElementByKey=function(e){var t,r,c=n(e)&u-1;if(d[c]){var h=d[c].size();if(d[c]instanceof o.default)d[c].eraseElementByKey(e),d[c].size()<=i.untreeifyThreshold&&(d[c]=new s.default(d[c]));else{var p=-1;try{for(var f=a(d[c]),m=f.next();!m.done;m=f.next()){var g=m.value;if(++p,g.key===e){d[c].eraseElementByPos(p);break}}}catch(e){t={error:e}}finally{try{m&&!m.done&&(r=f.return)&&r.call(f)}finally{if(t)throw t.error}}}var y=d[c].size();l+=y-h}},this.find=function(e){var t,r,s=n(e)&u-1;if(!d[s])return!1;if(d[s]instanceof o.default)return d[s].find(e);try{for(var i=a(d[s]),c=i.next();!c.done;c=i.next())if(c.value.key===e)return!0}catch(e){t={error:e}}finally{try{c&&!c.done&&(r=i.return)&&r.call(i)}finally{if(t)throw t.error}}return!1},this[Symbol.iterator]=function(){return function(){var e,t,n,s,o,i;return r(this,(function(r){switch(r.label){case 0:e=0,r.label=1;case 1:if(!(e<u))return[3,10];for(;e<u&&!d[e];)++e;if(e>=u)return[3,10];r.label=2;case 2:r.trys.push([2,7,8,9]),o=void 0,t=a(d[e]),n=t.next(),r.label=3;case 3:return n.done?[3,6]:[4,n.value];case 4:r.sent(),r.label=5;case 5:return n=t.next(),[3,3];case 6:return[3,9];case 7:return s=r.sent(),o={error:s},[3,9];case 8:try{n&&!n.done&&(i=t.return)&&i.call(t)}finally{if(o)throw o.error}return[7];case 9:return++e,[3,1];case 10:return[2]}}))}()},e.forEach((function(e){var t=e.key,n=e.value;return c.setElement(t,n)})),Object.freeze(this)}i.initSize=16,i.maxSize=1<<30,i.sigma=.75,i.treeifyThreshold=8,i.untreeifyThreshold=6,i.minTreeifySize=64,Object.freeze(i),n.default=i},{"../LinkList/LinkList":29,"../Map/Map":30}],28:[function(e,t,n){var r=this&&this.__generator||function(e,t){var n,r,a,s,o={label:0,sent:function(){if(1&a[0])throw a[1];return a[1]},trys:[],ops:[]};return s={next:i(0),throw:i(1),return:i(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function i(e){return function(t){return c([e,t])}}function c(s){if(n)throw new TypeError("Generator is already executing.");for(;o;)try{if(n=1,r&&(a=2&s[0]?r.return:s[0]?r.throw||((a=r.return)&&a.call(r),0):r.next)&&!(a=a.call(r,s[1])).done)return a;switch(r=0,a&&(s=[2&s[0],a.value]),s[0]){case 0:case 1:a=s;break;case 4:return o.label++,{value:s[1],done:!1};case 5:o.label++,r=s[1],s=[0];continue;case 7:s=o.ops.pop(),o.trys.pop();continue;default:if(!((a=(a=o.trys).length>0&&a[a.length-1])||6!==s[0]&&2!==s[0])){o=0;continue}if(3===s[0]&&(!a||s[1]>a[0]&&s[1]<a[3])){o.label=s[1];break}if(6===s[0]&&o.label<a[1]){o.label=a[1],a=s;break}if(a&&o.label<a[2]){o.label=a[2],o.ops.push(s);break}a[2]&&o.ops.pop(),o.trys.pop();continue}s=t.call(e,o)}catch(e){s=[6,e],r=0}finally{n=a=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}},a=this&&this.__values||function(e){var t="function"==typeof Symbol&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(n,"__esModule",{value:!0});var s=e("../Set/Set"),o=e("../LinkList/LinkList");function i(e,t,n){var c=this;if(void 0===e&&(e=[]),void 0===t&&(t=i.initSize),n=n||function(e){var t=0,n="";if("number"==typeof e)t=((t=Math.floor(e))<<5)-t,t&=t;else{n="string"!=typeof e?JSON.stringify(e):e;for(var r=0;r<n.length;r++)t=(t<<5)-t+n.charCodeAt(r),t&=t}return t^=t>>>16},0!=(t&t-1))throw new Error("initBucketNum must be 2 to the power of n");var l=0,d=[],u=Math.max(i.initSize,Math.min(i.maxSize,t));this.size=function(){return l},this.empty=function(){return 0===l},this.clear=function(){l=0,u=t,d=[]},this.forEach=function(e){var t=0;d.forEach((function(n){n.forEach((function(n){e(n,t++)}))}))};var h=function(e){if(!(e>=i.maxSize)){u=2*e;var t=[];d.forEach((function(r,a){if(!r.empty()){if(r instanceof o.default&&1===r.size()){var c=r.front();if(void 0===c)throw new Error("unknown error");t[n(c)&u-1]=new o.default([c])}else if(r instanceof s.default){var l=new o.default,h=new o.default;r.forEach((function(t){0==(n(t)&e)?l.pushBack(t):h.pushBack(t)})),l.size()>i.untreeifyThreshold?t[a]=new s.default(l):l.size()&&(t[a]=l),h.size()>i.untreeifyThreshold?t[a+e]=new s.default(h):h.size()&&(t[a+e]=h)}else{var p=new o.default,f=new o.default;r.forEach((function(t){0==(n(t)&e)?p.pushBack(t):f.pushBack(t)})),p.size()&&(t[a]=p),f.size()&&(t[a+e]=f)}d[a].clear()}})),d=t}};this.insert=function(e){if(null==e)throw new Error("to avoid some unnecessary errors, we don't suggest you insert null or undefined here");var t=n(e)&u-1;if(d[t]){var r=d[t].size();if(d[t]instanceof o.default){if(d[t].find(e))return;d[t].pushBack(e),d[t].size()>=i.treeifyThreshold&&(d[t]=new s.default(d[t]))}else d[t].insert(e);var a=d[t].size();l+=a-r}else d[t]=new o.default([e]),++l;l>u*i.sigma&&h.call(this,u)},this.eraseElementByValue=function(e){var t=n(e)&u-1;if(d[t]){var r=d[t].size();d[t].eraseElementByValue(e),d[t]instanceof s.default&&d[t].size()<=i.untreeifyThreshold&&(d[t]=new o.default(d[t]));var a=d[t].size();l+=a-r}},this.find=function(e){var t=n(e)&u-1;return!!d[t]&&d[t].find(e)},this[Symbol.iterator]=function(){return function(){var e,t,n,s,o,i;return r(this,(function(r){switch(r.label){case 0:e=0,r.label=1;case 1:if(!(e<u))return[3,10];for(;e<u&&!d[e];)++e;if(e>=u)return[3,10];r.label=2;case 2:r.trys.push([2,7,8,9]),o=void 0,t=a(d[e]),n=t.next(),r.label=3;case 3:return n.done?[3,6]:[4,n.value];case 4:r.sent(),r.label=5;case 5:return n=t.next(),[3,3];case 6:return[3,9];case 7:return s=r.sent(),o={error:s},[3,9];case 8:try{n&&!n.done&&(i=t.return)&&i.call(t)}finally{if(o)throw o.error}return[7];case 9:return++e,[3,1];case 10:return[2]}}))}()},e.forEach((function(e){return c.insert(e)})),Object.freeze(this)}i.initSize=16,i.maxSize=1<<30,i.sigma=.75,i.treeifyThreshold=8,i.untreeifyThreshold=6,i.minTreeifySize=64,Object.freeze(i),n.default=i},{"../LinkList/LinkList":29,"../Set/Set":33}],29:[function(e,t,n){var r=this&&this.__generator||function(e,t){var n,r,a,s,o={label:0,sent:function(){if(1&a[0])throw a[1];return a[1]},trys:[],ops:[]};return s={next:i(0),throw:i(1),return:i(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function i(e){return function(t){return c([e,t])}}function c(s){if(n)throw new TypeError("Generator is already executing.");for(;o;)try{if(n=1,r&&(a=2&s[0]?r.return:s[0]?r.throw||((a=r.return)&&a.call(r),0):r.next)&&!(a=a.call(r,s[1])).done)return a;switch(r=0,a&&(s=[2&s[0],a.value]),s[0]){case 0:case 1:a=s;break;case 4:return o.label++,{value:s[1],done:!1};case 5:o.label++,r=s[1],s=[0];continue;case 7:s=o.ops.pop(),o.trys.pop();continue;default:if(!((a=(a=o.trys).length>0&&a[a.length-1])||6!==s[0]&&2!==s[0])){o=0;continue}if(3===s[0]&&(!a||s[1]>a[0]&&s[1]<a[3])){o.label=s[1];break}if(6===s[0]&&o.label<a[1]){o.label=a[1],a=s;break}if(a&&o.label<a[2]){o.label=a[2],o.ops.push(s);break}a[2]&&o.ops.pop(),o.trys.pop();continue}s=t.call(e,o)}catch(e){s=[6,e],r=0}finally{n=a=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}};Object.defineProperty(n,"__esModule",{value:!0});var a=function(){function e(e){this.value=void 0,this.pre=void 0,this.next=void 0,this.value=e}return e}();function s(e){var t=this;void 0===e&&(e=[]);var n=0,s=void 0,o=void 0;this.size=function(){return n},this.empty=function(){return 0===n},this.clear=function(){s=o=void 0,n=0},this.front=function(){return null==s?void 0:s.value},this.back=function(){return null==o?void 0:o.value},this.forEach=function(e){for(var t=s,n=0;t;){if(void 0===t.value)throw new Error("unknown error");e(t.value,n++),t=t.next}},this.getElementByPos=function(e){if(e<0||e>=n)throw new Error("pos must more then 0 and less then the list length");for(var t=s;e--&&t;)t=t.next;if(!t||void 0===t.value)throw new Error("unknown error");return t.value},this.eraseElementByPos=function(e){if(e<0||e>=n)throw new Error("erase pos must more then 0 and less then the list length");if(0===e)this.popFront();else if(e===n-1)this.popBack();else{for(var t=s;e--;){if(!(null==t?void 0:t.next))throw new Error("unknown error");t=t.next}if(!t||!t.pre||!t.next)throw new Error("unknown error");var r=t.pre,a=t.next;a.pre=r,r.next=a,n>0&&--n}},this.eraseElementByValue=function(e){for(;s&&s.value===e;)this.popFront();for(;o&&o.value===e;)this.popBack();if(s)for(var t=s;t;){if(t.value===e){var r=t.pre,a=t.next;a&&(a.pre=r),r&&(r.next=a),n>0&&--n}t=t.next}},this.pushBack=function(e){if(null==e)throw new Error("you can't push null or undefined here");++n;var t=new a(e);o?(o.next=t,t.pre=o,o=t):s=o=t},this.popBack=function(){o&&(n>0&&--n,o&&(s===o?s=o=void 0:(o=o.pre)&&(o.next=void 0)))},this.setElementByPos=function(e,t){if(null==t)throw new Error("you can't set null or undefined here");if(e<0||e>=n)throw new Error("pos must more then 0 and less then the list length");for(var r=s;e--;){if(!r)throw new Error("unknown error");r=r.next}r&&(r.value=t)},this.insert=function(e,t,r){if(void 0===r&&(r=1),null==t)throw new Error("you can't insert null or undefined here");if(e<0||e>n)throw new Error("insert pos must more then 0 and less then or equal to the list length");if(r<0)throw new Error("insert size must more than 0");if(0===e)for(;r--;)this.pushFront(t);else if(e===n)for(;r--;)this.pushBack(t);else{for(var o=s,i=1;i<e;++i){if(!(null==o?void 0:o.next))throw new Error("unknown error");o=null==o?void 0:o.next}if(!o)throw new Error("unknown error");var c=o.next;for(n+=r;r--;)o.next=new a(t),o.next.pre=o,o=o.next;o.next=c,c&&(c.pre=o)}},this.find=function(e){for(var t=s;t;){if(t.value===e)return!0;t=t.next}return!1},this.reverse=function(){for(var e=s,t=o,r=0;e&&t&&2*r<n;){var a=e.value;e.value=t.value,t.value=a,e=e.next,t=t.pre,++r}},this.unique=function(){for(var e=s;e;){for(var t=e;t&&t.next&&t.value===t.next.value;)t=t.next,n>0&&--n;e.next=t.next,e.next&&(e.next.pre=e),e=e.next}},this.sort=function(e){var t=[];this.forEach((function(e){t.push(e)})),t.sort(e);var n=s;t.forEach((function(e){n&&(n.value=e,n=n.next)}))},this.pushFront=function(e){if(null==e)throw new Error("you can't push null or undefined here");++n;var t=new a(e);s?(t.next=s,s.pre=t,s=t):s=o=t},this.popFront=function(){s&&(n>0&&--n,s&&(s===o?s=o=void 0:(s=s.next)&&(s.pre=void 0)))},this.merge=function(e){var t=this,r=s;e.forEach((function(e){for(;r&&void 0!==r.value&&r.value<=e;)r=r.next;if(void 0===r)t.pushBack(e),r=o;else if(r===s)t.pushFront(e),r=s;else{++n;var i=r.pre;i&&(i.next=new a(e),i.next.pre=i,i.next.next=r,r&&(r.pre=i.next))}}))},this[Symbol.iterator]=function(){return function(){var e;return r(this,(function(t){switch(t.label){case 0:e=s,t.label=1;case 1:if(void 0===e)return[3,3];if(!e.value)throw new Error("unknown error");return[4,e.value];case 2:return t.sent(),e=e.next,[3,1];case 3:return[2]}}))}()},e.forEach((function(e){return t.pushBack(e)})),Object.freeze(this)}Object.freeze(s),n.default=s},{}],30:[function(e,t,n){var r=this&&this.__generator||function(e,t){var n,r,a,s,o={label:0,sent:function(){if(1&a[0])throw a[1];return a[1]},trys:[],ops:[]};return s={next:i(0),throw:i(1),return:i(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function i(e){return function(t){return c([e,t])}}function c(s){if(n)throw new TypeError("Generator is already executing.");for(;o;)try{if(n=1,r&&(a=2&s[0]?r.return:s[0]?r.throw||((a=r.return)&&a.call(r),0):r.next)&&!(a=a.call(r,s[1])).done)return a;switch(r=0,a&&(s=[2&s[0],a.value]),s[0]){case 0:case 1:a=s;break;case 4:return o.label++,{value:s[1],done:!1};case 5:o.label++,r=s[1],s=[0];continue;case 7:s=o.ops.pop(),o.trys.pop();continue;default:if(!((a=(a=o.trys).length>0&&a[a.length-1])||6!==s[0]&&2!==s[0])){o=0;continue}if(3===s[0]&&(!a||s[1]>a[0]&&s[1]<a[3])){o.label=s[1];break}if(6===s[0]&&o.label<a[1]){o.label=a[1],a=s;break}if(a&&o.label<a[2]){o.label=a[2],o.ops.push(s);break}a[2]&&o.ops.pop(),o.trys.pop();continue}s=t.call(e,o)}catch(e){s=[6,e],r=0}finally{n=a=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}},a=this&&this.__values||function(e){var t="function"==typeof Symbol&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(n,"__esModule",{value:!0});var s=e("../Base/TreeNode");function o(e,t){var n=this;void 0===e&&(e=[]),t=t||function(e,t){return e<t?-1:e>t?1:0};var o=0,i=new s.default;i.color=s.default.TreeNodeColorType.black,this.size=function(){return o},this.empty=function(){return 0===o},this.clear=function(){o=0,i.key=i.value=void 0,i.leftChild=i.rightChild=i.brother=void 0};var c=function(e){if(!e||void 0===e.key)throw new Error("unknown error");return e.leftChild?c(e.leftChild):e},l=function(e){if(!e||void 0===e.key)throw new Error("unknown error");return e.rightChild?l(e.rightChild):e};this.front=function(){if(!this.empty()){var e=c(i);if(void 0===e.key||void 0===e.value)throw new Error("unknown error");return{key:e.key,value:e.value}}},this.back=function(){if(!this.empty()){var e=l(i);if(void 0===e.key||void 0===e.value)throw new Error("unknown error");return{key:e.key,value:e.value}}},this.forEach=function(e){var t,n,r=0;try{for(var s=a(this),o=s.next();!o.done;o=s.next())e(o.value,r++)}catch(e){t={error:e}}finally{try{o&&!o.done&&(n=s.return)&&n.call(s)}finally{if(t)throw t.error}}},this.getElementByPos=function(e){var t,n;if(e<0||e>=this.size())throw new Error("pos must more than 0 and less than set's size");var r=0;try{for(var s=a(this),o=s.next();!o.done;o=s.next()){var i=o.value;if(r===e)return i;++r}}catch(e){t={error:e}}finally{try{o&&!o.done&&(n=s.return)&&n.call(s)}finally{if(t)throw t.error}}throw new Error("unknown Error")};var d=function(e,n){if(e&&void 0!==e.key&&void 0!==e.value){var r=t(e.key,n);return 0===r?{key:e.key,value:e.value}:r<0?d(e.rightChild,n):d(e.leftChild,n)||{key:e.key,value:e.value}}};this.lowerBound=function(e){return d(i,e)};var u=function(e,n){if(e&&void 0!==e.key&&void 0!==e.value)return t(e.key,n)<=0?u(e.rightChild,n):u(e.leftChild,n)||{key:e.key,value:e.value}};this.upperBound=function(e){return u(i,e)};var h=function(e,n){if(e&&void 0!==e.key&&void 0!==e.value){var r=t(e.key,n);return 0===r?{key:e.key,value:e.value}:r>0?h(e.leftChild,n):h(e.rightChild,n)||{key:e.key,value:e.value}}};this.reverseLowerBound=function(e){return h(i,e)};var p=function(e,n){if(e&&void 0!==e.key&&void 0!==e.value)return t(e.key,n)>=0?p(e.leftChild,n):p(e.rightChild,n)||{key:e.key,value:e.value}};this.reverseUpperBound=function(e){return p(i,e)};var f=function(e){var t=e.parent;if(!t){if(e===i)return;throw new Error("unknown error")}if(e.color!==s.default.TreeNodeColorType.red){var n=e.brother;if(!n)throw new Error("unknown error");if(e===t.leftChild)if(n.color===s.default.TreeNodeColorType.red){n.color=s.default.TreeNodeColorType.black,t.color=s.default.TreeNodeColorType.red;var r=t.rotateLeft();i===t&&(i=r),f(e)}else n.color===s.default.TreeNodeColorType.black&&(n.rightChild&&n.rightChild.color===s.default.TreeNodeColorType.red?(n.color=t.color,t.color=s.default.TreeNodeColorType.black,n.rightChild&&(n.rightChild.color=s.default.TreeNodeColorType.black),r=t.rotateLeft(),i===t&&(i=r),e.color=s.default.TreeNodeColorType.black):n.rightChild&&n.rightChild.color!==s.default.TreeNodeColorType.black||!n.leftChild||n.leftChild.color!==s.default.TreeNodeColorType.red?n.leftChild&&n.leftChild.color!==s.default.TreeNodeColorType.black||n.rightChild&&n.rightChild.color!==s.default.TreeNodeColorType.black||(n.color=s.default.TreeNodeColorType.red,f(t)):(n.color=s.default.TreeNodeColorType.red,n.leftChild&&(n.leftChild.color=s.default.TreeNodeColorType.black),r=n.rotateRight(),i===n&&(i=r),f(e)));else e===t.rightChild&&(n.color===s.default.TreeNodeColorType.red?(n.color=s.default.TreeNodeColorType.black,t.color=s.default.TreeNodeColorType.red,r=t.rotateRight(),i===t&&(i=r),f(e)):n.color===s.default.TreeNodeColorType.black&&(n.leftChild&&n.leftChild.color===s.default.TreeNodeColorType.red?(n.color=t.color,t.color=s.default.TreeNodeColorType.black,n.leftChild&&(n.leftChild.color=s.default.TreeNodeColorType.black),r=t.rotateRight(),i===t&&(i=r),e.color=s.default.TreeNodeColorType.black):n.leftChild&&n.leftChild.color!==s.default.TreeNodeColorType.black||!n.rightChild||n.rightChild.color!==s.default.TreeNodeColorType.red?n.leftChild&&n.leftChild.color!==s.default.TreeNodeColorType.black||n.rightChild&&n.rightChild.color!==s.default.TreeNodeColorType.black||(n.color=s.default.TreeNodeColorType.red,f(t)):(n.color=s.default.TreeNodeColorType.red,n.rightChild&&(n.rightChild.color=s.default.TreeNodeColorType.black),r=n.rotateLeft(),i===n&&(i=r),f(e))))}else e.color=s.default.TreeNodeColorType.black},m=function(e){for(var t=e;t.leftChild||t.rightChild;){if(t.rightChild){t=c(t.rightChild);var n=e.key;e.key=t.key,t.key=n;var r=e.value;e.value=t.value,t.value=r,e=t}t.leftChild&&(t=l(t.leftChild),n=e.key,e.key=t.key,t.key=n,r=e.value,e.value=t.value,t.value=r,e=t)}f(t),t&&t.remove(),--o,i.color=s.default.TreeNodeColorType.black},g=function(e,t){return!(!e||void 0===e.key)&&(!!g(e.leftChild,t)||!!t(e)||g(e.rightChild,t))};this.eraseElementByPos=function(e){if(e<0||e>=o)throw new Error("pos must more than 0 and less than set's size");var t=0;g(i,(function(n){return e===t?(m(n),!0):(++t,!1)}))},this.eraseElementByKey=function(e){if(!this.empty()){var n=b(i,e);void 0!==n&&void 0!==n.key&&0===t(n.key,e)&&m(n)}};var y=function(e,n){if(!e||void 0===e.key)throw new Error("unknown error");var r=t(n,e.key);return r<0?e.leftChild?y(e.leftChild,n):(e.leftChild=new s.default,e.leftChild.parent=e,e.leftChild.brother=e.rightChild,e.rightChild&&(e.rightChild.brother=e.leftChild),e.leftChild):r>0?e.rightChild?y(e.rightChild,n):(e.rightChild=new s.default,e.rightChild.parent=e,e.rightChild.brother=e.leftChild,e.leftChild&&(e.leftChild.brother=e.rightChild),e.rightChild):e},v=function(e){var t=e.parent;if(!t){if(e===i)return;throw new Error("unknown error")}if(t.color!==s.default.TreeNodeColorType.black&&t.color===s.default.TreeNodeColorType.red){var n=t.brother,r=t.parent;if(!r)throw new Error("unknown error");if(n&&n.color===s.default.TreeNodeColorType.red)n.color=t.color=s.default.TreeNodeColorType.black,r.color=s.default.TreeNodeColorType.red,v(r);else if(!n||n.color===s.default.TreeNodeColorType.black)if(t===r.leftChild)if(e===t.leftChild){t.color=s.default.TreeNodeColorType.black,r.color=s.default.TreeNodeColorType.red;var a=r.rotateRight();r===i&&(i=a)}else e===t.rightChild&&(a=t.rotateLeft(),r===i&&(i=a),v(t));else t===r.rightChild&&(e===t.leftChild?(a=t.rotateRight(),r===i&&(i=a),v(t)):e===t.rightChild&&(t.color=s.default.TreeNodeColorType.black,r.color=s.default.TreeNodeColorType.red,a=r.rotateLeft(),r===i&&(i=a)))}};this.setElement=function(e,n){if(null==e)throw new Error("to avoid some unnecessary errors, we don't suggest you insert null or undefined here");if(null!=n){if(this.empty())return++o,i.key=e,i.value=n,void(i.color=s.default.TreeNodeColorType.black);var r=y(i,e);void 0===r.key||0!==t(r.key,e)?(++o,r.key=e,r.value=n,v(r),i.color=s.default.TreeNodeColorType.black):r.value=n}else this.eraseElementByKey(e)};var b=function(e,n){if(e&&void 0!==e.key){var r=t(n,e.key);return r<0?b(e.leftChild,n):r>0?b(e.rightChild,n):e}};this.find=function(e){return!!b(i,e)},this.getElementByKey=function(e){var t=b(i,e);if(void 0===(null==t?void 0:t.key)||void 0===(null==t?void 0:t.value))throw new Error("unknown error");return t.value},this.union=function(e){var t=this;e.forEach((function(e){var n=e.key,r=e.value;return t.setElement(n,r)}))},this.getHeight=function(){if(this.empty())return 0;var e=function(t){return t?Math.max(e(t.leftChild),e(t.rightChild))+1:1};return e(i)};var w=function(e){return r(this,(function(t){switch(t.label){case 0:return e&&void 0!==e.key&&void 0!==e.value?[5,a(w(e.leftChild))]:[2];case 1:return t.sent(),[4,{key:e.key,value:e.value}];case 2:return t.sent(),[5,a(w(e.rightChild))];case 3:return t.sent(),[2]}}))};this[Symbol.iterator]=function(){return w(i)},e.forEach((function(e){var t=e.key,r=e.value;return n.setElement(t,r)})),Object.freeze(this)}Object.freeze(o),n.default=o},{"../Base/TreeNode":25}],31:[function(e,t,n){function r(e,t){void 0===e&&(e=[]),t=t||function(e,t){return e>t?-1:e<t?1:0};var n=[];e.forEach((function(e){return n.push(e)}));var r=n.length,a=function(e,t){if(e<0||e>=r)throw new Error("unknown error");if(t<0||t>=r)throw new Error("unknown error");var a=n[e];n[e]=n[t],n[t]=a},s=function(e){if(e<0||e>=r)throw new Error("unknown error");var s=2*e+1,o=2*e+2;s<r&&t(n[e],n[s])>0&&a(e,s),o<r&&t(n[e],n[o])>0&&a(e,o)};!function(){for(var e=Math.floor((r-1)/2);e>=0;--e)for(var s=e,o=2*s+1;o<r;){var i=o+1,c=o;if(i<r&&t(n[o],n[i])>0&&(c=i),t(n[s],n[c])<=0)break;a(s,c),o=2*(s=c)+1}}(),this.size=function(){return r},this.empty=function(){return 0===r},this.clear=function(){r=0,n.length=0},this.push=function(e){if(n.push(e),1!=++r)for(var a=r-1;a>0;){var o=Math.floor((a-1)/2);if(t(n[o],e)<=0)break;s(o),a=o}},this.pop=function(){if(!this.empty())if(1!==this.size()){var e=n[r-1];--r;for(var a=0;a<this.size();){var s=2*a+1,o=2*a+2;if(s>=this.size())break;var i=s;if(o<this.size()&&t(n[s],n[o])>0&&(i=o),t(n[i],e)>=0)break;n[a]=n[i],a=i}n[a]=e}else--r},this.top=function(){return n[0]},Object.freeze(this)}Object.defineProperty(n,"__esModule",{value:!0}),Object.freeze(r),n.default=r},{}],32:[function(e,t,n){Object.defineProperty(n,"__esModule",{value:!0});var r=e("../LinkList/LinkList");function a(e){void 0===e&&(e=[]);var t=new r.default(e);this.size=function(){return t.size()},this.empty=function(){return t.empty()},this.clear=function(){t.clear()},this.push=function(e){t.pushBack(e)},this.pop=function(){t.popFront()},this.front=function(){return t.front()},Object.freeze(this)}Object.freeze(a),n.default=a},{"../LinkList/LinkList":29}],33:[function(e,t,n){var r=this&&this.__generator||function(e,t){var n,r,a,s,o={label:0,sent:function(){if(1&a[0])throw a[1];return a[1]},trys:[],ops:[]};return s={next:i(0),throw:i(1),return:i(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function i(e){return function(t){return c([e,t])}}function c(s){if(n)throw new TypeError("Generator is already executing.");for(;o;)try{if(n=1,r&&(a=2&s[0]?r.return:s[0]?r.throw||((a=r.return)&&a.call(r),0):r.next)&&!(a=a.call(r,s[1])).done)return a;switch(r=0,a&&(s=[2&s[0],a.value]),s[0]){case 0:case 1:a=s;break;case 4:return o.label++,{value:s[1],done:!1};case 5:o.label++,r=s[1],s=[0];continue;case 7:s=o.ops.pop(),o.trys.pop();continue;default:if(!((a=(a=o.trys).length>0&&a[a.length-1])||6!==s[0]&&2!==s[0])){o=0;continue}if(3===s[0]&&(!a||s[1]>a[0]&&s[1]<a[3])){o.label=s[1];break}if(6===s[0]&&o.label<a[1]){o.label=a[1],a=s;break}if(a&&o.label<a[2]){o.label=a[2],o.ops.push(s);break}a[2]&&o.ops.pop(),o.trys.pop();continue}s=t.call(e,o)}catch(e){s=[6,e],r=0}finally{n=a=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}},a=this&&this.__values||function(e){var t="function"==typeof Symbol&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(n,"__esModule",{value:!0});var s=e("../Base/TreeNode");function o(e,t){var n=this;void 0===e&&(e=[]),t=t||function(e,t){return e<t?-1:e>t?1:0};var o=0,i=new s.default;i.color=s.default.TreeNodeColorType.black,this.size=function(){return o},this.empty=function(){return 0===o},this.clear=function(){o=0,i.key=void 0,i.leftChild=i.rightChild=i.brother=i.parent=void 0,i.color=s.default.TreeNodeColorType.black};var c=function(e){if(!e||void 0===e.key)throw new Error("unknown error");return e.leftChild?c(e.leftChild):e},l=function(e){if(!e||void 0===e.key)throw new Error("unknown error");return e.rightChild?l(e.rightChild):e};this.front=function(){if(!this.empty())return c(i).key},this.back=function(){if(!this.empty())return l(i).key},this.forEach=function(e){var t,n,r=0;try{for(var s=a(this),o=s.next();!o.done;o=s.next())e(o.value,r++)}catch(e){t={error:e}}finally{try{o&&!o.done&&(n=s.return)&&n.call(s)}finally{if(t)throw t.error}}},this.getElementByPos=function(e){var t,n;if(e<0||e>=this.size())throw new Error("pos must more than 0 and less than set's size");var r=0;try{for(var s=a(this),o=s.next();!o.done;o=s.next()){var i=o.value;if(r===e)return i;++r}}catch(e){t={error:e}}finally{try{o&&!o.done&&(n=s.return)&&n.call(s)}finally{if(t)throw t.error}}throw new Error("unknown error")};var d=function(e){var t=e.parent;if(!t){if(e===i)return;throw new Error("unknown error")}if(e.color!==s.default.TreeNodeColorType.red){var n=e.brother;if(!n)throw new Error("unknown error");if(e===t.leftChild)if(n.color===s.default.TreeNodeColorType.red){n.color=s.default.TreeNodeColorType.black,t.color=s.default.TreeNodeColorType.red;var r=t.rotateLeft();i===t&&(i=r),d(e)}else n.color===s.default.TreeNodeColorType.black&&(n.rightChild&&n.rightChild.color===s.default.TreeNodeColorType.red?(n.color=t.color,t.color=s.default.TreeNodeColorType.black,n.rightChild&&(n.rightChild.color=s.default.TreeNodeColorType.black),r=t.rotateLeft(),i===t&&(i=r),e.color=s.default.TreeNodeColorType.black):n.rightChild&&n.rightChild.color!==s.default.TreeNodeColorType.black||!n.leftChild||n.leftChild.color!==s.default.TreeNodeColorType.red?n.leftChild&&n.leftChild.color!==s.default.TreeNodeColorType.black||n.rightChild&&n.rightChild.color!==s.default.TreeNodeColorType.black||(n.color=s.default.TreeNodeColorType.red,d(t)):(n.color=s.default.TreeNodeColorType.red,n.leftChild&&(n.leftChild.color=s.default.TreeNodeColorType.black),r=n.rotateRight(),i===n&&(i=r),d(e)));else e===t.rightChild&&(n.color===s.default.TreeNodeColorType.red?(n.color=s.default.TreeNodeColorType.black,t.color=s.default.TreeNodeColorType.red,r=t.rotateRight(),i===t&&(i=r),d(e)):n.color===s.default.TreeNodeColorType.black&&(n.leftChild&&n.leftChild.color===s.default.TreeNodeColorType.red?(n.color=t.color,t.color=s.default.TreeNodeColorType.black,n.leftChild&&(n.leftChild.color=s.default.TreeNodeColorType.black),r=t.rotateRight(),i===t&&(i=r),e.color=s.default.TreeNodeColorType.black):n.leftChild&&n.leftChild.color!==s.default.TreeNodeColorType.black||!n.rightChild||n.rightChild.color!==s.default.TreeNodeColorType.red?n.leftChild&&n.leftChild.color!==s.default.TreeNodeColorType.black||n.rightChild&&n.rightChild.color!==s.default.TreeNodeColorType.black||(n.color=s.default.TreeNodeColorType.red,d(t)):(n.color=s.default.TreeNodeColorType.red,n.rightChild&&(n.rightChild.color=s.default.TreeNodeColorType.black),r=n.rotateLeft(),i===n&&(i=r),d(e))))}else e.color=s.default.TreeNodeColorType.black},u=function(e){for(var t=e;t.leftChild||t.rightChild;){if(t.rightChild){t=c(t.rightChild);var n=e.key;e.key=t.key,t.key=n,e=t}t.leftChild&&(t=l(t.leftChild),n=e.key,e.key=t.key,t.key=n,e=t)}d(t),t&&t.remove(),--o,i.color=s.default.TreeNodeColorType.black},h=function(e,t){return!(!e||void 0===e.key)&&(!!h(e.leftChild,t)||!!t(e)||h(e.rightChild,t))};this.eraseElementByPos=function(e){if(e<0||e>=o)throw new Error("pos must more than 0 and less than set's size");var t=0;h(i,(function(n){return e===t?(u(n),!0):(++t,!1)}))},this.eraseElementByValue=function(e){if(!this.empty()){var n=m(i,e);void 0!==n&&void 0!==n.key&&0===t(n.key,e)&&u(n)}};var p=function(e,n){if(!e||void 0===e.key)throw new Error("unknown error");var r=t(n,e.key);return r<0?e.leftChild?p(e.leftChild,n):(e.leftChild=new s.default,e.leftChild.parent=e,e.leftChild.brother=e.rightChild,e.rightChild&&(e.rightChild.brother=e.leftChild),e.leftChild):r>0?e.rightChild?p(e.rightChild,n):(e.rightChild=new s.default,e.rightChild.parent=e,e.rightChild.brother=e.leftChild,e.leftChild&&(e.leftChild.brother=e.rightChild),e.rightChild):e},f=function(e){var t=e.parent;if(!t){if(e===i)return;throw new Error("unknown error")}if(t.color!==s.default.TreeNodeColorType.black&&t.color===s.default.TreeNodeColorType.red){var n=t.brother,r=t.parent;if(!r)throw new Error("unknown error");if(n&&n.color===s.default.TreeNodeColorType.red)n.color=t.color=s.default.TreeNodeColorType.black,r.color=s.default.TreeNodeColorType.red,f(r);else if(!n||n.color===s.default.TreeNodeColorType.black)if(t===r.leftChild)if(e===t.leftChild){t.color=s.default.TreeNodeColorType.black,r.color=s.default.TreeNodeColorType.red;var a=r.rotateRight();r===i&&(i=a)}else e===t.rightChild&&(a=t.rotateLeft(),r===i&&(i=a),f(t));else t===r.rightChild&&(e===t.leftChild?(a=t.rotateRight(),r===i&&(i=a),f(t)):e===t.rightChild&&(t.color=s.default.TreeNodeColorType.black,r.color=s.default.TreeNodeColorType.red,a=r.rotateLeft(),r===i&&(i=a)))}};this.insert=function(e){if(null==e)throw new Error("to avoid some unnecessary errors, we don't suggest you insert null or undefined here");if(this.empty())return++o,i.key=e,void(i.color=s.default.TreeNodeColorType.black);var n=p(i,e);void 0!==n.key&&0===t(n.key,e)||(++o,n.key=e,f(n),i.color=s.default.TreeNodeColorType.black)};var m=function(e,n){if(e&&void 0!==e.key){var r=t(n,e.key);return r<0?m(e.leftChild,n):r>0?m(e.rightChild,n):e}};this.find=function(e){var n=m(i,e);return void 0!==n&&void 0!==n.key&&0===t(n.key,e)};var g=function(e,n){if(e&&void 0!==e.key){var r=t(e.key,n);if(0===r)return e.key;if(r<0)return g(e.rightChild,n);var a=g(e.leftChild,n);return void 0!==a?a:e.key}};this.lowerBound=function(e){return g(i,e)};var y=function(e,n){if(e&&void 0!==e.key){if(t(e.key,n)<=0)return y(e.rightChild,n);var r=y(e.leftChild,n);return void 0!==r?r:e.key}};this.upperBound=function(e){return y(i,e)};var v=function(e,n){if(e&&void 0!==e.key){var r=t(e.key,n);if(0===r)return e.key;if(r>0)return v(e.leftChild,n);var a=v(e.rightChild,n);return void 0!==a?a:e.key}};this.reverseLowerBound=function(e){return v(i,e)};var b=function(e,n){if(e&&void 0!==e.key){if(t(e.key,n)>=0)return b(e.leftChild,n);var r=b(e.rightChild,n);return void 0!==r?r:e.key}};this.reverseUpperBound=function(e){return b(i,e)},this.union=function(e){var t=this;e.forEach((function(e){return t.insert(e)}))},this.getHeight=function(){if(this.empty())return 0;var e=function(t){return t?Math.max(e(t.leftChild),e(t.rightChild))+1:1};return e(i)};var w=function(e){return r(this,(function(t){switch(t.label){case 0:return e&&void 0!==e.key?[5,a(w(e.leftChild))]:[2];case 1:return t.sent(),[4,e.key];case 2:return t.sent(),[5,a(w(e.rightChild))];case 3:return t.sent(),[2]}}))};this[Symbol.iterator]=function(){return w(i)},e.forEach((function(e){return n.insert(e)})),Object.freeze(this)}Object.freeze(o),n.default=o},{"../Base/TreeNode":25}],34:[function(e,t,n){function r(e){var t=this;void 0===e&&(e=[]);var n=0,r=[];this.size=function(){return n},this.empty=function(){return 0===n},this.clear=function(){n=0,r.length=0},this.push=function(e){r.push(e),++n},this.pop=function(){r.pop(),n>0&&--n},this.top=function(){return r[n-1]},e.forEach((function(e){return t.push(e)})),Object.freeze(this)}Object.defineProperty(n,"__esModule",{value:!0}),Object.freeze(r),n.default=r},{}],35:[function(e,t,n){var r=this&&this.__generator||function(e,t){var n,r,a,s,o={label:0,sent:function(){if(1&a[0])throw a[1];return a[1]},trys:[],ops:[]};return s={next:i(0),throw:i(1),return:i(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function i(e){return function(t){return c([e,t])}}function c(s){if(n)throw new TypeError("Generator is already executing.");for(;o;)try{if(n=1,r&&(a=2&s[0]?r.return:s[0]?r.throw||((a=r.return)&&a.call(r),0):r.next)&&!(a=a.call(r,s[1])).done)return a;switch(r=0,a&&(s=[2&s[0],a.value]),s[0]){case 0:case 1:a=s;break;case 4:return o.label++,{value:s[1],done:!1};case 5:o.label++,r=s[1],s=[0];continue;case 7:s=o.ops.pop(),o.trys.pop();continue;default:if(!((a=(a=o.trys).length>0&&a[a.length-1])||6!==s[0]&&2!==s[0])){o=0;continue}if(3===s[0]&&(!a||s[1]>a[0]&&s[1]<a[3])){o.label=s[1];break}if(6===s[0]&&o.label<a[1]){o.label=a[1],a=s;break}if(a&&o.label<a[2]){o.label=a[2],o.ops.push(s);break}a[2]&&o.ops.pop(),o.trys.pop();continue}s=t.call(e,o)}catch(e){s=[6,e],r=0}finally{n=a=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}},a=this&&this.__read||function(e,t){var n="function"==typeof Symbol&&e[Symbol.iterator];if(!n)return e;var r,a,s=n.call(e),o=[];try{for(;(void 0===t||t-- >0)&&!(r=s.next()).done;)o.push(r.value)}catch(e){a={error:e}}finally{try{r&&!r.done&&(n=s.return)&&n.call(s)}finally{if(a)throw a.error}}return o},s=this&&this.__spreadArray||function(e,t,n){if(n||2===arguments.length)for(var r,a=0,s=t.length;a<s;a++)!r&&a in t||(r||(r=Array.prototype.slice.call(t,0,a)),r[a]=t[a]);return e.concat(r||Array.prototype.slice.call(t))},o=this&&this.__values||function(e){var t="function"==typeof Symbol&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")};function i(e){var t=this;void 0===e&&(e=[]);var n=0,i=[];this.size=function(){return n},this.empty=function(){return 0===n},this.clear=function(){n=0,i.length=0},this.front=function(){if(!this.empty())return i[0]},this.back=function(){if(!this.empty())return i[n-1]},this.forEach=function(e){i.forEach(e)},this.getElementByPos=function(e){if(e<0||e>=n)throw new Error("pos must more than 0 and less than vector's size");return i[e]},this.eraseElementByPos=function(e){if(e<0||e>=n)throw new Error("pos must more than 0 and less than vector's size");for(var t=e;t<n-1;++t)i[t]=i[t+1];this.popBack()},this.eraseElementByValue=function(e){var t=[];this.forEach((function(n){n!==e&&t.push(n)})),t.forEach((function(e,t){i[t]=e}));for(var r=t.length;n>r;)this.popBack()},this.pushBack=function(e){i.push(e),++n},this.popBack=function(){i.pop(),n>0&&--n},this.setElementByPos=function(e,t){if(e<0||e>=n)throw new Error("pos must more than 0 and less than vector's size");i[e]=t},this.insert=function(e,t,r){if(void 0===r&&(r=1),e<0||e>n)throw new Error("pos must more than 0 and less than or equal to vector's size");i.splice.apply(i,s([e,0],a(new Array(r).fill(t)),!1)),n+=r},this.find=function(e){return i.includes(e)},this.reverse=function(){i.reverse()},this.unique=function(){var e,t=[];this.forEach((function(n,r){0!==r&&n===e||(t.push(n),e=n)})),t.forEach((function(e,t){i[t]=e}));for(var r=t.length;n>r;)this.popBack()},this.sort=function(e){i.sort(e)},this[Symbol.iterator]=function(){return function(){return r(this,(function(e){switch(e.label){case 0:return[5,o(i)];case 1:return[2,e.sent()]}}))}()},e.forEach((function(e){return t.pushBack(e)})),Object.freeze(this)}Object.defineProperty(n,"__esModule",{value:!0}),Object.freeze(i),n.default=i},{}],36:[function(e,t,n){Object.defineProperty(n,"__esModule",{value:!0}),n.HashMap=n.HashSet=n.Map=n.Set=n.PriorityQueue=n.Deque=n.LinkList=n.Queue=n.Stack=n.Vector=void 0;var r=e("./Vector/Vector");n.Vector=r.default;var a=e("./Stack/Stack");n.Stack=a.default;var s=e("./Queue/Queue");n.Queue=s.default;var o=e("./LinkList/LinkList");n.LinkList=o.default;var i=e("./Deque/Deque");n.Deque=i.default;var c=e("./PriorityQueue/PriorityQueue");n.PriorityQueue=c.default;var l=e("./Set/Set");n.Set=l.default;var d=e("./Map/Map");n.Map=d.default;var u=e("./HashSet/HashSet");n.HashSet=u.default;var h=e("./HashMap/HashMap");n.HashMap=h.default},{"./Deque/Deque":26,"./HashMap/HashMap":27,"./HashSet/HashSet":28,"./LinkList/LinkList":29,"./Map/Map":30,"./PriorityQueue/PriorityQueue":31,"./Queue/Queue":32,"./Set/Set":33,"./Stack/Stack":34,"./Vector/Vector":35}],37:[function(e,t,n){const r=e("yallist"),a=Symbol("max"),s=Symbol("length"),o=Symbol("lengthCalculator"),i=Symbol("allowStale"),c=Symbol("maxAge"),l=Symbol("dispose"),d=Symbol("noDisposeOnSet"),u=Symbol("lruList"),h=Symbol("cache"),p=Symbol("updateAgeOnGet"),f=()=>1;class m{constructor(e){if("number"==typeof e&&(e={max:e}),e||(e={}),e.max&&("number"!=typeof e.max||e.max<0))throw new TypeError("max must be a non-negative number");this[a]=e.max||1/0;const t=e.length||f;if(this[o]="function"!=typeof t?f:t,this[i]=e.stale||!1,e.maxAge&&"number"!=typeof e.maxAge)throw new TypeError("maxAge must be a number");this[c]=e.maxAge||0,this[l]=e.dispose,this[d]=e.noDisposeOnSet||!1,this[p]=e.updateAgeOnGet||!1,this.reset()}set max(e){if("number"!=typeof e||e<0)throw new TypeError("max must be a non-negative number");this[a]=e||1/0,v(this)}get max(){return this[a]}set allowStale(e){this[i]=!!e}get allowStale(){return this[i]}set maxAge(e){if("number"!=typeof e)throw new TypeError("maxAge must be a non-negative number");this[c]=e,v(this)}get maxAge(){return this[c]}set lengthCalculator(e){"function"!=typeof e&&(e=f),e!==this[o]&&(this[o]=e,this[s]=0,this[u].forEach((e=>{e.length=this[o](e.value,e.key),this[s]+=e.length}))),v(this)}get lengthCalculator(){return this[o]}get length(){return this[s]}get itemCount(){return this[u].length}rforEach(e,t){t=t||this;for(let n=this[u].tail;null!==n;){const r=n.prev;C(this,e,n,t),n=r}}forEach(e,t){t=t||this;for(let n=this[u].head;null!==n;){const r=n.next;C(this,e,n,t),n=r}}keys(){return this[u].toArray().map((e=>e.key))}values(){return this[u].toArray().map((e=>e.value))}reset(){this[l]&&this[u]&&this[u].length&&this[u].forEach((e=>this[l](e.key,e.value))),this[h]=new Map,this[u]=new r,this[s]=0}dump(){return this[u].map((e=>!y(this,e)&&{k:e.key,v:e.value,e:e.now+(e.maxAge||0)})).toArray().filter((e=>e))}dumpLru(){return this[u]}set(e,t,n){if((n=n||this[c])&&"number"!=typeof n)throw new TypeError("maxAge must be a number");const r=n?Date.now():0,i=this[o](t,e);if(this[h].has(e)){if(i>this[a])return b(this,this[h].get(e)),!1;const o=this[h].get(e).value;return this[l]&&(this[d]||this[l](e,o.value)),o.now=r,o.maxAge=n,o.value=t,this[s]+=i-o.length,o.length=i,this.get(e),v(this),!0}const p=new w(e,t,i,r,n);return p.length>this[a]?(this[l]&&this[l](e,t),!1):(this[s]+=p.length,this[u].unshift(p),this[h].set(e,this[u].head),v(this),!0)}has(e){if(!this[h].has(e))return!1;const t=this[h].get(e).value;return!y(this,t)}get(e){return g(this,e,!0)}peek(e){return g(this,e,!1)}pop(){const e=this[u].tail;return e?(b(this,e),e.value):null}del(e){b(this,this[h].get(e))}load(e){this.reset();const t=Date.now();for(let n=e.length-1;n>=0;n--){const r=e[n],a=r.e||0;if(0===a)this.set(r.k,r.v);else{const e=a-t;e>0&&this.set(r.k,r.v,e)}}}prune(){this[h].forEach(((e,t)=>g(this,t,!1)))}}const g=(e,t,n)=>{const r=e[h].get(t);if(r){const t=r.value;if(y(e,t)){if(b(e,r),!e[i])return}else n&&(e[p]&&(r.value.now=Date.now()),e[u].unshiftNode(r));return t.value}},y=(e,t)=>{if(!t||!t.maxAge&&!e[c])return!1;const n=Date.now()-t.now;return t.maxAge?n>t.maxAge:e[c]&&n>e[c]},v=e=>{if(e[s]>e[a])for(let t=e[u].tail;e[s]>e[a]&&null!==t;){const n=t.prev;b(e,t),t=n}},b=(e,t)=>{if(t){const n=t.value;e[l]&&e[l](n.key,n.value),e[s]-=n.length,e[h].delete(n.key),e[u].removeNode(t)}};class w{constructor(e,t,n,r,a){this.key=e,this.value=t,this.length=n,this.now=r,this.maxAge=a||0}}const C=(e,t,n,r)=>{let a=n.value;y(e,a)&&(b(e,n),e[i]||(a=void 0)),a&&t.call(r,a.value,a.key,e)};t.exports=m},{yallist:83}],38:[function(e,t,n){(function(e){(function(){const n=t.exports;n.types={0:"reserved",1:"connect",2:"connack",3:"publish",4:"puback",5:"pubrec",6:"pubrel",7:"pubcomp",8:"subscribe",9:"suback",10:"unsubscribe",11:"unsuback",12:"pingreq",13:"pingresp",14:"disconnect",15:"auth"},n.codes={};for(const e in n.types){const t=n.types[e];n.codes[t]=e}n.CMD_SHIFT=4,n.CMD_MASK=240,n.DUP_MASK=8,n.QOS_MASK=3,n.QOS_SHIFT=1,n.RETAIN_MASK=1,n.VARBYTEINT_MASK=127,n.VARBYTEINT_FIN_MASK=128,n.VARBYTEINT_MAX=268435455,n.SESSIONPRESENT_MASK=1,n.SESSIONPRESENT_HEADER=e.from([n.SESSIONPRESENT_MASK]),n.CONNACK_HEADER=e.from([n.codes.connack<<n.CMD_SHIFT]),n.USERNAME_MASK=128,n.PASSWORD_MASK=64,n.WILL_RETAIN_MASK=32,n.WILL_QOS_MASK=24,n.WILL_QOS_SHIFT=3,n.WILL_FLAG_MASK=4,n.CLEAN_SESSION_MASK=2,n.CONNECT_HEADER=e.from([n.codes.connect<<n.CMD_SHIFT]),n.properties={sessionExpiryInterval:17,willDelayInterval:24,receiveMaximum:33,maximumPacketSize:39,topicAliasMaximum:34,requestResponseInformation:25,requestProblemInformation:23,userProperties:38,authenticationMethod:21,authenticationData:22,payloadFormatIndicator:1,messageExpiryInterval:2,contentType:3,responseTopic:8,correlationData:9,maximumQoS:36,retainAvailable:37,assignedClientIdentifier:18,reasonString:31,wildcardSubscriptionAvailable:40,subscriptionIdentifiersAvailable:41,sharedSubscriptionAvailable:42,serverKeepAlive:19,responseInformation:26,serverReference:28,topicAlias:35,subscriptionIdentifier:11},n.propertiesCodes={};for(const e in n.properties){const t=n.properties[e];n.propertiesCodes[t]=e}function r(t){return[0,1,2].map((r=>[0,1].map((a=>[0,1].map((s=>{const o=e.alloc(1);return o.writeUInt8(n.codes[t]<<n.CMD_SHIFT|(a?n.DUP_MASK:0)|r<<n.QOS_SHIFT|s,0,!0),o}))))))}n.propertiesTypes={sessionExpiryInterval:"int32",willDelayInterval:"int32",receiveMaximum:"int16",maximumPacketSize:"int32",topicAliasMaximum:"int16",requestResponseInformation:"byte",requestProblemInformation:"byte",userProperties:"pair",authenticationMethod:"string",authenticationData:"binary",payloadFormatIndicator:"byte",messageExpiryInterval:"int32",contentType:"string",responseTopic:"string",correlationData:"binary",maximumQoS:"int8",retainAvailable:"byte",assignedClientIdentifier:"string",reasonString:"string",wildcardSubscriptionAvailable:"byte",subscriptionIdentifiersAvailable:"byte",sharedSubscriptionAvailable:"byte",serverKeepAlive:"int16",responseInformation:"string",serverReference:"string",topicAlias:"int16",subscriptionIdentifier:"var"},n.PUBLISH_HEADER=r("publish"),n.SUBSCRIBE_HEADER=r("subscribe"),n.SUBSCRIBE_OPTIONS_QOS_MASK=3,n.SUBSCRIBE_OPTIONS_NL_MASK=1,n.SUBSCRIBE_OPTIONS_NL_SHIFT=2,n.SUBSCRIBE_OPTIONS_RAP_MASK=1,n.SUBSCRIBE_OPTIONS_RAP_SHIFT=3,n.SUBSCRIBE_OPTIONS_RH_MASK=3,n.SUBSCRIBE_OPTIONS_RH_SHIFT=4,n.SUBSCRIBE_OPTIONS_RH=[0,16,32],n.SUBSCRIBE_OPTIONS_NL=4,n.SUBSCRIBE_OPTIONS_RAP=8,n.SUBSCRIBE_OPTIONS_QOS=[0,1,2],n.UNSUBSCRIBE_HEADER=r("unsubscribe"),n.ACKS={unsuback:r("unsuback"),puback:r("puback"),pubcomp:r("pubcomp"),pubrel:r("pubrel"),pubrec:r("pubrec")},n.SUBACK_HEADER=e.from([n.codes.suback<<n.CMD_SHIFT]),n.VERSION3=e.from([3]),n.VERSION4=e.from([4]),n.VERSION5=e.from([5]),n.VERSION131=e.from([131]),n.VERSION132=e.from([132]),n.QOS=[0,1,2].map((t=>e.from([t]))),n.EMPTY={pingreq:e.from([n.codes.pingreq<<4,0]),pingresp:e.from([n.codes.pingresp<<4,0]),disconnect:e.from([n.codes.disconnect<<4,0])}}).call(this)}).call(this,e("buffer").Buffer)},{buffer:17}],39:[function(e,t,n){(function(n){(function(){const r=e("./writeToStream"),a=e("events");function s(e,t){const n=new o;return r(e,n,t),n.concat()}class o extends a{constructor(){super(),this._array=new Array(20),this._i=0}write(e){return this._array[this._i++]=e,!0}concat(){let e=0;const t=new Array(this._array.length),r=this._array;let a,s=0;for(a=0;a<r.length&&void 0!==r[a];a++)"string"!=typeof r[a]?t[a]=r[a].length:t[a]=n.byteLength(r[a]),e+=t[a];const o=n.allocUnsafe(e);for(a=0;a<r.length&&void 0!==r[a];a++)"string"!=typeof r[a]?(r[a].copy(o,s),s+=t[a]):(o.write(r[a],s),s+=t[a]);return o}}t.exports=s}).call(this)}).call(this,e("buffer").Buffer)},{"./writeToStream":44,buffer:17,events:22}],40:[function(e,t,n){n.parser=e("./parser").parser,n.generate=e("./generate"),n.writeToStream=e("./writeToStream")},{"./generate":39,"./parser":43,"./writeToStream":44}],41:[function(e,t,n){(function(e){(function(){const n=65536,r={},a=e.isBuffer(e.from([1,2]).subarray(0,1));function s(t){const n=e.allocUnsafe(2);return n.writeUInt8(t>>8,0),n.writeUInt8(255&t,1),n}function o(){for(let e=0;e<n;e++)r[e]=s(e)}function i(t){const n=4;let r=0,s=0;const o=e.allocUnsafe(n);do{r=t%128|0,(t=t/128|0)>0&&(r|=128),o.writeUInt8(r,s++)}while(t>0&&s<n);return t>0&&(s=0),a?o.subarray(0,s):o.slice(0,s)}function c(t){const n=e.allocUnsafe(4);return n.writeUInt32BE(t,0),n}t.exports={cache:r,generateCache:o,generateNumber:s,genBufVariableByteInt:i,generate4ByteBuffer:c}}).call(this)}).call(this,e("buffer").Buffer)},{buffer:17}],42:[function(e,t,n){class r{constructor(){this.cmd=null,this.retain=!1,this.qos=0,this.dup=!1,this.length=-1,this.topic=null,this.payload=null}}t.exports=r},{}],43:[function(e,t,n){const r=e("bl"),a=e("events"),s=e("./packet"),o=e("./constants"),i=e("debug")("mqtt-packet:parser");class c extends a{constructor(){super(),this.parser=this.constructor.parser}static parser(e){return this instanceof c?(this.settings=e||{},this._states=["_parseHeader","_parseLength","_parsePayload","_newPacket"],this._resetState(),this):(new c).parser(e)}_resetState(){i("_resetState: resetting packet, error, _list, and _stateCounter"),this.packet=new s,this.error=null,this._list=r(),this._stateCounter=0}parse(e){for(this.error&&this._resetState(),this._list.append(e),i("parse: current state: %s",this._states[this._stateCounter]);(-1!==this.packet.length||this._list.length>0)&&this[this._states[this._stateCounter]]()&&!this.error;)this._stateCounter++,i("parse: state complete. _stateCounter is now: %d",this._stateCounter),i("parse: packet.length: %d, buffer list length: %d",this.packet.length,this._list.length),this._stateCounter>=this._states.length&&(this._stateCounter=0);return i("parse: exited while loop. packet: %d, buffer list length: %d",this.packet.length,this._list.length),this._list.length}_parseHeader(){const e=this._list.readUInt8(0);return this.packet.cmd=o.types[e>>o.CMD_SHIFT],this.packet.retain=0!=(e&o.RETAIN_MASK),this.packet.qos=e>>o.QOS_SHIFT&o.QOS_MASK,this.packet.dup=0!=(e&o.DUP_MASK),i("_parseHeader: packet: %o",this.packet),this._list.consume(1),!0}_parseLength(){const e=this._parseVarByteNum(!0);return e&&(this.packet.length=e.value,this._list.consume(e.bytes)),i("_parseLength %d",e.value),!!e}_parsePayload(){i("_parsePayload: payload %O",this._list);let e=!1;if(0===this.packet.length||this._list.length>=this.packet.length){switch(this._pos=0,this.packet.cmd){case"connect":this._parseConnect();break;case"connack":this._parseConnack();break;case"publish":this._parsePublish();break;case"puback":case"pubrec":case"pubrel":case"pubcomp":this._parseConfirmation();break;case"subscribe":this._parseSubscribe();break;case"suback":this._parseSuback();break;case"unsubscribe":this._parseUnsubscribe();break;case"unsuback":this._parseUnsuback();break;case"pingreq":case"pingresp":break;case"disconnect":this._parseDisconnect();break;case"auth":this._parseAuth();break;default:this._emitError(new Error("Not supported"))}e=!0}return i("_parsePayload complete result: %s",e),e}_parseConnect(){let e,t,n,r;i("_parseConnect");const a={},s=this.packet,c=this._parseString();if(null===c)return this._emitError(new Error("Cannot parse protocolId"));if("MQTT"!==c&&"MQIsdp"!==c)return this._emitError(new Error("Invalid protocolId"));if(s.protocolId=c,this._pos>=this._list.length)return this._emitError(new Error("Packet too short"));if(s.protocolVersion=this._list.readUInt8(this._pos),s.protocolVersion>=128&&(s.bridgeMode=!0,s.protocolVersion=s.protocolVersion-128),3!==s.protocolVersion&&4!==s.protocolVersion&&5!==s.protocolVersion)return this._emitError(new Error("Invalid protocol version"));if(this._pos++,this._pos>=this._list.length)return this._emitError(new Error("Packet too short"));if(a.username=this._list.readUInt8(this._pos)&o.USERNAME_MASK,a.password=this._list.readUInt8(this._pos)&o.PASSWORD_MASK,a.will=this._list.readUInt8(this._pos)&o.WILL_FLAG_MASK,a.will&&(s.will={},s.will.retain=0!=(this._list.readUInt8(this._pos)&o.WILL_RETAIN_MASK),s.will.qos=(this._list.readUInt8(this._pos)&o.WILL_QOS_MASK)>>o.WILL_QOS_SHIFT),s.clean=0!=(this._list.readUInt8(this._pos)&o.CLEAN_SESSION_MASK),this._pos++,s.keepalive=this._parseNum(),-1===s.keepalive)return this._emitError(new Error("Packet too short"));if(5===s.protocolVersion){const e=this._parseProperties();Object.getOwnPropertyNames(e).length&&(s.properties=e)}const l=this._parseString();if(null===l)return this._emitError(new Error("Packet too short"));if(s.clientId=l,i("_parseConnect: packet.clientId: %s",s.clientId),a.will){if(5===s.protocolVersion){const e=this._parseProperties();Object.getOwnPropertyNames(e).length&&(s.will.properties=e)}if(e=this._parseString(),null===e)return this._emitError(new Error("Cannot parse will topic"));if(s.will.topic=e,i("_parseConnect: packet.will.topic: %s",s.will.topic),t=this._parseBuffer(),null===t)return this._emitError(new Error("Cannot parse will payload"));s.will.payload=t,i("_parseConnect: packet.will.paylaod: %s",s.will.payload)}if(a.username){if(r=this._parseString(),null===r)return this._emitError(new Error("Cannot parse username"));s.username=r,i("_parseConnect: packet.username: %s",s.username)}if(a.password){if(n=this._parseBuffer(),null===n)return this._emitError(new Error("Cannot parse password"));s.password=n}return this.settings=s,i("_parseConnect: complete"),s}_parseConnack(){i("_parseConnack");const e=this.packet;if(this._list.length<1)return null;if(e.sessionPresent=!!(this._list.readUInt8(this._pos++)&o.SESSIONPRESENT_MASK),5===this.settings.protocolVersion)this._list.length>=2?e.reasonCode=this._list.readUInt8(this._pos++):e.reasonCode=0;else{if(this._list.length<2)return null;e.returnCode=this._list.readUInt8(this._pos++)}if(-1===e.returnCode||-1===e.reasonCode)return this._emitError(new Error("Cannot parse return code"));if(5===this.settings.protocolVersion){const t=this._parseProperties();Object.getOwnPropertyNames(t).length&&(e.properties=t)}i("_parseConnack: complete")}_parsePublish(){i("_parsePublish");const e=this.packet;if(e.topic=this._parseString(),null===e.topic)return this._emitError(new Error("Cannot parse topic"));if(!(e.qos>0)||this._parseMessageId()){if(5===this.settings.protocolVersion){const t=this._parseProperties();Object.getOwnPropertyNames(t).length&&(e.properties=t)}e.payload=this._list.slice(this._pos,e.length),i("_parsePublish: payload from buffer list: %o",e.payload)}}_parseSubscribe(){i("_parseSubscribe");const e=this.packet;let t,n,r,a,s,c,l;if(1!==e.qos)return this._emitError(new Error("Wrong subscribe header"));if(e.subscriptions=[],this._parseMessageId()){if(5===this.settings.protocolVersion){const t=this._parseProperties();Object.getOwnPropertyNames(t).length&&(e.properties=t)}for(;this._pos<e.length;){if(t=this._parseString(),null===t)return this._emitError(new Error("Cannot parse topic"));if(this._pos>=e.length)return this._emitError(new Error("Malformed Subscribe Payload"));n=this._parseByte(),r=n&o.SUBSCRIBE_OPTIONS_QOS_MASK,c=0!=(n>>o.SUBSCRIBE_OPTIONS_NL_SHIFT&o.SUBSCRIBE_OPTIONS_NL_MASK),s=0!=(n>>o.SUBSCRIBE_OPTIONS_RAP_SHIFT&o.SUBSCRIBE_OPTIONS_RAP_MASK),a=n>>o.SUBSCRIBE_OPTIONS_RH_SHIFT&o.SUBSCRIBE_OPTIONS_RH_MASK,l={topic:t,qos:r},5===this.settings.protocolVersion?(l.nl=c,l.rap=s,l.rh=a):this.settings.bridgeMode&&(l.rh=0,l.rap=!0,l.nl=!0),i("_parseSubscribe: push subscription `%s` to subscription",l),e.subscriptions.push(l)}}}_parseSuback(){i("_parseSuback");const e=this.packet;if(this.packet.granted=[],this._parseMessageId()){if(5===this.settings.protocolVersion){const t=this._parseProperties();Object.getOwnPropertyNames(t).length&&(e.properties=t)}for(;this._pos<this.packet.length;)this.packet.granted.push(this._list.readUInt8(this._pos++))}}_parseUnsubscribe(){i("_parseUnsubscribe");const e=this.packet;if(e.unsubscriptions=[],this._parseMessageId()){if(5===this.settings.protocolVersion){const t=this._parseProperties();Object.getOwnPropertyNames(t).length&&(e.properties=t)}for(;this._pos<e.length;){const t=this._parseString();if(null===t)return this._emitError(new Error("Cannot parse topic"));i("_parseUnsubscribe: push topic `%s` to unsubscriptions",t),e.unsubscriptions.push(t)}}}_parseUnsuback(){i("_parseUnsuback");const e=this.packet;if(!this._parseMessageId())return this._emitError(new Error("Cannot parse messageId"));if(5===this.settings.protocolVersion){const t=this._parseProperties();for(Object.getOwnPropertyNames(t).length&&(e.properties=t),e.granted=[];this._pos<this.packet.length;)this.packet.granted.push(this._list.readUInt8(this._pos++))}}_parseConfirmation(){i("_parseConfirmation: packet.cmd: `%s`",this.packet.cmd);const e=this.packet;if(this._parseMessageId(),5===this.settings.protocolVersion&&(e.length>2?(e.reasonCode=this._parseByte(),i("_parseConfirmation: packet.reasonCode `%d`",e.reasonCode)):e.reasonCode=0,e.length>3)){const t=this._parseProperties();Object.getOwnPropertyNames(t).length&&(e.properties=t)}return!0}_parseDisconnect(){const e=this.packet;if(i("_parseDisconnect"),5===this.settings.protocolVersion){this._list.length>0?e.reasonCode=this._parseByte():e.reasonCode=0;const t=this._parseProperties();Object.getOwnPropertyNames(t).length&&(e.properties=t)}return i("_parseDisconnect result: true"),!0}_parseAuth(){i("_parseAuth");const e=this.packet;if(5!==this.settings.protocolVersion)return this._emitError(new Error("Not supported auth packet for this version MQTT"));e.reasonCode=this._parseByte();const t=this._parseProperties();return Object.getOwnPropertyNames(t).length&&(e.properties=t),i("_parseAuth: result: true"),!0}_parseMessageId(){const e=this.packet;return e.messageId=this._parseNum(),null===e.messageId?(this._emitError(new Error("Cannot parse messageId")),!1):(i("_parseMessageId: packet.messageId %d",e.messageId),!0)}_parseString(e){const t=this._parseNum(),n=t+this._pos;if(-1===t||n>this._list.length||n>this.packet.length)return null;const r=this._list.toString("utf8",this._pos,n);return this._pos+=t,i("_parseString: result: %s",r),r}_parseStringPair(){return i("_parseStringPair"),{name:this._parseString(),value:this._parseString()}}_parseBuffer(){const e=this._parseNum(),t=e+this._pos;if(-1===e||t>this._list.length||t>this.packet.length)return null;const n=this._list.slice(this._pos,t);return this._pos+=e,i("_parseBuffer: result: %o",n),n}_parseNum(){if(this._list.length-this._pos<2)return-1;const e=this._list.readUInt16BE(this._pos);return this._pos+=2,i("_parseNum: result: %s",e),e}_parse4ByteNum(){if(this._list.length-this._pos<4)return-1;const e=this._list.readUInt32BE(this._pos);return this._pos+=4,i("_parse4ByteNum: result: %s",e),e}_parseVarByteNum(e){i("_parseVarByteNum");const t=4;let n,r=0,a=1,s=0,c=!1;const l=this._pos?this._pos:0;for(;r<t&&l+r<this._list.length;){if(n=this._list.readUInt8(l+r++),s+=a*(n&o.VARBYTEINT_MASK),a*=128,0==(n&o.VARBYTEINT_FIN_MASK)){c=!0;break}if(this._list.length<=r)break}return!c&&r===t&&this._list.length>=r&&this._emitError(new Error("Invalid variable byte integer")),l&&(this._pos+=r),c=!!c&&(e?{bytes:r,value:s}:s),i("_parseVarByteNum: result: %o",c),c}_parseByte(){let e;return this._pos<this._list.length&&(e=this._list.readUInt8(this._pos),this._pos++),i("_parseByte: result: %o",e),e}_parseByType(e){switch(i("_parseByType: type: %s",e),e){case"byte":return 0!==this._parseByte();case"int8":return this._parseByte();case"int16":return this._parseNum();case"int32":return this._parse4ByteNum();case"var":return this._parseVarByteNum();case"string":return this._parseString();case"pair":return this._parseStringPair();case"binary":return this._parseBuffer()}}_parseProperties(){i("_parseProperties");const e=this._parseVarByteNum(),t=this._pos+e,n={};for(;this._pos<t;){const e=this._parseByte();if(!e)return this._emitError(new Error("Cannot parse property code type")),!1;const t=o.propertiesCodes[e];if(!t)return this._emitError(new Error("Unknown property")),!1;if("userProperties"!==t)n[t]?(Array.isArray(n[t])||(n[t]=[n[t]]),n[t].push(this._parseByType(o.propertiesTypes[t]))):n[t]=this._parseByType(o.propertiesTypes[t]);else{n[t]||(n[t]=Object.create(null));const e=this._parseByType(o.propertiesTypes[t]);if(n[t][e.name])if(Array.isArray(n[t][e.name]))n[t][e.name].push(e.value);else{const r=n[t][e.name];n[t][e.name]=[r],n[t][e.name].push(e.value)}else n[t][e.name]=e.value}}return n}_newPacket(){return i("_newPacket"),this.packet&&(this._list.consume(this.packet.length),i("_newPacket: parser emit packet: packet.cmd: %s, packet.payload: %s, packet.length: %d",this.packet.cmd,this.packet.payload,this.packet.length),this.emit("packet",this.packet)),i("_newPacket: new packet"),this.packet=new s,this._pos=0,!0}_emitError(e){i("_emitError"),this.error=e,this.emit("error",e)}}t.exports=c},{"./constants":38,"./packet":42,bl:15,debug:18,events:22}],44:[function(e,t,n){(function(n){(function(){const r=e("./constants"),a=n.allocUnsafe(0),s=n.from([0]),o=e("./numbers"),i=e("process-nextick-args").nextTick,c=e("debug")("mqtt-packet:writeToStream"),l=o.cache,d=o.generateNumber,u=o.generateCache,h=o.genBufVariableByteInt,p=o.generate4ByteBuffer;let f=P,m=!0;function g(e,t,n){switch(c("generate called"),t.cork&&(t.cork(),i(y,t)),m&&(m=!1,u()),c("generate: packet.cmd: %s",e.cmd),e.cmd){case"connect":return v(e,t);case"connack":return b(e,t,n);case"publish":return w(e,t,n);case"puback":case"pubrec":case"pubrel":case"pubcomp":return C(e,t,n);case"subscribe":return I(e,t,n);case"suback":return S(e,t,n);case"unsubscribe":return _(e,t,n);case"unsuback":return k(e,t,n);case"pingreq":case"pingresp":return O(e,t);case"disconnect":return T(e,t,n);case"auth":return E(e,t,n);default:return t.emit("error",new Error("Unknown command")),!1}}function y(e){e.uncork()}function v(e,t,a){const s=e||{},o=s.protocolId||"MQTT";let i=s.protocolVersion||4;const c=s.will;let l=s.clean;const d=s.keepalive||0,u=s.clientId||"",h=s.username,p=s.password,m=s.properties;void 0===l&&(l=!0);let g=0;if(!o||"string"!=typeof o&&!n.isBuffer(o))return t.emit("error",new Error("Invalid protocolId")),!1;if(g+=o.length+2,3!==i&&4!==i&&5!==i)return t.emit("error",new Error("Invalid protocol version")),!1;if(g+=1,("string"==typeof u||n.isBuffer(u))&&(u||i>=4)&&(u||l))g+=n.byteLength(u)+2;else{if(i<4)return t.emit("error",new Error("clientId must be supplied before 3.1.1")),!1;if(1*l==0)return t.emit("error",new Error("clientId must be given if cleanSession set to 0")),!1}if("number"!=typeof d||d<0||d>65535||d%1!=0)return t.emit("error",new Error("Invalid keepalive")),!1;if(g+=2,g+=1,5===i){var y=q(t,m);if(!y)return!1;g+=y.length}if(c){if("object"!=typeof c)return t.emit("error",new Error("Invalid will")),!1;if(!c.topic||"string"!=typeof c.topic)return t.emit("error",new Error("Invalid will topic")),!1;if(g+=n.byteLength(c.topic)+2,g+=2,c.payload){if(!(c.payload.length>=0))return t.emit("error",new Error("Invalid will payload")),!1;"string"==typeof c.payload?g+=n.byteLength(c.payload):g+=c.payload.length}var v={};if(5===i){if(!(v=q(t,c.properties)))return!1;g+=v.length}}let b=!1;if(null!=h){if(!K(h))return t.emit("error",new Error("Invalid username")),!1;b=!0,g+=n.byteLength(h)+2}if(null!=p){if(!b)return t.emit("error",new Error("Username is required to use password")),!1;if(!K(p))return t.emit("error",new Error("Invalid password")),!1;g+=F(p)+2}t.write(r.CONNECT_HEADER),R(t,g),D(t,o),s.bridgeMode&&(i+=128),t.write(131===i?r.VERSION131:132===i?r.VERSION132:4===i?r.VERSION4:5===i?r.VERSION5:r.VERSION3);let w=0;return w|=null!=h?r.USERNAME_MASK:0,w|=null!=p?r.PASSWORD_MASK:0,w|=c&&c.retain?r.WILL_RETAIN_MASK:0,w|=c&&c.qos?c.qos<<r.WILL_QOS_SHIFT:0,w|=c?r.WILL_FLAG_MASK:0,w|=l?r.CLEAN_SESSION_MASK:0,t.write(n.from([w])),f(t,d),5===i&&y.write(),D(t,u),c&&(5===i&&v.write(),M(t,c.topic),D(t,c.payload)),null!=h&&D(t,h),null!=p&&D(t,p),!0}function b(e,t,a){const o=a?a.protocolVersion:4,i=e||{},c=5===o?i.reasonCode:i.returnCode,l=i.properties;let d=2;if("number"!=typeof c)return t.emit("error",new Error("Invalid return code")),!1;let u=null;if(5===o){if(u=q(t,l),!u)return!1;d+=u.length}return t.write(r.CONNACK_HEADER),R(t,d),t.write(i.sessionPresent?r.SESSIONPRESENT_HEADER:s),t.write(n.from([c])),null!=u&&u.write(),!0}function w(e,t,s){c("publish: packet: %o",e);const o=s?s.protocolVersion:4,i=e||{},l=i.qos||0,d=i.retain?r.RETAIN_MASK:0,u=i.topic,h=i.payload||a,p=i.messageId,m=i.properties;let g=0;if("string"==typeof u)g+=n.byteLength(u)+2;else{if(!n.isBuffer(u))return t.emit("error",new Error("Invalid topic")),!1;g+=u.length+2}if(n.isBuffer(h)?g+=h.length:g+=n.byteLength(h),l&&"number"!=typeof p)return t.emit("error",new Error("Invalid messageId")),!1;l&&(g+=2);let y=null;if(5===o){if(y=q(t,m),!y)return!1;g+=y.length}return t.write(r.PUBLISH_HEADER[l][i.dup?1:0][d?1:0]),R(t,g),f(t,F(u)),t.write(u),l>0&&f(t,p),null!=y&&y.write(),c("publish: payload: %o",h),t.write(h)}function C(e,t,a){const s=a?a.protocolVersion:4,o=e||{},i=o.cmd||"puback",c=o.messageId,l=o.dup&&"pubrel"===i?r.DUP_MASK:0;let d=0;const u=o.reasonCode,h=o.properties;let p=5===s?3:2;if("pubrel"===i&&(d=1),"number"!=typeof c)return t.emit("error",new Error("Invalid messageId")),!1;let m=null;if(5===s&&"object"==typeof h){if(m=N(t,h,a,p),!m)return!1;p+=m.length}return t.write(r.ACKS[i][d][l][0]),R(t,p),f(t,c),5===s&&t.write(n.from([u])),null!==m&&m.write(),!0}function I(e,t,a){c("subscribe: packet: ");const s=a?a.protocolVersion:4,o=e||{},i=o.dup?r.DUP_MASK:0,l=o.messageId,d=o.subscriptions,u=o.properties;let h=0;if("number"!=typeof l)return t.emit("error",new Error("Invalid messageId")),!1;h+=2;let p=null;if(5===s){if(p=q(t,u),!p)return!1;h+=p.length}if("object"!=typeof d||!d.length)return t.emit("error",new Error("Invalid subscriptions")),!1;for(let e=0;e<d.length;e+=1){const r=d[e].topic,a=d[e].qos;if("string"!=typeof r)return t.emit("error",new Error("Invalid subscriptions - invalid topic")),!1;if("number"!=typeof a)return t.emit("error",new Error("Invalid subscriptions - invalid qos")),!1;if(5===s){if("boolean"!=typeof(d[e].nl||!1))return t.emit("error",new Error("Invalid subscriptions - invalid No Local")),!1;if("boolean"!=typeof(d[e].rap||!1))return t.emit("error",new Error("Invalid subscriptions - invalid Retain as Published")),!1;const n=d[e].rh||0;if("number"!=typeof n||n>2)return t.emit("error",new Error("Invalid subscriptions - invalid Retain Handling")),!1}h+=n.byteLength(r)+2+1}c("subscribe: writing to stream: %o",r.SUBSCRIBE_HEADER),t.write(r.SUBSCRIBE_HEADER[1][i?1:0][0]),R(t,h),f(t,l),null!==p&&p.write();let m=!0;for(const e of d){const a=e.topic,o=e.qos,i=+e.nl,c=+e.rap,l=e.rh;let d;M(t,a),d=r.SUBSCRIBE_OPTIONS_QOS[o],5===s&&(d|=i?r.SUBSCRIBE_OPTIONS_NL:0,d|=c?r.SUBSCRIBE_OPTIONS_RAP:0,d|=l?r.SUBSCRIBE_OPTIONS_RH[l]:0),m=t.write(n.from([d]))}return m}function S(e,t,a){const s=a?a.protocolVersion:4,o=e||{},i=o.messageId,c=o.granted,l=o.properties;let d=0;if("number"!=typeof i)return t.emit("error",new Error("Invalid messageId")),!1;if(d+=2,"object"!=typeof c||!c.length)return t.emit("error",new Error("Invalid qos vector")),!1;for(let e=0;e<c.length;e+=1){if("number"!=typeof c[e])return t.emit("error",new Error("Invalid qos vector")),!1;d+=1}let u=null;if(5===s){if(u=N(t,l,a,d),!u)return!1;d+=u.length}return t.write(r.SUBACK_HEADER),R(t,d),f(t,i),null!==u&&u.write(),t.write(n.from(c))}function _(e,t,a){const s=a?a.protocolVersion:4,o=e||{},i=o.messageId,c=o.dup?r.DUP_MASK:0,l=o.unsubscriptions,d=o.properties;let u=0;if("number"!=typeof i)return t.emit("error",new Error("Invalid messageId")),!1;if(u+=2,"object"!=typeof l||!l.length)return t.emit("error",new Error("Invalid unsubscriptions")),!1;for(let e=0;e<l.length;e+=1){if("string"!=typeof l[e])return t.emit("error",new Error("Invalid unsubscriptions")),!1;u+=n.byteLength(l[e])+2}let h=null;if(5===s){if(h=q(t,d),!h)return!1;u+=h.length}t.write(r.UNSUBSCRIBE_HEADER[1][c?1:0][0]),R(t,u),f(t,i),null!==h&&h.write();let p=!0;for(let e=0;e<l.length;e++)p=M(t,l[e]);return p}function k(e,t,a){const s=a?a.protocolVersion:4,o=e||{},i=o.messageId,c=o.dup?r.DUP_MASK:0,l=o.granted,d=o.properties,u=o.cmd,h=0;let p=2;if("number"!=typeof i)return t.emit("error",new Error("Invalid messageId")),!1;if(5===s){if("object"!=typeof l||!l.length)return t.emit("error",new Error("Invalid qos vector")),!1;for(let e=0;e<l.length;e+=1){if("number"!=typeof l[e])return t.emit("error",new Error("Invalid qos vector")),!1;p+=1}}let m=null;if(5===s){if(m=N(t,d,a,p),!m)return!1;p+=m.length}return t.write(r.ACKS[u][h][c][0]),R(t,p),f(t,i),null!==m&&m.write(),5===s&&t.write(n.from(l)),!0}function O(e,t,n){return t.write(r.EMPTY[e.cmd])}function T(e,t,a){const s=a?a.protocolVersion:4,o=e||{},i=o.reasonCode,c=o.properties;let l=5===s?1:0,d=null;if(5===s){if(d=N(t,c,a,l),!d)return!1;l+=d.length}return t.write(n.from([r.codes.disconnect<<4])),R(t,l),5===s&&t.write(n.from([i])),null!==d&&d.write(),!0}function E(e,t,a){const s=a?a.protocolVersion:4,o=e||{},i=o.reasonCode,c=o.properties;let l=5===s?1:0;5!==s&&t.emit("error",new Error("Invalid mqtt version for auth packet"));const d=N(t,c,a,l);return!!d&&(l+=d.length,t.write(n.from([r.codes.auth<<4])),R(t,l),t.write(n.from([i])),null!==d&&d.write(),!0)}Object.defineProperty(g,"cacheNumbers",{get:()=>f===P,set(e){e?(l&&0!==Object.keys(l).length||(m=!0),f=P):(m=!1,f=U)}});const A={};function R(e,t){if(t>r.VARBYTEINT_MAX)return e.emit("error",new Error(`Invalid variable byte integer: ${t}`)),!1;let n=A[t];return n||(n=h(t),t<16384&&(A[t]=n)),c("writeVarByteInt: writing to stream: %o",n),e.write(n)}function M(e,t){const r=n.byteLength(t);return f(e,r),c("writeString: %s",t),e.write(t,"utf8")}function j(e,t,n){M(e,t),M(e,n)}function P(e,t){return c("writeNumberCached: number: %d",t),c("writeNumberCached: %o",l[t]),e.write(l[t])}function U(e,t){const n=d(t);return c("writeNumberGenerated: %o",n),e.write(n)}function x(e,t){const n=p(t);return c("write4ByteNumber: %o",n),e.write(n)}function D(e,t){"string"==typeof t?M(e,t):t?(f(e,t.length),e.write(t)):f(e,0)}function q(e,t){if("object"!=typeof t||null!=t.length)return{length:1,write(){L(e,{},0)}};let a=0;function s(t,a){let s=0;switch(r.propertiesTypes[t]){case"byte":if("boolean"!=typeof a)return e.emit("error",new Error(`Invalid ${t}: ${a}`)),!1;s+=2;break;case"int8":if("number"!=typeof a||a<0||a>255)return e.emit("error",new Error(`Invalid ${t}: ${a}`)),!1;s+=2;break;case"binary":if(a&&null===a)return e.emit("error",new Error(`Invalid ${t}: ${a}`)),!1;s+=1+n.byteLength(a)+2;break;case"int16":if("number"!=typeof a||a<0||a>65535)return e.emit("error",new Error(`Invalid ${t}: ${a}`)),!1;s+=3;break;case"int32":if("number"!=typeof a||a<0||a>4294967295)return e.emit("error",new Error(`Invalid ${t}: ${a}`)),!1;s+=5;break;case"var":if("number"!=typeof a||a<0||a>268435455)return e.emit("error",new Error(`Invalid ${t}: ${a}`)),!1;s+=1+n.byteLength(h(a));break;case"string":if("string"!=typeof a)return e.emit("error",new Error(`Invalid ${t}: ${a}`)),!1;s+=3+n.byteLength(a.toString());break;case"pair":if("object"!=typeof a)return e.emit("error",new Error(`Invalid ${t}: ${a}`)),!1;s+=Object.getOwnPropertyNames(a).reduce(((e,t)=>{const r=a[t];return Array.isArray(r)?e+=r.reduce(((e,r)=>e+=3+n.byteLength(t.toString())+2+n.byteLength(r.toString())),0):e+=3+n.byteLength(t.toString())+2+n.byteLength(a[t].toString()),e}),0);break;default:return e.emit("error",new Error(`Invalid property ${t}: ${a}`)),!1}return s}if(t)for(const e in t){let n=0,r=0;const o=t[e];if(Array.isArray(o))for(let t=0;t<o.length;t++){if(r=s(e,o[t]),!r)return!1;n+=r}else{if(r=s(e,o),!r)return!1;n=r}if(!n)return!1;a+=n}return{length:n.byteLength(h(a))+a,write(){L(e,t,a)}}}function N(e,t,n,r){const a=["reasonString","userProperties"],s=n&&n.properties&&n.properties.maximumPacketSize?n.properties.maximumPacketSize:0;let o=q(e,t);if(s)for(;r+o.length>s;){const n=a.shift();if(!n||!t[n])return!1;delete t[n],o=q(e,t)}return o}function B(e,t,a){switch(r.propertiesTypes[t]){case"byte":e.write(n.from([r.properties[t]])),e.write(n.from([+a]));break;case"int8":e.write(n.from([r.properties[t]])),e.write(n.from([a]));break;case"binary":e.write(n.from([r.properties[t]])),D(e,a);break;case"int16":e.write(n.from([r.properties[t]])),f(e,a);break;case"int32":e.write(n.from([r.properties[t]])),x(e,a);break;case"var":e.write(n.from([r.properties[t]])),R(e,a);break;case"string":e.write(n.from([r.properties[t]])),M(e,a);break;case"pair":Object.getOwnPropertyNames(a).forEach((s=>{const o=a[s];Array.isArray(o)?o.forEach((a=>{e.write(n.from([r.properties[t]])),j(e,s.toString(),a.toString())})):(e.write(n.from([r.properties[t]])),j(e,s.toString(),o.toString()))}));break;default:return e.emit("error",new Error(`Invalid property ${t} value: ${a}`)),!1}}function L(e,t,n){R(e,n);for(const n in t)if(Object.prototype.hasOwnProperty.call(t,n)&&null!==t[n]){const r=t[n];if(Array.isArray(r))for(let t=0;t<r.length;t++)B(e,n,r[t]);else B(e,n,r)}}function F(e){return e?e instanceof n?e.length:n.byteLength(e):0}function K(e){return"string"==typeof e||e instanceof n}t.exports=g}).call(this)}).call(this,e("buffer").Buffer)},{"./constants":38,"./numbers":41,buffer:17,debug:18,"process-nextick-args":49}],45:[function(e,t,n){var r=1e3,a=60*r,s=60*a,o=24*s,i=7*o,c=365.25*o;function l(e){if(!((e=String(e)).length>100)){var t=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);if(t){var n=parseFloat(t[1]);switch((t[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return n*c;case"weeks":case"week":case"w":return n*i;case"days":case"day":case"d":return n*o;case"hours":case"hour":case"hrs":case"hr":case"h":return n*s;case"minutes":case"minute":case"mins":case"min":case"m":return n*a;case"seconds":case"second":case"secs":case"sec":case"s":return n*r;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return n;default:return}}}}function d(e){var t=Math.abs(e);return t>=o?Math.round(e/o)+"d":t>=s?Math.round(e/s)+"h":t>=a?Math.round(e/a)+"m":t>=r?Math.round(e/r)+"s":e+"ms"}function u(e){var t=Math.abs(e);return t>=o?h(e,t,o,"day"):t>=s?h(e,t,s,"hour"):t>=a?h(e,t,a,"minute"):t>=r?h(e,t,r,"second"):e+" ms"}function h(e,t,n,r){var a=t>=1.5*n;return Math.round(e/n)+" "+r+(a?"s":"")}t.exports=function(e,t){t=t||{};var n=typeof e;if("string"===n&&e.length>0)return l(e);if("number"===n&&isFinite(e))return t.long?u(e):d(e);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(e))}},{}],46:[function(e,t,n){const r=e("./lib/number-allocator.js");t.exports.NumberAllocator=r},{"./lib/number-allocator.js":47}],47:[function(e,t,n){const r=e("js-sdsl").Set,a=e("debug")("number-allocator:trace"),s=e("debug")("number-allocator:error");function o(e,t){this.low=e,this.high=t}function i(e,t){if(!(this instanceof i))return new i(e,t);this.min=e,this.max=t,this.ss=new r([],((e,t)=>e.compare(t))),a("Create"),this.clear()}o.prototype.equals=function(e){return this.low===e.low&&this.high===e.high},o.prototype.compare=function(e){return this.low<e.low&&this.high<e.low?-1:e.low<this.low&&e.high<this.low?1:0},i.prototype.firstVacant=function(){return 0===this.ss.size()?null:this.ss.front().low},i.prototype.alloc=function(){if(0===this.ss.size())return a("alloc():empty"),null;const e=this.ss.front(),t=e.low;return t+1<=e.high?++e.low:this.ss.eraseElementByPos(0),a("alloc():"+t),t},i.prototype.use=function(e){const t=new o(e,e),n=this.ss.lowerBound(t);if(n){if(n.equals(t))return this.ss.eraseElementByValue(n),a("use():"+e),!0;if(n.low>e)return!1;if(n.low===e)return++n.low,a("use():"+e),!0;if(n.high===e)return--n.high,a("use():"+e),!0;const r=n.low;return n.low=e+1,this.ss.insert(new o(r,e-1)),a("use():"+e),!0}return a("use():failed"),!1},i.prototype.free=function(e){if(e<this.min||e>this.max)return void s("free():"+e+" is out of range");const t=new o(e,e),n=this.ss.lowerBound(t);if(n){if(n.low<=e&&e<=n.high)return void s("free():"+e+" has already been vacant");if(n===this.ss.front())e+1===n.low?--n.low:this.ss.insert(t);else{const r=this.ss.reverseLowerBound(t);r.high+1===e?e+1===n.low?(this.ss.eraseElementByValue(r),n.low=r.low):r.high=e:e+1===n.low?n.low=e:this.ss.insert(t)}}else{if(n===this.ss.front())return void this.ss.insert(t);const r=this.ss.reverseLowerBound(t);r.high+1===e?r.high=e:this.ss.insert(t)}a("free():"+e)},i.prototype.clear=function(){a("clear()"),this.ss.clear(),this.ss.insert(new o(this.min,this.max))},i.prototype.intervalCount=function(){return this.ss.size()},i.prototype.dump=function(){console.log("length:"+this.ss.size());for(const e of this.ss)console.log(e)},t.exports=i},{debug:18,"js-sdsl":36}],48:[function(e,t,n){var r=e("wrappy");function a(e){var t=function(){return t.called?t.value:(t.called=!0,t.value=e.apply(this,arguments))};return t.called=!1,t}function s(e){var t=function(){if(t.called)throw new Error(t.onceError);return t.called=!0,t.value=e.apply(this,arguments)},n=e.name||"Function wrapped with `once`";return t.onceError=n+" shouldn't be called more than once",t.called=!1,t}t.exports=r(a),t.exports.strict=r(s),a.proto=a((function(){Object.defineProperty(Function.prototype,"once",{value:function(){return a(this)},configurable:!0}),Object.defineProperty(Function.prototype,"onceStrict",{value:function(){return s(this)},configurable:!0})}))},{wrappy:79}],49:[function(e,t,n){(function(e){(function(){function n(t,n,r,a){if("function"!=typeof t)throw new TypeError('"callback" argument must be a function');var s,o,i=arguments.length;switch(i){case 0:case 1:return e.nextTick(t);case 2:return e.nextTick((function(){t.call(null,n)}));case 3:return e.nextTick((function(){t.call(null,n,r)}));case 4:return e.nextTick((function(){t.call(null,n,r,a)}));default:for(s=new Array(i-1),o=0;o<s.length;)s[o++]=arguments[o];return e.nextTick((function(){t.apply(null,s)}))}}void 0===e||!e.version||0===e.version.indexOf("v0.")||0===e.version.indexOf("v1.")&&0!==e.version.indexOf("v1.8.")?t.exports={nextTick:n}:t.exports=e}).call(this)}).call(this,e("_process"))},{_process:50}],50:[function(e,t,n){var r,a,s=t.exports={};function o(){throw new Error("setTimeout has not been defined")}function i(){throw new Error("clearTimeout has not been defined")}function c(e){if(r===setTimeout)return setTimeout(e,0);if((r===o||!r)&&setTimeout)return r=setTimeout,setTimeout(e,0);try{return r(e,0)}catch(t){try{return r.call(null,e,0)}catch(t){return r.call(this,e,0)}}}function l(e){if(a===clearTimeout)return clearTimeout(e);if((a===i||!a)&&clearTimeout)return a=clearTimeout,clearTimeout(e);try{return a(e)}catch(t){try{return a.call(null,e)}catch(t){return a.call(this,e)}}}!function(){try{r="function"==typeof setTimeout?setTimeout:o}catch(e){r=o}try{a="function"==typeof clearTimeout?clearTimeout:i}catch(e){a=i}}();var d,u=[],h=!1,p=-1;function f(){h&&d&&(h=!1,d.length?u=d.concat(u):p=-1,u.length&&m())}function m(){if(!h){var e=c(f);h=!0;for(var t=u.length;t;){for(d=u,u=[];++p<t;)d&&d[p].run();p=-1,t=u.length}d=null,h=!1,l(e)}}function g(e,t){this.fun=e,this.array=t}function y(){}s.nextTick=function(e){var t=new Array(arguments.length-1);if(arguments.length>1)for(var n=1;n<arguments.length;n++)t[n-1]=arguments[n];u.push(new g(e,t)),1!==u.length||h||c(m)},g.prototype.run=function(){this.fun.apply(null,this.array)},s.title="browser",s.browser=!0,s.env={},s.argv=[],s.version="",s.versions={},s.on=y,s.addListener=y,s.once=y,s.off=y,s.removeListener=y,s.removeAllListeners=y,s.emit=y,s.prependListener=y,s.prependOnceListener=y,s.listeners=function(e){return[]},s.binding=function(e){throw new Error("process.binding is not supported")},s.cwd=function(){return"/"},s.chdir=function(e){throw new Error("process.chdir is not supported")},s.umask=function(){return 0}},{}],51:[function(e,t,n){(function(e){(function(){!function(r){var a="object"==typeof n&&n&&!n.nodeType&&n,s="object"==typeof t&&t&&!t.nodeType&&t,o="object"==typeof e&&e;o.global!==o&&o.window!==o&&o.self!==o||(r=o);var i,c,l=2147483647,d=36,u=1,h=26,p=38,f=700,m=72,g=128,y="-",v=/^xn--/,b=/[^\x20-\x7E]/,w=/[\x2E\u3002\uFF0E\uFF61]/g,C={overflow:"Overflow: input needs wider integers to process","not-basic":"Illegal input >= 0x80 (not a basic code point)","invalid-input":"Invalid input"},I=d-u,S=Math.floor,_=String.fromCharCode;function k(e){throw new RangeError(C[e])}function O(e,t){for(var n=e.length,r=[];n--;)r[n]=t(e[n]);return r}function T(e,t){var n=e.split("@"),r="";return n.length>1&&(r=n[0]+"@",e=n[1]),r+O((e=e.replace(w,".")).split("."),t).join(".")}function E(e){for(var t,n,r=[],a=0,s=e.length;a<s;)(t=e.charCodeAt(a++))>=55296&&t<=56319&&a<s?56320==(64512&(n=e.charCodeAt(a++)))?r.push(((1023&t)<<10)+(1023&n)+65536):(r.push(t),a--):r.push(t);return r}function A(e){return O(e,(function(e){var t="";return e>65535&&(t+=_((e-=65536)>>>10&1023|55296),e=56320|1023&e),t+=_(e)})).join("")}function R(e){return e-48<10?e-22:e-65<26?e-65:e-97<26?e-97:d}function M(e,t){return e+22+75*(e<26)-((0!=t)<<5)}function j(e,t,n){var r=0;for(e=n?S(e/f):e>>1,e+=S(e/t);e>I*h>>1;r+=d)e=S(e/I);return S(r+(I+1)*e/(e+p))}function P(e){var t,n,r,a,s,o,i,c,p,f,v=[],b=e.length,w=0,C=g,I=m;for((n=e.lastIndexOf(y))<0&&(n=0),r=0;r<n;++r)e.charCodeAt(r)>=128&&k("not-basic"),v.push(e.charCodeAt(r));for(a=n>0?n+1:0;a<b;){for(s=w,o=1,i=d;a>=b&&k("invalid-input"),((c=R(e.charCodeAt(a++)))>=d||c>S((l-w)/o))&&k("overflow"),w+=c*o,!(c<(p=i<=I?u:i>=I+h?h:i-I));i+=d)o>S(l/(f=d-p))&&k("overflow"),o*=f;I=j(w-s,t=v.length+1,0==s),S(w/t)>l-C&&k("overflow"),C+=S(w/t),w%=t,v.splice(w++,0,C)}return A(v)}function U(e){var t,n,r,a,s,o,i,c,p,f,v,b,w,C,I,O=[];for(b=(e=E(e)).length,t=g,n=0,s=m,o=0;o<b;++o)(v=e[o])<128&&O.push(_(v));for(r=a=O.length,a&&O.push(y);r<b;){for(i=l,o=0;o<b;++o)(v=e[o])>=t&&v<i&&(i=v);for(i-t>S((l-n)/(w=r+1))&&k("overflow"),n+=(i-t)*w,t=i,o=0;o<b;++o)if((v=e[o])<t&&++n>l&&k("overflow"),v==t){for(c=n,p=d;!(c<(f=p<=s?u:p>=s+h?h:p-s));p+=d)I=c-f,C=d-f,O.push(_(M(f+I%C,0))),c=S(I/C);O.push(_(M(c,0))),s=j(n,w,r==a),n=0,++r}++n,++t}return O.join("")}function x(e){return T(e,(function(e){return v.test(e)?P(e.slice(4).toLowerCase()):e}))}function D(e){return T(e,(function(e){return b.test(e)?"xn--"+U(e):e}))}if(i={version:"1.4.1",ucs2:{decode:E,encode:A},decode:P,encode:U,toASCII:D,toUnicode:x},a&&s)if(t.exports==a)s.exports=i;else for(c in i)i.hasOwnProperty(c)&&(a[c]=i[c]);else r.punycode=i}(this)}).call(this)}).call(this,void 0!==qt?qt:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],52:[function(e,t,n){function r(e,t){return Object.prototype.hasOwnProperty.call(e,t)}t.exports=function(e,t,n,s){t=t||"&",n=n||"=";var o={};if("string"!=typeof e||0===e.length)return o;var i=/\+/g;e=e.split(t);var c=1e3;s&&"number"==typeof s.maxKeys&&(c=s.maxKeys);var l=e.length;c>0&&l>c&&(l=c);for(var d=0;d<l;++d){var u,h,p,f,m=e[d].replace(i,"%20"),g=m.indexOf(n);g>=0?(u=m.substr(0,g),h=m.substr(g+1)):(u=m,h=""),p=decodeURIComponent(u),f=decodeURIComponent(h),r(o,p)?a(o[p])?o[p].push(f):o[p]=[o[p],f]:o[p]=f}return o};var a=Array.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)}},{}],53:[function(e,t,n){var r=function(e){switch(typeof e){case"string":return e;case"boolean":return e?"true":"false";case"number":return isFinite(e)?e:"";default:return""}};t.exports=function(e,t,n,i){return t=t||"&",n=n||"=",null===e&&(e=void 0),"object"==typeof e?s(o(e),(function(o){var i=encodeURIComponent(r(o))+n;return a(e[o])?s(e[o],(function(e){return i+encodeURIComponent(r(e))})).join(t):i+encodeURIComponent(r(e[o]))})).join(t):i?encodeURIComponent(r(i))+n+encodeURIComponent(r(e)):""};var a=Array.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)};function s(e,t){if(e.map)return e.map(t);for(var n=[],r=0;r<e.length;r++)n.push(t(e[r],r));return n}var o=Object.keys||function(e){var t=[];for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.push(n);return t}},{}],54:[function(e,t,n){n.decode=n.parse=e("./decode"),n.encode=n.stringify=e("./encode")},{"./decode":52,"./encode":53}],55:[function(e,t,n){function r(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,e.__proto__=t}var a={};function s(e,t,n){function s(e,n,r){return"string"==typeof t?t:t(e,n,r)}n||(n=Error);var o=function(e){function t(t,n,r){return e.call(this,s(t,n,r))||this}return r(t,e),t}(n);o.prototype.name=n.name,o.prototype.code=e,a[e]=o}function o(e,t){if(Array.isArray(e)){var n=e.length;return e=e.map((function(e){return String(e)})),n>2?"one of ".concat(t," ").concat(e.slice(0,n-1).join(", "),", or ")+e[n-1]:2===n?"one of ".concat(t," ").concat(e[0]," or ").concat(e[1]):"of ".concat(t," ").concat(e[0])}return"of ".concat(t," ").concat(String(e))}function i(e,t,n){return e.substr(!n||n<0?0:+n,t.length)===t}function c(e,t,n){return(void 0===n||n>e.length)&&(n=e.length),e.substring(n-t.length,n)===t}function l(e,t,n){return"number"!=typeof n&&(n=0),!(n+t.length>e.length)&&-1!==e.indexOf(t,n)}s("ERR_INVALID_OPT_VALUE",(function(e,t){return'The value "'+t+'" is invalid for option "'+e+'"'}),TypeError),s("ERR_INVALID_ARG_TYPE",(function(e,t,n){var r,a;if("string"==typeof t&&i(t,"not ")?(r="must not be",t=t.replace(/^not /,"")):r="must be",c(e," argument"))a="The ".concat(e," ").concat(r," ").concat(o(t,"type"));else{var s=l(e,".")?"property":"argument";a='The "'.concat(e,'" ').concat(s," ").concat(r," ").concat(o(t,"type"))}return a+=". Received type ".concat(typeof n)}),TypeError),s("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF"),s("ERR_METHOD_NOT_IMPLEMENTED",(function(e){return"The "+e+" method is not implemented"})),s("ERR_STREAM_PREMATURE_CLOSE","Premature close"),s("ERR_STREAM_DESTROYED",(function(e){return"Cannot call "+e+" after a stream was destroyed"})),s("ERR_MULTIPLE_CALLBACK","Callback called multiple times"),s("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable"),s("ERR_STREAM_WRITE_AFTER_END","write after end"),s("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError),s("ERR_UNKNOWN_ENCODING",(function(e){return"Unknown encoding: "+e}),TypeError),s("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event"),t.exports.codes=a},{}],56:[function(e,t,n){(function(n){(function(){var r=Object.keys||function(e){var t=[];for(var n in e)t.push(n);return t};t.exports=l;var a=e("./_stream_readable"),s=e("./_stream_writable");e("inherits")(l,a);for(var o=r(s.prototype),i=0;i<o.length;i++){var c=o[i];l.prototype[c]||(l.prototype[c]=s.prototype[c])}function l(e){if(!(this instanceof l))return new l(e);a.call(this,e),s.call(this,e),this.allowHalfOpen=!0,e&&(!1===e.readable&&(this.readable=!1),!1===e.writable&&(this.writable=!1),!1===e.allowHalfOpen&&(this.allowHalfOpen=!1,this.once("end",d)))}function d(){this._writableState.ended||n.nextTick(u,this)}function u(e){e.end()}Object.defineProperty(l.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),Object.defineProperty(l.prototype,"writableBuffer",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}}),Object.defineProperty(l.prototype,"writableLength",{enumerable:!1,get:function(){return this._writableState.length}}),Object.defineProperty(l.prototype,"destroyed",{enumerable:!1,get:function(){return void 0!==this._readableState&&void 0!==this._writableState&&this._readableState.destroyed&&this._writableState.destroyed},set:function(e){void 0!==this._readableState&&void 0!==this._writableState&&(this._readableState.destroyed=e,this._writableState.destroyed=e)}})}).call(this)}).call(this,e("_process"))},{"./_stream_readable":58,"./_stream_writable":60,_process:50,inherits:24}],57:[function(e,t,n){t.exports=a;var r=e("./_stream_transform");function a(e){if(!(this instanceof a))return new a(e);r.call(this,e)}e("inherits")(a,r),a.prototype._transform=function(e,t,n){n(null,e)}},{"./_stream_transform":59,inherits:24}],58:[function(e,t,n){(function(n,r){(function(){var a;t.exports=E,E.ReadableState=T,e("events").EventEmitter;var s=function(e,t){return e.listeners(t).length},o=e("./internal/streams/stream"),i=e("buffer").Buffer,c=r.Uint8Array||function(){};function l(e){return i.from(e)}function d(e){return i.isBuffer(e)||e instanceof c}var u,h=e("util");u=h&&h.debuglog?h.debuglog("stream"):function(){};var p,f,m,g=e("./internal/streams/buffer_list"),y=e("./internal/streams/destroy"),v=e("./internal/streams/state").getHighWaterMark,b=e("../errors").codes,w=b.ERR_INVALID_ARG_TYPE,C=b.ERR_STREAM_PUSH_AFTER_EOF,I=b.ERR_METHOD_NOT_IMPLEMENTED,S=b.ERR_STREAM_UNSHIFT_AFTER_END_EVENT;e("inherits")(E,o);var _=y.errorOrDestroy,k=["error","close","destroy","pause","resume"];function O(e,t,n){if("function"==typeof e.prependListener)return e.prependListener(t,n);e._events&&e._events[t]?Array.isArray(e._events[t])?e._events[t].unshift(n):e._events[t]=[n,e._events[t]]:e.on(t,n)}function T(t,n,r){a=a||e("./_stream_duplex"),t=t||{},"boolean"!=typeof r&&(r=n instanceof a),this.objectMode=!!t.objectMode,r&&(this.objectMode=this.objectMode||!!t.readableObjectMode),this.highWaterMark=v(this,t,"readableHighWaterMark",r),this.buffer=new g,this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=null,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.resumeScheduled=!1,this.paused=!0,this.emitClose=!1!==t.emitClose,this.autoDestroy=!!t.autoDestroy,this.destroyed=!1,this.defaultEncoding=t.defaultEncoding||"utf8",this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,t.encoding&&(p||(p=e("string_decoder/").StringDecoder),this.decoder=new p(t.encoding),this.encoding=t.encoding)}function E(t){if(a=a||e("./_stream_duplex"),!(this instanceof E))return new E(t);var n=this instanceof a;this._readableState=new T(t,this,n),this.readable=!0,t&&("function"==typeof t.read&&(this._read=t.read),"function"==typeof t.destroy&&(this._destroy=t.destroy)),o.call(this)}function A(e,t,n,r,a){u("readableAddChunk",t);var s,o=e._readableState;if(null===t)o.reading=!1,x(e,o);else if(a||(s=M(o,t)),s)_(e,s);else if(o.objectMode||t&&t.length>0)if("string"==typeof t||o.objectMode||Object.getPrototypeOf(t)===i.prototype||(t=l(t)),r)o.endEmitted?_(e,new S):R(e,o,t,!0);else if(o.ended)_(e,new C);else{if(o.destroyed)return!1;o.reading=!1,o.decoder&&!n?(t=o.decoder.write(t),o.objectMode||0!==t.length?R(e,o,t,!1):N(e,o)):R(e,o,t,!1)}else r||(o.reading=!1,N(e,o));return!o.ended&&(o.length<o.highWaterMark||0===o.length)}function R(e,t,n,r){t.flowing&&0===t.length&&!t.sync?(t.awaitDrain=0,e.emit("data",n)):(t.length+=t.objectMode?1:n.length,r?t.buffer.unshift(n):t.buffer.push(n),t.needReadable&&D(e)),N(e,t)}function M(e,t){var n;return d(t)||"string"==typeof t||void 0===t||e.objectMode||(n=new w("chunk",["string","Buffer","Uint8Array"],t)),n}Object.defineProperty(E.prototype,"destroyed",{enumerable:!1,get:function(){return void 0!==this._readableState&&this._readableState.destroyed},set:function(e){this._readableState&&(this._readableState.destroyed=e)}}),E.prototype.destroy=y.destroy,E.prototype._undestroy=y.undestroy,E.prototype._destroy=function(e,t){t(e)},E.prototype.push=function(e,t){var n,r=this._readableState;return r.objectMode?n=!0:"string"==typeof e&&((t=t||r.defaultEncoding)!==r.encoding&&(e=i.from(e,t),t=""),n=!0),A(this,e,t,!1,n)},E.prototype.unshift=function(e){return A(this,e,null,!0,!1)},E.prototype.isPaused=function(){return!1===this._readableState.flowing},E.prototype.setEncoding=function(t){p||(p=e("string_decoder/").StringDecoder);var n=new p(t);this._readableState.decoder=n,this._readableState.encoding=this._readableState.decoder.encoding;for(var r=this._readableState.buffer.head,a="";null!==r;)a+=n.write(r.data),r=r.next;return this._readableState.buffer.clear(),""!==a&&this._readableState.buffer.push(a),this._readableState.length=a.length,this};var j=1073741824;function P(e){return e>=j?e=j:(e--,e|=e>>>1,e|=e>>>2,e|=e>>>4,e|=e>>>8,e|=e>>>16,e++),e}function U(e,t){return e<=0||0===t.length&&t.ended?0:t.objectMode?1:e!=e?t.flowing&&t.length?t.buffer.head.data.length:t.length:(e>t.highWaterMark&&(t.highWaterMark=P(e)),e<=t.length?e:t.ended?t.length:(t.needReadable=!0,0))}function x(e,t){if(u("onEofChunk"),!t.ended){if(t.decoder){var n=t.decoder.end();n&&n.length&&(t.buffer.push(n),t.length+=t.objectMode?1:n.length)}t.ended=!0,t.sync?D(e):(t.needReadable=!1,t.emittedReadable||(t.emittedReadable=!0,q(e)))}}function D(e){var t=e._readableState;u("emitReadable",t.needReadable,t.emittedReadable),t.needReadable=!1,t.emittedReadable||(u("emitReadable",t.flowing),t.emittedReadable=!0,n.nextTick(q,e))}function q(e){var t=e._readableState;u("emitReadable_",t.destroyed,t.length,t.ended),t.destroyed||!t.length&&!t.ended||(e.emit("readable"),t.emittedReadable=!1),t.needReadable=!t.flowing&&!t.ended&&t.length<=t.highWaterMark,z(e)}function N(e,t){t.readingMore||(t.readingMore=!0,n.nextTick(B,e,t))}function B(e,t){for(;!t.reading&&!t.ended&&(t.length<t.highWaterMark||t.flowing&&0===t.length);){var n=t.length;if(u("maybeReadMore read 0"),e.read(0),n===t.length)break}t.readingMore=!1}function L(e){return function(){var t=e._readableState;u("pipeOnDrain",t.awaitDrain),t.awaitDrain&&t.awaitDrain--,0===t.awaitDrain&&s(e,"data")&&(t.flowing=!0,z(e))}}function F(e){var t=e._readableState;t.readableListening=e.listenerCount("readable")>0,t.resumeScheduled&&!t.paused?t.flowing=!0:e.listenerCount("data")>0&&e.resume()}function K(e){u("readable nexttick read 0"),e.read(0)}function $(e,t){t.resumeScheduled||(t.resumeScheduled=!0,n.nextTick(Q,e,t))}function Q(e,t){u("resume",t.reading),t.reading||e.read(0),t.resumeScheduled=!1,e.emit("resume"),z(e),t.flowing&&!t.reading&&e.read(0)}function z(e){var t=e._readableState;for(u("flow",t.flowing);t.flowing&&null!==e.read(););}function V(e,t){return 0===t.length?null:(t.objectMode?n=t.buffer.shift():!e||e>=t.length?(n=t.decoder?t.buffer.join(""):1===t.buffer.length?t.buffer.first():t.buffer.concat(t.length),t.buffer.clear()):n=t.buffer.consume(e,t.decoder),n);var n}function H(e){var t=e._readableState;u("endReadable",t.endEmitted),t.endEmitted||(t.ended=!0,n.nextTick(J,t,e))}function J(e,t){if(u("endReadableNT",e.endEmitted,e.length),!e.endEmitted&&0===e.length&&(e.endEmitted=!0,t.readable=!1,t.emit("end"),e.autoDestroy)){var n=t._writableState;(!n||n.autoDestroy&&n.finished)&&t.destroy()}}function W(e,t){for(var n=0,r=e.length;n<r;n++)if(e[n]===t)return n;return-1}E.prototype.read=function(e){u("read",e),e=parseInt(e,10);var t=this._readableState,n=e;if(0!==e&&(t.emittedReadable=!1),0===e&&t.needReadable&&((0!==t.highWaterMark?t.length>=t.highWaterMark:t.length>0)||t.ended))return u("read: emitReadable",t.length,t.ended),0===t.length&&t.ended?H(this):D(this),null;if(0===(e=U(e,t))&&t.ended)return 0===t.length&&H(this),null;var r,a=t.needReadable;return u("need readable",a),(0===t.length||t.length-e<t.highWaterMark)&&u("length less than watermark",a=!0),t.ended||t.reading?u("reading or ended",a=!1):a&&(u("do read"),t.reading=!0,t.sync=!0,0===t.length&&(t.needReadable=!0),this._read(t.highWaterMark),t.sync=!1,t.reading||(e=U(n,t))),null===(r=e>0?V(e,t):null)?(t.needReadable=t.length<=t.highWaterMark,e=0):(t.length-=e,t.awaitDrain=0),0===t.length&&(t.ended||(t.needReadable=!0),n!==e&&t.ended&&H(this)),null!==r&&this.emit("data",r),r},E.prototype._read=function(e){_(this,new I("_read()"))},E.prototype.pipe=function(e,t){var r=this,a=this._readableState;switch(a.pipesCount){case 0:a.pipes=e;break;case 1:a.pipes=[a.pipes,e];break;default:a.pipes.push(e)}a.pipesCount+=1,u("pipe count=%d opts=%j",a.pipesCount,t);var o=t&&!1===t.end||e===n.stdout||e===n.stderr?y:c;function i(e,t){u("onunpipe"),e===r&&t&&!1===t.hasUnpiped&&(t.hasUnpiped=!0,h())}function c(){u("onend"),e.end()}a.endEmitted?n.nextTick(o):r.once("end",o),e.on("unpipe",i);var l=L(r);e.on("drain",l);var d=!1;function h(){u("cleanup"),e.removeListener("close",m),e.removeListener("finish",g),e.removeListener("drain",l),e.removeListener("error",f),e.removeListener("unpipe",i),r.removeListener("end",c),r.removeListener("end",y),r.removeListener("data",p),d=!0,!a.awaitDrain||e._writableState&&!e._writableState.needDrain||l()}function p(t){u("ondata");var n=e.write(t);u("dest.write",n),!1===n&&((1===a.pipesCount&&a.pipes===e||a.pipesCount>1&&-1!==W(a.pipes,e))&&!d&&(u("false write response, pause",a.awaitDrain),a.awaitDrain++),r.pause())}function f(t){u("onerror",t),y(),e.removeListener("error",f),0===s(e,"error")&&_(e,t)}function m(){e.removeListener("finish",g),y()}function g(){u("onfinish"),e.removeListener("close",m),y()}function y(){u("unpipe"),r.unpipe(e)}return r.on("data",p),O(e,"error",f),e.once("close",m),e.once("finish",g),e.emit("pipe",r),a.flowing||(u("pipe resume"),r.resume()),e},E.prototype.unpipe=function(e){var t=this._readableState,n={hasUnpiped:!1};if(0===t.pipesCount)return this;if(1===t.pipesCount)return e&&e!==t.pipes||(e||(e=t.pipes),t.pipes=null,t.pipesCount=0,t.flowing=!1,e&&e.emit("unpipe",this,n)),this;if(!e){var r=t.pipes,a=t.pipesCount;t.pipes=null,t.pipesCount=0,t.flowing=!1;for(var s=0;s<a;s++)r[s].emit("unpipe",this,{hasUnpiped:!1});return this}var o=W(t.pipes,e);return-1===o||(t.pipes.splice(o,1),t.pipesCount-=1,1===t.pipesCount&&(t.pipes=t.pipes[0]),e.emit("unpipe",this,n)),this},E.prototype.on=function(e,t){var r=o.prototype.on.call(this,e,t),a=this._readableState;return"data"===e?(a.readableListening=this.listenerCount("readable")>0,!1!==a.flowing&&this.resume()):"readable"===e&&(a.endEmitted||a.readableListening||(a.readableListening=a.needReadable=!0,a.flowing=!1,a.emittedReadable=!1,u("on readable",a.length,a.reading),a.length?D(this):a.reading||n.nextTick(K,this))),r},E.prototype.addListener=E.prototype.on,E.prototype.removeListener=function(e,t){var r=o.prototype.removeListener.call(this,e,t);return"readable"===e&&n.nextTick(F,this),r},E.prototype.removeAllListeners=function(e){var t=o.prototype.removeAllListeners.apply(this,arguments);return"readable"!==e&&void 0!==e||n.nextTick(F,this),t},E.prototype.resume=function(){var e=this._readableState;return e.flowing||(u("resume"),e.flowing=!e.readableListening,$(this,e)),e.paused=!1,this},E.prototype.pause=function(){return u("call pause flowing=%j",this._readableState.flowing),!1!==this._readableState.flowing&&(u("pause"),this._readableState.flowing=!1,this.emit("pause")),this._readableState.paused=!0,this},E.prototype.wrap=function(e){var t=this,n=this._readableState,r=!1;for(var a in e.on("end",(function(){if(u("wrapped end"),n.decoder&&!n.ended){var e=n.decoder.end();e&&e.length&&t.push(e)}t.push(null)})),e.on("data",(function(a){u("wrapped data"),n.decoder&&(a=n.decoder.write(a)),n.objectMode&&null==a||(n.objectMode||a&&a.length)&&(t.push(a)||(r=!0,e.pause()))})),e)void 0===this[a]&&"function"==typeof e[a]&&(this[a]=function(t){return function(){return e[t].apply(e,arguments)}}(a));for(var s=0;s<k.length;s++)e.on(k[s],this.emit.bind(this,k[s]));return this._read=function(t){u("wrapped _read",t),r&&(r=!1,e.resume())},this},"function"==typeof Symbol&&(E.prototype[Symbol.asyncIterator]=function(){return void 0===f&&(f=e("./internal/streams/async_iterator")),f(this)}),Object.defineProperty(E.prototype,"readableHighWaterMark",{enumerable:!1,get:function(){return this._readableState.highWaterMark}}),Object.defineProperty(E.prototype,"readableBuffer",{enumerable:!1,get:function(){return this._readableState&&this._readableState.buffer}}),Object.defineProperty(E.prototype,"readableFlowing",{enumerable:!1,get:function(){return this._readableState.flowing},set:function(e){this._readableState&&(this._readableState.flowing=e)}}),E._fromList=V,Object.defineProperty(E.prototype,"readableLength",{enumerable:!1,get:function(){return this._readableState.length}}),"function"==typeof Symbol&&(E.from=function(t,n){return void 0===m&&(m=e("./internal/streams/from")),m(E,t,n)})}).call(this)}).call(this,e("_process"),void 0!==qt?qt:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"../errors":55,"./_stream_duplex":56,"./internal/streams/async_iterator":61,"./internal/streams/buffer_list":62,"./internal/streams/destroy":63,"./internal/streams/from":65,"./internal/streams/state":67,"./internal/streams/stream":68,_process:50,buffer:17,events:22,inherits:24,"string_decoder/":75,util:16}],59:[function(e,t,n){t.exports=d;var r=e("../errors").codes,a=r.ERR_METHOD_NOT_IMPLEMENTED,s=r.ERR_MULTIPLE_CALLBACK,o=r.ERR_TRANSFORM_ALREADY_TRANSFORMING,i=r.ERR_TRANSFORM_WITH_LENGTH_0,c=e("./_stream_duplex");function l(e,t){var n=this._transformState;n.transforming=!1;var r=n.writecb;if(null===r)return this.emit("error",new s);n.writechunk=null,n.writecb=null,null!=t&&this.push(t),r(e);var a=this._readableState;a.reading=!1,(a.needReadable||a.length<a.highWaterMark)&&this._read(a.highWaterMark)}function d(e){if(!(this instanceof d))return new d(e);c.call(this,e),this._transformState={afterTransform:l.bind(this),needTransform:!1,transforming:!1,writecb:null,writechunk:null,writeencoding:null},this._readableState.needReadable=!0,this._readableState.sync=!1,e&&("function"==typeof e.transform&&(this._transform=e.transform),"function"==typeof e.flush&&(this._flush=e.flush)),this.on("prefinish",u)}function u(){var e=this;"function"!=typeof this._flush||this._readableState.destroyed?h(this,null,null):this._flush((function(t,n){h(e,t,n)}))}function h(e,t,n){if(t)return e.emit("error",t);if(null!=n&&e.push(n),e._writableState.length)throw new i;if(e._transformState.transforming)throw new o;return e.push(null)}e("inherits")(d,c),d.prototype.push=function(e,t){return this._transformState.needTransform=!1,c.prototype.push.call(this,e,t)},d.prototype._transform=function(e,t,n){n(new a("_transform()"))},d.prototype._write=function(e,t,n){var r=this._transformState;if(r.writecb=n,r.writechunk=e,r.writeencoding=t,!r.transforming){var a=this._readableState;(r.needTransform||a.needReadable||a.length<a.highWaterMark)&&this._read(a.highWaterMark)}},d.prototype._read=function(e){var t=this._transformState;null===t.writechunk||t.transforming?t.needTransform=!0:(t.transforming=!0,this._transform(t.writechunk,t.writeencoding,t.afterTransform))},d.prototype._destroy=function(e,t){c.prototype._destroy.call(this,e,(function(e){t(e)}))}},{"../errors":55,"./_stream_duplex":56,inherits:24}],60:[function(e,t,n){(function(n,r){(function(){function a(e){var t=this;this.next=null,this.entry=null,this.finish=function(){Q(t,e)}}var s;t.exports=T,T.WritableState=O;var o={deprecate:e("util-deprecate")},i=e("./internal/streams/stream"),c=e("buffer").Buffer,l=r.Uint8Array||function(){};function d(e){return c.from(e)}function u(e){return c.isBuffer(e)||e instanceof l}var h,p=e("./internal/streams/destroy"),f=e("./internal/streams/state").getHighWaterMark,m=e("../errors").codes,g=m.ERR_INVALID_ARG_TYPE,y=m.ERR_METHOD_NOT_IMPLEMENTED,v=m.ERR_MULTIPLE_CALLBACK,b=m.ERR_STREAM_CANNOT_PIPE,w=m.ERR_STREAM_DESTROYED,C=m.ERR_STREAM_NULL_VALUES,I=m.ERR_STREAM_WRITE_AFTER_END,S=m.ERR_UNKNOWN_ENCODING,_=p.errorOrDestroy;function k(){}function O(t,n,r){s=s||e("./_stream_duplex"),t=t||{},"boolean"!=typeof r&&(r=n instanceof s),this.objectMode=!!t.objectMode,r&&(this.objectMode=this.objectMode||!!t.writableObjectMode),this.highWaterMark=f(this,t,"writableHighWaterMark",r),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;var o=!1===t.decodeStrings;this.decodeStrings=!o,this.defaultEncoding=t.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(e){x(n,e)},this.writecb=null,this.writelen=0,this.bufferedRequest=null,this.lastBufferedRequest=null,this.pendingcb=0,this.prefinished=!1,this.errorEmitted=!1,this.emitClose=!1!==t.emitClose,this.autoDestroy=!!t.autoDestroy,this.bufferedRequestCount=0,this.corkedRequestsFree=new a(this)}function T(t){var n=this instanceof(s=s||e("./_stream_duplex"));if(!n&&!h.call(T,this))return new T(t);this._writableState=new O(t,this,n),this.writable=!0,t&&("function"==typeof t.write&&(this._write=t.write),"function"==typeof t.writev&&(this._writev=t.writev),"function"==typeof t.destroy&&(this._destroy=t.destroy),"function"==typeof t.final&&(this._final=t.final)),i.call(this)}function E(e,t){var r=new I;_(e,r),n.nextTick(t,r)}function A(e,t,r,a){var s;return null===r?s=new C:"string"==typeof r||t.objectMode||(s=new g("chunk",["string","Buffer"],r)),!s||(_(e,s),n.nextTick(a,s),!1)}function R(e,t,n){return e.objectMode||!1===e.decodeStrings||"string"!=typeof t||(t=c.from(t,n)),t}function M(e,t,n,r,a,s){if(!n){var o=R(t,r,a);r!==o&&(n=!0,a="buffer",r=o)}var i=t.objectMode?1:r.length;t.length+=i;var c=t.length<t.highWaterMark;if(c||(t.needDrain=!0),t.writing||t.corked){var l=t.lastBufferedRequest;t.lastBufferedRequest={chunk:r,encoding:a,isBuf:n,callback:s,next:null},l?l.next=t.lastBufferedRequest:t.bufferedRequest=t.lastBufferedRequest,t.bufferedRequestCount+=1}else j(e,t,!1,i,r,a,s);return c}function j(e,t,n,r,a,s,o){t.writelen=r,t.writecb=o,t.writing=!0,t.sync=!0,t.destroyed?t.onwrite(new w("write")):n?e._writev(a,t.onwrite):e._write(a,s,t.onwrite),t.sync=!1}function P(e,t,r,a,s){--t.pendingcb,r?(n.nextTick(s,a),n.nextTick(K,e,t),e._writableState.errorEmitted=!0,_(e,a)):(s(a),e._writableState.errorEmitted=!0,_(e,a),K(e,t))}function U(e){e.writing=!1,e.writecb=null,e.length-=e.writelen,e.writelen=0}function x(e,t){var r=e._writableState,a=r.sync,s=r.writecb;if("function"!=typeof s)throw new v;if(U(r),t)P(e,r,a,t,s);else{var o=B(r)||e.destroyed;o||r.corked||r.bufferProcessing||!r.bufferedRequest||N(e,r),a?n.nextTick(D,e,r,o,s):D(e,r,o,s)}}function D(e,t,n,r){n||q(e,t),t.pendingcb--,r(),K(e,t)}function q(e,t){0===t.length&&t.needDrain&&(t.needDrain=!1,e.emit("drain"))}function N(e,t){t.bufferProcessing=!0;var n=t.bufferedRequest;if(e._writev&&n&&n.next){var r=t.bufferedRequestCount,s=new Array(r),o=t.corkedRequestsFree;o.entry=n;for(var i=0,c=!0;n;)s[i]=n,n.isBuf||(c=!1),n=n.next,i+=1;s.allBuffers=c,j(e,t,!0,t.length,s,"",o.finish),t.pendingcb++,t.lastBufferedRequest=null,o.next?(t.corkedRequestsFree=o.next,o.next=null):t.corkedRequestsFree=new a(t),t.bufferedRequestCount=0}else{for(;n;){var l=n.chunk,d=n.encoding,u=n.callback;if(j(e,t,!1,t.objectMode?1:l.length,l,d,u),n=n.next,t.bufferedRequestCount--,t.writing)break}null===n&&(t.lastBufferedRequest=null)}t.bufferedRequest=n,t.bufferProcessing=!1}function B(e){return e.ending&&0===e.length&&null===e.bufferedRequest&&!e.finished&&!e.writing}function L(e,t){e._final((function(n){t.pendingcb--,n&&_(e,n),t.prefinished=!0,e.emit("prefinish"),K(e,t)}))}function F(e,t){t.prefinished||t.finalCalled||("function"!=typeof e._final||t.destroyed?(t.prefinished=!0,e.emit("prefinish")):(t.pendingcb++,t.finalCalled=!0,n.nextTick(L,e,t)))}function K(e,t){var n=B(t);if(n&&(F(e,t),0===t.pendingcb&&(t.finished=!0,e.emit("finish"),t.autoDestroy))){var r=e._readableState;(!r||r.autoDestroy&&r.endEmitted)&&e.destroy()}return n}function $(e,t,r){t.ending=!0,K(e,t),r&&(t.finished?n.nextTick(r):e.once("finish",r)),t.ended=!0,e.writable=!1}function Q(e,t,n){var r=e.entry;for(e.entry=null;r;){var a=r.callback;t.pendingcb--,a(n),r=r.next}t.corkedRequestsFree.next=e}e("inherits")(T,i),O.prototype.getBuffer=function(){for(var e=this.bufferedRequest,t=[];e;)t.push(e),e=e.next;return t},function(){try{Object.defineProperty(O.prototype,"buffer",{get:o.deprecate((function(){return this.getBuffer()}),"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.","DEP0003")})}catch(e){}}(),"function"==typeof Symbol&&Symbol.hasInstance&&"function"==typeof Function.prototype[Symbol.hasInstance]?(h=Function.prototype[Symbol.hasInstance],Object.defineProperty(T,Symbol.hasInstance,{value:function(e){return!!h.call(this,e)||this===T&&e&&e._writableState instanceof O}})):h=function(e){return e instanceof this},T.prototype.pipe=function(){_(this,new b)},T.prototype.write=function(e,t,n){var r=this._writableState,a=!1,s=!r.objectMode&&u(e);return s&&!c.isBuffer(e)&&(e=d(e)),"function"==typeof t&&(n=t,t=null),s?t="buffer":t||(t=r.defaultEncoding),"function"!=typeof n&&(n=k),r.ending?E(this,n):(s||A(this,r,e,n))&&(r.pendingcb++,a=M(this,r,s,e,t,n)),a},T.prototype.cork=function(){this._writableState.corked++},T.prototype.uncork=function(){var e=this._writableState;e.corked&&(e.corked--,e.writing||e.corked||e.bufferProcessing||!e.bufferedRequest||N(this,e))},T.prototype.setDefaultEncoding=function(e){if("string"==typeof e&&(e=e.toLowerCase()),!(["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((e+"").toLowerCase())>-1))throw new S(e);return this._writableState.defaultEncoding=e,this},Object.defineProperty(T.prototype,"writableBuffer",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}}),Object.defineProperty(T.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),T.prototype._write=function(e,t,n){n(new y("_write()"))},T.prototype._writev=null,T.prototype.end=function(e,t,n){var r=this._writableState;return"function"==typeof e?(n=e,e=null,t=null):"function"==typeof t&&(n=t,t=null),null!=e&&this.write(e,t),r.corked&&(r.corked=1,this.uncork()),r.ending||$(this,r,n),this},Object.defineProperty(T.prototype,"writableLength",{enumerable:!1,get:function(){return this._writableState.length}}),Object.defineProperty(T.prototype,"destroyed",{enumerable:!1,get:function(){return void 0!==this._writableState&&this._writableState.destroyed},set:function(e){this._writableState&&(this._writableState.destroyed=e)}}),T.prototype.destroy=p.destroy,T.prototype._undestroy=p.undestroy,T.prototype._destroy=function(e,t){t(e)}}).call(this)}).call(this,e("_process"),void 0!==qt?qt:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"../errors":55,"./_stream_duplex":56,"./internal/streams/destroy":63,"./internal/streams/state":67,"./internal/streams/stream":68,_process:50,buffer:17,inherits:24,"util-deprecate":78}],61:[function(e,t,n){(function(n){(function(){var r;function a(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}var s=e("./end-of-stream"),o=Symbol("lastResolve"),i=Symbol("lastReject"),c=Symbol("error"),l=Symbol("ended"),d=Symbol("lastPromise"),u=Symbol("handlePromise"),h=Symbol("stream");function p(e,t){return{value:e,done:t}}function f(e){var t=e[o];if(null!==t){var n=e[h].read();null!==n&&(e[d]=null,e[o]=null,e[i]=null,t(p(n,!1)))}}function m(e){n.nextTick(f,e)}function g(e,t){return function(n,r){e.then((function(){t[l]?n(p(void 0,!0)):t[u](n,r)}),r)}}var y=Object.getPrototypeOf((function(){})),v=Object.setPrototypeOf((a(r={get stream(){return this[h]},next:function(){var e=this,t=this[c];if(null!==t)return Promise.reject(t);if(this[l])return Promise.resolve(p(void 0,!0));if(this[h].destroyed)return new Promise((function(t,r){n.nextTick((function(){e[c]?r(e[c]):t(p(void 0,!0))}))}));var r,a=this[d];if(a)r=new Promise(g(a,this));else{var s=this[h].read();if(null!==s)return Promise.resolve(p(s,!1));r=new Promise(this[u])}return this[d]=r,r}},Symbol.asyncIterator,(function(){return this})),a(r,"return",(function(){var e=this;return new Promise((function(t,n){e[h].destroy(null,(function(e){e?n(e):t(p(void 0,!0))}))}))})),r),y),b=function(e){var t,n=Object.create(v,(a(t={},h,{value:e,writable:!0}),a(t,o,{value:null,writable:!0}),a(t,i,{value:null,writable:!0}),a(t,c,{value:null,writable:!0}),a(t,l,{value:e._readableState.endEmitted,writable:!0}),a(t,u,{value:function(e,t){var r=n[h].read();r?(n[d]=null,n[o]=null,n[i]=null,e(p(r,!1))):(n[o]=e,n[i]=t)},writable:!0}),t));return n[d]=null,s(e,(function(e){if(e&&"ERR_STREAM_PREMATURE_CLOSE"!==e.code){var t=n[i];return null!==t&&(n[d]=null,n[o]=null,n[i]=null,t(e)),void(n[c]=e)}var r=n[o];null!==r&&(n[d]=null,n[o]=null,n[i]=null,r(p(void 0,!0))),n[l]=!0})),e.on("readable",m.bind(null,n)),n};t.exports=b}).call(this)}).call(this,e("_process"))},{"./end-of-stream":64,_process:50}],62:[function(e,t,n){function r(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function a(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?r(Object(n),!0).forEach((function(t){s(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):r(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}function s(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}function c(e,t,n){return t&&i(e.prototype,t),n&&i(e,n),e}var l=e("buffer").Buffer,d=e("util").inspect,u=d&&d.custom||"inspect";function h(e,t,n){l.prototype.copy.call(e,t,n)}t.exports=function(){function e(){o(this,e),this.head=null,this.tail=null,this.length=0}return c(e,[{key:"push",value:function(e){var t={data:e,next:null};this.length>0?this.tail.next=t:this.head=t,this.tail=t,++this.length}},{key:"unshift",value:function(e){var t={data:e,next:this.head};0===this.length&&(this.tail=t),this.head=t,++this.length}},{key:"shift",value:function(){if(0!==this.length){var e=this.head.data;return 1===this.length?this.head=this.tail=null:this.head=this.head.next,--this.length,e}}},{key:"clear",value:function(){this.head=this.tail=null,this.length=0}},{key:"join",value:function(e){if(0===this.length)return"";for(var t=this.head,n=""+t.data;t=t.next;)n+=e+t.data;return n}},{key:"concat",value:function(e){if(0===this.length)return l.alloc(0);for(var t=l.allocUnsafe(e>>>0),n=this.head,r=0;n;)h(n.data,t,r),r+=n.data.length,n=n.next;return t}},{key:"consume",value:function(e,t){var n;return e<this.head.data.length?(n=this.head.data.slice(0,e),this.head.data=this.head.data.slice(e)):n=e===this.head.data.length?this.shift():t?this._getString(e):this._getBuffer(e),n}},{key:"first",value:function(){return this.head.data}},{key:"_getString",value:function(e){var t=this.head,n=1,r=t.data;for(e-=r.length;t=t.next;){var a=t.data,s=e>a.length?a.length:e;if(s===a.length?r+=a:r+=a.slice(0,e),0==(e-=s)){s===a.length?(++n,t.next?this.head=t.next:this.head=this.tail=null):(this.head=t,t.data=a.slice(s));break}++n}return this.length-=n,r}},{key:"_getBuffer",value:function(e){var t=l.allocUnsafe(e),n=this.head,r=1;for(n.data.copy(t),e-=n.data.length;n=n.next;){var a=n.data,s=e>a.length?a.length:e;if(a.copy(t,t.length-e,0,s),0==(e-=s)){s===a.length?(++r,n.next?this.head=n.next:this.head=this.tail=null):(this.head=n,n.data=a.slice(s));break}++r}return this.length-=r,t}},{key:u,value:function(e,t){return d(this,a({},t,{depth:0,customInspect:!1}))}}]),e}()},{buffer:17,util:16}],63:[function(e,t,n){(function(e){(function(){function n(t,n){var s=this,i=this._readableState&&this._readableState.destroyed,c=this._writableState&&this._writableState.destroyed;return i||c?(n?n(t):t&&(this._writableState?this._writableState.errorEmitted||(this._writableState.errorEmitted=!0,e.nextTick(o,this,t)):e.nextTick(o,this,t)),this):(this._readableState&&(this._readableState.destroyed=!0),this._writableState&&(this._writableState.destroyed=!0),this._destroy(t||null,(function(t){!n&&t?s._writableState?s._writableState.errorEmitted?e.nextTick(a,s):(s._writableState.errorEmitted=!0,e.nextTick(r,s,t)):e.nextTick(r,s,t):n?(e.nextTick(a,s),n(t)):e.nextTick(a,s)})),this)}function r(e,t){o(e,t),a(e)}function a(e){e._writableState&&!e._writableState.emitClose||e._readableState&&!e._readableState.emitClose||e.emit("close")}function s(){this._readableState&&(this._readableState.destroyed=!1,this._readableState.reading=!1,this._readableState.ended=!1,this._readableState.endEmitted=!1),this._writableState&&(this._writableState.destroyed=!1,this._writableState.ended=!1,this._writableState.ending=!1,this._writableState.finalCalled=!1,this._writableState.prefinished=!1,this._writableState.finished=!1,this._writableState.errorEmitted=!1)}function o(e,t){e.emit("error",t)}function i(e,t){var n=e._readableState,r=e._writableState;n&&n.autoDestroy||r&&r.autoDestroy?e.destroy(t):e.emit("error",t)}t.exports={destroy:n,undestroy:s,errorOrDestroy:i}}).call(this)}).call(this,e("_process"))},{_process:50}],64:[function(e,t,n){var r=e("../../../errors").codes.ERR_STREAM_PREMATURE_CLOSE;function a(e){var t=!1;return function(){if(!t){t=!0;for(var n=arguments.length,r=new Array(n),a=0;a<n;a++)r[a]=arguments[a];e.apply(this,r)}}}function s(){}function o(e){return e.setHeader&&"function"==typeof e.abort}function i(e,t,n){if("function"==typeof t)return i(e,null,t);t||(t={}),n=a(n||s);var c=t.readable||!1!==t.readable&&e.readable,l=t.writable||!1!==t.writable&&e.writable,d=function(){e.writable||h()},u=e._writableState&&e._writableState.finished,h=function(){l=!1,u=!0,c||n.call(e)},p=e._readableState&&e._readableState.endEmitted,f=function(){c=!1,p=!0,l||n.call(e)},m=function(t){n.call(e,t)},g=function(){var t;return c&&!p?(e._readableState&&e._readableState.ended||(t=new r),n.call(e,t)):l&&!u?(e._writableState&&e._writableState.ended||(t=new r),n.call(e,t)):void 0},y=function(){e.req.on("finish",h)};return o(e)?(e.on("complete",h),e.on("abort",g),e.req?y():e.on("request",y)):l&&!e._writableState&&(e.on("end",d),e.on("close",d)),e.on("end",f),e.on("finish",h),!1!==t.error&&e.on("error",m),e.on("close",g),function(){e.removeListener("complete",h),e.removeListener("abort",g),e.removeListener("request",y),e.req&&e.req.removeListener("finish",h),e.removeListener("end",d),e.removeListener("close",d),e.removeListener("finish",h),e.removeListener("end",f),e.removeListener("error",m),e.removeListener("close",g)}}t.exports=i},{"../../../errors":55}],65:[function(e,t,n){t.exports=function(){throw new Error("Readable.from is not available in the browser")}},{}],66:[function(e,t,n){var r;function a(e){var t=!1;return function(){t||(t=!0,e.apply(void 0,arguments))}}var s=e("../../../errors").codes,o=s.ERR_MISSING_ARGS,i=s.ERR_STREAM_DESTROYED;function c(e){if(e)throw e}function l(e){return e.setHeader&&"function"==typeof e.abort}function d(t,n,s,o){o=a(o);var c=!1;t.on("close",(function(){c=!0})),void 0===r&&(r=e("./end-of-stream")),r(t,{readable:n,writable:s},(function(e){if(e)return o(e);c=!0,o()}));var d=!1;return function(e){if(!c&&!d)return d=!0,l(t)?t.abort():"function"==typeof t.destroy?t.destroy():void o(e||new i("pipe"))}}function u(e){e()}function h(e,t){return e.pipe(t)}function p(e){return e.length?"function"!=typeof e[e.length-1]?c:e.pop():c}function f(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];var r,a=p(t);if(Array.isArray(t[0])&&(t=t[0]),t.length<2)throw new o("streams");var s=t.map((function(e,n){var o=n<t.length-1;return d(e,o,n>0,(function(e){r||(r=e),e&&s.forEach(u),o||(s.forEach(u),a(r))}))}));return t.reduce(h)}t.exports=f},{"../../../errors":55,"./end-of-stream":64}],67:[function(e,t,n){var r=e("../../../errors").codes.ERR_INVALID_OPT_VALUE;function a(e,t,n){return null!=e.highWaterMark?e.highWaterMark:t?e[n]:null}function s(e,t,n,s){var o=a(t,s,n);if(null!=o){if(!isFinite(o)||Math.floor(o)!==o||o<0)throw new r(s?n:"highWaterMark",o);return Math.floor(o)}return e.objectMode?16:16384}t.exports={getHighWaterMark:s}},{"../../../errors":55}],68:[function(e,t,n){t.exports=e("events").EventEmitter},{events:22}],69:[function(e,t,n){(n=t.exports=e("./lib/_stream_readable.js")).Stream=n,n.Readable=n,n.Writable=e("./lib/_stream_writable.js"),n.Duplex=e("./lib/_stream_duplex.js"),n.Transform=e("./lib/_stream_transform.js"),n.PassThrough=e("./lib/_stream_passthrough.js"),n.finished=e("./lib/internal/streams/end-of-stream.js"),n.pipeline=e("./lib/internal/streams/pipeline.js")},{"./lib/_stream_duplex.js":56,"./lib/_stream_passthrough.js":57,"./lib/_stream_readable.js":58,"./lib/_stream_transform.js":59,"./lib/_stream_writable.js":60,"./lib/internal/streams/end-of-stream.js":64,"./lib/internal/streams/pipeline.js":66}],70:[function(e,t,n){function r(e,t,n){var r=this;this._callback=e,this._args=n,this._interval=setInterval(e,t,this._args),this.reschedule=function(e){e||(e=r._interval),r._interval&&clearInterval(r._interval),r._interval=setInterval(r._callback,e,r._args)},this.clear=function(){r._interval&&(clearInterval(r._interval),r._interval=void 0)},this.destroy=function(){r._interval&&clearInterval(r._interval),r._callback=void 0,r._interval=void 0,r._args=void 0}}function a(){if("function"!=typeof arguments[0])throw new Error("callback needed");if("number"!=typeof arguments[1])throw new Error("interval needed");var e;if(arguments.length>0){e=new Array(arguments.length-2);for(var t=0;t<e.length;t++)e[t]=arguments[t+2]}return new r(arguments[0],arguments[1],e)}t.exports=a},{}],71:[function(e,t,n){t.exports=e("./index.js")()},{"./index.js":72}],72:[function(e,t,n){(function(e){(function(){function n(t){return t instanceof e?e.from(t):new t.constructor(t.buffer.slice(),t.byteOffset,t.length)}function r(e){return(e=e||{}).circles?a(e):e.proto?s:r;function t(e,t){for(var r=Object.keys(e),a=new Array(r.length),s=0;s<r.length;s++){var o=r[s],i=e[o];"object"!=typeof i||null===i?a[o]=i:i instanceof Date?a[o]=new Date(i):ArrayBuffer.isView(i)?a[o]=n(i):a[o]=t(i)}return a}function r(e){if("object"!=typeof e||null===e)return e;if(e instanceof Date)return new Date(e);if(Array.isArray(e))return t(e,r);if(e instanceof Map)return new Map(t(Array.from(e),r));if(e instanceof Set)return new Set(t(Array.from(e),r));var a={};for(var s in e)if(!1!==Object.hasOwnProperty.call(e,s)){var o=e[s];"object"!=typeof o||null===o?a[s]=o:o instanceof Date?a[s]=new Date(o):o instanceof Map?a[s]=new Map(t(Array.from(o),r)):o instanceof Set?a[s]=new Set(t(Array.from(o),r)):ArrayBuffer.isView(o)?a[s]=n(o):a[s]=r(o)}return a}function s(e){if("object"!=typeof e||null===e)return e;if(e instanceof Date)return new Date(e);if(Array.isArray(e))return t(e,s);if(e instanceof Map)return new Map(t(Array.from(e),s));if(e instanceof Set)return new Set(t(Array.from(e),s));var r={};for(var a in e){var o=e[a];"object"!=typeof o||null===o?r[a]=o:o instanceof Date?r[a]=new Date(o):o instanceof Map?r[a]=new Map(t(Array.from(o),s)):o instanceof Set?r[a]=new Set(t(Array.from(o),s)):ArrayBuffer.isView(o)?r[a]=n(o):r[a]=s(o)}return r}}function a(e){var t=[],r=[];return e.proto?o:s;function a(e,a){for(var s=Object.keys(e),o=new Array(s.length),i=0;i<s.length;i++){var c=s[i],l=e[c];if("object"!=typeof l||null===l)o[c]=l;else if(l instanceof Date)o[c]=new Date(l);else if(ArrayBuffer.isView(l))o[c]=n(l);else{var d=t.indexOf(l);o[c]=-1!==d?r[d]:a(l)}}return o}function s(e){if("object"!=typeof e||null===e)return e;if(e instanceof Date)return new Date(e);if(Array.isArray(e))return a(e,s);if(e instanceof Map)return new Map(a(Array.from(e),s));if(e instanceof Set)return new Set(a(Array.from(e),s));var o={};for(var i in t.push(e),r.push(o),e)if(!1!==Object.hasOwnProperty.call(e,i)){var c=e[i];if("object"!=typeof c||null===c)o[i]=c;else if(c instanceof Date)o[i]=new Date(c);else if(c instanceof Map)o[i]=new Map(a(Array.from(c),s));else if(c instanceof Set)o[i]=new Set(a(Array.from(c),s));else if(ArrayBuffer.isView(c))o[i]=n(c);else{var l=t.indexOf(c);o[i]=-1!==l?r[l]:s(c)}}return t.pop(),r.pop(),o}function o(e){if("object"!=typeof e||null===e)return e;if(e instanceof Date)return new Date(e);if(Array.isArray(e))return a(e,o);if(e instanceof Map)return new Map(a(Array.from(e),o));if(e instanceof Set)return new Set(a(Array.from(e),o));var s={};for(var i in t.push(e),r.push(s),e){var c=e[i];if("object"!=typeof c||null===c)s[i]=c;else if(c instanceof Date)s[i]=new Date(c);else if(c instanceof Map)s[i]=new Map(a(Array.from(c),o));else if(c instanceof Set)s[i]=new Set(a(Array.from(c),o));else if(ArrayBuffer.isView(c))s[i]=n(c);else{var l=t.indexOf(c);s[i]=-1!==l?r[l]:o(c)}}return t.pop(),r.pop(),s}}t.exports=r}).call(this)}).call(this,e("buffer").Buffer)},{buffer:17}],73:[function(e,t,n){
4
4
  /*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */
5
- var r=e("buffer"),s=r.Buffer;function a(e,t){for(var n in e)t[n]=e[n]}function o(e,t,n){return s(e,t,n)}s.from&&s.alloc&&s.allocUnsafe&&s.allocUnsafeSlow?t.exports=r:(a(r,n),n.Buffer=o),o.prototype=Object.create(s.prototype),a(s,o),o.from=function(e,t,n){if("number"==typeof e)throw new TypeError("Argument must not be a number");return s(e,t,n)},o.alloc=function(e,t,n){if("number"!=typeof e)throw new TypeError("Argument must be a number");var r=s(e);return void 0!==t?"string"==typeof n?r.fill(t,n):r.fill(t):r.fill(0),r},o.allocUnsafe=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return s(e)},o.allocUnsafeSlow=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return r.SlowBuffer(e)}},{buffer:17}],74:[function(e,t,n){function r(e){var t=e._readableState;return t?t.objectMode||"number"==typeof e._duplexState?e.read():e.read(s(t)):null}function s(e){return e.buffer.length?e.buffer.head?e.buffer.head.data.length:e.buffer[0].length:e.length}t.exports=r},{}],75:[function(e,t,n){var r=e("safe-buffer").Buffer,s=r.isEncoding||function(e){switch((e=""+e)&&e.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}};function a(e){if(!e)return"utf8";for(var t;;)switch(e){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return e;default:if(t)return;e=(""+e).toLowerCase(),t=!0}}function o(e){var t=a(e);if("string"!=typeof t&&(r.isEncoding===s||!s(e)))throw new Error("Unknown encoding: "+e);return t||e}function i(e){var t;switch(this.encoding=o(e),this.encoding){case"utf16le":this.text=f,this.end=m,t=4;break;case"utf8":this.fillLast=u,t=4;break;case"base64":this.text=g,this.end=y,t=3;break;default:return this.write=v,void(this.end=b)}this.lastNeed=0,this.lastTotal=0,this.lastChar=r.allocUnsafe(t)}function c(e){return e<=127?0:e>>5==6?2:e>>4==14?3:e>>3==30?4:e>>6==2?-1:-2}function l(e,t,n){var r=t.length-1;if(r<n)return 0;var s=c(t[r]);return s>=0?(s>0&&(e.lastNeed=s-1),s):--r<n||-2===s?0:(s=c(t[r]))>=0?(s>0&&(e.lastNeed=s-2),s):--r<n||-2===s?0:(s=c(t[r]))>=0?(s>0&&(2===s?s=0:e.lastNeed=s-3),s):0}function d(e,t,n){if(128!=(192&t[0]))return e.lastNeed=0,"�";if(e.lastNeed>1&&t.length>1){if(128!=(192&t[1]))return e.lastNeed=1,"�";if(e.lastNeed>2&&t.length>2&&128!=(192&t[2]))return e.lastNeed=2,"�"}}function u(e){var t=this.lastTotal-this.lastNeed,n=d(this,e);return void 0!==n?n:this.lastNeed<=e.length?(e.copy(this.lastChar,t,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal)):(e.copy(this.lastChar,t,0,e.length),void(this.lastNeed-=e.length))}function h(e,t){var n=l(this,e,t);if(!this.lastNeed)return e.toString("utf8",t);this.lastTotal=n;var r=e.length-(n-this.lastNeed);return e.copy(this.lastChar,0,r),e.toString("utf8",t,r)}function p(e){var t=e&&e.length?this.write(e):"";return this.lastNeed?t+"�":t}function f(e,t){if((e.length-t)%2==0){var n=e.toString("utf16le",t);if(n){var r=n.charCodeAt(n.length-1);if(r>=55296&&r<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1],n.slice(0,-1)}return n}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=e[e.length-1],e.toString("utf16le",t,e.length-1)}function m(e){var t=e&&e.length?this.write(e):"";if(this.lastNeed){var n=this.lastTotal-this.lastNeed;return t+this.lastChar.toString("utf16le",0,n)}return t}function g(e,t){var n=(e.length-t)%3;return 0===n?e.toString("base64",t):(this.lastNeed=3-n,this.lastTotal=3,1===n?this.lastChar[0]=e[e.length-1]:(this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1]),e.toString("base64",t,e.length-n))}function y(e){var t=e&&e.length?this.write(e):"";return this.lastNeed?t+this.lastChar.toString("base64",0,3-this.lastNeed):t}function v(e){return e.toString(this.encoding)}function b(e){return e&&e.length?this.write(e):""}n.StringDecoder=i,i.prototype.write=function(e){if(0===e.length)return"";var t,n;if(this.lastNeed){if(void 0===(t=this.fillLast(e)))return"";n=this.lastNeed,this.lastNeed=0}else n=0;return n<e.length?t?t+this.text(e,n):this.text(e,n):t||""},i.prototype.end=p,i.prototype.text=h,i.prototype.fillLast=function(e){if(this.lastNeed<=e.length)return e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,e.length),this.lastNeed-=e.length}},{"safe-buffer":73}],76:[function(e,t,n){var r=e("punycode"),s=e("./util");function a(){this.protocol=null,this.slashes=null,this.auth=null,this.host=null,this.port=null,this.hostname=null,this.hash=null,this.search=null,this.query=null,this.pathname=null,this.path=null,this.href=null}n.parse=w,n.resolve=I,n.resolveObject=S,n.format=C,n.Url=a;var o=/^([a-z0-9.+-]+:)/i,i=/:[0-9]*$/,c=/^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/,l=["{","}","|","\\","^","`"].concat(["<",">",'"',"`"," ","\r","\n","\t"]),d=["'"].concat(l),u=["%","/","?",";","#"].concat(d),h=["/","?","#"],p=255,f=/^[+a-z0-9A-Z_-]{0,63}$/,m=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,g={javascript:!0,"javascript:":!0},y={javascript:!0,"javascript:":!0},v={http:!0,https:!0,ftp:!0,gopher:!0,file:!0,"http:":!0,"https:":!0,"ftp:":!0,"gopher:":!0,"file:":!0},b=e("querystring");function w(e,t,n){if(e&&s.isObject(e)&&e instanceof a)return e;var r=new a;return r.parse(e,t,n),r}function C(e){return s.isString(e)&&(e=w(e)),e instanceof a?e.format():a.prototype.format.call(e)}function I(e,t){return w(e,!1,!0).resolve(t)}function S(e,t){return e?w(e,!1,!0).resolveObject(t):t}a.prototype.parse=function(e,t,n){if(!s.isString(e))throw new TypeError("Parameter 'url' must be a string, not "+typeof e);var a=e.indexOf("?"),i=-1!==a&&a<e.indexOf("#")?"?":"#",l=e.split(i),w=/\\/g;l[0]=l[0].replace(w,"/");var C=e=l.join(i);if(C=C.trim(),!n&&1===e.split("#").length){var I=c.exec(C);if(I)return this.path=C,this.href=C,this.pathname=I[1],I[2]?(this.search=I[2],this.query=t?b.parse(this.search.substr(1)):this.search.substr(1)):t&&(this.search="",this.query={}),this}var S=o.exec(C);if(S){var _=(S=S[0]).toLowerCase();this.protocol=_,C=C.substr(S.length)}if(n||S||C.match(/^\/\/[^@\/]+@[^@\/]+/)){var k="//"===C.substr(0,2);!k||S&&y[S]||(C=C.substr(2),this.slashes=!0)}if(!y[S]&&(k||S&&!v[S])){for(var T,O,A=-1,E=0;E<h.length;E++)-1!==(M=C.indexOf(h[E]))&&(-1===A||M<A)&&(A=M);for(-1!==(O=-1===A?C.lastIndexOf("@"):C.lastIndexOf("@",A))&&(T=C.slice(0,O),C=C.slice(O+1),this.auth=decodeURIComponent(T)),A=-1,E=0;E<u.length;E++){var M;-1!==(M=C.indexOf(u[E]))&&(-1===A||M<A)&&(A=M)}-1===A&&(A=C.length),this.host=C.slice(0,A),C=C.slice(A),this.parseHost(),this.hostname=this.hostname||"";var R="["===this.hostname[0]&&"]"===this.hostname[this.hostname.length-1];if(!R)for(var P=this.hostname.split(/\./),j=(E=0,P.length);E<j;E++){var U=P[E];if(U&&!U.match(f)){for(var x="",D=0,N=U.length;D<N;D++)U.charCodeAt(D)>127?x+="x":x+=U[D];if(!x.match(f)){var B=P.slice(0,E),q=P.slice(E+1),F=U.match(m);F&&(B.push(F[1]),q.unshift(F[2])),q.length&&(C="/"+q.join(".")+C),this.hostname=B.join(".");break}}}this.hostname.length>p?this.hostname="":this.hostname=this.hostname.toLowerCase(),R||(this.hostname=r.toASCII(this.hostname));var L=this.port?":"+this.port:"",K=this.hostname||"";this.host=K+L,this.href+=this.host,R&&(this.hostname=this.hostname.substr(1,this.hostname.length-2),"/"!==C[0]&&(C="/"+C))}if(!g[_])for(E=0,j=d.length;E<j;E++){var $=d[E];if(-1!==C.indexOf($)){var z=encodeURIComponent($);z===$&&(z=escape($)),C=C.split($).join(z)}}var Q=C.indexOf("#");-1!==Q&&(this.hash=C.substr(Q),C=C.slice(0,Q));var V=C.indexOf("?");if(-1!==V?(this.search=C.substr(V),this.query=C.substr(V+1),t&&(this.query=b.parse(this.query)),C=C.slice(0,V)):t&&(this.search="",this.query={}),C&&(this.pathname=C),v[_]&&this.hostname&&!this.pathname&&(this.pathname="/"),this.pathname||this.search){L=this.pathname||"";var H=this.search||"";this.path=L+H}return this.href=this.format(),this},a.prototype.format=function(){var e=this.auth||"";e&&(e=(e=encodeURIComponent(e)).replace(/%3A/i,":"),e+="@");var t=this.protocol||"",n=this.pathname||"",r=this.hash||"",a=!1,o="";this.host?a=e+this.host:this.hostname&&(a=e+(-1===this.hostname.indexOf(":")?this.hostname:"["+this.hostname+"]"),this.port&&(a+=":"+this.port)),this.query&&s.isObject(this.query)&&Object.keys(this.query).length&&(o=b.stringify(this.query));var i=this.search||o&&"?"+o||"";return t&&":"!==t.substr(-1)&&(t+=":"),this.slashes||(!t||v[t])&&!1!==a?(a="//"+(a||""),n&&"/"!==n.charAt(0)&&(n="/"+n)):a||(a=""),r&&"#"!==r.charAt(0)&&(r="#"+r),i&&"?"!==i.charAt(0)&&(i="?"+i),t+a+(n=n.replace(/[?#]/g,(function(e){return encodeURIComponent(e)})))+(i=i.replace("#","%23"))+r},a.prototype.resolve=function(e){return this.resolveObject(w(e,!1,!0)).format()},a.prototype.resolveObject=function(e){if(s.isString(e)){var t=new a;t.parse(e,!1,!0),e=t}for(var n=new a,r=Object.keys(this),o=0;o<r.length;o++){var i=r[o];n[i]=this[i]}if(n.hash=e.hash,""===e.href)return n.href=n.format(),n;if(e.slashes&&!e.protocol){for(var c=Object.keys(e),l=0;l<c.length;l++){var d=c[l];"protocol"!==d&&(n[d]=e[d])}return v[n.protocol]&&n.hostname&&!n.pathname&&(n.path=n.pathname="/"),n.href=n.format(),n}if(e.protocol&&e.protocol!==n.protocol){if(!v[e.protocol]){for(var u=Object.keys(e),h=0;h<u.length;h++){var p=u[h];n[p]=e[p]}return n.href=n.format(),n}if(n.protocol=e.protocol,e.host||y[e.protocol])n.pathname=e.pathname;else{for(var f=(e.pathname||"").split("/");f.length&&!(e.host=f.shift()););e.host||(e.host=""),e.hostname||(e.hostname=""),""!==f[0]&&f.unshift(""),f.length<2&&f.unshift(""),n.pathname=f.join("/")}if(n.search=e.search,n.query=e.query,n.host=e.host||"",n.auth=e.auth,n.hostname=e.hostname||e.host,n.port=e.port,n.pathname||n.search){var m=n.pathname||"",g=n.search||"";n.path=m+g}return n.slashes=n.slashes||e.slashes,n.href=n.format(),n}var b=n.pathname&&"/"===n.pathname.charAt(0),w=e.host||e.pathname&&"/"===e.pathname.charAt(0),C=w||b||n.host&&e.pathname,I=C,S=n.pathname&&n.pathname.split("/")||[],_=(f=e.pathname&&e.pathname.split("/")||[],n.protocol&&!v[n.protocol]);if(_&&(n.hostname="",n.port=null,n.host&&(""===S[0]?S[0]=n.host:S.unshift(n.host)),n.host="",e.protocol&&(e.hostname=null,e.port=null,e.host&&(""===f[0]?f[0]=e.host:f.unshift(e.host)),e.host=null),C=C&&(""===f[0]||""===S[0])),w)n.host=e.host||""===e.host?e.host:n.host,n.hostname=e.hostname||""===e.hostname?e.hostname:n.hostname,n.search=e.search,n.query=e.query,S=f;else if(f.length)S||(S=[]),S.pop(),S=S.concat(f),n.search=e.search,n.query=e.query;else if(!s.isNullOrUndefined(e.search))return _&&(n.hostname=n.host=S.shift(),(E=!!(n.host&&n.host.indexOf("@")>0)&&n.host.split("@"))&&(n.auth=E.shift(),n.host=n.hostname=E.shift())),n.search=e.search,n.query=e.query,s.isNull(n.pathname)&&s.isNull(n.search)||(n.path=(n.pathname?n.pathname:"")+(n.search?n.search:"")),n.href=n.format(),n;if(!S.length)return n.pathname=null,n.search?n.path="/"+n.search:n.path=null,n.href=n.format(),n;for(var k=S.slice(-1)[0],T=(n.host||e.host||S.length>1)&&("."===k||".."===k)||""===k,O=0,A=S.length;A>=0;A--)"."===(k=S[A])?S.splice(A,1):".."===k?(S.splice(A,1),O++):O&&(S.splice(A,1),O--);if(!C&&!I)for(;O--;O)S.unshift("..");!C||""===S[0]||S[0]&&"/"===S[0].charAt(0)||S.unshift(""),T&&"/"!==S.join("/").substr(-1)&&S.push("");var E,M=""===S[0]||S[0]&&"/"===S[0].charAt(0);return _&&(n.hostname=n.host=M?"":S.length?S.shift():"",(E=!!(n.host&&n.host.indexOf("@")>0)&&n.host.split("@"))&&(n.auth=E.shift(),n.host=n.hostname=E.shift())),(C=C||n.host&&S.length)&&!M&&S.unshift(""),S.length?n.pathname=S.join("/"):(n.pathname=null,n.path=null),s.isNull(n.pathname)&&s.isNull(n.search)||(n.path=(n.pathname?n.pathname:"")+(n.search?n.search:"")),n.auth=e.auth||n.auth,n.slashes=n.slashes||e.slashes,n.href=n.format(),n},a.prototype.parseHost=function(){var e=this.host,t=i.exec(e);t&&(":"!==(t=t[0])&&(this.port=t.substr(1)),e=e.substr(0,e.length-t.length)),e&&(this.hostname=e)}},{"./util":77,punycode:51,querystring:54}],77:[function(e,t,n){t.exports={isString:function(e){return"string"==typeof e},isObject:function(e){return"object"==typeof e&&null!==e},isNull:function(e){return null===e},isNullOrUndefined:function(e){return null==e}}},{}],78:[function(e,t,n){(function(e){(function(){function n(e,t){if(r("noDeprecation"))return e;var n=!1;function s(){if(!n){if(r("throwDeprecation"))throw new Error(t);r("traceDeprecation")?console.trace(t):console.warn(t),n=!0}return e.apply(this,arguments)}return s}function r(t){try{if(!e.localStorage)return!1}catch(e){return!1}var n=e.localStorage[t];return null!=n&&"true"===String(n).toLowerCase()}t.exports=n}).call(this)}).call(this,void 0!==At?At:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],79:[function(e,t,n){function r(e,t){if(e&&t)return r(e)(t);if("function"!=typeof e)throw new TypeError("need wrapper function");return Object.keys(e).forEach((function(t){n[t]=e[t]})),n;function n(){for(var t=new Array(arguments.length),n=0;n<t.length;n++)t[n]=arguments[n];var r=e.apply(this,t),s=t[t.length-1];return"function"==typeof r&&r!==s&&Object.keys(s).forEach((function(e){r[e]=s[e]})),r}}t.exports=r},{}],80:[function(e,t,n){t.exports=function(){throw new Error("ws does not work in the browser. Browser clients must use the native WebSocket object")}},{}],81:[function(e,t,n){t.exports=s;var r=Object.prototype.hasOwnProperty;function s(){for(var e={},t=0;t<arguments.length;t++){var n=arguments[t];for(var s in n)r.call(n,s)&&(e[s]=n[s])}return e}},{}],82:[function(e,t,n){t.exports=function(e){e.prototype[Symbol.iterator]=function*(){for(let e=this.head;e;e=e.next)yield e.value}}},{}],83:[function(e,t,n){function r(e){var t=this;if(t instanceof r||(t=new r),t.tail=null,t.head=null,t.length=0,e&&"function"==typeof e.forEach)e.forEach((function(e){t.push(e)}));else if(arguments.length>0)for(var n=0,s=arguments.length;n<s;n++)t.push(arguments[n]);return t}function s(e,t,n){var r=t===e.head?new i(n,null,t,e):new i(n,t,t.next,e);return null===r.next&&(e.tail=r),null===r.prev&&(e.head=r),e.length++,r}function a(e,t){e.tail=new i(t,e.tail,null,e),e.head||(e.head=e.tail),e.length++}function o(e,t){e.head=new i(t,null,e.head,e),e.tail||(e.tail=e.head),e.length++}function i(e,t,n,r){if(!(this instanceof i))return new i(e,t,n,r);this.list=r,this.value=e,t?(t.next=this,this.prev=t):this.prev=null,n?(n.prev=this,this.next=n):this.next=null}t.exports=r,r.Node=i,r.create=r,r.prototype.removeNode=function(e){if(e.list!==this)throw new Error("removing node which does not belong to this list");var t=e.next,n=e.prev;return t&&(t.prev=n),n&&(n.next=t),e===this.head&&(this.head=t),e===this.tail&&(this.tail=n),e.list.length--,e.next=null,e.prev=null,e.list=null,t},r.prototype.unshiftNode=function(e){if(e!==this.head){e.list&&e.list.removeNode(e);var t=this.head;e.list=this,e.next=t,t&&(t.prev=e),this.head=e,this.tail||(this.tail=e),this.length++}},r.prototype.pushNode=function(e){if(e!==this.tail){e.list&&e.list.removeNode(e);var t=this.tail;e.list=this,e.prev=t,t&&(t.next=e),this.tail=e,this.head||(this.head=e),this.length++}},r.prototype.push=function(){for(var e=0,t=arguments.length;e<t;e++)a(this,arguments[e]);return this.length},r.prototype.unshift=function(){for(var e=0,t=arguments.length;e<t;e++)o(this,arguments[e]);return this.length},r.prototype.pop=function(){if(this.tail){var e=this.tail.value;return this.tail=this.tail.prev,this.tail?this.tail.next=null:this.head=null,this.length--,e}},r.prototype.shift=function(){if(this.head){var e=this.head.value;return this.head=this.head.next,this.head?this.head.prev=null:this.tail=null,this.length--,e}},r.prototype.forEach=function(e,t){t=t||this;for(var n=this.head,r=0;null!==n;r++)e.call(t,n.value,r,this),n=n.next},r.prototype.forEachReverse=function(e,t){t=t||this;for(var n=this.tail,r=this.length-1;null!==n;r--)e.call(t,n.value,r,this),n=n.prev},r.prototype.get=function(e){for(var t=0,n=this.head;null!==n&&t<e;t++)n=n.next;if(t===e&&null!==n)return n.value},r.prototype.getReverse=function(e){for(var t=0,n=this.tail;null!==n&&t<e;t++)n=n.prev;if(t===e&&null!==n)return n.value},r.prototype.map=function(e,t){t=t||this;for(var n=new r,s=this.head;null!==s;)n.push(e.call(t,s.value,this)),s=s.next;return n},r.prototype.mapReverse=function(e,t){t=t||this;for(var n=new r,s=this.tail;null!==s;)n.push(e.call(t,s.value,this)),s=s.prev;return n},r.prototype.reduce=function(e,t){var n,r=this.head;if(arguments.length>1)n=t;else{if(!this.head)throw new TypeError("Reduce of empty list with no initial value");r=this.head.next,n=this.head.value}for(var s=0;null!==r;s++)n=e(n,r.value,s),r=r.next;return n},r.prototype.reduceReverse=function(e,t){var n,r=this.tail;if(arguments.length>1)n=t;else{if(!this.tail)throw new TypeError("Reduce of empty list with no initial value");r=this.tail.prev,n=this.tail.value}for(var s=this.length-1;null!==r;s--)n=e(n,r.value,s),r=r.prev;return n},r.prototype.toArray=function(){for(var e=new Array(this.length),t=0,n=this.head;null!==n;t++)e[t]=n.value,n=n.next;return e},r.prototype.toArrayReverse=function(){for(var e=new Array(this.length),t=0,n=this.tail;null!==n;t++)e[t]=n.value,n=n.prev;return e},r.prototype.slice=function(e,t){(t=t||this.length)<0&&(t+=this.length),(e=e||0)<0&&(e+=this.length);var n=new r;if(t<e||t<0)return n;e<0&&(e=0),t>this.length&&(t=this.length);for(var s=0,a=this.head;null!==a&&s<e;s++)a=a.next;for(;null!==a&&s<t;s++,a=a.next)n.push(a.value);return n},r.prototype.sliceReverse=function(e,t){(t=t||this.length)<0&&(t+=this.length),(e=e||0)<0&&(e+=this.length);var n=new r;if(t<e||t<0)return n;e<0&&(e=0),t>this.length&&(t=this.length);for(var s=this.length,a=this.tail;null!==a&&s>t;s--)a=a.prev;for(;null!==a&&s>e;s--,a=a.prev)n.push(a.value);return n},r.prototype.splice=function(e,t,...n){e>this.length&&(e=this.length-1),e<0&&(e=this.length+e);for(var r=0,a=this.head;null!==a&&r<e;r++)a=a.next;var o=[];for(r=0;a&&r<t;r++)o.push(a.value),a=this.removeNode(a);for(null===a&&(a=this.tail),a!==this.head&&a!==this.tail&&(a=a.prev),r=0;r<n.length;r++)a=s(this,a,n[r]);return o},r.prototype.reverse=function(){for(var e=this.head,t=this.tail,n=e;null!==n;n=n.prev){var r=n.prev;n.prev=n.next,n.next=r}return this.head=t,this.tail=e,this};try{e("./iterator.js")(r)}catch(e){}},{"./iterator.js":82}]},{},[12])(12);var Pt=Et(Rt.exports);class jt{constructor(){this.store={},this.store={}}clear(){this.store={}}getItem(e){return this.store[e]||null}setItem(e,t){this.store[e]=String(t)}removeItem(e){delete this.store[e]}get length(){return Object.keys(this.store).length}key(e){return Object.keys(this.store)[e]||null}}const Ut=()=>"undefined"!=typeof window&&window.localStorage?window:{localStorage:new jt},xt=()=>b.default.v4().toString();let Dt=0;if("undefined"!=typeof BroadcastChannel&&"undefined"!=typeof window){const e=xt(),t={},n=new BroadcastChannel("amity_ts_sdk");let r;n.postMessage({type:"startup",tabId:e}),n.onmessage=({data:s})=>{s.tabId!==e&&("startup"===s.type&&n.postMessage({type:"identify",tabId:e,tabIndex:Dt}),"identify"===s.type&&void 0!==s.tabIndex&&s.tabId&&(t[s.tabId]=s.tabIndex,r||(r=setTimeout((()=>{const e=Object.values(t).sort();e&&0!==e.length&&(Dt=e.reduce(((e,t)=>e<t?e:t+1),0))}),15))))}}const Nt=async()=>{var e;const t=`${null!==(e=be().prefixDeviceIdKey)&&void 0!==e?e:""}#deviceId`,n=await(async e=>{if("undefined"!=typeof navigator&&"ReactNative"===navigator.product)return await v.default.getItem(e);return new Promise((t=>{t(Ut().localStorage.getItem(e))}))})(t);if(n)return n;const r=`ascWebSdk#${xt()}`;return await(async(e,t)=>"undefined"!=typeof navigator&&"ReactNative"===navigator.product?(await v.default.setItem(e,t),!0):new Promise((n=>{Ut().localStorage.setItem(e,t),n(!0)})))(t,r),r},Bt=()=>{const e=(()=>{var e,t;return(null===(e=gt.versions)||void 0===e?void 0:e.node)?gt.versions.node:navigator?`${navigator.product.toLowerCase()}#${null!==(t=navigator.userAgent)&&void 0!==t?t:"unknown_agent"}`:"unknown_model"})();return{kind:"web",model:e,sdkVersion:U}},qt=1e3;var Ft;!function(e){e[e.IDENTIFIER_REJECTED=2]="IDENTIFIER_REJECTED",e[e.BAD_USERNAME_OR_PASSWORD=134]="BAD_USERNAME_OR_PASSWORD",e[e.NOT_AUTHORIZED=135]="NOT_AUTHORIZED"}(Ft||(Ft={}));const Lt=e=>{let t,n="disconnected";const r=new Set,s=e=>{n!==e&&(n=e,r.forEach((t=>{t(e)})))};return{connect:async function(n){const r=await(async e=>`mqttjs_${await Nt()}_${e}_${Dt}`)(n.userId);return s("connecting"),t&&(s("disconnecting"),t.removeAllListeners(),t.end(!0)),t=Pt.connect(e,function(e){return Object.assign({clean:!1,clientId:`mqttjs_ + ${Math.random().toString(16).substring(2,10)}`,protocolId:"MQTT",protocolVersion:4,reconnectPeriod:qt,will:{topic:"WillMsg",payload:"Connection Closed abnormally..!",qos:0,retain:!1},resubscribe:!0},e)}({username:n.userId,password:n.accessToken,clientId:r})),t.on("connect",(()=>{t.options.reconnectPeriod=qt,s("connected"),(()=>{const e=[ht(ct()),ht(lt()),ht(dt()),ht(ut()),ht(at(ze())),ht(it()),ht(pt())]})()})),t.on("error",(e=>{switch(e.code){case 2:case 134:case 135:t.end(),s("disconnected")}})),t.on("reconnect",(()=>{s("reconnecting"),t.options.reconnectPeriod=Math.min(2*(t.options.reconnectPeriod||qt),8e3)})),t.on("close",(()=>{s("disconnected")})),t.on("disconnect",(()=>{s("disconnected")})),new Promise((e=>t.once("connect",(()=>e()))))},async disconnect(){if(this.connected)return new Promise((e=>null==t?void 0:t.end(!0,void 0,(()=>e()))))},reconnect:async()=>new Promise((e=>{null==t||t.reconnect(),e()})),listen:e=>(r.add(e),n&&e(n),()=>{r.delete(e)}),get connected(){return!!(null==t?void 0:t.connected)},on(e,n){null==t||t.on(e,n)},once(e,n){null==t||t.once(e,n)},off(e,n){void 0!==n?null==t||t.off(e,n):null==t||t.removeAllListeners(e)},removeAllListeners(){null==t||t.removeAllListeners()},subscribe(e,n){const r=(t,r)=>{var s;if(t||128===(null===(s=r[0])||void 0===s?void 0:s.qos)){const r=t?new pe(t.message,8e5,"error"):new me(8e5,"error");console.warn(`Failed to subscribe to topic ${e}`,r),null==n||n(r)}else console.log(`Subscribed to topic ${e}`),null==n||n()};return t?t.subscribe(e,{qos:0},r):r(new Error("No connection to broker"),[]),()=>null==t?void 0:t.unsubscribe(e)},unsubscribe(e){null==t||t.unsubscribe(e)}}},Kt=(e={},t,n=!0)=>{Object.entries(e).forEach((([e,r])=>{const s=ue[e];if(!s)return;const a=de(s);a&&r.forEach((e=>{(n?Se:ke)([s,"get",a(e)],e,t)}))}))},$t=(e,t)=>{const{log:n,cache:r}=be(),s=[e,K,t],a={cachedAt:Date.now()};r&&(n("cache/api/pushToTombstone",{cacheKey:s,data:a}),Te([e,"get",t],!0),Se(s,a))};function zt(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var s=0;for(r=Object.getOwnPropertySymbols(e);s<r.length;s++)t.indexOf(r[s])<0&&Object.prototype.propertyIsEnumerable.call(e,r[s])&&(n[r[s]]=e[r[s]])}return n}const Qt=(e,t="userId",n="user")=>{var r;return null!==(r=null==e?void 0:e.map((e=>((e,t="userId",n="user")=>e[n]?e:Object.assign({get[n](){var n;if(!be().cache)return;return(null===(n=Ie(["user","get",e[t]]))||void 0===n?void 0:n.data)||void 0}},e))(e,t,n))))&&void 0!==r?r:e},Vt=(e,t,n="userId",r="user")=>{const s=e,a=t,o=s[a],i=zt(s,["symbol"==typeof a?a:a+""]),c=Qt(o,n,r);return Object.assign(Object.assign({},i),{[t]:c})};function Ht(e){return e.map((e=>{var{isMentioned:t}=e,n=zt(e,["isMentioned"]);return Object.assign({hasMentioned:t},n)}))}function Wt(e){return Ht(e)}function Jt(e){return Ht(e)}const Gt=e=>{var t,n;return null!==(n=null===(t=Ie(["messagePreviewChannel","get",e]))||void 0===t?void 0:t.data)&&void 0!==n?n:null},Yt=["analytic","normal-priority"],Zt=["analytic","high-priority"],Xt=async e=>{const t=be(),n={activities:e};await t.http.post("/api/v1/analytics/activities",n)};class en{constructor(){this._timer=void 0,this._high_priority_timer=void 0}start(){this.syncCapturedEvent(),this._timer=setInterval((()=>{this.syncCapturedEvent()}),6e4),this._high_priority_timer=setInterval((()=>{this.syncHighPriorityCapturedEvent()}),1e4)}stop(){this._timer&&(clearInterval(this._timer),this._timer=void 0),this._high_priority_timer&&(clearInterval(this._high_priority_timer),this._high_priority_timer=void 0)}async syncCapturedEvent(){try{const e=Ie(Yt);if(!(null==e?void 0:e.data))return;if(0===e.data.event.length)return;const t=e.data.event;await Xt(t),Te(Yt)}catch(e){this.stop(),Te(Yt)}}async syncHighPriorityCapturedEvent(){try{const e=Ie(Zt);if(!(null==e?void 0:e.data))return;if(0===e.data.event.length)return;const t=e.data.event;await Xt(t),Te(Zt)}catch(e){this.stop(),Te(Zt)}}}class tn{constructor(){this._expireTime=3e5,this._poolLimit=1e3,this._recentViewed={},this._recentHighPriorityViewed={},this._throttleStoryTimer=void 0,this._bufferNewSeenStoryReferenceIds=[]}isAbleToEnqueue({uniqueId:e,expireTime:t,isHighPriority:n=!1}){const r=new Date,s=n?this._recentHighPriorityViewed[e]:this._recentViewed[e];if(!s)return!0;return!(r.getTime()-s.getTime()<t)}markAs({uniqueId:e,contentId:t,contentType:n,activityType:r,metadata:s}){if(!this.isAbleToEnqueue({uniqueId:e,expireTime:this._expireTime}))return;const a=new Date,o={event:[]},i=Ie(Yt);(null==i?void 0:i.data)&&(o.event=i.data.event),o.event.length>=this._poolLimit&&o.event.shift();const c={contentId:t,contentType:n,activityType:r,timestamp:a.toISOString()};s&&(c.metadata=s),o.event.push(c),ke(Yt,o),this._recentViewed[e]=a}markPostAsViewed(e){this.markAs({uniqueId:e,contentId:e,contentType:"post",activityType:"view"})}markStory(e,t){if(!e.expiresAt)return;const n=new Date,r=new Date(e.expiresAt);if(!this.isAbleToEnqueue({uniqueId:e.storyId,expireTime:r.getTime(),isHighPriority:!0}))return;const s={event:[]},a=Ie(Zt);if((null==a?void 0:a.data)&&(s.event=a.data.event),s.event.length>=this._poolLimit&&s.event.shift(),s.event.push({contentId:e.storyId,contentType:"story",activityType:t,timestamp:n.toISOString()}),ke(Zt,s),this._recentHighPriorityViewed[e.storyId]=n,"linkClicked"===t)return;Se(["story-seen","get",e.storyId],(new Date).toISOString());const o=Ie(["story-last-seen",e.targetId]);(null==o?void 0:o.data)?new Date(o.data).getTime()<new Date(e.expiresAt).getTime()&&Se(["story-last-seen",e.targetId],e.expiresAt):Se(["story-last-seen",e.targetId],e.expiresAt),this._bufferNewSeenStoryReferenceIds.push(e.referenceId),this._throttleStoryTimer||(this._throttleStoryTimer=setTimeout((()=>{clearTimeout(this._throttleStoryTimer),Ze("local.story.reload",{referenceIds:this._bufferNewSeenStoryReferenceIds}),this._bufferNewSeenStoryReferenceIds=[]}),300))}resetAllBuckets(){this._recentViewed={},this._recentHighPriorityViewed={},Te(Yt),Te(Zt)}markStoryAsViewed(e){this.markStory(e,"view")}markStoryAsClicked(e){this.markStory(e,"linkClicked")}markAdAsViewed(e,t){const n={placement:t},r="view";this.markAs({uniqueId:`${e.adId}.view.${t}`,contentId:e.adId,contentType:"ad",activityType:r,metadata:n})}markAdAsClicked(e,t){const n={placement:t},r="linkClicked";this.markAs({uniqueId:`${e.adId}.linkClicked.${t}`,contentId:e.adId,contentType:"ad",activityType:r,metadata:n})}}class nn{constructor(){this._client=be(),this._eventCapturer=new tn,this._eventSyncer=new en}markPostAsViewed(e){"established"!==this._client.sessionState&&"tokenExpired"!==this._client.sessionState||this._eventCapturer.markPostAsViewed(e)}markStoryAsViewed(e){"established"!==this._client.sessionState&&"tokenExpired"!==this._client.sessionState||this._eventCapturer.markStoryAsViewed(e)}markAdAsViewed(e,t){"established"!==this._client.sessionState&&"tokenExpired"!==this._client.sessionState||this._eventCapturer.markAdAsViewed(e,t)}markAdAsClicked(e,t){"established"!==this._client.sessionState&&"tokenExpired"!==this._client.sessionState||this._eventCapturer.markAdAsClicked(e,t)}markStoryAsClicked(e){"established"!==this._client.sessionState&&"tokenExpired"!==this._client.sessionState||this._eventCapturer.markStoryAsClicked(e)}established(){this._eventSyncer.start()}handleTokenExpired(){this._stopAndDestroy()}destroy(){this._stopAndDestroy()}_stopAndDestroy(){this._eventSyncer.stop(),this._eventCapturer.resetAllBuckets()}}let rn;var sn=()=>(rn||(rn=new nn),rn);const an=e=>Object.assign(Object.assign({},e),{get avatar(){var t;if(!e.avatarFileId)return;return null===(t=Ie(["file","get",`${e.avatarFileId}`]))||void 0===t?void 0:t.data}});class on{constructor(e,t,n){this._syncingStoriesCount=0,this._errorStoriesCount=0,this._targetId=e,this._lastStoryExpiresAt=t,this._lastStorySeenExpiresAt=n,this.cacheStoryExpireTime=Ie(["story-expire",this._targetId]),this.cacheStoreSeenTime=Ie(["story-last-seen",this._targetId]),this.getTotalStoryByStatus()}get lastStoryExpiresAt(){return this._lastStoryExpiresAt?new Date(this._lastStoryExpiresAt).getTime():0}get lastStorySeenExpiresAt(){return this._lastStorySeenExpiresAt?new Date(this._lastStorySeenExpiresAt).getTime():0}get localLastStoryExpires(){var e,t;return(null===(e=this.cacheStoryExpireTime)||void 0===e?void 0:e.data)?new Date(null===(t=this.cacheStoryExpireTime)||void 0===t?void 0:t.data).getTime():0}get localLastStorySeenExpiresAt(){var e,t;return(null===(e=this.cacheStoreSeenTime)||void 0===e?void 0:e.data)?new Date(null===(t=this.cacheStoreSeenTime)||void 0===t?void 0:t.data).getTime():0}get isContainUnSyncedStory(){const e=Ie(["story-sync-state",this._targetId]);return!!(null==e?void 0:e.data)&&["syncing","error"].includes(e.data)}getLocalLastSortingDate(){return this.isContainUnSyncedStory?this.localLastStoryExpires:this.lastStoryExpiresAt}getHasUnseenFlag(){const e=(new Date).getTime(),t=Math.max(this.lastStorySeenExpiresAt,this.localLastStorySeenExpiresAt);return Ie(["story-sync-state",this._targetId]),this.isContainUnSyncedStory?this.localLastStoryExpires>e&&this.localLastStoryExpires>t:this.lastStoryExpiresAt>e&&this.lastStoryExpiresAt>t}getTotalStoryByStatus(){const e=Ce(["story","get"]);if(!e)return this._errorStoriesCount=0,void(this._syncingStoriesCount=0);const t=e.reduce(((e,t)=>{const{data:{targetId:n,syncState:r,isDeleted:s}}=t;return n!==this._targetId||s||(e[r]+=1),e}),{syncing:0,error:0,synced:0});this._errorStoriesCount=t.error,this._syncingStoriesCount=t.syncing}get syncingStoriesCount(){return this._syncingStoriesCount}get failedStoriesCount(){return this._errorStoriesCount}}const cn=e=>{const{targetType:t,targetId:n,lastStoryExpiresAt:r,lastStorySeenExpiresAt:s,targetUpdatedAt:a,localFilter:o}=e,i=new on(n,r,s);return{targetType:t,targetId:n,lastStoryExpiresAt:r,updatedAt:a,hasUnseen:i.getHasUnseenFlag(),syncingStoriesCount:i.syncingStoriesCount,failedStoriesCount:i.failedStoriesCount,localFilter:o,localLastExpires:i.localLastStoryExpires,localLastSeen:i.localLastStorySeenExpiresAt,localSortingDate:i.getLocalLastSortingDate()}};function ln(e,t){if(null==e||null==t)return e===t;if(e.constructor!==t.constructor)return!1;if(e instanceof Function)return e===t;if(e instanceof RegExp)return e===t;if(e===t||e.valueOf()===t.valueOf())return!0;if(Array.isArray(e)&&e.length!==t.length)return!1;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(!ln(e[n],t[n]))return!1;return!0}if(e instanceof Date)return!1;if(!(e instanceof Object))return!1;if(!(t instanceof Object))return!1;const n=Object.keys(e);return Object.keys(t).every((e=>-1!==n.indexOf(e)))&&n.every((n=>ln(e[n],t[n])))}function dn(e){return null!=e}const un=e=>Object.assign(Object.assign({},e),{get target(){const t={type:e.targetType};if("user"===e.targetType)return Object.assign(Object.assign({},t),{userId:e.targetId});if("content"===t.type)return Object.assign(Object.assign({},t),{contentId:e.targetId});if("community"===t.type){const n=Ie(["communityUsers","get",`${e.targetId}#${e.userId}`]);return Object.assign(Object.assign({},t),{communityId:e.targetId,creatorMember:null==n?void 0:n.data})}return{type:"unknown"}},get creator(){const t=Ie(["user","get",e.userId]);if(null==t?void 0:t.data)return an(t.data)},get childrenComment(){return e.children.map((e=>{const t=Ie(["comment","get",e]);if(null==t?void 0:t.data)return null==t?void 0:t.data})).filter(dn).map((e=>un(e)))}});function hn(e){return!!(e.data&&"string"!=typeof e.data&&"videoFileId"in e.data&&"thumbnailFileId"in e.data&&"video"===e.dataType)}const pn=e=>Object.assign(Object.assign({},e),{analytics:{markAsViewed:()=>{sn().markPostAsViewed(e.postId)}},get latestComments(){return e.comments&&e.comments.map((e=>{var t;const n=null===(t=Ie(["comment","get",e]))||void 0===t?void 0:t.data;return n?un(n):null})).filter(Boolean)||[]},get creator(){const t=Ie(["user","get",e.postedUserId]);if(null==t?void 0:t.data)return an(t.data)},getImageInfo(){var t,n;return function(e){return!(!e.data||"string"==typeof e.data||!("fileId"in e.data)||"image"!==e.dataType)}(e)?null===(n=Ie(["file","get",null===(t=null==e?void 0:e.data)||void 0===t?void 0:t.fileId]))||void 0===n?void 0:n.data:void 0},getVideoInfo(){var t,n,r;return hn(e)?null===(r=Ie(["file","get",null===(n=null===(t=null==e?void 0:e.data)||void 0===t?void 0:t.videoFileId)||void 0===n?void 0:n.original]))||void 0===r?void 0:r.data:void 0},getVideoThumbnailInfo(){var t,n;return hn(e)?null===(n=Ie(["file","get",null===(t=null==e?void 0:e.data)||void 0===t?void 0:t.thumbnailFileId]))||void 0===n?void 0:n.data:void 0},getFileInfo(){var t,n;return function(e){return!(!e.data||"string"==typeof e.data||!("fileId"in e.data)||"file"!==e.dataType)}(e)?null===(n=Ie(["file","get",null===(t=null==e?void 0:e.data)||void 0===t?void 0:t.fileId]))||void 0===n?void 0:n.data:void 0}}),fn=(e,t)=>{var n;return null!==(n=null!=t?t:(e=>{var t,n;const r={creatorId:"creatorPrivateId"in e?e.creatorPrivateId:e.creatorId,feedId:null!==(t=e.messageFeedId)&&void 0!==t?t:e.subChannelId,contentId:e.messageId};return null===(n=Ie(["messageMarker","get",de("messageMarker")(r)]))||void 0===n?void 0:n.data})(e))&&void 0!==n?n:{readCount:0,deliveredCount:0}};class mn{constructor(){this.isActive=!0,this.MAX_RETRY=3,this.JOB_QUEUE_SIZE=120,this.jobQueue=[],this.RECEIPT_SYNC_INTERVAL=1,this.client=be(),this.getUnsyncJobs()}startSyncReadReceipt(){this.timer=setInterval((()=>{this.syncReadReceipts()}),1e3*this.RECEIPT_SYNC_INTERVAL)}syncReadReceipts(){if(0===this.jobQueue.length||!1===this.isActive)return;const e=this.getReadReceipts();e&&this.markReadApi(e)}getUnsyncJobs(){var e;const t=null===(e=Ce(["readReceipt"]))||void 0===e?void 0:e.filter((({data:e})=>e.latestSyncSegment<e.latestSegment));null==t||t.forEach((({data:e})=>{this.enqueueReadReceipt(e.channelId,e.latestSegment)}))}getReadReceipts(){const e=this.jobQueue.splice(0,this.jobQueue.length);if(0!==e.length)return e.filter((e=>{var t;const n=null===(t=Ie(["readReceipt",e.channelId]))||void 0===t?void 0:t.data;return!!n&&n.latestSegment>n.latestSyncSegment}))}async markReadApi(e){var t;const n=e.map((e=>({channelId:e.channelId,readToSegment:e.segment})));if(await(async e=>{const t=be();try{return await t.http.post("api/v3/channels/seen",{channels:e}),!0}catch(e){return!1}})(n))for(let n=0;n<e.length;n+=1){const r=["readReceipt",e[n].channelId],s=null===(t=Ie(r))||void 0===t?void 0:t.data;Se(r,Object.assign(Object.assign({},s),{latestSyncSegment:e[n].segment}))}else for(let t=0;t<e.length;t+=1){if(e[t].retryCount>=this.MAX_RETRY)return;const n=Object.assign(Object.assign({},e[t]),{syncState:"create",retryCount:e[t].retryCount+1});this.enqueueJob(n)}}startObservingReadReceiptQueue(){this.client.useLegacyUnreadCount&&(this.isActive=!0,this.startSyncReadReceipt())}stopObservingReadReceiptQueue(){this.isActive=!1,this.jobQueue.map((e=>"syncing"===e.syncState?Object.assign(Object.assign({},e),{syncState:"create"}):e)),this.timer&&clearInterval(this.timer)}onSessionEstablished(){this.startObservingReadReceiptQueue()}onSessionDestroyed(){this.stopObservingReadReceiptQueue(),this.jobQueue=[]}onTokenExpired(){this.stopObservingReadReceiptQueue()}onNetworkOffline(){this.stopObservingReadReceiptQueue()}onNetworkOnline(){this.startObservingReadReceiptQueue()}markRead(e,t){var n;const r=["channelUnread","get",e],s=null===(n=Ie(r))||void 0===n?void 0:n.data;"number"==typeof(null==s?void 0:s.readToSegment)&&s&&t>s.readToSegment&&(s.readToSegment=t,s.unreadCount=Math.max(s.lastSegment-t,0),Se(r,s),Ze("local.channelUnread.updated",[s])),this.enqueueReadReceipt(e,t)}enqueueReadReceipt(e,t){var n;const r=null===(n=Ie(["readReceipt",e]))||void 0===n?void 0:n.data;if(r){if(r.latestSegment<t)Se(["readReceipt",e],Object.assign(Object.assign({},r),{latestSegment:t}));else if(r.latestSyncSegment>=t)return}else{Se(["readReceipt",e],{channelId:e,latestSegment:t,latestSyncSegment:0})}let s=this.getSyncJob(e);null===s||"syncing"===s.syncState?(s={channelId:e,segment:t,syncState:"create",retryCount:0},this.enqueueJob(s)):s.segment<t&&(s.segment=t)}getSyncJob(e){const{jobQueue:t}=this;return t.find((t=>t.channelId===e))||null}enqueueJob(e){this.jobQueue.length<this.JOB_QUEUE_SIZE||this.jobQueue.shift(),this.jobQueue.push(e)}}let gn=null;var yn=()=>(gn||(gn=new mn),gn);const vn=e=>{var t;const n=["channelUnreadInfo","get",e],r=null===(t=Ie(n))||void 0===t?void 0:t.data,s=Ce(["subChannelUnreadInfo","get"]);let a=0,o=!1;if(s&&(null==s?void 0:s.length)>0){const t=null==s?void 0:s.filter((({data:t})=>t.channelId===e&&!t.isDeleted));a=t.map((({data:e})=>e.unreadCount)).reduce(((e,t)=>e+t),0),o=t.some((({data:e})=>e.isMentioned))}const i=Object.assign(Object.assign({},null!=r?r:{channelId:e,createdAt:(new Date).toISOString()}),{updatedAt:(new Date).toISOString(),unreadCount:a,isMentioned:o});return Se(n,i),i};class bn{constructor(){this.isActive=!0,this.MAX_RETRY=3,this.JOB_QUEUE_SIZE=120,this.jobQueue=[],this.RECEIPT_SYNC_INTERVAL=1,this.client=be(),this.getUnsyncJobs()}startSyncReadReceipt(){this.timer=setInterval((()=>{this.syncReadReceipts()}),1e3*this.RECEIPT_SYNC_INTERVAL)}syncReadReceipts(){if(0===this.jobQueue.length||!1===this.isActive)return;const e=this.getReadReceipt();e&&this.markReadApi(e)}getUnsyncJobs(){var e;const t=null===(e=Ce(["legacyReadReceipt"]))||void 0===e?void 0:e.filter((({data:e})=>e.latestSyncSegment<e.latestSegment));null==t||t.forEach((({data:e})=>{this.enqueueReadReceipt(e.subChannelId,e.latestSegment)}))}getReadReceipt(){var e;const t=this.jobQueue[0];if(!t)return;if("syncing"===t.syncState)return;const n=null===(e=Ie(["legacyReadReceipt",t.subChannelId]))||void 0===e?void 0:e.data;return n?(null==n?void 0:n.latestSegment)>(null==n?void 0:n.latestSyncSegment)?(t.segment=n.latestSegment,t):(this.removeSynedReceipt(n.subChannelId,n.latestSegment),this.getReadReceipt()):void 0}async markReadApi(e){var t;const n=e;n.syncState="syncing";const{subChannelId:r,segment:s}=n,a=await(async({subChannelId:e,readToSegment:t})=>{const n=be();n.log("subChannel/markAsReadBySegment",e);try{return await n.http.put(`/api/v1/markers/message-feeds/${e}/mark-read`,{readToSegment:t}),!0}catch(e){return!1}})({subChannelId:r,readToSegment:s});if(a){this.removeSynedReceipt(e.subChannelId,e.segment);const n=null===(t=Ie(["legacyReadReceipt",r]))||void 0===t?void 0:t.data;Se(["legacyReadReceipt",r],Object.assign(Object.assign({},n),{latestSyncSegment:s}))}else a||(n.retryCount>this.MAX_RETRY?this.removeJobFromQueue(n):(n.retryCount+=1,n.syncState="create"))}removeSynedReceipt(e,t){this.jobQueue.forEach((n=>{n.subChannelId===e&&n.segment<=t&&this.removeJobFromQueue(n)}))}startObservingReadReceiptQueue(){this.client.isUnreadCountEnabled&&(this.isActive=!0,this.startSyncReadReceipt())}stopObservingReadReceiptQueue(){this.isActive=!1;this.jobQueue.map((e=>"syncing"===e.syncState?Object.assign(Object.assign({},e),{syncState:"create"}):e)),this.timer&&clearInterval(this.timer)}onSessionEstablished(){this.startObservingReadReceiptQueue()}onSessionDestroyed(){this.stopObservingReadReceiptQueue(),this.jobQueue=[]}onTokenExpired(){this.stopObservingReadReceiptQueue()}onNetworkOffline(){this.stopObservingReadReceiptQueue()}onNetworkOnline(){this.startObservingReadReceiptQueue()}markRead(e,t){var n;const r=["subChannelUnreadInfo","get",e],s=null===(n=Ie(r))||void 0===n?void 0:n.data;if(s&&t>s.readToSegment){s.readToSegment=t,s.unreadCount=Math.max(s.lastSegment-t,0);const e=vn(s.channelId);Ze("local.channelUnreadInfo.updated",e),Se(r,s),Ze("local.subChannelUnread.updated",s)}this.enqueueReadReceipt(e,t)}enqueueReadReceipt(e,t){var n;const r=null===(n=Ie(["legacyReadReceipt",e]))||void 0===n?void 0:n.data;if(r){if(r.latestSegment<t)Se(["legacyReadReceipt",e],Object.assign(Object.assign({},r),{latestSegment:t}));else if(r.latestSyncSegment>=t)return}else{Se(["legacyReadReceipt",e],{subChannelId:e,latestSegment:t,latestSyncSegment:0})}let s=this.getSyncJob(e);null===s||"syncing"===s.syncState?(s={subChannelId:e,segment:t,syncState:"create",retryCount:0},this.enqueueJob(s)):s.segment<t&&(s.segment=t)}getSyncJob(e){return this.jobQueue.find((t=>t.subChannelId===e))||null}enqueueJob(e){this.jobQueue.length<this.JOB_QUEUE_SIZE||this.jobQueue.shift(),this.jobQueue.push(e)}removeJobFromQueue(e){const t=this.jobQueue.indexOf(e);t>-1&&this.jobQueue.splice(t,1)}}let wn=null;var Cn=()=>(wn||(wn=new bn),wn);const In=e=>{if(be().useLegacyUnreadCount){yn().markRead(e.channelId,e.channelSegment)}else{Cn().markRead(e.subChannelId,e.channelSegment)}};function Sn(e,t){return Object.create(Object.getPrototypeOf(e),Object.assign(Object.assign({},Object.getOwnPropertyDescriptors(e)),Object.getOwnPropertyDescriptors(t)))}const _n={ad:e=>{const t=sn(),{image9_16:n,image1_1:r}=e,s=zt(e,["image9_16","image1_1"]);return Object.assign(Object.assign({},s),{analytics:{markAsSeen:n=>{t.markAdAsViewed(e,n)},markLinkAsClicked:n=>{t.markAdAsClicked(e,n)}},get advertiser(){var t,n;const r=null===(t=Ie(["advertiser","get",e.advertiserId]))||void 0===t?void 0:t.data;if(!r)return;const s=null===(n=Ie(["file","get",r.avatarFileId]))||void 0===n?void 0:n.data;return Object.assign(Object.assign({},r),{avatar:s})},get image1_1(){const e=Ie(["file","get",r]);if(e)return e.data||void 0},get image9_16(){const e=Ie(["file","get",n]);if(e)return e.data||void 0}})},comment:un,post:pn,user:an,category:e=>Object.assign(Object.assign({},e),{get avatar(){var t;if(!e.avatarFileId)return;return null===(t=Ie(["file","get",`${e.avatarFileId}`]))||void 0===t?void 0:t.data}}),stream:e=>Object.assign(Object.assign({},e),{get moderation(){var t;return null===(t=Ie(["streamModeration","get",e.streamId]))||void 0===t?void 0:t.data},get post(){var t;if("post"===e.referenceType)return null===(t=Ie(["post","get",e.referenceId]))||void 0===t?void 0:t.data},get community(){var t;if("community"===e.targetType)return null===(t=Ie(["community","get",e.targetId]))||void 0===t?void 0:t.data},get user(){var t;return null===(t=Ie(["user","get",e.userId]))||void 0===t?void 0:t.data}}),story:e=>{const t=sn(),n=Ie(["storyTarget","get",e.targetId]),r=Ie(["community","get",e.targetId]);return Object.assign(Object.assign({},e),{analytics:{markAsSeen:()=>{e.expiresAt&&"synced"===e.syncState&&t.markStoryAsViewed(e)},markLinkAsClicked:()=>{e.expiresAt&&"synced"===e.syncState&&t.markStoryAsClicked(e)}},get videoData(){var t,n;const r=Ie(["file","get",null===(n=null===(t=e.data)||void 0===t?void 0:t.videoFileId)||void 0===n?void 0:n.original]);if(!r)return;const{data:s}=r;return s||void 0},get imageData(){var t,n;if(!(null===(t=e.data)||void 0===t?void 0:t.fileId))return;const r=Ie(["file","get",null===(n=e.data)||void 0===n?void 0:n.fileId]);if(!r)return;const{data:s}=r;return s?Object.assign(Object.assign({},s),{fileUrl:`${s.fileUrl}?size=full`}):void 0},get community(){if("community"===e.targetType&&r)return(null==r?void 0:r.data)||void 0},get communityCategories(){if("community"!==e.targetType)return;if(!r)return;const{data:{categoryIds:t}}=r;return 0!==t.length?t.map((e=>{const t=Ie(["category","get",e]);return(null==t?void 0:t.data)||void 0})).filter((e=>void 0!==e)):void 0},get creator(){const t=Ie(["user","get",e.creatorPublicId]);if(null==t?void 0:t.data)return an(t.data)},get storyTarget(){if(null==n?void 0:n.data)return cn(n.data)},get isSeen(){const t=Ie(["story-last-seen",e.targetId]);if(!(null==n?void 0:n.data))return!1;const r=(null==t?void 0:t.data)?new Date(t.data).getTime():0,s=new Date(null==n?void 0:n.data.lastStorySeenExpiresAt).getTime()||0,a=new Date(e.expiresAt).getTime();return Math.max(r,s)>=a}})},storyTarget:cn,message:e=>{const t=zt(e,["creatorPrivateId"]);return Object.assign(Object.assign({},t),{get readCount(){return fn(e).readCount},get deliveredCount(){return fn(e).deliveredCount},get creator(){var t;return null===(t=Ie(["user","get",e.creatorId]))||void 0===t?void 0:t.data},markRead:()=>In(e)})},reactor:e=>Object.assign(Object.assign({},e),{get user(){var t;const n=null===(t=Ie(["user","get",e.userId]))||void 0===t?void 0:t.data;if(n)return an(n)}}),channel:e=>Sn(e,{markAsRead:()=>(async e=>{const t=be();t.log("channel/markAsRead",e);const{data:n}=await t.http.put(`/api/v1/markers/channels/${e}/mark-read`),{userMarkers:r,userEntityMarkers:s,userFeedMarkers:a}=n,o=zt(n,["userMarkers","userEntityMarkers","userFeedMarkers"]),i=t.cache&&Date.now(),c=Wt(s),l=Jt(a);return t.cache&&Kt(Object.assign({userMarkers:r,userEntityMarkers:c,userFeedMarkers:l},o),{cachedAt:i}),Ze("local.channelMarker.updated",{userEntityMarkers:c}),Ze("local.subChannelMarker.updated",{userFeedMarkers:l}),!0})(e.channelInternalId)}),pinnedPost:e=>{var t;const n=Ie(["post","get",e.referenceId]),r=null===(t=Ce(["user","get"]).find((t=>{var n;return(null===(n=t.data)||void 0===n?void 0:n.userInternalId)===e.pinnedBy})))||void 0===t?void 0:t.data;return Object.assign(Object.assign({},e),{pinnedBy:r,get post(){if(null==n?void 0:n.data)return pn(n.data)},get target(){const e=Ie(["pinTarget","get",null==n?void 0:n.data.targetId]);if(null==e?void 0:e.data)return null==e?void 0:e.data}})},notificationTray:e=>Object.assign(Object.assign({},e),{isSeen:e.lastSeenAt>e.lastOccurredAt,isRecent:new Date(e.lastOccurredAt).getTime()>=Date.now()-6048e5,users:e.actors.map((({publicId:e})=>Ie(["user","get",e]))).filter(dn).map((({data:e})=>e)).map((e=>an(e)))})},kn=e=>{var t,n;const r={messagePreviewChannel:null!==(n=null===(t=e.messagePreviews)||void 0===t?void 0:t.map((t=>(t=>{var n;const r=null===(n=e.messageFeedsInfo)||void 0===n?void 0:n.find((e=>e.messageFeedId===t.messageFeedId)),{channelPublicId:s,messageFeedId:a,data:o,dataType:i,isDeleted:c,segment:l,creatorPublicId:d,createdAt:u,updatedAt:h}=t;return{channelId:s,subChannelId:a,data:o,dataType:i,isDeleted:c,segment:l,creatorId:d,createdAt:u,updatedAt:h,subChannelName:null==r?void 0:r.name,messagePreviewId:null==r?void 0:r.messagePreviewId,subChannelUpdatedAt:null==r?void 0:r.updatedAt}})(t))))&&void 0!==n?n:[]};Kt(r)},Tn=e=>{var t,n;return null!==(n=null===(t=Ie(["messagePreviewSubChannel","get",e]))||void 0===t?void 0:t.data)&&void 0!==n?n:null},On=e=>{var t;const n=e.messagePreviewId?Tn(e.subChannelId):null,r=n?Object.assign(Object.assign({},n),{user:null===(t=Ie(["user","get",null==n?void 0:n.creatorId]))||void 0===t?void 0:t.data}):null;return Object.assign(Object.assign({},e),{messagePreview:r})},An=e=>{var t,n;const r={messagePreviewSubChannel:null!==(n=null===(t=e.messages)||void 0===t?void 0:t.map((t=>(t=>{var n;const r=null===(n=e.messageFeeds)||void 0===n?void 0:n.find((e=>e.messageFeedId===t.messageFeedId)),{channelPublicId:s,messageFeedId:a,messageId:o,creatorPublicId:i,data:c,dataType:l,isDeleted:d,segment:u,createdAt:h,updatedAt:p}=t;return{messagePreviewId:o,channelId:s,subChannelId:a,data:c,dataType:l,isDeleted:d,segment:u,creatorId:i,createdAt:h,updatedAt:p,subChannelName:null==r?void 0:r.name,subChannelUpdatedAt:null==r?void 0:r.updatedAt}})(t))))&&void 0!==n?n:[]};Kt(r)};function En(e,t,n){Se(["subChannel","get",e],Sn(t,n))}const Mn=(e,t)=>{const{log:n,cache:r}=be(),s=[e,K,t];if(!r)return;n("cache/api/isInTombstone",s);const a=Ie(s),{lifeSpan:o}=oe("cache_then_server",18e4);if(a&&se(a.data,o))throw new fe("Item not found!",400400,"error")},Rn=e=>{const{feedMarkers:t,userFeedMarkers:n}=e;if(t.length>0&&n.length>0){const e=[],r=new Map(t.map((e=>[e.feedId,e])));n.forEach((t=>{const n=r.get(t.feedId);if(n&&n.feedId===t.feedId){const r=n.lastSegment-t.readToSegment,s={subChannelId:n.feedId,channelId:n.entityId,readToSegment:t.readToSegment,lastSegment:n.lastSegment,lastMentionSegment:t.lastMentionSegment,unreadCount:Math.max(0,r),isMentioned:t.isMentioned,isDeleted:n.isDeleted,createdAt:t.createdAt,updatedAt:t.updatedAt};Kt({subChannelUnreadInfo:[s]}),e.includes(n.entityId)||e.push(n.entityId)}})),e.forEach((e=>{vn(e)}))}},Pn=async()=>{const e=be();e.log("channel/getUserMarker");const{data:t}=await e.http.get("/api/v1/markers/userMarker"),{userMarkers:n}=t,r=e.cache&&Date.now();e.cache&&Kt({userMarkers:n},{cachedAt:r}),Ze("local.userMarker.fetched",{userMarkers:n});return{data:n.reduce(((e,t)=>null==e||new Date(e.lastSyncAt).getTime()<new Date(t.lastSyncAt).getTime()?t:e),void 0),cachedAt:r}},jn=e=>!0===e&&void 0;function Un(e,t,n){var r,s;if(n)return n.hasMentioned;const a=be();if(a.isUnreadCountEnabled&&a.getMarkerSyncConsistentMode()){const e=null===(r=Ie(["subChannelUnreadInfo","get",t]))||void 0===r?void 0:r.data;return!!e&&e.isMentioned}const o={entityId:e,feedId:t,userId:ze()._id},i=null===(s=Ie(["subChannelMarker","get",de("subChannelMarker")(o)]))||void 0===s?void 0:s.data;return!!i&&i.hasMentioned}const xn=["broadcast","conversation","community"],Dn=({channelType:e})=>xn.includes(e);function Nn(e){var{channelId:t,channelPublicId:n,channelType:r,childCount:s,creatorId:a,creatorPublicId:o,lastMessageId:i,lastMessageTimestamp:c,messageFeedId:l,name:d}=e,u=zt(e,["channelId","channelPublicId","channelType","childCount","creatorId","creatorPublicId","lastMessageId","lastMessageTimestamp","messageFeedId","name"]);return Object.assign(Object.assign({get unreadCount(){return function(e,t,n){var r,s;if(n)return n.unreadCount;const a=be();if(a.isUnreadCountEnabled&&a.getMarkerSyncConsistentMode()){const e=null===(r=Ie(["subChannelUnreadInfo","get",t]))||void 0===r?void 0:r.data;return e?e.isDeleted?0:e.unreadCount:0}const o={entityId:e,feedId:t,userId:ze()._id},i=null===(s=Ie(["subChannelMarker","get",de("subChannelMarker")(o)]))||void 0===s?void 0:s.data;return i?i.unreadCount:0}(t,l)},get hasMentioned(){return Un(t,l)},get isMentioned(){return Un(t,l)}},u),{channelId:n,creatorId:o,displayName:d,lastActivity:c,latestMessageId:i,messageCount:s,subChannelId:l,isUnreadCountSupport:Dn({channelType:r})})}function Bn(e,t,n){var r;const s=(e=>{var t,n,r;const s=null===(n=null===(t=Ce(["message","get"]))||void 0===t?void 0:t.find((({data:t})=>t.messageId===e.messageId)))||void 0===n?void 0:n.data;return s?Object.assign(Object.assign(Object.assign({},s),e),{referenceId:null!==(r=s.referenceId)&&void 0!==r?r:e.referenceId}):e})(e),{channelPublicId:a,childCount:o,creatorPublicId:i,mentionedUsers:c,messageFeedId:l,myReactions:d,reactionCount:u,reactions:h,referenceId:p,segment:f,messageId:m,creatorId:g}=s,y=zt(s,["channelPublicId","childCount","creatorPublicId","mentionedUsers","messageFeedId","myReactions","reactionCount","reactions","referenceId","segment","messageId","creatorId"]);let v;p&&(v=Ie(["message","get",p])),v||(v=Ie(["message","get",m]));const b=Object.assign(Object.assign({},y),{messageId:m,channelId:a,channelSegment:f,childrenNumber:o,creatorId:i,creatorPrivateId:e.creatorId,reactions:null!=h?h:{},myReactions:d||(null!==(r=null==v?void 0:v.data.myReactions)&&void 0!==r?r:[]),reactionsCount:u,subChannelId:l,uniqueId:v?v.data.uniqueId:m,referenceId:p,syncState:"synced"});return c&&(b.mentionees=c.map((e=>"channel"===e.type?e:{type:"user",userIds:e.userPublicIds}))),t&&t.length&&n&&((e,t,n)=>{const r=be(),s=Ie(["message","get",e.messageId]),a=(null==s?void 0:s.data.myReactions)||[];Object.assign(e,{myReactions:a});const o=t[0];o&&o.userId===r.userId&&("message.reactionAdded"!==n||a.includes(o.reactionName)||Object.assign(e,{myReactions:[...a,o.reactionName]}),"message.reactionRemoved"===n&&a.includes(o.reactionName)&&Object.assign(e,{myReactions:a.filter((e=>e!==o.reactionName))}))})(b,t,n),b}const qn={},Fn=async(e,t)=>{const n=e.messages.map((({messageId:e})=>e));if(n.length>0){Kt({messages:(r=e).messages.map((e=>Bn(e,r.reactions)))});const t=n.join("");qn[t]&&clearTimeout(qn[t]),qn[t]=setTimeout((()=>{try{(async e=>{const t=be();t.log("channel/getMessageMarkers",e);const{data:n}=await t.http.get("/api/v1/markers/messages",{params:{messageIds:e}}),{contentMarkers:r,feedMarkers:s,userMarkers:a}=n,o=t.cache&&Date.now();t.cache&&Kt({contentMarkers:r,feedMarkers:s,userMarkers:a},{cachedAt:o}),Ze("local.feedMarker.fetched",{feedMarkers:s}),Ze("local.messageMarker.fetched",{contentMarkers:r}),Ze("local.userMarker.fetched",{userMarkers:a})})(n)}catch(e){}}),2e3)}var r;const{messageFeeds:s}=e,a=zt(e,["messageFeeds"]);return s&&s.length>0&&(null==s||s.forEach((e=>{var t,n;const r=null!==(n=null===(t=Ie(["subChannel","get",e.messageFeedId]))||void 0===t?void 0:t.data)&&void 0!==n?n:{},s=zt(Nn(e),["unreadCount","isMentioned"]);En(e.messageFeedId,r,s)}))),Object.assign(Object.assign({},a),{messages:e.messages.map((n=>Bn(n,e.reactions,t)))})};function Ln(e){var{subChannelId:t,mentionees:n,dataType:r,data:s}=e,a=zt(e,["subChannelId","mentionees","dataType","data"]);return r===P.IMAGE||r===P.FILE?Object.assign({messageFeedId:t,mentionedUsers:n,dataType:r,data:Object.assign({caption:""},s)},a):Object.assign({messageFeedId:t,mentionedUsers:n,dataType:r,data:s},a)}function Kn(e){var{sortBy:t,subChannelId:n,includingTags:r,excludingTags:s,includeDeleted:a,aroundMessageId:o,limit:i,type:c}=e,l=zt(e,["sortBy","subChannelId","includingTags","excludingTags","includeDeleted","aroundMessageId","limit","type"]);const d=Object.assign(Object.assign({},l),{messageFeedId:n,isDeleted:jn(a),options:{sortBy:t,limit:i||x,around:o}});return r&&(d.includeTags=r),c&&(d.dataType=c),s&&(d.excludeTags=s),d}const $n=["broadcast","conversation","community"],zn=({channelType:e})=>$n.includes(e),Qn=async e=>{const t=e.messageFeeds.filter(zn).map((({messageFeedId:e})=>e));if(t.length>0){(e=>{Kt({messageFeeds:e.messageFeeds.map((e=>Nn(e)))})})(e);try{await(async(e,t={limit:100})=>{const n=be();n.log("channel/getSubChannelMarkers",e,t);const{data:r}=await n.http.get("/api/v1/markers/message-feeds",{params:{messageFeedIds:e,options:{token:Z(t,"skiplimit")}}}),{paging:s}=r,a=zt(r,["paging"]),{userEntityMarkers:o,userFeedMarkers:i,userMarkers:c,feedMarkers:l}=a;n.isUnreadCountEnabled&&n.getMarkerSyncConsistentMode()&&Rn({feedMarkers:l,userFeedMarkers:i});const d=Wt(o),u=Jt(i),h=n.cache&&Date.now();n.cache&&Kt({userEntityMarkers:d,userFeedMarkers:u,userMarkers:c},{cachedAt:h}),Ze("local.channelMarker.fetched",{userEntityMarkers:d}),Ze("local.subChannelMarker.fetched",{userFeedMarkers:u}),Ze("local.userMarker.fetched",{userMarkers:c});const p=X(s.next);return{data:u,cachedAt:h,prevPage:X(s.previous),nextPage:p}})(t)}catch(e){}}An(e);const n=e.messageFeeds.map(Nn),r=e.messages.map((e=>Bn(e)));return Object.assign(Object.assign({},e),{messageFeeds:n,messages:r})};const Vn=async e=>{const t=be();t.log("channel/getSubChannel",e),Mn("subChannel",e);try{const n=await t.http.get(`/api/v5/message-feeds/${encodeURIComponent(e)}`),r=await Qn(n.data),s=t.cache&&Date.now();return t.cache&&Kt(r,{cachedAt:s}),Ze("local.message-feed.fetched",r),{data:r.messageFeeds[0],cachedAt:s}}catch(t){throw H(null==t?void 0:t.code)&&$t("subChannel",e),t}};Vn.locally=e=>{const t=be();if(t.log("channel/getSubChannel.locally",e),!t.cache)return;const n=Ie(["subChannel","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const Hn=e=>new Date(e).getTime(),Wn=async e=>{var t;let n=null===(t=Ie(["subChannel","get",e]))||void 0===t?void 0:t.data;return n||(n=(await Vn(e)).data),n},Jn=async e=>{const t=await(async()=>be().getMessagePreviewSetting(!1))(),{channelId:n,messageId:r,creatorId:s,createdAt:a,updatedAt:o,data:i,dataType:c,subChannelId:l,channelSegment:d,isDeleted:u}=e,h=await Wn(l);"no-message-preview"!==t?(e=>{var t;const n=null===(t=Ie(["messagePreviewSubChannel","get",e.subChannelId]))||void 0===t?void 0:t.data;return!n||n.segment<=e.channelSegment||Hn(n.createdAt)<=Hn(e.createdAt)})(e)&&(Se(["messagePreviewSubChannel","get",e.subChannelId],{channelId:n,creatorId:s,messagePreviewId:r,createdAt:a,updatedAt:o,subChannelId:l,data:i,dataType:c,segment:d,isDeleted:u,subChannelUpdatedAt:null==h?void 0:h.updatedAt,subChannelName:null==h?void 0:h.displayName}),En(e.subChannelId,h,{lastActivity:a,messagePreviewId:r})):Hn(h.lastActivity)<Hn(a)&&En(e.subChannelId,h,{lastActivity:a})},Gn=async e=>{var t;const{channelId:n,messageId:r,creatorId:s,createdAt:a,updatedAt:o,data:i,dataType:c,subChannelId:l,channelSegment:d,isDeleted:u}=e,h=null===(t=Ie(["messagePreviewSubChannel","get",e.subChannelId]))||void 0===t?void 0:t.data;if(h&&h.messagePreviewId===e.messageId){const t=await Wn(l);Se(["messagePreviewSubChannel","get",e.subChannelId],{channelId:n,creatorId:s,messagePreviewId:r,createdAt:a,updatedAt:o,subChannelId:l,data:i,dataType:c,segment:d,isDeleted:u,subChannelUpdatedAt:t.updatedAt,subChannelName:h.subChannelName})}},Yn=async e=>{const{channelId:t,messageId:n,creatorId:r,createdAt:s,updatedAt:a,data:o,dataType:i,subChannelId:c,channelSegment:l,isDeleted:d}=e;if((e=>{var t;const n=null===(t=Ie(["messagePreviewChannel","get",e.channelId]))||void 0===t?void 0:t.data;return!n||Hn(n.createdAt)<=Hn(e.createdAt)})(e)){const u=await Wn(c);Se(["messagePreviewChannel","get",e.channelId],{channelId:t,creatorId:r,messagePreviewId:n,createdAt:s,updatedAt:a,subChannelId:c,data:o,dataType:i,segment:l,isDeleted:d,subChannelUpdatedAt:null==u?void 0:u.updatedAt,subChannelName:null==u?void 0:u.displayName})}},Zn=async e=>{var t;const{channelId:n,messageId:r,creatorId:s,createdAt:a,updatedAt:o,data:i,dataType:c,subChannelId:l,channelSegment:d,isDeleted:u}=e,h=null===(t=Ie(["messagePreviewChannel","get",e.channelId]))||void 0===t?void 0:t.data;if(h&&h.messagePreviewId===e.messageId){const t=await Wn(l);Se(["messagePreviewChannel","get",e.channelId],{channelId:n,creatorId:s,messagePreviewId:r,createdAt:a,updatedAt:o,subChannelId:l,data:i,dataType:c,segment:d,isDeleted:u,subChannelUpdatedAt:t.updatedAt,subChannelName:h.subChannelName})}},Xn=async e=>{var t,n,r,s;const{channelId:a,subChannelId:o}=e,i=null===(t=Ie(["messagePreviewChannel","get",a]))||void 0===t?void 0:t.data;if((null==i?void 0:i.subChannelId)===o){const e=null===(n=Ie(["subChannel","get",o]))||void 0===n?void 0:n.data;Se(["messagePreviewChannel","get",a],Object.assign(Object.assign({},i),{subChannelName:null==e?void 0:e.displayName,subChannelUpdatedAt:null==e?void 0:e.updatedAt}))}const c=null===(r=Ie(["messagePreviewSubChannel","get",o]))||void 0===r?void 0:r.data;if(c&&new Date(c.updatedAt).valueOf()>new Date(e.updatedAt).valueOf()){const e=null===(s=Ie(["subChannel","get",o]))||void 0===s?void 0:s.data;Se(["messagePreviewSubChannel","get",o],Object.assign(Object.assign({},c),{subChannelName:null==e?void 0:e.displayName,subChannelUpdatedAt:null==e?void 0:e.updatedAt}))}};function er(e){return Object.assign(Object.assign({},e),{isGlobalBanned:(null==e?void 0:e.isGlobalBan)||!1})}const tr=["broadcast","conversation","community"],nr=({type:e})=>tr.includes(e);function rr(e,t={isMessagePreviewUpdated:!0}){var n;let{messagePreviewId:r}=e;const s=null===(n=Ie(["messagePreviewChannel","get",e.channelId]))||void 0===n?void 0:n.data;return(null==s?void 0:s.messagePreviewId)&&!t.isMessagePreviewUpdated&&(r=s.messagePreviewId),Object.assign(Object.assign({},e),{defaultSubChannelId:e.channelInternalId,isUnreadCountSupport:nr(e),messagePreviewId:r})}const sr=(e,t={isMessagePreviewUpdated:!0})=>{Kt({channels:e.channels.map((e=>rr(e,{isMessagePreviewUpdated:t.isMessagePreviewUpdated})))})},ar=async(e,t={isMessagePreviewUpdated:!0})=>{const n=be(),r=await n.getMessagePreviewSetting(!1);if(t.isMessagePreviewUpdated&&"no-message-preview"!==r&&e.messagePreviews&&e.messagePreviews.length>0&&kn(e),n.useLegacyUnreadCount)(({currentUserId:e,channels:t,channelUsers:n})=>{const r=[];for(let s=0;s<t.length;s+=1){const a=["channelUnread","get",t[s].channelId],o=n.find((n=>n.channelId===t[s].channelId&&n.userId===e));let i=0,c=null,l=null,d=!1;o&&(c=o.readToSegment,l=o.lastMentionedSegment,i=Math.max(t[s].messageCount-c,0),d=l>c);const u={channelId:t[s].channelId,lastSegment:t[s].messageCount,readToSegment:c,lastMentionedSegment:l,unreadCount:i,isMentioned:d,isDeleted:t[s].isDeleted||!1};Se(a,u),r.push(u)}Ze("local.channelUnread.updated",r)})({channels:e.channels,channelUsers:e.channelUsers,currentUserId:n.userId});else{const n=e.channels.filter(nr).map((({channelInternalId:e})=>e));if(n.length>0){sr(e,{isMessagePreviewUpdated:t.isMessagePreviewUpdated});try{await(async e=>{const t=be();t.log("channel/getChannelMarkers",e);const{data:n}=await t.http.get("/api/v1/markers/channels",{params:{channelIds:e}}),{userEntityMarkers:r,userMarkers:s}=n,a=Wt(r),o=t.cache&&Date.now();return t.cache&&Kt({userEntityMarkers:a,userMarkers:s},{cachedAt:o}),Ze("local.channelMarker.fetched",{userEntityMarkers:a}),Ze("local.userMarker.fetched",{userMarkers:s}),{data:a,cachedAt:o}})(n)}catch(e){}}}const s=e.channels.map((e=>rr(e,{isMessagePreviewUpdated:t.isMessagePreviewUpdated}))),a=e.channelUsers.map((e=>{return t=e,Object.assign(Object.assign({},t),{get user(){var e;if(be().cache)return(null===(e=Ie(["user","get",t.userId]))||void 0===e?void 0:e.data)||void 0}});var t})),o=e.users.map(er),i=zt(e,["messageFeedsInfo","messagePreviews"]);return Object.assign(Object.assign({},i),{users:o,channels:s,channelUsers:a})},or=async e=>{const t=be();t.log("channel/getUserMessageFeedMakers",e);const{data:n}=await t.http.get("/api/v1/markers/user-message-feed",{params:{channelIds:e}});return Ze("local.userMessageFeedMarker.fetched",{userMessageFeedMarker:n}),n},ir=async e=>{const t=be(),n=await or(e.channels.map((({channelInternalId:e})=>e))),{feedMarkers:r,userFeedMarkers:s}=n;Rn({feedMarkers:r,userFeedMarkers:s}),t.log("channel/prepareUnreadCountInfo",e.channels)},cr=(e,t)=>{var n,r,s,a;const o=be();return o.isUnreadCountEnabled&&o.getMarkerSyncConsistentMode()?null!==(r=null===(n=(e=>{var t;return null===(t=Ie(["channelUnreadInfo","get",e]))||void 0===t?void 0:t.data})(e.channelPublicId))||void 0===n?void 0:n.isMentioned)&&void 0!==r&&r:void 0!==(null==t?void 0:t.hasMentioned)?null==t?void 0:t.hasMentioned:null!==(a=null===(s=(e=>{var t;const n={entityId:e,userId:ze()._id};return null===(t=Ie(["channelMarker","get",de("channelMarker")(n)]))||void 0===t?void 0:t.data})(e.channelPublicId))||void 0===s?void 0:s.hasMentioned)&&void 0!==a&&a},lr=(e,t)=>{var n,r,s,a,o;const i=be();return i.isUnreadCountEnabled&&i.getMarkerSyncConsistentMode()?null!==(r=null===(n=(e=>{var t;return null===(t=Ie(["channelUnreadInfo","get",e]))||void 0===t?void 0:t.data})(e.channelInternalId))||void 0===n?void 0:n.unreadCount)&&void 0!==r?r:0:(null==t?void 0:t.isDeleted)?0:null!==(o=null!==(s=null==t?void 0:t.unreadCount)&&void 0!==s?s:null===(a=(e=>{var t;const n={entityId:e,userId:ze()._id};return null===(t=Ie(["channelMarker","get",de("channelMarker")(n)]))||void 0===t?void 0:t.data})(e.channelInternalId))||void 0===a?void 0:a.unreadCount)&&void 0!==o?o:0},dr=e=>{var t;return null===(t=Ie(["channelUnread","get",e]))||void 0===t?void 0:t.data},ur=e=>{const t=be(),n=zt(e,["messageCount"]);return Sn(n,{get unreadCount(){var e,t;return null!==(t=null===(e=dr(n.channelId))||void 0===e?void 0:e.unreadCount)&&void 0!==t?t:0},get subChannelsUnreadCount(){return lr(n)},get isMentioned(){var e,r;return t.useLegacyUnreadCount?null!==(r=null===(e=dr(n.channelId))||void 0===e?void 0:e.isMentioned)&&void 0!==r&&r:cr(n)}})},hr=e=>_n.channel(ur((e=>{var t;const n=e.messagePreviewId?Gt(e.channelId):null,r=null===(t=Ie(["user","get",null==n?void 0:n.creatorId]))||void 0===t?void 0:t.data,s=n?Object.assign(Object.assign({},n),{user:r?_n.user(r):void 0}):null;return Object.assign(Object.assign({},e),{messagePreview:s})})(e))),pr=async e=>{const t=be();t.log("channel/getChannelByIds",e);const n=e.map((e=>encodeURIComponent(e)));let r;try{r=(await t.http.get("/api/v3/channels/list",{params:{channelIds:n}})).data}catch(t){throw e.forEach((e=>{H(null==t?void 0:t.code)&&$t("channel",e)})),t}const s=await ar(r);t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&await ir(r);const a=t.cache&&Date.now();return t.cache&&Kt(s,{cachedAt:a}),Ze("local.channel.fetched",s.channels),{data:s.channels.map((e=>hr(e))),cachedAt:a}};pr.locally=e=>{var t,n;const r=be();if(r.log("channel/getChannelByIds.locally",e),!r.cache)return;const s=null===(t=Ce(["channel","get"]))||void 0===t?void 0:t.filter((({data:t})=>e.includes(t.channelPublicId)));if(!s||(null==s?void 0:s.length)<e.length)return;const a=s.map((({data:e})=>e)),o=null===(n=s.sort(((e,t)=>e.cachedAt<t.cachedAt?-1:1)))||void 0===n?void 0:n[0];return{data:a.map((e=>hr(e))),cachedAt:o.cachedAt}};class fr{constructor(){this._sessionState="notLoggedIn",this._listener=new Map}onSessionStateChange(e){return this._listener.set(e,e),()=>{this._listener.delete(e)}}setSessionState(e){this._sessionState!==e&&(this._sessionState=e,this._listener.forEach((t=>t(e))))}destroy(){this._listener.clear()}}let mr;var gr=()=>(mr||(mr=new fr),mr);const yr=e=>gr().onSessionStateChange(e),vr=(e,t)=>{const n=setInterval(e,t);return()=>clearInterval(n)};let br=!1;const wr={},Cr=async()=>{const e=Object.entries(wr).filter((([,e])=>e)).map((([e])=>e));return 0!==e.length&&(async e=>{const t=be();t.log("subChannel/readingAPI",e);const{data:n}=await t.http.post("/api/v1/markers/message-feeds/reading",{messageFeedIds:e}),{userEntityMarkers:r,userFeedMarkers:s,feedMarkers:a,userMarkers:o}=n,i=Wt(r),c=Jt(s),l=t.cache&&Date.now();return t.cache&&Kt({userEntityMarkers:i,userFeedMarkers:c,feedMarkers:a,userMarkers:o},{cachedAt:l}),Ze("local.feedMarker.fetched",{feedMarkers:a}),Ze("local.channelMarker.fetched",{userEntityMarkers:i}),Ze("local.subChannelMarker.fetched",{userFeedMarkers:c}),Ze("local.userMarker.fetched",{userMarkers:o}),!0})(e)},Ir=()=>{br=!1},Sr=()=>(br=!0,yr((e=>{"notLoggedIn"===e&&Ir()})),()=>{Ir()});vr((async()=>{br&&await Cr()}),3e4);const _r=async e=>{const t=be();t.log("channel/getSubChannels",e);const n=await t.http.get("/api/v5/message-feeds/list",{params:{messageFeedIds:e.map(encodeURIComponent)}}),r=await Qn(n.data),s=t.cache&&Date.now();return t.cache&&Kt(r,{cachedAt:s}),Ze("local.message-feed.fetched",r),{data:r.messageFeeds,cachedAt:s}};_r.locally=e=>{var t;const n=be();if(n.log("channel/getSubChannels.locally",e),!n.cache)return;const r=e.map((e=>Ie(["subChannel","get",e]))).filter(Boolean);if((null==r?void 0:r.length)<e.length)return;return{data:r.map((({data:e})=>e)),cachedAt:(null===(t=r.sort(((e,t)=>e.cachedAt<t.cachedAt?-1:1)))||void 0===t?void 0:t[0]).cachedAt}};const kr=async(e=!0)=>{var t;const n=null===(t=Ie(["MessagePreviewSetting"]))||void 0===t?void 0:t.data;if(!e&&n)return n;const r=await(async()=>{const e=be(),{data:t}=await e.http.get("/api/v3/network-settings/chat");return t})();var s;return(s=r).messagePreview.enabled?s.messagePreview.isIncludeDeleted?"message-preview-include-deleted":"message-preview-not-include-deleted":"no-message-preview"},Tr=async()=>{const e=be(),{data:t}=await e.http.get("/api/v3/network-settings/social");return t.socialNetworkSetting},Or=(e,t)=>{var n;const r=null===(n=Ie(["user","get",e]))||void 0===n?void 0:n.data;return!!r&&r.permissions.some((e=>e===t))},Ar=e=>{const{userId:t}=be();return{currentUser:()=>Or(t,e),community:n=>((e,t,n)=>{var r;if(!e)return!1;const s=null===(r=Ie(["communityUsers","get",`${n}#${e}`]))||void 0===r?void 0:r.data;return!!s&&(!!s.permissions.some((e=>e===t))||Or(e,t))})(t,e,n),channel:n=>((e,t,n)=>{var r;if(!e)return!1;const s=null===(r=Ie(["channelUsers","get",`${n}#${e}`]))||void 0===r?void 0:r.data;return!!s&&(!!s.permissions.some((e=>e===t))||Or(e,t))})(t,e,n)}},Er=async e=>{const t=be();if(t.log("channel/markerSync"),0===e.length)return!1;const{data:n}=await t.http.post("/api/v3/allowlists/verify",{data:e});return n.success},Mr=async e=>{const t=be();if(t.log("channel/markerSync"),0===e.length)return!1;const{data:n}=await t.http.post("/api/v3/blocklists/verify",{data:e});return n.success},Rr=async()=>{const e=be(),{data:t}=await e.http.get("/api/v3/network-settings/feed-setting");return Object.fromEntries(t.feedSettings.map((({feedType:e,contentSettings:t})=>[e,t])))},Pr={notLoggedIn:["establishing"],terminated:["establishing"],establishing:["notLoggedIn","established"],established:["notLoggedIn","terminated","tokenExpired","establishing"],tokenExpired:["establishing"]},jr=e=>{const t=be();t.log("client/api/setSessionState",e);const{sessionState:n}=t;if(n===e)return!1;if(!((e,t)=>Pr[e].includes(t))(n,e))throw new pe(`Session state cannot change from ${n} to ${e}`,8e5,"error");return t.sessionState=e,gr().setSessionState(e),!0},Ur=async e=>{const t=be();jr("establishing");const{accessToken:n,users:r,expiresAt:s,issuedAt:a}=await(async({params:e,options:t})=>{const n=be();n.log("client/api/getToken",e);const r=Bt(),{data:s}=await n.http.post("/api/v5/sessions",Object.assign(Object.assign({},e),{deviceInfo:r}),{headers:{"X-API-Key":n.apiKey,"set-access-token-cookie":(null==t?void 0:t.setAccessTokenCookie)||!1}});return s})(e);return t.http.defaults.headers.common.Authorization=`Bearer ${n}`,t.http.defaults.metadata={tokenExpiry:s,isGlobalBanned:!1,isUserDeleted:!1},t.upload.defaults.headers.common.Authorization=`Bearer ${n}`,t.upload.defaults.metadata={tokenExpiry:s,isGlobalBanned:!1,isUserDeleted:!1},t.ws&&(t.ws.io.opts.query={token:n}),t.token={accessToken:n,issuedAt:a,expiresAt:s},jr("established"),{accessToken:n,users:r}},xr=e=>{const t=Ce(["subChannelUnreadInfo","get"]);if(t){(null==t?void 0:t.filter((({data:t})=>t.channelId===e))).forEach((({key:e,data:t})=>{Se(e,Object.assign(Object.assign({},t),{isDeleted:!0}))}))}},Dr=e=>{var t;const n=["channelUnreadInfo","get",e];(null===(t=Ie(n))||void 0===t?void 0:t.data)&&Te(n)},Nr=[];let Br=null;const qr=e=>{if(0===Nr.length){const e=be(),t=async t=>{const n=await ar(t),r=e.getMarkerSyncConsistentMode()&&e.isUnreadCountEnabled,s=e.useLegacyUnreadCount;n.channels.forEach((e=>{if(r)xr(e.channelId),Dr(e.channelId);else if(s){const t=["channelUnread","get",e.channelId],n=Ie(t);n&&Se(t,Object.assign(Object.assign({},n),{isDeleted:!0}))}})),Kt(n),Nr.forEach((e=>e(n.channels[0])))};Br=Ye(e,"onChannelDeleted","channel.deleted",t)}return Nr.push(e),()=>(e=>{const t=Nr.indexOf(e);t>-1&&Nr.splice(t,1),0===Nr.length&&(null==Br||Br())})(e)},Fr=[];let Lr=null;const Kr=e=>{const t=be();return Lr=Ye(t,"onChannelMemberBanned","channel.banned",(async e=>{const n=await ar(e),{channels:r,channelUsers:s}=n,a=s.some((e=>"banned"===e.membership&&e.userId===t.userId));t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&a&&n.channels.forEach((e=>{xr(e.channelId),Dr(e.channelId)})),Kt(n),Fr.forEach((e=>e(r[0],s.find((e=>"banned"===e.membership)))))})),Fr.push(e),()=>(e=>{const t=Fr.indexOf(e);t>-1&&Fr.splice(t,1),0===Fr.length&&(null==Lr||Lr())})(e)};function $r(e){return{users:e.users.map(er),files:e.files}}const zr=(e,t)=>{const n=be();return Ye(n,e,e,(e=>{const r=$r(e);n.cache&&Kt(r),t(r.users[0])}))},Qr=e=>zr("user.deleted",e);const Vr=async e=>{const t=be();t.log("channel/getChannelByIds",e);const n=e.map((e=>encodeURIComponent(e)));let r;try{r=(await t.http.get("/api/v3/channels/list",{params:{channelIds:n}})).data}catch(t){throw e.forEach((e=>{H(null==t?void 0:t.code)&&$t("channel",e)})),t}const s=await ar(r);t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&await ir(r);const a=t.cache&&Date.now();return t.cache&&Kt(s,{cachedAt:a}),Ze("local.channel.fetched",s.channels),{data:s.channels,cachedAt:a}};Vr.locally=e=>{var t,n;const r=be();if(r.log("channel/getChannelByIds.locally",e),!r.cache)return;const s=null===(t=Ce(["channel","get"]))||void 0===t?void 0:t.filter((({data:t})=>e.includes(t.channelPublicId)));if(!s||(null==s?void 0:s.length)<e.length)return;return{data:s.map((({data:e})=>e)),cachedAt:(null===(n=s.sort(((e,t)=>e.cachedAt<t.cachedAt?-1:1)))||void 0===n?void 0:n[0]).cachedAt}};class Hr{constructor(){this.TIMER_INTERVAL_MS=F,this.BUFFER_ID_LIMIT=100,this.buffer={channel:[],userMessageFeedMarker:[]},this.isResolvingTask=!1,this.connectionListener=[],this.isConnected=!0,this.addConnectionListener()}startResolver(){this.timer||(this.timer=setInterval((()=>{this.isConnected&&this.resolveObjects()}),this.TIMER_INTERVAL_MS))}stopResolver(){this.timer&&(clearInterval(this.timer),this.timer=void 0)}resolve(e,t){const n=this.getBuffer(t);n.includes(e)||(n.length>=this.BUFFER_ID_LIMIT&&n.shift(),n.push(e))}addConnectionListener(){this.connectionListener.length>0||(this.connectionListener.push((e=>{if("undefined"!=typeof window&&window.addEventListener)return window.addEventListener("online",e),()=>window.removeEventListener("online",e);if("undefined"!=typeof document&&document.addEventListener)return document.addEventListener("online",e),()=>document.removeEventListener("online",e);if("undefined"!=typeof navigator&&"ReactNative"===navigator.product){let t=()=>{};return import("@react-native-community/netinfo").then((n=>{t=n.addEventListener((t=>{t.isConnected&&e()}))})),()=>{t()}}return console.error("Unsupported environment"),()=>console.error("Unsupported environment")})((()=>{this.isConnected=!0}))),this.connectionListener.push((e=>{if("undefined"!=typeof window&&window.addEventListener)return window.addEventListener("offline",e),()=>window.removeEventListener("offline",e);if("undefined"!=typeof document&&document.addEventListener)return document.addEventListener("offline",e),()=>document.removeEventListener("offline",e);if("undefined"!=typeof navigator&&"ReactNative"===navigator.product){let t=()=>{};return import("@react-native-community/netinfo").then((n=>{t=n.addEventListener((t=>{t.isConnected||e()}))})),()=>{t()}}return console.error("Unsupported environment"),()=>console.error("Unsupported environment")})((()=>{this.isConnected=!1}))))}removeConnectionListener(){this.connectionListener.length>0&&this.connectionListener.forEach((e=>e()))}resolveObjects(){if(this.isResolvingTask)return;this.isResolvingTask=!0;const e=this.getBuffer("channel"),t=this.getBuffer("userMessageFeedMarker");this.clearBuffer(),e.length>0&&(async e=>{var t,n,r;await Vr(e);const s=null!==(r=null===(n=null===(t=Ce(["channel","get"]))||void 0===t?void 0:t.filter((({data:t})=>t.channelPublicId&&e.includes(t.channelPublicId))))||void 0===n?void 0:n.map((({data:e})=>e)))&&void 0!==r?r:[];Ze("local.channel.resolved",s)})(e),t.length>0&&(async e=>{const t=await or(e),{feedMarkers:n,userFeedMarkers:r}=t;Rn({feedMarkers:n,userFeedMarkers:r}),Ze("local.userMessageFeedMarkers.resolved",{feedMarkers:n,userFeedMarkers:r})})(t),this.isResolvingTask=!1}clearBuffer(){this.buffer={channel:[],userMessageFeedMarker:[]}}getBuffer(e){return this.buffer[e]}onSessionEstablished(){this.startResolver(),this.addConnectionListener()}onSessionDestroyed(){this.stopResolver(),this.clearBuffer(),this.isResolvingTask=!1,this.removeConnectionListener()}onTokenExpired(){this.stopResolver()}}let Wr=null;var Jr=()=>(Wr||(Wr=new Hr),Wr);const Gr=async()=>{var e,t;const n=be();return n.log("client/api/disconnectClient"),n.mqtt&&n.mqtt.connected&&n.mqtt.disconnect(),n.ws&&n.ws.connected&&n.ws.disconnect(),"established"===n.sessionState&&jr("notLoggedIn"),n.emitter.all.clear(),null===(e=n.ws)||void 0===e||e.removeAllListeners(),null===(t=n.mqtt)||void 0===t||t.removeAllListeners(),n.userId=void 0,n.token=void 0,n.http.defaults.headers.common.Authorization="",n.http.defaults.metadata={tokenExpiry:"",isGlobalBanned:!1,isUserDeleted:!1},n.ws&&(n.ws.io.opts.query={token:""}),"undefined"!=typeof document&&(document.cookie="_ascSession=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;"),"tokenExpired"!==n.sessionState&&n.cache&&(n.cache={data:{}}),!0},Yr=e=>{const t=be();jr("terminated"),t.http.defaults.metadata&&("globalBan"===e&&(t.http.defaults.metadata.isGlobalBanned=!0),"userDeleted"===e&&(t.http.defaults.metadata.isUserDeleted=!0)),t.sessionHandler=void 0,Gr()},Zr=["disconnected","error","connect_error","reconnect_error","reconnect_failed"],Xr=e=>{const t=be(),n=Zr.map((n=>Ye(t,`client/onConnectionError(${n})`,n,(t=>{const r=(null==t?void 0:t.code)?new pe(t.message,t.code,"fatal"):new ge(n);e(r)}))));return()=>{n.forEach((e=>e()))}},es=e=>{const t=be();return Ye(t,"client/onConnectionError(user.didGlobalBan)","user.didGlobalBan",e)},ts=e=>{const t=de("channelMarker")({userId:ze()._id,entityId:e.channelId});Te(["channelMarker","get",t],!0)};let ns=[];const rs=async(e,t,n)=>{var r;const s=be();let a;s.log("client/api/connectClient",Object.assign({apiKey:s.apiKey,sessionState:s.sessionState},e)),s.userId&&s.userId!==e.userId&&(await Gr(),ns.forEach((e=>e())),ns=[]);const o=await Nt();try{const{users:n}=await Ur({params:Object.assign(Object.assign({},e),{displayName:null==e?void 0:e.displayName,deviceId:(null==e?void 0:e.deviceId)||o}),options:{setAccessTokenCookie:!0}}),l=n.find((t=>t.userId===e.userId));if(null==l)throw new pe(`${e.userId} has not been founded`,8e5,"error");if(l.isDeleted)return Yr("userDeleted"),!1;if(l.isGlobalBanned)return Yr("globalBan"),!1;i=s.ws,c=s.emitter,Je.forEach((e=>{null==i||i.on(e,(t=>{c.emit(e,t)}))})),null===(r=s.ws)||void 0===r||r.open(),s.userId=l.userId,s.sessionHandler=t,a=s.accessTokenExpiryWatcher(t),Qe(l)}catch(e){throw gr().setSessionState("notLoggedIn"),e}var i,c;return!0!==(null==n?void 0:n.disableRTE)&&async function(){await tt()}(),await(async()=>{var e;const t=await kr();if(t===(null===(e=Ie(["MessagePreviewSetting"]))||void 0===e?void 0:e.data))return;Se(["MessagePreviewSetting"],t);const n=[],r=[];if("no-message-preview"===t){const e=Ce(["MessagePreview"]);e&&(null==e?void 0:e.length)>0&&e.forEach((({key:e,data:t})=>{Te(e),e.includes("MessagePreviewChannel")&&n.push(t.channelId),e.includes("MessagePreviewSubChannel")&&r.push(t.subChannelId)}))}else if("message-preview-not-include-deleted"===t){const e=Ce(["MessagePreview"]);e&&(null==e?void 0:e.length)>0&&e.forEach((({key:e,data:t})=>{(null==t?void 0:t.isDeleted)&&(Te(e),e.includes("MessagePreviewChannel")&&n.push(t.channelId),e.includes("MessagePreviewSubChannel")&&r.push(t.subChannelId))})),0!==n.length&&await pr(n),0!==r.length&&await _r(r)}})(),0===ns.length&&(ns.push(es((e=>{Yr("globalBan"),ns.forEach((e=>e())),a()})),(e=>{const t=be();return Ye(t,"client/onTokenTerminated","tokenTerminated",e)})((e=>{Yr(),ns.forEach((e=>e())),a()})),Qr((e=>{e.userId===s.userId&&(Yr("userDeleted"),ns.forEach((e=>e())),a())})),(e=>{const t=be();return Ye(t,"client/onTokenExpired","tokenExpired",e)})((e=>{gr().setSessionState(e),Gr(),ns.forEach((e=>e()))})),qr(ts),Kr(ts),Sr(),(()=>{const e=sn();return e.established(),yr((t=>{"established"===t?e.established():e.handleTokenExpired()})),()=>{e.destroy()}})(),(()=>{const e=Jr();return e.startResolver(),yr((t=>{"established"===t?e.onSessionEstablished():"tokenExpired"===t?e.onTokenExpired():e.onSessionDestroyed()})),()=>{e.onSessionDestroyed()}})()),s.useLegacyUnreadCount?ns.push((()=>{const e=yn();return e.startSyncReadReceipt(),yr((t=>{"established"===t?e.onSessionEstablished():"tokenExpired"===t?e.onTokenExpired():e.onSessionDestroyed()})),()=>{e.onSessionDestroyed()}})()):ns.push((()=>{const e=Cn();return e.startSyncReadReceipt(),yr((t=>{"established"===t?e.onSessionEstablished():"tokenExpired"===t?e.onTokenExpired():e.onSessionDestroyed()})),()=>{e.onSessionDestroyed()}})())),!0},ss=()=>{let e,t=!1;const n=be();n.log("initiating access token renewal");const r=async r=>{const{userId:s,displayName:a}=ze(),o={userId:s,displayName:a,authToken:r,deviceId:await Nt()};"tokenExpired"===n.sessionState&&n.sessionHandler?await rs(o,n.sessionHandler):await Ur({params:o,options:{setAccessTokenCookie:!0}}),t=!0,e&&clearTimeout(e)};return{renew:()=>{t?console.log("'renew' method can be called only once per renewal instance"):r()},renewWithAuthToken:e=>{t?console.log("'renewWithAuthToken' method can be called only once per renewal instance"):r(e)},unableToRetrieveAuthToken:()=>{e=setTimeout((()=>{var e;null===(e=n.sessionHandler)||void 0===e||e.sessionWillRenewAccessToken(ss())}),L)}}},as=3e5,os=e=>{const t=setInterval((()=>{const t=be();if(!t.token)return;const{issuedAt:n,expiresAt:r}=t.token;if((e=>Date.now()>Date.parse(e)-as)(r))return Ze("tokenExpired","tokenExpired"),void We((()=>e.sessionWillRenewAccessToken(ss())));(e=>{const{expiresAt:t,issuedAt:n}=e,r=Date.parse(t),s=Date.parse(n),a=Date.now();return a>s+.8*(r-s-as)&&a<r})({expiresAt:r,issuedAt:n})&&e.sessionWillRenewAccessToken(ss())}),L);return()=>clearInterval(t)},is=[];let cs=null;const ls=e=>{if(0===is.length){const e=be();cs=Ye(e,"onChannelCreated","channel.created",(async e=>{const t=await ar(e);Kt(t),is.forEach((e=>e(t.channels[0])))}))}return is.push(e),()=>(e=>{const t=is.indexOf(e);t>-1&&is.splice(t,1),0===is.length&&(null==cs||cs())})(e)},ds=[],us=[],hs=e=>{const t=be();if(0===ds.length){const e=async e=>{const t=await ar(e);Kt(t),ds.forEach((e=>e(t.channels[0])))};us.push(Ye(t,"onChannelUpdated","channel.updated",e)),us.push(Ye(t,"onChannelUpdated","local.channel.updated",(e=>ds.forEach((t=>t(e.channels[0]))))))}return ds.push(e),()=>(e=>{const t=ds.indexOf(e);t>-1&&ds.splice(t,1),0===ds.length&&us.forEach((e=>e()))})(e)},ps=[];let fs=null;const ms=e=>{if(0===ps.length){const e=be();fs=Ye(e,"onChannelJoined","channel.joined",(async e=>{const t=await ar(e),{channels:n,channelUsers:r}=t;Kt(t),ps.forEach((e=>e(n[0],r[0])))}))}return ps.push(e),()=>(e=>{const t=ps.indexOf(e);t>-1&&ps.splice(t,1),0===ps.length&&(null==fs||fs())})(e)},gs=[];let ys=null;const vs=e=>{if(0===gs.length){const e=be(),t=async t=>{const{userId:n}=be(),{channelUsers:r}=t,s=r.some((e=>e.userId===n)),a=await ar(t,{isMessagePreviewUpdated:s}),o=e.getMarkerSyncConsistentMode()&&e.isUnreadCountEnabled,i=e.useLegacyUnreadCount;s&&a.channels.forEach((e=>{o?(xr(e.channelId),Dr(e.channelId)):i&&Te(["channelUnread","get",e.channelId])}));const{channels:c,channelUsers:l}=a;Kt(a),gs.forEach((e=>e(c[0],l[0])))};ys=Ye(e,"onChannelLeft","channel.left",t)}return gs.push(e),()=>(e=>{const t=gs.indexOf(e);t>-1&&gs.splice(t,1),0===gs.length&&(null==ys||ys())})(e)},bs=[];let ws=null;const Cs=e=>{if(0===bs.length){const e=be();ws=Ye(e,"onChannelMuted","channel.setMuted",(async e=>{const t=await ar(e);Kt(t),bs.forEach((e=>e(t.channels[0])))}))}return bs.push(e),()=>(e=>{const t=bs.indexOf(e);t>-1&&bs.splice(t,1),0===bs.length&&(null==ws||ws())})(e)},Is=[];let Ss=null;const _s=e=>{if(0===Is.length){const e=be();Ss=Ye(e,"onChannelMemberAdded","channel.membersAdded",(async e=>{const t=await ar(e),{channels:n,channelUsers:r}=t;Kt(t),Is.forEach((e=>e(n[0],r.find((e=>"member"===e.membership)))))}))}return Is.push(e),()=>(e=>{const t=Is.indexOf(e);t>-1&&Is.splice(t,1),0===Is.length&&(null==Ss||Ss())})(e)},ks=[];let Ts=null;const Os=e=>{if(0===ks.length){const e=be();Ts=Ye(e,"onChannelMemberRemoved","channel.membersRemoved",(async e=>{const t=await ar(e),{channels:n,channelUsers:r}=t;Kt(t),ks.forEach((e=>e(n[0],r[0])))}))}return ks.push(e),()=>(e=>{const t=ks.indexOf(e);t>-1&&ks.splice(t,1),0===ks.length&&(null==Ts||Ts())})(e)},As=[];let Es=null;const Ms=e=>{if(0===As.length){const e=be();Es=Ye(e,"onChannelMemberUnbanned","channel.unbanned",(async e=>{const t=await ar(e),{channels:n,channelUsers:r}=t;Kt(t),As.forEach((e=>e(n[0],r.find((e=>"none"===e.membership)))))}))}return As.push(e),()=>(e=>{const t=As.indexOf(e);t>-1&&As.splice(t,1),0===As.length&&(null==Es||Es())})(e)},Rs=[];let Ps=null;const js=e=>{if(0===Rs.length){const e=be();Ps=Ye(e,"onChannelMemberRoleAdded","local.channel-moderator.role-added",(async e=>{const{channels:t,channelUsers:n}=e;Rs.forEach((e=>e(t[0],n.find((e=>"member"===e.membership)))))}))}return Rs.push(e),()=>(e=>{const t=Rs.indexOf(e);t>-1&&Rs.splice(t,1),0===Rs.length&&(null==Ps||Ps())})(e)},Us=[];let xs=null;const Ds=e=>{if(0===Us.length){const t=be();xs=Ye(t,"onChannelMemberRoleRemoved","local.channel-moderator.role-removed",(async t=>{const{channels:n,channelUsers:r}=t;e(n[0],r.find((e=>"member"===e.membership)))}))}return Us.push(e),()=>(e=>{const t=Us.indexOf(e);t>-1&&Us.splice(t,1),0===Us.length&&(null==xs||xs())})(e)},Ns=e=>{const t=be(),n=ze(),r=[Ye(t,"message/onMessageCreated","message.created",(async r=>{const s=await Fn(r);t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&r.messages.forEach((e=>{(e=>{var t;const n=be(),r=["subChannelUnreadInfo","get",e.messageFeedId],s=null===(t=Ie(r))||void 0===t?void 0:t.data;if(!s)return;const a=s.lastSegment<e.segment?e.segment:s.lastSegment,o=a-s.readToSegment;let{lastMentionSegment:i}=s;e.mentionedUsers&&e.mentionedUsers.length>0&&e.mentionedUsers.forEach((t=>{("channel"===t.type||"user"===t.type&&n.userId&&t.userPublicIds.includes(n.userId))&&(i=e.segment)}));const c=Object.assign(Object.assign({},s),{lastMentionSegment:i,lastSegment:a,isMentioned:!(s.readToSegment>=i),unreadCount:Math.max(o,0)});Se(r,c)})(e),vn(e.channelId)})),t.useLegacyUnreadCount&&r.messages.forEach((e=>{var n,r;const s=null===(n=Ie(["channelUnread","get",e.channelId]))||void 0===n?void 0:n.data;if(!s||s.lastSegment>=e.segment||"number"!=typeof s.readToSegment||"number"!=typeof s.lastMentionedSegment)return;const a=e.segment,o=(null===(r=e.mentionedUsers)||void 0===r?void 0:r.some((e=>"channel"===e.type||"user"===e.type&&t.userId&&e.userPublicIds.includes(t.userId))))?e.segment:s.lastMentionedSegment,i=Object.assign(Object.assign({},s),{lastSegment:a,unreadCount:Math.max(a-s.readToSegment,0),lastMentionedSegment:o,isMentioned:!(s.readToSegment>=o)});Se(["channelUnread","get",e.channelId],i),Ze("local.channelUnread.updated",[i])})),Kt(s),s.messages.forEach((t=>{t.creatorPrivateId===n._id&&In(t),e(t)}))}))];return()=>{r.forEach((e=>e()))}},Bs=e=>{const t=be(),n=[Ye(t,"message/onMessageCreated","local.message.created",(async t=>(Kt(t),t.messages.forEach((t=>{e(t)})))))];return()=>{n.forEach((e=>e()))}},qs=e=>{const t=be();return Ye(t,"onSubChannelCreated","message-feed.created",(async n=>{const r=await Qn(n);t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&n.messageFeeds.forEach((e=>{(e=>{const{channelId:t,subChannelId:n,createdAt:r,updatedAt:s}=e,a={channelId:t,subChannelId:n,unreadCount:0,readToSegment:0,lastMentionSegment:0,lastSegment:0,isMentioned:!1,isDeleted:!1,createdAt:r,updatedAt:s};Se(["subChannelUnreadInfo","get",a.subChannelId],a)})({channelId:e.channelId,subChannelId:e.messageFeedId,createdAt:e.createdAt,updatedAt:e.updatedAt})})),Kt(r),e(r.messageFeeds[0])}))},Fs=e=>{const t=be(),n=[Ye(t,"onSubChannelDeleted","message-feed.deleted",(async n=>{const r=await Qn(n);t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&r.messageFeeds.forEach((e=>{(e=>{var t;const n=["subChannelUnreadInfo","get",e],r=null===(t=Ie(n))||void 0===t?void 0:t.data;r&&Se(n,Object.assign(Object.assign({},r),{isDeleted:!0}))})(e.subChannelId),vn(e.channelId)})),Kt(r),e(r.messageFeeds[0])})),Ye(t,"local.message-feed.deleted","local.message-feed.deleted",(t=>e(t.messageFeeds[0])))];return()=>{n.forEach((e=>e()))}},Ls=async e=>{const t=be();t.log("channel/markerSync");const{data:n}=await t.http.post("/api/v1/markers/sync",{deviceLastSyncAt:e}),{userEntityMarkers:r,userFeedMarkers:s,feedMarkers:a,userMarkers:o}=n,i=Wt(r),c=Jt(s),l=t.cache&&Date.now();return t.cache&&Kt({userEntityMarkers:i,userFeedMarkers:c,feedMarkers:a,userMarkers:o},{cachedAt:l}),Ze("local.feedMarker.fetched",{feedMarkers:a}),Ze("local.channelMarker.fetched",{userEntityMarkers:i}),Ze("local.subChannelMarker.fetched",{userFeedMarkers:c}),Ze("local.userMarker.fetched",{userMarkers:o}),{data:n,hasMore:n.feedMarkers.length>0}};let Ks=!1,$s=[],zs=!1;let Qs=null;let Vs=[];const Hs=e=>{Vs=e},Ws=async()=>{var e;if(!zs&&0!==Vs.length)try{zs=!0,Vs=[];const t=await Ls((null==Qs?new Date:Qs).toISOString()),n=t.data.userMarkers.reduce(((e,t)=>null==e||e.getTime()<new Date(t.lastSyncAt).getTime()?new Date(t.lastSyncAt):e),null);null!=(e=n)&&(!Qs||e.getTime()>Qs.getTime())&&(Qs=e),t.hasMore&&Vs.push("has_more")}catch(e){}finally{zs&&(zs=!1)}};vr((async()=>{Ks&&await Ws()}),2e3);const Js=()=>true,Gs=e=>{var t;const n=be();if(n.mqtt)return null===(t=n.mqtt)||void 0===t?void 0:t.listen(e)};var Ys;class Zs{constructor(){Ys.set(this,e.FileAccessTypeEnum.PUBLIC)}setFileAccessType(e){!function(e,t,n,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");"a"===r?s.call(e,n):s?s.value=n:t.set(e,n)}(this,Ys,e,"f")}getFileAccessType(){return function(e,t,n,r){if("a"===n&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?r:"a"===n?r.call(e):r?r.value:t.get(e)}(this,Ys,"f")}}let Xs;Ys=new WeakMap;var ea=()=>(Xs||(Xs=new Zs),Xs);const ta=e=>{const t=be();return Ye(t,"channelMarker/onChannelMarkerFetched","local.channelMarker.fetched",(t=>{t.userEntityMarkers.forEach((t=>{e(t)}))}))},na=e=>{const t=be();return Ye(t,"subChannelMarker/onSubChannelMarkerFetched","local.subChannelMarker.fetched",(t=>{t.userFeedMarkers.forEach(e)}))},ra=e=>{const t=be();return Ye(t,"subChannelMarker/onSubChannelMarkerUpdated","local.subChannelMarker.updated",(t=>{e(t.userFeedMarkers)}))},sa=e=>{const t=be();return Ye(t,"userMarker/onUserMarkerFetched","local.userMarker.fetched",(t=>{e(t.userMarkers)}))},aa=e=>{const t=be();return Ye(t,"messageMarker/onMessageMarkerFetched","local.messageMarker.fetched",(t=>{e(t.contentMarkers[0])}))},oa=e=>{const t=be();return Ye(t,"messageMarker/onMessageMarked","marker.marked-message",(t=>{var n,r,s;Kt(t);const a=Ce(["message","collection"]),{contentMarkers:o,feedMarkers:i}=t;if(a&&(null==a?void 0:a.length)>0&&(null==i?void 0:i.length)>0){const e=a.filter((e=>{var t,n;return(null===(n=null===(t=e.data)||void 0===t?void 0:t.query)||void 0===n?void 0:n.subChannelId)===i[0].feedId}));if(e.length>0&&(null==o?void 0:o.length)>0){(null!==(s=null===(r=null===(n=e[0].data)||void 0===n?void 0:n.data)||void 0===r?void 0:r.map((e=>Ie(["message","get",e]))).map((({data:e})=>e)).filter(Boolean))&&void 0!==s?s:[]).forEach((e=>{var t,n;const r=["messageMarker","get",de("messageMarker")({creatorId:e.creatorPrivateId,feedId:e.subChannelId,contentId:e.messageId})],s=null===(t=Ie(r))||void 0===t?void 0:t.data;if(!s)return;const a=o[0].feedId===s.feedId,i=o[0].readCount>s.readCount,c=(null===(n=o[0])||void 0===n?void 0:n.deliveredCount)>s.deliveredCount;if(a){const e=Object.assign(Object.assign({},s),{readCount:i?o[0].readCount:s.readCount,deliveredCount:c?o[0].deliveredCount:s.deliveredCount});Se(r,e)}}))}}e(t.contentMarkers[0])}))};function ia(e){return"object"==typeof e&&null!==e}const ca=e=>{if(!ia(e))return e;const t=Object.entries(e).map((([t,n])=>{const r=Object.getOwnPropertyDescriptor(e,t);return"function"==typeof(null==r?void 0:r.get)?[t,r.get.call(e)]:[t,n]}));return Object.fromEntries(t)},la=e=>{if(!ia(e))return e;const t=Object.entries(e).map((([e,t])=>"function"==typeof t?[e,void 0]:[e,t]));return Object.fromEntries(t)};var da=Object.freeze({__proto__:null,getActiveClient:be,getActiveUser:ze,setActiveUser:Qe,createClient:(e,t=vt.SG,{debugSession:n="amity",apiEndpoint:r,prefixDeviceIdKey:s,rteEnabled:a=!0}={})=>{var o,i,c;const l=(e=>{const t=`${null==e?void 0:e.trim()}`.length>0&&!yt,n=f.default(e),r=(e,...r)=>{t&&n(e,r)};return r.__instance__=n,r})(n);l("client/api/createClient",{apiKey:e.replace(/.{5}$/g,"xxxxx"),apiRegion:t});const d=null!==(o=null==r?void 0:r.http)&&void 0!==o?o:wt("http",t),u=null!==(i=null==r?void 0:r.upload)&&void 0!==i?i:wt("upload",t),h=null!==(c=null==r?void 0:r.mqtt)&&void 0!==c?c:wt("mqtt",t),m=Ot(d),g=Ot(u);let v,b;a&&(v=(e=>{const t=y.default(e,{autoConnect:!1,reconnectionDelay:2e3,transports:["websocket"]});return t.on("disconnect",(e=>{"io server disconnect"===e&&t.connect()})),t})(d),b=Lt(h));const w=p.default(),C={version:`${U}`,apiKey:e,log:l,cache:{data:{}},http:m,ws:v,mqtt:b,upload:g,emitter:w,sessionState:"notLoggedIn",accessTokenExpiryWatcher:os,sessionHandler:undefined,hasPermission:Ar,validateUrls:Er,validateTexts:Mr,getFeedSettings:Rr,getSocialSettings:Tr,getMessagePreviewSetting:kr,onRTEConnectionStateChange:Gs,use:()=>we(C),isUnreadCountEnabled:!1,useLegacyUnreadCount:!0,getMarkerSyncConsistentMode:Js,prefixDeviceIdKey:s};try{const t=be();if(t.apiKey===e)return t;we(C)}catch(e){we(C)}return C},login:rs,logout:Gr,secureLogout:async()=>{const e=be(),{data:{success:t}}=await e.http.delete("/api/v4/sessions");if(!t)throw new Error("Failed to logout");return await Gr()},isConnected:()=>{var e,t;const n=be();n.log("client/api/isConnected",n);const r=n.ws&&n.ws.connected||!!n.ws;return!!(n.userId&&(null===(t=String(null===(e=n.http.defaults.headers.common)||void 0===e?void 0:e.Authorization))||void 0===t?void 0:t.length)&&r)},getFeedSettings:Rr,renewal:ss,markerSync:Ls,enableUnreadCount:()=>!0,setUploadedFileAccessType:function(e){ea().setFileAccessType(e)},registerPushNotification:async e=>{const t=be();let n;if("ios"!==l.Platform.OS&&"android"!==l.Platform.OS)throw new ye("Unsupported platform");n=l.Platform.OS;const r=await Nt(),{data:{status:s,error:a}}=await t.http.post("/v1/notification",{userId:t.userId,deviceId:r,platform:n,token:e},{headers:{"X-API-Key":t.apiKey}});if(a)throw new fe(a,5e5,"error");return"success"===s},unregisterPushNotification:async()=>{const e=be(),t=Nt(),{data:{status:n,error:r}}=await e.http.delete("/v1/notification",{data:{deviceId:t},headers:{"X-API-Key":e.apiKey}});if(r)throw new fe(r,5e5,"error");return"success"===n},onRTEConnectionStateChange:Gs,fetchLinkPreview:async e=>{const t=be();let n=e;/^https?:\/\//i.test(e)||(n=`https://${e}`);const{data:r}=await t.http.get(`/api/v1/link-preview?url=${encodeURIComponent(n)}`);return r},onConnectionError:Xr,onClientDisconnected:e=>Xr((({code:t})=>{800211===t&&e()})),onClientBanned:es,onSessionStateChange:yr,onNetworkActivities:e=>_t().onNetworkActivities(e),getUserUnread:e=>{const{_id:t}=ze();if(!t)throw new pe("The _id has not been defined in ActiveUser",8e5,"error");const{log:n,cache:r}=be();r||console.log("For using Live Object feature you need to enable Cache!");n(`liveUserUnread(tmpid: ${Date.now()}) > listen`);const s=[];let a,o=!1;const i=t=>{const{data:n}=t,r=n?{unreadCount:n.unreadCount,isMentioned:n.isMentioned}:void 0;a=r?ca(r):r,e({data:r?Object.assign(Object.assign({},r),{isMentioned:r.isMentioned}):r,loading:t.loading,error:t.error})};return s.push(sa((e=>(e=>{var n;const r=e.filter((e=>t===e.userId)),s=r.reduce(((e,t)=>null==e||new Date(t.lastSyncAt).getTime()>new Date(e.lastSyncAt).getTime()?t:e),null),o={unreadCount:null!==(n=null==s?void 0:s.unreadCount)&&void 0!==n?n:0,isMentioned:r.some((e=>!!e.isMentioned))};ln(a,o)||i({loading:!1,data:o})})(e)))),(()=>{const e=ae(Pn);ie(e,(({error:e,data:t,loading:n,origin:r,cachedAt:a})=>{!function(e){return null!=e&&null!=e}(t)?i({loading:n,data:void 0,origin:r,error:e}):(a===q?(i({data:t,origin:r,loading:!1,error:new fe(B,800800,"error")}),o=!0,s.forEach((e=>e()))):o||i({loading:n,data:t,origin:r,error:e}),e&&s.forEach((e=>e())))}))})(),()=>{s.forEach((e=>e()))}},getMarkerSyncEvents:()=>Vs,setMarkerSyncEvents:Hs,pushMarkerSyncEvent:e=>Vs.push(e),markerSyncTrigger:Ws,startMarkerSync:async()=>Promise.resolve(),startUnreadSync:async()=>Promise.resolve(),stopUnreadSync:()=>{Ks=!1,Hs([]),$s.forEach((e=>e())),$s=[]},getMarkerSyncConsistentMode:Js});function ua(e){const{users:t,follows:n}=e,r=zt(e,["users","follows"]);return Object.assign(Object.assign({},r),{follows:n,users:t.map(er)})}function ha(e){const{users:t,follows:n}=e,r=zt(e,["users","follows"]);return Object.assign(Object.assign({},r),{follows:n,users:t.map(er)})}function pa(e){const{follows:t}=e,n=zt(e,["follows"]);return Object.assign(Object.assign({},n),{follows:t})}const fa=(e,t)=>{const n=be();return Ye(n,e,e,(e=>{const r=ua(e);n.cache?(Kt(r),t(r.follows[0])):t(r.follows[0])}))},ma=(e,t)=>{const n=be();return Ye(n,e,e,(e=>{const r=pa(e);n.cache?(Kt(r),t(r.follows[0])):t(r.follows[0])}))},ga=e=>fa("follow.created",e),ya=e=>fa("follow.unfollowed",e),va=e=>fa("follow.followerDeleted",e),ba=e=>fa("follow.requested",e),wa=e=>fa("follow.requestCanceled",e),Ca=e=>fa("follow.accepted",e),Ia=e=>fa("follow.requestDeclined",e),Sa=async e=>{var t,n;const r=be();r.log("follow/getFollowInfo",e);const{data:s}=await r.http.get(r.userId===e?"/api/v4/me/followInfo":`/api/v5/users/${e}/followInfo`),a=r.cache&&Date.now(),o="follows"in s?Object.assign(Object.assign({},s.followCounts[0]),{status:null===(n=null===(t=s.follows)||void 0===t?void 0:t[0])||void 0===n?void 0:n.status}):s.followCounts[0];return r.cache&&Se(["followInfo","get",e],o,{cachedAt:a}),{data:o,cachedAt:a}};Sa.locally=e=>{const t=be();if(t.log("follow/getFollowInfo.locally",e),!t.cache)return;const n=Ie(["followInfo","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const _a=e=>{const t=async t=>{const[{data:n},{data:r}]=await Promise.all([Sa(t.from),Sa(t.to)]);e(n),e(r)},n=[fa("follow.created",t),fa("follow.requested",t),fa("follow.accepted",t),fa("follow.unfollowed",t),fa("follow.requestCanceled",t),fa("follow.requestDeclined",t),fa("follow.followerDeleted",t),ma("local.follow.created",t),ma("local.follow.requested",t),ma("local.follow.accepted",t),ma("local.follow.unfollowed",t),ma("local.follow.requestDeclined",t)];return()=>{n.forEach((e=>e()))}},ka=e=>ma("local.follow.created",e),Ta=e=>ma("local.follow.unfollowed",e),Oa=e=>ma("local.follow.requested",e),Aa=e=>ma("local.follow.accepted",e),Ea=e=>ma("local.follow.requestDeclined",e);class Ma{constructor(e){const{http:t}=be();this.queryParams=e,this.http=t}loadFirstPage(){return this.onFetch("first")}loadNextPage(){return this.onFetch("next")}loadPreviousPage(){return this.onFetch("prev")}async onFetch(e="first"){var t,n,r,s;if("prev"===e&&!this.previousToken)return;if("next"===e&&!this.nextToken)return;let a;"prev"===e&&(a=this.previousToken),"next"===e&&(a=this.nextToken);const o=await this.getRequest(this.queryParams,a);return"first"===e&&(this.nextToken=null===(t=o.paging)||void 0===t?void 0:t.next,this.previousToken=null===(n=o.paging)||void 0===n?void 0:n.previous),"prev"===e&&(this.previousToken=null===(r=o.paging)||void 0===r?void 0:r.previous),"next"===e&&(this.nextToken=null===(s=o.paging)||void 0===s?void 0:s.next),o}getNextToken(){return this.nextToken}getPrevToken(){return this.previousToken}}class Ra extends Ma{async getRequest(e,t){const{limit:n=x,userId:r}=e,s=zt(e,["limit","userId"]),a=t?{token:t}:{limit:n},o=be().userId===r?"/api/v4/me/followers":`/api/v4/users/${r}/followers`,{data:i}=await this.http.get(o,{params:Object.assign(Object.assign({},s),{options:a,isDeleted:!1})});return i}}class Pa{constructor(e,t){this.query=e,this.cacheKey=t}}var ja;!function(e){e.OnRequested="onRequested",e.OnAccepted="onAccepted",e.OnDeclined="onDeclined",e.OnCanceled="onCanceled",e.OnFollowed="onFollowed",e.OnUnfollowed="onUnfollowed",e.OnDeleted="onDeleted",e.OnUserDeleted="onUserDeleted"}(ja||(ja={}));class Ua extends Pa{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=be(),r=n.cache&&Date.now();n.cache&&Kt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,s;if(n)Se(this.cacheKey,{data:e.follows.map(de("follow"))});else{const t=null===(r=Ie(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];Se(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.follows.map(de("follow"))])]}))}}reactor(e){return t=>{var n;const r=null===(n=Ie(this.cacheKey))||void 0===n?void 0:n.data;if(this.query.userId===t.to&&r){switch(e){case ja.OnDeclined:case ja.OnCanceled:case ja.OnUnfollowed:case ja.OnDeleted:r.data=r.data.filter((e=>e!==de("follow")(t)));break;case ja.OnRequested:case ja.OnAccepted:case ja.OnFollowed:r.data=[...new Set([de("follow")(t),...r.data])]}Se(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class xa{constructor(e){const{http:t}=be();this.queryParams=e,this.http=t}async onFetch(){return await this.getRequest(this.queryParams)}}class Da{constructor(e,t,n,r){this.paginationController=e,this.queryStreamId=t,this.cacheKey=n,this.callback=r}async refresh(){try{let e;if(e=this.paginationController instanceof xa?await this.paginationController.onFetch():await this.paginationController.loadFirstPage(),!e)return;await this.persistModel(e),this.persistQueryStream({response:e,direction:"next",refresh:!0}),this.notifyChange({origin:"server",loading:!1})}catch(e){this.notifyChange({origin:"server",loading:!1,error:e})}}loadPage({initial:e=!1,direction:t="next"}){this.setup(),this.notifyChange({origin:"local",loading:!0}),e?this.refresh():"prev"===t?this.loadPrevPage():"next"===t&&this.loadNextPage()}async loadNextPage(){try{if(this.paginationController instanceof xa)return;const e=await this.paginationController.loadNextPage();if(!e)return;await this.persistModel(e),this.persistQueryStream({response:e,direction:"next"}),this.notifyChange({origin:"server",loading:!1})}catch(e){this.notifyChange({origin:"server",loading:!1,error:e})}}async loadPrevPage(){try{if(this.paginationController instanceof xa)return;const e=await this.paginationController.loadPreviousPage();if(!e)return;await this.persistModel(e),this.persistQueryStream({response:e,direction:"prev"}),this.notifyChange({origin:"server",loading:!1})}catch(e){this.notifyChange({origin:"server",loading:!1,error:e})}}shouldNotify(e){const t=e.map(ca).map(la);return!ln(this.snapshot,t)&&(this.snapshot=t,!0)}getCacheKey(){return this.cacheKey}}const Na=({userId:e})=>t=>{const n=be();return Ye(n,"user.deleted","user.deleted",(n=>{const r=$r(n);Kt(r);const s=Ie(["follow","get",de("follow")({from:r.users[0].userId,to:e})]);s&&t(null==s?void 0:s.data)}))};class Ba extends Da{constructor(e,t){const n=w.default(Object.assign(Object.assign({},e),{type:"follower"})),r=["follow","collection",n];super(new Ra(e),n,r,t),this.query=e,this.queryStreamController=new Ua(this.query,this.cacheKey,this.notifyChange.bind(this),ua),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Ie(this.cacheKey))||void 0===e?void 0:e.data)||Se(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:ga,action:ja.OnFollowed},{fn:ya,action:ja.OnUnfollowed},{fn:Ca,action:ja.OnAccepted},{fn:Ia,action:ja.OnDeclined},{fn:wa,action:ja.OnCanceled},{fn:va,action:ja.OnDeleted},{fn:Aa,action:ja.OnAccepted},{fn:Ea,action:ja.OnDeclined},{fn:ka,action:ja.OnFollowed},{fn:Ta,action:ja.OnUnfollowed},{fn:Na({userId:this.query.userId}),action:ja.OnUserDeleted}])}notifyChange({origin:e,loading:t,error:n}){var r,s;const a=null===(r=Ie(this.cacheKey))||void 0===r?void 0:r.data;if(!a)return;const o=this.applyFilter(null!==(s=a.data.map((e=>Ie(["follow","get",e]))).filter(dn).map((({data:e})=>e)))&&void 0!==s?s:[]);(this.shouldNotify(o)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:o,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=e;return this.query.status&&"all"!==this.query.status&&(t=t.filter((e=>e.status===this.query.status))),t=t.filter((e=>{var t;const n=null===(t=Ie(["user","get",e.from]))||void 0===t?void 0:t.data;return null==(null==n?void 0:n.isDeleted)||!1===(null==n?void 0:n.isDeleted)})),t}}class qa extends Ma{async getRequest(e,t){const{limit:n=x,userId:r}=e,s=zt(e,["limit","userId"]),a=t?{token:t}:{limit:n},o=be().userId===r?"/api/v4/me/following":`/api/v4/users/${r}/following`,{data:i}=await this.http.get(o,{params:Object.assign(Object.assign({},s),{options:a,isDeleted:!1})});return i}}class Fa extends Pa{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=be(),r=n.cache&&Date.now();n.cache&&Kt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,s;if(n)Se(this.cacheKey,{data:e.follows.map(de("follow"))});else{const t=null===(r=Ie(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];Se(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.follows.map(de("follow"))])]}))}}reactor(e){return t=>{var n;const r=null===(n=Ie(this.cacheKey))||void 0===n?void 0:n.data;if(this.query.userId===t.from&&r){switch(e){case ja.OnDeclined:case ja.OnCanceled:case ja.OnUnfollowed:case ja.OnDeleted:r.data=r.data.filter((e=>e!==de("follow")(t)));break;case ja.OnRequested:case ja.OnAccepted:case ja.OnFollowed:r.data=[...new Set([de("follow")(t),...r.data])]}Se(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const La=({userId:e})=>t=>{const n=be();return Ye(n,"user.deleted","user.deleted",(n=>{const r=$r(n);Kt(r);const s=Ie(["follow","get",de("follow")({from:e,to:r.users[0].userId})]);s&&t(null==s?void 0:s.data)}))};class Ka extends Da{constructor(e,t){const n=w.default(Object.assign(Object.assign({},e),{type:"following"})),r=["follow","collection",n];super(new qa(e),n,r,t),this.query=e,this.queryStreamController=new Fa(this.query,this.cacheKey,this.notifyChange.bind(this),ha),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Ie(this.cacheKey))||void 0===e?void 0:e.data)||Se(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:ba,action:ja.OnRequested},{fn:Ca,action:ja.OnAccepted},{fn:Ia,action:ja.OnDeclined},{fn:wa,action:ja.OnCanceled},{fn:ga,action:ja.OnFollowed},{fn:ya,action:ja.OnUnfollowed},{fn:va,action:ja.OnDeleted},{fn:Oa,action:ja.OnRequested},{fn:Aa,action:ja.OnAccepted},{fn:Ea,action:ja.OnDeclined},{fn:ka,action:ja.OnFollowed},{fn:Ta,action:ja.OnUnfollowed},{fn:La({userId:this.query.userId}),action:ja.OnUserDeleted}])}notifyChange({origin:e,loading:t,error:n}){var r,s;const a=null===(r=Ie(this.cacheKey))||void 0===r?void 0:r.data;if(!a)return;const o=this.applyFilter(null!==(s=a.data.map((e=>Ie(["follow","get",e]))).filter(dn).map((({data:e})=>e)))&&void 0!==s?s:[]);(this.shouldNotify(o)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:o,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=e;return this.query.status&&"all"!==this.query.status&&(t=t.filter((e=>e.status===this.query.status))),t=t.filter((e=>{var t;const n=null===(t=Ie(["user","get",e.to]))||void 0===t?void 0:t.data;return null==(null==n?void 0:n.isDeleted)||!1===(null==n?void 0:n.isDeleted)})),t}}const $a=(e,t,n,r,s,a)=>{const{forceDispatch:o,callbackDataSelector:i,callbackFilter:c}=Object.assign({forceDispatch:!1,callbackDataSelector:e=>e},a),{cache:l}=be();let d;l||console.log("For using Live Object feature you need to enable Cache!");let u=!1;const h=[],p=e=>{const{data:n}=e,r=zt(e,["data"]);c&&!c(n,d)||t(Object.assign({data:i(n)},r)),d=ca(n)};return h.push(...s.map((t=>t((t=>((t,r=!1)=>{e===t[n]&&(d&&!r&&ln(d,t)||p({loading:!1,data:t,origin:"event"}))})(t,o)))))),(()=>{const t=ae(r,e,!0);ie(t,(({error:e,data:t,loading:n,origin:r,cachedAt:s})=>{s===q?(p({data:t,origin:r,loading:!1,error:new fe(B,800800,"error")}),u=!0,h.forEach((e=>e()))):u||p({loading:n,data:t,origin:r,error:e}),e&&h.forEach((e=>e()))}))})(),()=>{h.forEach((e=>e()))}};var za=Object.freeze({__proto__:null,blockUser:async e=>{const t=be();t.log("user/blockUser",e);const{data:n}=await t.http.post(`/api/v4/me/user-blocks/${e}`),r=t.cache&&Date.now(),{follows:s,followCounts:a}=n,o={follows:s};t.cache&&(Kt(o,{cachedAt:r}),ke(["followInfo","get",e],a[0],{cachedAt:r}));const i=pa(o);return Ze("local.follow.unfollowed",i),n},unBlockUser:async e=>{const t=be();t.log("user/unBlockUser",e);const{data:n}=await t.http.delete(`/api/v4/me/user-blocks/${e}`),r=t.cache&&Date.now(),{follows:s,followCounts:a}=n,o={follows:s};t.cache&&(Kt(o,{cachedAt:r}),ke(["followInfo","get",e],a[0],{cachedAt:r}));const i=pa(o);return Ze("local.follow.created",i),n},follow:async e=>{const t=be();t.log("follow/follow",e);const{data:n}=await t.http.post(`/api/v4/me/following/${e}`),r=t.cache&&Date.now();t.cache&&Kt(n,{cachedAt:r});const s=pa(n);return"accepted"===n.follows[0].status?Ze("local.follow.created",s):Ze("local.follow.requested",s),{data:n.follows[0],cachedAt:r}},unfollow:async e=>{const t=be();t.log("follow/unfollow",e);const{data:n}=await t.http.delete(`/api/v4/me/following/${e}`);t.cache&&Kt(n);const r=pa(n);return Ze("local.follow.unfollowed",r),!0},acceptMyFollower:async e=>{const t=be();t.log("follow/acceptMyFollower",e);const{data:n}=await t.http.post(`/api/v4/me/followers/${e}`);t.cache&&Kt(n);const r=pa(n);return Ze("local.follow.accepted",r),!0},declineMyFollower:async e=>{const t=be();t.log("follow/declineMyFollower",e);const{data:n}=await t.http.delete(`/api/v4/me/followers/${e}`);t.cache&&Kt(n);const r=pa(n);return Ze("local.follow.requestDeclined",r),!0},onUserFollowed:ga,onUserUnfollowed:ya,onFollowerDeleted:va,onFollowerRequested:ba,onFollowRequestCanceled:wa,onFollowRequestAccepted:Ca,onFollowRequestDeclined:Ia,onFollowInfoUpdated:_a,onLocalUserFollowed:ka,onLocalUserUnfollowed:Ta,onLocalFollowerRequested:Oa,onLocalFollowRequestAccepted:Aa,onLocalFollowRequestDeclined:Ea,getFollowers:(e,t,n)=>{const{log:r,cache:s}=be();s||console.log(N);const a=Date.now();r(`getFollowers(tmpid: ${a}) > listen`);const o=new Ba(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>Te(c))),()=>{r(`getFollowers(tmpid: ${a}) > dispose`),i.forEach((e=>e()))}},getFollowings:(e,t,n)=>{const{log:r,cache:s}=be();s||console.log("For using Live Collection feature you need to enable Cache!");const a=Date.now();r(`getFollowings(tmpid: ${a}) > listen`);const o=new Ka(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>Te(c))),()=>{r(`getFollowings(tmpid: ${a}) > dispose`),i.forEach((e=>e()))}},getFollowInfo:(e,t)=>$a(e,t,"userId",Sa,[_a],{forceDispatch:!0}),getMyFollowInfo:e=>{const{userId:t}=ze();return $a(t,e,"userId",Sa,[_a],{forceDispatch:!0})}});const Qa=async e=>{const t=be();t.log("user/getUsers",e);const n=e.map((e=>encodeURIComponent(e))),{data:r}=await t.http.get("/api/v3/users/list",{params:{userIds:n}}),s=$r(r),a=t.cache&&Date.now();return t.cache&&Kt(s,{cachedAt:a}),Ze("user.fetched",r),{data:s.users.map((e=>_n.user(e))),cachedAt:a}};Qa.locally=e=>{var t;const n=be();if(n.log("user/getUsers.locally",e),!n.cache)return;const r=e.map((e=>Ie(["user","get",e]))).filter(Boolean),s=r.map((({data:e})=>_n.user(e))),a=null===(t=r.sort(((e,t)=>e.cachedAt<t.cachedAt?-1:1)))||void 0===t?void 0:t[0];return(null==r?void 0:r.length)<e.length?void 0:{data:s,cachedAt:a.cachedAt}};const Va=e=>zr("user.updated",e),Ha=e=>zr("user.flagged",e),Wa=e=>zr("user.unflagged",e),Ja=e=>zr("user.flagCleared",e),Ga=e=>zr("user.fetched",e),Ya=async e=>{const t=be();t.log("user/getUser",e),Mn("user",e);try{const{data:n}=await t.http.get(`/api/v3/users/${encodeURIComponent(e)}`),r=t.cache&&Date.now(),s=$r(n);return t.cache&&Kt(s,{cachedAt:r}),Ze("user.fetched",n),{data:s.users.find((t=>t.userId===e)),cachedAt:r}}catch(t){throw H(null==t?void 0:t.code)&&$t("user",e),t}};Ya.locally=e=>{const t=be();if(t.log("user/getUser.locally",e),!t.cache)return;const n=Ie(["user","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};class Za extends Ma{async getRequest(e,t){const{limit:n=x}=e,r=zt(e,["limit"]),s=t?{token:t}:{limit:n},{data:a}=await this.http.get("/api/v3/users",{params:Object.assign(Object.assign({},r),{options:s,isDeleted:!1})});return a}}class Xa extends Pa{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=be(),r=n.cache&&Date.now();n.cache&&Kt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,s;if(n)Se(this.cacheKey,{data:e.users.map(de("user"))});else{const t=null===(r=Ie(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];Se(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.users.map(de("user"))])]}))}}reactor(e){return e=>{var t;const n=null===(t=Ie(this.cacheKey))||void 0===t?void 0:t.data;n&&(n.data=[...new Set([e.userId,...n.data])],Se(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}var eo;!function(e){e.OnUserDeleted="onUserDeleted",e.OnUserUpdated="onUserUpdated",e.OnUserFlagged="onUserFlagged",e.OnUserUnflagged="onUserUnflagged",e.OnUserFlagCleared="onUserFlagCleared"}(eo||(eo={}));class to extends Da{constructor(e,t){const n=w.default(e),r=["user","collection",n];super(new Za(e),n,r,t),this.query=e,this.queryStreamController=new Xa(this.query,this.cacheKey,this.notifyChange.bind(this),$r),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Ie(this.cacheKey))||void 0===e?void 0:e.data)||Se(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:Qr,action:eo.OnUserDeleted},{fn:Va,action:eo.OnUserUpdated},{fn:Ha,action:eo.OnUserFlagged},{fn:Wa,action:eo.OnUserUnflagged},{fn:Ja,action:eo.OnUserFlagCleared}])}notifyChange({origin:e,loading:t,error:n}){var r,s;const a=null===(r=Ie(this.cacheKey))||void 0===r?void 0:r.data;if(!a)return;const o=this.applyFilter(null!==(s=a.data.map((e=>Ie(["user","get",e]))).filter(dn).map((({data:e})=>e)).map(_n.user))&&void 0!==s?s:[]);(this.shouldNotify(o)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:o,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=e;const n=(()=>"firstCreated"===this.query.sortBy?Ne:qe)();return t=t.sort(n),"flagged"===this.query.filter&&(t=t.filter((e=>!!e.hashFlag))),t=t.filter((e=>null==e.isDeleted||!1===e.isDeleted)),t}}class no extends Ma{async getRequest(e,t){const{limit:n=x}=e,r=zt(e,["limit"]),s=t?{token:t}:{limit:n},{data:a}=await this.http.get("/api/v4/me/user-blocks",{params:Object.assign(Object.assign({},r),{options:s,isDeleted:!1})});return a}}class ro extends Pa{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=be(),r=n.cache&&Date.now();n.cache&&Kt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,s;if(n)Se(this.cacheKey,{data:e.users.map(de("user"))});else{const t=null===(r=Ie(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];Se(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.users.map(de("user"))])]}))}}reactor(e){return t=>{var n;if(e===ja.OnFollowed){const e=null===(n=Ie(this.cacheKey))||void 0===n?void 0:n.data,r=null==e?void 0:e.data.filter((e=>e!==t.userId));Se(this.cacheKey,Object.assign(Object.assign({},e),{data:r}))}this.notifyChange({origin:"event",loading:!1})}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}function so(e){const{users:t,follows:n}=e,r=zt(e,["users","follows"]);return Object.assign(Object.assign({},r),{follows:n.map((e=>{const n=t.find((t=>t.userId===e.from));return Object.assign(Object.assign({},e),{user:er(n)})})),users:t.map(er)})}const ao=(e,t,n)=>r=>e((e=>{var s;if(!e)return e;const a=[n,"get",`${e[t]}`],o=null===(s=Ie(a))||void 0===s?void 0:s.data;return o?r(o):void 0}));class oo extends Da{constructor(e,t){const n=w.default(e),r=["blockedUsers","collection",n];super(new no(e),n,r,t),this.query=e,this.queryStreamController=new ro(this.query,this.cacheKey,this.notifyChange.bind(this),so),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Ie(this.cacheKey))||void 0===e?void 0:e.data)||Se(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:Qr,action:eo.OnUserDeleted},{fn:ao(ka,"to","user"),action:ja.OnFollowed},{fn:ao(ga,"to","user"),action:ja.OnFollowed}])}notifyChange({origin:e,loading:t,error:n}){var r,s;const a=null===(r=Ie(this.cacheKey))||void 0===r?void 0:r.data;if(!a)return;const o=this.applyFilter(null!==(s=a.data.map((e=>Ie(["user","get",e]))).filter(dn).map((({data:e})=>e)).map(_n.user))&&void 0!==s?s:[]);(this.shouldNotify(o)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:o,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=e;return t=t.filter((e=>null==e.isDeleted||!1===e.isDeleted)),t}}class io extends Ma{async getRequest(e,t){const{limit:n=x,displayName:r}=e,s=zt(e,["limit","displayName"]),a=t?{token:t}:{limit:n},{data:o}=await this.http.get("/api/v3/users",{params:Object.assign(Object.assign({},s),{keyword:r,options:a,isDeleted:!1})});return o}}class co extends Pa{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=be(),r=n.cache&&Date.now();n.cache&&Kt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,s;if(n)Se(this.cacheKey,{data:e.users.map(de("user"))});else{const t=null===(r=Ie(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];Se(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.users.map(de("user"))])]}))}}reactor(e){return e=>{var t;const n=null===(t=Ie(this.cacheKey))||void 0===t?void 0:t.data;n&&(n.data=[...new Set([e.userId,...n.data])],Se(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class lo extends Da{constructor(e,t){var n;const r=w.default(e),s=["user","collection",r];super(new io(e),r,s,t),this.query=Object.assign(Object.assign({},e),{filter:null!==(n=e.filter)&&void 0!==n?n:"all"}),this.queryStreamController=new co(this.query,this.cacheKey,this.notifyChange.bind(this),$r),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Ie(this.cacheKey))||void 0===e?void 0:e.data)||Se(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:Qr,action:eo.OnUserDeleted},{fn:Va,action:eo.OnUserUpdated},{fn:Ha,action:eo.OnUserFlagged},{fn:Wa,action:eo.OnUserUnflagged},{fn:Ja,action:eo.OnUserFlagCleared}])}notifyChange({origin:e,loading:t,error:n}){var r,s;const a=null===(r=Ie(this.cacheKey))||void 0===r?void 0:r.data;if(!a)return;const o=this.applyFilter(null!==(s=a.data.map((e=>Ie(["user","get",e]))).filter(dn).map((({data:e})=>e)).map(_n.user))&&void 0!==s?s:[]);(this.shouldNotify(o)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:o,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=e;return"flagged"===this.query.filter&&(t=t.filter((e=>!!e.hashFlag))),t=t.filter((e=>null==e.isDeleted||!1===e.isDeleted)),t}}const uo=async({viewId:e,viewedType:t,limit:n,token:r})=>{const s=be(),a={};r?a.token=r:a.limit=n;const o=`/api/v1/analytics/views/${"post"===t?"posts":"stories"}/${e}/users`,i=await s.http.get(o,{params:a});return Kt(i.data),i.data};var ho;!function(e){e.DEFAULT="default",e.PARTIAL="partial"}(ho||(ho={}));var po=Object.freeze({__proto__:null,Relationship:za,getUserByIds:Qa,updateUser:async(e,t)=>{const n=be();n.log("user/updateUser",e,t);const{data:r}=await n.http.put("/api/v3/users/",Object.assign(Object.assign({userId:e},t),{createNewUserWhenNotFound:!1})),s=$r(r),a=n.cache&&Date.now();return n.cache&&Kt(s,{cachedAt:a}),Ze("user.updated",r),{data:s.users.find((t=>t.userId===e)),cachedAt:a}},flagUser:async e=>{const t=be();t.log("user/flagUser",e);const{data:n}=await t.http.post(`api/v4/me/flags/${encodeURIComponent(e)}`),r=$r(n);return t.cache&&Kt(r),Ze("user.flagged",n),!!r},unflagUser:async e=>{const t=be();t.log("user/unflag",e);const{data:n}=await t.http.delete(`/api/v4/me/flags/${encodeURIComponent(e)}`),r=$r(n);return t.cache&&Kt(r),Ze("user.unflagged",n),!!r},isUserFlaggedByMe:async e=>{const t=be();t.log("user/isUserFlaggedByMe",e);const{data:{isFlagByMe:n}}=await t.http.get(`/api/v3/users/${e}/isFlagByMe`);return n},onUserUpdated:Va,onUserDeleted:Qr,onUserFlagged:Ha,onUserUnflagged:Wa,onUserFlagCleared:Ja,getUser:(e,t)=>$a(e,(e=>t(Object.assign(Object.assign({},e),{data:e.data?_n.user(e.data):e.data}))),"userId",Ya,[Ga,Va,Qr,Ha,Wa,Ja]),getUsers:(e,t,n)=>{const{log:r,cache:s}=be();s||console.log(N);const a=Date.now();r(`liveUsers(tmpid: ${a}) > listen`);const o=new to(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>Te(c))),()=>{r(`liveUsers(tmpid: ${a}) > dispose`),i.forEach((e=>e()))}},getBlockedUsers:(e,t,n)=>{const{log:r,cache:s}=be();s||console.log(N);const a=Date.now();r(`getBlockedUsers(tmpid: ${a}) > listen`);const o=new oo(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>Te(c))),()=>{r(`getBlockedUsers(tmpid: ${a}) > dispose`),i.forEach((e=>e())),Te(c)}},searchUserByDisplayName:(e,t,n)=>{const{log:r,cache:s}=be();s||console.log(N);const a=Date.now();r(`liveSearchUsers(tmpid: ${a}) > listen`);const o=new lo(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>Te(c))),()=>{r(`liveSearchUsers(tmpid: ${a}) > dispose`),i.forEach((e=>e()))}},getReachedUsers:(e,t)=>{let n=(e=!1)=>{};const{log:r,cache:s}=be(),a=["viewedUsers","collection",{viewId:e.viewId,viewedType:e.viewedType}];s||console.log(N);const o=Date.now();r(`getReachUsers(tmpid: ${o}) > listen`);const{limit:i,viewId:c,viewedType:l}=e;return n=(e=!1)=>{var r,s,o;const d=null===(r=Ie(a))||void 0===r?void 0:r.data,u=null!==(s=null==d?void 0:d.data)&&void 0!==s?s:[];if(!e&&u.length>0&&!(null==d?void 0:d.params.page))return;const h=ae(uo,{viewId:c,viewedType:l,limit:i||10,token:e||null===(o=null==d?void 0:d.params.page)||void 0===o?void 0:o.next});ie(h,(e=>{var r,s,o,i,c;let l=null!==(o=null===(s=null===(r=Ie(a))||void 0===r?void 0:r.data)||void 0===s?void 0:s.data)&&void 0!==o?o:[];(null===(i=e.data)||void 0===i?void 0:i.users)&&(l=[...new Set([...l,...e.data.users.map((({userId:e})=>e))])]);const d={loading:e.loading,params:{page:null===(c=e.data)||void 0===c?void 0:c.paging},data:l||[]};Se(a,d),(e=>{var r,s;let a=[];(null==e?void 0:e.data)&&(a=e.data.map((e=>Ie(["user","get",e]))).filter(Boolean).map((e=>null==e?void 0:e.data))||[]),t({onNextPage:n,data:a,hasNextPage:!!(null===(s=null===(r=e.params)||void 0===r?void 0:r.page)||void 0===s?void 0:s.next),loading:e.loading||!1})})(d)}),oe(D,2e3))},n(!0),()=>{r(`getReachUsers(tmpid: ${o}) > dispose`),Te(a)}},get AmityUserSearchMatchType(){return ho}});const fo=async e=>{const t=be();t.log("file/getFile",e);const{data:n}=await t.http.get(`/api/v3/files/${e}`),r=t.cache&&Date.now();return t.cache&&Kt({files:[n]},{cachedAt:r}),{data:n,cachedAt:r}};fo.locally=e=>{const t=be();if(t.log("file/getFile.locally",e),!t.cache)return;const n=Ie(["file","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const mo=async(e,t,n)=>{const r=be();r.log("file/uploadVideo",e);const s=e.getAll("files");if(!s.length)throw new Error("The formData object must have a `files` key.");const a=ea().getFileAccessType();e.append("accessType",a),e.append("preferredFilename",s[0].name),t&&e.append("feedType",t);const o="getHeaders"in e?e.getHeaders():{"content-type":"multipart/form-data"},{data:i}=await r.upload.post("/api/v4/videos",e,{headers:o,onUploadProgress({loaded:e,total:t=100}){n&&n(Math.round(100*e/t))}}),c=r.cache&&Date.now();return r.cache&&Kt({files:i},{cachedAt:c}),{data:i,cachedAt:c}},go=async(e,t,n)=>{const r=be();r.log("file/uploadImage",e);const s=e.getAll("files");if(null==s?void 0:s.length)console.warn("Deprecation Warning: `files` is deprecated, please use `file` instead."),e.append("preferredFilename",s[0].name);else{const t=e.get("file");if(!t)throw new Error("The formData object must have a `file` or `files` key");e.append("preferredFilename",t.name),n&&e.append("altText",n)}const a=ea().getFileAccessType();e.append("accessType",a);const o="getHeaders"in e?e.getHeaders():{"content-type":"multipart/form-data"},{data:i}=await r.upload.post("/api/v4/images",e,{headers:o,onUploadProgress({loaded:e,total:n=100}){t&&t(Math.round(100*e/n))}}),c=r.cache&&Date.now();return r.cache&&Kt({files:i},{cachedAt:c}),{data:i,cachedAt:c}};var yo=Object.freeze({__proto__:null,getFile:fo,uploadFile:async(e,t)=>{const n=be();n.log("file/uploadFile",e);const r=e.getAll("files");if(!r.length)throw new Error("The formData object must have a `files` key.");const s=ea().getFileAccessType();e.append("accessType",s),e.append("preferredFilename",r[0].name);const a="getHeaders"in e?e.getHeaders():{"content-type":"multipart/form-data"},{data:o}=await n.upload.post("/api/v4/files",e,{headers:a,onUploadProgress({loaded:e,total:n=100}){t&&t(Math.round(100*e/n))}}),i=n.cache&&Date.now();return n.cache&&Kt({files:o},{cachedAt:i}),{data:o,cachedAt:i}},deleteFile:async e=>{const t=be();return t.log("file/deleteFile",e),await t.http.delete(`/api/v3/files/${e}`),Te(["file","get",e],!0),{success:!0}},fileUrlWithSize:(e,t)=>`${e}?size=${t}`,uploadVideo:mo,uploadImage:go,updateAltText:async(e,t)=>{const n=be();n.log("file/updateAltText",t);const{data:r}=await n.http.put(`/api/v3/files/${e}`,{altText:t}),s=n.cache&&Date.now();return n.cache&&Kt({files:[r]},{cachedAt:s}),!0}});const vo=async e=>{const t=be();t.log("role/queryRoles",e);const n=null!=e?e:{},{limit:r=10,queryToken:s,displayName:a,sortBy:o}=n,i=zt(n,["limit","queryToken","displayName","sortBy"]),c=s?{token:s}:r?{limit:r}:void 0,{data:l}=await t.http.get("/api/v3/roles",{params:Object.assign(Object.assign({},i),{keyword:a,sortBy:o,options:c})}),{paging:d}=l,u=zt(l,["paging"]),{roles:h}=u,p=t.cache&&Date.now();t.cache&&Kt(u,{cachedAt:p});const f=X(d.next);return{data:h,cachedAt:p,prevPage:X(d.previous),nextPage:f,paging:d}};vo.locally=e=>{be().log("role/queryRoles.locally",e)};const bo=async e=>{const t=be();t.log("role/getRole",e);const{data:n}=await t.http.get(`/api/v3/roles/${e}`),r=t.cache&&Date.now();return t.cache&&Kt({roles:n},{cachedAt:r}),{data:n.find((t=>t.roleId===e)),cachedAt:r}};bo.locally=e=>{const t=be();if(t.log("role/getRole.locally",e),!t.cache)return;const n=Ie(["role","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const wo=(e,t)=>{"message"===e?Ze("local.message.updated",{messages:[t]}):"post"===e?Ze("post.updated",{posts:[t]}):"comment"===e?Ze("comment.updated",{comments:[t]}):"story"===e&&Ze("story.updated",{categories:[],comments:[],communities:[],communityUsers:[],files:[],users:[],stories:[t]})},Co=async(e,t=!1)=>{const n=be();let r;n.log("message/getMessage",e),Mn("message",e);try{const{data:t}=await n.http.get(`/api/v5/messages/${encodeURIComponent(e)}`);r=await Fn(t)}catch(t){throw H(null==t?void 0:t.code)&&$t("message",e),t}const s=n.cache&&Date.now();n.cache&&Kt(r,{cachedAt:s});const{messages:a}=r;return Ze("local.message.fetched",{messages:a}),{data:a.find((t=>t.messageId===e)),cachedAt:s}};Co.locally=e=>{const t=be();if(t.log("message/getMessage.locally",e),!t.cache)return;const n=Ie(["message","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const Io=async e=>{const t=be();let n;t.log("post/getPost",e),Mn("post",e);try{n=(await t.http.get(`/api/v3/posts/${encodeURIComponent(e)}`)).data}catch(t){throw H(null==t?void 0:t.code)&&$t("post",e),t}const r=Vt(n,"communityUsers"),s=t.cache&&Date.now();t.cache&&Kt(r,{cachedAt:s});const{posts:a}=r;return{data:a.find((t=>t.postId===e)),cachedAt:s}};Io.locally=e=>{const t=be();if(t.log("post/getPost.locally",e),!t.cache)return;const n=Ie(["post","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const So=async e=>{const t=be();let n;t.log("comment/getComment",e),Mn("comment",e);try{n=(await t.http.get(`/api/v3/comments/${encodeURIComponent(e)}`)).data}catch(t){throw H(null==t?void 0:t.code)&&$t("comment",e),t}const r=t.cache&&Date.now();t.cache&&Kt(n,{cachedAt:r});const{comments:s}=n;return{data:_n.comment(s.find((t=>t.commentId===e))),cachedAt:r}};function _o(e,t){return e.map((e=>{const n=Ie(["community","get",e.communityId]);if((null==n?void 0:n.data)&&(null==n?void 0:n.data.hasOwnProperty("isJoined")))return Object.assign(Object.assign({},n.data),e);const r=t.some((t=>function(e,t){const{userId:n}=ze();return e.communityId===t.communityId&&t.userId===n}(e,t)&&"none"!==t.communityMembership));return Object.assign(Object.assign({},e),{isJoined:r})}))}So.locally=e=>{const t=be();if(t.log("comment/getComment.locally",e),!t.cache)return;const n=Ie(["comment","get",e]);return n?{data:_n.comment(n.data),cachedAt:n.cachedAt}:void 0};const ko=(e,t)=>{var n,r;let s,a;if("post"===t)a="post",s=e.posts[0].postId;else if("comment"===t)a="comment",s=e.comments[0].commentId;else{if("story"!==t)throw new Error("Unknown event type");a="story",s=e.stories[0].referenceId}return(null===(r=null===(n=Ie([a,"get",s]))||void 0===n?void 0:n.data)||void 0===r?void 0:r.myReactions)||[]},To=(e,t,n)=>{const[r]=e[t];return Object.assign(Object.assign({},e),{[t]:[Object.assign(Object.assign({},r),{myReactions:n})]})},Oo=(e,t,n,r=[])=>{const s=e.split(".")[1];let a=r;if(be().userId===t)if(["addReaction","reactionAdded"].includes(s))a.includes(n)||a.push(n);else{if(!["removeReaction","reactionRemoved"].includes(s))throw new Error(`Unknown event type: ${s}`);a=a.filter((e=>e!==n))}return a},Ao=(e,t)=>{const n=e.split(".")[0],r=ko(t,n),s=Oo(e,t.reactor.userId,t.reactor.reactionName,r);return To(t,`${n}s`,s)},Eo=(e,t)=>{var n,r;const s=e.split(".")[0];let a=ko(t,s);(null==t?void 0:t.reactions)&&t.reactions.length>0&&(a=Oo(e,null===(n=t.reactions[0])||void 0===n?void 0:n.userId,null===(r=t.reactions[0])||void 0===r?void 0:r.reactionName,a));const o=To(t,"stories",a);if(!(null==t?void 0:t.communities)||!(null==t?void 0:t.communityUsers))return o;const i=_o(t.communities,t.communityUsers);return Object.assign(Object.assign({},o),{communities:i})},Mo=async(e,t,n)=>{var r,s,a;const o=be();if(o.log("reaction/createReaction",{referenceId:t,referenceType:e,reactionName:n}),!["post","comment","story","message"].includes(e))throw new fe("The reference type is not valid. It should be one of post, comment, story, or message",4e5,"error");const{data:i}=await o.http.post("/api/v2/reactions",{referenceId:t,referenceType:e,reactionName:n,referenceVersion:"message"===e?5:void 0});if(o.cache){const c=Ie([e,"get",t]);if(!c||(null===(r=c.data.myReactions)||void 0===r?void 0:r.includes(n)))return!0;const l=Object.assign(Object.assign({},c.data),{reactionsCount:c.data.reactionsCount+1,myReactions:[...null!==(s=c.data.myReactions)&&void 0!==s?s:[],n],reactions:Object.assign(Object.assign({},c.data.reactions),{[n]:(null!==(a=c.data.reactions[n])&&void 0!==a?a:0)+1})});if("comment"===e)return Ze("local.comment.addReaction",{comment:l,reactor:{userId:o.userId,reactionName:n,reactionId:i.addedId}}),!0;if("post"===e)return Ze("local.post.addReaction",{post:l,reactor:{userId:o.userId,reactionName:n,reactionId:i.addedId}}),!0;if("story"===e)return Ze("local.story.reactionAdded",{story:l,reactor:{userId:o.userId,reactionName:n,reactionId:i.addedId}}),!0}return!0};Mo.optimistically=(e,t,n)=>{var r,s,a,o,i;const c=be();if(c.log("reaction/createReaction.optimistically",{referenceId:t,referenceType:e,reactionName:n}),!c.cache)return;const l=Ie([e,"get",t]);if(!(null==l?void 0:l.data)||(null===(r=l.data.myReactions)||void 0===r?void 0:r.includes(n)))return;const d=Object.assign(Object.assign({},l.data),{reactionsCount:l.data.reactionsCount+1,myReactions:[...null!==(s=l.data.myReactions)&&void 0!==s?s:[],n],reactions:Object.assign(Object.assign({},l.data.reactions),{[n]:(null!==(a=l.data.reactions[n])&&void 0!==a?a:0)+1})});return ke([e,"get",t],d,{cachedAt:q}),wo(e,d),null!==(i=null===(o=null==d?void 0:d.myReactions)||void 0===o?void 0:o.includes(n))&&void 0!==i&&i};const Ro=async(e,t,n)=>{var r,s;const a=be();if(a.log("reaction/removeReaction",{referenceId:t,referenceType:e,reactionName:n}),!["post","comment","story","message"].includes(e))throw new fe("The reference type is not valid. It should be one of post, comment, story, or message",4e5,"error");const{data:o}=await a.http.delete("/api/v2/reactions",{data:{referenceId:t,referenceType:e,reactionName:n,referenceVersion:"message"===e?5:void 0}});if(a.cache){const i=Ie([e,"get",t]);if(!i)return!0;const c=Object.assign(Object.assign({},i.data),{reactionsCount:Math.max(0,i.data.reactionsCount-1),myReactions:(null!==(r=i.data.myReactions)&&void 0!==r?r:[]).filter((e=>e!==n)),reactions:Object.assign(Object.assign({},i.data.reactions),{[n]:Math.max(0,(null!==(s=i.data.reactions[n])&&void 0!==s?s:0)-1)})});if("comment"===e)return Ze("local.comment.removeReaction",{comment:c,reactor:{reactionId:o.removedId,reactionName:n,userId:a.userId}}),!0;if("post"===e)return Ze("local.post.removeReaction",{post:c,reactor:{reactionId:o.removedId,reactionName:n,userId:a.userId}}),!0;if("story"===e)return Ze("local.story.reactionAdded",{story:c,reactor:{userId:a.userId,reactionName:n,reactionId:o.removedId}}),!0}return!0};Ro.optimistically=(e,t,n)=>{var r,s,a,o;const i=be();if(i.log("reaction/removeReaction.optimistically",{referenceId:t,referenceType:e,reactionName:n}),!i.cache)return;const c=Ie([e,"get",t]);if(!(null==c?void 0:c.data)||!(null===(r=c.data.myReactions)||void 0===r?void 0:r.includes(n)))return;const l=Object.assign(Object.assign({},c.data),{reactionsCount:Math.max(0,c.data.reactionsCount-1),myReactions:(null!==(s=c.data.myReactions)&&void 0!==s?s:[]).filter((e=>e!==n)),reactions:Object.assign(Object.assign({},c.data.reactions),{[n]:Math.max(0,(null!==(a=c.data.reactions[n])&&void 0!==a?a:0)-1)})});return ke([e,"get",t],l,{cachedAt:q}),wo(e,l),!(null===(o=null==l?void 0:l.myReactions)||void 0===o?void 0:o.includes(n))};const Po=e=>{var t;return null!==(t=Object.keys(A).find((t=>e.needApprovalOnPostCreation===A[t].needApprovalOnPostCreation&&e.onlyAdminCanPost===A[t].onlyAdminCanPost)))&&void 0!==t?t:E};function jo({communities:e}){return e.map((e=>{var{needApprovalOnPostCreation:t,onlyAdminCanPost:n}=e,r=zt(e,["needApprovalOnPostCreation","onlyAdminCanPost"]);return Object.assign({postSetting:Po({needApprovalOnPostCreation:t,onlyAdminCanPost:n})},r)}))}const Uo=e=>{const t=jo({communities:e.communities}),n=e.communityUsers.map((t=>{const n=e.users.find((e=>e.userId===t.userId));return Object.assign(Object.assign({},t),{user:n})})),r=_o(t,n);return Object.assign(Object.assign({},e),{communities:r,communityUsers:n})},xo=e=>{const t=jo({communities:e.communities}),n=e.communityUsers.map((t=>{const n=e.users.find((e=>e.userId===t.userId));return Object.assign(Object.assign({},t),{user:n})})),r=_o(t,n);return Object.assign(Object.assign({},e),{communities:r,communityUsers:n})},Do=e=>{const{postSetting:t,storySetting:n}=e,r=zt(e,["postSetting","storySetting"]);return Object.assign(Object.assign(Object.assign({},r),t?A[t]:void 0),{allowCommentInStory:"boolean"!=typeof(null==n?void 0:n.enableComment)||n.enableComment})},No=e=>{var t=zt(e,["searchResult"]);const n=Uo(t);return Object.assign({},n)},Bo=e=>{const{posts:t}=e,n=zt(e,["posts"]),r=jo({communities:n.communities}),s=n.communityUsers.map((e=>{const t=n.users.find((t=>t.userId===e.userId));return Object.assign(Object.assign({},e),{user:t})})),a=_o(r,s),o=t.map((e=>{var t;const r=null===(t=n.feeds.find((t=>t.feedId===e.feedId)))||void 0===t?void 0:t.feedType;return Object.assign(Object.assign({},e),{feedType:r})}));return Object.assign(Object.assign({},n),{posts:o,communities:a,communityUsers:s})},qo=e=>{var{searchResult:t,polls:n}=e,r=zt(e,["searchResult","polls"]);const s=Bo(r);return Object.assign(Object.assign({},s),{polls:n})},Fo=(e,t)=>{const n=be();return Ye(n,e,e,(r=>{var s;if(n.cache){const a=Bo(r),{communities:o}=a;if(Kt(a,void 0,!1),(null==o?void 0:o[0])&&!["post.updated"].includes(e)&&Ze("community.updated",{communities:o,categories:[],communityUsers:a.communityUsers,feeds:[],files:[],users:[]}),"post.deleted"===e){const{postId:e,postedUserId:s}=r.posts[0];try{Mn("post",e)}catch(e){return}return s!==n.userId&&Te(["post","get",e]),t(r.posts[0])}const i=Ie(["post","get",r.posts[0].postId]);if(["post.created","post.approved","post.declined"].includes(e)){let t=null===(s=Ce(["post","query"]))||void 0===s?void 0:s.filter((({key:e})=>{var t;return(null===(t=e[2])||void 0===t?void 0:t.targetId)===i.data.targetId}));"post.declined"===e&&(t=null==t?void 0:t.filter((({key:e})=>{var t;return"reviewing"===(null===(t=e[2])||void 0===t?void 0:t.feedType)}))),null==t||t.map((({key:e,data:t})=>ke(e,t,{cachedAt:-1})))}t(i.data)}else t(r.posts[0])}))},Lo=(e,t)=>{const n=be();return Ye(n,e,e,(r=>{if(n.cache){const n=Bo(r),{communities:s}=n;Kt(n),(null==s?void 0:s[0])&&!["local.post.updated"].includes(e)&&Ze("community.updated",{communities:s,categories:[],communityUsers:n.communityUsers,feeds:[],files:[],users:[]});const a=Ie(["post","get",r.posts[0].postId]);t(a.data)}else t(r.posts[0])}))},Ko=e=>Fo("post.created",e),$o=e=>Fo("post.updated",e),zo=e=>Fo("post.deleted",e),Qo=e=>Fo("post.approved",e),Vo=e=>Fo("post.declined",e),Ho=e=>Fo("post.flagged",e),Wo=e=>Fo("post.unflagged",e),Jo=e=>{const t=be();return Ye(t,"post.addReaction","post.addReaction",(n=>{if(t.cache){const t=zt(Ao("post.addReaction",n),["reactor"]);Kt(t);const r=Ie(["post","get",n.posts[0].postId]);e(r.data)}else e(n.posts[0])}))},Go=e=>{const t=be();return Ye(t,"post.removeReaction","post.removeReaction",(n=>{if(t.cache){const t=zt(Ao("post.removeReaction",n),["reactor"]);Kt(t);const r=Ie(["post","get",n.posts[0].postId]);e(r.data)}else e(n.posts[0])}))},Yo=(e,t)=>{const n=be();return Ye(n,e,e,(r=>{var s;if(n.cache){const a=["comment.flagged","comment.unflagged"].includes(e)?(e=>{const t=ko(e,"comment");return To(e,"comments",t)})(r):r;Kt(a,void 0,!1);const{comments:o}=a;if(o.length>0){const r=Ie(["comment","get",o[0].commentId]);if(["comment.created"].includes(e)){if("comment.created"===e&&r.data.userId===n.userId)return;if(o[0].parentId){const e=Ie(["comment","get",o[0].parentId]);(null==e?void 0:e.data)&&(e.data.children.includes(o[0].commentId)||Se(["comment","get",o[0].parentId],Object.assign(Object.assign({},e.data),{childrenNumber:e.data.childrenNumber+1,children:[...new Set([...e.data.children,o[0].commentId])]})))}}if(["comment.deleted"].includes(e)){if("comment.deleted"===e&&r.data.userId===n.userId)return;if(o[0].parentId){const e=Ie(["comment","get",o[0].parentId]);if((null==e?void 0:e.data)&&e.data.children.includes(o[0].commentId)){const t=Object.assign(Object.assign({},e.data),{childrenNumber:e.data.childrenNumber-1,children:[...new Set([...e.data.children.filter((e=>e!==o[0].commentId))])]});Se(["comment","get",o[0].parentId],t)}}const t=null===(s=Ce(["comment","query"]))||void 0===s?void 0:s.filter((({key:e})=>{var t;return(null===(t=e[2])||void 0===t?void 0:t.referenceId)===r.data.referenceId}));null==t||t.map((({key:e,data:t})=>ke(e,t,{cachedAt:-1})))}t(_n.comment(r.data))}}else t(_n.comment(r.comments[0]))}))},Zo=(e,t)=>{const n=be();return Ye(n,e,e,(r=>{var s,a;if(n.cache){const n=r;Kt(n);const{comments:o}=n;if(o.length>0){const n=Ie(["comment","get",o[0].commentId]);if(["local.comment.created"].includes(e)){if(o[0].parentId){const e=Ie(["comment","get",o[0].parentId]);if((null==e?void 0:e.data)&&!e.data.children.includes(o[0].commentId)){const t=Object.assign(Object.assign({},e.data),{childrenNumber:e.data.childrenNumber+1,children:[...new Set([...e.data.children,o[0].commentId])]});Se(["comment","get",o[0].parentId],t),setTimeout((()=>{Ze("comment.updated",{comments:[t],commentChildren:[],files:[],users:[],communityUsers:[]})}),200)}}const e=null===(s=Ce(["comment","query"]))||void 0===s?void 0:s.filter((({key:e})=>{var t;return(null===(t=e[2])||void 0===t?void 0:t.referenceId)===n.data.referenceId}));null==e||e.map((({key:e,data:t})=>ke(e,t,{cachedAt:-1})))}if(["local.comment.deleted"].includes(e)){if(o[0].parentId){const e=Ie(["comment","get",o[0].parentId]);if((null==e?void 0:e.data)&&e.data.children.includes(o[0].commentId)){const t=Object.assign(Object.assign({},e.data),{childrenNumber:e.data.childrenNumber-1,children:[...new Set([...e.data.children.filter((e=>e!==o[0].commentId))])]});Se(["comment","get",o[0].parentId],t),setTimeout((()=>{Ze("comment.updated",{comments:[t],commentChildren:[],files:[],users:[],communityUsers:[]})}),200)}}const e=null===(a=Ce(["comment","query"]))||void 0===a?void 0:a.filter((({key:e})=>{var t;return(null===(t=e[2])||void 0===t?void 0:t.referenceId)===n.data.referenceId}));null==e||e.map((({key:e,data:t})=>ke(e,t,{cachedAt:-1})))}t(_n.comment(n.data))}}else t(_n.comment(r.comments[0]))}))},Xo=e=>Yo("comment.created",e),ei=e=>Yo("comment.updated",e),ti=e=>Yo("comment.deleted",e),ni=e=>Yo("comment.flagged",e),ri=e=>Yo("comment.unflagged",e),si=e=>{const t=be();return Ye(t,"comment.addReaction","comment.addReaction",(n=>{if(t.cache){const t=zt(Ao("comment.addReaction",n),["reactor"]);Kt(t);const r=Ie(["comment","get",n.comments[0].commentId]);e(_n.comment(r.data))}else e(_n.comment(n.comments[0]))}))},ai=e=>{const t=be();return Ye(t,"comment.removeReaction","comment.removeReaction",(n=>{if(t.cache){const t=zt(Ao("comment.removeReaction",n),["reactor"]);Kt(t);const r=Ie(["comment","get",n.comments[0].commentId]);e(_n.comment(r.data))}else e(_n.comment(n.comments[0]))}))},oi=(e,t,n)=>{const r=be(),s=(r,s,a)=>{r===e&&s===t&&n(a)};if("message"===e){return Ye(r,"reaction/onReactorAdded","message.reactionAdded",(async e=>{const t=await Fn(e);t.reactions[0]&&(Kt(t),Kt({reactors:t.reactions}),s("message",t.messages[0].messageId,t.reactions[0]))}))}if("post"===e){return Ye(r,"post.addReaction","post.addReaction",(e=>{const{reactor:t}=e,n=zt(e,["reactor"]);Kt(n),Kt({reactions:[t]}),s("post",e.posts[0].postId,t)}))}if("story"===e){return Ye(r,"story.reactionAdded","story.reactionAdded",(e=>{const{reactions:t}=e,n=zt(e,["reactions"]);Kt(n),Kt({reactors:t}),0!==e.stories.length&&0!==e.reactions.length&&s("story",e.stories[0].storyId,e.reactions[0])}))}return Ye(r,"comment.addReaction","comment.addReaction",(e=>{const{reactor:t}=e,n=zt(e,["reactor"]);Kt(n),Kt({reactions:[t]}),s("comment",e.comments[0].commentId,t)}))},ii=(e,t,n)=>{const r=be(),s=(r,s,a)=>{r===e&&s===t&&n(a)};if("message"===e){return Ye(r,"reaction/onReactorRemoved","message.reactionRemoved",(async e=>{const t=await Fn(e);t.reactions[0]&&(Kt(t),s("message",t.messages[0].messageId,t.reactions[0]))}))}if("post"===e){return Ye(r,"post.removeReaction","post.removeReaction",(e=>{const{reactor:t}=e,n=zt(e,["reactor"]);Kt(n),Kt({reactions:[t]}),s("post",e.posts[0].postId,t)}))}if("story"===e){return Ye(r,"story.reactionRemoved","story.reactionRemoved",(e=>{const{reactions:t}=e,n=zt(e,["reactions"]);Kt(n),Kt({reactors:t}),0!==e.stories.length&&0!==e.reactions.length&&s("story",e.stories[0].storyId,e.reactions[0])}))}return Ye(r,"comment.removeReaction","comment.removeReaction",(e=>{const{reactor:t}=e,n=zt(e,["reactor"]);Kt(n),Kt({reactions:[t]}),s("comment",e.comments[0].commentId,t)}))};class ci extends Ma{async getRequest(e,t){const{limit:n=x}=e,r=zt(e,["limit"]),s=t?{token:t}:{limit:n};be().log("reaction/queryReactions",e);if(!["post","comment","story","message"].includes(r.referenceType))throw new fe("The reference type is not valid. It should be one of post, comment, story, or message",4e5,"error");const{data:a}=await this.http.get("/api/v3/reactions",{params:Object.assign(Object.assign({},r),{referenceVersion:5,options:s})});return a}}class li extends Pa{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){var t;const n=await this.preparePayload(e),r=be(),s=r.cache&&Date.now();if(r.cache){const{reactions:e}=n,r=zt(n,["reactions"]);Kt(Object.assign(Object.assign({},r),{reactions:e,reactors:null===(t=e[0])||void 0===t?void 0:t.reactors}),{cachedAt:s})}}appendToQueryStream(e,t,n=!1){var r,s,a,o;const i=null!==(s=null===(r=e.reactions[0])||void 0===r?void 0:r.reactors)&&void 0!==s?s:[];if(n)Se(this.cacheKey,{data:i.map(de("reactor"))});else{const e=null===(a=Ie(this.cacheKey))||void 0===a?void 0:a.data,t=null!==(o=null==e?void 0:e.data)&&void 0!==o?o:[];Se(this.cacheKey,Object.assign(Object.assign({},e),{data:[...new Set([...t,...i.map(de("reactor"))])]}))}}reactor(e){return t=>{var n;const r=null===(n=Ie(this.cacheKey))||void 0===n?void 0:n.data;r&&("onAdded"===e?r.data=[...new Set([t.reactionId,...r.data])]:"onRemoved"===e&&(r.data=r.data.filter((e=>e!==t.reactionId))),Se(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class di extends Da{constructor(e,t){const n=w.default(e),r=["reaction","collection",n];super(new ci(e),n,r,t),this.query=e,this.queryStreamController=new li(this.query,this.cacheKey,this.notifyChange.bind(this),(e=>e)),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Ie(this.cacheKey))||void 0===e?void 0:e.data)||Se(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:e=>oi(this.query.referenceType,this.query.referenceId,e),action:"onAdded"},{fn:e=>ii(this.query.referenceType,this.query.referenceId,e),action:"onRemoved"},{fn:e=>((e,t,n)=>{const r=be(),s=(r,s,a)=>{r===e&&s===t&&n(a)};if("message"===e)return Ye(r,"reaction/onReactorRemoved","message.reactionRemoved",(async e=>{const t=await Fn(e);t.reactions[0]&&(Kt(t),s("message",t.messages[0].messageId,t.reactions[0]))}));if("post"===e)return Ye(r,"local.post.removeReaction","local.post.removeReaction",(e=>{s("post",e.post.postId,e.reactor)}));if("story"===e)return Ye(r,"story.reactionRemoved","story.reactionRemoved",(e=>{const{reactions:t}=e,n=zt(e,["reactions"]);Kt(n),Kt({reactors:t}),0!==e.stories.length&&0!==e.reactions.length&&s("story",e.stories[0].storyId,e.reactions[0])}));return Ye(r,"local.comment.removeReaction","local.comment.removeReaction",(e=>{s("comment",e.comment.commentId,e.reactor)}))})(this.query.referenceType,this.query.referenceId,e),action:"onRemoved"},{fn:e=>((e,t,n)=>{const r=be(),s=(r,s,a)=>{r===e&&s===t&&n(a)};if("message"===e)return Ye(r,"reaction/onReactorAdded","message.reactionAdded",(async e=>{const t=await Fn(e);t.reactions[0]&&(Kt(t),Kt({reactors:t.reactions}),s("message",t.messages[0].messageId,t.reactions[0]))}));if("post"===e)return Ye(r,"local.post.addReaction","local.post.addReaction",(e=>{s("post",e.post.postId,e.reactor)}));if("story"===e)return Ye(r,"story.reactionAdded","story.reactionAdded",(e=>{const{reactions:t}=e,n=zt(e,["reactions"]);Kt(n),Kt({reactors:t}),0!==e.stories.length&&0!==e.reactions.length&&s("story",e.stories[0].storyId,e.reactions[0])}));return Ye(r,"local.comment.addReaction","local.comment.addReaction",(e=>{s("comment",e.comment.commentId,e.reactor)}))})(this.query.referenceType,this.query.referenceId,e),action:"onRemoved"}])}notifyChange({origin:e,loading:t,error:n}){var r,s;const a=null===(r=Ie(this.cacheKey))||void 0===r?void 0:r.data;if(!a)return;const o=null!==(s=a.data.map((e=>Ie(["reactor","get",e]))).filter(Boolean).map((({data:e})=>_n.reactor(e))))&&void 0!==s?s:[];(this.shouldNotify(o)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:o,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}}var ui=Object.freeze({__proto__:null,addReaction:Mo,removeReaction:Ro,onReactionAdded:(e,t,n)=>{const r=r=>{de(e)(r)===t&&n(r)};if("message"===e){const e=be(),t=async e=>{var t;const n=await Fn(e),s=Ie(["message","get",n.messages[0].messageId]),a=(null===(t=null==s?void 0:s.data)||void 0===t?void 0:t.reactionsCount)!==n.messages[0].reactionsCount;Kt(n),a&&r(n.messages[0])};return Ye(e,"reaction/onReactionAdded","message.updated",t)}return"post"===e?Jo(r):si(r)},onReactionRemoved:(e,t,n)=>{const r=r=>{de(e)(r)===t&&n(r)};if("message"===e){const e=be(),t=async e=>{var t;const n=await Fn(e),s=Ie(["message","get",n.messages[0].messageId]),a=(null===(t=null==s?void 0:s.data)||void 0===t?void 0:t.reactionsCount)!==n.messages[0].reactionsCount;Kt(n),a&&r(n.messages[0])};return Ye(e,"reaction/onReactionRemoved","message.updated",t)}return"post"===e?Go(r):ai(r)},onReactorAdded:oi,onReactorRemoved:ii,getReactions:(e,t,n)=>{const{log:r,cache:s}=be(),a=Date.now();r(`getReactions(tmpid: ${a}) > listen`);const o=new di(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>{Te(c)})),()=>{r(`getReactions(tmpid: ${a}) > dispose`),i.forEach((e=>e()))}}});function hi(e){const{comments:t}=e;return Object.assign(Object.assign({},e),{comments:t.map((e=>e.hasOwnProperty("myReactions")?e:Object.assign({myReactions:[]},e)))})}const pi=async e=>{const t=be();let n;t.log("channel/getChannel",e),Mn("channel",e);try{const{data:r}=await t.http.get(`/api/v3/channels/${encodeURIComponent(e)}`);n=await ar(r),t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&ir(r)}catch(t){throw H(null==t?void 0:t.code)&&$t("channel",e),t}const r=t.cache&&Date.now();t.cache&&Kt(n,{cachedAt:r});const{channels:s}=n;return{data:s.find((t=>t.channelId===e)),cachedAt:r}};pi.locally=e=>{var t;const n=be();if(n.log("channel/getChannel.locally",e),!n.cache)return;const r=null===(t=Ce(["channel","get"]))||void 0===t?void 0:t.filter((({data:t})=>t.channelPublicId===e));return r&&0!==(null==r?void 0:r.length)?{data:r[0].data,cachedAt:r[0].cachedAt}:void 0};const fi=e=>{const t=be(),n=[Ye(t,"onMessageUpdated","message.updated",(async t=>{const n=await Fn(t);Kt(n),e(n.messages[0])})),Ye(t,"onMessageUpdated","local.message.updated",(t=>e(t.messages[0])))];return()=>{n.forEach((e=>e()))}},mi=e=>{const t=be(),n=[Ye(t,"message/onMessageDeleted","message.deleted",(async t=>{const n=await Fn(t);Kt(n),e(n.messages[0])})),Ye(t,"message/onMessageDeleted","local.message.deleted",(t=>e(t.messages[0])))];return()=>{n.forEach((e=>e()))}},gi=e=>{const t=be(),n=[Ye(t,"onSubChannelUpdated","message-feed.updated",(async t=>{const n=await Qn(t);Kt(n),e(n.messageFeeds[0])})),Ye(t,"onSubChannelUpdated","local.message-feed.updated",(t=>e(t.messageFeeds[0])))];return()=>{n.forEach((e=>e()))}};function yi(e,t){Se(["channel","get",e.channelId],Sn(e,t))}const vi=e=>{const t=be();return Ye(t,"channelMarker/onChannelMarkerUpdated","local.channelMarker.updated",(t=>{e(t.userEntityMarkers[0])}))},bi=async(e,t=!1)=>{const n=be(),r=await Vn(e);await n.http.delete(`/api/v5/message-feeds/${encodeURIComponent(e)}`,{params:{permanent:t}});const s=Object.assign(Object.assign({},r.data),{isDeleted:!0,updatedAt:he(r.data.updatedAt)});return t?setTimeout((()=>{$t("subChannel",e)}),0):ke(["subChannel","get",e],s),Ze("local.message-feed.deleted",{messageFeeds:[s]}),s},wi=e=>Ye(be(),"onSubChannelFetched","local.message-feed.fetched",(t=>e(t.messageFeeds[0]))),Ci=()=>`LOCAL_${xt()}`;let Ii;const Si=async(e,t)=>{const n=be();n.log("message/updateMessage",t),console.warn("MessageRepository.updateMessage will be replaced with MessageRepository.editMessage");const{data:r}=await n.http.put(`/api/v5/messages/${encodeURIComponent(e)}`,Ln(t)),s=await Fn(r),a=n.cache&&Date.now();n.cache&&Kt(s,{cachedAt:a});const{messages:o}=s;return Ze("local.message.updated",{messages:o}),{data:_n.message(o.find((t=>t.messageId===e))),cachedAt:a}};Si.optimistically=(e,t)=>{const n=be();if(n.log("message/updateMessage.optimistically",t),!n.cache)return;const r=Ie(["message","get",e]);if(!r)return;const s=Object.assign(Object.assign(Object.assign({},r.data),t),{updatedAt:(new Date).toISOString()});return ke(["message","get",e],s,{cachedAt:-1}),Ze("local.message.updated",{messages:[s]}),{data:_n.message(s),cachedAt:-1}};const _i=async(e,t)=>{const n=be();n.log("message/editMessage",t);const{data:r}=await n.http.put(`/api/v5/messages/${encodeURIComponent(e)}`,Ln(t)),s=await Fn(r),a=n.cache&&Date.now();n.cache&&Kt(s,{cachedAt:a});const{messages:o}=s;return Ze("local.message.updated",{messages:o}),{data:_n.message(o.find((t=>t.messageId===e))),cachedAt:a}};_i.optimistically=(e,t)=>{const n=be();if(n.log("message/editMessage.optimistically",t),!n.cache)return;const r=Ie(["message","get",e]);if(!r)return;const s=Object.assign(Object.assign(Object.assign({},r.data),t),{updatedAt:(new Date).toISOString()});return ke(["message","get",e],s,{cachedAt:-1}),Ze("local.message.updated",{messages:[s]}),{data:_n.message(s),cachedAt:-1}};const ki=async e=>{const t=be();t.log("message/deleteMessage",e);const{data:n}=await t.http.delete(`/api/v5/messages/${encodeURIComponent(e)}`),r=await Fn(n);return Ze("local.message.deleted",{messages:[r.messages[0]]}),_n.message(r.messages[0])};ki.optimistically=e=>{be().log("message/deleteMessage.optimistically",e);const t=Ie(["message","get",e]);if(!t)return;const n=Object.assign(Object.assign({},t.data),{isDeleted:!0,updatedAt:(new Date).toISOString()});return ke(["message","get",e],n,{cachedAt:-1}),Ze("local.message.deleted",{messages:[n]}),{data:_n.message(n),cachedAt:-1}};const Ti=async e=>{const t=be();t.log("message/softDeleteMessage",e),await t.http.delete(`/api/v5/messages/${encodeURIComponent(e)}`);const n=await Co(e);return Ze("local.message.deleted",{messages:[n.data]}),_n.message(n.data)};Ti.optimistically=e=>{be().log("message/softDeleteMessage.optimistically",e);const t=Ie(["message","get",e]);if(!t)return;const n=Object.assign(Object.assign({},t.data),{isDeleted:!0,updatedAt:(new Date).toISOString()});return ke(["message","get",e],n,{cachedAt:-1}),Ze("local.message.deleted",{messages:[n]}),{data:_n.message(n),cachedAt:-1}};const Oi=async e=>{const t=be();t.log("user/getReadUsers",e);const{page:n,messageId:r}=e,s=zt(e,["page","messageId"]),{data:a}=await t.http.get(`/api/v1/markers/messages/${r}/read-users`,{params:Object.assign(Object.assign({},s),{options:{token:Z(n,"afterbeforeraw")}})}),{paging:o,publicUserIds:i,userFeedMarkers:c}=a,l=zt(a,["paging","publicUserIds","userFeedMarkers"]),d=t.cache&&Date.now();if(t.cache){Kt(Object.assign(Object.assign({},l),{userFeedMarkers:Jt(c)}),{cachedAt:d});const e=["read-user","query",Object.assign(Object.assign({messageId:r},s),{options:Object.assign({},n)})];Se(e,{users:i,paging:o})}let u=[];i.length>0&&({data:u}=await Qa(i));return{data:u,cachedAt:d,prevPage:X(o.previous),nextPage:X(o.next)}};Oi.locally=e=>{var t;const n=be();if(n.log("user/getReadUsers.locally",e),!n.cache)return;const{page:r}=e,s=zt(e,["page"]),a=["read-user","query",Object.assign(Object.assign({},s),{options:Object.assign({},r)})],{data:o,cachedAt:i}=null!==(t=Ie(a))&&void 0!==t?t:{},c=null==o?void 0:o.users.map((e=>{var t;return null===(t=Ie(["user","get",e]))||void 0===t?void 0:t.data}));if(!c||c.some((e=>!e)))return;return{data:c,cachedAt:i,prevPage:X(null==o?void 0:o.paging.previous),nextPage:X(null==o?void 0:o.paging.next)}};const Ai=async e=>{const t=be();t.log("user/getDeliveredUsers",e);const{page:n,messageId:r}=e,s=zt(e,["page","messageId"]),{data:a}=await t.http.get(`/api/v1/markers/messages/${r}/delivered-users`,{params:Object.assign(Object.assign({},s),{options:{token:Z(n,"afterbeforeraw")}})}),{paging:o,publicUserIds:i,userFeedMarkers:c}=a,l=zt(a,["paging","publicUserIds","userFeedMarkers"]),d=t.cache&&Date.now();if(t.cache){Kt(Object.assign(Object.assign({},l),{userFeedMarkers:Jt(c)}),{cachedAt:d});const e=["delivered-user","query",Object.assign(Object.assign({messageId:r},s),{options:Object.assign({},n)})];Se(e,{users:i,paging:o})}let u=[];i.length>0&&({data:u}=await Qa(i));return{data:u,cachedAt:d,prevPage:X(o.previous),nextPage:X(o.next)}};Ai.locally=e=>{var t;const n=be();if(n.log("user/getDeliveredUsers.locally",e),!n.cache)return;const{page:r}=e,s=zt(e,["page"]),a=["delivered-user","query",Object.assign(Object.assign({},s),{options:Object.assign({},r)})],{data:o,cachedAt:i}=null!==(t=Ie(a))&&void 0!==t?t:{},c=null==o?void 0:o.users.map((e=>{var t;return null===(t=Ie(["user","get",e]))||void 0===t?void 0:t.data}));if(!c||c.some((e=>!e)))return;return{data:c,cachedAt:i,prevPage:X(null==o?void 0:o.paging.previous),nextPage:X(null==o?void 0:o.paging.next)}};const Ei=e=>{const t=be();return Ye(t,"onMessageFlagged","message.flagged",(async t=>{const n=await Fn(t);Kt(n),e(n.messages[0])}))},Mi=e=>{const t=be();return Ye(t,"onMessageUnflagged","message.unflagged",(async t=>{const n=await Fn(t);Kt(n),e(n.messages[0])}))},Ri=e=>{const t=be();return Ye(t,"onMessageFlagCleared","message.flagCleared",(async t=>{const n=await Fn(t);Kt(n),e(n.messages[0])}))},Pi=e=>{const t=be();return Ye(t,"onMessageReactionAdded","message.reactionAdded",(async t=>{const n=await Fn(t,"message.reactionAdded");Kt(n),e(n.messages[0])}))},ji=e=>{const t=be();return Ye(t,"onMessageReactionRemoved","message.reactionRemoved",(async t=>{const n=await Fn(t,"message.reactionRemoved");Kt(n),e(n.messages[0])}))},Ui=e=>{const t=be();return Ye(t,"message/onMessageFetched","local.message.fetched",(t=>{Kt(t),e(t.messages[0])}))};class xi extends Pa{constructor(e,t,n,r,s){super(e,t),this.notifyChange=n,this.preparePayload=r,this.paginationController=s}async saveToMainDB(e){const t=await this.preparePayload(e),n=be(),r=n.cache&&Date.now();n.cache&&Kt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,s;if(n)Se(this.cacheKey,{data:e.messages.map(de("message")),query:this.query});else{const n=null===(r=Ie(this.cacheKey))||void 0===r?void 0:r.data,a=null!==(s=null==n?void 0:n.data)&&void 0!==s?s:[];Se(this.cacheKey,Object.assign(Object.assign({},n),{data:"next"===t?[...new Set([...a,...e.messages.map(de("message"))])]:[...new Set([...e.messages.map(de("message")),...a])]}))}}reactor(e){return t=>{var n,r,s;if("onCreate"===e){const e=null===(n=Ie(this.cacheKey))||void 0===n?void 0:n.data,{referenceId:a}=t;if(!e)return;if(this.query.subChannelId!==(null==t?void 0:t.subChannelId)||!e)return;if(this.query.type&&this.query.type!==t.dataType)return;if(this.query.excludingTags&&(null===(r=this.query.excludingTags)||void 0===r?void 0:r.some((e=>{var n;return null===(n=t.tags)||void 0===n?void 0:n.includes(e)}))))return;if(!!this.query.hasFlags!=!!t.flagCount)return;if(this.query.parentId&&this.query.parentId!==t.parentId)return;if(this.query.hasOwnProperty("includeDeleted")&&!this.query.includeDeleted&&t.isDeleted)return;if(this.query.includingTags&&!(null===(s=this.query.includingTags)||void 0===s?void 0:s.some((e=>{var n;return null===(n=t.tags)||void 0===n?void 0:n.includes(e)}))))return;this.query.sortBy&&"segmentDesc"!==this.query.sortBy||this.paginationController.getPrevToken()||(e.data=[...new Set([null!=a?a:t.messageId,...e.data])]),"segmentAsc"!==this.query.sortBy||this.paginationController.getNextToken()||(e.data=[...new Set([...e.data,null!=a?a:t.messageId])]),Se(this.cacheKey,e)}this.notifyChange({origin:"event",loading:!1})}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class Di extends Ma{async getRequest(e,t){const n=Kn(e),{data:r}=await this.http.get("/api/v5/messages",{params:Object.assign(Object.assign({},n),{options:t?{token:t}:Object.assign({},n.options)})});return r}}class Ni extends Da{constructor(e,t){const n=w.default(e),r=["message","collection",n];super(new Di(e),n,r,t),this.query=e,this.queryStreamController=new xi(this.query,this.cacheKey,this.notifyChange.bind(this),Fn,this.paginationController),this.callback=t.bind(this),this.loadPage({initial:!0})}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:Ns,action:"onCreate"},{fn:Bs,action:"onCreate"},{fn:mi,action:"onDelete"},{fn:fi,action:"onUpdate"},{fn:Ei,action:"onFlagged"},{fn:Mi,action:"onUnflagged"},{fn:Ri,action:"onFlagCleared"},{fn:Pi,action:"onReactionAdded"},{fn:ji,action:"onReactionRemoved"},{fn:ao(aa,"contentId","message"),action:"onUpdate"},{fn:ao(oa,"contentId","message"),action:"onUpdate"}])}notifyChange({origin:e,loading:t,error:n}){var r,s;const a=null===(r=Ie(this.cacheKey))||void 0===r?void 0:r.data;if(!a)return;const o=this.applyFilter(null!==(s=a.data.map((e=>(e=>{var t,n;const r=null===(t=Ie(["message","get",e]))||void 0===t?void 0:t.data;if(r)return r;const s=Ce(["message","get"]);return null===(n=null==s?void 0:s.find((({data:t})=>t.messageId===e)))||void 0===n?void 0:n.data})(e))).filter(Boolean).map((e=>_n.message(e))))&&void 0!==s?s:[]);(this.shouldNotify(o)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),onPrevPage:()=>this.loadPage({direction:"prev"}),data:o,hasNextPage:!!this.paginationController.getNextToken(),hasPrevPage:!!this.paginationController.getPrevToken(),loading:t,error:n})}applyFilter(e){let t=e;return this.query.includeDeleted||(t=Oe(t,"isDeleted",!1)),t=t.sort(((e,t)=>"segmentAsc"===this.query.sortBy?e.channelSegment-t.channelSegment:"segmentDesc"===this.query.sortBy?t.channelSegment-e.channelSegment:0)),t}setup(){var e;(null===(e=Ie(this.cacheKey))||void 0===e?void 0:e.data)||Se(this.cacheKey,{data:[],query:this.query})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}}var Bi=Object.freeze({__proto__:null,createMessage:async e=>{const t=be();t.log("message/createMessage",e);const n=(e=>{var t,n;const r=be();if(!r.cache)return;Ii=e.referenceId||Ci();const s=Object.assign({messageId:Ii,uniqueId:Ii},e);r.log("message/createMessage.optimistically",s);const a=Ie(["subChannel","get",e.subChannelId]);if(a&&(ke(["subChannel","get",e.subChannelId],Object.assign(Object.assign({},a.data),{messageCount:a.data.messageCount+1})),a.data.channelId===a.data.subChannelId)){const e=Ie(["channel","get",a.data.channelId]);(null==e?void 0:e.data)&&ke(["channel","get",a.data.channelId],Object.assign(Object.assign({},e.data),{messageCount:(null!==(t=e.data.messageCount)&&void 0!==t?t:0)+1}))}const o=(new Date).toISOString(),i=Object.assign({creatorId:r.userId,creatorPrivateId:ze()._id,channelSegment:(null!==(n=null==a?void 0:a.data.messageCount)&&void 0!==n?n:0)+1,childrenNumber:0,createdAt:o,updatedAt:o,syncState:"syncing",isDeleted:!1},s);return Se(["message","get",i.messageId],i,{cachedAt:-5}),Ze("local.message.created",{messages:[i]}),i})(e),r=e.referenceId||Ii||Ci();Ii=void 0;try{const{data:n}=await t.http.post("/api/v5/messages",Object.assign(Object.assign({},Ln(e)),{referenceId:r})),s=await Fn(n),{messages:a}=s,o=t.cache&&Date.now();return t.cache&&Kt(s,{cachedAt:o}),Ze("local.message.created",{messages:[Object.assign(Object.assign({},a[0]),{syncState:"synced"})]}),{data:_n.message(a[0]),cachedAt:o}}catch(e){throw Ze("local.message.created",{messages:[Object.assign(Object.assign({},n),{syncState:"error"})]}),e}},updateMessage:Si,editMessage:_i,deleteMessage:ki,softDeleteMessage:Ti,markAsDelivered:async(e,t)=>{const n=be();n.log("message/markAsDelivered",e,t);const{data:r}=await n.http.put(`/api/v1/markers/message-feeds/${e}/mark-delivering`,{messageId:t}),{userMarkers:s,userEntityMarkers:a,userFeedMarkers:o}=r,i=zt(r,["userMarkers","userEntityMarkers","userFeedMarkers"]),c=n.cache&&Date.now();return n.cache&&Kt(Object.assign({userMarkers:s,userEntityMarkers:Wt(a),userFeedMarkers:Jt(o)},i),{cachedAt:c}),!0},getReadUsers:Oi,getDeliveredUsers:Ai,flagMessage:async(t,n)=>{const r=be();r.log("message/flag",t);const s=n&&Object.entries(e.ContentFlagReasonEnum).some((([t,r])=>t!==e.ContentFlagReasonEnum.Others&&r===n)),a={reason:s?n:e.ContentFlagReasonEnum.Others,detail:s?"":n},{data:o}=await r.http.post(`/api/v5/messages/${encodeURIComponent(t)}/flags`,a);if(r.cache){const e=await Fn(o);Kt(e)}return Ze("message.flagged",o),!!o},unflagMessage:async e=>{const t=be();t.log("message/unflag",e);const{data:n}=await t.http.delete(`/api/v5/messages/${encodeURIComponent(e)}/flags`);if(t.cache){const e=await Fn(n);Kt(e)}return Ze("message.unflagged",n),!!n},isMessageFlaggedByMe:async e=>{const t=be();t.log("message/isMessageFlaggedByMe",e);const{data:n}=await t.http.get(`/api/v5/messages/${encodeURIComponent(e)}/flags`);return n.result},onMessageCreatedMqtt:Ns,onMessageCreatedLocal:Bs,onMessageUpdated:fi,onMessageDeleted:mi,onMessageFlagged:Ei,onMessageUnflagged:Mi,onMessageFlagCleared:Ri,onMessageReactionAdded:Pi,onMessageReactionRemoved:ji,onMessageFetched:Ui,getMessage:(e,t)=>$a(e,(e=>{const{data:n}=e;t(Object.assign(Object.assign({},e),{data:n?_n.message(e.data):n}))}),"messageId",Co,[Ui,fi,mi,Ei,Mi,Ri,Pi,ji,ao(aa,"contentId","message"),ao(oa,"contentId","message")]),getMessages:(e,t,n)=>{const{log:r,cache:s}=be();s||console.log(N);const a=Date.now();r(`getMessages(tmpid: ${a}) > listen`);const o=new Ni(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>{Te(c)})),()=>{r(`getMessages(tmpid: ${a}) > dispose`),i.forEach((e=>e()))}},convertFromRaw:Bn,prepareMessagePayload:Fn,convertParams:Ln,convertQueryParams:Kn});const qi=e=>{const t=be();return Ye(t,"subChannelMarker/onSubChannelUnreadUpdatedLocal","local.subChannelUnread.updated",(t=>{e(t)}))};class Fi extends Ma{async getRequest(e,t){var n;const{limit:r=x}=e,s=null!==(n=function(e){var{excludeDefaultSubChannel:t}=e,n=zt(e,["excludeDefaultSubChannel"]);const r=Object.assign({},n);return void 0!==t&&(r.excludeDefaultMessageFeed=t),r}(zt(e,["limit"])))&&void 0!==n?n:{},{channelId:a,includeDeleted:o}=s,i=zt(s,["channelId","includeDeleted"]),c=t?{token:t}:{limit:r},{data:l}=await this.http.get(`/api/v5/message-feeds/channel/${a}`,{params:Object.assign(Object.assign({},i),{isDeleted:jn(o),options:c})});return l}}class Li extends Pa{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=be(),r=n.cache&&Date.now();n.cache&&Kt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,s;if(n)Se(this.cacheKey,{data:e.messageFeeds.map((({messageFeedId:e})=>e))});else{const t=null===(r=Ie(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];Se(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.messageFeeds.map((({messageFeedId:e})=>e))])]}))}}reactor(e){return t=>{var n;const r=null===(n=Ie(this.cacheKey))||void 0===n?void 0:n.data;if(r){if(!Array.isArray(t)){if(this.query.channelId!==t.channelId)return;"onCreate"===e&&(r.data=[...new Set([t.subChannelId,...r.data])]),Se(this.cacheKey,r)}this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class Ki extends Da{constructor(e,t){const n=w.default(e),r=["subChannel","collection",n];super(new Fi(e),n,r,t),this.query=e,this.queryStreamController=new Li(this.query,this.cacheKey,this.notifyChange.bind(this),Qn),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Ie(this.cacheKey))||void 0===e?void 0:e.data)||Se(this.cacheKey,{data:[]})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:wi,action:"onCreate"},{fn:qs,action:"onCreate"},{fn:Fs,action:"onDelete"},{fn:e=>gi((async t=>{if(!this.isRelatedCollection(t.subChannelId))return;const n=be();if("no-message-preview"!==await n.getMessagePreviewSetting(!1)){const e=Tn(t.subChannelId);(null==e?void 0:e.subChannelId)===t.subChannelId&&Hn(t.updatedAt)>Hn(e.subChannelUpdatedAt)&&Se(["messagePreviewSubChannel","get",t.subChannelId],Object.assign(Object.assign({},e),{subChannelName:t.displayName,subChannelUpdatedAt:t.updatedAt}))}e(t)})),action:"onUpdate"},{fn:ao((e=>Ns((async t=>{this.isRelatedCollection(t.subChannelId)&&(await Jn(t),e(t))}))),"subChannelId","subChannel"),action:"onUpdate"},{fn:ao((e=>Bs((async t=>{this.isRelatedCollection(t.subChannelId)&&(await Jn(t),e(t))}))),"subChannelId","subChannel"),action:"onUpdate"},{fn:e=>ra((t=>{var n;const r=null!==(n=t.map((({feedId:e})=>Ie(["subChannel","get",e]))).filter(Boolean).map((({data:e})=>e)))&&void 0!==n?n:[];0!==r.length&&e(r)})),action:"onUpdate"},{fn:ao(na,"feedId","subChannel"),action:"onUpdate"},{fn:ao((e=>fi((async t=>{var n;const r=be();if("no-message-preview"===await r.getMessagePreviewSetting(!1))return;const s=null===(n=Ie(this.cacheKey))||void 0===n?void 0:n.data;s&&s.data.includes(t.subChannelId)&&(Gn(t),e(t))}))),"subChannelId","subChannel"),action:"onUpdate"},{fn:ao((e=>mi((async t=>{const n=be(),r=await n.getMessagePreviewSetting(!1);"no-message-preview"!==r&&this.isRelatedCollection(t.subChannelId)&&("message-preview-not-include-deleted"===r?await Vn(t.subChannelId):await Gn(t),e(t))}))),"subChannelId","subChannel"),action:"onUpdate"},{fn:ao(qi,"subChannelId","subChannel"),action:"onUpdate"}])}notifyChange({origin:e,loading:t,error:n}){var r,s;const a=null===(r=Ie(this.cacheKey))||void 0===r?void 0:r.data;if(!a)return;const o=this.applyFilter(null!==(s=a.data.map((e=>Ie(["subChannel","get",e]))).filter(Boolean).map((({data:e})=>e)).map(On))&&void 0!==s?s:[]);(this.shouldNotify(o)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:o,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=e;return this.query.includeDeleted||(t=Oe(e,"isDeleted",!1)),t.sort(Ke),t}isRelatedCollection(e){var t;const n=null===(t=Ie(this.cacheKey))||void 0===t?void 0:t.data;return n&&n.data.includes(e)}}const $i={},zi=async e=>{const t=await(async e=>{const t=Vn.locally(e);if(t)return t.data.channelId;const{data:n}=await Vn(e);return n.channelId})(e),n=ot({channelId:t,subChannelId:e});$i[e]=ht(n)};var Qi=Object.freeze({__proto__:null,getSubChannelByIds:_r,createSubChannel:async e=>{const t=be();t.log("user/createSubChannel",e);const n=await t.http.post("/api/v5/message-feeds",{channelId:e.channelId,name:e.displayName}),r=await Qn(n.data),s=t.cache&&Date.now();return t.cache&&Kt(r,{cachedAt:s}),Ze("message-feed.created",n.data),{data:r.messageFeeds[0],cachedAt:s}},updateSubChannel:async(e,t)=>{const n=be();n.log("channel/updateSubChannel",e,t);const r=await n.http.put(`/api/v5/message-feeds/${encodeURIComponent(e)}`,{name:t.displayName}),s=await Qn(r.data),a=n.cache&&Date.now();return n.cache&&Kt(s,{cachedAt:a}),Ze("message-feed.updated",r.data),{data:s.messageFeeds[0],cachedAt:a}},deleteSubChannel:bi,hardDeleteSubChannel:async e=>{be().log("channel/hardDeleteSubChannel",e);return await bi(e,!0)},softDeleteSubChannel:async e=>{be().log("channel/softDeleteSubChannel",e);return await bi(e,!1)},onSubChannelCreated:qs,onSubChannelUpdated:gi,onSubChannelDeleted:Fs,getSubChannel:(e,t)=>{const n=be();let r;return $a(e,(e=>{if(!e.data)return t(e);const n=Object.assign(Object.assign({},e),{data:On(e.data)}),s=zt(n,["origin"]);return ln(r,s)?void 0:(r=s,t(n))}),"subChannelId",Vn,[wi,t=>gi((async r=>{"no-message-preview"!==await n.getMessagePreviewSetting(!1)&&(Xn(r),r.subChannelId===e&&t(r))})),Fs,ao(na,"feedId","subChannel"),t=>ra((n=>{var r;if(!n.find((({feedId:t})=>t===e)))return;const s=null===(r=Ie(["subChannel","get",e]))||void 0===r?void 0:r.data;s&&t(s)})),ao((t=>Ns((async n=>{n.subChannelId===e&&(await Jn(n),t(n))}))),"subChannelId","subChannel"),ao((t=>Bs((async n=>{n.subChannelId===e&&(await Jn(n),t(n))}))),"subChannelId","subChannel"),ao((t=>fi((async r=>{"no-message-preview"!==await n.getMessagePreviewSetting(!1)&&r.subChannelId===e&&(Gn(r),t(r))}))),"subChannelId","subChannel"),ao((t=>mi((async r=>{const s=await n.getMessagePreviewSetting(!1);"no-message-preview"!==s&&r.subChannelId===e&&("message-preview-include-deleted"===s&&await Gn(r),"message-preview-not-include-deleted"===s&&await Vn(r.subChannelId),t(r))}))),"subChannelId","subChannel"),ao(qi,"subChannelId","subChannel")],{forceDispatch:!0})},getSubChannels:(e,t,n)=>{const{log:r,cache:s}=be(),a=Date.now();r(`getSubChannels(tmpid: ${a}) > listen`),s||console.log(N);const o=new Ki(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>{Te(c)})),()=>{r(`getSubChannels(tmpid: ${a}) > dispose`),i.forEach((e=>e()))}},markReadEngineOnLoginHandler:Sr,startMessageReceiptSync:async e=>(await zi(e),!0),stopMessageReceiptSync:e=>($i[e]&&$i[e](),!0)});const Vi=e=>{const t=be();return Ye(t,"channelMarker/onChannelUnreadInfoUpdatedLocal","local.channelUnreadInfo.updated",(t=>{e(t)}))},Hi=e=>{const t=be();return Ye(t,"channel/onChannelUnreadUpdatedLocal","local.channelUnread.updated",(t=>{e(t)}))};class Wi extends Ma{async getRequest(e,t){const{limit:n=x,displayName:r,membership:s}=e,a=zt(e,["limit","displayName","membership"]),o=t?{token:t}:{limit:n},{data:i}=await this.http.get("/api/v3/channels",{params:Object.assign(Object.assign({},a),{keyword:r,filter:s,options:o})});return i}}class Ji extends xa{async getRequest(e){const{data:t}=await this.http.get("/api/v3/channels/list",{params:Object.assign({},e)});return t}}class Gi extends Pa{constructor(e,t,n,r,s){super(e,t),this.notifyChange=n,this.preparePayload=r,this.paginationController=s}async saveToMainDB(e){const t=await this.preparePayload(e),n=be(),r=n.cache&&Date.now();n.cache&&Kt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,s;if(n)Se(this.cacheKey,{data:e.channels.map(de("channel"))});else{const t=null===(r=Ie(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];Se(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.channels.map(de("channel"))])]}))}}reactor(e){return t=>{var n;const r=null===(n=Ie(this.cacheKey))||void 0===n?void 0:n.data;if(r){if(this.paginationController instanceof Ji)return this.notifyChange({origin:"event",loading:!1});["onCreate","onJoin","onResolveChannel"].includes(e)&&(Array.isArray(t)?r.data=[...new Set([...t.map(de("channel")),...r.data])]:r.data=[...new Set([t.channelInternalId,...r.data])]),Se(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const Yi=e=>{const t=be();if(t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()){Jr().resolve(e.channelId,"userMessageFeedMarker")}},Zi=e=>{const t=be();return Ye(t,"onChannelResolved","local.channel.resolved",(async t=>{e(t)}))};class Xi extends Da{constructor(e,t){const n=w.default(e),r=["channel","collection",n],s=Xi.getPaginationController(e);super(s,n,r,t),this.query=e,this.queryStreamController=new Gi(this.query,this.cacheKey,this.notifyChange.bind(this),(async e=>{try{const t=be();t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&await ir(e)}catch(e){console.error("Error while preparing unread count info",e)}return ar(e)}),s),this.paginationController=s,this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Ie(this.cacheKey))||void 0===e?void 0:e.data)||Se(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE(this.getSubscriptions())}notifyChange({origin:e,loading:t,error:n}){var r,s;const a=null===(r=Ie(this.cacheKey))||void 0===r?void 0:r.data;if(!a)return;let o=null!==(s=a.data.map((e=>Ie(["channel","get",e]))).filter(Boolean).map((({data:e})=>e)).map(hr))&&void 0!==s?s:[];this.paginationController instanceof Wi&&(o=this.applyFilter(o)),(this.shouldNotify(o)||"event"!==e)&&this.callback({onNextPage:this.paginationController instanceof Wi?()=>this.loadPage({direction:"next"}):void 0,data:o,hasNextPage:this.paginationController instanceof Wi&&!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){const{userId:t}=be();let n=e;switch(n=Oe(n,"isDeleted",this.query.isDeleted),n=Ae(n,"displayName",this.query.displayName),this.query.types&&(n=n.filter((e=>{var t;return null===(t=this.query.types)||void 0===t?void 0:t.includes(e.type)}))),this.query.tags&&(n=n.filter((e=>{var t;return null===(t=e.tags)||void 0===t?void 0:t.some((e=>{var t;return null===(t=this.query.tags)||void 0===t?void 0:t.includes(e)}))}))),this.query.excludeTags&&(n=n.filter((e=>{var t;return!(null===(t=e.tags)||void 0===t?void 0:t.some((e=>{var t;return null===(t=this.query.excludeTags)||void 0===t?void 0:t.includes(e)})))}))),this.query.membership&&t&&(n=Me(n,this.query.membership,t)),this.query.sortBy){case"firstCreated":n=n.sort(Ne);break;case"lastCreated":n=n.sort(qe);break;case"displayName":n=n.map((e=>e.displayName?e:Object.assign(Object.assign({},e),{displayName:""}))).sort(xe);break;default:n=n.sort(Ke)}return n}shouldAbort(e){var t,n;const r=null===(t=Ie(this.cacheKey))||void 0===t?void 0:t.data;if(!r)return!0;return!(null===(n=null==r?void 0:r.data)||void 0===n?void 0:n.find((t=>t===e)))}static getMessagePreviewSetting(){return be().getMessagePreviewSetting(!1)}static getPaginationController(e){return e.channelIds&&e.channelIds.length>0?new Ji(e):new Wi(e)}getSubscriptions(){const e=[{fn:ao((e=>Ns((t=>{var n,r;const s=Jr();(null===(n=Ie(["subChannelUnreadInfo","get",t.subChannelId]))||void 0===n?void 0:n.data)||s.resolve(t.subChannelId,"userMessageFeedMarker");const a=null===(r=Ie(["channel","get",t.channelId]))||void 0===r?void 0:r.data;a?(yi(a,{lastActivity:t.createdAt}),e(t)):s.resolve(t.channelId,"channel")}))),"channelId","channel"),action:"onUpdate"},{fn:ao((e=>Bs((t=>{var n;const r=null===(n=Ie(["channel","get",t.channelId]))||void 0===n?void 0:n.data;r&&(yi(r,{lastActivity:t.createdAt}),e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:qr,action:"onDelete"},{fn:hs,action:"onUpdate"},{fn:Cs,action:"onMute"},{fn:e=>ms((t=>{Yi(t),e(t)})),action:"onJoin"},{fn:e=>vs(((t,n)=>{var r,s;const{userId:a}=be();if("member"===this.query.membership&&a===n.userId){const e=null===(r=Ie(this.cacheKey))||void 0===r?void 0:r.data;Se(this.cacheKey,Object.assign(Object.assign({},e),{data:null!==(s=null==e?void 0:e.data.filter((e=>e!==t.channelId)))&&void 0!==s?s:[]}))}return e(t)})),action:"onLeft"},{fn:_s,action:"onMemberAdded"},{fn:Os,action:"onMemberRemoved"},{fn:ao(ta,"entityId","channel"),action:"onUpdate"},{fn:ao(vi,"entityId","channel"),action:"onUpdate"},{fn:ao((e=>Ns((async t=>{var n;if("no-message-preview"===await Xi.getMessagePreviewSetting())return;if(Yn(t),this.shouldAbort(t.channelId))return;const r=null===(n=Ie(["channel","get",t.channelId]))||void 0===n?void 0:n.data;r&&(yi(r,{messagePreviewId:t.messageId}),e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:ao((e=>Bs((async t=>{var n;if("no-message-preview"===await Xi.getMessagePreviewSetting())return;if(Yn(t),this.shouldAbort(t.channelId))return;const r=null===(n=Ie(["channel","get",t.channelId]))||void 0===n?void 0:n.data;r&&(yi(r,{messagePreviewId:t.messageId}),e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:ao((e=>fi((async t=>{"no-message-preview"!==await Xi.getMessagePreviewSetting()&&(Zn(t),this.shouldAbort(t.channelId)||e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:ao((e=>mi((async t=>{const n=await Xi.getMessagePreviewSetting();"no-message-preview"!==n&&("message-preview-include-deleted"===n&&await Zn(t),this.shouldAbort(t.channelId)||("message-preview-not-include-deleted"===n&&await pi(t.channelId),e(t)))}))),"channelId","channel"),action:"onUpdate"},{fn:ao((e=>Fs((async t=>{var n;const r=null===(n=Ie(this.cacheKey))||void 0===n?void 0:n.data;if(!r)return;r.data.find((e=>{const n=Gt(e);return(null==n?void 0:n.subChannelId)===t.subChannelId}))&&(await pi(t.channelId),e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:ao((e=>gi((async t=>{var n;if("no-message-preview"===await Xi.getMessagePreviewSetting())return;(null===(n=Ie(this.cacheKey))||void 0===n?void 0:n.data)&&(await Xn(t),this.shouldAbort(t.channelId)||e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:ao(qs,"channelId","channel"),action:"onUpdate"},{fn:Zi,action:"onResolveChannel"},{fn:e=>(e=>{const t=be();return Ye(t,"userMessageFeedMarker/onUserMessageFeedMarkerResolved","local.userMessageFeedMarkers.resolved",(t=>{e(t)}))})((async t=>{if(t.feedMarkers){const n=t.feedMarkers.map((e=>{var t;return null===(t=Ie(["channel","get",e.entityId]))||void 0===t?void 0:t.data})).filter(Boolean);e(n)}})),action:"OnResolveUnread"},{fn:ao(Vi,"channelId","channel"),action:"onUpdate"},{fn:ao((e=>Hi((t=>{t.forEach(e)}))),"channelId","channel"),action:"onUpdate"}];return this.paginationController instanceof Ma?[...e,{fn:e=>ls((t=>{Yi(t),e(t)})),action:"onCreate"}]:e}}const ec=()=>{var e;const t=be();t.log("channel/getTotalChannelsUnread.locally");const n=(null===(e=Ce(["channelUnread","get"]))||void 0===e?void 0:e.filter((({data:e})=>!e.isDeleted)))||[];return{data:(null==n?void 0:n.reduce(((e,{data:t})=>(e.unreadCount+=t.unreadCount,e.isMentioned=e.isMentioned||t.isMentioned,e)),{unreadCount:0,isMentioned:!1}))||{unreadCount:0,isMentioned:!1},cachedAt:t.cache&&Date.now()}};class tc extends Ma{async getRequest(e,t){const{limit:n=x,includeDeleted:r}=e,s=zt(e,["limit","includeDeleted"]),a=t?{token:t}:{limit:n},o=!1!==r&&void 0,{data:i}=await this.http.get(`/api/v4/channels/${encodeURIComponent(s.channelId)}/users`,{params:Object.assign(Object.assign({},s),{options:a,isDeleted:o})});return i}}class nc extends Pa{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=be(),r=n.cache&&Date.now();n.cache&&Kt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,s;if(n)Se(this.cacheKey,{data:e.channelUsers.map((({channelId:e,userId:t})=>de("channelUsers")({channelId:e,userId:t})))});else{const t=null===(r=Ie(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];Se(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.channelUsers.map((({channelId:e,userId:t})=>de("channelUsers")({channelId:e,userId:t})))])]}))}}reactor(e){return(e,t)=>{var n;if(this.query.channelId!==t.channelId)return;const r=null===(n=Ie(this.cacheKey))||void 0===n?void 0:n.data;if(!r)return;const s=de("channelUsers")({channelId:this.query.channelId,userId:t.userId});"none"===t.membership?r.data=r.data.filter((e=>e!==s)):r.data.includes(s)||(r.data=[s,...r.data]),Se(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1})}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class rc extends Da{constructor(e,t){const n=w.default(e),r=["channelUsers","collection",n];super(new tc(e),n,r,t),this.query=e,this.queryStreamController=new nc(this.query,this.cacheKey,this.notifyChange.bind(this),ar),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Ie(this.cacheKey))||void 0===e?void 0:e.data)||Se(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:ms,action:"onJoin"},{fn:vs,action:"onLeft"},{fn:_s,action:"onMemberAdded"},{fn:Os,action:"onMemberRemoved"},{fn:Kr,action:"onChannelMemberBanned"},{fn:Ms,action:"onChannelMemberUnbanned"},{fn:js,action:"onChannelMemberRoleAdded"},{fn:Ds,action:"onChannelMemberRoleRemoved"},{fn:(e=this.query.channelId,t=>{const n=be();return Ye(n,"user.deleted","user.deleted",(n=>{var r,s;const a=$r(n);if(0===a.users.length)return;const o=a.users[0];Kt(a);const i=de("channelUsers")({channelId:e,userId:o.userId}),c=null===(r=Ie(["channelUsers","get",i]))||void 0===r?void 0:r.data;ke(["channelUsers","get",i],Object.assign(Object.assign({},c),{user:o}));const l=null===(s=Ie(["channel","get",e]))||void 0===s?void 0:s.data;l&&t(l,c)}))}),action:"onChannelMemberChanged"}]);var e}notifyChange({origin:e,loading:t,error:n}){var r,s;const a=null===(r=Ie(this.cacheKey))||void 0===r?void 0:r.data;if(!a)return;const o=this.applyFilter(null!==(s=a.data.map((e=>Ie(["channelUsers","get",e]))).filter(Boolean).map((({data:e})=>e)))&&void 0!==s?s:[]);(this.shouldNotify(o)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:o,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=Ee(e,"roles",this.query.roles);this.query.memberships&&(t=t.filter((e=>{var t,n;return!(!(null===(t=this.query.memberships)||void 0===t?void 0:t.includes("muted"))||!e.isMuted)||"none"!==e.membership&&(null===(n=this.query.memberships)||void 0===n?void 0:n.includes(e.membership))}))),!1===this.query.includeDeleted&&(t=t.filter((e=>{var t;return!0!==(null===(t=e.user)||void 0===t?void 0:t.isDeleted)})));const n=this.query.sortBy?this.query.sortBy:"lastCreated";return t=t.sort("lastCreated"===n?qe:Ne),t}}const sc=(e,t,n)=>{const{log:r,cache:s}=be();s||console.log(N);const a=Date.now();r(`getMembers(tmpid: ${a}) > listen`);const o=new rc(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>{Te(c)})),()=>{r(`getMembers(tmpid: ${a}) > dispose`),i.forEach((e=>e()))}};var ac=Object.freeze({__proto__:null,addMembers:async(e,t)=>{const n=be();n.log("channel/addMembers",e,t);const{data:r}=await n.http.post(`/api/v3/channels/${encodeURIComponent(e)}/users`,{channelId:e,userIds:t});t.forEach((e=>Ze("channel.membersAdded",Object.assign(Object.assign({},r),{channelUsers:r.channelUsers.filter((t=>t.userId===e))}))));const s=await ar(r);n.cache&&Kt(s);const{channelUsers:a}=s;return!!a.find((t=>t.channelId===e&&"member"===t.membership))},removeMembers:async(e,t)=>{const n=be();n.log("channel/removeMembers",e,t);const{data:r}=await n.http.delete(`/api/v3/channels/${encodeURIComponent(e)}/users`,{data:{channelId:e,userIds:t}});t.forEach((e=>Ze("channel.membersRemoved",Object.assign(Object.assign({},r),{channelUsers:r.channelUsers.filter((t=>t.userId===e))}))));const s=await ar(r);n.cache&&Kt(s);const{channelUsers:a}=s;return!!a.find((t=>t.channelId===e&&"member"!==t.membership))},applyFilter:(e,t)=>{let n=Ee(e,"roles",t.roles);t.memberships&&(n=n.filter((e=>!(!t.memberships.includes("muted")||!e.isMuted)||t.memberships.includes(e.membership))));const r=t.sortBy?t.sortBy:"lastCreated";return n=n.sort("lastCreated"===r?qe:Ne),n},getMembers:sc,searchMembers:(e,t,n)=>sc(e,t)});var oc=Object.freeze({__proto__:null,addRole:async(e,t,n)=>{const r=be();r.log("channel/addRole",e,t,n);const{data:s}=await r.http.post(`/api/v3/channels/${encodeURIComponent(e)}/users/roles`,{channelId:e,role:t,userIds:n}),a=await ar(s);r.cache&&Kt(a),Ze("local.channel-moderator.role-added",a);const{channelUsers:o}=a;return!!o.find((n=>n.channelId===e&&n.roles.includes(t)))},removeRole:async(e,t,n)=>{const r=be();r.log("channel/removeRole",e,t,n);const{data:s}=await r.http.delete(`/api/v3/channels/${encodeURIComponent(e)}/users/roles`,{data:{channelId:e,role:t,userIds:n}}),a=await ar(s);r.cache&&Kt(a),Ze("local.channel-moderator.role-removed",a);const{channelUsers:o}=a;return!!o.find((n=>n.channelId===e&&!n.roles.includes(t)))},banMembers:async(e,t)=>{const n=be();n.log("channel/banMembers",{userIds:t,channelId:e});const{data:r}=await n.http.put(`/api/v3/channels/${e}/users/ban`,{userIds:t}),s=await ar(r),{channelUsers:a}=s,o=n.cache&&Date.now();return n.cache&&Kt(s,{cachedAt:o}),{data:null==a?void 0:a.filter((e=>"banned"===e.membership)),cachedAt:o}},unbanMembers:async(e,t)=>{const n=be();n.log("channel/unbanMembers",{userIds:t,channelId:e});const{data:r}=await n.http.put(`/api/v3/channels/${encodeURIComponent(e)}/users/unban`,{userIds:t}),s=await ar(r),a=n.cache&&Date.now();n.cache&&Kt(s,{cachedAt:a});const{channelUsers:o}=s;return{data:null==o?void 0:o.filter((e=>"member"===e.membership)),cachedAt:a}},muteMembers:async(e,t,n=-1)=>{const r=be();r.log("channel/muteMembers",{userIds:t,channelId:e,mutePeriod:n});const{data:s}=await r.http.put(`/api/v2/channel/${e}/users/mute`,{userIds:t,mutePeriod:-1===n?n:1e3*n}),{success:a}=s;return a},unmuteMembers:async(e,t)=>{const n=be();n.log("channel/unmuteMembers",{userIds:t,channelId:e});const{data:r}=await n.http.put(`/api/v2/channel/${encodeURIComponent(e)}/users/mute`,{userIds:t,mutePeriod:0}),{success:s}=r;return s}}),ic=Object.freeze({__proto__:null,Membership:ac,Moderation:oc,getChannelByIds:pr,createChannel:async e=>{const t=be();let n;if(t.log("user/createChannel",e),"conversation"===(null==e?void 0:e.type))n=await t.http.post("/api/v3/channels/conversation",Object.assign(Object.assign({},e),{isDistinct:!0}));else{const{isPublic:r}=e,s=zt(e,["isPublic"]);n=await t.http.post("/api/v3/channels",Object.assign(Object.assign({},s),{isPublic:"community"===(null==e?void 0:e.type)?r:void 0}))}const r=await ar(n.data),s=t.cache&&Date.now();t.cache&&Kt(r,{cachedAt:s});const{channels:a}=r;return{data:ur(a[0]),cachedAt:s}},updateChannel:async(e,t)=>{const n=be();n.log("channel/updateChannel",e,t);const{data:r}=await n.http.put(`/api/v3/channels/${encodeURIComponent(e)}`,t),s=await ar(r),a=n.cache&&Date.now();n.cache&&Kt(s,{cachedAt:a});const{channels:o}=s;return{data:ur(o.find((t=>t.channelId===e))),cachedAt:a}},deleteChannel:async e=>{const t=be();t.log("channel/deleteChannel",e),await t.http.delete(`/api/v3/channels/${encodeURIComponent(e)}`);const n=await pi(e);return ur(n.data)},joinChannel:async e=>{const t=be();t.log("channel/joinChannel",e);const{data:n}=await t.http.post(`/api/v3/channels/${encodeURIComponent(e)}/join`),r=await ar(n);t.cache&&Kt(r);const{channelUsers:s}=r;return!!s.find((t=>t.channelId===e&&"member"===t.membership))},leaveChannel:async e=>{const t=be();t.log("channel/leaveChannel",e);const{data:n}=await t.http.delete(`/api/v3/channels/${encodeURIComponent(e)}/leave`),r=await ar(n);t.cache&&Kt(r);const{channelUsers:s}=r;return!!s.find((t=>t.channelId===e&&"member"!==t.membership))},muteChannel:async(e,t=-1)=>{const n=be();if(n.log("channel/muteChannel",e),-1!==t&&t<0)throw new pe("Mute Period can only be positive numbers or -1(mute forever)",800110,"error");const{data:r}=await n.http.put(`/api/v2/channel/${encodeURIComponent(e)}/mute`,{mutePeriod:t}),{success:s}=r;return s},unmuteChannel:async e=>{const t=be();t.log("channel/unmuteChannel",e);const{data:n}=await t.http.put(`/api/v2/channel/${encodeURIComponent(e)}/mute`,{mutePeriod:0}),{success:r}=n;return r},onChannelCreated:ls,onChannelUpdated:hs,onChannelDeleted:qr,onChannelJoined:ms,onChannelLeft:vs,onChannelMuted:Cs,onChannelMemberAdded:_s,onChannelMemberRemoved:Os,onChannelMemberBanned:Kr,onChannelMemberUnbanned:Ms,onChannelMemberRoleAdded:js,onChannelMemberRoleRemoved:Ds,getChannel:(e,t)=>{const n=be();let r;return $a(e,(async e=>{if(!e.data)return t(e);const n=Object.assign(Object.assign({},e),{data:hr(e.data)}),s=zt(n,["origin"]);return ln(r,s)?void 0:(r=s,t(n))}),"channelId",pi,[hs,qr,ms,vs,_s,Os,Kr,Ms,Cs,ao(ta,"entityId","channel"),ao(vi,"entityId","channel"),ao((t=>Ns((async r=>{await(async r=>{var s;if("no-message-preview"===await n.getMessagePreviewSetting(!1))return;if(await Yn(r),r.channelId!==e)return;const a=null===(s=Ie(["channel","get",e]))||void 0===s?void 0:s.data;a&&(yi(a,{messagePreviewId:r.messageId}),t(r))})(r),t(r)}))),"channelId","channel"),ao((t=>Bs((async r=>{var s;if("no-message-preview"===await n.getMessagePreviewSetting(!1))return;if(await Yn(r),r.channelId!==e)return;const a=null===(s=Ie(["channel","get",e]))||void 0===s?void 0:s.data;a&&(yi(a,{messagePreviewId:r.messageId}),t(r))}))),"channelId","channel"),ao((t=>fi((async r=>{var s;const a=null===(s=Ie(["channel","get",e]))||void 0===s?void 0:s.data;if(!a||a.messagePreviewId!==r.messageId)return;"no-message-preview"!==await n.getMessagePreviewSetting(!1)&&(await Zn(r),t(r))}))),"channelId","channel"),ao((t=>mi((async r=>{var s;const a=null===(s=Ie(["channel","get",e]))||void 0===s?void 0:s.data;if(!a||a.messagePreviewId!==r.messageId)return;const o=await n.getMessagePreviewSetting(!1);"no-message-preview"!==o&&("message-preview-not-include-deleted"===o?(Te(["messagePreviewChannel","get",e]),await pi(r.channelId)):await Zn(r),t(r))}))),"channelId","channel"),ao((e=>Fs((async t=>{var r,s;const{channelId:a,subChannelId:o}=t,i=null===(r=Ie(["messagePreviewChannel","get",a]))||void 0===r?void 0:r.data;if(!i||i.subChannelId!==o)return;if("no-message-preview"===await n.getMessagePreviewSetting(!1))return;await pi(a);(null===(s=Ie(["channel","get",a]))||void 0===s?void 0:s.data)&&e(t)}))),"channelId","channel"),ao((t=>gi((async r=>{var s,a;if("no-message-preview"===await n.getMessagePreviewSetting(!1))return;Xn(r);const o=null===(s=Ie(["messagePreviewChannel","get",e]))||void 0===s?void 0:s.data;if(!o||o.subChannelId!==r.subChannelId)return;(null===(a=Ie(["channel","get",e]))||void 0===a?void 0:a.data)&&t(r)}))),"channelId","channel"),ao(qs,"channelId","channel"),ao(Vi,"channelId","channel"),ao((e=>Hi((t=>{t.forEach(e)}))),"channelId","channel")],{forceDispatch:!0})},getChannels:(e,t,n)=>{const{log:r,cache:s,userId:a}=be();s||console.log(N);const o=Date.now();r(`getChannels(tmpid: ${o}) > listen`);const i=new Xi(e,t),c=i.startSubscription(),l=i.getCacheKey();return c.push((()=>{Te(l)})),()=>{r(`getChannels(tmpid: ${o}) > dispose`),c.forEach((e=>e()))}},getTotalChannelsUnread:e=>{const{_id:t}=ze();if(!t)throw new pe("The _id has not been defined in ActiveUser",8e5,"error");const{log:n,cache:r}=be();r||console.log("For using Live Object feature you need to enable Cache!");n(`liveTotalChannelsUnread(tmpid: ${Date.now()}) > listen`);const s=[];let a,o=!1;const i=t=>{const{data:n}=t,r=n?{unreadCount:n.unreadCount,isMentioned:n.isMentioned}:void 0;a=r?ca(r):r,e({data:r?Object.assign(Object.assign({},r),{isMentioned:r.isMentioned}):r,loading:t.loading,error:t.error})};return s.push(Hi((e=>{const{data:t}=ec();ln(a,t)||i({loading:!1,data:t})}))),(()=>{const e=ae((async()=>ec()));ie(e,(({error:e,data:t,loading:n,origin:r,cachedAt:a})=>{a===q?(i({data:t,origin:r,loading:!1,error:new fe(B,800800,"error")}),o=!0,s.forEach((e=>e()))):o||i({loading:n,data:t,origin:r,error:e}),e&&s.forEach((e=>e()))}))})(),()=>{s.forEach((e=>e()))}},MARKER_INCLUDED_CHANNEL_TYPE:tr,isUnreadCountSupport:nr,convertFromRaw:rr,preUpdateChannelCache:sr,prepareChannelPayload:ar});const cc=(e,t)=>{0!==e.length&&0!==t.length&&e.forEach((({communityId:e})=>{const n=t.filter((({communityId:t})=>e===t));Se(["communityUsers","collection",e],n)}))},lc=async e=>{const t=be();t.log("community/getCommunities",e);const{data:n}=await t.http.get("/api/v3/communities/list",{params:{communityIds:e}}),r=Uo(n),s=t.cache&&Date.now();return t.cache&&(Kt(r,{cachedAt:s}),cc(r.communities,r.communityUsers)),{data:r.communities,cachedAt:s}};lc.locally=e=>{var t;const n=be();if(n.log("community/getCommunities.locally",e),!n.cache)return;const r=e.map((e=>Ie(["community","get",e]))).filter(Boolean),s=r.map((({data:e})=>e)),a=null===(t=r.sort(((e,t)=>e.cachedAt<t.cachedAt?-1:1)))||void 0===t?void 0:t[0];return(null==r?void 0:r.length)<e.length?void 0:{data:s,cachedAt:a.cachedAt}};const dc=async e=>{const t=be();t.log("community/getCommunity",e);const{data:n}=await t.http.get(`/api/v3/communities/${e}`),r=Uo(n),s=t.cache&&Date.now();t.cache&&(Kt(r,{cachedAt:s}),cc(r.communities,r.communityUsers));const{communities:a}=r;return{data:a.find((t=>t.communityId===e)),cachedAt:s}};dc.locally=e=>{const t=be();if(t.log("community/getCommunity.locally",e),!t.cache)return;const n=Ie(["community","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const uc=(e,t)=>{const n=be();return Ye(n,e,e,(e=>{const r=Uo(e);if(n.cache){Kt(r);const e=Ie(["community","get",r.communities[0].communityId]);t(e.data)}else t(r.communities[0])}))},hc=e=>uc("community.created",e),pc=e=>uc("community.updated",e),fc=e=>uc("community.deleted",e);class mc extends Ma{async getRequest(e,t){const{limit:n=x}=e,r=zt(e,["limit"]),s=t?{token:t}:{limit:n},{data:a}=await this.http.get("/api/v3/communities",{params:Object.assign(Object.assign({},r),{isDeleted:jn(r.includeDeleted),keyword:r.displayName,filter:r.membership,options:s})});return a}}class gc extends Pa{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=be(),r=n.cache&&Date.now();n.cache&&Kt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,s;if(n)Se(this.cacheKey,{data:e.communities.map(de("community"))});else{const t=null===(r=Ie(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];Se(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.communities.map(de("community"))])]}))}}reactor(e){return e=>{var t;const n=null===(t=Ie(this.cacheKey))||void 0===t?void 0:t.data;n&&(Se(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}var yc,vc;!function(e){e.OnCommunityCreated="onCommunityCreated",e.OnCommunityDeleted="onCommunityDeleted",e.OnCommunityUpdated="onCommunityUpdated"}(yc||(yc={})),function(e){e.OnCommunityJoined="onCommunityJoined",e.OnCommunityLeft="onCommunityLeft",e.OnCommunityUserBanned="onCommunityUserBanned",e.OnCommunityUserChanged="onCommunityUserChanged",e.OnCommunityUserRoleAdded="onCommunityUserRoleAdded",e.OnCommunityUserRoleRemoved="onCommunityUserRoleRemoved",e.OnCommunityUserUnbanned="onCommunityUserUnbanned",e.OnMemberCountChanged="OnMemberCountChanged",e.OnCommunityUserAdded="OnCommunityUserAdded",e.onCommunityUserRemoved="onCommunityUserRemoved",e.OnUserDeleted="OnUserDeleted"}(vc||(vc={}));class bc extends Ma{async getRequest(e,t){const{limit:n=x,includeDeleted:r}=e,s=zt(e,["limit","includeDeleted"]),a=t?{token:t}:{limit:n},o=!1!==r&&void 0,{data:i}=await this.http.get(`/api/v3/communities/${s.communityId}/users`,{params:Object.assign(Object.assign({},s),{options:a,isDeleted:o})});return i}}class wc extends Pa{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=be(),r=n.cache&&Date.now();n.cache&&Kt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,s;if(n)Se(this.cacheKey,{data:e.communityUsers.map((({communityId:e,userId:t})=>de("communityUsers")({communityId:e,userId:t})))});else{const t=null===(r=Ie(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];Se(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.communityUsers.map((({communityId:e,userId:t})=>de("communityUsers")({communityId:e,userId:t})))])]}))}}reactor(e){return(e,t)=>{var n;const r=null===(n=Ie(this.cacheKey))||void 0===n?void 0:n.data;r&&(t.forEach((e=>{const t=de("communityUsers")({communityId:this.query.communityId,userId:e.userId});"none"===e.communityMembership?r.data=r.data.filter((e=>e!==t)):r.data.includes(t)||(r.data=[t,...r.data])})),Se(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}function Cc(e,t,n){return!!e.permissions.some((e=>e===n))||t.communityUsers.find((t=>t.userId===e.userId)).permissions.some((e=>e===n))}function Ic(e,t){return"community.joined"===e||"community.left"===e?t.communityUsers:"community.userRemoved"===e||"local.community.userRemoved"===e?t.communityUsers.filter((e=>"none"===e.communityMembership)):"community.userBanned"===e?t.communityUsers.filter((e=>"banned"===e.communityMembership)):"community.userUnbanned"===e?t.communityUsers.filter((e=>!Cc(e,t,"BAN_COMMUNITY_USER"))):t.communityUsers.filter((e=>!Cc(e,t,"ADD_COMMUNITY_USER")))}const Sc=(e,t)=>{const n=be();return Ye(n,e,e,(r=>{const s=Uo(r),{communities:a,communityUsers:o}=s,i=_o(a,o);if(s.communities=i,n.cache){Kt(s,void 0,!1);const n=Ie(["community","get",s.communities[0].communityId]),r=Ic(e,s).map((e=>{const t=Ie(["communityUsers","get",de("communityUsers")(e)]);return null==t?void 0:t.data})).filter(dn);t(n.data,r)}else t(s.communities[0],Ic(e,s))}))},_c=(e,t)=>{const n=be();return Ye(n,e,e,(r=>{const s=Uo(r),{communities:a,communityUsers:o}=s,i=_o(a,o);if(s.communities=i,n.cache){Kt(s,void 0,!1);const n=Ie(["community","get",s.communities[0].communityId]),r=Ic(e,s).map((e=>{const t=Ie(["communityUsers","get",de("communityUsers")(e)]);return null==t?void 0:t.data})).filter(dn);t(n.data,r)}else t(s.communities[0],Ic(e,s))}))},kc=e=>Sc("community.userBanned",e),Tc=e=>Sc("community.userChanged",e),Oc=e=>Sc("community.userUnbanned",e),Ac=e=>Sc("community.roleAdded",e),Ec=e=>Sc("community.roleRemoved",e),Mc=e=>_c("local.community.userAdded",e),Rc=e=>_c("local.community.userRemoved",e),Pc=e=>Sc("community.joined",e),jc=e=>Sc("community.left",e),Uc=e=>_c("local.community.joined",e),xc=e=>_c("local.community.left",e),Dc=e=>{const t=be();return Ye(t,"onLocalCommunityRoleRemoved","local.community.roleRemoved",(async t=>{const{communities:n,communityUsers:r}=t;e(n[0],r.filter((e=>"member"===e.communityMembership)))}))},Nc=e=>{const t=be();return Ye(t,"onLocalCommunityRoleAdded","local.community.roleAdded",(async t=>{const{communities:n,communityUsers:r}=t;e(n[0],r.filter((e=>"member"===e.communityMembership)))}))},Bc=e=>t=>{const n=be();return Ye(n,"user.deleted","user.deleted",(n=>{var r,s;const a=$r(n);if(0===a.users.length)return;const o=a.users[0];Kt(a);const i=de("communityUsers")({communityId:e,userId:o.userId}),c=null===(r=Ie(["communityUsers","get",i]))||void 0===r?void 0:r.data;Se(["communityUsers","get",i],Object.assign(Object.assign({},c),{user:o}));const l=null===(s=Ie(["community","get",e]))||void 0===s?void 0:s.data;t(l,[Object.assign(Object.assign({},c),{user:o})])}))};class qc extends Da{constructor(e,t){const n=w.default(e),r=["communityUsers","collection",n];super(new bc(e),n,r,t),this.query=e,this.queryStreamController=new wc(this.query,this.cacheKey,this.notifyChange.bind(this),Uo),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Ie(this.cacheKey))||void 0===e?void 0:e.data)||Se(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:Pc,action:vc.OnCommunityJoined},{fn:Uc,action:vc.OnCommunityJoined},{fn:jc,action:vc.OnCommunityLeft},{fn:xc,action:vc.OnCommunityLeft},{fn:kc,action:vc.OnCommunityUserBanned},{fn:Tc,action:vc.OnCommunityUserChanged},{fn:Ac,action:vc.OnCommunityUserRoleAdded},{fn:Ec,action:vc.OnCommunityUserRoleRemoved},{fn:Nc,action:vc.OnCommunityUserRoleAdded},{fn:Dc,action:vc.OnCommunityUserRoleRemoved},{fn:Oc,action:vc.OnCommunityUserUnbanned},{fn:Mc,action:vc.OnCommunityUserAdded},{fn:Rc,action:vc.onCommunityUserRemoved},{fn:Bc(this.query.communityId),action:vc.OnCommunityUserChanged}])}notifyChange({origin:e,loading:t,error:n}){var r,s;const a=null===(r=Ie(this.cacheKey))||void 0===r?void 0:r.data;if(!a)return;const o=this.applyFilter(null!==(s=a.data.map((e=>Ie(["communityUsers","get",e]))).filter(dn).map((({data:e})=>e)))&&void 0!==s?s:[]);(this.shouldNotify(o)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:o,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=Ee(e,"roles",this.query.roles);if(this.query.memberships&&(t=t.filter((({communityMembership:e})=>(this.query.memberships||[]).includes(e)))),!1===this.query.includeDeleted&&(t=t.filter((({user:e})=>!0!==(null==e?void 0:e.isDeleted)))),"firstCreated"===this.query.sortBy)t=t.sort(Ne);else t=t.sort(qe);return t}}class Fc extends Ma{async getRequest(e,t){const{limit:n=x,includeDeleted:r}=e,s=zt(e,["limit","includeDeleted"]),a=t?{token:t}:{limit:n},o=!1!==r&&void 0,{data:i}=await this.http.get(`/api/v3/communities/${s.communityId}/users`,{params:Object.assign(Object.assign({},s),{options:a,isDeleted:o})});return i}}class Lc extends Pa{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=be(),r=n.cache&&Date.now();n.cache&&Kt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,s;if(n)Se(this.cacheKey,{data:e.communityUsers.map((({communityId:e,userId:t})=>de("communityUsers")({communityId:e,userId:t})))});else{const t=null===(r=Ie(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];Se(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.communityUsers.map((({communityId:e,userId:t})=>de("communityUsers")({communityId:e,userId:t})))])]}))}}reactor(e){return(e,t)=>{var n;const r=null===(n=Ie(this.cacheKey))||void 0===n?void 0:n.data;r&&(t.forEach((e=>{const t=de("communityUsers")({communityId:this.query.communityId,userId:e.userId});"none"===e.communityMembership&&(r.data=r.data.filter((e=>e!==t)))})),Se(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}var Kc;!function(e){e.OnCommunityJoined="onCommunityJoined",e.OnCommunityLeft="onCommunityLeft",e.OnCommunityUserBanned="onCommunityUserBanned",e.OnCommunityUserChanged="onCommunityUserChanged",e.OnCommunityUserRoleAdded="onCommunityUserRoleAdded",e.OnCommunityUserRoleRemoved="onCommunityUserRoleRemoved",e.OnCommunityUserUnbanned="onCommunityUserUnbanned"}(Kc||(Kc={}));class $c extends Da{constructor(e,t){const n=w.default(e),r=["communityUsers","collection",n];super(new Fc(e),n,r,t),this.query=e,this.queryStreamController=new Lc(this.query,this.cacheKey,this.notifyChange.bind(this),Uo),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Ie(this.cacheKey))||void 0===e?void 0:e.data)||Se(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:Pc,action:Kc.OnCommunityJoined},{fn:Uc,action:Kc.OnCommunityJoined},{fn:jc,action:Kc.OnCommunityLeft},{fn:xc,action:Kc.OnCommunityLeft},{fn:kc,action:Kc.OnCommunityUserBanned},{fn:Tc,action:Kc.OnCommunityUserChanged},{fn:Dc,action:Kc.OnCommunityUserRoleRemoved},{fn:Ec,action:Kc.OnCommunityUserRoleRemoved},{fn:Oc,action:Kc.OnCommunityUserUnbanned},{fn:Bc(this.query.communityId),action:Kc.OnCommunityUserChanged}])}notifyChange({origin:e,loading:t,error:n}){var r,s;const a=null===(r=Ie(this.cacheKey))||void 0===r?void 0:r.data;if(!a)return;const o=this.applyFilter(null!==(s=a.data.map((e=>Ie(["communityUsers","get",e]))).filter(dn).map((({data:e})=>e)))&&void 0!==s?s:[]);(this.shouldNotify(o)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:o,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=Ee(e,"roles",this.query.roles);return this.query.memberships&&(t=t.filter((({communityMembership:e})=>(this.query.memberships||[]).includes(e)))),this.query.search&&(t=Ue(t,this.query.search)),!1===this.query.includeDeleted&&(t=t.filter((({user:e})=>!0!==(null==e?void 0:e.isDeleted)))),t}}var zc=Object.freeze({__proto__:null,addMembers:async(e,t)=>{const n=be();n.log("community/moderation/addMembers",e,t);const{data:r}=await n.http.post(`/api/v3/communities/${e}/users`,{communityId:e,userIds:t});Ze("local.community.userAdded",r);const s=Vt(r,"communityUsers");n.cache&&Kt(s);const{communityUsers:a}=s;return!!a.find((t=>t.communityId===e&&"member"===t.communityMembership))},removeMembers:async(e,t)=>{const n=be();n.log("community/moderation/removeMembers",e,t);const{data:r}=await n.http.delete(`/api/v3/communities/${e}/users`,{data:{communityId:e,userIds:t}});Ze("local.community.userRemoved",r);const s=Vt(r,"communityUsers");n.cache&&Kt(s);const{communityUsers:a}=s;return!!a.find((t=>t.communityId===e&&"member"!==t.communityMembership))},applyFilter:(e,t)=>{let n=Ee(e,"roles",t.roles);t.memberships&&(n=n.filter((({communityMembership:e})=>t.memberships.includes(e))));const r=t.sortBy?t.sortBy:"lastCreated";return n=n.sort("lastCreated"===r?qe:Ne),n},getMembers:(e,t,n)=>{const{log:r,cache:s}=be();s||console.log(N);const a=Date.now();r(`getMembers(tmpid: ${a}) > listen`);const o=new qc(e,(e=>{t(e)})),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>{Te(c)})),()=>{r(`getMembers(tmpid: ${a}) > dispose`),i.forEach((e=>e()))}},searchMembers:(e,t,n)=>{const{log:r,cache:s}=be();s||console.log(N);const a=Date.now();r(`getMembers(tmpid: ${a}) > listen`);const o=new $c(e,(e=>{t(e)})),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>{Te(c)})),()=>{r(`getMembers(tmpid: ${a}) > dispose`),i.forEach((e=>e()))}},onCommunityUserAdded:e=>Sc("community.userAdded",e),onCommunityUserRemoved:e=>Sc("community.userRemoved",e),onCommunityUserBanned:kc,onCommunityUserChanged:Tc,onCommunityUserUnbanned:Oc,onCommunityUserRoleAdded:Ac,onCommunityUserRoleRemoved:Ec,onLocalCommunityUserAdded:Mc,onLocalCommunityUserRemoved:Rc,onCommunityJoined:Pc,onCommunityLeft:jc,onLocalCommunityJoined:Uc,onLocalCommunityLeft:xc});class Qc extends Da{constructor(e,t){const n=w.default(e),r=["community","collection",n];super(new mc(e),n,r,t),this.query=e,this.queryStreamController=new gc(this.query,this.cacheKey,this.notifyChange.bind(this),Uo),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Ie(this.cacheKey))||void 0===e?void 0:e.data)||Se(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:fc,action:yc.OnCommunityDeleted},{fn:pc,action:yc.OnCommunityUpdated},{fn:Pc,action:vc.OnCommunityJoined},{fn:jc,action:vc.OnCommunityLeft},{fn:Tc,action:vc.OnMemberCountChanged},{fn:Uc,action:vc.OnCommunityJoined},{fn:xc,action:vc.OnCommunityLeft}])}notifyChange({origin:e,loading:t,error:n}){var r,s;const a=null===(r=Ie(this.cacheKey))||void 0===r?void 0:r.data;if(!a)return;const o=this.applyFilter(null!==(s=a.data.map((e=>Ie(["community","get",e]))).filter(dn).map((({data:e})=>e)))&&void 0!==s?s:[]);(this.shouldNotify(o)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:o,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){const{userId:t}=be();let n=e;return this.query.includeDeleted||(n=Oe(n,"isDeleted",!1)),this.query.categoryId&&(n=n.filter((e=>{var t;return null===(t=e.categoryIds)||void 0===t?void 0:t.includes(this.query.categoryId)}))),this.query.tags&&(n=n.filter((e=>{var t;return null===(t=e.tags)||void 0===t?void 0:t.some((e=>{var t;return null===(t=this.query.tags)||void 0===t?void 0:t.includes(e)}))}))),this.query.membership&&t&&(n=Pe(n,this.query.membership,t)),n}}class Vc extends Ma{async getRequest(e,t){const{limit:n=x}=e,r=zt(e,["limit"]),s=t?{token:t}:{limit:n},{data:a}=await this.http.get("/api/v3/communities",{params:Object.assign(Object.assign({},r),{isDeleted:jn(r.includeDeleted),filter:r.membership,options:s})});return a}}class Hc extends Pa{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=be(),r=n.cache&&Date.now();n.cache&&(Kt(t,{cachedAt:r}),cc(e.communities,e.communityUsers))}appendToQueryStream(e,t,n=!1){var r,s;if(n)Se(this.cacheKey,{data:e.communities.map(de("community"))});else{const t=null===(r=Ie(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];Se(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.communities.map(de("community"))])]}))}}reactor(e){return e=>{var t;const n=null===(t=Ie(this.cacheKey))||void 0===t?void 0:t.data;n&&(n.data=[...new Set([e.communityId,...n.data])],Se(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}var Wc;!function(e){e.OnCommunityCreated="onCommunityCreated",e.OnCommunityDeleted="onCommunityDeleted",e.OnCommunityUpdated="onCommunityUpdated"}(Wc||(Wc={}));class Jc extends Da{constructor(e,t){const n=w.default(e),r=["community","collection",n];super(new Vc(e),n,r,t),this.query=e,this.queryStreamController=new Hc(this.query,this.cacheKey,this.notifyChange.bind(this),Uo),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Ie(this.cacheKey))||void 0===e?void 0:e.data)||Se(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:hc,action:Wc.OnCommunityCreated},{fn:fc,action:Wc.OnCommunityDeleted},{fn:pc,action:Wc.OnCommunityUpdated},{fn:Pc,action:vc.OnCommunityJoined},{fn:jc,action:vc.OnCommunityLeft},{fn:Tc,action:vc.OnMemberCountChanged},{fn:Uc,action:vc.OnCommunityJoined},{fn:xc,action:vc.OnCommunityLeft}])}notifyChange({origin:e,loading:t,error:n}){var r,s;const a=null===(r=Ie(this.cacheKey))||void 0===r?void 0:r.data;if(!a)return;const o=this.applyFilter(null!==(s=a.data.map((e=>Ie(["community","get",e]))).filter(dn).map((({data:e})=>e)))&&void 0!==s?s:[]);(this.shouldNotify(o)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:o,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){const{userId:t}=be();let n=e;this.query.includeDeleted||(n=Oe(n,"isDeleted",!1)),this.query.categoryId&&(n=n.filter((e=>{var t;return null===(t=e.categoryIds)||void 0===t?void 0:t.includes(this.query.categoryId)}))),this.query.tags&&(n=n.filter((e=>{var t;return null===(t=e.tags)||void 0===t?void 0:t.some((e=>{var t;return null===(t=this.query.tags)||void 0===t?void 0:t.includes(e)}))}))),this.query.membership&&t&&(n=Pe(n,this.query.membership,t));const r=(()=>"firstCreated"===this.query.sortBy?Ne:qe)();return n=n.sort(r),n}}class Gc extends Ma{async getRequest(e,t){const{limit:n=x}=e,r=zt(e,["limit"]),s=t?{token:t}:{limit:n},{data:a}=await this.http.get("/api/v3/communities/top-trending",{params:Object.assign(Object.assign({},r),{options:s})});return a}}class Yc extends Pa{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=be(),r=n.cache&&Date.now();n.cache&&(Kt(t,{cachedAt:r}),cc(e.communities,e.communityUsers))}appendToQueryStream(e,t,n=!1){var r,s;if(n)Se(this.cacheKey,{data:e.communities.map(de("community"))});else{const t=null===(r=Ie(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];Se(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.communities.map(de("community"))])]}))}}reactor(e){return e=>{var t;const n=null===(t=Ie(this.cacheKey))||void 0===t?void 0:t.data;n&&(Se(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}var Zc;!function(e){e.OnCommunityDeleted="onCommunityDeleted",e.OnCommunityUpdated="onCommunityUpdated"}(Zc||(Zc={}));class Xc extends Da{constructor(e,t){const n=w.default(e),r=["trendingCommunity","collection",n];super(new Gc(e),n,r,t),this.query=e,this.queryStreamController=new Yc(this.query,this.cacheKey,this.notifyChange.bind(this),Uo),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Ie(this.cacheKey))||void 0===e?void 0:e.data)||Se(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:fc,action:Zc.OnCommunityDeleted},{fn:pc,action:Zc.OnCommunityUpdated},{fn:Pc,action:vc.OnCommunityJoined},{fn:jc,action:vc.OnCommunityLeft},{fn:Tc,action:vc.OnMemberCountChanged},{fn:Uc,action:vc.OnCommunityJoined},{fn:xc,action:vc.OnCommunityLeft}])}notifyChange({origin:e,loading:t,error:n}){var r,s;const a=null===(r=Ie(this.cacheKey))||void 0===r?void 0:r.data;if(!a)return;const o=null!==(s=a.data.map((e=>Ie(["community","get",e]))).filter(dn).map((({data:e})=>e)))&&void 0!==s?s:[];(this.shouldNotify(o)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:o,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}}class el extends Ma{async getRequest(e,t){const{limit:n=x}=e,r=zt(e,["limit"]),s=t?{token:t}:{limit:n},{data:a}=await this.http.get("/api/v3/communities/recommended",{params:Object.assign(Object.assign({},r),{options:s})});return a}}class tl extends Pa{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=be(),r=n.cache&&Date.now();n.cache&&(Kt(t,{cachedAt:r}),cc(e.communities,e.communityUsers))}appendToQueryStream(e,t,n=!1){var r,s;if(n)Se(this.cacheKey,{data:e.communities.map(de("community"))});else{const t=null===(r=Ie(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];Se(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.communities.map(de("community"))])]}))}}reactor(e){return e=>{var t;const n=null===(t=Ie(this.cacheKey))||void 0===t?void 0:t.data;n&&(Se(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}var nl;!function(e){e.OnCommunityDeleted="onCommunityDeleted",e.OnCommunityUpdated="onCommunityUpdated"}(nl||(nl={}));class rl extends Da{constructor(e,t){const n=w.default(e),r=["community","collection",n];super(new el(e),n,r,t),this.query=e,this.queryStreamController=new tl(this.query,this.cacheKey,this.notifyChange.bind(this),Uo),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Ie(this.cacheKey))||void 0===e?void 0:e.data)||Se(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:fc,action:nl.OnCommunityDeleted},{fn:pc,action:nl.OnCommunityUpdated},{fn:Pc,action:vc.OnCommunityJoined},{fn:jc,action:vc.OnCommunityLeft},{fn:Tc,action:vc.OnMemberCountChanged},{fn:Uc,action:vc.OnCommunityJoined},{fn:xc,action:vc.OnCommunityLeft}])}notifyChange({origin:e,loading:t,error:n}){var r,s;const a=null===(r=Ie(this.cacheKey))||void 0===r?void 0:r.data;if(!a)return;const o=null!==(s=a.data.map((e=>Ie(["community","get",e]))).filter(dn).map((({data:e})=>e)))&&void 0!==s?s:[];(this.shouldNotify(o)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:o,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}}class sl extends Ma{async getRequest(e,t){const{limit:n=x,communityMembershipStatus:r}=e,s=zt(e,["limit","communityMembershipStatus"]),a={type:e.limit?"pagination":void 0},o=t?Object.assign(Object.assign({},a),{token:t}):Object.assign(Object.assign({},a),{limit:n}),{data:i}=await this.http.get("/api/v1/semantic-search/communities",{params:Object.assign(Object.assign({},s),{filter:null!=r?r:"all",options:o})});return i}}function al(e){return e.communities.map((t=>{const n=e.searchResult.find((e=>e.communityId===t.communityId));return`${t.communityId}:${n}`}))}class ol extends Pa{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=this.preparePayload(e),n=be(),r=n.cache&&Date.now();n.cache&&Kt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,s;if(n)Se(this.cacheKey,{data:al(e)});else{const t=null===(r=Ie(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];Se(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...al(e)])]}))}}reactor(e){return e=>{var t;const n=null===(t=Ie(this.cacheKey))||void 0===t?void 0:t.data;n&&(n.data=[...new Set([e.communityId,...n.data])],Se(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}var il;!function(e){e.OnCommunityCreated="onCommunityCreated",e.OnCommunityDeleted="onCommunityDeleted",e.OnCommunityUpdated="onCommunityUpdated"}(il||(il={}));class cl extends Da{constructor(e,t){const n=w.default(e),r=["community","collection",n];super(new sl(e),n,r,t),this.query=e,this.queryStreamController=new ol(this.query,this.cacheKey,this.notifyChange.bind(this),No),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Ie(this.cacheKey))||void 0===e?void 0:e.data)||Se(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:hc,action:il.OnCommunityCreated},{fn:fc,action:il.OnCommunityDeleted},{fn:pc,action:il.OnCommunityUpdated},{fn:Pc,action:vc.OnCommunityJoined},{fn:jc,action:vc.OnCommunityLeft},{fn:Tc,action:vc.OnMemberCountChanged},{fn:Uc,action:vc.OnCommunityJoined},{fn:xc,action:vc.OnCommunityLeft}])}notifyChange({origin:e,loading:t,error:n}){var r,s;const a=null===(r=Ie(this.cacheKey))||void 0===r?void 0:r.data;if(!a)return;const o=this.applyFilter(null!==(s=a.data.map((e=>{const[t,n]=e.split(":");return{communityId:t,score:parseFloat(n)}})).sort(((e,t)=>t.score-e.score)).map((({communityId:e})=>Ie(["community","get",e]))).filter(dn).map((({data:e})=>e)))&&void 0!==s?s:[]);(this.shouldNotify(o)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:o,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){const{userId:t}=be();let n=e;return this.query.categoryIds&&(n=n.filter((e=>{var t;return null===(t=e.categoryIds)||void 0===t?void 0:t.some((e=>!this.query.categoryIds||(0===this.query.categoryIds.length||this.query.categoryIds.includes(e))))}))),this.query.tags&&(n=n.filter((e=>{var t;return null===(t=e.tags)||void 0===t?void 0:t.some((e=>{var t;return null===(t=this.query.tags)||void 0===t?void 0:t.includes(e)}))}))),this.query.communityMembershipStatus&&t&&(n=Pe(n,this.query.communityMembershipStatus,t)),n}}var ll;!function(e){e.ALL="all",e.MEMBER="member",e.NOT_MEMBER="notMember"}(ll||(ll={}));var dl=Object.freeze({__proto__:null,addRoles:async(e,t,n)=>{const r=be();r.log("community/moderation/addRoles",e,t,n);const{data:s}=await r.http.post(`/api/v4/communities/${e}/users/roles`,{communityId:e,roles:t,userIds:n}),a=xo(s);r.cache&&Kt(a),Ze("local.community.roleAdded",a);const{communityUsers:o}=a;return!!o.find((n=>n.communityId===e&&t.some((e=>n.roles.includes(e)))))},removeRoles:async(e,t,n)=>{const r=be();r.log("community/moderation/removeRoles",e,t,n);const{data:s}=await r.http.delete(`/api/v4/communities/${e}/users/roles`,{data:{communityId:e,roles:t,userIds:n}}),a=xo(s);r.cache&&Kt(a),Ze("local.community.roleRemoved",a);const{communityUsers:o}=a;return!!o.find((n=>n.communityId===e&&!t.some((e=>n.roles.includes(e)))))},banMembers:async(e,t)=>{const n=be();n.log("community/banMembers",{userIds:t,communityId:e});const{data:r}=await n.http.put(`/api/v3/communities/${e}/users/ban`,{userIds:t}),s=Vt(r,"communityUsers"),a=n.cache&&Date.now();n.cache&&Kt(s,{cachedAt:a});const{communityUsers:o}=s;return{data:o.filter((e=>t.includes(e.userId))),cachedAt:a}},unbanMembers:async(e,t)=>{const n=be();n.log("community/unbanMembers",{userIds:t,communityId:e});const{data:r}=await n.http.put(`/api/v3/communities/${e}/users/unban`,{userIds:t}),s=Vt(r,"communityUsers"),a=n.cache&&Date.now();n.cache&&Kt(s,{cachedAt:a});const{communityUsers:o}=s;return{data:o.filter((e=>t.includes(e.userId))),cachedAt:a}}}),ul=Object.freeze({__proto__:null,Moderation:dl,Membership:zc,getCommunityByIds:lc,createCommunity:async e=>{const t=be();t.log("user/createCommunity",e);const{data:n}=await t.http.post("/api/v3/communities/",Do(e));Ze("community.created",n);const r=Uo(n),s=t.cache&&Date.now();t.cache&&(Kt(r,{cachedAt:s}),cc(r.communities,r.communityUsers));const{communities:a}=r;return{data:a[0],cachedAt:s}},updateCommunity:async(e,t)=>{const n=be();n.log("community/updateCommunity",e,t);const{data:r}=await n.http.put(`/api/v3/communities/${e}`,Do(t));Ze("community.updated",r);const s=Uo(r),a=n.cache&&Date.now();n.cache&&(Kt(s,{cachedAt:a}),cc(s.communities,s.communityUsers));const{communities:o}=s;return{data:o.find((t=>t.communityId===e)),cachedAt:a}},deleteCommunity:async e=>{const t=be();t.log("community/deleteCommunity",e),await t.http.delete(`/api/v3/communities/${e}`);const n=await dc(e);return Ze("community.deleted",{communities:[n.data],categories:[],communityUsers:[],feeds:[],files:[],users:[]}),n.data},joinCommunity:async e=>{const t=be();t.log("community/joinCommunity",e);const{data:n}=await t.http.post(`/api/v3/communities/${e}/join`);Ze("local.community.joined",n);const r=Uo(n),s=t.cache&&Date.now();t.cache&&Kt(r,{cachedAt:s});const{communityUsers:a}=r;return!!a.find((t=>t.communityId===e&&"member"===t.communityMembership))},leaveCommunity:async e=>{const t=be();t.log("community/leaveCommunity",e);const{data:n}=await t.http.delete(`/api/v3/communities/${e}/leave`);Ze("local.community.left",n);const r=Uo(n),s=t.cache&&Date.now();t.cache&&Kt(r,{cachedAt:s});const{communityUsers:a}=r;return!!a.find((t=>t.communityId===e&&"member"!==t.communityMembership))},onCommunityCreated:hc,onCommunityUpdated:pc,onCommunityDeleted:fc,searchCommunities:(e,t,n)=>{const{log:r,cache:s}=be();s||console.log(N);const a=Date.now();r(`searchCommunities(tmpid: ${a}) > listen`);const o=new Qc(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>Te(c))),()=>{r(`searchCommunities(tmpid: ${a}) > dispose`),i.forEach((e=>e()))}},getCommunities:(e,t,n)=>{const{log:r,cache:s}=be();s||console.log(N);const a=Date.now();r(`getCommunities(tmpid: ${a}) > listen`);const o=new Jc(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>Te(c))),()=>{r(`getCommunities(tmpid: ${a}) > dispose`),i.forEach((e=>e()))}},getCommunity:(e,t)=>$a(e,t,"communityId",dc,[pc,fc,Pc,jc,Uc,xc,kc,Oc,Tc]),getTrendingCommunities:(e,t,n)=>{const{log:r,cache:s,userId:a}=be();s||console.log(N);const o=Date.now();r(`getTrendingCommunities(tmpid: ${o}) > listen`);const i=new Xc(e,t),c=i.startSubscription(),l=i.getCacheKey();return c.push((()=>Te(l))),()=>{r(`getTrendingCommunities(tmpid: ${o}) > dispose`),c.forEach((e=>e()))}},getRecommendedCommunities:(e,t,n)=>{const{log:r,cache:s,userId:a}=be();s||console.log(N);const o=Date.now();r(`getRecommendedCommunities(tmpid: ${o}) > listen`);const i=new rl(e,t),c=i.startSubscription(),l=i.getCacheKey();return c.push((()=>Te(l))),()=>{r(`getRecommendedCommunities(tmpid: ${o}) > dispose`),c.forEach((e=>e()))}},semanticSearchCommunities:(e,t,n)=>{const{log:r,cache:s}=be();s||console.log(N);const a=Date.now();r(`semanticSearchCommunities(tmpid: ${a}) > listen`);const o=new cl(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>Te(c))),()=>{r(`semanticSearchCommunities(tmpid: ${a}) > dispose`),i.forEach((e=>e()))}},get AmityCommunityMemberStatusFilter(){return ll}});const hl=async e=>{const t=be();t.log("category/getCategory",e);const{data:n}=await t.http.get(`/api/v3/community-categories/${encodeURIComponent(e)}`),r=t.cache&&Date.now();t.cache&&Kt(n,{cachedAt:r});const{categories:s}=n;return{data:_n.category(s.find((t=>t.categoryId===e))),cachedAt:r}};hl.locally=e=>{const t=be();if(t.log("category/getCategory.locally",e),!t.cache)return;const n=Ie(["category","get",e]);return n?{data:_n.category(n.data),cachedAt:n.cachedAt}:void 0};const pl=async e=>{const t=be();t.log("category/queryCategories",e);const n=null!=e?e:{},{page:r,limit:s,includeDeleted:a}=n,o=zt(n,["page","limit","includeDeleted"]),i=r?{token:r}:s?{limit:s}:void 0,{data:c}=await t.http.get("/api/v3/community-categories",{params:Object.assign(Object.assign({},o),{isDeleted:jn(a),options:i})}),{paging:l}=c,d=zt(c,["paging"]),{categories:u}=d,h=t.cache&&Date.now();if(t.cache){Kt(d,{cachedAt:h});const e=["category","query",Object.assign(Object.assign({},o),{includeDeleted:a,options:i})];Se(e,{categories:u.map(de("category")),paging:l})}return{data:u,cachedAt:h,paging:l}};pl.locally=e=>{var t,n;const r=be();if(r.log("category/queryCategories.locally",e),!r.cache)return;const s=null!=e?e:{},{page:a,limit:o=10}=s,i=zt(s,["page","limit"]),c=a?{token:a}:o?{limit:o}:void 0,l=["category","query",Object.assign(Object.assign({},i),{options:c})],{data:d,cachedAt:u}=null!==(t=Ie(l))&&void 0!==t?t:{};if(!(null==d?void 0:d.categories.length))return;const h=d.categories.map((e=>Ie(["category","get",e]))).filter(Boolean).map((({data:e})=>e)),{paging:p}=d;return h.length===(null===(n=null==d?void 0:d.categories)||void 0===n?void 0:n.length)?{data:h,cachedAt:u,paging:p}:void 0};var fl=Object.freeze({__proto__:null,getCategory:hl,getCategories:(e,t,n)=>{const{log:r,cache:s}=be();s||console.log(N);const a=Date.now();r(`getCategories(tmpid: ${a}) > listen`);const{limit:o}=e,i=zt(e,["limit"]),c=null!=o?o:x,{policy:l=D}=null!=n?n:{},d=[],u=["category","collection",{}],h=(n=!1)=>{var r,s;const a=null===(r=Ie(u))||void 0===r?void 0:r.data,o=null!==(s=null==a?void 0:a.data)&&void 0!==s?s:[];if(!n&&o.length>0&&!(null==a?void 0:a.params.page))return;const d=ae(pl,Object.assign(Object.assign({},i),{limit:n?c:void 0,page:n||null==a?void 0:a.params.page}));ie(d,(({data:n,error:r,loading:s,paging:a})=>{const i={loading:s,error:r,params:{page:null==a?void 0:a.next},data:o};n&&(i.data=[...new Set([...o,...n.map(de("category"))])]),Se(u,i),(n=>{var r,s;let a=null!==(r=n.data.map((e=>Ie(["category","get",e]))).filter(Boolean).map((({data:e})=>_n.category(e))))&&void 0!==r?r:[];switch(e.includeDeleted||(a=Oe(a,"isDeleted",!1)),e.sortBy){case"firstCreated":a=a.sort(Ne);break;case"lastCreated":a=a.sort(qe);break;default:a=a.sort(De)}t({onNextPage:h,data:a,hasNextPage:!!(null===(s=n.params)||void 0===s?void 0:s.page),loading:n.loading,error:n.error})})(i)}),oe(l))};return d.push((()=>{})),h(!0),()=>{r(`getCategories(tmpid: ${a}) > dispose`),d.forEach((e=>e()))}}});const ml=async e=>{const t=be();t.log("feed/queryGlobalFeed",e);const n=null!=e?e:{},{queryToken:r}=n,s=zt(n,["queryToken"]),a=(()=>{if(r)return{token:r}})(),{data:o}=await t.http.get("/api/v4/me/global-feeds",{params:Object.assign(Object.assign({},s),{options:a})}),{paging:i}=o,c=zt(o,["paging"]),l=Vt(c,"communityUsers"),{posts:d}=l,{communities:u}=Uo(l),h=t.cache&&Date.now();if(t.cache){Kt(Object.assign(Object.assign({},l),{communitis:u}));const e=["globalFeed","query",Object.assign(Object.assign({},s),{options:a})];Se(e,{posts:d.map(de("post")),paging:i})}return{data:d.map(_n.post),cachedAt:h,paging:i}};ml.locally=e=>{var t,n;const r=be();if(r.log("post/queryGlobalFeed.locally",e),!r.cache)return;const s=zt(null!=e?e:{},[]),a=["globalFeed","query",Object.assign({},s)],{data:o,cachedAt:i}=null!==(t=Ie(a))&&void 0!==t?t:{};if(!(null==o?void 0:o.posts.length))return;const c=o.posts.map((e=>Ie(["post","get",e]))).filter(Boolean).map((({data:e})=>e)).map(_n.post),{paging:l}=o;return c.length===(null===(n=null==o?void 0:o.posts)||void 0===n?void 0:n.length)?{data:c,cachedAt:i,paging:l}:void 0};const gl=async e=>{const t=be();t.log("feed/getCustomRankingGlobalFeed",e);const n=null!=e?e:{},{queryToken:r,limit:s}=n,a=zt(n,["queryToken","limit"]),o=(()=>{if(r)return{token:r}})(),{data:i}=await t.http.get("/api/v5/me/global-feeds",{params:Object.assign(Object.assign({},a),{limit:r?void 0:s,options:o})}),{paging:c}=i,l=zt(i,["paging"]),d=Vt(l,"communityUsers"),{posts:u}=d,h=t.cache&&Date.now();if(t.cache){Kt(d);const e=["customGlobalFeed","query",Object.assign(Object.assign({},a),{options:o})];Se(e,{posts:u.map(de("post")),paging:c})}return{data:u.map(_n.post),cachedAt:h,paging:c}};gl.locally=e=>{var t,n;const r=be();if(r.log("post/getCustomRankingGlobalFeed.locally",e),!r.cache)return;const s=zt(null!=e?e:{},[]),a=["customGlobalFeed","query",Object.assign({},s)],{data:o,cachedAt:i}=null!==(t=Ie(a))&&void 0!==t?t:{};if(!(null==o?void 0:o.posts.length))return;const c=o.posts.map((e=>Ie(["post","get",e]))).filter(Boolean).map((({data:e})=>e)),{paging:l}=o;return c.length===(null===(n=null==o?void 0:o.posts)||void 0===n?void 0:n.length)?{data:c.map(_n.post),cachedAt:i,paging:l}:void 0};var yl=Object.freeze({__proto__:null,queryGlobalFeed:ml,getCustomRankingGlobalFeed:gl});const vl=async e=>{const t=be();t.log("post/getPostByIds",e);const n=e.map((e=>encodeURIComponent(e)));let r;try{r=(await t.http.get("/api/v3/posts/list",{params:{postIds:n}})).data}catch(t){throw e.forEach((e=>{H(null==t?void 0:t.code)&&$t("post",e)})),t}const s=Vt(r,"communityUsers"),a=t.cache&&Date.now();return t.cache&&Kt(s,{cachedAt:a}),{data:s.posts.map(_n.post),cachedAt:a}};vl.locally=e=>{var t;const n=be();if(n.log("post/getPostByIds.locally",e),!n.cache)return;const r=e.map((e=>Ie(["post","get",e]))).filter(Boolean),s=r.map((({data:e})=>e)),a=null===(t=r.sort(((e,t)=>e.cachedAt<t.cachedAt?-1:1)))||void 0===t?void 0:t[0];return(null==r?void 0:r.length)<e.length?void 0:{data:s.map(_n.post),cachedAt:a.cachedAt}};const bl=async(e,t=!1)=>{var n;const r=be(),s=await Io(e);if(await r.http.delete(`/api/v4/posts/${encodeURIComponent(e)}`,{params:{postId:e,permanent:t}}),"community"===s.data.targetType){const e=await dc(s.data.targetId),t=(null!==(n=Ce(["communityUsers","get"]))&&void 0!==n?n:[]).filter((({key:t})=>"communityUsers"===t[0]&&("get"===t[1]&&("string"==typeof t[2]&&t[2].includes(e.data.communityId))))).map((({data:e})=>e));Ze("community.updated",{communities:[e.data],categories:[],communityUsers:t,feeds:[],files:[],users:[]})}const a=Object.assign(Object.assign({},s.data),{isDeleted:!0});return t?setTimeout((()=>{$t("post",e)}),0):ke(["post","get",e],{isDeleted:!0}),Ze("local.post.deleted",{posts:[a],categories:[],comments:[],communities:[],communityUsers:[],feeds:[],files:[],postChildren:[],users:[],videoStreamings:[]}),_n.post(a)},wl=async e=>{const t=be();t.log("comment/getCommentByIds",e);const n=e.map((e=>encodeURIComponent(e)));let r;try{r=(await t.http.get("/api/v3/comments/list",{params:{commentIds:n}})).data}catch(t){throw e.forEach((e=>{H(null==t?void 0:t.code)&&$t("comment",e)})),t}const s=t.cache&&Date.now();return t.cache&&Kt(r,{cachedAt:s}),{data:r.comments.map((e=>_n.comment(e))),cachedAt:s}};wl.locally=e=>{var t;const n=be();if(n.log("comment/getCommentByIds.locally",e),!n.cache)return;const r=e.map((e=>Ie(["comment","get",e]))).filter(Boolean),s=r.map((({data:e})=>e)),a=null===(t=r.sort(((e,t)=>e.cachedAt<t.cachedAt?-1:1)))||void 0===t?void 0:t[0];return(null==r?void 0:r.length)<e.length?void 0:{data:s.map((e=>_n.comment(e))),cachedAt:a.cachedAt}};const Cl=(e,t=!1)=>{const{stories:n}=e,r=n.map((e=>((e,t=!1)=>{const{storyId:n,referenceId:r}=e;return!t&&r?Object.assign(Object.assign({},e),{syncState:"synced"}):Object.assign(Object.assign({},e),{syncState:"synced",referenceId:n})})(e,t)));return Object.assign(Object.assign({},e),{stories:r})},Il=async e=>{const t=be();t.log("story/getStoryByStoryId",e);const n=Ie(["story-reference",e]);if(null==n?void 0:n.data){const{data:e}=n;Mn("story",e)}let r;try{const n=await t.http.get(`/api/v4/stories/${e}`);r=Cl(n.data)}catch(t){throw H(null==t?void 0:t.code)&&$t("story",e),t}const s=t.cache&&Date.now();return t.cache&&Kt(r,{cachedAt:s}),{data:r.stories[0],cachedAt:s}};Il.locally=e=>{const t=be();t.log("story/getStorybyStoryId",e);const n=Ie(["story-reference",e]);if(null==n?void 0:n.data){const{data:e}=n;Mn("story",e)}const r=t.cache&&Date.now(),s=Ie(["story","get",e]);if(s)return{data:s.data,cachedAt:r}};const Sl=async(e,t=!1)=>{var n;const r=be(),s=await So(e);await r.http.delete(`/api/v4/comments/${encodeURIComponent(e)}`,{params:{commentId:e,permanent:t}});const a=Object.assign(Object.assign({},s.data),{isDeleted:!0});if("story"===s.data.referenceType){const e=await Il(s.data.referenceId);Ze("local.story.updated",{stories:[e.data],categories:[],comments:[],communities:[],communityUsers:[],files:[],users:[]})}else{const e=null===(n=Ie(["post","get",s.data.referenceId]))||void 0===n?void 0:n.data;if(e){let t;t=a.parentId?1:a.childrenNumber+1,e.commentsCount-=t,Ze("local.post.updated",{posts:[e],categories:[],comments:[],communities:[],communityUsers:[],feeds:[],files:[],postChildren:[],users:[],videoStreamings:[]})}}return Ze("local.comment.deleted",{comments:[a],commentChildren:[],files:[],users:[],communityUsers:[]}),t?We((()=>$t("comment",e))):ke(["comment","get",e],{isDeleted:!0}),a},_l=async e=>{const t=be();let n;t.log("comment/getComment",e),Mn("comment",e);try{n=(await t.http.get(`/api/v3/comments/${encodeURIComponent(e)}`)).data}catch(t){throw H(null==t?void 0:t.code)&&$t("comment",e),t}const r=t.cache&&Date.now();t.cache&&Kt(n,{cachedAt:r});const{comments:s}=n;return{data:s.find((t=>t.commentId===e)),cachedAt:r}};_l.locally=e=>{const t=be();if(t.log("comment/getComment.locally",e),!t.cache)return;const n=Ie(["comment","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const kl=e=>Zo("local.comment.deleted",e),Tl=e=>{const t=be();return Ye(t,"local.comment.addReaction","local.comment.addReaction",(({comment:n})=>{t.cache?(ke(["comment","get",n.commentId],n),e(un(n))):e(n)}))},Ol=e=>{const t=be();return Ye(t,"local.comment.removeReaction","local.comment.removeReaction",(({comment:n})=>{t.cache?(ke(["comment","get",n.commentId],n),e(un(n))):e(n)}))};class Al extends Ma{async getRequest(e,t){const{limit:n=x,includeDeleted:r}=e,s=zt(e,["limit","includeDeleted"]),a={type:s.sortBy||e.limit?"pagination":void 0},o=t?Object.assign(Object.assign({},a),{token:t}):Object.assign(Object.assign({},a),{limit:n}),{data:i}=await this.http.get("/api/v3/comments",{params:Object.assign(Object.assign({},s),{isDeleted:jn(r),options:o})});return i}}var El;!function(e){e.OnCommentCreated="onCommentCreated",e.OnCommentUpdated="onCommentUpdated",e.OnCommentDeleted="onCommentDeleted",e.OnCommentFlagged="onCommentFlagged",e.OnCommentUnflagged="onCommentUnflagged",e.OnCommentReactionAdded="onCommentReactionAdded",e.OnCommentReactionRemoved="onCommentReactionRemoved"}(El||(El={}));class Ml extends Pa{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=be(),r=n.cache&&Date.now();n.cache&&Kt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,s;if(n)Se(this.cacheKey,{data:e.comments.map(de("comment"))});else{const t=null===(r=Ie(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];Se(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.comments.map(de("comment"))])]}))}}reactor(e){return t=>{var n;const r=null===(n=Ie(this.cacheKey))||void 0===n?void 0:n.data;this.query.referenceId===t.referenceId&&this.query.referenceType===t.referenceType&&r&&(this.query.parentId&&this.query.parentId!==t.parentId||!this.query.parentId&&t.parentId||(e===El.OnCommentCreated&&(r.data=[...new Set([t.commentId,...r.data])]),Se(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1})))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const Rl=e=>Zo("local.comment.created",e);class Pl extends Da{constructor(e,t){const n=w.default(e),r=["comments","collection",n];super(new Al(e),n,r,t),this.query=e,this.queryStreamController=new Ml(this.query,this.cacheKey,this.notifyChange.bind(this),hi),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Ie(this.cacheKey))||void 0===e?void 0:e.data)||Se(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:Rl,action:El.OnCommentCreated},{fn:kl,action:El.OnCommentDeleted},{fn:Xo,action:El.OnCommentCreated},{fn:ei,action:El.OnCommentUpdated},{fn:ti,action:El.OnCommentDeleted},{fn:ni,action:El.OnCommentFlagged},{fn:ri,action:El.OnCommentUnflagged},{fn:si,action:El.OnCommentReactionAdded},{fn:ai,action:El.OnCommentReactionRemoved},{fn:Tl,action:El.OnCommentReactionAdded},{fn:Ol,action:El.OnCommentReactionRemoved}])}notifyChange({origin:e,loading:t,error:n}){var r,s;const a=null===(r=Ie(this.cacheKey))||void 0===r?void 0:r.data;if(!a)return;const o=this.applyFilter(null!==(s=a.data.map((e=>Ie(["comment","get",e]))).filter(dn).map((({data:e})=>e)))&&void 0!==s?s:[]).map(_n.comment);(this.shouldNotify(o)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:o,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=e;if(this.query.includeDeleted||(t=Oe(t,"isDeleted",!1)),this.query.parentId&&(t=t.filter((e=>e.parentId===this.query.parentId))),"boolean"==typeof this.query.hasFlag&&(t=this.query.hasFlag?t.filter((e=>null!=e.hashFlag)):t.filter((e=>null==e.hashFlag))),this.query.dataTypes&&("exact"===this.query.dataTypes.matchType&&(t=t.filter((e=>{var t,n;const r=(null===(t=this.query.dataTypes)||void 0===t?void 0:t.values.sort())||[],s=(null===(n=e.dataTypes)||void 0===n?void 0:n.sort())||[];return s.length===r.length&&r.every(((e,t)=>e===s[t]))}))),"any"===this.query.dataTypes.matchType&&(t=t.filter((e=>{var t;return null===(t=this.query.dataTypes)||void 0===t?void 0:t.values.some((t=>{var n;return null===(n=e.dataTypes)||void 0===n?void 0:n.includes(t)}))})))),"firstCreated"===this.query.sortBy)t=t.sort(Ne);else t=t.sort(qe);return t}}var jl=Object.freeze({__proto__:null,getCommentByIds:wl,createComment:async e=>{var t;const n=be();n.log("comment/createComment",e);const{data:r}=await n.http.post("/api/v3/comments",e),{comments:s}=r;if(0===s.length)throw new Error("Comment not created");const a=n.cache&&Date.now();if(n.cache&&Kt(r,{cachedAt:a}),["post","content"].includes(e.referenceType)){const n=null===(t=Ie(["post","get",e.referenceId]))||void 0===t?void 0:t.data;n&&(n.commentsCount+=1,Ze("local.post.updated",{posts:[n],categories:[],comments:[],communities:[],communityUsers:r.communityUsers,feeds:[],files:r.files,postChildren:[],users:r.users,videoStreamings:[]}))}else if("story"===e.referenceType){const t=Ie(["story-reference",e.referenceId]);if(null==t?void 0:t.data){const e=Ie(["story","get",t.data]);(null==e?void 0:e.data)&&Ze("story.updated",{stories:[Object.assign(Object.assign({},e.data),{commentsCount:e.data.commentsCount+1,comments:[...new Set([...e.data.comments,s[0].commentId])]})],categories:[],comments:s,communities:[],communityUsers:r.communityUsers,files:r.files,users:r.users})}}return Ze("local.comment.created",r),{data:_n.comment(s[0]),cachedAt:a}},updateComment:async(e,t)=>{const n=be();n.log("user/updateComment",t);const{data:r}=await n.http.put(`/api/v3/comments/${encodeURIComponent(e)}`,t),s=n.cache&&Date.now();n.cache&&Kt(r,{cachedAt:s}),Ze("comment.updated",r);const{comments:a}=r;return{data:_n.comment(a.find((t=>t.commentId===e))),cachedAt:s}},deleteComment:Sl,softDeleteComment:async e=>{be().log("comment/softDeleteComment",e);return Sl(e)},hardDeleteComment:async e=>{be().log("comment/hardDeleteComment",e);return Sl(e,!0)},flagComment:async(t,n)=>{const r=be();r.log("comment/flagComment",t);const s=n&&Object.entries(e.ContentFlagReasonEnum).some((([t,r])=>t!==e.ContentFlagReasonEnum.Others&&r===n)),a={reason:n&&s?n:e.ContentFlagReasonEnum.Others,detail:n&&!s?n:""},{data:o}=await r.http.post(`/api/v3/comments/${encodeURIComponent(t)}/flag`,a);return r.cache&&Kt(o),Ze("comment.flagged",o),!!o},unflagComment:async e=>{const t=be();t.log("comment/unflagComment",e);const{data:n}=await t.http.delete(`/api/v3/comments/${encodeURIComponent(e)}/unflag`);return t.cache&&Kt(n),Ze("comment.unflagged",n),!!n},isCommentFlaggedByMe:async e=>{const t=be();t.log("comment/isCommentFlaggedByMe",e);const{data:{result:n}}=await t.http.get(`/api/v3/comments/${e}/isflagbyme`);return n},onCommentCreated:Xo,onCommentUpdated:ei,onCommentDeleted:ti,onCommentFlagged:ni,onCommentUnflagged:ri,onCommentReactionAdded:si,onCommentReactionRemoved:ai,getComment:(e,t)=>$a(e,t,"commentId",_l,[kl,ti,ni,si,ai,ri,ei,Tl,Ol]),getComments:(e,t,n)=>{const{log:r,cache:s}=be();s||console.log("For using Live Collection feature you need to enable Cache!");const a=Date.now();r(`getComments(tmpid: ${a}) > listen`);const o=new Pl(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>Te(c))),()=>{r(`getComments(tmpid: ${a}) > dispose`),i.forEach((e=>e()))}}});const Ul=e=>Lo("local.post.updated",e),xl=e=>{const t=be();return Ye(t,"local.post.addReaction","local.post.addReaction",(({post:n})=>{t.cache?(ke(["post","get",n.postId],n),e(n)):e(n)}))},Dl=e=>{const t=be();return Ye(t,"local.post.removeReaction","local.post.removeReaction",(({post:n})=>{t.cache?(ke(["post","get",n.postId],n),e(n)):e(n)}))},Nl=e=>Lo("local.post.deleted",e);class Bl extends Ma{async getRequest(e,t){const{limit:n=x,includeDeleted:r,matchingOnlyParentPost:s}=e,a=zt(e,["limit","includeDeleted","matchingOnlyParentPost"]),{dataTypes:o}=a,i={type:a.sortBy||e.limit?"pagination":void 0},c=t?Object.assign(Object.assign({},i),{token:t}):Object.assign(Object.assign({},i),{limit:n}),{data:l}=await this.http.get("/api/v4/posts",{params:Object.assign(Object.assign({},a),{isDeleted:jn(r),matchingOnlyParentPost:null!=s?s:!(null==o?void 0:o.length),options:c})});return l}}var ql;!function(e){e.OnPostCreated="onPostCreated",e.OnPostUpdated="onPostUpdated",e.OnPostDeleted="onPostDeleted",e.OnPostFlagged="onPostFlagged",e.OnPostUnflagged="onPostUnflagged",e.OnPostReactionAdded="onPostReactionAdded",e.OnPostReactionRemoved="onPostReactionRemoved",e.OnPostApproved="onPostApproved",e.OnPostDeclined="onPostDeclined"}(ql||(ql={}));class Fl extends Pa{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=be(),r=n.cache&&Date.now();n.cache&&Kt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,s;if(n)Se(this.cacheKey,{data:e.posts.map(de("post"))});else{const t=null===(r=Ie(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];Se(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.posts.map(de("post"))])]}))}}reactor(e){return t=>{var n,r;const s=null===(n=Ie(this.cacheKey))||void 0===n?void 0:n.data;if(s){if(t.parentPostId&&t.isDeleted){const e=null===(r=Ie(["post","get",t.parentPostId]))||void 0===r?void 0:r.data;if(!e||(null==e?void 0:e.targetId)!==this.query.targetId)return;e.children=e.children.filter((e=>e!==t.postId)),Se(["post","get",e.postId],e)}else{if(this.query.targetId!==t.targetId)return;if(this.query.targetType!==t.targetType)return}e===ql.OnPostDeclined&&(s.data=s.data.filter((e=>e!==t.postId))),e!==ql.OnPostCreated&&e!==ql.OnPostApproved||(s.data=[...new Set([t.postId,...s.data])]),Se(this.cacheKey,s),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const Ll=async e=>{const t=be();let n;t.log("post/getPost",e),Mn("post",e);try{n=(await t.http.get(`/api/v3/posts/${encodeURIComponent(e)}`)).data}catch(t){throw H(null==t?void 0:t.code)&&$t("post",e),t}const r=Vt(n,"communityUsers"),s=t.cache&&Date.now();t.cache&&Kt(r,{cachedAt:s});const{posts:a}=r;return{data:a.find((t=>t.postId===e)),cachedAt:s}};Ll.locally=e=>{const t=be();if(t.log("post/getPost.locally",e),!t.cache)return;const n=Ie(["post","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};class Kl extends Da{constructor(e,t){const n=w.default(e),r=["posts","collection",n];super(new Bl(e),n,r,t),this.query=e,this.queryStreamController=new Fl(this.query,this.cacheKey,this.notifyChange.bind(this),Bo),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Ie(this.cacheKey))||void 0===e?void 0:e.data)||Se(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:Ko,action:ql.OnPostCreated},{fn:$o,action:ql.OnPostUpdated},{fn:Ul,action:ql.OnPostUpdated},{fn:zo,action:ql.OnPostDeleted},{fn:Ho,action:ql.OnPostFlagged},{fn:Wo,action:ql.OnPostUnflagged},{fn:Qo,action:ql.OnPostApproved},{fn:Vo,action:ql.OnPostDeclined},{fn:Jo,action:ql.OnPostReactionAdded},{fn:Go,action:ql.OnPostReactionRemoved},{fn:xl,action:ql.OnPostReactionAdded},{fn:Dl,action:ql.OnPostReactionRemoved},{fn:Nl,action:ql.OnPostDeleted},{fn:ao((e=>Xo((async t=>{var n;const r=null===(n=Ie(this.cacheKey))||void 0===n?void 0:n.data;r&&!r.data.includes(t.referenceId)&&(await Ll(t.referenceId),e(t))}))),"referenceId","post"),action:ql.OnPostUpdated},{fn:ao((e=>ti((async t=>{var n;const r=null===(n=Ie(this.cacheKey))||void 0===n?void 0:n.data;r&&!r.data.includes(t.referenceId)&&(await Ll(t.referenceId),e(t))}))),"referenceId","post"),action:ql.OnPostUpdated}])}notifyChange({origin:e,loading:t,error:n}){var r,s;const a=null===(r=Ie(this.cacheKey))||void 0===r?void 0:r.data;if(!a)return;const o=this.applyFilter(null!==(s=a.data.map((e=>Ie(["post","get",e]))).filter(dn).map((({data:e})=>e)))&&void 0!==s?s:[]).map(_n.post);(this.shouldNotify(o)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:o,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){var t;let n=e;if(this.query.includeDeleted||(n=Oe(n,"isDeleted",!1)),this.query.tags&&(n=n.filter((e=>{var t;return null===(t=e.tags)||void 0===t?void 0:t.some((e=>{var t;return null===(t=this.query.tags)||void 0===t?void 0:t.includes(e)}))}))),"community"===this.query.targetType&&this.query.feedType&&(n=Re(n,this.query.feedType)),(null===(t=this.query.dataTypes)||void 0===t?void 0:t.length)&&(n=je(n,this.query.dataTypes)),"firstCreated"===this.query.sortBy)n=n.sort(Ne);else n=n.sort(qe);return n}}class $l extends Ma{async getRequest(e,t){const n=zt(e,["limit"]),{communityId:r,placement:s}=n,a=s?`/api/v1/pinned-posts/communities/${r}/${s}`:`/api/v1/pinned-posts/communities/${r}`,{data:o}=await this.http.get(a);return o}}class zl extends Pa{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=be(),n=t.cache&&Date.now();t.cache&&Kt(e,{cachedAt:n})}appendToQueryStream(e,t,n=!1){var r,s;if(n)Se(this.cacheKey,{data:e.pins.map(de("pin"))});else{const t=null===(r=Ie(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];Se(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.pins.map(de("pin"))])]})),this.notifyChange({origin:"server",loading:!1})}}}class Ql extends Da{constructor(e,t){const n=w.default(e),r=["pinnedPosts","collection",n];super(new $l(e),n,r,t),this.query=e,this.queryStreamController=new zl(this.query,this.cacheKey,this.notifyChange.bind(this),(e=>e)),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Ie(this.cacheKey))||void 0===e?void 0:e.data)||Se(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return[]}notifyChange({origin:e,loading:t,error:n}){var r,s;const a=null===(r=Ie(this.cacheKey))||void 0===r?void 0:r.data;if(!a)return;let o=(null!==(s=a.data.map((e=>Ie(["pin","get",e]))).filter(dn).map((({data:e})=>e)))&&void 0!==s?s:[]).map(_n.pinnedPost);o=this.applyFilter(o),(this.shouldNotify(o)||"event"!==e)&&this.callback({data:o,loading:t,error:n})}applyFilter(e){let t=e;if("lastCreated"===this.query.sortBy)t=t.sort((({post:e},{post:t})=>qe({createdAt:null==e?void 0:e.createdAt},{createdAt:null==t?void 0:t.createdAt})));return t}}class Vl extends Ma{async getRequest(e,t){zt(e,["limit"]);const{data:n}=await this.http.get("/api/v1/pinned-posts/global");return n}}class Hl extends Pa{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=be(),n=t.cache&&Date.now();t.cache&&Kt(e,{cachedAt:n})}appendToQueryStream(e,t,n=!1){var r,s;if(n)Se(this.cacheKey,{data:e.pins.map(de("pin"))});else{const t=null===(r=Ie(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];Se(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.pins.map(de("pin"))])]})),this.notifyChange({origin:"server",loading:!1})}}reactor(e){return t=>{var n;const r=null===(n=Ie(this.cacheKey))||void 0===n?void 0:n.data;r&&(e===ql.OnPostDeleted&&(r.data=r.data.filter((e=>e!==`global#${t.postId}`))),Se(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class Wl extends Da{constructor(e,t){const n=w.default(e),r=["pinnedPosts","collection",n];super(new Vl(e),n,r,t),this.query=e,this.queryStreamController=new Hl(this.query,this.cacheKey,this.notifyChange.bind(this),(e=>e)),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Ie(this.cacheKey))||void 0===e?void 0:e.data)||Se(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:Nl,action:ql.OnPostDeleted},{fn:zo,action:ql.OnPostDeleted}])}notifyChange({origin:e,loading:t,error:n}){var r,s;const a=null===(r=Ie(this.cacheKey))||void 0===r?void 0:r.data;if(!a)return;const o=(null!==(s=a.data.map((e=>Ie(["pin","get",e]))).filter(dn).map((({data:e})=>e)))&&void 0!==s?s:[]).map(_n.pinnedPost);(this.shouldNotify(o)||"event"!==e)&&this.callback({data:o,loading:t,error:n})}}class Jl extends Ma{async getRequest(e,t){const{limit:n=x}=e,r=zt(e,["limit"]),s={type:e.limit?"pagination":void 0},a=t?Object.assign(Object.assign({},s),{token:t}):Object.assign(Object.assign({},s),{limit:n}),{data:o}=await this.http.get("/api/v1/semantic-search/posts",{params:Object.assign(Object.assign({},r),{options:a})});return o}}function Gl(e){return e.posts.map((t=>{const n=e.searchResult.find((e=>e.postId===t.postId));return`${t.postId}:${n.score}`}))}function Yl(e){return(null!=e?e:[]).map((e=>e.split(":")[0]))}class Zl extends Pa{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=this.preparePayload(e),n=be(),r=n.cache&&Date.now();n.cache&&Kt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,s;if(n)Se(this.cacheKey,{data:Gl(e)});else{const t=null===(r=Ie(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];Se(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...Gl(e)])]}))}}reactor(e){return t=>{var n,r;const s=null===(n=Ie(this.cacheKey))||void 0===n?void 0:n.data;if(s){if(t.parentPostId&&t.isDeleted){const e=null===(r=Ie(["post","get",t.parentPostId]))||void 0===r?void 0:r.data;if(!e||(null==e?void 0:e.targetId)!==this.query.targetId)return;e.children=e.children.filter((e=>e!==t.postId)),Se(["post","get",e.postId],e)}else{if(this.query.targetId!==t.targetId)return;if(this.query.targetType!==t.targetType)return}e===ql.OnPostDeclined&&(s.data=s.data.filter((e=>e!==t.postId))),e!==ql.OnPostCreated&&e!==ql.OnPostApproved||(s.data=[...new Set([t.postId,...s.data])]),Se(this.cacheKey,s),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class Xl extends Da{constructor(e,t){const n=Object.assign(Object.assign({},e),{matchingOnlyParentPost:null==e.matchingOnlyParentPost||e.matchingOnlyParentPost,dataTypes:null==e.dataTypes?["text","image"]:e.dataTypes}),r=w.default(n),s=["posts","collection",r];super(new Jl(n),r,s,t),this.query=n,this.queryStreamController=new Zl(this.query,this.cacheKey,this.notifyChange.bind(this),qo),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Ie(this.cacheKey))||void 0===e?void 0:e.data)||Se(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:$o,action:ql.OnPostUpdated},{fn:zo,action:ql.OnPostDeleted},{fn:Ho,action:ql.OnPostFlagged},{fn:Wo,action:ql.OnPostUnflagged},{fn:Qo,action:ql.OnPostApproved},{fn:Vo,action:ql.OnPostDeclined},{fn:Jo,action:ql.OnPostReactionAdded},{fn:Go,action:ql.OnPostReactionRemoved},{fn:ao((e=>Xo((async t=>{const n=Ie(this.cacheKey);Yl(null==n?void 0:n.data).includes(t.referenceId)||(await Io(t.referenceId),e(t))}))),"referenceId","post"),action:ql.OnPostUpdated},{fn:ao((e=>ti((async t=>{const n=Ie(this.cacheKey);Yl(null==n?void 0:n.data).includes(t.referenceId)||(await Io(t.referenceId),e(t))}))),"referenceId","post"),action:ql.OnPostUpdated}])}notifyChange({origin:e,loading:t,error:n}){var r,s;const a=null===(r=Ie(this.cacheKey))||void 0===r?void 0:r.data;if(!a)return;const o=this.applyFilter(null!==(s=a.data.map((e=>{const[t,n]=e.split(":");return{postId:t,score:parseFloat(n)}})).sort(((e,t)=>t.score-e.score)).map((({postId:e})=>Ie(["post","get",e]))).filter(dn).map((({data:e})=>e)))&&void 0!==s?s:[]).map(_n.post);(this.shouldNotify(o)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:o,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=e;return this.query.targetType&&(t=t.filter((e=>e.targetType===this.query.targetType))),this.query.targetId&&(t=t.filter((e=>e.targetId===this.query.targetId))),this.query.dataTypes&&this.query.dataTypes.length>0&&(t=je(t,this.query.dataTypes)),t}}var ed=Object.freeze({__proto__:null,getPostByIds:vl,createPost:async e=>{const t=be();t.log("post/createPost",e),e.dataType&&!["text","image","file","video"].includes(e.dataType)||delete e.dataType;const{data:n}=await t.http.post("/api/v4/posts",e);Ze("post.created",n);const r=Vt(n,"communityUsers"),s=t.cache&&Date.now();t.cache&&Kt(r,{cachedAt:s});const{posts:a}=r;return{data:_n.post(a[0]),cachedAt:s}},editPost:async(e,t)=>{const n=be();n.log("user/editPost",t);const{data:r}=await n.http.put(`/api/v4/posts/${encodeURIComponent(e)}`,t),s=Vt(r,"communityUsers"),a=n.cache&&Date.now();n.cache&&Kt(s,{cachedAt:a}),Ze("local.post.updated",s);const{posts:o}=s;return{data:_n.post(o.find((t=>t.postId===e))),cachedAt:a}},deletePost:bl,softDeletePost:async e=>{be().log("post/softDeletePost",e);const t=await bl(e,!1);return _n.post(t)},hardDeletePost:async e=>{be().log("post/hardDeletePost",e);const t=await bl(e,!0);return _n.post(t)},approvePost:async e=>{const t=be();t.log("post/approvePost",e);const{data:n}=await t.http.post(`/api/v3/posts/${encodeURIComponent(e)}/approve`);Ze("post.approved",n),"community"===n.posts[0].targetType&&Ze("community.updated",n);const r=Vt(n,"communityUsers"),s=t.cache&&Date.now();return t.cache&&Kt(r,{cachedAt:s}),{data:_n.post(r.posts.find((t=>t.postId===e))),cachedAt:s}},declinePost:async e=>{const t=be();t.log("post/declinePost",e);const{data:n}=await t.http.post(`/api/v3/posts/${encodeURIComponent(e)}/decline`);"community"===n.posts[0].targetType&&Ze("community.updated",n),Ze("post.declined",n);const r=Vt(n,"communityUsers"),s=t.cache&&Date.now();return t.cache&&Kt(r,{cachedAt:s}),{data:_n.post(n.posts.find((t=>t.postId===e))),cachedAt:s}},flagPost:async(t,n)=>{const r=be();r.log("post/flagPost",t);const s=n&&Object.entries(e.ContentFlagReasonEnum).some((([t,r])=>t!==e.ContentFlagReasonEnum.Others&&r===n)),a={reason:n&&s?n:e.ContentFlagReasonEnum.Others,detail:n&&!s?n:""},{data:o}=await r.http.post(`/api/v3/posts/${encodeURIComponent(t)}/flag`,a);return r.cache&&Kt(Vt(o,"communityUsers")),Ze("post.flagged",o),!!o},unflagPost:async e=>{const t=be();t.log("post/unflagPost",e);const{data:n}=await t.http.delete(`/api/v3/posts/${encodeURIComponent(e)}/unflag`);return t.cache&&Kt(Vt(n,"communityUsers")),Ze("post.unflagged",n),!!n},isPostFlaggedByMe:async e=>{const t=be();t.log("post/isPostFlaggedByMe",e);const{data:{result:n}}=await t.http.get(`/api/v3/posts/${e}/isflagbyme`);return n},onPostCreated:Ko,onPostUpdated:$o,onPostDeleted:zo,onPostApproved:Qo,onPostDeclined:Vo,onPostFlagged:Ho,onPostUnflagged:Wo,onPostReactionAdded:Jo,onPostReactionRemoved:Go,getPost:(e,t)=>$a(e,(e=>{const{data:n}=e;t(Object.assign(Object.assign({},e),{data:n?_n.post(e.data):n}))}),"postId",Io,[Qo,Vo,xl,Dl,t=>zo((n=>{var r;let s=n;if(n.parentPostId===e&&n.isDeleted){const e=null===(r=Ie(["post","get",n.parentPostId]))||void 0===r?void 0:r.data;e&&(e.children=e.children.filter((e=>e!==n.postId)),Se(["post","get",e.postId],e),s=e)}t(s)})),Ho,e=>Jo((t=>{e(t)})),e=>Go((t=>{e(t)})),Wo,$o,Ul,Nl,ao((t=>Xo((async n=>{n.referenceId===e&&(await Io(e),t(n))}))),"referenceId","post"),ao((t=>ti((async n=>{n.referenceId===e&&(await Io(e),t(n))}))),"referenceId","post")]),getPosts:(e,t,n)=>{const{log:r,cache:s}=be();s||console.log(N);const a=Date.now();r(`getPosts(tmpid: ${a}) > listen`);const o=new Kl(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>Te(c))),()=>{r(`getPosts(tmpid: ${a}) > dispose`),i.forEach((e=>e()))}},getPinnedPosts:(e,t,n)=>{const{log:r,cache:s}=be();s||console.log(N);const a=Date.now();r(`getPinnedPosts(tmpid: ${a}) > listen`);const o=new Ql(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>Te(c))),()=>{r(`getPinnedPosts(tmpid: ${a}) > dispose`),i.forEach((e=>e()))}},getGlobalPinnedPosts:(e,t,n)=>{const{log:r,cache:s}=be(),a=Date.now();r(`getGlobalPinnedPosts(tmpid: ${a}) > listen`);const o=new Wl(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>Te(c))),()=>{r(`getGlobalPinnedPosts(tmpid: ${a}) > dispose`),i.forEach((e=>e()))}},semanticSearchPosts:(e,t,n)=>{const{log:r,cache:s}=be();s||console.log(N);const a=Date.now();r(`semanticSearchPosts(tmpid: ${a}) > listen`);const o=new Xl(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>Te(c))),()=>{r(`semanticSearchPosts(tmpid: ${a}) > dispose`),i.forEach((e=>e()))}}});const td=async e=>{const t=be();t.log("stream/getStream",e);const{data:n}=await t.http.get(`/api/v3/video-streaming/${e}`),r=t.cache&&Date.now();t.cache&&Kt(n,{cachedAt:r});const{videoStreamings:s}=n;return{data:s.find((t=>t.streamId===e)),cachedAt:r}};td.locally=e=>{const t=be();if(t.log("stream/getStream",e),!t.cache)return;const n=Ie(["stream","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const nd=e=>{const t=be();return Ye(t,"stream/onStreamStarted","video-streaming.didStart",(t=>{Kt(t),e(t.videoStreamings[0])}))},rd=e=>{const t=be();return Ye(t,"stream/onStreamStropped","video-streaming.didStop",(t=>{Kt(t),e(t.videoStreamings[0])}))},sd=e=>{const t=be();return Ye(t,"stream/onStreamRecorded","video-streaming.didRecord",(t=>{Kt(t),e(t.videoStreamings[0])}))},ad=e=>{const t=be();return Ye(t,"stream/onStreamFlagged","video-streaming.didFlag",(t=>{Kt(t),e(t.videoStreamings[0])}))},od=e=>{const t=be();return Ye(t,"stream/onStreamTerminated","video-streaming.didTerminate",(t=>{Kt(t),e(t.videoStreamings[0])}))},id=(e,t)=>$a(e,(e=>{const{data:n}=e;t(Object.assign(Object.assign({},e),{data:n?_n.stream(e.data):n}))}),"streamId",td,[sd,nd,rd,ad,od]);id.locally=e=>{const t=be();if(t.log("stream/getStreamById",e),!t.cache)return;const n=Ie(["stream","get",e]);return n?{data:_n.stream(n.data),cachedAt:n.cachedAt}:void 0};const cd=async e=>{const t=be();t.log("stream/queryStreams",e);const n=null!=e?e:{},{page:r,limit:s}=n,a=zt(n,["page","limit"]),o=r?{token:r}:s?{limit:s}:void 0,{data:i}=await t.http.get("/api/v3/video-streaming",{params:Object.assign(Object.assign({},a),{options:o})}),{paging:c,results:l}=i,{videoStreamings:d}=l,u=t.cache&&Date.now();return t.cache&&Kt(l,{cachedAt:u}),{data:d,cachedAt:u,paging:c}};var ld=Object.freeze({__proto__:null,createStream:async e=>{const t=be();t.log("stream/createStream",e);const{data:n}=await t.http.post("/api/v3/video-streaming",e),r=t.cache&&Date.now();t.cache&&Kt(n,{cachedAt:r});const{videoStreamings:s}=n;return{data:_n.stream(s[0]),cachedAt:r}},updateStream:async(e,t)=>{const n=be();n.log("stream/updateStream",e,t);const{data:r}=await n.http.put(`/api/v3/video-streaming/${e}`,t),s=n.cache&&Date.now();n.cache&&Kt(r,{cachedAt:s});const{videoStreamings:a}=r;return{data:_n.stream(a.find((t=>t.streamId===e))),cachedAt:s}},deleteStream:async e=>{const t=be();t.log("stream/deleteStream",e);const n=await td(e),{data:r}=await t.http.delete(`/api/v3/video-streaming/${e}`),{success:s}=r,a=Object.assign(Object.assign({},n.data),{isDeleted:!0});return ke(["stream","get",e],a),s},disposeStream:async e=>{const t=be();t.log("stream/disposeStream",e);const{data:n}=await t.http.delete(`/api/v3/video-streaming/${e}/streaming-url`),r=t.cache&&Date.now();t.cache&&Kt(n,{cachedAt:r});const{videoStreamings:s}=n;return{data:s.find((t=>t.streamId===e)),cachedAt:r}},onStreamStarted:nd,onStreamStopped:rd,onStreamRecorded:sd,onStreamFlagged:ad,onStreamTerminated:od,getStreamById:id,getStreams:(e,t,n)=>{const{log:r,cache:s}=be();s||console.log(N);const a=Date.now();r(`getStreams(tmpid: ${a}) > listen`);const{limit:o}=e,i=zt(e,["limit"]),c=null!=o?o:x,{policy:l=D}=null!=n?n:{},d=[],u=["streams","collection",e],h=t=>{let n=Oe(t,"isDeleted",e.isDeleted);return n=n.sort("lastCreated"===e.sortBy?qe:Ne),n},p=(e,n=!1)=>{var r,s;const a=null!==(r=e.data.map((e=>Ie(["stream","get",e]))).filter(Boolean).map((({data:e})=>e)))&&void 0!==r?r:[];t({onNextPage:m,data:n?h(a):a,hasNextPage:!!(null===(s=e.params)||void 0===s?void 0:s.page),loading:e.loading,error:e.error})},f=e=>e=>{var t;const n=null===(t=Ie(u))||void 0===t?void 0:t.data;n&&(n.data=[...new Set([e.streamId,...n.data])],Se(u,n),p(n,!0))},m=(e=!1)=>{var t,n;const r=null===(t=Ie(u))||void 0===t?void 0:t.data,s=null!==(n=null==r?void 0:r.data)&&void 0!==n?n:[];if(!e&&s.length>0&&!(null==r?void 0:r.params.page))return;const a=ae(cd,Object.assign(Object.assign({},i),{limit:e?c:void 0,page:e||null==r?void 0:r.params.page}));ie(a,(({data:e,error:t,loading:n,paging:r})=>{const a={loading:n,error:t,params:{page:null==r?void 0:r.next},data:s};e&&(a.data=[...new Set([...s,...e.map(de("stream"))])]),Se(u,a),p(a)}),oe(l))};return d.push(sd(f()),nd(f()),rd(f())),m(!0),()=>{r(`getStreams(tmpid: ${a}) > dispose`),d.forEach((e=>e()))}}});const dd=async e=>{const t=be();t.log("poll/getPoll",e);const{data:n}=await t.http.get(`/api/v3/polls/${e}`),r=t.cache&&Date.now();t.cache&&Kt(n,{cachedAt:r});const{polls:s}=n;return{data:s.find((t=>t.pollId===e)),cachedAt:r}};dd.locally=e=>{const t=be();if(t.log("poll/getPoll",e),!t.cache)return;const n=Ie(["poll","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const ud=e=>{const t=be();return Ye(t,"poll/onPollUpdated","poll.updated",(n=>{t.cache&&Kt(n),e(n.polls[0])}))},hd=e=>{const t=be();return Ye(t,"poll/onPollDeleted","poll.deleted",(n=>{t.cache&&Kt(n),e(n.polls[0])}))};var pd=Object.freeze({__proto__:null,createPoll:async e=>{const t=be();t.log("post/createPoll",e);const{data:n}=await t.http.post("/api/v3/polls",e),r=t.cache&&Date.now();t.cache&&Kt(n,{cachedAt:r});const{polls:s}=n;return{data:s[0],cachedAt:r}},closePoll:async e=>{const t=be();t.log("user/closePoll",e);const{data:n}=await t.http.put(`/api/v3/polls/${encodeURIComponent(e)}`,{status:"closed"}),r=t.cache&&Date.now();t.cache&&Kt(n,{cachedAt:r}),Ze("poll.updated",n);const{polls:s}=n;return{data:s.find((t=>t.pollId===e)),cachedAt:r}},deletePoll:async e=>{const t=be();t.log("poll/deletePoll",e);const n=await dd(e),{data:r}=await t.http.delete(`/api/v3/polls/${e}`),{success:s}=r,a=Object.assign(Object.assign({},n.data),{isDeleted:!0});return ke(["poll","get",e],a),Ze("poll.deleted",{polls:[a],users:[]}),s},votePoll:async(e,t)=>{const n=be();n.log("user/votePoll",e);const{data:r}=await n.http.post(`/api/v3/polls/${encodeURIComponent(e)}/votes`,{pollId:e,answerIds:t}),s=n.cache&&Date.now();n.cache&&Kt(r,{cachedAt:s});const{polls:a}=r;return Ze("poll.updated",r),{data:a.find((t=>t.pollId===e)),cachedAt:s}},onPollUpdated:ud,onPollDeleted:hd,getPoll:(e,t)=>$a(e,t,"pollId",dd,[ud,hd])});const fd={name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};function md(e){const n=new Uint8Array(e);let r="";return n.forEach((e=>{r+=String.fromCharCode(e)})),t.btoa(r)}function gd(e){const n=e.substring("-----BEGIN PRIVATE KEY-----".length,e.length-"-----END PRIVATE KEY-----".length),r=function(e){const t=new ArrayBuffer(e.length),n=new Uint8Array(t);for(let t=0,r=e.length;t<r;t+=1)n[t]=e.charCodeAt(t);return t}(t.atob(n));return crypto.subtle.importKey("pkcs8",r,fd,!1,["sign"])}async function yd({bufferCurrentUsage:e,getActiveStreams:t,updateUsage:n,dispose:r}){const s=e();if(s.length)try{const n=(new Date).toISOString(),a=await async function({timestamp:e,streams:t}){const n=t.map((e=>Object.keys(e).sort().map((t=>`${t}=${e[t]}`)).join("&"))).join(";"),r=b.default.v4(),s=`nonceStr=${r}&timestamp=${e}&data=${n}==`,a=(new TextEncoder).encode(s),o=await gd("-----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-----");return{signature:md(await crypto.subtle.sign(fd,o,a)),nonceStr:r}}({timestamp:n,streams:s});if(!a||!a.signature)throw new Error("Signature is undefined");const o={signature:a.signature,nonceStr:a.nonceStr,timestamp:n,streams:s},i=be();return await i.http.post("/api/v3/user-event/video-streaming",o),t().length||e().length||r(),!0}catch(e){return s.forEach((e=>n(e))),!1}}class vd{constructor(){this._unsyncedData=[],this._syncBuffer=[],this._activeStreams=[],this._startInterval(),this._syncInterval=null}registerStream(e){this._activeStreams.push(e)}getActiveStreams(){return this._activeStreams}unregisterStream(e){this._activeStreams=this._activeStreams.filter((t=>t!==e))}updateUsage(e){this._unsyncedData.push(e)}bufferCurrentUsage(){const e=this._unsyncedData;return this._unsyncedData=[],e}dispose(){this._syncInterval&&clearInterval(this._syncInterval)}_startInterval(){this._syncInterval=setInterval((()=>{yd({bufferCurrentUsage:this.bufferCurrentUsage.bind(this),getActiveStreams:this.getActiveStreams.bind(this),updateUsage:this.updateUsage.bind(this),dispose:this.dispose.bind(this)})}),2e4)}}let bd=null;class wd{constructor(e,t){this.player=e,this.resolution=t,this._startTime=null,this._usageCollector=bd||(bd=new vd,bd),this._usageCollector.registerStream(e.id),this._sessionId=String(b.default.v4()),this._controller=new AbortController,this._observer=new MutationObserver((t=>{t.forEach((t=>{t.removedNodes.forEach((t=>{t===e&&this._unregisterEvents()}))}))}))}_resetStartTime(){this._startTime=Date.now()}_shouldUpdateCollector(){return!!this._startTime&&Date.now()-this._startTime>2e4}_sendUsageToCollector(){if(!this._startTime)return;const e=Date.now(),t=e-this._startTime,n=Math.round(t/1e3);n&&this._usageCollector.updateUsage({streamId:this.player.id,sessionId:this._sessionId,startTime:this._startTime?new Date(this._startTime).toISOString():null,endTime:new Date(e).toISOString(),watchSeconds:n,resolution:this.resolution})}registerEvents(){this.player.addEventListener("play",(()=>{this._startTime||this._resetStartTime()}),{signal:this._controller.signal}),this.player.addEventListener("playing",(()=>{this._startTime||this._resetStartTime()}),{signal:this._controller.signal}),this.player.addEventListener("timeupdate",(()=>{this._shouldUpdateCollector()&&(this._sendUsageToCollector(),this._resetStartTime())}),{signal:this._controller.signal}),this.player.addEventListener("pause",(()=>{this._sendUsageToCollector(),this._startTime=null}),{signal:this._controller.signal}),this.player.addEventListener("ended",(()=>{this._sendUsageToCollector(),this._startTime=null}),{signal:this._controller.signal})}_unregisterEvents(){this._usageCollector.unregisterStream(this.player.id),this._controller.abort(),this._observer.disconnect()}}var Cd=Object.freeze({__proto__:null,getPlayer:async e=>{const{streamId:t}=e;if(!document)throw new Error("This method can be invoked within the browser enviornment only");if(!C.default.isSupported())throw new Error("This browswer does not support hls, unable to play stream");const{data:n}=await td(t),{watcherUrl:r,status:s,recordings:a=[],resolution:o}=n;if(!r.hls)throw new Error("This stream does not support hls. Unable to play");const i=document.createElement("video");i.id=t,i.controls=!0;const c=new C.default;if(c.attachMedia(i),"recorded"!==s){let{url:e}=r.hls;e=e.replace("http:","https:"),c.loadSource(e)}else{const e=a.find((e=>!!e.mp4));if(!e||!e.mp4)throw new Error("No playable recording available");i.src=e.mp4.url}return new wd(i,o).registerEvents(),i}});const Id=e=>{const t=(e=>{var t;const n=be(),r=new Date,s=r.getTime()+31536e6,a=new Date(s).toISOString();let o=null===(t=Ie(["storyTarget","get",e.targetId]))||void 0===t?void 0:t.data;return o||(o={targetType:e.targetType,targetId:e.targetId,lastStoryExpiresAt:a,targetPublicId:e.targetId,targetUpdatedAt:r.toISOString()},Kt({storyTargets:[o]})),{stories:[Object.assign({createdAt:r.toISOString(),updatedAt:r.toISOString(),flagCount:0,hashFlag:null,reactions:{},reactionsCount:0,storyId:e.referenceId,path:"",creatorId:n.userId||"",creatorPublicId:n.userId||"",targetPublicId:e.targetId,comments:[],commentsCount:0,isDeleted:!1,hasFlaggedComment:!1,mentionedUsers:[],impression:0,reach:0,expiresAt:new Date(s).toISOString()},e)],categories:[],communityUsers:[],comments:[],files:[],users:[],communities:[]}})(e);return Kt(t),t},Sd=({payload:e,formData:t,isVideo:n=!1},r)=>{if(t){const s=t.getAll("files")[0]||void 0;if(!s)return;const a=Object.assign(Object.assign({},e),{data:Object.assign(Object.assign({},e.data),{fileId:void 0,fileData:s.uri})});return n&&(a.data.videoFileId={original:void 0}),r(Id(a))}return r(Id(Object.assign(Object.assign({},e),{data:Object.assign(Object.assign({},e.data),{fileData:null})})))},_d=async e=>{const t=be();t.log("post/createStory",e);const n=await t.http.post("/api/v4/stories",e),r=Cl(n.data);t.cache&&Kt(r),Se(["story-sync-state",e.targetId],"synced"),Ze("local.story.created",r);const s=t.cache&&Date.now();return{data:r.stories.length>0?r.stories[0]:void 0,cachedAt:s}},kd=async({targetId:e,targetType:t})=>{var n,r;if(!Ie(["storyTarget","get",e])){let s={targetId:e,targetType:t};if("community"===t){const t=await dc(e);s=Object.assign(Object.assign({},s),{targetPublicId:t.data.communityId,targetUpdatedAt:null!==(n=t.data.updatedAt)&&void 0!==n?n:(new Date).toISOString()})}if("user"===t){const t=await Ya(e);s=Object.assign(Object.assign({},s),{targetPublicId:t.data.userPublicId,targetUpdatedAt:null!==(r=t.data.updatedAt)&&void 0!==r?r:(new Date).toISOString()})}Se(["storyTarget","get",e],s)}},Td=e=>e?Ie(["story","get",e]):{data:void 0,cachedAt:void 0},Od=async(e,t=!1)=>{var n,r,s;const a=be();let o;if(a.log("story/deleteStory",e),a.cache&&(o=Td(e),null==o?void 0:o.data)){const{data:a}=o;if(Ze("local.story.deleted",{categories:[],comments:[],communities:[],communityUsers:[],files:[],users:[],stories:[Object.assign(Object.assign({},a),{isDeleted:!0})]}),"synced"!==a.syncState){t?Te(["story","get",e]):Se(["story","get",e],Object.assign(Object.assign({},o.data),{isDeleted:!0}));const r=null===(n=Ce(["story","get"]))||void 0===n?void 0:n.filter((e=>"synced"!==e.data.syncState&&e.data.targetId===a.targetId&&!0!==e.data.isDeleted));if(r&&r.length>0){const e=r.reduce(((e,t)=>{const n=new Date(t.data.expiresAt||0);return n>e?n:e}),new Date(0));Se(["story-expire",o.data.targetId],e.toISOString())}else Te(["story-expire",o.data.targetId]);return!0}const i=null===(r=Ie(["storyTarget","get",a.targetId]))||void 0===r?void 0:r.data,c=null===(s=Ce(["story","get"]))||void 0===s?void 0:s.filter((e=>"synced"===e.data.syncState&&e.data.targetId===a.targetId&&!0!==e.data.isDeleted));let l;c&&c.length>0&&(l=null==c?void 0:c.reduce(((e,t)=>{const n=new Date(t.data.expiresAt||0);return n>e?n:e}),new Date(0))),i&&Se(["storyTarget","get",a.targetId],Object.assign(Object.assign({},i),{lastStoryExpiresAt:l}))}return(await a.http.delete(`/api/v4/stories/${e}`,{params:{permanent:t}})).data.success},Ad=e=>{const t=be(),n=[Ye(t,"onStoryUpdated","story.updated",(async t=>{const n=Cl(t);Kt(n),e(n.stories)}))];return()=>{n.forEach((e=>e()))}},Ed=e=>{const t=be(),n=[Ye(t,"onStoryUpdated","local.story.updated",(async t=>{Kt(t),e(t.stories)}))];return()=>{n.forEach((e=>e()))}},Md=e=>{const t=be(),n=[Ye(t,"onStoryReactionAdded","story.reactionAdded",(async t=>{const{reactions:n}=t,r=zt(t,["reactions"]),s=Cl(r),a=Eo("story.reactionAdded",Object.assign(Object.assign({},s),{reactions:n}));Kt(a),e(a.stories)}))];return()=>{n.forEach((e=>e()))}},Rd=e=>{const t=be(),n=[Ye(t,"onStoryReactionAdded","local.story.reactionAdded",(async t=>{Kt({stories:[t.story]}),e([t.story])}))];return()=>{n.forEach((e=>e()))}},Pd=e=>{const t=be(),n=[Ye(t,"onStoryReactionRemoved","story.reactionRemoved",(async t=>{const{reactions:n}=t,r=zt(t,["reactions"]),s=Cl(r),a=Eo("story.reactionRemoved",Object.assign(Object.assign({},s),{reactions:n}));Kt(a),e(a.stories)}))];return()=>{n.forEach((e=>e()))}},jd=e=>{const t=be(),n=[Ye(t,"onStoryReactionRemoved","local.story.reactionRemoved",(async t=>{Kt({stories:[t.story]}),e([t.story])}))];return()=>{n.forEach((e=>e()))}},Ud=e=>{e.forEach((e=>{const t=Ie(["story-expire",e.targetId]),n=new Date(e.expiresAt||0);n<new Date((null==t?void 0:t.data)||0)||Se(["story-expire",e.targetId],n.toISOString())}))},xd=e=>{e.forEach((e=>{Se(["story-reference",e.storyId],e.referenceId)}))},Dd=async({targetType:e,targetId:t,options:n})=>{const r=be();r.log("story/getActiveStoriesByTarget");const s=r.cache&&Date.now(),a=await r.http.get("/api/v4/stories",{params:{targetType:e,targetId:t,options:{sortBy:(null==n?void 0:n.sortBy)||"createdAt",orderBy:(null==n?void 0:n.orderBy)||"desc"}}}),o=Cl(a.data);return r.cache&&(Kt(o),Ud(o.stories),xd(o.stories)),{data:o.stories,cachedAt:s,paging:{next:void 0,previous:void 0}}},Nd=e=>{const t=be(),n=[Ye(t,"onStoryCreated","story.created",(async t=>{const n=Cl(t,!0);Kt(n),e(n.stories)}))];return()=>{n.forEach((e=>e()))}},Bd=e=>{const t=be(),n=[Ye(t,"onStoryCreated","local.story.created",(async t=>{Kt(t),e(t.stories)}))];return()=>{n.forEach((e=>e()))}},qd=e=>{const t=be(),n=[Ye(t,"onStoryDeleted","story.deleted",(async t=>{const n=Cl(t);Kt(n),e(n.stories)}))];return()=>{n.forEach((e=>e()))}},Fd=e=>{const t=be(),n=[Ye(t,"onStoryDeleted","local.story.deleted",(async t=>{Kt(t),e(t.stories)}))];return()=>{n.forEach((e=>e()))}},Ld=e=>{const t=be();return Ye(t,"onStoryError","local.story.error",(async t=>{Kt(t),e(t.stories)}))},Kd=e=>t=>e((e=>t(e[0]))),$d=async e=>{const t=be();t.log("story/getTargetsByTargetIds",e);const n=await t.http.get("/api/v4/stories/seen",{params:{targets:e}}),{data:r}=n;return t.cache&&Kt(n.data),{data:r.storyTargets,cachedAt:Date.now()}};class zd extends Pa{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.paginationController=r}saveToMainDB(e){const t=be(),n=t.cache&&Date.now(),r=Cl(e);t.cache&&(Kt(r,{cachedAt:n}),Ud(r.stories),xd(r.stories))}getStoryReferenceIds(e){return(null==e?void 0:e.referenceId)?e.referenceId:e.storyId}appendToQueryStream(e,t,n=!1){var r,s;if(n)Se(this.cacheKey,{data:e.stories.map(this.getStoryReferenceIds)});else{const t=null===(r=Ie(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];Se(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.stories.map(this.getStoryReferenceIds)])]}))}}reactor(e){return e=>{var t;const n=null===(t=Ie(this.cacheKey))||void 0===t?void 0:t.data;if(!n)return;const r=e.map((({referenceId:e})=>e));n.data=[...new Set([...r,...n.data])],Se(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1})}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class Qd extends xa{async getRequest(e){const{data:t}=await this.http.get("/api/v4/stories-by-targets",{params:Object.assign({},e)});return t}}class Vd extends Da{constructor(e,t){const n=w.default(e),r=["story-target-ids","collection",n],s=new Qd(e);super(s,n,r,t),this.query=e,this.queryStreamController=new zd(this.query,this.cacheKey,this.notifyChange.bind(this),s),this.paginationController=s,this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Ie(this.cacheKey))||void 0===e?void 0:e.data)||Se(this.cacheKey,{data:[],params:{}})}persistModel(e){this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}notifyChange({origin:e,loading:t,error:n}){var r;const s=null===(r=Ie(this.cacheKey))||void 0===r?void 0:r.data;if(!s)return;let a=s.data.map((e=>Ie(["story","get",e]))).filter(Boolean).map((e=>_n.story(e.data)));(this.shouldNotify(a)||"event"!==e)&&(a=this.applyFilter(a),this.callback({onNextPage:void 0,data:a,hasNextPage:!1,loading:t,error:n}))}applyFilter(e){var t,n;const r=e;return"asc"===((null===(n=null===(t=this.query)||void 0===t?void 0:t.options)||void 0===n?void 0:n.orderBy)||"desc")?r.sort(Ne):r.sort(qe)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:Nd,action:"onCreate"},{fn:Ad,action:"onUpdate"},{fn:qd,action:"onDelete"},{fn:Ld,action:"onError"}])}}const Hd=(e,t)=>{var n,r;const s=null===(n=Ie(e))||void 0===n?void 0:n.data,a=null!==(r=null==s?void 0:s.data)&&void 0!==r?r:[];Se(e,Object.assign(Object.assign({},s),{data:[...new Set([...a,...t])]}))};class Wd extends Pa{constructor(e,t,n,r,s){super(e,t),this.notifyChange=n,this.paginationController=r,this.preparePayload=s}saveToMainDB(e){const t=be(),n=t.cache&&Date.now(),r=this.preparePayload(e);t.cache&&Kt(r,{cachedAt:n})}appendToQueryStream(e,t,n=!1){n?Se(this.cacheKey,{data:e.storyTargets.map((({targetId:e})=>e))}):Hd(this.cacheKey,e.storyTargets.map((({targetId:e})=>e)))}reactor(e){return t=>{"onCreate"===e&&"seen"!==this.query.seenState&&Hd(this.cacheKey,t.map((({targetId:e})=>e))),this.notifyChange({origin:"event",loading:!1})}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class Jd extends Ma{constructor(){super(...arguments),this.smartFilterState="unseen"}async getRequest(e,t){var n;const{limit:r=10,seenState:s="unseen"}=e,a=await this.createRequest({seenState:"smart"===s?this.smartFilterState:s,limit:r,token:t});if(null===(n=a.paging)||void 0===n?void 0:n.next)return a;if("smart"!==s)return a;if("seen"===this.smartFilterState)return a;this.smartFilterState="seen";const o=await this.createRequest({seenState:this.smartFilterState,limit:r});return c=o,{categories:(i=a).categories.concat(c.categories),communities:i.communities.concat(c.communities),communityUsers:i.communityUsers.concat(c.communityUsers),files:i.files.concat(c.files),storyTargets:i.storyTargets.concat(c.storyTargets),users:i.users.concat(c.users),paging:c.paging};var i,c}async createRequest(e){const{data:t}=await this.http.get("/api/v5/me/global-story-targets",{params:e});return n=t,r=e.seenState,Object.assign(Object.assign({},n),{storyTargets:n.storyTargets.map((e=>Object.assign(Object.assign({},e),{localFilter:r})))||[]});var n,r}}class Gd extends Da{constructor(e,t){const n=w.default(e),r=["story-global-feed","collection",n],s=new Jd(e);super(s,n,r,t),this.query=e,this.queryStreamController=new Wd(this.query,this.cacheKey,this.notifyChange.bind(this),s,(e=>{const t=zt(Uo(Object.assign(Object.assign({},e),{feeds:[]})),["feeds"]);return Object.assign(Object.assign({},e),t)})),this.paginationController=s,this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Ie(this.cacheKey))||void 0===e?void 0:e.data)||Se(this.cacheKey,{data:[],params:{}})}persistModel(e){this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}notifyChange({origin:e,loading:t,error:n}){var r;const s=null===(r=Ie(this.cacheKey))||void 0===r?void 0:r.data;if(!s)return;const a=s.data,o=Ce(["storyTarget"]);o&&(null==o?void 0:o.length)>0&&(null==o||o.forEach((({key:e})=>{s.data.includes(e[2])||a.push(e[2])})));let i=a.map((e=>Ie(["storyTarget","get",e]))).filter(Boolean).map((e=>_n.storyTarget(e.data)));(this.shouldNotify(i)||"event"!==e)&&(i=this.applyFilter(i).filter((({localSortingDate:e})=>!!e)).map((e=>zt(e,["localFilter","localLastExpires","localLastSeen","localSortingDate"]))),this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n}))}applyFilter(e){if("smart"!==this.query.seenState)return e.filter((({hasUnseen:e})=>"all"===this.query.seenState||("seen"===this.query.seenState&&!e||"unseen"===this.query.seenState&&e))).sort(Be);const t=e.reduce(((e,t)=>("unseen"===t.localFilter?e.unseen.push(t):"seen"===t.localFilter?e.seen.push(t):e.unknown.push(t),e)),{unseen:[],seen:[],unknown:[]}),n=t.unknown.sort(Be)||[],r=t.unseen.sort(Be)||[],s=t.seen.sort(Be)||[];return n.concat(r,s)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:Nd,action:"onCreate"},{fn:Ad,action:"onUpdate"},{fn:qd,action:"onDelete"},{fn:Bd,action:"onCreate"},{fn:Ed,action:"onUpdate"},{fn:Fd,action:"onDelete"},{fn:Ld,action:"onError"}])}}var Yd=Object.freeze({__proto__:null,createImageStory:async(e,t,n,r={},s="fit",a=[])=>{if(!n.getAll("files").length)throw new Error("The formData object must have a `files` key.");let o={data:{text:"",fileId:void 0,fileData:null,imageDisplayMode:s},syncState:"syncing",referenceId:xt(),dataType:"image",items:a,targetType:e,targetId:t,metadata:r};const i=new Date;Se(["story-sync-state",t],"syncing"),Se(["story-expire",t],new Date(i.setFullYear(i.getFullYear()+1))),Sd({payload:o,formData:n},(e=>{Ze("local.story.created",e)}));try{const{data:r}=await go(n);if(0===r.length)throw new Error("Failed to upload image");const{fileId:s}=r[0];o=Object.assign(Object.assign({},o),{data:Object.assign(Object.assign({},o.data),{fileId:s})}),kd({targetId:t,targetType:e}),Sd({payload:o,formData:n},(e=>{Ze("local.story.created",e)}));const a=await _d(o);return a.data?Object.assign(Object.assign({},a),{data:_n.story(a.data)}):a}catch(e){throw Se(["story-sync-state",t],"error"),Sd({payload:Object.assign(Object.assign({},o),{syncState:"error"}),formData:n},(e=>{Ze("local.story.error",e)})),e}},createVideoStory:async(e,t,n,r={},s=[])=>{if(!n.getAll("files").length)throw new Error("The formData object must have a `files` key.");let a={data:{text:"",fileId:void 0,fileData:null},syncState:"syncing",referenceId:xt(),dataType:"video",items:s,targetType:e,targetId:t,metadata:r};const o=new Date;Se(["story-sync-state",t],"syncing"),Se(["story-expire",t],new Date(o.setFullYear(o.getFullYear()+1))),kd({targetId:t,targetType:e}),Sd({payload:a,formData:n,isVideo:!0},(e=>{Ze("local.story.created",e)}));try{const{data:e}=await mo(n,M.STORY);if(0===e.length)throw new Error("Failed to upload video");const{fileId:t}=e[0];a=Object.assign(Object.assign({},a),{data:Object.assign(Object.assign({},a.data),{fileId:t,videoFileId:{original:t}})}),Sd({payload:a,formData:n,isVideo:!0},(e=>{Ze("local.story.created",e)}));const r=await _d(a);return r.data?Object.assign(Object.assign({},r),{data:_n.story(r.data)}):r}catch(e){throw Se(["story-sync-state",t],"error"),Sd({payload:Object.assign(Object.assign({},a),{syncState:"error"}),formData:n,isVideo:!0},(e=>{Ze("local.story.error",e)})),e}},hardDeleteStory:async e=>await Od(e,!0),softDeleteStory:async e=>await Od(e),getActiveStoriesByTarget:(e,t)=>{const{log:n,cache:r}=be(),s=[],a=["story-target","collection",e],o=Date.now();n(`getActiveStoriesByTarget(tmpid: ${o}) > listen`),r||console.log(N);const i=t=>{var n,r;const s=(null===(n=e.options)||void 0===n?void 0:n.sortBy)||"createdAt",a=(null===(r=e.options)||void 0===r?void 0:r.orderBy)||"desc";return 0===t.length?[]:"createdAt"===s?"asc"===a?t.sort(Ne):t.sort(qe):"asc"===a?t.sort(Fe):t.sort(Le)},c=e=>{var n;const r=e.data.map((e=>{const t=Td(e);if(null==t?void 0:t.data)return _n.story(t.data)})).filter(Boolean).filter((e=>!!e&&!e.isDeleted)),s=[];if(r.length>0){const e=r.reduce(((e,t)=>{if(!t)return e;const{syncState:n}=t;if(!n)return e;let r=e.get(n);return r||(r=[]),r.push(t),e.set(n,r),e}),new Map);if(e.has("error")){const t=i(e.get("error")||[]);s.push(...t)}if(e.has("syncing")){const t=i(e.get("syncing")||[]);s.push(...t)}if(e.has("synced")){const t=i(e.get("synced")||[]);s.push(...t)}}t({onNextPage:()=>!1,data:s||r,hasNextPage:!!(null===(n=e.params)||void 0===n?void 0:n.page),loading:e.loading||!1})},l=(t,n,r=!1,s=!1,o=!1)=>{var i;const l=Ie(a),d={loading:s,error:o,params:{page:void 0},data:(null==l?void 0:l.data)||[]};if(t)if("onDelete"===n){const e=t.map((({referenceId:e})=>e));d.data=d.data.filter((t=>!e.includes(t)))||[]}else d.data=r?t.map(de("story")):[...new Set([...d.data,...t.map(de("story"))])];const u=null===(i=Ce(["story","get"]))||void 0===i?void 0:i.filter((t=>t.data.targetId===e.targetId&&"synced"!==t.data.syncState)).map((e=>de("story")(e.data)));u&&(null==u?void 0:u.length)>0&&u.forEach((e=>{d.data.includes(e)||d.data.push(e)})),Se(a,d.data),c(d)},d=e=>t=>{l(t,e)};return(t=>{const n=ae(Dd,e);ie(n,(({data:e,error:n,loading:r})=>{l(e,"fetch",t,r,n)}))})(!0),s.push(Nd(d("onCreate")),Ad(d("onUpdate")),qd(d("onDelete")),Md(d("onReactionAdded")),Pd(d("onReactionRemoved")),Ld(d("onError")),Bd(d("onCreate")),Ed(d("onUpdate")),Fd(d("onDelete")),Rd(d("onReactionAdded")),jd(d("onReactionRemoved")),(e=>{const t=be();return Ye(t,"onStoryLocalDataUpdated","local.story.reload",(t=>{e(t)}))})((e=>{const t=Ie(a);if(!t)return;if(0===e.referenceIds.length||0===(null==t?void 0:t.data.length))return;if(!(null==t?void 0:t.data.find((t=>e.referenceIds.includes(t)))))return;const n={loading:!1,error:!1,params:{page:void 0},data:(null==t?void 0:t.data)||[]};c(n)})),(()=>Te(a))),()=>{n(`getActiveStoriesByTarget(tmpid: ${o}) > dispose`),s.forEach((e=>e()))}},getStoryByStoryId:(e,t)=>$a(e,(e=>{(null==e?void 0:e.data)?t(Object.assign(Object.assign({},e),{data:_n.story(e.data)})):t(e)}),"storyId",Il,[Kd(Ad),Kd(qd),Kd(Md),Kd(Pd),Kd(Ld),Kd(Ed),Kd(Fd),Kd(Rd),Kd(jd)]),getTargetById:(e,t)=>$a(e,(e=>{(null==e?void 0:e.data)?t(Object.assign(Object.assign({},e),{data:_n.storyTarget(e.data[0])})):t(e)}),"query",(e=>$d([e])),[]),getTargetsByTargetIds:(e,t)=>{const{log:n,cache:r}=be(),s=[],a=["storyTargets","collection",e],o=Date.now();n(`getTargetsByTargetIds(tmpid: ${o}) > listen`),r||console.log(N);const i=(e,n=!1,r=!1,s=!1)=>{const o=Ie(a),i={loading:r,error:s,params:{page:void 0},data:[]};e&&(i.data=n?e.map(de("storyTarget")):[...new Set([...(null==o?void 0:o.data)||[],...e.map(de("storyTarget"))])]),Se(a,i.data),(e=>{var n;const r=e.data.map((e=>{const t=Ie(["storyTarget","get",e]);if(null==t?void 0:t.data)return _n.storyTarget(t.data)})).filter(Boolean);t({onNextPage:void 0,data:r,hasNextPage:!!(null===(n=e.params)||void 0===n?void 0:n.page),loading:e.loading||!1})})(i)};return(t=>{const n=ae($d,e);ie(n,(({data:e,error:n,loading:r})=>{i(e,t,r,n)}))})(!0),s.push((()=>Te(a))),()=>{n(`getTargetsByTargetIds(tmpid: ${o}) > dispose`),s.forEach((e=>e()))}},getStoriesByTargetIds:(e,t,n)=>{const{log:r,cache:s,userId:a}=be();s||console.log(N);const o=Date.now();r(`getStoriesByTargetIds(tmpid: ${o}) > listen`);const i=new Vd(e,t),c=i.startSubscription(),l=i.getCacheKey();return c.push((()=>{Te(l)})),()=>{r(`getStoriesByTargetIds(tmpid: ${o}) > dispose`),c.forEach((e=>e()))}},getGlobalStoryTargets:(e,t,n)=>{const{log:r,cache:s,userId:a}=be();s||console.log(N);const o=Date.now();r(`getGlobalStoryTarget(tmpid: ${o}) > listen`);const i=new Gd(e,t),c=i.startSubscription(),l=i.getCacheKey();return c.push((()=>{Te(l)})),()=>{r(`getGlobalStoryTarget(tmpid: ${o}) > dispose`),c.forEach((e=>e()))}}});const Zd=e=>Object.assign(Object.assign({},e),{endAt:e.endAt?e.endAt:null}),Xd=e=>Object.assign({},e);var eu=Object.freeze({__proto__:null,getNetworkAds:async()=>{const e=be(),{data:t}=await e.http.get("/api/v1/ads/me"),n=t.ads.map(Zd),r=t.advertisers.map(Xd);return Kt({ads:n,advertisers:r,files:t.files}),Se(["ad","setting"],t.settings),{ads:n.map(_n.ad),settings:t.settings}}});const tu=async()=>{const e=be();e.log("notificationTray/getNotificationTraySeen",{});const{data:t}=await e.http.get("api/v1/notification-tray/tray/seen"),n=e.cache&&Date.now();if(e.cache){const n=["notificationTraySeen","get",e.userId];Se(n,{userId:e.userId,lastTraySeenAt:t.lastTraySeenAt,lastTrayOccuredAt:t.lastTrayOccurredAt})}return{data:{userId:e.userId,lastTraySeenAt:t.lastTraySeenAt,lastTrayOccurredAt:t.lastTrayOccurredAt,isSeen:t.lastTraySeenAt>t.lastTrayOccurredAt},cachedAt:n}};tu.locally=()=>{var e;const t=be();if(t.log("notificationTray/getNotificationTraySeen.locally",{}),!t.cache)return;const{data:n,cachedAt:r}=null!==(e=Ie(["notificationTraySeen","get"]))&&void 0!==e?e:{};return n?{data:n,cachedAt:r}:void 0};const nu=e=>{const t=be(),n=[Ye(t,"onNotificationTraySeenUpdated","local.notificationTraySeen.updated",(t=>e(t)))];return()=>{n.forEach((e=>e()))}};class ru extends Ma{async getRequest(e,t){const{limit:n=x}=e,r=zt(e,["limit"]),s=t?{token:t}:{limit:n},{data:a}=await this.http.get("/api/v1/notification-tray",{params:Object.assign(Object.assign({},r),{options:s})});return a}}class su extends Pa{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=be(),r=n.cache&&Date.now();n.cache&&Kt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,s;if(n)Se(this.cacheKey,{data:e.notificationTrayItems.map(de("notificationTrayItem"))});else{const t=null===(r=Ie(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(s=null==t?void 0:t.data)&&void 0!==s?s:[];Se(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.notificationTrayItems.map(de("notificationTrayItem"))])]}))}}}const au=e=>{const t=e.users.map(er);return Object.assign(Object.assign({},e),{users:t})};class ou extends Da{constructor(e,t){const n=w.default(e),r=["notificationTrayItem","collection",n];super(new ru(e),n,r,t),this.query=e,this.queryStreamController=new su(this.query,this.cacheKey,this.notifyChange.bind(this),au),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Ie(this.cacheKey))||void 0===e?void 0:e.data)||Se(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return[]}notifyChange({origin:e,loading:t,error:n}){var r,s;const a=null===(r=Ie(this.cacheKey))||void 0===r?void 0:r.data;if(!a)return;const o=(null!==(s=a.data.map((e=>Ie(["notificationTrayItem","get",e]))).filter(dn).map((({data:e})=>e)))&&void 0!==s?s:[]).map(_n.notificationTray);(this.shouldNotify(o)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:o,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}}var iu=Object.freeze({__proto__:null,getNotificationTraySeen:e=>{const{userId:t}=ze();return $a(t,e,"userId",tu,[nu],{callbackDataSelector:e=>{let t=!0;return(null==e?void 0:e.lastTrayOccurredAt)&&(t=!!e.lastTraySeenAt&&Hn(e.lastTraySeenAt)>Hn(e.lastTrayOccurredAt)),{lastTrayOccurredAt:null==e?void 0:e.lastTrayOccurredAt,lastTraySeenAt:null==e?void 0:e.lastTraySeenAt,isSeen:t}}})},getNotificationTrayItems:(e,t,n)=>{const{log:r,cache:s}=be();s||console.log(N);const a=Date.now();r(`getNotificationTrayItems(tmpid: ${a}) > listen`);const o=new ou(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>Te(c))),()=>{r(`getNotificationTrayItems(tmpid: ${a}) > dispose`),i.forEach((e=>e()))}},markItemsSeen:async e=>{const t=be();t.log("notificationTray/markItemsSeen",{});const{data:n}=await t.http.post("api/v1/notification-tray/items/seen",{trayItems:e.map((e=>({id:e.id,lastSeenAt:e.lastSeenAt})))}),r=n.trayItems.map((e=>{var n;const r=null===(n=Ie(["notificationTrayItem","get",e.id]))||void 0===n?void 0:n.data;if(!r)return;const s=Object.assign(Object.assign({},r),{lastSeenAt:e.lastSeenAt});if(t.cache){const e=Date.now();Se(["notificationTrayItem","get"],s,{cachedAt:e})}return s})).filter(Boolean);Ze("local.notificationTrayItem.updated",{notificationTrayItems:r})},markTraySeen:async e=>{var t;const n=be();n.log("notificationTray/markTraySeen",{});const{data:r}=await n.http.post("api/v1/notification-tray/tray/seen",{lastSeenAt:e}),s=null===(t=Ie(["notificationTraySeen","get"]))||void 0===t?void 0:t.data,a={userId:n.userId,lastTraySeenAt:r.lastSeenAt},o=Object.assign(Object.assign({},s),a),i=n.cache&&Date.now();return n.cache&&Se(["notificationTraySeen","get",n.userId],o,{cachedAt:i}),Ze("local.notificationTraySeen.updated",a),{data:r,cachedAt:i}},onNotificationTraySeenUpdated:nu});return e.API_REGIONS=vt,e.AdRepository=eu,e.CategoryRepository=fl,e.ChannelRepository=ic,e.Client=da,e.CommentRepository=jl,e.CommunityPostSettingMaps=A,e.CommunityPostSettings=O,e.CommunityRepository=ul,e.ContentFeedType=M,e.DefaultCommunityPostSetting=E,e.FeedRepository=yl,e.FileRepository=yo,e.FileType=I,e.LiveStreamPlayer=Cd,e.MessageContentType=P,e.MessageRepository=Bi,e.PollRepository=pd,e.PostContentType=j,e.PostRepository=ed,e.ReactionRepository=ui,e.StoryRepository=Yd,e.StreamRepository=ld,e.SubChannelRepository=Qi,e.UserRepository=po,e.VERSION=U,e.VideoResolution=S,e.VideoSize=k,e.VideoTranscodingStatus=_,e.backupCache=async(e="amitySdk",t=(e=>e.offline))=>{const{log:n,cache:r,userId:s}=be();if(!r)return!1;n("cache/api/backupCache",{storageKey:e});const a=Object.fromEntries(Object.entries(r.data).filter((([e,n])=>t(n))));return!!Object.keys(a).length&&(localStorage&&await localStorage.setItem(`${e}#${s}`,JSON.stringify(a)),!0)},e.createQuery=ae,e.createReport=async(e,t)=>{const n=be();return n.log("report/createReport",{referenceType:e,referenceId:t}),"user"===e?(async({client:e,referenceId:t})=>{const{data:n}=await e.http.post(`/api/v4/me/flags/${encodeURIComponent(t)}`);if(e.cache){const e=await $r(n);Kt(e)}return Ze("user.flagged",n),!!n})({client:n,referenceId:t}):"message"===e?(async({client:e,referenceId:t})=>{const{data:n}=await e.http.post(`/api/v5/messages/${encodeURIComponent(t)}/flags`);if(e.cache){const e=await Fn(n);Kt(e)}return Ze("message.flagged",n),!!n})({client:n,referenceId:t}):"post"===e?(async({client:e,referenceId:t})=>{const{data:n}=await e.http.post(`/api/v3/posts/${encodeURIComponent(t)}/flag`);if(e.cache){const e=await Bo(n);Kt(e)}return Ze("post.flagged",n),!!n})({client:n,referenceId:t}):"comment"===e&&(async({client:e,referenceId:t})=>{const{data:n}=await e.http.post(`/api/v3/comments/${encodeURIComponent(t)}/flag`);if(e.cache){const e=await hi(n);Kt(e)}return Ze("comment.flagged",n),!!n})({client:n,referenceId:t})},e.createUserToken=async(e,t,n)=>{const r=await Nt(),s=Bt(),a=Ot(wt("http",t)),{data:o}=await a.post("/api/v5/sessions",Object.assign(Object.assign({},n),{deviceId:r,deviceInfo:Object.assign(Object.assign({},s),{model:"token management API on TS-SDK"})}),{headers:{"X-API-Key":e}});return{accessToken:o.accessToken}},e.deleteReport=async(e,t)=>{const n=be();return n.log("report/deleteReport",{referenceType:e,referenceId:t}),"user"===e?(async({client:e,referenceId:t})=>{const{data:n}=await e.http.delete(`/api/v4/me/flags/${encodeURIComponent(t)}`);if(e.cache){const e=await $r(n);Kt(e)}return Ze("user.unflagged",n),!!n})({client:n,referenceId:t}):"message"===e?(async({client:e,referenceId:t})=>{const{data:n}=await e.http.delete(`/api/v5/messages/${encodeURIComponent(t)}/flags`);if(e.cache){const e=await Fn(n);Kt(e)}return Ze("message.unflagged",n),!!n})({client:n,referenceId:t}):"post"===e?(async({client:e,referenceId:t})=>{const{data:n}=await e.http.delete(`/api/v3/posts/${encodeURIComponent(t)}/unflag`);if(e.cache){const e=await Bo(n);Kt(e)}return Ze("post.unflagged",n),!!n})({client:n,referenceId:t}):"comment"===e&&(async({client:e,referenceId:t})=>{const{data:n}=await e.http.delete(`/api/v3/comments/${encodeURIComponent(t)}/unflag`);if(e.cache){const e=await hi(n);Kt(e)}return Ze("comment.unflagged",n),!!n})({client:n,referenceId:t})},e.disableCache=()=>{const e=be();e.cache&&(e.log("cache/api/disableCache"),delete e.cache)},e.dropFromCache=Te,e.enableCache=(e={},t)=>{const n=be();n.cache||(n.log("cache/api/enableCache"),n.cache={data:e,persistIf:t})},e.filterByChannelMembership=Me,e.filterByCommunityMembership=Pe,e.filterByFeedType=Re,e.filterByPostDataTypes=je,e.filterByPropEquality=Oe,e.filterByPropInclusion=(e,t,n)=>void 0!==n?e.filter((e=>n.includes(e[t]))):e,e.filterByPropIntersection=Ee,e.filterBySearchTerm=Ue,e.filterByStringComparePartially=Ae,e.getChannelTopic=e=>`${e.path}/#`,e.getCommentTopic=({path:e})=>e,e.getCommunityStoriesTopic=({targetId:e,targetType:t})=>{const n=ze();return`${st(n)}/social/${t}/${e}/story/#`},e.getCommunityTopic=({path:t},n=e.SubscriptionLevels.COMMUNITY)=>rt(t,n),e.getLiveStreamTopic=pt,e.getMarkedMessageTopic=ot,e.getMarkerUserFeedTopic=it,e.getMessageTopic=e=>e.path,e.getMyFollowersTopic=()=>{const e=ze();return`${st(e)}/membership/${e._id}/+/+`},e.getMyFollowingsTopic=()=>{const e=ze();return`${st(e)}/membership/+/${e._id}/+`},e.getNetworkTopic=ct,e.getPostTopic=({path:t},n=e.SubscriptionLevels.POST)=>"comment"===n?`${t}/comment/+`:t,e.getRole=bo,e.getSmartFeedChannelTopic=lt,e.getSmartFeedMessageTopic=ut,e.getSmartFeedSubChannelTopic=dt,e.getStoryTopic=({targetId:e,targetType:t,storyId:n})=>{const r=ze();return`${st(r)}/social/${t}/${e}/story/${n}/#`},e.getSubChannelTopic=e=>`${e.path}/#`,e.getUserTopic=at,e.isAfterBefore=J,e.isAfterBeforeRaw=G,e.isCachable=re,e.isFetcher=ee,e.isFresh=se,e.isLocal=e=>re(e)&&-1===(null==e?void 0:e.cachedAt),e.isMutator=te,e.isOffline=ne,e.isPaged=Y,e.isReportedByMe=async(e,t)=>{const n=be();return n.log("report/isReportedByMe",{referenceType:e,referenceId:t}),"user"===e?(async({client:e,referenceId:t})=>{var n;const{data:r}=await e.http.get(`/api/v3/users/${t}/isflagbyme`),{result:s,isFlagByMe:a}=null!=r?r:{};return null!==(n=null!=s?s:a)&&void 0!==n&&n})({client:n,referenceId:t}):"message"===e?(async({client:e,referenceId:t})=>{var n;const{data:r}=await e.http.get(`/api/v5/messages/${encodeURIComponent(t)}/flags`),{result:s,isFlagByMe:a}=null!=r?r:{};return null!==(n=null!=s?s:a)&&void 0!==n&&n})({client:n,referenceId:t}):"post"===e?(async({client:e,referenceId:t})=>{var n;const{data:r}=await e.http.get(`/api/v3/posts/${t}/isflagbyme`),{result:s,isFlagByMe:a}=null!=r?r:{};return null!==(n=null!=s?s:a)&&void 0!==n&&n})({client:n,referenceId:t}):"comment"===e&&(async({client:e,referenceId:t})=>{var n;const{data:r}=await e.http.get(`/api/v3/comments/${t}/isflagbyme`),{result:s,isFlagByMe:a}=null!=r?r:{};return null!==(n=null!=s?s:a)&&void 0!==n&&n})({client:n,referenceId:t})},e.isSkip=W,e.mergeInCache=_e,e.notificationTray=iu,e.onChannelMarkerFetched=ta,e.onFeedMarkerFetched=e=>{const t=be();return Ye(t,"feedMarker/onFeedMarkerFetched","local.feedMarker.fetched",(t=>{e(t.feedMarkers[0])}))},e.onFeedMarkerUpdated=e=>{const t=be();return Ye(t,"feedMarker/onFeedMarkerUpdated","marker.feed-updated",(t=>{Kt(t),e(t.feedMarkers[0])}))},e.onMessageMarked=oa,e.onMessageMarkerFetched=aa,e.onSubChannelMarkerFetched=na,e.onSubChannelMarkerUpdated=ra,e.onUserMarkerFetched=sa,e.onUserMarkerFetchedLegacy=e=>{const t=be();return Ye(t,"userMarker/onUserMarkerFetched","local.userMarker.fetched",(t=>{e(t.userMarkers[0])}))},e.pullFromCache=Ie,e.pushToCache=Se,e.queryCache=Ce,e.queryOptions=oe,e.queryRoles=vo,e.restoreCache=async(e="amitySdk")=>{var t;const n=be();if(!n.cache)return!1;n.log("cache/api/restoreCache",{storageKey:e});const r=localStorage&&null!==(t=await localStorage.getItem(`${e}#${n.userId}`))&&void 0!==t?t:"{}";let s={};try{s=JSON.parse(r)}catch(e){}return n.cache.data=Object.assign(Object.assign({},s),n.cache.data),!0},e.runQuery=ie,e.sortByChannelSegment=({channelSegment:e},{channelSegment:t})=>e-t,e.sortByDisplayName=xe,e.sortByFirstCreated=Ne,e.sortByFirstUpdated=Fe,e.sortByLastActivity=Ke,e.sortByLastCreated=qe,e.sortByLastUpdated=Le,e.sortByLocalSortingDate=Be,e.sortByName=De,e.sortBySegmentNumber=({segmentNumber:e},{segmentNumber:t})=>e-t,e.subscribeTopic=ht,e.toPage=X,e.toPageRaw=e=>{if(!e)return;const n=JSON.parse(t.decode(e));return G(n)?n:void 0},e.toToken=Z,e.upsertInCache=ke,e.wipeCache=async(e="amitySdk")=>{const{log:t,cache:n,userId:r}=be();return!!n&&(t("cache/api/wipeCache",{storageKey:e}),n.data={},localStorage&&await localStorage.setItem(`${e}#${r}`,"{}"),!0)},Object.defineProperty(e,"__esModule",{value:!0}),e}({},jsBase64,mitt,debug,axios,HttpAgent,io,AsyncStorage,uuid$1,reactNative,hash,Hls);
5
+ var r=e("buffer"),a=r.Buffer;function s(e,t){for(var n in e)t[n]=e[n]}function o(e,t,n){return a(e,t,n)}a.from&&a.alloc&&a.allocUnsafe&&a.allocUnsafeSlow?t.exports=r:(s(r,n),n.Buffer=o),o.prototype=Object.create(a.prototype),s(a,o),o.from=function(e,t,n){if("number"==typeof e)throw new TypeError("Argument must not be a number");return a(e,t,n)},o.alloc=function(e,t,n){if("number"!=typeof e)throw new TypeError("Argument must be a number");var r=a(e);return void 0!==t?"string"==typeof n?r.fill(t,n):r.fill(t):r.fill(0),r},o.allocUnsafe=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return a(e)},o.allocUnsafeSlow=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return r.SlowBuffer(e)}},{buffer:17}],74:[function(e,t,n){function r(e){var t=e._readableState;return t?t.objectMode||"number"==typeof e._duplexState?e.read():e.read(a(t)):null}function a(e){return e.buffer.length?e.buffer.head?e.buffer.head.data.length:e.buffer[0].length:e.length}t.exports=r},{}],75:[function(e,t,n){var r=e("safe-buffer").Buffer,a=r.isEncoding||function(e){switch((e=""+e)&&e.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}};function s(e){if(!e)return"utf8";for(var t;;)switch(e){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return e;default:if(t)return;e=(""+e).toLowerCase(),t=!0}}function o(e){var t=s(e);if("string"!=typeof t&&(r.isEncoding===a||!a(e)))throw new Error("Unknown encoding: "+e);return t||e}function i(e){var t;switch(this.encoding=o(e),this.encoding){case"utf16le":this.text=f,this.end=m,t=4;break;case"utf8":this.fillLast=u,t=4;break;case"base64":this.text=g,this.end=y,t=3;break;default:return this.write=v,void(this.end=b)}this.lastNeed=0,this.lastTotal=0,this.lastChar=r.allocUnsafe(t)}function c(e){return e<=127?0:e>>5==6?2:e>>4==14?3:e>>3==30?4:e>>6==2?-1:-2}function l(e,t,n){var r=t.length-1;if(r<n)return 0;var a=c(t[r]);return a>=0?(a>0&&(e.lastNeed=a-1),a):--r<n||-2===a?0:(a=c(t[r]))>=0?(a>0&&(e.lastNeed=a-2),a):--r<n||-2===a?0:(a=c(t[r]))>=0?(a>0&&(2===a?a=0:e.lastNeed=a-3),a):0}function d(e,t,n){if(128!=(192&t[0]))return e.lastNeed=0,"�";if(e.lastNeed>1&&t.length>1){if(128!=(192&t[1]))return e.lastNeed=1,"�";if(e.lastNeed>2&&t.length>2&&128!=(192&t[2]))return e.lastNeed=2,"�"}}function u(e){var t=this.lastTotal-this.lastNeed,n=d(this,e);return void 0!==n?n:this.lastNeed<=e.length?(e.copy(this.lastChar,t,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal)):(e.copy(this.lastChar,t,0,e.length),void(this.lastNeed-=e.length))}function h(e,t){var n=l(this,e,t);if(!this.lastNeed)return e.toString("utf8",t);this.lastTotal=n;var r=e.length-(n-this.lastNeed);return e.copy(this.lastChar,0,r),e.toString("utf8",t,r)}function p(e){var t=e&&e.length?this.write(e):"";return this.lastNeed?t+"�":t}function f(e,t){if((e.length-t)%2==0){var n=e.toString("utf16le",t);if(n){var r=n.charCodeAt(n.length-1);if(r>=55296&&r<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1],n.slice(0,-1)}return n}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=e[e.length-1],e.toString("utf16le",t,e.length-1)}function m(e){var t=e&&e.length?this.write(e):"";if(this.lastNeed){var n=this.lastTotal-this.lastNeed;return t+this.lastChar.toString("utf16le",0,n)}return t}function g(e,t){var n=(e.length-t)%3;return 0===n?e.toString("base64",t):(this.lastNeed=3-n,this.lastTotal=3,1===n?this.lastChar[0]=e[e.length-1]:(this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1]),e.toString("base64",t,e.length-n))}function y(e){var t=e&&e.length?this.write(e):"";return this.lastNeed?t+this.lastChar.toString("base64",0,3-this.lastNeed):t}function v(e){return e.toString(this.encoding)}function b(e){return e&&e.length?this.write(e):""}n.StringDecoder=i,i.prototype.write=function(e){if(0===e.length)return"";var t,n;if(this.lastNeed){if(void 0===(t=this.fillLast(e)))return"";n=this.lastNeed,this.lastNeed=0}else n=0;return n<e.length?t?t+this.text(e,n):this.text(e,n):t||""},i.prototype.end=p,i.prototype.text=h,i.prototype.fillLast=function(e){if(this.lastNeed<=e.length)return e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,e.length),this.lastNeed-=e.length}},{"safe-buffer":73}],76:[function(e,t,n){var r=e("punycode"),a=e("./util");function s(){this.protocol=null,this.slashes=null,this.auth=null,this.host=null,this.port=null,this.hostname=null,this.hash=null,this.search=null,this.query=null,this.pathname=null,this.path=null,this.href=null}n.parse=w,n.resolve=I,n.resolveObject=S,n.format=C,n.Url=s;var o=/^([a-z0-9.+-]+:)/i,i=/:[0-9]*$/,c=/^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/,l=["{","}","|","\\","^","`"].concat(["<",">",'"',"`"," ","\r","\n","\t"]),d=["'"].concat(l),u=["%","/","?",";","#"].concat(d),h=["/","?","#"],p=255,f=/^[+a-z0-9A-Z_-]{0,63}$/,m=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,g={javascript:!0,"javascript:":!0},y={javascript:!0,"javascript:":!0},v={http:!0,https:!0,ftp:!0,gopher:!0,file:!0,"http:":!0,"https:":!0,"ftp:":!0,"gopher:":!0,"file:":!0},b=e("querystring");function w(e,t,n){if(e&&a.isObject(e)&&e instanceof s)return e;var r=new s;return r.parse(e,t,n),r}function C(e){return a.isString(e)&&(e=w(e)),e instanceof s?e.format():s.prototype.format.call(e)}function I(e,t){return w(e,!1,!0).resolve(t)}function S(e,t){return e?w(e,!1,!0).resolveObject(t):t}s.prototype.parse=function(e,t,n){if(!a.isString(e))throw new TypeError("Parameter 'url' must be a string, not "+typeof e);var s=e.indexOf("?"),i=-1!==s&&s<e.indexOf("#")?"?":"#",l=e.split(i),w=/\\/g;l[0]=l[0].replace(w,"/");var C=e=l.join(i);if(C=C.trim(),!n&&1===e.split("#").length){var I=c.exec(C);if(I)return this.path=C,this.href=C,this.pathname=I[1],I[2]?(this.search=I[2],this.query=t?b.parse(this.search.substr(1)):this.search.substr(1)):t&&(this.search="",this.query={}),this}var S=o.exec(C);if(S){var _=(S=S[0]).toLowerCase();this.protocol=_,C=C.substr(S.length)}if(n||S||C.match(/^\/\/[^@\/]+@[^@\/]+/)){var k="//"===C.substr(0,2);!k||S&&y[S]||(C=C.substr(2),this.slashes=!0)}if(!y[S]&&(k||S&&!v[S])){for(var O,T,E=-1,A=0;A<h.length;A++)-1!==(R=C.indexOf(h[A]))&&(-1===E||R<E)&&(E=R);for(-1!==(T=-1===E?C.lastIndexOf("@"):C.lastIndexOf("@",E))&&(O=C.slice(0,T),C=C.slice(T+1),this.auth=decodeURIComponent(O)),E=-1,A=0;A<u.length;A++){var R;-1!==(R=C.indexOf(u[A]))&&(-1===E||R<E)&&(E=R)}-1===E&&(E=C.length),this.host=C.slice(0,E),C=C.slice(E),this.parseHost(),this.hostname=this.hostname||"";var M="["===this.hostname[0]&&"]"===this.hostname[this.hostname.length-1];if(!M)for(var j=this.hostname.split(/\./),P=(A=0,j.length);A<P;A++){var U=j[A];if(U&&!U.match(f)){for(var x="",D=0,q=U.length;D<q;D++)U.charCodeAt(D)>127?x+="x":x+=U[D];if(!x.match(f)){var N=j.slice(0,A),B=j.slice(A+1),L=U.match(m);L&&(N.push(L[1]),B.unshift(L[2])),B.length&&(C="/"+B.join(".")+C),this.hostname=N.join(".");break}}}this.hostname.length>p?this.hostname="":this.hostname=this.hostname.toLowerCase(),M||(this.hostname=r.toASCII(this.hostname));var F=this.port?":"+this.port:"",K=this.hostname||"";this.host=K+F,this.href+=this.host,M&&(this.hostname=this.hostname.substr(1,this.hostname.length-2),"/"!==C[0]&&(C="/"+C))}if(!g[_])for(A=0,P=d.length;A<P;A++){var $=d[A];if(-1!==C.indexOf($)){var Q=encodeURIComponent($);Q===$&&(Q=escape($)),C=C.split($).join(Q)}}var z=C.indexOf("#");-1!==z&&(this.hash=C.substr(z),C=C.slice(0,z));var V=C.indexOf("?");if(-1!==V?(this.search=C.substr(V),this.query=C.substr(V+1),t&&(this.query=b.parse(this.query)),C=C.slice(0,V)):t&&(this.search="",this.query={}),C&&(this.pathname=C),v[_]&&this.hostname&&!this.pathname&&(this.pathname="/"),this.pathname||this.search){F=this.pathname||"";var H=this.search||"";this.path=F+H}return this.href=this.format(),this},s.prototype.format=function(){var e=this.auth||"";e&&(e=(e=encodeURIComponent(e)).replace(/%3A/i,":"),e+="@");var t=this.protocol||"",n=this.pathname||"",r=this.hash||"",s=!1,o="";this.host?s=e+this.host:this.hostname&&(s=e+(-1===this.hostname.indexOf(":")?this.hostname:"["+this.hostname+"]"),this.port&&(s+=":"+this.port)),this.query&&a.isObject(this.query)&&Object.keys(this.query).length&&(o=b.stringify(this.query));var i=this.search||o&&"?"+o||"";return t&&":"!==t.substr(-1)&&(t+=":"),this.slashes||(!t||v[t])&&!1!==s?(s="//"+(s||""),n&&"/"!==n.charAt(0)&&(n="/"+n)):s||(s=""),r&&"#"!==r.charAt(0)&&(r="#"+r),i&&"?"!==i.charAt(0)&&(i="?"+i),t+s+(n=n.replace(/[?#]/g,(function(e){return encodeURIComponent(e)})))+(i=i.replace("#","%23"))+r},s.prototype.resolve=function(e){return this.resolveObject(w(e,!1,!0)).format()},s.prototype.resolveObject=function(e){if(a.isString(e)){var t=new s;t.parse(e,!1,!0),e=t}for(var n=new s,r=Object.keys(this),o=0;o<r.length;o++){var i=r[o];n[i]=this[i]}if(n.hash=e.hash,""===e.href)return n.href=n.format(),n;if(e.slashes&&!e.protocol){for(var c=Object.keys(e),l=0;l<c.length;l++){var d=c[l];"protocol"!==d&&(n[d]=e[d])}return v[n.protocol]&&n.hostname&&!n.pathname&&(n.path=n.pathname="/"),n.href=n.format(),n}if(e.protocol&&e.protocol!==n.protocol){if(!v[e.protocol]){for(var u=Object.keys(e),h=0;h<u.length;h++){var p=u[h];n[p]=e[p]}return n.href=n.format(),n}if(n.protocol=e.protocol,e.host||y[e.protocol])n.pathname=e.pathname;else{for(var f=(e.pathname||"").split("/");f.length&&!(e.host=f.shift()););e.host||(e.host=""),e.hostname||(e.hostname=""),""!==f[0]&&f.unshift(""),f.length<2&&f.unshift(""),n.pathname=f.join("/")}if(n.search=e.search,n.query=e.query,n.host=e.host||"",n.auth=e.auth,n.hostname=e.hostname||e.host,n.port=e.port,n.pathname||n.search){var m=n.pathname||"",g=n.search||"";n.path=m+g}return n.slashes=n.slashes||e.slashes,n.href=n.format(),n}var b=n.pathname&&"/"===n.pathname.charAt(0),w=e.host||e.pathname&&"/"===e.pathname.charAt(0),C=w||b||n.host&&e.pathname,I=C,S=n.pathname&&n.pathname.split("/")||[],_=(f=e.pathname&&e.pathname.split("/")||[],n.protocol&&!v[n.protocol]);if(_&&(n.hostname="",n.port=null,n.host&&(""===S[0]?S[0]=n.host:S.unshift(n.host)),n.host="",e.protocol&&(e.hostname=null,e.port=null,e.host&&(""===f[0]?f[0]=e.host:f.unshift(e.host)),e.host=null),C=C&&(""===f[0]||""===S[0])),w)n.host=e.host||""===e.host?e.host:n.host,n.hostname=e.hostname||""===e.hostname?e.hostname:n.hostname,n.search=e.search,n.query=e.query,S=f;else if(f.length)S||(S=[]),S.pop(),S=S.concat(f),n.search=e.search,n.query=e.query;else if(!a.isNullOrUndefined(e.search))return _&&(n.hostname=n.host=S.shift(),(A=!!(n.host&&n.host.indexOf("@")>0)&&n.host.split("@"))&&(n.auth=A.shift(),n.host=n.hostname=A.shift())),n.search=e.search,n.query=e.query,a.isNull(n.pathname)&&a.isNull(n.search)||(n.path=(n.pathname?n.pathname:"")+(n.search?n.search:"")),n.href=n.format(),n;if(!S.length)return n.pathname=null,n.search?n.path="/"+n.search:n.path=null,n.href=n.format(),n;for(var k=S.slice(-1)[0],O=(n.host||e.host||S.length>1)&&("."===k||".."===k)||""===k,T=0,E=S.length;E>=0;E--)"."===(k=S[E])?S.splice(E,1):".."===k?(S.splice(E,1),T++):T&&(S.splice(E,1),T--);if(!C&&!I)for(;T--;T)S.unshift("..");!C||""===S[0]||S[0]&&"/"===S[0].charAt(0)||S.unshift(""),O&&"/"!==S.join("/").substr(-1)&&S.push("");var A,R=""===S[0]||S[0]&&"/"===S[0].charAt(0);return _&&(n.hostname=n.host=R?"":S.length?S.shift():"",(A=!!(n.host&&n.host.indexOf("@")>0)&&n.host.split("@"))&&(n.auth=A.shift(),n.host=n.hostname=A.shift())),(C=C||n.host&&S.length)&&!R&&S.unshift(""),S.length?n.pathname=S.join("/"):(n.pathname=null,n.path=null),a.isNull(n.pathname)&&a.isNull(n.search)||(n.path=(n.pathname?n.pathname:"")+(n.search?n.search:"")),n.auth=e.auth||n.auth,n.slashes=n.slashes||e.slashes,n.href=n.format(),n},s.prototype.parseHost=function(){var e=this.host,t=i.exec(e);t&&(":"!==(t=t[0])&&(this.port=t.substr(1)),e=e.substr(0,e.length-t.length)),e&&(this.hostname=e)}},{"./util":77,punycode:51,querystring:54}],77:[function(e,t,n){t.exports={isString:function(e){return"string"==typeof e},isObject:function(e){return"object"==typeof e&&null!==e},isNull:function(e){return null===e},isNullOrUndefined:function(e){return null==e}}},{}],78:[function(e,t,n){(function(e){(function(){function n(e,t){if(r("noDeprecation"))return e;var n=!1;function a(){if(!n){if(r("throwDeprecation"))throw new Error(t);r("traceDeprecation")?console.trace(t):console.warn(t),n=!0}return e.apply(this,arguments)}return a}function r(t){try{if(!e.localStorage)return!1}catch(e){return!1}var n=e.localStorage[t];return null!=n&&"true"===String(n).toLowerCase()}t.exports=n}).call(this)}).call(this,void 0!==qt?qt:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],79:[function(e,t,n){function r(e,t){if(e&&t)return r(e)(t);if("function"!=typeof e)throw new TypeError("need wrapper function");return Object.keys(e).forEach((function(t){n[t]=e[t]})),n;function n(){for(var t=new Array(arguments.length),n=0;n<t.length;n++)t[n]=arguments[n];var r=e.apply(this,t),a=t[t.length-1];return"function"==typeof r&&r!==a&&Object.keys(a).forEach((function(e){r[e]=a[e]})),r}}t.exports=r},{}],80:[function(e,t,n){t.exports=function(){throw new Error("ws does not work in the browser. Browser clients must use the native WebSocket object")}},{}],81:[function(e,t,n){t.exports=a;var r=Object.prototype.hasOwnProperty;function a(){for(var e={},t=0;t<arguments.length;t++){var n=arguments[t];for(var a in n)r.call(n,a)&&(e[a]=n[a])}return e}},{}],82:[function(e,t,n){t.exports=function(e){e.prototype[Symbol.iterator]=function*(){for(let e=this.head;e;e=e.next)yield e.value}}},{}],83:[function(e,t,n){function r(e){var t=this;if(t instanceof r||(t=new r),t.tail=null,t.head=null,t.length=0,e&&"function"==typeof e.forEach)e.forEach((function(e){t.push(e)}));else if(arguments.length>0)for(var n=0,a=arguments.length;n<a;n++)t.push(arguments[n]);return t}function a(e,t,n){var r=t===e.head?new i(n,null,t,e):new i(n,t,t.next,e);return null===r.next&&(e.tail=r),null===r.prev&&(e.head=r),e.length++,r}function s(e,t){e.tail=new i(t,e.tail,null,e),e.head||(e.head=e.tail),e.length++}function o(e,t){e.head=new i(t,null,e.head,e),e.tail||(e.tail=e.head),e.length++}function i(e,t,n,r){if(!(this instanceof i))return new i(e,t,n,r);this.list=r,this.value=e,t?(t.next=this,this.prev=t):this.prev=null,n?(n.prev=this,this.next=n):this.next=null}t.exports=r,r.Node=i,r.create=r,r.prototype.removeNode=function(e){if(e.list!==this)throw new Error("removing node which does not belong to this list");var t=e.next,n=e.prev;return t&&(t.prev=n),n&&(n.next=t),e===this.head&&(this.head=t),e===this.tail&&(this.tail=n),e.list.length--,e.next=null,e.prev=null,e.list=null,t},r.prototype.unshiftNode=function(e){if(e!==this.head){e.list&&e.list.removeNode(e);var t=this.head;e.list=this,e.next=t,t&&(t.prev=e),this.head=e,this.tail||(this.tail=e),this.length++}},r.prototype.pushNode=function(e){if(e!==this.tail){e.list&&e.list.removeNode(e);var t=this.tail;e.list=this,e.prev=t,t&&(t.next=e),this.tail=e,this.head||(this.head=e),this.length++}},r.prototype.push=function(){for(var e=0,t=arguments.length;e<t;e++)s(this,arguments[e]);return this.length},r.prototype.unshift=function(){for(var e=0,t=arguments.length;e<t;e++)o(this,arguments[e]);return this.length},r.prototype.pop=function(){if(this.tail){var e=this.tail.value;return this.tail=this.tail.prev,this.tail?this.tail.next=null:this.head=null,this.length--,e}},r.prototype.shift=function(){if(this.head){var e=this.head.value;return this.head=this.head.next,this.head?this.head.prev=null:this.tail=null,this.length--,e}},r.prototype.forEach=function(e,t){t=t||this;for(var n=this.head,r=0;null!==n;r++)e.call(t,n.value,r,this),n=n.next},r.prototype.forEachReverse=function(e,t){t=t||this;for(var n=this.tail,r=this.length-1;null!==n;r--)e.call(t,n.value,r,this),n=n.prev},r.prototype.get=function(e){for(var t=0,n=this.head;null!==n&&t<e;t++)n=n.next;if(t===e&&null!==n)return n.value},r.prototype.getReverse=function(e){for(var t=0,n=this.tail;null!==n&&t<e;t++)n=n.prev;if(t===e&&null!==n)return n.value},r.prototype.map=function(e,t){t=t||this;for(var n=new r,a=this.head;null!==a;)n.push(e.call(t,a.value,this)),a=a.next;return n},r.prototype.mapReverse=function(e,t){t=t||this;for(var n=new r,a=this.tail;null!==a;)n.push(e.call(t,a.value,this)),a=a.prev;return n},r.prototype.reduce=function(e,t){var n,r=this.head;if(arguments.length>1)n=t;else{if(!this.head)throw new TypeError("Reduce of empty list with no initial value");r=this.head.next,n=this.head.value}for(var a=0;null!==r;a++)n=e(n,r.value,a),r=r.next;return n},r.prototype.reduceReverse=function(e,t){var n,r=this.tail;if(arguments.length>1)n=t;else{if(!this.tail)throw new TypeError("Reduce of empty list with no initial value");r=this.tail.prev,n=this.tail.value}for(var a=this.length-1;null!==r;a--)n=e(n,r.value,a),r=r.prev;return n},r.prototype.toArray=function(){for(var e=new Array(this.length),t=0,n=this.head;null!==n;t++)e[t]=n.value,n=n.next;return e},r.prototype.toArrayReverse=function(){for(var e=new Array(this.length),t=0,n=this.tail;null!==n;t++)e[t]=n.value,n=n.prev;return e},r.prototype.slice=function(e,t){(t=t||this.length)<0&&(t+=this.length),(e=e||0)<0&&(e+=this.length);var n=new r;if(t<e||t<0)return n;e<0&&(e=0),t>this.length&&(t=this.length);for(var a=0,s=this.head;null!==s&&a<e;a++)s=s.next;for(;null!==s&&a<t;a++,s=s.next)n.push(s.value);return n},r.prototype.sliceReverse=function(e,t){(t=t||this.length)<0&&(t+=this.length),(e=e||0)<0&&(e+=this.length);var n=new r;if(t<e||t<0)return n;e<0&&(e=0),t>this.length&&(t=this.length);for(var a=this.length,s=this.tail;null!==s&&a>t;a--)s=s.prev;for(;null!==s&&a>e;a--,s=s.prev)n.push(s.value);return n},r.prototype.splice=function(e,t,...n){e>this.length&&(e=this.length-1),e<0&&(e=this.length+e);for(var r=0,s=this.head;null!==s&&r<e;r++)s=s.next;var o=[];for(r=0;s&&r<t;r++)o.push(s.value),s=this.removeNode(s);for(null===s&&(s=this.tail),s!==this.head&&s!==this.tail&&(s=s.prev),r=0;r<n.length;r++)s=a(this,s,n[r]);return o},r.prototype.reverse=function(){for(var e=this.head,t=this.tail,n=e;null!==n;n=n.prev){var r=n.prev;n.prev=n.next,n.next=r}return this.head=t,this.tail=e,this};try{e("./iterator.js")(r)}catch(e){}},{"./iterator.js":82}]},{},[12])(12);var Ft=Nt(Lt.exports);class Kt{constructor(){this.store={},this.store={}}clear(){this.store={}}getItem(e){return this.store[e]||null}setItem(e,t){this.store[e]=String(t)}removeItem(e){delete this.store[e]}get length(){return Object.keys(this.store).length}key(e){return Object.keys(this.store)[e]||null}}const $t=()=>"undefined"!=typeof window&&window.localStorage?window:{localStorage:new Kt},Qt=()=>C.default.v4().toString();let zt=0;if("undefined"!=typeof BroadcastChannel&&"undefined"!=typeof window){const e=Qt(),t={},n=new BroadcastChannel("amity_ts_sdk");let r;n.postMessage({type:"startup",tabId:e}),n.onmessage=({data:a})=>{a.tabId!==e&&("startup"===a.type&&n.postMessage({type:"identify",tabId:e,tabIndex:zt}),"identify"===a.type&&void 0!==a.tabIndex&&a.tabId&&(t[a.tabId]=a.tabIndex,r||(r=setTimeout((()=>{const e=Object.values(t).sort();e&&0!==e.length&&(zt=e.reduce(((e,t)=>e<t?e:t+1),0))}),15))))}}const Vt=async()=>{var e;const t=`${null!==(e=Te().prefixDeviceIdKey)&&void 0!==e?e:""}#deviceId`,n=await(async e=>{if("undefined"!=typeof navigator&&"ReactNative"===navigator.product)return await w.default.getItem(e);return new Promise((t=>{t($t().localStorage.getItem(e))}))})(t);if(n)return n;const r=`ascWebSdk#${Qt()}`;return await(async(e,t)=>"undefined"!=typeof navigator&&"ReactNative"===navigator.product?(await w.default.setItem(e,t),!0):new Promise((n=>{$t().localStorage.setItem(e,t),n(!0)})))(t,r),r},Ht=()=>{const e=(()=>{var e,t;return(null===(e=kt.versions)||void 0===e?void 0:e.node)?kt.versions.node:navigator?`${navigator.product.toLowerCase()}#${null!==(t=navigator.userAgent)&&void 0!==t?t:"unknown_agent"}`:"unknown_model"})();return{kind:"web",model:e,sdkVersion:K}},Jt=1e3;var Wt;!function(e){e[e.IDENTIFIER_REJECTED=2]="IDENTIFIER_REJECTED",e[e.BAD_USERNAME_OR_PASSWORD=134]="BAD_USERNAME_OR_PASSWORD",e[e.NOT_AUTHORIZED=135]="NOT_AUTHORIZED"}(Wt||(Wt={}));const Gt=e=>{let t,n="disconnected";const r=new Set,a=e=>{n!==e&&(n=e,r.forEach((t=>{t(e)})))};return{connect:async function(n){const r=await(async e=>`mqttjs_${await Vt()}_${e}_${zt}`)(n.userId);return a("connecting"),t&&(a("disconnecting"),t.removeAllListeners(),t.end(!0)),t=Ft.connect(e,function(e){return Object.assign({clean:!1,clientId:`mqttjs_ + ${Math.random().toString(16).substring(2,10)}`,protocolId:"MQTT",protocolVersion:4,reconnectPeriod:Jt,will:{topic:"WillMsg",payload:"Connection Closed abnormally..!",qos:0,retain:!1},resubscribe:!0},e)}({username:n.userId,password:n.accessToken,clientId:r})),t.on("connect",(()=>{t.options.reconnectPeriod=Jt,a("connected"),(()=>{const e=[Ct(yt()),Ct(vt()),Ct(bt()),Ct(wt()),Ct(ft(Ze())),Ct(gt()),Ct(It())]})()})),t.on("error",(e=>{switch(e.code){case 2:case 134:case 135:t.end(),a("disconnected")}})),t.on("reconnect",(()=>{a("reconnecting"),t.options.reconnectPeriod=Math.min(2*(t.options.reconnectPeriod||Jt),8e3)})),t.on("close",(()=>{a("disconnected")})),t.on("disconnect",(()=>{a("disconnected")})),new Promise((e=>t.once("connect",(()=>e()))))},async disconnect(){if(this.connected)return new Promise((e=>null==t?void 0:t.end(!0,void 0,(()=>e()))))},reconnect:async()=>new Promise((e=>{null==t||t.reconnect(),e()})),listen:e=>(r.add(e),n&&e(n),()=>{r.delete(e)}),get connected(){return!!(null==t?void 0:t.connected)},on(e,n){null==t||t.on(e,n)},once(e,n){null==t||t.once(e,n)},off(e,n){void 0!==n?null==t||t.off(e,n):null==t||t.removeAllListeners(e)},removeAllListeners(){null==t||t.removeAllListeners()},subscribe(e,n){const r=(t,r)=>{var a;if(t||128===(null===(a=r[0])||void 0===a?void 0:a.qos)){const r=t?new Ce(t.message,8e5,"error"):new Se(8e5,"error");console.warn(`Failed to subscribe to topic ${e}`,r),null==n||n(r)}else console.log(`Subscribed to topic ${e}`),null==n||n()};return t?t.subscribe(e,{qos:0},r):r(new Error("No connection to broker"),[]),()=>null==t?void 0:t.unsubscribe(e)},unsubscribe(e){null==t||t.unsubscribe(e)}}},Yt=(e={},t,n=!0)=>{Object.entries(e).forEach((([e,r])=>{const a=be[e];if(!a)return;const s=ve(a);s&&r.forEach((e=>{(n?Me:Pe)([a,"get",s(e)],e,t)}))}))},Zt=(e,t)=>{const{log:n,cache:r}=Te(),a=[e,G,t],s={cachedAt:Date.now()};r&&(n("cache/api/pushToTombstone",{cacheKey:a,data:s}),Ue([e,"get",t],!0),Me(a,s))};function Xt(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var a=0;for(r=Object.getOwnPropertySymbols(e);a<r.length;a++)t.indexOf(r[a])<0&&Object.prototype.propertyIsEnumerable.call(e,r[a])&&(n[r[a]]=e[r[a]])}return n}const en=(e,t="userId",n="user")=>{var r;return null!==(r=null==e?void 0:e.map((e=>((e,t="userId",n="user")=>e[n]?e:Object.assign({get[n](){var n;if(!Te().cache)return;return(null===(n=Re(["user","get",e[t]]))||void 0===n?void 0:n.data)||void 0}},e))(e,t,n))))&&void 0!==r?r:e},tn=(e,t,n="userId",r="user")=>{const a=e,s=t,o=a[s],i=Xt(a,["symbol"==typeof s?s:s+""]),c=en(o,n,r);return Object.assign(Object.assign({},i),{[t]:c})};function nn(e){return e.map((e=>{var{isMentioned:t}=e,n=Xt(e,["isMentioned"]);return Object.assign({hasMentioned:t},n)}))}function rn(e){return nn(e)}function an(e){return nn(e)}const sn=e=>{var t,n;return null!==(n=null===(t=Re(["messagePreviewChannel","get",e]))||void 0===t?void 0:t.data)&&void 0!==n?n:null},on=e=>Object.assign(Object.assign({},e),{get avatar(){var t;if(!e.avatarFileId)return;return null===(t=Re(["file","get",`${e.avatarFileId}`]))||void 0===t?void 0:t.data}}),cn=e=>{var t,n;const r={messagePreviewChannel:null!==(n=null===(t=e.messagePreviews)||void 0===t?void 0:t.map((t=>(t=>{var n;const r=null===(n=e.messageFeedsInfo)||void 0===n?void 0:n.find((e=>e.messageFeedId===t.messageFeedId)),{channelPublicId:a,messageFeedId:s,data:o,dataType:i,isDeleted:c,segment:l,creatorPublicId:d,createdAt:u,updatedAt:h}=t;return{channelId:a,subChannelId:s,data:o,dataType:i,isDeleted:c,segment:l,creatorId:d,createdAt:u,updatedAt:h,subChannelName:null==r?void 0:r.name,messagePreviewId:null==r?void 0:r.messagePreviewId,subChannelUpdatedAt:null==r?void 0:r.updatedAt}})(t))))&&void 0!==n?n:[]};Yt(r)},ln=e=>{var t,n;return null!==(n=null===(t=Re(["messagePreviewSubChannel","get",e]))||void 0===t?void 0:t.data)&&void 0!==n?n:null},dn=e=>{var t;const n=e.messagePreviewId?ln(e.subChannelId):null,r=n?Object.assign(Object.assign({},n),{user:null===(t=Re(["user","get",null==n?void 0:n.creatorId]))||void 0===t?void 0:t.data}):null;return Object.assign(Object.assign({},e),{messagePreview:r})},un=e=>{var t,n;const r={messagePreviewSubChannel:null!==(n=null===(t=e.messages)||void 0===t?void 0:t.map((t=>(t=>{var n;const r=null===(n=e.messageFeeds)||void 0===n?void 0:n.find((e=>e.messageFeedId===t.messageFeedId)),{channelPublicId:a,messageFeedId:s,messageId:o,creatorPublicId:i,data:c,dataType:l,isDeleted:d,segment:u,createdAt:h,updatedAt:p}=t;return{messagePreviewId:o,channelId:a,subChannelId:s,data:c,dataType:l,isDeleted:d,segment:u,creatorId:i,createdAt:h,updatedAt:p,subChannelName:null==r?void 0:r.name,subChannelUpdatedAt:null==r?void 0:r.updatedAt}})(t))))&&void 0!==n?n:[]};Yt(r)};function hn(e,t){return Object.create(Object.getPrototypeOf(e),Object.assign(Object.assign({},Object.getOwnPropertyDescriptors(e)),Object.getOwnPropertyDescriptors(t)))}function pn(e,t,n){Me(["subChannel","get",e],hn(t,n))}const fn=(e,t)=>{const{log:n,cache:r}=Te(),a=[e,G,t];if(!r)return;n("cache/api/isInTombstone",a);const s=Re(a),{lifeSpan:o}=fe("cache_then_server",18e4);if(s&&he(s.data,o))throw new Ie("Item not found!",400400,"error")},mn=e=>{var t;const n=["channelUnreadInfo","get",e],r=null===(t=Re(n))||void 0===t?void 0:t.data,a=Ae(["subChannelUnreadInfo","get"]);let s=0,o=!1;if(a&&(null==a?void 0:a.length)>0){const t=null==a?void 0:a.filter((({data:t})=>t.channelId===e&&!t.isDeleted));s=t.map((({data:e})=>e.unreadCount)).reduce(((e,t)=>e+t),0),o=t.some((({data:e})=>e.isMentioned))}const i=Object.assign(Object.assign({},null!=r?r:{channelId:e,createdAt:(new Date).toISOString()}),{updatedAt:(new Date).toISOString(),unreadCount:s,isMentioned:o});return Me(n,i),i},gn=e=>{const{feedMarkers:t,userFeedMarkers:n}=e;if(t.length>0&&n.length>0){const e=[],r=new Map(t.map((e=>[e.feedId,e])));n.forEach((t=>{const n=r.get(t.feedId);if(n&&n.feedId===t.feedId){const r=n.lastSegment-t.readToSegment,a={subChannelId:n.feedId,channelId:n.entityId,readToSegment:t.readToSegment,lastSegment:n.lastSegment,lastMentionSegment:t.lastMentionSegment,unreadCount:Math.max(0,r),isMentioned:t.isMentioned,isDeleted:n.isDeleted,createdAt:t.createdAt,updatedAt:t.updatedAt};Yt({subChannelUnreadInfo:[a]}),e.includes(n.entityId)||e.push(n.entityId)}})),e.forEach((e=>{mn(e)}))}},yn=async()=>{const e=Te();e.log("channel/getUserMarker");const{data:t}=await e.http.get("/api/v1/markers/userMarker"),{userMarkers:n}=t,r=e.cache&&Date.now();e.cache&&Yt({userMarkers:n},{cachedAt:r}),it("local.userMarker.fetched",{userMarkers:n});return{data:n.reduce(((e,t)=>null==e||new Date(e.lastSyncAt).getTime()<new Date(t.lastSyncAt).getTime()?t:e),void 0),cachedAt:r}},vn=e=>!0===e&&void 0;function bn(e,t,n){var r,a;if(n)return n.hasMentioned;const s=Te();if(s.isUnreadCountEnabled&&s.getMarkerSyncConsistentMode()){const e=null===(r=Re(["subChannelUnreadInfo","get",t]))||void 0===r?void 0:r.data;return!!e&&e.isMentioned}const o={entityId:e,feedId:t,userId:Ze()._id},i=null===(a=Re(["subChannelMarker","get",ve("subChannelMarker")(o)]))||void 0===a?void 0:a.data;return!!i&&i.hasMentioned}const wn=["broadcast","conversation","community"],Cn=({channelType:e})=>wn.includes(e);function In(e){var{channelId:t,channelPublicId:n,channelType:r,childCount:a,creatorId:s,creatorPublicId:o,lastMessageId:i,lastMessageTimestamp:c,messageFeedId:l,name:d}=e,u=Xt(e,["channelId","channelPublicId","channelType","childCount","creatorId","creatorPublicId","lastMessageId","lastMessageTimestamp","messageFeedId","name"]);return Object.assign(Object.assign({get unreadCount(){return function(e,t,n){var r,a;if(n)return n.unreadCount;const s=Te();if(s.isUnreadCountEnabled&&s.getMarkerSyncConsistentMode()){const e=null===(r=Re(["subChannelUnreadInfo","get",t]))||void 0===r?void 0:r.data;return e?e.isDeleted?0:e.unreadCount:0}const o={entityId:e,feedId:t,userId:Ze()._id},i=null===(a=Re(["subChannelMarker","get",ve("subChannelMarker")(o)]))||void 0===a?void 0:a.data;return i?i.unreadCount:0}(t,l)},get hasMentioned(){return bn(t,l)},get isMentioned(){return bn(t,l)}},u),{channelId:n,creatorId:o,displayName:d,lastActivity:c,latestMessageId:i,messageCount:a,subChannelId:l,isUnreadCountSupport:Cn({channelType:r})})}function Sn(e,t,n){var r;const a=(e=>{var t,n,r;const a=null===(n=null===(t=Ae(["message","get"]))||void 0===t?void 0:t.find((({data:t})=>t.messageId===e.messageId)))||void 0===n?void 0:n.data;return a?Object.assign(Object.assign(Object.assign({},a),e),{referenceId:null!==(r=a.referenceId)&&void 0!==r?r:e.referenceId}):e})(e),{channelPublicId:s,childCount:o,creatorPublicId:i,mentionedUsers:c,messageFeedId:l,myReactions:d,reactionCount:u,reactions:h,referenceId:p,segment:f,messageId:m,creatorId:g}=a,y=Xt(a,["channelPublicId","childCount","creatorPublicId","mentionedUsers","messageFeedId","myReactions","reactionCount","reactions","referenceId","segment","messageId","creatorId"]);let v;p&&(v=Re(["message","get",p])),v||(v=Re(["message","get",m]));const b=Object.assign(Object.assign({},y),{messageId:m,channelId:s,channelSegment:f,childrenNumber:o,creatorId:i,creatorPrivateId:e.creatorId,reactions:null!=h?h:{},myReactions:d||(null!==(r=null==v?void 0:v.data.myReactions)&&void 0!==r?r:[]),reactionsCount:u,subChannelId:l,uniqueId:v?v.data.uniqueId:m,referenceId:p,syncState:"synced"});return c&&(b.mentionees=c.map((e=>"channel"===e.type?e:{type:"user",userIds:e.userPublicIds}))),t&&t.length&&n&&((e,t,n)=>{const r=Te(),a=Re(["message","get",e.messageId]),s=(null==a?void 0:a.data.myReactions)||[];Object.assign(e,{myReactions:s});const o=t[0];o&&o.userId===r.userId&&("message.reactionAdded"!==n||s.includes(o.reactionName)||Object.assign(e,{myReactions:[...s,o.reactionName]}),"message.reactionRemoved"===n&&s.includes(o.reactionName)&&Object.assign(e,{myReactions:s.filter((e=>e!==o.reactionName))}))})(b,t,n),b}const _n={},kn=async(e,t)=>{const n=e.messages.map((({messageId:e})=>e));if(n.length>0){Yt({messages:(r=e).messages.map((e=>Sn(e,r.reactions)))});const t=n.join("");_n[t]&&clearTimeout(_n[t]),_n[t]=setTimeout((()=>{try{(async e=>{const t=Te();t.log("channel/getMessageMarkers",e);const{data:n}=await t.http.get("/api/v1/markers/messages",{params:{messageIds:e}}),{contentMarkers:r,feedMarkers:a,userMarkers:s}=n,o=t.cache&&Date.now();t.cache&&Yt({contentMarkers:r,feedMarkers:a,userMarkers:s},{cachedAt:o}),it("local.feedMarker.fetched",{feedMarkers:a}),it("local.messageMarker.fetched",{contentMarkers:r}),it("local.userMarker.fetched",{userMarkers:s})})(n)}catch(e){}}),2e3)}var r;const{messageFeeds:a}=e,s=Xt(e,["messageFeeds"]);return a&&a.length>0&&(null==a||a.forEach((e=>{var t,n;const r=null!==(n=null===(t=Re(["subChannel","get",e.messageFeedId]))||void 0===t?void 0:t.data)&&void 0!==n?n:{},a=Xt(In(e),["unreadCount","isMentioned"]);pn(e.messageFeedId,r,a)}))),Object.assign(Object.assign({},s),{messages:e.messages.map((n=>Sn(n,e.reactions,t)))})};function On(e){var{subChannelId:t,mentionees:n,dataType:r,data:a}=e,s=Xt(e,["subChannelId","mentionees","dataType","data"]);return r===x.IMAGE||r===x.FILE?Object.assign({messageFeedId:t,mentionedUsers:n,dataType:r,data:Object.assign({caption:""},a)},s):Object.assign({messageFeedId:t,mentionedUsers:n,dataType:r,data:a},s)}function Tn(e){var{sortBy:t,subChannelId:n,includingTags:r,excludingTags:a,includeDeleted:s,aroundMessageId:o,limit:i,type:c}=e,l=Xt(e,["sortBy","subChannelId","includingTags","excludingTags","includeDeleted","aroundMessageId","limit","type"]);const d=Object.assign(Object.assign({},l),{messageFeedId:n,isDeleted:vn(s),options:{sortBy:t,limit:i||$,around:o}});return r&&(d.includeTags=r),c&&(d.dataType=c),a&&(d.excludeTags=a),d}function En(e){return Object.assign(Object.assign({},e),{isGlobalBanned:(null==e?void 0:e.isGlobalBan)||!1})}const An=["broadcast","conversation","community"],Rn=({channelType:e})=>An.includes(e),Mn=async e=>{const t=e.messageFeeds.filter(Rn).map((({messageFeedId:e})=>e));if(t.length>0){(e=>{Yt({messageFeeds:e.messageFeeds.map((e=>In(e)))})})(e);try{await(async(e,t={limit:100})=>{const n=Te();n.log("channel/getSubChannelMarkers",e,t);const{data:r}=await n.http.get("/api/v1/markers/message-feeds",{params:{messageFeedIds:e,options:{token:oe(t,"skiplimit")}}}),{paging:a}=r,s=Xt(r,["paging"]),{userEntityMarkers:o,userFeedMarkers:i,userMarkers:c,feedMarkers:l}=s;n.isUnreadCountEnabled&&n.getMarkerSyncConsistentMode()&&gn({feedMarkers:l,userFeedMarkers:i});const d=rn(o),u=an(i),h=n.cache&&Date.now();n.cache&&Yt({userEntityMarkers:d,userFeedMarkers:u,userMarkers:c},{cachedAt:h}),it("local.channelMarker.fetched",{userEntityMarkers:d}),it("local.subChannelMarker.fetched",{userFeedMarkers:u}),it("local.userMarker.fetched",{userMarkers:c});const p=ie(a.next);return{data:u,cachedAt:h,prevPage:ie(a.previous),nextPage:p}})(t)}catch(e){}}un(e);const n=e.messageFeeds.map(In),r=e.messages.map((e=>Sn(e))),a=e.users.map(En);return Object.assign(Object.assign({},e),{messageFeeds:n,messages:r,users:a})};const jn=async e=>{const t=Te();t.log("channel/getSubChannel",e),fn("subChannel",e);try{const n=await t.http.get(`/api/v5/message-feeds/${encodeURIComponent(e)}`),r=await Mn(n.data),a=t.cache&&Date.now();return t.cache&&Yt(r,{cachedAt:a}),it("local.message-feed.fetched",r),{data:r.messageFeeds[0],cachedAt:a}}catch(t){throw te(null==t?void 0:t.code)&&Zt("subChannel",e),t}};jn.locally=e=>{const t=Te();if(t.log("channel/getSubChannel.locally",e),!t.cache)return;const n=Re(["subChannel","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const Pn=e=>new Date(e).getTime(),Un=async e=>{var t;let n=null===(t=Re(["subChannel","get",e]))||void 0===t?void 0:t.data;return n||(n=(await jn(e)).data),n},xn=async e=>{const t=await(async()=>Te().getMessagePreviewSetting(!1))(),{channelId:n,messageId:r,creatorId:a,createdAt:s,updatedAt:o,data:i,dataType:c,subChannelId:l,channelSegment:d,isDeleted:u}=e,h=await Un(l);"no-message-preview"!==t?(e=>{var t;const n=null===(t=Re(["messagePreviewSubChannel","get",e.subChannelId]))||void 0===t?void 0:t.data;return!n||n.segment<=e.channelSegment||Pn(n.createdAt)<=Pn(e.createdAt)})(e)&&(Me(["messagePreviewSubChannel","get",e.subChannelId],{channelId:n,creatorId:a,messagePreviewId:r,createdAt:s,updatedAt:o,subChannelId:l,data:i,dataType:c,segment:d,isDeleted:u,subChannelUpdatedAt:null==h?void 0:h.updatedAt,subChannelName:null==h?void 0:h.displayName}),pn(e.subChannelId,h,{lastActivity:s,messagePreviewId:r})):Pn(h.lastActivity)<Pn(s)&&pn(e.subChannelId,h,{lastActivity:s})},Dn=async e=>{var t;const{channelId:n,messageId:r,creatorId:a,createdAt:s,updatedAt:o,data:i,dataType:c,subChannelId:l,channelSegment:d,isDeleted:u}=e,h=null===(t=Re(["messagePreviewSubChannel","get",e.subChannelId]))||void 0===t?void 0:t.data;if(h&&h.messagePreviewId===e.messageId){const t=await Un(l);Me(["messagePreviewSubChannel","get",e.subChannelId],{channelId:n,creatorId:a,messagePreviewId:r,createdAt:s,updatedAt:o,subChannelId:l,data:i,dataType:c,segment:d,isDeleted:u,subChannelUpdatedAt:t.updatedAt,subChannelName:h.subChannelName})}},qn=async e=>{const{channelId:t,messageId:n,creatorId:r,createdAt:a,updatedAt:s,data:o,dataType:i,subChannelId:c,channelSegment:l,isDeleted:d}=e;if((e=>{var t;const n=null===(t=Re(["messagePreviewChannel","get",e.channelId]))||void 0===t?void 0:t.data;return!n||Pn(n.createdAt)<=Pn(e.createdAt)})(e)){const u=await Un(c);Me(["messagePreviewChannel","get",e.channelId],{channelId:t,creatorId:r,messagePreviewId:n,createdAt:a,updatedAt:s,subChannelId:c,data:o,dataType:i,segment:l,isDeleted:d,subChannelUpdatedAt:null==u?void 0:u.updatedAt,subChannelName:null==u?void 0:u.displayName})}},Nn=async e=>{var t;const{channelId:n,messageId:r,creatorId:a,createdAt:s,updatedAt:o,data:i,dataType:c,subChannelId:l,channelSegment:d,isDeleted:u}=e,h=null===(t=Re(["messagePreviewChannel","get",e.channelId]))||void 0===t?void 0:t.data;if(h&&h.messagePreviewId===e.messageId){const t=await Un(l);Me(["messagePreviewChannel","get",e.channelId],{channelId:n,creatorId:a,messagePreviewId:r,createdAt:s,updatedAt:o,subChannelId:l,data:i,dataType:c,segment:d,isDeleted:u,subChannelUpdatedAt:t.updatedAt,subChannelName:h.subChannelName})}},Bn=async e=>{var t,n,r,a;const{channelId:s,subChannelId:o}=e,i=null===(t=Re(["messagePreviewChannel","get",s]))||void 0===t?void 0:t.data;if((null==i?void 0:i.subChannelId)===o){const e=null===(n=Re(["subChannel","get",o]))||void 0===n?void 0:n.data;Me(["messagePreviewChannel","get",s],Object.assign(Object.assign({},i),{subChannelName:null==e?void 0:e.displayName,subChannelUpdatedAt:null==e?void 0:e.updatedAt}))}const c=null===(r=Re(["messagePreviewSubChannel","get",o]))||void 0===r?void 0:r.data;if(c&&new Date(c.updatedAt).valueOf()>new Date(e.updatedAt).valueOf()){const e=null===(a=Re(["subChannel","get",o]))||void 0===a?void 0:a.data;Me(["messagePreviewSubChannel","get",o],Object.assign(Object.assign({},c),{subChannelName:null==e?void 0:e.displayName,subChannelUpdatedAt:null==e?void 0:e.updatedAt}))}},Ln=["broadcast","conversation","community"],Fn=({type:e})=>Ln.includes(e);function Kn(e,t={isMessagePreviewUpdated:!0}){var n;let{messagePreviewId:r}=e;const a=null===(n=Re(["messagePreviewChannel","get",e.channelId]))||void 0===n?void 0:n.data;return(null==a?void 0:a.messagePreviewId)&&!t.isMessagePreviewUpdated&&(r=a.messagePreviewId),Object.assign(Object.assign({},e),{defaultSubChannelId:e.channelInternalId,isUnreadCountSupport:Fn(e),messagePreviewId:r})}const $n=(e,t={isMessagePreviewUpdated:!0})=>{Yt({channels:e.channels.map((e=>Kn(e,{isMessagePreviewUpdated:t.isMessagePreviewUpdated})))})},Qn=async(e,t={isMessagePreviewUpdated:!0})=>{const n=Te(),r=await n.getMessagePreviewSetting(!1);if(t.isMessagePreviewUpdated&&"no-message-preview"!==r&&e.messagePreviews&&e.messagePreviews.length>0&&cn(e),n.useLegacyUnreadCount)(({currentUserId:e,channels:t,channelUsers:n})=>{const r=[];for(let a=0;a<t.length;a+=1){const s=["channelUnread","get",t[a].channelId],o=n.find((n=>n.channelId===t[a].channelId&&n.userId===e));let i=0,c=null,l=null,d=!1;o&&(c=o.readToSegment,l=o.lastMentionedSegment,i=Math.max(t[a].messageCount-c,0),d=l>c);const u={channelId:t[a].channelId,lastSegment:t[a].messageCount,readToSegment:c,lastMentionedSegment:l,unreadCount:i,isMentioned:d,isDeleted:t[a].isDeleted||!1};Me(s,u),r.push(u)}it("local.channelUnread.updated",r)})({channels:e.channels,channelUsers:e.channelUsers,currentUserId:n.userId});else{const n=e.channels.filter(Fn).map((({channelInternalId:e})=>e));if(n.length>0){$n(e,{isMessagePreviewUpdated:t.isMessagePreviewUpdated});try{await(async e=>{const t=Te();t.log("channel/getChannelMarkers",e);const{data:n}=await t.http.get("/api/v1/markers/channels",{params:{channelIds:e}}),{userEntityMarkers:r,userMarkers:a}=n,s=rn(r),o=t.cache&&Date.now();return t.cache&&Yt({userEntityMarkers:s,userMarkers:a},{cachedAt:o}),it("local.channelMarker.fetched",{userEntityMarkers:s}),it("local.userMarker.fetched",{userMarkers:a}),{data:s,cachedAt:o}})(n)}catch(e){}}}const a=e.channels.map((e=>Kn(e,{isMessagePreviewUpdated:t.isMessagePreviewUpdated}))),s=e.channelUsers.map((e=>{return t=e,Object.assign(Object.assign({},t),{get user(){var e;if(Te().cache)return(null===(e=Re(["user","get",t.userId]))||void 0===e?void 0:e.data)||void 0}});var t})),o=e.users.map(En),i=Xt(e,["messageFeedsInfo","messagePreviews"]);return Object.assign(Object.assign({},i),{users:o,channels:a,channelUsers:s})},zn=async e=>{const t=Te();t.log("channel/getUserMessageFeedMakers",e);const{data:n}=await t.http.get("/api/v1/markers/user-message-feed",{params:{channelIds:e}});return it("local.userMessageFeedMarker.fetched",{userMessageFeedMarker:n}),n},Vn=async e=>{const t=Te(),n=await zn(e.channels.map((({channelInternalId:e})=>e))),{feedMarkers:r,userFeedMarkers:a}=n;gn({feedMarkers:r,userFeedMarkers:a}),t.log("channel/prepareUnreadCountInfo",e.channels)},Hn=(e,t)=>{var n,r,a,s;const o=Te();return o.isUnreadCountEnabled&&o.getMarkerSyncConsistentMode()?null!==(r=null===(n=(e=>{var t;return null===(t=Re(["channelUnreadInfo","get",e]))||void 0===t?void 0:t.data})(e.channelPublicId))||void 0===n?void 0:n.isMentioned)&&void 0!==r&&r:void 0!==(null==t?void 0:t.hasMentioned)?null==t?void 0:t.hasMentioned:null!==(s=null===(a=(e=>{var t;const n={entityId:e,userId:Ze()._id};return null===(t=Re(["channelMarker","get",ve("channelMarker")(n)]))||void 0===t?void 0:t.data})(e.channelPublicId))||void 0===a?void 0:a.hasMentioned)&&void 0!==s&&s},Jn=(e,t)=>{var n,r,a,s,o;const i=Te();return i.isUnreadCountEnabled&&i.getMarkerSyncConsistentMode()?null!==(r=null===(n=(e=>{var t;return null===(t=Re(["channelUnreadInfo","get",e]))||void 0===t?void 0:t.data})(e.channelInternalId))||void 0===n?void 0:n.unreadCount)&&void 0!==r?r:0:(null==t?void 0:t.isDeleted)?0:null!==(o=null!==(a=null==t?void 0:t.unreadCount)&&void 0!==a?a:null===(s=(e=>{var t;const n={entityId:e,userId:Ze()._id};return null===(t=Re(["channelMarker","get",ve("channelMarker")(n)]))||void 0===t?void 0:t.data})(e.channelInternalId))||void 0===s?void 0:s.unreadCount)&&void 0!==o?o:0},Wn=e=>{var t;return null===(t=Re(["channelUnread","get",e]))||void 0===t?void 0:t.data},Gn=e=>{const t=Te(),n=Xt(e,["messageCount"]);return hn(n,{get unreadCount(){var e,t;return null!==(t=null===(e=Wn(n.channelId))||void 0===e?void 0:e.unreadCount)&&void 0!==t?t:0},get subChannelsUnreadCount(){return Jn(n)},get isMentioned(){var e,r;return t.useLegacyUnreadCount?null!==(r=null===(e=Wn(n.channelId))||void 0===e?void 0:e.isMentioned)&&void 0!==r&&r:Hn(n)}})},Yn=["analytic","normal-priority"],Zn=["analytic","high-priority"],Xn=async e=>{const t=Te(),n={activities:e};await t.http.post("/api/v1/analytics/activities",n)};class er{constructor(){this._timer=void 0,this._high_priority_timer=void 0}start(){this.syncCapturedEvent(),this._timer=setInterval((()=>{this.syncCapturedEvent()}),6e4),this._high_priority_timer=setInterval((()=>{this.syncHighPriorityCapturedEvent()}),1e4)}stop(){this._timer&&(clearInterval(this._timer),this._timer=void 0),this._high_priority_timer&&(clearInterval(this._high_priority_timer),this._high_priority_timer=void 0)}async syncCapturedEvent(){try{const e=Re(Yn);if(!(null==e?void 0:e.data))return;if(0===e.data.event.length)return;const t=e.data.event;await Xn(t),Ue(Yn)}catch(e){this.stop(),Ue(Yn)}}async syncHighPriorityCapturedEvent(){try{const e=Re(Zn);if(!(null==e?void 0:e.data))return;if(0===e.data.event.length)return;const t=e.data.event;await Xn(t),Ue(Zn)}catch(e){this.stop(),Ue(Zn)}}}class tr{constructor(){this._expireTime=3e5,this._poolLimit=1e3,this._recentViewed={},this._recentHighPriorityViewed={},this._throttleStoryTimer=void 0,this._bufferNewSeenStoryReferenceIds=[]}isAbleToEnqueue({uniqueId:e,expireTime:t,isHighPriority:n=!1}){const r=new Date,a=n?this._recentHighPriorityViewed[e]:this._recentViewed[e];if(!a)return!0;return!(r.getTime()-a.getTime()<t)}markAs({uniqueId:e,contentId:t,contentType:n,activityType:r,metadata:a}){if(!this.isAbleToEnqueue({uniqueId:e,expireTime:this._expireTime}))return;const s=new Date,o={event:[]},i=Re(Yn);(null==i?void 0:i.data)&&(o.event=i.data.event),o.event.length>=this._poolLimit&&o.event.shift();const c={contentId:t,contentType:n,activityType:r,timestamp:s.toISOString()};a&&(c.metadata=a),o.event.push(c),Pe(Yn,o),this._recentViewed[e]=s}markPostAsViewed(e){this.markAs({uniqueId:e,contentId:e,contentType:"post",activityType:"view"})}markStory(e,t){if(!e.expiresAt)return;const n=new Date,r=new Date(e.expiresAt);if(!this.isAbleToEnqueue({uniqueId:e.storyId,expireTime:r.getTime(),isHighPriority:!0}))return;const a={event:[]},s=Re(Zn);if((null==s?void 0:s.data)&&(a.event=s.data.event),a.event.length>=this._poolLimit&&a.event.shift(),a.event.push({contentId:e.storyId,contentType:"story",activityType:t,timestamp:n.toISOString()}),Pe(Zn,a),this._recentHighPriorityViewed[e.storyId]=n,"linkClicked"===t)return;Me(["story-seen","get",e.storyId],(new Date).toISOString());const o=Re(["story-last-seen",e.targetId]);(null==o?void 0:o.data)?new Date(o.data).getTime()<new Date(e.expiresAt).getTime()&&Me(["story-last-seen",e.targetId],e.expiresAt):Me(["story-last-seen",e.targetId],e.expiresAt),this._bufferNewSeenStoryReferenceIds.push(e.referenceId),this._throttleStoryTimer||(this._throttleStoryTimer=setTimeout((()=>{clearTimeout(this._throttleStoryTimer),it("local.story.reload",{referenceIds:this._bufferNewSeenStoryReferenceIds}),this._bufferNewSeenStoryReferenceIds=[]}),300))}resetAllBuckets(){this._recentViewed={},this._recentHighPriorityViewed={},Ue(Yn),Ue(Zn)}markStoryAsViewed(e){this.markStory(e,"view")}markStoryAsClicked(e){this.markStory(e,"linkClicked")}markAdAsViewed(e,t){const n={placement:t},r="view";this.markAs({uniqueId:`${e.adId}.view.${t}`,contentId:e.adId,contentType:"ad",activityType:r,metadata:n})}markAdAsClicked(e,t){const n={placement:t},r="linkClicked";this.markAs({uniqueId:`${e.adId}.linkClicked.${t}`,contentId:e.adId,contentType:"ad",activityType:r,metadata:n})}}class nr{constructor(){this._client=Te(),this._eventCapturer=new tr,this._eventSyncer=new er}markPostAsViewed(e){"established"!==this._client.sessionState&&"tokenExpired"!==this._client.sessionState||this._eventCapturer.markPostAsViewed(e)}markStoryAsViewed(e){"established"!==this._client.sessionState&&"tokenExpired"!==this._client.sessionState||this._eventCapturer.markStoryAsViewed(e)}markAdAsViewed(e,t){"established"!==this._client.sessionState&&"tokenExpired"!==this._client.sessionState||this._eventCapturer.markAdAsViewed(e,t)}markAdAsClicked(e,t){"established"!==this._client.sessionState&&"tokenExpired"!==this._client.sessionState||this._eventCapturer.markAdAsClicked(e,t)}markStoryAsClicked(e){"established"!==this._client.sessionState&&"tokenExpired"!==this._client.sessionState||this._eventCapturer.markStoryAsClicked(e)}established(){this._eventSyncer.start()}handleTokenExpired(){this._stopAndDestroy()}destroy(){this._stopAndDestroy()}_stopAndDestroy(){this._eventSyncer.stop(),this._eventCapturer.resetAllBuckets()}}let rr;var ar=()=>(rr||(rr=new nr),rr);class sr{constructor(e,t,n){this._syncingStoriesCount=0,this._errorStoriesCount=0,this._targetId=e,this._lastStoryExpiresAt=t,this._lastStorySeenExpiresAt=n,this.cacheStoryExpireTime=Re(["story-expire",this._targetId]),this.cacheStoreSeenTime=Re(["story-last-seen",this._targetId]),this.getTotalStoryByStatus()}get lastStoryExpiresAt(){return this._lastStoryExpiresAt?new Date(this._lastStoryExpiresAt).getTime():0}get lastStorySeenExpiresAt(){return this._lastStorySeenExpiresAt?new Date(this._lastStorySeenExpiresAt).getTime():0}get localLastStoryExpires(){var e,t;return(null===(e=this.cacheStoryExpireTime)||void 0===e?void 0:e.data)?new Date(null===(t=this.cacheStoryExpireTime)||void 0===t?void 0:t.data).getTime():0}get localLastStorySeenExpiresAt(){var e,t;return(null===(e=this.cacheStoreSeenTime)||void 0===e?void 0:e.data)?new Date(null===(t=this.cacheStoreSeenTime)||void 0===t?void 0:t.data).getTime():0}get isContainUnSyncedStory(){const e=Re(["story-sync-state",this._targetId]);return!!(null==e?void 0:e.data)&&["syncing","error"].includes(e.data)}getLocalLastSortingDate(){return this.isContainUnSyncedStory?this.localLastStoryExpires:this.lastStoryExpiresAt}getHasUnseenFlag(){const e=(new Date).getTime(),t=Math.max(this.lastStorySeenExpiresAt,this.localLastStorySeenExpiresAt);return Re(["story-sync-state",this._targetId]),this.isContainUnSyncedStory?this.localLastStoryExpires>e&&this.localLastStoryExpires>t:this.lastStoryExpiresAt>e&&this.lastStoryExpiresAt>t}getTotalStoryByStatus(){const e=Ae(["story","get"]);if(!e)return this._errorStoriesCount=0,void(this._syncingStoriesCount=0);const t=e.reduce(((e,t)=>{const{data:{targetId:n,syncState:r,isDeleted:a}}=t;return n!==this._targetId||a||(e[r]+=1),e}),{syncing:0,error:0,synced:0});this._errorStoriesCount=t.error,this._syncingStoriesCount=t.syncing}get syncingStoriesCount(){return this._syncingStoriesCount}get failedStoriesCount(){return this._errorStoriesCount}}const or=e=>{const{targetType:t,targetId:n,lastStoryExpiresAt:r,lastStorySeenExpiresAt:a,targetUpdatedAt:s,localFilter:o}=e,i=new sr(n,r,a);return{targetType:t,targetId:n,lastStoryExpiresAt:r,updatedAt:s,hasUnseen:i.getHasUnseenFlag(),syncingStoriesCount:i.syncingStoriesCount,failedStoriesCount:i.failedStoriesCount,localFilter:o,localLastExpires:i.localLastStoryExpires,localLastSeen:i.localLastStorySeenExpiresAt,localSortingDate:i.getLocalLastSortingDate()}};function ir(e,t){if(null==e||null==t)return e===t;if(e.constructor!==t.constructor)return!1;if(e instanceof Function)return e===t;if(e instanceof RegExp)return e===t;if(e===t||e.valueOf()===t.valueOf())return!0;if(Array.isArray(e)&&e.length!==t.length)return!1;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(!ir(e[n],t[n]))return!1;return!0}if(e instanceof Date)return!1;if(!(e instanceof Object))return!1;if(!(t instanceof Object))return!1;const n=Object.keys(e);return Object.keys(t).every((e=>-1!==n.indexOf(e)))&&n.every((n=>ir(e[n],t[n])))}function cr(e){return null!=e}const lr=e=>Object.assign(Object.assign({},e),{get target(){const t={type:e.targetType};if("user"===e.targetType)return Object.assign(Object.assign({},t),{userId:e.targetId});if("content"===t.type)return Object.assign(Object.assign({},t),{contentId:e.targetId});if("community"===t.type){const n=Re(["communityUsers","get",`${e.targetId}#${e.userId}`]);return Object.assign(Object.assign({},t),{communityId:e.targetId,creatorMember:null==n?void 0:n.data})}return{type:"unknown"}},get creator(){const t=Re(["user","get",e.userId]);if(null==t?void 0:t.data)return on(t.data)},get childrenComment(){return e.children.map((e=>{const t=Re(["comment","get",e]);if(null==t?void 0:t.data)return null==t?void 0:t.data})).filter(cr).map((e=>lr(e)))}});function dr(e){return!!(e.data&&"string"!=typeof e.data&&"videoFileId"in e.data&&"thumbnailFileId"in e.data&&"video"===e.dataType)}const ur=e=>Object.assign(Object.assign({},e),{analytics:{markAsViewed:()=>{ar().markPostAsViewed(e.postId)}},get latestComments(){return e.comments&&e.comments.map((e=>{var t;const n=null===(t=Re(["comment","get",e]))||void 0===t?void 0:t.data;return n?lr(n):null})).filter(Boolean)||[]},get creator(){const t=Re(["user","get",e.postedUserId]);if(null==t?void 0:t.data)return on(t.data)},getImageInfo(){var t,n;return function(e){return!(!e.data||"string"==typeof e.data||!("fileId"in e.data)||"image"!==e.dataType)}(e)?null===(n=Re(["file","get",null===(t=null==e?void 0:e.data)||void 0===t?void 0:t.fileId]))||void 0===n?void 0:n.data:void 0},getVideoInfo(){var t,n,r;return dr(e)?null===(r=Re(["file","get",null===(n=null===(t=null==e?void 0:e.data)||void 0===t?void 0:t.videoFileId)||void 0===n?void 0:n.original]))||void 0===r?void 0:r.data:void 0},getVideoThumbnailInfo(){var t,n;return dr(e)?null===(n=Re(["file","get",null===(t=null==e?void 0:e.data)||void 0===t?void 0:t.thumbnailFileId]))||void 0===n?void 0:n.data:void 0},getFileInfo(){var t,n;return function(e){return!(!e.data||"string"==typeof e.data||!("fileId"in e.data)||"file"!==e.dataType)}(e)?null===(n=Re(["file","get",null===(t=null==e?void 0:e.data)||void 0===t?void 0:t.fileId]))||void 0===n?void 0:n.data:void 0}}),hr=(e,t)=>{var n;return null!==(n=null!=t?t:(e=>{var t,n;const r={creatorId:"creatorPrivateId"in e?e.creatorPrivateId:e.creatorId,feedId:null!==(t=e.messageFeedId)&&void 0!==t?t:e.subChannelId,contentId:e.messageId};return null===(n=Re(["messageMarker","get",ve("messageMarker")(r)]))||void 0===n?void 0:n.data})(e))&&void 0!==n?n:{readCount:0,deliveredCount:0}};class pr{constructor(){this.isActive=!0,this.MAX_RETRY=3,this.JOB_QUEUE_SIZE=120,this.jobQueue=[],this.RECEIPT_SYNC_INTERVAL=1,this.client=Te(),this.getUnsyncJobs()}startSyncReadReceipt(){this.timer=setInterval((()=>{this.syncReadReceipts()}),1e3*this.RECEIPT_SYNC_INTERVAL)}syncReadReceipts(){if(0===this.jobQueue.length||!1===this.isActive)return;const e=this.getReadReceipts();e&&this.markReadApi(e)}getUnsyncJobs(){var e;const t=null===(e=Ae(["readReceipt"]))||void 0===e?void 0:e.filter((({data:e})=>e.latestSyncSegment<e.latestSegment));null==t||t.forEach((({data:e})=>{this.enqueueReadReceipt(e.channelId,e.latestSegment)}))}getReadReceipts(){const e=this.jobQueue.splice(0,this.jobQueue.length);if(0!==e.length)return e.filter((e=>{var t;const n=null===(t=Re(["readReceipt",e.channelId]))||void 0===t?void 0:t.data;return!!n&&n.latestSegment>n.latestSyncSegment}))}async markReadApi(e){var t;const n=e.map((e=>({channelId:e.channelId,readToSegment:e.segment})));if(await(async e=>{const t=Te();try{return await t.http.post("api/v3/channels/seen",{channels:e}),!0}catch(e){return!1}})(n))for(let n=0;n<e.length;n+=1){const r=["readReceipt",e[n].channelId],a=null===(t=Re(r))||void 0===t?void 0:t.data;Me(r,Object.assign(Object.assign({},a),{latestSyncSegment:e[n].segment}))}else for(let t=0;t<e.length;t+=1){if(e[t].retryCount>=this.MAX_RETRY)return;const n=Object.assign(Object.assign({},e[t]),{syncState:"create",retryCount:e[t].retryCount+1});this.enqueueJob(n)}}startObservingReadReceiptQueue(){this.client.useLegacyUnreadCount&&(this.isActive=!0,this.startSyncReadReceipt())}stopObservingReadReceiptQueue(){this.isActive=!1,this.jobQueue.map((e=>"syncing"===e.syncState?Object.assign(Object.assign({},e),{syncState:"create"}):e)),this.timer&&clearInterval(this.timer)}onSessionEstablished(){this.startObservingReadReceiptQueue()}onSessionDestroyed(){this.stopObservingReadReceiptQueue(),this.jobQueue=[]}onTokenExpired(){this.stopObservingReadReceiptQueue()}onNetworkOffline(){this.stopObservingReadReceiptQueue()}onNetworkOnline(){this.startObservingReadReceiptQueue()}markRead(e,t){var n;const r=["channelUnread","get",e],a=null===(n=Re(r))||void 0===n?void 0:n.data;"number"==typeof(null==a?void 0:a.readToSegment)&&a&&t>a.readToSegment&&(a.readToSegment=t,a.unreadCount=Math.max(a.lastSegment-t,0),Me(r,a),it("local.channelUnread.updated",[a])),this.enqueueReadReceipt(e,t)}enqueueReadReceipt(e,t){var n;const r=null===(n=Re(["readReceipt",e]))||void 0===n?void 0:n.data;if(r){if(r.latestSegment<t)Me(["readReceipt",e],Object.assign(Object.assign({},r),{latestSegment:t}));else if(r.latestSyncSegment>=t)return}else{Me(["readReceipt",e],{channelId:e,latestSegment:t,latestSyncSegment:0})}let a=this.getSyncJob(e);null===a||"syncing"===a.syncState?(a={channelId:e,segment:t,syncState:"create",retryCount:0},this.enqueueJob(a)):a.segment<t&&(a.segment=t)}getSyncJob(e){const{jobQueue:t}=this;return t.find((t=>t.channelId===e))||null}enqueueJob(e){this.jobQueue.length<this.JOB_QUEUE_SIZE||this.jobQueue.shift(),this.jobQueue.push(e)}}let fr=null;var mr=()=>(fr||(fr=new pr),fr);class gr{constructor(){this.isActive=!0,this.MAX_RETRY=3,this.JOB_QUEUE_SIZE=120,this.jobQueue=[],this.RECEIPT_SYNC_INTERVAL=1,this.client=Te(),this.getUnsyncJobs()}startSyncReadReceipt(){this.timer=setInterval((()=>{this.syncReadReceipts()}),1e3*this.RECEIPT_SYNC_INTERVAL)}syncReadReceipts(){if(0===this.jobQueue.length||!1===this.isActive)return;const e=this.getReadReceipt();e&&this.markReadApi(e)}getUnsyncJobs(){var e;const t=null===(e=Ae(["legacyReadReceipt"]))||void 0===e?void 0:e.filter((({data:e})=>e.latestSyncSegment<e.latestSegment));null==t||t.forEach((({data:e})=>{this.enqueueReadReceipt(e.subChannelId,e.latestSegment)}))}getReadReceipt(){var e;const t=this.jobQueue[0];if(!t)return;if("syncing"===t.syncState)return;const n=null===(e=Re(["legacyReadReceipt",t.subChannelId]))||void 0===e?void 0:e.data;return n?(null==n?void 0:n.latestSegment)>(null==n?void 0:n.latestSyncSegment)?(t.segment=n.latestSegment,t):(this.removeSynedReceipt(n.subChannelId,n.latestSegment),this.getReadReceipt()):void 0}async markReadApi(e){var t;const n=e;n.syncState="syncing";const{subChannelId:r,segment:a}=n,s=await(async({subChannelId:e,readToSegment:t})=>{const n=Te();n.log("subChannel/markAsReadBySegment",e);try{return await n.http.put(`/api/v1/markers/message-feeds/${e}/mark-read`,{readToSegment:t}),!0}catch(e){return!1}})({subChannelId:r,readToSegment:a});if(s){this.removeSynedReceipt(e.subChannelId,e.segment);const n=null===(t=Re(["legacyReadReceipt",r]))||void 0===t?void 0:t.data;Me(["legacyReadReceipt",r],Object.assign(Object.assign({},n),{latestSyncSegment:a}))}else s||(n.retryCount>this.MAX_RETRY?this.removeJobFromQueue(n):(n.retryCount+=1,n.syncState="create"))}removeSynedReceipt(e,t){this.jobQueue.forEach((n=>{n.subChannelId===e&&n.segment<=t&&this.removeJobFromQueue(n)}))}startObservingReadReceiptQueue(){this.client.isUnreadCountEnabled&&(this.isActive=!0,this.startSyncReadReceipt())}stopObservingReadReceiptQueue(){this.isActive=!1;this.jobQueue.map((e=>"syncing"===e.syncState?Object.assign(Object.assign({},e),{syncState:"create"}):e)),this.timer&&clearInterval(this.timer)}onSessionEstablished(){this.startObservingReadReceiptQueue()}onSessionDestroyed(){this.stopObservingReadReceiptQueue(),this.jobQueue=[]}onTokenExpired(){this.stopObservingReadReceiptQueue()}onNetworkOffline(){this.stopObservingReadReceiptQueue()}onNetworkOnline(){this.startObservingReadReceiptQueue()}markRead(e,t){var n;const r=["subChannelUnreadInfo","get",e],a=null===(n=Re(r))||void 0===n?void 0:n.data;if(a&&t>a.readToSegment){a.readToSegment=t,a.unreadCount=Math.max(a.lastSegment-t,0);const e=mn(a.channelId);it("local.channelUnreadInfo.updated",e),Me(r,a),it("local.subChannelUnread.updated",a)}this.enqueueReadReceipt(e,t)}enqueueReadReceipt(e,t){var n;const r=null===(n=Re(["legacyReadReceipt",e]))||void 0===n?void 0:n.data;if(r){if(r.latestSegment<t)Me(["legacyReadReceipt",e],Object.assign(Object.assign({},r),{latestSegment:t}));else if(r.latestSyncSegment>=t)return}else{Me(["legacyReadReceipt",e],{subChannelId:e,latestSegment:t,latestSyncSegment:0})}let a=this.getSyncJob(e);null===a||"syncing"===a.syncState?(a={subChannelId:e,segment:t,syncState:"create",retryCount:0},this.enqueueJob(a)):a.segment<t&&(a.segment=t)}getSyncJob(e){return this.jobQueue.find((t=>t.subChannelId===e))||null}enqueueJob(e){this.jobQueue.length<this.JOB_QUEUE_SIZE||this.jobQueue.shift(),this.jobQueue.push(e)}removeJobFromQueue(e){const t=this.jobQueue.indexOf(e);t>-1&&this.jobQueue.splice(t,1)}}let yr=null;var vr=()=>(yr||(yr=new gr),yr);const br=e=>{if(Te().useLegacyUnreadCount){mr().markRead(e.channelId,e.channelSegment)}else{vr().markRead(e.subChannelId,e.channelSegment)}},wr=e=>Object.assign(Object.assign({},e),{get user(){return(()=>{var t;const n=["user","get",e.userId],r=null===(t=Re(n))||void 0===t?void 0:t.data;return r?on(r):void 0})()}});function Cr(e,t){return e.map((e=>{const n=Re(["community","get",e.communityId]);if((null==n?void 0:n.data)&&(null==n?void 0:n.data.hasOwnProperty("isJoined")))return Object.assign(Object.assign({},n.data),e);const r=t.some((t=>function(e,t){const{userId:n}=Ze();return e.communityId===t.communityId&&t.userId===n}(e,t)&&"none"!==t.communityMembership));return Object.assign(Object.assign({},e),{isJoined:r})}))}const Ir=e=>{var t;return null!==(t=Object.keys(M).find((t=>e.needApprovalOnPostCreation===M[t].needApprovalOnPostCreation&&e.onlyAdminCanPost===M[t].onlyAdminCanPost)))&&void 0!==t?t:j};function Sr({communities:e}){return e.map((e=>{var{needApprovalOnPostCreation:t,onlyAdminCanPost:n}=e,r=Xt(e,["needApprovalOnPostCreation","onlyAdminCanPost"]);return Object.assign({postSetting:Ir({needApprovalOnPostCreation:t,onlyAdminCanPost:n})},r)}))}const _r=e=>{const t=Sr({communities:e.communities}),n=e.users.map(En),r=e.communityUsers.map((e=>{const t=n.find((t=>t.userId===e.userId));return Object.assign(Object.assign({},e),{user:t})})),a=Cr(t,r);return Object.assign(Object.assign({},e),{users:e.users.map(En),communities:a,communityUsers:r})},kr=e=>{const t=e.joinRequests.map((e=>Object.assign(Object.assign({},e),{joinRequestId:e._id}))),n=e.users.map(En);return Object.assign(Object.assign({},e),{joinRequests:t,users:n})},Or=e=>{const t=Sr({communities:e.communities}),n=e.communityUsers.map((t=>{const n=e.users.find((e=>e.userId===t.userId));return Object.assign(Object.assign({},t),{user:n})})),r=Cr(t,n);return Object.assign(Object.assign({},e),{communities:r,communityUsers:n})},Tr=e=>{const{postSetting:t,storySetting:n}=e,r=Xt(e,["postSetting","storySetting"]);return Object.assign(Object.assign(Object.assign({},r),t?M[t]:void 0),{allowCommentInStory:"boolean"!=typeof(null==n?void 0:n.enableComment)||n.enableComment})},Er=e=>{var t=Xt(e,["searchResult"]);const n=_r(t);return Object.assign({},n)},Ar=e=>Object.assign(Object.assign({},e),{get user(){var t;const n=null===(t=Re(["user","get",e.requestorPublicId]))||void 0===t?void 0:t.data;if(n)return on(n)},cancel:async()=>{await(async e=>{var t;const n=Te();n.log("joinRequest/cancelJoinRequest",e.joinRequestId);const{data:r}=await n.http.delete(`/api/v4/communities/${e.targetId}/join`),a=null===(t=Re(["joinRequest","get",e.joinRequestId]))||void 0===t?void 0:t.data;return a&&(Pe(["joinRequest","get",e.joinRequestId],{status:"cancelled"}),it("local.joinRequest.deleted",[a])),r.success})(e)},approve:async()=>{await(async e=>{var t;const n=Te();n.log("joinRequest/approveJoinRequest",e.joinRequestId);const{data:r}=await n.http.post(`/api/v4/communities/${e.targetId}/join/approve`,{userId:e.requestorInternalId}),a=null===(t=Re(["joinRequest","get",e.joinRequestId]))||void 0===t?void 0:t.data;return a&&(Pe(["joinRequest","get",e.joinRequestId],{status:"approved"}),it("local.joinRequest.updated",[a])),r.success})(e)},reject:async()=>{await(async e=>{var t;const n=Te();n.log("joinRequest/rejectJoinRequest",e.joinRequestId);const{data:r}=await n.http.post(`/api/v4/communities/${e.targetId}/join/reject`,{userId:e.requestorInternalId}),a=null===(t=Re(["joinRequest","get",e.joinRequestId]))||void 0===t?void 0:t.data;return a&&(Pe(["joinRequest","get",e.joinRequestId],{status:"rejected"}),it("local.joinRequest.updated",[a])),r.success})(e)}});class Rr{constructor(e){const{http:t}=Te();this.queryParams=e,this.http=t}loadFirstPage(){return this.onFetch("first")}loadNextPage(){return this.onFetch("next")}loadPreviousPage(){return this.onFetch("prev")}async onFetch(e="first"){var t,n,r,a;if("prev"===e&&!this.previousToken)return;if("next"===e&&!this.nextToken)return;let s;"prev"===e&&(s=this.previousToken),"next"===e&&(s=this.nextToken);const o=await this.getRequest(this.queryParams,s);return"first"===e&&(this.nextToken=null===(t=o.paging)||void 0===t?void 0:t.next,this.previousToken=null===(n=o.paging)||void 0===n?void 0:n.previous),"prev"===e&&(this.previousToken=null===(r=o.paging)||void 0===r?void 0:r.previous),"next"===e&&(this.nextToken=null===(a=o.paging)||void 0===a?void 0:a.next),o}getNextToken(){return this.nextToken}getPrevToken(){return this.previousToken}}class Mr extends Rr{async getRequest(e,t){const{limit:n=20,communityId:r}=e,a=Xt(e,["limit","communityId"]),s=t?{token:t}:{limit:n},{data:o}=await this.http.get(`/api/v4/communities/${r}/join`,{params:Object.assign(Object.assign({},a),{options:s})});return o}}class jr{constructor(e,t){this.query=e,this.cacheKey=t}}var Pr;!function(e){e.OnLocalJoinRequestCreated="OnLocalJoinRequestCreated",e.OnLocalJoinRequestUpdated="OnLocalJoinRequestUpdated",e.OnLocalJoinRequestDeleted="OnLocalJoinRequestDeleted"}(Pr||(Pr={}));class Ur extends jr{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Te(),r=n.cache&&Date.now();n.cache&&Yt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,a;if(n)Me(this.cacheKey,{data:e.joinRequests.map((e=>ve("joinRequest")({joinRequestId:e._id})))});else{const t=null===(r=Re(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Me(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.joinRequests.map((e=>ve("joinRequest")({joinRequestId:e._id})))])]}))}}reactor(e){return t=>{var n;const r=null===(n=Re(this.cacheKey))||void 0===n?void 0:n.data;if(r){if(e===Pr.OnLocalJoinRequestUpdated){if(!r.data.find((e=>e===t[0].joinRequestId)))return}e===Pr.OnLocalJoinRequestCreated&&(r.data=[...new Set([...t.map((e=>e.joinRequestId)),...r.data])]),e===Pr.OnLocalJoinRequestDeleted&&(r.data=r.data.filter((e=>e!==t[0].joinRequestId))),Me(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}function xr(e){return"object"==typeof e&&null!==e}const Dr=e=>{if(!xr(e))return e;const t=Object.entries(e).map((([t,n])=>{const r=Object.getOwnPropertyDescriptor(e,t);return"function"==typeof(null==r?void 0:r.get)?[t,r.get.call(e)]:[t,n]}));return Object.fromEntries(t)},qr=e=>{if(!xr(e))return e;const t=Object.entries(e).map((([e,t])=>"function"==typeof t?[e,void 0]:[e,t]));return Object.fromEntries(t)};class Nr{constructor(e){const{http:t}=Te();this.queryParams=e,this.http=t}async onFetch(){return await this.getRequest(this.queryParams)}}class Br{constructor(e,t,n,r){this.paginationController=e,this.queryStreamId=t,this.cacheKey=n,this.callback=r}async refresh(){try{let e;if(e=this.paginationController instanceof Nr?await this.paginationController.onFetch():await this.paginationController.loadFirstPage(),!e)return;await this.persistModel(e),this.persistQueryStream({response:e,direction:"next",refresh:!0}),this.notifyChange({origin:"server",loading:!1})}catch(e){this.notifyChange({origin:"server",loading:!1,error:e})}}loadPage({initial:e=!1,direction:t="next"}){this.setup(),this.notifyChange({origin:"local",loading:!0}),e?this.refresh():"prev"===t?this.loadPrevPage():"next"===t&&this.loadNextPage()}async loadNextPage(){try{if(this.paginationController instanceof Nr)return;const e=await this.paginationController.loadNextPage();if(!e)return;await this.persistModel(e),this.persistQueryStream({response:e,direction:"next"}),this.notifyChange({origin:"server",loading:!1})}catch(e){this.notifyChange({origin:"server",loading:!1,error:e})}}async loadPrevPage(){try{if(this.paginationController instanceof Nr)return;const e=await this.paginationController.loadPreviousPage();if(!e)return;await this.persistModel(e),this.persistQueryStream({response:e,direction:"prev"}),this.notifyChange({origin:"server",loading:!1})}catch(e){this.notifyChange({origin:"server",loading:!1,error:e})}}shouldNotify(e){const t=e.map(Dr).map(qr);return!ir(this.snapshot,t)&&(this.snapshot=t,!0)}getCacheKey(){return this.cacheKey}}const Lr=e=>{const t=Te(),n=[ot(t,"onJoinRequestCreated","local.joinRequest.created",(t=>e(t)))];return()=>{n.forEach((e=>e()))}},Fr=e=>{const t=Te(),n=[ot(t,"onJoinRequestUpdated","local.joinRequest.updated",(t=>e(t)))];return()=>{n.forEach((e=>e()))}},Kr=e=>{const t=Te(),n=[ot(t,"onJoinRequestDeleted","local.joinRequest.deleted",(t=>e(t)))];return()=>{n.forEach((e=>e()))}};class $r extends Br{constructor(e,t){const n=I.default(e),r=["joinRequest","collection",n];super(new Mr(e),n,r,t),this.query=e,this.queryStreamController=new Ur(this.query,this.cacheKey,this.notifyChange.bind(this),kr),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Re(this.cacheKey))||void 0===e?void 0:e.data)||Me(this.cacheKey,{data:[],params:this.query})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){const r=e;this.queryStreamController.appendToQueryStream(r,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:Lr,action:Pr.OnLocalJoinRequestCreated},{fn:Fr,action:Pr.OnLocalJoinRequestUpdated},{fn:Kr,action:Pr.OnLocalJoinRequestDeleted}])}notifyChange({origin:e,loading:t,error:n}){var r;const a=null===(r=Re(this.cacheKey))||void 0===r?void 0:r.data;if(!a)return;const s=this.applyFilter(a.data.map((e=>Re(["joinRequest","get",e]))).filter(cr).map((({data:e})=>e)).map(Ar));(this.shouldNotify(s)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:s,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=e;this.query.status&&(t=t.filter((e=>e.status===this.query.status)));const n=(()=>"firstCreated"===this.query.sortBy?ze:He)();return t=t.sort(n),t}}const Qr=e=>Object.assign(Object.assign({},e),{createdById:e.createdBy}),zr=e=>Object.assign(Object.assign({},e),{invitations:e.invitations.map(Qr),users:e.users.map(En)}),Vr=e=>Object.assign(Object.assign({},e),{users:e.users.map(En),invitations:e.invitations.map(Qr)}),Hr=e=>Object.assign(Object.assign({},e),{get user(){const t=Re(["user","get",e.invitedUserPublicId]);if(null==t?void 0:t.data)return on(t.data)},get createdBy(){const t=Re(["user","get",e.inviterUserPublicId]);if(null==t?void 0:t.data)return on(t.data)},get target(){if("community"===e.targetType){const t=Re(["community","get",e.targetId]);return(null==t?void 0:t.data)?t.data:void 0}},accept:async()=>{await(async e=>{var t;const n=Te();n.log("invitation/acceptInvitation",e);const{data:r}=await n.http.post(`/api/v1/invitations/${e}/accept`),a=null===(t=Re(["invitation","get",e]))||void 0===t?void 0:t.data;return a&&(Pe(["invitation","get",e],{status:"approved"}),it("local.invitation.updated",[a])),r.success})(e._id)},reject:async()=>{await(async e=>{var t;const n=Te();n.log("invitation/rejectInvitation",e);const{data:r}=await n.http.post(`/api/v1/invitations/${e}/reject`),a=null===(t=Re(["invitation","get",e]))||void 0===t?void 0:t.data;return a&&(Pe(["invitation","get",e],{status:"rejected"}),it("local.invitation.updated",[a])),r.success})(e._id)}});var Jr;!function(e){e.OnLocalInvitationCreated="onLocalInvitationCreated",e.OnLocalInvitationUpdated="onLocalInvitationUpdated",e.OnLocalInvitationDeleted="onLocalInvitationDeleted"}(Jr||(Jr={}));class Wr extends Rr{async getRequest(e,t){const{limit:n=$}=e,r=Xt(e,["limit"]),a=t?{token:t}:{limit:n},{data:s}=await this.http.get("/api/v1/invitations",{params:Object.assign(Object.assign({},r),{options:a})});return s}}class Gr extends jr{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Te(),r=n.cache&&Date.now();n.cache&&Yt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,a;if(n)Me(this.cacheKey,{data:e.invitations.map(ve("invitation"))});else{const t=null===(r=Re(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Me(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.invitations.map(ve("invitation"))])]}))}}reactor(e){return t=>{var n;const r=null===(n=Re(this.cacheKey))||void 0===n?void 0:n.data;if(r){if(e===Jr.OnLocalInvitationUpdated){if(!r.data.find((e=>e===t[0].invitationId)))return}e===Jr.OnLocalInvitationCreated&&(r.data=[...new Set([...t.map((e=>e.invitationId)),...r.data])]),e===Jr.OnLocalInvitationDeleted&&(r.data=r.data.filter((e=>e!==t[0].invitationId))),Me(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const Yr=e=>{const t=Te(),n=[ot(t,"onLocalInvitationCreated","local.invitation.created",(t=>e(t)))];return()=>{n.forEach((e=>e()))}},Zr=e=>{const t=Te(),n=[ot(t,"onLocalInvitationUpdated","local.invitation.updated",(t=>e(t)))];return()=>{n.forEach((e=>e()))}},Xr=e=>{const t=Te(),n=[ot(t,"onLocalInvitationDeleted","local.invitation.deleted",(t=>e(t)))];return()=>{n.forEach((e=>e()))}};class ea extends Br{constructor(e,t){const n=I.default(e),r=["invitation","collection",n];super(new Wr(e),n,r,t),this.query=e,this.queryStreamController=new Gr(this.query,this.cacheKey,this.notifyChange.bind(this),zr),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Re(this.cacheKey))||void 0===e?void 0:e.data)||Me(this.cacheKey,{data:[],params:this.query})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:Yr,action:Jr.OnLocalInvitationCreated},{fn:Zr,action:Jr.OnLocalInvitationUpdated},{fn:Xr,action:Jr.OnLocalInvitationDeleted}])}notifyChange({origin:e,loading:t,error:n}){var r,a;const s=null===(r=Re(this.cacheKey))||void 0===r?void 0:r.data;if(!s)return;const o=this.applyFilter(null!==(a=s.data.map((e=>Re(["invitation","get",e]))).filter(cr).map((({data:e})=>Hr(e))))&&void 0!==a?a:[]);(this.shouldNotify(o)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:o,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=e;this.query.targetId&&(t=t.filter((e=>e.targetId===this.query.targetId))),this.query.statuses&&(t=t.filter((e=>{var t;return null===(t=this.query.statuses)||void 0===t?void 0:t.includes(e.status)}))),this.query.targetType&&(t=t.filter((e=>e.targetType===this.query.targetType))),this.query.type&&(t=t.filter((e=>e.type===this.query.type)));const n=(()=>"firstCreated"===this.query.sortBy?ze:He)();return t=t.sort(n),t}}const ta=e=>Object.assign(Object.assign({},e),{createInvitations:async t=>{await(async e=>{const t=Te();t.log("invitation/createInvitations",e);const{data:n}=await t.http.post("/api/v1/invitations",e),r=zr(n),a=t.cache&&Date.now();return t.cache&&Yt(r,{cachedAt:a}),it("local.invitation.created",r.invitations),{data:r.invitations,cachedAt:a}})({type:"communityMemberInvite",targetType:"community",targetId:e.communityId,userIds:t})},getMemberInvitations:(t,n)=>((e,t,n)=>{const{log:r,cache:a}=Te();a||console.log(z);const s=Date.now();r(`getInvitations: (tmpid: ${s}) > listen`);const o=new ea(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>{Ue(c)})),()=>{r(`getInvitations (tmpid: ${s}) > dispose`),i.forEach((e=>e()))}})(Object.assign(Object.assign({},t),{targetId:e.communityId,targetType:"community",type:"communityMemberInvite"}),n),getInvitation:async()=>{const{data:t}=await(async(e,t)=>{const n=Te();n.log("invitation/getInvitation",e,t);const{data:r}=await n.http.get("/api/v1/invitations/me",{params:{targetType:e,targetId:t}}),a=Vr(r),s=n.cache&&Date.now();return n.cache&&Yt(a,{cachedAt:s}),{data:a.invitations[0]?Hr(a.invitations[0]):void 0,cachedAt:s}})("community",e.communityId);return t},join:async()=>(async e=>{var t;const n=Te();n.log("community/joinRequest",e);const{data:r}=await n.http.post(`/api/v4/communities/${e}/join`),a=kr(r),s=n.cache&&Date.now();n.cache&&Yt(a,{cachedAt:s});const o="approved"===a.joinRequests[0].status?"success":"pending";if("success"===o&&n.cache){const n=null===(t=Re(["community","get",e]))||void 0===t?void 0:t.data;if(n){const t=Object.assign(Object.assign({},n),{isJoined:!0});Pe(["community","get",e],t)}}return it("v4.local.community.joined",a.joinRequests),"success"===o?{status:o}:{status:o,request:Ar(a.joinRequests[0])}})(e.communityId),getJoinRequests:(t,n)=>((e,t,n)=>{const{log:r,cache:a}=Te();a||console.log(z);const s=Date.now();r(`getJoinRequests: (tmpid: ${s}) > listen`);const o=new $r(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>{Ue(c)})),()=>{r(`getJoinRequests (tmpid: ${s}) > dispose`),i.forEach((e=>e()))}})(Object.assign(Object.assign({},t),{communityId:e.communityId}),n),getMyJoinRequest:async()=>{const{data:t}=await(async e=>{const t=Te();t.log("community/myJoinRequest",e);const{data:n}=await t.http.get(`/api/v4/communities/${e}/join/me`),r=kr(n),a=t.cache&&Date.now();return t.cache&&Yt(r,{cachedAt:a}),{data:r.joinRequests[0]?Ar(r.joinRequests[0]):void 0,cachedAt:a}})(e.communityId);return t}}),na={ad:e=>{const t=ar(),{image9_16:n,image1_1:r}=e,a=Xt(e,["image9_16","image1_1"]);return Object.assign(Object.assign({},a),{analytics:{markAsSeen:n=>{t.markAdAsViewed(e,n)},markLinkAsClicked:n=>{t.markAdAsClicked(e,n)}},get advertiser(){var t,n;const r=null===(t=Re(["advertiser","get",e.advertiserId]))||void 0===t?void 0:t.data;if(!r)return;const a=null===(n=Re(["file","get",r.avatarFileId]))||void 0===n?void 0:n.data;return Object.assign(Object.assign({},r),{avatar:a})},get image1_1(){const e=Re(["file","get",r]);if(e)return e.data||void 0},get image9_16(){const e=Re(["file","get",n]);if(e)return e.data||void 0}})},comment:lr,post:ur,user:on,category:e=>Object.assign(Object.assign({},e),{get avatar(){var t;if(!e.avatarFileId)return;return null===(t=Re(["file","get",`${e.avatarFileId}`]))||void 0===t?void 0:t.data}}),stream:e=>Object.assign(Object.assign({},e),{get moderation(){var t;return null===(t=Re(["streamModeration","get",e.streamId]))||void 0===t?void 0:t.data},get post(){var t;if("post"===e.referenceType)return null===(t=Re(["post","get",e.referenceId]))||void 0===t?void 0:t.data},get community(){var t;if("community"===e.targetType)return null===(t=Re(["community","get",e.targetId]))||void 0===t?void 0:t.data},get user(){var t;return null===(t=Re(["user","get",e.userId]))||void 0===t?void 0:t.data}}),story:e=>{const t=ar(),n=Re(["storyTarget","get",e.targetId]),r=Re(["community","get",e.targetId]);return Object.assign(Object.assign({},e),{analytics:{markAsSeen:()=>{e.expiresAt&&"synced"===e.syncState&&t.markStoryAsViewed(e)},markLinkAsClicked:()=>{e.expiresAt&&"synced"===e.syncState&&t.markStoryAsClicked(e)}},get videoData(){var t,n;const r=Re(["file","get",null===(n=null===(t=e.data)||void 0===t?void 0:t.videoFileId)||void 0===n?void 0:n.original]);if(!r)return;const{data:a}=r;return a||void 0},get imageData(){var t,n;if(!(null===(t=e.data)||void 0===t?void 0:t.fileId))return;const r=Re(["file","get",null===(n=e.data)||void 0===n?void 0:n.fileId]);if(!r)return;const{data:a}=r;return a?Object.assign(Object.assign({},a),{fileUrl:`${a.fileUrl}?size=full`}):void 0},get community(){if("community"===e.targetType&&r)return(null==r?void 0:r.data)||void 0},get communityCategories(){if("community"!==e.targetType)return;if(!r)return;const{data:{categoryIds:t}}=r;return 0!==t.length?t.map((e=>{const t=Re(["category","get",e]);return(null==t?void 0:t.data)||void 0})).filter((e=>void 0!==e)):void 0},get creator(){const t=Re(["user","get",e.creatorPublicId]);if(null==t?void 0:t.data)return on(t.data)},get storyTarget(){if(null==n?void 0:n.data)return or(n.data)},get isSeen(){const t=Re(["story-last-seen",e.targetId]);if(!(null==n?void 0:n.data))return!1;const r=(null==t?void 0:t.data)?new Date(t.data).getTime():0,a=new Date(null==n?void 0:n.data.lastStorySeenExpiresAt).getTime()||0,s=new Date(e.expiresAt).getTime();return Math.max(r,a)>=s}})},storyTarget:or,message:e=>{const t=Xt(e,["creatorPrivateId"]);return Object.assign(Object.assign({},t),{get readCount(){return hr(e).readCount},get deliveredCount(){return hr(e).deliveredCount},get creator(){var t;return null===(t=Re(["user","get",e.creatorId]))||void 0===t?void 0:t.data},markRead:()=>br(e)})},reactor:e=>Object.assign(Object.assign({},e),{get user(){var t;const n=null===(t=Re(["user","get",e.userId]))||void 0===t?void 0:t.data;if(n)return on(n)}}),channel:e=>{var t;let n=[];if("conversation"===e.type){const r=Ae(["channelUsers","get"]);r&&(null==r?void 0:r.length)>0&&(n=(null!==(t=null==r?void 0:r.filter((({data:t})=>t.channelId===e.channelId)))&&void 0!==t?t:[]).sort(((e,t)=>e.data.userInternalId.localeCompare(t.data.userInternalId))).slice(0,4).map((({data:e})=>wr(e))))}return hn(e,{markAsRead:()=>(async e=>{const t=Te();t.log("channel/markAsRead",e);const{data:n}=await t.http.put(`/api/v1/markers/channels/${e}/mark-read`),{userMarkers:r,userEntityMarkers:a,userFeedMarkers:s}=n,o=Xt(n,["userMarkers","userEntityMarkers","userFeedMarkers"]),i=t.cache&&Date.now(),c=rn(a),l=an(s);return t.cache&&Yt(Object.assign({userMarkers:r,userEntityMarkers:c,userFeedMarkers:l},o),{cachedAt:i}),it("local.channelMarker.updated",{userEntityMarkers:c}),it("local.subChannelMarker.updated",{userFeedMarkers:l}),!0})(e.channelInternalId),previewMembers:n})},pinnedPost:e=>{var t;const n=Re(["post","get",e.referenceId]),r=null===(t=Ae(["user","get"]).find((t=>{var n;return(null===(n=t.data)||void 0===n?void 0:n.userInternalId)===e.pinnedBy})))||void 0===t?void 0:t.data;return Object.assign(Object.assign({},e),{pinnedBy:r,get post(){if(null==n?void 0:n.data)return ur(n.data)},get target(){const e=Re(["pinTarget","get",null==n?void 0:n.data.targetId]);if(null==e?void 0:e.data)return null==e?void 0:e.data}})},notificationTray:e=>Object.assign(Object.assign({},e),{isSeen:e.lastSeenAt>e.lastOccurredAt,isRecent:new Date(e.lastOccurredAt).getTime()>=Date.now()-6048e5,users:e.actors.map((({publicId:e})=>Re(["user","get",e]))).filter(cr).map((({data:e})=>e)).map((e=>on(e)))}),community:ta,invitation:Hr,joinRequest:Ar,channelMember:wr},ra=e=>na.channel(Gn((e=>{var t;const n=e.messagePreviewId?sn(e.channelId):null,r=null===(t=Re(["user","get",null==n?void 0:n.creatorId]))||void 0===t?void 0:t.data,a=n?Object.assign(Object.assign({},n),{user:r?on(r):void 0}):null;return Object.assign(Object.assign({},e),{messagePreview:a})})(e))),aa=async e=>{const t=Te();t.log("channel/getChannelByIds",e);const n=e.map((e=>encodeURIComponent(e)));let r;try{r=(await t.http.get("/api/v3/channels/list",{params:{channelIds:n}})).data}catch(t){throw e.forEach((e=>{te(null==t?void 0:t.code)&&Zt("channel",e)})),t}const a=await Qn(r);t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&await Vn(r);const s=t.cache&&Date.now();return t.cache&&Yt(a,{cachedAt:s}),it("local.channel.fetched",a.channels),{data:a.channels.map((e=>ra(e))),cachedAt:s}};aa.locally=e=>{var t,n;const r=Te();if(r.log("channel/getChannelByIds.locally",e),!r.cache)return;const a=null===(t=Ae(["channel","get"]))||void 0===t?void 0:t.filter((({data:t})=>e.includes(t.channelPublicId)));if(!a||(null==a?void 0:a.length)<e.length)return;const s=a.map((({data:e})=>e)),o=null===(n=a.sort(((e,t)=>e.cachedAt<t.cachedAt?-1:1)))||void 0===n?void 0:n[0];return{data:s.map((e=>ra(e))),cachedAt:o.cachedAt}};class sa{constructor(){this._sessionState="notLoggedIn",this._listener=new Map}onSessionStateChange(e){return this._listener.set(e,e),()=>{this._listener.delete(e)}}setSessionState(e){this._sessionState!==e&&(this._sessionState=e,this._listener.forEach((t=>t(e))))}destroy(){this._listener.clear()}}let oa;var ia=()=>(oa||(oa=new sa),oa);const ca=e=>ia().onSessionStateChange(e),la=(e,t)=>{const n=setInterval(e,t);return()=>clearInterval(n)};let da=!1;const ua={},ha=async()=>{const e=Object.entries(ua).filter((([,e])=>e)).map((([e])=>e));return 0!==e.length&&(async e=>{const t=Te();t.log("subChannel/readingAPI",e);const{data:n}=await t.http.post("/api/v1/markers/message-feeds/reading",{messageFeedIds:e}),{userEntityMarkers:r,userFeedMarkers:a,feedMarkers:s,userMarkers:o}=n,i=rn(r),c=an(a),l=t.cache&&Date.now();return t.cache&&Yt({userEntityMarkers:i,userFeedMarkers:c,feedMarkers:s,userMarkers:o},{cachedAt:l}),it("local.feedMarker.fetched",{feedMarkers:s}),it("local.channelMarker.fetched",{userEntityMarkers:i}),it("local.subChannelMarker.fetched",{userFeedMarkers:c}),it("local.userMarker.fetched",{userMarkers:o}),!0})(e)},pa=()=>{da=!1},fa=()=>(da=!0,ca((e=>{"notLoggedIn"===e&&pa()})),()=>{pa()});la((async()=>{da&&await ha()}),3e4);const ma=async e=>{const t=Te();t.log("channel/getSubChannels",e);const n=await t.http.get("/api/v5/message-feeds/list",{params:{messageFeedIds:e.map(encodeURIComponent)}}),r=await Mn(n.data),a=t.cache&&Date.now();return t.cache&&Yt(r,{cachedAt:a}),it("local.message-feed.fetched",r),{data:r.messageFeeds,cachedAt:a}};ma.locally=e=>{var t;const n=Te();if(n.log("channel/getSubChannels.locally",e),!n.cache)return;const r=e.map((e=>Re(["subChannel","get",e]))).filter(Boolean);if((null==r?void 0:r.length)<e.length)return;return{data:r.map((({data:e})=>e)),cachedAt:(null===(t=r.sort(((e,t)=>e.cachedAt<t.cachedAt?-1:1)))||void 0===t?void 0:t[0]).cachedAt}};const ga=async(e=!0)=>{var t;const n=null===(t=Re(["MessagePreviewSetting"]))||void 0===t?void 0:t.data;if(!e&&n)return n;const r=await(async()=>{const e=Te(),{data:t}=await e.http.get("/api/v3/network-settings/chat");return t})();var a;return(a=r).messagePreview.enabled?a.messagePreview.isIncludeDeleted?"message-preview-include-deleted":"message-preview-not-include-deleted":"no-message-preview"},ya=async()=>{var e;const t=await ga();if(t===(null===(e=Re(["MessagePreviewSetting"]))||void 0===e?void 0:e.data))return;Me(["MessagePreviewSetting"],t);const n=[],r=[];if("no-message-preview"===t){const e=Ae(["MessagePreview"]);e&&(null==e?void 0:e.length)>0&&e.forEach((({key:e,data:t})=>{Ue(e),e.includes("MessagePreviewChannel")&&n.push(t.channelId),e.includes("MessagePreviewSubChannel")&&r.push(t.subChannelId)}))}else if("message-preview-not-include-deleted"===t){const e=Ae(["MessagePreview"]);e&&(null==e?void 0:e.length)>0&&e.forEach((({key:e,data:t})=>{(null==t?void 0:t.isDeleted)&&(Ue(e),e.includes("MessagePreviewChannel")&&n.push(t.channelId),e.includes("MessagePreviewSubChannel")&&r.push(t.subChannelId))})),0!==n.length&&await aa(n),0!==r.length&&await ma(r)}},va=async()=>{const e=Te(),{data:t}=await e.http.get("/api/v3/network-settings/social");return t.socialNetworkSetting},ba=(e,t)=>{var n;const r=null===(n=Re(["user","get",e]))||void 0===n?void 0:n.data;return!!r&&r.permissions.some((e=>e===t))},wa=e=>{const{userId:t}=Te();return{currentUser:()=>ba(t,e),community:n=>((e,t,n)=>{var r;if(!e)return!1;const a=null===(r=Re(["communityUsers","get",`${n}#${e}`]))||void 0===r?void 0:r.data;return!!a&&(!!a.permissions.some((e=>e===t))||ba(e,t))})(t,e,n),channel:n=>((e,t,n)=>{var r;if(!e)return!1;const a=null===(r=Re(["channelUsers","get",`${n}#${e}`]))||void 0===r?void 0:r.data;return!!a&&(!!a.permissions.some((e=>e===t))||ba(e,t))})(t,e,n)}},Ca=async e=>{const t=Te();if(t.log("channel/markerSync"),0===e.length)return!1;const{data:n}=await t.http.post("/api/v3/allowlists/verify",{data:e});return n.success},Ia=async e=>{const t=Te();if(t.log("channel/markerSync"),0===e.length)return!1;const{data:n}=await t.http.post("/api/v3/blocklists/verify",{data:e});return n.success},Sa=async()=>{const e=Te(),{data:t}=await e.http.get("/api/v3/network-settings/feed-setting");return Object.fromEntries(t.feedSettings.map((({feedType:e,contentSettings:t})=>[e,t])))},_a={notLoggedIn:["establishing"],terminated:["establishing"],establishing:["notLoggedIn","established"],established:["notLoggedIn","terminated","tokenExpired","establishing"],tokenExpired:["establishing"]},ka=e=>{const t=Te();t.log("client/api/setSessionState",e);const{sessionState:n}=t;if(n===e)return!1;if(!((e,t)=>_a[e].includes(t))(n,e))throw new Ce(`Session state cannot change from ${n} to ${e}`,8e5,"error");return t.sessionState=e,ia().setSessionState(e),!0},Oa=async e=>{const t=Te();ka("establishing");const{accessToken:n,users:r,expiresAt:a,issuedAt:s}=await(async({params:e,options:t})=>{const n=Te();n.log("client/api/getToken",e);const r=Ht(),{data:a}=await n.http.post("/api/v5/sessions",Object.assign(Object.assign({},e),{deviceInfo:r}),{headers:{"X-API-Key":n.apiKey,"set-access-token-cookie":(null==t?void 0:t.setAccessTokenCookie)||!1}});return a})(e);return t.http.defaults.headers.common.Authorization=`Bearer ${n}`,t.http.defaults.metadata={tokenExpiry:a,isGlobalBanned:!1,isUserDeleted:!1},t.upload.defaults.headers.common.Authorization=`Bearer ${n}`,t.upload.defaults.metadata={tokenExpiry:a,isGlobalBanned:!1,isUserDeleted:!1},t.ws&&(t.ws.io.opts.query={token:n}),t.token={accessToken:n,issuedAt:s,expiresAt:a},ka("established"),{accessToken:n,users:r}},Ta=e=>{const t=Ae(["subChannelUnreadInfo","get"]);if(t){(null==t?void 0:t.filter((({data:t})=>t.channelId===e))).forEach((({key:e,data:t})=>{Me(e,Object.assign(Object.assign({},t),{isDeleted:!0}))}))}},Ea=e=>{var t;const n=["channelUnreadInfo","get",e];(null===(t=Re(n))||void 0===t?void 0:t.data)&&Ue(n)},Aa=[];let Ra=null;const Ma=e=>{if(0===Aa.length){const e=Te(),t=async t=>{const n=await Qn(t),r=e.getMarkerSyncConsistentMode()&&e.isUnreadCountEnabled,a=e.useLegacyUnreadCount;n.channels.forEach((e=>{if(r)Ta(e.channelId),Ea(e.channelId);else if(a){const t=["channelUnread","get",e.channelId],n=Re(t);n&&Me(t,Object.assign(Object.assign({},n),{isDeleted:!0}))}})),Yt(n),Aa.forEach((e=>e(n.channels[0])))};Ra=ot(e,"onChannelDeleted","channel.deleted",t)}return Aa.push(e),()=>(e=>{const t=Aa.indexOf(e);t>-1&&Aa.splice(t,1),0===Aa.length&&(null==Ra||Ra())})(e)},ja=[];let Pa=null;const Ua=e=>{const t=Te();return Pa=ot(t,"onChannelMemberBanned","channel.banned",(async e=>{const n=await Qn(e),{channels:r,channelUsers:a}=n,s=a.some((e=>"banned"===e.membership&&e.userId===t.userId));t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&s&&n.channels.forEach((e=>{Ta(e.channelId),Ea(e.channelId)})),Yt(n),ja.forEach((e=>e(r[0],a.find((e=>"banned"===e.membership)))))})),ja.push(e),()=>(e=>{const t=ja.indexOf(e);t>-1&&ja.splice(t,1),0===ja.length&&(null==Pa||Pa())})(e)};function xa(e){return{users:e.users.map(En),files:e.files}}const Da=(e,t)=>{const n=Te();return ot(n,e,e,(e=>{const r=xa(e);n.cache&&Yt(r),t(r.users[0])}))},qa=e=>Da("user.deleted",e);var Na=()=>{const e=ar();return e.established(),ca((t=>{"established"===t?e.established():e.handleTokenExpired()})),()=>{e.destroy()}},Ba=()=>{const e=mr();return e.startSyncReadReceipt(),ca((t=>{"established"===t?e.onSessionEstablished():"tokenExpired"===t?e.onTokenExpired():e.onSessionDestroyed()})),()=>{e.onSessionDestroyed()}},La=()=>{const e=vr();return e.startSyncReadReceipt(),ca((t=>{"established"===t?e.onSessionEstablished():"tokenExpired"===t?e.onTokenExpired():e.onSessionDestroyed()})),()=>{e.onSessionDestroyed()}};const Fa=async e=>{const t=Te();t.log("channel/getChannelByIds",e);const n=e.map((e=>encodeURIComponent(e)));let r;try{r=(await t.http.get("/api/v3/channels/list",{params:{channelIds:n}})).data}catch(t){throw e.forEach((e=>{te(null==t?void 0:t.code)&&Zt("channel",e)})),t}const a=await Qn(r);t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&await Vn(r);const s=t.cache&&Date.now();return t.cache&&Yt(a,{cachedAt:s}),it("local.channel.fetched",a.channels),{data:a.channels,cachedAt:s}};Fa.locally=e=>{var t,n;const r=Te();if(r.log("channel/getChannelByIds.locally",e),!r.cache)return;const a=null===(t=Ae(["channel","get"]))||void 0===t?void 0:t.filter((({data:t})=>e.includes(t.channelPublicId)));if(!a||(null==a?void 0:a.length)<e.length)return;return{data:a.map((({data:e})=>e)),cachedAt:(null===(n=a.sort(((e,t)=>e.cachedAt<t.cachedAt?-1:1)))||void 0===n?void 0:n[0]).cachedAt}};class Ka{constructor(){this.TIMER_INTERVAL_MS=J,this.BUFFER_ID_LIMIT=100,this.buffer={channel:[],userMessageFeedMarker:[]},this.isResolvingTask=!1,this.connectionListener=[],this.isConnected=!0,this.addConnectionListener()}startResolver(){this.timer||(this.timer=setInterval((()=>{this.isConnected&&this.resolveObjects()}),this.TIMER_INTERVAL_MS))}stopResolver(){this.timer&&(clearInterval(this.timer),this.timer=void 0)}resolve(e,t){const n=this.getBuffer(t);n.includes(e)||(n.length>=this.BUFFER_ID_LIMIT&&n.shift(),n.push(e))}addConnectionListener(){this.connectionListener.length>0||(this.connectionListener.push((e=>{if("undefined"!=typeof window&&window.addEventListener)return window.addEventListener("online",e),()=>window.removeEventListener("online",e);if("undefined"!=typeof document&&document.addEventListener)return document.addEventListener("online",e),()=>document.removeEventListener("online",e);if("undefined"!=typeof navigator&&"ReactNative"===navigator.product){let t=()=>{};return import("@react-native-community/netinfo").then((n=>{t=n.addEventListener((t=>{t.isConnected&&e()}))})),()=>{t()}}return console.error("Unsupported environment"),()=>console.error("Unsupported environment")})((()=>{this.isConnected=!0}))),this.connectionListener.push((e=>{if("undefined"!=typeof window&&window.addEventListener)return window.addEventListener("offline",e),()=>window.removeEventListener("offline",e);if("undefined"!=typeof document&&document.addEventListener)return document.addEventListener("offline",e),()=>document.removeEventListener("offline",e);if("undefined"!=typeof navigator&&"ReactNative"===navigator.product){let t=()=>{};return import("@react-native-community/netinfo").then((n=>{t=n.addEventListener((t=>{t.isConnected||e()}))})),()=>{t()}}return console.error("Unsupported environment"),()=>console.error("Unsupported environment")})((()=>{this.isConnected=!1}))))}removeConnectionListener(){this.connectionListener.length>0&&this.connectionListener.forEach((e=>e()))}resolveObjects(){if(this.isResolvingTask)return;this.isResolvingTask=!0;const e=this.getBuffer("channel"),t=this.getBuffer("userMessageFeedMarker");this.clearBuffer(),e.length>0&&(async e=>{var t,n,r;await Fa(e);const a=null!==(r=null===(n=null===(t=Ae(["channel","get"]))||void 0===t?void 0:t.filter((({data:t})=>t.channelPublicId&&e.includes(t.channelPublicId))))||void 0===n?void 0:n.map((({data:e})=>e)))&&void 0!==r?r:[];it("local.channel.resolved",a)})(e),t.length>0&&(async e=>{const t=await zn(e),{feedMarkers:n,userFeedMarkers:r}=t;gn({feedMarkers:n,userFeedMarkers:r}),it("local.userMessageFeedMarkers.resolved",{feedMarkers:n,userFeedMarkers:r})})(t),this.isResolvingTask=!1}clearBuffer(){this.buffer={channel:[],userMessageFeedMarker:[]}}getBuffer(e){return this.buffer[e]}onSessionEstablished(){this.startResolver(),this.addConnectionListener()}onSessionDestroyed(){this.stopResolver(),this.clearBuffer(),this.isResolvingTask=!1,this.removeConnectionListener()}onTokenExpired(){this.stopResolver()}}let $a=null;var Qa=()=>($a||($a=new Ka),$a),za=()=>{const e=Qa();return e.startResolver(),ca((t=>{"established"===t?e.onSessionEstablished():"tokenExpired"===t?e.onTokenExpired():e.onSessionDestroyed()})),()=>{e.onSessionDestroyed()}};const Va=async()=>{var e,t;const n=Te();return n.log("client/api/disconnectClient"),n.mqtt&&n.mqtt.connected&&n.mqtt.disconnect(),n.ws&&n.ws.connected&&n.ws.disconnect(),"established"===n.sessionState&&ka("notLoggedIn"),n.emitter.all.clear(),null===(e=n.ws)||void 0===e||e.removeAllListeners(),null===(t=n.mqtt)||void 0===t||t.removeAllListeners(),n.userId=void 0,n.token=void 0,n.http.defaults.headers.common.Authorization="",n.http.defaults.metadata={tokenExpiry:"",isGlobalBanned:!1,isUserDeleted:!1},n.ws&&(n.ws.io.opts.query={token:""}),"undefined"!=typeof document&&(document.cookie="_ascSession=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;"),"tokenExpired"!==n.sessionState&&n.cache&&(n.cache={data:{}}),!0},Ha=e=>{const t=Te();ka("terminated"),t.http.defaults.metadata&&("globalBan"===e&&(t.http.defaults.metadata.isGlobalBanned=!0),"userDeleted"===e&&(t.http.defaults.metadata.isUserDeleted=!0)),t.sessionHandler=void 0,Va()},Ja=["disconnected","error","connect_error","reconnect_error","reconnect_failed"],Wa=e=>{const t=Te(),n=Ja.map((n=>ot(t,`client/onConnectionError(${n})`,n,(t=>{const r=(null==t?void 0:t.code)?new Ce(t.message,t.code,"fatal"):new _e(n);e(r)}))));return()=>{n.forEach((e=>e()))}},Ga=e=>{const t=Te();return ot(t,"client/onConnectionError(user.didGlobalBan)","user.didGlobalBan",e)},Ya=e=>{const t=Te();return ot(t,"client/onTokenExpired","tokenExpired",e)},Za=e=>{const t=Te();return ot(t,"client/onTokenTerminated","tokenTerminated",e)},Xa=e=>{const t=ve("channelMarker")({userId:Ze()._id,entityId:e.channelId});Ue(["channelMarker","get",t],!0)};let es=[];const ts=async(e,t,n)=>{var r;const a=Te();let s;a.log("client/api/connectClient",Object.assign({apiKey:a.apiKey,sessionState:a.sessionState},e)),a.userId&&a.userId!==e.userId&&(await Va(),es.forEach((e=>e())),es=[]);const o=await Vt();try{const{users:n}=await Oa({params:Object.assign(Object.assign({},e),{displayName:null==e?void 0:e.displayName,deviceId:(null==e?void 0:e.deviceId)||o}),options:{setAccessTokenCookie:!0}}),i=n.find((t=>t.userId===e.userId));if(null==i)throw new Ce(`${e.userId} has not been founded`,8e5,"error");if(i.isDeleted)return Ha("userDeleted"),!1;if(i.isGlobalBanned)return Ha("globalBan"),!1;st(a.ws,a.emitter),null===(r=a.ws)||void 0===r||r.open(),a.userId=i.userId,a.sessionHandler=t,s=a.accessTokenExpiryWatcher(t),Xe(i)}catch(e){throw ia().setSessionState("notLoggedIn"),e}return!0!==(null==n?void 0:n.disableRTE)&&async function(){await dt()}(),await ya(),0===es.length&&(es.push(Ga((e=>{Ha("globalBan"),es.forEach((e=>e())),s()})),Za((e=>{Ha(),es.forEach((e=>e())),s()})),qa((e=>{e.userId===a.userId&&(Ha("userDeleted"),es.forEach((e=>e())),s())})),Ya((e=>{ia().setSessionState(e),Va(),es.forEach((e=>e()))})),Ma(Xa),Ua(Xa),fa(),Na(),za()),a.useLegacyUnreadCount?es.push(Ba()):es.push(La())),!0},ns=()=>{let e,t=!1;const n=Te();n.log("initiating access token renewal");const r=async r=>{const{userId:a,displayName:s}=Ze(),o={userId:a,displayName:s,authToken:r,deviceId:await Vt()};"tokenExpired"===n.sessionState&&n.sessionHandler?await ts(o,n.sessionHandler):await Oa({params:o,options:{setAccessTokenCookie:!0}}),t=!0,e&&clearTimeout(e)};return{renew:()=>{t?console.log("'renew' method can be called only once per renewal instance"):r()},renewWithAuthToken:e=>{t?console.log("'renewWithAuthToken' method can be called only once per renewal instance"):r(e)},unableToRetrieveAuthToken:()=>{e=setTimeout((()=>{var e;null===(e=n.sessionHandler)||void 0===e||e.sessionWillRenewAccessToken(ns())}),W)}}},rs=3e5,as=e=>{const t=setInterval((()=>{const t=Te();if(!t.token)return;const{issuedAt:n,expiresAt:r}=t.token;if((e=>Date.now()>Date.parse(e)-rs)(r))return it("tokenExpired","tokenExpired"),void nt((()=>e.sessionWillRenewAccessToken(ns())));(e=>{const{expiresAt:t,issuedAt:n}=e,r=Date.parse(t),a=Date.parse(n),s=Date.now();return s>a+.8*(r-a-rs)&&s<r})({expiresAt:r,issuedAt:n})&&e.sessionWillRenewAccessToken(ns())}),W);return()=>clearInterval(t)},ss=[];let os=null;const is=e=>{if(0===ss.length){const e=Te();os=ot(e,"onChannelCreated","channel.created",(async e=>{const t=await Qn(e);Yt(t),ss.forEach((e=>e(t.channels[0])))}))}return ss.push(e),()=>(e=>{const t=ss.indexOf(e);t>-1&&ss.splice(t,1),0===ss.length&&(null==os||os())})(e)},cs=[],ls=[],ds=e=>{const t=Te();if(0===cs.length){const e=async e=>{const t=await Qn(e);Yt(t),cs.forEach((e=>e(t.channels[0])))};ls.push(ot(t,"onChannelUpdated","channel.updated",e)),ls.push(ot(t,"onChannelUpdated","local.channel.updated",(e=>cs.forEach((t=>t(e.channels[0]))))))}return cs.push(e),()=>(e=>{const t=cs.indexOf(e);t>-1&&cs.splice(t,1),0===cs.length&&ls.forEach((e=>e()))})(e)},us=[];let hs=null;const ps=e=>{if(0===us.length){const e=Te();hs=ot(e,"onChannelJoined","channel.joined",(async e=>{const t=await Qn(e),{channels:n,channelUsers:r}=t;Yt(t),us.forEach((e=>e(n[0],r[0])))}))}return us.push(e),()=>(e=>{const t=us.indexOf(e);t>-1&&us.splice(t,1),0===us.length&&(null==hs||hs())})(e)},fs=[];let ms=null;const gs=e=>{if(0===fs.length){const e=Te(),t=async t=>{const{userId:n}=Te(),{channelUsers:r}=t,a=r.some((e=>e.userId===n)),s=await Qn(t,{isMessagePreviewUpdated:a}),o=e.getMarkerSyncConsistentMode()&&e.isUnreadCountEnabled,i=e.useLegacyUnreadCount;a&&s.channels.forEach((e=>{o?(Ta(e.channelId),Ea(e.channelId)):i&&Ue(["channelUnread","get",e.channelId])}));const{channels:c,channelUsers:l}=s;Yt(s),fs.forEach((e=>e(c[0],l[0])))};ms=ot(e,"onChannelLeft","channel.left",t)}return fs.push(e),()=>(e=>{const t=fs.indexOf(e);t>-1&&fs.splice(t,1),0===fs.length&&(null==ms||ms())})(e)},ys=[];let vs=null;const bs=e=>{if(0===ys.length){const e=Te();vs=ot(e,"onChannelMuted","channel.setMuted",(async e=>{const t=await Qn(e);Yt(t),ys.forEach((e=>e(t.channels[0])))}))}return ys.push(e),()=>(e=>{const t=ys.indexOf(e);t>-1&&ys.splice(t,1),0===ys.length&&(null==vs||vs())})(e)},ws=[];let Cs=null;const Is=e=>{if(0===ws.length){const e=Te();Cs=ot(e,"onChannelMemberAdded","channel.membersAdded",(async e=>{const t=await Qn(e),{channels:n,channelUsers:r}=t;Yt(t),ws.forEach((e=>e(n[0],r.find((e=>"member"===e.membership)))))}))}return ws.push(e),()=>(e=>{const t=ws.indexOf(e);t>-1&&ws.splice(t,1),0===ws.length&&(null==Cs||Cs())})(e)},Ss=[];let _s=null;const ks=e=>{if(0===Ss.length){const e=Te();_s=ot(e,"onChannelMemberRemoved","channel.membersRemoved",(async e=>{const t=await Qn(e),{channels:n,channelUsers:r}=t;Yt(t),Ss.forEach((e=>e(n[0],r[0])))}))}return Ss.push(e),()=>(e=>{const t=Ss.indexOf(e);t>-1&&Ss.splice(t,1),0===Ss.length&&(null==_s||_s())})(e)},Os=[];let Ts=null;const Es=e=>{if(0===Os.length){const e=Te();Ts=ot(e,"onChannelMemberUnbanned","channel.unbanned",(async e=>{const t=await Qn(e),{channels:n,channelUsers:r}=t;Yt(t),Os.forEach((e=>e(n[0],r.find((e=>"none"===e.membership)))))}))}return Os.push(e),()=>(e=>{const t=Os.indexOf(e);t>-1&&Os.splice(t,1),0===Os.length&&(null==Ts||Ts())})(e)},As=[];let Rs=null;const Ms=e=>{if(0===As.length){const e=Te();Rs=ot(e,"onChannelMemberRoleAdded","local.channel-moderator.role-added",(async e=>{const{channels:t,channelUsers:n}=e;As.forEach((e=>e(t[0],n.find((e=>"member"===e.membership)))))}))}return As.push(e),()=>(e=>{const t=As.indexOf(e);t>-1&&As.splice(t,1),0===As.length&&(null==Rs||Rs())})(e)},js=[];let Ps=null;const Us=e=>{if(0===js.length){const t=Te();Ps=ot(t,"onChannelMemberRoleRemoved","local.channel-moderator.role-removed",(async t=>{const{channels:n,channelUsers:r}=t;e(n[0],r.find((e=>"member"===e.membership)))}))}return js.push(e),()=>(e=>{const t=js.indexOf(e);t>-1&&js.splice(t,1),0===js.length&&(null==Ps||Ps())})(e)},xs=e=>{const t=Te(),n=Ze(),r=[ot(t,"message/onMessageCreated","message.created",(async r=>{const a=await kn(r);t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&r.messages.forEach((e=>{(e=>{var t;const n=Te(),r=["subChannelUnreadInfo","get",e.messageFeedId],a=null===(t=Re(r))||void 0===t?void 0:t.data;if(!a)return;const s=a.lastSegment<e.segment?e.segment:a.lastSegment,o=s-a.readToSegment;let{lastMentionSegment:i}=a;e.mentionedUsers&&e.mentionedUsers.length>0&&e.mentionedUsers.forEach((t=>{("channel"===t.type||"user"===t.type&&n.userId&&t.userPublicIds.includes(n.userId))&&(i=e.segment)}));const c=Object.assign(Object.assign({},a),{lastMentionSegment:i,lastSegment:s,isMentioned:!(a.readToSegment>=i),unreadCount:Math.max(o,0)});Me(r,c)})(e),mn(e.channelId)})),t.useLegacyUnreadCount&&r.messages.forEach((e=>{var n,r;const a=null===(n=Re(["channelUnread","get",e.channelId]))||void 0===n?void 0:n.data;if(!a||a.lastSegment>=e.segment||"number"!=typeof a.readToSegment||"number"!=typeof a.lastMentionedSegment)return;const s=e.segment,o=(null===(r=e.mentionedUsers)||void 0===r?void 0:r.some((e=>"channel"===e.type||"user"===e.type&&t.userId&&e.userPublicIds.includes(t.userId))))?e.segment:a.lastMentionedSegment,i=Object.assign(Object.assign({},a),{lastSegment:s,unreadCount:Math.max(s-a.readToSegment,0),lastMentionedSegment:o,isMentioned:!(a.readToSegment>=o)});Me(["channelUnread","get",e.channelId],i),it("local.channelUnread.updated",[i])})),Yt(a),a.messages.forEach((t=>{t.creatorPrivateId===n._id&&br(t),e(t)}))}))];return()=>{r.forEach((e=>e()))}},Ds=e=>{const t=Te(),n=[ot(t,"message/onMessageCreated","local.message.created",(async t=>(Yt(t),t.messages.forEach((t=>{e(t)})))))];return()=>{n.forEach((e=>e()))}},qs=e=>{const t=Te();return ot(t,"onSubChannelCreated","message-feed.created",(async n=>{const r=await Mn(n);t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&n.messageFeeds.forEach((e=>{(e=>{const{channelId:t,subChannelId:n,createdAt:r,updatedAt:a}=e,s={channelId:t,subChannelId:n,unreadCount:0,readToSegment:0,lastMentionSegment:0,lastSegment:0,isMentioned:!1,isDeleted:!1,createdAt:r,updatedAt:a};Me(["subChannelUnreadInfo","get",s.subChannelId],s)})({channelId:e.channelId,subChannelId:e.messageFeedId,createdAt:e.createdAt,updatedAt:e.updatedAt})})),Yt(r),e(r.messageFeeds[0])}))},Ns=e=>{const t=Te(),n=[ot(t,"onSubChannelDeleted","message-feed.deleted",(async n=>{const r=await Mn(n);t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&r.messageFeeds.forEach((e=>{(e=>{var t;const n=["subChannelUnreadInfo","get",e],r=null===(t=Re(n))||void 0===t?void 0:t.data;r&&Me(n,Object.assign(Object.assign({},r),{isDeleted:!0}))})(e.subChannelId),mn(e.channelId)})),Yt(r),e(r.messageFeeds[0])})),ot(t,"local.message-feed.deleted","local.message-feed.deleted",(t=>e(t.messageFeeds[0])))];return()=>{n.forEach((e=>e()))}},Bs=async e=>{const t=Te();t.log("channel/markerSync");const{data:n}=await t.http.post("/api/v1/markers/sync",{deviceLastSyncAt:e}),{userEntityMarkers:r,userFeedMarkers:a,feedMarkers:s,userMarkers:o}=n,i=rn(r),c=an(a),l=t.cache&&Date.now();return t.cache&&Yt({userEntityMarkers:i,userFeedMarkers:c,feedMarkers:s,userMarkers:o},{cachedAt:l}),it("local.feedMarker.fetched",{feedMarkers:s}),it("local.channelMarker.fetched",{userEntityMarkers:i}),it("local.subChannelMarker.fetched",{userFeedMarkers:c}),it("local.userMarker.fetched",{userMarkers:o}),{data:n,hasMore:n.feedMarkers.length>0}};let Ls=!1,Fs=[],Ks=!1;let $s=null;let Qs=[];const zs=e=>{Qs=e},Vs=async()=>{var e;if(!Ks&&0!==Qs.length)try{Ks=!0,Qs=[];const t=await Bs((null==$s?new Date:$s).toISOString()),n=t.data.userMarkers.reduce(((e,t)=>null==e||e.getTime()<new Date(t.lastSyncAt).getTime()?new Date(t.lastSyncAt):e),null);null!=(e=n)&&(!$s||e.getTime()>$s.getTime())&&($s=e),t.hasMore&&Qs.push("has_more")}catch(e){}finally{Ks&&(Ks=!1)}};la((async()=>{Ls&&await Vs()}),2e3);const Hs=()=>true,Js=e=>{var t;const n=Te();if(n.mqtt)return null===(t=n.mqtt)||void 0===t?void 0:t.listen(e)};let Ws=[];var Gs;class Ys{constructor(){Gs.set(this,e.FileAccessTypeEnum.PUBLIC)}setFileAccessType(e){!function(e,t,n,r,a){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!a)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!a:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");"a"===r?a.call(e,n):a?a.value=n:t.set(e,n)}(this,Gs,e,"f")}getFileAccessType(){return function(e,t,n,r){if("a"===n&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?r:"a"===n?r.call(e):r?r.value:t.get(e)}(this,Gs,"f")}}let Zs;Gs=new WeakMap;var Xs=()=>(Zs||(Zs=new Ys),Zs);const eo=e=>{const t=Te();return ot(t,"channelMarker/onChannelMarkerFetched","local.channelMarker.fetched",(t=>{t.userEntityMarkers.forEach((t=>{e(t)}))}))},to=e=>{const t=Te();return ot(t,"subChannelMarker/onSubChannelMarkerFetched","local.subChannelMarker.fetched",(t=>{t.userFeedMarkers.forEach(e)}))},no=e=>{const t=Te();return ot(t,"subChannelMarker/onSubChannelMarkerUpdated","local.subChannelMarker.updated",(t=>{e(t.userFeedMarkers)}))},ro=e=>{const t=Te();return ot(t,"userMarker/onUserMarkerFetched","local.userMarker.fetched",(t=>{e(t.userMarkers)}))},ao=e=>{const t=Te();return ot(t,"messageMarker/onMessageMarkerFetched","local.messageMarker.fetched",(t=>{e(t.contentMarkers[0])}))},so=e=>{const t=Te();return ot(t,"messageMarker/onMessageMarked","marker.marked-message",(t=>{var n,r,a;Yt(t);const s=Ae(["message","collection"]),{contentMarkers:o,feedMarkers:i}=t;if(s&&(null==s?void 0:s.length)>0&&(null==i?void 0:i.length)>0){const e=s.filter((e=>{var t,n;return(null===(n=null===(t=e.data)||void 0===t?void 0:t.query)||void 0===n?void 0:n.subChannelId)===i[0].feedId}));if(e.length>0&&(null==o?void 0:o.length)>0){(null!==(a=null===(r=null===(n=e[0].data)||void 0===n?void 0:n.data)||void 0===r?void 0:r.map((e=>Re(["message","get",e]))).map((({data:e})=>e)).filter(Boolean))&&void 0!==a?a:[]).forEach((e=>{var t,n;const r=["messageMarker","get",ve("messageMarker")({creatorId:e.creatorPrivateId,feedId:e.subChannelId,contentId:e.messageId})],a=null===(t=Re(r))||void 0===t?void 0:t.data;if(!a)return;const s=o[0].feedId===a.feedId,i=o[0].readCount>a.readCount,c=(null===(n=o[0])||void 0===n?void 0:n.deliveredCount)>a.deliveredCount;if(s){const e=Object.assign(Object.assign({},a),{readCount:i?o[0].readCount:a.readCount,deliveredCount:c?o[0].deliveredCount:a.deliveredCount});Me(r,e)}}))}}e(t.contentMarkers[0])}))};var oo=Object.freeze({__proto__:null,getActiveClient:Te,getActiveUser:Ze,setActiveUser:Xe,createClient:(e,t=Tt.SG,{debugSession:n="amity",apiEndpoint:r,prefixDeviceIdKey:a,rteEnabled:s=!0}={})=>{var o,i,c;const l=(e=>{const t=`${null==e?void 0:e.trim()}`.length>0&&!Ot,n=g.default(e),r=(e,...r)=>{t&&n(e,r)};return r.__instance__=n,r})(n);l("client/api/createClient",{apiKey:e.replace(/.{5}$/g,"xxxxx"),apiRegion:t});const d=null!==(o=null==r?void 0:r.http)&&void 0!==o?o:At("http",t),u=null!==(i=null==r?void 0:r.upload)&&void 0!==i?i:At("upload",t),h=null!==(c=null==r?void 0:r.mqtt)&&void 0!==c?c:At("mqtt",t),p=Dt(d),f=Dt(u);let y,v;s&&(y=(e=>{const t=b.default(e,{autoConnect:!1,reconnectionDelay:2e3,transports:["websocket"]});return t.on("disconnect",(e=>{"io server disconnect"===e&&t.connect()})),t})(d),v=Gt(h));const w=m.default(),C={version:`${K}`,apiKey:e,log:l,cache:{data:{}},http:p,ws:y,mqtt:v,upload:f,emitter:w,sessionState:"notLoggedIn",accessTokenExpiryWatcher:as,sessionHandler:undefined,hasPermission:wa,validateUrls:Ca,validateTexts:Ia,getFeedSettings:Sa,getSocialSettings:va,getMessagePreviewSetting:ga,onRTEConnectionStateChange:Js,use:()=>Ee(C),isUnreadCountEnabled:!1,useLegacyUnreadCount:!0,getMarkerSyncConsistentMode:Hs,prefixDeviceIdKey:a};try{const t=Te();if(t.apiKey===e)return t;Ee(C)}catch(e){Ee(C)}return C},login:ts,logout:Va,secureLogout:async()=>{const e=Te(),{data:{success:t}}=await e.http.delete("/api/v4/sessions");if(!t)throw new Error("Failed to logout");return await Va()},resumeSession:async(e,t,n)=>{var r;const a=Te();let s;a.log("client/api/resumeSession",Object.assign({apiKey:a.apiKey,sessionState:a.sessionState},e)),a.userId&&(a.userId===e.userId&&(e=>{var t;const n=Te(),r=S.default(e);return(null===(t=null==r?void 0:r.user)||void 0===t?void 0:t.publicUserId)===n.userId})(e.token.accessToken)?(a.mqtt&&a.mqtt.connected&&a.mqtt.disconnect(),a.ws&&a.ws.connected&&a.ws.disconnect(),Ws.forEach((e=>e())),Ws=[]):(await Va(),Ws.forEach((e=>e())),Ws=[]));try{const n=await(async({token:e,userId:t})=>{const n=Te();ka("establishing");const{data:{users:r}}=await n.http.get(`/api/v3/users/${t}`,{headers:{Authorization:`Bearer ${e.accessToken}`}}),a=r.find((e=>e.userId===t));return n.http.defaults.headers.common.Authorization=`Bearer ${e.accessToken}`,n.http.defaults.metadata={tokenExpiry:e.expiresAt,isGlobalBanned:!1,isUserDeleted:!1},n.upload.defaults.headers.common.Authorization=`Bearer ${e.accessToken}`,n.upload.defaults.metadata={tokenExpiry:e.expiresAt,isGlobalBanned:!1,isUserDeleted:!1},n.ws&&(n.ws.io.opts.query={token:e.accessToken}),n.token=e,ka("established"),a})(e);if(null==n)throw new Ce(`${e.userId} has not been found`,8e5,"error");if(n.isDeleted)return Ha("userDeleted"),!1;if(n.isGlobalBanned)return Ha("globalBan"),!1;st(a.ws,a.emitter),null===(r=a.ws)||void 0===r||r.open(),a.userId=n.userId,a.sessionHandler=t,s=a.accessTokenExpiryWatcher(t),Xe(n)}catch(e){throw ia().setSessionState("notLoggedIn"),e}return!0!==(null==n?void 0:n.disableRTE)&&async function(){await dt()}(),await ya(),0===Ws.length&&(Ws.push(Ga((e=>{Ha("globalBan"),Ws.forEach((e=>e())),s()})),Za((e=>{Ha(),Ws.forEach((e=>e())),s()})),qa((e=>{e.userId===a.userId&&(Ha("userDeleted"),Ws.forEach((e=>e())),s())})),Ya((e=>{ia().setSessionState(e),Va(),Ws.forEach((e=>e()))})),Ma(Xa),Ua(Xa),fa(),Na(),za()),a.useLegacyUnreadCount?Ws.push(Ba()):Ws.push(La())),!0},isConnected:()=>{var e,t;const n=Te();n.log("client/api/isConnected",n);const r=n.ws&&n.ws.connected||!!n.ws;return!!(n.userId&&(null===(t=String(null===(e=n.http.defaults.headers.common)||void 0===e?void 0:e.Authorization))||void 0===t?void 0:t.length)&&r)},getFeedSettings:Sa,renewal:ns,markerSync:Bs,enableUnreadCount:()=>!0,setUploadedFileAccessType:function(e){Xs().setFileAccessType(e)},registerPushNotification:async e=>{const t=Te();let n;if("ios"!==u.Platform.OS&&"android"!==u.Platform.OS)throw new ke("Unsupported platform");n=u.Platform.OS;const r=await Vt(),{data:{status:a,error:s}}=await t.http.post("/v1/notification",{userId:t.userId,deviceId:r,platform:n,token:e},{headers:{"X-API-Key":t.apiKey}});if(s)throw new Ie(s,5e5,"error");return"success"===a},unregisterPushNotification:async()=>{const e=Te(),t=Vt(),{data:{status:n,error:r}}=await e.http.delete("/v1/notification",{data:{deviceId:t},headers:{"X-API-Key":e.apiKey}});if(r)throw new Ie(r,5e5,"error");return"success"===n},onRTEConnectionStateChange:Js,fetchLinkPreview:async e=>{const t=Te();let n=e;/^https?:\/\//i.test(e)||(n=`https://${e}`);const{data:r}=await t.http.get(`/api/v1/link-preview?url=${encodeURIComponent(n)}`);return r},onConnectionError:Wa,onClientDisconnected:e=>Wa((({code:t})=>{800211===t&&e()})),onClientBanned:Ga,onSessionStateChange:ca,onNetworkActivities:e=>Pt().onNetworkActivities(e),getUserUnread:e=>{const{_id:t}=Ze();if(!t)throw new Ce("The _id has not been defined in ActiveUser",8e5,"error");const{log:n,cache:r}=Te();r||console.log("For using Live Object feature you need to enable Cache!");n(`liveUserUnread(tmpid: ${Date.now()}) > listen`);const a=[];let s,o=!1;const i=t=>{const{data:n}=t,r=n?{unreadCount:n.unreadCount,isMentioned:n.isMentioned}:void 0;s=r?Dr(r):r,e({data:r?Object.assign(Object.assign({},r),{isMentioned:r.isMentioned}):r,loading:t.loading,error:t.error})};return a.push(ro((e=>(e=>{var n;const r=e.filter((e=>t===e.userId)),a=r.reduce(((e,t)=>null==e||new Date(t.lastSyncAt).getTime()>new Date(e.lastSyncAt).getTime()?t:e),null),o={unreadCount:null!==(n=null==a?void 0:a.unreadCount)&&void 0!==n?n:0,isMentioned:r.some((e=>!!e.isMentioned))};ir(s,o)||i({loading:!1,data:o})})(e)))),(()=>{const e=pe(yn);me(e,(({error:e,data:t,loading:n,origin:r,cachedAt:s})=>{!function(e){return null!=e&&null!=e}(t)?i({loading:n,data:void 0,origin:r,error:e}):(s===H?(i({data:t,origin:r,loading:!1,error:new Ie(V,800800,"error")}),o=!0,a.forEach((e=>e()))):o||i({loading:n,data:t,origin:r,error:e}),e&&a.forEach((e=>e())))}))})(),()=>{a.forEach((e=>e()))}},getMarkerSyncEvents:()=>Qs,setMarkerSyncEvents:zs,pushMarkerSyncEvent:e=>Qs.push(e),markerSyncTrigger:Vs,startMarkerSync:async()=>Promise.resolve(),startUnreadSync:async()=>Promise.resolve(),stopUnreadSync:()=>{Ls=!1,zs([]),Fs.forEach((e=>e())),Fs=[]},getMarkerSyncConsistentMode:Hs});function io(e){const{users:t,follows:n}=e,r=Xt(e,["users","follows"]);return Object.assign(Object.assign({},r),{follows:n,users:t.map(En)})}function co(e){const{users:t,follows:n}=e,r=Xt(e,["users","follows"]);return Object.assign(Object.assign({},r),{follows:n,users:t.map(En)})}function lo(e){const{follows:t}=e,n=Xt(e,["follows"]);return Object.assign(Object.assign({},n),{follows:t})}const uo=(e,t)=>{const n=Te();return ot(n,e,e,(e=>{const r=io(e);n.cache?(Yt(r),t(r.follows[0])):t(r.follows[0])}))},ho=(e,t)=>{const n=Te();return ot(n,e,e,(e=>{const r=lo(e);n.cache?(Yt(r),t(r.follows[0])):t(r.follows[0])}))},po=e=>uo("follow.created",e),fo=e=>uo("follow.unfollowed",e),mo=e=>uo("follow.followerDeleted",e),go=e=>uo("follow.requested",e),yo=e=>uo("follow.requestCanceled",e),vo=e=>uo("follow.accepted",e),bo=e=>uo("follow.requestDeclined",e),wo=async e=>{var t,n;const r=Te();r.log("follow/getFollowInfo",e);const{data:a}=await r.http.get(r.userId===e?"/api/v4/me/followInfo":`/api/v5/users/${e}/followInfo`),s=r.cache&&Date.now(),o="follows"in a?Object.assign(Object.assign({},a.followCounts[0]),{status:null===(n=null===(t=a.follows)||void 0===t?void 0:t[0])||void 0===n?void 0:n.status}):a.followCounts[0];return r.cache&&Me(["followInfo","get",e],o,{cachedAt:s}),{data:o,cachedAt:s}};wo.locally=e=>{const t=Te();if(t.log("follow/getFollowInfo.locally",e),!t.cache)return;const n=Re(["followInfo","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const Co=e=>{const t=async t=>{const[{data:n},{data:r}]=await Promise.all([wo(t.from),wo(t.to)]);e(n),e(r)},n=[uo("follow.created",t),uo("follow.requested",t),uo("follow.accepted",t),uo("follow.unfollowed",t),uo("follow.requestCanceled",t),uo("follow.requestDeclined",t),uo("follow.followerDeleted",t),ho("local.follow.created",t),ho("local.follow.requested",t),ho("local.follow.accepted",t),ho("local.follow.unfollowed",t),ho("local.follow.requestDeclined",t)];return()=>{n.forEach((e=>e()))}},Io=e=>ho("local.follow.created",e),So=e=>ho("local.follow.unfollowed",e),_o=e=>ho("local.follow.requested",e),ko=e=>ho("local.follow.accepted",e),Oo=e=>ho("local.follow.requestDeclined",e);class To extends Rr{async getRequest(e,t){const{limit:n=$,userId:r}=e,a=Xt(e,["limit","userId"]),s=t?{token:t}:{limit:n},o=Te().userId===r?"/api/v4/me/followers":`/api/v4/users/${r}/followers`,{data:i}=await this.http.get(o,{params:Object.assign(Object.assign({},a),{options:s,isDeleted:!1})});return i}}var Eo;!function(e){e.OnRequested="onRequested",e.OnAccepted="onAccepted",e.OnDeclined="onDeclined",e.OnCanceled="onCanceled",e.OnFollowed="onFollowed",e.OnUnfollowed="onUnfollowed",e.OnDeleted="onDeleted",e.OnUserDeleted="onUserDeleted"}(Eo||(Eo={}));class Ao extends jr{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Te(),r=n.cache&&Date.now();n.cache&&Yt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,a;if(n)Me(this.cacheKey,{data:e.follows.map(ve("follow"))});else{const t=null===(r=Re(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Me(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.follows.map(ve("follow"))])]}))}}reactor(e){return t=>{var n;const r=null===(n=Re(this.cacheKey))||void 0===n?void 0:n.data;if(this.query.userId===t.to&&r){switch(e){case Eo.OnDeclined:case Eo.OnCanceled:case Eo.OnUnfollowed:case Eo.OnDeleted:r.data=r.data.filter((e=>e!==ve("follow")(t)));break;case Eo.OnRequested:case Eo.OnAccepted:case Eo.OnFollowed:r.data=[...new Set([ve("follow")(t),...r.data])]}Me(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const Ro=({userId:e})=>t=>{const n=Te();return ot(n,"user.deleted","user.deleted",(n=>{const r=xa(n);Yt(r);const a=Re(["follow","get",ve("follow")({from:r.users[0].userId,to:e})]);a&&t(null==a?void 0:a.data)}))};class Mo extends Br{constructor(e,t){const n=I.default(Object.assign(Object.assign({},e),{type:"follower"})),r=["follow","collection",n];super(new To(e),n,r,t),this.query=e,this.queryStreamController=new Ao(this.query,this.cacheKey,this.notifyChange.bind(this),io),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Re(this.cacheKey))||void 0===e?void 0:e.data)||Me(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:po,action:Eo.OnFollowed},{fn:fo,action:Eo.OnUnfollowed},{fn:vo,action:Eo.OnAccepted},{fn:bo,action:Eo.OnDeclined},{fn:yo,action:Eo.OnCanceled},{fn:mo,action:Eo.OnDeleted},{fn:ko,action:Eo.OnAccepted},{fn:Oo,action:Eo.OnDeclined},{fn:Io,action:Eo.OnFollowed},{fn:So,action:Eo.OnUnfollowed},{fn:Ro({userId:this.query.userId}),action:Eo.OnUserDeleted}])}notifyChange({origin:e,loading:t,error:n}){var r,a;const s=null===(r=Re(this.cacheKey))||void 0===r?void 0:r.data;if(!s)return;const o=this.applyFilter(null!==(a=s.data.map((e=>Re(["follow","get",e]))).filter(cr).map((({data:e})=>e)))&&void 0!==a?a:[]);(this.shouldNotify(o)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:o,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=e;return this.query.status&&"all"!==this.query.status&&(t=t.filter((e=>e.status===this.query.status))),t=t.filter((e=>{var t;const n=null===(t=Re(["user","get",e.from]))||void 0===t?void 0:t.data;return null==(null==n?void 0:n.isDeleted)||!1===(null==n?void 0:n.isDeleted)})),t}}class jo extends Rr{async getRequest(e,t){const{limit:n=$,userId:r}=e,a=Xt(e,["limit","userId"]),s=t?{token:t}:{limit:n},o=Te().userId===r?"/api/v4/me/following":`/api/v4/users/${r}/following`,{data:i}=await this.http.get(o,{params:Object.assign(Object.assign({},a),{options:s,isDeleted:!1})});return i}}class Po extends jr{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Te(),r=n.cache&&Date.now();n.cache&&Yt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,a;if(n)Me(this.cacheKey,{data:e.follows.map(ve("follow"))});else{const t=null===(r=Re(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Me(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.follows.map(ve("follow"))])]}))}}reactor(e){return t=>{var n;const r=null===(n=Re(this.cacheKey))||void 0===n?void 0:n.data;if(this.query.userId===t.from&&r){switch(e){case Eo.OnDeclined:case Eo.OnCanceled:case Eo.OnUnfollowed:case Eo.OnDeleted:r.data=r.data.filter((e=>e!==ve("follow")(t)));break;case Eo.OnRequested:case Eo.OnAccepted:case Eo.OnFollowed:r.data=[...new Set([ve("follow")(t),...r.data])]}Me(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const Uo=({userId:e})=>t=>{const n=Te();return ot(n,"user.deleted","user.deleted",(n=>{const r=xa(n);Yt(r);const a=Re(["follow","get",ve("follow")({from:e,to:r.users[0].userId})]);a&&t(null==a?void 0:a.data)}))};class xo extends Br{constructor(e,t){const n=I.default(Object.assign(Object.assign({},e),{type:"following"})),r=["follow","collection",n];super(new jo(e),n,r,t),this.query=e,this.queryStreamController=new Po(this.query,this.cacheKey,this.notifyChange.bind(this),co),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Re(this.cacheKey))||void 0===e?void 0:e.data)||Me(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:go,action:Eo.OnRequested},{fn:vo,action:Eo.OnAccepted},{fn:bo,action:Eo.OnDeclined},{fn:yo,action:Eo.OnCanceled},{fn:po,action:Eo.OnFollowed},{fn:fo,action:Eo.OnUnfollowed},{fn:mo,action:Eo.OnDeleted},{fn:_o,action:Eo.OnRequested},{fn:ko,action:Eo.OnAccepted},{fn:Oo,action:Eo.OnDeclined},{fn:Io,action:Eo.OnFollowed},{fn:So,action:Eo.OnUnfollowed},{fn:Uo({userId:this.query.userId}),action:Eo.OnUserDeleted}])}notifyChange({origin:e,loading:t,error:n}){var r,a;const s=null===(r=Re(this.cacheKey))||void 0===r?void 0:r.data;if(!s)return;const o=this.applyFilter(null!==(a=s.data.map((e=>Re(["follow","get",e]))).filter(cr).map((({data:e})=>e)))&&void 0!==a?a:[]);(this.shouldNotify(o)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:o,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=e;return this.query.status&&"all"!==this.query.status&&(t=t.filter((e=>e.status===this.query.status))),t=t.filter((e=>{var t;const n=null===(t=Re(["user","get",e.to]))||void 0===t?void 0:t.data;return null==(null==n?void 0:n.isDeleted)||!1===(null==n?void 0:n.isDeleted)})),t}}const Do=(e,t,n,r,a,s)=>{const{forceDispatch:o,callbackDataSelector:i,callbackFilter:c}=Object.assign({forceDispatch:!1,callbackDataSelector:e=>e},s),{cache:l}=Te();let d;l||console.log("For using Live Object feature you need to enable Cache!");let u=!1;const h=[],p=e=>{const{data:n}=e,r=Xt(e,["data"]);c&&!c(n,d)||t(Object.assign({data:i(n)},r)),d=Dr(n)};return h.push(...a.map((t=>t((t=>((t,r=!1)=>{e===t[n]&&(d&&!r&&ir(d,t)||p({loading:!1,data:t,origin:"event"}))})(t,o)))))),(()=>{const t=pe(r,e,!0);me(t,(({error:e,data:t,loading:n,origin:r,cachedAt:a})=>{a===H?(p({data:t,origin:r,loading:!1,error:new Ie(V,800800,"error")}),u=!0,h.forEach((e=>e()))):u||p({loading:n,data:t,origin:r,error:e}),e&&h.forEach((e=>e()))}))})(),()=>{h.forEach((e=>e()))}};var qo=Object.freeze({__proto__:null,blockUser:async e=>{const t=Te();t.log("user/blockUser",e);const{data:n}=await t.http.post(`/api/v4/me/user-blocks/${e}`),r=t.cache&&Date.now(),{follows:a,followCounts:s}=n,o={follows:a};t.cache&&(Yt(o,{cachedAt:r}),Pe(["followInfo","get",e],s[0],{cachedAt:r}));const i=lo(o);return it("local.follow.unfollowed",i),n},unBlockUser:async e=>{const t=Te();t.log("user/unBlockUser",e);const{data:n}=await t.http.delete(`/api/v4/me/user-blocks/${e}`),r=t.cache&&Date.now(),{follows:a,followCounts:s}=n,o={follows:a};t.cache&&(Yt(o,{cachedAt:r}),Pe(["followInfo","get",e],s[0],{cachedAt:r}));const i=lo(o);return it("local.follow.created",i),n},follow:async e=>{const t=Te();t.log("follow/follow",e);const{data:n}=await t.http.post(`/api/v4/me/following/${e}`),r=t.cache&&Date.now();t.cache&&Yt(n,{cachedAt:r});const a=lo(n);return"accepted"===n.follows[0].status?it("local.follow.created",a):it("local.follow.requested",a),{data:n.follows[0],cachedAt:r}},unfollow:async e=>{const t=Te();t.log("follow/unfollow",e);const{data:n}=await t.http.delete(`/api/v4/me/following/${e}`);t.cache&&Yt(n);const r=lo(n);return it("local.follow.unfollowed",r),!0},acceptMyFollower:async e=>{const t=Te();t.log("follow/acceptMyFollower",e);const{data:n}=await t.http.post(`/api/v4/me/followers/${e}`);t.cache&&Yt(n);const r=lo(n);return it("local.follow.accepted",r),!0},declineMyFollower:async e=>{const t=Te();t.log("follow/declineMyFollower",e);const{data:n}=await t.http.delete(`/api/v4/me/followers/${e}`);t.cache&&Yt(n);const r=lo(n);return it("local.follow.requestDeclined",r),!0},onUserFollowed:po,onUserUnfollowed:fo,onFollowerDeleted:mo,onFollowerRequested:go,onFollowRequestCanceled:yo,onFollowRequestAccepted:vo,onFollowRequestDeclined:bo,onFollowInfoUpdated:Co,onLocalUserFollowed:Io,onLocalUserUnfollowed:So,onLocalFollowerRequested:_o,onLocalFollowRequestAccepted:ko,onLocalFollowRequestDeclined:Oo,getFollowers:(e,t,n)=>{const{log:r,cache:a}=Te();a||console.log(z);const s=Date.now();r(`getFollowers(tmpid: ${s}) > listen`);const o=new Mo(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>Ue(c))),()=>{r(`getFollowers(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}},getFollowings:(e,t,n)=>{const{log:r,cache:a}=Te();a||console.log("For using Live Collection feature you need to enable Cache!");const s=Date.now();r(`getFollowings(tmpid: ${s}) > listen`);const o=new xo(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>Ue(c))),()=>{r(`getFollowings(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}},getFollowInfo:(e,t)=>Do(e,t,"userId",wo,[Co],{forceDispatch:!0}),getMyFollowInfo:e=>{const{userId:t}=Ze();return Do(t,e,"userId",wo,[Co],{forceDispatch:!0})}});const No=async e=>{const t=Te();t.log("user/getUsers",e);const n=e.map((e=>encodeURIComponent(e))),{data:r}=await t.http.get("/api/v3/users/list",{params:{userIds:n}}),a=xa(r),s=t.cache&&Date.now();return t.cache&&Yt(a,{cachedAt:s}),it("user.fetched",r),{data:a.users.map((e=>na.user(e))),cachedAt:s}};No.locally=e=>{var t;const n=Te();if(n.log("user/getUsers.locally",e),!n.cache)return;const r=e.map((e=>Re(["user","get",e]))).filter(Boolean),a=r.map((({data:e})=>na.user(e))),s=null===(t=r.sort(((e,t)=>e.cachedAt<t.cachedAt?-1:1)))||void 0===t?void 0:t[0];return(null==r?void 0:r.length)<e.length?void 0:{data:a,cachedAt:s.cachedAt}};const Bo=e=>Da("user.updated",e),Lo=e=>Da("user.flagged",e),Fo=e=>Da("user.unflagged",e),Ko=e=>Da("user.flagCleared",e),$o=e=>Da("user.fetched",e),Qo=async e=>{const t=Te();t.log("user/getUser",e),fn("user",e);try{const{data:n}=await t.http.get(`/api/v3/users/${encodeURIComponent(e)}`),r=t.cache&&Date.now(),a=xa(n);return t.cache&&Yt(a,{cachedAt:r}),it("user.fetched",n),{data:a.users.find((t=>t.userId===e)),cachedAt:r}}catch(t){throw te(null==t?void 0:t.code)&&Zt("user",e),t}};Qo.locally=e=>{const t=Te();if(t.log("user/getUser.locally",e),!t.cache)return;const n=Re(["user","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};class zo extends Rr{async getRequest(e,t){const{limit:n=$}=e,r=Xt(e,["limit"]),a=t?{token:t}:{limit:n},{data:s}=await this.http.get("/api/v3/users",{params:Object.assign(Object.assign({},r),{options:a,isDeleted:!1})});return s}}class Vo extends jr{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Te(),r=n.cache&&Date.now();n.cache&&Yt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,a;if(n)Me(this.cacheKey,{data:e.users.map(ve("user"))});else{const t=null===(r=Re(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Me(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.users.map(ve("user"))])]}))}}reactor(e){return e=>{var t;const n=null===(t=Re(this.cacheKey))||void 0===t?void 0:t.data;n&&(n.data=[...new Set([e.userId,...n.data])],Me(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}var Ho;!function(e){e.OnUserDeleted="onUserDeleted",e.OnUserUpdated="onUserUpdated",e.OnUserFlagged="onUserFlagged",e.OnUserUnflagged="onUserUnflagged",e.OnUserFlagCleared="onUserFlagCleared"}(Ho||(Ho={}));class Jo extends Br{constructor(e,t){const n=I.default(e),r=["user","collection",n];super(new zo(e),n,r,t),this.query=e,this.queryStreamController=new Vo(this.query,this.cacheKey,this.notifyChange.bind(this),xa),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Re(this.cacheKey))||void 0===e?void 0:e.data)||Me(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:qa,action:Ho.OnUserDeleted},{fn:Bo,action:Ho.OnUserUpdated},{fn:Lo,action:Ho.OnUserFlagged},{fn:Fo,action:Ho.OnUserUnflagged},{fn:Ko,action:Ho.OnUserFlagCleared}])}notifyChange({origin:e,loading:t,error:n}){var r,a;const s=null===(r=Re(this.cacheKey))||void 0===r?void 0:r.data;if(!s)return;const o=this.applyFilter(null!==(a=s.data.map((e=>Re(["user","get",e]))).filter(cr).map((({data:e})=>e)).map(na.user))&&void 0!==a?a:[]);(this.shouldNotify(o)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:o,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=e;const n=(()=>"firstCreated"===this.query.sortBy?ze:He)();return t=t.sort(n),"flagged"===this.query.filter&&(t=t.filter((e=>!!e.hashFlag))),t=t.filter((e=>null==e.isDeleted||!1===e.isDeleted)),t}}class Wo extends Rr{async getRequest(e,t){const{limit:n=$}=e,r=Xt(e,["limit"]),a=t?{token:t}:{limit:n},{data:s}=await this.http.get("/api/v4/me/user-blocks",{params:Object.assign(Object.assign({},r),{options:a,isDeleted:!1})});return s}}class Go extends jr{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Te(),r=n.cache&&Date.now();n.cache&&Yt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,a;if(n)Me(this.cacheKey,{data:e.users.map(ve("user"))});else{const t=null===(r=Re(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Me(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.users.map(ve("user"))])]}))}}reactor(e){return t=>{var n;if(e===Eo.OnFollowed){const e=null===(n=Re(this.cacheKey))||void 0===n?void 0:n.data,r=null==e?void 0:e.data.filter((e=>e!==t.userId));Me(this.cacheKey,Object.assign(Object.assign({},e),{data:r}))}this.notifyChange({origin:"event",loading:!1})}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}function Yo(e){const{users:t,follows:n}=e,r=Xt(e,["users","follows"]);return Object.assign(Object.assign({},r),{follows:n.map((e=>{const n=t.find((t=>t.userId===e.from));return Object.assign(Object.assign({},e),{user:En(n)})})),users:t.map(En)})}const Zo=(e,t,n)=>r=>e((e=>{var a;if(!e)return e;const s=[n,"get",`${e[t]}`],o=null===(a=Re(s))||void 0===a?void 0:a.data;return o?r(o):void 0}));class Xo extends Br{constructor(e,t){const n=I.default(e),r=["blockedUsers","collection",n];super(new Wo(e),n,r,t),this.query=e,this.queryStreamController=new Go(this.query,this.cacheKey,this.notifyChange.bind(this),Yo),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Re(this.cacheKey))||void 0===e?void 0:e.data)||Me(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:qa,action:Ho.OnUserDeleted},{fn:Zo(Io,"to","user"),action:Eo.OnFollowed},{fn:Zo(po,"to","user"),action:Eo.OnFollowed}])}notifyChange({origin:e,loading:t,error:n}){var r,a;const s=null===(r=Re(this.cacheKey))||void 0===r?void 0:r.data;if(!s)return;const o=this.applyFilter(null!==(a=s.data.map((e=>Re(["user","get",e]))).filter(cr).map((({data:e})=>e)).map(na.user))&&void 0!==a?a:[]);(this.shouldNotify(o)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:o,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=e;return t=t.filter((e=>null==e.isDeleted||!1===e.isDeleted)),t}}class ei extends Rr{async getRequest(e,t){const{limit:n=$,displayName:r}=e,a=Xt(e,["limit","displayName"]),s=t?{token:t}:{limit:n},{data:o}=await this.http.get("/api/v3/users",{params:Object.assign(Object.assign({},a),{keyword:r,options:s,isDeleted:!1})});return o}}class ti extends jr{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Te(),r=n.cache&&Date.now();n.cache&&Yt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,a;if(n)Me(this.cacheKey,{data:e.users.map(ve("user"))});else{const t=null===(r=Re(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Me(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.users.map(ve("user"))])]}))}}reactor(e){return e=>{var t;const n=null===(t=Re(this.cacheKey))||void 0===t?void 0:t.data;n&&(n.data=[...new Set([e.userId,...n.data])],Me(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class ni extends Br{constructor(e,t){var n;const r=I.default(e),a=["user","collection",r];super(new ei(e),r,a,t),this.query=Object.assign(Object.assign({},e),{filter:null!==(n=e.filter)&&void 0!==n?n:"all"}),this.queryStreamController=new ti(this.query,this.cacheKey,this.notifyChange.bind(this),xa),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Re(this.cacheKey))||void 0===e?void 0:e.data)||Me(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:qa,action:Ho.OnUserDeleted},{fn:Bo,action:Ho.OnUserUpdated},{fn:Lo,action:Ho.OnUserFlagged},{fn:Fo,action:Ho.OnUserUnflagged},{fn:Ko,action:Ho.OnUserFlagCleared}])}notifyChange({origin:e,loading:t,error:n}){var r,a;const s=null===(r=Re(this.cacheKey))||void 0===r?void 0:r.data;if(!s)return;const o=this.applyFilter(null!==(a=s.data.map((e=>Re(["user","get",e]))).filter(cr).map((({data:e})=>e)).map(na.user))&&void 0!==a?a:[]);(this.shouldNotify(o)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:o,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=e;return"flagged"===this.query.filter&&(t=t.filter((e=>!!e.hashFlag))),t=t.filter((e=>null==e.isDeleted||!1===e.isDeleted)),t}}const ri=async({viewId:e,viewedType:t,limit:n,token:r})=>{const a=Te(),s={};r?s.token=r:s.limit=n;const o=`/api/v1/analytics/views/${"post"===t?"posts":"stories"}/${e}/users`,i=await a.http.get(o,{params:s});return Yt(i.data),i.data};var ai;!function(e){e.DEFAULT="default",e.PARTIAL="partial"}(ai||(ai={}));var si=Object.freeze({__proto__:null,Relationship:qo,getUserByIds:No,updateUser:async(e,t)=>{const n=Te();n.log("user/updateUser",e,t);const{data:r}=await n.http.put("/api/v3/users/",Object.assign(Object.assign({userId:e},t),{createNewUserWhenNotFound:!1})),a=xa(r),s=n.cache&&Date.now();return n.cache&&Yt(a,{cachedAt:s}),it("user.updated",r),{data:a.users.find((t=>t.userId===e)),cachedAt:s}},flagUser:async e=>{const t=Te();t.log("user/flagUser",e);const{data:n}=await t.http.post(`api/v4/me/flags/${encodeURIComponent(e)}`),r=xa(n);return t.cache&&Yt(r),it("user.flagged",n),!!r},unflagUser:async e=>{const t=Te();t.log("user/unflag",e);const{data:n}=await t.http.delete(`/api/v4/me/flags/${encodeURIComponent(e)}`),r=xa(n);return t.cache&&Yt(r),it("user.unflagged",n),!!r},isUserFlaggedByMe:async e=>{const t=Te();t.log("user/isUserFlaggedByMe",e);const{data:{isFlagByMe:n}}=await t.http.get(`/api/v3/users/${e}/isFlagByMe`);return n},onUserUpdated:Bo,onUserDeleted:qa,onUserFlagged:Lo,onUserUnflagged:Fo,onUserFlagCleared:Ko,getUser:(e,t)=>Do(e,(e=>t(Object.assign(Object.assign({},e),{data:e.data?na.user(e.data):e.data}))),"userId",Qo,[$o,Bo,qa,Lo,Fo,Ko]),getUsers:(e,t,n)=>{const{log:r,cache:a}=Te();a||console.log(z);const s=Date.now();r(`liveUsers(tmpid: ${s}) > listen`);const o=new Jo(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>Ue(c))),()=>{r(`liveUsers(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}},getBlockedUsers:(e,t,n)=>{const{log:r,cache:a}=Te();a||console.log(z);const s=Date.now();r(`getBlockedUsers(tmpid: ${s}) > listen`);const o=new Xo(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>Ue(c))),()=>{r(`getBlockedUsers(tmpid: ${s}) > dispose`),i.forEach((e=>e())),Ue(c)}},searchUserByDisplayName:(e,t,n)=>{const{log:r,cache:a}=Te();a||console.log(z);const s=Date.now();r(`liveSearchUsers(tmpid: ${s}) > listen`);const o=new ni(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>Ue(c))),()=>{r(`liveSearchUsers(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}},getReachedUsers:(e,t)=>{let n=(e=!1)=>{};const{log:r,cache:a}=Te(),s=["viewedUsers","collection",{viewId:e.viewId,viewedType:e.viewedType}];a||console.log(z);const o=Date.now();r(`getReachUsers(tmpid: ${o}) > listen`);const{limit:i,viewId:c,viewedType:l}=e;return n=(e=!1)=>{var r,a,o;const d=null===(r=Re(s))||void 0===r?void 0:r.data,u=null!==(a=null==d?void 0:d.data)&&void 0!==a?a:[];if(!e&&u.length>0&&!(null==d?void 0:d.params.page))return;const h=pe(ri,{viewId:c,viewedType:l,limit:i||10,token:e||null===(o=null==d?void 0:d.params.page)||void 0===o?void 0:o.next});me(h,(e=>{var r,a,o,i,c;let l=null!==(o=null===(a=null===(r=Re(s))||void 0===r?void 0:r.data)||void 0===a?void 0:a.data)&&void 0!==o?o:[];(null===(i=e.data)||void 0===i?void 0:i.users)&&(l=[...new Set([...l,...e.data.users.map((({userId:e})=>e))])]);const d={loading:e.loading,params:{page:null===(c=e.data)||void 0===c?void 0:c.paging},data:l||[]};Me(s,d),(e=>{var r,a;let s=[];(null==e?void 0:e.data)&&(s=e.data.map((e=>Re(["user","get",e]))).filter(Boolean).map((e=>null==e?void 0:e.data))||[]),t({onNextPage:n,data:s,hasNextPage:!!(null===(a=null===(r=e.params)||void 0===r?void 0:r.page)||void 0===a?void 0:a.next),loading:e.loading||!1})})(d)}),fe(Q,2e3))},n(!0),()=>{r(`getReachUsers(tmpid: ${o}) > dispose`),Ue(s)}},get AmityUserSearchMatchType(){return ai}});const oi=async e=>{const t=Te();t.log("file/getFile",e);const{data:n}=await t.http.get(`/api/v3/files/${e}`),r=t.cache&&Date.now();return t.cache&&Yt({files:[n]},{cachedAt:r}),{data:n,cachedAt:r}};oi.locally=e=>{const t=Te();if(t.log("file/getFile.locally",e),!t.cache)return;const n=Re(["file","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const ii=async(e,t,n)=>{const r=Te();r.log("file/uploadVideo",e);const a=e.getAll("files");if(!a.length)throw new Error("The formData object must have a `files` key.");const s=Xs().getFileAccessType();e.append("accessType",s),e.append("preferredFilename",a[0].name),t&&e.append("feedType",t);const o="getHeaders"in e?e.getHeaders():{"content-type":"multipart/form-data"},{data:i}=await r.upload.post("/api/v4/videos",e,{headers:o,onUploadProgress({loaded:e,total:t=100}){n&&n(Math.round(100*e/t))}}),c=r.cache&&Date.now();return r.cache&&Yt({files:i},{cachedAt:c}),{data:i,cachedAt:c}},ci=async(e,t,n)=>{const r=Te();r.log("file/uploadImage",e);const a=e.getAll("files");if(null==a?void 0:a.length)console.warn("Deprecation Warning: `files` is deprecated, please use `file` instead."),e.append("preferredFilename",a[0].name);else{const t=e.get("file");if(!t)throw new Error("The formData object must have a `file` or `files` key");e.append("preferredFilename",t.name),n&&e.append("altText",n)}const s=Xs().getFileAccessType();e.append("accessType",s);const o="getHeaders"in e?e.getHeaders():{"content-type":"multipart/form-data"},{data:i}=await r.upload.post("/api/v4/images",e,{headers:o,onUploadProgress({loaded:e,total:n=100}){t&&t(Math.round(100*e/n))}}),c=r.cache&&Date.now();return r.cache&&Yt({files:i},{cachedAt:c}),{data:i,cachedAt:c}};var li=Object.freeze({__proto__:null,getFile:oi,uploadFile:async(e,t)=>{const n=Te();n.log("file/uploadFile",e);const r=e.getAll("files");if(!r.length)throw new Error("The formData object must have a `files` key.");const a=Xs().getFileAccessType();e.append("accessType",a),e.append("preferredFilename",r[0].name);const s="getHeaders"in e?e.getHeaders():{"content-type":"multipart/form-data"},{data:o}=await n.upload.post("/api/v4/files",e,{headers:s,onUploadProgress({loaded:e,total:n=100}){t&&t(Math.round(100*e/n))}}),i=n.cache&&Date.now();return n.cache&&Yt({files:o},{cachedAt:i}),{data:o,cachedAt:i}},deleteFile:async e=>{const t=Te();return t.log("file/deleteFile",e),await t.http.delete(`/api/v3/files/${e}`),Ue(["file","get",e],!0),{success:!0}},fileUrlWithSize:(e,t)=>`${e}?size=${t}`,uploadVideo:ii,uploadImage:ci,updateAltText:async(e,t)=>{const n=Te();n.log("file/updateAltText",t);const{data:r}=await n.http.put(`/api/v3/files/${e}`,{altText:t}),a=n.cache&&Date.now();return n.cache&&Yt({files:[r]},{cachedAt:a}),!0}});const di=async e=>{const t=Te();t.log("role/queryRoles",e);const n=null!=e?e:{},{limit:r=10,queryToken:a,displayName:s,sortBy:o}=n,i=Xt(n,["limit","queryToken","displayName","sortBy"]),c=a?{token:a}:r?{limit:r}:void 0,{data:l}=await t.http.get("/api/v3/roles",{params:Object.assign(Object.assign({},i),{keyword:s,sortBy:o,options:c})}),{paging:d}=l,u=Xt(l,["paging"]),{roles:h}=u,p=t.cache&&Date.now();t.cache&&Yt(u,{cachedAt:p});const f=ie(d.next);return{data:h,cachedAt:p,prevPage:ie(d.previous),nextPage:f,paging:d}};di.locally=e=>{Te().log("role/queryRoles.locally",e)};const ui=async e=>{const t=Te();t.log("role/getRole",e);const{data:n}=await t.http.get(`/api/v3/roles/${e}`),r=t.cache&&Date.now();return t.cache&&Yt({roles:n},{cachedAt:r}),{data:n.find((t=>t.roleId===e)),cachedAt:r}};ui.locally=e=>{const t=Te();if(t.log("role/getRole.locally",e),!t.cache)return;const n=Re(["role","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const hi=(e,t)=>{"message"===e?it("local.message.updated",{messages:[t]}):"post"===e?it("post.updated",{posts:[t]}):"comment"===e?it("comment.updated",{comments:[t]}):"story"===e&&it("story.updated",{categories:[],comments:[],communities:[],communityUsers:[],files:[],users:[],stories:[t]})},pi=async(e,t=!1)=>{const n=Te();let r;n.log("message/getMessage",e),fn("message",e);try{const{data:t}=await n.http.get(`/api/v5/messages/${encodeURIComponent(e)}`);r=await kn(t)}catch(t){throw te(null==t?void 0:t.code)&&Zt("message",e),t}const a=n.cache&&Date.now();n.cache&&Yt(r,{cachedAt:a});const{messages:s}=r;return it("local.message.fetched",{messages:s}),{data:s.find((t=>t.messageId===e)),cachedAt:a}};pi.locally=e=>{const t=Te();if(t.log("message/getMessage.locally",e),!t.cache)return;const n=Re(["message","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const fi=async e=>{const t=Te();let n;t.log("post/getPost",e),fn("post",e);try{n=(await t.http.get(`/api/v3/posts/${encodeURIComponent(e)}`)).data}catch(t){throw te(null==t?void 0:t.code)&&Zt("post",e),t}const r=tn(n,"communityUsers"),a=t.cache&&Date.now();t.cache&&Yt(r,{cachedAt:a});const{posts:s}=r;return{data:s.find((t=>t.postId===e)),cachedAt:a}};fi.locally=e=>{const t=Te();if(t.log("post/getPost.locally",e),!t.cache)return;const n=Re(["post","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const mi=async e=>{const t=Te();let n;t.log("comment/getComment",e),fn("comment",e);try{n=(await t.http.get(`/api/v3/comments/${encodeURIComponent(e)}`)).data}catch(t){throw te(null==t?void 0:t.code)&&Zt("comment",e),t}const r=t.cache&&Date.now();t.cache&&Yt(n,{cachedAt:r});const{comments:a}=n;return{data:na.comment(a.find((t=>t.commentId===e))),cachedAt:r}};mi.locally=e=>{const t=Te();if(t.log("comment/getComment.locally",e),!t.cache)return;const n=Re(["comment","get",e]);return n?{data:na.comment(n.data),cachedAt:n.cachedAt}:void 0};const gi=(e,t)=>{var n,r;let a,s;if("post"===t)s="post",a=e.posts[0].postId;else if("comment"===t)s="comment",a=e.comments[0].commentId;else{if("story"!==t)throw new Error("Unknown event type");s="story",a=e.stories[0].referenceId}return(null===(r=null===(n=Re([s,"get",a]))||void 0===n?void 0:n.data)||void 0===r?void 0:r.myReactions)||[]},yi=(e,t,n)=>{const[r]=e[t];return Object.assign(Object.assign({},e),{[t]:[Object.assign(Object.assign({},r),{myReactions:n})]})},vi=(e,t,n,r=[])=>{const a=e.split(".")[1];let s=r;if(Te().userId===t)if(["addReaction","reactionAdded"].includes(a))s.includes(n)||s.push(n);else{if(!["removeReaction","reactionRemoved"].includes(a))throw new Error(`Unknown event type: ${a}`);s=s.filter((e=>e!==n))}return s},bi=(e,t)=>{const n=e.split(".")[0],r=gi(t,n),a=vi(e,t.reactor.userId,t.reactor.reactionName,r);return yi(t,`${n}s`,a)},wi=(e,t)=>{var n,r;const a=e.split(".")[0];let s=gi(t,a);(null==t?void 0:t.reactions)&&t.reactions.length>0&&(s=vi(e,null===(n=t.reactions[0])||void 0===n?void 0:n.userId,null===(r=t.reactions[0])||void 0===r?void 0:r.reactionName,s));const o=yi(t,"stories",s);if(!(null==t?void 0:t.communities)||!(null==t?void 0:t.communityUsers))return o;const i=Cr(t.communities,t.communityUsers);return Object.assign(Object.assign({},o),{communities:i})},Ci=async(e,t,n)=>{var r,a,s;const o=Te();if(o.log("reaction/createReaction",{referenceId:t,referenceType:e,reactionName:n}),!["post","comment","story","message"].includes(e))throw new Ie("The reference type is not valid. It should be one of post, comment, story, or message",4e5,"error");const{data:i}=await o.http.post("/api/v2/reactions",{referenceId:t,referenceType:e,reactionName:n,referenceVersion:"message"===e?5:void 0});if(o.cache){const c=Re([e,"get",t]);if(!c||(null===(r=c.data.myReactions)||void 0===r?void 0:r.includes(n)))return!0;const l=Object.assign(Object.assign({},c.data),{reactionsCount:c.data.reactionsCount+1,myReactions:[...null!==(a=c.data.myReactions)&&void 0!==a?a:[],n],reactions:Object.assign(Object.assign({},c.data.reactions),{[n]:(null!==(s=c.data.reactions[n])&&void 0!==s?s:0)+1})});if("comment"===e)return it("local.comment.addReaction",{comment:l,reactor:{userId:o.userId,reactionName:n,reactionId:i.addedId}}),!0;if("post"===e)return it("local.post.addReaction",{post:l,reactor:{userId:o.userId,reactionName:n,reactionId:i.addedId}}),!0;if("story"===e)return it("local.story.reactionAdded",{story:l,reactor:{userId:o.userId,reactionName:n,reactionId:i.addedId}}),!0}return!0};Ci.optimistically=(e,t,n)=>{var r,a,s,o,i;const c=Te();if(c.log("reaction/createReaction.optimistically",{referenceId:t,referenceType:e,reactionName:n}),!c.cache)return;const l=Re([e,"get",t]);if(!(null==l?void 0:l.data)||(null===(r=l.data.myReactions)||void 0===r?void 0:r.includes(n)))return;const d=Object.assign(Object.assign({},l.data),{reactionsCount:l.data.reactionsCount+1,myReactions:[...null!==(a=l.data.myReactions)&&void 0!==a?a:[],n],reactions:Object.assign(Object.assign({},l.data.reactions),{[n]:(null!==(s=l.data.reactions[n])&&void 0!==s?s:0)+1})});return Pe([e,"get",t],d,{cachedAt:H}),hi(e,d),null!==(i=null===(o=null==d?void 0:d.myReactions)||void 0===o?void 0:o.includes(n))&&void 0!==i&&i};const Ii=async(e,t,n)=>{var r,a;const s=Te();if(s.log("reaction/removeReaction",{referenceId:t,referenceType:e,reactionName:n}),!["post","comment","story","message"].includes(e))throw new Ie("The reference type is not valid. It should be one of post, comment, story, or message",4e5,"error");const{data:o}=await s.http.delete("/api/v2/reactions",{data:{referenceId:t,referenceType:e,reactionName:n,referenceVersion:"message"===e?5:void 0}});if(s.cache){const i=Re([e,"get",t]);if(!i)return!0;const c=Object.assign(Object.assign({},i.data),{reactionsCount:Math.max(0,i.data.reactionsCount-1),myReactions:(null!==(r=i.data.myReactions)&&void 0!==r?r:[]).filter((e=>e!==n)),reactions:Object.assign(Object.assign({},i.data.reactions),{[n]:Math.max(0,(null!==(a=i.data.reactions[n])&&void 0!==a?a:0)-1)})});if("comment"===e)return it("local.comment.removeReaction",{comment:c,reactor:{reactionId:o.removedId,reactionName:n,userId:s.userId}}),!0;if("post"===e)return it("local.post.removeReaction",{post:c,reactor:{reactionId:o.removedId,reactionName:n,userId:s.userId}}),!0;if("story"===e)return it("local.story.reactionAdded",{story:c,reactor:{userId:s.userId,reactionName:n,reactionId:o.removedId}}),!0}return!0};Ii.optimistically=(e,t,n)=>{var r,a,s,o;const i=Te();if(i.log("reaction/removeReaction.optimistically",{referenceId:t,referenceType:e,reactionName:n}),!i.cache)return;const c=Re([e,"get",t]);if(!(null==c?void 0:c.data)||!(null===(r=c.data.myReactions)||void 0===r?void 0:r.includes(n)))return;const l=Object.assign(Object.assign({},c.data),{reactionsCount:Math.max(0,c.data.reactionsCount-1),myReactions:(null!==(a=c.data.myReactions)&&void 0!==a?a:[]).filter((e=>e!==n)),reactions:Object.assign(Object.assign({},c.data.reactions),{[n]:Math.max(0,(null!==(s=c.data.reactions[n])&&void 0!==s?s:0)-1)})});return Pe([e,"get",t],l,{cachedAt:H}),hi(e,l),!(null===(o=null==l?void 0:l.myReactions)||void 0===o?void 0:o.includes(n))};const Si=e=>{const{posts:t}=e,n=Xt(e,["posts"]),r=Sr({communities:n.communities}),a=n.communityUsers.map((e=>{const t=n.users.find((t=>t.userId===e.userId));return Object.assign(Object.assign({},e),{user:t})})),s=Cr(r,a),o=t.map((e=>{var t;const r=null===(t=n.feeds.find((t=>t.feedId===e.feedId)))||void 0===t?void 0:t.feedType;return Object.assign(Object.assign({},e),{feedType:r})}));return Object.assign(Object.assign({},n),{posts:o,communities:s,communityUsers:a})},_i=e=>{var{searchResult:t,polls:n}=e,r=Xt(e,["searchResult","polls"]);const a=Si(r);return Object.assign(Object.assign({},a),{polls:n})},ki=(e,t)=>{const n=Te();return ot(n,e,e,(r=>{var a;if(n.cache){const s=Si(r),{communities:o}=s;if(Yt(s,void 0,!1),(null==o?void 0:o[0])&&!["post.updated"].includes(e)&&it("community.updated",{communities:o,categories:[],communityUsers:s.communityUsers,feeds:[],files:[],users:[]}),"post.deleted"===e){const{postId:e,postedUserId:a}=r.posts[0];try{fn("post",e)}catch(e){return}return a!==n.userId&&Ue(["post","get",e]),t(r.posts[0])}const i=Re(["post","get",r.posts[0].postId]);if(["post.created","post.approved","post.declined"].includes(e)){let t=null===(a=Ae(["post","query"]))||void 0===a?void 0:a.filter((({key:e})=>{var t;return(null===(t=e[2])||void 0===t?void 0:t.targetId)===i.data.targetId}));"post.declined"===e&&(t=null==t?void 0:t.filter((({key:e})=>{var t;return"reviewing"===(null===(t=e[2])||void 0===t?void 0:t.feedType)}))),null==t||t.map((({key:e,data:t})=>Pe(e,t,{cachedAt:-1})))}t(i.data)}else t(r.posts[0])}))},Oi=(e,t)=>{const n=Te();return ot(n,e,e,(r=>{if(n.cache){const n=Si(r),{communities:a}=n;Yt(n),(null==a?void 0:a[0])&&!["local.post.updated"].includes(e)&&it("community.updated",{communities:a,categories:[],communityUsers:n.communityUsers,feeds:[],files:[],users:[]});const s=Re(["post","get",r.posts[0].postId]);t(s.data)}else t(r.posts[0])}))},Ti=e=>ki("post.created",e),Ei=e=>ki("post.updated",e),Ai=e=>ki("post.deleted",e),Ri=e=>ki("post.approved",e),Mi=e=>ki("post.declined",e),ji=e=>ki("post.flagged",e),Pi=e=>ki("post.unflagged",e),Ui=e=>{const t=Te();return ot(t,"post.addReaction","post.addReaction",(n=>{if(t.cache){const t=Xt(bi("post.addReaction",n),["reactor"]);Yt(t);const r=Re(["post","get",n.posts[0].postId]);e(r.data)}else e(n.posts[0])}))},xi=e=>{const t=Te();return ot(t,"post.removeReaction","post.removeReaction",(n=>{if(t.cache){const t=Xt(bi("post.removeReaction",n),["reactor"]);Yt(t);const r=Re(["post","get",n.posts[0].postId]);e(r.data)}else e(n.posts[0])}))},Di=(e,t)=>{const n=Te();return ot(n,e,e,(r=>{var a;if(n.cache){const s=["comment.flagged","comment.unflagged"].includes(e)?(e=>{const t=gi(e,"comment");return yi(e,"comments",t)})(r):r;Yt(s,void 0,!1);const{comments:o}=s;if(o.length>0){const r=Re(["comment","get",o[0].commentId]);if(["comment.created"].includes(e)){if("comment.created"===e&&r.data.userId===n.userId)return;if(o[0].parentId){const e=Re(["comment","get",o[0].parentId]);(null==e?void 0:e.data)&&(e.data.children.includes(o[0].commentId)||Me(["comment","get",o[0].parentId],Object.assign(Object.assign({},e.data),{childrenNumber:e.data.childrenNumber+1,children:[...new Set([...e.data.children,o[0].commentId])]})))}}if(["comment.deleted"].includes(e)){if("comment.deleted"===e&&r.data.userId===n.userId)return;if(o[0].parentId){const e=Re(["comment","get",o[0].parentId]);if((null==e?void 0:e.data)&&e.data.children.includes(o[0].commentId)){const t=Object.assign(Object.assign({},e.data),{childrenNumber:e.data.childrenNumber-1,children:[...new Set([...e.data.children.filter((e=>e!==o[0].commentId))])]});Me(["comment","get",o[0].parentId],t)}}const t=null===(a=Ae(["comment","query"]))||void 0===a?void 0:a.filter((({key:e})=>{var t;return(null===(t=e[2])||void 0===t?void 0:t.referenceId)===r.data.referenceId}));null==t||t.map((({key:e,data:t})=>Pe(e,t,{cachedAt:-1})))}t(na.comment(r.data))}}else t(na.comment(r.comments[0]))}))},qi=(e,t)=>{const n=Te();return ot(n,e,e,(r=>{var a,s;if(n.cache){const n=r;Yt(n);const{comments:o}=n;if(o.length>0){const n=Re(["comment","get",o[0].commentId]);if(["local.comment.created"].includes(e)){if(o[0].parentId){const e=Re(["comment","get",o[0].parentId]);if((null==e?void 0:e.data)&&!e.data.children.includes(o[0].commentId)){const t=Object.assign(Object.assign({},e.data),{childrenNumber:e.data.childrenNumber+1,children:[...new Set([...e.data.children,o[0].commentId])]});Me(["comment","get",o[0].parentId],t),setTimeout((()=>{it("comment.updated",{comments:[t],commentChildren:[],files:[],users:[],communityUsers:[]})}),200)}}const e=null===(a=Ae(["comment","query"]))||void 0===a?void 0:a.filter((({key:e})=>{var t;return(null===(t=e[2])||void 0===t?void 0:t.referenceId)===n.data.referenceId}));null==e||e.map((({key:e,data:t})=>Pe(e,t,{cachedAt:-1})))}if(["local.comment.deleted"].includes(e)){if(o[0].parentId){const e=Re(["comment","get",o[0].parentId]);if((null==e?void 0:e.data)&&e.data.children.includes(o[0].commentId)){const t=Object.assign(Object.assign({},e.data),{childrenNumber:e.data.childrenNumber-1,children:[...new Set([...e.data.children.filter((e=>e!==o[0].commentId))])]});Me(["comment","get",o[0].parentId],t),setTimeout((()=>{it("comment.updated",{comments:[t],commentChildren:[],files:[],users:[],communityUsers:[]})}),200)}}const e=null===(s=Ae(["comment","query"]))||void 0===s?void 0:s.filter((({key:e})=>{var t;return(null===(t=e[2])||void 0===t?void 0:t.referenceId)===n.data.referenceId}));null==e||e.map((({key:e,data:t})=>Pe(e,t,{cachedAt:-1})))}t(na.comment(n.data))}}else t(na.comment(r.comments[0]))}))},Ni=e=>Di("comment.created",e),Bi=e=>Di("comment.updated",e),Li=e=>Di("comment.deleted",e),Fi=e=>Di("comment.flagged",e),Ki=e=>Di("comment.unflagged",e),$i=e=>{const t=Te();return ot(t,"comment.addReaction","comment.addReaction",(n=>{if(t.cache){const t=Xt(bi("comment.addReaction",n),["reactor"]);Yt(t);const r=Re(["comment","get",n.comments[0].commentId]);e(na.comment(r.data))}else e(na.comment(n.comments[0]))}))},Qi=e=>{const t=Te();return ot(t,"comment.removeReaction","comment.removeReaction",(n=>{if(t.cache){const t=Xt(bi("comment.removeReaction",n),["reactor"]);Yt(t);const r=Re(["comment","get",n.comments[0].commentId]);e(na.comment(r.data))}else e(na.comment(n.comments[0]))}))},zi=(e,t,n)=>{const r=Te(),a=(r,a,s)=>{r===e&&a===t&&n(s)};if("message"===e){return ot(r,"reaction/onReactorAdded","message.reactionAdded",(async e=>{const t=await kn(e);t.reactions[0]&&(Yt(t),Yt({reactors:t.reactions}),a("message",t.messages[0].messageId,t.reactions[0]))}))}if("post"===e){return ot(r,"post.addReaction","post.addReaction",(e=>{const{reactor:t}=e,n=Xt(e,["reactor"]);Yt(n),Yt({reactions:[t]}),a("post",e.posts[0].postId,t)}))}if("story"===e){return ot(r,"story.reactionAdded","story.reactionAdded",(e=>{const{reactions:t}=e,n=Xt(e,["reactions"]);Yt(n),Yt({reactors:t}),0!==e.stories.length&&0!==e.reactions.length&&a("story",e.stories[0].storyId,e.reactions[0])}))}return ot(r,"comment.addReaction","comment.addReaction",(e=>{const{reactor:t}=e,n=Xt(e,["reactor"]);Yt(n),Yt({reactions:[t]}),a("comment",e.comments[0].commentId,t)}))},Vi=(e,t,n)=>{const r=Te(),a=(r,a,s)=>{r===e&&a===t&&n(s)};if("message"===e){return ot(r,"reaction/onReactorRemoved","message.reactionRemoved",(async e=>{const t=await kn(e);t.reactions[0]&&(Yt(t),a("message",t.messages[0].messageId,t.reactions[0]))}))}if("post"===e){return ot(r,"post.removeReaction","post.removeReaction",(e=>{const{reactor:t}=e,n=Xt(e,["reactor"]);Yt(n),Yt({reactions:[t]}),a("post",e.posts[0].postId,t)}))}if("story"===e){return ot(r,"story.reactionRemoved","story.reactionRemoved",(e=>{const{reactions:t}=e,n=Xt(e,["reactions"]);Yt(n),Yt({reactors:t}),0!==e.stories.length&&0!==e.reactions.length&&a("story",e.stories[0].storyId,e.reactions[0])}))}return ot(r,"comment.removeReaction","comment.removeReaction",(e=>{const{reactor:t}=e,n=Xt(e,["reactor"]);Yt(n),Yt({reactions:[t]}),a("comment",e.comments[0].commentId,t)}))};class Hi extends Rr{async getRequest(e,t){const{limit:n=$}=e,r=Xt(e,["limit"]),a=t?{token:t}:{limit:n};Te().log("reaction/queryReactions",e);if(!["post","comment","story","message"].includes(r.referenceType))throw new Ie("The reference type is not valid. It should be one of post, comment, story, or message",4e5,"error");const{data:s}=await this.http.get("/api/v3/reactions",{params:Object.assign(Object.assign({},r),{referenceVersion:5,options:a})});return s}}class Ji extends jr{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){var t;const n=await this.preparePayload(e),r=Te(),a=r.cache&&Date.now();if(r.cache){const{reactions:e}=n,r=Xt(n,["reactions"]);Yt(Object.assign(Object.assign({},r),{reactions:e,reactors:null===(t=e[0])||void 0===t?void 0:t.reactors}),{cachedAt:a})}}appendToQueryStream(e,t,n=!1){var r,a,s,o;const i=null!==(a=null===(r=e.reactions[0])||void 0===r?void 0:r.reactors)&&void 0!==a?a:[];if(n)Me(this.cacheKey,{data:i.map(ve("reactor"))});else{const e=null===(s=Re(this.cacheKey))||void 0===s?void 0:s.data,t=null!==(o=null==e?void 0:e.data)&&void 0!==o?o:[];Me(this.cacheKey,Object.assign(Object.assign({},e),{data:[...new Set([...t,...i.map(ve("reactor"))])]}))}}reactor(e){return t=>{var n;const r=null===(n=Re(this.cacheKey))||void 0===n?void 0:n.data;r&&("onAdded"===e?r.data=[...new Set([t.reactionId,...r.data])]:"onRemoved"===e&&(r.data=r.data.filter((e=>e!==t.reactionId))),Me(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class Wi extends Br{constructor(e,t){const n=I.default(e),r=["reaction","collection",n];super(new Hi(e),n,r,t),this.query=e,this.queryStreamController=new Ji(this.query,this.cacheKey,this.notifyChange.bind(this),(e=>e)),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Re(this.cacheKey))||void 0===e?void 0:e.data)||Me(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:e=>zi(this.query.referenceType,this.query.referenceId,e),action:"onAdded"},{fn:e=>Vi(this.query.referenceType,this.query.referenceId,e),action:"onRemoved"},{fn:e=>((e,t,n)=>{const r=Te(),a=(r,a,s)=>{r===e&&a===t&&n(s)};if("message"===e)return ot(r,"reaction/onReactorRemoved","message.reactionRemoved",(async e=>{const t=await kn(e);t.reactions[0]&&(Yt(t),a("message",t.messages[0].messageId,t.reactions[0]))}));if("post"===e)return ot(r,"local.post.removeReaction","local.post.removeReaction",(e=>{a("post",e.post.postId,e.reactor)}));if("story"===e)return ot(r,"story.reactionRemoved","story.reactionRemoved",(e=>{const{reactions:t}=e,n=Xt(e,["reactions"]);Yt(n),Yt({reactors:t}),0!==e.stories.length&&0!==e.reactions.length&&a("story",e.stories[0].storyId,e.reactions[0])}));return ot(r,"local.comment.removeReaction","local.comment.removeReaction",(e=>{a("comment",e.comment.commentId,e.reactor)}))})(this.query.referenceType,this.query.referenceId,e),action:"onRemoved"},{fn:e=>((e,t,n)=>{const r=Te(),a=(r,a,s)=>{r===e&&a===t&&n(s)};if("message"===e)return ot(r,"reaction/onReactorAdded","message.reactionAdded",(async e=>{const t=await kn(e);t.reactions[0]&&(Yt(t),Yt({reactors:t.reactions}),a("message",t.messages[0].messageId,t.reactions[0]))}));if("post"===e)return ot(r,"local.post.addReaction","local.post.addReaction",(e=>{a("post",e.post.postId,e.reactor)}));if("story"===e)return ot(r,"story.reactionAdded","story.reactionAdded",(e=>{const{reactions:t}=e,n=Xt(e,["reactions"]);Yt(n),Yt({reactors:t}),0!==e.stories.length&&0!==e.reactions.length&&a("story",e.stories[0].storyId,e.reactions[0])}));return ot(r,"local.comment.addReaction","local.comment.addReaction",(e=>{a("comment",e.comment.commentId,e.reactor)}))})(this.query.referenceType,this.query.referenceId,e),action:"onRemoved"}])}notifyChange({origin:e,loading:t,error:n}){var r,a;const s=null===(r=Re(this.cacheKey))||void 0===r?void 0:r.data;if(!s)return;const o=null!==(a=s.data.map((e=>Re(["reactor","get",e]))).filter(Boolean).map((({data:e})=>na.reactor(e))))&&void 0!==a?a:[];(this.shouldNotify(o)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:o,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}}var Gi=Object.freeze({__proto__:null,addReaction:Ci,removeReaction:Ii,onReactionAdded:(e,t,n)=>{const r=r=>{ve(e)(r)===t&&n(r)};if("message"===e){const e=Te(),t=async e=>{var t;const n=await kn(e),a=Re(["message","get",n.messages[0].messageId]),s=(null===(t=null==a?void 0:a.data)||void 0===t?void 0:t.reactionsCount)!==n.messages[0].reactionsCount;Yt(n),s&&r(n.messages[0])};return ot(e,"reaction/onReactionAdded","message.updated",t)}return"post"===e?Ui(r):$i(r)},onReactionRemoved:(e,t,n)=>{const r=r=>{ve(e)(r)===t&&n(r)};if("message"===e){const e=Te(),t=async e=>{var t;const n=await kn(e),a=Re(["message","get",n.messages[0].messageId]),s=(null===(t=null==a?void 0:a.data)||void 0===t?void 0:t.reactionsCount)!==n.messages[0].reactionsCount;Yt(n),s&&r(n.messages[0])};return ot(e,"reaction/onReactionRemoved","message.updated",t)}return"post"===e?xi(r):Qi(r)},onReactorAdded:zi,onReactorRemoved:Vi,getReactions:(e,t,n)=>{const{log:r,cache:a}=Te(),s=Date.now();r(`getReactions(tmpid: ${s}) > listen`);const o=new Wi(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>{Ue(c)})),()=>{r(`getReactions(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}}});function Yi(e){const{comments:t}=e;return Object.assign(Object.assign({},e),{comments:t.map((e=>e.hasOwnProperty("myReactions")?e:Object.assign({myReactions:[]},e)))})}const Zi=async e=>{const t=Te();let n;t.log("channel/getChannel",e),fn("channel",e);try{const{data:r}=await t.http.get(`/api/v3/channels/${encodeURIComponent(e)}`);n=await Qn(r),t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&Vn(r)}catch(t){throw te(null==t?void 0:t.code)&&Zt("channel",e),t}const r=t.cache&&Date.now();t.cache&&Yt(n,{cachedAt:r});const{channels:a}=n;return{data:a.find((t=>t.channelId===e)),cachedAt:r}};Zi.locally=e=>{var t;const n=Te();if(n.log("channel/getChannel.locally",e),!n.cache)return;const r=null===(t=Ae(["channel","get"]))||void 0===t?void 0:t.filter((({data:t})=>t.channelPublicId===e));return r&&0!==(null==r?void 0:r.length)?{data:r[0].data,cachedAt:r[0].cachedAt}:void 0};const Xi=e=>{const t=Te(),n=[ot(t,"onMessageUpdated","message.updated",(async t=>{const n=await kn(t);Yt(n),e(n.messages[0])})),ot(t,"onMessageUpdated","local.message.updated",(t=>e(t.messages[0])))];return()=>{n.forEach((e=>e()))}},ec=e=>{const t=Te(),n=[ot(t,"message/onMessageDeleted","message.deleted",(async t=>{const n=await kn(t);Yt(n),e(n.messages[0])})),ot(t,"message/onMessageDeleted","local.message.deleted",(t=>e(t.messages[0])))];return()=>{n.forEach((e=>e()))}},tc=e=>{const t=Te(),n=[ot(t,"onSubChannelUpdated","message-feed.updated",(async t=>{const n=await Mn(t);Yt(n),e(n.messageFeeds[0])})),ot(t,"onSubChannelUpdated","local.message-feed.updated",(t=>e(t.messageFeeds[0])))];return()=>{n.forEach((e=>e()))}};function nc(e,t){Me(["channel","get",e.channelId],hn(e,t))}const rc=e=>{const t=Te();return ot(t,"channelMarker/onChannelMarkerUpdated","local.channelMarker.updated",(t=>{e(t.userEntityMarkers[0])}))},ac=async(e,t=!1)=>{const n=Te(),r=await jn(e);await n.http.delete(`/api/v5/message-feeds/${encodeURIComponent(e)}`,{params:{permanent:t}});const a=Object.assign(Object.assign({},r.data),{isDeleted:!0,updatedAt:we(r.data.updatedAt)});return t?setTimeout((()=>{Zt("subChannel",e)}),0):Pe(["subChannel","get",e],a),it("local.message-feed.deleted",{messageFeeds:[a]}),a},sc=e=>ot(Te(),"onSubChannelFetched","local.message-feed.fetched",(t=>e(t.messageFeeds[0]))),oc=()=>`LOCAL_${Qt()}`;let ic;const cc=async(e,t)=>{const n=Te();n.log("message/updateMessage",t),console.warn("MessageRepository.updateMessage will be replaced with MessageRepository.editMessage");const{data:r}=await n.http.put(`/api/v5/messages/${encodeURIComponent(e)}`,On(t)),a=await kn(r),s=n.cache&&Date.now();n.cache&&Yt(a,{cachedAt:s});const{messages:o}=a;return it("local.message.updated",{messages:o}),{data:na.message(o.find((t=>t.messageId===e))),cachedAt:s}};cc.optimistically=(e,t)=>{const n=Te();if(n.log("message/updateMessage.optimistically",t),!n.cache)return;const r=Re(["message","get",e]);if(!r)return;const a=Object.assign(Object.assign(Object.assign({},r.data),t),{updatedAt:(new Date).toISOString()});return Pe(["message","get",e],a,{cachedAt:-1}),it("local.message.updated",{messages:[a]}),{data:na.message(a),cachedAt:-1}};const lc=async(e,t)=>{const n=Te();n.log("message/editMessage",t);const{data:r}=await n.http.put(`/api/v5/messages/${encodeURIComponent(e)}`,On(t)),a=await kn(r),s=n.cache&&Date.now();n.cache&&Yt(a,{cachedAt:s});const{messages:o}=a;return it("local.message.updated",{messages:o}),{data:na.message(o.find((t=>t.messageId===e))),cachedAt:s}};lc.optimistically=(e,t)=>{const n=Te();if(n.log("message/editMessage.optimistically",t),!n.cache)return;const r=Re(["message","get",e]);if(!r)return;const a=Object.assign(Object.assign(Object.assign({},r.data),t),{updatedAt:(new Date).toISOString()});return Pe(["message","get",e],a,{cachedAt:-1}),it("local.message.updated",{messages:[a]}),{data:na.message(a),cachedAt:-1}};const dc=async e=>{const t=Te();t.log("message/deleteMessage",e);const{data:n}=await t.http.delete(`/api/v5/messages/${encodeURIComponent(e)}`),r=await kn(n);return it("local.message.deleted",{messages:[r.messages[0]]}),na.message(r.messages[0])};dc.optimistically=e=>{Te().log("message/deleteMessage.optimistically",e);const t=Re(["message","get",e]);if(!t)return;const n=Object.assign(Object.assign({},t.data),{isDeleted:!0,updatedAt:(new Date).toISOString()});return Pe(["message","get",e],n,{cachedAt:-1}),it("local.message.deleted",{messages:[n]}),{data:na.message(n),cachedAt:-1}};const uc=async e=>{const t=Te();t.log("message/softDeleteMessage",e),await t.http.delete(`/api/v5/messages/${encodeURIComponent(e)}`);const n=await pi(e);return it("local.message.deleted",{messages:[n.data]}),na.message(n.data)};uc.optimistically=e=>{Te().log("message/softDeleteMessage.optimistically",e);const t=Re(["message","get",e]);if(!t)return;const n=Object.assign(Object.assign({},t.data),{isDeleted:!0,updatedAt:(new Date).toISOString()});return Pe(["message","get",e],n,{cachedAt:-1}),it("local.message.deleted",{messages:[n]}),{data:na.message(n),cachedAt:-1}};const hc=async e=>{const t=Te();t.log("user/getReadUsers",e);const{page:n,messageId:r}=e,a=Xt(e,["page","messageId"]),{data:s}=await t.http.get(`/api/v1/markers/messages/${r}/read-users`,{params:Object.assign(Object.assign({},a),{options:{token:oe(n,"afterbeforeraw")}})}),{paging:o,publicUserIds:i,userFeedMarkers:c}=s,l=Xt(s,["paging","publicUserIds","userFeedMarkers"]),d=t.cache&&Date.now();if(t.cache){Yt(Object.assign(Object.assign({},l),{userFeedMarkers:an(c)}),{cachedAt:d});const e=["read-user","query",Object.assign(Object.assign({messageId:r},a),{options:Object.assign({},n)})];Me(e,{users:i,paging:o})}let u=[];i.length>0&&({data:u}=await No(i));return{data:u,cachedAt:d,prevPage:ie(o.previous),nextPage:ie(o.next)}};hc.locally=e=>{var t;const n=Te();if(n.log("user/getReadUsers.locally",e),!n.cache)return;const{page:r}=e,a=Xt(e,["page"]),s=["read-user","query",Object.assign(Object.assign({},a),{options:Object.assign({},r)})],{data:o,cachedAt:i}=null!==(t=Re(s))&&void 0!==t?t:{},c=null==o?void 0:o.users.map((e=>{var t;return null===(t=Re(["user","get",e]))||void 0===t?void 0:t.data}));if(!c||c.some((e=>!e)))return;return{data:c,cachedAt:i,prevPage:ie(null==o?void 0:o.paging.previous),nextPage:ie(null==o?void 0:o.paging.next)}};const pc=async e=>{const t=Te();t.log("user/getDeliveredUsers",e);const{page:n,messageId:r}=e,a=Xt(e,["page","messageId"]),{data:s}=await t.http.get(`/api/v1/markers/messages/${r}/delivered-users`,{params:Object.assign(Object.assign({},a),{options:{token:oe(n,"afterbeforeraw")}})}),{paging:o,publicUserIds:i,userFeedMarkers:c}=s,l=Xt(s,["paging","publicUserIds","userFeedMarkers"]),d=t.cache&&Date.now();if(t.cache){Yt(Object.assign(Object.assign({},l),{userFeedMarkers:an(c)}),{cachedAt:d});const e=["delivered-user","query",Object.assign(Object.assign({messageId:r},a),{options:Object.assign({},n)})];Me(e,{users:i,paging:o})}let u=[];i.length>0&&({data:u}=await No(i));return{data:u,cachedAt:d,prevPage:ie(o.previous),nextPage:ie(o.next)}};pc.locally=e=>{var t;const n=Te();if(n.log("user/getDeliveredUsers.locally",e),!n.cache)return;const{page:r}=e,a=Xt(e,["page"]),s=["delivered-user","query",Object.assign(Object.assign({},a),{options:Object.assign({},r)})],{data:o,cachedAt:i}=null!==(t=Re(s))&&void 0!==t?t:{},c=null==o?void 0:o.users.map((e=>{var t;return null===(t=Re(["user","get",e]))||void 0===t?void 0:t.data}));if(!c||c.some((e=>!e)))return;return{data:c,cachedAt:i,prevPage:ie(null==o?void 0:o.paging.previous),nextPage:ie(null==o?void 0:o.paging.next)}};const fc=e=>{const t=Te();return ot(t,"onMessageFlagged","message.flagged",(async t=>{const n=await kn(t);Yt(n),e(n.messages[0])}))},mc=e=>{const t=Te();return ot(t,"onMessageUnflagged","message.unflagged",(async t=>{const n=await kn(t);Yt(n),e(n.messages[0])}))},gc=e=>{const t=Te();return ot(t,"onMessageFlagCleared","message.flagCleared",(async t=>{const n=await kn(t);Yt(n),e(n.messages[0])}))},yc=e=>{const t=Te();return ot(t,"onMessageReactionAdded","message.reactionAdded",(async t=>{const n=await kn(t,"message.reactionAdded");Yt(n),e(n.messages[0])}))},vc=e=>{const t=Te();return ot(t,"onMessageReactionRemoved","message.reactionRemoved",(async t=>{const n=await kn(t,"message.reactionRemoved");Yt(n),e(n.messages[0])}))},bc=e=>{const t=Te();return ot(t,"message/onMessageFetched","local.message.fetched",(t=>{Yt(t),e(t.messages[0])}))};class wc extends jr{constructor(e,t,n,r,a){super(e,t),this.notifyChange=n,this.preparePayload=r,this.paginationController=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Te(),r=n.cache&&Date.now();n.cache&&Yt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,a;if(n)Me(this.cacheKey,{data:e.messages.map(ve("message")),query:this.query});else{const n=null===(r=Re(this.cacheKey))||void 0===r?void 0:r.data,s=null!==(a=null==n?void 0:n.data)&&void 0!==a?a:[];Me(this.cacheKey,Object.assign(Object.assign({},n),{data:"next"===t?[...new Set([...s,...e.messages.map(ve("message"))])]:[...new Set([...e.messages.map(ve("message")),...s])]}))}}reactor(e){return t=>{var n,r,a;if("onCreate"===e){const e=null===(n=Re(this.cacheKey))||void 0===n?void 0:n.data,{referenceId:s}=t;if(!e)return;if(this.query.subChannelId!==(null==t?void 0:t.subChannelId)||!e)return;if(this.query.type&&this.query.type!==t.dataType)return;if(this.query.excludingTags&&(null===(r=this.query.excludingTags)||void 0===r?void 0:r.some((e=>{var n;return null===(n=t.tags)||void 0===n?void 0:n.includes(e)}))))return;if(!!this.query.hasFlags!=!!t.flagCount)return;if(this.query.parentId&&this.query.parentId!==t.parentId)return;if(this.query.hasOwnProperty("includeDeleted")&&!this.query.includeDeleted&&t.isDeleted)return;if(this.query.includingTags&&!(null===(a=this.query.includingTags)||void 0===a?void 0:a.some((e=>{var n;return null===(n=t.tags)||void 0===n?void 0:n.includes(e)}))))return;this.query.sortBy&&"segmentDesc"!==this.query.sortBy||this.paginationController.getPrevToken()||(e.data=[...new Set([null!=s?s:t.messageId,...e.data])]),"segmentAsc"!==this.query.sortBy||this.paginationController.getNextToken()||(e.data=[...new Set([...e.data,null!=s?s:t.messageId])]),Me(this.cacheKey,e)}this.notifyChange({origin:"event",loading:!1})}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class Cc extends Rr{async getRequest(e,t){const n=Tn(e),{data:r}=await this.http.get("/api/v5/messages",{params:Object.assign(Object.assign({},n),{options:t?{token:t}:Object.assign({},n.options)})});return r}}class Ic extends Br{constructor(e,t){const n=I.default(e),r=["message","collection",n];super(new Cc(e),n,r,t),this.query=e,this.queryStreamController=new wc(this.query,this.cacheKey,this.notifyChange.bind(this),kn,this.paginationController),this.callback=t.bind(this),this.loadPage({initial:!0})}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:xs,action:"onCreate"},{fn:Ds,action:"onCreate"},{fn:ec,action:"onDelete"},{fn:Xi,action:"onUpdate"},{fn:fc,action:"onFlagged"},{fn:mc,action:"onUnflagged"},{fn:gc,action:"onFlagCleared"},{fn:yc,action:"onReactionAdded"},{fn:vc,action:"onReactionRemoved"},{fn:Zo(ao,"contentId","message"),action:"onUpdate"},{fn:Zo(so,"contentId","message"),action:"onUpdate"}])}notifyChange({origin:e,loading:t,error:n}){var r,a;const s=null===(r=Re(this.cacheKey))||void 0===r?void 0:r.data;if(!s)return;const o=this.applyFilter(null!==(a=s.data.map((e=>(e=>{var t,n;const r=null===(t=Re(["message","get",e]))||void 0===t?void 0:t.data;if(r)return r;const a=Ae(["message","get"]);return null===(n=null==a?void 0:a.find((({data:t})=>t.messageId===e)))||void 0===n?void 0:n.data})(e))).filter(Boolean).map((e=>na.message(e))))&&void 0!==a?a:[]);(this.shouldNotify(o)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),onPrevPage:()=>this.loadPage({direction:"prev"}),data:o,hasNextPage:!!this.paginationController.getNextToken(),hasPrevPage:!!this.paginationController.getPrevToken(),loading:t,error:n})}applyFilter(e){let t=e;return this.query.includeDeleted||(t=xe(t,"isDeleted",!1)),t=t.sort(((e,t)=>"segmentAsc"===this.query.sortBy?e.channelSegment-t.channelSegment:"segmentDesc"===this.query.sortBy?t.channelSegment-e.channelSegment:0)),t}setup(){var e;(null===(e=Re(this.cacheKey))||void 0===e?void 0:e.data)||Me(this.cacheKey,{data:[],query:this.query})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}}var Sc=Object.freeze({__proto__:null,createMessage:async e=>{const t=Te();t.log("message/createMessage",e);const n=(e=>{var t,n;const r=Te();if(!r.cache)return;ic=e.referenceId||oc();const a=Object.assign({messageId:ic,uniqueId:ic},e);r.log("message/createMessage.optimistically",a);const s=Re(["subChannel","get",e.subChannelId]);if(s&&(Pe(["subChannel","get",e.subChannelId],Object.assign(Object.assign({},s.data),{messageCount:s.data.messageCount+1})),s.data.channelId===s.data.subChannelId)){const e=Re(["channel","get",s.data.channelId]);(null==e?void 0:e.data)&&Pe(["channel","get",s.data.channelId],Object.assign(Object.assign({},e.data),{messageCount:(null!==(t=e.data.messageCount)&&void 0!==t?t:0)+1}))}const o=(new Date).toISOString(),i=Object.assign({creatorId:r.userId,creatorPrivateId:Ze()._id,channelSegment:(null!==(n=null==s?void 0:s.data.messageCount)&&void 0!==n?n:0)+1,childrenNumber:0,createdAt:o,updatedAt:o,syncState:"syncing",isDeleted:!1},a);return Me(["message","get",i.messageId],i,{cachedAt:-5}),it("local.message.created",{messages:[i]}),i})(e),r=e.referenceId||ic||oc();ic=void 0;try{const{data:n}=await t.http.post("/api/v5/messages",Object.assign(Object.assign({},On(e)),{referenceId:r})),a=await kn(n),{messages:s}=a,o=t.cache&&Date.now();return t.cache&&Yt(a,{cachedAt:o}),it("local.message.created",{messages:[Object.assign(Object.assign({},s[0]),{syncState:"synced"})]}),{data:na.message(s[0]),cachedAt:o}}catch(e){throw it("local.message.created",{messages:[Object.assign(Object.assign({},n),{syncState:"error"})]}),e}},updateMessage:cc,editMessage:lc,deleteMessage:dc,softDeleteMessage:uc,markAsDelivered:async(e,t)=>{const n=Te();n.log("message/markAsDelivered",e,t);const{data:r}=await n.http.put(`/api/v1/markers/message-feeds/${e}/mark-delivering`,{messageId:t}),{userMarkers:a,userEntityMarkers:s,userFeedMarkers:o}=r,i=Xt(r,["userMarkers","userEntityMarkers","userFeedMarkers"]),c=n.cache&&Date.now();return n.cache&&Yt(Object.assign({userMarkers:a,userEntityMarkers:rn(s),userFeedMarkers:an(o)},i),{cachedAt:c}),!0},getReadUsers:hc,getDeliveredUsers:pc,flagMessage:async(t,n)=>{const r=Te();r.log("message/flag",t);const a=n&&Object.entries(e.ContentFlagReasonEnum).some((([t,r])=>t!==e.ContentFlagReasonEnum.Others&&r===n)),s={reason:a?n:e.ContentFlagReasonEnum.Others,detail:a?"":n},{data:o}=await r.http.post(`/api/v5/messages/${encodeURIComponent(t)}/flags`,s);if(r.cache){const e=await kn(o);Yt(e)}return it("message.flagged",o),!!o},unflagMessage:async e=>{const t=Te();t.log("message/unflag",e);const{data:n}=await t.http.delete(`/api/v5/messages/${encodeURIComponent(e)}/flags`);if(t.cache){const e=await kn(n);Yt(e)}return it("message.unflagged",n),!!n},isMessageFlaggedByMe:async e=>{const t=Te();t.log("message/isMessageFlaggedByMe",e);const{data:n}=await t.http.get(`/api/v5/messages/${encodeURIComponent(e)}/flags`);return n.result},onMessageCreatedMqtt:xs,onMessageCreatedLocal:Ds,onMessageUpdated:Xi,onMessageDeleted:ec,onMessageFlagged:fc,onMessageUnflagged:mc,onMessageFlagCleared:gc,onMessageReactionAdded:yc,onMessageReactionRemoved:vc,onMessageFetched:bc,getMessage:(e,t)=>Do(e,(e=>{const{data:n}=e;t(Object.assign(Object.assign({},e),{data:n?na.message(e.data):n}))}),"messageId",pi,[bc,Xi,ec,fc,mc,gc,yc,vc,Zo(ao,"contentId","message"),Zo(so,"contentId","message")]),getMessages:(e,t,n)=>{const{log:r,cache:a}=Te();a||console.log(z);const s=Date.now();r(`getMessages(tmpid: ${s}) > listen`);const o=new Ic(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>{Ue(c)})),()=>{r(`getMessages(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}},convertFromRaw:Sn,prepareMessagePayload:kn,convertParams:On,convertQueryParams:Tn});const _c=e=>{const t=Te();return ot(t,"subChannelMarker/onSubChannelUnreadUpdatedLocal","local.subChannelUnread.updated",(t=>{e(t)}))};class kc extends Rr{async getRequest(e,t){var n;const{limit:r=$}=e,a=null!==(n=function(e){var{excludeDefaultSubChannel:t}=e,n=Xt(e,["excludeDefaultSubChannel"]);const r=Object.assign({},n);return void 0!==t&&(r.excludeDefaultMessageFeed=t),r}(Xt(e,["limit"])))&&void 0!==n?n:{},{channelId:s,includeDeleted:o}=a,i=Xt(a,["channelId","includeDeleted"]),c=t?{token:t}:{limit:r},{data:l}=await this.http.get(`/api/v5/message-feeds/channel/${s}`,{params:Object.assign(Object.assign({},i),{isDeleted:vn(o),options:c})});return l}}class Oc extends jr{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Te(),r=n.cache&&Date.now();n.cache&&Yt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,a;if(n)Me(this.cacheKey,{data:e.messageFeeds.map((({messageFeedId:e})=>e))});else{const t=null===(r=Re(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Me(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.messageFeeds.map((({messageFeedId:e})=>e))])]}))}}reactor(e){return t=>{var n;const r=null===(n=Re(this.cacheKey))||void 0===n?void 0:n.data;if(r){if(!Array.isArray(t)){if(this.query.channelId!==t.channelId)return;"onCreate"===e&&(r.data=[...new Set([t.subChannelId,...r.data])]),Me(this.cacheKey,r)}this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class Tc extends Br{constructor(e,t){const n=I.default(e),r=["subChannel","collection",n];super(new kc(e),n,r,t),this.query=e,this.queryStreamController=new Oc(this.query,this.cacheKey,this.notifyChange.bind(this),Mn),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Re(this.cacheKey))||void 0===e?void 0:e.data)||Me(this.cacheKey,{data:[]})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:sc,action:"onCreate"},{fn:qs,action:"onCreate"},{fn:Ns,action:"onDelete"},{fn:e=>tc((async t=>{if(!this.isRelatedCollection(t.subChannelId))return;const n=Te();if("no-message-preview"!==await n.getMessagePreviewSetting(!1)){const e=ln(t.subChannelId);(null==e?void 0:e.subChannelId)===t.subChannelId&&Pn(t.updatedAt)>Pn(e.subChannelUpdatedAt)&&Me(["messagePreviewSubChannel","get",t.subChannelId],Object.assign(Object.assign({},e),{subChannelName:t.displayName,subChannelUpdatedAt:t.updatedAt}))}e(t)})),action:"onUpdate"},{fn:Zo((e=>xs((async t=>{this.isRelatedCollection(t.subChannelId)&&(await xn(t),e(t))}))),"subChannelId","subChannel"),action:"onUpdate"},{fn:Zo((e=>Ds((async t=>{this.isRelatedCollection(t.subChannelId)&&(await xn(t),e(t))}))),"subChannelId","subChannel"),action:"onUpdate"},{fn:e=>no((t=>{var n;const r=null!==(n=t.map((({feedId:e})=>Re(["subChannel","get",e]))).filter(Boolean).map((({data:e})=>e)))&&void 0!==n?n:[];0!==r.length&&e(r)})),action:"onUpdate"},{fn:Zo(to,"feedId","subChannel"),action:"onUpdate"},{fn:Zo((e=>Xi((async t=>{var n;const r=Te();if("no-message-preview"===await r.getMessagePreviewSetting(!1))return;const a=null===(n=Re(this.cacheKey))||void 0===n?void 0:n.data;a&&a.data.includes(t.subChannelId)&&(Dn(t),e(t))}))),"subChannelId","subChannel"),action:"onUpdate"},{fn:Zo((e=>ec((async t=>{const n=Te(),r=await n.getMessagePreviewSetting(!1);"no-message-preview"!==r&&this.isRelatedCollection(t.subChannelId)&&("message-preview-not-include-deleted"===r?await jn(t.subChannelId):await Dn(t),e(t))}))),"subChannelId","subChannel"),action:"onUpdate"},{fn:Zo(_c,"subChannelId","subChannel"),action:"onUpdate"}])}notifyChange({origin:e,loading:t,error:n}){var r,a;const s=null===(r=Re(this.cacheKey))||void 0===r?void 0:r.data;if(!s)return;const o=this.applyFilter(null!==(a=s.data.map((e=>Re(["subChannel","get",e]))).filter(Boolean).map((({data:e})=>e)).map(dn))&&void 0!==a?a:[]);(this.shouldNotify(o)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:o,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=e;return this.query.includeDeleted||(t=xe(e,"isDeleted",!1)),t.sort(Ge),t}isRelatedCollection(e){var t;const n=null===(t=Re(this.cacheKey))||void 0===t?void 0:t.data;return n&&n.data.includes(e)}}const Ec={},Ac=async e=>{const t=await(async e=>{const t=jn.locally(e);if(t)return t.data.channelId;const{data:n}=await jn(e);return n.channelId})(e),n=mt({channelId:t,subChannelId:e});Ec[e]=Ct(n)};var Rc=Object.freeze({__proto__:null,getSubChannelByIds:ma,createSubChannel:async e=>{const t=Te();t.log("user/createSubChannel",e);const n=await t.http.post("/api/v5/message-feeds",{channelId:e.channelId,name:e.displayName}),r=await Mn(n.data),a=t.cache&&Date.now();return t.cache&&Yt(r,{cachedAt:a}),it("message-feed.created",n.data),{data:r.messageFeeds[0],cachedAt:a}},updateSubChannel:async(e,t)=>{const n=Te();n.log("channel/updateSubChannel",e,t);const r=await n.http.put(`/api/v5/message-feeds/${encodeURIComponent(e)}`,{name:t.displayName}),a=await Mn(r.data),s=n.cache&&Date.now();return n.cache&&Yt(a,{cachedAt:s}),it("message-feed.updated",r.data),{data:a.messageFeeds[0],cachedAt:s}},deleteSubChannel:ac,hardDeleteSubChannel:async e=>{Te().log("channel/hardDeleteSubChannel",e);return await ac(e,!0)},softDeleteSubChannel:async e=>{Te().log("channel/softDeleteSubChannel",e);return await ac(e,!1)},onSubChannelCreated:qs,onSubChannelUpdated:tc,onSubChannelDeleted:Ns,getSubChannel:(e,t)=>{const n=Te();let r;return Do(e,(e=>{if(!e.data)return t(e);const n=Object.assign(Object.assign({},e),{data:dn(e.data)}),a=Xt(n,["origin"]);return ir(r,a)?void 0:(r=a,t(n))}),"subChannelId",jn,[sc,t=>tc((async r=>{"no-message-preview"!==await n.getMessagePreviewSetting(!1)&&(Bn(r),r.subChannelId===e&&t(r))})),Ns,Zo(to,"feedId","subChannel"),t=>no((n=>{var r;if(!n.find((({feedId:t})=>t===e)))return;const a=null===(r=Re(["subChannel","get",e]))||void 0===r?void 0:r.data;a&&t(a)})),Zo((t=>xs((async n=>{n.subChannelId===e&&(await xn(n),t(n))}))),"subChannelId","subChannel"),Zo((t=>Ds((async n=>{n.subChannelId===e&&(await xn(n),t(n))}))),"subChannelId","subChannel"),Zo((t=>Xi((async r=>{"no-message-preview"!==await n.getMessagePreviewSetting(!1)&&r.subChannelId===e&&(Dn(r),t(r))}))),"subChannelId","subChannel"),Zo((t=>ec((async r=>{const a=await n.getMessagePreviewSetting(!1);"no-message-preview"!==a&&r.subChannelId===e&&("message-preview-include-deleted"===a&&await Dn(r),"message-preview-not-include-deleted"===a&&await jn(r.subChannelId),t(r))}))),"subChannelId","subChannel"),Zo(_c,"subChannelId","subChannel")],{forceDispatch:!0})},getSubChannels:(e,t,n)=>{const{log:r,cache:a}=Te(),s=Date.now();r(`getSubChannels(tmpid: ${s}) > listen`),a||console.log(z);const o=new Tc(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>{Ue(c)})),()=>{r(`getSubChannels(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}},markReadEngineOnLoginHandler:fa,startMessageReceiptSync:async e=>(await Ac(e),!0),stopMessageReceiptSync:e=>(Ec[e]&&Ec[e](),!0)});const Mc=e=>{const t=Te();return ot(t,"channelMarker/onChannelUnreadInfoUpdatedLocal","local.channelUnreadInfo.updated",(t=>{e(t)}))},jc=e=>{const t=Te();return ot(t,"channel/onChannelUnreadUpdatedLocal","local.channelUnread.updated",(t=>{e(t)}))};class Pc extends Rr{async getRequest(e,t){const{limit:n=$,displayName:r,membership:a}=e,s=Xt(e,["limit","displayName","membership"]),o=t?{token:t}:{limit:n},{data:i}=await this.http.get("/api/v3/channels",{params:Object.assign(Object.assign({},s),{keyword:r,filter:a,options:o})});return i}}class Uc extends Nr{async getRequest(e){const{data:t}=await this.http.get("/api/v3/channels/list",{params:Object.assign({},e)});return t}}class xc extends jr{constructor(e,t,n,r,a){super(e,t),this.notifyChange=n,this.preparePayload=r,this.paginationController=a}async saveToMainDB(e){const t=await this.preparePayload(e),n=Te(),r=n.cache&&Date.now();n.cache&&Yt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,a;if(n)Me(this.cacheKey,{data:e.channels.map(ve("channel"))});else{const t=null===(r=Re(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Me(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.channels.map(ve("channel"))])]}))}}reactor(e){return t=>{var n;const r=null===(n=Re(this.cacheKey))||void 0===n?void 0:n.data;if(r){if(this.paginationController instanceof Uc)return this.notifyChange({origin:"event",loading:!1});["onCreate","onJoin","onResolveChannel"].includes(e)&&(Array.isArray(t)?r.data=[...new Set([...t.map(ve("channel")),...r.data])]:r.data=[...new Set([t.channelInternalId,...r.data])]),Me(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const Dc=e=>{const t=Te();if(t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()){Qa().resolve(e.channelId,"userMessageFeedMarker")}},qc=e=>{const t=Te();return ot(t,"onChannelResolved","local.channel.resolved",(async t=>{e(t)}))};class Nc extends Br{constructor(e,t){const n=I.default(e),r=["channel","collection",n],a=Nc.getPaginationController(e);super(a,n,r,t),this.query=e,this.queryStreamController=new xc(this.query,this.cacheKey,this.notifyChange.bind(this),(async e=>{try{const t=Te();t.isUnreadCountEnabled&&t.getMarkerSyncConsistentMode()&&await Vn(e)}catch(e){console.error("Error while preparing unread count info",e)}return Qn(e)}),a),this.paginationController=a,this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Re(this.cacheKey))||void 0===e?void 0:e.data)||Me(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE(this.getSubscriptions())}notifyChange({origin:e,loading:t,error:n}){var r,a;const s=null===(r=Re(this.cacheKey))||void 0===r?void 0:r.data;if(!s)return;let o=null!==(a=s.data.map((e=>Re(["channel","get",e]))).filter(Boolean).map((({data:e})=>e)).map(ra))&&void 0!==a?a:[];this.paginationController instanceof Pc&&(o=this.applyFilter(o)),(this.shouldNotify(o)||"event"!==e)&&this.callback({onNextPage:this.paginationController instanceof Pc?()=>this.loadPage({direction:"next"}):void 0,data:o,hasNextPage:this.paginationController instanceof Pc&&!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){const{userId:t}=Te();let n=e;switch(n=xe(n,"isDeleted",this.query.isDeleted),n=De(n,"displayName",this.query.displayName),this.query.types&&(n=n.filter((e=>{var t;return null===(t=this.query.types)||void 0===t?void 0:t.includes(e.type)}))),this.query.tags&&(n=n.filter((e=>{var t;return null===(t=e.tags)||void 0===t?void 0:t.some((e=>{var t;return null===(t=this.query.tags)||void 0===t?void 0:t.includes(e)}))}))),this.query.excludeTags&&(n=n.filter((e=>{var t;return!(null===(t=e.tags)||void 0===t?void 0:t.some((e=>{var t;return null===(t=this.query.excludeTags)||void 0===t?void 0:t.includes(e)})))}))),this.query.membership&&t&&(n=Ne(n,this.query.membership,t)),this.query.sortBy){case"firstCreated":n=n.sort(ze);break;case"lastCreated":n=n.sort(He);break;case"displayName":n=n.map((e=>e.displayName?e:Object.assign(Object.assign({},e),{displayName:""}))).sort($e);break;default:n=n.sort(Ge)}return n}shouldAbort(e){var t,n;const r=null===(t=Re(this.cacheKey))||void 0===t?void 0:t.data;if(!r)return!0;return!(null===(n=null==r?void 0:r.data)||void 0===n?void 0:n.find((t=>t===e)))}static getMessagePreviewSetting(){return Te().getMessagePreviewSetting(!1)}static getPaginationController(e){return e.channelIds&&e.channelIds.length>0?new Uc(e):new Pc(e)}getSubscriptions(){const e=[{fn:Zo((e=>xs((t=>{var n,r;const a=Qa();(null===(n=Re(["subChannelUnreadInfo","get",t.subChannelId]))||void 0===n?void 0:n.data)||a.resolve(t.subChannelId,"userMessageFeedMarker");const s=null===(r=Re(["channel","get",t.channelId]))||void 0===r?void 0:r.data;s?(nc(s,{lastActivity:t.createdAt}),e(t)):a.resolve(t.channelId,"channel")}))),"channelId","channel"),action:"onUpdate"},{fn:Zo((e=>Ds((t=>{var n;const r=null===(n=Re(["channel","get",t.channelId]))||void 0===n?void 0:n.data;r&&(nc(r,{lastActivity:t.createdAt}),e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:Ma,action:"onDelete"},{fn:ds,action:"onUpdate"},{fn:bs,action:"onMute"},{fn:e=>ps((t=>{Dc(t),e(t)})),action:"onJoin"},{fn:e=>gs(((t,n)=>{var r,a;const{userId:s}=Te();if("member"===this.query.membership&&s===n.userId){const e=null===(r=Re(this.cacheKey))||void 0===r?void 0:r.data;Me(this.cacheKey,Object.assign(Object.assign({},e),{data:null!==(a=null==e?void 0:e.data.filter((e=>e!==t.channelId)))&&void 0!==a?a:[]}))}return e(t)})),action:"onLeft"},{fn:Is,action:"onMemberAdded"},{fn:ks,action:"onMemberRemoved"},{fn:Zo(eo,"entityId","channel"),action:"onUpdate"},{fn:Zo(rc,"entityId","channel"),action:"onUpdate"},{fn:Zo((e=>xs((async t=>{var n;if("no-message-preview"===await Nc.getMessagePreviewSetting())return;if(qn(t),this.shouldAbort(t.channelId))return;const r=null===(n=Re(["channel","get",t.channelId]))||void 0===n?void 0:n.data;r&&(nc(r,{messagePreviewId:t.messageId}),e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:Zo((e=>Ds((async t=>{var n;if("no-message-preview"===await Nc.getMessagePreviewSetting())return;if(qn(t),this.shouldAbort(t.channelId))return;const r=null===(n=Re(["channel","get",t.channelId]))||void 0===n?void 0:n.data;r&&(nc(r,{messagePreviewId:t.messageId}),e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:Zo((e=>Xi((async t=>{"no-message-preview"!==await Nc.getMessagePreviewSetting()&&(Nn(t),this.shouldAbort(t.channelId)||e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:Zo((e=>ec((async t=>{const n=await Nc.getMessagePreviewSetting();"no-message-preview"!==n&&("message-preview-include-deleted"===n&&await Nn(t),this.shouldAbort(t.channelId)||("message-preview-not-include-deleted"===n&&await Zi(t.channelId),e(t)))}))),"channelId","channel"),action:"onUpdate"},{fn:Zo((e=>Ns((async t=>{var n;const r=null===(n=Re(this.cacheKey))||void 0===n?void 0:n.data;if(!r)return;r.data.find((e=>{const n=sn(e);return(null==n?void 0:n.subChannelId)===t.subChannelId}))&&(await Zi(t.channelId),e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:Zo((e=>tc((async t=>{var n;if("no-message-preview"===await Nc.getMessagePreviewSetting())return;(null===(n=Re(this.cacheKey))||void 0===n?void 0:n.data)&&(await Bn(t),this.shouldAbort(t.channelId)||e(t))}))),"channelId","channel"),action:"onUpdate"},{fn:Zo(qs,"channelId","channel"),action:"onUpdate"},{fn:qc,action:"onResolveChannel"},{fn:e=>(e=>{const t=Te();return ot(t,"userMessageFeedMarker/onUserMessageFeedMarkerResolved","local.userMessageFeedMarkers.resolved",(t=>{e(t)}))})((async t=>{if(t.feedMarkers){const n=t.feedMarkers.map((e=>{var t;return null===(t=Re(["channel","get",e.entityId]))||void 0===t?void 0:t.data})).filter(Boolean);e(n)}})),action:"OnResolveUnread"},{fn:Zo(Mc,"channelId","channel"),action:"onUpdate"},{fn:Zo((e=>jc((t=>{t.forEach(e)}))),"channelId","channel"),action:"onUpdate"}];return this.paginationController instanceof Rr?[...e,{fn:e=>is((t=>{Dc(t),e(t)})),action:"onCreate"}]:e}}const Bc=()=>{var e;const t=Te();t.log("channel/getTotalChannelsUnread.locally");const n=(null===(e=Ae(["channelUnread","get"]))||void 0===e?void 0:e.filter((({data:e})=>!e.isDeleted)))||[];return{data:(null==n?void 0:n.reduce(((e,{data:t})=>(e.unreadCount+=t.unreadCount,e.isMentioned=e.isMentioned||t.isMentioned,e)),{unreadCount:0,isMentioned:!1}))||{unreadCount:0,isMentioned:!1},cachedAt:t.cache&&Date.now()}};class Lc extends Rr{async getRequest(e,t){const{limit:n=$,includeDeleted:r}=e,a=Xt(e,["limit","includeDeleted"]),s=t?{token:t}:{limit:n},o=!1!==r&&void 0,{data:i}=await this.http.get(`/api/v4/channels/${encodeURIComponent(a.channelId)}/users`,{params:Object.assign(Object.assign({},a),{options:s,isDeleted:o})});return i}}class Fc extends jr{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Te(),r=n.cache&&Date.now();n.cache&&Yt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,a;if(n)Me(this.cacheKey,{data:e.channelUsers.map((({channelId:e,userId:t})=>ve("channelUsers")({channelId:e,userId:t})))});else{const t=null===(r=Re(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Me(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.channelUsers.map((({channelId:e,userId:t})=>ve("channelUsers")({channelId:e,userId:t})))])]}))}}reactor(e){return(e,t)=>{var n;if(this.query.channelId!==t.channelId)return;const r=null===(n=Re(this.cacheKey))||void 0===n?void 0:n.data;if(!r)return;const a=ve("channelUsers")({channelId:this.query.channelId,userId:t.userId});"none"===t.membership?r.data=r.data.filter((e=>e!==a)):r.data.includes(a)||(r.data=[a,...r.data]),Me(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1})}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class Kc extends Br{constructor(e,t){const n=I.default(e),r=["channelUsers","collection",n];super(new Lc(e),n,r,t),this.query=e,this.queryStreamController=new Fc(this.query,this.cacheKey,this.notifyChange.bind(this),Qn),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Re(this.cacheKey))||void 0===e?void 0:e.data)||Me(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:ps,action:"onJoin"},{fn:gs,action:"onLeft"},{fn:Is,action:"onMemberAdded"},{fn:ks,action:"onMemberRemoved"},{fn:Ua,action:"onChannelMemberBanned"},{fn:Es,action:"onChannelMemberUnbanned"},{fn:Ms,action:"onChannelMemberRoleAdded"},{fn:Us,action:"onChannelMemberRoleRemoved"},{fn:(e=this.query.channelId,t=>{const n=Te();return ot(n,"user.deleted","user.deleted",(n=>{var r,a;const s=xa(n);if(0===s.users.length)return;const o=s.users[0];Yt(s);const i=ve("channelUsers")({channelId:e,userId:o.userId}),c=null===(r=Re(["channelUsers","get",i]))||void 0===r?void 0:r.data;Pe(["channelUsers","get",i],Object.assign(Object.assign({},c),{user:o}));const l=null===(a=Re(["channel","get",e]))||void 0===a?void 0:a.data;l&&t(l,c)}))}),action:"onChannelMemberChanged"}]);var e}notifyChange({origin:e,loading:t,error:n}){var r,a;const s=null===(r=Re(this.cacheKey))||void 0===r?void 0:r.data;if(!s)return;const o=this.applyFilter(null!==(a=s.data.map((e=>Re(["channelUsers","get",e]))).filter(Boolean).map((({data:e})=>e)).map(na.channelMember))&&void 0!==a?a:[]);(this.shouldNotify(o)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:o,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=qe(e,"roles",this.query.roles);this.query.memberships&&(t=t.filter((e=>{var t,n;return!(!(null===(t=this.query.memberships)||void 0===t?void 0:t.includes("muted"))||!e.isMuted)||"none"!==e.membership&&(null===(n=this.query.memberships)||void 0===n?void 0:n.includes(e.membership))}))),!1===this.query.includeDeleted&&(t=t.filter((e=>{var t;return!0!==(null===(t=e.user)||void 0===t?void 0:t.isDeleted)})));const n=this.query.sortBy?this.query.sortBy:"lastCreated";return t=t.sort("lastCreated"===n?He:ze),t}}const $c=(e,t,n)=>{const{log:r,cache:a}=Te();a||console.log(z);const s=Date.now();r(`getMembers(tmpid: ${s}) > listen`);const o=new Kc(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>{Ue(c)})),()=>{r(`getMembers(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}};var Qc=Object.freeze({__proto__:null,addMembers:async(e,t)=>{const n=Te();n.log("channel/addMembers",e,t);const{data:r}=await n.http.post(`/api/v3/channels/${encodeURIComponent(e)}/users`,{channelId:e,userIds:t});t.forEach((e=>it("channel.membersAdded",Object.assign(Object.assign({},r),{channelUsers:r.channelUsers.filter((t=>t.userId===e))}))));const a=await Qn(r);n.cache&&Yt(a);const{channelUsers:s}=a;return!!s.find((t=>t.channelId===e&&"member"===t.membership))},removeMembers:async(e,t)=>{const n=Te();n.log("channel/removeMembers",e,t);const{data:r}=await n.http.delete(`/api/v3/channels/${encodeURIComponent(e)}/users`,{data:{channelId:e,userIds:t}});t.forEach((e=>it("channel.membersRemoved",Object.assign(Object.assign({},r),{channelUsers:r.channelUsers.filter((t=>t.userId===e))}))));const a=await Qn(r);n.cache&&Yt(a);const{channelUsers:s}=a;return!!s.find((t=>t.channelId===e&&"member"!==t.membership))},applyFilter:(e,t)=>{let n=qe(e,"roles",t.roles);t.memberships&&(n=n.filter((e=>!(!t.memberships.includes("muted")||!e.isMuted)||t.memberships.includes(e.membership))));const r=t.sortBy?t.sortBy:"lastCreated";return n=n.sort("lastCreated"===r?He:ze),n},getMembers:$c,searchMembers:(e,t,n)=>$c(e,t)});var zc=Object.freeze({__proto__:null,addRole:async(e,t,n)=>{const r=Te();r.log("channel/addRole",e,t,n);const{data:a}=await r.http.post(`/api/v3/channels/${encodeURIComponent(e)}/users/roles`,{channelId:e,role:t,userIds:n}),s=await Qn(a);r.cache&&Yt(s),it("local.channel-moderator.role-added",s);const{channelUsers:o}=s;return!!o.find((n=>n.channelId===e&&n.roles.includes(t)))},removeRole:async(e,t,n)=>{const r=Te();r.log("channel/removeRole",e,t,n);const{data:a}=await r.http.delete(`/api/v3/channels/${encodeURIComponent(e)}/users/roles`,{data:{channelId:e,role:t,userIds:n}}),s=await Qn(a);r.cache&&Yt(s),it("local.channel-moderator.role-removed",s);const{channelUsers:o}=s;return!!o.find((n=>n.channelId===e&&!n.roles.includes(t)))},banMembers:async(e,t)=>{const n=Te();n.log("channel/banMembers",{userIds:t,channelId:e});const{data:r}=await n.http.put(`/api/v3/channels/${e}/users/ban`,{userIds:t}),a=await Qn(r),{channelUsers:s}=a,o=n.cache&&Date.now();return n.cache&&Yt(a,{cachedAt:o}),{data:null==s?void 0:s.filter((e=>"banned"===e.membership)),cachedAt:o}},unbanMembers:async(e,t)=>{const n=Te();n.log("channel/unbanMembers",{userIds:t,channelId:e});const{data:r}=await n.http.put(`/api/v3/channels/${encodeURIComponent(e)}/users/unban`,{userIds:t}),a=await Qn(r),s=n.cache&&Date.now();n.cache&&Yt(a,{cachedAt:s});const{channelUsers:o}=a;return{data:null==o?void 0:o.filter((e=>"member"===e.membership)),cachedAt:s}},muteMembers:async(e,t,n=-1)=>{const r=Te();r.log("channel/muteMembers",{userIds:t,channelId:e,mutePeriod:n});const{data:a}=await r.http.put(`/api/v2/channel/${e}/users/mute`,{userIds:t,mutePeriod:-1===n?n:1e3*n}),{success:s}=a;return s},unmuteMembers:async(e,t)=>{const n=Te();n.log("channel/unmuteMembers",{userIds:t,channelId:e});const{data:r}=await n.http.put(`/api/v2/channel/${encodeURIComponent(e)}/users/mute`,{userIds:t,mutePeriod:0}),{success:a}=r;return a}}),Vc=Object.freeze({__proto__:null,Membership:Qc,Moderation:zc,getChannelByIds:aa,createChannel:async e=>{const t=Te();let n;if(t.log("user/createChannel",e),"conversation"===(null==e?void 0:e.type))n=await t.http.post("/api/v3/channels/conversation",Object.assign(Object.assign({},e),{isDistinct:!0}));else{const{isPublic:r}=e,a=Xt(e,["isPublic"]);n=await t.http.post("/api/v3/channels",Object.assign(Object.assign({},a),{isPublic:"community"===(null==e?void 0:e.type)?r:void 0}))}const r=await Qn(n.data),a=t.cache&&Date.now();t.cache&&Yt(r,{cachedAt:a});const{channels:s}=r;return{data:Gn(s[0]),cachedAt:a}},updateChannel:async(e,t)=>{const n=Te();n.log("channel/updateChannel",e,t);const{data:r}=await n.http.put(`/api/v3/channels/${encodeURIComponent(e)}`,t),a=await Qn(r),s=n.cache&&Date.now();n.cache&&Yt(a,{cachedAt:s});const{channels:o}=a;return{data:Gn(o.find((t=>t.channelId===e))),cachedAt:s}},deleteChannel:async e=>{const t=Te();t.log("channel/deleteChannel",e),await t.http.delete(`/api/v3/channels/${encodeURIComponent(e)}`);const n=await Zi(e);return Gn(n.data)},joinChannel:async e=>{const t=Te();t.log("channel/joinChannel",e);const{data:n}=await t.http.post(`/api/v3/channels/${encodeURIComponent(e)}/join`),r=await Qn(n);t.cache&&Yt(r);const{channelUsers:a}=r;return!!a.find((t=>t.channelId===e&&"member"===t.membership))},leaveChannel:async e=>{const t=Te();t.log("channel/leaveChannel",e);const{data:n}=await t.http.delete(`/api/v3/channels/${encodeURIComponent(e)}/leave`),r=await Qn(n);t.cache&&Yt(r);const{channelUsers:a}=r;return!!a.find((t=>t.channelId===e&&"member"!==t.membership))},muteChannel:async(e,t=-1)=>{const n=Te();if(n.log("channel/muteChannel",e),-1!==t&&t<0)throw new Ce("Mute Period can only be positive numbers or -1(mute forever)",800110,"error");const{data:r}=await n.http.put(`/api/v2/channel/${encodeURIComponent(e)}/mute`,{mutePeriod:t}),{success:a}=r;return a},unmuteChannel:async e=>{const t=Te();t.log("channel/unmuteChannel",e);const{data:n}=await t.http.put(`/api/v2/channel/${encodeURIComponent(e)}/mute`,{mutePeriod:0}),{success:r}=n;return r},onChannelCreated:is,onChannelUpdated:ds,onChannelDeleted:Ma,onChannelJoined:ps,onChannelLeft:gs,onChannelMuted:bs,onChannelMemberAdded:Is,onChannelMemberRemoved:ks,onChannelMemberBanned:Ua,onChannelMemberUnbanned:Es,onChannelMemberRoleAdded:Ms,onChannelMemberRoleRemoved:Us,getChannel:(e,t)=>{const n=Te();let r;return Do(e,(async e=>{if(!e.data)return t(e);const n=Object.assign(Object.assign({},e),{data:ra(e.data)}),a=Xt(n,["origin"]);return ir(r,a)?void 0:(r=a,t(n))}),"channelId",Zi,[ds,Ma,ps,gs,Is,ks,Ua,Es,bs,Zo(eo,"entityId","channel"),Zo(rc,"entityId","channel"),Zo((t=>xs((async r=>{await(async r=>{var a;if("no-message-preview"===await n.getMessagePreviewSetting(!1))return;if(await qn(r),r.channelId!==e)return;const s=null===(a=Re(["channel","get",e]))||void 0===a?void 0:a.data;s&&(nc(s,{messagePreviewId:r.messageId}),t(r))})(r),t(r)}))),"channelId","channel"),Zo((t=>Ds((async r=>{var a;if("no-message-preview"===await n.getMessagePreviewSetting(!1))return;if(await qn(r),r.channelId!==e)return;const s=null===(a=Re(["channel","get",e]))||void 0===a?void 0:a.data;s&&(nc(s,{messagePreviewId:r.messageId}),t(r))}))),"channelId","channel"),Zo((t=>Xi((async r=>{var a;const s=null===(a=Re(["channel","get",e]))||void 0===a?void 0:a.data;if(!s||s.messagePreviewId!==r.messageId)return;"no-message-preview"!==await n.getMessagePreviewSetting(!1)&&(await Nn(r),t(r))}))),"channelId","channel"),Zo((t=>ec((async r=>{var a;const s=null===(a=Re(["channel","get",e]))||void 0===a?void 0:a.data;if(!s||s.messagePreviewId!==r.messageId)return;const o=await n.getMessagePreviewSetting(!1);"no-message-preview"!==o&&("message-preview-not-include-deleted"===o?(Ue(["messagePreviewChannel","get",e]),await Zi(r.channelId)):await Nn(r),t(r))}))),"channelId","channel"),Zo((e=>Ns((async t=>{var r,a;const{channelId:s,subChannelId:o}=t,i=null===(r=Re(["messagePreviewChannel","get",s]))||void 0===r?void 0:r.data;if(!i||i.subChannelId!==o)return;if("no-message-preview"===await n.getMessagePreviewSetting(!1))return;await Zi(s);(null===(a=Re(["channel","get",s]))||void 0===a?void 0:a.data)&&e(t)}))),"channelId","channel"),Zo((t=>tc((async r=>{var a,s;if("no-message-preview"===await n.getMessagePreviewSetting(!1))return;Bn(r);const o=null===(a=Re(["messagePreviewChannel","get",e]))||void 0===a?void 0:a.data;if(!o||o.subChannelId!==r.subChannelId)return;(null===(s=Re(["channel","get",e]))||void 0===s?void 0:s.data)&&t(r)}))),"channelId","channel"),Zo(qs,"channelId","channel"),Zo(Mc,"channelId","channel"),Zo((e=>jc((t=>{t.forEach(e)}))),"channelId","channel")],{forceDispatch:!0})},getChannels:(e,t,n)=>{const{log:r,cache:a,userId:s}=Te();a||console.log(z);const o=Date.now();r(`getChannels(tmpid: ${o}) > listen`);const i=new Nc(e,t),c=i.startSubscription(),l=i.getCacheKey();return c.push((()=>{Ue(l)})),()=>{r(`getChannels(tmpid: ${o}) > dispose`),c.forEach((e=>e()))}},getTotalChannelsUnread:e=>{const{_id:t}=Ze();if(!t)throw new Ce("The _id has not been defined in ActiveUser",8e5,"error");const{log:n,cache:r}=Te();r||console.log("For using Live Object feature you need to enable Cache!");n(`liveTotalChannelsUnread(tmpid: ${Date.now()}) > listen`);const a=[];let s,o=!1;const i=t=>{const{data:n}=t,r=n?{unreadCount:n.unreadCount,isMentioned:n.isMentioned}:void 0;s=r?Dr(r):r,e({data:r?Object.assign(Object.assign({},r),{isMentioned:r.isMentioned}):r,loading:t.loading,error:t.error})};return a.push(jc((e=>{const{data:t}=Bc();ir(s,t)||i({loading:!1,data:t})}))),(()=>{const e=pe((async()=>Bc()));me(e,(({error:e,data:t,loading:n,origin:r,cachedAt:s})=>{s===H?(i({data:t,origin:r,loading:!1,error:new Ie(V,800800,"error")}),o=!0,a.forEach((e=>e()))):o||i({loading:n,data:t,origin:r,error:e}),e&&a.forEach((e=>e()))}))})(),()=>{a.forEach((e=>e()))}},MARKER_INCLUDED_CHANNEL_TYPE:Ln,isUnreadCountSupport:Fn,convertFromRaw:Kn,preUpdateChannelCache:$n,prepareChannelPayload:Qn});const Hc=(e,t)=>{0!==e.length&&0!==t.length&&e.forEach((({communityId:e})=>{const n=t.filter((({communityId:t})=>e===t));Me(["communityUsers","collection",e],n)}))},Jc=async(e,t)=>{const n=Te();n.log("community/getCommunities",e);const r=e.map((e=>encodeURIComponent(e))),{data:a}=await n.http.get("/api/v3/communities/list",{params:{communityIds:r,includeDiscoverablePrivateCommunity:null==t||t}}),s=_r(a),o=n.cache&&Date.now();return n.cache&&(Yt(s,{cachedAt:o}),Hc(s.communities,s.communityUsers)),{data:s.communities.map((e=>na.community(e))),cachedAt:o}};Jc.locally=e=>{var t;const n=Te();if(n.log("community/getCommunities.locally",e),!n.cache)return;const r=e.map((e=>Re(["community","get",e]))).filter(Boolean),a=r.map((({data:e})=>e)),s=null===(t=r.sort(((e,t)=>e.cachedAt<t.cachedAt?-1:1)))||void 0===t?void 0:t[0];return(null==r?void 0:r.length)<e.length?void 0:{data:a,cachedAt:s.cachedAt}};const Wc=async(e,t,n)=>{const r=Te();r.log("community/getCommunity",e);const{data:a}=await r.http.get(`/api/v3/communities/${e}`,{params:{type:"communityJoinRequest",includeDiscoverablePrivateCommunity:null==n||n}}),s=_r(a),o=r.cache&&Date.now();r.cache&&(Yt(s,{cachedAt:o}),Hc(s.communities,s.communityUsers));const{communities:i}=s;return{data:i.find((t=>t.communityId===e)),cachedAt:o}};Wc.locally=e=>{const t=Te();if(t.log("community/getCommunity.locally",e),!t.cache)return;const n=Re(["community","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const Gc=(e,t)=>{const n=Te();return ot(n,e,e,(e=>{const r=_r(e);if(n.cache){Yt(r);const e=Re(["community","get",r.communities[0].communityId]);t(e.data)}else t(r.communities[0])}))},Yc=e=>Gc("community.created",e),Zc=e=>Gc("community.updated",e),Xc=e=>Gc("community.deleted",e);class el extends Rr{async getRequest(e,t){var n;const{limit:r=$}=e,a=Xt(e,["limit"]),s=t?{token:t}:{limit:r},{data:o}=await this.http.get("/api/v3/communities",{params:Object.assign(Object.assign({},a),{isDeleted:vn(a.includeDeleted),keyword:a.displayName,filter:a.membership,includeDiscoverablePrivateCommunity:null===(n=a.includeDiscoverablePrivateCommunity)||void 0===n||n,options:s})});return o}}class tl extends jr{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Te(),r=n.cache&&Date.now();n.cache&&Yt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,a;if(n)Me(this.cacheKey,{data:e.communities.map(ve("community"))});else{const t=null===(r=Re(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Me(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.communities.map(ve("community"))])]}))}}reactor(e){return e=>{var t;const n=null===(t=Re(this.cacheKey))||void 0===t?void 0:t.data;n&&(Me(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}var nl,rl;!function(e){e.OnCommunityCreated="onCommunityCreated",e.OnCommunityDeleted="onCommunityDeleted",e.OnCommunityUpdated="onCommunityUpdated"}(nl||(nl={})),function(e){e.OnCommunityJoined="onCommunityJoined",e.OnCommunityLeft="onCommunityLeft",e.OnCommunityUserBanned="onCommunityUserBanned",e.OnCommunityUserChanged="onCommunityUserChanged",e.OnCommunityUserRoleAdded="onCommunityUserRoleAdded",e.OnCommunityUserRoleRemoved="onCommunityUserRoleRemoved",e.OnCommunityUserUnbanned="onCommunityUserUnbanned",e.OnMemberCountChanged="OnMemberCountChanged",e.OnCommunityUserAdded="OnCommunityUserAdded",e.onCommunityUserRemoved="onCommunityUserRemoved",e.OnUserDeleted="OnUserDeleted",e.OnLocalCommunityJoin="OnLocalCommunityJoin"}(rl||(rl={}));class al extends Rr{async getRequest(e,t){const{limit:n=$,includeDeleted:r}=e,a=Xt(e,["limit","includeDeleted"]),s=t?{token:t}:{limit:n},o=!1!==r&&void 0,{data:i}=await this.http.get(`/api/v3/communities/${a.communityId}/users`,{params:Object.assign(Object.assign({},a),{options:s,isDeleted:o})});return i}}class sl extends jr{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Te(),r=n.cache&&Date.now();n.cache&&Yt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,a;if(n)Me(this.cacheKey,{data:e.communityUsers.map((({communityId:e,userId:t})=>ve("communityUsers")({communityId:e,userId:t})))});else{const t=null===(r=Re(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Me(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.communityUsers.map((({communityId:e,userId:t})=>ve("communityUsers")({communityId:e,userId:t})))])]}))}}reactor(e){return(e,t)=>{var n;const r=null===(n=Re(this.cacheKey))||void 0===n?void 0:n.data;r&&(t.forEach((e=>{const t=ve("communityUsers")({communityId:this.query.communityId,userId:e.userId});"none"===e.communityMembership?r.data=r.data.filter((e=>e!==t)):r.data.includes(t)||(r.data=[t,...r.data])})),Me(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}function ol(e,t,n){return!!e.permissions.some((e=>e===n))||t.communityUsers.find((t=>t.userId===e.userId)).permissions.some((e=>e===n))}function il(e,t){return"community.joined"===e||"community.left"===e?t.communityUsers:"community.userRemoved"===e||"local.community.userRemoved"===e?t.communityUsers.filter((e=>"none"===e.communityMembership)):"community.userBanned"===e?t.communityUsers.filter((e=>"banned"===e.communityMembership)):"community.userUnbanned"===e?t.communityUsers.filter((e=>!ol(e,t,"BAN_COMMUNITY_USER"))):t.communityUsers.filter((e=>!ol(e,t,"ADD_COMMUNITY_USER")))}const cl=(e,t)=>{const n=Te();return ot(n,e,e,(r=>{const a=_r(r),{communities:s,communityUsers:o}=a,i=Cr(s,o);if(a.communities=i,n.cache){Yt(a,void 0,!1);const n=Re(["community","get",a.communities[0].communityId]),r=il(e,a).map((e=>{const t=Re(["communityUsers","get",ve("communityUsers")(e)]);return null==t?void 0:t.data})).filter(cr);t(n.data,r)}else t(a.communities[0],il(e,a))}))},ll=(e,t)=>{const n=Te();return ot(n,e,e,(r=>{const a=_r(r),{communities:s,communityUsers:o}=a,i=Cr(s,o);if(a.communities=i,n.cache){Yt(a,void 0,!1);const n=Re(["community","get",a.communities[0].communityId]),r=il(e,a).map((e=>{const t=Re(["communityUsers","get",ve("communityUsers")(e)]);return null==t?void 0:t.data})).filter(cr);t(n.data,r)}else t(a.communities[0],il(e,a))}))},dl=e=>cl("community.userBanned",e),ul=e=>cl("community.userChanged",e),hl=e=>cl("community.userUnbanned",e),pl=e=>cl("community.roleAdded",e),fl=e=>cl("community.roleRemoved",e),ml=e=>ll("local.community.userAdded",e),gl=e=>ll("local.community.userRemoved",e),yl=e=>cl("community.joined",e),vl=e=>cl("community.left",e),bl=e=>ll("local.community.joined",e),wl=e=>ll("local.community.left",e),Cl=e=>{const t=Te(),n=[ot(t,"onCommunityUpdate","v4.local.community.joined",(async t=>{e(t[0])}))];return()=>{n.forEach((e=>e()))}},Il=e=>{const t=Te();return ot(t,"onLocalCommunityRoleRemoved","local.community.roleRemoved",(async t=>{const{communities:n,communityUsers:r}=t;e(n[0],r.filter((e=>"member"===e.communityMembership)))}))},Sl=e=>{const t=Te();return ot(t,"onLocalCommunityRoleAdded","local.community.roleAdded",(async t=>{const{communities:n,communityUsers:r}=t;e(n[0],r.filter((e=>"member"===e.communityMembership)))}))},_l=e=>t=>{const n=Te();return ot(n,"user.deleted","user.deleted",(n=>{var r,a;const s=xa(n);if(0===s.users.length)return;const o=s.users[0];Yt(s);const i=ve("communityUsers")({communityId:e,userId:o.userId}),c=null===(r=Re(["communityUsers","get",i]))||void 0===r?void 0:r.data;Me(["communityUsers","get",i],Object.assign(Object.assign({},c),{user:o}));const l=null===(a=Re(["community","get",e]))||void 0===a?void 0:a.data;t(l,[Object.assign(Object.assign({},c),{user:o})])}))};class kl extends Br{constructor(e,t){const n=I.default(e),r=["communityUsers","collection",n];super(new al(e),n,r,t),this.query=e,this.queryStreamController=new sl(this.query,this.cacheKey,this.notifyChange.bind(this),_r),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Re(this.cacheKey))||void 0===e?void 0:e.data)||Me(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:yl,action:rl.OnCommunityJoined},{fn:bl,action:rl.OnCommunityJoined},{fn:vl,action:rl.OnCommunityLeft},{fn:wl,action:rl.OnCommunityLeft},{fn:dl,action:rl.OnCommunityUserBanned},{fn:ul,action:rl.OnCommunityUserChanged},{fn:pl,action:rl.OnCommunityUserRoleAdded},{fn:fl,action:rl.OnCommunityUserRoleRemoved},{fn:Sl,action:rl.OnCommunityUserRoleAdded},{fn:Il,action:rl.OnCommunityUserRoleRemoved},{fn:hl,action:rl.OnCommunityUserUnbanned},{fn:ml,action:rl.OnCommunityUserAdded},{fn:gl,action:rl.onCommunityUserRemoved},{fn:_l(this.query.communityId),action:rl.OnCommunityUserChanged}])}notifyChange({origin:e,loading:t,error:n}){var r,a;const s=null===(r=Re(this.cacheKey))||void 0===r?void 0:r.data;if(!s)return;const o=this.applyFilter(null!==(a=s.data.map((e=>Re(["communityUsers","get",e]))).filter(cr).map((({data:e})=>e)))&&void 0!==a?a:[]);(this.shouldNotify(o)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:o,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=qe(e,"roles",this.query.roles);if(this.query.memberships&&(t=t.filter((({communityMembership:e})=>(this.query.memberships||[]).includes(e)))),!1===this.query.includeDeleted&&(t=t.filter((({user:e})=>!0!==(null==e?void 0:e.isDeleted)))),"firstCreated"===this.query.sortBy)t=t.sort(ze);else t=t.sort(He);return t}}class Ol extends Rr{async getRequest(e,t){const{limit:n=$,includeDeleted:r}=e,a=Xt(e,["limit","includeDeleted"]),s=t?{token:t}:{limit:n},o=!1!==r&&void 0,{data:i}=await this.http.get(`/api/v3/communities/${a.communityId}/users`,{params:Object.assign(Object.assign({},a),{options:s,isDeleted:o})});return i}}class Tl extends jr{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Te(),r=n.cache&&Date.now();n.cache&&Yt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,a;if(n)Me(this.cacheKey,{data:e.communityUsers.map((({communityId:e,userId:t})=>ve("communityUsers")({communityId:e,userId:t})))});else{const t=null===(r=Re(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Me(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.communityUsers.map((({communityId:e,userId:t})=>ve("communityUsers")({communityId:e,userId:t})))])]}))}}reactor(e){return(e,t)=>{var n;const r=null===(n=Re(this.cacheKey))||void 0===n?void 0:n.data;r&&(t.forEach((e=>{const t=ve("communityUsers")({communityId:this.query.communityId,userId:e.userId});"none"===e.communityMembership&&(r.data=r.data.filter((e=>e!==t)))})),Me(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}var El;!function(e){e.OnCommunityJoined="onCommunityJoined",e.OnLocalCommunityJoin="onLocalCommunityJoin",e.OnCommunityLeft="onCommunityLeft",e.OnCommunityUserBanned="onCommunityUserBanned",e.OnCommunityUserChanged="onCommunityUserChanged",e.OnCommunityUserRoleAdded="onCommunityUserRoleAdded",e.OnCommunityUserRoleRemoved="onCommunityUserRoleRemoved",e.OnCommunityUserUnbanned="onCommunityUserUnbanned"}(El||(El={}));class Al extends Br{constructor(e,t){const n=I.default(e),r=["communityUsers","collection",n];super(new Ol(e),n,r,t),this.query=e,this.queryStreamController=new Tl(this.query,this.cacheKey,this.notifyChange.bind(this),_r),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Re(this.cacheKey))||void 0===e?void 0:e.data)||Me(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:yl,action:El.OnCommunityJoined},{fn:bl,action:El.OnCommunityJoined},{fn:vl,action:El.OnCommunityLeft},{fn:wl,action:El.OnCommunityLeft},{fn:dl,action:El.OnCommunityUserBanned},{fn:ul,action:El.OnCommunityUserChanged},{fn:Il,action:El.OnCommunityUserRoleRemoved},{fn:fl,action:El.OnCommunityUserRoleRemoved},{fn:hl,action:El.OnCommunityUserUnbanned},{fn:_l(this.query.communityId),action:El.OnCommunityUserChanged}])}notifyChange({origin:e,loading:t,error:n}){var r,a;const s=null===(r=Re(this.cacheKey))||void 0===r?void 0:r.data;if(!s)return;const o=this.applyFilter(null!==(a=s.data.map((e=>Re(["communityUsers","get",e]))).filter(cr).map((({data:e})=>e)))&&void 0!==a?a:[]);(this.shouldNotify(o)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:o,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=qe(e,"roles",this.query.roles);return this.query.memberships&&(t=t.filter((({communityMembership:e})=>(this.query.memberships||[]).includes(e)))),this.query.search&&(t=Ke(t,this.query.search)),!1===this.query.includeDeleted&&(t=t.filter((({user:e})=>!0!==(null==e?void 0:e.isDeleted)))),t}}var Rl=Object.freeze({__proto__:null,addMembers:async(e,t)=>{const n=Te();n.log("community/moderation/addMembers",e,t);const{data:r}=await n.http.post(`/api/v3/communities/${e}/users`,{communityId:e,userIds:t});it("local.community.userAdded",r);const a=tn(r,"communityUsers");n.cache&&Yt(a);const{communityUsers:s}=a;return!!s.find((t=>t.communityId===e&&"member"===t.communityMembership))},removeMembers:async(e,t)=>{const n=Te();n.log("community/moderation/removeMembers",e,t);const{data:r}=await n.http.delete(`/api/v3/communities/${e}/users`,{data:{communityId:e,userIds:t}});it("local.community.userRemoved",r);const a=tn(r,"communityUsers");n.cache&&Yt(a);const{communityUsers:s}=a;return!!s.find((t=>t.communityId===e&&"member"!==t.communityMembership))},applyFilter:(e,t)=>{let n=qe(e,"roles",t.roles);t.memberships&&(n=n.filter((({communityMembership:e})=>t.memberships.includes(e))));const r=t.sortBy?t.sortBy:"lastCreated";return n=n.sort("lastCreated"===r?He:ze),n},getMembers:(e,t,n)=>{const{log:r,cache:a}=Te();a||console.log(z);const s=Date.now();r(`getMembers(tmpid: ${s}) > listen`);const o=new kl(e,(e=>{t(e)})),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>{Ue(c)})),()=>{r(`getMembers(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}},searchMembers:(e,t,n)=>{const{log:r,cache:a}=Te();a||console.log(z);const s=Date.now();r(`getMembers(tmpid: ${s}) > listen`);const o=new Al(e,(e=>{t(e)})),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>{Ue(c)})),()=>{r(`getMembers(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}},onCommunityUserAdded:e=>cl("community.userAdded",e),onCommunityUserRemoved:e=>cl("community.userRemoved",e),onCommunityUserBanned:dl,onCommunityUserChanged:ul,onCommunityUserUnbanned:hl,onCommunityUserRoleAdded:pl,onCommunityUserRoleRemoved:fl,onLocalCommunityUserAdded:ml,onLocalCommunityUserRemoved:gl,onCommunityJoined:yl,onCommunityLeft:vl,onLocalCommunityJoined:bl,onLocalCommunityLeft:wl,onLocalCommunityJoin:Cl});class Ml extends Br{constructor(e,t){const n=I.default(e),r=["community","collection",n];super(new el(e),n,r,t),this.query=e,this.queryStreamController=new tl(this.query,this.cacheKey,this.notifyChange.bind(this),_r),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Re(this.cacheKey))||void 0===e?void 0:e.data)||Me(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:Xc,action:nl.OnCommunityDeleted},{fn:Zc,action:nl.OnCommunityUpdated},{fn:yl,action:rl.OnCommunityJoined},{fn:vl,action:rl.OnCommunityLeft},{fn:ul,action:rl.OnMemberCountChanged},{fn:bl,action:rl.OnCommunityJoined},{fn:wl,action:rl.OnCommunityLeft},{fn:Zo(Cl,"targetId","community"),action:nl.OnCommunityUpdated}])}notifyChange({origin:e,loading:t,error:n}){var r,a;const s=null===(r=Re(this.cacheKey))||void 0===r?void 0:r.data;if(!s)return;const o=this.applyFilter(null!==(a=s.data.map((e=>Re(["community","get",e]))).filter(cr).map((({data:e})=>e)))&&void 0!==a?a:[]);(this.shouldNotify(o)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:o,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){const{userId:t}=Te();let n=e;return this.query.includeDeleted||(n=xe(n,"isDeleted",!1)),this.query.categoryId&&(n=n.filter((e=>{var t;return null===(t=e.categoryIds)||void 0===t?void 0:t.includes(this.query.categoryId)}))),this.query.tags&&(n=n.filter((e=>{var t;return null===(t=e.tags)||void 0===t?void 0:t.some((e=>{var t;return null===(t=this.query.tags)||void 0===t?void 0:t.includes(e)}))}))),this.query.membership&&t&&(n=Le(n,this.query.membership,t)),n}}class jl extends Rr{async getRequest(e,t){var n;const{limit:r=$}=e,a=Xt(e,["limit"]),s=t?{token:t}:{limit:r},{data:o}=await this.http.get("/api/v3/communities",{params:Object.assign(Object.assign({},a),{isDeleted:vn(a.includeDeleted),filter:a.membership,includeDiscoverablePrivateCommunity:null===(n=a.includeDiscoverablePrivateCommunity)||void 0===n||n,options:s})});return o}}class Pl extends jr{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Te(),r=n.cache&&Date.now();n.cache&&(Yt(t,{cachedAt:r}),Hc(e.communities,e.communityUsers))}appendToQueryStream(e,t,n=!1){var r,a;if(n)Me(this.cacheKey,{data:e.communities.map(ve("community"))});else{const t=null===(r=Re(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Me(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.communities.map(ve("community"))])]}))}}reactor(e){return e=>{var t;const n=null===(t=Re(this.cacheKey))||void 0===t?void 0:t.data;n&&(n.data=[...new Set([e.communityId,...n.data])],Me(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}var Ul;!function(e){e.OnCommunityCreated="onCommunityCreated",e.OnCommunityDeleted="onCommunityDeleted",e.OnCommunityUpdated="onCommunityUpdated"}(Ul||(Ul={}));class xl extends Br{constructor(e,t){const n=I.default(e),r=["community","collection",n];super(new jl(e),n,r,t),this.query=e,this.queryStreamController=new Pl(this.query,this.cacheKey,this.notifyChange.bind(this),_r),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Re(this.cacheKey))||void 0===e?void 0:e.data)||Me(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:Yc,action:Ul.OnCommunityCreated},{fn:Xc,action:Ul.OnCommunityDeleted},{fn:Zc,action:Ul.OnCommunityUpdated},{fn:yl,action:rl.OnCommunityJoined},{fn:vl,action:rl.OnCommunityLeft},{fn:ul,action:rl.OnMemberCountChanged},{fn:bl,action:rl.OnCommunityJoined},{fn:wl,action:rl.OnCommunityLeft},{fn:Zo(Cl,"targetId","community"),action:Ul.OnCommunityUpdated}])}notifyChange({origin:e,loading:t,error:n}){var r,a;const s=null===(r=Re(this.cacheKey))||void 0===r?void 0:r.data;if(!s)return;const o=this.applyFilter(null!==(a=s.data.map((e=>Re(["community","get",e]))).filter(cr).map((({data:e})=>e)))&&void 0!==a?a:[]);(this.shouldNotify(o)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:o,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){const{userId:t}=Te();let n=e;this.query.includeDeleted||(n=xe(n,"isDeleted",!1)),this.query.categoryId&&(n=n.filter((e=>{var t;return null===(t=e.categoryIds)||void 0===t?void 0:t.includes(this.query.categoryId)}))),this.query.tags&&(n=n.filter((e=>{var t;return null===(t=e.tags)||void 0===t?void 0:t.some((e=>{var t;return null===(t=this.query.tags)||void 0===t?void 0:t.includes(e)}))}))),this.query.membership&&t&&(n=Le(n,this.query.membership,t));const r=(()=>"firstCreated"===this.query.sortBy?ze:He)();return n=n.sort(r),n}}class Dl extends Rr{async getRequest(e,t){const{limit:n=$,includeDiscoverablePrivateCommunity:r}=e,a=Xt(e,["limit","includeDiscoverablePrivateCommunity"]),s=t?{token:t}:{limit:n},{data:o}=await this.http.get("/api/v3/communities/top-trending",{params:Object.assign(Object.assign({},a),{options:s,includeDiscoverablePrivateCommunity:null==r||r})});return o}}class ql extends jr{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Te(),r=n.cache&&Date.now();n.cache&&(Yt(t,{cachedAt:r}),Hc(e.communities,e.communityUsers))}appendToQueryStream(e,t,n=!1){var r,a;if(n)Me(this.cacheKey,{data:e.communities.map(ve("community"))});else{const t=null===(r=Re(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Me(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.communities.map(ve("community"))])]}))}}reactor(e){return e=>{var t;const n=null===(t=Re(this.cacheKey))||void 0===t?void 0:t.data;n&&(Me(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}var Nl;!function(e){e.OnCommunityDeleted="onCommunityDeleted",e.OnCommunityUpdated="onCommunityUpdated"}(Nl||(Nl={}));class Bl extends Br{constructor(e,t){const n=I.default(e),r=["trendingCommunity","collection",n];super(new Dl(e),n,r,t),this.query=e,this.queryStreamController=new ql(this.query,this.cacheKey,this.notifyChange.bind(this),_r),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Re(this.cacheKey))||void 0===e?void 0:e.data)||Me(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:Xc,action:Nl.OnCommunityDeleted},{fn:Zc,action:Nl.OnCommunityUpdated},{fn:yl,action:rl.OnCommunityJoined},{fn:vl,action:rl.OnCommunityLeft},{fn:ul,action:rl.OnMemberCountChanged},{fn:bl,action:rl.OnCommunityJoined},{fn:wl,action:rl.OnCommunityLeft},{fn:Zo(Cl,"targetId","community"),action:Nl.OnCommunityUpdated}])}notifyChange({origin:e,loading:t,error:n}){var r,a;const s=null===(r=Re(this.cacheKey))||void 0===r?void 0:r.data;if(!s)return;const o=null!==(a=s.data.map((e=>Re(["community","get",e]))).filter(cr).map((({data:e})=>ta(e))))&&void 0!==a?a:[];(this.shouldNotify(o)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:o,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}}class Ll extends Rr{async getRequest(e,t){const{limit:n=$,includeDiscoverablePrivateCommunity:r}=e,a=Xt(e,["limit","includeDiscoverablePrivateCommunity"]),s=t?{token:t}:{limit:n},{data:o}=await this.http.get("/api/v3/communities/recommended",{params:Object.assign(Object.assign({},a),{options:s,includeDiscoverablePrivateCommunity:null==r||r})});return o}}class Fl extends jr{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Te(),r=n.cache&&Date.now();n.cache&&(Yt(t,{cachedAt:r}),Hc(e.communities,e.communityUsers))}appendToQueryStream(e,t,n=!1){var r,a;if(n)Me(this.cacheKey,{data:e.communities.map(ve("community"))});else{const t=null===(r=Re(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Me(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.communities.map(ve("community"))])]}))}}reactor(e){return e=>{var t;const n=null===(t=Re(this.cacheKey))||void 0===t?void 0:t.data;n&&(Me(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}var Kl;!function(e){e.OnCommunityDeleted="onCommunityDeleted",e.OnCommunityUpdated="onCommunityUpdated",e.OnLocalCommunityJoin="onLocalCommunityJoin"}(Kl||(Kl={}));class $l extends Br{constructor(e,t){const n=I.default(e),r=["community","collection",n];super(new Ll(e),n,r,t),this.query=e,this.queryStreamController=new Fl(this.query,this.cacheKey,this.notifyChange.bind(this),_r),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Re(this.cacheKey))||void 0===e?void 0:e.data)||Me(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:Xc,action:Kl.OnCommunityDeleted},{fn:Zc,action:Kl.OnCommunityUpdated},{fn:yl,action:rl.OnCommunityJoined},{fn:vl,action:rl.OnCommunityLeft},{fn:ul,action:rl.OnMemberCountChanged},{fn:bl,action:rl.OnCommunityJoined},{fn:wl,action:rl.OnCommunityLeft},{fn:Zo(Cl,"targetId","community"),action:Kl.OnCommunityUpdated}])}notifyChange({origin:e,loading:t,error:n}){var r,a;const s=null===(r=Re(this.cacheKey))||void 0===r?void 0:r.data;if(!s)return;const o=null!==(a=s.data.map((e=>Re(["community","get",e]))).filter(cr).map((({data:e})=>ta(e))))&&void 0!==a?a:[];(this.shouldNotify(o)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:o,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}}class Ql extends Rr{async getRequest(e,t){var n;const{limit:r=$,communityMembershipStatus:a}=e,s=Xt(e,["limit","communityMembershipStatus"]),o={type:e.limit?"pagination":void 0},i=t?Object.assign(Object.assign({},o),{token:t}):Object.assign(Object.assign({},o),{limit:r}),{data:c}=await this.http.get("/api/v1/semantic-search/communities",{params:Object.assign(Object.assign({},s),{filter:null!=a?a:"all",options:i,includeDiscoverablePrivateCommunity:null===(n=s.includeDiscoverablePrivateCommunity)||void 0===n||n})});return c}}function zl(e){return e.communities.map((t=>{const n=e.searchResult.find((e=>e.communityId===t.communityId));return`${t.communityId}:${n}`}))}class Vl extends jr{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=this.preparePayload(e),n=Te(),r=n.cache&&Date.now();n.cache&&Yt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,a;if(n)Me(this.cacheKey,{data:zl(e)});else{const t=null===(r=Re(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Me(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...zl(e)])]}))}}reactor(e){return e=>{var t;const n=null===(t=Re(this.cacheKey))||void 0===t?void 0:t.data;n&&(n.data=[...new Set([e.communityId,...n.data])],Me(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}var Hl;!function(e){e.OnCommunityCreated="onCommunityCreated",e.OnCommunityDeleted="onCommunityDeleted",e.OnCommunityUpdated="onCommunityUpdated"}(Hl||(Hl={}));class Jl extends Br{constructor(e,t){const n=I.default(e),r=["community","collection",n];super(new Ql(e),n,r,t),this.query=e,this.queryStreamController=new Vl(this.query,this.cacheKey,this.notifyChange.bind(this),Er),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Re(this.cacheKey))||void 0===e?void 0:e.data)||Me(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:Yc,action:Hl.OnCommunityCreated},{fn:Xc,action:Hl.OnCommunityDeleted},{fn:Zc,action:Hl.OnCommunityUpdated},{fn:yl,action:rl.OnCommunityJoined},{fn:vl,action:rl.OnCommunityLeft},{fn:ul,action:rl.OnMemberCountChanged},{fn:bl,action:rl.OnCommunityJoined},{fn:wl,action:rl.OnCommunityLeft},{fn:Zo(Cl,"targetId","community"),action:Hl.OnCommunityUpdated}])}notifyChange({origin:e,loading:t,error:n}){var r,a;const s=null===(r=Re(this.cacheKey))||void 0===r?void 0:r.data;if(!s)return;const o=this.applyFilter(null!==(a=s.data.map((e=>{const[t,n]=e.split(":");return{communityId:t,score:parseFloat(n)}})).sort(((e,t)=>t.score-e.score)).map((({communityId:e})=>Re(["community","get",e]))).filter(cr).map((({data:e})=>e)))&&void 0!==a?a:[]);(this.shouldNotify(o)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:o,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){const{userId:t}=Te();let n=e;return this.query.categoryIds&&(n=n.filter((e=>{var t;return null===(t=e.categoryIds)||void 0===t?void 0:t.some((e=>!this.query.categoryIds||(0===this.query.categoryIds.length||this.query.categoryIds.includes(e))))}))),this.query.tags&&(n=n.filter((e=>{var t;return null===(t=e.tags)||void 0===t?void 0:t.some((e=>{var t;return null===(t=this.query.tags)||void 0===t?void 0:t.includes(e)}))}))),this.query.communityMembershipStatus&&t&&(n=Le(n,this.query.communityMembershipStatus,t)),n}}class Wl extends Rr{async getRequest(e,t){const{limit:n=$,communityIds:r}=e,a=Xt(e,["limit","communityIds"]),s=t?{token:t}:{limit:n},o=r.map((e=>encodeURIComponent(e))),{data:i}=await this.http.get("/api/v4/communities/join/requests",{params:Object.assign(Object.assign({},a),{options:s,communityIds:o})});return i}}var Gl;!function(e){e.OnLocalJoinRequestCreated="OnLocalJoinRequestCreated",e.OnLocalJoinRequestUpdated="OnLocalJoinRequestUpdated",e.OnLocalJoinRequestDeleted="OnLocalJoinRequestDeleted"}(Gl||(Gl={}));class Yl extends jr{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Te(),r=n.cache&&Date.now();n.cache&&Yt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,a;if(n)Me(this.cacheKey,{data:e.joinRequests.map((e=>ve("joinRequest")({joinRequestId:e._id})))});else{const t=null===(r=Re(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Me(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.joinRequests.map((e=>ve("joinRequest")({joinRequestId:e._id})))])]}))}}reactor(e){return t=>{var n;const r=null===(n=Re(this.cacheKey))||void 0===n?void 0:n.data;if(!r)return;const a=(Array.isArray(t)?t:[t]).map((e=>e.joinRequestId));if(e===Gl.OnLocalJoinRequestUpdated){if(!r.data.find((e=>a.includes(e))))return}e===Gl.OnLocalJoinRequestCreated&&(r.data=[...new Set([...a,...r.data])]),e===Gl.OnLocalJoinRequestDeleted&&(r.data=r.data.filter((e=>!a.includes(e)))),Me(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1})}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class Zl extends Br{constructor(e,t){const n=I.default(e),r=["joinRequestList","collection",n];super(new Wl(e),n,r,t),this.query=e,this.queryStreamController=new Yl(this.query,this.cacheKey,this.notifyChange.bind(this),kr),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Re(this.cacheKey))||void 0===e?void 0:e.data)||Me(this.cacheKey,{data:[],params:this.query})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){const r=e;this.queryStreamController.appendToQueryStream(r,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:Lr,action:Gl.OnLocalJoinRequestCreated},{fn:Fr,action:Gl.OnLocalJoinRequestUpdated},{fn:Kr,action:Gl.OnLocalJoinRequestUpdated},{fn:Cl,action:Gl.OnLocalJoinRequestUpdated}])}notifyChange({origin:e,loading:t,error:n}){var r;const a=null===(r=Re(this.cacheKey))||void 0===r?void 0:r.data;if(!a)return;const s=this.applyFilter(a.data.map((e=>Re(["joinRequest","get",e]))).filter(cr).map((({data:e})=>e)).map(Ar));(this.shouldNotify(s)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:s,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=e;this.query.communityIds&&this.query.communityIds.length>0&&(t=t.filter((e=>this.query.communityIds.some((t=>t===e.targetId)))));const n=(()=>"firstCreated"===this.query.sortBy?ze:He)();return t=t.sort(n),t}}var Xl;!function(e){e.ALL="all",e.MEMBER="member",e.NOT_MEMBER="notMember"}(Xl||(Xl={}));var ed=Object.freeze({__proto__:null,addRoles:async(e,t,n)=>{const r=Te();r.log("community/moderation/addRoles",e,t,n);const{data:a}=await r.http.post(`/api/v4/communities/${e}/users/roles`,{communityId:e,roles:t,userIds:n}),s=Or(a);r.cache&&Yt(s),it("local.community.roleAdded",s);const{communityUsers:o}=s;return!!o.find((n=>n.communityId===e&&t.some((e=>n.roles.includes(e)))))},removeRoles:async(e,t,n)=>{const r=Te();r.log("community/moderation/removeRoles",e,t,n);const{data:a}=await r.http.delete(`/api/v4/communities/${e}/users/roles`,{data:{communityId:e,roles:t,userIds:n}}),s=Or(a);r.cache&&Yt(s),it("local.community.roleRemoved",s);const{communityUsers:o}=s;return!!o.find((n=>n.communityId===e&&!t.some((e=>n.roles.includes(e)))))},banMembers:async(e,t)=>{const n=Te();n.log("community/banMembers",{userIds:t,communityId:e});const{data:r}=await n.http.put(`/api/v3/communities/${e}/users/ban`,{userIds:t}),a=tn(r,"communityUsers"),s=n.cache&&Date.now();n.cache&&Yt(a,{cachedAt:s});const{communityUsers:o}=a;return{data:o.filter((e=>t.includes(e.userId))),cachedAt:s}},unbanMembers:async(e,t)=>{const n=Te();n.log("community/unbanMembers",{userIds:t,communityId:e});const{data:r}=await n.http.put(`/api/v3/communities/${e}/users/unban`,{userIds:t}),a=tn(r,"communityUsers"),s=n.cache&&Date.now();n.cache&&Yt(a,{cachedAt:s});const{communityUsers:o}=a;return{data:o.filter((e=>t.includes(e.userId))),cachedAt:s}}}),td=Object.freeze({__proto__:null,Moderation:ed,Membership:Rl,getCommunityByIds:Jc,createCommunity:async e=>{const t=Te();t.log("user/createCommunity",e);const{data:n}=await t.http.post("/api/v3/communities/",Tr(e));it("community.created",n);const r=_r(n),a=t.cache&&Date.now();t.cache&&(Yt(r,{cachedAt:a}),Hc(r.communities,r.communityUsers));const{communities:s}=r;return{data:na.community(s[0]),cachedAt:a}},updateCommunity:async(e,t)=>{const n=Te();n.log("community/updateCommunity",e,t);const{data:r}=await n.http.put(`/api/v3/communities/${e}`,Tr(t));it("community.updated",r);const a=_r(r),s=n.cache&&Date.now();n.cache&&(Yt(a,{cachedAt:s}),Hc(a.communities,a.communityUsers));const{communities:o}=a;return{data:na.community(o.find((t=>t.communityId===e))),cachedAt:s}},deleteCommunity:async e=>{const t=Te();t.log("community/deleteCommunity",e),await t.http.delete(`/api/v3/communities/${e}`);const n=await Wc(e);return it("community.deleted",{communities:[n.data],categories:[],communityUsers:[],feeds:[],files:[],users:[]}),na.community(n.data)},joinCommunity:async e=>{const t=Te();t.log("community/joinCommunity",e);const{data:n}=await t.http.post(`/api/v3/communities/${e}/join`);it("local.community.joined",n);const r=_r(n),a=t.cache&&Date.now();t.cache&&Yt(r,{cachedAt:a});const{communityUsers:s}=r;return!!s.find((t=>t.communityId===e&&"member"===t.communityMembership))},leaveCommunity:async e=>{const t=Te();t.log("community/leaveCommunity",e);const{data:n}=await t.http.delete(`/api/v3/communities/${e}/leave`);it("local.community.left",n);const r=_r(n),a=t.cache&&Date.now();t.cache&&Yt(r,{cachedAt:a});const{communityUsers:s}=r;return!!s.find((t=>t.communityId===e&&"member"!==t.communityMembership))},onCommunityCreated:Yc,onCommunityUpdated:Zc,onCommunityDeleted:Xc,searchCommunities:(e,t,n)=>{const{log:r,cache:a}=Te();a||console.log(z);const s=Date.now();r(`searchCommunities(tmpid: ${s}) > listen`);const o=new Ml(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>Ue(c))),()=>{r(`searchCommunities(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}},getCommunities:(e,t,n)=>{const{log:r,cache:a}=Te();a||console.log(z);const s=Date.now();r(`getCommunities(tmpid: ${s}) > listen`);const o=new xl(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>Ue(c))),()=>{r(`getCommunities(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}},getCommunity:(e,t)=>Do(e,t,"communityId",Wc,[Zc,Xc,yl,vl,bl,wl,dl,hl,ul,Zo(Cl,"targetId","community")],{callbackDataSelector:e=>na.community(e)}),getTrendingCommunities:(e,t,n)=>{const{log:r,cache:a,userId:s}=Te();a||console.log(z);const o=Date.now();r(`getTrendingCommunities(tmpid: ${o}) > listen`);const i=new Bl(e,t),c=i.startSubscription(),l=i.getCacheKey();return c.push((()=>Ue(l))),()=>{r(`getTrendingCommunities(tmpid: ${o}) > dispose`),c.forEach((e=>e()))}},getRecommendedCommunities:(e,t,n)=>{const{log:r,cache:a,userId:s}=Te();a||console.log(z);const o=Date.now();r(`getRecommendedCommunities(tmpid: ${o}) > listen`);const i=new $l(e,t),c=i.startSubscription(),l=i.getCacheKey();return c.push((()=>Ue(l))),()=>{r(`getRecommendedCommunities(tmpid: ${o}) > dispose`),c.forEach((e=>e()))}},semanticSearchCommunities:(e,t,n)=>{const{log:r,cache:a}=Te();a||console.log(z);const s=Date.now();r(`semanticSearchCommunities(tmpid: ${s}) > listen`);const o=new Jl(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>Ue(c))),()=>{r(`semanticSearchCommunities(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}},getJoinRequestList:(e,t,n)=>{const{log:r,cache:a}=Te();a||console.log(z);const s=Date.now();r(`getJoinRequestList: (tmpid: ${s}) > listen`);const o=new Zl(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>{Ue(c)})),()=>{r(`getJoinRequestList (tmpid: ${s}) > dispose`),i.forEach((e=>e()))}},get AmityCommunityMemberStatusFilter(){return Xl}});const nd=async e=>{const t=Te();t.log("category/getCategory",e);const{data:n}=await t.http.get(`/api/v3/community-categories/${encodeURIComponent(e)}`),r=t.cache&&Date.now();t.cache&&Yt(n,{cachedAt:r});const{categories:a}=n;return{data:na.category(a.find((t=>t.categoryId===e))),cachedAt:r}};nd.locally=e=>{const t=Te();if(t.log("category/getCategory.locally",e),!t.cache)return;const n=Re(["category","get",e]);return n?{data:na.category(n.data),cachedAt:n.cachedAt}:void 0};const rd=async e=>{const t=Te();t.log("category/queryCategories",e);const n=null!=e?e:{},{page:r,limit:a,includeDeleted:s}=n,o=Xt(n,["page","limit","includeDeleted"]),i=r?{token:r}:a?{limit:a}:void 0,{data:c}=await t.http.get("/api/v3/community-categories",{params:Object.assign(Object.assign({},o),{isDeleted:vn(s),options:i})}),{paging:l}=c,d=Xt(c,["paging"]),{categories:u}=d,h=t.cache&&Date.now();if(t.cache){Yt(d,{cachedAt:h});const e=["category","query",Object.assign(Object.assign({},o),{includeDeleted:s,options:i})];Me(e,{categories:u.map(ve("category")),paging:l})}return{data:u,cachedAt:h,paging:l}};rd.locally=e=>{var t,n;const r=Te();if(r.log("category/queryCategories.locally",e),!r.cache)return;const a=null!=e?e:{},{page:s,limit:o=10}=a,i=Xt(a,["page","limit"]),c=s?{token:s}:o?{limit:o}:void 0,l=["category","query",Object.assign(Object.assign({},i),{options:c})],{data:d,cachedAt:u}=null!==(t=Re(l))&&void 0!==t?t:{};if(!(null==d?void 0:d.categories.length))return;const h=d.categories.map((e=>Re(["category","get",e]))).filter(Boolean).map((({data:e})=>e)),{paging:p}=d;return h.length===(null===(n=null==d?void 0:d.categories)||void 0===n?void 0:n.length)?{data:h,cachedAt:u,paging:p}:void 0};var ad=Object.freeze({__proto__:null,getCategory:nd,getCategories:(e,t,n)=>{const{log:r,cache:a}=Te();a||console.log(z);const s=Date.now();r(`getCategories(tmpid: ${s}) > listen`);const{limit:o}=e,i=Xt(e,["limit"]),c=null!=o?o:$,{policy:l=Q}=null!=n?n:{},d=[],u=["category","collection",{}],h=(n=!1)=>{var r,a;const s=null===(r=Re(u))||void 0===r?void 0:r.data,o=null!==(a=null==s?void 0:s.data)&&void 0!==a?a:[];if(!n&&o.length>0&&!(null==s?void 0:s.params.page))return;const d=pe(rd,Object.assign(Object.assign({},i),{limit:n?c:void 0,page:n||null==s?void 0:s.params.page}));me(d,(({data:n,error:r,loading:a,paging:s})=>{const i={loading:a,error:r,params:{page:null==s?void 0:s.next},data:o};n&&(i.data=[...new Set([...o,...n.map(ve("category"))])]),Me(u,i),(n=>{var r,a;let s=null!==(r=n.data.map((e=>Re(["category","get",e]))).filter(Boolean).map((({data:e})=>na.category(e))))&&void 0!==r?r:[];switch(e.includeDeleted||(s=xe(s,"isDeleted",!1)),e.sortBy){case"firstCreated":s=s.sort(ze);break;case"lastCreated":s=s.sort(He);break;default:s=s.sort(Qe)}t({onNextPage:h,data:s,hasNextPage:!!(null===(a=n.params)||void 0===a?void 0:a.page),loading:n.loading,error:n.error})})(i)}),fe(l))};return d.push((()=>{})),h(!0),()=>{r(`getCategories(tmpid: ${s}) > dispose`),d.forEach((e=>e()))}}});const sd=async e=>{const t=Te();t.log("feed/queryGlobalFeed",e);const n=null!=e?e:{},{queryToken:r}=n,a=Xt(n,["queryToken"]),s=(()=>{if(r)return{token:r}})(),{data:o}=await t.http.get("/api/v4/me/global-feeds",{params:Object.assign(Object.assign({},a),{options:s})}),{paging:i}=o,c=Xt(o,["paging"]),l=tn(c,"communityUsers"),{posts:d}=l,{communities:u}=_r(l),h=t.cache&&Date.now();if(t.cache){Yt(Object.assign(Object.assign({},l),{communitis:u}));const e=["globalFeed","query",Object.assign(Object.assign({},a),{options:s})];Me(e,{posts:d.map(ve("post")),paging:i})}return{data:d.map(na.post),cachedAt:h,paging:i}};sd.locally=e=>{var t,n;const r=Te();if(r.log("post/queryGlobalFeed.locally",e),!r.cache)return;const a=Xt(null!=e?e:{},[]),s=["globalFeed","query",Object.assign({},a)],{data:o,cachedAt:i}=null!==(t=Re(s))&&void 0!==t?t:{};if(!(null==o?void 0:o.posts.length))return;const c=o.posts.map((e=>Re(["post","get",e]))).filter(Boolean).map((({data:e})=>e)).map(na.post),{paging:l}=o;return c.length===(null===(n=null==o?void 0:o.posts)||void 0===n?void 0:n.length)?{data:c,cachedAt:i,paging:l}:void 0};const od=async e=>{const t=Te();t.log("feed/getCustomRankingGlobalFeed",e);const n=null!=e?e:{},{queryToken:r,limit:a}=n,s=Xt(n,["queryToken","limit"]),o=(()=>{if(r)return{token:r}})(),{data:i}=await t.http.get("/api/v5/me/global-feeds",{params:Object.assign(Object.assign({},s),{limit:r?void 0:a,options:o})}),{paging:c}=i,l=Xt(i,["paging"]),d=tn(l,"communityUsers"),{posts:u}=d,h=t.cache&&Date.now();if(t.cache){Yt(d);const e=["customGlobalFeed","query",Object.assign(Object.assign({},s),{options:o})];Me(e,{posts:u.map(ve("post")),paging:c})}return{data:u.map(na.post),cachedAt:h,paging:c}};od.locally=e=>{var t,n;const r=Te();if(r.log("post/getCustomRankingGlobalFeed.locally",e),!r.cache)return;const a=Xt(null!=e?e:{},[]),s=["customGlobalFeed","query",Object.assign({},a)],{data:o,cachedAt:i}=null!==(t=Re(s))&&void 0!==t?t:{};if(!(null==o?void 0:o.posts.length))return;const c=o.posts.map((e=>Re(["post","get",e]))).filter(Boolean).map((({data:e})=>e)),{paging:l}=o;return c.length===(null===(n=null==o?void 0:o.posts)||void 0===n?void 0:n.length)?{data:c.map(na.post),cachedAt:i,paging:l}:void 0};var id=Object.freeze({__proto__:null,queryGlobalFeed:sd,getCustomRankingGlobalFeed:od});const cd=async e=>{const t=Te();t.log("post/getPostByIds",e);const n=e.map((e=>encodeURIComponent(e)));let r;try{r=(await t.http.get("/api/v3/posts/list",{params:{postIds:n}})).data}catch(t){throw e.forEach((e=>{te(null==t?void 0:t.code)&&Zt("post",e)})),t}const a=tn(r,"communityUsers"),s=t.cache&&Date.now();return t.cache&&Yt(a,{cachedAt:s}),{data:a.posts.map(na.post),cachedAt:s}};cd.locally=e=>{var t;const n=Te();if(n.log("post/getPostByIds.locally",e),!n.cache)return;const r=e.map((e=>Re(["post","get",e]))).filter(Boolean),a=r.map((({data:e})=>e)),s=null===(t=r.sort(((e,t)=>e.cachedAt<t.cachedAt?-1:1)))||void 0===t?void 0:t[0];return(null==r?void 0:r.length)<e.length?void 0:{data:a.map(na.post),cachedAt:s.cachedAt}};const ld=async(e,t=!1)=>{var n;const r=Te(),a=await fi(e);if(await r.http.delete(`/api/v4/posts/${encodeURIComponent(e)}`,{params:{postId:e,permanent:t}}),"community"===a.data.targetType){const e=await Wc(a.data.targetId),t=(null!==(n=Ae(["communityUsers","get"]))&&void 0!==n?n:[]).filter((({key:t})=>"communityUsers"===t[0]&&("get"===t[1]&&("string"==typeof t[2]&&t[2].includes(e.data.communityId))))).map((({data:e})=>e));it("community.updated",{communities:[e.data],categories:[],communityUsers:t,feeds:[],files:[],users:[]})}const s=Object.assign(Object.assign({},a.data),{isDeleted:!0});return t?setTimeout((()=>{Zt("post",e)}),0):Pe(["post","get",e],{isDeleted:!0}),it("local.post.deleted",{posts:[s],categories:[],comments:[],communities:[],communityUsers:[],feeds:[],files:[],postChildren:[],users:[],videoStreamings:[]}),na.post(s)},dd=async e=>{const t=Te();t.log("comment/getCommentByIds",e);const n=e.map((e=>encodeURIComponent(e)));let r;try{r=(await t.http.get("/api/v3/comments/list",{params:{commentIds:n}})).data}catch(t){throw e.forEach((e=>{te(null==t?void 0:t.code)&&Zt("comment",e)})),t}const a=t.cache&&Date.now();return t.cache&&Yt(r,{cachedAt:a}),{data:r.comments.map((e=>na.comment(e))),cachedAt:a}};dd.locally=e=>{var t;const n=Te();if(n.log("comment/getCommentByIds.locally",e),!n.cache)return;const r=e.map((e=>Re(["comment","get",e]))).filter(Boolean),a=r.map((({data:e})=>e)),s=null===(t=r.sort(((e,t)=>e.cachedAt<t.cachedAt?-1:1)))||void 0===t?void 0:t[0];return(null==r?void 0:r.length)<e.length?void 0:{data:a.map((e=>na.comment(e))),cachedAt:s.cachedAt}};const ud=(e,t=!1)=>{const{stories:n}=e,r=n.map((e=>((e,t=!1)=>{const{storyId:n,referenceId:r}=e;return!t&&r?Object.assign(Object.assign({},e),{syncState:"synced"}):Object.assign(Object.assign({},e),{syncState:"synced",referenceId:n})})(e,t)));return Object.assign(Object.assign({},e),{stories:r})},hd=async e=>{const t=Te();t.log("story/getStoryByStoryId",e);const n=Re(["story-reference",e]);if(null==n?void 0:n.data){const{data:e}=n;fn("story",e)}let r;try{const n=await t.http.get(`/api/v4/stories/${e}`);r=ud(n.data)}catch(t){throw te(null==t?void 0:t.code)&&Zt("story",e),t}const a=t.cache&&Date.now();return t.cache&&Yt(r,{cachedAt:a}),{data:r.stories[0],cachedAt:a}};hd.locally=e=>{const t=Te();t.log("story/getStorybyStoryId",e);const n=Re(["story-reference",e]);if(null==n?void 0:n.data){const{data:e}=n;fn("story",e)}const r=t.cache&&Date.now(),a=Re(["story","get",e]);if(a)return{data:a.data,cachedAt:r}};const pd=async(e,t=!1)=>{var n;const r=Te(),a=await mi(e);await r.http.delete(`/api/v4/comments/${encodeURIComponent(e)}`,{params:{commentId:e,permanent:t}});const s=Object.assign(Object.assign({},a.data),{isDeleted:!0});if("story"===a.data.referenceType){const e=await hd(a.data.referenceId);it("local.story.updated",{stories:[e.data],categories:[],comments:[],communities:[],communityUsers:[],files:[],users:[]})}else{const e=null===(n=Re(["post","get",a.data.referenceId]))||void 0===n?void 0:n.data;if(e){let t;t=s.parentId?1:s.childrenNumber+1,e.commentsCount-=t,it("local.post.updated",{posts:[e],categories:[],comments:[],communities:[],communityUsers:[],feeds:[],files:[],postChildren:[],users:[],videoStreamings:[]})}}return it("local.comment.deleted",{comments:[s],commentChildren:[],files:[],users:[],communityUsers:[]}),t?nt((()=>Zt("comment",e))):Pe(["comment","get",e],{isDeleted:!0}),s},fd=async e=>{const t=Te();let n;t.log("comment/getComment",e),fn("comment",e);try{n=(await t.http.get(`/api/v3/comments/${encodeURIComponent(e)}`)).data}catch(t){throw te(null==t?void 0:t.code)&&Zt("comment",e),t}const r=t.cache&&Date.now();t.cache&&Yt(n,{cachedAt:r});const{comments:a}=n;return{data:a.find((t=>t.commentId===e)),cachedAt:r}};fd.locally=e=>{const t=Te();if(t.log("comment/getComment.locally",e),!t.cache)return;const n=Re(["comment","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const md=e=>qi("local.comment.deleted",e),gd=e=>{const t=Te();return ot(t,"local.comment.addReaction","local.comment.addReaction",(({comment:n})=>{t.cache?(Pe(["comment","get",n.commentId],n),e(lr(n))):e(n)}))},yd=e=>{const t=Te();return ot(t,"local.comment.removeReaction","local.comment.removeReaction",(({comment:n})=>{t.cache?(Pe(["comment","get",n.commentId],n),e(lr(n))):e(n)}))};class vd extends Rr{async getRequest(e,t){const{limit:n=$,includeDeleted:r}=e,a=Xt(e,["limit","includeDeleted"]),s={type:a.sortBy||e.limit?"pagination":void 0},o=t?Object.assign(Object.assign({},s),{token:t}):Object.assign(Object.assign({},s),{limit:n}),{data:i}=await this.http.get("/api/v3/comments",{params:Object.assign(Object.assign({},a),{isDeleted:vn(r),options:o})});return i}}var bd;!function(e){e.OnCommentCreated="onCommentCreated",e.OnCommentUpdated="onCommentUpdated",e.OnCommentDeleted="onCommentDeleted",e.OnCommentFlagged="onCommentFlagged",e.OnCommentUnflagged="onCommentUnflagged",e.OnCommentReactionAdded="onCommentReactionAdded",e.OnCommentReactionRemoved="onCommentReactionRemoved"}(bd||(bd={}));class wd extends jr{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Te(),r=n.cache&&Date.now();n.cache&&Yt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,a;if(n)Me(this.cacheKey,{data:e.comments.map(ve("comment"))});else{const t=null===(r=Re(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Me(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.comments.map(ve("comment"))])]}))}}reactor(e){return t=>{var n;const r=null===(n=Re(this.cacheKey))||void 0===n?void 0:n.data;this.query.referenceId===t.referenceId&&this.query.referenceType===t.referenceType&&r&&(this.query.parentId&&this.query.parentId!==t.parentId||!this.query.parentId&&t.parentId||(e===bd.OnCommentCreated&&(r.data=[...new Set([t.commentId,...r.data])]),Me(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1})))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const Cd=e=>qi("local.comment.created",e);class Id extends Br{constructor(e,t){const n=I.default(e),r=["comments","collection",n];super(new vd(e),n,r,t),this.query=e,this.queryStreamController=new wd(this.query,this.cacheKey,this.notifyChange.bind(this),Yi),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Re(this.cacheKey))||void 0===e?void 0:e.data)||Me(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:Cd,action:bd.OnCommentCreated},{fn:md,action:bd.OnCommentDeleted},{fn:Ni,action:bd.OnCommentCreated},{fn:Bi,action:bd.OnCommentUpdated},{fn:Li,action:bd.OnCommentDeleted},{fn:Fi,action:bd.OnCommentFlagged},{fn:Ki,action:bd.OnCommentUnflagged},{fn:$i,action:bd.OnCommentReactionAdded},{fn:Qi,action:bd.OnCommentReactionRemoved},{fn:gd,action:bd.OnCommentReactionAdded},{fn:yd,action:bd.OnCommentReactionRemoved}])}notifyChange({origin:e,loading:t,error:n}){var r,a;const s=null===(r=Re(this.cacheKey))||void 0===r?void 0:r.data;if(!s)return;const o=this.applyFilter(null!==(a=s.data.map((e=>Re(["comment","get",e]))).filter(cr).map((({data:e})=>e)))&&void 0!==a?a:[]).map(na.comment);(this.shouldNotify(o)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:o,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=e;if(this.query.includeDeleted||(t=xe(t,"isDeleted",!1)),this.query.parentId&&(t=t.filter((e=>e.parentId===this.query.parentId))),"boolean"==typeof this.query.hasFlag&&(t=this.query.hasFlag?t.filter((e=>null!=e.hashFlag)):t.filter((e=>null==e.hashFlag))),this.query.dataTypes&&("exact"===this.query.dataTypes.matchType&&(t=t.filter((e=>{var t,n;const r=(null===(t=this.query.dataTypes)||void 0===t?void 0:t.values.sort())||[],a=(null===(n=e.dataTypes)||void 0===n?void 0:n.sort())||[];return a.length===r.length&&r.every(((e,t)=>e===a[t]))}))),"any"===this.query.dataTypes.matchType&&(t=t.filter((e=>{var t;return null===(t=this.query.dataTypes)||void 0===t?void 0:t.values.some((t=>{var n;return null===(n=e.dataTypes)||void 0===n?void 0:n.includes(t)}))})))),"firstCreated"===this.query.sortBy)t=t.sort(ze);else t=t.sort(He);return t}}var Sd=Object.freeze({__proto__:null,getCommentByIds:dd,createComment:async e=>{var t;const n=Te();n.log("comment/createComment",e);const{data:r}=await n.http.post("/api/v3/comments",e),{comments:a}=r;if(0===a.length)throw new Error("Comment not created");const s=n.cache&&Date.now();if(n.cache&&Yt(r,{cachedAt:s}),["post","content"].includes(e.referenceType)){const n=null===(t=Re(["post","get",e.referenceId]))||void 0===t?void 0:t.data;n&&(n.commentsCount+=1,it("local.post.updated",{posts:[n],categories:[],comments:[],communities:[],communityUsers:r.communityUsers,feeds:[],files:r.files,postChildren:[],users:r.users,videoStreamings:[]}))}else if("story"===e.referenceType){const t=Re(["story-reference",e.referenceId]);if(null==t?void 0:t.data){const e=Re(["story","get",t.data]);(null==e?void 0:e.data)&&it("story.updated",{stories:[Object.assign(Object.assign({},e.data),{commentsCount:e.data.commentsCount+1,comments:[...new Set([...e.data.comments,a[0].commentId])]})],categories:[],comments:a,communities:[],communityUsers:r.communityUsers,files:r.files,users:r.users})}}return it("local.comment.created",r),{data:na.comment(a[0]),cachedAt:s}},updateComment:async(e,t)=>{const n=Te();n.log("user/updateComment",t);const{data:r}=await n.http.put(`/api/v3/comments/${encodeURIComponent(e)}`,t),a=n.cache&&Date.now();n.cache&&Yt(r,{cachedAt:a}),it("comment.updated",r);const{comments:s}=r;return{data:na.comment(s.find((t=>t.commentId===e))),cachedAt:a}},deleteComment:pd,softDeleteComment:async e=>{Te().log("comment/softDeleteComment",e);return pd(e)},hardDeleteComment:async e=>{Te().log("comment/hardDeleteComment",e);return pd(e,!0)},flagComment:async(t,n)=>{const r=Te();r.log("comment/flagComment",t);const a=n&&Object.entries(e.ContentFlagReasonEnum).some((([t,r])=>t!==e.ContentFlagReasonEnum.Others&&r===n)),s={reason:n&&a?n:e.ContentFlagReasonEnum.Others,detail:n&&!a?n:""},{data:o}=await r.http.post(`/api/v3/comments/${encodeURIComponent(t)}/flag`,s);return r.cache&&Yt(o),it("comment.flagged",o),!!o},unflagComment:async e=>{const t=Te();t.log("comment/unflagComment",e);const{data:n}=await t.http.delete(`/api/v3/comments/${encodeURIComponent(e)}/unflag`);return t.cache&&Yt(n),it("comment.unflagged",n),!!n},isCommentFlaggedByMe:async e=>{const t=Te();t.log("comment/isCommentFlaggedByMe",e);const{data:{result:n}}=await t.http.get(`/api/v3/comments/${e}/isflagbyme`);return n},onCommentCreated:Ni,onCommentUpdated:Bi,onCommentDeleted:Li,onCommentFlagged:Fi,onCommentUnflagged:Ki,onCommentReactionAdded:$i,onCommentReactionRemoved:Qi,getComment:(e,t)=>Do(e,t,"commentId",fd,[md,Li,Fi,$i,Qi,Ki,Bi,gd,yd]),getComments:(e,t,n)=>{const{log:r,cache:a}=Te();a||console.log("For using Live Collection feature you need to enable Cache!");const s=Date.now();r(`getComments(tmpid: ${s}) > listen`);const o=new Id(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>Ue(c))),()=>{r(`getComments(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}}});const _d=e=>Oi("local.post.updated",e),kd=e=>{const t=Te();return ot(t,"local.post.addReaction","local.post.addReaction",(({post:n})=>{t.cache?(Pe(["post","get",n.postId],n),e(n)):e(n)}))},Od=e=>{const t=Te();return ot(t,"local.post.removeReaction","local.post.removeReaction",(({post:n})=>{t.cache?(Pe(["post","get",n.postId],n),e(n)):e(n)}))},Td=e=>Oi("local.post.deleted",e);class Ed extends Rr{async getRequest(e,t){const{limit:n=$,includeDeleted:r,matchingOnlyParentPost:a}=e,s=Xt(e,["limit","includeDeleted","matchingOnlyParentPost"]),{dataTypes:o}=s,i={type:s.sortBy||e.limit?"pagination":void 0},c=t?Object.assign(Object.assign({},i),{token:t}):Object.assign(Object.assign({},i),{limit:n}),{data:l}=await this.http.get("/api/v4/posts",{params:Object.assign(Object.assign({},s),{isDeleted:vn(r),matchingOnlyParentPost:null!=a?a:!(null==o?void 0:o.length),options:c})});return l}}var Ad;!function(e){e.OnPostCreated="onPostCreated",e.OnPostUpdated="onPostUpdated",e.OnPostDeleted="onPostDeleted",e.OnPostFlagged="onPostFlagged",e.OnPostUnflagged="onPostUnflagged",e.OnPostReactionAdded="onPostReactionAdded",e.OnPostReactionRemoved="onPostReactionRemoved",e.OnPostApproved="onPostApproved",e.OnPostDeclined="onPostDeclined"}(Ad||(Ad={}));class Rd extends jr{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Te(),r=n.cache&&Date.now();n.cache&&Yt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,a;if(n)Me(this.cacheKey,{data:e.posts.map(ve("post"))});else{const t=null===(r=Re(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Me(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.posts.map(ve("post"))])]}))}}reactor(e){return t=>{var n,r;const a=null===(n=Re(this.cacheKey))||void 0===n?void 0:n.data;if(a){if(t.parentPostId&&t.isDeleted){const e=null===(r=Re(["post","get",t.parentPostId]))||void 0===r?void 0:r.data;if(!e||(null==e?void 0:e.targetId)!==this.query.targetId)return;e.children=e.children.filter((e=>e!==t.postId)),Me(["post","get",e.postId],e)}else{if(this.query.targetId!==t.targetId)return;if(this.query.targetType!==t.targetType)return}e===Ad.OnPostDeclined&&(a.data=a.data.filter((e=>e!==t.postId))),e!==Ad.OnPostCreated&&e!==Ad.OnPostApproved||(a.data=[...new Set([t.postId,...a.data])]),Me(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}const Md=async e=>{const t=Te();let n;t.log("post/getPost",e),fn("post",e);try{n=(await t.http.get(`/api/v3/posts/${encodeURIComponent(e)}`)).data}catch(t){throw te(null==t?void 0:t.code)&&Zt("post",e),t}const r=tn(n,"communityUsers"),a=t.cache&&Date.now();t.cache&&Yt(r,{cachedAt:a});const{posts:s}=r;return{data:s.find((t=>t.postId===e)),cachedAt:a}};Md.locally=e=>{const t=Te();if(t.log("post/getPost.locally",e),!t.cache)return;const n=Re(["post","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};class jd extends Br{constructor(e,t){const n=I.default(e),r=["posts","collection",n];super(new Ed(e),n,r,t),this.query=e,this.queryStreamController=new Rd(this.query,this.cacheKey,this.notifyChange.bind(this),Si),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Re(this.cacheKey))||void 0===e?void 0:e.data)||Me(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:Ti,action:Ad.OnPostCreated},{fn:Ei,action:Ad.OnPostUpdated},{fn:_d,action:Ad.OnPostUpdated},{fn:Ai,action:Ad.OnPostDeleted},{fn:ji,action:Ad.OnPostFlagged},{fn:Pi,action:Ad.OnPostUnflagged},{fn:Ri,action:Ad.OnPostApproved},{fn:Mi,action:Ad.OnPostDeclined},{fn:Ui,action:Ad.OnPostReactionAdded},{fn:xi,action:Ad.OnPostReactionRemoved},{fn:kd,action:Ad.OnPostReactionAdded},{fn:Od,action:Ad.OnPostReactionRemoved},{fn:Td,action:Ad.OnPostDeleted},{fn:Zo((e=>Ni((async t=>{var n;const r=null===(n=Re(this.cacheKey))||void 0===n?void 0:n.data;r&&!r.data.includes(t.referenceId)&&(await Md(t.referenceId),e(t))}))),"referenceId","post"),action:Ad.OnPostUpdated},{fn:Zo((e=>Li((async t=>{var n;const r=null===(n=Re(this.cacheKey))||void 0===n?void 0:n.data;r&&!r.data.includes(t.referenceId)&&(await Md(t.referenceId),e(t))}))),"referenceId","post"),action:Ad.OnPostUpdated}])}notifyChange({origin:e,loading:t,error:n}){var r,a;const s=null===(r=Re(this.cacheKey))||void 0===r?void 0:r.data;if(!s)return;const o=this.applyFilter(null!==(a=s.data.map((e=>Re(["post","get",e]))).filter(cr).map((({data:e})=>e)))&&void 0!==a?a:[]).map(na.post);(this.shouldNotify(o)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:o,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){var t;let n=e;if(this.query.includeDeleted||(n=xe(n,"isDeleted",!1)),this.query.tags&&(n=n.filter((e=>{var t;return null===(t=e.tags)||void 0===t?void 0:t.some((e=>{var t;return null===(t=this.query.tags)||void 0===t?void 0:t.includes(e)}))}))),"community"===this.query.targetType&&this.query.feedType&&(n=Be(n,this.query.feedType)),(null===(t=this.query.dataTypes)||void 0===t?void 0:t.length)&&(n=Fe(n,this.query.dataTypes)),"firstCreated"===this.query.sortBy)n=n.sort(ze);else n=n.sort(He);return n}}class Pd extends Rr{async getRequest(e,t){const n=Xt(e,["limit"]),{communityId:r,placement:a}=n,s=a?`/api/v1/pinned-posts/communities/${r}/${a}`:`/api/v1/pinned-posts/communities/${r}`,{data:o}=await this.http.get(s);return o}}class Ud extends jr{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=Te(),n=t.cache&&Date.now();if(t.cache){const t=Object.assign(Object.assign({},e),{users:e.users?e.users.map(En):[]});Yt(t,{cachedAt:n})}}appendToQueryStream(e,t,n=!1){var r,a;if(n)Me(this.cacheKey,{data:e.pins.map(ve("pin"))});else{const t=null===(r=Re(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Me(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.pins.map(ve("pin"))])]})),this.notifyChange({origin:"server",loading:!1})}}}class xd extends Br{constructor(e,t){const n=I.default(e),r=["pinnedPosts","collection",n];super(new Pd(e),n,r,t),this.query=e,this.queryStreamController=new Ud(this.query,this.cacheKey,this.notifyChange.bind(this),(e=>e)),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Re(this.cacheKey))||void 0===e?void 0:e.data)||Me(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return[]}notifyChange({origin:e,loading:t,error:n}){var r,a;const s=null===(r=Re(this.cacheKey))||void 0===r?void 0:r.data;if(!s)return;let o=(null!==(a=s.data.map((e=>Re(["pin","get",e]))).filter(cr).map((({data:e})=>e)))&&void 0!==a?a:[]).map(na.pinnedPost);o=this.applyFilter(o),(this.shouldNotify(o)||"event"!==e)&&this.callback({data:o,loading:t,error:n})}applyFilter(e){let t=e;if("lastCreated"===this.query.sortBy)t=t.sort((({post:e},{post:t})=>He({createdAt:null==e?void 0:e.createdAt},{createdAt:null==t?void 0:t.createdAt})));return t}}class Dd extends Rr{async getRequest(e,t){Xt(e,["limit"]);const{data:n}=await this.http.get("/api/v1/pinned-posts/global");return n}}class qd extends jr{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=Te(),n=t.cache&&Date.now();if(t.cache){const t=Object.assign(Object.assign({},e),{users:e.users.map(En)});Yt(t,{cachedAt:n})}}appendToQueryStream(e,t,n=!1){var r,a;if(n)Me(this.cacheKey,{data:e.pins.map(ve("pin"))});else{const t=null===(r=Re(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Me(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.pins.map(ve("pin"))])]})),this.notifyChange({origin:"server",loading:!1})}}reactor(e){return t=>{var n;const r=null===(n=Re(this.cacheKey))||void 0===n?void 0:n.data;r&&(e===Ad.OnPostDeleted&&(r.data=r.data.filter((e=>e!==`global#${t.postId}`))),Me(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1}))}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class Nd extends Br{constructor(e,t){const n=I.default(e),r=["pinnedPosts","collection",n];super(new Dd(e),n,r,t),this.query=e,this.queryStreamController=new qd(this.query,this.cacheKey,this.notifyChange.bind(this),(e=>e)),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Re(this.cacheKey))||void 0===e?void 0:e.data)||Me(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:Td,action:Ad.OnPostDeleted},{fn:Ai,action:Ad.OnPostDeleted}])}notifyChange({origin:e,loading:t,error:n}){var r,a;const s=null===(r=Re(this.cacheKey))||void 0===r?void 0:r.data;if(!s)return;const o=(null!==(a=s.data.map((e=>Re(["pin","get",e]))).filter(cr).map((({data:e})=>e)))&&void 0!==a?a:[]).map(na.pinnedPost);(this.shouldNotify(o)||"event"!==e)&&this.callback({data:o,loading:t,error:n})}}class Bd extends Rr{async getRequest(e,t){const{limit:n=$}=e,r=Xt(e,["limit"]),a={type:e.limit?"pagination":void 0},s=t?Object.assign(Object.assign({},a),{token:t}):Object.assign(Object.assign({},a),{limit:n}),{data:o}=await this.http.get("/api/v1/semantic-search/posts",{params:Object.assign(Object.assign({},r),{options:s})});return o}}function Ld(e){return e.posts.map((t=>{const n=e.searchResult.find((e=>e.postId===t.postId));return`${t.postId}:${n.score}`}))}function Fd(e){return(null!=e?e:[]).map((e=>e.split(":")[0]))}class Kd extends jr{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=this.preparePayload(e),n=Te(),r=n.cache&&Date.now();n.cache&&Yt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,a;if(n)Me(this.cacheKey,{data:Ld(e)});else{const t=null===(r=Re(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Me(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...Ld(e)])]}))}}reactor(e){return t=>{var n,r;const a=null===(n=Re(this.cacheKey))||void 0===n?void 0:n.data;if(a){if(t.parentPostId&&t.isDeleted){const e=null===(r=Re(["post","get",t.parentPostId]))||void 0===r?void 0:r.data;if(!e||(null==e?void 0:e.targetId)!==this.query.targetId)return;e.children=e.children.filter((e=>e!==t.postId)),Me(["post","get",e.postId],e)}else{if(this.query.targetId!==t.targetId)return;if(this.query.targetType!==t.targetType)return}e===Ad.OnPostDeclined&&(a.data=a.data.filter((e=>e!==t.postId))),e!==Ad.OnPostCreated&&e!==Ad.OnPostApproved||(a.data=[...new Set([t.postId,...a.data])]),Me(this.cacheKey,a),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class $d extends Br{constructor(e,t){const n=Object.assign(Object.assign({},e),{matchingOnlyParentPost:null==e.matchingOnlyParentPost||e.matchingOnlyParentPost,dataTypes:null==e.dataTypes?["text","image"]:e.dataTypes}),r=I.default(n),a=["posts","collection",r];super(new Bd(n),r,a,t),this.query=n,this.queryStreamController=new Kd(this.query,this.cacheKey,this.notifyChange.bind(this),_i),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Re(this.cacheKey))||void 0===e?void 0:e.data)||Me(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:Ei,action:Ad.OnPostUpdated},{fn:Ai,action:Ad.OnPostDeleted},{fn:ji,action:Ad.OnPostFlagged},{fn:Pi,action:Ad.OnPostUnflagged},{fn:Ri,action:Ad.OnPostApproved},{fn:Mi,action:Ad.OnPostDeclined},{fn:Ui,action:Ad.OnPostReactionAdded},{fn:xi,action:Ad.OnPostReactionRemoved},{fn:Zo((e=>Ni((async t=>{const n=Re(this.cacheKey);Fd(null==n?void 0:n.data).includes(t.referenceId)||(await fi(t.referenceId),e(t))}))),"referenceId","post"),action:Ad.OnPostUpdated},{fn:Zo((e=>Li((async t=>{const n=Re(this.cacheKey);Fd(null==n?void 0:n.data).includes(t.referenceId)||(await fi(t.referenceId),e(t))}))),"referenceId","post"),action:Ad.OnPostUpdated}])}notifyChange({origin:e,loading:t,error:n}){var r,a;const s=null===(r=Re(this.cacheKey))||void 0===r?void 0:r.data;if(!s)return;const o=this.applyFilter(null!==(a=s.data.map((e=>{const[t,n]=e.split(":");return{postId:t,score:parseFloat(n)}})).sort(((e,t)=>t.score-e.score)).map((({postId:e})=>Re(["post","get",e]))).filter(cr).map((({data:e})=>e)))&&void 0!==a?a:[]).map(na.post);(this.shouldNotify(o)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:o,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=e;return this.query.targetType&&(t=t.filter((e=>e.targetType===this.query.targetType))),this.query.targetId&&(t=t.filter((e=>e.targetId===this.query.targetId))),this.query.dataTypes&&this.query.dataTypes.length>0&&(t=Fe(t,this.query.dataTypes)),t}}var Qd=Object.freeze({__proto__:null,getPostByIds:cd,createPost:async e=>{const t=Te();t.log("post/createPost",e),e.dataType&&!["text","image","file","video"].includes(e.dataType)||delete e.dataType;const{data:n}=await t.http.post("/api/v4/posts",e);it("post.created",n);const r=tn(n,"communityUsers"),a=t.cache&&Date.now();t.cache&&Yt(r,{cachedAt:a});const{posts:s}=r;return{data:na.post(s[0]),cachedAt:a}},editPost:async(e,t)=>{const n=Te();n.log("user/editPost",t);const{data:r}=await n.http.put(`/api/v4/posts/${encodeURIComponent(e)}`,t),a=tn(r,"communityUsers"),s=n.cache&&Date.now();n.cache&&Yt(a,{cachedAt:s}),it("local.post.updated",a);const{posts:o}=a;return{data:na.post(o.find((t=>t.postId===e))),cachedAt:s}},deletePost:ld,softDeletePost:async e=>{Te().log("post/softDeletePost",e);const t=await ld(e,!1);return na.post(t)},hardDeletePost:async e=>{Te().log("post/hardDeletePost",e);const t=await ld(e,!0);return na.post(t)},approvePost:async e=>{const t=Te();t.log("post/approvePost",e);const{data:n}=await t.http.post(`/api/v3/posts/${encodeURIComponent(e)}/approve`);it("post.approved",n),"community"===n.posts[0].targetType&&it("community.updated",n);const r=tn(n,"communityUsers"),a=t.cache&&Date.now();return t.cache&&Yt(r,{cachedAt:a}),{data:na.post(r.posts.find((t=>t.postId===e))),cachedAt:a}},declinePost:async e=>{const t=Te();t.log("post/declinePost",e);const{data:n}=await t.http.post(`/api/v3/posts/${encodeURIComponent(e)}/decline`);"community"===n.posts[0].targetType&&it("community.updated",n),it("post.declined",n);const r=tn(n,"communityUsers"),a=t.cache&&Date.now();return t.cache&&Yt(r,{cachedAt:a}),{data:na.post(n.posts.find((t=>t.postId===e))),cachedAt:a}},flagPost:async(t,n)=>{const r=Te();r.log("post/flagPost",t);const a=n&&Object.entries(e.ContentFlagReasonEnum).some((([t,r])=>t!==e.ContentFlagReasonEnum.Others&&r===n)),s={reason:n&&a?n:e.ContentFlagReasonEnum.Others,detail:n&&!a?n:""},{data:o}=await r.http.post(`/api/v3/posts/${encodeURIComponent(t)}/flag`,s);return r.cache&&Yt(tn(o,"communityUsers")),it("post.flagged",o),!!o},unflagPost:async e=>{const t=Te();t.log("post/unflagPost",e);const{data:n}=await t.http.delete(`/api/v3/posts/${encodeURIComponent(e)}/unflag`);return t.cache&&Yt(tn(n,"communityUsers")),it("post.unflagged",n),!!n},isPostFlaggedByMe:async e=>{const t=Te();t.log("post/isPostFlaggedByMe",e);const{data:{result:n}}=await t.http.get(`/api/v3/posts/${e}/isflagbyme`);return n},onPostCreated:Ti,onPostUpdated:Ei,onPostDeleted:Ai,onPostApproved:Ri,onPostDeclined:Mi,onPostFlagged:ji,onPostUnflagged:Pi,onPostReactionAdded:Ui,onPostReactionRemoved:xi,getPost:(e,t)=>Do(e,(e=>{const{data:n}=e;t(Object.assign(Object.assign({},e),{data:n?na.post(e.data):n}))}),"postId",fi,[Ri,Mi,kd,Od,t=>Ai((n=>{var r;let a=n;if(n.parentPostId===e&&n.isDeleted){const e=null===(r=Re(["post","get",n.parentPostId]))||void 0===r?void 0:r.data;e&&(e.children=e.children.filter((e=>e!==n.postId)),Me(["post","get",e.postId],e),a=e)}t(a)})),ji,e=>Ui((t=>{e(t)})),e=>xi((t=>{e(t)})),Pi,Ei,_d,Td,Zo((t=>Ni((async n=>{n.referenceId===e&&(await fi(e),t(n))}))),"referenceId","post"),Zo((t=>Li((async n=>{n.referenceId===e&&(await fi(e),t(n))}))),"referenceId","post")]),getPosts:(e,t,n)=>{const{log:r,cache:a}=Te();a||console.log(z);const s=Date.now();r(`getPosts(tmpid: ${s}) > listen`);const o=new jd(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>Ue(c))),()=>{r(`getPosts(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}},getPinnedPosts:(e,t,n)=>{const{log:r,cache:a}=Te();a||console.log(z);const s=Date.now();r(`getPinnedPosts(tmpid: ${s}) > listen`);const o=new xd(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>Ue(c))),()=>{r(`getPinnedPosts(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}},getGlobalPinnedPosts:(e,t,n)=>{const{log:r,cache:a}=Te(),s=Date.now();r(`getGlobalPinnedPosts(tmpid: ${s}) > listen`);const o=new Nd(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>Ue(c))),()=>{r(`getGlobalPinnedPosts(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}},semanticSearchPosts:(e,t,n)=>{const{log:r,cache:a}=Te();a||console.log(z);const s=Date.now();r(`semanticSearchPosts(tmpid: ${s}) > listen`);const o=new $d(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>Ue(c))),()=>{r(`semanticSearchPosts(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}}});const zd=async e=>{const t=Te();t.log("stream/getStream",e);const{data:n}=await t.http.get(`/api/v3/video-streaming/${e}`),r=t.cache&&Date.now();t.cache&&Yt(n,{cachedAt:r});const{videoStreamings:a}=n;return{data:a.find((t=>t.streamId===e)),cachedAt:r}};zd.locally=e=>{const t=Te();if(t.log("stream/getStream",e),!t.cache)return;const n=Re(["stream","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const Vd=e=>{const t=Te();return ot(t,"stream/onStreamStarted","video-streaming.didStart",(t=>{Yt(t),e(t.videoStreamings[0])}))},Hd=e=>{const t=Te();return ot(t,"stream/onStreamStropped","video-streaming.didStop",(t=>{Yt(t),e(t.videoStreamings[0])}))},Jd=e=>{const t=Te();return ot(t,"stream/onStreamRecorded","video-streaming.didRecord",(t=>{Yt(t),e(t.videoStreamings[0])}))},Wd=e=>{const t=Te();return ot(t,"stream/onStreamFlagged","video-streaming.didFlag",(t=>{Yt(t),e(t.videoStreamings[0])}))},Gd=e=>{const t=Te();return ot(t,"stream/onStreamTerminated","video-streaming.didTerminate",(t=>{Yt(t),e(t.videoStreamings[0])}))},Yd=(e,t)=>Do(e,(e=>{const{data:n}=e;t(Object.assign(Object.assign({},e),{data:n?na.stream(e.data):n}))}),"streamId",zd,[Jd,Vd,Hd,Wd,Gd]);Yd.locally=e=>{const t=Te();if(t.log("stream/getStreamById",e),!t.cache)return;const n=Re(["stream","get",e]);return n?{data:na.stream(n.data),cachedAt:n.cachedAt}:void 0};const Zd=async e=>{const t=Te();t.log("stream/queryStreams",e);const n=null!=e?e:{},{page:r,limit:a}=n,s=Xt(n,["page","limit"]),o=r?{token:r}:a?{limit:a}:void 0,{data:i}=await t.http.get("/api/v3/video-streaming",{params:Object.assign(Object.assign({},s),{options:o})}),{paging:c,results:l}=i,{videoStreamings:d}=l,u=t.cache&&Date.now();return t.cache&&Yt(l,{cachedAt:u}),{data:d,cachedAt:u,paging:c}};var Xd=Object.freeze({__proto__:null,createStream:async e=>{const t=Te();t.log("stream/createStream",e);const{data:n}=await t.http.post("/api/v3/video-streaming",e),r=t.cache&&Date.now();t.cache&&Yt(n,{cachedAt:r});const{videoStreamings:a}=n;return{data:na.stream(a[0]),cachedAt:r}},updateStream:async(e,t)=>{const n=Te();n.log("stream/updateStream",e,t);const{data:r}=await n.http.put(`/api/v3/video-streaming/${e}`,t),a=n.cache&&Date.now();n.cache&&Yt(r,{cachedAt:a});const{videoStreamings:s}=r;return{data:na.stream(s.find((t=>t.streamId===e))),cachedAt:a}},deleteStream:async e=>{const t=Te();t.log("stream/deleteStream",e);const n=await zd(e),{data:r}=await t.http.delete(`/api/v3/video-streaming/${e}`),{success:a}=r,s=Object.assign(Object.assign({},n.data),{isDeleted:!0});return Pe(["stream","get",e],s),a},disposeStream:async e=>{const t=Te();t.log("stream/disposeStream",e);const{data:n}=await t.http.delete(`/api/v3/video-streaming/${e}/streaming-url`),r=t.cache&&Date.now();t.cache&&Yt(n,{cachedAt:r});const{videoStreamings:a}=n;return{data:a.find((t=>t.streamId===e)),cachedAt:r}},onStreamStarted:Vd,onStreamStopped:Hd,onStreamRecorded:Jd,onStreamFlagged:Wd,onStreamTerminated:Gd,getStreamById:Yd,getStreams:(e,t,n)=>{const{log:r,cache:a}=Te();a||console.log(z);const s=Date.now();r(`getStreams(tmpid: ${s}) > listen`);const{limit:o}=e,i=Xt(e,["limit"]),c=null!=o?o:$,{policy:l=Q}=null!=n?n:{},d=[],u=["streams","collection",e],h=t=>{let n=xe(t,"isDeleted",e.isDeleted);return n=n.sort("lastCreated"===e.sortBy?He:ze),n},p=(e,n=!1)=>{var r,a;const s=null!==(r=e.data.map((e=>Re(["stream","get",e]))).filter(Boolean).map((({data:e})=>e)))&&void 0!==r?r:[];t({onNextPage:m,data:n?h(s):s,hasNextPage:!!(null===(a=e.params)||void 0===a?void 0:a.page),loading:e.loading,error:e.error})},f=e=>e=>{var t;const n=null===(t=Re(u))||void 0===t?void 0:t.data;n&&(n.data=[...new Set([e.streamId,...n.data])],Me(u,n),p(n,!0))},m=(e=!1)=>{var t,n;const r=null===(t=Re(u))||void 0===t?void 0:t.data,a=null!==(n=null==r?void 0:r.data)&&void 0!==n?n:[];if(!e&&a.length>0&&!(null==r?void 0:r.params.page))return;const s=pe(Zd,Object.assign(Object.assign({},i),{limit:e?c:void 0,page:e||null==r?void 0:r.params.page}));me(s,(({data:e,error:t,loading:n,paging:r})=>{const s={loading:n,error:t,params:{page:null==r?void 0:r.next},data:a};e&&(s.data=[...new Set([...a,...e.map(ve("stream"))])]),Me(u,s),p(s)}),fe(l))};return d.push(Jd(f()),Vd(f()),Hd(f())),m(!0),()=>{r(`getStreams(tmpid: ${s}) > dispose`),d.forEach((e=>e()))}}});const eu=async e=>{const t=Te();t.log("poll/getPoll",e);const{data:n}=await t.http.get(`/api/v3/polls/${e}`),r=t.cache&&Date.now();t.cache&&Yt(n,{cachedAt:r});const{polls:a}=n;return{data:a.find((t=>t.pollId===e)),cachedAt:r}};eu.locally=e=>{const t=Te();if(t.log("poll/getPoll",e),!t.cache)return;const n=Re(["poll","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const tu=e=>{const t=Te();return ot(t,"poll/onPollUpdated","poll.updated",(n=>{t.cache&&Yt(n),e(n.polls[0])}))},nu=e=>{const t=Te();return ot(t,"poll/onPollDeleted","poll.deleted",(n=>{t.cache&&Yt(n),e(n.polls[0])}))};var ru=Object.freeze({__proto__:null,createPoll:async e=>{const t=Te();t.log("post/createPoll",e);const{data:n}=await t.http.post("/api/v3/polls",e),r=t.cache&&Date.now();t.cache&&Yt(n,{cachedAt:r});const{polls:a}=n;return{data:a[0],cachedAt:r}},closePoll:async e=>{const t=Te();t.log("user/closePoll",e);const{data:n}=await t.http.put(`/api/v3/polls/${encodeURIComponent(e)}`,{status:"closed"}),r=t.cache&&Date.now();t.cache&&Yt(n,{cachedAt:r}),it("poll.updated",n);const{polls:a}=n;return{data:a.find((t=>t.pollId===e)),cachedAt:r}},deletePoll:async e=>{const t=Te();t.log("poll/deletePoll",e);const n=await eu(e),{data:r}=await t.http.delete(`/api/v3/polls/${e}`),{success:a}=r,s=Object.assign(Object.assign({},n.data),{isDeleted:!0});return Pe(["poll","get",e],s),it("poll.deleted",{polls:[s],users:[]}),a},votePoll:async(e,t)=>{const n=Te();n.log("user/votePoll",e);const{data:r}=await n.http.post(`/api/v3/polls/${encodeURIComponent(e)}/votes`,{pollId:e,answerIds:t}),a=n.cache&&Date.now();n.cache&&Yt(r,{cachedAt:a});const{polls:s}=r;return it("poll.updated",r),{data:s.find((t=>t.pollId===e)),cachedAt:a}},onPollUpdated:tu,onPollDeleted:nu,getPoll:(e,t)=>Do(e,t,"pollId",eu,[tu,nu])});const au={name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};function su(e){const n=new Uint8Array(e);let r="";return n.forEach((e=>{r+=String.fromCharCode(e)})),t.btoa(r)}function ou(e){const n=e.substring("-----BEGIN PRIVATE KEY-----".length,e.length-"-----END PRIVATE KEY-----".length),r=function(e){const t=new ArrayBuffer(e.length),n=new Uint8Array(t);for(let t=0,r=e.length;t<r;t+=1)n[t]=e.charCodeAt(t);return t}(t.atob(n));return crypto.subtle.importKey("pkcs8",r,au,!1,["sign"])}async function iu({bufferCurrentUsage:e,getActiveStreams:t,updateUsage:n,dispose:r}){const a=e();if(a.length)try{const n=(new Date).toISOString(),s=await async function({timestamp:e,streams:t}){const n=t.map((e=>Object.keys(e).sort().map((t=>`${t}=${e[t]}`)).join("&"))).join(";"),r=C.default.v4(),a=`nonceStr=${r}&timestamp=${e}&data=${n}==`,s=(new TextEncoder).encode(a),o=await ou("-----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-----");return{signature:su(await crypto.subtle.sign(au,o,s)),nonceStr:r}}({timestamp:n,streams:a});if(!s||!s.signature)throw new Error("Signature is undefined");const o={signature:s.signature,nonceStr:s.nonceStr,timestamp:n,streams:a},i=Te();return await i.http.post("/api/v3/user-event/video-streaming",o),t().length||e().length||r(),!0}catch(e){return a.forEach((e=>n(e))),!1}}class cu{constructor(){this._unsyncedData=[],this._syncBuffer=[],this._activeStreams=[],this._startInterval(),this._syncInterval=null}registerStream(e){this._activeStreams.push(e)}getActiveStreams(){return this._activeStreams}unregisterStream(e){this._activeStreams=this._activeStreams.filter((t=>t!==e))}updateUsage(e){this._unsyncedData.push(e)}bufferCurrentUsage(){const e=this._unsyncedData;return this._unsyncedData=[],e}dispose(){this._syncInterval&&clearInterval(this._syncInterval)}_startInterval(){this._syncInterval=setInterval((()=>{iu({bufferCurrentUsage:this.bufferCurrentUsage.bind(this),getActiveStreams:this.getActiveStreams.bind(this),updateUsage:this.updateUsage.bind(this),dispose:this.dispose.bind(this)})}),2e4)}}let lu=null;class du{constructor(e,t){this.player=e,this.resolution=t,this._startTime=null,this._usageCollector=lu||(lu=new cu,lu),this._usageCollector.registerStream(e.id),this._sessionId=String(C.default.v4()),this._controller=new AbortController,this._observer=new MutationObserver((t=>{t.forEach((t=>{t.removedNodes.forEach((t=>{t===e&&this._unregisterEvents()}))}))}))}_resetStartTime(){this._startTime=Date.now()}_shouldUpdateCollector(){return!!this._startTime&&Date.now()-this._startTime>2e4}_sendUsageToCollector(){if(!this._startTime)return;const e=Date.now(),t=e-this._startTime,n=Math.round(t/1e3);n&&this._usageCollector.updateUsage({streamId:this.player.id,sessionId:this._sessionId,startTime:this._startTime?new Date(this._startTime).toISOString():null,endTime:new Date(e).toISOString(),watchSeconds:n,resolution:this.resolution})}registerEvents(){this.player.addEventListener("play",(()=>{this._startTime||this._resetStartTime()}),{signal:this._controller.signal}),this.player.addEventListener("playing",(()=>{this._startTime||this._resetStartTime()}),{signal:this._controller.signal}),this.player.addEventListener("timeupdate",(()=>{this._shouldUpdateCollector()&&(this._sendUsageToCollector(),this._resetStartTime())}),{signal:this._controller.signal}),this.player.addEventListener("pause",(()=>{this._sendUsageToCollector(),this._startTime=null}),{signal:this._controller.signal}),this.player.addEventListener("ended",(()=>{this._sendUsageToCollector(),this._startTime=null}),{signal:this._controller.signal})}_unregisterEvents(){this._usageCollector.unregisterStream(this.player.id),this._controller.abort(),this._observer.disconnect()}}var uu=Object.freeze({__proto__:null,getPlayer:async e=>{const{streamId:t}=e;if(!document)throw new Error("This method can be invoked within the browser enviornment only");if(!_.default.isSupported())throw new Error("This browswer does not support hls, unable to play stream");const{data:n}=await zd(t),{watcherUrl:r,status:a,recordings:s=[],resolution:o}=n;if(!r.hls)throw new Error("This stream does not support hls. Unable to play");const i=document.createElement("video");i.id=t,i.controls=!0;const c=new _.default;if(c.attachMedia(i),"recorded"!==a){let{url:e}=r.hls;e=e.replace("http:","https:"),c.loadSource(e)}else{const e=s.find((e=>!!e.mp4));if(!e||!e.mp4)throw new Error("No playable recording available");i.src=e.mp4.url}return new du(i,o).registerEvents(),i}});const hu=e=>{const t=(e=>{var t;const n=Te(),r=new Date,a=r.getTime()+31536e6,s=new Date(a).toISOString();let o=null===(t=Re(["storyTarget","get",e.targetId]))||void 0===t?void 0:t.data;return o||(o={targetType:e.targetType,targetId:e.targetId,lastStoryExpiresAt:s,targetPublicId:e.targetId,targetUpdatedAt:r.toISOString()},Yt({storyTargets:[o]})),{stories:[Object.assign({createdAt:r.toISOString(),updatedAt:r.toISOString(),flagCount:0,hashFlag:null,reactions:{},reactionsCount:0,storyId:e.referenceId,path:"",creatorId:n.userId||"",creatorPublicId:n.userId||"",targetPublicId:e.targetId,comments:[],commentsCount:0,isDeleted:!1,hasFlaggedComment:!1,mentionedUsers:[],impression:0,reach:0,expiresAt:new Date(a).toISOString()},e)],categories:[],communityUsers:[],comments:[],files:[],users:[],communities:[]}})(e);return Yt(t),t},pu=({payload:e,formData:t,isVideo:n=!1},r)=>{if(t){const a=t.getAll("files")[0]||void 0;if(!a)return;const s=Object.assign(Object.assign({},e),{data:Object.assign(Object.assign({},e.data),{fileId:void 0,fileData:a.uri})});return n&&(s.data.videoFileId={original:void 0}),r(hu(s))}return r(hu(Object.assign(Object.assign({},e),{data:Object.assign(Object.assign({},e.data),{fileData:null})})))},fu=async e=>{const t=Te();t.log("post/createStory",e);const n=await t.http.post("/api/v4/stories",e),r=ud(n.data);t.cache&&Yt(r),Me(["story-sync-state",e.targetId],"synced"),it("local.story.created",r);const a=t.cache&&Date.now();return{data:r.stories.length>0?r.stories[0]:void 0,cachedAt:a}},mu=async({targetId:e,targetType:t})=>{var n,r;if(!Re(["storyTarget","get",e])){let a={targetId:e,targetType:t};if("community"===t){const t=await Wc(e);a=Object.assign(Object.assign({},a),{targetPublicId:t.data.communityId,targetUpdatedAt:null!==(n=t.data.updatedAt)&&void 0!==n?n:(new Date).toISOString()})}if("user"===t){const t=await Qo(e);a=Object.assign(Object.assign({},a),{targetPublicId:t.data.userPublicId,targetUpdatedAt:null!==(r=t.data.updatedAt)&&void 0!==r?r:(new Date).toISOString()})}Me(["storyTarget","get",e],a)}},gu=e=>e?Re(["story","get",e]):{data:void 0,cachedAt:void 0},yu=async(e,t=!1)=>{var n,r,a;const s=Te();let o;if(s.log("story/deleteStory",e),s.cache&&(o=gu(e),null==o?void 0:o.data)){const{data:s}=o;if(it("local.story.deleted",{categories:[],comments:[],communities:[],communityUsers:[],files:[],users:[],stories:[Object.assign(Object.assign({},s),{isDeleted:!0})]}),"synced"!==s.syncState){t?Ue(["story","get",e]):Me(["story","get",e],Object.assign(Object.assign({},o.data),{isDeleted:!0}));const r=null===(n=Ae(["story","get"]))||void 0===n?void 0:n.filter((e=>"synced"!==e.data.syncState&&e.data.targetId===s.targetId&&!0!==e.data.isDeleted));if(r&&r.length>0){const e=r.reduce(((e,t)=>{const n=new Date(t.data.expiresAt||0);return n>e?n:e}),new Date(0));Me(["story-expire",o.data.targetId],e.toISOString())}else Ue(["story-expire",o.data.targetId]);return!0}const i=null===(r=Re(["storyTarget","get",s.targetId]))||void 0===r?void 0:r.data,c=null===(a=Ae(["story","get"]))||void 0===a?void 0:a.filter((e=>"synced"===e.data.syncState&&e.data.targetId===s.targetId&&!0!==e.data.isDeleted));let l;c&&c.length>0&&(l=null==c?void 0:c.reduce(((e,t)=>{const n=new Date(t.data.expiresAt||0);return n>e?n:e}),new Date(0))),i&&Me(["storyTarget","get",s.targetId],Object.assign(Object.assign({},i),{lastStoryExpiresAt:l}))}return(await s.http.delete(`/api/v4/stories/${e}`,{params:{permanent:t}})).data.success},vu=e=>{const t=Te(),n=[ot(t,"onStoryUpdated","story.updated",(async t=>{const n=ud(t);Yt(n),e(n.stories)}))];return()=>{n.forEach((e=>e()))}},bu=e=>{const t=Te(),n=[ot(t,"onStoryUpdated","local.story.updated",(async t=>{Yt(t),e(t.stories)}))];return()=>{n.forEach((e=>e()))}},wu=e=>{const t=Te(),n=[ot(t,"onStoryReactionAdded","story.reactionAdded",(async t=>{const{reactions:n}=t,r=Xt(t,["reactions"]),a=ud(r),s=wi("story.reactionAdded",Object.assign(Object.assign({},a),{reactions:n}));Yt(s),e(s.stories)}))];return()=>{n.forEach((e=>e()))}},Cu=e=>{const t=Te(),n=[ot(t,"onStoryReactionAdded","local.story.reactionAdded",(async t=>{Yt({stories:[t.story]}),e([t.story])}))];return()=>{n.forEach((e=>e()))}},Iu=e=>{const t=Te(),n=[ot(t,"onStoryReactionRemoved","story.reactionRemoved",(async t=>{const{reactions:n}=t,r=Xt(t,["reactions"]),a=ud(r),s=wi("story.reactionRemoved",Object.assign(Object.assign({},a),{reactions:n}));Yt(s),e(s.stories)}))];return()=>{n.forEach((e=>e()))}},Su=e=>{const t=Te(),n=[ot(t,"onStoryReactionRemoved","local.story.reactionRemoved",(async t=>{Yt({stories:[t.story]}),e([t.story])}))];return()=>{n.forEach((e=>e()))}},_u=e=>{e.forEach((e=>{const t=Re(["story-expire",e.targetId]),n=new Date(e.expiresAt||0);n<new Date((null==t?void 0:t.data)||0)||Me(["story-expire",e.targetId],n.toISOString())}))},ku=e=>{e.forEach((e=>{Me(["story-reference",e.storyId],e.referenceId)}))},Ou=async({targetType:e,targetId:t,options:n})=>{const r=Te();r.log("story/getActiveStoriesByTarget");const a=r.cache&&Date.now(),s=await r.http.get("/api/v4/stories",{params:{targetType:e,targetId:t,options:{sortBy:(null==n?void 0:n.sortBy)||"createdAt",orderBy:(null==n?void 0:n.orderBy)||"desc"}}}),o=ud(s.data);return r.cache&&(Yt(o),_u(o.stories),ku(o.stories)),{data:o.stories,cachedAt:a,paging:{next:void 0,previous:void 0}}},Tu=e=>{const t=Te(),n=[ot(t,"onStoryCreated","story.created",(async t=>{const n=ud(t,!0);Yt(n),e(n.stories)}))];return()=>{n.forEach((e=>e()))}},Eu=e=>{const t=Te(),n=[ot(t,"onStoryCreated","local.story.created",(async t=>{Yt(t),e(t.stories)}))];return()=>{n.forEach((e=>e()))}},Au=e=>{const t=Te(),n=[ot(t,"onStoryDeleted","story.deleted",(async t=>{const n=ud(t);Yt(n),e(n.stories)}))];return()=>{n.forEach((e=>e()))}},Ru=e=>{const t=Te(),n=[ot(t,"onStoryDeleted","local.story.deleted",(async t=>{Yt(t),e(t.stories)}))];return()=>{n.forEach((e=>e()))}},Mu=e=>{const t=Te();return ot(t,"onStoryError","local.story.error",(async t=>{Yt(t),e(t.stories)}))},ju=e=>t=>e((e=>t(e[0]))),Pu=async e=>{const t=Te();t.log("story/getTargetsByTargetIds",e);const n=await t.http.get("/api/v4/stories/seen",{params:{targets:e}}),{data:r}=n;return t.cache&&Yt(n.data),{data:r.storyTargets,cachedAt:Date.now()}};class Uu extends jr{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.paginationController=r}saveToMainDB(e){const t=Te(),n=t.cache&&Date.now(),r=ud(e);t.cache&&(Yt(r,{cachedAt:n}),_u(r.stories),ku(r.stories))}getStoryReferenceIds(e){return(null==e?void 0:e.referenceId)?e.referenceId:e.storyId}appendToQueryStream(e,t,n=!1){var r,a;if(n)Me(this.cacheKey,{data:e.stories.map(this.getStoryReferenceIds)});else{const t=null===(r=Re(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Me(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.stories.map(this.getStoryReferenceIds)])]}))}}reactor(e){return e=>{var t;const n=null===(t=Re(this.cacheKey))||void 0===t?void 0:t.data;if(!n)return;const r=e.map((({referenceId:e})=>e));n.data=[...new Set([...r,...n.data])],Me(this.cacheKey,n),this.notifyChange({origin:"event",loading:!1})}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class xu extends Nr{async getRequest(e){const{data:t}=await this.http.get("/api/v4/stories-by-targets",{params:Object.assign({},e)});return t}}class Du extends Br{constructor(e,t){const n=I.default(e),r=["story-target-ids","collection",n],a=new xu(e);super(a,n,r,t),this.query=e,this.queryStreamController=new Uu(this.query,this.cacheKey,this.notifyChange.bind(this),a),this.paginationController=a,this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Re(this.cacheKey))||void 0===e?void 0:e.data)||Me(this.cacheKey,{data:[],params:{}})}persistModel(e){this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}notifyChange({origin:e,loading:t,error:n}){var r;const a=null===(r=Re(this.cacheKey))||void 0===r?void 0:r.data;if(!a)return;let s=a.data.map((e=>Re(["story","get",e]))).filter(Boolean).map((e=>na.story(e.data)));(this.shouldNotify(s)||"event"!==e)&&(s=this.applyFilter(s),this.callback({onNextPage:void 0,data:s,hasNextPage:!1,loading:t,error:n}))}applyFilter(e){var t,n;const r=e;return"asc"===((null===(n=null===(t=this.query)||void 0===t?void 0:t.options)||void 0===n?void 0:n.orderBy)||"desc")?r.sort(ze):r.sort(He)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:Tu,action:"onCreate"},{fn:vu,action:"onUpdate"},{fn:Au,action:"onDelete"},{fn:Mu,action:"onError"}])}}const qu=(e,t)=>{var n,r;const a=null===(n=Re(e))||void 0===n?void 0:n.data,s=null!==(r=null==a?void 0:a.data)&&void 0!==r?r:[];Me(e,Object.assign(Object.assign({},a),{data:[...new Set([...s,...t])]}))};class Nu extends jr{constructor(e,t,n,r,a){super(e,t),this.notifyChange=n,this.paginationController=r,this.preparePayload=a}saveToMainDB(e){const t=Te(),n=t.cache&&Date.now(),r=this.preparePayload(e);t.cache&&Yt(r,{cachedAt:n})}appendToQueryStream(e,t,n=!1){n?Me(this.cacheKey,{data:e.storyTargets.map((({targetId:e})=>e))}):qu(this.cacheKey,e.storyTargets.map((({targetId:e})=>e)))}reactor(e){return t=>{"onCreate"===e&&"seen"!==this.query.seenState&&qu(this.cacheKey,t.map((({targetId:e})=>e))),this.notifyChange({origin:"event",loading:!1})}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class Bu extends Rr{constructor(){super(...arguments),this.smartFilterState="unseen"}async getRequest(e,t){var n;const{limit:r=10,seenState:a="unseen"}=e,s=await this.createRequest({seenState:"smart"===a?this.smartFilterState:a,limit:r,token:t});if(null===(n=s.paging)||void 0===n?void 0:n.next)return s;if("smart"!==a)return s;if("seen"===this.smartFilterState)return s;this.smartFilterState="seen";const o=await this.createRequest({seenState:this.smartFilterState,limit:r});return c=o,{categories:(i=s).categories.concat(c.categories),communities:i.communities.concat(c.communities),communityUsers:i.communityUsers.concat(c.communityUsers),files:i.files.concat(c.files),storyTargets:i.storyTargets.concat(c.storyTargets),users:i.users.concat(c.users),paging:c.paging};var i,c}async createRequest(e){const{data:t}=await this.http.get("/api/v5/me/global-story-targets",{params:e});return n=t,r=e.seenState,Object.assign(Object.assign({},n),{storyTargets:n.storyTargets.map((e=>Object.assign(Object.assign({},e),{localFilter:r})))||[]});var n,r}}class Lu extends Br{constructor(e,t){const n=I.default(e),r=["story-global-feed","collection",n],a=new Bu(e);super(a,n,r,t),this.query=e,this.queryStreamController=new Nu(this.query,this.cacheKey,this.notifyChange.bind(this),a,(e=>{const t=Xt(_r(Object.assign(Object.assign({},e),{feeds:[]})),["feeds"]);return Object.assign(Object.assign({},e),t)})),this.paginationController=a,this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Re(this.cacheKey))||void 0===e?void 0:e.data)||Me(this.cacheKey,{data:[],params:{}})}persistModel(e){this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}notifyChange({origin:e,loading:t,error:n}){var r;const a=null===(r=Re(this.cacheKey))||void 0===r?void 0:r.data;if(!a)return;const s=a.data,o=Ae(["storyTarget"]);o&&(null==o?void 0:o.length)>0&&(null==o||o.forEach((({key:e})=>{a.data.includes(e[2])||s.push(e[2])})));let i=s.map((e=>Re(["storyTarget","get",e]))).filter(Boolean).map((e=>na.storyTarget(e.data)));(this.shouldNotify(i)||"event"!==e)&&(i=this.applyFilter(i).filter((({localSortingDate:e})=>!!e)).map((e=>Xt(e,["localFilter","localLastExpires","localLastSeen","localSortingDate"]))),this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:i,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n}))}applyFilter(e){if("smart"!==this.query.seenState)return e.filter((({hasUnseen:e})=>"all"===this.query.seenState||("seen"===this.query.seenState&&!e||"unseen"===this.query.seenState&&e))).sort(Ve);const t=e.reduce(((e,t)=>("unseen"===t.localFilter?e.unseen.push(t):"seen"===t.localFilter?e.seen.push(t):e.unknown.push(t),e)),{unseen:[],seen:[],unknown:[]}),n=t.unknown.sort(Ve)||[],r=t.unseen.sort(Ve)||[],a=t.seen.sort(Ve)||[];return n.concat(r,a)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:Tu,action:"onCreate"},{fn:vu,action:"onUpdate"},{fn:Au,action:"onDelete"},{fn:Eu,action:"onCreate"},{fn:bu,action:"onUpdate"},{fn:Ru,action:"onDelete"},{fn:Mu,action:"onError"}])}}var Fu=Object.freeze({__proto__:null,createImageStory:async(e,t,n,r={},a="fit",s=[])=>{if(!n.getAll("files").length)throw new Error("The formData object must have a `files` key.");let o={data:{text:"",fileId:void 0,fileData:null,imageDisplayMode:a},syncState:"syncing",referenceId:Qt(),dataType:"image",items:s,targetType:e,targetId:t,metadata:r};const i=new Date;Me(["story-sync-state",t],"syncing"),Me(["story-expire",t],new Date(i.setFullYear(i.getFullYear()+1))),pu({payload:o,formData:n},(e=>{it("local.story.created",e)}));try{const{data:r}=await ci(n);if(0===r.length)throw new Error("Failed to upload image");const{fileId:a}=r[0];o=Object.assign(Object.assign({},o),{data:Object.assign(Object.assign({},o.data),{fileId:a})}),mu({targetId:t,targetType:e}),pu({payload:o,formData:n},(e=>{it("local.story.created",e)}));const s=await fu(o);return s.data?Object.assign(Object.assign({},s),{data:na.story(s.data)}):s}catch(e){throw Me(["story-sync-state",t],"error"),pu({payload:Object.assign(Object.assign({},o),{syncState:"error"}),formData:n},(e=>{it("local.story.error",e)})),e}},createVideoStory:async(e,t,n,r={},a=[])=>{if(!n.getAll("files").length)throw new Error("The formData object must have a `files` key.");let s={data:{text:"",fileId:void 0,fileData:null},syncState:"syncing",referenceId:Qt(),dataType:"video",items:a,targetType:e,targetId:t,metadata:r};const o=new Date;Me(["story-sync-state",t],"syncing"),Me(["story-expire",t],new Date(o.setFullYear(o.getFullYear()+1))),mu({targetId:t,targetType:e}),pu({payload:s,formData:n,isVideo:!0},(e=>{it("local.story.created",e)}));try{const{data:e}=await ii(n,P.STORY);if(0===e.length)throw new Error("Failed to upload video");const{fileId:t}=e[0];s=Object.assign(Object.assign({},s),{data:Object.assign(Object.assign({},s.data),{fileId:t,videoFileId:{original:t}})}),pu({payload:s,formData:n,isVideo:!0},(e=>{it("local.story.created",e)}));const r=await fu(s);return r.data?Object.assign(Object.assign({},r),{data:na.story(r.data)}):r}catch(e){throw Me(["story-sync-state",t],"error"),pu({payload:Object.assign(Object.assign({},s),{syncState:"error"}),formData:n,isVideo:!0},(e=>{it("local.story.error",e)})),e}},hardDeleteStory:async e=>await yu(e,!0),softDeleteStory:async e=>await yu(e),getActiveStoriesByTarget:(e,t)=>{const{log:n,cache:r}=Te(),a=[],s=["story-target","collection",e],o=Date.now();n(`getActiveStoriesByTarget(tmpid: ${o}) > listen`),r||console.log(z);const i=t=>{var n,r;const a=(null===(n=e.options)||void 0===n?void 0:n.sortBy)||"createdAt",s=(null===(r=e.options)||void 0===r?void 0:r.orderBy)||"desc";return 0===t.length?[]:"createdAt"===a?"asc"===s?t.sort(ze):t.sort(He):"asc"===s?t.sort(Je):t.sort(We)},c=e=>{var n;const r=e.data.map((e=>{const t=gu(e);if(null==t?void 0:t.data)return na.story(t.data)})).filter(Boolean).filter((e=>!!e&&!e.isDeleted)),a=[];if(r.length>0){const e=r.reduce(((e,t)=>{if(!t)return e;const{syncState:n}=t;if(!n)return e;let r=e.get(n);return r||(r=[]),r.push(t),e.set(n,r),e}),new Map);if(e.has("error")){const t=i(e.get("error")||[]);a.push(...t)}if(e.has("syncing")){const t=i(e.get("syncing")||[]);a.push(...t)}if(e.has("synced")){const t=i(e.get("synced")||[]);a.push(...t)}}t({onNextPage:()=>!1,data:a||r,hasNextPage:!!(null===(n=e.params)||void 0===n?void 0:n.page),loading:e.loading||!1})},l=(t,n,r=!1,a=!1,o=!1)=>{var i;const l=Re(s),d={loading:a,error:o,params:{page:void 0},data:(null==l?void 0:l.data)||[]};if(t)if("onDelete"===n){const e=t.map((({referenceId:e})=>e));d.data=d.data.filter((t=>!e.includes(t)))||[]}else d.data=r?t.map(ve("story")):[...new Set([...d.data,...t.map(ve("story"))])];const u=null===(i=Ae(["story","get"]))||void 0===i?void 0:i.filter((t=>t.data.targetId===e.targetId&&"synced"!==t.data.syncState)).map((e=>ve("story")(e.data)));u&&(null==u?void 0:u.length)>0&&u.forEach((e=>{d.data.includes(e)||d.data.push(e)})),Me(s,d.data),c(d)},d=e=>t=>{l(t,e)};return(t=>{const n=pe(Ou,e);me(n,(({data:e,error:n,loading:r})=>{l(e,"fetch",t,r,n)}))})(!0),a.push(Tu(d("onCreate")),vu(d("onUpdate")),Au(d("onDelete")),wu(d("onReactionAdded")),Iu(d("onReactionRemoved")),Mu(d("onError")),Eu(d("onCreate")),bu(d("onUpdate")),Ru(d("onDelete")),Cu(d("onReactionAdded")),Su(d("onReactionRemoved")),(e=>{const t=Te();return ot(t,"onStoryLocalDataUpdated","local.story.reload",(t=>{e(t)}))})((e=>{const t=Re(s);if(!t)return;if(0===e.referenceIds.length||0===(null==t?void 0:t.data.length))return;if(!(null==t?void 0:t.data.find((t=>e.referenceIds.includes(t)))))return;const n={loading:!1,error:!1,params:{page:void 0},data:(null==t?void 0:t.data)||[]};c(n)})),(()=>Ue(s))),()=>{n(`getActiveStoriesByTarget(tmpid: ${o}) > dispose`),a.forEach((e=>e()))}},getStoryByStoryId:(e,t)=>Do(e,(e=>{(null==e?void 0:e.data)?t(Object.assign(Object.assign({},e),{data:na.story(e.data)})):t(e)}),"storyId",hd,[ju(vu),ju(Au),ju(wu),ju(Iu),ju(Mu),ju(bu),ju(Ru),ju(Cu),ju(Su)]),getTargetById:(e,t)=>Do(e,(e=>{(null==e?void 0:e.data)?t(Object.assign(Object.assign({},e),{data:na.storyTarget(e.data[0])})):t(e)}),"query",(e=>Pu([e])),[]),getTargetsByTargetIds:(e,t)=>{const{log:n,cache:r}=Te(),a=[],s=["storyTargets","collection",e],o=Date.now();n(`getTargetsByTargetIds(tmpid: ${o}) > listen`),r||console.log(z);const i=(e,n=!1,r=!1,a=!1)=>{const o=Re(s),i={loading:r,error:a,params:{page:void 0},data:[]};e&&(i.data=n?e.map(ve("storyTarget")):[...new Set([...(null==o?void 0:o.data)||[],...e.map(ve("storyTarget"))])]),Me(s,i.data),(e=>{var n;const r=e.data.map((e=>{const t=Re(["storyTarget","get",e]);if(null==t?void 0:t.data)return na.storyTarget(t.data)})).filter(Boolean);t({onNextPage:void 0,data:r,hasNextPage:!!(null===(n=e.params)||void 0===n?void 0:n.page),loading:e.loading||!1})})(i)};return(t=>{const n=pe(Pu,e);me(n,(({data:e,error:n,loading:r})=>{i(e,t,r,n)}))})(!0),a.push((()=>Ue(s))),()=>{n(`getTargetsByTargetIds(tmpid: ${o}) > dispose`),a.forEach((e=>e()))}},getStoriesByTargetIds:(e,t,n)=>{const{log:r,cache:a,userId:s}=Te();a||console.log(z);const o=Date.now();r(`getStoriesByTargetIds(tmpid: ${o}) > listen`);const i=new Du(e,t),c=i.startSubscription(),l=i.getCacheKey();return c.push((()=>{Ue(l)})),()=>{r(`getStoriesByTargetIds(tmpid: ${o}) > dispose`),c.forEach((e=>e()))}},getGlobalStoryTargets:(e,t,n)=>{const{log:r,cache:a,userId:s}=Te();a||console.log(z);const o=Date.now();r(`getGlobalStoryTarget(tmpid: ${o}) > listen`);const i=new Lu(e,t),c=i.startSubscription(),l=i.getCacheKey();return c.push((()=>{Ue(l)})),()=>{r(`getGlobalStoryTarget(tmpid: ${o}) > dispose`),c.forEach((e=>e()))}}});const Ku=e=>Object.assign(Object.assign({},e),{endAt:e.endAt?e.endAt:null}),$u=e=>Object.assign({},e);var Qu=Object.freeze({__proto__:null,getNetworkAds:async()=>{const e=Te(),{data:t}=await e.http.get("/api/v1/ads/me"),n=t.ads.map(Ku),r=t.advertisers.map($u);return Yt({ads:n,advertisers:r,files:t.files}),Me(["ad","setting"],t.settings),{ads:n.map(na.ad),settings:t.settings}}});const zu=async()=>{const e=Te();e.log("notificationTray/getNotificationTraySeen",{});const{data:t}=await e.http.get("api/v1/notification-tray/tray/seen"),n=e.cache&&Date.now();if(e.cache){const n=["notificationTraySeen","get",e.userId];Me(n,{userId:e.userId,lastTraySeenAt:t.lastTraySeenAt,lastTrayOccuredAt:t.lastTrayOccurredAt})}return{data:{userId:e.userId,lastTraySeenAt:t.lastTraySeenAt,lastTrayOccurredAt:t.lastTrayOccurredAt,isSeen:t.lastTraySeenAt>t.lastTrayOccurredAt},cachedAt:n}};zu.locally=()=>{var e;const t=Te();if(t.log("notificationTray/getNotificationTraySeen.locally",{}),!t.cache)return;const{data:n,cachedAt:r}=null!==(e=Re(["notificationTraySeen","get"]))&&void 0!==e?e:{};return n?{data:n,cachedAt:r}:void 0};const Vu=e=>{const t=Te(),n=[ot(t,"onNotificationTraySeenUpdated","local.notificationTraySeen.updated",(t=>e(t)))];return()=>{n.forEach((e=>e()))}};class Hu extends Rr{async getRequest(e,t){const{limit:n=$}=e,r=Xt(e,["limit"]),a=t?{token:t}:{limit:n},{data:s}=await this.http.get("/api/v1/notification-tray",{params:Object.assign(Object.assign({},r),{options:a})});return s}}class Ju extends jr{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Te(),r=n.cache&&Date.now();n.cache&&Yt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,a;if(n)Me(this.cacheKey,{data:e.notificationTrayItems.map(ve("notificationTrayItem"))});else{const t=null===(r=Re(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Me(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.notificationTrayItems.map(ve("notificationTrayItem"))])]}))}}}const Wu=e=>{const t=e.users.map(En);return Object.assign(Object.assign({},e),{users:t})};class Gu extends Br{constructor(e,t){const n=I.default(e),r=["notificationTrayItem","collection",n];super(new Hu(e),n,r,t),this.query=e,this.queryStreamController=new Ju(this.query,this.cacheKey,this.notifyChange.bind(this),Wu),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Re(this.cacheKey))||void 0===e?void 0:e.data)||Me(this.cacheKey,{data:[],params:{}})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return[]}notifyChange({origin:e,loading:t,error:n}){var r,a;const s=null===(r=Re(this.cacheKey))||void 0===r?void 0:r.data;if(!s)return;const o=(null!==(a=s.data.map((e=>Re(["notificationTrayItem","get",e]))).filter(cr).map((({data:e})=>e)))&&void 0!==a?a:[]).map(na.notificationTray);(this.shouldNotify(o)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:o,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}}var Yu=Object.freeze({__proto__:null,getNotificationTraySeen:e=>{const{userId:t}=Ze();return Do(t,e,"userId",zu,[Vu],{callbackDataSelector:e=>{let t=!0;return(null==e?void 0:e.lastTrayOccurredAt)&&(t=!!e.lastTraySeenAt&&Pn(e.lastTraySeenAt)>Pn(e.lastTrayOccurredAt)),{lastTrayOccurredAt:null==e?void 0:e.lastTrayOccurredAt,lastTraySeenAt:null==e?void 0:e.lastTraySeenAt,isSeen:t}}})},getNotificationTrayItems:(e,t,n)=>{const{log:r,cache:a}=Te();a||console.log(z);const s=Date.now();r(`getNotificationTrayItems(tmpid: ${s}) > listen`);const o=new Gu(e,t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>Ue(c))),()=>{r(`getNotificationTrayItems(tmpid: ${s}) > dispose`),i.forEach((e=>e()))}},markItemsSeen:async e=>{const t=Te();t.log("notificationTray/markItemsSeen",{});const{data:n}=await t.http.post("api/v1/notification-tray/items/seen",{trayItems:e.map((e=>({id:e.id,lastSeenAt:e.lastSeenAt})))}),r=n.trayItems.map((e=>{var n;const r=null===(n=Re(["notificationTrayItem","get",e.id]))||void 0===n?void 0:n.data;if(!r)return;const a=Object.assign(Object.assign({},r),{lastSeenAt:e.lastSeenAt});if(t.cache){const e=Date.now();Me(["notificationTrayItem","get"],a,{cachedAt:e})}return a})).filter(Boolean);it("local.notificationTrayItem.updated",{notificationTrayItems:r})},markTraySeen:async e=>{var t;const n=Te();n.log("notificationTray/markTraySeen",{});const{data:r}=await n.http.post("api/v1/notification-tray/tray/seen",{lastSeenAt:e}),a=null===(t=Re(["notificationTraySeen","get"]))||void 0===t?void 0:t.data,s={userId:n.userId,lastTraySeenAt:r.lastSeenAt},o=Object.assign(Object.assign({},a),s),i=n.cache&&Date.now();return n.cache&&Me(["notificationTraySeen","get",n.userId],o,{cachedAt:i}),it("local.notificationTraySeen.updated",s),{data:r,cachedAt:i}},onNotificationTraySeenUpdated:Vu});class Zu extends Rr{async getRequest(e,t){const{limit:n=$}=e,r=Xt(e,["limit"]),a=t?{token:t}:{limit:n},{data:s}=await this.http.get("/api/v1/invitations/me",{params:Object.assign(Object.assign({},r),{options:a})});return await Jc(s.invitations.map((e=>e.communityId))),s}}class Xu extends jr{constructor(e,t,n,r){super(e,t),this.notifyChange=n,this.preparePayload=r}async saveToMainDB(e){const t=await this.preparePayload(e),n=Te(),r=n.cache&&Date.now();n.cache&&Yt(t,{cachedAt:r})}appendToQueryStream(e,t,n=!1){var r,a;if(n)Me(this.cacheKey,{data:e.invitations.map(ve("invitation"))});else{const t=null===(r=Re(this.cacheKey))||void 0===r?void 0:r.data,n=null!==(a=null==t?void 0:t.data)&&void 0!==a?a:[];Me(this.cacheKey,Object.assign(Object.assign({},t),{data:[...new Set([...n,...e.invitations.map(ve("invitation"))])]}))}}reactor(e){return t=>{var n;const r=null===(n=Re(this.cacheKey))||void 0===n?void 0:n.data;if(r){if(e===Jr.OnLocalInvitationUpdated){if(!r.data.find((e=>e===t[0].invitationId)))return}if(e===Jr.OnLocalInvitationCreated){const e=Te(),n=t.filter((t=>t.invitedUserId===e.userId));r.data=[...new Set([...n.map((e=>e.invitationId)),...r.data])]}e===Jr.OnLocalInvitationDeleted&&(r.data=r.data.filter((e=>e!==t[0].invitationId))),Me(this.cacheKey,r),this.notifyChange({origin:"event",loading:!1})}}}subscribeRTE(e){return e.map((e=>e.fn(this.reactor(e.action))))}}class eh extends Br{constructor(e,t){const n=I.default(e),r=["invitation","collection",n];super(new Zu(e),n,r,t),this.query=e,this.queryStreamController=new Xu(this.query,this.cacheKey,this.notifyChange.bind(this),Vr),this.callback=t.bind(this),this.loadPage({initial:!0})}setup(){var e;(null===(e=Re(this.cacheKey))||void 0===e?void 0:e.data)||Me(this.cacheKey,{data:[],params:this.query})}async persistModel(e){await this.queryStreamController.saveToMainDB(e)}persistQueryStream({response:e,direction:t,refresh:n}){this.queryStreamController.appendToQueryStream(e,t,n)}startSubscription(){return this.queryStreamController.subscribeRTE([{fn:Yr,action:Jr.OnLocalInvitationCreated},{fn:Zr,action:Jr.OnLocalInvitationUpdated},{fn:Xr,action:Jr.OnLocalInvitationDeleted}])}notifyChange({origin:e,loading:t,error:n}){var r,a;const s=null===(r=Re(this.cacheKey))||void 0===r?void 0:r.data;if(!s)return;const o=this.applyFilter(null!==(a=s.data.map((e=>Re(["invitation","get",e]))).filter(cr).map((({data:e})=>Hr(e))))&&void 0!==a?a:[]);(this.shouldNotify(o)||"event"!==e)&&this.callback({onNextPage:()=>this.loadPage({direction:"next"}),data:o,hasNextPage:!!this.paginationController.getNextToken(),loading:t,error:n})}applyFilter(e){let t=e;this.query.targetId&&(t=t.filter((e=>e.targetId===this.query.targetId))),this.query.statuses&&(t=t.filter((e=>{var t;return null===(t=this.query.statuses)||void 0===t?void 0:t.includes(e.status)}))),this.query.targetType&&(t=t.filter((e=>e.targetType===this.query.targetType))),this.query.type&&(t=t.filter((e=>e.type===this.query.type)));const n=(()=>"firstCreated"===this.query.sortBy?ze:He)();return t=t.sort(n),t}}var th=Object.freeze({__proto__:null,onLocalInvitationCreated:Yr,onLocalInvitationUpdated:Zr,onLocalInvitationDeleted:Xr,getMyCommunityInvitations:(e,t,n)=>{const{log:r,cache:a}=Te();a||console.log(z);const s=Date.now();r(`getMyCommunityInvitations: (tmpid: ${s}) > listen`);const o=new eh(Object.assign(Object.assign({},e),{targetType:"community",statuses:["pending"]}),t),i=o.startSubscription(),c=o.getCacheKey();return i.push((()=>{Ue(c)})),()=>{r(`getInvitations (tmpid: ${s}) > dispose`),i.forEach((e=>e()))}}});return e.API_REGIONS=Tt,e.AdRepository=Qu,e.CategoryRepository=ad,e.ChannelRepository=Vc,e.Client=oo,e.CommentRepository=Sd,e.CommunityPostSettingMaps=M,e.CommunityPostSettings=R,e.CommunityRepository=td,e.ContentFeedType=P,e.DefaultCommunityPostSetting=j,e.FeedRepository=id,e.FileRepository=li,e.FileType=k,e.InvitationRepository=th,e.LiveStreamPlayer=uu,e.MessageContentType=x,e.MessageRepository=Sc,e.PollRepository=ru,e.PostContentType=D,e.PostRepository=Qd,e.ReactionRepository=Gi,e.StoryRepository=Fu,e.StreamRepository=Xd,e.SubChannelRepository=Rc,e.UserRepository=si,e.VERSION=K,e.VideoResolution=O,e.VideoSize=E,e.VideoTranscodingStatus=T,e.backupCache=async(e="amitySdk",t=(e=>e.offline))=>{const{log:n,cache:r,userId:a}=Te();if(!r)return!1;n("cache/api/backupCache",{storageKey:e});const s=Object.fromEntries(Object.entries(r.data).filter((([e,n])=>t(n))));return!!Object.keys(s).length&&(localStorage&&await localStorage.setItem(`${e}#${a}`,JSON.stringify(s)),!0)},e.createQuery=pe,e.createReport=async(e,t)=>{const n=Te();return n.log("report/createReport",{referenceType:e,referenceId:t}),"user"===e?(async({client:e,referenceId:t})=>{const{data:n}=await e.http.post(`/api/v4/me/flags/${encodeURIComponent(t)}`);if(e.cache){const e=await xa(n);Yt(e)}return it("user.flagged",n),!!n})({client:n,referenceId:t}):"message"===e?(async({client:e,referenceId:t})=>{const{data:n}=await e.http.post(`/api/v5/messages/${encodeURIComponent(t)}/flags`);if(e.cache){const e=await kn(n);Yt(e)}return it("message.flagged",n),!!n})({client:n,referenceId:t}):"post"===e?(async({client:e,referenceId:t})=>{const{data:n}=await e.http.post(`/api/v3/posts/${encodeURIComponent(t)}/flag`);if(e.cache){const e=await Si(n);Yt(e)}return it("post.flagged",n),!!n})({client:n,referenceId:t}):"comment"===e&&(async({client:e,referenceId:t})=>{const{data:n}=await e.http.post(`/api/v3/comments/${encodeURIComponent(t)}/flag`);if(e.cache){const e=await Yi(n);Yt(e)}return it("comment.flagged",n),!!n})({client:n,referenceId:t})},e.createUserToken=async(e,t,n)=>{const r=await Vt(),a=Ht(),s=Dt(At("http",t)),{data:o}=await s.post("/api/v5/sessions",Object.assign(Object.assign({},n),{deviceId:r,deviceInfo:Object.assign(Object.assign({},a),{model:"token management API on TS-SDK"})}),{headers:{"X-API-Key":e}});return{accessToken:o.accessToken}},e.deleteReport=async(e,t)=>{const n=Te();return n.log("report/deleteReport",{referenceType:e,referenceId:t}),"user"===e?(async({client:e,referenceId:t})=>{const{data:n}=await e.http.delete(`/api/v4/me/flags/${encodeURIComponent(t)}`);if(e.cache){const e=await xa(n);Yt(e)}return it("user.unflagged",n),!!n})({client:n,referenceId:t}):"message"===e?(async({client:e,referenceId:t})=>{const{data:n}=await e.http.delete(`/api/v5/messages/${encodeURIComponent(t)}/flags`);if(e.cache){const e=await kn(n);Yt(e)}return it("message.unflagged",n),!!n})({client:n,referenceId:t}):"post"===e?(async({client:e,referenceId:t})=>{const{data:n}=await e.http.delete(`/api/v3/posts/${encodeURIComponent(t)}/unflag`);if(e.cache){const e=await Si(n);Yt(e)}return it("post.unflagged",n),!!n})({client:n,referenceId:t}):"comment"===e&&(async({client:e,referenceId:t})=>{const{data:n}=await e.http.delete(`/api/v3/comments/${encodeURIComponent(t)}/unflag`);if(e.cache){const e=await Yi(n);Yt(e)}return it("comment.unflagged",n),!!n})({client:n,referenceId:t})},e.disableCache=()=>{const e=Te();e.cache&&(e.log("cache/api/disableCache"),delete e.cache)},e.dropFromCache=Ue,e.enableCache=(e={},t)=>{const n=Te();n.cache||(n.log("cache/api/enableCache"),n.cache={data:e,persistIf:t})},e.filterByChannelMembership=Ne,e.filterByCommunityMembership=Le,e.filterByFeedType=Be,e.filterByPostDataTypes=Fe,e.filterByPropEquality=xe,e.filterByPropInclusion=(e,t,n)=>void 0!==n?e.filter((e=>n.includes(e[t]))):e,e.filterByPropIntersection=qe,e.filterBySearchTerm=Ke,e.filterByStringComparePartially=De,e.getChannelTopic=e=>`${e.path}/#`,e.getCommentTopic=({path:e})=>e,e.getCommunityStoriesTopic=({targetId:e,targetType:t})=>{const n=Ze();return`${pt(n)}/social/${t}/${e}/story/#`},e.getCommunityTopic=({path:t},n=e.SubscriptionLevels.COMMUNITY)=>ht(t,n),e.getLiveStreamTopic=It,e.getMarkedMessageTopic=mt,e.getMarkerUserFeedTopic=gt,e.getMessageTopic=e=>e.path,e.getMyFollowersTopic=()=>{const e=Ze();return`${pt(e)}/membership/${e._id}/+/+`},e.getMyFollowingsTopic=()=>{const e=Ze();return`${pt(e)}/membership/+/${e._id}/+`},e.getNetworkTopic=yt,e.getPostTopic=({path:t},n=e.SubscriptionLevels.POST)=>"comment"===n?`${t}/comment/+`:t,e.getRole=ui,e.getSmartFeedChannelTopic=vt,e.getSmartFeedMessageTopic=wt,e.getSmartFeedSubChannelTopic=bt,e.getStoryTopic=({targetId:e,targetType:t,storyId:n})=>{const r=Ze();return`${pt(r)}/social/${t}/${e}/story/${n}/#`},e.getSubChannelTopic=e=>`${e.path}/#`,e.getUserTopic=ft,e.isAfterBefore=re,e.isAfterBeforeRaw=ae,e.isCachable=ue,e.isFetcher=ce,e.isFresh=he,e.isLocal=e=>ue(e)&&-1===(null==e?void 0:e.cachedAt),e.isMutator=le,e.isOffline=de,e.isPaged=se,e.isReportedByMe=async(e,t)=>{const n=Te();return n.log("report/isReportedByMe",{referenceType:e,referenceId:t}),"user"===e?(async({client:e,referenceId:t})=>{var n;const{data:r}=await e.http.get(`/api/v3/users/${t}/isflagbyme`),{result:a,isFlagByMe:s}=null!=r?r:{};return null!==(n=null!=a?a:s)&&void 0!==n&&n})({client:n,referenceId:t}):"message"===e?(async({client:e,referenceId:t})=>{var n;const{data:r}=await e.http.get(`/api/v5/messages/${encodeURIComponent(t)}/flags`),{result:a,isFlagByMe:s}=null!=r?r:{};return null!==(n=null!=a?a:s)&&void 0!==n&&n})({client:n,referenceId:t}):"post"===e?(async({client:e,referenceId:t})=>{var n;const{data:r}=await e.http.get(`/api/v3/posts/${t}/isflagbyme`),{result:a,isFlagByMe:s}=null!=r?r:{};return null!==(n=null!=a?a:s)&&void 0!==n&&n})({client:n,referenceId:t}):"comment"===e&&(async({client:e,referenceId:t})=>{var n;const{data:r}=await e.http.get(`/api/v3/comments/${t}/isflagbyme`),{result:a,isFlagByMe:s}=null!=r?r:{};return null!==(n=null!=a?a:s)&&void 0!==n&&n})({client:n,referenceId:t})},e.isSkip=ne,e.mergeInCache=je,e.notificationTray=Yu,e.onChannelMarkerFetched=eo,e.onFeedMarkerFetched=e=>{const t=Te();return ot(t,"feedMarker/onFeedMarkerFetched","local.feedMarker.fetched",(t=>{e(t.feedMarkers[0])}))},e.onFeedMarkerUpdated=e=>{const t=Te();return ot(t,"feedMarker/onFeedMarkerUpdated","marker.feed-updated",(t=>{Yt(t),e(t.feedMarkers[0])}))},e.onMessageMarked=so,e.onMessageMarkerFetched=ao,e.onSubChannelMarkerFetched=to,e.onSubChannelMarkerUpdated=no,e.onUserMarkerFetched=ro,e.onUserMarkerFetchedLegacy=e=>{const t=Te();return ot(t,"userMarker/onUserMarkerFetched","local.userMarker.fetched",(t=>{e(t.userMarkers[0])}))},e.pullFromCache=Re,e.pushToCache=Me,e.queryCache=Ae,e.queryOptions=fe,e.queryRoles=di,e.restoreCache=async(e="amitySdk")=>{var t;const n=Te();if(!n.cache)return!1;n.log("cache/api/restoreCache",{storageKey:e});const r=localStorage&&null!==(t=await localStorage.getItem(`${e}#${n.userId}`))&&void 0!==t?t:"{}";let a={};try{a=JSON.parse(r)}catch(e){}return n.cache.data=Object.assign(Object.assign({},a),n.cache.data),!0},e.runQuery=me,e.sortByChannelSegment=({channelSegment:e},{channelSegment:t})=>e-t,e.sortByDisplayName=$e,e.sortByFirstCreated=ze,e.sortByFirstUpdated=Je,e.sortByLastActivity=Ge,e.sortByLastCreated=He,e.sortByLastUpdated=We,e.sortByLocalSortingDate=Ve,e.sortByName=Qe,e.sortBySegmentNumber=({segmentNumber:e},{segmentNumber:t})=>e-t,e.subscribeTopic=Ct,e.toPage=ie,e.toPageRaw=e=>{if(!e)return;const n=JSON.parse(t.decode(e));return ae(n)?n:void 0},e.toToken=oe,e.upsertInCache=Pe,e.wipeCache=async(e="amitySdk")=>{const{log:t,cache:n,userId:r}=Te();return!!n&&(t("cache/api/wipeCache",{storageKey:e}),n.data={},localStorage&&await localStorage.setItem(`${e}#${r}`,"{}"),!0)},Object.defineProperty(e,"__esModule",{value:!0}),e}({},jsBase64,mitt,debug,axios,HttpAgent,io,AsyncStorage,uuid$1,hash,jwtDecode,reactNative,Hls);