nyxlink 0.0.0-stage → 0.1.0-dev.1

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 (154) hide show
  1. package/LICENSE +172 -0
  2. package/README.md +72 -2
  3. package/assets/nyxlink_banner.png +0 -0
  4. package/dist/index.d.ts +41 -0
  5. package/dist/index.js +89 -0
  6. package/dist/index.js.map +1 -0
  7. package/dist/src/Util.d.ts +110 -0
  8. package/dist/src/Util.js +621 -0
  9. package/dist/src/Util.js.map +1 -0
  10. package/dist/src/autoplay/AutoPlayManager.d.ts +6 -0
  11. package/dist/src/autoplay/AutoPlayManager.js +36 -0
  12. package/dist/src/autoplay/AutoPlayManager.js.map +1 -0
  13. package/dist/src/autoplay/RecommendationResolver.d.ts +6 -0
  14. package/dist/src/autoplay/RecommendationResolver.js +115 -0
  15. package/dist/src/autoplay/RecommendationResolver.js.map +1 -0
  16. package/dist/src/backends/BackendAdapter.d.ts +13 -0
  17. package/dist/src/backends/BackendAdapter.js +25 -0
  18. package/dist/src/backends/BackendAdapter.js.map +1 -0
  19. package/dist/src/backends/BackendDetector.d.ts +4 -0
  20. package/dist/src/backends/BackendDetector.js +32 -0
  21. package/dist/src/backends/BackendDetector.js.map +1 -0
  22. package/dist/src/backends/LavalinkAdapter.d.ts +4 -0
  23. package/dist/src/backends/LavalinkAdapter.js +9 -0
  24. package/dist/src/backends/LavalinkAdapter.js.map +1 -0
  25. package/dist/src/backends/NodeLinkAdapter.d.ts +4 -0
  26. package/dist/src/backends/NodeLinkAdapter.js +9 -0
  27. package/dist/src/backends/NodeLinkAdapter.js.map +1 -0
  28. package/dist/src/connectors/Connector.d.ts +8 -0
  29. package/dist/src/connectors/Connector.js +11 -0
  30. package/dist/src/connectors/Connector.js.map +1 -0
  31. package/dist/src/connectors/DiscordJs.d.ts +10 -0
  32. package/dist/src/connectors/DiscordJs.js +49 -0
  33. package/dist/src/connectors/DiscordJs.js.map +1 -0
  34. package/dist/src/connectors/index.d.ts +4 -0
  35. package/dist/src/connectors/index.js +8 -0
  36. package/dist/src/connectors/index.js.map +1 -0
  37. package/dist/src/core/Manager.d.ts +44 -0
  38. package/dist/src/core/Manager.js +328 -0
  39. package/dist/src/core/Manager.js.map +1 -0
  40. package/dist/src/database/Local.d.ts +23 -0
  41. package/dist/src/database/Local.js +134 -0
  42. package/dist/src/database/Local.js.map +1 -0
  43. package/dist/src/database/Memory.d.ts +14 -0
  44. package/dist/src/database/Memory.js +86 -0
  45. package/dist/src/database/Memory.js.map +1 -0
  46. package/dist/src/database/StorageAdapter.d.ts +12 -0
  47. package/dist/src/database/StorageAdapter.js +3 -0
  48. package/dist/src/database/StorageAdapter.js.map +1 -0
  49. package/dist/src/entities/Filters.d.ts +72 -0
  50. package/dist/src/entities/Filters.js +559 -0
  51. package/dist/src/entities/Filters.js.map +1 -0
  52. package/dist/src/entities/Node.d.ts +243 -0
  53. package/dist/src/entities/Node.js +1257 -0
  54. package/dist/src/entities/Node.js.map +1 -0
  55. package/dist/src/entities/Player.d.ts +152 -0
  56. package/dist/src/entities/Player.js +1083 -0
  57. package/dist/src/entities/Player.js.map +1 -0
  58. package/dist/src/entities/Queue.d.ts +47 -0
  59. package/dist/src/entities/Queue.js +305 -0
  60. package/dist/src/entities/Queue.js.map +1 -0
  61. package/dist/src/entities/Rest.d.ts +83 -0
  62. package/dist/src/entities/Rest.js +428 -0
  63. package/dist/src/entities/Rest.js.map +1 -0
  64. package/dist/src/entities/Track.d.ts +33 -0
  65. package/dist/src/entities/Track.js +160 -0
  66. package/dist/src/entities/Track.js.map +1 -0
  67. package/dist/src/entities/Voice.d.ts +54 -0
  68. package/dist/src/entities/Voice.js +378 -0
  69. package/dist/src/entities/Voice.js.map +1 -0
  70. package/dist/src/entities/VoicePacketHandler.d.ts +4 -0
  71. package/dist/src/entities/VoicePacketHandler.js +33 -0
  72. package/dist/src/entities/VoicePacketHandler.js.map +1 -0
  73. package/dist/src/entities/VoiceReceiver.d.ts +42 -0
  74. package/dist/src/entities/VoiceReceiver.js +114 -0
  75. package/dist/src/entities/VoiceReceiver.js.map +1 -0
  76. package/dist/src/entities/YouTubeLiveChat.d.ts +54 -0
  77. package/dist/src/entities/YouTubeLiveChat.js +95 -0
  78. package/dist/src/entities/YouTubeLiveChat.js.map +1 -0
  79. package/dist/src/errors/FeatureUnavailableError.d.ts +7 -0
  80. package/dist/src/errors/FeatureUnavailableError.js +18 -0
  81. package/dist/src/errors/FeatureUnavailableError.js.map +1 -0
  82. package/dist/src/errors/HttpError.d.ts +6 -0
  83. package/dist/src/errors/HttpError.js +17 -0
  84. package/dist/src/errors/HttpError.js.map +1 -0
  85. package/dist/src/logging/Banner.d.ts +1 -0
  86. package/dist/src/logging/Banner.js +18 -0
  87. package/dist/src/logging/Banner.js.map +1 -0
  88. package/dist/src/logging/ConsoleReporter.d.ts +8 -0
  89. package/dist/src/logging/ConsoleReporter.js +25 -0
  90. package/dist/src/logging/ConsoleReporter.js.map +1 -0
  91. package/dist/src/logging/LogFormatter.d.ts +33 -0
  92. package/dist/src/logging/LogFormatter.js +146 -0
  93. package/dist/src/logging/LogFormatter.js.map +1 -0
  94. package/dist/src/logging/LogLevels.d.ts +3 -0
  95. package/dist/src/logging/LogLevels.js +26 -0
  96. package/dist/src/logging/LogLevels.js.map +1 -0
  97. package/dist/src/logging/Logger.d.ts +37 -0
  98. package/dist/src/logging/Logger.js +122 -0
  99. package/dist/src/logging/Logger.js.map +1 -0
  100. package/dist/src/logging/index.d.ts +8 -0
  101. package/dist/src/logging/index.js +16 -0
  102. package/dist/src/logging/index.js.map +1 -0
  103. package/dist/src/managers/DatabaseManager.d.ts +21 -0
  104. package/dist/src/managers/DatabaseManager.js +92 -0
  105. package/dist/src/managers/DatabaseManager.js.map +1 -0
  106. package/dist/src/managers/NodeManager.d.ts +21 -0
  107. package/dist/src/managers/NodeManager.js +106 -0
  108. package/dist/src/managers/NodeManager.js.map +1 -0
  109. package/dist/src/managers/PlayerManager.d.ts +22 -0
  110. package/dist/src/managers/PlayerManager.js +96 -0
  111. package/dist/src/managers/PlayerManager.js.map +1 -0
  112. package/dist/src/nodes/NodeFailover.d.ts +16 -0
  113. package/dist/src/nodes/NodeFailover.js +58 -0
  114. package/dist/src/nodes/NodeFailover.js.map +1 -0
  115. package/dist/src/nodes/NodeHealthMonitor.d.ts +12 -0
  116. package/dist/src/nodes/NodeHealthMonitor.js +33 -0
  117. package/dist/src/nodes/NodeHealthMonitor.js.map +1 -0
  118. package/dist/src/nodes/NodeSelector.d.ts +9 -0
  119. package/dist/src/nodes/NodeSelector.js +46 -0
  120. package/dist/src/nodes/NodeSelector.js.map +1 -0
  121. package/dist/src/players/PlaybackGuard.d.ts +11 -0
  122. package/dist/src/players/PlaybackGuard.js +25 -0
  123. package/dist/src/players/PlaybackGuard.js.map +1 -0
  124. package/dist/src/players/PlayerCommandQueue.d.ts +4 -0
  125. package/dist/src/players/PlayerCommandQueue.js +13 -0
  126. package/dist/src/players/PlayerCommandQueue.js.map +1 -0
  127. package/dist/src/search/SearchService.d.ts +14 -0
  128. package/dist/src/search/SearchService.js +143 -0
  129. package/dist/src/search/SearchService.js.map +1 -0
  130. package/dist/src/services/WebSocket.d.ts +40 -0
  131. package/dist/src/services/WebSocket.js +447 -0
  132. package/dist/src/services/WebSocket.js.map +1 -0
  133. package/dist/src/sources/deezer.d.ts +18 -0
  134. package/dist/src/sources/deezer.js +153 -0
  135. package/dist/src/sources/deezer.js.map +1 -0
  136. package/dist/src/sources/spotify.d.ts +35 -0
  137. package/dist/src/sources/spotify.js +239 -0
  138. package/dist/src/sources/spotify.js.map +1 -0
  139. package/dist/src/structures/SearchResult.d.ts +22 -0
  140. package/dist/src/structures/SearchResult.js +64 -0
  141. package/dist/src/structures/SearchResult.js.map +1 -0
  142. package/dist/src/tracks/TrackCodec.d.ts +17 -0
  143. package/dist/src/tracks/TrackCodec.js +25 -0
  144. package/dist/src/tracks/TrackCodec.js.map +1 -0
  145. package/dist/src/tracks/TrackResolver.d.ts +9 -0
  146. package/dist/src/tracks/TrackResolver.js +41 -0
  147. package/dist/src/tracks/TrackResolver.js.map +1 -0
  148. package/dist/src/typings/Interfaces.d.ts +561 -0
  149. package/dist/src/typings/Interfaces.js +3 -0
  150. package/dist/src/typings/Interfaces.js.map +1 -0
  151. package/dist/src/typings/types.d.ts +65 -0
  152. package/dist/src/typings/types.js +28 -0
  153. package/dist/src/typings/types.js.map +1 -0
  154. package/package.json +68 -4
@@ -0,0 +1,1083 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Player = void 0;
4
+ const PlayerCommandQueue_1 = require("../players/PlayerCommandQueue");
5
+ const PlaybackGuard_1 = require("../players/PlaybackGuard");
6
+ const Util_1 = require("../Util");
7
+ const Voice_1 = require("./Voice");
8
+ const Track_1 = require("./Track");
9
+ const TrackCodec_1 = require("../tracks/TrackCodec");
10
+ const TrackResolver_1 = require("../tracks/TrackResolver");
11
+ const VoiceReceiver_1 = require("./VoiceReceiver");
12
+ class Player {
13
+ manager;
14
+ node;
15
+ guildId;
16
+ queue;
17
+ filters;
18
+ voice;
19
+ data = {};
20
+ voiceChannelId;
21
+ textChannelId;
22
+ playing = false;
23
+ paused = false;
24
+ connected = false;
25
+ destroyed = false;
26
+ volume = 100;
27
+ loop = "off";
28
+ loopCount;
29
+ autoPlay = false;
30
+ autoLeave = false;
31
+ ping = -1;
32
+ isResuming = false;
33
+ current = null;
34
+ previous = [];
35
+ recommendations = [];
36
+ historySize = 10;
37
+ lastActivityTime = Date.now();
38
+ commands = new PlayerCommandQueue_1.PlayerCommandQueue();
39
+ destructionPromise;
40
+ volumeRevision = 0;
41
+ optimisticVolumeRevision = 0;
42
+ fading;
43
+ nextTrack;
44
+ audioTrackId;
45
+ loudnessNormalizer;
46
+ endTime;
47
+ healthCheckTimer;
48
+ lastPosition = 0;
49
+ lastPositionTime = Date.now();
50
+ stuckDetectionCount = 0;
51
+ silentDetectionCount = 0;
52
+ resumeDebounceTimer;
53
+ isResumeInProgress = false;
54
+ lastResumeAttempt = 0;
55
+ constructor(manager, node, config) {
56
+ this.manager = manager;
57
+ this.node = node;
58
+ this.guildId = config.guildId;
59
+ this.voiceChannelId = config.voiceChannelId;
60
+ this.textChannelId = config.textChannelId || config.voiceChannelId;
61
+ this.volume = config.volume ?? this.manager.options.defaultPlayer?.volume ?? 100;
62
+ this.set("selfDeaf", config.selfDeaf ?? this.manager.options.defaultPlayer?.selfDeaf ?? true);
63
+ this.set("selfMute", config.selfMute ?? this.manager.options.defaultPlayer?.selfMute ?? false);
64
+ this.autoPlay = config.autoPlay ?? this.manager.options.defaultPlayer?.autoPlay ?? false;
65
+ this.autoLeave = config.autoLeave ?? this.manager.options.defaultPlayer?.autoLeave ?? false;
66
+ this.loop = config.loop ?? this.manager.options.defaultPlayer?.loop ?? "off";
67
+ this.loopCount = config.loopCount;
68
+ this.historySize = this.manager.options.defaultPlayer?.historySize ?? 10;
69
+ this.queue = new (Util_1.Structure.get("Queue"))(this);
70
+ this.filters = new (Util_1.Structure.get("Filters"))(this);
71
+ this.voice = new Voice_1.Voice(this);
72
+ if (config.current) {
73
+ this.current = TrackCodec_1.TrackCodec.restore(config.current);
74
+ if (config.current.position) {
75
+ this.current.position = config.current.position;
76
+ this.lastPosition = this.current.position;
77
+ }
78
+ }
79
+ if (config.queue && Array.isArray(config.queue)) {
80
+ for (const track of config.queue) {
81
+ this.queue.add(TrackCodec_1.TrackCodec.restore(track));
82
+ }
83
+ }
84
+ if (config.previous && Array.isArray(config.previous)) {
85
+ for (const track of config.previous) {
86
+ this.previous.push(TrackCodec_1.TrackCodec.restore(track));
87
+ }
88
+ }
89
+ 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}`);
90
+ this.startHealthCheck();
91
+ }
92
+ startHealthCheck() {
93
+ this.stopHealthCheck();
94
+ const interval = this.manager.options.playerHealth?.checkInterval ?? 30000;
95
+ this.healthCheckTimer = setInterval(() => {
96
+ this.performHealthCheck();
97
+ }, interval);
98
+ }
99
+ stopHealthCheck() {
100
+ if (this.healthCheckTimer) {
101
+ clearInterval(this.healthCheckTimer);
102
+ this.healthCheckTimer = undefined;
103
+ }
104
+ }
105
+ async performHealthCheck() {
106
+ if (this.destroyed || !this.connected)
107
+ return;
108
+ const now = Date.now();
109
+ const silenceTimeout = this.manager.options.playerHealth?.silenceTimeout ?? 120000;
110
+ const maxStuckCount = this.manager.options.playerHealth?.maxStuckCount ?? 3;
111
+ const maxSilentCount = this.manager.options.playerHealth?.maxSilentCount ?? 2;
112
+ if (this.playing && !this.paused && this.current) {
113
+ const currentPosition = this.current.position ?? 0;
114
+ const positionDelta = Math.abs(currentPosition - this.lastPosition);
115
+ const timeDelta = now - this.lastPositionTime;
116
+ if (positionDelta < 1000 && timeDelta > 30000 && !this.current.isStream) {
117
+ this.stuckDetectionCount++;
118
+ this.manager.emit("debug", `Moonlink.js > Player#healthCheck >> Player ${this.guildId} appears stuck. Position: ${currentPosition}, Delta: ${positionDelta}, Stuck count: ${this.stuckDetectionCount}/${maxStuckCount}`);
119
+ if (this.stuckDetectionCount >= maxStuckCount) {
120
+ this.manager.emit("debug", `Moonlink.js > Player#healthCheck >> Player ${this.guildId} stuck for too long, attempting recovery.`);
121
+ await this.recoverFromStuck();
122
+ this.stuckDetectionCount = 0;
123
+ return;
124
+ }
125
+ }
126
+ else {
127
+ if (this.stuckDetectionCount > 0) {
128
+ this.manager.emit("debug", `Moonlink.js > Player#healthCheck >> Player ${this.guildId} position advanced (Delta: ${positionDelta}). Resetting stuck count.`);
129
+ }
130
+ this.stuckDetectionCount = 0;
131
+ }
132
+ const activityDelta = now - this.lastActivityTime;
133
+ if (activityDelta > silenceTimeout) {
134
+ this.silentDetectionCount++;
135
+ this.manager.emit("debug", `Moonlink.js > Player#healthCheck >> Player ${this.guildId} silent for ${Math.round(activityDelta / 1000)}s. Silent count: ${this.silentDetectionCount}/${maxSilentCount}`);
136
+ if (this.silentDetectionCount >= maxSilentCount) {
137
+ this.manager.emit("debug", `Moonlink.js > Player#healthCheck >> Player ${this.guildId} silent for too long, attempting soft restart.`);
138
+ await this.softRestart("Silent player detected");
139
+ this.silentDetectionCount = 0;
140
+ return;
141
+ }
142
+ }
143
+ else {
144
+ this.silentDetectionCount = 0;
145
+ }
146
+ this.lastPosition = currentPosition;
147
+ this.lastPositionTime = now;
148
+ }
149
+ else {
150
+ this.stuckDetectionCount = 0;
151
+ this.silentDetectionCount = 0;
152
+ }
153
+ }
154
+ async recoverFromStuck() {
155
+ if (this.destroyed)
156
+ return;
157
+ let ticket = (0, PlaybackGuard_1.playbackGuard)(this).ticket;
158
+ this.manager.emit("playerRecoveryStarted", this);
159
+ try {
160
+ if (this.current && this.current.isSeekable) {
161
+ const seekPos = Math.max(0, (this.current.position ?? 0) + 2000);
162
+ this.manager.emit("debug", `Moonlink.js > Player#recoverFromStuck >> Seeking forward 2s for player ${this.guildId}.`);
163
+ await this.seek(seekPos);
164
+ }
165
+ else {
166
+ const restoring = this.softRestart("Stuck player recovery");
167
+ ticket = (0, PlaybackGuard_1.playbackGuard)(this).ticket;
168
+ if (!await restoring) {
169
+ throw new Error("Soft restart did not restore playback");
170
+ }
171
+ }
172
+ if (this.destroyed || !(0, PlaybackGuard_1.playbackGuard)(this).isCurrent(ticket))
173
+ return;
174
+ this.manager.emit("playerRecoverySuccess", this);
175
+ }
176
+ catch (error) {
177
+ this.manager.emit("debug", `Moonlink.js > Player#recoverFromStuck >> Recovery failed: ${error.message}`);
178
+ this.manager.emit("playerRecoveryFailed", this);
179
+ }
180
+ }
181
+ async softRestart(reason) {
182
+ if (this.destroyed)
183
+ return false;
184
+ this.manager.emit("debug", `Moonlink.js > Player#softRestart >> Soft restart triggered for player ${this.guildId}. Reason: ${reason}`);
185
+ const currentTrack = this.current;
186
+ const currentPosition = currentTrack?.position ?? 0;
187
+ const wasPaused = this.paused;
188
+ if (!currentTrack) {
189
+ this.manager.emit("debug", `Moonlink.js > Player#softRestart >> No current track, skipping soft restart for player ${this.guildId}.`);
190
+ return false;
191
+ }
192
+ try {
193
+ const stopping = this.stop();
194
+ const ticket = (0, PlaybackGuard_1.playbackGuard)(this).ticket;
195
+ await stopping;
196
+ if (this.destroyed || !(0, PlaybackGuard_1.playbackGuard)(this).isCurrent(ticket))
197
+ return false;
198
+ await new Promise(resolve => setTimeout(resolve, 500));
199
+ if (this.destroyed || !(0, PlaybackGuard_1.playbackGuard)(this).isCurrent(ticket))
200
+ return false;
201
+ if (this.voice.sessionId && this.voice.token && this.voice.endpoint) {
202
+ const voicePayload = {
203
+ sessionId: this.voice.sessionId,
204
+ token: this.voice.token,
205
+ endpoint: this.voice.endpoint
206
+ };
207
+ if (this.node.isNodeLink) {
208
+ voicePayload.channelId = this.voiceChannelId;
209
+ }
210
+ await this.updatePlayer({ voice: voicePayload }, true);
211
+ }
212
+ if (this.destroyed || !(0, PlaybackGuard_1.playbackGuard)(this).isCurrent(ticket))
213
+ return false;
214
+ const restored = await this.commands.enqueue(() => this.playNext({
215
+ track: currentTrack,
216
+ position: currentPosition,
217
+ noReplace: false
218
+ }, ticket));
219
+ if (!restored)
220
+ return false;
221
+ if (this.destroyed || !(0, PlaybackGuard_1.playbackGuard)(this).isCurrent(ticket))
222
+ return false;
223
+ if (wasPaused) {
224
+ await this.pause();
225
+ }
226
+ if (this.destroyed || !(0, PlaybackGuard_1.playbackGuard)(this).isCurrent(ticket))
227
+ return false;
228
+ this.stuckDetectionCount = 0;
229
+ this.silentDetectionCount = 0;
230
+ this.lastPosition = currentPosition;
231
+ this.lastPositionTime = Date.now();
232
+ this.updateActivity();
233
+ this.manager.emit("debug", `Moonlink.js > Player#softRestart >> Soft restart completed for player ${this.guildId}.`);
234
+ return true;
235
+ }
236
+ catch (error) {
237
+ this.manager.emit("debug", `Moonlink.js > Player#softRestart >> Soft restart failed: ${error.message}`);
238
+ return false;
239
+ }
240
+ }
241
+ updateActivity() {
242
+ this.lastActivityTime = Date.now();
243
+ }
244
+ set(key, value) {
245
+ this.data[key] = value;
246
+ return this;
247
+ }
248
+ get(key) {
249
+ return this.data[key];
250
+ }
251
+ updateData(path, data) {
252
+ const dbPath = `players.${this.guildId}${path ? `.${path}` : ''}`;
253
+ const operation = this.manager.database.set(dbPath, data);
254
+ void operation.catch(error => this.manager.emit('debug', `NyxLink > Storage > Write failed for ${dbPath}: ${error.message}`));
255
+ return operation;
256
+ }
257
+ assertNodeLinkFeature(feature) {
258
+ this.node.assertFeature(feature);
259
+ }
260
+ resolveEncodedTrack(track) {
261
+ if (track instanceof Track_1.Track)
262
+ return track.encoded;
263
+ if (typeof track === "string" && track.length > 0)
264
+ return track;
265
+ throw new Error("Invalid track input. Provide a Track instance or encoded string.");
266
+ }
267
+ async sendPlayerUpdate(payload, noReplace) {
268
+ const hasNodeLinkExtras = Boolean(payload?.fading ||
269
+ payload?.nextTrack ||
270
+ payload?.track?.audioTrackId ||
271
+ payload?.loudnessNormalizer !== undefined ||
272
+ payload?.endTime !== undefined);
273
+ if (!this.node.isNodeLink && hasNodeLinkExtras) {
274
+ throw (0, Util_1.nodeLinkOnlyError)("updatePlayer extras");
275
+ }
276
+ const finalPayload = { ...payload };
277
+ if (payload.voice) {
278
+ const voicePayload = { ...payload.voice };
279
+ if (this.node.isNodeLink && (!voicePayload.sessionId || !voicePayload.token || !voicePayload.endpoint)) {
280
+ throw new Error("voice payload requires sessionId, token, and endpoint.");
281
+ }
282
+ if (!voicePayload.channelId && this.voiceChannelId) {
283
+ voicePayload.channelId = this.voiceChannelId;
284
+ }
285
+ finalPayload.voice = voicePayload;
286
+ }
287
+ const response = await this.node.rest.updatePlayer(this.guildId, finalPayload, noReplace);
288
+ if (response == null)
289
+ throw new Error("Backend did not acknowledge player update");
290
+ return response;
291
+ }
292
+ async updatePlayer(payload, noReplace) {
293
+ return this.commands.enqueue(() => {
294
+ if (this.destroyed)
295
+ throw new Error("Cannot update a destroyed player");
296
+ return this.sendPlayerUpdate(payload, noReplace);
297
+ });
298
+ }
299
+ async updateVoice(voice) {
300
+ if (this.destroyed)
301
+ throw new Error("Cannot update voice on a destroyed player");
302
+ return this.sendPlayerUpdate({ voice }, true);
303
+ }
304
+ async connect({ selfDeaf, selfMute } = {}) {
305
+ const connectStack = new Error().stack?.split("\n").slice(2, 8).join("\n");
306
+ this.manager.emit("debug", `Moonlink.js > Player#connect -> Connect requested for guild ${this.guildId}. Stack: ${connectStack || "unavailable"}`);
307
+ this.set("userInitiatedConnect", true);
308
+ if (selfDeaf !== undefined)
309
+ this.set("selfDeaf", selfDeaf);
310
+ if (selfMute !== undefined)
311
+ this.set("selfMute", selfMute);
312
+ await this.voice.connect({ selfDeaf: this.get("selfDeaf") ?? true, selfMute: this.get("selfMute") ?? false });
313
+ return this;
314
+ }
315
+ async disconnect() {
316
+ const disconnectStack = new Error().stack?.split("\n").slice(2, 8).join("\n");
317
+ this.manager.emit("debug", `Moonlink.js > Player#disconnect -> Disconnect requested for guild ${this.guildId}. Stack: ${disconnectStack || "unavailable"}`);
318
+ this.set("userInitiatedConnect", false);
319
+ await this.voice.disconnect();
320
+ return this;
321
+ }
322
+ async play(options = {}) {
323
+ const ticket = (0, PlaybackGuard_1.playbackGuard)(this).invalidate();
324
+ return this.commands.enqueue(() => this.playNext(options, ticket));
325
+ }
326
+ async playAutoPlay(track, ticket, automaticTicket) {
327
+ return this.commands.enqueue(() => this.playNext({ track }, ticket, () => this.autoPlay && (0, PlaybackGuard_1.playbackGuard)(this).isAutoCurrent(automaticTicket)));
328
+ }
329
+ async playNext(options, ticket, allowed = () => true) {
330
+ const guard = (0, PlaybackGuard_1.playbackGuard)(this);
331
+ if (this.destroyed || !guard.isCurrent(ticket) || !allowed())
332
+ return false;
333
+ this.recommendations = [];
334
+ let finalOptions;
335
+ if (options instanceof Track_1.Track) {
336
+ finalOptions = { track: options };
337
+ }
338
+ else if ('encoded' in options && 'info' in options) {
339
+ finalOptions = { track: options };
340
+ }
341
+ else {
342
+ finalOptions = options;
343
+ }
344
+ this.manager.emit("debug", `Moonlink.js > Player#play -> play() called for guild ${this.guildId} with options: ${JSON.stringify(options)}`);
345
+ if (!this.voice.sessionId || !this.voice.endpoint) {
346
+ this.manager.emit("debug", `Moonlink.js > Player#play >> Voice not ready for guild ${this.guildId}, attempting to connect...`);
347
+ try {
348
+ await this.connect();
349
+ }
350
+ catch (e) {
351
+ this.manager.emit("debug", `Moonlink.js > Player#play >> Failed to connect voice: ${e}`);
352
+ return false;
353
+ }
354
+ }
355
+ if (!guard.isCurrent(ticket) || this.destroyed || !allowed())
356
+ return false;
357
+ let track = finalOptions.track;
358
+ if (finalOptions.encoded) {
359
+ try {
360
+ const decoded = (0, Util_1.decodeTrack)(finalOptions.encoded);
361
+ track = new Track_1.Track(decoded, finalOptions.requester);
362
+ }
363
+ catch (e) {
364
+ this.manager.emit("debug", `Moonlink.js > Player#play >> Error decoding track for guild ${this.guildId}. Error: ${e}`);
365
+ return false;
366
+ }
367
+ }
368
+ if (track && !(track instanceof Track_1.Track)) {
369
+ try {
370
+ track = new Track_1.Track(track, finalOptions.requester);
371
+ }
372
+ catch (e) {
373
+ this.manager.emit("debug", `Moonlink.js > Player#play >> Invalid track object for guild ${this.guildId}. Error: ${e}`);
374
+ return false;
375
+ }
376
+ }
377
+ if (track) {
378
+ this.queue.unshift(track);
379
+ this.manager.emit("debug", `Moonlink.js > Player#play >> Added track "${track.title}" to front of queue for guild ${this.guildId}`);
380
+ }
381
+ if (this.queue.size === 0) {
382
+ this.manager.emit("debug", `Moonlink.js > Player#play >> Queue is empty, cannot start playback for guild ${this.guildId}`);
383
+ return false;
384
+ }
385
+ const previousTrack = this.current;
386
+ const queuedTrack = this.queue.first;
387
+ let nextTrack = queuedTrack;
388
+ if (!nextTrack || !nextTrack.encoded) {
389
+ this.manager.emit("debug", `Moonlink.js > Player#play >> Invalid track data for guild ${this.guildId}. Next track is ${JSON.stringify(nextTrack)}`);
390
+ return false;
391
+ }
392
+ try {
393
+ nextTrack = await TrackResolver_1.TrackResolver.resolve(nextTrack, this.node);
394
+ }
395
+ catch (error) {
396
+ this.manager.emit('debug', `NyxLink > TrackResolver > ${error.message}`);
397
+ return false;
398
+ }
399
+ if (this.destroyed || !guard.isCurrent(ticket) || !allowed() || this.queue.first !== queuedTrack)
400
+ return false;
401
+ this.queue.shift();
402
+ const oldTrackTitle = this.current?.title ?? "null";
403
+ this.current = nextTrack instanceof Track_1.Track ? nextTrack : new Track_1.Track(nextTrack);
404
+ this.current.position = finalOptions.position || 0;
405
+ this.updateData("current", TrackCodec_1.TrackCodec.serialize(this.current));
406
+ this.manager.emit("debug", `Moonlink.js > Player#play >> Player state changed: current track: ${oldTrackTitle} -> ${this.current.title}`);
407
+ const oldPlaying = this.playing;
408
+ const oldPaused = this.paused;
409
+ this.playing = true;
410
+ this.paused = false;
411
+ this.updateData("playing", this.playing);
412
+ this.updateData("paused", this.paused);
413
+ const audioTrackId = finalOptions.audioTrackId ?? this.audioTrackId;
414
+ const payload = {
415
+ track: {
416
+ encoded: this.current.encoded,
417
+ userData: this.current.userData
418
+ },
419
+ position: finalOptions.position || this.current.position,
420
+ volume: this.volume
421
+ };
422
+ if (audioTrackId) {
423
+ payload.track.audioTrackId = audioTrackId;
424
+ }
425
+ if (this.fading)
426
+ payload.fading = this.fading;
427
+ if (this.nextTrack)
428
+ payload.nextTrack = this.nextTrack;
429
+ if (this.loudnessNormalizer !== undefined) {
430
+ payload.loudnessNormalizer = this.loudnessNormalizer;
431
+ }
432
+ this.manager.emit("playerTriggeredPlay", this, this.current);
433
+ this.manager.emit("debug", `Moonlink.js > Player#play -> Sending play request to node ${this.node.identifier} for guild ${this.guildId}. Payload: ${JSON.stringify(payload)}`);
434
+ try {
435
+ const response = await this.sendPlayerUpdate(payload, finalOptions.noReplace ?? this.manager.options.noReplace);
436
+ if (response == null)
437
+ throw new Error("Backend did not acknowledge playback");
438
+ if (!guard.isCurrent(ticket) || this.destroyed)
439
+ return false;
440
+ this.manager.emit("debug", `Moonlink.js > Player#play >> Successfully sent play request for track "${this.current.title}" for guild ${this.guildId}`);
441
+ }
442
+ catch (e) {
443
+ this.manager.emit("debug", `Moonlink.js > Player#play >> CRITICAL: Failed to send play request for guild ${this.guildId}. Reverting state. Error: ${e.message}`);
444
+ this.playing = oldPlaying;
445
+ this.paused = oldPaused;
446
+ this.current = previousTrack;
447
+ this.queue.unshift(nextTrack);
448
+ return false;
449
+ }
450
+ if (previousTrack && !this.get("isBackPlay")) {
451
+ this.previous.push(previousTrack);
452
+ const historyLimit = this.manager.options.queue?.historyLimit ?? this.historySize;
453
+ if (this.previous.length > historyLimit) {
454
+ this.previous.shift();
455
+ }
456
+ this.updateData("previous", this.previous.map(t => TrackCodec_1.TrackCodec.serialize(t)));
457
+ this.manager.emit("debug", `Moonlink.js > Player#play << Added track "${previousTrack.title}" to history for guild ${this.guildId}. History size: ${this.previous.length}`);
458
+ }
459
+ this.set("isBackPlay", false);
460
+ this.playing = true;
461
+ this.paused = false;
462
+ this.manager.emit("debug", `Moonlink.js > Player#play >> Player state changed: playing: ${oldPlaying} -> ${this.playing}, paused: ${oldPaused} -> ${this.paused}`);
463
+ this.node.updateRecommendations(this).catch(() => { });
464
+ return true;
465
+ }
466
+ async addMix(track, options) {
467
+ this.assertNodeLinkFeature("mix:add");
468
+ const encoded = this.resolveEncodedTrack(track);
469
+ return this.node.rest.addMixLayer(this.guildId, {
470
+ track: { encoded, userData: options?.userData },
471
+ volume: options?.volume
472
+ });
473
+ }
474
+ async getMixes() {
475
+ this.assertNodeLinkFeature("mix:list");
476
+ return this.node.rest.getMixLayers(this.guildId);
477
+ }
478
+ async updateMixVolume(mixId, volume) {
479
+ this.assertNodeLinkFeature("mix:update");
480
+ await this.node.rest.updateMixLayerVolume(this.guildId, mixId, volume);
481
+ return this;
482
+ }
483
+ async removeMix(mixId) {
484
+ this.assertNodeLinkFeature("mix:remove");
485
+ await this.node.rest.removeMixLayer(this.guildId, mixId);
486
+ return this;
487
+ }
488
+ async subscribeLyrics(options) {
489
+ this.assertNodeLinkFeature("lyrics:subscribe");
490
+ await this.node.rest.subscribeLyrics(this.guildId, options?.skipTrackSource);
491
+ return this;
492
+ }
493
+ async unsubscribeLyrics() {
494
+ this.assertNodeLinkFeature("lyrics:unsubscribe");
495
+ await this.node.rest.unsubscribeLyrics(this.guildId);
496
+ return this;
497
+ }
498
+ async loadChapters(encodedTrack) {
499
+ this.assertNodeLinkFeature("chapters");
500
+ const target = encodedTrack ?? this.current?.encoded;
501
+ if (!target) {
502
+ throw new Error("loadChapters requires an encoded track or an active player track.");
503
+ }
504
+ return this.node.rest.loadChapters(target);
505
+ }
506
+ async loadMeaning(encodedTrack, lang) {
507
+ this.assertNodeLinkFeature("meaning");
508
+ const target = encodedTrack ?? this.current?.encoded;
509
+ if (!target) {
510
+ throw new Error("loadMeaning requires an encoded track or an active player track.");
511
+ }
512
+ return this.node.rest.loadMeaning(target, lang);
513
+ }
514
+ async getLoadDirectStream(options) {
515
+ this.assertNodeLinkFeature("loadstream");
516
+ const target = this.current?.encoded;
517
+ if (!target) {
518
+ throw new Error("getLoadDirectStream requires an active player track.");
519
+ }
520
+ return this.node.loadDirectStream(target, options?.volume, options?.position, options?.filters);
521
+ }
522
+ async getDirectStream(itag) {
523
+ this.assertNodeLinkFeature("trackstream");
524
+ const target = this.current?.encoded;
525
+ if (!target) {
526
+ throw new Error("getDirectStream requires an active player track.");
527
+ }
528
+ return this.node.getDirectStream(target, itag);
529
+ }
530
+ async setFading(fading) {
531
+ this.assertNodeLinkFeature("fading");
532
+ this.fading = fading;
533
+ await this.sendPlayerUpdate({ fading });
534
+ return this;
535
+ }
536
+ async clearFading() {
537
+ this.assertNodeLinkFeature("fading");
538
+ this.fading = undefined;
539
+ await this.sendPlayerUpdate({ fading: { enabled: false } });
540
+ return this;
541
+ }
542
+ async setNextTrack(track, userData) {
543
+ this.assertNodeLinkFeature("nextTrack");
544
+ const encoded = this.resolveEncodedTrack(track);
545
+ this.nextTrack = { encoded, userData };
546
+ await this.sendPlayerUpdate({ nextTrack: this.nextTrack });
547
+ return this;
548
+ }
549
+ async clearNextTrack() {
550
+ this.assertNodeLinkFeature("nextTrack");
551
+ this.nextTrack = undefined;
552
+ await this.sendPlayerUpdate({ nextTrack: null });
553
+ return this;
554
+ }
555
+ setAudioTrackId(audioTrackId) {
556
+ this.assertNodeLinkFeature("audioTrackId");
557
+ this.audioTrackId = audioTrackId;
558
+ return this;
559
+ }
560
+ async setLoudnessNormalizer(enabled) {
561
+ this.assertNodeLinkFeature("loudnessNormalizer");
562
+ this.loudnessNormalizer = enabled;
563
+ await this.sendPlayerUpdate({ loudnessNormalizer: enabled });
564
+ return this;
565
+ }
566
+ createVoiceReceiver(options) {
567
+ this.assertNodeLinkFeature("voiceReceive");
568
+ return new VoiceReceiver_1.VoiceReceiver(this.node, this.guildId, options);
569
+ }
570
+ async pause() {
571
+ return this.commands.enqueue(() => this.pausePlayback());
572
+ }
573
+ async pausePlayback() {
574
+ if (this.destroyed)
575
+ return this;
576
+ if (this.paused) {
577
+ this.manager.emit("debug", `Moonlink.js > Player#pause >> Player is already paused for guild ${this.guildId}`);
578
+ return this;
579
+ }
580
+ this.manager.emit("debug", `Moonlink.js > Player#pause -> Sending pause request to node ${this.node.identifier} for guild ${this.guildId}`);
581
+ this.manager.emit("playerTriggeredPause", this);
582
+ await this.sendPlayerUpdate({ paused: true });
583
+ const oldPaused = this.paused;
584
+ this.paused = true;
585
+ this.updateData("paused", this.paused);
586
+ this.manager.emit("debug", `Moonlink.js > Player#pause >> Player state changed: paused: ${oldPaused} -> ${this.paused}`);
587
+ this.manager.emit("debug", `Moonlink.js > Player#pause >> Player paused for guild ${this.guildId}`);
588
+ return this;
589
+ }
590
+ async resume(options) {
591
+ const pending = this.commands.enqueue(() => this.resumePlayback());
592
+ if (!options?.timeout)
593
+ return pending;
594
+ let timer;
595
+ try {
596
+ return await Promise.race([
597
+ pending,
598
+ new Promise((_, reject) => {
599
+ timer = setTimeout(() => reject(new Error("Resume timed out")), options.timeout);
600
+ })
601
+ ]);
602
+ }
603
+ finally {
604
+ clearTimeout(timer);
605
+ }
606
+ }
607
+ async resumePlayback() {
608
+ if (this.destroyed)
609
+ return this;
610
+ const now = Date.now();
611
+ const minResumeInterval = this.manager.options.playerHealth?.resumeDebounce ?? 1000;
612
+ if (this.isResumeInProgress) {
613
+ this.manager.emit("debug", `Moonlink.js > Player#resume >> Resume already in progress for guild ${this.guildId}, skipping.`);
614
+ return this;
615
+ }
616
+ if (now - this.lastResumeAttempt < minResumeInterval) {
617
+ this.manager.emit("debug", `Moonlink.js > Player#resume >> Resume debounced for guild ${this.guildId} (last attempt ${now - this.lastResumeAttempt}ms ago).`);
618
+ return this;
619
+ }
620
+ this.updateActivity();
621
+ if (!this.paused) {
622
+ this.manager.emit("debug", `Moonlink.js > Player#resume >> Player is not paused for guild ${this.guildId}`);
623
+ return this;
624
+ }
625
+ this.isResumeInProgress = true;
626
+ this.lastResumeAttempt = now;
627
+ this.manager.emit("debug", `Moonlink.js > Player#resume -> Sending resume request to node ${this.node.identifier} for guild ${this.guildId}`);
628
+ this.manager.emit("playerTriggeredResume", this);
629
+ try {
630
+ await this.sendPlayerUpdate({ paused: false });
631
+ const oldPaused = this.paused;
632
+ this.paused = false;
633
+ this.updateData("paused", this.paused);
634
+ this.manager.emit("debug", `Moonlink.js > Player#resume >> Player state changed: paused: ${oldPaused} -> ${this.paused}`);
635
+ this.manager.emit("debug", `Moonlink.js > Player#resume >> Player resumed for guild ${this.guildId}`);
636
+ }
637
+ finally {
638
+ this.isResumeInProgress = false;
639
+ }
640
+ return this;
641
+ }
642
+ async forward(ms) {
643
+ if (!this.current)
644
+ return this;
645
+ const newPosition = Math.min(this.current.duration, this.current.position + ms);
646
+ return this.seek(newPosition);
647
+ }
648
+ async rewind(ms) {
649
+ if (!this.current)
650
+ return this;
651
+ const newPosition = Math.max(0, this.current.position - ms);
652
+ return this.seek(newPosition);
653
+ }
654
+ async setVoiceState(state) {
655
+ if (state.channelId) {
656
+ this.setVoiceChannelId(state.channelId);
657
+ }
658
+ const selfMute = state.selfMute ?? this.get("selfMute");
659
+ const selfDeaf = state.selfDeaf ?? this.get("selfDeaf");
660
+ this.set("selfMute", selfMute);
661
+ this.set("selfDeaf", selfDeaf);
662
+ await this.connect({ selfMute, selfDeaf });
663
+ return this;
664
+ }
665
+ async toggleMute() {
666
+ return this.setVoiceState({ selfMute: !this.get("selfMute") });
667
+ }
668
+ async toggleDeaf() {
669
+ return this.setVoiceState({ selfDeaf: !this.get("selfDeaf") });
670
+ }
671
+ async search(query, source) {
672
+ return this.manager.search({
673
+ query,
674
+ source,
675
+ node: this.node.identifier
676
+ });
677
+ }
678
+ async stop() {
679
+ (0, PlaybackGuard_1.playbackGuard)(this).invalidate();
680
+ return this.commands.enqueue(() => this.stopPlayback());
681
+ }
682
+ async stopPlayback() {
683
+ if (this.destroyed)
684
+ return this;
685
+ this.manager.emit("debug", `Moonlink.js > Player#stop -> Sending stop request to node ${this.node.identifier} for guild ${this.guildId}`);
686
+ this.manager.emit("playerTriggeredStop", this);
687
+ await this.sendPlayerUpdate({ track: { encoded: null } });
688
+ const oldPlaying = this.playing;
689
+ this.playing = false;
690
+ this.updateData("playing", this.playing);
691
+ this.manager.emit("debug", `Moonlink.js > Player#stop >> Player state changed: playing: ${oldPlaying} -> ${this.playing}`);
692
+ const oldTrackTitle = this.current?.title ?? "null";
693
+ this.current = null;
694
+ this.updateData("current", this.current);
695
+ this.manager.emit("debug", `Moonlink.js > Player#stop >> Player state changed: current: ${oldTrackTitle} -> null`);
696
+ this.manager.emit("debug", `Moonlink.js > Player#stop >> Player stopped for guild ${this.guildId}`);
697
+ this.manager.emit("playerStop", this);
698
+ return this;
699
+ }
700
+ async skip(position) {
701
+ const oldTrack = this.current;
702
+ if (position !== undefined) {
703
+ this.manager.emit("debug", `Moonlink.js > Player#skip -> Skipping to position ${position} in queue for guild ${this.guildId}`);
704
+ const track = this.queue.remove(position);
705
+ if (!track) {
706
+ this.manager.emit("debug", `Moonlink.js > Player#skip >> Invalid queue position for guild ${this.guildId}`);
707
+ return false;
708
+ }
709
+ this.manager.emit("playerTriggeredSkip", this, oldTrack, track, position);
710
+ return await this.play({ track: track instanceof Track_1.Track ? track : new Track_1.Track(track) });
711
+ }
712
+ if (!this.queue.size) {
713
+ if (this.autoPlay) {
714
+ if (!this.current) {
715
+ this.manager.emit("debug", `Moonlink.js > Player#skip >> Queue is empty and no current track, cannot trigger autoPlay for guild ${this.guildId}`);
716
+ return false;
717
+ }
718
+ this.manager.emit("debug", `Moonlink.js > Player#skip >> Queue empty, triggering autoPlay for guild ${this.guildId}`);
719
+ return await this.node.handleAutoPlay(this, this.current);
720
+ }
721
+ this.manager.emit("debug", `Moonlink.js > Player#skip >> Queue is empty, stopping player for guild ${this.guildId}`);
722
+ await this.stop();
723
+ return true;
724
+ }
725
+ const nextTrack = this.queue.first;
726
+ this.manager.emit("playerTriggeredSkip", this, oldTrack, nextTrack, 0);
727
+ this.manager.emit("debug", `Moonlink.js > Player#skip -> Skipping to next track in queue for guild ${this.guildId}`);
728
+ return await this.play();
729
+ }
730
+ async seek(position) {
731
+ return this.commands.enqueue(() => this.seekPlayback(position));
732
+ }
733
+ async seekPlayback(position) {
734
+ if (this.destroyed)
735
+ return this;
736
+ (0, Util_1.validate)(position, (v) => typeof v === "number" && !isNaN(v) && v >= 0, "Player#seek > Position must be a valid number.");
737
+ this.manager.emit("debug", `Moonlink.js > Player#seek -> Seeking to position ${position}ms for guild ${this.guildId}`);
738
+ this.manager.emit("playerTriggeredSeek", this, position);
739
+ await this.sendPlayerUpdate({ position });
740
+ if (this.current) {
741
+ this.current.position = position;
742
+ }
743
+ this.manager.emit("debug", `Moonlink.js > Player#seek >> Sent seek request to node ${this.node.identifier}`);
744
+ return this;
745
+ }
746
+ setVolume(volume) {
747
+ (0, Util_1.validate)(volume, (v) => typeof v === "number" && !isNaN(v) && v >= 0 && v <= 1000, "Player#setVolume > Volume must be between 0 and 1000.");
748
+ this.optimisticVolumeRevision = ++this.volumeRevision;
749
+ const oldVolume = this.volume;
750
+ this.volume = volume;
751
+ this.manager.emit("playerChangedVolume", this, oldVolume, volume);
752
+ this.manager.emit("debug", `Moonlink.js > Player#setVolume -> Changing volume from ${oldVolume} to ${volume} for guild ${this.guildId}`);
753
+ void this.commands.enqueue(async () => {
754
+ if (this.destroyed)
755
+ return;
756
+ await this.sendPlayerUpdate({ volume });
757
+ }).catch(error => {
758
+ this.manager.emit("playerVolumeError", this, error, volume);
759
+ this.manager.emit("debug", `NyxLink > Player#setVolume >> Volume update failed for guild ${this.guildId}: ${error.message}`);
760
+ });
761
+ this.updateData("volume", this.volume);
762
+ this.manager.emit("debug", `Moonlink.js > Player#setVolume >> Volume updated for guild ${this.guildId}`);
763
+ return this;
764
+ }
765
+ async setVolumeAsync(volume) {
766
+ (0, Util_1.validate)(volume, v => typeof v === "number" && Number.isFinite(v) && v >= 0 && v <= 1000, "Player#setVolumeAsync > Volume must be between 0 and 1000.");
767
+ const revision = ++this.volumeRevision;
768
+ return this.commands.enqueue(async () => {
769
+ if (this.destroyed)
770
+ throw new Error("Cannot update volume on a destroyed player");
771
+ await this.sendPlayerUpdate({ volume });
772
+ if (this.optimisticVolumeRevision > revision)
773
+ return this;
774
+ const oldVolume = this.volume;
775
+ this.volume = volume;
776
+ await this.updateData("volume", volume);
777
+ this.manager.emit("playerChangedVolume", this, oldVolume, volume);
778
+ return this;
779
+ });
780
+ }
781
+ setLoop(loop, count) {
782
+ const oldLoop = this.loop;
783
+ const oldLoopCount = this.loopCount;
784
+ this.loop = loop;
785
+ this.loopCount = count;
786
+ this.manager.emit("playerChangedLoop", this, oldLoop, this.loop, oldLoopCount, this.loopCount);
787
+ this.updateData("loop", this.loop);
788
+ this.updateData("loopCount", this.loopCount);
789
+ this.manager.emit("debug", `Moonlink.js > Player#setLoop >> Loop mode changed from "${oldLoop}" to "${loop}"${count ? ` (count: ${count})` : ""} for guild ${this.guildId}`);
790
+ return this;
791
+ }
792
+ setAutoPlay(autoPlay) {
793
+ if (!autoPlay)
794
+ (0, PlaybackGuard_1.playbackGuard)(this).cancelAutoPlay();
795
+ this.autoPlay = autoPlay;
796
+ this.manager.emit("playerAutoPlaySet", this, autoPlay);
797
+ this.updateData("autoPlay", this.autoPlay);
798
+ this.manager.emit("debug", `Moonlink.js > Player#setAutoPlay >> AutoPlay set to ${autoPlay} for guild ${this.guildId}`);
799
+ return this;
800
+ }
801
+ setAutoLeave(autoLeave) {
802
+ this.autoLeave = autoLeave;
803
+ this.manager.emit("playerAutoLeaveSet", this, autoLeave);
804
+ this.updateData("autoLeave", this.autoLeave);
805
+ this.manager.emit("debug", `Moonlink.js > Player#setAutoLeave >> AutoLeave set to ${autoLeave} for guild ${this.guildId}`);
806
+ return this;
807
+ }
808
+ shuffle() {
809
+ if (this.queue.size < 2) {
810
+ this.manager.emit("debug", `Moonlink.js > Player#shuffle >> Queue has less than 2 tracks, cannot shuffle for guild ${this.guildId}`);
811
+ return this;
812
+ }
813
+ const oldQueue = [...this.queue.tracks];
814
+ this.manager.emit("debug", `Moonlink.js > Player#shuffle -> Shuffling queue with ${this.queue.size} tracks for guild ${this.guildId}`);
815
+ this.queue.shuffle();
816
+ this.manager.emit("playerTriggeredShuffle", this, oldQueue, this.queue.tracks);
817
+ this.manager.emit("debug", `Moonlink.js > Player#shuffle >> Queue shuffled for guild ${this.guildId}`);
818
+ return this;
819
+ }
820
+ async destroy(reason) {
821
+ if (this.destructionPromise)
822
+ return this.destructionPromise;
823
+ if (this.destroyed) {
824
+ return;
825
+ }
826
+ (0, PlaybackGuard_1.playbackGuard)(this).invalidate();
827
+ this.destroyed = true;
828
+ this.destructionPromise = this.commands.enqueue(() => this.destroyPlayback(reason));
829
+ this.voice.destroy();
830
+ this.stopHealthCheck();
831
+ return this.destructionPromise;
832
+ }
833
+ async destroyPlayback(reason) {
834
+ if (this.resumeDebounceTimer) {
835
+ clearTimeout(this.resumeDebounceTimer);
836
+ this.resumeDebounceTimer = undefined;
837
+ }
838
+ if (!reason) {
839
+ const stack = new Error().stack?.split("\n").slice(2, 8).join("\n");
840
+ this.manager.emit("debug", `Moonlink.js > Player#destroy >> Destroy called without reason for guild ${this.guildId}. Stack: ${stack || "unavailable"}`);
841
+ }
842
+ const destroyReason = reason ?? "No reason provided";
843
+ this.manager.emit("debug", `Moonlink.js > Player#destroy -> Destroying player for guild ${this.guildId}. Reason: ${destroyReason}`);
844
+ this.playing = false;
845
+ this.paused = false;
846
+ try {
847
+ await this.disconnect();
848
+ }
849
+ catch (e) {
850
+ this.manager.emit("debug", `Moonlink.js > Player#destroy >> Voice disconnection failed for guild ${this.guildId}: ${e.message}`);
851
+ }
852
+ try {
853
+ await this.node.rest.destroyPlayer(this.guildId);
854
+ }
855
+ catch (e) {
856
+ this.manager.emit("debug", `Moonlink.js > Player#destroy >> Failed to destroy player on node: ${e.message}`);
857
+ }
858
+ this.current = null;
859
+ this.queue.clear();
860
+ this.previous = [];
861
+ this.updateData("previous", []);
862
+ this.manager.players.players.delete(this.guildId);
863
+ await this.manager.database.remove(`players.${this.guildId}`);
864
+ this.manager.emit('playerDestroyed', this, reason);
865
+ this.manager.emit("debug", `Moonlink.js > Player#destroy >> Player destroyed for guild ${this.guildId}.`);
866
+ }
867
+ async restart(options = {}) {
868
+ const guard = (0, PlaybackGuard_1.playbackGuard)(this);
869
+ const ticket = guard.ticket;
870
+ if (this.destroyed)
871
+ return false;
872
+ this.manager.emit("debug", `Moonlink.js > Player#restart -> Restarting player for guild ${this.guildId}`);
873
+ this.manager.emit("playerResuming", this);
874
+ if (!this.voiceChannelId) {
875
+ this.manager.emit("debug", `Moonlink.js > Player#restart >> Cannot restart player without a voiceChannelId for guild ${this.guildId}`);
876
+ return false;
877
+ }
878
+ try {
879
+ await this.connect();
880
+ }
881
+ catch (error) {
882
+ this.manager.emit("debug", `Moonlink.js > Player#restart >> Voice connection failed for guild ${this.guildId}. Error: ${error.message}`);
883
+ if (this.destroyed || !guard.isCurrent(ticket))
884
+ return false;
885
+ if (options.destroyOnFailure !== false)
886
+ await this.destroy("Failed to establish voice connection on restart.");
887
+ return false;
888
+ }
889
+ if (this.destroyed || !guard.isCurrent(ticket))
890
+ return false;
891
+ if (this.current) {
892
+ const lastKnownPosition = this.get("lastKnownPosition");
893
+ const lastState = this.get("lastState");
894
+ const currentLavalinkPos = lastState?.position ?? 0;
895
+ const isResumedSync = this.node.resumed && this.playing && currentLavalinkPos > 0;
896
+ const isAlreadySync = isResumedSync || (lastState?.connected && Math.abs(currentLavalinkPos - (this.current.position ?? 0)) < 2000);
897
+ if (isAlreadySync && this.playing) {
898
+ 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})`);
899
+ this.manager.emit("playerResumed", this);
900
+ return true;
901
+ }
902
+ const resumePosition = Math.max(typeof lastKnownPosition === "number" ? lastKnownPosition : 0, currentLavalinkPos, this.current.position ?? 0);
903
+ this.manager.emit("debug", `Moonlink.js > Player#restart -> Restoring current track "${this.current.title}" for guild ${this.guildId} at ${resumePosition}ms. AlreadySync: ${isAlreadySync}`);
904
+ const payload = {
905
+ track: { encoded: this.current.encoded, userData: this.current.userData },
906
+ volume: this.volume,
907
+ playing: this.playing,
908
+ paused: this.paused
909
+ };
910
+ if (resumePosition > 0 && this.current.isSeekable && !isAlreadySync) {
911
+ payload.position = resumePosition;
912
+ }
913
+ if (this.audioTrackId) {
914
+ payload.track.audioTrackId = this.audioTrackId;
915
+ }
916
+ if (this.fading)
917
+ payload.fading = this.fading;
918
+ if (this.nextTrack)
919
+ payload.nextTrack = this.nextTrack;
920
+ if (this.loudnessNormalizer !== undefined) {
921
+ payload.loudnessNormalizer = this.loudnessNormalizer;
922
+ }
923
+ const restored = await this.commands.enqueue(async () => {
924
+ if (this.destroyed || !guard.isCurrent(ticket))
925
+ return false;
926
+ if (!await this.restoreVoiceForRestart(ticket))
927
+ return false;
928
+ await this.sendPlayerUpdate(payload);
929
+ return !this.destroyed && guard.isCurrent(ticket);
930
+ });
931
+ if (!restored)
932
+ return false;
933
+ }
934
+ else if (this.queue.size > 0 && options.startQueued !== false) {
935
+ this.manager.emit("debug", `Moonlink.js > Player#restart -> No current track, playing first from queue for guild ${this.guildId}`);
936
+ if (!await this.commands.enqueue(async () => {
937
+ if (!await this.restoreVoiceForRestart(ticket))
938
+ return false;
939
+ return this.playNext({}, ticket);
940
+ }).catch(() => false))
941
+ return false;
942
+ }
943
+ else {
944
+ this.manager.emit("debug", `Moonlink.js > Player#restart >> No track to restore and queue is empty for guild ${this.guildId}`);
945
+ return true;
946
+ }
947
+ this.manager.emit("playerResumed", this);
948
+ return true;
949
+ }
950
+ async restoreVoiceForRestart(ticket) {
951
+ if (this.destroyed || !(0, PlaybackGuard_1.playbackGuard)(this).isCurrent(ticket))
952
+ return false;
953
+ const { sessionId, token, endpoint } = this.voice;
954
+ if (!sessionId || !token || !endpoint)
955
+ return false;
956
+ await this.sendPlayerUpdate({ voice: { sessionId, token, endpoint, channelId: this.voiceChannelId } }, true);
957
+ return !this.destroyed && (0, PlaybackGuard_1.playbackGuard)(this).isCurrent(ticket);
958
+ }
959
+ async transferNode(node) {
960
+ const targetNode = typeof node === "string" ? this.manager.nodes.nodes.get(node) : node;
961
+ if (this.destroyed || !targetNode || !targetNode.connected || targetNode.identifier === this.node.identifier)
962
+ return false;
963
+ const oldNode = this.node;
964
+ const guard = (0, PlaybackGuard_1.playbackGuard)(this);
965
+ const ticket = guard.invalidate();
966
+ const report = (status, reason) => {
967
+ this.manager.emit("playerNodeFailover", this, {
968
+ source: oldNode.identifier, target: targetNode.identifier, status,
969
+ positionMs: this.current?.position, reason
970
+ });
971
+ };
972
+ report('in-progress');
973
+ try {
974
+ const moved = await this.commands.enqueue(async () => {
975
+ if (this.destroyed || !guard.isCurrent(ticket) || !targetNode.connected)
976
+ return false;
977
+ const resolved = this.current ? await TrackResolver_1.TrackResolver.resolve(this.current, targetNode, oldNode) : null;
978
+ if (this.destroyed || !guard.isCurrent(ticket) || !targetNode.connected)
979
+ return false;
980
+ try {
981
+ await oldNode.rest.destroyPlayer(this.guildId);
982
+ }
983
+ catch (error) {
984
+ this.manager.emit("debug", `NyxLink > Player#transferNode >> Old node cleanup failed: ${error.message}`);
985
+ }
986
+ if (this.destroyed || !guard.isCurrent(ticket))
987
+ return false;
988
+ for (const track of [...this.queue.tracks, ...this.previous]) {
989
+ track.backend ??= oldNode.backend?.kind;
990
+ }
991
+ this.updateData('queue', this.queue.tracks.map(track => TrackCodec_1.TrackCodec.serialize(track)));
992
+ this.updateData('previous', this.previous.map(track => TrackCodec_1.TrackCodec.serialize(track)));
993
+ this.node = targetNode;
994
+ if (resolved) {
995
+ this.current = resolved;
996
+ this.updateData('current', TrackCodec_1.TrackCodec.serialize(resolved));
997
+ }
998
+ this.set("lastState", undefined);
999
+ return true;
1000
+ });
1001
+ if (!moved || !await this.restart({ destroyOnFailure: false, startQueued: false }) || this.destroyed || !guard.isCurrent(ticket)) {
1002
+ report(guard.isCurrent(ticket) ? 'failed' : 'cancelled');
1003
+ return false;
1004
+ }
1005
+ this.manager.emit("playerSwitchedNode", this, oldNode, targetNode);
1006
+ report('recovered');
1007
+ return true;
1008
+ }
1009
+ catch (error) {
1010
+ report(guard.isCurrent(ticket) ? 'failed' : 'cancelled', error.message);
1011
+ return false;
1012
+ }
1013
+ }
1014
+ setVoiceChannelId(voiceChannelId) {
1015
+ (0, Util_1.validate)(voiceChannelId, (v) => typeof v === "string" && v.length > 0, "Player#setVoiceChannelId > Voice channel ID must be a non-empty string.");
1016
+ if (this.voiceChannelId === voiceChannelId) {
1017
+ this.manager.emit("debug", `Moonlink.js > Player#setVoiceChannelId >> Voice channel already set to ${voiceChannelId} for guild ${this.guildId}`);
1018
+ return this;
1019
+ }
1020
+ const oldChannel = this.voiceChannelId;
1021
+ this.voiceChannelId = voiceChannelId;
1022
+ this.updateData("voiceChannelId", this.voiceChannelId);
1023
+ this.manager.emit("debug", `Moonlink.js > Player#setVoiceChannel >> Voice channel changed from ${oldChannel} to ${voiceChannelId} for guild ${this.guildId}`);
1024
+ this.manager.emit("playerVoiceChannelIdSet", this, oldChannel, voiceChannelId);
1025
+ return this;
1026
+ }
1027
+ setTextChannelId(textChannelId) {
1028
+ (0, Util_1.validate)(textChannelId, (v) => typeof v === "string" && v.length > 0, "Player#setTextChannelId > Text channel ID must be a non-empty string.");
1029
+ if (this.textChannelId === textChannelId) {
1030
+ this.manager.emit("debug", `Moonlink.js > Player#setTextChannelId >> Text channel already set to ${textChannelId} for guild ${this.guildId}`);
1031
+ return this;
1032
+ }
1033
+ const oldChannel = this.textChannelId;
1034
+ this.textChannelId = textChannelId;
1035
+ this.updateData("textChannelId", this.textChannelId);
1036
+ this.manager.emit("debug", `Moonlink.js > Player#setTextChannel >> Text channel changed from ${oldChannel} to ${textChannelId} for guild ${this.guildId}`);
1037
+ this.manager.emit("playerTextChannelIdSet", this, oldChannel, textChannelId);
1038
+ return this;
1039
+ }
1040
+ async replay() {
1041
+ if (!this.current?.encoded) {
1042
+ this.manager.emit("debug", `Moonlink.js > Player#replay >> No current track to replay for guild ${this.guildId}`);
1043
+ return false;
1044
+ }
1045
+ this.manager.emit("debug", `Moonlink.js > Player#replay -> Replaying track "${this.current.title}" for guild ${this.guildId}`);
1046
+ return await this.play({
1047
+ track: this.current,
1048
+ position: 0,
1049
+ });
1050
+ }
1051
+ async back() {
1052
+ if (this.previous.length === 0) {
1053
+ this.manager.emit("debug", `Moonlink.js > Player#back >> No previous tracks available for guild ${this.guildId}`);
1054
+ return false;
1055
+ }
1056
+ const lastTrack = this.previous.pop();
1057
+ if (!lastTrack) {
1058
+ this.manager.emit("debug", `Moonlink.js > Player#back >> Popped an invalid track from history for guild ${this.guildId}`);
1059
+ return false;
1060
+ }
1061
+ this.manager.emit("debug", `Moonlink.js > Player#back -> Going back to previous track "${lastTrack.title}" for guild ${this.guildId}`);
1062
+ if (this.current) {
1063
+ this.queue.unshift(this.current);
1064
+ this.manager.emit("debug", `Moonlink.js > Player#back >> Pushed current track "${this.current.title}" to the front of the queue.`);
1065
+ }
1066
+ this.current = lastTrack;
1067
+ this.set("isBackPlay", true);
1068
+ const played = await this.play({
1069
+ track: this.current,
1070
+ position: 0
1071
+ });
1072
+ if (played) {
1073
+ this.manager.emit("playerTriggeredBack", this, lastTrack);
1074
+ this.manager.emit("debug", `Moonlink.js > Player#back >> Successfully went back for guild ${this.guildId}`);
1075
+ }
1076
+ else {
1077
+ this.manager.emit("debug", `Moonlink.js > Player#back >> Failed to play previous track for guild ${this.guildId}.`);
1078
+ }
1079
+ return played;
1080
+ }
1081
+ }
1082
+ exports.Player = Player;
1083
+ //# sourceMappingURL=Player.js.map