@fluxerjs/core 3.2.0 → 3.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cluster.mjs CHANGED
@@ -35,6 +35,14 @@ var Events = {
35
35
  ChannelCreate: "channelCreate",
36
36
  ChannelUpdate: "channelUpdate",
37
37
  ChannelDelete: "channelDelete",
38
+ ThreadCreate: "threadCreate",
39
+ ThreadUpdate: "threadUpdate",
40
+ ThreadDelete: "threadDelete",
41
+ ThreadListSync: "threadListSync",
42
+ ThreadMemberUpdate: "threadMemberUpdate",
43
+ ThreadMembersUpdate: "threadMembersUpdate",
44
+ ThreadMemberListUpdate: "threadMemberListUpdate",
45
+ ForumUnreads: "forumUnreads",
38
46
  ChannelPinsUpdate: "channelPinsUpdate",
39
47
  ChannelRecipientAdd: "channelRecipientAdd",
40
48
  ChannelRecipientRemove: "channelRecipientRemove",
@@ -72,15 +80,15 @@ import { FluxerError } from "@fluxerjs/util";
72
80
  // src/ClientCore/Client.ts
73
81
  import { EventEmitter as EventEmitter3 } from "events";
74
82
  import { REST } from "@fluxerjs/rest";
75
- import { GatewayOpcodes as GatewayOpcodes2, Routes as Routes34 } from "@fluxerjs/types";
83
+ import { GatewayOpcodes as GatewayOpcodes2, Routes as Routes37 } from "@fluxerjs/types";
76
84
  import { createLogger } from "@fluxerjs/util";
77
85
 
78
86
  // src/Domain/Message/Message.ts
79
87
  import { EmbedBuilder as EmbedBuilder2 } from "@fluxerjs/builders";
80
- import { Collection as Collection3 } from "@fluxerjs/collection";
88
+ import { Collection as Collection5 } from "@fluxerjs/collection";
81
89
  import {
82
90
  MessageType,
83
- Routes as Routes4
91
+ Routes as Routes7
84
92
  } from "@fluxerjs/types";
85
93
  import { MessageFlagsBitField } from "@fluxerjs/util";
86
94
 
@@ -149,7 +157,132 @@ function toAttachmentUploadPlanResponse(data) {
149
157
  }
150
158
 
151
159
  // src/ClientCore/SdkOptions/Channels.ts
160
+ import { ChannelType as ChannelType2 } from "@fluxerjs/types";
152
161
  import { resolvePermissionsToBitfield } from "@fluxerjs/util";
162
+
163
+ // src/ClientCore/SdkOptions/Threads.ts
164
+ import {
165
+ ChannelType
166
+ } from "@fluxerjs/types";
167
+ function toThreadEditBody(type, options) {
168
+ const body = {};
169
+ if (options.name !== void 0) body.name = options.name;
170
+ if (options.archived !== void 0) body.archived = options.archived;
171
+ if (options.autoArchiveDuration !== void 0) {
172
+ body.auto_archive_duration = options.autoArchiveDuration;
173
+ }
174
+ if (options.locked !== void 0) body.locked = options.locked;
175
+ if (options.rateLimitPerUser !== void 0) body.rate_limit_per_user = options.rateLimitPerUser;
176
+ if (options.flags !== void 0) body.flags = options.flags;
177
+ if (options.appliedTags !== void 0 && type !== ChannelType.PrivateThread) {
178
+ body.applied_tags = options.appliedTags;
179
+ }
180
+ if (options.invitable !== void 0 && type === ChannelType.PrivateThread) {
181
+ body.invitable = options.invitable;
182
+ }
183
+ return body;
184
+ }
185
+ function toThreadParentEditBody(options) {
186
+ const body = {};
187
+ if (options.autoArchiveDuration !== void 0) {
188
+ body.default_auto_archive_duration = options.autoArchiveDuration;
189
+ }
190
+ if (options.rateLimitPerUser !== void 0) {
191
+ body.default_thread_rate_limit_per_user = options.rateLimitPerUser;
192
+ }
193
+ return body;
194
+ }
195
+ function toStartThreadBody(channelType, options) {
196
+ const type = options.type ?? (channelType === ChannelType.GuildAnnouncement ? ChannelType.AnnouncementThread : ChannelType.PublicThread);
197
+ const body = { name: options.name, type };
198
+ if (options.autoArchiveDuration !== void 0) {
199
+ body.auto_archive_duration = options.autoArchiveDuration;
200
+ }
201
+ if (options.rateLimitPerUser !== void 0) body.rate_limit_per_user = options.rateLimitPerUser;
202
+ if (options.invitable !== void 0) body.invitable = options.invitable;
203
+ return body;
204
+ }
205
+ function toStartThreadFromMessageBody(options) {
206
+ const body = { name: options.name };
207
+ if (options.autoArchiveDuration !== void 0) {
208
+ body.auto_archive_duration = options.autoArchiveDuration;
209
+ }
210
+ if (options.rateLimitPerUser !== void 0) body.rate_limit_per_user = options.rateLimitPerUser;
211
+ return body;
212
+ }
213
+ function toForumThreadMessage(body) {
214
+ const message = {};
215
+ if (body.content !== void 0) message.content = body.content;
216
+ if (body.embeds !== void 0) message.embeds = body.embeds;
217
+ if (body.attachments !== void 0) message.attachments = body.attachments;
218
+ if (body.allowed_mentions !== void 0) message.allowed_mentions = body.allowed_mentions;
219
+ if (body.flags !== void 0) message.flags = body.flags;
220
+ if (body.sticker_ids !== void 0) message.sticker_ids = body.sticker_ids;
221
+ return message;
222
+ }
223
+ function toForumTagBody(options) {
224
+ const body = { name: options.name };
225
+ if ("id" in options && options.id !== void 0) body.id = options.id;
226
+ if (options.moderated !== void 0) body.moderated = options.moderated;
227
+ if (options.emojiId !== void 0) body.emoji_id = options.emojiId;
228
+ if (options.emojiName !== void 0) body.emoji_name = options.emojiName;
229
+ return body;
230
+ }
231
+ function forumParentWire(options, includeLayout) {
232
+ const body = {};
233
+ if (options.availableTags !== void 0) {
234
+ body.available_tags = options.availableTags.map((tag) => toForumTagBody(tag));
235
+ }
236
+ if (options.defaultReactionEmoji !== void 0) {
237
+ body.default_reaction_emoji = options.defaultReactionEmoji === null ? null : reactionEmojiWire(options.defaultReactionEmoji);
238
+ }
239
+ if (options.defaultSortOrder !== void 0) body.default_sort_order = options.defaultSortOrder;
240
+ if (options.defaultTagSetting !== void 0) body.default_tag_setting = options.defaultTagSetting;
241
+ if (options.flags !== void 0) body.flags = options.flags;
242
+ if (options.defaultAutoArchiveDuration !== void 0) {
243
+ body.default_auto_archive_duration = options.defaultAutoArchiveDuration;
244
+ }
245
+ if (options.defaultThreadRateLimitPerUser !== void 0) {
246
+ body.default_thread_rate_limit_per_user = options.defaultThreadRateLimitPerUser;
247
+ }
248
+ if (includeLayout && options.defaultForumLayout !== void 0) {
249
+ body.default_forum_layout = options.defaultForumLayout;
250
+ }
251
+ return body;
252
+ }
253
+ function reactionEmojiWire(emoji) {
254
+ const body = {};
255
+ if (emoji.emojiId !== void 0) body.emoji_id = emoji.emojiId;
256
+ if (emoji.emojiName !== void 0) body.emoji_name = emoji.emojiName;
257
+ return body;
258
+ }
259
+ function toThreadMemberSettingsBody(options) {
260
+ const body = {};
261
+ if (options.flags !== void 0) body.flags = options.flags;
262
+ if (options.muted !== void 0) body.muted = options.muted;
263
+ if (options.muteConfig !== void 0) {
264
+ body.mute_config = options.muteConfig === null ? null : {
265
+ ...options.muteConfig.endTime !== void 0 ? { end_time: options.muteConfig.endTime } : {},
266
+ selected_time_window: options.muteConfig.selectedTimeWindow
267
+ };
268
+ }
269
+ return body;
270
+ }
271
+ function withQuery(path, params) {
272
+ const query = new URLSearchParams();
273
+ for (const [key, value] of Object.entries(params)) {
274
+ if (value === void 0) continue;
275
+ if (Array.isArray(value)) {
276
+ for (const item of value) query.append(key, item);
277
+ continue;
278
+ }
279
+ query.set(key, String(value));
280
+ }
281
+ const text = query.toString();
282
+ return text ? `${path}?${text}` : path;
283
+ }
284
+
285
+ // src/ClientCore/SdkOptions/Channels.ts
153
286
  function toOverwriteWire(overwrite) {
154
287
  return {
155
288
  id: overwrite.id,
@@ -210,6 +343,16 @@ function toChannelCreateBody(options) {
210
343
  body.content_warning_text = options.contentWarningText;
211
344
  }
212
345
  if (options.rateLimitPerUser !== void 0) body.rate_limit_per_user = options.rateLimitPerUser;
346
+ if (options.defaultAutoArchiveDuration !== void 0) {
347
+ body.default_auto_archive_duration = options.defaultAutoArchiveDuration;
348
+ }
349
+ if (options.defaultThreadRateLimitPerUser !== void 0) {
350
+ body.default_thread_rate_limit_per_user = options.defaultThreadRateLimitPerUser;
351
+ }
352
+ const forumParent = options.type === ChannelType2.GuildForum || options.type === ChannelType2.GuildMedia;
353
+ if (forumParent) {
354
+ Object.assign(body, forumParentWire(options, options.type === ChannelType2.GuildForum));
355
+ }
213
356
  return body;
214
357
  }
215
358
  function toChannelInviteBody(options) {
@@ -963,1346 +1106,1404 @@ var ReactionCollector = class _ReactionCollector extends EventEmitter {
963
1106
  }
964
1107
  };
965
1108
 
966
- // src/Domain/Message/Attachment.ts
967
- function toMessageAttachment(data) {
968
- return {
969
- id: data.id,
970
- filename: data.filename,
971
- title: data.title ?? null,
972
- description: data.description ?? null,
973
- contentType: data.content_type ?? null,
974
- contentHash: data.content_hash ?? null,
975
- size: data.size,
976
- url: data.url ?? null,
977
- proxyUrl: data.proxy_url ?? null,
978
- width: data.width ?? null,
979
- height: data.height ?? null,
980
- placeholder: data.placeholder ?? null,
981
- flags: data.flags ?? 0,
982
- nsfw: data.nsfw ?? false,
983
- duration: data.duration ?? null,
984
- waveform: data.waveform ?? null,
985
- expiresAt: data.expires_at ? new Date(data.expires_at) : null,
986
- expired: data.expired ?? false
987
- };
988
- }
989
-
990
- // src/Domain/Message/Embed.ts
991
- function toMessageEmbedAuthor(data) {
992
- return {
993
- name: data.name ?? null,
994
- url: data.url ?? null,
995
- iconUrl: data.icon_url ?? null,
996
- proxyIconUrl: data.proxy_icon_url ?? null
997
- };
998
- }
999
- function toMessageEmbedFooter(data) {
1000
- return {
1001
- text: data.text,
1002
- iconUrl: data.icon_url ?? null,
1003
- proxyIconUrl: data.proxy_icon_url ?? null
1004
- };
1005
- }
1006
- function toMessageEmbedMedia(data) {
1007
- return {
1008
- url: data.url,
1009
- proxyUrl: data.proxy_url ?? null,
1010
- contentType: data.content_type ?? null,
1011
- contentHash: data.content_hash ?? null,
1012
- width: data.width ?? null,
1013
- height: data.height ?? null,
1014
- description: data.description ?? null,
1015
- placeholder: data.placeholder ?? null,
1016
- duration: data.duration ?? null,
1017
- flags: data.flags ?? null
1018
- };
1019
- }
1020
- function toMessageEmbed(data) {
1021
- const full = data;
1022
- return {
1023
- type: data.type ?? "rich",
1024
- url: data.url ?? null,
1025
- title: data.title ?? null,
1026
- color: data.color ?? null,
1027
- timestamp: data.timestamp ? new Date(data.timestamp) : null,
1028
- description: data.description ?? null,
1029
- author: data.author ? toMessageEmbedAuthor(data.author) : null,
1030
- image: data.image ? toMessageEmbedMedia(data.image) : null,
1031
- thumbnail: data.thumbnail ? toMessageEmbedMedia(data.thumbnail) : null,
1032
- footer: data.footer ? toMessageEmbedFooter(data.footer) : null,
1033
- fields: (data.fields ?? []).map((f) => ({
1034
- name: f.name,
1035
- value: f.value,
1036
- inline: f.inline ?? false
1037
- })),
1038
- provider: data.provider ? toMessageEmbedAuthor(data.provider) : null,
1039
- video: data.video ? toMessageEmbedMedia(data.video) : null,
1040
- audio: data.audio ? toMessageEmbedMedia(data.audio) : null,
1041
- nsfw: data.nsfw ?? false,
1042
- children: (full.children ?? []).map(toMessageEmbed),
1043
- html: full.html ?? null,
1044
- htmlWidth: full.html_width ?? null,
1045
- htmlHeight: full.html_height ?? null
1046
- };
1047
- }
1109
+ // src/Domain/Channel/Base.ts
1110
+ import { ChannelType as ChannelType3, Routes as Routes4 } from "@fluxerjs/types";
1111
+ import { SnowflakeUtil } from "@fluxerjs/util";
1048
1112
 
1049
- // src/Domain/Message/MessageReactionManager.ts
1113
+ // src/ClientCore/MessageManager.ts
1050
1114
  import { Collection as Collection2 } from "@fluxerjs/collection";
1051
- var MessageReactionManager = class {
1052
- constructor(message) {
1053
- this.message = message;
1115
+ import { Routes as Routes2 } from "@fluxerjs/types";
1116
+ var BULK = {
1117
+ requests: { min: 1, max: 25 },
1118
+ limit: { min: 1, max: 25 },
1119
+ totalMax: 250
1120
+ };
1121
+ function validateBulkMessageFetchRequests(requests) {
1122
+ const { requests: req, limit, totalMax } = BULK;
1123
+ if (requests.length < req.min || requests.length > req.max) {
1124
+ throw new FluxerError(`bulkFetchMessages requires between ${req.min} and ${req.max} requests`, {
1125
+ code: ErrorCodes.InvalidFetchLimit
1126
+ });
1054
1127
  }
1055
- _cache = new Collection2();
1056
- /** Reactions keyed by unicode name or `name:id`. */
1057
- get cache() {
1058
- return this._cache;
1128
+ let total = 0;
1129
+ for (const request of requests) {
1130
+ if (request.limit < limit.min || request.limit > limit.max) {
1131
+ throw new FluxerError(
1132
+ `limit must be between ${limit.min} and ${limit.max} for channel ${request.channelId}`,
1133
+ { code: ErrorCodes.InvalidFetchLimit }
1134
+ );
1135
+ }
1136
+ total += request.limit;
1059
1137
  }
1060
- get size() {
1061
- return this._cache.size;
1138
+ if (total > totalMax) {
1139
+ throw new FluxerError(`bulkFetchMessages total message limit must not exceed ${totalMax}`, {
1140
+ code: ErrorCodes.InvalidFetchLimit
1141
+ });
1062
1142
  }
1063
- [Symbol.iterator]() {
1064
- return this._cache.values();
1143
+ }
1144
+ var MessageManager = class {
1145
+ constructor(client, channelId) {
1146
+ this.client = client;
1147
+ this.channelId = channelId;
1065
1148
  }
1066
- /** @internal Sync from an API message payload. */
1067
- _patch(reactions) {
1068
- this._cache.clear();
1069
- for (const data of reactions ?? []) {
1070
- const reaction = MessageReaction.fromMessage(this.message, data);
1071
- this._cache.set(reaction.emojiIdentifier, reaction);
1149
+ /** Structure cache keyed by message id (identity for {@link get}). */
1150
+ _structures = new Collection2();
1151
+ /** Retrieve a cached message by ID, or `undefined` if missing / caching disabled. */
1152
+ get(messageId) {
1153
+ const data = this.client._getMessageCache(this.channelId)?.get(messageId);
1154
+ if (!data) {
1155
+ this._structures.delete(messageId);
1156
+ return void 0;
1157
+ }
1158
+ const existing = this._structures.get(messageId);
1159
+ if (existing) return existing;
1160
+ const message = new Message(this.client, data);
1161
+ this._structures.set(messageId, message);
1162
+ return message;
1163
+ }
1164
+ /** Retrieve from cache, otherwise {@link fetch}. */
1165
+ async resolve(messageId) {
1166
+ return this.get(messageId) ?? this.fetch(messageId);
1167
+ }
1168
+ async fetch(idOrOptions) {
1169
+ return typeof idOrOptions === "string" ? this.fetchOne(idOrOptions) : this.fetchMany(idOrOptions);
1170
+ }
1171
+ /** Cache API data and return a {@link Message} (reusing identity when present). */
1172
+ wrap(data) {
1173
+ this.client._addMessageToCache(this.channelId, data);
1174
+ const cached = this.client._getMessageCache(this.channelId)?.get(data.id) ?? data;
1175
+ const existing = this._structures.get(data.id);
1176
+ if (existing) {
1177
+ existing._patch(cached);
1178
+ return existing;
1179
+ }
1180
+ const message = new Message(this.client, cached);
1181
+ this._structures.set(data.id, message);
1182
+ return message;
1183
+ }
1184
+ /** Fetch a single message from the API. */
1185
+ async fetchOne(messageId) {
1186
+ try {
1187
+ const data = await this.client.rest.get(
1188
+ Routes2.channelMessage(this.channelId, messageId)
1189
+ );
1190
+ return this.wrap(data);
1191
+ } catch (err) {
1192
+ rethrowMapped(err, {
1193
+ notFound: {
1194
+ code: ErrorCodes.MessageNotFound,
1195
+ message: `Message ${messageId} not found in channel ${this.channelId}`
1196
+ },
1197
+ fallback: `Failed to fetch message ${messageId}`
1198
+ });
1199
+ }
1200
+ }
1201
+ /** Fetch multiple messages from the API with pagination/filtering. */
1202
+ async fetchMany(options) {
1203
+ if (options.limit != null && (options.limit < 1 || options.limit > 100)) {
1204
+ throw new FluxerError("limit must be between 1 and 100", {
1205
+ code: ErrorCodes.InvalidFetchLimit
1206
+ });
1207
+ }
1208
+ const qs2 = new URLSearchParams();
1209
+ for (const key of ["limit", "before", "after", "around"]) {
1210
+ const value = options[key];
1211
+ if (value != null && value !== "") qs2.set(key, String(value));
1072
1212
  }
1213
+ const base = Routes2.channelMessages(this.channelId);
1214
+ const data = await this.client.rest.get(qs2.size > 0 ? `${base}?${qs2}` : base);
1215
+ const collection = new Collection2();
1216
+ for (const msg of data) collection.set(msg.id, this.wrap(msg));
1217
+ return collection;
1073
1218
  }
1074
1219
  };
1075
1220
 
1076
- // src/Domain/Message/MessageSticker.ts
1077
- import { SnowflakeUtil } from "@fluxerjs/util";
1078
-
1079
- // src/Helpers/Constants.ts
1080
- import { DEFAULT_USER_AGENT } from "@fluxerjs/rest";
1081
- var CDN_URL = "https://fluxerusercontent.com";
1082
- var STATIC_CDN_URL = "https://fluxerstatic.com";
1083
-
1084
- // src/Helpers/Cdn.ts
1085
- var CDN_SIZE_LADDER = [
1086
- 16,
1087
- 20,
1088
- 22,
1089
- 24,
1090
- 28,
1091
- 32,
1092
- 40,
1093
- 44,
1094
- 48,
1095
- 56,
1096
- 60,
1097
- 64,
1098
- 80,
1099
- 96,
1100
- 100,
1101
- 128,
1102
- 160,
1103
- 240,
1104
- 256,
1105
- 300,
1106
- 320,
1107
- 480,
1108
- 512,
1109
- 600,
1110
- 640,
1111
- 1024,
1112
- 1280,
1113
- 1536,
1114
- 2048,
1115
- 3072,
1116
- 4096,
1117
- 8192,
1118
- 16384
1119
- ];
1120
- var CDN_ASSET_CLASS_RANGE = {
1121
- icon: { min: 128, max: 1024 },
1122
- banner: { min: 480, max: 2400 },
1123
- emoji: { min: 32, max: 512 },
1124
- sticker: { min: 128, max: 512 }
1125
- };
1126
- function nearestSize(requested, candidates) {
1127
- let best = candidates[0];
1128
- let bestDist = Math.abs(requested - best);
1129
- for (let i = 1; i < candidates.length; i++) {
1130
- const step = candidates[i];
1131
- const dist = Math.abs(requested - step);
1132
- if (dist < bestDist || dist === bestDist && step > best) {
1133
- best = step;
1134
- bestDist = dist;
1135
- }
1221
+ // src/Helpers/MessageCollector.ts
1222
+ import { EventEmitter as EventEmitter2 } from "events";
1223
+ import { Collection as Collection3 } from "@fluxerjs/collection";
1224
+ function requireCollectorBounds(options) {
1225
+ const time = options.time ?? 0;
1226
+ const max = options.max ?? 0;
1227
+ if (time <= 0 && max <= 0) {
1228
+ throw new FluxerError("MessageCollector requires `time` and/or `max`", {
1229
+ code: ErrorCodes.CollectorOptionsRequired
1230
+ });
1136
1231
  }
1137
- return best;
1138
- }
1139
- function snapCdnSize(requested, assetClass) {
1140
- const { min, max } = CDN_ASSET_CLASS_RANGE[assetClass];
1141
- const snapped = nearestSize(requested, CDN_SIZE_LADDER);
1142
- const clamped = Math.min(max, Math.max(min, snapped));
1143
- const allowed = CDN_SIZE_LADDER.filter((step) => step >= min && step <= max);
1144
- return nearestSize(clamped, allowed);
1145
- }
1146
- function mediaBase(options) {
1147
- return (options?.mediaBase ?? CDN_URL).replace(/\/+$/, "");
1148
- }
1149
- function staticBase(options) {
1150
- return (options?.staticCdnBase ?? STATIC_CDN_URL).replace(/\/+$/, "");
1151
- }
1152
- function getExtension(hash, options) {
1153
- const ext = options?.extension ?? "png";
1154
- if (hash?.startsWith("a_")) return "gif";
1155
- return ext;
1156
- }
1157
- function appendSize(options, assetClass) {
1158
- const size = options?.size;
1159
- if (size == null || !Number.isFinite(size) || size <= 0) return "";
1160
- return `?size=${snapCdnSize(size, assetClass)}`;
1161
- }
1162
- function cdnAvatarURL(userId, avatarHash, options) {
1163
- if (!avatarHash) return null;
1164
- const ext = getExtension(avatarHash, options);
1165
- const size = appendSize(options, "icon");
1166
- return `${mediaBase(options)}/avatars/${userId}/${avatarHash}.${ext}${size}`;
1167
- }
1168
- function cdnBannerURL(resourceId, bannerHash, options) {
1169
- if (!bannerHash) return null;
1170
- const ext = getExtension(bannerHash, options);
1171
- const size = appendSize(options, "banner");
1172
- return `${mediaBase(options)}/banners/${resourceId}/${bannerHash}.${ext}${size}`;
1173
- }
1174
- function cdnMemberAvatarURL(guildId, userId, avatarHash, options) {
1175
- if (!avatarHash) return null;
1176
- const ext = getExtension(avatarHash, options);
1177
- const size = appendSize(options, "icon");
1178
- return `${mediaBase(options)}/guilds/${guildId}/users/${userId}/avatars/${avatarHash}.${ext}${size}`;
1179
- }
1180
- function cdnMemberBannerURL(guildId, userId, bannerHash, options) {
1181
- if (!bannerHash) return null;
1182
- const ext = getExtension(bannerHash, options);
1183
- const size = appendSize(options, "banner");
1184
- return `${mediaBase(options)}/guilds/${guildId}/users/${userId}/banners/${bannerHash}.${ext}${size}`;
1185
- }
1186
- function cdnDefaultAvatarURL(userIdOrIndex, options) {
1187
- const index = typeof userIdOrIndex === "string" ? Number(BigInt(userIdOrIndex) % 6n) : Math.abs(Math.floor(userIdOrIndex) % 6);
1188
- return `${staticBase(options)}/avatars/${index}.png`;
1189
- }
1190
- function cdnGuildAssetURL(kind, id, hash, options) {
1191
- if (!hash) return null;
1192
- const assetClass = kind === "icons" ? "icon" : "banner";
1193
- const size = appendSize(options, assetClass);
1194
- return `${mediaBase(options)}/${kind}/${id}/${hash}.png${size}`;
1195
- }
1196
- function cdnEmojiURL(emojiId, animated, options) {
1197
- const ext = animated ? "gif" : "png";
1198
- const size = appendSize(options, "emoji");
1199
- return `${mediaBase(options)}/emojis/${emojiId}.${ext}${size}`;
1200
1232
  }
1201
- function cdnStickerURL(stickerId, animated, options) {
1202
- const ext = animated ? "gif" : "png";
1203
- const size = appendSize(options, "sticker");
1204
- return `${mediaBase(options)}/stickers/${stickerId}.${ext}${size}`;
1205
- }
1206
-
1207
- // src/Domain/Message/MessageSticker.ts
1208
- var MessageSticker = class extends Base {
1233
+ var MessageCollector = class _MessageCollector extends EventEmitter2 {
1209
1234
  client;
1210
- id;
1211
- name;
1212
- description;
1213
- tags;
1214
- animated;
1215
- constructor(client, data) {
1235
+ channelId;
1236
+ options;
1237
+ collected = new Collection3();
1238
+ _timeout = null;
1239
+ _ended = false;
1240
+ _listener;
1241
+ constructor(client, channelId, options = {}) {
1216
1242
  super();
1243
+ requireCollectorBounds(options);
1217
1244
  this.client = client;
1218
- this.id = data.id;
1219
- this.name = data.name;
1220
- this.description = data.description ?? "";
1221
- this.tags = data.tags ?? [];
1222
- this.animated = data.animated ?? false;
1245
+ this.channelId = channelId;
1246
+ this.options = {
1247
+ filter: options.filter ?? (() => true),
1248
+ time: options.time ?? 0,
1249
+ max: options.max ?? 0
1250
+ };
1251
+ this._listener = (message) => {
1252
+ if (this._ended || message.channelId !== this.channelId) return;
1253
+ if (!this.options.filter(message)) return;
1254
+ this.collected.set(message.id, message);
1255
+ this.emit("collect", message);
1256
+ if (this.options.max > 0 && this.collected.size >= this.options.max) {
1257
+ this.stop("limit");
1258
+ }
1259
+ };
1260
+ this.client.on(Events.MessageCreate, this._listener);
1261
+ if (this.options.time > 0) {
1262
+ this._timeout = setTimeout(() => this.stop("time"), this.options.time);
1263
+ }
1223
1264
  }
1224
- /** CDN URL for this sticker image. */
1225
- get url() {
1226
- return cdnStickerURL(this.id, this.animated, {
1227
- mediaBase: this.client.instance.endpoints.media
1265
+ stop(reason = "user") {
1266
+ if (this._ended) return;
1267
+ this._ended = true;
1268
+ this.client.off(Events.MessageCreate, this._listener);
1269
+ if (this._timeout) {
1270
+ clearTimeout(this._timeout);
1271
+ this._timeout = null;
1272
+ }
1273
+ this.emit("end", this.collected, reason);
1274
+ }
1275
+ /**
1276
+ * One-shot helper used by {@link Channel.awaitMessages}.
1277
+ * Resolves with the collected messages when the collector ends for `user` (or when
1278
+ * the end reason is not listed in `errors`).
1279
+ * By default, `time` and `limit` reject with {@link FluxerError}
1280
+ * (`CollectorIdle` / `CollectorMax`).
1281
+ */
1282
+ static awaitMessages(client, channelId, options) {
1283
+ const errors = options?.errors ?? ["time", "limit"];
1284
+ return new Promise((resolve, reject) => {
1285
+ const collector = new _MessageCollector(client, channelId, options);
1286
+ collector.on("end", (collected, reason) => {
1287
+ if (!errors.includes(reason)) {
1288
+ resolve(collected);
1289
+ return;
1290
+ }
1291
+ if (reason === "time") {
1292
+ reject(
1293
+ new FluxerError("Message collector timed out", {
1294
+ code: ErrorCodes.CollectorIdle
1295
+ })
1296
+ );
1297
+ return;
1298
+ }
1299
+ if (reason === "limit") {
1300
+ reject(
1301
+ new FluxerError("Message collector reached max", {
1302
+ code: ErrorCodes.CollectorMax
1303
+ })
1304
+ );
1305
+ return;
1306
+ }
1307
+ reject(collected);
1308
+ });
1228
1309
  });
1229
1310
  }
1230
- /** Unix timestamp (ms) when this sticker was created, derived from its snowflake ID. */
1231
- get createdTimestamp() {
1232
- return SnowflakeUtil.timestampFromSnowflake(this.id);
1311
+ on(event, listener) {
1312
+ return super.on(event, listener);
1233
1313
  }
1234
- /** Date when this sticker was created, derived from its snowflake ID. */
1235
- get createdAt() {
1236
- return SnowflakeUtil.dateFromSnowflake(this.id);
1314
+ emit(event, ...args) {
1315
+ return super.emit(event, ...args);
1237
1316
  }
1238
1317
  };
1239
1318
 
1240
- // src/Domain/Message/Reactions.ts
1241
- import { Routes as Routes2 } from "@fluxerjs/types";
1242
- async function emojiPath(message, emoji) {
1243
- return message.client.resolveEmoji(emoji, message.guildId);
1244
- }
1245
- async function reactToMessage(message, emoji) {
1246
- const wire = await emojiPath(message, emoji);
1247
- await message.client.rest.put(
1248
- Routes2.channelMessageReactionMe(message.channelId, message.id, wire)
1249
- );
1319
+ // src/Domain/Channel/Attachments.ts
1320
+ import { Routes as Routes3 } from "@fluxerjs/types";
1321
+ var BOT_ATTACHMENT_MAX_BYTES = 50 * 1024 * 1024;
1322
+ var ATTACHMENT_MULTIPART_THRESHOLD_BYTES = 10 * 1024 * 1024;
1323
+ function instanceLimitOverridesSnapshot(client) {
1324
+ const rules = client.instance.discovery?.limits?.rules;
1325
+ if (!rules?.length) return null;
1326
+ const snapshot = {};
1327
+ for (const rule of rules) {
1328
+ Object.assign(snapshot, rule.overrides);
1329
+ }
1330
+ return Object.keys(snapshot).length ? snapshot : null;
1250
1331
  }
1251
- async function removeMessageReaction(message, emoji, userId) {
1252
- const e = await emojiPath(message, emoji);
1253
- const route = userId ? Routes2.channelMessageReactionUser(message.channelId, message.id, e, userId) : Routes2.channelMessageReactionMe(message.channelId, message.id, e);
1254
- await message.client.rest.delete(route);
1255
- }
1256
- async function removeAllMessageReactions(message) {
1257
- await message.client.rest.delete(Routes2.channelMessageReactions(message.channelId, message.id));
1258
- }
1259
- async function removeMessageReactionEmoji(message, emoji) {
1260
- const e = await emojiPath(message, emoji);
1261
- await message.client.rest.delete(Routes2.channelMessageReaction(message.channelId, message.id, e));
1262
- }
1263
- async function fetchMessageReactionUsers(message, emoji, options) {
1264
- return (await fetchMessageReactionUsersPage(message, emoji, options)).users;
1265
- }
1266
- async function fetchMessageReactionUsersPage(message, emoji, options) {
1267
- const e = await emojiPath(message, emoji);
1268
- const params = new URLSearchParams();
1269
- if (options?.limit != null) params.set("limit", String(options.limit));
1270
- if (options?.after) params.set("after", options.after);
1271
- const qs2 = params.toString();
1272
- const route = Routes2.channelMessageReactionUsers(message.channelId, message.id, e) + (qs2 ? `?${qs2}` : "");
1273
- const data = await message.client.rest.get(route);
1274
- if (Array.isArray(data)) {
1275
- return {
1276
- users: data.map((u) => message.client.getOrCreateUser(u)),
1277
- hasMore: false,
1278
- nextAfter: null
1279
- };
1332
+ function assertBotAttachmentLimits(client, files) {
1333
+ const snapshot = instanceLimitOverridesSnapshot(client);
1334
+ for (const file of files) {
1335
+ const size = file.data.byteLength;
1336
+ if (size <= BOT_ATTACHMENT_MAX_BYTES) continue;
1337
+ const snapshotNote = snapshot ? ` Instance limit overrides: ${JSON.stringify(snapshot)}.` : "";
1338
+ throw new FluxerError(
1339
+ `Bot attachments are limited to 50 MiB (${BOT_ATTACHMENT_MAX_BYTES} bytes); "${file.filename}" is ${size} bytes.${snapshotNote}`,
1340
+ { code: ErrorCodes.AttachmentTooLarge }
1341
+ );
1280
1342
  }
1281
- const list = data.items ?? data.users ?? [];
1282
- return {
1283
- users: list.map((u) => message.client.getOrCreateUser(u)),
1284
- hasMore: data.has_more ?? false,
1285
- nextAfter: data.next_after ?? null
1286
- };
1287
1343
  }
1288
-
1289
- // src/Domain/Message/Send.ts
1290
- import { MessagePayload as MessagePayloadBuilder } from "@fluxerjs/builders";
1291
- import { Routes as Routes3 } from "@fluxerjs/types";
1292
- function toReplyTarget(ref) {
1293
- return {
1294
- channelId: ref.channel_id,
1295
- messageId: ref.message_id,
1296
- ...ref.guild_id != null ? { guildId: ref.guild_id } : {}
1297
- };
1298
- }
1299
- function toSendOptions(content) {
1300
- if (typeof content === "string") return { content };
1301
- if (content instanceof MessagePayloadBuilder) return messagePayloadToSendOptions(content);
1302
- return { ...content };
1344
+ function asBytes(data) {
1345
+ const src = data instanceof ArrayBuffer ? new Uint8Array(data) : new Uint8Array(data);
1346
+ const out = new Uint8Array(src.byteLength);
1347
+ out.set(src);
1348
+ return out;
1303
1349
  }
1304
- async function createMessageBody(content, referenced_message, ping) {
1305
- if (typeof content === "string" && content.length === 0) {
1306
- throw new FluxerError("Cannot send an empty message", { code: ErrorCodes.EmptyMessage });
1307
- }
1308
- const opts = toSendOptions(content);
1309
- if (referenced_message) {
1310
- opts.replyTo = toReplyTarget(referenced_message);
1311
- if (ping !== void 0) opts.ping = ping;
1350
+ async function putBlob(url, body, contentType) {
1351
+ const res = await fetch(url, {
1352
+ method: "PUT",
1353
+ headers: contentType ? { "Content-Type": contentType } : void 0,
1354
+ body
1355
+ });
1356
+ if (!res.ok) {
1357
+ throw new FluxerError(`Presigned upload failed: ${res.status}`, {
1358
+ code: ErrorCodes.AttachmentUploadFailed
1359
+ });
1312
1360
  }
1313
- return prepareMessagePostPayload(opts);
1314
1361
  }
1315
- function asReplyTarget(value) {
1316
- if ("messageId" in value) return value;
1317
- return {
1318
- channelId: value.channelId,
1319
- messageId: value.id,
1320
- guildId: value.guildId
1321
- };
1322
- }
1323
- async function sendPrepared(message, payload) {
1324
- const data = await message.client.rest.post(
1325
- Routes3.channelMessages(message.channelId),
1326
- payload
1327
- );
1328
- message.client._addMessageToCache(message.channelId, data);
1329
- return new message.constructor(message.client, data);
1330
- }
1331
- async function sendMessage(message, options) {
1332
- return message._send(
1333
- await prepareMessagePostPayload(options, {
1334
- defaultAllowedMentions: message.client.options.defaultAllowedMentions
1335
- })
1336
- );
1337
- }
1338
- async function sendMessageTo(message, channelId, options) {
1339
- return message.client.channels.send(channelId, options);
1340
- }
1341
- async function replyToMessage(message, options, replyOptions) {
1342
- const opts = typeof options === "string" ? { content: options } : { ...options };
1343
- const { replyTo: inlineReplyTo, ping: inlinePing, ...sendOpts } = opts;
1344
- const ping = replyOptions?.ping ?? inlinePing ?? message.client.options.defaultReplyPing;
1345
- const replyTo = asReplyTarget(replyOptions?.replyTo ?? inlineReplyTo ?? message);
1346
- return message._send(
1347
- await prepareMessagePostPayload(
1348
- { ...sendOpts, replyTo, ping },
1349
- { defaultAllowedMentions: message.client.options.defaultAllowedMentions }
1350
- )
1362
+ async function uploadAttachmentsForSend(client, channelId, files) {
1363
+ assertBotAttachmentLimits(client, files);
1364
+ const plan = await client.rest.post(
1365
+ Routes3.channelAttachments(channelId),
1366
+ {
1367
+ body: {
1368
+ attachments: files.map((f) => ({
1369
+ id: f.id,
1370
+ filename: f.filename,
1371
+ file_size: f.data.byteLength,
1372
+ content_type: f.contentType
1373
+ }))
1374
+ },
1375
+ auth: true
1376
+ }
1351
1377
  );
1378
+ const multipart = [];
1379
+ const uploaded = [];
1380
+ for (const item of plan.attachments) {
1381
+ const file = files.find((f) => f.id === item.id);
1382
+ if (!file) {
1383
+ throw new FluxerError(`No file data for planned attachment id ${item.id}`, {
1384
+ code: ErrorCodes.InvalidAttachmentInput
1385
+ });
1386
+ }
1387
+ const bytes = asBytes(file.data);
1388
+ if (item.upload_mode === "singlepart") {
1389
+ await putBlob(
1390
+ item.upload_url,
1391
+ new Blob([bytes], { type: file.contentType }),
1392
+ item.content_type
1393
+ );
1394
+ } else {
1395
+ for (const part of item.parts) {
1396
+ const start = (part.part_number - 1) * item.part_size;
1397
+ const chunk = bytes.subarray(start, Math.min(start + item.part_size, bytes.byteLength));
1398
+ await putBlob(part.upload_url, new Blob([asBytes(chunk)]));
1399
+ }
1400
+ multipart.push({ upload_filename: item.upload_filename, upload_id: item.upload_id });
1401
+ }
1402
+ uploaded.push({
1403
+ id: item.id,
1404
+ filename: item.filename,
1405
+ upload_filename: item.upload_filename,
1406
+ file_size: item.file_size,
1407
+ content_type: item.content_type
1408
+ });
1409
+ }
1410
+ if (multipart.length) {
1411
+ await client.rest.post(Routes3.channelAttachmentsComplete(channelId), {
1412
+ body: { uploads: multipart },
1413
+ auth: true
1414
+ });
1415
+ }
1416
+ return uploaded;
1352
1417
  }
1353
1418
 
1354
- // src/Domain/Message/Message.ts
1355
- function toMessageCall(data) {
1356
- return {
1357
- participants: data.participants,
1358
- endedAt: data.ended_timestamp ? new Date(data.ended_timestamp) : null
1359
- };
1360
- }
1361
- function toMessageSnapshot(client, data) {
1362
- return {
1363
- content: data.content ?? null,
1364
- createdAt: new Date(data.timestamp),
1365
- editedAt: data.edited_timestamp ? new Date(data.edited_timestamp) : null,
1366
- mentionUserIds: data.mentions ?? [],
1367
- mentionRoles: data.mention_roles ?? [],
1368
- embeds: (data.embeds ?? []).map(toMessageEmbed),
1369
- attachments: (data.attachments ?? []).map(toMessageAttachment),
1370
- stickers: (data.stickers ?? []).map((s) => new MessageSticker(client, s)),
1371
- ...data.type !== void 0 ? { type: data.type } : {}
1372
- };
1373
- }
1374
- function resolveMessageFlags(flags) {
1375
- if (flags === void 0) return void 0;
1376
- if (typeof flags === "number") return flags;
1377
- return Number(MessageFlagsBitField.resolve(flags));
1378
- }
1379
- var Message = class _Message extends Base {
1380
- /** Discriminant vs {@link PartialMessage}: always `false` on a hydrated Message. */
1381
- partial = false;
1382
- /** The {@link Client} that instantiated this message. */
1419
+ // src/Domain/Channel/Base.ts
1420
+ var Channel = class extends Base {
1421
+ #messages;
1422
+ /** The {@link Client} that instantiated this channel. */
1383
1423
  client;
1384
- /** Snowflake ID of this message. */
1424
+ /** Snowflake ID of this channel. */
1385
1425
  id;
1386
- /** Channel ID where this message was sent. */
1387
- channelId;
1388
- /** Guild ID if in a guild channel, null for DMs. */
1389
- guildId;
1390
- /** The user who sent this message. */
1391
- author;
1392
- /** Text content of the message. */
1393
- content;
1394
- /** When the message was created. */
1395
- createdAt;
1396
- /** When the message was last edited, or null if never edited. */
1397
- editedAt;
1398
- /** Whether the message is pinned. */
1399
- pinned;
1400
- /** Attached files (images, videos, etc.). */
1401
- attachments;
1402
- /** Message type (Default, Reply, etc.). */
1426
+ /** Channel type (text, voice, category, etc.). */
1403
1427
  type;
1404
- /** Message flags bitfield. */
1405
- flags;
1406
- /** Whether `@everyone` or `@here` was mentioned. */
1407
- mentionEveryone;
1408
- /** Whether this is a text-to-speech message. */
1409
- tts;
1410
- /** Embedded content (camelCase read view; send with {@link EmbedBuilder}). */
1411
- embeds;
1412
- /** Stickers sent with the message. */
1413
- stickers;
1414
- /** Reactions on the message. */
1415
- reactions;
1416
- /** Reference to a replied-to message, if any. */
1417
- messageReference;
1418
- /** Message snapshots for forwarded messages. */
1419
- messageSnapshots;
1420
- /** Call data if this message represents a call event. */
1421
- call;
1422
- /** The full referenced (replied-to) message, or null. */
1423
- referencedMessage;
1424
- /** Webhook ID if sent by a webhook. */
1425
- webhookId;
1426
- /** Users mentioned in the message. */
1427
- mentions;
1428
- /** Role IDs mentioned in the message. */
1429
- mentionRoles;
1430
- /** Client-side nonce for deduplication. */
1431
- nonce;
1432
- /** IDs of custom emojis in the message classified as explicit. */
1433
- nsfwEmojis;
1434
- /**
1435
- * Cached text-capable channel (guild text, guild voice, or DM), or null if uncached / not text-based.
1436
- * Narrowed type has {@link Channel.send} and {@link Channel.delete}.
1437
- */
1438
- get channel() {
1439
- const channel = this.client.channels.get(this.channelId) ?? null;
1440
- return channel?.isTextBased() ? channel : null;
1441
- }
1442
- /** Cached guild, or null for DMs / uncached. */
1443
- get guild() {
1444
- return this.guildId ? this.client.guilds.get(this.guildId) ?? null : null;
1445
- }
1446
- /** Cached guild member for the author, or null in DMs / if uncached. */
1447
- get member() {
1448
- return this.guild?.members.get(this.author.id) ?? null;
1449
- }
1450
- /**
1451
- * Fetch this message's channel (cache first). The returned {@link Channel}
1452
- * has {@link Channel.delete} and {@link Channel.send}.
1453
- * @example
1454
- * const channel = await message.resolveChannel();
1455
- * await channel.delete();
1456
- */
1457
- async resolveChannel() {
1458
- return this.client.channels.resolve(this.channelId);
1459
- }
1460
- /**
1461
- * Fetch and resolve the guild, or null if a DM.
1462
- * Propagates network/auth errors; only returns null when there is no guildId.
1463
- * @example
1464
- * const guild = await message.resolveGuild();
1465
- */
1466
- async resolveGuild() {
1467
- if (!this.guildId) return null;
1468
- return this.client.guilds.resolve(this.guildId);
1469
- }
1470
- /**
1471
- * Construct a message from API data.
1472
- * @param data - API message from REST or MESSAGE_CREATE
1473
- */
1428
+ /** Channel name (null for some channel types). */
1429
+ name;
1430
+ /** Channel icon hash (null for most channel types). */
1431
+ icon;
1432
+ /** ISO8601 timestamp of the last pinned message update. */
1433
+ lastPinTimestamp;
1474
1434
  constructor(client, data) {
1475
1435
  super();
1476
1436
  this.client = client;
1477
1437
  this.id = data.id;
1478
- this.channelId = data.channel_id;
1479
- this.guildId = data.guild_id ?? null;
1480
- this.author = client.getOrCreateUser(data.author);
1481
- this.content = data.content;
1482
- this.createdAt = new Date(data.timestamp);
1483
- this.editedAt = data.edited_timestamp ? new Date(data.edited_timestamp) : null;
1484
- this.pinned = data.pinned;
1485
- this.attachments = new Collection3();
1486
- for (const a of data.attachments ?? []) this.attachments.set(a.id, toMessageAttachment(a));
1487
- this.type = data.type ?? MessageType.Default;
1488
- this.flags = new MessageFlagsBitField(BigInt(data.flags ?? 0));
1489
- this.mentionEveryone = data.mention_everyone ?? false;
1490
- this.tts = data.tts ?? false;
1491
- this.embeds = (data.embeds ?? []).map(toMessageEmbed);
1492
- this.stickers = (data.stickers ?? []).map((s) => new MessageSticker(client, s));
1493
- this.reactions = new MessageReactionManager(this);
1494
- this.reactions._patch(data.reactions);
1495
- this.messageReference = data.message_reference ? {
1496
- channelId: data.message_reference.channel_id,
1497
- messageId: data.message_reference.message_id,
1498
- guildId: data.message_reference.guild_id ?? null,
1499
- ...data.message_reference.type !== void 0 ? { type: data.message_reference.type } : {}
1500
- } : null;
1501
- this.messageSnapshots = (data.message_snapshots ?? []).map((s) => toMessageSnapshot(client, s));
1502
- this.call = data.call ? toMessageCall(data.call) : null;
1503
- this.referencedMessage = data.referenced_message ? new _Message(client, data.referenced_message) : null;
1504
- this.webhookId = data.webhook_id ?? null;
1505
- this.mentions = (data.mentions ?? []).map((u) => client.getOrCreateUser(u));
1506
- this.mentionRoles = data.mention_roles ?? [];
1507
- this.nonce = data.nonce ?? null;
1508
- this.nsfwEmojis = data.nsfw_emojis ?? [];
1438
+ this.type = data.type;
1439
+ this.name = data.name ?? null;
1440
+ this.icon = data.icon ?? null;
1441
+ this.lastPinTimestamp = data.last_pin_timestamp ?? null;
1442
+ }
1443
+ /** Unix timestamp (ms) when this channel was created, derived from its snowflake ID. */
1444
+ get createdTimestamp() {
1445
+ return SnowflakeUtil.timestampFromSnowflake(this.id);
1446
+ }
1447
+ /** Date when this channel was created, derived from its snowflake ID. */
1448
+ get createdAt() {
1449
+ return SnowflakeUtil.dateFromSnowflake(this.id);
1509
1450
  }
1510
1451
  /**
1511
- * Apply an API message payload in place (cache identity / MESSAGE_UPDATE).
1452
+ * Apply shared channel fields in place (gateway CHANNEL_UPDATE when type is unchanged).
1512
1453
  * @internal
1513
1454
  */
1514
1455
  _patch(data) {
1515
- this.content = data.content;
1516
- this.editedAt = data.edited_timestamp ? new Date(data.edited_timestamp) : null;
1517
- this.pinned = data.pinned;
1518
- this.attachments.clear();
1519
- for (const a of data.attachments ?? []) this.attachments.set(a.id, toMessageAttachment(a));
1520
- this.flags = new MessageFlagsBitField(BigInt(data.flags ?? 0));
1521
- this.mentionEveryone = data.mention_everyone ?? false;
1522
- this.tts = data.tts ?? false;
1523
- this.embeds = (data.embeds ?? []).map(toMessageEmbed);
1524
- this.stickers = (data.stickers ?? []).map((s) => new MessageSticker(this.client, s));
1525
- this.reactions._patch(data.reactions);
1526
- this.messageReference = data.message_reference ? {
1527
- channelId: data.message_reference.channel_id,
1528
- messageId: data.message_reference.message_id,
1529
- guildId: data.message_reference.guild_id ?? null,
1530
- ...data.message_reference.type !== void 0 ? { type: data.message_reference.type } : {}
1531
- } : null;
1532
- this.messageSnapshots = (data.message_snapshots ?? []).map(
1533
- (s) => toMessageSnapshot(this.client, s)
1534
- );
1535
- this.call = data.call ? toMessageCall(data.call) : null;
1536
- this.referencedMessage = data.referenced_message ? new _Message(this.client, data.referenced_message) : null;
1537
- this.webhookId = data.webhook_id ?? null;
1538
- this.mentions = (data.mentions ?? []).map((u) => this.client.getOrCreateUser(u));
1539
- this.mentionRoles = data.mention_roles ?? [];
1540
- this.nonce = data.nonce ?? null;
1541
- this.nsfwEmojis = data.nsfw_emojis ?? [];
1456
+ if (data.type !== void 0) this.type = data.type;
1457
+ if (data.name !== void 0) this.name = data.name ?? null;
1458
+ if (data.icon !== void 0) this.icon = data.icon ?? null;
1459
+ if ("last_pin_timestamp" in data && data.last_pin_timestamp !== void 0) {
1460
+ this.lastPinTimestamp = data.last_pin_timestamp ?? null;
1461
+ }
1542
1462
  }
1543
- /**
1544
- * Send a standalone message in this channel (not a reply).
1545
- * Prefer {@link Channel.send} or {@link reply} when you already have the channel or are answering.
1546
- */
1547
- async send(options) {
1548
- return sendMessage(this, options);
1463
+ /** @internal Factory wired after subclasses load. */
1464
+ static from(_c, _d) {
1465
+ throw new Error("Channel.from not initialized");
1549
1466
  }
1550
- /**
1551
- * Send a message to another channel by ID.
1552
- * Prefer `client.channels.fetch(channelId)` then {@link Channel.send}.
1553
- */
1554
- async sendTo(channelId, options) {
1555
- return sendMessageTo(this, channelId, options);
1467
+ /** @internal Factory wired after subclasses load. */
1468
+ static fromOrCreate(_c, _d) {
1469
+ throw new Error("Channel.fromOrCreate not initialized");
1556
1470
  }
1557
- /**
1558
- * Reply to this message.
1559
- * @example
1560
- * await message.reply('Pong!');
1561
- * await message.reply('No ping!', { ping: false });
1562
- * await message.reply({ content: 'Silent', allowedMentions: AllowedMentions.suppressReplyPing });
1563
- */
1564
- async reply(options, replyOptions) {
1565
- return replyToMessage(this, options, replyOptions);
1471
+ /** @internal Factory wired after subclasses load. */
1472
+ static createDM(_c, _d) {
1473
+ throw new Error("Channel.createDM not initialized");
1566
1474
  }
1567
1475
  /**
1568
- * Hydrate a partial message, or return the message as-is.
1569
- * @example
1570
- * client.on(Events.MessageUpdate, async (_old, msg) => {
1571
- * const message = await Message.resolve(msg);
1572
- * });
1476
+ * Whether this channel type can carry messages (text, announcement, voice, threads, DM, group DM, notes).
1477
+ * Forum and media channels contain threads and do not accept `send`.
1478
+ * Checks {@link ChannelType}, not whether `send` exists on the instance.
1573
1479
  */
1574
- static async resolve(message) {
1575
- return message.partial ? message.fetch() : message;
1480
+ isTextBased() {
1481
+ return this.type === ChannelType3.GuildText || this.type === ChannelType3.GuildAnnouncement || this.type === ChannelType3.GuildVoice || this.type === ChannelType3.DM || this.type === ChannelType3.GroupDM || this.type === ChannelType3.DMPersonalNotes || this.type === ChannelType3.AnnouncementThread || this.type === ChannelType3.PublicThread || this.type === ChannelType3.PrivateThread;
1576
1482
  }
1577
- /** Test helper — prefer {@link reply} / `prepareMessagePostPayload()`. */
1578
- static async _createMessageBody(content, referenced_message, ping) {
1579
- return createMessageBody(content, referenced_message, ping);
1483
+ /** Check if this is a guild channel, including threads, forums, and media channels. */
1484
+ isGuild() {
1485
+ return this.type === ChannelType3.GuildText || this.type === ChannelType3.GuildAnnouncement || this.type === ChannelType3.GuildVoice || this.type === ChannelType3.GuildCategory || this.type === ChannelType3.GuildLink || this.type === ChannelType3.AnnouncementThread || this.type === ChannelType3.PublicThread || this.type === ChannelType3.PrivateThread || this.type === ChannelType3.GuildForum || this.type === ChannelType3.GuildMedia;
1580
1486
  }
1581
- /** Send a prepared payload (internal helper). */
1582
- async _send(payload) {
1583
- return sendPrepared(this, payload);
1487
+ /** Check if this is a thread (public, private, or announcement). */
1488
+ isThread() {
1489
+ return this.type === ChannelType3.AnnouncementThread || this.type === ChannelType3.PublicThread || this.type === ChannelType3.PrivateThread;
1584
1490
  }
1585
- /** Edit this message (requires author or admin permissions). */
1586
- async edit(options) {
1587
- const body = {};
1588
- if (options.content !== void 0) body.content = options.content;
1589
- if (options.embeds !== void 0) {
1590
- body.embeds = options.embeds.map(
1591
- (e) => e instanceof EmbedBuilder2 ? e.toJSON() : e
1592
- );
1491
+ /** Check if this is a forum channel. */
1492
+ isForum() {
1493
+ return this.type === ChannelType3.GuildForum;
1494
+ }
1495
+ /** Check if this is a media channel. */
1496
+ isMedia() {
1497
+ return this.type === ChannelType3.GuildMedia;
1498
+ }
1499
+ /** Check if this is a guild text channel. */
1500
+ isText() {
1501
+ return this.type === ChannelType3.GuildText;
1502
+ }
1503
+ /** Check if this is a guild announcement channel. */
1504
+ isAnnouncement() {
1505
+ return this.type === ChannelType3.GuildAnnouncement;
1506
+ }
1507
+ /** Check if this is a category channel. */
1508
+ isCategory() {
1509
+ return this.type === ChannelType3.GuildCategory;
1510
+ }
1511
+ /** Check if this is a DM, group DM, or personal notes channel. */
1512
+ isDM() {
1513
+ return this.type === ChannelType3.DM || this.type === ChannelType3.GroupDM || this.type === ChannelType3.DMPersonalNotes;
1514
+ }
1515
+ /** Check if this is a personal notes channel. */
1516
+ isPersonalNotes() {
1517
+ return this.type === ChannelType3.DMPersonalNotes;
1518
+ }
1519
+ /** Check if this is a voice channel. */
1520
+ isVoice() {
1521
+ return this.type === ChannelType3.GuildVoice;
1522
+ }
1523
+ /** Check if this is a link channel. */
1524
+ isLink() {
1525
+ return this.type === ChannelType3.GuildLink;
1526
+ }
1527
+ /**
1528
+ * Delete recent messages or an explicit ID list.
1529
+ * - `bulkDelete(5)` — fetch last 5 via {@link MessageManager} then delete (1–100)
1530
+ * - `bulkDelete(['id1'])` — single DELETE; 2–100 uses bulk-delete route
1531
+ */
1532
+ async bulkDelete(countOrIds) {
1533
+ let ids;
1534
+ if (typeof countOrIds === "number") {
1535
+ if (!Number.isInteger(countOrIds) || countOrIds < 1 || countOrIds > 100) {
1536
+ throw new FluxerError("bulkDelete count must be between 1 and 100", {
1537
+ code: ErrorCodes.InvalidBulkDelete
1538
+ });
1539
+ }
1540
+ ids = [
1541
+ ...(await new MessageManager(this.client, this.id).fetch({ limit: countOrIds })).keys()
1542
+ ];
1543
+ } else {
1544
+ ids = [...countOrIds];
1593
1545
  }
1594
- if (options.allowedMentions) {
1595
- body.allowed_mentions = toAPIAllowedMentions(options.allowedMentions);
1546
+ if (ids.length === 0) return [];
1547
+ if (ids.length === 1) {
1548
+ await this.client.rest.delete(Routes4.channelMessage(this.id, ids[0]), { auth: true });
1549
+ this.client._removeMessageFromCache(this.id, ids[0]);
1550
+ return ids;
1596
1551
  }
1597
- const flags = resolveMessageFlags(options.flags);
1598
- if (flags !== void 0) body.flags = flags;
1599
- if (options.attachments !== void 0) {
1600
- body.attachments = toMessageAttachmentEditWire(options.attachments);
1552
+ if (ids.length > 100) {
1553
+ throw new FluxerError("bulkDelete requires at most 100 message IDs", {
1554
+ code: ErrorCodes.InvalidBulkDelete
1555
+ });
1601
1556
  }
1602
- const data = await this.client.rest.patch(Routes4.channelMessage(this.channelId, this.id), {
1603
- body
1557
+ await this.client.rest.post(Routes4.channelBulkDelete(this.id), {
1558
+ body: { message_ids: ids },
1559
+ auth: true
1560
+ });
1561
+ for (const id of ids) this.client._removeMessageFromCache(this.id, id);
1562
+ return ids;
1563
+ }
1564
+ /** Delete all messages sent by the bot in this channel. Sudo auto-passes for bots. */
1565
+ async bulkDeleteMyMessages(options) {
1566
+ const body = options ? toSudoBody(options) : void 0;
1567
+ await this.client.rest.post(Routes4.channelBulkDeleteMine(this.id), {
1568
+ body: body && Object.keys(body).length ? body : void 0,
1569
+ auth: true
1604
1570
  });
1605
- const updated = new _Message(this.client, data);
1606
- this.client._addMessageToCache(this.channelId, data);
1607
- return updated;
1608
1571
  }
1609
- /** Create a {@link ReactionCollector} for this message. */
1610
- createReactionCollector(options) {
1611
- return new ReactionCollector(this.client, this.id, this.channelId, options);
1572
+ /**
1573
+ * Mark all pinned messages as read in this channel.
1574
+ * Session-token helper; bots usually skip this.
1575
+ */
1576
+ async acknowledgePins() {
1577
+ await this.client.rest.post(Routes4.channelPinsAck(this.id), { auth: true });
1612
1578
  }
1613
1579
  /**
1614
- * Wait for reactions matching the filter, then resolve the collected set.
1615
- * Pass `errors: ['time']` to reject when the timer fires instead of resolving.
1580
+ * Clear the read state for this channel.
1581
+ * Session-token helper; bots usually skip this.
1616
1582
  */
1617
- awaitReactions(options) {
1618
- return ReactionCollector.awaitReactions(this.client, this.id, this.channelId, options);
1583
+ async clearReadState() {
1584
+ await this.client.rest.delete(Routes4.channelMessagesAck(this.id), { auth: true });
1619
1585
  }
1620
- /** Fetch the latest version of this message from the API. */
1621
- async fetch() {
1622
- return this.client.channels.fetchMessage(this.channelId, this.id);
1586
+ /** Request upload URLs for attachments before sending a message. */
1587
+ async requestAttachmentUploads(attachments) {
1588
+ const data = await this.client.rest.post(
1589
+ Routes4.channelAttachments(this.id),
1590
+ {
1591
+ body: toAttachmentUploadPlanBody(attachments),
1592
+ auth: true
1593
+ }
1594
+ );
1595
+ return toAttachmentUploadPlanResponse(data);
1623
1596
  }
1624
- /** Delete this message. */
1625
- async delete(reason) {
1626
- await this.client.rest.delete(Routes4.channelMessage(this.channelId, this.id), {
1627
- ...auditReasonHeaders(reason)
1597
+ /** Complete the attachment upload flow after uploading to the CDN. */
1598
+ async completeAttachmentUploads(uploads) {
1599
+ const data = await this.client.rest.post(
1600
+ Routes4.channelAttachmentsComplete(this.id),
1601
+ {
1602
+ body: toAttachmentUploadCompleteBody(uploads),
1603
+ auth: true
1604
+ }
1605
+ );
1606
+ return {
1607
+ uploads: data.uploads.map((u) => ({ uploadFilename: u.upload_filename }))
1608
+ };
1609
+ }
1610
+ /** Upload files for sending in a message (helper). */
1611
+ async uploadAttachmentsForSend(files) {
1612
+ return uploadAttachmentsForSend(this.client, this.id, files);
1613
+ }
1614
+ /** Trigger the typing indicator in this channel. */
1615
+ async sendTyping() {
1616
+ await this.client.rest.post(Routes4.channelTyping(this.id), { auth: true });
1617
+ }
1618
+ /**
1619
+ * Fetch available RTC regions for voice channels.
1620
+ * User-account only (`DefaultUserOnly`); bots receive `AccessDeniedError`.
1621
+ * Bots should skip this and join voice with `@fluxerjs/voice` instead.
1622
+ */
1623
+ async fetchRtcRegions() {
1624
+ const data = await this.client.rest.get(Routes4.channelRtcRegions(this.id), {
1625
+ auth: true
1628
1626
  });
1629
- this.client._removeMessageFromCache(this.channelId, this.id);
1627
+ return data.map((r) => ({ id: r.id, name: r.name, emoji: r.emoji }));
1630
1628
  }
1631
- /** Delete a specific attachment from this message. */
1632
- async deleteAttachment(attachmentId) {
1633
- await this.client.rest.delete(
1634
- Routes4.channelMessageAttachment(this.channelId, this.id, attachmentId),
1629
+ /** Fetch slowmode state for this channel. */
1630
+ async fetchSlowmode() {
1631
+ const data = await this.client.rest.get(
1632
+ Routes4.channelSlowmode(this.id),
1635
1633
  { auth: true }
1636
1634
  );
1637
- this.attachments.delete(attachmentId);
1635
+ return {
1636
+ rateLimitPerUser: data.rate_limit_per_user,
1637
+ retryAfterMs: data.retry_after_ms,
1638
+ nextSendAllowedAt: data.next_send_allowed_at
1639
+ };
1638
1640
  }
1639
- /** Pin this message in the channel. */
1640
- async pin() {
1641
- await this.client.rest.put(Routes4.channelPinMessage(this.channelId, this.id));
1642
- this.pinned = true;
1641
+ /** Whether this channel type can carry messages (does not check permissions). */
1642
+ canSendMessage() {
1643
+ return this.isTextBased();
1643
1644
  }
1644
- /** Unpin this message from the channel. */
1645
- async unpin() {
1646
- await this.client.rest.delete(Routes4.channelPinMessage(this.channelId, this.id));
1647
- this.pinned = false;
1645
+ /** Per-channel message cache + fetch. */
1646
+ get messages() {
1647
+ if (!this.#messages) {
1648
+ this.#messages = new MessageManager(this.client, this.id);
1649
+ }
1650
+ return this.#messages;
1648
1651
  }
1649
- /** React to this message with an emoji. */
1650
- async react(emoji) {
1651
- return reactToMessage(this, emoji);
1652
+ /** Collect messages in this channel until time/max/stop. */
1653
+ createMessageCollector(options) {
1654
+ return new MessageCollector(this.client, this.id, options);
1652
1655
  }
1653
- /** Remove a reaction (bot's own or a user's if ID is provided). */
1654
- async removeReaction(emoji, userId) {
1655
- return removeMessageReaction(this, emoji, userId);
1656
+ /**
1657
+ * Wait for messages matching the filter, then resolve the collected set.
1658
+ * Pass `errors: ['time']` to reject when the timer fires instead of resolving.
1659
+ * @example
1660
+ * const collected = await channel.awaitMessages({ max: 1, time: 15_000 });
1661
+ */
1662
+ awaitMessages(options) {
1663
+ return MessageCollector.awaitMessages(this.client, this.id, options);
1656
1664
  }
1657
- /** Remove all reactions from this message. */
1658
- async removeAllReactions() {
1659
- return removeAllMessageReactions(this);
1665
+ /**
1666
+ * Delete this channel (or close it if it is a DM).
1667
+ * Guild channels require Manage Channels. `silent` / `deleteMessages` are Fluxer query params.
1668
+ * @example
1669
+ * const channel = await client.channels.fetch(channelId);
1670
+ * await channel.delete();
1671
+ */
1672
+ async delete(options) {
1673
+ const params = new URLSearchParams();
1674
+ if (options?.silent) params.set("silent", "true");
1675
+ if (options?.deleteMessages) params.set("delete_messages", "true");
1676
+ const qs2 = params.toString();
1677
+ const { silent: _s, deleteMessages: _d, reason: _reason, ...sudo } = options ?? {};
1678
+ const body = Object.keys(sudo).length ? toSudoBody(sudo) : void 0;
1679
+ await this.client.rest.delete(Routes4.channel(this.id) + (qs2 ? `?${qs2}` : ""), {
1680
+ body,
1681
+ auth: true,
1682
+ ...auditReasonHeaders(_reason)
1683
+ });
1684
+ this.client.channels.delete(this.id);
1685
+ this.client._clearMessageCache(this.id);
1686
+ if (this.isGuild() && this.guildId) {
1687
+ this.client.guilds.get(this.guildId)?.channels.delete(this.id);
1688
+ }
1660
1689
  }
1661
- /** Remove all reactions of a specific emoji. */
1662
- async removeReactionEmoji(emoji) {
1663
- return removeMessageReactionEmoji(this, emoji);
1690
+ /** Channel mention (`<#id>`). */
1691
+ toString() {
1692
+ return `<#${this.id}>`;
1664
1693
  }
1665
- /** Fetch users who reacted with a specific emoji. */
1666
- async fetchReactionUsers(emoji, options) {
1667
- return fetchMessageReactionUsers(this, emoji, options);
1694
+ };
1695
+
1696
+ // src/Domain/Channel/ThreadCache.ts
1697
+ function cacheThread(client, data) {
1698
+ const existing = client.channels.get(data.id);
1699
+ if (existing?.isThread() && existing.type === data.type) {
1700
+ existing._patch(data);
1701
+ placeThread(client, existing);
1702
+ return existing;
1668
1703
  }
1669
- /** Fetch reaction users with pagination metadata. */
1670
- async fetchReactionUsersPage(emoji, options) {
1671
- return fetchMessageReactionUsersPage(this, emoji, options);
1704
+ const created = Channel.from(client, data);
1705
+ if (!created.isThread()) {
1706
+ throw new FluxerError(`Channel ${data.id} is not a thread`, {
1707
+ code: ErrorCodes.InvalidChannelType
1708
+ });
1672
1709
  }
1673
- };
1710
+ placeThread(client, created);
1711
+ return created;
1712
+ }
1713
+ function placeThread(client, thread) {
1714
+ client.channels.set(thread.id, thread);
1715
+ if (!thread.guildId) return;
1716
+ const guild = client.guilds.get(thread.guildId);
1717
+ if (guild) guild.channels.set(thread.id, thread);
1718
+ }
1674
1719
 
1675
- // src/Domain/Message/PartialMessage.ts
1676
- import { SnowflakeUtil as SnowflakeUtil2 } from "@fluxerjs/util";
1677
- var PartialMessage = class {
1678
- partial = true;
1679
- client;
1680
- id;
1681
- channelId;
1682
- guildId;
1683
- content;
1684
- authorId;
1685
- author;
1686
- createdAt;
1687
- constructor(client, data) {
1688
- this.client = client;
1689
- this.id = data.id;
1690
- this.channelId = data.channelId;
1691
- this.guildId = data.guildId ?? null;
1692
- this.content = data.content ?? null;
1693
- this.authorId = data.authorId ?? null;
1694
- this.author = data.author ?? null;
1695
- this.createdAt = data.createdAt ?? (SnowflakeUtil2.isValid(data.id) ? SnowflakeUtil2.dateFromSnowflake(data.id) : null);
1720
+ // src/Domain/Message/Attachment.ts
1721
+ function toMessageAttachment(data) {
1722
+ return {
1723
+ id: data.id,
1724
+ filename: data.filename,
1725
+ title: data.title ?? null,
1726
+ description: data.description ?? null,
1727
+ contentType: data.content_type ?? null,
1728
+ contentHash: data.content_hash ?? null,
1729
+ size: data.size,
1730
+ url: data.url ?? null,
1731
+ proxyUrl: data.proxy_url ?? null,
1732
+ width: data.width ?? null,
1733
+ height: data.height ?? null,
1734
+ placeholder: data.placeholder ?? null,
1735
+ flags: data.flags ?? 0,
1736
+ nsfw: data.nsfw ?? false,
1737
+ duration: data.duration ?? null,
1738
+ waveform: data.waveform ?? null,
1739
+ expiresAt: data.expires_at ? new Date(data.expires_at) : null,
1740
+ expired: data.expired ?? false
1741
+ };
1742
+ }
1743
+
1744
+ // src/Domain/Message/Embed.ts
1745
+ function toMessageEmbedAuthor(data) {
1746
+ return {
1747
+ name: data.name ?? null,
1748
+ url: data.url ?? null,
1749
+ iconUrl: data.icon_url ?? null,
1750
+ proxyIconUrl: data.proxy_icon_url ?? null
1751
+ };
1752
+ }
1753
+ function toMessageEmbedFooter(data) {
1754
+ return {
1755
+ text: data.text,
1756
+ iconUrl: data.icon_url ?? null,
1757
+ proxyIconUrl: data.proxy_icon_url ?? null
1758
+ };
1759
+ }
1760
+ function toMessageEmbedMedia(data) {
1761
+ return {
1762
+ url: data.url,
1763
+ proxyUrl: data.proxy_url ?? null,
1764
+ contentType: data.content_type ?? null,
1765
+ contentHash: data.content_hash ?? null,
1766
+ width: data.width ?? null,
1767
+ height: data.height ?? null,
1768
+ description: data.description ?? null,
1769
+ placeholder: data.placeholder ?? null,
1770
+ duration: data.duration ?? null,
1771
+ flags: data.flags ?? null
1772
+ };
1773
+ }
1774
+ function toMessageEmbed(data) {
1775
+ const full = data;
1776
+ return {
1777
+ type: data.type ?? "rich",
1778
+ url: data.url ?? null,
1779
+ title: data.title ?? null,
1780
+ color: data.color ?? null,
1781
+ timestamp: data.timestamp ? new Date(data.timestamp) : null,
1782
+ description: data.description ?? null,
1783
+ author: data.author ? toMessageEmbedAuthor(data.author) : null,
1784
+ image: data.image ? toMessageEmbedMedia(data.image) : null,
1785
+ thumbnail: data.thumbnail ? toMessageEmbedMedia(data.thumbnail) : null,
1786
+ footer: data.footer ? toMessageEmbedFooter(data.footer) : null,
1787
+ fields: (data.fields ?? []).map((f) => ({
1788
+ name: f.name,
1789
+ value: f.value,
1790
+ inline: f.inline ?? false
1791
+ })),
1792
+ provider: data.provider ? toMessageEmbedAuthor(data.provider) : null,
1793
+ video: data.video ? toMessageEmbedMedia(data.video) : null,
1794
+ audio: data.audio ? toMessageEmbedMedia(data.audio) : null,
1795
+ nsfw: data.nsfw ?? false,
1796
+ children: (full.children ?? []).map(toMessageEmbed),
1797
+ html: full.html ?? null,
1798
+ htmlWidth: full.html_width ?? null,
1799
+ htmlHeight: full.html_height ?? null
1800
+ };
1801
+ }
1802
+
1803
+ // src/Domain/Message/MessageReactionManager.ts
1804
+ import { Collection as Collection4 } from "@fluxerjs/collection";
1805
+ var MessageReactionManager = class {
1806
+ constructor(message) {
1807
+ this.message = message;
1696
1808
  }
1697
- /**
1698
- * Live text-capable channel from cache, or null if uncached / not text-based.
1699
- * Same contract as {@link Message.channel}.
1700
- */
1701
- get channel() {
1702
- const channel = this.client.channels.get(this.channelId) ?? null;
1703
- return channel?.isTextBased() ? channel : null;
1809
+ _cache = new Collection4();
1810
+ /** Reactions keyed by unicode name or `name:id`. */
1811
+ get cache() {
1812
+ return this._cache;
1704
1813
  }
1705
- /**
1706
- * Fetch this message's channel (cache first). The returned {@link Channel}
1707
- * has {@link Channel.delete} and {@link Channel.send}.
1708
- * @example
1709
- * const channel = await message.resolveChannel();
1710
- * await channel.delete();
1711
- */
1712
- async resolveChannel() {
1713
- return this.client.channels.resolve(this.channelId);
1814
+ get size() {
1815
+ return this._cache.size;
1714
1816
  }
1715
- /**
1716
- * Fetch the full message from the API.
1717
- * @example
1718
- * const message = await partial.fetch();
1719
- * await message.reply('Pong!');
1720
- */
1721
- async fetch() {
1722
- return this.client.channels.fetchMessage(this.channelId, this.id);
1817
+ [Symbol.iterator]() {
1818
+ return this._cache.values();
1819
+ }
1820
+ /** @internal Sync from an API message payload. */
1821
+ _patch(reactions) {
1822
+ this._cache.clear();
1823
+ for (const data of reactions ?? []) {
1824
+ const reaction = MessageReaction.fromMessage(this.message, data);
1825
+ this._cache.set(reaction.emojiIdentifier, reaction);
1826
+ }
1723
1827
  }
1724
1828
  };
1725
1829
 
1726
- // src/Domain/User.ts
1727
- import { Routes as Routes14 } from "@fluxerjs/types";
1728
- import { SnowflakeUtil as SnowflakeUtil5 } from "@fluxerjs/util";
1830
+ // src/Domain/Message/MessageSticker.ts
1831
+ import { SnowflakeUtil as SnowflakeUtil2 } from "@fluxerjs/util";
1729
1832
 
1730
- // src/Domain/Channel/Base.ts
1731
- import { ChannelType, Routes as Routes7 } from "@fluxerjs/types";
1732
- import { SnowflakeUtil as SnowflakeUtil3 } from "@fluxerjs/util";
1833
+ // src/Helpers/Constants.ts
1834
+ import { DEFAULT_USER_AGENT } from "@fluxerjs/rest";
1835
+ var CDN_URL = "https://fluxerusercontent.com";
1836
+ var STATIC_CDN_URL = "https://fluxerstatic.com";
1733
1837
 
1734
- // src/ClientCore/MessageManager.ts
1735
- import { Collection as Collection4 } from "@fluxerjs/collection";
1736
- import { Routes as Routes5 } from "@fluxerjs/types";
1737
- var BULK = {
1738
- requests: { min: 1, max: 25 },
1739
- limit: { min: 1, max: 25 },
1740
- totalMax: 250
1838
+ // src/Helpers/Cdn.ts
1839
+ var CDN_SIZE_LADDER = [
1840
+ 16,
1841
+ 20,
1842
+ 22,
1843
+ 24,
1844
+ 28,
1845
+ 32,
1846
+ 40,
1847
+ 44,
1848
+ 48,
1849
+ 56,
1850
+ 60,
1851
+ 64,
1852
+ 80,
1853
+ 96,
1854
+ 100,
1855
+ 128,
1856
+ 160,
1857
+ 240,
1858
+ 256,
1859
+ 300,
1860
+ 320,
1861
+ 480,
1862
+ 512,
1863
+ 600,
1864
+ 640,
1865
+ 1024,
1866
+ 1280,
1867
+ 1536,
1868
+ 2048,
1869
+ 3072,
1870
+ 4096,
1871
+ 8192,
1872
+ 16384
1873
+ ];
1874
+ var CDN_ASSET_CLASS_RANGE = {
1875
+ icon: { min: 128, max: 1024 },
1876
+ banner: { min: 480, max: 2400 },
1877
+ emoji: { min: 32, max: 512 },
1878
+ sticker: { min: 128, max: 512 }
1741
1879
  };
1742
- function validateBulkMessageFetchRequests(requests) {
1743
- const { requests: req, limit, totalMax } = BULK;
1744
- if (requests.length < req.min || requests.length > req.max) {
1745
- throw new FluxerError(`bulkFetchMessages requires between ${req.min} and ${req.max} requests`, {
1746
- code: ErrorCodes.InvalidFetchLimit
1747
- });
1748
- }
1749
- let total = 0;
1750
- for (const request of requests) {
1751
- if (request.limit < limit.min || request.limit > limit.max) {
1752
- throw new FluxerError(
1753
- `limit must be between ${limit.min} and ${limit.max} for channel ${request.channelId}`,
1754
- { code: ErrorCodes.InvalidFetchLimit }
1755
- );
1880
+ function nearestSize(requested, candidates) {
1881
+ let best = candidates[0];
1882
+ let bestDist = Math.abs(requested - best);
1883
+ for (let i = 1; i < candidates.length; i++) {
1884
+ const step = candidates[i];
1885
+ const dist = Math.abs(requested - step);
1886
+ if (dist < bestDist || dist === bestDist && step > best) {
1887
+ best = step;
1888
+ bestDist = dist;
1756
1889
  }
1757
- total += request.limit;
1758
- }
1759
- if (total > totalMax) {
1760
- throw new FluxerError(`bulkFetchMessages total message limit must not exceed ${totalMax}`, {
1761
- code: ErrorCodes.InvalidFetchLimit
1762
- });
1763
1890
  }
1891
+ return best;
1764
1892
  }
1765
- var MessageManager = class {
1766
- constructor(client, channelId) {
1767
- this.client = client;
1768
- this.channelId = channelId;
1769
- }
1770
- /** Structure cache keyed by message id (identity for {@link get}). */
1771
- _structures = new Collection4();
1772
- /** Retrieve a cached message by ID, or `undefined` if missing / caching disabled. */
1773
- get(messageId) {
1774
- const data = this.client._getMessageCache(this.channelId)?.get(messageId);
1775
- if (!data) {
1776
- this._structures.delete(messageId);
1777
- return void 0;
1778
- }
1779
- const existing = this._structures.get(messageId);
1780
- if (existing) return existing;
1781
- const message = new Message(this.client, data);
1782
- this._structures.set(messageId, message);
1783
- return message;
1784
- }
1785
- /** Retrieve from cache, otherwise {@link fetch}. */
1786
- async resolve(messageId) {
1787
- return this.get(messageId) ?? this.fetch(messageId);
1788
- }
1789
- async fetch(idOrOptions) {
1790
- return typeof idOrOptions === "string" ? this.fetchOne(idOrOptions) : this.fetchMany(idOrOptions);
1791
- }
1792
- /** Cache API data and return a {@link Message} (reusing identity when present). */
1793
- wrap(data) {
1794
- this.client._addMessageToCache(this.channelId, data);
1795
- const cached = this.client._getMessageCache(this.channelId)?.get(data.id) ?? data;
1796
- const existing = this._structures.get(data.id);
1797
- if (existing) {
1798
- existing._patch(cached);
1799
- return existing;
1800
- }
1801
- const message = new Message(this.client, cached);
1802
- this._structures.set(data.id, message);
1803
- return message;
1804
- }
1805
- /** Fetch a single message from the API. */
1806
- async fetchOne(messageId) {
1807
- try {
1808
- const data = await this.client.rest.get(
1809
- Routes5.channelMessage(this.channelId, messageId)
1810
- );
1811
- return this.wrap(data);
1812
- } catch (err) {
1813
- rethrowMapped(err, {
1814
- notFound: {
1815
- code: ErrorCodes.MessageNotFound,
1816
- message: `Message ${messageId} not found in channel ${this.channelId}`
1817
- },
1818
- fallback: `Failed to fetch message ${messageId}`
1819
- });
1820
- }
1821
- }
1822
- /** Fetch multiple messages from the API with pagination/filtering. */
1823
- async fetchMany(options) {
1824
- if (options.limit != null && (options.limit < 1 || options.limit > 100)) {
1825
- throw new FluxerError("limit must be between 1 and 100", {
1826
- code: ErrorCodes.InvalidFetchLimit
1827
- });
1828
- }
1829
- const qs2 = new URLSearchParams();
1830
- for (const key of ["limit", "before", "after", "around"]) {
1831
- const value = options[key];
1832
- if (value != null && value !== "") qs2.set(key, String(value));
1833
- }
1834
- const base = Routes5.channelMessages(this.channelId);
1835
- const data = await this.client.rest.get(qs2.size > 0 ? `${base}?${qs2}` : base);
1836
- const collection = new Collection4();
1837
- for (const msg of data) collection.set(msg.id, this.wrap(msg));
1838
- return collection;
1839
- }
1840
- };
1841
-
1842
- // src/Helpers/MessageCollector.ts
1843
- import { EventEmitter as EventEmitter2 } from "events";
1844
- import { Collection as Collection5 } from "@fluxerjs/collection";
1845
- function requireCollectorBounds(options) {
1846
- const time = options.time ?? 0;
1847
- const max = options.max ?? 0;
1848
- if (time <= 0 && max <= 0) {
1849
- throw new FluxerError("MessageCollector requires `time` and/or `max`", {
1850
- code: ErrorCodes.CollectorOptionsRequired
1851
- });
1852
- }
1893
+ function snapCdnSize(requested, assetClass) {
1894
+ const { min, max } = CDN_ASSET_CLASS_RANGE[assetClass];
1895
+ const snapped = nearestSize(requested, CDN_SIZE_LADDER);
1896
+ const clamped = Math.min(max, Math.max(min, snapped));
1897
+ const allowed = CDN_SIZE_LADDER.filter((step) => step >= min && step <= max);
1898
+ return nearestSize(clamped, allowed);
1899
+ }
1900
+ function mediaBase(options) {
1901
+ return (options?.mediaBase ?? CDN_URL).replace(/\/+$/, "");
1902
+ }
1903
+ function staticBase(options) {
1904
+ return (options?.staticCdnBase ?? STATIC_CDN_URL).replace(/\/+$/, "");
1905
+ }
1906
+ function getExtension(hash, options) {
1907
+ const ext = options?.extension ?? "png";
1908
+ if (hash?.startsWith("a_")) return "gif";
1909
+ return ext;
1910
+ }
1911
+ function appendSize(options, assetClass) {
1912
+ const size = options?.size;
1913
+ if (size == null || !Number.isFinite(size) || size <= 0) return "";
1914
+ return `?size=${snapCdnSize(size, assetClass)}`;
1915
+ }
1916
+ function cdnAvatarURL(userId, avatarHash, options) {
1917
+ if (!avatarHash) return null;
1918
+ const ext = getExtension(avatarHash, options);
1919
+ const size = appendSize(options, "icon");
1920
+ return `${mediaBase(options)}/avatars/${userId}/${avatarHash}.${ext}${size}`;
1921
+ }
1922
+ function cdnBannerURL(resourceId, bannerHash, options) {
1923
+ if (!bannerHash) return null;
1924
+ const ext = getExtension(bannerHash, options);
1925
+ const size = appendSize(options, "banner");
1926
+ return `${mediaBase(options)}/banners/${resourceId}/${bannerHash}.${ext}${size}`;
1927
+ }
1928
+ function cdnMemberAvatarURL(guildId, userId, avatarHash, options) {
1929
+ if (!avatarHash) return null;
1930
+ const ext = getExtension(avatarHash, options);
1931
+ const size = appendSize(options, "icon");
1932
+ return `${mediaBase(options)}/guilds/${guildId}/users/${userId}/avatars/${avatarHash}.${ext}${size}`;
1933
+ }
1934
+ function cdnMemberBannerURL(guildId, userId, bannerHash, options) {
1935
+ if (!bannerHash) return null;
1936
+ const ext = getExtension(bannerHash, options);
1937
+ const size = appendSize(options, "banner");
1938
+ return `${mediaBase(options)}/guilds/${guildId}/users/${userId}/banners/${bannerHash}.${ext}${size}`;
1853
1939
  }
1854
- var MessageCollector = class _MessageCollector extends EventEmitter2 {
1940
+ function cdnDefaultAvatarURL(userIdOrIndex, options) {
1941
+ const index = typeof userIdOrIndex === "string" ? Number(BigInt(userIdOrIndex) % 6n) : Math.abs(Math.floor(userIdOrIndex) % 6);
1942
+ return `${staticBase(options)}/avatars/${index}.png`;
1943
+ }
1944
+ function cdnGuildAssetURL(kind, id, hash, options) {
1945
+ if (!hash) return null;
1946
+ const assetClass = kind === "icons" ? "icon" : "banner";
1947
+ const size = appendSize(options, assetClass);
1948
+ return `${mediaBase(options)}/${kind}/${id}/${hash}.png${size}`;
1949
+ }
1950
+ function cdnEmojiURL(emojiId, animated, options) {
1951
+ const ext = animated ? "gif" : "png";
1952
+ const size = appendSize(options, "emoji");
1953
+ return `${mediaBase(options)}/emojis/${emojiId}.${ext}${size}`;
1954
+ }
1955
+ function cdnStickerURL(stickerId, animated, options) {
1956
+ const ext = animated ? "gif" : "png";
1957
+ const size = appendSize(options, "sticker");
1958
+ return `${mediaBase(options)}/stickers/${stickerId}.${ext}${size}`;
1959
+ }
1960
+
1961
+ // src/Domain/Message/MessageSticker.ts
1962
+ var MessageSticker = class extends Base {
1855
1963
  client;
1856
- channelId;
1857
- options;
1858
- collected = new Collection5();
1859
- _timeout = null;
1860
- _ended = false;
1861
- _listener;
1862
- constructor(client, channelId, options = {}) {
1964
+ id;
1965
+ name;
1966
+ description;
1967
+ tags;
1968
+ animated;
1969
+ constructor(client, data) {
1863
1970
  super();
1864
- requireCollectorBounds(options);
1865
1971
  this.client = client;
1866
- this.channelId = channelId;
1867
- this.options = {
1868
- filter: options.filter ?? (() => true),
1869
- time: options.time ?? 0,
1870
- max: options.max ?? 0
1871
- };
1872
- this._listener = (message) => {
1873
- if (this._ended || message.channelId !== this.channelId) return;
1874
- if (!this.options.filter(message)) return;
1875
- this.collected.set(message.id, message);
1876
- this.emit("collect", message);
1877
- if (this.options.max > 0 && this.collected.size >= this.options.max) {
1878
- this.stop("limit");
1879
- }
1880
- };
1881
- this.client.on(Events.MessageCreate, this._listener);
1882
- if (this.options.time > 0) {
1883
- this._timeout = setTimeout(() => this.stop("time"), this.options.time);
1884
- }
1885
- }
1886
- stop(reason = "user") {
1887
- if (this._ended) return;
1888
- this._ended = true;
1889
- this.client.off(Events.MessageCreate, this._listener);
1890
- if (this._timeout) {
1891
- clearTimeout(this._timeout);
1892
- this._timeout = null;
1893
- }
1894
- this.emit("end", this.collected, reason);
1972
+ this.id = data.id;
1973
+ this.name = data.name;
1974
+ this.description = data.description ?? "";
1975
+ this.tags = data.tags ?? [];
1976
+ this.animated = data.animated ?? false;
1895
1977
  }
1896
- /**
1897
- * One-shot helper used by {@link Channel.awaitMessages}.
1898
- * Resolves with the collected messages when the collector ends for `user` (or when
1899
- * the end reason is not listed in `errors`).
1900
- * By default, `time` and `limit` reject with {@link FluxerError}
1901
- * (`CollectorIdle` / `CollectorMax`).
1902
- */
1903
- static awaitMessages(client, channelId, options) {
1904
- const errors = options?.errors ?? ["time", "limit"];
1905
- return new Promise((resolve, reject) => {
1906
- const collector = new _MessageCollector(client, channelId, options);
1907
- collector.on("end", (collected, reason) => {
1908
- if (!errors.includes(reason)) {
1909
- resolve(collected);
1910
- return;
1911
- }
1912
- if (reason === "time") {
1913
- reject(
1914
- new FluxerError("Message collector timed out", {
1915
- code: ErrorCodes.CollectorIdle
1916
- })
1917
- );
1918
- return;
1919
- }
1920
- if (reason === "limit") {
1921
- reject(
1922
- new FluxerError("Message collector reached max", {
1923
- code: ErrorCodes.CollectorMax
1924
- })
1925
- );
1926
- return;
1927
- }
1928
- reject(collected);
1929
- });
1978
+ /** CDN URL for this sticker image. */
1979
+ get url() {
1980
+ return cdnStickerURL(this.id, this.animated, {
1981
+ mediaBase: this.client.instance.endpoints.media
1930
1982
  });
1931
1983
  }
1932
- on(event, listener) {
1933
- return super.on(event, listener);
1984
+ /** Unix timestamp (ms) when this sticker was created, derived from its snowflake ID. */
1985
+ get createdTimestamp() {
1986
+ return SnowflakeUtil2.timestampFromSnowflake(this.id);
1934
1987
  }
1935
- emit(event, ...args) {
1936
- return super.emit(event, ...args);
1988
+ /** Date when this sticker was created, derived from its snowflake ID. */
1989
+ get createdAt() {
1990
+ return SnowflakeUtil2.dateFromSnowflake(this.id);
1937
1991
  }
1938
1992
  };
1939
1993
 
1940
- // src/Domain/Channel/Attachments.ts
1941
- import { Routes as Routes6 } from "@fluxerjs/types";
1942
- var BOT_ATTACHMENT_MAX_BYTES = 50 * 1024 * 1024;
1943
- var ATTACHMENT_MULTIPART_THRESHOLD_BYTES = 10 * 1024 * 1024;
1944
- function instanceLimitOverridesSnapshot(client) {
1945
- const rules = client.instance.discovery?.limits?.rules;
1946
- if (!rules?.length) return null;
1947
- const snapshot = {};
1948
- for (const rule of rules) {
1949
- Object.assign(snapshot, rule.overrides);
1950
- }
1951
- return Object.keys(snapshot).length ? snapshot : null;
1994
+ // src/Domain/Message/Reactions.ts
1995
+ import { Routes as Routes5 } from "@fluxerjs/types";
1996
+ async function emojiPath(message, emoji) {
1997
+ return message.client.resolveEmoji(emoji, message.guildId);
1952
1998
  }
1953
- function assertBotAttachmentLimits(client, files) {
1954
- const snapshot = instanceLimitOverridesSnapshot(client);
1955
- for (const file of files) {
1956
- const size = file.data.byteLength;
1957
- if (size <= BOT_ATTACHMENT_MAX_BYTES) continue;
1958
- const snapshotNote = snapshot ? ` Instance limit overrides: ${JSON.stringify(snapshot)}.` : "";
1959
- throw new FluxerError(
1960
- `Bot attachments are limited to 50 MiB (${BOT_ATTACHMENT_MAX_BYTES} bytes); "${file.filename}" is ${size} bytes.${snapshotNote}`,
1961
- { code: ErrorCodes.AttachmentTooLarge }
1962
- );
1963
- }
1999
+ async function reactToMessage(message, emoji) {
2000
+ const wire = await emojiPath(message, emoji);
2001
+ await message.client.rest.put(
2002
+ Routes5.channelMessageReactionMe(message.channelId, message.id, wire)
2003
+ );
1964
2004
  }
1965
- function asBytes(data) {
1966
- const src = data instanceof ArrayBuffer ? new Uint8Array(data) : new Uint8Array(data);
1967
- const out = new Uint8Array(src.byteLength);
1968
- out.set(src);
1969
- return out;
2005
+ async function removeMessageReaction(message, emoji, userId) {
2006
+ const e = await emojiPath(message, emoji);
2007
+ const route = userId ? Routes5.channelMessageReactionUser(message.channelId, message.id, e, userId) : Routes5.channelMessageReactionMe(message.channelId, message.id, e);
2008
+ await message.client.rest.delete(route);
1970
2009
  }
1971
- async function putBlob(url, body, contentType) {
1972
- const res = await fetch(url, {
1973
- method: "PUT",
1974
- headers: contentType ? { "Content-Type": contentType } : void 0,
1975
- body
1976
- });
1977
- if (!res.ok) {
1978
- throw new FluxerError(`Presigned upload failed: ${res.status}`, {
1979
- code: ErrorCodes.AttachmentUploadFailed
1980
- });
2010
+ async function removeAllMessageReactions(message) {
2011
+ await message.client.rest.delete(Routes5.channelMessageReactions(message.channelId, message.id));
2012
+ }
2013
+ async function removeMessageReactionEmoji(message, emoji) {
2014
+ const e = await emojiPath(message, emoji);
2015
+ await message.client.rest.delete(Routes5.channelMessageReaction(message.channelId, message.id, e));
2016
+ }
2017
+ async function fetchMessageReactionUsers(message, emoji, options) {
2018
+ return (await fetchMessageReactionUsersPage(message, emoji, options)).users;
2019
+ }
2020
+ async function fetchMessageReactionUsersPage(message, emoji, options) {
2021
+ const e = await emojiPath(message, emoji);
2022
+ const params = new URLSearchParams();
2023
+ if (options?.limit != null) params.set("limit", String(options.limit));
2024
+ if (options?.after) params.set("after", options.after);
2025
+ const qs2 = params.toString();
2026
+ const route = Routes5.channelMessageReactionUsers(message.channelId, message.id, e) + (qs2 ? `?${qs2}` : "");
2027
+ const data = await message.client.rest.get(route);
2028
+ if (Array.isArray(data)) {
2029
+ return {
2030
+ users: data.map((u) => message.client.getOrCreateUser(u)),
2031
+ hasMore: false,
2032
+ nextAfter: null
2033
+ };
1981
2034
  }
2035
+ const list = data.items ?? data.users ?? [];
2036
+ return {
2037
+ users: list.map((u) => message.client.getOrCreateUser(u)),
2038
+ hasMore: data.has_more ?? false,
2039
+ nextAfter: data.next_after ?? null
2040
+ };
1982
2041
  }
1983
- async function uploadAttachmentsForSend(client, channelId, files) {
1984
- assertBotAttachmentLimits(client, files);
1985
- const plan = await client.rest.post(
1986
- Routes6.channelAttachments(channelId),
1987
- {
1988
- body: {
1989
- attachments: files.map((f) => ({
1990
- id: f.id,
1991
- filename: f.filename,
1992
- file_size: f.data.byteLength,
1993
- content_type: f.contentType
1994
- }))
1995
- },
1996
- auth: true
1997
- }
1998
- );
1999
- const multipart = [];
2000
- const uploaded = [];
2001
- for (const item of plan.attachments) {
2002
- const file = files.find((f) => f.id === item.id);
2003
- if (!file) {
2004
- throw new FluxerError(`No file data for planned attachment id ${item.id}`, {
2005
- code: ErrorCodes.InvalidAttachmentInput
2006
- });
2007
- }
2008
- const bytes = asBytes(file.data);
2009
- if (item.upload_mode === "singlepart") {
2010
- await putBlob(
2011
- item.upload_url,
2012
- new Blob([bytes], { type: file.contentType }),
2013
- item.content_type
2014
- );
2015
- } else {
2016
- for (const part of item.parts) {
2017
- const start = (part.part_number - 1) * item.part_size;
2018
- const chunk = bytes.subarray(start, Math.min(start + item.part_size, bytes.byteLength));
2019
- await putBlob(part.upload_url, new Blob([asBytes(chunk)]));
2020
- }
2021
- multipart.push({ upload_filename: item.upload_filename, upload_id: item.upload_id });
2022
- }
2023
- uploaded.push({
2024
- id: item.id,
2025
- filename: item.filename,
2026
- upload_filename: item.upload_filename,
2027
- file_size: item.file_size,
2028
- content_type: item.content_type
2029
- });
2042
+
2043
+ // src/Domain/Message/Send.ts
2044
+ import { MessagePayload as MessagePayloadBuilder } from "@fluxerjs/builders";
2045
+ import { Routes as Routes6 } from "@fluxerjs/types";
2046
+ function toReplyTarget(ref) {
2047
+ return {
2048
+ channelId: ref.channel_id,
2049
+ messageId: ref.message_id,
2050
+ ...ref.guild_id != null ? { guildId: ref.guild_id } : {}
2051
+ };
2052
+ }
2053
+ function toSendOptions(content) {
2054
+ if (typeof content === "string") return { content };
2055
+ if (content instanceof MessagePayloadBuilder) return messagePayloadToSendOptions(content);
2056
+ return { ...content };
2057
+ }
2058
+ async function createMessageBody(content, referenced_message, ping) {
2059
+ if (typeof content === "string" && content.length === 0) {
2060
+ throw new FluxerError("Cannot send an empty message", { code: ErrorCodes.EmptyMessage });
2030
2061
  }
2031
- if (multipart.length) {
2032
- await client.rest.post(Routes6.channelAttachmentsComplete(channelId), {
2033
- body: { uploads: multipart },
2034
- auth: true
2035
- });
2062
+ const opts = toSendOptions(content);
2063
+ if (referenced_message) {
2064
+ opts.replyTo = toReplyTarget(referenced_message);
2065
+ if (ping !== void 0) opts.ping = ping;
2036
2066
  }
2037
- return uploaded;
2067
+ return prepareMessagePostPayload(opts);
2068
+ }
2069
+ function asReplyTarget(value) {
2070
+ if ("messageId" in value) return value;
2071
+ return {
2072
+ channelId: value.channelId,
2073
+ messageId: value.id,
2074
+ guildId: value.guildId
2075
+ };
2076
+ }
2077
+ async function sendPrepared(message, payload) {
2078
+ const data = await message.client.rest.post(
2079
+ Routes6.channelMessages(message.channelId),
2080
+ payload
2081
+ );
2082
+ message.client._addMessageToCache(message.channelId, data);
2083
+ return new message.constructor(message.client, data);
2084
+ }
2085
+ async function sendMessage(message, options) {
2086
+ return message._send(
2087
+ await prepareMessagePostPayload(options, {
2088
+ defaultAllowedMentions: message.client.options.defaultAllowedMentions
2089
+ })
2090
+ );
2091
+ }
2092
+ async function sendMessageTo(message, channelId, options) {
2093
+ return message.client.channels.send(channelId, options);
2094
+ }
2095
+ async function replyToMessage(message, options, replyOptions) {
2096
+ const opts = typeof options === "string" ? { content: options } : { ...options };
2097
+ const { replyTo: inlineReplyTo, ping: inlinePing, ...sendOpts } = opts;
2098
+ const ping = replyOptions?.ping ?? inlinePing ?? message.client.options.defaultReplyPing;
2099
+ const replyTo = asReplyTarget(replyOptions?.replyTo ?? inlineReplyTo ?? message);
2100
+ return message._send(
2101
+ await prepareMessagePostPayload(
2102
+ { ...sendOpts, replyTo, ping },
2103
+ { defaultAllowedMentions: message.client.options.defaultAllowedMentions }
2104
+ )
2105
+ );
2038
2106
  }
2039
2107
 
2040
- // src/Domain/Channel/Base.ts
2041
- var Channel = class extends Base {
2042
- #messages;
2043
- /** The {@link Client} that instantiated this channel. */
2108
+ // src/Domain/Message/Message.ts
2109
+ function toMessageCall(data) {
2110
+ return {
2111
+ participants: data.participants,
2112
+ endedAt: data.ended_timestamp ? new Date(data.ended_timestamp) : null
2113
+ };
2114
+ }
2115
+ function toMessageSnapshot(client, data) {
2116
+ return {
2117
+ content: data.content ?? null,
2118
+ createdAt: new Date(data.timestamp),
2119
+ editedAt: data.edited_timestamp ? new Date(data.edited_timestamp) : null,
2120
+ mentionUserIds: data.mentions ?? [],
2121
+ mentionRoles: data.mention_roles ?? [],
2122
+ embeds: (data.embeds ?? []).map(toMessageEmbed),
2123
+ attachments: (data.attachments ?? []).map(toMessageAttachment),
2124
+ stickers: (data.stickers ?? []).map((s) => new MessageSticker(client, s)),
2125
+ ...data.type !== void 0 ? { type: data.type } : {}
2126
+ };
2127
+ }
2128
+ function resolveMessageFlags(flags) {
2129
+ if (flags === void 0) return void 0;
2130
+ if (typeof flags === "number") return flags;
2131
+ return Number(MessageFlagsBitField.resolve(flags));
2132
+ }
2133
+ var Message = class _Message extends Base {
2134
+ /** Discriminant vs {@link PartialMessage}: always `false` on a hydrated Message. */
2135
+ partial = false;
2136
+ /** The {@link Client} that instantiated this message. */
2044
2137
  client;
2045
- /** Snowflake ID of this channel. */
2138
+ /** Snowflake ID of this message. */
2046
2139
  id;
2047
- /** Channel type (text, voice, category, etc.). */
2140
+ /** Channel ID where this message was sent. */
2141
+ channelId;
2142
+ /** Guild ID if in a guild channel, null for DMs. */
2143
+ guildId;
2144
+ /** The user who sent this message. */
2145
+ author;
2146
+ /** Text content of the message. */
2147
+ content;
2148
+ /** When the message was created. */
2149
+ createdAt;
2150
+ /** When the message was last edited, or null if never edited. */
2151
+ editedAt;
2152
+ /** Whether the message is pinned. */
2153
+ pinned;
2154
+ /** Attached files (images, videos, etc.). */
2155
+ attachments;
2156
+ /** Message type (Default, Reply, etc.). */
2048
2157
  type;
2049
- /** Channel name (null for some channel types). */
2050
- name;
2051
- /** Channel icon hash (null for most channel types). */
2052
- icon;
2053
- /** ISO8601 timestamp of the last pinned message update. */
2054
- lastPinTimestamp;
2158
+ /** Message flags bitfield. */
2159
+ flags;
2160
+ /** Whether `@everyone` or `@here` was mentioned. */
2161
+ mentionEveryone;
2162
+ /** Whether this is a text-to-speech message. */
2163
+ tts;
2164
+ /** Embedded content (camelCase read view; send with {@link EmbedBuilder}). */
2165
+ embeds;
2166
+ /** Stickers sent with the message. */
2167
+ stickers;
2168
+ /** Reactions on the message. */
2169
+ reactions;
2170
+ /** Reference to a replied-to message, if any. */
2171
+ messageReference;
2172
+ /** Message snapshots for forwarded messages. */
2173
+ messageSnapshots;
2174
+ /** Call data if this message represents a call event. */
2175
+ call;
2176
+ /** The full referenced (replied-to) message, or null. */
2177
+ referencedMessage;
2178
+ /** Webhook ID if sent by a webhook. */
2179
+ webhookId;
2180
+ /** Users mentioned in the message. */
2181
+ mentions;
2182
+ /** Role IDs mentioned in the message. */
2183
+ mentionRoles;
2184
+ /** Client-side nonce for deduplication. */
2185
+ nonce;
2186
+ /** IDs of custom emojis in the message classified as explicit. */
2187
+ nsfwEmojis;
2188
+ /** Thread started from this message, when the payload included one. */
2189
+ thread;
2190
+ /**
2191
+ * Cached text-capable channel (guild text, guild voice, or DM), or null if uncached / not text-based.
2192
+ * Narrowed type has {@link Channel.send} and {@link Channel.delete}.
2193
+ */
2194
+ get channel() {
2195
+ const channel = this.client.channels.get(this.channelId) ?? null;
2196
+ return channel?.isTextBased() ? channel : null;
2197
+ }
2198
+ /** Cached guild, or null for DMs / uncached. */
2199
+ get guild() {
2200
+ return this.guildId ? this.client.guilds.get(this.guildId) ?? null : null;
2201
+ }
2202
+ /** Cached guild member for the author, or null in DMs / if uncached. */
2203
+ get member() {
2204
+ return this.guild?.members.get(this.author.id) ?? null;
2205
+ }
2206
+ /**
2207
+ * Fetch this message's channel (cache first). The returned {@link Channel}
2208
+ * has {@link Channel.delete} and {@link Channel.send}.
2209
+ * @example
2210
+ * const channel = await message.resolveChannel();
2211
+ * await channel.delete();
2212
+ */
2213
+ async resolveChannel() {
2214
+ return this.client.channels.resolve(this.channelId);
2215
+ }
2216
+ /**
2217
+ * Fetch and resolve the guild, or null if a DM.
2218
+ * Propagates network/auth errors; only returns null when there is no guildId.
2219
+ * @example
2220
+ * const guild = await message.resolveGuild();
2221
+ */
2222
+ async resolveGuild() {
2223
+ if (!this.guildId) return null;
2224
+ return this.client.guilds.resolve(this.guildId);
2225
+ }
2226
+ /**
2227
+ * Construct a message from API data.
2228
+ * @param data - API message from REST or MESSAGE_CREATE
2229
+ */
2055
2230
  constructor(client, data) {
2056
2231
  super();
2057
2232
  this.client = client;
2058
2233
  this.id = data.id;
2059
- this.type = data.type;
2060
- this.name = data.name ?? null;
2061
- this.icon = data.icon ?? null;
2062
- this.lastPinTimestamp = data.last_pin_timestamp ?? null;
2234
+ this.channelId = data.channel_id;
2235
+ this.guildId = data.guild_id ?? null;
2236
+ this.author = client.getOrCreateUser(data.author);
2237
+ this.content = data.content;
2238
+ this.createdAt = new Date(data.timestamp);
2239
+ this.editedAt = data.edited_timestamp ? new Date(data.edited_timestamp) : null;
2240
+ this.pinned = data.pinned;
2241
+ this.attachments = new Collection5();
2242
+ for (const a of data.attachments ?? []) this.attachments.set(a.id, toMessageAttachment(a));
2243
+ this.type = data.type ?? MessageType.Default;
2244
+ this.flags = new MessageFlagsBitField(BigInt(data.flags ?? 0));
2245
+ this.mentionEveryone = data.mention_everyone ?? false;
2246
+ this.tts = data.tts ?? false;
2247
+ this.embeds = (data.embeds ?? []).map(toMessageEmbed);
2248
+ this.stickers = (data.stickers ?? []).map((s) => new MessageSticker(client, s));
2249
+ this.reactions = new MessageReactionManager(this);
2250
+ this.reactions._patch(data.reactions);
2251
+ this.messageReference = data.message_reference ? {
2252
+ channelId: data.message_reference.channel_id,
2253
+ messageId: data.message_reference.message_id,
2254
+ guildId: data.message_reference.guild_id ?? null,
2255
+ ...data.message_reference.type !== void 0 ? { type: data.message_reference.type } : {}
2256
+ } : null;
2257
+ this.messageSnapshots = (data.message_snapshots ?? []).map((s) => toMessageSnapshot(client, s));
2258
+ this.call = data.call ? toMessageCall(data.call) : null;
2259
+ this.referencedMessage = data.referenced_message ? new _Message(client, data.referenced_message) : null;
2260
+ this.webhookId = data.webhook_id ?? null;
2261
+ this.mentions = (data.mentions ?? []).map((u) => client.getOrCreateUser(u));
2262
+ this.mentionRoles = data.mention_roles ?? [];
2263
+ this.nonce = data.nonce ?? null;
2264
+ this.nsfwEmojis = data.nsfw_emojis ?? [];
2265
+ this.thread = data.thread ? cacheThread(client, data.thread) : null;
2063
2266
  }
2064
- /** Unix timestamp (ms) when this channel was created, derived from its snowflake ID. */
2065
- get createdTimestamp() {
2066
- return SnowflakeUtil3.timestampFromSnowflake(this.id);
2267
+ /**
2268
+ * Apply an API message payload in place (cache identity / MESSAGE_UPDATE).
2269
+ * @internal
2270
+ */
2271
+ _patch(data) {
2272
+ this.content = data.content;
2273
+ this.editedAt = data.edited_timestamp ? new Date(data.edited_timestamp) : null;
2274
+ this.pinned = data.pinned;
2275
+ this.attachments.clear();
2276
+ for (const a of data.attachments ?? []) this.attachments.set(a.id, toMessageAttachment(a));
2277
+ this.flags = new MessageFlagsBitField(BigInt(data.flags ?? 0));
2278
+ this.mentionEveryone = data.mention_everyone ?? false;
2279
+ this.tts = data.tts ?? false;
2280
+ this.embeds = (data.embeds ?? []).map(toMessageEmbed);
2281
+ this.stickers = (data.stickers ?? []).map((s) => new MessageSticker(this.client, s));
2282
+ this.reactions._patch(data.reactions);
2283
+ this.messageReference = data.message_reference ? {
2284
+ channelId: data.message_reference.channel_id,
2285
+ messageId: data.message_reference.message_id,
2286
+ guildId: data.message_reference.guild_id ?? null,
2287
+ ...data.message_reference.type !== void 0 ? { type: data.message_reference.type } : {}
2288
+ } : null;
2289
+ this.messageSnapshots = (data.message_snapshots ?? []).map(
2290
+ (s) => toMessageSnapshot(this.client, s)
2291
+ );
2292
+ this.call = data.call ? toMessageCall(data.call) : null;
2293
+ this.referencedMessage = data.referenced_message ? new _Message(this.client, data.referenced_message) : null;
2294
+ this.webhookId = data.webhook_id ?? null;
2295
+ this.mentions = (data.mentions ?? []).map((u) => this.client.getOrCreateUser(u));
2296
+ this.mentionRoles = data.mention_roles ?? [];
2297
+ this.nonce = data.nonce ?? null;
2298
+ this.nsfwEmojis = data.nsfw_emojis ?? [];
2299
+ if (data.thread) this.thread = cacheThread(this.client, data.thread);
2067
2300
  }
2068
- /** Date when this channel was created, derived from its snowflake ID. */
2069
- get createdAt() {
2070
- return SnowflakeUtil3.dateFromSnowflake(this.id);
2301
+ /**
2302
+ * Send a standalone message in this channel (not a reply).
2303
+ * Prefer {@link Channel.send} or {@link reply} when you already have the channel or are answering.
2304
+ */
2305
+ async send(options) {
2306
+ return sendMessage(this, options);
2071
2307
  }
2072
2308
  /**
2073
- * Apply shared channel fields in place (gateway CHANNEL_UPDATE when type is unchanged).
2074
- * @internal
2309
+ * Send a message to another channel by ID.
2310
+ * Prefer `client.channels.fetch(channelId)` then {@link Channel.send}.
2075
2311
  */
2076
- _patch(data) {
2077
- if (data.type !== void 0) this.type = data.type;
2078
- if (data.name !== void 0) this.name = data.name ?? null;
2079
- if (data.icon !== void 0) this.icon = data.icon ?? null;
2080
- if ("last_pin_timestamp" in data && data.last_pin_timestamp !== void 0) {
2081
- this.lastPinTimestamp = data.last_pin_timestamp ?? null;
2082
- }
2083
- }
2084
- /** @internal Factory wired after subclasses load. */
2085
- static from(_c, _d) {
2086
- throw new Error("Channel.from not initialized");
2087
- }
2088
- /** @internal Factory wired after subclasses load. */
2089
- static fromOrCreate(_c, _d) {
2090
- throw new Error("Channel.fromOrCreate not initialized");
2091
- }
2092
- /** @internal Factory wired after subclasses load. */
2093
- static createDM(_c, _d) {
2094
- throw new Error("Channel.createDM not initialized");
2312
+ async sendTo(channelId, options) {
2313
+ return sendMessageTo(this, channelId, options);
2095
2314
  }
2096
2315
  /**
2097
- * Whether this channel type can carry messages (text, announcement, voice, DM, group DM, notes).
2098
- * Checks {@link ChannelType}, not whether `send` exists on the instance.
2316
+ * Reply to this message.
2317
+ * @example
2318
+ * await message.reply('Pong!');
2319
+ * await message.reply('No ping!', { ping: false });
2320
+ * await message.reply({ content: 'Silent', allowedMentions: AllowedMentions.suppressReplyPing });
2099
2321
  */
2100
- isTextBased() {
2101
- return this.type === ChannelType.GuildText || this.type === ChannelType.GuildAnnouncement || this.type === ChannelType.GuildVoice || this.type === ChannelType.DM || this.type === ChannelType.GroupDM || this.type === ChannelType.DMPersonalNotes;
2102
- }
2103
- /** Check if this is a guild channel (text, announcement, voice, category, or link). */
2104
- isGuild() {
2105
- return this.type === ChannelType.GuildText || this.type === ChannelType.GuildAnnouncement || this.type === ChannelType.GuildVoice || this.type === ChannelType.GuildCategory || this.type === ChannelType.GuildLink;
2106
- }
2107
- /** Check if this is a guild text channel. */
2108
- isText() {
2109
- return this.type === ChannelType.GuildText;
2110
- }
2111
- /** Check if this is a guild announcement channel. */
2112
- isAnnouncement() {
2113
- return this.type === ChannelType.GuildAnnouncement;
2114
- }
2115
- /** Check if this is a category channel. */
2116
- isCategory() {
2117
- return this.type === ChannelType.GuildCategory;
2118
- }
2119
- /** Check if this is a DM, group DM, or personal notes channel. */
2120
- isDM() {
2121
- return this.type === ChannelType.DM || this.type === ChannelType.GroupDM || this.type === ChannelType.DMPersonalNotes;
2322
+ async reply(options, replyOptions) {
2323
+ return replyToMessage(this, options, replyOptions);
2122
2324
  }
2123
- /** Check if this is a personal notes channel. */
2124
- isPersonalNotes() {
2125
- return this.type === ChannelType.DMPersonalNotes;
2325
+ /**
2326
+ * Hydrate a partial message, or return the message as-is.
2327
+ * @example
2328
+ * client.on(Events.MessageUpdate, async (_old, msg) => {
2329
+ * const message = await Message.resolve(msg);
2330
+ * });
2331
+ */
2332
+ static async resolve(message) {
2333
+ return message.partial ? message.fetch() : message;
2126
2334
  }
2127
- /** Check if this is a voice channel. */
2128
- isVoice() {
2129
- return this.type === ChannelType.GuildVoice;
2335
+ /** Test helper — prefer {@link reply} / `prepareMessagePostPayload()`. */
2336
+ static async _createMessageBody(content, referenced_message, ping) {
2337
+ return createMessageBody(content, referenced_message, ping);
2130
2338
  }
2131
- /** Check if this is a link channel. */
2132
- isLink() {
2133
- return this.type === ChannelType.GuildLink;
2339
+ /** Send a prepared payload (internal helper). */
2340
+ async _send(payload) {
2341
+ return sendPrepared(this, payload);
2134
2342
  }
2135
- /**
2136
- * Delete recent messages or an explicit ID list.
2137
- * - `bulkDelete(5)` — fetch last 5 via {@link MessageManager} then delete (1–100)
2138
- * - `bulkDelete(['id1'])` — single DELETE; 2–100 uses bulk-delete route
2139
- */
2140
- async bulkDelete(countOrIds) {
2141
- let ids;
2142
- if (typeof countOrIds === "number") {
2143
- if (!Number.isInteger(countOrIds) || countOrIds < 1 || countOrIds > 100) {
2144
- throw new FluxerError("bulkDelete count must be between 1 and 100", {
2145
- code: ErrorCodes.InvalidBulkDelete
2146
- });
2147
- }
2148
- ids = [
2149
- ...(await new MessageManager(this.client, this.id).fetch({ limit: countOrIds })).keys()
2150
- ];
2151
- } else {
2152
- ids = [...countOrIds];
2343
+ /** Edit this message (requires author or admin permissions). */
2344
+ async edit(options) {
2345
+ const body = {};
2346
+ if (options.content !== void 0) body.content = options.content;
2347
+ if (options.embeds !== void 0) {
2348
+ body.embeds = options.embeds.map(
2349
+ (e) => e instanceof EmbedBuilder2 ? e.toJSON() : e
2350
+ );
2153
2351
  }
2154
- if (ids.length === 0) return [];
2155
- if (ids.length === 1) {
2156
- await this.client.rest.delete(Routes7.channelMessage(this.id, ids[0]), { auth: true });
2157
- this.client._removeMessageFromCache(this.id, ids[0]);
2158
- return ids;
2352
+ if (options.allowedMentions) {
2353
+ body.allowed_mentions = toAPIAllowedMentions(options.allowedMentions);
2159
2354
  }
2160
- if (ids.length > 100) {
2161
- throw new FluxerError("bulkDelete requires at most 100 message IDs", {
2162
- code: ErrorCodes.InvalidBulkDelete
2163
- });
2355
+ const flags = resolveMessageFlags(options.flags);
2356
+ if (flags !== void 0) body.flags = flags;
2357
+ if (options.attachments !== void 0) {
2358
+ body.attachments = toMessageAttachmentEditWire(options.attachments);
2164
2359
  }
2165
- await this.client.rest.post(Routes7.channelBulkDelete(this.id), {
2166
- body: { message_ids: ids },
2167
- auth: true
2360
+ const data = await this.client.rest.patch(Routes7.channelMessage(this.channelId, this.id), {
2361
+ body
2168
2362
  });
2169
- for (const id of ids) this.client._removeMessageFromCache(this.id, id);
2170
- return ids;
2363
+ const updated = new _Message(this.client, data);
2364
+ this.client._addMessageToCache(this.channelId, data);
2365
+ return updated;
2171
2366
  }
2172
- /** Delete all messages sent by the bot in this channel. Sudo auto-passes for bots. */
2173
- async bulkDeleteMyMessages(options) {
2174
- const body = options ? toSudoBody(options) : void 0;
2175
- await this.client.rest.post(Routes7.channelBulkDeleteMine(this.id), {
2176
- body: body && Object.keys(body).length ? body : void 0,
2177
- auth: true
2178
- });
2367
+ /** Create a {@link ReactionCollector} for this message. */
2368
+ createReactionCollector(options) {
2369
+ return new ReactionCollector(this.client, this.id, this.channelId, options);
2179
2370
  }
2180
2371
  /**
2181
- * Mark all pinned messages as read in this channel.
2182
- * Session-token helper; bots usually skip this.
2372
+ * Wait for reactions matching the filter, then resolve the collected set.
2373
+ * Pass `errors: ['time']` to reject when the timer fires instead of resolving.
2183
2374
  */
2184
- async acknowledgePins() {
2185
- await this.client.rest.post(Routes7.channelPinsAck(this.id), { auth: true });
2375
+ awaitReactions(options) {
2376
+ return ReactionCollector.awaitReactions(this.client, this.id, this.channelId, options);
2186
2377
  }
2187
2378
  /**
2188
- * Clear the read state for this channel.
2189
- * Session-token helper; bots usually skip this.
2379
+ * Start a thread from this message.
2380
+ * Fluxer chooses a public or announcement thread from the parent channel.
2190
2381
  */
2191
- async clearReadState() {
2192
- await this.client.rest.delete(Routes7.channelMessagesAck(this.id), { auth: true });
2193
- }
2194
- /** Request upload URLs for attachments before sending a message. */
2195
- async requestAttachmentUploads(attachments) {
2196
- const data = await this.client.rest.post(
2197
- Routes7.channelAttachments(this.id),
2198
- {
2199
- body: toAttachmentUploadPlanBody(attachments),
2200
- auth: true
2201
- }
2202
- );
2203
- return toAttachmentUploadPlanResponse(data);
2204
- }
2205
- /** Complete the attachment upload flow after uploading to the CDN. */
2206
- async completeAttachmentUploads(uploads) {
2382
+ async startThread(options) {
2207
2383
  const data = await this.client.rest.post(
2208
- Routes7.channelAttachmentsComplete(this.id),
2384
+ Routes7.channelMessageThreads(this.channelId, this.id),
2209
2385
  {
2210
- body: toAttachmentUploadCompleteBody(uploads),
2211
- auth: true
2386
+ body: toStartThreadFromMessageBody(options),
2387
+ auth: true,
2388
+ ...auditReasonHeaders(options.reason)
2212
2389
  }
2213
2390
  );
2214
- return {
2215
- uploads: data.uploads.map((u) => ({ uploadFilename: u.upload_filename }))
2216
- };
2217
- }
2218
- /** Upload files for sending in a message (helper). */
2219
- async uploadAttachmentsForSend(files) {
2220
- return uploadAttachmentsForSend(this.client, this.id, files);
2391
+ const thread = cacheThread(this.client, data);
2392
+ this.thread = thread;
2393
+ return thread;
2221
2394
  }
2222
- /** Trigger the typing indicator in this channel. */
2223
- async sendTyping() {
2224
- await this.client.rest.post(Routes7.channelTyping(this.id), { auth: true });
2395
+ /** Fetch the latest version of this message from the API. */
2396
+ async fetch() {
2397
+ return this.client.channels.fetchMessage(this.channelId, this.id);
2225
2398
  }
2226
- /**
2227
- * Fetch available RTC regions for voice channels.
2228
- * User-account only (`DefaultUserOnly`); bots receive `AccessDeniedError`.
2229
- * Bots should skip this and join voice with `@fluxerjs/voice` instead.
2230
- */
2231
- async fetchRtcRegions() {
2232
- const data = await this.client.rest.get(Routes7.channelRtcRegions(this.id), {
2233
- auth: true
2399
+ /** Delete this message. */
2400
+ async delete(reason) {
2401
+ await this.client.rest.delete(Routes7.channelMessage(this.channelId, this.id), {
2402
+ ...auditReasonHeaders(reason)
2234
2403
  });
2235
- return data.map((r) => ({ id: r.id, name: r.name, emoji: r.emoji }));
2404
+ this.client._removeMessageFromCache(this.channelId, this.id);
2236
2405
  }
2237
- /** Fetch slowmode state for this channel. */
2238
- async fetchSlowmode() {
2239
- const data = await this.client.rest.get(
2240
- Routes7.channelSlowmode(this.id),
2406
+ /** Delete a specific attachment from this message. */
2407
+ async deleteAttachment(attachmentId) {
2408
+ await this.client.rest.delete(
2409
+ Routes7.channelMessageAttachment(this.channelId, this.id, attachmentId),
2241
2410
  { auth: true }
2242
2411
  );
2243
- return {
2244
- rateLimitPerUser: data.rate_limit_per_user,
2245
- retryAfterMs: data.retry_after_ms,
2246
- nextSendAllowedAt: data.next_send_allowed_at
2247
- };
2412
+ this.attachments.delete(attachmentId);
2248
2413
  }
2249
- /** Whether this channel type can carry messages (does not check permissions). */
2250
- canSendMessage() {
2251
- return this.isTextBased();
2414
+ /** Pin this message in the channel. */
2415
+ async pin() {
2416
+ await this.client.rest.put(Routes7.channelPinMessage(this.channelId, this.id));
2417
+ this.pinned = true;
2252
2418
  }
2253
- /** Per-channel message cache + fetch. */
2254
- get messages() {
2255
- if (!this.#messages) {
2256
- this.#messages = new MessageManager(this.client, this.id);
2257
- }
2258
- return this.#messages;
2419
+ /** Unpin this message from the channel. */
2420
+ async unpin() {
2421
+ await this.client.rest.delete(Routes7.channelPinMessage(this.channelId, this.id));
2422
+ this.pinned = false;
2259
2423
  }
2260
- /** Collect messages in this channel until time/max/stop. */
2261
- createMessageCollector(options) {
2262
- return new MessageCollector(this.client, this.id, options);
2424
+ /** React to this message with an emoji. */
2425
+ async react(emoji) {
2426
+ return reactToMessage(this, emoji);
2427
+ }
2428
+ /** Remove a reaction (bot's own or a user's if ID is provided). */
2429
+ async removeReaction(emoji, userId) {
2430
+ return removeMessageReaction(this, emoji, userId);
2431
+ }
2432
+ /** Remove all reactions from this message. */
2433
+ async removeAllReactions() {
2434
+ return removeAllMessageReactions(this);
2435
+ }
2436
+ /** Remove all reactions of a specific emoji. */
2437
+ async removeReactionEmoji(emoji) {
2438
+ return removeMessageReactionEmoji(this, emoji);
2439
+ }
2440
+ /** Fetch users who reacted with a specific emoji. */
2441
+ async fetchReactionUsers(emoji, options) {
2442
+ return fetchMessageReactionUsers(this, emoji, options);
2443
+ }
2444
+ /** Fetch reaction users with pagination metadata. */
2445
+ async fetchReactionUsersPage(emoji, options) {
2446
+ return fetchMessageReactionUsersPage(this, emoji, options);
2447
+ }
2448
+ };
2449
+
2450
+ // src/Domain/Message/PartialMessage.ts
2451
+ import { SnowflakeUtil as SnowflakeUtil3 } from "@fluxerjs/util";
2452
+ var PartialMessage = class {
2453
+ partial = true;
2454
+ client;
2455
+ id;
2456
+ channelId;
2457
+ guildId;
2458
+ content;
2459
+ authorId;
2460
+ author;
2461
+ createdAt;
2462
+ constructor(client, data) {
2463
+ this.client = client;
2464
+ this.id = data.id;
2465
+ this.channelId = data.channelId;
2466
+ this.guildId = data.guildId ?? null;
2467
+ this.content = data.content ?? null;
2468
+ this.authorId = data.authorId ?? null;
2469
+ this.author = data.author ?? null;
2470
+ this.createdAt = data.createdAt ?? (SnowflakeUtil3.isValid(data.id) ? SnowflakeUtil3.dateFromSnowflake(data.id) : null);
2471
+ }
2472
+ /**
2473
+ * Live text-capable channel from cache, or null if uncached / not text-based.
2474
+ * Same contract as {@link Message.channel}.
2475
+ */
2476
+ get channel() {
2477
+ const channel = this.client.channels.get(this.channelId) ?? null;
2478
+ return channel?.isTextBased() ? channel : null;
2263
2479
  }
2264
2480
  /**
2265
- * Wait for messages matching the filter, then resolve the collected set.
2266
- * Pass `errors: ['time']` to reject when the timer fires instead of resolving.
2481
+ * Fetch this message's channel (cache first). The returned {@link Channel}
2482
+ * has {@link Channel.delete} and {@link Channel.send}.
2267
2483
  * @example
2268
- * const collected = await channel.awaitMessages({ max: 1, time: 15_000 });
2484
+ * const channel = await message.resolveChannel();
2485
+ * await channel.delete();
2269
2486
  */
2270
- awaitMessages(options) {
2271
- return MessageCollector.awaitMessages(this.client, this.id, options);
2487
+ async resolveChannel() {
2488
+ return this.client.channels.resolve(this.channelId);
2272
2489
  }
2273
2490
  /**
2274
- * Delete this channel (or close it if it is a DM).
2275
- * Guild channels require Manage Channels. `silent` / `deleteMessages` are Fluxer query params.
2491
+ * Fetch the full message from the API.
2276
2492
  * @example
2277
- * const channel = await client.channels.fetch(channelId);
2278
- * await channel.delete();
2493
+ * const message = await partial.fetch();
2494
+ * await message.reply('Pong!');
2279
2495
  */
2280
- async delete(options) {
2281
- const params = new URLSearchParams();
2282
- if (options?.silent) params.set("silent", "true");
2283
- if (options?.deleteMessages) params.set("delete_messages", "true");
2284
- const qs2 = params.toString();
2285
- const { silent: _s, deleteMessages: _d, reason: _reason, ...sudo } = options ?? {};
2286
- const body = Object.keys(sudo).length ? toSudoBody(sudo) : void 0;
2287
- await this.client.rest.delete(Routes7.channel(this.id) + (qs2 ? `?${qs2}` : ""), {
2288
- body,
2289
- auth: true,
2290
- ...auditReasonHeaders(_reason)
2291
- });
2292
- this.client.channels.delete(this.id);
2293
- this.client._clearMessageCache(this.id);
2294
- if (this.isGuild() && this.guildId) {
2295
- this.client.guilds.get(this.guildId)?.channels.delete(this.id);
2296
- }
2297
- }
2298
- /** Channel mention (`<#id>`). */
2299
- toString() {
2300
- return `<#${this.id}>`;
2496
+ async fetch() {
2497
+ return this.client.channels.fetchMessage(this.channelId, this.id);
2301
2498
  }
2302
2499
  };
2303
2500
 
2501
+ // src/Domain/User.ts
2502
+ import { Routes as Routes17 } from "@fluxerjs/types";
2503
+ import { SnowflakeUtil as SnowflakeUtil5 } from "@fluxerjs/util";
2504
+
2304
2505
  // src/Domain/Channel/Dm.ts
2305
- import { ChannelType as ChannelType2, Routes as Routes9 } from "@fluxerjs/types";
2506
+ import { ChannelType as ChannelType4, Routes as Routes9 } from "@fluxerjs/types";
2306
2507
 
2307
2508
  // src/Domain/Channel/TextCapable.ts
2308
2509
  import { Routes as Routes8 } from "@fluxerjs/types";
@@ -2394,7 +2595,7 @@ var DMChannel = class extends TextCapable(Channel) {
2394
2595
  * Notes-only; bots usually skip this.
2395
2596
  */
2396
2597
  async purgeMessages() {
2397
- if (this.type !== ChannelType2.DMPersonalNotes) {
2598
+ if (this.type !== ChannelType4.DMPersonalNotes) {
2398
2599
  throw new FluxerError("purgeMessages is only available on personal notes channels", {
2399
2600
  code: ErrorCodes.InvalidChannelType
2400
2601
  });
@@ -2437,6 +2638,12 @@ var DMChannel = class extends TextCapable(Channel) {
2437
2638
  }
2438
2639
  };
2439
2640
 
2641
+ // src/Domain/Channel/Forum.ts
2642
+ import {
2643
+ ChannelType as ChannelType7,
2644
+ Routes as Routes16
2645
+ } from "@fluxerjs/types";
2646
+
2440
2647
  // src/Domain/Channel/Guild.ts
2441
2648
  import { Routes as Routes13 } from "@fluxerjs/types";
2442
2649
  import { PermissionFlags } from "@fluxerjs/util";
@@ -2748,7 +2955,8 @@ var Invite = class _Invite extends Base {
2748
2955
  // src/Domain/Webhook.ts
2749
2956
  import { EmbedBuilder as EmbedBuilder3 } from "@fluxerjs/builders";
2750
2957
  import {
2751
- Routes as Routes11
2958
+ Routes as Routes11,
2959
+ WebhookType
2752
2960
  } from "@fluxerjs/types";
2753
2961
  import { SnowflakeUtil as SnowflakeUtil4 } from "@fluxerjs/util";
2754
2962
  var Webhook = class _Webhook extends Base {
@@ -2768,6 +2976,8 @@ var Webhook = class _Webhook extends Base {
2768
2976
  token;
2769
2977
  /** The user that created this webhook. */
2770
2978
  user;
2979
+ /** Incoming or channel-follower webhook. */
2980
+ type;
2771
2981
  constructor(client, data) {
2772
2982
  super();
2773
2983
  this.client = client;
@@ -2778,6 +2988,7 @@ var Webhook = class _Webhook extends Base {
2778
2988
  this.avatar = data.avatar ?? null;
2779
2989
  this.token = data.token ?? null;
2780
2990
  this.user = client.getOrCreateUser(data.user);
2991
+ this.type = data.type ?? WebhookType.Incoming;
2781
2992
  }
2782
2993
  avatarURL(options) {
2783
2994
  return cdnAvatarURL(this.id, this.avatar, {
@@ -2888,6 +3099,7 @@ var Webhook = class _Webhook extends Base {
2888
3099
  name: options?.name ?? "Webhook",
2889
3100
  avatar: null,
2890
3101
  token,
3102
+ type: WebhookType.Incoming,
2891
3103
  user: {
2892
3104
  id: "",
2893
3105
  username: "webhook",
@@ -3007,6 +3219,23 @@ var PermissionOverwriteManager = class {
3007
3219
  }
3008
3220
  };
3009
3221
 
3222
+ // src/Domain/Channel/ThreadBind.ts
3223
+ var factory;
3224
+ var managers = /* @__PURE__ */ new WeakMap();
3225
+ function bindThreadManager(next) {
3226
+ factory = next;
3227
+ }
3228
+ function threadManagerFor(channel) {
3229
+ const existing = managers.get(channel);
3230
+ if (existing) return existing;
3231
+ if (!factory) {
3232
+ throw new Error("ThreadManager is not initialized");
3233
+ }
3234
+ const created = factory(channel);
3235
+ managers.set(channel, created);
3236
+ return created;
3237
+ }
3238
+
3010
3239
  // src/Domain/Channel/Guild.ts
3011
3240
  var GuildChannel = class extends Channel {
3012
3241
  /** Guild ID this channel belongs to, or null if missing from the payload. */
@@ -3127,6 +3356,93 @@ var TextChannel = class extends TextCapable(GuildChannel) {
3127
3356
  contentWarningLevel;
3128
3357
  /** Custom content warning text. */
3129
3358
  contentWarningText;
3359
+ /** Default auto-archive duration in minutes for new threads. */
3360
+ defaultAutoArchiveDuration;
3361
+ /** Slowmode in seconds copied onto new threads. */
3362
+ defaultThreadRateLimitPerUser;
3363
+ constructor(client, data) {
3364
+ super(client, data);
3365
+ this.topic = data.topic ?? null;
3366
+ this.nsfw = data.nsfw ?? false;
3367
+ this.nsfwOverride = data.nsfw_override ?? null;
3368
+ this.rateLimitPerUser = data.rate_limit_per_user ?? 0;
3369
+ this.lastMessageId = data.last_message_id ?? null;
3370
+ this.contentWarningLevel = data.content_warning_level ?? null;
3371
+ this.contentWarningText = data.content_warning_text ?? null;
3372
+ this.defaultAutoArchiveDuration = data.default_auto_archive_duration ?? null;
3373
+ this.defaultThreadRateLimitPerUser = data.default_thread_rate_limit_per_user ?? null;
3374
+ }
3375
+ /** Create, list, and search threads in this channel. */
3376
+ get threads() {
3377
+ return threadManagerFor(this);
3378
+ }
3379
+ /**
3380
+ * Set slowmode (seconds between messages). Pass `0` to disable.
3381
+ * Requires Manage Channels. Calls {@link GuildChannel.edit} with `rateLimitPerUser`.
3382
+ */
3383
+ async setSlowmode(seconds) {
3384
+ return this.edit({ rateLimitPerUser: seconds });
3385
+ }
3386
+ applyEditPatch(data) {
3387
+ if ("topic" in data) this.topic = data.topic ?? null;
3388
+ if ("nsfw" in data) this.nsfw = data.nsfw ?? false;
3389
+ if ("nsfw_override" in data) this.nsfwOverride = data.nsfw_override ?? null;
3390
+ if ("rate_limit_per_user" in data) this.rateLimitPerUser = data.rate_limit_per_user ?? 0;
3391
+ if ("last_message_id" in data) this.lastMessageId = data.last_message_id ?? null;
3392
+ if ("content_warning_level" in data) {
3393
+ this.contentWarningLevel = data.content_warning_level ?? null;
3394
+ }
3395
+ if ("content_warning_text" in data) {
3396
+ this.contentWarningText = data.content_warning_text ?? null;
3397
+ }
3398
+ if ("default_auto_archive_duration" in data) {
3399
+ this.defaultAutoArchiveDuration = data.default_auto_archive_duration ?? null;
3400
+ }
3401
+ if ("default_thread_rate_limit_per_user" in data) {
3402
+ this.defaultThreadRateLimitPerUser = data.default_thread_rate_limit_per_user ?? null;
3403
+ }
3404
+ }
3405
+ /**
3406
+ * Set the auto-archive and slowmode defaults copied onto new threads.
3407
+ * Sends only those fields. The thread-parent update body does not accept a channel rename.
3408
+ */
3409
+ async editThreadDefaults(options) {
3410
+ const data = await this.client.rest.patch(Routes13.channel(this.id), {
3411
+ body: toThreadParentEditBody(options),
3412
+ auth: true,
3413
+ ...auditReasonHeaders(options.reason)
3414
+ });
3415
+ this._patch(data);
3416
+ return this;
3417
+ }
3418
+ };
3419
+ var AnnouncementChannel = class extends TextChannel {
3420
+ };
3421
+ var CategoryChannel = class extends GuildChannel {
3422
+ };
3423
+ var VoiceChannel = class extends TextCapable(GuildChannel) {
3424
+ /** Channel topic. */
3425
+ topic;
3426
+ /** Whether this channel is marked as NSFW. */
3427
+ nsfw;
3428
+ /** Per-channel NSFW override (`null` inherits). */
3429
+ nsfwOverride;
3430
+ /** Slowmode rate limit in seconds. */
3431
+ rateLimitPerUser;
3432
+ /** ID of the last message sent in this channel. */
3433
+ lastMessageId;
3434
+ /** Content warning level. */
3435
+ contentWarningLevel;
3436
+ /** Custom content warning text. */
3437
+ contentWarningText;
3438
+ /** Voice bitrate. */
3439
+ bitrate;
3440
+ /** Maximum number of users allowed. */
3441
+ userLimit;
3442
+ /** Max active voice connections per user. */
3443
+ voiceConnectionLimit;
3444
+ /** RTC region override for this channel. */
3445
+ rtcRegion;
3130
3446
  constructor(client, data) {
3131
3447
  super(client, data);
3132
3448
  this.topic = data.topic ?? null;
@@ -3136,128 +3452,566 @@ var TextChannel = class extends TextCapable(GuildChannel) {
3136
3452
  this.lastMessageId = data.last_message_id ?? null;
3137
3453
  this.contentWarningLevel = data.content_warning_level ?? null;
3138
3454
  this.contentWarningText = data.content_warning_text ?? null;
3455
+ this.bitrate = data.bitrate ?? null;
3456
+ this.userLimit = data.user_limit ?? null;
3457
+ this.voiceConnectionLimit = data.voice_connection_limit ?? null;
3458
+ this.rtcRegion = data.rtc_region ?? null;
3459
+ }
3460
+ /**
3461
+ * Set slowmode (seconds between messages). Pass `0` to disable.
3462
+ * Requires Manage Channels. Calls {@link GuildChannel.edit} with `rateLimitPerUser`.
3463
+ */
3464
+ async setSlowmode(seconds) {
3465
+ return this.edit({ rateLimitPerUser: seconds });
3466
+ }
3467
+ applyEditPatch(data) {
3468
+ if ("topic" in data) this.topic = data.topic ?? null;
3469
+ if ("nsfw" in data) this.nsfw = data.nsfw ?? false;
3470
+ if ("nsfw_override" in data) this.nsfwOverride = data.nsfw_override ?? null;
3471
+ if ("rate_limit_per_user" in data) this.rateLimitPerUser = data.rate_limit_per_user ?? 0;
3472
+ if ("last_message_id" in data) this.lastMessageId = data.last_message_id ?? null;
3473
+ if ("content_warning_level" in data) {
3474
+ this.contentWarningLevel = data.content_warning_level ?? null;
3475
+ }
3476
+ if ("content_warning_text" in data) {
3477
+ this.contentWarningText = data.content_warning_text ?? null;
3478
+ }
3479
+ if ("bitrate" in data) this.bitrate = data.bitrate ?? null;
3480
+ if ("user_limit" in data) this.userLimit = data.user_limit ?? null;
3481
+ if ("voice_connection_limit" in data) {
3482
+ this.voiceConnectionLimit = data.voice_connection_limit ?? null;
3483
+ }
3484
+ if ("rtc_region" in data) this.rtcRegion = data.rtc_region ?? null;
3485
+ }
3486
+ };
3487
+ var LinkChannel = class extends GuildChannel {
3488
+ /** External URL this channel links to. */
3489
+ url;
3490
+ constructor(client, data) {
3491
+ super(client, data);
3492
+ this.url = data.url ?? null;
3493
+ }
3494
+ applyEditPatch(data) {
3495
+ if ("url" in data) this.url = data.url ?? null;
3496
+ }
3497
+ };
3498
+
3499
+ // src/Domain/Channel/ThreadManager.ts
3500
+ import { ChannelType as ChannelType6, Routes as Routes15 } from "@fluxerjs/types";
3501
+
3502
+ // src/Domain/Channel/ThreadChannel.ts
3503
+ import { ChannelType as ChannelType5, Routes as Routes14 } from "@fluxerjs/types";
3504
+ var ThreadMember = class {
3505
+ /** Thread ID. */
3506
+ id;
3507
+ /** User ID. */
3508
+ userId;
3509
+ /** When the user last joined the thread. */
3510
+ joinedAt;
3511
+ /** Thread member flags bitfield. */
3512
+ flags;
3513
+ /** Whether the current user has muted the thread. */
3514
+ muted;
3515
+ /** ISO-8601 timestamp when the mute expires, if set. */
3516
+ muteEndTime;
3517
+ /** Selected mute duration in seconds, if set. */
3518
+ muteWindow;
3519
+ constructor(data) {
3520
+ this.id = data.id ?? null;
3521
+ this.userId = data.user_id ?? data.member?.user?.id ?? null;
3522
+ this.joinedAt = new Date(data.join_timestamp);
3523
+ this.flags = data.flags;
3524
+ this.muted = data.muted ?? null;
3525
+ this.muteEndTime = data.mute_config?.end_time ?? null;
3526
+ this.muteWindow = data.mute_config?.selected_time_window ?? null;
3527
+ }
3528
+ };
3529
+ function threadEditFields(options) {
3530
+ const source = options;
3531
+ return {
3532
+ name: typeof source.name === "string" ? source.name : void 0,
3533
+ archived: source.archived,
3534
+ autoArchiveDuration: source.autoArchiveDuration,
3535
+ locked: source.locked,
3536
+ rateLimitPerUser: source.rateLimitPerUser,
3537
+ flags: source.flags,
3538
+ appliedTags: source.appliedTags,
3539
+ invitable: source.invitable,
3540
+ reason: source.reason
3541
+ };
3542
+ }
3543
+ function readMetadata(data) {
3544
+ return {
3545
+ archived: data?.archived ?? false,
3546
+ autoArchiveDuration: data?.auto_archive_duration ?? 0,
3547
+ archiveTimestamp: data?.archive_timestamp ?? null,
3548
+ locked: data?.locked ?? false,
3549
+ invitable: data?.invitable ?? null
3550
+ };
3551
+ }
3552
+ var ThreadChannel = class extends TextCapable(GuildChannel) {
3553
+ /** User who created the thread. */
3554
+ ownerId;
3555
+ /** Whether the thread is archived. */
3556
+ archived;
3557
+ /** Minutes of inactivity before the thread archives. */
3558
+ autoArchiveDuration;
3559
+ /** ISO-8601 timestamp when the archive status last changed. */
3560
+ archiveTimestamp;
3561
+ /** Whether only moderators can unarchive the thread. */
3562
+ locked;
3563
+ /** Whether non-moderators can add other non-moderators. Private threads only. */
3564
+ invitable;
3565
+ /** Slowmode in seconds. */
3566
+ rateLimitPerUser;
3567
+ /** ID of the last message sent in this thread. */
3568
+ lastMessageId;
3569
+ /** Messages in the thread, excluding the starter and deleted messages. */
3570
+ messageCount;
3571
+ /** Messages ever sent in the thread. This count is never decremented. */
3572
+ totalMessageSent;
3573
+ /** Approximate member count, capped at 50. */
3574
+ memberCount;
3575
+ /** Tag IDs applied to a forum or media post. */
3576
+ appliedTags;
3577
+ /** Channel flags bitfield. */
3578
+ flags;
3579
+ /** The current user's membership, when the payload included it. */
3580
+ member;
3581
+ /** Add, remove, and list members of this thread. */
3582
+ members;
3583
+ constructor(client, data) {
3584
+ super(client, data);
3585
+ const metadata = readMetadata(data.thread_metadata);
3586
+ this.ownerId = data.owner_id ?? null;
3587
+ this.archived = metadata.archived;
3588
+ this.autoArchiveDuration = metadata.autoArchiveDuration;
3589
+ this.archiveTimestamp = metadata.archiveTimestamp;
3590
+ this.locked = metadata.locked;
3591
+ this.invitable = metadata.invitable;
3592
+ this.rateLimitPerUser = data.rate_limit_per_user ?? 0;
3593
+ this.lastMessageId = data.last_message_id ?? null;
3594
+ this.messageCount = data.message_count ?? 0;
3595
+ this.totalMessageSent = data.total_message_sent ?? 0;
3596
+ this.memberCount = data.member_count ?? 0;
3597
+ this.appliedTags = data.applied_tags ?? [];
3598
+ this.flags = data.flags ?? 0;
3599
+ this.member = data.member ? new ThreadMember(data.member) : null;
3600
+ this.members = new ThreadMemberManager(this);
3601
+ }
3602
+ /** @internal */
3603
+ _patch(data) {
3604
+ super._patch(data);
3605
+ if (data.owner_id !== void 0) this.ownerId = data.owner_id ?? null;
3606
+ if (data.thread_metadata) {
3607
+ const metadata = readMetadata(data.thread_metadata);
3608
+ this.archived = metadata.archived;
3609
+ this.autoArchiveDuration = metadata.autoArchiveDuration;
3610
+ this.archiveTimestamp = metadata.archiveTimestamp;
3611
+ this.locked = metadata.locked;
3612
+ this.invitable = metadata.invitable;
3613
+ }
3614
+ if ("rate_limit_per_user" in data && data.rate_limit_per_user !== void 0) {
3615
+ this.rateLimitPerUser = data.rate_limit_per_user ?? 0;
3616
+ }
3617
+ if ("last_message_id" in data) this.lastMessageId = data.last_message_id ?? null;
3618
+ if (data.message_count !== void 0) this.messageCount = data.message_count;
3619
+ if (data.total_message_sent !== void 0) this.totalMessageSent = data.total_message_sent;
3620
+ if (data.member_count !== void 0) this.memberCount = data.member_count;
3621
+ if (data.applied_tags !== void 0) this.appliedTags = data.applied_tags ?? [];
3622
+ if (data.flags !== void 0) this.flags = data.flags;
3623
+ if (data.member !== void 0) this.member = data.member ? new ThreadMember(data.member) : null;
3624
+ }
3625
+ /**
3626
+ * Edit this thread. Requires Manage Threads on public threads, or ownership on private ones.
3627
+ * `appliedTags` is sent for public and announcement threads. `invitable` is sent for private threads.
3628
+ */
3629
+ async edit(options) {
3630
+ const data = await this.client.rest.patch(Routes14.channel(this.id), {
3631
+ body: toThreadEditBody(this.type, threadEditFields(options)),
3632
+ auth: true,
3633
+ ...auditReasonHeaders(options.reason)
3634
+ });
3635
+ this._patch(data);
3636
+ return this;
3637
+ }
3638
+ /** Archive or unarchive this thread. */
3639
+ async setArchived(archived, reason) {
3640
+ return this.edit({ archived, reason });
3641
+ }
3642
+ /** Lock or unlock this thread. Locked threads can only be unarchived by moderators. */
3643
+ async setLocked(locked, reason) {
3644
+ return this.edit({ locked, reason });
3645
+ }
3646
+ /** Join this thread. */
3647
+ async join() {
3648
+ await this.client.rest.put(Routes14.channelThreadMemberMe(this.id), { auth: true });
3649
+ }
3650
+ /** Leave this thread. */
3651
+ async leave() {
3652
+ await this.client.rest.delete(Routes14.channelThreadMemberMe(this.id), { auth: true });
3653
+ }
3654
+ /** Update the current user's notification settings for this thread. */
3655
+ async editSelf(options) {
3656
+ const data = await this.client.rest.patch(
3657
+ Routes14.channelThreadMemberMeSettings(this.id),
3658
+ { body: toThreadMemberSettingsBody(options), auth: true }
3659
+ );
3660
+ this.member = data ? new ThreadMember(data) : null;
3661
+ return this.member;
3662
+ }
3663
+ };
3664
+ var ThreadMemberManager = class {
3665
+ constructor(thread) {
3666
+ this.thread = thread;
3667
+ }
3668
+ /** List members of this thread. */
3669
+ async fetch(options) {
3670
+ const data = await this.thread.client.rest.get(
3671
+ withQuery(Routes14.channelThreadMembers(this.thread.id), {
3672
+ with_member: options?.withMember === void 0 ? void 0 : String(options.withMember),
3673
+ after: options?.after,
3674
+ limit: options?.limit
3675
+ })
3676
+ );
3677
+ return data.map((member) => new ThreadMember(member));
3678
+ }
3679
+ /** Fetch one member of this thread. */
3680
+ async fetchOne(userId, options) {
3681
+ const data = await this.thread.client.rest.get(
3682
+ withQuery(Routes14.channelThreadMember(this.thread.id, userId), {
3683
+ with_member: options?.withMember === void 0 ? void 0 : String(options.withMember)
3684
+ })
3685
+ );
3686
+ return new ThreadMember(data);
3687
+ }
3688
+ /** Add a user to this thread. Private threads only, unless the caller can manage the parent. */
3689
+ async add(userId) {
3690
+ await this.thread.client.rest.put(Routes14.channelThreadMember(this.thread.id, userId), {
3691
+ auth: true
3692
+ });
3693
+ }
3694
+ /** Remove a user from this thread. */
3695
+ async remove(userId) {
3696
+ await this.thread.client.rest.delete(Routes14.channelThreadMember(this.thread.id, userId), {
3697
+ auth: true
3698
+ });
3699
+ }
3700
+ };
3701
+ function isThreadType(type) {
3702
+ return type === ChannelType5.AnnouncementThread || type === ChannelType5.PublicThread || type === ChannelType5.PrivateThread;
3703
+ }
3704
+
3705
+ // src/Domain/Channel/ThreadManager.ts
3706
+ var ThreadManager = class {
3707
+ constructor(channel) {
3708
+ this.channel = channel;
3709
+ }
3710
+ /**
3711
+ * Start a thread in a text or announcement channel.
3712
+ * Forum and media channels must use {@link createPost}.
3713
+ */
3714
+ async create(options) {
3715
+ if (this.channel.type === ChannelType6.GuildForum || this.channel.type === ChannelType6.GuildMedia) {
3716
+ throw new FluxerError("Forum and media channels start posts with createPost", {
3717
+ code: ErrorCodes.InvalidChannelType
3718
+ });
3719
+ }
3720
+ const data = await this.channel.client.rest.post(
3721
+ Routes15.channelThreads(this.channel.id),
3722
+ {
3723
+ body: toStartThreadBody(this.channel.type, options),
3724
+ auth: true,
3725
+ ...auditReasonHeaders(options.reason)
3726
+ }
3727
+ );
3728
+ return cacheThread(this.channel.client, data);
3729
+ }
3730
+ /**
3731
+ * Start a post in a forum or media channel.
3732
+ * The post is a public thread. `message` is its first message.
3733
+ */
3734
+ async createPost(options) {
3735
+ if (this.channel.type !== ChannelType6.GuildForum && this.channel.type !== ChannelType6.GuildMedia) {
3736
+ throw new FluxerError("createPost is for forum and media channels", {
3737
+ code: ErrorCodes.InvalidChannelType
3738
+ });
3739
+ }
3740
+ const prepared = await prepareMessagePostPayload(options.message, {
3741
+ defaultAllowedMentions: this.channel.client.options.defaultAllowedMentions
3742
+ });
3743
+ const body = {
3744
+ name: options.name,
3745
+ type: ChannelType6.PublicThread,
3746
+ message: toForumThreadMessage(prepared.body)
3747
+ };
3748
+ if (options.autoArchiveDuration !== void 0) {
3749
+ body.auto_archive_duration = options.autoArchiveDuration;
3750
+ }
3751
+ if (options.rateLimitPerUser !== void 0) body.rate_limit_per_user = options.rateLimitPerUser;
3752
+ if (options.appliedTags !== void 0) body.applied_tags = options.appliedTags;
3753
+ const data = await this.channel.client.rest.post(
3754
+ Routes15.channelThreads(this.channel.id),
3755
+ {
3756
+ body,
3757
+ files: prepared.files,
3758
+ auth: true,
3759
+ ...auditReasonHeaders(options.reason)
3760
+ }
3761
+ );
3762
+ const thread = cacheThread(this.channel.client, data);
3763
+ if (data.message) {
3764
+ this.channel.client._addMessageToCache(data.message.channel_id, data.message);
3765
+ }
3766
+ return thread;
3767
+ }
3768
+ /**
3769
+ * List archived threads in this channel.
3770
+ * `before` is an ISO-8601 archive timestamp.
3771
+ */
3772
+ async fetchArchived(options) {
3773
+ const path = options.type === "private" ? Routes15.channelThreadsArchivedPrivate(this.channel.id) : Routes15.channelThreadsArchivedPublic(this.channel.id);
3774
+ const data = await this.channel.client.rest.get(
3775
+ withQuery(path, { before: options.before, limit: options.limit })
3776
+ );
3777
+ return fetchedThreadsFrom(this.channel.client, data);
3139
3778
  }
3140
3779
  /**
3141
- * Set slowmode (seconds between messages). Pass `0` to disable.
3142
- * Requires Manage Channels. Calls {@link GuildChannel.edit} with `rateLimitPerUser`.
3780
+ * List private archived threads in this channel that the current user has joined.
3781
+ * `before` is a thread snowflake.
3143
3782
  */
3144
- async setSlowmode(seconds) {
3145
- return this.edit({ rateLimitPerUser: seconds });
3783
+ async fetchJoinedPrivateArchived(options) {
3784
+ const data = await this.channel.client.rest.get(
3785
+ withQuery(Routes15.channelJoinedArchivedPrivateThreads(this.channel.id), {
3786
+ before: options?.before,
3787
+ limit: options?.limit
3788
+ })
3789
+ );
3790
+ return fetchedThreadsFrom(this.channel.client, data);
3146
3791
  }
3147
- applyEditPatch(data) {
3148
- if ("topic" in data) this.topic = data.topic ?? null;
3149
- if ("nsfw" in data) this.nsfw = data.nsfw ?? false;
3150
- if ("nsfw_override" in data) this.nsfwOverride = data.nsfw_override ?? null;
3151
- if ("rate_limit_per_user" in data) this.rateLimitPerUser = data.rate_limit_per_user ?? 0;
3152
- if ("last_message_id" in data) this.lastMessageId = data.last_message_id ?? null;
3153
- if ("content_warning_level" in data) {
3154
- this.contentWarningLevel = data.content_warning_level ?? null;
3155
- }
3156
- if ("content_warning_text" in data) {
3157
- this.contentWarningText = data.content_warning_text ?? null;
3792
+ /**
3793
+ * Search threads in this channel.
3794
+ * Returns `{ indexing: true }` while the search index is still building.
3795
+ */
3796
+ async search(options) {
3797
+ const data = await this.channel.client.rest.get(
3798
+ withQuery(Routes15.channelThreadSearch(this.channel.id), {
3799
+ name: options?.name,
3800
+ tag: options?.tag,
3801
+ tag_setting: options?.tagSetting,
3802
+ archived: options?.archived === void 0 ? void 0 : String(options.archived),
3803
+ sort_by: options?.sortBy,
3804
+ sort_order: options?.sortOrder,
3805
+ limit: options?.limit,
3806
+ offset: options?.offset,
3807
+ max_id: options?.maxId,
3808
+ min_id: options?.minId
3809
+ })
3810
+ );
3811
+ if (isSearchNotReady(data)) {
3812
+ return { indexing: true, retryAfter: data.retry_after, message: data.message };
3158
3813
  }
3814
+ const page = fetchedThreadsFrom(this.channel.client, data);
3815
+ return {
3816
+ ...page,
3817
+ hasMore: data.has_more,
3818
+ totalResults: data.total_results,
3819
+ firstMessages: (data.first_messages ?? []).map(
3820
+ (message) => new Message(this.channel.client, message)
3821
+ )
3822
+ };
3823
+ }
3824
+ /** Set the auto-archive and slowmode defaults copied onto new threads. */
3825
+ async editDefaults(options) {
3826
+ return this.channel.client.rest.patch(Routes15.channel(this.channel.id), {
3827
+ body: toThreadParentEditBody(options),
3828
+ auth: true,
3829
+ ...auditReasonHeaders(options.reason)
3830
+ });
3159
3831
  }
3160
3832
  };
3161
- var AnnouncementChannel = class extends TextChannel {
3162
- };
3163
- var CategoryChannel = class extends GuildChannel {
3164
- };
3165
- var VoiceChannel = class extends TextCapable(GuildChannel) {
3166
- /** Channel topic. */
3167
- topic;
3168
- /** Whether this channel is marked as NSFW. */
3169
- nsfw;
3170
- /** Per-channel NSFW override (`null` inherits). */
3171
- nsfwOverride;
3172
- /** Slowmode rate limit in seconds. */
3173
- rateLimitPerUser;
3174
- /** ID of the last message sent in this channel. */
3175
- lastMessageId;
3176
- /** Content warning level. */
3177
- contentWarningLevel;
3178
- /** Custom content warning text. */
3179
- contentWarningText;
3180
- /** Voice bitrate. */
3181
- bitrate;
3182
- /** Maximum number of users allowed. */
3183
- userLimit;
3184
- /** Max active voice connections per user. */
3185
- voiceConnectionLimit;
3186
- /** RTC region override for this channel. */
3187
- rtcRegion;
3833
+ function fetchedThreadsFrom(client, data) {
3834
+ return {
3835
+ threads: (data.threads ?? []).map((thread) => cacheThread(client, thread)),
3836
+ members: (data.members ?? []).map((member) => new ThreadMember(member)),
3837
+ hasMore: data.has_more ?? false
3838
+ };
3839
+ }
3840
+ function isSearchNotReady(data) {
3841
+ return "code" in data && data.code === "SEARCH_INDEX_NOT_READY";
3842
+ }
3843
+ async function fetchActiveThreads(client, guildId) {
3844
+ const data = await client.rest.get(Routes15.guildActiveThreads(guildId));
3845
+ return fetchedThreadsFrom(client, data);
3846
+ }
3847
+
3848
+ // src/Domain/Channel/Forum.ts
3849
+ function tagsFrom(data) {
3850
+ return data ?? [];
3851
+ }
3852
+ var ThreadOnlyChannel = class extends GuildChannel {
3853
+ /** Tags that can be applied to posts. */
3854
+ availableTags;
3855
+ /** Default reaction for new posts. */
3856
+ defaultReactionEmoji;
3857
+ /** Default sort order for posts. */
3858
+ defaultSortOrder;
3859
+ /** How posts are filtered when searching by several tags. */
3860
+ defaultTagSetting;
3861
+ /** Default auto-archive duration in minutes for new posts. */
3862
+ defaultAutoArchiveDuration;
3863
+ /** Slowmode in seconds copied onto new posts. */
3864
+ defaultThreadRateLimitPerUser;
3865
+ /** Channel flags bitfield. */
3866
+ flags;
3867
+ /** Create, list, and search posts in this channel. */
3868
+ threads;
3188
3869
  constructor(client, data) {
3189
3870
  super(client, data);
3190
- this.topic = data.topic ?? null;
3191
- this.nsfw = data.nsfw ?? false;
3192
- this.nsfwOverride = data.nsfw_override ?? null;
3193
- this.rateLimitPerUser = data.rate_limit_per_user ?? 0;
3194
- this.lastMessageId = data.last_message_id ?? null;
3195
- this.contentWarningLevel = data.content_warning_level ?? null;
3196
- this.contentWarningText = data.content_warning_text ?? null;
3197
- this.bitrate = data.bitrate ?? null;
3198
- this.userLimit = data.user_limit ?? null;
3199
- this.voiceConnectionLimit = data.voice_connection_limit ?? null;
3200
- this.rtcRegion = data.rtc_region ?? null;
3201
- }
3202
- /**
3203
- * Set slowmode (seconds between messages). Pass `0` to disable.
3204
- * Requires Manage Channels. Calls {@link GuildChannel.edit} with `rateLimitPerUser`.
3205
- */
3206
- async setSlowmode(seconds) {
3207
- return this.edit({ rateLimitPerUser: seconds });
3871
+ this.availableTags = tagsFrom(data.available_tags);
3872
+ this.defaultReactionEmoji = data.default_reaction_emoji ?? null;
3873
+ this.defaultSortOrder = data.default_sort_order ?? null;
3874
+ this.defaultTagSetting = data.default_tag_setting ?? null;
3875
+ this.defaultAutoArchiveDuration = data.default_auto_archive_duration ?? null;
3876
+ this.defaultThreadRateLimitPerUser = data.default_thread_rate_limit_per_user ?? null;
3877
+ this.flags = data.flags ?? 0;
3878
+ this.threads = new ThreadManager(this);
3208
3879
  }
3209
- applyEditPatch(data) {
3210
- if ("topic" in data) this.topic = data.topic ?? null;
3211
- if ("nsfw" in data) this.nsfw = data.nsfw ?? false;
3212
- if ("nsfw_override" in data) this.nsfwOverride = data.nsfw_override ?? null;
3213
- if ("rate_limit_per_user" in data) this.rateLimitPerUser = data.rate_limit_per_user ?? 0;
3214
- if ("last_message_id" in data) this.lastMessageId = data.last_message_id ?? null;
3215
- if ("content_warning_level" in data) {
3216
- this.contentWarningLevel = data.content_warning_level ?? null;
3880
+ /** @internal */
3881
+ _patch(data) {
3882
+ super._patch(data);
3883
+ if (data.available_tags !== void 0) this.availableTags = tagsFrom(data.available_tags);
3884
+ if ("default_reaction_emoji" in data) {
3885
+ this.defaultReactionEmoji = data.default_reaction_emoji ?? null;
3217
3886
  }
3218
- if ("content_warning_text" in data) {
3219
- this.contentWarningText = data.content_warning_text ?? null;
3887
+ if ("default_sort_order" in data) this.defaultSortOrder = data.default_sort_order ?? null;
3888
+ if ("default_tag_setting" in data) this.defaultTagSetting = data.default_tag_setting ?? null;
3889
+ if ("default_auto_archive_duration" in data) {
3890
+ this.defaultAutoArchiveDuration = data.default_auto_archive_duration ?? null;
3220
3891
  }
3221
- if ("bitrate" in data) this.bitrate = data.bitrate ?? null;
3222
- if ("user_limit" in data) this.userLimit = data.user_limit ?? null;
3223
- if ("voice_connection_limit" in data) {
3224
- this.voiceConnectionLimit = data.voice_connection_limit ?? null;
3892
+ if ("default_thread_rate_limit_per_user" in data) {
3893
+ this.defaultThreadRateLimitPerUser = data.default_thread_rate_limit_per_user ?? null;
3225
3894
  }
3226
- if ("rtc_region" in data) this.rtcRegion = data.rtc_region ?? null;
3895
+ if (data.flags !== void 0) this.flags = data.flags;
3896
+ }
3897
+ /**
3898
+ * Edit this channel.
3899
+ * Tag, sort, reaction, and thread-default fields are sent with the usual channel fields.
3900
+ * `defaultForumLayout` is sent only for forum channels.
3901
+ */
3902
+ async edit(options) {
3903
+ const data = await this.client.rest.patch(Routes16.channel(this.id), {
3904
+ body: {
3905
+ ...toChannelEditBody(options),
3906
+ ...forumParentWire(options, this.type === ChannelType7.GuildForum)
3907
+ },
3908
+ auth: true,
3909
+ ...auditReasonHeaders(options.reason)
3910
+ });
3911
+ this._patch(data);
3912
+ return this;
3913
+ }
3914
+ /** Replace the tags that can be applied to posts (max 20). */
3915
+ async setAvailableTags(tags, reason) {
3916
+ return this.edit({ availableTags: tags, reason });
3917
+ }
3918
+ /** Set or clear the default reaction on new posts. */
3919
+ async setDefaultReactionEmoji(emoji, reason) {
3920
+ return this.edit({ defaultReactionEmoji: emoji, reason });
3921
+ }
3922
+ /** Set or clear the default post sort order. */
3923
+ async setDefaultSortOrder(order, reason) {
3924
+ return this.edit({ defaultSortOrder: order, reason });
3925
+ }
3926
+ /** Set or clear how posts match when several tags are selected. */
3927
+ async setDefaultTagSetting(setting, reason) {
3928
+ return this.edit({ defaultTagSetting: setting, reason });
3929
+ }
3930
+ /** Set the auto-archive and slowmode defaults copied onto new posts. */
3931
+ async editThreadDefaults(options) {
3932
+ const data = await this.client.rest.patch(Routes16.channel(this.id), {
3933
+ body: toThreadParentEditBody(options),
3934
+ auth: true,
3935
+ ...auditReasonHeaders(options.reason)
3936
+ });
3937
+ this._patch(data);
3938
+ return this;
3939
+ }
3940
+ /** Create a tag. The response replaces {@link availableTags}. */
3941
+ async createTag(options) {
3942
+ const data = await this.client.rest.post(Routes16.channelTags(this.id), {
3943
+ body: toForumTagBody(options),
3944
+ auth: true,
3945
+ ...auditReasonHeaders(options.reason)
3946
+ });
3947
+ this._patch(data);
3948
+ return this;
3949
+ }
3950
+ /** Replace a tag. The response replaces {@link availableTags}. */
3951
+ async editTag(tagId, options) {
3952
+ const data = await this.client.rest.put(Routes16.channelTag(this.id, tagId), {
3953
+ body: toForumTagBody(options),
3954
+ auth: true,
3955
+ ...auditReasonHeaders(options.reason)
3956
+ });
3957
+ this._patch(data);
3958
+ return this;
3959
+ }
3960
+ /** Delete a tag. The response replaces {@link availableTags}. */
3961
+ async deleteTag(tagId, reason) {
3962
+ const data = await this.client.rest.delete(Routes16.channelTag(this.id, tagId), {
3963
+ auth: true,
3964
+ ...auditReasonHeaders(reason)
3965
+ });
3966
+ this._patch(data);
3967
+ return this;
3227
3968
  }
3228
3969
  };
3229
- var LinkChannel = class extends GuildChannel {
3230
- /** External URL this channel links to. */
3231
- url;
3970
+ var ForumChannel = class extends ThreadOnlyChannel {
3971
+ /** Default layout for posts. */
3972
+ defaultForumLayout;
3973
+ /** Set or clear the default post layout. */
3974
+ async setDefaultForumLayout(layout, reason) {
3975
+ return this.edit({ defaultForumLayout: layout, reason });
3976
+ }
3232
3977
  constructor(client, data) {
3233
3978
  super(client, data);
3234
- this.url = data.url ?? null;
3979
+ this.defaultForumLayout = data.default_forum_layout ?? null;
3235
3980
  }
3236
- applyEditPatch(data) {
3237
- if ("url" in data) this.url = data.url ?? null;
3981
+ /** @internal */
3982
+ _patch(data) {
3983
+ super._patch(data);
3984
+ if ("default_forum_layout" in data) this.defaultForumLayout = data.default_forum_layout ?? null;
3238
3985
  }
3239
3986
  };
3987
+ var MediaChannel = class extends ThreadOnlyChannel {
3988
+ };
3240
3989
 
3241
3990
  // src/Domain/Channel/Factory.ts
3242
- import { ChannelType as ChannelType3 } from "@fluxerjs/types";
3991
+ import { ChannelType as ChannelType8 } from "@fluxerjs/types";
3243
3992
  var GUILD_FACTORIES = {
3244
- [ChannelType3.GuildText]: (c, d) => new TextChannel(c, d),
3245
- [ChannelType3.GuildAnnouncement]: (c, d) => new AnnouncementChannel(c, d),
3246
- [ChannelType3.GuildCategory]: (c, d) => new CategoryChannel(c, d),
3247
- [ChannelType3.GuildVoice]: (c, d) => new VoiceChannel(c, d),
3248
- [ChannelType3.GuildLink]: (c, d) => new LinkChannel(c, d)
3993
+ [ChannelType8.GuildText]: (c, d) => new TextChannel(c, d),
3994
+ [ChannelType8.GuildAnnouncement]: (c, d) => new AnnouncementChannel(c, d),
3995
+ [ChannelType8.GuildCategory]: (c, d) => new CategoryChannel(c, d),
3996
+ [ChannelType8.GuildVoice]: (c, d) => new VoiceChannel(c, d),
3997
+ [ChannelType8.GuildLink]: (c, d) => new LinkChannel(c, d),
3998
+ [ChannelType8.AnnouncementThread]: (c, d) => new ThreadChannel(c, d),
3999
+ [ChannelType8.PublicThread]: (c, d) => new ThreadChannel(c, d),
4000
+ [ChannelType8.PrivateThread]: (c, d) => new ThreadChannel(c, d),
4001
+ [ChannelType8.GuildForum]: (c, d) => new ForumChannel(c, d),
4002
+ [ChannelType8.GuildMedia]: (c, d) => new MediaChannel(c, d)
3249
4003
  };
3250
4004
  var DM_TYPES = /* @__PURE__ */ new Set([
3251
- ChannelType3.DM,
3252
- ChannelType3.GroupDM,
3253
- ChannelType3.DMPersonalNotes
4005
+ ChannelType8.DM,
4006
+ ChannelType8.GroupDM,
4007
+ ChannelType8.DMPersonalNotes
3254
4008
  ]);
3255
4009
  function createDM(client, data) {
3256
4010
  return new DMChannel(client, data);
3257
4011
  }
3258
4012
  function channelFrom(client, data) {
3259
- const factory = GUILD_FACTORIES[data.type ?? 0];
3260
- return factory ? factory(client, data) : new GuildChannel(client, data);
4013
+ const factory2 = GUILD_FACTORIES[data.type ?? 0];
4014
+ return factory2 ? factory2(client, data) : new GuildChannel(client, data);
3261
4015
  }
3262
4016
  function channelFromOrCreate(client, data) {
3263
4017
  return DM_TYPES.has(data.type ?? 0) ? createDM(client, data) : channelFrom(client, data);
@@ -3267,6 +4021,7 @@ function channelFromOrCreate(client, data) {
3267
4021
  Channel.from = channelFrom;
3268
4022
  Channel.fromOrCreate = channelFromOrCreate;
3269
4023
  Channel.createDM = createDM;
4024
+ bindThreadManager((channel) => new ThreadManager(channel));
3270
4025
 
3271
4026
  // src/Domain/User.ts
3272
4027
  var User = class extends Base {
@@ -3366,7 +4121,7 @@ var User = class extends Base {
3366
4121
  * @returns DM channel instance (cached if already open)
3367
4122
  */
3368
4123
  async createDM() {
3369
- const data = await this.client.rest.post(Routes14.userMeChannels(), {
4124
+ const data = await this.client.rest.post(Routes17.userMeChannels(), {
3370
4125
  body: { recipient_id: this.id },
3371
4126
  auth: true
3372
4127
  });
@@ -3583,10 +4338,13 @@ var CacheController = class {
3583
4338
 
3584
4339
  // src/ClientCore/ChannelManager.ts
3585
4340
  import { LimitedCollection } from "@fluxerjs/collection";
3586
- import { Routes as Routes20 } from "@fluxerjs/types";
4341
+ import { Routes as Routes23 } from "@fluxerjs/types";
4342
+
4343
+ // src/Domain/Guild/Cache.ts
4344
+ import { ChannelType as ChannelType9 } from "@fluxerjs/types";
3587
4345
 
3588
4346
  // src/Domain/Guild/GuildEmoji.ts
3589
- import { Routes as Routes15 } from "@fluxerjs/types";
4347
+ import { Routes as Routes18 } from "@fluxerjs/types";
3590
4348
  import { SnowflakeUtil as SnowflakeUtil6 } from "@fluxerjs/util";
3591
4349
  var GuildEmoji = class extends Base {
3592
4350
  client;
@@ -3635,7 +4393,7 @@ var GuildEmoji = class extends Base {
3635
4393
  }
3636
4394
  /** Delete this emoji. Requires Manage Emojis and Stickers permission. */
3637
4395
  async delete(reason) {
3638
- await this.client.rest.delete(Routes15.guildEmoji(this.guildId, this.id), {
4396
+ await this.client.rest.delete(Routes18.guildEmoji(this.guildId, this.id), {
3639
4397
  auth: true,
3640
4398
  ...auditReasonHeaders(reason)
3641
4399
  });
@@ -3648,7 +4406,7 @@ var GuildEmoji = class extends Base {
3648
4406
  */
3649
4407
  async edit(options) {
3650
4408
  const { reason, name } = options;
3651
- const data = await this.client.rest.patch(Routes15.guildEmoji(this.guildId, this.id), {
4409
+ const data = await this.client.rest.patch(Routes18.guildEmoji(this.guildId, this.id), {
3652
4410
  body: { name },
3653
4411
  auth: true,
3654
4412
  ...auditReasonHeaders(reason)
@@ -3659,7 +4417,7 @@ var GuildEmoji = class extends Base {
3659
4417
  };
3660
4418
 
3661
4419
  // src/Domain/Guild/GuildMember.ts
3662
- import { Routes as Routes17 } from "@fluxerjs/types";
4420
+ import { Routes as Routes20 } from "@fluxerjs/types";
3663
4421
  import { PermissionFlags as PermissionFlags3, PermissionsBitField as PermissionsBitField2 } from "@fluxerjs/util";
3664
4422
 
3665
4423
  // src/Helpers/Permissions.ts
@@ -3683,7 +4441,7 @@ function computePermissions(basePermissions, overwrites, memberRoles, memberId,
3683
4441
 
3684
4442
  // src/Domain/Guild/GuildMemberRoleManager.ts
3685
4443
  import { Collection as Collection7 } from "@fluxerjs/collection";
3686
- import { Routes as Routes16 } from "@fluxerjs/types";
4444
+ import { Routes as Routes19 } from "@fluxerjs/types";
3687
4445
  function roleId(roleOrId) {
3688
4446
  return typeof roleOrId === "string" ? roleOrId : roleOrId.id;
3689
4447
  }
@@ -3712,7 +4470,7 @@ var GuildMemberRoleManager = class {
3712
4470
  const id = roleId(roleOrId);
3713
4471
  if (this.ids.includes(id)) return;
3714
4472
  await this.member.client.rest.put(
3715
- Routes16.guildMemberRole(this.member.guild.id, this.member.id, id)
4473
+ Routes19.guildMemberRole(this.member.guild.id, this.member.id, id)
3716
4474
  );
3717
4475
  this.ids.push(id);
3718
4476
  }
@@ -3721,13 +4479,13 @@ var GuildMemberRoleManager = class {
3721
4479
  const idx = this.ids.indexOf(id);
3722
4480
  if (idx === -1) return;
3723
4481
  await this.member.client.rest.delete(
3724
- Routes16.guildMemberRole(this.member.guild.id, this.member.id, id)
4482
+ Routes19.guildMemberRole(this.member.guild.id, this.member.id, id)
3725
4483
  );
3726
4484
  this.ids.splice(idx, 1);
3727
4485
  }
3728
4486
  async set(roleIds) {
3729
4487
  const data = await this.member.client.rest.patch(
3730
- Routes16.guildMember(this.member.guild.id, this.member.id),
4488
+ Routes19.guildMember(this.member.guild.id, this.member.id),
3731
4489
  { body: { roles: roleIds }, auth: true }
3732
4490
  );
3733
4491
  this.ids = data.roles ? [...data.roles] : [];
@@ -3881,7 +4639,7 @@ var GuildMember = class _GuildMember extends Base {
3881
4639
  */
3882
4640
  async edit(options) {
3883
4641
  const isMe = this.client.user?.id === this.id;
3884
- const route = isMe ? Routes17.guildMemberMe(this.guild.id) : Routes17.guildMember(this.guild.id, this.id);
4642
+ const route = isMe ? Routes20.guildMemberMe(this.guild.id) : Routes20.guildMember(this.guild.id, this.id);
3885
4643
  const data = await this.client.rest.patch(route, {
3886
4644
  body: toMemberEditBody(options),
3887
4645
  auth: true,
@@ -3994,7 +4752,7 @@ var GuildMember = class _GuildMember extends Base {
3994
4752
  };
3995
4753
 
3996
4754
  // src/Domain/Guild/GuildSticker.ts
3997
- import { Routes as Routes18 } from "@fluxerjs/types";
4755
+ import { Routes as Routes21 } from "@fluxerjs/types";
3998
4756
  import { SnowflakeUtil as SnowflakeUtil7 } from "@fluxerjs/util";
3999
4757
  var GuildSticker = class extends Base {
4000
4758
  client;
@@ -4045,7 +4803,7 @@ var GuildSticker = class extends Base {
4045
4803
  }
4046
4804
  /** Delete this sticker. Requires Manage Emojis and Stickers permission. */
4047
4805
  async delete(reason) {
4048
- await this.client.rest.delete(Routes18.guildSticker(this.guildId, this.id), {
4806
+ await this.client.rest.delete(Routes21.guildSticker(this.guildId, this.id), {
4049
4807
  auth: true,
4050
4808
  ...auditReasonHeaders(reason)
4051
4809
  });
@@ -4058,7 +4816,7 @@ var GuildSticker = class extends Base {
4058
4816
  */
4059
4817
  async edit(options) {
4060
4818
  const { reason, ...body } = options;
4061
- const data = await this.client.rest.patch(Routes18.guildSticker(this.guildId, this.id), {
4819
+ const data = await this.client.rest.patch(Routes21.guildSticker(this.guildId, this.id), {
4062
4820
  body,
4063
4821
  auth: true,
4064
4822
  ...auditReasonHeaders(reason)
@@ -4071,7 +4829,7 @@ var GuildSticker = class extends Base {
4071
4829
  };
4072
4830
 
4073
4831
  // src/Domain/Guild/Role.ts
4074
- import { Routes as Routes19 } from "@fluxerjs/types";
4832
+ import { Routes as Routes22 } from "@fluxerjs/types";
4075
4833
  import {
4076
4834
  ALL_PERMISSIONS_BIGINT as ALL_PERMISSIONS_BIGINT2,
4077
4835
  PermissionFlags as PermissionFlags4,
@@ -4186,7 +4944,7 @@ var Role = class _Role extends Base {
4186
4944
  */
4187
4945
  async edit(options) {
4188
4946
  const body = toRoleEditBody(options);
4189
- const data = await this.client.rest.patch(Routes19.guildRole(this.guildId, this.id), {
4947
+ const data = await this.client.rest.patch(Routes22.guildRole(this.guildId, this.id), {
4190
4948
  body: Object.keys(body).length ? body : void 0,
4191
4949
  auth: true,
4192
4950
  ...auditReasonHeaders(options.reason)
@@ -4199,7 +4957,7 @@ var Role = class _Role extends Base {
4199
4957
  * @param reason - Audit log reason (`X-Audit-Log-Reason`)
4200
4958
  */
4201
4959
  async delete(reason) {
4202
- await this.client.rest.delete(Routes19.guildRole(this.guildId, this.id), {
4960
+ await this.client.rest.delete(Routes22.guildRole(this.guildId, this.id), {
4203
4961
  auth: true,
4204
4962
  ...auditReasonHeaders(reason)
4205
4963
  });
@@ -4294,11 +5052,30 @@ function syncChannels(guild, channels) {
4294
5052
  const keep = new Set(channels.map((c) => c.id));
4295
5053
  for (const data of channels) cacheChannel(guild, data);
4296
5054
  for (const [id, channel] of [...guild.channels.entries()]) {
4297
- if (keep.has(id)) continue;
5055
+ if (keep.has(id) || channel.isThread()) continue;
4298
5056
  Map.prototype.delete.call(guild.channels, id);
4299
5057
  guild.client.cache.cascadeChannel(channel, "guild");
4300
5058
  }
4301
5059
  }
5060
+ function isThreadChannelType(type) {
5061
+ return type === ChannelType9.AnnouncementThread || type === ChannelType9.PublicThread || type === ChannelType9.PrivateThread;
5062
+ }
5063
+ function syncThreads(guild, threads, alsoKeep = /* @__PURE__ */ new Set()) {
5064
+ const keep = new Set(alsoKeep);
5065
+ for (const data of threads) {
5066
+ if (!isThreadChannelType(data.type)) continue;
5067
+ const withGuild = data.guild_id ? data : { ...data, guild_id: guild.id };
5068
+ cacheThread(guild.client, withGuild);
5069
+ keep.add(data.id);
5070
+ }
5071
+ const seen = /* @__PURE__ */ new Set();
5072
+ for (const channel of [...guild.channels.values(), ...guild.client.channels.values()]) {
5073
+ if (seen.has(channel.id)) continue;
5074
+ seen.add(channel.id);
5075
+ if (!channel.isThread() || channel.guildId !== guild.id || keep.has(channel.id)) continue;
5076
+ guild.client.cache.cascadeChannel(channel);
5077
+ }
5078
+ }
4302
5079
  function mergeMembers(guild, members) {
4303
5080
  for (const m of members) {
4304
5081
  if (!m.user?.id) continue;
@@ -4362,7 +5139,7 @@ var ChannelManager = class extends LimitedCollection {
4362
5139
  const cached = this.get(channelId);
4363
5140
  if (cached && !options?.force) return cached;
4364
5141
  try {
4365
- const data = await this.client.rest.get(Routes20.channel(channelId));
5142
+ const data = await this.client.rest.get(Routes23.channel(channelId));
4366
5143
  const guildId = "guild_id" in data ? data.guild_id : void 0;
4367
5144
  if (guildId) {
4368
5145
  const guild = this.client.guilds.get(guildId);
@@ -4407,7 +5184,7 @@ var ChannelManager = class extends LimitedCollection {
4407
5184
  defaultAllowedMentions: this.client.options.defaultAllowedMentions
4408
5185
  });
4409
5186
  const data = await this.client.rest.post(
4410
- Routes20.channelMessages(channelId),
5187
+ Routes23.channelMessages(channelId),
4411
5188
  postPayload
4412
5189
  );
4413
5190
  this.client._addMessageToCache(channelId, data);
@@ -4417,7 +5194,7 @@ var ChannelManager = class extends LimitedCollection {
4417
5194
 
4418
5195
  // src/ClientCore/ClientEmoji.ts
4419
5196
  import { Collection as Collection8 } from "@fluxerjs/collection";
4420
- import { Routes as Routes21 } from "@fluxerjs/types";
5197
+ import { Routes as Routes24 } from "@fluxerjs/types";
4421
5198
  import { formatEmoji, getUnicodeFromShortcode, parseEmoji } from "@fluxerjs/util";
4422
5199
  async function resolveClientEmoji(client, emoji, guildId) {
4423
5200
  if (typeof emoji === "object" && emoji.id) {
@@ -4436,7 +5213,7 @@ async function resolveClientEmoji(client, emoji, guildId) {
4436
5213
  const unicodeFromShortcode = getUnicodeFromShortcode(parsed.name);
4437
5214
  if (unicodeFromShortcode) return unicodeFromShortcode;
4438
5215
  if (guildId) {
4439
- const emojis = await client.rest.get(Routes21.guildEmojis(guildId));
5216
+ const emojis = await client.rest.get(Routes24.guildEmojis(guildId));
4440
5217
  const found = emojis.find((e) => e.name && e.name.toLowerCase() === parsed.name.toLowerCase());
4441
5218
  if (found) return formatEmoji({ ...parsed, id: found.id, animated: found.animated });
4442
5219
  throw new FluxerError(
@@ -4453,26 +5230,26 @@ async function resolveClientEmoji(client, emoji, guildId) {
4453
5230
  return parsed.name;
4454
5231
  }
4455
5232
  async function fetchInstance(client) {
4456
- const raw = await client.rest.get(Routes21.instanceDiscovery(), {
5233
+ const raw = await client.rest.get(Routes24.instanceDiscovery(), {
4457
5234
  auth: false,
4458
5235
  unversioned: true
4459
5236
  });
4460
5237
  return parseInstanceDiscovery(raw);
4461
5238
  }
4462
5239
  function fetchGatewayInfo(client) {
4463
- return client.rest.get(Routes21.gatewayBot());
5240
+ return client.rest.get(Routes24.gatewayBot());
4464
5241
  }
4465
5242
  function fetchEmojiMetadata(client, emojiId) {
4466
- return client.rest.get(Routes21.emojiMetadata(emojiId), { auth: true });
5243
+ return client.rest.get(Routes24.emojiMetadata(emojiId), { auth: true });
4467
5244
  }
4468
5245
  function fetchStickerMetadata(client, stickerId) {
4469
- return client.rest.get(Routes21.stickerMetadata(stickerId), { auth: true });
5246
+ return client.rest.get(Routes24.stickerMetadata(stickerId), { auth: true });
4470
5247
  }
4471
5248
  function fetchApplication(client) {
4472
- return client.rest.get(Routes21.applicationsMe(), { auth: true });
5249
+ return client.rest.get(Routes24.applicationsMe(), { auth: true });
4473
5250
  }
4474
5251
  async function fetchOAuthApplications(client) {
4475
- const data = await client.rest.get(Routes21.oauth2ApplicationsMe(), { auth: true });
5252
+ const data = await client.rest.get(Routes24.oauth2ApplicationsMe(), { auth: true });
4476
5253
  if (Array.isArray(data)) return data;
4477
5254
  if (data && typeof data === "object" && "applications" in data && Array.isArray(data.applications)) {
4478
5255
  return data.applications;
@@ -4491,14 +5268,14 @@ function assertChannelIdBatch(name, channelIds) {
4491
5268
  }
4492
5269
  function preloadMessages(client, channelIds) {
4493
5270
  assertChannelIdBatch("preloadMessages", channelIds);
4494
- return client.rest.post(Routes21.preloadMessages(), {
5271
+ return client.rest.post(Routes24.preloadMessages(), {
4495
5272
  body: { channels: channelIds },
4496
5273
  auth: true
4497
5274
  });
4498
5275
  }
4499
5276
  function preloadMessagesAlt(client, channelIds) {
4500
5277
  assertChannelIdBatch("preloadMessagesAlt", channelIds);
4501
- return client.rest.post(Routes21.preloadMessagesAlt(), {
5278
+ return client.rest.post(Routes24.preloadMessagesAlt(), {
4502
5279
  body: { channels: channelIds },
4503
5280
  auth: true
4504
5281
  });
@@ -4506,7 +5283,7 @@ function preloadMessagesAlt(client, channelIds) {
4506
5283
  async function bulkFetchMessages(client, requests, options = {}) {
4507
5284
  validateBulkMessageFetchRequests(requests);
4508
5285
  const wire = toBulkFetchWire(requests);
4509
- const data = await client.rest.post(Routes21.channelsMessagesBulk(), {
5286
+ const data = await client.rest.post(Routes24.channelsMessagesBulk(), {
4510
5287
  body: { requests: wire },
4511
5288
  auth: true
4512
5289
  });
@@ -4523,7 +5300,7 @@ async function bulkFetchMessages(client, requests, options = {}) {
4523
5300
  };
4524
5301
  }
4525
5302
  async function searchMessages(client, options = {}) {
4526
- const data = await client.rest.post(Routes21.searchMessages(), {
5303
+ const data = await client.rest.post(Routes24.searchMessages(), {
4527
5304
  body: toMessageSearchBody(options),
4528
5305
  auth: true
4529
5306
  });
@@ -4553,7 +5330,7 @@ import { SnowflakeUtil as SnowflakeUtil9 } from "@fluxerjs/util";
4553
5330
 
4554
5331
  // src/ClientCore/GuildMemberManager.ts
4555
5332
  import { LimitedCollection as LimitedCollection2 } from "@fluxerjs/collection";
4556
- import { Routes as Routes22 } from "@fluxerjs/types";
5333
+ import { Routes as Routes25 } from "@fluxerjs/types";
4557
5334
  var GuildMemberManager = class extends LimitedCollection2 {
4558
5335
  constructor(guild) {
4559
5336
  super({ maxSize: guild.client.cache.limits.members });
@@ -4610,7 +5387,7 @@ var GuildMemberManager = class extends LimitedCollection2 {
4610
5387
  if (options?.limit != null) params.set("limit", String(options.limit));
4611
5388
  if (options?.after) params.set("after", options.after);
4612
5389
  const qs2 = params.toString();
4613
- const url = Routes22.guildMembers(this.guild.id) + (qs2 ? `?${qs2}` : "");
5390
+ const url = Routes25.guildMembers(this.guild.id) + (qs2 ? `?${qs2}` : "");
4614
5391
  const data = await this.guild.client.rest.get(url, { auth: true });
4615
5392
  const members = [];
4616
5393
  for (const m of data) {
@@ -4633,7 +5410,7 @@ var GuildMemberManager = class extends LimitedCollection2 {
4633
5410
  */
4634
5411
  async search(options = {}) {
4635
5412
  const data = await this.guild.client.rest.post(
4636
- Routes22.guildMembersSearch(this.guild.id),
5413
+ Routes25.guildMembersSearch(this.guild.id),
4637
5414
  { body: toMemberSearchBody(options), auth: true }
4638
5415
  );
4639
5416
  const offset = options.offset ?? 0;
@@ -4659,7 +5436,7 @@ var GuildMemberManager = class extends LimitedCollection2 {
4659
5436
  };
4660
5437
 
4661
5438
  // src/Domain/Guild/Admin.ts
4662
- import { Routes as Routes23 } from "@fluxerjs/types";
5439
+ import { Routes as Routes26 } from "@fluxerjs/types";
4663
5440
  function toAuditLogEntryPayload(entry, guildId) {
4664
5441
  return {
4665
5442
  id: entry.id,
@@ -4680,7 +5457,7 @@ function toVanityPayload(data) {
4680
5457
  return { code: data.code ?? null, uses: data.uses };
4681
5458
  }
4682
5459
  async function fetchAuditLogs(guild, options) {
4683
- const url = Routes23.guildAuditLogs(guild.id) + qs({
5460
+ const url = Routes26.guildAuditLogs(guild.id) + qs({
4684
5461
  limit: options?.limit,
4685
5462
  before: options?.before,
4686
5463
  after: options?.after,
@@ -4704,7 +5481,7 @@ async function fetchAuditLogs(guild, options) {
4704
5481
  };
4705
5482
  }
4706
5483
  async function editGuild(guild, options) {
4707
- const data = await guild.client.rest.patch(Routes23.guild(guild.id), {
5484
+ const data = await guild.client.rest.patch(Routes26.guild(guild.id), {
4708
5485
  body: toGuildEditBody(options),
4709
5486
  auth: true
4710
5487
  });
@@ -4712,13 +5489,13 @@ async function editGuild(guild, options) {
4712
5489
  return guild;
4713
5490
  }
4714
5491
  async function fetchVanityURL(guild) {
4715
- const data = await guild.client.rest.get(Routes23.guildVanityUrl(guild.id), {
5492
+ const data = await guild.client.rest.get(Routes26.guildVanityUrl(guild.id), {
4716
5493
  auth: true
4717
5494
  });
4718
5495
  return toVanityPayload(data);
4719
5496
  }
4720
5497
  async function editVanityURL(guild, code) {
4721
- const data = await guild.client.rest.patch(Routes23.guildVanityUrl(guild.id), {
5498
+ const data = await guild.client.rest.patch(Routes26.guildVanityUrl(guild.id), {
4722
5499
  body: { code },
4723
5500
  auth: true
4724
5501
  });
@@ -4726,14 +5503,14 @@ async function editVanityURL(guild, code) {
4726
5503
  return toVanityPayload(data);
4727
5504
  }
4728
5505
  async function fetchDiscoveryStatus(guild) {
4729
- const data = await guild.client.rest.get(Routes23.guildDiscovery(guild.id), {
5506
+ const data = await guild.client.rest.get(Routes26.guildDiscovery(guild.id), {
4730
5507
  auth: true
4731
5508
  });
4732
5509
  return toDiscoveryStatusPayload(data);
4733
5510
  }
4734
5511
  async function applyForDiscovery(guild, options) {
4735
5512
  const data = await guild.client.rest.post(
4736
- Routes23.guildDiscovery(guild.id),
5513
+ Routes26.guildDiscovery(guild.id),
4737
5514
  {
4738
5515
  body: toDiscoveryBody(options),
4739
5516
  auth: true
@@ -4743,7 +5520,7 @@ async function applyForDiscovery(guild, options) {
4743
5520
  }
4744
5521
  async function editDiscoveryApplication(guild, options) {
4745
5522
  const data = await guild.client.rest.patch(
4746
- Routes23.guildDiscovery(guild.id),
5523
+ Routes26.guildDiscovery(guild.id),
4747
5524
  {
4748
5525
  body: toDiscoveryBody(options),
4749
5526
  auth: true
@@ -4752,34 +5529,34 @@ async function editDiscoveryApplication(guild, options) {
4752
5529
  return toDiscoveryApplicationPayload(data);
4753
5530
  }
4754
5531
  async function withdrawDiscoveryApplication(guild) {
4755
- await guild.client.rest.delete(Routes23.guildDiscovery(guild.id), { auth: true });
5532
+ await guild.client.rest.delete(Routes26.guildDiscovery(guild.id), { auth: true });
4756
5533
  }
4757
5534
  async function deleteGuild(guild, options) {
4758
5535
  const body = options ? toSudoBody(options) : {};
4759
- await guild.client.rest.post(Routes23.guildDelete(guild.id), {
5536
+ await guild.client.rest.post(Routes26.guildDelete(guild.id), {
4760
5537
  body,
4761
5538
  auth: true
4762
5539
  });
4763
5540
  guild.client.guilds.delete(guild.id);
4764
5541
  }
4765
5542
  async function transferOwnership(guild, newOwnerId, password) {
4766
- await guild.client.rest.post(Routes23.guildTransferOwnership(guild.id), {
5543
+ await guild.client.rest.post(Routes26.guildTransferOwnership(guild.id), {
4767
5544
  body: { new_owner_id: newOwnerId, ...password != null && { password } },
4768
5545
  auth: true
4769
5546
  });
4770
5547
  }
4771
5548
 
4772
5549
  // src/Domain/Guild/Channels.ts
4773
- import { Routes as Routes24 } from "@fluxerjs/types";
5550
+ import { Routes as Routes27 } from "@fluxerjs/types";
4774
5551
  async function createChannel(guild, options) {
4775
- const created = await guild.client.rest.post(Routes24.guildChannels(guild.id), {
5552
+ const created = await guild.client.rest.post(Routes27.guildChannels(guild.id), {
4776
5553
  body: toChannelCreateBody(options),
4777
5554
  auth: true
4778
5555
  });
4779
5556
  return cacheChannel(guild, created);
4780
5557
  }
4781
5558
  async function fetchChannels(guild) {
4782
- const data = await guild.client.rest.get(Routes24.guildChannels(guild.id));
5559
+ const data = await guild.client.rest.get(Routes27.guildChannels(guild.id));
4783
5560
  const channels = [];
4784
5561
  for (const ch of data) {
4785
5562
  const channel = cacheChannel(guild, ch);
@@ -4788,17 +5565,17 @@ async function fetchChannels(guild) {
4788
5565
  return channels;
4789
5566
  }
4790
5567
  async function setChannelPositions(guild, updates) {
4791
- await guild.client.rest.patch(Routes24.guildChannels(guild.id), {
5568
+ await guild.client.rest.patch(Routes27.guildChannels(guild.id), {
4792
5569
  body: toChannelPositionBody(updates),
4793
5570
  auth: true
4794
5571
  });
4795
5572
  }
4796
5573
  async function fetchWebhooks(guild) {
4797
- const data = await guild.client.rest.get(Routes24.guildWebhooks(guild.id));
5574
+ const data = await guild.client.rest.get(Routes27.guildWebhooks(guild.id));
4798
5575
  return data.map((w) => new Webhook(guild.client, w));
4799
5576
  }
4800
5577
  async function fetchInvites(guild) {
4801
- const data = await guild.client.rest.get(Routes24.guildInvites(guild.id));
5578
+ const data = await guild.client.rest.get(Routes27.guildInvites(guild.id));
4802
5579
  return data.map((invite) => new Invite(guild.client, invite));
4803
5580
  }
4804
5581
  async function fetchInvite(guild, codeOrUrl) {
@@ -4818,14 +5595,14 @@ function resolveGuildOnlineCount(data) {
4818
5595
  }
4819
5596
 
4820
5597
  // src/Domain/Guild/Emojis.ts
4821
- import { Routes as Routes25 } from "@fluxerjs/types";
5598
+ import { Routes as Routes28 } from "@fluxerjs/types";
4822
5599
  async function fetchEmojis(guild) {
4823
- const data = await guild.client.rest.get(Routes25.guildEmojis(guild.id));
5600
+ const data = await guild.client.rest.get(Routes28.guildEmojis(guild.id));
4824
5601
  return data.map((e) => cacheEmoji(guild, e));
4825
5602
  }
4826
5603
  async function fetchEmoji(guild, emojiId) {
4827
5604
  try {
4828
- const data = await guild.client.rest.get(Routes25.guildEmoji(guild.id, emojiId));
5605
+ const data = await guild.client.rest.get(Routes28.guildEmoji(guild.id, emojiId));
4829
5606
  return cacheEmoji(guild, data);
4830
5607
  } catch (err) {
4831
5608
  rethrowMapped(err, {
@@ -4836,7 +5613,7 @@ async function fetchEmoji(guild, emojiId) {
4836
5613
  }
4837
5614
  async function createEmoji(guild, options) {
4838
5615
  const { reason, ...body } = options;
4839
- const data = await guild.client.rest.post(Routes25.guildEmojis(guild.id), {
5616
+ const data = await guild.client.rest.post(Routes28.guildEmojis(guild.id), {
4840
5617
  body,
4841
5618
  auth: true,
4842
5619
  ...auditReasonHeaders(reason)
@@ -4844,7 +5621,7 @@ async function createEmoji(guild, options) {
4844
5621
  return cacheEmoji(guild, data);
4845
5622
  }
4846
5623
  async function cloneEmoji(guild, sourceEmojiId) {
4847
- const data = await guild.client.rest.post(Routes25.guildEmojisClone(guild.id), {
5624
+ const data = await guild.client.rest.post(Routes28.guildEmojisClone(guild.id), {
4848
5625
  body: { source_emoji_id: sourceEmojiId },
4849
5626
  auth: true
4850
5627
  });
@@ -4852,7 +5629,7 @@ async function cloneEmoji(guild, sourceEmojiId) {
4852
5629
  }
4853
5630
  async function createEmojisBulk(guild, emojis) {
4854
5631
  const data = await guild.client.rest.post(
4855
- Routes25.guildEmojisBulk(guild.id),
5632
+ Routes28.guildEmojisBulk(guild.id),
4856
5633
  { body: { emojis }, auth: true }
4857
5634
  );
4858
5635
  return { success: data.success.map((e) => cacheEmoji(guild, e)), failed: data.failed };
@@ -4872,11 +5649,11 @@ var GuildRoleManager = class extends LimitedCollection3 {
4872
5649
  };
4873
5650
 
4874
5651
  // src/Domain/Guild/MemberHttp.ts
4875
- import { Routes as Routes26 } from "@fluxerjs/types";
5652
+ import { Routes as Routes29 } from "@fluxerjs/types";
4876
5653
  async function fetchMember(guild, userId) {
4877
5654
  try {
4878
5655
  const data = await guild.client.rest.get(
4879
- Routes26.guildMember(guild.id, userId)
5656
+ Routes29.guildMember(guild.id, userId)
4880
5657
  );
4881
5658
  return cacheMember(guild, data);
4882
5659
  } catch (err) {
@@ -4891,17 +5668,17 @@ async function fetchMember(guild, userId) {
4891
5668
  }
4892
5669
  async function fetchMe(guild) {
4893
5670
  const data = await guild.client.rest.get(
4894
- Routes26.guildMemberMe(guild.id),
5671
+ Routes29.guildMemberMe(guild.id),
4895
5672
  { auth: true }
4896
5673
  );
4897
5674
  return cacheMember(guild, data);
4898
5675
  }
4899
5676
 
4900
5677
  // src/Domain/Guild/Moderation.ts
4901
- import { Routes as Routes28 } from "@fluxerjs/types";
5678
+ import { Routes as Routes31 } from "@fluxerjs/types";
4902
5679
 
4903
5680
  // src/Domain/Guild/GuildBan.ts
4904
- import { Routes as Routes27 } from "@fluxerjs/types";
5681
+ import { Routes as Routes30 } from "@fluxerjs/types";
4905
5682
  function parseOptionalDate2(value) {
4906
5683
  if (value == null || value === "") return null;
4907
5684
  const date = new Date(value);
@@ -4928,7 +5705,7 @@ var GuildBan = class extends Base {
4928
5705
  * Requires Ban Members permission.
4929
5706
  */
4930
5707
  async unban(reason) {
4931
- await this.client.rest.delete(Routes27.guildBan(this.guildId, this.user.id), {
5708
+ await this.client.rest.delete(Routes30.guildBan(this.guildId, this.user.id), {
4932
5709
  auth: true,
4933
5710
  ...auditReasonHeaders(reason)
4934
5711
  });
@@ -4938,35 +5715,35 @@ var GuildBan = class extends Base {
4938
5715
  // src/Domain/Guild/Moderation.ts
4939
5716
  async function ban(guild, userId, options) {
4940
5717
  const body = options ? toGuildBanBody(options) : {};
4941
- await guild.client.rest.put(Routes28.guildBan(guild.id, userId), {
5718
+ await guild.client.rest.put(Routes31.guildBan(guild.id, userId), {
4942
5719
  body: Object.keys(body).length ? body : void 0,
4943
5720
  auth: true,
4944
5721
  ...auditReasonHeaders(options?.reason)
4945
5722
  });
4946
5723
  }
4947
5724
  async function fetchBans(guild) {
4948
- const data = await guild.client.rest.get(Routes28.guildBans(guild.id));
5725
+ const data = await guild.client.rest.get(Routes31.guildBans(guild.id));
4949
5726
  return data.map((b) => new GuildBan(guild.client, { ...b, guild_id: guild.id }, guild.id));
4950
5727
  }
4951
5728
  async function unban(guild, userId, reason) {
4952
- await guild.client.rest.delete(Routes28.guildBan(guild.id, userId), {
5729
+ await guild.client.rest.delete(Routes31.guildBan(guild.id, userId), {
4953
5730
  auth: true,
4954
5731
  ...auditReasonHeaders(reason)
4955
5732
  });
4956
5733
  }
4957
5734
  async function kick(guild, userId, reason) {
4958
- await guild.client.rest.delete(Routes28.guildMember(guild.id, userId), {
5735
+ await guild.client.rest.delete(Routes31.guildMember(guild.id, userId), {
4959
5736
  auth: true,
4960
5737
  ...auditReasonHeaders(reason)
4961
5738
  });
4962
5739
  }
4963
5740
 
4964
5741
  // src/Domain/Guild/Roles.ts
4965
- import { Routes as Routes29 } from "@fluxerjs/types";
5742
+ import { Routes as Routes32 } from "@fluxerjs/types";
4966
5743
  import { parseRoleMention } from "@fluxerjs/util";
4967
5744
  async function createRole(guild, options = {}) {
4968
5745
  const body = toRoleCreateBody(options);
4969
- const data = await guild.client.rest.post(Routes29.guildRoles(guild.id), {
5746
+ const data = await guild.client.rest.post(Routes32.guildRoles(guild.id), {
4970
5747
  body: Object.keys(body).length ? body : void 0,
4971
5748
  auth: true,
4972
5749
  ...auditReasonHeaders(options.reason)
@@ -4974,12 +5751,12 @@ async function createRole(guild, options = {}) {
4974
5751
  return cacheRole(guild, data);
4975
5752
  }
4976
5753
  async function fetchRoles(guild) {
4977
- const data = await guild.client.rest.get(Routes29.guildRoles(guild.id));
5754
+ const data = await guild.client.rest.get(Routes32.guildRoles(guild.id));
4978
5755
  return data.map((r) => cacheRole(guild, r));
4979
5756
  }
4980
5757
  async function fetchRole(guild, roleId2) {
4981
5758
  try {
4982
- const data = await guild.client.rest.get(Routes29.guildRole(guild.id, roleId2));
5759
+ const data = await guild.client.rest.get(Routes32.guildRole(guild.id, roleId2));
4983
5760
  return cacheRole(guild, data);
4984
5761
  } catch (err) {
4985
5762
  rethrowMapped(err, {
@@ -4996,7 +5773,7 @@ async function resolveRoleId(guild, arg) {
4996
5773
  const needle = trimmed.toLowerCase();
4997
5774
  const cached = guild.roles.find((r) => r.name?.toLowerCase() === needle);
4998
5775
  if (cached) return cached.id;
4999
- const roles = await guild.client.rest.get(Routes29.guildRoles(guild.id));
5776
+ const roles = await guild.client.rest.get(Routes32.guildRoles(guild.id));
5000
5777
  const role = roles.find((r) => r.name?.toLowerCase() === needle);
5001
5778
  if (!role) return null;
5002
5779
  cacheRole(guild, role);
@@ -5005,7 +5782,7 @@ async function resolveRoleId(guild, arg) {
5005
5782
  async function setRolePositions(guild, updates) {
5006
5783
  return replaceRoles(
5007
5784
  guild,
5008
- await guild.client.rest.patch(Routes29.guildRoles(guild.id), {
5785
+ await guild.client.rest.patch(Routes32.guildRoles(guild.id), {
5009
5786
  body: updates,
5010
5787
  auth: true
5011
5788
  })
@@ -5014,7 +5791,7 @@ async function setRolePositions(guild, updates) {
5014
5791
  async function setRoleHoistPositions(guild, updates) {
5015
5792
  return replaceRoles(
5016
5793
  guild,
5017
- await guild.client.rest.patch(Routes29.guildRolesHoistPositions(guild.id), {
5794
+ await guild.client.rest.patch(Routes32.guildRolesHoistPositions(guild.id), {
5018
5795
  body: updates.map((u) => ({
5019
5796
  id: u.id,
5020
5797
  ...u.hoistPosition !== void 0 ? { hoist_position: u.hoistPosition } : {}
@@ -5026,17 +5803,17 @@ async function setRoleHoistPositions(guild, updates) {
5026
5803
  async function resetRoleHoistPositions(guild) {
5027
5804
  return replaceRoles(
5028
5805
  guild,
5029
- await guild.client.rest.delete(Routes29.guildRolesHoistPositions(guild.id), {
5806
+ await guild.client.rest.delete(Routes32.guildRolesHoistPositions(guild.id), {
5030
5807
  auth: true
5031
5808
  })
5032
5809
  );
5033
5810
  }
5034
5811
 
5035
5812
  // src/Domain/Guild/Stickers.ts
5036
- import { Routes as Routes30 } from "@fluxerjs/types";
5813
+ import { Routes as Routes33 } from "@fluxerjs/types";
5037
5814
  async function createSticker(guild, options) {
5038
5815
  const { reason, ...body } = options;
5039
- const data = await guild.client.rest.post(Routes30.guildStickers(guild.id), {
5816
+ const data = await guild.client.rest.post(Routes33.guildStickers(guild.id), {
5040
5817
  body,
5041
5818
  auth: true,
5042
5819
  ...auditReasonHeaders(reason)
@@ -5044,7 +5821,7 @@ async function createSticker(guild, options) {
5044
5821
  return cacheSticker(guild, data);
5045
5822
  }
5046
5823
  async function cloneSticker(guild, sourceStickerId) {
5047
- const data = await guild.client.rest.post(Routes30.guildStickersClone(guild.id), {
5824
+ const data = await guild.client.rest.post(Routes33.guildStickersClone(guild.id), {
5048
5825
  body: { source_sticker_id: sourceStickerId },
5049
5826
  auth: true
5050
5827
  });
@@ -5052,17 +5829,17 @@ async function cloneSticker(guild, sourceStickerId) {
5052
5829
  }
5053
5830
  async function createStickersBulk(guild, stickers) {
5054
5831
  const data = await guild.client.rest.post(
5055
- Routes30.guildStickersBulk(guild.id),
5832
+ Routes33.guildStickersBulk(guild.id),
5056
5833
  { body: { stickers }, auth: true }
5057
5834
  );
5058
5835
  return { success: data.success.map((s) => cacheSticker(guild, s)), failed: data.failed };
5059
5836
  }
5060
5837
  async function fetchStickers(guild) {
5061
- const data = await guild.client.rest.get(Routes30.guildStickers(guild.id));
5838
+ const data = await guild.client.rest.get(Routes33.guildStickers(guild.id));
5062
5839
  return data.map((s) => cacheSticker(guild, s));
5063
5840
  }
5064
5841
  async function fetchSticker(guild, stickerId) {
5065
- const data = await guild.client.rest.get(Routes30.guildSticker(guild.id, stickerId));
5842
+ const data = await guild.client.rest.get(Routes33.guildSticker(guild.id, stickerId));
5066
5843
  return cacheSticker(guild, data);
5067
5844
  }
5068
5845
 
@@ -5294,7 +6071,7 @@ var Guild = class extends Base {
5294
6071
  });
5295
6072
  }
5296
6073
  /**
5297
- * Create a channel. `type`: 0=text, 2=voice, 4=category, 998=link (set `url`).
6074
+ * Create a channel. `type`: 0=text, 2=voice, 4=category, 5=announcement, 15=forum, 16=media, 998=link (set `url`).
5298
6075
  * Requires Manage Channels.
5299
6076
  */
5300
6077
  createChannel(options) {
@@ -5304,6 +6081,10 @@ var Guild = class extends Base {
5304
6081
  fetchChannels() {
5305
6082
  return fetchChannels(this);
5306
6083
  }
6084
+ /** Fetch active threads in this guild. */
6085
+ fetchActiveThreads() {
6086
+ return fetchActiveThreads(this.client, this.id);
6087
+ }
5307
6088
  /** Update channel positions (reordering). */
5308
6089
  setChannelPositions(updates) {
5309
6090
  return setChannelPositions(this, updates);
@@ -5534,6 +6315,13 @@ function upsertGuildFromSnapshot(client, guildData, resources = {}) {
5534
6315
  client.guilds.set(guild.id, guild);
5535
6316
  if (resources.roles !== void 0) syncRoles(guild, resources.roles);
5536
6317
  if (resources.channels !== void 0) syncChannels(guild, resources.channels);
6318
+ if (resources.threads !== void 0) {
6319
+ syncThreads(
6320
+ guild,
6321
+ resources.threads,
6322
+ new Set((resources.channels ?? []).map((channel) => channel.id))
6323
+ );
6324
+ }
5537
6325
  if (resources.members !== void 0) mergeMembers(guild, resources.members);
5538
6326
  if (resources.emojis !== void 0) syncEmojis(guild, resources.emojis);
5539
6327
  if (resources.stickers !== void 0) syncStickers(guild, resources.stickers);
@@ -5548,7 +6336,9 @@ function applyGuildSnapshotFromGateway(client, raw) {
5548
6336
  channels: g.channels,
5549
6337
  members: g.members,
5550
6338
  emojis: g.emojis,
5551
- stickers: g.stickers
6339
+ stickers: g.stickers,
6340
+ // A channel list without `threads` means this session has no viewable threads.
6341
+ threads: g.channels !== void 0 ? g.threads ?? [] : g.threads
5552
6342
  });
5553
6343
  if (g.voice_states?.length) {
5554
6344
  client.emit(Events.VoiceStatesSync, {
@@ -5560,7 +6350,7 @@ function applyGuildSnapshotFromGateway(client, raw) {
5560
6350
  }
5561
6351
 
5562
6352
  // src/ClientCore/ClientUser.ts
5563
- import { GatewayOpcodes, Routes as Routes31 } from "@fluxerjs/types";
6353
+ import { GatewayOpcodes, Routes as Routes34 } from "@fluxerjs/types";
5564
6354
  var ClientUser = class extends User {
5565
6355
  /** Broadcast presence (gateway opcode 3) on all shards. */
5566
6356
  setPresence(presence) {
@@ -5570,13 +6360,13 @@ var ClientUser = class extends User {
5570
6360
  }
5571
6361
  /** GET /users/@me — refresh the logged-in user from REST and patch this instance. */
5572
6362
  async fetch() {
5573
- const data = await this.client.rest.get(Routes31.currentUser(), { auth: true });
6363
+ const data = await this.client.rest.get(Routes34.currentUser(), { auth: true });
5574
6364
  this._patch(data);
5575
6365
  return this;
5576
6366
  }
5577
6367
  /** GET /users/@me/guilds — returns camelCase partial guilds. */
5578
6368
  async fetchGuilds(options) {
5579
- const path = Routes31.currentUserGuilds() + (options?.withCounts ? "?with_counts=true" : "");
6369
+ const path = Routes34.currentUserGuilds() + (options?.withCounts ? "?with_counts=true" : "");
5580
6370
  const data = await this.client.rest.get(path, { auth: true });
5581
6371
  return data.map((g) => ({
5582
6372
  id: g.id,
@@ -5600,7 +6390,7 @@ var ClientUser = class extends User {
5600
6390
  */
5601
6391
  async leaveGuild(guildId, options) {
5602
6392
  const body = options ? toSudoBody(options) : void 0;
5603
- await this.client.rest.delete(Routes31.leaveGuild(guildId), {
6393
+ await this.client.rest.delete(Routes34.leaveGuild(guildId), {
5604
6394
  body: body && Object.keys(body).length ? body : void 0,
5605
6395
  auth: true
5606
6396
  });
@@ -5608,7 +6398,7 @@ var ClientUser = class extends User {
5608
6398
  /** Delete every message authored by the caller across a guild (sudo). */
5609
6399
  async bulkDeleteMyMessagesInGuild(guildId, options) {
5610
6400
  const body = options ? toSudoBody(options) : void 0;
5611
- await this.client.rest.post(Routes31.guildBulkDeleteMine(guildId), {
6401
+ await this.client.rest.post(Routes34.guildBulkDeleteMine(guildId), {
5612
6402
  body: body && Object.keys(body).length ? body : void 0,
5613
6403
  auth: true
5614
6404
  });
@@ -5643,6 +6433,7 @@ var channelHandlers = {
5643
6433
  if (!ch) return;
5644
6434
  indexChannel(client, ch);
5645
6435
  client.emit(Events.ChannelCreate, ch);
6436
+ if (ch.isThread()) client.emit(Events.ThreadCreate, ch);
5646
6437
  },
5647
6438
  CHANNEL_UPDATE(client, d) {
5648
6439
  const data = d;
@@ -5655,12 +6446,14 @@ var channelHandlers = {
5655
6446
  existing._patch(data);
5656
6447
  indexChannel(client, existing);
5657
6448
  client.emit(Events.ChannelUpdate, oldCh, existing);
6449
+ if (existing.isThread()) client.emit(Events.ThreadUpdate, oldCh, existing);
5658
6450
  return;
5659
6451
  }
5660
6452
  const newCh = Channel.from(client, data);
5661
6453
  if (!newCh) return;
5662
6454
  indexChannel(client, newCh);
5663
6455
  client.emit(Events.ChannelUpdate, existing ?? newCh, newCh);
6456
+ if (newCh.isThread()) client.emit(Events.ThreadUpdate, existing ?? newCh, newCh);
5664
6457
  },
5665
6458
  CHANNEL_UPDATE_BULK(client, d) {
5666
6459
  const data = d;
@@ -5682,7 +6475,11 @@ var channelHandlers = {
5682
6475
  }
5683
6476
  if (!channel) return;
5684
6477
  client.channels.delete(id);
6478
+ if (channel.isGuild() && channel.guildId) {
6479
+ client.guilds.get(channel.guildId)?.channels.delete(id);
6480
+ }
5685
6481
  client.emit(Events.ChannelDelete, channel);
6482
+ if (channel.isThread()) client.emit(Events.ThreadDelete, channel);
5686
6483
  },
5687
6484
  CHANNEL_PINS_UPDATE(client, d) {
5688
6485
  const data = d;
@@ -5872,6 +6669,10 @@ var guildHandlers = {
5872
6669
  }
5873
6670
  client._onGuildReceived(guild.id);
5874
6671
  },
6672
+ /** Same snapshot as Guild Create, including `threads`. Cache only: this is not a join. */
6673
+ GUILD_SYNC(client, d) {
6674
+ applyGuildSnapshotFromGateway(client, d);
6675
+ },
5875
6676
  GUILD_UPDATE(client, d) {
5876
6677
  const guildData = normalizeGuildUpdatePayload(d);
5877
6678
  if (!guildData) return;
@@ -5921,7 +6722,7 @@ var guildHandlers = {
5921
6722
 
5922
6723
  // src/ClientCore/EventHandlers/Invites.ts
5923
6724
  import {
5924
- ChannelType as ChannelType4,
6725
+ ChannelType as ChannelType10,
5925
6726
  InviteType as InviteType2
5926
6727
  } from "@fluxerjs/types";
5927
6728
  function normalizeInviteCreate(client, payload) {
@@ -5946,11 +6747,11 @@ function normalizeInviteCreate(client, payload) {
5946
6747
  const guildId = str(guildObj?.id) ?? str(raw.guild_id) ?? "0";
5947
6748
  const channelId = str(channelObj?.id) ?? str(raw.channel_id) ?? "0";
5948
6749
  const cachedGuild = guildId !== "0" ? client.guilds.get(guildId) : null;
5949
- const cachedChannel = channelId !== "0" ? client.channels.get(channelId) : null;
6750
+ const cachedChannel2 = channelId !== "0" ? client.channels.get(channelId) : null;
5950
6751
  const channel = {
5951
6752
  id: channelId,
5952
- type: num(channelObj?.type) ?? cachedChannel?.type ?? ChannelType4.GuildText,
5953
- name: str(channelObj?.name) ?? cachedChannel?.name ?? null,
6753
+ type: num(channelObj?.type) ?? cachedChannel2?.type ?? ChannelType10.GuildText,
6754
+ name: str(channelObj?.name) ?? cachedChannel2?.name ?? null,
5954
6755
  icon: channelObj?.icon ?? null
5955
6756
  };
5956
6757
  if (type === InviteType2.GroupDM) return { ...shared, type, channel };
@@ -6354,6 +7155,107 @@ var passthroughHandlers = {
6354
7155
  WEBAUTHN_CREDENTIALS_UPDATE: pass(Events.WebAuthnCredentialsUpdate)
6355
7156
  };
6356
7157
 
7158
+ // src/ClientCore/EventHandlers/Threads.ts
7159
+ function cachedChannel(client, id) {
7160
+ const direct = client.channels.get(id);
7161
+ if (direct) return direct;
7162
+ for (const guild of client.guilds.values()) {
7163
+ const nested = guild.channels.get(id);
7164
+ if (nested) return nested;
7165
+ }
7166
+ return null;
7167
+ }
7168
+ var threadHandlers = {
7169
+ THREAD_CREATE(client, d) {
7170
+ channelHandlers.CHANNEL_CREATE(client, d);
7171
+ },
7172
+ THREAD_UPDATE(client, d) {
7173
+ channelHandlers.CHANNEL_UPDATE(client, d);
7174
+ },
7175
+ THREAD_DELETE(client, d) {
7176
+ const data = d;
7177
+ const existing = data.id ? cachedChannel(client, data.id) : null;
7178
+ if (existing?.isThread()) {
7179
+ channelHandlers.CHANNEL_DELETE(client, data);
7180
+ return;
7181
+ }
7182
+ if (!data.id || !isThreadType(data.type)) return;
7183
+ const thread = Channel.from(client, {
7184
+ id: data.id,
7185
+ type: data.type,
7186
+ guild_id: data.guild_id,
7187
+ parent_id: data.parent_id
7188
+ });
7189
+ if (!thread.isThread()) return;
7190
+ client.emit(Events.ChannelDelete, thread);
7191
+ client.emit(Events.ThreadDelete, thread);
7192
+ },
7193
+ THREAD_LIST_SYNC(client, d) {
7194
+ const data = d;
7195
+ const { threads } = fetchedThreadsFrom(client, {
7196
+ threads: data.threads ?? [],
7197
+ members: data.members ?? []
7198
+ });
7199
+ const payload = {
7200
+ guildId: data.guild_id,
7201
+ channelIds: data.channel_ids ?? [],
7202
+ threads
7203
+ };
7204
+ client.emit(Events.ThreadListSync, payload);
7205
+ },
7206
+ THREAD_MEMBER_UPDATE(client, d) {
7207
+ const data = d;
7208
+ const member = new ThreadMember(data);
7209
+ const thread = member.id ? client.channels.get(member.id) : void 0;
7210
+ if (thread?.isThread() && member.userId && member.userId === client.user?.id) {
7211
+ thread.member = member;
7212
+ }
7213
+ client.emit(Events.ThreadMemberUpdate, member);
7214
+ },
7215
+ THREAD_MEMBERS_UPDATE(client, d) {
7216
+ const data = d;
7217
+ const thread = client.channels.get(data.id);
7218
+ if (thread?.isThread()) thread.memberCount = data.member_count;
7219
+ const payload = {
7220
+ id: data.id,
7221
+ guildId: data.guild_id,
7222
+ memberCount: data.member_count,
7223
+ addedMembers: (data.added_members ?? []).map((member) => new ThreadMember(member)),
7224
+ removedMemberIds: data.removed_member_ids ?? []
7225
+ };
7226
+ client.emit(Events.ThreadMembersUpdate, payload);
7227
+ },
7228
+ THREAD_MEMBER_LIST_UPDATE(client, d) {
7229
+ const data = d;
7230
+ const guild = data.guild_id ? client.guilds.get(data.guild_id) : void 0;
7231
+ const payload = {
7232
+ guildId: data.guild_id,
7233
+ threadId: data.thread_id,
7234
+ members: (data.members ?? []).map((entry) => ({
7235
+ userId: entry.user_id,
7236
+ joinTimestamp: entry.join_timestamp,
7237
+ flags: entry.flags,
7238
+ member: guild && entry.member?.user?.id ? cacheMember(guild, entry.member) : null,
7239
+ presence: entry.presence ? { status: entry.presence.status ?? null } : null
7240
+ }))
7241
+ };
7242
+ client.emit(Events.ThreadMemberListUpdate, payload);
7243
+ },
7244
+ FORUM_UNREADS(client, d) {
7245
+ const data = d;
7246
+ const payload = {
7247
+ guildId: data.guild_id,
7248
+ channelId: data.channel_id,
7249
+ threads: (data.threads ?? []).map((entry) => ({
7250
+ threadId: entry.thread_id,
7251
+ count: entry.count ?? null,
7252
+ missing: entry.missing === true
7253
+ }))
7254
+ };
7255
+ client.emit(Events.ForumUnreads, payload);
7256
+ }
7257
+ };
7258
+
6357
7259
  // src/ClientCore/EventHandlers/index.ts
6358
7260
  var eventHandlers = buildRegistry(
6359
7261
  messageHandlers,
@@ -6362,7 +7264,8 @@ var eventHandlers = buildRegistry(
6362
7264
  memberHandlers,
6363
7265
  inviteHandlers,
6364
7266
  guildResourceHandlers,
6365
- passthroughHandlers
7267
+ passthroughHandlers,
7268
+ threadHandlers
6366
7269
  );
6367
7270
 
6368
7271
  // src/ClientCore/GatewayDispatch.ts
@@ -6588,7 +7491,7 @@ async function connectClientGateway(client, token, signal) {
6588
7491
 
6589
7492
  // src/ClientCore/GuildManager.ts
6590
7493
  import { LimitedCollection as LimitedCollection5 } from "@fluxerjs/collection";
6591
- import { Routes as Routes32 } from "@fluxerjs/types";
7494
+ import { Routes as Routes35 } from "@fluxerjs/types";
6592
7495
  var GuildManager = class extends LimitedCollection5 {
6593
7496
  constructor(client) {
6594
7497
  super({
@@ -6627,7 +7530,7 @@ var GuildManager = class extends LimitedCollection5 {
6627
7530
  const cached = this.get(guildId);
6628
7531
  if (cached && !options?.force) return cached;
6629
7532
  try {
6630
- const data = await this.client.rest.get(Routes32.guild(guildId));
7533
+ const data = await this.client.rest.get(Routes35.guild(guildId));
6631
7534
  if (cached) {
6632
7535
  cached._patch(data);
6633
7536
  return cached;
@@ -6715,7 +7618,7 @@ var MessageCache = class {
6715
7618
  // src/ClientCore/UserManager.ts
6716
7619
  import { LimitedCollection as LimitedCollection6 } from "@fluxerjs/collection";
6717
7620
  import {
6718
- Routes as Routes33
7621
+ Routes as Routes36
6719
7622
  } from "@fluxerjs/types";
6720
7623
  var soft = (p) => p.catch(() => null);
6721
7624
  var UserManager = class extends LimitedCollection6 {
@@ -6740,7 +7643,7 @@ var UserManager = class extends LimitedCollection6 {
6740
7643
  async fetch(userId, options) {
6741
7644
  const cached = this.get(userId);
6742
7645
  if (cached && !options?.force) return cached;
6743
- const data = await this.client.rest.get(Routes33.user(userId));
7646
+ const data = await this.client.rest.get(Routes36.user(userId));
6744
7647
  return this.client.getOrCreateUser(data);
6745
7648
  }
6746
7649
  /** Return a cached user, otherwise {@link fetch}. */
@@ -6758,10 +7661,10 @@ var UserManager = class extends LimitedCollection6 {
6758
7661
  async fetchWithProfile(userId, options) {
6759
7662
  const guildId = options?.guildId ?? void 0;
6760
7663
  const [userData, globalProfileRaw, serverProfileRaw, memberData] = await Promise.all([
6761
- this.client.rest.get(Routes33.user(userId)),
6762
- soft(this.client.rest.get(Routes33.userProfile(userId))),
6763
- guildId ? soft(this.client.rest.get(Routes33.userProfile(userId, guildId))) : null,
6764
- guildId ? soft(this.client.rest.get(Routes33.guildMember(guildId, userId))) : null
7664
+ this.client.rest.get(Routes36.user(userId)),
7665
+ soft(this.client.rest.get(Routes36.userProfile(userId))),
7666
+ guildId ? soft(this.client.rest.get(Routes36.userProfile(userId, guildId))) : null,
7667
+ guildId ? soft(this.client.rest.get(Routes36.guildMember(guildId, userId))) : null
6765
7668
  ]);
6766
7669
  const user = this.client.getOrCreateUser(userData);
6767
7670
  let member = null;
@@ -7140,6 +8043,72 @@ var Client = class _Client extends EventEmitter3 {
7140
8043
  if (options.nonce !== void 0) data.nonce = options.nonce;
7141
8044
  this._sendToAllShards({ op: GatewayOpcodes2.RequestChannelMemberCounts, d: data });
7142
8045
  }
8046
+ /**
8047
+ * Request unread counts for posts in one forum or media channel (opcode 28).
8048
+ * Listen for `forumUnreads`. The gateway keeps at most 40 posts and ignores a channel the session cannot view.
8049
+ */
8050
+ requestForumUnreads(options) {
8051
+ if (!options.guildId || !options.channelId) {
8052
+ throw new FluxerError("requestForumUnreads requires guildId and channelId", {
8053
+ code: ErrorCodes.InvalidGatewayRequest
8054
+ });
8055
+ }
8056
+ const threads = [];
8057
+ const seen = /* @__PURE__ */ new Set();
8058
+ for (const thread of options.threads) {
8059
+ if (!thread.threadId || seen.has(thread.threadId)) continue;
8060
+ seen.add(thread.threadId);
8061
+ const entry = { thread_id: thread.threadId };
8062
+ if (thread.ackMessageId !== void 0) entry.ack_message_id = thread.ackMessageId;
8063
+ threads.push(entry);
8064
+ }
8065
+ if (!threads.length) {
8066
+ throw new FluxerError("requestForumUnreads requires at least one thread", {
8067
+ code: ErrorCodes.InvalidGatewayRequest
8068
+ });
8069
+ }
8070
+ if (threads.length > 40) {
8071
+ throw new FluxerError("requestForumUnreads accepts at most 40 threads", {
8072
+ code: ErrorCodes.InvalidGatewayRequest
8073
+ });
8074
+ }
8075
+ const data = {
8076
+ guild_id: options.guildId,
8077
+ channel_id: options.channelId,
8078
+ threads
8079
+ };
8080
+ this._sendToAllShards({ op: GatewayOpcodes2.RequestForumUnreads, d: data });
8081
+ }
8082
+ /**
8083
+ * Subscribe to thread traffic in a guild (opcode 14).
8084
+ * `threads: true` receives every thread event in the guild.
8085
+ * `threadIds` (at most 10) subscribes to those member lists. Each one arrives as `threadMemberListUpdate`.
8086
+ */
8087
+ subscribeThreads(options) {
8088
+ if (!options.guildId) {
8089
+ throw new FluxerError("subscribeThreads requires guildId", {
8090
+ code: ErrorCodes.InvalidGatewayRequest
8091
+ });
8092
+ }
8093
+ if (options.threads === void 0 && options.threadIds === void 0) {
8094
+ throw new FluxerError("subscribeThreads requires threads or threadIds", {
8095
+ code: ErrorCodes.InvalidGatewayRequest
8096
+ });
8097
+ }
8098
+ const subscription = {};
8099
+ if (options.threads !== void 0) subscription.threads = options.threads;
8100
+ if (options.threadIds !== void 0) {
8101
+ const threadIds = [...new Set(options.threadIds.filter(Boolean))];
8102
+ if (threadIds.length > 10) {
8103
+ throw new FluxerError("subscribeThreads accepts at most 10 threadIds", {
8104
+ code: ErrorCodes.InvalidGatewayRequest
8105
+ });
8106
+ }
8107
+ subscription.thread_member_lists = threadIds;
8108
+ }
8109
+ const data = { subscriptions: { [options.guildId]: subscription } };
8110
+ this._sendToAllShards({ op: GatewayOpcodes2.LazyRequest, d: data });
8111
+ }
7143
8112
  /**
7144
8113
  * Broadcast a gateway payload to all shards.
7145
8114
  * @param payload - Gateway send payload
@@ -7243,7 +8212,7 @@ var Client = class _Client extends EventEmitter3 {
7243
8212
  * @see {@link Routes}
7244
8213
  */
7245
8214
  static get Routes() {
7246
- return Routes34;
8215
+ return Routes37;
7247
8216
  }
7248
8217
  };
7249
8218