@fluxerjs/core 2.2.0 → 3.1.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.mjs CHANGED
@@ -4,91 +4,14 @@ import { REST } from "@fluxerjs/rest";
4
4
  import { GatewayOpcodes as GatewayOpcodes2, Routes as Routes34 } from "@fluxerjs/types";
5
5
  import { createLogger } from "@fluxerjs/util";
6
6
 
7
- // src/Domain/User.ts
8
- import { Routes as Routes13 } from "@fluxerjs/types";
9
- import { SnowflakeUtil as SnowflakeUtil3 } from "@fluxerjs/util";
10
-
11
- // src/Helpers/Constants.ts
12
- import { DEFAULT_USER_AGENT } from "@fluxerjs/rest";
13
- var CDN_URL = "https://fluxerusercontent.com";
14
- var STATIC_CDN_URL = "https://fluxerstatic.com";
15
-
16
- // src/Helpers/Cdn.ts
17
- function mediaBase(options) {
18
- return (options?.mediaBase ?? CDN_URL).replace(/\/+$/, "");
19
- }
20
- function staticBase(options) {
21
- return (options?.staticCdnBase ?? STATIC_CDN_URL).replace(/\/+$/, "");
22
- }
23
- function getExtension(hash, options) {
24
- const ext = options?.extension ?? "png";
25
- if (hash?.startsWith("a_")) return "gif";
26
- return ext;
27
- }
28
- function appendSize(options) {
29
- return options?.size ? `?size=${options.size}` : "";
30
- }
31
- function cdnAvatarURL(userId, avatarHash, options) {
32
- if (!avatarHash) return null;
33
- const ext = getExtension(avatarHash, options);
34
- const size = appendSize(options);
35
- return `${mediaBase(options)}/avatars/${userId}/${avatarHash}.${ext}${size}`;
36
- }
37
- function cdnBannerURL(resourceId, bannerHash, options) {
38
- if (!bannerHash) return null;
39
- const ext = getExtension(bannerHash, options);
40
- const size = appendSize(options);
41
- return `${mediaBase(options)}/banners/${resourceId}/${bannerHash}.${ext}${size}`;
42
- }
43
- function cdnMemberAvatarURL(guildId, userId, avatarHash, options) {
44
- if (!avatarHash) return null;
45
- const ext = getExtension(avatarHash, options);
46
- const size = appendSize(options);
47
- return `${mediaBase(options)}/guilds/${guildId}/users/${userId}/avatars/${avatarHash}.${ext}${size}`;
48
- }
49
- function cdnMemberBannerURL(guildId, userId, bannerHash, options) {
50
- if (!bannerHash) return null;
51
- const ext = getExtension(bannerHash, options);
52
- const size = appendSize(options);
53
- return `${mediaBase(options)}/guilds/${guildId}/users/${userId}/banners/${bannerHash}.${ext}${size}`;
54
- }
55
- function cdnDefaultAvatarURL(userIdOrIndex, options) {
56
- const index = typeof userIdOrIndex === "string" ? Number(BigInt(userIdOrIndex) % 6n) : Math.abs(Math.floor(userIdOrIndex) % 6);
57
- return `${staticBase(options)}/avatars/${index}.png`;
58
- }
59
- function cdnGuildAssetURL(kind, id, hash, options) {
60
- if (!hash) return null;
61
- const size = options?.size ? `?size=${options.size}` : "";
62
- return `${mediaBase(options)}/${kind}/${id}/${hash}.png${size}`;
63
- }
64
- function cdnEmojiURL(emojiId, animated, options) {
65
- const ext = animated ? "gif" : "png";
66
- return `${mediaBase(options)}/emojis/${emojiId}.${ext}`;
67
- }
68
- function cdnStickerURL(stickerId, animated, options) {
69
- const ext = animated ? "gif" : "png";
70
- return `${mediaBase(options)}/stickers/${stickerId}.${ext}`;
71
- }
72
-
73
- // src/Domain/Base.ts
74
- var Base = class {
75
- };
76
-
77
- // src/Domain/Channel/Base.ts
78
- import { ChannelType, Routes as Routes7 } from "@fluxerjs/types";
79
- import { SnowflakeUtil } from "@fluxerjs/util";
80
-
81
- // src/ClientCore/MessageManager.ts
82
- import { Collection as Collection3 } from "@fluxerjs/collection";
83
- import { Routes as Routes5 } from "@fluxerjs/types";
84
-
85
7
  // src/Domain/Message/Message.ts
86
8
  import { EmbedBuilder as EmbedBuilder2 } from "@fluxerjs/builders";
87
- import { Collection as Collection2 } from "@fluxerjs/collection";
9
+ import { Collection as Collection3 } from "@fluxerjs/collection";
88
10
  import {
89
11
  MessageType,
90
12
  Routes as Routes4
91
13
  } from "@fluxerjs/types";
14
+ import { MessageFlagsBitField } from "@fluxerjs/util";
92
15
 
93
16
  // src/ClientCore/SdkOptions/Attachments.ts
94
17
  function toMessageAttachmentEditWire(attachments) {
@@ -155,21 +78,66 @@ function toAttachmentUploadPlanResponse(data) {
155
78
  }
156
79
 
157
80
  // src/ClientCore/SdkOptions/Channels.ts
81
+ import { resolvePermissionsToBitfield } from "@fluxerjs/util";
82
+ function toOverwriteWire(overwrite) {
83
+ return {
84
+ id: overwrite.id,
85
+ type: overwrite.type,
86
+ allow: overwrite.allow !== void 0 ? resolvePermissionsToBitfield(overwrite.allow) : "0",
87
+ deny: overwrite.deny !== void 0 ? resolvePermissionsToBitfield(overwrite.deny) : "0"
88
+ };
89
+ }
158
90
  function toChannelEditBody(options) {
159
91
  const body = {};
160
92
  if (options.name !== void 0) body.name = options.name;
161
93
  if (options.topic !== void 0) body.topic = options.topic;
94
+ if (options.url !== void 0) body.url = options.url;
162
95
  if (options.parentId !== void 0) body.parent_id = options.parentId;
163
96
  if (options.bitrate !== void 0) body.bitrate = options.bitrate;
164
97
  if (options.userLimit !== void 0) body.user_limit = options.userLimit;
98
+ if (options.voiceConnectionLimit !== void 0) {
99
+ body.voice_connection_limit = options.voiceConnectionLimit;
100
+ }
165
101
  if (options.nsfw !== void 0) body.nsfw = options.nsfw;
102
+ if (options.nsfwOverride !== void 0) body.nsfw_override = options.nsfwOverride;
103
+ if (options.contentWarningLevel !== void 0) {
104
+ body.content_warning_level = options.contentWarningLevel;
105
+ }
106
+ if (options.contentWarningText !== void 0) {
107
+ body.content_warning_text = options.contentWarningText;
108
+ }
166
109
  if (options.rateLimitPerUser !== void 0) {
167
110
  body.rate_limit_per_user = options.rateLimitPerUser;
168
111
  }
169
112
  if (options.rtcRegion !== void 0) body.rtc_region = options.rtcRegion;
113
+ if (options.icon !== void 0) body.icon = options.icon;
114
+ if (options.permissionOverwrites !== void 0) {
115
+ body.permission_overwrites = options.permissionOverwrites.map(toOverwriteWire);
116
+ }
117
+ return body;
118
+ }
119
+ function toChannelCreateBody(options) {
120
+ const body = { name: options.name, type: options.type };
121
+ if (options.topic !== void 0) body.topic = options.topic;
122
+ if (options.url !== void 0) body.url = options.url;
123
+ if (options.parentId !== void 0) body.parent_id = options.parentId;
124
+ if (options.bitrate !== void 0) body.bitrate = options.bitrate;
125
+ if (options.userLimit !== void 0) body.user_limit = options.userLimit;
126
+ if (options.voiceConnectionLimit !== void 0) {
127
+ body.voice_connection_limit = options.voiceConnectionLimit;
128
+ }
170
129
  if (options.permissionOverwrites !== void 0) {
171
- body.permission_overwrites = options.permissionOverwrites;
130
+ body.permission_overwrites = options.permissionOverwrites.map(toOverwriteWire);
172
131
  }
132
+ if (options.nsfw !== void 0) body.nsfw = options.nsfw;
133
+ if (options.nsfwOverride !== void 0) body.nsfw_override = options.nsfwOverride;
134
+ if (options.contentWarningLevel !== void 0) {
135
+ body.content_warning_level = options.contentWarningLevel;
136
+ }
137
+ if (options.contentWarningText !== void 0) {
138
+ body.content_warning_text = options.contentWarningText;
139
+ }
140
+ if (options.rateLimitPerUser !== void 0) body.rate_limit_per_user = options.rateLimitPerUser;
173
141
  return body;
174
142
  }
175
143
  function toChannelInviteBody(options) {
@@ -180,6 +148,13 @@ function toChannelInviteBody(options) {
180
148
  if (options.temporary !== void 0) body.temporary = options.temporary;
181
149
  return body;
182
150
  }
151
+ function toGroupDmEditBody(options) {
152
+ const body = { type: 3 };
153
+ if (options.name !== void 0) body.name = options.name;
154
+ if (options.icon !== void 0) body.icon = options.icon;
155
+ if (options.nicks !== void 0) body.nicks = options.nicks;
156
+ return body;
157
+ }
183
158
 
184
159
  // src/ClientCore/SdkOptions/Discovery.ts
185
160
  function toDiscoveryBody(options) {
@@ -215,32 +190,8 @@ function toDiscoveryStatusPayload(data) {
215
190
  };
216
191
  }
217
192
 
218
- // src/ClientCore/SdkOptions/Expressions.ts
219
- function toEmojiCreateBody(options) {
220
- return { name: options.name, image: options.image };
221
- }
222
- function toEmojiEditBody(options) {
223
- return { name: options.name };
224
- }
225
- function toStickerCreateBody(options) {
226
- const body = {
227
- name: options.name,
228
- image: options.file
229
- };
230
- if (options.description !== void 0) body.description = options.description;
231
- if (options.tags !== void 0) body.tags = options.tags;
232
- return body;
233
- }
234
- function toStickerEditBody(options) {
235
- const body = {};
236
- if (options.name !== void 0) body.name = options.name;
237
- if (options.description !== void 0) body.description = options.description;
238
- if (options.tags !== void 0) body.tags = options.tags;
239
- return body;
240
- }
241
-
242
193
  // src/ClientCore/SdkOptions/Guild.ts
243
- import { resolvePermissionsToBitfield } from "@fluxerjs/util";
194
+ import { resolvePermissionsToBitfield as resolvePermissionsToBitfield2 } from "@fluxerjs/util";
244
195
  function toGuildEditBody(options) {
245
196
  const body = {};
246
197
  if (options.name !== void 0) body.name = options.name;
@@ -268,6 +219,16 @@ function toGuildEditBody(options) {
268
219
  body.splash_card_alignment = options.splashCardAlignment;
269
220
  }
270
221
  if (options.nsfwLevel !== void 0) body.nsfw_level = options.nsfwLevel;
222
+ if (options.nsfw !== void 0) body.nsfw = options.nsfw;
223
+ if (options.contentWarningLevel !== void 0) {
224
+ body.content_warning_level = options.contentWarningLevel;
225
+ }
226
+ if (options.contentWarningText !== void 0) {
227
+ body.content_warning_text = options.contentWarningText;
228
+ }
229
+ if (options.messageHistoryCutoff !== void 0) {
230
+ body.message_history_cutoff = options.messageHistoryCutoff;
231
+ }
271
232
  if (options.features !== void 0) body.features = options.features;
272
233
  return body;
273
234
  }
@@ -277,6 +238,9 @@ function toGuildBanBody(options) {
277
238
  if (options.deleteMessageDays !== void 0) {
278
239
  body.delete_message_days = options.deleteMessageDays;
279
240
  }
241
+ if (options.deleteMessageSeconds !== void 0) {
242
+ body.delete_message_seconds = options.deleteMessageSeconds;
243
+ }
280
244
  if (options.banDurationSeconds !== void 0) {
281
245
  body.ban_duration_seconds = options.banDurationSeconds;
282
246
  }
@@ -291,18 +255,26 @@ function toChannelPositionBody(updates) {
291
255
  return row;
292
256
  });
293
257
  }
294
- function toRoleRequestBody(options) {
258
+ function toRolePermissionsBody(options) {
295
259
  const body = {};
260
+ if (options.permissions !== void 0) {
261
+ body.permissions = typeof options.permissions === "string" ? options.permissions : resolvePermissionsToBitfield2(options.permissions);
262
+ }
263
+ return body;
264
+ }
265
+ function toRoleCreateBody(options) {
266
+ const body = { ...toRolePermissionsBody(options) };
267
+ if (options.name !== void 0) body.name = options.name;
268
+ if (options.color !== void 0) body.color = options.color;
269
+ return body;
270
+ }
271
+ function toRoleEditBody(options) {
272
+ const body = { ...toRolePermissionsBody(options) };
296
273
  if (options.name !== void 0) body.name = options.name;
297
274
  if (options.color !== void 0) body.color = options.color;
298
275
  if (options.hoist !== void 0) body.hoist = options.hoist;
299
276
  if (options.mentionable !== void 0) body.mentionable = options.mentionable;
300
- if (options.unicodeEmoji !== void 0) body.unicode_emoji = options.unicodeEmoji;
301
- if (options.position !== void 0) body.position = options.position;
302
277
  if (options.hoistPosition !== void 0) body.hoist_position = options.hoistPosition;
303
- if (options.permissions !== void 0) {
304
- body.permissions = typeof options.permissions === "string" ? options.permissions : resolvePermissionsToBitfield(options.permissions);
305
- }
306
278
  return body;
307
279
  }
308
280
 
@@ -320,6 +292,8 @@ function toMemberSearchBody(options) {
320
292
  if (options.userCreatedAtLte !== void 0) body.user_created_at_lte = options.userCreatedAtLte;
321
293
  if (options.sortBy !== void 0) body.sort_by = options.sortBy;
322
294
  if (options.sortOrder !== void 0) body.sort_order = options.sortOrder;
295
+ if (options.joinSourceType !== void 0) body.join_source_type = options.joinSourceType;
296
+ if (options.sourceInviteCode !== void 0) body.source_invite_code = options.sourceInviteCode;
323
297
  return body;
324
298
  }
325
299
  function toMemberEditBody(options) {
@@ -332,6 +306,7 @@ function toMemberEditBody(options) {
332
306
  if (options.pronouns !== void 0) body.pronouns = options.pronouns;
333
307
  if (options.accentColor !== void 0) body.accent_color = options.accentColor;
334
308
  if (options.profileFlags !== void 0) body.profile_flags = options.profileFlags;
309
+ if (options.mentionFlags !== void 0) body.mention_flags = options.mentionFlags;
335
310
  if (options.mute !== void 0) body.mute = options.mute;
336
311
  if (options.deaf !== void 0) body.deaf = options.deaf;
337
312
  if (options.communicationDisabledUntil !== void 0) {
@@ -353,15 +328,54 @@ function toBulkFetchWire(requests) {
353
328
  ...r.around !== void 0 ? { around: r.around } : {}
354
329
  }));
355
330
  }
356
-
357
- // src/ClientCore/SdkOptions/Packs.ts
358
- function toPackInviteBody(options) {
359
- const body = {};
360
- if (options.maxUses !== void 0) body.max_uses = options.maxUses;
361
- if (options.maxAge !== void 0) body.max_age = options.maxAge;
362
- if (options.unique !== void 0) body.unique = options.unique;
331
+ function toMessageSearchBody(options = {}) {
332
+ const body = { scope: "current" };
333
+ if (options.content !== void 0) body.content = options.content;
334
+ if (options.contents !== void 0) body.contents = options.contents;
335
+ if (options.exactPhrases !== void 0) body.exact_phrases = options.exactPhrases;
336
+ if (options.channelIds !== void 0) {
337
+ body.channel_id = options.channelIds;
338
+ body.channel_ids = options.channelIds;
339
+ }
340
+ if (options.excludeChannelIds !== void 0) body.exclude_channel_id = options.excludeChannelIds;
341
+ if (options.contextGuildId !== void 0) body.context_guild_id = options.contextGuildId;
342
+ if (options.contextChannelId !== void 0) body.context_channel_id = options.contextChannelId;
343
+ if (options.hitsPerPage !== void 0) body.hits_per_page = options.hitsPerPage;
344
+ if (options.page !== void 0) body.page = options.page;
345
+ if (options.cursor !== void 0) body.cursor = options.cursor;
346
+ if (options.minId !== void 0) body.min_id = options.minId;
347
+ if (options.maxId !== void 0) body.max_id = options.maxId;
348
+ if (options.authorIds !== void 0) body.author_id = options.authorIds;
349
+ if (options.excludeAuthorIds !== void 0) body.exclude_author_id = options.excludeAuthorIds;
350
+ if (options.authorType !== void 0) body.author_type = options.authorType;
351
+ if (options.excludeAuthorType !== void 0) body.exclude_author_type = options.excludeAuthorType;
352
+ if (options.mentions !== void 0) body.mentions = options.mentions;
353
+ if (options.excludeMentions !== void 0) body.exclude_mentions = options.excludeMentions;
354
+ if (options.mentionEveryone !== void 0) body.mention_everyone = options.mentionEveryone;
355
+ if (options.pinned !== void 0) body.pinned = options.pinned;
356
+ if (options.includeNsfw !== void 0) body.include_nsfw = options.includeNsfw;
357
+ if (options.has !== void 0) body.has = options.has;
358
+ if (options.excludeHas !== void 0) body.exclude_has = options.excludeHas;
359
+ if (options.sortBy !== void 0) body.sort_by = options.sortBy;
360
+ if (options.sortOrder !== void 0) body.sort_order = options.sortOrder;
363
361
  return body;
364
362
  }
363
+ function isMessageSearchIndexing(data) {
364
+ return "indexing" in data && data.indexing === true;
365
+ }
366
+ function toMessageSearchResponse(data) {
367
+ if (isMessageSearchIndexing(data)) {
368
+ return { indexing: true };
369
+ }
370
+ return {
371
+ messages: data.messages,
372
+ channels: data.channels,
373
+ total: data.total,
374
+ hitsPerPage: data.hits_per_page,
375
+ page: data.page,
376
+ ...data.cursor !== void 0 ? { cursor: data.cursor } : {}
377
+ };
378
+ }
365
379
 
366
380
  // src/ClientCore/SdkOptions/Presence.ts
367
381
  function toPresenceWire(options) {
@@ -410,9 +424,16 @@ function toSudoBody(options) {
410
424
  return body;
411
425
  }
412
426
 
427
+ // src/Helpers/AuditReason.ts
428
+ var AUDIT_LOG_REASON_HEADER = "X-Audit-Log-Reason";
429
+ function auditReasonHeaders(reason) {
430
+ if (reason == null || reason === "") return {};
431
+ return { headers: { [AUDIT_LOG_REASON_HEADER]: encodeURIComponent(reason) } };
432
+ }
433
+
413
434
  // src/Helpers/MessageUtils/Body.ts
414
- import { EmbedBuilder, MessagePayload } from "@fluxerjs/builders";
415
- import { MessageReferenceType } from "@fluxerjs/types";
435
+ import { AttachmentBuilder, EmbedBuilder, MessagePayload } from "@fluxerjs/builders";
436
+ import { MessageAttachmentFlags, MessageReferenceType } from "@fluxerjs/types";
416
437
 
417
438
  // src/LibErrors/ErrorCodes.ts
418
439
  import { ErrorCodes } from "@fluxerjs/util";
@@ -481,6 +502,37 @@ function applyReplyPingSuppression(body) {
481
502
  function assignIfDefined(target, key, value) {
482
503
  if (value !== void 0) target[key] = value;
483
504
  }
505
+ function normalizeSendFiles(files) {
506
+ if (!files?.length) return void 0;
507
+ const normalized = [];
508
+ const metaFromBuilders = [];
509
+ let anyBuilderMeta = false;
510
+ for (let i = 0; i < files.length; i++) {
511
+ const file = files[i];
512
+ if (!file) continue;
513
+ if (file instanceof AttachmentBuilder) {
514
+ normalized.push(file.toFileData());
515
+ const meta = {
516
+ id: i,
517
+ filename: file.filename,
518
+ ...file.description != null ? { description: file.description } : {},
519
+ ...file.spoiler ? { flags: MessageAttachmentFlags.IS_SPOILER } : {}
520
+ };
521
+ if (file.description != null || file.spoiler) anyBuilderMeta = true;
522
+ metaFromBuilders.push(meta);
523
+ } else {
524
+ normalized.push(file);
525
+ metaFromBuilders.push({
526
+ id: i,
527
+ filename: file.filename ?? file.name
528
+ });
529
+ }
530
+ }
531
+ return {
532
+ files: normalized,
533
+ metaFromBuilders: anyBuilderMeta ? metaFromBuilders : []
534
+ };
535
+ }
484
536
  function buildSendBody(options) {
485
537
  const body = typeof options === "string" ? { content: options } : options;
486
538
  const result = {};
@@ -488,16 +540,17 @@ function buildSendBody(options) {
488
540
  if (body.embeds?.length) {
489
541
  result.embeds = body.embeds.map((e) => e instanceof EmbedBuilder ? e.toJSON() : e);
490
542
  }
543
+ const normalizedFiles = normalizeSendFiles(body.files);
491
544
  if (body.uploadedAttachments?.length) {
492
545
  result.attachments = body.uploadedAttachments;
493
- } else if (body.files?.length) {
546
+ } else if (normalizedFiles?.files.length) {
494
547
  result.attachments = body.attachments?.length ? body.attachments.map((a) => ({
495
548
  id: a.id,
496
549
  filename: a.filename,
497
550
  ...a.title != null && { title: a.title },
498
551
  ...a.description != null && { description: a.description },
499
552
  ...a.flags != null && { flags: a.flags }
500
- })) : body.files.map((f, i) => ({ id: i, filename: f.filename ?? f.name }));
553
+ })) : normalizedFiles.metaFromBuilders.length ? normalizedFiles.metaFromBuilders : normalizedFiles.files.map((f, i) => ({ id: i, filename: f.filename ?? f.name }));
501
554
  }
502
555
  if (body.allowedMentions) result.allowed_mentions = toAPIAllowedMentions(body.allowedMentions);
503
556
  if (body.stickerIds?.length) result.sticker_ids = body.stickerIds;
@@ -591,9 +644,10 @@ async function prepareMessagePostPayload(options, defaults) {
591
644
  } else if (allowedMentions?.repliedUser === false) {
592
645
  applyReplyPingSuppression(body);
593
646
  }
647
+ const resolvedFiles = normalizeSendFiles(files);
594
648
  return {
595
649
  body,
596
- files: !uploadedAttachments?.length && files?.length ? await resolveMessageFiles(files) : void 0
650
+ files: !uploadedAttachments?.length && resolvedFiles?.files.length ? await resolveMessageFiles(resolvedFiles.files) : void 0
597
651
  };
598
652
  }
599
653
 
@@ -642,14 +696,22 @@ function qs(params) {
642
696
  return out ? `?${out}` : "";
643
697
  }
644
698
 
699
+ // src/Domain/Base.ts
700
+ var Base = class {
701
+ };
702
+
645
703
  // src/Domain/Message/MessageReaction.ts
646
- var MessageReaction = class extends Base {
704
+ var MessageReaction = class _MessageReaction extends Base {
647
705
  client;
648
706
  messageId;
649
707
  channelId;
650
708
  guildId;
651
709
  emoji;
652
- /** Raw gateway payload for low-level access. */
710
+ /** Total count when hydrated from a message payload; `1` for gateway add events. */
711
+ count;
712
+ /** Whether the current user reacted (message payload); false for gateway remove. */
713
+ me;
714
+ /** Raw gateway payload for low-level access (null when built from a message aggregate). */
653
715
  _data;
654
716
  constructor(client, data) {
655
717
  super();
@@ -663,6 +725,26 @@ var MessageReaction = class extends Base {
663
725
  ...data.emoji.id !== void 0 ? { id: data.emoji.id } : {},
664
726
  ...data.emoji.animated !== void 0 ? { animated: data.emoji.animated } : {}
665
727
  };
728
+ this.count = 1;
729
+ this.me = false;
730
+ }
731
+ /** Build a reaction aggregate from a message's `reactions` array entry. */
732
+ static fromMessage(message, data) {
733
+ const reaction = new _MessageReaction(message.client, {
734
+ user_id: message.client.user?.id ?? "0",
735
+ message_id: message.id,
736
+ channel_id: message.channelId,
737
+ guild_id: message.guildId ?? void 0,
738
+ emoji: {
739
+ name: data.emoji.name,
740
+ id: data.emoji.id ?? void 0,
741
+ animated: data.emoji.animated ?? void 0
742
+ }
743
+ });
744
+ Object.defineProperty(reaction, "_data", { value: null });
745
+ reaction.count = data.count;
746
+ reaction.me = data.me ?? false;
747
+ return reaction;
666
748
  }
667
749
  /** Emoji as a string for reaction routes: unicode or `name:id` (`a:name:id` when animated). */
668
750
  get emojiIdentifier() {
@@ -672,12 +754,23 @@ var MessageReaction = class extends Base {
672
754
  get guild() {
673
755
  return this.guildId ? this.client.guilds.get(this.guildId) ?? null : null;
674
756
  }
757
+ /** Cached message this reaction belongs to, or null if the message was not cached. */
758
+ get message() {
759
+ const cached = this.client._getMessageCache(this.channelId)?.get(this.messageId);
760
+ return cached ? new Message(this.client, cached) : null;
761
+ }
762
+ /** Cached text-capable channel, or null if uncached / not text-based. */
763
+ get channel() {
764
+ const channel = this.client.channels.get(this.channelId);
765
+ return channel?.isTextBased() ? channel : null;
766
+ }
675
767
  /**
676
- * Fetch the message this reaction belongs to.
677
- * Use when you need to edit, delete, or otherwise interact with the message.
768
+ * Fetch the message this reaction belongs to (cache first, then REST).
678
769
  * @throws FluxerError with MESSAGE_NOT_FOUND if the message does not exist
679
770
  */
680
771
  async fetchMessage() {
772
+ const cached = this.message;
773
+ if (cached) return cached;
681
774
  try {
682
775
  const data = await this.client.rest.get(
683
776
  Routes.channelMessage(this.channelId, this.messageId)
@@ -748,11 +841,17 @@ var Events = {
748
841
  WebhooksUpdate: "webhooksUpdate",
749
842
  Resumed: "resumed",
750
843
  Error: "error",
751
- Debug: "debug"
844
+ Debug: "debug",
845
+ ShardReady: "shardReady",
846
+ ShardResumed: "shardResumed",
847
+ ShardDisconnect: "shardDisconnect",
848
+ ShardReconnecting: "shardReconnecting",
849
+ ShardError: "shardError",
850
+ ShardingRequired: "shardingRequired"
752
851
  };
753
852
 
754
853
  // src/Helpers/ReactionCollector.ts
755
- var ReactionCollector = class extends EventEmitter {
854
+ var ReactionCollector = class _ReactionCollector extends EventEmitter {
756
855
  client;
757
856
  messageId;
758
857
  channelId;
@@ -795,15 +894,17 @@ var ReactionCollector = class extends EventEmitter {
795
894
  ...entry.emoji.animated !== void 0 ? { animated: entry.emoji.animated } : {}
796
895
  }
797
896
  });
798
- const user = entry.member?.user ?? this.client.users.get(entry.userId) ?? this.client.getOrCreateUser({
897
+ const cached = this.client.users.get(entry.userId);
898
+ const user = entry.member?.user ?? cached ?? // Ephemeral stub only; do not cache fake "Unknown" users as real Users.
899
+ {
799
900
  id: entry.userId,
800
901
  username: "Unknown",
801
902
  discriminator: "0",
802
- global_name: null,
903
+ globalName: null,
803
904
  avatar: null,
804
- avatar_color: null,
805
- flags: 0
806
- });
905
+ bot: false,
906
+ system: false
907
+ };
807
908
  this._collect(reaction, user, entry.userId);
808
909
  }
809
910
  };
@@ -835,6 +936,21 @@ var ReactionCollector = class extends EventEmitter {
835
936
  }
836
937
  this.emit("end", this.collected, reason);
837
938
  }
939
+ /**
940
+ * One-shot helper used by {@link Message.awaitReactions}.
941
+ * Resolves with the collected reactions when the collector ends.
942
+ * Rejects if `options.errors` includes the end reason.
943
+ */
944
+ static awaitReactions(client, messageId, channelId, options) {
945
+ const errors = options?.errors ?? [];
946
+ return new Promise((resolve, reject) => {
947
+ const collector = new _ReactionCollector(client, messageId, channelId, options);
948
+ collector.on("end", (collected, reason) => {
949
+ if (errors.includes(reason)) reject(collected);
950
+ else resolve(collected);
951
+ });
952
+ });
953
+ }
838
954
  on(event, listener) {
839
955
  return super.on(event, listener);
840
956
  }
@@ -843,146 +959,366 @@ var ReactionCollector = class extends EventEmitter {
843
959
  }
844
960
  };
845
961
 
846
- // src/Domain/Message/Reactions.ts
847
- import { Routes as Routes2 } from "@fluxerjs/types";
848
- import { parseEmoji } from "@fluxerjs/util";
849
- async function emojiPath(message, emoji) {
850
- return message.client.resolveEmoji(emoji, message.guildId);
851
- }
852
- function toReactionEmoji(emoji) {
853
- if (typeof emoji !== "string") {
854
- return {
855
- name: emoji.name,
856
- ...emoji.id !== void 0 ? { id: emoji.id } : {},
857
- ...emoji.animated !== void 0 ? { animated: emoji.animated } : {}
858
- };
859
- }
860
- const animatedWire = /^a:(\w+):(\d+)$/.exec(emoji);
861
- if (animatedWire) {
862
- return { name: animatedWire[1], id: animatedWire[2], animated: true };
863
- }
864
- const parsed = parseEmoji(emoji);
865
- if (parsed?.id) {
866
- return {
867
- name: parsed.name,
868
- id: parsed.id,
869
- ...parsed.animated ? { animated: true } : {}
870
- };
871
- }
872
- let name = emoji;
873
- try {
874
- name = decodeURIComponent(emoji);
875
- } catch {
876
- }
877
- return { name: parsed?.name ?? name };
878
- }
879
- function emitOwnReactionAdd(message, wireOrInput) {
880
- const user = message.client.user;
881
- if (!user) return;
882
- const emojiPayload = toReactionEmoji(wireOrInput);
883
- const reaction = new MessageReaction(message.client, {
884
- user_id: user.id,
885
- channel_id: message.channelId,
886
- message_id: message.id,
887
- guild_id: message.guildId ?? void 0,
888
- emoji: {
889
- name: emojiPayload.name,
890
- ...emojiPayload.id !== void 0 ? { id: emojiPayload.id } : {},
891
- ...emojiPayload.animated !== void 0 ? { animated: emojiPayload.animated } : {}
892
- }
893
- });
894
- const payload = {
895
- reaction,
896
- user,
897
- messageId: message.id,
898
- channelId: message.channelId,
899
- emoji: emojiPayload,
900
- userId: user.id
901
- };
902
- message.client.emit(Events.MessageReactionAdd, payload);
903
- }
904
- async function reactToMessage(message, emoji) {
905
- const wire = await emojiPath(message, emoji);
906
- await message.client.rest.put(
907
- Routes2.channelMessageReactionMe(message.channelId, message.id, wire)
908
- );
909
- emitOwnReactionAdd(message, wire);
910
- }
911
- async function removeMessageReaction(message, emoji, userId) {
912
- const e = await emojiPath(message, emoji);
913
- const route = userId ? Routes2.channelMessageReactionUser(message.channelId, message.id, e, userId) : Routes2.channelMessageReactionMe(message.channelId, message.id, e);
914
- await message.client.rest.delete(route);
915
- }
916
- async function removeAllMessageReactions(message) {
917
- await message.client.rest.delete(Routes2.channelMessageReactions(message.channelId, message.id));
918
- }
919
- async function removeMessageReactionEmoji(message, emoji) {
920
- const e = await emojiPath(message, emoji);
921
- await message.client.rest.delete(Routes2.channelMessageReaction(message.channelId, message.id, e));
922
- }
923
- async function fetchMessageReactionUsers(message, emoji, options) {
924
- return (await fetchMessageReactionUsersPage(message, emoji, options)).users;
925
- }
926
- async function fetchMessageReactionUsersPage(message, emoji, options) {
927
- const e = await emojiPath(message, emoji);
928
- const params = new URLSearchParams();
929
- if (options?.limit != null) params.set("limit", String(options.limit));
930
- if (options?.after) params.set("after", options.after);
931
- const qs2 = params.toString();
932
- const route = Routes2.channelMessageReactionUsers(message.channelId, message.id, e) + (qs2 ? `?${qs2}` : "");
933
- const data = await message.client.rest.get(route);
934
- if (Array.isArray(data)) {
935
- return {
936
- users: data.map((u) => message.client.getOrCreateUser(u)),
937
- hasMore: false,
938
- nextAfter: null
939
- };
940
- }
941
- const list = data.items ?? data.users ?? [];
962
+ // src/Domain/Message/Attachment.ts
963
+ function toMessageAttachment(data) {
942
964
  return {
943
- users: list.map((u) => message.client.getOrCreateUser(u)),
944
- hasMore: data.has_more ?? false,
945
- nextAfter: data.next_after ?? null
965
+ id: data.id,
966
+ filename: data.filename,
967
+ title: data.title ?? null,
968
+ description: data.description ?? null,
969
+ contentType: data.content_type ?? null,
970
+ contentHash: data.content_hash ?? null,
971
+ size: data.size,
972
+ url: data.url ?? null,
973
+ proxyUrl: data.proxy_url ?? null,
974
+ width: data.width ?? null,
975
+ height: data.height ?? null,
976
+ placeholder: data.placeholder ?? null,
977
+ flags: data.flags ?? 0,
978
+ nsfw: data.nsfw ?? false,
979
+ duration: data.duration ?? null,
980
+ waveform: data.waveform ?? null,
981
+ expiresAt: data.expires_at ? new Date(data.expires_at) : null,
982
+ expired: data.expired ?? false
946
983
  };
947
984
  }
948
985
 
949
- // src/Domain/Message/Send.ts
950
- import { MessagePayload as MessagePayloadBuilder } from "@fluxerjs/builders";
951
- import { Routes as Routes3 } from "@fluxerjs/types";
952
- function toReplyTarget(ref) {
986
+ // src/Domain/Message/Embed.ts
987
+ function toMessageEmbedAuthor(data) {
953
988
  return {
954
- channelId: ref.channel_id,
955
- messageId: ref.message_id,
956
- ...ref.guild_id != null ? { guildId: ref.guild_id } : {}
989
+ name: data.name ?? null,
990
+ url: data.url ?? null,
991
+ iconUrl: data.icon_url ?? null,
992
+ proxyIconUrl: data.proxy_icon_url ?? null
957
993
  };
958
994
  }
959
- function toSendOptions(content) {
960
- if (typeof content === "string") return { content };
961
- if (content instanceof MessagePayloadBuilder) return messagePayloadToSendOptions(content);
962
- return { ...content };
995
+ function toMessageEmbedFooter(data) {
996
+ return {
997
+ text: data.text,
998
+ iconUrl: data.icon_url ?? null,
999
+ proxyIconUrl: data.proxy_icon_url ?? null
1000
+ };
963
1001
  }
964
- async function createMessageBody(content, referenced_message, ping) {
965
- if (typeof content === "string" && content.length === 0) {
966
- throw new FluxerError("Cannot send an empty message", { code: ErrorCodes.EmptyMessage });
967
- }
968
- const opts = toSendOptions(content);
969
- if (referenced_message) {
970
- opts.replyTo = toReplyTarget(referenced_message);
971
- if (ping !== void 0) opts.ping = ping;
972
- }
973
- return prepareMessagePostPayload(opts);
1002
+ function toMessageEmbedMedia(data) {
1003
+ return {
1004
+ url: data.url,
1005
+ proxyUrl: data.proxy_url ?? null,
1006
+ contentType: data.content_type ?? null,
1007
+ contentHash: data.content_hash ?? null,
1008
+ width: data.width ?? null,
1009
+ height: data.height ?? null,
1010
+ description: data.description ?? null,
1011
+ placeholder: data.placeholder ?? null,
1012
+ duration: data.duration ?? null,
1013
+ flags: data.flags ?? null
1014
+ };
974
1015
  }
975
- function asReplyTarget(value) {
976
- if ("messageId" in value) return value;
1016
+ function toMessageEmbed(data) {
1017
+ const full = data;
977
1018
  return {
978
- channelId: value.channelId,
979
- messageId: value.id,
980
- guildId: value.guildId
1019
+ type: data.type ?? "rich",
1020
+ url: data.url ?? null,
1021
+ title: data.title ?? null,
1022
+ color: data.color ?? null,
1023
+ timestamp: data.timestamp ? new Date(data.timestamp) : null,
1024
+ description: data.description ?? null,
1025
+ author: data.author ? toMessageEmbedAuthor(data.author) : null,
1026
+ image: data.image ? toMessageEmbedMedia(data.image) : null,
1027
+ thumbnail: data.thumbnail ? toMessageEmbedMedia(data.thumbnail) : null,
1028
+ footer: data.footer ? toMessageEmbedFooter(data.footer) : null,
1029
+ fields: (data.fields ?? []).map((f) => ({
1030
+ name: f.name,
1031
+ value: f.value,
1032
+ inline: f.inline ?? false
1033
+ })),
1034
+ provider: data.provider ? toMessageEmbedAuthor(data.provider) : null,
1035
+ video: data.video ? toMessageEmbedMedia(data.video) : null,
1036
+ audio: data.audio ? toMessageEmbedMedia(data.audio) : null,
1037
+ nsfw: data.nsfw ?? false,
1038
+ children: (full.children ?? []).map(toMessageEmbed),
1039
+ html: full.html ?? null,
1040
+ htmlWidth: full.html_width ?? null,
1041
+ htmlHeight: full.html_height ?? null
981
1042
  };
982
1043
  }
983
- async function sendPrepared(message, payload) {
984
- const data = await message.client.rest.post(
985
- Routes3.channelMessages(message.channelId),
1044
+
1045
+ // src/Domain/Message/MessageReactionManager.ts
1046
+ import { Collection as Collection2 } from "@fluxerjs/collection";
1047
+ var MessageReactionManager = class {
1048
+ constructor(message) {
1049
+ this.message = message;
1050
+ }
1051
+ _cache = new Collection2();
1052
+ /** Reactions keyed by unicode name or `name:id`. */
1053
+ get cache() {
1054
+ return this._cache;
1055
+ }
1056
+ get size() {
1057
+ return this._cache.size;
1058
+ }
1059
+ [Symbol.iterator]() {
1060
+ return this._cache.values();
1061
+ }
1062
+ /** @internal Sync from an API message payload. */
1063
+ _patch(reactions) {
1064
+ this._cache.clear();
1065
+ for (const data of reactions ?? []) {
1066
+ const reaction = MessageReaction.fromMessage(this.message, data);
1067
+ this._cache.set(reaction.emojiIdentifier, reaction);
1068
+ }
1069
+ }
1070
+ };
1071
+
1072
+ // src/Domain/Message/MessageSticker.ts
1073
+ import { SnowflakeUtil } from "@fluxerjs/util";
1074
+
1075
+ // src/Helpers/Constants.ts
1076
+ import { DEFAULT_USER_AGENT } from "@fluxerjs/rest";
1077
+ var CDN_URL = "https://fluxerusercontent.com";
1078
+ var STATIC_CDN_URL = "https://fluxerstatic.com";
1079
+
1080
+ // src/Helpers/Cdn.ts
1081
+ var CDN_SIZE_LADDER = [
1082
+ 16,
1083
+ 20,
1084
+ 22,
1085
+ 24,
1086
+ 28,
1087
+ 32,
1088
+ 40,
1089
+ 44,
1090
+ 48,
1091
+ 56,
1092
+ 60,
1093
+ 64,
1094
+ 80,
1095
+ 96,
1096
+ 100,
1097
+ 128,
1098
+ 160,
1099
+ 240,
1100
+ 256,
1101
+ 300,
1102
+ 320,
1103
+ 480,
1104
+ 512,
1105
+ 600,
1106
+ 640,
1107
+ 1024,
1108
+ 1280,
1109
+ 1536,
1110
+ 2048,
1111
+ 3072,
1112
+ 4096,
1113
+ 8192,
1114
+ 16384
1115
+ ];
1116
+ var CDN_ASSET_CLASS_RANGE = {
1117
+ icon: { min: 128, max: 1024 },
1118
+ banner: { min: 480, max: 2400 },
1119
+ emoji: { min: 32, max: 512 },
1120
+ sticker: { min: 128, max: 512 }
1121
+ };
1122
+ function nearestSize(requested, candidates) {
1123
+ let best = candidates[0];
1124
+ let bestDist = Math.abs(requested - best);
1125
+ for (let i = 1; i < candidates.length; i++) {
1126
+ const step = candidates[i];
1127
+ const dist = Math.abs(requested - step);
1128
+ if (dist < bestDist || dist === bestDist && step > best) {
1129
+ best = step;
1130
+ bestDist = dist;
1131
+ }
1132
+ }
1133
+ return best;
1134
+ }
1135
+ function snapCdnSize(requested, assetClass) {
1136
+ const { min, max } = CDN_ASSET_CLASS_RANGE[assetClass];
1137
+ const snapped = nearestSize(requested, CDN_SIZE_LADDER);
1138
+ const clamped = Math.min(max, Math.max(min, snapped));
1139
+ const allowed = CDN_SIZE_LADDER.filter((step) => step >= min && step <= max);
1140
+ return nearestSize(clamped, allowed);
1141
+ }
1142
+ function mediaBase(options) {
1143
+ return (options?.mediaBase ?? CDN_URL).replace(/\/+$/, "");
1144
+ }
1145
+ function staticBase(options) {
1146
+ return (options?.staticCdnBase ?? STATIC_CDN_URL).replace(/\/+$/, "");
1147
+ }
1148
+ function getExtension(hash, options) {
1149
+ const ext = options?.extension ?? "png";
1150
+ if (hash?.startsWith("a_")) return "gif";
1151
+ return ext;
1152
+ }
1153
+ function appendSize(options, assetClass) {
1154
+ const size = options?.size;
1155
+ if (size == null || !Number.isFinite(size) || size <= 0) return "";
1156
+ return `?size=${snapCdnSize(size, assetClass)}`;
1157
+ }
1158
+ function cdnAvatarURL(userId, avatarHash, options) {
1159
+ if (!avatarHash) return null;
1160
+ const ext = getExtension(avatarHash, options);
1161
+ const size = appendSize(options, "icon");
1162
+ return `${mediaBase(options)}/avatars/${userId}/${avatarHash}.${ext}${size}`;
1163
+ }
1164
+ function cdnBannerURL(resourceId, bannerHash, options) {
1165
+ if (!bannerHash) return null;
1166
+ const ext = getExtension(bannerHash, options);
1167
+ const size = appendSize(options, "banner");
1168
+ return `${mediaBase(options)}/banners/${resourceId}/${bannerHash}.${ext}${size}`;
1169
+ }
1170
+ function cdnMemberAvatarURL(guildId, userId, avatarHash, options) {
1171
+ if (!avatarHash) return null;
1172
+ const ext = getExtension(avatarHash, options);
1173
+ const size = appendSize(options, "icon");
1174
+ return `${mediaBase(options)}/guilds/${guildId}/users/${userId}/avatars/${avatarHash}.${ext}${size}`;
1175
+ }
1176
+ function cdnMemberBannerURL(guildId, userId, bannerHash, options) {
1177
+ if (!bannerHash) return null;
1178
+ const ext = getExtension(bannerHash, options);
1179
+ const size = appendSize(options, "banner");
1180
+ return `${mediaBase(options)}/guilds/${guildId}/users/${userId}/banners/${bannerHash}.${ext}${size}`;
1181
+ }
1182
+ function cdnDefaultAvatarURL(userIdOrIndex, options) {
1183
+ const index = typeof userIdOrIndex === "string" ? Number(BigInt(userIdOrIndex) % 6n) : Math.abs(Math.floor(userIdOrIndex) % 6);
1184
+ return `${staticBase(options)}/avatars/${index}.png`;
1185
+ }
1186
+ function cdnGuildAssetURL(kind, id, hash, options) {
1187
+ if (!hash) return null;
1188
+ const assetClass = kind === "icons" ? "icon" : "banner";
1189
+ const size = appendSize(options, assetClass);
1190
+ return `${mediaBase(options)}/${kind}/${id}/${hash}.png${size}`;
1191
+ }
1192
+ function cdnEmojiURL(emojiId, animated, options) {
1193
+ const ext = animated ? "gif" : "png";
1194
+ const size = appendSize(options, "emoji");
1195
+ return `${mediaBase(options)}/emojis/${emojiId}.${ext}${size}`;
1196
+ }
1197
+ function cdnStickerURL(stickerId, animated, options) {
1198
+ const ext = animated ? "gif" : "png";
1199
+ const size = appendSize(options, "sticker");
1200
+ return `${mediaBase(options)}/stickers/${stickerId}.${ext}${size}`;
1201
+ }
1202
+
1203
+ // src/Domain/Message/MessageSticker.ts
1204
+ var MessageSticker = class extends Base {
1205
+ client;
1206
+ id;
1207
+ name;
1208
+ description;
1209
+ tags;
1210
+ animated;
1211
+ constructor(client, data) {
1212
+ super();
1213
+ this.client = client;
1214
+ this.id = data.id;
1215
+ this.name = data.name;
1216
+ this.description = data.description ?? "";
1217
+ this.tags = data.tags ?? [];
1218
+ this.animated = data.animated ?? false;
1219
+ }
1220
+ /** CDN URL for this sticker image. */
1221
+ get url() {
1222
+ return cdnStickerURL(this.id, this.animated, {
1223
+ mediaBase: this.client.instance.endpoints.media
1224
+ });
1225
+ }
1226
+ /** Unix timestamp (ms) when this sticker was created, derived from its snowflake ID. */
1227
+ get createdTimestamp() {
1228
+ return SnowflakeUtil.timestampFromSnowflake(this.id);
1229
+ }
1230
+ /** Date when this sticker was created, derived from its snowflake ID. */
1231
+ get createdAt() {
1232
+ return SnowflakeUtil.dateFromSnowflake(this.id);
1233
+ }
1234
+ };
1235
+
1236
+ // src/Domain/Message/Reactions.ts
1237
+ import { Routes as Routes2 } from "@fluxerjs/types";
1238
+ async function emojiPath(message, emoji) {
1239
+ return message.client.resolveEmoji(emoji, message.guildId);
1240
+ }
1241
+ async function reactToMessage(message, emoji) {
1242
+ const wire = await emojiPath(message, emoji);
1243
+ await message.client.rest.put(
1244
+ Routes2.channelMessageReactionMe(message.channelId, message.id, wire)
1245
+ );
1246
+ }
1247
+ async function removeMessageReaction(message, emoji, userId) {
1248
+ const e = await emojiPath(message, emoji);
1249
+ const route = userId ? Routes2.channelMessageReactionUser(message.channelId, message.id, e, userId) : Routes2.channelMessageReactionMe(message.channelId, message.id, e);
1250
+ await message.client.rest.delete(route);
1251
+ }
1252
+ async function removeAllMessageReactions(message) {
1253
+ await message.client.rest.delete(Routes2.channelMessageReactions(message.channelId, message.id));
1254
+ }
1255
+ async function removeMessageReactionEmoji(message, emoji) {
1256
+ const e = await emojiPath(message, emoji);
1257
+ await message.client.rest.delete(Routes2.channelMessageReaction(message.channelId, message.id, e));
1258
+ }
1259
+ async function fetchMessageReactionUsers(message, emoji, options) {
1260
+ return (await fetchMessageReactionUsersPage(message, emoji, options)).users;
1261
+ }
1262
+ async function fetchMessageReactionUsersPage(message, emoji, options) {
1263
+ const e = await emojiPath(message, emoji);
1264
+ const params = new URLSearchParams();
1265
+ if (options?.limit != null) params.set("limit", String(options.limit));
1266
+ if (options?.after) params.set("after", options.after);
1267
+ const qs2 = params.toString();
1268
+ const route = Routes2.channelMessageReactionUsers(message.channelId, message.id, e) + (qs2 ? `?${qs2}` : "");
1269
+ const data = await message.client.rest.get(route);
1270
+ if (Array.isArray(data)) {
1271
+ return {
1272
+ users: data.map((u) => message.client.getOrCreateUser(u)),
1273
+ hasMore: false,
1274
+ nextAfter: null
1275
+ };
1276
+ }
1277
+ const list = data.items ?? data.users ?? [];
1278
+ return {
1279
+ users: list.map((u) => message.client.getOrCreateUser(u)),
1280
+ hasMore: data.has_more ?? false,
1281
+ nextAfter: data.next_after ?? null
1282
+ };
1283
+ }
1284
+
1285
+ // src/Domain/Message/Send.ts
1286
+ import { MessagePayload as MessagePayloadBuilder } from "@fluxerjs/builders";
1287
+ import { Routes as Routes3 } from "@fluxerjs/types";
1288
+ function toReplyTarget(ref) {
1289
+ return {
1290
+ channelId: ref.channel_id,
1291
+ messageId: ref.message_id,
1292
+ ...ref.guild_id != null ? { guildId: ref.guild_id } : {}
1293
+ };
1294
+ }
1295
+ function toSendOptions(content) {
1296
+ if (typeof content === "string") return { content };
1297
+ if (content instanceof MessagePayloadBuilder) return messagePayloadToSendOptions(content);
1298
+ return { ...content };
1299
+ }
1300
+ async function createMessageBody(content, referenced_message, ping) {
1301
+ if (typeof content === "string" && content.length === 0) {
1302
+ throw new FluxerError("Cannot send an empty message", { code: ErrorCodes.EmptyMessage });
1303
+ }
1304
+ const opts = toSendOptions(content);
1305
+ if (referenced_message) {
1306
+ opts.replyTo = toReplyTarget(referenced_message);
1307
+ if (ping !== void 0) opts.ping = ping;
1308
+ }
1309
+ return prepareMessagePostPayload(opts);
1310
+ }
1311
+ function asReplyTarget(value) {
1312
+ if ("messageId" in value) return value;
1313
+ return {
1314
+ channelId: value.channelId,
1315
+ messageId: value.id,
1316
+ guildId: value.guildId
1317
+ };
1318
+ }
1319
+ async function sendPrepared(message, payload) {
1320
+ const data = await message.client.rest.post(
1321
+ Routes3.channelMessages(message.channelId),
986
1322
  payload
987
1323
  );
988
1324
  message.client._addMessageToCache(message.channelId, data);
@@ -1012,7 +1348,33 @@ async function replyToMessage(message, options, replyOptions) {
1012
1348
  }
1013
1349
 
1014
1350
  // src/Domain/Message/Message.ts
1351
+ function toMessageCall(data) {
1352
+ return {
1353
+ participants: data.participants,
1354
+ endedAt: data.ended_timestamp ? new Date(data.ended_timestamp) : null
1355
+ };
1356
+ }
1357
+ function toMessageSnapshot(client, data) {
1358
+ return {
1359
+ content: data.content ?? null,
1360
+ createdAt: new Date(data.timestamp),
1361
+ editedAt: data.edited_timestamp ? new Date(data.edited_timestamp) : null,
1362
+ mentionUserIds: data.mentions ?? [],
1363
+ mentionRoles: data.mention_roles ?? [],
1364
+ embeds: (data.embeds ?? []).map(toMessageEmbed),
1365
+ attachments: (data.attachments ?? []).map(toMessageAttachment),
1366
+ stickers: (data.stickers ?? []).map((s) => new MessageSticker(client, s)),
1367
+ ...data.type !== void 0 ? { type: data.type } : {}
1368
+ };
1369
+ }
1370
+ function resolveMessageFlags(flags) {
1371
+ if (flags === void 0) return void 0;
1372
+ if (typeof flags === "number") return flags;
1373
+ return Number(MessageFlagsBitField.resolve(flags));
1374
+ }
1015
1375
  var Message = class _Message extends Base {
1376
+ /** Discriminant vs {@link PartialMessage}: always `false` on a hydrated Message. */
1377
+ partial = false;
1016
1378
  /** The {@link Client} that instantiated this message. */
1017
1379
  client;
1018
1380
  /** Snowflake ID of this message. */
@@ -1041,7 +1403,7 @@ var Message = class _Message extends Base {
1041
1403
  mentionEveryone;
1042
1404
  /** Whether this is a text-to-speech message. */
1043
1405
  tts;
1044
- /** Embedded content (rich previews, etc.). */
1406
+ /** Embedded content (camelCase read view; send with {@link EmbedBuilder}). */
1045
1407
  embeds;
1046
1408
  /** Stickers sent with the message. */
1047
1409
  stickers;
@@ -1063,26 +1425,43 @@ var Message = class _Message extends Base {
1063
1425
  mentionRoles;
1064
1426
  /** Client-side nonce for deduplication. */
1065
1427
  nonce;
1066
- /** Cached text/DM/guild channel, or null if uncached. */
1428
+ /** IDs of custom emojis in the message classified as explicit. */
1429
+ nsfwEmojis;
1430
+ /**
1431
+ * Cached text-capable channel (guild text, guild voice, or DM), or null if uncached / not text-based.
1432
+ * Narrowed type has {@link Channel.send} and {@link Channel.delete}.
1433
+ */
1067
1434
  get channel() {
1068
- return this.client.channels.get(this.channelId) ?? null;
1435
+ const channel = this.client.channels.get(this.channelId) ?? null;
1436
+ return channel?.isTextBased() ? channel : null;
1069
1437
  }
1070
1438
  /** Cached guild, or null for DMs / uncached. */
1071
1439
  get guild() {
1072
1440
  return this.guildId ? this.client.guilds.get(this.guildId) ?? null : null;
1073
1441
  }
1074
- /** Fetch and resolve the channel this message is in. */
1442
+ /** Cached guild member for the author, or null in DMs / if uncached. */
1443
+ get member() {
1444
+ return this.guild?.members.get(this.author.id) ?? null;
1445
+ }
1446
+ /**
1447
+ * Fetch this message's channel (cache first). The returned {@link Channel}
1448
+ * has {@link Channel.delete} and {@link Channel.send}.
1449
+ * @example
1450
+ * const channel = await message.resolveChannel();
1451
+ * await channel.delete();
1452
+ */
1075
1453
  async resolveChannel() {
1076
1454
  return this.client.channels.resolve(this.channelId);
1077
1455
  }
1078
- /** Fetch and resolve the guild, or null if a DM. */
1456
+ /**
1457
+ * Fetch and resolve the guild, or null if a DM.
1458
+ * Propagates network/auth errors; only returns null when there is no guildId.
1459
+ * @example
1460
+ * const guild = await message.resolveGuild();
1461
+ */
1079
1462
  async resolveGuild() {
1080
1463
  if (!this.guildId) return null;
1081
- try {
1082
- return await this.client.guilds.resolve(this.guildId);
1083
- } catch {
1084
- return null;
1085
- }
1464
+ return this.client.guilds.resolve(this.guildId);
1086
1465
  }
1087
1466
  /**
1088
1467
  * Construct a message from API data.
@@ -1099,29 +1478,75 @@ var Message = class _Message extends Base {
1099
1478
  this.createdAt = new Date(data.timestamp);
1100
1479
  this.editedAt = data.edited_timestamp ? new Date(data.edited_timestamp) : null;
1101
1480
  this.pinned = data.pinned;
1102
- this.attachments = new Collection2();
1103
- for (const a of data.attachments ?? []) this.attachments.set(a.id, a);
1481
+ this.attachments = new Collection3();
1482
+ for (const a of data.attachments ?? []) this.attachments.set(a.id, toMessageAttachment(a));
1104
1483
  this.type = data.type ?? MessageType.Default;
1105
- this.flags = data.flags ?? 0;
1484
+ this.flags = new MessageFlagsBitField(BigInt(data.flags ?? 0));
1106
1485
  this.mentionEveryone = data.mention_everyone ?? false;
1107
1486
  this.tts = data.tts ?? false;
1108
- this.embeds = data.embeds ?? [];
1109
- this.stickers = data.stickers ?? [];
1110
- this.reactions = data.reactions ?? [];
1111
- this.messageReference = data.message_reference ?? null;
1112
- this.messageSnapshots = data.message_snapshots ?? [];
1113
- this.call = data.call ?? null;
1487
+ this.embeds = (data.embeds ?? []).map(toMessageEmbed);
1488
+ this.stickers = (data.stickers ?? []).map((s) => new MessageSticker(client, s));
1489
+ this.reactions = new MessageReactionManager(this);
1490
+ this.reactions._patch(data.reactions);
1491
+ this.messageReference = data.message_reference ? {
1492
+ channelId: data.message_reference.channel_id,
1493
+ messageId: data.message_reference.message_id,
1494
+ guildId: data.message_reference.guild_id ?? null,
1495
+ ...data.message_reference.type !== void 0 ? { type: data.message_reference.type } : {}
1496
+ } : null;
1497
+ this.messageSnapshots = (data.message_snapshots ?? []).map((s) => toMessageSnapshot(client, s));
1498
+ this.call = data.call ? toMessageCall(data.call) : null;
1114
1499
  this.referencedMessage = data.referenced_message ? new _Message(client, data.referenced_message) : null;
1115
1500
  this.webhookId = data.webhook_id ?? null;
1116
1501
  this.mentions = (data.mentions ?? []).map((u) => client.getOrCreateUser(u));
1117
1502
  this.mentionRoles = data.mention_roles ?? [];
1118
1503
  this.nonce = data.nonce ?? null;
1504
+ this.nsfwEmojis = data.nsfw_emojis ?? [];
1119
1505
  }
1120
- /** Send a message in this channel without replying. */
1506
+ /**
1507
+ * Apply an API message payload in place (cache identity / MESSAGE_UPDATE).
1508
+ * @internal
1509
+ */
1510
+ _patch(data) {
1511
+ this.content = data.content;
1512
+ this.editedAt = data.edited_timestamp ? new Date(data.edited_timestamp) : null;
1513
+ this.pinned = data.pinned;
1514
+ this.attachments.clear();
1515
+ for (const a of data.attachments ?? []) this.attachments.set(a.id, toMessageAttachment(a));
1516
+ this.flags = new MessageFlagsBitField(BigInt(data.flags ?? 0));
1517
+ this.mentionEveryone = data.mention_everyone ?? false;
1518
+ this.tts = data.tts ?? false;
1519
+ this.embeds = (data.embeds ?? []).map(toMessageEmbed);
1520
+ this.stickers = (data.stickers ?? []).map((s) => new MessageSticker(this.client, s));
1521
+ this.reactions._patch(data.reactions);
1522
+ this.messageReference = data.message_reference ? {
1523
+ channelId: data.message_reference.channel_id,
1524
+ messageId: data.message_reference.message_id,
1525
+ guildId: data.message_reference.guild_id ?? null,
1526
+ ...data.message_reference.type !== void 0 ? { type: data.message_reference.type } : {}
1527
+ } : null;
1528
+ this.messageSnapshots = (data.message_snapshots ?? []).map(
1529
+ (s) => toMessageSnapshot(this.client, s)
1530
+ );
1531
+ this.call = data.call ? toMessageCall(data.call) : null;
1532
+ this.referencedMessage = data.referenced_message ? new _Message(this.client, data.referenced_message) : null;
1533
+ this.webhookId = data.webhook_id ?? null;
1534
+ this.mentions = (data.mentions ?? []).map((u) => this.client.getOrCreateUser(u));
1535
+ this.mentionRoles = data.mention_roles ?? [];
1536
+ this.nonce = data.nonce ?? null;
1537
+ this.nsfwEmojis = data.nsfw_emojis ?? [];
1538
+ }
1539
+ /**
1540
+ * Send a standalone message in this channel (not a reply).
1541
+ * Prefer {@link Channel.send} or {@link reply} when you already have the channel or are answering.
1542
+ */
1121
1543
  async send(options) {
1122
1544
  return sendMessage(this, options);
1123
1545
  }
1124
- /** Send a message to another channel by ID. */
1546
+ /**
1547
+ * Send a message to another channel by ID.
1548
+ * Prefer `client.channels.fetch(channelId)` then {@link Channel.send}.
1549
+ */
1125
1550
  async sendTo(channelId, options) {
1126
1551
  return sendMessageTo(this, channelId, options);
1127
1552
  }
@@ -1135,6 +1560,16 @@ var Message = class _Message extends Base {
1135
1560
  async reply(options, replyOptions) {
1136
1561
  return replyToMessage(this, options, replyOptions);
1137
1562
  }
1563
+ /**
1564
+ * Hydrate a partial message, or return the message as-is.
1565
+ * @example
1566
+ * client.on(Events.MessageUpdate, async (_old, msg) => {
1567
+ * const message = await Message.resolve(msg);
1568
+ * });
1569
+ */
1570
+ static async resolve(message) {
1571
+ return message.partial ? message.fetch() : message;
1572
+ }
1138
1573
  /** Test helper — prefer {@link reply} / `prepareMessagePostPayload()`. */
1139
1574
  static async _createMessageBody(content, referenced_message, ping) {
1140
1575
  return createMessageBody(content, referenced_message, ping);
@@ -1147,7 +1582,7 @@ var Message = class _Message extends Base {
1147
1582
  async edit(options) {
1148
1583
  const body = {};
1149
1584
  if (options.content !== void 0) body.content = options.content;
1150
- if (options.embeds?.length) {
1585
+ if (options.embeds !== void 0) {
1151
1586
  body.embeds = options.embeds.map(
1152
1587
  (e) => e instanceof EmbedBuilder2 ? e.toJSON() : e
1153
1588
  );
@@ -1155,7 +1590,8 @@ var Message = class _Message extends Base {
1155
1590
  if (options.allowedMentions) {
1156
1591
  body.allowed_mentions = toAPIAllowedMentions(options.allowedMentions);
1157
1592
  }
1158
- if (options.flags !== void 0) body.flags = options.flags;
1593
+ const flags = resolveMessageFlags(options.flags);
1594
+ if (flags !== void 0) body.flags = flags;
1159
1595
  if (options.attachments !== void 0) {
1160
1596
  body.attachments = toMessageAttachmentEditWire(options.attachments);
1161
1597
  }
@@ -1170,13 +1606,22 @@ var Message = class _Message extends Base {
1170
1606
  createReactionCollector(options) {
1171
1607
  return new ReactionCollector(this.client, this.id, this.channelId, options);
1172
1608
  }
1609
+ /**
1610
+ * Wait for reactions matching the filter, then resolve the collected set.
1611
+ * Pass `errors: ['time']` to reject when the timer fires instead of resolving.
1612
+ */
1613
+ awaitReactions(options) {
1614
+ return ReactionCollector.awaitReactions(this.client, this.id, this.channelId, options);
1615
+ }
1173
1616
  /** Fetch the latest version of this message from the API. */
1174
1617
  async fetch() {
1175
1618
  return this.client.channels.fetchMessage(this.channelId, this.id);
1176
1619
  }
1177
1620
  /** Delete this message. */
1178
- async delete() {
1179
- await this.client.rest.delete(Routes4.channelMessage(this.channelId, this.id));
1621
+ async delete(reason) {
1622
+ await this.client.rest.delete(Routes4.channelMessage(this.channelId, this.id), {
1623
+ ...auditReasonHeaders(reason)
1624
+ });
1180
1625
  this.client._removeMessageFromCache(this.channelId, this.id);
1181
1626
  }
1182
1627
  /** Delete a specific attachment from this message. */
@@ -1223,7 +1668,68 @@ var Message = class _Message extends Base {
1223
1668
  }
1224
1669
  };
1225
1670
 
1671
+ // src/Domain/Message/PartialMessage.ts
1672
+ import { SnowflakeUtil as SnowflakeUtil2 } from "@fluxerjs/util";
1673
+ var PartialMessage = class {
1674
+ partial = true;
1675
+ client;
1676
+ id;
1677
+ channelId;
1678
+ guildId;
1679
+ content;
1680
+ authorId;
1681
+ author;
1682
+ createdAt;
1683
+ constructor(client, data) {
1684
+ this.client = client;
1685
+ this.id = data.id;
1686
+ this.channelId = data.channelId;
1687
+ this.guildId = data.guildId ?? null;
1688
+ this.content = data.content ?? null;
1689
+ this.authorId = data.authorId ?? null;
1690
+ this.author = data.author ?? null;
1691
+ this.createdAt = data.createdAt ?? (SnowflakeUtil2.isValid(data.id) ? SnowflakeUtil2.dateFromSnowflake(data.id) : null);
1692
+ }
1693
+ /**
1694
+ * Live text-capable channel from cache, or null if uncached / not text-based.
1695
+ * Same contract as {@link Message.channel}.
1696
+ */
1697
+ get channel() {
1698
+ const channel = this.client.channels.get(this.channelId) ?? null;
1699
+ return channel?.isTextBased() ? channel : null;
1700
+ }
1701
+ /**
1702
+ * Fetch this message's channel (cache first). The returned {@link Channel}
1703
+ * has {@link Channel.delete} and {@link Channel.send}.
1704
+ * @example
1705
+ * const channel = await message.resolveChannel();
1706
+ * await channel.delete();
1707
+ */
1708
+ async resolveChannel() {
1709
+ return this.client.channels.resolve(this.channelId);
1710
+ }
1711
+ /**
1712
+ * Fetch the full message from the API.
1713
+ * @example
1714
+ * const message = await partial.fetch();
1715
+ * await message.reply('Pong!');
1716
+ */
1717
+ async fetch() {
1718
+ return this.client.channels.fetchMessage(this.channelId, this.id);
1719
+ }
1720
+ };
1721
+
1722
+ // src/Domain/User.ts
1723
+ import { Routes as Routes14 } from "@fluxerjs/types";
1724
+ import { SnowflakeUtil as SnowflakeUtil5 } from "@fluxerjs/util";
1725
+
1726
+ // src/Domain/Channel/Base.ts
1727
+ import { ChannelType, Routes as Routes7 } from "@fluxerjs/types";
1728
+ import { SnowflakeUtil as SnowflakeUtil3 } from "@fluxerjs/util";
1729
+
1226
1730
  // src/ClientCore/MessageManager.ts
1731
+ import { Collection as Collection4 } from "@fluxerjs/collection";
1732
+ import { Routes as Routes5 } from "@fluxerjs/types";
1227
1733
  var BULK = {
1228
1734
  requests: { min: 1, max: 25 },
1229
1735
  limit: { min: 1, max: 25 },
@@ -1257,19 +1763,40 @@ var MessageManager = class {
1257
1763
  this.client = client;
1258
1764
  this.channelId = channelId;
1259
1765
  }
1766
+ /** Structure cache keyed by message id (identity for {@link get}). */
1767
+ _structures = new Collection4();
1260
1768
  /** Retrieve a cached message by ID, or `undefined` if missing / caching disabled. */
1261
1769
  get(messageId) {
1262
1770
  const data = this.client._getMessageCache(this.channelId)?.get(messageId);
1263
- return data ? new Message(this.client, data) : void 0;
1771
+ if (!data) {
1772
+ this._structures.delete(messageId);
1773
+ return void 0;
1774
+ }
1775
+ const existing = this._structures.get(messageId);
1776
+ if (existing) return existing;
1777
+ const message = new Message(this.client, data);
1778
+ this._structures.set(messageId, message);
1779
+ return message;
1780
+ }
1781
+ /** Retrieve from cache, otherwise {@link fetch}. */
1782
+ async resolve(messageId) {
1783
+ return this.get(messageId) ?? this.fetch(messageId);
1264
1784
  }
1265
1785
  async fetch(idOrOptions) {
1266
1786
  return typeof idOrOptions === "string" ? this.fetchOne(idOrOptions) : this.fetchMany(idOrOptions);
1267
1787
  }
1268
- /** Cache API data and return a {@link Message} built from the cached entry when present. */
1788
+ /** Cache API data and return a {@link Message} (reusing identity when present). */
1269
1789
  wrap(data) {
1270
1790
  this.client._addMessageToCache(this.channelId, data);
1271
1791
  const cached = this.client._getMessageCache(this.channelId)?.get(data.id) ?? data;
1272
- return new Message(this.client, cached);
1792
+ const existing = this._structures.get(data.id);
1793
+ if (existing) {
1794
+ existing._patch(cached);
1795
+ return existing;
1796
+ }
1797
+ const message = new Message(this.client, cached);
1798
+ this._structures.set(data.id, message);
1799
+ return message;
1273
1800
  }
1274
1801
  /** Fetch a single message from the API. */
1275
1802
  async fetchOne(messageId) {
@@ -1302,14 +1829,135 @@ var MessageManager = class {
1302
1829
  }
1303
1830
  const base = Routes5.channelMessages(this.channelId);
1304
1831
  const data = await this.client.rest.get(qs2.size > 0 ? `${base}?${qs2}` : base);
1305
- const collection = new Collection3();
1832
+ const collection = new Collection4();
1306
1833
  for (const msg of data) collection.set(msg.id, this.wrap(msg));
1307
1834
  return collection;
1308
1835
  }
1309
1836
  };
1310
1837
 
1838
+ // src/Helpers/MessageCollector.ts
1839
+ import { EventEmitter as EventEmitter2 } from "events";
1840
+ import { Collection as Collection5 } from "@fluxerjs/collection";
1841
+ function requireCollectorBounds(options) {
1842
+ const time = options.time ?? 0;
1843
+ const max = options.max ?? 0;
1844
+ if (time <= 0 && max <= 0) {
1845
+ throw new FluxerError("MessageCollector requires `time` and/or `max`", {
1846
+ code: ErrorCodes.CollectorOptionsRequired
1847
+ });
1848
+ }
1849
+ }
1850
+ var MessageCollector = class _MessageCollector extends EventEmitter2 {
1851
+ client;
1852
+ channelId;
1853
+ options;
1854
+ collected = new Collection5();
1855
+ _timeout = null;
1856
+ _ended = false;
1857
+ _listener;
1858
+ constructor(client, channelId, options = {}) {
1859
+ super();
1860
+ requireCollectorBounds(options);
1861
+ this.client = client;
1862
+ this.channelId = channelId;
1863
+ this.options = {
1864
+ filter: options.filter ?? (() => true),
1865
+ time: options.time ?? 0,
1866
+ max: options.max ?? 0
1867
+ };
1868
+ this._listener = (message) => {
1869
+ if (this._ended || message.channelId !== this.channelId) return;
1870
+ if (!this.options.filter(message)) return;
1871
+ this.collected.set(message.id, message);
1872
+ this.emit("collect", message);
1873
+ if (this.options.max > 0 && this.collected.size >= this.options.max) {
1874
+ this.stop("limit");
1875
+ }
1876
+ };
1877
+ this.client.on(Events.MessageCreate, this._listener);
1878
+ if (this.options.time > 0) {
1879
+ this._timeout = setTimeout(() => this.stop("time"), this.options.time);
1880
+ }
1881
+ }
1882
+ stop(reason = "user") {
1883
+ if (this._ended) return;
1884
+ this._ended = true;
1885
+ this.client.off(Events.MessageCreate, this._listener);
1886
+ if (this._timeout) {
1887
+ clearTimeout(this._timeout);
1888
+ this._timeout = null;
1889
+ }
1890
+ this.emit("end", this.collected, reason);
1891
+ }
1892
+ /**
1893
+ * One-shot helper used by {@link Channel.awaitMessages}.
1894
+ * Resolves with the collected messages when the collector ends for `user` (or when
1895
+ * the end reason is not listed in `errors`).
1896
+ * By default, `time` and `limit` reject with {@link FluxerError}
1897
+ * (`CollectorIdle` / `CollectorMax`).
1898
+ */
1899
+ static awaitMessages(client, channelId, options) {
1900
+ const errors = options?.errors ?? ["time", "limit"];
1901
+ return new Promise((resolve, reject) => {
1902
+ const collector = new _MessageCollector(client, channelId, options);
1903
+ collector.on("end", (collected, reason) => {
1904
+ if (!errors.includes(reason)) {
1905
+ resolve(collected);
1906
+ return;
1907
+ }
1908
+ if (reason === "time") {
1909
+ reject(
1910
+ new FluxerError("Message collector timed out", {
1911
+ code: ErrorCodes.CollectorIdle
1912
+ })
1913
+ );
1914
+ return;
1915
+ }
1916
+ if (reason === "limit") {
1917
+ reject(
1918
+ new FluxerError("Message collector reached max", {
1919
+ code: ErrorCodes.CollectorMax
1920
+ })
1921
+ );
1922
+ return;
1923
+ }
1924
+ reject(collected);
1925
+ });
1926
+ });
1927
+ }
1928
+ on(event, listener) {
1929
+ return super.on(event, listener);
1930
+ }
1931
+ emit(event, ...args) {
1932
+ return super.emit(event, ...args);
1933
+ }
1934
+ };
1935
+
1311
1936
  // src/Domain/Channel/Attachments.ts
1312
1937
  import { Routes as Routes6 } from "@fluxerjs/types";
1938
+ var BOT_ATTACHMENT_MAX_BYTES = 50 * 1024 * 1024;
1939
+ var ATTACHMENT_MULTIPART_THRESHOLD_BYTES = 10 * 1024 * 1024;
1940
+ function instanceLimitOverridesSnapshot(client) {
1941
+ const rules = client.instance.discovery?.limits?.rules;
1942
+ if (!rules?.length) return null;
1943
+ const snapshot = {};
1944
+ for (const rule of rules) {
1945
+ Object.assign(snapshot, rule.overrides);
1946
+ }
1947
+ return Object.keys(snapshot).length ? snapshot : null;
1948
+ }
1949
+ function assertBotAttachmentLimits(client, files) {
1950
+ const snapshot = instanceLimitOverridesSnapshot(client);
1951
+ for (const file of files) {
1952
+ const size = file.data.byteLength;
1953
+ if (size <= BOT_ATTACHMENT_MAX_BYTES) continue;
1954
+ const snapshotNote = snapshot ? ` Instance limit overrides: ${JSON.stringify(snapshot)}.` : "";
1955
+ throw new FluxerError(
1956
+ `Bot attachments are limited to 50 MiB (${BOT_ATTACHMENT_MAX_BYTES} bytes); "${file.filename}" is ${size} bytes.${snapshotNote}`,
1957
+ { code: ErrorCodes.AttachmentTooLarge }
1958
+ );
1959
+ }
1960
+ }
1313
1961
  function asBytes(data) {
1314
1962
  const src = data instanceof ArrayBuffer ? new Uint8Array(data) : new Uint8Array(data);
1315
1963
  const out = new Uint8Array(src.byteLength);
@@ -1329,6 +1977,7 @@ async function putBlob(url, body, contentType) {
1329
1977
  }
1330
1978
  }
1331
1979
  async function uploadAttachmentsForSend(client, channelId, files) {
1980
+ assertBotAttachmentLimits(client, files);
1332
1981
  const plan = await client.rest.post(
1333
1982
  Routes6.channelAttachments(channelId),
1334
1983
  {
@@ -1386,6 +2035,7 @@ async function uploadAttachmentsForSend(client, channelId, files) {
1386
2035
 
1387
2036
  // src/Domain/Channel/Base.ts
1388
2037
  var Channel = class extends Base {
2038
+ #messages;
1389
2039
  /** The {@link Client} that instantiated this channel. */
1390
2040
  client;
1391
2041
  /** Snowflake ID of this channel. */
@@ -1409,11 +2059,11 @@ var Channel = class extends Base {
1409
2059
  }
1410
2060
  /** Unix timestamp (ms) when this channel was created, derived from its snowflake ID. */
1411
2061
  get createdTimestamp() {
1412
- return SnowflakeUtil.timestampFromSnowflake(this.id);
2062
+ return SnowflakeUtil3.timestampFromSnowflake(this.id);
1413
2063
  }
1414
2064
  /** Date when this channel was created, derived from its snowflake ID. */
1415
2065
  get createdAt() {
1416
- return SnowflakeUtil.dateFromSnowflake(this.id);
2066
+ return SnowflakeUtil3.dateFromSnowflake(this.id);
1417
2067
  }
1418
2068
  /**
1419
2069
  * Apply shared channel fields in place (gateway CHANNEL_UPDATE when type is unchanged).
@@ -1427,19 +2077,36 @@ var Channel = class extends Base {
1427
2077
  this.lastPinTimestamp = data.last_pin_timestamp ?? null;
1428
2078
  }
1429
2079
  }
1430
- /** Wired in `structures/channel/index.ts` after subclasses load. */
2080
+ /** @internal Factory wired after subclasses load. */
1431
2081
  static from(_c, _d) {
1432
2082
  throw new Error("Channel.from not initialized");
1433
2083
  }
2084
+ /** @internal Factory wired after subclasses load. */
1434
2085
  static fromOrCreate(_c, _d) {
1435
2086
  throw new Error("Channel.fromOrCreate not initialized");
1436
2087
  }
2088
+ /** @internal Factory wired after subclasses load. */
1437
2089
  static createDM(_c, _d) {
1438
2090
  throw new Error("Channel.createDM not initialized");
1439
2091
  }
1440
- /** Check if this channel supports sending messages (text/DM). */
2092
+ /**
2093
+ * Whether this channel type can carry messages (text, voice, DM, group DM, notes).
2094
+ * Checks {@link ChannelType}, not whether `send` exists on the instance.
2095
+ */
1441
2096
  isTextBased() {
1442
- return "send" in this;
2097
+ return this.type === ChannelType.GuildText || this.type === ChannelType.GuildVoice || this.type === ChannelType.DM || this.type === ChannelType.GroupDM || this.type === ChannelType.DMPersonalNotes;
2098
+ }
2099
+ /** Check if this is a guild channel (text, voice, category, or link). */
2100
+ isGuild() {
2101
+ return this.type === ChannelType.GuildText || this.type === ChannelType.GuildVoice || this.type === ChannelType.GuildCategory || this.type === ChannelType.GuildLink;
2102
+ }
2103
+ /** Check if this is a guild text channel. */
2104
+ isText() {
2105
+ return this.type === ChannelType.GuildText;
2106
+ }
2107
+ /** Check if this is a category channel. */
2108
+ isCategory() {
2109
+ return this.type === ChannelType.GuildCategory;
1443
2110
  }
1444
2111
  /** Check if this is a DM, group DM, or personal notes channel. */
1445
2112
  isDM() {
@@ -1451,11 +2118,11 @@ var Channel = class extends Base {
1451
2118
  }
1452
2119
  /** Check if this is a voice channel. */
1453
2120
  isVoice() {
1454
- return "bitrate" in this;
2121
+ return this.type === ChannelType.GuildVoice;
1455
2122
  }
1456
2123
  /** Check if this is a link channel. */
1457
2124
  isLink() {
1458
- return "url" in this;
2125
+ return this.type === ChannelType.GuildLink;
1459
2126
  }
1460
2127
  /**
1461
2128
  * Delete recent messages or an explicit ID list.
@@ -1494,7 +2161,7 @@ var Channel = class extends Base {
1494
2161
  for (const id of ids) this.client._removeMessageFromCache(this.id, id);
1495
2162
  return ids;
1496
2163
  }
1497
- /** Delete all messages sent by the bot in this channel (user account feature). */
2164
+ /** Delete all messages sent by the bot in this channel. Sudo auto-passes for bots. */
1498
2165
  async bulkDeleteMyMessages(options) {
1499
2166
  const body = options ? toSudoBody(options) : void 0;
1500
2167
  await this.client.rest.post(Routes7.channelBulkDeleteMine(this.id), {
@@ -1502,11 +2169,17 @@ var Channel = class extends Base {
1502
2169
  auth: true
1503
2170
  });
1504
2171
  }
1505
- /** Mark all pinned messages as read in this channel. */
2172
+ /**
2173
+ * Mark all pinned messages as read in this channel.
2174
+ * Session-token helper; bots usually skip this.
2175
+ */
1506
2176
  async acknowledgePins() {
1507
2177
  await this.client.rest.post(Routes7.channelPinsAck(this.id), { auth: true });
1508
2178
  }
1509
- /** Clear the read state for this channel. */
2179
+ /**
2180
+ * Clear the read state for this channel.
2181
+ * Session-token helper; bots usually skip this.
2182
+ */
1510
2183
  async clearReadState() {
1511
2184
  await this.client.rest.delete(Routes7.channelMessagesAck(this.id), { auth: true });
1512
2185
  }
@@ -1542,90 +2215,89 @@ var Channel = class extends Base {
1542
2215
  async sendTyping() {
1543
2216
  await this.client.rest.post(Routes7.channelTyping(this.id), { auth: true });
1544
2217
  }
1545
- /** Fetch available RTC regions for voice channels. */
2218
+ /**
2219
+ * Fetch available RTC regions for voice channels.
2220
+ * User-account only (`DefaultUserOnly`); bots receive `AccessDeniedError`.
2221
+ * Bots should skip this and join voice with `@fluxerjs/voice` instead.
2222
+ */
1546
2223
  async fetchRtcRegions() {
1547
2224
  const data = await this.client.rest.get(Routes7.channelRtcRegions(this.id), {
1548
2225
  auth: true
1549
2226
  });
1550
- return data.map((r) => ({ id: r.id, name: r.name, emoji: r.emoji }));
1551
- }
1552
- /** Fetch slowmode state for this channel. */
1553
- async fetchSlowmode() {
1554
- const data = await this.client.rest.get(
1555
- Routes7.channelSlowmode(this.id),
1556
- { auth: true }
1557
- );
1558
- return {
1559
- rateLimitPerUser: data.rate_limit_per_user,
1560
- retryAfterMs: data.retry_after_ms,
1561
- nextSendAllowedAt: data.next_send_allowed_at
1562
- };
1563
- }
1564
- /** Check if the bot can send messages in this channel. */
1565
- canSendMessage() {
1566
- return this.isDM();
1567
- }
1568
- };
1569
-
1570
- // src/Domain/Channel/Dm.ts
1571
- import { ChannelType as ChannelType2, Routes as Routes9 } from "@fluxerjs/types";
1572
-
1573
- // src/Domain/Channel/TextCapable.ts
1574
- import { Routes as Routes8 } from "@fluxerjs/types";
1575
-
1576
- // src/Helpers/MessageCollector.ts
1577
- import { EventEmitter as EventEmitter2 } from "events";
1578
- import { Collection as Collection4 } from "@fluxerjs/collection";
1579
- var MessageCollector = class extends EventEmitter2 {
1580
- client;
1581
- channelId;
1582
- options;
1583
- collected = new Collection4();
1584
- _timeout = null;
1585
- _ended = false;
1586
- _listener;
1587
- constructor(client, channelId, options = {}) {
1588
- super();
1589
- this.client = client;
1590
- this.channelId = channelId;
1591
- this.options = {
1592
- filter: options.filter ?? (() => true),
1593
- time: options.time ?? 0,
1594
- max: options.max ?? 0
1595
- };
1596
- this._listener = (message) => {
1597
- if (this._ended || message.channelId !== this.channelId) return;
1598
- if (!this.options.filter(message)) return;
1599
- this.collected.set(message.id, message);
1600
- this.emit("collect", message);
1601
- if (this.options.max > 0 && this.collected.size >= this.options.max) {
1602
- this.stop("limit");
1603
- }
2227
+ return data.map((r) => ({ id: r.id, name: r.name, emoji: r.emoji }));
2228
+ }
2229
+ /** Fetch slowmode state for this channel. */
2230
+ async fetchSlowmode() {
2231
+ const data = await this.client.rest.get(
2232
+ Routes7.channelSlowmode(this.id),
2233
+ { auth: true }
2234
+ );
2235
+ return {
2236
+ rateLimitPerUser: data.rate_limit_per_user,
2237
+ retryAfterMs: data.retry_after_ms,
2238
+ nextSendAllowedAt: data.next_send_allowed_at
1604
2239
  };
1605
- this.client.on(Events.MessageCreate, this._listener);
1606
- if (this.options.time > 0) {
1607
- this._timeout = setTimeout(() => this.stop("time"), this.options.time);
1608
- }
1609
2240
  }
1610
- stop(reason = "user") {
1611
- if (this._ended) return;
1612
- this._ended = true;
1613
- this.client.off(Events.MessageCreate, this._listener);
1614
- if (this._timeout) {
1615
- clearTimeout(this._timeout);
1616
- this._timeout = null;
2241
+ /** Whether this channel type can carry messages (does not check permissions). */
2242
+ canSendMessage() {
2243
+ return this.isTextBased();
2244
+ }
2245
+ /** Per-channel message cache + fetch. */
2246
+ get messages() {
2247
+ if (!this.#messages) {
2248
+ this.#messages = new MessageManager(this.client, this.id);
1617
2249
  }
1618
- this.emit("end", this.collected, reason);
2250
+ return this.#messages;
1619
2251
  }
1620
- on(event, listener) {
1621
- return super.on(event, listener);
2252
+ /** Collect messages in this channel until time/max/stop. */
2253
+ createMessageCollector(options) {
2254
+ return new MessageCollector(this.client, this.id, options);
1622
2255
  }
1623
- emit(event, ...args) {
1624
- return super.emit(event, ...args);
2256
+ /**
2257
+ * Wait for messages matching the filter, then resolve the collected set.
2258
+ * Pass `errors: ['time']` to reject when the timer fires instead of resolving.
2259
+ * @example
2260
+ * const collected = await channel.awaitMessages({ max: 1, time: 15_000 });
2261
+ */
2262
+ awaitMessages(options) {
2263
+ return MessageCollector.awaitMessages(this.client, this.id, options);
2264
+ }
2265
+ /**
2266
+ * Delete this channel (or close it if it is a DM).
2267
+ * Guild channels require Manage Channels. `silent` / `deleteMessages` are Fluxer query params.
2268
+ * @example
2269
+ * const channel = await client.channels.fetch(channelId);
2270
+ * await channel.delete();
2271
+ */
2272
+ async delete(options) {
2273
+ const params = new URLSearchParams();
2274
+ if (options?.silent) params.set("silent", "true");
2275
+ if (options?.deleteMessages) params.set("delete_messages", "true");
2276
+ const qs2 = params.toString();
2277
+ const { silent: _s, deleteMessages: _d, reason: _reason, ...sudo } = options ?? {};
2278
+ const body = Object.keys(sudo).length ? toSudoBody(sudo) : void 0;
2279
+ await this.client.rest.delete(Routes7.channel(this.id) + (qs2 ? `?${qs2}` : ""), {
2280
+ body,
2281
+ auth: true,
2282
+ ...auditReasonHeaders(_reason)
2283
+ });
2284
+ this.client.channels.delete(this.id);
2285
+ this.client._clearMessageCache(this.id);
2286
+ if (this.isGuild() && this.guildId) {
2287
+ this.client.guilds.get(this.guildId)?.channels.delete(this.id);
2288
+ }
2289
+ }
2290
+ /** Channel mention (`<#id>`). */
2291
+ toString() {
2292
+ return `<#${this.id}>`;
1625
2293
  }
1626
2294
  };
1627
2295
 
2296
+ // src/Domain/Channel/Dm.ts
2297
+ import { ChannelType as ChannelType2, Routes as Routes9 } from "@fluxerjs/types";
2298
+
1628
2299
  // src/Domain/Channel/TextCapable.ts
2300
+ import { Routes as Routes8 } from "@fluxerjs/types";
1629
2301
  async function fetchPinnedMessagesPageFor(client, channelId, options) {
1630
2302
  const params = new URLSearchParams();
1631
2303
  if (options?.limit != null) params.set("limit", String(options.limit));
@@ -1643,27 +2315,19 @@ async function fetchPinnedMessagesPageFor(client, channelId, options) {
1643
2315
  }
1644
2316
  function TextCapable(Base2) {
1645
2317
  class TextCapableChannel extends Base2 {
1646
- #messages;
2318
+ /**
2319
+ * Send a message in this channel.
2320
+ * @example
2321
+ * await channel.send('hi');
2322
+ */
1647
2323
  async send(options) {
1648
- const payload = await prepareMessagePostPayload(options, {
1649
- defaultAllowedMentions: this.client.options.defaultAllowedMentions
1650
- });
1651
- const data = await this.client.rest.post(Routes8.channelMessages(this.id), payload);
1652
- this.client._addMessageToCache(this.id, data);
1653
- return new Message(this.client, data);
1654
- }
1655
- get messages() {
1656
- if (!this.#messages) {
1657
- this.#messages = new MessageManager(this.client, this.id);
1658
- }
1659
- return this.#messages;
1660
- }
1661
- createMessageCollector(options) {
1662
- return new MessageCollector(this.client, this.id, options);
2324
+ return this.client.channels.send(this.id, options);
1663
2325
  }
2326
+ /** Fetch pinned messages in this channel. */
1664
2327
  async fetchPinnedMessages(options) {
1665
2328
  return (await this.fetchPinnedMessagesPage(options)).messages;
1666
2329
  }
2330
+ /** Fetch a page of pinned messages plus pagination metadata. */
1667
2331
  async fetchPinnedMessagesPage(options) {
1668
2332
  return fetchPinnedMessagesPageFor(this.client, this.id, options);
1669
2333
  }
@@ -1689,7 +2353,38 @@ var DMChannel = class extends TextCapable(Channel) {
1689
2353
  this.recipients = (full.recipients ?? []).map((u) => client.getOrCreateUser(u));
1690
2354
  this.nicks = full.nicks ?? {};
1691
2355
  }
1692
- /** Purge all messages from personal notes. Only works on personal notes channels. */
2356
+ /**
2357
+ * Apply DM/group-DM fields in place.
2358
+ * @internal
2359
+ */
2360
+ _patch(data) {
2361
+ super._patch(data);
2362
+ const full = data;
2363
+ if ("last_message_id" in full && full.last_message_id !== void 0) {
2364
+ this.lastMessageId = full.last_message_id ?? null;
2365
+ }
2366
+ if ("owner_id" in full && full.owner_id !== void 0) this.ownerId = full.owner_id ?? null;
2367
+ if ("recipients" in full && full.recipients !== void 0) {
2368
+ this.recipients = (full.recipients ?? []).map((u) => this.client.getOrCreateUser(u));
2369
+ }
2370
+ if ("nicks" in full && full.nicks !== void 0) this.nicks = full.nicks ?? {};
2371
+ }
2372
+ /**
2373
+ * Edit this group DM (name, icon, nicks).
2374
+ * Transferring ownership to a bot fails (`CannotTransferOwnershipToBotError`).
2375
+ */
2376
+ async edit(options) {
2377
+ const data = await this.client.rest.patch(Routes9.channel(this.id), {
2378
+ body: toGroupDmEditBody(options),
2379
+ auth: true
2380
+ });
2381
+ this._patch(data);
2382
+ return this;
2383
+ }
2384
+ /**
2385
+ * Purge all messages from personal notes. Only works on personal notes channels.
2386
+ * Notes-only; bots usually skip this.
2387
+ */
1693
2388
  async purgeMessages() {
1694
2389
  if (this.type !== ChannelType2.DMPersonalNotes) {
1695
2390
  throw new FluxerError("purgeMessages is only available on personal notes channels", {
@@ -1702,15 +2397,24 @@ var DMChannel = class extends TextCapable(Channel) {
1702
2397
  );
1703
2398
  return data.deleted_count;
1704
2399
  }
1705
- /** Pin this DM channel to the top of the DM list. */
2400
+ /**
2401
+ * Pin this DM channel to the top of the DM list.
2402
+ * Session-token helper; bots usually skip this.
2403
+ */
1706
2404
  async pinInList() {
1707
2405
  await this.client.rest.put(Routes9.userMeChannelPin(this.id), { auth: true });
1708
2406
  }
1709
- /** Unpin this DM channel from the DM list. */
2407
+ /**
2408
+ * Unpin this DM channel from the DM list.
2409
+ * Session-token helper; bots usually skip this.
2410
+ */
1710
2411
  async unpinFromList() {
1711
2412
  await this.client.rest.delete(Routes9.userMeChannelPin(this.id), { auth: true });
1712
2413
  }
1713
- /** Add a user to this group DM. */
2414
+ /**
2415
+ * Add a user to this group DM.
2416
+ * Captcha-gated when captcha is enabled; bots are not exempt (`CaptchaRequiredError`).
2417
+ */
1714
2418
  async addRecipient(userId) {
1715
2419
  await this.client.rest.put(Routes9.channelRecipient(this.id, userId), { auth: true });
1716
2420
  const user = this.client.users.get(userId) ?? await this.client.users.fetch(userId);
@@ -1726,7 +2430,7 @@ var DMChannel = class extends TextCapable(Channel) {
1726
2430
  };
1727
2431
 
1728
2432
  // src/Domain/Channel/Guild.ts
1729
- import { Routes as Routes12 } from "@fluxerjs/types";
2433
+ import { Routes as Routes13 } from "@fluxerjs/types";
1730
2434
  import { PermissionFlags } from "@fluxerjs/util";
1731
2435
 
1732
2436
  // src/Domain/Invite.ts
@@ -1734,14 +2438,13 @@ import {
1734
2438
  InviteType,
1735
2439
  isGroupDmInvite,
1736
2440
  isGuildInvite,
1737
- isPackInvite,
1738
2441
  Routes as Routes10
1739
2442
  } from "@fluxerjs/types";
1740
2443
 
1741
2444
  // src/Helpers/Instance.ts
1742
2445
  import { isRecord } from "@fluxerjs/util";
1743
2446
  var DEFAULT_INSTANCE_ENDPOINTS = Object.freeze({
1744
- api: "https://api.fluxer.app",
2447
+ api: "https://web.fluxer.app/api",
1745
2448
  api_client: "https://web.fluxer.app/api",
1746
2449
  api_public: "https://api.fluxer.app",
1747
2450
  gateway: "wss://gateway.fluxer.app",
@@ -1775,6 +2478,10 @@ function requireString(obj, key, path) {
1775
2478
  }
1776
2479
  return value;
1777
2480
  }
2481
+ var INSTANCE_DISCOVERY_PATH = "/.well-known/fluxer";
2482
+ function instanceDiscoveryUrl(origin) {
2483
+ return `${normalizeApiOrigin(origin)}${INSTANCE_DISCOVERY_PATH}`;
2484
+ }
1778
2485
  function normalizeApiOrigin(api) {
1779
2486
  const trimmed = api.trim().replace(/\/+$/, "");
1780
2487
  return trimmed.replace(/\/v\d+$/i, "");
@@ -1803,6 +2510,8 @@ function parseInstanceDiscovery(raw) {
1803
2510
  endpoints[key] = requireString(raw.endpoints, key, "endpoints");
1804
2511
  }
1805
2512
  endpoints.api = normalizeApiOrigin(endpoints.api);
2513
+ endpoints.api_client = normalizeApiOrigin(endpoints.api_client);
2514
+ endpoints.api_public = normalizeApiOrigin(endpoints.api_public);
1806
2515
  endpoints.invite = normalizeInviteBase(endpoints.invite);
1807
2516
  endpoints.media = endpoints.media.replace(/\/+$/, "");
1808
2517
  endpoints.static_cdn = endpoints.static_cdn.replace(/\/+$/, "");
@@ -1880,6 +2589,11 @@ function resolveInstanceEndpoints(input) {
1880
2589
  }
1881
2590
  }
1882
2591
  merged.api = normalizeApiOrigin(merged.api);
2592
+ merged.api_client = normalizeApiOrigin(merged.api_client);
2593
+ merged.api_public = normalizeApiOrigin(merged.api_public);
2594
+ if (typeof partial.api === "string" && partial.api.length > 0 && (typeof partial.api_public !== "string" || partial.api_public.length === 0)) {
2595
+ merged.api_public = merged.api;
2596
+ }
1883
2597
  merged.invite = normalizeInviteBase(merged.invite);
1884
2598
  merged.media = merged.media.replace(/\/+$/, "");
1885
2599
  merged.static_cdn = merged.static_cdn.replace(/\/+$/, "");
@@ -1888,13 +2602,13 @@ function resolveInstanceEndpoints(input) {
1888
2602
  discovery: null
1889
2603
  });
1890
2604
  }
1891
- function resolveRestApi(instanceApi, restApi) {
1892
- const fromInstance = normalizeApiOrigin(instanceApi);
2605
+ function resolveRestApi(instanceApiPublic, restApi) {
2606
+ const fromInstance = normalizeApiOrigin(instanceApiPublic);
1893
2607
  if (restApi === void 0) return fromInstance;
1894
2608
  const fromRest = normalizeApiOrigin(restApi);
1895
2609
  if (fromRest !== fromInstance) {
1896
2610
  throw new FluxerError(
1897
- `Conflicting API hosts: instance.api (${fromInstance}) vs rest.api (${fromRest}). Prefer ClientOptions.instance.`,
2611
+ `Conflicting API hosts: instance.api_public (${fromInstance}) vs rest.api (${fromRest}). Prefer ClientOptions.instance.`,
1898
2612
  { code: ErrorCodes.ConflictingInstanceConfig }
1899
2613
  );
1900
2614
  }
@@ -1930,13 +2644,36 @@ function parseInviteCode(codeOrUrl) {
1930
2644
  }
1931
2645
  return code;
1932
2646
  }
2647
+ function parseOptionalDate(value) {
2648
+ if (value == null || value === "") return null;
2649
+ const date = new Date(value);
2650
+ return Number.isNaN(date.getTime()) ? null : date;
2651
+ }
2652
+ function toInviteGuild(data) {
2653
+ return {
2654
+ id: data.id,
2655
+ name: data.name,
2656
+ icon: data.icon ?? null,
2657
+ banner: data.banner ?? null,
2658
+ splash: data.splash ?? null,
2659
+ features: data.features ?? []
2660
+ };
2661
+ }
2662
+ function toInviteChannel(data) {
2663
+ return {
2664
+ id: data.id,
2665
+ name: data.name ?? null,
2666
+ type: data.type,
2667
+ icon: data.icon ?? null,
2668
+ parentId: data.parent_id ?? null
2669
+ };
2670
+ }
1933
2671
  var Invite = class _Invite extends Base {
1934
2672
  client;
1935
2673
  code;
1936
2674
  type;
1937
- guild;
1938
- channel;
1939
- pack;
2675
+ guildSnapshot;
2676
+ channelSnapshot;
1940
2677
  inviter;
1941
2678
  memberCount;
1942
2679
  presenceCount;
@@ -1951,15 +2688,14 @@ var Invite = class _Invite extends Base {
1951
2688
  this.client = client;
1952
2689
  this.code = data.code;
1953
2690
  this.type = data.type;
1954
- this.guild = isGuildInvite(data) ? data.guild : null;
1955
- this.channel = isGuildInvite(data) || isGroupDmInvite(data) ? data.channel : null;
1956
- this.pack = isPackInvite(data) ? data.pack : null;
2691
+ this.guildSnapshot = isGuildInvite(data) ? toInviteGuild(data.guild) : null;
2692
+ this.channelSnapshot = isGuildInvite(data) || isGroupDmInvite(data) ? toInviteChannel(data.channel) : null;
1957
2693
  this.inviter = data.inviter ? client.getOrCreateUser(data.inviter) : null;
1958
- this.memberCount = isPackInvite(data) ? null : data.member_count ?? null;
2694
+ this.memberCount = data.member_count ?? null;
1959
2695
  this.presenceCount = isGuildInvite(data) ? data.presence_count ?? null : null;
1960
- this.expiresAt = data.expires_at ?? null;
2696
+ this.expiresAt = parseOptionalDate(data.expires_at);
1961
2697
  this.temporary = data.temporary ?? null;
1962
- this.createdAt = data.created_at ?? null;
2698
+ this.createdAt = parseOptionalDate(data.created_at);
1963
2699
  this.uses = data.uses ?? null;
1964
2700
  this.maxUses = data.max_uses ?? null;
1965
2701
  this.maxAge = data.max_age ?? null;
@@ -1970,16 +2706,25 @@ var Invite = class _Invite extends Base {
1970
2706
  isGroupDM() {
1971
2707
  return this.type === InviteType.GroupDM;
1972
2708
  }
1973
- isPack() {
1974
- return this.type === InviteType.EmojiPack || this.type === InviteType.StickerPack;
1975
- }
1976
2709
  /** Full invite URL (uses this client's instance invite base). */
1977
2710
  get url() {
1978
2711
  return inviteUrl(this.client.instance.endpoints.invite, this.code);
1979
2712
  }
1980
- /** Cached guild for guild invites, else null. */
1981
- getGuild() {
1982
- return this.guild?.id ? this.client.guilds.get(this.guild.id) ?? null : null;
2713
+ /**
2714
+ * Resolve the cached/fetched {@link Guild} for this invite, or null.
2715
+ * `guildSnapshot` is metadata only.
2716
+ */
2717
+ async resolveGuild() {
2718
+ if (!this.guildSnapshot?.id) return null;
2719
+ return this.client.guilds.resolve(this.guildSnapshot.id);
2720
+ }
2721
+ /**
2722
+ * Resolve the cached/fetched {@link Channel} for this invite, or null.
2723
+ * `channelSnapshot` is metadata only.
2724
+ */
2725
+ async resolveChannel() {
2726
+ if (!this.channelSnapshot?.id) return null;
2727
+ return this.client.channels.resolve(this.channelSnapshot.id);
1983
2728
  }
1984
2729
  /** Fetch invite metadata by code or URL (does not join). */
1985
2730
  static async fetch(client, codeOrUrl) {
@@ -1997,7 +2742,7 @@ import { EmbedBuilder as EmbedBuilder3 } from "@fluxerjs/builders";
1997
2742
  import {
1998
2743
  Routes as Routes11
1999
2744
  } from "@fluxerjs/types";
2000
- import { SnowflakeUtil as SnowflakeUtil2 } from "@fluxerjs/util";
2745
+ import { SnowflakeUtil as SnowflakeUtil4 } from "@fluxerjs/util";
2001
2746
  var Webhook = class _Webhook extends Base {
2002
2747
  /** Parent client instance. */
2003
2748
  client;
@@ -2034,11 +2779,11 @@ var Webhook = class _Webhook extends Base {
2034
2779
  }
2035
2780
  /** Unix timestamp (ms) when this webhook was created, derived from its snowflake ID. */
2036
2781
  get createdTimestamp() {
2037
- return SnowflakeUtil2.timestampFromSnowflake(this.id);
2782
+ return SnowflakeUtil4.timestampFromSnowflake(this.id);
2038
2783
  }
2039
2784
  /** Date when this webhook was created, derived from its snowflake ID. */
2040
2785
  get createdAt() {
2041
- return SnowflakeUtil2.dateFromSnowflake(this.id);
2786
+ return SnowflakeUtil4.dateFromSnowflake(this.id);
2042
2787
  }
2043
2788
  /** Delete this webhook (token auth when available, otherwise bot auth). */
2044
2789
  async delete() {
@@ -2160,9 +2905,103 @@ var Webhook = class _Webhook extends Base {
2160
2905
  }
2161
2906
  };
2162
2907
 
2908
+ // src/Domain/Channel/PermissionOverwriteManager.ts
2909
+ import { Collection as Collection6 } from "@fluxerjs/collection";
2910
+ import { Routes as Routes12 } from "@fluxerjs/types";
2911
+ import { resolvePermissionsToBitfield as resolvePermissionsToBitfield3 } from "@fluxerjs/util";
2912
+
2913
+ // src/Domain/Channel/PermissionOverwrite.ts
2914
+ import { PermissionsBitField } from "@fluxerjs/util";
2915
+ var PermissionOverwrite = class {
2916
+ id;
2917
+ type;
2918
+ /** @internal Raw allow bitfield string. */
2919
+ _allow;
2920
+ /** @internal Raw deny bitfield string. */
2921
+ _deny;
2922
+ constructor(data) {
2923
+ this.id = data.id;
2924
+ this.type = data.type;
2925
+ this._allow = data.allow ?? "0";
2926
+ this._deny = data.deny ?? "0";
2927
+ }
2928
+ /** Allowed permissions for this overwrite. */
2929
+ get allow() {
2930
+ return new PermissionsBitField(BigInt(this._allow || "0"));
2931
+ }
2932
+ /** Denied permissions for this overwrite. */
2933
+ get deny() {
2934
+ return new PermissionsBitField(BigInt(this._deny || "0"));
2935
+ }
2936
+ /** Wire shape for permission computation / REST. */
2937
+ toJSON() {
2938
+ return {
2939
+ id: this.id,
2940
+ type: this.type,
2941
+ allow: this._allow,
2942
+ deny: this._deny
2943
+ };
2944
+ }
2945
+ };
2946
+
2947
+ // src/Domain/Channel/PermissionOverwriteManager.ts
2948
+ var PermissionOverwriteManager = class {
2949
+ constructor(channel, initial = []) {
2950
+ this.channel = channel;
2951
+ this._patch(initial);
2952
+ }
2953
+ _cache = new Collection6();
2954
+ /** Cached overwrites keyed by role/member ID. */
2955
+ get cache() {
2956
+ return this._cache;
2957
+ }
2958
+ get size() {
2959
+ return this._cache.size;
2960
+ }
2961
+ [Symbol.iterator]() {
2962
+ return this._cache.values();
2963
+ }
2964
+ /** Wire-shaped overwrites for permission computation. */
2965
+ toJSON() {
2966
+ return [...this._cache.values()].map((o) => o.toJSON());
2967
+ }
2968
+ /** Edit or create a permission overwrite. */
2969
+ async edit(overwriteId, options) {
2970
+ const allow = options.allow !== void 0 ? resolvePermissionsToBitfield3(options.allow) : "0";
2971
+ const deny = options.deny !== void 0 ? resolvePermissionsToBitfield3(options.deny) : "0";
2972
+ await this.channel.client.rest.put(Routes12.channelPermission(this.channel.id, overwriteId), {
2973
+ body: { type: options.type, allow, deny },
2974
+ auth: true
2975
+ });
2976
+ this._cache.set(
2977
+ overwriteId,
2978
+ new PermissionOverwrite({
2979
+ id: overwriteId,
2980
+ type: options.type,
2981
+ allow,
2982
+ deny
2983
+ })
2984
+ );
2985
+ }
2986
+ /** Delete a permission overwrite. */
2987
+ async delete(overwriteId) {
2988
+ await this.channel.client.rest.delete(Routes12.channelPermission(this.channel.id, overwriteId), {
2989
+ auth: true
2990
+ });
2991
+ this._cache.delete(overwriteId);
2992
+ }
2993
+ /** @internal Sync from an API channel payload. */
2994
+ _patch(overwrites) {
2995
+ this._cache.clear();
2996
+ for (const entry of overwrites ?? []) {
2997
+ this._cache.set(entry.id, new PermissionOverwrite(entry));
2998
+ }
2999
+ }
3000
+ };
3001
+
2163
3002
  // src/Domain/Channel/Guild.ts
2164
3003
  var GuildChannel = class extends Channel {
2165
- /** Guild ID this channel belongs to. */
3004
+ /** Guild ID this channel belongs to, or null if missing from the payload. */
2166
3005
  guildId;
2167
3006
  /** Position in the channel list. */
2168
3007
  position;
@@ -2172,11 +3011,14 @@ var GuildChannel = class extends Channel {
2172
3011
  permissionOverwrites;
2173
3012
  constructor(client, data) {
2174
3013
  super(client, data);
2175
- this.guildId = data.guild_id ?? "";
3014
+ this.guildId = data.guild_id ?? null;
2176
3015
  this.name = data.name ?? null;
2177
3016
  this.position = data.position;
2178
3017
  this.parentId = data.parent_id ?? null;
2179
- this.permissionOverwrites = data.permission_overwrites ?? [];
3018
+ this.permissionOverwrites = new PermissionOverwriteManager(
3019
+ this,
3020
+ data.permission_overwrites ?? []
3021
+ );
2180
3022
  }
2181
3023
  /**
2182
3024
  * Apply guild-channel fields in place.
@@ -2188,13 +3030,13 @@ var GuildChannel = class extends Channel {
2188
3030
  if (data.position !== void 0) this.position = data.position;
2189
3031
  if (data.parent_id !== void 0) this.parentId = data.parent_id ?? null;
2190
3032
  if (data.permission_overwrites !== void 0) {
2191
- this.permissionOverwrites = data.permission_overwrites ?? [];
3033
+ this.permissionOverwrites._patch(data.permission_overwrites ?? []);
2192
3034
  }
2193
3035
  this.applyEditPatch(data);
2194
3036
  }
2195
3037
  /** Create a webhook for this channel. Requires Manage Webhooks. */
2196
3038
  async createWebhook(options) {
2197
- const data = await this.client.rest.post(Routes12.channelWebhooks(this.id), {
3039
+ const data = await this.client.rest.post(Routes13.channelWebhooks(this.id), {
2198
3040
  body: options,
2199
3041
  auth: true
2200
3042
  });
@@ -2202,13 +3044,13 @@ var GuildChannel = class extends Channel {
2202
3044
  }
2203
3045
  /** Fetch all webhooks in this channel. Requires Manage Webhooks. */
2204
3046
  async fetchWebhooks() {
2205
- const data = await this.client.rest.get(Routes12.channelWebhooks(this.id));
3047
+ const data = await this.client.rest.get(Routes13.channelWebhooks(this.id));
2206
3048
  return data.map((w) => new Webhook(this.client, w));
2207
3049
  }
2208
3050
  /** Create an invite for this channel. Requires Create Instant Invite. */
2209
3051
  async createInvite(options) {
2210
3052
  const body = options ? toChannelInviteBody(options) : {};
2211
- const data = await this.client.rest.post(Routes12.channelInvites(this.id), {
3053
+ const data = await this.client.rest.post(Routes13.channelInvites(this.id), {
2212
3054
  body: Object.keys(body).length ? body : void 0,
2213
3055
  auth: true
2214
3056
  });
@@ -2216,109 +3058,161 @@ var GuildChannel = class extends Channel {
2216
3058
  }
2217
3059
  /** Fetch all invites for this channel. Requires Manage Channels. */
2218
3060
  async fetchInvites() {
2219
- const data = await this.client.rest.get(Routes12.channelInvites(this.id));
3061
+ const data = await this.client.rest.get(Routes13.channelInvites(this.id));
2220
3062
  return data.map((i) => new Invite(this.client, i));
2221
3063
  }
2222
- /** Edit or create a permission overwrite. Requires Manage Roles. */
2223
- async editPermission(overwriteId, options) {
2224
- await this.client.rest.put(Routes12.channelPermission(this.id, overwriteId), {
2225
- body: options,
2226
- auth: true
2227
- });
2228
- const entry = {
2229
- id: overwriteId,
2230
- type: options.type,
2231
- allow: options.allow ?? "0",
2232
- deny: options.deny ?? "0"
2233
- };
2234
- const idx = this.permissionOverwrites.findIndex((o) => o.id === overwriteId);
2235
- if (idx >= 0) this.permissionOverwrites[idx] = entry;
2236
- else this.permissionOverwrites.push(entry);
2237
- }
2238
- /** Delete a permission overwrite. Requires Manage Roles. */
2239
- async deletePermission(overwriteId) {
2240
- await this.client.rest.delete(Routes12.channelPermission(this.id, overwriteId), { auth: true });
2241
- const idx = this.permissionOverwrites.findIndex((o) => o.id === overwriteId);
2242
- if (idx >= 0) this.permissionOverwrites.splice(idx, 1);
2243
- }
2244
- /** Check if the bot can send messages in this channel (with permissions). */
3064
+ /** Check if the bot can send messages in this channel (cache-only; needs `members.me`). */
2245
3065
  canSendMessage() {
3066
+ if (!this.guildId) return false;
2246
3067
  const me = this.client.guilds.get(this.guildId)?.members.me;
2247
3068
  if (!me) return false;
2248
3069
  const perms = me.permissionsIn(this);
2249
3070
  return perms.has(PermissionFlags.ViewChannel) && perms.has(PermissionFlags.SendMessages);
2250
3071
  }
3072
+ /**
3073
+ * Like {@link canSendMessage}, but hydrates `members.me` via REST when missing.
3074
+ * Returns false when the channel has no guildId.
3075
+ */
3076
+ async canSend() {
3077
+ if (!this.guildId) return false;
3078
+ const guild = this.client.guilds.get(this.guildId);
3079
+ if (!guild) return false;
3080
+ if (!guild.members.me) {
3081
+ try {
3082
+ await guild.members.fetchMe();
3083
+ } catch {
3084
+ return false;
3085
+ }
3086
+ }
3087
+ return this.canSendMessage();
3088
+ }
2251
3089
  /** Edit this channel's settings. Requires Manage Channels. */
2252
3090
  async edit(options) {
2253
- const data = await this.client.rest.patch(Routes12.channel(this.id), {
3091
+ const data = await this.client.rest.patch(Routes13.channel(this.id), {
2254
3092
  body: toChannelEditBody(options),
2255
- auth: true
3093
+ auth: true,
3094
+ ...auditReasonHeaders(options.reason)
2256
3095
  });
2257
3096
  this.name = data.name ?? this.name;
2258
3097
  this.parentId = data.parent_id ?? this.parentId;
2259
- this.permissionOverwrites = data.permission_overwrites ?? this.permissionOverwrites;
3098
+ if (data.permission_overwrites !== void 0) {
3099
+ this.permissionOverwrites._patch(data.permission_overwrites);
3100
+ }
2260
3101
  this.applyEditPatch(data);
2261
3102
  return this;
2262
3103
  }
2263
3104
  applyEditPatch(_data) {
2264
3105
  }
2265
- /** Delete this channel. Requires Manage Channels or channel ownership. */
2266
- async delete(options) {
2267
- const params = new URLSearchParams();
2268
- if (options?.silent) params.set("silent", "true");
2269
- if (options?.deleteMessages) params.set("delete_messages", "true");
2270
- const qs2 = params.toString();
2271
- const { silent: _s, deleteMessages: _d, ...sudo } = options ?? {};
2272
- const body = Object.keys(sudo).length ? toSudoBody(sudo) : void 0;
2273
- await this.client.rest.delete(Routes12.channel(this.id) + (qs2 ? `?${qs2}` : ""), {
2274
- body,
2275
- auth: true
2276
- });
2277
- this.client.channels.delete(this.id);
2278
- this.client._clearMessageCache(this.id);
2279
- this.client.guilds.get(this.guildId)?.channels.delete(this.id);
2280
- }
2281
3106
  };
2282
3107
  var TextChannel = class extends TextCapable(GuildChannel) {
2283
3108
  /** Channel topic. */
2284
3109
  topic;
2285
3110
  /** Whether this channel is marked as NSFW. */
2286
3111
  nsfw;
3112
+ /** Per-channel NSFW override (`null` inherits). */
3113
+ nsfwOverride;
2287
3114
  /** Slowmode rate limit in seconds. */
2288
3115
  rateLimitPerUser;
2289
3116
  /** ID of the last message sent in this channel. */
2290
3117
  lastMessageId;
3118
+ /** Content warning level. */
3119
+ contentWarningLevel;
3120
+ /** Custom content warning text. */
3121
+ contentWarningText;
2291
3122
  constructor(client, data) {
2292
3123
  super(client, data);
2293
3124
  this.topic = data.topic ?? null;
2294
3125
  this.nsfw = data.nsfw ?? false;
3126
+ this.nsfwOverride = data.nsfw_override ?? null;
2295
3127
  this.rateLimitPerUser = data.rate_limit_per_user ?? 0;
2296
3128
  this.lastMessageId = data.last_message_id ?? null;
3129
+ this.contentWarningLevel = data.content_warning_level ?? null;
3130
+ this.contentWarningText = data.content_warning_text ?? null;
3131
+ }
3132
+ /**
3133
+ * Set slowmode (seconds between messages). Pass `0` to disable.
3134
+ * Requires Manage Channels. Calls {@link GuildChannel.edit} with `rateLimitPerUser`.
3135
+ */
3136
+ async setSlowmode(seconds) {
3137
+ return this.edit({ rateLimitPerUser: seconds });
2297
3138
  }
2298
3139
  applyEditPatch(data) {
2299
3140
  if ("topic" in data) this.topic = data.topic ?? null;
2300
3141
  if ("nsfw" in data) this.nsfw = data.nsfw ?? false;
3142
+ if ("nsfw_override" in data) this.nsfwOverride = data.nsfw_override ?? null;
2301
3143
  if ("rate_limit_per_user" in data) this.rateLimitPerUser = data.rate_limit_per_user ?? 0;
3144
+ if ("last_message_id" in data) this.lastMessageId = data.last_message_id ?? null;
3145
+ if ("content_warning_level" in data) {
3146
+ this.contentWarningLevel = data.content_warning_level ?? null;
3147
+ }
3148
+ if ("content_warning_text" in data) {
3149
+ this.contentWarningText = data.content_warning_text ?? null;
3150
+ }
2302
3151
  }
2303
3152
  };
2304
3153
  var CategoryChannel = class extends GuildChannel {
2305
3154
  };
2306
- var VoiceChannel = class extends GuildChannel {
3155
+ var VoiceChannel = class extends TextCapable(GuildChannel) {
3156
+ /** Channel topic. */
3157
+ topic;
3158
+ /** Whether this channel is marked as NSFW. */
3159
+ nsfw;
3160
+ /** Per-channel NSFW override (`null` inherits). */
3161
+ nsfwOverride;
3162
+ /** Slowmode rate limit in seconds. */
3163
+ rateLimitPerUser;
3164
+ /** ID of the last message sent in this channel. */
3165
+ lastMessageId;
3166
+ /** Content warning level. */
3167
+ contentWarningLevel;
3168
+ /** Custom content warning text. */
3169
+ contentWarningText;
2307
3170
  /** Voice bitrate. */
2308
3171
  bitrate;
2309
3172
  /** Maximum number of users allowed. */
2310
3173
  userLimit;
3174
+ /** Max active voice connections per user. */
3175
+ voiceConnectionLimit;
2311
3176
  /** RTC region override for this channel. */
2312
3177
  rtcRegion;
2313
3178
  constructor(client, data) {
2314
3179
  super(client, data);
3180
+ this.topic = data.topic ?? null;
3181
+ this.nsfw = data.nsfw ?? false;
3182
+ this.nsfwOverride = data.nsfw_override ?? null;
3183
+ this.rateLimitPerUser = data.rate_limit_per_user ?? 0;
3184
+ this.lastMessageId = data.last_message_id ?? null;
3185
+ this.contentWarningLevel = data.content_warning_level ?? null;
3186
+ this.contentWarningText = data.content_warning_text ?? null;
2315
3187
  this.bitrate = data.bitrate ?? null;
2316
3188
  this.userLimit = data.user_limit ?? null;
3189
+ this.voiceConnectionLimit = data.voice_connection_limit ?? null;
2317
3190
  this.rtcRegion = data.rtc_region ?? null;
2318
3191
  }
3192
+ /**
3193
+ * Set slowmode (seconds between messages). Pass `0` to disable.
3194
+ * Requires Manage Channels. Calls {@link GuildChannel.edit} with `rateLimitPerUser`.
3195
+ */
3196
+ async setSlowmode(seconds) {
3197
+ return this.edit({ rateLimitPerUser: seconds });
3198
+ }
2319
3199
  applyEditPatch(data) {
3200
+ if ("topic" in data) this.topic = data.topic ?? null;
3201
+ if ("nsfw" in data) this.nsfw = data.nsfw ?? false;
3202
+ if ("nsfw_override" in data) this.nsfwOverride = data.nsfw_override ?? null;
3203
+ if ("rate_limit_per_user" in data) this.rateLimitPerUser = data.rate_limit_per_user ?? 0;
3204
+ if ("last_message_id" in data) this.lastMessageId = data.last_message_id ?? null;
3205
+ if ("content_warning_level" in data) {
3206
+ this.contentWarningLevel = data.content_warning_level ?? null;
3207
+ }
3208
+ if ("content_warning_text" in data) {
3209
+ this.contentWarningText = data.content_warning_text ?? null;
3210
+ }
2320
3211
  if ("bitrate" in data) this.bitrate = data.bitrate ?? null;
2321
3212
  if ("user_limit" in data) this.userLimit = data.user_limit ?? null;
3213
+ if ("voice_connection_limit" in data) {
3214
+ this.voiceConnectionLimit = data.voice_connection_limit ?? null;
3215
+ }
2322
3216
  if ("rtc_region" in data) this.rtcRegion = data.rtc_region ?? null;
2323
3217
  }
2324
3218
  };
@@ -2329,6 +3223,9 @@ var LinkChannel = class extends GuildChannel {
2329
3223
  super(client, data);
2330
3224
  this.url = data.url ?? null;
2331
3225
  }
3226
+ applyEditPatch(data) {
3227
+ if ("url" in data) this.url = data.url ?? null;
3228
+ }
2332
3229
  };
2333
3230
 
2334
3231
  // src/Domain/Channel/Factory.ts
@@ -2444,11 +3341,11 @@ var User = class extends Base {
2444
3341
  */
2445
3342
  /** Unix timestamp (ms) when this account was created, derived from its snowflake ID. */
2446
3343
  get createdTimestamp() {
2447
- return SnowflakeUtil3.timestampFromSnowflake(this.id);
3344
+ return SnowflakeUtil5.timestampFromSnowflake(this.id);
2448
3345
  }
2449
3346
  /** Date when this account was created, derived from its snowflake ID. */
2450
3347
  get createdAt() {
2451
- return SnowflakeUtil3.dateFromSnowflake(this.id);
3348
+ return SnowflakeUtil5.dateFromSnowflake(this.id);
2452
3349
  }
2453
3350
  toString() {
2454
3351
  return `<@${this.id}>`;
@@ -2458,7 +3355,7 @@ var User = class extends Base {
2458
3355
  * @returns DM channel instance (cached if already open)
2459
3356
  */
2460
3357
  async createDM() {
2461
- const data = await this.client.rest.post(Routes13.userMeChannels(), {
3358
+ const data = await this.client.rest.post(Routes14.userMeChannels(), {
2462
3359
  body: { recipient_id: this.id },
2463
3360
  auth: true
2464
3361
  });
@@ -2573,6 +3470,9 @@ var CacheController = class {
2573
3470
  stickers
2574
3471
  };
2575
3472
  }
3473
+ /**
3474
+ * Sweep cached messages. Filter receives a hydrated {@link Message} (`createdAt`).
3475
+ */
2576
3476
  sweepMessages(filter, channelId) {
2577
3477
  return this.client.sweepMessages(filter, channelId);
2578
3478
  }
@@ -2641,7 +3541,7 @@ var CacheController = class {
2641
3541
  * @internal
2642
3542
  */
2643
3543
  cascadeChannel(channel, from = "both") {
2644
- const guildId = "guildId" in channel && typeof channel.guildId === "string" ? channel.guildId : void 0;
3544
+ const guildId = typeof channel.isGuild === "function" && channel.isGuild() ? channel.guildId : void 0;
2645
3545
  const dropFromGuild = () => {
2646
3546
  if (!guildId) return;
2647
3547
  const guildChannels = this.client.guilds.get(guildId)?.channels;
@@ -2672,11 +3572,11 @@ var CacheController = class {
2672
3572
 
2673
3573
  // src/ClientCore/ChannelManager.ts
2674
3574
  import { LimitedCollection } from "@fluxerjs/collection";
2675
- import { Routes as Routes19 } from "@fluxerjs/types";
3575
+ import { Routes as Routes20 } from "@fluxerjs/types";
2676
3576
 
2677
3577
  // src/Domain/Guild/GuildEmoji.ts
2678
- import { Routes as Routes14 } from "@fluxerjs/types";
2679
- import { SnowflakeUtil as SnowflakeUtil4 } from "@fluxerjs/util";
3578
+ import { Routes as Routes15 } from "@fluxerjs/types";
3579
+ import { SnowflakeUtil as SnowflakeUtil6 } from "@fluxerjs/util";
2680
3580
  var GuildEmoji = class extends Base {
2681
3581
  client;
2682
3582
  id;
@@ -2712,20 +3612,21 @@ var GuildEmoji = class extends Base {
2712
3612
  }
2713
3613
  /** Unix timestamp (ms) when this emoji was created, derived from its snowflake ID. */
2714
3614
  get createdTimestamp() {
2715
- return SnowflakeUtil4.timestampFromSnowflake(this.id);
3615
+ return SnowflakeUtil6.timestampFromSnowflake(this.id);
2716
3616
  }
2717
3617
  /** Date when this emoji was created, derived from its snowflake ID. */
2718
3618
  get createdAt() {
2719
- return SnowflakeUtil4.dateFromSnowflake(this.id);
3619
+ return SnowflakeUtil6.dateFromSnowflake(this.id);
2720
3620
  }
2721
3621
  /** Renders this emoji for use in message content: `<:name:id>` (or `<a:name:id>` when animated). */
2722
3622
  toString() {
2723
3623
  return `<${this.animated ? "a" : ""}:${this.name}:${this.id}>`;
2724
3624
  }
2725
3625
  /** Delete this emoji. Requires Manage Emojis and Stickers permission. */
2726
- async delete() {
2727
- await this.client.rest.delete(Routes14.guildEmoji(this.guildId, this.id), {
2728
- auth: true
3626
+ async delete(reason) {
3627
+ await this.client.rest.delete(Routes15.guildEmoji(this.guildId, this.id), {
3628
+ auth: true,
3629
+ ...auditReasonHeaders(reason)
2729
3630
  });
2730
3631
  const guild = this.client.guilds.get(this.guildId);
2731
3632
  if (guild) guild.emojis.delete(this.id);
@@ -2735,9 +3636,11 @@ var GuildEmoji = class extends Base {
2735
3636
  * Requires Manage Emojis and Stickers permission.
2736
3637
  */
2737
3638
  async edit(options) {
2738
- const data = await this.client.rest.patch(Routes14.guildEmoji(this.guildId, this.id), {
2739
- body: options,
2740
- auth: true
3639
+ const { reason, name } = options;
3640
+ const data = await this.client.rest.patch(Routes15.guildEmoji(this.guildId, this.id), {
3641
+ body: { name },
3642
+ auth: true,
3643
+ ...auditReasonHeaders(reason)
2741
3644
  });
2742
3645
  this.name = data.name;
2743
3646
  return this;
@@ -2745,14 +3648,17 @@ var GuildEmoji = class extends Base {
2745
3648
  };
2746
3649
 
2747
3650
  // src/Domain/Guild/GuildMember.ts
2748
- import { Routes as Routes16 } from "@fluxerjs/types";
2749
- import { PermissionsBitField } from "@fluxerjs/util";
3651
+ import { Routes as Routes17 } from "@fluxerjs/types";
3652
+ import { PermissionFlags as PermissionFlags3, PermissionsBitField as PermissionsBitField2 } from "@fluxerjs/util";
2750
3653
 
2751
3654
  // src/Helpers/Permissions.ts
2752
3655
  import { OverwriteType } from "@fluxerjs/types";
2753
3656
  import { ALL_PERMISSIONS_BIGINT, PermissionFlags as PermissionFlags2 } from "@fluxerjs/util";
2754
3657
  function computePermissions(basePermissions, overwrites, memberRoles, memberId, isOwner) {
2755
3658
  if (isOwner) return ALL_PERMISSIONS_BIGINT;
3659
+ if ((basePermissions & PermissionFlags2.Administrator) !== 0n) {
3660
+ return ALL_PERMISSIONS_BIGINT;
3661
+ }
2756
3662
  let perms = basePermissions;
2757
3663
  for (const overwrite of overwrites ?? []) {
2758
3664
  const applies = overwrite.type === OverwriteType.Role && memberRoles.includes(overwrite.id) || overwrite.type === OverwriteType.Member && overwrite.id === memberId;
@@ -2761,12 +3667,12 @@ function computePermissions(basePermissions, overwrites, memberRoles, memberId,
2761
3667
  const deny = BigInt(overwrite.deny || "0");
2762
3668
  perms = perms & ~deny | allow;
2763
3669
  }
2764
- return (perms & PermissionFlags2.Administrator) !== 0n ? ALL_PERMISSIONS_BIGINT : perms;
3670
+ return perms;
2765
3671
  }
2766
3672
 
2767
3673
  // src/Domain/Guild/GuildMemberRoleManager.ts
2768
- import { Collection as Collection5 } from "@fluxerjs/collection";
2769
- import { Routes as Routes15 } from "@fluxerjs/types";
3674
+ import { Collection as Collection7 } from "@fluxerjs/collection";
3675
+ import { Routes as Routes16 } from "@fluxerjs/types";
2770
3676
  function roleId(roleOrId) {
2771
3677
  return typeof roleOrId === "string" ? roleOrId : roleOrId.id;
2772
3678
  }
@@ -2784,7 +3690,7 @@ var GuildMemberRoleManager = class {
2784
3690
  }
2785
3691
  /** Live Role objects from `guild.roles` for this member's role IDs. */
2786
3692
  get cache() {
2787
- const out = new Collection5();
3693
+ const out = new Collection7();
2788
3694
  for (const id of this.ids) {
2789
3695
  const role = this.member.guild.roles.get(id);
2790
3696
  if (role) out.set(id, role);
@@ -2795,7 +3701,7 @@ var GuildMemberRoleManager = class {
2795
3701
  const id = roleId(roleOrId);
2796
3702
  if (this.ids.includes(id)) return;
2797
3703
  await this.member.client.rest.put(
2798
- Routes15.guildMemberRole(this.member.guild.id, this.member.id, id)
3704
+ Routes16.guildMemberRole(this.member.guild.id, this.member.id, id)
2799
3705
  );
2800
3706
  this.ids.push(id);
2801
3707
  }
@@ -2804,13 +3710,13 @@ var GuildMemberRoleManager = class {
2804
3710
  const idx = this.ids.indexOf(id);
2805
3711
  if (idx === -1) return;
2806
3712
  await this.member.client.rest.delete(
2807
- Routes15.guildMemberRole(this.member.guild.id, this.member.id, id)
3713
+ Routes16.guildMemberRole(this.member.guild.id, this.member.id, id)
2808
3714
  );
2809
3715
  this.ids.splice(idx, 1);
2810
3716
  }
2811
3717
  async set(roleIds) {
2812
3718
  const data = await this.member.client.rest.patch(
2813
- Routes15.guildMember(this.member.guild.id, this.member.id),
3719
+ Routes16.guildMember(this.member.guild.id, this.member.id),
2814
3720
  { body: { roles: roleIds }, auth: true }
2815
3721
  );
2816
3722
  this.ids = data.roles ? [...data.roles] : [];
@@ -2823,6 +3729,8 @@ var GuildMemberRoleManager = class {
2823
3729
 
2824
3730
  // src/Domain/Guild/GuildMember.ts
2825
3731
  var GuildMember = class _GuildMember extends Base {
3732
+ /** Discriminant vs {@link PartialGuildMember}: always `false` on a hydrated member. */
3733
+ partial = false;
2826
3734
  /** Parent client instance. */
2827
3735
  client;
2828
3736
  /** User ID (same as `user.id`). */
@@ -2851,6 +3759,12 @@ var GuildMember = class _GuildMember extends Base {
2851
3759
  accentColor;
2852
3760
  /** Guild-specific profile flags. */
2853
3761
  profileFlags;
3762
+ /** Per-guild reply mention preference override. */
3763
+ mentionFlags;
3764
+ /** Guild-specific bio (set from member edit; not always on GET member). */
3765
+ bio;
3766
+ /** Guild-specific pronouns (set from member edit; not always on GET member). */
3767
+ pronouns;
2854
3768
  constructor(client, data, guild) {
2855
3769
  super();
2856
3770
  this.client = client;
@@ -2867,6 +3781,9 @@ var GuildMember = class _GuildMember extends Base {
2867
3781
  this.banner = data.banner ?? null;
2868
3782
  this.accentColor = data.accent_color ?? null;
2869
3783
  this.profileFlags = data.profile_flags ?? null;
3784
+ this.mentionFlags = data.mention_flags ?? null;
3785
+ this.bio = data.bio ?? null;
3786
+ this.pronouns = data.pronouns ?? null;
2870
3787
  }
2871
3788
  /**
2872
3789
  * Apply an API member payload in place (gateway GUILD_MEMBER_UPDATE / REST edit).
@@ -2885,6 +3802,9 @@ var GuildMember = class _GuildMember extends Base {
2885
3802
  if (data.banner !== void 0) this.banner = data.banner ?? null;
2886
3803
  if (data.accent_color !== void 0) this.accentColor = data.accent_color ?? null;
2887
3804
  if (data.profile_flags !== void 0) this.profileFlags = data.profile_flags ?? null;
3805
+ if (data.mention_flags !== void 0) this.mentionFlags = data.mention_flags ?? null;
3806
+ if (data.bio !== void 0) this.bio = data.bio ?? null;
3807
+ if (data.pronouns !== void 0) this.pronouns = data.pronouns ?? null;
2888
3808
  }
2889
3809
  /**
2890
3810
  * Snapshot for `guildMemberUpdate` old-member arg (before in-place patch).
@@ -2913,7 +3833,10 @@ var GuildMember = class _GuildMember extends Base {
2913
3833
  avatar: this.avatar,
2914
3834
  banner: this.banner,
2915
3835
  accent_color: this.accentColor,
2916
- profile_flags: this.profileFlags ?? void 0
3836
+ profile_flags: this.profileFlags ?? void 0,
3837
+ mention_flags: this.mentionFlags,
3838
+ bio: this.bio,
3839
+ pronouns: this.pronouns
2917
3840
  },
2918
3841
  this.guild
2919
3842
  );
@@ -2940,15 +3863,23 @@ var GuildMember = class _GuildMember extends Base {
2940
3863
  mediaBase: this.client.instance.endpoints.media
2941
3864
  });
2942
3865
  }
2943
- /** PATCH member (`/members/@me` when editing the bot). */
3866
+ /**
3867
+ * PATCH member (`/members/@me` when editing the bot).
3868
+ * @example
3869
+ * await member.edit({ nick: 'Ada' });
3870
+ */
2944
3871
  async edit(options) {
2945
3872
  const isMe = this.client.user?.id === this.id;
2946
- const route = isMe ? Routes16.guildMemberMe(this.guild.id) : Routes16.guildMember(this.guild.id, this.id);
3873
+ const route = isMe ? Routes17.guildMemberMe(this.guild.id) : Routes17.guildMember(this.guild.id, this.id);
2947
3874
  const data = await this.client.rest.patch(route, {
2948
3875
  body: toMemberEditBody(options),
2949
- auth: true
3876
+ auth: true,
3877
+ ...auditReasonHeaders(options.reason ?? options.timeoutReason)
2950
3878
  });
2951
3879
  this._patch(data);
3880
+ if (options.bio !== void 0) this.bio = options.bio;
3881
+ if (options.pronouns !== void 0) this.pronouns = options.pronouns;
3882
+ if (options.mentionFlags !== void 0) this.mentionFlags = options.mentionFlags;
2952
3883
  return this;
2953
3884
  }
2954
3885
  /**
@@ -2956,7 +3887,7 @@ var GuildMember = class _GuildMember extends Base {
2956
3887
  * @see {@link permissionsIn} for channel-specific permissions
2957
3888
  */
2958
3889
  get permissions() {
2959
- return new PermissionsBitField(this._effectivePermissions([], []));
3890
+ return new PermissionsBitField2(this._effectivePermissions([], []));
2960
3891
  }
2961
3892
  /**
2962
3893
  * Effective permissions in a channel (roles + overwrites).
@@ -2964,8 +3895,8 @@ var GuildMember = class _GuildMember extends Base {
2964
3895
  * @returns Computed permissions bitfield
2965
3896
  */
2966
3897
  permissionsIn(channel) {
2967
- return new PermissionsBitField(
2968
- this._effectivePermissions(channel.permissionOverwrites, [...this.roles.roleIds])
3898
+ return new PermissionsBitField2(
3899
+ this._effectivePermissions(channel.permissionOverwrites.toJSON(), [...this.roles.roleIds])
2969
3900
  );
2970
3901
  }
2971
3902
  /**
@@ -2976,6 +3907,63 @@ var GuildMember = class _GuildMember extends Base {
2976
3907
  async move(channelId, connectionId) {
2977
3908
  await this.edit({ channelId, connectionId });
2978
3909
  }
3910
+ /** Kick this member. Requires Kick Members. */
3911
+ async kick(reason) {
3912
+ await this.guild.kick(this.id, reason);
3913
+ }
3914
+ /** Ban this member. Requires Ban Members. */
3915
+ async ban(options) {
3916
+ await this.guild.ban(this.id, options);
3917
+ }
3918
+ /**
3919
+ * Whether the bot can kick this member (cache-only; needs `members.me`).
3920
+ * False for the guild owner, self, or when the bot lacks Kick Members / role hierarchy.
3921
+ */
3922
+ get kickable() {
3923
+ return this._moderatableWith(PermissionFlags3.KickMembers);
3924
+ }
3925
+ /**
3926
+ * Whether the bot can ban this member (cache-only; needs `members.me`).
3927
+ */
3928
+ get bannable() {
3929
+ return this._moderatableWith(PermissionFlags3.BanMembers);
3930
+ }
3931
+ /**
3932
+ * Whether the bot can timeout this member (cache-only; needs `members.me`).
3933
+ */
3934
+ get moderatable() {
3935
+ return this._moderatableWith(PermissionFlags3.ModerateMembers);
3936
+ }
3937
+ _moderatableWith(flag) {
3938
+ const me = this.guild.members.me;
3939
+ if (!me) return false;
3940
+ if (this.id === me.id) return false;
3941
+ if (this.guild.ownerId != null && String(this.guild.ownerId) === String(this.id)) return false;
3942
+ if (!me.permissions.has(flag)) return false;
3943
+ return this._compareRolePosition(me) < 0;
3944
+ }
3945
+ /** Negative when this member's highest role is below `other`'s. */
3946
+ _compareRolePosition(other) {
3947
+ const highest = (m) => {
3948
+ let pos = -1;
3949
+ for (const role of m.roles.cache.values()) {
3950
+ if (role.position > pos) pos = role.position;
3951
+ }
3952
+ return pos;
3953
+ };
3954
+ return highest(this) - highest(other);
3955
+ }
3956
+ /**
3957
+ * Timeout this member for `durationMs` milliseconds, or pass `null` to clear.
3958
+ * Requires Moderate Members.
3959
+ */
3960
+ async timeout(durationMs, reason) {
3961
+ const communicationDisabledUntil = durationMs == null || durationMs <= 0 ? null : new Date(Date.now() + durationMs).toISOString();
3962
+ return this.edit({
3963
+ communicationDisabledUntil,
3964
+ ...reason !== void 0 ? { timeoutReason: reason } : {}
3965
+ });
3966
+ }
2979
3967
  _effectivePermissions(overwrites, roleIds) {
2980
3968
  const ownerId = this.guild.ownerId;
2981
3969
  const isOwner = ownerId != null && ownerId !== "" && String(ownerId) === String(this.id);
@@ -2995,8 +3983,8 @@ var GuildMember = class _GuildMember extends Base {
2995
3983
  };
2996
3984
 
2997
3985
  // src/Domain/Guild/GuildSticker.ts
2998
- import { Routes as Routes17 } from "@fluxerjs/types";
2999
- import { SnowflakeUtil as SnowflakeUtil5 } from "@fluxerjs/util";
3986
+ import { Routes as Routes18 } from "@fluxerjs/types";
3987
+ import { SnowflakeUtil as SnowflakeUtil7 } from "@fluxerjs/util";
3000
3988
  var GuildSticker = class extends Base {
3001
3989
  client;
3002
3990
  id;
@@ -3038,16 +4026,17 @@ var GuildSticker = class extends Base {
3038
4026
  }
3039
4027
  /** Unix timestamp (ms) when this sticker was created, derived from its snowflake ID. */
3040
4028
  get createdTimestamp() {
3041
- return SnowflakeUtil5.timestampFromSnowflake(this.id);
4029
+ return SnowflakeUtil7.timestampFromSnowflake(this.id);
3042
4030
  }
3043
4031
  /** Date when this sticker was created, derived from its snowflake ID. */
3044
4032
  get createdAt() {
3045
- return SnowflakeUtil5.dateFromSnowflake(this.id);
4033
+ return SnowflakeUtil7.dateFromSnowflake(this.id);
3046
4034
  }
3047
4035
  /** Delete this sticker. Requires Manage Emojis and Stickers permission. */
3048
- async delete() {
3049
- await this.client.rest.delete(Routes17.guildSticker(this.guildId, this.id), {
3050
- auth: true
4036
+ async delete(reason) {
4037
+ await this.client.rest.delete(Routes18.guildSticker(this.guildId, this.id), {
4038
+ auth: true,
4039
+ ...auditReasonHeaders(reason)
3051
4040
  });
3052
4041
  const guild = this.client.guilds.get(this.guildId);
3053
4042
  if (guild) guild.stickers.delete(this.id);
@@ -3057,9 +4046,11 @@ var GuildSticker = class extends Base {
3057
4046
  * Requires Manage Emojis and Stickers permission.
3058
4047
  */
3059
4048
  async edit(options) {
3060
- const data = await this.client.rest.patch(Routes17.guildSticker(this.guildId, this.id), {
3061
- body: options,
3062
- auth: true
4049
+ const { reason, ...body } = options;
4050
+ const data = await this.client.rest.patch(Routes18.guildSticker(this.guildId, this.id), {
4051
+ body,
4052
+ auth: true,
4053
+ ...auditReasonHeaders(reason)
3063
4054
  });
3064
4055
  const s = data;
3065
4056
  this.name = s.name;
@@ -3069,12 +4060,12 @@ var GuildSticker = class extends Base {
3069
4060
  };
3070
4061
 
3071
4062
  // src/Domain/Guild/Role.ts
3072
- import { Routes as Routes18 } from "@fluxerjs/types";
4063
+ import { Routes as Routes19 } from "@fluxerjs/types";
3073
4064
  import {
3074
4065
  ALL_PERMISSIONS_BIGINT as ALL_PERMISSIONS_BIGINT2,
3075
- PermissionFlags as PermissionFlags3,
3076
- PermissionsBitField as PermissionsBitField2,
3077
- SnowflakeUtil as SnowflakeUtil6
4066
+ PermissionFlags as PermissionFlags4,
4067
+ PermissionsBitField as PermissionsBitField3,
4068
+ SnowflakeUtil as SnowflakeUtil8
3078
4069
  } from "@fluxerjs/util";
3079
4070
  var Role = class _Role extends Base {
3080
4071
  /** Parent client instance. */
@@ -3118,21 +4109,29 @@ var Role = class _Role extends Base {
3118
4109
  */
3119
4110
  get permissions() {
3120
4111
  const bits = BigInt(this._permissions);
3121
- return new PermissionsBitField2(
3122
- (bits & PermissionFlags3.Administrator) !== 0n ? ALL_PERMISSIONS_BIGINT2 : bits
4112
+ return new PermissionsBitField3(
4113
+ (bits & PermissionFlags4.Administrator) !== 0n ? ALL_PERMISSIONS_BIGINT2 : bits
3123
4114
  );
3124
4115
  }
4116
+ /**
4117
+ * Alias of {@link permissions}.has for discord.js-style checks.
4118
+ * @example
4119
+ * if (role.has(PermissionFlags.BanMembers)) { ... }
4120
+ */
4121
+ has(permission) {
4122
+ return this.permissions.has(permission);
4123
+ }
3125
4124
  /**
3126
4125
  * Format as a mention string (`<@&id>`).
3127
4126
  * @returns Mention syntax
3128
4127
  */
3129
4128
  /** Unix timestamp (ms) when this role was created, derived from its snowflake ID. */
3130
4129
  get createdTimestamp() {
3131
- return SnowflakeUtil6.timestampFromSnowflake(this.id);
4130
+ return SnowflakeUtil8.timestampFromSnowflake(this.id);
3132
4131
  }
3133
4132
  /** Date when this role was created, derived from its snowflake ID. */
3134
4133
  get createdAt() {
3135
- return SnowflakeUtil6.dateFromSnowflake(this.id);
4134
+ return SnowflakeUtil8.dateFromSnowflake(this.id);
3136
4135
  }
3137
4136
  toString() {
3138
4137
  return `<@&${this.id}>`;
@@ -3175,19 +4174,24 @@ var Role = class _Role extends Base {
3175
4174
  * @returns This role instance (updated in-place)
3176
4175
  */
3177
4176
  async edit(options) {
3178
- const body = toRoleRequestBody(options);
3179
- const data = await this.client.rest.patch(Routes18.guildRole(this.guildId, this.id), {
4177
+ const body = toRoleEditBody(options);
4178
+ const data = await this.client.rest.patch(Routes19.guildRole(this.guildId, this.id), {
3180
4179
  body: Object.keys(body).length ? body : void 0,
3181
- auth: true
4180
+ auth: true,
4181
+ ...auditReasonHeaders(options.reason)
3182
4182
  });
3183
4183
  this._patch(data);
3184
4184
  return this;
3185
4185
  }
3186
4186
  /**
3187
4187
  * DELETE role. Requires Manage Roles.
4188
+ * @param reason - Audit log reason (`X-Audit-Log-Reason`)
3188
4189
  */
3189
- async delete() {
3190
- await this.client.rest.delete(Routes18.guildRole(this.guildId, this.id), { auth: true });
4190
+ async delete(reason) {
4191
+ await this.client.rest.delete(Routes19.guildRole(this.guildId, this.id), {
4192
+ auth: true,
4193
+ ...auditReasonHeaders(reason)
4194
+ });
3191
4195
  this.client.guilds.get(this.guildId)?.roles.delete(this.id);
3192
4196
  }
3193
4197
  };
@@ -3195,17 +4199,15 @@ var Role = class _Role extends Base {
3195
4199
  // src/Domain/Guild/Cache.ts
3196
4200
  function putChannel(client, channel, guild) {
3197
4201
  client.channels.set(channel.id, channel);
3198
- const resolvedGuild = guild ?? (() => {
3199
- const guildId = "guildId" in channel ? channel.guildId : void 0;
3200
- return guildId ? client.guilds.get(guildId) : void 0;
3201
- })();
4202
+ if (!channel.isGuild()) return;
4203
+ const resolvedGuild = guild ?? (channel.guildId ? client.guilds.get(channel.guildId) : void 0);
3202
4204
  if (resolvedGuild) {
3203
4205
  resolvedGuild.channels.set(channel.id, channel);
3204
4206
  }
3205
4207
  }
3206
4208
  function cacheChannel(guild, data) {
3207
4209
  const existing = guild.channels.get(data.id) ?? guild.client.channels.get(data.id);
3208
- if (existing && "guildId" in existing && existing.type === data.type) {
4210
+ if (existing?.isGuild() && existing.type === data.type) {
3209
4211
  existing._patch(data);
3210
4212
  putChannel(guild.client, existing, guild);
3211
4213
  return existing;
@@ -3319,6 +4321,10 @@ var ChannelManager = class extends LimitedCollection {
3319
4321
  });
3320
4322
  this.client = client;
3321
4323
  }
4324
+ /**
4325
+ * Remove a channel from cache. Does not delete it on the API.
4326
+ * Use {@link Channel.delete} after {@link fetch} to delete the channel.
4327
+ */
3322
4328
  delete(key) {
3323
4329
  const channel = this.get(key);
3324
4330
  const deleted = super.delete(key);
@@ -3332,15 +4338,20 @@ var ChannelManager = class extends LimitedCollection {
3332
4338
  return this.get(channelId) ?? this.fetch(channelId);
3333
4339
  }
3334
4340
  /**
3335
- * Fetch a channel by ID.
3336
- * Returns the cached channel unless `force` is set, in which case REST metadata is applied.
4341
+ * Fetch a channel by ID. The returned {@link Channel} has {@link Channel.delete}
4342
+ * and {@link Channel.send} (send throws if the type is not text-based).
4343
+ * Returns the cached channel unless `force` is set.
4344
+ * @example
4345
+ * const channel = await client.channels.fetch(channelId);
4346
+ * await channel.delete();
4347
+ * await channel.send('hi');
3337
4348
  * @throws {@link FluxerError} with CHANNEL_NOT_FOUND if missing
3338
4349
  */
3339
4350
  async fetch(channelId, options) {
3340
4351
  const cached = this.get(channelId);
3341
4352
  if (cached && !options?.force) return cached;
3342
4353
  try {
3343
- const data = await this.client.rest.get(Routes19.channel(channelId));
4354
+ const data = await this.client.rest.get(Routes20.channel(channelId));
3344
4355
  const guildId = "guild_id" in data ? data.guild_id : void 0;
3345
4356
  if (guildId) {
3346
4357
  const guild = this.client.guilds.get(guildId);
@@ -3376,6 +4387,7 @@ var ChannelManager = class extends LimitedCollection {
3376
4387
  }
3377
4388
  /**
3378
4389
  * Send to a channel by ID without resolving it first.
4390
+ * Prefer {@link Channel.send} after {@link fetch} when you want the channel object.
3379
4391
  * @example
3380
4392
  * await client.channels.send(logChannelId, 'User joined!');
3381
4393
  */
@@ -3384,7 +4396,7 @@ var ChannelManager = class extends LimitedCollection {
3384
4396
  defaultAllowedMentions: this.client.options.defaultAllowedMentions
3385
4397
  });
3386
4398
  const data = await this.client.rest.post(
3387
- Routes19.channelMessages(channelId),
4399
+ Routes20.channelMessages(channelId),
3388
4400
  postPayload
3389
4401
  );
3390
4402
  this.client._addMessageToCache(channelId, data);
@@ -3393,14 +4405,14 @@ var ChannelManager = class extends LimitedCollection {
3393
4405
  };
3394
4406
 
3395
4407
  // src/ClientCore/ClientEmoji.ts
3396
- import { Collection as Collection6 } from "@fluxerjs/collection";
3397
- import { Routes as Routes20 } from "@fluxerjs/types";
3398
- import { formatEmoji, getUnicodeFromShortcode, parseEmoji as parseEmoji2 } from "@fluxerjs/util";
4408
+ import { Collection as Collection8 } from "@fluxerjs/collection";
4409
+ import { Routes as Routes21 } from "@fluxerjs/types";
4410
+ import { formatEmoji, getUnicodeFromShortcode, parseEmoji } from "@fluxerjs/util";
3399
4411
  async function resolveClientEmoji(client, emoji, guildId) {
3400
4412
  if (typeof emoji === "object" && emoji.id) {
3401
4413
  return formatEmoji({ name: emoji.name, id: emoji.id, animated: emoji.animated });
3402
4414
  }
3403
- const parsed = parseEmoji2(
4415
+ const parsed = parseEmoji(
3404
4416
  typeof emoji === "string" ? emoji : emoji.id ? `:${emoji.name}:` : emoji.name
3405
4417
  );
3406
4418
  if (!parsed) {
@@ -3413,7 +4425,7 @@ async function resolveClientEmoji(client, emoji, guildId) {
3413
4425
  const unicodeFromShortcode = getUnicodeFromShortcode(parsed.name);
3414
4426
  if (unicodeFromShortcode) return unicodeFromShortcode;
3415
4427
  if (guildId) {
3416
- const emojis = await client.rest.get(Routes20.guildEmojis(guildId));
4428
+ const emojis = await client.rest.get(Routes21.guildEmojis(guildId));
3417
4429
  const found = emojis.find((e) => e.name && e.name.toLowerCase() === parsed.name.toLowerCase());
3418
4430
  if (found) return formatEmoji({ ...parsed, id: found.id, animated: found.animated });
3419
4431
  throw new FluxerError(
@@ -3430,28 +4442,34 @@ async function resolveClientEmoji(client, emoji, guildId) {
3430
4442
  return parsed.name;
3431
4443
  }
3432
4444
  async function fetchInstance(client) {
3433
- const raw = await client.rest.get(Routes20.instanceDiscovery(), { auth: false });
4445
+ const raw = await client.rest.get(Routes21.instanceDiscovery(), {
4446
+ auth: false,
4447
+ unversioned: true
4448
+ });
3434
4449
  return parseInstanceDiscovery(raw);
3435
4450
  }
3436
4451
  function fetchGatewayInfo(client) {
3437
- return client.rest.get(Routes20.gatewayBot());
4452
+ return client.rest.get(Routes21.gatewayBot());
3438
4453
  }
3439
4454
  function fetchEmojiMetadata(client, emojiId) {
3440
- return client.rest.get(Routes20.emojiMetadata(emojiId), { auth: true });
4455
+ return client.rest.get(Routes21.emojiMetadata(emojiId), { auth: true });
3441
4456
  }
3442
4457
  function fetchStickerMetadata(client, stickerId) {
3443
- return client.rest.get(Routes20.stickerMetadata(stickerId), { auth: true });
4458
+ return client.rest.get(Routes21.stickerMetadata(stickerId), { auth: true });
3444
4459
  }
3445
4460
  function fetchApplication(client) {
3446
- return client.rest.get(Routes20.applicationsMe(), { auth: true });
4461
+ return client.rest.get(Routes21.applicationsMe(), { auth: true });
3447
4462
  }
3448
4463
  async function fetchOAuthApplications(client) {
3449
- const data = await client.rest.get(Routes20.oauth2ApplicationsMe(), { auth: true });
3450
- return Array.isArray(data) ? data : data.applications ?? [];
3451
- }
3452
- function checkUsernameTag(client, username, discriminator) {
3453
- const params = new URLSearchParams({ username, discriminator });
3454
- return client.rest.get(`${Routes20.checkUsernameTag()}?${params}`, { auth: true });
4464
+ const data = await client.rest.get(Routes21.oauth2ApplicationsMe(), { auth: true });
4465
+ if (Array.isArray(data)) return data;
4466
+ if (data && typeof data === "object" && "applications" in data && Array.isArray(data.applications)) {
4467
+ return data.applications;
4468
+ }
4469
+ if (data && typeof data === "object" && "id" in data && typeof data.id === "string") {
4470
+ return [data];
4471
+ }
4472
+ return [];
3455
4473
  }
3456
4474
  function assertChannelIdBatch(name, channelIds) {
3457
4475
  if (channelIds.length < 1 || channelIds.length > 100) {
@@ -3462,14 +4480,14 @@ function assertChannelIdBatch(name, channelIds) {
3462
4480
  }
3463
4481
  function preloadMessages(client, channelIds) {
3464
4482
  assertChannelIdBatch("preloadMessages", channelIds);
3465
- return client.rest.post(Routes20.preloadMessages(), {
4483
+ return client.rest.post(Routes21.preloadMessages(), {
3466
4484
  body: { channels: channelIds },
3467
4485
  auth: true
3468
4486
  });
3469
4487
  }
3470
4488
  function preloadMessagesAlt(client, channelIds) {
3471
4489
  assertChannelIdBatch("preloadMessagesAlt", channelIds);
3472
- return client.rest.post(Routes20.preloadMessagesAlt(), {
4490
+ return client.rest.post(Routes21.preloadMessagesAlt(), {
3473
4491
  body: { channels: channelIds },
3474
4492
  auth: true
3475
4493
  });
@@ -3477,14 +4495,14 @@ function preloadMessagesAlt(client, channelIds) {
3477
4495
  async function bulkFetchMessages(client, requests, options = {}) {
3478
4496
  validateBulkMessageFetchRequests(requests);
3479
4497
  const wire = toBulkFetchWire(requests);
3480
- const data = await client.rest.post(Routes20.channelsMessagesBulk(), {
4498
+ const data = await client.rest.post(Routes21.channelsMessagesBulk(), {
3481
4499
  body: { requests: wire },
3482
4500
  auth: true
3483
4501
  });
3484
4502
  if (options.hydrate === false) return data;
3485
4503
  return {
3486
4504
  channels: data.channels.map((entry) => {
3487
- const collection = new Collection6();
4505
+ const collection = new Collection8();
3488
4506
  for (const msg of entry.messages) {
3489
4507
  client._addMessageToCache(entry.channel_id, msg);
3490
4508
  collection.set(msg.id, new Message(client, msg));
@@ -3493,6 +4511,13 @@ async function bulkFetchMessages(client, requests, options = {}) {
3493
4511
  })
3494
4512
  };
3495
4513
  }
4514
+ async function searchMessages(client, options = {}) {
4515
+ const data = await client.rest.post(Routes21.searchMessages(), {
4516
+ body: toMessageSearchBody(options),
4517
+ auth: true
4518
+ });
4519
+ return toMessageSearchResponse(data);
4520
+ }
3496
4521
 
3497
4522
  // src/ClientCore/ClientEvents.ts
3498
4523
  function createEventMethods(client) {
@@ -3508,16 +4533,16 @@ function createEventMethods(client) {
3508
4533
  }
3509
4534
 
3510
4535
  // src/ClientCore/GatewayReady.ts
3511
- import { WebSocketManager } from "@fluxerjs/ws";
4536
+ import { GatewayCloseCodes, WebSocketManager } from "@fluxerjs/ws";
3512
4537
 
3513
4538
  // src/Domain/Guild/Guild.ts
3514
- import { LimitedCollection as LimitedCollection3 } from "@fluxerjs/collection";
4539
+ import { LimitedCollection as LimitedCollection4 } from "@fluxerjs/collection";
3515
4540
  import { GuildNSFWLevel } from "@fluxerjs/types";
3516
- import { SnowflakeUtil as SnowflakeUtil7 } from "@fluxerjs/util";
4541
+ import { SnowflakeUtil as SnowflakeUtil9 } from "@fluxerjs/util";
3517
4542
 
3518
4543
  // src/ClientCore/GuildMemberManager.ts
3519
4544
  import { LimitedCollection as LimitedCollection2 } from "@fluxerjs/collection";
3520
- import { Routes as Routes21 } from "@fluxerjs/types";
4545
+ import { Routes as Routes22 } from "@fluxerjs/types";
3521
4546
  var GuildMemberManager = class extends LimitedCollection2 {
3522
4547
  constructor(guild) {
3523
4548
  super({ maxSize: guild.client.cache.limits.members });
@@ -3534,7 +4559,7 @@ var GuildMemberManager = class extends LimitedCollection2 {
3534
4559
  * console.log(member.displayName);
3535
4560
  */
3536
4561
  async resolve(userId) {
3537
- return this.get(userId) ?? this.guild.fetchMember(userId);
4562
+ return this.get(userId) ?? this.fetch(userId);
3538
4563
  }
3539
4564
  /**
3540
4565
  * The current bot user as a GuildMember in this guild.
@@ -3561,17 +4586,20 @@ var GuildMemberManager = class extends LimitedCollection2 {
3561
4586
  async fetchMe() {
3562
4587
  return this.guild.fetchMe();
3563
4588
  }
3564
- /**
3565
- * Fetch guild members with pagination. GET /guilds/{id}/members.
3566
- * @param options - limit (1-1000), after (user ID for pagination)
3567
- * @returns Array of GuildMember objects (cached in guild.members)
3568
- */
3569
- async fetch(options) {
4589
+ async fetch(userIdOrOptions, options) {
4590
+ if (typeof userIdOrOptions === "string") {
4591
+ const cached = this.get(userIdOrOptions);
4592
+ if (cached && !options?.force) return cached;
4593
+ return this.guild.fetchMember(userIdOrOptions);
4594
+ }
4595
+ return this.fetchMany(userIdOrOptions);
4596
+ }
4597
+ async fetchMany(options) {
3570
4598
  const params = new URLSearchParams();
3571
4599
  if (options?.limit != null) params.set("limit", String(options.limit));
3572
4600
  if (options?.after) params.set("after", options.after);
3573
4601
  const qs2 = params.toString();
3574
- const url = Routes21.guildMembers(this.guild.id) + (qs2 ? `?${qs2}` : "");
4602
+ const url = Routes22.guildMembers(this.guild.id) + (qs2 ? `?${qs2}` : "");
3575
4603
  const data = await this.guild.client.rest.get(url, { auth: true });
3576
4604
  const members = [];
3577
4605
  for (const m of data) {
@@ -3594,7 +4622,7 @@ var GuildMemberManager = class extends LimitedCollection2 {
3594
4622
  */
3595
4623
  async search(options = {}) {
3596
4624
  const data = await this.guild.client.rest.post(
3597
- Routes21.guildMembersSearch(this.guild.id),
4625
+ Routes22.guildMembersSearch(this.guild.id),
3598
4626
  { body: toMemberSearchBody(options), auth: true }
3599
4627
  );
3600
4628
  const offset = options.offset ?? 0;
@@ -3620,7 +4648,7 @@ var GuildMemberManager = class extends LimitedCollection2 {
3620
4648
  };
3621
4649
 
3622
4650
  // src/Domain/Guild/Admin.ts
3623
- import { Routes as Routes22 } from "@fluxerjs/types";
4651
+ import { Routes as Routes23 } from "@fluxerjs/types";
3624
4652
  function toAuditLogEntryPayload(entry, guildId) {
3625
4653
  return {
3626
4654
  id: entry.id,
@@ -3641,7 +4669,7 @@ function toVanityPayload(data) {
3641
4669
  return { code: data.code ?? null, uses: data.uses };
3642
4670
  }
3643
4671
  async function fetchAuditLogs(guild, options) {
3644
- const url = Routes22.guildAuditLogs(guild.id) + qs({
4672
+ const url = Routes23.guildAuditLogs(guild.id) + qs({
3645
4673
  limit: options?.limit,
3646
4674
  before: options?.before,
3647
4675
  after: options?.after,
@@ -3665,7 +4693,7 @@ async function fetchAuditLogs(guild, options) {
3665
4693
  };
3666
4694
  }
3667
4695
  async function editGuild(guild, options) {
3668
- const data = await guild.client.rest.patch(Routes22.guild(guild.id), {
4696
+ const data = await guild.client.rest.patch(Routes23.guild(guild.id), {
3669
4697
  body: toGuildEditBody(options),
3670
4698
  auth: true
3671
4699
  });
@@ -3673,13 +4701,13 @@ async function editGuild(guild, options) {
3673
4701
  return guild;
3674
4702
  }
3675
4703
  async function fetchVanityURL(guild) {
3676
- const data = await guild.client.rest.get(Routes22.guildVanityUrl(guild.id), {
4704
+ const data = await guild.client.rest.get(Routes23.guildVanityUrl(guild.id), {
3677
4705
  auth: true
3678
4706
  });
3679
4707
  return toVanityPayload(data);
3680
4708
  }
3681
4709
  async function editVanityURL(guild, code) {
3682
- const data = await guild.client.rest.patch(Routes22.guildVanityUrl(guild.id), {
4710
+ const data = await guild.client.rest.patch(Routes23.guildVanityUrl(guild.id), {
3683
4711
  body: { code },
3684
4712
  auth: true
3685
4713
  });
@@ -3687,14 +4715,14 @@ async function editVanityURL(guild, code) {
3687
4715
  return toVanityPayload(data);
3688
4716
  }
3689
4717
  async function fetchDiscoveryStatus(guild) {
3690
- const data = await guild.client.rest.get(Routes22.guildDiscovery(guild.id), {
4718
+ const data = await guild.client.rest.get(Routes23.guildDiscovery(guild.id), {
3691
4719
  auth: true
3692
4720
  });
3693
4721
  return toDiscoveryStatusPayload(data);
3694
4722
  }
3695
4723
  async function applyForDiscovery(guild, options) {
3696
4724
  const data = await guild.client.rest.post(
3697
- Routes22.guildDiscovery(guild.id),
4725
+ Routes23.guildDiscovery(guild.id),
3698
4726
  {
3699
4727
  body: toDiscoveryBody(options),
3700
4728
  auth: true
@@ -3704,7 +4732,7 @@ async function applyForDiscovery(guild, options) {
3704
4732
  }
3705
4733
  async function editDiscoveryApplication(guild, options) {
3706
4734
  const data = await guild.client.rest.patch(
3707
- Routes22.guildDiscovery(guild.id),
4735
+ Routes23.guildDiscovery(guild.id),
3708
4736
  {
3709
4737
  body: toDiscoveryBody(options),
3710
4738
  auth: true
@@ -3713,34 +4741,34 @@ async function editDiscoveryApplication(guild, options) {
3713
4741
  return toDiscoveryApplicationPayload(data);
3714
4742
  }
3715
4743
  async function withdrawDiscoveryApplication(guild) {
3716
- await guild.client.rest.delete(Routes22.guildDiscovery(guild.id), { auth: true });
4744
+ await guild.client.rest.delete(Routes23.guildDiscovery(guild.id), { auth: true });
3717
4745
  }
3718
4746
  async function deleteGuild(guild, options) {
3719
4747
  const body = options ? toSudoBody(options) : {};
3720
- await guild.client.rest.post(Routes22.guildDelete(guild.id), {
4748
+ await guild.client.rest.post(Routes23.guildDelete(guild.id), {
3721
4749
  body,
3722
4750
  auth: true
3723
4751
  });
3724
4752
  guild.client.guilds.delete(guild.id);
3725
4753
  }
3726
4754
  async function transferOwnership(guild, newOwnerId, password) {
3727
- await guild.client.rest.post(Routes22.guildTransferOwnership(guild.id), {
4755
+ await guild.client.rest.post(Routes23.guildTransferOwnership(guild.id), {
3728
4756
  body: { new_owner_id: newOwnerId, ...password != null && { password } },
3729
4757
  auth: true
3730
4758
  });
3731
4759
  }
3732
4760
 
3733
4761
  // src/Domain/Guild/Channels.ts
3734
- import { Routes as Routes23 } from "@fluxerjs/types";
3735
- async function createChannel(guild, data) {
3736
- const created = await guild.client.rest.post(Routes23.guildChannels(guild.id), {
3737
- body: data,
4762
+ import { Routes as Routes24 } from "@fluxerjs/types";
4763
+ async function createChannel(guild, options) {
4764
+ const created = await guild.client.rest.post(Routes24.guildChannels(guild.id), {
4765
+ body: toChannelCreateBody(options),
3738
4766
  auth: true
3739
4767
  });
3740
4768
  return cacheChannel(guild, created);
3741
4769
  }
3742
4770
  async function fetchChannels(guild) {
3743
- const data = await guild.client.rest.get(Routes23.guildChannels(guild.id));
4771
+ const data = await guild.client.rest.get(Routes24.guildChannels(guild.id));
3744
4772
  const channels = [];
3745
4773
  for (const ch of data) {
3746
4774
  const channel = cacheChannel(guild, ch);
@@ -3749,17 +4777,17 @@ async function fetchChannels(guild) {
3749
4777
  return channels;
3750
4778
  }
3751
4779
  async function setChannelPositions(guild, updates) {
3752
- await guild.client.rest.patch(Routes23.guildChannels(guild.id), {
4780
+ await guild.client.rest.patch(Routes24.guildChannels(guild.id), {
3753
4781
  body: toChannelPositionBody(updates),
3754
4782
  auth: true
3755
4783
  });
3756
4784
  }
3757
4785
  async function fetchWebhooks(guild) {
3758
- const data = await guild.client.rest.get(Routes23.guildWebhooks(guild.id));
4786
+ const data = await guild.client.rest.get(Routes24.guildWebhooks(guild.id));
3759
4787
  return data.map((w) => new Webhook(guild.client, w));
3760
4788
  }
3761
4789
  async function fetchInvites(guild) {
3762
- const data = await guild.client.rest.get(Routes23.guildInvites(guild.id));
4790
+ const data = await guild.client.rest.get(Routes24.guildInvites(guild.id));
3763
4791
  return data.map((invite) => new Invite(guild.client, invite));
3764
4792
  }
3765
4793
  async function fetchInvite(guild, codeOrUrl) {
@@ -3779,14 +4807,14 @@ function resolveGuildOnlineCount(data) {
3779
4807
  }
3780
4808
 
3781
4809
  // src/Domain/Guild/Emojis.ts
3782
- import { Routes as Routes24 } from "@fluxerjs/types";
4810
+ import { Routes as Routes25 } from "@fluxerjs/types";
3783
4811
  async function fetchEmojis(guild) {
3784
- const data = await guild.client.rest.get(Routes24.guildEmojis(guild.id));
4812
+ const data = await guild.client.rest.get(Routes25.guildEmojis(guild.id));
3785
4813
  return data.map((e) => cacheEmoji(guild, e));
3786
4814
  }
3787
4815
  async function fetchEmoji(guild, emojiId) {
3788
4816
  try {
3789
- const data = await guild.client.rest.get(Routes24.guildEmoji(guild.id, emojiId));
4817
+ const data = await guild.client.rest.get(Routes25.guildEmoji(guild.id, emojiId));
3790
4818
  return cacheEmoji(guild, data);
3791
4819
  } catch (err) {
3792
4820
  rethrowMapped(err, {
@@ -3796,14 +4824,16 @@ async function fetchEmoji(guild, emojiId) {
3796
4824
  }
3797
4825
  }
3798
4826
  async function createEmoji(guild, options) {
3799
- const data = await guild.client.rest.post(Routes24.guildEmojis(guild.id), {
3800
- body: options,
3801
- auth: true
4827
+ const { reason, ...body } = options;
4828
+ const data = await guild.client.rest.post(Routes25.guildEmojis(guild.id), {
4829
+ body,
4830
+ auth: true,
4831
+ ...auditReasonHeaders(reason)
3802
4832
  });
3803
4833
  return cacheEmoji(guild, data);
3804
4834
  }
3805
4835
  async function cloneEmoji(guild, sourceEmojiId) {
3806
- const data = await guild.client.rest.post(Routes24.guildEmojisClone(guild.id), {
4836
+ const data = await guild.client.rest.post(Routes25.guildEmojisClone(guild.id), {
3807
4837
  body: { source_emoji_id: sourceEmojiId },
3808
4838
  auth: true
3809
4839
  });
@@ -3811,18 +4841,31 @@ async function cloneEmoji(guild, sourceEmojiId) {
3811
4841
  }
3812
4842
  async function createEmojisBulk(guild, emojis) {
3813
4843
  const data = await guild.client.rest.post(
3814
- Routes24.guildEmojisBulk(guild.id),
4844
+ Routes25.guildEmojisBulk(guild.id),
3815
4845
  { body: { emojis }, auth: true }
3816
4846
  );
3817
4847
  return { success: data.success.map((e) => cacheEmoji(guild, e)), failed: data.failed };
3818
4848
  }
3819
4849
 
4850
+ // src/Domain/Guild/GuildRoleManager.ts
4851
+ import { LimitedCollection as LimitedCollection3 } from "@fluxerjs/collection";
4852
+ var GuildRoleManager = class extends LimitedCollection3 {
4853
+ constructor(guildId, options) {
4854
+ super(options);
4855
+ this.guildId = guildId;
4856
+ }
4857
+ /** The @everyone role (`id === guild.id`), or undefined if uncached. */
4858
+ get everyone() {
4859
+ return this.get(this.guildId);
4860
+ }
4861
+ };
4862
+
3820
4863
  // src/Domain/Guild/MemberHttp.ts
3821
- import { Routes as Routes25 } from "@fluxerjs/types";
4864
+ import { Routes as Routes26 } from "@fluxerjs/types";
3822
4865
  async function fetchMember(guild, userId) {
3823
4866
  try {
3824
4867
  const data = await guild.client.rest.get(
3825
- Routes25.guildMember(guild.id, userId)
4868
+ Routes26.guildMember(guild.id, userId)
3826
4869
  );
3827
4870
  return cacheMember(guild, data);
3828
4871
  } catch (err) {
@@ -3837,23 +4880,28 @@ async function fetchMember(guild, userId) {
3837
4880
  }
3838
4881
  async function fetchMe(guild) {
3839
4882
  const data = await guild.client.rest.get(
3840
- Routes25.guildMemberMe(guild.id),
4883
+ Routes26.guildMemberMe(guild.id),
3841
4884
  { auth: true }
3842
4885
  );
3843
4886
  return cacheMember(guild, data);
3844
4887
  }
3845
4888
 
3846
4889
  // src/Domain/Guild/Moderation.ts
3847
- import { Routes as Routes27 } from "@fluxerjs/types";
4890
+ import { Routes as Routes28 } from "@fluxerjs/types";
3848
4891
 
3849
4892
  // src/Domain/Guild/GuildBan.ts
3850
- import { Routes as Routes26 } from "@fluxerjs/types";
4893
+ import { Routes as Routes27 } from "@fluxerjs/types";
4894
+ function parseOptionalDate2(value) {
4895
+ if (value == null || value === "") return null;
4896
+ const date = new Date(value);
4897
+ return Number.isNaN(date.getTime()) ? null : date;
4898
+ }
3851
4899
  var GuildBan = class extends Base {
3852
4900
  client;
3853
4901
  guildId;
3854
4902
  user;
3855
4903
  reason;
3856
- /** ISO timestamp when a temporary ban expires. Null for permanent bans. */
4904
+ /** When a temporary ban expires. Null for permanent bans. */
3857
4905
  expiresAt;
3858
4906
  /** @param data - API ban from GET /guilds/{id}/bans or gateway GUILD_BAN_ADD */
3859
4907
  constructor(client, data, guildId) {
@@ -3862,15 +4910,16 @@ var GuildBan = class extends Base {
3862
4910
  this.guildId = data.guild_id ?? guildId;
3863
4911
  this.user = client.getOrCreateUser(data.user);
3864
4912
  this.reason = data.reason ?? null;
3865
- this.expiresAt = data.expires_at ?? null;
4913
+ this.expiresAt = parseOptionalDate2(data.expires_at);
3866
4914
  }
3867
4915
  /**
3868
4916
  * Remove this ban (unban the user).
3869
4917
  * Requires Ban Members permission.
3870
4918
  */
3871
- async unban() {
3872
- await this.client.rest.delete(Routes26.guildBan(this.guildId, this.user.id), {
3873
- auth: true
4919
+ async unban(reason) {
4920
+ await this.client.rest.delete(Routes27.guildBan(this.guildId, this.user.id), {
4921
+ auth: true,
4922
+ ...auditReasonHeaders(reason)
3874
4923
  });
3875
4924
  }
3876
4925
  };
@@ -3878,40 +4927,48 @@ var GuildBan = class extends Base {
3878
4927
  // src/Domain/Guild/Moderation.ts
3879
4928
  async function ban(guild, userId, options) {
3880
4929
  const body = options ? toGuildBanBody(options) : {};
3881
- await guild.client.rest.put(Routes27.guildBan(guild.id, userId), {
4930
+ await guild.client.rest.put(Routes28.guildBan(guild.id, userId), {
3882
4931
  body: Object.keys(body).length ? body : void 0,
3883
- auth: true
4932
+ auth: true,
4933
+ ...auditReasonHeaders(options?.reason)
3884
4934
  });
3885
4935
  }
3886
4936
  async function fetchBans(guild) {
3887
- const data = await guild.client.rest.get(Routes27.guildBans(guild.id));
4937
+ const data = await guild.client.rest.get(Routes28.guildBans(guild.id));
3888
4938
  return data.map((b) => new GuildBan(guild.client, { ...b, guild_id: guild.id }, guild.id));
3889
4939
  }
3890
- async function unban(guild, userId) {
3891
- await guild.client.rest.delete(Routes27.guildBan(guild.id, userId), { auth: true });
4940
+ async function unban(guild, userId, reason) {
4941
+ await guild.client.rest.delete(Routes28.guildBan(guild.id, userId), {
4942
+ auth: true,
4943
+ ...auditReasonHeaders(reason)
4944
+ });
3892
4945
  }
3893
- async function kick(guild, userId) {
3894
- await guild.client.rest.delete(Routes27.guildMember(guild.id, userId), { auth: true });
4946
+ async function kick(guild, userId, reason) {
4947
+ await guild.client.rest.delete(Routes28.guildMember(guild.id, userId), {
4948
+ auth: true,
4949
+ ...auditReasonHeaders(reason)
4950
+ });
3895
4951
  }
3896
4952
 
3897
4953
  // src/Domain/Guild/Roles.ts
3898
- import { Routes as Routes28 } from "@fluxerjs/types";
4954
+ import { Routes as Routes29 } from "@fluxerjs/types";
3899
4955
  import { parseRoleMention } from "@fluxerjs/util";
3900
4956
  async function createRole(guild, options = {}) {
3901
- const body = toRoleRequestBody(options);
3902
- const data = await guild.client.rest.post(Routes28.guildRoles(guild.id), {
4957
+ const body = toRoleCreateBody(options);
4958
+ const data = await guild.client.rest.post(Routes29.guildRoles(guild.id), {
3903
4959
  body: Object.keys(body).length ? body : void 0,
3904
- auth: true
4960
+ auth: true,
4961
+ ...auditReasonHeaders(options.reason)
3905
4962
  });
3906
4963
  return cacheRole(guild, data);
3907
4964
  }
3908
4965
  async function fetchRoles(guild) {
3909
- const data = await guild.client.rest.get(Routes28.guildRoles(guild.id));
4966
+ const data = await guild.client.rest.get(Routes29.guildRoles(guild.id));
3910
4967
  return data.map((r) => cacheRole(guild, r));
3911
4968
  }
3912
4969
  async function fetchRole(guild, roleId2) {
3913
4970
  try {
3914
- const data = await guild.client.rest.get(Routes28.guildRole(guild.id, roleId2));
4971
+ const data = await guild.client.rest.get(Routes29.guildRole(guild.id, roleId2));
3915
4972
  return cacheRole(guild, data);
3916
4973
  } catch (err) {
3917
4974
  rethrowMapped(err, {
@@ -3928,7 +4985,7 @@ async function resolveRoleId(guild, arg) {
3928
4985
  const needle = trimmed.toLowerCase();
3929
4986
  const cached = guild.roles.find((r) => r.name?.toLowerCase() === needle);
3930
4987
  if (cached) return cached.id;
3931
- const roles = await guild.client.rest.get(Routes28.guildRoles(guild.id));
4988
+ const roles = await guild.client.rest.get(Routes29.guildRoles(guild.id));
3932
4989
  const role = roles.find((r) => r.name?.toLowerCase() === needle);
3933
4990
  if (!role) return null;
3934
4991
  cacheRole(guild, role);
@@ -3937,7 +4994,7 @@ async function resolveRoleId(guild, arg) {
3937
4994
  async function setRolePositions(guild, updates) {
3938
4995
  return replaceRoles(
3939
4996
  guild,
3940
- await guild.client.rest.patch(Routes28.guildRoles(guild.id), {
4997
+ await guild.client.rest.patch(Routes29.guildRoles(guild.id), {
3941
4998
  body: updates,
3942
4999
  auth: true
3943
5000
  })
@@ -3946,7 +5003,7 @@ async function setRolePositions(guild, updates) {
3946
5003
  async function setRoleHoistPositions(guild, updates) {
3947
5004
  return replaceRoles(
3948
5005
  guild,
3949
- await guild.client.rest.patch(Routes28.guildRolesHoistPositions(guild.id), {
5006
+ await guild.client.rest.patch(Routes29.guildRolesHoistPositions(guild.id), {
3950
5007
  body: updates.map((u) => ({
3951
5008
  id: u.id,
3952
5009
  ...u.hoistPosition !== void 0 ? { hoist_position: u.hoistPosition } : {}
@@ -3958,23 +5015,25 @@ async function setRoleHoistPositions(guild, updates) {
3958
5015
  async function resetRoleHoistPositions(guild) {
3959
5016
  return replaceRoles(
3960
5017
  guild,
3961
- await guild.client.rest.delete(Routes28.guildRolesHoistPositions(guild.id), {
5018
+ await guild.client.rest.delete(Routes29.guildRolesHoistPositions(guild.id), {
3962
5019
  auth: true
3963
5020
  })
3964
5021
  );
3965
5022
  }
3966
5023
 
3967
5024
  // src/Domain/Guild/Stickers.ts
3968
- import { Routes as Routes29 } from "@fluxerjs/types";
5025
+ import { Routes as Routes30 } from "@fluxerjs/types";
3969
5026
  async function createSticker(guild, options) {
3970
- const data = await guild.client.rest.post(Routes29.guildStickers(guild.id), {
3971
- body: options,
3972
- auth: true
5027
+ const { reason, ...body } = options;
5028
+ const data = await guild.client.rest.post(Routes30.guildStickers(guild.id), {
5029
+ body,
5030
+ auth: true,
5031
+ ...auditReasonHeaders(reason)
3973
5032
  });
3974
5033
  return cacheSticker(guild, data);
3975
5034
  }
3976
5035
  async function cloneSticker(guild, sourceStickerId) {
3977
- const data = await guild.client.rest.post(Routes29.guildStickersClone(guild.id), {
5036
+ const data = await guild.client.rest.post(Routes30.guildStickersClone(guild.id), {
3978
5037
  body: { source_sticker_id: sourceStickerId },
3979
5038
  auth: true
3980
5039
  });
@@ -3982,17 +5041,17 @@ async function cloneSticker(guild, sourceStickerId) {
3982
5041
  }
3983
5042
  async function createStickersBulk(guild, stickers) {
3984
5043
  const data = await guild.client.rest.post(
3985
- Routes29.guildStickersBulk(guild.id),
5044
+ Routes30.guildStickersBulk(guild.id),
3986
5045
  { body: { stickers }, auth: true }
3987
5046
  );
3988
5047
  return { success: data.success.map((s) => cacheSticker(guild, s)), failed: data.failed };
3989
5048
  }
3990
5049
  async function fetchStickers(guild) {
3991
- const data = await guild.client.rest.get(Routes29.guildStickers(guild.id));
5050
+ const data = await guild.client.rest.get(Routes30.guildStickers(guild.id));
3992
5051
  return data.map((s) => cacheSticker(guild, s));
3993
5052
  }
3994
5053
  async function fetchSticker(guild, stickerId) {
3995
- const data = await guild.client.rest.get(Routes29.guildSticker(guild.id, stickerId));
5054
+ const data = await guild.client.rest.get(Routes30.guildSticker(guild.id, stickerId));
3996
5055
  return cacheSticker(guild, data);
3997
5056
  }
3998
5057
 
@@ -4032,8 +5091,26 @@ var Guild = class extends Base {
4032
5091
  systemChannelId;
4033
5092
  /** Rules channel ID (for Community guilds), or null if none. */
4034
5093
  rulesChannelId;
5094
+ /** {@link SystemChannelFlags} bitfield. */
5095
+ systemChannelFlags;
5096
+ /** Splash card alignment. */
5097
+ splashCardAlignment;
5098
+ /** Embed splash hash. */
5099
+ embedSplash;
4035
5100
  /** NSFW level for this guild. */
4036
5101
  nsfwLevel;
5102
+ /** Whether the guild is marked as adult (18+) content. */
5103
+ nsfw;
5104
+ /** Content warning level. */
5105
+ contentWarningLevel;
5106
+ /** Custom guild-wide content warning text. */
5107
+ contentWarningText;
5108
+ /** {@link GuildOperations} bitfield of disabled operations. */
5109
+ disabledOperations;
5110
+ /** ISO-8601 timestamp before which message history is not available. */
5111
+ messageHistoryCutoff;
5112
+ /** Permissions for the current member in this guild (bitfield string). */
5113
+ permissions;
4037
5114
  /** MFA level required for moderation actions. */
4038
5115
  mfaLevel;
4039
5116
  /** Banner width in pixels. */
@@ -4067,13 +5144,13 @@ var Guild = class extends Base {
4067
5144
  this.client = client;
4068
5145
  this.id = data.id;
4069
5146
  this.members = new GuildMemberManager(this);
4070
- this.channels = new LimitedCollection3({
5147
+ this.channels = new LimitedCollection4({
4071
5148
  maxSize: Number.POSITIVE_INFINITY,
4072
5149
  onEvict: (_id, channel) => client.cache.cascadeChannel(channel, "guild")
4073
5150
  });
4074
- this.roles = new LimitedCollection3({ maxSize: client.cache.limits.roles });
4075
- this.emojis = new LimitedCollection3({ maxSize: client.cache.limits.emojis });
4076
- this.stickers = new LimitedCollection3({ maxSize: client.cache.limits.stickers });
5151
+ this.roles = new GuildRoleManager(this.id, { maxSize: client.cache.limits.roles });
5152
+ this.emojis = new LimitedCollection4({ maxSize: client.cache.limits.emojis });
5153
+ this.stickers = new LimitedCollection4({ maxSize: client.cache.limits.stickers });
4077
5154
  this.name = data.name ?? "";
4078
5155
  this.icon = data.icon ?? null;
4079
5156
  this.banner = data.banner ?? null;
@@ -4088,7 +5165,16 @@ var Guild = class extends Base {
4088
5165
  this.afkTimeout = data.afk_timeout ?? 0;
4089
5166
  this.systemChannelId = data.system_channel_id ?? null;
4090
5167
  this.rulesChannelId = data.rules_channel_id ?? null;
5168
+ this.systemChannelFlags = data.system_channel_flags ?? 0;
5169
+ this.splashCardAlignment = data.splash_card_alignment ?? 0;
5170
+ this.embedSplash = data.embed_splash ?? null;
4091
5171
  this.nsfwLevel = data.nsfw_level ?? GuildNSFWLevel.Safe;
5172
+ this.nsfw = data.nsfw ?? false;
5173
+ this.contentWarningLevel = data.content_warning_level ?? 0;
5174
+ this.contentWarningText = data.content_warning_text ?? null;
5175
+ this.disabledOperations = data.disabled_operations ?? 0;
5176
+ this.messageHistoryCutoff = data.message_history_cutoff ?? null;
5177
+ this.permissions = data.permissions ?? null;
4092
5178
  this.mfaLevel = data.mfa_level ?? 0;
4093
5179
  this.bannerWidth = data.banner_width ?? null;
4094
5180
  this.bannerHeight = data.banner_height ?? null;
@@ -4123,7 +5209,28 @@ var Guild = class extends Base {
4123
5209
  if (data.afk_timeout !== void 0) this.afkTimeout = data.afk_timeout ?? 0;
4124
5210
  if (data.system_channel_id !== void 0) this.systemChannelId = data.system_channel_id ?? null;
4125
5211
  if (data.rules_channel_id !== void 0) this.rulesChannelId = data.rules_channel_id ?? null;
5212
+ if (data.system_channel_flags !== void 0) {
5213
+ this.systemChannelFlags = data.system_channel_flags ?? 0;
5214
+ }
5215
+ if (data.splash_card_alignment !== void 0) {
5216
+ this.splashCardAlignment = data.splash_card_alignment ?? 0;
5217
+ }
5218
+ if (data.embed_splash !== void 0) this.embedSplash = data.embed_splash ?? null;
4126
5219
  if (data.nsfw_level !== void 0) this.nsfwLevel = data.nsfw_level ?? GuildNSFWLevel.Safe;
5220
+ if (data.nsfw !== void 0) this.nsfw = data.nsfw ?? false;
5221
+ if (data.content_warning_level !== void 0) {
5222
+ this.contentWarningLevel = data.content_warning_level ?? 0;
5223
+ }
5224
+ if (data.content_warning_text !== void 0) {
5225
+ this.contentWarningText = data.content_warning_text ?? null;
5226
+ }
5227
+ if (data.disabled_operations !== void 0) {
5228
+ this.disabledOperations = data.disabled_operations ?? 0;
5229
+ }
5230
+ if (data.message_history_cutoff !== void 0) {
5231
+ this.messageHistoryCutoff = data.message_history_cutoff ?? null;
5232
+ }
5233
+ if (data.permissions !== void 0) this.permissions = data.permissions ?? null;
4127
5234
  if (data.mfa_level !== void 0) this.mfaLevel = data.mfa_level ?? 0;
4128
5235
  if (data.banner_width !== void 0) this.bannerWidth = data.banner_width ?? null;
4129
5236
  if (data.banner_height !== void 0) this.bannerHeight = data.banner_height ?? null;
@@ -4144,11 +5251,11 @@ var Guild = class extends Base {
4144
5251
  }
4145
5252
  /** Unix timestamp (ms) when this guild was created, derived from its snowflake ID. */
4146
5253
  get createdTimestamp() {
4147
- return SnowflakeUtil7.timestampFromSnowflake(this.id);
5254
+ return SnowflakeUtil9.timestampFromSnowflake(this.id);
4148
5255
  }
4149
5256
  /** Date when this guild was created, derived from its snowflake ID. */
4150
5257
  get createdAt() {
4151
- return SnowflakeUtil7.dateFromSnowflake(this.id);
5258
+ return SnowflakeUtil9.dateFromSnowflake(this.id);
4152
5259
  }
4153
5260
  /** The guild's name. */
4154
5261
  toString() {
@@ -4176,11 +5283,11 @@ var Guild = class extends Base {
4176
5283
  });
4177
5284
  }
4178
5285
  /**
4179
- * Create a channel. `data.type`: 0=text, 2=voice, 4=category, 998=link (set `url`).
5286
+ * Create a channel. `type`: 0=text, 2=voice, 4=category, 998=link (set `url`).
4180
5287
  * Requires Manage Channels.
4181
5288
  */
4182
- createChannel(data) {
4183
- return createChannel(this, data);
5289
+ createChannel(options) {
5290
+ return createChannel(this, options);
4184
5291
  }
4185
5292
  /** Fetch all channels in this guild from the API. */
4186
5293
  fetchChannels() {
@@ -4242,7 +5349,7 @@ var Guild = class extends Base {
4242
5349
  resetRoleHoistPositions() {
4243
5350
  return resetRoleHoistPositions(this);
4244
5351
  }
4245
- /** Ban a user from the guild. Requires Ban Members. `ban_duration_seconds`: 0 = permanent. */
5352
+ /** Ban a user from the guild. Requires Ban Members. `banDurationSeconds`: 0 = permanent. */
4246
5353
  ban(userId, options) {
4247
5354
  return ban(this, userId, options);
4248
5355
  }
@@ -4251,12 +5358,12 @@ var Guild = class extends Base {
4251
5358
  return fetchBans(this);
4252
5359
  }
4253
5360
  /** Unban a user from the guild. Requires Ban Members. */
4254
- unban(userId) {
4255
- return unban(this, userId);
5361
+ unban(userId, reason) {
5362
+ return unban(this, userId, reason);
4256
5363
  }
4257
5364
  /** Kick a user from the guild. Requires Kick Members. */
4258
- kick(userId) {
4259
- return kick(this, userId);
5365
+ kick(userId, reason) {
5366
+ return kick(this, userId, reason);
4260
5367
  }
4261
5368
  /** Fetch all emojis in this guild from the API. */
4262
5369
  fetchEmojis() {
@@ -4442,23 +5549,23 @@ function applyGuildSnapshotFromGateway(client, raw) {
4442
5549
  }
4443
5550
 
4444
5551
  // src/ClientCore/ClientUser.ts
4445
- import { GatewayOpcodes, Routes as Routes30 } from "@fluxerjs/types";
5552
+ import { GatewayOpcodes, Routes as Routes31 } from "@fluxerjs/types";
4446
5553
  var ClientUser = class extends User {
4447
5554
  /** Broadcast presence (gateway opcode 3) on all shards. */
4448
5555
  setPresence(presence) {
5556
+ this.client.options.presence = presence;
4449
5557
  const wire = toPresenceWire(presence);
4450
- this.client.options.presence = wire;
4451
5558
  this.client._sendToAllShards({ op: GatewayOpcodes.PresenceUpdate, d: wire });
4452
5559
  }
4453
5560
  /** GET /users/@me — refresh the logged-in user from REST and patch this instance. */
4454
5561
  async fetch() {
4455
- const data = await this.client.rest.get(Routes30.currentUser(), { auth: true });
5562
+ const data = await this.client.rest.get(Routes31.currentUser(), { auth: true });
4456
5563
  this._patch(data);
4457
5564
  return this;
4458
5565
  }
4459
5566
  /** GET /users/@me/guilds — returns camelCase partial guilds. */
4460
5567
  async fetchGuilds(options) {
4461
- const path = Routes30.currentUserGuilds() + (options?.withCounts ? "?with_counts=true" : "");
5568
+ const path = Routes31.currentUserGuilds() + (options?.withCounts ? "?with_counts=true" : "");
4462
5569
  const data = await this.client.rest.get(path, { auth: true });
4463
5570
  return data.map((g) => ({
4464
5571
  id: g.id,
@@ -4471,10 +5578,18 @@ var ClientUser = class extends User {
4471
5578
  ...g.approximate_presence_count !== void 0 ? { approximatePresenceCount: g.approximate_presence_count } : {}
4472
5579
  }));
4473
5580
  }
4474
- /** DELETE /users/@me/guilds/{guild_id} */
5581
+ /**
5582
+ * Leave a guild (`client.user.leaveGuild`).
5583
+ * DELETE /users/@me/guilds/{guild_id}.
5584
+ *
5585
+ * @param guildId - Guild to leave
5586
+ * @param options - Optional sudo / MFA body for user accounts
5587
+ * @example
5588
+ * await client.user.leaveGuild(guildId);
5589
+ */
4475
5590
  async leaveGuild(guildId, options) {
4476
5591
  const body = options ? toSudoBody(options) : void 0;
4477
- await this.client.rest.delete(Routes30.leaveGuild(guildId), {
5592
+ await this.client.rest.delete(Routes31.leaveGuild(guildId), {
4478
5593
  body: body && Object.keys(body).length ? body : void 0,
4479
5594
  auth: true
4480
5595
  });
@@ -4482,7 +5597,7 @@ var ClientUser = class extends User {
4482
5597
  /** Delete every message authored by the caller across a guild (sudo). */
4483
5598
  async bulkDeleteMyMessagesInGuild(guildId, options) {
4484
5599
  const body = options ? toSudoBody(options) : void 0;
4485
- await this.client.rest.post(Routes30.guildBulkDeleteMine(guildId), {
5600
+ await this.client.rest.post(Routes31.guildBulkDeleteMine(guildId), {
4486
5601
  body: body && Object.keys(body).length ? body : void 0,
4487
5602
  auth: true
4488
5603
  });
@@ -4649,7 +5764,7 @@ var guildResourceHandlers = {
4649
5764
  role = new Role(client, data.role, data.guild_id);
4650
5765
  guild?.roles.set(role.id, role);
4651
5766
  }
4652
- client.emit(Events.GuildRoleUpdate, { role, oldRole });
5767
+ client.emit(Events.GuildRoleUpdate, oldRole, role);
4653
5768
  },
4654
5769
  GUILD_ROLE_UPDATE_BULK(client, d) {
4655
5770
  const data = d;
@@ -4665,11 +5780,7 @@ var guildResourceHandlers = {
4665
5780
  const guild = client.guilds.get(data.guild_id);
4666
5781
  const role = guild?.roles.get(data.role_id) ?? null;
4667
5782
  guild?.roles.delete(data.role_id);
4668
- client.emit(Events.GuildRoleDelete, {
4669
- roleId: data.role_id,
4670
- guildId: data.guild_id,
4671
- role
4672
- });
5783
+ client.emit(Events.GuildRoleDelete, role, data.guild_id, data.role_id);
4673
5784
  },
4674
5785
  GUILD_BAN_ADD(client, d) {
4675
5786
  const data = d;
@@ -4702,7 +5813,14 @@ function markGuildUnavailable(client, id) {
4702
5813
  guild.available = false;
4703
5814
  client.emit(Events.GuildUnavailable, guild);
4704
5815
  }
5816
+ function isStartupGuildHydration(client) {
5817
+ return client._guildStreamSettleTimeout !== null;
5818
+ }
4705
5819
  var guildHandlers = {
5820
+ /**
5821
+ * Available snapshots: {@link Events.GuildAvailable} for READY stubs / outage recovery,
5822
+ * {@link Events.GuildCreate} for real joins (unless {@link ClientOptions.emitGuildCreateOnStartup}).
5823
+ */
4706
5824
  GUILD_CREATE(client, d) {
4707
5825
  const raw = d;
4708
5826
  if (raw.unavailable === true) {
@@ -4715,11 +5833,32 @@ var guildHandlers = {
4715
5833
  }
4716
5834
  return;
4717
5835
  }
5836
+ const startupHydration = isStartupGuildHydration(client);
5837
+ if (startupHydration) {
5838
+ resetGuildStreamSettle(client);
5839
+ }
4718
5840
  const result = applyGuildSnapshotFromGateway(client, d);
4719
5841
  if (!result) return;
4720
5842
  const { guild, recovered } = result;
4721
- if (recovered) guild.available = true;
4722
- client.emit(recovered ? Events.GuildAvailable : Events.GuildCreate, guild);
5843
+ const legacyStartup = client.options.emitGuildCreateOnStartup === true;
5844
+ const wasReadyStub = client._readyStubGuildIds.delete(guild.id);
5845
+ const isStartupBackfill = wasReadyStub || startupHydration;
5846
+ if (recovered) {
5847
+ guild.available = true;
5848
+ if (legacyStartup && isStartupBackfill) {
5849
+ client.emit(Events.GuildCreate, guild);
5850
+ } else {
5851
+ client.emit(Events.GuildAvailable, guild);
5852
+ }
5853
+ } else if (startupHydration) {
5854
+ if (legacyStartup) {
5855
+ client.emit(Events.GuildCreate, guild);
5856
+ } else {
5857
+ client.emit(Events.GuildAvailable, guild);
5858
+ }
5859
+ } else {
5860
+ client.emit(Events.GuildCreate, guild);
5861
+ }
4723
5862
  client._onGuildReceived(guild.id);
4724
5863
  },
4725
5864
  GUILD_UPDATE(client, d) {
@@ -4758,6 +5897,7 @@ var guildHandlers = {
4758
5897
  markGuildUnavailable(client, id);
4759
5898
  return;
4760
5899
  }
5900
+ client._readyStubGuildIds.delete(id);
4761
5901
  const guild = client.guilds.get(id);
4762
5902
  if (!guild) return;
4763
5903
  client.guilds.delete(id);
@@ -4778,7 +5918,7 @@ function normalizeInviteCreate(client, payload) {
4778
5918
  const code = str(raw?.code);
4779
5919
  if (!raw || !code) return null;
4780
5920
  const typeNum = num(raw.type);
4781
- const type = typeNum === InviteType2.GroupDM || typeNum === InviteType2.EmojiPack || typeNum === InviteType2.StickerPack ? typeNum : InviteType2.Guild;
5921
+ const type = typeNum === InviteType2.GroupDM ? InviteType2.GroupDM : InviteType2.Guild;
4782
5922
  const shared = {
4783
5923
  code,
4784
5924
  inviter: raw.inviter ?? null,
@@ -4790,11 +5930,6 @@ function normalizeInviteCreate(client, payload) {
4790
5930
  max_uses: num(raw.max_uses),
4791
5931
  max_age: num(raw.max_age)
4792
5932
  };
4793
- if (type === InviteType2.EmojiPack || type === InviteType2.StickerPack) {
4794
- const pack = asRecord(raw.pack);
4795
- if (!pack || !str(pack.id) || !str(pack.name)) return null;
4796
- return { ...shared, type, pack };
4797
- }
4798
5933
  const guildObj = asRecord(raw.guild);
4799
5934
  const channelObj = asRecord(raw.channel);
4800
5935
  const guildId = str(guildObj?.id) ?? str(raw.guild_id) ?? "0";
@@ -4846,6 +5981,30 @@ var inviteHandlers = {
4846
5981
  }
4847
5982
  };
4848
5983
 
5984
+ // src/Domain/Guild/PartialGuildMember.ts
5985
+ var PartialGuildMember = class {
5986
+ partial = true;
5987
+ client;
5988
+ id;
5989
+ user;
5990
+ guildId;
5991
+ guild;
5992
+ constructor(data) {
5993
+ this.client = data.client;
5994
+ this.id = data.id;
5995
+ this.user = data.user;
5996
+ this.guild = data.guild;
5997
+ this.guildId = data.guild.id;
5998
+ }
5999
+ /**
6000
+ * Fetch the full {@link GuildMember} from the API (cache-aware via `guild.members.fetch`).
6001
+ * @throws FluxerError with MEMBER_NOT_FOUND if the user is not in the guild
6002
+ */
6003
+ async fetch() {
6004
+ return this.guild.members.fetch(this.id);
6005
+ }
6006
+ };
6007
+
4849
6008
  // src/ClientCore/EventHandlers/Members.ts
4850
6009
  var memberHandlers = {
4851
6010
  GUILD_MEMBER_ADD(client, d) {
@@ -4872,28 +6031,15 @@ var memberHandlers = {
4872
6031
  const data = d;
4873
6032
  const guild = client.guilds.get(data.guild_id);
4874
6033
  if (!guild || !data.user?.id) return;
4875
- let member = guild.members.get(data.user.id);
4876
- if (member) {
4877
- guild.members.delete(data.user.id);
4878
- } else {
4879
- member = new GuildMember(
4880
- client,
4881
- {
4882
- user: {
4883
- ...unknownUser(data.user.id),
4884
- ...data.user,
4885
- username: data.user.username ?? "Unknown",
4886
- discriminator: data.user.discriminator ?? "0"
4887
- },
4888
- roles: [],
4889
- joined_at: (/* @__PURE__ */ new Date(0)).toISOString(),
4890
- nick: null,
4891
- mute: false,
4892
- deaf: false
4893
- },
4894
- guild
4895
- );
4896
- }
6034
+ const cached = guild.members.get(data.user.id);
6035
+ if (cached) guild.members.delete(data.user.id);
6036
+ const user = client.getOrCreateUser(data.user);
6037
+ const member = cached ?? new PartialGuildMember({
6038
+ client,
6039
+ id: data.user.id,
6040
+ user,
6041
+ guild
6042
+ });
4897
6043
  guild.adjustMemberCount(-1);
4898
6044
  client.emit(Events.GuildMemberRemove, member);
4899
6045
  },
@@ -4912,7 +6058,7 @@ var memberHandlers = {
4912
6058
  members,
4913
6059
  chunkIndex: data.chunk_index,
4914
6060
  chunkCount: data.chunk_count,
4915
- notFound: [],
6061
+ notFound: data.not_found ?? [],
4916
6062
  nonce: data.nonce ?? null
4917
6063
  };
4918
6064
  client.emit(Events.GuildMembersChunk, payload);
@@ -4920,7 +6066,35 @@ var memberHandlers = {
4920
6066
  };
4921
6067
 
4922
6068
  // src/ClientCore/EventHandlers/Messages.ts
4923
- function toReactionEmoji2(emoji) {
6069
+ import { SnowflakeUtil as SnowflakeUtil10 } from "@fluxerjs/util";
6070
+ function cachedTextChannel(client, channelId) {
6071
+ const channel = client.channels.get(channelId);
6072
+ return channel?.isTextBased() ? channel : null;
6073
+ }
6074
+ function cachedMessage(client, channelId, messageId) {
6075
+ const data = client._getMessageCache(channelId)?.get(messageId);
6076
+ return data ? new Message(client, data) : null;
6077
+ }
6078
+ function isHydratableMessage(data) {
6079
+ return Boolean(data.author?.id && data.timestamp);
6080
+ }
6081
+ function toPartialMessage(client, args) {
6082
+ const cached = args.cached;
6083
+ const authorId = args.authorId ?? cached?.author?.id ?? null;
6084
+ const author = cached?.author ? client.getOrCreateUser(cached.author) : authorId ? client.users.get(authorId) ?? null : null;
6085
+ const createdAt = cached?.timestamp ? new Date(cached.timestamp) : SnowflakeUtil10.isValid(args.id) ? SnowflakeUtil10.dateFromSnowflake(args.id) : null;
6086
+ return new PartialMessage(client, {
6087
+ id: args.id,
6088
+ channelId: args.channelId,
6089
+ guildId: args.guildId ?? cached?.guild_id ?? null,
6090
+ channel: cachedTextChannel(client, args.channelId),
6091
+ content: args.content ?? cached?.content ?? null,
6092
+ authorId,
6093
+ author,
6094
+ createdAt
6095
+ });
6096
+ }
6097
+ function toReactionEmoji(emoji) {
4924
6098
  return {
4925
6099
  name: emoji.name,
4926
6100
  ...emoji.id !== void 0 ? { id: emoji.id } : {},
@@ -4937,9 +6111,12 @@ function emitReaction(event) {
4937
6111
  const payload = {
4938
6112
  reaction,
4939
6113
  user,
6114
+ message: cachedMessage(client, data.channel_id, data.message_id),
6115
+ channel: cachedTextChannel(client, data.channel_id),
6116
+ member,
4940
6117
  messageId: data.message_id,
4941
6118
  channelId: data.channel_id,
4942
- emoji: toReactionEmoji2(data.emoji),
6119
+ emoji: toReactionEmoji(data.emoji),
4943
6120
  userId: data.user_id
4944
6121
  };
4945
6122
  client.emit(event, payload);
@@ -4959,37 +6136,60 @@ var messageHandlers = {
4959
6136
  },
4960
6137
  MESSAGE_UPDATE(client, d) {
4961
6138
  const partial = d;
4962
- const cache = client._getMessageCache(partial.channel_id);
4963
- let oldMessage = null;
4964
- let mergedData = partial;
4965
- if (cache) {
4966
- const oldData = cache.get(partial.id);
4967
- if (oldData) {
4968
- oldMessage = new Message(client, oldData);
4969
- mergedData = { ...oldData, ...partial };
4970
- }
6139
+ const oldData = client._getMessageCache(partial.channel_id)?.get(partial.id);
6140
+ const oldMessage = oldData ? new Message(client, oldData) : null;
6141
+ const mergedData = oldData ? { ...oldData, ...partial } : partial;
6142
+ if (isHydratableMessage(mergedData)) {
6143
+ client._addMessageToCache(partial.channel_id, mergedData);
6144
+ client.emit(Events.MessageUpdate, oldMessage, new Message(client, mergedData));
6145
+ return;
4971
6146
  }
4972
- client._addMessageToCache(partial.channel_id, mergedData);
4973
- client.emit(Events.MessageUpdate, oldMessage, new Message(client, mergedData));
6147
+ client.emit(
6148
+ Events.MessageUpdate,
6149
+ oldMessage,
6150
+ toPartialMessage(client, {
6151
+ id: partial.id,
6152
+ channelId: partial.channel_id,
6153
+ guildId: partial.guild_id ?? oldData?.guild_id ?? null,
6154
+ content: partial.content ?? oldData?.content ?? null,
6155
+ authorId: partial.author?.id ?? oldData?.author?.id ?? null,
6156
+ cached: oldData
6157
+ })
6158
+ );
4974
6159
  },
4975
6160
  MESSAGE_DELETE(client, d) {
4976
6161
  const data = d;
4977
- client._removeMessageFromCache(data.channel_id, data.id);
4978
- client.emit(Events.MessageDelete, {
6162
+ const cached = client._getMessageCache(data.channel_id)?.get(data.id);
6163
+ const payload = toPartialMessage(client, {
4979
6164
  id: data.id,
4980
6165
  channelId: data.channel_id,
4981
- channel: client.channels.get(data.channel_id) ?? null,
4982
- content: data.content ?? null,
4983
- authorId: data.author_id ?? null
6166
+ guildId: data.guild_id ?? cached?.guild_id ?? null,
6167
+ content: data.content ?? cached?.content ?? null,
6168
+ authorId: data.author_id ?? cached?.author?.id ?? null,
6169
+ cached
4984
6170
  });
6171
+ client._removeMessageFromCache(data.channel_id, data.id);
6172
+ client.emit(Events.MessageDelete, payload);
4985
6173
  },
4986
6174
  MESSAGE_DELETE_BULK(client, d) {
4987
6175
  const data = d;
4988
- for (const id of data.ids ?? []) client._removeMessageFromCache(data.channel_id, id);
6176
+ const ids = data.ids ?? [];
6177
+ const cache = client._getMessageCache(data.channel_id);
6178
+ const messages = ids.map(
6179
+ (id) => toPartialMessage(client, {
6180
+ id,
6181
+ channelId: data.channel_id,
6182
+ guildId: data.guild_id ?? cache?.get(id)?.guild_id ?? null,
6183
+ cached: cache?.get(id)
6184
+ })
6185
+ );
6186
+ for (const id of ids) client._removeMessageFromCache(data.channel_id, id);
4989
6187
  client.emit(Events.MessageDeleteBulk, {
4990
- ids: data.ids ?? [],
6188
+ ids,
4991
6189
  channelId: data.channel_id,
4992
- guildId: data.guild_id ?? null
6190
+ guildId: data.guild_id ?? null,
6191
+ channel: cachedTextChannel(client, data.channel_id),
6192
+ messages
4993
6193
  });
4994
6194
  },
4995
6195
  MESSAGE_REACTION_ADD: emitReaction(Events.MessageReactionAdd),
@@ -4999,7 +6199,9 @@ var messageHandlers = {
4999
6199
  const payload = {
5000
6200
  messageId: data.message_id,
5001
6201
  channelId: data.channel_id,
5002
- guildId: data.guild_id ?? null
6202
+ guildId: data.guild_id ?? null,
6203
+ message: cachedMessage(client, data.channel_id, data.message_id),
6204
+ channel: cachedTextChannel(client, data.channel_id)
5003
6205
  };
5004
6206
  client.emit(Events.MessageReactionRemoveAll, payload);
5005
6207
  },
@@ -5009,7 +6211,9 @@ var messageHandlers = {
5009
6211
  messageId: data.message_id,
5010
6212
  channelId: data.channel_id,
5011
6213
  guildId: data.guild_id ?? null,
5012
- emoji: toReactionEmoji2(data.emoji)
6214
+ emoji: toReactionEmoji(data.emoji),
6215
+ message: cachedMessage(client, data.channel_id, data.message_id),
6216
+ channel: cachedTextChannel(client, data.channel_id)
5013
6217
  };
5014
6218
  client.emit(Events.MessageReactionRemoveEmoji, payload);
5015
6219
  },
@@ -5028,7 +6232,7 @@ var messageHandlers = {
5028
6232
  }
5029
6233
  reactions.push({
5030
6234
  userId: entry.user_id,
5031
- emoji: toReactionEmoji2(entry.emoji),
6235
+ emoji: toReactionEmoji(entry.emoji),
5032
6236
  member
5033
6237
  });
5034
6238
  }
@@ -5036,6 +6240,8 @@ var messageHandlers = {
5036
6240
  channelId: data.channel_id,
5037
6241
  messageId: data.message_id,
5038
6242
  guildId: data.guild_id ?? null,
6243
+ message: cachedMessage(client, data.channel_id, data.message_id),
6244
+ channel: cachedTextChannel(client, data.channel_id),
5039
6245
  reactions
5040
6246
  };
5041
6247
  client.emit(Events.MessageReactionAddMany, payload);
@@ -5210,10 +6416,15 @@ function hydrateReadyGuilds(client, guilds, waitForGuilds) {
5210
6416
  for (const g of guilds ?? []) {
5211
6417
  if (g.unavailable === true) {
5212
6418
  if (typeof g.id === "string") {
5213
- const existing = client.guilds.get(g.id);
5214
- if (existing && existing.available !== false) {
5215
- existing.available = false;
6419
+ let guild = client.guilds.get(g.id);
6420
+ if (!guild) {
6421
+ guild = new Guild(client, { id: g.id });
6422
+ guild.available = false;
6423
+ client.guilds.set(g.id, guild);
6424
+ } else if (guild.available !== false) {
6425
+ guild.available = false;
5216
6426
  }
6427
+ client._readyStubGuildIds.add(g.id);
5217
6428
  if (pending !== null) pending.add(g.id);
5218
6429
  }
5219
6430
  continue;
@@ -5241,22 +6452,36 @@ function clearGuildStreamSettle(client) {
5241
6452
  clearTimeout(client._guildStreamSettleTimeout);
5242
6453
  client._guildStreamSettleTimeout = null;
5243
6454
  }
6455
+ function resetGuildStreamSettle(client) {
6456
+ clearGuildStreamSettle(client);
6457
+ client._guildStreamSettleTimeout = setTimeout(() => {
6458
+ client._guildStreamSettleTimeout = null;
6459
+ if (client.readyAt === null) finalizeClientReady(client);
6460
+ }, GUILD_STREAM_SETTLE_MS);
6461
+ }
5244
6462
  function handleReadyPayload(client, data) {
5245
6463
  client.user = new ClientUser(client, data.user);
5246
6464
  const waitForGuilds = client.options.waitForGuilds === true;
5247
6465
  const guilds = data.guilds ?? [];
5248
6466
  const pending = hydrateReadyGuilds(client, guilds, waitForGuilds);
5249
- if (pending !== null && pending.size > 0) {
5250
- client._pendingGuildIds = pending;
6467
+ if (client.readyAt !== null) {
6468
+ if (pending !== null && pending.size > 0) {
6469
+ const existing = client._pendingGuildIds ?? /* @__PURE__ */ new Set();
6470
+ for (const id of pending) existing.add(id);
6471
+ client._pendingGuildIds = existing;
6472
+ }
5251
6473
  return;
5252
6474
  }
5253
- if (waitForGuilds && guilds.length === 0) {
5254
- client._guildStreamSettleTimeout = setTimeout(() => {
5255
- client._guildStreamSettleTimeout = null;
5256
- finalizeClientReady(client);
5257
- }, GUILD_STREAM_SETTLE_MS);
6475
+ if (pending !== null && pending.size > 0) {
6476
+ const existing = client._pendingGuildIds ?? /* @__PURE__ */ new Set();
6477
+ for (const id of pending) existing.add(id);
6478
+ client._pendingGuildIds = existing;
5258
6479
  return;
5259
6480
  }
6481
+ if (guilds.length === 0) {
6482
+ resetGuildStreamSettle(client);
6483
+ if (waitForGuilds) return;
6484
+ }
5260
6485
  finalizeClientReady(client);
5261
6486
  }
5262
6487
  async function connectClientGateway(client, token, signal) {
@@ -5266,7 +6491,7 @@ async function connectClientGateway(client, token, signal) {
5266
6491
  const ws = new WebSocketManager({
5267
6492
  token,
5268
6493
  intents: client.options.intents ?? 0,
5269
- presence: client.options.presence,
6494
+ presence: client.options.presence ? toPresenceWire(client.options.presence) : void 0,
5270
6495
  flags: client.options.identifyFlags,
5271
6496
  ignoredEvents: client.options.ignoredEvents,
5272
6497
  initialGuildId: client.options.initialGuildId,
@@ -5275,24 +6500,57 @@ async function connectClientGateway(client, token, signal) {
5275
6500
  },
5276
6501
  version: client.options.rest?.version ?? "1",
5277
6502
  debug: client.options.gatewayDebug !== false,
5278
- WebSocket: client.options.WebSocket
6503
+ WebSocket: client.options.WebSocket,
6504
+ shardCount: client.options.shardCount ?? client.options.totalShards,
6505
+ shardIds: client.options.shardIds ?? client.options.shardList,
6506
+ guildsPerShard: client.options.guildsPerShard,
6507
+ buildStrategy: client.options.buildStrategy,
6508
+ sessionStore: client.options.sessionStore,
6509
+ identifyThrottler: client.options.identifyThrottler
5279
6510
  });
5280
6511
  ws.on("dispatch", ({ payload }) => {
5281
6512
  handleGatewayDispatch(client, payload, client._deferredGatewayDispatches).catch(
5282
6513
  (err) => emitClientError(client, err)
5283
6514
  );
5284
6515
  });
5285
- ws.on("ready", ({ data }) => {
5286
- handleReadyPayload(client, data);
6516
+ ws.on("ready", ({ shardId, data }) => {
6517
+ client.emit(Events.ShardReady, shardId);
6518
+ try {
6519
+ handleReadyPayload(client, data);
6520
+ } catch (err) {
6521
+ emitClientError(client, err);
6522
+ }
6523
+ });
6524
+ ws.on("resumed", (shardId) => {
6525
+ client.emit(Events.ShardResumed, shardId);
6526
+ });
6527
+ ws.on("close", ({ shardId, code }) => {
6528
+ client.emit(Events.ShardDisconnect, shardId, code);
6529
+ if (code === GatewayCloseCodes.AuthenticationFailed) {
6530
+ emitClientError(
6531
+ client,
6532
+ new FluxerError("Gateway authentication failed (4004). Check the bot token.", {
6533
+ code: ErrorCodes.InvalidToken
6534
+ })
6535
+ );
6536
+ }
5287
6537
  });
5288
- ws.on("error", ({ error }) => {
5289
- client.logger.error("gateway error", { error: error.message, name: error.name });
6538
+ ws.on("error", ({ shardId, error }) => {
6539
+ if (shardId >= 0) client.emit(Events.ShardError, shardId, error);
6540
+ client.logger.error("gateway error", {
6541
+ error: error.message,
6542
+ name: error.name,
6543
+ shardId
6544
+ });
5290
6545
  client.emit(Events.Error, error);
5291
6546
  });
5292
6547
  ws.on("debug", (msg) => {
5293
6548
  client.logger.debug(msg);
5294
6549
  client.emit(Events.Debug, msg);
5295
6550
  });
6551
+ ws.on("shardingRequired", (payload) => {
6552
+ client.emit(Events.ShardingRequired, payload);
6553
+ });
5296
6554
  client._ws = ws;
5297
6555
  const onAbort = () => {
5298
6556
  ws.destroy();
@@ -5318,9 +6576,9 @@ async function connectClientGateway(client, token, signal) {
5318
6576
  }
5319
6577
 
5320
6578
  // src/ClientCore/GuildManager.ts
5321
- import { LimitedCollection as LimitedCollection4 } from "@fluxerjs/collection";
5322
- import { Routes as Routes31 } from "@fluxerjs/types";
5323
- var GuildManager = class extends LimitedCollection4 {
6579
+ import { LimitedCollection as LimitedCollection5 } from "@fluxerjs/collection";
6580
+ import { Routes as Routes32 } from "@fluxerjs/types";
6581
+ var GuildManager = class extends LimitedCollection5 {
5324
6582
  constructor(client) {
5325
6583
  super({
5326
6584
  maxSize: client.cache.limits.guilds,
@@ -5329,8 +6587,8 @@ var GuildManager = class extends LimitedCollection4 {
5329
6587
  this.client = client;
5330
6588
  }
5331
6589
  /**
5332
- * Remove a guild and cascade its channels / message caches.
5333
- * FIFO eviction uses `onEvict` instead (via `super.delete` in LimitedCollection).
6590
+ * Remove a guild from cache and cascade its channels / message caches.
6591
+ * Does not leave the guild. Use {@link ClientUser.leaveGuild} for that.
5334
6592
  */
5335
6593
  delete(key) {
5336
6594
  const guild = this.get(key);
@@ -5358,7 +6616,7 @@ var GuildManager = class extends LimitedCollection4 {
5358
6616
  const cached = this.get(guildId);
5359
6617
  if (cached && !options?.force) return cached;
5360
6618
  try {
5361
- const data = await this.client.rest.get(Routes31.guild(guildId));
6619
+ const data = await this.client.rest.get(Routes32.guild(guildId));
5362
6620
  if (cached) {
5363
6621
  cached._patch(data);
5364
6622
  return cached;
@@ -5443,184 +6701,13 @@ var MessageCache = class {
5443
6701
  }
5444
6702
  };
5445
6703
 
5446
- // src/ClientCore/PackManager.ts
5447
- import {
5448
- Routes as Routes32
5449
- } from "@fluxerjs/types";
5450
- function toPackSummaryPayload(data) {
5451
- return {
5452
- id: data.id,
5453
- name: data.name,
5454
- description: data.description,
5455
- type: data.type,
5456
- creatorId: data.creator_id,
5457
- createdAt: data.created_at,
5458
- updatedAt: data.updated_at,
5459
- ...data.installed_at !== void 0 ? { installedAt: data.installed_at } : {}
5460
- };
5461
- }
5462
- function toEmojiPayload(data) {
5463
- return {
5464
- id: data.id,
5465
- name: data.name,
5466
- animated: data.animated
5467
- };
5468
- }
5469
- function toStickerPayload(data) {
5470
- return {
5471
- id: data.id,
5472
- name: data.name,
5473
- description: data.description,
5474
- tags: data.tags,
5475
- animated: data.animated,
5476
- nsfw: data.nsfw
5477
- };
5478
- }
5479
- function toInvitePayload(data) {
5480
- return {
5481
- code: data.code,
5482
- ...data.max_uses !== void 0 ? { maxUses: data.max_uses } : {},
5483
- ...data.max_age !== void 0 ? { maxAge: data.max_age } : {},
5484
- ...data.uses !== void 0 ? { uses: data.uses } : {},
5485
- ...data.temporary !== void 0 ? { temporary: data.temporary } : {},
5486
- ...data.created_at !== void 0 ? { createdAt: data.created_at } : {},
5487
- ...data.expires_at !== void 0 ? { expiresAt: data.expires_at } : {}
5488
- };
5489
- }
5490
- function mapDashboardSection(section) {
5491
- return {
5492
- installedLimit: section.installed_limit,
5493
- createdLimit: section.created_limit,
5494
- installed: section.installed.map(toPackSummaryPayload),
5495
- created: section.created.map(toPackSummaryPayload)
5496
- };
5497
- }
5498
- var PackManager = class {
5499
- constructor(client) {
5500
- this.client = client;
5501
- }
5502
- /** Fetch the current user's pack dashboard (camelCase summaries). */
5503
- async fetchDashboard() {
5504
- const data = await this.client.rest.get(Routes32.packs());
5505
- return {
5506
- emoji: mapDashboardSection(data.emoji),
5507
- sticker: mapDashboardSection(data.sticker)
5508
- };
5509
- }
5510
- /** Create a pack. */
5511
- async create(packType, body) {
5512
- const data = await this.client.rest.post(Routes32.packsByType(packType), {
5513
- body
5514
- });
5515
- return toPackSummaryPayload(data);
5516
- }
5517
- /** Edit a pack. */
5518
- async edit(packId, body) {
5519
- const data = await this.client.rest.patch(Routes32.pack(packId), { body });
5520
- return toPackSummaryPayload(data);
5521
- }
5522
- /** Delete a pack. */
5523
- async delete(packId) {
5524
- await this.client.rest.delete(Routes32.pack(packId));
5525
- }
5526
- /** Install a pack for the current user. */
5527
- async install(packId) {
5528
- await this.client.rest.post(Routes32.packInstall(packId));
5529
- }
5530
- /** Uninstall a pack for the current user. */
5531
- async uninstall(packId) {
5532
- await this.client.rest.delete(Routes32.packInstall(packId));
5533
- }
5534
- /** List invites for a pack. */
5535
- async listInvites(packId) {
5536
- const data = await this.client.rest.get(Routes32.packInvites(packId));
5537
- return data.map(toInvitePayload);
5538
- }
5539
- /** Create an invite for a pack. */
5540
- async createInvite(packId, options = {}) {
5541
- const body = toPackInviteBody(options);
5542
- const data = await this.client.rest.post(Routes32.packInvites(packId), {
5543
- body: Object.keys(body).length ? body : void 0
5544
- });
5545
- return toInvitePayload(data);
5546
- }
5547
- /** List emojis in a pack. */
5548
- async listEmojis(packId) {
5549
- const data = await this.client.rest.get(Routes32.packEmojis(packId));
5550
- return data.map(toEmojiPayload);
5551
- }
5552
- /** Create an emoji in a pack. */
5553
- async createEmoji(packId, options) {
5554
- const data = await this.client.rest.post(Routes32.packEmojis(packId), {
5555
- body: toEmojiCreateBody(options)
5556
- });
5557
- return toEmojiPayload(data);
5558
- }
5559
- /** Bulk-create emojis in a pack. */
5560
- async createEmojisBulk(packId, emojis) {
5561
- const data = await this.client.rest.post(
5562
- Routes32.packEmojisBulk(packId),
5563
- { body: { emojis: emojis.map(toEmojiCreateBody) } }
5564
- );
5565
- return {
5566
- success: data.success.map(toEmojiPayload),
5567
- failed: data.failed
5568
- };
5569
- }
5570
- /** Edit an emoji in a pack. */
5571
- async editEmoji(packId, emojiId, options) {
5572
- const data = await this.client.rest.patch(Routes32.packEmoji(packId, emojiId), {
5573
- body: toEmojiEditBody(options)
5574
- });
5575
- return toEmojiPayload(data);
5576
- }
5577
- /** Delete an emoji from a pack. */
5578
- async deleteEmoji(packId, emojiId) {
5579
- await this.client.rest.delete(Routes32.packEmoji(packId, emojiId));
5580
- }
5581
- /** List stickers in a pack. */
5582
- async listStickers(packId) {
5583
- const data = await this.client.rest.get(Routes32.packStickers(packId));
5584
- return data.map(toStickerPayload);
5585
- }
5586
- /** Create a sticker in a pack. */
5587
- async createSticker(packId, options) {
5588
- const data = await this.client.rest.post(Routes32.packStickers(packId), {
5589
- body: toStickerCreateBody(options)
5590
- });
5591
- return toStickerPayload(data);
5592
- }
5593
- /** Bulk-create stickers in a pack. */
5594
- async createStickersBulk(packId, stickers) {
5595
- const data = await this.client.rest.post(
5596
- Routes32.packStickersBulk(packId),
5597
- { body: { stickers: stickers.map(toStickerCreateBody) } }
5598
- );
5599
- return {
5600
- success: data.success.map(toStickerPayload),
5601
- failed: data.failed
5602
- };
5603
- }
5604
- /** Edit a sticker in a pack. */
5605
- async editSticker(packId, stickerId, options) {
5606
- const data = await this.client.rest.patch(Routes32.packSticker(packId, stickerId), {
5607
- body: toStickerEditBody(options)
5608
- });
5609
- return toStickerPayload(data);
5610
- }
5611
- /** Delete a sticker from a pack. */
5612
- async deleteSticker(packId, stickerId) {
5613
- await this.client.rest.delete(Routes32.packSticker(packId, stickerId));
5614
- }
5615
- };
5616
-
5617
6704
  // src/ClientCore/UserManager.ts
5618
- import { LimitedCollection as LimitedCollection5 } from "@fluxerjs/collection";
6705
+ import { LimitedCollection as LimitedCollection6 } from "@fluxerjs/collection";
5619
6706
  import {
5620
6707
  Routes as Routes33
5621
6708
  } from "@fluxerjs/types";
5622
6709
  var soft = (p) => p.catch(() => null);
5623
- var UserManager = class extends LimitedCollection5 {
6710
+ var UserManager = class extends LimitedCollection6 {
5624
6711
  constructor(client) {
5625
6712
  super({ maxSize: client.cache.limits.users });
5626
6713
  this.client = client;
@@ -5638,11 +6725,17 @@ var UserManager = class extends LimitedCollection5 {
5638
6725
  }
5639
6726
  return removed;
5640
6727
  }
5641
- /** Fetch a user by ID and update cache. */
5642
- async fetch(userId) {
6728
+ /** Fetch a user by ID and update cache. Returns cache unless `force` is set. */
6729
+ async fetch(userId, options) {
6730
+ const cached = this.get(userId);
6731
+ if (cached && !options?.force) return cached;
5643
6732
  const data = await this.client.rest.get(Routes33.user(userId));
5644
6733
  return this.client.getOrCreateUser(data);
5645
6734
  }
6735
+ /** Return a cached user, otherwise {@link fetch}. */
6736
+ async resolve(userId) {
6737
+ return this.get(userId) ?? this.fetch(userId);
6738
+ }
5646
6739
  /**
5647
6740
  * Fetch user + profiles (+ optional guild member). Ideal for userinfo commands.
5648
6741
  * @example
@@ -5702,19 +6795,32 @@ var Client = class _Client extends EventEmitter3 {
5702
6795
  users;
5703
6796
  /** Cache limits, stats, sweeps, and cascade entry points. */
5704
6797
  cache;
5705
- /** Emoji/sticker pack REST wrappers (`/packs/*`). */
5706
- packs = new PackManager(this);
5707
- /** Typed event handlers. Prefer `client.events.*` or `client.on(Events.*, ...)`. */
6798
+ /** Typed event handlers. Prefer `client.on(Events.*, ...)`. */
5708
6799
  events;
5709
6800
  /** The authenticated bot user. Null until READY is received. */
5710
6801
  user = null;
5711
6802
  /** Timestamp when the client became ready. Null until READY is received. */
5712
6803
  readyAt = null;
6804
+ /**
6805
+ * Milliseconds since {@link readyAt}, or `null` if the client is not ready.
6806
+ * @example
6807
+ * client.on(Events.Ready, () => {
6808
+ * console.log(client.uptime);
6809
+ * });
6810
+ */
6811
+ get uptime() {
6812
+ return this.readyAt ? Date.now() - this.readyAt.getTime() : null;
6813
+ }
5713
6814
  /** @internal WebSocket manager. */
5714
6815
  _ws = null;
5715
6816
  /** When waitForGuilds, guild IDs still expected via GUILD_CREATE. */
5716
6817
  _pendingGuildIds = null;
5717
- /** @internal Timeout when READY has no guilds but waitForGuilds is set. */
6818
+ /** Guild IDs inserted as unavailable stubs from READY (startup / reconnect backfill). */
6819
+ _readyStubGuildIds = /* @__PURE__ */ new Set();
6820
+ /**
6821
+ * @internal Empty-READY guild stream window.
6822
+ * Classifies incoming GUILD_CREATE as startup hydration. Also delays Ready when waitForGuilds.
6823
+ */
5718
6824
  _guildStreamSettleTimeout = null;
5719
6825
  /** @internal Dispatches queued until Ready when waitForGuilds delays Ready. */
5720
6826
  _deferredGatewayDispatches = [];
@@ -5745,7 +6851,7 @@ var Client = class _Client extends EventEmitter3 {
5745
6851
  const restApi = options.rest?.api;
5746
6852
  if (options.instance !== void 0) {
5747
6853
  this.instance = resolveInstanceEndpoints(options.instance);
5748
- resolveRestApi(this.instance.endpoints.api, restApi);
6854
+ resolveRestApi(this.instance.endpoints.api_public, restApi);
5749
6855
  } else {
5750
6856
  this.instance = resolveInstanceEndpoints(
5751
6857
  restApi !== void 0 ? { api: restApi } : void 0
@@ -5758,27 +6864,31 @@ var Client = class _Client extends EventEmitter3 {
5758
6864
  }
5759
6865
  this.rest = new REST({
5760
6866
  ...this.options.rest,
5761
- api: this.instance.endpoints.api,
5762
- version: this.options.rest?.version ?? "1"
6867
+ api: this.instance.endpoints.api_public,
6868
+ version: this.options.rest?.version ?? "1",
6869
+ locale: this.options.locale ?? this.options.rest?.locale
5763
6870
  });
5764
6871
  }
5765
6872
  /**
5766
6873
  * Create a client from instance discovery (`GET /.well-known/fluxer`).
5767
- * Does not log in — call {@link login} with a token afterward.
6874
+ * Fetches the unversioned well-known document from the given origin (not `{api}/v1/.well-known/fluxer`).
6875
+ * Wires REST from `endpoints.api_public`. `endpoints.api` / `api_client` stay on the instance for inspection.
6876
+ * Does not log in. Call {@link login} with a token afterward.
5768
6877
  *
5769
- * @param origin - API origin used only to fetch discovery (e.g. `https://api.example.com`)
5770
- * @param options - Client options (must not conflict with discovered `endpoints.api`)
6878
+ * @param origin - Origin used only to fetch discovery (e.g. `https://fluxer.app` or `https://my.instance`)
6879
+ * @param options - Client options (must not conflict with discovered `endpoints.api_public`)
5771
6880
  * @param connectOptions - Optional abort signal for the discovery request
5772
6881
  */
5773
6882
  static async fromDiscovery(origin, options = {}, connectOptions) {
5774
- const bootstrapApi = typeof origin === "string" ? normalizeApiOrigin(origin) : normalizeApiOrigin(origin.api);
6883
+ const bootstrapOrigin = typeof origin === "string" ? normalizeApiOrigin(origin) : normalizeApiOrigin(origin.api);
5775
6884
  const version = typeof origin === "string" ? options.rest?.version ?? "1" : origin.version ?? options.rest?.version ?? "1";
5776
6885
  const bootstrap = new REST({
5777
6886
  ...options.rest ?? {},
5778
- api: bootstrapApi,
5779
- version
6887
+ api: bootstrapOrigin,
6888
+ version,
6889
+ locale: options.locale ?? options.rest?.locale
5780
6890
  });
5781
- const raw = await bootstrap.get(Routes34.instanceDiscovery(), {
6891
+ const raw = await bootstrap.get(instanceDiscoveryUrl(bootstrapOrigin), {
5782
6892
  auth: false,
5783
6893
  ...connectOptions?.signal ? { signal: connectOptions.signal } : {}
5784
6894
  });
@@ -5786,7 +6896,7 @@ var Client = class _Client extends EventEmitter3 {
5786
6896
  const { rest, ...restOptions } = options;
5787
6897
  return new _Client({
5788
6898
  ...restOptions,
5789
- // Drop rest.api so discovered endpoints.api owns the host; keep other REST opts.
6899
+ // Drop rest.api so discovered endpoints.api_public owns the REST host; keep other REST opts.
5790
6900
  ...rest ? { rest: { ...rest, api: void 0 } } : {},
5791
6901
  instance: discovery
5792
6902
  });
@@ -5813,7 +6923,7 @@ var Client = class _Client extends EventEmitter3 {
5813
6923
  return resolveClientEmoji(this, emoji, guildId);
5814
6924
  }
5815
6925
  /**
5816
- * Fetch instance discovery document (`/.well-known/fluxer`).
6926
+ * Fetch instance discovery document (unversioned `GET /.well-known/fluxer` on the REST host).
5817
6927
  * @returns Instance configuration (endpoints, features, metadata)
5818
6928
  */
5819
6929
  fetchInstance() {
@@ -5850,33 +6960,23 @@ var Client = class _Client extends EventEmitter3 {
5850
6960
  return fetchApplication(this);
5851
6961
  }
5852
6962
  /**
5853
- * Fetch OAuth2 applications owned by this bot.
5854
- * @returns Array of OAuth application objects
6963
+ * Fetch OAuth2 applications (`GET /oauth2/applications/@me`).
6964
+ * A bot token returns the bot application object (normalized to a one-element array).
6965
+ * A user token returns the owner's application list.
5855
6966
  */
5856
6967
  fetchOAuthApplications() {
5857
6968
  return fetchOAuthApplications(this);
5858
6969
  }
5859
- /**
5860
- * Check username#discriminator availability.
5861
- * @param username - Username to check
5862
- * @param discriminator - Discriminator to check
5863
- * @returns Availability result
5864
- */
5865
- checkUsernameTag(username, discriminator) {
5866
- return checkUsernameTag(this, username, discriminator);
5867
- }
5868
6970
  /**
5869
6971
  * Preload recent messages for multiple channels (batch endpoint).
5870
- * @param channelIds - Array of channel IDs to preload
5871
- * @returns Preload response with message counts/timestamps
6972
+ * Prefer this over {@link bulkFetchMessages} for bots (`bulkFetchMessages` is user-account only).
5872
6973
  */
5873
6974
  preloadMessages(channelIds) {
5874
6975
  return preloadMessages(this, channelIds);
5875
6976
  }
5876
6977
  /**
5877
6978
  * Preload recent messages (alternate endpoint).
5878
- * @param channelIds - Array of channel IDs to preload
5879
- * @returns Preload response with message counts/timestamps
6979
+ * Prefer this over {@link bulkFetchMessages} for bots.
5880
6980
  */
5881
6981
  preloadMessagesAlt(channelIds) {
5882
6982
  return preloadMessagesAlt(this, channelIds);
@@ -5884,6 +6984,14 @@ var Client = class _Client extends EventEmitter3 {
5884
6984
  bulkFetchMessages(requests, options = {}) {
5885
6985
  return bulkFetchMessages(this, requests, options);
5886
6986
  }
6987
+ /**
6988
+ * Search messages in the current bot scope (`POST /search/messages`, `scope: current`).
6989
+ * Other scopes are denied for bots (`BOT_SEARCH_SCOPE_UNAVAILABLE`).
6990
+ * Returns camelCase results (`hitsPerPage`) or `{ indexing: true }` while channels are indexed.
6991
+ */
6992
+ searchMessages(options) {
6993
+ return searchMessages(this, options);
6994
+ }
5887
6995
  /** @internal */
5888
6996
  _getMessageCache(channelId) {
5889
6997
  return this._messageCache.get(channelId);
@@ -5907,12 +7015,16 @@ var Client = class _Client extends EventEmitter3 {
5907
7015
  /**
5908
7016
  * Sweep cached messages (remove entries matching filter).
5909
7017
  * Prefer {@link CacheController.sweepMessages} (`client.cache.sweepMessages`).
7018
+ * The filter receives a hydrated {@link Message} (`createdAt`), not the stored wire payload.
5910
7019
  * @param filter - Predicate to test each message (return true to remove)
5911
7020
  * @param channelId - Optional channel ID to scope sweep
5912
7021
  * @returns Count of messages removed
5913
7022
  */
5914
7023
  sweepMessages(filter, channelId) {
5915
- return this._messageCache.sweep(filter, channelId);
7024
+ return this._messageCache.sweep(
7025
+ filter ? (data, chId) => filter(new Message(this, data), chId) : void 0,
7026
+ channelId
7027
+ );
5916
7028
  }
5917
7029
  /**
5918
7030
  * Sweep cached members across all guilds (remove entries matching filter).
@@ -5945,6 +7057,9 @@ var Client = class _Client extends EventEmitter3 {
5945
7057
  }
5946
7058
  /**
5947
7059
  * The underlying {@link WebSocketManager} (throws if not logged in).
7060
+ * Gateway heartbeat ACK latency: `client.ws.ping` (ms, or `-1` before the first ACK).
7061
+ * @example
7062
+ * console.log(client.ws.ping);
5948
7063
  * @throws {@link FluxerError} with {@link ErrorCodes.NotLoggedIn}
5949
7064
  */
5950
7065
  get ws() {
@@ -5983,6 +7098,37 @@ var Client = class _Client extends EventEmitter3 {
5983
7098
  if (options.nonce !== void 0) data.nonce = options.nonce;
5984
7099
  this._sendToAllShards({ op: GatewayOpcodes2.RequestGuildMembers, d: data });
5985
7100
  }
7101
+ /**
7102
+ * Request guild member/online counts via gateway opcode 15.
7103
+ * Listen for `guildCountsUpdate`. Cached `guild.memberCount` / `guild.onlineCount` update when that event arrives.
7104
+ */
7105
+ requestGuildCounts(options) {
7106
+ const guildIds = [...new Set(options.guildIds.filter(Boolean))];
7107
+ if (!guildIds.length) {
7108
+ throw new FluxerError("requestGuildCounts requires at least one guildId", {
7109
+ code: ErrorCodes.InvalidGatewayRequest
7110
+ });
7111
+ }
7112
+ const data = { guild_ids: guildIds };
7113
+ if (options.nonce !== void 0) data.nonce = options.nonce;
7114
+ this._sendToAllShards({ op: GatewayOpcodes2.RequestGuildCounts, d: data });
7115
+ }
7116
+ /**
7117
+ * Request per-channel member counts via gateway opcode 16.
7118
+ * Event-only: listen for `channelMemberCountsUpdate`. There is no `channel.memberCount` field.
7119
+ */
7120
+ requestChannelMemberCounts(options) {
7121
+ if (!options.guildId) {
7122
+ throw new FluxerError("requestChannelMemberCounts requires guildId", {
7123
+ code: ErrorCodes.InvalidGatewayRequest
7124
+ });
7125
+ }
7126
+ const data = { guild_id: options.guildId };
7127
+ if (options.channelId !== void 0) data.channel_id = options.channelId;
7128
+ if (options.channelIds !== void 0) data.channel_ids = [...new Set(options.channelIds)];
7129
+ if (options.nonce !== void 0) data.nonce = options.nonce;
7130
+ this._sendToAllShards({ op: GatewayOpcodes2.RequestChannelMemberCounts, d: data });
7131
+ }
5986
7132
  /**
5987
7133
  * Broadcast a gateway payload to all shards.
5988
7134
  * @param payload - Gateway send payload
@@ -5996,9 +7142,13 @@ var Client = class _Client extends EventEmitter3 {
5996
7142
  }
5997
7143
  /**
5998
7144
  * Connect to the gateway with a bot token.
7145
+ * @example
7146
+ * const client = new Client();
7147
+ * client.on(Events.Ready, () => console.log('Ready!'));
7148
+ * await client.login(process.env.FLUXER_BOT_TOKEN);
5999
7149
  * @param token - Bot token from the developer portal
6000
7150
  * @param options - Optional abort signal for cancellation
6001
- * @returns The token that was used (echo)
7151
+ * @returns This client (for chaining)
6002
7152
  * @throws {@link FluxerError} if already logged in or token is invalid
6003
7153
  */
6004
7154
  async login(token, options) {
@@ -6013,7 +7163,7 @@ var Client = class _Client extends EventEmitter3 {
6013
7163
  this.rest.setToken(token);
6014
7164
  try {
6015
7165
  this._ws = await connectClientGateway(this, token, options?.signal);
6016
- return token;
7166
+ return this;
6017
7167
  } catch (err) {
6018
7168
  this._ws?.destroy();
6019
7169
  this._ws = null;
@@ -6042,6 +7192,7 @@ var Client = class _Client extends EventEmitter3 {
6042
7192
  this.user = null;
6043
7193
  this.readyAt = null;
6044
7194
  this._pendingGuildIds = null;
7195
+ this._readyStubGuildIds.clear();
6045
7196
  this.guilds.clear();
6046
7197
  this.channels.clear();
6047
7198
  this.users.clear();
@@ -6066,6 +7217,20 @@ var Client = class _Client extends EventEmitter3 {
6066
7217
  );
6067
7218
  }
6068
7219
  }
7220
+ /**
7221
+ * REST path helpers ({@link Routes}). Pass the path to {@link REST client.rest}.
7222
+ * Prefer high-level helpers (`channel.send()`, `guild.members.fetch()`) when they exist.
7223
+ *
7224
+ * @example
7225
+ * const channel = await client.rest.get(Client.Routes.channel(channelId));
7226
+ *
7227
+ * @example
7228
+ * await client.rest.post(Client.Routes.channelMessages(channelId), {
7229
+ * body: { content: 'hello' },
7230
+ * });
7231
+ *
7232
+ * @see {@link Routes}
7233
+ */
6069
7234
  static get Routes() {
6070
7235
  return Routes34;
6071
7236
  }