yukimu 1.2.0 → 2.0.0

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 (135) hide show
  1. package/dist/BitrateOptimizer.d.ts +52 -0
  2. package/dist/BitrateOptimizer.d.ts.map +1 -0
  3. package/dist/BitrateOptimizer.js +115 -0
  4. package/dist/BitrateOptimizer.js.map +1 -0
  5. package/dist/ConnectionPool.d.ts +52 -2
  6. package/dist/ConnectionPool.d.ts.map +1 -1
  7. package/dist/ConnectionPool.js +123 -44
  8. package/dist/ConnectionPool.js.map +1 -1
  9. package/dist/Constants.d.ts +26 -47
  10. package/dist/Constants.d.ts.map +1 -1
  11. package/dist/Constants.js +134 -67
  12. package/dist/Constants.js.map +1 -1
  13. package/dist/Logger.d.ts +22 -0
  14. package/dist/Logger.d.ts.map +1 -0
  15. package/dist/Logger.js +74 -0
  16. package/dist/Logger.js.map +1 -0
  17. package/dist/Node.d.ts +17 -4
  18. package/dist/Node.d.ts.map +1 -1
  19. package/dist/Node.js +217 -79
  20. package/dist/Node.js.map +1 -1
  21. package/dist/Player.d.ts +77 -6
  22. package/dist/Player.d.ts.map +1 -1
  23. package/dist/Player.js +319 -75
  24. package/dist/Player.js.map +1 -1
  25. package/dist/Plugin.d.ts +16 -12
  26. package/dist/Plugin.d.ts.map +1 -1
  27. package/dist/Plugin.js +5 -9
  28. package/dist/Plugin.js.map +1 -1
  29. package/dist/Queue.d.ts +69 -3
  30. package/dist/Queue.d.ts.map +1 -1
  31. package/dist/Queue.js +123 -17
  32. package/dist/Queue.js.map +1 -1
  33. package/dist/Resolver.d.ts +33 -2
  34. package/dist/Resolver.d.ts.map +1 -1
  35. package/dist/Resolver.js +233 -27
  36. package/dist/Resolver.js.map +1 -1
  37. package/dist/Rest.d.ts +25 -3
  38. package/dist/Rest.d.ts.map +1 -1
  39. package/dist/Rest.js +165 -23
  40. package/dist/Rest.js.map +1 -1
  41. package/dist/TrackCache.d.ts +28 -8
  42. package/dist/TrackCache.d.ts.map +1 -1
  43. package/dist/TrackCache.js +111 -24
  44. package/dist/TrackCache.js.map +1 -1
  45. package/dist/WsQueue.d.ts +30 -9
  46. package/dist/WsQueue.d.ts.map +1 -1
  47. package/dist/WsQueue.js +66 -24
  48. package/dist/WsQueue.js.map +1 -1
  49. package/dist/Yukimu.d.ts +37 -13
  50. package/dist/Yukimu.d.ts.map +1 -1
  51. package/dist/Yukimu.js +146 -59
  52. package/dist/Yukimu.js.map +1 -1
  53. package/dist/connector/Connector.d.ts +26 -0
  54. package/dist/connector/Connector.d.ts.map +1 -1
  55. package/dist/connector/Connector.js +28 -0
  56. package/dist/connector/Connector.js.map +1 -1
  57. package/dist/connector/DiscordJS.d.ts +21 -19
  58. package/dist/connector/DiscordJS.d.ts.map +1 -1
  59. package/dist/connector/DiscordJS.js +44 -2
  60. package/dist/connector/DiscordJS.js.map +1 -1
  61. package/dist/connector/Eris.d.ts +13 -17
  62. package/dist/connector/Eris.d.ts.map +1 -1
  63. package/dist/connector/Eris.js +36 -4
  64. package/dist/connector/Eris.js.map +1 -1
  65. package/dist/connector/Oceanic.d.ts +13 -14
  66. package/dist/connector/Oceanic.d.ts.map +1 -1
  67. package/dist/connector/Oceanic.js +35 -2
  68. package/dist/connector/Oceanic.js.map +1 -1
  69. package/dist/errors/YukimuError.d.ts +40 -4
  70. package/dist/errors/YukimuError.d.ts.map +1 -1
  71. package/dist/errors/YukimuError.js +79 -9
  72. package/dist/errors/YukimuError.js.map +1 -1
  73. package/dist/index.d.ts +13 -4
  74. package/dist/index.d.ts.map +1 -1
  75. package/dist/index.js +30 -21
  76. package/dist/index.js.map +1 -1
  77. package/dist/plugins/AutoResume.d.ts +18 -14
  78. package/dist/plugins/AutoResume.d.ts.map +1 -1
  79. package/dist/plugins/AutoResume.js +101 -21
  80. package/dist/plugins/AutoResume.js.map +1 -1
  81. package/dist/plugins/AutoplayPlugin.d.ts +35 -0
  82. package/dist/plugins/AutoplayPlugin.d.ts.map +1 -0
  83. package/dist/plugins/AutoplayPlugin.js +111 -0
  84. package/dist/plugins/AutoplayPlugin.js.map +1 -0
  85. package/dist/plugins/InactivityPlugin.d.ts +30 -0
  86. package/dist/plugins/InactivityPlugin.d.ts.map +1 -0
  87. package/dist/plugins/InactivityPlugin.js +86 -0
  88. package/dist/plugins/InactivityPlugin.js.map +1 -0
  89. package/dist/plugins/PlayerMoved.d.ts +23 -1
  90. package/dist/plugins/PlayerMoved.d.ts.map +1 -1
  91. package/dist/plugins/PlayerMoved.js +57 -12
  92. package/dist/plugins/PlayerMoved.js.map +1 -1
  93. package/dist/types.d.ts +196 -78
  94. package/dist/types.d.ts.map +1 -1
  95. package/dist/types.js +1 -0
  96. package/dist/types.js.map +1 -1
  97. package/package.json +49 -5
  98. package/.cache/replit/env/latest +0 -88
  99. package/.cache/replit/env/latest.json +0 -1
  100. package/.cache/replit/modules/nodejs-20.res +0 -1
  101. package/.cache/replit/modules/python-3.11.res +0 -1
  102. package/.cache/replit/modules/replit.res +0 -1
  103. package/.cache/replit/modules.stamp +0 -0
  104. package/.cache/replit/nix/dotreplitenv.json +0 -1
  105. package/.cache/replit/toolchain.json +0 -1
  106. package/.local/state/workflow-logs/7zVU0iVo-fBL1ccMCmELy/configure_your_app.packager.installForAll.0 +0 -9
  107. package/.local/state/workflow-logs/7zVU0iVo-fBL1ccMCmELy/configure_your_app.shell.exec.1 +0 -1
  108. package/.local/state/workflow-logs/KRgHXizaECjWI5nWtS7Dj/configure_your_app.packager.installForAll.0 +0 -1
  109. package/.local/state/workflow-logs/KRgHXizaECjWI5nWtS7Dj/configure_your_app.shell.exec.1 +0 -1
  110. package/.local/state/workflow-logs/U0AinJQVHonnwGjj0RXLn/configure_your_app.packager.installForAll.0 +0 -2
  111. package/.local/state/workflow-logs/jVavLOnv1MqxUvxhMmqER/configure_your_app.packager.installForAll.0 +0 -1
  112. package/.local/state/workflow-logs/jVavLOnv1MqxUvxhMmqER/configure_your_app.shell.exec.1 +0 -1
  113. package/.replit +0 -7
  114. package/.upm/store.json +0 -1
  115. package/src/ConnectionPool.ts +0 -131
  116. package/src/Constants.ts +0 -101
  117. package/src/Node.ts +0 -309
  118. package/src/Player.ts +0 -337
  119. package/src/Plugin.ts +0 -23
  120. package/src/Queue.ts +0 -91
  121. package/src/Resolver.ts +0 -79
  122. package/src/Rest.ts +0 -121
  123. package/src/TrackCache.ts +0 -69
  124. package/src/WsQueue.ts +0 -78
  125. package/src/Yukimu.ts +0 -248
  126. package/src/connector/Connector.ts +0 -13
  127. package/src/connector/DiscordJS.ts +0 -33
  128. package/src/connector/Eris.ts +0 -35
  129. package/src/connector/Oceanic.ts +0 -32
  130. package/src/errors/YukimuError.ts +0 -33
  131. package/src/index.ts +0 -46
  132. package/src/plugins/AutoResume.ts +0 -61
  133. package/src/plugins/PlayerMoved.ts +0 -26
  134. package/src/types.ts +0 -145
  135. package/tsconfig.json +0 -20
package/src/Player.ts DELETED
@@ -1,337 +0,0 @@
1
- import { Queue } from "./Queue";
2
- import { PlayerState } from "./Constants";
3
- import { PlayerError } from "./errors/YukimuError";
4
- import type { Yukimu } from "./Yukimu";
5
- import type { Node } from "./Node";
6
- import type { Track, PlayerOptions, VoiceState, FilterOptions } from "./types";
7
-
8
- export class Player {
9
- public readonly manager: Yukimu;
10
- public node: Node;
11
- public readonly queue: Queue;
12
-
13
- // IDs
14
- public readonly guildId: string;
15
- public voiceChannelId: string | null;
16
- public textChannelId?: string;
17
-
18
- // State
19
- public state: PlayerState = PlayerState.DISCONNECTED;
20
- public playing: boolean = false;
21
- public paused: boolean = false;
22
- public position: number = 0;
23
- public ping: number = -1;
24
- public lastUpdated: number = Date.now();
25
- public volume: number;
26
- public loop: "none" | "track" | "queue" = "none";
27
-
28
- // Voice
29
- public sessionId: string | null = null;
30
- public voiceToken: string | null = null;
31
- public voiceEndpoint: string | null = null;
32
- public selfDeaf: boolean;
33
- public selfMute: boolean;
34
-
35
- // Filters
36
- public filters: FilterOptions = {};
37
-
38
- // Data store (like Kazagumo's player.data)
39
- public readonly data: Map<string, unknown> = new Map();
40
-
41
- // Autoplay
42
- public autoplay: boolean = false;
43
-
44
- constructor(manager: Yukimu, node: Node, options: PlayerOptions) {
45
- this.manager = manager;
46
- this.node = node;
47
- this.queue = new Queue();
48
-
49
- this.guildId = options.guildId;
50
- this.voiceChannelId = options.voiceChannelId;
51
- this.textChannelId = options.textChannelId;
52
- this.volume = options.volume ?? 100;
53
- this.selfDeaf = options.selfDeaf ?? true;
54
- this.selfMute = options.selfMute ?? false;
55
-
56
- this.sendVoicePayload(options.voiceChannelId, this.selfDeaf, this.selfMute);
57
- this.state = PlayerState.CONNECTING;
58
- }
59
-
60
- // ─── Getters ──────────────────────────────────────────────────────
61
-
62
- get connected(): boolean {
63
- return this.state === PlayerState.CONNECTED;
64
- }
65
-
66
- /** Real-time position estimate */
67
- get realPosition(): number {
68
- if (!this.playing || this.paused) return this.position;
69
- return Math.min(this.position + (Date.now() - this.lastUpdated), this.queue.current?.info.length ?? this.position);
70
- }
71
-
72
- // ─── Voice ───────────────────────────────────────────────────────
73
-
74
- public sendVoicePayload(channelId: string | null, selfDeaf: boolean, selfMute: boolean): void {
75
- this.manager.connector.sendPayload(this.guildId, {
76
- op: 4,
77
- d: { guild_id: this.guildId, channel_id: channelId, self_deaf: selfDeaf, self_mute: selfMute },
78
- });
79
- }
80
-
81
- public checkVoiceReady(): void {
82
- if (!this.sessionId || !this.voiceToken || !this.voiceEndpoint) return;
83
-
84
- const voiceState: VoiceState = {
85
- token: this.voiceToken,
86
- endpoint: this.voiceEndpoint,
87
- sessionId: this.sessionId,
88
- };
89
-
90
- if (this.node.version === 4) {
91
- this.node.rest.updatePlayer(this.guildId, { voice: voiceState }).catch(console.error);
92
- } else {
93
- this.node.send({
94
- op: "voiceUpdate",
95
- guildId: this.guildId,
96
- sessionId: this.sessionId,
97
- event: { token: this.voiceToken, guild_id: this.guildId, endpoint: this.voiceEndpoint },
98
- });
99
- }
100
-
101
- this.state = PlayerState.CONNECTED;
102
- }
103
-
104
- // ─── Playback ─────────────────────────────────────────────────────
105
-
106
- public async play(track?: Track, options?: { startTime?: number; endTime?: number; noReplace?: boolean }): Promise<void> {
107
- const toPlay = track ?? this.queue.current;
108
- if (!toPlay) throw new PlayerError("No track to play");
109
-
110
- this.queue.current = toPlay;
111
-
112
- if (this.node.version === 4) {
113
- await this.node.rest.updatePlayer(this.guildId, {
114
- track: { encoded: toPlay.encoded },
115
- volume: this.volume,
116
- ...(options?.startTime !== undefined && { position: options.startTime }),
117
- ...(options?.endTime !== undefined && { endTime: options.endTime }),
118
- }, options?.noReplace ?? false);
119
- } else {
120
- this.node.send({
121
- op: "play",
122
- guildId: this.guildId,
123
- track: toPlay.encoded,
124
- volume: String(this.volume),
125
- ...(options?.startTime !== undefined && { startTime: String(options.startTime) }),
126
- ...(options?.endTime !== undefined && { endTime: String(options.endTime) }),
127
- ...(options?.noReplace !== undefined && { noReplace: options.noReplace }),
128
- });
129
- }
130
-
131
- this.playing = true;
132
- this.paused = false;
133
- this.lastUpdated = Date.now();
134
- }
135
-
136
- public async pause(state: boolean = true): Promise<void> {
137
- if (this.node.version === 4) {
138
- await this.node.rest.updatePlayer(this.guildId, { paused: state });
139
- } else {
140
- this.node.send({ op: "pause", guildId: this.guildId, pause: state });
141
- }
142
- this.paused = state;
143
- this.playing = !state;
144
- }
145
-
146
- public async resume(): Promise<void> { return this.pause(false); }
147
-
148
- public async stop(): Promise<void> {
149
- if (this.node.version === 4) {
150
- await this.node.rest.updatePlayer(this.guildId, { track: { encoded: null } });
151
- } else {
152
- this.node.send({ op: "stop", guildId: this.guildId });
153
- }
154
- this.playing = false;
155
- this.paused = false;
156
- this.position = 0;
157
- this.queue.current = null;
158
- }
159
-
160
- public async skip(): Promise<Track | null> {
161
- const next = this.queue.next();
162
- if (next) {
163
- await this.play(next);
164
- } else {
165
- await this.stop();
166
- this.manager.emit("queueEnd", this);
167
- }
168
- return next;
169
- }
170
-
171
- public async seek(position: number): Promise<void> {
172
- if (!this.queue.current?.info.isSeekable) throw new PlayerError("Current track is not seekable");
173
- if (position < 0 || position > (this.queue.current.info.length ?? Infinity)) {
174
- throw new PlayerError(`Seek position out of range: ${position}`);
175
- }
176
- if (this.node.version === 4) {
177
- await this.node.rest.updatePlayer(this.guildId, { position });
178
- } else {
179
- this.node.send({ op: "seek", guildId: this.guildId, position });
180
- }
181
- this.position = position;
182
- this.lastUpdated = Date.now();
183
- }
184
-
185
- public async setVolume(volume: number): Promise<void> {
186
- if (volume < 0 || volume > 1000) throw new PlayerError("Volume must be between 0 and 1000");
187
- if (this.node.version === 4) {
188
- await this.node.rest.updatePlayer(this.guildId, { volume });
189
- } else {
190
- this.node.send({ op: "volume", guildId: this.guildId, volume });
191
- }
192
- this.volume = volume;
193
- }
194
-
195
- // ─── Filters ──────────────────────────────────────────────────────
196
-
197
- public async setFilters(filters: FilterOptions): Promise<void> {
198
- this.filters = { ...this.filters, ...filters };
199
-
200
- if (this.node.version === 4) {
201
- await this.node.rest.updatePlayer(this.guildId, { filters: this.filters });
202
- } else {
203
- if (filters.equalizer) {
204
- this.node.send({ op: "equalizer", guildId: this.guildId, bands: filters.equalizer });
205
- }
206
- const rest = { ...filters };
207
- delete rest.equalizer;
208
- if (Object.keys(rest).length > 0) {
209
- this.node.send({ op: "filters", guildId: this.guildId, ...rest });
210
- }
211
- }
212
- }
213
-
214
- public async clearFilters(): Promise<void> {
215
- this.filters = {};
216
- if (this.node.version === 4) {
217
- await this.node.rest.updatePlayer(this.guildId, { filters: {} });
218
- } else {
219
- this.node.send({ op: "filters", guildId: this.guildId });
220
- }
221
- }
222
-
223
- // ─── Preset Filters ───────────────────────────────────────────────
224
-
225
- public async setBassBoost(level: "off" | "low" | "medium" | "high" | "extreme"): Promise<void> {
226
- const presets: Record<string, number[]> = {
227
- off: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
228
- low: [0.2, 0.15, 0.1, 0.05, 0.0, -0.05, 0, 0, 0, 0, 0, 0, 0, 0, 0],
229
- medium: [0.4, 0.3, 0.2, 0.1, 0.05, -0.05, 0, 0, 0, 0, 0, 0, 0, 0, 0],
230
- high: [0.6, 0.5, 0.4, 0.25, 0.1, -0.1, 0, 0, 0, 0, 0, 0, 0, 0, 0],
231
- extreme: [1.0, 0.8, 0.6, 0.4, 0.2, -0.2, 0, 0, 0, 0, 0, 0, 0, 0, 0],
232
- };
233
- await this.setFilters({ equalizer: presets[level].map((gain, band) => ({ band, gain })) });
234
- }
235
-
236
- public async setNightcore(enabled: boolean): Promise<void> {
237
- await this.setFilters({ timescale: enabled ? { speed: 1.2, pitch: 1.2, rate: 1.0 } : undefined });
238
- }
239
-
240
- public async setVaporwave(enabled: boolean): Promise<void> {
241
- await this.setFilters({ timescale: enabled ? { speed: 0.8, pitch: 0.8, rate: 1.0 } : undefined });
242
- }
243
-
244
- public async set8D(enabled: boolean): Promise<void> {
245
- await this.setFilters({ rotation: enabled ? { rotationHz: 0.2 } : undefined });
246
- }
247
-
248
- public async setKaraoke(enabled: boolean): Promise<void> {
249
- await this.setFilters({
250
- karaoke: enabled ? { level: 1.0, monoLevel: 1.0, filterBand: 220.0, filterWidth: 100.0 } : undefined,
251
- });
252
- }
253
-
254
- public async setTremolo(enabled: boolean, frequency = 2.0, depth = 0.5): Promise<void> {
255
- await this.setFilters({ tremolo: enabled ? { frequency, depth } : undefined });
256
- }
257
-
258
- public async setVibrato(enabled: boolean, frequency = 2.0, depth = 0.5): Promise<void> {
259
- await this.setFilters({ vibrato: enabled ? { frequency, depth } : undefined });
260
- }
261
-
262
- public async setLowPass(enabled: boolean, smoothing = 20.0): Promise<void> {
263
- await this.setFilters({ lowPass: enabled ? { smoothing } : undefined });
264
- }
265
-
266
- // ─── Queue Helpers ────────────────────────────────────────────────
267
-
268
- public async add(tracks: Track | Track[], requester?: unknown): Promise<void> {
269
- const arr = Array.isArray(tracks) ? tracks : [tracks];
270
-
271
- // Attach requester to each track
272
- if (requester) arr.forEach(t => { (t as any).requester = requester; });
273
-
274
- if (!this.queue.current && arr.length > 0) {
275
- const first = arr.shift()!;
276
- this.queue.add(arr);
277
- await this.play(first);
278
- } else {
279
- this.queue.add(arr);
280
- }
281
- }
282
-
283
- public setLoop(mode: "none" | "track" | "queue"): void {
284
- this.loop = mode;
285
- }
286
-
287
- public setAutoplay(enabled: boolean): void {
288
- this.autoplay = enabled;
289
- }
290
-
291
- // ─── Node Moving ──────────────────────────────────────────────────
292
-
293
- /** Move player to a different Lavalink node */
294
- public async moveToNode(node: Node): Promise<void> {
295
- if (this.node === node) return;
296
- const oldNode = this.node;
297
- this.node = node;
298
-
299
- // Destroy on old node
300
- await oldNode.rest.destroyPlayer(this.guildId).catch(() => {});
301
-
302
- // Recreate on new node with current state
303
- if (this.queue.current) {
304
- await this.play(this.queue.current, { startTime: this.realPosition });
305
- }
306
-
307
- // Reapply filters and volume
308
- if (Object.keys(this.filters).length > 0) {
309
- await this.setFilters(this.filters).catch(() => {});
310
- }
311
- if (this.volume !== 100) {
312
- await this.setVolume(this.volume).catch(() => {});
313
- }
314
- }
315
-
316
- // ─── Voice Channel Moves ──────────────────────────────────────────
317
-
318
- public async move(channelId: string): Promise<void> {
319
- this.voiceChannelId = channelId;
320
- this.sendVoicePayload(channelId, this.selfDeaf, this.selfMute);
321
- }
322
-
323
- // ─── Destroy ──────────────────────────────────────────────────────
324
-
325
- public async destroy(): Promise<void> {
326
- this.state = PlayerState.DISCONNECTING;
327
- this.sendVoicePayload(null, false, false);
328
-
329
- await this.node.rest.destroyPlayer(this.guildId).catch(() => {});
330
-
331
- this.playing = false;
332
- this.paused = false;
333
- this.queue.clear();
334
- this.data.clear();
335
- this.state = PlayerState.DISCONNECTED;
336
- }
337
- }
package/src/Plugin.ts DELETED
@@ -1,23 +0,0 @@
1
- import type { Yukimu } from "./Yukimu";
2
-
3
- /**
4
- * Base Plugin class — extend this to create Yukimu plugins.
5
- * Similar to Kazagumo's plugin system.
6
- *
7
- * Example:
8
- * class MyPlugin extends Plugin {
9
- * public name = "MyPlugin";
10
- * public load(manager: Yukimu) {
11
- * manager.on("trackStart", (player, track) => { ... });
12
- * }
13
- * }
14
- */
15
- export abstract class Plugin {
16
- public abstract name: string;
17
-
18
- /** Called when plugin is loaded into Yukimu */
19
- public abstract load(manager: Yukimu): void;
20
-
21
- /** Called when plugin is unloaded */
22
- public unload?(manager: Yukimu): void;
23
- }
package/src/Queue.ts DELETED
@@ -1,91 +0,0 @@
1
- import type { Track } from "./types";
2
-
3
- export class Queue {
4
- public current: Track | null = null;
5
- public previous: Track[] = [];
6
- private tracks: Track[] = [];
7
-
8
- // ─── Add / Remove ─────────────────────────────────────────────────
9
-
10
- public add(tracks: Track | Track[], position?: number): void {
11
- const arr = Array.isArray(tracks) ? tracks : [tracks];
12
- if (position !== undefined) {
13
- this.tracks.splice(position, 0, ...arr);
14
- } else {
15
- this.tracks.push(...arr);
16
- }
17
- }
18
-
19
- public next(): Track | null {
20
- if (this.current) {
21
- this.previous.unshift(this.current);
22
- if (this.previous.length > 10) this.previous.pop(); // keep last 10
23
- }
24
- this.current = this.tracks.shift() ?? null;
25
- return this.current;
26
- }
27
-
28
- public remove(index: number): Track | null {
29
- if (index < 0 || index >= this.tracks.length) return null;
30
- const [removed] = this.tracks.splice(index, 1);
31
- return removed;
32
- }
33
-
34
- public removeRange(start: number, end: number): Track[] {
35
- return this.tracks.splice(start, end - start);
36
- }
37
-
38
- public clear(): void {
39
- this.tracks = [];
40
- this.current = null;
41
- this.previous = [];
42
- }
43
-
44
- // ─── Reorder ──────────────────────────────────────────────────────
45
-
46
- public shuffle(): void {
47
- for (let i = this.tracks.length - 1; i > 0; i--) {
48
- const j = Math.floor(Math.random() * (i + 1));
49
- [this.tracks[i], this.tracks[j]] = [this.tracks[j], this.tracks[i]];
50
- }
51
- }
52
-
53
- public move(from: number, to: number): void {
54
- if (from < 0 || to < 0 || from >= this.tracks.length || to >= this.tracks.length) return;
55
- const [track] = this.tracks.splice(from, 1);
56
- this.tracks.splice(to, 0, track);
57
- }
58
-
59
- /** Skip to a specific position in queue */
60
- public skipto(index: number): Track | null {
61
- if (index < 0 || index >= this.tracks.length) return null;
62
- this.tracks.splice(0, index);
63
- return this.next();
64
- }
65
-
66
- // ─── Peek / Find ──────────────────────────────────────────────────
67
-
68
- public peek(count: number = 10): Track[] {
69
- return this.tracks.slice(0, count);
70
- }
71
-
72
- public find(predicate: (track: Track) => boolean): Track | undefined {
73
- return this.tracks.find(predicate);
74
- }
75
-
76
- public filter(predicate: (track: Track) => boolean): Track[] {
77
- return this.tracks.filter(predicate);
78
- }
79
-
80
- // ─── Getters ──────────────────────────────────────────────────────
81
-
82
- get size(): number { return this.tracks.length; }
83
-
84
- get isEmpty(): boolean { return this.tracks.length === 0; }
85
-
86
- get totalDuration(): number {
87
- return this.tracks.reduce((acc, t) => acc + (t.info?.length ?? 0), 0);
88
- }
89
-
90
- get list(): ReadonlyArray<Track> { return this.tracks; }
91
- }
package/src/Resolver.ts DELETED
@@ -1,79 +0,0 @@
1
- import { SOURCE_PREFIXES, URL_PATTERNS } from "./Constants";
2
- import type { Yukimu } from "./Yukimu";
3
- import type { SearchResult, SearchSource, Track } from "./types";
4
-
5
- export class Resolver {
6
- private manager: Yukimu;
7
- private spotifyToken: string | null = null;
8
- private spotifyExpiry: number = 0;
9
-
10
- constructor(manager: Yukimu) {
11
- this.manager = manager;
12
- }
13
-
14
- public async resolve(query: string, source: SearchSource, requester?: unknown): Promise<SearchResult> {
15
- const node = this.manager.getBestNode();
16
- const isUrl = /^https?:\/\//.test(query);
17
- const identifier = isUrl ? query : `${SOURCE_PREFIXES[source] ?? "ytsearch"}:${query}`;
18
-
19
- const result = await node.loadTracks(identifier);
20
-
21
- // Attach requester
22
- if (requester) result.tracks.forEach(t => { (t as Track & { requester: unknown }).requester = requester; });
23
-
24
- // Spotify fallback — if LavaSrc not installed
25
- if ((result.loadType === "error" || result.loadType === "empty") && isUrl) {
26
- const spotifyMatch = query.match(/spotify\.com\/track\/([a-zA-Z0-9]+)/);
27
- if (spotifyMatch) {
28
- const meta = await this.resolveSpotifyMeta(spotifyMatch[1]);
29
- if (meta) return this.resolve(`${meta.title} ${meta.artist}`, "youtube", requester);
30
- }
31
- }
32
-
33
- // Cache all returned tracks
34
- for (const track of result.tracks) {
35
- if (track.encoded) this.manager.trackCache.set(track.encoded, track);
36
- }
37
-
38
- return result;
39
- }
40
-
41
- public detectSource(url: string): SearchSource | null {
42
- for (const [source, patterns] of Object.entries(URL_PATTERNS)) {
43
- if (patterns.some(p => p.test(url))) return source as SearchSource;
44
- }
45
- return null;
46
- }
47
-
48
- private async getSpotifyToken(): Promise<string | null> {
49
- const opts = this.manager.options.spotify;
50
- if (!opts) return null;
51
- if (this.spotifyToken && Date.now() < this.spotifyExpiry) return this.spotifyToken;
52
- try {
53
- const res = await fetch("https://accounts.spotify.com/api/token", {
54
- method: "POST",
55
- headers: {
56
- "Content-Type": "application/x-www-form-urlencoded",
57
- Authorization: `Basic ${Buffer.from(`${opts.clientId}:${opts.clientSecret}`).toString("base64")}`,
58
- },
59
- body: "grant_type=client_credentials",
60
- });
61
- const data = await res.json() as { access_token: string; expires_in: number };
62
- this.spotifyToken = data.access_token;
63
- this.spotifyExpiry = Date.now() + data.expires_in * 1000 - 5000;
64
- return this.spotifyToken;
65
- } catch { return null; }
66
- }
67
-
68
- private async resolveSpotifyMeta(trackId: string): Promise<{ title: string; artist: string } | null> {
69
- const token = await this.getSpotifyToken();
70
- if (!token) return null;
71
- try {
72
- const res = await fetch(`https://api.spotify.com/v1/tracks/${trackId}`, {
73
- headers: { Authorization: `Bearer ${token}` },
74
- });
75
- const data = await res.json() as { name: string; artists: { name: string }[] };
76
- return { title: data.name, artist: data.artists[0]?.name ?? "Unknown" };
77
- } catch { return null; }
78
- }
79
- }
package/src/Rest.ts DELETED
@@ -1,121 +0,0 @@
1
- import { RestError } from "./errors/YukimuError";
2
- import type { Node } from "./Node";
3
- import type { SearchResult, Track, NodeStats, NodeInfo } from "./types";
4
-
5
- const TIMEOUT_MS = 15000;
6
-
7
- export class Rest {
8
- private node: Node;
9
-
10
- constructor(node: Node) {
11
- this.node = node;
12
- }
13
-
14
- get baseUrl(): string {
15
- const protocol = this.node.options.secure ? "https" : "http";
16
- return `${protocol}://${this.node.options.host}:${this.node.options.port}`;
17
- }
18
-
19
- get prefix(): string {
20
- return this.node.version === 4 ? "/v4" : "";
21
- }
22
-
23
- get headers(): Record<string, string> {
24
- return {
25
- Authorization: this.node.options.password,
26
- "User-Id": this.node.manager.options.clientId,
27
- "Client-Name": "Yukimu/1.2.0",
28
- "Content-Type": "application/json",
29
- ...(this.node.version === 3 ? { "Num-Shards": "1" } : {}),
30
- };
31
- }
32
-
33
- public async request<T = unknown>(method: string, path: string, body?: unknown): Promise<T> {
34
- const url = `${this.baseUrl}${this.prefix}${path}`;
35
- const controller = new AbortController();
36
- const timeout = setTimeout(() => controller.abort(), TIMEOUT_MS);
37
-
38
- try {
39
- const res = await (globalThis as any).fetch(url, {
40
- method,
41
- headers: this.headers,
42
- body: body ? JSON.stringify(body) : undefined,
43
- signal: controller.signal,
44
- });
45
-
46
- clearTimeout(timeout);
47
-
48
- if (!res.ok) {
49
- const text = await res.text().catch(() => "Unknown error");
50
- throw new RestError(`REST ${res.status} on ${method} ${path}: ${text}`, res.status, path);
51
- }
52
-
53
- if (res.status === 204) return undefined as T;
54
- return res.json() as Promise<T>;
55
- } catch (err: any) {
56
- clearTimeout(timeout);
57
- if (err.name === "AbortError") throw new RestError(`REST timeout on ${method} ${path}`, 408, path);
58
- throw err;
59
- }
60
- }
61
-
62
- public async loadTracks(identifier: string): Promise<SearchResult> {
63
- const raw = await this.request<Record<string, unknown>>("GET", `/loadtracks?identifier=${encodeURIComponent(identifier)}`);
64
- return this.node.version === 3 ? this.normalizeV3(raw) : raw as unknown as SearchResult;
65
- }
66
-
67
- public async decodeTrack(encoded: string): Promise<Track> {
68
- return this.request("GET", `/decodetrack?encodedTrack=${encodeURIComponent(encoded)}`);
69
- }
70
-
71
- public async decodeTracks(encoded: string[]): Promise<Track[]> {
72
- return this.request("POST", `/decodetracks`, encoded);
73
- }
74
-
75
- public async getInfo(): Promise<NodeInfo> {
76
- return this.request("GET", "/info");
77
- }
78
-
79
- public async getStats(): Promise<NodeStats> {
80
- return this.request("GET", "/stats");
81
- }
82
-
83
- public async getVersion(): Promise<string> {
84
- const res = await (globalThis as any).fetch(`${this.baseUrl}/version`, { headers: this.headers });
85
- return res.text();
86
- }
87
-
88
- public async updatePlayer(guildId: string, body: unknown, noReplace = false): Promise<unknown> {
89
- const path = this.node.version === 4
90
- ? `/sessions/${this.node.sessionId}/players/${guildId}?noReplace=${noReplace}`
91
- : `/players/${guildId}`;
92
- return this.request("PATCH", path, body);
93
- }
94
-
95
- public async destroyPlayer(guildId: string): Promise<void> {
96
- const path = this.node.version === 4
97
- ? `/sessions/${this.node.sessionId}/players/${guildId}`
98
- : `/players/${guildId}`;
99
- await this.request("DELETE", path);
100
- }
101
-
102
- public async updateSession(body: { resuming?: boolean; timeout?: number }): Promise<unknown> {
103
- if (this.node.version !== 4) return;
104
- return this.request("PATCH", `/sessions/${this.node.sessionId}`, body);
105
- }
106
-
107
- private normalizeV3(raw: Record<string, unknown>): SearchResult {
108
- const loadType = ((raw.loadType as string) ?? "").toLowerCase();
109
- const norm = (tracks: unknown[]): Track[] =>
110
- (tracks ?? []).map((t: any) => ({ encoded: t.track ?? t.encoded, info: t.info, pluginInfo: t.pluginInfo ?? {} }));
111
-
112
- switch (loadType) {
113
- case "track_loaded": return { loadType: "track", tracks: norm(raw.tracks as unknown[]) };
114
- case "playlist_loaded": return { loadType: "playlist", tracks: norm(raw.tracks as unknown[]), playlistInfo: raw.playlistInfo as any };
115
- case "search_result": return { loadType: "search", tracks: norm(raw.tracks as unknown[]) };
116
- case "no_matches": return { loadType: "empty", tracks: [] };
117
- case "load_failed": return { loadType: "error", tracks: [], exception: raw.exception as any };
118
- default: return { loadType: "empty", tracks: [] };
119
- }
120
- }
121
- }