nyxlink 0.1.0-dev.3 → 5.3.0-rc.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (322) hide show
  1. package/NOTICE.md +39 -0
  2. package/README.md +159 -215
  3. package/dist/index.d.ts +72 -3
  4. package/dist/index.js +66 -3
  5. package/dist/index.js.map +1 -1
  6. package/dist/src/Util.d.ts +13 -5
  7. package/dist/src/Util.js +153 -76
  8. package/dist/src/Util.js.map +1 -1
  9. package/dist/src/autoplay/AutoPlayManager.js +19 -9
  10. package/dist/src/autoplay/AutoPlayManager.js.map +1 -1
  11. package/dist/src/autoplay/RecommendationDiscovery.d.ts +27 -0
  12. package/dist/src/autoplay/RecommendationDiscovery.js +67 -0
  13. package/dist/src/autoplay/RecommendationDiscovery.js.map +1 -0
  14. package/dist/src/autoplay/RecommendationPreference.d.ts +15 -0
  15. package/dist/src/autoplay/RecommendationPreference.js +31 -0
  16. package/dist/src/autoplay/RecommendationPreference.js.map +1 -0
  17. package/dist/src/autoplay/RecommendationResolver.js +129 -91
  18. package/dist/src/autoplay/RecommendationResolver.js.map +1 -1
  19. package/dist/src/backends/BackendAdapter.d.ts +16 -3
  20. package/dist/src/backends/BackendAdapter.js +27 -9
  21. package/dist/src/backends/BackendAdapter.js.map +1 -1
  22. package/dist/src/backends/BackendDetector.js +36 -8
  23. package/dist/src/backends/BackendDetector.js.map +1 -1
  24. package/dist/src/backends/BackendInventory.d.ts +16 -0
  25. package/dist/src/backends/BackendInventory.js +3 -0
  26. package/dist/src/backends/BackendInventory.js.map +1 -0
  27. package/dist/src/backends/CapabilityRegistry.d.ts +17 -0
  28. package/dist/src/backends/CapabilityRegistry.js +39 -0
  29. package/dist/src/backends/CapabilityRegistry.js.map +1 -0
  30. package/dist/src/backends/ClientPCMSeek.d.ts +5 -0
  31. package/dist/src/backends/ClientPCMSeek.js +46 -0
  32. package/dist/src/backends/ClientPCMSeek.js.map +1 -0
  33. package/dist/src/backends/ExtensionRoutes.d.ts +202 -0
  34. package/dist/src/backends/ExtensionRoutes.js +57 -0
  35. package/dist/src/backends/ExtensionRoutes.js.map +1 -0
  36. package/dist/src/backends/HoloTrackMetadata.d.ts +24 -0
  37. package/dist/src/backends/HoloTrackMetadata.js +50 -0
  38. package/dist/src/backends/HoloTrackMetadata.js.map +1 -0
  39. package/dist/src/backends/LavaDSPXContracts.d.ts +27 -0
  40. package/dist/src/backends/LavaDSPXContracts.js +54 -0
  41. package/dist/src/backends/LavaDSPXContracts.js.map +1 -0
  42. package/dist/src/backends/LavaLyricsContracts.d.ts +21 -0
  43. package/dist/src/backends/LavaLyricsContracts.js +45 -0
  44. package/dist/src/backends/LavaLyricsContracts.js.map +1 -0
  45. package/dist/src/backends/LavaSearchContracts.d.ts +33 -0
  46. package/dist/src/backends/LavaSearchContracts.js +67 -0
  47. package/dist/src/backends/LavaSearchContracts.js.map +1 -0
  48. package/dist/src/backends/LavaSrcMetadata.d.ts +18 -0
  49. package/dist/src/backends/LavaSrcMetadata.js +38 -0
  50. package/dist/src/backends/LavaSrcMetadata.js.map +1 -0
  51. package/dist/src/backends/LavalinkAdapter.d.ts +2 -1
  52. package/dist/src/backends/LavalinkAdapter.js +3 -0
  53. package/dist/src/backends/LavalinkAdapter.js.map +1 -1
  54. package/dist/src/backends/LavalinkSponsorBlockContracts.d.ts +8 -0
  55. package/dist/src/backends/LavalinkSponsorBlockContracts.js +41 -0
  56. package/dist/src/backends/LavalinkSponsorBlockContracts.js.map +1 -0
  57. package/dist/src/backends/NodeLinkAdapter.d.ts +2 -1
  58. package/dist/src/backends/NodeLinkAdapter.js +3 -0
  59. package/dist/src/backends/NodeLinkAdapter.js.map +1 -1
  60. package/dist/src/backends/NodeLinkContracts.d.ts +99 -0
  61. package/dist/src/backends/NodeLinkContracts.js +146 -0
  62. package/dist/src/backends/NodeLinkContracts.js.map +1 -0
  63. package/dist/src/backends/NodeLinkMixContracts.d.ts +34 -0
  64. package/dist/src/backends/NodeLinkMixContracts.js +51 -0
  65. package/dist/src/backends/NodeLinkMixContracts.js.map +1 -0
  66. package/dist/src/backends/NodeLinkOrchestration.d.ts +69 -0
  67. package/dist/src/backends/NodeLinkOrchestration.js +123 -0
  68. package/dist/src/backends/NodeLinkOrchestration.js.map +1 -0
  69. package/dist/src/backends/NodeLinkSearchContracts.d.ts +9 -0
  70. package/dist/src/backends/NodeLinkSearchContracts.js +25 -0
  71. package/dist/src/backends/NodeLinkSearchContracts.js.map +1 -0
  72. package/dist/src/backends/NodeLinkStreamResponse.d.ts +1 -0
  73. package/dist/src/backends/NodeLinkStreamResponse.js +32 -0
  74. package/dist/src/backends/NodeLinkStreamResponse.js.map +1 -0
  75. package/dist/src/backends/ProtocolContracts.d.ts +56 -0
  76. package/dist/src/backends/ProtocolContracts.js +31 -0
  77. package/dist/src/backends/ProtocolContracts.js.map +1 -0
  78. package/dist/src/backends/ProtocolValidation.d.ts +13 -0
  79. package/dist/src/backends/ProtocolValidation.js +119 -0
  80. package/dist/src/backends/ProtocolValidation.js.map +1 -0
  81. package/dist/src/backends/SessionPath.d.ts +3 -0
  82. package/dist/src/backends/SessionPath.js +19 -0
  83. package/dist/src/backends/SessionPath.js.map +1 -0
  84. package/dist/src/backends/SponsorBlockEvents.d.ts +31 -0
  85. package/dist/src/backends/SponsorBlockEvents.js +56 -0
  86. package/dist/src/backends/SponsorBlockEvents.js.map +1 -0
  87. package/dist/src/cluster/GuildOwnership.d.ts +30 -0
  88. package/dist/src/cluster/GuildOwnership.js +190 -0
  89. package/dist/src/cluster/GuildOwnership.js.map +1 -0
  90. package/dist/src/cluster/RedisGuildIpcRouter.d.ts +34 -0
  91. package/dist/src/cluster/RedisGuildIpcRouter.js +150 -0
  92. package/dist/src/cluster/RedisGuildIpcRouter.js.map +1 -0
  93. package/dist/src/connectors/Connector.d.ts +3 -1
  94. package/dist/src/connectors/Connector.js +7 -1
  95. package/dist/src/connectors/Connector.js.map +1 -1
  96. package/dist/src/core/Manager.d.ts +26 -8
  97. package/dist/src/core/Manager.js +91 -23
  98. package/dist/src/core/Manager.js.map +1 -1
  99. package/dist/src/database/Local.d.ts +6 -2
  100. package/dist/src/database/Local.js +49 -14
  101. package/dist/src/database/Local.js.map +1 -1
  102. package/dist/src/database/Memory.d.ts +4 -0
  103. package/dist/src/database/Memory.js +17 -3
  104. package/dist/src/database/Memory.js.map +1 -1
  105. package/dist/src/database/PlayerSnapshot.d.ts +35 -0
  106. package/dist/src/database/PlayerSnapshot.js +176 -0
  107. package/dist/src/database/PlayerSnapshot.js.map +1 -0
  108. package/dist/src/database/RedisGuildLeaseCoordinator.d.ts +30 -0
  109. package/dist/src/database/RedisGuildLeaseCoordinator.js +134 -0
  110. package/dist/src/database/RedisGuildLeaseCoordinator.js.map +1 -0
  111. package/dist/src/database/RedisPlayerFence.d.ts +15 -0
  112. package/dist/src/database/RedisPlayerFence.js +44 -0
  113. package/dist/src/database/RedisPlayerFence.js.map +1 -0
  114. package/dist/src/database/RedisStorage.d.ts +32 -0
  115. package/dist/src/database/RedisStorage.js +209 -0
  116. package/dist/src/database/RedisStorage.js.map +1 -0
  117. package/dist/src/database/StorageAdapter.d.ts +1 -0
  118. package/dist/src/entities/Filters.d.ts +10 -2
  119. package/dist/src/entities/Filters.js +118 -59
  120. package/dist/src/entities/Filters.js.map +1 -1
  121. package/dist/src/entities/Node.d.ts +60 -6
  122. package/dist/src/entities/Node.js +511 -291
  123. package/dist/src/entities/Node.js.map +1 -1
  124. package/dist/src/entities/Player.d.ts +29 -7
  125. package/dist/src/entities/Player.js +527 -222
  126. package/dist/src/entities/Player.js.map +1 -1
  127. package/dist/src/entities/Queue.d.ts +1 -0
  128. package/dist/src/entities/Queue.js +76 -25
  129. package/dist/src/entities/Queue.js.map +1 -1
  130. package/dist/src/entities/Rest.d.ts +48 -8
  131. package/dist/src/entities/Rest.js +482 -112
  132. package/dist/src/entities/Rest.js.map +1 -1
  133. package/dist/src/entities/Track.d.ts +19 -12
  134. package/dist/src/entities/Track.js +44 -22
  135. package/dist/src/entities/Track.js.map +1 -1
  136. package/dist/src/entities/Voice.js +13 -6
  137. package/dist/src/entities/Voice.js.map +1 -1
  138. package/dist/src/entities/VoicePacketHandler.js +2 -2
  139. package/dist/src/entities/VoicePacketHandler.js.map +1 -1
  140. package/dist/src/entities/VoiceReceiver.d.ts +5 -0
  141. package/dist/src/entities/VoiceReceiver.js +117 -13
  142. package/dist/src/entities/VoiceReceiver.js.map +1 -1
  143. package/dist/src/entities/YouTubeLiveChat.d.ts +1 -0
  144. package/dist/src/entities/YouTubeLiveChat.js +53 -8
  145. package/dist/src/entities/YouTubeLiveChat.js.map +1 -1
  146. package/dist/src/errors/FeatureUnavailableError.d.ts +2 -2
  147. package/dist/src/errors/FeatureUnavailableError.js +1 -1
  148. package/dist/src/errors/FeatureUnavailableError.js.map +1 -1
  149. package/dist/src/errors/HttpError.d.ts +2 -2
  150. package/dist/src/errors/HttpPolicyError.d.ts +6 -0
  151. package/dist/src/errors/HttpPolicyError.js +14 -0
  152. package/dist/src/errors/HttpPolicyError.js.map +1 -0
  153. package/dist/src/errors/PlayerOperationCancelledError.d.ts +5 -0
  154. package/dist/src/errors/PlayerOperationCancelledError.js +14 -0
  155. package/dist/src/errors/PlayerOperationCancelledError.js.map +1 -0
  156. package/dist/src/extensions/ExtensionHost.d.ts +33 -0
  157. package/dist/src/extensions/ExtensionHost.js +156 -0
  158. package/dist/src/extensions/ExtensionHost.js.map +1 -0
  159. package/dist/src/http/RequestPolicy.d.ts +6 -0
  160. package/dist/src/http/RequestPolicy.js +52 -0
  161. package/dist/src/http/RequestPolicy.js.map +1 -0
  162. package/dist/src/logging/AuroraBootstrap.d.ts +22 -0
  163. package/dist/src/logging/AuroraBootstrap.js +89 -0
  164. package/dist/src/logging/AuroraBootstrap.js.map +1 -0
  165. package/dist/src/logging/AuroraDiagnostics.d.ts +56 -0
  166. package/dist/src/logging/AuroraDiagnostics.js +152 -0
  167. package/dist/src/logging/AuroraDiagnostics.js.map +1 -0
  168. package/dist/src/logging/AuroraEvents.d.ts +423 -0
  169. package/dist/src/logging/AuroraEvents.js +305 -0
  170. package/dist/src/logging/AuroraEvents.js.map +1 -0
  171. package/dist/src/logging/AuroraInspector.d.ts +55 -0
  172. package/dist/src/logging/AuroraInspector.js +117 -0
  173. package/dist/src/logging/AuroraInspector.js.map +1 -0
  174. package/dist/src/logging/AuroraPresentation.d.ts +35 -0
  175. package/dist/src/logging/AuroraPresentation.js +108 -0
  176. package/dist/src/logging/AuroraPresentation.js.map +1 -0
  177. package/dist/src/logging/ErrorDiagnostics.d.ts +11 -0
  178. package/dist/src/logging/ErrorDiagnostics.js +32 -0
  179. package/dist/src/logging/ErrorDiagnostics.js.map +1 -0
  180. package/dist/src/logging/LogFormatter.d.ts +1 -0
  181. package/dist/src/logging/LogFormatter.js +70 -20
  182. package/dist/src/logging/LogFormatter.js.map +1 -1
  183. package/dist/src/logging/LogLevels.d.ts +0 -2
  184. package/dist/src/logging/LogLevels.js +1 -9
  185. package/dist/src/logging/LogLevels.js.map +1 -1
  186. package/dist/src/logging/ManagerLogRoute.d.ts +4 -0
  187. package/dist/src/logging/ManagerLogRoute.js +18 -0
  188. package/dist/src/logging/ManagerLogRoute.js.map +1 -0
  189. package/dist/src/logging/ObservedFields.d.ts +1 -0
  190. package/dist/src/logging/ObservedFields.js +16 -0
  191. package/dist/src/logging/ObservedFields.js.map +1 -0
  192. package/dist/src/logging/PinoEngine.d.ts +13 -0
  193. package/dist/src/logging/PinoEngine.js +38 -0
  194. package/dist/src/logging/PinoEngine.js.map +1 -0
  195. package/dist/src/logging/SafeDiagnostics.d.ts +3 -0
  196. package/dist/src/logging/SafeDiagnostics.js +71 -0
  197. package/dist/src/logging/SafeDiagnostics.js.map +1 -0
  198. package/dist/src/logging/TerminalCoordinator.d.ts +64 -0
  199. package/dist/src/logging/TerminalCoordinator.js +237 -0
  200. package/dist/src/logging/TerminalCoordinator.js.map +1 -0
  201. package/dist/src/logging/index.d.ts +4 -6
  202. package/dist/src/logging/index.js +5 -8
  203. package/dist/src/logging/index.js.map +1 -1
  204. package/dist/src/managers/DatabaseManager.d.ts +10 -0
  205. package/dist/src/managers/DatabaseManager.js +192 -1
  206. package/dist/src/managers/DatabaseManager.js.map +1 -1
  207. package/dist/src/managers/NodeManager.d.ts +13 -8
  208. package/dist/src/managers/NodeManager.js +116 -22
  209. package/dist/src/managers/NodeManager.js.map +1 -1
  210. package/dist/src/managers/PlayerManager.d.ts +3 -0
  211. package/dist/src/managers/PlayerManager.js +30 -2
  212. package/dist/src/managers/PlayerManager.js.map +1 -1
  213. package/dist/src/nodes/NodeCircuitBreaker.js +10 -2
  214. package/dist/src/nodes/NodeCircuitBreaker.js.map +1 -1
  215. package/dist/src/nodes/NodeFailover.js +38 -10
  216. package/dist/src/nodes/NodeFailover.js.map +1 -1
  217. package/dist/src/nodes/NodeHealthMonitor.js +1 -1
  218. package/dist/src/nodes/NodeHealthMonitor.js.map +1 -1
  219. package/dist/src/nodes/NodeScoring.d.ts +4 -0
  220. package/dist/src/nodes/NodeScoring.js +52 -0
  221. package/dist/src/nodes/NodeScoring.js.map +1 -0
  222. package/dist/src/nodes/NodeSelector.d.ts +6 -0
  223. package/dist/src/nodes/NodeSelector.js +43 -3
  224. package/dist/src/nodes/NodeSelector.js.map +1 -1
  225. package/dist/src/nodes/SessionRecovery.js +38 -12
  226. package/dist/src/nodes/SessionRecovery.js.map +1 -1
  227. package/dist/src/nodes/SourceHealthMonitor.d.ts +16 -0
  228. package/dist/src/nodes/SourceHealthMonitor.js +47 -0
  229. package/dist/src/nodes/SourceHealthMonitor.js.map +1 -0
  230. package/dist/src/observability/OpenTelemetry.d.ts +64 -0
  231. package/dist/src/observability/OpenTelemetry.js +183 -0
  232. package/dist/src/observability/OpenTelemetry.js.map +1 -0
  233. package/dist/src/observability/PerformanceMonitor.d.ts +69 -0
  234. package/dist/src/observability/PerformanceMonitor.js +164 -0
  235. package/dist/src/observability/PerformanceMonitor.js.map +1 -0
  236. package/dist/src/observability/PrivateMetricsServer.d.ts +47 -0
  237. package/dist/src/observability/PrivateMetricsServer.js +221 -0
  238. package/dist/src/observability/PrivateMetricsServer.js.map +1 -0
  239. package/dist/src/observability/TerminalDashboard.d.ts +60 -0
  240. package/dist/src/observability/TerminalDashboard.js +111 -0
  241. package/dist/src/observability/TerminalDashboard.js.map +1 -0
  242. package/dist/src/players/AdvancedAudioRecovery.d.ts +18 -0
  243. package/dist/src/players/AdvancedAudioRecovery.js +38 -0
  244. package/dist/src/players/AdvancedAudioRecovery.js.map +1 -0
  245. package/dist/src/players/MixRecovery.d.ts +24 -0
  246. package/dist/src/players/MixRecovery.js +89 -0
  247. package/dist/src/players/MixRecovery.js.map +1 -0
  248. package/dist/src/players/PlaybackAttempt.d.ts +2 -1
  249. package/dist/src/players/PlaybackAttempt.js +1 -0
  250. package/dist/src/players/PlaybackAttempt.js.map +1 -1
  251. package/dist/src/players/PlaybackGuard.d.ts +4 -0
  252. package/dist/src/players/PlaybackGuard.js +15 -2
  253. package/dist/src/players/PlaybackGuard.js.map +1 -1
  254. package/dist/src/players/PlayerCommandQueue.d.ts +2 -0
  255. package/dist/src/players/PlayerCommandQueue.js +4 -1
  256. package/dist/src/players/PlayerCommandQueue.js.map +1 -1
  257. package/dist/src/players/PlayerMigration.d.ts +11 -0
  258. package/dist/src/players/PlayerMigration.js +111 -22
  259. package/dist/src/players/PlayerMigration.js.map +1 -1
  260. package/dist/src/players/QueuePreload.d.ts +10 -0
  261. package/dist/src/players/QueuePreload.js +46 -0
  262. package/dist/src/players/QueuePreload.js.map +1 -0
  263. package/dist/src/players/VoiceRecovery.d.ts +7 -0
  264. package/dist/src/players/VoiceRecovery.js +56 -0
  265. package/dist/src/players/VoiceRecovery.js.map +1 -0
  266. package/dist/src/search/SearchService.d.ts +6 -2
  267. package/dist/src/search/SearchService.js +91 -44
  268. package/dist/src/search/SearchService.js.map +1 -1
  269. package/dist/src/search/SharedSearchRequests.d.ts +6 -0
  270. package/dist/src/search/SharedSearchRequests.js +61 -0
  271. package/dist/src/search/SharedSearchRequests.js.map +1 -0
  272. package/dist/src/search/SourceRouting.d.ts +4 -0
  273. package/dist/src/search/SourceRouting.js +36 -0
  274. package/dist/src/search/SourceRouting.js.map +1 -0
  275. package/dist/src/services/WebSocket.d.ts +3 -0
  276. package/dist/src/services/WebSocket.js +75 -48
  277. package/dist/src/services/WebSocket.js.map +1 -1
  278. package/dist/src/sources/deezer.d.ts +2 -0
  279. package/dist/src/sources/deezer.js +35 -22
  280. package/dist/src/sources/deezer.js.map +1 -1
  281. package/dist/src/sources/spotify.d.ts +2 -0
  282. package/dist/src/sources/spotify.js +27 -18
  283. package/dist/src/sources/spotify.js.map +1 -1
  284. package/dist/src/structures/SearchResult.d.ts +6 -3
  285. package/dist/src/structures/SearchResult.js +13 -4
  286. package/dist/src/structures/SearchResult.js.map +1 -1
  287. package/dist/src/tracks/AbortableLookup.d.ts +1 -0
  288. package/dist/src/tracks/AbortableLookup.js +14 -0
  289. package/dist/src/tracks/AbortableLookup.js.map +1 -0
  290. package/dist/src/tracks/MetadataTrackResolver.d.ts +11 -0
  291. package/dist/src/tracks/MetadataTrackResolver.js +90 -0
  292. package/dist/src/tracks/MetadataTrackResolver.js.map +1 -0
  293. package/dist/src/tracks/TrackCodec.js +1 -1
  294. package/dist/src/tracks/TrackCodec.js.map +1 -1
  295. package/dist/src/tracks/TrackResolver.d.ts +1 -1
  296. package/dist/src/tracks/TrackResolver.js +75 -27
  297. package/dist/src/tracks/TrackResolver.js.map +1 -1
  298. package/dist/src/typings/Interfaces.d.ts +23 -6
  299. package/examples/aurora-bootstrap.d.mts +2 -0
  300. package/examples/aurora-bootstrap.mjs +77 -0
  301. package/examples/aurora-demo.mjs +63 -0
  302. package/examples/aurora-diagnostics.d.mts +5 -0
  303. package/examples/aurora-diagnostics.mjs +73 -0
  304. package/examples/aurora-file.d.mts +2 -0
  305. package/examples/aurora-file.mjs +55 -0
  306. package/examples/aurora-inspector.d.mts +7 -0
  307. package/examples/aurora-inspector.mjs +173 -0
  308. package/examples/aurora-otel.d.mts +4 -0
  309. package/examples/aurora-otel.mjs +4 -0
  310. package/examples/aurora-pipeline.d.mts +22 -0
  311. package/examples/aurora-pipeline.mjs +91 -0
  312. package/examples/aurora-sdk.cjs +73 -0
  313. package/examples/aurora-sdk.d.cts +2 -0
  314. package/examples/aurora-terminal-tools.mjs +44 -0
  315. package/examples/aurora-visual.mjs +55 -0
  316. package/package.json +109 -7
  317. package/dist/src/logging/ConsoleReporter.d.ts +0 -8
  318. package/dist/src/logging/ConsoleReporter.js +0 -25
  319. package/dist/src/logging/ConsoleReporter.js.map +0 -1
  320. package/dist/src/logging/Logger.d.ts +0 -37
  321. package/dist/src/logging/Logger.js +0 -122
  322. package/dist/src/logging/Logger.js.map +0 -1
@@ -1,6 +1,10 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.Player = void 0;
4
+ const AdvancedAudioRecovery_1 = require("../players/AdvancedAudioRecovery");
5
+ const OpenTelemetry_1 = require("../observability/OpenTelemetry");
6
+ const NodeLinkContracts_1 = require("../backends/NodeLinkContracts");
7
+ const ProtocolContracts_1 = require("../backends/ProtocolContracts");
4
8
  const PlayerMigration_1 = require("../players/PlayerMigration");
5
9
  const PlayerCommandQueue_1 = require("../players/PlayerCommandQueue");
6
10
  const PlaybackGuard_1 = require("../players/PlaybackGuard");
@@ -12,6 +16,10 @@ const Track_1 = require("./Track");
12
16
  const TrackCodec_1 = require("../tracks/TrackCodec");
13
17
  const TrackResolver_1 = require("../tracks/TrackResolver");
14
18
  const VoiceReceiver_1 = require("./VoiceReceiver");
19
+ const PlayerSnapshot_1 = require("../database/PlayerSnapshot");
20
+ const NodeLinkMixContracts_1 = require("../backends/NodeLinkMixContracts");
21
+ const PlayerOperationCancelledError_1 = require("../errors/PlayerOperationCancelledError");
22
+ const QueuePreload_1 = require("../players/QueuePreload");
15
23
  class Player {
16
24
  manager;
17
25
  node;
@@ -40,11 +48,19 @@ class Player {
40
48
  historySize = 10;
41
49
  lastActivityTime = Date.now();
42
50
  commands = new PlayerCommandQueue_1.PlayerCommandQueue();
51
+ get pendingCommands() { return this.commands.pending; }
43
52
  destructionPromise;
53
+ pendingPlayTicket;
54
+ lastSuccessfulExplicitPlayTicket;
44
55
  volumeRevision = 0;
45
56
  optimisticVolumeRevision = 0;
46
57
  fading;
58
+ crossfade;
47
59
  nextTrack;
60
+ preloadOptions;
61
+ queuePreload;
62
+ preloadScheduler = new QueuePreload_1.QueuePreloadScheduler();
63
+ get preloadJob() { return this.preloadScheduler.pending; }
48
64
  audioTrackId;
49
65
  loudnessNormalizer;
50
66
  endTime;
@@ -83,10 +99,7 @@ class Player {
83
99
  this.voice = new Voice_1.Voice(this);
84
100
  if (config.current) {
85
101
  this.current = TrackCodec_1.TrackCodec.restore(config.current);
86
- if (config.current.position) {
87
- this.current.position = config.current.position;
88
- this.lastPosition = this.current.position;
89
- }
102
+ this.lastPosition = this.current.getInfo().position;
90
103
  }
91
104
  if (config.queue && Array.isArray(config.queue)) {
92
105
  for (const track of config.queue) {
@@ -98,7 +111,7 @@ class Player {
98
111
  this.previous.push(TrackCodec_1.TrackCodec.restore(track));
99
112
  }
100
113
  }
101
- this.manager.emit("debug", `Moonlink.js > Player#constructor >> Player created for guild ${this.guildId} on node ${this.node.identifier} | autoPlay: ${this.autoPlay}, autoLeave: ${this.autoLeave}, loop: ${this.loop}`);
114
+ this.manager.emit("debug", `NyxLink > Player#constructor >> Player created for guild ${this.guildId} on node ${this.node.identifier} | autoPlay: ${this.autoPlay}, autoLeave: ${this.autoLeave}, loop: ${this.loop}`);
102
115
  this.startHealthCheck();
103
116
  }
104
117
  startHealthCheck() {
@@ -125,11 +138,11 @@ class Player {
125
138
  const currentPosition = this.current.position ?? 0;
126
139
  const positionDelta = Math.abs(currentPosition - this.lastPosition);
127
140
  const timeDelta = now - this.lastPositionTime;
128
- if (positionDelta < 1000 && timeDelta > 30000 && !this.current.isStream) {
141
+ if (positionDelta < 1000 && timeDelta > 30000 && !this.current.getInfo().isStream) {
129
142
  this.stuckDetectionCount++;
130
- this.manager.emit("debug", `Moonlink.js > Player#healthCheck >> Player ${this.guildId} appears stuck. Position: ${currentPosition}, Delta: ${positionDelta}, Stuck count: ${this.stuckDetectionCount}/${maxStuckCount}`);
143
+ this.manager.emit("debug", `NyxLink > Player#healthCheck >> Player ${this.guildId} appears stuck. Position: ${currentPosition}, Delta: ${positionDelta}, Stuck count: ${this.stuckDetectionCount}/${maxStuckCount}`);
131
144
  if (this.stuckDetectionCount >= maxStuckCount) {
132
- this.manager.emit("debug", `Moonlink.js > Player#healthCheck >> Player ${this.guildId} stuck for too long, attempting recovery.`);
145
+ this.manager.emit("debug", `NyxLink > Player#healthCheck >> Player ${this.guildId} stuck for too long, attempting recovery.`);
133
146
  await this.recoverFromStuck();
134
147
  this.stuckDetectionCount = 0;
135
148
  return;
@@ -137,16 +150,16 @@ class Player {
137
150
  }
138
151
  else {
139
152
  if (this.stuckDetectionCount > 0) {
140
- this.manager.emit("debug", `Moonlink.js > Player#healthCheck >> Player ${this.guildId} position advanced (Delta: ${positionDelta}). Resetting stuck count.`);
153
+ this.manager.emit("debug", `NyxLink > Player#healthCheck >> Player ${this.guildId} position advanced (Delta: ${positionDelta}). Resetting stuck count.`);
141
154
  }
142
155
  this.stuckDetectionCount = 0;
143
156
  }
144
157
  const activityDelta = now - this.lastActivityTime;
145
158
  if (activityDelta > silenceTimeout) {
146
159
  this.silentDetectionCount++;
147
- this.manager.emit("debug", `Moonlink.js > Player#healthCheck >> Player ${this.guildId} silent for ${Math.round(activityDelta / 1000)}s. Silent count: ${this.silentDetectionCount}/${maxSilentCount}`);
160
+ this.manager.emit("debug", `NyxLink > Player#healthCheck >> Player ${this.guildId} silent for ${Math.round(activityDelta / 1000)}s. Silent count: ${this.silentDetectionCount}/${maxSilentCount}`);
148
161
  if (this.silentDetectionCount >= maxSilentCount) {
149
- this.manager.emit("debug", `Moonlink.js > Player#healthCheck >> Player ${this.guildId} silent for too long, attempting soft restart.`);
162
+ this.manager.emit("debug", `NyxLink > Player#healthCheck >> Player ${this.guildId} silent for too long, attempting soft restart.`);
150
163
  await this.softRestart("Silent player detected");
151
164
  this.silentDetectionCount = 0;
152
165
  return;
@@ -169,9 +182,9 @@ class Player {
169
182
  let ticket = (0, PlaybackGuard_1.playbackGuard)(this).ticket;
170
183
  this.manager.emit("playerRecoveryStarted", this);
171
184
  try {
172
- if (this.current && this.current.isSeekable) {
185
+ if (this.current && this.current.getInfo().isSeekable) {
173
186
  const seekPos = Math.max(0, (this.current.position ?? 0) + 2000);
174
- this.manager.emit("debug", `Moonlink.js > Player#recoverFromStuck >> Seeking forward 2s for player ${this.guildId}.`);
187
+ this.manager.emit("debug", `NyxLink > Player#recoverFromStuck >> Seeking forward 2s for player ${this.guildId}.`);
175
188
  await this.seek(seekPos);
176
189
  }
177
190
  else {
@@ -186,19 +199,19 @@ class Player {
186
199
  this.manager.emit("playerRecoverySuccess", this);
187
200
  }
188
201
  catch (error) {
189
- this.manager.emit("debug", `Moonlink.js > Player#recoverFromStuck >> Recovery failed: ${error.message}`);
202
+ this.manager.emit("debug", `NyxLink > Player#recoverFromStuck >> Recovery failed: ${error.message}`);
190
203
  this.manager.emit("playerRecoveryFailed", this);
191
204
  }
192
205
  }
193
206
  async softRestart(reason) {
194
207
  if (this.destroyed)
195
208
  return false;
196
- this.manager.emit("debug", `Moonlink.js > Player#softRestart >> Soft restart triggered for player ${this.guildId}. Reason: ${reason}`);
209
+ this.manager.emit("debug", `NyxLink > Player#softRestart >> Soft restart triggered for player ${this.guildId}. Reason: ${reason}`);
197
210
  const currentTrack = this.current;
198
211
  const currentPosition = currentTrack?.position ?? 0;
199
212
  const wasPaused = this.paused;
200
213
  if (!currentTrack) {
201
- this.manager.emit("debug", `Moonlink.js > Player#softRestart >> No current track, skipping soft restart for player ${this.guildId}.`);
214
+ this.manager.emit("debug", `NyxLink > Player#softRestart >> No current track, skipping soft restart for player ${this.guildId}.`);
202
215
  return false;
203
216
  }
204
217
  try {
@@ -242,11 +255,11 @@ class Player {
242
255
  this.lastPosition = currentPosition;
243
256
  this.lastPositionTime = Date.now();
244
257
  this.updateActivity();
245
- this.manager.emit("debug", `Moonlink.js > Player#softRestart >> Soft restart completed for player ${this.guildId}.`);
258
+ this.manager.emit("debug", `NyxLink > Player#softRestart >> Soft restart completed for player ${this.guildId}.`);
246
259
  return true;
247
260
  }
248
261
  catch (error) {
249
- this.manager.emit("debug", `Moonlink.js > Player#softRestart >> Soft restart failed: ${error.message}`);
262
+ this.manager.emit("debug", `NyxLink > Player#softRestart >> Soft restart failed: ${error.message}`);
250
263
  return false;
251
264
  }
252
265
  }
@@ -266,6 +279,16 @@ class Player {
266
279
  void operation.catch(error => this.manager.emit('debug', `NyxLink > Storage > Write failed for ${dbPath}: ${error.message}`));
267
280
  return operation;
268
281
  }
282
+ exportSnapshot() {
283
+ return this.commands.enqueue(async () => {
284
+ if (this.destroyed)
285
+ throw new Error('Cannot export a destroyed player');
286
+ const record = await this.manager.database.get(`players.${this.guildId}`);
287
+ if (this.destroyed)
288
+ throw new Error('Cannot export a destroyed player');
289
+ return PlayerSnapshot_1.PlayerSnapshotCodec.capture(this, (0, PlayerSnapshot_1.recordRevision)(record));
290
+ });
291
+ }
269
292
  assertNodeLinkFeature(feature) {
270
293
  this.node.assertFeature(feature);
271
294
  }
@@ -276,33 +299,22 @@ class Player {
276
299
  return track;
277
300
  throw new Error("Invalid track input. Provide a Track instance or encoded string.");
278
301
  }
279
- async sendPlayerUpdate(payload, noReplace) {
280
- const hasNodeLinkExtras = Boolean(payload?.fading ||
281
- payload?.nextTrack ||
282
- payload?.track?.audioTrackId ||
283
- payload?.loudnessNormalizer !== undefined ||
284
- payload?.endTime !== undefined);
285
- if (!this.node.isNodeLink && hasNodeLinkExtras) {
286
- throw (0, Util_1.nodeLinkOnlyError)("updatePlayer extras");
287
- }
288
- const finalPayload = { ...payload };
289
- if (payload.voice) {
290
- const voicePayload = { ...payload.voice };
291
- if (this.node.isNodeLink && (!voicePayload.sessionId || !voicePayload.token || !voicePayload.endpoint)) {
292
- throw new Error("voice payload requires sessionId, token, and endpoint.");
293
- }
294
- if (!voicePayload.channelId && this.voiceChannelId) {
295
- voicePayload.channelId = this.voiceChannelId;
296
- }
297
- finalPayload.voice = voicePayload;
298
- }
302
+ async sendPlayerUpdate(payload, noReplace, reservedTrack) {
303
+ await this.manager.guildOwnership?.assertCurrent(this.guildId);
304
+ const finalPayload = this.node.backend
305
+ ? this.node.backend.preparePlayerUpdate(payload, this.voiceChannelId)
306
+ : (0, ProtocolContracts_1.preparePlayerUpdate)(this.node.isNodeLink ? 'nodelink' : 'unknown', payload, this.voiceChannelId);
299
307
  const attempts = (0, PlaybackAttempt_1.playbackAttempt)(this);
300
- const attempt = typeof payload.track?.encoded === 'string' ? attempts.begin(this.node, payload.track, typeof payload.paused === 'boolean') : undefined;
308
+ const attempt = typeof payload.track?.encoded === 'string' ? attempts.begin(this.node, { ...payload.track, encoded: payload.track.encoded }, typeof payload.paused === 'boolean') : undefined;
301
309
  if (attempt)
302
310
  finalPayload.track = attempt.track;
303
311
  const preload = typeof payload.nextTrack?.encoded === 'string' || payload.nextTrack === null ? attempts.preload(this.node, payload.nextTrack) : undefined;
304
312
  if (preload)
305
313
  finalPayload.nextTrack = preload.track;
314
+ const previousReservation = this.queuePreload;
315
+ const reservation = reservedTrack ? { track: reservedTrack, node: this.node, session: this.node.sessionId } : undefined;
316
+ if (preload)
317
+ this.queuePreload = reservation;
306
318
  let acknowledged = false;
307
319
  try {
308
320
  const response = await this.node.rest.updatePlayer(this.guildId, finalPayload, noReplace);
@@ -311,12 +323,22 @@ class Player {
311
323
  acknowledged = true;
312
324
  if (attempt && !attempt.accepted(response))
313
325
  throw new Error("Backend did not accept the requested track");
326
+ if (preload && !this.destroyed) {
327
+ if (payload.nextTrack === null)
328
+ this.nextTrack = undefined;
329
+ else if (preload.pending() && payload.nextTrack)
330
+ this.nextTrack = structuredClone(payload.nextTrack);
331
+ }
314
332
  return response;
315
333
  }
316
334
  catch (error) {
317
335
  attempt?.rollback();
318
- if (!acknowledged)
336
+ if (!acknowledged) {
337
+ const restoreReservation = preload && this.queuePreload === reservation && (!reservation || preload.pending());
319
338
  preload?.rollback();
339
+ if (restoreReservation)
340
+ this.queuePreload = previousReservation;
341
+ }
320
342
  throw error;
321
343
  }
322
344
  }
@@ -333,8 +355,10 @@ class Player {
333
355
  return this.sendPlayerUpdate({ voice }, true);
334
356
  }
335
357
  async connect({ selfDeaf, selfMute } = {}) {
358
+ await this.manager.guildOwnership?.assertCurrent(this.guildId);
359
+ this.node.cancelVoiceReconnect?.(this);
336
360
  const connectStack = new Error().stack?.split("\n").slice(2, 8).join("\n");
337
- this.manager.emit("debug", `Moonlink.js > Player#connect -> Connect requested for guild ${this.guildId}. Stack: ${connectStack || "unavailable"}`);
361
+ this.manager.emit("debug", `NyxLink > Player#connect -> Connect requested for guild ${this.guildId}. Stack: ${connectStack || "unavailable"}`);
338
362
  this.set("userInitiatedConnect", true);
339
363
  if (selfDeaf !== undefined)
340
364
  this.set("selfDeaf", selfDeaf);
@@ -344,28 +368,56 @@ class Player {
344
368
  return this;
345
369
  }
346
370
  async disconnect() {
371
+ this.node.cancelVoiceReconnect?.(this);
347
372
  const disconnectStack = new Error().stack?.split("\n").slice(2, 8).join("\n");
348
- this.manager.emit("debug", `Moonlink.js > Player#disconnect -> Disconnect requested for guild ${this.guildId}. Stack: ${disconnectStack || "unavailable"}`);
373
+ this.manager.emit("debug", `NyxLink > Player#disconnect -> Disconnect requested for guild ${this.guildId}. Stack: ${disconnectStack || "unavailable"}`);
349
374
  this.set("userInitiatedConnect", false);
350
375
  await this.voice.disconnect();
351
376
  return this;
352
377
  }
353
378
  async play(options = {}) {
354
379
  const ticket = (0, PlaybackGuard_1.playbackGuard)(this).invalidate();
355
- return this.commands.enqueue(() => this.playNext(options, ticket));
380
+ this.pendingPlayTicket = ticket;
381
+ return this.commands.enqueue(async () => {
382
+ const played = await (0, OpenTelemetry_1.observeOperation)(this.manager, 'nyxlink.player.play', () => this.playNext(options, ticket), result => result ? 'success' : 'resolved');
383
+ if (played)
384
+ this.lastSuccessfulExplicitPlayTicket = ticket;
385
+ return played;
386
+ }).finally(() => {
387
+ if (this.pendingPlayTicket === ticket)
388
+ this.pendingPlayTicket = undefined;
389
+ });
356
390
  }
357
391
  async playAutoPlay(track, ticket, automaticTicket) {
358
- return this.commands.enqueue(() => this.playNext({ track }, ticket, () => this.autoPlay && (0, PlaybackGuard_1.playbackGuard)(this).isAutoCurrent(automaticTicket)));
392
+ return this.commands.enqueue(async () => {
393
+ if (this.queue.size > 0)
394
+ return false;
395
+ let automaticTrackQueued = false;
396
+ const markAutomaticQueue = (queued) => { automaticTrackQueued = queued; };
397
+ try {
398
+ return await (0, OpenTelemetry_1.observeOperation)(this.manager, 'nyxlink.autoplay', () => this.playNext({ track }, ticket, () => this.autoPlay && (0, PlaybackGuard_1.playbackGuard)(this).isAutoCurrent(automaticTicket) &&
399
+ (automaticTrackQueued
400
+ ? this.queue.size === 1 && this.queue.first === track
401
+ : this.queue.size === 0), markAutomaticQueue), result => result ? 'success' : 'resolved');
402
+ }
403
+ finally {
404
+ if (automaticTrackQueued) {
405
+ const index = this.queue.tracks.indexOf(track);
406
+ if (index >= 0)
407
+ this.queue.remove(index);
408
+ }
409
+ }
410
+ });
359
411
  }
360
- async playNext(options, ticket, allowed = () => true) {
412
+ async playNext(options, ticket, allowed = () => true, onInjectedQueueChange, suppressHistory = false) {
361
413
  try {
362
- return await this.applyPlayback(options, ticket, allowed);
414
+ return await this.applyPlayback(options, ticket, allowed, onInjectedQueueChange, suppressHistory);
363
415
  }
364
416
  finally {
365
417
  (0, PlaybackAttempt_1.playbackAttempt)(this).retain(ticket);
366
418
  }
367
419
  }
368
- async applyPlayback(options, ticket, allowed) {
420
+ async applyPlayback(options, ticket, allowed, onInjectedQueueChange, suppressHistory = false) {
369
421
  const guard = (0, PlaybackGuard_1.playbackGuard)(this);
370
422
  if (this.destroyed || !guard.isCurrent(ticket) || !allowed())
371
423
  return false;
@@ -380,14 +432,16 @@ class Player {
380
432
  else {
381
433
  finalOptions = options;
382
434
  }
383
- this.manager.emit("debug", `Moonlink.js > Player#play -> play() called for guild ${this.guildId} with options: ${JSON.stringify(options)}`);
435
+ if (finalOptions.audioTrackId !== undefined && !(0, AdvancedAudioRecovery_1.canSendNativeAudio)(this.node, 'audioTrackId'))
436
+ return false;
437
+ this.manager.emit("debug", `NyxLink > Player#play -> Playback requested for guild ${this.guildId}. Explicit track: ${Boolean(finalOptions.track || finalOptions.encoded)}`);
384
438
  if (!this.voice.sessionId || !this.voice.endpoint) {
385
- this.manager.emit("debug", `Moonlink.js > Player#play >> Voice not ready for guild ${this.guildId}, attempting to connect...`);
439
+ this.manager.emit("debug", `NyxLink > Player#play >> Voice not ready for guild ${this.guildId}, attempting to connect...`);
386
440
  try {
387
441
  await this.connect();
388
442
  }
389
443
  catch (e) {
390
- this.manager.emit("debug", `Moonlink.js > Player#play >> Failed to connect voice: ${e}`);
444
+ this.manager.emit("debug", `NyxLink > Player#play >> Failed to connect voice: ${e}`);
391
445
  return false;
392
446
  }
393
447
  }
@@ -397,52 +451,58 @@ class Player {
397
451
  if (finalOptions.encoded) {
398
452
  try {
399
453
  const decoded = (0, Util_1.decodeTrack)(finalOptions.encoded);
400
- track = new Track_1.Track(decoded, finalOptions.requester);
454
+ track = new Track_1.Track(decoded, finalOptions.requester, undefined, this.manager.options.trackPartial ?? []);
401
455
  }
402
456
  catch (e) {
403
- this.manager.emit("debug", `Moonlink.js > Player#play >> Error decoding track for guild ${this.guildId}. Error: ${e}`);
457
+ this.manager.emit("debug", `NyxLink > Player#play >> Error decoding track for guild ${this.guildId}. Error: ${e}`);
404
458
  return false;
405
459
  }
406
460
  }
407
461
  if (track && !(track instanceof Track_1.Track)) {
408
462
  try {
409
- track = new Track_1.Track(track, finalOptions.requester);
463
+ track = new Track_1.Track(track, finalOptions.requester, undefined, this.manager.options.trackPartial ?? []);
410
464
  }
411
465
  catch (e) {
412
- this.manager.emit("debug", `Moonlink.js > Player#play >> Invalid track object for guild ${this.guildId}. Error: ${e}`);
466
+ this.manager.emit("debug", `NyxLink > Player#play >> Invalid track object for guild ${this.guildId}. Error: ${e}`);
413
467
  return false;
414
468
  }
415
469
  }
416
470
  if (track) {
417
471
  this.queue.unshift(track);
418
- this.manager.emit("debug", `Moonlink.js > Player#play >> Added track "${track.title}" to front of queue for guild ${this.guildId}`);
472
+ onInjectedQueueChange?.(true);
473
+ this.manager.emit("debug", `NyxLink > Player#play >> Added track "${track.title}" to front of queue for guild ${this.guildId}`);
419
474
  }
420
475
  if (this.queue.size === 0) {
421
- this.manager.emit("debug", `Moonlink.js > Player#play >> Queue is empty, cannot start playback for guild ${this.guildId}`);
476
+ this.manager.emit("debug", `NyxLink > Player#play >> Queue is empty, cannot start playback for guild ${this.guildId}`);
422
477
  return false;
423
478
  }
424
479
  const previousTrack = this.current;
425
480
  const queuedTrack = this.queue.first;
426
481
  let nextTrack = queuedTrack;
427
- if (!nextTrack || !nextTrack.encoded) {
428
- this.manager.emit("debug", `Moonlink.js > Player#play >> Invalid track data for guild ${this.guildId}. Next track is ${JSON.stringify(nextTrack)}`);
482
+ if (!queuedTrack || !nextTrack || !nextTrack.encoded) {
483
+ this.manager.emit("debug", `NyxLink > Player#play >> Invalid track data for guild ${this.guildId}.`);
429
484
  return false;
430
485
  }
486
+ let selectedPlaybackTrack;
431
487
  try {
432
- nextTrack = await TrackResolver_1.TrackResolver.resolve(nextTrack, this.node);
488
+ nextTrack = await TrackResolver_1.TrackResolver.resolve(nextTrack, this.node, undefined, guard.signal);
489
+ selectedPlaybackTrack = nextTrack instanceof Track_1.Track ? nextTrack :
490
+ new Track_1.Track(nextTrack, undefined, undefined, this.manager.options.trackPartial ?? []);
433
491
  }
434
492
  catch (error) {
435
- this.manager.emit('debug', `NyxLink > TrackResolver > ${error.message}`);
493
+ this.manager.emit('debug', `NyxLink > TrackResolver > ${error instanceof Error ? error.message : String(error)}`);
436
494
  return false;
437
495
  }
438
496
  if (this.destroyed || !guard.isCurrent(ticket) || !allowed() || this.queue.first !== queuedTrack)
439
497
  return false;
440
498
  this.queue.shift();
499
+ onInjectedQueueChange?.(false);
441
500
  const oldTrackTitle = this.current?.title ?? "null";
442
- this.current = nextTrack instanceof Track_1.Track ? nextTrack : new Track_1.Track(nextTrack);
501
+ const positionBeforePlayback = selectedPlaybackTrack.position;
502
+ this.current = selectedPlaybackTrack;
443
503
  this.current.position = finalOptions.position || 0;
444
504
  this.updateData("current", TrackCodec_1.TrackCodec.serialize(this.current));
445
- this.manager.emit("debug", `Moonlink.js > Player#play >> Player state changed: current track: ${oldTrackTitle} -> ${this.current.title}`);
505
+ this.manager.emit("debug", `NyxLink > Player#play >> Player state changed: current track: ${oldTrackTitle} -> ${this.current.title}`);
446
506
  const oldPlaying = this.playing;
447
507
  const oldPaused = this.paused;
448
508
  this.playing = true;
@@ -458,72 +518,95 @@ class Player {
458
518
  position: finalOptions.position || this.current.position,
459
519
  volume: this.volume
460
520
  };
461
- if (audioTrackId) {
462
- payload.track.audioTrackId = audioTrackId;
463
- }
464
- if (this.fading)
465
- payload.fading = this.fading;
466
- if (this.nextTrack)
467
- payload.nextTrack = this.nextTrack;
468
- if (this.loudnessNormalizer !== undefined) {
469
- payload.loudnessNormalizer = this.loudnessNormalizer;
470
- }
521
+ (0, AdvancedAudioRecovery_1.projectAdvancedAudio)(payload, this.node, {
522
+ audioTrackId, fading: this.fading, crossfade: this.crossfade,
523
+ loudnessNormalizer: this.loudnessNormalizer,
524
+ nextTrack: this.queuePreload ? null : this.nextTrack
525
+ });
471
526
  this.manager.emit("playerTriggeredPlay", this, this.current);
472
- this.manager.emit("debug", `Moonlink.js > Player#play -> Sending play request to node ${this.node.identifier} for guild ${this.guildId}. Payload: ${JSON.stringify(payload)}`);
527
+ this.manager.emit("debug", `NyxLink > Player#play -> Sending play request to node ${this.node.identifier} for guild ${this.guildId}.`);
473
528
  try {
474
529
  const response = await this.sendPlayerUpdate(payload, finalOptions.noReplace ?? this.manager.options.noReplace);
475
530
  if (response == null)
476
531
  throw new Error("Backend did not acknowledge playback");
477
532
  if (!guard.isCurrent(ticket) || this.destroyed)
478
533
  return false;
479
- this.manager.emit("debug", `Moonlink.js > Player#play >> Successfully sent play request for track "${this.current.title}" for guild ${this.guildId}`);
534
+ this.manager.emit("debug", `NyxLink > Player#play >> Successfully sent play request for track "${this.current.title}" for guild ${this.guildId}`);
480
535
  }
481
536
  catch (e) {
482
- this.manager.emit("debug", `Moonlink.js > Player#play >> CRITICAL: Failed to send play request for guild ${this.guildId}. Reverting state. Error: ${e.message}`);
537
+ this.manager.emit("debug", `NyxLink > Player#play >> CRITICAL: Failed to send play request for guild ${this.guildId}. Reverting state. Error: ${e.message}`);
483
538
  this.playing = oldPlaying;
484
539
  this.paused = oldPaused;
540
+ selectedPlaybackTrack.position = positionBeforePlayback;
485
541
  this.current = previousTrack;
486
- this.queue.unshift(nextTrack);
542
+ this.updateData("current", previousTrack ? TrackCodec_1.TrackCodec.serialize(previousTrack) : null);
543
+ this.updateData("playing", oldPlaying);
544
+ this.updateData("paused", oldPaused);
545
+ this.queue.unshift(queuedTrack);
546
+ onInjectedQueueChange?.(true);
487
547
  return false;
488
548
  }
489
- if (previousTrack && !this.get("isBackPlay")) {
549
+ if (previousTrack && !suppressHistory && !this.get("isBackPlay")) {
490
550
  this.previous.push(previousTrack);
491
551
  const historyLimit = this.manager.options.queue?.historyLimit ?? this.historySize;
492
552
  if (this.previous.length > historyLimit) {
493
553
  this.previous.shift();
494
554
  }
495
555
  this.updateData("previous", this.previous.map(t => TrackCodec_1.TrackCodec.serialize(t)));
496
- this.manager.emit("debug", `Moonlink.js > Player#play << Added track "${previousTrack.title}" to history for guild ${this.guildId}. History size: ${this.previous.length}`);
556
+ this.manager.emit("debug", `NyxLink > Player#play << Added track "${previousTrack.title}" to history for guild ${this.guildId}. History size: ${this.previous.length}`);
497
557
  }
498
558
  this.set("isBackPlay", false);
499
559
  this.playing = true;
500
560
  this.paused = false;
501
- this.manager.emit("debug", `Moonlink.js > Player#play >> Player state changed: playing: ${oldPlaying} -> ${this.playing}, paused: ${oldPaused} -> ${this.paused}`);
561
+ this.manager.emit("debug", `NyxLink > Player#play >> Player state changed: playing: ${oldPlaying} -> ${this.playing}, paused: ${oldPaused} -> ${this.paused}`);
502
562
  this.node.updateRecommendations(this).catch(() => { });
503
563
  return true;
504
564
  }
505
565
  async addMix(track, options) {
506
566
  this.assertNodeLinkFeature("mix:add");
507
567
  const encoded = this.resolveEncodedTrack(track);
508
- return this.node.rest.addMixLayer(this.guildId, {
568
+ const body = (0, NodeLinkMixContracts_1.mixCreateBody)({
509
569
  track: { encoded, userData: options?.userData },
510
570
  volume: options?.volume
511
571
  });
572
+ return this.mixCommand('mix:add', node => node.rest.addMixLayer(this.guildId, body));
512
573
  }
513
574
  async getMixes() {
514
575
  this.assertNodeLinkFeature("mix:list");
515
- return this.node.rest.getMixLayers(this.guildId);
576
+ return this.mixCommand('mix:list', node => node.rest.getMixLayers(this.guildId));
516
577
  }
517
578
  async updateMixVolume(mixId, volume) {
518
579
  this.assertNodeLinkFeature("mix:update");
519
- await this.node.rest.updateMixLayerVolume(this.guildId, mixId, volume);
580
+ await this.mixCommand('mix:update', node => node.rest.updateMixLayerVolume(this.guildId, mixId, volume));
520
581
  return this;
521
582
  }
522
583
  async removeMix(mixId) {
523
584
  this.assertNodeLinkFeature("mix:remove");
524
- await this.node.rest.removeMixLayer(this.guildId, mixId);
585
+ await this.mixCommand('mix:remove', node => node.rest.removeMixLayer(this.guildId, mixId));
525
586
  return this;
526
587
  }
588
+ mixCommand(operation, execute) {
589
+ const node = this.node, session = node.sessionId, socket = node.socket, backend = node.backend;
590
+ const guard = (0, PlaybackGuard_1.playbackGuard)(this), ticket = guard.ticket;
591
+ const active = () => !this.destroyed && !this.manager.destroyed && !node.destroyed && node.connected &&
592
+ this.node === node && node.sessionId === session && node.socket === socket && node.backend === backend && guard.isCurrent(ticket);
593
+ return this.commands.enqueue(async () => {
594
+ if (!active())
595
+ throw new PlayerOperationCancelledError_1.PlayerOperationCancelledError(operation);
596
+ let result;
597
+ try {
598
+ result = await execute(node);
599
+ }
600
+ catch (error) {
601
+ if (!active())
602
+ throw new PlayerOperationCancelledError_1.PlayerOperationCancelledError(operation);
603
+ throw error;
604
+ }
605
+ if (!active())
606
+ throw new PlayerOperationCancelledError_1.PlayerOperationCancelledError(operation);
607
+ return result;
608
+ });
609
+ }
527
610
  async subscribeLyrics(options) {
528
611
  this.assertNodeLinkFeature("lyrics:subscribe");
529
612
  await this.node.rest.subscribeLyrics(this.guildId, options?.skipTrackSource);
@@ -567,16 +650,39 @@ class Player {
567
650
  return this.node.getDirectStream(target, itag);
568
651
  }
569
652
  async setFading(fading) {
570
- this.assertNodeLinkFeature("fading");
571
- this.fading = fading;
572
- await this.sendPlayerUpdate({ fading });
573
- return this;
653
+ const config = structuredClone(fading);
654
+ return this.commands.enqueue(async () => {
655
+ if (this.destroyed)
656
+ throw new Error("Cannot update a destroyed player");
657
+ this.assertNodeLinkFeature("fading");
658
+ await this.sendPlayerUpdate({ fading: config });
659
+ if (!this.destroyed)
660
+ this.fading = config;
661
+ return this;
662
+ });
574
663
  }
575
664
  async clearFading() {
576
- this.assertNodeLinkFeature("fading");
577
- this.fading = undefined;
578
- await this.sendPlayerUpdate({ fading: { enabled: false } });
579
- return this;
665
+ return this.setFading({ enabled: false });
666
+ }
667
+ getCrossfade() {
668
+ return this.crossfade ? { ...this.crossfade } : undefined;
669
+ }
670
+ async setCrossfade(options) {
671
+ const config = (0, NodeLinkContracts_1.normalizeCrossfade)(options);
672
+ return this.commands.enqueue(async () => {
673
+ if (this.destroyed)
674
+ throw new Error("Cannot update a destroyed player");
675
+ this.assertNodeLinkFeature("crossfade");
676
+ await (0, OpenTelemetry_1.observeOperation)(this.manager, 'nyxlink.crossfade', () => this.sendPlayerUpdate({ crossfade: config }));
677
+ if (!this.destroyed) {
678
+ this.crossfade = config;
679
+ this.requestQueuePreload();
680
+ }
681
+ return this;
682
+ });
683
+ }
684
+ async clearCrossfade() {
685
+ return this.setCrossfade({ enabled: false });
580
686
  }
581
687
  async setNextTrack(track, userData) {
582
688
  const encoded = this.resolveEncodedTrack(track);
@@ -586,7 +692,6 @@ class Player {
586
692
  this.assertNodeLinkFeature("nextTrack");
587
693
  const nextTrack = { encoded, userData: userData ?? (track instanceof Track_1.Track ? track.userData : undefined) };
588
694
  await this.sendPlayerUpdate({ nextTrack });
589
- this.nextTrack = nextTrack;
590
695
  return this;
591
696
  });
592
697
  }
@@ -596,20 +701,100 @@ class Player {
596
701
  throw new Error("Cannot update a destroyed player");
597
702
  this.assertNodeLinkFeature("nextTrack");
598
703
  await this.sendPlayerUpdate({ nextTrack: null });
599
- this.nextTrack = undefined;
600
704
  return this;
601
705
  });
602
706
  }
707
+ getNextTrack() {
708
+ return this.nextTrack ? structuredClone(this.nextTrack) : undefined;
709
+ }
710
+ setQueuePreload(options) {
711
+ if (!options || typeof options.enabled !== 'boolean' ||
712
+ options.leadMs !== undefined && (!Number.isSafeInteger(options.leadMs) || options.leadMs < 1000 || options.leadMs > 120000)) {
713
+ throw new TypeError('Invalid queue preload options');
714
+ }
715
+ this.preloadOptions = { enabled: options.enabled, leadMs: options.leadMs ?? 35000 };
716
+ this.requestQueuePreload();
717
+ return this;
718
+ }
719
+ requestQueuePreload() {
720
+ if (this.destroyed || this.manager.destroyed || (!this.preloadOptions?.enabled && !this.queuePreload))
721
+ return;
722
+ const ticket = (0, PlaybackGuard_1.playbackGuard)(this).ticket;
723
+ const node = this.node;
724
+ const session = node.sessionId;
725
+ const active = () => !this.destroyed && !this.manager.destroyed && this.node === node &&
726
+ node.connected && !node.destroyed && node.sessionId === session && (0, PlaybackGuard_1.playbackGuard)(this).isCurrent(ticket);
727
+ const desired = () => active() ? (0, QueuePreload_1.desiredPreload)(this, this.preloadOptions, !!this.crossfade?.enabled) : undefined;
728
+ this.preloadScheduler.request(operation => this.commands.enqueue(operation), async () => {
729
+ if (!active())
730
+ return;
731
+ const reservation = this.queuePreload;
732
+ if (reservation && (reservation.node !== node || reservation.session !== session)) {
733
+ this.queuePreload = undefined;
734
+ this.nextTrack = undefined;
735
+ }
736
+ if (!node.isNodeLink)
737
+ return;
738
+ let candidate = desired();
739
+ if (this.queuePreload) {
740
+ if (this.queuePreload.track === candidate)
741
+ return;
742
+ await this.sendPlayerUpdate({ nextTrack: null });
743
+ candidate = desired();
744
+ }
745
+ if (!candidate || this.paused || this.nextTrack)
746
+ return;
747
+ const current = this.current;
748
+ const resolved = await TrackResolver_1.TrackResolver.resolve(candidate, node, undefined, (0, PlaybackGuard_1.playbackGuard)(this).signal);
749
+ if (this.current !== current || desired() !== candidate || this.paused || this.nextTrack)
750
+ return;
751
+ await this.sendPlayerUpdate({ nextTrack: { encoded: resolved.encoded, userData: resolved.userData } }, undefined, candidate);
752
+ }, () => {
753
+ this.manager.emit('debug', 'NyxLink > Queue preload request failed');
754
+ }, () => this.requestQueuePreload());
755
+ }
756
+ completeAudioMigration() {
757
+ const manualPreloadDiscarded = !!this.nextTrack && !this.queuePreload;
758
+ this.nextTrack = undefined;
759
+ this.queuePreload = undefined;
760
+ (0, PlaybackAttempt_1.playbackAttempt)(this).preload(this.node, null);
761
+ this.requestQueuePreload();
762
+ return manualPreloadDiscarded;
763
+ }
764
+ consumePreloadedTrack() {
765
+ const reservation = this.queuePreload;
766
+ this.queuePreload = undefined;
767
+ this.nextTrack = undefined;
768
+ if (reservation && reservation.node === this.node && reservation.session === this.node.sessionId) {
769
+ const index = this.queue.tracks.indexOf(reservation.track);
770
+ if (index !== -1)
771
+ this.queue.remove(index);
772
+ if (this.current) {
773
+ this.previous.push(this.current);
774
+ const limit = this.manager.options.queue?.historyLimit ?? this.historySize;
775
+ if (this.previous.length > limit)
776
+ this.previous.shift();
777
+ this.updateData('previous', this.previous.map(track => TrackCodec_1.TrackCodec.serialize(track)));
778
+ }
779
+ }
780
+ }
603
781
  setAudioTrackId(audioTrackId) {
604
782
  this.assertNodeLinkFeature("audioTrackId");
605
783
  this.audioTrackId = audioTrackId;
606
784
  return this;
607
785
  }
608
786
  async setLoudnessNormalizer(enabled) {
609
- this.assertNodeLinkFeature("loudnessNormalizer");
610
- this.loudnessNormalizer = enabled;
611
- await this.sendPlayerUpdate({ loudnessNormalizer: enabled });
612
- return this;
787
+ if (typeof enabled !== 'boolean')
788
+ throw new TypeError('Invalid loudness normalizer state');
789
+ return this.commands.enqueue(async () => {
790
+ if (this.destroyed)
791
+ throw new Error("Cannot update a destroyed player");
792
+ this.assertNodeLinkFeature("loudnessNormalizer");
793
+ await this.sendPlayerUpdate({ loudnessNormalizer: enabled });
794
+ if (!this.destroyed)
795
+ this.loudnessNormalizer = enabled;
796
+ return this;
797
+ });
613
798
  }
614
799
  createVoiceReceiver(options) {
615
800
  this.assertNodeLinkFeature("voiceReceive");
@@ -622,17 +807,17 @@ class Player {
622
807
  if (this.destroyed)
623
808
  return this;
624
809
  if (this.paused) {
625
- this.manager.emit("debug", `Moonlink.js > Player#pause >> Player is already paused for guild ${this.guildId}`);
810
+ this.manager.emit("debug", `NyxLink > Player#pause >> Player is already paused for guild ${this.guildId}`);
626
811
  return this;
627
812
  }
628
- this.manager.emit("debug", `Moonlink.js > Player#pause -> Sending pause request to node ${this.node.identifier} for guild ${this.guildId}`);
813
+ this.manager.emit("debug", `NyxLink > Player#pause -> Sending pause request to node ${this.node.identifier} for guild ${this.guildId}`);
629
814
  this.manager.emit("playerTriggeredPause", this);
630
815
  await this.sendPlayerUpdate({ paused: true });
631
816
  const oldPaused = this.paused;
632
817
  this.paused = true;
633
818
  this.updateData("paused", this.paused);
634
- this.manager.emit("debug", `Moonlink.js > Player#pause >> Player state changed: paused: ${oldPaused} -> ${this.paused}`);
635
- this.manager.emit("debug", `Moonlink.js > Player#pause >> Player paused for guild ${this.guildId}`);
819
+ this.manager.emit("debug", `NyxLink > Player#pause >> Player state changed: paused: ${oldPaused} -> ${this.paused}`);
820
+ this.manager.emit("debug", `NyxLink > Player#pause >> Player paused for guild ${this.guildId}`);
636
821
  return this;
637
822
  }
638
823
  async resume(options) {
@@ -658,29 +843,29 @@ class Player {
658
843
  const now = Date.now();
659
844
  const minResumeInterval = this.manager.options.playerHealth?.resumeDebounce ?? 1000;
660
845
  if (this.isResumeInProgress) {
661
- this.manager.emit("debug", `Moonlink.js > Player#resume >> Resume already in progress for guild ${this.guildId}, skipping.`);
846
+ this.manager.emit("debug", `NyxLink > Player#resume >> Resume already in progress for guild ${this.guildId}, skipping.`);
662
847
  return this;
663
848
  }
664
849
  if (now - this.lastResumeAttempt < minResumeInterval) {
665
- this.manager.emit("debug", `Moonlink.js > Player#resume >> Resume debounced for guild ${this.guildId} (last attempt ${now - this.lastResumeAttempt}ms ago).`);
850
+ this.manager.emit("debug", `NyxLink > Player#resume >> Resume debounced for guild ${this.guildId} (last attempt ${now - this.lastResumeAttempt}ms ago).`);
666
851
  return this;
667
852
  }
668
853
  this.updateActivity();
669
854
  if (!this.paused) {
670
- this.manager.emit("debug", `Moonlink.js > Player#resume >> Player is not paused for guild ${this.guildId}`);
855
+ this.manager.emit("debug", `NyxLink > Player#resume >> Player is not paused for guild ${this.guildId}`);
671
856
  return this;
672
857
  }
673
858
  this.isResumeInProgress = true;
674
859
  this.lastResumeAttempt = now;
675
- this.manager.emit("debug", `Moonlink.js > Player#resume -> Sending resume request to node ${this.node.identifier} for guild ${this.guildId}`);
860
+ this.manager.emit("debug", `NyxLink > Player#resume -> Sending resume request to node ${this.node.identifier} for guild ${this.guildId}`);
676
861
  this.manager.emit("playerTriggeredResume", this);
677
862
  try {
678
863
  await this.sendPlayerUpdate({ paused: false });
679
864
  const oldPaused = this.paused;
680
865
  this.paused = false;
681
866
  this.updateData("paused", this.paused);
682
- this.manager.emit("debug", `Moonlink.js > Player#resume >> Player state changed: paused: ${oldPaused} -> ${this.paused}`);
683
- this.manager.emit("debug", `Moonlink.js > Player#resume >> Player resumed for guild ${this.guildId}`);
867
+ this.manager.emit("debug", `NyxLink > Player#resume >> Player state changed: paused: ${oldPaused} -> ${this.paused}`);
868
+ this.manager.emit("debug", `NyxLink > Player#resume >> Player resumed for guild ${this.guildId}`);
684
869
  }
685
870
  finally {
686
871
  this.isResumeInProgress = false;
@@ -690,13 +875,13 @@ class Player {
690
875
  async forward(ms) {
691
876
  if (!this.current)
692
877
  return this;
693
- const newPosition = Math.min(this.current.duration, this.current.position + ms);
878
+ const newPosition = Math.min(this.current.getInfo().length, this.current.getInfo().position + ms);
694
879
  return this.seek(newPosition);
695
880
  }
696
881
  async rewind(ms) {
697
882
  if (!this.current)
698
883
  return this;
699
- const newPosition = Math.max(0, this.current.position - ms);
884
+ const newPosition = Math.max(0, this.current.getInfo().position - ms);
700
885
  return this.seek(newPosition);
701
886
  }
702
887
  async setVoiceState(state) {
@@ -725,23 +910,29 @@ class Player {
725
910
  }
726
911
  async stop() {
727
912
  (0, PlaybackGuard_1.playbackGuard)(this).invalidate();
728
- return this.commands.enqueue(() => this.stopPlayback());
913
+ return this.commands.enqueue(() => (0, OpenTelemetry_1.observeOperation)(this.manager, 'nyxlink.player.stop', () => this.stopPlayback()));
729
914
  }
730
915
  async stopPlayback() {
731
916
  if (this.destroyed)
732
917
  return this;
733
- this.manager.emit("debug", `Moonlink.js > Player#stop -> Sending stop request to node ${this.node.identifier} for guild ${this.guildId}`);
918
+ this.manager.emit("debug", `NyxLink > Player#stop -> Sending stop request to node ${this.node.identifier} for guild ${this.guildId}`);
734
919
  this.manager.emit("playerTriggeredStop", this);
735
- await this.sendPlayerUpdate({ track: { encoded: null } });
920
+ await this.sendPlayerUpdate({
921
+ track: { encoded: null },
922
+ ...(this.node.isNodeLink && this.nextTrack ? { nextTrack: null } : {})
923
+ });
736
924
  const oldPlaying = this.playing;
737
- this.playing = false;
738
- this.updateData("playing", this.playing);
739
- this.manager.emit("debug", `Moonlink.js > Player#stop >> Player state changed: playing: ${oldPlaying} -> ${this.playing}`);
925
+ const oldPaused = this.paused;
740
926
  const oldTrackTitle = this.current?.title ?? "null";
927
+ this.playing = false;
928
+ this.paused = false;
741
929
  this.current = null;
742
- this.updateData("current", this.current);
743
- this.manager.emit("debug", `Moonlink.js > Player#stop >> Player state changed: current: ${oldTrackTitle} -> null`);
744
- this.manager.emit("debug", `Moonlink.js > Player#stop >> Player stopped for guild ${this.guildId}`);
930
+ await this.updateData("playing", false);
931
+ await this.updateData("paused", false);
932
+ await this.updateData("current", null);
933
+ this.manager.emit("debug", `NyxLink > Player#stop >> State changed: playing: ${oldPlaying} -> ${this.playing}, paused: ${oldPaused} -> ${this.paused}`);
934
+ this.manager.emit("debug", `NyxLink > Player#stop >> Player state changed: current: ${oldTrackTitle} -> null`);
935
+ this.manager.emit("debug", `NyxLink > Player#stop >> Player stopped for guild ${this.guildId}`);
745
936
  this.manager.emit("playerStop", this);
746
937
  return this;
747
938
  }
@@ -762,8 +953,38 @@ class Player {
762
953
  this.manager.emit("playerTriggeredSkip", this, this.current, track, position);
763
954
  if (this.destroyed || !guard.isCurrent(ticket) || this.queue.get(position) !== track)
764
955
  return false;
765
- this.queue.remove(position);
766
- return await this.playNext({ track: track instanceof Track_1.Track ? track : new Track_1.Track(track) }, ticket);
956
+ let playbackTrack;
957
+ try {
958
+ playbackTrack = track instanceof Track_1.Track ? track :
959
+ new Track_1.Track(track, undefined, undefined, this.manager.options.trackPartial ?? []);
960
+ }
961
+ catch (error) {
962
+ this.manager.emit("debug", `NyxLink > Player#skip >> Invalid queued track: ${error instanceof Error ? error.name : "unknown"}`);
963
+ return false;
964
+ }
965
+ const selected = this.queue.remove(position);
966
+ if (!selected)
967
+ return false;
968
+ const originalPosition = playbackTrack.position;
969
+ let injectedTrackQueued = false;
970
+ let played = false;
971
+ try {
972
+ played = await this.playNext({ track: playbackTrack }, ticket, () => true, queued => { injectedTrackQueued = queued; });
973
+ return played;
974
+ }
975
+ finally {
976
+ if (!played) {
977
+ playbackTrack.position = originalPosition;
978
+ if (injectedTrackQueued) {
979
+ const injectedIndex = this.queue.tracks.indexOf(playbackTrack);
980
+ if (injectedIndex >= 0)
981
+ this.queue.remove(injectedIndex);
982
+ }
983
+ if (!this.destroyed && !this.manager.destroyed) {
984
+ this.queue.insert(Math.min(position, this.queue.size), selected);
985
+ }
986
+ }
987
+ }
767
988
  }
768
989
  finally {
769
990
  (0, PlaybackAttempt_1.playbackAttempt)(this).retain(ticket);
@@ -773,44 +994,55 @@ class Player {
773
994
  if (!this.queue.size) {
774
995
  if (this.autoPlay) {
775
996
  if (!this.current) {
776
- this.manager.emit("debug", `Moonlink.js > Player#skip >> Queue is empty and no current track, cannot trigger autoPlay for guild ${this.guildId}`);
997
+ this.manager.emit("debug", `NyxLink > Player#skip >> Queue is empty and no current track, cannot trigger autoPlay for guild ${this.guildId}`);
777
998
  return false;
778
999
  }
779
- this.manager.emit("debug", `Moonlink.js > Player#skip >> Queue empty, triggering autoPlay for guild ${this.guildId}`);
1000
+ this.manager.emit("debug", `NyxLink > Player#skip >> Queue empty, triggering autoPlay for guild ${this.guildId}`);
780
1001
  return await this.node.handleAutoPlay(this, this.current);
781
1002
  }
782
- this.manager.emit("debug", `Moonlink.js > Player#skip >> Queue is empty, stopping player for guild ${this.guildId}`);
1003
+ this.manager.emit("debug", `NyxLink > Player#skip >> Queue is empty, stopping player for guild ${this.guildId}`);
783
1004
  await this.stop();
784
1005
  return true;
785
1006
  }
786
1007
  const nextTrack = this.queue.first;
1008
+ if (!nextTrack)
1009
+ return false;
787
1010
  this.manager.emit("playerTriggeredSkip", this, oldTrack, nextTrack, 0);
788
- this.manager.emit("debug", `Moonlink.js > Player#skip -> Skipping to next track in queue for guild ${this.guildId}`);
1011
+ this.manager.emit("debug", `NyxLink > Player#skip -> Skipping to next track in queue for guild ${this.guildId}`);
789
1012
  return await this.play();
790
1013
  }
791
1014
  async seek(position) {
792
- return this.commands.enqueue(() => this.seekPlayback(position));
1015
+ const ticket = (0, PlaybackGuard_1.playbackGuard)(this).ticket;
1016
+ const track = this.current;
1017
+ const afterPendingPlay = this.pendingPlayTicket === ticket;
1018
+ return this.commands.enqueue(() => (0, OpenTelemetry_1.observeOperation)(this.manager, 'nyxlink.player.seek', () => this.seekPlayback(position, ticket, track, afterPendingPlay)));
793
1019
  }
794
- async seekPlayback(position) {
1020
+ async seekPlayback(position, ticket, track, afterPendingPlay) {
795
1021
  if (this.destroyed)
796
1022
  return this;
797
- (0, Util_1.validate)(position, (v) => typeof v === "number" && !isNaN(v) && v >= 0, "Player#seek > Position must be a valid number.");
798
- this.manager.emit("debug", `Moonlink.js > Player#seek -> Seeking to position ${position}ms for guild ${this.guildId}`);
1023
+ (0, Util_1.validate)(position, (v) => typeof v === "number" && Number.isFinite(v) && v >= 0, "Player#seek > Position must be a valid number.");
1024
+ const guard = (0, PlaybackGuard_1.playbackGuard)(this);
1025
+ if (!guard.isCurrent(ticket) ||
1026
+ (afterPendingPlay && this.lastSuccessfulExplicitPlayTicket !== ticket) ||
1027
+ (!afterPendingPlay && track !== null && this.current !== track))
1028
+ return this;
1029
+ const activeTrack = this.current;
1030
+ this.manager.emit("debug", `NyxLink > Player#seek -> Seeking to position ${position}ms for guild ${this.guildId}`);
799
1031
  this.manager.emit("playerTriggeredSeek", this, position);
800
1032
  await this.sendPlayerUpdate({ position });
801
- if (this.current) {
802
- this.current.position = position;
1033
+ if (guard.isCurrent(ticket) && !this.destroyed && this.current === activeTrack && activeTrack) {
1034
+ activeTrack.position = position;
803
1035
  }
804
- this.manager.emit("debug", `Moonlink.js > Player#seek >> Sent seek request to node ${this.node.identifier}`);
1036
+ this.manager.emit("debug", `NyxLink > Player#seek >> Sent seek request to node ${this.node.identifier}`);
805
1037
  return this;
806
1038
  }
807
1039
  setVolume(volume) {
808
- (0, Util_1.validate)(volume, (v) => typeof v === "number" && !isNaN(v) && v >= 0 && v <= 1000, "Player#setVolume > Volume must be between 0 and 1000.");
1040
+ (0, Util_1.validate)(volume, (v) => typeof v === "number" && Number.isFinite(v) && v >= 0 && v <= 1000, "Player#setVolume > Volume must be between 0 and 1000.");
809
1041
  this.optimisticVolumeRevision = ++this.volumeRevision;
810
1042
  const oldVolume = this.volume;
811
1043
  this.volume = volume;
812
1044
  this.manager.emit("playerChangedVolume", this, oldVolume, volume);
813
- this.manager.emit("debug", `Moonlink.js > Player#setVolume -> Changing volume from ${oldVolume} to ${volume} for guild ${this.guildId}`);
1045
+ this.manager.emit("debug", `NyxLink > Player#setVolume -> Changing volume from ${oldVolume} to ${volume} for guild ${this.guildId}`);
814
1046
  void this.commands.enqueue(async () => {
815
1047
  if (this.destroyed)
816
1048
  return;
@@ -820,7 +1052,7 @@ class Player {
820
1052
  this.manager.emit("debug", `NyxLink > Player#setVolume >> Volume update failed for guild ${this.guildId}: ${error.message}`);
821
1053
  });
822
1054
  this.updateData("volume", this.volume);
823
- this.manager.emit("debug", `Moonlink.js > Player#setVolume >> Volume updated for guild ${this.guildId}`);
1055
+ this.manager.emit("debug", `NyxLink > Player#setVolume >> Volume updated for guild ${this.guildId}`);
824
1056
  return this;
825
1057
  }
826
1058
  async setVolumeAsync(volume) {
@@ -829,7 +1061,21 @@ class Player {
829
1061
  return this.commands.enqueue(async () => {
830
1062
  if (this.destroyed)
831
1063
  throw new Error("Cannot update volume on a destroyed player");
832
- await this.sendPlayerUpdate({ volume });
1064
+ const node = this.node, session = node.sessionId, socket = node.socket, backend = node.backend;
1065
+ const active = () => !this.destroyed && !this.manager.destroyed && !node.destroyed && node.connected &&
1066
+ this.node === node && node.sessionId === session && node.socket === socket && node.backend === backend;
1067
+ if (!active())
1068
+ throw new PlayerOperationCancelledError_1.PlayerOperationCancelledError('volume');
1069
+ try {
1070
+ await this.sendPlayerUpdate({ volume });
1071
+ }
1072
+ catch (error) {
1073
+ if (!active())
1074
+ throw new PlayerOperationCancelledError_1.PlayerOperationCancelledError('volume');
1075
+ throw error;
1076
+ }
1077
+ if (!active())
1078
+ throw new PlayerOperationCancelledError_1.PlayerOperationCancelledError('volume');
833
1079
  if (this.optimisticVolumeRevision > revision)
834
1080
  return this;
835
1081
  const oldVolume = this.volume;
@@ -847,7 +1093,7 @@ class Player {
847
1093
  this.manager.emit("playerChangedLoop", this, oldLoop, this.loop, oldLoopCount, this.loopCount);
848
1094
  this.updateData("loop", this.loop);
849
1095
  this.updateData("loopCount", this.loopCount);
850
- this.manager.emit("debug", `Moonlink.js > Player#setLoop >> Loop mode changed from "${oldLoop}" to "${loop}"${count ? ` (count: ${count})` : ""} for guild ${this.guildId}`);
1096
+ this.manager.emit("debug", `NyxLink > Player#setLoop >> Loop mode changed from "${oldLoop}" to "${loop}"${count ? ` (count: ${count})` : ""} for guild ${this.guildId}`);
851
1097
  return this;
852
1098
  }
853
1099
  setAutoPlay(autoPlay) {
@@ -856,26 +1102,26 @@ class Player {
856
1102
  this.autoPlay = autoPlay;
857
1103
  this.manager.emit("playerAutoPlaySet", this, autoPlay);
858
1104
  this.updateData("autoPlay", this.autoPlay);
859
- this.manager.emit("debug", `Moonlink.js > Player#setAutoPlay >> AutoPlay set to ${autoPlay} for guild ${this.guildId}`);
1105
+ this.manager.emit("debug", `NyxLink > Player#setAutoPlay >> AutoPlay set to ${autoPlay} for guild ${this.guildId}`);
860
1106
  return this;
861
1107
  }
862
1108
  setAutoLeave(autoLeave) {
863
1109
  this.autoLeave = autoLeave;
864
1110
  this.manager.emit("playerAutoLeaveSet", this, autoLeave);
865
1111
  this.updateData("autoLeave", this.autoLeave);
866
- this.manager.emit("debug", `Moonlink.js > Player#setAutoLeave >> AutoLeave set to ${autoLeave} for guild ${this.guildId}`);
1112
+ this.manager.emit("debug", `NyxLink > Player#setAutoLeave >> AutoLeave set to ${autoLeave} for guild ${this.guildId}`);
867
1113
  return this;
868
1114
  }
869
1115
  shuffle() {
870
1116
  if (this.queue.size < 2) {
871
- this.manager.emit("debug", `Moonlink.js > Player#shuffle >> Queue has less than 2 tracks, cannot shuffle for guild ${this.guildId}`);
1117
+ this.manager.emit("debug", `NyxLink > Player#shuffle >> Queue has less than 2 tracks, cannot shuffle for guild ${this.guildId}`);
872
1118
  return this;
873
1119
  }
874
1120
  const oldQueue = [...this.queue.tracks];
875
- this.manager.emit("debug", `Moonlink.js > Player#shuffle -> Shuffling queue with ${this.queue.size} tracks for guild ${this.guildId}`);
1121
+ this.manager.emit("debug", `NyxLink > Player#shuffle -> Shuffling queue with ${this.queue.size} tracks for guild ${this.guildId}`);
876
1122
  this.queue.shuffle();
877
1123
  this.manager.emit("playerTriggeredShuffle", this, oldQueue, this.queue.tracks);
878
- this.manager.emit("debug", `Moonlink.js > Player#shuffle >> Queue shuffled for guild ${this.guildId}`);
1124
+ this.manager.emit("debug", `NyxLink > Player#shuffle >> Queue shuffled for guild ${this.guildId}`);
879
1125
  return this;
880
1126
  }
881
1127
  async destroy(reason) {
@@ -886,8 +1132,15 @@ class Player {
886
1132
  }
887
1133
  (0, PlaybackGuard_1.playbackGuard)(this).invalidate();
888
1134
  this.destroyed = true;
889
- this.destructionPromise = this.commands.enqueue(() => this.destroyPlayback(reason));
890
- this.voice.destroy();
1135
+ this.node.cancelVoiceReconnect?.(this);
1136
+ const leased = this.manager.guildOwnership?.localLease(this.guildId);
1137
+ this.destructionPromise = this.commands.enqueue(() => this.destroyPlayback(reason))
1138
+ .finally(async () => {
1139
+ if (leased)
1140
+ await this.manager.guildOwnership?.release(this.guildId, leased);
1141
+ });
1142
+ if (!this.manager.guildOwnership)
1143
+ this.voice.destroy();
891
1144
  this.stopHealthCheck();
892
1145
  return this.destructionPromise;
893
1146
  }
@@ -898,32 +1151,42 @@ class Player {
898
1151
  }
899
1152
  if (!reason) {
900
1153
  const stack = new Error().stack?.split("\n").slice(2, 8).join("\n");
901
- this.manager.emit("debug", `Moonlink.js > Player#destroy >> Destroy called without reason for guild ${this.guildId}. Stack: ${stack || "unavailable"}`);
1154
+ this.manager.emit("debug", `NyxLink > Player#destroy >> Destroy called without reason for guild ${this.guildId}. Stack: ${stack || "unavailable"}`);
902
1155
  }
903
1156
  const destroyReason = reason ?? "No reason provided";
904
- this.manager.emit("debug", `Moonlink.js > Player#destroy -> Destroying player for guild ${this.guildId}. Reason: ${destroyReason}`);
1157
+ this.manager.emit("debug", `NyxLink > Player#destroy -> Destroying player for guild ${this.guildId}. Reason: ${destroyReason}`);
905
1158
  this.playing = false;
906
1159
  this.paused = false;
907
- try {
908
- await this.disconnect();
909
- }
910
- catch (e) {
911
- this.manager.emit("debug", `Moonlink.js > Player#destroy >> Voice disconnection failed for guild ${this.guildId}: ${e.message}`);
912
- }
913
- try {
914
- await this.node.rest.destroyPlayer(this.guildId);
915
- }
916
- catch (e) {
917
- this.manager.emit("debug", `Moonlink.js > Player#destroy >> Failed to destroy player on node: ${e.message}`);
918
- }
1160
+ const owner = !this.manager.guildOwnership ||
1161
+ await this.manager.guildOwnership.isCurrent(this.guildId);
1162
+ if (owner)
1163
+ try {
1164
+ await this.disconnect();
1165
+ }
1166
+ catch (e) {
1167
+ this.manager.emit("debug", `NyxLink > Player#destroy >> Voice disconnection failed for guild ${this.guildId}: ${e.message}`);
1168
+ }
1169
+ if (owner)
1170
+ try {
1171
+ await this.node.rest.destroyPlayer(this.guildId);
1172
+ }
1173
+ catch (e) {
1174
+ this.manager.emit("debug", `NyxLink > Player#destroy >> Failed to destroy player on node: ${e.message}`);
1175
+ }
919
1176
  this.current = null;
920
1177
  this.queue.clear();
921
1178
  this.previous = [];
922
- this.updateData("previous", []);
923
- this.manager.players.players.delete(this.guildId);
924
- await this.manager.database.remove(`players.${this.guildId}`);
1179
+ if (owner)
1180
+ this.updateData("previous", []);
1181
+ if (this.manager.players.get(this.guildId) === this) {
1182
+ this.manager.players.players.delete(this.guildId);
1183
+ }
1184
+ if (owner && (!this.manager.guildOwnership ||
1185
+ await this.manager.guildOwnership.isCurrent(this.guildId))) {
1186
+ await this.manager.database.remove(`players.${this.guildId}`);
1187
+ }
925
1188
  this.manager.emit('playerDestroyed', this, reason);
926
- this.manager.emit("debug", `Moonlink.js > Player#destroy >> Player destroyed for guild ${this.guildId}.`);
1189
+ this.manager.emit("debug", `NyxLink > Player#destroy >> Player destroyed for guild ${this.guildId}.`);
927
1190
  }
928
1191
  async restart(options = {}) {
929
1192
  const guard = (0, PlaybackGuard_1.playbackGuard)(this);
@@ -931,17 +1194,19 @@ class Player {
931
1194
  const run = (operation) => options[PlayerMigration_1.migrationRestart] ? operation() : this.commands.enqueue(operation);
932
1195
  if (this.destroyed)
933
1196
  return false;
934
- this.manager.emit("debug", `Moonlink.js > Player#restart -> Restarting player for guild ${this.guildId}`);
1197
+ this.manager.emit("debug", `NyxLink > Player#restart -> Restarting player for guild ${this.guildId}`);
935
1198
  this.manager.emit("playerResuming", this);
1199
+ if (this.destroyed || !guard.isCurrent(ticket))
1200
+ return false;
936
1201
  if (!this.voiceChannelId) {
937
- this.manager.emit("debug", `Moonlink.js > Player#restart >> Cannot restart player without a voiceChannelId for guild ${this.guildId}`);
1202
+ this.manager.emit("debug", `NyxLink > Player#restart >> Cannot restart player without a voiceChannelId for guild ${this.guildId}`);
938
1203
  return false;
939
1204
  }
940
1205
  try {
941
1206
  await this.connect();
942
1207
  }
943
1208
  catch (error) {
944
- this.manager.emit("debug", `Moonlink.js > Player#restart >> Voice connection failed for guild ${this.guildId}. Error: ${error.message}`);
1209
+ this.manager.emit("debug", `NyxLink > Player#restart >> Voice connection failed for guild ${this.guildId}. Error: ${error.message}`);
945
1210
  if (this.destroyed || !guard.isCurrent(ticket))
946
1211
  return false;
947
1212
  if (options.destroyOnFailure !== false)
@@ -955,34 +1220,30 @@ class Player {
955
1220
  const lastState = this.get("lastState");
956
1221
  const currentLavalinkPos = lastState?.position ?? 0;
957
1222
  const isResumedSync = this.node.resumed && this.playing && currentLavalinkPos > 0;
958
- const isAlreadySync = isResumedSync || (lastState?.connected && Math.abs(currentLavalinkPos - (this.current.position ?? 0)) < 2000);
1223
+ const isAlreadySync = !options[PlayerMigration_1.migrationRestart] && (isResumedSync || (lastState?.connected && Math.abs(currentLavalinkPos - (this.current.position ?? 0)) < 2000));
959
1224
  if (isAlreadySync && this.playing) {
960
- this.manager.emit("debug", `Moonlink.js > Player#restart >> Player already in sync for guild ${this.guildId}, skipping track restoration. (Resumed: ${this.node.resumed}, Sync: ${isAlreadySync})`);
1225
+ this.manager.emit("debug", `NyxLink > Player#restart >> Player already in sync for guild ${this.guildId}, skipping track restoration. (Resumed: ${this.node.resumed}, Sync: ${isAlreadySync})`);
961
1226
  this.manager.emit("playerResumed", this);
962
1227
  return true;
963
1228
  }
964
- const resumePosition = Math.max(typeof lastKnownPosition === "number" ? lastKnownPosition : 0, currentLavalinkPos, this.current.position ?? 0);
965
- this.manager.emit("debug", `Moonlink.js > Player#restart -> Restoring current track "${this.current.title}" for guild ${this.guildId} at ${resumePosition}ms. AlreadySync: ${isAlreadySync}`);
1229
+ const observed = this.current.position ?? 0;
1230
+ const resumePosition = options[PlayerMigration_1.migrationRestart] ? observed : Math.max(Number.isFinite(lastKnownPosition) ? lastKnownPosition : 0, Number.isFinite(currentLavalinkPos) ? currentLavalinkPos : 0, observed);
1231
+ this.manager.emit("debug", `NyxLink > Player#restart -> Restoring current track "${this.current.title}" for guild ${this.guildId} at ${resumePosition}ms. AlreadySync: ${isAlreadySync}`);
966
1232
  const payload = {
967
1233
  track: { encoded: this.current.encoded, userData: this.current.userData },
968
1234
  volume: this.volume,
969
1235
  playing: this.playing,
970
1236
  paused: this.paused,
971
- filters: this.filters.toPayload()
1237
+ filters: this.filters.toPayload({ compatibleOnly: true, suspended: options.suspendedFeatures })
972
1238
  };
973
- if (resumePosition > 0 && this.current.isSeekable && !isAlreadySync) {
1239
+ if (resumePosition > 0 && this.current.getInfo().isSeekable && !isAlreadySync) {
974
1240
  payload.position = resumePosition;
975
1241
  }
976
- if (this.audioTrackId) {
977
- payload.track.audioTrackId = this.audioTrackId;
978
- }
979
- if (this.fading)
980
- payload.fading = this.fading;
981
- if (this.nextTrack)
982
- payload.nextTrack = this.nextTrack;
983
- if (this.loudnessNormalizer !== undefined) {
984
- payload.loudnessNormalizer = this.loudnessNormalizer;
985
- }
1242
+ (0, AdvancedAudioRecovery_1.projectAdvancedAudio)(payload, this.node, {
1243
+ audioTrackId: this.audioTrackId, fading: this.fading, crossfade: this.crossfade,
1244
+ loudnessNormalizer: this.loudnessNormalizer,
1245
+ nextTrack: options[PlayerMigration_1.migrationRestart] ? undefined : this.queuePreload ? null : this.nextTrack
1246
+ }, options.suspendedFeatures);
986
1247
  const restored = await run(async () => {
987
1248
  if (this.destroyed || !guard.isCurrent(ticket))
988
1249
  return false;
@@ -995,7 +1256,7 @@ class Player {
995
1256
  return false;
996
1257
  }
997
1258
  else if (this.queue.size > 0 && options.startQueued !== false) {
998
- this.manager.emit("debug", `Moonlink.js > Player#restart -> No current track, playing first from queue for guild ${this.guildId}`);
1259
+ this.manager.emit("debug", `NyxLink > Player#restart -> No current track, playing first from queue for guild ${this.guildId}`);
999
1260
  if (!await run(async () => {
1000
1261
  if (!await this.restoreVoiceForRestart(ticket))
1001
1262
  return false;
@@ -1007,14 +1268,19 @@ class Player {
1007
1268
  if (options[PlayerMigration_1.migrationRestart]) {
1008
1269
  if (!await this.restoreVoiceForRestart(ticket))
1009
1270
  return false;
1010
- await this.sendPlayerUpdate({ filters: this.filters.toPayload(), volume: this.volume, paused: this.paused });
1271
+ const payload = { filters: this.filters.toPayload({ compatibleOnly: true, suspended: options.suspendedFeatures }), volume: this.volume, paused: this.paused };
1272
+ (0, AdvancedAudioRecovery_1.projectAdvancedAudio)(payload, this.node, {
1273
+ fading: this.fading, crossfade: this.crossfade, loudnessNormalizer: this.loudnessNormalizer
1274
+ }, options.suspendedFeatures);
1275
+ await this.sendPlayerUpdate(payload);
1011
1276
  if (this.destroyed || !guard.isCurrent(ticket))
1012
1277
  return false;
1013
1278
  }
1014
- this.manager.emit("debug", `Moonlink.js > Player#restart >> No track to restore and queue is empty for guild ${this.guildId}`);
1279
+ this.manager.emit("debug", `NyxLink > Player#restart >> No track to restore and queue is empty for guild ${this.guildId}`);
1015
1280
  return true;
1016
1281
  }
1017
- this.manager.emit("playerResumed", this);
1282
+ if (!options[PlayerMigration_1.migrationRestart])
1283
+ this.manager.emit("playerResumed", this);
1018
1284
  return true;
1019
1285
  }
1020
1286
  async restoreVoiceForRestart(ticket) {
@@ -1028,77 +1294,116 @@ class Player {
1028
1294
  }
1029
1295
  async transferNode(node) {
1030
1296
  const targetNode = typeof node === "string" ? this.manager.nodes.nodes.get(node) : node;
1031
- if (this.destroyed || !targetNode || !NodeSelector_1.NodeSelector.matches(targetNode, this.nodeSelection) || targetNode.identifier === this.node.identifier)
1297
+ if (this.destroyed || !targetNode || targetNode.manager !== this.manager || !NodeSelector_1.NodeSelector.matches(targetNode, this.nodeSelection) || targetNode.identifier === this.node.identifier)
1032
1298
  return false;
1299
+ this.node.cancelVoiceReconnect?.(this);
1033
1300
  const ticket = (0, PlaybackGuard_1.playbackGuard)(this).invalidate();
1034
1301
  return this.commands.enqueue(() => (0, PlayerMigration_1.migratePlayer)(this, targetNode, ticket));
1035
1302
  }
1036
1303
  setVoiceChannelId(voiceChannelId) {
1037
1304
  (0, Util_1.validate)(voiceChannelId, (v) => typeof v === "string" && v.length > 0, "Player#setVoiceChannelId > Voice channel ID must be a non-empty string.");
1038
1305
  if (this.voiceChannelId === voiceChannelId) {
1039
- this.manager.emit("debug", `Moonlink.js > Player#setVoiceChannelId >> Voice channel already set to ${voiceChannelId} for guild ${this.guildId}`);
1306
+ this.manager.emit("debug", `NyxLink > Player#setVoiceChannelId >> Voice channel already set to ${voiceChannelId} for guild ${this.guildId}`);
1040
1307
  return this;
1041
1308
  }
1309
+ this.node.cancelVoiceReconnect?.(this);
1042
1310
  const oldChannel = this.voiceChannelId;
1043
1311
  this.voiceChannelId = voiceChannelId;
1044
1312
  this.updateData("voiceChannelId", this.voiceChannelId);
1045
- this.manager.emit("debug", `Moonlink.js > Player#setVoiceChannel >> Voice channel changed from ${oldChannel} to ${voiceChannelId} for guild ${this.guildId}`);
1313
+ this.manager.emit("debug", `NyxLink > Player#setVoiceChannel >> Voice channel changed from ${oldChannel} to ${voiceChannelId} for guild ${this.guildId}`);
1046
1314
  this.manager.emit("playerVoiceChannelIdSet", this, oldChannel, voiceChannelId);
1047
1315
  return this;
1048
1316
  }
1049
1317
  setTextChannelId(textChannelId) {
1050
1318
  (0, Util_1.validate)(textChannelId, (v) => typeof v === "string" && v.length > 0, "Player#setTextChannelId > Text channel ID must be a non-empty string.");
1051
1319
  if (this.textChannelId === textChannelId) {
1052
- this.manager.emit("debug", `Moonlink.js > Player#setTextChannelId >> Text channel already set to ${textChannelId} for guild ${this.guildId}`);
1320
+ this.manager.emit("debug", `NyxLink > Player#setTextChannelId >> Text channel already set to ${textChannelId} for guild ${this.guildId}`);
1053
1321
  return this;
1054
1322
  }
1055
1323
  const oldChannel = this.textChannelId;
1056
1324
  this.textChannelId = textChannelId;
1057
1325
  this.updateData("textChannelId", this.textChannelId);
1058
- this.manager.emit("debug", `Moonlink.js > Player#setTextChannel >> Text channel changed from ${oldChannel} to ${textChannelId} for guild ${this.guildId}`);
1326
+ this.manager.emit("debug", `NyxLink > Player#setTextChannel >> Text channel changed from ${oldChannel} to ${textChannelId} for guild ${this.guildId}`);
1059
1327
  this.manager.emit("playerTextChannelIdSet", this, oldChannel, textChannelId);
1060
1328
  return this;
1061
1329
  }
1062
1330
  async replay() {
1063
- if (!this.current?.encoded) {
1064
- this.manager.emit("debug", `Moonlink.js > Player#replay >> No current track to replay for guild ${this.guildId}`);
1331
+ if (!this.current?.encoded || this.destroyed)
1065
1332
  return false;
1066
- }
1067
- this.manager.emit("debug", `Moonlink.js > Player#replay -> Replaying track "${this.current.title}" for guild ${this.guildId}`);
1068
- return await this.play({
1069
- track: this.current,
1070
- position: 0,
1333
+ const guard = (0, PlaybackGuard_1.playbackGuard)(this);
1334
+ const ticket = guard.invalidate();
1335
+ this.pendingPlayTicket = ticket;
1336
+ return this.commands.enqueue(async () => {
1337
+ if (this.destroyed || !guard.isCurrent(ticket))
1338
+ return false;
1339
+ const original = this.current;
1340
+ if (!original?.encoded)
1341
+ return false;
1342
+ const copy = new Track_1.Track(original.toJSON(), original.requester, original.origin, this.manager.options.trackPartial ?? []);
1343
+ let injectedTrackQueued = false;
1344
+ try {
1345
+ const played = await this.playNext({ track: copy, position: 0 }, ticket, () => true, queued => { injectedTrackQueued = queued; }, true);
1346
+ if (played)
1347
+ this.lastSuccessfulExplicitPlayTicket = ticket;
1348
+ return played;
1349
+ }
1350
+ finally {
1351
+ if (injectedTrackQueued) {
1352
+ const index = this.queue.tracks.indexOf(copy);
1353
+ if (index >= 0)
1354
+ this.queue.remove(index);
1355
+ }
1356
+ }
1357
+ }).finally(() => {
1358
+ if (this.pendingPlayTicket === ticket)
1359
+ this.pendingPlayTicket = undefined;
1071
1360
  });
1072
1361
  }
1073
1362
  async back() {
1074
- if (this.previous.length === 0) {
1075
- this.manager.emit("debug", `Moonlink.js > Player#back >> No previous tracks available for guild ${this.guildId}`);
1363
+ if (this.destroyed || this.previous.length === 0)
1076
1364
  return false;
1077
- }
1078
- const lastTrack = this.previous.pop();
1079
- if (!lastTrack) {
1080
- this.manager.emit("debug", `Moonlink.js > Player#back >> Popped an invalid track from history for guild ${this.guildId}`);
1081
- return false;
1082
- }
1083
- this.manager.emit("debug", `Moonlink.js > Player#back -> Going back to previous track "${lastTrack.title}" for guild ${this.guildId}`);
1084
- if (this.current) {
1085
- this.queue.unshift(this.current);
1086
- this.manager.emit("debug", `Moonlink.js > Player#back >> Pushed current track "${this.current.title}" to the front of the queue.`);
1087
- }
1088
- this.current = lastTrack;
1089
- this.set("isBackPlay", true);
1090
- const played = await this.play({
1091
- track: this.current,
1092
- position: 0
1365
+ const guard = (0, PlaybackGuard_1.playbackGuard)(this);
1366
+ const ticket = guard.invalidate();
1367
+ return this.commands.enqueue(async () => {
1368
+ if (this.destroyed || !guard.isCurrent(ticket))
1369
+ return false;
1370
+ const lastTrack = this.previous.at(-1);
1371
+ if (!lastTrack)
1372
+ return false;
1373
+ const outgoing = this.current;
1374
+ const priorBackFlag = this.get("isBackPlay") ?? false;
1375
+ const originalPreviousPosition = lastTrack.position;
1376
+ let injectedTrackQueued = false;
1377
+ let played = false;
1378
+ let committed = false;
1379
+ this.set("isBackPlay", true);
1380
+ try {
1381
+ played = await this.playNext({ track: lastTrack, position: 0 }, ticket, () => true, queued => { injectedTrackQueued = queued; });
1382
+ if (!played || !guard.isCurrent(ticket) || this.destroyed)
1383
+ return false;
1384
+ const index = this.previous.lastIndexOf(lastTrack);
1385
+ if (index >= 0) {
1386
+ this.previous.splice(index, 1);
1387
+ this.updateData("previous", this.previous.map(track => TrackCodec_1.TrackCodec.serialize(track)));
1388
+ }
1389
+ if (outgoing)
1390
+ this.queue.unshift(outgoing);
1391
+ committed = true;
1392
+ this.manager.emit("playerTriggeredBack", this, lastTrack);
1393
+ return true;
1394
+ }
1395
+ finally {
1396
+ if (injectedTrackQueued) {
1397
+ const index = this.queue.tracks.indexOf(lastTrack);
1398
+ if (index >= 0)
1399
+ this.queue.remove(index);
1400
+ }
1401
+ if (!committed) {
1402
+ lastTrack.position = originalPreviousPosition;
1403
+ this.set("isBackPlay", priorBackFlag);
1404
+ }
1405
+ }
1093
1406
  });
1094
- if (played) {
1095
- this.manager.emit("playerTriggeredBack", this, lastTrack);
1096
- this.manager.emit("debug", `Moonlink.js > Player#back >> Successfully went back for guild ${this.guildId}`);
1097
- }
1098
- else {
1099
- this.manager.emit("debug", `Moonlink.js > Player#back >> Failed to play previous track for guild ${this.guildId}.`);
1100
- }
1101
- return played;
1102
1407
  }
1103
1408
  }
1104
1409
  exports.Player = Player;