@sparkle-learning/core 0.0.39 → 0.0.42

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 (267) hide show
  1. package/dist/cjs/{auth.service-4b584cd7.js → PrivateRoute-074c584e.js} +30 -0
  2. package/dist/cjs/{sparkle-export-lessons_6.cjs.entry.js → header-mobile-collapse_61.cjs.entry.js} +11602 -2716
  3. package/dist/cjs/{icons-c61db785.js → icons-fda820af.js} +0 -0
  4. package/dist/cjs/index.cjs.js +5 -6
  5. package/dist/cjs/loader.cjs.js +1 -1
  6. package/dist/cjs/sparkle-code.cjs.entry.js +1 -1
  7. package/dist/cjs/sparkle-core.cjs.js +1 -1
  8. package/dist/cjs/sparkle-feedback.cjs.entry.js +1 -2
  9. package/dist/cjs/sparkle-menu-collapsible.cjs.entry.js +1 -1
  10. package/dist/cjs/sparkle-quiz-feedback_5.cjs.entry.js +117 -0
  11. package/dist/cjs/sparkle-quiz.cjs.entry.js +120 -0
  12. package/dist/cjs/student.service-2e58f237.js +78 -0
  13. package/dist/esm/{auth.service-9fb86455.js → PrivateRoute-c5441f35.js} +33 -4
  14. package/dist/esm/{animation-e0716b39.js → animation-12377cb3.js} +1 -1
  15. package/dist/esm/{auth.store-633e8414.js → auth.store-dba2c2da.js} +1 -1
  16. package/dist/esm/{facilitator.service-8fd435bf.js → facilitator.service-b0292f7f.js} +2 -2
  17. package/dist/esm/{feed.service-ace049e5.js → feed.service-8fbe4ce3.js} +3 -3
  18. package/dist/esm/{framework-delegate-e4f8013b.js → framework-delegate-3e634a5c.js} +1 -1
  19. package/dist/esm/{sparkle-export-lessons_6.entry.js → header-mobile-collapse_61.entry.js} +11501 -2670
  20. package/dist/esm/{helpers-03073fe4.js → helpers-bf0e23d6.js} +1 -1
  21. package/dist/esm/{httpService-61864992.js → httpService-7b75b095.js} +2 -2
  22. package/dist/esm/{icons-90b957ab.js → icons-1c794c74.js} +1 -1
  23. package/dist/esm/{index-b4b4e503.js → index-2b84cad2.js} +3 -3
  24. package/dist/esm/{index-a2d2941d.js → index-45fec1e7.js} +1 -1
  25. package/dist/esm/{index-37004831.js → index-5e8971ae.js} +1 -1
  26. package/dist/esm/{index-dedabca0.js → index-cded2d87.js} +2 -2
  27. package/dist/esm/{index.es-283fbd2e.js → index.es-e0c0f891.js} +1 -1
  28. package/dist/esm/index.js +5 -6
  29. package/dist/esm/{input-shims-cc3720a0.js → input-shims-671d8d9f.js} +2 -2
  30. package/dist/esm/ion-accordion.entry.js +1 -1
  31. package/dist/esm/ion-action-sheet_4.entry.js +5 -5
  32. package/dist/esm/ion-app.entry.js +3 -3
  33. package/dist/esm/ion-back-button.entry.js +1 -1
  34. package/dist/esm/ion-breadcrumb.entry.js +1 -1
  35. package/dist/esm/ion-content_2.entry.js +2 -2
  36. package/dist/esm/ion-datetime-button.entry.js +1 -1
  37. package/dist/esm/ion-datetime.entry.js +1 -1
  38. package/dist/esm/ion-fab-button.entry.js +1 -1
  39. package/dist/esm/ion-footer.entry.js +2 -2
  40. package/dist/esm/ion-img.entry.js +1 -1
  41. package/dist/esm/ion-infinite-scroll.entry.js +2 -2
  42. package/dist/esm/ion-item-options.entry.js +1 -1
  43. package/dist/esm/ion-item-sliding.entry.js +2 -2
  44. package/dist/esm/ion-loading.entry.js +3 -3
  45. package/dist/esm/ion-menu-button.entry.js +4 -4
  46. package/dist/esm/ion-menu-toggle.entry.js +4 -4
  47. package/dist/esm/ion-menu.entry.js +4 -4
  48. package/dist/esm/ion-modal.entry.js +6 -6
  49. package/dist/esm/ion-nav.entry.js +4 -4
  50. package/dist/esm/ion-picker-column-internal_2.entry.js +1 -1
  51. package/dist/esm/ion-picker-column.entry.js +1 -1
  52. package/dist/esm/ion-picker.entry.js +3 -3
  53. package/dist/esm/ion-progress-bar.entry.js +1 -1
  54. package/dist/esm/ion-refresher.entry.js +3 -3
  55. package/dist/esm/ion-reorder-group.entry.js +2 -2
  56. package/dist/esm/ion-router-outlet.entry.js +4 -4
  57. package/dist/esm/ion-router.entry.js +1 -1
  58. package/dist/esm/ion-searchbar.entry.js +1 -1
  59. package/dist/esm/ion-segment-button.entry.js +1 -1
  60. package/dist/esm/ion-segment.entry.js +1 -1
  61. package/dist/esm/ion-select_2.entry.js +2 -2
  62. package/dist/esm/ion-slides.entry.js +1 -1
  63. package/dist/esm/ion-tab.entry.js +2 -2
  64. package/dist/esm/ion-textarea.entry.js +1 -1
  65. package/dist/esm/ion-toast.entry.js +3 -3
  66. package/dist/esm/ion-toggle.entry.js +1 -1
  67. package/dist/esm/ion-virtual-scroll.entry.js +1 -1
  68. package/dist/esm/{ios.transition-3a6179bb.js → ios.transition-131d64fe.js} +3 -3
  69. package/dist/esm/loader.js +1 -1
  70. package/dist/esm/{md.transition-cff16bf3.js → md.transition-f6126011.js} +3 -3
  71. package/dist/esm/{menu-toggle-util-59241733.js → menu-toggle-util-bace8ae6.js} +1 -1
  72. package/dist/esm/{overlays-bdd9344a.js → overlays-3b4dca92.js} +2 -2
  73. package/dist/esm/{purify-7085b248.js → purify-85bfcc69.js} +1 -1
  74. package/dist/esm/sparkle-animation-player.entry.js +1 -1
  75. package/dist/esm/sparkle-code.entry.js +1 -1
  76. package/dist/esm/sparkle-core.js +1 -1
  77. package/dist/esm/sparkle-facilitator-notes-form.entry.js +5 -5
  78. package/dist/esm/sparkle-feed-post.entry.js +1 -1
  79. package/dist/esm/sparkle-feedback.entry.js +5 -6
  80. package/dist/esm/sparkle-goal-form.entry.js +6 -6
  81. package/dist/esm/sparkle-menu-collapsible.entry.js +1 -1
  82. package/dist/esm/sparkle-quiz-feedback_5.entry.js +109 -0
  83. package/dist/esm/sparkle-quiz.entry.js +116 -0
  84. package/dist/esm/{status-tap-463d0f87.js → status-tap-dde52787.js} +2 -2
  85. package/dist/esm/{student.service-e6eb1f99.js → student.service-0746418b.js} +19 -3
  86. package/dist/esm/{swipe-back-f8765ac9.js → swipe-back-7847a0c1.js} +1 -1
  87. package/dist/esm/{util-a831d09d.js → util-6ef753e9.js} +1 -1
  88. package/dist/node_modules/@sparkle-learning/components/dist/collection/components/button/button.css +49 -0
  89. package/dist/node_modules/@sparkle-learning/components/dist/collection/components/cards/card/card.css +208 -0
  90. package/dist/node_modules/@sparkle-learning/components/dist/collection/components/cards/cards.css +31 -0
  91. package/dist/node_modules/@sparkle-learning/components/dist/collection/components/code/code.css +245 -0
  92. package/dist/node_modules/@sparkle-learning/components/dist/collection/components/dropdown/dropdown.css +115 -0
  93. package/dist/node_modules/@sparkle-learning/components/dist/collection/components/header/header-mobile-collapse/header-mobile-collapse.css +255 -0
  94. package/dist/node_modules/@sparkle-learning/components/dist/collection/components/header/header.css +232 -0
  95. package/dist/node_modules/@sparkle-learning/components/dist/collection/components/menu/collapsible/collapsible.css +3 -0
  96. package/dist/node_modules/@sparkle-learning/components/dist/collection/components/menu/menu-toggle/menu-toggle.css +25 -0
  97. package/dist/node_modules/@sparkle-learning/components/dist/collection/components/menu/menu.css +71 -0
  98. package/dist/node_modules/@sparkle-learning/components/dist/collection/components/nav/nav.css +194 -0
  99. package/dist/node_modules/@sparkle-learning/components/dist/collection/components/notfound-page/notfound-page.css +4 -0
  100. package/dist/node_modules/@sparkle-learning/components/dist/collection/components/overlay/overlay.css +67 -0
  101. package/dist/node_modules/@sparkle-learning/components/dist/collection/components/page-footer/page-footer.css +18 -0
  102. package/dist/node_modules/@sparkle-learning/components/dist/collection/components/pagination/pagination.css +89 -0
  103. package/dist/node_modules/@sparkle-learning/components/dist/collection/components/select/select.css +52 -0
  104. package/dist/node_modules/@sparkle-learning/components/dist/collection/components/sidebar/sidebar.css +98 -0
  105. package/dist/node_modules/@sparkle-learning/components/dist/collection/components/sparkle-lower-content-nav/sparkle-lower-content-nav.css +8 -0
  106. package/dist/node_modules/@sparkle-learning/components/dist/collection/components/table-of-contents/table-of-contents.css +37 -0
  107. package/dist/node_modules/@sparkle-learning/components/dist/collection/components/tabs/tabs.css +64 -0
  108. package/dist/sparkle-core/index.esm.js +1 -1
  109. package/dist/sparkle-core/{p-539bf742.js → p-00d10dc9.js} +2 -2
  110. package/dist/sparkle-core/{p-b9933822.js → p-05c032dd.js} +1 -1
  111. package/dist/sparkle-core/{p-dabc80c4.entry.js → p-0664370b.entry.js} +1 -1
  112. package/dist/sparkle-core/p-077c732b.js +4 -0
  113. package/dist/sparkle-core/{p-c278db5f.entry.js → p-0ad5c123.entry.js} +1 -1
  114. package/dist/sparkle-core/{p-b9b1d4da.entry.js → p-0afa3a4d.entry.js} +1 -1
  115. package/dist/sparkle-core/{p-285ab4ed.entry.js → p-0c3f3ea6.entry.js} +1 -1
  116. package/dist/sparkle-core/{p-727e1c28.entry.js → p-0f1c5899.entry.js} +1 -1
  117. package/dist/sparkle-core/{p-64e814b9.entry.js → p-11356b03.entry.js} +1 -1
  118. package/dist/sparkle-core/{p-b5ec8fb0.entry.js → p-11a6c175.entry.js} +1 -1
  119. package/dist/sparkle-core/p-12dd96d7.js +4 -0
  120. package/dist/sparkle-core/{p-a85598ad.js → p-1d4c7c11.js} +1 -1
  121. package/dist/sparkle-core/{p-c8fe45df.entry.js → p-1e125ca5.entry.js} +1 -1
  122. package/dist/sparkle-core/{p-cab3da3c.entry.js → p-1e4f65ee.entry.js} +1 -1
  123. package/dist/sparkle-core/{p-405f7c58.js → p-2033cd86.js} +2 -2
  124. package/dist/sparkle-core/p-23aca7ca.js +4 -0
  125. package/dist/sparkle-core/{p-e65c72cc.entry.js → p-24cb9a33.entry.js} +1 -1
  126. package/dist/sparkle-core/{p-014b5707.entry.js → p-2c1ca854.entry.js} +1 -1
  127. package/dist/sparkle-core/{p-340754ed.js → p-2f569553.js} +1 -1
  128. package/dist/sparkle-core/{p-2e2b813c.js → p-2ff67662.js} +2 -2
  129. package/dist/sparkle-core/{p-0c0f8acd.entry.js → p-30b810d1.entry.js} +1 -1
  130. package/dist/sparkle-core/{p-b236d258.entry.js → p-377b04c2.entry.js} +1 -1
  131. package/dist/sparkle-core/{p-fde382f0.entry.js → p-39712c56.entry.js} +1 -1
  132. package/dist/sparkle-core/{p-be28346b.js → p-3de0e00c.js} +1 -1
  133. package/dist/sparkle-core/p-462bffba.js +1 -0
  134. package/dist/sparkle-core/{p-3f85e1ca.js → p-48f72e63.js} +2 -2
  135. package/dist/sparkle-core/{p-6f0545b3.entry.js → p-54dd894f.entry.js} +1 -1
  136. package/dist/sparkle-core/{p-ce94efdb.entry.js → p-564e64fc.entry.js} +1 -1
  137. package/dist/sparkle-core/{p-db8387eb.entry.js → p-58e4bbe5.entry.js} +1 -1
  138. package/dist/sparkle-core/{p-ca4c8a10.js → p-5cad23f1.js} +1 -1
  139. package/dist/sparkle-core/p-5efc6566.js +1 -0
  140. package/dist/sparkle-core/{p-c9cd4ff1.js → p-600cf6a3.js} +1 -1
  141. package/dist/sparkle-core/{p-2e035338.entry.js → p-641bfc92.entry.js} +1 -1
  142. package/dist/sparkle-core/{p-b4bc8b02.entry.js → p-6faa194c.entry.js} +1 -1
  143. package/dist/sparkle-core/{p-2f10208d.entry.js → p-6ffd2420.entry.js} +1 -1
  144. package/dist/sparkle-core/p-73721c84.js +4 -0
  145. package/dist/sparkle-core/{p-ed9f48c4.entry.js → p-74864276.entry.js} +1 -1
  146. package/dist/sparkle-core/p-80d6b0e6.entry.js +1 -0
  147. package/dist/sparkle-core/p-8492a765.entry.js +1 -0
  148. package/dist/sparkle-core/{p-a019ad0c.js → p-86ed13f0.js} +1 -1
  149. package/dist/sparkle-core/{p-4ae75caa.entry.js → p-894ff7e6.entry.js} +1 -1
  150. package/dist/sparkle-core/{p-5519d283.entry.js → p-9289cdbc.entry.js} +1 -1
  151. package/dist/sparkle-core/{p-4bd4dab2.js → p-935e7cfc.js} +1 -1
  152. package/dist/sparkle-core/{p-25e556cc.entry.js → p-957715c5.entry.js} +1 -1
  153. package/dist/sparkle-core/{p-b4b01fa2.entry.js → p-9abbd715.entry.js} +1 -1
  154. package/dist/sparkle-core/{p-e7568d4b.js → p-9d894ed4.js} +1 -1
  155. package/dist/sparkle-core/{p-4320dac0.entry.js → p-9ebf0537.entry.js} +1 -1
  156. package/dist/sparkle-core/p-a49ab4e8.entry.js +1 -0
  157. package/dist/sparkle-core/{p-93e74f1b.entry.js → p-af3cc111.entry.js} +1 -1
  158. package/dist/sparkle-core/{p-5fc26938.js → p-b0603d19.js} +1 -1
  159. package/dist/sparkle-core/{p-317037de.entry.js → p-b3f375fb.entry.js} +1 -1
  160. package/dist/sparkle-core/p-b4408842.entry.js +352 -0
  161. package/dist/sparkle-core/{p-2fba9a3a.entry.js → p-b5f3e1bf.entry.js} +1 -1
  162. package/dist/sparkle-core/{p-82ad4e7c.entry.js → p-b96f3c84.entry.js} +2 -2
  163. package/dist/sparkle-core/{p-ad102371.js → p-bd80ff43.js} +1 -1
  164. package/dist/sparkle-core/{p-f0cf4a8f.entry.js → p-be64105c.entry.js} +1 -1
  165. package/dist/sparkle-core/{p-f4b0b6a4.entry.js → p-c0533c23.entry.js} +1 -1
  166. package/dist/sparkle-core/p-c3cadfc6.entry.js +1 -0
  167. package/dist/sparkle-core/{p-2d4a5ddf.entry.js → p-c60b29bd.entry.js} +2 -2
  168. package/dist/sparkle-core/{p-56a2e8a2.js → p-cabe9139.js} +1 -1
  169. package/dist/sparkle-core/{p-0bb0cf41.entry.js → p-cabfbf22.entry.js} +1 -1
  170. package/dist/sparkle-core/{p-66a85393.entry.js → p-ce4b22f7.entry.js} +1 -1
  171. package/dist/sparkle-core/{p-17eb4633.js → p-d68092b7.js} +1 -1
  172. package/dist/sparkle-core/{p-0ea2518d.entry.js → p-de4deb61.entry.js} +1 -1
  173. package/dist/sparkle-core/{p-1f0b3ff9.entry.js → p-e686d8b5.entry.js} +1 -1
  174. package/dist/sparkle-core/{p-08d97c59.entry.js → p-e77d982d.entry.js} +1 -1
  175. package/dist/sparkle-core/{p-44f813b7.entry.js → p-e863bf1d.entry.js} +1 -1
  176. package/dist/sparkle-core/{p-63f69cdc.entry.js → p-ebd4354b.entry.js} +1 -1
  177. package/dist/sparkle-core/{p-fc965b88.entry.js → p-ef4edc48.entry.js} +1 -1
  178. package/dist/sparkle-core/{p-c2bbaf55.entry.js → p-fb0ca75e.entry.js} +1 -1
  179. package/dist/sparkle-core/{p-b83444c7.entry.js → p-fb757951.entry.js} +1 -1
  180. package/dist/sparkle-core/{p-d81a0680.js → p-fbccd30c.js} +1 -1
  181. package/dist/sparkle-core/sparkle-core.esm.js +1 -1
  182. package/package.json +2 -2
  183. package/dist/cjs/PrivateRoute-4abc9d29.js +0 -35
  184. package/dist/cjs/dom-utils-b8befdd5.js +0 -63
  185. package/dist/cjs/header-mobile-collapse.cjs.entry.js +0 -90
  186. package/dist/cjs/index-70e63f5b.js +0 -3071
  187. package/dist/cjs/injectHistory-7206bbb9.js +0 -9
  188. package/dist/cjs/ion-avatar.cjs.entry.js +0 -25
  189. package/dist/cjs/ion-button.cjs.entry.js +0 -129
  190. package/dist/cjs/ion-card_2.cjs.entry.js +0 -91
  191. package/dist/cjs/ion-checkbox_4.cjs.entry.js +0 -360
  192. package/dist/cjs/ion-col_3.cjs.entry.js +0 -159
  193. package/dist/cjs/ion-icon_13.cjs.entry.js +0 -1505
  194. package/dist/cjs/ion-input_2.cjs.entry.js +0 -313
  195. package/dist/cjs/ion-label_2.cjs.entry.js +0 -126
  196. package/dist/cjs/ion-spinner.cjs.entry.js +0 -64
  197. package/dist/cjs/match-path-84c9f7ca.js +0 -511
  198. package/dist/cjs/sparkle-card_3.cjs.entry.js +0 -91
  199. package/dist/cjs/sparkle-course-root.cjs.entry.js +0 -146
  200. package/dist/cjs/sparkle-dropdown.cjs.entry.js +0 -61
  201. package/dist/cjs/sparkle-facilitator-header_19.cjs.entry.js +0 -2130
  202. package/dist/cjs/sparkle-goal-progress.cjs.entry.js +0 -19
  203. package/dist/cjs/sparkle-gww-item.cjs.entry.js +0 -74
  204. package/dist/cjs/sparkle-menu-toggle_3.cjs.entry.js +0 -236
  205. package/dist/cjs/sparkle-validation-error.cjs.entry.js +0 -21
  206. package/dist/cjs/stencil-router-redirect.cjs.entry.js +0 -32
  207. package/dist/cjs/student.service-d48f1c99.js +0 -61
  208. package/dist/cjs/user.store-8a049c4e.js +0 -21
  209. package/dist/esm/PrivateRoute-7b526801.js +0 -33
  210. package/dist/esm/dom-utils-109a7d75.js +0 -55
  211. package/dist/esm/header-mobile-collapse.entry.js +0 -86
  212. package/dist/esm/index-f9b9ba5d.js +0 -3067
  213. package/dist/esm/injectHistory-968f626d.js +0 -7
  214. package/dist/esm/ion-avatar.entry.js +0 -21
  215. package/dist/esm/ion-button.entry.js +0 -125
  216. package/dist/esm/ion-card_2.entry.js +0 -86
  217. package/dist/esm/ion-checkbox_4.entry.js +0 -353
  218. package/dist/esm/ion-col_3.entry.js +0 -153
  219. package/dist/esm/ion-icon_13.entry.js +0 -1489
  220. package/dist/esm/ion-input_2.entry.js +0 -308
  221. package/dist/esm/ion-label_2.entry.js +0 -121
  222. package/dist/esm/ion-spinner.entry.js +0 -60
  223. package/dist/esm/match-path-36fdf5c7.js +0 -499
  224. package/dist/esm/sparkle-card_3.entry.js +0 -85
  225. package/dist/esm/sparkle-course-root.entry.js +0 -142
  226. package/dist/esm/sparkle-dropdown.entry.js +0 -57
  227. package/dist/esm/sparkle-facilitator-header_19.entry.js +0 -2108
  228. package/dist/esm/sparkle-goal-progress.entry.js +0 -15
  229. package/dist/esm/sparkle-gww-item.entry.js +0 -70
  230. package/dist/esm/sparkle-menu-toggle_3.entry.js +0 -230
  231. package/dist/esm/sparkle-validation-error.entry.js +0 -17
  232. package/dist/esm/stencil-router-redirect.entry.js +0 -28
  233. package/dist/esm/user.store-b8645067.js +0 -19
  234. package/dist/sparkle-core/p-03585916.js +0 -1
  235. package/dist/sparkle-core/p-1019ebc3.js +0 -1
  236. package/dist/sparkle-core/p-1728ead7.js +0 -1
  237. package/dist/sparkle-core/p-32762a44.entry.js +0 -1
  238. package/dist/sparkle-core/p-3bc68dd0.js +0 -1
  239. package/dist/sparkle-core/p-3c133235.entry.js +0 -1
  240. package/dist/sparkle-core/p-46869031.entry.js +0 -1
  241. package/dist/sparkle-core/p-4a5f2b2b.js +0 -1
  242. package/dist/sparkle-core/p-53bcbd1d.js +0 -1
  243. package/dist/sparkle-core/p-54ada5e3.entry.js +0 -1
  244. package/dist/sparkle-core/p-554da5b8.entry.js +0 -1
  245. package/dist/sparkle-core/p-5da2d95a.entry.js +0 -1
  246. package/dist/sparkle-core/p-6b05a1d3.entry.js +0 -1
  247. package/dist/sparkle-core/p-6ea246fe.js +0 -4
  248. package/dist/sparkle-core/p-6ed0236e.entry.js +0 -1
  249. package/dist/sparkle-core/p-7f25366a.entry.js +0 -1
  250. package/dist/sparkle-core/p-91accfc1.js +0 -1
  251. package/dist/sparkle-core/p-a5c5da9a.entry.js +0 -1
  252. package/dist/sparkle-core/p-a8a77bec.entry.js +0 -1
  253. package/dist/sparkle-core/p-c4af184b.entry.js +0 -1
  254. package/dist/sparkle-core/p-c71cbbf7.entry.js +0 -1
  255. package/dist/sparkle-core/p-c8c73fa7.js +0 -4
  256. package/dist/sparkle-core/p-cd832fbf.entry.js +0 -1
  257. package/dist/sparkle-core/p-d0ac5f17.js +0 -1
  258. package/dist/sparkle-core/p-d1fcbfc2.js +0 -4
  259. package/dist/sparkle-core/p-d432d3ac.entry.js +0 -1
  260. package/dist/sparkle-core/p-d969f7d0.entry.js +0 -348
  261. package/dist/sparkle-core/p-dca90a55.entry.js +0 -4
  262. package/dist/sparkle-core/p-dd2e7f84.js +0 -4
  263. package/dist/sparkle-core/p-e0429a19.entry.js +0 -1
  264. package/dist/sparkle-core/p-e7066c64.entry.js +0 -1
  265. package/dist/sparkle-core/p-eb40a191.entry.js +0 -1
  266. package/dist/sparkle-core/p-ecdea569.entry.js +0 -1
  267. package/dist/sparkle-core/p-ef6c2352.entry.js +0 -1
@@ -1,3071 +0,0 @@
1
- 'use strict';
2
-
3
- const environmentConfig_service = require('./environment-config.service-0e02b049.js');
4
- const auth_store = require('./auth.store-1e630a7d.js');
5
- const index = require('./index-51e8292e.js');
6
- const util = require('./util-d383acb8.js');
7
-
8
- // Licensed to the .NET Foundation under one or more agreements.
9
- // The .NET Foundation licenses this file to you under the MIT license.
10
- /** Error thrown when an HTTP request fails. */
11
- class HttpError extends Error {
12
- /** Constructs a new instance of {@link @microsoft/signalr.HttpError}.
13
- *
14
- * @param {string} errorMessage A descriptive error message.
15
- * @param {number} statusCode The HTTP status code represented by this error.
16
- */
17
- constructor(errorMessage, statusCode) {
18
- const trueProto = new.target.prototype;
19
- super(`${errorMessage}: Status code '${statusCode}'`);
20
- this.statusCode = statusCode;
21
- // Workaround issue in Typescript compiler
22
- // https://github.com/Microsoft/TypeScript/issues/13965#issuecomment-278570200
23
- this.__proto__ = trueProto;
24
- }
25
- }
26
- /** Error thrown when a timeout elapses. */
27
- class TimeoutError extends Error {
28
- /** Constructs a new instance of {@link @microsoft/signalr.TimeoutError}.
29
- *
30
- * @param {string} errorMessage A descriptive error message.
31
- */
32
- constructor(errorMessage = "A timeout occurred.") {
33
- const trueProto = new.target.prototype;
34
- super(errorMessage);
35
- // Workaround issue in Typescript compiler
36
- // https://github.com/Microsoft/TypeScript/issues/13965#issuecomment-278570200
37
- this.__proto__ = trueProto;
38
- }
39
- }
40
- /** Error thrown when an action is aborted. */
41
- class AbortError extends Error {
42
- /** Constructs a new instance of {@link AbortError}.
43
- *
44
- * @param {string} errorMessage A descriptive error message.
45
- */
46
- constructor(errorMessage = "An abort occurred.") {
47
- const trueProto = new.target.prototype;
48
- super(errorMessage);
49
- // Workaround issue in Typescript compiler
50
- // https://github.com/Microsoft/TypeScript/issues/13965#issuecomment-278570200
51
- this.__proto__ = trueProto;
52
- }
53
- }
54
- /** Error thrown when the selected transport is unsupported by the browser. */
55
- /** @private */
56
- class UnsupportedTransportError extends Error {
57
- /** Constructs a new instance of {@link @microsoft/signalr.UnsupportedTransportError}.
58
- *
59
- * @param {string} message A descriptive error message.
60
- * @param {HttpTransportType} transport The {@link @microsoft/signalr.HttpTransportType} this error occured on.
61
- */
62
- constructor(message, transport) {
63
- const trueProto = new.target.prototype;
64
- super(message);
65
- this.transport = transport;
66
- this.errorType = 'UnsupportedTransportError';
67
- // Workaround issue in Typescript compiler
68
- // https://github.com/Microsoft/TypeScript/issues/13965#issuecomment-278570200
69
- this.__proto__ = trueProto;
70
- }
71
- }
72
- /** Error thrown when the selected transport is disabled by the browser. */
73
- /** @private */
74
- class DisabledTransportError extends Error {
75
- /** Constructs a new instance of {@link @microsoft/signalr.DisabledTransportError}.
76
- *
77
- * @param {string} message A descriptive error message.
78
- * @param {HttpTransportType} transport The {@link @microsoft/signalr.HttpTransportType} this error occured on.
79
- */
80
- constructor(message, transport) {
81
- const trueProto = new.target.prototype;
82
- super(message);
83
- this.transport = transport;
84
- this.errorType = 'DisabledTransportError';
85
- // Workaround issue in Typescript compiler
86
- // https://github.com/Microsoft/TypeScript/issues/13965#issuecomment-278570200
87
- this.__proto__ = trueProto;
88
- }
89
- }
90
- /** Error thrown when the selected transport cannot be started. */
91
- /** @private */
92
- class FailedToStartTransportError extends Error {
93
- /** Constructs a new instance of {@link @microsoft/signalr.FailedToStartTransportError}.
94
- *
95
- * @param {string} message A descriptive error message.
96
- * @param {HttpTransportType} transport The {@link @microsoft/signalr.HttpTransportType} this error occured on.
97
- */
98
- constructor(message, transport) {
99
- const trueProto = new.target.prototype;
100
- super(message);
101
- this.transport = transport;
102
- this.errorType = 'FailedToStartTransportError';
103
- // Workaround issue in Typescript compiler
104
- // https://github.com/Microsoft/TypeScript/issues/13965#issuecomment-278570200
105
- this.__proto__ = trueProto;
106
- }
107
- }
108
- /** Error thrown when the negotiation with the server failed to complete. */
109
- /** @private */
110
- class FailedToNegotiateWithServerError extends Error {
111
- /** Constructs a new instance of {@link @microsoft/signalr.FailedToNegotiateWithServerError}.
112
- *
113
- * @param {string} message A descriptive error message.
114
- */
115
- constructor(message) {
116
- const trueProto = new.target.prototype;
117
- super(message);
118
- this.errorType = 'FailedToNegotiateWithServerError';
119
- // Workaround issue in Typescript compiler
120
- // https://github.com/Microsoft/TypeScript/issues/13965#issuecomment-278570200
121
- this.__proto__ = trueProto;
122
- }
123
- }
124
- /** Error thrown when multiple errors have occured. */
125
- /** @private */
126
- class AggregateErrors extends Error {
127
- /** Constructs a new instance of {@link @microsoft/signalr.AggregateErrors}.
128
- *
129
- * @param {string} message A descriptive error message.
130
- * @param {Error[]} innerErrors The collection of errors this error is aggregating.
131
- */
132
- constructor(message, innerErrors) {
133
- const trueProto = new.target.prototype;
134
- super(message);
135
- this.innerErrors = innerErrors;
136
- // Workaround issue in Typescript compiler
137
- // https://github.com/Microsoft/TypeScript/issues/13965#issuecomment-278570200
138
- this.__proto__ = trueProto;
139
- }
140
- }
141
-
142
- // Licensed to the .NET Foundation under one or more agreements.
143
- // The .NET Foundation licenses this file to you under the MIT license.
144
- /** Represents an HTTP response. */
145
- class HttpResponse {
146
- constructor(statusCode, statusText, content) {
147
- this.statusCode = statusCode;
148
- this.statusText = statusText;
149
- this.content = content;
150
- }
151
- }
152
- /** Abstraction over an HTTP client.
153
- *
154
- * This class provides an abstraction over an HTTP client so that a different implementation can be provided on different platforms.
155
- */
156
- class HttpClient {
157
- get(url, options) {
158
- return this.send({
159
- ...options,
160
- method: "GET",
161
- url,
162
- });
163
- }
164
- post(url, options) {
165
- return this.send({
166
- ...options,
167
- method: "POST",
168
- url,
169
- });
170
- }
171
- delete(url, options) {
172
- return this.send({
173
- ...options,
174
- method: "DELETE",
175
- url,
176
- });
177
- }
178
- /** Gets all cookies that apply to the specified URL.
179
- *
180
- * @param url The URL that the cookies are valid for.
181
- * @returns {string} A string containing all the key-value cookie pairs for the specified URL.
182
- */
183
- // @ts-ignore
184
- getCookieString(url) {
185
- return "";
186
- }
187
- }
188
-
189
- // Licensed to the .NET Foundation under one or more agreements.
190
- // The .NET Foundation licenses this file to you under the MIT license.
191
- // These values are designed to match the ASP.NET Log Levels since that's the pattern we're emulating here.
192
- /** Indicates the severity of a log message.
193
- *
194
- * Log Levels are ordered in increasing severity. So `Debug` is more severe than `Trace`, etc.
195
- */
196
- var LogLevel;
197
- (function (LogLevel) {
198
- /** Log level for very low severity diagnostic messages. */
199
- LogLevel[LogLevel["Trace"] = 0] = "Trace";
200
- /** Log level for low severity diagnostic messages. */
201
- LogLevel[LogLevel["Debug"] = 1] = "Debug";
202
- /** Log level for informational diagnostic messages. */
203
- LogLevel[LogLevel["Information"] = 2] = "Information";
204
- /** Log level for diagnostic messages that indicate a non-fatal problem. */
205
- LogLevel[LogLevel["Warning"] = 3] = "Warning";
206
- /** Log level for diagnostic messages that indicate a failure in the current operation. */
207
- LogLevel[LogLevel["Error"] = 4] = "Error";
208
- /** Log level for diagnostic messages that indicate a failure that will terminate the entire application. */
209
- LogLevel[LogLevel["Critical"] = 5] = "Critical";
210
- /** The highest possible log level. Used when configuring logging to indicate that no log messages should be emitted. */
211
- LogLevel[LogLevel["None"] = 6] = "None";
212
- })(LogLevel || (LogLevel = {}));
213
-
214
- // Licensed to the .NET Foundation under one or more agreements.
215
- // The .NET Foundation licenses this file to you under the MIT license.
216
- /** A logger that does nothing when log messages are sent to it. */
217
- class NullLogger {
218
- constructor() { }
219
- /** @inheritDoc */
220
- // eslint-disable-next-line
221
- log(_logLevel, _message) {
222
- }
223
- }
224
- /** The singleton instance of the {@link @microsoft/signalr.NullLogger}. */
225
- NullLogger.instance = new NullLogger();
226
-
227
- // Licensed to the .NET Foundation under one or more agreements.
228
- // Version token that will be replaced by the prepack command
229
- /** The version of the SignalR client. */
230
- const VERSION = "6.0.3";
231
- /** @private */
232
- class Arg {
233
- static isRequired(val, name) {
234
- if (val === null || val === undefined) {
235
- throw new Error(`The '${name}' argument is required.`);
236
- }
237
- }
238
- static isNotEmpty(val, name) {
239
- if (!val || val.match(/^\s*$/)) {
240
- throw new Error(`The '${name}' argument should not be empty.`);
241
- }
242
- }
243
- static isIn(val, values, name) {
244
- // TypeScript enums have keys for **both** the name and the value of each enum member on the type itself.
245
- if (!(val in values)) {
246
- throw new Error(`Unknown ${name} value: ${val}.`);
247
- }
248
- }
249
- }
250
- /** @private */
251
- class Platform {
252
- // react-native has a window but no document so we should check both
253
- static get isBrowser() {
254
- return typeof window === "object" && typeof window.document === "object";
255
- }
256
- // WebWorkers don't have a window object so the isBrowser check would fail
257
- static get isWebWorker() {
258
- return typeof self === "object" && "importScripts" in self;
259
- }
260
- // react-native has a window but no document
261
- static get isReactNative() {
262
- return typeof window === "object" && typeof window.document === "undefined";
263
- }
264
- // Node apps shouldn't have a window object, but WebWorkers don't either
265
- // so we need to check for both WebWorker and window
266
- static get isNode() {
267
- return !this.isBrowser && !this.isWebWorker && !this.isReactNative;
268
- }
269
- }
270
- /** @private */
271
- function getDataDetail(data, includeContent) {
272
- let detail = "";
273
- if (isArrayBuffer(data)) {
274
- detail = `Binary data of length ${data.byteLength}`;
275
- if (includeContent) {
276
- detail += `. Content: '${formatArrayBuffer(data)}'`;
277
- }
278
- }
279
- else if (typeof data === "string") {
280
- detail = `String data of length ${data.length}`;
281
- if (includeContent) {
282
- detail += `. Content: '${data}'`;
283
- }
284
- }
285
- return detail;
286
- }
287
- /** @private */
288
- function formatArrayBuffer(data) {
289
- const view = new Uint8Array(data);
290
- // Uint8Array.map only supports returning another Uint8Array?
291
- let str = "";
292
- view.forEach((num) => {
293
- const pad = num < 16 ? "0" : "";
294
- str += `0x${pad}${num.toString(16)} `;
295
- });
296
- // Trim of trailing space.
297
- return str.substr(0, str.length - 1);
298
- }
299
- // Also in signalr-protocol-msgpack/Utils.ts
300
- /** @private */
301
- function isArrayBuffer(val) {
302
- return val && typeof ArrayBuffer !== "undefined" &&
303
- (val instanceof ArrayBuffer ||
304
- // Sometimes we get an ArrayBuffer that doesn't satisfy instanceof
305
- (val.constructor && val.constructor.name === "ArrayBuffer"));
306
- }
307
- /** @private */
308
- async function sendMessage(logger, transportName, httpClient, url, accessTokenFactory, content, options) {
309
- let headers = {};
310
- if (accessTokenFactory) {
311
- const token = await accessTokenFactory();
312
- if (token) {
313
- headers = {
314
- ["Authorization"]: `Bearer ${token}`,
315
- };
316
- }
317
- }
318
- const [name, value] = getUserAgentHeader();
319
- headers[name] = value;
320
- logger.log(LogLevel.Trace, `(${transportName} transport) sending data. ${getDataDetail(content, options.logMessageContent)}.`);
321
- const responseType = isArrayBuffer(content) ? "arraybuffer" : "text";
322
- const response = await httpClient.post(url, {
323
- content,
324
- headers: { ...headers, ...options.headers },
325
- responseType,
326
- timeout: options.timeout,
327
- withCredentials: options.withCredentials,
328
- });
329
- logger.log(LogLevel.Trace, `(${transportName} transport) request complete. Response status: ${response.statusCode}.`);
330
- }
331
- /** @private */
332
- function createLogger(logger) {
333
- if (logger === undefined) {
334
- return new ConsoleLogger(LogLevel.Information);
335
- }
336
- if (logger === null) {
337
- return NullLogger.instance;
338
- }
339
- if (logger.log !== undefined) {
340
- return logger;
341
- }
342
- return new ConsoleLogger(logger);
343
- }
344
- /** @private */
345
- class SubjectSubscription {
346
- constructor(subject, observer) {
347
- this._subject = subject;
348
- this._observer = observer;
349
- }
350
- dispose() {
351
- const index = this._subject.observers.indexOf(this._observer);
352
- if (index > -1) {
353
- this._subject.observers.splice(index, 1);
354
- }
355
- if (this._subject.observers.length === 0 && this._subject.cancelCallback) {
356
- this._subject.cancelCallback().catch((_) => { });
357
- }
358
- }
359
- }
360
- /** @private */
361
- class ConsoleLogger {
362
- constructor(minimumLogLevel) {
363
- this._minLevel = minimumLogLevel;
364
- this.out = console;
365
- }
366
- log(logLevel, message) {
367
- if (logLevel >= this._minLevel) {
368
- const msg = `[${new Date().toISOString()}] ${LogLevel[logLevel]}: ${message}`;
369
- switch (logLevel) {
370
- case LogLevel.Critical:
371
- case LogLevel.Error:
372
- this.out.error(msg);
373
- break;
374
- case LogLevel.Warning:
375
- this.out.warn(msg);
376
- break;
377
- case LogLevel.Information:
378
- this.out.info(msg);
379
- break;
380
- default:
381
- // console.debug only goes to attached debuggers in Node, so we use console.log for Trace and Debug
382
- this.out.log(msg);
383
- break;
384
- }
385
- }
386
- }
387
- }
388
- /** @private */
389
- function getUserAgentHeader() {
390
- let userAgentHeaderName = "X-SignalR-User-Agent";
391
- if (Platform.isNode) {
392
- userAgentHeaderName = "User-Agent";
393
- }
394
- return [userAgentHeaderName, constructUserAgent(VERSION, getOsName(), getRuntime(), getRuntimeVersion())];
395
- }
396
- /** @private */
397
- function constructUserAgent(version, os, runtime, runtimeVersion) {
398
- // Microsoft SignalR/[Version] ([Detailed Version]; [Operating System]; [Runtime]; [Runtime Version])
399
- let userAgent = "Microsoft SignalR/";
400
- const majorAndMinor = version.split(".");
401
- userAgent += `${majorAndMinor[0]}.${majorAndMinor[1]}`;
402
- userAgent += ` (${version}; `;
403
- if (os && os !== "") {
404
- userAgent += `${os}; `;
405
- }
406
- else {
407
- userAgent += "Unknown OS; ";
408
- }
409
- userAgent += `${runtime}`;
410
- if (runtimeVersion) {
411
- userAgent += `; ${runtimeVersion}`;
412
- }
413
- else {
414
- userAgent += "; Unknown Runtime Version";
415
- }
416
- userAgent += ")";
417
- return userAgent;
418
- }
419
- // eslint-disable-next-line spaced-comment
420
- /*#__PURE__*/ function getOsName() {
421
- if (Platform.isNode) {
422
- switch (process.platform) {
423
- case "win32":
424
- return "Windows NT";
425
- case "darwin":
426
- return "macOS";
427
- case "linux":
428
- return "Linux";
429
- default:
430
- return process.platform;
431
- }
432
- }
433
- else {
434
- return "";
435
- }
436
- }
437
- // eslint-disable-next-line spaced-comment
438
- /*#__PURE__*/ function getRuntimeVersion() {
439
- if (Platform.isNode) {
440
- return process.versions.node;
441
- }
442
- return undefined;
443
- }
444
- function getRuntime() {
445
- if (Platform.isNode) {
446
- return "NodeJS";
447
- }
448
- else {
449
- return "Browser";
450
- }
451
- }
452
- /** @private */
453
- function getErrorString(e) {
454
- if (e.stack) {
455
- return e.stack;
456
- }
457
- else if (e.message) {
458
- return e.message;
459
- }
460
- return `${e}`;
461
- }
462
- /** @private */
463
- function getGlobalThis() {
464
- // globalThis is semi-new and not available in Node until v12
465
- if (typeof globalThis !== "undefined") {
466
- return globalThis;
467
- }
468
- if (typeof self !== "undefined") {
469
- return self;
470
- }
471
- if (typeof window !== "undefined") {
472
- return window;
473
- }
474
- if (typeof global !== "undefined") {
475
- return global;
476
- }
477
- throw new Error("could not find global");
478
- }
479
-
480
- // Licensed to the .NET Foundation under one or more agreements.
481
- class FetchHttpClient extends HttpClient {
482
- constructor(logger) {
483
- super();
484
- this._logger = logger;
485
- if (typeof fetch === "undefined") {
486
- // In order to ignore the dynamic require in webpack builds we need to do this magic
487
- // @ts-ignore: TS doesn't know about these names
488
- const requireFunc = typeof __webpack_require__ === "function" ? __non_webpack_require__ : require;
489
- // Cookies aren't automatically handled in Node so we need to add a CookieJar to preserve cookies across requests
490
- this._jar = new (requireFunc("tough-cookie")).CookieJar();
491
- this._fetchType = requireFunc("node-fetch");
492
- // node-fetch doesn't have a nice API for getting and setting cookies
493
- // fetch-cookie will wrap a fetch implementation with a default CookieJar or a provided one
494
- this._fetchType = requireFunc("fetch-cookie")(this._fetchType, this._jar);
495
- }
496
- else {
497
- this._fetchType = fetch.bind(getGlobalThis());
498
- }
499
- if (typeof AbortController === "undefined") {
500
- // In order to ignore the dynamic require in webpack builds we need to do this magic
501
- // @ts-ignore: TS doesn't know about these names
502
- const requireFunc = typeof __webpack_require__ === "function" ? __non_webpack_require__ : require;
503
- // Node needs EventListener methods on AbortController which our custom polyfill doesn't provide
504
- this._abortControllerType = requireFunc("abort-controller");
505
- }
506
- else {
507
- this._abortControllerType = AbortController;
508
- }
509
- }
510
- /** @inheritDoc */
511
- async send(request) {
512
- // Check that abort was not signaled before calling send
513
- if (request.abortSignal && request.abortSignal.aborted) {
514
- throw new AbortError();
515
- }
516
- if (!request.method) {
517
- throw new Error("No method defined.");
518
- }
519
- if (!request.url) {
520
- throw new Error("No url defined.");
521
- }
522
- const abortController = new this._abortControllerType();
523
- let error;
524
- // Hook our abortSignal into the abort controller
525
- if (request.abortSignal) {
526
- request.abortSignal.onabort = () => {
527
- abortController.abort();
528
- error = new AbortError();
529
- };
530
- }
531
- // If a timeout has been passed in, setup a timeout to call abort
532
- // Type needs to be any to fit window.setTimeout and NodeJS.setTimeout
533
- let timeoutId = null;
534
- if (request.timeout) {
535
- const msTimeout = request.timeout;
536
- timeoutId = setTimeout(() => {
537
- abortController.abort();
538
- this._logger.log(LogLevel.Warning, `Timeout from HTTP request.`);
539
- error = new TimeoutError();
540
- }, msTimeout);
541
- }
542
- let response;
543
- try {
544
- response = await this._fetchType(request.url, {
545
- body: request.content,
546
- cache: "no-cache",
547
- credentials: request.withCredentials === true ? "include" : "same-origin",
548
- headers: {
549
- "Content-Type": "text/plain;charset=UTF-8",
550
- "X-Requested-With": "XMLHttpRequest",
551
- ...request.headers,
552
- },
553
- method: request.method,
554
- mode: "cors",
555
- redirect: "follow",
556
- signal: abortController.signal,
557
- });
558
- }
559
- catch (e) {
560
- if (error) {
561
- throw error;
562
- }
563
- this._logger.log(LogLevel.Warning, `Error from HTTP request. ${e}.`);
564
- throw e;
565
- }
566
- finally {
567
- if (timeoutId) {
568
- clearTimeout(timeoutId);
569
- }
570
- if (request.abortSignal) {
571
- request.abortSignal.onabort = null;
572
- }
573
- }
574
- if (!response.ok) {
575
- const errorMessage = await deserializeContent(response, "text");
576
- throw new HttpError(errorMessage || response.statusText, response.status);
577
- }
578
- const content = deserializeContent(response, request.responseType);
579
- const payload = await content;
580
- return new HttpResponse(response.status, response.statusText, payload);
581
- }
582
- getCookieString(url) {
583
- let cookies = "";
584
- if (Platform.isNode && this._jar) {
585
- // @ts-ignore: unused variable
586
- this._jar.getCookies(url, (e, c) => cookies = c.join("; "));
587
- }
588
- return cookies;
589
- }
590
- }
591
- function deserializeContent(response, responseType) {
592
- let content;
593
- switch (responseType) {
594
- case "arraybuffer":
595
- content = response.arrayBuffer();
596
- break;
597
- case "text":
598
- content = response.text();
599
- break;
600
- case "blob":
601
- case "document":
602
- case "json":
603
- throw new Error(`${responseType} is not supported.`);
604
- default:
605
- content = response.text();
606
- break;
607
- }
608
- return content;
609
- }
610
-
611
- // Licensed to the .NET Foundation under one or more agreements.
612
- class XhrHttpClient extends HttpClient {
613
- constructor(logger) {
614
- super();
615
- this._logger = logger;
616
- }
617
- /** @inheritDoc */
618
- send(request) {
619
- // Check that abort was not signaled before calling send
620
- if (request.abortSignal && request.abortSignal.aborted) {
621
- return Promise.reject(new AbortError());
622
- }
623
- if (!request.method) {
624
- return Promise.reject(new Error("No method defined."));
625
- }
626
- if (!request.url) {
627
- return Promise.reject(new Error("No url defined."));
628
- }
629
- return new Promise((resolve, reject) => {
630
- const xhr = new XMLHttpRequest();
631
- xhr.open(request.method, request.url, true);
632
- xhr.withCredentials = request.withCredentials === undefined ? true : request.withCredentials;
633
- xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
634
- // Explicitly setting the Content-Type header for React Native on Android platform.
635
- xhr.setRequestHeader("Content-Type", "text/plain;charset=UTF-8");
636
- const headers = request.headers;
637
- if (headers) {
638
- Object.keys(headers)
639
- .forEach((header) => {
640
- xhr.setRequestHeader(header, headers[header]);
641
- });
642
- }
643
- if (request.responseType) {
644
- xhr.responseType = request.responseType;
645
- }
646
- if (request.abortSignal) {
647
- request.abortSignal.onabort = () => {
648
- xhr.abort();
649
- reject(new AbortError());
650
- };
651
- }
652
- if (request.timeout) {
653
- xhr.timeout = request.timeout;
654
- }
655
- xhr.onload = () => {
656
- if (request.abortSignal) {
657
- request.abortSignal.onabort = null;
658
- }
659
- if (xhr.status >= 200 && xhr.status < 300) {
660
- resolve(new HttpResponse(xhr.status, xhr.statusText, xhr.response || xhr.responseText));
661
- }
662
- else {
663
- reject(new HttpError(xhr.response || xhr.responseText || xhr.statusText, xhr.status));
664
- }
665
- };
666
- xhr.onerror = () => {
667
- this._logger.log(LogLevel.Warning, `Error from HTTP request. ${xhr.status}: ${xhr.statusText}.`);
668
- reject(new HttpError(xhr.statusText, xhr.status));
669
- };
670
- xhr.ontimeout = () => {
671
- this._logger.log(LogLevel.Warning, `Timeout from HTTP request.`);
672
- reject(new TimeoutError());
673
- };
674
- xhr.send(request.content || "");
675
- });
676
- }
677
- }
678
-
679
- // Licensed to the .NET Foundation under one or more agreements.
680
- /** Default implementation of {@link @microsoft/signalr.HttpClient}. */
681
- class DefaultHttpClient extends HttpClient {
682
- /** Creates a new instance of the {@link @microsoft/signalr.DefaultHttpClient}, using the provided {@link @microsoft/signalr.ILogger} to log messages. */
683
- constructor(logger) {
684
- super();
685
- if (typeof fetch !== "undefined" || Platform.isNode) {
686
- this._httpClient = new FetchHttpClient(logger);
687
- }
688
- else if (typeof XMLHttpRequest !== "undefined") {
689
- this._httpClient = new XhrHttpClient(logger);
690
- }
691
- else {
692
- throw new Error("No usable HttpClient found.");
693
- }
694
- }
695
- /** @inheritDoc */
696
- send(request) {
697
- // Check that abort was not signaled before calling send
698
- if (request.abortSignal && request.abortSignal.aborted) {
699
- return Promise.reject(new AbortError());
700
- }
701
- if (!request.method) {
702
- return Promise.reject(new Error("No method defined."));
703
- }
704
- if (!request.url) {
705
- return Promise.reject(new Error("No url defined."));
706
- }
707
- return this._httpClient.send(request);
708
- }
709
- getCookieString(url) {
710
- return this._httpClient.getCookieString(url);
711
- }
712
- }
713
-
714
- // Licensed to the .NET Foundation under one or more agreements.
715
- // The .NET Foundation licenses this file to you under the MIT license.
716
- // Not exported from index
717
- /** @private */
718
- class TextMessageFormat {
719
- static write(output) {
720
- return `${output}${TextMessageFormat.RecordSeparator}`;
721
- }
722
- static parse(input) {
723
- if (input[input.length - 1] !== TextMessageFormat.RecordSeparator) {
724
- throw new Error("Message is incomplete.");
725
- }
726
- const messages = input.split(TextMessageFormat.RecordSeparator);
727
- messages.pop();
728
- return messages;
729
- }
730
- }
731
- TextMessageFormat.RecordSeparatorCode = 0x1e;
732
- TextMessageFormat.RecordSeparator = String.fromCharCode(TextMessageFormat.RecordSeparatorCode);
733
-
734
- // Licensed to the .NET Foundation under one or more agreements.
735
- /** @private */
736
- class HandshakeProtocol {
737
- // Handshake request is always JSON
738
- writeHandshakeRequest(handshakeRequest) {
739
- return TextMessageFormat.write(JSON.stringify(handshakeRequest));
740
- }
741
- parseHandshakeResponse(data) {
742
- let messageData;
743
- let remainingData;
744
- if (isArrayBuffer(data)) {
745
- // Format is binary but still need to read JSON text from handshake response
746
- const binaryData = new Uint8Array(data);
747
- const separatorIndex = binaryData.indexOf(TextMessageFormat.RecordSeparatorCode);
748
- if (separatorIndex === -1) {
749
- throw new Error("Message is incomplete.");
750
- }
751
- // content before separator is handshake response
752
- // optional content after is additional messages
753
- const responseLength = separatorIndex + 1;
754
- messageData = String.fromCharCode.apply(null, Array.prototype.slice.call(binaryData.slice(0, responseLength)));
755
- remainingData = (binaryData.byteLength > responseLength) ? binaryData.slice(responseLength).buffer : null;
756
- }
757
- else {
758
- const textData = data;
759
- const separatorIndex = textData.indexOf(TextMessageFormat.RecordSeparator);
760
- if (separatorIndex === -1) {
761
- throw new Error("Message is incomplete.");
762
- }
763
- // content before separator is handshake response
764
- // optional content after is additional messages
765
- const responseLength = separatorIndex + 1;
766
- messageData = textData.substring(0, responseLength);
767
- remainingData = (textData.length > responseLength) ? textData.substring(responseLength) : null;
768
- }
769
- // At this point we should have just the single handshake message
770
- const messages = TextMessageFormat.parse(messageData);
771
- const response = JSON.parse(messages[0]);
772
- if (response.type) {
773
- throw new Error("Expected a handshake response from the server.");
774
- }
775
- const responseMessage = response;
776
- // multiple messages could have arrived with handshake
777
- // return additional data to be parsed as usual, or null if all parsed
778
- return [remainingData, responseMessage];
779
- }
780
- }
781
-
782
- // Licensed to the .NET Foundation under one or more agreements.
783
- // The .NET Foundation licenses this file to you under the MIT license.
784
- /** Defines the type of a Hub Message. */
785
- var MessageType;
786
- (function (MessageType) {
787
- /** Indicates the message is an Invocation message and implements the {@link @microsoft/signalr.InvocationMessage} interface. */
788
- MessageType[MessageType["Invocation"] = 1] = "Invocation";
789
- /** Indicates the message is a StreamItem message and implements the {@link @microsoft/signalr.StreamItemMessage} interface. */
790
- MessageType[MessageType["StreamItem"] = 2] = "StreamItem";
791
- /** Indicates the message is a Completion message and implements the {@link @microsoft/signalr.CompletionMessage} interface. */
792
- MessageType[MessageType["Completion"] = 3] = "Completion";
793
- /** Indicates the message is a Stream Invocation message and implements the {@link @microsoft/signalr.StreamInvocationMessage} interface. */
794
- MessageType[MessageType["StreamInvocation"] = 4] = "StreamInvocation";
795
- /** Indicates the message is a Cancel Invocation message and implements the {@link @microsoft/signalr.CancelInvocationMessage} interface. */
796
- MessageType[MessageType["CancelInvocation"] = 5] = "CancelInvocation";
797
- /** Indicates the message is a Ping message and implements the {@link @microsoft/signalr.PingMessage} interface. */
798
- MessageType[MessageType["Ping"] = 6] = "Ping";
799
- /** Indicates the message is a Close message and implements the {@link @microsoft/signalr.CloseMessage} interface. */
800
- MessageType[MessageType["Close"] = 7] = "Close";
801
- })(MessageType || (MessageType = {}));
802
-
803
- // Licensed to the .NET Foundation under one or more agreements.
804
- /** Stream implementation to stream items to the server. */
805
- class Subject {
806
- constructor() {
807
- this.observers = [];
808
- }
809
- next(item) {
810
- for (const observer of this.observers) {
811
- observer.next(item);
812
- }
813
- }
814
- error(err) {
815
- for (const observer of this.observers) {
816
- if (observer.error) {
817
- observer.error(err);
818
- }
819
- }
820
- }
821
- complete() {
822
- for (const observer of this.observers) {
823
- if (observer.complete) {
824
- observer.complete();
825
- }
826
- }
827
- }
828
- subscribe(observer) {
829
- this.observers.push(observer);
830
- return new SubjectSubscription(this, observer);
831
- }
832
- }
833
-
834
- // Licensed to the .NET Foundation under one or more agreements.
835
- const DEFAULT_TIMEOUT_IN_MS = 30 * 1000;
836
- const DEFAULT_PING_INTERVAL_IN_MS = 15 * 1000;
837
- /** Describes the current state of the {@link HubConnection} to the server. */
838
- var HubConnectionState;
839
- (function (HubConnectionState) {
840
- /** The hub connection is disconnected. */
841
- HubConnectionState["Disconnected"] = "Disconnected";
842
- /** The hub connection is connecting. */
843
- HubConnectionState["Connecting"] = "Connecting";
844
- /** The hub connection is connected. */
845
- HubConnectionState["Connected"] = "Connected";
846
- /** The hub connection is disconnecting. */
847
- HubConnectionState["Disconnecting"] = "Disconnecting";
848
- /** The hub connection is reconnecting. */
849
- HubConnectionState["Reconnecting"] = "Reconnecting";
850
- })(HubConnectionState || (HubConnectionState = {}));
851
- /** Represents a connection to a SignalR Hub. */
852
- class HubConnection {
853
- constructor(connection, logger, protocol, reconnectPolicy) {
854
- this._nextKeepAlive = 0;
855
- this._freezeEventListener = () => {
856
- this._logger.log(LogLevel.Warning, "The page is being frozen, this will likely lead to the connection being closed and messages being lost. For more information see the docs at https://docs.microsoft.com/aspnet/core/signalr/javascript-client#bsleep");
857
- };
858
- Arg.isRequired(connection, "connection");
859
- Arg.isRequired(logger, "logger");
860
- Arg.isRequired(protocol, "protocol");
861
- this.serverTimeoutInMilliseconds = DEFAULT_TIMEOUT_IN_MS;
862
- this.keepAliveIntervalInMilliseconds = DEFAULT_PING_INTERVAL_IN_MS;
863
- this._logger = logger;
864
- this._protocol = protocol;
865
- this.connection = connection;
866
- this._reconnectPolicy = reconnectPolicy;
867
- this._handshakeProtocol = new HandshakeProtocol();
868
- this.connection.onreceive = (data) => this._processIncomingData(data);
869
- this.connection.onclose = (error) => this._connectionClosed(error);
870
- this._callbacks = {};
871
- this._methods = {};
872
- this._closedCallbacks = [];
873
- this._reconnectingCallbacks = [];
874
- this._reconnectedCallbacks = [];
875
- this._invocationId = 0;
876
- this._receivedHandshakeResponse = false;
877
- this._connectionState = HubConnectionState.Disconnected;
878
- this._connectionStarted = false;
879
- this._cachedPingMessage = this._protocol.writeMessage({ type: MessageType.Ping });
880
- }
881
- /** @internal */
882
- // Using a public static factory method means we can have a private constructor and an _internal_
883
- // create method that can be used by HubConnectionBuilder. An "internal" constructor would just
884
- // be stripped away and the '.d.ts' file would have no constructor, which is interpreted as a
885
- // public parameter-less constructor.
886
- static create(connection, logger, protocol, reconnectPolicy) {
887
- return new HubConnection(connection, logger, protocol, reconnectPolicy);
888
- }
889
- /** Indicates the state of the {@link HubConnection} to the server. */
890
- get state() {
891
- return this._connectionState;
892
- }
893
- /** Represents the connection id of the {@link HubConnection} on the server. The connection id will be null when the connection is either
894
- * in the disconnected state or if the negotiation step was skipped.
895
- */
896
- get connectionId() {
897
- return this.connection ? (this.connection.connectionId || null) : null;
898
- }
899
- /** Indicates the url of the {@link HubConnection} to the server. */
900
- get baseUrl() {
901
- return this.connection.baseUrl || "";
902
- }
903
- /**
904
- * Sets a new url for the HubConnection. Note that the url can only be changed when the connection is in either the Disconnected or
905
- * Reconnecting states.
906
- * @param {string} url The url to connect to.
907
- */
908
- set baseUrl(url) {
909
- if (this._connectionState !== HubConnectionState.Disconnected && this._connectionState !== HubConnectionState.Reconnecting) {
910
- throw new Error("The HubConnection must be in the Disconnected or Reconnecting state to change the url.");
911
- }
912
- if (!url) {
913
- throw new Error("The HubConnection url must be a valid url.");
914
- }
915
- this.connection.baseUrl = url;
916
- }
917
- /** Starts the connection.
918
- *
919
- * @returns {Promise<void>} A Promise that resolves when the connection has been successfully established, or rejects with an error.
920
- */
921
- start() {
922
- this._startPromise = this._startWithStateTransitions();
923
- return this._startPromise;
924
- }
925
- async _startWithStateTransitions() {
926
- if (this._connectionState !== HubConnectionState.Disconnected) {
927
- return Promise.reject(new Error("Cannot start a HubConnection that is not in the 'Disconnected' state."));
928
- }
929
- this._connectionState = HubConnectionState.Connecting;
930
- this._logger.log(LogLevel.Debug, "Starting HubConnection.");
931
- try {
932
- await this._startInternal();
933
- if (Platform.isBrowser) {
934
- // Log when the browser freezes the tab so users know why their connection unexpectedly stopped working
935
- window.document.addEventListener("freeze", this._freezeEventListener);
936
- }
937
- this._connectionState = HubConnectionState.Connected;
938
- this._connectionStarted = true;
939
- this._logger.log(LogLevel.Debug, "HubConnection connected successfully.");
940
- }
941
- catch (e) {
942
- this._connectionState = HubConnectionState.Disconnected;
943
- this._logger.log(LogLevel.Debug, `HubConnection failed to start successfully because of error '${e}'.`);
944
- return Promise.reject(e);
945
- }
946
- }
947
- async _startInternal() {
948
- this._stopDuringStartError = undefined;
949
- this._receivedHandshakeResponse = false;
950
- // Set up the promise before any connection is (re)started otherwise it could race with received messages
951
- const handshakePromise = new Promise((resolve, reject) => {
952
- this._handshakeResolver = resolve;
953
- this._handshakeRejecter = reject;
954
- });
955
- await this.connection.start(this._protocol.transferFormat);
956
- try {
957
- const handshakeRequest = {
958
- protocol: this._protocol.name,
959
- version: this._protocol.version,
960
- };
961
- this._logger.log(LogLevel.Debug, "Sending handshake request.");
962
- await this._sendMessage(this._handshakeProtocol.writeHandshakeRequest(handshakeRequest));
963
- this._logger.log(LogLevel.Information, `Using HubProtocol '${this._protocol.name}'.`);
964
- // defensively cleanup timeout in case we receive a message from the server before we finish start
965
- this._cleanupTimeout();
966
- this._resetTimeoutPeriod();
967
- this._resetKeepAliveInterval();
968
- await handshakePromise;
969
- // It's important to check the stopDuringStartError instead of just relying on the handshakePromise
970
- // being rejected on close, because this continuation can run after both the handshake completed successfully
971
- // and the connection was closed.
972
- if (this._stopDuringStartError) {
973
- // It's important to throw instead of returning a rejected promise, because we don't want to allow any state
974
- // transitions to occur between now and the calling code observing the exceptions. Returning a rejected promise
975
- // will cause the calling continuation to get scheduled to run later.
976
- // eslint-disable-next-line @typescript-eslint/no-throw-literal
977
- throw this._stopDuringStartError;
978
- }
979
- }
980
- catch (e) {
981
- this._logger.log(LogLevel.Debug, `Hub handshake failed with error '${e}' during start(). Stopping HubConnection.`);
982
- this._cleanupTimeout();
983
- this._cleanupPingTimer();
984
- // HttpConnection.stop() should not complete until after the onclose callback is invoked.
985
- // This will transition the HubConnection to the disconnected state before HttpConnection.stop() completes.
986
- await this.connection.stop(e);
987
- throw e;
988
- }
989
- }
990
- /** Stops the connection.
991
- *
992
- * @returns {Promise<void>} A Promise that resolves when the connection has been successfully terminated, or rejects with an error.
993
- */
994
- async stop() {
995
- // Capture the start promise before the connection might be restarted in an onclose callback.
996
- const startPromise = this._startPromise;
997
- this._stopPromise = this._stopInternal();
998
- await this._stopPromise;
999
- try {
1000
- // Awaiting undefined continues immediately
1001
- await startPromise;
1002
- }
1003
- catch (e) {
1004
- // This exception is returned to the user as a rejected Promise from the start method.
1005
- }
1006
- }
1007
- _stopInternal(error) {
1008
- if (this._connectionState === HubConnectionState.Disconnected) {
1009
- this._logger.log(LogLevel.Debug, `Call to HubConnection.stop(${error}) ignored because it is already in the disconnected state.`);
1010
- return Promise.resolve();
1011
- }
1012
- if (this._connectionState === HubConnectionState.Disconnecting) {
1013
- this._logger.log(LogLevel.Debug, `Call to HttpConnection.stop(${error}) ignored because the connection is already in the disconnecting state.`);
1014
- return this._stopPromise;
1015
- }
1016
- this._connectionState = HubConnectionState.Disconnecting;
1017
- this._logger.log(LogLevel.Debug, "Stopping HubConnection.");
1018
- if (this._reconnectDelayHandle) {
1019
- // We're in a reconnect delay which means the underlying connection is currently already stopped.
1020
- // Just clear the handle to stop the reconnect loop (which no one is waiting on thankfully) and
1021
- // fire the onclose callbacks.
1022
- this._logger.log(LogLevel.Debug, "Connection stopped during reconnect delay. Done reconnecting.");
1023
- clearTimeout(this._reconnectDelayHandle);
1024
- this._reconnectDelayHandle = undefined;
1025
- this._completeClose();
1026
- return Promise.resolve();
1027
- }
1028
- this._cleanupTimeout();
1029
- this._cleanupPingTimer();
1030
- this._stopDuringStartError = error || new Error("The connection was stopped before the hub handshake could complete.");
1031
- // HttpConnection.stop() should not complete until after either HttpConnection.start() fails
1032
- // or the onclose callback is invoked. The onclose callback will transition the HubConnection
1033
- // to the disconnected state if need be before HttpConnection.stop() completes.
1034
- return this.connection.stop(error);
1035
- }
1036
- /** Invokes a streaming hub method on the server using the specified name and arguments.
1037
- *
1038
- * @typeparam T The type of the items returned by the server.
1039
- * @param {string} methodName The name of the server method to invoke.
1040
- * @param {any[]} args The arguments used to invoke the server method.
1041
- * @returns {IStreamResult<T>} An object that yields results from the server as they are received.
1042
- */
1043
- stream(methodName, ...args) {
1044
- const [streams, streamIds] = this._replaceStreamingParams(args);
1045
- const invocationDescriptor = this._createStreamInvocation(methodName, args, streamIds);
1046
- // eslint-disable-next-line prefer-const
1047
- let promiseQueue;
1048
- const subject = new Subject();
1049
- subject.cancelCallback = () => {
1050
- const cancelInvocation = this._createCancelInvocation(invocationDescriptor.invocationId);
1051
- delete this._callbacks[invocationDescriptor.invocationId];
1052
- return promiseQueue.then(() => {
1053
- return this._sendWithProtocol(cancelInvocation);
1054
- });
1055
- };
1056
- this._callbacks[invocationDescriptor.invocationId] = (invocationEvent, error) => {
1057
- if (error) {
1058
- subject.error(error);
1059
- return;
1060
- }
1061
- else if (invocationEvent) {
1062
- // invocationEvent will not be null when an error is not passed to the callback
1063
- if (invocationEvent.type === MessageType.Completion) {
1064
- if (invocationEvent.error) {
1065
- subject.error(new Error(invocationEvent.error));
1066
- }
1067
- else {
1068
- subject.complete();
1069
- }
1070
- }
1071
- else {
1072
- subject.next((invocationEvent.item));
1073
- }
1074
- }
1075
- };
1076
- promiseQueue = this._sendWithProtocol(invocationDescriptor)
1077
- .catch((e) => {
1078
- subject.error(e);
1079
- delete this._callbacks[invocationDescriptor.invocationId];
1080
- });
1081
- this._launchStreams(streams, promiseQueue);
1082
- return subject;
1083
- }
1084
- _sendMessage(message) {
1085
- this._resetKeepAliveInterval();
1086
- return this.connection.send(message);
1087
- }
1088
- /**
1089
- * Sends a js object to the server.
1090
- * @param message The js object to serialize and send.
1091
- */
1092
- _sendWithProtocol(message) {
1093
- return this._sendMessage(this._protocol.writeMessage(message));
1094
- }
1095
- /** Invokes a hub method on the server using the specified name and arguments. Does not wait for a response from the receiver.
1096
- *
1097
- * The Promise returned by this method resolves when the client has sent the invocation to the server. The server may still
1098
- * be processing the invocation.
1099
- *
1100
- * @param {string} methodName The name of the server method to invoke.
1101
- * @param {any[]} args The arguments used to invoke the server method.
1102
- * @returns {Promise<void>} A Promise that resolves when the invocation has been successfully sent, or rejects with an error.
1103
- */
1104
- send(methodName, ...args) {
1105
- const [streams, streamIds] = this._replaceStreamingParams(args);
1106
- const sendPromise = this._sendWithProtocol(this._createInvocation(methodName, args, true, streamIds));
1107
- this._launchStreams(streams, sendPromise);
1108
- return sendPromise;
1109
- }
1110
- /** Invokes a hub method on the server using the specified name and arguments.
1111
- *
1112
- * The Promise returned by this method resolves when the server indicates it has finished invoking the method. When the promise
1113
- * resolves, the server has finished invoking the method. If the server method returns a result, it is produced as the result of
1114
- * resolving the Promise.
1115
- *
1116
- * @typeparam T The expected return type.
1117
- * @param {string} methodName The name of the server method to invoke.
1118
- * @param {any[]} args The arguments used to invoke the server method.
1119
- * @returns {Promise<T>} A Promise that resolves with the result of the server method (if any), or rejects with an error.
1120
- */
1121
- invoke(methodName, ...args) {
1122
- const [streams, streamIds] = this._replaceStreamingParams(args);
1123
- const invocationDescriptor = this._createInvocation(methodName, args, false, streamIds);
1124
- const p = new Promise((resolve, reject) => {
1125
- // invocationId will always have a value for a non-blocking invocation
1126
- this._callbacks[invocationDescriptor.invocationId] = (invocationEvent, error) => {
1127
- if (error) {
1128
- reject(error);
1129
- return;
1130
- }
1131
- else if (invocationEvent) {
1132
- // invocationEvent will not be null when an error is not passed to the callback
1133
- if (invocationEvent.type === MessageType.Completion) {
1134
- if (invocationEvent.error) {
1135
- reject(new Error(invocationEvent.error));
1136
- }
1137
- else {
1138
- resolve(invocationEvent.result);
1139
- }
1140
- }
1141
- else {
1142
- reject(new Error(`Unexpected message type: ${invocationEvent.type}`));
1143
- }
1144
- }
1145
- };
1146
- const promiseQueue = this._sendWithProtocol(invocationDescriptor)
1147
- .catch((e) => {
1148
- reject(e);
1149
- // invocationId will always have a value for a non-blocking invocation
1150
- delete this._callbacks[invocationDescriptor.invocationId];
1151
- });
1152
- this._launchStreams(streams, promiseQueue);
1153
- });
1154
- return p;
1155
- }
1156
- /** Registers a handler that will be invoked when the hub method with the specified method name is invoked.
1157
- *
1158
- * @param {string} methodName The name of the hub method to define.
1159
- * @param {Function} newMethod The handler that will be raised when the hub method is invoked.
1160
- */
1161
- on(methodName, newMethod) {
1162
- if (!methodName || !newMethod) {
1163
- return;
1164
- }
1165
- methodName = methodName.toLowerCase();
1166
- if (!this._methods[methodName]) {
1167
- this._methods[methodName] = [];
1168
- }
1169
- // Preventing adding the same handler multiple times.
1170
- if (this._methods[methodName].indexOf(newMethod) !== -1) {
1171
- return;
1172
- }
1173
- this._methods[methodName].push(newMethod);
1174
- }
1175
- off(methodName, method) {
1176
- if (!methodName) {
1177
- return;
1178
- }
1179
- methodName = methodName.toLowerCase();
1180
- const handlers = this._methods[methodName];
1181
- if (!handlers) {
1182
- return;
1183
- }
1184
- if (method) {
1185
- const removeIdx = handlers.indexOf(method);
1186
- if (removeIdx !== -1) {
1187
- handlers.splice(removeIdx, 1);
1188
- if (handlers.length === 0) {
1189
- delete this._methods[methodName];
1190
- }
1191
- }
1192
- }
1193
- else {
1194
- delete this._methods[methodName];
1195
- }
1196
- }
1197
- /** Registers a handler that will be invoked when the connection is closed.
1198
- *
1199
- * @param {Function} callback The handler that will be invoked when the connection is closed. Optionally receives a single argument containing the error that caused the connection to close (if any).
1200
- */
1201
- onclose(callback) {
1202
- if (callback) {
1203
- this._closedCallbacks.push(callback);
1204
- }
1205
- }
1206
- /** Registers a handler that will be invoked when the connection starts reconnecting.
1207
- *
1208
- * @param {Function} callback The handler that will be invoked when the connection starts reconnecting. Optionally receives a single argument containing the error that caused the connection to start reconnecting (if any).
1209
- */
1210
- onreconnecting(callback) {
1211
- if (callback) {
1212
- this._reconnectingCallbacks.push(callback);
1213
- }
1214
- }
1215
- /** Registers a handler that will be invoked when the connection successfully reconnects.
1216
- *
1217
- * @param {Function} callback The handler that will be invoked when the connection successfully reconnects.
1218
- */
1219
- onreconnected(callback) {
1220
- if (callback) {
1221
- this._reconnectedCallbacks.push(callback);
1222
- }
1223
- }
1224
- _processIncomingData(data) {
1225
- this._cleanupTimeout();
1226
- if (!this._receivedHandshakeResponse) {
1227
- data = this._processHandshakeResponse(data);
1228
- this._receivedHandshakeResponse = true;
1229
- }
1230
- // Data may have all been read when processing handshake response
1231
- if (data) {
1232
- // Parse the messages
1233
- const messages = this._protocol.parseMessages(data, this._logger);
1234
- for (const message of messages) {
1235
- switch (message.type) {
1236
- case MessageType.Invocation:
1237
- this._invokeClientMethod(message);
1238
- break;
1239
- case MessageType.StreamItem:
1240
- case MessageType.Completion: {
1241
- const callback = this._callbacks[message.invocationId];
1242
- if (callback) {
1243
- if (message.type === MessageType.Completion) {
1244
- delete this._callbacks[message.invocationId];
1245
- }
1246
- try {
1247
- callback(message);
1248
- }
1249
- catch (e) {
1250
- this._logger.log(LogLevel.Error, `Stream callback threw error: ${getErrorString(e)}`);
1251
- }
1252
- }
1253
- break;
1254
- }
1255
- case MessageType.Ping:
1256
- // Don't care about pings
1257
- break;
1258
- case MessageType.Close: {
1259
- this._logger.log(LogLevel.Information, "Close message received from server.");
1260
- const error = message.error ? new Error("Server returned an error on close: " + message.error) : undefined;
1261
- if (message.allowReconnect === true) {
1262
- // It feels wrong not to await connection.stop() here, but processIncomingData is called as part of an onreceive callback which is not async,
1263
- // this is already the behavior for serverTimeout(), and HttpConnection.Stop() should catch and log all possible exceptions.
1264
- // eslint-disable-next-line @typescript-eslint/no-floating-promises
1265
- this.connection.stop(error);
1266
- }
1267
- else {
1268
- // We cannot await stopInternal() here, but subsequent calls to stop() will await this if stopInternal() is still ongoing.
1269
- this._stopPromise = this._stopInternal(error);
1270
- }
1271
- break;
1272
- }
1273
- default:
1274
- this._logger.log(LogLevel.Warning, `Invalid message type: ${message.type}.`);
1275
- break;
1276
- }
1277
- }
1278
- }
1279
- this._resetTimeoutPeriod();
1280
- }
1281
- _processHandshakeResponse(data) {
1282
- let responseMessage;
1283
- let remainingData;
1284
- try {
1285
- [remainingData, responseMessage] = this._handshakeProtocol.parseHandshakeResponse(data);
1286
- }
1287
- catch (e) {
1288
- const message = "Error parsing handshake response: " + e;
1289
- this._logger.log(LogLevel.Error, message);
1290
- const error = new Error(message);
1291
- this._handshakeRejecter(error);
1292
- throw error;
1293
- }
1294
- if (responseMessage.error) {
1295
- const message = "Server returned handshake error: " + responseMessage.error;
1296
- this._logger.log(LogLevel.Error, message);
1297
- const error = new Error(message);
1298
- this._handshakeRejecter(error);
1299
- throw error;
1300
- }
1301
- else {
1302
- this._logger.log(LogLevel.Debug, "Server handshake complete.");
1303
- }
1304
- this._handshakeResolver();
1305
- return remainingData;
1306
- }
1307
- _resetKeepAliveInterval() {
1308
- if (this.connection.features.inherentKeepAlive) {
1309
- return;
1310
- }
1311
- // Set the time we want the next keep alive to be sent
1312
- // Timer will be setup on next message receive
1313
- this._nextKeepAlive = new Date().getTime() + this.keepAliveIntervalInMilliseconds;
1314
- this._cleanupPingTimer();
1315
- }
1316
- _resetTimeoutPeriod() {
1317
- if (!this.connection.features || !this.connection.features.inherentKeepAlive) {
1318
- // Set the timeout timer
1319
- this._timeoutHandle = setTimeout(() => this.serverTimeout(), this.serverTimeoutInMilliseconds);
1320
- // Set keepAlive timer if there isn't one
1321
- if (this._pingServerHandle === undefined) {
1322
- let nextPing = this._nextKeepAlive - new Date().getTime();
1323
- if (nextPing < 0) {
1324
- nextPing = 0;
1325
- }
1326
- // The timer needs to be set from a networking callback to avoid Chrome timer throttling from causing timers to run once a minute
1327
- this._pingServerHandle = setTimeout(async () => {
1328
- if (this._connectionState === HubConnectionState.Connected) {
1329
- try {
1330
- await this._sendMessage(this._cachedPingMessage);
1331
- }
1332
- catch {
1333
- // We don't care about the error. It should be seen elsewhere in the client.
1334
- // The connection is probably in a bad or closed state now, cleanup the timer so it stops triggering
1335
- this._cleanupPingTimer();
1336
- }
1337
- }
1338
- }, nextPing);
1339
- }
1340
- }
1341
- }
1342
- // eslint-disable-next-line @typescript-eslint/naming-convention
1343
- serverTimeout() {
1344
- // The server hasn't talked to us in a while. It doesn't like us anymore ... :(
1345
- // Terminate the connection, but we don't need to wait on the promise. This could trigger reconnecting.
1346
- // eslint-disable-next-line @typescript-eslint/no-floating-promises
1347
- this.connection.stop(new Error("Server timeout elapsed without receiving a message from the server."));
1348
- }
1349
- _invokeClientMethod(invocationMessage) {
1350
- const methods = this._methods[invocationMessage.target.toLowerCase()];
1351
- if (methods) {
1352
- try {
1353
- methods.forEach((m) => m.apply(this, invocationMessage.arguments));
1354
- }
1355
- catch (e) {
1356
- this._logger.log(LogLevel.Error, `A callback for the method ${invocationMessage.target.toLowerCase()} threw error '${e}'.`);
1357
- }
1358
- if (invocationMessage.invocationId) {
1359
- // This is not supported in v1. So we return an error to avoid blocking the server waiting for the response.
1360
- const message = "Server requested a response, which is not supported in this version of the client.";
1361
- this._logger.log(LogLevel.Error, message);
1362
- // We don't want to wait on the stop itself.
1363
- this._stopPromise = this._stopInternal(new Error(message));
1364
- }
1365
- }
1366
- else {
1367
- this._logger.log(LogLevel.Warning, `No client method with the name '${invocationMessage.target}' found.`);
1368
- }
1369
- }
1370
- _connectionClosed(error) {
1371
- this._logger.log(LogLevel.Debug, `HubConnection.connectionClosed(${error}) called while in state ${this._connectionState}.`);
1372
- // Triggering this.handshakeRejecter is insufficient because it could already be resolved without the continuation having run yet.
1373
- this._stopDuringStartError = this._stopDuringStartError || error || new Error("The underlying connection was closed before the hub handshake could complete.");
1374
- // If the handshake is in progress, start will be waiting for the handshake promise, so we complete it.
1375
- // If it has already completed, this should just noop.
1376
- if (this._handshakeResolver) {
1377
- this._handshakeResolver();
1378
- }
1379
- this._cancelCallbacksWithError(error || new Error("Invocation canceled due to the underlying connection being closed."));
1380
- this._cleanupTimeout();
1381
- this._cleanupPingTimer();
1382
- if (this._connectionState === HubConnectionState.Disconnecting) {
1383
- this._completeClose(error);
1384
- }
1385
- else if (this._connectionState === HubConnectionState.Connected && this._reconnectPolicy) {
1386
- // eslint-disable-next-line @typescript-eslint/no-floating-promises
1387
- this._reconnect(error);
1388
- }
1389
- else if (this._connectionState === HubConnectionState.Connected) {
1390
- this._completeClose(error);
1391
- }
1392
- // If none of the above if conditions were true were called the HubConnection must be in either:
1393
- // 1. The Connecting state in which case the handshakeResolver will complete it and stopDuringStartError will fail it.
1394
- // 2. The Reconnecting state in which case the handshakeResolver will complete it and stopDuringStartError will fail the current reconnect attempt
1395
- // and potentially continue the reconnect() loop.
1396
- // 3. The Disconnected state in which case we're already done.
1397
- }
1398
- _completeClose(error) {
1399
- if (this._connectionStarted) {
1400
- this._connectionState = HubConnectionState.Disconnected;
1401
- this._connectionStarted = false;
1402
- if (Platform.isBrowser) {
1403
- window.document.removeEventListener("freeze", this._freezeEventListener);
1404
- }
1405
- try {
1406
- this._closedCallbacks.forEach((c) => c.apply(this, [error]));
1407
- }
1408
- catch (e) {
1409
- this._logger.log(LogLevel.Error, `An onclose callback called with error '${error}' threw error '${e}'.`);
1410
- }
1411
- }
1412
- }
1413
- async _reconnect(error) {
1414
- const reconnectStartTime = Date.now();
1415
- let previousReconnectAttempts = 0;
1416
- let retryError = error !== undefined ? error : new Error("Attempting to reconnect due to a unknown error.");
1417
- let nextRetryDelay = this._getNextRetryDelay(previousReconnectAttempts++, 0, retryError);
1418
- if (nextRetryDelay === null) {
1419
- this._logger.log(LogLevel.Debug, "Connection not reconnecting because the IRetryPolicy returned null on the first reconnect attempt.");
1420
- this._completeClose(error);
1421
- return;
1422
- }
1423
- this._connectionState = HubConnectionState.Reconnecting;
1424
- if (error) {
1425
- this._logger.log(LogLevel.Information, `Connection reconnecting because of error '${error}'.`);
1426
- }
1427
- else {
1428
- this._logger.log(LogLevel.Information, "Connection reconnecting.");
1429
- }
1430
- if (this._reconnectingCallbacks.length !== 0) {
1431
- try {
1432
- this._reconnectingCallbacks.forEach((c) => c.apply(this, [error]));
1433
- }
1434
- catch (e) {
1435
- this._logger.log(LogLevel.Error, `An onreconnecting callback called with error '${error}' threw error '${e}'.`);
1436
- }
1437
- // Exit early if an onreconnecting callback called connection.stop().
1438
- if (this._connectionState !== HubConnectionState.Reconnecting) {
1439
- this._logger.log(LogLevel.Debug, "Connection left the reconnecting state in onreconnecting callback. Done reconnecting.");
1440
- return;
1441
- }
1442
- }
1443
- while (nextRetryDelay !== null) {
1444
- this._logger.log(LogLevel.Information, `Reconnect attempt number ${previousReconnectAttempts} will start in ${nextRetryDelay} ms.`);
1445
- await new Promise((resolve) => {
1446
- this._reconnectDelayHandle = setTimeout(resolve, nextRetryDelay);
1447
- });
1448
- this._reconnectDelayHandle = undefined;
1449
- if (this._connectionState !== HubConnectionState.Reconnecting) {
1450
- this._logger.log(LogLevel.Debug, "Connection left the reconnecting state during reconnect delay. Done reconnecting.");
1451
- return;
1452
- }
1453
- try {
1454
- await this._startInternal();
1455
- this._connectionState = HubConnectionState.Connected;
1456
- this._logger.log(LogLevel.Information, "HubConnection reconnected successfully.");
1457
- if (this._reconnectedCallbacks.length !== 0) {
1458
- try {
1459
- this._reconnectedCallbacks.forEach((c) => c.apply(this, [this.connection.connectionId]));
1460
- }
1461
- catch (e) {
1462
- this._logger.log(LogLevel.Error, `An onreconnected callback called with connectionId '${this.connection.connectionId}; threw error '${e}'.`);
1463
- }
1464
- }
1465
- return;
1466
- }
1467
- catch (e) {
1468
- this._logger.log(LogLevel.Information, `Reconnect attempt failed because of error '${e}'.`);
1469
- if (this._connectionState !== HubConnectionState.Reconnecting) {
1470
- this._logger.log(LogLevel.Debug, `Connection moved to the '${this._connectionState}' from the reconnecting state during reconnect attempt. Done reconnecting.`);
1471
- // The TypeScript compiler thinks that connectionState must be Connected here. The TypeScript compiler is wrong.
1472
- if (this._connectionState === HubConnectionState.Disconnecting) {
1473
- this._completeClose();
1474
- }
1475
- return;
1476
- }
1477
- retryError = e instanceof Error ? e : new Error(e.toString());
1478
- nextRetryDelay = this._getNextRetryDelay(previousReconnectAttempts++, Date.now() - reconnectStartTime, retryError);
1479
- }
1480
- }
1481
- this._logger.log(LogLevel.Information, `Reconnect retries have been exhausted after ${Date.now() - reconnectStartTime} ms and ${previousReconnectAttempts} failed attempts. Connection disconnecting.`);
1482
- this._completeClose();
1483
- }
1484
- _getNextRetryDelay(previousRetryCount, elapsedMilliseconds, retryReason) {
1485
- try {
1486
- return this._reconnectPolicy.nextRetryDelayInMilliseconds({
1487
- elapsedMilliseconds,
1488
- previousRetryCount,
1489
- retryReason,
1490
- });
1491
- }
1492
- catch (e) {
1493
- this._logger.log(LogLevel.Error, `IRetryPolicy.nextRetryDelayInMilliseconds(${previousRetryCount}, ${elapsedMilliseconds}) threw error '${e}'.`);
1494
- return null;
1495
- }
1496
- }
1497
- _cancelCallbacksWithError(error) {
1498
- const callbacks = this._callbacks;
1499
- this._callbacks = {};
1500
- Object.keys(callbacks)
1501
- .forEach((key) => {
1502
- const callback = callbacks[key];
1503
- try {
1504
- callback(null, error);
1505
- }
1506
- catch (e) {
1507
- this._logger.log(LogLevel.Error, `Stream 'error' callback called with '${error}' threw error: ${getErrorString(e)}`);
1508
- }
1509
- });
1510
- }
1511
- _cleanupPingTimer() {
1512
- if (this._pingServerHandle) {
1513
- clearTimeout(this._pingServerHandle);
1514
- this._pingServerHandle = undefined;
1515
- }
1516
- }
1517
- _cleanupTimeout() {
1518
- if (this._timeoutHandle) {
1519
- clearTimeout(this._timeoutHandle);
1520
- }
1521
- }
1522
- _createInvocation(methodName, args, nonblocking, streamIds) {
1523
- if (nonblocking) {
1524
- if (streamIds.length !== 0) {
1525
- return {
1526
- arguments: args,
1527
- streamIds,
1528
- target: methodName,
1529
- type: MessageType.Invocation,
1530
- };
1531
- }
1532
- else {
1533
- return {
1534
- arguments: args,
1535
- target: methodName,
1536
- type: MessageType.Invocation,
1537
- };
1538
- }
1539
- }
1540
- else {
1541
- const invocationId = this._invocationId;
1542
- this._invocationId++;
1543
- if (streamIds.length !== 0) {
1544
- return {
1545
- arguments: args,
1546
- invocationId: invocationId.toString(),
1547
- streamIds,
1548
- target: methodName,
1549
- type: MessageType.Invocation,
1550
- };
1551
- }
1552
- else {
1553
- return {
1554
- arguments: args,
1555
- invocationId: invocationId.toString(),
1556
- target: methodName,
1557
- type: MessageType.Invocation,
1558
- };
1559
- }
1560
- }
1561
- }
1562
- _launchStreams(streams, promiseQueue) {
1563
- if (streams.length === 0) {
1564
- return;
1565
- }
1566
- // Synchronize stream data so they arrive in-order on the server
1567
- if (!promiseQueue) {
1568
- promiseQueue = Promise.resolve();
1569
- }
1570
- // We want to iterate over the keys, since the keys are the stream ids
1571
- // eslint-disable-next-line guard-for-in
1572
- for (const streamId in streams) {
1573
- streams[streamId].subscribe({
1574
- complete: () => {
1575
- promiseQueue = promiseQueue.then(() => this._sendWithProtocol(this._createCompletionMessage(streamId)));
1576
- },
1577
- error: (err) => {
1578
- let message;
1579
- if (err instanceof Error) {
1580
- message = err.message;
1581
- }
1582
- else if (err && err.toString) {
1583
- message = err.toString();
1584
- }
1585
- else {
1586
- message = "Unknown error";
1587
- }
1588
- promiseQueue = promiseQueue.then(() => this._sendWithProtocol(this._createCompletionMessage(streamId, message)));
1589
- },
1590
- next: (item) => {
1591
- promiseQueue = promiseQueue.then(() => this._sendWithProtocol(this._createStreamItemMessage(streamId, item)));
1592
- },
1593
- });
1594
- }
1595
- }
1596
- _replaceStreamingParams(args) {
1597
- const streams = [];
1598
- const streamIds = [];
1599
- for (let i = 0; i < args.length; i++) {
1600
- const argument = args[i];
1601
- if (this._isObservable(argument)) {
1602
- const streamId = this._invocationId;
1603
- this._invocationId++;
1604
- // Store the stream for later use
1605
- streams[streamId] = argument;
1606
- streamIds.push(streamId.toString());
1607
- // remove stream from args
1608
- args.splice(i, 1);
1609
- }
1610
- }
1611
- return [streams, streamIds];
1612
- }
1613
- _isObservable(arg) {
1614
- // This allows other stream implementations to just work (like rxjs)
1615
- return arg && arg.subscribe && typeof arg.subscribe === "function";
1616
- }
1617
- _createStreamInvocation(methodName, args, streamIds) {
1618
- const invocationId = this._invocationId;
1619
- this._invocationId++;
1620
- if (streamIds.length !== 0) {
1621
- return {
1622
- arguments: args,
1623
- invocationId: invocationId.toString(),
1624
- streamIds,
1625
- target: methodName,
1626
- type: MessageType.StreamInvocation,
1627
- };
1628
- }
1629
- else {
1630
- return {
1631
- arguments: args,
1632
- invocationId: invocationId.toString(),
1633
- target: methodName,
1634
- type: MessageType.StreamInvocation,
1635
- };
1636
- }
1637
- }
1638
- _createCancelInvocation(id) {
1639
- return {
1640
- invocationId: id,
1641
- type: MessageType.CancelInvocation,
1642
- };
1643
- }
1644
- _createStreamItemMessage(id, item) {
1645
- return {
1646
- invocationId: id,
1647
- item,
1648
- type: MessageType.StreamItem,
1649
- };
1650
- }
1651
- _createCompletionMessage(id, error, result) {
1652
- if (error) {
1653
- return {
1654
- error,
1655
- invocationId: id,
1656
- type: MessageType.Completion,
1657
- };
1658
- }
1659
- return {
1660
- invocationId: id,
1661
- result,
1662
- type: MessageType.Completion,
1663
- };
1664
- }
1665
- }
1666
-
1667
- // Licensed to the .NET Foundation under one or more agreements.
1668
- // The .NET Foundation licenses this file to you under the MIT license.
1669
- // 0, 2, 10, 30 second delays before reconnect attempts.
1670
- const DEFAULT_RETRY_DELAYS_IN_MILLISECONDS = [0, 2000, 10000, 30000, null];
1671
- /** @private */
1672
- class DefaultReconnectPolicy {
1673
- constructor(retryDelays) {
1674
- this._retryDelays = retryDelays !== undefined ? [...retryDelays, null] : DEFAULT_RETRY_DELAYS_IN_MILLISECONDS;
1675
- }
1676
- nextRetryDelayInMilliseconds(retryContext) {
1677
- return this._retryDelays[retryContext.previousRetryCount];
1678
- }
1679
- }
1680
-
1681
- // Licensed to the .NET Foundation under one or more agreements.
1682
- // The .NET Foundation licenses this file to you under the MIT license.
1683
- class HeaderNames {
1684
- }
1685
- HeaderNames.Authorization = "Authorization";
1686
- HeaderNames.Cookie = "Cookie";
1687
-
1688
- // Licensed to the .NET Foundation under one or more agreements.
1689
- // The .NET Foundation licenses this file to you under the MIT license.
1690
- // This will be treated as a bit flag in the future, so we keep it using power-of-two values.
1691
- /** Specifies a specific HTTP transport type. */
1692
- var HttpTransportType;
1693
- (function (HttpTransportType) {
1694
- /** Specifies no transport preference. */
1695
- HttpTransportType[HttpTransportType["None"] = 0] = "None";
1696
- /** Specifies the WebSockets transport. */
1697
- HttpTransportType[HttpTransportType["WebSockets"] = 1] = "WebSockets";
1698
- /** Specifies the Server-Sent Events transport. */
1699
- HttpTransportType[HttpTransportType["ServerSentEvents"] = 2] = "ServerSentEvents";
1700
- /** Specifies the Long Polling transport. */
1701
- HttpTransportType[HttpTransportType["LongPolling"] = 4] = "LongPolling";
1702
- })(HttpTransportType || (HttpTransportType = {}));
1703
- /** Specifies the transfer format for a connection. */
1704
- var TransferFormat;
1705
- (function (TransferFormat) {
1706
- /** Specifies that only text data will be transmitted over the connection. */
1707
- TransferFormat[TransferFormat["Text"] = 1] = "Text";
1708
- /** Specifies that binary data will be transmitted over the connection. */
1709
- TransferFormat[TransferFormat["Binary"] = 2] = "Binary";
1710
- })(TransferFormat || (TransferFormat = {}));
1711
-
1712
- // Licensed to the .NET Foundation under one or more agreements.
1713
- // The .NET Foundation licenses this file to you under the MIT license.
1714
- // Rough polyfill of https://developer.mozilla.org/en-US/docs/Web/API/AbortController
1715
- // We don't actually ever use the API being polyfilled, we always use the polyfill because
1716
- // it's a very new API right now.
1717
- // Not exported from index.
1718
- /** @private */
1719
- class AbortController$1 {
1720
- constructor() {
1721
- this._isAborted = false;
1722
- this.onabort = null;
1723
- }
1724
- abort() {
1725
- if (!this._isAborted) {
1726
- this._isAborted = true;
1727
- if (this.onabort) {
1728
- this.onabort();
1729
- }
1730
- }
1731
- }
1732
- get signal() {
1733
- return this;
1734
- }
1735
- get aborted() {
1736
- return this._isAborted;
1737
- }
1738
- }
1739
-
1740
- // Licensed to the .NET Foundation under one or more agreements.
1741
- // Not exported from 'index', this type is internal.
1742
- /** @private */
1743
- class LongPollingTransport {
1744
- constructor(httpClient, accessTokenFactory, logger, options) {
1745
- this._httpClient = httpClient;
1746
- this._accessTokenFactory = accessTokenFactory;
1747
- this._logger = logger;
1748
- this._pollAbort = new AbortController$1();
1749
- this._options = options;
1750
- this._running = false;
1751
- this.onreceive = null;
1752
- this.onclose = null;
1753
- }
1754
- // This is an internal type, not exported from 'index' so this is really just internal.
1755
- get pollAborted() {
1756
- return this._pollAbort.aborted;
1757
- }
1758
- async connect(url, transferFormat) {
1759
- Arg.isRequired(url, "url");
1760
- Arg.isRequired(transferFormat, "transferFormat");
1761
- Arg.isIn(transferFormat, TransferFormat, "transferFormat");
1762
- this._url = url;
1763
- this._logger.log(LogLevel.Trace, "(LongPolling transport) Connecting.");
1764
- // Allow binary format on Node and Browsers that support binary content (indicated by the presence of responseType property)
1765
- if (transferFormat === TransferFormat.Binary &&
1766
- (typeof XMLHttpRequest !== "undefined" && typeof new XMLHttpRequest().responseType !== "string")) {
1767
- throw new Error("Binary protocols over XmlHttpRequest not implementing advanced features are not supported.");
1768
- }
1769
- const [name, value] = getUserAgentHeader();
1770
- const headers = { [name]: value, ...this._options.headers };
1771
- const pollOptions = {
1772
- abortSignal: this._pollAbort.signal,
1773
- headers,
1774
- timeout: 100000,
1775
- withCredentials: this._options.withCredentials,
1776
- };
1777
- if (transferFormat === TransferFormat.Binary) {
1778
- pollOptions.responseType = "arraybuffer";
1779
- }
1780
- const token = await this._getAccessToken();
1781
- this._updateHeaderToken(pollOptions, token);
1782
- // Make initial long polling request
1783
- // Server uses first long polling request to finish initializing connection and it returns without data
1784
- const pollUrl = `${url}&_=${Date.now()}`;
1785
- this._logger.log(LogLevel.Trace, `(LongPolling transport) polling: ${pollUrl}.`);
1786
- const response = await this._httpClient.get(pollUrl, pollOptions);
1787
- if (response.statusCode !== 200) {
1788
- this._logger.log(LogLevel.Error, `(LongPolling transport) Unexpected response code: ${response.statusCode}.`);
1789
- // Mark running as false so that the poll immediately ends and runs the close logic
1790
- this._closeError = new HttpError(response.statusText || "", response.statusCode);
1791
- this._running = false;
1792
- }
1793
- else {
1794
- this._running = true;
1795
- }
1796
- this._receiving = this._poll(this._url, pollOptions);
1797
- }
1798
- async _getAccessToken() {
1799
- if (this._accessTokenFactory) {
1800
- return await this._accessTokenFactory();
1801
- }
1802
- return null;
1803
- }
1804
- _updateHeaderToken(request, token) {
1805
- if (!request.headers) {
1806
- request.headers = {};
1807
- }
1808
- if (token) {
1809
- request.headers[HeaderNames.Authorization] = `Bearer ${token}`;
1810
- return;
1811
- }
1812
- if (request.headers[HeaderNames.Authorization]) {
1813
- delete request.headers[HeaderNames.Authorization];
1814
- }
1815
- }
1816
- async _poll(url, pollOptions) {
1817
- try {
1818
- while (this._running) {
1819
- // We have to get the access token on each poll, in case it changes
1820
- const token = await this._getAccessToken();
1821
- this._updateHeaderToken(pollOptions, token);
1822
- try {
1823
- const pollUrl = `${url}&_=${Date.now()}`;
1824
- this._logger.log(LogLevel.Trace, `(LongPolling transport) polling: ${pollUrl}.`);
1825
- const response = await this._httpClient.get(pollUrl, pollOptions);
1826
- if (response.statusCode === 204) {
1827
- this._logger.log(LogLevel.Information, "(LongPolling transport) Poll terminated by server.");
1828
- this._running = false;
1829
- }
1830
- else if (response.statusCode !== 200) {
1831
- this._logger.log(LogLevel.Error, `(LongPolling transport) Unexpected response code: ${response.statusCode}.`);
1832
- // Unexpected status code
1833
- this._closeError = new HttpError(response.statusText || "", response.statusCode);
1834
- this._running = false;
1835
- }
1836
- else {
1837
- // Process the response
1838
- if (response.content) {
1839
- this._logger.log(LogLevel.Trace, `(LongPolling transport) data received. ${getDataDetail(response.content, this._options.logMessageContent)}.`);
1840
- if (this.onreceive) {
1841
- this.onreceive(response.content);
1842
- }
1843
- }
1844
- else {
1845
- // This is another way timeout manifest.
1846
- this._logger.log(LogLevel.Trace, "(LongPolling transport) Poll timed out, reissuing.");
1847
- }
1848
- }
1849
- }
1850
- catch (e) {
1851
- if (!this._running) {
1852
- // Log but disregard errors that occur after stopping
1853
- this._logger.log(LogLevel.Trace, `(LongPolling transport) Poll errored after shutdown: ${e.message}`);
1854
- }
1855
- else {
1856
- if (e instanceof TimeoutError) {
1857
- // Ignore timeouts and reissue the poll.
1858
- this._logger.log(LogLevel.Trace, "(LongPolling transport) Poll timed out, reissuing.");
1859
- }
1860
- else {
1861
- // Close the connection with the error as the result.
1862
- this._closeError = e;
1863
- this._running = false;
1864
- }
1865
- }
1866
- }
1867
- }
1868
- }
1869
- finally {
1870
- this._logger.log(LogLevel.Trace, "(LongPolling transport) Polling complete.");
1871
- // We will reach here with pollAborted==false when the server returned a response causing the transport to stop.
1872
- // If pollAborted==true then client initiated the stop and the stop method will raise the close event after DELETE is sent.
1873
- if (!this.pollAborted) {
1874
- this._raiseOnClose();
1875
- }
1876
- }
1877
- }
1878
- async send(data) {
1879
- if (!this._running) {
1880
- return Promise.reject(new Error("Cannot send until the transport is connected"));
1881
- }
1882
- return sendMessage(this._logger, "LongPolling", this._httpClient, this._url, this._accessTokenFactory, data, this._options);
1883
- }
1884
- async stop() {
1885
- this._logger.log(LogLevel.Trace, "(LongPolling transport) Stopping polling.");
1886
- // Tell receiving loop to stop, abort any current request, and then wait for it to finish
1887
- this._running = false;
1888
- this._pollAbort.abort();
1889
- try {
1890
- await this._receiving;
1891
- // Send DELETE to clean up long polling on the server
1892
- this._logger.log(LogLevel.Trace, `(LongPolling transport) sending DELETE request to ${this._url}.`);
1893
- const headers = {};
1894
- const [name, value] = getUserAgentHeader();
1895
- headers[name] = value;
1896
- const deleteOptions = {
1897
- headers: { ...headers, ...this._options.headers },
1898
- timeout: this._options.timeout,
1899
- withCredentials: this._options.withCredentials,
1900
- };
1901
- const token = await this._getAccessToken();
1902
- this._updateHeaderToken(deleteOptions, token);
1903
- await this._httpClient.delete(this._url, deleteOptions);
1904
- this._logger.log(LogLevel.Trace, "(LongPolling transport) DELETE request sent.");
1905
- }
1906
- finally {
1907
- this._logger.log(LogLevel.Trace, "(LongPolling transport) Stop finished.");
1908
- // Raise close event here instead of in polling
1909
- // It needs to happen after the DELETE request is sent
1910
- this._raiseOnClose();
1911
- }
1912
- }
1913
- _raiseOnClose() {
1914
- if (this.onclose) {
1915
- let logMessage = "(LongPolling transport) Firing onclose event.";
1916
- if (this._closeError) {
1917
- logMessage += " Error: " + this._closeError;
1918
- }
1919
- this._logger.log(LogLevel.Trace, logMessage);
1920
- this.onclose(this._closeError);
1921
- }
1922
- }
1923
- }
1924
-
1925
- // Licensed to the .NET Foundation under one or more agreements.
1926
- /** @private */
1927
- class ServerSentEventsTransport {
1928
- constructor(httpClient, accessTokenFactory, logger, options) {
1929
- this._httpClient = httpClient;
1930
- this._accessTokenFactory = accessTokenFactory;
1931
- this._logger = logger;
1932
- this._options = options;
1933
- this.onreceive = null;
1934
- this.onclose = null;
1935
- }
1936
- async connect(url, transferFormat) {
1937
- Arg.isRequired(url, "url");
1938
- Arg.isRequired(transferFormat, "transferFormat");
1939
- Arg.isIn(transferFormat, TransferFormat, "transferFormat");
1940
- this._logger.log(LogLevel.Trace, "(SSE transport) Connecting.");
1941
- // set url before accessTokenFactory because this.url is only for send and we set the auth header instead of the query string for send
1942
- this._url = url;
1943
- if (this._accessTokenFactory) {
1944
- const token = await this._accessTokenFactory();
1945
- if (token) {
1946
- url += (url.indexOf("?") < 0 ? "?" : "&") + `access_token=${encodeURIComponent(token)}`;
1947
- }
1948
- }
1949
- return new Promise((resolve, reject) => {
1950
- let opened = false;
1951
- if (transferFormat !== TransferFormat.Text) {
1952
- reject(new Error("The Server-Sent Events transport only supports the 'Text' transfer format"));
1953
- return;
1954
- }
1955
- let eventSource;
1956
- if (Platform.isBrowser || Platform.isWebWorker) {
1957
- eventSource = new this._options.EventSource(url, { withCredentials: this._options.withCredentials });
1958
- }
1959
- else {
1960
- // Non-browser passes cookies via the dictionary
1961
- const cookies = this._httpClient.getCookieString(url);
1962
- const headers = {};
1963
- headers.Cookie = cookies;
1964
- const [name, value] = getUserAgentHeader();
1965
- headers[name] = value;
1966
- eventSource = new this._options.EventSource(url, { withCredentials: this._options.withCredentials, headers: { ...headers, ...this._options.headers } });
1967
- }
1968
- try {
1969
- eventSource.onmessage = (e) => {
1970
- if (this.onreceive) {
1971
- try {
1972
- this._logger.log(LogLevel.Trace, `(SSE transport) data received. ${getDataDetail(e.data, this._options.logMessageContent)}.`);
1973
- this.onreceive(e.data);
1974
- }
1975
- catch (error) {
1976
- this._close(error);
1977
- return;
1978
- }
1979
- }
1980
- };
1981
- // @ts-ignore: not using event on purpose
1982
- eventSource.onerror = (e) => {
1983
- // EventSource doesn't give any useful information about server side closes.
1984
- if (opened) {
1985
- this._close();
1986
- }
1987
- else {
1988
- reject(new Error("EventSource failed to connect. The connection could not be found on the server,"
1989
- + " either the connection ID is not present on the server, or a proxy is refusing/buffering the connection."
1990
- + " If you have multiple servers check that sticky sessions are enabled."));
1991
- }
1992
- };
1993
- eventSource.onopen = () => {
1994
- this._logger.log(LogLevel.Information, `SSE connected to ${this._url}`);
1995
- this._eventSource = eventSource;
1996
- opened = true;
1997
- resolve();
1998
- };
1999
- }
2000
- catch (e) {
2001
- reject(e);
2002
- return;
2003
- }
2004
- });
2005
- }
2006
- async send(data) {
2007
- if (!this._eventSource) {
2008
- return Promise.reject(new Error("Cannot send until the transport is connected"));
2009
- }
2010
- return sendMessage(this._logger, "SSE", this._httpClient, this._url, this._accessTokenFactory, data, this._options);
2011
- }
2012
- stop() {
2013
- this._close();
2014
- return Promise.resolve();
2015
- }
2016
- _close(e) {
2017
- if (this._eventSource) {
2018
- this._eventSource.close();
2019
- this._eventSource = undefined;
2020
- if (this.onclose) {
2021
- this.onclose(e);
2022
- }
2023
- }
2024
- }
2025
- }
2026
-
2027
- // Licensed to the .NET Foundation under one or more agreements.
2028
- /** @private */
2029
- class WebSocketTransport {
2030
- constructor(httpClient, accessTokenFactory, logger, logMessageContent, webSocketConstructor, headers) {
2031
- this._logger = logger;
2032
- this._accessTokenFactory = accessTokenFactory;
2033
- this._logMessageContent = logMessageContent;
2034
- this._webSocketConstructor = webSocketConstructor;
2035
- this._httpClient = httpClient;
2036
- this.onreceive = null;
2037
- this.onclose = null;
2038
- this._headers = headers;
2039
- }
2040
- async connect(url, transferFormat) {
2041
- Arg.isRequired(url, "url");
2042
- Arg.isRequired(transferFormat, "transferFormat");
2043
- Arg.isIn(transferFormat, TransferFormat, "transferFormat");
2044
- this._logger.log(LogLevel.Trace, "(WebSockets transport) Connecting.");
2045
- if (this._accessTokenFactory) {
2046
- const token = await this._accessTokenFactory();
2047
- if (token) {
2048
- url += (url.indexOf("?") < 0 ? "?" : "&") + `access_token=${encodeURIComponent(token)}`;
2049
- }
2050
- }
2051
- return new Promise((resolve, reject) => {
2052
- url = url.replace(/^http/, "ws");
2053
- let webSocket;
2054
- const cookies = this._httpClient.getCookieString(url);
2055
- let opened = false;
2056
- if (Platform.isNode) {
2057
- const headers = {};
2058
- const [name, value] = getUserAgentHeader();
2059
- headers[name] = value;
2060
- if (cookies) {
2061
- headers[HeaderNames.Cookie] = `${cookies}`;
2062
- }
2063
- // Only pass headers when in non-browser environments
2064
- webSocket = new this._webSocketConstructor(url, undefined, {
2065
- headers: { ...headers, ...this._headers },
2066
- });
2067
- }
2068
- if (!webSocket) {
2069
- // Chrome is not happy with passing 'undefined' as protocol
2070
- webSocket = new this._webSocketConstructor(url);
2071
- }
2072
- if (transferFormat === TransferFormat.Binary) {
2073
- webSocket.binaryType = "arraybuffer";
2074
- }
2075
- webSocket.onopen = (_event) => {
2076
- this._logger.log(LogLevel.Information, `WebSocket connected to ${url}.`);
2077
- this._webSocket = webSocket;
2078
- opened = true;
2079
- resolve();
2080
- };
2081
- webSocket.onerror = (event) => {
2082
- let error = null;
2083
- // ErrorEvent is a browser only type we need to check if the type exists before using it
2084
- if (typeof ErrorEvent !== "undefined" && event instanceof ErrorEvent) {
2085
- error = event.error;
2086
- }
2087
- else {
2088
- error = "There was an error with the transport";
2089
- }
2090
- this._logger.log(LogLevel.Information, `(WebSockets transport) ${error}.`);
2091
- };
2092
- webSocket.onmessage = (message) => {
2093
- this._logger.log(LogLevel.Trace, `(WebSockets transport) data received. ${getDataDetail(message.data, this._logMessageContent)}.`);
2094
- if (this.onreceive) {
2095
- try {
2096
- this.onreceive(message.data);
2097
- }
2098
- catch (error) {
2099
- this._close(error);
2100
- return;
2101
- }
2102
- }
2103
- };
2104
- webSocket.onclose = (event) => {
2105
- // Don't call close handler if connection was never established
2106
- // We'll reject the connect call instead
2107
- if (opened) {
2108
- this._close(event);
2109
- }
2110
- else {
2111
- let error = null;
2112
- // ErrorEvent is a browser only type we need to check if the type exists before using it
2113
- if (typeof ErrorEvent !== "undefined" && event instanceof ErrorEvent) {
2114
- error = event.error;
2115
- }
2116
- else {
2117
- error = "WebSocket failed to connect. The connection could not be found on the server,"
2118
- + " either the endpoint may not be a SignalR endpoint,"
2119
- + " the connection ID is not present on the server, or there is a proxy blocking WebSockets."
2120
- + " If you have multiple servers check that sticky sessions are enabled.";
2121
- }
2122
- reject(new Error(error));
2123
- }
2124
- };
2125
- });
2126
- }
2127
- send(data) {
2128
- if (this._webSocket && this._webSocket.readyState === this._webSocketConstructor.OPEN) {
2129
- this._logger.log(LogLevel.Trace, `(WebSockets transport) sending data. ${getDataDetail(data, this._logMessageContent)}.`);
2130
- this._webSocket.send(data);
2131
- return Promise.resolve();
2132
- }
2133
- return Promise.reject("WebSocket is not in the OPEN state");
2134
- }
2135
- stop() {
2136
- if (this._webSocket) {
2137
- // Manually invoke onclose callback inline so we know the HttpConnection was closed properly before returning
2138
- // This also solves an issue where websocket.onclose could take 18+ seconds to trigger during network disconnects
2139
- this._close(undefined);
2140
- }
2141
- return Promise.resolve();
2142
- }
2143
- _close(event) {
2144
- // webSocket will be null if the transport did not start successfully
2145
- if (this._webSocket) {
2146
- // Clear websocket handlers because we are considering the socket closed now
2147
- this._webSocket.onclose = () => { };
2148
- this._webSocket.onmessage = () => { };
2149
- this._webSocket.onerror = () => { };
2150
- this._webSocket.close();
2151
- this._webSocket = undefined;
2152
- }
2153
- this._logger.log(LogLevel.Trace, "(WebSockets transport) socket closed.");
2154
- if (this.onclose) {
2155
- if (this._isCloseEvent(event) && (event.wasClean === false || event.code !== 1000)) {
2156
- this.onclose(new Error(`WebSocket closed with status code: ${event.code} (${event.reason || "no reason given"}).`));
2157
- }
2158
- else if (event instanceof Error) {
2159
- this.onclose(event);
2160
- }
2161
- else {
2162
- this.onclose();
2163
- }
2164
- }
2165
- }
2166
- _isCloseEvent(event) {
2167
- return event && typeof event.wasClean === "boolean" && typeof event.code === "number";
2168
- }
2169
- }
2170
-
2171
- // Licensed to the .NET Foundation under one or more agreements.
2172
- const MAX_REDIRECTS = 100;
2173
- /** @private */
2174
- class HttpConnection {
2175
- constructor(url, options = {}) {
2176
- this._stopPromiseResolver = () => { };
2177
- this.features = {};
2178
- this._negotiateVersion = 1;
2179
- Arg.isRequired(url, "url");
2180
- this._logger = createLogger(options.logger);
2181
- this.baseUrl = this._resolveUrl(url);
2182
- options = options || {};
2183
- options.logMessageContent = options.logMessageContent === undefined ? false : options.logMessageContent;
2184
- if (typeof options.withCredentials === "boolean" || options.withCredentials === undefined) {
2185
- options.withCredentials = options.withCredentials === undefined ? true : options.withCredentials;
2186
- }
2187
- else {
2188
- throw new Error("withCredentials option was not a 'boolean' or 'undefined' value");
2189
- }
2190
- options.timeout = options.timeout === undefined ? 100 * 1000 : options.timeout;
2191
- let webSocketModule = null;
2192
- let eventSourceModule = null;
2193
- if (Platform.isNode && typeof require !== "undefined") {
2194
- // In order to ignore the dynamic require in webpack builds we need to do this magic
2195
- // @ts-ignore: TS doesn't know about these names
2196
- const requireFunc = typeof __webpack_require__ === "function" ? __non_webpack_require__ : require;
2197
- webSocketModule = requireFunc("ws");
2198
- eventSourceModule = requireFunc("eventsource");
2199
- }
2200
- if (!Platform.isNode && typeof WebSocket !== "undefined" && !options.WebSocket) {
2201
- options.WebSocket = WebSocket;
2202
- }
2203
- else if (Platform.isNode && !options.WebSocket) {
2204
- if (webSocketModule) {
2205
- options.WebSocket = webSocketModule;
2206
- }
2207
- }
2208
- if (!Platform.isNode && typeof EventSource !== "undefined" && !options.EventSource) {
2209
- options.EventSource = EventSource;
2210
- }
2211
- else if (Platform.isNode && !options.EventSource) {
2212
- if (typeof eventSourceModule !== "undefined") {
2213
- options.EventSource = eventSourceModule;
2214
- }
2215
- }
2216
- this._httpClient = options.httpClient || new DefaultHttpClient(this._logger);
2217
- this._connectionState = "Disconnected" /* Disconnected */;
2218
- this._connectionStarted = false;
2219
- this._options = options;
2220
- this.onreceive = null;
2221
- this.onclose = null;
2222
- }
2223
- async start(transferFormat) {
2224
- transferFormat = transferFormat || TransferFormat.Binary;
2225
- Arg.isIn(transferFormat, TransferFormat, "transferFormat");
2226
- this._logger.log(LogLevel.Debug, `Starting connection with transfer format '${TransferFormat[transferFormat]}'.`);
2227
- if (this._connectionState !== "Disconnected" /* Disconnected */) {
2228
- return Promise.reject(new Error("Cannot start an HttpConnection that is not in the 'Disconnected' state."));
2229
- }
2230
- this._connectionState = "Connecting" /* Connecting */;
2231
- this._startInternalPromise = this._startInternal(transferFormat);
2232
- await this._startInternalPromise;
2233
- // The TypeScript compiler thinks that connectionState must be Connecting here. The TypeScript compiler is wrong.
2234
- if (this._connectionState === "Disconnecting" /* Disconnecting */) {
2235
- // stop() was called and transitioned the client into the Disconnecting state.
2236
- const message = "Failed to start the HttpConnection before stop() was called.";
2237
- this._logger.log(LogLevel.Error, message);
2238
- // We cannot await stopPromise inside startInternal since stopInternal awaits the startInternalPromise.
2239
- await this._stopPromise;
2240
- return Promise.reject(new Error(message));
2241
- }
2242
- else if (this._connectionState !== "Connected" /* Connected */) {
2243
- // stop() was called and transitioned the client into the Disconnecting state.
2244
- const message = "HttpConnection.startInternal completed gracefully but didn't enter the connection into the connected state!";
2245
- this._logger.log(LogLevel.Error, message);
2246
- return Promise.reject(new Error(message));
2247
- }
2248
- this._connectionStarted = true;
2249
- }
2250
- send(data) {
2251
- if (this._connectionState !== "Connected" /* Connected */) {
2252
- return Promise.reject(new Error("Cannot send data if the connection is not in the 'Connected' State."));
2253
- }
2254
- if (!this._sendQueue) {
2255
- this._sendQueue = new TransportSendQueue(this.transport);
2256
- }
2257
- // Transport will not be null if state is connected
2258
- return this._sendQueue.send(data);
2259
- }
2260
- async stop(error) {
2261
- if (this._connectionState === "Disconnected" /* Disconnected */) {
2262
- this._logger.log(LogLevel.Debug, `Call to HttpConnection.stop(${error}) ignored because the connection is already in the disconnected state.`);
2263
- return Promise.resolve();
2264
- }
2265
- if (this._connectionState === "Disconnecting" /* Disconnecting */) {
2266
- this._logger.log(LogLevel.Debug, `Call to HttpConnection.stop(${error}) ignored because the connection is already in the disconnecting state.`);
2267
- return this._stopPromise;
2268
- }
2269
- this._connectionState = "Disconnecting" /* Disconnecting */;
2270
- this._stopPromise = new Promise((resolve) => {
2271
- // Don't complete stop() until stopConnection() completes.
2272
- this._stopPromiseResolver = resolve;
2273
- });
2274
- // stopInternal should never throw so just observe it.
2275
- await this._stopInternal(error);
2276
- await this._stopPromise;
2277
- }
2278
- async _stopInternal(error) {
2279
- // Set error as soon as possible otherwise there is a race between
2280
- // the transport closing and providing an error and the error from a close message
2281
- // We would prefer the close message error.
2282
- this._stopError = error;
2283
- try {
2284
- await this._startInternalPromise;
2285
- }
2286
- catch (e) {
2287
- // This exception is returned to the user as a rejected Promise from the start method.
2288
- }
2289
- // The transport's onclose will trigger stopConnection which will run our onclose event.
2290
- // The transport should always be set if currently connected. If it wasn't set, it's likely because
2291
- // stop was called during start() and start() failed.
2292
- if (this.transport) {
2293
- try {
2294
- await this.transport.stop();
2295
- }
2296
- catch (e) {
2297
- this._logger.log(LogLevel.Error, `HttpConnection.transport.stop() threw error '${e}'.`);
2298
- this._stopConnection();
2299
- }
2300
- this.transport = undefined;
2301
- }
2302
- else {
2303
- this._logger.log(LogLevel.Debug, "HttpConnection.transport is undefined in HttpConnection.stop() because start() failed.");
2304
- }
2305
- }
2306
- async _startInternal(transferFormat) {
2307
- // Store the original base url and the access token factory since they may change
2308
- // as part of negotiating
2309
- let url = this.baseUrl;
2310
- this._accessTokenFactory = this._options.accessTokenFactory;
2311
- try {
2312
- if (this._options.skipNegotiation) {
2313
- if (this._options.transport === HttpTransportType.WebSockets) {
2314
- // No need to add a connection ID in this case
2315
- this.transport = this._constructTransport(HttpTransportType.WebSockets);
2316
- // We should just call connect directly in this case.
2317
- // No fallback or negotiate in this case.
2318
- await this._startTransport(url, transferFormat);
2319
- }
2320
- else {
2321
- throw new Error("Negotiation can only be skipped when using the WebSocket transport directly.");
2322
- }
2323
- }
2324
- else {
2325
- let negotiateResponse = null;
2326
- let redirects = 0;
2327
- do {
2328
- negotiateResponse = await this._getNegotiationResponse(url);
2329
- // the user tries to stop the connection when it is being started
2330
- if (this._connectionState === "Disconnecting" /* Disconnecting */ || this._connectionState === "Disconnected" /* Disconnected */) {
2331
- throw new Error("The connection was stopped during negotiation.");
2332
- }
2333
- if (negotiateResponse.error) {
2334
- throw new Error(negotiateResponse.error);
2335
- }
2336
- if (negotiateResponse.ProtocolVersion) {
2337
- throw new Error("Detected a connection attempt to an ASP.NET SignalR Server. This client only supports connecting to an ASP.NET Core SignalR Server. See https://aka.ms/signalr-core-differences for details.");
2338
- }
2339
- if (negotiateResponse.url) {
2340
- url = negotiateResponse.url;
2341
- }
2342
- if (negotiateResponse.accessToken) {
2343
- // Replace the current access token factory with one that uses
2344
- // the returned access token
2345
- const accessToken = negotiateResponse.accessToken;
2346
- this._accessTokenFactory = () => accessToken;
2347
- }
2348
- redirects++;
2349
- } while (negotiateResponse.url && redirects < MAX_REDIRECTS);
2350
- if (redirects === MAX_REDIRECTS && negotiateResponse.url) {
2351
- throw new Error("Negotiate redirection limit exceeded.");
2352
- }
2353
- await this._createTransport(url, this._options.transport, negotiateResponse, transferFormat);
2354
- }
2355
- if (this.transport instanceof LongPollingTransport) {
2356
- this.features.inherentKeepAlive = true;
2357
- }
2358
- if (this._connectionState === "Connecting" /* Connecting */) {
2359
- // Ensure the connection transitions to the connected state prior to completing this.startInternalPromise.
2360
- // start() will handle the case when stop was called and startInternal exits still in the disconnecting state.
2361
- this._logger.log(LogLevel.Debug, "The HttpConnection connected successfully.");
2362
- this._connectionState = "Connected" /* Connected */;
2363
- }
2364
- // stop() is waiting on us via this.startInternalPromise so keep this.transport around so it can clean up.
2365
- // This is the only case startInternal can exit in neither the connected nor disconnected state because stopConnection()
2366
- // will transition to the disconnected state. start() will wait for the transition using the stopPromise.
2367
- }
2368
- catch (e) {
2369
- this._logger.log(LogLevel.Error, "Failed to start the connection: " + e);
2370
- this._connectionState = "Disconnected" /* Disconnected */;
2371
- this.transport = undefined;
2372
- // if start fails, any active calls to stop assume that start will complete the stop promise
2373
- this._stopPromiseResolver();
2374
- return Promise.reject(e);
2375
- }
2376
- }
2377
- async _getNegotiationResponse(url) {
2378
- const headers = {};
2379
- if (this._accessTokenFactory) {
2380
- const token = await this._accessTokenFactory();
2381
- if (token) {
2382
- headers[HeaderNames.Authorization] = `Bearer ${token}`;
2383
- }
2384
- }
2385
- const [name, value] = getUserAgentHeader();
2386
- headers[name] = value;
2387
- const negotiateUrl = this._resolveNegotiateUrl(url);
2388
- this._logger.log(LogLevel.Debug, `Sending negotiation request: ${negotiateUrl}.`);
2389
- try {
2390
- const response = await this._httpClient.post(negotiateUrl, {
2391
- content: "",
2392
- headers: { ...headers, ...this._options.headers },
2393
- timeout: this._options.timeout,
2394
- withCredentials: this._options.withCredentials,
2395
- });
2396
- if (response.statusCode !== 200) {
2397
- return Promise.reject(new Error(`Unexpected status code returned from negotiate '${response.statusCode}'`));
2398
- }
2399
- const negotiateResponse = JSON.parse(response.content);
2400
- if (!negotiateResponse.negotiateVersion || negotiateResponse.negotiateVersion < 1) {
2401
- // Negotiate version 0 doesn't use connectionToken
2402
- // So we set it equal to connectionId so all our logic can use connectionToken without being aware of the negotiate version
2403
- negotiateResponse.connectionToken = negotiateResponse.connectionId;
2404
- }
2405
- return negotiateResponse;
2406
- }
2407
- catch (e) {
2408
- let errorMessage = "Failed to complete negotiation with the server: " + e;
2409
- if (e instanceof HttpError) {
2410
- if (e.statusCode === 404) {
2411
- errorMessage = errorMessage + " Either this is not a SignalR endpoint or there is a proxy blocking the connection.";
2412
- }
2413
- }
2414
- this._logger.log(LogLevel.Error, errorMessage);
2415
- return Promise.reject(new FailedToNegotiateWithServerError(errorMessage));
2416
- }
2417
- }
2418
- _createConnectUrl(url, connectionToken) {
2419
- if (!connectionToken) {
2420
- return url;
2421
- }
2422
- return url + (url.indexOf("?") === -1 ? "?" : "&") + `id=${connectionToken}`;
2423
- }
2424
- async _createTransport(url, requestedTransport, negotiateResponse, requestedTransferFormat) {
2425
- let connectUrl = this._createConnectUrl(url, negotiateResponse.connectionToken);
2426
- if (this._isITransport(requestedTransport)) {
2427
- this._logger.log(LogLevel.Debug, "Connection was provided an instance of ITransport, using that directly.");
2428
- this.transport = requestedTransport;
2429
- await this._startTransport(connectUrl, requestedTransferFormat);
2430
- this.connectionId = negotiateResponse.connectionId;
2431
- return;
2432
- }
2433
- const transportExceptions = [];
2434
- const transports = negotiateResponse.availableTransports || [];
2435
- let negotiate = negotiateResponse;
2436
- for (const endpoint of transports) {
2437
- const transportOrError = this._resolveTransportOrError(endpoint, requestedTransport, requestedTransferFormat);
2438
- if (transportOrError instanceof Error) {
2439
- // Store the error and continue, we don't want to cause a re-negotiate in these cases
2440
- transportExceptions.push(`${endpoint.transport} failed:`);
2441
- transportExceptions.push(transportOrError);
2442
- }
2443
- else if (this._isITransport(transportOrError)) {
2444
- this.transport = transportOrError;
2445
- if (!negotiate) {
2446
- try {
2447
- negotiate = await this._getNegotiationResponse(url);
2448
- }
2449
- catch (ex) {
2450
- return Promise.reject(ex);
2451
- }
2452
- connectUrl = this._createConnectUrl(url, negotiate.connectionToken);
2453
- }
2454
- try {
2455
- await this._startTransport(connectUrl, requestedTransferFormat);
2456
- this.connectionId = negotiate.connectionId;
2457
- return;
2458
- }
2459
- catch (ex) {
2460
- this._logger.log(LogLevel.Error, `Failed to start the transport '${endpoint.transport}': ${ex}`);
2461
- negotiate = undefined;
2462
- transportExceptions.push(new FailedToStartTransportError(`${endpoint.transport} failed: ${ex}`, HttpTransportType[endpoint.transport]));
2463
- if (this._connectionState !== "Connecting" /* Connecting */) {
2464
- const message = "Failed to select transport before stop() was called.";
2465
- this._logger.log(LogLevel.Debug, message);
2466
- return Promise.reject(new Error(message));
2467
- }
2468
- }
2469
- }
2470
- }
2471
- if (transportExceptions.length > 0) {
2472
- return Promise.reject(new AggregateErrors(`Unable to connect to the server with any of the available transports. ${transportExceptions.join(" ")}`, transportExceptions));
2473
- }
2474
- return Promise.reject(new Error("None of the transports supported by the client are supported by the server."));
2475
- }
2476
- _constructTransport(transport) {
2477
- switch (transport) {
2478
- case HttpTransportType.WebSockets:
2479
- if (!this._options.WebSocket) {
2480
- throw new Error("'WebSocket' is not supported in your environment.");
2481
- }
2482
- return new WebSocketTransport(this._httpClient, this._accessTokenFactory, this._logger, this._options.logMessageContent, this._options.WebSocket, this._options.headers || {});
2483
- case HttpTransportType.ServerSentEvents:
2484
- if (!this._options.EventSource) {
2485
- throw new Error("'EventSource' is not supported in your environment.");
2486
- }
2487
- return new ServerSentEventsTransport(this._httpClient, this._accessTokenFactory, this._logger, this._options);
2488
- case HttpTransportType.LongPolling:
2489
- return new LongPollingTransport(this._httpClient, this._accessTokenFactory, this._logger, this._options);
2490
- default:
2491
- throw new Error(`Unknown transport: ${transport}.`);
2492
- }
2493
- }
2494
- _startTransport(url, transferFormat) {
2495
- this.transport.onreceive = this.onreceive;
2496
- this.transport.onclose = (e) => this._stopConnection(e);
2497
- return this.transport.connect(url, transferFormat);
2498
- }
2499
- _resolveTransportOrError(endpoint, requestedTransport, requestedTransferFormat) {
2500
- const transport = HttpTransportType[endpoint.transport];
2501
- if (transport === null || transport === undefined) {
2502
- this._logger.log(LogLevel.Debug, `Skipping transport '${endpoint.transport}' because it is not supported by this client.`);
2503
- return new Error(`Skipping transport '${endpoint.transport}' because it is not supported by this client.`);
2504
- }
2505
- else {
2506
- if (transportMatches(requestedTransport, transport)) {
2507
- const transferFormats = endpoint.transferFormats.map((s) => TransferFormat[s]);
2508
- if (transferFormats.indexOf(requestedTransferFormat) >= 0) {
2509
- if ((transport === HttpTransportType.WebSockets && !this._options.WebSocket) ||
2510
- (transport === HttpTransportType.ServerSentEvents && !this._options.EventSource)) {
2511
- this._logger.log(LogLevel.Debug, `Skipping transport '${HttpTransportType[transport]}' because it is not supported in your environment.'`);
2512
- return new UnsupportedTransportError(`'${HttpTransportType[transport]}' is not supported in your environment.`, transport);
2513
- }
2514
- else {
2515
- this._logger.log(LogLevel.Debug, `Selecting transport '${HttpTransportType[transport]}'.`);
2516
- try {
2517
- return this._constructTransport(transport);
2518
- }
2519
- catch (ex) {
2520
- return ex;
2521
- }
2522
- }
2523
- }
2524
- else {
2525
- this._logger.log(LogLevel.Debug, `Skipping transport '${HttpTransportType[transport]}' because it does not support the requested transfer format '${TransferFormat[requestedTransferFormat]}'.`);
2526
- return new Error(`'${HttpTransportType[transport]}' does not support ${TransferFormat[requestedTransferFormat]}.`);
2527
- }
2528
- }
2529
- else {
2530
- this._logger.log(LogLevel.Debug, `Skipping transport '${HttpTransportType[transport]}' because it was disabled by the client.`);
2531
- return new DisabledTransportError(`'${HttpTransportType[transport]}' is disabled by the client.`, transport);
2532
- }
2533
- }
2534
- }
2535
- _isITransport(transport) {
2536
- return transport && typeof (transport) === "object" && "connect" in transport;
2537
- }
2538
- _stopConnection(error) {
2539
- this._logger.log(LogLevel.Debug, `HttpConnection.stopConnection(${error}) called while in state ${this._connectionState}.`);
2540
- this.transport = undefined;
2541
- // If we have a stopError, it takes precedence over the error from the transport
2542
- error = this._stopError || error;
2543
- this._stopError = undefined;
2544
- if (this._connectionState === "Disconnected" /* Disconnected */) {
2545
- this._logger.log(LogLevel.Debug, `Call to HttpConnection.stopConnection(${error}) was ignored because the connection is already in the disconnected state.`);
2546
- return;
2547
- }
2548
- if (this._connectionState === "Connecting" /* Connecting */) {
2549
- this._logger.log(LogLevel.Warning, `Call to HttpConnection.stopConnection(${error}) was ignored because the connection is still in the connecting state.`);
2550
- throw new Error(`HttpConnection.stopConnection(${error}) was called while the connection is still in the connecting state.`);
2551
- }
2552
- if (this._connectionState === "Disconnecting" /* Disconnecting */) {
2553
- // A call to stop() induced this call to stopConnection and needs to be completed.
2554
- // Any stop() awaiters will be scheduled to continue after the onclose callback fires.
2555
- this._stopPromiseResolver();
2556
- }
2557
- if (error) {
2558
- this._logger.log(LogLevel.Error, `Connection disconnected with error '${error}'.`);
2559
- }
2560
- else {
2561
- this._logger.log(LogLevel.Information, "Connection disconnected.");
2562
- }
2563
- if (this._sendQueue) {
2564
- this._sendQueue.stop().catch((e) => {
2565
- this._logger.log(LogLevel.Error, `TransportSendQueue.stop() threw error '${e}'.`);
2566
- });
2567
- this._sendQueue = undefined;
2568
- }
2569
- this.connectionId = undefined;
2570
- this._connectionState = "Disconnected" /* Disconnected */;
2571
- if (this._connectionStarted) {
2572
- this._connectionStarted = false;
2573
- try {
2574
- if (this.onclose) {
2575
- this.onclose(error);
2576
- }
2577
- }
2578
- catch (e) {
2579
- this._logger.log(LogLevel.Error, `HttpConnection.onclose(${error}) threw error '${e}'.`);
2580
- }
2581
- }
2582
- }
2583
- _resolveUrl(url) {
2584
- // startsWith is not supported in IE
2585
- if (url.lastIndexOf("https://", 0) === 0 || url.lastIndexOf("http://", 0) === 0) {
2586
- return url;
2587
- }
2588
- if (!Platform.isBrowser) {
2589
- throw new Error(`Cannot resolve '${url}'.`);
2590
- }
2591
- // Setting the url to the href propery of an anchor tag handles normalization
2592
- // for us. There are 3 main cases.
2593
- // 1. Relative path normalization e.g "b" -> "http://localhost:5000/a/b"
2594
- // 2. Absolute path normalization e.g "/a/b" -> "http://localhost:5000/a/b"
2595
- // 3. Networkpath reference normalization e.g "//localhost:5000/a/b" -> "http://localhost:5000/a/b"
2596
- const aTag = window.document.createElement("a");
2597
- aTag.href = url;
2598
- this._logger.log(LogLevel.Information, `Normalizing '${url}' to '${aTag.href}'.`);
2599
- return aTag.href;
2600
- }
2601
- _resolveNegotiateUrl(url) {
2602
- const index = url.indexOf("?");
2603
- let negotiateUrl = url.substring(0, index === -1 ? url.length : index);
2604
- if (negotiateUrl[negotiateUrl.length - 1] !== "/") {
2605
- negotiateUrl += "/";
2606
- }
2607
- negotiateUrl += "negotiate";
2608
- negotiateUrl += index === -1 ? "" : url.substring(index);
2609
- if (negotiateUrl.indexOf("negotiateVersion") === -1) {
2610
- negotiateUrl += index === -1 ? "?" : "&";
2611
- negotiateUrl += "negotiateVersion=" + this._negotiateVersion;
2612
- }
2613
- return negotiateUrl;
2614
- }
2615
- }
2616
- function transportMatches(requestedTransport, actualTransport) {
2617
- return !requestedTransport || ((actualTransport & requestedTransport) !== 0);
2618
- }
2619
- /** @private */
2620
- class TransportSendQueue {
2621
- constructor(_transport) {
2622
- this._transport = _transport;
2623
- this._buffer = [];
2624
- this._executing = true;
2625
- this._sendBufferedData = new PromiseSource();
2626
- this._transportResult = new PromiseSource();
2627
- this._sendLoopPromise = this._sendLoop();
2628
- }
2629
- send(data) {
2630
- this._bufferData(data);
2631
- if (!this._transportResult) {
2632
- this._transportResult = new PromiseSource();
2633
- }
2634
- return this._transportResult.promise;
2635
- }
2636
- stop() {
2637
- this._executing = false;
2638
- this._sendBufferedData.resolve();
2639
- return this._sendLoopPromise;
2640
- }
2641
- _bufferData(data) {
2642
- if (this._buffer.length && typeof (this._buffer[0]) !== typeof (data)) {
2643
- throw new Error(`Expected data to be of type ${typeof (this._buffer)} but was of type ${typeof (data)}`);
2644
- }
2645
- this._buffer.push(data);
2646
- this._sendBufferedData.resolve();
2647
- }
2648
- async _sendLoop() {
2649
- while (true) {
2650
- await this._sendBufferedData.promise;
2651
- if (!this._executing) {
2652
- if (this._transportResult) {
2653
- this._transportResult.reject("Connection stopped.");
2654
- }
2655
- break;
2656
- }
2657
- this._sendBufferedData = new PromiseSource();
2658
- const transportResult = this._transportResult;
2659
- this._transportResult = undefined;
2660
- const data = typeof (this._buffer[0]) === "string" ?
2661
- this._buffer.join("") :
2662
- TransportSendQueue._concatBuffers(this._buffer);
2663
- this._buffer.length = 0;
2664
- try {
2665
- await this._transport.send(data);
2666
- transportResult.resolve();
2667
- }
2668
- catch (error) {
2669
- transportResult.reject(error);
2670
- }
2671
- }
2672
- }
2673
- static _concatBuffers(arrayBuffers) {
2674
- const totalLength = arrayBuffers.map((b) => b.byteLength).reduce((a, b) => a + b);
2675
- const result = new Uint8Array(totalLength);
2676
- let offset = 0;
2677
- for (const item of arrayBuffers) {
2678
- result.set(new Uint8Array(item), offset);
2679
- offset += item.byteLength;
2680
- }
2681
- return result.buffer;
2682
- }
2683
- }
2684
- class PromiseSource {
2685
- constructor() {
2686
- this.promise = new Promise((resolve, reject) => [this._resolver, this._rejecter] = [resolve, reject]);
2687
- }
2688
- resolve() {
2689
- this._resolver();
2690
- }
2691
- reject(reason) {
2692
- this._rejecter(reason);
2693
- }
2694
- }
2695
-
2696
- // Licensed to the .NET Foundation under one or more agreements.
2697
- const JSON_HUB_PROTOCOL_NAME = "json";
2698
- /** Implements the JSON Hub Protocol. */
2699
- class JsonHubProtocol {
2700
- constructor() {
2701
- /** @inheritDoc */
2702
- this.name = JSON_HUB_PROTOCOL_NAME;
2703
- /** @inheritDoc */
2704
- this.version = 1;
2705
- /** @inheritDoc */
2706
- this.transferFormat = TransferFormat.Text;
2707
- }
2708
- /** Creates an array of {@link @microsoft/signalr.HubMessage} objects from the specified serialized representation.
2709
- *
2710
- * @param {string} input A string containing the serialized representation.
2711
- * @param {ILogger} logger A logger that will be used to log messages that occur during parsing.
2712
- */
2713
- parseMessages(input, logger) {
2714
- // The interface does allow "ArrayBuffer" to be passed in, but this implementation does not. So let's throw a useful error.
2715
- if (typeof input !== "string") {
2716
- throw new Error("Invalid input for JSON hub protocol. Expected a string.");
2717
- }
2718
- if (!input) {
2719
- return [];
2720
- }
2721
- if (logger === null) {
2722
- logger = NullLogger.instance;
2723
- }
2724
- // Parse the messages
2725
- const messages = TextMessageFormat.parse(input);
2726
- const hubMessages = [];
2727
- for (const message of messages) {
2728
- const parsedMessage = JSON.parse(message);
2729
- if (typeof parsedMessage.type !== "number") {
2730
- throw new Error("Invalid payload.");
2731
- }
2732
- switch (parsedMessage.type) {
2733
- case MessageType.Invocation:
2734
- this._isInvocationMessage(parsedMessage);
2735
- break;
2736
- case MessageType.StreamItem:
2737
- this._isStreamItemMessage(parsedMessage);
2738
- break;
2739
- case MessageType.Completion:
2740
- this._isCompletionMessage(parsedMessage);
2741
- break;
2742
- case MessageType.Ping:
2743
- // Single value, no need to validate
2744
- break;
2745
- case MessageType.Close:
2746
- // All optional values, no need to validate
2747
- break;
2748
- default:
2749
- // Future protocol changes can add message types, old clients can ignore them
2750
- logger.log(LogLevel.Information, "Unknown message type '" + parsedMessage.type + "' ignored.");
2751
- continue;
2752
- }
2753
- hubMessages.push(parsedMessage);
2754
- }
2755
- return hubMessages;
2756
- }
2757
- /** Writes the specified {@link @microsoft/signalr.HubMessage} to a string and returns it.
2758
- *
2759
- * @param {HubMessage} message The message to write.
2760
- * @returns {string} A string containing the serialized representation of the message.
2761
- */
2762
- writeMessage(message) {
2763
- return TextMessageFormat.write(JSON.stringify(message));
2764
- }
2765
- _isInvocationMessage(message) {
2766
- this._assertNotEmptyString(message.target, "Invalid payload for Invocation message.");
2767
- if (message.invocationId !== undefined) {
2768
- this._assertNotEmptyString(message.invocationId, "Invalid payload for Invocation message.");
2769
- }
2770
- }
2771
- _isStreamItemMessage(message) {
2772
- this._assertNotEmptyString(message.invocationId, "Invalid payload for StreamItem message.");
2773
- if (message.item === undefined) {
2774
- throw new Error("Invalid payload for StreamItem message.");
2775
- }
2776
- }
2777
- _isCompletionMessage(message) {
2778
- if (message.result && message.error) {
2779
- throw new Error("Invalid payload for Completion message.");
2780
- }
2781
- if (!message.result && message.error) {
2782
- this._assertNotEmptyString(message.error, "Invalid payload for Completion message.");
2783
- }
2784
- this._assertNotEmptyString(message.invocationId, "Invalid payload for Completion message.");
2785
- }
2786
- _assertNotEmptyString(value, errorMessage) {
2787
- if (typeof value !== "string" || value === "") {
2788
- throw new Error(errorMessage);
2789
- }
2790
- }
2791
- }
2792
-
2793
- // Licensed to the .NET Foundation under one or more agreements.
2794
- const LogLevelNameMapping = {
2795
- trace: LogLevel.Trace,
2796
- debug: LogLevel.Debug,
2797
- info: LogLevel.Information,
2798
- information: LogLevel.Information,
2799
- warn: LogLevel.Warning,
2800
- warning: LogLevel.Warning,
2801
- error: LogLevel.Error,
2802
- critical: LogLevel.Critical,
2803
- none: LogLevel.None,
2804
- };
2805
- function parseLogLevel(name) {
2806
- // Case-insensitive matching via lower-casing
2807
- // Yes, I know case-folding is a complicated problem in Unicode, but we only support
2808
- // the ASCII strings defined in LogLevelNameMapping anyway, so it's fine -anurse.
2809
- const mapping = LogLevelNameMapping[name.toLowerCase()];
2810
- if (typeof mapping !== "undefined") {
2811
- return mapping;
2812
- }
2813
- else {
2814
- throw new Error(`Unknown log level: ${name}`);
2815
- }
2816
- }
2817
- /** A builder for configuring {@link @microsoft/signalr.HubConnection} instances. */
2818
- class HubConnectionBuilder {
2819
- configureLogging(logging) {
2820
- Arg.isRequired(logging, "logging");
2821
- if (isLogger(logging)) {
2822
- this.logger = logging;
2823
- }
2824
- else if (typeof logging === "string") {
2825
- const logLevel = parseLogLevel(logging);
2826
- this.logger = new ConsoleLogger(logLevel);
2827
- }
2828
- else {
2829
- this.logger = new ConsoleLogger(logging);
2830
- }
2831
- return this;
2832
- }
2833
- withUrl(url, transportTypeOrOptions) {
2834
- Arg.isRequired(url, "url");
2835
- Arg.isNotEmpty(url, "url");
2836
- this.url = url;
2837
- // Flow-typing knows where it's at. Since HttpTransportType is a number and IHttpConnectionOptions is guaranteed
2838
- // to be an object, we know (as does TypeScript) this comparison is all we need to figure out which overload was called.
2839
- if (typeof transportTypeOrOptions === "object") {
2840
- this.httpConnectionOptions = { ...this.httpConnectionOptions, ...transportTypeOrOptions };
2841
- }
2842
- else {
2843
- this.httpConnectionOptions = {
2844
- ...this.httpConnectionOptions,
2845
- transport: transportTypeOrOptions,
2846
- };
2847
- }
2848
- return this;
2849
- }
2850
- /** Configures the {@link @microsoft/signalr.HubConnection} to use the specified Hub Protocol.
2851
- *
2852
- * @param {IHubProtocol} protocol The {@link @microsoft/signalr.IHubProtocol} implementation to use.
2853
- */
2854
- withHubProtocol(protocol) {
2855
- Arg.isRequired(protocol, "protocol");
2856
- this.protocol = protocol;
2857
- return this;
2858
- }
2859
- withAutomaticReconnect(retryDelaysOrReconnectPolicy) {
2860
- if (this.reconnectPolicy) {
2861
- throw new Error("A reconnectPolicy has already been set.");
2862
- }
2863
- if (!retryDelaysOrReconnectPolicy) {
2864
- this.reconnectPolicy = new DefaultReconnectPolicy();
2865
- }
2866
- else if (Array.isArray(retryDelaysOrReconnectPolicy)) {
2867
- this.reconnectPolicy = new DefaultReconnectPolicy(retryDelaysOrReconnectPolicy);
2868
- }
2869
- else {
2870
- this.reconnectPolicy = retryDelaysOrReconnectPolicy;
2871
- }
2872
- return this;
2873
- }
2874
- /** Creates a {@link @microsoft/signalr.HubConnection} from the configuration options specified in this builder.
2875
- *
2876
- * @returns {HubConnection} The configured {@link @microsoft/signalr.HubConnection}.
2877
- */
2878
- build() {
2879
- // If httpConnectionOptions has a logger, use it. Otherwise, override it with the one
2880
- // provided to configureLogger
2881
- const httpConnectionOptions = this.httpConnectionOptions || {};
2882
- // If it's 'null', the user **explicitly** asked for null, don't mess with it.
2883
- if (httpConnectionOptions.logger === undefined) {
2884
- // If our logger is undefined or null, that's OK, the HttpConnection constructor will handle it.
2885
- httpConnectionOptions.logger = this.logger;
2886
- }
2887
- // Now create the connection
2888
- if (!this.url) {
2889
- throw new Error("The 'HubConnectionBuilder.withUrl' method must be called before building the connection.");
2890
- }
2891
- const connection = new HttpConnection(this.url, httpConnectionOptions);
2892
- return HubConnection.create(connection, this.logger || NullLogger.instance, this.protocol || new JsonHubProtocol(), this.reconnectPolicy);
2893
- }
2894
- }
2895
- function isLogger(logger) {
2896
- return logger.log !== undefined;
2897
- }
2898
-
2899
- const { state, onChange, reset } = auth_store.createStore({
2900
- connecting: false,
2901
- connected: false
2902
- });
2903
- const signalRStore = { state, onChange, reset };
2904
-
2905
- class SignalRService {
2906
- constructor() {
2907
- console.log("Starting signalR");
2908
- //TODO: update courseClassId
2909
- var defaultCourseClassId = 1;
2910
- var sparkleConfig = environmentConfig_service.EnvironmentConfigService.getInstance().get('sparkle');
2911
- this.connection = new HubConnectionBuilder()
2912
- .withUrl(`${sparkleConfig.apiUrl}hubs/sparkle?url=${window.location.href}${"&courseClassId=" + defaultCourseClassId }`, {
2913
- accessTokenFactory: () => this.getToken(),
2914
- skipNegotiation: true,
2915
- transport: HttpTransportType.WebSockets
2916
- })
2917
- .configureLogging(LogLevel.Debug)
2918
- //.withAutomaticReconnect()
2919
- .withAutomaticReconnect({
2920
- nextRetryDelayInMilliseconds: retryContext => {
2921
- if (retryContext.elapsedMilliseconds < 60000) {
2922
- // If we've been reconnecting for less than 60 seconds so far,
2923
- // wait between 0 and 10 seconds before the next reconnect attempt.
2924
- return Math.random() * 10000;
2925
- }
2926
- else {
2927
- // If we've been reconnecting for more than 60 seconds so far, stop reconnecting.
2928
- return null;
2929
- }
2930
- }
2931
- })
2932
- .build();
2933
- this.connection.on("SendMessage", (user, data) => {
2934
- let payload = JSON.parse(data);
2935
- console.log("Server said ", user, payload);
2936
- });
2937
- this.connection.onclose(error => {
2938
- });
2939
- this.connection.onreconnecting(error => {
2940
- console.assert(this.connection.state === HubConnectionState.Reconnecting);
2941
- });
2942
- this.connection.onreconnected(connectionId => {
2943
- console.assert(this.connection.state === HubConnectionState.Connected);
2944
- });
2945
- }
2946
- static getInstance() {
2947
- if (!SignalRService.instance) {
2948
- SignalRService.instance = new SignalRService();
2949
- }
2950
- return SignalRService.instance;
2951
- }
2952
- async start() {
2953
- console.log("start");
2954
- try {
2955
- signalRStore.state.connecting = true;
2956
- signalRStore.state.connected = !signalRStore.state.connecting;
2957
- await this.connection.start();
2958
- console.log(this.connection);
2959
- signalRStore.state.connecting = false;
2960
- signalRStore.state.connected = !signalRStore.state.connecting;
2961
- console.assert(this.connection.state === HubConnectionState.Connected);
2962
- console.log("SignalR Connected.");
2963
- }
2964
- catch (err) {
2965
- console.assert(this.connection.state === HubConnectionState.Disconnected);
2966
- console.log(err);
2967
- }
2968
- }
2969
- ;
2970
- async callSignalR(hub, data) {
2971
- console.log('signalR invoke', hub, this.connection.connectionState);
2972
- if (!this.getToken()) {
2973
- console.log("Cannot connect to signalR. Not logged in");
2974
- return;
2975
- }
2976
- this.connection.invoke(hub, JSON.stringify(data));
2977
- console.log('After signalR invoke', hub, this.connection.connectionState);
2978
- }
2979
- getToken() {
2980
- var sparkleConfig = environmentConfig_service.EnvironmentConfigService.getInstance().get('sparkle');
2981
- if (!!sparkleConfig && !!sparkleConfig.auth && !!sparkleConfig.auth.getToken()) {
2982
- return sparkle.auth.getToken();
2983
- }
2984
- return null;
2985
- }
2986
- }
2987
-
2988
- const toHypertext = (h, data) => {
2989
- const args = [];
2990
- for (let i = 0; i < data.length; i++) {
2991
- let arg = data[i];
2992
- if (i === 0 && typeof arg === 'string' && tagBlacklist.includes(arg.toLowerCase().trim())) {
2993
- arg = 'template';
2994
- }
2995
- else if (i === 1 && arg) {
2996
- const attrs = {};
2997
- Object.keys(arg).forEach(key => {
2998
- const k = key.toLowerCase();
2999
- if (!k.startsWith('on') && k !== 'innerhtml') {
3000
- attrs[key] = arg[key];
3001
- }
3002
- });
3003
- arg = attrs;
3004
- }
3005
- else if (i > 1) {
3006
- if (Array.isArray(arg)) {
3007
- arg = toHypertext(h, arg);
3008
- }
3009
- }
3010
- args.push(arg);
3011
- }
3012
- return h.apply(null, args);
3013
- };
3014
- const tagBlacklist = ['script', 'link', 'meta', 'object', 'head', 'html', 'body'];
3015
-
3016
- const defaultTemplate = props => {
3017
- const { page } = props;
3018
- return (index.h("article", null,
3019
- page.renderTitle !== false ? index.h("h1", null, page.title) : null,
3020
- index.h("section", { class: "markdown-content" }, toHypertext(index.h, page.body)),
3021
- index.h("sparkle-page-footer", { page: page })));
3022
- };
3023
-
3024
- const pdfTemplate = props => {
3025
- const { page } = props;
3026
- return (index.h("article", null,
3027
- page.renderTitle !== false ? index.h("h1", null, page.title) : null,
3028
- index.h("section", { class: "markdown-content" }, toHypertext(index.h, page.body))));
3029
- };
3030
-
3031
- const error = (response) => (index.h("main", { class: "Error full-screen" },
3032
- index.h("div", null, util.sample(appropriateEmoji)),
3033
- index.h("h1", null, getHelpfulTitle(response)),
3034
- index.h("p", null, getHelpfulMessage(response))));
3035
- const getHelpfulTitle = (response) => {
3036
- switch (response.status) {
3037
- case 404:
3038
- return 'Not Found';
3039
- default:
3040
- return 'Uh Oh';
3041
- }
3042
- };
3043
- const getHelpfulMessage = (response) => {
3044
- switch (response.status) {
3045
- case 404:
3046
- return 'Sorry, we couldn\'t find that page.';
3047
- default:
3048
- return 'Sorry, something went wrong.';
3049
- }
3050
- };
3051
- const appropriateEmoji = [
3052
- '😕',
3053
- '😟',
3054
- '😑',
3055
- '😧',
3056
- '😯',
3057
- '😮',
3058
- '🙃',
3059
- '🤕',
3060
- '😫'
3061
- ];
3062
-
3063
- const templates = {
3064
- 'default': defaultTemplate,
3065
- 'pdf': pdfTemplate,
3066
- 'error': error
3067
- };
3068
-
3069
- exports.SignalRService = SignalRService;
3070
- exports.signalRStore = signalRStore;
3071
- exports.templates = templates;