quickblox-react-ui-kit 0.5.1 → 0.5.2

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 (538) hide show
  1. package/.claude/settings.local.json +15 -0
  2. package/dist/App.d.ts +1 -0
  3. package/dist/CommonTypes/BaseViewModel.d.ts +2 -1
  4. package/dist/CommonTypes/CommonTypes.d.ts +1 -0
  5. package/dist/CommonTypes/FunctionResult.d.ts +1 -0
  6. package/dist/Data/Creator.d.ts +1 -0
  7. package/dist/Data/DefaultConfigurations.d.ts +1 -0
  8. package/dist/Data/Stubs.d.ts +1 -0
  9. package/dist/Data/dto/dialog/LocalDialogDTO.d.ts +1 -0
  10. package/dist/Data/dto/dialog/LocalDialogsDTO.d.ts +1 -0
  11. package/dist/Data/dto/dialog/RemoteDialogDTO.d.ts +1 -0
  12. package/dist/Data/dto/dialog/RemoteDialogsDTO.d.ts +1 -0
  13. package/dist/Data/dto/file/LocalFileDTO.d.ts +1 -0
  14. package/dist/Data/dto/file/RemoteFileDTO.d.ts +1 -0
  15. package/dist/Data/dto/message/LocalMessageDTO.d.ts +1 -0
  16. package/dist/Data/dto/message/LocalMessagesDTO.d.ts +1 -0
  17. package/dist/Data/dto/message/RemoteMessageDTO.d.ts +1 -0
  18. package/dist/Data/dto/message/RemoteMessagesDTO.d.ts +1 -0
  19. package/dist/Data/dto/user/LocalUserDTO.d.ts +1 -0
  20. package/dist/Data/dto/user/LocalUsersDTO.d.ts +1 -0
  21. package/dist/Data/dto/user/RemoteUserDTO.d.ts +1 -0
  22. package/dist/Data/dto/user/RemoteUsersDTO.d.ts +1 -0
  23. package/dist/Data/mapper/DialogLocalDTOMapper.d.ts +1 -0
  24. package/dist/Data/mapper/DialogRemoteDTOMapper.d.ts +1 -0
  25. package/dist/Data/mapper/FileLocalDTOMapper.d.ts +1 -0
  26. package/dist/Data/mapper/FileRemoteDTOMapper.d.ts +1 -0
  27. package/dist/Data/mapper/IMapper.d.ts +1 -0
  28. package/dist/Data/mapper/MessageLocalDTOMapper.d.ts +1 -0
  29. package/dist/Data/mapper/MessageRemoteDTOMapper.d.ts +1 -0
  30. package/dist/Data/mapper/UserLocalDTOMapper.d.ts +1 -0
  31. package/dist/Data/mapper/UserRemoteDTOMapper.d.ts +1 -0
  32. package/dist/Data/repository/ConnectionRepository.d.ts +1 -0
  33. package/dist/Data/repository/ConnectionRepository.d.ts.map +1 -1
  34. package/dist/Data/repository/DialogsRepository.d.ts +1 -0
  35. package/dist/Data/repository/EventMessagesRepository.d.ts +1 -0
  36. package/dist/Data/repository/FileRepository.d.ts +1 -0
  37. package/dist/Data/repository/MessagesRepository.d.ts +1 -0
  38. package/dist/Data/repository/UsersRepository.d.ts +1 -0
  39. package/dist/Data/source/AISource.d.ts +1 -0
  40. package/dist/Data/source/exception/LocalDataSourceException.d.ts +1 -0
  41. package/dist/Data/source/exception/MapperDTOException.d.ts +1 -0
  42. package/dist/Data/source/exception/RemoteDataSourceException.d.ts +1 -0
  43. package/dist/Data/source/exception/RepositoryException.d.ts +1 -0
  44. package/dist/Data/source/local/ChatLocalStorageDataSource.d.ts +1 -0
  45. package/dist/Data/source/local/ILocalDataSource.d.ts +1 -0
  46. package/dist/Data/source/local/ILocalFileDataSource.d.ts +1 -0
  47. package/dist/Data/source/local/LocalDataSource.d.ts +1 -0
  48. package/dist/Data/source/local/LocalFileDataSource.d.ts +1 -0
  49. package/dist/Data/source/remote/IRemoteDataSource.d.ts +1 -0
  50. package/dist/Data/source/remote/Mapper/DialogDTOMapper.d.ts +1 -0
  51. package/dist/Data/source/remote/Mapper/FileDTOMapper.d.ts +1 -0
  52. package/dist/Data/source/remote/Mapper/IDTOMapper.d.ts +1 -0
  53. package/dist/Data/source/remote/Mapper/MessageDTOMapper.d.ts +2 -0
  54. package/dist/Data/source/remote/Mapper/MessageDTOMapper.d.ts.map +1 -1
  55. package/dist/Data/source/remote/Mapper/UserDTOMapper.d.ts +1 -0
  56. package/dist/Data/source/remote/RemoteDataSource.d.ts +1 -0
  57. package/dist/Domain/entity/Chat.d.ts +1 -0
  58. package/dist/Domain/entity/ChatMessageAttachmentEntity.d.ts +1 -0
  59. package/dist/Domain/entity/CustomDataEntity.d.ts +1 -0
  60. package/dist/Domain/entity/DialogEntity.d.ts +1 -0
  61. package/dist/Domain/entity/DialogEventInfo.d.ts +1 -0
  62. package/dist/Domain/entity/DialogTypes.d.ts +1 -0
  63. package/dist/Domain/entity/EventMessageType.d.ts +1 -0
  64. package/dist/Domain/entity/FileEntity.d.ts +1 -0
  65. package/dist/Domain/entity/FileTypes.d.ts +1 -0
  66. package/dist/Domain/entity/GroupDialogEntity.d.ts +1 -0
  67. package/dist/Domain/entity/LastMessageEntity.d.ts +1 -0
  68. package/dist/Domain/entity/MessageEntity.d.ts +1 -0
  69. package/dist/Domain/entity/NotificationTypes.d.ts +1 -0
  70. package/dist/Domain/entity/PrivateDialogEntity.d.ts +1 -0
  71. package/dist/Domain/entity/PublicDialogEntity.d.ts +1 -0
  72. package/dist/Domain/entity/UserEntity.d.ts +1 -0
  73. package/dist/Domain/exception/domain/DomainExecption.d.ts +1 -0
  74. package/dist/Domain/repository/IDialogsRepository.d.ts +1 -0
  75. package/dist/Domain/repository/IFileRepository.d.ts +1 -0
  76. package/dist/Domain/repository/IMessagesRepository.d.ts +1 -0
  77. package/dist/Domain/repository/IUsersRepository.d.ts +1 -0
  78. package/dist/Domain/repository/Pagination.d.ts +1 -0
  79. package/dist/Domain/use_cases/CreateDialogUseCase.d.ts +1 -0
  80. package/dist/Domain/use_cases/ForwardMessagesUseCase.d.ts +1 -0
  81. package/dist/Domain/use_cases/GetAllDialogsUseCase.d.ts +1 -0
  82. package/dist/Domain/use_cases/GetAllDialogsUseCaseWithMock.d.ts +1 -0
  83. package/dist/Domain/use_cases/GetAllMessagesForDialog.d.ts +1 -0
  84. package/dist/Domain/use_cases/GetAllUsersUseCase.d.ts +1 -0
  85. package/dist/Domain/use_cases/GetDialogByIdUseCase.d.ts +1 -0
  86. package/dist/Domain/use_cases/GetUsersByIdsUseCase.d.ts +1 -0
  87. package/dist/Domain/use_cases/LeaveDialogUseCase.d.ts +1 -0
  88. package/dist/Domain/use_cases/RemoveUsersFromTheDialogUseCase.d.ts +1 -0
  89. package/dist/Domain/use_cases/ReplyMessagesUseCase.d.ts +1 -0
  90. package/dist/Domain/use_cases/SendTextMessageUseCase.d.ts +1 -0
  91. package/dist/Domain/use_cases/SubscribeToDialogEventsUseCase.d.ts +1 -0
  92. package/dist/Domain/use_cases/SubscribeToDialogsUpdatesUseCase.d.ts +1 -0
  93. package/dist/Domain/use_cases/SubscribeToDialogsUpdatesUseCaseWithMock.d.ts +1 -0
  94. package/dist/Domain/use_cases/SyncDialogsUseCase.d.ts +1 -0
  95. package/dist/Domain/use_cases/SyncDialogsUseCase.d.ts.map +1 -1
  96. package/dist/Domain/use_cases/UpdateCurrentDialogInDataSourceUseCase.d.ts +1 -0
  97. package/dist/Domain/use_cases/UpdateDialogUseCase.d.ts +1 -0
  98. package/dist/Domain/use_cases/UploadFileUseCase.d.ts +1 -0
  99. package/dist/Domain/use_cases/UserTypingMessageUseCase.d.ts +1 -0
  100. package/dist/Domain/use_cases/UserTypingMessageUseCase.d.ts.map +1 -1
  101. package/dist/Domain/use_cases/ai/AIAnswerAssistUseCase.d.ts +1 -0
  102. package/dist/Domain/use_cases/ai/AIAnswerAssistWithProxyUseCase.d.ts +1 -0
  103. package/dist/Domain/use_cases/ai/AIAnswerAssistWithSDKUseCase.d.ts +1 -0
  104. package/dist/Domain/use_cases/ai/AIRephraseUseCase.d.ts +1 -0
  105. package/dist/Domain/use_cases/ai/AIRephraseWithProxyUseCase.d.ts +1 -0
  106. package/dist/Domain/use_cases/ai/AITranslateUseCase.d.ts +1 -0
  107. package/dist/Domain/use_cases/ai/AITranslateWithProxyUseCase.d.ts +1 -0
  108. package/dist/Domain/use_cases/ai/AITranslateWithSDKUseCase.d.ts +1 -0
  109. package/dist/Domain/use_cases/base/BaseUseCase.d.ts +1 -0
  110. package/dist/Domain/use_cases/base/IUseCase.d.ts +1 -0
  111. package/dist/Domain/use_cases/base/Subscribable/ISubscribable.d.ts +1 -0
  112. package/dist/Domain/use_cases/base/Subscribable/SubscriptionPerformer.d.ts +1 -0
  113. package/dist/Presentation/Views/Dialog/AIComponents/AIAssist/AIAssist.d.ts +1 -0
  114. package/dist/Presentation/Views/Dialog/AIComponents/AIAssistComponent/AIAssistComponent.d.ts +1 -0
  115. package/dist/Presentation/Views/Dialog/AIComponents/AITranslate/AITranslate.d.ts +1 -0
  116. package/dist/Presentation/Views/Dialog/AIComponents/AITranslateComponent/AITranslateComponent.d.ts +1 -0
  117. package/dist/Presentation/Views/Dialog/AIWidgets/AIMessageWidget.d.ts +1 -0
  118. package/dist/Presentation/Views/Dialog/AIWidgets/AIRephraseWidget/AIRephraseWidget.d.ts +1 -0
  119. package/dist/Presentation/Views/Dialog/AIWidgets/AIWidgetActions/AIWidgetActions.d.ts +2 -1
  120. package/dist/Presentation/Views/Dialog/AIWidgets/ErrorMessageIcon.d.ts +1 -0
  121. package/dist/Presentation/Views/Dialog/AIWidgets/SliderMenu.d.ts +2 -1
  122. package/dist/Presentation/Views/Dialog/AIWidgets/Tone.d.ts +1 -0
  123. package/dist/Presentation/Views/Dialog/AIWidgets/UseDefaultAIAssistAnswerWidget.d.ts +1 -0
  124. package/dist/Presentation/Views/Dialog/AIWidgets/UseDefaultAIAssistAnswerWidgetWithProxy.d.ts +1 -0
  125. package/dist/Presentation/Views/Dialog/AIWidgets/UseDefaultAIAssistAnswerWidgetWithSDK.d.ts +1 -0
  126. package/dist/Presentation/Views/Dialog/AIWidgets/UseDefaultAIRephraseMessageWidget.d.ts +1 -0
  127. package/dist/Presentation/Views/Dialog/AIWidgets/UseDefaultAIRephraseMessageWidgetWithProxy.d.ts +1 -0
  128. package/dist/Presentation/Views/Dialog/AIWidgets/UseDefaultAITranslateWidget.d.ts +1 -0
  129. package/dist/Presentation/Views/Dialog/AIWidgets/UseDefaultAITranslateWidgetWithProxy.d.ts +1 -0
  130. package/dist/Presentation/Views/Dialog/AIWidgets/UseDefaultAITranslateWidgetWithSDK.d.ts +1 -0
  131. package/dist/Presentation/Views/Dialog/AIWidgets/useDefaultVoiceInputWidget.d.ts +1 -0
  132. package/dist/Presentation/Views/Dialog/ContextMenu/ContextMenu.d.ts +2 -1
  133. package/dist/Presentation/Views/Dialog/Dialog.d.ts +1 -1
  134. package/dist/Presentation/Views/Dialog/DialogHeader/DialogBackIcon/DialogBackIcon.d.ts +1 -0
  135. package/dist/Presentation/Views/Dialog/DialogHeader/DialogHeader.d.ts +1 -1
  136. package/dist/Presentation/Views/Dialog/DialogHeader/DialogInfoIcon/DialogInfoIcon.d.ts +1 -0
  137. package/dist/Presentation/Views/Dialog/DialogViewModel.d.ts +1 -0
  138. package/dist/Presentation/Views/Dialog/DropDownMenu/DropDownMenu.d.ts +1 -1
  139. package/dist/Presentation/Views/Dialog/DropDownMenu/ItemDropDownMenu/ItemDropDownMenu.d.ts +1 -1
  140. package/dist/Presentation/Views/Dialog/ErrorToast/ErrorToast.d.ts +1 -0
  141. package/dist/Presentation/Views/Dialog/ForwardMessageFlow/DialogsWithSearch/DialogListItem/DialogListItem.d.ts +1 -0
  142. package/dist/Presentation/Views/Dialog/ForwardMessageFlow/DialogsWithSearch/DialogsWithSearch.d.ts +1 -0
  143. package/dist/Presentation/Views/Dialog/ForwardMessageFlow/DialogsWithSearch/SearchComponent/SearchComponent.d.ts +1 -0
  144. package/dist/Presentation/Views/Dialog/ForwardMessageFlow/ForwardMessageFlow.d.ts +1 -0
  145. package/dist/Presentation/Views/Dialog/ForwardMessageFlow/ForwardMessagePreview/ForwardMessagePreview.d.ts +1 -0
  146. package/dist/Presentation/Views/Dialog/ForwardMessageFlow/InputForForwarding/InputForForwarding.d.ts +1 -0
  147. package/dist/Presentation/Views/Dialog/InputMessage/InputMessage.d.ts +1 -1
  148. package/dist/Presentation/Views/Dialog/Message/HighLightLink/HighLightLink.d.ts +1 -0
  149. package/dist/Presentation/Views/Dialog/Message/IncomingForwardedMessage/IncomingForwardedMessage.d.ts +1 -1
  150. package/dist/Presentation/Views/Dialog/Message/IncomingMessage/AvatarContentIncomingUser/AvatarContentIncomingUser.d.ts +1 -0
  151. package/dist/Presentation/Views/Dialog/Message/IncomingMessage/IncomingMessage.d.ts +1 -1
  152. package/dist/Presentation/Views/Dialog/Message/IncomingMessage/MessageContentComponent/MessageContentComponent.d.ts +1 -1
  153. package/dist/Presentation/Views/Dialog/Message/IncomingRepliedMessage/IncomingRepliedMessage.d.ts +1 -1
  154. package/dist/Presentation/Views/Dialog/Message/Message.d.ts +2 -1
  155. package/dist/Presentation/Views/Dialog/Message/MessageAttachment/AudioAttachment/AudioAttachment.d.ts +1 -0
  156. package/dist/Presentation/Views/Dialog/Message/MessageAttachment/DefaultAttachment/DefaultAttachment.d.ts +1 -0
  157. package/dist/Presentation/Views/Dialog/Message/MessageAttachment/ImageAttachment/ImageAttachment.d.ts +1 -0
  158. package/dist/Presentation/Views/Dialog/Message/MessageAttachment/MessageAttachment.d.ts +2 -1
  159. package/dist/Presentation/Views/Dialog/Message/MessageAttachment/VideoAttachment/VideoAttachment.d.ts +1 -0
  160. package/dist/Presentation/Views/Dialog/Message/MessageContextMenu/MessageContextMenu.d.ts +1 -0
  161. package/dist/Presentation/Views/Dialog/Message/OutgoinForwardedMessage/OutgoinForwardedMessage.d.ts +1 -1
  162. package/dist/Presentation/Views/Dialog/Message/OutgoingMessage/OutgoingMessage.d.ts +2 -1
  163. package/dist/Presentation/Views/Dialog/Message/OutgoingRepliedMessage/OutgoingRepliedMessage.d.ts +1 -1
  164. package/dist/Presentation/Views/Dialog/MessageContextMenu/MessageContextMenu.d.ts +1 -0
  165. package/dist/Presentation/Views/Dialog/MessageItem/MessageItem.d.ts +1 -1
  166. package/dist/Presentation/Views/Dialog/SystemDateBanner/SystemDateBanner.d.ts +1 -0
  167. package/dist/Presentation/Views/Dialog/SystemMessageBanner/SystemMessageBanner.d.ts +1 -0
  168. package/dist/Presentation/Views/Dialog/VoiceMessage/VoiceMessage.d.ts +1 -1
  169. package/dist/Presentation/Views/Dialog/useDialogViewModel.d.ts +1 -0
  170. package/dist/Presentation/Views/DialogInfo/DialogInfo.d.ts +1 -1
  171. package/dist/Presentation/Views/DialogInfo/DialogMemberButton/DialogMembersButton.d.ts +1 -0
  172. package/dist/Presentation/Views/DialogInfo/MembersList/MembersList.d.ts +1 -0
  173. package/dist/Presentation/Views/DialogInfo/UsersList/SingleUser/SingleUser.d.ts +1 -0
  174. package/dist/Presentation/Views/DialogInfo/UsersList/UsersList.d.ts +1 -1
  175. package/dist/Presentation/Views/DialogInfo/UsersList/UsersListViewModel.d.ts +1 -0
  176. package/dist/Presentation/Views/DialogInfo/UsersList/useUsersListViewModel.d.ts +1 -0
  177. package/dist/Presentation/Views/DialogList/DialogList.d.ts +1 -1
  178. package/dist/Presentation/Views/DialogList/DialogListViewModel.d.ts +1 -0
  179. package/dist/Presentation/Views/DialogList/useDialogListViewModel.d.ts +1 -0
  180. package/dist/Presentation/Views/DialogListHeader/DialogListHeader.d.ts +1 -0
  181. package/dist/Presentation/Views/EditDialog/EditDialog.d.ts +1 -0
  182. package/dist/Presentation/Views/EditDialog/UserAvatar/UserAvatar.d.ts +1 -0
  183. package/dist/Presentation/Views/Flow/CreateDialog/CreateDialog.d.ts +1 -0
  184. package/dist/Presentation/Views/Flow/CreateDialogFlow/CreateNewDialogFlow.d.ts +1 -0
  185. package/dist/Presentation/Views/Flow/LeaveDialogFlow/LeaveDialogFlow.d.ts +1 -0
  186. package/dist/Presentation/Views/InviteMembers/InviteMembers.d.ts +1 -0
  187. package/dist/Presentation/Views/InviteMembers/InviteMembersViewModel.d.ts +1 -0
  188. package/dist/Presentation/Views/InviteMembers/InviteUsersList/SingleUserWithCheckBox/SingleUserWithCheckBox.d.ts +1 -0
  189. package/dist/Presentation/Views/InviteMembers/InviteUsersResultViewModel.d.ts +1 -0
  190. package/dist/Presentation/Views/InviteMembers/NotFoundContent/NotFoundContent.d.ts +1 -0
  191. package/dist/Presentation/Views/InviteMembers/useInviteMembersViewModel.d.ts +1 -0
  192. package/dist/Presentation/Views/PreviewDialog/PreviewDialog.d.ts +2 -1
  193. package/dist/Presentation/Views/PreviewDialog/PreviewDialogContextMenu/PreviewDialogContextMenu.d.ts +1 -0
  194. package/dist/Presentation/Views/PreviewDialog/PreviewDialogViewModel.d.ts +1 -0
  195. package/dist/Presentation/Views/YesNoQuestion/YesNoQuestion.d.ts +1 -0
  196. package/dist/Presentation/components/Navbar.d.ts +1 -0
  197. package/dist/Presentation/components/UI/Buttons/ActiveButton/ActiveButton.d.ts +1 -1
  198. package/dist/Presentation/components/UI/Buttons/MainBoundedButton/MainBoundedButton.d.ts +1 -1
  199. package/dist/Presentation/components/UI/Buttons/MainButton/MainButton.d.ts +1 -1
  200. package/dist/Presentation/components/UI/Elements/SwitchButton/SwitchButton.d.ts +1 -1
  201. package/dist/Presentation/components/UI/Placeholders/ErrorComponent/ErrorComponent.d.ts +1 -0
  202. package/dist/Presentation/components/UI/Placeholders/LoaderComponent/LoaderComponent.d.ts +1 -0
  203. package/dist/Presentation/components/UI/svgs/ActiveSvg/ActiveSvg.d.ts +1 -1
  204. package/dist/Presentation/components/UI/svgs/Icons/AIWidgets/AIWidget/index.d.ts +1 -0
  205. package/dist/Presentation/components/UI/svgs/Icons/AIWidgets/BookIcon/BookIcon.d.ts +1 -0
  206. package/dist/Presentation/components/UI/svgs/Icons/AIWidgets/BotIcon/BotIcon.d.ts +1 -0
  207. package/dist/Presentation/components/UI/svgs/Icons/AIWidgets/HammerIcon/index.d.ts +1 -0
  208. package/dist/Presentation/components/UI/svgs/Icons/AIWidgets/HandshakeIcon/index.d.ts +1 -0
  209. package/dist/Presentation/components/UI/svgs/Icons/AIWidgets/MuscleIcon/index.d.ts +1 -0
  210. package/dist/Presentation/components/UI/svgs/Icons/AIWidgets/NecktieIcon/index.d.ts +1 -0
  211. package/dist/Presentation/components/UI/svgs/Icons/AIWidgets/NeutralFaceIcon/index.d.ts +1 -0
  212. package/dist/Presentation/components/UI/svgs/Icons/AIWidgets/PalmsUpTogetherIcon/index.d.ts +1 -0
  213. package/dist/Presentation/components/UI/svgs/Icons/AIWidgets/PerformingArtsIcon/index.d.ts +1 -0
  214. package/dist/Presentation/components/UI/svgs/Icons/AIWidgets/PointUpIcon/index.d.ts +1 -0
  215. package/dist/Presentation/components/UI/svgs/Icons/AIWidgets/SmileyIcon/index.d.ts +1 -0
  216. package/dist/Presentation/components/UI/svgs/Icons/AIWidgets/SmirkIcon/index.d.ts +1 -0
  217. package/dist/Presentation/components/UI/svgs/Icons/AIWidgets/WhiteCheckMarkIcon/index.d.ts +1 -0
  218. package/dist/Presentation/components/UI/svgs/Icons/Actions/Add/index.d.ts +1 -0
  219. package/dist/Presentation/components/UI/svgs/Icons/Actions/AddContact/index.d.ts +1 -0
  220. package/dist/Presentation/components/UI/svgs/Icons/Actions/Archive/index.d.ts +1 -0
  221. package/dist/Presentation/components/UI/svgs/Icons/Actions/AssistAnswer/index.d.ts +1 -0
  222. package/dist/Presentation/components/UI/svgs/Icons/Actions/Copy/index.d.ts +1 -0
  223. package/dist/Presentation/components/UI/svgs/Icons/Actions/Delete/index.d.ts +1 -0
  224. package/dist/Presentation/components/UI/svgs/Icons/Actions/Download/index.d.ts +1 -0
  225. package/dist/Presentation/components/UI/svgs/Icons/Actions/Edit/index.d.ts +1 -0
  226. package/dist/Presentation/components/UI/svgs/Icons/Actions/EditDots/index.d.ts +1 -0
  227. package/dist/Presentation/components/UI/svgs/Icons/Actions/Emoji/index.d.ts +1 -0
  228. package/dist/Presentation/components/UI/svgs/Icons/Actions/ForwardFilled/index.d.ts +1 -0
  229. package/dist/Presentation/components/UI/svgs/Icons/Actions/Hungup/index.d.ts +1 -0
  230. package/dist/Presentation/components/UI/svgs/Icons/Actions/IncomeCall/index.d.ts +1 -0
  231. package/dist/Presentation/components/UI/svgs/Icons/Actions/Like/index.d.ts +1 -0
  232. package/dist/Presentation/components/UI/svgs/Icons/Actions/NewChat/index.d.ts +1 -0
  233. package/dist/Presentation/components/UI/svgs/Icons/Actions/OutcomeCall/index.d.ts +1 -0
  234. package/dist/Presentation/components/UI/svgs/Icons/Actions/Phone/index.d.ts +1 -0
  235. package/dist/Presentation/components/UI/svgs/Icons/Actions/PhoneFilled/index.d.ts +1 -0
  236. package/dist/Presentation/components/UI/svgs/Icons/Actions/Remove/index.d.ts +1 -0
  237. package/dist/Presentation/components/UI/svgs/Icons/Actions/Remove2/index.d.ts +1 -0
  238. package/dist/Presentation/components/UI/svgs/Icons/Actions/ReplyFilled/index.d.ts +1 -0
  239. package/dist/Presentation/components/UI/svgs/Icons/Actions/Send/index.d.ts +1 -0
  240. package/dist/Presentation/components/UI/svgs/Icons/Actions/Share/index.d.ts +1 -0
  241. package/dist/Presentation/components/UI/svgs/Icons/Actions/Summarize/index.d.ts +1 -0
  242. package/dist/Presentation/components/UI/svgs/Icons/Actions/SwapCamera/index.d.ts +1 -0
  243. package/dist/Presentation/components/UI/svgs/Icons/Actions/Tone/index.d.ts +1 -0
  244. package/dist/Presentation/components/UI/svgs/Icons/Actions/Unarchive/index.d.ts +1 -0
  245. package/dist/Presentation/components/UI/svgs/Icons/Actions/VideoIcon/index.d.ts +1 -0
  246. package/dist/Presentation/components/UI/svgs/Icons/Actions/Voice/index.d.ts +1 -0
  247. package/dist/Presentation/components/UI/svgs/Icons/Contents/Brodcast/index.d.ts +1 -0
  248. package/dist/Presentation/components/UI/svgs/Icons/Contents/Chat/index.d.ts +1 -0
  249. package/dist/Presentation/components/UI/svgs/Icons/Contents/ChatFilled/index.d.ts +1 -0
  250. package/dist/Presentation/components/UI/svgs/Icons/Contents/Conference/index.d.ts +1 -0
  251. package/dist/Presentation/components/UI/svgs/Icons/Contents/Contact/index.d.ts +1 -0
  252. package/dist/Presentation/components/UI/svgs/Icons/Contents/ContactFilled/index.d.ts +1 -0
  253. package/dist/Presentation/components/UI/svgs/Icons/Contents/GroupChat/index.d.ts +1 -0
  254. package/dist/Presentation/components/UI/svgs/Icons/Contents/Notifications/index.d.ts +1 -0
  255. package/dist/Presentation/components/UI/svgs/Icons/Contents/PrivateChat/index.d.ts +1 -0
  256. package/dist/Presentation/components/UI/svgs/Icons/Contents/PublicChannel/index.d.ts +1 -0
  257. package/dist/Presentation/components/UI/svgs/Icons/Contents/Stream/index.d.ts +1 -0
  258. package/dist/Presentation/components/UI/svgs/Icons/Contents/StreamFilled/index.d.ts +1 -0
  259. package/dist/Presentation/components/UI/svgs/Icons/Contents/User/index.d.ts +1 -0
  260. package/dist/Presentation/components/UI/svgs/Icons/IconsCommonTypes.d.ts +1 -0
  261. package/dist/Presentation/components/UI/svgs/Icons/Media/Attachment/index.d.ts +1 -0
  262. package/dist/Presentation/components/UI/svgs/Icons/Media/AudioFile/index.d.ts +1 -0
  263. package/dist/Presentation/components/UI/svgs/Icons/Media/BrokenFile/index.d.ts +1 -0
  264. package/dist/Presentation/components/UI/svgs/Icons/Media/Camera/index.d.ts +1 -0
  265. package/dist/Presentation/components/UI/svgs/Icons/Media/GifFile/index.d.ts +1 -0
  266. package/dist/Presentation/components/UI/svgs/Icons/Media/ImageEmpty/index.d.ts +1 -0
  267. package/dist/Presentation/components/UI/svgs/Icons/Media/ImageFile/index.d.ts +1 -0
  268. package/dist/Presentation/components/UI/svgs/Icons/Media/ImageFilled/index.d.ts +1 -0
  269. package/dist/Presentation/components/UI/svgs/Icons/Media/LinkWeb/index.d.ts +1 -0
  270. package/dist/Presentation/components/UI/svgs/Icons/Media/Location/index.d.ts +1 -0
  271. package/dist/Presentation/components/UI/svgs/Icons/Media/TextDocument/index.d.ts +1 -0
  272. package/dist/Presentation/components/UI/svgs/Icons/Media/Translate/index.d.ts +1 -0
  273. package/dist/Presentation/components/UI/svgs/Icons/Media/VideoFile/index.d.ts +1 -0
  274. package/dist/Presentation/components/UI/svgs/Icons/Moderation/Admin/index.d.ts +1 -0
  275. package/dist/Presentation/components/UI/svgs/Icons/Moderation/Banned/index.d.ts +1 -0
  276. package/dist/Presentation/components/UI/svgs/Icons/Moderation/Freeze/index.d.ts +1 -0
  277. package/dist/Presentation/components/UI/svgs/Icons/Moderation/Moderations/index.d.ts +1 -0
  278. package/dist/Presentation/components/UI/svgs/Icons/Moderation/Muted/index.d.ts +1 -0
  279. package/dist/Presentation/components/UI/svgs/Icons/Navigation/ArrowLeft/index.d.ts +1 -0
  280. package/dist/Presentation/components/UI/svgs/Icons/Navigation/ArrowRight/index.d.ts +1 -0
  281. package/dist/Presentation/components/UI/svgs/Icons/Navigation/Back/index.d.ts +1 -0
  282. package/dist/Presentation/components/UI/svgs/Icons/Navigation/Close/index.d.ts +1 -0
  283. package/dist/Presentation/components/UI/svgs/Icons/Navigation/Down/index.d.ts +1 -0
  284. package/dist/Presentation/components/UI/svgs/Icons/Navigation/Leave/index.d.ts +1 -0
  285. package/dist/Presentation/components/UI/svgs/Icons/Navigation/More/index.d.ts +1 -0
  286. package/dist/Presentation/components/UI/svgs/Icons/Navigation/Next/index.d.ts +1 -0
  287. package/dist/Presentation/components/UI/svgs/Icons/Navigation/Plus/index.d.ts +1 -0
  288. package/dist/Presentation/components/UI/svgs/Icons/Navigation/Refresh/index.d.ts +1 -0
  289. package/dist/Presentation/components/UI/svgs/Icons/Navigation/Search/index.d.ts +1 -0
  290. package/dist/Presentation/components/UI/svgs/Icons/Navigation/Settings/index.d.ts +1 -0
  291. package/dist/Presentation/components/UI/svgs/Icons/Navigation/SettingsField/index.d.ts +1 -0
  292. package/dist/Presentation/components/UI/svgs/Icons/Status/Error/index.d.ts +1 -0
  293. package/dist/Presentation/components/UI/svgs/Icons/Status/Help/index.d.ts +1 -0
  294. package/dist/Presentation/components/UI/svgs/Icons/Status/Information/index.d.ts +1 -0
  295. package/dist/Presentation/components/UI/svgs/Icons/Status/InformationFill/index.d.ts +1 -0
  296. package/dist/Presentation/components/UI/svgs/Icons/Status/Loader/index.d.ts +1 -0
  297. package/dist/Presentation/components/UI/svgs/Icons/Status/Mention/index.d.ts +1 -0
  298. package/dist/Presentation/components/UI/svgs/Icons/Status/Sent/index.d.ts +1 -0
  299. package/dist/Presentation/components/UI/svgs/Icons/Status/ViewedDelivered/index.d.ts +1 -0
  300. package/dist/Presentation/components/UI/svgs/Icons/Toggle/CameraOff/index.d.ts +1 -0
  301. package/dist/Presentation/components/UI/svgs/Icons/Toggle/CameraOn/index.d.ts +1 -0
  302. package/dist/Presentation/components/UI/svgs/Icons/Toggle/CheckOff/index.d.ts +1 -0
  303. package/dist/Presentation/components/UI/svgs/Icons/Toggle/CheckOn/index.d.ts +1 -0
  304. package/dist/Presentation/components/UI/svgs/Icons/Toggle/Favourite/index.d.ts +1 -0
  305. package/dist/Presentation/components/UI/svgs/Icons/Toggle/FavouriteFilled/index.d.ts +1 -0
  306. package/dist/Presentation/components/UI/svgs/Icons/Toggle/FullScreen/inex.d.ts +1 -0
  307. package/dist/Presentation/components/UI/svgs/Icons/Toggle/Hide/index.d.ts +1 -0
  308. package/dist/Presentation/components/UI/svgs/Icons/Toggle/ImagePlay/index.d.ts +1 -0
  309. package/dist/Presentation/components/UI/svgs/Icons/Toggle/Louder/index.d.ts +1 -0
  310. package/dist/Presentation/components/UI/svgs/Icons/Toggle/MicOff/index.d.ts +1 -0
  311. package/dist/Presentation/components/UI/svgs/Icons/Toggle/MicOn/index.d.ts +1 -0
  312. package/dist/Presentation/components/UI/svgs/Icons/Toggle/Minimize/index.d.ts +1 -0
  313. package/dist/Presentation/components/UI/svgs/Icons/Toggle/NotifyOff/index.d.ts +1 -0
  314. package/dist/Presentation/components/UI/svgs/Icons/Toggle/NotifyOn/index.d.ts +1 -0
  315. package/dist/Presentation/components/UI/svgs/Icons/Toggle/Pause/index.d.ts +1 -0
  316. package/dist/Presentation/components/UI/svgs/Icons/Toggle/Quite/index.d.ts +1 -0
  317. package/dist/Presentation/components/UI/svgs/Icons/Toggle/Record/index.d.ts +1 -0
  318. package/dist/Presentation/components/UI/svgs/Icons/Toggle/Screenshare/index.d.ts +1 -0
  319. package/dist/Presentation/components/UI/svgs/Icons/Toggle/Show/index.d.ts +1 -0
  320. package/dist/Presentation/components/UI/svgs/Icons/Toggle/Speaker/index.d.ts +1 -0
  321. package/dist/Presentation/components/UI/svgs/Icons/Toggle/SpeakerOff/index.d.ts +1 -0
  322. package/dist/Presentation/components/UI/svgs/Icons/Toggle/StopRecord/index.d.ts +1 -0
  323. package/dist/Presentation/components/UI/svgs/Icons/Toggle/StopShare/index.d.ts +1 -0
  324. package/dist/Presentation/components/containers/ColumnContainer/ColumnContainer.d.ts +1 -0
  325. package/dist/Presentation/components/containers/RowCenterContainer/RowCenterContainer.d.ts +1 -1
  326. package/dist/Presentation/components/containers/RowLeftContainer/RowLeftContainer.d.ts +1 -1
  327. package/dist/Presentation/components/containers/RowRightContainer/RowRightContainer.d.ts +1 -1
  328. package/dist/Presentation/components/containers/ScrollableContainer/ScrollableContainer.d.ts +1 -1
  329. package/dist/Presentation/components/containers/SectionList/hooks/createUseComponent.d.ts +1 -0
  330. package/dist/Presentation/components/containers/SectionList/hooks/index.d.ts +1 -0
  331. package/dist/Presentation/components/containers/SectionList/hooks/useMobileLayout.d.ts +1 -0
  332. package/dist/Presentation/components/containers/SectionList/hooks/usePrevious.d.ts +1 -0
  333. package/dist/Presentation/components/containers/SectionList/hooks/useVisibility.d.ts +1 -0
  334. package/dist/Presentation/components/containers/SectionList/index.d.ts +1 -0
  335. package/dist/Presentation/components/containers/SectionList/useComponent.d.ts +1 -1
  336. package/dist/Presentation/icons/actions/index.d.ts +1 -0
  337. package/dist/Presentation/icons/contents/index.d.ts +1 -0
  338. package/dist/Presentation/icons/index.d.ts +1 -0
  339. package/dist/Presentation/icons/media/index.d.ts +1 -0
  340. package/dist/Presentation/icons/moderation/index.d.ts +1 -0
  341. package/dist/Presentation/icons/navigation/index.d.ts +1 -0
  342. package/dist/Presentation/icons/status/index.d.ts +1 -0
  343. package/dist/Presentation/icons/toggle/index.d.ts +1 -0
  344. package/dist/Presentation/layouts/Desktop/DesktopLayout.d.ts +1 -1
  345. package/dist/Presentation/layouts/Desktop/QuickBloxUIKitDesktopLayout.d.ts +1 -0
  346. package/dist/Presentation/layouts/LayoutCommonTypes.d.ts +1 -1
  347. package/dist/Presentation/layouts/TestStage/CompanyLogo/CompanyLogo.d.ts +1 -1
  348. package/dist/Presentation/layouts/TestStage/LoginView/Login.d.ts +1 -0
  349. package/dist/Presentation/providers/ProviderProps.d.ts +1 -1
  350. package/dist/Presentation/providers/QuickBloxUIKitProvider/QuickBloxUIKitProvider.d.ts +1 -1
  351. package/dist/Presentation/providers/QuickBloxUIKitProvider/useEventMessagesRepository.d.ts +1 -0
  352. package/dist/Presentation/providers/QuickBloxUIKitProvider/useQBConnection.d.ts +1 -0
  353. package/dist/Presentation/providers/QuickBloxUIKitProvider/useQbInitializedDataContext.d.ts +1 -0
  354. package/dist/Presentation/providers/QuickBloxUIKitProvider/useQbUIKitDataContext.d.ts +1 -0
  355. package/dist/Presentation/themes/DarkTheme.d.ts +1 -0
  356. package/dist/Presentation/themes/DefaultThemes/CustomTheme.d.ts +1 -0
  357. package/dist/Presentation/themes/DefaultThemes/DefaultTheme.d.ts +1 -0
  358. package/dist/Presentation/themes/LightTheme.d.ts +1 -0
  359. package/dist/Presentation/themes/ThemeScheme.d.ts +1 -0
  360. package/dist/Presentation/themes/UiKitTheme.d.ts +1 -0
  361. package/dist/Presentation/ui-components/Avatar/Avatar.d.ts +1 -1
  362. package/dist/Presentation/ui-components/Badge/Badge.d.ts +1 -0
  363. package/dist/Presentation/ui-components/Badge/Badge.stories.d.ts +1 -0
  364. package/dist/Presentation/ui-components/Button/Button.d.ts +1 -1
  365. package/dist/Presentation/ui-components/Button/Button.stories.d.ts +1 -0
  366. package/dist/Presentation/ui-components/CheckBox/CheckBox.d.ts +1 -0
  367. package/dist/Presentation/ui-components/DialogBanner/DialogBanner.d.ts +1 -0
  368. package/dist/Presentation/ui-components/DialogBanner/DialogBanner.stories.d.ts +1 -0
  369. package/dist/Presentation/ui-components/DialogItemPreview/DialogItemPreview.d.ts +1 -1
  370. package/dist/Presentation/ui-components/DialogWindow/DialogWindow.d.ts +1 -1
  371. package/dist/Presentation/ui-components/Dropdown/Dropdown.d.ts +1 -1
  372. package/dist/Presentation/ui-components/Dropdown/DropdownOption.d.ts +1 -1
  373. package/dist/Presentation/ui-components/Header/Header.d.ts +1 -1
  374. package/dist/Presentation/ui-components/Loader/Loader.d.ts +1 -0
  375. package/dist/Presentation/ui-components/Loader/Loader.stories.d.ts +1 -0
  376. package/dist/Presentation/ui-components/Message/Bubble/AttachmentBubble/AttachmentBubble.d.ts +1 -0
  377. package/dist/Presentation/ui-components/Message/Bubble/AudioBubble/AudioBubble.d.ts +1 -0
  378. package/dist/Presentation/ui-components/Message/Bubble/FileBubble/FileBubble.d.ts +1 -0
  379. package/dist/Presentation/ui-components/Message/Bubble/ImageBubble/ImageBubble.d.ts +1 -0
  380. package/dist/Presentation/ui-components/Message/Bubble/TextBubble/TextBubble.d.ts +1 -0
  381. package/dist/Presentation/ui-components/Message/Bubble/VideoBubble/VideoBubble.d.ts +1 -0
  382. package/dist/Presentation/ui-components/Message/FileUrl/FileUrl.d.ts +1 -0
  383. package/dist/Presentation/ui-components/Message/Message.d.ts +1 -1
  384. package/dist/Presentation/ui-components/Message/MessageCaption/MessageCaption.d.ts +1 -0
  385. package/dist/Presentation/ui-components/Message/TimeAndStatus/TimeAndStatus.d.ts +1 -0
  386. package/dist/Presentation/ui-components/MessageInput/AttachmentUploader/AttachmentUploader.d.ts +1 -1
  387. package/dist/Presentation/ui-components/MessageInput/MessageInput.d.ts +1 -1
  388. package/dist/Presentation/ui-components/MessageInput/ReplyMessagePreview/ReplyImagePreviewAttachment/ReplyImagePreviewAttachment.d.ts +1 -0
  389. package/dist/Presentation/ui-components/MessageInput/ReplyMessagePreview/ReplyMessagePreview.d.ts +1 -0
  390. package/dist/Presentation/ui-components/MessageInput/VoiceRecordingProgress/VoiceRecordingProgress.d.ts +1 -0
  391. package/dist/Presentation/ui-components/MessageInput/VoiceRecordingProgress/VoiceRecordingProgress.d.ts.map +1 -1
  392. package/dist/Presentation/ui-components/MessageSeparator/MessageSeparator.d.ts +1 -0
  393. package/dist/Presentation/ui-components/MessageSeparator/MessageSeparator.stories.d.ts +1 -0
  394. package/dist/Presentation/ui-components/Placeholder/Placeholder.d.ts +1 -1
  395. package/dist/Presentation/ui-components/PreviewFileMessage/PreviewFileMessage.d.ts +1 -0
  396. package/dist/Presentation/ui-components/PreviewFileMessage/PreviewFileMessage.stories.d.ts +1 -0
  397. package/dist/Presentation/ui-components/SettingsItem/SettingsItem.d.ts +1 -1
  398. package/dist/Presentation/ui-components/TextField/TextField.d.ts +1 -1
  399. package/dist/Presentation/ui-components/TextField/TextField.stories.d.ts +1 -0
  400. package/dist/Presentation/ui-components/Toast/ToastProvider.d.ts +1 -1
  401. package/dist/Presentation/ui-components/UserListItem/UserListItem.d.ts +1 -0
  402. package/dist/Presentation/ui-components/index.d.ts +1 -0
  403. package/dist/QBconfig.d.ts +1 -0
  404. package/dist/hooks/useModal.d.ts +1 -0
  405. package/dist/hooks/useQuickBloxUIKit.d.ts +1 -1
  406. package/dist/index-ui.d.ts +1 -0
  407. package/dist/index-ui.js +43359 -58620
  408. package/dist/index.d.ts +1 -0
  409. package/dist/qb-api-calls/index.d.ts +1 -0
  410. package/dist/setupTests.d.ts +1 -0
  411. package/dist/utils/DateTimeFormatter.d.ts +1 -0
  412. package/dist/utils/formatFileSize.d.ts +1 -0
  413. package/dist/utils/parse.d.ts +1 -0
  414. package/dist/utils/utils.d.ts +1 -0
  415. package/package.json +14 -8
  416. package/src/Data/repository/ConnectionRepository.ts +3 -2
  417. package/src/Data/source/remote/Mapper/MessageDTOMapper.ts +39 -22
  418. package/src/Domain/use_cases/SyncDialogsUseCase.ts +3 -3
  419. package/src/Domain/use_cases/UserTypingMessageUseCase.ts +4 -2
  420. package/src/Presentation/ui-components/MessageInput/VoiceRecordingProgress/VoiceRecordingProgress.tsx +24 -8
  421. package/storybook-static/161.77e7dbc5.iframe.bundle.js +2 -0
  422. package/storybook-static/217.cb8da73c.iframe.bundle.js +408 -0
  423. package/storybook-static/217.cb8da73c.iframe.bundle.js.map +1 -0
  424. package/storybook-static/263.f039edee.iframe.bundle.js +2 -0
  425. package/storybook-static/294.7ed84cb5.iframe.bundle.js +1 -0
  426. package/storybook-static/338.ed5286bb.iframe.bundle.js +2 -0
  427. package/storybook-static/363.fe646024.iframe.bundle.js +2 -0
  428. package/storybook-static/{363.f6fcc1b9.iframe.bundle.js.LICENSE.txt → 363.fe646024.iframe.bundle.js.LICENSE.txt} +0 -7
  429. package/storybook-static/364.fb3fc9b4.iframe.bundle.js +1 -0
  430. package/storybook-static/488.a47f0de8.iframe.bundle.js +1 -0
  431. package/storybook-static/559.fdf11e08.iframe.bundle.js +2 -0
  432. package/storybook-static/618.ab5566c8.iframe.bundle.js +1 -0
  433. package/storybook-static/844.5804474b.iframe.bundle.js +95 -0
  434. package/storybook-static/844.5804474b.iframe.bundle.js.map +1 -0
  435. package/storybook-static/936.ba75ae44.iframe.bundle.js +1 -0
  436. package/storybook-static/Presentation-ui-components-Avatar-avatar-stories.6977856e.iframe.bundle.js +2 -0
  437. package/storybook-static/Presentation-ui-components-Badge-Badge-stories.d77c6500.iframe.bundle.js +2 -0
  438. package/storybook-static/Presentation-ui-components-Button-Button-stories.05f2f5b7.iframe.bundle.js +2 -0
  439. package/storybook-static/Presentation-ui-components-DialogBanner-DialogBanner-stories.118df514.iframe.bundle.js +1 -0
  440. package/storybook-static/Presentation-ui-components-DialogItemPreview-DialogItemPreview-stories.e9d3dc6b.iframe.bundle.js +2 -0
  441. package/storybook-static/Presentation-ui-components-DialogWindow-DialogWindow-stories.7d74bffa.iframe.bundle.js +2 -0
  442. package/storybook-static/Presentation-ui-components-Dropdown-Dropdown-stories.d92e6904.iframe.bundle.js +2 -0
  443. package/storybook-static/Presentation-ui-components-Header-Header-stories.b9a00187.iframe.bundle.js +2 -0
  444. package/storybook-static/Presentation-ui-components-Loader-Loader-stories.f484b131.iframe.bundle.js +2 -0
  445. package/storybook-static/Presentation-ui-components-Message-Message-stories.66867b7e.iframe.bundle.js +2 -0
  446. package/storybook-static/Presentation-ui-components-MessageInput-MessageInput-stories.d72f098b.iframe.bundle.js +1 -0
  447. package/storybook-static/Presentation-ui-components-MessageSeparator-MessageSeparator-stories.7d9e0991.iframe.bundle.js +1 -0
  448. package/storybook-static/Presentation-ui-components-Placeholder-Placeholder-stories.1e6bd1cd.iframe.bundle.js +2 -0
  449. package/storybook-static/Presentation-ui-components-PreviewFileMessage-PreviewFileMessage-stories.44c68c03.iframe.bundle.js +2 -0
  450. package/storybook-static/Presentation-ui-components-SettingsItem-SettingsItem-stories.3e87329b.iframe.bundle.js +2 -0
  451. package/storybook-static/Presentation-ui-components-TextField-TextField-stories.ec3e7d5f.iframe.bundle.js +2 -0
  452. package/storybook-static/Presentation-ui-components-Toast-Toast-stories.2721621c.iframe.bundle.js +1 -0
  453. package/storybook-static/Presentation-ui-components-UserListItem-UserListItem-stories.33b23eab.iframe.bundle.js +2 -0
  454. package/storybook-static/docs-Introduction-mdx.416f8bf9.iframe.bundle.js +1 -0
  455. package/storybook-static/docs-Styling-mdx.c119b271.iframe.bundle.js +1 -0
  456. package/storybook-static/iframe.html +5 -3
  457. package/storybook-static/main.bfaba8e3.iframe.bundle.js +1 -0
  458. package/storybook-static/project.json +1 -1
  459. package/storybook-static/runtime~main.b1ec3380.iframe.bundle.js +1 -0
  460. package/storybook-static/sb-addons/chromatic-com-storybook-10/manager-bundle.js +27 -27
  461. package/storybook-static/sb-addons/essentials-actions-3/manager-bundle.js +1 -1
  462. package/storybook-static/sb-addons/essentials-backgrounds-5/manager-bundle.js +1 -1
  463. package/storybook-static/sb-addons/essentials-controls-2/manager-bundle.js +74 -71
  464. package/storybook-static/sb-addons/essentials-docs-4/manager-bundle.js +73 -70
  465. package/storybook-static/sb-addons/essentials-viewport-6/manager-bundle.js +1 -1
  466. package/storybook-static/sb-addons/interactions-11/manager-bundle.js +6 -6
  467. package/storybook-static/sb-addons/onboarding-1/manager-bundle.js +18 -18
  468. package/storybook-static/sb-manager/globals-runtime.js +10691 -11043
  469. package/storybook-static/sb-preview/runtime.js +238 -238
  470. package/dist/Presentation/components/Button.d.ts +0 -4
  471. package/dist/Presentation/components/TextInput.d.ts +0 -1
  472. package/dist/Presentation/ui-components/Avatar/avatar.stories.d.ts +0 -8
  473. package/dist/Presentation/ui-components/DialogItemPreview/DialogItemPreview.stories.d.ts +0 -9
  474. package/dist/Presentation/ui-components/DialogWindow/DialogWindow.stories.d.ts +0 -6
  475. package/dist/Presentation/ui-components/Dropdown/Dropdown.stories.d.ts +0 -28
  476. package/dist/Presentation/ui-components/Header/Header.stories.d.ts +0 -9
  477. package/dist/Presentation/ui-components/Message/Message.stories.d.ts +0 -8
  478. package/dist/Presentation/ui-components/MessageInput/MessageInput.stories.d.ts +0 -8
  479. package/dist/Presentation/ui-components/Placeholder/Placeholder.stories.d.ts +0 -7
  480. package/dist/Presentation/ui-components/SettingsItem/SettingsItem.stories.d.ts +0 -8
  481. package/dist/Presentation/ui-components/Toast/Toast.stories.d.ts +0 -6
  482. package/dist/Presentation/ui-components/UserListItem/UserListItem.stories.d.ts +0 -86
  483. package/storybook-static/161.53da4e03.iframe.bundle.js +0 -2
  484. package/storybook-static/167.88fc69a9.iframe.bundle.js +0 -1
  485. package/storybook-static/217.f067a49f.iframe.bundle.js +0 -405
  486. package/storybook-static/217.f067a49f.iframe.bundle.js.map +0 -1
  487. package/storybook-static/294.b81cdbca.iframe.bundle.js +0 -1
  488. package/storybook-static/363.f6fcc1b9.iframe.bundle.js +0 -2
  489. package/storybook-static/364.988cd801.iframe.bundle.js +0 -1
  490. package/storybook-static/488.3cd3942e.iframe.bundle.js +0 -1
  491. package/storybook-static/559.9e64a6f5.iframe.bundle.js +0 -2
  492. package/storybook-static/735.6ee62079.iframe.bundle.js +0 -2
  493. package/storybook-static/844.be4346f2.iframe.bundle.js +0 -95
  494. package/storybook-static/844.be4346f2.iframe.bundle.js.map +0 -1
  495. package/storybook-static/936.8546c1d8.iframe.bundle.js +0 -1
  496. package/storybook-static/961.d47fc2bc.iframe.bundle.js +0 -2
  497. package/storybook-static/Presentation-ui-components-Avatar-avatar-stories.a5ba7608.iframe.bundle.js +0 -2
  498. package/storybook-static/Presentation-ui-components-Badge-Badge-stories.c8824861.iframe.bundle.js +0 -2
  499. package/storybook-static/Presentation-ui-components-Button-Button-stories.fa2aa72c.iframe.bundle.js +0 -2
  500. package/storybook-static/Presentation-ui-components-DialogBanner-DialogBanner-stories.cd797979.iframe.bundle.js +0 -1
  501. package/storybook-static/Presentation-ui-components-DialogItemPreview-DialogItemPreview-stories.b6998344.iframe.bundle.js +0 -2
  502. package/storybook-static/Presentation-ui-components-DialogWindow-DialogWindow-stories.46997cb0.iframe.bundle.js +0 -2
  503. package/storybook-static/Presentation-ui-components-Dropdown-Dropdown-stories.a03feb06.iframe.bundle.js +0 -2
  504. package/storybook-static/Presentation-ui-components-Header-Header-stories.a4edfcc6.iframe.bundle.js +0 -2
  505. package/storybook-static/Presentation-ui-components-Loader-Loader-stories.4e80520d.iframe.bundle.js +0 -2
  506. package/storybook-static/Presentation-ui-components-Message-Message-stories.213a90f6.iframe.bundle.js +0 -2
  507. package/storybook-static/Presentation-ui-components-MessageInput-MessageInput-stories.2af0de55.iframe.bundle.js +0 -1
  508. package/storybook-static/Presentation-ui-components-MessageSeparator-MessageSeparator-stories.b927d1e1.iframe.bundle.js +0 -1
  509. package/storybook-static/Presentation-ui-components-Placeholder-Placeholder-stories.34dfadb1.iframe.bundle.js +0 -2
  510. package/storybook-static/Presentation-ui-components-PreviewFileMessage-PreviewFileMessage-stories.9b4eff15.iframe.bundle.js +0 -2
  511. package/storybook-static/Presentation-ui-components-SettingsItem-SettingsItem-stories.e7f5a274.iframe.bundle.js +0 -2
  512. package/storybook-static/Presentation-ui-components-TextField-TextField-stories.969cfe2e.iframe.bundle.js +0 -2
  513. package/storybook-static/Presentation-ui-components-Toast-Toast-stories.4f00432b.iframe.bundle.js +0 -1
  514. package/storybook-static/Presentation-ui-components-UserListItem-UserListItem-stories.1713eab7.iframe.bundle.js +0 -2
  515. package/storybook-static/docs-Introduction-mdx.5addfa61.iframe.bundle.js +0 -1
  516. package/storybook-static/docs-Styling-mdx.9f4235f1.iframe.bundle.js +0 -1
  517. package/storybook-static/main.59f682e8.iframe.bundle.js +0 -1
  518. package/storybook-static/runtime~main.26de4dfd.iframe.bundle.js +0 -1
  519. /package/storybook-static/{161.53da4e03.iframe.bundle.js.LICENSE.txt → 161.77e7dbc5.iframe.bundle.js.LICENSE.txt} +0 -0
  520. /package/storybook-static/{217.f067a49f.iframe.bundle.js.LICENSE.txt → 217.cb8da73c.iframe.bundle.js.LICENSE.txt} +0 -0
  521. /package/storybook-static/{961.d47fc2bc.iframe.bundle.js.LICENSE.txt → 263.f039edee.iframe.bundle.js.LICENSE.txt} +0 -0
  522. /package/storybook-static/{735.6ee62079.iframe.bundle.js.LICENSE.txt → 338.ed5286bb.iframe.bundle.js.LICENSE.txt} +0 -0
  523. /package/storybook-static/{559.9e64a6f5.iframe.bundle.js.LICENSE.txt → 559.fdf11e08.iframe.bundle.js.LICENSE.txt} +0 -0
  524. /package/storybook-static/{844.be4346f2.iframe.bundle.js.LICENSE.txt → 844.5804474b.iframe.bundle.js.LICENSE.txt} +0 -0
  525. /package/storybook-static/{Presentation-ui-components-Avatar-avatar-stories.a5ba7608.iframe.bundle.js.LICENSE.txt → Presentation-ui-components-Avatar-avatar-stories.6977856e.iframe.bundle.js.LICENSE.txt} +0 -0
  526. /package/storybook-static/{Presentation-ui-components-Badge-Badge-stories.c8824861.iframe.bundle.js.LICENSE.txt → Presentation-ui-components-Badge-Badge-stories.d77c6500.iframe.bundle.js.LICENSE.txt} +0 -0
  527. /package/storybook-static/{Presentation-ui-components-Button-Button-stories.fa2aa72c.iframe.bundle.js.LICENSE.txt → Presentation-ui-components-Button-Button-stories.05f2f5b7.iframe.bundle.js.LICENSE.txt} +0 -0
  528. /package/storybook-static/{Presentation-ui-components-DialogItemPreview-DialogItemPreview-stories.b6998344.iframe.bundle.js.LICENSE.txt → Presentation-ui-components-DialogItemPreview-DialogItemPreview-stories.e9d3dc6b.iframe.bundle.js.LICENSE.txt} +0 -0
  529. /package/storybook-static/{Presentation-ui-components-DialogWindow-DialogWindow-stories.46997cb0.iframe.bundle.js.LICENSE.txt → Presentation-ui-components-DialogWindow-DialogWindow-stories.7d74bffa.iframe.bundle.js.LICENSE.txt} +0 -0
  530. /package/storybook-static/{Presentation-ui-components-Dropdown-Dropdown-stories.a03feb06.iframe.bundle.js.LICENSE.txt → Presentation-ui-components-Dropdown-Dropdown-stories.d92e6904.iframe.bundle.js.LICENSE.txt} +0 -0
  531. /package/storybook-static/{Presentation-ui-components-Header-Header-stories.a4edfcc6.iframe.bundle.js.LICENSE.txt → Presentation-ui-components-Header-Header-stories.b9a00187.iframe.bundle.js.LICENSE.txt} +0 -0
  532. /package/storybook-static/{Presentation-ui-components-Loader-Loader-stories.4e80520d.iframe.bundle.js.LICENSE.txt → Presentation-ui-components-Loader-Loader-stories.f484b131.iframe.bundle.js.LICENSE.txt} +0 -0
  533. /package/storybook-static/{Presentation-ui-components-Message-Message-stories.213a90f6.iframe.bundle.js.LICENSE.txt → Presentation-ui-components-Message-Message-stories.66867b7e.iframe.bundle.js.LICENSE.txt} +0 -0
  534. /package/storybook-static/{Presentation-ui-components-Placeholder-Placeholder-stories.34dfadb1.iframe.bundle.js.LICENSE.txt → Presentation-ui-components-Placeholder-Placeholder-stories.1e6bd1cd.iframe.bundle.js.LICENSE.txt} +0 -0
  535. /package/storybook-static/{Presentation-ui-components-PreviewFileMessage-PreviewFileMessage-stories.9b4eff15.iframe.bundle.js.LICENSE.txt → Presentation-ui-components-PreviewFileMessage-PreviewFileMessage-stories.44c68c03.iframe.bundle.js.LICENSE.txt} +0 -0
  536. /package/storybook-static/{Presentation-ui-components-SettingsItem-SettingsItem-stories.e7f5a274.iframe.bundle.js.LICENSE.txt → Presentation-ui-components-SettingsItem-SettingsItem-stories.3e87329b.iframe.bundle.js.LICENSE.txt} +0 -0
  537. /package/storybook-static/{Presentation-ui-components-TextField-TextField-stories.969cfe2e.iframe.bundle.js.LICENSE.txt → Presentation-ui-components-TextField-TextField-stories.ec3e7d5f.iframe.bundle.js.LICENSE.txt} +0 -0
  538. /package/storybook-static/{Presentation-ui-components-UserListItem-UserListItem-stories.1713eab7.iframe.bundle.js.LICENSE.txt → Presentation-ui-components-UserListItem-UserListItem-stories.33b23eab.iframe.bundle.js.LICENSE.txt} +0 -0
@@ -0,0 +1,2 @@
1
+ /*! For license information please see 363.fe646024.iframe.bundle.js.LICENSE.txt */
2
+ (self.webpackChunkquickblox_react_ui_kit=self.webpackChunkquickblox_react_ui_kit||[]).push([[363],{"./node_modules/classnames/index.js"(module,exports){var __WEBPACK_AMD_DEFINE_RESULT__;!function(){"use strict";var hasOwn={}.hasOwnProperty;function classNames(){for(var classes="",i=0;i<arguments.length;i++){var arg=arguments[i];arg&&(classes=appendClass(classes,parseValue(arg)))}return classes}function parseValue(arg){if("string"==typeof arg||"number"==typeof arg)return arg;if("object"!=typeof arg)return"";if(Array.isArray(arg))return classNames.apply(null,arg);if(arg.toString!==Object.prototype.toString&&!arg.toString.toString().includes("[native code]"))return arg.toString();var classes="";for(var key in arg)hasOwn.call(arg,key)&&arg[key]&&(classes=appendClass(classes,key));return classes}function appendClass(value,newClass){return newClass?value?value+" "+newClass:value+newClass:value}module.exports?(classNames.default=classNames,module.exports=classNames):void 0===(__WEBPACK_AMD_DEFINE_RESULT__=function(){return classNames}.apply(exports,[]))||(module.exports=__WEBPACK_AMD_DEFINE_RESULT__)}()},"./node_modules/quickblox/quickblox.js"(module,__unused_webpack_exports,__webpack_require__){var define;module.exports=function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){if(!f&&__webpack_require__("./node_modules/quickblox sync recursive"))return require(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){return o(e[i][1][r]||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u=void 0,i=0;i<t.length;i++)o(t[i]);return o}return r}()({1:[function(require,module,exports){"use strict";function find(list,predicate,ac){if(void 0===ac&&(ac=Array.prototype),list&&"function"==typeof ac.find)return ac.find.call(list,predicate);for(var i=0;i<list.length;i++)if(Object.prototype.hasOwnProperty.call(list,i)){var item=list[i];if(predicate.call(void 0,item,i,list))return item}}function freeze(object,oc){return void 0===oc&&(oc=Object),oc&&"function"==typeof oc.freeze?oc.freeze(object):object}function assign(target,source){if(null===target||"object"!=typeof target)throw new TypeError("target is not an object");for(var key in source)Object.prototype.hasOwnProperty.call(source,key)&&(target[key]=source[key]);return target}var MIME_TYPE=freeze({HTML:"text/html",isHTML:function(value){return value===MIME_TYPE.HTML},XML_APPLICATION:"application/xml",XML_TEXT:"text/xml",XML_XHTML_APPLICATION:"application/xhtml+xml",XML_SVG_IMAGE:"image/svg+xml"}),NAMESPACE=freeze({HTML:"http://www.w3.org/1999/xhtml",isHTML:function(uri){return uri===NAMESPACE.HTML},SVG:"http://www.w3.org/2000/svg",XML:"http://www.w3.org/XML/1998/namespace",XMLNS:"http://www.w3.org/2000/xmlns/"});exports.assign=assign,exports.find=find,exports.freeze=freeze,exports.MIME_TYPE=MIME_TYPE,exports.NAMESPACE=NAMESPACE},{}],2:[function(require,module,exports){var conventions=require("./conventions"),dom=require("./dom"),entities=require("./entities"),sax=require("./sax"),DOMImplementation=dom.DOMImplementation,NAMESPACE=conventions.NAMESPACE,ParseError=sax.ParseError,XMLReader=sax.XMLReader;function normalizeLineEndings(input){return input.replace(/\r[\n\u0085]/g,"\n").replace(/[\r\u0085\u2028]/g,"\n")}function DOMParser(options){this.options=options||{locator:{}}}function buildErrorHandler(errorImpl,domBuilder,locator){if(!errorImpl){if(domBuilder instanceof DOMHandler)return domBuilder;errorImpl=domBuilder}var errorHandler={},isCallback=errorImpl instanceof Function;function build(key){var fn=errorImpl[key];!fn&&isCallback&&(fn=2==errorImpl.length?function(msg){errorImpl(key,msg)}:errorImpl),errorHandler[key]=fn&&function(msg){fn("[xmldom "+key+"]\t"+msg+_locator(locator))}||function(){}}return locator=locator||{},build("warning"),build("error"),build("fatalError"),errorHandler}function DOMHandler(){this.cdata=!1}function position(locator,node){node.lineNumber=locator.lineNumber,node.columnNumber=locator.columnNumber}function _locator(l){if(l)return"\n@"+(l.systemId||"")+"#[line:"+l.lineNumber+",col:"+l.columnNumber+"]"}function _toString(chars,start,length){return"string"==typeof chars?chars.substr(start,length):chars.length>=start+length||start?new java.lang.String(chars,start,length)+"":chars}function appendElement(hander,node){hander.currentElement?hander.currentElement.appendChild(node):hander.doc.appendChild(node)}DOMParser.prototype.parseFromString=function(source,mimeType){var options=this.options,sax=new XMLReader,domBuilder=options.domBuilder||new DOMHandler,errorHandler=options.errorHandler,locator=options.locator,defaultNSMap=options.xmlns||{},isHTML=/\/x?html?$/.test(mimeType),entityMap=isHTML?entities.HTML_ENTITIES:entities.XML_ENTITIES;locator&&domBuilder.setDocumentLocator(locator),sax.errorHandler=buildErrorHandler(errorHandler,domBuilder,locator),sax.domBuilder=options.domBuilder||domBuilder,isHTML&&(defaultNSMap[""]=NAMESPACE.HTML),defaultNSMap.xml=defaultNSMap.xml||NAMESPACE.XML;var normalize=options.normalizeLineEndings||normalizeLineEndings;return source&&"string"==typeof source?sax.parse(normalize(source),defaultNSMap,entityMap):sax.errorHandler.error("invalid doc source"),domBuilder.doc},DOMHandler.prototype={startDocument:function(){this.doc=(new DOMImplementation).createDocument(null,null,null),this.locator&&(this.doc.documentURI=this.locator.systemId)},startElement:function(namespaceURI,localName,qName,attrs){var doc=this.doc,el=doc.createElementNS(namespaceURI,qName||localName),len=attrs.length;appendElement(this,el),this.currentElement=el,this.locator&&position(this.locator,el);for(var i=0;i<len;i++){namespaceURI=attrs.getURI(i);var value=attrs.getValue(i),attr=(qName=attrs.getQName(i),doc.createAttributeNS(namespaceURI,qName));this.locator&&position(attrs.getLocator(i),attr),attr.value=attr.nodeValue=value,el.setAttributeNode(attr)}},endElement:function(namespaceURI,localName,qName){var current=this.currentElement;current.tagName,this.currentElement=current.parentNode},startPrefixMapping:function(prefix,uri){},endPrefixMapping:function(prefix){},processingInstruction:function(target,data){var ins=this.doc.createProcessingInstruction(target,data);this.locator&&position(this.locator,ins),appendElement(this,ins)},ignorableWhitespace:function(ch,start,length){},characters:function(chars,start,length){if(chars=_toString.apply(this,arguments)){if(this.cdata)var charNode=this.doc.createCDATASection(chars);else charNode=this.doc.createTextNode(chars);this.currentElement?this.currentElement.appendChild(charNode):/^\s*$/.test(chars)&&this.doc.appendChild(charNode),this.locator&&position(this.locator,charNode)}},skippedEntity:function(name){},endDocument:function(){this.doc.normalize()},setDocumentLocator:function(locator){(this.locator=locator)&&(locator.lineNumber=0)},comment:function(chars,start,length){chars=_toString.apply(this,arguments);var comm=this.doc.createComment(chars);this.locator&&position(this.locator,comm),appendElement(this,comm)},startCDATA:function(){this.cdata=!0},endCDATA:function(){this.cdata=!1},startDTD:function(name,publicId,systemId){var impl=this.doc.implementation;if(impl&&impl.createDocumentType){var dt=impl.createDocumentType(name,publicId,systemId);this.locator&&position(this.locator,dt),appendElement(this,dt),this.doc.doctype=dt}},warning:function(error){console.warn("[xmldom warning]\t"+error,_locator(this.locator))},error:function(error){console.error("[xmldom error]\t"+error,_locator(this.locator))},fatalError:function(error){throw new ParseError(error,this.locator)}},"endDTD,startEntity,endEntity,attributeDecl,elementDecl,externalEntityDecl,internalEntityDecl,resolveEntity,getExternalSubset,notationDecl,unparsedEntityDecl".replace(/\w+/g,function(key){DOMHandler.prototype[key]=function(){return null}}),exports.__DOMHandler=DOMHandler,exports.normalizeLineEndings=normalizeLineEndings,exports.DOMParser=DOMParser},{"./conventions":1,"./dom":3,"./entities":4,"./sax":6}],3:[function(require,module,exports){var conventions=require("./conventions"),find=conventions.find,NAMESPACE=conventions.NAMESPACE;function notEmptyString(input){return""!==input}function splitOnASCIIWhitespace(input){return input?input.split(/[\t\n\f\r ]+/).filter(notEmptyString):[]}function orderedSetReducer(current,element){return current.hasOwnProperty(element)||(current[element]=!0),current}function toOrderedSet(input){if(!input)return[];var list=splitOnASCIIWhitespace(input);return Object.keys(list.reduce(orderedSetReducer,{}))}function arrayIncludes(list){return function(element){return list&&-1!==list.indexOf(element)}}function copy(src,dest){for(var p in src)Object.prototype.hasOwnProperty.call(src,p)&&(dest[p]=src[p])}function _extends(Class,Super){var pt=Class.prototype;if(!(pt instanceof Super)){function t(){}t.prototype=Super.prototype,copy(pt,t=new t),Class.prototype=pt=t}pt.constructor!=Class&&("function"!=typeof Class&&console.error("unknown Class:"+Class),pt.constructor=Class)}var NodeType={},ELEMENT_NODE=NodeType.ELEMENT_NODE=1,ATTRIBUTE_NODE=NodeType.ATTRIBUTE_NODE=2,TEXT_NODE=NodeType.TEXT_NODE=3,CDATA_SECTION_NODE=NodeType.CDATA_SECTION_NODE=4,ENTITY_REFERENCE_NODE=NodeType.ENTITY_REFERENCE_NODE=5,ENTITY_NODE=NodeType.ENTITY_NODE=6,PROCESSING_INSTRUCTION_NODE=NodeType.PROCESSING_INSTRUCTION_NODE=7,COMMENT_NODE=NodeType.COMMENT_NODE=8,DOCUMENT_NODE=NodeType.DOCUMENT_NODE=9,DOCUMENT_TYPE_NODE=NodeType.DOCUMENT_TYPE_NODE=10,DOCUMENT_FRAGMENT_NODE=NodeType.DOCUMENT_FRAGMENT_NODE=11,NOTATION_NODE=NodeType.NOTATION_NODE=12,ExceptionCode={},ExceptionMessage={},HIERARCHY_REQUEST_ERR=(ExceptionCode.INDEX_SIZE_ERR=(ExceptionMessage[1]="Index size error",1),ExceptionCode.DOMSTRING_SIZE_ERR=(ExceptionMessage[2]="DOMString size error",2),ExceptionCode.HIERARCHY_REQUEST_ERR=(ExceptionMessage[3]="Hierarchy request error",3)),NOT_FOUND_ERR=(ExceptionCode.WRONG_DOCUMENT_ERR=(ExceptionMessage[4]="Wrong document",4),ExceptionCode.INVALID_CHARACTER_ERR=(ExceptionMessage[5]="Invalid character",5),ExceptionCode.NO_DATA_ALLOWED_ERR=(ExceptionMessage[6]="No data allowed",6),ExceptionCode.NO_MODIFICATION_ALLOWED_ERR=(ExceptionMessage[7]="No modification allowed",7),ExceptionCode.NOT_FOUND_ERR=(ExceptionMessage[8]="Not found",8)),INUSE_ATTRIBUTE_ERR=(ExceptionCode.NOT_SUPPORTED_ERR=(ExceptionMessage[9]="Not supported",9),ExceptionCode.INUSE_ATTRIBUTE_ERR=(ExceptionMessage[10]="Attribute in use",10));function DOMException(code,message){if(message instanceof Error)var error=message;else error=this,Error.call(this,ExceptionMessage[code]),this.message=ExceptionMessage[code],Error.captureStackTrace&&Error.captureStackTrace(this,DOMException);return error.code=code,message&&(this.message=this.message+": "+message),error}function NodeList(){}function LiveNodeList(node,refresh){this._node=node,this._refresh=refresh,_updateLiveList(this)}function _updateLiveList(list){var inc=list._node._inc||list._node.ownerDocument._inc;if(list._inc!=inc){var ls=list._refresh(list._node);__set__(list,"length",ls.length),copy(ls,list),list._inc=inc}}function NamedNodeMap(){}function _findNodeIndex(list,node){for(var i=list.length;i--;)if(list[i]===node)return i}function _addNamedNode(el,list,newAttr,oldAttr){if(oldAttr?list[_findNodeIndex(list,oldAttr)]=newAttr:list[list.length++]=newAttr,el){newAttr.ownerElement=el;var doc=el.ownerDocument;doc&&(oldAttr&&_onRemoveAttribute(doc,el,oldAttr),_onAddAttribute(doc,el,newAttr))}}function _removeNamedNode(el,list,attr){var i=_findNodeIndex(list,attr);if(!(i>=0))throw new DOMException(NOT_FOUND_ERR,new Error(el.tagName+"@"+attr));for(var lastIndex=list.length-1;i<lastIndex;)list[i]=list[++i];if(list.length=lastIndex,el){var doc=el.ownerDocument;doc&&(_onRemoveAttribute(doc,el,attr),attr.ownerElement=null)}}function DOMImplementation(){}function Node(){}function _xmlEncoder(c){return("<"==c?"&lt;":">"==c&&"&gt;")||"&"==c&&"&amp;"||'"'==c&&"&quot;"||"&#"+c.charCodeAt()+";"}function _visitNode(node,callback){if(callback(node))return!0;if(node=node.firstChild)do{if(_visitNode(node,callback))return!0}while(node=node.nextSibling)}function Document(){this.ownerDocument=this}function _onAddAttribute(doc,el,newAttr){doc&&doc._inc++,newAttr.namespaceURI===NAMESPACE.XMLNS&&(el._nsMap[newAttr.prefix?newAttr.localName:""]=newAttr.value)}function _onRemoveAttribute(doc,el,newAttr,remove){doc&&doc._inc++,newAttr.namespaceURI===NAMESPACE.XMLNS&&delete el._nsMap[newAttr.prefix?newAttr.localName:""]}function _onUpdateChild(doc,el,newChild){if(doc&&doc._inc){doc._inc++;var cs=el.childNodes;if(newChild)cs[cs.length++]=newChild;else{for(var child=el.firstChild,i=0;child;)cs[i++]=child,child=child.nextSibling;cs.length=i,delete cs[cs.length]}}}function _removeChild(parentNode,child){var previous=child.previousSibling,next=child.nextSibling;return previous?previous.nextSibling=next:parentNode.firstChild=next,next?next.previousSibling=previous:parentNode.lastChild=previous,child.parentNode=null,child.previousSibling=null,child.nextSibling=null,_onUpdateChild(parentNode.ownerDocument,parentNode),child}function hasValidParentNodeType(node){return node&&(node.nodeType===Node.DOCUMENT_NODE||node.nodeType===Node.DOCUMENT_FRAGMENT_NODE||node.nodeType===Node.ELEMENT_NODE)}function hasInsertableNodeType(node){return node&&(isElementNode(node)||isTextNode(node)||isDocTypeNode(node)||node.nodeType===Node.DOCUMENT_FRAGMENT_NODE||node.nodeType===Node.COMMENT_NODE||node.nodeType===Node.PROCESSING_INSTRUCTION_NODE)}function isDocTypeNode(node){return node&&node.nodeType===Node.DOCUMENT_TYPE_NODE}function isElementNode(node){return node&&node.nodeType===Node.ELEMENT_NODE}function isTextNode(node){return node&&node.nodeType===Node.TEXT_NODE}function isElementInsertionPossible(doc,child){var parentChildNodes=doc.childNodes||[];if(find(parentChildNodes,isElementNode)||isDocTypeNode(child))return!1;var docTypeNode=find(parentChildNodes,isDocTypeNode);return!(child&&docTypeNode&&parentChildNodes.indexOf(docTypeNode)>parentChildNodes.indexOf(child))}function isElementReplacementPossible(doc,child){var parentChildNodes=doc.childNodes||[];function hasElementChildThatIsNotChild(node){return isElementNode(node)&&node!==child}if(find(parentChildNodes,hasElementChildThatIsNotChild))return!1;var docTypeNode=find(parentChildNodes,isDocTypeNode);return!(child&&docTypeNode&&parentChildNodes.indexOf(docTypeNode)>parentChildNodes.indexOf(child))}function assertPreInsertionValidity1to5(parent,node,child){if(!hasValidParentNodeType(parent))throw new DOMException(HIERARCHY_REQUEST_ERR,"Unexpected parent node type "+parent.nodeType);if(child&&child.parentNode!==parent)throw new DOMException(NOT_FOUND_ERR,"child not in parent");if(!hasInsertableNodeType(node)||isDocTypeNode(node)&&parent.nodeType!==Node.DOCUMENT_NODE)throw new DOMException(HIERARCHY_REQUEST_ERR,"Unexpected node type "+node.nodeType+" for parent node type "+parent.nodeType)}function assertPreInsertionValidityInDocument(parent,node,child){var parentChildNodes=parent.childNodes||[],nodeChildNodes=node.childNodes||[];if(node.nodeType===Node.DOCUMENT_FRAGMENT_NODE){var nodeChildElements=nodeChildNodes.filter(isElementNode);if(nodeChildElements.length>1||find(nodeChildNodes,isTextNode))throw new DOMException(HIERARCHY_REQUEST_ERR,"More than one element or text in fragment");if(1===nodeChildElements.length&&!isElementInsertionPossible(parent,child))throw new DOMException(HIERARCHY_REQUEST_ERR,"Element in fragment can not be inserted before doctype")}if(isElementNode(node)&&!isElementInsertionPossible(parent,child))throw new DOMException(HIERARCHY_REQUEST_ERR,"Only one element can be added and only after doctype");if(isDocTypeNode(node)){if(find(parentChildNodes,isDocTypeNode))throw new DOMException(HIERARCHY_REQUEST_ERR,"Only one doctype is allowed");var parentElementChild=find(parentChildNodes,isElementNode);if(child&&parentChildNodes.indexOf(parentElementChild)<parentChildNodes.indexOf(child))throw new DOMException(HIERARCHY_REQUEST_ERR,"Doctype can only be inserted before an element");if(!child&&parentElementChild)throw new DOMException(HIERARCHY_REQUEST_ERR,"Doctype can not be appended since element is present")}}function assertPreReplacementValidityInDocument(parent,node,child){var parentChildNodes=parent.childNodes||[],nodeChildNodes=node.childNodes||[];if(node.nodeType===Node.DOCUMENT_FRAGMENT_NODE){var nodeChildElements=nodeChildNodes.filter(isElementNode);if(nodeChildElements.length>1||find(nodeChildNodes,isTextNode))throw new DOMException(HIERARCHY_REQUEST_ERR,"More than one element or text in fragment");if(1===nodeChildElements.length&&!isElementReplacementPossible(parent,child))throw new DOMException(HIERARCHY_REQUEST_ERR,"Element in fragment can not be inserted before doctype")}if(isElementNode(node)&&!isElementReplacementPossible(parent,child))throw new DOMException(HIERARCHY_REQUEST_ERR,"Only one element can be added and only after doctype");if(isDocTypeNode(node)){function hasDoctypeChildThatIsNotChild(node){return isDocTypeNode(node)&&node!==child}if(find(parentChildNodes,hasDoctypeChildThatIsNotChild))throw new DOMException(HIERARCHY_REQUEST_ERR,"Only one doctype is allowed");var parentElementChild=find(parentChildNodes,isElementNode);if(child&&parentChildNodes.indexOf(parentElementChild)<parentChildNodes.indexOf(child))throw new DOMException(HIERARCHY_REQUEST_ERR,"Doctype can only be inserted before an element")}}function _insertBefore(parent,node,child,_inDocumentAssertion){assertPreInsertionValidity1to5(parent,node,child),parent.nodeType===Node.DOCUMENT_NODE&&(_inDocumentAssertion||assertPreInsertionValidityInDocument)(parent,node,child);var cp=node.parentNode;if(cp&&cp.removeChild(node),node.nodeType===DOCUMENT_FRAGMENT_NODE){var newFirst=node.firstChild;if(null==newFirst)return node;var newLast=node.lastChild}else newFirst=newLast=node;var pre=child?child.previousSibling:parent.lastChild;newFirst.previousSibling=pre,newLast.nextSibling=child,pre?pre.nextSibling=newFirst:parent.firstChild=newFirst,null==child?parent.lastChild=newLast:child.previousSibling=newLast;do{newFirst.parentNode=parent}while(newFirst!==newLast&&(newFirst=newFirst.nextSibling));return _onUpdateChild(parent.ownerDocument||parent,parent),node.nodeType==DOCUMENT_FRAGMENT_NODE&&(node.firstChild=node.lastChild=null),node}function _appendSingleChild(parentNode,newChild){return newChild.parentNode&&newChild.parentNode.removeChild(newChild),newChild.parentNode=parentNode,newChild.previousSibling=parentNode.lastChild,newChild.nextSibling=null,newChild.previousSibling?newChild.previousSibling.nextSibling=newChild:parentNode.firstChild=newChild,parentNode.lastChild=newChild,_onUpdateChild(parentNode.ownerDocument,parentNode,newChild),newChild}function Element(){this._nsMap={}}function Attr(){}function CharacterData(){}function Text(){}function Comment(){}function CDATASection(){}function DocumentType(){}function Notation(){}function Entity(){}function EntityReference(){}function DocumentFragment(){}function ProcessingInstruction(){}function XMLSerializer(){}function nodeSerializeToString(isHtml,nodeFilter){var buf=[],refNode=9==this.nodeType&&this.documentElement||this,prefix=refNode.prefix,uri=refNode.namespaceURI;if(uri&&null==prefix&&null==(prefix=refNode.lookupPrefix(uri)))var visibleNamespaces=[{namespace:uri,prefix:null}];return serializeToString(this,buf,isHtml,nodeFilter,visibleNamespaces),buf.join("")}function needNamespaceDefine(node,isHTML,visibleNamespaces){var prefix=node.prefix||"",uri=node.namespaceURI;if(!uri)return!1;if("xml"===prefix&&uri===NAMESPACE.XML||uri===NAMESPACE.XMLNS)return!1;for(var i=visibleNamespaces.length;i--;){var ns=visibleNamespaces[i];if(ns.prefix===prefix)return ns.namespace!==uri}return!0}function addSerializedAttribute(buf,qualifiedName,value){buf.push(" ",qualifiedName,'="',value.replace(/[<>&"\t\n\r]/g,_xmlEncoder),'"')}function serializeToString(node,buf,isHTML,nodeFilter,visibleNamespaces){if(visibleNamespaces||(visibleNamespaces=[]),nodeFilter){if(!(node=nodeFilter(node)))return;if("string"==typeof node)return void buf.push(node)}switch(node.nodeType){case ELEMENT_NODE:var attrs=node.attributes,len=attrs.length,child=node.firstChild,nodeName=node.tagName,prefixedNodeName=nodeName;if(!(isHTML=NAMESPACE.isHTML(node.namespaceURI)||isHTML)&&!node.prefix&&node.namespaceURI){for(var defaultNS,ai=0;ai<attrs.length;ai++)if("xmlns"===attrs.item(ai).name){defaultNS=attrs.item(ai).value;break}if(!defaultNS)for(var nsi=visibleNamespaces.length-1;nsi>=0;nsi--)if(""===(namespace=visibleNamespaces[nsi]).prefix&&namespace.namespace===node.namespaceURI){defaultNS=namespace.namespace;break}if(defaultNS!==node.namespaceURI)for(nsi=visibleNamespaces.length-1;nsi>=0;nsi--){var namespace;if((namespace=visibleNamespaces[nsi]).namespace===node.namespaceURI){namespace.prefix&&(prefixedNodeName=namespace.prefix+":"+nodeName);break}}}buf.push("<",prefixedNodeName);for(var i=0;i<len;i++)"xmlns"==(attr=attrs.item(i)).prefix?visibleNamespaces.push({prefix:attr.localName,namespace:attr.value}):"xmlns"==attr.nodeName&&visibleNamespaces.push({prefix:"",namespace:attr.value});for(i=0;i<len;i++){var attr,prefix,uri;needNamespaceDefine(attr=attrs.item(i),isHTML,visibleNamespaces)&&(addSerializedAttribute(buf,(prefix=attr.prefix||"")?"xmlns:"+prefix:"xmlns",uri=attr.namespaceURI),visibleNamespaces.push({prefix,namespace:uri})),serializeToString(attr,buf,isHTML,nodeFilter,visibleNamespaces)}if(nodeName===prefixedNodeName&&needNamespaceDefine(node,isHTML,visibleNamespaces)&&(addSerializedAttribute(buf,(prefix=node.prefix||"")?"xmlns:"+prefix:"xmlns",uri=node.namespaceURI),visibleNamespaces.push({prefix,namespace:uri})),child||isHTML&&!/^(?:meta|link|img|br|hr|input)$/i.test(nodeName)){if(buf.push(">"),isHTML&&/^script$/i.test(nodeName))for(;child;)child.data?buf.push(child.data):serializeToString(child,buf,isHTML,nodeFilter,visibleNamespaces.slice()),child=child.nextSibling;else for(;child;)serializeToString(child,buf,isHTML,nodeFilter,visibleNamespaces.slice()),child=child.nextSibling;buf.push("</",prefixedNodeName,">")}else buf.push("/>");return;case DOCUMENT_NODE:case DOCUMENT_FRAGMENT_NODE:for(child=node.firstChild;child;)serializeToString(child,buf,isHTML,nodeFilter,visibleNamespaces.slice()),child=child.nextSibling;return;case ATTRIBUTE_NODE:return addSerializedAttribute(buf,node.name,node.value);case TEXT_NODE:return buf.push(node.data.replace(/[<&>]/g,_xmlEncoder));case CDATA_SECTION_NODE:return buf.push("<![CDATA[",node.data,"]]>");case COMMENT_NODE:return buf.push("\x3c!--",node.data,"--\x3e");case DOCUMENT_TYPE_NODE:var pubid=node.publicId,sysid=node.systemId;if(buf.push("<!DOCTYPE ",node.name),pubid)buf.push(" PUBLIC ",pubid),sysid&&"."!=sysid&&buf.push(" ",sysid),buf.push(">");else if(sysid&&"."!=sysid)buf.push(" SYSTEM ",sysid,">");else{var sub=node.internalSubset;sub&&buf.push(" [",sub,"]"),buf.push(">")}return;case PROCESSING_INSTRUCTION_NODE:return buf.push("<?",node.target," ",node.data,"?>");case ENTITY_REFERENCE_NODE:return buf.push("&",node.nodeName,";");default:buf.push("??",node.nodeName)}}function importNode(doc,node,deep){var node2;switch(node.nodeType){case ELEMENT_NODE:(node2=node.cloneNode(!1)).ownerDocument=doc;case DOCUMENT_FRAGMENT_NODE:break;case ATTRIBUTE_NODE:deep=!0}if(node2||(node2=node.cloneNode(!1)),node2.ownerDocument=doc,node2.parentNode=null,deep)for(var child=node.firstChild;child;)node2.appendChild(importNode(doc,child,deep)),child=child.nextSibling;return node2}function cloneNode(doc,node,deep){var node2=new node.constructor;for(var n in node)if(Object.prototype.hasOwnProperty.call(node,n)){var v=node[n];"object"!=typeof v&&v!=node2[n]&&(node2[n]=v)}switch(node.childNodes&&(node2.childNodes=new NodeList),node2.ownerDocument=doc,node2.nodeType){case ELEMENT_NODE:var attrs=node.attributes,attrs2=node2.attributes=new NamedNodeMap,len=attrs.length;attrs2._ownerElement=node2;for(var i=0;i<len;i++)node2.setAttributeNode(cloneNode(doc,attrs.item(i),!0));break;case ATTRIBUTE_NODE:deep=!0}if(deep)for(var child=node.firstChild;child;)node2.appendChild(cloneNode(doc,child,deep)),child=child.nextSibling;return node2}function __set__(object,key,value){object[key]=value}ExceptionCode.INVALID_STATE_ERR=(ExceptionMessage[11]="Invalid state",11),ExceptionCode.SYNTAX_ERR=(ExceptionMessage[12]="Syntax error",12),ExceptionCode.INVALID_MODIFICATION_ERR=(ExceptionMessage[13]="Invalid modification",13),ExceptionCode.NAMESPACE_ERR=(ExceptionMessage[14]="Invalid namespace",14),ExceptionCode.INVALID_ACCESS_ERR=(ExceptionMessage[15]="Invalid access",15),DOMException.prototype=Error.prototype,copy(ExceptionCode,DOMException),NodeList.prototype={length:0,item:function(index){return this[index]||null},toString:function(isHTML,nodeFilter){for(var buf=[],i=0;i<this.length;i++)serializeToString(this[i],buf,isHTML,nodeFilter);return buf.join("")},filter:function(predicate){return Array.prototype.filter.call(this,predicate)},indexOf:function(item){return Array.prototype.indexOf.call(this,item)}},LiveNodeList.prototype.item=function(i){return _updateLiveList(this),this[i]},_extends(LiveNodeList,NodeList),NamedNodeMap.prototype={length:0,item:NodeList.prototype.item,getNamedItem:function(key){for(var i=this.length;i--;){var attr=this[i];if(attr.nodeName==key)return attr}},setNamedItem:function(attr){var el=attr.ownerElement;if(el&&el!=this._ownerElement)throw new DOMException(INUSE_ATTRIBUTE_ERR);var oldAttr=this.getNamedItem(attr.nodeName);return _addNamedNode(this._ownerElement,this,attr,oldAttr),oldAttr},setNamedItemNS:function(attr){var oldAttr,el=attr.ownerElement;if(el&&el!=this._ownerElement)throw new DOMException(INUSE_ATTRIBUTE_ERR);return oldAttr=this.getNamedItemNS(attr.namespaceURI,attr.localName),_addNamedNode(this._ownerElement,this,attr,oldAttr),oldAttr},removeNamedItem:function(key){var attr=this.getNamedItem(key);return _removeNamedNode(this._ownerElement,this,attr),attr},removeNamedItemNS:function(namespaceURI,localName){var attr=this.getNamedItemNS(namespaceURI,localName);return _removeNamedNode(this._ownerElement,this,attr),attr},getNamedItemNS:function(namespaceURI,localName){for(var i=this.length;i--;){var node=this[i];if(node.localName==localName&&node.namespaceURI==namespaceURI)return node}return null}},DOMImplementation.prototype={hasFeature:function(feature,version){return!0},createDocument:function(namespaceURI,qualifiedName,doctype){var doc=new Document;if(doc.implementation=this,doc.childNodes=new NodeList,doc.doctype=doctype||null,doctype&&doc.appendChild(doctype),qualifiedName){var root=doc.createElementNS(namespaceURI,qualifiedName);doc.appendChild(root)}return doc},createDocumentType:function(qualifiedName,publicId,systemId){var node=new DocumentType;return node.name=qualifiedName,node.nodeName=qualifiedName,node.publicId=publicId||"",node.systemId=systemId||"",node}},Node.prototype={firstChild:null,lastChild:null,previousSibling:null,nextSibling:null,attributes:null,parentNode:null,childNodes:null,ownerDocument:null,nodeValue:null,namespaceURI:null,prefix:null,localName:null,insertBefore:function(newChild,refChild){return _insertBefore(this,newChild,refChild)},replaceChild:function(newChild,oldChild){_insertBefore(this,newChild,oldChild,assertPreReplacementValidityInDocument),oldChild&&this.removeChild(oldChild)},removeChild:function(oldChild){return _removeChild(this,oldChild)},appendChild:function(newChild){return this.insertBefore(newChild,null)},hasChildNodes:function(){return null!=this.firstChild},cloneNode:function(deep){return cloneNode(this.ownerDocument||this,this,deep)},normalize:function(){for(var child=this.firstChild;child;){var next=child.nextSibling;next&&next.nodeType==TEXT_NODE&&child.nodeType==TEXT_NODE?(this.removeChild(next),child.appendData(next.data)):(child.normalize(),child=next)}},isSupported:function(feature,version){return this.ownerDocument.implementation.hasFeature(feature,version)},hasAttributes:function(){return this.attributes.length>0},lookupPrefix:function(namespaceURI){for(var el=this;el;){var map=el._nsMap;if(map)for(var n in map)if(Object.prototype.hasOwnProperty.call(map,n)&&map[n]===namespaceURI)return n;el=el.nodeType==ATTRIBUTE_NODE?el.ownerDocument:el.parentNode}return null},lookupNamespaceURI:function(prefix){for(var el=this;el;){var map=el._nsMap;if(map&&Object.prototype.hasOwnProperty.call(map,prefix))return map[prefix];el=el.nodeType==ATTRIBUTE_NODE?el.ownerDocument:el.parentNode}return null},isDefaultNamespace:function(namespaceURI){return null==this.lookupPrefix(namespaceURI)}},copy(NodeType,Node),copy(NodeType,Node.prototype),Document.prototype={nodeName:"#document",nodeType:DOCUMENT_NODE,doctype:null,documentElement:null,_inc:1,insertBefore:function(newChild,refChild){if(newChild.nodeType==DOCUMENT_FRAGMENT_NODE){for(var child=newChild.firstChild;child;){var next=child.nextSibling;this.insertBefore(child,refChild),child=next}return newChild}return _insertBefore(this,newChild,refChild),newChild.ownerDocument=this,null===this.documentElement&&newChild.nodeType===ELEMENT_NODE&&(this.documentElement=newChild),newChild},removeChild:function(oldChild){return this.documentElement==oldChild&&(this.documentElement=null),_removeChild(this,oldChild)},replaceChild:function(newChild,oldChild){_insertBefore(this,newChild,oldChild,assertPreReplacementValidityInDocument),newChild.ownerDocument=this,oldChild&&this.removeChild(oldChild),isElementNode(newChild)&&(this.documentElement=newChild)},importNode:function(importedNode,deep){return importNode(this,importedNode,deep)},getElementById:function(id){var rtv=null;return _visitNode(this.documentElement,function(node){if(node.nodeType==ELEMENT_NODE&&node.getAttribute("id")==id)return rtv=node,!0}),rtv},getElementsByClassName:function(classNames){var classNamesSet=toOrderedSet(classNames);return new LiveNodeList(this,function(base){var ls=[];return classNamesSet.length>0&&_visitNode(base.documentElement,function(node){if(node!==base&&node.nodeType===ELEMENT_NODE){var nodeClassNames=node.getAttribute("class");if(nodeClassNames){var matches=classNames===nodeClassNames;if(!matches){var nodeClassNamesSet=toOrderedSet(nodeClassNames);matches=classNamesSet.every(arrayIncludes(nodeClassNamesSet))}matches&&ls.push(node)}}}),ls})},createElement:function(tagName){var node=new Element;return node.ownerDocument=this,node.nodeName=tagName,node.tagName=tagName,node.localName=tagName,node.childNodes=new NodeList,(node.attributes=new NamedNodeMap)._ownerElement=node,node},createDocumentFragment:function(){var node=new DocumentFragment;return node.ownerDocument=this,node.childNodes=new NodeList,node},createTextNode:function(data){var node=new Text;return node.ownerDocument=this,node.appendData(data),node},createComment:function(data){var node=new Comment;return node.ownerDocument=this,node.appendData(data),node},createCDATASection:function(data){var node=new CDATASection;return node.ownerDocument=this,node.appendData(data),node},createProcessingInstruction:function(target,data){var node=new ProcessingInstruction;return node.ownerDocument=this,node.tagName=node.target=target,node.nodeValue=node.data=data,node},createAttribute:function(name){var node=new Attr;return node.ownerDocument=this,node.name=name,node.nodeName=name,node.localName=name,node.specified=!0,node},createEntityReference:function(name){var node=new EntityReference;return node.ownerDocument=this,node.nodeName=name,node},createElementNS:function(namespaceURI,qualifiedName){var node=new Element,pl=qualifiedName.split(":"),attrs=node.attributes=new NamedNodeMap;return node.childNodes=new NodeList,node.ownerDocument=this,node.nodeName=qualifiedName,node.tagName=qualifiedName,node.namespaceURI=namespaceURI,2==pl.length?(node.prefix=pl[0],node.localName=pl[1]):node.localName=qualifiedName,attrs._ownerElement=node,node},createAttributeNS:function(namespaceURI,qualifiedName){var node=new Attr,pl=qualifiedName.split(":");return node.ownerDocument=this,node.nodeName=qualifiedName,node.name=qualifiedName,node.namespaceURI=namespaceURI,node.specified=!0,2==pl.length?(node.prefix=pl[0],node.localName=pl[1]):node.localName=qualifiedName,node}},_extends(Document,Node),Element.prototype={nodeType:ELEMENT_NODE,hasAttribute:function(name){return null!=this.getAttributeNode(name)},getAttribute:function(name){var attr=this.getAttributeNode(name);return attr&&attr.value||""},getAttributeNode:function(name){return this.attributes.getNamedItem(name)},setAttribute:function(name,value){var attr=this.ownerDocument.createAttribute(name);attr.value=attr.nodeValue=""+value,this.setAttributeNode(attr)},removeAttribute:function(name){var attr=this.getAttributeNode(name);attr&&this.removeAttributeNode(attr)},appendChild:function(newChild){return newChild.nodeType===DOCUMENT_FRAGMENT_NODE?this.insertBefore(newChild,null):_appendSingleChild(this,newChild)},setAttributeNode:function(newAttr){return this.attributes.setNamedItem(newAttr)},setAttributeNodeNS:function(newAttr){return this.attributes.setNamedItemNS(newAttr)},removeAttributeNode:function(oldAttr){return this.attributes.removeNamedItem(oldAttr.nodeName)},removeAttributeNS:function(namespaceURI,localName){var old=this.getAttributeNodeNS(namespaceURI,localName);old&&this.removeAttributeNode(old)},hasAttributeNS:function(namespaceURI,localName){return null!=this.getAttributeNodeNS(namespaceURI,localName)},getAttributeNS:function(namespaceURI,localName){var attr=this.getAttributeNodeNS(namespaceURI,localName);return attr&&attr.value||""},setAttributeNS:function(namespaceURI,qualifiedName,value){var attr=this.ownerDocument.createAttributeNS(namespaceURI,qualifiedName);attr.value=attr.nodeValue=""+value,this.setAttributeNode(attr)},getAttributeNodeNS:function(namespaceURI,localName){return this.attributes.getNamedItemNS(namespaceURI,localName)},getElementsByTagName:function(tagName){return new LiveNodeList(this,function(base){var ls=[];return _visitNode(base,function(node){node===base||node.nodeType!=ELEMENT_NODE||"*"!==tagName&&node.tagName!=tagName||ls.push(node)}),ls})},getElementsByTagNameNS:function(namespaceURI,localName){return new LiveNodeList(this,function(base){var ls=[];return _visitNode(base,function(node){node===base||node.nodeType!==ELEMENT_NODE||"*"!==namespaceURI&&node.namespaceURI!==namespaceURI||"*"!==localName&&node.localName!=localName||ls.push(node)}),ls})}},Document.prototype.getElementsByTagName=Element.prototype.getElementsByTagName,Document.prototype.getElementsByTagNameNS=Element.prototype.getElementsByTagNameNS,_extends(Element,Node),Attr.prototype.nodeType=ATTRIBUTE_NODE,_extends(Attr,Node),CharacterData.prototype={data:"",substringData:function(offset,count){return this.data.substring(offset,offset+count)},appendData:function(text){text=this.data+text,this.nodeValue=this.data=text,this.length=text.length},insertData:function(offset,text){this.replaceData(offset,0,text)},appendChild:function(newChild){throw new Error(ExceptionMessage[HIERARCHY_REQUEST_ERR])},deleteData:function(offset,count){this.replaceData(offset,count,"")},replaceData:function(offset,count,text){text=this.data.substring(0,offset)+text+this.data.substring(offset+count),this.nodeValue=this.data=text,this.length=text.length}},_extends(CharacterData,Node),Text.prototype={nodeName:"#text",nodeType:TEXT_NODE,splitText:function(offset){var text=this.data,newText=text.substring(offset);text=text.substring(0,offset),this.data=this.nodeValue=text,this.length=text.length;var newNode=this.ownerDocument.createTextNode(newText);return this.parentNode&&this.parentNode.insertBefore(newNode,this.nextSibling),newNode}},_extends(Text,CharacterData),Comment.prototype={nodeName:"#comment",nodeType:COMMENT_NODE},_extends(Comment,CharacterData),CDATASection.prototype={nodeName:"#cdata-section",nodeType:CDATA_SECTION_NODE},_extends(CDATASection,CharacterData),DocumentType.prototype.nodeType=DOCUMENT_TYPE_NODE,_extends(DocumentType,Node),Notation.prototype.nodeType=NOTATION_NODE,_extends(Notation,Node),Entity.prototype.nodeType=ENTITY_NODE,_extends(Entity,Node),EntityReference.prototype.nodeType=ENTITY_REFERENCE_NODE,_extends(EntityReference,Node),DocumentFragment.prototype.nodeName="#document-fragment",DocumentFragment.prototype.nodeType=DOCUMENT_FRAGMENT_NODE,_extends(DocumentFragment,Node),ProcessingInstruction.prototype.nodeType=PROCESSING_INSTRUCTION_NODE,_extends(ProcessingInstruction,Node),XMLSerializer.prototype.serializeToString=function(node,isHtml,nodeFilter){return nodeSerializeToString.call(node,isHtml,nodeFilter)},Node.prototype.toString=nodeSerializeToString;try{if(Object.defineProperty){function getTextContent(node){switch(node.nodeType){case ELEMENT_NODE:case DOCUMENT_FRAGMENT_NODE:var buf=[];for(node=node.firstChild;node;)7!==node.nodeType&&8!==node.nodeType&&buf.push(getTextContent(node)),node=node.nextSibling;return buf.join("");default:return node.nodeValue}}Object.defineProperty(LiveNodeList.prototype,"length",{get:function(){return _updateLiveList(this),this.$$length}}),Object.defineProperty(Node.prototype,"textContent",{get:function(){return getTextContent(this)},set:function(data){switch(this.nodeType){case ELEMENT_NODE:case DOCUMENT_FRAGMENT_NODE:for(;this.firstChild;)this.removeChild(this.firstChild);(data||String(data))&&this.appendChild(this.ownerDocument.createTextNode(data));break;default:this.data=data,this.value=data,this.nodeValue=data}}}),__set__=function(object,key,value){object["$$"+key]=value}}}catch(e){}exports.DocumentType=DocumentType,exports.DOMException=DOMException,exports.DOMImplementation=DOMImplementation,exports.Element=Element,exports.Node=Node,exports.NodeList=NodeList,exports.XMLSerializer=XMLSerializer},{"./conventions":1}],4:[function(require,module,exports){"use strict";var freeze=require("./conventions").freeze;exports.XML_ENTITIES=freeze({amp:"&",apos:"'",gt:">",lt:"<",quot:'"'}),exports.HTML_ENTITIES=freeze({Aacute:"Á",aacute:"á",Abreve:"Ă",abreve:"ă",ac:"∾",acd:"∿",acE:"∾̳",Acirc:"Â",acirc:"â",acute:"´",Acy:"А",acy:"а",AElig:"Æ",aelig:"æ",af:"⁡",Afr:"𝔄",afr:"𝔞",Agrave:"À",agrave:"à",alefsym:"ℵ",aleph:"ℵ",Alpha:"Α",alpha:"α",Amacr:"Ā",amacr:"ā",amalg:"⨿",AMP:"&",amp:"&",And:"⩓",and:"∧",andand:"⩕",andd:"⩜",andslope:"⩘",andv:"⩚",ang:"∠",ange:"⦤",angle:"∠",angmsd:"∡",angmsdaa:"⦨",angmsdab:"⦩",angmsdac:"⦪",angmsdad:"⦫",angmsdae:"⦬",angmsdaf:"⦭",angmsdag:"⦮",angmsdah:"⦯",angrt:"∟",angrtvb:"⊾",angrtvbd:"⦝",angsph:"∢",angst:"Å",angzarr:"⍼",Aogon:"Ą",aogon:"ą",Aopf:"𝔸",aopf:"𝕒",ap:"≈",apacir:"⩯",apE:"⩰",ape:"≊",apid:"≋",apos:"'",ApplyFunction:"⁡",approx:"≈",approxeq:"≊",Aring:"Å",aring:"å",Ascr:"𝒜",ascr:"𝒶",Assign:"≔",ast:"*",asymp:"≈",asympeq:"≍",Atilde:"Ã",atilde:"ã",Auml:"Ä",auml:"ä",awconint:"∳",awint:"⨑",backcong:"≌",backepsilon:"϶",backprime:"‵",backsim:"∽",backsimeq:"⋍",Backslash:"∖",Barv:"⫧",barvee:"⊽",Barwed:"⌆",barwed:"⌅",barwedge:"⌅",bbrk:"⎵",bbrktbrk:"⎶",bcong:"≌",Bcy:"Б",bcy:"б",bdquo:"„",becaus:"∵",Because:"∵",because:"∵",bemptyv:"⦰",bepsi:"϶",bernou:"ℬ",Bernoullis:"ℬ",Beta:"Β",beta:"β",beth:"ℶ",between:"≬",Bfr:"𝔅",bfr:"𝔟",bigcap:"⋂",bigcirc:"◯",bigcup:"⋃",bigodot:"⨀",bigoplus:"⨁",bigotimes:"⨂",bigsqcup:"⨆",bigstar:"★",bigtriangledown:"▽",bigtriangleup:"△",biguplus:"⨄",bigvee:"⋁",bigwedge:"⋀",bkarow:"⤍",blacklozenge:"⧫",blacksquare:"▪",blacktriangle:"▴",blacktriangledown:"▾",blacktriangleleft:"◂",blacktriangleright:"▸",blank:"␣",blk12:"▒",blk14:"░",blk34:"▓",block:"█",bne:"=⃥",bnequiv:"≡⃥",bNot:"⫭",bnot:"⌐",Bopf:"𝔹",bopf:"𝕓",bot:"⊥",bottom:"⊥",bowtie:"⋈",boxbox:"⧉",boxDL:"╗",boxDl:"╖",boxdL:"╕",boxdl:"┐",boxDR:"╔",boxDr:"╓",boxdR:"╒",boxdr:"┌",boxH:"═",boxh:"─",boxHD:"╦",boxHd:"╤",boxhD:"╥",boxhd:"┬",boxHU:"╩",boxHu:"╧",boxhU:"╨",boxhu:"┴",boxminus:"⊟",boxplus:"⊞",boxtimes:"⊠",boxUL:"╝",boxUl:"╜",boxuL:"╛",boxul:"┘",boxUR:"╚",boxUr:"╙",boxuR:"╘",boxur:"└",boxV:"║",boxv:"│",boxVH:"╬",boxVh:"╫",boxvH:"╪",boxvh:"┼",boxVL:"╣",boxVl:"╢",boxvL:"╡",boxvl:"┤",boxVR:"╠",boxVr:"╟",boxvR:"╞",boxvr:"├",bprime:"‵",Breve:"˘",breve:"˘",brvbar:"¦",Bscr:"ℬ",bscr:"𝒷",bsemi:"⁏",bsim:"∽",bsime:"⋍",bsol:"\\",bsolb:"⧅",bsolhsub:"⟈",bull:"•",bullet:"•",bump:"≎",bumpE:"⪮",bumpe:"≏",Bumpeq:"≎",bumpeq:"≏",Cacute:"Ć",cacute:"ć",Cap:"⋒",cap:"∩",capand:"⩄",capbrcup:"⩉",capcap:"⩋",capcup:"⩇",capdot:"⩀",CapitalDifferentialD:"ⅅ",caps:"∩︀",caret:"⁁",caron:"ˇ",Cayleys:"ℭ",ccaps:"⩍",Ccaron:"Č",ccaron:"č",Ccedil:"Ç",ccedil:"ç",Ccirc:"Ĉ",ccirc:"ĉ",Cconint:"∰",ccups:"⩌",ccupssm:"⩐",Cdot:"Ċ",cdot:"ċ",cedil:"¸",Cedilla:"¸",cemptyv:"⦲",cent:"¢",CenterDot:"·",centerdot:"·",Cfr:"ℭ",cfr:"𝔠",CHcy:"Ч",chcy:"ч",check:"✓",checkmark:"✓",Chi:"Χ",chi:"χ",cir:"○",circ:"ˆ",circeq:"≗",circlearrowleft:"↺",circlearrowright:"↻",circledast:"⊛",circledcirc:"⊚",circleddash:"⊝",CircleDot:"⊙",circledR:"®",circledS:"Ⓢ",CircleMinus:"⊖",CirclePlus:"⊕",CircleTimes:"⊗",cirE:"⧃",cire:"≗",cirfnint:"⨐",cirmid:"⫯",cirscir:"⧂",ClockwiseContourIntegral:"∲",CloseCurlyDoubleQuote:"”",CloseCurlyQuote:"’",clubs:"♣",clubsuit:"♣",Colon:"∷",colon:":",Colone:"⩴",colone:"≔",coloneq:"≔",comma:",",commat:"@",comp:"∁",compfn:"∘",complement:"∁",complexes:"ℂ",cong:"≅",congdot:"⩭",Congruent:"≡",Conint:"∯",conint:"∮",ContourIntegral:"∮",Copf:"ℂ",copf:"𝕔",coprod:"∐",Coproduct:"∐",COPY:"©",copy:"©",copysr:"℗",CounterClockwiseContourIntegral:"∳",crarr:"↵",Cross:"⨯",cross:"✗",Cscr:"𝒞",cscr:"𝒸",csub:"⫏",csube:"⫑",csup:"⫐",csupe:"⫒",ctdot:"⋯",cudarrl:"⤸",cudarrr:"⤵",cuepr:"⋞",cuesc:"⋟",cularr:"↶",cularrp:"⤽",Cup:"⋓",cup:"∪",cupbrcap:"⩈",CupCap:"≍",cupcap:"⩆",cupcup:"⩊",cupdot:"⊍",cupor:"⩅",cups:"∪︀",curarr:"↷",curarrm:"⤼",curlyeqprec:"⋞",curlyeqsucc:"⋟",curlyvee:"⋎",curlywedge:"⋏",curren:"¤",curvearrowleft:"↶",curvearrowright:"↷",cuvee:"⋎",cuwed:"⋏",cwconint:"∲",cwint:"∱",cylcty:"⌭",Dagger:"‡",dagger:"†",daleth:"ℸ",Darr:"↡",dArr:"⇓",darr:"↓",dash:"‐",Dashv:"⫤",dashv:"⊣",dbkarow:"⤏",dblac:"˝",Dcaron:"Ď",dcaron:"ď",Dcy:"Д",dcy:"д",DD:"ⅅ",dd:"ⅆ",ddagger:"‡",ddarr:"⇊",DDotrahd:"⤑",ddotseq:"⩷",deg:"°",Del:"∇",Delta:"Δ",delta:"δ",demptyv:"⦱",dfisht:"⥿",Dfr:"𝔇",dfr:"𝔡",dHar:"⥥",dharl:"⇃",dharr:"⇂",DiacriticalAcute:"´",DiacriticalDot:"˙",DiacriticalDoubleAcute:"˝",DiacriticalGrave:"`",DiacriticalTilde:"˜",diam:"⋄",Diamond:"⋄",diamond:"⋄",diamondsuit:"♦",diams:"♦",die:"¨",DifferentialD:"ⅆ",digamma:"ϝ",disin:"⋲",div:"÷",divide:"÷",divideontimes:"⋇",divonx:"⋇",DJcy:"Ђ",djcy:"ђ",dlcorn:"⌞",dlcrop:"⌍",dollar:"$",Dopf:"𝔻",dopf:"𝕕",Dot:"¨",dot:"˙",DotDot:"⃜",doteq:"≐",doteqdot:"≑",DotEqual:"≐",dotminus:"∸",dotplus:"∔",dotsquare:"⊡",doublebarwedge:"⌆",DoubleContourIntegral:"∯",DoubleDot:"¨",DoubleDownArrow:"⇓",DoubleLeftArrow:"⇐",DoubleLeftRightArrow:"⇔",DoubleLeftTee:"⫤",DoubleLongLeftArrow:"⟸",DoubleLongLeftRightArrow:"⟺",DoubleLongRightArrow:"⟹",DoubleRightArrow:"⇒",DoubleRightTee:"⊨",DoubleUpArrow:"⇑",DoubleUpDownArrow:"⇕",DoubleVerticalBar:"∥",DownArrow:"↓",Downarrow:"⇓",downarrow:"↓",DownArrowBar:"⤓",DownArrowUpArrow:"⇵",DownBreve:"̑",downdownarrows:"⇊",downharpoonleft:"⇃",downharpoonright:"⇂",DownLeftRightVector:"⥐",DownLeftTeeVector:"⥞",DownLeftVector:"↽",DownLeftVectorBar:"⥖",DownRightTeeVector:"⥟",DownRightVector:"⇁",DownRightVectorBar:"⥗",DownTee:"⊤",DownTeeArrow:"↧",drbkarow:"⤐",drcorn:"⌟",drcrop:"⌌",Dscr:"𝒟",dscr:"𝒹",DScy:"Ѕ",dscy:"ѕ",dsol:"⧶",Dstrok:"Đ",dstrok:"đ",dtdot:"⋱",dtri:"▿",dtrif:"▾",duarr:"⇵",duhar:"⥯",dwangle:"⦦",DZcy:"Џ",dzcy:"џ",dzigrarr:"⟿",Eacute:"É",eacute:"é",easter:"⩮",Ecaron:"Ě",ecaron:"ě",ecir:"≖",Ecirc:"Ê",ecirc:"ê",ecolon:"≕",Ecy:"Э",ecy:"э",eDDot:"⩷",Edot:"Ė",eDot:"≑",edot:"ė",ee:"ⅇ",efDot:"≒",Efr:"𝔈",efr:"𝔢",eg:"⪚",Egrave:"È",egrave:"è",egs:"⪖",egsdot:"⪘",el:"⪙",Element:"∈",elinters:"⏧",ell:"ℓ",els:"⪕",elsdot:"⪗",Emacr:"Ē",emacr:"ē",empty:"∅",emptyset:"∅",EmptySmallSquare:"◻",emptyv:"∅",EmptyVerySmallSquare:"▫",emsp:" ",emsp13:" ",emsp14:" ",ENG:"Ŋ",eng:"ŋ",ensp:" ",Eogon:"Ę",eogon:"ę",Eopf:"𝔼",eopf:"𝕖",epar:"⋕",eparsl:"⧣",eplus:"⩱",epsi:"ε",Epsilon:"Ε",epsilon:"ε",epsiv:"ϵ",eqcirc:"≖",eqcolon:"≕",eqsim:"≂",eqslantgtr:"⪖",eqslantless:"⪕",Equal:"⩵",equals:"=",EqualTilde:"≂",equest:"≟",Equilibrium:"⇌",equiv:"≡",equivDD:"⩸",eqvparsl:"⧥",erarr:"⥱",erDot:"≓",Escr:"ℰ",escr:"ℯ",esdot:"≐",Esim:"⩳",esim:"≂",Eta:"Η",eta:"η",ETH:"Ð",eth:"ð",Euml:"Ë",euml:"ë",euro:"€",excl:"!",exist:"∃",Exists:"∃",expectation:"ℰ",ExponentialE:"ⅇ",exponentiale:"ⅇ",fallingdotseq:"≒",Fcy:"Ф",fcy:"ф",female:"♀",ffilig:"ffi",fflig:"ff",ffllig:"ffl",Ffr:"𝔉",ffr:"𝔣",filig:"fi",FilledSmallSquare:"◼",FilledVerySmallSquare:"▪",fjlig:"fj",flat:"♭",fllig:"fl",fltns:"▱",fnof:"ƒ",Fopf:"𝔽",fopf:"𝕗",ForAll:"∀",forall:"∀",fork:"⋔",forkv:"⫙",Fouriertrf:"ℱ",fpartint:"⨍",frac12:"½",frac13:"⅓",frac14:"¼",frac15:"⅕",frac16:"⅙",frac18:"⅛",frac23:"⅔",frac25:"⅖",frac34:"¾",frac35:"⅗",frac38:"⅜",frac45:"⅘",frac56:"⅚",frac58:"⅝",frac78:"⅞",frasl:"⁄",frown:"⌢",Fscr:"ℱ",fscr:"𝒻",gacute:"ǵ",Gamma:"Γ",gamma:"γ",Gammad:"Ϝ",gammad:"ϝ",gap:"⪆",Gbreve:"Ğ",gbreve:"ğ",Gcedil:"Ģ",Gcirc:"Ĝ",gcirc:"ĝ",Gcy:"Г",gcy:"г",Gdot:"Ġ",gdot:"ġ",gE:"≧",ge:"≥",gEl:"⪌",gel:"⋛",geq:"≥",geqq:"≧",geqslant:"⩾",ges:"⩾",gescc:"⪩",gesdot:"⪀",gesdoto:"⪂",gesdotol:"⪄",gesl:"⋛︀",gesles:"⪔",Gfr:"𝔊",gfr:"𝔤",Gg:"⋙",gg:"≫",ggg:"⋙",gimel:"ℷ",GJcy:"Ѓ",gjcy:"ѓ",gl:"≷",gla:"⪥",glE:"⪒",glj:"⪤",gnap:"⪊",gnapprox:"⪊",gnE:"≩",gne:"⪈",gneq:"⪈",gneqq:"≩",gnsim:"⋧",Gopf:"𝔾",gopf:"𝕘",grave:"`",GreaterEqual:"≥",GreaterEqualLess:"⋛",GreaterFullEqual:"≧",GreaterGreater:"⪢",GreaterLess:"≷",GreaterSlantEqual:"⩾",GreaterTilde:"≳",Gscr:"𝒢",gscr:"ℊ",gsim:"≳",gsime:"⪎",gsiml:"⪐",Gt:"≫",GT:">",gt:">",gtcc:"⪧",gtcir:"⩺",gtdot:"⋗",gtlPar:"⦕",gtquest:"⩼",gtrapprox:"⪆",gtrarr:"⥸",gtrdot:"⋗",gtreqless:"⋛",gtreqqless:"⪌",gtrless:"≷",gtrsim:"≳",gvertneqq:"≩︀",gvnE:"≩︀",Hacek:"ˇ",hairsp:" ",half:"½",hamilt:"ℋ",HARDcy:"Ъ",hardcy:"ъ",hArr:"⇔",harr:"↔",harrcir:"⥈",harrw:"↭",Hat:"^",hbar:"ℏ",Hcirc:"Ĥ",hcirc:"ĥ",hearts:"♥",heartsuit:"♥",hellip:"…",hercon:"⊹",Hfr:"ℌ",hfr:"𝔥",HilbertSpace:"ℋ",hksearow:"⤥",hkswarow:"⤦",hoarr:"⇿",homtht:"∻",hookleftarrow:"↩",hookrightarrow:"↪",Hopf:"ℍ",hopf:"𝕙",horbar:"―",HorizontalLine:"─",Hscr:"ℋ",hscr:"𝒽",hslash:"ℏ",Hstrok:"Ħ",hstrok:"ħ",HumpDownHump:"≎",HumpEqual:"≏",hybull:"⁃",hyphen:"‐",Iacute:"Í",iacute:"í",ic:"⁣",Icirc:"Î",icirc:"î",Icy:"И",icy:"и",Idot:"İ",IEcy:"Е",iecy:"е",iexcl:"¡",iff:"⇔",Ifr:"ℑ",ifr:"𝔦",Igrave:"Ì",igrave:"ì",ii:"ⅈ",iiiint:"⨌",iiint:"∭",iinfin:"⧜",iiota:"℩",IJlig:"IJ",ijlig:"ij",Im:"ℑ",Imacr:"Ī",imacr:"ī",image:"ℑ",ImaginaryI:"ⅈ",imagline:"ℐ",imagpart:"ℑ",imath:"ı",imof:"⊷",imped:"Ƶ",Implies:"⇒",in:"∈",incare:"℅",infin:"∞",infintie:"⧝",inodot:"ı",Int:"∬",int:"∫",intcal:"⊺",integers:"ℤ",Integral:"∫",intercal:"⊺",Intersection:"⋂",intlarhk:"⨗",intprod:"⨼",InvisibleComma:"⁣",InvisibleTimes:"⁢",IOcy:"Ё",iocy:"ё",Iogon:"Į",iogon:"į",Iopf:"𝕀",iopf:"𝕚",Iota:"Ι",iota:"ι",iprod:"⨼",iquest:"¿",Iscr:"ℐ",iscr:"𝒾",isin:"∈",isindot:"⋵",isinE:"⋹",isins:"⋴",isinsv:"⋳",isinv:"∈",it:"⁢",Itilde:"Ĩ",itilde:"ĩ",Iukcy:"І",iukcy:"і",Iuml:"Ï",iuml:"ï",Jcirc:"Ĵ",jcirc:"ĵ",Jcy:"Й",jcy:"й",Jfr:"𝔍",jfr:"𝔧",jmath:"ȷ",Jopf:"𝕁",jopf:"𝕛",Jscr:"𝒥",jscr:"𝒿",Jsercy:"Ј",jsercy:"ј",Jukcy:"Є",jukcy:"є",Kappa:"Κ",kappa:"κ",kappav:"ϰ",Kcedil:"Ķ",kcedil:"ķ",Kcy:"К",kcy:"к",Kfr:"𝔎",kfr:"𝔨",kgreen:"ĸ",KHcy:"Х",khcy:"х",KJcy:"Ќ",kjcy:"ќ",Kopf:"𝕂",kopf:"𝕜",Kscr:"𝒦",kscr:"𝓀",lAarr:"⇚",Lacute:"Ĺ",lacute:"ĺ",laemptyv:"⦴",lagran:"ℒ",Lambda:"Λ",lambda:"λ",Lang:"⟪",lang:"⟨",langd:"⦑",langle:"⟨",lap:"⪅",Laplacetrf:"ℒ",laquo:"«",Larr:"↞",lArr:"⇐",larr:"←",larrb:"⇤",larrbfs:"⤟",larrfs:"⤝",larrhk:"↩",larrlp:"↫",larrpl:"⤹",larrsim:"⥳",larrtl:"↢",lat:"⪫",lAtail:"⤛",latail:"⤙",late:"⪭",lates:"⪭︀",lBarr:"⤎",lbarr:"⤌",lbbrk:"❲",lbrace:"{",lbrack:"[",lbrke:"⦋",lbrksld:"⦏",lbrkslu:"⦍",Lcaron:"Ľ",lcaron:"ľ",Lcedil:"Ļ",lcedil:"ļ",lceil:"⌈",lcub:"{",Lcy:"Л",lcy:"л",ldca:"⤶",ldquo:"“",ldquor:"„",ldrdhar:"⥧",ldrushar:"⥋",ldsh:"↲",lE:"≦",le:"≤",LeftAngleBracket:"⟨",LeftArrow:"←",Leftarrow:"⇐",leftarrow:"←",LeftArrowBar:"⇤",LeftArrowRightArrow:"⇆",leftarrowtail:"↢",LeftCeiling:"⌈",LeftDoubleBracket:"⟦",LeftDownTeeVector:"⥡",LeftDownVector:"⇃",LeftDownVectorBar:"⥙",LeftFloor:"⌊",leftharpoondown:"↽",leftharpoonup:"↼",leftleftarrows:"⇇",LeftRightArrow:"↔",Leftrightarrow:"⇔",leftrightarrow:"↔",leftrightarrows:"⇆",leftrightharpoons:"⇋",leftrightsquigarrow:"↭",LeftRightVector:"⥎",LeftTee:"⊣",LeftTeeArrow:"↤",LeftTeeVector:"⥚",leftthreetimes:"⋋",LeftTriangle:"⊲",LeftTriangleBar:"⧏",LeftTriangleEqual:"⊴",LeftUpDownVector:"⥑",LeftUpTeeVector:"⥠",LeftUpVector:"↿",LeftUpVectorBar:"⥘",LeftVector:"↼",LeftVectorBar:"⥒",lEg:"⪋",leg:"⋚",leq:"≤",leqq:"≦",leqslant:"⩽",les:"⩽",lescc:"⪨",lesdot:"⩿",lesdoto:"⪁",lesdotor:"⪃",lesg:"⋚︀",lesges:"⪓",lessapprox:"⪅",lessdot:"⋖",lesseqgtr:"⋚",lesseqqgtr:"⪋",LessEqualGreater:"⋚",LessFullEqual:"≦",LessGreater:"≶",lessgtr:"≶",LessLess:"⪡",lesssim:"≲",LessSlantEqual:"⩽",LessTilde:"≲",lfisht:"⥼",lfloor:"⌊",Lfr:"𝔏",lfr:"𝔩",lg:"≶",lgE:"⪑",lHar:"⥢",lhard:"↽",lharu:"↼",lharul:"⥪",lhblk:"▄",LJcy:"Љ",ljcy:"љ",Ll:"⋘",ll:"≪",llarr:"⇇",llcorner:"⌞",Lleftarrow:"⇚",llhard:"⥫",lltri:"◺",Lmidot:"Ŀ",lmidot:"ŀ",lmoust:"⎰",lmoustache:"⎰",lnap:"⪉",lnapprox:"⪉",lnE:"≨",lne:"⪇",lneq:"⪇",lneqq:"≨",lnsim:"⋦",loang:"⟬",loarr:"⇽",lobrk:"⟦",LongLeftArrow:"⟵",Longleftarrow:"⟸",longleftarrow:"⟵",LongLeftRightArrow:"⟷",Longleftrightarrow:"⟺",longleftrightarrow:"⟷",longmapsto:"⟼",LongRightArrow:"⟶",Longrightarrow:"⟹",longrightarrow:"⟶",looparrowleft:"↫",looparrowright:"↬",lopar:"⦅",Lopf:"𝕃",lopf:"𝕝",loplus:"⨭",lotimes:"⨴",lowast:"∗",lowbar:"_",LowerLeftArrow:"↙",LowerRightArrow:"↘",loz:"◊",lozenge:"◊",lozf:"⧫",lpar:"(",lparlt:"⦓",lrarr:"⇆",lrcorner:"⌟",lrhar:"⇋",lrhard:"⥭",lrm:"‎",lrtri:"⊿",lsaquo:"‹",Lscr:"ℒ",lscr:"𝓁",Lsh:"↰",lsh:"↰",lsim:"≲",lsime:"⪍",lsimg:"⪏",lsqb:"[",lsquo:"‘",lsquor:"‚",Lstrok:"Ł",lstrok:"ł",Lt:"≪",LT:"<",lt:"<",ltcc:"⪦",ltcir:"⩹",ltdot:"⋖",lthree:"⋋",ltimes:"⋉",ltlarr:"⥶",ltquest:"⩻",ltri:"◃",ltrie:"⊴",ltrif:"◂",ltrPar:"⦖",lurdshar:"⥊",luruhar:"⥦",lvertneqq:"≨︀",lvnE:"≨︀",macr:"¯",male:"♂",malt:"✠",maltese:"✠",Map:"⤅",map:"↦",mapsto:"↦",mapstodown:"↧",mapstoleft:"↤",mapstoup:"↥",marker:"▮",mcomma:"⨩",Mcy:"М",mcy:"м",mdash:"—",mDDot:"∺",measuredangle:"∡",MediumSpace:" ",Mellintrf:"ℳ",Mfr:"𝔐",mfr:"𝔪",mho:"℧",micro:"µ",mid:"∣",midast:"*",midcir:"⫰",middot:"·",minus:"−",minusb:"⊟",minusd:"∸",minusdu:"⨪",MinusPlus:"∓",mlcp:"⫛",mldr:"…",mnplus:"∓",models:"⊧",Mopf:"𝕄",mopf:"𝕞",mp:"∓",Mscr:"ℳ",mscr:"𝓂",mstpos:"∾",Mu:"Μ",mu:"μ",multimap:"⊸",mumap:"⊸",nabla:"∇",Nacute:"Ń",nacute:"ń",nang:"∠⃒",nap:"≉",napE:"⩰̸",napid:"≋̸",napos:"ʼn",napprox:"≉",natur:"♮",natural:"♮",naturals:"ℕ",nbsp:" ",nbump:"≎̸",nbumpe:"≏̸",ncap:"⩃",Ncaron:"Ň",ncaron:"ň",Ncedil:"Ņ",ncedil:"ņ",ncong:"≇",ncongdot:"⩭̸",ncup:"⩂",Ncy:"Н",ncy:"н",ndash:"–",ne:"≠",nearhk:"⤤",neArr:"⇗",nearr:"↗",nearrow:"↗",nedot:"≐̸",NegativeMediumSpace:"​",NegativeThickSpace:"​",NegativeThinSpace:"​",NegativeVeryThinSpace:"​",nequiv:"≢",nesear:"⤨",nesim:"≂̸",NestedGreaterGreater:"≫",NestedLessLess:"≪",NewLine:"\n",nexist:"∄",nexists:"∄",Nfr:"𝔑",nfr:"𝔫",ngE:"≧̸",nge:"≱",ngeq:"≱",ngeqq:"≧̸",ngeqslant:"⩾̸",nges:"⩾̸",nGg:"⋙̸",ngsim:"≵",nGt:"≫⃒",ngt:"≯",ngtr:"≯",nGtv:"≫̸",nhArr:"⇎",nharr:"↮",nhpar:"⫲",ni:"∋",nis:"⋼",nisd:"⋺",niv:"∋",NJcy:"Њ",njcy:"њ",nlArr:"⇍",nlarr:"↚",nldr:"‥",nlE:"≦̸",nle:"≰",nLeftarrow:"⇍",nleftarrow:"↚",nLeftrightarrow:"⇎",nleftrightarrow:"↮",nleq:"≰",nleqq:"≦̸",nleqslant:"⩽̸",nles:"⩽̸",nless:"≮",nLl:"⋘̸",nlsim:"≴",nLt:"≪⃒",nlt:"≮",nltri:"⋪",nltrie:"⋬",nLtv:"≪̸",nmid:"∤",NoBreak:"⁠",NonBreakingSpace:" ",Nopf:"ℕ",nopf:"𝕟",Not:"⫬",not:"¬",NotCongruent:"≢",NotCupCap:"≭",NotDoubleVerticalBar:"∦",NotElement:"∉",NotEqual:"≠",NotEqualTilde:"≂̸",NotExists:"∄",NotGreater:"≯",NotGreaterEqual:"≱",NotGreaterFullEqual:"≧̸",NotGreaterGreater:"≫̸",NotGreaterLess:"≹",NotGreaterSlantEqual:"⩾̸",NotGreaterTilde:"≵",NotHumpDownHump:"≎̸",NotHumpEqual:"≏̸",notin:"∉",notindot:"⋵̸",notinE:"⋹̸",notinva:"∉",notinvb:"⋷",notinvc:"⋶",NotLeftTriangle:"⋪",NotLeftTriangleBar:"⧏̸",NotLeftTriangleEqual:"⋬",NotLess:"≮",NotLessEqual:"≰",NotLessGreater:"≸",NotLessLess:"≪̸",NotLessSlantEqual:"⩽̸",NotLessTilde:"≴",NotNestedGreaterGreater:"⪢̸",NotNestedLessLess:"⪡̸",notni:"∌",notniva:"∌",notnivb:"⋾",notnivc:"⋽",NotPrecedes:"⊀",NotPrecedesEqual:"⪯̸",NotPrecedesSlantEqual:"⋠",NotReverseElement:"∌",NotRightTriangle:"⋫",NotRightTriangleBar:"⧐̸",NotRightTriangleEqual:"⋭",NotSquareSubset:"⊏̸",NotSquareSubsetEqual:"⋢",NotSquareSuperset:"⊐̸",NotSquareSupersetEqual:"⋣",NotSubset:"⊂⃒",NotSubsetEqual:"⊈",NotSucceeds:"⊁",NotSucceedsEqual:"⪰̸",NotSucceedsSlantEqual:"⋡",NotSucceedsTilde:"≿̸",NotSuperset:"⊃⃒",NotSupersetEqual:"⊉",NotTilde:"≁",NotTildeEqual:"≄",NotTildeFullEqual:"≇",NotTildeTilde:"≉",NotVerticalBar:"∤",npar:"∦",nparallel:"∦",nparsl:"⫽⃥",npart:"∂̸",npolint:"⨔",npr:"⊀",nprcue:"⋠",npre:"⪯̸",nprec:"⊀",npreceq:"⪯̸",nrArr:"⇏",nrarr:"↛",nrarrc:"⤳̸",nrarrw:"↝̸",nRightarrow:"⇏",nrightarrow:"↛",nrtri:"⋫",nrtrie:"⋭",nsc:"⊁",nsccue:"⋡",nsce:"⪰̸",Nscr:"𝒩",nscr:"𝓃",nshortmid:"∤",nshortparallel:"∦",nsim:"≁",nsime:"≄",nsimeq:"≄",nsmid:"∤",nspar:"∦",nsqsube:"⋢",nsqsupe:"⋣",nsub:"⊄",nsubE:"⫅̸",nsube:"⊈",nsubset:"⊂⃒",nsubseteq:"⊈",nsubseteqq:"⫅̸",nsucc:"⊁",nsucceq:"⪰̸",nsup:"⊅",nsupE:"⫆̸",nsupe:"⊉",nsupset:"⊃⃒",nsupseteq:"⊉",nsupseteqq:"⫆̸",ntgl:"≹",Ntilde:"Ñ",ntilde:"ñ",ntlg:"≸",ntriangleleft:"⋪",ntrianglelefteq:"⋬",ntriangleright:"⋫",ntrianglerighteq:"⋭",Nu:"Ν",nu:"ν",num:"#",numero:"№",numsp:" ",nvap:"≍⃒",nVDash:"⊯",nVdash:"⊮",nvDash:"⊭",nvdash:"⊬",nvge:"≥⃒",nvgt:">⃒",nvHarr:"⤄",nvinfin:"⧞",nvlArr:"⤂",nvle:"≤⃒",nvlt:"<⃒",nvltrie:"⊴⃒",nvrArr:"⤃",nvrtrie:"⊵⃒",nvsim:"∼⃒",nwarhk:"⤣",nwArr:"⇖",nwarr:"↖",nwarrow:"↖",nwnear:"⤧",Oacute:"Ó",oacute:"ó",oast:"⊛",ocir:"⊚",Ocirc:"Ô",ocirc:"ô",Ocy:"О",ocy:"о",odash:"⊝",Odblac:"Ő",odblac:"ő",odiv:"⨸",odot:"⊙",odsold:"⦼",OElig:"Œ",oelig:"œ",ofcir:"⦿",Ofr:"𝔒",ofr:"𝔬",ogon:"˛",Ograve:"Ò",ograve:"ò",ogt:"⧁",ohbar:"⦵",ohm:"Ω",oint:"∮",olarr:"↺",olcir:"⦾",olcross:"⦻",oline:"‾",olt:"⧀",Omacr:"Ō",omacr:"ō",Omega:"Ω",omega:"ω",Omicron:"Ο",omicron:"ο",omid:"⦶",ominus:"⊖",Oopf:"𝕆",oopf:"𝕠",opar:"⦷",OpenCurlyDoubleQuote:"“",OpenCurlyQuote:"‘",operp:"⦹",oplus:"⊕",Or:"⩔",or:"∨",orarr:"↻",ord:"⩝",order:"ℴ",orderof:"ℴ",ordf:"ª",ordm:"º",origof:"⊶",oror:"⩖",orslope:"⩗",orv:"⩛",oS:"Ⓢ",Oscr:"𝒪",oscr:"ℴ",Oslash:"Ø",oslash:"ø",osol:"⊘",Otilde:"Õ",otilde:"õ",Otimes:"⨷",otimes:"⊗",otimesas:"⨶",Ouml:"Ö",ouml:"ö",ovbar:"⌽",OverBar:"‾",OverBrace:"⏞",OverBracket:"⎴",OverParenthesis:"⏜",par:"∥",para:"¶",parallel:"∥",parsim:"⫳",parsl:"⫽",part:"∂",PartialD:"∂",Pcy:"П",pcy:"п",percnt:"%",period:".",permil:"‰",perp:"⊥",pertenk:"‱",Pfr:"𝔓",pfr:"𝔭",Phi:"Φ",phi:"φ",phiv:"ϕ",phmmat:"ℳ",phone:"☎",Pi:"Π",pi:"π",pitchfork:"⋔",piv:"ϖ",planck:"ℏ",planckh:"ℎ",plankv:"ℏ",plus:"+",plusacir:"⨣",plusb:"⊞",pluscir:"⨢",plusdo:"∔",plusdu:"⨥",pluse:"⩲",PlusMinus:"±",plusmn:"±",plussim:"⨦",plustwo:"⨧",pm:"±",Poincareplane:"ℌ",pointint:"⨕",Popf:"ℙ",popf:"𝕡",pound:"£",Pr:"⪻",pr:"≺",prap:"⪷",prcue:"≼",prE:"⪳",pre:"⪯",prec:"≺",precapprox:"⪷",preccurlyeq:"≼",Precedes:"≺",PrecedesEqual:"⪯",PrecedesSlantEqual:"≼",PrecedesTilde:"≾",preceq:"⪯",precnapprox:"⪹",precneqq:"⪵",precnsim:"⋨",precsim:"≾",Prime:"″",prime:"′",primes:"ℙ",prnap:"⪹",prnE:"⪵",prnsim:"⋨",prod:"∏",Product:"∏",profalar:"⌮",profline:"⌒",profsurf:"⌓",prop:"∝",Proportion:"∷",Proportional:"∝",propto:"∝",prsim:"≾",prurel:"⊰",Pscr:"𝒫",pscr:"𝓅",Psi:"Ψ",psi:"ψ",puncsp:" ",Qfr:"𝔔",qfr:"𝔮",qint:"⨌",Qopf:"ℚ",qopf:"𝕢",qprime:"⁗",Qscr:"𝒬",qscr:"𝓆",quaternions:"ℍ",quatint:"⨖",quest:"?",questeq:"≟",QUOT:'"',quot:'"',rAarr:"⇛",race:"∽̱",Racute:"Ŕ",racute:"ŕ",radic:"√",raemptyv:"⦳",Rang:"⟫",rang:"⟩",rangd:"⦒",range:"⦥",rangle:"⟩",raquo:"»",Rarr:"↠",rArr:"⇒",rarr:"→",rarrap:"⥵",rarrb:"⇥",rarrbfs:"⤠",rarrc:"⤳",rarrfs:"⤞",rarrhk:"↪",rarrlp:"↬",rarrpl:"⥅",rarrsim:"⥴",Rarrtl:"⤖",rarrtl:"↣",rarrw:"↝",rAtail:"⤜",ratail:"⤚",ratio:"∶",rationals:"ℚ",RBarr:"⤐",rBarr:"⤏",rbarr:"⤍",rbbrk:"❳",rbrace:"}",rbrack:"]",rbrke:"⦌",rbrksld:"⦎",rbrkslu:"⦐",Rcaron:"Ř",rcaron:"ř",Rcedil:"Ŗ",rcedil:"ŗ",rceil:"⌉",rcub:"}",Rcy:"Р",rcy:"р",rdca:"⤷",rdldhar:"⥩",rdquo:"”",rdquor:"”",rdsh:"↳",Re:"ℜ",real:"ℜ",realine:"ℛ",realpart:"ℜ",reals:"ℝ",rect:"▭",REG:"®",reg:"®",ReverseElement:"∋",ReverseEquilibrium:"⇋",ReverseUpEquilibrium:"⥯",rfisht:"⥽",rfloor:"⌋",Rfr:"ℜ",rfr:"𝔯",rHar:"⥤",rhard:"⇁",rharu:"⇀",rharul:"⥬",Rho:"Ρ",rho:"ρ",rhov:"ϱ",RightAngleBracket:"⟩",RightArrow:"→",Rightarrow:"⇒",rightarrow:"→",RightArrowBar:"⇥",RightArrowLeftArrow:"⇄",rightarrowtail:"↣",RightCeiling:"⌉",RightDoubleBracket:"⟧",RightDownTeeVector:"⥝",RightDownVector:"⇂",RightDownVectorBar:"⥕",RightFloor:"⌋",rightharpoondown:"⇁",rightharpoonup:"⇀",rightleftarrows:"⇄",rightleftharpoons:"⇌",rightrightarrows:"⇉",rightsquigarrow:"↝",RightTee:"⊢",RightTeeArrow:"↦",RightTeeVector:"⥛",rightthreetimes:"⋌",RightTriangle:"⊳",RightTriangleBar:"⧐",RightTriangleEqual:"⊵",RightUpDownVector:"⥏",RightUpTeeVector:"⥜",RightUpVector:"↾",RightUpVectorBar:"⥔",RightVector:"⇀",RightVectorBar:"⥓",ring:"˚",risingdotseq:"≓",rlarr:"⇄",rlhar:"⇌",rlm:"‏",rmoust:"⎱",rmoustache:"⎱",rnmid:"⫮",roang:"⟭",roarr:"⇾",robrk:"⟧",ropar:"⦆",Ropf:"ℝ",ropf:"𝕣",roplus:"⨮",rotimes:"⨵",RoundImplies:"⥰",rpar:")",rpargt:"⦔",rppolint:"⨒",rrarr:"⇉",Rrightarrow:"⇛",rsaquo:"›",Rscr:"ℛ",rscr:"𝓇",Rsh:"↱",rsh:"↱",rsqb:"]",rsquo:"’",rsquor:"’",rthree:"⋌",rtimes:"⋊",rtri:"▹",rtrie:"⊵",rtrif:"▸",rtriltri:"⧎",RuleDelayed:"⧴",ruluhar:"⥨",rx:"℞",Sacute:"Ś",sacute:"ś",sbquo:"‚",Sc:"⪼",sc:"≻",scap:"⪸",Scaron:"Š",scaron:"š",sccue:"≽",scE:"⪴",sce:"⪰",Scedil:"Ş",scedil:"ş",Scirc:"Ŝ",scirc:"ŝ",scnap:"⪺",scnE:"⪶",scnsim:"⋩",scpolint:"⨓",scsim:"≿",Scy:"С",scy:"с",sdot:"⋅",sdotb:"⊡",sdote:"⩦",searhk:"⤥",seArr:"⇘",searr:"↘",searrow:"↘",sect:"§",semi:";",seswar:"⤩",setminus:"∖",setmn:"∖",sext:"✶",Sfr:"𝔖",sfr:"𝔰",sfrown:"⌢",sharp:"♯",SHCHcy:"Щ",shchcy:"щ",SHcy:"Ш",shcy:"ш",ShortDownArrow:"↓",ShortLeftArrow:"←",shortmid:"∣",shortparallel:"∥",ShortRightArrow:"→",ShortUpArrow:"↑",shy:"­",Sigma:"Σ",sigma:"σ",sigmaf:"ς",sigmav:"ς",sim:"∼",simdot:"⩪",sime:"≃",simeq:"≃",simg:"⪞",simgE:"⪠",siml:"⪝",simlE:"⪟",simne:"≆",simplus:"⨤",simrarr:"⥲",slarr:"←",SmallCircle:"∘",smallsetminus:"∖",smashp:"⨳",smeparsl:"⧤",smid:"∣",smile:"⌣",smt:"⪪",smte:"⪬",smtes:"⪬︀",SOFTcy:"Ь",softcy:"ь",sol:"/",solb:"⧄",solbar:"⌿",Sopf:"𝕊",sopf:"𝕤",spades:"♠",spadesuit:"♠",spar:"∥",sqcap:"⊓",sqcaps:"⊓︀",sqcup:"⊔",sqcups:"⊔︀",Sqrt:"√",sqsub:"⊏",sqsube:"⊑",sqsubset:"⊏",sqsubseteq:"⊑",sqsup:"⊐",sqsupe:"⊒",sqsupset:"⊐",sqsupseteq:"⊒",squ:"□",Square:"□",square:"□",SquareIntersection:"⊓",SquareSubset:"⊏",SquareSubsetEqual:"⊑",SquareSuperset:"⊐",SquareSupersetEqual:"⊒",SquareUnion:"⊔",squarf:"▪",squf:"▪",srarr:"→",Sscr:"𝒮",sscr:"𝓈",ssetmn:"∖",ssmile:"⌣",sstarf:"⋆",Star:"⋆",star:"☆",starf:"★",straightepsilon:"ϵ",straightphi:"ϕ",strns:"¯",Sub:"⋐",sub:"⊂",subdot:"⪽",subE:"⫅",sube:"⊆",subedot:"⫃",submult:"⫁",subnE:"⫋",subne:"⊊",subplus:"⪿",subrarr:"⥹",Subset:"⋐",subset:"⊂",subseteq:"⊆",subseteqq:"⫅",SubsetEqual:"⊆",subsetneq:"⊊",subsetneqq:"⫋",subsim:"⫇",subsub:"⫕",subsup:"⫓",succ:"≻",succapprox:"⪸",succcurlyeq:"≽",Succeeds:"≻",SucceedsEqual:"⪰",SucceedsSlantEqual:"≽",SucceedsTilde:"≿",succeq:"⪰",succnapprox:"⪺",succneqq:"⪶",succnsim:"⋩",succsim:"≿",SuchThat:"∋",Sum:"∑",sum:"∑",sung:"♪",Sup:"⋑",sup:"⊃",sup1:"¹",sup2:"²",sup3:"³",supdot:"⪾",supdsub:"⫘",supE:"⫆",supe:"⊇",supedot:"⫄",Superset:"⊃",SupersetEqual:"⊇",suphsol:"⟉",suphsub:"⫗",suplarr:"⥻",supmult:"⫂",supnE:"⫌",supne:"⊋",supplus:"⫀",Supset:"⋑",supset:"⊃",supseteq:"⊇",supseteqq:"⫆",supsetneq:"⊋",supsetneqq:"⫌",supsim:"⫈",supsub:"⫔",supsup:"⫖",swarhk:"⤦",swArr:"⇙",swarr:"↙",swarrow:"↙",swnwar:"⤪",szlig:"ß",Tab:"\t",target:"⌖",Tau:"Τ",tau:"τ",tbrk:"⎴",Tcaron:"Ť",tcaron:"ť",Tcedil:"Ţ",tcedil:"ţ",Tcy:"Т",tcy:"т",tdot:"⃛",telrec:"⌕",Tfr:"𝔗",tfr:"𝔱",there4:"∴",Therefore:"∴",therefore:"∴",Theta:"Θ",theta:"θ",thetasym:"ϑ",thetav:"ϑ",thickapprox:"≈",thicksim:"∼",ThickSpace:"  ",thinsp:" ",ThinSpace:" ",thkap:"≈",thksim:"∼",THORN:"Þ",thorn:"þ",Tilde:"∼",tilde:"˜",TildeEqual:"≃",TildeFullEqual:"≅",TildeTilde:"≈",times:"×",timesb:"⊠",timesbar:"⨱",timesd:"⨰",tint:"∭",toea:"⤨",top:"⊤",topbot:"⌶",topcir:"⫱",Topf:"𝕋",topf:"𝕥",topfork:"⫚",tosa:"⤩",tprime:"‴",TRADE:"™",trade:"™",triangle:"▵",triangledown:"▿",triangleleft:"◃",trianglelefteq:"⊴",triangleq:"≜",triangleright:"▹",trianglerighteq:"⊵",tridot:"◬",trie:"≜",triminus:"⨺",TripleDot:"⃛",triplus:"⨹",trisb:"⧍",tritime:"⨻",trpezium:"⏢",Tscr:"𝒯",tscr:"𝓉",TScy:"Ц",tscy:"ц",TSHcy:"Ћ",tshcy:"ћ",Tstrok:"Ŧ",tstrok:"ŧ",twixt:"≬",twoheadleftarrow:"↞",twoheadrightarrow:"↠",Uacute:"Ú",uacute:"ú",Uarr:"↟",uArr:"⇑",uarr:"↑",Uarrocir:"⥉",Ubrcy:"Ў",ubrcy:"ў",Ubreve:"Ŭ",ubreve:"ŭ",Ucirc:"Û",ucirc:"û",Ucy:"У",ucy:"у",udarr:"⇅",Udblac:"Ű",udblac:"ű",udhar:"⥮",ufisht:"⥾",Ufr:"𝔘",ufr:"𝔲",Ugrave:"Ù",ugrave:"ù",uHar:"⥣",uharl:"↿",uharr:"↾",uhblk:"▀",ulcorn:"⌜",ulcorner:"⌜",ulcrop:"⌏",ultri:"◸",Umacr:"Ū",umacr:"ū",uml:"¨",UnderBar:"_",UnderBrace:"⏟",UnderBracket:"⎵",UnderParenthesis:"⏝",Union:"⋃",UnionPlus:"⊎",Uogon:"Ų",uogon:"ų",Uopf:"𝕌",uopf:"𝕦",UpArrow:"↑",Uparrow:"⇑",uparrow:"↑",UpArrowBar:"⤒",UpArrowDownArrow:"⇅",UpDownArrow:"↕",Updownarrow:"⇕",updownarrow:"↕",UpEquilibrium:"⥮",upharpoonleft:"↿",upharpoonright:"↾",uplus:"⊎",UpperLeftArrow:"↖",UpperRightArrow:"↗",Upsi:"ϒ",upsi:"υ",upsih:"ϒ",Upsilon:"Υ",upsilon:"υ",UpTee:"⊥",UpTeeArrow:"↥",upuparrows:"⇈",urcorn:"⌝",urcorner:"⌝",urcrop:"⌎",Uring:"Ů",uring:"ů",urtri:"◹",Uscr:"𝒰",uscr:"𝓊",utdot:"⋰",Utilde:"Ũ",utilde:"ũ",utri:"▵",utrif:"▴",uuarr:"⇈",Uuml:"Ü",uuml:"ü",uwangle:"⦧",vangrt:"⦜",varepsilon:"ϵ",varkappa:"ϰ",varnothing:"∅",varphi:"ϕ",varpi:"ϖ",varpropto:"∝",vArr:"⇕",varr:"↕",varrho:"ϱ",varsigma:"ς",varsubsetneq:"⊊︀",varsubsetneqq:"⫋︀",varsupsetneq:"⊋︀",varsupsetneqq:"⫌︀",vartheta:"ϑ",vartriangleleft:"⊲",vartriangleright:"⊳",Vbar:"⫫",vBar:"⫨",vBarv:"⫩",Vcy:"В",vcy:"в",VDash:"⊫",Vdash:"⊩",vDash:"⊨",vdash:"⊢",Vdashl:"⫦",Vee:"⋁",vee:"∨",veebar:"⊻",veeeq:"≚",vellip:"⋮",Verbar:"‖",verbar:"|",Vert:"‖",vert:"|",VerticalBar:"∣",VerticalLine:"|",VerticalSeparator:"❘",VerticalTilde:"≀",VeryThinSpace:" ",Vfr:"𝔙",vfr:"𝔳",vltri:"⊲",vnsub:"⊂⃒",vnsup:"⊃⃒",Vopf:"𝕍",vopf:"𝕧",vprop:"∝",vrtri:"⊳",Vscr:"𝒱",vscr:"𝓋",vsubnE:"⫋︀",vsubne:"⊊︀",vsupnE:"⫌︀",vsupne:"⊋︀",Vvdash:"⊪",vzigzag:"⦚",Wcirc:"Ŵ",wcirc:"ŵ",wedbar:"⩟",Wedge:"⋀",wedge:"∧",wedgeq:"≙",weierp:"℘",Wfr:"𝔚",wfr:"𝔴",Wopf:"𝕎",wopf:"𝕨",wp:"℘",wr:"≀",wreath:"≀",Wscr:"𝒲",wscr:"𝓌",xcap:"⋂",xcirc:"◯",xcup:"⋃",xdtri:"▽",Xfr:"𝔛",xfr:"𝔵",xhArr:"⟺",xharr:"⟷",Xi:"Ξ",xi:"ξ",xlArr:"⟸",xlarr:"⟵",xmap:"⟼",xnis:"⋻",xodot:"⨀",Xopf:"𝕏",xopf:"𝕩",xoplus:"⨁",xotime:"⨂",xrArr:"⟹",xrarr:"⟶",Xscr:"𝒳",xscr:"𝓍",xsqcup:"⨆",xuplus:"⨄",xutri:"△",xvee:"⋁",xwedge:"⋀",Yacute:"Ý",yacute:"ý",YAcy:"Я",yacy:"я",Ycirc:"Ŷ",ycirc:"ŷ",Ycy:"Ы",ycy:"ы",yen:"¥",Yfr:"𝔜",yfr:"𝔶",YIcy:"Ї",yicy:"ї",Yopf:"𝕐",yopf:"𝕪",Yscr:"𝒴",yscr:"𝓎",YUcy:"Ю",yucy:"ю",Yuml:"Ÿ",yuml:"ÿ",Zacute:"Ź",zacute:"ź",Zcaron:"Ž",zcaron:"ž",Zcy:"З",zcy:"з",Zdot:"Ż",zdot:"ż",zeetrf:"ℨ",ZeroWidthSpace:"​",Zeta:"Ζ",zeta:"ζ",Zfr:"ℨ",zfr:"𝔷",ZHcy:"Ж",zhcy:"ж",zigrarr:"⇝",Zopf:"ℤ",zopf:"𝕫",Zscr:"𝒵",zscr:"𝓏",zwj:"‍",zwnj:"‌"}),exports.entityMap=exports.HTML_ENTITIES},{"./conventions":1}],5:[function(require,module,exports){var dom=require("./dom");exports.DOMImplementation=dom.DOMImplementation,exports.XMLSerializer=dom.XMLSerializer,exports.DOMParser=require("./dom-parser").DOMParser},{"./dom":3,"./dom-parser":2}],6:[function(require,module,exports){var NAMESPACE=require("./conventions").NAMESPACE,nameStartChar=/[A-Z_a-z\xC0-\xD6\xD8-\xF6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/,nameChar=new RegExp("[\\-\\.0-9"+nameStartChar.source.slice(1,-1)+"\\u00B7\\u0300-\\u036F\\u203F-\\u2040]"),tagNamePattern=new RegExp("^"+nameStartChar.source+nameChar.source+"*(?::"+nameStartChar.source+nameChar.source+"*)?$"),S_TAG=0,S_ATTR=1,S_ATTR_SPACE=2,S_EQ=3,S_ATTR_NOQUOT_VALUE=4,S_ATTR_END=5,S_TAG_SPACE=6,S_TAG_CLOSE=7;function ParseError(message,locator){this.message=message,this.locator=locator,Error.captureStackTrace&&Error.captureStackTrace(this,ParseError)}function XMLReader(){}function parse(source,defaultNSMapCopy,entityMap,domBuilder,errorHandler){function fixedFromCharCode(code){if(code>65535){var surrogate1=55296+((code-=65536)>>10),surrogate2=56320+(1023&code);return String.fromCharCode(surrogate1,surrogate2)}return String.fromCharCode(code)}function entityReplacer(a){var k=a.slice(1,-1);return Object.hasOwnProperty.call(entityMap,k)?entityMap[k]:"#"===k.charAt(0)?fixedFromCharCode(parseInt(k.substr(1).replace("x","0x"))):(errorHandler.error("entity not found:"+a),a)}function appendText(end){if(end>start){var xt=source.substring(start,end).replace(/&#?\w+;/g,entityReplacer);locator&&position(start),domBuilder.characters(xt,0,end-start),start=end}}function position(p,m){for(;p>=lineEnd&&(m=linePattern.exec(source));)lineStart=m.index,lineEnd=lineStart+m[0].length,locator.lineNumber++;locator.columnNumber=p-lineStart+1}for(var lineStart=0,lineEnd=0,linePattern=/.*(?:\r\n?|\n)|.*$/g,locator=domBuilder.locator,parseStack=[{currentNSMap:defaultNSMapCopy}],closeMap={},start=0;;){try{var tagStart=source.indexOf("<",start);if(tagStart<0){if(!source.substr(start).match(/^\s*$/)){var doc=domBuilder.doc,text=doc.createTextNode(source.substr(start));doc.appendChild(text),domBuilder.currentElement=text}return}switch(tagStart>start&&appendText(tagStart),source.charAt(tagStart+1)){case"/":var end=source.indexOf(">",tagStart+3),tagName=source.substring(tagStart+2,end).replace(/[ \t\n\r]+$/g,""),config=parseStack.pop();end<0?(tagName=source.substring(tagStart+2).replace(/[\s<].*/,""),errorHandler.error("end tag name: "+tagName+" is not complete:"+config.tagName),end=tagStart+1+tagName.length):tagName.match(/\s</)&&(tagName=tagName.replace(/[\s<].*/,""),errorHandler.error("end tag name: "+tagName+" maybe not complete"),end=tagStart+1+tagName.length);var localNSMap=config.localNSMap,endMatch=config.tagName==tagName;if(endMatch||config.tagName&&config.tagName.toLowerCase()==tagName.toLowerCase()){if(domBuilder.endElement(config.uri,config.localName,tagName),localNSMap)for(var prefix in localNSMap)Object.prototype.hasOwnProperty.call(localNSMap,prefix)&&domBuilder.endPrefixMapping(prefix);endMatch||errorHandler.fatalError("end tag name: "+tagName+" is not match the current start tagName:"+config.tagName)}else parseStack.push(config);end++;break;case"?":locator&&position(tagStart),end=parseInstruction(source,tagStart,domBuilder);break;case"!":locator&&position(tagStart),end=parseDCC(source,tagStart,domBuilder,errorHandler);break;default:locator&&position(tagStart);var el=new ElementAttributes,currentNSMap=parseStack[parseStack.length-1].currentNSMap,len=(end=parseElementStartPart(source,tagStart,el,currentNSMap,entityReplacer,errorHandler),el.length);if(!el.closed&&fixSelfClosed(source,end,el.tagName,closeMap)&&(el.closed=!0,entityMap.nbsp||errorHandler.warning("unclosed xml attribute")),locator&&len){for(var locator2=copyLocator(locator,{}),i=0;i<len;i++){var a=el[i];position(a.offset),a.locator=copyLocator(locator,{})}domBuilder.locator=locator2,appendElement(el,domBuilder,currentNSMap)&&parseStack.push(el),domBuilder.locator=locator}else appendElement(el,domBuilder,currentNSMap)&&parseStack.push(el);NAMESPACE.isHTML(el.uri)&&!el.closed?end=parseHtmlSpecialContent(source,end,el.tagName,entityReplacer,domBuilder):end++}}catch(e){if(e instanceof ParseError)throw e;errorHandler.error("element parse error: "+e),end=-1}end>start?start=end:appendText(Math.max(tagStart,start)+1)}}function copyLocator(f,t){return t.lineNumber=f.lineNumber,t.columnNumber=f.columnNumber,t}function parseElementStartPart(source,start,el,currentNSMap,entityReplacer,errorHandler){function addAttribute(qname,value,startIndex){el.attributeNames.hasOwnProperty(qname)&&errorHandler.fatalError("Attribute "+qname+" redefined"),el.addValue(qname,value.replace(/[\t\n\r]/g," ").replace(/&#?\w+;/g,entityReplacer),startIndex)}for(var attrName,p=++start,s=S_TAG;;){var c=source.charAt(p);switch(c){case"=":if(s===S_ATTR)attrName=source.slice(start,p),s=S_EQ;else{if(s!==S_ATTR_SPACE)throw new Error("attribute equal must after attrName");s=S_EQ}break;case"'":case'"':if(s===S_EQ||s===S_ATTR){if(s===S_ATTR&&(errorHandler.warning('attribute value must after "="'),attrName=source.slice(start,p)),start=p+1,!((p=source.indexOf(c,start))>0))throw new Error("attribute value no end '"+c+"' match");addAttribute(attrName,value=source.slice(start,p),start-1),s=S_ATTR_END}else{if(s!=S_ATTR_NOQUOT_VALUE)throw new Error('attribute value must after "="');addAttribute(attrName,value=source.slice(start,p),start),errorHandler.warning('attribute "'+attrName+'" missed start quot('+c+")!!"),start=p+1,s=S_ATTR_END}break;case"/":switch(s){case S_TAG:el.setTagName(source.slice(start,p));case S_ATTR_END:case S_TAG_SPACE:case S_TAG_CLOSE:s=S_TAG_CLOSE,el.closed=!0;case S_ATTR_NOQUOT_VALUE:case S_ATTR:break;case S_ATTR_SPACE:el.closed=!0;break;default:throw new Error("attribute invalid close char('/')")}break;case"":return errorHandler.error("unexpected end of input"),s==S_TAG&&el.setTagName(source.slice(start,p)),p;case">":switch(s){case S_TAG:el.setTagName(source.slice(start,p));case S_ATTR_END:case S_TAG_SPACE:case S_TAG_CLOSE:break;case S_ATTR_NOQUOT_VALUE:case S_ATTR:"/"===(value=source.slice(start,p)).slice(-1)&&(el.closed=!0,value=value.slice(0,-1));case S_ATTR_SPACE:s===S_ATTR_SPACE&&(value=attrName),s==S_ATTR_NOQUOT_VALUE?(errorHandler.warning('attribute "'+value+'" missed quot(")!'),addAttribute(attrName,value,start)):(NAMESPACE.isHTML(currentNSMap[""])&&value.match(/^(?:disabled|checked|selected)$/i)||errorHandler.warning('attribute "'+value+'" missed value!! "'+value+'" instead!!'),addAttribute(value,value,start));break;case S_EQ:throw new Error("attribute value missed!!")}return p;case"€":c=" ";default:if(c<=" ")switch(s){case S_TAG:el.setTagName(source.slice(start,p)),s=S_TAG_SPACE;break;case S_ATTR:attrName=source.slice(start,p),s=S_ATTR_SPACE;break;case S_ATTR_NOQUOT_VALUE:var value=source.slice(start,p);errorHandler.warning('attribute "'+value+'" missed quot(")!!'),addAttribute(attrName,value,start);case S_ATTR_END:s=S_TAG_SPACE}else switch(s){case S_ATTR_SPACE:el.tagName,NAMESPACE.isHTML(currentNSMap[""])&&attrName.match(/^(?:disabled|checked|selected)$/i)||errorHandler.warning('attribute "'+attrName+'" missed value!! "'+attrName+'" instead2!!'),addAttribute(attrName,attrName,start),start=p,s=S_ATTR;break;case S_ATTR_END:errorHandler.warning('attribute space is required"'+attrName+'"!!');case S_TAG_SPACE:s=S_ATTR,start=p;break;case S_EQ:s=S_ATTR_NOQUOT_VALUE,start=p;break;case S_TAG_CLOSE:throw new Error("elements closed character '/' and '>' must be connected to")}}p++}}function appendElement(el,domBuilder,currentNSMap){for(var tagName=el.tagName,localNSMap=null,i=el.length;i--;){var a=el[i],qName=a.qName,value=a.value;if((nsp=qName.indexOf(":"))>0)var prefix=a.prefix=qName.slice(0,nsp),localName=qName.slice(nsp+1),nsPrefix="xmlns"===prefix&&localName;else localName=qName,prefix=null,nsPrefix="xmlns"===qName&&"";a.localName=localName,!1!==nsPrefix&&(null==localNSMap&&(localNSMap={},_copy(currentNSMap,currentNSMap={})),currentNSMap[nsPrefix]=localNSMap[nsPrefix]=value,a.uri=NAMESPACE.XMLNS,domBuilder.startPrefixMapping(nsPrefix,value))}for(i=el.length;i--;)(prefix=(a=el[i]).prefix)&&("xml"===prefix&&(a.uri=NAMESPACE.XML),"xmlns"!==prefix&&(a.uri=currentNSMap[prefix||""]));var nsp;(nsp=tagName.indexOf(":"))>0?(prefix=el.prefix=tagName.slice(0,nsp),localName=el.localName=tagName.slice(nsp+1)):(prefix=null,localName=el.localName=tagName);var ns=el.uri=currentNSMap[prefix||""];if(domBuilder.startElement(ns,localName,tagName,el),!el.closed)return el.currentNSMap=currentNSMap,el.localNSMap=localNSMap,!0;if(domBuilder.endElement(ns,localName,tagName),localNSMap)for(prefix in localNSMap)Object.prototype.hasOwnProperty.call(localNSMap,prefix)&&domBuilder.endPrefixMapping(prefix)}function parseHtmlSpecialContent(source,elStartEnd,tagName,entityReplacer,domBuilder){if(/^(?:script|textarea)$/i.test(tagName)){var elEndStart=source.indexOf("</"+tagName+">",elStartEnd),text=source.substring(elStartEnd+1,elEndStart);if(/[&<]/.test(text))return/^script$/i.test(tagName)?(domBuilder.characters(text,0,text.length),elEndStart):(text=text.replace(/&#?\w+;/g,entityReplacer),domBuilder.characters(text,0,text.length),elEndStart)}return elStartEnd+1}function fixSelfClosed(source,elStartEnd,tagName,closeMap){var pos=closeMap[tagName];return null==pos&&((pos=source.lastIndexOf("</"+tagName+">"))<elStartEnd&&(pos=source.lastIndexOf("</"+tagName)),closeMap[tagName]=pos),pos<elStartEnd}function _copy(source,target){for(var n in source)Object.prototype.hasOwnProperty.call(source,n)&&(target[n]=source[n])}function parseDCC(source,start,domBuilder,errorHandler){if("-"===source.charAt(start+2))return"-"===source.charAt(start+3)?(end=source.indexOf("--\x3e",start+4))>start?(domBuilder.comment(source,start+4,end-start-4),end+3):(errorHandler.error("Unclosed comment"),-1):-1;if("CDATA["==source.substr(start+3,6)){var end=source.indexOf("]]>",start+9);return domBuilder.startCDATA(),domBuilder.characters(source,start+9,end-start-9),domBuilder.endCDATA(),end+3}var matchs=split(source,start),len=matchs.length;if(len>1&&/!doctype/i.test(matchs[0][0])){var name=matchs[1][0],pubid=!1,sysid=!1;len>3&&(/^public$/i.test(matchs[2][0])?(pubid=matchs[3][0],sysid=len>4&&matchs[4][0]):/^system$/i.test(matchs[2][0])&&(sysid=matchs[3][0]));var lastMatch=matchs[len-1];return domBuilder.startDTD(name,pubid,sysid),domBuilder.endDTD(),lastMatch.index+lastMatch[0].length}return-1}function parseInstruction(source,start,domBuilder){var end=source.indexOf("?>",start);if(end){var match=source.substring(start,end).match(/^<\?(\S*)\s*([\s\S]*?)\s*$/);return match?(match[0].length,domBuilder.processingInstruction(match[1],match[2]),end+2):-1}return-1}function ElementAttributes(){this.attributeNames={}}function split(source,start){var match,buf=[],reg=/'[^']+'|"[^"]+"|[^\s<>\/=]+=?|(\/?\s*>|<)/g;for(reg.lastIndex=start,reg.exec(source);match=reg.exec(source);)if(buf.push(match),match[1])return buf}ParseError.prototype=new Error,ParseError.prototype.name=ParseError.name,XMLReader.prototype={parse:function(source,defaultNSMap,entityMap){var domBuilder=this.domBuilder;domBuilder.startDocument(),_copy(defaultNSMap,defaultNSMap={}),parse(source,defaultNSMap,entityMap,domBuilder,this.errorHandler),domBuilder.endDocument()}},ElementAttributes.prototype={setTagName:function(tagName){if(!tagNamePattern.test(tagName))throw new Error("invalid tagName:"+tagName);this.tagName=tagName},addValue:function(qName,value,offset){if(!tagNamePattern.test(qName))throw new Error("invalid attribute:"+qName);this.attributeNames[qName]=this.length,this[this.length++]={qName,value,offset}},length:0,getLocalName:function(i){return this[i].localName},getLocator:function(i){return this[i].locator},getQName:function(i){return this[i].qName},getURI:function(i){return this[i].uri},getValue:function(i){return this[i].value}},exports.XMLReader=XMLReader,exports.ParseError=ParseError},{"./conventions":1}],7:[function(require,module,exports){"use strict";var inherits=require("inherits"),EventEmitter=require("events").EventEmitter,LtxParser=require("ltx/lib/parsers/ltx"),xml=require("@xmpp/xml"),Stanza=xml.Stanza,Element=xml.Element;function StreamParser(options){EventEmitter.call(this);var self=this,ElementInterface=options&&options.Element||Element,ParserInterface=options&&options.Parser||LtxParser;this.maxStanzaSize=options&&options.maxStanzaSize,this.parser=new ParserInterface,this.bytesParsed=0,this.bytesParsedOnStanzaBegin=0,this.parser.on("startElement",function(name,attrs){var child;self.element||(self.emit("startElement",name,attrs),self.emit("start",new Element(name,attrs))),self.element||"stream:stream"!==name?self.element?(child=new ElementInterface(name,attrs),self.element=self.element.cnode(child)):(child=new Stanza(name,attrs),self.element=child,self.bytesParsedOnStanzaBegin=self.bytesParsed):self.emit("streamStart",attrs)}),this.parser.on("endElement",function(name){self.element||self.emit("endElement",name),self.element||"stream:stream"!==name?self.element&&name===self.element.name?self.element.parent?self.element=self.element.parent:(self.emit("element",self.element),self.emit("stanza",self.element),delete self.element,delete self.bytesParsedOnStanzaBegin):self.error("xml-not-well-formed","XML parse error"):self.end()}),this.parser.on("text",function(str){self.element&&self.element.t(str)}),this.parser.on("entityDecl",function(){self.error("xml-not-well-formed","No entity declarations allowed"),self.end()}),this.parser.on("error",this.emit.bind(this,"error"))}inherits(StreamParser,EventEmitter),StreamParser.prototype.checkXMLHeader=function(data){var index=data.indexOf("<?xml");if(-1!==index){var end=data.indexOf("?>");if(index>=0&&end>=0&&index<end+2){var search=data.substring(index,end+2);data=data.replace(search,"")}}return data},StreamParser.prototype.write=function(data){if(this.parser){if(data=data.toString("utf8"),data=this.checkXMLHeader(data),this.bytesParsedOnStanzaBegin&&this.maxStanzaSize&&this.bytesParsed>this.bytesParsedOnStanzaBegin+this.maxStanzaSize)return void this.error("policy-violation","Maximum stanza size exceeded");this.bytesParsed+=data.length,this.parser.write(data)}},StreamParser.prototype.end=function(data){data&&this.write(data),delete this.parser,this.emit("end")},StreamParser.prototype.error=function(condition,message){var e=new Error(message);e.condition=condition,this.emit("error",e)},module.exports=StreamParser},{"@xmpp/xml":8,events:37,inherits:41,"ltx/lib/parsers/ltx":53}],8:[function(require,module,exports){"use strict";var ltx=require("ltx"),tag=require("./lib/tag");exports=module.exports=function xml(){return tag.apply(null,arguments)},Object.assign(exports,ltx),exports.IQ=require("./lib/IQ"),exports.Message=require("./lib/Message"),exports.Presence=require("./lib/Presence"),exports.Stanza=require("./lib/Stanza"),exports.createStanza=require("./lib/createStanza"),exports.parse=require("./lib/parse"),exports.Parser=require("./lib/Parser"),exports.tag=require("./lib/tag"),exports.ltx=ltx},{"./lib/IQ":9,"./lib/Message":10,"./lib/Parser":11,"./lib/Presence":12,"./lib/Stanza":13,"./lib/createStanza":14,"./lib/parse":15,"./lib/tag":16,ltx:44}],9:[function(require,module,exports){"use strict";var Stanza=require("./Stanza");function IQ(attrs){Stanza.call(this,"iq",attrs)}require("inherits")(IQ,Stanza),module.exports=IQ},{"./Stanza":13,inherits:41}],10:[function(require,module,exports){"use strict";var Stanza=require("./Stanza");function Message(attrs){Stanza.call(this,"message",attrs)}require("inherits")(Message,Stanza),module.exports=Message},{"./Stanza":13,inherits:41}],11:[function(require,module,exports){"use strict";var inherits=require("inherits"),createStanza=require("./createStanza"),LtxParser=require("ltx").Parser;function Parser(options){LtxParser.call(this,options)}inherits(Parser,LtxParser),Parser.prototype.DefaultElement=createStanza,module.exports=Parser},{"./createStanza":14,inherits:41,ltx:44}],12:[function(require,module,exports){"use strict";var Stanza=require("./Stanza");function Presence(attrs){Stanza.call(this,"presence",attrs)}require("inherits")(Presence,Stanza),module.exports=Presence},{"./Stanza":13,inherits:41}],13:[function(require,module,exports){"use strict";var inherits=require("inherits"),Element=require("ltx").Element;function Stanza(name,attrs){Element.call(this,name,attrs)}inherits(Stanza,Element),Object.defineProperty(Stanza.prototype,"from",{get:function(){return this.attrs.from},set:function(from){this.attrs.from=from}}),Object.defineProperty(Stanza.prototype,"to",{get:function(){return this.attrs.to},set:function(to){this.attrs.to=to}}),Object.defineProperty(Stanza.prototype,"id",{get:function(){return this.attrs.id},set:function(id){this.attrs.id=id}}),Object.defineProperty(Stanza.prototype,"type",{get:function(){return this.attrs.type},set:function(type){this.attrs.type=type}}),module.exports=Stanza},{inherits:41,ltx:44}],14:[function(require,module,exports){"use strict";var Stanza=require("./Stanza"),Element=require("ltx").Element;module.exports=function createStanza(name,attrs){var el;switch(name){case"presence":case"message":case"iq":el=new Stanza(name,attrs);break;default:el=new Element(name,attrs)}return Array.prototype.slice.call(arguments,2).forEach(function(child){el.cnode(child)}),el}},{"./Stanza":13,ltx:44}],15:[function(require,module,exports){"use strict";var Parser=require("./Parser"),ltxParse=require("ltx").parse;module.exports=function parse(data){return ltxParse(data,Parser)}},{"./Parser":11,ltx:44}],16:[function(require,module,exports){"use strict";var tagString=require("ltx").tagString,parse=require("./parse");module.exports=function tag(){return parse(tagString.apply(null,arguments))}},{"./parse":15,ltx:44}],17:[function(require,module,exports){var Backoff=require("./lib/backoff"),ExponentialBackoffStrategy=require("./lib/strategy/exponential"),FibonacciBackoffStrategy=require("./lib/strategy/fibonacci"),FunctionCall=require("./lib/function_call.js");module.exports.Backoff=Backoff,module.exports.FunctionCall=FunctionCall,module.exports.FibonacciStrategy=FibonacciBackoffStrategy,module.exports.ExponentialStrategy=ExponentialBackoffStrategy,module.exports.fibonacci=function(options){return new Backoff(new FibonacciBackoffStrategy(options))},module.exports.exponential=function(options){return new Backoff(new ExponentialBackoffStrategy(options))},module.exports.call=function(fn,vargs,callback){var args=Array.prototype.slice.call(arguments);return fn=args[0],vargs=args.slice(1,args.length-1),callback=args[args.length-1],new FunctionCall(fn,vargs,callback)}},{"./lib/backoff":18,"./lib/function_call.js":19,"./lib/strategy/exponential":20,"./lib/strategy/fibonacci":21}],18:[function(require,module,exports){var events=require("events");function Backoff(backoffStrategy){events.EventEmitter.call(this),this.backoffStrategy_=backoffStrategy,this.maxNumberOfRetry_=-1,this.backoffNumber_=0,this.backoffDelay_=0,this.timeoutID_=-1,this.handlers={backoff:this.onBackoff_.bind(this)}}require("util").inherits(Backoff,events.EventEmitter),Backoff.prototype.failAfter=function(maxNumberOfRetry){if(maxNumberOfRetry<1)throw new Error("Maximum number of retry must be greater than 0. Actual: "+maxNumberOfRetry);this.maxNumberOfRetry_=maxNumberOfRetry},Backoff.prototype.backoff=function(err){if(-1!==this.timeoutID_)throw new Error("Backoff in progress.");this.backoffNumber_===this.maxNumberOfRetry_?(this.emit("fail",err),this.reset()):(this.backoffDelay_=this.backoffStrategy_.next(),this.timeoutID_=setTimeout(this.handlers.backoff,this.backoffDelay_),this.emit("backoff",this.backoffNumber_,this.backoffDelay_,err))},Backoff.prototype.onBackoff_=function(){this.timeoutID_=-1,this.emit("ready",this.backoffNumber_,this.backoffDelay_),this.backoffNumber_++},Backoff.prototype.reset=function(){this.backoffNumber_=0,this.backoffStrategy_.reset(),clearTimeout(this.timeoutID_),this.timeoutID_=-1},module.exports=Backoff},{events:37,util:116}],19:[function(require,module,exports){var events=require("events"),util=require("util"),Backoff=require("./backoff"),FibonacciBackoffStrategy=require("./strategy/fibonacci");function isFunction(val){return"function"==typeof val}function FunctionCall(fn,args,callback){if(events.EventEmitter.call(this),!isFunction(fn))throw new Error("fn should be a function.Actual: "+typeof fn);if(!isFunction(callback))throw new Error("callback should be a function.Actual: "+typeof fn);this.function_=fn,this.arguments_=args,this.callback_=callback,this.results_=[],this.backoff_=null,this.strategy_=null,this.failAfter_=-1,this.state_=FunctionCall.State_.PENDING}util.inherits(FunctionCall,events.EventEmitter),FunctionCall.State_={PENDING:0,RUNNING:1,COMPLETED:2,ABORTED:3},FunctionCall.prototype.isPending=function(){return this.state_==FunctionCall.State_.PENDING},FunctionCall.prototype.isRunning=function(){return this.state_==FunctionCall.State_.RUNNING},FunctionCall.prototype.isCompleted=function(){return this.state_==FunctionCall.State_.COMPLETED},FunctionCall.prototype.isAborted=function(){return this.state_==FunctionCall.State_.ABORTED},FunctionCall.prototype.setStrategy=function(strategy){if(!this.isPending())throw new Error("FunctionCall in progress.");return this.strategy_=strategy,this},FunctionCall.prototype.getResults=function(){return this.results_.concat()},FunctionCall.prototype.failAfter=function(maxNumberOfRetry){if(!this.isPending())throw new Error("FunctionCall in progress.");return this.failAfter_=maxNumberOfRetry,this},FunctionCall.prototype.abort=function(){if(this.isCompleted())throw new Error("FunctionCall already completed.");this.isRunning()&&this.backoff_.reset(),this.state_=FunctionCall.State_.ABORTED},FunctionCall.prototype.start=function(backoffFactory){if(this.isAborted())throw new Error("FunctionCall aborted.");if(!this.isPending())throw new Error("FunctionCall already started.");var strategy=this.strategy_||new FibonacciBackoffStrategy;this.backoff_=backoffFactory?backoffFactory(strategy):new Backoff(strategy),this.backoff_.on("ready",this.doCall_.bind(this)),this.backoff_.on("fail",this.doCallback_.bind(this)),this.backoff_.on("backoff",this.handleBackoff_.bind(this)),this.failAfter_>0&&this.backoff_.failAfter(this.failAfter_),this.state_=FunctionCall.State_.RUNNING,this.doCall_()},FunctionCall.prototype.doCall_=function(){var eventArgs=["call"].concat(this.arguments_);events.EventEmitter.prototype.emit.apply(this,eventArgs);var callback=this.handleFunctionCallback_.bind(this);this.function_.apply(null,this.arguments_.concat(callback))},FunctionCall.prototype.doCallback_=function(){var args=this.results_[this.results_.length-1];this.callback_.apply(null,args)},FunctionCall.prototype.handleFunctionCallback_=function(){if(!this.isAborted()){var args=Array.prototype.slice.call(arguments);this.results_.push(args),events.EventEmitter.prototype.emit.apply(this,["callback"].concat(args)),args[0]?this.backoff_.backoff(args[0]):(this.state_=FunctionCall.State_.COMPLETED,this.doCallback_())}},FunctionCall.prototype.handleBackoff_=function(number,delay,err){this.emit("backoff",number,delay,err)},module.exports=FunctionCall},{"./backoff":18,"./strategy/fibonacci":21,events:37,util:116}],20:[function(require,module,exports){var util=require("util"),BackoffStrategy=require("./strategy");function ExponentialBackoffStrategy(options){BackoffStrategy.call(this,options),this.backoffDelay_=0,this.nextBackoffDelay_=this.getInitialDelay()}util.inherits(ExponentialBackoffStrategy,BackoffStrategy),ExponentialBackoffStrategy.prototype.next_=function(){return this.backoffDelay_=Math.min(this.nextBackoffDelay_,this.getMaxDelay()),this.nextBackoffDelay_=2*this.backoffDelay_,this.backoffDelay_},ExponentialBackoffStrategy.prototype.reset_=function(){this.backoffDelay_=0,this.nextBackoffDelay_=this.getInitialDelay()},module.exports=ExponentialBackoffStrategy},{"./strategy":22,util:116}],21:[function(require,module,exports){var util=require("util"),BackoffStrategy=require("./strategy");function FibonacciBackoffStrategy(options){BackoffStrategy.call(this,options),this.backoffDelay_=0,this.nextBackoffDelay_=this.getInitialDelay()}util.inherits(FibonacciBackoffStrategy,BackoffStrategy),FibonacciBackoffStrategy.prototype.next_=function(){var backoffDelay=Math.min(this.nextBackoffDelay_,this.getMaxDelay());return this.nextBackoffDelay_+=this.backoffDelay_,this.backoffDelay_=backoffDelay,backoffDelay},FibonacciBackoffStrategy.prototype.reset_=function(){this.nextBackoffDelay_=this.getInitialDelay(),this.backoffDelay_=0},module.exports=FibonacciBackoffStrategy},{"./strategy":22,util:116}],22:[function(require,module,exports){function isDef(value){return null!=value}function BackoffStrategy(options){if(isDef((options=options||{}).initialDelay)&&options.initialDelay<1)throw new Error("The initial timeout must be greater than 0.");if(isDef(options.maxDelay)&&options.maxDelay<1)throw new Error("The maximal timeout must be greater than 0.");if(this.initialDelay_=options.initialDelay||100,this.maxDelay_=options.maxDelay||1e4,this.maxDelay_<=this.initialDelay_)throw new Error("The maximal backoff delay must be greater than the initial backoff delay.");if(isDef(options.randomisationFactor)&&(options.randomisationFactor<0||options.randomisationFactor>1))throw new Error("The randomisation factor must be between 0 and 1.");this.randomisationFactor_=options.randomisationFactor||0}require("events"),require("util"),BackoffStrategy.prototype.getMaxDelay=function(){return this.maxDelay_},BackoffStrategy.prototype.getInitialDelay=function(){return this.initialDelay_},BackoffStrategy.prototype.next=function(){var backoffDelay=this.next_(),randomisationMultiple=1+Math.random()*this.randomisationFactor_;return Math.round(backoffDelay*randomisationMultiple)},BackoffStrategy.prototype.next_=function(){throw new Error("BackoffStrategy.next_() unimplemented.")},BackoffStrategy.prototype.reset=function(){this.reset_()},BackoffStrategy.prototype.reset_=function(){throw new Error("BackoffStrategy.reset_() unimplemented.")},module.exports=BackoffStrategy},{events:37,util:116}],23:[function(require,module,exports){"use strict";exports.byteLength=byteLength,exports.toByteArray=toByteArray,exports.fromByteArray=fromByteArray;for(var lookup=[],revLookup=[],Arr="undefined"!=typeof Uint8Array?Uint8Array:Array,code="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",i=0,len=code.length;i<len;++i)lookup[i]=code[i],revLookup[code.charCodeAt(i)]=i;function getLens(b64){var len=b64.length;if(len%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var validLen=b64.indexOf("=");return-1===validLen&&(validLen=len),[validLen,validLen===len?0:4-validLen%4]}function byteLength(b64){var lens=getLens(b64),validLen=lens[0],placeHoldersLen=lens[1];return 3*(validLen+placeHoldersLen)/4-placeHoldersLen}function _byteLength(b64,validLen,placeHoldersLen){return 3*(validLen+placeHoldersLen)/4-placeHoldersLen}function toByteArray(b64){var tmp,i,lens=getLens(b64),validLen=lens[0],placeHoldersLen=lens[1],arr=new Arr(_byteLength(b64,validLen,placeHoldersLen)),curByte=0,len=placeHoldersLen>0?validLen-4:validLen;for(i=0;i<len;i+=4)tmp=revLookup[b64.charCodeAt(i)]<<18|revLookup[b64.charCodeAt(i+1)]<<12|revLookup[b64.charCodeAt(i+2)]<<6|revLookup[b64.charCodeAt(i+3)],arr[curByte++]=tmp>>16&255,arr[curByte++]=tmp>>8&255,arr[curByte++]=255&tmp;return 2===placeHoldersLen&&(tmp=revLookup[b64.charCodeAt(i)]<<2|revLookup[b64.charCodeAt(i+1)]>>4,arr[curByte++]=255&tmp),1===placeHoldersLen&&(tmp=revLookup[b64.charCodeAt(i)]<<10|revLookup[b64.charCodeAt(i+1)]<<4|revLookup[b64.charCodeAt(i+2)]>>2,arr[curByte++]=tmp>>8&255,arr[curByte++]=255&tmp),arr}function tripletToBase64(num){return lookup[num>>18&63]+lookup[num>>12&63]+lookup[num>>6&63]+lookup[63&num]}function encodeChunk(uint8,start,end){for(var tmp,output=[],i=start;i<end;i+=3)tmp=(uint8[i]<<16&16711680)+(uint8[i+1]<<8&65280)+(255&uint8[i+2]),output.push(tripletToBase64(tmp));return output.join("")}function fromByteArray(uint8){for(var tmp,len=uint8.length,extraBytes=len%3,parts=[],maxChunkLength=16383,i=0,len2=len-extraBytes;i<len2;i+=maxChunkLength)parts.push(encodeChunk(uint8,i,i+maxChunkLength>len2?len2:i+maxChunkLength));return 1===extraBytes?(tmp=uint8[len-1],parts.push(lookup[tmp>>2]+lookup[tmp<<4&63]+"==")):2===extraBytes&&(tmp=(uint8[len-2]<<8)+uint8[len-1],parts.push(lookup[tmp>>10]+lookup[tmp>>4&63]+lookup[tmp<<2&63]+"=")),parts.join("")}revLookup["-".charCodeAt(0)]=62,revLookup["_".charCodeAt(0)]=63},{}],24:[function(require,module,exports){var root,factory;root=this,factory=function(){var XHR=XMLHttpRequest;if(!XHR)throw new Error("missing XMLHttpRequest");request.log={trace:noop,debug:noop,info:noop,warn:noop,error:noop};var DEFAULT_TIMEOUT=18e4;function request(options,callback){if("function"!=typeof callback)throw new Error("Bad callback given: "+callback);if(!options)throw new Error("No options given");var options_onResponse=options.onResponse;if((options="string"==typeof options?{uri:options}:JSON.parse(JSON.stringify(options))).onResponse=options_onResponse,options.verbose&&(request.log=getLogger()),options.url&&(options.uri=options.url,delete options.url),!options.uri&&""!==options.uri)throw new Error("options.uri is a required argument");if("string"!=typeof options.uri)throw new Error("options.uri must be a string");for(var unsupported_options=["proxy","_redirectsFollowed","maxRedirects","followRedirect"],i=0;i<unsupported_options.length;i++)if(options[unsupported_options[i]])throw new Error("options."+unsupported_options[i]+" is not supported");if(options.callback=callback,options.method=options.method||"GET",options.headers=options.headers||{},options.body=options.body||null,options.timeout=options.timeout||request.DEFAULT_TIMEOUT,options.headers.host)throw new Error("Options.headers.host is not supported");options.json&&(options.headers.accept=options.headers.accept||"application/json","GET"!==options.method&&(options.headers["content-type"]="application/json"),"boolean"!=typeof options.json?options.body=JSON.stringify(options.json):"string"!=typeof options.body&&(options.body=JSON.stringify(options.body)));var serialize=function(obj){var str=[];for(var p in obj)obj.hasOwnProperty(p)&&str.push(encodeURIComponent(p)+"="+encodeURIComponent(obj[p]));return str.join("&")};if(options.qs){var qs="string"==typeof options.qs?options.qs:serialize(options.qs);-1!==options.uri.indexOf("?")?options.uri=options.uri+"&"+qs:options.uri=options.uri+"?"+qs}var multipart=function(obj){var result={};result.boundry="-------------------------------"+Math.floor(1e9*Math.random());var lines=[];for(var p in obj)obj.hasOwnProperty(p)&&lines.push("--"+result.boundry+'\nContent-Disposition: form-data; name="'+p+'"\n\n'+obj[p]+"\n");return lines.push("--"+result.boundry+"--"),result.body=lines.join(""),result.length=result.body.length,result.type="multipart/form-data; boundary="+result.boundry,result};if(options.form){if("string"==typeof options.form)throw"form name unsupported";if("POST"===options.method){var encoding=(options.encoding||"application/x-www-form-urlencoded").toLowerCase();switch(options.headers["content-type"]=encoding,encoding){case"application/x-www-form-urlencoded":options.body=serialize(options.form).replace(/%20/g,"+");break;case"multipart/form-data":var multi=multipart(options.form);options.body=multi.body,options.headers["content-type"]=multi.type;break;default:throw new Error("unsupported encoding:"+encoding)}}}return options.onResponse=options.onResponse||noop,!0===options.onResponse&&(options.onResponse=callback,options.callback=noop),!options.headers.authorization&&options.auth&&(options.headers.authorization="Basic "+b64_enc(options.auth.username+":"+options.auth.password)),run_xhr(options)}var req_seq=0;function run_xhr(options){var xhr=new XHR,timed_out=!1,is_cors=is_crossDomain(options.uri),supports_cors="withCredentials"in xhr;if(req_seq+=1,xhr.seq_id=req_seq,xhr.id=req_seq+": "+options.method+" "+options.uri,xhr._id=xhr.id,is_cors&&!supports_cors){var cors_err=new Error("Browser does not support cross-origin request: "+options.uri);return cors_err.cors="unsupported",options.callback(cors_err,xhr)}function too_late(){timed_out=!0;var er=new Error("ETIMEDOUT");return er.code="ETIMEDOUT",er.duration=options.timeout,request.log.error("Timeout",{id:xhr._id,milliseconds:options.timeout}),options.callback(er,xhr)}xhr.timeoutTimer=setTimeout(too_late,options.timeout);var did={response:!1,loading:!1,end:!1};return xhr.onreadystatechange=on_state_change,xhr.open(options.method,options.uri,!0),is_cors&&(xhr.withCredentials=!!options.withCredentials),xhr.send(options.body),xhr;function on_state_change(event){if(timed_out)return request.log.debug("Ignoring timed out state change",{state:xhr.readyState,id:xhr.id});if(request.log.debug("State change",{state:xhr.readyState,id:xhr.id,timed_out}),xhr.readyState===XHR.OPENED)for(var key in request.log.debug("Request started",{id:xhr.id}),options.headers)xhr.setRequestHeader(key,options.headers[key]);else xhr.readyState===XHR.HEADERS_RECEIVED?on_response():xhr.readyState===XHR.LOADING?(on_response(),on_loading()):xhr.readyState===XHR.DONE&&(on_response(),on_loading(),on_end())}function on_response(){if(!did.response){if(did.response=!0,request.log.debug("Got response",{id:xhr.id,status:xhr.status}),clearTimeout(xhr.timeoutTimer),xhr.statusCode=xhr.status,is_cors&&0==xhr.statusCode){var cors_err=new Error("CORS request rejected: "+options.uri);return cors_err.cors="rejected",did.loading=!0,did.end=!0,options.callback(cors_err,xhr)}options.onResponse(null,xhr)}}function on_loading(){did.loading||(did.loading=!0,request.log.debug("Response body loading",{id:xhr.id}))}function on_end(){if(!did.end){if(did.end=!0,request.log.debug("Request done",{id:xhr.id}),xhr.body=xhr.responseText,options.json)try{xhr.body=JSON.parse(xhr.responseText)}catch(er){return options.callback(er,xhr)}options.callback(null,xhr,xhr.body)}}}function noop(){}function getLogger(){var level,i,logger={},levels=["trace","debug","info","warn","error"];for(i=0;i<levels.length;i++)logger[level=levels[i]]=noop,"undefined"!=typeof console&&console&&console[level]&&(logger[level]=formatted(console,level));return logger}function formatted(obj,method){return formatted_logger;function formatted_logger(str,context){return"object"==typeof context&&(str+=" "+JSON.stringify(context)),obj[method].call(obj,str)}}function is_crossDomain(url){var ajaxLocation,rurl=/^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+))?)?/;try{ajaxLocation=location.href}catch(e){(ajaxLocation=document.createElement("a")).href="",ajaxLocation=ajaxLocation.href}var ajaxLocParts=rurl.exec(ajaxLocation.toLowerCase())||[],parts=rurl.exec(url.toLowerCase());return!(!parts||parts[1]==ajaxLocParts[1]&&parts[2]==ajaxLocParts[2]&&(parts[3]||("http:"===parts[1]?80:443))==(ajaxLocParts[3]||("http:"===ajaxLocParts[1]?80:443)))}function b64_enc(data){var h1,h2,h3,h4,bits,b64="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",i=0,ac=0,enc="",tmp_arr=[];if(!data)return data;do{h1=(bits=data.charCodeAt(i++)<<16|data.charCodeAt(i++)<<8|data.charCodeAt(i++))>>18&63,h2=bits>>12&63,h3=bits>>6&63,h4=63&bits,tmp_arr[ac++]=b64.charAt(h1)+b64.charAt(h2)+b64.charAt(h3)+b64.charAt(h4)}while(i<data.length);switch(enc=tmp_arr.join(""),data.length%3){case 1:enc=enc.slice(0,-2)+"==";break;case 2:enc=enc.slice(0,-1)+"="}return enc}return request.withCredentials=!1,request.DEFAULT_TIMEOUT=DEFAULT_TIMEOUT,request.defaults=function(options,requester){var def=function(method){return function(params,callback){for(var i in params="string"==typeof params?{uri:params}:JSON.parse(JSON.stringify(params)),options)void 0===params[i]&&(params[i]=options[i]);return method(params,callback)}},de=def(request);return de.get=def(request.get),de.post=def(request.post),de.put=def(request.put),de.head=def(request.head),de},["get","put","post","head"].forEach(function(shortcut){var method=shortcut.toUpperCase();request[shortcut.toLowerCase()]=function(opts){"string"==typeof opts?opts={method,uri:opts}:(opts=JSON.parse(JSON.stringify(opts))).method=method;var args=[opts].concat(Array.prototype.slice.apply(arguments,[1]));return request.apply(this,args)}}),request.couch=function(options,callback){return"string"==typeof options&&(options={uri:options}),options.json=!0,options.body&&(options.json=options.body),delete options.body,callback=callback||noop,request(options,couch_handler);function couch_handler(er,resp,body){if(er)return callback(er,resp,body);if((resp.statusCode<200||resp.statusCode>299)&&body.error){for(var key in er=new Error("CouchDB error: "+(body.error.reason||body.error.error)),body)er[key]=body[key];return callback(er,resp,body)}return callback(er,resp,body)}},request},"function"==typeof define&&define.amd?define([],factory):"object"==typeof exports?module.exports=factory():root.returnExports=factory()},{}],25:[function(require,module,exports){},{}],26:[function(require,module,exports){arguments[4][25][0].apply(exports,arguments)},{dup:25}],27:[function(require,module,exports){(function(global,Buffer){(function(){"use strict";var base64=require("base64-js"),ieee754=require("ieee754"),isArray=require("isarray");function typedArraySupport(){try{var arr=new Uint8Array(1);return arr.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}},42===arr.foo()&&"function"==typeof arr.subarray&&0===arr.subarray(1,1).byteLength}catch(e){return!1}}function kMaxLength(){return Buffer.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function createBuffer(that,length){if(kMaxLength()<length)throw new RangeError("Invalid typed array length");return Buffer.TYPED_ARRAY_SUPPORT?(that=new Uint8Array(length)).__proto__=Buffer.prototype:(null===that&&(that=new Buffer(length)),that.length=length),that}function Buffer(arg,encodingOrOffset,length){if(!(Buffer.TYPED_ARRAY_SUPPORT||this instanceof Buffer))return new Buffer(arg,encodingOrOffset,length);if("number"==typeof arg){if("string"==typeof encodingOrOffset)throw new Error("If encoding is specified then the first argument must be a string");return allocUnsafe(this,arg)}return from(this,arg,encodingOrOffset,length)}function from(that,value,encodingOrOffset,length){if("number"==typeof value)throw new TypeError('"value" argument must not be a number');return"undefined"!=typeof ArrayBuffer&&value instanceof ArrayBuffer?fromArrayBuffer(that,value,encodingOrOffset,length):"string"==typeof value?fromString(that,value,encodingOrOffset):fromObject(that,value)}function assertSize(size){if("number"!=typeof size)throw new TypeError('"size" argument must be a number');if(size<0)throw new RangeError('"size" argument must not be negative')}function alloc(that,size,fill,encoding){return assertSize(size),size<=0?createBuffer(that,size):void 0!==fill?"string"==typeof encoding?createBuffer(that,size).fill(fill,encoding):createBuffer(that,size).fill(fill):createBuffer(that,size)}function allocUnsafe(that,size){if(assertSize(size),that=createBuffer(that,size<0?0:0|checked(size)),!Buffer.TYPED_ARRAY_SUPPORT)for(var i=0;i<size;++i)that[i]=0;return that}function fromString(that,string,encoding){if("string"==typeof encoding&&""!==encoding||(encoding="utf8"),!Buffer.isEncoding(encoding))throw new TypeError('"encoding" must be a valid string encoding');var length=0|byteLength(string,encoding),actual=(that=createBuffer(that,length)).write(string,encoding);return actual!==length&&(that=that.slice(0,actual)),that}function fromArrayLike(that,array){var length=array.length<0?0:0|checked(array.length);that=createBuffer(that,length);for(var i=0;i<length;i+=1)that[i]=255&array[i];return that}function fromArrayBuffer(that,array,byteOffset,length){if(array.byteLength,byteOffset<0||array.byteLength<byteOffset)throw new RangeError("'offset' is out of bounds");if(array.byteLength<byteOffset+(length||0))throw new RangeError("'length' is out of bounds");return array=void 0===byteOffset&&void 0===length?new Uint8Array(array):void 0===length?new Uint8Array(array,byteOffset):new Uint8Array(array,byteOffset,length),Buffer.TYPED_ARRAY_SUPPORT?(that=array).__proto__=Buffer.prototype:that=fromArrayLike(that,array),that}function fromObject(that,obj){if(Buffer.isBuffer(obj)){var len=0|checked(obj.length);return 0===(that=createBuffer(that,len)).length||obj.copy(that,0,0,len),that}if(obj){if("undefined"!=typeof ArrayBuffer&&obj.buffer instanceof ArrayBuffer||"length"in obj)return"number"!=typeof obj.length||isnan(obj.length)?createBuffer(that,0):fromArrayLike(that,obj);if("Buffer"===obj.type&&isArray(obj.data))return fromArrayLike(that,obj.data)}throw new TypeError("First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.")}function checked(length){if(length>=kMaxLength())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+kMaxLength().toString(16)+" bytes");return 0|length}function SlowBuffer(length){return+length!=length&&(length=0),Buffer.alloc(+length)}function byteLength(string,encoding){if(Buffer.isBuffer(string))return string.length;if("undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView&&(ArrayBuffer.isView(string)||string instanceof ArrayBuffer))return string.byteLength;"string"!=typeof string&&(string=""+string);var len=string.length;if(0===len)return 0;for(var loweredCase=!1;;)switch(encoding){case"ascii":case"latin1":case"binary":return len;case"utf8":case"utf-8":case void 0:return utf8ToBytes(string).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*len;case"hex":return len>>>1;case"base64":return base64ToBytes(string).length;default:if(loweredCase)return utf8ToBytes(string).length;encoding=(""+encoding).toLowerCase(),loweredCase=!0}}function slowToString(encoding,start,end){var loweredCase=!1;if((void 0===start||start<0)&&(start=0),start>this.length)return"";if((void 0===end||end>this.length)&&(end=this.length),end<=0)return"";if((end>>>=0)<=(start>>>=0))return"";for(encoding||(encoding="utf8");;)switch(encoding){case"hex":return hexSlice(this,start,end);case"utf8":case"utf-8":return utf8Slice(this,start,end);case"ascii":return asciiSlice(this,start,end);case"latin1":case"binary":return latin1Slice(this,start,end);case"base64":return base64Slice(this,start,end);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return utf16leSlice(this,start,end);default:if(loweredCase)throw new TypeError("Unknown encoding: "+encoding);encoding=(encoding+"").toLowerCase(),loweredCase=!0}}function swap(b,n,m){var i=b[n];b[n]=b[m],b[m]=i}function bidirectionalIndexOf(buffer,val,byteOffset,encoding,dir){if(0===buffer.length)return-1;if("string"==typeof byteOffset?(encoding=byteOffset,byteOffset=0):byteOffset>2147483647?byteOffset=2147483647:byteOffset<-2147483648&&(byteOffset=-2147483648),byteOffset=+byteOffset,isNaN(byteOffset)&&(byteOffset=dir?0:buffer.length-1),byteOffset<0&&(byteOffset=buffer.length+byteOffset),byteOffset>=buffer.length){if(dir)return-1;byteOffset=buffer.length-1}else if(byteOffset<0){if(!dir)return-1;byteOffset=0}if("string"==typeof val&&(val=Buffer.from(val,encoding)),Buffer.isBuffer(val))return 0===val.length?-1:arrayIndexOf(buffer,val,byteOffset,encoding,dir);if("number"==typeof val)return val&=255,Buffer.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?dir?Uint8Array.prototype.indexOf.call(buffer,val,byteOffset):Uint8Array.prototype.lastIndexOf.call(buffer,val,byteOffset):arrayIndexOf(buffer,[val],byteOffset,encoding,dir);throw new TypeError("val must be string, number or Buffer")}function arrayIndexOf(arr,val,byteOffset,encoding,dir){var i,indexSize=1,arrLength=arr.length,valLength=val.length;if(void 0!==encoding&&("ucs2"===(encoding=String(encoding).toLowerCase())||"ucs-2"===encoding||"utf16le"===encoding||"utf-16le"===encoding)){if(arr.length<2||val.length<2)return-1;indexSize=2,arrLength/=2,valLength/=2,byteOffset/=2}function read(buf,i){return 1===indexSize?buf[i]:buf.readUInt16BE(i*indexSize)}if(dir){var foundIndex=-1;for(i=byteOffset;i<arrLength;i++)if(read(arr,i)===read(val,-1===foundIndex?0:i-foundIndex)){if(-1===foundIndex&&(foundIndex=i),i-foundIndex+1===valLength)return foundIndex*indexSize}else-1!==foundIndex&&(i-=i-foundIndex),foundIndex=-1}else for(byteOffset+valLength>arrLength&&(byteOffset=arrLength-valLength),i=byteOffset;i>=0;i--){for(var found=!0,j=0;j<valLength;j++)if(read(arr,i+j)!==read(val,j)){found=!1;break}if(found)return i}return-1}function hexWrite(buf,string,offset,length){offset=Number(offset)||0;var remaining=buf.length-offset;length?(length=Number(length))>remaining&&(length=remaining):length=remaining;var strLen=string.length;if(strLen%2!=0)throw new TypeError("Invalid hex string");length>strLen/2&&(length=strLen/2);for(var i=0;i<length;++i){var parsed=parseInt(string.substr(2*i,2),16);if(isNaN(parsed))return i;buf[offset+i]=parsed}return i}function utf8Write(buf,string,offset,length){return blitBuffer(utf8ToBytes(string,buf.length-offset),buf,offset,length)}function asciiWrite(buf,string,offset,length){return blitBuffer(asciiToBytes(string),buf,offset,length)}function latin1Write(buf,string,offset,length){return asciiWrite(buf,string,offset,length)}function base64Write(buf,string,offset,length){return blitBuffer(base64ToBytes(string),buf,offset,length)}function ucs2Write(buf,string,offset,length){return blitBuffer(utf16leToBytes(string,buf.length-offset),buf,offset,length)}function base64Slice(buf,start,end){return 0===start&&end===buf.length?base64.fromByteArray(buf):base64.fromByteArray(buf.slice(start,end))}function utf8Slice(buf,start,end){end=Math.min(buf.length,end);for(var res=[],i=start;i<end;){var secondByte,thirdByte,fourthByte,tempCodePoint,firstByte=buf[i],codePoint=null,bytesPerSequence=firstByte>239?4:firstByte>223?3:firstByte>191?2:1;if(i+bytesPerSequence<=end)switch(bytesPerSequence){case 1:firstByte<128&&(codePoint=firstByte);break;case 2:128==(192&(secondByte=buf[i+1]))&&(tempCodePoint=(31&firstByte)<<6|63&secondByte)>127&&(codePoint=tempCodePoint);break;case 3:secondByte=buf[i+1],thirdByte=buf[i+2],128==(192&secondByte)&&128==(192&thirdByte)&&(tempCodePoint=(15&firstByte)<<12|(63&secondByte)<<6|63&thirdByte)>2047&&(tempCodePoint<55296||tempCodePoint>57343)&&(codePoint=tempCodePoint);break;case 4:secondByte=buf[i+1],thirdByte=buf[i+2],fourthByte=buf[i+3],128==(192&secondByte)&&128==(192&thirdByte)&&128==(192&fourthByte)&&(tempCodePoint=(15&firstByte)<<18|(63&secondByte)<<12|(63&thirdByte)<<6|63&fourthByte)>65535&&tempCodePoint<1114112&&(codePoint=tempCodePoint)}null===codePoint?(codePoint=65533,bytesPerSequence=1):codePoint>65535&&(codePoint-=65536,res.push(codePoint>>>10&1023|55296),codePoint=56320|1023&codePoint),res.push(codePoint),i+=bytesPerSequence}return decodeCodePointsArray(res)}exports.Buffer=Buffer,exports.SlowBuffer=SlowBuffer,exports.INSPECT_MAX_BYTES=50,Buffer.TYPED_ARRAY_SUPPORT=void 0!==global.TYPED_ARRAY_SUPPORT?global.TYPED_ARRAY_SUPPORT:typedArraySupport(),exports.kMaxLength=kMaxLength(),Buffer.poolSize=8192,Buffer._augment=function(arr){return arr.__proto__=Buffer.prototype,arr},Buffer.from=function(value,encodingOrOffset,length){return from(null,value,encodingOrOffset,length)},Buffer.TYPED_ARRAY_SUPPORT&&(Buffer.prototype.__proto__=Uint8Array.prototype,Buffer.__proto__=Uint8Array,"undefined"!=typeof Symbol&&Symbol.species&&Buffer[Symbol.species]===Buffer&&Object.defineProperty(Buffer,Symbol.species,{value:null,configurable:!0})),Buffer.alloc=function(size,fill,encoding){return alloc(null,size,fill,encoding)},Buffer.allocUnsafe=function(size){return allocUnsafe(null,size)},Buffer.allocUnsafeSlow=function(size){return allocUnsafe(null,size)},Buffer.isBuffer=function isBuffer(b){return!(null==b||!b._isBuffer)},Buffer.compare=function compare(a,b){if(!Buffer.isBuffer(a)||!Buffer.isBuffer(b))throw new TypeError("Arguments must be Buffers");if(a===b)return 0;for(var x=a.length,y=b.length,i=0,len=Math.min(x,y);i<len;++i)if(a[i]!==b[i]){x=a[i],y=b[i];break}return x<y?-1:y<x?1:0},Buffer.isEncoding=function isEncoding(encoding){switch(String(encoding).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}},Buffer.concat=function concat(list,length){if(!isArray(list))throw new TypeError('"list" argument must be an Array of Buffers');if(0===list.length)return Buffer.alloc(0);var i;if(void 0===length)for(length=0,i=0;i<list.length;++i)length+=list[i].length;var buffer=Buffer.allocUnsafe(length),pos=0;for(i=0;i<list.length;++i){var buf=list[i];if(!Buffer.isBuffer(buf))throw new TypeError('"list" argument must be an Array of Buffers');buf.copy(buffer,pos),pos+=buf.length}return buffer},Buffer.byteLength=byteLength,Buffer.prototype._isBuffer=!0,Buffer.prototype.swap16=function swap16(){var len=this.length;if(len%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(var i=0;i<len;i+=2)swap(this,i,i+1);return this},Buffer.prototype.swap32=function swap32(){var len=this.length;if(len%4!=0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(var i=0;i<len;i+=4)swap(this,i,i+3),swap(this,i+1,i+2);return this},Buffer.prototype.swap64=function swap64(){var len=this.length;if(len%8!=0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(var i=0;i<len;i+=8)swap(this,i,i+7),swap(this,i+1,i+6),swap(this,i+2,i+5),swap(this,i+3,i+4);return this},Buffer.prototype.toString=function toString(){var length=0|this.length;return 0===length?"":0===arguments.length?utf8Slice(this,0,length):slowToString.apply(this,arguments)},Buffer.prototype.equals=function equals(b){if(!Buffer.isBuffer(b))throw new TypeError("Argument must be a Buffer");return this===b||0===Buffer.compare(this,b)},Buffer.prototype.inspect=function inspect(){var str="",max=exports.INSPECT_MAX_BYTES;return this.length>0&&(str=this.toString("hex",0,max).match(/.{2}/g).join(" "),this.length>max&&(str+=" ... ")),"<Buffer "+str+">"},Buffer.prototype.compare=function compare(target,start,end,thisStart,thisEnd){if(!Buffer.isBuffer(target))throw new TypeError("Argument must be a Buffer");if(void 0===start&&(start=0),void 0===end&&(end=target?target.length:0),void 0===thisStart&&(thisStart=0),void 0===thisEnd&&(thisEnd=this.length),start<0||end>target.length||thisStart<0||thisEnd>this.length)throw new RangeError("out of range index");if(thisStart>=thisEnd&&start>=end)return 0;if(thisStart>=thisEnd)return-1;if(start>=end)return 1;if(this===target)return 0;for(var x=(thisEnd>>>=0)-(thisStart>>>=0),y=(end>>>=0)-(start>>>=0),len=Math.min(x,y),thisCopy=this.slice(thisStart,thisEnd),targetCopy=target.slice(start,end),i=0;i<len;++i)if(thisCopy[i]!==targetCopy[i]){x=thisCopy[i],y=targetCopy[i];break}return x<y?-1:y<x?1:0},Buffer.prototype.includes=function includes(val,byteOffset,encoding){return-1!==this.indexOf(val,byteOffset,encoding)},Buffer.prototype.indexOf=function indexOf(val,byteOffset,encoding){return bidirectionalIndexOf(this,val,byteOffset,encoding,!0)},Buffer.prototype.lastIndexOf=function lastIndexOf(val,byteOffset,encoding){return bidirectionalIndexOf(this,val,byteOffset,encoding,!1)},Buffer.prototype.write=function write(string,offset,length,encoding){if(void 0===offset)encoding="utf8",length=this.length,offset=0;else if(void 0===length&&"string"==typeof offset)encoding=offset,length=this.length,offset=0;else{if(!isFinite(offset))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");offset|=0,isFinite(length)?(length|=0,void 0===encoding&&(encoding="utf8")):(encoding=length,length=void 0)}var remaining=this.length-offset;if((void 0===length||length>remaining)&&(length=remaining),string.length>0&&(length<0||offset<0)||offset>this.length)throw new RangeError("Attempt to write outside buffer bounds");encoding||(encoding="utf8");for(var loweredCase=!1;;)switch(encoding){case"hex":return hexWrite(this,string,offset,length);case"utf8":case"utf-8":return utf8Write(this,string,offset,length);case"ascii":return asciiWrite(this,string,offset,length);case"latin1":case"binary":return latin1Write(this,string,offset,length);case"base64":return base64Write(this,string,offset,length);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return ucs2Write(this,string,offset,length);default:if(loweredCase)throw new TypeError("Unknown encoding: "+encoding);encoding=(""+encoding).toLowerCase(),loweredCase=!0}},Buffer.prototype.toJSON=function toJSON(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var MAX_ARGUMENTS_LENGTH=4096;function decodeCodePointsArray(codePoints){var len=codePoints.length;if(len<=MAX_ARGUMENTS_LENGTH)return String.fromCharCode.apply(String,codePoints);for(var res="",i=0;i<len;)res+=String.fromCharCode.apply(String,codePoints.slice(i,i+=MAX_ARGUMENTS_LENGTH));return res}function asciiSlice(buf,start,end){var ret="";end=Math.min(buf.length,end);for(var i=start;i<end;++i)ret+=String.fromCharCode(127&buf[i]);return ret}function latin1Slice(buf,start,end){var ret="";end=Math.min(buf.length,end);for(var i=start;i<end;++i)ret+=String.fromCharCode(buf[i]);return ret}function hexSlice(buf,start,end){var len=buf.length;(!start||start<0)&&(start=0),(!end||end<0||end>len)&&(end=len);for(var out="",i=start;i<end;++i)out+=toHex(buf[i]);return out}function utf16leSlice(buf,start,end){for(var bytes=buf.slice(start,end),res="",i=0;i<bytes.length;i+=2)res+=String.fromCharCode(bytes[i]+256*bytes[i+1]);return res}function checkOffset(offset,ext,length){if(offset%1!=0||offset<0)throw new RangeError("offset is not uint");if(offset+ext>length)throw new RangeError("Trying to access beyond buffer length")}function checkInt(buf,value,offset,ext,max,min){if(!Buffer.isBuffer(buf))throw new TypeError('"buffer" argument must be a Buffer instance');if(value>max||value<min)throw new RangeError('"value" argument is out of bounds');if(offset+ext>buf.length)throw new RangeError("Index out of range")}function objectWriteUInt16(buf,value,offset,littleEndian){value<0&&(value=65535+value+1);for(var i=0,j=Math.min(buf.length-offset,2);i<j;++i)buf[offset+i]=(value&255<<8*(littleEndian?i:1-i))>>>8*(littleEndian?i:1-i)}function objectWriteUInt32(buf,value,offset,littleEndian){value<0&&(value=4294967295+value+1);for(var i=0,j=Math.min(buf.length-offset,4);i<j;++i)buf[offset+i]=value>>>8*(littleEndian?i:3-i)&255}function checkIEEE754(buf,value,offset,ext,max,min){if(offset+ext>buf.length)throw new RangeError("Index out of range");if(offset<0)throw new RangeError("Index out of range")}function writeFloat(buf,value,offset,littleEndian,noAssert){return noAssert||checkIEEE754(buf,value,offset,4,34028234663852886e22,-34028234663852886e22),ieee754.write(buf,value,offset,littleEndian,23,4),offset+4}function writeDouble(buf,value,offset,littleEndian,noAssert){return noAssert||checkIEEE754(buf,value,offset,8,17976931348623157e292,-17976931348623157e292),ieee754.write(buf,value,offset,littleEndian,52,8),offset+8}Buffer.prototype.slice=function slice(start,end){var newBuf,len=this.length;if((start=~~start)<0?(start+=len)<0&&(start=0):start>len&&(start=len),(end=void 0===end?len:~~end)<0?(end+=len)<0&&(end=0):end>len&&(end=len),end<start&&(end=start),Buffer.TYPED_ARRAY_SUPPORT)(newBuf=this.subarray(start,end)).__proto__=Buffer.prototype;else{var sliceLen=end-start;newBuf=new Buffer(sliceLen,void 0);for(var i=0;i<sliceLen;++i)newBuf[i]=this[i+start]}return newBuf},Buffer.prototype.readUIntLE=function readUIntLE(offset,byteLength,noAssert){offset|=0,byteLength|=0,noAssert||checkOffset(offset,byteLength,this.length);for(var val=this[offset],mul=1,i=0;++i<byteLength&&(mul*=256);)val+=this[offset+i]*mul;return val},Buffer.prototype.readUIntBE=function readUIntBE(offset,byteLength,noAssert){offset|=0,byteLength|=0,noAssert||checkOffset(offset,byteLength,this.length);for(var val=this[offset+--byteLength],mul=1;byteLength>0&&(mul*=256);)val+=this[offset+--byteLength]*mul;return val},Buffer.prototype.readUInt8=function readUInt8(offset,noAssert){return noAssert||checkOffset(offset,1,this.length),this[offset]},Buffer.prototype.readUInt16LE=function readUInt16LE(offset,noAssert){return noAssert||checkOffset(offset,2,this.length),this[offset]|this[offset+1]<<8},Buffer.prototype.readUInt16BE=function readUInt16BE(offset,noAssert){return noAssert||checkOffset(offset,2,this.length),this[offset]<<8|this[offset+1]},Buffer.prototype.readUInt32LE=function readUInt32LE(offset,noAssert){return noAssert||checkOffset(offset,4,this.length),(this[offset]|this[offset+1]<<8|this[offset+2]<<16)+16777216*this[offset+3]},Buffer.prototype.readUInt32BE=function readUInt32BE(offset,noAssert){return noAssert||checkOffset(offset,4,this.length),16777216*this[offset]+(this[offset+1]<<16|this[offset+2]<<8|this[offset+3])},Buffer.prototype.readIntLE=function readIntLE(offset,byteLength,noAssert){offset|=0,byteLength|=0,noAssert||checkOffset(offset,byteLength,this.length);for(var val=this[offset],mul=1,i=0;++i<byteLength&&(mul*=256);)val+=this[offset+i]*mul;return val>=(mul*=128)&&(val-=Math.pow(2,8*byteLength)),val},Buffer.prototype.readIntBE=function readIntBE(offset,byteLength,noAssert){offset|=0,byteLength|=0,noAssert||checkOffset(offset,byteLength,this.length);for(var i=byteLength,mul=1,val=this[offset+--i];i>0&&(mul*=256);)val+=this[offset+--i]*mul;return val>=(mul*=128)&&(val-=Math.pow(2,8*byteLength)),val},Buffer.prototype.readInt8=function readInt8(offset,noAssert){return noAssert||checkOffset(offset,1,this.length),128&this[offset]?-1*(255-this[offset]+1):this[offset]},Buffer.prototype.readInt16LE=function readInt16LE(offset,noAssert){noAssert||checkOffset(offset,2,this.length);var val=this[offset]|this[offset+1]<<8;return 32768&val?4294901760|val:val},Buffer.prototype.readInt16BE=function readInt16BE(offset,noAssert){noAssert||checkOffset(offset,2,this.length);var val=this[offset+1]|this[offset]<<8;return 32768&val?4294901760|val:val},Buffer.prototype.readInt32LE=function readInt32LE(offset,noAssert){return noAssert||checkOffset(offset,4,this.length),this[offset]|this[offset+1]<<8|this[offset+2]<<16|this[offset+3]<<24},Buffer.prototype.readInt32BE=function readInt32BE(offset,noAssert){return noAssert||checkOffset(offset,4,this.length),this[offset]<<24|this[offset+1]<<16|this[offset+2]<<8|this[offset+3]},Buffer.prototype.readFloatLE=function readFloatLE(offset,noAssert){return noAssert||checkOffset(offset,4,this.length),ieee754.read(this,offset,!0,23,4)},Buffer.prototype.readFloatBE=function readFloatBE(offset,noAssert){return noAssert||checkOffset(offset,4,this.length),ieee754.read(this,offset,!1,23,4)},Buffer.prototype.readDoubleLE=function readDoubleLE(offset,noAssert){return noAssert||checkOffset(offset,8,this.length),ieee754.read(this,offset,!0,52,8)},Buffer.prototype.readDoubleBE=function readDoubleBE(offset,noAssert){return noAssert||checkOffset(offset,8,this.length),ieee754.read(this,offset,!1,52,8)},Buffer.prototype.writeUIntLE=function writeUIntLE(value,offset,byteLength,noAssert){value=+value,offset|=0,byteLength|=0,noAssert||checkInt(this,value,offset,byteLength,Math.pow(2,8*byteLength)-1,0);var mul=1,i=0;for(this[offset]=255&value;++i<byteLength&&(mul*=256);)this[offset+i]=value/mul&255;return offset+byteLength},Buffer.prototype.writeUIntBE=function writeUIntBE(value,offset,byteLength,noAssert){value=+value,offset|=0,byteLength|=0,noAssert||checkInt(this,value,offset,byteLength,Math.pow(2,8*byteLength)-1,0);var i=byteLength-1,mul=1;for(this[offset+i]=255&value;--i>=0&&(mul*=256);)this[offset+i]=value/mul&255;return offset+byteLength},Buffer.prototype.writeUInt8=function writeUInt8(value,offset,noAssert){return value=+value,offset|=0,noAssert||checkInt(this,value,offset,1,255,0),Buffer.TYPED_ARRAY_SUPPORT||(value=Math.floor(value)),this[offset]=255&value,offset+1},Buffer.prototype.writeUInt16LE=function writeUInt16LE(value,offset,noAssert){return value=+value,offset|=0,noAssert||checkInt(this,value,offset,2,65535,0),Buffer.TYPED_ARRAY_SUPPORT?(this[offset]=255&value,this[offset+1]=value>>>8):objectWriteUInt16(this,value,offset,!0),offset+2},Buffer.prototype.writeUInt16BE=function writeUInt16BE(value,offset,noAssert){return value=+value,offset|=0,noAssert||checkInt(this,value,offset,2,65535,0),Buffer.TYPED_ARRAY_SUPPORT?(this[offset]=value>>>8,this[offset+1]=255&value):objectWriteUInt16(this,value,offset,!1),offset+2},Buffer.prototype.writeUInt32LE=function writeUInt32LE(value,offset,noAssert){return value=+value,offset|=0,noAssert||checkInt(this,value,offset,4,4294967295,0),Buffer.TYPED_ARRAY_SUPPORT?(this[offset+3]=value>>>24,this[offset+2]=value>>>16,this[offset+1]=value>>>8,this[offset]=255&value):objectWriteUInt32(this,value,offset,!0),offset+4},Buffer.prototype.writeUInt32BE=function writeUInt32BE(value,offset,noAssert){return value=+value,offset|=0,noAssert||checkInt(this,value,offset,4,4294967295,0),Buffer.TYPED_ARRAY_SUPPORT?(this[offset]=value>>>24,this[offset+1]=value>>>16,this[offset+2]=value>>>8,this[offset+3]=255&value):objectWriteUInt32(this,value,offset,!1),offset+4},Buffer.prototype.writeIntLE=function writeIntLE(value,offset,byteLength,noAssert){if(value=+value,offset|=0,!noAssert){var limit=Math.pow(2,8*byteLength-1);checkInt(this,value,offset,byteLength,limit-1,-limit)}var i=0,mul=1,sub=0;for(this[offset]=255&value;++i<byteLength&&(mul*=256);)value<0&&0===sub&&0!==this[offset+i-1]&&(sub=1),this[offset+i]=(value/mul|0)-sub&255;return offset+byteLength},Buffer.prototype.writeIntBE=function writeIntBE(value,offset,byteLength,noAssert){if(value=+value,offset|=0,!noAssert){var limit=Math.pow(2,8*byteLength-1);checkInt(this,value,offset,byteLength,limit-1,-limit)}var i=byteLength-1,mul=1,sub=0;for(this[offset+i]=255&value;--i>=0&&(mul*=256);)value<0&&0===sub&&0!==this[offset+i+1]&&(sub=1),this[offset+i]=(value/mul|0)-sub&255;return offset+byteLength},Buffer.prototype.writeInt8=function writeInt8(value,offset,noAssert){return value=+value,offset|=0,noAssert||checkInt(this,value,offset,1,127,-128),Buffer.TYPED_ARRAY_SUPPORT||(value=Math.floor(value)),value<0&&(value=255+value+1),this[offset]=255&value,offset+1},Buffer.prototype.writeInt16LE=function writeInt16LE(value,offset,noAssert){return value=+value,offset|=0,noAssert||checkInt(this,value,offset,2,32767,-32768),Buffer.TYPED_ARRAY_SUPPORT?(this[offset]=255&value,this[offset+1]=value>>>8):objectWriteUInt16(this,value,offset,!0),offset+2},Buffer.prototype.writeInt16BE=function writeInt16BE(value,offset,noAssert){return value=+value,offset|=0,noAssert||checkInt(this,value,offset,2,32767,-32768),Buffer.TYPED_ARRAY_SUPPORT?(this[offset]=value>>>8,this[offset+1]=255&value):objectWriteUInt16(this,value,offset,!1),offset+2},Buffer.prototype.writeInt32LE=function writeInt32LE(value,offset,noAssert){return value=+value,offset|=0,noAssert||checkInt(this,value,offset,4,2147483647,-2147483648),Buffer.TYPED_ARRAY_SUPPORT?(this[offset]=255&value,this[offset+1]=value>>>8,this[offset+2]=value>>>16,this[offset+3]=value>>>24):objectWriteUInt32(this,value,offset,!0),offset+4},Buffer.prototype.writeInt32BE=function writeInt32BE(value,offset,noAssert){return value=+value,offset|=0,noAssert||checkInt(this,value,offset,4,2147483647,-2147483648),value<0&&(value=4294967295+value+1),Buffer.TYPED_ARRAY_SUPPORT?(this[offset]=value>>>24,this[offset+1]=value>>>16,this[offset+2]=value>>>8,this[offset+3]=255&value):objectWriteUInt32(this,value,offset,!1),offset+4},Buffer.prototype.writeFloatLE=function writeFloatLE(value,offset,noAssert){return writeFloat(this,value,offset,!0,noAssert)},Buffer.prototype.writeFloatBE=function writeFloatBE(value,offset,noAssert){return writeFloat(this,value,offset,!1,noAssert)},Buffer.prototype.writeDoubleLE=function writeDoubleLE(value,offset,noAssert){return writeDouble(this,value,offset,!0,noAssert)},Buffer.prototype.writeDoubleBE=function writeDoubleBE(value,offset,noAssert){return writeDouble(this,value,offset,!1,noAssert)},Buffer.prototype.copy=function copy(target,targetStart,start,end){if(start||(start=0),end||0===end||(end=this.length),targetStart>=target.length&&(targetStart=target.length),targetStart||(targetStart=0),end>0&&end<start&&(end=start),end===start)return 0;if(0===target.length||0===this.length)return 0;if(targetStart<0)throw new RangeError("targetStart out of bounds");if(start<0||start>=this.length)throw new RangeError("sourceStart out of bounds");if(end<0)throw new RangeError("sourceEnd out of bounds");end>this.length&&(end=this.length),target.length-targetStart<end-start&&(end=target.length-targetStart+start);var i,len=end-start;if(this===target&&start<targetStart&&targetStart<end)for(i=len-1;i>=0;--i)target[i+targetStart]=this[i+start];else if(len<1e3||!Buffer.TYPED_ARRAY_SUPPORT)for(i=0;i<len;++i)target[i+targetStart]=this[i+start];else Uint8Array.prototype.set.call(target,this.subarray(start,start+len),targetStart);return len},Buffer.prototype.fill=function fill(val,start,end,encoding){if("string"==typeof val){if("string"==typeof start?(encoding=start,start=0,end=this.length):"string"==typeof end&&(encoding=end,end=this.length),1===val.length){var code=val.charCodeAt(0);code<256&&(val=code)}if(void 0!==encoding&&"string"!=typeof encoding)throw new TypeError("encoding must be a string");if("string"==typeof encoding&&!Buffer.isEncoding(encoding))throw new TypeError("Unknown encoding: "+encoding)}else"number"==typeof val&&(val&=255);if(start<0||this.length<start||this.length<end)throw new RangeError("Out of range index");if(end<=start)return this;var i;if(start>>>=0,end=void 0===end?this.length:end>>>0,val||(val=0),"number"==typeof val)for(i=start;i<end;++i)this[i]=val;else{var bytes=Buffer.isBuffer(val)?val:utf8ToBytes(new Buffer(val,encoding).toString()),len=bytes.length;for(i=0;i<end-start;++i)this[i+start]=bytes[i%len]}return this};var INVALID_BASE64_RE=/[^+\/0-9A-Za-z-_]/g;function base64clean(str){if((str=stringtrim(str).replace(INVALID_BASE64_RE,"")).length<2)return"";for(;str.length%4!=0;)str+="=";return str}function stringtrim(str){return str.trim?str.trim():str.replace(/^\s+|\s+$/g,"")}function toHex(n){return n<16?"0"+n.toString(16):n.toString(16)}function utf8ToBytes(string,units){var codePoint;units=units||1/0;for(var length=string.length,leadSurrogate=null,bytes=[],i=0;i<length;++i){if((codePoint=string.charCodeAt(i))>55295&&codePoint<57344){if(!leadSurrogate){if(codePoint>56319){(units-=3)>-1&&bytes.push(239,191,189);continue}if(i+1===length){(units-=3)>-1&&bytes.push(239,191,189);continue}leadSurrogate=codePoint;continue}if(codePoint<56320){(units-=3)>-1&&bytes.push(239,191,189),leadSurrogate=codePoint;continue}codePoint=65536+(leadSurrogate-55296<<10|codePoint-56320)}else leadSurrogate&&(units-=3)>-1&&bytes.push(239,191,189);if(leadSurrogate=null,codePoint<128){if((units-=1)<0)break;bytes.push(codePoint)}else if(codePoint<2048){if((units-=2)<0)break;bytes.push(codePoint>>6|192,63&codePoint|128)}else if(codePoint<65536){if((units-=3)<0)break;bytes.push(codePoint>>12|224,codePoint>>6&63|128,63&codePoint|128)}else{if(!(codePoint<1114112))throw new Error("Invalid code point");if((units-=4)<0)break;bytes.push(codePoint>>18|240,codePoint>>12&63|128,codePoint>>6&63|128,63&codePoint|128)}}return bytes}function asciiToBytes(str){for(var byteArray=[],i=0;i<str.length;++i)byteArray.push(255&str.charCodeAt(i));return byteArray}function utf16leToBytes(str,units){for(var c,hi,lo,byteArray=[],i=0;i<str.length&&!((units-=2)<0);++i)hi=(c=str.charCodeAt(i))>>8,lo=c%256,byteArray.push(lo),byteArray.push(hi);return byteArray}function base64ToBytes(str){return base64.toByteArray(base64clean(str))}function blitBuffer(src,dst,offset,length){for(var i=0;i<length&&!(i+offset>=dst.length||i>=src.length);++i)dst[i+offset]=src[i];return i}function isnan(val){return val!=val}}).call(this)}).call(this,void 0!==__webpack_require__.g?__webpack_require__.g:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},require("buffer").Buffer)},{"base64-js":23,buffer:27,ieee754:40,isarray:42}],28:[function(require,module,exports){function isArray(arg){return Array.isArray?Array.isArray(arg):"[object Array]"===objectToString(arg)}function isBoolean(arg){return"boolean"==typeof arg}function isNull(arg){return null===arg}function isNullOrUndefined(arg){return null==arg}function isNumber(arg){return"number"==typeof arg}function isString(arg){return"string"==typeof arg}function isSymbol(arg){return"symbol"==typeof arg}function isUndefined(arg){return void 0===arg}function isRegExp(re){return"[object RegExp]"===objectToString(re)}function isObject(arg){return"object"==typeof arg&&null!==arg}function isDate(d){return"[object Date]"===objectToString(d)}function isError(e){return"[object Error]"===objectToString(e)||e instanceof Error}function isFunction(arg){return"function"==typeof arg}function isPrimitive(arg){return null===arg||"boolean"==typeof arg||"number"==typeof arg||"string"==typeof arg||"symbol"==typeof arg||void 0===arg}function objectToString(o){return Object.prototype.toString.call(o)}exports.isArray=isArray,exports.isBoolean=isBoolean,exports.isNull=isNull,exports.isNullOrUndefined=isNullOrUndefined,exports.isNumber=isNumber,exports.isString=isString,exports.isSymbol=isSymbol,exports.isUndefined=isUndefined,exports.isRegExp=isRegExp,exports.isObject=isObject,exports.isDate=isDate,exports.isError=isError,exports.isFunction=isFunction,exports.isPrimitive=isPrimitive,exports.isBuffer=require("buffer").Buffer.isBuffer},{buffer:27}],29:[function(require,module,exports){(function(global){(function(){var root,factory;root=this,factory=function(){var CryptoJS=CryptoJS||function(Math,undefined){var crypto;if("undefined"!=typeof window&&window.crypto&&(crypto=window.crypto),"undefined"!=typeof self&&self.crypto&&(crypto=self.crypto),"undefined"!=typeof globalThis&&globalThis.crypto&&(crypto=globalThis.crypto),!crypto&&"undefined"!=typeof window&&window.msCrypto&&(crypto=window.msCrypto),!crypto&&void 0!==global&&global.crypto&&(crypto=global.crypto),!crypto&&"function"==typeof require)try{crypto=require("crypto")}catch(err){}var cryptoSecureRandomInt=function(){if(crypto){if("function"==typeof crypto.getRandomValues)try{return crypto.getRandomValues(new Uint32Array(1))[0]}catch(err){}if("function"==typeof crypto.randomBytes)try{return crypto.randomBytes(4).readInt32LE()}catch(err){}}throw new Error("Native crypto module could not be used to get secure random number.")},create=Object.create||function(){function F(){}return function(obj){var subtype;return F.prototype=obj,subtype=new F,F.prototype=null,subtype}}(),C={},C_lib=C.lib={},Base=C_lib.Base={extend:function(overrides){var subtype=create(this);return overrides&&subtype.mixIn(overrides),subtype.hasOwnProperty("init")&&this.init!==subtype.init||(subtype.init=function(){subtype.$super.init.apply(this,arguments)}),subtype.init.prototype=subtype,subtype.$super=this,subtype},create:function(){var instance=this.extend();return instance.init.apply(instance,arguments),instance},init:function(){},mixIn:function(properties){for(var propertyName in properties)properties.hasOwnProperty(propertyName)&&(this[propertyName]=properties[propertyName]);properties.hasOwnProperty("toString")&&(this.toString=properties.toString)},clone:function(){return this.init.prototype.extend(this)}},WordArray=C_lib.WordArray=Base.extend({init:function(words,sigBytes){words=this.words=words||[],this.sigBytes=sigBytes!=undefined?sigBytes:4*words.length},toString:function(encoder){return(encoder||Hex).stringify(this)},concat:function(wordArray){var thisWords=this.words,thatWords=wordArray.words,thisSigBytes=this.sigBytes,thatSigBytes=wordArray.sigBytes;if(this.clamp(),thisSigBytes%4)for(var i=0;i<thatSigBytes;i++){var thatByte=thatWords[i>>>2]>>>24-i%4*8&255;thisWords[thisSigBytes+i>>>2]|=thatByte<<24-(thisSigBytes+i)%4*8}else for(var j=0;j<thatSigBytes;j+=4)thisWords[thisSigBytes+j>>>2]=thatWords[j>>>2];return this.sigBytes+=thatSigBytes,this},clamp:function(){var words=this.words,sigBytes=this.sigBytes;words[sigBytes>>>2]&=4294967295<<32-sigBytes%4*8,words.length=Math.ceil(sigBytes/4)},clone:function(){var clone=Base.clone.call(this);return clone.words=this.words.slice(0),clone},random:function(nBytes){for(var words=[],i=0;i<nBytes;i+=4)words.push(cryptoSecureRandomInt());return new WordArray.init(words,nBytes)}}),C_enc=C.enc={},Hex=C_enc.Hex={stringify:function(wordArray){for(var words=wordArray.words,sigBytes=wordArray.sigBytes,hexChars=[],i=0;i<sigBytes;i++){var bite=words[i>>>2]>>>24-i%4*8&255;hexChars.push((bite>>>4).toString(16)),hexChars.push((15&bite).toString(16))}return hexChars.join("")},parse:function(hexStr){for(var hexStrLength=hexStr.length,words=[],i=0;i<hexStrLength;i+=2)words[i>>>3]|=parseInt(hexStr.substr(i,2),16)<<24-i%8*4;return new WordArray.init(words,hexStrLength/2)}},Latin1=C_enc.Latin1={stringify:function(wordArray){for(var words=wordArray.words,sigBytes=wordArray.sigBytes,latin1Chars=[],i=0;i<sigBytes;i++){var bite=words[i>>>2]>>>24-i%4*8&255;latin1Chars.push(String.fromCharCode(bite))}return latin1Chars.join("")},parse:function(latin1Str){for(var latin1StrLength=latin1Str.length,words=[],i=0;i<latin1StrLength;i++)words[i>>>2]|=(255&latin1Str.charCodeAt(i))<<24-i%4*8;return new WordArray.init(words,latin1StrLength)}},Utf8=C_enc.Utf8={stringify:function(wordArray){try{return decodeURIComponent(escape(Latin1.stringify(wordArray)))}catch(e){throw new Error("Malformed UTF-8 data")}},parse:function(utf8Str){return Latin1.parse(unescape(encodeURIComponent(utf8Str)))}},BufferedBlockAlgorithm=C_lib.BufferedBlockAlgorithm=Base.extend({reset:function(){this._data=new WordArray.init,this._nDataBytes=0},_append:function(data){"string"==typeof data&&(data=Utf8.parse(data)),this._data.concat(data),this._nDataBytes+=data.sigBytes},_process:function(doFlush){var processedWords,data=this._data,dataWords=data.words,dataSigBytes=data.sigBytes,blockSize=this.blockSize,nBlocksReady=dataSigBytes/(4*blockSize),nWordsReady=(nBlocksReady=doFlush?Math.ceil(nBlocksReady):Math.max((0|nBlocksReady)-this._minBufferSize,0))*blockSize,nBytesReady=Math.min(4*nWordsReady,dataSigBytes);if(nWordsReady){for(var offset=0;offset<nWordsReady;offset+=blockSize)this._doProcessBlock(dataWords,offset);processedWords=dataWords.splice(0,nWordsReady),data.sigBytes-=nBytesReady}return new WordArray.init(processedWords,nBytesReady)},clone:function(){var clone=Base.clone.call(this);return clone._data=this._data.clone(),clone},_minBufferSize:0}),C_algo=(C_lib.Hasher=BufferedBlockAlgorithm.extend({cfg:Base.extend(),init:function(cfg){this.cfg=this.cfg.extend(cfg),this.reset()},reset:function(){BufferedBlockAlgorithm.reset.call(this),this._doReset()},update:function(messageUpdate){return this._append(messageUpdate),this._process(),this},finalize:function(messageUpdate){return messageUpdate&&this._append(messageUpdate),this._doFinalize()},blockSize:16,_createHelper:function(hasher){return function(message,cfg){return new hasher.init(cfg).finalize(message)}},_createHmacHelper:function(hasher){return function(message,key){return new C_algo.HMAC.init(hasher,key).finalize(message)}}}),C.algo={});return C}(Math);return CryptoJS},"object"==typeof exports?module.exports=exports=factory():"function"==typeof define&&define.amd?define([],factory):root.CryptoJS=factory()}).call(this)}).call(this,void 0!==__webpack_require__.g?__webpack_require__.g:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{crypto:25}],30:[function(require,module,exports){var root,factory;root=this,factory=function(CryptoJS){return CryptoJS.HmacSHA1},"object"==typeof exports?module.exports=exports=factory(require("./core"),require("./sha1"),require("./hmac")):"function"==typeof define&&define.amd?define(["./core","./sha1","./hmac"],factory):factory(root.CryptoJS)},{"./core":29,"./hmac":32,"./sha1":33}],31:[function(require,module,exports){var root,factory;root=this,factory=function(CryptoJS){return CryptoJS.HmacSHA256},"object"==typeof exports?module.exports=exports=factory(require("./core"),require("./sha256"),require("./hmac")):"function"==typeof define&&define.amd?define(["./core","./sha256","./hmac"],factory):factory(root.CryptoJS)},{"./core":29,"./hmac":32,"./sha256":34}],32:[function(require,module,exports){var root,factory;root=this,factory=function(CryptoJS){var C,Base,Utf8;Base=(C=CryptoJS).lib.Base,Utf8=C.enc.Utf8,C.algo.HMAC=Base.extend({init:function(hasher,key){hasher=this._hasher=new hasher.init,"string"==typeof key&&(key=Utf8.parse(key));var hasherBlockSize=hasher.blockSize,hasherBlockSizeBytes=4*hasherBlockSize;key.sigBytes>hasherBlockSizeBytes&&(key=hasher.finalize(key)),key.clamp();for(var oKey=this._oKey=key.clone(),iKey=this._iKey=key.clone(),oKeyWords=oKey.words,iKeyWords=iKey.words,i=0;i<hasherBlockSize;i++)oKeyWords[i]^=1549556828,iKeyWords[i]^=909522486;oKey.sigBytes=iKey.sigBytes=hasherBlockSizeBytes,this.reset()},reset:function(){var hasher=this._hasher;hasher.reset(),hasher.update(this._iKey)},update:function(messageUpdate){return this._hasher.update(messageUpdate),this},finalize:function(messageUpdate){var hasher=this._hasher,innerHash=hasher.finalize(messageUpdate);return hasher.reset(),hasher.finalize(this._oKey.clone().concat(innerHash))}})},"object"==typeof exports?module.exports=exports=factory(require("./core")):"function"==typeof define&&define.amd?define(["./core"],factory):factory(root.CryptoJS)},{"./core":29}],33:[function(require,module,exports){var root,factory;root=this,factory=function(CryptoJS){var C,C_lib,WordArray,Hasher,C_algo,W,SHA1;return C_lib=(C=CryptoJS).lib,WordArray=C_lib.WordArray,Hasher=C_lib.Hasher,C_algo=C.algo,W=[],SHA1=C_algo.SHA1=Hasher.extend({_doReset:function(){this._hash=new WordArray.init([1732584193,4023233417,2562383102,271733878,3285377520])},_doProcessBlock:function(M,offset){for(var H=this._hash.words,a=H[0],b=H[1],c=H[2],d=H[3],e=H[4],i=0;i<80;i++){if(i<16)W[i]=0|M[offset+i];else{var n=W[i-3]^W[i-8]^W[i-14]^W[i-16];W[i]=n<<1|n>>>31}var t=(a<<5|a>>>27)+e+W[i];t+=i<20?1518500249+(b&c|~b&d):i<40?1859775393+(b^c^d):i<60?(b&c|b&d|c&d)-1894007588:(b^c^d)-899497514,e=d,d=c,c=b<<30|b>>>2,b=a,a=t}H[0]=H[0]+a|0,H[1]=H[1]+b|0,H[2]=H[2]+c|0,H[3]=H[3]+d|0,H[4]=H[4]+e|0},_doFinalize:function(){var data=this._data,dataWords=data.words,nBitsTotal=8*this._nDataBytes,nBitsLeft=8*data.sigBytes;return dataWords[nBitsLeft>>>5]|=128<<24-nBitsLeft%32,dataWords[14+(nBitsLeft+64>>>9<<4)]=Math.floor(nBitsTotal/4294967296),dataWords[15+(nBitsLeft+64>>>9<<4)]=nBitsTotal,data.sigBytes=4*dataWords.length,this._process(),this._hash},clone:function(){var clone=Hasher.clone.call(this);return clone._hash=this._hash.clone(),clone}}),C.SHA1=Hasher._createHelper(SHA1),C.HmacSHA1=Hasher._createHmacHelper(SHA1),CryptoJS.SHA1},"object"==typeof exports?module.exports=exports=factory(require("./core")):"function"==typeof define&&define.amd?define(["./core"],factory):factory(root.CryptoJS)},{"./core":29}],34:[function(require,module,exports){var root,factory;root=this,factory=function(CryptoJS){return function(Math){var C=CryptoJS,C_lib=C.lib,WordArray=C_lib.WordArray,Hasher=C_lib.Hasher,C_algo=C.algo,H=[],K=[];!function(){function isPrime(n){for(var sqrtN=Math.sqrt(n),factor=2;factor<=sqrtN;factor++)if(!(n%factor))return!1;return!0}function getFractionalBits(n){return 4294967296*(n-(0|n))|0}for(var n=2,nPrime=0;nPrime<64;)isPrime(n)&&(nPrime<8&&(H[nPrime]=getFractionalBits(Math.pow(n,.5))),K[nPrime]=getFractionalBits(Math.pow(n,1/3)),nPrime++),n++}();var W=[],SHA256=C_algo.SHA256=Hasher.extend({_doReset:function(){this._hash=new WordArray.init(H.slice(0))},_doProcessBlock:function(M,offset){for(var H=this._hash.words,a=H[0],b=H[1],c=H[2],d=H[3],e=H[4],f=H[5],g=H[6],h=H[7],i=0;i<64;i++){if(i<16)W[i]=0|M[offset+i];else{var gamma0x=W[i-15],gamma0=(gamma0x<<25|gamma0x>>>7)^(gamma0x<<14|gamma0x>>>18)^gamma0x>>>3,gamma1x=W[i-2],gamma1=(gamma1x<<15|gamma1x>>>17)^(gamma1x<<13|gamma1x>>>19)^gamma1x>>>10;W[i]=gamma0+W[i-7]+gamma1+W[i-16]}var maj=a&b^a&c^b&c,sigma0=(a<<30|a>>>2)^(a<<19|a>>>13)^(a<<10|a>>>22),t1=h+((e<<26|e>>>6)^(e<<21|e>>>11)^(e<<7|e>>>25))+(e&f^~e&g)+K[i]+W[i];h=g,g=f,f=e,e=d+t1|0,d=c,c=b,b=a,a=t1+(sigma0+maj)|0}H[0]=H[0]+a|0,H[1]=H[1]+b|0,H[2]=H[2]+c|0,H[3]=H[3]+d|0,H[4]=H[4]+e|0,H[5]=H[5]+f|0,H[6]=H[6]+g|0,H[7]=H[7]+h|0},_doFinalize:function(){var data=this._data,dataWords=data.words,nBitsTotal=8*this._nDataBytes,nBitsLeft=8*data.sigBytes;return dataWords[nBitsLeft>>>5]|=128<<24-nBitsLeft%32,dataWords[14+(nBitsLeft+64>>>9<<4)]=Math.floor(nBitsTotal/4294967296),dataWords[15+(nBitsLeft+64>>>9<<4)]=nBitsTotal,data.sigBytes=4*dataWords.length,this._process(),this._hash},clone:function(){var clone=Hasher.clone.call(this);return clone._hash=this._hash.clone(),clone}});C.SHA256=Hasher._createHelper(SHA256),C.HmacSHA256=Hasher._createHmacHelper(SHA256)}(Math),CryptoJS.SHA256},"object"==typeof exports?module.exports=exports=factory(require("./core")):"function"==typeof define&&define.amd?define(["./core"],factory):factory(root.CryptoJS)},{"./core":29}],35:[function(require,module,exports){(function(process){(function(){function useColors(){return!("undefined"==typeof window||!window.process||"renderer"!==window.process.type)||"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 formatArgs(args){var useColors=this.useColors;if(args[0]=(useColors?"%c":"")+this.namespace+(useColors?" %c":" ")+args[0]+(useColors?"%c ":" ")+"+"+exports.humanize(this.diff),useColors){var c="color: "+this.color;args.splice(1,0,c,"color: inherit");var index=0,lastC=0;args[0].replace(/%[a-zA-Z%]/g,function(match){"%%"!==match&&(index++,"%c"===match&&(lastC=index))}),args.splice(lastC,0,c)}}function log(){return"object"==typeof console&&console.log&&Function.prototype.apply.call(console.log,console,arguments)}function save(namespaces){try{null==namespaces?exports.storage.removeItem("debug"):exports.storage.debug=namespaces}catch(e){}}function load(){var r;try{r=exports.storage.debug}catch(e){}return!r&&void 0!==process&&"env"in process&&(r=process.env.DEBUG),r}function localstorage(){try{return window.localStorage}catch(e){}}(exports=module.exports=require("./debug")).log=log,exports.formatArgs=formatArgs,exports.save=save,exports.load=load,exports.useColors=useColors,exports.storage="undefined"!=typeof chrome&&void 0!==chrome.storage?chrome.storage.local:localstorage(),exports.colors=["lightseagreen","forestgreen","goldenrod","dodgerblue","darkorchid","crimson"],exports.formatters.j=function(v){try{return JSON.stringify(v)}catch(err){return"[UnexpectedJSONParseError]: "+err.message}},exports.enable(load())}).call(this)}).call(this,require("_process"))},{"./debug":36,_process:89}],36:[function(require,module,exports){var prevTime;function selectColor(namespace){var i,hash=0;for(i in namespace)hash=(hash<<5)-hash+namespace.charCodeAt(i),hash|=0;return exports.colors[Math.abs(hash)%exports.colors.length]}function createDebug(namespace){function debug(){if(debug.enabled){var self=debug,curr=+new Date,ms=curr-(prevTime||curr);self.diff=ms,self.prev=prevTime,self.curr=curr,prevTime=curr;for(var args=new Array(arguments.length),i=0;i<args.length;i++)args[i]=arguments[i];args[0]=exports.coerce(args[0]),"string"!=typeof args[0]&&args.unshift("%O");var index=0;args[0]=args[0].replace(/%([a-zA-Z%])/g,function(match,format){if("%%"===match)return match;index++;var formatter=exports.formatters[format];if("function"==typeof formatter){var val=args[index];match=formatter.call(self,val),args.splice(index,1),index--}return match}),exports.formatArgs.call(self,args),(debug.log||exports.log||console.log.bind(console)).apply(self,args)}}return debug.namespace=namespace,debug.enabled=exports.enabled(namespace),debug.useColors=exports.useColors(),debug.color=selectColor(namespace),"function"==typeof exports.init&&exports.init(debug),debug}function enable(namespaces){exports.save(namespaces),exports.names=[],exports.skips=[];for(var split=("string"==typeof namespaces?namespaces:"").split(/[\s,]+/),len=split.length,i=0;i<len;i++)split[i]&&("-"===(namespaces=split[i].replace(/\*/g,".*?"))[0]?exports.skips.push(new RegExp("^"+namespaces.substr(1)+"$")):exports.names.push(new RegExp("^"+namespaces+"$")))}function disable(){exports.enable("")}function enabled(name){var i,len;for(i=0,len=exports.skips.length;i<len;i++)if(exports.skips[i].test(name))return!1;for(i=0,len=exports.names.length;i<len;i++)if(exports.names[i].test(name))return!0;return!1}function coerce(val){return val instanceof Error?val.stack||val.message:val}(exports=module.exports=createDebug.debug=createDebug.default=createDebug).coerce=coerce,exports.disable=disable,exports.enable=enable,exports.enabled=enabled,exports.humanize=require("ms"),exports.names=[],exports.skips=[],exports.formatters={}},{ms:58}],37:[function(require,module,exports){function EventEmitter(){this._events=this._events||{},this._maxListeners=this._maxListeners||void 0}function isFunction(arg){return"function"==typeof arg}function isNumber(arg){return"number"==typeof arg}function isObject(arg){return"object"==typeof arg&&null!==arg}function isUndefined(arg){return void 0===arg}module.exports=EventEmitter,EventEmitter.EventEmitter=EventEmitter,EventEmitter.prototype._events=void 0,EventEmitter.prototype._maxListeners=void 0,EventEmitter.defaultMaxListeners=10,EventEmitter.prototype.setMaxListeners=function(n){if(!isNumber(n)||n<0||isNaN(n))throw TypeError("n must be a positive number");return this._maxListeners=n,this},EventEmitter.prototype.emit=function(type){var er,handler,len,args,i,listeners;if(this._events||(this._events={}),"error"===type&&(!this._events.error||isObject(this._events.error)&&!this._events.error.length)){if((er=arguments[1])instanceof Error)throw er;var err=new Error('Uncaught, unspecified "error" event. ('+er+")");throw err.context=er,err}if(isUndefined(handler=this._events[type]))return!1;if(isFunction(handler))switch(arguments.length){case 1:handler.call(this);break;case 2:handler.call(this,arguments[1]);break;case 3:handler.call(this,arguments[1],arguments[2]);break;default:args=Array.prototype.slice.call(arguments,1),handler.apply(this,args)}else if(isObject(handler))for(args=Array.prototype.slice.call(arguments,1),len=(listeners=handler.slice()).length,i=0;i<len;i++)listeners[i].apply(this,args);return!0},EventEmitter.prototype.addListener=function(type,listener){var m;if(!isFunction(listener))throw TypeError("listener must be a function");return this._events||(this._events={}),this._events.newListener&&this.emit("newListener",type,isFunction(listener.listener)?listener.listener:listener),this._events[type]?isObject(this._events[type])?this._events[type].push(listener):this._events[type]=[this._events[type],listener]:this._events[type]=listener,isObject(this._events[type])&&!this._events[type].warned&&(m=isUndefined(this._maxListeners)?EventEmitter.defaultMaxListeners:this._maxListeners)&&m>0&&this._events[type].length>m&&(this._events[type].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[type].length),"function"==typeof console.trace&&console.trace()),this},EventEmitter.prototype.on=EventEmitter.prototype.addListener,EventEmitter.prototype.once=function(type,listener){if(!isFunction(listener))throw TypeError("listener must be a function");var fired=!1;function g(){this.removeListener(type,g),fired||(fired=!0,listener.apply(this,arguments))}return g.listener=listener,this.on(type,g),this},EventEmitter.prototype.removeListener=function(type,listener){var list,position,length,i;if(!isFunction(listener))throw TypeError("listener must be a function");if(!this._events||!this._events[type])return this;if(length=(list=this._events[type]).length,position=-1,list===listener||isFunction(list.listener)&&list.listener===listener)delete this._events[type],this._events.removeListener&&this.emit("removeListener",type,listener);else if(isObject(list)){for(i=length;i-- >0;)if(list[i]===listener||list[i].listener&&list[i].listener===listener){position=i;break}if(position<0)return this;1===list.length?(list.length=0,delete this._events[type]):list.splice(position,1),this._events.removeListener&&this.emit("removeListener",type,listener)}return this},EventEmitter.prototype.removeAllListeners=function(type){var key,listeners;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[type]&&delete this._events[type],this;if(0===arguments.length){for(key in this._events)"removeListener"!==key&&this.removeAllListeners(key);return this.removeAllListeners("removeListener"),this._events={},this}if(isFunction(listeners=this._events[type]))this.removeListener(type,listeners);else if(listeners)for(;listeners.length;)this.removeListener(type,listeners[listeners.length-1]);return delete this._events[type],this},EventEmitter.prototype.listeners=function(type){return this._events&&this._events[type]?isFunction(this._events[type])?[this._events[type]]:this._events[type].slice():[]},EventEmitter.prototype.listenerCount=function(type){if(this._events){var evlistener=this._events[type];if(isFunction(evlistener))return 1;if(evlistener)return evlistener.length}return 0},EventEmitter.listenerCount=function(emitter,type){return emitter.listenerCount(type)}},{}],38:[function(require,module,exports){"use strict";module.exports="object"==typeof self?self.FormData:window.FormData},{}],39:[function(require,module,exports){"use strict";var Buffer=require("safe-buffer").Buffer,Transform=require("stream").Transform;function HashBase(blockSize){Transform.call(this),this._block=Buffer.allocUnsafe(blockSize),this._blockSize=blockSize,this._blockOffset=0,this._length=[0,0,0,0],this._finalized=!1}require("inherits")(HashBase,Transform),HashBase.prototype._transform=function(chunk,encoding,callback){var error=null;try{this.update(chunk,encoding)}catch(err){error=err}callback(error)},HashBase.prototype._flush=function(callback){var error=null;try{this.push(this.digest())}catch(err){error=err}callback(error)};var useUint8Array="undefined"!=typeof Uint8Array,useArrayBuffer="undefined"!=typeof ArrayBuffer&&"undefined"!=typeof Uint8Array&&ArrayBuffer.isView&&(Buffer.prototype instanceof Uint8Array||Buffer.TYPED_ARRAY_SUPPORT);function toBuffer(data,encoding){if(data instanceof Buffer)return data;if("string"==typeof data)return Buffer.from(data,encoding);if(useArrayBuffer&&ArrayBuffer.isView(data)){if(0===data.byteLength)return Buffer.alloc(0);var res=Buffer.from(data.buffer,data.byteOffset,data.byteLength);if(res.byteLength===data.byteLength)return res}if(useUint8Array&&data instanceof Uint8Array)return Buffer.from(data);if(Buffer.isBuffer(data)&&data.constructor&&"function"==typeof data.constructor.isBuffer&&data.constructor.isBuffer(data))return Buffer.from(data);throw new TypeError('The "data" argument must be of type string or an instance of Buffer, TypedArray, or DataView.')}HashBase.prototype.update=function(data,encoding){if(this._finalized)throw new Error("Digest already called");data=toBuffer(data,encoding);for(var block=this._block,offset=0;this._blockOffset+data.length-offset>=this._blockSize;){for(var i=this._blockOffset;i<this._blockSize;)block[i++]=data[offset++];this._update(),this._blockOffset=0}for(;offset<data.length;)block[this._blockOffset++]=data[offset++];for(var j=0,carry=8*data.length;carry>0;++j)this._length[j]+=carry,(carry=this._length[j]/4294967296|0)>0&&(this._length[j]-=4294967296*carry);return this},HashBase.prototype._update=function(){throw new Error("_update is not implemented")},HashBase.prototype.digest=function(encoding){if(this._finalized)throw new Error("Digest already called");this._finalized=!0;var digest=this._digest();void 0!==encoding&&(digest=digest.toString(encoding)),this._block.fill(0),this._blockOffset=0;for(var i=0;i<4;++i)this._length[i]=0;return digest},HashBase.prototype._digest=function(){throw new Error("_digest is not implemented")},module.exports=HashBase},{inherits:41,"safe-buffer":107,stream:109}],40:[function(require,module,exports){exports.read=function(buffer,offset,isLE,mLen,nBytes){var e,m,eLen=8*nBytes-mLen-1,eMax=(1<<eLen)-1,eBias=eMax>>1,nBits=-7,i=isLE?nBytes-1:0,d=isLE?-1:1,s=buffer[offset+i];for(i+=d,e=s&(1<<-nBits)-1,s>>=-nBits,nBits+=eLen;nBits>0;e=256*e+buffer[offset+i],i+=d,nBits-=8);for(m=e&(1<<-nBits)-1,e>>=-nBits,nBits+=mLen;nBits>0;m=256*m+buffer[offset+i],i+=d,nBits-=8);if(0===e)e=1-eBias;else{if(e===eMax)return m?NaN:1/0*(s?-1:1);m+=Math.pow(2,mLen),e-=eBias}return(s?-1:1)*m*Math.pow(2,e-mLen)},exports.write=function(buffer,value,offset,isLE,mLen,nBytes){var e,m,c,eLen=8*nBytes-mLen-1,eMax=(1<<eLen)-1,eBias=eMax>>1,rt=23===mLen?Math.pow(2,-24)-Math.pow(2,-77):0,i=isLE?0:nBytes-1,d=isLE?1:-1,s=value<0||0===value&&1/value<0?1:0;for(value=Math.abs(value),isNaN(value)||value===1/0?(m=isNaN(value)?1:0,e=eMax):(e=Math.floor(Math.log(value)/Math.LN2),value*(c=Math.pow(2,-e))<1&&(e--,c*=2),(value+=e+eBias>=1?rt/c:rt*Math.pow(2,1-eBias))*c>=2&&(e++,c/=2),e+eBias>=eMax?(m=0,e=eMax):e+eBias>=1?(m=(value*c-1)*Math.pow(2,mLen),e+=eBias):(m=value*Math.pow(2,eBias-1)*Math.pow(2,mLen),e=0));mLen>=8;buffer[offset+i]=255&m,i+=d,m/=256,mLen-=8);for(e=e<<mLen|m,eLen+=mLen;eLen>0;buffer[offset+i]=255&e,i+=d,e/=256,eLen-=8);buffer[offset+i-d]|=128*s}},{}],41:[function(require,module,exports){"function"==typeof Object.create?module.exports=function inherits(ctor,superCtor){superCtor&&(ctor.super_=superCtor,ctor.prototype=Object.create(superCtor.prototype,{constructor:{value:ctor,enumerable:!1,writable:!0,configurable:!0}}))}:module.exports=function inherits(ctor,superCtor){if(superCtor){ctor.super_=superCtor;var TempCtor=function(){};TempCtor.prototype=superCtor.prototype,ctor.prototype=new TempCtor,ctor.prototype.constructor=ctor}}},{}],42:[function(require,module,exports){var toString={}.toString;module.exports=Array.isArray||function(arr){return"[object Array]"==toString.call(arr)}},{}],43:[function(require,module,exports){var MAX_SAFE_INTEGER=9007199254740991,argsTag="[object Arguments]",funcTag="[object Function]",genTag="[object GeneratorFunction]",reIsUint=/^(?:0|[1-9]\d*)$/;function apply(func,thisArg,args){switch(args.length){case 0:return func.call(thisArg);case 1:return func.call(thisArg,args[0]);case 2:return func.call(thisArg,args[0],args[1]);case 3:return func.call(thisArg,args[0],args[1],args[2])}return func.apply(thisArg,args)}function baseTimes(n,iteratee){for(var index=-1,result=Array(n);++index<n;)result[index]=iteratee(index);return result}function overArg(func,transform){return function(arg){return func(transform(arg))}}var objectProto=Object.prototype,hasOwnProperty=objectProto.hasOwnProperty,objectToString=objectProto.toString,propertyIsEnumerable=objectProto.propertyIsEnumerable,nativeKeys=overArg(Object.keys,Object),nativeMax=Math.max,nonEnumShadows=!propertyIsEnumerable.call({valueOf:1},"valueOf");function arrayLikeKeys(value,inherited){var result=isArray(value)||isArguments(value)?baseTimes(value.length,String):[],length=result.length,skipIndexes=!!length;for(var key in value)!inherited&&!hasOwnProperty.call(value,key)||skipIndexes&&("length"==key||isIndex(key,length))||result.push(key);return result}function assignValue(object,key,value){var objValue=object[key];hasOwnProperty.call(object,key)&&eq(objValue,value)&&(void 0!==value||key in object)||(object[key]=value)}function baseKeys(object){if(!isPrototype(object))return nativeKeys(object);var result=[];for(var key in Object(object))hasOwnProperty.call(object,key)&&"constructor"!=key&&result.push(key);return result}function baseRest(func,start){return start=nativeMax(void 0===start?func.length-1:start,0),function(){for(var args=arguments,index=-1,length=nativeMax(args.length-start,0),array=Array(length);++index<length;)array[index]=args[start+index];index=-1;for(var otherArgs=Array(start+1);++index<start;)otherArgs[index]=args[index];return otherArgs[start]=array,apply(func,this,otherArgs)}}function copyObject(source,props,object,customizer){object||(object={});for(var index=-1,length=props.length;++index<length;){var key=props[index],newValue=customizer?customizer(object[key],source[key],key,object,source):void 0;assignValue(object,key,void 0===newValue?source[key]:newValue)}return object}function createAssigner(assigner){return baseRest(function(object,sources){var index=-1,length=sources.length,customizer=length>1?sources[length-1]:void 0,guard=length>2?sources[2]:void 0;for(customizer=assigner.length>3&&"function"==typeof customizer?(length--,customizer):void 0,guard&&isIterateeCall(sources[0],sources[1],guard)&&(customizer=length<3?void 0:customizer,length=1),object=Object(object);++index<length;){var source=sources[index];source&&assigner(object,source,index,customizer)}return object})}function isIndex(value,length){return!!(length=null==length?MAX_SAFE_INTEGER:length)&&("number"==typeof value||reIsUint.test(value))&&value>-1&&value%1==0&&value<length}function isIterateeCall(value,index,object){if(!isObject(object))return!1;var type=typeof index;return!!("number"==type?isArrayLike(object)&&isIndex(index,object.length):"string"==type&&index in object)&&eq(object[index],value)}function isPrototype(value){var Ctor=value&&value.constructor;return value===("function"==typeof Ctor&&Ctor.prototype||objectProto)}function eq(value,other){return value===other||value!=value&&other!=other}function isArguments(value){return isArrayLikeObject(value)&&hasOwnProperty.call(value,"callee")&&(!propertyIsEnumerable.call(value,"callee")||objectToString.call(value)==argsTag)}var isArray=Array.isArray;function isArrayLike(value){return null!=value&&isLength(value.length)&&!isFunction(value)}function isArrayLikeObject(value){return isObjectLike(value)&&isArrayLike(value)}function isFunction(value){var tag=isObject(value)?objectToString.call(value):"";return tag==funcTag||tag==genTag}function isLength(value){return"number"==typeof value&&value>-1&&value%1==0&&value<=MAX_SAFE_INTEGER}function isObject(value){var type=typeof value;return!!value&&("object"==type||"function"==type)}function isObjectLike(value){return!!value&&"object"==typeof value}var assign=createAssigner(function(object,source){if(nonEnumShadows||isPrototype(source)||isArrayLike(source))copyObject(source,keys(source),object);else for(var key in source)hasOwnProperty.call(source,key)&&assignValue(object,key,source[key])});function keys(object){return isArrayLike(object)?arrayLikeKeys(object):baseKeys(object)}module.exports=assign},{}],44:[function(require,module,exports){"use strict";var parse=require("./lib/parse"),Parser=require("./lib/Parser"),escape=require("./lib/escape"),Element=require("./lib/Element"),equal=require("./lib/equal"),createElement=require("./lib/createElement"),tag=require("./lib/tag"),tagString=require("./lib/tagString"),is=require("./lib/is"),clone=require("./lib/clone"),stringify=require("./lib/stringify");exports=module.exports=function ltx(){return tag.apply(null,arguments)},exports.Element=Element,exports.equal=equal.equal,exports.nameEqual=equal.name,exports.attrsEqual=equal.attrs,exports.childrenEqual=equal.children,exports.isNode=is.isNode,exports.isElement=is.isElement,exports.isText=is.isText,exports.clone=clone,exports.createElement=createElement,exports.escapeXML=escape.escapeXML,exports.unescapeXML=escape.unescapeXML,exports.escapeXMLText=escape.escapeXMLText,exports.unescapeXMLText=escape.unescapeXMLText,exports.Parser=Parser,exports.parse=parse,exports.tag=tag,exports.tagString=tagString,exports.stringify=stringify},{"./lib/Element":45,"./lib/Parser":46,"./lib/clone":47,"./lib/createElement":48,"./lib/equal":49,"./lib/escape":50,"./lib/is":51,"./lib/parse":52,"./lib/stringify":54,"./lib/tag":55,"./lib/tagString":56}],45:[function(require,module,exports){"use strict";var escape=require("./escape"),escapeXML=escape.escapeXML,escapeXMLText=escape.escapeXMLText,equality=require("./equal"),equal=equality.equal,nameEqual=equality.name,attrsEqual=equality.attrs,childrenEqual=equality.children,clone=require("./clone");function Element(name,attrs){this.name=name,this.parent=null,this.children=[],this.attrs={},this.setAttrs(attrs)}Element.prototype.is=function(name,xmlns){return this.getName()===name&&(!xmlns||this.getNS()===xmlns)},Element.prototype.getName=function(){return this.name.indexOf(":")>=0?this.name.substr(this.name.indexOf(":")+1):this.name},Element.prototype.getNS=function(){if(this.name.indexOf(":")>=0){var prefix=this.name.substr(0,this.name.indexOf(":"));return this.findNS(prefix)}return this.findNS()},Element.prototype.findNS=function(prefix){if(prefix){var attr="xmlns:"+prefix;if(this.attrs[attr])return this.attrs[attr];if(this.parent)return this.parent.findNS(prefix)}else{if(this.attrs.xmlns)return this.attrs.xmlns;if(this.parent)return this.parent.findNS()}},Element.prototype.getXmlns=function(){var namespaces={};for(var attr in this.parent&&(namespaces=this.parent.getXmlns()),this.attrs){var m=attr.match("xmlns:?(.*)");this.attrs.hasOwnProperty(attr)&&m&&(namespaces[this.attrs[attr]]=m[1])}return namespaces},Element.prototype.setAttrs=function(attrs){"string"==typeof attrs?this.attrs.xmlns=attrs:attrs&&Object.keys(attrs).forEach(function(key){this.attrs[key]=attrs[key]},this)},Element.prototype.getAttr=function(name,xmlns){if(!xmlns)return this.attrs[name];var namespaces=this.getXmlns();return namespaces[xmlns]?this.attrs[[namespaces[xmlns],name].join(":")]:null},Element.prototype.getChild=function(name,xmlns){return this.getChildren(name,xmlns)[0]},Element.prototype.getChildren=function(name,xmlns){for(var result=[],i=0;i<this.children.length;i++){var child=this.children[i];!child.getName||child.getName()!==name||xmlns&&child.getNS()!==xmlns||result.push(child)}return result},Element.prototype.getChildByAttr=function(attr,val,xmlns,recursive){return this.getChildrenByAttr(attr,val,xmlns,recursive)[0]},Element.prototype.getChildrenByAttr=function(attr,val,xmlns,recursive){for(var result=[],i=0;i<this.children.length;i++){var child=this.children[i];!child.attrs||child.attrs[attr]!==val||xmlns&&child.getNS()!==xmlns||result.push(child),recursive&&child.getChildrenByAttr&&result.push(child.getChildrenByAttr(attr,val,xmlns,!0))}return recursive&&(result=[].concat.apply([],result)),result},Element.prototype.getChildrenByFilter=function(filter,recursive){for(var result=[],i=0;i<this.children.length;i++){var child=this.children[i];filter(child)&&result.push(child),recursive&&child.getChildrenByFilter&&result.push(child.getChildrenByFilter(filter,!0))}return recursive&&(result=[].concat.apply([],result)),result},Element.prototype.getText=function(){for(var text="",i=0;i<this.children.length;i++){var child=this.children[i];"string"!=typeof child&&"number"!=typeof child||(text+=child)}return text},Element.prototype.getChildText=function(name,xmlns){var child=this.getChild(name,xmlns);return child?child.getText():null},Element.prototype.getChildElements=function(){return this.getChildrenByFilter(function(child){return child instanceof Element})},Element.prototype.root=function(){return this.parent?this.parent.root():this},Element.prototype.tree=Element.prototype.root,Element.prototype.up=function(){return this.parent?this.parent:this},Element.prototype.c=function(name,attrs){return this.cnode(new Element(name,attrs))},Element.prototype.cnode=function(child){return this.children.push(child),"object"==typeof child&&(child.parent=this),child},Element.prototype.t=function(text){return this.children.push(text),this},Element.prototype.remove=function(el,xmlns){var filter;return filter="string"==typeof el?function(child){return!(child.is&&child.is(el,xmlns))}:function(child){return child!==el},this.children=this.children.filter(filter),this},Element.prototype.clone=function(){return clone(this)},Element.prototype.text=function(val){return val&&1===this.children.length?(this.children[0]=val,this):this.getText()},Element.prototype.attr=function(attr,val){return void 0!==val||null===val?(this.attrs||(this.attrs={}),this.attrs[attr]=val,this):this.attrs[attr]},Element.prototype.toString=function(){var s="";return this.write(function(c){s+=c}),s},Element.prototype.toJSON=function(){return{name:this.name,attrs:this.attrs,children:this.children.map(function(child){return child&&child.toJSON?child.toJSON():child})}},Element.prototype._addChildren=function(writer){writer(">");for(var i=0;i<this.children.length;i++){var child=this.children[i];(child||0===child)&&(child.write?child.write(writer):"string"==typeof child?writer(escapeXMLText(child)):child.toString&&writer(escapeXMLText(child.toString(10))))}writer("</"),writer(this.name),writer(">")},Element.prototype.write=function(writer){for(var k in writer("<"),writer(this.name),this.attrs){var v=this.attrs[k];null!=v&&(writer(" "),writer(k),writer('="'),"string"!=typeof v&&(v=v.toString()),writer(escapeXML(v)),writer('"'))}0===this.children.length?writer("/>"):this._addChildren(writer)},Element.prototype.nameEquals=function(el){return nameEqual(this,el)},Element.prototype.attrsEquals=function(el){return attrsEqual(this,el)},Element.prototype.childrenEquals=function(el){return childrenEqual(this,el)},Element.prototype.equals=function(el){return equal(this,el)},module.exports=Element},{"./clone":47,"./equal":49,"./escape":50}],46:[function(require,module,exports){"use strict";var EventEmitter=require("events").EventEmitter,inherits=require("inherits"),Element=require("./Element"),LtxParser=require("./parsers/ltx"),Parser=function(options){EventEmitter.call(this);var el,ParserInterface=this.Parser=options&&options.Parser||this.DefaultParser,ElementInterface=this.Element=options&&options.Element||this.DefaultElement;this.parser=new ParserInterface;var self=this;this.parser.on("startElement",function(name,attrs){var child=new ElementInterface(name,attrs);el=el?el.cnode(child):child}),this.parser.on("endElement",function(name){el&&name===el.name&&(el.parent?el=el.parent:self.tree||(self.tree=el,el=void 0))}),this.parser.on("text",function(str){el&&el.t(str)}),this.parser.on("error",function(e){self.error=e,self.emit("error",e)})};inherits(Parser,EventEmitter),Parser.prototype.DefaultParser=LtxParser,Parser.prototype.DefaultElement=Element,Parser.prototype.write=function(data){this.parser.write(data)},Parser.prototype.end=function(data){this.parser.end(data),this.error||(this.tree?this.emit("tree",this.tree):this.emit("error",new Error("Incomplete document")))},module.exports=Parser},{"./Element":45,"./parsers/ltx":53,events:37,inherits:41}],47:[function(require,module,exports){"use strict";module.exports=function clone(el){for(var clone=new el.constructor(el.name,el.attrs),i=0;i<el.children.length;i++){var child=el.children[i];clone.cnode(child.clone?child.clone():child)}return clone}},{}],48:[function(require,module,exports){"use strict";var Element=require("./Element");module.exports=function createElement(name,attrs){for(var el=new Element(name,attrs),i=2;i<arguments.length;i++){var child=arguments[i];child&&el.cnode(child)}return el}},{"./Element":45}],49:[function(require,module,exports){"use strict";function nameEqual(a,b){return a.name===b.name}function attrsEqual(a,b){var attrs=a.attrs,keys=Object.keys(attrs),length=keys.length;if(length!==Object.keys(b.attrs).length)return!1;for(var i=0,l=length;i<l;i++){var key=keys[i],value=attrs[key];if(null==value||null==b.attrs[key]){if(value!==b.attrs[key])return!1}else if(value.toString()!==b.attrs[key].toString())return!1}return!0}function childrenEqual(a,b){var children=a.children,length=children.length;if(length!==b.children.length)return!1;for(var i=0,l=length;i<l;i++){var child=children[i];if("string"==typeof child){if(child!==b.children[i])return!1}else if(!child.equals(b.children[i]))return!1}return!0}function equal(a,b){return!!nameEqual(a,b)&&!!attrsEqual(a,b)&&!!childrenEqual(a,b)}module.exports.name=nameEqual,module.exports.attrs=attrsEqual,module.exports.children=childrenEqual,module.exports.equal=equal},{}],50:[function(require,module,exports){"use strict";var escapeXMLTable={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&apos;"};function escapeXMLReplace(match){return escapeXMLTable[match]}var unescapeXMLTable={"&amp;":"&","&lt;":"<","&gt;":">","&quot;":'"',"&apos;":"'"};function unescapeXMLReplace(match){if("#"===match[1]){var num;if(9===(num="x"===match[2]?parseInt(match.slice(3),16):parseInt(match.slice(2),10))||10===num||13===num||num>=32&&num<=55295||num>=57344&&num<=65533||num>=65536&&num<=1114111)return String.fromCodePoint(num);throw new Error("Illegal XML character 0x"+num.toString(16))}if(unescapeXMLTable[match])return unescapeXMLTable[match]||match;throw new Error("Illegal XML entity "+match)}exports.escapeXML=function escapeXML(s){return s.replace(/&|<|>|"|'/g,escapeXMLReplace)},exports.unescapeXML=function unescapeXML(s){for(var result="",start=-1,end=-1,previous=0;-1!==(start=s.indexOf("&",previous))&&-1!==(end=s.indexOf(";",start+1));)result=result+s.substring(previous,start)+unescapeXMLReplace(s.substring(start,end+1)),previous=end+1;return 0===previous?s:result+=s.substring(previous)},exports.escapeXMLText=function escapeXMLText(s){return s.replace(/&|<|>/g,escapeXMLReplace)},exports.unescapeXMLText=function unescapeXMLText(s){return s.replace(/&(amp|#38|lt|#60|gt|#62);/g,unescapeXMLReplace)}},{}],51:[function(require,module,exports){"use strict";var Element=require("./Element");module.exports.isNode=function is(el){return el instanceof Element||"string"==typeof el},module.exports.isElement=function isElement(el){return el instanceof Element},module.exports.isText=function isText(el){return"string"==typeof el}},{"./Element":45}],52:[function(require,module,exports){"use strict";var Parser=require("./Parser");module.exports=function parse(data,options){var p;p="function"==typeof options?new options:new Parser(options);var result=null,error=null;if(p.on("tree",function(tree){result=tree}),p.on("error",function(e){error=e}),p.write(data),p.end(),error)throw error;return result}},{"./Parser":46}],53:[function(require,module,exports){"use strict";var inherits=require("inherits"),EventEmitter=require("events").EventEmitter,unescapeXML=require("../escape").unescapeXML,STATE_TEXT=0,STATE_IGNORE_COMMENT=1,STATE_IGNORE_INSTRUCTION=2,STATE_TAG_NAME=3,STATE_TAG=4,STATE_ATTR_NAME=5,STATE_ATTR_EQ=6,STATE_ATTR_QUOT=7,STATE_ATTR_VALUE=8,STATE_CDATA=9,STATE_IGNORE_CDATA=10,SaxLtx=module.exports=function SaxLtx(){EventEmitter.call(this);var remainder,tagName,attrs,endTag,selfClosing,attrQuote,attrQuoteChar,attrName,state=STATE_TEXT,recordStart=0;this._handleTagOpening=function(endTag,tagName,attrs){endTag?this.emit("endElement",tagName):(this.emit("startElement",tagName,attrs),selfClosing&&this.emit("endElement",tagName))},this.write=function(data){"string"!=typeof data&&(data=data.toString());var pos=0;function endRecording(){if("number"==typeof recordStart){var recorded=data.substring(recordStart,pos);return recordStart=void 0,recorded}}for(remainder&&(data=remainder+data,pos+=remainder.length,remainder=null);pos<data.length;pos++){if(state===STATE_TEXT){var lt=data.indexOf("<",pos);-1!==lt&&pos!==lt&&(pos=lt)}else if(state===STATE_ATTR_VALUE){var quot=data.indexOf(attrQuoteChar,pos);-1!==quot&&(pos=quot)}else if(state===STATE_IGNORE_COMMENT){var endcomment=data.indexOf("--\x3e",pos);-1!==endcomment&&(pos=endcomment+2)}else if(state===STATE_IGNORE_CDATA){var endCDATA=data.indexOf("]]>",pos);-1!==endCDATA&&(pos=endCDATA+2)}var c=data.charCodeAt(pos);switch(state){case STATE_TEXT:if(60===c){var text=endRecording();text&&this.emit("text",unescapeXML(text)),state=STATE_TAG_NAME,recordStart=pos+1,attrs={}}break;case STATE_CDATA:if(93===c&&"]>"===data.substr(pos+1,2)){var cData=endRecording();cData&&this.emit("text",cData),state=STATE_TEXT}break;case STATE_TAG_NAME:47===c&&recordStart===pos?(recordStart=pos+1,endTag=!0):33===c?"[CDATA["===data.substr(pos+1,7)?(recordStart=pos+8,state=STATE_CDATA):(recordStart=void 0,state=STATE_IGNORE_COMMENT):63===c?(recordStart=void 0,state=STATE_IGNORE_INSTRUCTION):(c<=32||47===c||62===c)&&(tagName=endRecording(),pos--,state=STATE_TAG);break;case STATE_IGNORE_COMMENT:if(62===c){var prevFirst=data.charCodeAt(pos-1),prevSecond=data.charCodeAt(pos-2);(45===prevFirst&&45===prevSecond||93===prevFirst&&93===prevSecond)&&(state=STATE_TEXT)}break;case STATE_IGNORE_INSTRUCTION:62===c&&63===data.charCodeAt(pos-1)&&(state=STATE_TEXT);break;case STATE_TAG:62===c?(this._handleTagOpening(endTag,tagName,attrs),tagName=void 0,attrs=void 0,endTag=void 0,selfClosing=void 0,state=STATE_TEXT,recordStart=pos+1):47===c?selfClosing=!0:c>32&&(recordStart=pos,state=STATE_ATTR_NAME);break;case STATE_ATTR_NAME:(c<=32||61===c)&&(attrName=endRecording(),pos--,state=STATE_ATTR_EQ);break;case STATE_ATTR_EQ:61===c&&(state=STATE_ATTR_QUOT);break;case STATE_ATTR_QUOT:34!==c&&39!==c||(attrQuote=c,attrQuoteChar=34===c?'"':"'",state=STATE_ATTR_VALUE,recordStart=pos+1);break;case STATE_ATTR_VALUE:if(c===attrQuote){var value=unescapeXML(endRecording());attrs[attrName]=value,attrName=void 0,state=STATE_TAG}}}"number"==typeof recordStart&&recordStart<=data.length&&(remainder=data.slice(recordStart),recordStart=0)}};inherits(SaxLtx,EventEmitter),SaxLtx.prototype.end=function(data){data&&this.write(data),this.write=function(){}}},{"../escape":50,events:37,inherits:41}],54:[function(require,module,exports){"use strict";function stringify(el,indent,level){"number"==typeof indent&&(indent=" ".repeat(indent)),level||(level=1);var s="";return s+="<"+el.name,Object.keys(el.attrs).forEach(function(k){s+=" "+k+'="'+el.attrs[k]+'"'}),el.children.length?(s+=">",el.children.forEach(function(child,i){indent&&(s+="\n"+indent.repeat(level)),s+="string"==typeof child?child:stringify(child,indent,level+1)}),indent&&(s+="\n"+indent.repeat(level-1)),s+="</"+el.name+">"):s+="/>",s}module.exports=stringify},{}],55:[function(require,module,exports){"use strict";var tagString=require("./tagString"),parse=require("./parse");module.exports=function tag(){return parse(tagString.apply(null,arguments))}},{"./parse":52,"./tagString":56}],56:[function(require,module,exports){"use strict";var escape=require("./escape").escapeXML;module.exports=function tagString(){for(var literals=arguments[0],str="",i=1;i<arguments.length;i++)str+=literals[i-1],str+=escape(arguments[i]);return str+=literals[literals.length-1]}},{"./escape":50}],57:[function(require,module,exports){"use strict";var inherits=require("inherits"),HashBase=require("hash-base"),Buffer=require("safe-buffer").Buffer,ARRAY16=new Array(16);function MD5(){HashBase.call(this,64),this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878}function rotl(x,n){return x<<n|x>>>32-n}function fnF(a,b,c,d,m,k,s){return rotl(a+(b&c|~b&d)+m+k|0,s)+b|0}function fnG(a,b,c,d,m,k,s){return rotl(a+(b&d|c&~d)+m+k|0,s)+b|0}function fnH(a,b,c,d,m,k,s){return rotl(a+(b^c^d)+m+k|0,s)+b|0}function fnI(a,b,c,d,m,k,s){return rotl(a+(c^(b|~d))+m+k|0,s)+b|0}inherits(MD5,HashBase),MD5.prototype._update=function(){for(var M=ARRAY16,i=0;i<16;++i)M[i]=this._block.readInt32LE(4*i);var a=this._a,b=this._b,c=this._c,d=this._d;a=fnF(a,b,c,d,M[0],3614090360,7),d=fnF(d,a,b,c,M[1],3905402710,12),c=fnF(c,d,a,b,M[2],606105819,17),b=fnF(b,c,d,a,M[3],3250441966,22),a=fnF(a,b,c,d,M[4],4118548399,7),d=fnF(d,a,b,c,M[5],1200080426,12),c=fnF(c,d,a,b,M[6],2821735955,17),b=fnF(b,c,d,a,M[7],4249261313,22),a=fnF(a,b,c,d,M[8],1770035416,7),d=fnF(d,a,b,c,M[9],2336552879,12),c=fnF(c,d,a,b,M[10],4294925233,17),b=fnF(b,c,d,a,M[11],2304563134,22),a=fnF(a,b,c,d,M[12],1804603682,7),d=fnF(d,a,b,c,M[13],4254626195,12),c=fnF(c,d,a,b,M[14],2792965006,17),a=fnG(a,b=fnF(b,c,d,a,M[15],1236535329,22),c,d,M[1],4129170786,5),d=fnG(d,a,b,c,M[6],3225465664,9),c=fnG(c,d,a,b,M[11],643717713,14),b=fnG(b,c,d,a,M[0],3921069994,20),a=fnG(a,b,c,d,M[5],3593408605,5),d=fnG(d,a,b,c,M[10],38016083,9),c=fnG(c,d,a,b,M[15],3634488961,14),b=fnG(b,c,d,a,M[4],3889429448,20),a=fnG(a,b,c,d,M[9],568446438,5),d=fnG(d,a,b,c,M[14],3275163606,9),c=fnG(c,d,a,b,M[3],4107603335,14),b=fnG(b,c,d,a,M[8],1163531501,20),a=fnG(a,b,c,d,M[13],2850285829,5),d=fnG(d,a,b,c,M[2],4243563512,9),c=fnG(c,d,a,b,M[7],1735328473,14),a=fnH(a,b=fnG(b,c,d,a,M[12],2368359562,20),c,d,M[5],4294588738,4),d=fnH(d,a,b,c,M[8],2272392833,11),c=fnH(c,d,a,b,M[11],1839030562,16),b=fnH(b,c,d,a,M[14],4259657740,23),a=fnH(a,b,c,d,M[1],2763975236,4),d=fnH(d,a,b,c,M[4],1272893353,11),c=fnH(c,d,a,b,M[7],4139469664,16),b=fnH(b,c,d,a,M[10],3200236656,23),a=fnH(a,b,c,d,M[13],681279174,4),d=fnH(d,a,b,c,M[0],3936430074,11),c=fnH(c,d,a,b,M[3],3572445317,16),b=fnH(b,c,d,a,M[6],76029189,23),a=fnH(a,b,c,d,M[9],3654602809,4),d=fnH(d,a,b,c,M[12],3873151461,11),c=fnH(c,d,a,b,M[15],530742520,16),a=fnI(a,b=fnH(b,c,d,a,M[2],3299628645,23),c,d,M[0],4096336452,6),d=fnI(d,a,b,c,M[7],1126891415,10),c=fnI(c,d,a,b,M[14],2878612391,15),b=fnI(b,c,d,a,M[5],4237533241,21),a=fnI(a,b,c,d,M[12],1700485571,6),d=fnI(d,a,b,c,M[3],2399980690,10),c=fnI(c,d,a,b,M[10],4293915773,15),b=fnI(b,c,d,a,M[1],2240044497,21),a=fnI(a,b,c,d,M[8],1873313359,6),d=fnI(d,a,b,c,M[15],4264355552,10),c=fnI(c,d,a,b,M[6],2734768916,15),b=fnI(b,c,d,a,M[13],1309151649,21),a=fnI(a,b,c,d,M[4],4149444226,6),d=fnI(d,a,b,c,M[11],3174756917,10),c=fnI(c,d,a,b,M[2],718787259,15),b=fnI(b,c,d,a,M[9],3951481745,21),this._a=this._a+a|0,this._b=this._b+b|0,this._c=this._c+c|0,this._d=this._d+d|0},MD5.prototype._digest=function(){this._block[this._blockOffset++]=128,this._blockOffset>56&&(this._block.fill(0,this._blockOffset,64),this._update(),this._blockOffset=0),this._block.fill(0,this._blockOffset,56),this._block.writeUInt32LE(this._length[0],56),this._block.writeUInt32LE(this._length[1],60),this._update();var buffer=Buffer.allocUnsafe(16);return buffer.writeInt32LE(this._a,0),buffer.writeInt32LE(this._b,4),buffer.writeInt32LE(this._c,8),buffer.writeInt32LE(this._d,12),buffer},module.exports=MD5},{"hash-base":39,inherits:41,"safe-buffer":107}],58:[function(require,module,exports){var s=1e3,m=60*s,h=60*m,d=24*h,y=365.25*d;function parse(str){if(!((str=String(str)).length>100)){var match=/^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(str);if(match){var n=parseFloat(match[1]);switch((match[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return n*y;case"days":case"day":case"d":return n*d;case"hours":case"hour":case"hrs":case"hr":case"h":return n*h;case"minutes":case"minute":case"mins":case"min":case"m":return n*m;case"seconds":case"second":case"secs":case"sec":case"s":return n*s;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return n;default:return}}}}function fmtShort(ms){return ms>=d?Math.round(ms/d)+"d":ms>=h?Math.round(ms/h)+"h":ms>=m?Math.round(ms/m)+"m":ms>=s?Math.round(ms/s)+"s":ms+"ms"}function fmtLong(ms){return plural(ms,d,"day")||plural(ms,h,"hour")||plural(ms,m,"minute")||plural(ms,s,"second")||ms+" ms"}function plural(ms,n,name){if(!(ms<n))return ms<1.5*n?Math.floor(ms/n)+" "+name:Math.ceil(ms/n)+" "+name+"s"}module.exports=function(val,options){options=options||{};var type=typeof val;if("string"===type&&val.length>0)return parse(val);if("number"===type&&!1===isNaN(val))return options.long?fmtLong(val):fmtShort(val);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(val))}},{}],59:[function(require,module,exports){(function(global){(function(){"use strict";var globalObject=function(){if("undefined"!=typeof self)return self;if("undefined"!=typeof window)return window;if(void 0!==global)return global;throw new Error("unable to locate global object")}();module.exports=exports=globalObject.fetch,globalObject.fetch&&(exports.default=globalObject.fetch.bind(globalObject)),exports.Headers=globalObject.Headers,exports.Request=globalObject.Request,exports.Response=globalObject.Response}).call(this)}).call(this,void 0!==__webpack_require__.g?__webpack_require__.g:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],60:[function(require,module,exports){"use strict";var Client=require("./lib/Client"),SASL=require("./lib/sasl"),core=require("node-xmpp-core");module.exports=Client,module.exports.Client=Client,module.exports.SASL=SASL,core.exportCoreUtils(module.exports)},{"./lib/Client":61,"./lib/sasl":69,"node-xmpp-core":72}],61:[function(require,module,exports){(function(__dirname){(function(){"use strict";var decode64,encode64,Buffer,Session=require("./session"),core=require("node-xmpp-core"),JID=core.JID,Stanza=core.Stanza,Element=core.Element,inherits=core.inherits,sasl=require("./sasl"),Anonymous=require("./authentication/anonymous"),Plain=require("./authentication/plain"),DigestMD5=require("./authentication/digestmd5"),XOAuth2=require("./authentication/xoauth2"),External=require("./authentication/external"),exec=require("child_process").exec,debug=require("debug")("xmpp:client"),path=require("path"),NS_CLIENT="jabber:client",NS_REGISTER="jabber:iq:register",NS_XMPP_SASL="urn:ietf:params:xml:ns:xmpp-sasl",NS_XMPP_BIND="urn:ietf:params:xml:ns:xmpp-bind",NS_XMPP_SESSION="urn:ietf:params:xml:ns:xmpp-session",STATE_PREAUTH=0,STATE_AUTH=1,STATE_AUTHED=2,STATE_BIND=3,STATE_SESSION=4,STATE_ONLINE=5,IQID_SESSION="sess",IQID_BIND="bind";if(void 0===btoa)var btoa=null,atob=null;function Client(options){this.options={},options&&(this.options=options),this.availableSaslMechanisms=[XOAuth2,External,DigestMD5,Plain,Anonymous],!1!==this.options.autostart&&this.connect()}"function"==typeof btoa?decode64=function(encoded){return atob(encoded)}:(Buffer=require("buffer").Buffer,decode64=function(encoded){return new Buffer(encoded,"base64").toString("utf8")}),"function"==typeof atob?encode64=function(decoded){return btoa(decoded)}:(Buffer=require("buffer").Buffer,encode64=function(decoded){return new Buffer(decoded,"utf8").toString("base64")}),inherits(Client,Session),Client.NS_CLIENT=NS_CLIENT,Client.prototype.connect=function(){if(this.options.bosh&&this.options.bosh.prebind)return this._connectViaBosh();this._useStandardConnect()},Client.prototype._useStandardConnect=function(){this.options.xmlns=NS_CLIENT,delete this.did_bind,delete this.did_session,this.state=STATE_PREAUTH,this.on("end",function(){this.state=STATE_PREAUTH,delete this.did_bind,delete this.did_session}),Session.call(this,this.options),this.options.jid=this.jid,this.connection.on("disconnect",function(error){this.state=STATE_PREAUTH,this.connection.reconnect||(error&&this.emit("error",error),this.emit("offline")),delete this.did_bind,delete this.did_session}.bind(this)),this.options.preferred?this.preferredSaslMechanism=this.options.preferred:this.preferredSaslMechanism="DIGEST-MD5";var mechs=sasl.detectMechanisms(this.options,this.availableSaslMechanisms);this.availableSaslMechanisms=mechs},Client.prototype._connectViaBosh=function(){debug("load bosh prebind");var cb=this.options.bosh.prebind;delete this.options.bosh.prebind;var cmd="node "+path.join(__dirname,"prebind.js")+" "+encodeURI(JSON.stringify(this.options));exec(cmd,function(error,stdout,stderr){if(error)cb(error,null);else{var r=stdout.match(/rid:+[ 0-9]*/i),s=stdout.match(/sid:+[ a-z+'"-_A-Z+0-9]*/i);if(!r||!s)return cb(stderr);if(r=r[0].split(":")[1].trim(),s=s[0].split(":")[1].replace("'","").replace("'","").trim(),r&&s)return cb(null,{rid:r,sid:s});cb(stderr)}})},Client.prototype.onStanza=function(stanza){return"stream:error"===stanza.name?this._handleStreamError(stanza):this.state!==STATE_ONLINE&&stanza.is("features")?(this.streamFeatures=stanza,this.useFeatures()):void this._handleStanza(stanza)},Client.prototype._handleStanza=function(stanza){switch(this.state){case STATE_ONLINE:this.emit("stanza",stanza);break;case STATE_PREAUTH:this.emit("stanza:preauth",stanza);break;case STATE_AUTH:this._handleAuthState(stanza);break;case STATE_BIND:stanza.is("iq")&&stanza.attrs.id===IQID_BIND&&this._handleBindState(stanza);break;case STATE_SESSION:!0===stanza.is("iq")&&stanza.attrs.id===IQID_SESSION&&this._handleSessionState(stanza)}},Client.prototype._handleStreamError=function(stanza){this.reconnect||this.emit("error",stanza)},Client.prototype._handleSessionState=function(stanza){"result"===stanza.attrs.type?(this.state=STATE_AUTHED,this.did_session=!0,this.useFeatures()):this.emit("error","Cannot bind resource")},Client.prototype._handleBindState=function(stanza){if("result"===stanza.attrs.type){this.state=STATE_AUTHED,this.did_bind=!0;var bindEl=stanza.getChild("bind",NS_XMPP_BIND);bindEl&&bindEl.getChild("jid")&&(this.jid=new JID(bindEl.getChild("jid").getText())),this.useFeatures()}else this.emit("error","Cannot bind resource")},Client.prototype._handleAuthState=function(stanza){if(stanza.is("challenge",NS_XMPP_SASL)){var challengeMsg=decode64(stanza.getText()),responseMsg=encode64(this.mech.challenge(challengeMsg)),response=new Element("response",{xmlns:NS_XMPP_SASL}).t(responseMsg);this.send(response)}else stanza.is("success",NS_XMPP_SASL)?(this.mech=null,this.state=STATE_AUTHED,this.emit("auth")):this.emit("error","XMPP authentication failure")},Client.prototype._handlePreAuthState=function(){this.state=STATE_AUTH;var offeredMechs=this.streamFeatures.getChild("mechanisms",NS_XMPP_SASL).getChildren("mechanism",NS_XMPP_SASL).map(function(el){return el.getText()});if(this.mech=sasl.selectMechanism(offeredMechs,this.preferredSaslMechanism,this.availableSaslMechanisms),this.mech){this.mech.authzid=this.jid.bare().toString(),this.mech.authcid=this.jid.local,this.mech.password=this.password,this.mech.api_key=this.api_key,this.mech.access_token=this.access_token,this.mech.oauth2_token=this.oauth2_token,this.mech.oauth2_auth=this.oauth2_auth,this.mech.realm=this.jid.domain,this.actAs&&(this.mech.actAs=this.actAs.user),this.mech.digest_uri="xmpp/"+this.jid.domain;var authMsg=encode64(this.mech.auth()),attrs=this.mech.authAttrs();attrs.xmlns=NS_XMPP_SASL,attrs.mechanism=this.mech.name,this.send(new Element("auth",attrs).t(authMsg))}else this.emit("error",new Error("No usable SASL mechanism"))},Client.prototype.useFeatures=function(){if(this.state===STATE_PREAUTH&&this.register)delete this.register,this.doRegister();else if(this.state===STATE_PREAUTH&&this.streamFeatures.getChild("mechanisms",NS_XMPP_SASL))this._handlePreAuthState();else if(this.state===STATE_AUTHED&&!this.did_bind&&this.streamFeatures.getChild("bind",NS_XMPP_BIND)){this.state=STATE_BIND;var bindEl=new Stanza("iq",{type:"set",id:IQID_BIND}).c("bind",{xmlns:NS_XMPP_BIND});this.jid.resource&&bindEl.c("resource").t(this.jid.resource),this.send(bindEl)}else if(this.state===STATE_AUTHED&&!this.did_session&&this.streamFeatures.getChild("session",NS_XMPP_SESSION)){this.state=STATE_SESSION;var stanza=new Stanza("iq",{type:"set",to:this.jid.domain,id:IQID_SESSION}).c("session",{xmlns:NS_XMPP_SESSION});this.send(stanza)}else this.state===STATE_AUTHED&&(this.state=STATE_ONLINE,this.emit("online",{jid:this.jid}))},Client.prototype.doRegister=function(){var id="register"+Math.ceil(99999*Math.random()),iq=new Stanza("iq",{type:"set",id,to:this.jid.domain}).c("query",{xmlns:NS_REGISTER}).c("username").t(this.jid.local).up().c("password").t(this.password);this.send(iq);var self=this,onReply=function(reply){reply.is("iq")&&reply.attrs.id===id&&(self.removeListener("stanza",onReply),"result"===reply.attrs.type?self.useFeatures():self.emit("error",new Error("Registration error")))};this.on("stanza:preauth",onReply)},Client.prototype.getSaslMechanisms=function(){return this.availableSaslMechanisms},Client.prototype.clearSaslMechanism=function(){this.availableSaslMechanisms=[]},Client.prototype.registerSaslMechanism=function(method){-1===this.availableSaslMechanisms.indexOf(method)&&this.availableSaslMechanisms.push(method)},Client.prototype.unregisterSaslMechanism=function(method){var index=this.availableSaslMechanisms.indexOf(method);index>=0&&(this.availableSaslMechanisms=this.availableSaslMechanisms.splice(index,1))},module.exports=Client}).call(this)}).call(this,"/node_modules/node-xmpp-client/lib")},{"./authentication/anonymous":62,"./authentication/digestmd5":63,"./authentication/external":64,"./authentication/plain":66,"./authentication/xoauth2":67,"./sasl":69,"./session":70,buffer:27,child_process:26,debug:35,"node-xmpp-core":72,path:25}],62:[function(require,module,exports){"use strict";var Mechanism=require("./mechanism");function Anonymous(){}(0,require("node-xmpp-core").inherits)(Anonymous,Mechanism),Anonymous.prototype.name="ANONYMOUS",Anonymous.prototype.auth=function(){return this.authzid},Anonymous.prototype.match=function(){return!0},module.exports=Anonymous},{"./mechanism":65,"node-xmpp-core":72}],63:[function(require,module,exports){"use strict";var inherits=require("node-xmpp-core").inherits,Mechanism=require("./mechanism"),crypto=require("crypto"),MD5=require("md5.js");function md5(s,encoding){return(crypto.createHash?crypto.createHash("md5"):new MD5).update(s,"binary").digest(encoding||"binary")}function md5Hex(s){return md5(s,"hex")}function parseDict(s){for(var result={};s;){var m;(m=/^(.+?)=(.*?[^\\]),\s*(.*)/.exec(s))?(result[m[1]]=m[2].replace(/"/g,""),s=m[3]):(m=/^(.+?)=(.+?),\s*(.*)/.exec(s))||(m=/^(.+?)="(.*?[^\\])"$/.exec(s))||(m=/^(.+?)=(.+?)$/.exec(s))?(result[m[1]]=m[2],s=m[3]):s=null}return result}function encodeDict(dict){var s="";for(var k in dict){var v=dict[k];v&&(s+=","+k+'="'+v+'"')}return s.substr(1)}function rjust(s,targetLen,padding){for(;s.length<targetLen;)s=padding+s;return s}function generateNonce(){for(var result="",i=0;i<8;i++)result+=String.fromCharCode(48+Math.ceil(10*Math.random()));return result}function DigestMD5(){this.nonce_count=0,this.cnonce=generateNonce(),this.authcid=null,this.actAs=null,this.realm=null,this.password=null}inherits(DigestMD5,Mechanism),DigestMD5.prototype.name="DIGEST-MD5",DigestMD5.prototype.auth=function(){return""},DigestMD5.prototype.getNC=function(){return rjust(this.nonce_count.toString(),8,"0")},DigestMD5.prototype.responseValue=function(s){var value,dict=parseDict(s);if(dict.realm&&(this.realm=dict.realm),dict.nonce&&dict.qop){this.nonce_count++;var a1=md5(this.authcid+":"+this.realm+":"+this.password)+":"+dict.nonce+":"+this.cnonce;this.actAs&&(a1+=":"+this.actAs);var a2="AUTHENTICATE:"+this.digest_uri;"auth-int"!==dict.qop&&"auth-conf"!==dict.qop||(a2+=":00000000000000000000000000000000"),value=md5Hex(md5Hex(a1)+":"+dict.nonce+":"+this.getNC()+":"+this.cnonce+":"+dict.qop+":"+md5Hex(a2))}return value},DigestMD5.prototype.challenge=function(s){var response,dict=parseDict(s);if(dict.realm&&(this.realm=dict.realm),dict.nonce&&dict.qop){var responseValue=this.responseValue(s);response={username:this.authcid,realm:this.realm,nonce:dict.nonce,cnonce:this.cnonce,nc:this.getNC(),qop:dict.qop,"digest-uri":this.digest_uri,response:responseValue,charset:"utf-8"},this.actAs&&(response.authzid=this.actAs)}else if(dict.rspauth)return"";return encodeDict(response)},DigestMD5.prototype.serverChallenge=function(){var dict={realm:""};return this.nonce=dict.nonce=generateNonce(),dict.qop="auth",this.charset=dict.charset="utf-8",dict.algorithm="md5-sess",encodeDict(dict)},DigestMD5.prototype.response=function(s){var dict=parseDict(s);return this.authcid=dict.username,dict.nonce===this.nonce&&!!dict.cnonce&&(this.cnonce=dict.cnonce,this.charset===dict.charset&&(this.response=dict.response,!0))},DigestMD5.prototype.match=function(options){return!!options.password},module.exports=DigestMD5},{"./mechanism":65,crypto:25,"md5.js":57,"node-xmpp-core":72}],64:[function(require,module,exports){"use strict";function External(){}(0,require("node-xmpp-core").inherits)(External,require("./mechanism")),External.prototype.name="EXTERNAL",External.prototype.auth=function(){return this.authzid},External.prototype.match=function(options){return!!options.credentials},module.exports=External},{"./mechanism":65,"node-xmpp-core":72}],65:[function(require,module,exports){"use strict";function Mechanism(){}(0,require("node-xmpp-core").inherits)(Mechanism,require("events").EventEmitter),Mechanism.prototype.authAttrs=function(){return{}},module.exports=Mechanism},{events:37,"node-xmpp-core":72}],66:[function(require,module,exports){"use strict";function Plain(){}(0,require("node-xmpp-core").inherits)(Plain,require("./mechanism")),Plain.prototype.name="PLAIN",Plain.prototype.auth=function(){return this.authzid+"\0"+this.authcid+"\0"+this.password},Plain.prototype.match=function(options){return!!options.password},module.exports=Plain},{"./mechanism":65,"node-xmpp-core":72}],67:[function(require,module,exports){"use strict";function XOAuth2(){this.oauth2_auth=null,this.authzid=null}(0,require("node-xmpp-core").inherits)(XOAuth2,require("./mechanism")),XOAuth2.prototype.name="X-OAUTH2",XOAuth2.prototype.NS_GOOGLE_AUTH="http://www.google.com/talk/protocol/auth",XOAuth2.prototype.auth=function(){return"\0"+this.authzid+"\0"+this.oauth2_token},XOAuth2.prototype.authAttrs=function(){return{"auth:service":"oauth2","xmlns:auth":this.oauth2_auth}},XOAuth2.prototype.match=function(options){return options.oauth2_auth===XOAuth2.prototype.NS_GOOGLE_AUTH},module.exports=XOAuth2},{"./mechanism":65,"node-xmpp-core":72}],68:[function(require,module,exports){(function(process){(function(){"use strict";var EventEmitter=require("events").EventEmitter,core=require("node-xmpp-core"),inherits=core.inherits,ltx=core.ltx,request=require("request"),debug=require("debug")("xmpp:client:bosh");function BOSHConnection(opts){var that=this;if(EventEmitter.call(this),this.boshURL=opts.bosh.url,this.jid=opts.jid,this.wait=opts.bosh.wait||60,this.xmlnsAttrs={xmlns:"http://jabber.org/protocol/httpbind","xmlns:xmpp":"urn:xmpp:xbosh","xmlns:stream":"http://etherx.jabber.org/streams"},opts.xmlns)for(var prefix in opts.xmlns)prefix?this.xmlnsAttrs["xmlns:"+prefix]=opts.xmlns[prefix]:this.xmlnsAttrs.xmlns=opts.xmlns[prefix];this.currentRequests=0,this.queue=[],this.rid=Math.ceil(9999999999*Math.random()),this.request({to:this.jid.domain,ver:"1.6",wait:this.wait,hold:"1",content:this.contentType,"xmpp:version":"1.0"},[],function(err,bodyEl){err?that.emit("error",err):bodyEl&&bodyEl.attrs&&(that.sid=bodyEl.attrs.sid,that.maxRequests=parseInt(bodyEl.attrs.requests,10)||2,that.sid&&that.maxRequests>0?(that.emit("connect"),that.processResponse(bodyEl),process.nextTick(that.mayRequest.bind(that))):that.emit("error","Invalid parameters"))})}inherits(BOSHConnection,EventEmitter),BOSHConnection.prototype.contentType="text/xml; charset=utf-8",BOSHConnection.prototype.send=function(stanza){this.queue.push(stanza.root()),process.nextTick(this.mayRequest.bind(this))},BOSHConnection.prototype.startStream=function(){var that=this;this.rid++,this.request({to:this.jid.domain,"xmpp:restart":"true"},[],function(err,bodyEl){err?(that.emit("error",err),that.emit("disconnect"),that.emit("end"),delete that.sid,that.emit("close")):(that.streamOpened=!0,bodyEl&&that.processResponse(bodyEl),process.nextTick(that.mayRequest.bind(that)))})},BOSHConnection.prototype.processResponse=function(bodyEl){if(debug("process bosh server response "+bodyEl.toString()),bodyEl&&bodyEl.children)for(var i=0;i<bodyEl.children.length;i++){var child=bodyEl.children[i];child.name&&child.attrs&&child.children&&this.emit("stanza",child)}bodyEl&&"terminate"===bodyEl.attrs.type&&(this.shutdown&&!bodyEl.attrs.condition||this.emit("error",new Error(bodyEl.attrs.condition||"Session terminated")),this.emit("disconnect"),this.emit("end"),this.emit("close"))},BOSHConnection.prototype.mayRequest=function(){if(this.sid&&(0===this.currentRequests||this.queue.length>0&&this.currentRequests<this.maxRequests)){var stanzas=this.queue;this.queue=[],this.rid++,this.request({},stanzas,function(err,bodyEl){err?(this.emit("error",err),this.emit("disconnect"),this.emit("end"),delete this.sid,this.emit("close")):(bodyEl&&this.processResponse(bodyEl),process.nextTick(this.mayRequest.bind(this)))}.bind(this))}},BOSHConnection.prototype.end=function(stanzas){typeof(stanzas=stanzas||[])!==Array&&(stanzas=[stanzas]),stanzas=this.queue.concat(stanzas),this.shutdown=!0,this.queue=[],this.rid++,this.request({type:"terminate"},stanzas,function(err,bodyEl){err||bodyEl&&this.processResponse(bodyEl),this.emit("disconnect"),this.emit("end"),delete this.sid,this.emit("close")}.bind(this))},BOSHConnection.prototype.maxHTTPRetries=5,BOSHConnection.prototype.request=function(attrs,children,cb,retry){var that=this;for(var k in retry=retry||0,attrs.rid=this.rid.toString(),this.sid&&(attrs.sid=this.sid),this.xmlnsAttrs)attrs[k]=this.xmlnsAttrs[k];for(var boshEl=new ltx.Element("body",attrs),i=0;i<children.length;i++)boshEl.cnode(children[i]);debug("send bosh request:"+boshEl.toString()),request({uri:this.boshURL,method:"POST",headers:{"Content-Type":this.contentType},body:boshEl.toString()},function(err,res,body){if(that.currentRequests--,err)return retry<that.maxHTTPRetries?that.request(attrs,children,cb,retry+1):cb(err);if(res.statusCode<200||res.statusCode>=400)return cb(new Error("HTTP status "+res.statusCode));var bodyEl;try{bodyEl=ltx.parse(body)}catch(e){return cb(e)}bodyEl&&"terminate"===bodyEl.attrs.type&&bodyEl.attrs.condition?cb(new Error(bodyEl.attrs.condition)):bodyEl?cb(null,bodyEl):cb(new Error("no <body/>"))}),this.currentRequests++},module.exports=BOSHConnection}).call(this)}).call(this,require("_process"))},{_process:89,debug:35,events:37,"node-xmpp-core":72,request:24}],69:[function(require,module,exports){"use strict";var Mechanism=require("./authentication/mechanism");function selectMechanism(offeredMechs,preferredMech,availableMech){var Mech,mechClasses=[],byName={};return Array.isArray(availableMech)&&(mechClasses=mechClasses.concat(availableMech)),mechClasses.forEach(function(mechClass){byName[mechClass.prototype.name]=mechClass}),byName[preferredMech]&&offeredMechs.indexOf(preferredMech)>=0&&(Mech=byName[preferredMech]),mechClasses.forEach(function(mechClass){!Mech&&offeredMechs.indexOf(mechClass.prototype.name)>=0&&(Mech=mechClass)}),Mech?new Mech:null}function detectMechanisms(options,availableMech){var detect=[];return(availableMech||[]).forEach(function(mechClass){(0,mechClass.prototype.match)(options)&&detect.push(mechClass)}),detect}exports.selectMechanism=selectMechanism,exports.detectMechanisms=detectMechanisms,exports.AbstractMechanism=Mechanism},{"./authentication/mechanism":65}],70:[function(require,module,exports){(function(process){(function(){"use strict";var tls=require("tls"),EventEmitter=require("events").EventEmitter,core=require("node-xmpp-core"),inherits=core.inherits,Connection=core.Connection,JID=core.JID,SRV=core.SRV,BOSHConnection=require("./bosh"),WSConnection=require("./websockets"),debug=require("debug")("xmpp:client:session");function Session(opts){EventEmitter.call(this),this.setOptions(opts),opts.websocket&&opts.websocket.url?(debug("start websocket connection"),this._setupWebsocketConnection(opts)):opts.bosh&&opts.bosh.url?(debug("start bosh connection"),this._setupBoshConnection(opts)):(debug("start socket connection"),this._setupSocketConnection(opts))}inherits(Session,EventEmitter),Session.prototype._setupSocketConnection=function(opts){var params={xmlns:{"":opts.xmlns},streamAttrs:{version:"1.0",to:this.jid.domain},serialized:opts.serialized};for(var key in opts)key in params||(params[key]=opts[key]);if(this.connection=new Connection(params),this._addConnectionListeners(),opts.host||opts.port)this._socketConnectionToHost(opts);else{if(!SRV)throw new Error("Cannot load SRV");this._performSrvLookup(opts)}},Session.prototype._socketConnectionToHost=function(opts){var _this=this;opts.legacySSL?(this.connection.allowTLS=!1,this.connection.connect({socket:function(){return tls.connect(opts.port||5223,opts.host||"localhost",opts.credentials||{},function(){this.socket.authorized?_this.emit("connect",this.socket):_this.emit("error","unauthorized")}.bind(this))}})):(opts.credentials&&(this.connection.credentials=tls.createSecureContext(opts.credentials)),opts.disallowTLS&&(this.connection.allowTLS=!1),this.connection.listen({socket:function(){process.nextTick(function(){this.socket.connect(opts.port||5222,opts.host)}.bind(this));var socket=opts.socket;return opts.socket=null,socket}}))},Session.prototype._performSrvLookup=function(opts){if(opts.legacySSL)throw new Error("LegacySSL mode does not support DNS lookups");opts.credentials&&(this.connection.credentials=tls.createSecureContext(opts.credentials)),opts.disallowTLS&&(this.connection.allowTLS=!1),this.connection.listen({socket:SRV.connect({socket:opts.socket,services:["_xmpp-client._tcp"],domain:this.jid.domain,defaultPort:5222})})},Session.prototype._setupBoshConnection=function(opts){this.connection=new BOSHConnection({jid:this.jid,bosh:opts.bosh}),this._addConnectionListeners(),this.connection.on("connected",function(){this.connection.startStream&&this.connection.startStream()}.bind(this))},Session.prototype._setupWebsocketConnection=function(opts){this.connection=new WSConnection({jid:this.jid,websocket:opts.websocket}),this._addConnectionListeners(),this.connection.on("connected",function(){this.connection.startStream&&this.connection.startStream()}.bind(this))},Session.prototype.setOptions=function(opts){this.jid="string"==typeof opts.jid?new JID(opts.jid):opts.jid,this.password=opts.password,this.preferredSaslMechanism=opts.preferredSaslMechanism,this.api_key=opts.api_key,this.access_token=opts.access_token,this.oauth2_token=opts.oauth2_token,this.oauth2_auth=opts.oauth2_auth,this.register=opts.register,"string"==typeof opts.actAs?this.actAs=new JID(opts.actAs):this.actAs=opts.actAs},Session.prototype._addConnectionListeners=function(con){(con=con||this.connection).on("stanza",this.onStanza.bind(this)),con.on("drain",this.emit.bind(this,"drain")),con.on("end",this.emit.bind(this,"end")),con.on("close",this.emit.bind(this,"close")),con.on("error",this.emit.bind(this,"error")),con.on("connect",this.emit.bind(this,"connect")),con.on("reconnect",this.emit.bind(this,"reconnect")),con.on("disconnect",this.emit.bind(this,"disconnect")),con.startStream&&(con.on("connect",function(){con.startStream()}),this.on("auth",function(){con.startStream()}))},Session.prototype.pause=function(){this.connection&&this.connection.pause&&this.connection.pause()},Session.prototype.resume=function(){this.connection&&this.connection.resume&&this.connection.resume()},Session.prototype.send=function(stanza){return!!this.connection&&this.connection.send(stanza)},Session.prototype.end=function(){this.connection&&this.connection.end()},Session.prototype.onStanza=function(){},module.exports=Session}).call(this)}).call(this,require("_process"))},{"./bosh":68,"./websockets":71,_process:89,debug:35,events:37,"node-xmpp-core":72,tls:26}],71:[function(require,module,exports){"use strict";var EventEmitter=require("events").EventEmitter,core=require("node-xmpp-core"),Element=core.Element,StreamParser=core.StreamParser,Connection=core.Connection,inherits=core.inherits,ws=require("ws"),WebSocket=ws.Server?ws:window.WebSocket,debug=require("debug")("xmpp:client:websocket"),NS_FRAMING="urn:ietf:params:xml:ns:xmpp-framing";function WSConnection(opts){EventEmitter.call(this),this.url=opts.websocket.url,this.jid=opts.jid,this.xmlns={"":NS_FRAMING},this.websocket=new WebSocket(this.url,["xmpp"],opts.websocket.options),this.websocket.onopen=this.onopen.bind(this),this.websocket.onmessage=this.onmessage.bind(this),this.websocket.onclose=this.onclose.bind(this),this.websocket.onerror=this.onerror.bind(this)}inherits(WSConnection,EventEmitter),WSConnection.prototype.maxStanzaSize=65535,WSConnection.prototype.xmppVersion="1.0",WSConnection.prototype.onopen=function(){this.startParser(),this.emit("connected")},WSConnection.prototype.startParser=function(){var self=this;this.parser=new StreamParser(this.maxStanzaSize),this.parser.on("start",function(attrs){for(var k in self.streamAttrs=attrs,self.streamNsAttrs={},attrs)"xmlns"!==k&&"xmlns:"!==k.substr(0,6)||(self.streamNsAttrs[k]=attrs[k]);self.emit("streamStart",attrs)}),this.parser.on("stanza",function(stanza){self.onStanza(stanza)}),this.parser.on("error",this.onerror.bind(this)),this.parser.on("end",function(){self.stopParser(),self.end()})},WSConnection.prototype.stopParser=function(){this.parser&&delete this.parser},WSConnection.prototype.onmessage=function(msg){debug("ws msg <--",msg.data),msg&&msg.data&&this.parser&&this.parser.write(msg.data)},WSConnection.prototype.onStanza=function(stanza){stanza.is("error",Connection.NS_STREAM)?this.emit("error",stanza):this.emit("stanza",stanza)},WSConnection.prototype.startStream=function(){var attrs={};for(var k in this.xmlns)this.xmlns.hasOwnProperty(k)&&(k?attrs["xmlns:"+k]=this.xmlns[k]:attrs.xmlns=this.xmlns[k]);this.xmppVersion&&(attrs.version=this.xmppVersion),this.streamTo&&(attrs.to=this.streamTo),this.jid&&(attrs.to=this.jid.domain),this.send(new Element("open",attrs)),this.streamOpened=!0},WSConnection.prototype.send=function(stanza){stanza.root&&(stanza=stanza.root()),!stanza.attrs.xmlns&&(stanza.is("iq")||stanza.is("presence")||stanza.is("message"))&&(stanza.attrs.xmlns="jabber:client"),stanza=stanza.toString(),debug("ws send --\x3e",stanza),this.websocket.send(stanza)},WSConnection.prototype.onclose=function(){this.emit("disconnect"),this.emit("close")},WSConnection.prototype.end=function(){this.send(new Element("close",{xmlns:NS_FRAMING})),this.emit("disconnect"),this.emit("end"),this.websocket&&this.websocket.close()},WSConnection.prototype.onerror=function(e){this.emit("error",e)},module.exports=WSConnection},{debug:35,events:37,"node-xmpp-core":72,ws:25}],72:[function(require,module,exports){"use strict";var Connection=require("./lib/Connection"),StreamParser=require("@xmpp/streamparser"),JID=require("@xmpp/jid"),xml=require("@xmpp/xml"),inherits=require("inherits");exports.SRV=require("./lib/SRV"),exports.exportCoreUtils=function(obj){obj.Connection=Connection,obj.StreamParser=StreamParser,obj.JID=JID,obj.inherits=inherits,obj.stanza=xml,obj.Stanza=xml.Stanza,obj.createStanza=xml.createStanza,obj.IQ=xml.IQ,obj.Presence=xml.Presence,obj.Message=xml.Message,obj.Parser=xml.Parser,obj.parse=xml.parse,obj.ltx=xml.ltx,obj.createElement=xml.createElement,obj.Element=xml.Element,obj.escapeXML=xml.escapeXML,obj.escapeXMLText=xml.escapeXMLText},exports.exportCoreUtils(exports)},{"./lib/Connection":73,"./lib/SRV":25,"@xmpp/jid":74,"@xmpp/streamparser":7,"@xmpp/xml":78,inherits:41}],73:[function(require,module,exports){"use strict";var net=require("net"),EventEmitter=require("events").EventEmitter,inherits=require("inherits"),Element=require("@xmpp/xml").Element,reconnect=require("reconnect-core"),StreamParser=require("@xmpp/streamparser"),starttls=require("node-xmpp-tls-connect"),debug=require("debug")("xmpp:connection"),assign=require("lodash.assign"),NS_XMPP_TLS="urn:ietf:params:xml:ns:xmpp-tls",NS_STREAM="http://etherx.jabber.org/streams",NS_XMPP_STREAMS="urn:ietf:params:xml:ns:xmpp-streams",INITIAL_RECONNECT_DELAY=1e3,MAX_RECONNECT_DELAY=3e4,STREAM_OPEN="stream:stream",STREAM_CLOSE="</stream:stream>";function defaultInjection(emitter,opts){var options=assign({},opts);return options.initialDelay=opts&&(opts.initialReconnectDelay||opts.reconnectDelay)||INITIAL_RECONNECT_DELAY,options.maxDelay=opts&&opts.maxReconnectDelay||MAX_RECONNECT_DELAY,options.immediate=opts&&opts.socket&&"function"!=typeof opts.socket,options.type=opts&&opts.delayType,options.emitter=emitter,options}function Connection(opts){EventEmitter.call(this),this.streamAttrs=opts&&opts.streamAttrs||{},this.xmlns=opts&&opts.xmlns||{},this.xmlns.stream=NS_STREAM,this.streamOpen=opts&&opts.streamOpen||STREAM_OPEN,this.streamClose=opts&&opts.streamClose||STREAM_CLOSE,this.rejectUnauthorized=!(!opts||!opts.rejectUnauthorized),this.serialized=!(!opts||!opts.serialized),this.requestCert=!(!opts||!opts.requestCert),this.servername=opts&&opts.servername,this.boundOnData=this.onData.bind(this),this.boundOnClose=this.onClose.bind(this),this.boundEmitData=this.emit.bind(this,"data"),this.boundEmitDrain=this.emit.bind(this,"drain"),this._setupSocket(defaultInjection(this,opts)),this.once("reconnect",function(){this.reconnect=opts&&opts.reconnect})}function getAllText(el){return el.children?el.children.reduce(function(text,child){return text+getAllText(child)},""):el}inherits(Connection,EventEmitter),Connection.prototype.NS_XMPP_TLS=NS_XMPP_TLS,Connection.NS_STREAM=NS_STREAM,Connection.prototype.NS_XMPP_STREAMS=NS_XMPP_STREAMS,Connection.prototype.allowTLS=!0,Connection.prototype._setupSocket=function(options){debug("setup socket");var previousOptions={},inject=reconnect(function(opts){var previousSocket=this.socket;return"on"===opts.preserve?(opts.preserve=previousOptions,previousOptions=opts):opts=previousOptions=opts.preserve?opts.preserve:opts||previousOptions,"function"==typeof opts.socket?(debug("use lazy socket"),this.socket=opts.socket.call(this)):(debug("use standard socket"),this.socket=opts.socket,opts.socket=null,this.socket&&this.once("connect",function(){inject.options.immediate=!1})),this.socket=this.socket||new net.Socket,previousSocket!==this.socket&&this.setupStream(),this.socket}.bind(this));inject(inject.options=options);var end=this.end;this.end=this.disconnect=function(){this.closeStream(),end()},this.on("connection",function(){this.parser||this.startParser()}),this.on("end",function(){previousOptions={}})},Connection.prototype.setupStream=function(){debug("setup stream"),this.socket.on("end",this.onEnd.bind(this)),this.socket.on("data",this.boundOnData),this.socket.on("close",this.boundOnClose),this.socket.on("data",this.boundEmitData),this.socket.on("drain",this.boundEmitDrain),this.socket.on("error",function(){}),this.socket.serializeStanza||(this.serialized?this.socket.serializeStanza=function(el,cb){el.write(function(s){cb(s)})}:this.socket.serializeStanza=function(el,cb){cb(el.toString())})},Connection.prototype.pause=function(){this.socket.pause&&this.socket.pause()},Connection.prototype.resume=function(){this.socket.resume&&this.socket.resume()},Connection.prototype.send=function(stanza){if(this.socket&&this.streamOpened){if(this.socket.writable){debug("send: "+stanza.toString());var flushed=!0;if(stanza.root){var el=this.rmXmlns(stanza.root());this.socket.serializeStanza(el,function(s){flushed=this.write(s)}.bind(this.socket))}else flushed=this.socket.write(stanza);return flushed}this.socket.end()}},Connection.prototype.startParser=function(){var self=this;this.parser=new StreamParser(this.maxStanzaSize),this.parser.on("streamStart",function(attrs){for(var k in self.streamNsAttrs={},attrs)"xmlns"!==k&&"xmlns:"!==k.substr(0,6)||(self.streamNsAttrs[k]=attrs[k]);self.emit("streamStart",attrs)}),this.parser.on("stanza",function(stanza){self.onStanza(self.addStreamNs(stanza))}),this.parser.on("error",function(e){self.error(e.condition||"internal-server-error",e.message)}),this.parser.once("end",function(){self.stopParser(),self.reconnect?self.once("reconnect",self.startParser.bind(self)):self.end()})},Connection.prototype.stopParser=function(){if(this.parser){var parser=this.parser;this.parser=null,parser.end()}},Connection.prototype.openStream=function(){var attrs={};for(var k in this.xmlns)this.xmlns.hasOwnProperty(k)&&(k?attrs["xmlns:"+k]=this.xmlns[k]:attrs.xmlns=this.xmlns[k]);for(k in this.streamAttrs)this.streamAttrs.hasOwnProperty(k)&&(attrs[k]=this.streamAttrs[k]);this.streamTo&&(attrs.to=this.streamTo);var streamOpen,el=new Element(this.streamOpen,attrs);if("stream:stream"===el.name){el.t(" ");var s=el.toString();streamOpen=s.substr(0,s.indexOf(" </stream:stream>"))}else streamOpen=el.toString();this.streamOpened=!0,this.send(streamOpen)},Connection.prototype.startStream=Connection.prototype.openStream,Connection.prototype.closeStream=function(){this.send(this.streamClose),this.streamOpened=!1},Connection.prototype.endStream=Connection.prototype.closeStream,Connection.prototype.onData=function(data){debug("receive: "+data.toString("utf8")),this.parser&&this.parser.write(data)},Connection.prototype.setSecure=function(credentials,isServer,servername){this.socket.removeListener("data",this.boundOnData),this.socket.removeListener("data",this.boundEmitData),this.socket.removeListener("drain",this.boundEmitDrain),this.socket.removeListener("close",this.boundOnClose),this.socket.clearTimer&&this.socket.clearTimer();var cleartext=starttls({socket:this.socket,rejectUnauthorized:this.rejectUnauthorized,credentials:credentials||this.credentials,requestCert:this.requestCert,isServer:!!isServer,servername:isServer&&servername},function(){this.isSecure=!0,this.once("disconnect",function(){this.isSecure=!1}),cleartext.emit("connect",cleartext)}.bind(this));cleartext.on("clientError",this.emit.bind(this,"error")),this.reconnect||(this.reconnect=!0,this.once("reconnect",function(){this.reconnect=!1})),this.stopParser(),this.listen({socket:cleartext,preserve:"on"})},Connection.prototype.onStanza=function(stanza){if(stanza.is("error",NS_STREAM)){var error=new Error(""+getAllText(stanza));error.stanza=stanza,this.socket.emit("error",error)}else stanza.is("features",this.NS_STREAM)&&this.allowTLS&&!this.isSecure&&stanza.getChild("starttls",this.NS_XMPP_TLS)?this.send(new Element("starttls",{xmlns:this.NS_XMPP_TLS})):this.allowTLS&&stanza.is("proceed",this.NS_XMPP_TLS)?this.setSecure():this.emit("stanza",stanza)},Connection.prototype.addStreamNs=function(stanza){for(var attr in this.streamNsAttrs)stanza.attrs[attr]||"xmlns"===attr&&this.streamNsAttrs[attr]===this.xmlns[""]||(stanza.attrs[attr]=this.streamNsAttrs[attr]);return stanza},Connection.prototype.rmXmlns=function(stanza){for(var prefix in this.xmlns){var attr=prefix?"xmlns:"+prefix:"xmlns";stanza.attrs[attr]===this.xmlns[prefix]&&(stanza.attrs[attr]=null)}return stanza},Connection.prototype.onEnd=function(){this.closeStream(),this.reconnect||this.emit("end")},Connection.prototype.onClose=function(){this.reconnect||this.emit("close")},Connection.prototype.error=function(condition,message){if(this.emit("error",new Error(message)),this.socket&&this.socket.writable){this.streamOpened||this.openStream();var error=new Element("stream:error");error.c(condition,{xmlns:NS_XMPP_STREAMS}),message&&error.c("text",{xmlns:NS_XMPP_STREAMS,"xml:lang":"en"}).t(message),this.send(error),this.end()}},module.exports=Connection},{"@xmpp/streamparser":7,"@xmpp/xml":78,debug:35,events:37,inherits:41,"lodash.assign":43,net:26,"node-xmpp-tls-connect":25,"reconnect-core":105}],74:[function(require,module,exports){"use strict";var JID=require("./lib/JID"),tag=require("./lib/tag");module.exports=function createJID(a,b,c){return Array.isArray(a)?tag.apply(null,arguments):new JID(a,b,c)},module.exports.JID=JID,module.exports.tag=tag,module.exports.equal=function(a,b){return a.equals(b)},module.exports.is=function(a){return a instanceof JID}},{"./lib/JID":75,"./lib/tag":77}],75:[function(require,module,exports){"use strict";var escaping=require("./escaping");function JID(a,b,c){if(this._local=null,this.user=null,this._domain=null,this._resource=null,!a||b||c){if(!b)throw new Error("Argument error");this.setLocal(a),this.setDomain(b),this.setResource(c)}else this.parseJID(a)}JID.prototype.parseJID=function(s){var resourceStart=s.indexOf("/");-1!==resourceStart&&(this.setResource(s.substr(resourceStart+1)),s=s.substr(0,resourceStart));var atStart=s.indexOf("@");-1!==atStart&&(this.setLocal(s.substr(0,atStart)),s=s.substr(atStart+1)),this.setDomain(s)},JID.prototype.toString=function(unescape){var s=this._domain;return this._local&&(s=this.getLocal(unescape)+"@"+s),this._resource&&(s=s+"/"+this._resource),s},JID.prototype.bare=function(){return this._resource?new JID(this._local,this._domain,null):this},JID.prototype.equals=function(other){return this._local===other._local&&this._domain===other._domain&&this._resource===other._resource},JID.prototype.setLocal=function(local,escape){return(escape=escape||escaping.detect(local))&&(local=escaping.escape(local)),this._local=local&&local.toLowerCase(),this.user=this._local,this},JID.prototype.setUser=function(){console.log("JID.setUser: Use JID.setLocal instead"),this.setLocal.apply(this,arguments)},JID.prototype.getUser=function(){return console.log("JID.getUser: Use JID.getLocal instead"),this.getLocal.apply(this,arguments)},JID.prototype.getLocal=function(unescape){return(unescape=unescape||!1)?escaping.unescape(this._local):this._local},Object.defineProperty(JID.prototype,"local",{get:JID.prototype.getLocal,set:JID.prototype.setLocal}),JID.prototype.setDomain=function(domain){return this._domain=domain.toLowerCase(),this},JID.prototype.getDomain=function(){return this._domain},Object.defineProperty(JID.prototype,"domain",{get:JID.prototype.getDomain,set:JID.prototype.setDomain}),JID.prototype.setResource=function(resource){return this._resource=resource,this},JID.prototype.getResource=function(){return this._resource},Object.defineProperty(JID.prototype,"resource",{get:JID.prototype.getResource,set:JID.prototype.setResource}),JID.prototype.detectEscape=escaping.detectEscape,JID.prototype.escapeLocal=escaping.escape,JID.prototype.unescapeLocal=escaping.unescape,module.exports=JID},{"./escaping":76}],76:[function(require,module,exports){"use strict";module.exports.detect=function(local){return!!local&&-1!==local.replace(/\\20/g,"").replace(/\\22/g,"").replace(/\\26/g,"").replace(/\\27/g,"").replace(/\\2f/g,"").replace(/\\3a/g,"").replace(/\\3c/g,"").replace(/\\3e/g,"").replace(/\\40/g,"").replace(/\\5c/g,"").search(/\\| |"|&|'|\/|:|<|>|@/g)},module.exports.escape=function(local){return null===local?null:local.replace(/^\s+|\s+$/g,"").replace(/\\/g,"\\5c").replace(/ /g,"\\20").replace(/"/g,"\\22").replace(/&/g,"\\26").replace(/'/g,"\\27").replace(/\//g,"\\2f").replace(/:/g,"\\3a").replace(/</g,"\\3c").replace(/>/g,"\\3e").replace(/@/g,"\\40").replace(/\3a/g,"c3a")},module.exports.unescape=function(local){return null===local?null:local.replace(/\\20/g," ").replace(/\\22/g,'"').replace(/\\26/g,"&").replace(/\\27/g,"'").replace(/\\2f/g,"/").replace(/\\3a/g,":").replace(/\\3c/g,"<").replace(/\\3e/g,">").replace(/\\40/g,"@").replace(/\\5c/g,"\\")}},{}],77:[function(require,module,exports){"use strict";var JID=require("./JID");module.exports=function tag(){for(var literals=arguments[0],substitutions=Array.prototype.slice.call(arguments,1),str="",i=0;i<substitutions.length;i++)str+=literals[i],str+=substitutions[i];return str+=literals[literals.length-1],new JID(str)}},{"./JID":75}],78:[function(require,module,exports){arguments[4][8][0].apply(exports,arguments)},{"./lib/IQ":79,"./lib/Message":80,"./lib/Parser":81,"./lib/Presence":82,"./lib/Stanza":83,"./lib/createStanza":84,"./lib/parse":85,"./lib/tag":86,dup:8,ltx:44}],79:[function(require,module,exports){arguments[4][9][0].apply(exports,arguments)},{"./Stanza":83,dup:9,inherits:41}],80:[function(require,module,exports){arguments[4][10][0].apply(exports,arguments)},{"./Stanza":83,dup:10,inherits:41}],81:[function(require,module,exports){arguments[4][11][0].apply(exports,arguments)},{"./createStanza":84,dup:11,inherits:41,ltx:44}],82:[function(require,module,exports){arguments[4][12][0].apply(exports,arguments)},{"./Stanza":83,dup:12,inherits:41}],83:[function(require,module,exports){arguments[4][13][0].apply(exports,arguments)},{dup:13,inherits:41,ltx:44}],84:[function(require,module,exports){arguments[4][14][0].apply(exports,arguments)},{"./Stanza":83,dup:14,ltx:44}],85:[function(require,module,exports){arguments[4][15][0].apply(exports,arguments)},{"./Parser":81,dup:15,ltx:44}],86:[function(require,module,exports){arguments[4][16][0].apply(exports,arguments)},{"./parse":85,dup:16,ltx:44}],87:[function(require,module,exports){exports.endianness=function(){return"LE"},exports.hostname=function(){return"undefined"!=typeof location?location.hostname:""},exports.loadavg=function(){return[]},exports.uptime=function(){return 0},exports.freemem=function(){return Number.MAX_VALUE},exports.totalmem=function(){return Number.MAX_VALUE},exports.cpus=function(){return[]},exports.type=function(){return"Browser"},exports.release=function(){return"undefined"!=typeof navigator?navigator.appVersion:""},exports.networkInterfaces=exports.getNetworkInterfaces=function(){return{}},exports.arch=function(){return"javascript"},exports.platform=function(){return"browser"},exports.tmpdir=exports.tmpDir=function(){return"/tmp"},exports.EOL="\n"},{}],88:[function(require,module,exports){(function(process){(function(){"use strict";function nextTick(fn,arg1,arg2,arg3){if("function"!=typeof fn)throw new TypeError('"callback" argument must be a function');var args,i,len=arguments.length;switch(len){case 0:case 1:return process.nextTick(fn);case 2:return process.nextTick(function afterTickOne(){fn.call(null,arg1)});case 3:return process.nextTick(function afterTickTwo(){fn.call(null,arg1,arg2)});case 4:return process.nextTick(function afterTickThree(){fn.call(null,arg1,arg2,arg3)});default:for(args=new Array(len-1),i=0;i<args.length;)args[i++]=arguments[i];return process.nextTick(function afterTick(){fn.apply(null,args)})}}void 0===process||!process.version||0===process.version.indexOf("v0.")||0===process.version.indexOf("v1.")&&0!==process.version.indexOf("v1.8.")?module.exports={nextTick}:module.exports=process}).call(this)}).call(this,require("_process"))},{_process:89}],89:[function(require,module,exports){var cachedSetTimeout,cachedClearTimeout,process=module.exports={};function defaultSetTimout(){throw new Error("setTimeout has not been defined")}function defaultClearTimeout(){throw new Error("clearTimeout has not been defined")}function runTimeout(fun){if(cachedSetTimeout===setTimeout)return setTimeout(fun,0);if((cachedSetTimeout===defaultSetTimout||!cachedSetTimeout)&&setTimeout)return cachedSetTimeout=setTimeout,setTimeout(fun,0);try{return cachedSetTimeout(fun,0)}catch(e){try{return cachedSetTimeout.call(null,fun,0)}catch(e){return cachedSetTimeout.call(this,fun,0)}}}function runClearTimeout(marker){if(cachedClearTimeout===clearTimeout)return clearTimeout(marker);if((cachedClearTimeout===defaultClearTimeout||!cachedClearTimeout)&&clearTimeout)return cachedClearTimeout=clearTimeout,clearTimeout(marker);try{return cachedClearTimeout(marker)}catch(e){try{return cachedClearTimeout.call(null,marker)}catch(e){return cachedClearTimeout.call(this,marker)}}}!function(){try{cachedSetTimeout="function"==typeof setTimeout?setTimeout:defaultSetTimout}catch(e){cachedSetTimeout=defaultSetTimout}try{cachedClearTimeout="function"==typeof clearTimeout?clearTimeout:defaultClearTimeout}catch(e){cachedClearTimeout=defaultClearTimeout}}();var currentQueue,queue=[],draining=!1,queueIndex=-1;function cleanUpNextTick(){draining&&currentQueue&&(draining=!1,currentQueue.length?queue=currentQueue.concat(queue):queueIndex=-1,queue.length&&drainQueue())}function drainQueue(){if(!draining){var timeout=runTimeout(cleanUpNextTick);draining=!0;for(var len=queue.length;len;){for(currentQueue=queue,queue=[];++queueIndex<len;)currentQueue&&currentQueue[queueIndex].run();queueIndex=-1,len=queue.length}currentQueue=null,draining=!1,runClearTimeout(timeout)}}function Item(fun,array){this.fun=fun,this.array=array}function noop(){}process.nextTick=function(fun){var args=new Array(arguments.length-1);if(arguments.length>1)for(var i=1;i<arguments.length;i++)args[i-1]=arguments[i];queue.push(new Item(fun,args)),1!==queue.length||draining||runTimeout(drainQueue)},Item.prototype.run=function(){this.fun.apply(null,this.array)},process.title="browser",process.browser=!0,process.env={},process.argv=[],process.version="",process.versions={},process.on=noop,process.addListener=noop,process.once=noop,process.off=noop,process.removeListener=noop,process.removeAllListeners=noop,process.emit=noop,process.prependListener=noop,process.prependOnceListener=noop,process.listeners=function(name){return[]},process.binding=function(name){throw new Error("process.binding is not supported")},process.cwd=function(){return"/"},process.chdir=function(dir){throw new Error("process.chdir is not supported")},process.umask=function(){return 0}},{}],90:[function(require,module,exports){module.exports=require("./lib/_stream_duplex.js")},{"./lib/_stream_duplex.js":91}],91:[function(require,module,exports){"use strict";var pna=require("process-nextick-args"),objectKeys=Object.keys||function(obj){var keys=[];for(var key in obj)keys.push(key);return keys};module.exports=Duplex;var util=Object.create(require("core-util-is"));util.inherits=require("inherits");var Readable=require("./_stream_readable"),Writable=require("./_stream_writable");util.inherits(Duplex,Readable);for(var keys=objectKeys(Writable.prototype),v=0;v<keys.length;v++){var method=keys[v];Duplex.prototype[method]||(Duplex.prototype[method]=Writable.prototype[method])}function Duplex(options){if(!(this instanceof Duplex))return new Duplex(options);Readable.call(this,options),Writable.call(this,options),options&&!1===options.readable&&(this.readable=!1),options&&!1===options.writable&&(this.writable=!1),this.allowHalfOpen=!0,options&&!1===options.allowHalfOpen&&(this.allowHalfOpen=!1),this.once("end",onend)}function onend(){this.allowHalfOpen||this._writableState.ended||pna.nextTick(onEndNT,this)}function onEndNT(self){self.end()}Object.defineProperty(Duplex.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),Object.defineProperty(Duplex.prototype,"destroyed",{get:function(){return void 0!==this._readableState&&void 0!==this._writableState&&this._readableState.destroyed&&this._writableState.destroyed},set:function(value){void 0!==this._readableState&&void 0!==this._writableState&&(this._readableState.destroyed=value,this._writableState.destroyed=value)}}),Duplex.prototype._destroy=function(err,cb){this.push(null),this.end(),pna.nextTick(cb,err)}},{"./_stream_readable":93,"./_stream_writable":95,"core-util-is":28,inherits:41,"process-nextick-args":88}],92:[function(require,module,exports){"use strict";module.exports=PassThrough;var Transform=require("./_stream_transform"),util=Object.create(require("core-util-is"));function PassThrough(options){if(!(this instanceof PassThrough))return new PassThrough(options);Transform.call(this,options)}util.inherits=require("inherits"),util.inherits(PassThrough,Transform),PassThrough.prototype._transform=function(chunk,encoding,cb){cb(null,chunk)}},{"./_stream_transform":94,"core-util-is":28,inherits:41}],93:[function(require,module,exports){(function(process,global){(function(){"use strict";var pna=require("process-nextick-args");module.exports=Readable;var Duplex,isArray=require("isarray");Readable.ReadableState=ReadableState,require("events").EventEmitter;var EElistenerCount=function(emitter,type){return emitter.listeners(type).length},Stream=require("./internal/streams/stream"),Buffer=require("safe-buffer").Buffer,OurUint8Array=(void 0!==global?global:"undefined"!=typeof window?window:"undefined"!=typeof self?self:{}).Uint8Array||function(){};function _uint8ArrayToBuffer(chunk){return Buffer.from(chunk)}function _isUint8Array(obj){return Buffer.isBuffer(obj)||obj instanceof OurUint8Array}var util=Object.create(require("core-util-is"));util.inherits=require("inherits");var debugUtil=require("util"),debug=void 0;debug=debugUtil&&debugUtil.debuglog?debugUtil.debuglog("stream"):function(){};var StringDecoder,BufferList=require("./internal/streams/BufferList"),destroyImpl=require("./internal/streams/destroy");util.inherits(Readable,Stream);var kProxyEvents=["error","close","destroy","pause","resume"];function prependListener(emitter,event,fn){if("function"==typeof emitter.prependListener)return emitter.prependListener(event,fn);emitter._events&&emitter._events[event]?isArray(emitter._events[event])?emitter._events[event].unshift(fn):emitter._events[event]=[fn,emitter._events[event]]:emitter.on(event,fn)}function ReadableState(options,stream){options=options||{};var isDuplex=stream instanceof(Duplex=Duplex||require("./_stream_duplex"));this.objectMode=!!options.objectMode,isDuplex&&(this.objectMode=this.objectMode||!!options.readableObjectMode);var hwm=options.highWaterMark,readableHwm=options.readableHighWaterMark,defaultHwm=this.objectMode?16:16384;this.highWaterMark=hwm||0===hwm?hwm:isDuplex&&(readableHwm||0===readableHwm)?readableHwm:defaultHwm,this.highWaterMark=Math.floor(this.highWaterMark),this.buffer=new BufferList,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.destroyed=!1,this.defaultEncoding=options.defaultEncoding||"utf8",this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,options.encoding&&(StringDecoder||(StringDecoder=require("string_decoder/").StringDecoder),this.decoder=new StringDecoder(options.encoding),this.encoding=options.encoding)}function Readable(options){if(Duplex=Duplex||require("./_stream_duplex"),!(this instanceof Readable))return new Readable(options);this._readableState=new ReadableState(options,this),this.readable=!0,options&&("function"==typeof options.read&&(this._read=options.read),"function"==typeof options.destroy&&(this._destroy=options.destroy)),Stream.call(this)}function readableAddChunk(stream,chunk,encoding,addToFront,skipChunkCheck){var er,state=stream._readableState;return null===chunk?(state.reading=!1,onEofChunk(stream,state)):(skipChunkCheck||(er=chunkInvalid(state,chunk)),er?stream.emit("error",er):state.objectMode||chunk&&chunk.length>0?("string"==typeof chunk||state.objectMode||Object.getPrototypeOf(chunk)===Buffer.prototype||(chunk=_uint8ArrayToBuffer(chunk)),addToFront?state.endEmitted?stream.emit("error",new Error("stream.unshift() after end event")):addChunk(stream,state,chunk,!0):state.ended?stream.emit("error",new Error("stream.push() after EOF")):(state.reading=!1,state.decoder&&!encoding?(chunk=state.decoder.write(chunk),state.objectMode||0!==chunk.length?addChunk(stream,state,chunk,!1):maybeReadMore(stream,state)):addChunk(stream,state,chunk,!1))):addToFront||(state.reading=!1)),needMoreData(state)}function addChunk(stream,state,chunk,addToFront){state.flowing&&0===state.length&&!state.sync?(stream.emit("data",chunk),stream.read(0)):(state.length+=state.objectMode?1:chunk.length,addToFront?state.buffer.unshift(chunk):state.buffer.push(chunk),state.needReadable&&emitReadable(stream)),maybeReadMore(stream,state)}function chunkInvalid(state,chunk){var er;return _isUint8Array(chunk)||"string"==typeof chunk||void 0===chunk||state.objectMode||(er=new TypeError("Invalid non-string/buffer chunk")),er}function needMoreData(state){return!state.ended&&(state.needReadable||state.length<state.highWaterMark||0===state.length)}Object.defineProperty(Readable.prototype,"destroyed",{get:function(){return void 0!==this._readableState&&this._readableState.destroyed},set:function(value){this._readableState&&(this._readableState.destroyed=value)}}),Readable.prototype.destroy=destroyImpl.destroy,Readable.prototype._undestroy=destroyImpl.undestroy,Readable.prototype._destroy=function(err,cb){this.push(null),cb(err)},Readable.prototype.push=function(chunk,encoding){var skipChunkCheck,state=this._readableState;return state.objectMode?skipChunkCheck=!0:"string"==typeof chunk&&((encoding=encoding||state.defaultEncoding)!==state.encoding&&(chunk=Buffer.from(chunk,encoding),encoding=""),skipChunkCheck=!0),readableAddChunk(this,chunk,encoding,!1,skipChunkCheck)},Readable.prototype.unshift=function(chunk){return readableAddChunk(this,chunk,null,!0,!1)},Readable.prototype.isPaused=function(){return!1===this._readableState.flowing},Readable.prototype.setEncoding=function(enc){return StringDecoder||(StringDecoder=require("string_decoder/").StringDecoder),this._readableState.decoder=new StringDecoder(enc),this._readableState.encoding=enc,this};var MAX_HWM=8388608;function computeNewHighWaterMark(n){return n>=MAX_HWM?n=MAX_HWM:(n--,n|=n>>>1,n|=n>>>2,n|=n>>>4,n|=n>>>8,n|=n>>>16,n++),n}function howMuchToRead(n,state){return n<=0||0===state.length&&state.ended?0:state.objectMode?1:n!=n?state.flowing&&state.length?state.buffer.head.data.length:state.length:(n>state.highWaterMark&&(state.highWaterMark=computeNewHighWaterMark(n)),n<=state.length?n:state.ended?state.length:(state.needReadable=!0,0))}function onEofChunk(stream,state){if(!state.ended){if(state.decoder){var chunk=state.decoder.end();chunk&&chunk.length&&(state.buffer.push(chunk),state.length+=state.objectMode?1:chunk.length)}state.ended=!0,emitReadable(stream)}}function emitReadable(stream){var state=stream._readableState;state.needReadable=!1,state.emittedReadable||(debug("emitReadable",state.flowing),state.emittedReadable=!0,state.sync?pna.nextTick(emitReadable_,stream):emitReadable_(stream))}function emitReadable_(stream){debug("emit readable"),stream.emit("readable"),flow(stream)}function maybeReadMore(stream,state){state.readingMore||(state.readingMore=!0,pna.nextTick(maybeReadMore_,stream,state))}function maybeReadMore_(stream,state){for(var len=state.length;!state.reading&&!state.flowing&&!state.ended&&state.length<state.highWaterMark&&(debug("maybeReadMore read 0"),stream.read(0),len!==state.length);)len=state.length;state.readingMore=!1}function pipeOnDrain(src){return function(){var state=src._readableState;debug("pipeOnDrain",state.awaitDrain),state.awaitDrain&&state.awaitDrain--,0===state.awaitDrain&&EElistenerCount(src,"data")&&(state.flowing=!0,flow(src))}}function nReadingNextTick(self){debug("readable nexttick read 0"),self.read(0)}function resume(stream,state){state.resumeScheduled||(state.resumeScheduled=!0,pna.nextTick(resume_,stream,state))}function resume_(stream,state){state.reading||(debug("resume read 0"),stream.read(0)),state.resumeScheduled=!1,state.awaitDrain=0,stream.emit("resume"),flow(stream),state.flowing&&!state.reading&&stream.read(0)}function flow(stream){var state=stream._readableState;for(debug("flow",state.flowing);state.flowing&&null!==stream.read(););}function fromList(n,state){return 0===state.length?null:(state.objectMode?ret=state.buffer.shift():!n||n>=state.length?(ret=state.decoder?state.buffer.join(""):1===state.buffer.length?state.buffer.head.data:state.buffer.concat(state.length),state.buffer.clear()):ret=fromListPartial(n,state.buffer,state.decoder),ret);var ret}function fromListPartial(n,list,hasStrings){var ret;return n<list.head.data.length?(ret=list.head.data.slice(0,n),list.head.data=list.head.data.slice(n)):ret=n===list.head.data.length?list.shift():hasStrings?copyFromBufferString(n,list):copyFromBuffer(n,list),ret}function copyFromBufferString(n,list){var p=list.head,c=1,ret=p.data;for(n-=ret.length;p=p.next;){var str=p.data,nb=n>str.length?str.length:n;if(nb===str.length?ret+=str:ret+=str.slice(0,n),0===(n-=nb)){nb===str.length?(++c,p.next?list.head=p.next:list.head=list.tail=null):(list.head=p,p.data=str.slice(nb));break}++c}return list.length-=c,ret}function copyFromBuffer(n,list){var ret=Buffer.allocUnsafe(n),p=list.head,c=1;for(p.data.copy(ret),n-=p.data.length;p=p.next;){var buf=p.data,nb=n>buf.length?buf.length:n;if(buf.copy(ret,ret.length-n,0,nb),0===(n-=nb)){nb===buf.length?(++c,p.next?list.head=p.next:list.head=list.tail=null):(list.head=p,p.data=buf.slice(nb));break}++c}return list.length-=c,ret}function endReadable(stream){var state=stream._readableState;if(state.length>0)throw new Error('"endReadable()" called on non-empty stream');state.endEmitted||(state.ended=!0,pna.nextTick(endReadableNT,state,stream))}function endReadableNT(state,stream){state.endEmitted||0!==state.length||(state.endEmitted=!0,stream.readable=!1,stream.emit("end"))}function indexOf(xs,x){for(var i=0,l=xs.length;i<l;i++)if(xs[i]===x)return i;return-1}Readable.prototype.read=function(n){debug("read",n),n=parseInt(n,10);var state=this._readableState,nOrig=n;if(0!==n&&(state.emittedReadable=!1),0===n&&state.needReadable&&(state.length>=state.highWaterMark||state.ended))return debug("read: emitReadable",state.length,state.ended),0===state.length&&state.ended?endReadable(this):emitReadable(this),null;if(0===(n=howMuchToRead(n,state))&&state.ended)return 0===state.length&&endReadable(this),null;var ret,doRead=state.needReadable;return debug("need readable",doRead),(0===state.length||state.length-n<state.highWaterMark)&&debug("length less than watermark",doRead=!0),state.ended||state.reading?debug("reading or ended",doRead=!1):doRead&&(debug("do read"),state.reading=!0,state.sync=!0,0===state.length&&(state.needReadable=!0),this._read(state.highWaterMark),state.sync=!1,state.reading||(n=howMuchToRead(nOrig,state))),null===(ret=n>0?fromList(n,state):null)?(state.needReadable=!0,n=0):state.length-=n,0===state.length&&(state.ended||(state.needReadable=!0),nOrig!==n&&state.ended&&endReadable(this)),null!==ret&&this.emit("data",ret),ret},Readable.prototype._read=function(n){this.emit("error",new Error("_read() is not implemented"))},Readable.prototype.pipe=function(dest,pipeOpts){var src=this,state=this._readableState;switch(state.pipesCount){case 0:state.pipes=dest;break;case 1:state.pipes=[state.pipes,dest];break;default:state.pipes.push(dest)}state.pipesCount+=1,debug("pipe count=%d opts=%j",state.pipesCount,pipeOpts);var endFn=pipeOpts&&!1===pipeOpts.end||dest===process.stdout||dest===process.stderr?unpipe:onend;function onunpipe(readable,unpipeInfo){debug("onunpipe"),readable===src&&unpipeInfo&&!1===unpipeInfo.hasUnpiped&&(unpipeInfo.hasUnpiped=!0,cleanup())}function onend(){debug("onend"),dest.end()}state.endEmitted?pna.nextTick(endFn):src.once("end",endFn),dest.on("unpipe",onunpipe);var ondrain=pipeOnDrain(src);dest.on("drain",ondrain);var cleanedUp=!1;function cleanup(){debug("cleanup"),dest.removeListener("close",onclose),dest.removeListener("finish",onfinish),dest.removeListener("drain",ondrain),dest.removeListener("error",onerror),dest.removeListener("unpipe",onunpipe),src.removeListener("end",onend),src.removeListener("end",unpipe),src.removeListener("data",ondata),cleanedUp=!0,!state.awaitDrain||dest._writableState&&!dest._writableState.needDrain||ondrain()}var increasedAwaitDrain=!1;function ondata(chunk){debug("ondata"),increasedAwaitDrain=!1,!1!==dest.write(chunk)||increasedAwaitDrain||((1===state.pipesCount&&state.pipes===dest||state.pipesCount>1&&-1!==indexOf(state.pipes,dest))&&!cleanedUp&&(debug("false write response, pause",state.awaitDrain),state.awaitDrain++,increasedAwaitDrain=!0),src.pause())}function onerror(er){debug("onerror",er),unpipe(),dest.removeListener("error",onerror),0===EElistenerCount(dest,"error")&&dest.emit("error",er)}function onclose(){dest.removeListener("finish",onfinish),unpipe()}function onfinish(){debug("onfinish"),dest.removeListener("close",onclose),unpipe()}function unpipe(){debug("unpipe"),src.unpipe(dest)}return src.on("data",ondata),prependListener(dest,"error",onerror),dest.once("close",onclose),dest.once("finish",onfinish),dest.emit("pipe",src),state.flowing||(debug("pipe resume"),src.resume()),dest},Readable.prototype.unpipe=function(dest){var state=this._readableState,unpipeInfo={hasUnpiped:!1};if(0===state.pipesCount)return this;if(1===state.pipesCount)return dest&&dest!==state.pipes||(dest||(dest=state.pipes),state.pipes=null,state.pipesCount=0,state.flowing=!1,dest&&dest.emit("unpipe",this,unpipeInfo)),this;if(!dest){var dests=state.pipes,len=state.pipesCount;state.pipes=null,state.pipesCount=0,state.flowing=!1;for(var i=0;i<len;i++)dests[i].emit("unpipe",this,{hasUnpiped:!1});return this}var index=indexOf(state.pipes,dest);return-1===index||(state.pipes.splice(index,1),state.pipesCount-=1,1===state.pipesCount&&(state.pipes=state.pipes[0]),dest.emit("unpipe",this,unpipeInfo)),this},Readable.prototype.on=function(ev,fn){var res=Stream.prototype.on.call(this,ev,fn);if("data"===ev)!1!==this._readableState.flowing&&this.resume();else if("readable"===ev){var state=this._readableState;state.endEmitted||state.readableListening||(state.readableListening=state.needReadable=!0,state.emittedReadable=!1,state.reading?state.length&&emitReadable(this):pna.nextTick(nReadingNextTick,this))}return res},Readable.prototype.addListener=Readable.prototype.on,Readable.prototype.resume=function(){var state=this._readableState;return state.flowing||(debug("resume"),state.flowing=!0,resume(this,state)),this},Readable.prototype.pause=function(){return debug("call pause flowing=%j",this._readableState.flowing),!1!==this._readableState.flowing&&(debug("pause"),this._readableState.flowing=!1,this.emit("pause")),this},Readable.prototype.wrap=function(stream){var _this=this,state=this._readableState,paused=!1;for(var i in stream.on("end",function(){if(debug("wrapped end"),state.decoder&&!state.ended){var chunk=state.decoder.end();chunk&&chunk.length&&_this.push(chunk)}_this.push(null)}),stream.on("data",function(chunk){debug("wrapped data"),state.decoder&&(chunk=state.decoder.write(chunk)),state.objectMode&&null==chunk||(state.objectMode||chunk&&chunk.length)&&(_this.push(chunk)||(paused=!0,stream.pause()))}),stream)void 0===this[i]&&"function"==typeof stream[i]&&(this[i]=function(method){return function(){return stream[method].apply(stream,arguments)}}(i));for(var n=0;n<kProxyEvents.length;n++)stream.on(kProxyEvents[n],this.emit.bind(this,kProxyEvents[n]));return this._read=function(n){debug("wrapped _read",n),paused&&(paused=!1,stream.resume())},this},Object.defineProperty(Readable.prototype,"readableHighWaterMark",{enumerable:!1,get:function(){return this._readableState.highWaterMark}}),Readable._fromList=fromList}).call(this)}).call(this,require("_process"),void 0!==__webpack_require__.g?__webpack_require__.g:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./_stream_duplex":91,"./internal/streams/BufferList":96,"./internal/streams/destroy":97,"./internal/streams/stream":98,_process:89,"core-util-is":28,events:37,inherits:41,isarray:42,"process-nextick-args":88,"safe-buffer":99,"string_decoder/":100,util:25}],94:[function(require,module,exports){"use strict";module.exports=Transform;var Duplex=require("./_stream_duplex"),util=Object.create(require("core-util-is"));function afterTransform(er,data){var ts=this._transformState;ts.transforming=!1;var cb=ts.writecb;if(!cb)return this.emit("error",new Error("write callback called multiple times"));ts.writechunk=null,ts.writecb=null,null!=data&&this.push(data),cb(er);var rs=this._readableState;rs.reading=!1,(rs.needReadable||rs.length<rs.highWaterMark)&&this._read(rs.highWaterMark)}function Transform(options){if(!(this instanceof Transform))return new Transform(options);Duplex.call(this,options),this._transformState={afterTransform:afterTransform.bind(this),needTransform:!1,transforming:!1,writecb:null,writechunk:null,writeencoding:null},this._readableState.needReadable=!0,this._readableState.sync=!1,options&&("function"==typeof options.transform&&(this._transform=options.transform),"function"==typeof options.flush&&(this._flush=options.flush)),this.on("prefinish",prefinish)}function prefinish(){var _this=this;"function"==typeof this._flush?this._flush(function(er,data){done(_this,er,data)}):done(this,null,null)}function done(stream,er,data){if(er)return stream.emit("error",er);if(null!=data&&stream.push(data),stream._writableState.length)throw new Error("Calling transform done when ws.length != 0");if(stream._transformState.transforming)throw new Error("Calling transform done when still transforming");return stream.push(null)}util.inherits=require("inherits"),util.inherits(Transform,Duplex),Transform.prototype.push=function(chunk,encoding){return this._transformState.needTransform=!1,Duplex.prototype.push.call(this,chunk,encoding)},Transform.prototype._transform=function(chunk,encoding,cb){throw new Error("_transform() is not implemented")},Transform.prototype._write=function(chunk,encoding,cb){var ts=this._transformState;if(ts.writecb=cb,ts.writechunk=chunk,ts.writeencoding=encoding,!ts.transforming){var rs=this._readableState;(ts.needTransform||rs.needReadable||rs.length<rs.highWaterMark)&&this._read(rs.highWaterMark)}},Transform.prototype._read=function(n){var ts=this._transformState;null!==ts.writechunk&&ts.writecb&&!ts.transforming?(ts.transforming=!0,this._transform(ts.writechunk,ts.writeencoding,ts.afterTransform)):ts.needTransform=!0},Transform.prototype._destroy=function(err,cb){var _this2=this;Duplex.prototype._destroy.call(this,err,function(err2){cb(err2),_this2.emit("close")})}},{"./_stream_duplex":91,"core-util-is":28,inherits:41}],95:[function(require,module,exports){(function(process,global,setImmediate){(function(){"use strict";var pna=require("process-nextick-args");function CorkedRequest(state){var _this=this;this.next=null,this.entry=null,this.finish=function(){onCorkedFinish(_this,state)}}module.exports=Writable;var Duplex,asyncWrite=!process.browser&&["v0.10","v0.9."].indexOf(process.version.slice(0,5))>-1?setImmediate:pna.nextTick;Writable.WritableState=WritableState;var util=Object.create(require("core-util-is"));util.inherits=require("inherits");var internalUtil={deprecate:require("util-deprecate")},Stream=require("./internal/streams/stream"),Buffer=require("safe-buffer").Buffer,OurUint8Array=(void 0!==global?global:"undefined"!=typeof window?window:"undefined"!=typeof self?self:{}).Uint8Array||function(){};function _uint8ArrayToBuffer(chunk){return Buffer.from(chunk)}function _isUint8Array(obj){return Buffer.isBuffer(obj)||obj instanceof OurUint8Array}var realHasInstance,destroyImpl=require("./internal/streams/destroy");function nop(){}function WritableState(options,stream){Duplex=Duplex||require("./_stream_duplex"),options=options||{};var isDuplex=stream instanceof Duplex;this.objectMode=!!options.objectMode,isDuplex&&(this.objectMode=this.objectMode||!!options.writableObjectMode);var hwm=options.highWaterMark,writableHwm=options.writableHighWaterMark,defaultHwm=this.objectMode?16:16384;this.highWaterMark=hwm||0===hwm?hwm:isDuplex&&(writableHwm||0===writableHwm)?writableHwm:defaultHwm,this.highWaterMark=Math.floor(this.highWaterMark),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;var noDecode=!1===options.decodeStrings;this.decodeStrings=!noDecode,this.defaultEncoding=options.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(er){onwrite(stream,er)},this.writecb=null,this.writelen=0,this.bufferedRequest=null,this.lastBufferedRequest=null,this.pendingcb=0,this.prefinished=!1,this.errorEmitted=!1,this.bufferedRequestCount=0,this.corkedRequestsFree=new CorkedRequest(this)}function Writable(options){if(Duplex=Duplex||require("./_stream_duplex"),!(realHasInstance.call(Writable,this)||this instanceof Duplex))return new Writable(options);this._writableState=new WritableState(options,this),this.writable=!0,options&&("function"==typeof options.write&&(this._write=options.write),"function"==typeof options.writev&&(this._writev=options.writev),"function"==typeof options.destroy&&(this._destroy=options.destroy),"function"==typeof options.final&&(this._final=options.final)),Stream.call(this)}function writeAfterEnd(stream,cb){var er=new Error("write after end");stream.emit("error",er),pna.nextTick(cb,er)}function validChunk(stream,state,chunk,cb){var valid=!0,er=!1;return null===chunk?er=new TypeError("May not write null values to stream"):"string"==typeof chunk||void 0===chunk||state.objectMode||(er=new TypeError("Invalid non-string/buffer chunk")),er&&(stream.emit("error",er),pna.nextTick(cb,er),valid=!1),valid}function decodeChunk(state,chunk,encoding){return state.objectMode||!1===state.decodeStrings||"string"!=typeof chunk||(chunk=Buffer.from(chunk,encoding)),chunk}function writeOrBuffer(stream,state,isBuf,chunk,encoding,cb){if(!isBuf){var newChunk=decodeChunk(state,chunk,encoding);chunk!==newChunk&&(isBuf=!0,encoding="buffer",chunk=newChunk)}var len=state.objectMode?1:chunk.length;state.length+=len;var ret=state.length<state.highWaterMark;if(ret||(state.needDrain=!0),state.writing||state.corked){var last=state.lastBufferedRequest;state.lastBufferedRequest={chunk,encoding,isBuf,callback:cb,next:null},last?last.next=state.lastBufferedRequest:state.bufferedRequest=state.lastBufferedRequest,state.bufferedRequestCount+=1}else doWrite(stream,state,!1,len,chunk,encoding,cb);return ret}function doWrite(stream,state,writev,len,chunk,encoding,cb){state.writelen=len,state.writecb=cb,state.writing=!0,state.sync=!0,writev?stream._writev(chunk,state.onwrite):stream._write(chunk,encoding,state.onwrite),state.sync=!1}function onwriteError(stream,state,sync,er,cb){--state.pendingcb,sync?(pna.nextTick(cb,er),pna.nextTick(finishMaybe,stream,state),stream._writableState.errorEmitted=!0,stream.emit("error",er)):(cb(er),stream._writableState.errorEmitted=!0,stream.emit("error",er),finishMaybe(stream,state))}function onwriteStateUpdate(state){state.writing=!1,state.writecb=null,state.length-=state.writelen,state.writelen=0}function onwrite(stream,er){var state=stream._writableState,sync=state.sync,cb=state.writecb;if(onwriteStateUpdate(state),er)onwriteError(stream,state,sync,er,cb);else{var finished=needFinish(state);finished||state.corked||state.bufferProcessing||!state.bufferedRequest||clearBuffer(stream,state),sync?asyncWrite(afterWrite,stream,state,finished,cb):afterWrite(stream,state,finished,cb)}}function afterWrite(stream,state,finished,cb){finished||onwriteDrain(stream,state),state.pendingcb--,cb(),finishMaybe(stream,state)}function onwriteDrain(stream,state){0===state.length&&state.needDrain&&(state.needDrain=!1,stream.emit("drain"))}function clearBuffer(stream,state){state.bufferProcessing=!0;var entry=state.bufferedRequest;if(stream._writev&&entry&&entry.next){var l=state.bufferedRequestCount,buffer=new Array(l),holder=state.corkedRequestsFree;holder.entry=entry;for(var count=0,allBuffers=!0;entry;)buffer[count]=entry,entry.isBuf||(allBuffers=!1),entry=entry.next,count+=1;buffer.allBuffers=allBuffers,doWrite(stream,state,!0,state.length,buffer,"",holder.finish),state.pendingcb++,state.lastBufferedRequest=null,holder.next?(state.corkedRequestsFree=holder.next,holder.next=null):state.corkedRequestsFree=new CorkedRequest(state),state.bufferedRequestCount=0}else{for(;entry;){var chunk=entry.chunk,encoding=entry.encoding,cb=entry.callback;if(doWrite(stream,state,!1,state.objectMode?1:chunk.length,chunk,encoding,cb),entry=entry.next,state.bufferedRequestCount--,state.writing)break}null===entry&&(state.lastBufferedRequest=null)}state.bufferedRequest=entry,state.bufferProcessing=!1}function needFinish(state){return state.ending&&0===state.length&&null===state.bufferedRequest&&!state.finished&&!state.writing}function callFinal(stream,state){stream._final(function(err){state.pendingcb--,err&&stream.emit("error",err),state.prefinished=!0,stream.emit("prefinish"),finishMaybe(stream,state)})}function prefinish(stream,state){state.prefinished||state.finalCalled||("function"==typeof stream._final?(state.pendingcb++,state.finalCalled=!0,pna.nextTick(callFinal,stream,state)):(state.prefinished=!0,stream.emit("prefinish")))}function finishMaybe(stream,state){var need=needFinish(state);return need&&(prefinish(stream,state),0===state.pendingcb&&(state.finished=!0,stream.emit("finish"))),need}function endWritable(stream,state,cb){state.ending=!0,finishMaybe(stream,state),cb&&(state.finished?pna.nextTick(cb):stream.once("finish",cb)),state.ended=!0,stream.writable=!1}function onCorkedFinish(corkReq,state,err){var entry=corkReq.entry;for(corkReq.entry=null;entry;){var cb=entry.callback;state.pendingcb--,cb(err),entry=entry.next}state.corkedRequestsFree.next=corkReq}util.inherits(Writable,Stream),WritableState.prototype.getBuffer=function getBuffer(){for(var current=this.bufferedRequest,out=[];current;)out.push(current),current=current.next;return out},function(){try{Object.defineProperty(WritableState.prototype,"buffer",{get:internalUtil.deprecate(function(){return this.getBuffer()},"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.","DEP0003")})}catch(_){}}(),"function"==typeof Symbol&&Symbol.hasInstance&&"function"==typeof Function.prototype[Symbol.hasInstance]?(realHasInstance=Function.prototype[Symbol.hasInstance],Object.defineProperty(Writable,Symbol.hasInstance,{value:function(object){return!!realHasInstance.call(this,object)||this===Writable&&object&&object._writableState instanceof WritableState}})):realHasInstance=function(object){return object instanceof this},Writable.prototype.pipe=function(){this.emit("error",new Error("Cannot pipe, not readable"))},Writable.prototype.write=function(chunk,encoding,cb){var state=this._writableState,ret=!1,isBuf=!state.objectMode&&_isUint8Array(chunk);return isBuf&&!Buffer.isBuffer(chunk)&&(chunk=_uint8ArrayToBuffer(chunk)),"function"==typeof encoding&&(cb=encoding,encoding=null),isBuf?encoding="buffer":encoding||(encoding=state.defaultEncoding),"function"!=typeof cb&&(cb=nop),state.ended?writeAfterEnd(this,cb):(isBuf||validChunk(this,state,chunk,cb))&&(state.pendingcb++,ret=writeOrBuffer(this,state,isBuf,chunk,encoding,cb)),ret},Writable.prototype.cork=function(){this._writableState.corked++},Writable.prototype.uncork=function(){var state=this._writableState;state.corked&&(state.corked--,state.writing||state.corked||state.bufferProcessing||!state.bufferedRequest||clearBuffer(this,state))},Writable.prototype.setDefaultEncoding=function setDefaultEncoding(encoding){if("string"==typeof encoding&&(encoding=encoding.toLowerCase()),!(["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((encoding+"").toLowerCase())>-1))throw new TypeError("Unknown encoding: "+encoding);return this._writableState.defaultEncoding=encoding,this},Object.defineProperty(Writable.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),Writable.prototype._write=function(chunk,encoding,cb){cb(new Error("_write() is not implemented"))},Writable.prototype._writev=null,Writable.prototype.end=function(chunk,encoding,cb){var state=this._writableState;"function"==typeof chunk?(cb=chunk,chunk=null,encoding=null):"function"==typeof encoding&&(cb=encoding,encoding=null),null!=chunk&&this.write(chunk,encoding),state.corked&&(state.corked=1,this.uncork()),state.ending||endWritable(this,state,cb)},Object.defineProperty(Writable.prototype,"destroyed",{get:function(){return void 0!==this._writableState&&this._writableState.destroyed},set:function(value){this._writableState&&(this._writableState.destroyed=value)}}),Writable.prototype.destroy=destroyImpl.destroy,Writable.prototype._undestroy=destroyImpl.undestroy,Writable.prototype._destroy=function(err,cb){this.end(),cb(err)}}).call(this)}).call(this,require("_process"),void 0!==__webpack_require__.g?__webpack_require__.g:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},require("timers").setImmediate)},{"./_stream_duplex":91,"./internal/streams/destroy":97,"./internal/streams/stream":98,_process:89,"core-util-is":28,inherits:41,"process-nextick-args":88,"safe-buffer":99,timers:112,"util-deprecate":113}],96:[function(require,module,exports){"use strict";function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}var Buffer=require("safe-buffer").Buffer,util=require("util");function copyBuffer(src,target,offset){src.copy(target,offset)}module.exports=function(){function BufferList(){_classCallCheck(this,BufferList),this.head=null,this.tail=null,this.length=0}return BufferList.prototype.push=function push(v){var entry={data:v,next:null};this.length>0?this.tail.next=entry:this.head=entry,this.tail=entry,++this.length},BufferList.prototype.unshift=function unshift(v){var entry={data:v,next:this.head};0===this.length&&(this.tail=entry),this.head=entry,++this.length},BufferList.prototype.shift=function shift(){if(0!==this.length){var ret=this.head.data;return 1===this.length?this.head=this.tail=null:this.head=this.head.next,--this.length,ret}},BufferList.prototype.clear=function clear(){this.head=this.tail=null,this.length=0},BufferList.prototype.join=function join(s){if(0===this.length)return"";for(var p=this.head,ret=""+p.data;p=p.next;)ret+=s+p.data;return ret},BufferList.prototype.concat=function concat(n){if(0===this.length)return Buffer.alloc(0);for(var ret=Buffer.allocUnsafe(n>>>0),p=this.head,i=0;p;)copyBuffer(p.data,ret,i),i+=p.data.length,p=p.next;return ret},BufferList}(),util&&util.inspect&&util.inspect.custom&&(module.exports.prototype[util.inspect.custom]=function(){var obj=util.inspect({length:this.length});return this.constructor.name+" "+obj})},{"safe-buffer":99,util:25}],97:[function(require,module,exports){"use strict";var pna=require("process-nextick-args");function destroy(err,cb){var _this=this,readableDestroyed=this._readableState&&this._readableState.destroyed,writableDestroyed=this._writableState&&this._writableState.destroyed;return readableDestroyed||writableDestroyed?(cb?cb(err):err&&(this._writableState?this._writableState.errorEmitted||(this._writableState.errorEmitted=!0,pna.nextTick(emitErrorNT,this,err)):pna.nextTick(emitErrorNT,this,err)),this):(this._readableState&&(this._readableState.destroyed=!0),this._writableState&&(this._writableState.destroyed=!0),this._destroy(err||null,function(err){!cb&&err?_this._writableState?_this._writableState.errorEmitted||(_this._writableState.errorEmitted=!0,pna.nextTick(emitErrorNT,_this,err)):pna.nextTick(emitErrorNT,_this,err):cb&&cb(err)}),this)}function undestroy(){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 emitErrorNT(self,err){self.emit("error",err)}module.exports={destroy,undestroy}},{"process-nextick-args":88}],98:[function(require,module,exports){module.exports=require("events").EventEmitter},{events:37}],99:[function(require,module,exports){var buffer=require("buffer"),Buffer=buffer.Buffer;function copyProps(src,dst){for(var key in src)dst[key]=src[key]}function SafeBuffer(arg,encodingOrOffset,length){return Buffer(arg,encodingOrOffset,length)}Buffer.from&&Buffer.alloc&&Buffer.allocUnsafe&&Buffer.allocUnsafeSlow?module.exports=buffer:(copyProps(buffer,exports),exports.Buffer=SafeBuffer),copyProps(Buffer,SafeBuffer),SafeBuffer.from=function(arg,encodingOrOffset,length){if("number"==typeof arg)throw new TypeError("Argument must not be a number");return Buffer(arg,encodingOrOffset,length)},SafeBuffer.alloc=function(size,fill,encoding){if("number"!=typeof size)throw new TypeError("Argument must be a number");var buf=Buffer(size);return void 0!==fill?"string"==typeof encoding?buf.fill(fill,encoding):buf.fill(fill):buf.fill(0),buf},SafeBuffer.allocUnsafe=function(size){if("number"!=typeof size)throw new TypeError("Argument must be a number");return Buffer(size)},SafeBuffer.allocUnsafeSlow=function(size){if("number"!=typeof size)throw new TypeError("Argument must be a number");return buffer.SlowBuffer(size)}},{buffer:27}],100:[function(require,module,exports){"use strict";var Buffer=require("safe-buffer").Buffer,isEncoding=Buffer.isEncoding||function(encoding){switch((encoding=""+encoding)&&encoding.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 _normalizeEncoding(enc){if(!enc)return"utf8";for(var retried;;)switch(enc){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 enc;default:if(retried)return;enc=(""+enc).toLowerCase(),retried=!0}}function normalizeEncoding(enc){var nenc=_normalizeEncoding(enc);if("string"!=typeof nenc&&(Buffer.isEncoding===isEncoding||!isEncoding(enc)))throw new Error("Unknown encoding: "+enc);return nenc||enc}function StringDecoder(encoding){var nb;switch(this.encoding=normalizeEncoding(encoding),this.encoding){case"utf16le":this.text=utf16Text,this.end=utf16End,nb=4;break;case"utf8":this.fillLast=utf8FillLast,nb=4;break;case"base64":this.text=base64Text,this.end=base64End,nb=3;break;default:return this.write=simpleWrite,void(this.end=simpleEnd)}this.lastNeed=0,this.lastTotal=0,this.lastChar=Buffer.allocUnsafe(nb)}function utf8CheckByte(byte){return byte<=127?0:byte>>5==6?2:byte>>4==14?3:byte>>3==30?4:byte>>6==2?-1:-2}function utf8CheckIncomplete(self,buf,i){var j=buf.length-1;if(j<i)return 0;var nb=utf8CheckByte(buf[j]);return nb>=0?(nb>0&&(self.lastNeed=nb-1),nb):--j<i||-2===nb?0:(nb=utf8CheckByte(buf[j]))>=0?(nb>0&&(self.lastNeed=nb-2),nb):--j<i||-2===nb?0:(nb=utf8CheckByte(buf[j]))>=0?(nb>0&&(2===nb?nb=0:self.lastNeed=nb-3),nb):0}function utf8CheckExtraBytes(self,buf,p){if(128!=(192&buf[0]))return self.lastNeed=0,"�";if(self.lastNeed>1&&buf.length>1){if(128!=(192&buf[1]))return self.lastNeed=1,"�";if(self.lastNeed>2&&buf.length>2&&128!=(192&buf[2]))return self.lastNeed=2,"�"}}function utf8FillLast(buf){var p=this.lastTotal-this.lastNeed,r=utf8CheckExtraBytes(this,buf,p);return void 0!==r?r:this.lastNeed<=buf.length?(buf.copy(this.lastChar,p,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal)):(buf.copy(this.lastChar,p,0,buf.length),void(this.lastNeed-=buf.length))}function utf8Text(buf,i){var total=utf8CheckIncomplete(this,buf,i);if(!this.lastNeed)return buf.toString("utf8",i);this.lastTotal=total;var end=buf.length-(total-this.lastNeed);return buf.copy(this.lastChar,0,end),buf.toString("utf8",i,end)}function utf8End(buf){var r=buf&&buf.length?this.write(buf):"";return this.lastNeed?r+"�":r}function utf16Text(buf,i){if((buf.length-i)%2==0){var r=buf.toString("utf16le",i);if(r){var c=r.charCodeAt(r.length-1);if(c>=55296&&c<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=buf[buf.length-2],this.lastChar[1]=buf[buf.length-1],r.slice(0,-1)}return r}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=buf[buf.length-1],buf.toString("utf16le",i,buf.length-1)}function utf16End(buf){var r=buf&&buf.length?this.write(buf):"";if(this.lastNeed){var end=this.lastTotal-this.lastNeed;return r+this.lastChar.toString("utf16le",0,end)}return r}function base64Text(buf,i){var n=(buf.length-i)%3;return 0===n?buf.toString("base64",i):(this.lastNeed=3-n,this.lastTotal=3,1===n?this.lastChar[0]=buf[buf.length-1]:(this.lastChar[0]=buf[buf.length-2],this.lastChar[1]=buf[buf.length-1]),buf.toString("base64",i,buf.length-n))}function base64End(buf){var r=buf&&buf.length?this.write(buf):"";return this.lastNeed?r+this.lastChar.toString("base64",0,3-this.lastNeed):r}function simpleWrite(buf){return buf.toString(this.encoding)}function simpleEnd(buf){return buf&&buf.length?this.write(buf):""}exports.StringDecoder=StringDecoder,StringDecoder.prototype.write=function(buf){if(0===buf.length)return"";var r,i;if(this.lastNeed){if(void 0===(r=this.fillLast(buf)))return"";i=this.lastNeed,this.lastNeed=0}else i=0;return i<buf.length?r?r+this.text(buf,i):this.text(buf,i):r||""},StringDecoder.prototype.end=utf8End,StringDecoder.prototype.text=utf8Text,StringDecoder.prototype.fillLast=function(buf){if(this.lastNeed<=buf.length)return buf.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);buf.copy(this.lastChar,this.lastTotal-this.lastNeed,0,buf.length),this.lastNeed-=buf.length}},{"safe-buffer":99}],101:[function(require,module,exports){module.exports=require("./readable").PassThrough},{"./readable":102}],102:[function(require,module,exports){(exports=module.exports=require("./lib/_stream_readable.js")).Stream=exports,exports.Readable=exports,exports.Writable=require("./lib/_stream_writable.js"),exports.Duplex=require("./lib/_stream_duplex.js"),exports.Transform=require("./lib/_stream_transform.js"),exports.PassThrough=require("./lib/_stream_passthrough.js")},{"./lib/_stream_duplex.js":91,"./lib/_stream_passthrough.js":92,"./lib/_stream_readable.js":93,"./lib/_stream_transform.js":94,"./lib/_stream_writable.js":95}],103:[function(require,module,exports){module.exports=require("./readable").Transform},{"./readable":102}],104:[function(require,module,exports){module.exports=require("./lib/_stream_writable.js")},{"./lib/_stream_writable.js":95}],105:[function(require,module,exports){var EventEmitter=require("events").EventEmitter,backoff=require("backoff"),noop=function(){};module.exports=function(createConnection){return function(opts,onConnect){onConnect="function"==typeof opts?opts:onConnect,opts="object"==typeof opts?opts:{initialDelay:1e3,maxDelay:3e4},onConnect||(onConnect=opts.onConnect);var emitter=opts.emitter||new EventEmitter;emitter.connected=!1,emitter.reconnect=!0,onConnect&&emitter.on("connect",onConnect);var args,backoffMethod=(backoff[opts.type]||backoff.fibonacci)(opts);backoffMethod.on("backoff",function(n,d){emitter.emit("backoff",n,d)});var cleanup=noop;function attempt(n,delay){if(emitter.reconnect){cleanup(),emitter.emit("reconnect",n,delay);var con=createConnection.apply(null,args);con!==emitter._connection&&emitter.emit("connection",con),emitter._connection=con,cleanup=onCleanup,con.on("error",onDisconnect).on("close",onDisconnect).on("end",onDisconnect),opts.immediate||"Request"==con.constructor.name?(emitter.connected=!0,emitter.emit("connect",con),con.once("data",function(){backoffMethod.reset()})):con.on("connect",connect)}function onCleanup(err){cleanup=noop,con.removeListener("connect",connect),con.removeListener("error",onDisconnect),con.removeListener("close",onDisconnect),con.removeListener("end",onDisconnect),"Request"==con.constructor.name&&con.on("error",noop)}function onDisconnect(err){if(emitter.connected=!1,onCleanup(err),emitter.emit("disconnect",err),emitter.reconnect)try{backoffMethod.backoff()}catch(_){}}function connect(){backoffMethod.reset(),emitter.connected=!0,onConnect&&con.removeListener("connect",onConnect),emitter.emit("connect",con)}}return backoffMethod.on("ready",attempt),emitter.connect=emitter.listen=function(){return this.reconnect=!0,backoffMethod.reset(),args=[].slice.call(arguments),attempt(0,0),emitter},emitter.end=emitter.disconnect=function(){return emitter.reconnect=!1,emitter._connection&&emitter._connection.end(),emitter.emit("disconnect"),emitter},emitter}}},{backoff:17,events:37}],106:[function(require,module,exports){"use strict";var SDPUtils=require("sdp");function fixStatsType(stat){return{inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"}[stat.type]||stat.type}function writeMediaSection(transceiver,caps,type,stream,dtlsRole){var sdp=SDPUtils.writeRtpDescription(transceiver.kind,caps);if(sdp+=SDPUtils.writeIceParameters(transceiver.iceGatherer.getLocalParameters()),sdp+=SDPUtils.writeDtlsParameters(transceiver.dtlsTransport.getLocalParameters(),"offer"===type?"actpass":dtlsRole||"active"),sdp+="a=mid:"+transceiver.mid+"\r\n",transceiver.rtpSender&&transceiver.rtpReceiver?sdp+="a=sendrecv\r\n":transceiver.rtpSender?sdp+="a=sendonly\r\n":transceiver.rtpReceiver?sdp+="a=recvonly\r\n":sdp+="a=inactive\r\n",transceiver.rtpSender){var trackId=transceiver.rtpSender._initialTrackId||transceiver.rtpSender.track.id;transceiver.rtpSender._initialTrackId=trackId;var msid="msid:"+(stream?stream.id:"-")+" "+trackId+"\r\n";sdp+="a="+msid,sdp+="a=ssrc:"+transceiver.sendEncodingParameters[0].ssrc+" "+msid,transceiver.sendEncodingParameters[0].rtx&&(sdp+="a=ssrc:"+transceiver.sendEncodingParameters[0].rtx.ssrc+" "+msid,sdp+="a=ssrc-group:FID "+transceiver.sendEncodingParameters[0].ssrc+" "+transceiver.sendEncodingParameters[0].rtx.ssrc+"\r\n")}return sdp+="a=ssrc:"+transceiver.sendEncodingParameters[0].ssrc+" cname:"+SDPUtils.localCName+"\r\n",transceiver.rtpSender&&transceiver.sendEncodingParameters[0].rtx&&(sdp+="a=ssrc:"+transceiver.sendEncodingParameters[0].rtx.ssrc+" cname:"+SDPUtils.localCName+"\r\n"),sdp}function filterIceServers(iceServers,edgeVersion){var hasTurn=!1;return(iceServers=JSON.parse(JSON.stringify(iceServers))).filter(function(server){if(server&&(server.urls||server.url)){var urls=server.urls||server.url;server.url&&!server.urls&&console.warn("RTCIceServer.url is deprecated! Use urls instead.");var isString="string"==typeof urls;return isString&&(urls=[urls]),urls=urls.filter(function(url){return 0!==url.indexOf("turn:")||-1===url.indexOf("transport=udp")||-1!==url.indexOf("turn:[")||hasTurn?0===url.indexOf("stun:")&&edgeVersion>=14393&&-1===url.indexOf("?transport=udp"):(hasTurn=!0,!0)}),delete server.url,server.urls=isString?urls[0]:urls,!!urls.length}})}function getCommonCapabilities(localCapabilities,remoteCapabilities){var commonCapabilities={codecs:[],headerExtensions:[],fecMechanisms:[]},findCodecByPayloadType=function(pt,codecs){pt=parseInt(pt,10);for(var i=0;i<codecs.length;i++)if(codecs[i].payloadType===pt||codecs[i].preferredPayloadType===pt)return codecs[i]},rtxCapabilityMatches=function(lRtx,rRtx,lCodecs,rCodecs){var lCodec=findCodecByPayloadType(lRtx.parameters.apt,lCodecs),rCodec=findCodecByPayloadType(rRtx.parameters.apt,rCodecs);return lCodec&&rCodec&&lCodec.name.toLowerCase()===rCodec.name.toLowerCase()};return localCapabilities.codecs.forEach(function(lCodec){for(var i=0;i<remoteCapabilities.codecs.length;i++){var rCodec=remoteCapabilities.codecs[i];if(lCodec.name.toLowerCase()===rCodec.name.toLowerCase()&&lCodec.clockRate===rCodec.clockRate){if("rtx"===lCodec.name.toLowerCase()&&lCodec.parameters&&rCodec.parameters.apt&&!rtxCapabilityMatches(lCodec,rCodec,localCapabilities.codecs,remoteCapabilities.codecs))continue;(rCodec=JSON.parse(JSON.stringify(rCodec))).numChannels=Math.min(lCodec.numChannels,rCodec.numChannels),commonCapabilities.codecs.push(rCodec),rCodec.rtcpFeedback=rCodec.rtcpFeedback.filter(function(fb){for(var j=0;j<lCodec.rtcpFeedback.length;j++)if(lCodec.rtcpFeedback[j].type===fb.type&&lCodec.rtcpFeedback[j].parameter===fb.parameter)return!0;return!1});break}}}),localCapabilities.headerExtensions.forEach(function(lHeaderExtension){for(var i=0;i<remoteCapabilities.headerExtensions.length;i++){var rHeaderExtension=remoteCapabilities.headerExtensions[i];if(lHeaderExtension.uri===rHeaderExtension.uri){commonCapabilities.headerExtensions.push(rHeaderExtension);break}}}),commonCapabilities}function isActionAllowedInSignalingState(action,type,signalingState){return-1!=={offer:{setLocalDescription:["stable","have-local-offer"],setRemoteDescription:["stable","have-remote-offer"]},answer:{setLocalDescription:["have-remote-offer","have-local-pranswer"],setRemoteDescription:["have-local-offer","have-remote-pranswer"]}}[type][action].indexOf(signalingState)}function maybeAddCandidate(iceTransport,candidate){var alreadyAdded=iceTransport.getRemoteCandidates().find(function(remoteCandidate){return candidate.foundation===remoteCandidate.foundation&&candidate.ip===remoteCandidate.ip&&candidate.port===remoteCandidate.port&&candidate.priority===remoteCandidate.priority&&candidate.protocol===remoteCandidate.protocol&&candidate.type===remoteCandidate.type});return alreadyAdded||iceTransport.addRemoteCandidate(candidate),!alreadyAdded}function makeError(name,description){var e=new Error(description);return e.name=name,e.code={NotSupportedError:9,InvalidStateError:11,InvalidAccessError:15,TypeError:void 0,OperationError:void 0}[name],e}module.exports=function(window,edgeVersion){function addTrackToStreamAndFireEvent(track,stream){stream.addTrack(track),stream.dispatchEvent(new window.MediaStreamTrackEvent("addtrack",{track}))}function removeTrackFromStreamAndFireEvent(track,stream){stream.removeTrack(track),stream.dispatchEvent(new window.MediaStreamTrackEvent("removetrack",{track}))}function fireAddTrack(pc,track,receiver,streams){var trackEvent=new Event("track");trackEvent.track=track,trackEvent.receiver=receiver,trackEvent.transceiver={receiver},trackEvent.streams=streams,window.setTimeout(function(){pc._dispatchEvent("track",trackEvent)})}var RTCPeerConnection=function(config){var pc=this,_eventTarget=document.createDocumentFragment();if(["addEventListener","removeEventListener","dispatchEvent"].forEach(function(method){pc[method]=_eventTarget[method].bind(_eventTarget)}),this.canTrickleIceCandidates=null,this.needNegotiation=!1,this.localStreams=[],this.remoteStreams=[],this._localDescription=null,this._remoteDescription=null,this.signalingState="stable",this.iceConnectionState="new",this.connectionState="new",this.iceGatheringState="new",config=JSON.parse(JSON.stringify(config||{})),this.usingBundle="max-bundle"===config.bundlePolicy,"negotiate"===config.rtcpMuxPolicy)throw makeError("NotSupportedError","rtcpMuxPolicy 'negotiate' is not supported");switch(config.rtcpMuxPolicy||(config.rtcpMuxPolicy="require"),config.iceTransportPolicy){case"all":case"relay":break;default:config.iceTransportPolicy="all"}switch(config.bundlePolicy){case"balanced":case"max-compat":case"max-bundle":break;default:config.bundlePolicy="balanced"}if(config.iceServers=filterIceServers(config.iceServers||[],edgeVersion),this._iceGatherers=[],config.iceCandidatePoolSize)for(var i=config.iceCandidatePoolSize;i>0;i--)this._iceGatherers.push(new window.RTCIceGatherer({iceServers:config.iceServers,gatherPolicy:config.iceTransportPolicy}));else config.iceCandidatePoolSize=0;this._config=config,this.transceivers=[],this._sdpSessionId=SDPUtils.generateSessionId(),this._sdpSessionVersion=0,this._dtlsRole=void 0,this._isClosed=!1};Object.defineProperty(RTCPeerConnection.prototype,"localDescription",{configurable:!0,get:function(){return this._localDescription}}),Object.defineProperty(RTCPeerConnection.prototype,"remoteDescription",{configurable:!0,get:function(){return this._remoteDescription}}),RTCPeerConnection.prototype.onicecandidate=null,RTCPeerConnection.prototype.onaddstream=null,RTCPeerConnection.prototype.ontrack=null,RTCPeerConnection.prototype.onremovestream=null,RTCPeerConnection.prototype.onsignalingstatechange=null,RTCPeerConnection.prototype.oniceconnectionstatechange=null,RTCPeerConnection.prototype.onconnectionstatechange=null,RTCPeerConnection.prototype.onicegatheringstatechange=null,RTCPeerConnection.prototype.onnegotiationneeded=null,RTCPeerConnection.prototype.ondatachannel=null,RTCPeerConnection.prototype._dispatchEvent=function(name,event){this._isClosed||(this.dispatchEvent(event),"function"==typeof this["on"+name]&&this["on"+name](event))},RTCPeerConnection.prototype._emitGatheringStateChange=function(){var event=new Event("icegatheringstatechange");this._dispatchEvent("icegatheringstatechange",event)},RTCPeerConnection.prototype.getConfiguration=function(){return this._config},RTCPeerConnection.prototype.getLocalStreams=function(){return this.localStreams},RTCPeerConnection.prototype.getRemoteStreams=function(){return this.remoteStreams},RTCPeerConnection.prototype._createTransceiver=function(kind,doNotAdd){var hasBundleTransport=this.transceivers.length>0,transceiver={track:null,iceGatherer:null,iceTransport:null,dtlsTransport:null,localCapabilities:null,remoteCapabilities:null,rtpSender:null,rtpReceiver:null,kind,mid:null,sendEncodingParameters:null,recvEncodingParameters:null,stream:null,associatedRemoteMediaStreams:[],wantReceive:!0};if(this.usingBundle&&hasBundleTransport)transceiver.iceTransport=this.transceivers[0].iceTransport,transceiver.dtlsTransport=this.transceivers[0].dtlsTransport;else{var transports=this._createIceAndDtlsTransports();transceiver.iceTransport=transports.iceTransport,transceiver.dtlsTransport=transports.dtlsTransport}return doNotAdd||this.transceivers.push(transceiver),transceiver},RTCPeerConnection.prototype.addTrack=function(track,stream){if(this._isClosed)throw makeError("InvalidStateError","Attempted to call addTrack on a closed peerconnection.");var transceiver;if(this.transceivers.find(function(s){return s.track===track}))throw makeError("InvalidAccessError","Track already exists.");for(var i=0;i<this.transceivers.length;i++)this.transceivers[i].track||this.transceivers[i].kind!==track.kind||(transceiver=this.transceivers[i]);return transceiver||(transceiver=this._createTransceiver(track.kind)),this._maybeFireNegotiationNeeded(),-1===this.localStreams.indexOf(stream)&&this.localStreams.push(stream),transceiver.track=track,transceiver.stream=stream,transceiver.rtpSender=new window.RTCRtpSender(track,transceiver.dtlsTransport),transceiver.rtpSender},RTCPeerConnection.prototype.addStream=function(stream){var pc=this;if(edgeVersion>=15025)stream.getTracks().forEach(function(track){pc.addTrack(track,stream)});else{var clonedStream=stream.clone();stream.getTracks().forEach(function(track,idx){var clonedTrack=clonedStream.getTracks()[idx];track.addEventListener("enabled",function(event){clonedTrack.enabled=event.enabled})}),clonedStream.getTracks().forEach(function(track){pc.addTrack(track,clonedStream)})}},RTCPeerConnection.prototype.removeTrack=function(sender){if(this._isClosed)throw makeError("InvalidStateError","Attempted to call removeTrack on a closed peerconnection.");if(!(sender instanceof window.RTCRtpSender))throw new TypeError("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.");var transceiver=this.transceivers.find(function(t){return t.rtpSender===sender});if(!transceiver)throw makeError("InvalidAccessError","Sender was not created by this connection.");var stream=transceiver.stream;transceiver.rtpSender.stop(),transceiver.rtpSender=null,transceiver.track=null,transceiver.stream=null,-1===this.transceivers.map(function(t){return t.stream}).indexOf(stream)&&this.localStreams.indexOf(stream)>-1&&this.localStreams.splice(this.localStreams.indexOf(stream),1),this._maybeFireNegotiationNeeded()},RTCPeerConnection.prototype.removeStream=function(stream){var pc=this;stream.getTracks().forEach(function(track){var sender=pc.getSenders().find(function(s){return s.track===track});sender&&pc.removeTrack(sender)})},RTCPeerConnection.prototype.getSenders=function(){return this.transceivers.filter(function(transceiver){return!!transceiver.rtpSender}).map(function(transceiver){return transceiver.rtpSender})},RTCPeerConnection.prototype.getReceivers=function(){return this.transceivers.filter(function(transceiver){return!!transceiver.rtpReceiver}).map(function(transceiver){return transceiver.rtpReceiver})},RTCPeerConnection.prototype._createIceGatherer=function(sdpMLineIndex,usingBundle){var pc=this;if(usingBundle&&sdpMLineIndex>0)return this.transceivers[0].iceGatherer;if(this._iceGatherers.length)return this._iceGatherers.shift();var iceGatherer=new window.RTCIceGatherer({iceServers:this._config.iceServers,gatherPolicy:this._config.iceTransportPolicy});return Object.defineProperty(iceGatherer,"state",{value:"new",writable:!0}),this.transceivers[sdpMLineIndex].bufferedCandidateEvents=[],this.transceivers[sdpMLineIndex].bufferCandidates=function(event){var end=!event.candidate||0===Object.keys(event.candidate).length;iceGatherer.state=end?"completed":"gathering",null!==pc.transceivers[sdpMLineIndex].bufferedCandidateEvents&&pc.transceivers[sdpMLineIndex].bufferedCandidateEvents.push(event)},iceGatherer.addEventListener("localcandidate",this.transceivers[sdpMLineIndex].bufferCandidates),iceGatherer},RTCPeerConnection.prototype._gather=function(mid,sdpMLineIndex){var pc=this,iceGatherer=this.transceivers[sdpMLineIndex].iceGatherer;if(!iceGatherer.onlocalcandidate){var bufferedCandidateEvents=this.transceivers[sdpMLineIndex].bufferedCandidateEvents;this.transceivers[sdpMLineIndex].bufferedCandidateEvents=null,iceGatherer.removeEventListener("localcandidate",this.transceivers[sdpMLineIndex].bufferCandidates),iceGatherer.onlocalcandidate=function(evt){if(!(pc.usingBundle&&sdpMLineIndex>0)){var event=new Event("icecandidate");event.candidate={sdpMid:mid,sdpMLineIndex};var cand=evt.candidate,end=!cand||0===Object.keys(cand).length;if(end)"new"!==iceGatherer.state&&"gathering"!==iceGatherer.state||(iceGatherer.state="completed");else{"new"===iceGatherer.state&&(iceGatherer.state="gathering"),cand.component=1,cand.ufrag=iceGatherer.getLocalParameters().usernameFragment;var serializedCandidate=SDPUtils.writeCandidate(cand);event.candidate=Object.assign(event.candidate,SDPUtils.parseCandidate(serializedCandidate)),event.candidate.candidate=serializedCandidate,event.candidate.toJSON=function(){return{candidate:event.candidate.candidate,sdpMid:event.candidate.sdpMid,sdpMLineIndex:event.candidate.sdpMLineIndex,usernameFragment:event.candidate.usernameFragment}}}var sections=SDPUtils.getMediaSections(pc._localDescription.sdp);sections[event.candidate.sdpMLineIndex]+=end?"a=end-of-candidates\r\n":"a="+event.candidate.candidate+"\r\n",pc._localDescription.sdp=SDPUtils.getDescription(pc._localDescription.sdp)+sections.join("");var complete=pc.transceivers.every(function(transceiver){return transceiver.iceGatherer&&"completed"===transceiver.iceGatherer.state});"gathering"!==pc.iceGatheringState&&(pc.iceGatheringState="gathering",pc._emitGatheringStateChange()),end||pc._dispatchEvent("icecandidate",event),complete&&(pc._dispatchEvent("icecandidate",new Event("icecandidate")),pc.iceGatheringState="complete",pc._emitGatheringStateChange())}},window.setTimeout(function(){bufferedCandidateEvents.forEach(function(e){iceGatherer.onlocalcandidate(e)})},0)}},RTCPeerConnection.prototype._createIceAndDtlsTransports=function(){var pc=this,iceTransport=new window.RTCIceTransport(null);iceTransport.onicestatechange=function(){pc._updateIceConnectionState(),pc._updateConnectionState()};var dtlsTransport=new window.RTCDtlsTransport(iceTransport);return dtlsTransport.ondtlsstatechange=function(){pc._updateConnectionState()},dtlsTransport.onerror=function(){Object.defineProperty(dtlsTransport,"state",{value:"failed",writable:!0}),pc._updateConnectionState()},{iceTransport,dtlsTransport}},RTCPeerConnection.prototype._disposeIceAndDtlsTransports=function(sdpMLineIndex){var iceGatherer=this.transceivers[sdpMLineIndex].iceGatherer;iceGatherer&&(delete iceGatherer.onlocalcandidate,delete this.transceivers[sdpMLineIndex].iceGatherer);var iceTransport=this.transceivers[sdpMLineIndex].iceTransport;iceTransport&&(delete iceTransport.onicestatechange,delete this.transceivers[sdpMLineIndex].iceTransport);var dtlsTransport=this.transceivers[sdpMLineIndex].dtlsTransport;dtlsTransport&&(delete dtlsTransport.ondtlsstatechange,delete dtlsTransport.onerror,delete this.transceivers[sdpMLineIndex].dtlsTransport)},RTCPeerConnection.prototype._transceive=function(transceiver,send,recv){var params=getCommonCapabilities(transceiver.localCapabilities,transceiver.remoteCapabilities);send&&transceiver.rtpSender&&(params.encodings=transceiver.sendEncodingParameters,params.rtcp={cname:SDPUtils.localCName,compound:transceiver.rtcpParameters.compound},transceiver.recvEncodingParameters.length&&(params.rtcp.ssrc=transceiver.recvEncodingParameters[0].ssrc),transceiver.rtpSender.send(params)),recv&&transceiver.rtpReceiver&&params.codecs.length>0&&("video"===transceiver.kind&&transceiver.recvEncodingParameters&&edgeVersion<15019&&transceiver.recvEncodingParameters.forEach(function(p){delete p.rtx}),transceiver.recvEncodingParameters.length?params.encodings=transceiver.recvEncodingParameters:params.encodings=[{}],params.rtcp={compound:transceiver.rtcpParameters.compound},transceiver.rtcpParameters.cname&&(params.rtcp.cname=transceiver.rtcpParameters.cname),transceiver.sendEncodingParameters.length&&(params.rtcp.ssrc=transceiver.sendEncodingParameters[0].ssrc),transceiver.rtpReceiver.receive(params))},RTCPeerConnection.prototype.setLocalDescription=function(description){var sections,sessionpart,pc=this;if(-1===["offer","answer"].indexOf(description.type))return Promise.reject(makeError("TypeError",'Unsupported type "'+description.type+'"'));if(!isActionAllowedInSignalingState("setLocalDescription",description.type,pc.signalingState)||pc._isClosed)return Promise.reject(makeError("InvalidStateError","Can not set local "+description.type+" in state "+pc.signalingState));if("offer"===description.type)sections=SDPUtils.splitSections(description.sdp),sessionpart=sections.shift(),sections.forEach(function(mediaSection,sdpMLineIndex){var caps=SDPUtils.parseRtpParameters(mediaSection);pc.transceivers[sdpMLineIndex].localCapabilities=caps}),pc.transceivers.forEach(function(transceiver,sdpMLineIndex){pc._gather(transceiver.mid,sdpMLineIndex)});else if("answer"===description.type){sections=SDPUtils.splitSections(pc._remoteDescription.sdp),sessionpart=sections.shift();var isIceLite=SDPUtils.matchPrefix(sessionpart,"a=ice-lite").length>0;sections.forEach(function(mediaSection,sdpMLineIndex){var transceiver=pc.transceivers[sdpMLineIndex],iceGatherer=transceiver.iceGatherer,iceTransport=transceiver.iceTransport,dtlsTransport=transceiver.dtlsTransport,localCapabilities=transceiver.localCapabilities,remoteCapabilities=transceiver.remoteCapabilities;if(!(SDPUtils.isRejected(mediaSection)&&0===SDPUtils.matchPrefix(mediaSection,"a=bundle-only").length||transceiver.rejected)){var remoteIceParameters=SDPUtils.getIceParameters(mediaSection,sessionpart),remoteDtlsParameters=SDPUtils.getDtlsParameters(mediaSection,sessionpart);isIceLite&&(remoteDtlsParameters.role="server"),pc.usingBundle&&0!==sdpMLineIndex||(pc._gather(transceiver.mid,sdpMLineIndex),"new"===iceTransport.state&&iceTransport.start(iceGatherer,remoteIceParameters,isIceLite?"controlling":"controlled"),"new"===dtlsTransport.state&&dtlsTransport.start(remoteDtlsParameters));var params=getCommonCapabilities(localCapabilities,remoteCapabilities);pc._transceive(transceiver,params.codecs.length>0,!1)}})}return pc._localDescription={type:description.type,sdp:description.sdp},"offer"===description.type?pc._updateSignalingState("have-local-offer"):pc._updateSignalingState("stable"),Promise.resolve()},RTCPeerConnection.prototype.setRemoteDescription=function(description){var pc=this;if(-1===["offer","answer"].indexOf(description.type))return Promise.reject(makeError("TypeError",'Unsupported type "'+description.type+'"'));if(!isActionAllowedInSignalingState("setRemoteDescription",description.type,pc.signalingState)||pc._isClosed)return Promise.reject(makeError("InvalidStateError","Can not set remote "+description.type+" in state "+pc.signalingState));var streams={};pc.remoteStreams.forEach(function(stream){streams[stream.id]=stream});var receiverList=[],sections=SDPUtils.splitSections(description.sdp),sessionpart=sections.shift(),isIceLite=SDPUtils.matchPrefix(sessionpart,"a=ice-lite").length>0,usingBundle=SDPUtils.matchPrefix(sessionpart,"a=group:BUNDLE ").length>0;pc.usingBundle=usingBundle;var iceOptions=SDPUtils.matchPrefix(sessionpart,"a=ice-options:")[0];return pc.canTrickleIceCandidates=!!iceOptions&&iceOptions.substr(14).split(" ").indexOf("trickle")>=0,sections.forEach(function(mediaSection,sdpMLineIndex){var lines=SDPUtils.splitLines(mediaSection),kind=SDPUtils.getKind(mediaSection),rejected=SDPUtils.isRejected(mediaSection)&&0===SDPUtils.matchPrefix(mediaSection,"a=bundle-only").length,protocol=lines[0].substr(2).split(" ")[2],direction=SDPUtils.getDirection(mediaSection,sessionpart),remoteMsid=SDPUtils.parseMsid(mediaSection),mid=SDPUtils.getMid(mediaSection)||SDPUtils.generateIdentifier();if(rejected||"application"===kind&&("DTLS/SCTP"===protocol||"UDP/DTLS/SCTP"===protocol))pc.transceivers[sdpMLineIndex]={mid,kind,protocol,rejected:!0};else{var transceiver,iceGatherer,iceTransport,dtlsTransport,rtpReceiver,sendEncodingParameters,recvEncodingParameters,localCapabilities,track;!rejected&&pc.transceivers[sdpMLineIndex]&&pc.transceivers[sdpMLineIndex].rejected&&(pc.transceivers[sdpMLineIndex]=pc._createTransceiver(kind,!0));var remoteIceParameters,remoteDtlsParameters,remoteCapabilities=SDPUtils.parseRtpParameters(mediaSection);rejected||(remoteIceParameters=SDPUtils.getIceParameters(mediaSection,sessionpart),(remoteDtlsParameters=SDPUtils.getDtlsParameters(mediaSection,sessionpart)).role="client"),recvEncodingParameters=SDPUtils.parseRtpEncodingParameters(mediaSection);var rtcpParameters=SDPUtils.parseRtcpParameters(mediaSection),isComplete=SDPUtils.matchPrefix(mediaSection,"a=end-of-candidates",sessionpart).length>0,cands=SDPUtils.matchPrefix(mediaSection,"a=candidate:").map(function(cand){return SDPUtils.parseCandidate(cand)}).filter(function(cand){return 1===cand.component});if(("offer"===description.type||"answer"===description.type)&&!rejected&&usingBundle&&sdpMLineIndex>0&&pc.transceivers[sdpMLineIndex]&&(pc._disposeIceAndDtlsTransports(sdpMLineIndex),pc.transceivers[sdpMLineIndex].iceGatherer=pc.transceivers[0].iceGatherer,pc.transceivers[sdpMLineIndex].iceTransport=pc.transceivers[0].iceTransport,pc.transceivers[sdpMLineIndex].dtlsTransport=pc.transceivers[0].dtlsTransport,pc.transceivers[sdpMLineIndex].rtpSender&&pc.transceivers[sdpMLineIndex].rtpSender.setTransport(pc.transceivers[0].dtlsTransport),pc.transceivers[sdpMLineIndex].rtpReceiver&&pc.transceivers[sdpMLineIndex].rtpReceiver.setTransport(pc.transceivers[0].dtlsTransport)),"offer"!==description.type||rejected)"answer"!==description.type||rejected||(iceGatherer=(transceiver=pc.transceivers[sdpMLineIndex]).iceGatherer,iceTransport=transceiver.iceTransport,dtlsTransport=transceiver.dtlsTransport,rtpReceiver=transceiver.rtpReceiver,sendEncodingParameters=transceiver.sendEncodingParameters,localCapabilities=transceiver.localCapabilities,pc.transceivers[sdpMLineIndex].recvEncodingParameters=recvEncodingParameters,pc.transceivers[sdpMLineIndex].remoteCapabilities=remoteCapabilities,pc.transceivers[sdpMLineIndex].rtcpParameters=rtcpParameters,cands.length&&"new"===iceTransport.state&&(!isIceLite&&!isComplete||usingBundle&&0!==sdpMLineIndex?cands.forEach(function(candidate){maybeAddCandidate(transceiver.iceTransport,candidate)}):iceTransport.setRemoteCandidates(cands)),usingBundle&&0!==sdpMLineIndex||("new"===iceTransport.state&&iceTransport.start(iceGatherer,remoteIceParameters,"controlling"),"new"===dtlsTransport.state&&dtlsTransport.start(remoteDtlsParameters)),!getCommonCapabilities(transceiver.localCapabilities,transceiver.remoteCapabilities).codecs.filter(function(c){return"rtx"===c.name.toLowerCase()}).length&&transceiver.sendEncodingParameters[0].rtx&&delete transceiver.sendEncodingParameters[0].rtx,pc._transceive(transceiver,"sendrecv"===direction||"recvonly"===direction,"sendrecv"===direction||"sendonly"===direction),!rtpReceiver||"sendrecv"!==direction&&"sendonly"!==direction?delete transceiver.rtpReceiver:(track=rtpReceiver.track,remoteMsid?(streams[remoteMsid.stream]||(streams[remoteMsid.stream]=new window.MediaStream),addTrackToStreamAndFireEvent(track,streams[remoteMsid.stream]),receiverList.push([track,rtpReceiver,streams[remoteMsid.stream]])):(streams.default||(streams.default=new window.MediaStream),addTrackToStreamAndFireEvent(track,streams.default),receiverList.push([track,rtpReceiver,streams.default]))));else{(transceiver=pc.transceivers[sdpMLineIndex]||pc._createTransceiver(kind)).mid=mid,transceiver.iceGatherer||(transceiver.iceGatherer=pc._createIceGatherer(sdpMLineIndex,usingBundle)),cands.length&&"new"===transceiver.iceTransport.state&&(!isComplete||usingBundle&&0!==sdpMLineIndex?cands.forEach(function(candidate){maybeAddCandidate(transceiver.iceTransport,candidate)}):transceiver.iceTransport.setRemoteCandidates(cands)),localCapabilities=window.RTCRtpReceiver.getCapabilities(kind),edgeVersion<15019&&(localCapabilities.codecs=localCapabilities.codecs.filter(function(codec){return"rtx"!==codec.name})),sendEncodingParameters=transceiver.sendEncodingParameters||[{ssrc:1001*(2*sdpMLineIndex+2)}];var stream,isNewTrack=!1;"sendrecv"===direction||"sendonly"===direction?(isNewTrack=!transceiver.rtpReceiver,rtpReceiver=transceiver.rtpReceiver||new window.RTCRtpReceiver(transceiver.dtlsTransport,kind),isNewTrack&&(track=rtpReceiver.track,remoteMsid&&"-"===remoteMsid.stream||(remoteMsid?(streams[remoteMsid.stream]||(streams[remoteMsid.stream]=new window.MediaStream,Object.defineProperty(streams[remoteMsid.stream],"id",{get:function(){return remoteMsid.stream}})),Object.defineProperty(track,"id",{get:function(){return remoteMsid.track}}),stream=streams[remoteMsid.stream]):(streams.default||(streams.default=new window.MediaStream),stream=streams.default)),stream&&(addTrackToStreamAndFireEvent(track,stream),transceiver.associatedRemoteMediaStreams.push(stream)),receiverList.push([track,rtpReceiver,stream]))):transceiver.rtpReceiver&&transceiver.rtpReceiver.track&&(transceiver.associatedRemoteMediaStreams.forEach(function(s){var nativeTrack=s.getTracks().find(function(t){return t.id===transceiver.rtpReceiver.track.id});nativeTrack&&removeTrackFromStreamAndFireEvent(nativeTrack,s)}),transceiver.associatedRemoteMediaStreams=[]),transceiver.localCapabilities=localCapabilities,transceiver.remoteCapabilities=remoteCapabilities,transceiver.rtpReceiver=rtpReceiver,transceiver.rtcpParameters=rtcpParameters,transceiver.sendEncodingParameters=sendEncodingParameters,transceiver.recvEncodingParameters=recvEncodingParameters,pc._transceive(pc.transceivers[sdpMLineIndex],!1,isNewTrack)}}}),void 0===pc._dtlsRole&&(pc._dtlsRole="offer"===description.type?"active":"passive"),pc._remoteDescription={type:description.type,sdp:description.sdp},"offer"===description.type?pc._updateSignalingState("have-remote-offer"):pc._updateSignalingState("stable"),Object.keys(streams).forEach(function(sid){var stream=streams[sid];if(stream.getTracks().length){if(-1===pc.remoteStreams.indexOf(stream)){pc.remoteStreams.push(stream);var event=new Event("addstream");event.stream=stream,window.setTimeout(function(){pc._dispatchEvent("addstream",event)})}receiverList.forEach(function(item){var track=item[0],receiver=item[1];stream.id===item[2].id&&fireAddTrack(pc,track,receiver,[stream])})}}),receiverList.forEach(function(item){item[2]||fireAddTrack(pc,item[0],item[1],[])}),window.setTimeout(function(){pc&&pc.transceivers&&pc.transceivers.forEach(function(transceiver){transceiver.iceTransport&&"new"===transceiver.iceTransport.state&&transceiver.iceTransport.getRemoteCandidates().length>0&&(console.warn("Timeout for addRemoteCandidate. Consider sending an end-of-candidates notification"),transceiver.iceTransport.addRemoteCandidate({}))})},4e3),Promise.resolve()},RTCPeerConnection.prototype.close=function(){this.transceivers.forEach(function(transceiver){transceiver.iceTransport&&transceiver.iceTransport.stop(),transceiver.dtlsTransport&&transceiver.dtlsTransport.stop(),transceiver.rtpSender&&transceiver.rtpSender.stop(),transceiver.rtpReceiver&&transceiver.rtpReceiver.stop()}),this._isClosed=!0,this._updateSignalingState("closed")},RTCPeerConnection.prototype._updateSignalingState=function(newState){this.signalingState=newState;var event=new Event("signalingstatechange");this._dispatchEvent("signalingstatechange",event)},RTCPeerConnection.prototype._maybeFireNegotiationNeeded=function(){var pc=this;"stable"===this.signalingState&&!0!==this.needNegotiation&&(this.needNegotiation=!0,window.setTimeout(function(){if(pc.needNegotiation){pc.needNegotiation=!1;var event=new Event("negotiationneeded");pc._dispatchEvent("negotiationneeded",event)}},0))},RTCPeerConnection.prototype._updateIceConnectionState=function(){var newState,states={new:0,closed:0,checking:0,connected:0,completed:0,disconnected:0,failed:0};if(this.transceivers.forEach(function(transceiver){transceiver.iceTransport&&!transceiver.rejected&&states[transceiver.iceTransport.state]++}),newState="new",states.failed>0?newState="failed":states.checking>0?newState="checking":states.disconnected>0?newState="disconnected":states.new>0?newState="new":states.connected>0?newState="connected":states.completed>0&&(newState="completed"),newState!==this.iceConnectionState){this.iceConnectionState=newState;var event=new Event("iceconnectionstatechange");this._dispatchEvent("iceconnectionstatechange",event)}},RTCPeerConnection.prototype._updateConnectionState=function(){var newState,states={new:0,closed:0,connecting:0,connected:0,completed:0,disconnected:0,failed:0};if(this.transceivers.forEach(function(transceiver){transceiver.iceTransport&&transceiver.dtlsTransport&&!transceiver.rejected&&(states[transceiver.iceTransport.state]++,states[transceiver.dtlsTransport.state]++)}),states.connected+=states.completed,newState="new",states.failed>0?newState="failed":states.connecting>0?newState="connecting":states.disconnected>0?newState="disconnected":states.new>0?newState="new":states.connected>0&&(newState="connected"),newState!==this.connectionState){this.connectionState=newState;var event=new Event("connectionstatechange");this._dispatchEvent("connectionstatechange",event)}},RTCPeerConnection.prototype.createOffer=function(){var pc=this;if(pc._isClosed)return Promise.reject(makeError("InvalidStateError","Can not call createOffer after close"));var numAudioTracks=pc.transceivers.filter(function(t){return"audio"===t.kind}).length,numVideoTracks=pc.transceivers.filter(function(t){return"video"===t.kind}).length,offerOptions=arguments[0];if(offerOptions){if(offerOptions.mandatory||offerOptions.optional)throw new TypeError("Legacy mandatory/optional constraints not supported.");void 0!==offerOptions.offerToReceiveAudio&&(numAudioTracks=!0===offerOptions.offerToReceiveAudio?1:!1===offerOptions.offerToReceiveAudio?0:offerOptions.offerToReceiveAudio),void 0!==offerOptions.offerToReceiveVideo&&(numVideoTracks=!0===offerOptions.offerToReceiveVideo?1:!1===offerOptions.offerToReceiveVideo?0:offerOptions.offerToReceiveVideo)}for(pc.transceivers.forEach(function(transceiver){"audio"===transceiver.kind?--numAudioTracks<0&&(transceiver.wantReceive=!1):"video"===transceiver.kind&&--numVideoTracks<0&&(transceiver.wantReceive=!1)});numAudioTracks>0||numVideoTracks>0;)numAudioTracks>0&&(pc._createTransceiver("audio"),numAudioTracks--),numVideoTracks>0&&(pc._createTransceiver("video"),numVideoTracks--);var sdp=SDPUtils.writeSessionBoilerplate(pc._sdpSessionId,pc._sdpSessionVersion++);pc.transceivers.forEach(function(transceiver,sdpMLineIndex){var track=transceiver.track,kind=transceiver.kind,mid=transceiver.mid||SDPUtils.generateIdentifier();transceiver.mid=mid,transceiver.iceGatherer||(transceiver.iceGatherer=pc._createIceGatherer(sdpMLineIndex,pc.usingBundle));var localCapabilities=window.RTCRtpSender.getCapabilities(kind);edgeVersion<15019&&(localCapabilities.codecs=localCapabilities.codecs.filter(function(codec){return"rtx"!==codec.name})),localCapabilities.codecs.forEach(function(codec){"H264"===codec.name&&void 0===codec.parameters["level-asymmetry-allowed"]&&(codec.parameters["level-asymmetry-allowed"]="1"),transceiver.remoteCapabilities&&transceiver.remoteCapabilities.codecs&&transceiver.remoteCapabilities.codecs.forEach(function(remoteCodec){codec.name.toLowerCase()===remoteCodec.name.toLowerCase()&&codec.clockRate===remoteCodec.clockRate&&(codec.preferredPayloadType=remoteCodec.payloadType)})}),localCapabilities.headerExtensions.forEach(function(hdrExt){(transceiver.remoteCapabilities&&transceiver.remoteCapabilities.headerExtensions||[]).forEach(function(rHdrExt){hdrExt.uri===rHdrExt.uri&&(hdrExt.id=rHdrExt.id)})});var sendEncodingParameters=transceiver.sendEncodingParameters||[{ssrc:1001*(2*sdpMLineIndex+1)}];track&&edgeVersion>=15019&&"video"===kind&&!sendEncodingParameters[0].rtx&&(sendEncodingParameters[0].rtx={ssrc:sendEncodingParameters[0].ssrc+1}),transceiver.wantReceive&&(transceiver.rtpReceiver=new window.RTCRtpReceiver(transceiver.dtlsTransport,kind)),transceiver.localCapabilities=localCapabilities,transceiver.sendEncodingParameters=sendEncodingParameters}),"max-compat"!==pc._config.bundlePolicy&&(sdp+="a=group:BUNDLE "+pc.transceivers.map(function(t){return t.mid}).join(" ")+"\r\n"),sdp+="a=ice-options:trickle\r\n",pc.transceivers.forEach(function(transceiver,sdpMLineIndex){sdp+=writeMediaSection(transceiver,transceiver.localCapabilities,"offer",transceiver.stream,pc._dtlsRole),sdp+="a=rtcp-rsize\r\n",!transceiver.iceGatherer||"new"===pc.iceGatheringState||0!==sdpMLineIndex&&pc.usingBundle||(transceiver.iceGatherer.getLocalCandidates().forEach(function(cand){cand.component=1,sdp+="a="+SDPUtils.writeCandidate(cand)+"\r\n"}),"completed"===transceiver.iceGatherer.state&&(sdp+="a=end-of-candidates\r\n"))});var desc=new window.RTCSessionDescription({type:"offer",sdp});return Promise.resolve(desc)},RTCPeerConnection.prototype.createAnswer=function(){var pc=this;if(pc._isClosed)return Promise.reject(makeError("InvalidStateError","Can not call createAnswer after close"));if("have-remote-offer"!==pc.signalingState&&"have-local-pranswer"!==pc.signalingState)return Promise.reject(makeError("InvalidStateError","Can not call createAnswer in signalingState "+pc.signalingState));var sdp=SDPUtils.writeSessionBoilerplate(pc._sdpSessionId,pc._sdpSessionVersion++);pc.usingBundle&&(sdp+="a=group:BUNDLE "+pc.transceivers.map(function(t){return t.mid}).join(" ")+"\r\n"),sdp+="a=ice-options:trickle\r\n";var mediaSectionsInOffer=SDPUtils.getMediaSections(pc._remoteDescription.sdp).length;pc.transceivers.forEach(function(transceiver,sdpMLineIndex){if(!(sdpMLineIndex+1>mediaSectionsInOffer)){if(transceiver.rejected)return"application"===transceiver.kind?"DTLS/SCTP"===transceiver.protocol?sdp+="m=application 0 DTLS/SCTP 5000\r\n":sdp+="m=application 0 "+transceiver.protocol+" webrtc-datachannel\r\n":"audio"===transceiver.kind?sdp+="m=audio 0 UDP/TLS/RTP/SAVPF 0\r\na=rtpmap:0 PCMU/8000\r\n":"video"===transceiver.kind&&(sdp+="m=video 0 UDP/TLS/RTP/SAVPF 120\r\na=rtpmap:120 VP8/90000\r\n"),void(sdp+="c=IN IP4 0.0.0.0\r\na=inactive\r\na=mid:"+transceiver.mid+"\r\n");var localTrack;transceiver.stream&&("audio"===transceiver.kind?localTrack=transceiver.stream.getAudioTracks()[0]:"video"===transceiver.kind&&(localTrack=transceiver.stream.getVideoTracks()[0]),localTrack&&edgeVersion>=15019&&"video"===transceiver.kind&&!transceiver.sendEncodingParameters[0].rtx&&(transceiver.sendEncodingParameters[0].rtx={ssrc:transceiver.sendEncodingParameters[0].ssrc+1}));var commonCapabilities=getCommonCapabilities(transceiver.localCapabilities,transceiver.remoteCapabilities);!commonCapabilities.codecs.filter(function(c){return"rtx"===c.name.toLowerCase()}).length&&transceiver.sendEncodingParameters[0].rtx&&delete transceiver.sendEncodingParameters[0].rtx,sdp+=writeMediaSection(transceiver,commonCapabilities,"answer",transceiver.stream,pc._dtlsRole),transceiver.rtcpParameters&&transceiver.rtcpParameters.reducedSize&&(sdp+="a=rtcp-rsize\r\n")}});var desc=new window.RTCSessionDescription({type:"answer",sdp});return Promise.resolve(desc)},RTCPeerConnection.prototype.addIceCandidate=function(candidate){var sections,pc=this;return candidate&&void 0===candidate.sdpMLineIndex&&!candidate.sdpMid?Promise.reject(new TypeError("sdpMLineIndex or sdpMid required")):new Promise(function(resolve,reject){if(!pc._remoteDescription)return reject(makeError("InvalidStateError","Can not add ICE candidate without a remote description"));if(candidate&&""!==candidate.candidate){var sdpMLineIndex=candidate.sdpMLineIndex;if(candidate.sdpMid)for(var i=0;i<pc.transceivers.length;i++)if(pc.transceivers[i].mid===candidate.sdpMid){sdpMLineIndex=i;break}var transceiver=pc.transceivers[sdpMLineIndex];if(!transceiver)return reject(makeError("OperationError","Can not add ICE candidate"));if(transceiver.rejected)return resolve();var cand=Object.keys(candidate.candidate).length>0?SDPUtils.parseCandidate(candidate.candidate):{};if("tcp"===cand.protocol&&(0===cand.port||9===cand.port))return resolve();if(cand.component&&1!==cand.component)return resolve();if((0===sdpMLineIndex||sdpMLineIndex>0&&transceiver.iceTransport!==pc.transceivers[0].iceTransport)&&!maybeAddCandidate(transceiver.iceTransport,cand))return reject(makeError("OperationError","Can not add ICE candidate"));var candidateString=candidate.candidate.trim();0===candidateString.indexOf("a=")&&(candidateString=candidateString.substr(2)),(sections=SDPUtils.getMediaSections(pc._remoteDescription.sdp))[sdpMLineIndex]+="a="+(cand.type?candidateString:"end-of-candidates")+"\r\n",pc._remoteDescription.sdp=SDPUtils.getDescription(pc._remoteDescription.sdp)+sections.join("")}else for(var j=0;j<pc.transceivers.length&&(pc.transceivers[j].rejected||(pc.transceivers[j].iceTransport.addRemoteCandidate({}),(sections=SDPUtils.getMediaSections(pc._remoteDescription.sdp))[j]+="a=end-of-candidates\r\n",pc._remoteDescription.sdp=SDPUtils.getDescription(pc._remoteDescription.sdp)+sections.join(""),!pc.usingBundle));j++);resolve()})},RTCPeerConnection.prototype.getStats=function(selector){if(selector&&selector instanceof window.MediaStreamTrack){var senderOrReceiver=null;if(this.transceivers.forEach(function(transceiver){transceiver.rtpSender&&transceiver.rtpSender.track===selector?senderOrReceiver=transceiver.rtpSender:transceiver.rtpReceiver&&transceiver.rtpReceiver.track===selector&&(senderOrReceiver=transceiver.rtpReceiver)}),!senderOrReceiver)throw makeError("InvalidAccessError","Invalid selector.");return senderOrReceiver.getStats()}var promises=[];return this.transceivers.forEach(function(transceiver){["rtpSender","rtpReceiver","iceGatherer","iceTransport","dtlsTransport"].forEach(function(method){transceiver[method]&&promises.push(transceiver[method].getStats())})}),Promise.all(promises).then(function(allStats){var results=new Map;return allStats.forEach(function(stats){stats.forEach(function(stat){results.set(stat.id,stat)})}),results})},["RTCRtpSender","RTCRtpReceiver","RTCIceGatherer","RTCIceTransport","RTCDtlsTransport"].forEach(function(ortcObjectName){var obj=window[ortcObjectName];if(obj&&obj.prototype&&obj.prototype.getStats){var nativeGetstats=obj.prototype.getStats;obj.prototype.getStats=function(){return nativeGetstats.apply(this).then(function(nativeStats){var mapStats=new Map;return Object.keys(nativeStats).forEach(function(id){nativeStats[id].type=fixStatsType(nativeStats[id]),mapStats.set(id,nativeStats[id])}),mapStats})}}});var methods=["createOffer","createAnswer"];return methods.forEach(function(method){var nativeMethod=RTCPeerConnection.prototype[method];RTCPeerConnection.prototype[method]=function(){var args=arguments;return"function"==typeof args[0]||"function"==typeof args[1]?nativeMethod.apply(this,[arguments[2]]).then(function(description){"function"==typeof args[0]&&args[0].apply(null,[description])},function(error){"function"==typeof args[1]&&args[1].apply(null,[error])}):nativeMethod.apply(this,arguments)}}),(methods=["setLocalDescription","setRemoteDescription","addIceCandidate"]).forEach(function(method){var nativeMethod=RTCPeerConnection.prototype[method];RTCPeerConnection.prototype[method]=function(){var args=arguments;return"function"==typeof args[1]||"function"==typeof args[2]?nativeMethod.apply(this,arguments).then(function(){"function"==typeof args[1]&&args[1].apply(null)},function(error){"function"==typeof args[2]&&args[2].apply(null,[error])}):nativeMethod.apply(this,arguments)}}),["getStats"].forEach(function(method){var nativeMethod=RTCPeerConnection.prototype[method];RTCPeerConnection.prototype[method]=function(){var args=arguments;return"function"==typeof args[1]?nativeMethod.apply(this,arguments).then(function(){"function"==typeof args[1]&&args[1].apply(null)}):nativeMethod.apply(this,arguments)}}),RTCPeerConnection}},{sdp:108}],107:[function(require,module,exports){var buffer=require("buffer"),Buffer=buffer.Buffer;function copyProps(src,dst){for(var key in src)dst[key]=src[key]}function SafeBuffer(arg,encodingOrOffset,length){return Buffer(arg,encodingOrOffset,length)}Buffer.from&&Buffer.alloc&&Buffer.allocUnsafe&&Buffer.allocUnsafeSlow?module.exports=buffer:(copyProps(buffer,exports),exports.Buffer=SafeBuffer),SafeBuffer.prototype=Object.create(Buffer.prototype),copyProps(Buffer,SafeBuffer),SafeBuffer.from=function(arg,encodingOrOffset,length){if("number"==typeof arg)throw new TypeError("Argument must not be a number");return Buffer(arg,encodingOrOffset,length)},SafeBuffer.alloc=function(size,fill,encoding){if("number"!=typeof size)throw new TypeError("Argument must be a number");var buf=Buffer(size);return void 0!==fill?"string"==typeof encoding?buf.fill(fill,encoding):buf.fill(fill):buf.fill(0),buf},SafeBuffer.allocUnsafe=function(size){if("number"!=typeof size)throw new TypeError("Argument must be a number");return Buffer(size)},SafeBuffer.allocUnsafeSlow=function(size){if("number"!=typeof size)throw new TypeError("Argument must be a number");return buffer.SlowBuffer(size)}},{buffer:27}],108:[function(require,module,exports){"use strict";var SDPUtils={generateIdentifier:function(){return Math.random().toString(36).substr(2,10)}};SDPUtils.localCName=SDPUtils.generateIdentifier(),SDPUtils.splitLines=function(blob){return blob.trim().split("\n").map(function(line){return line.trim()})},SDPUtils.splitSections=function(blob){return blob.split("\nm=").map(function(part,index){return(index>0?"m="+part:part).trim()+"\r\n"})},SDPUtils.getDescription=function(blob){var sections=SDPUtils.splitSections(blob);return sections&&sections[0]},SDPUtils.getMediaSections=function(blob){var sections=SDPUtils.splitSections(blob);return sections.shift(),sections},SDPUtils.matchPrefix=function(blob,prefix){return SDPUtils.splitLines(blob).filter(function(line){return 0===line.indexOf(prefix)})},SDPUtils.parseCandidate=function(line){for(var parts,candidate={foundation:(parts=0===line.indexOf("a=candidate:")?line.substring(12).split(" "):line.substring(10).split(" "))[0],component:parseInt(parts[1],10),protocol:parts[2].toLowerCase(),priority:parseInt(parts[3],10),ip:parts[4],address:parts[4],port:parseInt(parts[5],10),type:parts[7]},i=8;i<parts.length;i+=2)switch(parts[i]){case"raddr":candidate.relatedAddress=parts[i+1];break;case"rport":candidate.relatedPort=parseInt(parts[i+1],10);break;case"tcptype":candidate.tcpType=parts[i+1];break;case"ufrag":candidate.ufrag=parts[i+1],candidate.usernameFragment=parts[i+1];break;default:candidate[parts[i]]=parts[i+1]}return candidate},SDPUtils.writeCandidate=function(candidate){var sdp=[];sdp.push(candidate.foundation),sdp.push(candidate.component),sdp.push(candidate.protocol.toUpperCase()),sdp.push(candidate.priority),sdp.push(candidate.address||candidate.ip),sdp.push(candidate.port);var type=candidate.type;return sdp.push("typ"),sdp.push(type),"host"!==type&&candidate.relatedAddress&&candidate.relatedPort&&(sdp.push("raddr"),sdp.push(candidate.relatedAddress),sdp.push("rport"),sdp.push(candidate.relatedPort)),candidate.tcpType&&"tcp"===candidate.protocol.toLowerCase()&&(sdp.push("tcptype"),sdp.push(candidate.tcpType)),(candidate.usernameFragment||candidate.ufrag)&&(sdp.push("ufrag"),sdp.push(candidate.usernameFragment||candidate.ufrag)),"candidate:"+sdp.join(" ")},SDPUtils.parseIceOptions=function(line){return line.substr(14).split(" ")},SDPUtils.parseRtpMap=function(line){var parts=line.substr(9).split(" "),parsed={payloadType:parseInt(parts.shift(),10)};return parts=parts[0].split("/"),parsed.name=parts[0],parsed.clockRate=parseInt(parts[1],10),parsed.channels=3===parts.length?parseInt(parts[2],10):1,parsed.numChannels=parsed.channels,parsed},SDPUtils.writeRtpMap=function(codec){var pt=codec.payloadType;void 0!==codec.preferredPayloadType&&(pt=codec.preferredPayloadType);var channels=codec.channels||codec.numChannels||1;return"a=rtpmap:"+pt+" "+codec.name+"/"+codec.clockRate+(1!==channels?"/"+channels:"")+"\r\n"},SDPUtils.parseExtmap=function(line){var parts=line.substr(9).split(" ");return{id:parseInt(parts[0],10),direction:parts[0].indexOf("/")>0?parts[0].split("/")[1]:"sendrecv",uri:parts[1]}},SDPUtils.writeExtmap=function(headerExtension){return"a=extmap:"+(headerExtension.id||headerExtension.preferredId)+(headerExtension.direction&&"sendrecv"!==headerExtension.direction?"/"+headerExtension.direction:"")+" "+headerExtension.uri+"\r\n"},SDPUtils.parseFmtp=function(line){for(var kv,parsed={},parts=line.substr(line.indexOf(" ")+1).split(";"),j=0;j<parts.length;j++)parsed[(kv=parts[j].trim().split("="))[0].trim()]=kv[1];return parsed},SDPUtils.writeFmtp=function(codec){var line="",pt=codec.payloadType;if(void 0!==codec.preferredPayloadType&&(pt=codec.preferredPayloadType),codec.parameters&&Object.keys(codec.parameters).length){var params=[];Object.keys(codec.parameters).forEach(function(param){codec.parameters[param]?params.push(param+"="+codec.parameters[param]):params.push(param)}),line+="a=fmtp:"+pt+" "+params.join(";")+"\r\n"}return line},SDPUtils.parseRtcpFb=function(line){var parts=line.substr(line.indexOf(" ")+1).split(" ");return{type:parts.shift(),parameter:parts.join(" ")}},SDPUtils.writeRtcpFb=function(codec){var lines="",pt=codec.payloadType;return void 0!==codec.preferredPayloadType&&(pt=codec.preferredPayloadType),codec.rtcpFeedback&&codec.rtcpFeedback.length&&codec.rtcpFeedback.forEach(function(fb){lines+="a=rtcp-fb:"+pt+" "+fb.type+(fb.parameter&&fb.parameter.length?" "+fb.parameter:"")+"\r\n"}),lines},SDPUtils.parseSsrcMedia=function(line){var sp=line.indexOf(" "),parts={ssrc:parseInt(line.substr(7,sp-7),10)},colon=line.indexOf(":",sp);return colon>-1?(parts.attribute=line.substr(sp+1,colon-sp-1),parts.value=line.substr(colon+1)):parts.attribute=line.substr(sp+1),parts},SDPUtils.parseSsrcGroup=function(line){var parts=line.substr(13).split(" ");return{semantics:parts.shift(),ssrcs:parts.map(function(ssrc){return parseInt(ssrc,10)})}},SDPUtils.getMid=function(mediaSection){var mid=SDPUtils.matchPrefix(mediaSection,"a=mid:")[0];if(mid)return mid.substr(6)},SDPUtils.parseFingerprint=function(line){var parts=line.substr(14).split(" ");return{algorithm:parts[0].toLowerCase(),value:parts[1]}},SDPUtils.getDtlsParameters=function(mediaSection,sessionpart){return{role:"auto",fingerprints:SDPUtils.matchPrefix(mediaSection+sessionpart,"a=fingerprint:").map(SDPUtils.parseFingerprint)}},SDPUtils.writeDtlsParameters=function(params,setupType){var sdp="a=setup:"+setupType+"\r\n";return params.fingerprints.forEach(function(fp){sdp+="a=fingerprint:"+fp.algorithm+" "+fp.value+"\r\n"}),sdp},SDPUtils.parseCryptoLine=function(line){var parts=line.substr(9).split(" ");return{tag:parseInt(parts[0],10),cryptoSuite:parts[1],keyParams:parts[2],sessionParams:parts.slice(3)}},SDPUtils.writeCryptoLine=function(parameters){return"a=crypto:"+parameters.tag+" "+parameters.cryptoSuite+" "+("object"==typeof parameters.keyParams?SDPUtils.writeCryptoKeyParams(parameters.keyParams):parameters.keyParams)+(parameters.sessionParams?" "+parameters.sessionParams.join(" "):"")+"\r\n"},SDPUtils.parseCryptoKeyParams=function(keyParams){if(0!==keyParams.indexOf("inline:"))return null;var parts=keyParams.substr(7).split("|");return{keyMethod:"inline",keySalt:parts[0],lifeTime:parts[1],mkiValue:parts[2]?parts[2].split(":")[0]:void 0,mkiLength:parts[2]?parts[2].split(":")[1]:void 0}},SDPUtils.writeCryptoKeyParams=function(keyParams){return keyParams.keyMethod+":"+keyParams.keySalt+(keyParams.lifeTime?"|"+keyParams.lifeTime:"")+(keyParams.mkiValue&&keyParams.mkiLength?"|"+keyParams.mkiValue+":"+keyParams.mkiLength:"")},SDPUtils.getCryptoParameters=function(mediaSection,sessionpart){return SDPUtils.matchPrefix(mediaSection+sessionpart,"a=crypto:").map(SDPUtils.parseCryptoLine)},SDPUtils.getIceParameters=function(mediaSection,sessionpart){var ufrag=SDPUtils.matchPrefix(mediaSection+sessionpart,"a=ice-ufrag:")[0],pwd=SDPUtils.matchPrefix(mediaSection+sessionpart,"a=ice-pwd:")[0];return ufrag&&pwd?{usernameFragment:ufrag.substr(12),password:pwd.substr(10)}:null},SDPUtils.writeIceParameters=function(params){return"a=ice-ufrag:"+params.usernameFragment+"\r\na=ice-pwd:"+params.password+"\r\n"},SDPUtils.parseRtpParameters=function(mediaSection){for(var description={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},mline=SDPUtils.splitLines(mediaSection)[0].split(" "),i=3;i<mline.length;i++){var pt=mline[i],rtpmapline=SDPUtils.matchPrefix(mediaSection,"a=rtpmap:"+pt+" ")[0];if(rtpmapline){var codec=SDPUtils.parseRtpMap(rtpmapline),fmtps=SDPUtils.matchPrefix(mediaSection,"a=fmtp:"+pt+" ");switch(codec.parameters=fmtps.length?SDPUtils.parseFmtp(fmtps[0]):{},codec.rtcpFeedback=SDPUtils.matchPrefix(mediaSection,"a=rtcp-fb:"+pt+" ").map(SDPUtils.parseRtcpFb),description.codecs.push(codec),codec.name.toUpperCase()){case"RED":case"ULPFEC":description.fecMechanisms.push(codec.name.toUpperCase())}}}return SDPUtils.matchPrefix(mediaSection,"a=extmap:").forEach(function(line){description.headerExtensions.push(SDPUtils.parseExtmap(line))}),description},SDPUtils.writeRtpDescription=function(kind,caps){var sdp="";sdp+="m="+kind+" ",sdp+=caps.codecs.length>0?"9":"0",sdp+=" UDP/TLS/RTP/SAVPF ",sdp+=caps.codecs.map(function(codec){return void 0!==codec.preferredPayloadType?codec.preferredPayloadType:codec.payloadType}).join(" ")+"\r\n",sdp+="c=IN IP4 0.0.0.0\r\n",sdp+="a=rtcp:9 IN IP4 0.0.0.0\r\n",caps.codecs.forEach(function(codec){sdp+=SDPUtils.writeRtpMap(codec),sdp+=SDPUtils.writeFmtp(codec),sdp+=SDPUtils.writeRtcpFb(codec)});var maxptime=0;return caps.codecs.forEach(function(codec){codec.maxptime>maxptime&&(maxptime=codec.maxptime)}),maxptime>0&&(sdp+="a=maxptime:"+maxptime+"\r\n"),sdp+="a=rtcp-mux\r\n",caps.headerExtensions&&caps.headerExtensions.forEach(function(extension){sdp+=SDPUtils.writeExtmap(extension)}),sdp},SDPUtils.parseRtpEncodingParameters=function(mediaSection){var secondarySsrc,encodingParameters=[],description=SDPUtils.parseRtpParameters(mediaSection),hasRed=-1!==description.fecMechanisms.indexOf("RED"),hasUlpfec=-1!==description.fecMechanisms.indexOf("ULPFEC"),ssrcs=SDPUtils.matchPrefix(mediaSection,"a=ssrc:").map(function(line){return SDPUtils.parseSsrcMedia(line)}).filter(function(parts){return"cname"===parts.attribute}),primarySsrc=ssrcs.length>0&&ssrcs[0].ssrc,flows=SDPUtils.matchPrefix(mediaSection,"a=ssrc-group:FID").map(function(line){return line.substr(17).split(" ").map(function(part){return parseInt(part,10)})});flows.length>0&&flows[0].length>1&&flows[0][0]===primarySsrc&&(secondarySsrc=flows[0][1]),description.codecs.forEach(function(codec){if("RTX"===codec.name.toUpperCase()&&codec.parameters.apt){var encParam={ssrc:primarySsrc,codecPayloadType:parseInt(codec.parameters.apt,10)};primarySsrc&&secondarySsrc&&(encParam.rtx={ssrc:secondarySsrc}),encodingParameters.push(encParam),hasRed&&((encParam=JSON.parse(JSON.stringify(encParam))).fec={ssrc:primarySsrc,mechanism:hasUlpfec?"red+ulpfec":"red"},encodingParameters.push(encParam))}}),0===encodingParameters.length&&primarySsrc&&encodingParameters.push({ssrc:primarySsrc});var bandwidth=SDPUtils.matchPrefix(mediaSection,"b=");return bandwidth.length&&(bandwidth=0===bandwidth[0].indexOf("b=TIAS:")?parseInt(bandwidth[0].substr(7),10):0===bandwidth[0].indexOf("b=AS:")?1e3*parseInt(bandwidth[0].substr(5),10)*.95-16e3:void 0,encodingParameters.forEach(function(params){params.maxBitrate=bandwidth})),encodingParameters},SDPUtils.parseRtcpParameters=function(mediaSection){var rtcpParameters={},remoteSsrc=SDPUtils.matchPrefix(mediaSection,"a=ssrc:").map(function(line){return SDPUtils.parseSsrcMedia(line)}).filter(function(obj){return"cname"===obj.attribute})[0];remoteSsrc&&(rtcpParameters.cname=remoteSsrc.value,rtcpParameters.ssrc=remoteSsrc.ssrc);var rsize=SDPUtils.matchPrefix(mediaSection,"a=rtcp-rsize");rtcpParameters.reducedSize=rsize.length>0,rtcpParameters.compound=0===rsize.length;var mux=SDPUtils.matchPrefix(mediaSection,"a=rtcp-mux");return rtcpParameters.mux=mux.length>0,rtcpParameters},SDPUtils.parseMsid=function(mediaSection){var parts,spec=SDPUtils.matchPrefix(mediaSection,"a=msid:");if(1===spec.length)return{stream:(parts=spec[0].substr(7).split(" "))[0],track:parts[1]};var planB=SDPUtils.matchPrefix(mediaSection,"a=ssrc:").map(function(line){return SDPUtils.parseSsrcMedia(line)}).filter(function(msidParts){return"msid"===msidParts.attribute});return planB.length>0?{stream:(parts=planB[0].value.split(" "))[0],track:parts[1]}:void 0},SDPUtils.parseSctpDescription=function(mediaSection){var maxMessageSize,mline=SDPUtils.parseMLine(mediaSection),maxSizeLine=SDPUtils.matchPrefix(mediaSection,"a=max-message-size:");maxSizeLine.length>0&&(maxMessageSize=parseInt(maxSizeLine[0].substr(19),10)),isNaN(maxMessageSize)&&(maxMessageSize=65536);var sctpPort=SDPUtils.matchPrefix(mediaSection,"a=sctp-port:");if(sctpPort.length>0)return{port:parseInt(sctpPort[0].substr(12),10),protocol:mline.fmt,maxMessageSize};if(SDPUtils.matchPrefix(mediaSection,"a=sctpmap:").length>0){var parts=SDPUtils.matchPrefix(mediaSection,"a=sctpmap:")[0].substr(10).split(" ");return{port:parseInt(parts[0],10),protocol:parts[1],maxMessageSize}}},SDPUtils.writeSctpDescription=function(media,sctp){var output=[];return output="DTLS/SCTP"!==media.protocol?["m="+media.kind+" 9 "+media.protocol+" "+sctp.protocol+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctp-port:"+sctp.port+"\r\n"]:["m="+media.kind+" 9 "+media.protocol+" "+sctp.port+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctpmap:"+sctp.port+" "+sctp.protocol+" 65535\r\n"],void 0!==sctp.maxMessageSize&&output.push("a=max-message-size:"+sctp.maxMessageSize+"\r\n"),output.join("")},SDPUtils.generateSessionId=function(){return Math.random().toString().substr(2,21)},SDPUtils.writeSessionBoilerplate=function(sessId,sessVer,sessUser){var version=void 0!==sessVer?sessVer:2;return"v=0\r\no="+(sessUser||"thisisadapterortc")+" "+(sessId||SDPUtils.generateSessionId())+" "+version+" IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\n"},SDPUtils.writeMediaSection=function(transceiver,caps,type,stream){var sdp=SDPUtils.writeRtpDescription(transceiver.kind,caps);if(sdp+=SDPUtils.writeIceParameters(transceiver.iceGatherer.getLocalParameters()),sdp+=SDPUtils.writeDtlsParameters(transceiver.dtlsTransport.getLocalParameters(),"offer"===type?"actpass":"active"),sdp+="a=mid:"+transceiver.mid+"\r\n",transceiver.direction?sdp+="a="+transceiver.direction+"\r\n":transceiver.rtpSender&&transceiver.rtpReceiver?sdp+="a=sendrecv\r\n":transceiver.rtpSender?sdp+="a=sendonly\r\n":transceiver.rtpReceiver?sdp+="a=recvonly\r\n":sdp+="a=inactive\r\n",transceiver.rtpSender){var msid="msid:"+stream.id+" "+transceiver.rtpSender.track.id+"\r\n";sdp+="a="+msid,sdp+="a=ssrc:"+transceiver.sendEncodingParameters[0].ssrc+" "+msid,transceiver.sendEncodingParameters[0].rtx&&(sdp+="a=ssrc:"+transceiver.sendEncodingParameters[0].rtx.ssrc+" "+msid,sdp+="a=ssrc-group:FID "+transceiver.sendEncodingParameters[0].ssrc+" "+transceiver.sendEncodingParameters[0].rtx.ssrc+"\r\n")}return sdp+="a=ssrc:"+transceiver.sendEncodingParameters[0].ssrc+" cname:"+SDPUtils.localCName+"\r\n",transceiver.rtpSender&&transceiver.sendEncodingParameters[0].rtx&&(sdp+="a=ssrc:"+transceiver.sendEncodingParameters[0].rtx.ssrc+" cname:"+SDPUtils.localCName+"\r\n"),sdp},SDPUtils.getDirection=function(mediaSection,sessionpart){for(var lines=SDPUtils.splitLines(mediaSection),i=0;i<lines.length;i++)switch(lines[i]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return lines[i].substr(2)}return sessionpart?SDPUtils.getDirection(sessionpart):"sendrecv"},SDPUtils.getKind=function(mediaSection){return SDPUtils.splitLines(mediaSection)[0].split(" ")[0].substr(2)},SDPUtils.isRejected=function(mediaSection){return"0"===mediaSection.split(" ",2)[1]},SDPUtils.parseMLine=function(mediaSection){var parts=SDPUtils.splitLines(mediaSection)[0].substr(2).split(" ");return{kind:parts[0],port:parseInt(parts[1],10),protocol:parts[2],fmt:parts.slice(3).join(" ")}},SDPUtils.parseOLine=function(mediaSection){var parts=SDPUtils.matchPrefix(mediaSection,"o=")[0].substr(2).split(" ");return{username:parts[0],sessionId:parts[1],sessionVersion:parseInt(parts[2],10),netType:parts[3],addressType:parts[4],address:parts[5]}},SDPUtils.isValidSDP=function(blob){if("string"!=typeof blob||0===blob.length)return!1;for(var lines=SDPUtils.splitLines(blob),i=0;i<lines.length;i++)if(lines[i].length<2||"="!==lines[i].charAt(1))return!1;return!0},"object"==typeof module&&(module.exports=SDPUtils)},{}],109:[function(require,module,exports){module.exports=Stream;var EE=require("events").EventEmitter;function Stream(){EE.call(this)}require("inherits")(Stream,EE),Stream.Readable=require("readable-stream/readable.js"),Stream.Writable=require("readable-stream/writable.js"),Stream.Duplex=require("readable-stream/duplex.js"),Stream.Transform=require("readable-stream/transform.js"),Stream.PassThrough=require("readable-stream/passthrough.js"),Stream.Stream=Stream,Stream.prototype.pipe=function(dest,options){var source=this;function ondata(chunk){dest.writable&&!1===dest.write(chunk)&&source.pause&&source.pause()}function ondrain(){source.readable&&source.resume&&source.resume()}source.on("data",ondata),dest.on("drain",ondrain),dest._isStdio||options&&!1===options.end||(source.on("end",onend),source.on("close",onclose));var didOnEnd=!1;function onend(){didOnEnd||(didOnEnd=!0,dest.end())}function onclose(){didOnEnd||(didOnEnd=!0,"function"==typeof dest.destroy&&dest.destroy())}function onerror(er){if(cleanup(),0===EE.listenerCount(this,"error"))throw er}function cleanup(){source.removeListener("data",ondata),dest.removeListener("drain",ondrain),source.removeListener("end",onend),source.removeListener("close",onclose),source.removeListener("error",onerror),dest.removeListener("error",onerror),source.removeListener("end",cleanup),source.removeListener("close",cleanup),dest.removeListener("close",cleanup)}return source.on("error",onerror),dest.on("error",onerror),source.on("end",cleanup),source.on("close",cleanup),dest.on("close",cleanup),dest.emit("pipe",source),dest}},{events:37,inherits:41,"readable-stream/duplex.js":90,"readable-stream/passthrough.js":101,"readable-stream/readable.js":102,"readable-stream/transform.js":103,"readable-stream/writable.js":104}],110:[function(require,module,exports){var global,factory;global=this,factory=function(exports){"use strict";function getWebSocketImplementation(){if(void 0===globalThis.WebSocket)try{return require("ws")}catch(err){throw new Error('You must install the "ws" package to use Strophe in nodejs.')}return globalThis.WebSocket}const WebSocket=getWebSocketImplementation();function getDOMParserImplementation(){let DOMParserImplementation=globalThis.DOMParser;if(void 0===DOMParserImplementation)try{DOMParserImplementation=require("@xmldom/xmldom").DOMParser}catch(err){throw new Error('You must install the "@xmldom/xmldom" package to use Strophe in nodejs.')}return DOMParserImplementation}const DOMParser=getDOMParserImplementation();function getDummyXMLDOMDocument(){if("undefined"==typeof document)try{return(new(0,require("@xmldom/xmldom").DOMImplementation)).createDocument("jabber:client","strophe",null)}catch(err){throw new Error('You must install the "@xmldom/xmldom" package to use Strophe in nodejs.')}return document.implementation.createDocument("jabber:client","strophe",null)}var shims=Object.freeze({__proto__:null,WebSocket,DOMParser,getDummyXMLDOMDocument});const NS={HTTPBIND:"http://jabber.org/protocol/httpbind",BOSH:"urn:xmpp:xbosh",CLIENT:"jabber:client",AUTH:"jabber:iq:auth",ROSTER:"jabber:iq:roster",PROFILE:"jabber:iq:profile",DISCO_INFO:"http://jabber.org/protocol/disco#info",DISCO_ITEMS:"http://jabber.org/protocol/disco#items",MUC:"http://jabber.org/protocol/muc",SASL:"urn:ietf:params:xml:ns:xmpp-sasl",STREAM:"http://etherx.jabber.org/streams",FRAMING:"urn:ietf:params:xml:ns:xmpp-framing",BIND:"urn:ietf:params:xml:ns:xmpp-bind",SESSION:"urn:ietf:params:xml:ns:xmpp-session",VERSION:"jabber:iq:version",STANZAS:"urn:ietf:params:xml:ns:xmpp-stanzas",XHTML_IM:"http://jabber.org/protocol/xhtml-im",XHTML:"http://www.w3.org/1999/xhtml"},XHTML={tags:["a","blockquote","br","cite","em","img","li","ol","p","span","strong","ul","body"],attributes:{a:["href"],blockquote:["style"],br:[],cite:["style"],em:[],img:["src","alt","style","height","width"],li:["style"],ol:["style"],p:["style"],span:["style"],strong:[],ul:["style"],body:[]},css:["background-color","color","font-family","font-size","font-style","font-weight","margin-left","margin-right","text-align","text-decoration"]},Status={ERROR:0,CONNECTING:1,CONNFAIL:2,AUTHENTICATING:3,AUTHFAIL:4,CONNECTED:5,DISCONNECTED:6,DISCONNECTING:7,ATTACHED:8,REDIRECT:9,CONNTIMEOUT:10,BINDREQUIRED:11,ATTACHFAIL:12,RECONNECTING:13},ErrorCondition={BAD_FORMAT:"bad-format",CONFLICT:"conflict",MISSING_JID_NODE:"x-strophe-bad-non-anon-jid",NO_AUTH_MECH:"no-auth-mech",UNKNOWN_REASON:"unknown"},LogLevel={DEBUG:0,INFO:1,WARN:2,ERROR:3,FATAL:4},ElementType={NORMAL:1,TEXT:3,CDATA:4,FRAGMENT:11};function $build(name,attrs){return new Builder(name,attrs)}function $msg(attrs){return new Builder("message",attrs)}function $iq(attrs){return new Builder("iq",attrs)}function $pres(attrs){return new Builder("presence",attrs)}class Builder{constructor(name,attrs){"presence"!==name&&"message"!==name&&"iq"!==name||(attrs&&!attrs.xmlns?attrs.xmlns=NS.CLIENT:attrs||(attrs={xmlns:NS.CLIENT})),this.nodeTree=xmlElement(name,attrs),this.node=this.nodeTree}tree(){return this.nodeTree}toString(){return serialize(this.nodeTree)}up(){return this.node=this.node.parentElement,this}root(){return this.node=this.nodeTree,this}attrs(moreattrs){for(const k in moreattrs)Object.prototype.hasOwnProperty.call(moreattrs,k)&&(null!=moreattrs[k]?this.node.setAttribute(k,moreattrs[k].toString()):this.node.removeAttribute(k));return this}c(name,attrs,text){const child=xmlElement(name,attrs,text);return this.node.appendChild(child),"string"!=typeof text&&"number"!=typeof text&&(this.node=child),this}cnode(elem){let impNode;const xmlGen=xmlGenerator();try{impNode=void 0!==xmlGen.importNode}catch(e){impNode=!1}const newElem=impNode?xmlGen.importNode(elem,!0):copyElement(elem);return this.node.appendChild(newElem),this.node=newElem,this}t(text){const child=xmlTextNode(text);return this.node.appendChild(child),this}h(html){const fragment=xmlGenerator().createElement("body");fragment.innerHTML=html;const xhtml=createHtml(fragment);for(;xhtml.childNodes.length>0;)this.node.appendChild(xhtml.childNodes[0]);return this}}function utf16to8(str){let out="";const len=str.length;for(let i=0;i<len;i++){const c=str.charCodeAt(i);c>=0&&c<=127?out+=str.charAt(i):c>2047?(out+=String.fromCharCode(224|c>>12&15),out+=String.fromCharCode(128|c>>6&63),out+=String.fromCharCode(128|63&c)):(out+=String.fromCharCode(192|c>>6&31),out+=String.fromCharCode(128|63&c))}return out}function xorArrayBuffers(x,y){const xIntArray=new Uint8Array(x),yIntArray=new Uint8Array(y),zIntArray=new Uint8Array(x.byteLength);for(let i=0;i<x.byteLength;i++)zIntArray[i]=xIntArray[i]^yIntArray[i];return zIntArray.buffer}function arrayBufToBase64(buffer){let binary="";const bytes=new Uint8Array(buffer),len=bytes.byteLength;for(let i=0;i<len;i++)binary+=String.fromCharCode(bytes[i]);return btoa(binary)}function base64ToArrayBuf(str){var _Uint8Array$from;return null===(_Uint8Array$from=Uint8Array.from(atob(str),c=>c.charCodeAt(0)))||void 0===_Uint8Array$from?void 0:_Uint8Array$from.buffer}function stringToArrayBuf(str){return(new TextEncoder).encode(str).buffer}function addCookies(cookies){"undefined"==typeof document&&Strophe.log(Strophe.LogLevel.ERROR,"addCookies: not adding any cookies, since there's no document object"),cookies=cookies||{};for(const cookieName in cookies)if(Object.prototype.hasOwnProperty.call(cookies,cookieName)){let expires="",domain="",path="";const cookieObj=cookies[cookieName],isObj="object"==typeof cookieObj,cookieValue=escape(unescape(isObj?cookieObj.value:cookieObj));isObj&&(expires=cookieObj.expires?";expires="+cookieObj.expires:"",domain=cookieObj.domain?";domain="+cookieObj.domain:"",path=cookieObj.path?";path="+cookieObj.path:""),document.cookie=cookieName+"="+cookieValue+expires+domain+path}}let _xmlGenerator=null;function xmlGenerator(){return _xmlGenerator||(_xmlGenerator=getDummyXMLDOMDocument()),_xmlGenerator}function xmlTextNode(text){return xmlGenerator().createTextNode(text)}function xmlHtmlNode(html){return(new DOMParser).parseFromString(html,"text/xml")}function xmlElement(name,attrs,text){if(!name)return null;const node=xmlGenerator().createElement(name);if(!text||"string"!=typeof text&&"number"!=typeof text){if("string"==typeof attrs||"number"==typeof attrs)return node.appendChild(xmlTextNode(attrs.toString())),node;if(!attrs)return node}else node.appendChild(xmlTextNode(text.toString()));if(Array.isArray(attrs))for(const attr of attrs)Array.isArray(attr)&&null!=attr[0]&&null!=attr[1]&&node.setAttribute(attr[0],attr[1]);else if("object"==typeof attrs)for(const k of Object.keys(attrs))k&&null!=attrs[k]&&node.setAttribute(k,attrs[k].toString());return node}function validTag(tag){for(let i=0;i<XHTML.tags.length;i++)if(tag===XHTML.tags[i])return!0;return!1}function validAttribute(tag,attribute){const attrs=XHTML.attributes[tag];if((null==attrs?void 0:attrs.length)>0)for(let i=0;i<attrs.length;i++)if(attribute===attrs[i])return!0;return!1}function validCSS(style){for(let i=0;i<XHTML.css.length;i++)if(style===XHTML.css[i])return!0;return!1}function createFromHtmlElement(elem){let el;const tag=elem.nodeName.toLowerCase();if(validTag(tag))try{if(el=xmlElement(tag),tag in XHTML.attributes){const attrs=XHTML.attributes[tag];for(let i=0;i<attrs.length;i++){const attribute=attrs[i];let value=elem.getAttribute(attribute);var _value$cssText;if(null!=value&&""!==value)if("style"===attribute&&"object"==typeof value&&(value=null!==(_value$cssText=value.cssText)&&void 0!==_value$cssText?_value$cssText:value),"style"===attribute){const css=[],cssAttrs=value.split(";");for(let j=0;j<cssAttrs.length;j++){const attr=cssAttrs[j].split(":"),cssName=attr[0].replace(/^\s*/,"").replace(/\s*$/,"").toLowerCase();if(validCSS(cssName)){const cssValue=attr[1].replace(/^\s*/,"").replace(/\s*$/,"");css.push(cssName+": "+cssValue)}}css.length>0&&(value=css.join("; "),el.setAttribute(attribute,value))}else el.setAttribute(attribute,value)}for(let i=0;i<elem.childNodes.length;i++)el.appendChild(createHtml(elem.childNodes[i]))}}catch(e){el=xmlTextNode("")}else{el=xmlGenerator().createDocumentFragment();for(let i=0;i<elem.childNodes.length;i++)el.appendChild(createHtml(elem.childNodes[i]))}return el}function createHtml(node){if(node.nodeType===ElementType.NORMAL)return createFromHtmlElement(node);if(node.nodeType===ElementType.FRAGMENT){const el=xmlGenerator().createDocumentFragment();for(let i=0;i<node.childNodes.length;i++)el.appendChild(createHtml(node.childNodes[i]));return el}return node.nodeType===ElementType.TEXT?xmlTextNode(node.nodeValue):void 0}function copyElement(node){let out;if(node.nodeType===ElementType.NORMAL){const el=node;out=xmlElement(el.tagName);for(let i=0;i<el.attributes.length;i++)out.setAttribute(el.attributes[i].nodeName,el.attributes[i].value);for(let i=0;i<el.childNodes.length;i++)out.appendChild(copyElement(el.childNodes[i]))}else node.nodeType===ElementType.TEXT&&(out=xmlGenerator().createTextNode(node.nodeValue));return out}function xmlescape(text){return text=(text=(text=(text=(text=text.replace(/\&/g,"&amp;")).replace(/</g,"&lt;")).replace(/>/g,"&gt;")).replace(/'/g,"&apos;")).replace(/"/g,"&quot;")}function xmlunescape(text){return text=(text=(text=(text=(text=text.replace(/\&amp;/g,"&")).replace(/&lt;/g,"<")).replace(/&gt;/g,">")).replace(/&apos;/g,"'")).replace(/&quot;/g,'"')}function serialize(elem){if(!elem)return null;const el=elem instanceof Builder?elem.tree():elem,names=[...Array(el.attributes.length).keys()].map(i=>el.attributes[i].nodeName);names.sort();let result=names.reduce((a,n)=>`${a} ${n}="${xmlescape(el.attributes.getNamedItem(n).value)}"`,`<${el.nodeName}`);if(el.childNodes.length>0){result+=">";for(let i=0;i<el.childNodes.length;i++){const child=el.childNodes[i];switch(child.nodeType){case ElementType.NORMAL:result+=serialize(child);break;case ElementType.TEXT:result+=xmlescape(child.nodeValue);break;case ElementType.CDATA:result+="<![CDATA["+child.nodeValue+"]]>"}}result+="</"+el.nodeName+">"}else result+="/>";return result}function forEachChild(elem,elemName,func){for(let i=0;i<elem.childNodes.length;i++){const childNode=elem.childNodes[i];childNode.nodeType!==ElementType.NORMAL||elemName&&!this.isTagEqual(childNode,elemName)||func(childNode)}}function isTagEqual(el,name){return el.tagName===name}function getText(elem){var _elem$childNodes;if(!elem)return null;let str="";null!==(_elem$childNodes=elem.childNodes)&&void 0!==_elem$childNodes&&_elem$childNodes.length||elem.nodeType!==ElementType.TEXT||(str+=elem.nodeValue);for(let i=0;null!==(_ref=i<(null===(_elem$childNodes2=elem.childNodes)||void 0===_elem$childNodes2?void 0:_elem$childNodes2.length))&&void 0!==_ref&&_ref;i++){var _ref,_elem$childNodes2;elem.childNodes[i].nodeType===ElementType.TEXT&&(str+=elem.childNodes[i].nodeValue)}return xmlescape(str)}function escapeNode(node){return"string"!=typeof node?node:node.replace(/^\s+|\s+$/g,"").replace(/\\/g,"\\5c").replace(/ /g,"\\20").replace(/\"/g,"\\22").replace(/\&/g,"\\26").replace(/\'/g,"\\27").replace(/\//g,"\\2f").replace(/:/g,"\\3a").replace(/</g,"\\3c").replace(/>/g,"\\3e").replace(/@/g,"\\40")}function unescapeNode(node){return"string"!=typeof node?node:node.replace(/\\20/g," ").replace(/\\22/g,'"').replace(/\\26/g,"&").replace(/\\27/g,"'").replace(/\\2f/g,"/").replace(/\\3a/g,":").replace(/\\3c/g,"<").replace(/\\3e/g,">").replace(/\\40/g,"@").replace(/\\5c/g,"\\")}function getNodeFromJid(jid){return jid.indexOf("@")<0?null:jid.split("@")[0]}function getDomainFromJid(jid){const bare=getBareJidFromJid(jid);if(bare.indexOf("@")<0)return bare;{const parts=bare.split("@");return parts.splice(0,1),parts.join("@")}}function getResourceFromJid(jid){if(!jid)return null;const s=jid.split("/");return s.length<2?null:(s.splice(0,1),s.join("/"))}function getBareJidFromJid(jid){return jid?jid.split("/")[0]:null}const utils={utf16to8,xorArrayBuffers,arrayBufToBase64,base64ToArrayBuf,stringToArrayBuf,addCookies};var utils$1=Object.freeze({__proto__:null,utf16to8,xorArrayBuffers,arrayBufToBase64,base64ToArrayBuf,stringToArrayBuf,addCookies,xmlGenerator,xmlTextNode,xmlHtmlNode,xmlElement,validTag,validAttribute,validCSS,createHtml,copyElement,xmlescape,xmlunescape,serialize,forEachChild,isTagEqual,getText,escapeNode,unescapeNode,getNodeFromJid,getDomainFromJid,getResourceFromJid,getBareJidFromJid,default:utils});class Handler{constructor(handler,ns,name,type,id,from,options){this.handler=handler,this.ns=ns,this.name=name,this.type=type,this.id=id,this.options=options||{matchBareFromJid:!1,ignoreNamespaceFragment:!1},this.options.matchBareFromJid?this.from=from?getBareJidFromJid(from):null:this.from=from,this.user=!0}getNamespace(elem){let elNamespace=elem.getAttribute("xmlns");return elNamespace&&this.options.ignoreNamespaceFragment&&(elNamespace=elNamespace.split("#")[0]),elNamespace}namespaceMatch(elem){let nsMatch=!1;return!this.ns||(forEachChild(elem,null,elem=>{this.getNamespace(elem)===this.ns&&(nsMatch=!0)}),nsMatch||this.getNamespace(elem)===this.ns)}isMatch(elem){let from=elem.getAttribute("from");this.options.matchBareFromJid&&(from=getBareJidFromJid(from));const elem_type=elem.getAttribute("type");return!(!this.namespaceMatch(elem)||this.name&&!Strophe.isTagEqual(elem,this.name)||this.type&&(Array.isArray(this.type)?-1===this.type.indexOf(elem_type):elem_type!==this.type)||this.id&&elem.getAttribute("id")!==this.id||this.from&&from!==this.from)}run(elem){let result=null;try{result=this.handler(elem)}catch(e){throw Strophe._handleError(e),e}return result}toString(){return"{Handler: "+this.handler+"("+this.name+","+this.id+","+this.ns+")}"}}class TimedHandler{constructor(period,handler){this.period=period,this.handler=handler,this.lastCalled=(new Date).getTime(),this.user=!0}run(){return this.lastCalled=(new Date).getTime(),this.handler()}reset(){this.lastCalled=(new Date).getTime()}toString(){return"{TimedHandler: "+this.handler+"("+this.period+")}"}}function atob$2(data){if(0===arguments.length)throw new TypeError("1 argument required, but only 0 present.");if((data=(data=`${data}`).replace(/[ \t\n\f\r]/g,"")).length%4==0&&(data=data.replace(/==?$/,"")),data.length%4==1||/[^+/0-9A-Za-z]/.test(data))return null;let output="",buffer=0,accumulatedBits=0;for(let i=0;i<data.length;i++)buffer<<=6,buffer|=atobLookup(data[i]),accumulatedBits+=6,24===accumulatedBits&&(output+=String.fromCharCode((16711680&buffer)>>16),output+=String.fromCharCode((65280&buffer)>>8),output+=String.fromCharCode(255&buffer),buffer=accumulatedBits=0);return 12===accumulatedBits?(buffer>>=4,output+=String.fromCharCode(buffer)):18===accumulatedBits&&(buffer>>=2,output+=String.fromCharCode((65280&buffer)>>8),output+=String.fromCharCode(255&buffer)),output}const keystr$1="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";function atobLookup(chr){const index=keystr$1.indexOf(chr);return index<0?void 0:index}function btoa$2(s){if(0===arguments.length)throw new TypeError("1 argument required, but only 0 present.");let i;for(s=`${s}`,i=0;i<s.length;i++)if(s.charCodeAt(i)>255)return null;let out="";for(i=0;i<s.length;i+=3){const groupsOfSix=[void 0,void 0,void 0,void 0];groupsOfSix[0]=s.charCodeAt(i)>>2,groupsOfSix[1]=(3&s.charCodeAt(i))<<4,s.length>i+1&&(groupsOfSix[1]|=s.charCodeAt(i+1)>>4,groupsOfSix[2]=(15&s.charCodeAt(i+1))<<2),s.length>i+2&&(groupsOfSix[2]|=s.charCodeAt(i+2)>>6,groupsOfSix[3]=63&s.charCodeAt(i+2));for(let j=0;j<groupsOfSix.length;j++)void 0===groupsOfSix[j]?out+="=":out+=btoaLookup(groupsOfSix[j])}return out}const keystr="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";function btoaLookup(index){if(index>=0&&index<64)return keystr[index]}var abab={atob:atob$2,btoa:btoa$2};class SessionError extends Error{constructor(message){super(message),this.name="StropheSessionError"}}class Connection{constructor(service,options={}){this.service=service,this.options=options,this.setProtocol(),this.jid="",this.domain=null,this.features=null,this._sasl_data={},this.do_bind=!1,this.do_session=!1,this.mechanisms={},this.timedHandlers=[],this.handlers=[],this.removeTimeds=[],this.removeHandlers=[],this.addTimeds=[],this.addHandlers=[],this.protocolErrorHandlers={HTTP:{},websocket:{}},this._idleTimeout=null,this._disconnectTimeout=null,this.authenticated=!1,this.connected=!1,this.disconnecting=!1,this.do_authentication=!0,this.paused=!1,this.restored=!1,this._data=[],this._uniqueId=0,this._sasl_success_handler=null,this._sasl_failure_handler=null,this._sasl_challenge_handler=null,this.maxRetries=5,this._idleTimeout=setTimeout(()=>this._onIdle(),100),addCookies(this.options.cookies),this.registerSASLMechanisms(this.options.mechanisms),this.iqFallbackHandler=new Handler(iq=>this.send($iq({type:"error",id:iq.getAttribute("id")}).c("error",{type:"cancel"}).c("service-unavailable",{xmlns:Strophe.NS.STANZAS})),null,"iq",["get","set"]);for(const k in Strophe._connectionPlugins)if(Object.prototype.hasOwnProperty.call(Strophe._connectionPlugins,k)){const F=function(){};F.prototype=Strophe._connectionPlugins[k],this[k]=new F,this[k].init(this)}}setProtocol(){const proto=this.options.protocol||"";this.options.worker?this._proto=new Strophe.WorkerWebsocket(this):0===this.service.indexOf("ws:")||0===this.service.indexOf("wss:")||0===proto.indexOf("ws")?this._proto=new Strophe.Websocket(this):this._proto=new Strophe.Bosh(this)}reset(){this._proto._reset(),this.do_session=!1,this.do_bind=!1,this.timedHandlers=[],this.handlers=[],this.removeTimeds=[],this.removeHandlers=[],this.addTimeds=[],this.addHandlers=[],this.authenticated=!1,this.connected=!1,this.disconnecting=!1,this.restored=!1,this._data=[],this._requests=[],this._uniqueId=0}pause(){this.paused=!0}resume(){this.paused=!1}getUniqueId(suffix){const uuid="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(c){const r=16*Math.random()|0;return("x"===c?r:3&r|8).toString(16)});return"string"==typeof suffix||"number"==typeof suffix?uuid+":"+suffix:uuid+""}addProtocolErrorHandler(protocol,status_code,callback){this.protocolErrorHandlers[protocol][status_code]=callback}connect(jid,pass,callback,wait,hold,route,authcid,disconnection_timeout=3e3){this.jid=jid,this.authzid=Strophe.getBareJidFromJid(this.jid),this.authcid=authcid||Strophe.getNodeFromJid(this.jid),this.pass=pass,this.scram_keys=null,this.connect_callback=callback,this.disconnecting=!1,this.connected=!1,this.authenticated=!1,this.restored=!1,this.disconnection_timeout=disconnection_timeout,this.domain=Strophe.getDomainFromJid(this.jid),this._changeConnectStatus(Status.CONNECTING,null),this._proto._connect(wait,hold,route)}attach(jid,sid,rid,callback,wait,hold,wind){if(this._proto instanceof Strophe.Bosh&&"string"==typeof jid)return this._proto._attach(jid,sid,rid,callback,wait,hold,wind);if(this._proto instanceof Strophe.WorkerWebsocket&&"function"==typeof jid){const callback=jid;return this._proto._attach(callback)}throw new SessionError('The "attach" method is not available for your connection protocol')}restore(jid,callback,wait,hold,wind){if(!(this._proto instanceof Strophe.Bosh&&this._sessionCachingSupported()))throw new SessionError('The "restore" method can only be used with a BOSH connection.');this._sessionCachingSupported()&&this._proto._restore(jid,callback,wait,hold,wind)}_sessionCachingSupported(){if(this._proto instanceof Strophe.Bosh){if(!JSON)return!1;try{sessionStorage.setItem("_strophe_","_strophe_"),sessionStorage.removeItem("_strophe_")}catch(e){return!1}return!0}return!1}xmlInput(elem){}xmlOutput(elem){}rawInput(data){}rawOutput(data){}nextValidRid(rid){}send(stanza){if(null!==stanza){if(Array.isArray(stanza))stanza.forEach(s=>this._queueData(s instanceof Builder?s.tree():s));else{const el=stanza instanceof Builder?stanza.tree():stanza;this._queueData(el)}this._proto._send()}}flush(){clearTimeout(this._idleTimeout),this._onIdle()}sendPresence(stanza,callback,errback,timeout){let timeoutHandler=null;const el=stanza instanceof Builder?stanza.tree():stanza;let id=el.getAttribute("id");if(id||(id=this.getUniqueId("sendPresence"),el.setAttribute("id",id)),"function"==typeof callback||"function"==typeof errback){const handler=this.addHandler(stanza=>{timeoutHandler&&this.deleteTimedHandler(timeoutHandler),"error"===stanza.getAttribute("type")?null==errback||errback(stanza):callback&&callback(stanza)},null,"presence",null,id);timeout&&(timeoutHandler=this.addTimedHandler(timeout,()=>(this.deleteHandler(handler),null==errback||errback(null),!1)))}return this.send(el),id}sendIQ(stanza,callback,errback,timeout){let timeoutHandler=null;const el=stanza instanceof Builder?stanza.tree():stanza;let id=el.getAttribute("id");if(id||(id=this.getUniqueId("sendIQ"),el.setAttribute("id",id)),"function"==typeof callback||"function"==typeof errback){const handler=this.addHandler(stanza=>{timeoutHandler&&this.deleteTimedHandler(timeoutHandler);const iqtype=stanza.getAttribute("type");if("result"===iqtype)null==callback||callback(stanza);else{if("error"!==iqtype){const error=new Error(`Got bad IQ type of ${iqtype}`);throw error.name="StropheError",error}null==errback||errback(stanza)}},null,"iq",["error","result"],id);timeout&&(timeoutHandler=this.addTimedHandler(timeout,()=>(this.deleteHandler(handler),null==errback||errback(null),!1)))}return this.send(el),id}_queueData(element){if(null===element||!element.tagName||!element.childNodes){const error=new Error("Cannot queue non-DOMElement.");throw error.name="StropheError",error}this._data.push(element)}_sendRestart(){this._data.push("restart"),this._proto._sendRestart(),this._idleTimeout=setTimeout(()=>this._onIdle(),100)}addTimedHandler(period,handler){const thand=new Strophe.TimedHandler(period,handler);return this.addTimeds.push(thand),thand}deleteTimedHandler(handRef){this.removeTimeds.push(handRef)}addHandler(handler,ns,name,type,id,from,options){const hand=new Handler(handler,ns,name,type,id,from,options);return this.addHandlers.push(hand),hand}deleteHandler(handRef){this.removeHandlers.push(handRef);const i=this.addHandlers.indexOf(handRef);i>=0&&this.addHandlers.splice(i,1)}registerSASLMechanisms(mechanisms){this.mechanisms={},(mechanisms||[Strophe.SASLAnonymous,Strophe.SASLExternal,Strophe.SASLOAuthBearer,Strophe.SASLXOAuth2,Strophe.SASLPlain,Strophe.SASLSHA1,Strophe.SASLSHA256,Strophe.SASLSHA384,Strophe.SASLSHA512]).forEach(m=>this.registerSASLMechanism(m))}registerSASLMechanism(Mechanism){const mechanism=new Mechanism;this.mechanisms[mechanism.mechname]=mechanism}disconnect(reason){if(this._changeConnectStatus(Status.DISCONNECTING,reason),reason?Strophe.warn("Disconnect was called because: "+reason):Strophe.info("Disconnect was called"),this.connected){let pres=null;this.disconnecting=!0,this.authenticated&&(pres=$pres({xmlns:Strophe.NS.CLIENT,type:"unavailable"})),this._disconnectTimeout=this._addSysTimedHandler(this.disconnection_timeout,this._onDisconnectTimeout.bind(this)),this._proto._disconnect(pres)}else Strophe.warn("Disconnect was called before Strophe connected to the server"),this._proto._abortAllRequests(),this._doDisconnect()}_changeConnectStatus(status,condition,elem){for(const k in Strophe._connectionPlugins)if(Object.prototype.hasOwnProperty.call(Strophe._connectionPlugins,k)){const plugin=this[k];if(plugin.statusChanged)try{plugin.statusChanged(status,condition)}catch(err){Strophe.error(`${k} plugin caused an exception changing status: ${err}`)}}if(this.connect_callback)try{this.connect_callback(status,condition,elem)}catch(e){Strophe._handleError(e),Strophe.error(`User connection callback caused an exception: ${e}`)}}_doDisconnect(condition){"number"==typeof this._idleTimeout&&clearTimeout(this._idleTimeout),null!==this._disconnectTimeout&&(this.deleteTimedHandler(this._disconnectTimeout),this._disconnectTimeout=null),Strophe.debug("_doDisconnect was called"),this._proto._doDisconnect(),this.authenticated=!1,this.disconnecting=!1,this.restored=!1,this.handlers=[],this.timedHandlers=[],this.removeTimeds=[],this.removeHandlers=[],this.addTimeds=[],this.addHandlers=[],this._changeConnectStatus(Status.DISCONNECTED,condition),this.connected=!1}_dataRecv(req,raw){const elem="_reqToData"in this._proto?this._proto._reqToData(req):req;if(null===elem)return;for(this.xmlInput!==Strophe.Connection.prototype.xmlInput&&(elem.nodeName===this._proto.strip&&elem.childNodes.length?this.xmlInput(elem.childNodes[0]):this.xmlInput(elem)),this.rawInput!==Strophe.Connection.prototype.rawInput&&(raw?this.rawInput(raw):this.rawInput(Strophe.serialize(elem)));this.removeHandlers.length>0;){const hand=this.removeHandlers.pop(),i=this.handlers.indexOf(hand);i>=0&&this.handlers.splice(i,1)}for(;this.addHandlers.length>0;)this.handlers.push(this.addHandlers.pop());if(this.disconnecting&&this._proto._emptyQueue())return void this._doDisconnect();const type=elem.getAttribute("type");if(null!==type&&"terminate"===type){if(this.disconnecting)return;let cond=elem.getAttribute("condition");const conflict=elem.getElementsByTagName("conflict");return null!==cond?("remote-stream-error"===cond&&conflict.length>0&&(cond="conflict"),this._changeConnectStatus(Status.CONNFAIL,cond)):this._changeConnectStatus(Status.CONNFAIL,Strophe.ErrorCondition.UNKNOWN_REASON),void this._doDisconnect(cond)}Strophe.forEachChild(elem,null,child=>{const matches=[];this.handlers=this.handlers.reduce((handlers,handler)=>{try{!handler.isMatch(child)||!this.authenticated&&handler.user?handlers.push(handler):(handler.run(child)&&handlers.push(handler),matches.push(handler))}catch(e){Strophe.warn("Removing Strophe handlers due to uncaught exception: "+e.message)}return handlers},[]),!matches.length&&this.iqFallbackHandler.isMatch(child)&&this.iqFallbackHandler.run(child)})}_connect_cb(req,_callback,raw){let bodyWrap,hasFeatures;Strophe.debug("_connect_cb was called"),this.connected=!0;try{bodyWrap="_reqToData"in this._proto?this._proto._reqToData(req):req}catch(e){if(e.name!==Strophe.ErrorCondition.BAD_FORMAT)throw e;this._changeConnectStatus(Status.CONNFAIL,Strophe.ErrorCondition.BAD_FORMAT),this._doDisconnect(Strophe.ErrorCondition.BAD_FORMAT)}if(!bodyWrap)return;if(this.xmlInput!==Strophe.Connection.prototype.xmlInput&&(bodyWrap.nodeName===this._proto.strip&&bodyWrap.childNodes.length?this.xmlInput(bodyWrap.childNodes[0]):this.xmlInput(bodyWrap)),this.rawInput!==Strophe.Connection.prototype.rawInput&&(raw?this.rawInput(raw):this.rawInput(Strophe.serialize(bodyWrap))),this._proto._connect_cb(bodyWrap)===Status.CONNFAIL)return;if(hasFeatures=bodyWrap.getElementsByTagNameNS?bodyWrap.getElementsByTagNameNS(Strophe.NS.STREAM,"features").length>0:bodyWrap.getElementsByTagName("stream:features").length>0||bodyWrap.getElementsByTagName("features").length>0,!hasFeatures)return void this._proto._no_auth_received(_callback);const matched=Array.from(bodyWrap.getElementsByTagName("mechanism")).map(m=>this.mechanisms[m.textContent]).filter(m=>m);0!==matched.length||0!==bodyWrap.getElementsByTagName("auth").length?!1!==this.do_authentication&&this.authenticate(matched):this._proto._no_auth_received(_callback)}sortMechanismsByPriority(mechanisms){for(let i=0;i<mechanisms.length-1;++i){let higher=i;for(let j=i+1;j<mechanisms.length;++j)mechanisms[j].priority>mechanisms[higher].priority&&(higher=j);if(higher!==i){const swap=mechanisms[i];mechanisms[i]=mechanisms[higher],mechanisms[higher]=swap}}return mechanisms}authenticate(matched){this._attemptSASLAuth(matched)||this._attemptLegacyAuth()}_attemptSASLAuth(mechanisms){mechanisms=this.sortMechanismsByPriority(mechanisms||[]);let mechanism_found=!1;for(let i=0;i<mechanisms.length;++i){if(!mechanisms[i].test(this))continue;this._sasl_success_handler=this._addSysHandler(this._sasl_success_cb.bind(this),null,"success",null,null),this._sasl_failure_handler=this._addSysHandler(this._sasl_failure_cb.bind(this),null,"failure",null,null),this._sasl_challenge_handler=this._addSysHandler(this._sasl_challenge_cb.bind(this),null,"challenge",null,null),this._sasl_mechanism=mechanisms[i],this._sasl_mechanism.onStart(this);const request_auth_exchange=$build("auth",{xmlns:Strophe.NS.SASL,mechanism:this._sasl_mechanism.mechname});if(this._sasl_mechanism.isClientFirst){const response=this._sasl_mechanism.clientChallenge(this);request_auth_exchange.t(abab.btoa(response))}this.send(request_auth_exchange.tree()),mechanism_found=!0;break}return mechanism_found}async _sasl_challenge_cb(elem){const challenge=abab.atob(getText(elem)),response=await this._sasl_mechanism.onChallenge(this,challenge),stanza=$build("response",{xmlns:Strophe.NS.SASL});return response&&stanza.t(abab.btoa(response)),this.send(stanza.tree()),!0}_attemptLegacyAuth(){null===Strophe.getNodeFromJid(this.jid)?(this._changeConnectStatus(Status.CONNFAIL,Strophe.ErrorCondition.MISSING_JID_NODE),this.disconnect(Strophe.ErrorCondition.MISSING_JID_NODE)):(this._changeConnectStatus(Status.AUTHENTICATING,null),this._addSysHandler(this._onLegacyAuthIQResult.bind(this),null,null,null,"_auth_1"),this.send($iq({type:"get",to:this.domain,id:"_auth_1"}).c("query",{xmlns:Strophe.NS.AUTH}).c("username",{}).t(Strophe.getNodeFromJid(this.jid)).tree()))}_onLegacyAuthIQResult(){const pass="string"==typeof this.pass?this.pass:"",iq=$iq({type:"set",id:"_auth_2"}).c("query",{xmlns:Strophe.NS.AUTH}).c("username",{}).t(Strophe.getNodeFromJid(this.jid)).up().c("password").t(pass);return Strophe.getResourceFromJid(this.jid)||(this.jid=Strophe.getBareJidFromJid(this.jid)+"/strophe"),iq.up().c("resource",{}).t(Strophe.getResourceFromJid(this.jid)),this._addSysHandler(this._auth2_cb.bind(this),null,null,null,"_auth_2"),this.send(iq.tree()),!1}_sasl_success_cb(elem){if(this._sasl_data["server-signature"]){let serverSignature;const attribMatch=/([a-z]+)=([^,]+)(,|$)/,matches=abab.atob(getText(elem)).match(attribMatch);if("v"===matches[1]&&(serverSignature=matches[2]),serverSignature!==this._sasl_data["server-signature"])return this.deleteHandler(this._sasl_failure_handler),this._sasl_failure_handler=null,this._sasl_challenge_handler&&(this.deleteHandler(this._sasl_challenge_handler),this._sasl_challenge_handler=null),this._sasl_data={},this._sasl_failure_cb(null)}Strophe.info("SASL authentication succeeded."),this._sasl_data.keys&&(this.scram_keys=this._sasl_data.keys),this._sasl_mechanism&&this._sasl_mechanism.onSuccess(),this.deleteHandler(this._sasl_failure_handler),this._sasl_failure_handler=null,this._sasl_challenge_handler&&(this.deleteHandler(this._sasl_challenge_handler),this._sasl_challenge_handler=null);const streamfeature_handlers=[],wrapper=(handlers,elem)=>{for(;handlers.length;)this.deleteHandler(handlers.pop());return this._onStreamFeaturesAfterSASL(elem),!1};return streamfeature_handlers.push(this._addSysHandler(elem=>wrapper(streamfeature_handlers,elem),null,"stream:features",null,null)),streamfeature_handlers.push(this._addSysHandler(elem=>wrapper(streamfeature_handlers,elem),Strophe.NS.STREAM,"features",null,null)),this._sendRestart(),!1}_onStreamFeaturesAfterSASL(elem){this.features=elem;for(let i=0;i<elem.childNodes.length;i++){const child=elem.childNodes[i];"bind"===child.nodeName&&(this.do_bind=!0),"session"===child.nodeName&&(this.do_session=!0)}return this.do_bind?(this.options.explicitResourceBinding?this._changeConnectStatus(Status.BINDREQUIRED,null):this.bind(),!1):(this._changeConnectStatus(Status.AUTHFAIL,null),!1)}bind(){if(!this.do_bind)return void Strophe.log(Strophe.LogLevel.INFO,'Strophe.Connection.prototype.bind called but "do_bind" is false');this._addSysHandler(this._onResourceBindResultIQ.bind(this),null,null,null,"_bind_auth_2");const resource=Strophe.getResourceFromJid(this.jid);resource?this.send($iq({type:"set",id:"_bind_auth_2"}).c("bind",{xmlns:Strophe.NS.BIND}).c("resource",{}).t(resource).tree()):this.send($iq({type:"set",id:"_bind_auth_2"}).c("bind",{xmlns:Strophe.NS.BIND}).tree())}_onResourceBindResultIQ(elem){if("error"===elem.getAttribute("type")){let condition;return Strophe.warn("Resource binding failed."),elem.getElementsByTagName("conflict").length>0&&(condition=Strophe.ErrorCondition.CONFLICT),this._changeConnectStatus(Status.AUTHFAIL,condition,elem),!1}const bind=elem.getElementsByTagName("bind");if(!(bind.length>0))return Strophe.warn("Resource binding failed."),this._changeConnectStatus(Status.AUTHFAIL,null,elem),!1;{const jidNode=bind[0].getElementsByTagName("jid");jidNode.length>0&&(this.authenticated=!0,this.jid=getText(jidNode[0]),this.do_session?this._establishSession():this._changeConnectStatus(Status.CONNECTED,null))}}_establishSession(){if(!this.do_session)throw new Error(`Strophe.Connection.prototype._establishSession called but apparently ${Strophe.NS.SESSION} wasn't advertised by the server`);this._addSysHandler(this._onSessionResultIQ.bind(this),null,null,null,"_session_auth_2"),this.send($iq({type:"set",id:"_session_auth_2"}).c("session",{xmlns:Strophe.NS.SESSION}).tree())}_onSessionResultIQ(elem){if("result"===elem.getAttribute("type"))this.authenticated=!0,this._changeConnectStatus(Status.CONNECTED,null);else if("error"===elem.getAttribute("type"))return this.authenticated=!1,Strophe.warn("Session creation failed."),this._changeConnectStatus(Status.AUTHFAIL,null,elem),!1;return!1}_sasl_failure_cb(elem){return this._sasl_success_handler&&(this.deleteHandler(this._sasl_success_handler),this._sasl_success_handler=null),this._sasl_challenge_handler&&(this.deleteHandler(this._sasl_challenge_handler),this._sasl_challenge_handler=null),this._sasl_mechanism&&this._sasl_mechanism.onFailure(),this._changeConnectStatus(Status.AUTHFAIL,null,elem),!1}_auth2_cb(elem){return"result"===elem.getAttribute("type")?(this.authenticated=!0,this._changeConnectStatus(Status.CONNECTED,null)):"error"===elem.getAttribute("type")&&(this._changeConnectStatus(Status.AUTHFAIL,null,elem),this.disconnect("authentication failed")),!1}_addSysTimedHandler(period,handler){const thand=new TimedHandler(period,handler);return thand.user=!1,this.addTimeds.push(thand),thand}_addSysHandler(handler,ns,name,type,id){const hand=new Handler(handler,ns,name,type,id);return hand.user=!1,this.addHandlers.push(hand),hand}_onDisconnectTimeout(){return Strophe.debug("_onDisconnectTimeout was called"),this._changeConnectStatus(Status.CONNTIMEOUT,null),this._proto._onDisconnectTimeout(),this._doDisconnect(),!1}_onIdle(){for(;this.addTimeds.length>0;)this.timedHandlers.push(this.addTimeds.pop());for(;this.removeTimeds.length>0;){const thand=this.removeTimeds.pop(),i=this.timedHandlers.indexOf(thand);i>=0&&this.timedHandlers.splice(i,1)}const now=(new Date).getTime(),newList=[];for(let i=0;i<this.timedHandlers.length;i++){const thand=this.timedHandlers[i];!this.authenticated&&thand.user||(thand.lastCalled+thand.period-now<=0?thand.run()&&newList.push(thand):newList.push(thand))}this.timedHandlers=newList,clearTimeout(this._idleTimeout),this._proto._onIdle(),this.connected&&(this._idleTimeout=setTimeout(()=>this._onIdle(),100))}}class SASLMechanism{constructor(name,isClientFirst,priority){this.mechname=name,this.isClientFirst=isClientFirst,this.priority=priority}test(connection){return!0}onStart(connection){this._connection=connection}onChallenge(connection,challenge){throw new Error("You should implement challenge handling!")}clientChallenge(connection){if(!this.isClientFirst)throw new Error("clientChallenge should not be called if isClientFirst is false!");return this.onChallenge(connection)}onFailure(){this._connection=null}onSuccess(){this._connection=null}}class SASLAnonymous extends SASLMechanism{constructor(mechname="ANONYMOUS",isClientFirst=!1,priority=20){super(mechname,isClientFirst,priority)}test(connection){return null===connection.authcid}}class SASLExternal extends SASLMechanism{constructor(mechname="EXTERNAL",isClientFirst=!0,priority=10){super(mechname,isClientFirst,priority)}onChallenge(connection){return connection.authcid===connection.authzid?"":connection.authzid}}class SASLOAuthBearer extends SASLMechanism{constructor(mechname="OAUTHBEARER",isClientFirst=!0,priority=40){super(mechname,isClientFirst,priority)}test(connection){return null!==connection.pass}onChallenge(connection){let auth_str="n,";return null!==connection.authcid&&(auth_str=auth_str+"a="+connection.authzid),auth_str+=",",auth_str+="",auth_str+="auth=Bearer ",auth_str+=connection.pass,auth_str+="",auth_str+="",utils.utf16to8(auth_str)}}class SASLPlain extends SASLMechanism{constructor(mechname="PLAIN",isClientFirst=!0,priority=50){super(mechname,isClientFirst,priority)}test(connection){return null!==connection.authcid}onChallenge(connection){const{authcid,authzid,domain,pass}=connection;if(!domain)throw new Error("SASLPlain onChallenge: domain is not defined!");let auth_str=authzid!==`${authcid}@${domain}`?authzid:"";return auth_str+="\0",auth_str+=authcid,auth_str+="\0",auth_str+=pass,utils.utf16to8(auth_str)}}async function scramClientProof(authMessage,clientKey,hashName){const storedKey=await crypto.subtle.importKey("raw",await crypto.subtle.digest(hashName,clientKey),{name:"HMAC",hash:hashName},!1,["sign"]),clientSignature=await crypto.subtle.sign("HMAC",storedKey,utils.stringToArrayBuf(authMessage));return utils.xorArrayBuffers(clientKey,clientSignature)}function scramParseChallenge(challenge){let nonce,salt,iter;const attribMatch=/([a-z]+)=([^,]+)(,|$)/;for(;challenge.match(attribMatch);){const matches=challenge.match(attribMatch);switch(challenge=challenge.replace(matches[0],""),matches[1]){case"r":nonce=matches[2];break;case"s":salt=utils.base64ToArrayBuf(matches[2]);break;case"i":iter=parseInt(matches[2],10);break;case"m":return}}if(isNaN(iter)||iter<4096)Strophe.warn("Failing SCRAM authentication because server supplied iteration count < 4096.");else{if(salt)return{nonce,salt,iter};Strophe.warn("Failing SCRAM authentication because server supplied incorrect salt.")}}async function scramDeriveKeys(password,salt,iter,hashName,hashBits){const saltedPasswordBits=await crypto.subtle.deriveBits({name:"PBKDF2",salt,iterations:iter,hash:{name:hashName}},await crypto.subtle.importKey("raw",utils.stringToArrayBuf(password),"PBKDF2",!1,["deriveBits"]),hashBits),saltedPassword=await crypto.subtle.importKey("raw",saltedPasswordBits,{name:"HMAC",hash:hashName},!1,["sign"]);return{ck:await crypto.subtle.sign("HMAC",saltedPassword,utils.stringToArrayBuf("Client Key")),sk:await crypto.subtle.sign("HMAC",saltedPassword,utils.stringToArrayBuf("Server Key"))}}async function scramServerSign(authMessage,sk,hashName){const serverKey=await crypto.subtle.importKey("raw",sk,{name:"HMAC",hash:hashName},!1,["sign"]);return crypto.subtle.sign("HMAC",serverKey,utils.stringToArrayBuf(authMessage))}function generate_cnonce(){const bytes=new Uint8Array(16);return utils.arrayBufToBase64(crypto.getRandomValues(bytes).buffer)}const scram={async scramResponse(connection,challenge,hashName,hashBits){const cnonce=connection._sasl_data.cnonce,challengeData=scramParseChallenge(challenge);if(!challengeData&&(null==challengeData?void 0:challengeData.nonce.slice(0,cnonce.length))!==cnonce)return Strophe.warn("Failing SCRAM authentication because server supplied incorrect nonce."),connection._sasl_data={},connection._sasl_failure_cb();let clientKey,serverKey;const{pass}=connection;if("string"==typeof connection.pass||connection.pass instanceof String){const keys=await scramDeriveKeys(pass,challengeData.salt,challengeData.iter,hashName,hashBits);clientKey=keys.ck,serverKey=keys.sk}else{if((null==pass?void 0:pass.name)!==hashName||(null==pass?void 0:pass.salt)!==utils.arrayBufToBase64(challengeData.salt)||(null==pass?void 0:pass.iter)!==challengeData.iter)return connection._sasl_failure_cb();{const{ck,sk}=pass;clientKey=utils.base64ToArrayBuf(ck),serverKey=utils.base64ToArrayBuf(sk)}}const clientFirstMessageBare=connection._sasl_data["client-first-message-bare"],serverFirstMessage=challenge,clientFinalMessageBare=`c=biws,r=${challengeData.nonce}`,authMessage=`${clientFirstMessageBare},${serverFirstMessage},${clientFinalMessageBare}`,clientProof=await scramClientProof(authMessage,clientKey,hashName),serverSignature=await scramServerSign(authMessage,serverKey,hashName);return connection._sasl_data["server-signature"]=utils.arrayBufToBase64(serverSignature),connection._sasl_data.keys={name:hashName,iter:challengeData.iter,salt:utils.arrayBufToBase64(challengeData.salt),ck:utils.arrayBufToBase64(clientKey),sk:utils.arrayBufToBase64(serverKey)},`${clientFinalMessageBare},p=${utils.arrayBufToBase64(clientProof)}`},clientChallenge(connection,test_cnonce){const cnonce=test_cnonce||generate_cnonce(),client_first_message_bare=`n=${connection.authcid},r=${cnonce}`;return connection._sasl_data.cnonce=cnonce,connection._sasl_data["client-first-message-bare"]=client_first_message_bare,`n,,${client_first_message_bare}`}};class SASLSHA1 extends SASLMechanism{constructor(mechname="SCRAM-SHA-1",isClientFirst=!0,priority=60){super(mechname,isClientFirst,priority)}test(connection){return null!==connection.authcid}async onChallenge(connection,challenge){return await scram.scramResponse(connection,challenge,"SHA-1",160)}clientChallenge(connection,test_cnonce){return scram.clientChallenge(connection,test_cnonce)}}class SASLSHA256 extends SASLMechanism{constructor(mechname="SCRAM-SHA-256",isClientFirst=!0,priority=70){super(mechname,isClientFirst,priority)}test(connection){return null!==connection.authcid}async onChallenge(connection,challenge){return await scram.scramResponse(connection,challenge,"SHA-256",256)}clientChallenge(connection,test_cnonce){return scram.clientChallenge(connection,test_cnonce)}}class SASLSHA384 extends SASLMechanism{constructor(mechname="SCRAM-SHA-384",isClientFirst=!0,priority=71){super(mechname,isClientFirst,priority)}test(connection){return null!==connection.authcid}async onChallenge(connection,challenge){return await scram.scramResponse(connection,challenge,"SHA-384",384)}clientChallenge(connection,test_cnonce){return scram.clientChallenge(connection,test_cnonce)}}class SASLSHA512 extends SASLMechanism{constructor(mechname="SCRAM-SHA-512",isClientFirst=!0,priority=72){super(mechname,isClientFirst,priority)}test(connection){return null!==connection.authcid}async onChallenge(connection,challenge){return await scram.scramResponse(connection,challenge,"SHA-512",512)}clientChallenge(connection,test_cnonce){return scram.clientChallenge(connection,test_cnonce)}}class SASLXOAuth2 extends SASLMechanism{constructor(mechname="X-OAUTH2",isClientFirst=!0,priority=30){super(mechname,isClientFirst,priority)}test(connection){return null!==connection.pass}onChallenge(connection){let auth_str="\0";return null!==connection.authcid&&(auth_str+=connection.authzid),auth_str+="\0",auth_str+=connection.pass,utils.utf16to8(auth_str)}}class Request{constructor(elem,func,rid,sends=0){this.id=++Strophe._requestId,this.xmlData=elem,this.data=Strophe.serialize(elem),this.origFunc=func,this.func=func,this.rid=rid,this.date=NaN,this.sends=sends,this.abort=!1,this.dead=null,this.age=()=>this.date?((new Date).valueOf()-this.date.valueOf())/1e3:0,this.timeDead=()=>this.dead?((new Date).valueOf()-this.dead.valueOf())/1e3:0,this.xhr=this._newXHR()}getResponse(){var _this$xhr$responseXML;let node=null===(_this$xhr$responseXML=this.xhr.responseXML)||void 0===_this$xhr$responseXML?void 0:_this$xhr$responseXML.documentElement;if(node){if("parsererror"===node.tagName)throw Strophe.error("invalid response received"),Strophe.error("responseText: "+this.xhr.responseText),Strophe.error("responseXML: "+Strophe.serialize(node)),new Error("parsererror")}else if(this.xhr.responseText){var _node;Strophe.debug("Got responseText but no responseXML; attempting to parse it with DOMParser..."),node=(new DOMParser).parseFromString(this.xhr.responseText,"application/xml").documentElement;const parserError=null===(_node=node)||void 0===_node?void 0:_node.querySelector("parsererror");if(!node||parserError){parserError&&(Strophe.error("invalid response received: "+parserError.textContent),Strophe.error("responseText: "+this.xhr.responseText));const error=new Error;throw error.name=Strophe.ErrorCondition.BAD_FORMAT,error}}return node}_newXHR(){const xhr=new XMLHttpRequest;return xhr.overrideMimeType&&xhr.overrideMimeType("text/xml; charset=utf-8"),xhr.onreadystatechange=this.func.bind(null,this),xhr}}class Bosh{constructor(connection){var _Bosh$prototype$strip;this._conn=connection,this.rid=Math.floor(4294967295*Math.random()),this.sid=null,this.hold=1,this.wait=60,this.window=5,this.errors=0,this.inactivity=null,this.strip=null!==(_Bosh$prototype$strip=Bosh.prototype.strip)&&void 0!==_Bosh$prototype$strip&&_Bosh$prototype$strip,this.lastResponseHeaders=null,this._requests=[]}_buildBody(){const bodyWrap=$build("body",{rid:this.rid++,xmlns:Strophe.NS.HTTPBIND});return null!==this.sid&&bodyWrap.attrs({sid:this.sid}),this._conn.options.keepalive&&this._conn._sessionCachingSupported()&&this._cacheSession(),bodyWrap}_reset(){this.rid=Math.floor(4294967295*Math.random()),this.sid=null,this.errors=0,this._conn._sessionCachingSupported()&&sessionStorage.removeItem("strophe-bosh-session"),this._conn.nextValidRid(this.rid)}_connect(wait,hold,route){this.wait=wait||this.wait,this.hold=hold||this.hold,this.errors=0;const body=this._buildBody().attrs({to:this._conn.domain,"xml:lang":"en",wait:this.wait,hold:this.hold,content:"text/xml; charset=utf-8",ver:"1.6","xmpp:version":"1.0","xmlns:xmpp":Strophe.NS.BOSH});route&&body.attrs({route});const _connect_cb=this._conn._connect_cb;this._requests.push(new Strophe.Request(body.tree(),this._onRequestStateChange.bind(this,_connect_cb.bind(this._conn)),Number(body.tree().getAttribute("rid")))),this._throttledRequestHandler()}_attach(jid,sid,rid,callback,wait,hold,wind){this._conn.jid=jid,this.sid=sid,this.rid=rid,this._conn.connect_callback=callback,this._conn.domain=Strophe.getDomainFromJid(this._conn.jid),this._conn.authenticated=!0,this._conn.connected=!0,this.wait=wait||this.wait,this.hold=hold||this.hold,this.window=wind||this.window,this._conn._changeConnectStatus(Strophe.Status.ATTACHED,null)}_restore(jid,callback,wait,hold,wind){const session=JSON.parse(sessionStorage.getItem("strophe-bosh-session"));if(!(null!=session&&session.rid&&session.sid&&session.jid&&(null==jid||Strophe.getBareJidFromJid(session.jid)===Strophe.getBareJidFromJid(jid)||null===Strophe.getNodeFromJid(jid)&&Strophe.getDomainFromJid(session.jid)===jid))){const error=new Error("_restore: no restoreable session.");throw error.name="StropheSessionError",error}this._conn.restored=!0,this._attach(session.jid,session.sid,session.rid,callback,wait,hold,wind)}_cacheSession(){this._conn.authenticated?this._conn.jid&&this.rid&&this.sid&&sessionStorage.setItem("strophe-bosh-session",JSON.stringify({jid:this._conn.jid,rid:this.rid,sid:this.sid})):sessionStorage.removeItem("strophe-bosh-session")}_connect_cb(bodyWrap){const typ=bodyWrap.getAttribute("type");if(null!==typ&&"terminate"===typ){let cond=bodyWrap.getAttribute("condition");Strophe.error("BOSH-Connection failed: "+cond);const conflict=bodyWrap.getElementsByTagName("conflict");return null!==cond?("remote-stream-error"===cond&&conflict.length>0&&(cond="conflict"),this._conn._changeConnectStatus(Strophe.Status.CONNFAIL,cond)):this._conn._changeConnectStatus(Strophe.Status.CONNFAIL,"unknown"),this._conn._doDisconnect(cond),Strophe.Status.CONNFAIL}this.sid||(this.sid=bodyWrap.getAttribute("sid"));const wind=bodyWrap.getAttribute("requests");wind&&(this.window=parseInt(wind,10));const hold=bodyWrap.getAttribute("hold");hold&&(this.hold=parseInt(hold,10));const wait=bodyWrap.getAttribute("wait");wait&&(this.wait=parseInt(wait,10));const inactivity=bodyWrap.getAttribute("inactivity");inactivity&&(this.inactivity=parseInt(inactivity,10))}_disconnect(pres){this._sendTerminate(pres)}_doDisconnect(){this.sid=null,this.rid=Math.floor(4294967295*Math.random()),this._conn._sessionCachingSupported()&&sessionStorage.removeItem("strophe-bosh-session"),this._conn.nextValidRid(this.rid)}_emptyQueue(){return 0===this._requests.length}_callProtocolErrorHandlers(req){const reqStatus=Bosh._getRequestStatus(req),err_callback=this._conn.protocolErrorHandlers.HTTP[reqStatus];err_callback&&err_callback.call(this,reqStatus)}_hitError(reqStatus){this.errors++,Strophe.warn("request errored, status: "+reqStatus+", number of errors: "+this.errors),this.errors>4&&this._conn._onDisconnectTimeout()}_no_auth_received(callback){Strophe.warn("Server did not yet offer a supported authentication mechanism. Sending a blank poll request."),callback=callback?callback.bind(this._conn):this._conn._connect_cb.bind(this._conn);const body=this._buildBody();this._requests.push(new Strophe.Request(body.tree(),this._onRequestStateChange.bind(this,callback),Number(body.tree().getAttribute("rid")))),this._throttledRequestHandler()}_onDisconnectTimeout(){this._abortAllRequests()}_abortAllRequests(){for(;this._requests.length>0;){const req=this._requests.pop();req.abort=!0,req.xhr.abort(),req.xhr.onreadystatechange=function(){}}}_onIdle(){const data=this._conn._data;if(this._conn.authenticated&&0===this._requests.length&&0===data.length&&!this._conn.disconnecting&&(Strophe.debug("no requests during idle cycle, sending blank request"),data.push(null)),!this._conn.paused){if(this._requests.length<2&&data.length>0){const body=this._buildBody();for(let i=0;i<data.length;i++)null!==data[i]&&("restart"===data[i]?body.attrs({to:this._conn.domain,"xml:lang":"en","xmpp:restart":"true","xmlns:xmpp":Strophe.NS.BOSH}):body.cnode(data[i]).up());delete this._conn._data,this._conn._data=[],this._requests.push(new Strophe.Request(body.tree(),this._onRequestStateChange.bind(this,this._conn._dataRecv.bind(this._conn)),Number(body.tree().getAttribute("rid")))),this._throttledRequestHandler()}if(this._requests.length>0){const time_elapsed=this._requests[0].age();null!==this._requests[0].dead&&this._requests[0].timeDead()>Math.floor(Strophe.SECONDARY_TIMEOUT*this.wait)&&this._throttledRequestHandler(),time_elapsed>Math.floor(Strophe.TIMEOUT*this.wait)&&(Strophe.warn("Request "+this._requests[0].id+" timed out, over "+Math.floor(Strophe.TIMEOUT*this.wait)+" seconds since last activity"),this._throttledRequestHandler())}}}static _getRequestStatus(req,def){let reqStatus;if(4===req.xhr.readyState)try{reqStatus=req.xhr.status}catch(e){Strophe.error("Caught an error while retrieving a request's status, reqStatus: "+reqStatus)}return void 0===reqStatus&&(reqStatus="number"==typeof def?def:0),reqStatus}_onRequestStateChange(func,req){if(Strophe.debug("request id "+req.id+"."+req.sends+" state changed to "+req.xhr.readyState),req.abort)return void(req.abort=!1);if(4!==req.xhr.readyState)return;const reqStatus=Bosh._getRequestStatus(req);if(this.lastResponseHeaders=req.xhr.getAllResponseHeaders(),this._conn.disconnecting&&reqStatus>=400)return this._hitError(reqStatus),void this._callProtocolErrorHandlers(req);const reqIs0=this._requests[0]===req,reqIs1=this._requests[1]===req,valid_request=reqStatus>0&&reqStatus<500,too_many_retries=req.sends>this._conn.maxRetries;(valid_request||too_many_retries)&&(this._removeRequest(req),Strophe.debug("request id "+req.id+" should now be removed")),200===reqStatus?((reqIs1||reqIs0&&this._requests.length>0&&this._requests[0].age()>Math.floor(Strophe.SECONDARY_TIMEOUT*this.wait))&&this._restartRequest(0),this._conn.nextValidRid(req.rid+1),Strophe.debug("request id "+req.id+"."+req.sends+" got 200"),func(req),this.errors=0):0===reqStatus||reqStatus>=400&&reqStatus<600||reqStatus>=12e3?(Strophe.error("request id "+req.id+"."+req.sends+" error "+reqStatus+" happened"),this._hitError(reqStatus),this._callProtocolErrorHandlers(req),reqStatus>=400&&reqStatus<500&&(this._conn._changeConnectStatus(Strophe.Status.DISCONNECTING,null),this._conn._doDisconnect())):Strophe.error("request id "+req.id+"."+req.sends+" error "+reqStatus+" happened"),valid_request||too_many_retries?too_many_retries&&!this._conn.connected&&this._conn._changeConnectStatus(Strophe.Status.CONNFAIL,"giving-up"):this._throttledRequestHandler()}_processRequest(i){let req=this._requests[i];const reqStatus=Bosh._getRequestStatus(req,-1);if(req.sends>this._conn.maxRetries)return void this._conn._onDisconnectTimeout();const time_elapsed=req.age(),primary_timeout=!isNaN(time_elapsed)&&time_elapsed>Math.floor(Strophe.TIMEOUT*this.wait),secondary_timeout=null!==req.dead&&req.timeDead()>Math.floor(Strophe.SECONDARY_TIMEOUT*this.wait),server_error=4===req.xhr.readyState&&(reqStatus<1||reqStatus>=500);if((primary_timeout||secondary_timeout||server_error)&&(secondary_timeout&&Strophe.error(`Request ${this._requests[i].id} timed out (secondary), restarting`),req.abort=!0,req.xhr.abort(),req.xhr.onreadystatechange=function(){},this._requests[i]=new Strophe.Request(req.xmlData,req.origFunc,req.rid,req.sends),req=this._requests[i]),0===req.xhr.readyState){var _this$_conn$rawOutput,_this$_conn3;Strophe.debug("request id "+req.id+"."+req.sends+" posting");try{const content_type=this._conn.options.contentType||"text/xml; charset=utf-8";req.xhr.open("POST",this._conn.service,!this._conn.options.sync),void 0!==req.xhr.setRequestHeader&&req.xhr.setRequestHeader("Content-Type",content_type),this._conn.options.withCredentials&&(req.xhr.withCredentials=!0)}catch(e2){return Strophe.error("XHR open failed: "+e2.toString()),this._conn.connected||this._conn._changeConnectStatus(Strophe.Status.CONNFAIL,"bad-service"),void this._conn.disconnect()}const sendFunc=()=>{if(req.date=(new Date).valueOf(),this._conn.options.customHeaders){const headers=this._conn.options.customHeaders;for(const header in headers)Object.prototype.hasOwnProperty.call(headers,header)&&req.xhr.setRequestHeader(header,headers[header])}req.xhr.send(req.data)};if(req.sends>1){const backoff=1e3*Math.min(Math.floor(Strophe.TIMEOUT*this.wait),Math.pow(req.sends,3));setTimeout(function(){sendFunc()},backoff)}else sendFunc();var _this$_conn$xmlOutput,_this$_conn,_this$_conn$xmlOutput2,_this$_conn2;req.sends++,this.strip&&"body"===req.xmlData.nodeName&&req.xmlData.childNodes.length?null===(_this$_conn$xmlOutput=(_this$_conn=this._conn).xmlOutput)||void 0===_this$_conn$xmlOutput||_this$_conn$xmlOutput.call(_this$_conn,req.xmlData.children[0]):null===(_this$_conn$xmlOutput2=(_this$_conn2=this._conn).xmlOutput)||void 0===_this$_conn$xmlOutput2||_this$_conn$xmlOutput2.call(_this$_conn2,req.xmlData),null===(_this$_conn$rawOutput=(_this$_conn3=this._conn).rawOutput)||void 0===_this$_conn$rawOutput||_this$_conn$rawOutput.call(_this$_conn3,req.data)}else Strophe.debug("_processRequest: "+(0===i?"first":"second")+" request has readyState of "+req.xhr.readyState)}_removeRequest(req){Strophe.debug("removing request");for(let i=this._requests.length-1;i>=0;i--)req===this._requests[i]&&this._requests.splice(i,1);req.xhr.onreadystatechange=function(){},this._throttledRequestHandler()}_restartRequest(i){const req=this._requests[i];null===req.dead&&(req.dead=new Date),this._processRequest(i)}_reqToData(req){try{return req.getResponse()}catch(e){if("parsererror"!==e.message)throw e;this._conn.disconnect("strophe-parsererror")}}_sendTerminate(pres){Strophe.debug("_sendTerminate was called");const body=this._buildBody().attrs({type:"terminate"}),el=pres instanceof Builder?pres.tree():pres;pres&&body.cnode(el);const req=new Strophe.Request(body.tree(),this._onRequestStateChange.bind(this,this._conn._dataRecv.bind(this._conn)),Number(body.tree().getAttribute("rid")));this._requests.push(req),this._throttledRequestHandler()}_send(){clearTimeout(this._conn._idleTimeout),this._throttledRequestHandler(),this._conn._idleTimeout=setTimeout(()=>this._conn._onIdle(),100)}_sendRestart(){this._throttledRequestHandler(),clearTimeout(this._conn._idleTimeout)}_throttledRequestHandler(){this._requests?Strophe.debug("_throttledRequestHandler called with "+this._requests.length+" requests"):Strophe.debug("_throttledRequestHandler called with undefined requests"),this._requests&&0!==this._requests.length&&(this._requests.length>0&&this._processRequest(0),this._requests.length>1&&Math.abs(this._requests[0].rid-this._requests[1].rid)<this.window&&this._processRequest(1))}}class Websocket{constructor(connection){this._conn=connection,this.strip="wrapper";const service=connection.service;if(0!==service.indexOf("ws:")&&0!==service.indexOf("wss:")){let new_service="";"ws"===connection.options.protocol&&"https:"!==location.protocol?new_service+="ws":new_service+="wss",new_service+="://"+location.host,0!==service.indexOf("/")?new_service+=location.pathname+service:new_service+=service,connection.service=new_service}}_buildStream(){return $build("open",{xmlns:Strophe.NS.FRAMING,to:this._conn.domain,version:"1.0"})}_checkStreamError(bodyWrap,connectstatus){let errors;if(errors=bodyWrap.getElementsByTagNameNS?bodyWrap.getElementsByTagNameNS(Strophe.NS.STREAM,"error"):bodyWrap.getElementsByTagName("stream:error"),0===errors.length)return!1;const error=errors[0];let condition="",text="";const ns="urn:ietf:params:xml:ns:xmpp-streams";for(let i=0;i<error.childNodes.length;i++){const e=error.children[i];if(e.getAttribute("xmlns")!==ns)break;"text"===e.nodeName?text=e.textContent:condition=e.nodeName}let errorString="WebSocket stream error: ";return errorString+=condition||"unknown",text&&(errorString+=" - "+text),Strophe.error(errorString),this._conn._changeConnectStatus(connectstatus,condition),this._conn._doDisconnect(),!0}_reset(){}_connect(){this._closeSocket(),this.socket=new WebSocket(this._conn.service,"xmpp"),this.socket.onopen=()=>this._onOpen(),this.socket.onerror=e=>this._onError(e),this.socket.onclose=e=>this._onClose(e),this.socket.onmessage=message=>this._onInitialMessage(message)}_connect_cb(bodyWrap){if(this._checkStreamError(bodyWrap,Strophe.Status.CONNFAIL))return Strophe.Status.CONNFAIL}_handleStreamStart(message){let error=null;const ns=message.getAttribute("xmlns");"string"!=typeof ns?error="Missing xmlns in <open />":ns!==Strophe.NS.FRAMING&&(error="Wrong xmlns in <open />: "+ns);const ver=message.getAttribute("version");return"string"!=typeof ver?error="Missing version in <open />":"1.0"!==ver&&(error="Wrong version in <open />: "+ver),!error||(this._conn._changeConnectStatus(Strophe.Status.CONNFAIL,error),this._conn._doDisconnect(),!1)}_onInitialMessage(message){if(0===message.data.indexOf("<open ")||0===message.data.indexOf("<?xml")){const data=message.data.replace(/^(<\?.*?\?>\s*)*/,"");if(""===data)return;const streamStart=(new DOMParser).parseFromString(data,"text/xml").documentElement;this._conn.xmlInput(streamStart),this._conn.rawInput(message.data),this._handleStreamStart(streamStart)&&this._connect_cb(streamStart)}else if(0===message.data.indexOf("<close ")){const parsedMessage=(new DOMParser).parseFromString(message.data,"text/xml").documentElement;this._conn.xmlInput(parsedMessage),this._conn.rawInput(message.data);const see_uri=parsedMessage.getAttribute("see-other-uri");if(see_uri){const service=this._conn.service;(service.indexOf("wss:")>=0&&see_uri.indexOf("wss:")>=0||service.indexOf("ws:")>=0)&&(this._conn._changeConnectStatus(Strophe.Status.REDIRECT,"Received see-other-uri, resetting connection"),this._conn.reset(),this._conn.service=see_uri,this._connect())}else this._conn._changeConnectStatus(Strophe.Status.CONNFAIL,"Received closing stream"),this._conn._doDisconnect()}else{this._replaceMessageHandler();const string=this._streamWrap(message.data),elem=(new DOMParser).parseFromString(string,"text/xml").documentElement;this._conn._connect_cb(elem,null,message.data)}}_replaceMessageHandler(){this.socket.onmessage=m=>this._onMessage(m)}_disconnect(pres){if(this.socket&&this.socket.readyState!==WebSocket.CLOSED){pres&&this._conn.send(pres);const close=$build("close",{xmlns:Strophe.NS.FRAMING});this._conn.xmlOutput(close.tree());const closeString=Strophe.serialize(close);this._conn.rawOutput(closeString);try{this.socket.send(closeString)}catch(e){Strophe.warn("Couldn't send <close /> tag.")}}setTimeout(()=>this._conn._doDisconnect(),0)}_doDisconnect(){Strophe.debug("WebSockets _doDisconnect was called"),this._closeSocket()}_streamWrap(stanza){return"<wrapper>"+stanza+"</wrapper>"}_closeSocket(){if(this.socket)try{this.socket.onclose=null,this.socket.onerror=null,this.socket.onmessage=null,this.socket.close()}catch(e){Strophe.debug(e.message)}this.socket=null}_emptyQueue(){return!0}_onClose(e){this._conn.connected&&!this._conn.disconnecting?(Strophe.error("Websocket closed unexpectedly"),this._conn._doDisconnect()):e&&1006===e.code&&!this._conn.connected&&this.socket?(Strophe.error("Websocket closed unexcectedly"),this._conn._changeConnectStatus(Strophe.Status.CONNFAIL,"The WebSocket connection could not be established or was disconnected."),this._conn._doDisconnect()):Strophe.debug("Websocket closed")}_no_auth_received(callback){Strophe.error("Server did not offer a supported authentication mechanism"),this._conn._changeConnectStatus(Strophe.Status.CONNFAIL,Strophe.ErrorCondition.NO_AUTH_MECH),null==callback||callback.call(this._conn),this._conn._doDisconnect()}_onDisconnectTimeout(){}_abortAllRequests(){}_onError(error){Strophe.error("Websocket error "+JSON.stringify(error)),this._conn._changeConnectStatus(Strophe.Status.CONNFAIL,"The WebSocket connection could not be established or was disconnected."),this._disconnect()}_onIdle(){const data=this._conn._data;if(data.length>0&&!this._conn.paused){for(let i=0;i<data.length;i++)if(null!==data[i]){const stanza="restart"===data[i]?this._buildStream().tree():data[i];if("restart"===stanza)throw new Error("Wrong type for stanza");const rawStanza=Strophe.serialize(stanza);this._conn.xmlOutput(stanza),this._conn.rawOutput(rawStanza),this.socket.send(rawStanza)}this._conn._data=[]}}_onMessage(message){let elem;const close='<close xmlns="urn:ietf:params:xml:ns:xmpp-framing" />';if(message.data===close)return this._conn.rawInput(close),this._conn.xmlInput(message),void(this._conn.disconnecting||this._conn._doDisconnect());if(0===message.data.search("<open ")){if(elem=(new DOMParser).parseFromString(message.data,"text/xml").documentElement,!this._handleStreamStart(elem))return}else{const data=this._streamWrap(message.data);elem=(new DOMParser).parseFromString(data,"text/xml").documentElement}return this._checkStreamError(elem,Strophe.Status.ERROR)?void 0:this._conn.disconnecting&&"presence"===elem.firstElementChild.nodeName&&"unavailable"===elem.firstElementChild.getAttribute("type")?(this._conn.xmlInput(elem),void this._conn.rawInput(Strophe.serialize(elem))):void this._conn._dataRecv(elem,message.data)}_onOpen(){Strophe.debug("Websocket open");const start=this._buildStream();this._conn.xmlOutput(start.tree());const startString=Strophe.serialize(start);this._conn.rawOutput(startString),this.socket.send(startString)}_send(){this._conn.flush()}_sendRestart(){clearTimeout(this._conn._idleTimeout),this._conn._onIdle.bind(this._conn)()}}class WorkerWebsocket extends Websocket{constructor(connection){super(connection),this._conn=connection,this.worker=new SharedWorker(this._conn.options.worker,"Strophe XMPP Connection"),this.worker.onerror=e=>{var _console;null===(_console=console)||void 0===_console||_console.error(e),Strophe.log(Strophe.LogLevel.ERROR,`Shared Worker Error: ${e}`)}}_setSocket(){this.socket={send:str=>this.worker.port.postMessage(["send",str]),close:()=>this.worker.port.postMessage(["_closeSocket"]),onopen:()=>{},onerror:e=>this._onError(e),onclose:e=>this._onClose(e),onmessage:()=>{},readyState:null}}_connect(){this._setSocket(),this._messageHandler=m=>this._onInitialMessage(m),this.worker.port.start(),this.worker.port.onmessage=ev=>this._onWorkerMessage(ev),this.worker.port.postMessage(["_connect",this._conn.service,this._conn.jid])}_attach(callback){this._setSocket(),this._messageHandler=m=>this._onMessage(m),this._conn.connect_callback=callback,this.worker.port.start(),this.worker.port.onmessage=ev=>this._onWorkerMessage(ev),this.worker.port.postMessage(["_attach",this._conn.service])}_attachCallback(status,jid){status===Strophe.Status.ATTACHED?(this._conn.jid=jid,this._conn.authenticated=!0,this._conn.connected=!0,this._conn.restored=!0,this._conn._changeConnectStatus(Strophe.Status.ATTACHED)):status===Strophe.Status.ATTACHFAIL&&(this._conn.authenticated=!1,this._conn.connected=!1,this._conn.restored=!1,this._conn._changeConnectStatus(Strophe.Status.ATTACHFAIL))}_disconnect(pres){pres&&this._conn.send(pres);const close=$build("close",{xmlns:Strophe.NS.FRAMING});this._conn.xmlOutput(close.tree());const closeString=Strophe.serialize(close);this._conn.rawOutput(closeString),this.worker.port.postMessage(["send",closeString]),this._conn._doDisconnect()}_closeSocket(){this.socket.close()}_replaceMessageHandler(){this._messageHandler=m=>this._onMessage(m)}_onWorkerMessage(ev){const lmap={};lmap.debug=Strophe.LogLevel.DEBUG,lmap.info=Strophe.LogLevel.INFO,lmap.warn=Strophe.LogLevel.WARN,lmap.error=Strophe.LogLevel.ERROR,lmap.fatal=Strophe.LogLevel.FATAL;const{data}=ev,method_name=data[0];if("_onMessage"===method_name)this._messageHandler(data[1]);else if(method_name in this)try{this[method_name].apply(this,ev.data.slice(1))}catch(e){Strophe.log(Strophe.LogLevel.ERROR,e)}else if("log"===method_name){const level=data[1],msg=data[2];Strophe.log(lmap[level],msg)}else Strophe.log(Strophe.LogLevel.ERROR,`Found unhandled service worker message: ${data}`)}}const Strophe={VERSION:"1.6.1",TIMEOUT:1.1,SECONDARY_TIMEOUT:.1,shims,Request,Bosh,Websocket,WorkerWebsocket,SASLAnonymous,SASLPlain,SASLSHA1,SASLSHA256,SASLSHA384,SASLSHA512,SASLOAuthBearer,SASLExternal,SASLXOAuth2,Builder,Connection,ElementType,ErrorCondition,Handler,LogLevel,NS,SASLMechanism,Status,TimedHandler,...utils$1,XHTML:{...XHTML,validTag,validCSS,validAttribute},addNamespace(name,value){Strophe.NS[name]=value},_handleError(e){void 0!==e.stack&&Strophe.fatal(e.stack),Strophe.fatal("error: "+e.message)},log(level,msg){var _console;level===this.LogLevel.FATAL&&(null===(_console=console)||void 0===_console||_console.error(msg))},debug(msg){this.log(this.LogLevel.DEBUG,msg)},info(msg){this.log(this.LogLevel.INFO,msg)},warn(msg){this.log(this.LogLevel.WARN,msg)},error(msg){this.log(this.LogLevel.ERROR,msg)},fatal(msg){this.log(this.LogLevel.FATAL,msg)},_requestId:0,_connectionPlugins:{},addConnectionPlugin(name,ptype){Strophe._connectionPlugins[name]=ptype}},PARSE_ERROR_NS="http://www.w3.org/1999/xhtml";function toStanza(string,throwErrorIfInvalidNS){const doc=Strophe.xmlHtmlNode(string);if(doc.getElementsByTagNameNS(PARSE_ERROR_NS,"parsererror").length)throw new Error(`Parser Error: ${string}`);const node=doc.firstElementChild;if(["message","iq","presence"].includes(node.nodeName.toLowerCase())&&"jabber:client"!==node.namespaceURI&&"jabber:server"!==node.namespaceURI){const err_msg=`Invalid namespaceURI ${node.namespaceURI}`;if(throwErrorIfInvalidNS)throw new Error(err_msg);Strophe.log(Strophe.LogLevel.ERROR,err_msg)}return node}class Stanza{constructor(strings,values){this.strings=strings,this.values=values}toString(){return this.string=this.string||this.strings.reduce((acc,str)=>{const idx=this.strings.indexOf(str);return acc+str+(this.values.length>idx?this.values[idx].toString():"")},""),this.string}tree(){var _this$node;return this.node=null!==(_this$node=this.node)&&void 0!==_this$node?_this$node:toStanza(this.toString(),!0),this.node}}function stx(strings,...values){return new Stanza(strings,values)}globalThis.$build=$build,globalThis.$iq=$iq,globalThis.$msg=$msg,globalThis.$pres=$pres,globalThis.Strophe=Strophe,exports.$build=$build,exports.$iq=$iq,exports.$msg=$msg,exports.$pres=$pres,exports.Builder=Builder,exports.Strophe=Strophe,exports.stx=stx,exports.toStanza=toStanza,Object.defineProperty(exports,"__esModule",{value:!0})},"object"==typeof exports&&void 0!==module?factory(exports):"function"==typeof define&&define.amd?define(["exports"],factory):factory((global="undefined"!=typeof globalThis?globalThis:global||self).strophe={})},{"@xmldom/xmldom":5,ws:111}],111:[function(require,module,exports){"use strict";module.exports=function(){throw new Error("ws does not work in the browser. Browser clients must use the native WebSocket object")}},{}],112:[function(require,module,exports){(function(setImmediate,clearImmediate){(function(){var nextTick=require("process/browser.js").nextTick,apply=Function.prototype.apply,slice=Array.prototype.slice,immediateIds={},nextImmediateId=0;function Timeout(id,clearFn){this._id=id,this._clearFn=clearFn}exports.setTimeout=function(){return new Timeout(apply.call(setTimeout,window,arguments),clearTimeout)},exports.setInterval=function(){return new Timeout(apply.call(setInterval,window,arguments),clearInterval)},exports.clearTimeout=exports.clearInterval=function(timeout){timeout.close()},Timeout.prototype.unref=Timeout.prototype.ref=function(){},Timeout.prototype.close=function(){this._clearFn.call(window,this._id)},exports.enroll=function(item,msecs){clearTimeout(item._idleTimeoutId),item._idleTimeout=msecs},exports.unenroll=function(item){clearTimeout(item._idleTimeoutId),item._idleTimeout=-1},exports._unrefActive=exports.active=function(item){clearTimeout(item._idleTimeoutId);var msecs=item._idleTimeout;msecs>=0&&(item._idleTimeoutId=setTimeout(function onTimeout(){item._onTimeout&&item._onTimeout()},msecs))},exports.setImmediate="function"==typeof setImmediate?setImmediate:function(fn){var id=nextImmediateId++,args=!(arguments.length<2)&&slice.call(arguments,1);return immediateIds[id]=!0,nextTick(function onNextTick(){immediateIds[id]&&(args?fn.apply(null,args):fn.call(null),exports.clearImmediate(id))}),id},exports.clearImmediate="function"==typeof clearImmediate?clearImmediate:function(id){delete immediateIds[id]}}).call(this)}).call(this,require("timers").setImmediate,require("timers").clearImmediate)},{"process/browser.js":89,timers:112}],113:[function(require,module,exports){(function(global){(function(){function deprecate(fn,msg){if(config("noDeprecation"))return fn;var warned=!1;function deprecated(){if(!warned){if(config("throwDeprecation"))throw new Error(msg);config("traceDeprecation")?console.trace(msg):console.warn(msg),warned=!0}return fn.apply(this,arguments)}return deprecated}function config(name){try{if(!global.localStorage)return!1}catch(_){return!1}var val=global.localStorage[name];return null!=val&&"true"===String(val).toLowerCase()}module.exports=deprecate}).call(this)}).call(this,void 0!==__webpack_require__.g?__webpack_require__.g:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],114:[function(require,module,exports){"function"==typeof Object.create?module.exports=function inherits(ctor,superCtor){ctor.super_=superCtor,ctor.prototype=Object.create(superCtor.prototype,{constructor:{value:ctor,enumerable:!1,writable:!0,configurable:!0}})}:module.exports=function inherits(ctor,superCtor){ctor.super_=superCtor;var TempCtor=function(){};TempCtor.prototype=superCtor.prototype,ctor.prototype=new TempCtor,ctor.prototype.constructor=ctor}},{}],115:[function(require,module,exports){module.exports=function isBuffer(arg){return arg&&"object"==typeof arg&&"function"==typeof arg.copy&&"function"==typeof arg.fill&&"function"==typeof arg.readUInt8}},{}],116:[function(require,module,exports){(function(process,global){(function(){var formatRegExp=/%[sdj%]/g;exports.format=function(f){if(!isString(f)){for(var objects=[],i=0;i<arguments.length;i++)objects.push(inspect(arguments[i]));return objects.join(" ")}i=1;for(var args=arguments,len=args.length,str=String(f).replace(formatRegExp,function(x){if("%%"===x)return"%";if(i>=len)return x;switch(x){case"%s":return String(args[i++]);case"%d":return Number(args[i++]);case"%j":try{return JSON.stringify(args[i++])}catch(_){return"[Circular]"}default:return x}}),x=args[i];i<len;x=args[++i])isNull(x)||!isObject(x)?str+=" "+x:str+=" "+inspect(x);return str},exports.deprecate=function(fn,msg){if(isUndefined(global.process))return function(){return exports.deprecate(fn,msg).apply(this,arguments)};if(!0===process.noDeprecation)return fn;var warned=!1;function deprecated(){if(!warned){if(process.throwDeprecation)throw new Error(msg);process.traceDeprecation?console.trace(msg):console.error(msg),warned=!0}return fn.apply(this,arguments)}return deprecated};var debugEnviron,debugs={};function inspect(obj,opts){var ctx={seen:[],stylize:stylizeNoColor};return arguments.length>=3&&(ctx.depth=arguments[2]),arguments.length>=4&&(ctx.colors=arguments[3]),isBoolean(opts)?ctx.showHidden=opts:opts&&exports._extend(ctx,opts),isUndefined(ctx.showHidden)&&(ctx.showHidden=!1),isUndefined(ctx.depth)&&(ctx.depth=2),isUndefined(ctx.colors)&&(ctx.colors=!1),isUndefined(ctx.customInspect)&&(ctx.customInspect=!0),ctx.colors&&(ctx.stylize=stylizeWithColor),formatValue(ctx,obj,ctx.depth)}function stylizeWithColor(str,styleType){var style=inspect.styles[styleType];return style?"["+inspect.colors[style][0]+"m"+str+"["+inspect.colors[style][1]+"m":str}function stylizeNoColor(str,styleType){return str}function arrayToHash(array){var hash={};return array.forEach(function(val,idx){hash[val]=!0}),hash}function formatValue(ctx,value,recurseTimes){if(ctx.customInspect&&value&&isFunction(value.inspect)&&value.inspect!==exports.inspect&&(!value.constructor||value.constructor.prototype!==value)){var ret=value.inspect(recurseTimes,ctx);return isString(ret)||(ret=formatValue(ctx,ret,recurseTimes)),ret}var primitive=formatPrimitive(ctx,value);if(primitive)return primitive;var keys=Object.keys(value),visibleKeys=arrayToHash(keys);if(ctx.showHidden&&(keys=Object.getOwnPropertyNames(value)),isError(value)&&(keys.indexOf("message")>=0||keys.indexOf("description")>=0))return formatError(value);if(0===keys.length){if(isFunction(value)){var name=value.name?": "+value.name:"";return ctx.stylize("[Function"+name+"]","special")}if(isRegExp(value))return ctx.stylize(RegExp.prototype.toString.call(value),"regexp");if(isDate(value))return ctx.stylize(Date.prototype.toString.call(value),"date");if(isError(value))return formatError(value)}var output,base="",array=!1,braces=["{","}"];return isArray(value)&&(array=!0,braces=["[","]"]),isFunction(value)&&(base=" [Function"+(value.name?": "+value.name:"")+"]"),isRegExp(value)&&(base=" "+RegExp.prototype.toString.call(value)),isDate(value)&&(base=" "+Date.prototype.toUTCString.call(value)),isError(value)&&(base=" "+formatError(value)),0!==keys.length||array&&0!=value.length?recurseTimes<0?isRegExp(value)?ctx.stylize(RegExp.prototype.toString.call(value),"regexp"):ctx.stylize("[Object]","special"):(ctx.seen.push(value),output=array?formatArray(ctx,value,recurseTimes,visibleKeys,keys):keys.map(function(key){return formatProperty(ctx,value,recurseTimes,visibleKeys,key,array)}),ctx.seen.pop(),reduceToSingleString(output,base,braces)):braces[0]+base+braces[1]}function formatPrimitive(ctx,value){if(isUndefined(value))return ctx.stylize("undefined","undefined");if(isString(value)){var simple="'"+JSON.stringify(value).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return ctx.stylize(simple,"string")}return isNumber(value)?ctx.stylize(""+value,"number"):isBoolean(value)?ctx.stylize(""+value,"boolean"):isNull(value)?ctx.stylize("null","null"):void 0}function formatError(value){return"["+Error.prototype.toString.call(value)+"]"}function formatArray(ctx,value,recurseTimes,visibleKeys,keys){for(var output=[],i=0,l=value.length;i<l;++i)hasOwnProperty(value,String(i))?output.push(formatProperty(ctx,value,recurseTimes,visibleKeys,String(i),!0)):output.push("");return keys.forEach(function(key){key.match(/^\d+$/)||output.push(formatProperty(ctx,value,recurseTimes,visibleKeys,key,!0))}),output}function formatProperty(ctx,value,recurseTimes,visibleKeys,key,array){var name,str,desc;if((desc=Object.getOwnPropertyDescriptor(value,key)||{value:value[key]}).get?str=desc.set?ctx.stylize("[Getter/Setter]","special"):ctx.stylize("[Getter]","special"):desc.set&&(str=ctx.stylize("[Setter]","special")),hasOwnProperty(visibleKeys,key)||(name="["+key+"]"),str||(ctx.seen.indexOf(desc.value)<0?(str=isNull(recurseTimes)?formatValue(ctx,desc.value,null):formatValue(ctx,desc.value,recurseTimes-1)).indexOf("\n")>-1&&(str=array?str.split("\n").map(function(line){return" "+line}).join("\n").substr(2):"\n"+str.split("\n").map(function(line){return" "+line}).join("\n")):str=ctx.stylize("[Circular]","special")),isUndefined(name)){if(array&&key.match(/^\d+$/))return str;(name=JSON.stringify(""+key)).match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(name=name.substr(1,name.length-2),name=ctx.stylize(name,"name")):(name=name.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),name=ctx.stylize(name,"string"))}return name+": "+str}function reduceToSingleString(output,base,braces){return output.reduce(function(prev,cur){return cur.indexOf("\n"),prev+cur.replace(/\u001b\[\d\d?m/g,"").length+1},0)>60?braces[0]+(""===base?"":base+"\n ")+" "+output.join(",\n ")+" "+braces[1]:braces[0]+base+" "+output.join(", ")+" "+braces[1]}function isArray(ar){return Array.isArray(ar)}function isBoolean(arg){return"boolean"==typeof arg}function isNull(arg){return null===arg}function isNullOrUndefined(arg){return null==arg}function isNumber(arg){return"number"==typeof arg}function isString(arg){return"string"==typeof arg}function isSymbol(arg){return"symbol"==typeof arg}function isUndefined(arg){return void 0===arg}function isRegExp(re){return isObject(re)&&"[object RegExp]"===objectToString(re)}function isObject(arg){return"object"==typeof arg&&null!==arg}function isDate(d){return isObject(d)&&"[object Date]"===objectToString(d)}function isError(e){return isObject(e)&&("[object Error]"===objectToString(e)||e instanceof Error)}function isFunction(arg){return"function"==typeof arg}function isPrimitive(arg){return null===arg||"boolean"==typeof arg||"number"==typeof arg||"string"==typeof arg||"symbol"==typeof arg||void 0===arg}function objectToString(o){return Object.prototype.toString.call(o)}function pad(n){return n<10?"0"+n.toString(10):n.toString(10)}exports.debuglog=function(set){if(isUndefined(debugEnviron)&&(debugEnviron=process.env.NODE_DEBUG||""),set=set.toUpperCase(),!debugs[set])if(new RegExp("\\b"+set+"\\b","i").test(debugEnviron)){var pid=process.pid;debugs[set]=function(){var msg=exports.format.apply(exports,arguments);console.error("%s %d: %s",set,pid,msg)}}else debugs[set]=function(){};return debugs[set]},exports.inspect=inspect,inspect.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]},inspect.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"},exports.isArray=isArray,exports.isBoolean=isBoolean,exports.isNull=isNull,exports.isNullOrUndefined=isNullOrUndefined,exports.isNumber=isNumber,exports.isString=isString,exports.isSymbol=isSymbol,exports.isUndefined=isUndefined,exports.isRegExp=isRegExp,exports.isObject=isObject,exports.isDate=isDate,exports.isError=isError,exports.isFunction=isFunction,exports.isPrimitive=isPrimitive,exports.isBuffer=require("./support/isBuffer");var months=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function timestamp(){var d=new Date,time=[pad(d.getHours()),pad(d.getMinutes()),pad(d.getSeconds())].join(":");return[d.getDate(),months[d.getMonth()],time].join(" ")}function hasOwnProperty(obj,prop){return Object.prototype.hasOwnProperty.call(obj,prop)}exports.log=function(){console.log("%s - %s",timestamp(),exports.format.apply(exports,arguments))},exports.inherits=require("inherits"),exports._extend=function(origin,add){if(!add||!isObject(add))return origin;for(var keys=Object.keys(add),i=keys.length;i--;)origin[keys[i]]=add[keys[i]];return origin}}).call(this)}).call(this,require("_process"),void 0!==__webpack_require__.g?__webpack_require__.g:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./support/isBuffer":115,_process:89,inherits:114}],117:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var adapter=(0,require("./adapter_factory.js").adapterFactory)({window:"undefined"==typeof window?void 0:window});exports.default=adapter},{"./adapter_factory.js":118}],118:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.adapterFactory=adapterFactory;var utils=_interopRequireWildcard(require("./utils")),chromeShim=_interopRequireWildcard(require("./chrome/chrome_shim")),edgeShim=_interopRequireWildcard(require("./edge/edge_shim")),firefoxShim=_interopRequireWildcard(require("./firefox/firefox_shim")),safariShim=_interopRequireWildcard(require("./safari/safari_shim")),commonShim=_interopRequireWildcard(require("./common_shim"));function _interopRequireWildcard(obj){if(obj&&obj.__esModule)return obj;var newObj={};if(null!=obj)for(var key in obj)Object.prototype.hasOwnProperty.call(obj,key)&&(newObj[key]=obj[key]);return newObj.default=obj,newObj}function adapterFactory(){var window=(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}).window,options=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{shimChrome:!0,shimFirefox:!0,shimEdge:!0,shimSafari:!0},logging=utils.log,browserDetails=utils.detectBrowser(window),adapter={browserDetails,commonShim,extractVersion:utils.extractVersion,disableLog:utils.disableLog,disableWarnings:utils.disableWarnings};switch(browserDetails.browser){case"chrome":if(!chromeShim||!chromeShim.shimPeerConnection||!options.shimChrome)return logging("Chrome shim is not included in this adapter release."),adapter;if(null===browserDetails.version)return logging("Chrome shim can not determine version, not shimming."),adapter;logging("adapter.js shimming chrome."),adapter.browserShim=chromeShim,commonShim.shimAddIceCandidateNullOrEmpty(window,browserDetails),chromeShim.shimGetUserMedia(window,browserDetails),chromeShim.shimMediaStream(window,browserDetails),chromeShim.shimPeerConnection(window,browserDetails),chromeShim.shimOnTrack(window,browserDetails),chromeShim.shimAddTrackRemoveTrack(window,browserDetails),chromeShim.shimGetSendersWithDtmf(window,browserDetails),chromeShim.shimGetStats(window,browserDetails),chromeShim.shimSenderReceiverGetStats(window,browserDetails),chromeShim.fixNegotiationNeeded(window,browserDetails),commonShim.shimRTCIceCandidate(window,browserDetails),commonShim.shimConnectionState(window,browserDetails),commonShim.shimMaxMessageSize(window,browserDetails),commonShim.shimSendThrowTypeError(window,browserDetails),commonShim.removeExtmapAllowMixed(window,browserDetails);break;case"firefox":if(!firefoxShim||!firefoxShim.shimPeerConnection||!options.shimFirefox)return logging("Firefox shim is not included in this adapter release."),adapter;logging("adapter.js shimming firefox."),adapter.browserShim=firefoxShim,commonShim.shimAddIceCandidateNullOrEmpty(window,browserDetails),firefoxShim.shimGetUserMedia(window,browserDetails),firefoxShim.shimPeerConnection(window,browserDetails),firefoxShim.shimOnTrack(window,browserDetails),firefoxShim.shimRemoveStream(window,browserDetails),firefoxShim.shimSenderGetStats(window,browserDetails),firefoxShim.shimReceiverGetStats(window,browserDetails),firefoxShim.shimRTCDataChannel(window,browserDetails),firefoxShim.shimAddTransceiver(window,browserDetails),firefoxShim.shimGetParameters(window,browserDetails),firefoxShim.shimCreateOffer(window,browserDetails),firefoxShim.shimCreateAnswer(window,browserDetails),commonShim.shimRTCIceCandidate(window,browserDetails),commonShim.shimConnectionState(window,browserDetails),commonShim.shimMaxMessageSize(window,browserDetails),commonShim.shimSendThrowTypeError(window,browserDetails);break;case"edge":if(!edgeShim||!edgeShim.shimPeerConnection||!options.shimEdge)return logging("MS edge shim is not included in this adapter release."),adapter;logging("adapter.js shimming edge."),adapter.browserShim=edgeShim,edgeShim.shimGetUserMedia(window,browserDetails),edgeShim.shimGetDisplayMedia(window,browserDetails),edgeShim.shimPeerConnection(window,browserDetails),edgeShim.shimReplaceTrack(window,browserDetails),commonShim.shimMaxMessageSize(window,browserDetails),commonShim.shimSendThrowTypeError(window,browserDetails);break;case"safari":if(!safariShim||!options.shimSafari)return logging("Safari shim is not included in this adapter release."),adapter;logging("adapter.js shimming safari."),adapter.browserShim=safariShim,commonShim.shimAddIceCandidateNullOrEmpty(window,browserDetails),safariShim.shimRTCIceServerUrls(window,browserDetails),safariShim.shimCreateOfferLegacy(window,browserDetails),safariShim.shimCallbacksAPI(window,browserDetails),safariShim.shimLocalStreamsAPI(window,browserDetails),safariShim.shimRemoteStreamsAPI(window,browserDetails),safariShim.shimTrackEventTransceiver(window,browserDetails),safariShim.shimGetUserMedia(window,browserDetails),safariShim.shimAudioContext(window,browserDetails),commonShim.shimRTCIceCandidate(window,browserDetails),commonShim.shimMaxMessageSize(window,browserDetails),commonShim.shimSendThrowTypeError(window,browserDetails),commonShim.removeExtmapAllowMixed(window,browserDetails);break;default:logging("Unsupported browser!")}return adapter}},{"./chrome/chrome_shim":119,"./common_shim":122,"./edge/edge_shim":123,"./firefox/firefox_shim":127,"./safari/safari_shim":130,"./utils":131}],119:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.shimGetDisplayMedia=exports.shimGetUserMedia=void 0;var _typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(obj){return typeof obj}:function(obj){return obj&&"function"==typeof Symbol&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj},_getusermedia=require("./getusermedia");Object.defineProperty(exports,"shimGetUserMedia",{enumerable:!0,get:function get(){return _getusermedia.shimGetUserMedia}});var _getdisplaymedia=require("./getdisplaymedia");Object.defineProperty(exports,"shimGetDisplayMedia",{enumerable:!0,get:function get(){return _getdisplaymedia.shimGetDisplayMedia}}),exports.shimMediaStream=shimMediaStream,exports.shimOnTrack=shimOnTrack,exports.shimGetSendersWithDtmf=shimGetSendersWithDtmf,exports.shimGetStats=shimGetStats,exports.shimSenderReceiverGetStats=shimSenderReceiverGetStats,exports.shimAddTrackRemoveTrackWithNative=shimAddTrackRemoveTrackWithNative,exports.shimAddTrackRemoveTrack=shimAddTrackRemoveTrack,exports.shimPeerConnection=shimPeerConnection,exports.fixNegotiationNeeded=fixNegotiationNeeded;var utils=_interopRequireWildcard(require("../utils.js"));function _interopRequireWildcard(obj){if(obj&&obj.__esModule)return obj;var newObj={};if(null!=obj)for(var key in obj)Object.prototype.hasOwnProperty.call(obj,key)&&(newObj[key]=obj[key]);return newObj.default=obj,newObj}function _defineProperty(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}function shimMediaStream(window){window.MediaStream=window.MediaStream||window.webkitMediaStream}function shimOnTrack(window){if("object"===(void 0===window?"undefined":_typeof(window))&&window.RTCPeerConnection&&!("ontrack"in window.RTCPeerConnection.prototype)){Object.defineProperty(window.RTCPeerConnection.prototype,"ontrack",{get:function get(){return this._ontrack},set:function set(f){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=f)},enumerable:!0,configurable:!0});var origSetRemoteDescription=window.RTCPeerConnection.prototype.setRemoteDescription;window.RTCPeerConnection.prototype.setRemoteDescription=function setRemoteDescription(){var _this=this;return this._ontrackpoly||(this._ontrackpoly=function(e){e.stream.addEventListener("addtrack",function(te){var receiver=void 0;receiver=window.RTCPeerConnection.prototype.getReceivers?_this.getReceivers().find(function(r){return r.track&&r.track.id===te.track.id}):{track:te.track};var event=new Event("track");event.track=te.track,event.receiver=receiver,event.transceiver={receiver},event.streams=[e.stream],_this.dispatchEvent(event)}),e.stream.getTracks().forEach(function(track){var receiver=void 0;receiver=window.RTCPeerConnection.prototype.getReceivers?_this.getReceivers().find(function(r){return r.track&&r.track.id===track.id}):{track};var event=new Event("track");event.track=track,event.receiver=receiver,event.transceiver={receiver},event.streams=[e.stream],_this.dispatchEvent(event)})},this.addEventListener("addstream",this._ontrackpoly)),origSetRemoteDescription.apply(this,arguments)}}else utils.wrapPeerConnectionEvent(window,"track",function(e){return e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e})}function shimGetSendersWithDtmf(window){if("object"===(void 0===window?"undefined":_typeof(window))&&window.RTCPeerConnection&&!("getSenders"in window.RTCPeerConnection.prototype)&&"createDTMFSender"in window.RTCPeerConnection.prototype){var shimSenderWithDtmf=function shimSenderWithDtmf(pc,track){return{track,get dtmf(){return void 0===this._dtmf&&("audio"===track.kind?this._dtmf=pc.createDTMFSender(track):this._dtmf=null),this._dtmf},_pc:pc}};if(!window.RTCPeerConnection.prototype.getSenders){window.RTCPeerConnection.prototype.getSenders=function getSenders(){return this._senders=this._senders||[],this._senders.slice()};var origAddTrack=window.RTCPeerConnection.prototype.addTrack;window.RTCPeerConnection.prototype.addTrack=function addTrack(track,stream){var sender=origAddTrack.apply(this,arguments);return sender||(sender=shimSenderWithDtmf(this,track),this._senders.push(sender)),sender};var origRemoveTrack=window.RTCPeerConnection.prototype.removeTrack;window.RTCPeerConnection.prototype.removeTrack=function removeTrack(sender){origRemoveTrack.apply(this,arguments);var idx=this._senders.indexOf(sender);-1!==idx&&this._senders.splice(idx,1)}}var origAddStream=window.RTCPeerConnection.prototype.addStream;window.RTCPeerConnection.prototype.addStream=function addStream(stream){var _this2=this;this._senders=this._senders||[],origAddStream.apply(this,[stream]),stream.getTracks().forEach(function(track){_this2._senders.push(shimSenderWithDtmf(_this2,track))})};var origRemoveStream=window.RTCPeerConnection.prototype.removeStream;window.RTCPeerConnection.prototype.removeStream=function removeStream(stream){var _this3=this;this._senders=this._senders||[],origRemoveStream.apply(this,[stream]),stream.getTracks().forEach(function(track){var sender=_this3._senders.find(function(s){return s.track===track});sender&&_this3._senders.splice(_this3._senders.indexOf(sender),1)})}}else if("object"===(void 0===window?"undefined":_typeof(window))&&window.RTCPeerConnection&&"getSenders"in window.RTCPeerConnection.prototype&&"createDTMFSender"in window.RTCPeerConnection.prototype&&window.RTCRtpSender&&!("dtmf"in window.RTCRtpSender.prototype)){var origGetSenders=window.RTCPeerConnection.prototype.getSenders;window.RTCPeerConnection.prototype.getSenders=function getSenders(){var _this4=this,senders=origGetSenders.apply(this,[]);return senders.forEach(function(sender){return sender._pc=_this4}),senders},Object.defineProperty(window.RTCRtpSender.prototype,"dtmf",{get:function get(){return void 0===this._dtmf&&("audio"===this.track.kind?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}}function shimGetStats(window){if(window.RTCPeerConnection){var origGetStats=window.RTCPeerConnection.prototype.getStats;window.RTCPeerConnection.prototype.getStats=function getStats(){var _this5=this,_arguments=Array.prototype.slice.call(arguments),selector=_arguments[0],onSucc=_arguments[1],onErr=_arguments[2];if(arguments.length>0&&"function"==typeof selector)return origGetStats.apply(this,arguments);if(0===origGetStats.length&&(0===arguments.length||"function"!=typeof selector))return origGetStats.apply(this,[]);var fixChromeStats_=function fixChromeStats_(response){var standardReport={};return response.result().forEach(function(report){var standardStats={id:report.id,timestamp:report.timestamp,type:{localcandidate:"local-candidate",remotecandidate:"remote-candidate"}[report.type]||report.type};report.names().forEach(function(name){standardStats[name]=report.stat(name)}),standardReport[standardStats.id]=standardStats}),standardReport},makeMapStats=function makeMapStats(stats){return new Map(Object.keys(stats).map(function(key){return[key,stats[key]]}))};if(arguments.length>=2){var successCallbackWrapper_=function successCallbackWrapper_(response){onSucc(makeMapStats(fixChromeStats_(response)))};return origGetStats.apply(this,[successCallbackWrapper_,selector])}return new Promise(function(resolve,reject){origGetStats.apply(_this5,[function(response){resolve(makeMapStats(fixChromeStats_(response)))},reject])}).then(onSucc,onErr)}}}function shimSenderReceiverGetStats(window){if("object"===(void 0===window?"undefined":_typeof(window))&&window.RTCPeerConnection&&window.RTCRtpSender&&window.RTCRtpReceiver){if(!("getStats"in window.RTCRtpSender.prototype)){var origGetSenders=window.RTCPeerConnection.prototype.getSenders;origGetSenders&&(window.RTCPeerConnection.prototype.getSenders=function getSenders(){var _this6=this,senders=origGetSenders.apply(this,[]);return senders.forEach(function(sender){return sender._pc=_this6}),senders});var origAddTrack=window.RTCPeerConnection.prototype.addTrack;origAddTrack&&(window.RTCPeerConnection.prototype.addTrack=function addTrack(){var sender=origAddTrack.apply(this,arguments);return sender._pc=this,sender}),window.RTCRtpSender.prototype.getStats=function getStats(){var sender=this;return this._pc.getStats().then(function(result){return utils.filterStats(result,sender.track,!0)})}}if(!("getStats"in window.RTCRtpReceiver.prototype)){var origGetReceivers=window.RTCPeerConnection.prototype.getReceivers;origGetReceivers&&(window.RTCPeerConnection.prototype.getReceivers=function getReceivers(){var _this7=this,receivers=origGetReceivers.apply(this,[]);return receivers.forEach(function(receiver){return receiver._pc=_this7}),receivers}),utils.wrapPeerConnectionEvent(window,"track",function(e){return e.receiver._pc=e.srcElement,e}),window.RTCRtpReceiver.prototype.getStats=function getStats(){var receiver=this;return this._pc.getStats().then(function(result){return utils.filterStats(result,receiver.track,!1)})}}if("getStats"in window.RTCRtpSender.prototype&&"getStats"in window.RTCRtpReceiver.prototype){var origGetStats=window.RTCPeerConnection.prototype.getStats;window.RTCPeerConnection.prototype.getStats=function getStats(){if(arguments.length>0&&arguments[0]instanceof window.MediaStreamTrack){var track=arguments[0],sender=void 0,receiver=void 0,err=void 0;return this.getSenders().forEach(function(s){s.track===track&&(sender?err=!0:sender=s)}),this.getReceivers().forEach(function(r){return r.track===track&&(receiver?err=!0:receiver=r),r.track===track}),err||sender&&receiver?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):sender?sender.getStats():receiver?receiver.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return origGetStats.apply(this,arguments)}}}}function shimAddTrackRemoveTrackWithNative(window){window.RTCPeerConnection.prototype.getLocalStreams=function getLocalStreams(){var _this8=this;return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map(function(streamId){return _this8._shimmedLocalStreams[streamId][0]})};var origAddTrack=window.RTCPeerConnection.prototype.addTrack;window.RTCPeerConnection.prototype.addTrack=function addTrack(track,stream){if(!stream)return origAddTrack.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};var sender=origAddTrack.apply(this,arguments);return this._shimmedLocalStreams[stream.id]?-1===this._shimmedLocalStreams[stream.id].indexOf(sender)&&this._shimmedLocalStreams[stream.id].push(sender):this._shimmedLocalStreams[stream.id]=[stream,sender],sender};var origAddStream=window.RTCPeerConnection.prototype.addStream;window.RTCPeerConnection.prototype.addStream=function addStream(stream){var _this9=this;this._shimmedLocalStreams=this._shimmedLocalStreams||{},stream.getTracks().forEach(function(track){if(_this9.getSenders().find(function(s){return s.track===track}))throw new DOMException("Track already exists.","InvalidAccessError")});var existingSenders=this.getSenders();origAddStream.apply(this,arguments);var newSenders=this.getSenders().filter(function(newSender){return-1===existingSenders.indexOf(newSender)});this._shimmedLocalStreams[stream.id]=[stream].concat(newSenders)};var origRemoveStream=window.RTCPeerConnection.prototype.removeStream;window.RTCPeerConnection.prototype.removeStream=function removeStream(stream){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[stream.id],origRemoveStream.apply(this,arguments)};var origRemoveTrack=window.RTCPeerConnection.prototype.removeTrack;window.RTCPeerConnection.prototype.removeTrack=function removeTrack(sender){var _this10=this;return this._shimmedLocalStreams=this._shimmedLocalStreams||{},sender&&Object.keys(this._shimmedLocalStreams).forEach(function(streamId){var idx=_this10._shimmedLocalStreams[streamId].indexOf(sender);-1!==idx&&_this10._shimmedLocalStreams[streamId].splice(idx,1),1===_this10._shimmedLocalStreams[streamId].length&&delete _this10._shimmedLocalStreams[streamId]}),origRemoveTrack.apply(this,arguments)}}function shimAddTrackRemoveTrack(window,browserDetails){if(window.RTCPeerConnection){if(window.RTCPeerConnection.prototype.addTrack&&browserDetails.version>=65)return shimAddTrackRemoveTrackWithNative(window);var origGetLocalStreams=window.RTCPeerConnection.prototype.getLocalStreams;window.RTCPeerConnection.prototype.getLocalStreams=function getLocalStreams(){var _this11=this,nativeStreams=origGetLocalStreams.apply(this);return this._reverseStreams=this._reverseStreams||{},nativeStreams.map(function(stream){return _this11._reverseStreams[stream.id]})};var origAddStream=window.RTCPeerConnection.prototype.addStream;window.RTCPeerConnection.prototype.addStream=function addStream(stream){var _this12=this;if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},stream.getTracks().forEach(function(track){if(_this12.getSenders().find(function(s){return s.track===track}))throw new DOMException("Track already exists.","InvalidAccessError")}),!this._reverseStreams[stream.id]){var newStream=new window.MediaStream(stream.getTracks());this._streams[stream.id]=newStream,this._reverseStreams[newStream.id]=stream,stream=newStream}origAddStream.apply(this,[stream])};var origRemoveStream=window.RTCPeerConnection.prototype.removeStream;window.RTCPeerConnection.prototype.removeStream=function removeStream(stream){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},origRemoveStream.apply(this,[this._streams[stream.id]||stream]),delete this._reverseStreams[this._streams[stream.id]?this._streams[stream.id].id:stream.id],delete this._streams[stream.id]},window.RTCPeerConnection.prototype.addTrack=function addTrack(track,stream){var _this13=this;if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");var streams=[].slice.call(arguments,1);if(1!==streams.length||!streams[0].getTracks().find(function(t){return t===track}))throw new DOMException("The adapter.js addTrack polyfill only supports a single stream which is associated with the specified track.","NotSupportedError");if(this.getSenders().find(function(s){return s.track===track}))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};var oldStream=this._streams[stream.id];if(oldStream)oldStream.addTrack(track),Promise.resolve().then(function(){_this13.dispatchEvent(new Event("negotiationneeded"))});else{var newStream=new window.MediaStream([track]);this._streams[stream.id]=newStream,this._reverseStreams[newStream.id]=stream,this.addStream(newStream)}return this.getSenders().find(function(s){return s.track===track})},["createOffer","createAnswer"].forEach(function(method){var nativeMethod=window.RTCPeerConnection.prototype[method],methodObj=_defineProperty({},method,function(){var _this14=this,args=arguments;return arguments.length&&"function"==typeof arguments[0]?nativeMethod.apply(this,[function(description){var desc=replaceInternalStreamId(_this14,description);args[0].apply(null,[desc])},function(err){args[1]&&args[1].apply(null,err)},arguments[2]]):nativeMethod.apply(this,arguments).then(function(description){return replaceInternalStreamId(_this14,description)})});window.RTCPeerConnection.prototype[method]=methodObj[method]});var origSetLocalDescription=window.RTCPeerConnection.prototype.setLocalDescription;window.RTCPeerConnection.prototype.setLocalDescription=function setLocalDescription(){return arguments.length&&arguments[0].type?(arguments[0]=replaceExternalStreamId(this,arguments[0]),origSetLocalDescription.apply(this,arguments)):origSetLocalDescription.apply(this,arguments)};var origLocalDescription=Object.getOwnPropertyDescriptor(window.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(window.RTCPeerConnection.prototype,"localDescription",{get:function get(){var description=origLocalDescription.get.apply(this);return""===description.type?description:replaceInternalStreamId(this,description)}}),window.RTCPeerConnection.prototype.removeTrack=function removeTrack(sender){var _this15=this;if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!sender._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(sender._pc!==this)throw new DOMException("Sender was not created by this connection.","InvalidAccessError");this._streams=this._streams||{};var stream=void 0;Object.keys(this._streams).forEach(function(streamid){_this15._streams[streamid].getTracks().find(function(track){return sender.track===track})&&(stream=_this15._streams[streamid])}),stream&&(1===stream.getTracks().length?this.removeStream(this._reverseStreams[stream.id]):stream.removeTrack(sender.track),this.dispatchEvent(new Event("negotiationneeded")))}}function replaceInternalStreamId(pc,description){var sdp=description.sdp;return Object.keys(pc._reverseStreams||[]).forEach(function(internalId){var externalStream=pc._reverseStreams[internalId],internalStream=pc._streams[externalStream.id];sdp=sdp.replace(new RegExp(internalStream.id,"g"),externalStream.id)}),new RTCSessionDescription({type:description.type,sdp})}function replaceExternalStreamId(pc,description){var sdp=description.sdp;return Object.keys(pc._reverseStreams||[]).forEach(function(internalId){var externalStream=pc._reverseStreams[internalId],internalStream=pc._streams[externalStream.id];sdp=sdp.replace(new RegExp(externalStream.id,"g"),internalStream.id)}),new RTCSessionDescription({type:description.type,sdp})}}function shimPeerConnection(window,browserDetails){!window.RTCPeerConnection&&window.webkitRTCPeerConnection&&(window.RTCPeerConnection=window.webkitRTCPeerConnection),window.RTCPeerConnection&&browserDetails.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(method){var nativeMethod=window.RTCPeerConnection.prototype[method],methodObj=_defineProperty({},method,function(){return arguments[0]=new("addIceCandidate"===method?window.RTCIceCandidate:window.RTCSessionDescription)(arguments[0]),nativeMethod.apply(this,arguments)});window.RTCPeerConnection.prototype[method]=methodObj[method]})}function fixNegotiationNeeded(window,browserDetails){utils.wrapPeerConnectionEvent(window,"negotiationneeded",function(e){var pc=e.target;if(!(browserDetails.version<72||pc.getConfiguration&&"plan-b"===pc.getConfiguration().sdpSemantics)||"stable"===pc.signalingState)return e})}},{"../utils.js":131,"./getdisplaymedia":120,"./getusermedia":121}],120:[function(require,module,exports){"use strict";function shimGetDisplayMedia(window,getSourceId){window.navigator.mediaDevices&&"getDisplayMedia"in window.navigator.mediaDevices||window.navigator.mediaDevices&&("function"==typeof getSourceId?window.navigator.mediaDevices.getDisplayMedia=function getDisplayMedia(constraints){return getSourceId(constraints).then(function(sourceId){var widthSpecified=constraints.video&&constraints.video.width,heightSpecified=constraints.video&&constraints.video.height,frameRateSpecified=constraints.video&&constraints.video.frameRate;return constraints.video={mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:sourceId,maxFrameRate:frameRateSpecified||3}},widthSpecified&&(constraints.video.mandatory.maxWidth=widthSpecified),heightSpecified&&(constraints.video.mandatory.maxHeight=heightSpecified),window.navigator.mediaDevices.getUserMedia(constraints)})}:console.error("shimGetDisplayMedia: getSourceId argument is not a function"))}Object.defineProperty(exports,"__esModule",{value:!0}),exports.shimGetDisplayMedia=shimGetDisplayMedia},{}],121:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var _typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(obj){return typeof obj}:function(obj){return obj&&"function"==typeof Symbol&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj};function _interopRequireWildcard(obj){if(obj&&obj.__esModule)return obj;var newObj={};if(null!=obj)for(var key in obj)Object.prototype.hasOwnProperty.call(obj,key)&&(newObj[key]=obj[key]);return newObj.default=obj,newObj}exports.shimGetUserMedia=shimGetUserMedia;var logging=_interopRequireWildcard(require("../utils.js")).log;function shimGetUserMedia(window,browserDetails){var navigator=window&&window.navigator;if(navigator.mediaDevices){var constraintsToChrome_=function constraintsToChrome_(c){if("object"!==(void 0===c?"undefined":_typeof(c))||c.mandatory||c.optional)return c;var cc={};return Object.keys(c).forEach(function(key){if("require"!==key&&"advanced"!==key&&"mediaSource"!==key){var r="object"===_typeof(c[key])?c[key]:{ideal:c[key]};void 0!==r.exact&&"number"==typeof r.exact&&(r.min=r.max=r.exact);var oldname_=function oldname_(prefix,name){return prefix?prefix+name.charAt(0).toUpperCase()+name.slice(1):"deviceId"===name?"sourceId":name};if(void 0!==r.ideal){cc.optional=cc.optional||[];var oc={};"number"==typeof r.ideal?(oc[oldname_("min",key)]=r.ideal,cc.optional.push(oc),(oc={})[oldname_("max",key)]=r.ideal,cc.optional.push(oc)):(oc[oldname_("",key)]=r.ideal,cc.optional.push(oc))}void 0!==r.exact&&"number"!=typeof r.exact?(cc.mandatory=cc.mandatory||{},cc.mandatory[oldname_("",key)]=r.exact):["min","max"].forEach(function(mix){void 0!==r[mix]&&(cc.mandatory=cc.mandatory||{},cc.mandatory[oldname_(mix,key)]=r[mix])})}}),c.advanced&&(cc.optional=(cc.optional||[]).concat(c.advanced)),cc},shimConstraints_=function shimConstraints_(constraints,func){if(browserDetails.version>=61)return func(constraints);if((constraints=JSON.parse(JSON.stringify(constraints)))&&"object"===_typeof(constraints.audio)){var remap=function remap(obj,a,b){a in obj&&!(b in obj)&&(obj[b]=obj[a],delete obj[a])};remap((constraints=JSON.parse(JSON.stringify(constraints))).audio,"autoGainControl","googAutoGainControl"),remap(constraints.audio,"noiseSuppression","googNoiseSuppression"),constraints.audio=constraintsToChrome_(constraints.audio)}if(constraints&&"object"===_typeof(constraints.video)){var face=constraints.video.facingMode;face=face&&("object"===(void 0===face?"undefined":_typeof(face))?face:{ideal:face});var getSupportedFacingModeLies=browserDetails.version<66;if(face&&("user"===face.exact||"environment"===face.exact||"user"===face.ideal||"environment"===face.ideal)&&(!navigator.mediaDevices.getSupportedConstraints||!navigator.mediaDevices.getSupportedConstraints().facingMode||getSupportedFacingModeLies)){delete constraints.video.facingMode;var matches=void 0;if("environment"===face.exact||"environment"===face.ideal?matches=["back","rear"]:"user"!==face.exact&&"user"!==face.ideal||(matches=["front"]),matches)return navigator.mediaDevices.enumerateDevices().then(function(devices){var dev=(devices=devices.filter(function(d){return"videoinput"===d.kind})).find(function(d){return matches.some(function(match){return d.label.toLowerCase().includes(match)})});return!dev&&devices.length&&matches.includes("back")&&(dev=devices[devices.length-1]),dev&&(constraints.video.deviceId=face.exact?{exact:dev.deviceId}:{ideal:dev.deviceId}),constraints.video=constraintsToChrome_(constraints.video),logging("chrome: "+JSON.stringify(constraints)),func(constraints)})}constraints.video=constraintsToChrome_(constraints.video)}return logging("chrome: "+JSON.stringify(constraints)),func(constraints)},shimError_=function shimError_(e){return browserDetails.version>=64?e:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[e.name]||e.name,message:e.message,constraint:e.constraint||e.constraintName,toString:function toString(){return this.name+(this.message&&": ")+this.message}}},getUserMedia_=function getUserMedia_(constraints,onSuccess,onError){shimConstraints_(constraints,function(c){navigator.webkitGetUserMedia(c,onSuccess,function(e){onError&&onError(shimError_(e))})})};if(navigator.getUserMedia=getUserMedia_.bind(navigator),navigator.mediaDevices.getUserMedia){var origGetUserMedia=navigator.mediaDevices.getUserMedia.bind(navigator.mediaDevices);navigator.mediaDevices.getUserMedia=function(cs){return shimConstraints_(cs,function(c){return origGetUserMedia(c).then(function(stream){if(c.audio&&!stream.getAudioTracks().length||c.video&&!stream.getVideoTracks().length)throw stream.getTracks().forEach(function(track){track.stop()}),new DOMException("","NotFoundError");return stream},function(e){return Promise.reject(shimError_(e))})})}}}}},{"../utils.js":131}],122:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var _typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(obj){return typeof obj}:function(obj){return obj&&"function"==typeof Symbol&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj};exports.shimRTCIceCandidate=shimRTCIceCandidate,exports.shimMaxMessageSize=shimMaxMessageSize,exports.shimSendThrowTypeError=shimSendThrowTypeError,exports.shimConnectionState=shimConnectionState,exports.removeExtmapAllowMixed=removeExtmapAllowMixed,exports.shimAddIceCandidateNullOrEmpty=shimAddIceCandidateNullOrEmpty;var _sdp2=_interopRequireDefault(require("sdp")),utils=_interopRequireWildcard(require("./utils"));function _interopRequireWildcard(obj){if(obj&&obj.__esModule)return obj;var newObj={};if(null!=obj)for(var key in obj)Object.prototype.hasOwnProperty.call(obj,key)&&(newObj[key]=obj[key]);return newObj.default=obj,newObj}function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function shimRTCIceCandidate(window){if(!(!window.RTCIceCandidate||window.RTCIceCandidate&&"foundation"in window.RTCIceCandidate.prototype)){var NativeRTCIceCandidate=window.RTCIceCandidate;window.RTCIceCandidate=function RTCIceCandidate(args){if("object"===(void 0===args?"undefined":_typeof(args))&&args.candidate&&0===args.candidate.indexOf("a=")&&((args=JSON.parse(JSON.stringify(args))).candidate=args.candidate.substr(2)),args.candidate&&args.candidate.length){var nativeCandidate=new NativeRTCIceCandidate(args),parsedCandidate=_sdp2.default.parseCandidate(args.candidate),augmentedCandidate=Object.assign(nativeCandidate,parsedCandidate);return augmentedCandidate.toJSON=function toJSON(){return{candidate:augmentedCandidate.candidate,sdpMid:augmentedCandidate.sdpMid,sdpMLineIndex:augmentedCandidate.sdpMLineIndex,usernameFragment:augmentedCandidate.usernameFragment}},augmentedCandidate}return new NativeRTCIceCandidate(args)},window.RTCIceCandidate.prototype=NativeRTCIceCandidate.prototype,utils.wrapPeerConnectionEvent(window,"icecandidate",function(e){return e.candidate&&Object.defineProperty(e,"candidate",{value:new window.RTCIceCandidate(e.candidate),writable:"false"}),e})}}function shimMaxMessageSize(window,browserDetails){if(window.RTCPeerConnection){"sctp"in window.RTCPeerConnection.prototype||Object.defineProperty(window.RTCPeerConnection.prototype,"sctp",{get:function get(){return void 0===this._sctp?null:this._sctp}});var sctpInDescription=function sctpInDescription(description){if(!description||!description.sdp)return!1;var sections=_sdp2.default.splitSections(description.sdp);return sections.shift(),sections.some(function(mediaSection){var mLine=_sdp2.default.parseMLine(mediaSection);return mLine&&"application"===mLine.kind&&-1!==mLine.protocol.indexOf("SCTP")})},getRemoteFirefoxVersion=function getRemoteFirefoxVersion(description){var match=description.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(null===match||match.length<2)return-1;var version=parseInt(match[1],10);return version!=version?-1:version},getCanSendMaxMessageSize=function getCanSendMaxMessageSize(remoteIsFirefox){var canSendMaxMessageSize=65536;return"firefox"===browserDetails.browser&&(canSendMaxMessageSize=browserDetails.version<57?-1===remoteIsFirefox?16384:2147483637:browserDetails.version<60?57===browserDetails.version?65535:65536:2147483637),canSendMaxMessageSize},getMaxMessageSize=function getMaxMessageSize(description,remoteIsFirefox){var maxMessageSize=65536;"firefox"===browserDetails.browser&&57===browserDetails.version&&(maxMessageSize=65535);var match=_sdp2.default.matchPrefix(description.sdp,"a=max-message-size:");return match.length>0?maxMessageSize=parseInt(match[0].substr(19),10):"firefox"===browserDetails.browser&&-1!==remoteIsFirefox&&(maxMessageSize=2147483637),maxMessageSize},origSetRemoteDescription=window.RTCPeerConnection.prototype.setRemoteDescription;window.RTCPeerConnection.prototype.setRemoteDescription=function setRemoteDescription(){if(this._sctp=null,"chrome"===browserDetails.browser&&browserDetails.version>=76&&"plan-b"===this.getConfiguration().sdpSemantics&&Object.defineProperty(this,"sctp",{get:function get(){return void 0===this._sctp?null:this._sctp},enumerable:!0,configurable:!0}),sctpInDescription(arguments[0])){var isFirefox=getRemoteFirefoxVersion(arguments[0]),canSendMMS=getCanSendMaxMessageSize(isFirefox),remoteMMS=getMaxMessageSize(arguments[0],isFirefox),maxMessageSize=void 0;maxMessageSize=0===canSendMMS&&0===remoteMMS?Number.POSITIVE_INFINITY:0===canSendMMS||0===remoteMMS?Math.max(canSendMMS,remoteMMS):Math.min(canSendMMS,remoteMMS);var sctp={};Object.defineProperty(sctp,"maxMessageSize",{get:function get(){return maxMessageSize}}),this._sctp=sctp}return origSetRemoteDescription.apply(this,arguments)}}}function shimSendThrowTypeError(window){if(window.RTCPeerConnection&&"createDataChannel"in window.RTCPeerConnection.prototype){var origCreateDataChannel=window.RTCPeerConnection.prototype.createDataChannel;window.RTCPeerConnection.prototype.createDataChannel=function createDataChannel(){var dataChannel=origCreateDataChannel.apply(this,arguments);return wrapDcSend(dataChannel,this),dataChannel},utils.wrapPeerConnectionEvent(window,"datachannel",function(e){return wrapDcSend(e.channel,e.target),e})}function wrapDcSend(dc,pc){var origDataChannelSend=dc.send;dc.send=function send(){var data=arguments[0],length=data.length||data.size||data.byteLength;if("open"===dc.readyState&&pc.sctp&&length>pc.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+pc.sctp.maxMessageSize+" bytes)");return origDataChannelSend.apply(dc,arguments)}}}function shimConnectionState(window){if(window.RTCPeerConnection&&!("connectionState"in window.RTCPeerConnection.prototype)){var proto=window.RTCPeerConnection.prototype;Object.defineProperty(proto,"connectionState",{get:function get(){return{completed:"connected",checking:"connecting"}[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(proto,"onconnectionstatechange",{get:function get(){return this._onconnectionstatechange||null},set:function set(cb){this._onconnectionstatechange&&(this.removeEventListener("connectionstatechange",this._onconnectionstatechange),delete this._onconnectionstatechange),cb&&this.addEventListener("connectionstatechange",this._onconnectionstatechange=cb)},enumerable:!0,configurable:!0}),["setLocalDescription","setRemoteDescription"].forEach(function(method){var origMethod=proto[method];proto[method]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=function(e){var pc=e.target;if(pc._lastConnectionState!==pc.connectionState){pc._lastConnectionState=pc.connectionState;var newEvent=new Event("connectionstatechange",e);pc.dispatchEvent(newEvent)}return e},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),origMethod.apply(this,arguments)}})}}function removeExtmapAllowMixed(window,browserDetails){if(window.RTCPeerConnection&&!("chrome"===browserDetails.browser&&browserDetails.version>=71||"safari"===browserDetails.browser&&browserDetails.version>=605)){var nativeSRD=window.RTCPeerConnection.prototype.setRemoteDescription;window.RTCPeerConnection.prototype.setRemoteDescription=function setRemoteDescription(desc){if(desc&&desc.sdp&&-1!==desc.sdp.indexOf("\na=extmap-allow-mixed")){var sdp=desc.sdp.split("\n").filter(function(line){return"a=extmap-allow-mixed"!==line.trim()}).join("\n");window.RTCSessionDescription&&desc instanceof window.RTCSessionDescription?arguments[0]=new window.RTCSessionDescription({type:desc.type,sdp}):desc.sdp=sdp}return nativeSRD.apply(this,arguments)}}}function shimAddIceCandidateNullOrEmpty(window,browserDetails){if(window.RTCPeerConnection&&window.RTCPeerConnection.prototype){var nativeAddIceCandidate=window.RTCPeerConnection.prototype.addIceCandidate;nativeAddIceCandidate&&0!==nativeAddIceCandidate.length&&(window.RTCPeerConnection.prototype.addIceCandidate=function addIceCandidate(){return arguments[0]?("chrome"===browserDetails.browser&&browserDetails.version<78||"firefox"===browserDetails.browser&&browserDetails.version<68||"safari"===browserDetails.browser)&&arguments[0]&&""===arguments[0].candidate?Promise.resolve():nativeAddIceCandidate.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}}},{"./utils":131,sdp:108}],123:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.shimGetDisplayMedia=exports.shimGetUserMedia=void 0;var _getusermedia=require("./getusermedia");Object.defineProperty(exports,"shimGetUserMedia",{enumerable:!0,get:function get(){return _getusermedia.shimGetUserMedia}});var _getdisplaymedia=require("./getdisplaymedia");Object.defineProperty(exports,"shimGetDisplayMedia",{enumerable:!0,get:function get(){return _getdisplaymedia.shimGetDisplayMedia}}),exports.shimPeerConnection=shimPeerConnection,exports.shimReplaceTrack=shimReplaceTrack;var utils=_interopRequireWildcard(require("../utils")),_filtericeservers=require("./filtericeservers"),_rtcpeerconnectionShim2=_interopRequireDefault(require("rtcpeerconnection-shim"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _interopRequireWildcard(obj){if(obj&&obj.__esModule)return obj;var newObj={};if(null!=obj)for(var key in obj)Object.prototype.hasOwnProperty.call(obj,key)&&(newObj[key]=obj[key]);return newObj.default=obj,newObj}function shimPeerConnection(window,browserDetails){if(window.RTCIceGatherer&&(window.RTCIceCandidate||(window.RTCIceCandidate=function RTCIceCandidate(args){return args}),window.RTCSessionDescription||(window.RTCSessionDescription=function RTCSessionDescription(args){return args}),browserDetails.version<15025)){var origMSTEnabled=Object.getOwnPropertyDescriptor(window.MediaStreamTrack.prototype,"enabled");Object.defineProperty(window.MediaStreamTrack.prototype,"enabled",{set:function set(value){origMSTEnabled.set.call(this,value);var ev=new Event("enabled");ev.enabled=value,this.dispatchEvent(ev)}})}window.RTCRtpSender&&!("dtmf"in window.RTCRtpSender.prototype)&&Object.defineProperty(window.RTCRtpSender.prototype,"dtmf",{get:function get(){return void 0===this._dtmf&&("audio"===this.track.kind?this._dtmf=new window.RTCDtmfSender(this):"video"===this.track.kind&&(this._dtmf=null)),this._dtmf}}),window.RTCDtmfSender&&!window.RTCDTMFSender&&(window.RTCDTMFSender=window.RTCDtmfSender);var RTCPeerConnectionShim=(0,_rtcpeerconnectionShim2.default)(window,browserDetails.version);window.RTCPeerConnection=function RTCPeerConnection(config){return config&&config.iceServers&&(config.iceServers=(0,_filtericeservers.filterIceServers)(config.iceServers,browserDetails.version),utils.log("ICE servers after filtering:",config.iceServers)),new RTCPeerConnectionShim(config)},window.RTCPeerConnection.prototype=RTCPeerConnectionShim.prototype}function shimReplaceTrack(window){window.RTCRtpSender&&!("replaceTrack"in window.RTCRtpSender.prototype)&&(window.RTCRtpSender.prototype.replaceTrack=window.RTCRtpSender.prototype.setTrack)}},{"../utils":131,"./filtericeservers":124,"./getdisplaymedia":125,"./getusermedia":126,"rtcpeerconnection-shim":106}],124:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.filterIceServers=filterIceServers;var utils=_interopRequireWildcard(require("../utils"));function _interopRequireWildcard(obj){if(obj&&obj.__esModule)return obj;var newObj={};if(null!=obj)for(var key in obj)Object.prototype.hasOwnProperty.call(obj,key)&&(newObj[key]=obj[key]);return newObj.default=obj,newObj}function filterIceServers(iceServers,edgeVersion){var hasTurn=!1;return(iceServers=JSON.parse(JSON.stringify(iceServers))).filter(function(server){if(server&&(server.urls||server.url)){var urls=server.urls||server.url;server.url&&!server.urls&&utils.deprecated("RTCIceServer.url","RTCIceServer.urls");var isString="string"==typeof urls;return isString&&(urls=[urls]),urls=urls.filter(function(url){if(0===url.indexOf("stun:"))return!1;var validTurn=url.startsWith("turn")&&!url.startsWith("turn:[")&&url.includes("transport=udp");return validTurn&&!hasTurn?(hasTurn=!0,!0):validTurn&&!hasTurn}),delete server.url,server.urls=isString?urls[0]:urls,!!urls.length}})}},{"../utils":131}],125:[function(require,module,exports){"use strict";function shimGetDisplayMedia(window){"getDisplayMedia"in window.navigator&&window.navigator.mediaDevices&&(window.navigator.mediaDevices&&"getDisplayMedia"in window.navigator.mediaDevices||(window.navigator.mediaDevices.getDisplayMedia=window.navigator.getDisplayMedia.bind(window.navigator)))}Object.defineProperty(exports,"__esModule",{value:!0}),exports.shimGetDisplayMedia=shimGetDisplayMedia},{}],126:[function(require,module,exports){"use strict";function shimGetUserMedia(window){var navigator=window&&window.navigator,shimError_=function shimError_(e){return{name:{PermissionDeniedError:"NotAllowedError"}[e.name]||e.name,message:e.message,constraint:e.constraint,toString:function toString(){return this.name}}},origGetUserMedia=navigator.mediaDevices.getUserMedia.bind(navigator.mediaDevices);navigator.mediaDevices.getUserMedia=function(c){return origGetUserMedia(c).catch(function(e){return Promise.reject(shimError_(e))})}}Object.defineProperty(exports,"__esModule",{value:!0}),exports.shimGetUserMedia=shimGetUserMedia},{}],127:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.shimGetDisplayMedia=exports.shimGetUserMedia=void 0;var _typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(obj){return typeof obj}:function(obj){return obj&&"function"==typeof Symbol&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj},_getusermedia=require("./getusermedia");Object.defineProperty(exports,"shimGetUserMedia",{enumerable:!0,get:function get(){return _getusermedia.shimGetUserMedia}});var _getdisplaymedia=require("./getdisplaymedia");Object.defineProperty(exports,"shimGetDisplayMedia",{enumerable:!0,get:function get(){return _getdisplaymedia.shimGetDisplayMedia}}),exports.shimOnTrack=shimOnTrack,exports.shimPeerConnection=shimPeerConnection,exports.shimSenderGetStats=shimSenderGetStats,exports.shimReceiverGetStats=shimReceiverGetStats,exports.shimRemoveStream=shimRemoveStream,exports.shimRTCDataChannel=shimRTCDataChannel,exports.shimAddTransceiver=shimAddTransceiver,exports.shimGetParameters=shimGetParameters,exports.shimCreateOffer=shimCreateOffer,exports.shimCreateAnswer=shimCreateAnswer;var utils=_interopRequireWildcard(require("../utils"));function _interopRequireWildcard(obj){if(obj&&obj.__esModule)return obj;var newObj={};if(null!=obj)for(var key in obj)Object.prototype.hasOwnProperty.call(obj,key)&&(newObj[key]=obj[key]);return newObj.default=obj,newObj}function _defineProperty(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}function shimOnTrack(window){"object"===(void 0===window?"undefined":_typeof(window))&&window.RTCTrackEvent&&"receiver"in window.RTCTrackEvent.prototype&&!("transceiver"in window.RTCTrackEvent.prototype)&&Object.defineProperty(window.RTCTrackEvent.prototype,"transceiver",{get:function get(){return{receiver:this.receiver}}})}function shimPeerConnection(window,browserDetails){if("object"===(void 0===window?"undefined":_typeof(window))&&(window.RTCPeerConnection||window.mozRTCPeerConnection)){!window.RTCPeerConnection&&window.mozRTCPeerConnection&&(window.RTCPeerConnection=window.mozRTCPeerConnection),browserDetails.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(method){var nativeMethod=window.RTCPeerConnection.prototype[method],methodObj=_defineProperty({},method,function(){return arguments[0]=new("addIceCandidate"===method?window.RTCIceCandidate:window.RTCSessionDescription)(arguments[0]),nativeMethod.apply(this,arguments)});window.RTCPeerConnection.prototype[method]=methodObj[method]});var modernStatsTypes={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},nativeGetStats=window.RTCPeerConnection.prototype.getStats;window.RTCPeerConnection.prototype.getStats=function getStats(){var _arguments=Array.prototype.slice.call(arguments),selector=_arguments[0],onSucc=_arguments[1],onErr=_arguments[2];return nativeGetStats.apply(this,[selector||null]).then(function(stats){if(browserDetails.version<53&&!onSucc)try{stats.forEach(function(stat){stat.type=modernStatsTypes[stat.type]||stat.type})}catch(e){if("TypeError"!==e.name)throw e;stats.forEach(function(stat,i){stats.set(i,Object.assign({},stat,{type:modernStatsTypes[stat.type]||stat.type}))})}return stats}).then(onSucc,onErr)}}}function shimSenderGetStats(window){if("object"===(void 0===window?"undefined":_typeof(window))&&window.RTCPeerConnection&&window.RTCRtpSender&&(!window.RTCRtpSender||!("getStats"in window.RTCRtpSender.prototype))){var origGetSenders=window.RTCPeerConnection.prototype.getSenders;origGetSenders&&(window.RTCPeerConnection.prototype.getSenders=function getSenders(){var _this=this,senders=origGetSenders.apply(this,[]);return senders.forEach(function(sender){return sender._pc=_this}),senders});var origAddTrack=window.RTCPeerConnection.prototype.addTrack;origAddTrack&&(window.RTCPeerConnection.prototype.addTrack=function addTrack(){var sender=origAddTrack.apply(this,arguments);return sender._pc=this,sender}),window.RTCRtpSender.prototype.getStats=function getStats(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}}function shimReceiverGetStats(window){if("object"===(void 0===window?"undefined":_typeof(window))&&window.RTCPeerConnection&&window.RTCRtpSender&&(!window.RTCRtpSender||!("getStats"in window.RTCRtpReceiver.prototype))){var origGetReceivers=window.RTCPeerConnection.prototype.getReceivers;origGetReceivers&&(window.RTCPeerConnection.prototype.getReceivers=function getReceivers(){var _this2=this,receivers=origGetReceivers.apply(this,[]);return receivers.forEach(function(receiver){return receiver._pc=_this2}),receivers}),utils.wrapPeerConnectionEvent(window,"track",function(e){return e.receiver._pc=e.srcElement,e}),window.RTCRtpReceiver.prototype.getStats=function getStats(){return this._pc.getStats(this.track)}}}function shimRemoveStream(window){window.RTCPeerConnection&&!("removeStream"in window.RTCPeerConnection.prototype)&&(window.RTCPeerConnection.prototype.removeStream=function removeStream(stream){var _this3=this;utils.deprecated("removeStream","removeTrack"),this.getSenders().forEach(function(sender){sender.track&&stream.getTracks().includes(sender.track)&&_this3.removeTrack(sender)})})}function shimRTCDataChannel(window){window.DataChannel&&!window.RTCDataChannel&&(window.RTCDataChannel=window.DataChannel)}function shimAddTransceiver(window){if("object"===(void 0===window?"undefined":_typeof(window))&&window.RTCPeerConnection){var origAddTransceiver=window.RTCPeerConnection.prototype.addTransceiver;origAddTransceiver&&(window.RTCPeerConnection.prototype.addTransceiver=function addTransceiver(){this.setParametersPromises=[];var initParameters=arguments[1],shouldPerformCheck=initParameters&&"sendEncodings"in initParameters;shouldPerformCheck&&initParameters.sendEncodings.forEach(function(encodingParam){if("rid"in encodingParam&&!/^[a-z0-9]{0,16}$/i.test(encodingParam.rid))throw new TypeError("Invalid RID value provided.");if("scaleResolutionDownBy"in encodingParam&&!(parseFloat(encodingParam.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in encodingParam&&!(parseFloat(encodingParam.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")});var transceiver=origAddTransceiver.apply(this,arguments);if(shouldPerformCheck){var sender=transceiver.sender,params=sender.getParameters();(!("encodings"in params)||1===params.encodings.length&&0===Object.keys(params.encodings[0]).length)&&(params.encodings=initParameters.sendEncodings,sender.sendEncodings=initParameters.sendEncodings,this.setParametersPromises.push(sender.setParameters(params).then(function(){delete sender.sendEncodings}).catch(function(){delete sender.sendEncodings})))}return transceiver})}}function shimGetParameters(window){if("object"===(void 0===window?"undefined":_typeof(window))&&window.RTCRtpSender){var origGetParameters=window.RTCRtpSender.prototype.getParameters;origGetParameters&&(window.RTCRtpSender.prototype.getParameters=function getParameters(){var params=origGetParameters.apply(this,arguments);return"encodings"in params||(params.encodings=[].concat(this.sendEncodings||[{}])),params})}}function shimCreateOffer(window){if("object"===(void 0===window?"undefined":_typeof(window))&&window.RTCPeerConnection){var origCreateOffer=window.RTCPeerConnection.prototype.createOffer;window.RTCPeerConnection.prototype.createOffer=function createOffer(){var _this4=this,_arguments2=arguments;return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(function(){return origCreateOffer.apply(_this4,_arguments2)}).finally(function(){_this4.setParametersPromises=[]}):origCreateOffer.apply(this,arguments)}}}function shimCreateAnswer(window){if("object"===(void 0===window?"undefined":_typeof(window))&&window.RTCPeerConnection){var origCreateAnswer=window.RTCPeerConnection.prototype.createAnswer;window.RTCPeerConnection.prototype.createAnswer=function createAnswer(){var _this5=this,_arguments3=arguments;return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(function(){return origCreateAnswer.apply(_this5,_arguments3)}).finally(function(){_this5.setParametersPromises=[]}):origCreateAnswer.apply(this,arguments)}}}},{"../utils":131,"./getdisplaymedia":128,"./getusermedia":129}],128:[function(require,module,exports){"use strict";function shimGetDisplayMedia(window,preferredMediaSource){window.navigator.mediaDevices&&"getDisplayMedia"in window.navigator.mediaDevices||window.navigator.mediaDevices&&(window.navigator.mediaDevices.getDisplayMedia=function getDisplayMedia(constraints){if(!constraints||!constraints.video){var err=new DOMException("getDisplayMedia without video constraints is undefined");return err.name="NotFoundError",err.code=8,Promise.reject(err)}return!0===constraints.video?constraints.video={mediaSource:preferredMediaSource}:constraints.video.mediaSource=preferredMediaSource,window.navigator.mediaDevices.getUserMedia(constraints)})}Object.defineProperty(exports,"__esModule",{value:!0}),exports.shimGetDisplayMedia=shimGetDisplayMedia},{}],129:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var _typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(obj){return typeof obj}:function(obj){return obj&&"function"==typeof Symbol&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj};exports.shimGetUserMedia=shimGetUserMedia;var utils=_interopRequireWildcard(require("../utils"));function _interopRequireWildcard(obj){if(obj&&obj.__esModule)return obj;var newObj={};if(null!=obj)for(var key in obj)Object.prototype.hasOwnProperty.call(obj,key)&&(newObj[key]=obj[key]);return newObj.default=obj,newObj}function shimGetUserMedia(window,browserDetails){var navigator=window&&window.navigator,MediaStreamTrack=window&&window.MediaStreamTrack;if(navigator.getUserMedia=function(constraints,onSuccess,onError){utils.deprecated("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),navigator.mediaDevices.getUserMedia(constraints).then(onSuccess,onError)},!(browserDetails.version>55&&"autoGainControl"in navigator.mediaDevices.getSupportedConstraints())){var remap=function remap(obj,a,b){a in obj&&!(b in obj)&&(obj[b]=obj[a],delete obj[a])},nativeGetUserMedia=navigator.mediaDevices.getUserMedia.bind(navigator.mediaDevices);if(navigator.mediaDevices.getUserMedia=function(c){return"object"===(void 0===c?"undefined":_typeof(c))&&"object"===_typeof(c.audio)&&(c=JSON.parse(JSON.stringify(c)),remap(c.audio,"autoGainControl","mozAutoGainControl"),remap(c.audio,"noiseSuppression","mozNoiseSuppression")),nativeGetUserMedia(c)},MediaStreamTrack&&MediaStreamTrack.prototype.getSettings){var nativeGetSettings=MediaStreamTrack.prototype.getSettings;MediaStreamTrack.prototype.getSettings=function(){var obj=nativeGetSettings.apply(this,arguments);return remap(obj,"mozAutoGainControl","autoGainControl"),remap(obj,"mozNoiseSuppression","noiseSuppression"),obj}}if(MediaStreamTrack&&MediaStreamTrack.prototype.applyConstraints){var nativeApplyConstraints=MediaStreamTrack.prototype.applyConstraints;MediaStreamTrack.prototype.applyConstraints=function(c){return"audio"===this.kind&&"object"===(void 0===c?"undefined":_typeof(c))&&(c=JSON.parse(JSON.stringify(c)),remap(c,"autoGainControl","mozAutoGainControl"),remap(c,"noiseSuppression","mozNoiseSuppression")),nativeApplyConstraints.apply(this,[c])}}}}},{"../utils":131}],130:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var _typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(obj){return typeof obj}:function(obj){return obj&&"function"==typeof Symbol&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj};exports.shimLocalStreamsAPI=shimLocalStreamsAPI,exports.shimRemoteStreamsAPI=shimRemoteStreamsAPI,exports.shimCallbacksAPI=shimCallbacksAPI,exports.shimGetUserMedia=shimGetUserMedia,exports.shimConstraints=shimConstraints,exports.shimRTCIceServerUrls=shimRTCIceServerUrls,exports.shimTrackEventTransceiver=shimTrackEventTransceiver,exports.shimCreateOfferLegacy=shimCreateOfferLegacy,exports.shimAudioContext=shimAudioContext;var utils=_interopRequireWildcard(require("../utils"));function _interopRequireWildcard(obj){if(obj&&obj.__esModule)return obj;var newObj={};if(null!=obj)for(var key in obj)Object.prototype.hasOwnProperty.call(obj,key)&&(newObj[key]=obj[key]);return newObj.default=obj,newObj}function shimLocalStreamsAPI(window){if("object"===(void 0===window?"undefined":_typeof(window))&&window.RTCPeerConnection){if("getLocalStreams"in window.RTCPeerConnection.prototype||(window.RTCPeerConnection.prototype.getLocalStreams=function getLocalStreams(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in window.RTCPeerConnection.prototype)){var _addTrack=window.RTCPeerConnection.prototype.addTrack;window.RTCPeerConnection.prototype.addStream=function addStream(stream){var _this=this;this._localStreams||(this._localStreams=[]),this._localStreams.includes(stream)||this._localStreams.push(stream),stream.getAudioTracks().forEach(function(track){return _addTrack.call(_this,track,stream)}),stream.getVideoTracks().forEach(function(track){return _addTrack.call(_this,track,stream)})},window.RTCPeerConnection.prototype.addTrack=function addTrack(track){for(var _this2=this,_len=arguments.length,streams=Array(_len>1?_len-1:0),_key=1;_key<_len;_key++)streams[_key-1]=arguments[_key];return streams&&streams.forEach(function(stream){_this2._localStreams?_this2._localStreams.includes(stream)||_this2._localStreams.push(stream):_this2._localStreams=[stream]}),_addTrack.apply(this,arguments)}}"removeStream"in window.RTCPeerConnection.prototype||(window.RTCPeerConnection.prototype.removeStream=function removeStream(stream){var _this3=this;this._localStreams||(this._localStreams=[]);var index=this._localStreams.indexOf(stream);if(-1!==index){this._localStreams.splice(index,1);var tracks=stream.getTracks();this.getSenders().forEach(function(sender){tracks.includes(sender.track)&&_this3.removeTrack(sender)})}})}}function shimRemoteStreamsAPI(window){if("object"===(void 0===window?"undefined":_typeof(window))&&window.RTCPeerConnection&&("getRemoteStreams"in window.RTCPeerConnection.prototype||(window.RTCPeerConnection.prototype.getRemoteStreams=function getRemoteStreams(){return this._remoteStreams?this._remoteStreams:[]}),!("onaddstream"in window.RTCPeerConnection.prototype))){Object.defineProperty(window.RTCPeerConnection.prototype,"onaddstream",{get:function get(){return this._onaddstream},set:function set(f){var _this4=this;this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=f),this.addEventListener("track",this._onaddstreampoly=function(e){e.streams.forEach(function(stream){if(_this4._remoteStreams||(_this4._remoteStreams=[]),!_this4._remoteStreams.includes(stream)){_this4._remoteStreams.push(stream);var event=new Event("addstream");event.stream=stream,_this4.dispatchEvent(event)}})})}});var origSetRemoteDescription=window.RTCPeerConnection.prototype.setRemoteDescription;window.RTCPeerConnection.prototype.setRemoteDescription=function setRemoteDescription(){var pc=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(e){e.streams.forEach(function(stream){if(pc._remoteStreams||(pc._remoteStreams=[]),!(pc._remoteStreams.indexOf(stream)>=0)){pc._remoteStreams.push(stream);var event=new Event("addstream");event.stream=stream,pc.dispatchEvent(event)}})}),origSetRemoteDescription.apply(pc,arguments)}}}function shimCallbacksAPI(window){if("object"===(void 0===window?"undefined":_typeof(window))&&window.RTCPeerConnection){var prototype=window.RTCPeerConnection.prototype,origCreateOffer=prototype.createOffer,origCreateAnswer=prototype.createAnswer,setLocalDescription=prototype.setLocalDescription,setRemoteDescription=prototype.setRemoteDescription,addIceCandidate=prototype.addIceCandidate;prototype.createOffer=function createOffer(successCallback,failureCallback){var options=arguments.length>=2?arguments[2]:arguments[0],promise=origCreateOffer.apply(this,[options]);return failureCallback?(promise.then(successCallback,failureCallback),Promise.resolve()):promise},prototype.createAnswer=function createAnswer(successCallback,failureCallback){var options=arguments.length>=2?arguments[2]:arguments[0],promise=origCreateAnswer.apply(this,[options]);return failureCallback?(promise.then(successCallback,failureCallback),Promise.resolve()):promise};var withCallback=function withCallback(description,successCallback,failureCallback){var promise=setLocalDescription.apply(this,[description]);return failureCallback?(promise.then(successCallback,failureCallback),Promise.resolve()):promise};prototype.setLocalDescription=withCallback,withCallback=function withCallback(description,successCallback,failureCallback){var promise=setRemoteDescription.apply(this,[description]);return failureCallback?(promise.then(successCallback,failureCallback),Promise.resolve()):promise},prototype.setRemoteDescription=withCallback,withCallback=function withCallback(candidate,successCallback,failureCallback){var promise=addIceCandidate.apply(this,[candidate]);return failureCallback?(promise.then(successCallback,failureCallback),Promise.resolve()):promise},prototype.addIceCandidate=withCallback}}function shimGetUserMedia(window){var navigator=window&&window.navigator;if(navigator.mediaDevices&&navigator.mediaDevices.getUserMedia){var mediaDevices=navigator.mediaDevices,_getUserMedia=mediaDevices.getUserMedia.bind(mediaDevices);navigator.mediaDevices.getUserMedia=function(constraints){return _getUserMedia(shimConstraints(constraints))}}!navigator.getUserMedia&&navigator.mediaDevices&&navigator.mediaDevices.getUserMedia&&(navigator.getUserMedia=function getUserMedia(constraints,cb,errcb){navigator.mediaDevices.getUserMedia(constraints).then(cb,errcb)}.bind(navigator))}function shimConstraints(constraints){return constraints&&void 0!==constraints.video?Object.assign({},constraints,{video:utils.compactObject(constraints.video)}):constraints}function shimRTCIceServerUrls(window){if(window.RTCPeerConnection){var OrigPeerConnection=window.RTCPeerConnection;window.RTCPeerConnection=function RTCPeerConnection(pcConfig,pcConstraints){if(pcConfig&&pcConfig.iceServers){for(var newIceServers=[],i=0;i<pcConfig.iceServers.length;i++){var server=pcConfig.iceServers[i];!server.hasOwnProperty("urls")&&server.hasOwnProperty("url")?(utils.deprecated("RTCIceServer.url","RTCIceServer.urls"),(server=JSON.parse(JSON.stringify(server))).urls=server.url,delete server.url,newIceServers.push(server)):newIceServers.push(pcConfig.iceServers[i])}pcConfig.iceServers=newIceServers}return new OrigPeerConnection(pcConfig,pcConstraints)},window.RTCPeerConnection.prototype=OrigPeerConnection.prototype,"generateCertificate"in OrigPeerConnection&&Object.defineProperty(window.RTCPeerConnection,"generateCertificate",{get:function get(){return OrigPeerConnection.generateCertificate}})}}function shimTrackEventTransceiver(window){"object"===(void 0===window?"undefined":_typeof(window))&&window.RTCTrackEvent&&"receiver"in window.RTCTrackEvent.prototype&&!("transceiver"in window.RTCTrackEvent.prototype)&&Object.defineProperty(window.RTCTrackEvent.prototype,"transceiver",{get:function get(){return{receiver:this.receiver}}})}function shimCreateOfferLegacy(window){var origCreateOffer=window.RTCPeerConnection.prototype.createOffer;window.RTCPeerConnection.prototype.createOffer=function createOffer(offerOptions){if(offerOptions){void 0!==offerOptions.offerToReceiveAudio&&(offerOptions.offerToReceiveAudio=!!offerOptions.offerToReceiveAudio);var audioTransceiver=this.getTransceivers().find(function(transceiver){return"audio"===transceiver.receiver.track.kind});!1===offerOptions.offerToReceiveAudio&&audioTransceiver?"sendrecv"===audioTransceiver.direction?audioTransceiver.setDirection?audioTransceiver.setDirection("sendonly"):audioTransceiver.direction="sendonly":"recvonly"===audioTransceiver.direction&&(audioTransceiver.setDirection?audioTransceiver.setDirection("inactive"):audioTransceiver.direction="inactive"):!0!==offerOptions.offerToReceiveAudio||audioTransceiver||this.addTransceiver("audio"),void 0!==offerOptions.offerToReceiveVideo&&(offerOptions.offerToReceiveVideo=!!offerOptions.offerToReceiveVideo);var videoTransceiver=this.getTransceivers().find(function(transceiver){return"video"===transceiver.receiver.track.kind});!1===offerOptions.offerToReceiveVideo&&videoTransceiver?"sendrecv"===videoTransceiver.direction?videoTransceiver.setDirection?videoTransceiver.setDirection("sendonly"):videoTransceiver.direction="sendonly":"recvonly"===videoTransceiver.direction&&(videoTransceiver.setDirection?videoTransceiver.setDirection("inactive"):videoTransceiver.direction="inactive"):!0!==offerOptions.offerToReceiveVideo||videoTransceiver||this.addTransceiver("video")}return origCreateOffer.apply(this,arguments)}}function shimAudioContext(window){"object"!==(void 0===window?"undefined":_typeof(window))||window.AudioContext||(window.AudioContext=window.webkitAudioContext)}},{"../utils":131}],131:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var _typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(obj){return typeof obj}:function(obj){return obj&&"function"==typeof Symbol&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj};function _defineProperty(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}exports.extractVersion=extractVersion,exports.wrapPeerConnectionEvent=wrapPeerConnectionEvent,exports.disableLog=disableLog,exports.disableWarnings=disableWarnings,exports.log=log,exports.deprecated=deprecated,exports.detectBrowser=detectBrowser,exports.compactObject=compactObject,exports.walkStats=walkStats,exports.filterStats=filterStats;var logDisabled_=!0,deprecationWarnings_=!0;function extractVersion(uastring,expr,pos){var match=uastring.match(expr);return match&&match.length>=pos&&parseInt(match[pos],10)}function wrapPeerConnectionEvent(window,eventNameToWrap,wrapper){if(window.RTCPeerConnection){var proto=window.RTCPeerConnection.prototype,nativeAddEventListener=proto.addEventListener;proto.addEventListener=function(nativeEventName,cb){if(nativeEventName!==eventNameToWrap)return nativeAddEventListener.apply(this,arguments);var wrappedCallback=function wrappedCallback(e){var modifiedEvent=wrapper(e);modifiedEvent&&(cb.handleEvent?cb.handleEvent(modifiedEvent):cb(modifiedEvent))};return this._eventMap=this._eventMap||{},this._eventMap[eventNameToWrap]||(this._eventMap[eventNameToWrap]=new Map),this._eventMap[eventNameToWrap].set(cb,wrappedCallback),nativeAddEventListener.apply(this,[nativeEventName,wrappedCallback])};var nativeRemoveEventListener=proto.removeEventListener;proto.removeEventListener=function(nativeEventName,cb){if(nativeEventName!==eventNameToWrap||!this._eventMap||!this._eventMap[eventNameToWrap])return nativeRemoveEventListener.apply(this,arguments);if(!this._eventMap[eventNameToWrap].has(cb))return nativeRemoveEventListener.apply(this,arguments);var unwrappedCb=this._eventMap[eventNameToWrap].get(cb);return this._eventMap[eventNameToWrap].delete(cb),0===this._eventMap[eventNameToWrap].size&&delete this._eventMap[eventNameToWrap],0===Object.keys(this._eventMap).length&&delete this._eventMap,nativeRemoveEventListener.apply(this,[nativeEventName,unwrappedCb])},Object.defineProperty(proto,"on"+eventNameToWrap,{get:function get(){return this["_on"+eventNameToWrap]},set:function set(cb){this["_on"+eventNameToWrap]&&(this.removeEventListener(eventNameToWrap,this["_on"+eventNameToWrap]),delete this["_on"+eventNameToWrap]),cb&&this.addEventListener(eventNameToWrap,this["_on"+eventNameToWrap]=cb)},enumerable:!0,configurable:!0})}}function disableLog(bool){return"boolean"!=typeof bool?new Error("Argument type: "+(void 0===bool?"undefined":_typeof(bool))+". Please use a boolean."):(logDisabled_=bool,bool?"adapter.js logging disabled":"adapter.js logging enabled")}function disableWarnings(bool){return"boolean"!=typeof bool?new Error("Argument type: "+(void 0===bool?"undefined":_typeof(bool))+". Please use a boolean."):(deprecationWarnings_=!bool,"adapter.js deprecation warnings "+(bool?"disabled":"enabled"))}function log(){if("object"===("undefined"==typeof window?"undefined":_typeof(window))){if(logDisabled_)return;"undefined"!=typeof console&&"function"==typeof console.log&&console.log.apply(console,arguments)}}function deprecated(oldMethod,newMethod){deprecationWarnings_&&console.warn(oldMethod+" is deprecated, please use "+newMethod+" instead.")}function detectBrowser(window){var result={browser:null,version:null};if(void 0===window||!window.navigator)return result.browser="Not a browser.",result;var navigator=window.navigator;if(navigator.mozGetUserMedia)result.browser="firefox",result.version=extractVersion(navigator.userAgent,/Firefox\/(\d+)\./,1);else if(navigator.webkitGetUserMedia||!1===window.isSecureContext&&window.webkitRTCPeerConnection&&!window.RTCIceGatherer)result.browser="chrome",result.version=extractVersion(navigator.userAgent,/Chrom(e|ium)\/(\d+)\./,2);else if(navigator.mediaDevices&&navigator.userAgent.match(/Edge\/(\d+).(\d+)$/))result.browser="edge",result.version=extractVersion(navigator.userAgent,/Edge\/(\d+).(\d+)$/,2);else{if(!window.RTCPeerConnection||!navigator.userAgent.match(/AppleWebKit\/(\d+)\./))return result.browser="Not a supported browser.",result;result.browser="safari",result.version=extractVersion(navigator.userAgent,/AppleWebKit\/(\d+)\./,1),result.supportsUnifiedPlan=window.RTCRtpTransceiver&&"currentDirection"in window.RTCRtpTransceiver.prototype}return result}function isObject(val){return"[object Object]"===Object.prototype.toString.call(val)}function compactObject(data){return isObject(data)?Object.keys(data).reduce(function(accumulator,key){var isObj=isObject(data[key]),value=isObj?compactObject(data[key]):data[key],isEmptyObject=isObj&&!Object.keys(value).length;return void 0===value||isEmptyObject?accumulator:Object.assign(accumulator,_defineProperty({},key,value))},{}):data}function walkStats(stats,base,resultSet){base&&!resultSet.has(base.id)&&(resultSet.set(base.id,base),Object.keys(base).forEach(function(name){name.endsWith("Id")?walkStats(stats,stats.get(base[name]),resultSet):name.endsWith("Ids")&&base[name].forEach(function(id){walkStats(stats,stats.get(id),resultSet)})}))}function filterStats(result,track,outbound){var streamStatsType=outbound?"outbound-rtp":"inbound-rtp",filteredResult=new Map;if(null===track)return filteredResult;var trackStats=[];return result.forEach(function(value){"track"===value.type&&value.trackIdentifier===track.id&&trackStats.push(value)}),trackStats.forEach(function(trackStat){result.forEach(function(stats){stats.type===streamStatsType&&stats.trackId===trackStat.id&&walkStats(result,stats,filteredResult)})}),filteredResult}},{}],132:[function(require,module,exports){"use strict";var XMPP,chatUtils=require("./qbChatHelpers"),config=require("../../qbConfig"),Utils=require("../../qbUtils"),StreamManagement=require("../../plugins/streamManagement"),unsupportedError="This function isn't supported outside of the browser (...yet)";if(Utils.getEnv().browser){var Connection=require("../../qbStrophe");Strophe.addNamespace("CARBONS",chatUtils.MARKERS.CARBONS),Strophe.addNamespace("CHAT_MARKERS",chatUtils.MARKERS.CHAT),Strophe.addNamespace("PRIVACY_LIST",chatUtils.MARKERS.PRIVACY),Strophe.addNamespace("CHAT_STATES",chatUtils.MARKERS.STATES)}else Utils.getEnv().nativescript?XMPP=require("nativescript-xmpp-client"):Utils.getEnv().node&&(XMPP=require("node-xmpp-client"));function ChatProxy(service){var originSendFunction,self=this;self.webrtcSignalingProcessor=null,Utils.getEnv().browser?(self.connection=Connection(self._OnLogListener.bind(this)),self.connection.XHandlerReferences=[],self.connection.XAddTrackedHandler=function(handler,ns,name,type,id,from,options){self.connection.XHandlerReferences.push(self.connection.addHandler(handler,ns,name,type,id,from,options))},self.connection.XDeleteHandlers=function(){for(;self.connection.XHandlerReferences.length;)self.connection.deleteHandler(self.connection.XHandlerReferences.pop())},originSendFunction=self.connection.send,self.connection.send=function(stanza){if(!self.connection.connected)throw new chatUtils.ChatNotConnectedError("Chat is not connected");originSendFunction.call(self.connection,stanza)}):(Utils.getEnv().nativescript?self.Client=new XMPP.Client({websocket:{url:config.chatProtocol.websocket},autostart:!1}):Utils.getEnv().node&&(self.Client=new XMPP({autostart:!1})),originSendFunction=self.Client.send,self.Client.send=function(stanza){Utils.QBLog("[QBChat]","SENT:",stanza.toString()),originSendFunction.call(self.Client,stanza)},self.nodeStanzasCallbacks={}),this.service=service,this.isConnected=!1,this._isConnecting=!1,this._isLogout=!1,this._checkConnectionTimer=void 0,this._checkConnectionPingTimer=void 0,this._chatPingFailedCounter=0,this._onlineStatus=!0,this._checkExpiredSessionTimer=void 0,this._sessionHasExpired=!1,this._pings={},this.helpers=new Helpers;var options={service,helpers:self.helpers,stropheClient:self.connection,xmppClient:self.Client,nodeStanzasCallbacks:self.nodeStanzasCallbacks};this.roster=new RosterProxy(options),this.privacylist=new PrivacyListProxy(options),this.muc=new MucProxy(options),this.chatUtils=chatUtils,config.streamManagement.enable&&(2===config.chatProtocol.active?(this.streamManagement=new StreamManagement(config.streamManagement),self._sentMessageCallback=function(messageLost,messageSent){"function"==typeof self.onSentMessageCallback&&(messageSent?self.onSentMessageCallback(null,messageSent):self.onSentMessageCallback(messageLost))}):Utils.QBLog("[QBChat] StreamManagement:",'BOSH protocol doesn\'t support stream management. Set WebSocket as the "chatProtocol" parameter to use this functionality. https://quickblox.com/developers/Javascript#Configuration')),this._onMessage=function(stanza){var extraParamsParsed,recipientId,recipient,jid,from=chatUtils.getAttr(stanza,"from"),type=(chatUtils.getAttr(stanza,"to"),chatUtils.getAttr(stanza,"type")),messageId=chatUtils.getAttr(stanza,"id"),markable=chatUtils.getElement(stanza,"markable"),delivered=chatUtils.getElement(stanza,"received"),read=chatUtils.getElement(stanza,"displayed"),composing=chatUtils.getElement(stanza,"composing"),paused=chatUtils.getElement(stanza,"paused"),invite=chatUtils.getElement(stanza,"invite"),delay=chatUtils.getElement(stanza,"delay"),extraParams=chatUtils.getElement(stanza,"extraParams"),bodyContent=chatUtils.getElementText(stanza,"body"),forwarded=chatUtils.getElement(stanza,"forwarded");if(Utils.getEnv().browser)recipient=stanza.querySelector("forwarded")?stanza.querySelector("forwarded").querySelector("message").getAttribute("to"):null,jid=self.connection.jid;else{var forwardedMessage=forwarded?chatUtils.getElement(forwarded,"message"):null;recipient=forwardedMessage?chatUtils.getAttr(forwardedMessage,"to"):null,jid=self.Client.options.jid.user}recipientId=recipient?self.helpers.getIdFromNode(recipient):null;var dialogId="groupchat"===type?self.helpers.getDialogIdFromNode(from):null,userId="groupchat"===type?self.helpers.getIdFromResource(from):self.helpers.getIdFromNode(from),marker=delivered||read||null;if(invite)return!0;if(extraParams&&(extraParamsParsed=chatUtils.parseExtraParams(extraParams)).dialogId&&(dialogId=extraParamsParsed.dialogId),composing||paused)return"function"!=typeof self.onMessageTypingListener||"chat"!==type&&"groupchat"!==type&&delay||Utils.safeCallbackCall(self.onMessageTypingListener,!!composing,userId,dialogId),!0;if(marker)return delivered?"function"==typeof self.onDeliveredStatusListener&&"chat"===type&&Utils.safeCallbackCall(self.onDeliveredStatusListener,chatUtils.getAttr(delivered,"id"),dialogId,userId):"function"==typeof self.onReadStatusListener&&"chat"===type&&Utils.safeCallbackCall(self.onReadStatusListener,chatUtils.getAttr(read,"id"),dialogId,userId),!0;if(markable&&userId!=self.helpers.getIdFromNode(jid)){var autoSendReceiveStatusParams={messageId,userId,dialogId};self.sendDeliveredStatus(autoSendReceiveStatusParams)}var message={id:messageId,dialog_id:dialogId,recipient_id:recipientId,type,body:bodyContent,extension:extraParamsParsed?extraParamsParsed.extension:null,delay};return markable&&(message.markable=1),"function"!=typeof self.onMessageListener||"chat"!==type&&"groupchat"!==type||Utils.safeCallbackCall(self.onMessageListener,userId,message),!0},this._onPresence=function(stanza){var xXMLNS,status,statusCode,dialogId,userId,from=chatUtils.getAttr(stanza,"from"),id=(chatUtils.getAttr(stanza,"to"),chatUtils.getAttr(stanza,"id")),type=chatUtils.getAttr(stanza,"type"),currentUserId=self.helpers.getIdFromNode(self.helpers.userCurrentJid(Utils.getEnv().browser?self.connection:self.Client)),x=chatUtils.getElement(stanza,"x");if(x&&(xXMLNS=chatUtils.getAttr(x,"xmlns"),(status=chatUtils.getElement(x,"status"))&&(statusCode=chatUtils.getAttr(status,"code"))),xXMLNS&&"http://jabber.org/protocol/muc#user"==xXMLNS){if(dialogId=self.helpers.getDialogIdFromNode(from),userId=self.helpers.getUserIdFromRoomJid(from),status&&"301"==statusCode){if("function"==typeof self.onKickOccupant){var actorElement=chatUtils.getElement(chatUtils.getElement(x,"item"),"actor"),initiatorUserJid=chatUtils.getAttr(actorElement,"jid");Utils.safeCallbackCall(self.onKickOccupant,dialogId,self.helpers.getIdFromNode(initiatorUserJid))}return delete self.muc.joinedRooms[self.helpers.getRoomJidFromRoomFullJid(from)],!0}if(!status&&userId!=currentUserId)return type&&"unavailable"===type?("function"==typeof self.onLeaveOccupant&&Utils.safeCallbackCall(self.onLeaveOccupant,dialogId,parseInt(userId)),!0):("function"==typeof self.onJoinOccupant&&Utils.safeCallbackCall(self.onJoinOccupant,dialogId,parseInt(userId)),!0)}if(!Utils.getEnv().browser&&xXMLNS)if("http://jabber.org/protocol/muc#user"==xXMLNS){if(type&&"unavailable"===type)return status&&"110"==statusCode&&"function"==typeof self.nodeStanzasCallbacks["muc:leave"]&&Utils.safeCallbackCall(self.nodeStanzasCallbacks["muc:leave"],null),!0;if(id.endsWith(":join")&&status&&"110"==statusCode)return"function"==typeof self.nodeStanzasCallbacks[id]&&self.nodeStanzasCallbacks[id](stanza),!0}else if(type&&"error"===type&&"http://jabber.org/protocol/muc"==xXMLNS)return id.endsWith(":join")&&"function"==typeof self.nodeStanzasCallbacks[id]&&self.nodeStanzasCallbacks[id](stanza),!0;if(userId=self.helpers.getIdFromNode(from),type)switch(type){case"subscribe":self.roster.contacts[userId]&&"to"===self.roster.contacts[userId].subscription?(self.roster.contacts[userId]={subscription:"both",ask:null},self.roster._sendSubscriptionPresence({jid:from,type:"subscribed"})):"function"==typeof self.onSubscribeListener&&Utils.safeCallbackCall(self.onSubscribeListener,userId);break;case"subscribed":self.roster.contacts[userId]&&"from"===self.roster.contacts[userId].subscription?self.roster.contacts[userId]={subscription:"both",ask:null}:(self.roster.contacts[userId]={subscription:"to",ask:null},"function"==typeof self.onConfirmSubscribeListener&&Utils.safeCallbackCall(self.onConfirmSubscribeListener,userId));break;case"unsubscribed":self.roster.contacts[userId]={subscription:"none",ask:null},"function"==typeof self.onRejectSubscribeListener&&Utils.safeCallbackCall(self.onRejectSubscribeListener,userId);break;case"unsubscribe":self.roster.contacts[userId]={subscription:"to",ask:null};break;case"unavailable":"function"==typeof self.onContactListListener&&self.roster.contacts[userId]&&"none"!==self.roster.contacts[userId].subscription&&Utils.safeCallbackCall(self.onContactListListener,userId,type),userId===currentUserId&&(Utils.getEnv().browser?self.connection.send($pres()):self.Client.send(chatUtils.createStanza(XMPP.Stanza,null,"presence")))}else"function"==typeof self.onContactListListener&&self.roster.contacts[userId]&&"none"!==self.roster.contacts[userId].subscription&&Utils.safeCallbackCall(self.onContactListListener,userId);return!0},this._onIQ=function(stanza){var stanzaId=chatUtils.getAttr(stanza,"id"),isLastActivity=stanzaId.indexOf("lastActivity")>-1,isPong=stanzaId.indexOf("ping")>-1,ping=chatUtils.getElement(stanza,"ping"),type=chatUtils.getAttr(stanza,"type"),from=chatUtils.getAttr(stanza,"from"),userId=from?self.helpers.getIdFromNode(from):null;if("function"==typeof self.onLastUserActivityListener&&isLastActivity){var query=chatUtils.getElement(stanza,"query"),seconds=chatUtils.getElement(stanza,"error")?void 0:+chatUtils.getAttr(query,"seconds");Utils.safeCallbackCall(self.onLastUserActivityListener,userId,seconds)}if((ping||isPong)&&type)if("get"===type&&ping&&self.isConnected){var builder=Utils.getEnv().browser?$iq:XMPP.Stanza,pongParams={from:self.helpers.getUserCurrentJid(),id:stanzaId,to:from,type:"result"},pongStanza=chatUtils.createStanza(builder,pongParams,"iq");Utils.getEnv().browser?self.connection.send(pongStanza):self.Client.send(pongStanza)}else{var pingRequest=self._pings[stanzaId];pingRequest&&(pingRequest.callback&&pingRequest.callback(null),pingRequest.interval&&clearInterval(pingRequest.interval),self._pings[stanzaId]=void 0,delete self._pings[stanzaId])}return Utils.getEnv().browser||self.nodeStanzasCallbacks[stanzaId]&&(Utils.safeCallbackCall(self.nodeStanzasCallbacks[stanzaId],stanza),delete self.nodeStanzasCallbacks[stanzaId]),!0},this._onSystemMessageListener=function(stanza){var message,from=chatUtils.getAttr(stanza,"from"),messageId=(chatUtils.getAttr(stanza,"to"),chatUtils.getAttr(stanza,"id")),extraParams=chatUtils.getElement(stanza,"extraParams"),userId=self.helpers.getIdFromNode(from),delay=chatUtils.getElement(stanza,"delay"),moduleIdentifier=chatUtils.getElementText(extraParams,"moduleIdentifier"),bodyContent=chatUtils.getElementText(stanza,"body"),extraParamsParsed=chatUtils.parseExtraParams(extraParams);return"SystemNotifications"===moduleIdentifier&&"function"==typeof self.onSystemMessageListener?(message={id:messageId,userId,body:bodyContent,extension:extraParamsParsed.extension},Utils.safeCallbackCall(self.onSystemMessageListener,message)):self.webrtcSignalingProcessor&&!delay&&"WebRTCVideoChat"===moduleIdentifier&&self.webrtcSignalingProcessor._onMessage(from,extraParams,delay,userId,extraParamsParsed.extension),!0},this._onMessageErrorListener=function(stanza){var messageId=chatUtils.getAttr(stanza,"id"),error=chatUtils.getErrorFromXMLNode(stanza);return"function"==typeof self.onMessageErrorListener&&Utils.safeCallbackCall(self.onMessageErrorListener,messageId,error),!0}}function RosterProxy(options){this.service=options.service,this.helpers=options.helpers,this.connection=options.stropheClient,this.Client=options.xmppClient,this.nodeStanzasCallbacks=options.nodeStanzasCallbacks,this.contacts={}}function MucProxy(options){this.service=options.service,this.helpers=options.helpers,this.connection=options.stropheClient,this.Client=options.xmppClient,this.nodeStanzasCallbacks=options.nodeStanzasCallbacks,this.joinedRooms={}}function PrivacyListProxy(options){this.service=options.service,this.helpers=options.helpers,this.connection=options.stropheClient,this.Client=options.xmppClient,this.nodeStanzasCallbacks=options.nodeStanzasCallbacks}function Helpers(){this._userCurrentJid=""}ChatProxy.prototype={_OnLogListener:function(message){var self=this;"function"==typeof self.onLogListener&&Utils.safeCallbackCall(self.onLogListener,message)},connect:function(params,callback){Utils.QBLog("[QBChat]","Connect with parameters "+JSON.stringify(params));var err,self=this,userJid=chatUtils.buildUserJid(params),isInitialConnect="function"==typeof callback;return self._isConnecting?(err=Utils.getError(422,"Status.REJECT - The connection is still in the Status.CONNECTING state","QBChat"),void(isInitialConnect&&callback(err,null))):self.isConnected?(Utils.QBLog("[QBChat]","Status.CONNECTED - You are already connected"),void(isInitialConnect&&callback(null,self.roster.contacts))):(self._isConnecting=!0,self._isLogout=!1,Utils.getEnv().browser&&(Utils.QBLog("[QBChat]","!!---Browser env - connected--!!"),self.connection.connect(userJid,params.password,function(status,condition,elem){switch(Utils.QBLog("[QBChat]","self.connection.connect called with status "+status),Utils.QBLog("[QBChat]","self.connection.connect called with condition "+condition),Utils.QBLog("[QBChat]","self.connection.connect called with elem "+elem),status){case Strophe.Status.ERROR:Utils.QBLog("[QBChat]","Status.ERROR at "+chatUtils.getLocalTime()),Utils.QBLog("[QBChat]","ERROR CONDITION: "+condition),"function"==typeof self.onLogListener&&Utils.safeCallbackCall(self.onLogListener,"[QBChat][SDK v"+config.version+"] Status.ERROR at "+chatUtils.getLocalTime()+" ERROR CONDITION: "+condition),self.isConnected=!1,self._isConnecting=!1,err=Utils.getError(422,"Status.ERROR - An error has occurred","QBChat"),isInitialConnect&&callback(err,null);break;case Strophe.Status.CONNFAIL:Utils.QBLog("[QBChat]","Status.CONNFAIL at "+chatUtils.getLocalTime()),Utils.QBLog("[QBChat]","CONNFAIL CONDITION: "+condition),"function"==typeof self.onLogListener&&Utils.safeCallbackCall(self.onLogListener,"[QBChat][SDK v"+config.version+"] Status.CONNFAIL at "+chatUtils.getLocalTime()+" CONNFAIL CONDITION: "+condition),self.isConnected=!1,self._isConnecting=!1,err=Utils.getError(422,"Status.CONNFAIL - The connection attempt failed","QBChat"),isInitialConnect&&callback(err,null);break;case Strophe.Status.AUTHENTICATING:Utils.QBLog("[QBChat]","Status.AUTHENTICATING at "+chatUtils.getLocalTime()),Utils.QBLog("[QBChat]","AUTHENTICATING CONDITION: "+condition),"function"==typeof self.onLogListener&&Utils.safeCallbackCall(self.onLogListener,"[QBChat][SDK v"+config.version+"] Status.AUTHENTICATING at "+chatUtils.getLocalTime()+" AUTHENTICATING CONDITION: "+condition);break;case Strophe.Status.AUTHFAIL:Utils.QBLog("[QBChat]","Status.AUTHFAIL at "+chatUtils.getLocalTime()),Utils.QBLog("[QBChat]","AUTHFAIL CONDITION: "+condition),"function"==typeof self.onLogListener&&Utils.safeCallbackCall(self.onLogListener,"[QBChat][SDK v"+config.version+"] Status.AUTHFAIL at "+chatUtils.getLocalTime()+" AUTHFAIL CONDITION: "+condition),self.isConnected=!1,self._isConnecting=!1,err=Utils.getError(401,"Status.AUTHFAIL - The authentication attempt failed","QBChat"),isInitialConnect&&callback(err,null),self.isConnected||"function"!=typeof self.onReconnectFailedListener||Utils.safeCallbackCall(self.onReconnectFailedListener,err);break;case Strophe.Status.CONNECTING:Utils.QBLog("[QBChat]","Status.CONNECTING","(Chat Protocol - "+(1===config.chatProtocol.active?"BOSH":"WebSocket)")),Utils.QBLog("[QBChat]","Status.CONNECTING at "+chatUtils.getLocalTime()),Utils.QBLog("[QBChat]","CONNECTING CONDITION: "+condition),"function"==typeof self.onLogListener&&Utils.safeCallbackCall(self.onLogListener,"[QBChat][SDK v"+config.version+"] Status.CONNECTING at (Chat Protocol - "+config.chatProtocol.active===1?"BOSH":"WebSocket)"+chatUtils.getLocalTime()+" CONNECTING CONDITION: "+condition);break;case Strophe.Status.CONNECTED:Utils.QBLog("[QBChat]","Status.CONNECTED at "+chatUtils.getLocalTime()),Utils.QBLog("[QBChat]","CONNECTED CONDITION: "+condition),"function"==typeof self.onLogListener&&Utils.safeCallbackCall(self.onLogListener,"[QBChat][SDK v"+config.version+"] Status.CONNECTED at "+chatUtils.getLocalTime()+" CONNECTED CONDITION: "+condition),self.connection.XDeleteHandlers(),self.connection.XAddTrackedHandler(self._onMessage,null,"message","chat"),self.connection.XAddTrackedHandler(self._onMessage,null,"message","groupchat"),self.connection.XAddTrackedHandler(self._onPresence,null,"presence"),self.connection.XAddTrackedHandler(self._onIQ,null,"iq"),self.connection.XAddTrackedHandler(self._onSystemMessageListener,null,"message","headline"),self.connection.XAddTrackedHandler(self._onMessageErrorListener,null,"message","error");var noTimerId=void 0===self._checkConnectionPingTimer;(noTimerId=0!==config.pingLocalhostTimeInterval&&noTimerId)&&(Utils.QBLog("[QBChat]","Init ping to chat at ",Utils.getCurrentTime()),self._checkConnectionPingTimer=setInterval(function(){try{self.pingchat(function(error){error?(Utils.QBLog("[QBChat]","Chat Ping: ","failed, at ",Utils.getCurrentTime(),"_chatPingFailedCounter: ",self._chatPingFailedCounter," error: ",error),self._chatPingFailedCounter+=1,self._chatPingFailedCounter>=config.chatPingMissLimit&&(self.isConnected&&"function"==typeof self.onDisconnectedListener&&Utils.safeCallbackCall(self.onDisconnectedListener),self.isConnected=!1,self._isConnecting=!1,self._chatPingFailedCounter=0,self._establishConnection(params,"CONNECTED have SDK ping failed"))):(Utils.QBLog("[QBChat]","Chat Ping: ","ok, at ",Utils.getCurrentTime(),"_chatPingFailedCounter: ",self._chatPingFailedCounter),self._chatPingFailedCounter=0)})}catch(err){Utils.QBLog("[QBChat]","Chat Ping: ","Exception, at ",Utils.getCurrentTime(),", detail info: ",err)}},1e3*config.pingLocalhostTimeInterval)),"function"==typeof self.onSessionExpiredListener&&void 0===self._checkExpiredSessionTimer&&(Utils.QBLog("[QBChat]","Init timer for check session expired at ",(new Date).toTimeString().split(" ")[0]),self._checkExpiredSessionTimer=setInterval(function(){var timeNow=new Date;void 0!==config.qbTokenExpirationDate&&Math.round((timeNow.getTime()-config.qbTokenExpirationDate.getTime())/6e4)>=0&&(self._sessionHasExpired=!0,Utils.safeCallbackCall(self.onSessionExpiredListener,null))},5e3)),self._postConnectActions(function(roster){callback(null,roster)},isInitialConnect);break;case Strophe.Status.DISCONNECTING:Utils.QBLog("[QBChat]","Status.DISCONNECTING at "+chatUtils.getLocalTime()),Utils.QBLog("[QBChat]","DISCONNECTING CONDITION: "+condition),"function"==typeof self.onLogListener&&Utils.safeCallbackCall(self.onLogListener,"[QBChat][SDK v"+config.version+"] Status.DISCONNECTING at "+chatUtils.getLocalTime()+" DISCONNECTING CONDITION: "+condition);break;case Strophe.Status.DISCONNECTED:Utils.QBLog("[QBChat]","Status.DISCONNECTED at "+chatUtils.getLocalTime()),Utils.QBLog("[QBChat]","DISCONNECTED CONDITION: "+condition),"function"==typeof self.onLogListener&&Utils.safeCallbackCall(self.onLogListener,"[QBChat][SDK v"+config.version+"] Status.DISCONNECTED at "+chatUtils.getLocalTime()+" DISCONNECTED CONDITION: "+condition),self.isConnected&&"function"==typeof self.onDisconnectedListener&&Utils.safeCallbackCall(self.onDisconnectedListener),self.isConnected=!1,self._isConnecting=!1,self.connection.reset(),self._establishConnection(params,"DISCONNECTED");break;case Strophe.Status.ATTACHED:Utils.QBLog("[QBChat]","Status.ATTACHED at "+chatUtils.getLocalTime()),Utils.QBLog("[QBChat]","ATTACHED CONDITION: "+condition),"function"==typeof self.onLogListener&&Utils.safeCallbackCall(self.onLogListener,"[QBChat][SDK v"+config.version+"] Status.ATTACHED at "+chatUtils.getLocalTime()+" ATTACHED CONDITION: "+condition);break;case Strophe.Status.REDIRECT:Utils.QBLog("[QBChat]","Status.REDIRECT at "+chatUtils.getLocalTime()),Utils.QBLog("[QBChat]","REDIRECT CONDITION: "+condition),"function"==typeof self.onLogListener&&Utils.safeCallbackCall(self.onLogListener,"[QBChat][SDK v"+config.version+"] Status.REDIRECT at "+chatUtils.getLocalTime()+" REDIRECT CONDITION: "+condition);break;case Strophe.Status.CONNTIMEOUT:Utils.QBLog("[QBChat]","Status.CONNTIMEOUT at "+chatUtils.getLocalTime()),Utils.QBLog("[QBChat]","CONNTIMEOUT CONDITION: "+condition),"function"==typeof self.onLogListener&&Utils.safeCallbackCall(self.onLogListener,"[QBChat][SDK v"+config.version+"] Status.CONNTIMEOUT at "+chatUtils.getLocalTime()+" CONNTIMEOUT CONDITION: "+condition);break;case Strophe.Status.BINDREQUIRED:Utils.QBLog("[QBChat]","Status.BINDREQUIRED at "+chatUtils.getLocalTime()),Utils.QBLog("[QBChat]","BINDREQUIRED CONDITION: "+condition),"function"==typeof self.onLogListener&&Utils.safeCallbackCall(self.onLogListener,"[QBChat][SDK v"+config.version+"] Status.BINDREQUIRED at "+chatUtils.getLocalTime()+" BINDREQUIRED CONDITION: "+condition);break;case Strophe.Status.ATTACHFAIL:Utils.QBLog("[QBChat]","Status.ATTACHFAIL at "+chatUtils.getLocalTime()),Utils.QBLog("[QBChat]","ATTACHFAIL CONDITION: "+condition),"function"==typeof self.onLogListener&&Utils.safeCallbackCall(self.onLogListener,"[QBChat][SDK v"+config.version+"] Status.ATTACHFAIL at "+chatUtils.getLocalTime()+" ATTACHFAIL CONDITION: "+condition);break;default:Utils.QBLog("[QBChat]","Status is unknown at "+chatUtils.getLocalTime()),Utils.QBLog("[QBChat]","unknown CONDITION: "+condition),"function"==typeof self.onLogListener&&Utils.safeCallbackCall(self.onLogListener,"[QBChat][SDK v"+config.version+"] Status is unknown at "+chatUtils.getLocalTime()+" unknown CONDITION: "+condition)}})),void(Utils.getEnv().browser||(Utils.QBLog("[QBChat]","!!--call branch code connect for node--!!"),self.Client.removeAllListeners(),self.Client.on("connect",function(){Utils.QBLog("[QBChat]","Status.CONNECTING","(Chat Protocol - "+(1===config.chatProtocol.active?"BOSH":"WebSocket)"))}),self.Client.on("auth",function(){Utils.QBLog("[QBChat]","Status.AUTHENTICATING")}),self.Client.on("online",function(){self._postConnectActions(function(roster){callback(null,roster)},isInitialConnect)}),self.Client.on("stanza",function(stanza){Utils.QBLog("[QBChat] RECV:",stanza.toString()),stanza.is("presence")?self._onPresence(stanza):stanza.is("iq")?self._onIQ(stanza):stanza.is("message")&&("headline"===stanza.attrs.type?self._onSystemMessageListener(stanza):"error"===stanza.attrs.type?self._onMessageErrorListener(stanza):self._onMessage(stanza))}),self.Client.on("disconnect",function(){Utils.QBLog("[QBChat]","Status.DISCONNECTED - "+chatUtils.getLocalTime()),"function"==typeof self.onDisconnectedListener&&Utils.safeCallbackCall(self.onDisconnectedListener),self.isConnected=!1,self._isConnecting=!1,self._establishConnection(params,"NODE:DISCONNECTED")}),self.Client.on("error",function(){Utils.QBLog("[QBChat]","Status.ERROR - "+chatUtils.getLocalTime()),err=Utils.getError(422,"Status.ERROR - An error has occurred","QBChat"),isInitialConnect&&callback(err,null),self.isConnected=!1,self._isConnecting=!1}),self.Client.on("end",function(){self.Client.removeAllListeners()}),self.Client.options.jid=userJid,self.Client.options.password=params.password,self.Client.connect())))},_postConnectActions:function(callback,isInitialConnect){Utils.QBLog("[QBChat]","Status.CONNECTED at "+chatUtils.getLocalTime());var self=this,isBrowser=Utils.getEnv().browser,xmppClient=isBrowser?self.connection:self.Client,presence=isBrowser?$pres():chatUtils.createStanza(XMPP.Stanza,null,"presence");if(config.streamManagement.enable&&2===config.chatProtocol.active&&(self.streamManagement.enable(self.connection,null),self.streamManagement.sentMessageCallback=self._sentMessageCallback),self.helpers.setUserCurrentJid(self.helpers.userCurrentJid(xmppClient)),self.isConnected=!0,self._isConnecting=!1,self._sessionHasExpired=!1,self._enableCarbons(),isInitialConnect)self.roster.get(function(contacts){xmppClient.send(presence),self.roster.contacts=contacts,callback(self.roster.contacts)});else{var rooms=Object.keys(self.muc.joinedRooms);xmppClient.send(presence),Utils.QBLog("[QBChat]","Re-joining "+rooms.length+" rooms...");for(var i=0,len=rooms.length;i<len;i++)self.muc.join(rooms[i]);"function"==typeof self.onReconnectListener&&Utils.safeCallbackCall(self.onReconnectListener)}},_establishConnection:function(params,description){var self=this;if(Utils.QBLog("[QBChat]","_establishConnection called in "+description),"function"==typeof self.onLogListener&&Utils.safeCallbackCall(self.onLogListener,"[QBChat]_establishConnection called in "+description),self._isLogout||self._checkConnectionTimer)return Utils.QBLog("[QBChat]","_establishConnection return"),void("function"==typeof self.onLogListener&&Utils.safeCallbackCall(self.onLogListener,(self._isLogout,self._isLogout)));var _connect=function(){Utils.QBLog("[QBChat]","call _connect() in _establishConnection in "+description),"function"==typeof self.onLogListener&&Utils.safeCallbackCall(self.onLogListener,"[QBChat] call _connect() in _establishConnection in "+description),self.isConnected||self._isConnecting||self._sessionHasExpired?(Utils.QBLog("[QBChat]","stop timer in _establishConnection "),clearInterval(self._checkConnectionTimer),self._checkConnectionTimer=void 0,"function"==typeof self.onLogListener&&Utils.safeCallbackCall(self.onLogListener,"[QBChat]stop timer in _establishConnection in "+description)):(Utils.QBLog("[QBChat]"," start EXECUTE connect() in _establishConnection "),"function"==typeof self.onLogListener&&Utils.safeCallbackCall(self.onLogListener,"[QBChat] start EXECUTE connect() in _establishConnection in "+description+" self.isConnected: "+self.isConnected+" self._isConnecting: "+self._isConnecting+" self._sessionHasExpired: "+self._sessionHasExpired),self.connect(params),"function"==typeof self.onLogListener&&Utils.safeCallbackCall(self.onLogListener,"[QBChat]call _connect() in _establishConnection in "+description+" is executed"))};_connect(),self._checkConnectionTimer=setInterval(function(){Utils.QBLog("[QBChat]","self._checkConnectionTimer called with config.chatReconnectionTimeInterval = "+config.chatReconnectionTimeInterval),"function"==typeof self.onLogListener&&Utils.safeCallbackCall(self.onLogListener,"[QBChat]self._checkConnectionTimer called with config.chatReconnectionTimeInterval = "+config.chatReconnectionTimeInterval),_connect()},1e3*config.chatReconnectionTimeInterval)},reconnect:function(){Utils.QBLog("[QBChat]","Call reconnect "),"function"==typeof this.onLogListener&&Utils.safeCallbackCall(this.onLogListener,"[QBChat][SDK v"+config.version+"] Call reconnect "+chatUtils.getLocalTime()),clearInterval(this._checkConnectionTimer),this._checkConnectionTimer=void 0,this.muc.joinedRooms={},this.helpers.setUserCurrentJid(""),Utils.getEnv().browser?(this.connection.flush(),this.connection.disconnect("call Qb.chat.reconnect")):this.Client.end()},send:function(jid_or_user_id,message){Utils.QBLog("[QBChat]","Call send "+JSON.stringify(message));var self=this,builder=Utils.getEnv().browser?$msg:XMPP.Stanza,paramsCreateMsg={from:self.helpers.getUserCurrentJid(),to:this.helpers.jidOrUserId(jid_or_user_id),type:message.type?message.type:"chat",id:message.id?message.id:Utils.getBsonObjectId()},stanza=chatUtils.createStanza(builder,paramsCreateMsg);return message.body&&stanza.c("body",{xmlns:chatUtils.MARKERS.CLIENT}).t(message.body).up(),message.markable&&stanza.c("markable",{xmlns:chatUtils.MARKERS.CHAT}).up(),message.extension&&(stanza.c("extraParams",{xmlns:chatUtils.MARKERS.CLIENT}),stanza=chatUtils.filledExtraParams(stanza,message.extension)),Utils.getEnv().browser?config.streamManagement.enable?(message.id=paramsCreateMsg.id,message.jid_or_user_id=jid_or_user_id,self.connection.send(stanza,message)):self.connection.send(stanza):config.streamManagement.enable?(message.id=paramsCreateMsg.id,message.jid_or_user_id=jid_or_user_id,self.Client.send(stanza,message)):self.Client.send(stanza),paramsCreateMsg.id},sendSystemMessage:function(jid_or_user_id,message){Utils.QBLog("[QBChat]","Call sendSystemMessage "+JSON.stringify(message));var self=this,builder=Utils.getEnv().browser?$msg:XMPP.Stanza,paramsCreateMsg={type:"headline",id:message.id?message.id:Utils.getBsonObjectId(),to:this.helpers.jidOrUserId(jid_or_user_id)},stanza=chatUtils.createStanza(builder,paramsCreateMsg);return message.body&&stanza.c("body",{xmlns:chatUtils.MARKERS.CLIENT}).t(message.body).up(),Utils.getEnv().browser?(message.extension&&(stanza.c("extraParams",{xmlns:chatUtils.MARKERS.CLIENT}).c("moduleIdentifier").t("SystemNotifications").up(),stanza=chatUtils.filledExtraParams(stanza,message.extension)),self.connection.send(stanza)):(message.extension&&(stanza.c("extraParams",{xmlns:chatUtils.MARKERS.CLIENT}).c("moduleIdentifier").t("SystemNotifications"),stanza=chatUtils.filledExtraParams(stanza,message.extension)),self.Client.send(stanza)),paramsCreateMsg.id},sendIsTypingStatus:function(jid_or_user_id){Utils.QBLog("[QBChat]","Call sendIsTypingStatus ");var self=this,stanzaParams={from:self.helpers.getUserCurrentJid(),to:this.helpers.jidOrUserId(jid_or_user_id),type:this.helpers.typeChat(jid_or_user_id)},builder=Utils.getEnv().browser?$msg:XMPP.Stanza,stanza=chatUtils.createStanza(builder,stanzaParams);stanza.c("composing",{xmlns:chatUtils.MARKERS.STATES}),Utils.getEnv().browser?self.connection.send(stanza):self.Client.send(stanza)},sendIsStopTypingStatus:function(jid_or_user_id){Utils.QBLog("[QBChat]","Call sendIsStopTypingStatus ");var self=this,stanzaParams={from:self.helpers.getUserCurrentJid(),to:this.helpers.jidOrUserId(jid_or_user_id),type:this.helpers.typeChat(jid_or_user_id)},builder=Utils.getEnv().browser?$msg:XMPP.Stanza,stanza=chatUtils.createStanza(builder,stanzaParams);stanza.c("paused",{xmlns:chatUtils.MARKERS.STATES}),Utils.getEnv().browser?self.connection.send(stanza):self.Client.send(stanza)},sendDeliveredStatus:function(params){Utils.QBLog("[QBChat]","Call sendDeliveredStatus ");var self=this,stanzaParams={type:"chat",from:self.helpers.getUserCurrentJid(),id:Utils.getBsonObjectId(),to:this.helpers.jidOrUserId(params.userId)},builder=Utils.getEnv().browser?$msg:XMPP.Stanza,stanza=chatUtils.createStanza(builder,stanzaParams);stanza.c("received",{xmlns:chatUtils.MARKERS.MARKERS,id:params.messageId}).up(),stanza.c("extraParams",{xmlns:chatUtils.MARKERS.CLIENT}).c("dialog_id").t(params.dialogId),Utils.getEnv().browser?self.connection.send(stanza):self.Client.send(stanza)},sendReadStatus:function(params){Utils.QBLog("[QBChat]","Call sendReadStatus "+JSON.stringify(params));var self=this,stanzaParams={type:"chat",from:self.helpers.getUserCurrentJid(),to:this.helpers.jidOrUserId(params.userId),id:Utils.getBsonObjectId()},builder=Utils.getEnv().browser?$msg:XMPP.Stanza,stanza=chatUtils.createStanza(builder,stanzaParams);stanza.c("displayed",{xmlns:chatUtils.MARKERS.MARKERS,id:params.messageId}).up(),stanza.c("extraParams",{xmlns:chatUtils.MARKERS.CLIENT}).c("dialog_id").t(params.dialogId),Utils.getEnv().browser?self.connection.send(stanza):self.Client.send(stanza)},getLastUserActivity:function(jid_or_user_id){var iqParams,builder,iq;Utils.QBLog("[QBChat]","Call getLastUserActivity "),iqParams={from:this.helpers.getUserCurrentJid(),id:this.helpers.getUniqueId("lastActivity"),to:this.helpers.jidOrUserId(jid_or_user_id),type:"get"},builder=Utils.getEnv().browser?$iq:XMPP.Stanza,(iq=chatUtils.createStanza(builder,iqParams,"iq")).c("query",{xmlns:chatUtils.MARKERS.LAST}),Utils.getEnv().browser?this.connection.sendIQ(iq):this.Client.send(iq)},pingchat:function(callback){Utils.QBLog("[QBChat]","ping chat");var to,_callback,stanza,self=this,id=this.helpers.getUniqueId("ping"),builder=Utils.getEnv().browser?$iq:XMPP.Stanza;to=config.endpoints.chat?config.endpoints.chat:"chat.quickblox.com",_callback=callback;var iqParams={from:this.helpers.getUserCurrentJid(),id,to,type:"get"};(stanza=chatUtils.createStanza(builder,iqParams,"iq")).c("ping",{xmlns:"urn:xmpp:ping"});var noAnswer=function(){_callback("Chat ping No answer"),self._pings[id]=void 0,delete self._pings[id]};return Utils.getEnv().browser?this.connection.send(stanza):this.Client.send(stanza),this._pings[id]={callback:_callback,interval:setTimeout(noAnswer,1e3*config.pingTimeout)},id},ping:function(jid_or_user_id,callback){Utils.QBLog("[QBChat]","Call ping ");var to,_callback,stanza,self=this,id=this.helpers.getUniqueId("ping"),builder=Utils.getEnv().browser?$iq:XMPP.Stanza;if("string"!=typeof jid_or_user_id&&"number"!=typeof jid_or_user_id||"function"!=typeof callback){if("function"!=typeof jid_or_user_id||callback)throw new Error("Invalid arguments provided. Either userId/jid (number/string) and callback or only callback should be provided.");to=config.endpoints.chat,_callback=jid_or_user_id}else to=this.helpers.jidOrUserId(jid_or_user_id),_callback=callback;var iqParams={from:this.helpers.getUserCurrentJid(),id,to,type:"get"};(stanza=chatUtils.createStanza(builder,iqParams,"iq")).c("ping",{xmlns:"urn:xmpp:ping"});var noAnswer=function(){_callback("No answer"),self._pings[id]=void 0,delete self._pings[id]};return Utils.getEnv().browser?this.connection.send(stanza):this.Client.send(stanza),this._pings[id]={callback:_callback,interval:setTimeout(noAnswer,1e3*config.pingTimeout)},id},disconnect:function(){Utils.QBLog("[QBChat]","Call disconnect "),"function"==typeof this.onLogListener&&Utils.safeCallbackCall(this.onLogListener,"[QBChat][SDK v"+config.version+"] Call disconnect "+chatUtils.getLocalTime()),clearInterval(this._checkConnectionTimer),clearInterval(this._checkExpiredSessionTimer),this._checkConnectionTimer=void 0,this._checkExpiredSessionTimer=void 0,this.muc.joinedRooms={},this._isLogout=!0,this.helpers.setUserCurrentJid(""),Utils.getEnv().browser?(this.connection.flush(),this.connection.disconnect("call QB.chat.disconnect"),void 0!==this._checkConnectionPingTimer&&(Utils.QBLog("[QBChat]","Stop ping"),clearInterval(this._checkConnectionPingTimer),this._checkConnectionPingTimer=void 0)):this.Client.end()},addListener:function(params,callback){if(Utils.QBLog("[Deprecated!]","Avoid using it, this feature will be removed in future version."),!Utils.getEnv().browser)throw new Error(unsupportedError);return this.connection.XAddTrackedHandler(handler,null,params.name||null,params.type||null,params.id||null,params.from||null);function handler(){return callback(),!1!==params.live}},deleteListener:function(ref){if(Utils.QBLog("[Deprecated!]","Avoid using it, this feature will be removed in future version."),!Utils.getEnv().browser)throw new Error(unsupportedError);this.connection.deleteHandler(ref)},_enableCarbons:function(cb){var self=this,carbonParams={type:"set",from:self.helpers.getUserCurrentJid(),id:chatUtils.getUniqueId("enableCarbons")},builder=Utils.getEnv().browser?$iq:XMPP.Stanza,iq=chatUtils.createStanza(builder,carbonParams,"iq");iq.c("enable",{xmlns:chatUtils.MARKERS.CARBONS}),Utils.getEnv().browser?self.connection.sendIQ(iq):self.Client.send(iq)}},RosterProxy.prototype={get:function(callback){var self=this,contacts={},iqParams={type:"get",from:self.helpers.getUserCurrentJid(),id:chatUtils.getUniqueId("getRoster")},builder=Utils.getEnv().browser?$iq:XMPP.Stanza,iq=chatUtils.createStanza(builder,iqParams,"iq");function _getItems(stanza){return Utils.getEnv().browser?stanza.getElementsByTagName("item"):stanza.getChild("query").children}function _callbackWrap(stanza){for(var items=_getItems(stanza),i=0,len=items.length;i<len;i++){var userId=self.helpers.getIdFromNode(chatUtils.getAttr(items[i],"jid")),ask=chatUtils.getAttr(items[i],"ask"),subscription=chatUtils.getAttr(items[i],"subscription");contacts[userId]={subscription,ask:ask||null}}callback(contacts)}iq.c("query",{xmlns:chatUtils.MARKERS.ROSTER}),Utils.getEnv().browser?self.connection.sendIQ(iq,_callbackWrap):(self.nodeStanzasCallbacks[iqParams.id]=_callbackWrap,self.Client.send(iq))},add:function(jidOrUserId,callback){var self=this,userJid=this.helpers.jidOrUserId(jidOrUserId),userId=this.helpers.getIdFromNode(userJid).toString();self.contacts[userId]={subscription:"none",ask:"subscribe"},self._sendSubscriptionPresence({jid:userJid,type:"subscribe"}),"function"==typeof callback&&callback()},confirm:function(jidOrUserId,callback){var self=this,userJid=this.helpers.jidOrUserId(jidOrUserId),userId=this.helpers.getIdFromNode(userJid).toString();self.contacts[userId]={subscription:"from",ask:"subscribe"},self._sendSubscriptionPresence({jid:userJid,type:"subscribed"}),self._sendSubscriptionPresence({jid:userJid,type:"subscribe"}),"function"==typeof callback&&callback()},reject:function(jidOrUserId,callback){var self=this,userJid=this.helpers.jidOrUserId(jidOrUserId),userId=this.helpers.getIdFromNode(userJid).toString();self.contacts[userId]={subscription:"none",ask:null},self._sendSubscriptionPresence({jid:userJid,type:"unsubscribed"}),"function"==typeof callback&&callback()},remove:function(jidOrUserId,callback){var self=this,userJid=this.helpers.jidOrUserId(jidOrUserId),userId=this.helpers.getIdFromNode(userJid),iqParams={type:"set",from:self.connection?self.connection.jid:self.Client.jid.user,id:chatUtils.getUniqueId("getRoster")},builder=Utils.getEnv().browser?$iq:XMPP.Stanza,iq=chatUtils.createStanza(builder,iqParams,"iq");function _callbackWrap(){delete self.contacts[userId],"function"==typeof callback&&callback()}iq.c("query",{xmlns:chatUtils.MARKERS.ROSTER}).c("item",{jid:userJid,subscription:"remove"}),Utils.getEnv().browser?self.connection.sendIQ(iq,_callbackWrap):(self.nodeStanzasCallbacks[iqParams.id]=_callbackWrap,self.Client.send(iq))},_sendSubscriptionPresence:function(params){var builder=Utils.getEnv().browser?$pres:XMPP.Stanza,presParams={to:params.jid,type:params.type},pres=chatUtils.createStanza(builder,presParams,"presence");Utils.getEnv().browser?this.connection.send(pres):this.Client.send(pres)}},MucProxy.prototype={join:function(dialogIdOrJid,callback){var self=this,id=chatUtils.getUniqueId("join"),dialogJid=this.helpers.getDialogJid(dialogIdOrJid),presParams={id,from:self.helpers.getUserCurrentJid(),to:self.helpers.getRoomJid(dialogJid)},builder=Utils.getEnv().browser?$pres:XMPP.Stanza,pres=chatUtils.createStanza(builder,presParams,"presence");function handleJoinAnswer(stanza){var id=chatUtils.getAttr(stanza,"id"),from=chatUtils.getAttr(stanza,"from"),dialogId=self.helpers.getDialogIdFromNode(from),x=chatUtils.getElement(stanza,"x"),xXMLNS=chatUtils.getAttr(x,"xmlns"),status=chatUtils.getElement(x,"status"),statusCode=chatUtils.getAttr(status,"code");if(1==callback.length)return Utils.safeCallbackCall(callback,stanza),!0;if(status&&"110"==statusCode)Utils.safeCallbackCall(callback,null,{dialogId});else{var type=chatUtils.getAttr(stanza,"type");if(type&&"error"===type&&"http://jabber.org/protocol/muc"==xXMLNS&&id.endsWith(":join")){var errorEl=chatUtils.getElement(stanza,"error"),code=chatUtils.getAttr(errorEl,"code"),errorMessage=chatUtils.getElementText(errorEl,"text");Utils.safeCallbackCall(callback,{code:code||500,message:errorMessage||"Unknown issue"},{dialogId})}}}pres.c("x",{xmlns:chatUtils.MARKERS.MUC}).c("history",{maxstanzas:0}),this.joinedRooms[dialogJid]=!0,Utils.getEnv().browser?("function"==typeof callback&&self.connection.XAddTrackedHandler(handleJoinAnswer,null,"presence",null,id),self.connection.send(pres)):("function"==typeof callback&&(self.nodeStanzasCallbacks[id]=handleJoinAnswer),self.Client.send(pres))},leave:function(jid,callback){var self=this,presParams={type:"unavailable",from:self.helpers.getUserCurrentJid(),to:self.helpers.getRoomJid(jid)},builder=Utils.getEnv().browser?$pres:XMPP.Stanza,pres=chatUtils.createStanza(builder,presParams,"presence");function handleLeaveAnswer(stanza){var id=chatUtils.getAttr(stanza,"id"),from=chatUtils.getAttr(stanza,"from"),dialogId=self.helpers.getDialogIdFromNode(from),x=chatUtils.getElement(stanza,"x"),xXMLNS=chatUtils.getAttr(x,"xmlns"),status=chatUtils.getElement(x,"status"),statusCode=chatUtils.getAttr(status,"code");if(status&&"110"==statusCode)Utils.safeCallbackCall(callback,null,{dialogId});else{var type=chatUtils.getAttr(stanza,"type");if(type&&"error"===type&&"http://jabber.org/protocol/muc"==xXMLNS&&id.endsWith(":join")){var errorEl=chatUtils.getElement(stanza,"error"),code=chatUtils.getAttr(errorEl,"code"),errorMessage=chatUtils.getElementText(errorEl,"text");Utils.safeCallbackCall(callback,{code:code||500,message:errorMessage||"Unknown issue"},null)}}}if(delete this.joinedRooms[jid],Utils.getEnv().browser){var roomJid=self.helpers.getRoomJid(jid);"function"==typeof callback&&self.connection.XAddTrackedHandler(handleLeaveAnswer,null,"presence",presParams.type,null,roomJid),self.connection.send(pres)}else"function"==typeof callback&&(self.nodeStanzasCallbacks["muc:leave"]=handleLeaveAnswer),self.Client.send(pres)},listOnlineUsers:function(dialogJID,callback){var self=this,onlineUsers=[],iqParams={type:"get",to:dialogJID,from:self.helpers.getUserCurrentJid(),id:chatUtils.getUniqueId("muc_disco_items")},builder=Utils.getEnv().browser?$iq:XMPP.Stanza,iq=chatUtils.createStanza(builder,iqParams,"iq");function _getUsers(stanza){var stanzaId=stanza.attrs.id;if(self.nodeStanzasCallbacks[stanzaId]){for(var userId,users=[],items=stanza.getChild("query").getChildElements("item"),i=0,len=items.length;i<len;i++)userId=self.helpers.getUserIdFromRoomJid(items[i].attrs.jid),users.push(parseInt(userId));callback(users)}}iq.c("query",{xmlns:"http://jabber.org/protocol/disco#items"}),Utils.getEnv().browser?self.connection.sendIQ(iq,function(stanza){for(var userId,items=stanza.getElementsByTagName("item"),i=0,len=items.length;i<len;i++)userId=self.helpers.getUserIdFromRoomJid(items[i].getAttribute("jid")),onlineUsers.push(parseInt(userId));callback(onlineUsers)}):(self.Client.send(iq),self.nodeStanzasCallbacks[iqParams.id]=_getUsers)}},PrivacyListProxy.prototype={create:function(list,callback){for(var userId,userJid,userMuc,userAction,mutualBlock,self=this,listPrivacy={},listUserId=[],i=list.items.length-1;i>=0;i--){var user=list.items[i];listPrivacy[user.user_id]={action:user.action,mutualBlock:!0===user.mutualBlock}}listUserId=Object.keys(listPrivacy);var iqParams={type:"set",from:self.helpers.getUserCurrentJid(),id:chatUtils.getUniqueId("edit")},builder=Utils.getEnv().browser?$iq:XMPP.Stanza,iq=chatUtils.createStanza(builder,iqParams,"iq");function createPrivacyItem(iq,params){return Utils.getEnv().browser?iq.c("item",{type:"jid",value:params.jidOrMuc,action:params.userAction,order:params.order}).c("message",{}).up().c("presence-in",{}).up().c("presence-out",{}).up().c("iq",{}).up().up():iq.getChild("query").getChild("list").c("item",{type:"jid",value:params.jidOrMuc,action:params.userAction,order:params.order}).c("message",{}).up().c("presence-in",{}).up().c("presence-out",{}).up().c("iq",{}).up().up(),iq}function createPrivacyItemMutal(iq,params){return Utils.getEnv().browser?iq.c("item",{type:"jid",value:params.jidOrMuc,action:params.userAction,order:params.order}).up():iq.getChild("query").getChild("list").c("item",{type:"jid",value:params.jidOrMuc,action:params.userAction,order:params.order}).up(),iq}iq.c("query",{xmlns:chatUtils.MARKERS.PRIVACY}).c("list",{name:list.name});for(var index=0,j=0,len=listUserId.length;index<len;index++,j+=2)mutualBlock=listPrivacy[userId=listUserId[index]].mutualBlock,userAction=listPrivacy[userId].action,userJid=self.helpers.jidOrUserId(parseInt(userId,10)),userMuc=self.helpers.getUserNickWithMucDomain(userId),mutualBlock&&"deny"===userAction?(iq=createPrivacyItemMutal(iq,{order:j+1,jidOrMuc:userJid,userAction}),iq=createPrivacyItemMutal(iq,{order:j+2,jidOrMuc:userMuc,userAction}).up().up()):(iq=createPrivacyItem(iq,{order:j+1,jidOrMuc:userJid,userAction}),iq=createPrivacyItem(iq,{order:j+2,jidOrMuc:userMuc,userAction}));Utils.getEnv().browser?self.connection.sendIQ(iq,function(stanzaResult){callback(null)},function(stanzaError){if(stanzaError){var errorObject=chatUtils.getErrorFromXMLNode(stanzaError);callback(errorObject)}else callback(Utils.getError(408))}):(self.Client.send(iq),self.nodeStanzasCallbacks[iqParams.id]=function(stanza){stanza.getChildElements("error").length?callback(Utils.getError(408)):callback(null)})},getList:function(name,callback){var items,userJid,userId,self=this,usersList=[],iqParams={type:"get",from:self.helpers.getUserCurrentJid(),id:chatUtils.getUniqueId("getlist")},builder=Utils.getEnv().browser?$iq:XMPP.Stanza,iq=chatUtils.createStanza(builder,iqParams,"iq");iq.c("query",{xmlns:chatUtils.MARKERS.PRIVACY}).c("list",{name}),Utils.getEnv().browser?self.connection.sendIQ(iq,function(stanzaResult){for(var i=0,len=(items=stanzaResult.getElementsByTagName("item")).length;i<len;i+=2)userJid=items[i].getAttribute("value"),userId=self.helpers.getIdFromNode(userJid),usersList.push({user_id:userId,action:items[i].getAttribute("action")});callback(null,{name,items:usersList})},function(stanzaError){if(stanzaError){var errorObject=chatUtils.getErrorFromXMLNode(stanzaError);callback(errorObject,null)}else callback(Utils.getError(408),null)}):(self.nodeStanzasCallbacks[iqParams.id]=function(stanza){for(var userJid,userId,stanzaQuery=stanza.getChild("query"),list=stanzaQuery?stanzaQuery.getChild("list"):null,items=list?list.getChildElements("item"):null,usersList=[],i=0,len=items.length;i<len;i+=2)userJid=items[i].attrs.value,userId=self.helpers.getIdFromNode(userJid),usersList.push({user_id:userId,action:items[i].attrs.action});list={name:list.attrs.name,items:usersList},callback(null,list),delete self.nodeStanzasCallbacks[iqParams.id]},self.Client.send(iq))},update:function(listWithUpdates,callback){var self=this;self.getList(listWithUpdates.name,function(error,existentList){if(error)callback(error,null);else{var updatedList={};updatedList.items=Utils.MergeArrayOfObjects(existentList.items,listWithUpdates.items),updatedList.name=listWithUpdates.name,self.create(updatedList,function(err,result){error?callback(err,null):callback(null,result)})}})},getNames:function(callback){var iq,self=this,stanzaParams={type:"get",from:self.helpers.getUserCurrentJid(),id:chatUtils.getUniqueId("getNames")};Utils.getEnv().browser?(iq=$iq(stanzaParams).c("query",{xmlns:Strophe.NS.PRIVACY_LIST}),self.connection.sendIQ(iq,function(stanzaResult){for(var allNames=[],defaultList=stanzaResult.getElementsByTagName("default"),activeList=stanzaResult.getElementsByTagName("active"),allLists=stanzaResult.getElementsByTagName("list"),defaultName=defaultList&&defaultList.length>0?defaultList[0].getAttribute("name"):null,activeName=activeList&&activeList.length>0?activeList[0].getAttribute("name"):null,i=0,len=allLists.length;i<len;i++)allNames.push(allLists[i].getAttribute("name"));callback(null,{default:defaultName,active:activeName,names:allNames})},function(stanzaError){if(stanzaError){var errorObject=chatUtils.getErrorFromXMLNode(stanzaError);callback(errorObject,null)}else callback(Utils.getError(408),null)})):((iq=new XMPP.Stanza("iq",stanzaParams)).c("query",{xmlns:chatUtils.MARKERS.PRIVACY}),self.nodeStanzasCallbacks[iq.attrs.id]=function(stanza){if("error"!==stanza.attrs.type){for(var allNames=[],query=stanza.getChild("query"),defaultList=query.getChild("default"),activeList=query.getChild("active"),allLists=query.getChildElements("list"),defaultName=defaultList?defaultList.attrs.name:null,activeName=activeList?activeList.attrs.name:null,i=0,len=allLists.length;i<len;i++)allNames.push(allLists[i].attrs.name);callback(null,{default:defaultName,active:activeName,names:allNames})}else callback(Utils.getError(408))},self.Client.send(iq))},delete:function(name,callback){var iq,stanzaParams={from:this.connection?this.connection.jid:this.Client.jid.user,type:"set",id:chatUtils.getUniqueId("remove")};Utils.getEnv().browser?(iq=$iq(stanzaParams).c("query",{xmlns:Strophe.NS.PRIVACY_LIST}).c("list",{name:name||""}),this.connection.sendIQ(iq,function(stanzaResult){callback(null)},function(stanzaError){if(stanzaError){var errorObject=chatUtils.getErrorFromXMLNode(stanzaError);callback(errorObject)}else callback(Utils.getError(408))})):((iq=new XMPP.Stanza("iq",stanzaParams)).c("query",{xmlns:chatUtils.MARKERS.PRIVACY}).c("list",{name:name||""}),this.nodeStanzasCallbacks[stanzaParams.id]=function(stanza){stanza.getChildElements("error").length?callback(Utils.getError(408)):callback(null)},this.Client.send(iq))},setAsDefault:function(name,callback){var iq,self=this,stanzaParams={from:this.connection?this.connection.jid:this.Client.jid.user,type:"set",id:chatUtils.getUniqueId("default")};function setAsActive(self){var setAsActiveIq,setAsActiveStanzaParams={from:self.connection?self.connection.jid:self.Client.jid.user,type:"set",id:chatUtils.getUniqueId("active1")};Utils.getEnv().browser?(setAsActiveIq=$iq(setAsActiveStanzaParams).c("query",{xmlns:Strophe.NS.PRIVACY_LIST}).c("active",name&&name.length>0?{name}:{}),self.connection.sendIQ(setAsActiveIq,function(setAsActiveStanzaResult){callback(null)},function(setAsActiveStanzaError){if(setAsActiveStanzaError){var setAsActiveErrorObject=chatUtils.getErrorFromXMLNode(setAsActiveStanzaError);callback(setAsActiveErrorObject)}else callback(Utils.getError(408))})):((setAsActiveIq=new XMPP.Stanza("iq",setAsActiveStanzaParams)).c("query",{xmlns:chatUtils.MARKERS.PRIVACY}).c("active",name&&name.length>0?{name}:{}),self.nodeStanzasCallbacks[setAsActiveStanzaParams.id]=function(setAsActistanza){setAsActistanza.getChildElements("error").length?callback(Utils.getError(408)):callback(null)},self.Client.send(setAsActiveIq))}Utils.getEnv().browser?(iq=$iq(stanzaParams).c("query",{xmlns:Strophe.NS.PRIVACY_LIST}).c("default",name&&name.length>0?{name}:{}),this.connection.sendIQ(iq,function(stanzaResult){setAsActive(self)},function(stanzaError){if(stanzaError){var errorObject=chatUtils.getErrorFromXMLNode(stanzaError);callback(errorObject)}else callback(Utils.getError(408))})):((iq=new XMPP.Stanza("iq",stanzaParams)).c("query",{xmlns:chatUtils.MARKERS.PRIVACY}).c("default",name&&name.length>0?{name}:{}),this.nodeStanzasCallbacks[stanzaParams.id]=function(stanza){stanza.getChildElements("error").length?callback(Utils.getError(408)):setAsActive(self)},this.Client.send(iq))}},Helpers.prototype={getUniqueId:chatUtils.getUniqueId,jidOrUserId:function(jid_or_user_id){var jid;if("string"==typeof jid_or_user_id)jid=jid_or_user_id;else{if("number"!=typeof jid_or_user_id)throw new Error('The method "jidOrUserId" may take jid or id');jid=jid_or_user_id+"-"+config.creds.appId+"@"+config.endpoints.chat}return jid},typeChat:function(jid_or_user_id){var chatType;if("string"==typeof jid_or_user_id)chatType=jid_or_user_id.indexOf("muc")>-1?"groupchat":"chat";else{if("number"!=typeof jid_or_user_id)throw new Error(unsupportedError);chatType="chat"}return chatType},getRecipientId:function(occupantsIds,UserId){var recipient=null;return occupantsIds.forEach(function(item){item!=UserId&&(recipient=item)}),recipient},getUserJid:function(userId,appId){return appId?userId+"-"+appId+"@"+config.endpoints.chat:userId+"-"+config.creds.appId+"@"+config.endpoints.chat},getUserNickWithMucDomain:function(userId){return config.endpoints.muc+"/"+userId},getIdFromNode:function(jid){return jid.indexOf("@")<0?null:parseInt(jid.split("@")[0].split("-")[0])},getDialogIdFromNode:function(jid){return jid.indexOf("@")<0?null:jid.split("@")[0].split("_")[1]},getRoomJidFromDialogId:function(dialogId){return config.creds.appId+"_"+dialogId+"@"+config.endpoints.muc},getRoomJid:function(jid){return jid+"/"+this.getIdFromNode(this._userCurrentJid)},getIdFromResource:function(jid){var s=jid.split("/");return s.length<2?null:(s.splice(0,1),parseInt(s.join("/")))},getRoomJidFromRoomFullJid:function(jid){var s=jid.split("/");return s.length<2?null:s[0]},getBsonObjectId:function(){return Utils.getBsonObjectId()},getUserIdFromRoomJid:function(jid){var arrayElements=jid.toString().split("/");return 0===arrayElements.length?null:arrayElements[arrayElements.length-1]},userCurrentJid:function(client){try{return client instanceof Strophe.Connection?client.jid:client.jid.user+"@"+client.jid._domain+"/"+client.jid._resource}catch(e){return client.jid.user+"@"+client.jid._domain+"/"+client.jid._resource}},getUserCurrentJid:function(){return this._userCurrentJid},setUserCurrentJid:function(jid){this._userCurrentJid=jid},getDialogJid:function(identifier){return identifier.indexOf("@")>0?identifier:this.getRoomJidFromDialogId(identifier)}},module.exports=ChatProxy},{"../../plugins/streamManagement":150,"../../qbConfig":151,"../../qbStrophe":154,"../../qbUtils":155,"./qbChatHelpers":133,"nativescript-xmpp-client":void 0,"node-xmpp-client":60}],133:[function(require,module,exports){"use strict";var utils=require("../../qbUtils"),config=require("../../qbConfig"),ERR_UNKNOWN_INTERFACE="Unknown interface. SDK support browser / node env.",MARKERS={CLIENT:"jabber:client",CHAT:"urn:xmpp:chat-markers:0",STATES:"http://jabber.org/protocol/chatstates",MARKERS:"urn:xmpp:chat-markers:0",CARBONS:"urn:xmpp:carbons:2",ROSTER:"jabber:iq:roster",MUC:"http://jabber.org/protocol/muc",PRIVACY:"jabber:iq:privacy",LAST:"jabber:iq:last"};function ChatNotConnectedError(message,fileName,lineNumber){var instance=new Error(message,fileName,lineNumber);return instance.name="ChatNotConnectedError",Object.setPrototypeOf(instance,Object.getPrototypeOf(this)),Error.captureStackTrace&&Error.captureStackTrace(instance,ChatNotConnectedError),instance}ChatNotConnectedError.prototype=Object.create(Error.prototype,{constructor:{value:Error,enumerable:!1,writable:!0,configurable:!0}}),Object.setPrototypeOf?Object.setPrototypeOf(ChatNotConnectedError,Error):ChatNotConnectedError.__proto__=Error;var qbChatHelpers={MARKERS,ChatNotConnectedError,buildUserJid:function(params){var jid;return"userId"in params?(jid=params.userId+"-"+config.creds.appId+"@"+config.endpoints.chat,"resource"in params&&(jid=jid+"/"+params.resource)):"jid"in params&&(jid=params.jid),jid},createStanza:function(builder,params,type){return utils.getEnv().browser?builder(params):new builder(type||"message",params)},getAttr:function(el,attrName){var attr;return el?("function"==typeof el.getAttribute?attr=el.getAttribute(attrName):el.attrs&&(attr=el.attrs[attrName]),attr||null):null},getElement:function(stanza,elName){var el;if("function"==typeof stanza.querySelector)el=stanza.querySelector(elName);else{if("function"!=typeof stanza.getChild)throw ERR_UNKNOWN_INTERFACE;el=stanza.getChild(elName)||stanza.children.find(child=>"function"==typeof child.getChild&&this.getElement(child,elName))}return el||null},getAllElements:function(stanza,elName){var el;if("function"==typeof stanza.querySelectorAll)el=stanza.querySelectorAll(elName);else{if("function"!=typeof stanza.getChild)throw ERR_UNKNOWN_INTERFACE;el=stanza.getChild(elName)}return el||null},getElementText:function(stanza,elName){var el,txt;if("function"==typeof stanza.querySelector)txt=(el=stanza.querySelector(elName))?el.textContent:null;else{if("function"!=typeof stanza.getChildText)throw ERR_UNKNOWN_INTERFACE;txt=stanza.getChildText(elName)||stanza.children.find(child=>"function"==typeof child.getChildText&&this.getElementText(child,elName))}return txt||null},_JStoXML:function(title,obj,msg){var self=this;msg.c(title),Object.keys(obj).forEach(function(field){"object"==typeof obj[field]?self._JStoXML(field,obj[field],msg):msg.c(field).t(obj[field]).up()}),msg.up()},_XMLtoJS:function(extension,title,obj){var self=this;extension[title]={};for(var i=0,len=obj.childNodes.length;i<len;i++)obj.childNodes[i].childNodes.length>1?extension[title]=self._XMLtoJS(extension[title],obj.childNodes[i].tagName,obj.childNodes[i]):extension[title][obj.childNodes[i].tagName]=obj.childNodes[i].textContent;return extension},filledExtraParams:function(stanza,extension){var helper=this;return Object.keys(extension).forEach(function(field){"attachments"===field?extension[field].forEach(function(attach){utils.getEnv().browser?stanza.c("attachment",attach).up():stanza.getChild("extraParams").c("attachment",attach).up()}):"object"==typeof extension[field]?helper._JStoXML(field,extension[field],stanza):utils.getEnv().browser?stanza.c(field).t(extension[field]).up():stanza.getChild("extraParams").c(field).t(extension[field]).up()}),stanza.up(),stanza},parseExtraParams:function(extraParams){var self=this;if(!extraParams)return null;var dialogId,attach,attributes,extension={},attachments=[];if(utils.getEnv().browser)for(var i=0,len=extraParams.childNodes.length;i<len;i++)if("attachment"===extraParams.childNodes[i].tagName){attach={};for(var j=0,len2=(attributes=extraParams.childNodes[i].attributes).length;j<len2;j++)"size"===attributes[j].name?attach[attributes[j].name]=parseInt(attributes[j].value):attach[attributes[j].name]=attributes[j].value;attachments.push(attach)}else if("dialog_id"===extraParams.childNodes[i].tagName)dialogId=extraParams.childNodes[i].textContent,extension.dialog_id=dialogId;else if(extraParams.childNodes[i].childNodes.length>1)if(extraParams.childNodes[i].textContent.length>4096){for(var wholeNodeContent="",k=0;k<extraParams.childNodes[i].childNodes.length;++k)wholeNodeContent+=extraParams.childNodes[i].childNodes[k].textContent;extension[extraParams.childNodes[i].tagName]=wholeNodeContent}else extension=self._XMLtoJS(extension,extraParams.childNodes[i].tagName,extraParams.childNodes[i]);else extension[extraParams.childNodes[i].tagName]=extraParams.childNodes[i].textContent;else for(var c=0,lenght=extraParams.children.length;c<lenght;c++){if("attachment"===extraParams.children[c].name){attach={},attributes=extraParams.children[c].attrs;for(var attrKeys=Object.keys(attributes),l=0;l<attrKeys.length;l++)"size"===attrKeys[l]?attach.size=parseInt(attributes.size):attach[attrKeys[l]]=attributes[attrKeys[l]];attachments.push(attach)}else"dialog_id"===extraParams.children[c].name&&(dialogId=extraParams.getChildText("dialog_id"),extension.dialog_id=dialogId);if(1===extraParams.children[c].children.length){var child=extraParams.children[c];extension[child.name]=child.children[0]}}return attachments.length>0&&(extension.attachments=attachments),extension.moduleIdentifier&&delete extension.moduleIdentifier,{extension,dialogId}},getUniqueId:function(suffix){var uuid="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(c){var r=16*Math.random()|0;return("x"==c?r:3&r|8).toString(16)});return"string"==typeof suffix||"number"==typeof suffix?uuid+":"+suffix:uuid+""},getErrorFromXMLNode:function(stanzaError){var errorElement=this.getElement(stanzaError,"error"),errorCode=parseInt(this.getAttr(errorElement,"code")),errorText=this.getElementText(errorElement,"text");return utils.getError(errorCode,errorText)},getLocalTime:function(){return(new Date).toTimeString().split(" ")[0]}};module.exports=qbChatHelpers},{"../../qbConfig":151,"../../qbUtils":155}],134:[function(require,module,exports){"use strict";var config=require("../../qbConfig"),Utils=require("../../qbUtils"),DIALOGS_API_URL=config.urls.chat+"/Dialog";function DialogProxy(service){this.service=service}DialogProxy.prototype={list:function(params,callback){"function"==typeof params&&void 0===callback&&(callback=params,params={}),this.service.ajax({url:Utils.getUrl(DIALOGS_API_URL),data:params},callback)},create:function(params,callback){params&&params.occupants_ids&&Utils.isArray(params.occupants_ids)&&(params.occupants_ids=params.occupants_ids.join(", ")),this.service.ajax({url:Utils.getUrl(DIALOGS_API_URL),type:"POST",data:params},callback)},update:function(id,params,callback){this.service.ajax({url:Utils.getUrl(DIALOGS_API_URL,id),type:"PUT",contentType:"application/json; charset=utf-8",isNeedStringify:!0,data:params},callback)},delete:function(id,params_or_callback,callback){var ajaxParams={url:Utils.getUrl(DIALOGS_API_URL,id),type:"DELETE",dataType:"text"};2===arguments.length?this.service.ajax(ajaxParams,params_or_callback):3===arguments.length&&(ajaxParams.data=params_or_callback,this.service.ajax(ajaxParams,callback))}},module.exports=DialogProxy},{"../../qbConfig":151,"../../qbUtils":155}],135:[function(require,module,exports){"use strict";var config=require("../../qbConfig"),Utils=require("../../qbUtils"),MESSAGES_API_URL=config.urls.chat+"/Message";function MessageProxy(service){this.service=service}MessageProxy.prototype={list:function(params,callback){this.service.ajax({url:Utils.getUrl(MESSAGES_API_URL),data:params},callback)},create:function(params,callback){this.service.ajax({url:Utils.getUrl(MESSAGES_API_URL),type:"POST",contentType:"application/json; charset=utf-8",isNeedStringify:!0,data:params},callback)},update:function(id,params,callback){var attrAjax={type:"PUT",dataType:"text",url:Utils.getUrl(MESSAGES_API_URL,id),data:params};this.service.ajax(attrAjax,callback)},delete:function(id,params_or_callback,callback){var ajaxParams={url:Utils.getUrl(MESSAGES_API_URL,id),type:"DELETE",dataType:"text"};2===arguments.length?this.service.ajax(ajaxParams,params_or_callback):3===arguments.length&&(ajaxParams.data=params_or_callback,this.service.ajax(ajaxParams,callback))},unreadCount:function(params,callback){params&&params.chat_dialog_ids&&Utils.isArray(params.chat_dialog_ids)&&(params.chat_dialog_ids=params.chat_dialog_ids.join()),this.service.ajax({url:Utils.getUrl(MESSAGES_API_URL+"/unread"),data:params},callback)}},module.exports=MessageProxy},{"../../qbConfig":151,"../../qbUtils":155}],136:[function(require,module,exports){"use strict";var Utils=require("../qbUtils"),AI_API_URL="ai/ai_extensions";function AIProxy(service){this.service=service}AIProxy.prototype={answerAssist:function(smartChatAssistantId,message,history,callback){if(!callback||"function"!=typeof callback)throw new Error("Callback function is required and must be a function");function validateHistory(history){var AIRole={user:"user",assistant:"assistant"};if(null!=history){if(!Array.isArray(history))throw new Error("History must be an array");for(var i=0;i<history.length;i++){var item=history[i];if("object"!=typeof item||null===item||Array.isArray(item))throw new Error("Each element of history must be an object");if(!("role"in item)||!("message"in item))throw new Error("Each element of history must have an role and message fields");if(item.role!==AIRole.user&&item.role!==AIRole.assistant)throw new Error("Invalid role in history item");if("string"!=typeof item.message)throw new Error("Message of history item must be a string")}}return!0}if(validateHistory(history)){var data=history?{smart_chat_assistant_id:smartChatAssistantId,message,history}:{smart_chat_assistant_id:smartChatAssistantId,message},attrAjax={type:"POST",url:Utils.formatUrl(AI_API_URL+"/ai_answer_assist"),data,contentType:"application/json; charset=utf-8",isNeedStringify:!0};this.service.ajax(attrAjax,callback)}},translate:function(smartChatAssistantId,text,languageCode,callback){if(!callback||"function"!=typeof callback)throw new Error("Callback function is required and must be a function");var data={smart_chat_assistant_id:smartChatAssistantId,text,to_language:languageCode||"en"},attrAjax={type:"POST",url:Utils.formatUrl(AI_API_URL+"/ai_translate"),data};this.service.ajax(attrAjax,callback)},gateway:function(smartChatAssistantId,messages,optionsOrCallback,callback){var options,cb;if("function"==typeof optionsOrCallback?(cb=optionsOrCallback,options={}):(options=optionsOrCallback||{},cb=callback),!cb||"function"!=typeof cb)throw new Error("Callback function is required and must be a function");if(!smartChatAssistantId||"string"!=typeof smartChatAssistantId)throw new Error("smartChatAssistantId is required and must be a string");this._validateGatewayMessages(messages);var data={smart_chat_assistant_id:smartChatAssistantId,messages},attrAjax={type:"POST",url:Utils.formatUrl(AI_API_URL+"/ai_gateway"),data,contentType:"application/json; charset=utf-8",isNeedStringify:!0};options.apiKey&&(attrAjax.headers={Authorization:"ApiKey "+options.apiKey}),this.service.ajax(attrAjax,cb)},_validateGatewayMessages:function(messages){var validRoles=["user","assistant","developer"],validContentTypes=["text","image_url"];if(!messages||!Array.isArray(messages))throw new Error("messages is required and must be an array");if(0===messages.length)throw new Error("messages array cannot be empty");for(var i=0;i<messages.length;i++){var msg=messages[i];if("object"!=typeof msg||null===msg||Array.isArray(msg))throw new Error("Each message must be an object");if(!msg.role||-1===validRoles.indexOf(msg.role))throw new Error("Each message must have a valid role (user, assistant, or developer)");if(void 0===msg.content||null===msg.content)throw new Error("Each message must have content (string or array)");if("string"!=typeof msg.content){if(!Array.isArray(msg.content))throw new Error("Message content must be a string or array");if(0===msg.content.length)throw new Error("Content array cannot be empty");for(var j=0;j<msg.content.length;j++){var item=msg.content[j];if("object"!=typeof item||null===item)throw new Error("Each content item must be an object");if(!item.type||-1===validContentTypes.indexOf(item.type))throw new Error("Each content item must have a valid type (text or image_url)");if("text"===item.type){if("string"!=typeof item.text)throw new Error("Text content item must have a text string")}else if("image_url"===item.type&&(!item.image_url||"string"!=typeof item.image_url.url))throw new Error("Image content item must have image_url.url string")}}else if(0===msg.content.length)throw new Error("String content cannot be empty")}return!0},summarize:function(smartChatAssistantId,dialogId,callback){if(!callback||"function"!=typeof callback)throw new Error("Callback function is required and must be a function");if(!smartChatAssistantId||"string"!=typeof smartChatAssistantId)throw new Error("smartChatAssistantId is required and must be a string");if(!dialogId||"string"!=typeof dialogId)throw new Error("dialogId is required and must be a string");var data={smart_chat_assistant_id:smartChatAssistantId,dialog_id:dialogId},attrAjax={type:"POST",url:Utils.formatUrl(AI_API_URL+"/ai_summarize"),data,contentType:"application/json; charset=utf-8",isNeedStringify:!0};this.service.ajax(attrAjax,callback)}},module.exports=AIProxy},{"../qbUtils":155}],137:[function(require,module,exports){"use strict";var Utils=require("../qbUtils"),config=require("../qbConfig");function AddressBook(service){this.service=service}function isFunction(func){return!!(func&&func.constructor&&func.call&&func.apply)}AddressBook.prototype={uploadAddressBook:function(list,optionsOrcallback,callback){if(Array.isArray(list)){var opts,cb;isFunction(optionsOrcallback)?cb=optionsOrcallback:(opts=optionsOrcallback,cb=callback);var data={contacts:list};opts&&(opts.force&&(data.force=opts.force),opts.udid&&(data.udid=opts.udid)),this.service.ajax({type:"POST",url:Utils.getUrl(config.urls.addressbook),data,contentType:"application/json; charset=utf-8",isNeedStringify:!0},function(err,res){err?cb(err,null):cb(null,res)})}else new Error("First parameter must be an Array.")},_isFakeErrorEmptyAddressBook:function(err){var errDetails=err.detail?err.detail:err.message.errors;return 404===err.code&&"Empty address book"===errDetails[0]},get:function(udidOrCallback,callback){var udid,cb,self=this;if(isFunction(udidOrCallback)?cb=udidOrCallback:(udid=udidOrCallback,cb=callback),!isFunction(cb))throw new Error("The QB.addressbook.get accept callback function is required.");var ajaxParams={type:"GET",url:Utils.getUrl(config.urls.addressbook),contentType:"application/json; charset=utf-8",isNeedStringify:!0};udid&&(ajaxParams.data={udid}),this.service.ajax(ajaxParams,function(err,res){err?self._isFakeErrorEmptyAddressBook(err)?cb(null,[]):cb(err,null):cb(null,res)})},getRegisteredUsers:function(isCompactOrCallback,callback){var isCompact,cb,self=this;if(isFunction(isCompactOrCallback)?cb=isCompactOrCallback:(isCompact=isCompactOrCallback,cb=callback),!isFunction(cb))throw new Error("The QB.addressbook.get accept callback function is required.");var ajaxParams={type:"GET",url:Utils.getUrl(config.urls.addressbookRegistered),contentType:"application/json; charset=utf-8"};isCompact&&(ajaxParams.data={compact:1}),this.service.ajax(ajaxParams,function(err,res){err?self._isFakeErrorEmptyAddressBook(err)?cb(null,[]):cb(err,null):cb(null,res)})}},module.exports=AddressBook},{"../qbConfig":151,"../qbUtils":155}],138:[function(require,module,exports){"use strict";var config=require("../qbConfig"),Utils=require("../qbUtils"),sha1=require("crypto-js/hmac-sha1"),sha256=require("crypto-js/hmac-sha256");function AuthProxy(service){this.service=service}function generateAuthMsg(params){var message={application_id:config.creds.appId,auth_key:config.creds.authKey,nonce:Utils.randomNonce(),timestamp:Utils.unixTime()};return params.login&&params.password?message.user={login:params.login,password:params.password}:params.email&&params.password?message.user={email:params.email,password:params.password}:params.provider&&(message.provider=params.provider,params.scope&&(message.scope=params.scope),params.keys&&params.keys.token&&(message.keys={token:params.keys.token}),params.keys&&params.keys.secret&&(message.keys.secret=params.keys.secret)),message}function signMessage(message,secret){var cryptoSessionMsg,sessionMsg=Object.keys(message).map(function(val){return"object"==typeof message[val]?Object.keys(message[val]).map(function(val1){return val+"["+val1+"]="+message[val][val1]}).sort().join("&"):val+"="+message[val]}).sort().join("&");if("sha1"===config.hash)cryptoSessionMsg=sha1(sessionMsg,secret).toString();else{if("sha256"!==config.hash)throw new Error("Quickblox SDK: unknown crypto standards, available sha1 or sha256");cryptoSessionMsg=sha256(sessionMsg,secret).toString()}return cryptoSessionMsg}AuthProxy.prototype={getSession:function(callback){this.service.ajax({url:Utils.getUrl(config.urls.session)},function(err,res){callback(err,err?null:res)})},createSession:function(params,callback){if(""===config.creds.appId||""===config.creds.authKey||""===config.creds.authSecret)throw new Error("Cannot create a new session without app credentials (app ID, auth key and auth secret)");var message,_this=this;"function"==typeof params&&void 0===callback&&(callback=params,params={}),(message=generateAuthMsg(params)).signature=signMessage(message,config.creds.authSecret),this.service.ajax({url:Utils.getUrl(config.urls.session),type:"POST",data:message},function(err,res){err?callback(err,null):(_this.service.setSession(res.session),callback(null,res.session))})},destroySession:function(callback){var _this=this;this.service.ajax({url:Utils.getUrl(config.urls.session),type:"DELETE",dataType:"text"},function(err,res){err?callback(err,null):(_this.service.setSession(null),callback(null,res))})},login:function(params,callback){var ajaxParams={type:"POST",url:Utils.getUrl(config.urls.login),data:params};function handleResponce(err,res){err?callback(err,null):callback(null,res.user)}this.service.ajax(ajaxParams,handleResponce)},logout:function(callback){this.service.ajax({url:Utils.getUrl(config.urls.login),type:"DELETE",dataType:"text"},callback)}},module.exports=AuthProxy},{"../qbConfig":151,"../qbUtils":155,"crypto-js/hmac-sha1":30,"crypto-js/hmac-sha256":31}],139:[function(require,module,exports){"use strict";var config=require("../qbConfig"),Utils=require("../qbUtils");function ContentProxy(service){this.service=service}function parseUri(str){for(var o=parseUri.options,m=o.parser[o.strictMode?"strict":"loose"].exec(str),uri={},i=14;i--;)uri[o.key[i]]=m[i]||"";return uri[o.q.name]={},uri[o.key[12]].replace(o.q.parser,function($0,$1,$2){$1&&(uri[o.q.name][$1]=$2)}),uri}ContentProxy.prototype={list:function(params,callback){"function"==typeof params&&void 0===callback&&(callback=params,params=null),this.service.ajax({url:Utils.getUrl(config.urls.blobs),data:params,type:"GET"},function(err,result){callback(err,err?null:result)})},create:function(params,callback){this.service.ajax({type:"POST",data:{blob:params},url:Utils.getUrl(config.urls.blobs)},function(err,result){callback(err,err?null:result.blob)})},delete:function(id,callback){this.service.ajax({url:Utils.getUrl(config.urls.blobs,id),type:"DELETE",dataType:"text"},function(err,result){err?callback(err,null):callback(null,!0)})},createAndUpload:function(params,callback){var file,name,type,size,fileId,_this=this,createParams={};JSON.parse(JSON.stringify(params)).file.data="...",file=params.file,name=params.name||file.name,type=params.type||file.type,size=params.size||file.size,createParams.name=name,createParams.content_type=type,params.public&&(createParams.public=params.public),params.tag_list&&(createParams.tag_list=params.tag_list),this.create(createParams,function(err,createResult){if(err)callback(err,null);else{var uri=parseUri(createResult.blob_object_access.params),uploadParams={url:uri.protocol+"://"+uri.authority+uri.path},data={};fileId=createResult.id,createResult.size=size,Object.keys(uri.queryKey).forEach(function(val){data[val]=decodeURIComponent(uri.queryKey[val])}),data.file=file,data.name=name,uploadParams.data=data,_this.upload(uploadParams,function(err,result){err?callback(err,null):_this.markUploaded({id:fileId,size},function(err,result){err?callback(err,null):callback(null,createResult)})})}})},upload:function(params,callback){var data=Object.assign({},params.data),file={data:params.data.file,name:params.data.name||params.data.file.name};data.file=file;var uploadParams={type:"POST",dataType:"text",contentType:!1,url:params.url,data,fileToCustomObject:!0};this.service.ajax(uploadParams,function(err,xmlDoc){err?callback(err,null):callback(null,{})})},markUploaded:function(params,callback){this.service.ajax({url:Utils.getUrl(config.urls.blobs,params.id+"/complete"),type:"PUT",data:{size:params.size},dataType:"text"},function(err,res){err?callback(err,null):callback(null,res)})},getInfo:function(id,callback){this.service.ajax({url:Utils.getUrl(config.urls.blobs,id)},function(err,res){err?callback(err,null):callback(null,res)})},getFile:function(uid,callback){this.service.ajax({url:Utils.getUrl(config.urls.blobs,uid)},function(err,res){err?callback(err,null):callback(null,res)})},update:function(params,callback){var data={blob:{}};void 0!==params.name&&(data.blob.name=params.name),this.service.ajax({url:Utils.getUrl(config.urls.blobs,params.id),data},function(err,res){err?callback(err,null):callback(null,res)})},privateUrl:function(fileUID){return"https://"+config.endpoints.api+"/blobs/"+fileUID+"?token="+this.service.getSession().token},publicUrl:function(fileUID){return"https://"+config.endpoints.api+"/blobs/"+fileUID}},module.exports=ContentProxy,parseUri.options={strictMode:!1,key:["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],q:{name:"queryKey",parser:/(?:^|&)([^&=]*)=?([^&]*)/g},parser:{strict:/^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,loose:/^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/}}},{"../qbConfig":151,"../qbUtils":155}],140:[function(require,module,exports){"use strict";var config=require("../qbConfig"),Utils=require("../qbUtils");function DataProxy(service){this.service=service}DataProxy.prototype={create:function(className,data,callback){var ajaxParams={type:"POST",data,isNeedStringify:!0,contentType:"application/json; charset=utf-8",url:Utils.getUrl(config.urls.data,className)};this.service.ajax(ajaxParams,function(err,res){callback(err,err?null:res)})},list:function(className,filters,callback){void 0===callback&&"function"==typeof filters&&(callback=filters,filters=null),this.service.ajax({url:Utils.getUrl(config.urls.data,className),data:filters},function(err,result){callback(err,err?null:result)})},update:function(className,data,callback){this.service.ajax({url:Utils.getUrl(config.urls.data,className+"/"+data._id),type:"PUT",contentType:"application/json; charset=utf-8",isNeedStringify:!0,data},function(err,result){callback(err,err?null:result)})},delete:function(className,requestedData,callback){var requestedTypeOf,typesData={id:1,ids:2,criteria:3},responceNormalized={deleted:[],deletedCount:0},ajaxParams={type:"DELETE",dataType:"text"};function handleDeleteCO(error,result){var response;error?callback(error,null):(requestedTypeOf===typesData.id?(responceNormalized.deleted.push(requestedData),responceNormalized.deletedCount=responceNormalized.deleted.length):requestedTypeOf===typesData.ids?(response=JSON.parse(result),responceNormalized.deleted=response.SuccessfullyDeleted.ids.slice(0),responceNormalized.deletedCount=responceNormalized.deleted.length):requestedTypeOf===typesData.criteria&&(response=JSON.parse(result),responceNormalized.deleted=null,responceNormalized.deletedCount=response.total_deleted),callback(error,responceNormalized))}"string"==typeof requestedData?requestedTypeOf=typesData.id:Utils.isArray(requestedData)?requestedTypeOf=typesData.ids:Utils.isObject(requestedData)&&(requestedTypeOf=typesData.criteria),requestedTypeOf===typesData.id?ajaxParams.url=Utils.getUrl(config.urls.data,className+"/"+requestedData):requestedTypeOf===typesData.ids?ajaxParams.url=Utils.getUrl(config.urls.data,className+"/"+requestedData.toString()):requestedTypeOf===typesData.criteria&&(ajaxParams.url=Utils.getUrl(config.urls.data,className+"/by_criteria"),ajaxParams.data=requestedData),this.service.ajax(ajaxParams,handleDeleteCO)},uploadFile:function(className,params,callback){var data={field_name:params.field_name,file:{data:params.file,name:params.name}};this.service.ajax({url:Utils.getUrl(config.urls.data,className+"/"+params.id+"/file"),type:"POST",fileToCustomObject:!0,contentType:!1,data},function(err,result){callback(err,err?null:result)})},downloadFile:function(className,params,callback){var result=Utils.getUrl(config.urls.data,className+"/"+params.id+"/file");callback(null,result+="?field_name="+params.field_name+"&token="+this.service.getSession().token)},fileUrl:function(className,params){var result=Utils.getUrl(config.urls.data,className+"/"+params.id+"/file");return result+="?field_name="+params.field_name+"&token="+this.service.getSession().token},deleteFile:function(className,params,callback){this.service.ajax({url:Utils.getUrl(config.urls.data,className+"/"+params.id+"/file"),data:{field_name:params.field_name},dataType:"text",type:"DELETE"},function(err,result){callback(err,!err||null)})}},module.exports=DataProxy},{"../qbConfig":151,"../qbUtils":155}],141:[function(require,module,exports){(function(Buffer){(function(){"use strict";var config=require("../qbConfig"),Utils=require("../qbUtils"),isBrowser="undefined"!=typeof window;function PushNotificationsProxy(service){this.service=service,this.subscriptions=new SubscriptionsProxy(service),this.events=new EventsProxy(service),this.base64Encode=function(str){return isBrowser?btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g,function(match,p1){return String.fromCharCode("0x"+p1)})):new Buffer(str).toString("base64")}}function SubscriptionsProxy(service){this.service=service}function EventsProxy(service){this.service=service}SubscriptionsProxy.prototype={create:function(params,callback){this.service.ajax({url:Utils.getUrl(config.urls.subscriptions),type:"POST",data:params},callback)},list:function(callback){this.service.ajax({url:Utils.getUrl(config.urls.subscriptions)},callback)},delete:function(id,callback){var attrAjax={type:"DELETE",dataType:"text",url:Utils.getUrl(config.urls.subscriptions,id)};this.service.ajax(attrAjax,function(err,res){err?callback(err,null):callback(null,!0)})}},EventsProxy.prototype={create:function(params,callback){this.service.ajax({url:Utils.getUrl(config.urls.events),type:"POST",contentType:"application/json; charset=utf-8",isNeedStringify:!0,data:{event:params}},callback)},list:function(params,callback){"function"==typeof params&&void 0===callback&&(callback=params,params=null),this.service.ajax({url:Utils.getUrl(config.urls.events),data:params},callback)},get:function(id,callback){this.service.ajax({url:Utils.getUrl(config.urls.events,id)},callback)},delete:function(id,callback){this.service.ajax({url:Utils.getUrl(config.urls.events,id),dataType:"text",type:"DELETE"},callback)},status:function(id,callback){this.service.ajax({url:Utils.getUrl(config.urls.events,id+"/status")},callback)}},module.exports=PushNotificationsProxy}).call(this)}).call(this,require("buffer").Buffer)},{"../qbConfig":151,"../qbUtils":155,buffer:27}],142:[function(require,module,exports){"use strict";var config=require("../qbConfig"),Utils=require("../qbUtils"),DATE_FIELDS=["created_at","updated_at","last_request_at"],NUMBER_FIELDS=["id","external_user_id"],resetPasswordUrl=config.urls.users+"/password/reset";function UsersProxy(service){this.service=service}function generateFilter(obj){var type=obj.field in DATE_FIELDS?"date":typeof obj.value;return Utils.isArray(obj.value)&&("object"===type&&(type=typeof obj.value[0]),obj.value=obj.value.toString()),[type,obj.field,obj.param,obj.value].join(" ")}function generateOrder(obj){var type=obj.field in DATE_FIELDS?"date":obj.field in NUMBER_FIELDS?"number":"string";return[obj.sort,type,obj.field].join(" ")}UsersProxy.prototype={listUsers:function(params,callback){var item,message={},filters=[];"function"==typeof params&&void 0===callback&&(callback=params,params={}),params&&params.filter&&(Utils.isArray(params.filter)?params.filter.forEach(function(el){item=generateFilter(el),filters.push(item)}):(item=generateFilter(params.filter),filters.push(item)),message.filter=filters),params.order&&(message.order=generateOrder(params.order)),params.page&&(message.page=params.page),params.per_page&&(message.per_page=params.per_page),this.service.ajax({url:Utils.getUrl(config.urls.users),data:message},callback)},get:function(params,callback){var url;"number"==typeof params?(url=params,params={}):params.login?url="by_login":params.full_name?url="by_full_name":params.facebook_id?url="by_facebook_id":params.twitter_id?url="by_twitter_id":params.phone?url="phone":params.email?url="by_email":params.tags?url="by_tags":params.external&&(url="external/"+params.external,params={}),this.service.ajax({url:Utils.getUrl(config.urls.users,url),data:params},function(err,res){err?callback(err,null):callback(null,res.user||res)})},create:function(params,callback){this.service.ajax({url:Utils.getUrl(config.urls.users),type:"POST",data:{user:params}},function(err,res){err?callback(err,null):callback(null,res.user)})},update:function(id,params,callback){this.service.ajax({url:Utils.getUrl(config.urls.users,id),type:"PUT",data:{user:params}},function(err,res){err?callback(err,null):callback(null,res.user)})},delete:function(params,callback){var url;"number"==typeof params?url=params:params.external&&(url="external/"+params.external),this.service.ajax({url:Utils.getUrl(config.urls.users,url),type:"DELETE",dataType:"text"},callback)},resetPassword:function(email,callback){this.service.ajax({url:Utils.getUrl(resetPasswordUrl),data:{email},dataType:"text"},callback)}},module.exports=UsersProxy},{"../qbConfig":151,"../qbUtils":155}],143:[function(require,module,exports){"use strict";var config=require("../../qbConfig"),Helpers=require("./qbWebRTCHelpers"),qbRTCPeerConnection=function qbRTCPeerConnection(config){this._pc=new window.RTCPeerConnection(config),this.remoteStream=void 0,this.preferredCodec="VP8"};function _getStats(peer,lastResults,successCallback,errorCallback){var statistic={local:{audio:{},video:{},candidate:{}},remote:{audio:{},video:{},candidate:{}}};if(Helpers.getVersionFirefox()){var localStream=peer.getLocalStreams().length?peer.getLocalStreams()[0]:peer.delegate.localStream,localVideoSettings=localStream.getVideoTracks().length?localStream.getVideoTracks()[0].getSettings():null;statistic.local.video.frameHeight=localVideoSettings&&localVideoSettings.height,statistic.local.video.frameWidth=localVideoSettings&&localVideoSettings.width}function _getBitratePerSecond(result,lastResults,isLocal){var bitrate,lastResult=lastResults&&lastResults.get(result.id),seconds=lastResult?(result.timestamp-lastResult.timestamp)/1e3:5,kilo=1024,bit=8;return bitrate=lastResult?isLocal?bit*(result.bytesSent-lastResult.bytesSent)/(kilo*seconds):bit*(result.bytesReceived-lastResult.bytesReceived)/(kilo*seconds):0,Math.round(bitrate)}function _getFramesPerSecond(result,lastResults,isLocal){var framesPerSecond,lastResult=lastResults&&lastResults.get(result.id),seconds=lastResult?(result.timestamp-lastResult.timestamp)/1e3:5;return framesPerSecond=lastResult?isLocal?(result.framesSent-lastResult.framesSent)/seconds:(result.framesReceived-lastResult.framesReceived)/seconds:0,Math.round(10*framesPerSecond)/10}peer.getStats(null).then(function(results){results.forEach(function(result){var item;result.bytesReceived&&"inbound-rtp"===result.type?((item=statistic.remote[result.mediaType]).bitrate=_getBitratePerSecond(result,lastResults,!1),item.bytesReceived=result.bytesReceived,item.packetsReceived=result.packetsReceived,item.timestamp=result.timestamp,"video"===result.mediaType&&result.framerateMean&&(item.framesPerSecond=Math.round(10*result.framerateMean)/10)):result.bytesSent&&"outbound-rtp"===result.type?((item=statistic.local[result.mediaType]).bitrate=_getBitratePerSecond(result,lastResults,!0),item.bytesSent=result.bytesSent,item.packetsSent=result.packetsSent,item.timestamp=result.timestamp,"video"===result.mediaType&&result.framerateMean&&(item.framesPerSecond=Math.round(10*result.framerateMean)/10)):"local-candidate"===result.type?(item=statistic.local.candidate,"host"===result.candidateType&&"udp"===result.mozLocalTransport&&"udp"===result.transport?(item.protocol=result.transport,item.ip=result.ipAddress,item.port=result.portNumber):Helpers.getVersionFirefox()||(item.protocol=result.protocol,item.ip=result.ip,item.port=result.port)):"remote-candidate"===result.type?((item=statistic.remote.candidate).protocol=result.protocol||result.transport,item.ip=result.ip||result.ipAddress,item.port=result.port||result.portNumber):"track"!==result.type||"video"!==result.kind||Helpers.getVersionFirefox()||(result.remoteSource?((item=statistic.remote.video).frameHeight=result.frameHeight,item.frameWidth=result.frameWidth,item.framesPerSecond=_getFramesPerSecond(result,lastResults,!1)):((item=statistic.local.video).frameHeight=result.frameHeight,item.frameWidth=result.frameWidth,item.framesPerSecond=_getFramesPerSecond(result,lastResults,!0)))}),successCallback(statistic,results)},errorCallback)}function findLineInRange(sdpLines,startLine,endLine,prefix,substr,direction){if(void 0===direction&&(direction="asc"),"asc"===(direction=direction||"asc")){for(var realEndLine=-1!==endLine?endLine:sdpLines.length,i=startLine;i<realEndLine;++i)if(0===sdpLines[i].indexOf(prefix)&&(!substr||-1!==sdpLines[i].toLowerCase().indexOf(substr.toLowerCase())))return i}else for(var j=-1!==startLine?startLine:sdpLines.length-1;j>=0;--j)if(0===sdpLines[j].indexOf(prefix)&&(!substr||-1!==sdpLines[j].toLowerCase().indexOf(substr.toLowerCase())))return j;return null}function getCodecPayloadTypeFromLine(sdpLine){var pattern=new RegExp("a=rtpmap:(\\d+) [a-zA-Z0-9-]+\\/\\d+"),result=sdpLine.match(pattern);return result&&2===result.length?result[1]:null}function setDefaultCodec(mLine,payload){var elements=mLine.split(" "),newLine=elements.slice(0,3);newLine.push(payload);for(var i=3;i<elements.length;i++)elements[i]!==payload&&newLine.push(elements[i]);return newLine.join(" ")}function setPreferredCodec(sdp,type,codec){if(!codec)return sdp;var sdpLines=sdp.split("\r\n"),mLineIndex=findLineInRange(sdpLines,0,-1,"m=",type);if(null===mLineIndex)return sdp;for(var payload=null,i=sdpLines.length-1;i>=0;--i){var index=findLineInRange(sdpLines,i,0,"a=rtpmap",codec,"desc");if(null===index)break;i=index,(payload=getCodecPayloadTypeFromLine(sdpLines[index]))&&(sdpLines[mLineIndex]=setDefaultCodec(sdpLines[mLineIndex],payload))}return sdp=sdpLines.join("\r\n")}function _removeExtmapMixedFromSDP(description){return description&&description.sdp&&-1!==description.sdp.indexOf("\na=extmap-allow-mixed")&&(description.sdp=description.sdp.split("\n").filter(function(line){return"a=extmap-allow-mixed"!==line.trim()}).join("\n")),description}function setMediaBitrate(sdp,media,bitrate){if(!bitrate)return sdp.replace(/b=AS:.*\r\n/,"").replace(/b=TIAS:.*\r\n/,"");for(var lines=sdp.split("\n"),line=-1,modifier=Helpers.getVersionFirefox()?"TIAS":"AS",amount=Helpers.getVersionFirefox()?1024*bitrate:bitrate,i=0;i<lines.length;i++)if(0===lines[i].indexOf("m="+media)){line=i;break}if(-1===line)return sdp;for(line++;0===lines[line].indexOf("i=")||0===lines[line].indexOf("c=");)line++;if(0===lines[line].indexOf("b"))return lines[line]="b="+modifier+":"+amount,lines.join("\n");var newLines=lines.slice(0,line);return newLines.push("b="+modifier+":"+amount),(newLines=newLines.concat(lines.slice(line,lines.length))).join("\n")}qbRTCPeerConnection.State={NEW:1,CONNECTING:2,CHECKING:3,CONNECTED:4,DISCONNECTED:5,FAILED:6,CLOSED:7,COMPLETED:8},qbRTCPeerConnection.prototype._init=function(delegate,userID,sessionID,polite){Helpers.trace("RTCPeerConnection init.","userID: ",userID,", sessionID: ",sessionID,", polite: ",polite),this.delegate=delegate,this.localIceCandidates=[],this.remoteIceCandidates=[],this.remoteSDP=void 0,this.sessionID=sessionID,this.polite=polite,this.userID=userID,this._reconnecting=!1,this.state=qbRTCPeerConnection.State.NEW,this._pc.onicecandidate=this.onIceCandidateCallback.bind(this),this._pc.onsignalingstatechange=this.onSignalingStateCallback.bind(this),this._pc.oniceconnectionstatechange=this.onIceConnectionStateCallback.bind(this),this._pc.ontrack=this.onTrackCallback.bind(this),this.dialingTimer=null,this.answerTimeInterval=0,this.statsReportTimer=null},qbRTCPeerConnection.prototype.release=function(){this._clearDialingTimer(),this._clearStatsReportTimer(),this._pc.close(),this.state=qbRTCPeerConnection.State.CLOSED,this._pc.onicecandidate=null,this._pc.onsignalingstatechange=null,this._pc.oniceconnectionstatechange=null,this._pc.ontrack=null,navigator.userAgent.includes("Edge")&&(this.connectionState="closed",this.iceConnectionState="closed")},qbRTCPeerConnection.prototype.negotiate=function(){var self=this;return this.setLocalSessionDescription({type:"offer",options:{iceRestart:!0}},function(error){if(error)return Helpers.traceError("Error in 'negotiate': "+error);var description=self._pc.localDescription.toJSON();self.delegate.update({reason:"reconnect",sessionDescription:{offerId:self.offerId,sdp:description.sdp,type:description.type}},self.userID)})},qbRTCPeerConnection.prototype.setRemoteSDP=function(newSDP){if(!newSDP)throw new Error("sdp string can't be empty.");this.remoteSDP=newSDP},qbRTCPeerConnection.prototype.getRemoteSDP=function(){return this.remoteSDP},qbRTCPeerConnection.prototype.setLocalSessionDescription=function(params,callback){var self=this;function successCallback(description){var modifiedDescription=_removeExtmapMixedFromSDP(description);modifiedDescription.sdp=setPreferredCodec(modifiedDescription.sdp,"video",self.preferredCodec),self.delegate.bandwidth&&(modifiedDescription.sdp=setMediaBitrate(modifiedDescription.sdp,"video",self.delegate.bandwidth)),self._pc.setLocalDescription(modifiedDescription).then(function(){callback(null)}).catch(function(error){Helpers.traceError("Error in 'setLocalSessionDescription': "+error),callback(error)})}self.state=qbRTCPeerConnection.State.CONNECTING,window.RTCRtpTransceiver&&"setCodecPreferences"in window.RTCRtpTransceiver.prototype&&Boolean(Helpers.getVersionSafari())&&self._pc.getTransceivers().forEach(function(transceiver){var kind=transceiver.sender.track.kind,sendCodecs=window.RTCRtpSender.getCapabilities(kind).codecs,recvCodecs=window.RTCRtpReceiver.getCapabilities(kind).codecs;if("video"===kind){var preferredCodecSendIndex=sendCodecs.findIndex(function(codec){return codec.mimeType.toLowerCase().includes(self.preferredCodec.toLowerCase())});if(-1!==preferredCodecSendIndex){var arrayWithPreferredSendCodec=sendCodecs.splice(preferredCodecSendIndex,1);sendCodecs.unshift(arrayWithPreferredSendCodec[0])}var preferredCodecRecvIndex=recvCodecs.findIndex(function(codec){return codec.mimeType.toLowerCase().includes(self.preferredCodec.toLowerCase())});if(-1!==preferredCodecRecvIndex){var arrayWithPreferredRecvCodec=recvCodecs.splice(preferredCodecRecvIndex,1);recvCodecs.unshift(arrayWithPreferredRecvCodec[0])}var filteredSendCodecs=sendCodecs.filter(function(codec){return!codec.mimeType.toLowerCase().includes("h264")}),filteredRecvCodecs=recvCodecs.filter(function(codec){return!codec.mimeType.toLowerCase().includes("h264")}),codecs=filteredSendCodecs.concat(filteredRecvCodecs);transceiver.setCodecPreferences(codecs)}}),"answer"===params.type?this._pc.createAnswer(params.options).then(successCallback).catch(callback):this._pc.createOffer(params.options).then(successCallback).catch(callback)},qbRTCPeerConnection.prototype.setRemoteSessionDescription=function(description,callback){var modifiedSDP=this.delegate.bandwidth?{type:description.type,sdp:setMediaBitrate(description.sdp,"video",this.delegate.bandwidth)}:description;this._pc.setRemoteDescription(modifiedSDP).then(function(){callback()}).catch(function(error){Helpers.traceError("Error in 'setRemoteSessionDescription': "+error),callback(error)})},qbRTCPeerConnection.prototype.addLocalStream=function(stream){if(!stream)throw new Error("'qbRTCPeerConnection.addLocalStream' error: stream is not defined");var self=this;stream.getTracks().forEach(function(track){self._pc.addTrack(track,stream)})},qbRTCPeerConnection.prototype._addIceCandidate=function(iceCandidate){return this._pc.addIceCandidate(iceCandidate).catch(function(error){Helpers.traceError("Error on 'addIceCandidate': "+error)})},qbRTCPeerConnection.prototype.addCandidates=function(iceCandidates){var self=this;iceCandidates.forEach(function(candidate){self.remoteIceCandidates.push(candidate)}),this._pc.remoteDescription&&self.remoteIceCandidates.forEach(function(candidate){self._addIceCandidate(candidate)})},qbRTCPeerConnection.prototype.toString=function sessionToString(){return"sessionID: "+this.sessionID+", userID: "+this.userID+", state: "+this.state},qbRTCPeerConnection.prototype.onSignalingStateCallback=function(){if("stable"===this._pc.signalingState&&this.localIceCandidates.length>0)for(this.delegate.processIceCandidates(this,this.localIceCandidates);this.localIceCandidates.length;)this.localIceCandidates.pop()},qbRTCPeerConnection.prototype.onIceCandidateCallback=function(event){if(event.candidate){var candidate={candidate:event.candidate.candidate,sdpMid:event.candidate.sdpMid,sdpMLineIndex:event.candidate.sdpMLineIndex};"stable"===this._pc.signalingState?this.delegate.processIceCandidates(this,[candidate]):this.localIceCandidates.push(candidate)}},qbRTCPeerConnection.prototype.onTrackCallback=function(event){this.remoteStream=event.streams[0],"function"==typeof this.delegate._onRemoteStreamListener&&["connected","completed"].includes(this._pc.iceConnectionState)&&this.delegate._onRemoteStreamListener(this.userID,this.remoteStream),this._getStatsWrap()},qbRTCPeerConnection.prototype.onIceConnectionStateCallback=function(){Helpers.trace("onIceConnectionStateCallback: "+this._pc.iceConnectionState);var connectionState=null;switch(this._pc.iceConnectionState){case"checking":this.state=qbRTCPeerConnection.State.CHECKING,connectionState=Helpers.SessionConnectionState.CONNECTING;break;case"connected":this._reconnecting&&this.delegate._stopReconnectTimer(this.userID),this.state=qbRTCPeerConnection.State.CONNECTED,connectionState=Helpers.SessionConnectionState.CONNECTED;break;case"completed":this._reconnecting&&this.delegate._stopReconnectTimer(this.userID),this.state=qbRTCPeerConnection.State.COMPLETED,connectionState=Helpers.SessionConnectionState.COMPLETED;break;case"failed":this.delegate._startReconnectTimer(this.userID),this.state=qbRTCPeerConnection.State.FAILED,connectionState=Helpers.SessionConnectionState.FAILED;break;case"disconnected":this.delegate._startReconnectTimer(this.userID),this.state=qbRTCPeerConnection.State.DISCONNECTED,connectionState=Helpers.SessionConnectionState.DISCONNECTED;break;case"closed":this.delegate._stopReconnectTimer(this.userID),this.state=qbRTCPeerConnection.State.CLOSED,connectionState=Helpers.SessionConnectionState.CLOSED}"function"==typeof this.delegate._onSessionConnectionStateChangedListener&&connectionState&&this.delegate._onSessionConnectionStateChangedListener(this.userID,connectionState),"connected"===this._pc.iceConnectionState&&"function"==typeof this.delegate._onRemoteStreamListener&&this.delegate._onRemoteStreamListener(this.userID,this.remoteStream)},qbRTCPeerConnection.prototype._clearStatsReportTimer=function(){this.statsReportTimer&&(clearInterval(this.statsReportTimer),this.statsReportTimer=null)},qbRTCPeerConnection.prototype._getStatsWrap=function(){var statsReportInterval,lastResult,self=this;if(config.webrtc&&config.webrtc.statsReportTimeInterval&&!self.statsReportTimer){if(isNaN(+config.webrtc.statsReportTimeInterval))return void Helpers.traceError("statsReportTimeInterval ("+config.webrtc.statsReportTimeInterval+") must be integer.");statsReportInterval=1e3*config.webrtc.statsReportTimeInterval;var _statsReportCallback=function(){_getStats(self._pc,lastResult,function(results,lastResults){lastResult=lastResults,self.delegate._onCallStatsReport(self.userID,results,null)},function errorLog(err){Helpers.traceError("_getStats error. "+err.name+": "+err.message),self.delegate._onCallStatsReport(self.userID,null,err)})};Helpers.trace("Stats tracker has been started."),self.statsReportTimer=setInterval(_statsReportCallback,statsReportInterval)}},qbRTCPeerConnection.prototype._clearDialingTimer=function(){this.dialingTimer&&(Helpers.trace("_clearDialingTimer"),clearInterval(this.dialingTimer),this.dialingTimer=null,this.answerTimeInterval=0)},qbRTCPeerConnection.prototype._startDialingTimer=function(extension){var self=this,dialingTimeInterval=1e3*config.webrtc.dialingTimeInterval;Helpers.trace("_startDialingTimer, dialingTimeInterval: "+dialingTimeInterval);var _dialingCallback=function(extension,skipIncrement){skipIncrement||(self.answerTimeInterval+=dialingTimeInterval),Helpers.trace("_dialingCallback, answerTimeInterval: "+self.answerTimeInterval),self.answerTimeInterval>=1e3*config.webrtc.answerTimeInterval?(self._clearDialingTimer(),self.delegate.processOnNotAnswer(self)):self.delegate.processCall(self,extension)};self.dialingTimer=setInterval(_dialingCallback,dialingTimeInterval,extension,!1),_dialingCallback(extension,!0)},module.exports=qbRTCPeerConnection},{"../../qbConfig":151,"./qbWebRTCHelpers":145}],144:[function(require,module,exports){"use strict";var WebRTCSession=require("./qbWebRTCSession"),WebRTCSignalingProcessor=require("./qbWebRTCSignalingProcessor"),WebRTCSignalingProvider=require("./qbWebRTCSignalingProvider"),Helpers=require("./qbWebRTCHelpers"),RTCPeerConnection=require("./qbRTCPeerConnection"),SignalingConstants=require("./qbWebRTCSignalingConstants"),Utils=require("../../qbUtils"),config=require("../../qbConfig"),LiveSessionStates=[WebRTCSession.State.NEW,WebRTCSession.State.CONNECTING,WebRTCSession.State.ACTIVE];function WebRTCClient(service,chat){this.chat=chat,this.signalingProcessor=new WebRTCSignalingProcessor(service,this),this.signalingProvider=new WebRTCSignalingProvider(service,chat),chat.webrtcSignalingProcessor=this.signalingProcessor,this.SessionConnectionState=Helpers.SessionConnectionState,this.CallType=Helpers.CallType,this.PeerConnectionState=RTCPeerConnection.State,this.sessions={},navigator.mediaDevices&&"ondevicechange"in navigator.mediaDevices&&(navigator.mediaDevices.ondevicechange=this._onDevicesChangeListener.bind(this))}function isOpponentsEqual(exOpponents,currentOpponents){var ans=!1,cOpponents=currentOpponents.sort();return exOpponents.length&&exOpponents.forEach(function(i){var array=i.sort();ans=array.length==cOpponents.length&&array.every(function(el,index){return el===cOpponents[index]})}),ans}function getOpponentsIdNASessions(sessions){var opponents=[];return Object.keys(sessions).length>0&&Object.keys(sessions).forEach(function(key,i,arr){var session=sessions[key];session.state!==WebRTCSession.State.NEW&&session.state!==WebRTCSession.State.ACTIVE||opponents.push(session.opponentsIDs)}),opponents}WebRTCClient.prototype.getMediaDevices=function(spec){var specDevices=[],errMsg="Browser does not support output device selection.";return new Promise(function(resolve,reject){navigator.mediaDevices&&navigator.mediaDevices.enumerateDevices?navigator.mediaDevices.enumerateDevices().then(function(devices){spec?(devices.forEach(function(device,i){device.kind===spec&&specDevices.push(device)}),resolve(specDevices)):resolve(devices)}):(reject(errMsg),Helpers.traceWarning(errMsg))})},WebRTCClient.prototype.sessions={},WebRTCClient.prototype.createNewSession=function(opponentsIDs,ct,cID,opts){var opponentsIdNASessions=getOpponentsIdNASessions(this.sessions),callerID=cID||Helpers.getIdFromNode(this.chat.connection.jid),bandwidth=opts&&opts.bandwidth&&!isNaN(opts.bandwidth)?+opts.bandwidth:0,callType=ct||2;if(!opponentsIDs)throw new Error("Can't create a session without the opponentsIDs.");if(!Array.isArray(opponentsIDs))throw new Error('"opponentsIDs" should be Array of numbers');if(opponentsIDs.forEach(function(id){var value=parseInt(id);if(isNaN(value))throw new Error('"opponentsIDs" should be Array of numbers');id=value}),isOpponentsEqual(opponentsIdNASessions,opponentsIDs))throw new Error("Can't create a session with the same opponentsIDs. There is a session already in NEW or ACTIVE state.");return this._createAndStoreSession(null,callerID,opponentsIDs,callType,bandwidth)},WebRTCClient.prototype._createAndStoreSession=function(sessionID,callerID,opponentsIDs,callType,bandwidth){var newSession=new WebRTCSession({sessionID,initiatorID:callerID,opIDs:opponentsIDs,callType,signalingProvider:this.signalingProvider,currentUserID:Helpers.getIdFromNode(this.chat.connection.jid),bandwidth});return newSession.onUserNotAnswerListener=this.onUserNotAnswerListener,newSession.onReconnectListener=this.onReconnectListener,newSession.onRemoteStreamListener=this.onRemoteStreamListener,newSession.onSessionConnectionStateChangedListener=this.onSessionConnectionStateChangedListener,newSession.onSessionCloseListener=this.onSessionCloseListener,newSession.onCallStatsReport=this.onCallStatsReport,this.sessions[newSession.ID]=newSession,newSession},WebRTCClient.prototype.clearSession=function(sessionId){delete WebRTCClient.sessions[sessionId]},WebRTCClient.prototype.isExistLiveSessionExceptSessionID=function(sessionID){var exist=!1,sessions=this.sessions;return Object.keys(sessions).length>0&&(exist=Object.keys(sessions).some(function(key){var session=sessions[key];return LiveSessionStates.includes(session.state)&&session.ID!==sessionID})),exist},WebRTCClient.prototype.getNewSessionsCount=function(exceptId){var sessions=this.sessions;return Object.keys(sessions).reduce(function(count,sessionId){var session=sessions[sessionId];return session.ID===exceptId?count:session.state===WebRTCSession.State.NEW?count+1:count},0)},WebRTCClient.prototype._onCallListener=function(userID,sessionID,extension){var userInfo=extension.userInfo||{},currentUserID=Helpers.getIdFromNode(this.chat.connection.jid);if(userID!==currentUserID||extension.opponentsIDs.includes(currentUserID)){Helpers.trace("onCall. UserID:"+userID+". SessionID: "+sessionID);var otherActiveSessions=this.isExistLiveSessionExceptSessionID(sessionID),newSessionsCount=this.getNewSessionsCount(sessionID);if(otherActiveSessions&&!this.sessions[sessionID]&&newSessionsCount++,otherActiveSessions&&(config.webrtc.autoReject||newSessionsCount>config.webrtc.incomingLimit))Helpers.trace("User with id "+userID+" is busy at the moment."),delete extension.sessionDescription,delete extension.platform,extension.sessionID=sessionID,this.signalingProvider.sendMessage(userID,extension,SignalingConstants.SignalingType.REJECT),"function"==typeof this.onInvalidEventsListener&&Utils.safeCallbackCall(this.onInvalidEventsListener,"onCall",sessionID,userID,userInfo);else{var session=this.sessions[sessionID],bandwidth=+userInfo.bandwidth||0;session||(session=this._createAndStoreSession(sessionID,extension.callerID,extension.opponentsIDs,extension.callType,bandwidth),"function"==typeof this.onCallListener&&Utils.safeCallbackCall(this.onCallListener,session,userInfo)),session.processOnCall(userID,extension)}}else Helpers.trace('Ignore "onCall" signal from current user. userID:'+userID+", sessionID: "+sessionID)},WebRTCClient.prototype._onAcceptListener=function(userID,sessionID,extension){var session=this.sessions[sessionID],userInfo=extension.userInfo||{};Helpers.trace("onAccept. UserID:"+userID+". SessionID: "+sessionID),session?session.state===WebRTCSession.State.CONNECTING||session.state===WebRTCSession.State.ACTIVE?("function"==typeof this.onAcceptCallListener&&Utils.safeCallbackCall(this.onAcceptCallListener,session,userID,userInfo),session.processOnAccept(userID,extension)):("function"==typeof this.onInvalidEventsListener&&Utils.safeCallbackCall(this.onInvalidEventsListener,"onAccept",session,userID,userInfo),Helpers.traceWarning("Ignore 'onAccept', the session( "+sessionID+" ) has invalid state.")):Helpers.traceError("Ignore 'onAccept', there is no information about session "+sessionID+" by some reason.")},WebRTCClient.prototype._onRejectListener=function(userID,sessionID,extension){var that=this,session=that.sessions[sessionID];if(Helpers.trace("onReject. UserID:"+userID+". SessionID: "+sessionID),session){var userInfo=extension.userInfo||{};"function"==typeof this.onRejectCallListener&&Utils.safeCallbackCall(that.onRejectCallListener,session,userID,userInfo),session.processOnReject(userID,extension)}else Helpers.traceError("Ignore 'onReject', there is no information about session "+sessionID+" by some reason.")},WebRTCClient.prototype._onStopListener=function(userID,sessionID,extension){Helpers.trace("onStop. UserID:"+userID+". SessionID: "+sessionID);var session=this.sessions[sessionID],userInfo=extension.userInfo||{};session&&LiveSessionStates.includes(session.state)?("function"==typeof this.onStopCallListener&&Utils.safeCallbackCall(this.onStopCallListener,session,userID,userInfo),setTimeout(session.processOnStop.bind(session),10,userID,extension)):("function"==typeof this.onInvalidEventsListener&&Utils.safeCallbackCall(this.onInvalidEventsListener,"onStop",session,userID,userInfo),Helpers.traceError("Ignore 'onStop', there is no information about session "+sessionID+" by some reason."))},WebRTCClient.prototype._onIceCandidatesListener=function(userID,sessionID,extension){var session=this.sessions[sessionID];Helpers.trace("onIceCandidates. UserID:"+userID+". SessionID: "+sessionID+". ICE candidates count: "+extension.iceCandidates.length),session?session.state===WebRTCSession.State.CONNECTING||session.state===WebRTCSession.State.ACTIVE?session.processOnIceCandidates(userID,extension):Helpers.traceWarning("Ignore 'OnIceCandidates', the session ( "+sessionID+" ) has invalid state."):Helpers.traceError("Ignore 'OnIceCandidates', there is no information about session "+sessionID+" by some reason.")},WebRTCClient.prototype._onUpdateListener=function(userID,sessionID,extension){var session=this.sessions[sessionID],userInfo=extension.userInfo||{};Helpers.trace("onUpdate. UserID:"+userID+". SessionID: "+sessionID+". Extension: "+JSON.stringify(userInfo)),session&&(extension.reason&&session.processOnUpdate(userID,extension),"function"==typeof this.onUpdateCallListener&&Utils.safeCallbackCall(this.onUpdateCallListener,session,userID,userInfo))},WebRTCClient.prototype._onDevicesChangeListener=function(){"function"==typeof this.onDevicesChangeListener&&Utils.safeCallbackCall(this.onDevicesChangeListener)},module.exports=WebRTCClient},{"../../qbConfig":151,"../../qbUtils":155,"./qbRTCPeerConnection":143,"./qbWebRTCHelpers":145,"./qbWebRTCSession":146,"./qbWebRTCSignalingConstants":147,"./qbWebRTCSignalingProcessor":148,"./qbWebRTCSignalingProvider":149}],145:[function(require,module,exports){"use strict";var config=require("../../qbConfig"),WebRTCHelpers={getUserJid:function(id,appId){return id+"-"+appId+"@"+config.endpoints.chat},getIdFromNode:function(jid){return jid.indexOf("@")<0?null:parseInt(jid.split("@")[0].split("-")[0])},trace:function(text){config.debug&&console.log("[QBWebRTC]:",text)},traceWarning:function(text){config.debug&&console.warn("[QBWebRTC]:",text)},traceError:function(text){config.debug&&console.error("[QBWebRTC]:",text)},getLocalTime:function(){return(new Date).toString().split(" ").slice(1,5).join("-")},isIOS:function(){if(!window||!window.navigator||!window.navigator.userAgent)return!1;var ua=window.navigator.userAgent;return Boolean(ua.match(/iP(ad|hone)/i))},isIOSSafari:function(){if(!window||!window.navigator||!window.navigator.userAgent)return!1;var ua=window.navigator.userAgent,iOS=Boolean(ua.match(/iP(ad|hone)/i)),isWebkit=Boolean(ua.match(/WebKit/i)),isChrome=Boolean(ua.match(/CriOS/i));return iOS&&isWebkit&&!isChrome},isIOSChrome:function(){if(!window||!window.navigator||!window.navigator.userAgent)return!1;var ua=window.navigator.userAgent,iOS=Boolean(ua.match(/iP(ad|hone)/i)),isWebkit=Boolean(ua.match(/WebKit/i)),isChrome=Boolean(ua.match(/CriOS/i));return iOS&&!isWebkit&&isChrome},getVersionFirefox:function(){var version,ua=!!navigator&&navigator.userAgent;if(ua){var ffInfo=ua.match(/(?:firefox)[ \/](\d+)/i)||[];version=ffInfo[1]?+ffInfo[1]:null}return version},getVersionSafari:function(){var version,ua=!!navigator&&navigator.userAgent;if(ua)if((ua.match(/(?:safari)[ \/](\d+)/i)||[]).length){var sVer=ua.match(/(?:version)[ \/](\d+)/i)||[];version=sVer&&sVer[1]?+sVer[1]:null}else version=null;return version},delay:function(timeout){return timeout="number"==typeof timeout&&timeout>0?timeout:0,new Promise(function(resolve){setTimeout(resolve,timeout)})},SessionConnectionState:{UNDEFINED:0,CONNECTING:1,CONNECTED:2,FAILED:3,DISCONNECTED:4,CLOSED:5,COMPLETED:6},CallType:{VIDEO:1,AUDIO:2}};module.exports=WebRTCHelpers},{"../../qbConfig":151}],146:[function(require,module,exports){"use strict";var config=require("../../qbConfig"),qbRTCPeerConnection=require("./qbRTCPeerConnection"),Utils=require("../../qbUtils"),Helpers=require("./qbWebRTCHelpers"),SignalingConstants=require("./qbWebRTCSignalingConstants"),ICE_TIMEOUT=5e3;WebRTCSession.State={NEW:1,ACTIVE:2,HUNGUP:3,REJECTED:4,CLOSED:5};var ReconnectionState={RECONNECTING:"reconnecting",RECONNECTED:"reconnected",FAILED:"failed"};function WebRTCSession(params){this.ID=params.sessionID?params.sessionID:generateUUID(),this.state=WebRTCSession.State.NEW,this.initiatorID=parseInt(params.initiatorID),this.opponentsIDs=params.opIDs,this.callType=parseInt(params.callType),this.peerConnections={},this.mediaParams=null,this.iceConnectTimers={},this.reconnectTimers={},this.signalingProvider=params.signalingProvider,this.currentUserID=params.currentUserID,this.bandwidth=params.bandwidth,this.answerTimer=null,this.startCallTime=0,this.acceptCallTime=0,this.localStream=void 0}function generateUUID(){var d=(new Date).getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(c){var r=(d+16*Math.random())%16|0;return d=Math.floor(d/16),("x"==c?r:3&r|8).toString(16)})}function _prepareExtension(extension){var ext={};try{if("[object Object]"!=={}.toString.call(extension))throw new Error('Invalid type of "extension" object.');ext.userInfo=extension,ext=JSON.parse(JSON.stringify(ext).replace(/null/g,'""'))}catch(err){Helpers.traceWarning(err.message)}return ext}WebRTCSession.prototype.getUserMedia=function(params,callback){if(!navigator.mediaDevices.getUserMedia)throw new Error("getUserMedia() is not supported in your browser");var self=this,mediaConstraints={audio:params.audio||!1,video:params.video||!1};function successCallback(stream){self.localStream=stream,self.mediaParams=Object.assign({},params),params.elemId&&self.attachMediaStream(params.elemId,stream,params.options),callback&&"function"==typeof callback&&callback(void 0,stream)}navigator.mediaDevices.getUserMedia(mediaConstraints).then(successCallback).catch(callback)},WebRTCSession.prototype.connectionStateForUser=function(userID){var peerConnection=this.peerConnections[userID];return peerConnection?peerConnection.state:void 0},WebRTCSession.prototype.attachMediaStream=function(elementId,stream,options){var elem=document.getElementById(elementId);if(!elem)throw new Error('Unable to attach media stream, cannot find element by Id "'+elementId+'"');if(!(elem instanceof HTMLMediaElement))throw new Error('Cannot attach media stream to element with id "'+elementId+'" because it is not of type HTMLMediaElement');"srcObject"in elem?elem.srcObject=stream:elem.src=window.URL.createObjectURL(stream),options&&options.muted&&(elem.muted=!0),options&&options.mirror&&(elem.style.transform="scaleX(-1)"),elem.autoplay||(elem.onloadedmetadata=function(){elem.play()})},WebRTCSession.prototype.detachMediaStream=function(elementId,options){var elem=document.getElementById(elementId);elem&&elem instanceof HTMLMediaElement&&(elem.pause(),options&&options.stopTracks&&elem.srcObject&&"object"==typeof elem.srcObject&&elem.srcObject.getTracks().forEach(function(track){track.stop(),track.enabled=!1}),elem.srcObject=null,elem.removeAttribute("src"),elem.removeAttribute("srcObject"))},WebRTCSession.prototype.switchMediaTracks=function(deviceIds,callback){if(!navigator.mediaDevices.getUserMedia)throw new Error("getUserMedia() is not supported in your browser");var self=this;deviceIds&&deviceIds.audio&&(this.mediaParams.audio.deviceId=deviceIds.audio),deviceIds&&deviceIds.video&&(this.mediaParams.video.deviceId=deviceIds.video),this.localStream.getTracks().forEach(function(track){track.stop()}),navigator.mediaDevices.getUserMedia({audio:self.mediaParams.audio||!1,video:self.mediaParams.video||!1}).then(function(stream){return self._replaceTracks(stream).then(function(){callback(null,stream)})}).catch(function(error){callback(error,null)})},WebRTCSession.prototype.replaceVideoTrack=function(newVideoTrack){var localStream=this.localStream,elemId=this.mediaParams.elemId,currentVideoTrack=localStream.getVideoTracks()[0];if(currentVideoTrack&&(currentVideoTrack.stop(),localStream.removeTrack(currentVideoTrack)),localStream.addTrack(newVideoTrack),elemId){var elem=document.getElementById(elemId);elem&&elem instanceof HTMLMediaElement&&(elem.srcObject=localStream)}function _replaceForPeer(peer){var videoSender=peer.getSenders().find(function(s){return s.track&&"video"===s.track.kind});return videoSender?videoSender.replaceTrack(newVideoTrack):Promise.resolve()}return Promise.all(Object.values(this.peerConnections).map(function(pc){return pc._pc}).map(_replaceForPeer))},WebRTCSession.prototype._replaceTracks=function(stream){var localStream=this.localStream,elemId=this.mediaParams.elemId,newStreamTracks=stream.getTracks();if(newStreamTracks.forEach(function(newTrack){var currentTrack=localStream.getTracks().find(function(track){return track.kind===newTrack.kind});currentTrack&&(currentTrack.stop(),localStream.removeTrack(currentTrack)),localStream.addTrack(newTrack)}),elemId){var elem=document.getElementById(elemId);elem&&elem instanceof HTMLMediaElement&&(elem.srcObject=localStream)}function _replaceTracksForPeer(peer){return Promise.all(peer.getSenders().filter(function(sender){return null!==sender.track}).map(function(sender){var newTrack=newStreamTracks.find(function(track){return track.kind===sender.track.kind});return newTrack?sender.replaceTrack(newTrack):Promise.resolve()}))}return Promise.all(Object.values(this.peerConnections).map(function(peerConnection){return peerConnection._pc}).map(_replaceTracksForPeer))},WebRTCSession.prototype.call=function(extension,callback){var self=this,ext=_prepareExtension(extension);Helpers.trace("Call, extension: "+JSON.stringify(ext.userInfo)),self.state=WebRTCSession.State.ACTIVE,self._reconnectToChat(function(){self.state===WebRTCSession.State.ACTIVE&&self.opponentsIDs.forEach(function(userID){self._callInternal(userID,ext)})}),"function"==typeof callback&&callback(null)},WebRTCSession.prototype._callInternal=function(userID,extension){var self=this,peer=this._createPeer(userID,this.currentUserID<userID);this.peerConnections[userID]=peer,peer.addLocalStream(self.localStream),peer.setLocalSessionDescription({type:"offer"},function(error){error?Helpers.trace("setLocalSessionDescription error: "+error):(Helpers.trace("setLocalSessionDescription success"),peer._startDialingTimer(extension))})},WebRTCSession.prototype.accept=function(extension){var self=this,ext=_prepareExtension(extension);if(Helpers.trace("Accept, extension: "+JSON.stringify(ext.userInfo)),self.state!==WebRTCSession.State.ACTIVE){if(self.state===WebRTCSession.State.CLOSED)return Helpers.traceError("Can't accept, the session is already closed, return."),void self.stop({});self.state=WebRTCSession.State.ACTIVE,self.acceptCallTime=new Date,self._clearAnswerTimer(),self._acceptInternal(self.initiatorID,ext);var oppIDs=self._uniqueOpponentsIDsWithoutInitiator();if(oppIDs.length>0){var offerTime=(self.acceptCallTime-self.startCallTime)/1e3;self._startWaitingOfferOrAnswerTimer(offerTime),oppIDs.forEach(function(opID,i,arr){self.currentUserID>opID&&self._callInternal(opID,{},!0)})}}else Helpers.traceError("Can't accept, the session is already active, return.")},WebRTCSession.prototype._acceptInternal=function(userID,extension){var self=this,peerConnection=this.peerConnections[userID];if(peerConnection){var remoteSDP=peerConnection.getRemoteSDP();peerConnection.addLocalStream(self.localStream),peerConnection.setRemoteSessionDescription(remoteSDP,function(error){error?Helpers.traceError("'setRemoteSessionDescription' error: "+error):(Helpers.trace("'setRemoteSessionDescription' success"),peerConnection.setLocalSessionDescription({type:"answer"},function(err){err?Helpers.trace("setLocalSessionDescription error: "+err):(Helpers.trace("'setLocalSessionDescription' success"),extension.sessionID=self.ID,extension.callType=self.callType,extension.callerID=self.initiatorID,extension.opponentsIDs=self.opponentsIDs,peerConnection._pc.localDescription&&(extension.sdp=peerConnection._pc.localDescription.toJSON().sdp),self.signalingProvider.sendMessage(userID,extension,SignalingConstants.SignalingType.ACCEPT))}))})}else Helpers.traceError("Can't accept the call, peer connection for userID "+userID+" was not found")},WebRTCSession.prototype.reject=function(extension){var self=this,ext=_prepareExtension(extension);Helpers.trace("Reject, extension: "+JSON.stringify(ext.userInfo)),self.state=WebRTCSession.State.REJECTED,self._clearAnswerTimer(),ext.sessionID=self.ID,ext.callType=self.callType,ext.callerID=self.initiatorID,ext.opponentsIDs=self.opponentsIDs,Object.keys(self.peerConnections).forEach(function(key){var peerConnection=self.peerConnections[key];self.signalingProvider.sendMessage(peerConnection.userID,ext,SignalingConstants.SignalingType.REJECT)}),self._close()},WebRTCSession.prototype.stop=function(extension){var self=this,ext=_prepareExtension(extension);Helpers.trace("Stop, extension: "+JSON.stringify(ext.userInfo)),self.state=WebRTCSession.State.HUNGUP,self.answerTimer&&self._clearAnswerTimer(),ext.sessionID=self.ID,ext.callType=self.callType,ext.callerID=self.initiatorID,ext.opponentsIDs=self.opponentsIDs,Object.keys(self.peerConnections).forEach(function(key){var peerConnection=self.peerConnections[key];self.signalingProvider.sendMessage(peerConnection.userID,ext,SignalingConstants.SignalingType.STOP)}),self._close()},WebRTCSession.prototype.closeConnection=function(userId){var self=this,peer=this.peerConnections[userId];if(!peer)return Helpers.traceWarn("Not found connection with user ("+userId+")"),!1;try{peer.release()}catch(e){Helpers.traceError(e)}finally{self._closeSessionIfAllConnectionsClosed()}},WebRTCSession.prototype.update=function(extension,userID){var self=this,ext="object"==typeof extension?extension:{};if(Helpers.trace("Update, extension: "+JSON.stringify(extension)),null!==extension)if(ext.sessionID=this.ID,ext.callType=this.callType,ext.callerID=this.initiatorID,ext.opponentsIDs=this.opponentsIDs,userID)self.signalingProvider.sendMessage(userID,ext,SignalingConstants.SignalingType.PARAMETERS_CHANGED);else for(var key in self.peerConnections){var peer=self.peerConnections[key];self.signalingProvider.sendMessage(peer.userID,ext,SignalingConstants.SignalingType.PARAMETERS_CHANGED)}else Helpers.trace("extension is null, no parameters to update")},WebRTCSession.prototype.mute=function(type){this._muteStream(0,type)},WebRTCSession.prototype.unmute=function(type){this._muteStream(1,type)},WebRTCSession.prototype.processOnCall=function(callerID,extension){var self=this;self._uniqueOpponentsIDs().forEach(function(opponentID){var peer=self.peerConnections[opponentID];peer||(peer=self._createPeer(opponentID,self.currentUserID<opponentID),self.peerConnections[opponentID]=peer,opponentID==callerID&&self._startAnswerTimer()),opponentID==callerID&&(peer.setRemoteSDP(new window.RTCSessionDescription({sdp:extension.sdp,type:"offer"})),callerID!=self.initiatorID&&self.state===WebRTCSession.State.ACTIVE&&self._acceptInternal(callerID,{}))})},WebRTCSession.prototype.processOnAccept=function(userID,extension){var self=this,peerConnection=this.peerConnections[userID];if(peerConnection)if(peerConnection._clearDialingTimer(),"stable"!==peerConnection._pc.signalingState){var remoteSessionDescription=new window.RTCSessionDescription({sdp:extension.sdp,type:"answer"});peerConnection.setRemoteSDP(remoteSessionDescription),peerConnection.setRemoteSessionDescription(remoteSessionDescription,function(error){error?Helpers.traceError("'setRemoteSessionDescription' error: "+error):(Helpers.trace("'setRemoteSessionDescription' success"),self.state!==WebRTCSession.State.ACTIVE&&(self.state=WebRTCSession.State.ACTIVE))})}else Helpers.traceError("Ignore 'onAccept', PeerConnection is already in 'stable' state");else Helpers.traceError("Ignore 'OnAccept': peer connection for user with Id "+userID+" was not found")},WebRTCSession.prototype.processOnReject=function(userID,extension){var peerConnection=this.peerConnections[userID];this._clearWaitingOfferOrAnswerTimer(),peerConnection?peerConnection.release():Helpers.traceError("Ignore 'OnReject', there is no information about peer connection by some reason."),this._closeSessionIfAllConnectionsClosed()},WebRTCSession.prototype.processOnStop=function(userID,extension){var self=this;this._clearAnswerTimer();var peerConnection=self.peerConnections[userID];peerConnection?(peerConnection.release(),peerConnection._reconnecting&&(peerConnection._reconnecting=!1),this._stopReconnectTimer(userID)):Helpers.traceError("Ignore 'OnStop', there is no information about peer connection by some reason."),this._closeSessionIfAllConnectionsClosed()},WebRTCSession.prototype.processOnIceCandidates=function(userID,extension){var peerConnection=this.peerConnections[userID];peerConnection?peerConnection.addCandidates(extension.iceCandidates):Helpers.traceError("Ignore 'OnIceCandidates', there is no information about peer connection by some reason.")},WebRTCSession.prototype.processOnUpdate=function(userID,extension){var SRD=extension.sessionDescription,reason=extension.reason;this.state===WebRTCSession.State.ACTIVE&&reason&&"reconnect"===reason&&(this.peerConnections[userID]?SRD&&("offer"===SRD.type?this._processReconnectOffer(userID,SRD):this._processReconnectAnswer(userID,SRD)):Helpers.traceError("Ignore 'OnUpdate': peer connection for user with Id "+userID+" was not found"))},WebRTCSession.prototype._processReconnectOffer=function(userID,SRD){var self=this;if(this.peerConnections[userID].polite){this._reconnect(this.peerConnections[userID]);var peer=this.peerConnections[userID],offerId=SRD.offerId,remoteDescription=new window.RTCSessionDescription({sdp:SRD.sdp,type:SRD.type});peer.setRemoteSDP(remoteDescription),peer.setRemoteSessionDescription(remoteDescription,function(e){e?Helpers.traceError('"setRemoteSessionDescription" error:'+e.message):peer.setLocalSessionDescription({type:"answer"},function(){var description=peer._pc.localDescription.toJSON(),ext={reason:"reconnect",sessionDescription:{offerId,sdp:description.sdp,type:description.type}};self.update(ext,userID)})})}else this._reconnect(this.peerConnections[userID],!0)},WebRTCSession.prototype._processReconnectAnswer=function(userID,SRD){var peer=this.peerConnections[userID],offerId=SRD.offerId;if(peer&&peer.offerId&&offerId&&peer.offerId===offerId){var remoteDescription=new window.RTCSessionDescription({sdp:SRD.sdp,type:SRD.type});peer.setRemoteSDP(remoteDescription),peer.setRemoteSessionDescription(remoteDescription,function(e){e&&Helpers.traceError('"setRemoteSessionDescription" error:'+e.message)})}},WebRTCSession.prototype.processCall=function(peerConnection,ext){var extension=ext||{};peerConnection._pc.localDescription&&(extension.sessionID=this.ID,extension.callType=this.callType,extension.callerID=this.initiatorID,extension.opponentsIDs=this.opponentsIDs,extension.sdp=peerConnection._pc.localDescription.sdp,extension.userInfo=ext&&ext.userInfo?ext.userInfo:{},extension.userInfo.bandwidth=this.bandwidth,this.signalingProvider.sendMessage(peerConnection.userID,extension,SignalingConstants.SignalingType.CALL))},WebRTCSession.prototype.processIceCandidates=function(peerConnection,iceCandidates){var extension={};extension.sessionID=this.ID,extension.callType=this.callType,extension.callerID=this.initiatorID,extension.opponentsIDs=this.opponentsIDs,this.signalingProvider.sendCandidate(peerConnection.userID,iceCandidates,extension)},WebRTCSession.prototype.processOnNotAnswer=function(peerConnection){Helpers.trace("Answer timeout callback for session "+this.ID+" for user "+peerConnection.userID),this._clearWaitingOfferOrAnswerTimer(),peerConnection.release(),"function"==typeof this.onUserNotAnswerListener&&Utils.safeCallbackCall(this.onUserNotAnswerListener,this,peerConnection.userID),this._closeSessionIfAllConnectionsClosed()},WebRTCSession.prototype._onRemoteStreamListener=function(userID,stream){"function"==typeof this.onRemoteStreamListener&&Utils.safeCallbackCall(this.onRemoteStreamListener,this,userID,stream)},WebRTCSession.prototype._onCallStatsReport=function(userId,stats,error){"function"==typeof this.onCallStatsReport&&Utils.safeCallbackCall(this.onCallStatsReport,this,userId,stats,error)},WebRTCSession.prototype._onSessionConnectionStateChangedListener=function(userID,connectionState){var StateClosed=Helpers.SessionConnectionState.CLOSED,peer=this.peerConnections[userID];"function"==typeof this.onSessionConnectionStateChangedListener&&Utils.safeCallbackCall(this.onSessionConnectionStateChangedListener,this,userID,connectionState),connectionState===StateClosed&&peer&&(peer._pc.onicecandidate=null,peer._pc.onsignalingstatechange=null,peer._pc.ontrack=null,peer._pc.oniceconnectionstatechange=null,delete this.peerConnections[userID])},WebRTCSession.prototype._createPeer=function(userId,polite){if(!window.RTCPeerConnection)throw new Error("_createPeer error: RTCPeerConnection is not supported in your browser");this.startCallTime=new Date;const base={iceServers:config.webrtc.iceServers},extra=void 0===config.webrtc.iceTransportPolicy?{}:{iceTransportPolicy:config.webrtc.iceTransportPolicy},pcConfig=Object.assign({},base,extra);Helpers.trace("_createPeer configuration: "+JSON.stringify(pcConfig));var peer=new qbRTCPeerConnection(pcConfig);return peer._init(this,userId,this.ID,polite),peer},WebRTCSession.prototype._startReconnectTimer=function(userID){var self=this,delay=1e3*config.webrtc.disconnectTimeInterval,peer=this.peerConnections[userID];peer._reconnecting=!0;var reconnectTimeoutCallback=function(){Helpers.trace("disconnectTimeInterval reached for userID "+userID),self._stopReconnectTimer(userID),self.peerConnections[userID].release(),self._onSessionConnectionStateChangedListener(userID,Helpers.SessionConnectionState.CLOSED),self._closeSessionIfAllConnectionsClosed()};"function"==typeof this.onReconnectListener&&Utils.safeCallbackCall(this.onReconnectListener,this,userID,ReconnectionState.RECONNECTING),Helpers.trace("_startReconnectTimer for userID:"+userID+", timeout: "+delay);var iceConnectTimeoutCallback=function(){Helpers.trace("iceConnectTimeout reached for user "+userID),self.iceConnectTimers[userID]&&(clearTimeout(self.iceConnectTimers[userID]),self.iceConnectTimers[userID]=void 0,self.reconnectTimers[userID]||(self.reconnectTimers[userID]=setTimeout(reconnectTimeoutCallback,delay-ICE_TIMEOUT),self._reconnectToChat(function(){self.state===WebRTCSession.State.ACTIVE&&self.reconnectTimers[userID]&&self._reconnect(peer,!0)})))};this.iceConnectTimers[userID]||(this.iceConnectTimers[userID]=setTimeout(iceConnectTimeoutCallback,ICE_TIMEOUT))},WebRTCSession.prototype._stopReconnectTimer=function(userID){var peer=this.peerConnections[userID];if(this.iceConnectTimers[userID]&&(clearTimeout(this.iceConnectTimers[userID]),this.iceConnectTimers[userID]=void 0),this.reconnectTimers[userID]&&(Helpers.trace("_stopReconnectTimer for userID: "+userID),clearTimeout(this.reconnectTimers[userID]),this.reconnectTimers[userID]=void 0),peer&&peer._reconnecting&&(peer._reconnecting=!1,"function"==typeof this.onReconnectListener)){var state=peer._pc.iceConnectionState;Utils.safeCallbackCall(this.onReconnectListener,this,userID,"connected"===state?ReconnectionState.RECONNECTED:ReconnectionState.FAILED)}},WebRTCSession.prototype._reconnectToChat=function(callback){var self=this,signalingProvider=this.signalingProvider,reconnectToChat=function(){var _onReconnectListener=signalingProvider.chat.onReconnectListener;signalingProvider.chat.onReconnectListener=function(){"function"==typeof _onReconnectListener&&_onReconnectListener(),signalingProvider.chat.onReconnectListener=_onReconnectListener,callback()},signalingProvider.chat.reconnect()};if(signalingProvider&&signalingProvider.chat)try{signalingProvider.chat.ping(function(e){self.state!==WebRTCSession.State.CLOSED&&(e?reconnectToChat():callback())})}catch(e){self.state!==WebRTCSession.State.CLOSED&&reconnectToChat()}},WebRTCSession.prototype._reconnect=function(peerConnection,negotiate){if(!peerConnection||!peerConnection.userID)return;var userId=peerConnection.userID,polite=peerConnection.polite,_reconnecting=peerConnection._reconnecting;peerConnection.release();const base={iceServers:config.webrtc.iceServers},extra=void 0===config.webrtc.iceTransportPolicy?{}:{iceTransportPolicy:config.webrtc.iceTransportPolicy},pcConfig=Object.assign({},base,extra);Helpers.trace("_reconnect peer configuration: "+JSON.stringify(pcConfig));var peer=new qbRTCPeerConnection(pcConfig);this.peerConnections[userId]=peer,peer._init(this,userId,this.ID,polite),peer._reconnecting=_reconnecting,peer.addLocalStream(this.localStream),negotiate&&(peer.offerId=generateUUID(),peer.negotiate())},WebRTCSession.prototype._close=function(){for(var key in Helpers.trace("_close"),this.peerConnections){var peer=this.peerConnections[key];this._stopReconnectTimer(peer.userID);try{peer.release()}catch(e){console.warn("Peer close error:",e)}}this._closeLocalMediaStream(),"function"==typeof this._detectSilentAudioTaskCleanup&&(this._detectSilentAudioTaskCleanup(),this._detectSilentAudioTaskCleanup=void 0),"function"==typeof this._detectSilentVideoTaskCleanup&&(this._detectSilentVideoTaskCleanup(),this._detectSilentVideoTaskCleanup=void 0),this.state=WebRTCSession.State.CLOSED,"function"==typeof this.onSessionCloseListener&&Utils.safeCallbackCall(this.onSessionCloseListener,this)},WebRTCSession.prototype._closeSessionIfAllConnectionsClosed=function(){var isAllConnectionsClosed=Object.values(this.peerConnections).every(function(peer){return peer.state===qbRTCPeerConnection.State.CLOSED});Helpers.trace("All peer connections closed: "+isAllConnectionsClosed),isAllConnectionsClosed&&(this._closeLocalMediaStream(),"function"==typeof this.onSessionCloseListener&&this.onSessionCloseListener(this),this.state=WebRTCSession.State.CLOSED)},WebRTCSession.prototype._closeLocalMediaStream=function(){this.localStream&&(this.localStream.getTracks().forEach(function(track){track.stop(),track.enabled=!1}),this.localStream=null)},WebRTCSession.prototype._muteStream=function(bool,type){"audio"===type&&this.localStream.getAudioTracks().length>0?this.localStream.getAudioTracks().forEach(function(track){track.enabled=!!bool}):"video"===type&&this.localStream.getVideoTracks().length>0&&this.localStream.getVideoTracks().forEach(function(track){track.enabled=!!bool})},WebRTCSession.prototype._clearAnswerTimer=function(){this.answerTimer&&(Helpers.trace("_clearAnswerTimer"),clearTimeout(this.answerTimer),this.answerTimer=null)},WebRTCSession.prototype._startAnswerTimer=function(){Helpers.trace("_startAnswerTimer");var self=this,answerTimeoutCallback=function(){Helpers.trace("_answerTimeoutCallback"),"function"==typeof self.onSessionCloseListener&&self._close(),self.answerTimer=null},answerTimeInterval=1e3*config.webrtc.answerTimeInterval;this.answerTimer=setTimeout(answerTimeoutCallback,answerTimeInterval)},WebRTCSession.prototype._clearWaitingOfferOrAnswerTimer=function(){this.waitingOfferOrAnswerTimer&&(Helpers.trace("_clearWaitingOfferOrAnswerTimer"),clearTimeout(this.waitingOfferOrAnswerTimer),this.waitingOfferOrAnswerTimer=null)},WebRTCSession.prototype._startWaitingOfferOrAnswerTimer=function(time){var self=this,timeout=config.webrtc.answerTimeInterval-time<0?1:config.webrtc.answerTimeInterval-time,waitingOfferOrAnswerTimeoutCallback=function(){Helpers.trace("waitingOfferOrAnswerTimeoutCallback"),Object.keys(self.peerConnections).length>0&&Object.keys(self.peerConnections).forEach(function(key){var peerConnection=self.peerConnections[key];peerConnection.state!==qbRTCPeerConnection.State.CONNECTING&&peerConnection.state!==qbRTCPeerConnection.State.NEW||self.processOnNotAnswer(peerConnection)}),self.waitingOfferOrAnswerTimer=null};Helpers.trace("_startWaitingOfferOrAnswerTimer, timeout: "+timeout),this.waitingOfferOrAnswerTimer=setTimeout(waitingOfferOrAnswerTimeoutCallback,1e3*timeout)},WebRTCSession.prototype._uniqueOpponentsIDs=function(){var self=this,opponents=[];return this.initiatorID!==this.currentUserID&&opponents.push(this.initiatorID),this.opponentsIDs.forEach(function(userID,i,arr){userID!=self.currentUserID&&opponents.push(parseInt(userID))}),opponents},WebRTCSession.prototype._uniqueOpponentsIDsWithoutInitiator=function(){var self=this,opponents=[];return this.opponentsIDs.forEach(function(userID,i,arr){userID!=self.currentUserID&&opponents.push(parseInt(userID))}),opponents},WebRTCSession.prototype.toString=function sessionToString(){return"ID: "+this.ID+", initiatorID: "+this.initiatorID+", opponentsIDs: "+this.opponentsIDs+", state: "+this.state+", callType: "+this.callType},module.exports=WebRTCSession},{"../../qbConfig":151,"../../qbUtils":155,"./qbRTCPeerConnection":143,"./qbWebRTCHelpers":145,"./qbWebRTCSignalingConstants":147}],147:[function(require,module,exports){"use strict";function WebRTCSignalingConstants(){}WebRTCSignalingConstants.MODULE_ID="WebRTCVideoChat",WebRTCSignalingConstants.SignalingType={CALL:"call",ACCEPT:"accept",REJECT:"reject",STOP:"hangUp",CANDIDATE:"iceCandidates",PARAMETERS_CHANGED:"update"},module.exports=WebRTCSignalingConstants},{}],148:[function(require,module,exports){"use strict";var __stropheMod;try{__stropheMod=require("strophe.js/dist/strophe.umd.js")}catch(e){__stropheMod=require("strophe.js")}var Strophe=__stropheMod&&(__stropheMod.Strophe||__stropheMod.default||__stropheMod)||void 0;if(!Strophe||!Strophe.Connection)throw new Error("[QBChat] Strophe import failed: Connection class not found");var SignalingConstants=require("./qbWebRTCSignalingConstants");function WebRTCSignalingProcessor(service,delegate){var self=this;self.service=service,self.delegate=delegate,this._onMessage=function(from,extraParams,delay,userId){var extension=self._getExtension(extraParams),sessionId=extension.sessionID,signalType=extension.signalType;switch(delete extension.moduleIdentifier,delete extension.sessionID,delete extension.signalType,signalType){case SignalingConstants.SignalingType.CALL:"function"==typeof self.delegate._onCallListener&&self.delegate._onCallListener(userId,sessionId,extension);break;case SignalingConstants.SignalingType.ACCEPT:"function"==typeof self.delegate._onAcceptListener&&self.delegate._onAcceptListener(userId,sessionId,extension);break;case SignalingConstants.SignalingType.REJECT:"function"==typeof self.delegate._onRejectListener&&self.delegate._onRejectListener(userId,sessionId,extension);break;case SignalingConstants.SignalingType.STOP:"function"==typeof self.delegate._onStopListener&&self.delegate._onStopListener(userId,sessionId,extension);break;case SignalingConstants.SignalingType.CANDIDATE:"function"==typeof self.delegate._onIceCandidatesListener&&self.delegate._onIceCandidatesListener(userId,sessionId,extension);break;case SignalingConstants.SignalingType.PARAMETERS_CHANGED:"function"==typeof self.delegate._onUpdateListener&&self.delegate._onUpdateListener(userId,sessionId,extension)}},this._getExtension=function(extraParams){if(!extraParams)return{};var extension={},iceCandidates=[],opponents=[];return extraParams.childNodes.forEach(function(childNode){"iceCandidates"===childNode.nodeName?childNode.childNodes.forEach(function(candidateNode){var candidate={};candidateNode.childNodes.forEach(function(node){candidate[node.nodeName]=node.textContent}),iceCandidates.push(candidate)}):"opponentsIDs"===childNode.nodeName?childNode.childNodes.forEach(function(opponentNode){var opponentId=opponentNode.textContent;opponents.push(parseInt(opponentId))}):childNode.childNodes.length>1||"userInfo"===childNode.nodeName?extension=self._XMLtoJS(extension,childNode.nodeName,childNode):extension[childNode.nodeName]=childNode.textContent}),iceCandidates.length>0&&(extension.iceCandidates=iceCandidates),opponents.length>0&&(extension.opponentsIDs=opponents),extension},this._XMLtoJS=function(extension,title,element){var self=this;return extension[title]={},element.childNodes.forEach(function(childNode){childNode.childNodes.length>1?extension[title]=self._XMLtoJS(extension[title],childNode.nodeName,childNode):extension[title][childNode.nodeName]=childNode.textContent}),extension}}module.exports=WebRTCSignalingProcessor},{"./qbWebRTCSignalingConstants":147,"strophe.js":110,"strophe.js/dist/strophe.umd.js":110}],149:[function(require,module,exports){"use strict";var __stropheMod;try{__stropheMod=require("strophe.js/dist/strophe.umd.js")}catch(e){__stropheMod=require("strophe.js")}var Strophe=__stropheMod&&(__stropheMod.Strophe||__stropheMod.default||__stropheMod)||void 0;if(!Strophe||!Strophe.Connection)throw new Error("[QBChat] Strophe import failed: Connection class not found");var Helpers=require("./qbWebRTCHelpers"),SignalingConstants=require("./qbWebRTCSignalingConstants"),Utils=require("../../qbUtils"),config=require("../../qbConfig");function WebRTCSignalingProvider(service,chat){this.service=service,this.chat=chat}WebRTCSignalingProvider.prototype.sendCandidate=function(userId,iceCandidates,ext){var extension=ext||{};extension.iceCandidates=iceCandidates,this.sendMessage(userId,extension,SignalingConstants.SignalingType.CANDIDATE)},WebRTCSignalingProvider.prototype.sendMessage=function(userId,ext,signalingType){var extension=ext||{},self=this;extension.moduleIdentifier=SignalingConstants.MODULE_ID,extension.signalType=signalingType,extension.platform="web",extension.userInfo&&!Object.keys(extension.userInfo).length&&delete extension.userInfo;var params={to:Helpers.getUserJid(userId,config.creds.appId),type:"headline",id:Utils.getBsonObjectId()},msg=$msg(params).c("extraParams",{xmlns:Strophe.NS.CLIENT});Object.keys(extension).forEach(function(field){"iceCandidates"===field?(msg.c("iceCandidates"),extension[field].forEach(function(candidate){msg.c("iceCandidate"),Object.keys(candidate).forEach(function(key){msg.c(key).t(candidate[key]).up()}),msg.up()}),msg.up()):"opponentsIDs"===field?(msg.c("opponentsIDs"),extension[field].forEach(function(opponentId){msg.c("opponentID").t(opponentId).up()}),msg.up()):"object"==typeof extension[field]?self._JStoXML(field,extension[field],msg):msg.c(field).t(extension[field]).up()}),this.chat.connection.send(msg)},WebRTCSignalingProvider.prototype._JStoXML=function(title,obj,msg){var self=this;msg.c(title),Object.keys(obj).forEach(function(field){"object"==typeof obj[field]?self._JStoXML(field,obj[field],msg):msg.c(field).t(obj[field]).up()}),msg.up()},module.exports=WebRTCSignalingProvider},{"../../qbConfig":151,"../../qbUtils":155,"./qbWebRTCHelpers":145,"./qbWebRTCSignalingConstants":147,"strophe.js":110,"strophe.js/dist/strophe.umd.js":110}],150:[function(require,module,exports){"use strict";var Utils=require("../qbUtils"),chatUtils=require("../modules/chat/qbChatHelpers");function StreamManagement(options){this._NS="urn:xmpp:sm:3",this._isStreamManagementEnabled=!1,this._clientProcessedStanzasCounter=null,this._clientSentStanzasCounter=null,this._intervalId=null,this._timeInterval=Utils.getTimeIntervalForCallBackMessage(),this.sentMessageCallback=null,Utils.getEnv().browser&&(this._parser=new DOMParser),this._c=null,this._nodeBuilder=null,this._originalSend=null,this._stanzasQueue=[]}StreamManagement.prototype.enable=function(connection,client){var stanza,self=this,enableParams={xmlns:self._NS};self._isStreamManagementEnabled||(self._c=connection,self._originalSend=this._c.send,self._c.send=this.send.bind(self)),Utils.getEnv().browser?(this._clientProcessedStanzasCounter=null,this._clientSentStanzasCounter=null,self._addEnableHandlers(),stanza=$build("enable",enableParams)):(self._nodeBuilder=client.Stanza,self._addEnableHandlers(),stanza=chatUtils.createStanza(self._nodeBuilder,enableParams,"enable")),self._c.send(stanza)},StreamManagement.prototype._timeoutCallback=function(){var self=this,now=Date.now(),updatedStanzasQueue=[];if(self._stanzasQueue.length){for(var i=0;i<self._stanzasQueue.length;i++)self._stanzasQueue[i]&&self._stanzasQueue[i].time<now?self.sentMessageCallback(self._stanzasQueue[i].message):updatedStanzasQueue.push(self._stanzasQueue[i]);self._stanzasQueue=updatedStanzasQueue}},StreamManagement.prototype._addEnableHandlers=function(){var self=this;function _incomingStanzaHandler(stanza){var tagName=stanza.name||stanza.tagName||stanza.nodeTree.tagName;if("enabled"===tagName)return self._isStreamManagementEnabled=!0,!0;if(self._isStreamManagementEnabled&&"message"===tagName)return clearInterval(self._intervalId),self._intervalId=setInterval(self._timeoutCallback.bind(self),self._timeInterval),!0;if(chatUtils.getAttr(stanza,"xmlns")!==self._NS&&self._increaseReceivedStanzasCounter(),"r"===tagName){var params={xmlns:self._NS,h:self._clientProcessedStanzasCounter},answerStanza=Utils.getEnv().browser?$build("a",params):chatUtils.createStanza(self._nodeBuilder,params,"a");return self._originalSend.call(self._c,answerStanza),!0}if("a"===tagName){var h=parseInt(chatUtils.getAttr(stanza,"h"));self._checkCounterOnIncomeStanza(h)}return!0}Utils.getEnv().browser?self._c.XAddTrackedHandler(_incomingStanzaHandler.bind(self)):self._c.on("stanza",_incomingStanzaHandler.bind(self))},StreamManagement.prototype.send=function(stanza,message){var self=this,stanzaXML=stanza.nodeTree?this._parser.parseFromString(stanza.nodeTree.outerHTML,"application/xml").childNodes[0]:stanza,tagName=stanzaXML.name||stanzaXML.tagName||stanzaXML.nodeTree.tagName,type=chatUtils.getAttr(stanzaXML,"type"),bodyContent=chatUtils.getElementText(stanzaXML,"body")||"",attachments=chatUtils.getAllElements(stanzaXML,"attachment")||"";try{self._originalSend.call(self._c,stanza)}catch(e){Utils.QBLog("[QBChat]",e.message)}finally{"message"!==tagName||"chat"!==type&&"groupchat"!==type||!bodyContent&&!attachments.length||self._sendStanzasRequest({message,time:Date.now()+self._timeInterval,expect:self._clientSentStanzasCounter}),self._clientSentStanzasCounter++}},StreamManagement.prototype._sendStanzasRequest=function(data){var self=this;if(self._isStreamManagementEnabled){self._stanzasQueue.push(data);var stanza=Utils.getEnv().browser?$build("r",{xmlns:self._NS}):chatUtils.createStanza(self._nodeBuilder,{xmlns:self._NS},"r");self._c.connected?self._originalSend.call(self._c,stanza):self._checkCounterOnIncomeStanza()}},StreamManagement.prototype.getClientSentStanzasCounter=function(){return this._clientSentStanzasCounter},StreamManagement.prototype._checkCounterOnIncomeStanza=function(count){var updatedStanzasQueue=[];if(this._stanzasQueue.length){for(var i=0;i<this._stanzasQueue.length;i++)this._stanzasQueue[i].expect==count?this.sentMessageCallback(null,this._stanzasQueue[i].message):updatedStanzasQueue.push(this._stanzasQueue[i]);this._stanzasQueue=updatedStanzasQueue}},StreamManagement.prototype._increaseReceivedStanzasCounter=function(){this._clientProcessedStanzasCounter++},module.exports=StreamManagement},{"../modules/chat/qbChatHelpers":133,"../qbUtils":155}],151:[function(require,module,exports){"use strict";var config={version:"2.22.0",buildNumber:"1176",creds:{appId:0,authKey:"",authSecret:"",accountKey:""},endpoints:{api:"api.quickblox.com",chat:"chat.quickblox.com",muc:"muc.chat.quickblox.com"},hash:"sha1",streamManagement:{enable:!1},chatProtocol:{bosh:"https://chat.quickblox.com:5281",websocket:"wss://chat.quickblox.com:5291",active:2},pingTimeout:1,pingDebug:!1,initBlockOnSettings:!1,initBlockDurationMs:3e3,pingLocalhostTimeInterval:5,chatReconnectionTimeInterval:3,chatPingMissLimit:3,webrtc:{answerTimeInterval:60,autoReject:!0,incomingLimit:1,dialingTimeInterval:5,disconnectTimeInterval:30,statsReportTimeInterval:!1,iceTransportPolicy:void 0,iceServers:[{urls:["turn:turn.quickblox.com","stun:turn.quickblox.com"],username:"quickblox",credential:"baccb97ba2d92d71e26eb9886da5f1e0"}]},urls:{account:"account_settings",session:"session",login:"login",users:"users",chat:"chat",blobs:"blobs",geodata:"geodata",pushtokens:"push_tokens",subscriptions:"subscriptions",events:"events",data:"data",addressbook:"address_book",addressbookRegistered:"address_book/registered_users",type:".json"},on:{sessionExpired:null},timeout:null,debug:{mode:0,file:null},addISOTime:!1,qbTokenExpirationDate:null,liveSessionInterval:120,callBackInterval:30,set:function(options){"object"==typeof options.endpoints&&options.endpoints.chat&&(config.endpoints.muc="muc."+options.endpoints.chat,config.chatProtocol.bosh="https://"+options.endpoints.chat+":5281",config.chatProtocol.websocket="wss://"+options.endpoints.chat+":5291"),Object.keys(options).forEach(function(key){"set"!==key&&Object.prototype.hasOwnProperty.call(config,key)&&("object"!=typeof options[key]||null===options[key]?void 0!==options[key]&&(config[key]=options[key]):Object.keys(options[key]).forEach(function(nextkey){Object.prototype.hasOwnProperty.call(config[key],nextkey)&&void 0!==options[key][nextkey]&&(config[key][nextkey]=options[key][nextkey])})),"iceServers"===key&&void 0!==options[key]&&(config.webrtc.iceServers=options[key]),"iceTransportPolicy"===key&&void 0!==options[key]&&(config.webrtc.iceTransportPolicy=options[key])})},updateSessionExpirationDate:function(tokenExpirationDate,headerHasToken=!1){var newDate,connectionTimeLag=1;if(headerHasToken){var d=tokenExpirationDate.replaceAll("-","/");(newDate=new Date(d)).setMinutes(newDate.getMinutes()-connectionTimeLag)}else(newDate=new Date(tokenExpirationDate)).setMinutes(newDate.getMinutes()-connectionTimeLag),newDate.setMinutes(newDate.getMinutes()+config.liveSessionInterval);config.qbTokenExpirationDate=newDate}};module.exports=config},{}],152:[function(require,module,exports){"use strict";var config=require("./qbConfig"),Utils=require("./qbUtils");function QuickBlox(){}QuickBlox.prototype={version:config.version,buildNumber:config.buildNumber,_getOS:Utils.getOS.bind(Utils),init:function(appIdOrToken,authKeyOrAppId,authSecret,accountKey,configMap){console.log("current platform: ",Utils.getEnv()),"string"==typeof accountKey&&accountKey.length?(configMap&&"object"==typeof configMap&&config.set(configMap),config.creds.accountKey=accountKey):(console.warn('Parameter "accountKey" is missing. This will lead to error in next major release'),console.warn('NOTE: Account migration will not work without "accountKey"'),"object"==typeof accountKey&&config.set(accountKey));var SHARED_API_ENDPOINT="api.quickblox.com",SHARED_CHAT_ENDPOINT="chat.quickblox.com",Proxy=require("./qbProxy"),Auth=require("./modules/qbAuth"),Users=require("./modules/qbUsers"),Content=require("./modules/qbContent"),PushNotifications=require("./modules/qbPushNotifications"),Data=require("./modules/qbData"),AddressBook=require("./modules/qbAddressBook"),Chat=require("./modules/chat/qbChat"),DialogProxy=require("./modules/chat/qbDialog"),MessageProxy=require("./modules/chat/qbMessage"),AIProxy=require("./modules/qbAI");if(this.service=new Proxy,this.auth=new Auth(this.service),this.users=new Users(this.service),this.content=new Content(this.service),this.pushnotifications=new PushNotifications(this.service),this.data=new Data(this.service),this.addressbook=new AddressBook(this.service),this.chat=new Chat(this.service),this.chat.dialog=new DialogProxy(this.service),this.chat.message=new MessageProxy(this.service),this.ai=new AIProxy(this.service),Utils.getEnv().browser)if(require("webrtc-adapter"),Utils.isWebRTCAvailble()){var WebRTCClient=require("./modules/webrtc/qbWebRTCClient");this.webrtc=new WebRTCClient(this.service,this.chat)}else this.webrtc=!1;else this.webrtc=!1;this._initReady=Promise.resolve();var initBlockOnSettings="boolean"!=typeof config.initBlockOnSettings||config.initBlockOnSettings,initBlockDurationMs="number"==typeof config.initBlockDurationMs?config.initBlockDurationMs:3e3;"string"!=typeof appIdOrToken||authKeyOrAppId&&"number"!=typeof authKeyOrAppId||authSecret?(config.creds.appId=appIdOrToken,config.creds.authKey=authKeyOrAppId,config.creds.authSecret=authSecret):("number"==typeof authKeyOrAppId&&(config.creds.appId=authKeyOrAppId),this.service.setSession({token:appIdOrToken}));var shouldGetSettings=config.creds.accountKey&&(!config.endpoints.api||config.endpoints.api===SHARED_API_ENDPOINT||!config.endpoints.chat||config.endpoints.chat===SHARED_CHAT_ENDPOINT);if(shouldGetSettings){var accountSettingsUrl=["https://",SHARED_API_ENDPOINT,"/",config.urls.account,config.urls.type].join(""),preserveListeners=function(obj){var map={};return obj?(Object.keys(obj).forEach(function(k){/^on[A-Z]/.test(k)&&"function"==typeof obj[k]&&(map[k]=obj[k])}),map):map},reassignListeners=function(target,map){target&&map&&Object.keys(map).forEach(function(k){target[k]=map[k]})},self=this;this._initReady=new Promise(function(resolve){self.service.ajax({url:accountSettingsUrl},function(err,response){if(!err&&"object"==typeof response){var update={endpoints:{api:response.api_endpoint.replace(/^https?:\/\//,""),chat:response.chat_endpoint}};config.set(update);var savedChatListeners=preserveListeners(self.chat),savedWebRTCListeners=preserveListeners(self.webrtc);if(self.pushnotifications=new PushNotifications(self.service),self.chat=new Chat(self.service),self.chat.dialog=new DialogProxy(self.service),self.chat.message=new MessageProxy(self.service),Utils.getEnv().browser)if(require("webrtc-adapter"),Utils.isWebRTCAvailble()){var WebRTCClient=require("./modules/webrtc/qbWebRTCClient");self.webrtc=new WebRTCClient(self.service,self.chat)}else self.webrtc=!1;else self.webrtc=!1;reassignListeners(self.chat,savedChatListeners),reassignListeners(self.webrtc,savedWebRTCListeners)}resolve()})})}if(shouldGetSettings&&initBlockOnSettings)try{for(var __qb_init_block_until__=Date.now()+initBlockDurationMs;Date.now()<__qb_init_block_until__;);}catch(_){}},ready:function(){return this._initReady||Promise.resolve()},initWithAppId:function(appId,accountKey,configMap){if("number"!=typeof appId)throw new Error("Type of appId must be a number");if(""===appId||null==appId||""===accountKey||null==accountKey)throw new Error("Cannot init QuickBlox without app credentials (app ID, auth key)");this.init("",appId,null,accountKey,configMap)},getSession:function(callback){this.auth.getSession(callback)},startSessionWithToken:function(token,callback){if(void 0===token)throw new Error("Cannot start session with undefined token");if(""===token)throw new Error("Cannot start session with empty string token");if(null===token)throw new Error("Cannot start session with null value token");if("function"!=typeof callback)throw new Error("Cannot start session without callback function");try{this.service.setSession({token})}catch(err){callback(err,null)}if("function"==typeof callback)try{this.auth.getSession(callback)}catch(er){callback(er,null)}},createSession:function(params,callback){this.auth.createSession(params,callback)},destroySession:function(callback){this.auth.destroySession(callback)},login:function(params,callback){this.auth.login(params,callback)},logout:function(callback){this.auth.logout(callback)}};var QB=new QuickBlox;QB.QuickBlox=QuickBlox,module.exports=QB},{"./modules/chat/qbChat":132,"./modules/chat/qbDialog":134,"./modules/chat/qbMessage":135,"./modules/qbAI":136,"./modules/qbAddressBook":137,"./modules/qbAuth":138,"./modules/qbContent":139,"./modules/qbData":140,"./modules/qbPushNotifications":141,"./modules/qbUsers":142,"./modules/webrtc/qbWebRTCClient":144,"./qbConfig":151,"./qbProxy":153,"./qbUtils":155,"webrtc-adapter":117}],153:[function(require,module,exports){"use strict";var qbFetch,qbFormData,config=require("./qbConfig"),Utils=require("./qbUtils");function ServiceProxy(){this.qbInst={config,session:null},this.reqCount=0}Utils.getEnv().node?(qbFetch=require("node-fetch"),qbFormData=require("form-data")):(qbFetch=fetch,qbFormData=FormData),ServiceProxy.prototype={_fetchingSettings:!1,_queue:[],setSession:function(session){this.qbInst.session=session},getSession:function(){return this.qbInst.session},handleResponse:function(error,response,next,retry){if(error){const errorMsg=error.message?JSON.stringify(error.message).toLowerCase():"";"function"==typeof config.on.sessionExpired&&401===error.code&&errorMsg.indexOf("session does not exist")>-1?config.on.sessionExpired(function(){next(error,response)},retry):next(error,null)}else config.addISOTime&&(response=Utils.injectISOTimes(response)),next(null,response)},startLogger:function(params){var clonedData;++this.reqCount,params.data&&params.data.file?(clonedData=JSON.parse(JSON.stringify(params.data))).file="...":clonedData=Utils.getEnv().nativescript?JSON.stringify(params.data):params.data,Utils.QBLog("[Request]["+this.reqCount+"]",(params.type||"GET")+" "+params.url,clonedData||"")},ajax:function(params,callback){if(this._fetchingSettings)this._queue.push([params,callback]);else{this.startLogger(params);var qbRequestBody,qbResponse,self=this,isGetOrHeadType=!params.type||"GET"===params.type||"HEAD"===params.type,qbSessionToken=self.qbInst&&self.qbInst.session&&self.qbInst.session.token,isQBRequest=-1===params.url.indexOf("s3.amazonaws.com"),isMultipartFormData=!1===params.contentType,qbDataType=params.dataType||"json",qbUrl=params.url,qbRequest={};qbRequest.method=params.type||"GET",params.data&&(qbRequestBody=_getBodyRequest(),isGetOrHeadType?qbUrl+="?"+qbRequestBody:qbRequest.body=qbRequestBody),isMultipartFormData||(qbRequest.headers={"Content-Type":params.contentType||"application/x-www-form-urlencoded; charset=UTF-8"}),isQBRequest&&(qbRequest.headers||(qbRequest.headers={}),qbRequest.headers["QB-OS"]=Utils.getOS(),qbRequest.headers["QB-SDK"]="JS "+config.version+" - Client",qbSessionToken&&(qbRequest.headers["QB-Token"]=qbSessionToken),params.url.indexOf(config.urls.account)>-1&&(qbRequest.headers["QB-Account-Key"]=config.creds.accountKey,this._fetchingSettings=!0)),params.headers&&Object.keys(params.headers).forEach(function(key){qbRequest.headers[key]=params.headers[key]}),config.timeout&&(qbRequest.timeout=config.timeout),qbFetch(qbUrl,qbRequest).then(function(response){if(qbResponse=response,"GET"===qbRequest.method||"POST"===qbRequest.method){var qbTokenExpirationDate=qbResponse.headers.get("qb-token-expirationdate"),headerHasToken=!(null==qbTokenExpirationDate);qbTokenExpirationDate=headerHasToken?qbTokenExpirationDate:new Date,self.qbInst.config.updateSessionExpirationDate(qbTokenExpirationDate,headerHasToken),Utils.QBLog("[Request][ajax]","header has token:",headerHasToken),Utils.QBLog("[Request][ajax]","updateSessionExpirationDate ... Set value: ",self.qbInst.config.qbTokenExpirationDate)}return"text"===qbDataType?response.text():response.json()},function(){return qbResponse={status:200}," "}).then(function(body){_requestCallback(null,qbResponse,body)},function(error){_requestCallback(error)}).catch(error=>{console.log("qbProxy fetch ... catch, error: ",error),_requestCallback(error)})}function _fixedEncodeURIComponent(str){return encodeURIComponent(str).replace(/[#$&+,/:;=?@\[\]]/g,function(c){return"%"+c.charCodeAt(0).toString(16)})}function _getBodyRequest(){var qbData,data=params.data;return isMultipartFormData?(qbData=new qbFormData,Object.keys(data).forEach(function(item){params.fileToCustomObject&&"file"===item?qbData.append(item,data[item].data,data[item].name):qbData.append(item,params.data[item])})):qbData=params.isNeedStringify?JSON.stringify(data):Object.keys(data).map(function(k){return Utils.isObject(data[k])?Object.keys(data[k]).map(function(v){return _fixedEncodeURIComponent(k)+"["+(Utils.isArray(data[k])?"":v)+"]="+_fixedEncodeURIComponent(data[k][v])}).sort().join("&"):_fixedEncodeURIComponent(k)+(Utils.isArray(data[k])?"[]":"")+"="+_fixedEncodeURIComponent(data[k])}).sort().join("&"),qbData}function _requestCallback(error,response,body){var responseMessage,responseBody,statusCode=response&&(response.status||response.statusCode);if(error||200!==statusCode&&201!==statusCode&&202!==statusCode){var errorMsg;try{errorMsg={code:response&&statusCode||error&&error.code,status:response&&response.headers&&response.headers.status||"error",message:body||error&&error.errno,detail:body&&body.errors||error&&error.syscall}}catch(e){errorMsg=error}responseBody=body||error||body.errors,responseMessage=Utils.getEnv().nativescript?JSON.stringify(responseBody):responseBody,Utils.QBLog("[Response]["+self.reqCount+"]","error",statusCode,responseMessage),self.handleResponse(errorMsg,null,callback,retry)}else responseBody=body&&" "!==body?body:"empty body",responseMessage=Utils.getEnv().nativescript?JSON.stringify(responseBody):responseBody,Utils.QBLog("[Response]["+self.reqCount+"]",responseMessage),self.handleResponse(null,body,callback,retry);if(self._fetchingSettings){self._fetchingSettings=!1;var sharedApiHost="api.quickblox.com",sharedChatHost="chat.quickblox.com";sharedApiHost=sharedApiHost.replace(/^https?:\/\//i,"").replace(/\/+$/,""),sharedChatHost=sharedChatHost.replace(/^https?:\/\//i,"").replace(/\/+$/,"");for(var RE_SHARED_API=new RegExp("^https?://"+sharedApiHost.replace(/\./g,"\\.")+"(?=[:/]|$)","i"),RE_SHARED_CHAT=new RegExp("^https?://"+sharedChatHost.replace(/\./g,"\\.")+"(?=[:/]|$)","i"),NEW_API_URL="https://"+(self.qbInst.config.endpoints.api||"").replace(/^https?:\/\//i,"").replace(/\/+$/,""),NEW_CHAT_URL="https://"+(self.qbInst.config.endpoints.chat||"").replace(/^https?:\/\//i,"").replace(/\/+$/,"");self._queue.length;){var args=self._queue.shift(),p=args&&args[0];if(p&&"string"==typeof p.url){var url=p.url,changed=!1;RE_SHARED_API.test(url)&&(url=url.replace(RE_SHARED_API,NEW_API_URL),changed=!0),RE_SHARED_CHAT.test(url)&&(url=url.replace(RE_SHARED_CHAT,NEW_CHAT_URL),changed=!0),changed&&(p.url=url)}self.ajax.apply(self,args)}}}function retry(session){session&&(self.setSession(session),self.ajax(params,callback))}}},module.exports=ServiceProxy},{"./qbConfig":151,"./qbUtils":155,"form-data":38,"node-fetch":59}],154:[function(require,module,exports){"use strict";var __stropheMod;try{__stropheMod=require("strophe.js/dist/strophe.umd.js")}catch(e){__stropheMod=require("strophe.js")}var Strophe=__stropheMod&&(__stropheMod.Strophe||__stropheMod.default||__stropheMod)||void 0;if(!Strophe||!Strophe.Connection)throw new Error("[QBChat] Strophe import failed: Connection class not found");var config=require("./qbConfig"),chatPRTCL=config.chatProtocol,Utils=require("./qbUtils");function Connection(onLogListenerCallback){var protocol=1===chatPRTCL.active?chatPRTCL.bosh:chatPRTCL.websocket,conn=new Strophe.Connection(protocol),onLogListener=config.debug?onLogListenerCallback:null,safeCallbackCall=function(message,data){if((onLogListener=config.debug?onLogListenerCallback:null)&&"function"==typeof onLogListener){var id=data&&data.id?data.id:"",innerHTML=data&&data.innerHTML?data.innerHTML:"",outerHTML=data&&data.outerHTML?data.outerHTML:"";Utils.safeCallbackCall(onLogListener,"[QBChat][QBStrophe]"+message+" id:"+id+" innerHTML: "+innerHTML+" outerHTML: "+outerHTML+JSON.stringify(data))}};return 1===chatPRTCL.active?(conn.xmlInput=function(data){if(data.childNodes[0])for(var i=0,len=data.childNodes.length;i<len;i++)Utils.QBLog("[QBChat]","RECV:",data.childNodes[i]),safeCallbackCall("RECV:",data.childNodes[i])},conn.xmlOutput=function(data){if(data.childNodes[0])for(var i=0,len=data.childNodes.length;i<len;i++)Utils.QBLog("[QBChat]","SENT:",data.childNodes[i]),safeCallbackCall("SENT",data.childNodes[i])}):(conn.xmlInput=function(data){Utils.QBLog("[QBChat]","RECV:",data),safeCallbackCall("RECV:",data);try{let errorElem=(new DOMParser).parseFromString(data,"text/xml").getElementsByTagName("error");if(errorElem.length>0){let conditionElem=errorElem[0].getElementsByTagName("condition");if(conditionElem.length>0){let disconnectCondition=conditionElem[0].textContent;console.log("Disconnect condition:",disconnectCondition),safeCallbackCall("DISCONNECTED CONDITION:",disconnectCondition)}}}catch(e){console.error("Error parsing XML input:",e)}},conn.xmlOutput=function(data){Utils.QBLog("[QBChat]","SENT:",data),safeCallbackCall("SENT",data)}),conn}module.exports=Connection},{"./qbConfig":151,"./qbUtils":155,"strophe.js":110,"strophe.js/dist/strophe.umd.js":110}],155:[function(require,module,exports){(function(global){(function(){"use strict";var config=require("./qbConfig"),unsupported="This function isn't supported outside of the browser (...yet)",isNativeScript="object"==typeof global&&(global.hasOwnProperty("android")||global.hasOwnProperty("NSObject")),isNode="undefined"==typeof window&&"object"==typeof exports&&!isNativeScript,isBrowser="undefined"!=typeof window;if(isNode)var fs=require("fs"),os=require("os");var ObjectId={machine:Math.floor(16777216*Math.random()).toString(16),pid:Math.floor(32767*Math.random()).toString(16),increment:0},Utils={getEnv:function(){return{nativescript:isNativeScript,browser:isBrowser,node:isNode}},_getOSInfoFromNodeJS:function(){return os.platform()},_getOSInfoFromBrowser:function(){return window.navigator.userAgent},_getOSInfoFromNativeScript:function(){return(global&&global.hasOwnProperty("android")?"Android":"iOS")+" - NativeScript"},getOS:function(){var platformInfo,self=this,osName="An unknown OS",OS_LIST=[{osName:"Windows",codeNames:["Windows","win32"]},{osName:"Linux",codeNames:["Linux","linux"]},{osName:"macOS",codeNames:["Mac OS","darwin"]}];if(self.getEnv().browser)platformInfo=self._getOSInfoFromBrowser();else if(self.getEnv().node)platformInfo=self._getOSInfoFromNodeJS();else if(self.getEnv().nativescript)return self._getOSInfoFromNativeScript();return OS_LIST.forEach(function(osInfo){osInfo.codeNames.forEach(function(codeName){-1!==platformInfo.indexOf(codeName)&&(osName=osInfo.osName)})}),osName},safeCallbackCall:function(){for(var listenerCall,listenerName=arguments[0].toString().split("(")[0].split(" ")[1],argumentsCopy=[],i=0;i<arguments.length;i++)argumentsCopy.push(arguments[i]);listenerCall=argumentsCopy.shift();try{listenerCall.apply(null,argumentsCopy)}catch(err){""===listenerName?console.error("Error: "+err):console.error("Error in listener "+listenerName+": "+err)}},randomNonce:function(){return Math.floor(1e4*Math.random())},unixTime:function(){return Math.floor(Date.now()/1e3)},getUrl:function(base,id){var resource=id?"/"+id:"";return"https://"+config.endpoints.api+"/"+base+resource+config.urls.type},formatUrl:function(base,id){var resource=id?"/"+id:"";return"https://"+config.endpoints.api+"/"+base+resource},isArray:function(arg){return"[object Array]"===Object.prototype.toString.call(arg)},isObject:function(arg){return"[object Object]"===Object.prototype.toString.call(arg)},getBsonObjectId:function(){var timestamp=this.unixTime().toString(16),increment=(ObjectId.increment++).toString(16);return increment>16777215&&(ObjectId.increment=0),"00000000".substr(0,8-timestamp.length)+timestamp+"000000".substr(0,6-ObjectId.machine.length)+ObjectId.machine+"0000".substr(0,4-ObjectId.pid.length)+ObjectId.pid+"000000".substr(0,6-increment.length)+increment},getCurrentTime:function(){return(new Date).toTimeString().split(" ")[0]},injectISOTimes:function(data){if(data.created_at)"number"==typeof data.created_at&&(data.iso_created_at=new Date(1e3*data.created_at).toISOString()),"number"==typeof data.updated_at&&(data.iso_updated_at=new Date(1e3*data.updated_at).toISOString());else if(data.items)for(var i=0,len=data.items.length;i<len;++i)"number"==typeof data.items[i].created_at&&(data.items[i].iso_created_at=new Date(1e3*data.items[i].created_at).toISOString()),"number"==typeof data.items[i].updated_at&&(data.items[i].iso_updated_at=new Date(1e3*data.items[i].updated_at).toISOString());return data},QBLog:function(){var argsArr=Array.prototype.slice.call(arguments);function containsPing(x){var needle="ping";try{if(null==x)return!1;if("string"==typeof x)return-1!==x.toLowerCase().indexOf(needle);if("number"==typeof x||"boolean"==typeof x)return!1;if("object"==typeof x){if("string"==typeof x.outerHTML){var oh=x.outerHTML.replace(/\s+/g," ").toLowerCase();if(-1!==oh.indexOf("urn:xmpp:sm:3")&&(/^<\s*r\b/.test(oh)||/^<\s*a\b/.test(oh)))return!0}for(var candidates=[x.textContent,x.innerHTML,x.outerHTML,x.nodeName,x.tagName,x.id],j=0;j<candidates.length;j++){var s=candidates[j];if("string"==typeof s&&-1!==s.toLowerCase().indexOf(needle))return!0}}}catch(_){}return!1}let shouldSuppressPing1=config&&!1===config.pingDebug,shouldSuppressPing2=argsArr.some(containsPing),shouldSuppressPing=shouldSuppressPing1&&shouldSuppressPing2;if(this.loggers)for(var i=0;i<this.loggers.length;++i)shouldSuppressPing||this.loggers[i](arguments);else{var logger;this.loggers=[];var consoleLoggerFunction=function(){return function(args){console.log.apply(console,Array.prototype.slice.call(args))}},fileLoggerFunction=function(){var logger=function(args){if(!fs)throw unsupported;for(var data=[],i=0;i<args.length;i++)data.push(JSON.stringify(args[i]));data=data.join(" ");var toLog="\n"+new Date+". "+data;fs.appendFile(config.debug.file,toLog,function(err){if(err)return console.error("Error while writing log to file. Error: "+err)})};return logger};if("object"==typeof config.debug){if("number"==typeof config.debug.mode)1==config.debug.mode?(logger=consoleLoggerFunction(),this.loggers.push(logger)):2==config.debug.mode&&(logger=fileLoggerFunction(),this.loggers.push(logger));else if("object"==typeof config.debug.mode){var self=this;config.debug.mode.forEach(function(mode){1===mode?(logger=consoleLoggerFunction(),self.loggers.push(logger)):2===mode&&(logger=fileLoggerFunction(),self.loggers.push(logger))})}}else"boolean"==typeof config.debug&&config.debug&&(logger=consoleLoggerFunction(),this.loggers.push(logger));if(this.loggers)for(var j=0;j<this.loggers.length;++j)shouldSuppressPing||this.loggers[j](arguments)}},isWebRTCAvailble:function(){var RTCPeerConnection=window.RTCPeerConnection,IceCandidate=window.RTCIceCandidate,SessionDescription=window.RTCSessionDescription,MediaDevices=window.navigator.mediaDevices;return Boolean(RTCPeerConnection)&&Boolean(IceCandidate)&&Boolean(SessionDescription)&&Boolean(MediaDevices)},getError:function(code,detail,moduleName){var errorMsg={code,status:"error",detail};switch(code){case 401:errorMsg.message="Unauthorized";break;case 403:errorMsg.message="Forbidden";break;case 408:errorMsg.message="Request Timeout";break;case 422:errorMsg.message="Unprocessable Entity";break;case 502:errorMsg.message="Bad Gateway";break;default:errorMsg.message="Unknown error"}return this.QBLog("["+moduleName+"]","Error:",detail),errorMsg},MergeArrayOfObjects:function(arrayTo,arrayFrom){var merged=JSON.parse(JSON.stringify(arrayTo));firstLevel:for(var i=0;i<arrayFrom.length;i++){for(var newItem=arrayFrom[i],j=0;j<merged.length;j++)if(newItem.user_id===merged[j].user_id){merged[j]=newItem;continue firstLevel}merged.push(newItem)}return merged},getTimeIntervalForCallBackMessage:function(){return 1e3*(void 0===config.callBackInterval?2:config.callBackInterval)}};module.exports=Utils}).call(this)}).call(this,void 0!==__webpack_require__.g?__webpack_require__.g:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./qbConfig":151,fs:26,os:87}]},{},[152])(152)}}]);