@nice2dev/game-engine 1.3.15 → 1.3.17

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 (434) hide show
  1. package/CHANGELOG.md +13 -0
  2. package/dist/cjs/accessibility/Accessibility.js +152 -165
  3. package/dist/cjs/ai/AI.js +292 -294
  4. package/dist/cjs/ai/BehaviorTree.js +1029 -1113
  5. package/dist/cjs/ai/StateMachine.js +694 -756
  6. package/dist/cjs/animation/Animation.js +232 -241
  7. package/dist/cjs/audio/AudioAdvanced.js +221 -236
  8. package/dist/cjs/audio/AudioBridge.js +441 -435
  9. package/dist/cjs/audio/AudioManager.js +242 -259
  10. package/dist/cjs/build-cloud/BuildOrchestration.js +1059 -1098
  11. package/dist/cjs/build-cloud/GodotBuildCloud.js +641 -670
  12. package/dist/cjs/build-cloud/UnityBuildCloud.js +563 -610
  13. package/dist/cjs/build-cloud/UnrealBuildCloud.js +610 -635
  14. package/dist/cjs/core/EventBus.js +51 -56
  15. package/dist/cjs/core/GameClock.js +62 -66
  16. package/dist/cjs/core/GameConfig.js +72 -79
  17. package/dist/cjs/core/GameLoop.js +80 -89
  18. package/dist/cjs/core/ServiceLocator.js +61 -65
  19. package/dist/cjs/core/Validation.js +72 -82
  20. package/dist/cjs/core/math.js +108 -112
  21. package/dist/cjs/devtools/DevTools.js +542 -563
  22. package/dist/cjs/devtools/DeveloperExperience.js +521 -559
  23. package/dist/cjs/devtools/GameplayAnalytics.js +636 -646
  24. package/dist/cjs/dialogue/DialogueSystem.js +984 -986
  25. package/dist/cjs/docs/DocGenerator.js +339 -364
  26. package/dist/cjs/ecs/World.js +355 -371
  27. package/dist/cjs/editor/AchievementEditor.js +580 -636
  28. package/dist/cjs/editor/AdvancedEditor.js +184 -191
  29. package/dist/cjs/editor/AnimationRetargeting.js +696 -741
  30. package/dist/cjs/editor/AssetBrowser.js +1072 -1160
  31. package/dist/cjs/editor/AssetManager.js +187 -192
  32. package/dist/cjs/editor/ConsolePro.js +971 -1061
  33. package/dist/cjs/editor/CraftingEditor.js +680 -730
  34. package/dist/cjs/editor/DebugTools.js +187 -185
  35. package/dist/cjs/editor/DialogueSystem.js +844 -901
  36. package/dist/cjs/editor/LeaderboardSystem.js +429 -483
  37. package/dist/cjs/editor/NiceGameEditor.js +1903 -1201
  38. package/dist/cjs/editor/PrefabSystem.js +772 -838
  39. package/dist/cjs/editor/ProfilerPanel.js +649 -700
  40. package/dist/cjs/editor/QuestEditor.js +792 -839
  41. package/dist/cjs/editor/ReplaySystem.js +585 -634
  42. package/dist/cjs/editor/SceneEditor.js +176 -200
  43. package/dist/cjs/editor/ScreenshotMode.js +621 -688
  44. package/dist/cjs/editor/ShaderGraph.js +1556 -1582
  45. package/dist/cjs/editor/TimelineEditor.js +715 -778
  46. package/dist/cjs/editor/UndoRedoPro.js +830 -904
  47. package/dist/cjs/editor/VRARMode.js +582 -645
  48. package/dist/cjs/engine/NiceGameEngine.js +141 -164
  49. package/dist/cjs/engine/SaveSystem.js +441 -495
  50. package/dist/cjs/enterprise/Enterprise.js +254 -261
  51. package/dist/cjs/export/BevyExporter.js +927 -967
  52. package/dist/cjs/export/CocosExporter.js +644 -673
  53. package/dist/cjs/export/Construct3Exporter.js +783 -794
  54. package/dist/cjs/export/DefoldExporter.js +1028 -1069
  55. package/dist/cjs/export/GDevelopExporter.js +674 -708
  56. package/dist/cjs/export/GameMakerExporter.js +791 -805
  57. package/dist/cjs/export/GodotExporter.js +1003 -1045
  58. package/dist/cjs/export/MinecraftBedrockExporter.js +573 -578
  59. package/dist/cjs/export/MonoGameExporter.js +1265 -1293
  60. package/dist/cjs/export/Pico8Exporter.js +766 -812
  61. package/dist/cjs/export/PlatformExporter.js +188 -206
  62. package/dist/cjs/export/RPGMakerExporter.js +860 -879
  63. package/dist/cjs/export/RobloxExporter.js +883 -919
  64. package/dist/cjs/export/Solar2DExporter.js +1218 -1256
  65. package/dist/cjs/export/ThreeJSExporter.js +1006 -1073
  66. package/dist/cjs/export/Tic80Exporter.js +1210 -1267
  67. package/dist/cjs/export/UnityExporter.js +1116 -1131
  68. package/dist/cjs/export/UnrealExporter.js +889 -919
  69. package/dist/cjs/export/WebExporter.js +931 -970
  70. package/dist/cjs/export/index.js +42 -65
  71. package/dist/cjs/godot-integration/GodotAssetLibrary.js +659 -692
  72. package/dist/cjs/godot-integration/GodotImport.js +929 -1027
  73. package/dist/cjs/godot-integration/GodotLiveLink.js +915 -945
  74. package/dist/cjs/godot-integration/components/GodotProjectBrowser.js +911 -611
  75. package/dist/cjs/i18n/I18n.js +860 -900
  76. package/dist/cjs/i18n/useTranslation.js +84 -89
  77. package/dist/cjs/import/AsepriteImporter.js +658 -716
  78. package/dist/cjs/import/DragonBonesImporter.js +437 -461
  79. package/dist/cjs/import/GameMakerImporter.js +511 -521
  80. package/dist/cjs/import/GodotSceneImporter.js +788 -822
  81. package/dist/cjs/import/LDtkImporter.js +436 -454
  82. package/dist/cjs/import/Live2DImporter.js +497 -518
  83. package/dist/cjs/import/NdgFormat.js +424 -457
  84. package/dist/cjs/import/OgmoImporter.js +466 -493
  85. package/dist/cjs/import/RPGMakerImporter.js +451 -477
  86. package/dist/cjs/import/SceneImporter.js +378 -423
  87. package/dist/cjs/import/SpineImporter.js +511 -546
  88. package/dist/cjs/import/SpriterImporter.js +590 -613
  89. package/dist/cjs/import/TiledMapImporter.js +811 -846
  90. package/dist/cjs/import/UnitySceneImporter.js +687 -703
  91. package/dist/cjs/import/index.js +206 -251
  92. package/dist/cjs/index.js +275 -278
  93. package/dist/cjs/input/GamepadNavigation.js +185 -205
  94. package/dist/cjs/input/InputManager.js +397 -421
  95. package/dist/cjs/input/useGamepads.js +70 -81
  96. package/dist/cjs/integration/IconSprite.js +129 -256
  97. package/dist/cjs/inventory/InventorySystem.js +920 -995
  98. package/dist/cjs/kids/KidMode.js +997 -1022
  99. package/dist/cjs/kids/KidTools.js +570 -594
  100. package/dist/cjs/monetization/Monetization.js +170 -177
  101. package/dist/cjs/multiplayer/LocalMultiplayer.js +287 -287
  102. package/dist/cjs/multiplayer/MiniGameTypes.js +49 -59
  103. package/dist/cjs/native-engine/AnimationSystem.js +731 -806
  104. package/dist/cjs/native-engine/AssetPipeline.js +454 -515
  105. package/dist/cjs/native-engine/AudioEngine.js +763 -804
  106. package/dist/cjs/native-engine/InputSystem.js +1075 -1145
  107. package/dist/cjs/native-engine/NetworkingSystem.js +733 -793
  108. package/dist/cjs/native-engine/PhysicsEngine.js +583 -607
  109. package/dist/cjs/native-engine/RenderingEngine.js +302 -350
  110. package/dist/cjs/native-engine/SceneGraph.js +769 -808
  111. package/dist/cjs/network/MultiplayerTransport.js +97 -132
  112. package/dist/cjs/network/Networking.js +549 -564
  113. package/dist/cjs/node_modules/@microsoft/signalr/dist/esm/AbortController.js +21 -29
  114. package/dist/cjs/node_modules/@microsoft/signalr/dist/esm/AccessTokenHttpClient.js +40 -48
  115. package/dist/cjs/node_modules/@microsoft/signalr/dist/esm/DefaultHttpClient.js +35 -43
  116. package/dist/cjs/node_modules/@microsoft/signalr/dist/esm/DefaultReconnectPolicy.js +10 -15
  117. package/dist/cjs/node_modules/@microsoft/signalr/dist/esm/Errors.js +103 -135
  118. package/dist/cjs/node_modules/@microsoft/signalr/dist/esm/FetchHttpClient.js +131 -158
  119. package/dist/cjs/node_modules/@microsoft/signalr/dist/esm/HandshakeProtocol.js +39 -53
  120. package/dist/cjs/node_modules/@microsoft/signalr/dist/esm/HeaderNames.js +5 -8
  121. package/dist/cjs/node_modules/@microsoft/signalr/dist/esm/HttpClient.js +40 -48
  122. package/dist/cjs/node_modules/@microsoft/signalr/dist/esm/HttpConnection.js +494 -572
  123. package/dist/cjs/node_modules/@microsoft/signalr/dist/esm/HubConnection.js +826 -953
  124. package/dist/cjs/node_modules/@microsoft/signalr/dist/esm/HubConnectionBuilder.js +125 -146
  125. package/dist/cjs/node_modules/@microsoft/signalr/dist/esm/IHubProtocol.js +13 -23
  126. package/dist/cjs/node_modules/@microsoft/signalr/dist/esm/ILogger.js +11 -25
  127. package/dist/cjs/node_modules/@microsoft/signalr/dist/esm/ITransport.js +13 -24
  128. package/dist/cjs/node_modules/@microsoft/signalr/dist/esm/JsonHubProtocol.js +108 -121
  129. package/dist/cjs/node_modules/@microsoft/signalr/dist/esm/Loggers.js +10 -14
  130. package/dist/cjs/node_modules/@microsoft/signalr/dist/esm/LongPollingTransport.js +150 -185
  131. package/dist/cjs/node_modules/@microsoft/signalr/dist/esm/MessageBuffer.js +158 -196
  132. package/dist/cjs/node_modules/@microsoft/signalr/dist/esm/ServerSentEventsTransport.js +90 -105
  133. package/dist/cjs/node_modules/@microsoft/signalr/dist/esm/Subject.js +30 -35
  134. package/dist/cjs/node_modules/@microsoft/signalr/dist/esm/TextMessageFormat.js +16 -21
  135. package/dist/cjs/node_modules/@microsoft/signalr/dist/esm/Utils.js +215 -248
  136. package/dist/cjs/node_modules/@microsoft/signalr/dist/esm/WebSocketTransport.js +135 -157
  137. package/dist/cjs/node_modules/@microsoft/signalr/dist/esm/XhrHttpClient.js +76 -85
  138. package/dist/cjs/node_modules/@microsoft/signalr/dist/esm/index.js +24 -27
  139. package/dist/cjs/node_modules/@microsoft/signalr/dist/esm/pkg-version.js +3 -4
  140. package/dist/cjs/pathfinding/Pathfinding.js +245 -263
  141. package/dist/cjs/performance/AssetStreaming.js +561 -635
  142. package/dist/cjs/performance/BenchmarkSuite.js +283 -311
  143. package/dist/cjs/performance/DeltaCompression.js +467 -526
  144. package/dist/cjs/performance/DeterministicPhysics.js +450 -498
  145. package/dist/cjs/performance/ECSOptimization.js +644 -695
  146. package/dist/cjs/performance/GameSaveSystem.js +509 -556
  147. package/dist/cjs/performance/HotReload.js +447 -500
  148. package/dist/cjs/performance/InputRecording.js +511 -561
  149. package/dist/cjs/performance/InterestManagement.js +453 -500
  150. package/dist/cjs/performance/LocalizationRuntime.js +376 -423
  151. package/dist/cjs/performance/MemoryManagement.js +410 -470
  152. package/dist/cjs/performance/ModSupport.js +445 -496
  153. package/dist/cjs/performance/MultiThreadedPhysics.js +400 -443
  154. package/dist/cjs/performance/NetworkPrediction.js +424 -482
  155. package/dist/cjs/performance/ObjectPooling.js +569 -617
  156. package/dist/cjs/performance/Performance.js +174 -190
  157. package/dist/cjs/performance/PerformanceAdvanced.js +614 -637
  158. package/dist/cjs/performance/WebGPURenderer.js +656 -683
  159. package/dist/cjs/physics/PhysicsAdvanced.js +345 -379
  160. package/dist/cjs/physics/PhysicsEngine2D.js +391 -427
  161. package/dist/cjs/plugins/PluginSDK.js +432 -466
  162. package/dist/cjs/plugins/PluginTestKit.js +307 -330
  163. package/dist/cjs/procedural/Procedural.js +243 -254
  164. package/dist/cjs/procedural/WorldBuilding.js +297 -314
  165. package/dist/cjs/quest/QuestSystem.js +975 -932
  166. package/dist/cjs/release/MobileExport.js +157 -163
  167. package/dist/cjs/release/Release.js +225 -238
  168. package/dist/cjs/rendering/Camera2D.js +121 -124
  169. package/dist/cjs/rendering/Renderer2D.js +321 -335
  170. package/dist/cjs/rendering/WebGPURenderPipeline.js +632 -651
  171. package/dist/cjs/runtime3d/Runtime3D.js +359 -378
  172. package/dist/cjs/runtime3d/SceneEditor3D.js +252 -263
  173. package/dist/cjs/scene/SceneManager.js +177 -193
  174. package/dist/cjs/scripting/GraphToAST.js +574 -547
  175. package/dist/cjs/scripting/LanguageExporter.js +254 -279
  176. package/dist/cjs/scripting/NodeGraph.js +546 -570
  177. package/dist/cjs/scripting/ScriptAST.js +31 -39
  178. package/dist/cjs/scripting/VisualScripting2.js +1016 -1065
  179. package/dist/cjs/scripting/exporters/CSharpExporter.js +464 -496
  180. package/dist/cjs/scripting/exporters/GDScriptExporter.js +390 -442
  181. package/dist/cjs/scripting/exporters/LuaExporter.js +406 -447
  182. package/dist/cjs/scripting/exporters/PythonExporter.js +484 -549
  183. package/dist/cjs/scripting/exporters/RustExporter.js +459 -512
  184. package/dist/cjs/scripting/exporters/TypeScriptExporter.js +505 -556
  185. package/dist/cjs/social/Social.js +72 -80
  186. package/dist/cjs/systems/LightingSystem.js +844 -931
  187. package/dist/cjs/systems/ParticleSystem2.js +1447 -1451
  188. package/dist/cjs/systems/PhysicsDebugSystem.js +1070 -1141
  189. package/dist/cjs/systems/TerrainSystem.js +985 -1098
  190. package/dist/cjs/templates/ActionTemplates.js +296 -309
  191. package/dist/cjs/templates/FightingTemplate.js +417 -463
  192. package/dist/cjs/templates/MetroidvaniaTemplate.js +353 -405
  193. package/dist/cjs/templates/PartyTemplates.js +190 -202
  194. package/dist/cjs/templates/PuzzleTemplates.js +245 -261
  195. package/dist/cjs/templates/RPGTemplates.js +160 -178
  196. package/dist/cjs/templates/SportsTemplates.js +237 -250
  197. package/dist/cjs/templates/StrategyTemplates.js +143 -153
  198. package/dist/cjs/templates/SurvivalTemplate.js +336 -380
  199. package/dist/cjs/templates/WaveDefense.js +499 -526
  200. package/dist/cjs/tilemap/Tilemap.js +207 -214
  201. package/dist/cjs/tutorials/TutorialBranching.js +396 -417
  202. package/dist/cjs/tutorials/TutorialEngine.js +888 -931
  203. package/dist/cjs/tutorials/TutorialOverlay.js +602 -640
  204. package/dist/cjs/tutorials/content/Tutorials_T05_T08.js +787 -809
  205. package/dist/cjs/tutorials/content/Tutorials_T09_T11.js +736 -756
  206. package/dist/cjs/tutorials/content/Tutorials_T12_T15.js +754 -778
  207. package/dist/cjs/ui/GameUI.js +295 -312
  208. package/dist/cjs/unity-integration/UnityAssetStore.js +700 -741
  209. package/dist/cjs/unity-integration/UnityImport.js +1066 -1176
  210. package/dist/cjs/unity-integration/UnityLiveLink.js +934 -981
  211. package/dist/cjs/unity-integration/components/UnityAssetStoreBrowser.js +1233 -757
  212. package/dist/cjs/unity-integration/components/UnityProjectBrowser.js +1240 -768
  213. package/dist/cjs/unreal-integration/UnrealImport.js +391 -412
  214. package/dist/cjs/unreal-integration/UnrealLiveLink.js +1102 -1137
  215. package/dist/cjs/unreal-integration/UnrealMarketplace.js +436 -473
  216. package/dist/cjs/unreal-integration/components/UnrealProjectBrowser.js +1150 -767
  217. package/dist/cjs/xr/ARVR.js +167 -175
  218. package/dist/esm/accessibility/Accessibility.js +160 -164
  219. package/dist/esm/ai/AI.js +310 -293
  220. package/dist/esm/ai/BehaviorTree.js +1057 -1112
  221. package/dist/esm/ai/StateMachine.js +709 -755
  222. package/dist/esm/animation/Animation.js +237 -240
  223. package/dist/esm/audio/AudioAdvanced.js +239 -235
  224. package/dist/esm/audio/AudioBridge.js +448 -434
  225. package/dist/esm/audio/AudioManager.js +243 -258
  226. package/dist/esm/build-cloud/BuildOrchestration.js +1071 -1097
  227. package/dist/esm/build-cloud/GodotBuildCloud.js +647 -669
  228. package/dist/esm/build-cloud/UnityBuildCloud.js +571 -609
  229. package/dist/esm/build-cloud/UnrealBuildCloud.js +615 -634
  230. package/dist/esm/core/EventBus.js +52 -55
  231. package/dist/esm/core/GameClock.js +63 -65
  232. package/dist/esm/core/GameConfig.js +77 -78
  233. package/dist/esm/core/GameLoop.js +81 -88
  234. package/dist/esm/core/ServiceLocator.js +63 -64
  235. package/dist/esm/core/Validation.js +82 -81
  236. package/dist/esm/core/math.js +109 -111
  237. package/dist/esm/devtools/DevTools.js +546 -562
  238. package/dist/esm/devtools/DeveloperExperience.js +535 -558
  239. package/dist/esm/devtools/GameplayAnalytics.js +647 -645
  240. package/dist/esm/dialogue/DialogueSystem.js +998 -985
  241. package/dist/esm/docs/DocGenerator.js +342 -363
  242. package/dist/esm/ecs/World.js +358 -370
  243. package/dist/esm/editor/AchievementEditor.js +584 -635
  244. package/dist/esm/editor/AdvancedEditor.js +191 -190
  245. package/dist/esm/editor/AnimationRetargeting.js +700 -740
  246. package/dist/esm/editor/AssetBrowser.js +1078 -1159
  247. package/dist/esm/editor/AssetManager.js +188 -191
  248. package/dist/esm/editor/ConsolePro.js +977 -1060
  249. package/dist/esm/editor/CraftingEditor.js +684 -729
  250. package/dist/esm/editor/DebugTools.js +194 -184
  251. package/dist/esm/editor/DialogueSystem.js +849 -900
  252. package/dist/esm/editor/LeaderboardSystem.js +433 -482
  253. package/dist/esm/editor/NiceGameEditor.js +1908 -1200
  254. package/dist/esm/editor/PrefabSystem.js +777 -837
  255. package/dist/esm/editor/ProfilerPanel.js +654 -699
  256. package/dist/esm/editor/QuestEditor.js +795 -838
  257. package/dist/esm/editor/ReplaySystem.js +591 -633
  258. package/dist/esm/editor/SceneEditor.js +189 -199
  259. package/dist/esm/editor/ScreenshotMode.js +628 -687
  260. package/dist/esm/editor/ShaderGraph.js +1565 -1581
  261. package/dist/esm/editor/TimelineEditor.js +733 -777
  262. package/dist/esm/editor/UndoRedoPro.js +835 -903
  263. package/dist/esm/editor/VRARMode.js +586 -644
  264. package/dist/esm/engine/NiceGameEngine.js +142 -163
  265. package/dist/esm/engine/SaveSystem.js +447 -494
  266. package/dist/esm/enterprise/Enterprise.js +265 -260
  267. package/dist/esm/export/BevyExporter.js +929 -966
  268. package/dist/esm/export/CocosExporter.js +646 -672
  269. package/dist/esm/export/Construct3Exporter.js +785 -793
  270. package/dist/esm/export/DefoldExporter.js +1030 -1068
  271. package/dist/esm/export/GDevelopExporter.js +676 -707
  272. package/dist/esm/export/GameMakerExporter.js +793 -804
  273. package/dist/esm/export/GodotExporter.js +1004 -1044
  274. package/dist/esm/export/MinecraftBedrockExporter.js +575 -577
  275. package/dist/esm/export/MonoGameExporter.js +1267 -1292
  276. package/dist/esm/export/Pico8Exporter.js +768 -811
  277. package/dist/esm/export/PlatformExporter.js +193 -205
  278. package/dist/esm/export/RPGMakerExporter.js +862 -878
  279. package/dist/esm/export/RobloxExporter.js +885 -918
  280. package/dist/esm/export/Solar2DExporter.js +1220 -1255
  281. package/dist/esm/export/ThreeJSExporter.js +1007 -1072
  282. package/dist/esm/export/Tic80Exporter.js +1212 -1266
  283. package/dist/esm/export/UnityExporter.js +1117 -1130
  284. package/dist/esm/export/UnrealExporter.js +891 -918
  285. package/dist/esm/export/WebExporter.js +933 -969
  286. package/dist/esm/export/index.js +86 -71
  287. package/dist/esm/godot-integration/GodotAssetLibrary.js +663 -691
  288. package/dist/esm/godot-integration/GodotImport.js +935 -1026
  289. package/dist/esm/godot-integration/GodotLiveLink.js +918 -944
  290. package/dist/esm/godot-integration/components/GodotProjectBrowser.js +912 -610
  291. package/dist/esm/i18n/I18n.js +871 -899
  292. package/dist/esm/i18n/useTranslation.js +88 -88
  293. package/dist/esm/import/AsepriteImporter.js +637 -715
  294. package/dist/esm/import/DragonBonesImporter.js +417 -460
  295. package/dist/esm/import/GameMakerImporter.js +491 -520
  296. package/dist/esm/import/GodotSceneImporter.js +767 -821
  297. package/dist/esm/import/LDtkImporter.js +415 -453
  298. package/dist/esm/import/Live2DImporter.js +477 -517
  299. package/dist/esm/import/NdgFormat.js +410 -456
  300. package/dist/esm/import/OgmoImporter.js +446 -492
  301. package/dist/esm/import/RPGMakerImporter.js +431 -476
  302. package/dist/esm/import/SceneImporter.js +385 -422
  303. package/dist/esm/import/SpineImporter.js +491 -545
  304. package/dist/esm/import/SpriterImporter.js +570 -612
  305. package/dist/esm/import/TiledMapImporter.js +790 -845
  306. package/dist/esm/import/UnitySceneImporter.js +666 -702
  307. package/dist/esm/import/index.js +247 -258
  308. package/dist/esm/index.js +1332 -188
  309. package/dist/esm/input/GamepadNavigation.js +187 -204
  310. package/dist/esm/input/InputManager.js +401 -420
  311. package/dist/esm/input/useGamepads.js +72 -80
  312. package/dist/esm/integration/IconSprite.js +143 -255
  313. package/dist/esm/inventory/InventorySystem.js +925 -994
  314. package/dist/esm/kids/KidMode.js +1003 -1021
  315. package/dist/esm/kids/KidTools.js +573 -593
  316. package/dist/esm/monetization/Monetization.js +180 -176
  317. package/dist/esm/multiplayer/LocalMultiplayer.js +290 -286
  318. package/dist/esm/multiplayer/MiniGameTypes.js +58 -58
  319. package/dist/esm/native-engine/AnimationSystem.js +735 -805
  320. package/dist/esm/native-engine/AssetPipeline.js +456 -514
  321. package/dist/esm/native-engine/AudioEngine.js +765 -803
  322. package/dist/esm/native-engine/InputSystem.js +1079 -1144
  323. package/dist/esm/native-engine/NetworkingSystem.js +740 -792
  324. package/dist/esm/native-engine/PhysicsEngine.js +585 -606
  325. package/dist/esm/native-engine/RenderingEngine.js +304 -349
  326. package/dist/esm/native-engine/SceneGraph.js +773 -807
  327. package/dist/esm/network/MultiplayerTransport.js +99 -131
  328. package/dist/esm/network/Networking.js +556 -563
  329. package/dist/esm/node_modules/@microsoft/signalr/dist/esm/AbortController.js +22 -28
  330. package/dist/esm/node_modules/@microsoft/signalr/dist/esm/AccessTokenHttpClient.js +41 -47
  331. package/dist/esm/node_modules/@microsoft/signalr/dist/esm/DefaultHttpClient.js +36 -42
  332. package/dist/esm/node_modules/@microsoft/signalr/dist/esm/DefaultReconnectPolicy.js +11 -14
  333. package/dist/esm/node_modules/@microsoft/signalr/dist/esm/Errors.js +111 -134
  334. package/dist/esm/node_modules/@microsoft/signalr/dist/esm/FetchHttpClient.js +132 -157
  335. package/dist/esm/node_modules/@microsoft/signalr/dist/esm/HandshakeProtocol.js +40 -52
  336. package/dist/esm/node_modules/@microsoft/signalr/dist/esm/HeaderNames.js +6 -7
  337. package/dist/esm/node_modules/@microsoft/signalr/dist/esm/HttpClient.js +42 -47
  338. package/dist/esm/node_modules/@microsoft/signalr/dist/esm/HttpConnection.js +496 -571
  339. package/dist/esm/node_modules/@microsoft/signalr/dist/esm/HubConnection.js +828 -952
  340. package/dist/esm/node_modules/@microsoft/signalr/dist/esm/HubConnectionBuilder.js +126 -145
  341. package/dist/esm/node_modules/@microsoft/signalr/dist/esm/IHubProtocol.js +14 -23
  342. package/dist/esm/node_modules/@microsoft/signalr/dist/esm/ILogger.js +12 -25
  343. package/dist/esm/node_modules/@microsoft/signalr/dist/esm/ITransport.js +15 -24
  344. package/dist/esm/node_modules/@microsoft/signalr/dist/esm/JsonHubProtocol.js +109 -120
  345. package/dist/esm/node_modules/@microsoft/signalr/dist/esm/Loggers.js +11 -13
  346. package/dist/esm/node_modules/@microsoft/signalr/dist/esm/LongPollingTransport.js +151 -184
  347. package/dist/esm/node_modules/@microsoft/signalr/dist/esm/MessageBuffer.js +159 -195
  348. package/dist/esm/node_modules/@microsoft/signalr/dist/esm/ServerSentEventsTransport.js +91 -104
  349. package/dist/esm/node_modules/@microsoft/signalr/dist/esm/Subject.js +31 -34
  350. package/dist/esm/node_modules/@microsoft/signalr/dist/esm/TextMessageFormat.js +17 -20
  351. package/dist/esm/node_modules/@microsoft/signalr/dist/esm/Utils.js +230 -248
  352. package/dist/esm/node_modules/@microsoft/signalr/dist/esm/WebSocketTransport.js +136 -156
  353. package/dist/esm/node_modules/@microsoft/signalr/dist/esm/XhrHttpClient.js +77 -84
  354. package/dist/esm/node_modules/@microsoft/signalr/dist/esm/index.js +31 -12
  355. package/dist/esm/node_modules/@microsoft/signalr/dist/esm/pkg-version.js +4 -3
  356. package/dist/esm/pathfinding/Pathfinding.js +249 -262
  357. package/dist/esm/performance/AssetStreaming.js +567 -634
  358. package/dist/esm/performance/BenchmarkSuite.js +285 -310
  359. package/dist/esm/performance/DeltaCompression.js +478 -525
  360. package/dist/esm/performance/DeterministicPhysics.js +479 -497
  361. package/dist/esm/performance/ECSOptimization.js +653 -694
  362. package/dist/esm/performance/GameSaveSystem.js +515 -555
  363. package/dist/esm/performance/HotReload.js +454 -499
  364. package/dist/esm/performance/InputRecording.js +520 -560
  365. package/dist/esm/performance/InterestManagement.js +460 -499
  366. package/dist/esm/performance/LocalizationRuntime.js +382 -422
  367. package/dist/esm/performance/MemoryManagement.js +415 -469
  368. package/dist/esm/performance/ModSupport.js +455 -495
  369. package/dist/esm/performance/MultiThreadedPhysics.js +408 -442
  370. package/dist/esm/performance/NetworkPrediction.js +436 -481
  371. package/dist/esm/performance/ObjectPooling.js +582 -616
  372. package/dist/esm/performance/Performance.js +182 -189
  373. package/dist/esm/performance/PerformanceAdvanced.js +621 -636
  374. package/dist/esm/performance/WebGPURenderer.js +660 -682
  375. package/dist/esm/physics/PhysicsAdvanced.js +359 -378
  376. package/dist/esm/physics/PhysicsEngine2D.js +393 -426
  377. package/dist/esm/plugins/PluginSDK.js +435 -465
  378. package/dist/esm/plugins/PluginTestKit.js +315 -329
  379. package/dist/esm/procedural/Procedural.js +248 -253
  380. package/dist/esm/procedural/WorldBuilding.js +316 -313
  381. package/dist/esm/quest/QuestSystem.js +982 -931
  382. package/dist/esm/release/MobileExport.js +163 -162
  383. package/dist/esm/release/Release.js +234 -237
  384. package/dist/esm/rendering/Camera2D.js +122 -123
  385. package/dist/esm/rendering/Renderer2D.js +323 -334
  386. package/dist/esm/rendering/WebGPURenderPipeline.js +647 -650
  387. package/dist/esm/runtime3d/Runtime3D.js +368 -377
  388. package/dist/esm/runtime3d/SceneEditor3D.js +268 -262
  389. package/dist/esm/scene/SceneManager.js +178 -192
  390. package/dist/esm/scripting/GraphToAST.js +576 -546
  391. package/dist/esm/scripting/LanguageExporter.js +263 -278
  392. package/dist/esm/scripting/NodeGraph.js +550 -569
  393. package/dist/esm/scripting/ScriptAST.js +45 -38
  394. package/dist/esm/scripting/VisualScripting2.js +1025 -1064
  395. package/dist/esm/scripting/exporters/CSharpExporter.js +465 -495
  396. package/dist/esm/scripting/exporters/GDScriptExporter.js +391 -441
  397. package/dist/esm/scripting/exporters/LuaExporter.js +407 -446
  398. package/dist/esm/scripting/exporters/PythonExporter.js +485 -548
  399. package/dist/esm/scripting/exporters/RustExporter.js +460 -511
  400. package/dist/esm/scripting/exporters/TypeScriptExporter.js +506 -555
  401. package/dist/esm/social/Social.js +77 -79
  402. package/dist/esm/systems/LightingSystem.js +855 -930
  403. package/dist/esm/systems/ParticleSystem2.js +1453 -1450
  404. package/dist/esm/systems/PhysicsDebugSystem.js +1078 -1140
  405. package/dist/esm/systems/TerrainSystem.js +996 -1097
  406. package/dist/esm/templates/ActionTemplates.js +307 -308
  407. package/dist/esm/templates/FightingTemplate.js +439 -462
  408. package/dist/esm/templates/MetroidvaniaTemplate.js +391 -404
  409. package/dist/esm/templates/PartyTemplates.js +206 -201
  410. package/dist/esm/templates/PuzzleTemplates.js +260 -260
  411. package/dist/esm/templates/RPGTemplates.js +172 -177
  412. package/dist/esm/templates/SportsTemplates.js +251 -249
  413. package/dist/esm/templates/StrategyTemplates.js +158 -152
  414. package/dist/esm/templates/SurvivalTemplate.js +367 -379
  415. package/dist/esm/templates/WaveDefense.js +501 -525
  416. package/dist/esm/tilemap/Tilemap.js +209 -213
  417. package/dist/esm/tutorials/TutorialBranching.js +399 -416
  418. package/dist/esm/tutorials/TutorialEngine.js +893 -930
  419. package/dist/esm/tutorials/TutorialOverlay.js +603 -639
  420. package/dist/esm/tutorials/content/Tutorials_T05_T08.js +792 -808
  421. package/dist/esm/tutorials/content/Tutorials_T09_T11.js +740 -755
  422. package/dist/esm/tutorials/content/Tutorials_T12_T15.js +759 -777
  423. package/dist/esm/ui/GameUI.js +296 -311
  424. package/dist/esm/unity-integration/UnityAssetStore.js +704 -740
  425. package/dist/esm/unity-integration/UnityImport.js +1071 -1175
  426. package/dist/esm/unity-integration/UnityLiveLink.js +938 -980
  427. package/dist/esm/unity-integration/components/UnityAssetStoreBrowser.js +1234 -756
  428. package/dist/esm/unity-integration/components/UnityProjectBrowser.js +1241 -767
  429. package/dist/esm/unreal-integration/UnrealImport.js +395 -411
  430. package/dist/esm/unreal-integration/UnrealLiveLink.js +1105 -1136
  431. package/dist/esm/unreal-integration/UnrealMarketplace.js +442 -472
  432. package/dist/esm/unreal-integration/components/UnrealProjectBrowser.js +1151 -766
  433. package/dist/esm/xr/ARVR.js +181 -174
  434. package/package.json +7 -12
@@ -1,955 +1,828 @@
1
- 'use strict';
2
-
3
- var HandshakeProtocol = require('./HandshakeProtocol.js');
4
- var Errors = require('./Errors.js');
5
- var IHubProtocol = require('./IHubProtocol.js');
6
- var ILogger = require('./ILogger.js');
7
- var Subject = require('./Subject.js');
8
- var Utils = require('./Utils.js');
9
- var MessageBuffer = require('./MessageBuffer.js');
10
-
11
- // Licensed to the .NET Foundation under one or more agreements.
12
- // The .NET Foundation licenses this file to you under the MIT license.
13
- const DEFAULT_TIMEOUT_IN_MS = 30 * 1000;
14
- const DEFAULT_PING_INTERVAL_IN_MS = 15 * 1000;
15
- const DEFAULT_STATEFUL_RECONNECT_BUFFER_SIZE = 100000;
16
- /** Describes the current state of the {@link HubConnection} to the server. */
17
- exports.HubConnectionState = void 0;
18
- (function (HubConnectionState) {
19
- /** The hub connection is disconnected. */
20
- HubConnectionState["Disconnected"] = "Disconnected";
21
- /** The hub connection is connecting. */
22
- HubConnectionState["Connecting"] = "Connecting";
23
- /** The hub connection is connected. */
24
- HubConnectionState["Connected"] = "Connected";
25
- /** The hub connection is disconnecting. */
26
- HubConnectionState["Disconnecting"] = "Disconnecting";
27
- /** The hub connection is reconnecting. */
28
- HubConnectionState["Reconnecting"] = "Reconnecting";
29
- })(exports.HubConnectionState || (exports.HubConnectionState = {}));
30
- /** Represents a connection to a SignalR Hub. */
31
- class HubConnection {
32
- /** @internal */
33
- // Using a public static factory method means we can have a private constructor and an _internal_
34
- // create method that can be used by HubConnectionBuilder. An "internal" constructor would just
35
- // be stripped away and the '.d.ts' file would have no constructor, which is interpreted as a
36
- // public parameter-less constructor.
37
- static create(connection, logger, protocol, reconnectPolicy, serverTimeoutInMilliseconds, keepAliveIntervalInMilliseconds, statefulReconnectBufferSize) {
38
- return new HubConnection(connection, logger, protocol, reconnectPolicy, serverTimeoutInMilliseconds, keepAliveIntervalInMilliseconds, statefulReconnectBufferSize);
39
- }
40
- constructor(connection, logger, protocol, reconnectPolicy, serverTimeoutInMilliseconds, keepAliveIntervalInMilliseconds, statefulReconnectBufferSize) {
41
- this._nextKeepAlive = 0;
42
- this._freezeEventListener = () => {
43
- this._logger.log(ILogger.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://learn.microsoft.com/aspnet/core/signalr/javascript-client#bsleep");
44
- };
45
- Utils.Arg.isRequired(connection, "connection");
46
- Utils.Arg.isRequired(logger, "logger");
47
- Utils.Arg.isRequired(protocol, "protocol");
48
- this.serverTimeoutInMilliseconds = serverTimeoutInMilliseconds !== null && serverTimeoutInMilliseconds !== void 0 ? serverTimeoutInMilliseconds : DEFAULT_TIMEOUT_IN_MS;
49
- this.keepAliveIntervalInMilliseconds = keepAliveIntervalInMilliseconds !== null && keepAliveIntervalInMilliseconds !== void 0 ? keepAliveIntervalInMilliseconds : DEFAULT_PING_INTERVAL_IN_MS;
50
- this._statefulReconnectBufferSize = statefulReconnectBufferSize !== null && statefulReconnectBufferSize !== void 0 ? statefulReconnectBufferSize : DEFAULT_STATEFUL_RECONNECT_BUFFER_SIZE;
51
- this._logger = logger;
52
- this._protocol = protocol;
53
- this.connection = connection;
54
- this._reconnectPolicy = reconnectPolicy;
55
- this._handshakeProtocol = new HandshakeProtocol.HandshakeProtocol();
56
- this.connection.onreceive = (data) => this._processIncomingData(data);
57
- this.connection.onclose = (error) => this._connectionClosed(error);
58
- this._callbacks = {};
59
- this._methods = {};
60
- this._closedCallbacks = [];
61
- this._reconnectingCallbacks = [];
62
- this._reconnectedCallbacks = [];
63
- this._invocationId = 0;
64
- this._receivedHandshakeResponse = false;
65
- this._connectionState = exports.HubConnectionState.Disconnected;
66
- this._connectionStarted = false;
67
- this._cachedPingMessage = this._protocol.writeMessage({ type: IHubProtocol.MessageType.Ping });
68
- }
69
- /** Indicates the state of the {@link HubConnection} to the server. */
70
- get state() {
71
- return this._connectionState;
72
- }
73
- /** Represents the connection id of the {@link HubConnection} on the server. The connection id will be null when the connection is either
74
- * in the disconnected state or if the negotiation step was skipped.
75
- */
76
- get connectionId() {
77
- return this.connection ? (this.connection.connectionId || null) : null;
78
- }
79
- /** Indicates the url of the {@link HubConnection} to the server. */
80
- get baseUrl() {
81
- return this.connection.baseUrl || "";
82
- }
83
- /**
84
- * Sets a new url for the HubConnection. Note that the url can only be changed when the connection is in either the Disconnected or
85
- * Reconnecting states.
86
- * @param {string} url The url to connect to.
87
- */
88
- set baseUrl(url) {
89
- if (this._connectionState !== exports.HubConnectionState.Disconnected && this._connectionState !== exports.HubConnectionState.Reconnecting) {
90
- throw new Error("The HubConnection must be in the Disconnected or Reconnecting state to change the url.");
91
- }
92
- if (!url) {
93
- throw new Error("The HubConnection url must be a valid url.");
94
- }
95
- this.connection.baseUrl = url;
96
- }
97
- /** Starts the connection.
98
- *
99
- * @returns {Promise<void>} A Promise that resolves when the connection has been successfully established, or rejects with an error.
100
- */
101
- start() {
102
- this._startPromise = this._startWithStateTransitions();
103
- return this._startPromise;
104
- }
105
- async _startWithStateTransitions() {
106
- if (this._connectionState !== exports.HubConnectionState.Disconnected) {
107
- return Promise.reject(new Error("Cannot start a HubConnection that is not in the 'Disconnected' state."));
108
- }
109
- this._connectionState = exports.HubConnectionState.Connecting;
110
- this._logger.log(ILogger.LogLevel.Debug, "Starting HubConnection.");
111
- try {
112
- await this._startInternal();
113
- if (Utils.Platform.isBrowser) {
114
- // Log when the browser freezes the tab so users know why their connection unexpectedly stopped working
115
- window.document.addEventListener("freeze", this._freezeEventListener);
116
- }
117
- this._connectionState = exports.HubConnectionState.Connected;
118
- this._connectionStarted = true;
119
- this._logger.log(ILogger.LogLevel.Debug, "HubConnection connected successfully.");
120
- }
121
- catch (e) {
122
- this._connectionState = exports.HubConnectionState.Disconnected;
123
- this._logger.log(ILogger.LogLevel.Debug, `HubConnection failed to start successfully because of error '${e}'.`);
124
- return Promise.reject(e);
125
- }
126
- }
127
- async _startInternal() {
128
- this._stopDuringStartError = undefined;
129
- this._receivedHandshakeResponse = false;
130
- // Set up the promise before any connection is (re)started otherwise it could race with received messages
131
- const handshakePromise = new Promise((resolve, reject) => {
132
- this._handshakeResolver = resolve;
133
- this._handshakeRejecter = reject;
134
- });
135
- await this.connection.start(this._protocol.transferFormat);
136
- try {
137
- let version = this._protocol.version;
138
- if (!this.connection.features.reconnect) {
139
- // Stateful Reconnect starts with HubProtocol version 2, newer clients connecting to older servers will fail to connect due to
140
- // the handshake only supporting version 1, so we will try to send version 1 during the handshake to keep old servers working.
141
- version = 1;
142
- }
143
- const handshakeRequest = {
144
- protocol: this._protocol.name,
145
- version,
146
- };
147
- this._logger.log(ILogger.LogLevel.Debug, "Sending handshake request.");
148
- await this._sendMessage(this._handshakeProtocol.writeHandshakeRequest(handshakeRequest));
149
- this._logger.log(ILogger.LogLevel.Information, `Using HubProtocol '${this._protocol.name}'.`);
150
- // defensively cleanup timeout in case we receive a message from the server before we finish start
151
- this._cleanupTimeout();
152
- this._resetTimeoutPeriod();
153
- this._resetKeepAliveInterval();
154
- await handshakePromise;
155
- // It's important to check the stopDuringStartError instead of just relying on the handshakePromise
156
- // being rejected on close, because this continuation can run after both the handshake completed successfully
157
- // and the connection was closed.
158
- if (this._stopDuringStartError) {
159
- // It's important to throw instead of returning a rejected promise, because we don't want to allow any state
160
- // transitions to occur between now and the calling code observing the exceptions. Returning a rejected promise
161
- // will cause the calling continuation to get scheduled to run later.
162
- // eslint-disable-next-line @typescript-eslint/no-throw-literal
163
- throw this._stopDuringStartError;
164
- }
165
- const useStatefulReconnect = this.connection.features.reconnect || false;
166
- if (useStatefulReconnect) {
167
- this._messageBuffer = new MessageBuffer.MessageBuffer(this._protocol, this.connection, this._statefulReconnectBufferSize);
168
- this.connection.features.disconnected = this._messageBuffer._disconnected.bind(this._messageBuffer);
169
- this.connection.features.resend = () => {
170
- if (this._messageBuffer) {
171
- return this._messageBuffer._resend();
172
- }
173
- };
174
- }
175
- if (!this.connection.features.inherentKeepAlive) {
176
- await this._sendMessage(this._cachedPingMessage);
177
- }
178
- }
179
- catch (e) {
180
- this._logger.log(ILogger.LogLevel.Debug, `Hub handshake failed with error '${e}' during start(). Stopping HubConnection.`);
181
- this._cleanupTimeout();
182
- this._cleanupPingTimer();
183
- // HttpConnection.stop() should not complete until after the onclose callback is invoked.
184
- // This will transition the HubConnection to the disconnected state before HttpConnection.stop() completes.
185
- await this.connection.stop(e);
186
- throw e;
187
- }
188
- }
189
- /** Stops the connection.
190
- *
191
- * @returns {Promise<void>} A Promise that resolves when the connection has been successfully terminated, or rejects with an error.
192
- */
193
- async stop() {
194
- // Capture the start promise before the connection might be restarted in an onclose callback.
195
- const startPromise = this._startPromise;
196
- this.connection.features.reconnect = false;
197
- this._stopPromise = this._stopInternal();
198
- await this._stopPromise;
199
- try {
200
- // Awaiting undefined continues immediately
201
- await startPromise;
202
- }
203
- catch (e) {
204
- // This exception is returned to the user as a rejected Promise from the start method.
205
- }
206
- }
207
- _stopInternal(error) {
208
- if (this._connectionState === exports.HubConnectionState.Disconnected) {
209
- this._logger.log(ILogger.LogLevel.Debug, `Call to HubConnection.stop(${error}) ignored because it is already in the disconnected state.`);
210
- return Promise.resolve();
211
- }
212
- if (this._connectionState === exports.HubConnectionState.Disconnecting) {
213
- this._logger.log(ILogger.LogLevel.Debug, `Call to HttpConnection.stop(${error}) ignored because the connection is already in the disconnecting state.`);
214
- return this._stopPromise;
215
- }
216
- const state = this._connectionState;
217
- this._connectionState = exports.HubConnectionState.Disconnecting;
218
- this._logger.log(ILogger.LogLevel.Debug, "Stopping HubConnection.");
219
- if (this._reconnectDelayHandle) {
220
- // We're in a reconnect delay which means the underlying connection is currently already stopped.
221
- // Just clear the handle to stop the reconnect loop (which no one is waiting on thankfully) and
222
- // fire the onclose callbacks.
223
- this._logger.log(ILogger.LogLevel.Debug, "Connection stopped during reconnect delay. Done reconnecting.");
224
- clearTimeout(this._reconnectDelayHandle);
225
- this._reconnectDelayHandle = undefined;
226
- this._completeClose();
227
- return Promise.resolve();
228
- }
229
- if (state === exports.HubConnectionState.Connected) {
230
- // eslint-disable-next-line @typescript-eslint/no-floating-promises
231
- this._sendCloseMessage();
232
- }
233
- this._cleanupTimeout();
234
- this._cleanupPingTimer();
235
- this._stopDuringStartError = error || new Errors.AbortError("The connection was stopped before the hub handshake could complete.");
236
- // HttpConnection.stop() should not complete until after either HttpConnection.start() fails
237
- // or the onclose callback is invoked. The onclose callback will transition the HubConnection
238
- // to the disconnected state if need be before HttpConnection.stop() completes.
239
- return this.connection.stop(error);
240
- }
241
- async _sendCloseMessage() {
242
- try {
243
- await this._sendWithProtocol(this._createCloseMessage());
244
- }
245
- catch {
246
- // Ignore, this is a best effort attempt to let the server know the client closed gracefully.
247
- }
248
- }
249
- /** Invokes a streaming hub method on the server using the specified name and arguments.
250
- *
251
- * @typeparam T The type of the items returned by the server.
252
- * @param {string} methodName The name of the server method to invoke.
253
- * @param {any[]} args The arguments used to invoke the server method.
254
- * @returns {IStreamResult<T>} An object that yields results from the server as they are received.
255
- */
256
- stream(methodName, ...args) {
257
- const [streams, streamIds] = this._replaceStreamingParams(args);
258
- const invocationDescriptor = this._createStreamInvocation(methodName, args, streamIds);
259
- // eslint-disable-next-line prefer-const
260
- let promiseQueue;
261
- const subject = new Subject.Subject();
262
- subject.cancelCallback = () => {
263
- const cancelInvocation = this._createCancelInvocation(invocationDescriptor.invocationId);
264
- delete this._callbacks[invocationDescriptor.invocationId];
265
- return promiseQueue.then(() => {
266
- return this._sendWithProtocol(cancelInvocation);
267
- });
268
- };
269
- this._callbacks[invocationDescriptor.invocationId] = (invocationEvent, error) => {
270
- if (error) {
271
- subject.error(error);
272
- return;
273
- }
274
- else if (invocationEvent) {
275
- // invocationEvent will not be null when an error is not passed to the callback
276
- if (invocationEvent.type === IHubProtocol.MessageType.Completion) {
277
- if (invocationEvent.error) {
278
- subject.error(new Error(invocationEvent.error));
279
- }
280
- else {
281
- subject.complete();
282
- }
283
- }
284
- else {
285
- subject.next((invocationEvent.item));
286
- }
287
- }
288
- };
289
- promiseQueue = this._sendWithProtocol(invocationDescriptor)
290
- .catch((e) => {
291
- subject.error(e);
292
- delete this._callbacks[invocationDescriptor.invocationId];
293
- });
294
- this._launchStreams(streams, promiseQueue);
295
- return subject;
296
- }
297
- _sendMessage(message) {
298
- this._resetKeepAliveInterval();
299
- return this.connection.send(message);
300
- }
301
- /**
302
- * Sends a js object to the server.
303
- * @param message The js object to serialize and send.
304
- */
305
- _sendWithProtocol(message) {
306
- if (this._messageBuffer) {
307
- return this._messageBuffer._send(message);
308
- }
309
- else {
310
- return this._sendMessage(this._protocol.writeMessage(message));
311
- }
312
- }
313
- /** Invokes a hub method on the server using the specified name and arguments. Does not wait for a response from the receiver.
314
- *
315
- * The Promise returned by this method resolves when the client has sent the invocation to the server. The server may still
316
- * be processing the invocation.
317
- *
318
- * @param {string} methodName The name of the server method to invoke.
319
- * @param {any[]} args The arguments used to invoke the server method.
320
- * @returns {Promise<void>} A Promise that resolves when the invocation has been successfully sent, or rejects with an error.
321
- */
322
- send(methodName, ...args) {
323
- const [streams, streamIds] = this._replaceStreamingParams(args);
324
- const sendPromise = this._sendWithProtocol(this._createInvocation(methodName, args, true, streamIds));
325
- this._launchStreams(streams, sendPromise);
326
- return sendPromise;
327
- }
328
- /** Invokes a hub method on the server using the specified name and arguments.
329
- *
330
- * The Promise returned by this method resolves when the server indicates it has finished invoking the method. When the promise
331
- * resolves, the server has finished invoking the method. If the server method returns a result, it is produced as the result of
332
- * resolving the Promise.
333
- *
334
- * @typeparam T The expected return type.
335
- * @param {string} methodName The name of the server method to invoke.
336
- * @param {any[]} args The arguments used to invoke the server method.
337
- * @returns {Promise<T>} A Promise that resolves with the result of the server method (if any), or rejects with an error.
338
- */
339
- invoke(methodName, ...args) {
340
- const [streams, streamIds] = this._replaceStreamingParams(args);
341
- const invocationDescriptor = this._createInvocation(methodName, args, false, streamIds);
342
- const p = new Promise((resolve, reject) => {
343
- // invocationId will always have a value for a non-blocking invocation
344
- this._callbacks[invocationDescriptor.invocationId] = (invocationEvent, error) => {
345
- if (error) {
346
- reject(error);
347
- return;
348
- }
349
- else if (invocationEvent) {
350
- // invocationEvent will not be null when an error is not passed to the callback
351
- if (invocationEvent.type === IHubProtocol.MessageType.Completion) {
352
- if (invocationEvent.error) {
353
- reject(new Error(invocationEvent.error));
354
- }
355
- else {
356
- resolve(invocationEvent.result);
357
- }
358
- }
359
- else {
360
- reject(new Error(`Unexpected message type: ${invocationEvent.type}`));
361
- }
362
- }
363
- };
364
- const promiseQueue = this._sendWithProtocol(invocationDescriptor)
365
- .catch((e) => {
366
- reject(e);
367
- // invocationId will always have a value for a non-blocking invocation
368
- delete this._callbacks[invocationDescriptor.invocationId];
369
- });
370
- this._launchStreams(streams, promiseQueue);
371
- });
372
- return p;
373
- }
374
- on(methodName, newMethod) {
375
- if (!methodName || !newMethod) {
376
- return;
377
- }
378
- methodName = methodName.toLowerCase();
379
- if (!this._methods[methodName]) {
380
- this._methods[methodName] = [];
381
- }
382
- // Preventing adding the same handler multiple times.
383
- if (this._methods[methodName].indexOf(newMethod) !== -1) {
384
- return;
385
- }
386
- this._methods[methodName].push(newMethod);
387
- }
388
- off(methodName, method) {
389
- if (!methodName) {
390
- return;
391
- }
392
- methodName = methodName.toLowerCase();
393
- const handlers = this._methods[methodName];
394
- if (!handlers) {
395
- return;
396
- }
397
- if (method) {
398
- const removeIdx = handlers.indexOf(method);
399
- if (removeIdx !== -1) {
400
- handlers.splice(removeIdx, 1);
401
- if (handlers.length === 0) {
402
- delete this._methods[methodName];
403
- }
404
- }
405
- }
406
- else {
407
- delete this._methods[methodName];
408
- }
409
- }
410
- /** Registers a handler that will be invoked when the connection is closed.
411
- *
412
- * @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).
413
- */
414
- onclose(callback) {
415
- if (callback) {
416
- this._closedCallbacks.push(callback);
417
- }
418
- }
419
- /** Registers a handler that will be invoked when the connection starts reconnecting.
420
- *
421
- * @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).
422
- */
423
- onreconnecting(callback) {
424
- if (callback) {
425
- this._reconnectingCallbacks.push(callback);
426
- }
427
- }
428
- /** Registers a handler that will be invoked when the connection successfully reconnects.
429
- *
430
- * @param {Function} callback The handler that will be invoked when the connection successfully reconnects.
431
- */
432
- onreconnected(callback) {
433
- if (callback) {
434
- this._reconnectedCallbacks.push(callback);
435
- }
436
- }
437
- _processIncomingData(data) {
438
- this._cleanupTimeout();
439
- if (!this._receivedHandshakeResponse) {
440
- data = this._processHandshakeResponse(data);
441
- this._receivedHandshakeResponse = true;
442
- }
443
- // Data may have all been read when processing handshake response
444
- if (data) {
445
- // Parse the messages
446
- const messages = this._protocol.parseMessages(data, this._logger);
447
- for (const message of messages) {
448
- if (this._messageBuffer && !this._messageBuffer._shouldProcessMessage(message)) {
449
- // Don't process the message, we are either waiting for a SequenceMessage or received a duplicate message
450
- continue;
451
- }
452
- switch (message.type) {
453
- case IHubProtocol.MessageType.Invocation:
454
- this._invokeClientMethod(message)
455
- .catch((e) => {
456
- this._logger.log(ILogger.LogLevel.Error, `Invoke client method threw error: ${Utils.getErrorString(e)}`);
457
- });
458
- break;
459
- case IHubProtocol.MessageType.StreamItem:
460
- case IHubProtocol.MessageType.Completion: {
461
- const callback = this._callbacks[message.invocationId];
462
- if (callback) {
463
- if (message.type === IHubProtocol.MessageType.Completion) {
464
- delete this._callbacks[message.invocationId];
465
- }
466
- try {
467
- callback(message);
468
- }
469
- catch (e) {
470
- this._logger.log(ILogger.LogLevel.Error, `Stream callback threw error: ${Utils.getErrorString(e)}`);
471
- }
472
- }
473
- break;
474
- }
475
- case IHubProtocol.MessageType.Ping:
476
- // Don't care about pings
477
- break;
478
- case IHubProtocol.MessageType.Close: {
479
- this._logger.log(ILogger.LogLevel.Information, "Close message received from server.");
480
- const error = message.error ? new Error("Server returned an error on close: " + message.error) : undefined;
481
- if (message.allowReconnect === true) {
482
- // It feels wrong not to await connection.stop() here, but processIncomingData is called as part of an onreceive callback which is not async,
483
- // this is already the behavior for serverTimeout(), and HttpConnection.Stop() should catch and log all possible exceptions.
484
- // eslint-disable-next-line @typescript-eslint/no-floating-promises
485
- this.connection.stop(error);
486
- }
487
- else {
488
- // We cannot await stopInternal() here, but subsequent calls to stop() will await this if stopInternal() is still ongoing.
489
- this._stopPromise = this._stopInternal(error);
490
- }
491
- break;
492
- }
493
- case IHubProtocol.MessageType.Ack:
494
- if (this._messageBuffer) {
495
- this._messageBuffer._ack(message);
496
- }
497
- break;
498
- case IHubProtocol.MessageType.Sequence:
499
- if (this._messageBuffer) {
500
- this._messageBuffer._resetSequence(message);
501
- }
502
- break;
503
- default:
504
- this._logger.log(ILogger.LogLevel.Warning, `Invalid message type: ${message.type}.`);
505
- break;
506
- }
507
- }
508
- }
509
- this._resetTimeoutPeriod();
510
- }
511
- _processHandshakeResponse(data) {
512
- let responseMessage;
513
- let remainingData;
514
- try {
515
- [remainingData, responseMessage] = this._handshakeProtocol.parseHandshakeResponse(data);
516
- }
517
- catch (e) {
518
- const message = "Error parsing handshake response: " + e;
519
- this._logger.log(ILogger.LogLevel.Error, message);
520
- const error = new Error(message);
521
- this._handshakeRejecter(error);
522
- throw error;
523
- }
524
- if (responseMessage.error) {
525
- const message = "Server returned handshake error: " + responseMessage.error;
526
- this._logger.log(ILogger.LogLevel.Error, message);
527
- const error = new Error(message);
528
- this._handshakeRejecter(error);
529
- throw error;
530
- }
531
- else {
532
- this._logger.log(ILogger.LogLevel.Debug, "Server handshake complete.");
533
- }
534
- this._handshakeResolver();
535
- return remainingData;
536
- }
537
- _resetKeepAliveInterval() {
538
- if (this.connection.features.inherentKeepAlive) {
539
- return;
540
- }
541
- // Set the time we want the next keep alive to be sent
542
- // Timer will be setup on next message receive
543
- this._nextKeepAlive = new Date().getTime() + this.keepAliveIntervalInMilliseconds;
544
- this._cleanupPingTimer();
545
- }
546
- _resetTimeoutPeriod() {
547
- if (!this.connection.features || !this.connection.features.inherentKeepAlive) {
548
- // Set the timeout timer
549
- this._timeoutHandle = setTimeout(() => this.serverTimeout(), this.serverTimeoutInMilliseconds);
550
- // Immediately fire Keep-Alive ping if nextPing is overdue to avoid dependency on JS timers
551
- let nextPing = this._nextKeepAlive - new Date().getTime();
552
- if (nextPing < 0) {
553
- if (this._connectionState === exports.HubConnectionState.Connected) {
554
- // eslint-disable-next-line @typescript-eslint/no-floating-promises
555
- this._trySendPingMessage();
556
- }
557
- return;
558
- }
559
- // Set keepAlive timer if there isn't one
560
- if (this._pingServerHandle === undefined) {
561
- if (nextPing < 0) {
562
- nextPing = 0;
563
- }
564
- // The timer needs to be set from a networking callback to avoid Chrome timer throttling from causing timers to run once a minute
565
- this._pingServerHandle = setTimeout(async () => {
566
- if (this._connectionState === exports.HubConnectionState.Connected) {
567
- await this._trySendPingMessage();
568
- }
569
- }, nextPing);
570
- }
571
- }
572
- }
573
- // eslint-disable-next-line @typescript-eslint/naming-convention
574
- serverTimeout() {
575
- // The server hasn't talked to us in a while. It doesn't like us anymore ... :(
576
- // Terminate the connection, but we don't need to wait on the promise. This could trigger reconnecting.
577
- // eslint-disable-next-line @typescript-eslint/no-floating-promises
578
- this.connection.stop(new Error("Server timeout elapsed without receiving a message from the server."));
579
- }
580
- async _invokeClientMethod(invocationMessage) {
581
- const methodName = invocationMessage.target.toLowerCase();
582
- const methods = this._methods[methodName];
583
- if (!methods) {
584
- this._logger.log(ILogger.LogLevel.Warning, `No client method with the name '${methodName}' found.`);
585
- // No handlers provided by client but the server is expecting a response still, so we send an error
586
- if (invocationMessage.invocationId) {
587
- this._logger.log(ILogger.LogLevel.Warning, `No result given for '${methodName}' method and invocation ID '${invocationMessage.invocationId}'.`);
588
- await this._sendWithProtocol(this._createCompletionMessage(invocationMessage.invocationId, "Client didn't provide a result.", null));
589
- }
590
- return;
591
- }
592
- // Avoid issues with handlers removing themselves thus modifying the list while iterating through it
593
- const methodsCopy = methods.slice();
594
- // Server expects a response
595
- const expectsResponse = invocationMessage.invocationId ? true : false;
596
- // We preserve the last result or exception but still call all handlers
597
- let res;
598
- let exception;
599
- let completionMessage;
600
- for (const m of methodsCopy) {
601
- try {
602
- const prevRes = res;
603
- res = await m.apply(this, invocationMessage.arguments);
604
- if (expectsResponse && res && prevRes) {
605
- this._logger.log(ILogger.LogLevel.Error, `Multiple results provided for '${methodName}'. Sending error to server.`);
606
- completionMessage = this._createCompletionMessage(invocationMessage.invocationId, `Client provided multiple results.`, null);
607
- }
608
- // Ignore exception if we got a result after, the exception will be logged
609
- exception = undefined;
610
- }
611
- catch (e) {
612
- exception = e;
613
- this._logger.log(ILogger.LogLevel.Error, `A callback for the method '${methodName}' threw error '${e}'.`);
614
- }
615
- }
616
- if (completionMessage) {
617
- await this._sendWithProtocol(completionMessage);
618
- }
619
- else if (expectsResponse) {
620
- // If there is an exception that means either no result was given or a handler after a result threw
621
- if (exception) {
622
- completionMessage = this._createCompletionMessage(invocationMessage.invocationId, `${exception}`, null);
623
- }
624
- else if (res !== undefined) {
625
- completionMessage = this._createCompletionMessage(invocationMessage.invocationId, null, res);
626
- }
627
- else {
628
- this._logger.log(ILogger.LogLevel.Warning, `No result given for '${methodName}' method and invocation ID '${invocationMessage.invocationId}'.`);
629
- // Client didn't provide a result or throw from a handler, server expects a response so we send an error
630
- completionMessage = this._createCompletionMessage(invocationMessage.invocationId, "Client didn't provide a result.", null);
631
- }
632
- await this._sendWithProtocol(completionMessage);
633
- }
634
- else {
635
- if (res) {
636
- this._logger.log(ILogger.LogLevel.Error, `Result given for '${methodName}' method but server is not expecting a result.`);
637
- }
638
- }
639
- }
640
- _connectionClosed(error) {
641
- this._logger.log(ILogger.LogLevel.Debug, `HubConnection.connectionClosed(${error}) called while in state ${this._connectionState}.`);
642
- // Triggering this.handshakeRejecter is insufficient because it could already be resolved without the continuation having run yet.
643
- this._stopDuringStartError = this._stopDuringStartError || error || new Errors.AbortError("The underlying connection was closed before the hub handshake could complete.");
644
- // If the handshake is in progress, start will be waiting for the handshake promise, so we complete it.
645
- // If it has already completed, this should just noop.
646
- if (this._handshakeResolver) {
647
- this._handshakeResolver();
648
- }
649
- this._cancelCallbacksWithError(error || new Error("Invocation canceled due to the underlying connection being closed."));
650
- this._cleanupTimeout();
651
- this._cleanupPingTimer();
652
- if (this._connectionState === exports.HubConnectionState.Disconnecting) {
653
- this._completeClose(error);
654
- }
655
- else if (this._connectionState === exports.HubConnectionState.Connected && this._reconnectPolicy) {
656
- // eslint-disable-next-line @typescript-eslint/no-floating-promises
657
- this._reconnect(error);
658
- }
659
- else if (this._connectionState === exports.HubConnectionState.Connected) {
660
- this._completeClose(error);
661
- }
662
- // If none of the above if conditions were true were called the HubConnection must be in either:
663
- // 1. The Connecting state in which case the handshakeResolver will complete it and stopDuringStartError will fail it.
664
- // 2. The Reconnecting state in which case the handshakeResolver will complete it and stopDuringStartError will fail the current reconnect attempt
665
- // and potentially continue the reconnect() loop.
666
- // 3. The Disconnected state in which case we're already done.
667
- }
668
- _completeClose(error) {
669
- if (this._connectionStarted) {
670
- this._connectionState = exports.HubConnectionState.Disconnected;
671
- this._connectionStarted = false;
672
- if (this._messageBuffer) {
673
- this._messageBuffer._dispose(error !== null && error !== void 0 ? error : new Error("Connection closed."));
674
- this._messageBuffer = undefined;
675
- }
676
- if (Utils.Platform.isBrowser) {
677
- window.document.removeEventListener("freeze", this._freezeEventListener);
678
- }
679
- try {
680
- this._closedCallbacks.forEach((c) => c.apply(this, [error]));
681
- }
682
- catch (e) {
683
- this._logger.log(ILogger.LogLevel.Error, `An onclose callback called with error '${error}' threw error '${e}'.`);
684
- }
685
- }
686
- }
687
- async _reconnect(error) {
688
- const reconnectStartTime = Date.now();
689
- let previousReconnectAttempts = 0;
690
- let retryError = error !== undefined ? error : new Error("Attempting to reconnect due to a unknown error.");
691
- let nextRetryDelay = this._getNextRetryDelay(previousReconnectAttempts, 0, retryError);
692
- if (nextRetryDelay === null) {
693
- this._logger.log(ILogger.LogLevel.Debug, "Connection not reconnecting because the IRetryPolicy returned null on the first reconnect attempt.");
694
- this._completeClose(error);
695
- return;
696
- }
697
- this._connectionState = exports.HubConnectionState.Reconnecting;
698
- if (error) {
699
- this._logger.log(ILogger.LogLevel.Information, `Connection reconnecting because of error '${error}'.`);
700
- }
701
- else {
702
- this._logger.log(ILogger.LogLevel.Information, "Connection reconnecting.");
703
- }
704
- if (this._reconnectingCallbacks.length !== 0) {
705
- try {
706
- this._reconnectingCallbacks.forEach((c) => c.apply(this, [error]));
707
- }
708
- catch (e) {
709
- this._logger.log(ILogger.LogLevel.Error, `An onreconnecting callback called with error '${error}' threw error '${e}'.`);
710
- }
711
- // Exit early if an onreconnecting callback called connection.stop().
712
- if (this._connectionState !== exports.HubConnectionState.Reconnecting) {
713
- this._logger.log(ILogger.LogLevel.Debug, "Connection left the reconnecting state in onreconnecting callback. Done reconnecting.");
714
- return;
715
- }
716
- }
717
- while (nextRetryDelay !== null) {
718
- this._logger.log(ILogger.LogLevel.Information, `Reconnect attempt number ${previousReconnectAttempts + 1} will start in ${nextRetryDelay} ms.`);
719
- await new Promise((resolve) => {
720
- this._reconnectDelayHandle = setTimeout(resolve, nextRetryDelay);
721
- });
722
- this._reconnectDelayHandle = undefined;
723
- if (this._connectionState !== exports.HubConnectionState.Reconnecting) {
724
- this._logger.log(ILogger.LogLevel.Debug, "Connection left the reconnecting state during reconnect delay. Done reconnecting.");
725
- return;
726
- }
727
- try {
728
- await this._startInternal();
729
- this._connectionState = exports.HubConnectionState.Connected;
730
- this._logger.log(ILogger.LogLevel.Information, "HubConnection reconnected successfully.");
731
- if (this._reconnectedCallbacks.length !== 0) {
732
- try {
733
- this._reconnectedCallbacks.forEach((c) => c.apply(this, [this.connection.connectionId]));
734
- }
735
- catch (e) {
736
- this._logger.log(ILogger.LogLevel.Error, `An onreconnected callback called with connectionId '${this.connection.connectionId}; threw error '${e}'.`);
737
- }
738
- }
739
- return;
740
- }
741
- catch (e) {
742
- this._logger.log(ILogger.LogLevel.Information, `Reconnect attempt failed because of error '${e}'.`);
743
- if (this._connectionState !== exports.HubConnectionState.Reconnecting) {
744
- this._logger.log(ILogger.LogLevel.Debug, `Connection moved to the '${this._connectionState}' from the reconnecting state during reconnect attempt. Done reconnecting.`);
745
- // The TypeScript compiler thinks that connectionState must be Connected here. The TypeScript compiler is wrong.
746
- if (this._connectionState === exports.HubConnectionState.Disconnecting) {
747
- this._completeClose();
748
- }
749
- return;
750
- }
751
- previousReconnectAttempts++;
752
- retryError = e instanceof Error ? e : new Error(e.toString());
753
- nextRetryDelay = this._getNextRetryDelay(previousReconnectAttempts, Date.now() - reconnectStartTime, retryError);
754
- }
755
- }
756
- this._logger.log(ILogger.LogLevel.Information, `Reconnect retries have been exhausted after ${Date.now() - reconnectStartTime} ms and ${previousReconnectAttempts} failed attempts. Connection disconnecting.`);
757
- this._completeClose();
758
- }
759
- _getNextRetryDelay(previousRetryCount, elapsedMilliseconds, retryReason) {
760
- try {
761
- return this._reconnectPolicy.nextRetryDelayInMilliseconds({
762
- elapsedMilliseconds,
763
- previousRetryCount,
764
- retryReason,
765
- });
766
- }
767
- catch (e) {
768
- this._logger.log(ILogger.LogLevel.Error, `IRetryPolicy.nextRetryDelayInMilliseconds(${previousRetryCount}, ${elapsedMilliseconds}) threw error '${e}'.`);
769
- return null;
770
- }
771
- }
772
- _cancelCallbacksWithError(error) {
773
- const callbacks = this._callbacks;
774
- this._callbacks = {};
775
- Object.keys(callbacks)
776
- .forEach((key) => {
777
- const callback = callbacks[key];
778
- try {
779
- callback(null, error);
780
- }
781
- catch (e) {
782
- this._logger.log(ILogger.LogLevel.Error, `Stream 'error' callback called with '${error}' threw error: ${Utils.getErrorString(e)}`);
783
- }
784
- });
785
- }
786
- _cleanupPingTimer() {
787
- if (this._pingServerHandle) {
788
- clearTimeout(this._pingServerHandle);
789
- this._pingServerHandle = undefined;
790
- }
791
- }
792
- _cleanupTimeout() {
793
- if (this._timeoutHandle) {
794
- clearTimeout(this._timeoutHandle);
795
- }
796
- }
797
- _createInvocation(methodName, args, nonblocking, streamIds) {
798
- if (nonblocking) {
799
- if (streamIds.length !== 0) {
800
- return {
801
- target: methodName,
802
- arguments: args,
803
- streamIds,
804
- type: IHubProtocol.MessageType.Invocation,
805
- };
806
- }
807
- else {
808
- return {
809
- target: methodName,
810
- arguments: args,
811
- type: IHubProtocol.MessageType.Invocation,
812
- };
813
- }
814
- }
815
- else {
816
- const invocationId = this._invocationId;
817
- this._invocationId++;
818
- if (streamIds.length !== 0) {
819
- return {
820
- target: methodName,
821
- arguments: args,
822
- invocationId: invocationId.toString(),
823
- streamIds,
824
- type: IHubProtocol.MessageType.Invocation,
825
- };
826
- }
827
- else {
828
- return {
829
- target: methodName,
830
- arguments: args,
831
- invocationId: invocationId.toString(),
832
- type: IHubProtocol.MessageType.Invocation,
833
- };
834
- }
835
- }
836
- }
837
- _launchStreams(streams, promiseQueue) {
838
- if (streams.length === 0) {
839
- return;
840
- }
841
- // Synchronize stream data so they arrive in-order on the server
842
- if (!promiseQueue) {
843
- promiseQueue = Promise.resolve();
844
- }
845
- // We want to iterate over the keys, since the keys are the stream ids
846
- // eslint-disable-next-line guard-for-in
847
- for (const streamId in streams) {
848
- streams[streamId].subscribe({
849
- complete: () => {
850
- promiseQueue = promiseQueue.then(() => this._sendWithProtocol(this._createCompletionMessage(streamId)));
851
- },
852
- error: (err) => {
853
- let message;
854
- if (err instanceof Error) {
855
- message = err.message;
856
- }
857
- else if (err && err.toString) {
858
- message = err.toString();
859
- }
860
- else {
861
- message = "Unknown error";
862
- }
863
- promiseQueue = promiseQueue.then(() => this._sendWithProtocol(this._createCompletionMessage(streamId, message)));
864
- },
865
- next: (item) => {
866
- promiseQueue = promiseQueue.then(() => this._sendWithProtocol(this._createStreamItemMessage(streamId, item)));
867
- },
868
- });
869
- }
870
- }
871
- _replaceStreamingParams(args) {
872
- const streams = [];
873
- const streamIds = [];
874
- for (let i = 0; i < args.length; i++) {
875
- const argument = args[i];
876
- if (this._isObservable(argument)) {
877
- const streamId = this._invocationId;
878
- this._invocationId++;
879
- // Store the stream for later use
880
- streams[streamId] = argument;
881
- streamIds.push(streamId.toString());
882
- // remove stream from args
883
- args.splice(i, 1);
884
- }
885
- }
886
- return [streams, streamIds];
887
- }
888
- _isObservable(arg) {
889
- // This allows other stream implementations to just work (like rxjs)
890
- return arg && arg.subscribe && typeof arg.subscribe === "function";
891
- }
892
- _createStreamInvocation(methodName, args, streamIds) {
893
- const invocationId = this._invocationId;
894
- this._invocationId++;
895
- if (streamIds.length !== 0) {
896
- return {
897
- target: methodName,
898
- arguments: args,
899
- invocationId: invocationId.toString(),
900
- streamIds,
901
- type: IHubProtocol.MessageType.StreamInvocation,
902
- };
903
- }
904
- else {
905
- return {
906
- target: methodName,
907
- arguments: args,
908
- invocationId: invocationId.toString(),
909
- type: IHubProtocol.MessageType.StreamInvocation,
910
- };
911
- }
912
- }
913
- _createCancelInvocation(id) {
914
- return {
915
- invocationId: id,
916
- type: IHubProtocol.MessageType.CancelInvocation,
917
- };
918
- }
919
- _createStreamItemMessage(id, item) {
920
- return {
921
- invocationId: id,
922
- item,
923
- type: IHubProtocol.MessageType.StreamItem,
924
- };
925
- }
926
- _createCompletionMessage(id, error, result) {
927
- if (error) {
928
- return {
929
- error,
930
- invocationId: id,
931
- type: IHubProtocol.MessageType.Completion,
932
- };
933
- }
934
- return {
935
- invocationId: id,
936
- result,
937
- type: IHubProtocol.MessageType.Completion,
938
- };
939
- }
940
- _createCloseMessage() {
941
- return { type: IHubProtocol.MessageType.Close };
942
- }
943
- async _trySendPingMessage() {
944
- try {
945
- await this._sendMessage(this._cachedPingMessage);
946
- }
947
- catch {
948
- // We don't care about the error. It should be seen elsewhere in the client.
949
- // The connection is probably in a bad or closed state now, cleanup the timer so it stops triggering
950
- this._cleanupPingTimer();
951
- }
952
- }
1
+ "use strict";
2
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
+ const HandshakeProtocol = require("./HandshakeProtocol.js");
4
+ const Errors = require("./Errors.js");
5
+ const IHubProtocol = require("./IHubProtocol.js");
6
+ const ILogger = require("./ILogger.js");
7
+ const Subject = require("./Subject.js");
8
+ const Utils = require("./Utils.js");
9
+ const MessageBuffer = require("./MessageBuffer.js");
10
+ const DEFAULT_TIMEOUT_IN_MS = 30 * 1e3;
11
+ const DEFAULT_PING_INTERVAL_IN_MS = 15 * 1e3;
12
+ const DEFAULT_STATEFUL_RECONNECT_BUFFER_SIZE = 1e5;
13
+ exports.HubConnectionState = void 0;
14
+ (function(HubConnectionState) {
15
+ HubConnectionState["Disconnected"] = "Disconnected";
16
+ HubConnectionState["Connecting"] = "Connecting";
17
+ HubConnectionState["Connected"] = "Connected";
18
+ HubConnectionState["Disconnecting"] = "Disconnecting";
19
+ HubConnectionState["Reconnecting"] = "Reconnecting";
20
+ })(exports.HubConnectionState || (exports.HubConnectionState = {}));
21
+ class HubConnection {
22
+ /** @internal */
23
+ // Using a public static factory method means we can have a private constructor and an _internal_
24
+ // create method that can be used by HubConnectionBuilder. An "internal" constructor would just
25
+ // be stripped away and the '.d.ts' file would have no constructor, which is interpreted as a
26
+ // public parameter-less constructor.
27
+ static create(connection, logger, protocol, reconnectPolicy, serverTimeoutInMilliseconds, keepAliveIntervalInMilliseconds, statefulReconnectBufferSize) {
28
+ return new HubConnection(connection, logger, protocol, reconnectPolicy, serverTimeoutInMilliseconds, keepAliveIntervalInMilliseconds, statefulReconnectBufferSize);
29
+ }
30
+ constructor(connection, logger, protocol, reconnectPolicy, serverTimeoutInMilliseconds, keepAliveIntervalInMilliseconds, statefulReconnectBufferSize) {
31
+ this._nextKeepAlive = 0;
32
+ this._freezeEventListener = () => {
33
+ this._logger.log(ILogger.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://learn.microsoft.com/aspnet/core/signalr/javascript-client#bsleep");
34
+ };
35
+ Utils.Arg.isRequired(connection, "connection");
36
+ Utils.Arg.isRequired(logger, "logger");
37
+ Utils.Arg.isRequired(protocol, "protocol");
38
+ this.serverTimeoutInMilliseconds = serverTimeoutInMilliseconds !== null && serverTimeoutInMilliseconds !== void 0 ? serverTimeoutInMilliseconds : DEFAULT_TIMEOUT_IN_MS;
39
+ this.keepAliveIntervalInMilliseconds = keepAliveIntervalInMilliseconds !== null && keepAliveIntervalInMilliseconds !== void 0 ? keepAliveIntervalInMilliseconds : DEFAULT_PING_INTERVAL_IN_MS;
40
+ this._statefulReconnectBufferSize = statefulReconnectBufferSize !== null && statefulReconnectBufferSize !== void 0 ? statefulReconnectBufferSize : DEFAULT_STATEFUL_RECONNECT_BUFFER_SIZE;
41
+ this._logger = logger;
42
+ this._protocol = protocol;
43
+ this.connection = connection;
44
+ this._reconnectPolicy = reconnectPolicy;
45
+ this._handshakeProtocol = new HandshakeProtocol.HandshakeProtocol();
46
+ this.connection.onreceive = (data) => this._processIncomingData(data);
47
+ this.connection.onclose = (error) => this._connectionClosed(error);
48
+ this._callbacks = {};
49
+ this._methods = {};
50
+ this._closedCallbacks = [];
51
+ this._reconnectingCallbacks = [];
52
+ this._reconnectedCallbacks = [];
53
+ this._invocationId = 0;
54
+ this._receivedHandshakeResponse = false;
55
+ this._connectionState = exports.HubConnectionState.Disconnected;
56
+ this._connectionStarted = false;
57
+ this._cachedPingMessage = this._protocol.writeMessage({ type: IHubProtocol.MessageType.Ping });
58
+ }
59
+ /** Indicates the state of the {@link HubConnection} to the server. */
60
+ get state() {
61
+ return this._connectionState;
62
+ }
63
+ /** Represents the connection id of the {@link HubConnection} on the server. The connection id will be null when the connection is either
64
+ * in the disconnected state or if the negotiation step was skipped.
65
+ */
66
+ get connectionId() {
67
+ return this.connection ? this.connection.connectionId || null : null;
68
+ }
69
+ /** Indicates the url of the {@link HubConnection} to the server. */
70
+ get baseUrl() {
71
+ return this.connection.baseUrl || "";
72
+ }
73
+ /**
74
+ * Sets a new url for the HubConnection. Note that the url can only be changed when the connection is in either the Disconnected or
75
+ * Reconnecting states.
76
+ * @param {string} url The url to connect to.
77
+ */
78
+ set baseUrl(url) {
79
+ if (this._connectionState !== exports.HubConnectionState.Disconnected && this._connectionState !== exports.HubConnectionState.Reconnecting) {
80
+ throw new Error("The HubConnection must be in the Disconnected or Reconnecting state to change the url.");
81
+ }
82
+ if (!url) {
83
+ throw new Error("The HubConnection url must be a valid url.");
84
+ }
85
+ this.connection.baseUrl = url;
86
+ }
87
+ /** Starts the connection.
88
+ *
89
+ * @returns {Promise<void>} A Promise that resolves when the connection has been successfully established, or rejects with an error.
90
+ */
91
+ start() {
92
+ this._startPromise = this._startWithStateTransitions();
93
+ return this._startPromise;
94
+ }
95
+ async _startWithStateTransitions() {
96
+ if (this._connectionState !== exports.HubConnectionState.Disconnected) {
97
+ return Promise.reject(new Error("Cannot start a HubConnection that is not in the 'Disconnected' state."));
98
+ }
99
+ this._connectionState = exports.HubConnectionState.Connecting;
100
+ this._logger.log(ILogger.LogLevel.Debug, "Starting HubConnection.");
101
+ try {
102
+ await this._startInternal();
103
+ if (Utils.Platform.isBrowser) {
104
+ window.document.addEventListener("freeze", this._freezeEventListener);
105
+ }
106
+ this._connectionState = exports.HubConnectionState.Connected;
107
+ this._connectionStarted = true;
108
+ this._logger.log(ILogger.LogLevel.Debug, "HubConnection connected successfully.");
109
+ } catch (e) {
110
+ this._connectionState = exports.HubConnectionState.Disconnected;
111
+ this._logger.log(ILogger.LogLevel.Debug, `HubConnection failed to start successfully because of error '${e}'.`);
112
+ return Promise.reject(e);
113
+ }
114
+ }
115
+ async _startInternal() {
116
+ this._stopDuringStartError = void 0;
117
+ this._receivedHandshakeResponse = false;
118
+ const handshakePromise = new Promise((resolve, reject) => {
119
+ this._handshakeResolver = resolve;
120
+ this._handshakeRejecter = reject;
121
+ });
122
+ await this.connection.start(this._protocol.transferFormat);
123
+ try {
124
+ let version = this._protocol.version;
125
+ if (!this.connection.features.reconnect) {
126
+ version = 1;
127
+ }
128
+ const handshakeRequest = {
129
+ protocol: this._protocol.name,
130
+ version
131
+ };
132
+ this._logger.log(ILogger.LogLevel.Debug, "Sending handshake request.");
133
+ await this._sendMessage(this._handshakeProtocol.writeHandshakeRequest(handshakeRequest));
134
+ this._logger.log(ILogger.LogLevel.Information, `Using HubProtocol '${this._protocol.name}'.`);
135
+ this._cleanupTimeout();
136
+ this._resetTimeoutPeriod();
137
+ this._resetKeepAliveInterval();
138
+ await handshakePromise;
139
+ if (this._stopDuringStartError) {
140
+ throw this._stopDuringStartError;
141
+ }
142
+ const useStatefulReconnect = this.connection.features.reconnect || false;
143
+ if (useStatefulReconnect) {
144
+ this._messageBuffer = new MessageBuffer.MessageBuffer(this._protocol, this.connection, this._statefulReconnectBufferSize);
145
+ this.connection.features.disconnected = this._messageBuffer._disconnected.bind(this._messageBuffer);
146
+ this.connection.features.resend = () => {
147
+ if (this._messageBuffer) {
148
+ return this._messageBuffer._resend();
149
+ }
150
+ };
151
+ }
152
+ if (!this.connection.features.inherentKeepAlive) {
153
+ await this._sendMessage(this._cachedPingMessage);
154
+ }
155
+ } catch (e) {
156
+ this._logger.log(ILogger.LogLevel.Debug, `Hub handshake failed with error '${e}' during start(). Stopping HubConnection.`);
157
+ this._cleanupTimeout();
158
+ this._cleanupPingTimer();
159
+ await this.connection.stop(e);
160
+ throw e;
161
+ }
162
+ }
163
+ /** Stops the connection.
164
+ *
165
+ * @returns {Promise<void>} A Promise that resolves when the connection has been successfully terminated, or rejects with an error.
166
+ */
167
+ async stop() {
168
+ const startPromise = this._startPromise;
169
+ this.connection.features.reconnect = false;
170
+ this._stopPromise = this._stopInternal();
171
+ await this._stopPromise;
172
+ try {
173
+ await startPromise;
174
+ } catch (e) {
175
+ }
176
+ }
177
+ _stopInternal(error) {
178
+ if (this._connectionState === exports.HubConnectionState.Disconnected) {
179
+ this._logger.log(ILogger.LogLevel.Debug, `Call to HubConnection.stop(${error}) ignored because it is already in the disconnected state.`);
180
+ return Promise.resolve();
181
+ }
182
+ if (this._connectionState === exports.HubConnectionState.Disconnecting) {
183
+ this._logger.log(ILogger.LogLevel.Debug, `Call to HttpConnection.stop(${error}) ignored because the connection is already in the disconnecting state.`);
184
+ return this._stopPromise;
185
+ }
186
+ const state = this._connectionState;
187
+ this._connectionState = exports.HubConnectionState.Disconnecting;
188
+ this._logger.log(ILogger.LogLevel.Debug, "Stopping HubConnection.");
189
+ if (this._reconnectDelayHandle) {
190
+ this._logger.log(ILogger.LogLevel.Debug, "Connection stopped during reconnect delay. Done reconnecting.");
191
+ clearTimeout(this._reconnectDelayHandle);
192
+ this._reconnectDelayHandle = void 0;
193
+ this._completeClose();
194
+ return Promise.resolve();
195
+ }
196
+ if (state === exports.HubConnectionState.Connected) {
197
+ this._sendCloseMessage();
198
+ }
199
+ this._cleanupTimeout();
200
+ this._cleanupPingTimer();
201
+ this._stopDuringStartError = error || new Errors.AbortError("The connection was stopped before the hub handshake could complete.");
202
+ return this.connection.stop(error);
203
+ }
204
+ async _sendCloseMessage() {
205
+ try {
206
+ await this._sendWithProtocol(this._createCloseMessage());
207
+ } catch {
208
+ }
209
+ }
210
+ /** Invokes a streaming hub method on the server using the specified name and arguments.
211
+ *
212
+ * @typeparam T The type of the items returned by the server.
213
+ * @param {string} methodName The name of the server method to invoke.
214
+ * @param {any[]} args The arguments used to invoke the server method.
215
+ * @returns {IStreamResult<T>} An object that yields results from the server as they are received.
216
+ */
217
+ stream(methodName, ...args) {
218
+ const [streams, streamIds] = this._replaceStreamingParams(args);
219
+ const invocationDescriptor = this._createStreamInvocation(methodName, args, streamIds);
220
+ let promiseQueue;
221
+ const subject = new Subject.Subject();
222
+ subject.cancelCallback = () => {
223
+ const cancelInvocation = this._createCancelInvocation(invocationDescriptor.invocationId);
224
+ delete this._callbacks[invocationDescriptor.invocationId];
225
+ return promiseQueue.then(() => {
226
+ return this._sendWithProtocol(cancelInvocation);
227
+ });
228
+ };
229
+ this._callbacks[invocationDescriptor.invocationId] = (invocationEvent, error) => {
230
+ if (error) {
231
+ subject.error(error);
232
+ return;
233
+ } else if (invocationEvent) {
234
+ if (invocationEvent.type === IHubProtocol.MessageType.Completion) {
235
+ if (invocationEvent.error) {
236
+ subject.error(new Error(invocationEvent.error));
237
+ } else {
238
+ subject.complete();
239
+ }
240
+ } else {
241
+ subject.next(invocationEvent.item);
242
+ }
243
+ }
244
+ };
245
+ promiseQueue = this._sendWithProtocol(invocationDescriptor).catch((e) => {
246
+ subject.error(e);
247
+ delete this._callbacks[invocationDescriptor.invocationId];
248
+ });
249
+ this._launchStreams(streams, promiseQueue);
250
+ return subject;
251
+ }
252
+ _sendMessage(message) {
253
+ this._resetKeepAliveInterval();
254
+ return this.connection.send(message);
255
+ }
256
+ /**
257
+ * Sends a js object to the server.
258
+ * @param message The js object to serialize and send.
259
+ */
260
+ _sendWithProtocol(message) {
261
+ if (this._messageBuffer) {
262
+ return this._messageBuffer._send(message);
263
+ } else {
264
+ return this._sendMessage(this._protocol.writeMessage(message));
265
+ }
266
+ }
267
+ /** Invokes a hub method on the server using the specified name and arguments. Does not wait for a response from the receiver.
268
+ *
269
+ * The Promise returned by this method resolves when the client has sent the invocation to the server. The server may still
270
+ * be processing the invocation.
271
+ *
272
+ * @param {string} methodName The name of the server method to invoke.
273
+ * @param {any[]} args The arguments used to invoke the server method.
274
+ * @returns {Promise<void>} A Promise that resolves when the invocation has been successfully sent, or rejects with an error.
275
+ */
276
+ send(methodName, ...args) {
277
+ const [streams, streamIds] = this._replaceStreamingParams(args);
278
+ const sendPromise = this._sendWithProtocol(this._createInvocation(methodName, args, true, streamIds));
279
+ this._launchStreams(streams, sendPromise);
280
+ return sendPromise;
281
+ }
282
+ /** Invokes a hub method on the server using the specified name and arguments.
283
+ *
284
+ * The Promise returned by this method resolves when the server indicates it has finished invoking the method. When the promise
285
+ * resolves, the server has finished invoking the method. If the server method returns a result, it is produced as the result of
286
+ * resolving the Promise.
287
+ *
288
+ * @typeparam T The expected return type.
289
+ * @param {string} methodName The name of the server method to invoke.
290
+ * @param {any[]} args The arguments used to invoke the server method.
291
+ * @returns {Promise<T>} A Promise that resolves with the result of the server method (if any), or rejects with an error.
292
+ */
293
+ invoke(methodName, ...args) {
294
+ const [streams, streamIds] = this._replaceStreamingParams(args);
295
+ const invocationDescriptor = this._createInvocation(methodName, args, false, streamIds);
296
+ const p = new Promise((resolve, reject) => {
297
+ this._callbacks[invocationDescriptor.invocationId] = (invocationEvent, error) => {
298
+ if (error) {
299
+ reject(error);
300
+ return;
301
+ } else if (invocationEvent) {
302
+ if (invocationEvent.type === IHubProtocol.MessageType.Completion) {
303
+ if (invocationEvent.error) {
304
+ reject(new Error(invocationEvent.error));
305
+ } else {
306
+ resolve(invocationEvent.result);
307
+ }
308
+ } else {
309
+ reject(new Error(`Unexpected message type: ${invocationEvent.type}`));
310
+ }
311
+ }
312
+ };
313
+ const promiseQueue = this._sendWithProtocol(invocationDescriptor).catch((e) => {
314
+ reject(e);
315
+ delete this._callbacks[invocationDescriptor.invocationId];
316
+ });
317
+ this._launchStreams(streams, promiseQueue);
318
+ });
319
+ return p;
320
+ }
321
+ on(methodName, newMethod) {
322
+ if (!methodName || !newMethod) {
323
+ return;
324
+ }
325
+ methodName = methodName.toLowerCase();
326
+ if (!this._methods[methodName]) {
327
+ this._methods[methodName] = [];
328
+ }
329
+ if (this._methods[methodName].indexOf(newMethod) !== -1) {
330
+ return;
331
+ }
332
+ this._methods[methodName].push(newMethod);
333
+ }
334
+ off(methodName, method) {
335
+ if (!methodName) {
336
+ return;
337
+ }
338
+ methodName = methodName.toLowerCase();
339
+ const handlers = this._methods[methodName];
340
+ if (!handlers) {
341
+ return;
342
+ }
343
+ if (method) {
344
+ const removeIdx = handlers.indexOf(method);
345
+ if (removeIdx !== -1) {
346
+ handlers.splice(removeIdx, 1);
347
+ if (handlers.length === 0) {
348
+ delete this._methods[methodName];
349
+ }
350
+ }
351
+ } else {
352
+ delete this._methods[methodName];
353
+ }
354
+ }
355
+ /** Registers a handler that will be invoked when the connection is closed.
356
+ *
357
+ * @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).
358
+ */
359
+ onclose(callback) {
360
+ if (callback) {
361
+ this._closedCallbacks.push(callback);
362
+ }
363
+ }
364
+ /** Registers a handler that will be invoked when the connection starts reconnecting.
365
+ *
366
+ * @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).
367
+ */
368
+ onreconnecting(callback) {
369
+ if (callback) {
370
+ this._reconnectingCallbacks.push(callback);
371
+ }
372
+ }
373
+ /** Registers a handler that will be invoked when the connection successfully reconnects.
374
+ *
375
+ * @param {Function} callback The handler that will be invoked when the connection successfully reconnects.
376
+ */
377
+ onreconnected(callback) {
378
+ if (callback) {
379
+ this._reconnectedCallbacks.push(callback);
380
+ }
381
+ }
382
+ _processIncomingData(data) {
383
+ this._cleanupTimeout();
384
+ if (!this._receivedHandshakeResponse) {
385
+ data = this._processHandshakeResponse(data);
386
+ this._receivedHandshakeResponse = true;
387
+ }
388
+ if (data) {
389
+ const messages = this._protocol.parseMessages(data, this._logger);
390
+ for (const message of messages) {
391
+ if (this._messageBuffer && !this._messageBuffer._shouldProcessMessage(message)) {
392
+ continue;
393
+ }
394
+ switch (message.type) {
395
+ case IHubProtocol.MessageType.Invocation:
396
+ this._invokeClientMethod(message).catch((e) => {
397
+ this._logger.log(ILogger.LogLevel.Error, `Invoke client method threw error: ${Utils.getErrorString(e)}`);
398
+ });
399
+ break;
400
+ case IHubProtocol.MessageType.StreamItem:
401
+ case IHubProtocol.MessageType.Completion: {
402
+ const callback = this._callbacks[message.invocationId];
403
+ if (callback) {
404
+ if (message.type === IHubProtocol.MessageType.Completion) {
405
+ delete this._callbacks[message.invocationId];
406
+ }
407
+ try {
408
+ callback(message);
409
+ } catch (e) {
410
+ this._logger.log(ILogger.LogLevel.Error, `Stream callback threw error: ${Utils.getErrorString(e)}`);
411
+ }
412
+ }
413
+ break;
414
+ }
415
+ case IHubProtocol.MessageType.Ping:
416
+ break;
417
+ case IHubProtocol.MessageType.Close: {
418
+ this._logger.log(ILogger.LogLevel.Information, "Close message received from server.");
419
+ const error = message.error ? new Error("Server returned an error on close: " + message.error) : void 0;
420
+ if (message.allowReconnect === true) {
421
+ this.connection.stop(error);
422
+ } else {
423
+ this._stopPromise = this._stopInternal(error);
424
+ }
425
+ break;
426
+ }
427
+ case IHubProtocol.MessageType.Ack:
428
+ if (this._messageBuffer) {
429
+ this._messageBuffer._ack(message);
430
+ }
431
+ break;
432
+ case IHubProtocol.MessageType.Sequence:
433
+ if (this._messageBuffer) {
434
+ this._messageBuffer._resetSequence(message);
435
+ }
436
+ break;
437
+ default:
438
+ this._logger.log(ILogger.LogLevel.Warning, `Invalid message type: ${message.type}.`);
439
+ break;
440
+ }
441
+ }
442
+ }
443
+ this._resetTimeoutPeriod();
444
+ }
445
+ _processHandshakeResponse(data) {
446
+ let responseMessage;
447
+ let remainingData;
448
+ try {
449
+ [remainingData, responseMessage] = this._handshakeProtocol.parseHandshakeResponse(data);
450
+ } catch (e) {
451
+ const message = "Error parsing handshake response: " + e;
452
+ this._logger.log(ILogger.LogLevel.Error, message);
453
+ const error = new Error(message);
454
+ this._handshakeRejecter(error);
455
+ throw error;
456
+ }
457
+ if (responseMessage.error) {
458
+ const message = "Server returned handshake error: " + responseMessage.error;
459
+ this._logger.log(ILogger.LogLevel.Error, message);
460
+ const error = new Error(message);
461
+ this._handshakeRejecter(error);
462
+ throw error;
463
+ } else {
464
+ this._logger.log(ILogger.LogLevel.Debug, "Server handshake complete.");
465
+ }
466
+ this._handshakeResolver();
467
+ return remainingData;
468
+ }
469
+ _resetKeepAliveInterval() {
470
+ if (this.connection.features.inherentKeepAlive) {
471
+ return;
472
+ }
473
+ this._nextKeepAlive = (/* @__PURE__ */ new Date()).getTime() + this.keepAliveIntervalInMilliseconds;
474
+ this._cleanupPingTimer();
475
+ }
476
+ _resetTimeoutPeriod() {
477
+ if (!this.connection.features || !this.connection.features.inherentKeepAlive) {
478
+ this._timeoutHandle = setTimeout(() => this.serverTimeout(), this.serverTimeoutInMilliseconds);
479
+ let nextPing = this._nextKeepAlive - (/* @__PURE__ */ new Date()).getTime();
480
+ if (nextPing < 0) {
481
+ if (this._connectionState === exports.HubConnectionState.Connected) {
482
+ this._trySendPingMessage();
483
+ }
484
+ return;
485
+ }
486
+ if (this._pingServerHandle === void 0) {
487
+ if (nextPing < 0) {
488
+ nextPing = 0;
489
+ }
490
+ this._pingServerHandle = setTimeout(async () => {
491
+ if (this._connectionState === exports.HubConnectionState.Connected) {
492
+ await this._trySendPingMessage();
493
+ }
494
+ }, nextPing);
495
+ }
496
+ }
497
+ }
498
+ // eslint-disable-next-line @typescript-eslint/naming-convention
499
+ serverTimeout() {
500
+ this.connection.stop(new Error("Server timeout elapsed without receiving a message from the server."));
501
+ }
502
+ async _invokeClientMethod(invocationMessage) {
503
+ const methodName = invocationMessage.target.toLowerCase();
504
+ const methods = this._methods[methodName];
505
+ if (!methods) {
506
+ this._logger.log(ILogger.LogLevel.Warning, `No client method with the name '${methodName}' found.`);
507
+ if (invocationMessage.invocationId) {
508
+ this._logger.log(ILogger.LogLevel.Warning, `No result given for '${methodName}' method and invocation ID '${invocationMessage.invocationId}'.`);
509
+ await this._sendWithProtocol(this._createCompletionMessage(invocationMessage.invocationId, "Client didn't provide a result.", null));
510
+ }
511
+ return;
512
+ }
513
+ const methodsCopy = methods.slice();
514
+ const expectsResponse = invocationMessage.invocationId ? true : false;
515
+ let res;
516
+ let exception;
517
+ let completionMessage;
518
+ for (const m of methodsCopy) {
519
+ try {
520
+ const prevRes = res;
521
+ res = await m.apply(this, invocationMessage.arguments);
522
+ if (expectsResponse && res && prevRes) {
523
+ this._logger.log(ILogger.LogLevel.Error, `Multiple results provided for '${methodName}'. Sending error to server.`);
524
+ completionMessage = this._createCompletionMessage(invocationMessage.invocationId, `Client provided multiple results.`, null);
525
+ }
526
+ exception = void 0;
527
+ } catch (e) {
528
+ exception = e;
529
+ this._logger.log(ILogger.LogLevel.Error, `A callback for the method '${methodName}' threw error '${e}'.`);
530
+ }
531
+ }
532
+ if (completionMessage) {
533
+ await this._sendWithProtocol(completionMessage);
534
+ } else if (expectsResponse) {
535
+ if (exception) {
536
+ completionMessage = this._createCompletionMessage(invocationMessage.invocationId, `${exception}`, null);
537
+ } else if (res !== void 0) {
538
+ completionMessage = this._createCompletionMessage(invocationMessage.invocationId, null, res);
539
+ } else {
540
+ this._logger.log(ILogger.LogLevel.Warning, `No result given for '${methodName}' method and invocation ID '${invocationMessage.invocationId}'.`);
541
+ completionMessage = this._createCompletionMessage(invocationMessage.invocationId, "Client didn't provide a result.", null);
542
+ }
543
+ await this._sendWithProtocol(completionMessage);
544
+ } else {
545
+ if (res) {
546
+ this._logger.log(ILogger.LogLevel.Error, `Result given for '${methodName}' method but server is not expecting a result.`);
547
+ }
548
+ }
549
+ }
550
+ _connectionClosed(error) {
551
+ this._logger.log(ILogger.LogLevel.Debug, `HubConnection.connectionClosed(${error}) called while in state ${this._connectionState}.`);
552
+ this._stopDuringStartError = this._stopDuringStartError || error || new Errors.AbortError("The underlying connection was closed before the hub handshake could complete.");
553
+ if (this._handshakeResolver) {
554
+ this._handshakeResolver();
555
+ }
556
+ this._cancelCallbacksWithError(error || new Error("Invocation canceled due to the underlying connection being closed."));
557
+ this._cleanupTimeout();
558
+ this._cleanupPingTimer();
559
+ if (this._connectionState === exports.HubConnectionState.Disconnecting) {
560
+ this._completeClose(error);
561
+ } else if (this._connectionState === exports.HubConnectionState.Connected && this._reconnectPolicy) {
562
+ this._reconnect(error);
563
+ } else if (this._connectionState === exports.HubConnectionState.Connected) {
564
+ this._completeClose(error);
565
+ }
566
+ }
567
+ _completeClose(error) {
568
+ if (this._connectionStarted) {
569
+ this._connectionState = exports.HubConnectionState.Disconnected;
570
+ this._connectionStarted = false;
571
+ if (this._messageBuffer) {
572
+ this._messageBuffer._dispose(error !== null && error !== void 0 ? error : new Error("Connection closed."));
573
+ this._messageBuffer = void 0;
574
+ }
575
+ if (Utils.Platform.isBrowser) {
576
+ window.document.removeEventListener("freeze", this._freezeEventListener);
577
+ }
578
+ try {
579
+ this._closedCallbacks.forEach((c) => c.apply(this, [error]));
580
+ } catch (e) {
581
+ this._logger.log(ILogger.LogLevel.Error, `An onclose callback called with error '${error}' threw error '${e}'.`);
582
+ }
583
+ }
584
+ }
585
+ async _reconnect(error) {
586
+ const reconnectStartTime = Date.now();
587
+ let previousReconnectAttempts = 0;
588
+ let retryError = error !== void 0 ? error : new Error("Attempting to reconnect due to a unknown error.");
589
+ let nextRetryDelay = this._getNextRetryDelay(previousReconnectAttempts, 0, retryError);
590
+ if (nextRetryDelay === null) {
591
+ this._logger.log(ILogger.LogLevel.Debug, "Connection not reconnecting because the IRetryPolicy returned null on the first reconnect attempt.");
592
+ this._completeClose(error);
593
+ return;
594
+ }
595
+ this._connectionState = exports.HubConnectionState.Reconnecting;
596
+ if (error) {
597
+ this._logger.log(ILogger.LogLevel.Information, `Connection reconnecting because of error '${error}'.`);
598
+ } else {
599
+ this._logger.log(ILogger.LogLevel.Information, "Connection reconnecting.");
600
+ }
601
+ if (this._reconnectingCallbacks.length !== 0) {
602
+ try {
603
+ this._reconnectingCallbacks.forEach((c) => c.apply(this, [error]));
604
+ } catch (e) {
605
+ this._logger.log(ILogger.LogLevel.Error, `An onreconnecting callback called with error '${error}' threw error '${e}'.`);
606
+ }
607
+ if (this._connectionState !== exports.HubConnectionState.Reconnecting) {
608
+ this._logger.log(ILogger.LogLevel.Debug, "Connection left the reconnecting state in onreconnecting callback. Done reconnecting.");
609
+ return;
610
+ }
611
+ }
612
+ while (nextRetryDelay !== null) {
613
+ this._logger.log(ILogger.LogLevel.Information, `Reconnect attempt number ${previousReconnectAttempts + 1} will start in ${nextRetryDelay} ms.`);
614
+ await new Promise((resolve) => {
615
+ this._reconnectDelayHandle = setTimeout(resolve, nextRetryDelay);
616
+ });
617
+ this._reconnectDelayHandle = void 0;
618
+ if (this._connectionState !== exports.HubConnectionState.Reconnecting) {
619
+ this._logger.log(ILogger.LogLevel.Debug, "Connection left the reconnecting state during reconnect delay. Done reconnecting.");
620
+ return;
621
+ }
622
+ try {
623
+ await this._startInternal();
624
+ this._connectionState = exports.HubConnectionState.Connected;
625
+ this._logger.log(ILogger.LogLevel.Information, "HubConnection reconnected successfully.");
626
+ if (this._reconnectedCallbacks.length !== 0) {
627
+ try {
628
+ this._reconnectedCallbacks.forEach((c) => c.apply(this, [this.connection.connectionId]));
629
+ } catch (e) {
630
+ this._logger.log(ILogger.LogLevel.Error, `An onreconnected callback called with connectionId '${this.connection.connectionId}; threw error '${e}'.`);
631
+ }
632
+ }
633
+ return;
634
+ } catch (e) {
635
+ this._logger.log(ILogger.LogLevel.Information, `Reconnect attempt failed because of error '${e}'.`);
636
+ if (this._connectionState !== exports.HubConnectionState.Reconnecting) {
637
+ this._logger.log(ILogger.LogLevel.Debug, `Connection moved to the '${this._connectionState}' from the reconnecting state during reconnect attempt. Done reconnecting.`);
638
+ if (this._connectionState === exports.HubConnectionState.Disconnecting) {
639
+ this._completeClose();
640
+ }
641
+ return;
642
+ }
643
+ previousReconnectAttempts++;
644
+ retryError = e instanceof Error ? e : new Error(e.toString());
645
+ nextRetryDelay = this._getNextRetryDelay(previousReconnectAttempts, Date.now() - reconnectStartTime, retryError);
646
+ }
647
+ }
648
+ this._logger.log(ILogger.LogLevel.Information, `Reconnect retries have been exhausted after ${Date.now() - reconnectStartTime} ms and ${previousReconnectAttempts} failed attempts. Connection disconnecting.`);
649
+ this._completeClose();
650
+ }
651
+ _getNextRetryDelay(previousRetryCount, elapsedMilliseconds, retryReason) {
652
+ try {
653
+ return this._reconnectPolicy.nextRetryDelayInMilliseconds({
654
+ elapsedMilliseconds,
655
+ previousRetryCount,
656
+ retryReason
657
+ });
658
+ } catch (e) {
659
+ this._logger.log(ILogger.LogLevel.Error, `IRetryPolicy.nextRetryDelayInMilliseconds(${previousRetryCount}, ${elapsedMilliseconds}) threw error '${e}'.`);
660
+ return null;
661
+ }
662
+ }
663
+ _cancelCallbacksWithError(error) {
664
+ const callbacks = this._callbacks;
665
+ this._callbacks = {};
666
+ Object.keys(callbacks).forEach((key) => {
667
+ const callback = callbacks[key];
668
+ try {
669
+ callback(null, error);
670
+ } catch (e) {
671
+ this._logger.log(ILogger.LogLevel.Error, `Stream 'error' callback called with '${error}' threw error: ${Utils.getErrorString(e)}`);
672
+ }
673
+ });
674
+ }
675
+ _cleanupPingTimer() {
676
+ if (this._pingServerHandle) {
677
+ clearTimeout(this._pingServerHandle);
678
+ this._pingServerHandle = void 0;
679
+ }
680
+ }
681
+ _cleanupTimeout() {
682
+ if (this._timeoutHandle) {
683
+ clearTimeout(this._timeoutHandle);
684
+ }
685
+ }
686
+ _createInvocation(methodName, args, nonblocking, streamIds) {
687
+ if (nonblocking) {
688
+ if (streamIds.length !== 0) {
689
+ return {
690
+ target: methodName,
691
+ arguments: args,
692
+ streamIds,
693
+ type: IHubProtocol.MessageType.Invocation
694
+ };
695
+ } else {
696
+ return {
697
+ target: methodName,
698
+ arguments: args,
699
+ type: IHubProtocol.MessageType.Invocation
700
+ };
701
+ }
702
+ } else {
703
+ const invocationId = this._invocationId;
704
+ this._invocationId++;
705
+ if (streamIds.length !== 0) {
706
+ return {
707
+ target: methodName,
708
+ arguments: args,
709
+ invocationId: invocationId.toString(),
710
+ streamIds,
711
+ type: IHubProtocol.MessageType.Invocation
712
+ };
713
+ } else {
714
+ return {
715
+ target: methodName,
716
+ arguments: args,
717
+ invocationId: invocationId.toString(),
718
+ type: IHubProtocol.MessageType.Invocation
719
+ };
720
+ }
721
+ }
722
+ }
723
+ _launchStreams(streams, promiseQueue) {
724
+ if (streams.length === 0) {
725
+ return;
726
+ }
727
+ if (!promiseQueue) {
728
+ promiseQueue = Promise.resolve();
729
+ }
730
+ for (const streamId in streams) {
731
+ streams[streamId].subscribe({
732
+ complete: () => {
733
+ promiseQueue = promiseQueue.then(() => this._sendWithProtocol(this._createCompletionMessage(streamId)));
734
+ },
735
+ error: (err) => {
736
+ let message;
737
+ if (err instanceof Error) {
738
+ message = err.message;
739
+ } else if (err && err.toString) {
740
+ message = err.toString();
741
+ } else {
742
+ message = "Unknown error";
743
+ }
744
+ promiseQueue = promiseQueue.then(() => this._sendWithProtocol(this._createCompletionMessage(streamId, message)));
745
+ },
746
+ next: (item) => {
747
+ promiseQueue = promiseQueue.then(() => this._sendWithProtocol(this._createStreamItemMessage(streamId, item)));
748
+ }
749
+ });
750
+ }
751
+ }
752
+ _replaceStreamingParams(args) {
753
+ const streams = [];
754
+ const streamIds = [];
755
+ for (let i = 0; i < args.length; i++) {
756
+ const argument = args[i];
757
+ if (this._isObservable(argument)) {
758
+ const streamId = this._invocationId;
759
+ this._invocationId++;
760
+ streams[streamId] = argument;
761
+ streamIds.push(streamId.toString());
762
+ args.splice(i, 1);
763
+ }
764
+ }
765
+ return [streams, streamIds];
766
+ }
767
+ _isObservable(arg) {
768
+ return arg && arg.subscribe && typeof arg.subscribe === "function";
769
+ }
770
+ _createStreamInvocation(methodName, args, streamIds) {
771
+ const invocationId = this._invocationId;
772
+ this._invocationId++;
773
+ if (streamIds.length !== 0) {
774
+ return {
775
+ target: methodName,
776
+ arguments: args,
777
+ invocationId: invocationId.toString(),
778
+ streamIds,
779
+ type: IHubProtocol.MessageType.StreamInvocation
780
+ };
781
+ } else {
782
+ return {
783
+ target: methodName,
784
+ arguments: args,
785
+ invocationId: invocationId.toString(),
786
+ type: IHubProtocol.MessageType.StreamInvocation
787
+ };
788
+ }
789
+ }
790
+ _createCancelInvocation(id) {
791
+ return {
792
+ invocationId: id,
793
+ type: IHubProtocol.MessageType.CancelInvocation
794
+ };
795
+ }
796
+ _createStreamItemMessage(id, item) {
797
+ return {
798
+ invocationId: id,
799
+ item,
800
+ type: IHubProtocol.MessageType.StreamItem
801
+ };
802
+ }
803
+ _createCompletionMessage(id, error, result) {
804
+ if (error) {
805
+ return {
806
+ error,
807
+ invocationId: id,
808
+ type: IHubProtocol.MessageType.Completion
809
+ };
810
+ }
811
+ return {
812
+ invocationId: id,
813
+ result,
814
+ type: IHubProtocol.MessageType.Completion
815
+ };
816
+ }
817
+ _createCloseMessage() {
818
+ return { type: IHubProtocol.MessageType.Close };
819
+ }
820
+ async _trySendPingMessage() {
821
+ try {
822
+ await this._sendMessage(this._cachedPingMessage);
823
+ } catch {
824
+ this._cleanupPingTimer();
825
+ }
826
+ }
953
827
  }
954
-
955
828
  exports.HubConnection = HubConnection;