@fluxerjs/core 1.2.4 → 1.3.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.
package/dist/client.js ADDED
@@ -0,0 +1,3926 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/subpath-client.ts
21
+ var subpath_client_exports = {};
22
+ __export(subpath_client_exports, {
23
+ Client: () => Client,
24
+ Events: () => Events
25
+ });
26
+ module.exports = __toCommonJS(subpath_client_exports);
27
+
28
+ // src/client/Client.ts
29
+ var import_events3 = require("events");
30
+ var import_rest5 = require("@fluxerjs/rest");
31
+ var import_ws = require("@fluxerjs/ws");
32
+ var import_types21 = require("@fluxerjs/types");
33
+
34
+ // src/client/ChannelManager.ts
35
+ var import_collection4 = require("@fluxerjs/collection");
36
+ var import_types6 = require("@fluxerjs/types");
37
+ var import_util5 = require("@fluxerjs/util");
38
+ var import_rest2 = require("@fluxerjs/rest");
39
+
40
+ // src/errors/FluxerError.ts
41
+ var import_util = require("@fluxerjs/util");
42
+
43
+ // src/errors/ErrorCodes.ts
44
+ var import_util2 = require("@fluxerjs/util");
45
+
46
+ // src/util/messageUtils.ts
47
+ var import_builders = require("@fluxerjs/builders");
48
+ var FILE_FETCH_TIMEOUT_MS = 3e4;
49
+ async function resolveMessageFiles(files) {
50
+ const result = [];
51
+ for (let i = 0; i < files.length; i++) {
52
+ const f = files[i];
53
+ const filename = f.filename ?? f.name;
54
+ if ("url" in f && f.url) {
55
+ if (!URL.canParse(f.url)) {
56
+ throw new import_util.FluxerError(`Invalid file URL at index ${i}: ${f.url}`, {
57
+ code: import_util2.ErrorCodes.InvalidFileUrl
58
+ });
59
+ }
60
+ let res;
61
+ try {
62
+ res = await fetch(f.url, {
63
+ signal: AbortSignal.timeout(FILE_FETCH_TIMEOUT_MS)
64
+ });
65
+ } catch (err) {
66
+ throw new import_util.FluxerError(`Failed to fetch file from ${f.url}`, {
67
+ code: import_util2.ErrorCodes.FileFetchFailed,
68
+ cause: err instanceof Error ? err : void 0
69
+ });
70
+ }
71
+ if (!res.ok) {
72
+ throw new import_util.FluxerError(
73
+ `Failed to fetch file from ${f.url}: ${res.status} ${res.statusText}`,
74
+ {
75
+ code: import_util2.ErrorCodes.FileFetchFailed
76
+ }
77
+ );
78
+ }
79
+ const data = await res.arrayBuffer();
80
+ result.push({ name: f.name, data, filename });
81
+ } else if ("data" in f && f.data != null) {
82
+ result.push({ name: f.name, data: f.data, filename });
83
+ } else {
84
+ throw new import_util.FluxerError(`File at index ${i} must have either "data" or "url"`, {
85
+ code: import_util2.ErrorCodes.InvalidAttachment
86
+ });
87
+ }
88
+ }
89
+ return result;
90
+ }
91
+ function buildSendBody(options) {
92
+ const body = typeof options === "string" ? { content: options } : options;
93
+ const result = {};
94
+ if (body.content !== void 0) result.content = body.content;
95
+ if (body.embeds?.length) {
96
+ result.embeds = body.embeds.map((e) => e instanceof import_builders.EmbedBuilder ? e.toJSON() : e);
97
+ }
98
+ if (body.files?.length && body.attachments) {
99
+ result.attachments = body.attachments.map((a) => ({
100
+ id: a.id,
101
+ filename: a.filename,
102
+ ...a.title != null && { title: a.title },
103
+ ...a.description != null && { description: a.description },
104
+ ...a.flags != null && { flags: a.flags }
105
+ }));
106
+ } else if (body.files?.length) {
107
+ result.attachments = body.files.map((f, i) => ({
108
+ id: i,
109
+ filename: f.filename ?? f.name
110
+ }));
111
+ }
112
+ if (body.flags !== void 0) result.flags = body.flags;
113
+ return result;
114
+ }
115
+
116
+ // src/client/MessageManager.ts
117
+ var import_types2 = require("@fluxerjs/types");
118
+ var import_rest = require("@fluxerjs/rest");
119
+
120
+ // src/structures/Base.ts
121
+ var Base = class {
122
+ };
123
+
124
+ // src/structures/Message.ts
125
+ var import_collection2 = require("@fluxerjs/collection");
126
+ var import_types = require("@fluxerjs/types");
127
+ var import_builders2 = require("@fluxerjs/builders");
128
+
129
+ // src/util/ReactionCollector.ts
130
+ var import_events = require("events");
131
+ var import_collection = require("@fluxerjs/collection");
132
+
133
+ // src/util/Events.ts
134
+ var Events = {
135
+ Ready: "ready",
136
+ MessageCreate: "messageCreate",
137
+ MessageUpdate: "messageUpdate",
138
+ MessageDelete: "messageDelete",
139
+ MessageDeleteBulk: "messageDeleteBulk",
140
+ MessageReactionAdd: "messageReactionAdd",
141
+ MessageReactionRemove: "messageReactionRemove",
142
+ MessageReactionRemoveAll: "messageReactionRemoveAll",
143
+ MessageReactionRemoveEmoji: "messageReactionRemoveEmoji",
144
+ InteractionCreate: "interactionCreate",
145
+ GuildCreate: "guildCreate",
146
+ GuildUpdate: "guildUpdate",
147
+ GuildDelete: "guildDelete",
148
+ GuildBanAdd: "guildBanAdd",
149
+ GuildBanRemove: "guildBanRemove",
150
+ GuildEmojisUpdate: "guildEmojisUpdate",
151
+ GuildStickersUpdate: "guildStickersUpdate",
152
+ GuildIntegrationsUpdate: "guildIntegrationsUpdate",
153
+ GuildMemberAdd: "guildMemberAdd",
154
+ GuildMemberUpdate: "guildMemberUpdate",
155
+ GuildMemberRemove: "guildMemberRemove",
156
+ GuildMembersChunk: "guildMembersChunk",
157
+ GuildRoleCreate: "guildRoleCreate",
158
+ GuildRoleUpdate: "guildRoleUpdate",
159
+ GuildRoleDelete: "guildRoleDelete",
160
+ GuildScheduledEventCreate: "guildScheduledEventCreate",
161
+ GuildScheduledEventUpdate: "guildScheduledEventUpdate",
162
+ GuildScheduledEventDelete: "guildScheduledEventDelete",
163
+ ChannelCreate: "channelCreate",
164
+ ChannelUpdate: "channelUpdate",
165
+ ChannelDelete: "channelDelete",
166
+ ChannelPinsUpdate: "channelPinsUpdate",
167
+ InviteCreate: "inviteCreate",
168
+ InviteDelete: "inviteDelete",
169
+ TypingStart: "typingStart",
170
+ UserUpdate: "userUpdate",
171
+ PresenceUpdate: "presenceUpdate",
172
+ VoiceStateUpdate: "voiceStateUpdate",
173
+ VoiceServerUpdate: "voiceServerUpdate",
174
+ VoiceStatesSync: "voiceStatesSync",
175
+ WebhooksUpdate: "webhooksUpdate",
176
+ Resumed: "resumed",
177
+ Error: "error",
178
+ Debug: "debug"
179
+ };
180
+
181
+ // src/util/ReactionCollector.ts
182
+ var ReactionCollector = class extends import_events.EventEmitter {
183
+ client;
184
+ messageId;
185
+ channelId;
186
+ options;
187
+ collected = new import_collection.Collection();
188
+ _timeout = null;
189
+ _ended = false;
190
+ _listener;
191
+ constructor(client, messageId, channelId, options = {}) {
192
+ super();
193
+ this.client = client;
194
+ this.messageId = messageId;
195
+ this.channelId = channelId;
196
+ this.options = {
197
+ filter: options.filter ?? (() => true),
198
+ time: options.time ?? 0,
199
+ max: options.max ?? 0
200
+ };
201
+ this._listener = (reaction, user, _msgId, chId, _emoji, userId) => {
202
+ if (this._ended || reaction.messageId !== this.messageId || chId !== this.channelId) return;
203
+ if (!this.options.filter(reaction, user)) return;
204
+ const key = `${userId}:${reaction.emoji.id ?? reaction.emoji.name}`;
205
+ this.collected.set(key, { reaction, user });
206
+ this.emit("collect", reaction, user);
207
+ if (this.options.max > 0 && this.collected.size >= this.options.max) {
208
+ this.stop("limit");
209
+ }
210
+ };
211
+ this.client.on(Events.MessageReactionAdd, this._listener);
212
+ if (this.options.time > 0) {
213
+ this._timeout = setTimeout(() => this.stop("time"), this.options.time);
214
+ }
215
+ }
216
+ stop(reason = "user") {
217
+ if (this._ended) return;
218
+ this._ended = true;
219
+ this.client.off(Events.MessageReactionAdd, this._listener);
220
+ if (this._timeout) {
221
+ clearTimeout(this._timeout);
222
+ this._timeout = null;
223
+ }
224
+ this.emit("end", this.collected, reason);
225
+ }
226
+ on(event, listener) {
227
+ return super.on(event, listener);
228
+ }
229
+ emit(event, ...args) {
230
+ return super.emit(event, ...args);
231
+ }
232
+ };
233
+
234
+ // src/structures/Message.ts
235
+ var Message = class _Message extends Base {
236
+ client;
237
+ id;
238
+ channelId;
239
+ guildId;
240
+ author;
241
+ content;
242
+ createdAt;
243
+ editedAt;
244
+ pinned;
245
+ attachments;
246
+ type;
247
+ flags;
248
+ mentionEveryone;
249
+ tts;
250
+ embeds;
251
+ stickers;
252
+ reactions;
253
+ messageReference;
254
+ messageSnapshots;
255
+ call;
256
+ referencedMessage;
257
+ /** Webhook ID if this message was sent via webhook. Null otherwise. */
258
+ webhookId;
259
+ /** Users mentioned in this message. */
260
+ mentions;
261
+ /** Role IDs mentioned in this message. */
262
+ mentionRoles;
263
+ /** Client-side nonce for acknowledgment. Null if not provided. */
264
+ nonce;
265
+ /**
266
+ * Channel where this message was sent. Resolved from cache; null if not cached.
267
+ * Messages can only exist in text-based channels (text, DM, announcement), so this always has send() when non-null.
268
+ */
269
+ get channel() {
270
+ return this.client.channels.get(this.channelId) ?? null;
271
+ }
272
+ /** Guild where this message was sent. Resolved from cache; null for DMs or if not cached. */
273
+ get guild() {
274
+ return this.guildId ? this.client.guilds.get(this.guildId) ?? null : null;
275
+ }
276
+ /**
277
+ * Resolve the channel (from cache or API). Use when you need the channel and it may not be cached.
278
+ * @returns The channel
279
+ * @throws FluxerError with CHANNEL_NOT_FOUND if the channel does not exist
280
+ */
281
+ async resolveChannel() {
282
+ return this.client.channels.resolve(this.channelId);
283
+ }
284
+ /**
285
+ * Resolve the guild (from cache or API). Returns null for DMs.
286
+ * @returns The guild, or null if this is a DM or guild not found
287
+ */
288
+ async resolveGuild() {
289
+ return this.guildId ? this.client.guilds.resolve(this.guildId) : null;
290
+ }
291
+ /** @param data - API message from POST/PATCH /channels/{id}/messages or gateway MESSAGE_CREATE */
292
+ constructor(client, data) {
293
+ super();
294
+ this.client = client;
295
+ this.id = data.id;
296
+ this.channelId = data.channel_id;
297
+ this.guildId = data.guild_id ?? null;
298
+ this.author = client.getOrCreateUser(data.author);
299
+ this.content = data.content;
300
+ this.createdAt = new Date(data.timestamp);
301
+ this.editedAt = data.edited_timestamp ? new Date(data.edited_timestamp) : null;
302
+ this.pinned = data.pinned;
303
+ this.attachments = new import_collection2.Collection();
304
+ for (const a of data.attachments ?? []) this.attachments.set(a.id, a);
305
+ this.type = data.type ?? import_types.MessageType.Default;
306
+ this.flags = data.flags ?? 0;
307
+ this.mentionEveryone = data.mention_everyone ?? false;
308
+ this.tts = data.tts ?? false;
309
+ this.embeds = data.embeds ?? [];
310
+ this.stickers = data.stickers ?? [];
311
+ this.reactions = data.reactions ?? [];
312
+ this.messageReference = data.message_reference ?? null;
313
+ this.messageSnapshots = data.message_snapshots ?? [];
314
+ this.call = data.call ?? null;
315
+ this.referencedMessage = data.referenced_message ? new _Message(client, data.referenced_message) : null;
316
+ this.webhookId = data.webhook_id ?? null;
317
+ this.mentions = (data.mentions ?? []).map((u) => client.getOrCreateUser(u));
318
+ this.mentionRoles = data.mention_roles ?? [];
319
+ this.nonce = data.nonce ?? null;
320
+ }
321
+ /**
322
+ * Send a message to this channel without replying. Use when you want a standalone message.
323
+ * @param options - Text content or object with content, embeds, and/or files
324
+ * @example
325
+ * await message.send('Pong!');
326
+ * await message.send({ embeds: [embed] }); // EmbedBuilder auto-converted
327
+ * await message.send({ content: 'File', files: [{ name: 'data.txt', data }] });
328
+ */
329
+ async send(options) {
330
+ const payload = await _Message._createMessageBody(options);
331
+ return this._send(payload);
332
+ }
333
+ /**
334
+ * Send a message to a specific channel. Use for logging, forwarding, or sending to another channel in the guild.
335
+ * @param channelId - Snowflake of the target channel (e.g. log channel ID)
336
+ * @param options - Text content or object with content and/or embeds
337
+ * @example
338
+ * await message.sendTo(logChannelId, 'User ' + message.author.username + ' said: ' + message.content);
339
+ * await message.sendTo(announceChannelId, { embeds: [embed] });
340
+ */
341
+ async sendTo(channelId, options) {
342
+ return this.client.channels.send(channelId, options);
343
+ }
344
+ /**
345
+ * Reply to this message (shows as a reply in the client).
346
+ * @param options - Text content or object with content, embeds, and/or reply options (ping, replyTo)
347
+ * @example
348
+ * await message.reply('Pong!');
349
+ * await message.reply({ embeds: [embed] });
350
+ * await message.reply('No ping!', { ping: false });
351
+ * await message.reply({ content: 'Reply to other', replyTo: otherMessage });
352
+ */
353
+ async reply(options, replyOptions) {
354
+ const opts = typeof options === "string" ? { content: options } : options;
355
+ const mergedReply = replyOptions ?? (opts.ping !== void 0 || opts.replyTo !== void 0) ? { ping: opts.ping, replyTo: opts.replyTo } : void 0;
356
+ const refMessage = mergedReply?.replyTo ?? this;
357
+ const ref = refMessage instanceof _Message ? {
358
+ channel_id: refMessage.channelId,
359
+ message_id: refMessage.id,
360
+ guild_id: refMessage.guildId ?? void 0
361
+ } : {
362
+ channel_id: refMessage.channelId,
363
+ message_id: refMessage.messageId,
364
+ guild_id: void 0
365
+ };
366
+ const payload = await _Message._createMessageBody(opts, ref, mergedReply?.ping !== false);
367
+ return this._send(payload);
368
+ }
369
+ /** Exposed for testing purposes, use Message.reply() or send() for normal use */
370
+ static async _createMessageBody(content, referenced_message, ping) {
371
+ if (typeof content === "string") {
372
+ if (content.length === 0) {
373
+ throw new RangeError("Cannot send an empty message");
374
+ }
375
+ content = { content };
376
+ }
377
+ const base = buildSendBody(content);
378
+ const files = content.files?.length ? await resolveMessageFiles(content.files) : void 0;
379
+ const body = { ...base };
380
+ if (referenced_message) {
381
+ body.message_reference = referenced_message;
382
+ if (ping === false) {
383
+ body.flags = (body.flags ?? 0) | import_types.MessageFlags.SuppressNotifications;
384
+ }
385
+ }
386
+ return { files, body };
387
+ }
388
+ async _send(payload) {
389
+ const data = await this.client.rest.post(
390
+ import_types.Routes.channelMessages(this.channelId),
391
+ payload
392
+ );
393
+ this.client._addMessageToCache(this.channelId, data);
394
+ return new _Message(this.client, data);
395
+ }
396
+ /**
397
+ * Edit this message. Only the author (or admins) can edit.
398
+ * @param options - New content and/or embeds
399
+ */
400
+ async edit(options) {
401
+ const body = {};
402
+ if (options.content !== void 0) body.content = options.content;
403
+ if (options.embeds?.length) {
404
+ body.embeds = options.embeds.map((e) => e instanceof import_builders2.EmbedBuilder ? e.toJSON() : e);
405
+ }
406
+ const data = await this.client.rest.patch(import_types.Routes.channelMessage(this.channelId, this.id), {
407
+ body
408
+ });
409
+ return new _Message(this.client, data);
410
+ }
411
+ /**
412
+ * Create a reaction collector for this message.
413
+ * Collects reactions matching the filter until time expires or max is reached.
414
+ * @param options - Filter, time (ms), and max count
415
+ * @example
416
+ * const collector = message.createReactionCollector({ filter: (r, u) => u.id === userId, time: 10000 });
417
+ * collector.on('collect', (reaction, user) => console.log(user.username, 'reacted with', reaction.emoji.name));
418
+ * collector.on('end', (collected, reason) => { ... });
419
+ */
420
+ createReactionCollector(options) {
421
+ return new ReactionCollector(this.client, this.id, this.channelId, options);
422
+ }
423
+ /**
424
+ * Re-fetch this message from the API to get the latest content, embeds, reactions, etc.
425
+ * Use when you have a stale Message (e.g. from an old event or cache) and need fresh data.
426
+ * @returns The updated message
427
+ * @throws FluxerError with MESSAGE_NOT_FOUND if the message was deleted or does not exist
428
+ * @example
429
+ * const updated = await message.fetch();
430
+ * console.log('Latest content:', updated.content);
431
+ */
432
+ async fetch() {
433
+ return this.client.channels.fetchMessage(this.channelId, this.id);
434
+ }
435
+ /** Delete this message. */
436
+ async delete() {
437
+ await this.client.rest.delete(import_types.Routes.channelMessage(this.channelId, this.id));
438
+ }
439
+ /**
440
+ * Delete a specific attachment from this message.
441
+ * DELETE /channels/{id}/messages/{id}/attachments/{attachmentId}.
442
+ */
443
+ async deleteAttachment(attachmentId) {
444
+ await this.client.rest.delete(
445
+ import_types.Routes.channelMessageAttachment(this.channelId, this.id, attachmentId),
446
+ { auth: true }
447
+ );
448
+ this.attachments.delete(attachmentId);
449
+ }
450
+ /** Pin this message to the channel. Requires Manage Messages permission. */
451
+ async pin() {
452
+ await this.client.rest.put(import_types.Routes.channelPinMessage(this.channelId, this.id));
453
+ this.pinned = true;
454
+ }
455
+ /** Unpin this message from the channel. Requires Manage Messages permission. */
456
+ async unpin() {
457
+ await this.client.rest.delete(import_types.Routes.channelPinMessage(this.channelId, this.id));
458
+ this.pinned = false;
459
+ }
460
+ /**
461
+ * Format emoji for reaction API: unicode string or "name:id" for custom.
462
+ * For string resolution (e.g. :name:), use client.resolveEmoji; Message methods resolve automatically when guildId is available.
463
+ */
464
+ static formatEmoji(emoji) {
465
+ if (typeof emoji === "string") return emoji;
466
+ return `${emoji.name}:${emoji.id}`;
467
+ }
468
+ resolveEmojiForReaction(emoji) {
469
+ return this.client.resolveEmoji(emoji, this.guildId);
470
+ }
471
+ /**
472
+ * Add a reaction to this message (as the bot).
473
+ * @param emoji - Unicode emoji, custom `{ name, id }`, `:name:`, `name:id`, or `<:name:id>`
474
+ */
475
+ async react(emoji) {
476
+ const emojiStr = await this.resolveEmojiForReaction(emoji);
477
+ const route = `${import_types.Routes.channelMessageReaction(this.channelId, this.id, emojiStr)}/@me`;
478
+ await this.client.rest.put(route);
479
+ }
480
+ /**
481
+ * Remove the bot's reaction, or a specific user's reaction if userId is provided.
482
+ * @param emoji - Unicode emoji, custom `{ name, id }`, `:name:`, `name:id`, or `<:name:id>`
483
+ * @param userId - If provided, removes that user's reaction (requires moderator permissions)
484
+ */
485
+ async removeReaction(emoji, userId) {
486
+ const emojiStr = await this.resolveEmojiForReaction(emoji);
487
+ const route = `${import_types.Routes.channelMessageReaction(this.channelId, this.id, emojiStr)}/${userId ?? "@me"}`;
488
+ await this.client.rest.delete(route);
489
+ }
490
+ /**
491
+ * Remove all reactions from this message.
492
+ * Requires moderator permissions.
493
+ */
494
+ async removeAllReactions() {
495
+ await this.client.rest.delete(import_types.Routes.channelMessageReactions(this.channelId, this.id));
496
+ }
497
+ /**
498
+ * Remove all reactions of a specific emoji from this message.
499
+ * @param emoji - Unicode emoji, custom `{ name, id }`, `:name:`, `name:id`, or `<:name:id>`. Requires moderator permissions.
500
+ */
501
+ async removeReactionEmoji(emoji) {
502
+ const emojiStr = await this.resolveEmojiForReaction(emoji);
503
+ await this.client.rest.delete(import_types.Routes.channelMessageReaction(this.channelId, this.id, emojiStr));
504
+ }
505
+ /**
506
+ * Fetch users who reacted with the given emoji.
507
+ * @param emoji - Unicode emoji or custom `{ name, id }`
508
+ * @param options - limit (1–100), after (user ID for pagination)
509
+ * @returns Array of User objects
510
+ */
511
+ async fetchReactionUsers(emoji, options) {
512
+ const emojiStr = await this.resolveEmojiForReaction(emoji);
513
+ const params = new URLSearchParams();
514
+ if (options?.limit != null) params.set("limit", String(options.limit));
515
+ if (options?.after) params.set("after", options.after);
516
+ const qs = params.toString();
517
+ const route = import_types.Routes.channelMessageReaction(this.channelId, this.id, emojiStr) + (qs ? `?${qs}` : "");
518
+ const data = await this.client.rest.get(route);
519
+ const list = Array.isArray(data) ? data : data?.users ?? [];
520
+ return list.map((u) => this.client.getOrCreateUser(u));
521
+ }
522
+ };
523
+
524
+ // src/client/MessageManager.ts
525
+ var MessageManager = class {
526
+ constructor(client, channelId) {
527
+ this.client = client;
528
+ this.channelId = channelId;
529
+ }
530
+ /**
531
+ * Get a message from cache. Returns undefined if not cached or caching is disabled.
532
+ * Requires options.cache.messages > 0.
533
+ * @param messageId - Snowflake of the message
534
+ */
535
+ get(messageId) {
536
+ const data = this.client._getMessageCache(this.channelId)?.get(messageId);
537
+ return data ? new Message(this.client, data) : void 0;
538
+ }
539
+ /**
540
+ * Fetch a message by ID from this channel.
541
+ * When message caching is enabled, the fetched message is added to the cache.
542
+ * @param messageId - Snowflake of the message
543
+ * @returns The message
544
+ * @throws FluxerError with MESSAGE_NOT_FOUND if the message does not exist
545
+ */
546
+ async fetch(messageId) {
547
+ try {
548
+ const data = await this.client.rest.get(
549
+ import_types2.Routes.channelMessage(this.channelId, messageId)
550
+ );
551
+ this.client._addMessageToCache(this.channelId, data);
552
+ return new Message(this.client, data);
553
+ } catch (err) {
554
+ if (err instanceof import_rest.RateLimitError) throw err;
555
+ if (err instanceof import_rest.FluxerAPIError && err.statusCode === 404) {
556
+ throw new import_util.FluxerError(`Message ${messageId} not found in channel ${this.channelId}`, {
557
+ code: import_util2.ErrorCodes.MessageNotFound,
558
+ cause: err
559
+ });
560
+ }
561
+ throw err instanceof import_util.FluxerError ? err : new import_util.FluxerError(String(err), { cause: err });
562
+ }
563
+ }
564
+ };
565
+
566
+ // src/util/MessageCollector.ts
567
+ var import_events2 = require("events");
568
+ var import_collection3 = require("@fluxerjs/collection");
569
+ var MessageCollector = class extends import_events2.EventEmitter {
570
+ client;
571
+ channelId;
572
+ options;
573
+ collected = new import_collection3.Collection();
574
+ _timeout = null;
575
+ _ended = false;
576
+ _listener;
577
+ constructor(client, channelId, options = {}) {
578
+ super();
579
+ this.client = client;
580
+ this.channelId = channelId;
581
+ this.options = {
582
+ filter: options.filter ?? (() => true),
583
+ time: options.time ?? 0,
584
+ max: options.max ?? 0
585
+ };
586
+ this._listener = (message) => {
587
+ if (this._ended || message.channelId !== this.channelId) return;
588
+ if (!this.options.filter(message)) return;
589
+ this.collected.set(message.id, message);
590
+ this.emit("collect", message);
591
+ if (this.options.max > 0 && this.collected.size >= this.options.max) {
592
+ this.stop("limit");
593
+ }
594
+ };
595
+ this.client.on(Events.MessageCreate, this._listener);
596
+ if (this.options.time > 0) {
597
+ this._timeout = setTimeout(() => this.stop("time"), this.options.time);
598
+ }
599
+ }
600
+ stop(reason = "user") {
601
+ if (this._ended) return;
602
+ this._ended = true;
603
+ this.client.off(Events.MessageCreate, this._listener);
604
+ if (this._timeout) {
605
+ clearTimeout(this._timeout);
606
+ this._timeout = null;
607
+ }
608
+ this.emit("end", this.collected, reason);
609
+ }
610
+ on(event, listener) {
611
+ return super.on(event, listener);
612
+ }
613
+ emit(event, ...args) {
614
+ return super.emit(event, ...args);
615
+ }
616
+ };
617
+
618
+ // src/structures/Channel.ts
619
+ var import_types5 = require("@fluxerjs/types");
620
+ var import_util3 = require("@fluxerjs/util");
621
+ var import_util4 = require("@fluxerjs/util");
622
+
623
+ // src/structures/Webhook.ts
624
+ var import_types3 = require("@fluxerjs/types");
625
+ var import_builders3 = require("@fluxerjs/builders");
626
+
627
+ // src/util/Constants.ts
628
+ var CDN_URL = "https://fluxerusercontent.com";
629
+ var STATIC_CDN_URL = "https://fluxerstatic.com";
630
+
631
+ // src/util/cdn.ts
632
+ function getExtension(hash, options) {
633
+ const ext = options?.extension ?? "png";
634
+ if (hash?.startsWith("a_")) return "gif";
635
+ return ext;
636
+ }
637
+ function appendSize(options) {
638
+ return options?.size ? `?size=${options.size}` : "";
639
+ }
640
+ function cdnAvatarURL(userId, avatarHash, options) {
641
+ if (!avatarHash) return null;
642
+ const ext = getExtension(avatarHash, options);
643
+ const size = appendSize(options);
644
+ return `${CDN_URL}/avatars/${userId}/${avatarHash}.${ext}${size}`;
645
+ }
646
+ function cdnMemberAvatarURL(guildId, userId, avatarHash, options) {
647
+ if (!avatarHash) return null;
648
+ const ext = getExtension(avatarHash, options);
649
+ const size = appendSize(options);
650
+ return `${CDN_URL}/guilds/${guildId}/users/${userId}/avatars/${avatarHash}.${ext}${size}`;
651
+ }
652
+ function cdnMemberBannerURL(guildId, userId, bannerHash, options) {
653
+ if (!bannerHash) return null;
654
+ const ext = getExtension(bannerHash, options);
655
+ const size = appendSize(options);
656
+ return `${CDN_URL}/guilds/${guildId}/users/${userId}/banners/${bannerHash}.${ext}${size}`;
657
+ }
658
+ function cdnDefaultAvatarURL(userIdOrIndex) {
659
+ const index = typeof userIdOrIndex === "string" ? Number(BigInt(userIdOrIndex) % 6n) : Math.abs(Math.floor(userIdOrIndex) % 6);
660
+ return `${STATIC_CDN_URL}/avatars/${index}.png`;
661
+ }
662
+
663
+ // src/structures/Webhook.ts
664
+ var Webhook = class _Webhook extends Base {
665
+ client;
666
+ id;
667
+ guildId;
668
+ channelId;
669
+ name;
670
+ avatar;
671
+ /** Present only when webhook was created via createWebhook(); not returned when fetching. */
672
+ token;
673
+ /** User who created the webhook. */
674
+ user;
675
+ /** @param data - API webhook from POST /channels/{id}/webhooks (has token) or GET /webhooks/{id} (no token) */
676
+ constructor(client, data) {
677
+ super();
678
+ this.client = client;
679
+ this.id = data.id;
680
+ this.guildId = data.guild_id;
681
+ this.channelId = data.channel_id;
682
+ this.name = data.name ?? "Unknown";
683
+ this.avatar = data.avatar ?? null;
684
+ this.token = data.token ?? null;
685
+ this.user = client.getOrCreateUser(data.user);
686
+ }
687
+ /**
688
+ * Get the URL for this webhook's avatar.
689
+ * Returns null if the webhook has no custom avatar.
690
+ */
691
+ avatarURL(options) {
692
+ return cdnAvatarURL(this.id, this.avatar, options);
693
+ }
694
+ /** Delete this webhook. Requires bot token with Manage Webhooks permission. */
695
+ async delete() {
696
+ await this.client.rest.delete(import_types3.Routes.webhook(this.id), { auth: true });
697
+ }
698
+ /**
699
+ * Edit this webhook. With token: name and avatar only. Without token (bot auth): name, avatar, and channel_id.
700
+ * @param options - Fields to update (name, avatar, channel_id when using bot auth)
701
+ * @returns This webhook instance with updated fields
702
+ */
703
+ async edit(options) {
704
+ const body = {};
705
+ if (options.name !== void 0) body.name = options.name;
706
+ if (options.avatar !== void 0) body.avatar = options.avatar;
707
+ if ("channel_id" in options && options.channel_id !== void 0 && !this.token) {
708
+ body.channel_id = options.channel_id;
709
+ }
710
+ if (this.token) {
711
+ const data2 = await this.client.rest.patch(import_types3.Routes.webhookExecute(this.id, this.token), {
712
+ body,
713
+ auth: false
714
+ });
715
+ const w2 = data2;
716
+ this.name = w2.name ?? this.name;
717
+ this.avatar = w2.avatar ?? null;
718
+ return this;
719
+ }
720
+ const data = await this.client.rest.patch(import_types3.Routes.webhook(this.id), {
721
+ body,
722
+ auth: true
723
+ });
724
+ const w = data;
725
+ this.name = w.name ?? this.name;
726
+ this.avatar = w.avatar ?? null;
727
+ this.channelId = w.channel_id ?? this.channelId;
728
+ return this;
729
+ }
730
+ /**
731
+ * Send a message via this webhook. Requires the webhook token (only present when created, not when fetched).
732
+ * @param options - Text content or object with content, embeds, username, avatar_url, tts, files, attachments
733
+ * @param wait - If true, waits for the API and returns the created Message; otherwise returns void (204)
734
+ * @throws Error if token is not available
735
+ * @example
736
+ * await webhook.send('Hello!');
737
+ * await webhook.send({ embeds: [embed] });
738
+ * await webhook.send({ content: 'File attached', files: [{ name: 'data.txt', data: buffer }] });
739
+ * const msg = await webhook.send({ content: 'Hi' }, true);
740
+ */
741
+ async send(options, wait) {
742
+ if (!this.token) {
743
+ throw new import_util.FluxerError(
744
+ "Webhook token is required to send. The token is only returned when creating a webhook; fetched webhooks cannot send.",
745
+ { code: import_util2.ErrorCodes.WebhookTokenRequired }
746
+ );
747
+ }
748
+ const opts = typeof options === "string" ? { content: options } : options;
749
+ const body = buildSendBody(opts);
750
+ if (opts.username !== void 0) body.username = opts.username;
751
+ if (opts.avatar_url !== void 0) body.avatar_url = opts.avatar_url;
752
+ if (opts.tts !== void 0) body.tts = opts.tts;
753
+ const route = import_types3.Routes.webhookExecute(this.id, this.token) + (wait ? "?wait=true" : "");
754
+ const files = opts.files?.length ? await resolveMessageFiles(opts.files) : void 0;
755
+ const postOptions = files?.length ? { body, files, auth: false } : { body, auth: false };
756
+ const data = await this.client.rest.post(route, postOptions);
757
+ if (wait && data) {
758
+ return new Message(this.client, data);
759
+ }
760
+ return void 0;
761
+ }
762
+ /**
763
+ * Edit a message previously sent by this webhook.
764
+ * Requires the webhook token.
765
+ */
766
+ async editMessage(messageId, options) {
767
+ if (!this.token) {
768
+ throw new import_util.FluxerError(
769
+ "Webhook token is required to edit messages. The token is only returned when creating a webhook; fetched webhooks cannot edit messages.",
770
+ { code: import_util2.ErrorCodes.WebhookTokenRequired }
771
+ );
772
+ }
773
+ const body = { ...options };
774
+ if (options.embeds !== void 0) {
775
+ body.embeds = options.embeds.map((e) => e instanceof import_builders3.EmbedBuilder ? e.toJSON() : e);
776
+ }
777
+ const data = await this.client.rest.patch(
778
+ import_types3.Routes.webhookMessage(this.id, this.token, messageId),
779
+ { body, auth: false }
780
+ );
781
+ return new Message(this.client, data);
782
+ }
783
+ /**
784
+ * Fetch a message sent by this webhook.
785
+ * Requires the webhook token.
786
+ */
787
+ async fetchMessage(messageId) {
788
+ if (!this.token) {
789
+ throw new import_util.FluxerError(
790
+ "Webhook token is required to fetch messages. The token is only returned when creating a webhook; fetched webhooks cannot fetch messages.",
791
+ { code: import_util2.ErrorCodes.WebhookTokenRequired }
792
+ );
793
+ }
794
+ const data = await this.client.rest.get(
795
+ import_types3.Routes.webhookMessage(this.id, this.token, messageId),
796
+ { auth: false }
797
+ );
798
+ return new Message(this.client, data);
799
+ }
800
+ /**
801
+ * Delete a message sent by this webhook.
802
+ * Requires the webhook token.
803
+ */
804
+ async deleteMessage(messageId) {
805
+ if (!this.token) {
806
+ throw new import_util.FluxerError(
807
+ "Webhook token is required to delete messages. The token is only returned when creating a webhook; fetched webhooks cannot delete messages.",
808
+ { code: import_util2.ErrorCodes.WebhookTokenRequired }
809
+ );
810
+ }
811
+ await this.client.rest.delete(import_types3.Routes.webhookMessage(this.id, this.token, messageId), {
812
+ auth: false
813
+ });
814
+ }
815
+ /**
816
+ * Fetch a webhook by ID using bot auth.
817
+ * @param client - The client instance
818
+ * @param webhookId - The webhook ID
819
+ * @returns Webhook without token (cannot send)
820
+ */
821
+ static async fetch(client, webhookId) {
822
+ const data = await client.rest.get(import_types3.Routes.webhook(webhookId));
823
+ return new _Webhook(client, data);
824
+ }
825
+ /**
826
+ * Create a Webhook instance from an ID and token (e.g. from a stored webhook URL).
827
+ * @param client - The client instance
828
+ * @param webhookId - The webhook ID
829
+ * @param token - The webhook token (from createWebhook or stored)
830
+ * @param options - Optional channelId, guildId, name for display
831
+ */
832
+ static fromToken(client, webhookId, token, options) {
833
+ return new _Webhook(client, {
834
+ id: webhookId,
835
+ guild_id: options?.guildId ?? "",
836
+ channel_id: options?.channelId ?? "",
837
+ name: options?.name ?? "Webhook",
838
+ avatar: null,
839
+ token,
840
+ user: { id: "", username: "webhook", discriminator: "0" }
841
+ });
842
+ }
843
+ };
844
+
845
+ // src/structures/Invite.ts
846
+ var import_types4 = require("@fluxerjs/types");
847
+ var Invite = class _Invite extends Base {
848
+ client;
849
+ code;
850
+ type;
851
+ guild;
852
+ channel;
853
+ inviter;
854
+ memberCount;
855
+ presenceCount;
856
+ expiresAt;
857
+ temporary;
858
+ createdAt;
859
+ uses;
860
+ maxUses;
861
+ maxAge;
862
+ /**
863
+ * Normalize invite input to a raw code (plain code or URL such as https://fluxer.gg/{code}).
864
+ */
865
+ static normalizeCode(codeOrUrl) {
866
+ const input = codeOrUrl.trim();
867
+ if (!input) {
868
+ throw new import_util.FluxerError("Invite code cannot be empty", { code: import_util2.ErrorCodes.InvalidInvite });
869
+ }
870
+ const parseInviteCodeFromUrl = (value) => {
871
+ if (!URL.canParse(value)) return null;
872
+ let url;
873
+ try {
874
+ url = new URL(value);
875
+ } catch {
876
+ return null;
877
+ }
878
+ const segments = url.pathname.split("/").filter(Boolean);
879
+ if (segments.length === 0) return null;
880
+ const inviteSegmentIdx = segments.findIndex((segment) => {
881
+ const lower = segment.toLowerCase();
882
+ return lower === "invite" || lower === "invites";
883
+ });
884
+ const code2 = inviteSegmentIdx >= 0 && segments[inviteSegmentIdx + 1] ? segments[inviteSegmentIdx + 1] : segments[segments.length - 1];
885
+ return decodeURIComponent(code2).trim();
886
+ };
887
+ const hasScheme = /^[a-z][a-z0-9+.-]*:\/\//i.test(input);
888
+ const fromAbsolute = hasScheme ? parseInviteCodeFromUrl(input) : null;
889
+ const fromHostLike = !hasScheme && URL.canParse(`https://${input}`) ? parseInviteCodeFromUrl(`https://${input}`) : null;
890
+ const directCode = decodeURIComponent(input).trim();
891
+ const code = fromAbsolute ?? fromHostLike ?? directCode;
892
+ if (!code || /[\s/?#]/.test(code)) {
893
+ throw new import_util.FluxerError("Invalid invite code or URL", { code: import_util2.ErrorCodes.InvalidInvite });
894
+ }
895
+ return code;
896
+ }
897
+ /** @param data - API invite from GET /invites/{code}, channel/guild invite list, or gateway INVITE_CREATE */
898
+ constructor(client, data) {
899
+ super();
900
+ this.client = client;
901
+ this.code = data.code;
902
+ this.type = data.type;
903
+ this.guild = data.guild;
904
+ this.channel = data.channel;
905
+ this.inviter = data.inviter ? client.getOrCreateUser(data.inviter) : null;
906
+ this.memberCount = data.member_count ?? null;
907
+ this.presenceCount = data.presence_count ?? null;
908
+ this.expiresAt = data.expires_at ?? null;
909
+ this.temporary = data.temporary ?? null;
910
+ this.createdAt = data.created_at ?? null;
911
+ this.uses = data.uses ?? null;
912
+ this.maxUses = data.max_uses ?? null;
913
+ this.maxAge = data.max_age ?? null;
914
+ }
915
+ /**
916
+ * Fetch invite metadata by code or URL (does not join the guild).
917
+ */
918
+ static async fetch(client, codeOrUrl) {
919
+ const code = _Invite.normalizeCode(codeOrUrl);
920
+ const data = await client.rest.get(import_types4.Routes.invite(code));
921
+ return new _Invite(client, data);
922
+ }
923
+ /** Full invite URL (https://fluxer.gg/{code} or instance-specific). */
924
+ get url() {
925
+ return `https://fluxer.gg/${this.code}`;
926
+ }
927
+ /**
928
+ * Resolve the guild from cache if available.
929
+ * @returns The guild, or null if not cached
930
+ */
931
+ getGuild() {
932
+ return this.guild?.id ? this.client.guilds.get(this.guild.id) ?? null : null;
933
+ }
934
+ /**
935
+ * Delete this invite.
936
+ * Requires Manage Guild or Create Instant Invite permission.
937
+ */
938
+ async delete() {
939
+ await this.client.rest.delete(import_types4.Routes.invite(this.code), { auth: true });
940
+ }
941
+ };
942
+
943
+ // src/structures/Channel.ts
944
+ var Channel = class _Channel extends Base {
945
+ /** Whether this channel has a send method (TextChannel, DMChannel). */
946
+ isTextBased() {
947
+ return "send" in this;
948
+ }
949
+ /** Whether this channel is a DM or Group DM. */
950
+ isDM() {
951
+ return this.type === import_types5.ChannelType.DM || this.type === import_types5.ChannelType.GroupDM;
952
+ }
953
+ /** Whether this channel is voice-based (VoiceChannel). */
954
+ isVoice() {
955
+ return "bitrate" in this;
956
+ }
957
+ isLink() {
958
+ return "url" in this;
959
+ }
960
+ /** Create a DM channel from API data (type DM or GroupDM). */
961
+ static createDM(client, data) {
962
+ return new DMChannel(client, data);
963
+ }
964
+ client;
965
+ id;
966
+ type;
967
+ /** Channel name. Guild channels and Group DMs have names; 1:1 DMs are typically null. */
968
+ name;
969
+ /** Channel icon hash (Group DMs). Null if none. */
970
+ icon;
971
+ /** ISO timestamp when the last message was pinned. Null if never pinned. */
972
+ lastPinTimestamp;
973
+ /** @param data - API channel from GET /channels/{id} or GET /guilds/{id}/channels */
974
+ constructor(client, data) {
975
+ super();
976
+ this.client = client;
977
+ this.id = data.id;
978
+ this.type = data.type;
979
+ this.name = data.name ?? null;
980
+ this.icon = data.icon ?? null;
981
+ this.lastPinTimestamp = data.last_pin_timestamp ?? null;
982
+ }
983
+ /**
984
+ * Create the appropriate channel subclass from API data.
985
+ * @param client - The client instance
986
+ * @param data - Channel data from the API
987
+ */
988
+ static from(client, data) {
989
+ const type = data.type ?? 0;
990
+ if (type === import_types5.ChannelType.GuildText) return new TextChannel(client, data);
991
+ if (type === import_types5.ChannelType.GuildCategory) return new CategoryChannel(client, data);
992
+ if (type === import_types5.ChannelType.GuildVoice) return new VoiceChannel(client, data);
993
+ if (type === import_types5.ChannelType.GuildLink || type === import_types5.ChannelType.GuildLinkExtended)
994
+ return new LinkChannel(client, data);
995
+ return new GuildChannel(client, data);
996
+ }
997
+ /**
998
+ * Create a channel from API data, including DM and GroupDM.
999
+ * Used by ChannelManager.fetch() for GET /channels/{id}.
1000
+ */
1001
+ static fromOrCreate(client, data) {
1002
+ const type = data.type ?? 0;
1003
+ if (type === import_types5.ChannelType.DM || type === import_types5.ChannelType.GroupDM)
1004
+ return _Channel.createDM(client, data);
1005
+ return _Channel.from(client, data);
1006
+ }
1007
+ /**
1008
+ * Bulk delete messages. Requires Manage Messages permission.
1009
+ * @param messageIds - Array of message IDs to delete (2–100)
1010
+ */
1011
+ async bulkDeleteMessages(messageIds) {
1012
+ await this.client.rest.post(import_types5.Routes.channelBulkDelete(this.id), {
1013
+ body: { message_ids: messageIds },
1014
+ auth: true
1015
+ });
1016
+ }
1017
+ /**
1018
+ * Send a typing indicator to the channel. Lasts ~10 seconds.
1019
+ */
1020
+ async sendTyping() {
1021
+ await this.client.rest.post(import_types5.Routes.channelTyping(this.id), { auth: true });
1022
+ }
1023
+ /**
1024
+ * Whether the bot can send messages in this channel.
1025
+ * For DMs: always true (when the channel exists).
1026
+ * For guild channels: checks ViewChannel and SendMessages permissions via guild.members.me.
1027
+ */
1028
+ canSendMessage() {
1029
+ if (this.isDM()) return true;
1030
+ return false;
1031
+ }
1032
+ };
1033
+ var GuildChannel = class extends Channel {
1034
+ guildId;
1035
+ name;
1036
+ position;
1037
+ parentId;
1038
+ /** Permission overwrites for roles and members. */
1039
+ permissionOverwrites;
1040
+ constructor(client, data) {
1041
+ super(client, data);
1042
+ this.guildId = data.guild_id ?? "";
1043
+ this.name = data.name ?? null;
1044
+ this.position = data.position;
1045
+ this.parentId = data.parent_id ?? null;
1046
+ this.permissionOverwrites = data.permission_overwrites ?? [];
1047
+ }
1048
+ /**
1049
+ * Create a webhook in this channel.
1050
+ * @param options - Webhook name and optional avatar URL
1051
+ * @returns The webhook with token (required for send()). Requires Manage Webhooks permission.
1052
+ */
1053
+ async createWebhook(options) {
1054
+ const data = await this.client.rest.post(import_types5.Routes.channelWebhooks(this.id), {
1055
+ body: options,
1056
+ auth: true
1057
+ });
1058
+ return new Webhook(this.client, data);
1059
+ }
1060
+ /**
1061
+ * Fetch all webhooks in this channel.
1062
+ * @returns Webhooks (includes token when listing from channel; can send via send())
1063
+ */
1064
+ async fetchWebhooks() {
1065
+ const data = await this.client.rest.get(import_types5.Routes.channelWebhooks(this.id));
1066
+ const list = Array.isArray(data) ? data : Object.values(data ?? {});
1067
+ return list.map((w) => new Webhook(this.client, w));
1068
+ }
1069
+ /**
1070
+ * Create an invite for this channel.
1071
+ * @param options - max_uses (0–100), max_age (0–604800 seconds), unique, temporary
1072
+ * Requires Create Instant Invite permission.
1073
+ */
1074
+ async createInvite(options) {
1075
+ const body = {};
1076
+ if (options?.max_uses != null) body.max_uses = options.max_uses;
1077
+ if (options?.max_age != null) body.max_age = options.max_age;
1078
+ if (options?.unique != null) body.unique = options.unique;
1079
+ if (options?.temporary != null) body.temporary = options.temporary;
1080
+ const data = await this.client.rest.post(import_types5.Routes.channelInvites(this.id), {
1081
+ body: Object.keys(body).length ? body : void 0,
1082
+ auth: true
1083
+ });
1084
+ return new Invite(this.client, data);
1085
+ }
1086
+ /**
1087
+ * Fetch invites for this channel.
1088
+ * Requires Manage Channel permission.
1089
+ */
1090
+ async fetchInvites() {
1091
+ const data = await this.client.rest.get(import_types5.Routes.channelInvites(this.id));
1092
+ const list = Array.isArray(data) ? data : Object.values(data ?? {});
1093
+ return list.map((i) => new Invite(this.client, i));
1094
+ }
1095
+ /**
1096
+ * Set or update a permission overwrite. PUT /channels/{id}/permissions/{overwriteId}.
1097
+ * @param overwriteId - Role or member ID
1098
+ * @param options - type (0=role, 1=member), allow, deny (permission bitfields)
1099
+ */
1100
+ async editPermission(overwriteId, options) {
1101
+ await this.client.rest.put(import_types5.Routes.channelPermission(this.id, overwriteId), {
1102
+ body: options,
1103
+ auth: true
1104
+ });
1105
+ const idx = this.permissionOverwrites.findIndex((o) => o.id === overwriteId);
1106
+ const entry = {
1107
+ id: overwriteId,
1108
+ type: options.type,
1109
+ allow: options.allow ?? "0",
1110
+ deny: options.deny ?? "0"
1111
+ };
1112
+ if (idx >= 0) this.permissionOverwrites[idx] = entry;
1113
+ else this.permissionOverwrites.push(entry);
1114
+ }
1115
+ /**
1116
+ * Whether the bot can send messages in this channel.
1117
+ * Checks ViewChannel and SendMessages via guild.members.me permissions.
1118
+ * Returns false if guild or bot member not cached.
1119
+ */
1120
+ canSendMessage() {
1121
+ const guild = this.client.guilds.get(this.guildId);
1122
+ if (!guild) return false;
1123
+ const me = guild.members.me;
1124
+ if (!me) return false;
1125
+ const perms = me.permissionsIn(this);
1126
+ return perms.has(import_util3.PermissionFlags.ViewChannel) && perms.has(import_util3.PermissionFlags.SendMessages);
1127
+ }
1128
+ /**
1129
+ * Send a message to this guild channel.
1130
+ * Works for text and announcement channels. Voice/category/link channels will fail at the API.
1131
+ */
1132
+ async send(options) {
1133
+ const opts = typeof options === "string" ? { content: options } : options;
1134
+ const body = buildSendBody(options);
1135
+ const files = opts.files?.length ? await resolveMessageFiles(opts.files) : void 0;
1136
+ const postOptions = files?.length ? { body, files } : { body };
1137
+ const data = await this.client.rest.post(import_types5.Routes.channelMessages(this.id), postOptions);
1138
+ this.client._addMessageToCache(this.id, data);
1139
+ return new Message(this.client, data);
1140
+ }
1141
+ /**
1142
+ * Remove a permission overwrite. DELETE /channels/{id}/permissions/{overwriteId}.
1143
+ */
1144
+ async deletePermission(overwriteId) {
1145
+ await this.client.rest.delete(import_types5.Routes.channelPermission(this.id, overwriteId), { auth: true });
1146
+ const idx = this.permissionOverwrites.findIndex((o) => o.id === overwriteId);
1147
+ if (idx >= 0) this.permissionOverwrites.splice(idx, 1);
1148
+ }
1149
+ /**
1150
+ * Edit this channel. PATCH /channels/{id}.
1151
+ * Requires Manage Channel permission.
1152
+ */
1153
+ async edit(options) {
1154
+ const data = await this.client.rest.patch(import_types5.Routes.channel(this.id), {
1155
+ body: options,
1156
+ auth: true
1157
+ });
1158
+ this.name = data.name ?? this.name;
1159
+ this.parentId = data.parent_id ?? this.parentId;
1160
+ this.permissionOverwrites = data.permission_overwrites ?? this.permissionOverwrites;
1161
+ const self = this;
1162
+ if ("topic" in self && "topic" in data) self.topic = data.topic ?? null;
1163
+ if ("nsfw" in self && "nsfw" in data) self.nsfw = data.nsfw ?? false;
1164
+ if ("rate_limit_per_user" in data) self.rateLimitPerUser = data.rate_limit_per_user ?? 0;
1165
+ if ("bitrate" in self && "bitrate" in data) self.bitrate = data.bitrate ?? null;
1166
+ if ("user_limit" in data) self.userLimit = data.user_limit ?? null;
1167
+ if ("rtc_region" in data) self.rtcRegion = data.rtc_region ?? null;
1168
+ return this;
1169
+ }
1170
+ /**
1171
+ * Delete this channel. Requires Manage Channel permission.
1172
+ * @param options - silent: if true, does not send a system message (default false)
1173
+ */
1174
+ async delete(options) {
1175
+ const url = import_types5.Routes.channel(this.id) + (options?.silent ? "?silent=true" : "");
1176
+ await this.client.rest.delete(url, { auth: true });
1177
+ this.client.channels.delete(this.id);
1178
+ const guild = this.client.guilds.get(this.guildId);
1179
+ if (guild) guild.channels.delete(this.id);
1180
+ }
1181
+ };
1182
+ var TextChannel = class extends GuildChannel {
1183
+ topic;
1184
+ nsfw;
1185
+ rateLimitPerUser;
1186
+ lastMessageId;
1187
+ constructor(client, data) {
1188
+ super(client, data);
1189
+ this.topic = data.topic ?? null;
1190
+ this.nsfw = data.nsfw ?? false;
1191
+ this.rateLimitPerUser = data.rate_limit_per_user ?? 0;
1192
+ this.lastMessageId = data.last_message_id ?? null;
1193
+ }
1194
+ /**
1195
+ * Send a message to this channel.
1196
+ * @param options - Text content or object with content, embeds, and/or files
1197
+ */
1198
+ async send(options) {
1199
+ const opts = typeof options === "string" ? { content: options } : options;
1200
+ const body = buildSendBody(options);
1201
+ const files = opts.files?.length ? await resolveMessageFiles(opts.files) : void 0;
1202
+ const postOptions = files?.length ? { body, files } : { body };
1203
+ const data = await this.client.rest.post(import_types5.Routes.channelMessages(this.id), postOptions);
1204
+ this.client._addMessageToCache(this.id, data);
1205
+ return new Message(this.client, data);
1206
+ }
1207
+ /** Message manager for this channel. Use channel.messages.fetch(messageId). */
1208
+ get messages() {
1209
+ return new MessageManager(this.client, this.id);
1210
+ }
1211
+ /**
1212
+ * Create a message collector for this channel.
1213
+ * Collects messages matching the filter until time expires or max is reached.
1214
+ * @param options - Filter, time (ms), and max count
1215
+ * @example
1216
+ * const collector = channel.createMessageCollector({ filter: m => m.author.id === userId, time: 10000 });
1217
+ * collector.on('collect', m => console.log(m.content));
1218
+ * collector.on('end', (collected, reason) => { ... });
1219
+ */
1220
+ createMessageCollector(options) {
1221
+ return new MessageCollector(this.client, this.id, options);
1222
+ }
1223
+ /**
1224
+ * Fetch pinned messages in this channel.
1225
+ * @returns Pinned messages
1226
+ */
1227
+ async fetchPinnedMessages() {
1228
+ const data = await this.client.rest.get(import_types5.Routes.channelPins(this.id));
1229
+ const list = Array.isArray(data) ? data : data?.items ?? [];
1230
+ return list.map((item) => {
1231
+ const msg = typeof item === "object" && item && "message" in item ? item.message : item;
1232
+ return new Message(this.client, msg);
1233
+ });
1234
+ }
1235
+ /**
1236
+ * Fetch a message by ID from this channel.
1237
+ * @param messageId - Snowflake of the message
1238
+ * @returns The message, or null if not found
1239
+ * @deprecated Use channel.messages.fetch(messageId) instead.
1240
+ */
1241
+ async fetchMessage(messageId) {
1242
+ (0, import_util4.emitDeprecationWarning)(
1243
+ "Channel.fetchMessage()",
1244
+ "Use channel.messages.fetch(messageId) instead."
1245
+ );
1246
+ return this.client.channels.fetchMessage(this.id, messageId);
1247
+ }
1248
+ };
1249
+ var CategoryChannel = class extends GuildChannel {
1250
+ };
1251
+ var VoiceChannel = class extends GuildChannel {
1252
+ bitrate;
1253
+ userLimit;
1254
+ rtcRegion;
1255
+ constructor(client, data) {
1256
+ super(client, data);
1257
+ this.bitrate = data.bitrate ?? null;
1258
+ this.userLimit = data.user_limit ?? null;
1259
+ this.rtcRegion = data.rtc_region ?? null;
1260
+ }
1261
+ };
1262
+ var LinkChannel = class extends GuildChannel {
1263
+ url;
1264
+ constructor(client, data) {
1265
+ super(client, data);
1266
+ this.url = data.url ?? null;
1267
+ }
1268
+ };
1269
+ var DMChannel = class extends Channel {
1270
+ lastMessageId;
1271
+ /** Group DM creator ID. Null for 1:1 DMs. */
1272
+ ownerId;
1273
+ /** Group DM recipients as User objects. Empty for 1:1 DMs. */
1274
+ recipients;
1275
+ /** Group DM member display names (userId -> nickname). */
1276
+ nicks;
1277
+ constructor(client, data) {
1278
+ super(client, data);
1279
+ this.lastMessageId = data.last_message_id ?? null;
1280
+ this.ownerId = data.owner_id ?? null;
1281
+ this.recipients = (data.recipients ?? []).map(
1282
+ (u) => client.getOrCreateUser(u)
1283
+ );
1284
+ this.nicks = data.nicks ?? {};
1285
+ }
1286
+ /**
1287
+ * Send a message to this DM channel.
1288
+ * @param options - Text content or object with content, embeds, and/or files
1289
+ */
1290
+ async send(options) {
1291
+ const opts = typeof options === "string" ? { content: options } : options;
1292
+ const body = buildSendBody(options);
1293
+ const files = opts.files?.length ? await resolveMessageFiles(opts.files) : void 0;
1294
+ const postOptions = files?.length ? { body, files } : { body };
1295
+ const data = await this.client.rest.post(import_types5.Routes.channelMessages(this.id), postOptions);
1296
+ this.client._addMessageToCache(this.id, data);
1297
+ return new Message(this.client, data);
1298
+ }
1299
+ /** Message manager for this channel. Use channel.messages.fetch(messageId). */
1300
+ get messages() {
1301
+ return new MessageManager(this.client, this.id);
1302
+ }
1303
+ /**
1304
+ * Create a message collector for this DM channel.
1305
+ * @param options - Filter, time (ms), and max count
1306
+ */
1307
+ createMessageCollector(options) {
1308
+ return new MessageCollector(this.client, this.id, options);
1309
+ }
1310
+ /**
1311
+ * Fetch pinned messages in this DM channel.
1312
+ * @returns Pinned messages
1313
+ */
1314
+ async fetchPinnedMessages() {
1315
+ const data = await this.client.rest.get(import_types5.Routes.channelPins(this.id));
1316
+ const list = Array.isArray(data) ? data : data?.items ?? [];
1317
+ return list.map((item) => {
1318
+ const msg = typeof item === "object" && item && "message" in item ? item.message : item;
1319
+ return new Message(this.client, msg);
1320
+ });
1321
+ }
1322
+ /**
1323
+ * Fetch a message by ID from this DM channel.
1324
+ * @param messageId - Snowflake of the message
1325
+ * @returns The message, or null if not found
1326
+ * @deprecated Use channel.messages.fetch(messageId) instead.
1327
+ */
1328
+ async fetchMessage(messageId) {
1329
+ (0, import_util4.emitDeprecationWarning)(
1330
+ "Channel.fetchMessage()",
1331
+ "Use channel.messages.fetch(messageId) instead."
1332
+ );
1333
+ return this.client.channels.fetchMessage(this.id, messageId);
1334
+ }
1335
+ /**
1336
+ * Add a recipient to this Group DM. Requires Group DM (type GroupDM).
1337
+ * PUT /channels/{id}/recipients/{userId}.
1338
+ */
1339
+ async addRecipient(userId) {
1340
+ await this.client.rest.put(import_types5.Routes.channelRecipient(this.id, userId), { auth: true });
1341
+ const user = this.client.users.get(userId) ?? await this.client.users.fetch(userId);
1342
+ if (user) this.recipients.push(user);
1343
+ }
1344
+ /**
1345
+ * Remove a recipient from this Group DM. Requires Group DM (type GroupDM).
1346
+ * DELETE /channels/{id}/recipients/{userId}.
1347
+ * @param options - silent: if true, does not send a system message (default false)
1348
+ */
1349
+ async removeRecipient(userId, options) {
1350
+ const url = import_types5.Routes.channelRecipient(this.id, userId) + (options?.silent ? "?silent=true" : "");
1351
+ await this.client.rest.delete(url, { auth: true });
1352
+ const idx = this.recipients.findIndex((u) => u.id === userId);
1353
+ if (idx >= 0) this.recipients.splice(idx, 1);
1354
+ }
1355
+ };
1356
+
1357
+ // src/client/ChannelManager.ts
1358
+ var ChannelManager = class extends import_collection4.Collection {
1359
+ constructor(client) {
1360
+ super();
1361
+ this.client = client;
1362
+ this.maxSize = client.options?.cache?.channels ?? 0;
1363
+ }
1364
+ maxSize;
1365
+ set(key, value) {
1366
+ if (this.maxSize > 0 && this.size >= this.maxSize && !this.has(key)) {
1367
+ const firstKey = this.keys().next().value;
1368
+ if (firstKey !== void 0) this.delete(firstKey);
1369
+ }
1370
+ return super.set(key, value);
1371
+ }
1372
+ /**
1373
+ * Get a channel from cache or fetch from the API if not present.
1374
+ * Convenience helper to avoid repeating `client.channels.get(id) ?? (await client.channels.fetch(id))`.
1375
+ * @param channelId - Snowflake of the channel
1376
+ * @returns The channel
1377
+ * @throws FluxerError with CHANNEL_NOT_FOUND if the channel does not exist
1378
+ * @example
1379
+ * const channel = await client.channels.resolve(message.channelId);
1380
+ * if (channel?.isTextBased()) await channel.send('Hello!');
1381
+ */
1382
+ async resolve(channelId) {
1383
+ return this.get(channelId) ?? this.fetch(channelId);
1384
+ }
1385
+ /**
1386
+ * Fetch a channel by ID from the API (or return from cache if present).
1387
+ * @param channelId - Snowflake of the channel
1388
+ * @returns The channel
1389
+ * @throws FluxerError with CHANNEL_NOT_FOUND if the channel does not exist
1390
+ * @example
1391
+ * const channel = await client.channels.fetch(channelId);
1392
+ * if (channel?.isTextBased()) await channel.send('Hello!');
1393
+ */
1394
+ async fetch(channelId) {
1395
+ const cached = this.get(channelId);
1396
+ if (cached) return cached;
1397
+ try {
1398
+ const data = await this.client.rest.get(import_types6.Routes.channel(channelId));
1399
+ const channel = Channel.fromOrCreate(this.client, data);
1400
+ if (!channel) {
1401
+ throw new import_util.FluxerError("Channel data invalid or unsupported type", {
1402
+ code: import_util2.ErrorCodes.ChannelNotFound
1403
+ });
1404
+ }
1405
+ this.set(channel.id, channel);
1406
+ if ("guildId" in channel) {
1407
+ const guild = this.client.guilds.get(channel.guildId);
1408
+ if (guild) guild.channels.set(channel.id, channel);
1409
+ }
1410
+ return channel;
1411
+ } catch (err) {
1412
+ if (err instanceof import_rest2.RateLimitError) throw err;
1413
+ if (err instanceof import_rest2.FluxerAPIError && err.statusCode === 404) {
1414
+ throw new import_util.FluxerError(`Channel ${channelId} not found`, {
1415
+ code: import_util2.ErrorCodes.ChannelNotFound,
1416
+ cause: err
1417
+ });
1418
+ }
1419
+ throw err instanceof import_util.FluxerError ? err : new import_util.FluxerError(String(err), { cause: err });
1420
+ }
1421
+ }
1422
+ /**
1423
+ * Fetch a message by ID from the API.
1424
+ * @param channelId - Snowflake of the channel
1425
+ * @param messageId - Snowflake of the message
1426
+ * @returns The message
1427
+ * @throws FluxerError with MESSAGE_NOT_FOUND if the message does not exist
1428
+ * @deprecated Use channel.messages.fetch(messageId). Prefer (await client.channels.resolve(channelId))?.messages?.fetch(messageId).
1429
+ * @example
1430
+ * const channel = await client.channels.resolve(channelId);
1431
+ * const message = await channel?.messages?.fetch(messageId);
1432
+ */
1433
+ async fetchMessage(channelId, messageId) {
1434
+ (0, import_util5.emitDeprecationWarning)(
1435
+ "ChannelManager.fetchMessage()",
1436
+ "Use channel.messages.fetch(messageId). Prefer (await client.channels.resolve(channelId))?.messages?.fetch(messageId)."
1437
+ );
1438
+ try {
1439
+ const data = await this.client.rest.get(
1440
+ import_types6.Routes.channelMessage(channelId, messageId)
1441
+ );
1442
+ return new Message(this.client, data);
1443
+ } catch (err) {
1444
+ if (err instanceof import_rest2.RateLimitError) throw err;
1445
+ if (err instanceof import_rest2.FluxerAPIError && err.statusCode === 404) {
1446
+ throw new import_util.FluxerError(`Message ${messageId} not found in channel ${channelId}`, {
1447
+ code: import_util2.ErrorCodes.MessageNotFound,
1448
+ cause: err
1449
+ });
1450
+ }
1451
+ throw err instanceof import_util.FluxerError ? err : new import_util.FluxerError(String(err), { cause: err });
1452
+ }
1453
+ }
1454
+ /**
1455
+ * Send a message to a channel by ID. Works even when the channel is not cached.
1456
+ * Skips the fetch when you only need to send.
1457
+ * @param channelId - Snowflake of the channel (text channel or DM)
1458
+ * @param payload - Text content or object with content, embeds, and/or files
1459
+ * @returns The created message
1460
+ * @example
1461
+ * await client.channels.send(logChannelId, 'User joined!');
1462
+ * await client.channels.send(channelId, { embeds: [embed] });
1463
+ * await client.channels.send(channelId, { content: 'Report', files: [{ name: 'log.txt', data }] });
1464
+ */
1465
+ async send(channelId, payload) {
1466
+ const opts = typeof payload === "string" ? { content: payload } : payload;
1467
+ const body = buildSendBody(payload);
1468
+ const files = opts.files?.length ? await resolveMessageFiles(opts.files) : void 0;
1469
+ const postOptions = files?.length ? { body, files } : { body };
1470
+ const data = await this.client.rest.post(import_types6.Routes.channelMessages(channelId), postOptions);
1471
+ this.client._addMessageToCache(channelId, data);
1472
+ return new Message(this.client, data);
1473
+ }
1474
+ };
1475
+
1476
+ // src/client/GuildManager.ts
1477
+ var import_collection8 = require("@fluxerjs/collection");
1478
+ var import_types16 = require("@fluxerjs/types");
1479
+
1480
+ // src/structures/Guild.ts
1481
+ var import_util9 = require("@fluxerjs/util");
1482
+ var import_rest3 = require("@fluxerjs/rest");
1483
+ var import_collection7 = require("@fluxerjs/collection");
1484
+
1485
+ // src/client/GuildMemberManager.ts
1486
+ var import_collection6 = require("@fluxerjs/collection");
1487
+ var import_types10 = require("@fluxerjs/types");
1488
+
1489
+ // src/structures/GuildMember.ts
1490
+ var import_util7 = require("@fluxerjs/util");
1491
+ var import_types9 = require("@fluxerjs/types");
1492
+
1493
+ // src/util/permissions.ts
1494
+ var import_types7 = require("@fluxerjs/types");
1495
+ var import_util6 = require("@fluxerjs/util");
1496
+ function computePermissions(basePermissions, overwrites, memberRoles, memberId, isOwner) {
1497
+ if (isOwner) return import_util6.ALL_PERMISSIONS_BIGINT;
1498
+ let perms = basePermissions;
1499
+ for (const overwrite of overwrites ?? []) {
1500
+ const applies = overwrite.type === import_types7.OverwriteType.Role && memberRoles.includes(overwrite.id) || overwrite.type === import_types7.OverwriteType.Member && overwrite.id === memberId;
1501
+ if (!applies) continue;
1502
+ const allow = BigInt(overwrite.allow || "0");
1503
+ const deny = BigInt(overwrite.deny || "0");
1504
+ perms = perms & ~deny | allow;
1505
+ }
1506
+ return (perms & import_util6.PermissionFlags.Administrator) !== 0n ? import_util6.ALL_PERMISSIONS_BIGINT : perms;
1507
+ }
1508
+
1509
+ // src/structures/GuildMemberRoleManager.ts
1510
+ var import_collection5 = require("@fluxerjs/collection");
1511
+ var import_types8 = require("@fluxerjs/types");
1512
+ var GuildMemberRoleManager = class {
1513
+ constructor(member, initialRoleIds = []) {
1514
+ this.member = member;
1515
+ this._roleIds = [...initialRoleIds];
1516
+ }
1517
+ _roleIds = [];
1518
+ /** Role IDs for this member. Used by permissions; prefer cache for Role objects. */
1519
+ get roleIds() {
1520
+ return this._roleIds;
1521
+ }
1522
+ /** Check if the member has a role. Discord.js parity: member.roles.cache.has(roleId) */
1523
+ has(roleOrId) {
1524
+ return this._roleIds.includes(this._resolveId(roleOrId));
1525
+ }
1526
+ /**
1527
+ * Collection of Role objects for this member's roles (from guild.roles).
1528
+ * Discord.js parity: member.roles.cache
1529
+ * @discordJsCompat https://discord.js.org/docs/packages/discord.js/main/GuildMemberRoleManager
1530
+ */
1531
+ get cache() {
1532
+ const coll = new import_collection5.Collection();
1533
+ for (const id of this._roleIds) {
1534
+ const role = this.member.guild.roles.get(id);
1535
+ if (role) coll.set(id, role);
1536
+ }
1537
+ return coll;
1538
+ }
1539
+ /** Resolve role ID from RoleResolvable. */
1540
+ _resolveId(roleOrId) {
1541
+ return typeof roleOrId === "string" ? roleOrId : roleOrId.id;
1542
+ }
1543
+ /**
1544
+ * Add a role to this member.
1545
+ * Discord.js parity: member.roles.add(roleId)
1546
+ * Requires Manage Roles permission.
1547
+ * @discordJsCompat https://discord.js.org/docs/packages/discord.js/main/GuildMemberRoleManager
1548
+ */
1549
+ async add(roleOrId) {
1550
+ const roleId = this._resolveId(roleOrId);
1551
+ if (this._roleIds.includes(roleId)) return;
1552
+ await this.member.client.rest.put(
1553
+ import_types8.Routes.guildMemberRole(this.member.guild.id, this.member.id, roleId)
1554
+ );
1555
+ this._roleIds.push(roleId);
1556
+ }
1557
+ /**
1558
+ * Remove a role from this member.
1559
+ * Discord.js parity: member.roles.remove(roleId)
1560
+ * Requires Manage Roles permission.
1561
+ * @discordJsCompat https://discord.js.org/docs/packages/discord.js/main/GuildMemberRoleManager
1562
+ */
1563
+ async remove(roleOrId) {
1564
+ const roleId = this._resolveId(roleOrId);
1565
+ const idx = this._roleIds.indexOf(roleId);
1566
+ if (idx === -1) return;
1567
+ await this.member.client.rest.delete(
1568
+ import_types8.Routes.guildMemberRole(this.member.guild.id, this.member.id, roleId)
1569
+ );
1570
+ this._roleIds.splice(idx, 1);
1571
+ }
1572
+ /**
1573
+ * Replace all roles for this member. PATCH /guilds/{id}/members/{userId}
1574
+ * Discord.js parity: member.roles.set(roleIds)
1575
+ * Requires Manage Roles permission.
1576
+ * @discordJsCompat https://discord.js.org/docs/packages/discord.js/main/GuildMemberRoleManager
1577
+ */
1578
+ async set(roleIds) {
1579
+ const data = await this.member.client.rest.patch(
1580
+ import_types8.Routes.guildMember(this.member.guild.id, this.member.id),
1581
+ { body: { roles: roleIds }, auth: true }
1582
+ );
1583
+ this._roleIds = data.roles ? [...data.roles] : [];
1584
+ }
1585
+ /**
1586
+ * Update internal role IDs from API response. Called by GuildMember.edit().
1587
+ * @internal
1588
+ */
1589
+ _patch(roleIds) {
1590
+ this._roleIds = [...roleIds];
1591
+ }
1592
+ };
1593
+
1594
+ // src/structures/GuildMember.ts
1595
+ var GuildMember = class extends Base {
1596
+ client;
1597
+ id;
1598
+ user;
1599
+ guild;
1600
+ nick;
1601
+ /**
1602
+ * Role manager with add/remove/set and cache. Discord.js parity: member.roles.add(), member.roles.cache
1603
+ * @discordJsCompat https://discord.js.org/docs/packages/discord.js/main/GuildMemberRoleManager
1604
+ */
1605
+ roles;
1606
+ joinedAt;
1607
+ communicationDisabledUntil;
1608
+ mute;
1609
+ deaf;
1610
+ avatar;
1611
+ banner;
1612
+ accentColor;
1613
+ profileFlags;
1614
+ /** @param data - API guild member from GET /guilds/{id}/members or GET /guilds/{id}/members/{user_id} */
1615
+ constructor(client, data, guild) {
1616
+ super();
1617
+ this.client = client;
1618
+ this.user = client.getOrCreateUser(data.user);
1619
+ this.id = data.user.id;
1620
+ this.guild = guild;
1621
+ this.nick = data.nick ?? null;
1622
+ this.roles = new GuildMemberRoleManager(this, data.roles ?? []);
1623
+ this.joinedAt = new Date(data.joined_at);
1624
+ this.communicationDisabledUntil = data.communication_disabled_until ? new Date(data.communication_disabled_until) : null;
1625
+ this.mute = data.mute ?? false;
1626
+ this.deaf = data.deaf ?? false;
1627
+ this.avatar = data.avatar ?? null;
1628
+ this.banner = data.banner ?? null;
1629
+ this.accentColor = data.accent_color ?? null;
1630
+ this.profileFlags = data.profile_flags ?? null;
1631
+ }
1632
+ /** Nickname, or global name, or username. */
1633
+ get displayName() {
1634
+ return this.nick ?? this.user.globalName ?? this.user.username;
1635
+ }
1636
+ /**
1637
+ * Get the guild-specific avatar URL for this member.
1638
+ * Returns null if the member has no guild avatar (use displayAvatarURL for fallback).
1639
+ */
1640
+ avatarURL(options) {
1641
+ return cdnMemberAvatarURL(this.guild.id, this.id, this.avatar, options);
1642
+ }
1643
+ /**
1644
+ * Get the avatar URL to display for this member.
1645
+ * Uses guild-specific avatar if set, otherwise falls back to the user's avatar.
1646
+ */
1647
+ displayAvatarURL(options) {
1648
+ return this.avatarURL(options) ?? this.user.displayAvatarURL(options);
1649
+ }
1650
+ /**
1651
+ * Get the guild-specific banner URL for this member.
1652
+ * Returns null if the member has no guild banner.
1653
+ */
1654
+ bannerURL(options) {
1655
+ return cdnMemberBannerURL(this.guild.id, this.id, this.banner, options);
1656
+ }
1657
+ /**
1658
+ * Add a role to this member.
1659
+ * Prefer member.roles.add(roleId) for Discord.js parity.
1660
+ * @param roleId - The role ID to add
1661
+ * Requires Manage Roles permission.
1662
+ */
1663
+ async addRole(roleId) {
1664
+ await this.roles.add(roleId);
1665
+ }
1666
+ /**
1667
+ * Remove a role from this member.
1668
+ * Prefer member.roles.remove(roleId) for Discord.js parity.
1669
+ * @param roleId - The role ID to remove
1670
+ * Requires Manage Roles permission.
1671
+ */
1672
+ async removeRole(roleId) {
1673
+ await this.roles.remove(roleId);
1674
+ }
1675
+ /**
1676
+ * Edit this guild member. PATCH /guilds/{id}/members/{userId} or /members/@me for the bot.
1677
+ * For @me: nick, avatar, banner, bio, pronouns, accent_color, profile_flags, mute, deaf,
1678
+ * communication_disabled_until, timeout_reason, channel_id, connection_id.
1679
+ * For other members: same plus roles (array of role IDs).
1680
+ */
1681
+ async edit(options) {
1682
+ const isMe = this.client.user?.id === this.id;
1683
+ const route = isMe ? `/guilds/${this.guild.id}/members/@me` : import_types9.Routes.guildMember(this.guild.id, this.id);
1684
+ const data = await this.client.rest.patch(route, {
1685
+ body: options,
1686
+ auth: true
1687
+ });
1688
+ this.nick = data.nick ?? this.nick;
1689
+ if (data.roles) this.roles._patch(data.roles);
1690
+ if (data.communication_disabled_until != null) {
1691
+ this.communicationDisabledUntil = data.communication_disabled_until ? new Date(data.communication_disabled_until) : null;
1692
+ }
1693
+ return this;
1694
+ }
1695
+ /**
1696
+ * Get the member's guild-level permissions (from roles only, no channel overwrites).
1697
+ * Use this for server-wide permission checks (e.g. ban, kick, manage roles).
1698
+ * @returns Object with has(permission) to check specific permissions
1699
+ * @example
1700
+ * const perms = member.permissions;
1701
+ * if (perms.has(PermissionFlags.BanMembers)) { ... }
1702
+ */
1703
+ get permissions() {
1704
+ const base = this._computeBasePermissions();
1705
+ const ownerId = this.guild.ownerId;
1706
+ const isOwner = ownerId != null && ownerId !== "" && String(ownerId) === String(this.id);
1707
+ const perms = computePermissions(base, [], [], this.id, isOwner);
1708
+ return new import_util7.BitField(perms);
1709
+ }
1710
+ /**
1711
+ * Compute the member's effective permissions in a guild channel.
1712
+ * Applies role permissions and channel overwrites.
1713
+ * @param channel - The guild channel to check permissions for
1714
+ * @returns Object with has(permission) to check specific permissions
1715
+ * @example
1716
+ * const perms = member.permissionsIn(channel);
1717
+ * if (perms.has(PermissionFlags.SendMessages)) { ... }
1718
+ */
1719
+ permissionsIn(channel) {
1720
+ const base = this._computeBasePermissions();
1721
+ const ownerId = this.guild.ownerId;
1722
+ const isOwner = ownerId != null && ownerId !== "" && String(ownerId) === String(this.id);
1723
+ const perms = computePermissions(
1724
+ base,
1725
+ channel.permissionOverwrites,
1726
+ [...this.roles.roleIds],
1727
+ this.id,
1728
+ isOwner
1729
+ );
1730
+ return new import_util7.BitField(perms);
1731
+ }
1732
+ /**
1733
+ * Move this member to a different voice channel or disconnect them from voice.
1734
+ * Requires Move Members permission.
1735
+ * @param channelId - The voice channel ID to move the member to, or null to disconnect
1736
+ * @param connectionId - Optional connection ID for the specific voice session (usually not needed)
1737
+ * @returns Promise that resolves when the member has been moved
1738
+ * @example
1739
+ * // Move member to a different voice channel
1740
+ * await member.move('123456789012345678');
1741
+ *
1742
+ * // Disconnect member from voice
1743
+ * await member.move(null);
1744
+ */
1745
+ async move(channelId, connectionId) {
1746
+ await this.edit({
1747
+ channel_id: channelId,
1748
+ connection_id: connectionId
1749
+ });
1750
+ }
1751
+ _computeBasePermissions() {
1752
+ let base = 0n;
1753
+ const everyone = this.guild.roles.get(this.guild.id);
1754
+ if (everyone) base |= everyone.permissions.bitfield;
1755
+ for (const roleId of this.roles.roleIds) {
1756
+ if (roleId === this.guild.id) continue;
1757
+ const role = this.guild.roles.get(roleId);
1758
+ if (role) base |= role.permissions.bitfield;
1759
+ }
1760
+ return base;
1761
+ }
1762
+ };
1763
+
1764
+ // src/client/GuildMemberManager.ts
1765
+ var GuildMemberManager = class extends import_collection6.Collection {
1766
+ constructor(guild) {
1767
+ super();
1768
+ this.guild = guild;
1769
+ }
1770
+ /**
1771
+ * Get a guild member from cache or fetch from the API if not present.
1772
+ * Convenience helper to avoid repeating `guild.members.get(userId) ?? (await guild.fetchMember(userId))`.
1773
+ * @param userId - Snowflake of the user
1774
+ * @returns The guild member
1775
+ * @throws FluxerError with MEMBER_NOT_FOUND if user is not in the guild (404)
1776
+ * @example
1777
+ * const member = await guild.members.resolve(userId);
1778
+ * console.log(member.displayName);
1779
+ */
1780
+ async resolve(userId) {
1781
+ return this.get(userId) ?? this.guild.fetchMember(userId);
1782
+ }
1783
+ /**
1784
+ * The current bot user as a GuildMember in this guild.
1785
+ * Returns null if the bot's member is not cached or client.user is null.
1786
+ * Use fetchMe() to load the bot's member when not cached.
1787
+ *
1788
+ * @discordJsCompat https://discord.js.org/docs/packages/discord.js/main/GuildMemberManager
1789
+ * @example
1790
+ * const perms = guild.members.me?.permissions;
1791
+ * if (perms?.has(PermissionFlags.BanMembers)) { ... }
1792
+ */
1793
+ get me() {
1794
+ const userId = this.guild.client.user?.id;
1795
+ return userId ? this.get(userId) ?? null : null;
1796
+ }
1797
+ /**
1798
+ * Fetch the current bot user as a GuildMember in this guild.
1799
+ * Caches the result in guild.members.
1800
+ *
1801
+ * @throws FluxerError with CLIENT_NOT_READY if client.user is null
1802
+ * @example
1803
+ * const me = await guild.members.fetchMe();
1804
+ * console.log(me.displayName);
1805
+ */
1806
+ async fetchMe() {
1807
+ const userId = this.guild.client.user?.id;
1808
+ if (!userId) {
1809
+ throw new import_util.FluxerError("Cannot fetch me: client.user is null (client not ready)", {
1810
+ code: import_util2.ErrorCodes.ClientNotReady
1811
+ });
1812
+ }
1813
+ return this.guild.fetchMember(userId);
1814
+ }
1815
+ /**
1816
+ * Fetch guild members with pagination. GET /guilds/{id}/members.
1817
+ * @param options - limit (1-1000), after (user ID for pagination)
1818
+ * @returns Array of GuildMember objects (cached in guild.members)
1819
+ */
1820
+ async fetch(options) {
1821
+ const params = new URLSearchParams();
1822
+ if (options?.limit != null) params.set("limit", String(options.limit));
1823
+ if (options?.after) params.set("after", options.after);
1824
+ const qs = params.toString();
1825
+ const url = import_types10.Routes.guildMembers(this.guild.id) + (qs ? `?${qs}` : "");
1826
+ const data = await this.guild.client.rest.get(url, { auth: true });
1827
+ const list = Array.isArray(data) ? data : data?.members ?? [];
1828
+ const members = [];
1829
+ for (const m of list) {
1830
+ const member = new GuildMember(
1831
+ this.guild.client,
1832
+ { ...m, guild_id: this.guild.id },
1833
+ this.guild
1834
+ );
1835
+ this.set(member.id, member);
1836
+ members.push(member);
1837
+ }
1838
+ return members;
1839
+ }
1840
+ };
1841
+
1842
+ // src/structures/Role.ts
1843
+ var import_types11 = require("@fluxerjs/types");
1844
+ var import_util8 = require("@fluxerjs/util");
1845
+ var Role = class extends Base {
1846
+ client;
1847
+ id;
1848
+ guildId;
1849
+ name;
1850
+ color;
1851
+ position;
1852
+ _permissions;
1853
+ hoist;
1854
+ mentionable;
1855
+ unicodeEmoji;
1856
+ /** Separately sorted position for hoisted roles. Null if not set. */
1857
+ hoistPosition;
1858
+ /** @param client - The client instance */
1859
+ /** @param data - API role from GET /guilds/{id}/roles or gateway role events */
1860
+ /** @param guildId - The guild this role belongs to */
1861
+ constructor(client, data, guildId) {
1862
+ super();
1863
+ this.client = client;
1864
+ this.id = data.id;
1865
+ this.guildId = guildId;
1866
+ this.name = data.name;
1867
+ this.color = data.color;
1868
+ this.position = data.position;
1869
+ this._permissions = data.permissions;
1870
+ this.hoist = !!data.hoist;
1871
+ this.mentionable = !!data.mentionable;
1872
+ this.unicodeEmoji = data.unicode_emoji ?? null;
1873
+ this.hoistPosition = data.hoist_position ?? null;
1874
+ }
1875
+ get permissions() {
1876
+ const bits = BigInt(this._permissions);
1877
+ return new import_util8.PermissionsBitField(
1878
+ (bits & import_util8.PermissionFlags.Administrator) !== 0n ? import_util8.ALL_PERMISSIONS_BIGINT : bits
1879
+ );
1880
+ }
1881
+ /** Update mutable fields from fresh API data. Used by edit and gateway events. */
1882
+ _patch(data) {
1883
+ if (data.name !== void 0) this.name = data.name;
1884
+ if (data.color !== void 0) this.color = data.color;
1885
+ if (data.position !== void 0) this.position = data.position;
1886
+ if (data.permissions !== void 0) this._permissions = data.permissions;
1887
+ if (data.hoist !== void 0) this.hoist = !!data.hoist;
1888
+ if (data.mentionable !== void 0) this.mentionable = !!data.mentionable;
1889
+ if (data.unicode_emoji !== void 0) this.unicodeEmoji = data.unicode_emoji ?? null;
1890
+ if (data.hoist_position !== void 0) this.hoistPosition = data.hoist_position ?? null;
1891
+ }
1892
+ /** Returns a mention string (e.g. `<@&123456>`). */
1893
+ toString() {
1894
+ return `<@&${this.id}>`;
1895
+ }
1896
+ /**
1897
+ * Edit this role.
1898
+ * Requires Manage Roles permission.
1899
+ * @param options - Role updates (permissions accepts PermissionResolvable for convenience)
1900
+ * @returns This role (updated in place)
1901
+ * @example
1902
+ * await role.edit({ name: 'Moderator', permissions: ['BanMembers', 'KickMembers'] });
1903
+ */
1904
+ async edit(options) {
1905
+ const body = {};
1906
+ if (options.name !== void 0) body.name = options.name;
1907
+ if (options.permissions !== void 0) {
1908
+ body.permissions = typeof options.permissions === "string" ? options.permissions : (0, import_util8.resolvePermissionsToBitfield)(options.permissions);
1909
+ }
1910
+ if (options.color !== void 0) body.color = options.color;
1911
+ if (options.hoist !== void 0) body.hoist = options.hoist;
1912
+ if (options.mentionable !== void 0) body.mentionable = options.mentionable;
1913
+ if (options.unicode_emoji !== void 0) body.unicode_emoji = options.unicode_emoji;
1914
+ if (options.position !== void 0) body.position = options.position;
1915
+ if (options.hoist_position !== void 0) body.hoist_position = options.hoist_position;
1916
+ const data = await this.client.rest.patch(import_types11.Routes.guildRole(this.guildId, this.id), {
1917
+ body: Object.keys(body).length ? body : void 0,
1918
+ auth: true
1919
+ });
1920
+ this._patch(data);
1921
+ return this;
1922
+ }
1923
+ /**
1924
+ * Delete this role.
1925
+ * Requires Manage Roles permission.
1926
+ */
1927
+ async delete() {
1928
+ await this.client.rest.delete(import_types11.Routes.guildRole(this.guildId, this.id), { auth: true });
1929
+ const guild = this.client.guilds.get(this.guildId);
1930
+ if (guild) guild.roles.delete(this.id);
1931
+ }
1932
+ };
1933
+
1934
+ // src/structures/Guild.ts
1935
+ var import_types15 = require("@fluxerjs/types");
1936
+
1937
+ // src/structures/GuildBan.ts
1938
+ var import_types12 = require("@fluxerjs/types");
1939
+ var GuildBan = class extends Base {
1940
+ client;
1941
+ guildId;
1942
+ user;
1943
+ reason;
1944
+ /** ISO timestamp when a temporary ban expires. Null for permanent bans. */
1945
+ expiresAt;
1946
+ /** @param data - API ban from GET /guilds/{id}/bans or gateway GUILD_BAN_ADD */
1947
+ constructor(client, data, guildId) {
1948
+ super();
1949
+ this.client = client;
1950
+ this.guildId = data.guild_id ?? guildId;
1951
+ this.user = client.getOrCreateUser(data.user);
1952
+ this.reason = data.reason ?? null;
1953
+ this.expiresAt = data.expires_at ?? null;
1954
+ }
1955
+ /**
1956
+ * Remove this ban (unban the user).
1957
+ * Requires Ban Members permission.
1958
+ */
1959
+ async unban() {
1960
+ await this.client.rest.delete(import_types12.Routes.guildBan(this.guildId, this.user.id), {
1961
+ auth: true
1962
+ });
1963
+ }
1964
+ };
1965
+
1966
+ // src/structures/GuildEmoji.ts
1967
+ var import_types13 = require("@fluxerjs/types");
1968
+ var GuildEmoji = class extends Base {
1969
+ client;
1970
+ id;
1971
+ guildId;
1972
+ name;
1973
+ animated;
1974
+ /** @param data - API emoji from GET /guilds/{id}/emojis or guild emoji events */
1975
+ constructor(client, data, guildId) {
1976
+ super();
1977
+ this.client = client;
1978
+ this.id = data.id;
1979
+ this.guildId = data.guild_id ?? guildId;
1980
+ this.name = data.name;
1981
+ this.animated = data.animated ?? false;
1982
+ }
1983
+ /** CDN URL for this emoji image. */
1984
+ get url() {
1985
+ const ext = this.animated ? "gif" : "png";
1986
+ return `${CDN_URL}/emojis/${this.id}.${ext}`;
1987
+ }
1988
+ /** Emoji identifier for use in reactions: `name:id` */
1989
+ get identifier() {
1990
+ return `${this.name}:${this.id}`;
1991
+ }
1992
+ /** Delete this emoji. Requires Manage Emojis and Stickers permission. */
1993
+ async delete() {
1994
+ await this.client.rest.delete(import_types13.Routes.guildEmoji(this.guildId, this.id), {
1995
+ auth: true
1996
+ });
1997
+ const guild = this.client.guilds.get(this.guildId);
1998
+ if (guild) guild.emojis.delete(this.id);
1999
+ }
2000
+ /**
2001
+ * Edit this emoji's name.
2002
+ * Requires Manage Emojis and Stickers permission.
2003
+ */
2004
+ async edit(options) {
2005
+ const data = await this.client.rest.patch(import_types13.Routes.guildEmoji(this.guildId, this.id), {
2006
+ body: options,
2007
+ auth: true
2008
+ });
2009
+ this.name = data.name;
2010
+ return this;
2011
+ }
2012
+ };
2013
+
2014
+ // src/structures/GuildSticker.ts
2015
+ var import_types14 = require("@fluxerjs/types");
2016
+ var GuildSticker = class extends Base {
2017
+ client;
2018
+ id;
2019
+ guildId;
2020
+ name;
2021
+ description;
2022
+ tags;
2023
+ animated;
2024
+ /** @param data - API sticker from GET /guilds/{id}/stickers or guild sticker events */
2025
+ constructor(client, data, guildId) {
2026
+ super();
2027
+ this.client = client;
2028
+ this.id = data.id;
2029
+ this.guildId = data.guild_id ?? guildId;
2030
+ this.name = data.name;
2031
+ this.description = data.description ?? "";
2032
+ this.tags = data.tags ?? [];
2033
+ this.animated = data.animated ?? false;
2034
+ }
2035
+ /** CDN URL for this sticker image. */
2036
+ get url() {
2037
+ const ext = this.animated ? "gif" : "png";
2038
+ return `${CDN_URL}/stickers/${this.id}.${ext}`;
2039
+ }
2040
+ /** Delete this sticker. Requires Manage Emojis and Stickers permission. */
2041
+ async delete() {
2042
+ await this.client.rest.delete(import_types14.Routes.guildSticker(this.guildId, this.id), {
2043
+ auth: true
2044
+ });
2045
+ }
2046
+ /**
2047
+ * Edit this sticker's name and/or description.
2048
+ * Requires Manage Emojis and Stickers permission.
2049
+ */
2050
+ async edit(options) {
2051
+ const data = await this.client.rest.patch(import_types14.Routes.guildSticker(this.guildId, this.id), {
2052
+ body: options,
2053
+ auth: true
2054
+ });
2055
+ const s = data;
2056
+ this.name = s.name;
2057
+ this.description = s.description ?? "";
2058
+ return this;
2059
+ }
2060
+ };
2061
+
2062
+ // src/structures/Guild.ts
2063
+ var Guild = class extends Base {
2064
+ client;
2065
+ id;
2066
+ name;
2067
+ icon;
2068
+ banner;
2069
+ ownerId;
2070
+ /** Invite splash image hash. Null if none. */
2071
+ splash;
2072
+ /** Custom vanity URL code (e.g. fluxer.gg/code). Null if none. */
2073
+ vanityURLCode;
2074
+ /** Enabled guild features. */
2075
+ features;
2076
+ verificationLevel;
2077
+ defaultMessageNotifications;
2078
+ explicitContentFilter;
2079
+ /** AFK voice channel ID. Null if none. */
2080
+ afkChannelId;
2081
+ /** AFK timeout in seconds. */
2082
+ afkTimeout;
2083
+ /** System messages channel ID. Null if none. */
2084
+ systemChannelId;
2085
+ /** Rules/guidelines channel ID. Null if none. */
2086
+ rulesChannelId;
2087
+ nsfwLevel;
2088
+ mfaLevel;
2089
+ /** Banner image width. Optional. */
2090
+ bannerWidth;
2091
+ /** Banner image height. Optional. */
2092
+ bannerHeight;
2093
+ /** Splash image width. Optional. */
2094
+ splashWidth;
2095
+ /** Splash image height. Optional. */
2096
+ splashHeight;
2097
+ members;
2098
+ channels = new import_collection7.Collection();
2099
+ roles = new import_collection7.Collection();
2100
+ emojis = new import_collection7.Collection();
2101
+ stickers = new import_collection7.Collection();
2102
+ /** @param data - API guild from GET /guilds/{id} or gateway GUILD_CREATE */
2103
+ constructor(client, data) {
2104
+ super();
2105
+ this.client = client;
2106
+ this.id = data.id;
2107
+ this.members = new GuildMemberManager(this);
2108
+ this.name = data.name;
2109
+ this.icon = data.icon ?? null;
2110
+ this.banner = data.banner ?? null;
2111
+ this.ownerId = data.owner_id ?? data.ownerId ?? "";
2112
+ this.splash = data.splash ?? null;
2113
+ this.vanityURLCode = data.vanity_url_code ?? null;
2114
+ this.features = data.features ?? [];
2115
+ this.verificationLevel = data.verification_level ?? 0;
2116
+ this.defaultMessageNotifications = data.default_message_notifications ?? 0;
2117
+ this.explicitContentFilter = data.explicit_content_filter ?? 0;
2118
+ this.afkChannelId = data.afk_channel_id ?? null;
2119
+ this.afkTimeout = data.afk_timeout ?? 0;
2120
+ this.systemChannelId = data.system_channel_id ?? null;
2121
+ this.rulesChannelId = data.rules_channel_id ?? null;
2122
+ this.nsfwLevel = data.nsfw_level ?? 0;
2123
+ this.mfaLevel = data.mfa_level ?? 0;
2124
+ this.bannerWidth = data.banner_width ?? null;
2125
+ this.bannerHeight = data.banner_height ?? null;
2126
+ this.splashWidth = data.splash_width ?? null;
2127
+ this.splashHeight = data.splash_height ?? null;
2128
+ for (const r of data.roles ?? []) {
2129
+ this.roles.set(r.id, new Role(client, r, this.id));
2130
+ }
2131
+ }
2132
+ /** Get the guild icon URL, or null if no icon. */
2133
+ iconURL(options) {
2134
+ if (!this.icon) return null;
2135
+ const size = options?.size ? `?size=${options.size}` : "";
2136
+ return `${CDN_URL}/icons/${this.id}/${this.icon}.png${size}`;
2137
+ }
2138
+ /** Get the guild banner URL, or null if no banner. */
2139
+ bannerURL(options) {
2140
+ if (!this.banner) return null;
2141
+ const size = options?.size ? `?size=${options.size}` : "";
2142
+ return `${CDN_URL}/banners/${this.id}/${this.banner}.png${size}`;
2143
+ }
2144
+ /** Get the guild splash (invite background) URL, or null if no splash. */
2145
+ splashURL(options) {
2146
+ if (!this.splash) return null;
2147
+ const size = options?.size ? `?size=${options.size}` : "";
2148
+ return `${CDN_URL}/splashes/${this.id}/${this.splash}.png${size}`;
2149
+ }
2150
+ /**
2151
+ * Add a role to a member by user ID. Does not require fetching the member first.
2152
+ * @param userId - The user ID of the member
2153
+ * @param roleId - The role ID to add (or use guild.resolveRoleId for mention/name resolution)
2154
+ * Requires Manage Roles permission.
2155
+ */
2156
+ async addRoleToMember(userId, roleId) {
2157
+ await this.client.rest.put(import_types15.Routes.guildMemberRole(this.id, userId, roleId));
2158
+ }
2159
+ /**
2160
+ * Remove a role from a member by user ID. Does not require fetching the member first.
2161
+ * @param userId - The user ID of the member
2162
+ * @param roleId - The role ID to remove
2163
+ * Requires Manage Roles permission.
2164
+ */
2165
+ async removeRoleFromMember(userId, roleId) {
2166
+ await this.client.rest.delete(import_types15.Routes.guildMemberRole(this.id, userId, roleId));
2167
+ }
2168
+ /**
2169
+ * Create a role in this guild.
2170
+ * Requires Manage Roles permission.
2171
+ * @param options - Role data (permissions accepts PermissionResolvable for convenience)
2172
+ * @returns The created role
2173
+ * @example
2174
+ * const role = await guild.createRole({ name: 'Mod', permissions: ['KickMembers', 'BanMembers'] });
2175
+ */
2176
+ async createRole(options) {
2177
+ const body = {};
2178
+ if (options.name !== void 0) body.name = options.name;
2179
+ if (options.permissions !== void 0) {
2180
+ body.permissions = typeof options.permissions === "string" ? options.permissions : (0, import_util9.resolvePermissionsToBitfield)(options.permissions);
2181
+ }
2182
+ if (options.color !== void 0) body.color = options.color;
2183
+ if (options.hoist !== void 0) body.hoist = options.hoist;
2184
+ if (options.mentionable !== void 0) body.mentionable = options.mentionable;
2185
+ if (options.unicode_emoji !== void 0) body.unicode_emoji = options.unicode_emoji;
2186
+ if (options.position !== void 0) body.position = options.position;
2187
+ if (options.hoist_position !== void 0) body.hoist_position = options.hoist_position;
2188
+ const data = await this.client.rest.post(import_types15.Routes.guildRoles(this.id), {
2189
+ body: Object.keys(body).length ? body : void 0,
2190
+ auth: true
2191
+ });
2192
+ const role = new Role(this.client, data, this.id);
2193
+ this.roles.set(role.id, role);
2194
+ return role;
2195
+ }
2196
+ /**
2197
+ * Fetch all roles in this guild.
2198
+ * @returns Array of Role objects (cached in guild.roles)
2199
+ */
2200
+ async fetchRoles() {
2201
+ const data = await this.client.rest.get(
2202
+ import_types15.Routes.guildRoles(this.id)
2203
+ );
2204
+ const list = Array.isArray(data) ? data : Object.values(data ?? {});
2205
+ const roles = [];
2206
+ for (const r of list) {
2207
+ const role = new Role(this.client, r, this.id);
2208
+ this.roles.set(role.id, role);
2209
+ roles.push(role);
2210
+ }
2211
+ return roles;
2212
+ }
2213
+ /**
2214
+ * Fetch a role by ID.
2215
+ * @param roleId - The role ID to fetch
2216
+ * @returns The role
2217
+ * @throws FluxerError with ROLE_NOT_FOUND if role does not exist (404)
2218
+ */
2219
+ async fetchRole(roleId) {
2220
+ try {
2221
+ const data = await this.client.rest.get(import_types15.Routes.guildRole(this.id, roleId));
2222
+ const role = new Role(this.client, data, this.id);
2223
+ this.roles.set(role.id, role);
2224
+ return role;
2225
+ } catch (err) {
2226
+ const statusCode = err instanceof import_rest3.FluxerAPIError ? err.statusCode : err?.statusCode;
2227
+ if (statusCode === 404) {
2228
+ throw new import_util.FluxerError(`Role ${roleId} not found in guild`, {
2229
+ code: import_util2.ErrorCodes.RoleNotFound,
2230
+ cause: err
2231
+ });
2232
+ }
2233
+ throw err instanceof import_util.FluxerError ? err : new import_util.FluxerError("Failed to fetch guild role", { cause: err });
2234
+ }
2235
+ }
2236
+ /**
2237
+ * Resolve a role ID from an argument (role mention, raw ID, or name).
2238
+ * Fetches guild roles if name is provided.
2239
+ * @param arg - Role mention (@role), role ID, or role name
2240
+ * @returns The role ID, or null if not found
2241
+ */
2242
+ async resolveRoleId(arg) {
2243
+ const parsed = (0, import_util9.parseRoleMention)(arg);
2244
+ if (parsed) return parsed;
2245
+ if (/^\d{17,19}$/.test(arg.trim())) return arg.trim();
2246
+ const cached = this.roles.find(
2247
+ (r) => !!(r.name && r.name.toLowerCase() === arg.trim().toLowerCase())
2248
+ );
2249
+ if (cached) return cached.id;
2250
+ const roles = await this.client.rest.get(import_types15.Routes.guildRoles(this.id));
2251
+ const list = Array.isArray(roles) ? roles : Object.values(roles ?? {});
2252
+ const role = list.find((r) => !!(r.name && r.name.toLowerCase() === arg.trim().toLowerCase()));
2253
+ if (role) {
2254
+ this.roles.set(role.id, new Role(this.client, role, this.id));
2255
+ return role.id;
2256
+ }
2257
+ return null;
2258
+ }
2259
+ /**
2260
+ * Ban a user from this guild.
2261
+ * @param userId - The user ID to ban
2262
+ * @param options - Optional reason, delete_message_days (0–7), and ban_duration_seconds (temporary ban).
2263
+ * ban_duration_seconds: 0 = permanent, or use 3600, 43200, 86400, 259200, 432000, 604800, 1209600, 2592000.
2264
+ * Requires Ban Members permission.
2265
+ */
2266
+ async ban(userId, options) {
2267
+ const body = {};
2268
+ if (options?.reason) body.reason = options.reason;
2269
+ if (options?.delete_message_days != null)
2270
+ body.delete_message_days = options.delete_message_days;
2271
+ if (options?.ban_duration_seconds != null)
2272
+ body.ban_duration_seconds = options.ban_duration_seconds;
2273
+ await this.client.rest.put(import_types15.Routes.guildBan(this.id, userId), {
2274
+ body: Object.keys(body).length ? body : void 0,
2275
+ auth: true
2276
+ });
2277
+ }
2278
+ /**
2279
+ * Fetch guild bans. Requires Ban Members permission.
2280
+ * @returns List of GuildBan objects
2281
+ */
2282
+ async fetchBans() {
2283
+ const data = await this.client.rest.get(
2284
+ import_types15.Routes.guildBans(this.id)
2285
+ );
2286
+ const list = Array.isArray(data) ? data : data?.bans ?? [];
2287
+ return list.map((b) => new GuildBan(this.client, { ...b, guild_id: this.id }, this.id));
2288
+ }
2289
+ /**
2290
+ * Remove a ban (unban a user).
2291
+ * @param userId - The user ID to unban
2292
+ * Requires Ban Members permission.
2293
+ */
2294
+ async unban(userId) {
2295
+ await this.client.rest.delete(import_types15.Routes.guildBan(this.id, userId), { auth: true });
2296
+ }
2297
+ /**
2298
+ * Kick a member from this guild.
2299
+ * @param userId - The user ID to kick
2300
+ * Requires Kick Members permission.
2301
+ */
2302
+ async kick(userId) {
2303
+ await this.client.rest.delete(import_types15.Routes.guildMember(this.id, userId), { auth: true });
2304
+ }
2305
+ /**
2306
+ * Fetch a guild member by user ID.
2307
+ * @param userId - The user ID of the member to fetch
2308
+ * @returns The guild member
2309
+ * @throws FluxerError with MEMBER_NOT_FOUND if user is not in the guild (404)
2310
+ * @throws FluxerError with cause for permission denied (403) or other REST errors
2311
+ */
2312
+ async fetchMember(userId) {
2313
+ try {
2314
+ const data = await this.client.rest.get(
2315
+ import_types15.Routes.guildMember(this.id, userId)
2316
+ );
2317
+ const member = new GuildMember(this.client, { ...data, guild_id: this.id }, this);
2318
+ this.members.set(member.id, member);
2319
+ return member;
2320
+ } catch (err) {
2321
+ const statusCode = err instanceof import_rest3.FluxerAPIError ? err.statusCode : err?.statusCode;
2322
+ if (statusCode === 404) {
2323
+ throw new import_util.FluxerError(`Member ${userId} not found in guild`, {
2324
+ code: import_util2.ErrorCodes.MemberNotFound,
2325
+ cause: err
2326
+ });
2327
+ }
2328
+ throw err instanceof import_util.FluxerError ? err : new import_util.FluxerError("Failed to fetch guild member", { cause: err });
2329
+ }
2330
+ }
2331
+ /**
2332
+ * Fetch guild audit logs. Requires View Audit Log permission.
2333
+ * @param options - Optional limit, before, after, user_id, action_type for filtering
2334
+ */
2335
+ async fetchAuditLogs(options) {
2336
+ const params = new URLSearchParams();
2337
+ if (options?.limit != null) params.set("limit", String(options.limit));
2338
+ if (options?.before) params.set("before", options.before);
2339
+ if (options?.after) params.set("after", options.after);
2340
+ if (options?.userId) params.set("user_id", options.userId);
2341
+ if (options?.actionType != null) params.set("action_type", String(options.actionType));
2342
+ const qs = params.toString();
2343
+ const url = import_types15.Routes.guildAuditLogs(this.id) + (qs ? `?${qs}` : "");
2344
+ return this.client.rest.get(url);
2345
+ }
2346
+ /** Fetch all webhooks in this guild. Returned webhooks do not include the token (cannot send). */
2347
+ async fetchWebhooks() {
2348
+ const data = await this.client.rest.get(import_types15.Routes.guildWebhooks(this.id));
2349
+ const list = Array.isArray(data) ? data : Object.values(data ?? {});
2350
+ return list.map((w) => new Webhook(this.client, w));
2351
+ }
2352
+ /**
2353
+ * Fetch all invites in this guild.
2354
+ * Requires Manage Guild permission.
2355
+ */
2356
+ async fetchInvites() {
2357
+ const data = await this.client.rest.get(
2358
+ import_types15.Routes.guildInvites(this.id)
2359
+ );
2360
+ const list = Array.isArray(data) ? data : Object.values(data ?? {});
2361
+ return list.map((invite) => new Invite(this.client, invite));
2362
+ }
2363
+ /**
2364
+ * Fetch a guild invite by code or URL.
2365
+ * @see Invite.fetch
2366
+ */
2367
+ async fetchInvite(codeOrUrl) {
2368
+ return Invite.fetch(this.client, codeOrUrl);
2369
+ }
2370
+ /**
2371
+ * Create a channel in this guild.
2372
+ * @param data - Channel data: type (0=text, 2=voice, 4=category, 5=link), name, and optional parent_id, topic, bitrate, user_limit, nsfw, permission_overwrites
2373
+ * Requires Manage Channels permission.
2374
+ */
2375
+ async createChannel(data) {
2376
+ const created = await this.client.rest.post(import_types15.Routes.guildChannels(this.id), {
2377
+ body: data,
2378
+ auth: true
2379
+ });
2380
+ const channel = Channel.from(this.client, created);
2381
+ if (channel) {
2382
+ this.client.channels.set(channel.id, channel);
2383
+ this.channels.set(channel.id, channel);
2384
+ }
2385
+ return channel;
2386
+ }
2387
+ /**
2388
+ * Fetch all channels in this guild.
2389
+ * @returns Array of GuildChannel objects (cached in guild.channels and client.channels)
2390
+ */
2391
+ async fetchChannels() {
2392
+ const data = await this.client.rest.get(import_types15.Routes.guildChannels(this.id));
2393
+ const list = Array.isArray(data) ? data : Object.values(data ?? {});
2394
+ const channels = [];
2395
+ for (const ch of list) {
2396
+ const channel = Channel.from(this.client, ch);
2397
+ if (channel) {
2398
+ this.client.channels.set(channel.id, channel);
2399
+ this.channels.set(channel.id, channel);
2400
+ channels.push(channel);
2401
+ }
2402
+ }
2403
+ return channels;
2404
+ }
2405
+ /**
2406
+ * Edit this guild. PATCH /guilds/{id}.
2407
+ * Requires guild owner or Administrator.
2408
+ */
2409
+ async edit(options) {
2410
+ const data = await this.client.rest.patch(import_types15.Routes.guild(this.id), {
2411
+ body: options,
2412
+ auth: true
2413
+ });
2414
+ this.name = data.name;
2415
+ this.icon = data.icon ?? this.icon;
2416
+ this.banner = data.banner ?? this.banner;
2417
+ this.splash = data.splash ?? this.splash;
2418
+ this.systemChannelId = data.system_channel_id ?? this.systemChannelId;
2419
+ this.afkChannelId = data.afk_channel_id ?? this.afkChannelId;
2420
+ this.afkTimeout = data.afk_timeout ?? this.afkTimeout;
2421
+ this.verificationLevel = data.verification_level ?? this.verificationLevel;
2422
+ this.mfaLevel = data.mfa_level ?? this.mfaLevel;
2423
+ this.explicitContentFilter = data.explicit_content_filter ?? this.explicitContentFilter;
2424
+ this.defaultMessageNotifications = data.default_message_notifications ?? this.defaultMessageNotifications;
2425
+ this.features = data.features ?? this.features;
2426
+ return this;
2427
+ }
2428
+ /**
2429
+ * Delete this guild. POST /guilds/{id}/delete.
2430
+ * Must be the guild owner.
2431
+ */
2432
+ async delete() {
2433
+ await this.client.rest.post(import_types15.Routes.guildDelete(this.id), { auth: true });
2434
+ this.client.guilds.delete(this.id);
2435
+ }
2436
+ /**
2437
+ * Fetch vanity URL for this guild. GET /guilds/{id}/vanity-url.
2438
+ * Requires Manage Guild permission.
2439
+ */
2440
+ async fetchVanityURL() {
2441
+ return this.client.rest.get(import_types15.Routes.guildVanityUrl(this.id), { auth: true });
2442
+ }
2443
+ /**
2444
+ * Transfer guild ownership to another user. POST /guilds/{id}/transfer-ownership.
2445
+ * Must be the guild owner.
2446
+ */
2447
+ async transferOwnership(newOwnerId, password) {
2448
+ await this.client.rest.post(import_types15.Routes.guildTransferOwnership(this.id), {
2449
+ body: { new_owner_id: newOwnerId, ...password != null && { password } },
2450
+ auth: true
2451
+ });
2452
+ }
2453
+ /**
2454
+ * Set text channel flexible names feature. PATCH /guilds/{id}/text-channel-flexible-names.
2455
+ */
2456
+ setTextChannelFlexibleNames(enabled) {
2457
+ return this.client.rest.patch(import_types15.Routes.guildTextChannelFlexibleNames(this.id), {
2458
+ body: { enabled },
2459
+ auth: true
2460
+ }).then(() => this);
2461
+ }
2462
+ /**
2463
+ * Set detached banner feature. PATCH /guilds/{id}/detached-banner.
2464
+ */
2465
+ setDetachedBanner(enabled) {
2466
+ return this.client.rest.patch(import_types15.Routes.guildDetachedBanner(this.id), {
2467
+ body: { enabled },
2468
+ auth: true
2469
+ }).then(() => this);
2470
+ }
2471
+ /**
2472
+ * Set disallow unclaimed accounts. PATCH /guilds/{id}/disallow-unclaimed-accounts.
2473
+ */
2474
+ setDisallowUnclaimedAccounts(enabled) {
2475
+ return this.client.rest.patch(import_types15.Routes.guildDisallowUnclaimedAccounts(this.id), {
2476
+ body: { enabled },
2477
+ auth: true
2478
+ }).then(() => this);
2479
+ }
2480
+ /**
2481
+ * Update role positions. PATCH /guilds/{id}/roles.
2482
+ * @param updates - Array of { id, position? }
2483
+ */
2484
+ async setRolePositions(updates) {
2485
+ const data = await this.client.rest.patch(
2486
+ import_types15.Routes.guildRoles(this.id),
2487
+ { body: updates, auth: true }
2488
+ );
2489
+ const list = Array.isArray(data) ? data : Object.values(data ?? {});
2490
+ for (const r of list) {
2491
+ this.roles.set(r.id, new Role(this.client, r, this.id));
2492
+ }
2493
+ return list;
2494
+ }
2495
+ /**
2496
+ * Update role hoist positions. PATCH /guilds/{id}/roles/hoist-positions.
2497
+ */
2498
+ async setRoleHoistPositions(updates) {
2499
+ const data = await this.client.rest.patch(
2500
+ import_types15.Routes.guildRolesHoistPositions(this.id),
2501
+ { body: updates, auth: true }
2502
+ );
2503
+ const list = Array.isArray(data) ? data : Object.values(data ?? {});
2504
+ for (const r of list) {
2505
+ this.roles.set(r.id, new Role(this.client, r, this.id));
2506
+ }
2507
+ return list;
2508
+ }
2509
+ /**
2510
+ * Reset role hoist positions. DELETE /guilds/{id}/roles/hoist-positions.
2511
+ */
2512
+ async resetRoleHoistPositions() {
2513
+ const data = await this.client.rest.delete(
2514
+ import_types15.Routes.guildRolesHoistPositions(this.id),
2515
+ { auth: true }
2516
+ );
2517
+ const list = Array.isArray(data) ? data : Object.values(data ?? {});
2518
+ for (const r of list) {
2519
+ this.roles.set(r.id, new Role(this.client, r, this.id));
2520
+ }
2521
+ return list;
2522
+ }
2523
+ /**
2524
+ * Update channel positions.
2525
+ * @param updates - Array of { id, position?, parent_id?, lock_permissions? }
2526
+ * Requires Manage Channels permission.
2527
+ */
2528
+ async setChannelPositions(updates) {
2529
+ await this.client.rest.patch(import_types15.Routes.guildChannels(this.id), {
2530
+ body: updates,
2531
+ auth: true
2532
+ });
2533
+ }
2534
+ /**
2535
+ * Fetch all emojis in this guild.
2536
+ * @returns Array of GuildEmoji objects (cached in guild.emojis)
2537
+ */
2538
+ async fetchEmojis() {
2539
+ const data = await this.client.rest.get(
2540
+ import_types15.Routes.guildEmojis(this.id)
2541
+ );
2542
+ const list = Array.isArray(data) ? data : Object.values(data ?? {});
2543
+ const emojis = [];
2544
+ for (const e of list) {
2545
+ const emoji = new GuildEmoji(this.client, { ...e, guild_id: this.id }, this.id);
2546
+ this.emojis.set(emoji.id, emoji);
2547
+ emojis.push(emoji);
2548
+ }
2549
+ return emojis;
2550
+ }
2551
+ /**
2552
+ * Fetch a single emoji by ID.
2553
+ * @param emojiId - The emoji ID to fetch
2554
+ * @returns The guild emoji
2555
+ * @throws FluxerError if emoji not found (404)
2556
+ */
2557
+ async fetchEmoji(emojiId) {
2558
+ try {
2559
+ const data = await this.client.rest.get(import_types15.Routes.guildEmoji(this.id, emojiId));
2560
+ const emoji = new GuildEmoji(this.client, { ...data, guild_id: this.id }, this.id);
2561
+ this.emojis.set(emoji.id, emoji);
2562
+ return emoji;
2563
+ } catch (err) {
2564
+ const statusCode = err instanceof import_rest3.FluxerAPIError ? err.statusCode : err?.statusCode;
2565
+ if (statusCode === 404) {
2566
+ throw new import_util.FluxerError(`Emoji ${emojiId} not found in guild`, {
2567
+ code: import_util2.ErrorCodes.EmojiNotFound,
2568
+ cause: err
2569
+ });
2570
+ }
2571
+ throw err instanceof import_util.FluxerError ? err : new import_util.FluxerError("Failed to fetch guild emoji", { cause: err });
2572
+ }
2573
+ }
2574
+ /**
2575
+ * Bulk create emojis. POST /guilds/{id}/emojis/bulk.
2576
+ * @param emojis - Array of { name, image } (base64), 1-50 emojis
2577
+ * @returns Array of created GuildEmoji objects
2578
+ */
2579
+ async createEmojisBulk(emojis) {
2580
+ const data = await this.client.rest.post(
2581
+ import_types15.Routes.guildEmojisBulk(this.id),
2582
+ {
2583
+ body: { emojis },
2584
+ auth: true
2585
+ }
2586
+ );
2587
+ const list = Array.isArray(data) ? data : data?.emojis ?? [];
2588
+ return list.map((e) => new GuildEmoji(this.client, { ...e, guild_id: this.id }, this.id));
2589
+ }
2590
+ /**
2591
+ * Bulk create stickers. POST /guilds/{id}/stickers/bulk.
2592
+ * @param stickers - Array of { name, image, description?, tags? }, 1-50 stickers
2593
+ * @returns Array of created GuildSticker objects
2594
+ */
2595
+ async createStickersBulk(stickers) {
2596
+ const data = await this.client.rest.post(
2597
+ import_types15.Routes.guildStickersBulk(this.id),
2598
+ {
2599
+ body: { stickers },
2600
+ auth: true
2601
+ }
2602
+ );
2603
+ const list = Array.isArray(data) ? data : data?.stickers ?? [];
2604
+ const created = list.map(
2605
+ (s) => new GuildSticker(this.client, { ...s, guild_id: this.id }, this.id)
2606
+ );
2607
+ for (const sticker of created) {
2608
+ this.stickers.set(sticker.id, sticker);
2609
+ }
2610
+ return created;
2611
+ }
2612
+ /**
2613
+ * Fetch all stickers in this guild.
2614
+ * @returns GuildSticker instances (cached on guild.stickers)
2615
+ */
2616
+ async fetchStickers() {
2617
+ const data = await this.client.rest.get(
2618
+ import_types15.Routes.guildStickers(this.id)
2619
+ );
2620
+ const list = Array.isArray(data) ? data : Object.values(data ?? {});
2621
+ const stickers = [];
2622
+ for (const s of list) {
2623
+ const sticker = new GuildSticker(this.client, { ...s, guild_id: this.id }, this.id);
2624
+ this.stickers.set(sticker.id, sticker);
2625
+ stickers.push(sticker);
2626
+ }
2627
+ return stickers;
2628
+ }
2629
+ /**
2630
+ * Fetch a single guild sticker by ID.
2631
+ */
2632
+ async fetchSticker(stickerId) {
2633
+ const data = await this.client.rest.get(import_types15.Routes.guildSticker(this.id, stickerId));
2634
+ const sticker = new GuildSticker(this.client, { ...data, guild_id: this.id }, this.id);
2635
+ this.stickers.set(sticker.id, sticker);
2636
+ return sticker;
2637
+ }
2638
+ };
2639
+
2640
+ // src/client/GuildManager.ts
2641
+ var GuildManager = class extends import_collection8.Collection {
2642
+ constructor(client) {
2643
+ super();
2644
+ this.client = client;
2645
+ this.maxSize = client.options?.cache?.guilds ?? 0;
2646
+ }
2647
+ maxSize;
2648
+ set(key, value) {
2649
+ if (this.maxSize > 0 && this.size >= this.maxSize && !this.has(key)) {
2650
+ const firstKey = this.keys().next().value;
2651
+ if (firstKey !== void 0) this.delete(firstKey);
2652
+ }
2653
+ return super.set(key, value);
2654
+ }
2655
+ /**
2656
+ * Get a guild from cache or fetch from the API if not present.
2657
+ * Convenience helper to avoid repeating `client.guilds.get(id) ?? (await client.guilds.fetch(id))`.
2658
+ * @param guildId - Snowflake of the guild
2659
+ * @returns The guild, or null if not found
2660
+ * @example
2661
+ * const guild = await client.guilds.resolve(message.guildId);
2662
+ * if (guild) console.log(guild.name);
2663
+ */
2664
+ async resolve(guildId) {
2665
+ return this.get(guildId) ?? this.fetch(guildId);
2666
+ }
2667
+ /**
2668
+ * Create a guild. POST /guilds.
2669
+ * @param options - name (required), icon (base64), empty_features
2670
+ * @returns The created guild
2671
+ */
2672
+ async create(options) {
2673
+ const data = await this.client.rest.post(import_types16.Routes.guilds(), {
2674
+ body: options,
2675
+ auth: true
2676
+ });
2677
+ const guild = new Guild(this.client, data);
2678
+ this.set(guild.id, guild);
2679
+ return guild;
2680
+ }
2681
+ /**
2682
+ * Fetch a guild by ID from the API (or return from cache if present).
2683
+ * @param guildId - Snowflake of the guild
2684
+ * @returns The guild, or null if not found
2685
+ * @example
2686
+ * const guild = await client.guilds.fetch(guildId);
2687
+ * if (guild) console.log(guild.name);
2688
+ */
2689
+ async fetch(guildId) {
2690
+ const cached = this.get(guildId);
2691
+ if (cached) return cached;
2692
+ try {
2693
+ const data = await this.client.rest.get(import_types16.Routes.guild(guildId));
2694
+ const guild = new Guild(this.client, data);
2695
+ this.set(guild.id, guild);
2696
+ return guild;
2697
+ } catch {
2698
+ return null;
2699
+ }
2700
+ }
2701
+ };
2702
+
2703
+ // src/structures/User.ts
2704
+ var import_types17 = require("@fluxerjs/types");
2705
+ var User = class extends Base {
2706
+ client;
2707
+ id;
2708
+ username;
2709
+ discriminator;
2710
+ globalName;
2711
+ avatar;
2712
+ bot;
2713
+ /** RGB avatar color (e.g. 7577782). Null if not set. */
2714
+ avatarColor;
2715
+ /** Public flags bitfield. Null if not set. */
2716
+ flags;
2717
+ /** Whether this is an official system user. */
2718
+ system;
2719
+ /** Banner hash (from profile, member, or invite context). Null when not available. */
2720
+ banner;
2721
+ /** @param data - API user from message author, GET /users/{id}, or GET /users/@me */
2722
+ constructor(client, data) {
2723
+ super();
2724
+ this.client = client;
2725
+ this.id = data.id;
2726
+ this.username = data.username;
2727
+ this.discriminator = data.discriminator;
2728
+ this.globalName = data.global_name ?? null;
2729
+ this.avatar = data.avatar ?? null;
2730
+ this.bot = !!data.bot;
2731
+ this.avatarColor = data.avatar_color ?? null;
2732
+ this.flags = data.flags ?? data.public_flags ?? null;
2733
+ this.system = !!data.system;
2734
+ this.banner = data.banner ?? null;
2735
+ }
2736
+ /** Update mutable fields from fresh API data. Used by getOrCreateUser cache. */
2737
+ _patch(data) {
2738
+ this.username = data.username;
2739
+ this.discriminator = data.discriminator;
2740
+ this.globalName = data.global_name ?? null;
2741
+ this.avatar = data.avatar ?? null;
2742
+ if (data.avatar_color !== void 0) this.avatarColor = data.avatar_color;
2743
+ if (data.flags !== void 0) this.flags = data.flags;
2744
+ if (data.banner !== void 0) this.banner = data.banner;
2745
+ }
2746
+ /**
2747
+ * Get the URL for this user's avatar.
2748
+ * Auto-detects animated avatars (hash starting with `a_`) and uses gif extension.
2749
+ * @param options - Optional `size` and `extension` (default: png, or gif for animated)
2750
+ */
2751
+ avatarURL(options) {
2752
+ if (!this.avatar) return null;
2753
+ const ext = this.avatar.startsWith("a_") ? "gif" : options?.extension ?? "png";
2754
+ const size = options?.size ? `?size=${options.size}` : "";
2755
+ return `${CDN_URL}/avatars/${this.id}/${this.avatar}.${ext}${size}`;
2756
+ }
2757
+ /** Get the avatar URL, or the default avatar if none set (Fluxer: fluxerstatic.com). */
2758
+ displayAvatarURL(options) {
2759
+ return this.avatarURL(options) ?? cdnDefaultAvatarURL(this.id);
2760
+ }
2761
+ /**
2762
+ * Get the URL for this user's banner.
2763
+ * Returns null if the user has no banner (only available when fetched from profile/member context).
2764
+ */
2765
+ bannerURL(options) {
2766
+ if (!this.banner) return null;
2767
+ const ext = this.banner.startsWith("a_") ? "gif" : options?.extension ?? "png";
2768
+ const size = options?.size ? `?size=${options.size}` : "";
2769
+ return `${CDN_URL}/banners/${this.id}/${this.banner}.${ext}${size}`;
2770
+ }
2771
+ /** Returns a mention string (e.g. `<@123456>`). */
2772
+ toString() {
2773
+ return `<@${this.id}>`;
2774
+ }
2775
+ /**
2776
+ * Create or get a DM channel with this user.
2777
+ * Returns the DM channel; use {@link DMChannel.send} to send messages.
2778
+ */
2779
+ async createDM() {
2780
+ const data = await this.client.rest.post(import_types17.Routes.userMeChannels(), {
2781
+ body: { recipient_id: this.id },
2782
+ auth: true
2783
+ });
2784
+ return new DMChannel(this.client, data);
2785
+ }
2786
+ /**
2787
+ * Send a DM to this user.
2788
+ * Convenience method that creates the DM channel and sends the message.
2789
+ */
2790
+ async send(options) {
2791
+ const dm = await this.createDM();
2792
+ return dm.send(options);
2793
+ }
2794
+ };
2795
+
2796
+ // src/client/ClientUser.ts
2797
+ var import_types18 = require("@fluxerjs/types");
2798
+ var ClientUser = class extends User {
2799
+ constructor(client, data) {
2800
+ super(client, { ...data });
2801
+ }
2802
+ /**
2803
+ * Fetch guilds the bot is a member of.
2804
+ * @returns Array of Guild objects (cached in client.guilds)
2805
+ */
2806
+ async fetchGuilds() {
2807
+ const data = await this.client.rest.get(
2808
+ import_types18.Routes.currentUserGuilds()
2809
+ );
2810
+ const list = Array.isArray(data) ? data : data?.guilds ?? [];
2811
+ const guilds = [];
2812
+ for (const g of list) {
2813
+ const guild = new Guild(this.client, g);
2814
+ this.client.guilds.set(guild.id, guild);
2815
+ guilds.push(guild);
2816
+ }
2817
+ return guilds;
2818
+ }
2819
+ /**
2820
+ * Leave a guild. Requires the bot to be a member.
2821
+ * @param guildId - The guild ID to leave
2822
+ */
2823
+ async leaveGuild(guildId) {
2824
+ await this.client.rest.delete(import_types18.Routes.leaveGuild(guildId), { auth: true });
2825
+ this.client.guilds.delete(guildId);
2826
+ }
2827
+ };
2828
+
2829
+ // src/client/Client.ts
2830
+ var import_util10 = require("@fluxerjs/util");
2831
+
2832
+ // src/client/UsersManager.ts
2833
+ var import_collection9 = require("@fluxerjs/collection");
2834
+ var import_types19 = require("@fluxerjs/types");
2835
+ var UsersManager = class extends import_collection9.Collection {
2836
+ constructor(client) {
2837
+ super();
2838
+ this.client = client;
2839
+ this.maxSize = client.options?.cache?.users ?? 0;
2840
+ }
2841
+ maxSize;
2842
+ set(key, value) {
2843
+ if (this.maxSize > 0 && this.size >= this.maxSize && !this.has(key)) {
2844
+ const firstKey = this.keys().next().value;
2845
+ if (firstKey !== void 0) this.delete(firstKey);
2846
+ }
2847
+ return super.set(key, value);
2848
+ }
2849
+ /**
2850
+ * Fetch a user by ID from the API.
2851
+ * Updates cache if user already exists.
2852
+ * @param userId - Snowflake of the user
2853
+ * @returns The user
2854
+ * @throws FluxerError (or REST error) if user not found
2855
+ * @example
2856
+ * const user = await client.users.fetch(userId);
2857
+ * console.log(user.username);
2858
+ */
2859
+ async fetch(userId) {
2860
+ const data = await this.client.rest.get(import_types19.Routes.user(userId));
2861
+ return this.client.getOrCreateUser(data);
2862
+ }
2863
+ /**
2864
+ * Fetch a user with full profile and optional guild context.
2865
+ * Returns user, global profile, server profile (when guildId), and member (when guildId).
2866
+ * Ideal for userinfo commands.
2867
+ * @param userId - Snowflake of the user
2868
+ * @param options - Optional guildId for server profile and member data
2869
+ * @returns User, raw data, profiles, and member (when in guild)
2870
+ * @throws FluxerError (or REST error) if user not found
2871
+ * @example
2872
+ * const { user, globalProfile, serverProfile, member } = await client.users.fetchWithProfile(
2873
+ * userId,
2874
+ * { guildId: message.guildId ?? undefined },
2875
+ * );
2876
+ */
2877
+ async fetchWithProfile(userId, options) {
2878
+ const guildId = options?.guildId ?? void 0;
2879
+ const [userData, globalProfileData, serverProfileData, memberData] = await Promise.all([
2880
+ this.client.rest.get(import_types19.Routes.user(userId)),
2881
+ this.client.rest.get(import_types19.Routes.userProfile(userId)).catch(() => null),
2882
+ guildId ? this.client.rest.get(import_types19.Routes.userProfile(userId, guildId)).catch(() => null) : Promise.resolve(null),
2883
+ guildId ? this.client.rest.get(import_types19.Routes.guildMember(guildId, userId)).catch(() => null) : Promise.resolve(null)
2884
+ ]);
2885
+ const user = this.client.getOrCreateUser(userData);
2886
+ const globalProfile = globalProfileData && typeof globalProfileData === "object" ? globalProfileData : null;
2887
+ const serverProfile = serverProfileData && typeof serverProfileData === "object" ? serverProfileData : null;
2888
+ let member = null;
2889
+ if (memberData && guildId) {
2890
+ const guild = this.client.guilds.get(guildId) ?? await this.client.guilds.fetch(guildId);
2891
+ if (guild) {
2892
+ member = new GuildMember(this.client, { ...memberData, guild_id: guildId }, guild);
2893
+ guild.members.set(member.id, member);
2894
+ }
2895
+ }
2896
+ return {
2897
+ user,
2898
+ userData,
2899
+ globalProfile,
2900
+ serverProfile,
2901
+ member,
2902
+ memberData
2903
+ };
2904
+ }
2905
+ };
2906
+
2907
+ // src/structures/interactions/BaseInteraction.ts
2908
+ var BaseInteraction = class {
2909
+ constructor(client, raw) {
2910
+ this.client = client;
2911
+ this.raw = raw;
2912
+ }
2913
+ get id() {
2914
+ return this.raw.id;
2915
+ }
2916
+ get applicationId() {
2917
+ return this.raw.application_id;
2918
+ }
2919
+ get token() {
2920
+ return this.raw.token;
2921
+ }
2922
+ get type() {
2923
+ return this.raw.type;
2924
+ }
2925
+ get channelId() {
2926
+ return this.raw.channel_id;
2927
+ }
2928
+ get guildId() {
2929
+ return this.raw.guild_id;
2930
+ }
2931
+ };
2932
+
2933
+ // src/structures/interactions/ChatInputCommandInteraction.ts
2934
+ var CommandOptionType = {
2935
+ SubCommand: 1,
2936
+ SubCommandGroup: 2,
2937
+ String: 3,
2938
+ Integer: 4,
2939
+ Boolean: 5,
2940
+ Number: 10
2941
+ };
2942
+ function findOptionDeep(options, name) {
2943
+ if (!options?.length) return void 0;
2944
+ for (const o of options) {
2945
+ if (o.name === name && o.value !== void 0) return o;
2946
+ const nested = findOptionDeep(o.options, name);
2947
+ if (nested) return nested;
2948
+ }
2949
+ return void 0;
2950
+ }
2951
+ var ChatInputCommandInteraction = class extends BaseInteraction {
2952
+ constructor(client, raw) {
2953
+ super(client, raw);
2954
+ if (raw.data?.name == null) {
2955
+ throw new import_util.FluxerError("ChatInputCommandInteraction requires interaction data with a command name", {
2956
+ code: import_util2.ErrorCodes.InteractionInvalidPayload
2957
+ });
2958
+ }
2959
+ }
2960
+ /** Command name (e.g. `ping`). */
2961
+ get commandName() {
2962
+ return this.raw.data.name;
2963
+ }
2964
+ /** Resolved option leaf by name (searches nested subcommand options). */
2965
+ getOption(name) {
2966
+ const opt = findOptionDeep(this.raw.data?.options, name);
2967
+ if (!opt) {
2968
+ throw new import_util.FluxerError(`Interaction option "${name}" was not provided`, {
2969
+ code: import_util2.ErrorCodes.InteractionOptionNotFound
2970
+ });
2971
+ }
2972
+ return opt;
2973
+ }
2974
+ getString(name) {
2975
+ const o = this.getOption(name);
2976
+ if (o.type !== CommandOptionType.String) {
2977
+ throw new import_util.FluxerError(`Option "${name}" is not a string`, {
2978
+ code: import_util2.ErrorCodes.InteractionOptionTypeMismatch
2979
+ });
2980
+ }
2981
+ return String(o.value);
2982
+ }
2983
+ getInteger(name) {
2984
+ const o = this.getOption(name);
2985
+ if (o.type !== CommandOptionType.Integer) {
2986
+ throw new import_util.FluxerError(`Option "${name}" is not an integer`, {
2987
+ code: import_util2.ErrorCodes.InteractionOptionTypeMismatch
2988
+ });
2989
+ }
2990
+ const v = o.value;
2991
+ if (typeof v !== "number" || !Number.isInteger(v)) {
2992
+ throw new import_util.FluxerError(`Option "${name}" has invalid integer value`, {
2993
+ code: import_util2.ErrorCodes.InteractionOptionTypeMismatch
2994
+ });
2995
+ }
2996
+ return v;
2997
+ }
2998
+ getNumber(name) {
2999
+ const o = this.getOption(name);
3000
+ if (o.type !== CommandOptionType.Number && o.type !== CommandOptionType.Integer) {
3001
+ throw new import_util.FluxerError(`Option "${name}" is not a number`, {
3002
+ code: import_util2.ErrorCodes.InteractionOptionTypeMismatch
3003
+ });
3004
+ }
3005
+ const v = o.value;
3006
+ if (typeof v !== "number") {
3007
+ throw new import_util.FluxerError(`Option "${name}" has invalid number value`, {
3008
+ code: import_util2.ErrorCodes.InteractionOptionTypeMismatch
3009
+ });
3010
+ }
3011
+ return v;
3012
+ }
3013
+ getBoolean(name) {
3014
+ const o = this.getOption(name);
3015
+ if (o.type !== CommandOptionType.Boolean) {
3016
+ throw new import_util.FluxerError(`Option "${name}" is not a boolean`, {
3017
+ code: import_util2.ErrorCodes.InteractionOptionTypeMismatch
3018
+ });
3019
+ }
3020
+ if (typeof o.value !== "boolean") {
3021
+ throw new import_util.FluxerError(`Option "${name}" has invalid boolean value`, {
3022
+ code: import_util2.ErrorCodes.InteractionOptionTypeMismatch
3023
+ });
3024
+ }
3025
+ return o.value;
3026
+ }
3027
+ /** Name of the invoked subcommand (when using subcommands). */
3028
+ getSubcommand(fallback) {
3029
+ const opts = this.raw.data?.options;
3030
+ const first = opts?.[0];
3031
+ if (first?.type === CommandOptionType.SubCommand) return first.name;
3032
+ if (first?.type === CommandOptionType.SubCommandGroup) {
3033
+ const inner = first.options?.[0];
3034
+ if (inner?.type === CommandOptionType.SubCommand) return inner.name;
3035
+ }
3036
+ if (fallback !== void 0) return fallback;
3037
+ throw new import_util.FluxerError("No subcommand in this interaction", {
3038
+ code: import_util2.ErrorCodes.InteractionOptionNotFound
3039
+ });
3040
+ }
3041
+ };
3042
+
3043
+ // src/structures/interactions/createInteraction.ts
3044
+ function createInteraction(client, data) {
3045
+ if (data.data?.name != null) {
3046
+ return new ChatInputCommandInteraction(client, data);
3047
+ }
3048
+ return new BaseInteraction(client, data);
3049
+ }
3050
+
3051
+ // src/util/guildUtils.ts
3052
+ function normalizeGuildPayload(raw) {
3053
+ if (!raw || typeof raw !== "object") {
3054
+ return null;
3055
+ }
3056
+ if ("properties" in raw && raw.properties != null && typeof raw.properties === "object") {
3057
+ const r = raw;
3058
+ return {
3059
+ ...r.properties,
3060
+ roles: r.roles
3061
+ };
3062
+ }
3063
+ return raw;
3064
+ }
3065
+
3066
+ // src/structures/MessageReaction.ts
3067
+ var import_types20 = require("@fluxerjs/types");
3068
+ var import_rest4 = require("@fluxerjs/rest");
3069
+ var MessageReaction = class extends Base {
3070
+ client;
3071
+ messageId;
3072
+ channelId;
3073
+ guildId;
3074
+ emoji;
3075
+ /** Raw gateway payload for low-level access. */
3076
+ _data;
3077
+ constructor(client, data) {
3078
+ super();
3079
+ this.client = client;
3080
+ this._data = data;
3081
+ this.messageId = data.message_id;
3082
+ this.channelId = data.channel_id;
3083
+ this.guildId = data.guild_id ?? null;
3084
+ this.emoji = data.emoji;
3085
+ }
3086
+ /** Emoji as a string: unicode or "name:id" for custom. */
3087
+ get emojiIdentifier() {
3088
+ return this.emoji.id ? `${this.emoji.name}:${this.emoji.id}` : this.emoji.name;
3089
+ }
3090
+ /** Guild where this reaction was added. Resolved from cache; null for DMs or if not cached. */
3091
+ get guild() {
3092
+ return this.guildId ? this.client.guilds.get(this.guildId) ?? null : null;
3093
+ }
3094
+ /**
3095
+ * Fetch the message this reaction belongs to.
3096
+ * Use when you need to edit, delete, or otherwise interact with the message.
3097
+ * @throws FluxerError with MESSAGE_NOT_FOUND if the message does not exist
3098
+ */
3099
+ async fetchMessage() {
3100
+ try {
3101
+ const data = await this.client.rest.get(
3102
+ import_types20.Routes.channelMessage(this.channelId, this.messageId)
3103
+ );
3104
+ return new Message(this.client, data);
3105
+ } catch (err) {
3106
+ if (err instanceof import_rest4.RateLimitError) throw err;
3107
+ if (err instanceof import_rest4.FluxerAPIError && err.statusCode === 404) {
3108
+ throw new import_util.FluxerError(`Message ${this.messageId} not found in channel ${this.channelId}`, {
3109
+ code: import_util2.ErrorCodes.MessageNotFound,
3110
+ cause: err
3111
+ });
3112
+ }
3113
+ throw err instanceof import_util.FluxerError ? err : new import_util.FluxerError(String(err), { cause: err });
3114
+ }
3115
+ }
3116
+ };
3117
+
3118
+ // src/client/EventHandlerRegistry.ts
3119
+ var handlers = /* @__PURE__ */ new Map();
3120
+ function normalizeInviteCreatePayload(client, payload) {
3121
+ if (!payload?.code) return null;
3122
+ const guildId = payload.guild?.id ?? payload.guild_id ?? "0";
3123
+ const cachedGuild = guildId !== "0" ? client.guilds.get(guildId) : null;
3124
+ const guild = {
3125
+ id: guildId,
3126
+ name: payload.guild?.name ?? cachedGuild?.name ?? "Unknown Guild",
3127
+ icon: payload.guild?.icon ?? null,
3128
+ banner: payload.guild?.banner ?? null,
3129
+ splash: payload.guild?.splash ?? null,
3130
+ features: payload.guild?.features
3131
+ };
3132
+ const channelId = payload.channel?.id ?? payload.channel_id ?? "0";
3133
+ const cachedChannel = channelId !== "0" ? client.channels.get(channelId) : null;
3134
+ const channel = {
3135
+ id: channelId,
3136
+ type: payload.channel?.type ?? cachedChannel?.type ?? 0,
3137
+ name: payload.channel?.name ?? cachedChannel?.name ?? null,
3138
+ icon: payload.channel?.icon ?? null
3139
+ };
3140
+ return {
3141
+ code: payload.code,
3142
+ type: typeof payload.type === "number" ? payload.type : 0,
3143
+ guild,
3144
+ channel,
3145
+ inviter: payload.inviter ?? null,
3146
+ member_count: payload.member_count,
3147
+ presence_count: payload.presence_count,
3148
+ expires_at: payload.expires_at,
3149
+ temporary: payload.temporary,
3150
+ created_at: payload.created_at,
3151
+ uses: payload.uses,
3152
+ max_uses: payload.max_uses,
3153
+ max_age: payload.max_age
3154
+ };
3155
+ }
3156
+ handlers.set("MESSAGE_CREATE", async (client, d) => {
3157
+ const data = d;
3158
+ if (data.guild_id && data.member && data.author) {
3159
+ const guild = client.guilds.get(data.guild_id);
3160
+ if (guild) {
3161
+ const memberData = { ...data.member, user: data.author, guild_id: data.guild_id };
3162
+ const member = new GuildMember(client, memberData, guild);
3163
+ guild.members.set(member.id, member);
3164
+ }
3165
+ }
3166
+ client._addMessageToCache(data.channel_id, data);
3167
+ client.emit(Events.MessageCreate, new Message(client, data));
3168
+ });
3169
+ handlers.set("MESSAGE_UPDATE", async (client, d) => {
3170
+ const partial = d;
3171
+ const cache = client._getMessageCache(partial.channel_id);
3172
+ let oldMessage = null;
3173
+ let mergedData = partial;
3174
+ if (cache) {
3175
+ const oldData = cache.get(partial.id);
3176
+ if (oldData) {
3177
+ oldMessage = new Message(client, oldData);
3178
+ mergedData = { ...oldData, ...partial };
3179
+ }
3180
+ cache.set(partial.id, mergedData);
3181
+ }
3182
+ const newMessage = new Message(client, mergedData);
3183
+ client.emit(Events.MessageUpdate, oldMessage, newMessage);
3184
+ });
3185
+ handlers.set("MESSAGE_DELETE", async (client, d) => {
3186
+ const data = d;
3187
+ client._removeMessageFromCache(data.channel_id, data.id);
3188
+ const channel = client.channels.get(data.channel_id) ?? null;
3189
+ client.emit(Events.MessageDelete, {
3190
+ id: data.id,
3191
+ channelId: data.channel_id,
3192
+ channel,
3193
+ content: data.content ?? null,
3194
+ authorId: data.author_id ?? null
3195
+ });
3196
+ });
3197
+ handlers.set("MESSAGE_REACTION_ADD", async (client, d) => {
3198
+ const data = d;
3199
+ const reaction = new MessageReaction(client, data);
3200
+ const user = client.getOrCreateUser({
3201
+ id: data.user_id,
3202
+ username: "Unknown",
3203
+ discriminator: "0"
3204
+ });
3205
+ client.emit(Events.MessageReactionAdd, reaction, user);
3206
+ });
3207
+ handlers.set("MESSAGE_REACTION_REMOVE", async (client, d) => {
3208
+ const data = d;
3209
+ const reaction = new MessageReaction(client, data);
3210
+ const user = client.getOrCreateUser({
3211
+ id: data.user_id,
3212
+ username: "Unknown",
3213
+ discriminator: "0"
3214
+ });
3215
+ client.emit(Events.MessageReactionRemove, reaction, user);
3216
+ });
3217
+ handlers.set("MESSAGE_REACTION_REMOVE_ALL", async (client, d) => {
3218
+ client.emit(Events.MessageReactionRemoveAll, d);
3219
+ });
3220
+ handlers.set("MESSAGE_REACTION_REMOVE_EMOJI", async (client, d) => {
3221
+ client.emit(
3222
+ Events.MessageReactionRemoveEmoji,
3223
+ d
3224
+ );
3225
+ });
3226
+ handlers.set("GUILD_CREATE", async (client, d) => {
3227
+ const guildData = normalizeGuildPayload(d);
3228
+ if (!guildData) return;
3229
+ const guild = new Guild(client, guildData);
3230
+ client.guilds.set(guild.id, guild);
3231
+ const g = d;
3232
+ for (const ch of g.channels ?? []) {
3233
+ const channel = Channel.from(client, ch);
3234
+ if (channel) {
3235
+ client.channels.set(channel.id, channel);
3236
+ guild.channels.set(channel.id, channel);
3237
+ }
3238
+ }
3239
+ for (const m of g.members ?? []) {
3240
+ if (m?.user?.id) {
3241
+ const memberData = { ...m, guild_id: guild.id };
3242
+ const member = new GuildMember(client, memberData, guild);
3243
+ guild.members.set(member.id, member);
3244
+ }
3245
+ }
3246
+ client.emit(Events.GuildCreate, guild);
3247
+ if (g.voice_states?.length) {
3248
+ client.emit(Events.VoiceStatesSync, { guildId: guild.id, voiceStates: g.voice_states });
3249
+ }
3250
+ client._onGuildReceived(guild.id);
3251
+ });
3252
+ handlers.set("GUILD_UPDATE", async (client, d) => {
3253
+ const guildData = normalizeGuildPayload(d);
3254
+ if (!guildData) return;
3255
+ const old = client.guilds.get(guildData.id);
3256
+ const updated = new Guild(client, guildData);
3257
+ client.guilds.set(updated.id, updated);
3258
+ client.emit(Events.GuildUpdate, old ?? updated, updated);
3259
+ });
3260
+ handlers.set("GUILD_DELETE", async (client, d) => {
3261
+ const g = d;
3262
+ const guild = client.guilds.get(g.id);
3263
+ if (guild) {
3264
+ client.guilds.delete(g.id);
3265
+ client.emit(Events.GuildDelete, guild);
3266
+ }
3267
+ });
3268
+ handlers.set("CHANNEL_CREATE", async (client, d) => {
3269
+ const ch = Channel.from(client, d);
3270
+ if (ch) {
3271
+ client.channels.set(ch.id, ch);
3272
+ if ("guildId" in ch && ch.guildId) {
3273
+ const guild = client.guilds.get(ch.guildId);
3274
+ if (guild) guild.channels.set(ch.id, ch);
3275
+ }
3276
+ client.emit(Events.ChannelCreate, ch);
3277
+ }
3278
+ });
3279
+ handlers.set("CHANNEL_UPDATE", async (client, d) => {
3280
+ const ch = d;
3281
+ const oldCh = client.channels.get(ch.id);
3282
+ const newCh = Channel.from(client, ch);
3283
+ if (newCh) {
3284
+ client.channels.set(newCh.id, newCh);
3285
+ if ("guildId" in newCh && newCh.guildId) {
3286
+ const guild = client.guilds.get(newCh.guildId);
3287
+ if (guild) guild.channels.set(newCh.id, newCh);
3288
+ }
3289
+ client.emit(Events.ChannelUpdate, oldCh ?? newCh, newCh);
3290
+ }
3291
+ });
3292
+ handlers.set("CHANNEL_DELETE", async (client, d) => {
3293
+ const ch = d;
3294
+ const channel = client.channels.get(ch.id);
3295
+ if (channel) {
3296
+ if ("guildId" in channel && channel.guildId) {
3297
+ const guild = client.guilds.get(channel.guildId);
3298
+ if (guild) guild.channels.delete(channel.id);
3299
+ }
3300
+ client.channels.delete(ch.id);
3301
+ client.emit(Events.ChannelDelete, channel);
3302
+ }
3303
+ });
3304
+ handlers.set("GUILD_MEMBER_ADD", async (client, d) => {
3305
+ const data = d;
3306
+ const guild = client.guilds.get(data.guild_id);
3307
+ if (guild) {
3308
+ const member = new GuildMember(client, data, guild);
3309
+ guild.members.set(member.id, member);
3310
+ client.emit(Events.GuildMemberAdd, member);
3311
+ }
3312
+ });
3313
+ handlers.set("GUILD_MEMBER_UPDATE", async (client, d) => {
3314
+ const data = d;
3315
+ const guild = client.guilds.get(data.guild_id);
3316
+ if (guild) {
3317
+ const oldM = guild.members.get(data.user.id);
3318
+ const newM = new GuildMember(client, data, guild);
3319
+ guild.members.set(newM.id, newM);
3320
+ client.emit(Events.GuildMemberUpdate, oldM ?? newM, newM);
3321
+ }
3322
+ });
3323
+ handlers.set("GUILD_MEMBER_REMOVE", async (client, d) => {
3324
+ const data = d;
3325
+ const guild = client.guilds.get(data.guild_id);
3326
+ if (!guild || !data.user?.id) return;
3327
+ let member = guild.members.get(data.user.id);
3328
+ if (member) {
3329
+ guild.members.delete(data.user.id);
3330
+ } else {
3331
+ const user = {
3332
+ ...data.user,
3333
+ id: data.user.id,
3334
+ username: data.user.username ?? "Unknown",
3335
+ discriminator: data.user.discriminator ?? "0"
3336
+ };
3337
+ const memberData = {
3338
+ user,
3339
+ roles: [],
3340
+ joined_at: (/* @__PURE__ */ new Date(0)).toISOString(),
3341
+ nick: null
3342
+ };
3343
+ member = new GuildMember(client, memberData, guild);
3344
+ }
3345
+ client.emit(Events.GuildMemberRemove, member);
3346
+ });
3347
+ handlers.set("GUILD_MEMBERS_CHUNK", async (client, d) => {
3348
+ const data = d;
3349
+ const guild = client.guilds.get(data.guild_id);
3350
+ if (guild) {
3351
+ for (const m of data.members ?? []) {
3352
+ if (m?.user?.id) {
3353
+ const memberData = { ...m, guild_id: guild.id };
3354
+ const member = new GuildMember(client, memberData, guild);
3355
+ guild.members.set(member.id, member);
3356
+ }
3357
+ }
3358
+ }
3359
+ client.emit(Events.GuildMembersChunk, data);
3360
+ });
3361
+ handlers.set("INTERACTION_CREATE", async (client, d) => {
3362
+ client.emit(
3363
+ Events.InteractionCreate,
3364
+ createInteraction(client, d)
3365
+ );
3366
+ });
3367
+ handlers.set("VOICE_STATE_UPDATE", async (client, d) => {
3368
+ client.emit(Events.VoiceStateUpdate, d);
3369
+ });
3370
+ handlers.set("VOICE_SERVER_UPDATE", async (client, d) => {
3371
+ client.emit(Events.VoiceServerUpdate, d);
3372
+ });
3373
+ handlers.set("MESSAGE_DELETE_BULK", async (client, d) => {
3374
+ const data = d;
3375
+ for (const id of data.ids ?? []) {
3376
+ client._removeMessageFromCache(data.channel_id, id);
3377
+ }
3378
+ client.emit(Events.MessageDeleteBulk, data);
3379
+ });
3380
+ handlers.set("GUILD_BAN_ADD", async (client, d) => {
3381
+ const data = d;
3382
+ const banData = {
3383
+ user: data.user,
3384
+ reason: data.reason ?? null,
3385
+ guild_id: data.guild_id
3386
+ };
3387
+ const ban = new GuildBan(client, banData, data.guild_id);
3388
+ client.emit(Events.GuildBanAdd, ban);
3389
+ });
3390
+ handlers.set("GUILD_BAN_REMOVE", async (client, d) => {
3391
+ const data = d;
3392
+ const ban = new GuildBan(client, { ...data, reason: null }, data.guild_id);
3393
+ client.emit(Events.GuildBanRemove, ban);
3394
+ });
3395
+ handlers.set("GUILD_EMOJIS_UPDATE", async (client, d) => {
3396
+ const data = d;
3397
+ const guild = client.guilds.get(data.guild_id);
3398
+ if (guild) {
3399
+ guild.emojis.clear();
3400
+ for (const e of data.emojis ?? []) {
3401
+ if (!e.id || e.name == null) continue;
3402
+ guild.emojis.set(
3403
+ e.id,
3404
+ new GuildEmoji(
3405
+ client,
3406
+ { id: e.id, name: e.name, animated: e.animated ?? false, guild_id: guild.id },
3407
+ guild.id
3408
+ )
3409
+ );
3410
+ }
3411
+ }
3412
+ client.emit(Events.GuildEmojisUpdate, d);
3413
+ });
3414
+ handlers.set("GUILD_STICKERS_UPDATE", async (client, d) => {
3415
+ client.emit(Events.GuildStickersUpdate, d);
3416
+ });
3417
+ handlers.set("GUILD_INTEGRATIONS_UPDATE", async (client, d) => {
3418
+ client.emit(Events.GuildIntegrationsUpdate, d);
3419
+ });
3420
+ handlers.set("GUILD_ROLE_CREATE", async (client, d) => {
3421
+ const data = d;
3422
+ const guild = client.guilds.get(data.guild_id);
3423
+ if (guild) {
3424
+ guild.roles.set(data.role.id, new Role(client, data.role, guild.id));
3425
+ }
3426
+ client.emit(Events.GuildRoleCreate, data);
3427
+ });
3428
+ handlers.set("GUILD_ROLE_UPDATE", async (client, d) => {
3429
+ const data = d;
3430
+ const guild = client.guilds.get(data.guild_id);
3431
+ if (guild) {
3432
+ const existing = guild.roles.get(data.role.id);
3433
+ if (existing) {
3434
+ existing._patch(data.role);
3435
+ } else {
3436
+ guild.roles.set(data.role.id, new Role(client, data.role, guild.id));
3437
+ }
3438
+ }
3439
+ client.emit(Events.GuildRoleUpdate, data);
3440
+ });
3441
+ handlers.set("GUILD_ROLE_DELETE", async (client, d) => {
3442
+ const data = d;
3443
+ const guild = client.guilds.get(data.guild_id);
3444
+ if (guild) guild.roles.delete(data.role_id);
3445
+ client.emit(Events.GuildRoleDelete, data);
3446
+ });
3447
+ handlers.set("GUILD_SCHEDULED_EVENT_CREATE", async (client, d) => {
3448
+ client.emit(Events.GuildScheduledEventCreate, d);
3449
+ });
3450
+ handlers.set("GUILD_SCHEDULED_EVENT_UPDATE", async (client, d) => {
3451
+ client.emit(Events.GuildScheduledEventUpdate, d);
3452
+ });
3453
+ handlers.set("GUILD_SCHEDULED_EVENT_DELETE", async (client, d) => {
3454
+ client.emit(Events.GuildScheduledEventDelete, d);
3455
+ });
3456
+ handlers.set("CHANNEL_PINS_UPDATE", async (client, d) => {
3457
+ client.emit(Events.ChannelPinsUpdate, d);
3458
+ });
3459
+ handlers.set("INVITE_CREATE", async (client, d) => {
3460
+ const data = normalizeInviteCreatePayload(client, d);
3461
+ if (!data) {
3462
+ client.emit(
3463
+ Events.Debug,
3464
+ "[Gateway] INVITE_CREATE payload had no invite code (documented as possibly empty)"
3465
+ );
3466
+ return;
3467
+ }
3468
+ client.emit(Events.InviteCreate, new Invite(client, data));
3469
+ });
3470
+ handlers.set("INVITE_DELETE", async (client, d) => {
3471
+ client.emit(Events.InviteDelete, d);
3472
+ });
3473
+ handlers.set("TYPING_START", async (client, d) => {
3474
+ client.emit(Events.TypingStart, d);
3475
+ });
3476
+ handlers.set("USER_UPDATE", async (client, d) => {
3477
+ const data = d;
3478
+ if (client.user?.id === data.id) {
3479
+ client.user._patch(data);
3480
+ }
3481
+ client.emit(Events.UserUpdate, data);
3482
+ });
3483
+ handlers.set("PRESENCE_UPDATE", async (client, d) => {
3484
+ client.emit(Events.PresenceUpdate, d);
3485
+ });
3486
+ handlers.set("WEBHOOKS_UPDATE", async (client, d) => {
3487
+ client.emit(Events.WebhooksUpdate, d);
3488
+ });
3489
+ handlers.set("RESUMED", async (client) => {
3490
+ client.emit(Events.Resumed);
3491
+ });
3492
+ var eventHandlers = handlers;
3493
+
3494
+ // src/client/Client.ts
3495
+ function createEventMethods(client) {
3496
+ const result = {};
3497
+ for (const key of Object.keys(Events)) {
3498
+ const eventName = Events[key];
3499
+ result[key] = (cb) => {
3500
+ client.on(eventName, cb);
3501
+ return client;
3502
+ };
3503
+ }
3504
+ return result;
3505
+ }
3506
+ var Client = class extends import_events3.EventEmitter {
3507
+ /** @param options - Token, REST config, WebSocket, presence, etc. */
3508
+ constructor(options = {}) {
3509
+ super();
3510
+ this.options = options;
3511
+ this.setMaxListeners(0);
3512
+ this.events = createEventMethods(this);
3513
+ Object.defineProperty(this.channels, "cache", {
3514
+ get: () => this.channels,
3515
+ configurable: true
3516
+ });
3517
+ Object.defineProperty(this.guilds, "cache", {
3518
+ get: () => this.guilds,
3519
+ configurable: true
3520
+ });
3521
+ Object.defineProperty(this.users, "cache", {
3522
+ get: () => this.users,
3523
+ configurable: true
3524
+ });
3525
+ this.rest = new import_rest5.REST({
3526
+ api: options.rest?.api ?? "https://api.fluxer.app",
3527
+ version: options.rest?.version ?? "1",
3528
+ ...options.rest
3529
+ });
3530
+ }
3531
+ rest;
3532
+ guilds = new GuildManager(this);
3533
+ channels = new ChannelManager(this);
3534
+ users = new UsersManager(this);
3535
+ /** Typed event handlers. Use client.events.MessageReactionAdd((reaction, user, messageId, channelId, emoji, userId) => {...}) or client.on(Events.MessageReactionAdd, ...). */
3536
+ events;
3537
+ /** The authenticated bot user. Null until READY is received. */
3538
+ user = null;
3539
+ /** Timestamp when the client became ready. Null until READY is received. */
3540
+ readyAt = null;
3541
+ _ws = null;
3542
+ /** When waitForGuilds, set of guild IDs we're waiting for GUILD_CREATE on. Null when not waiting. */
3543
+ _pendingGuildIds = null;
3544
+ /** Timeout for guild stream when READY has no guilds (gateway sends only GUILD_CREATE). Cleared in finally. */
3545
+ _guildStreamSettleTimeout = null;
3546
+ /** Per-channel message cache (channelId -> messageId -> APIMessage). Used when options.cache.messages > 0. */
3547
+ _messageCaches = null;
3548
+ on(event, listener) {
3549
+ return super.on(event, listener);
3550
+ }
3551
+ once(event, listener) {
3552
+ return super.once(event, listener);
3553
+ }
3554
+ off(event, listener) {
3555
+ return super.off(event, listener);
3556
+ }
3557
+ emit(event, ...args) {
3558
+ return super.emit(event, ...args);
3559
+ }
3560
+ /**
3561
+ * Resolve an emoji argument to the API format (unicode or "name:id").
3562
+ * Supports: <:name:id>, :name:, name:id, { name, id }, unicode.
3563
+ * When id is missing (e.g. :name:), fetches guild emojis if guildId provided.
3564
+ * When reacting in a guild channel, custom emojis must be from that guild.
3565
+ * @param emoji - Emoji string or object
3566
+ * @param guildId - Guild ID for resolving custom emoji by name (required when id is missing)
3567
+ * @returns API-formatted string for reactions
3568
+ */
3569
+ async resolveEmoji(emoji, guildId) {
3570
+ if (typeof emoji === "object" && emoji.id) {
3571
+ if (guildId) {
3572
+ await this.assertEmojiInGuild(emoji.id, guildId);
3573
+ }
3574
+ return (0, import_util10.formatEmoji)({ name: emoji.name, id: emoji.id, animated: emoji.animated });
3575
+ }
3576
+ const parsed = (0, import_util10.parseEmoji)(
3577
+ typeof emoji === "string" ? emoji : emoji.id ? `:${emoji.name}:` : emoji.name
3578
+ );
3579
+ if (!parsed) {
3580
+ throw new import_util.FluxerError("Invalid emoji", { code: import_util2.ErrorCodes.InvalidEmoji });
3581
+ }
3582
+ if (parsed.id) {
3583
+ if (guildId) {
3584
+ await this.assertEmojiInGuild(parsed.id, guildId);
3585
+ }
3586
+ return (0, import_util10.formatEmoji)(parsed);
3587
+ }
3588
+ if (!/^\w+$/.test(parsed.name)) return parsed.name;
3589
+ const unicodeFromShortcode = (0, import_util10.getUnicodeFromShortcode)(parsed.name);
3590
+ if (unicodeFromShortcode) return unicodeFromShortcode;
3591
+ if (guildId) {
3592
+ const emojis = await this.rest.get(import_types21.Routes.guildEmojis(guildId));
3593
+ const list = Array.isArray(emojis) ? emojis : Object.values(emojis ?? {});
3594
+ const found = list.find((e) => e.name && e.name.toLowerCase() === parsed.name.toLowerCase());
3595
+ if (found) return (0, import_util10.formatEmoji)({ ...parsed, id: found.id, animated: found.animated });
3596
+ throw new import_util.FluxerError(
3597
+ `Custom emoji ":${parsed.name}:" not found in guild. Use name:id or <:name:id> format.`,
3598
+ { code: import_util2.ErrorCodes.EmojiNotFound }
3599
+ );
3600
+ }
3601
+ if (/^\w+$/.test(parsed.name)) {
3602
+ throw new import_util.FluxerError(
3603
+ `Custom emoji ":${parsed.name}:" requires guild context. Use message.react() in a guild channel, or pass guildId to client.resolveEmoji().`,
3604
+ { code: import_util2.ErrorCodes.EmojiRequiresGuild }
3605
+ );
3606
+ }
3607
+ return parsed.name;
3608
+ }
3609
+ /**
3610
+ * Asserts that a custom emoji (by id) belongs to the given guild.
3611
+ * Used when reacting in guild channels to reject emojis from other servers.
3612
+ * @throws FluxerError with EMOJI_NOT_IN_GUILD if the emoji is not in the guild
3613
+ */
3614
+ async assertEmojiInGuild(emojiId, guildId) {
3615
+ const emojis = await this.rest.get(import_types21.Routes.guildEmojis(guildId));
3616
+ const list = Array.isArray(emojis) ? emojis : Object.values(emojis ?? {});
3617
+ const found = list.some((e) => e.id === emojiId);
3618
+ if (!found) {
3619
+ throw new import_util.FluxerError("Custom emoji is from another server. Use an emoji from this server.", {
3620
+ code: import_util2.ErrorCodes.EmojiNotInGuild
3621
+ });
3622
+ }
3623
+ }
3624
+ /**
3625
+ * Fetch instance info (API URL, gateway URL, features). GET /instance.
3626
+ * Does not require authentication.
3627
+ */
3628
+ async fetchInstance() {
3629
+ return this.rest.get(import_types21.Routes.instance(), { auth: false });
3630
+ }
3631
+ /**
3632
+ * Fetch instance discovery document (API URL, gateway URL, features). GET /.well-known/fluxer.
3633
+ * Does not require authentication.
3634
+ */
3635
+ async fetchInstanceDiscovery() {
3636
+ return this.rest.get(import_types21.Routes.instanceDiscovery(), { auth: false });
3637
+ }
3638
+ /**
3639
+ * Fetch gateway connection metadata (WebSocket URL, recommended shards, session limits).
3640
+ * GET /gateway/bot (authenticated).
3641
+ */
3642
+ async fetchGatewayInfo() {
3643
+ return this.rest.get(import_types21.Routes.gatewayBot());
3644
+ }
3645
+ /**
3646
+ * Fetch a message by channel and message ID. Use when you have IDs (e.g. from a DB).
3647
+ * @param channelId - Snowflake of the channel
3648
+ * @param messageId - Snowflake of the message
3649
+ * @returns The message
3650
+ * @throws FluxerError with MESSAGE_NOT_FOUND if the message does not exist
3651
+ * @deprecated Use channel.messages.fetch(messageId). For IDs-only: (await client.channels.resolve(channelId))?.messages?.fetch(messageId)
3652
+ * @example
3653
+ * const channel = await client.channels.resolve(channelId);
3654
+ * const message = await channel?.messages?.fetch(messageId);
3655
+ */
3656
+ async fetchMessage(channelId, messageId) {
3657
+ (0, import_util10.emitDeprecationWarning)(
3658
+ "Client.fetchMessage()",
3659
+ "Use channel.messages.fetch(messageId). For IDs-only: (await client.channels.resolve(channelId))?.messages?.fetch(messageId)"
3660
+ );
3661
+ return this.channels.fetchMessage(channelId, messageId);
3662
+ }
3663
+ /**
3664
+ * Send a message to any channel by ID. Shorthand for client.channels.send().
3665
+ * Works even when the channel is not cached.
3666
+ * @deprecated Use client.channels.send(channelId, payload).
3667
+ */
3668
+ async sendToChannel(channelId, payload) {
3669
+ (0, import_util10.emitDeprecationWarning)(
3670
+ "Client.sendToChannel()",
3671
+ "Use client.channels.send(channelId, payload)."
3672
+ );
3673
+ return this.channels.send(channelId, payload);
3674
+ }
3675
+ /**
3676
+ * Get the message cache for a channel. Returns null if message caching is disabled.
3677
+ * Used by MessageManager.get() and event handlers.
3678
+ * @internal
3679
+ */
3680
+ _getMessageCache(channelId) {
3681
+ const limit = this.options.cache?.messages ?? 0;
3682
+ if (limit <= 0) return null;
3683
+ if (!this._messageCaches) this._messageCaches = /* @__PURE__ */ new Map();
3684
+ let cache = this._messageCaches.get(channelId);
3685
+ if (!cache) {
3686
+ cache = /* @__PURE__ */ new Map();
3687
+ this._messageCaches.set(channelId, cache);
3688
+ }
3689
+ return cache;
3690
+ }
3691
+ /**
3692
+ * Add a message to the channel cache. Evicts oldest (FIFO) when over limit.
3693
+ * @internal
3694
+ */
3695
+ _addMessageToCache(channelId, data) {
3696
+ const cache = this._getMessageCache(channelId);
3697
+ if (!cache) return;
3698
+ const limit = this.options.cache?.messages ?? 0;
3699
+ if (limit > 0 && cache.size >= limit && !cache.has(data.id)) {
3700
+ const firstKey = cache.keys().next().value;
3701
+ if (firstKey !== void 0) cache.delete(firstKey);
3702
+ }
3703
+ cache.set(data.id, { ...data });
3704
+ }
3705
+ /**
3706
+ * Remove a message from the channel cache.
3707
+ * @internal
3708
+ */
3709
+ _removeMessageFromCache(channelId, messageId) {
3710
+ this._messageCaches?.get(channelId)?.delete(messageId);
3711
+ }
3712
+ /**
3713
+ * Get or create a User from API data. Caches in client.users.
3714
+ * Updates existing user's username, avatar, etc. when fresh data is provided.
3715
+ */
3716
+ getOrCreateUser(data) {
3717
+ const existing = this.users.get(data.id);
3718
+ if (existing) {
3719
+ existing._patch(data);
3720
+ return existing;
3721
+ }
3722
+ const user = new User(this, data);
3723
+ this.users.set(user.id, user);
3724
+ return user;
3725
+ }
3726
+ /** WebSocket manager. Throws if not logged in. */
3727
+ get ws() {
3728
+ if (!this._ws) {
3729
+ throw new import_util.FluxerError("Client is not logged in. Call login() first.", {
3730
+ code: import_util2.ErrorCodes.NotLoggedIn
3731
+ });
3732
+ }
3733
+ return this._ws;
3734
+ }
3735
+ /**
3736
+ * Send a payload to the gateway (e.g. Voice State Update).
3737
+ * @param shardId - Shard ID (use 0 for single-shard)
3738
+ * @param payload - Gateway payload to send
3739
+ */
3740
+ sendToGateway(shardId, payload) {
3741
+ this.ws.send(shardId, payload);
3742
+ }
3743
+ /**
3744
+ * Run gateway event handlers. By default (see {@link ClientOptions.gatewayDeferHandlers}) work is deferred to the next
3745
+ * macrotask so user code does not block the WebSocket `message` callback.
3746
+ */
3747
+ handleDispatch(payload) {
3748
+ if (payload.op !== 0 || !payload.t) return Promise.resolve();
3749
+ const { t: event, d } = payload;
3750
+ const handler = eventHandlers.get(event);
3751
+ if (!handler) return Promise.resolve();
3752
+ const run = async () => {
3753
+ try {
3754
+ await handler(this, d);
3755
+ } catch (err) {
3756
+ this.emit(Events.Error, err instanceof Error ? err : new Error(String(err)));
3757
+ }
3758
+ };
3759
+ if (this.options.gatewayDeferHandlers === false) {
3760
+ return run();
3761
+ }
3762
+ return new Promise((resolve, reject) => {
3763
+ const start = () => {
3764
+ void run().then(resolve).catch(reject);
3765
+ };
3766
+ if (typeof setImmediate === "function") {
3767
+ setImmediate(start);
3768
+ } else {
3769
+ setTimeout(start, 0);
3770
+ }
3771
+ });
3772
+ }
3773
+ /**
3774
+ * Connect to the Fluxer gateway and authenticate.
3775
+ * @param token - Bot token (e.g. from FLUXER_BOT_TOKEN)
3776
+ */
3777
+ async login(token) {
3778
+ if (this._ws) {
3779
+ throw new import_util.FluxerError("Client is already logged in. Call destroy() first.", {
3780
+ code: import_util2.ErrorCodes.AlreadyLoggedIn
3781
+ });
3782
+ }
3783
+ this.rest.setToken(token);
3784
+ let intents = this.options.intents ?? 0;
3785
+ if (intents !== 0) {
3786
+ if (!this.options.suppressIntentWarning) {
3787
+ if (typeof process !== "undefined" && process.emitWarning) {
3788
+ process.emitWarning("Fluxer does not support intents yet. Value has been set to 0.", {
3789
+ type: "FluxerIntents"
3790
+ });
3791
+ } else {
3792
+ console.warn("Fluxer does not support intents yet. Value has been set to 0.");
3793
+ }
3794
+ }
3795
+ intents = 0;
3796
+ }
3797
+ this._ws = new import_ws.WebSocketManager({
3798
+ token,
3799
+ intents,
3800
+ presence: this.options.presence,
3801
+ rest: { get: (route) => this.rest.get(route) },
3802
+ version: this.options.rest?.version ?? "1",
3803
+ debug: this.options.gatewayDebug !== false,
3804
+ WebSocket: this.options.WebSocket
3805
+ });
3806
+ this._ws.on("dispatch", ({ payload }) => {
3807
+ this.handleDispatch(payload).catch(
3808
+ (err) => this.emit(Events.Error, err instanceof Error ? err : new Error(String(err)))
3809
+ );
3810
+ });
3811
+ this._ws.on(
3812
+ "ready",
3813
+ async ({
3814
+ data
3815
+ }) => {
3816
+ this.user = new ClientUser(this, data.user);
3817
+ const waitForGuilds = this.options.waitForGuilds === true;
3818
+ const pending = waitForGuilds ? /* @__PURE__ */ new Set() : null;
3819
+ for (const g of data.guilds ?? []) {
3820
+ if (g.unavailable === true) {
3821
+ if (pending !== null && g.id) pending.add(g.id);
3822
+ continue;
3823
+ }
3824
+ const guildData = normalizeGuildPayload(g);
3825
+ if (!guildData) continue;
3826
+ const guild = new Guild(this, guildData);
3827
+ this.guilds.set(guild.id, guild);
3828
+ const withCh = g;
3829
+ for (const ch of withCh.channels ?? []) {
3830
+ const channel = Channel.from(this, ch);
3831
+ if (channel) {
3832
+ this.channels.set(channel.id, channel);
3833
+ guild.channels.set(channel.id, channel);
3834
+ }
3835
+ }
3836
+ if (withCh.voice_states?.length) {
3837
+ this.emit(Events.VoiceStatesSync, {
3838
+ guildId: guild.id,
3839
+ voiceStates: withCh.voice_states
3840
+ });
3841
+ }
3842
+ }
3843
+ if (pending !== null && pending.size > 0) {
3844
+ this._pendingGuildIds = pending;
3845
+ return;
3846
+ }
3847
+ if (waitForGuilds && (data.guilds ?? []).length === 0) {
3848
+ const GUILD_STREAM_SETTLE_MS = 500;
3849
+ this._guildStreamSettleTimeout = setTimeout(() => {
3850
+ this._guildStreamSettleTimeout = null;
3851
+ this._finalizeReady();
3852
+ }, GUILD_STREAM_SETTLE_MS);
3853
+ return;
3854
+ }
3855
+ this._finalizeReady();
3856
+ }
3857
+ );
3858
+ this._ws.on("error", ({ error }) => this.emit(Events.Error, error));
3859
+ this._ws.on("debug", (msg) => this.emit(Events.Debug, msg));
3860
+ await this._ws.connect();
3861
+ return token;
3862
+ }
3863
+ /**
3864
+ * Called when all guilds have been received (or immediately if not waiting).
3865
+ * Sets readyAt, emits Ready, clears pending state.
3866
+ */
3867
+ _finalizeReady() {
3868
+ this._pendingGuildIds = null;
3869
+ this.readyAt = /* @__PURE__ */ new Date();
3870
+ this.emit(Events.Ready);
3871
+ }
3872
+ /**
3873
+ * Called by GUILD_CREATE handler when waitForGuilds is enabled.
3874
+ * Removes guild from pending set; when empty, finalizes ready.
3875
+ */
3876
+ _onGuildReceived(guildId) {
3877
+ const pending = this._pendingGuildIds;
3878
+ if (pending === null) return;
3879
+ pending.delete(guildId);
3880
+ if (pending.size === 0) this._finalizeReady();
3881
+ }
3882
+ /** Disconnect from the gateway and clear cached data. */
3883
+ async destroy() {
3884
+ if (this._guildStreamSettleTimeout !== null) {
3885
+ clearTimeout(this._guildStreamSettleTimeout);
3886
+ this._guildStreamSettleTimeout = null;
3887
+ }
3888
+ if (this._ws) {
3889
+ this._ws.destroy();
3890
+ this._ws = null;
3891
+ }
3892
+ this.rest.setToken(null);
3893
+ this.user = null;
3894
+ this.readyAt = null;
3895
+ this._pendingGuildIds = null;
3896
+ this.guilds.clear();
3897
+ this.channels.clear();
3898
+ this.users.clear();
3899
+ }
3900
+ /** Returns true if the client has received Ready and `user` is set. */
3901
+ isReady() {
3902
+ return this.readyAt !== null && this.user !== null;
3903
+ }
3904
+ /**
3905
+ * Throws if the client is not ready. Use before accessing client.user or other post-ready state.
3906
+ * @throws FluxerError with CLIENT_NOT_READY if client has not received Ready yet
3907
+ */
3908
+ assertReady() {
3909
+ if (!this.isReady()) {
3910
+ throw new import_util.FluxerError(
3911
+ "Client is not ready yet. Wait for the Ready event before accessing client.user.",
3912
+ {
3913
+ code: import_util2.ErrorCodes.ClientNotReady
3914
+ }
3915
+ );
3916
+ }
3917
+ }
3918
+ static get Routes() {
3919
+ return import_types21.Routes;
3920
+ }
3921
+ };
3922
+ // Annotate the CommonJS export names for ESM import in node:
3923
+ 0 && (module.exports = {
3924
+ Client,
3925
+ Events
3926
+ });