@fluxerjs/core 1.2.4 → 1.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,8 @@
1
+ export { M as Message, v as MessageEditOptions, y as MessageSendOptions, P as PartialMessage, J as ReplyOptions } from './subpath-message-CZC4oGko.mjs';
2
+ import 'events';
3
+ import '@fluxerjs/rest';
4
+ import '@fluxerjs/ws';
5
+ import '@fluxerjs/types';
6
+ import '@fluxerjs/collection';
7
+ import '@fluxerjs/builders';
8
+ import '@fluxerjs/util';
@@ -0,0 +1,8 @@
1
+ export { M as Message, v as MessageEditOptions, y as MessageSendOptions, P as PartialMessage, J as ReplyOptions } from './subpath-message-CZC4oGko.js';
2
+ import 'events';
3
+ import '@fluxerjs/rest';
4
+ import '@fluxerjs/ws';
5
+ import '@fluxerjs/types';
6
+ import '@fluxerjs/collection';
7
+ import '@fluxerjs/builders';
8
+ import '@fluxerjs/util';
@@ -0,0 +1,511 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/subpath-message.ts
21
+ var subpath_message_exports = {};
22
+ __export(subpath_message_exports, {
23
+ Message: () => Message
24
+ });
25
+ module.exports = __toCommonJS(subpath_message_exports);
26
+
27
+ // src/structures/Base.ts
28
+ var Base = class {
29
+ };
30
+
31
+ // src/structures/Message.ts
32
+ var import_collection2 = require("@fluxerjs/collection");
33
+ var import_types = require("@fluxerjs/types");
34
+ var import_builders2 = require("@fluxerjs/builders");
35
+
36
+ // src/util/messageUtils.ts
37
+ var import_builders = require("@fluxerjs/builders");
38
+
39
+ // src/errors/ErrorCodes.ts
40
+ var import_util = require("@fluxerjs/util");
41
+
42
+ // src/errors/FluxerError.ts
43
+ var import_util2 = require("@fluxerjs/util");
44
+
45
+ // src/util/messageUtils.ts
46
+ var FILE_FETCH_TIMEOUT_MS = 3e4;
47
+ async function resolveMessageFiles(files) {
48
+ const result = [];
49
+ for (let i = 0; i < files.length; i++) {
50
+ const f = files[i];
51
+ const filename = f.filename ?? f.name;
52
+ if ("url" in f && f.url) {
53
+ if (!URL.canParse(f.url)) {
54
+ throw new import_util2.FluxerError(`Invalid file URL at index ${i}: ${f.url}`, {
55
+ code: import_util.ErrorCodes.InvalidFileUrl
56
+ });
57
+ }
58
+ let res;
59
+ try {
60
+ res = await fetch(f.url, {
61
+ signal: AbortSignal.timeout(FILE_FETCH_TIMEOUT_MS)
62
+ });
63
+ } catch (err) {
64
+ throw new import_util2.FluxerError(`Failed to fetch file from ${f.url}`, {
65
+ code: import_util.ErrorCodes.FileFetchFailed,
66
+ cause: err instanceof Error ? err : void 0
67
+ });
68
+ }
69
+ if (!res.ok) {
70
+ throw new import_util2.FluxerError(
71
+ `Failed to fetch file from ${f.url}: ${res.status} ${res.statusText}`,
72
+ {
73
+ code: import_util.ErrorCodes.FileFetchFailed
74
+ }
75
+ );
76
+ }
77
+ const data = await res.arrayBuffer();
78
+ result.push({ name: f.name, data, filename });
79
+ } else if ("data" in f && f.data != null) {
80
+ result.push({ name: f.name, data: f.data, filename });
81
+ } else {
82
+ throw new import_util2.FluxerError(`File at index ${i} must have either "data" or "url"`, {
83
+ code: import_util.ErrorCodes.InvalidAttachment
84
+ });
85
+ }
86
+ }
87
+ return result;
88
+ }
89
+ function buildSendBody(options) {
90
+ const body = typeof options === "string" ? { content: options } : options;
91
+ const result = {};
92
+ if (body.content !== void 0) result.content = body.content;
93
+ if (body.embeds?.length) {
94
+ result.embeds = body.embeds.map((e) => e instanceof import_builders.EmbedBuilder ? e.toJSON() : e);
95
+ }
96
+ if (body.files?.length && body.attachments) {
97
+ result.attachments = body.attachments.map((a) => ({
98
+ id: a.id,
99
+ filename: a.filename,
100
+ ...a.title != null && { title: a.title },
101
+ ...a.description != null && { description: a.description },
102
+ ...a.flags != null && { flags: a.flags }
103
+ }));
104
+ } else if (body.files?.length) {
105
+ result.attachments = body.files.map((f, i) => ({
106
+ id: i,
107
+ filename: f.filename ?? f.name
108
+ }));
109
+ }
110
+ if (body.flags !== void 0) result.flags = body.flags;
111
+ return result;
112
+ }
113
+
114
+ // src/util/ReactionCollector.ts
115
+ var import_events = require("events");
116
+ var import_collection = require("@fluxerjs/collection");
117
+
118
+ // src/util/Events.ts
119
+ var Events = {
120
+ Ready: "ready",
121
+ MessageCreate: "messageCreate",
122
+ MessageUpdate: "messageUpdate",
123
+ MessageDelete: "messageDelete",
124
+ MessageDeleteBulk: "messageDeleteBulk",
125
+ MessageReactionAdd: "messageReactionAdd",
126
+ MessageReactionRemove: "messageReactionRemove",
127
+ MessageReactionRemoveAll: "messageReactionRemoveAll",
128
+ MessageReactionRemoveEmoji: "messageReactionRemoveEmoji",
129
+ InteractionCreate: "interactionCreate",
130
+ GuildCreate: "guildCreate",
131
+ GuildUpdate: "guildUpdate",
132
+ GuildDelete: "guildDelete",
133
+ GuildBanAdd: "guildBanAdd",
134
+ GuildBanRemove: "guildBanRemove",
135
+ GuildEmojisUpdate: "guildEmojisUpdate",
136
+ GuildStickersUpdate: "guildStickersUpdate",
137
+ GuildIntegrationsUpdate: "guildIntegrationsUpdate",
138
+ GuildMemberAdd: "guildMemberAdd",
139
+ GuildMemberUpdate: "guildMemberUpdate",
140
+ GuildMemberRemove: "guildMemberRemove",
141
+ GuildMembersChunk: "guildMembersChunk",
142
+ GuildRoleCreate: "guildRoleCreate",
143
+ GuildRoleUpdate: "guildRoleUpdate",
144
+ GuildRoleDelete: "guildRoleDelete",
145
+ GuildScheduledEventCreate: "guildScheduledEventCreate",
146
+ GuildScheduledEventUpdate: "guildScheduledEventUpdate",
147
+ GuildScheduledEventDelete: "guildScheduledEventDelete",
148
+ ChannelCreate: "channelCreate",
149
+ ChannelUpdate: "channelUpdate",
150
+ ChannelDelete: "channelDelete",
151
+ ChannelPinsUpdate: "channelPinsUpdate",
152
+ InviteCreate: "inviteCreate",
153
+ InviteDelete: "inviteDelete",
154
+ TypingStart: "typingStart",
155
+ UserUpdate: "userUpdate",
156
+ PresenceUpdate: "presenceUpdate",
157
+ VoiceStateUpdate: "voiceStateUpdate",
158
+ VoiceServerUpdate: "voiceServerUpdate",
159
+ VoiceStatesSync: "voiceStatesSync",
160
+ WebhooksUpdate: "webhooksUpdate",
161
+ Resumed: "resumed",
162
+ Error: "error",
163
+ Debug: "debug"
164
+ };
165
+
166
+ // src/util/ReactionCollector.ts
167
+ var ReactionCollector = class extends import_events.EventEmitter {
168
+ client;
169
+ messageId;
170
+ channelId;
171
+ options;
172
+ collected = new import_collection.Collection();
173
+ _timeout = null;
174
+ _ended = false;
175
+ _listener;
176
+ constructor(client, messageId, channelId, options = {}) {
177
+ super();
178
+ this.client = client;
179
+ this.messageId = messageId;
180
+ this.channelId = channelId;
181
+ this.options = {
182
+ filter: options.filter ?? (() => true),
183
+ time: options.time ?? 0,
184
+ max: options.max ?? 0
185
+ };
186
+ this._listener = (reaction, user, _msgId, chId, _emoji, userId) => {
187
+ if (this._ended || reaction.messageId !== this.messageId || chId !== this.channelId) return;
188
+ if (!this.options.filter(reaction, user)) return;
189
+ const key = `${userId}:${reaction.emoji.id ?? reaction.emoji.name}`;
190
+ this.collected.set(key, { reaction, user });
191
+ this.emit("collect", reaction, user);
192
+ if (this.options.max > 0 && this.collected.size >= this.options.max) {
193
+ this.stop("limit");
194
+ }
195
+ };
196
+ this.client.on(Events.MessageReactionAdd, this._listener);
197
+ if (this.options.time > 0) {
198
+ this._timeout = setTimeout(() => this.stop("time"), this.options.time);
199
+ }
200
+ }
201
+ stop(reason = "user") {
202
+ if (this._ended) return;
203
+ this._ended = true;
204
+ this.client.off(Events.MessageReactionAdd, this._listener);
205
+ if (this._timeout) {
206
+ clearTimeout(this._timeout);
207
+ this._timeout = null;
208
+ }
209
+ this.emit("end", this.collected, reason);
210
+ }
211
+ on(event, listener) {
212
+ return super.on(event, listener);
213
+ }
214
+ emit(event, ...args) {
215
+ return super.emit(event, ...args);
216
+ }
217
+ };
218
+
219
+ // src/structures/Message.ts
220
+ var Message = class _Message extends Base {
221
+ client;
222
+ id;
223
+ channelId;
224
+ guildId;
225
+ author;
226
+ content;
227
+ createdAt;
228
+ editedAt;
229
+ pinned;
230
+ attachments;
231
+ type;
232
+ flags;
233
+ mentionEveryone;
234
+ tts;
235
+ embeds;
236
+ stickers;
237
+ reactions;
238
+ messageReference;
239
+ messageSnapshots;
240
+ call;
241
+ referencedMessage;
242
+ /** Webhook ID if this message was sent via webhook. Null otherwise. */
243
+ webhookId;
244
+ /** Users mentioned in this message. */
245
+ mentions;
246
+ /** Role IDs mentioned in this message. */
247
+ mentionRoles;
248
+ /** Client-side nonce for acknowledgment. Null if not provided. */
249
+ nonce;
250
+ /**
251
+ * Channel where this message was sent. Resolved from cache; null if not cached.
252
+ * Messages can only exist in text-based channels (text, DM, announcement), so this always has send() when non-null.
253
+ */
254
+ get channel() {
255
+ return this.client.channels.get(this.channelId) ?? null;
256
+ }
257
+ /** Guild where this message was sent. Resolved from cache; null for DMs or if not cached. */
258
+ get guild() {
259
+ return this.guildId ? this.client.guilds.get(this.guildId) ?? null : null;
260
+ }
261
+ /**
262
+ * Resolve the channel (from cache or API). Use when you need the channel and it may not be cached.
263
+ * @returns The channel
264
+ * @throws FluxerError with CHANNEL_NOT_FOUND if the channel does not exist
265
+ */
266
+ async resolveChannel() {
267
+ return this.client.channels.resolve(this.channelId);
268
+ }
269
+ /**
270
+ * Resolve the guild (from cache or API). Returns null for DMs.
271
+ * @returns The guild, or null if this is a DM or guild not found
272
+ */
273
+ async resolveGuild() {
274
+ return this.guildId ? this.client.guilds.resolve(this.guildId) : null;
275
+ }
276
+ /** @param data - API message from POST/PATCH /channels/{id}/messages or gateway MESSAGE_CREATE */
277
+ constructor(client, data) {
278
+ super();
279
+ this.client = client;
280
+ this.id = data.id;
281
+ this.channelId = data.channel_id;
282
+ this.guildId = data.guild_id ?? null;
283
+ this.author = client.getOrCreateUser(data.author);
284
+ this.content = data.content;
285
+ this.createdAt = new Date(data.timestamp);
286
+ this.editedAt = data.edited_timestamp ? new Date(data.edited_timestamp) : null;
287
+ this.pinned = data.pinned;
288
+ this.attachments = new import_collection2.Collection();
289
+ for (const a of data.attachments ?? []) this.attachments.set(a.id, a);
290
+ this.type = data.type ?? import_types.MessageType.Default;
291
+ this.flags = data.flags ?? 0;
292
+ this.mentionEveryone = data.mention_everyone ?? false;
293
+ this.tts = data.tts ?? false;
294
+ this.embeds = data.embeds ?? [];
295
+ this.stickers = data.stickers ?? [];
296
+ this.reactions = data.reactions ?? [];
297
+ this.messageReference = data.message_reference ?? null;
298
+ this.messageSnapshots = data.message_snapshots ?? [];
299
+ this.call = data.call ?? null;
300
+ this.referencedMessage = data.referenced_message ? new _Message(client, data.referenced_message) : null;
301
+ this.webhookId = data.webhook_id ?? null;
302
+ this.mentions = (data.mentions ?? []).map((u) => client.getOrCreateUser(u));
303
+ this.mentionRoles = data.mention_roles ?? [];
304
+ this.nonce = data.nonce ?? null;
305
+ }
306
+ /**
307
+ * Send a message to this channel without replying. Use when you want a standalone message.
308
+ * @param options - Text content or object with content, embeds, and/or files
309
+ * @example
310
+ * await message.send('Pong!');
311
+ * await message.send({ embeds: [embed] }); // EmbedBuilder auto-converted
312
+ * await message.send({ content: 'File', files: [{ name: 'data.txt', data }] });
313
+ */
314
+ async send(options) {
315
+ const payload = await _Message._createMessageBody(options);
316
+ return this._send(payload);
317
+ }
318
+ /**
319
+ * Send a message to a specific channel. Use for logging, forwarding, or sending to another channel in the guild.
320
+ * @param channelId - Snowflake of the target channel (e.g. log channel ID)
321
+ * @param options - Text content or object with content and/or embeds
322
+ * @example
323
+ * await message.sendTo(logChannelId, 'User ' + message.author.username + ' said: ' + message.content);
324
+ * await message.sendTo(announceChannelId, { embeds: [embed] });
325
+ */
326
+ async sendTo(channelId, options) {
327
+ return this.client.channels.send(channelId, options);
328
+ }
329
+ /**
330
+ * Reply to this message (shows as a reply in the client).
331
+ * @param options - Text content or object with content, embeds, and/or reply options (ping, replyTo)
332
+ * @example
333
+ * await message.reply('Pong!');
334
+ * await message.reply({ embeds: [embed] });
335
+ * await message.reply('No ping!', { ping: false });
336
+ * await message.reply({ content: 'Reply to other', replyTo: otherMessage });
337
+ */
338
+ async reply(options, replyOptions) {
339
+ const opts = typeof options === "string" ? { content: options } : options;
340
+ const mergedReply = replyOptions ?? (opts.ping !== void 0 || opts.replyTo !== void 0) ? { ping: opts.ping, replyTo: opts.replyTo } : void 0;
341
+ const refMessage = mergedReply?.replyTo ?? this;
342
+ const ref = refMessage instanceof _Message ? {
343
+ channel_id: refMessage.channelId,
344
+ message_id: refMessage.id,
345
+ guild_id: refMessage.guildId ?? void 0
346
+ } : {
347
+ channel_id: refMessage.channelId,
348
+ message_id: refMessage.messageId,
349
+ guild_id: void 0
350
+ };
351
+ const payload = await _Message._createMessageBody(opts, ref, mergedReply?.ping !== false);
352
+ return this._send(payload);
353
+ }
354
+ /** Exposed for testing purposes, use Message.reply() or send() for normal use */
355
+ static async _createMessageBody(content, referenced_message, ping) {
356
+ if (typeof content === "string") {
357
+ if (content.length === 0) {
358
+ throw new RangeError("Cannot send an empty message");
359
+ }
360
+ content = { content };
361
+ }
362
+ const base = buildSendBody(content);
363
+ const files = content.files?.length ? await resolveMessageFiles(content.files) : void 0;
364
+ const body = { ...base };
365
+ if (referenced_message) {
366
+ body.message_reference = referenced_message;
367
+ if (ping === false) {
368
+ body.flags = (body.flags ?? 0) | import_types.MessageFlags.SuppressNotifications;
369
+ }
370
+ }
371
+ return { files, body };
372
+ }
373
+ async _send(payload) {
374
+ const data = await this.client.rest.post(
375
+ import_types.Routes.channelMessages(this.channelId),
376
+ payload
377
+ );
378
+ this.client._addMessageToCache(this.channelId, data);
379
+ return new _Message(this.client, data);
380
+ }
381
+ /**
382
+ * Edit this message. Only the author (or admins) can edit.
383
+ * @param options - New content and/or embeds
384
+ */
385
+ async edit(options) {
386
+ const body = {};
387
+ if (options.content !== void 0) body.content = options.content;
388
+ if (options.embeds?.length) {
389
+ body.embeds = options.embeds.map((e) => e instanceof import_builders2.EmbedBuilder ? e.toJSON() : e);
390
+ }
391
+ const data = await this.client.rest.patch(import_types.Routes.channelMessage(this.channelId, this.id), {
392
+ body
393
+ });
394
+ return new _Message(this.client, data);
395
+ }
396
+ /**
397
+ * Create a reaction collector for this message.
398
+ * Collects reactions matching the filter until time expires or max is reached.
399
+ * @param options - Filter, time (ms), and max count
400
+ * @example
401
+ * const collector = message.createReactionCollector({ filter: (r, u) => u.id === userId, time: 10000 });
402
+ * collector.on('collect', (reaction, user) => console.log(user.username, 'reacted with', reaction.emoji.name));
403
+ * collector.on('end', (collected, reason) => { ... });
404
+ */
405
+ createReactionCollector(options) {
406
+ return new ReactionCollector(this.client, this.id, this.channelId, options);
407
+ }
408
+ /**
409
+ * Re-fetch this message from the API to get the latest content, embeds, reactions, etc.
410
+ * Use when you have a stale Message (e.g. from an old event or cache) and need fresh data.
411
+ * @returns The updated message
412
+ * @throws FluxerError with MESSAGE_NOT_FOUND if the message was deleted or does not exist
413
+ * @example
414
+ * const updated = await message.fetch();
415
+ * console.log('Latest content:', updated.content);
416
+ */
417
+ async fetch() {
418
+ return this.client.channels.fetchMessage(this.channelId, this.id);
419
+ }
420
+ /** Delete this message. */
421
+ async delete() {
422
+ await this.client.rest.delete(import_types.Routes.channelMessage(this.channelId, this.id));
423
+ }
424
+ /**
425
+ * Delete a specific attachment from this message.
426
+ * DELETE /channels/{id}/messages/{id}/attachments/{attachmentId}.
427
+ */
428
+ async deleteAttachment(attachmentId) {
429
+ await this.client.rest.delete(
430
+ import_types.Routes.channelMessageAttachment(this.channelId, this.id, attachmentId),
431
+ { auth: true }
432
+ );
433
+ this.attachments.delete(attachmentId);
434
+ }
435
+ /** Pin this message to the channel. Requires Manage Messages permission. */
436
+ async pin() {
437
+ await this.client.rest.put(import_types.Routes.channelPinMessage(this.channelId, this.id));
438
+ this.pinned = true;
439
+ }
440
+ /** Unpin this message from the channel. Requires Manage Messages permission. */
441
+ async unpin() {
442
+ await this.client.rest.delete(import_types.Routes.channelPinMessage(this.channelId, this.id));
443
+ this.pinned = false;
444
+ }
445
+ /**
446
+ * Format emoji for reaction API: unicode string or "name:id" for custom.
447
+ * For string resolution (e.g. :name:), use client.resolveEmoji; Message methods resolve automatically when guildId is available.
448
+ */
449
+ static formatEmoji(emoji) {
450
+ if (typeof emoji === "string") return emoji;
451
+ return `${emoji.name}:${emoji.id}`;
452
+ }
453
+ resolveEmojiForReaction(emoji) {
454
+ return this.client.resolveEmoji(emoji, this.guildId);
455
+ }
456
+ /**
457
+ * Add a reaction to this message (as the bot).
458
+ * @param emoji - Unicode emoji, custom `{ name, id }`, `:name:`, `name:id`, or `<:name:id>`
459
+ */
460
+ async react(emoji) {
461
+ const emojiStr = await this.resolveEmojiForReaction(emoji);
462
+ const route = `${import_types.Routes.channelMessageReaction(this.channelId, this.id, emojiStr)}/@me`;
463
+ await this.client.rest.put(route);
464
+ }
465
+ /**
466
+ * Remove the bot's reaction, or a specific user's reaction if userId is provided.
467
+ * @param emoji - Unicode emoji, custom `{ name, id }`, `:name:`, `name:id`, or `<:name:id>`
468
+ * @param userId - If provided, removes that user's reaction (requires moderator permissions)
469
+ */
470
+ async removeReaction(emoji, userId) {
471
+ const emojiStr = await this.resolveEmojiForReaction(emoji);
472
+ const route = `${import_types.Routes.channelMessageReaction(this.channelId, this.id, emojiStr)}/${userId ?? "@me"}`;
473
+ await this.client.rest.delete(route);
474
+ }
475
+ /**
476
+ * Remove all reactions from this message.
477
+ * Requires moderator permissions.
478
+ */
479
+ async removeAllReactions() {
480
+ await this.client.rest.delete(import_types.Routes.channelMessageReactions(this.channelId, this.id));
481
+ }
482
+ /**
483
+ * Remove all reactions of a specific emoji from this message.
484
+ * @param emoji - Unicode emoji, custom `{ name, id }`, `:name:`, `name:id`, or `<:name:id>`. Requires moderator permissions.
485
+ */
486
+ async removeReactionEmoji(emoji) {
487
+ const emojiStr = await this.resolveEmojiForReaction(emoji);
488
+ await this.client.rest.delete(import_types.Routes.channelMessageReaction(this.channelId, this.id, emojiStr));
489
+ }
490
+ /**
491
+ * Fetch users who reacted with the given emoji.
492
+ * @param emoji - Unicode emoji or custom `{ name, id }`
493
+ * @param options - limit (1–100), after (user ID for pagination)
494
+ * @returns Array of User objects
495
+ */
496
+ async fetchReactionUsers(emoji, options) {
497
+ const emojiStr = await this.resolveEmojiForReaction(emoji);
498
+ const params = new URLSearchParams();
499
+ if (options?.limit != null) params.set("limit", String(options.limit));
500
+ if (options?.after) params.set("after", options.after);
501
+ const qs = params.toString();
502
+ const route = import_types.Routes.channelMessageReaction(this.channelId, this.id, emojiStr) + (qs ? `?${qs}` : "");
503
+ const data = await this.client.rest.get(route);
504
+ const list = Array.isArray(data) ? data : data?.users ?? [];
505
+ return list.map((u) => this.client.getOrCreateUser(u));
506
+ }
507
+ };
508
+ // Annotate the CommonJS export names for ESM import in node:
509
+ 0 && (module.exports = {
510
+ Message
511
+ });