@seedcord/gateway 0.0.1 → 0.1.0-next.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/index.mjs CHANGED
@@ -1,7 +1,3918 @@
1
- //#region src/index.ts
1
+ import "reflect-metadata";
2
+ import { BuilderComponent, CustomId, Fault, Notice, RegisterCommand, RowComponent, Silence, defineGate, paginate } from "@seedcord/core";
3
+ import { CommandMetadataKey, ComponentDefsKey, EventMetadataKey, GateNotice, GatedMetadataKey, InteractionMetadataKey, InteractionRouteKeys, InteractionRoutes, MiddlewareMetadataKey, NotInGuild, NoticeCard, PAGE_MAX, SubscribeMetadataKey, decodeFor, pageCursor, pickNotice, prefixOf, runHandlerGates, setBotColor } from "@seedcord/core/internal";
4
+ import { ApplicationCommandType, AttachmentBuilder, ButtonStyle, Client, Collection, ComponentType, DiscordAPIError, Events, Guild, GuildMember, Message, MessageFlags, PermissionFlagsBits, RESTJSONErrorCodes, Role, SeparatorSpacingSize, SnowflakeUtil, TextChannel, User, WebhookClient, chatInputApplicationCommandMention } from "discord.js";
5
+ import { SeedcordErrorCode } from "@seedcord/errors";
6
+ import { SeedcordError, SeedcordRangeError, SeedcordTypeError, validateDiscordToken } from "@seedcord/errors/internal";
7
+ import { filterCirculars, formatFilePath, hasKeys, prettify, traverseDirectory } from "@seedcord/utils";
8
+ import { CoordinatedShutdown, CoordinatedStartup, HealthCheck, Logger, ShutdownPhase, StartupPhase, StrictEventEmitter } from "@seedcord/services";
9
+ import chalk from "chalk";
10
+ import { ActionRowBuilder, ButtonBuilder, ContextMenuCommandBuilder, SlashCommandBuilder, TextDisplayBuilder } from "@discordjs/builders";
11
+ import { buildSlashRoute, routeLeavesOf } from "@seedcord/utils/internal";
12
+ import { existsSync } from "node:fs";
13
+ import { resolve } from "node:path";
14
+ import { pathToFileURL } from "node:url";
15
+ import { MemoryRateLimiter } from "@seedcord/rate-limiter";
16
+ import { SeedcordBrand, wrapHot } from "@seedcord/types/internal";
17
+ import { Envapt, Envapter } from "envapt";
18
+ import * as crypto from "node:crypto";
19
+
20
+ export * from "@seedcord/core"
21
+
22
+ export * from "@seedcord/errors"
23
+
24
+ export * from "@seedcord/utils"
25
+
26
+ export * from "@seedcord/services"
27
+
28
+ export * from "@seedcord/rate-limiter"
29
+
30
+ //#region src/bot/decorators/Events.ts
31
+ /**
32
+ * Registers an event handler class with one or more Discord.js events.
33
+ *
34
+ * Associates the decorated class with the provided Discord client events for automatic registration and execution when those events are emitted.
35
+ *
36
+ * Supply any number of event tuples. Each tuple can include per event options.
37
+ *
38
+ * @typeParam EventKey - Union of Discord.js ClientEvents keys to register for
39
+ * @param defs - One or more tuples of [event, options]
40
+ * @decorator
41
+ * @example
42
+ * ```ts
43
+ * \@RegisterEvent([Events.MessageCreate])
44
+ * class MessageHandler extends EventHandler<Events.MessageCreate> {
45
+ * async execute() {
46
+ * // Handle message creation
47
+ * }
48
+ * }
49
+ * ```
50
+ *
51
+ * @example
52
+ * ```ts
53
+ * \@RegisterEvent([Events.MessageCreate], [Events.MessageUpdate])
54
+ * class MessageHandler extends EventHandler<Events.MessageCreate | Events.MessageUpdate> {
55
+ * async execute() {
56
+ * // Handle message creation or update
57
+ * }
58
+ * }
59
+ * ```
60
+ *
61
+ * @example
62
+ * ```ts
63
+ * \@RegisterEvent([Events.MessageCreate, { frequency: 'once' }], [Events.MessageUpdate])
64
+ * class OneTimeMessageHandler extends EventHandler<Events.MessageCreate | Events.MessageUpdate> {
65
+ * async execute() {
66
+ * // Handle only the first message creation, and message update normally
67
+ * }
68
+ * }
69
+ * ```
70
+ */
71
+ function RegisterEvent(...defs) {
72
+ return function(constructor) {
73
+ const existing = Reflect.getMetadata(EventMetadataKey, constructor) ?? [];
74
+ const entries = defs.map(([event, options]) => ({
75
+ event,
76
+ frequency: options?.frequency ?? "on"
77
+ }));
78
+ Reflect.defineMetadata(EventMetadataKey, [...existing, ...entries], constructor);
79
+ };
80
+ }
81
+
82
+ //#endregion
83
+ //#region src/bot/decorators/Gated.ts
84
+ /**
85
+ * Attaches gates to a handler. The gates run before `execute`, and a gate refusing stops the handler with
86
+ * the reply or drop the gate threw. Multiple gates are ANDed, so each must pass. A gate that requires a
87
+ * context the handler does not provide (a button gate on a slash handler, an interaction gate on an event
88
+ * handler) is a compile error at this line, and the error names the gate and the handler kind. Place it
89
+ * above the route decorator.
90
+ *
91
+ * Combine gates with {@link and} or {@link or} to build a single gate from multiple arms.
92
+ *
93
+ * @example
94
+ * ```ts
95
+ * import { PermissionFlagsBits } from 'discord.js';
96
+ *
97
+ * \@Gated(GuildOnly(), RequirePermissions([PermissionFlagsBits.Administrator]))
98
+ * \@SlashRoute('maintenance')
99
+ * class Maintenance extends SlashHandler<'maintenance'> {
100
+ * async execute() {
101
+ * // both gates passed, so this runs in a guild with an admin caller
102
+ * }
103
+ * }
104
+ * ```
105
+ *
106
+ * @typeParam Gates - The non-empty tuple of gates to run, in order, against the handler's context.
107
+ * @typeParam TCtor - The decorated handler's constructor, checked against every gate's required context.
108
+ * @param gates - One or more gates to attach, each ANDed so the handler runs only when all pass.
109
+ * @param ctor - The handler class being decorated, rejected at compile time when a gate needs a context it lacks.
110
+ *
111
+ * @see {@link defineGate}
112
+ * @see {@link defineEffectGate}
113
+ * @decorator
114
+ */
115
+ function Gated(...gates) {
116
+ return function(ctor) {
117
+ const existing = Reflect.getMetadata(GatedMetadataKey, ctor) ?? [];
118
+ Reflect.defineMetadata(GatedMetadataKey, [...existing, ...gates], ctor);
119
+ };
120
+ }
121
+
122
+ //#endregion
123
+ //#region src/miscellaneous/areRoutes.ts
124
+ /**
125
+ * Checks if the provided value is an array of strings.
126
+ *
127
+ * @internal
128
+ */
129
+ function areRoutes(routes) {
130
+ return Array.isArray(routes) && routes.every((r) => typeof r === "string");
131
+ }
132
+
133
+ //#endregion
134
+ //#region src/bot/decorators/Interactions.ts
135
+ /**
136
+ * Types of select menus supported for routing
137
+ */
138
+ let SelectMenuKind = /* @__PURE__ */ function(SelectMenuKind) {
139
+ SelectMenuKind["String"] = "string";
140
+ SelectMenuKind["User"] = "user";
141
+ SelectMenuKind["Role"] = "role";
142
+ SelectMenuKind["Channel"] = "channel";
143
+ SelectMenuKind["Mentionable"] = "mentionable";
144
+ return SelectMenuKind;
145
+ }({});
146
+ /**
147
+ * Routes one or more slash commands to a {@link SlashHandler}.
148
+ *
149
+ * Pass the same route string(s) as the handler's generic. A single command reads `this.options`, several
150
+ * commands branch with `this.match`. The decorator routes and the generic must match exactly, so listing
151
+ * fewer or more than the handler declares is a compile error. Subcommands use a slash path.
152
+ *
153
+ * @param routes - The route string(s) this handler serves, e.g. `'ban'`, `'ban', 'kick'`, or `'demo/setup'`.
154
+ * @decorator
155
+ * @example
156
+ * ```ts
157
+ * \@SlashRoute('ban')
158
+ * class BanHandler extends SlashHandler<'ban'> {
159
+ * async execute() {
160
+ * const target = this.options.getUser('target');
161
+ * }
162
+ * }
163
+ * ```
164
+ *
165
+ * @example
166
+ * ```ts
167
+ * \@SlashRoute('ban', 'kick')
168
+ * class ModerationHandler extends SlashHandler<'ban' | 'kick'> {
169
+ * async execute() {
170
+ * await this.match({ ban: (o) => o.getUser('target'), kick: (o) => o.getUser('member') });
171
+ * }
172
+ * }
173
+ * ```
174
+ */
175
+ function SlashRoute(...routes) {
176
+ return function(constructor) {
177
+ storeMetadata(InteractionRoutes.Slash, routes, constructor);
178
+ };
179
+ }
180
+ /**
181
+ * Routes button interactions to handler classes.
182
+ *
183
+ * Pass the {@link CustomId} definition(s) this handler decodes and list the same ones in the handler's
184
+ * generic. Passing different definitions to the decorator and the generic is a compile error. Routing
185
+ * matches the stable prefix, so a wire minted from an older shape still reaches the handler, where
186
+ * reading this.params throws StaleCustomId and the controller boundary turns it into a reply.
187
+ *
188
+ * @param defs - The customId definition(s) this handler decodes, one per route.
189
+ * @decorator
190
+ */
191
+ function ButtonRoute(...defs) {
192
+ return function(constructor) {
193
+ storeComponentRoute(InteractionRoutes.Button, defs, constructor);
194
+ };
195
+ }
196
+ /**
197
+ * Routes modal submissions to handler classes.
198
+ *
199
+ * Pass the {@link CustomId} definition(s) this handler decodes and list the same ones in the handler's
200
+ * generic. Passing different definitions to the decorator and the generic is a compile error. Routing
201
+ * matches the stable prefix, so an older-shape wire still reaches the handler and throws StaleCustomId
202
+ * on read, the same as a button route.
203
+ *
204
+ * @param defs - The customId definition(s) this handler decodes, one per route.
205
+ * @decorator
206
+ */
207
+ function ModalRoute(...defs) {
208
+ return function(constructor) {
209
+ storeComponentRoute(InteractionRoutes.Modal, defs, constructor);
210
+ };
211
+ }
212
+ /**
213
+ * Routes one or more context-menu commands to a {@link ContextMenuHandler}.
214
+ *
215
+ * Pass the kind (`ApplicationCommandType.User` or `ApplicationCommandType.Message`) and the command name(s),
216
+ * each checked against that kind's registry, so a typo is a compile error. The same kind must sit on the
217
+ * handler's generic, cross-checked both directions. Context menus carry no options, so a multi-name handler
218
+ * reads `this.target` uniformly with no branch.
219
+ *
220
+ * @param kind - The context-menu kind, `ApplicationCommandType.User` or `ApplicationCommandType.Message`.
221
+ * @param names - The command name(s) this handler serves, keyed off the matching registry.
222
+ * @decorator
223
+ * @example
224
+ * ```ts
225
+ * \@ContextMenuRoute(ApplicationCommandType.User, 'View Profile')
226
+ * class ViewProfile extends ContextMenuHandler<ApplicationCommandType.User> {
227
+ * async execute() {
228
+ * const user = this.target;
229
+ * }
230
+ * }
231
+ * ```
232
+ */
233
+ function ContextMenuRoute(kind, ...names) {
234
+ return function(constructor) {
235
+ storeMetadata(kind === ApplicationCommandType.User ? InteractionRoutes.UserContextMenu : InteractionRoutes.MessageContextMenu, names, constructor);
236
+ };
237
+ }
238
+ /**
239
+ * Routes one or more commands' autocomplete to an {@link AutocompleteHandler}.
240
+ *
241
+ * Pass the same command route string(s) as the handler's generic. One command branches with `this.match`
242
+ * over its autocompletable fields, several commands share one handler whose arms span every command's
243
+ * fields. The decorator routes and the generic must match exactly, so listing fewer or more than the
244
+ * handler declares is a compile error.
245
+ *
246
+ * @param routes - The command route string(s) this handler serves, e.g. `'search'` or `'search', 'find'`.
247
+ * @decorator
248
+ * @example
249
+ * ```ts
250
+ * \@AutocompleteRoute('search')
251
+ * class SearchAutocomplete extends AutocompleteHandler<'search'> {
252
+ * async execute() {
253
+ * await this.match({ query: (value, respond) => respond([{ name: value, value }]) });
254
+ * }
255
+ * }
256
+ * ```
257
+ */
258
+ function AutocompleteRoute(...routes) {
259
+ return function(constructor) {
260
+ storeMetadata(InteractionRoutes.Autocomplete, routes, constructor);
261
+ };
262
+ }
263
+ /**
264
+ * Routes select menu interactions to handler classes.
265
+ *
266
+ * Pass the select kind and the {@link CustomId} definition(s) this handler decodes. The handler's
267
+ * generic must list the same definitions, and its second generic argument must be the matching select
268
+ * interaction type, or it is a compile error.
269
+ *
270
+ * @param type - Select menu kind from {@link SelectMenuKind}.
271
+ * @param defs - The customId definition(s) this handler decodes, one per route.
272
+ * @decorator
273
+ *
274
+ * @example
275
+ * ```typescript
276
+ * \@SelectMenuRoute(SelectMenuKind.User, AssignId)
277
+ * class AssignSelect extends SelectMenuHandler<SelectMenuKind.User, [typeof AssignId]> {
278
+ * // handles user select menus minted from AssignId
279
+ * }
280
+ * ```
281
+ */
282
+ function SelectMenuRoute(type, ...defs) {
283
+ return function(constructor) {
284
+ storeComponentRoute({
285
+ ["string"]: InteractionRoutes.StringMenu,
286
+ ["user"]: InteractionRoutes.UserMenu,
287
+ ["role"]: InteractionRoutes.RoleMenu,
288
+ ["channel"]: InteractionRoutes.ChannelMenu,
289
+ ["mentionable"]: InteractionRoutes.MentionableMenu
290
+ }[type], defs, constructor);
291
+ };
292
+ }
293
+ function storeComponentRoute(route, defs, constructor) {
294
+ storeMetadata(route, defs.map((def) => def.prefix), constructor);
295
+ Reflect.defineMetadata(ComponentDefsKey, defs, constructor);
296
+ }
297
+ function storeMetadata(route, routes, constructor) {
298
+ const key = InteractionRouteKeys[route];
299
+ const savedRoutes = Reflect.getMetadata(key, constructor);
300
+ const existing = areRoutes(savedRoutes) ? savedRoutes : [];
301
+ const toStore = Array.isArray(routes) ? routes : [routes];
302
+ Reflect.defineMetadata(key, [...existing, ...toStore], constructor);
303
+ Reflect.defineMetadata(InteractionMetadataKey, true, constructor);
304
+ }
305
+
306
+ //#endregion
307
+ //#region src/bot/decorators/Middlewares.ts
308
+ /**
309
+ * Middleware types supported by Seedcord
310
+ */
311
+ let MiddlewareType = /* @__PURE__ */ function(MiddlewareType) {
312
+ MiddlewareType["Interaction"] = "interaction";
313
+ MiddlewareType["Event"] = "event";
314
+ return MiddlewareType;
315
+ }({});
316
+ /**
317
+ * Decorator used to register middleware with priority ordering. The lower the priority number, the earlier it runs.
318
+ *
319
+ * Interaction middleware cannot specify event filters.
320
+ *
321
+ * @param type - Middleware kind from {@link MiddlewareType}
322
+ * @param priority - Ordering value where lower runs earlier. {@default `0`}
323
+ * @param options - Additional registration options
324
+ *
325
+ * @decorator
326
+ *
327
+ * @example
328
+ * ```ts
329
+ * \@Middleware(MiddlewareType.Event, 10, { events: [Events.MessageCreate, Events.MessageUpdate] })
330
+ * class MyEventMiddleware extends EventMiddleware {}
331
+ * ```
332
+ * @throws A **SeedcordTypeError** If priority is not a finite number
333
+ * @throws A **SeedcordError** If interaction middleware specifies event filters
334
+ */
335
+ function Middleware(type, priority = 0, options = {}) {
336
+ return (ctor) => {
337
+ const normalizedPriority = Number(priority);
338
+ if (!Number.isFinite(normalizedPriority)) throw new SeedcordTypeError(SeedcordErrorCode.DecoratorInvalidMiddlewarePriority);
339
+ if (type === "interaction" && Array.isArray(options.events) && options.events.length > 0) throw new SeedcordError(SeedcordErrorCode.DecoratorInteractionEventFilter);
340
+ const metadata = {
341
+ priority: normalizedPriority,
342
+ type,
343
+ ...options.events && options.events.length > 0 && { events: options.events }
344
+ };
345
+ Reflect.defineMetadata(MiddlewareMetadataKey, metadata, ctor);
346
+ };
347
+ }
348
+
349
+ //#endregion
350
+ //#region src/bot/gates/catalog/IgnoreBots.ts
351
+ /**
352
+ * Drops a client event whose actor is a bot, with a {@link Silence} so nothing is replied. Event-only, because a
353
+ * Silence on an interaction would leave Discord's failed-interaction state. It rejects an interaction handler at
354
+ * the decorator line. Takes no options, so attach it directly without calling it.
355
+ *
356
+ * @see {@link Gated}
357
+ *
358
+ * @example
359
+ * ```ts
360
+ * import { Events } from 'discord.js';
361
+ *
362
+ * \@Gated(IgnoreBots)
363
+ * class OnMessage extends EventHandler<Events.MessageCreate> {
364
+ * async execute() {
365
+ * // ...
366
+ * }
367
+ * }
368
+ * ```
369
+ */
370
+ const IgnoreBots = defineGate("IgnoreBots", (ctx) => {
371
+ if (ctx.user?.bot) throw new Silence("actor is a bot");
372
+ });
373
+
374
+ //#endregion
375
+ //#region src/bot/notices/utils.ts
376
+ function mentionFor(subject) {
377
+ if (subject instanceof Role) return `<@&${subject.id}>`;
378
+ if (subject instanceof TextChannel) return `<#${subject.id}>`;
379
+ if (subject instanceof GuildMember) return `<@${subject.id}>`;
380
+ return `\`${subject.name}\``;
381
+ }
382
+ function labelFor(subject) {
383
+ if (subject instanceof Role) return "role";
384
+ if (subject instanceof TextChannel) return "channel";
385
+ if (subject instanceof GuildMember) return "member";
386
+ return "guild";
387
+ }
388
+
389
+ //#endregion
390
+ //#region src/bot/notices/index.ts
391
+ var NotNsfw = class extends GateNotice {
392
+ constructor(message = "This can only be used in an age-restricted channel.") {
393
+ super(message);
394
+ }
395
+ };
396
+ var MissingRole = class extends GateNotice {
397
+ role;
398
+ constructor(message, role) {
399
+ super(message ?? (role ? `You need the ${role.name} role to use this.` : "You do not have the required role."));
400
+ this.role = role;
401
+ }
402
+ };
403
+ var RoleHigherThanMe = class extends Notice {
404
+ role;
405
+ botRole;
406
+ constructor(message, role, botRole) {
407
+ super(message);
408
+ this.role = role;
409
+ this.botRole = botRole;
410
+ }
411
+ render() {
412
+ return { components: [new NoticeCard(`I cannot assign a role that is higher than me.\n\nThe role <@&${this.role.id}> is higher than my role <@&${this.botRole.id}> in the hierarchy.`).component] };
413
+ }
414
+ };
415
+ var CannotAssignBotRole = class extends Notice {
416
+ constructor(message = "I cannot assign a managed role.") {
417
+ super(message);
418
+ }
419
+ render() {
420
+ return { components: [new NoticeCard("I cannot assign a managed role.").component] };
421
+ }
422
+ };
423
+ var MissingPermissions = class extends Notice {
424
+ where;
425
+ missingPerms;
426
+ constructor(message, where, missingPerms) {
427
+ super(message);
428
+ this.where = where;
429
+ this.missingPerms = missingPerms;
430
+ }
431
+ render() {
432
+ const bullets = this.missingPerms.map((perm) => `• ${perm}`).join("\n");
433
+ return { components: [new NoticeCard(`The ${labelFor(this.where)} ${mentionFor(this.where)} is missing the following permission entries:\n\n${bullets}`).component] };
434
+ }
435
+ };
436
+ var HasDangerousPermissions = class extends Notice {
437
+ target;
438
+ dangerousPerms;
439
+ constructor(message, target, dangerousPerms) {
440
+ super(message);
441
+ this.target = target;
442
+ this.dangerousPerms = dangerousPerms;
443
+ }
444
+ render() {
445
+ const bullets = this.dangerousPerms.map((perm) => `• ${perm}`).join("\n");
446
+ return { components: [new NoticeCard(`The ${labelFor(this.target)} ${mentionFor(this.target)} has the following permission entries that must not be enabled:\n\n${bullets}`).component] };
447
+ }
448
+ };
449
+ var UserNotFound = class extends Notice {
450
+ userArg;
451
+ constructor(userArg) {
452
+ super(`User not found: ${userArg}`);
453
+ this.userArg = userArg;
454
+ }
455
+ render() {
456
+ return { components: [new NoticeCard(`User probably doesn't exist or was deleted.\n**User Argument:** \`${this.userArg}\`\nPlease check the user ID and try again. Only pass valid user IDs as the argument.`, "User Not Found").component] };
457
+ }
458
+ };
459
+ var UserNotInGuild = class extends Notice {
460
+ constructor(message = "User is not in the guild.") {
461
+ super(message);
462
+ }
463
+ render() {
464
+ return { components: [new NoticeCard(this.message).component] };
465
+ }
466
+ };
467
+ var RoleDoesNotExist = class extends Notice {
468
+ roleId;
469
+ constructor(message, roleId) {
470
+ super(message);
471
+ this.roleId = roleId;
472
+ }
473
+ render() {
474
+ return { components: [new NoticeCard(`The role with ID \`${this.roleId}\` does not exist.`).component] };
475
+ }
476
+ };
477
+ var CouldNotFindChannel = class extends Notice {
478
+ channelId;
479
+ constructor(message, channelId) {
480
+ super(message);
481
+ this.channelId = channelId;
482
+ }
483
+ render() {
484
+ return { components: [new NoticeCard(`Could not find channel with ID \`${this.channelId}\`. It could also be that the channel is not a text channel.`).component] };
485
+ }
486
+ };
487
+
488
+ //#endregion
489
+ //#region src/bot/gates/catalog/Nsfw.ts
490
+ function channelIsNsfw(channel) {
491
+ if (!channel) return false;
492
+ if (channel.isThread()) return channel.parent?.nsfw ?? false;
493
+ return "nsfw" in channel ? channel.nsfw : false;
494
+ }
495
+ /**
496
+ * Requires an age-restricted channel, else refuses. Pass {@link GateNoticeOptions} to reword or replace the refusal.
497
+ *
498
+ * A thread inherits its parent channel's nsfw flag. ModalSubmit has no reliable channel, so it is excluded.
499
+ *
500
+ * @param options - Reword the default refusal with `message`, or replace it with `notice`.
501
+ *
502
+ * @see {@link Gated}
503
+ *
504
+ * @example
505
+ * ```ts
506
+ * \@Gated(Nsfw())
507
+ * \@SlashRoute('nsfwcmd')
508
+ * class NsfwHandler extends SlashHandler<'nsfwcmd'> {
509
+ * async execute() {
510
+ * // ...
511
+ * }
512
+ * }
513
+ * ```
514
+ */
515
+ function Nsfw(options) {
516
+ return defineGate("Nsfw", (ctx) => {
517
+ if (channelIsNsfw(ctx.interaction.channel)) return;
518
+ throw pickNotice(options, (message) => new NotNsfw(message));
519
+ });
520
+ }
521
+
522
+ //#endregion
523
+ //#region src/bot/utilities/permissions/checkPermissions.ts
524
+ /**
525
+ * Map of permission bits to their prettified human readable names.
526
+ */
527
+ const PermissionNames = new Map(Object.entries(PermissionFlagsBits).map(([key, bit]) => [bit, prettify(key)]));
528
+ function checkPermissions(a, b, c, d, e) {
529
+ const { for: pFor, in: pIn, scope, inverse = false, missing: missingCtor, dangerous: dangerousCtor } = a instanceof Role || a instanceof GuildMember ? {
530
+ for: a,
531
+ in: b,
532
+ scope: c,
533
+ inverse: d ?? false,
534
+ ...e
535
+ } : a;
536
+ const Missing = missingCtor ?? MissingPermissions;
537
+ const Dangerous = dangerousCtor ?? HasDangerousPermissions;
538
+ const perms = pIn instanceof Guild ? pFor.permissions : pIn.permissionsFor(pFor, true);
539
+ const names = (bits) => bits.map((bit) => PermissionNames.get(bit) ?? String(bit));
540
+ const present = scope.filter((bit) => perms.has(bit, true));
541
+ const presentNames = names(present);
542
+ if (inverse) {
543
+ if (present.length > 0) throw new Dangerous(`${pFor instanceof Role ? "Role" : "Member"} has dangerous permissions in this ${pIn instanceof Guild ? "guild" : "channel"}`, pFor, presentNames);
544
+ return;
545
+ }
546
+ const missingBits = scope.filter((bit) => !perms.has(bit, true));
547
+ if (missingBits.length > 0) throw new Missing("Missing Any/All/No Permissions", pFor, names(missingBits));
548
+ }
549
+
550
+ //#endregion
551
+ //#region src/bot/gates/catalog/permissions.ts
552
+ const UNCACHED_MEMBER = "Your server member data could not be resolved. Try again.";
553
+ /**
554
+ * Requires the caller to hold every permission in `scope`, via `checkPermissions`. Refuses outside a guild.
555
+ *
556
+ * Interaction-only and excludes ModalSubmit, since a modal lacks a reliable cached caller member.
557
+ *
558
+ * @param scope - The permission flag bits the caller must all hold.
559
+ * @param options - Override each refusal, the outside-guild one with `notInGuild` and the missing-permissions one with `missing`.
560
+ *
561
+ * @see {@link Gated}
562
+ *
563
+ * @example
564
+ * ```ts
565
+ * import { PermissionFlagsBits } from 'discord.js';
566
+ *
567
+ * \@Gated(RequirePermissions([PermissionFlagsBits.BanMembers]))
568
+ * \@SlashRoute('ban')
569
+ * class BanHandler extends SlashHandler<'ban'> {
570
+ * async execute() {
571
+ * const target = this.options.getUser('target');
572
+ * }
573
+ * }
574
+ * ```
575
+ */
576
+ function RequirePermissions(scope, options) {
577
+ return defineGate("RequirePermissions", (ctx) => {
578
+ if (!ctx.guild) throw pickNotice(options?.notInGuild, (message) => new NotInGuild(message));
579
+ if (!ctx.member) throw pickNotice(options?.notInGuild, (message) => new NotInGuild(message ?? UNCACHED_MEMBER));
580
+ checkPermissions(ctx.member, ctx.guild, scope, false, options?.missing ? { missing: options.missing } : void 0);
581
+ });
582
+ }
583
+ /**
584
+ * Requires the bot to hold every permission in `scope`, via `checkPermissions`. Refuses outside a guild.
585
+ *
586
+ * It reads the bot's own member, so it attaches to modal handlers as well.
587
+ *
588
+ * @param scope - The permission flag bits the bot must all hold.
589
+ * @param options - Override each refusal, the outside-guild one with `notInGuild` and the missing-permissions one with `missing`.
590
+ *
591
+ * @see {@link Gated}
592
+ *
593
+ * @example
594
+ * ```ts
595
+ * import { PermissionFlagsBits } from 'discord.js';
596
+ *
597
+ * \@Gated(RequireBotPermissions([PermissionFlagsBits.BanMembers]))
598
+ * \@ModalRoute(MyModalId)
599
+ * class MyModalHandler extends ModalHandler<[typeof MyModalId]> {
600
+ * async execute() {
601
+ * // ...
602
+ * }
603
+ * }
604
+ * ```
605
+ */
606
+ function RequireBotPermissions(scope, options) {
607
+ return defineGate("RequireBotPermissions", (ctx) => {
608
+ const botMember = ctx.guild?.members.me;
609
+ if (!ctx.guild || !botMember) throw pickNotice(options?.notInGuild, (message) => new NotInGuild(message));
610
+ checkPermissions(botMember, ctx.guild, scope, false, options?.missing ? { missing: options.missing } : void 0);
611
+ });
612
+ }
613
+ /**
614
+ * Requires the caller to have `roleId`, read from the member's role cache. Refuses outside a guild first, then
615
+ * when the role is missing.
616
+ *
617
+ * Interaction-only and excludes ModalSubmit.
618
+ *
619
+ * @param roleId - The role snowflake the caller must hold, read from the member's role cache.
620
+ * @param options - Override each refusal, the outside-guild one with `notInGuild` and the missing-role one with `missingRole`.
621
+ *
622
+ * @see {@link Gated}
623
+ *
624
+ * @example
625
+ * ```ts
626
+ * \@Gated(RequireRole('123456789012345678'))
627
+ * \@SlashRoute('vip')
628
+ * class VipHandler extends SlashHandler<'vip'> {
629
+ * async execute() {
630
+ * // ...
631
+ * }
632
+ * }
633
+ * ```
634
+ */
635
+ function RequireRole(roleId, options) {
636
+ return defineGate("RequireRole", (ctx) => {
637
+ if (!ctx.guild) throw pickNotice(options?.notInGuild, (message) => new NotInGuild(message));
638
+ if (!ctx.member) throw pickNotice(options?.notInGuild, (message) => new NotInGuild(message ?? UNCACHED_MEMBER));
639
+ if (ctx.member.roles.cache.has(roleId)) return;
640
+ const role = ctx.guild.roles.cache.get(roleId) ?? null;
641
+ throw pickNotice(options?.missingRole, (message) => new MissingRole(message, role));
642
+ });
643
+ }
644
+
645
+ //#endregion
646
+ //#region src/bot/injectors/EmojiInjector.ts
647
+ const emojiStorage = {};
648
+ function isEmojiTuple(v) {
649
+ return Array.isArray(v) && v.length === 2 && typeof v[0] === "string" && typeof v[1] === "string";
650
+ }
651
+ /**
652
+ * Global emoji mappings object
653
+ *
654
+ * @see {@link EmojiMap}
655
+ */
656
+ const Emojis = emojiStorage;
657
+ /**
658
+ * Loads and injects emojis based on bot configuration.
659
+ *
660
+ * For emojis injected from specific guilds, ensure that the Guilds intent is provided in client options.
661
+ *
662
+ * @internal
663
+ */
664
+ var EmojiInjector = class {
665
+ core;
666
+ logger = new Logger("Emojis");
667
+ constructor(core) {
668
+ this.core = core;
669
+ }
670
+ async init() {
671
+ this.clearEmojis();
672
+ if (!this.core.config.bot.emojis || Object.keys(this.core.config.bot.emojis).length === 0) {
673
+ this.logger.debug(chalk.bold.yellow("No emojis configured, skipping emoji injection."));
674
+ return;
675
+ }
676
+ const configEmojis = this.core.config.bot.emojis;
677
+ await this.core.bot.client.application?.emojis.fetch();
678
+ const failures = [];
679
+ const fetchedGuilds = /* @__PURE__ */ new Set();
680
+ for (const [key, value] of Object.entries(configEmojis)) if (isEmojiTuple(value)) await this.resolveTuple(key, value, failures, fetchedGuilds);
681
+ else if (typeof value === "string") this.resolveString(key, value, failures);
682
+ else failures.push(` - "${key}" has an invalid value (expected a name or [name, guildId])`);
683
+ if (failures.length > 0) throw new SeedcordError(SeedcordErrorCode.ConfigEmojiUnresolved, [failures.length, failures.join("\n")]);
684
+ this.logger.utils.summary("Loaded emojis", { emojis: Object.keys(emojiStorage).length });
685
+ }
686
+ async resolveTuple(key, value, failures, fetchedGuilds) {
687
+ const [emojiName, guildId] = value;
688
+ const guild = this.core.bot.client.guilds.cache.get(guildId);
689
+ if (!guild) {
690
+ failures.push(` - "${emojiName}" for "${key}" targets guild ${guildId}, which is not available (check the Guilds intent)`);
691
+ return;
692
+ }
693
+ if (!fetchedGuilds.has(guildId)) {
694
+ await guild.emojis.fetch();
695
+ fetchedGuilds.add(guildId);
696
+ }
697
+ const guildEmoji = guild.emojis.cache.find((e) => e.name === emojiName);
698
+ if (!guildEmoji) {
699
+ failures.push(` - "${emojiName}" for "${key}" was not found in guild ${guildId}`);
700
+ return;
701
+ }
702
+ emojiStorage[key] = guildEmoji;
703
+ }
704
+ resolveString(key, emojiName, failures) {
705
+ const appEmoji = this.core.bot.client.application?.emojis.cache.find((e) => e.name === emojiName);
706
+ if (!appEmoji) {
707
+ failures.push(` - "${emojiName}" for "${key}" was not found among the application emojis`);
708
+ return;
709
+ }
710
+ emojiStorage[key] = appEmoji;
711
+ }
712
+ clearEmojis() {
713
+ for (const key of Object.keys(emojiStorage)) Reflect.deleteProperty(emojiStorage, key);
714
+ }
715
+ };
716
+
717
+ //#endregion
718
+ //#region src/bot/injectors/CommandMentionInjector.ts
719
+ const mentionStorage = {};
720
+ /**
721
+ * Ready-to-send command mention strings, keyed by {@link SlashOptionRegistry}.
722
+ *
723
+ * A value is a clickable `</name:id>` when the command's id resolved from the deploy, otherwise the plain
724
+ * `/name` text. Populated by {@link CommandMentionInjector} after each deploy.
725
+ */
726
+ const CommandMentions = mentionStorage;
727
+ const MULTI_GUILD = Symbol("seedcord:commandmentions:multi-guild");
728
+ /**
729
+ * Turns each deployed slash route into a clickable command mention exposed through {@link CommandMentions}.
730
+ *
731
+ * Consumes the ids {@link DeployResult} carries, so it runs after a deploy rather than resolving from a name
732
+ * cache (discord.js offers none for command ids). A global command is clickable everywhere by its app-wide id.
733
+ * A guild command deployed to one guild is clickable by that guild's id. A command deployed to two or more
734
+ * guilds mints a different id per guild, so one accessor key cannot resolve it, and it falls back to plain
735
+ * `/name` text with one warn. On a non-owning shard a guild command also falls back to plain text.
736
+ *
737
+ * @internal
738
+ */
739
+ var CommandMentionInjector = class {
740
+ core;
741
+ logger = new Logger("CommandMentions");
742
+ constructor(core) {
743
+ this.core = core;
744
+ }
745
+ inject(deploy) {
746
+ this.clear();
747
+ const globalIds = this.indexByName(deploy.global);
748
+ const guildIds = this.indexGuilds(deploy.guilds);
749
+ const warned = /* @__PURE__ */ new Set();
750
+ let clickable = 0;
751
+ for (const command of this.allSlashBuilders()) {
752
+ const id = this.resolveId(command.name, globalIds, guildIds, warned);
753
+ for (const leaf of routeLeavesOf(command.toJSON())) {
754
+ mentionStorage[leaf.route] = id ? this.toMention(leaf.route, id) : this.toPlain(leaf.route);
755
+ if (id) clickable++;
756
+ }
757
+ }
758
+ this.logger.utils.summary("Linked mentions", {
759
+ clickable,
760
+ plain: Object.keys(mentionStorage).length - clickable
761
+ });
762
+ }
763
+ allSlashBuilders() {
764
+ const registry = this.core.bot.commands;
765
+ if (!registry) return [];
766
+ const slash = [...registry.globalCommands, ...registry.guildCommands.values()].flat().filter((command) => command instanceof SlashCommandBuilder);
767
+ return [...new Set(slash)];
768
+ }
769
+ indexByName(collection) {
770
+ const map = /* @__PURE__ */ new Map();
771
+ for (const command of collection.values()) map.set(command.name, command.id);
772
+ return map;
773
+ }
774
+ indexGuilds(guilds) {
775
+ const map = /* @__PURE__ */ new Map();
776
+ for (const collection of guilds.values()) for (const command of collection.values()) {
777
+ const existing = map.get(command.name);
778
+ if (existing === void 0) map.set(command.name, command.id);
779
+ else if (existing !== command.id) map.set(command.name, MULTI_GUILD);
780
+ }
781
+ return map;
782
+ }
783
+ resolveId(name, globalIds, guildIds, warned) {
784
+ const global = globalIds.get(name);
785
+ if (global) return global;
786
+ const guild = guildIds.get(name);
787
+ if (guild === void 0) return void 0;
788
+ if (guild === MULTI_GUILD) {
789
+ if (!warned.has(name)) {
790
+ this.logger.warn(`${name} is deployed to multiple guilds, falling back to plain text (not clickable).`);
791
+ warned.add(name);
792
+ }
793
+ return;
794
+ }
795
+ return guild;
796
+ }
797
+ toMention(route, id) {
798
+ const [name, middle, sub] = route.split("/");
799
+ if (name && middle && sub) return chatInputApplicationCommandMention(name, middle, sub, id);
800
+ if (name && middle) return chatInputApplicationCommandMention(name, middle, id);
801
+ return chatInputApplicationCommandMention(name ?? route, id);
802
+ }
803
+ toPlain(route) {
804
+ return `/${route.replaceAll("/", " ")}`;
805
+ }
806
+ clear() {
807
+ for (const key of Object.keys(mentionStorage)) Reflect.deleteProperty(mentionStorage, key);
808
+ }
809
+ };
810
+
811
+ //#endregion
812
+ //#region src/bot/utilities/channels/fetchText.ts
813
+ /**
814
+ * Fetches and validates a text channel. Refuses when the channel doesn't exist or isn't a text channel.
815
+ *
816
+ * @param client - The Discord client instance
817
+ * @param channelId - Channel ID or TextChannel instance
818
+ * @returns Promise resolving to the text channel
819
+ */
820
+ async function fetchText(client, channelId) {
821
+ if (channelId instanceof TextChannel) return channelId;
822
+ let channel = client.channels.cache.get(channelId);
823
+ if (!channel) try {
824
+ channel = await client.channels.fetch(channelId);
825
+ } catch (err) {
826
+ if (err instanceof DiscordAPIError && err.code === RESTJSONErrorCodes.UnknownChannel) throw new CouldNotFindChannel("Channel not found or not a text channel", channelId);
827
+ throw err;
828
+ }
829
+ if (channel?.isTextBased()) return channel;
830
+ throw new CouldNotFindChannel("Channel not found or not a text channel", channelId);
831
+ }
832
+
833
+ //#endregion
834
+ //#region src/bot/utilities/permissions/checkBotPermissions.ts
835
+ /**
836
+ * Checks if the bot has required permissions in a {@link Guild} or {@link TextChannel}. Refuses when a
837
+ * required permission is missing.
838
+ *
839
+ * @param target - Guild or text channel to check in
840
+ * @param scope - Permission bits to validate
841
+ * @param inverse - Whether to check for absence of the given permissions
842
+ * @param errors - Optional custom error constructors
843
+ *
844
+ * @example
845
+ * ```ts
846
+ * import { PermissionFlagsBits } from 'discord.js';
847
+ * import { checkBotPermissions } from '@seedcord/gateway';
848
+ *
849
+ * // Check if the bot has SendMessages and ViewChannel permissions in a text channel
850
+ * checkBotPermissions(textChannel, [
851
+ * PermissionFlagsBits.SendMessages,
852
+ * PermissionFlagsBits.ViewChannel
853
+ * ]);
854
+ * ```
855
+ */
856
+ function checkBotPermissions(target, scope, inverse = false, errors) {
857
+ if (target instanceof Guild) {
858
+ const me = target.members.me;
859
+ if (!me) {
860
+ const names = scope.map((bit) => PermissionNames.get(bit) ?? String(bit));
861
+ throw new ((errors?.missing) ?? MissingPermissions)("Missing Permissions", target, names);
862
+ }
863
+ checkPermissions(me, target, scope, inverse, errors);
864
+ return;
865
+ }
866
+ const me = target.guild.members.me;
867
+ if (!me) {
868
+ new Logger("checkBotPermissions").warn(`Bot member is unavailable in guild ${target.guild.id} while checking permissions in channel ${target.id}`);
869
+ const names = scope.map((bit) => PermissionNames.get(bit) ?? String(bit));
870
+ throw new ((errors?.missing) ?? MissingPermissions)("Missing Permissions", target, names);
871
+ }
872
+ checkPermissions(me, target, scope, inverse, errors);
873
+ }
874
+
875
+ //#endregion
876
+ //#region src/bot/utilities/roles/getBotRole.ts
877
+ /**
878
+ * Gets the bot's managed role in a guild.
879
+ *
880
+ * @param guild - The guild to get the bot role from
881
+ * @returns The bot's managed role in the guild
882
+ * @throws A **SeedcordError** if the client user is unavailable or if the bot role is missing
883
+ */
884
+ function getBotRole(guild) {
885
+ const botRole = guild.roles.botRoleFor(guild.client.user);
886
+ if (!botRole) throw new SeedcordError(SeedcordErrorCode.CoreBotRoleMissing, [guild.id]);
887
+ return botRole;
888
+ }
889
+
890
+ //#endregion
891
+ //#region src/bot/utilities/permissions/hasPermsToAssign.ts
892
+ /**
893
+ * Validates if the bot can assign a target role. Refuses when the target role is above the bot's, is managed, or the bot lacks Manage Roles.
894
+ *
895
+ * @param roleOrOptions - Target role or complete options for the check
896
+ *
897
+ * @example
898
+ * ```ts
899
+ * import { hasPermsToAssign } from '@seedcord/gateway';
900
+ *
901
+ * // Check if the bot can assign a specific role
902
+ * hasPermsToAssign(role);
903
+ *
904
+ * // Check with custom error handling
905
+ * hasPermsToAssign({
906
+ * targetRole: role,
907
+ * errors: {
908
+ * higher: CustomHigherError,
909
+ * managed: CustomManagedError,
910
+ * missing: CustomMissingPermissionsError
911
+ * }
912
+ * });
913
+ * ```
914
+ */
915
+ function hasPermsToAssign(roleOrOptions) {
916
+ const { targetRole, errors } = roleOrOptions instanceof Role ? {
917
+ targetRole: roleOrOptions,
918
+ errors: void 0
919
+ } : roleOrOptions;
920
+ const HigherErr = errors?.higher ?? RoleHigherThanMe;
921
+ const ManagedErr = errors?.managed ?? CannotAssignBotRole;
922
+ const Missing = errors?.missing ?? MissingPermissions;
923
+ const botRole = getBotRole(targetRole.guild);
924
+ if (targetRole.comparePositionTo(botRole) >= 0) throw new HigherErr("Role is higher than me", targetRole, botRole);
925
+ if (targetRole.managed) throw new ManagedErr(`Cannot assign managed role ${targetRole.name}`);
926
+ checkBotPermissions(targetRole.guild, [PermissionFlagsBits.ManageRoles], false, { missing: Missing });
927
+ }
928
+
929
+ //#endregion
930
+ //#region src/bot/utilities/roles/fetchRole.ts
931
+ function isUnknownRole(err) {
932
+ return err instanceof DiscordAPIError && err.code === RESTJSONErrorCodes.UnknownRole;
933
+ }
934
+ async function fetchRoleInGuild(guild, roleId) {
935
+ const cached = guild.roles.cache.get(roleId);
936
+ if (cached) return cached;
937
+ try {
938
+ return await guild.roles.fetch(roleId);
939
+ } catch (err) {
940
+ if (isUnknownRole(err)) throw new RoleDoesNotExist("Role not found in specified guild", roleId);
941
+ throw err;
942
+ }
943
+ }
944
+ async function scanGuildsForRole(client, roleId) {
945
+ const cached = client.guilds.cache.map((guild) => guild.roles.cache.get(roleId)).find(Boolean);
946
+ if (cached) return cached;
947
+ for (const guild of client.guilds.cache.values()) try {
948
+ const role = await guild.roles.fetch(roleId);
949
+ if (role) return role;
950
+ } catch (err) {
951
+ if (isUnknownRole(err)) continue;
952
+ throw err;
953
+ }
954
+ return null;
955
+ }
956
+ /**
957
+ * Fetches a role by ID from a client or guild. Refuses when the role doesn't exist.
958
+ *
959
+ * @param clientOrGuild - Discord client or guild instance
960
+ * @param roleId - The role ID to fetch
961
+ * @returns Promise resolving to the role
962
+ */
963
+ async function fetchRole(clientOrGuild, roleId) {
964
+ if (!roleId) throw new RoleDoesNotExist("Role ID is null or undefined", roleId);
965
+ const role = clientOrGuild instanceof Guild ? await fetchRoleInGuild(clientOrGuild, roleId) : await scanGuildsForRole(clientOrGuild, roleId);
966
+ if (!role) throw new RoleDoesNotExist("Role not found", roleId);
967
+ return role;
968
+ }
969
+
970
+ //#endregion
971
+ //#region src/bot/utilities/users/fetchGuildMember.ts
972
+ /**
973
+ * Fetches a guild member by user ID. Refuses when the user is not in the guild.
974
+ *
975
+ * @param guild - The guild to fetch the member from
976
+ * @param userId - The Discord user ID
977
+ * @returns Promise resolving to the guild member
978
+ */
979
+ async function fetchGuildMember(guild, userId) {
980
+ let user = guild.members.cache.get(userId);
981
+ user ??= await guild.members.fetch(userId).catch((err) => {
982
+ if (err instanceof DiscordAPIError && err.code === RESTJSONErrorCodes.UnknownMember) throw new UserNotInGuild(`User with ID ${userId} not found in guild`);
983
+ throw err;
984
+ });
985
+ return user;
986
+ }
987
+
988
+ //#endregion
989
+ //#region src/bot/utilities/users/fetchManyGuildMembers.ts
990
+ /**
991
+ * Fetches multiple guild members by user IDs.
992
+ *
993
+ * @param guild - The guild to fetch members from
994
+ * @param userIds - Array of Discord user IDs
995
+ * @returns Promise resolving to array of successfully fetched members
996
+ */
997
+ async function fetchManyGuildMembers(guild, userIds) {
998
+ return (await Promise.allSettled(userIds.map((userId) => fetchGuildMember(guild, userId)))).filter((result) => result.status === "fulfilled").map((result) => result.value);
999
+ }
1000
+
1001
+ //#endregion
1002
+ //#region src/bot/utilities/users/fetchUser.ts
1003
+ /**
1004
+ * Fetches a Discord user by ID. Refuses when the user doesn't exist, with `options.throwAs` or the default.
1005
+ *
1006
+ * @param client - The Discord client instance
1007
+ * @param userId - The Discord user ID
1008
+ * @param options - Optional overrides, including the {@link FetchUserOptions.throwAs} notice
1009
+ * @returns Promise resolving to the user
1010
+ */
1011
+ async function fetchUser(client, userId, options) {
1012
+ const Throw = options?.throwAs ?? UserNotFound;
1013
+ let user = client.users.cache.get(userId);
1014
+ user ??= await client.users.fetch(userId).catch((err) => {
1015
+ if (err instanceof DiscordAPIError && err.code === RESTJSONErrorCodes.UnknownUser) throw new Throw(userId);
1016
+ throw err;
1017
+ });
1018
+ return user;
1019
+ }
1020
+
1021
+ //#endregion
1022
+ //#region src/bot/utilities/users/fetchManyUsers.ts
1023
+ /**
1024
+ * Fetches multiple Discord users by IDs.
1025
+ *
1026
+ * @param client - The Discord client instance
1027
+ * @param userIds - Array of Discord user IDs
1028
+ * @param options - Optional overrides threaded to each {@link fetchUser} call
1029
+ * @returns Promise resolving to array of successfully fetched users
1030
+ */
1031
+ async function fetchManyUsers(client, userIds, options) {
1032
+ return (await Promise.allSettled(userIds.map((userId) => fetchUser(client, userId, options)))).filter((result) => result.status === "fulfilled").map((result) => result.value);
1033
+ }
1034
+
1035
+ //#endregion
1036
+ //#region src/bot/utilities/users/updateMemberRoles.ts
1037
+ /**
1038
+ * Updates a guild member's roles by adding and removing specified roles.
1039
+ *
1040
+ * @param rolesToAdd - Array of role IDs to add to the member
1041
+ * @param rolesToRemove - Array of role IDs to remove from the member
1042
+ * @param member - The guild member to update
1043
+ * @returns Promise that resolves when roles are updated
1044
+ */
1045
+ async function updateMemberRoles(rolesToAdd, rolesToRemove, member) {
1046
+ const current = new Set(member.roles.cache.map((r) => r.id));
1047
+ const toAdd = new Set(rolesToAdd);
1048
+ const toRemove = new Set(rolesToRemove);
1049
+ const updated = current.union(toAdd).difference(toRemove);
1050
+ await member.roles.set([...updated]);
1051
+ }
1052
+
1053
+ //#endregion
1054
+ //#region src/bot/harmlessApiCodes.ts
1055
+ /**
1056
+ * Discord API error codes that mean a dead end on an interaction, a dead token, a double ack, or a gone
1057
+ * message. There is nothing to show the user and no bug to report. The controller boundary drops them on
1058
+ * the original throw, and {@link ReplySender} drops them on its own send.
1059
+ *
1060
+ * @internal
1061
+ */
1062
+ const HARMLESS_API_CODES = new Set([
1063
+ RESTJSONErrorCodes.UnknownInteraction,
1064
+ RESTJSONErrorCodes.InteractionHasAlreadyBeenAcknowledged,
1065
+ RESTJSONErrorCodes.UnknownMessage
1066
+ ]);
1067
+
1068
+ //#endregion
1069
+ //#region src/miscellaneous/flagsFor.ts
1070
+ /**
1071
+ * Builds the `flags` bitfield for a framework reply. Every framework reply is ComponentsV2, so the
1072
+ * IsComponentsV2 flag is always set.
1073
+ *
1074
+ * @param ephemeral - Whether the reply is ephemeral.
1075
+ * @returns The OR'd `MessageFlags` value as a plain number.
1076
+ *
1077
+ * @internal
1078
+ */
1079
+ function flagsFor(ephemeral) {
1080
+ let flags = MessageFlags.IsComponentsV2;
1081
+ if (ephemeral) flags |= MessageFlags.Ephemeral;
1082
+ return flags;
1083
+ }
1084
+
1085
+ //#endregion
1086
+ //#region src/bot/ReplySender.ts
1087
+ /**
1088
+ * Sends a {@link ReplyResponse} to an interaction, picking reply, editReply, or followUp from the live
1089
+ * acknowledgement state. Logs and drops its own send failures so a dead token never escapes into the
1090
+ * controller.
1091
+ */
1092
+ var ReplySender = class {
1093
+ interaction;
1094
+ logger = new Logger("ReplySender");
1095
+ constructor(interaction) {
1096
+ this.interaction = interaction;
1097
+ }
1098
+ /**
1099
+ * Sends the reply and returns the sent message so a caller can attach a collector to it. Never throws,
1100
+ * a failed send is logged and dropped and resolves to `undefined`.
1101
+ *
1102
+ * @param response - The ComponentsV2 reply to show.
1103
+ * @param ephemeral - Whether the reply is ephemeral. {@default `true`}
1104
+ * @returns The sent {@link Message}, or `undefined` when the send was swallowed.
1105
+ */
1106
+ async send(response, ephemeral = true) {
1107
+ try {
1108
+ return await this.dispatch(response, ephemeral);
1109
+ } catch (error) {
1110
+ this.logSwallowed("send", error);
1111
+ return;
1112
+ }
1113
+ }
1114
+ /**
1115
+ * Edits an already-sent message to a new {@link ReplyResponse}. Used to swap a confirmation prompt for
1116
+ * its outcome. Never throws, a failed edit is logged and dropped.
1117
+ *
1118
+ * @param message - The message to edit (the handle a prior {@link send} returned).
1119
+ * @param response - The reply to replace it with.
1120
+ */
1121
+ async edit(message, response) {
1122
+ try {
1123
+ await this.interaction.webhook.editMessage(message, this.editBody(response));
1124
+ } catch (error) {
1125
+ this.logSwallowed("edit", error);
1126
+ }
1127
+ }
1128
+ async dispatch(response, ephemeral) {
1129
+ if (this.interaction.replied) return await this.interaction.followUp(this.replyOptions(response, ephemeral));
1130
+ if (this.interaction.deferred) {
1131
+ if (this.interaction.ephemeral === null) return await this.interaction.followUp(this.replyOptions(response, ephemeral));
1132
+ return await this.interaction.editReply(this.editBody(response));
1133
+ }
1134
+ await this.interaction.reply(this.replyOptions(response, ephemeral));
1135
+ return await this.interaction.fetchReply();
1136
+ }
1137
+ replyOptions(response, ephemeral) {
1138
+ return {
1139
+ components: response.components,
1140
+ flags: flagsFor(ephemeral),
1141
+ ...response.allowedMentions && { allowedMentions: response.allowedMentions },
1142
+ ...response.files && { files: response.files }
1143
+ };
1144
+ }
1145
+ editBody(response) {
1146
+ return {
1147
+ components: response.components,
1148
+ flags: MessageFlags.IsComponentsV2,
1149
+ ...response.allowedMentions && { allowedMentions: response.allowedMentions },
1150
+ ...response.files && { files: response.files }
1151
+ };
1152
+ }
1153
+ logSwallowed(action, error) {
1154
+ if (error instanceof DiscordAPIError && HARMLESS_API_CODES.has(error.code)) {
1155
+ this.logger.debug(`reply ${action} hit harmless code ${error.code}`);
1156
+ return;
1157
+ }
1158
+ this.logger.error(`reply ${action} failed`, error);
1159
+ }
1160
+ };
1161
+
1162
+ //#endregion
1163
+ //#region src/bot/confirm/reserved.ts
1164
+ const RESERVED_CONFIRM_PREFIX = "__seedcord_confirm";
1165
+ /**
1166
+ * The reserved confirm/cancel codec. It has no route, so the dispatcher ignores its clicks and only the
1167
+ * in-process collector reads them. Do not mint a real component from it.
1168
+ *
1169
+ * @internal
1170
+ */
1171
+ const CONFIRM_DEF = new CustomId(RESERVED_CONFIRM_PREFIX).oneOf("choice", ["confirm", "cancel"]);
1172
+
1173
+ //#endregion
1174
+ //#region src/bot/confirm/getConfirmation.ts
1175
+ const DEFAULT_TIMEOUT_MS = 3e4;
1176
+ const CONFIRM_IDS = {
1177
+ confirm: CONFIRM_DEF.encode({ choice: "confirm" }),
1178
+ cancel: CONFIRM_DEF.encode({ choice: "cancel" })
1179
+ };
1180
+ var ConfirmButtons = class extends RowComponent {
1181
+ constructor(options) {
1182
+ super("button");
1183
+ this.instance.addComponents(new ButtonBuilder().setCustomId(CONFIRM_IDS.confirm).setLabel(options?.confirmLabel ?? "Confirm").setStyle(options?.confirmStyle ?? ButtonStyle.Danger), new ButtonBuilder().setCustomId(CONFIRM_IDS.cancel).setLabel(options?.cancelLabel ?? "Cancel").setStyle(ButtonStyle.Secondary));
1184
+ }
1185
+ };
1186
+ var ConfirmPromptCard = class extends BuilderComponent {
1187
+ constructor(text, options) {
1188
+ super("container");
1189
+ this.instance.addTextDisplayComponents(new TextDisplayBuilder().setContent(text)).addActionRowComponents(new ConfirmButtons(options).component);
1190
+ }
1191
+ };
1192
+ function defaultPrompt(text, options) {
1193
+ return { components: [new ConfirmPromptCard(text, options).component] };
1194
+ }
1195
+ async function collectChoice(message, userId, timeoutMs) {
1196
+ try {
1197
+ return await message.awaitMessageComponent({
1198
+ componentType: ComponentType.Button,
1199
+ time: timeoutMs,
1200
+ filter: (click) => click.user.id === userId && CONFIRM_DEF.owns(click.customId)
1201
+ });
1202
+ } catch {
1203
+ return null;
1204
+ }
1205
+ }
1206
+ async function settle(sender, interaction, message, outcome) {
1207
+ if (outcome === void 0) {
1208
+ await interaction.deleteReply(message).catch(() => void 0);
1209
+ return;
1210
+ }
1211
+ await sender.edit(message, typeof outcome === "function" ? await outcome() : outcome);
1212
+ }
1213
+ async function getConfirmation(interaction, prompt, options) {
1214
+ const { ephemeral = true, timeoutMs = DEFAULT_TIMEOUT_MS } = options ?? {};
1215
+ const response = typeof prompt === "string" ? defaultPrompt(prompt, options) : await prompt(CONFIRM_IDS);
1216
+ const sender = new ReplySender(interaction);
1217
+ const message = await sender.send(response, ephemeral);
1218
+ if (!message) return false;
1219
+ const winner = await collectChoice(message, interaction.user.id, timeoutMs);
1220
+ if (!winner) {
1221
+ await settle(sender, interaction, message, options?.onTimeout);
1222
+ return false;
1223
+ }
1224
+ await winner.deferUpdate().catch(() => void 0);
1225
+ const confirmed = winner.customId === CONFIRM_IDS.confirm;
1226
+ await settle(sender, interaction, message, confirmed ? options?.onConfirm : options?.onCancel);
1227
+ return confirmed;
1228
+ }
1229
+
1230
+ //#endregion
1231
+ //#region src/hmr/devChannel.ts
1232
+ let channel;
1233
+ function setDevChannel(next) {
1234
+ channel = next;
1235
+ }
1236
+ function getDevChannel() {
1237
+ return channel;
1238
+ }
1239
+
1240
+ //#endregion
1241
+ //#region src/interfaces/Plugin.ts
1242
+ /**
1243
+ * Base class for Seedcord plugins
1244
+ *
1245
+ * Extend this class to create plugins that integrate with the Seedcord lifecycle.
1246
+ * Plugins have access to the core instance and must implement initialization logic.
1247
+ */
1248
+ var Plugin = class extends StrictEventEmitter {
1249
+ pluggable;
1250
+ name = this.constructor.name;
1251
+ constructor(pluggable) {
1252
+ super();
1253
+ this.pluggable = pluggable;
1254
+ }
1255
+ /**
1256
+ * Reloads plugin state on an HMR update. The base implementation is a no-op, override it in your plugin.
1257
+ * @virtual
1258
+ */
1259
+ onHmr(_event) {
1260
+ return Promise.resolve();
1261
+ }
1262
+ /**
1263
+ * Registers critical file patterns that should trigger a full restart when changed in Dev HMR.
1264
+ * @param patterns - Glob patterns relative to the project root
1265
+ */
1266
+ registerCriticalFiles(patterns) {
1267
+ getDevChannel()?.send("seedcord:register-critical-files", { patterns });
1268
+ }
1269
+ /** @internal */
1270
+ setMaxListeners(n) {
1271
+ return super.setMaxListeners(n);
1272
+ }
1273
+ /** @internal */
1274
+ removeListener(event, listener) {
1275
+ return super.removeListener(event, listener);
1276
+ }
1277
+ /** @internal */
1278
+ removeAllListeners(eventName) {
1279
+ return super.removeAllListeners(eventName);
1280
+ }
1281
+ };
1282
+ /**
1283
+ * Base class for objects that can have plugins attached.
1284
+ *
1285
+ * Provides plugin attachment capabilities and lifecycle management. Plugins are attached during
1286
+ * configuration and initialized during startup. Not constructed directly, the host is a {@link Seedcord}.
1287
+ */
1288
+ var Pluggable = class Pluggable extends StrictEventEmitter {
1289
+ isInitialized = false;
1290
+ shutdown;
1291
+ startup;
1292
+ plugins = [];
1293
+ static PLUGIN_INIT_TIMEOUT_MS = 15e3;
1294
+ constructor(shutdown, startup) {
1295
+ super();
1296
+ this.shutdown = shutdown;
1297
+ this.startup = startup;
1298
+ }
1299
+ /** @internal */
1300
+ async init() {
1301
+ if (this.isInitialized) return this;
1302
+ await this.startup.run();
1303
+ this.isInitialized = true;
1304
+ return this;
1305
+ }
1306
+ /**
1307
+ * Attaches a plugin to this instance
1308
+ *
1309
+ * Plugins provide external functionality and are initialized during the specified startup phase.
1310
+ * The plugin instance becomes available as a property in `core` wherever it's available.
1311
+ *
1312
+ * Make sure to augment the {@link Core} interface with the plugin type to ensure TypeScript recognizes it and provides intellisense.
1313
+ *
1314
+ * @typeParam Key - The property name for accessing the plugin
1315
+ * @typeParam Ctor - The plugin constructor type
1316
+ * @param key - Property name to access the plugin instance
1317
+ * @param Plugin - Plugin constructor class
1318
+ * @param startupPhase - When during startup to initialize this plugin ({@link StartupPhase})
1319
+ * @param args - Additional arguments to pass to the plugin constructor
1320
+ * @returns This instance with the plugin attached as a typed property
1321
+ * @throws A **SeedcordError** When called after initialization or if key already exists
1322
+ * @example
1323
+ * ```typescript
1324
+ * seedcord.attach('db', Mongo, StartupPhase.Configuration, { uri: 'mongodb://...', name: 'seedcord', dir: ... })
1325
+ * ```
1326
+ */
1327
+ attach(key, Plugin, startupPhase, ...args) {
1328
+ if (this.isInitialized) throw new SeedcordError(SeedcordErrorCode.CorePluginAfterInit);
1329
+ if (key in this) throw new SeedcordError(SeedcordErrorCode.CorePluginKeyExists, [key]);
1330
+ const instance = new Plugin(this, ...args);
1331
+ this.plugins.push(instance);
1332
+ const entry = { [key]: instance };
1333
+ this.startup.addTask(startupPhase, `Plugin:${key}`, async () => {
1334
+ instance.logger.utils.initialization(key, "start");
1335
+ await instance.init();
1336
+ instance.logger.utils.initialization(key, "end");
1337
+ }, Pluggable.PLUGIN_INIT_TIMEOUT_MS);
1338
+ return Object.assign(this, entry);
1339
+ }
1340
+ /** @internal */
1341
+ setMaxListeners(n) {
1342
+ return super.setMaxListeners(n);
1343
+ }
1344
+ /** @internal */
1345
+ removeListener(event, listener) {
1346
+ return super.removeListener(event, listener);
1347
+ }
1348
+ /** @internal */
1349
+ removeAllListeners(eventName) {
1350
+ return super.removeAllListeners(eventName);
1351
+ }
1352
+ };
1353
+
1354
+ //#endregion
1355
+ //#region src/handlers/BaseHandler.ts
1356
+ /**
1357
+ * Base class for a Discord event or interaction handler. Don't register handlers directly, use the more specific handler subclasses.
1358
+ */
1359
+ var BaseHandler = class {
1360
+ core;
1361
+ event;
1362
+ logger;
1363
+ constructor(event, core) {
1364
+ this.core = core;
1365
+ this.event = event;
1366
+ this.logger = new Logger(this.constructor.name);
1367
+ }
1368
+ /** @internal */
1369
+ getEvent() {
1370
+ return this.event;
1371
+ }
1372
+ };
1373
+
1374
+ //#endregion
1375
+ //#region src/handlers/interaction/InteractionMiddleware.ts
1376
+ /**
1377
+ * Base class for interaction middleware
1378
+ *
1379
+ * Middleware runs before interaction handlers and can modify behavior or block execution.
1380
+ * Unlike handlers, middleware should not send responses directly.
1381
+ *
1382
+ * @typeParam Repliable - The interaction type this middleware processes
1383
+ */
1384
+ var InteractionMiddleware = class extends BaseHandler {
1385
+ constructor(event, core) {
1386
+ super(event, core);
1387
+ }
1388
+ };
1389
+
1390
+ //#endregion
1391
+ //#region src/handlers/interaction/InteractionHandler.ts
1392
+ /**
1393
+ * Shared base the typed interaction handlers extend.
1394
+ *
1395
+ * Not a public entry point. You should be using {@link SlashHandler}, {@link ButtonHandler}, {@link ModalHandler},
1396
+ * or {@link SelectMenuHandler} instead. This class only carries the repliable-event plumbing those bases share,
1397
+ * so DO NOT use it directly.
1398
+ *
1399
+ * @typeParam Repliable - The interaction type this handler processes
1400
+ */
1401
+ var InteractionHandler = class extends BaseHandler {
1402
+ constructor(event, core) {
1403
+ super(event, core);
1404
+ }
1405
+ };
1406
+
1407
+ //#endregion
1408
+ //#region src/bot/utilities/miscellaneous/slashRouteOf.ts
1409
+ /**
1410
+ * Computes the dispatch route for a chat-input or autocomplete interaction. The controller and
1411
+ * `seedcord codegen` both assemble route keys through the same {@link buildSlashRoute}, so a dispatched
1412
+ * interaction and a generated registry key always match.
1413
+ *
1414
+ * @internal
1415
+ */
1416
+ function slashRouteOf(interaction) {
1417
+ const group = interaction.options.getSubcommandGroup(false) ?? void 0;
1418
+ const subcommand = interaction.options.getSubcommand(false) ?? void 0;
1419
+ return buildSlashRoute(interaction.commandName, subcommand, group);
1420
+ }
1421
+
1422
+ //#endregion
1423
+ //#region src/handlers/interaction/SlashHandler.ts
1424
+ /**
1425
+ * Base class for a chat-input (slash) command handler.
1426
+ *
1427
+ * Pass the route from the generated registry as the generic, the same string as `@SlashRoute`, then read
1428
+ * `this.options` for a single command or `this.match` for several. Command authoring stays plain
1429
+ * discord.js, `seedcord codegen` reads its `toJSON()` to type these options.
1430
+ *
1431
+ * @typeParam Route - One or more route keys from {@link SlashOptionRegistry}, e.g. `'ban'` or `'ban' | 'kick'`.
1432
+ * @typeParam Cache - The interaction cache state, `'cached'` by default.
1433
+ *
1434
+ * @example
1435
+ * ```ts
1436
+ * \@SlashRoute('ban')
1437
+ * class BanHandler extends SlashHandler<'ban'> {
1438
+ * async execute() {
1439
+ * const target = this.options.getUser('target'); // User
1440
+ * const reason = this.options.getString('reason'); // string | null
1441
+ * }
1442
+ * }
1443
+ * ```
1444
+ */
1445
+ var SlashHandler = class extends InteractionHandler {
1446
+ /**
1447
+ * The typed options for this command's route. Required options drop the null, choices narrow to their
1448
+ * literal union, and only the getters for kinds this command actually uses appear. Use `this.event.options`
1449
+ * directly for anything outside this view, such as narrowing a channel option by type.
1450
+ */
1451
+ get options() {
1452
+ return this.event.options;
1453
+ }
1454
+ /**
1455
+ * Run the arm for whichever command fired. Use this only when the handler is registered for several
1456
+ * routes. A single-route handler reads `this.options` directly instead, match buys nothing there.
1457
+ *
1458
+ * Provide one arm per registered route, keyed by its route string, and each arm receives that route's
1459
+ * own narrowed options. The arms must cover every route in the generic, a missing route or an unknown
1460
+ * key is a compile error.
1461
+ *
1462
+ * @param arms - One handler per registered route, keyed by route string.
1463
+ * @returns The result of the arm that ran.
1464
+ *
1465
+ * @example
1466
+ * ```ts
1467
+ * \@SlashRoute('ban', 'kick')
1468
+ * class ModHandler extends SlashHandler<'ban' | 'kick'> {
1469
+ * async execute() {
1470
+ * await this.match({
1471
+ * ban: (options) => this.event.guild?.members.ban(options.getUser('target', true).id),
1472
+ * kick: (options) => this.event.guild?.members.kick(options.getUser('member', true).id)
1473
+ * });
1474
+ * }
1475
+ * }
1476
+ * ```
1477
+ */
1478
+ async match(arms) {
1479
+ const route = slashRouteOf(this.event);
1480
+ const arm = arms[route];
1481
+ if (!arm) throw new SeedcordError(SeedcordErrorCode.SlashMatchArmMissing, [route]);
1482
+ return await arm(this.options);
1483
+ }
1484
+ };
1485
+
1486
+ //#endregion
1487
+ //#region src/handlers/interaction/ContextMenuHandler.ts
1488
+ /**
1489
+ * Base class for a context-menu command handler (right-click a user or a message).
1490
+ *
1491
+ * Pass the kind from `discord.js`'s {@link ApplicationCommandType} as the generic, the same value as
1492
+ * `@ContextMenuRoute`. Read the right-clicked entity from `this.target`, a `User` for a user menu and a
1493
+ * `Message` for a message menu. Context menus carry no options, so a handler registered for several names
1494
+ * reads `this.target` uniformly with no per-name branch.
1495
+ *
1496
+ * @typeParam Kind - `ApplicationCommandType.User` or `ApplicationCommandType.Message`.
1497
+ * @typeParam Cache - The interaction cache state, `'cached'` by default.
1498
+ *
1499
+ * @example
1500
+ * ```ts
1501
+ * \@ContextMenuRoute(ApplicationCommandType.Message, 'Report Message')
1502
+ * class ReportMessage extends ContextMenuHandler<ApplicationCommandType.Message> {
1503
+ * async execute() {
1504
+ * const message = this.target;
1505
+ * }
1506
+ * }
1507
+ * ```
1508
+ */
1509
+ var ContextMenuHandler = class extends InteractionHandler {
1510
+ get target() {
1511
+ const event = this.event;
1512
+ return "targetUser" in event ? event.targetUser : event.targetMessage;
1513
+ }
1514
+ /**
1515
+ * The invoking guild member, resolved only on user menus. Reading it on a message menu is a compile
1516
+ * error since the type is `never` there.
1517
+ */
1518
+ get targetMember() {
1519
+ return this.event.targetMember;
1520
+ }
1521
+ };
1522
+
1523
+ //#endregion
1524
+ //#region src/handlers/interaction/AutocompleteHandler.ts
1525
+ /**
1526
+ * Base class for a Discord autocomplete handler.
1527
+ *
1528
+ * Pass the command route(s) from the generated registry as the generic, the same string(s) as
1529
+ * `@AutocompleteRoute`. Branch on the focused field with `this.match`, read already-entered sibling options
1530
+ * with `this.options`, and find which command fired with `this.route`.
1531
+ *
1532
+ * @typeParam Route - One or more route keys from {@link SlashOptionRegistry}, e.g. `'search'` or `'search' | 'find'`.
1533
+ * @typeParam Cache - The interaction cache state, `'cached'` by default.
1534
+ *
1535
+ * @example
1536
+ * ```ts
1537
+ * \@AutocompleteRoute('search')
1538
+ * class SearchAutocomplete extends AutocompleteHandler<'search'> {
1539
+ * async execute() {
1540
+ * await this.match({
1541
+ * query: (value, respond) => respond([{ name: value, value }])
1542
+ * });
1543
+ * }
1544
+ * }
1545
+ * ```
1546
+ */
1547
+ var AutocompleteHandler = class extends BaseHandler {
1548
+ constructor(event, core) {
1549
+ super(event, core);
1550
+ }
1551
+ /**
1552
+ * The focused option for this interaction. `value` is always the raw partial string the user is typing,
1553
+ * even for an integer or number option, so coerce it yourself when you need a number.
1554
+ */
1555
+ decodedFocused;
1556
+ get focused() {
1557
+ if (this.decodedFocused) return this.decodedFocused;
1558
+ const raw = this.event.options.getFocused(true);
1559
+ const focused = {
1560
+ name: raw.name,
1561
+ value: raw.value
1562
+ };
1563
+ this.decodedFocused = focused;
1564
+ return focused;
1565
+ }
1566
+ /**
1567
+ * Run the arm for the focused field. An autocomplete always dispatches by which field is focused, so
1568
+ * match is how you read it. There is no single-field shortcut the way slash/component handlers have one.
1569
+ *
1570
+ * Provide one arm per autocompletable field across the registered commands, keyed by field name. Each
1571
+ * arm receives the focused partial value and a `respond` pinned to that field's choice value type. The
1572
+ * arms must cover every autocompletable field, a missing field or an unknown key is a compile error. A
1573
+ * focused field with no arm, only reachable from a stale-deployed command, throws at runtime.
1574
+ *
1575
+ * @param arms - One handler per autocompletable field, keyed by field name.
1576
+ * @returns The result of the arm that ran.
1577
+ *
1578
+ * @example
1579
+ * ```ts
1580
+ * \@AutocompleteRoute('search')
1581
+ * class SearchAutocomplete extends AutocompleteHandler<'search'> {
1582
+ * async execute() {
1583
+ * await this.match({
1584
+ * query: (value, respond) => respond(titles(value).map((s) => ({ name: s, value: s }))),
1585
+ * tag: (value, respond) => respond(tags(value).map((s) => ({ name: s, value: s })))
1586
+ * });
1587
+ * }
1588
+ * }
1589
+ * ```
1590
+ */
1591
+ async match(arms) {
1592
+ const { name, value } = this.focused;
1593
+ const respond = (choices) => this.event.respond(choices);
1594
+ const arm = arms[name];
1595
+ if (!arm) throw new SeedcordError(SeedcordErrorCode.AutocompleteMatchArmMissing, [name]);
1596
+ return await arm(value, respond);
1597
+ }
1598
+ /** The firing command route, for a field whose completion differs per registered command. */
1599
+ get route() {
1600
+ return slashRouteOf(this.event);
1601
+ }
1602
+ /**
1603
+ * The already-entered options on this command, restricted to the kinds Discord resolves during autocomplete
1604
+ * (string, integer, number, boolean) with every read nullable, since a sibling is partial while the user
1605
+ * types the focused field. Read the focused field from `this.focused`, not here.
1606
+ */
1607
+ get options() {
1608
+ return this.event.options;
1609
+ }
1610
+ };
1611
+
1612
+ //#endregion
1613
+ //#region src/handlers/interaction/components/ComponentHandler.ts
1614
+ /**
1615
+ * Shared base the customId-routed component handlers extend.
1616
+ *
1617
+ * Not a public entry point. You should be using {@link ButtonHandler}, {@link SelectMenuHandler}, or
1618
+ * {@link ModalHandler} instead. This class only carries the customId decode and route-matching plumbing
1619
+ * those bases share, so DO NOT use it directly.
1620
+ *
1621
+ * @typeParam Event - The component interaction type this handler processes
1622
+ * @typeParam Defs - The customId route definitions registered on the concrete handler
1623
+ */
1624
+ var ComponentHandler = class extends InteractionHandler {
1625
+ get registeredDefs() {
1626
+ const defs = Reflect.getMetadata(ComponentDefsKey, this.constructor);
1627
+ if (!defs) throw new SeedcordError(SeedcordErrorCode.CustomIdHandlerRouteMissing, [this.constructor.name]);
1628
+ return defs;
1629
+ }
1630
+ decoded;
1631
+ get route() {
1632
+ if (this.decoded) return this.decoded;
1633
+ const decoded = decodeFor(this.registeredDefs, this.event.customId);
1634
+ this.decoded = decoded;
1635
+ return decoded;
1636
+ }
1637
+ /**
1638
+ * The decoded params of the single route this handler is registered for.
1639
+ *
1640
+ * Reading this decodes `this.event.customId` once (cached after the first read) and throws
1641
+ * `StaleCustomId` or `InvalidCustomId` when the wire no longer matches the current shape, which the
1642
+ * controller boundary turns into a reply. On a handler registered for several routes this is
1643
+ * `never`, so use {@link match} instead.
1644
+ */
1645
+ get params() {
1646
+ return this.route.params;
1647
+ }
1648
+ /**
1649
+ * Run the arm for whichever route the component was minted from. Use this only when the handler is
1650
+ * registered for several routes. A single-route handler reads `this.params` directly. On a multi-route
1651
+ * handler `this.params` is `never`, so match is the only way to read the decoded params.
1652
+ *
1653
+ * Provide one arm per registered route, keyed by its prefix, and each arm receives that route's own
1654
+ * decoded params. The arms must cover every registered def, a missing prefix or an unknown key is a
1655
+ * compile error. Decoding runs before any arm, so a stale or corrupt wire throws before an arm body executes.
1656
+ *
1657
+ * @param arms - One handler per registered route, keyed by prefix.
1658
+ * @returns The result of the arm that ran.
1659
+ *
1660
+ * @example
1661
+ * ```ts
1662
+ * \@ButtonRoute(Approve, Reject)
1663
+ * class ReviewButtons extends ButtonHandler<[typeof Approve, typeof Reject]> {
1664
+ * async execute() {
1665
+ * await this.match({
1666
+ * approve: ({ userId }) => this.event.reply(`approved <@${userId}>`),
1667
+ * reject: ({ userId }) => this.event.reply(`rejected <@${userId}>`)
1668
+ * });
1669
+ * }
1670
+ * }
1671
+ * ```
1672
+ */
1673
+ async match(arms) {
1674
+ const { prefix, params } = this.route;
1675
+ const arm = arms[prefix];
1676
+ if (!arm) throw new SeedcordError(SeedcordErrorCode.CustomIdMatchArmMissing, [prefix]);
1677
+ return await arm(params);
1678
+ }
1679
+ };
1680
+
1681
+ //#endregion
1682
+ //#region src/handlers/interaction/components/ButtonHandler.ts
1683
+ /**
1684
+ * Base class for a button interaction handler.
1685
+ *
1686
+ * Register the customId definitions this handler decodes with `@ButtonRoute`, list the same ones in the
1687
+ * generic, then read `this.params` for a single route or `this.match` for several. Passing different
1688
+ * definitions to the decorator and the generic is a compile error.
1689
+ *
1690
+ * @typeParam Defs - The customId definitions this handler decodes, e.g. `[typeof ApproveId]`.
1691
+ * @typeParam Cache - The interaction cache state, `'cached'` by default.
1692
+ *
1693
+ * @example
1694
+ * ```ts
1695
+ * \@ButtonRoute(ApproveId)
1696
+ * class ApproveButton extends ButtonHandler<[typeof ApproveId]> {
1697
+ * async execute() {
1698
+ * const { userId } = this.params;
1699
+ * await this.event.reply(`approved <@${userId}>`);
1700
+ * }
1701
+ * }
1702
+ * ```
1703
+ */
1704
+ var ButtonHandler = class extends ComponentHandler {};
1705
+
1706
+ //#endregion
1707
+ //#region src/handlers/interaction/components/ModalHandler.ts
1708
+ /**
1709
+ * Base class for a modal submit handler.
1710
+ *
1711
+ * Register the customId definitions this handler decodes with `@ModalRoute`, list the same ones in the
1712
+ * generic, then read `this.params` for a single route or `this.match` for several. Read the submitted
1713
+ * inputs from `this.event.fields`.
1714
+ *
1715
+ * @typeParam Defs - The customId definitions this handler decodes, e.g. `[typeof ConfigId]`.
1716
+ * @typeParam Cache - The interaction cache state, `'cached'` by default.
1717
+ *
1718
+ * @example
1719
+ * ```ts
1720
+ * \@ModalRoute(ConfigId)
1721
+ * class ConfigModal extends ModalHandler<[typeof ConfigId]> {
1722
+ * async execute() {
1723
+ * const { guildId } = this.params;
1724
+ * const name = this.event.fields.getTextInputValue('name');
1725
+ * await this.event.reply(`saved ${name} for ${guildId}`);
1726
+ * }
1727
+ * }
1728
+ * ```
1729
+ */
1730
+ var ModalHandler = class extends ComponentHandler {};
1731
+
1732
+ //#endregion
1733
+ //#region src/handlers/interaction/components/SelectMenuHandler.ts
1734
+ /**
1735
+ * Base class for a select menu handler.
1736
+ *
1737
+ * Pass the select kind first and the customId definitions second, the same order as `@SelectMenuRoute`,
1738
+ * so `this.event` and `this.event.values` are narrowed to that kind. Read `this.params` for a single
1739
+ * route or `this.match` for several.
1740
+ *
1741
+ * @typeParam Kind - The select kind from {@link SelectMenuKind}, e.g. `SelectMenuKind.User`.
1742
+ * @typeParam Defs - The customId definitions this handler decodes, e.g. `[typeof AssignId]`.
1743
+ * @typeParam Cache - The interaction cache state, `'cached'` by default.
1744
+ *
1745
+ * @example
1746
+ * ```ts
1747
+ * \@SelectMenuRoute(SelectMenuKind.User, AssignId)
1748
+ * class AssignSelect extends SelectMenuHandler<SelectMenuKind.User, [typeof AssignId]> {
1749
+ * async execute() {
1750
+ * const { roleId } = this.params;
1751
+ * await this.event.reply(`assigning ${this.event.values.length} member(s) to <@&${roleId}>`);
1752
+ * }
1753
+ * }
1754
+ * ```
1755
+ */
1756
+ var SelectMenuHandler = class extends ComponentHandler {};
1757
+
1758
+ //#endregion
1759
+ //#region src/handlers/event/EventHandler.ts
1760
+ /**
1761
+ * Base class for a Discord client event handler.
1762
+ *
1763
+ * Pass the event name(s) as the generic, the same one(s) as `@RegisterEvent`. A single-event handler reads
1764
+ * `this.event` (the payload tuple) directly. A handler registered for several events branches with `this.match`,
1765
+ * keyed by event name, since the union of payload tuples is not directly readable.
1766
+ *
1767
+ * @typeParam Names - One or more `ClientEvents` keys, e.g. `Events.MessageCreate` or `Events.MessageCreate | Events.MessageUpdate`.
1768
+ *
1769
+ * @example
1770
+ * ```ts
1771
+ * \@RegisterEvent([Events.MessageCreate], [Events.MessageUpdate])
1772
+ * class PingPong extends EventHandler<Events.MessageCreate | Events.MessageUpdate> {
1773
+ * async execute() {
1774
+ * await this.match({
1775
+ * [Events.MessageCreate]: (message) => message.reply('pong'),
1776
+ * [Events.MessageUpdate]: (_oldMessage, edited) => edited.reply('pong')
1777
+ * });
1778
+ * }
1779
+ * }
1780
+ * ```
1781
+ */
1782
+ var EventHandler = class extends BaseHandler {
1783
+ firedEvent;
1784
+ constructor(event, core, eventName) {
1785
+ super(event, core);
1786
+ this.firedEvent = eventName;
1787
+ }
1788
+ /**
1789
+ * Run the arm for whichever event fired. Use this only when the handler is registered for several
1790
+ * events. A single-event handler reads `this.event` directly. On a multi-event handler `this.event` is
1791
+ * `never`, so match is the only way to read the payload.
1792
+ *
1793
+ * Provide one arm per registered event, keyed by its name, and each arm receives that event's own
1794
+ * payload tuple. The arms must cover every event in the generic, a missing event or an unknown key is a
1795
+ * compile error.
1796
+ *
1797
+ * @param arms - One handler per registered event, keyed by event name.
1798
+ * @returns The result of the arm that ran.
1799
+ *
1800
+ * @example
1801
+ * ```ts
1802
+ * \@RegisterEvent([Events.MessageCreate], [Events.MessageUpdate])
1803
+ * class MessageWatcher extends EventHandler<Events.MessageCreate | Events.MessageUpdate> {
1804
+ * async execute() {
1805
+ * await this.match({
1806
+ * [Events.MessageCreate]: (message) => this.scan(message),
1807
+ * [Events.MessageUpdate]: (_old, updated) => this.scan(updated)
1808
+ * });
1809
+ * }
1810
+ * }
1811
+ * ```
1812
+ */
1813
+ async match(arms) {
1814
+ const name = this.firedEvent;
1815
+ if (name === void 0) throw new SeedcordError(SeedcordErrorCode.EventMatchArmMissing, ["<no event>"]);
1816
+ const arm = arms[name];
1817
+ if (typeof arm !== "function") throw new SeedcordError(SeedcordErrorCode.EventMatchArmMissing, [name]);
1818
+ return await arm(...this.getEvent());
1819
+ }
1820
+ };
1821
+
1822
+ //#endregion
1823
+ //#region src/handlers/event/EventMiddleware.ts
1824
+ /**
1825
+ * Base class for Discord event middleware.
1826
+ *
1827
+ * Middleware runs before event handlers and can stop the event by throwing a `Silence`. Unlike `EventHandler`, it
1828
+ * runs the SAME for every event it is registered for, so it has no `match`. Specify a single event in the
1829
+ * generic and `{ events }` to read `this.event` fully typed. Span several events (or omit `{ events }` for a
1830
+ * catchall) and `this.event` narrows to `never`, read `this.eventName` and do work that does not depend on the
1831
+ * payload shape. A middleware that needs each event's payload is written one event per class.
1832
+ *
1833
+ * @typeParam EventName - One or more `ClientEvents` keys. Defaults to every event (catchall).
1834
+ */
1835
+ var EventMiddleware = class extends BaseHandler {
1836
+ firedEvent;
1837
+ constructor(event, core, eventName) {
1838
+ super(event, core);
1839
+ this.firedEvent = eventName;
1840
+ }
1841
+ /**
1842
+ * The event that fired this middleware. Read it on a catchall or multi-event middleware, where `this.event`
1843
+ * is `never`, to do work that does not depend on the payload shape. A single-event middleware reads
1844
+ * `this.event` directly and does not need this.
1845
+ */
1846
+ get eventName() {
1847
+ if (this.firedEvent === void 0) throw new SeedcordError(SeedcordErrorCode.EventMiddlewareNameUnavailable);
1848
+ return this.firedEvent;
1849
+ }
1850
+ };
1851
+
1852
+ //#endregion
1853
+ //#region src/pagination/controls.ts
1854
+ const DEFAULT_LABEL = {
1855
+ first: "First",
1856
+ prev: "Prev",
1857
+ indicator: "",
1858
+ next: "Next",
1859
+ last: "Last"
1860
+ };
1861
+ const CONTROL_SLOT = {
1862
+ first: 0,
1863
+ prev: 1,
1864
+ indicator: 2,
1865
+ next: 3,
1866
+ last: 4
1867
+ };
1868
+ const MAX_BUTTONS_PER_ROW = 5;
1869
+ var Controls = class {
1870
+ cursor;
1871
+ view;
1872
+ constructor(cursor, view) {
1873
+ this.cursor = cursor;
1874
+ this.view = view;
1875
+ }
1876
+ button(key, cosmetics) {
1877
+ const { target, disabled } = this.navState(key);
1878
+ const defaultLabel = key === "indicator" ? this.indicatorText() : DEFAULT_LABEL[key];
1879
+ const label = cosmetics?.label ?? (key === "indicator" || !cosmetics?.emoji ? defaultLabel : void 0);
1880
+ const button = new ButtonBuilder().setCustomId(this.cursor.encode({
1881
+ page: Math.min(Math.max(0, target), PAGE_MAX),
1882
+ slot: CONTROL_SLOT[key]
1883
+ })).setStyle(cosmetics?.style ?? ButtonStyle.Secondary).setDisabled(disabled);
1884
+ if (label !== void 0) button.setLabel(label);
1885
+ if (cosmetics?.emoji) button.setEmoji(cosmetics.emoji);
1886
+ return button;
1887
+ }
1888
+ navState(key) {
1889
+ const { page, totalPages, hasPrev, hasNext } = this.view;
1890
+ const knownTotal = totalPages !== void 0;
1891
+ return {
1892
+ target: {
1893
+ first: 0,
1894
+ prev: page - 1,
1895
+ indicator: page,
1896
+ next: page + 1,
1897
+ last: knownTotal ? totalPages - 1 : page
1898
+ }[key],
1899
+ disabled: {
1900
+ first: !hasPrev,
1901
+ prev: !hasPrev,
1902
+ indicator: true,
1903
+ next: !hasNext || page + 1 > PAGE_MAX,
1904
+ last: !hasNext || !knownTotal || totalPages - 1 > PAGE_MAX
1905
+ }[key]
1906
+ };
1907
+ }
1908
+ row(...keys) {
1909
+ if (keys.length === 0) throw new SeedcordRangeError(SeedcordErrorCode.PaginationEmptyControls);
1910
+ if (keys.length > MAX_BUTTONS_PER_ROW) throw new SeedcordRangeError(SeedcordErrorCode.PaginationTooManyControls, [keys.length]);
1911
+ const seen = /* @__PURE__ */ new Set();
1912
+ for (const key of keys) {
1913
+ if (seen.has(key)) throw new SeedcordTypeError(SeedcordErrorCode.PaginationDuplicateControls, [key]);
1914
+ seen.add(key);
1915
+ }
1916
+ return new ActionRowBuilder().addComponents(keys.map((key) => this.button(key)));
1917
+ }
1918
+ indicatorText() {
1919
+ const { page, totalPages } = this.view;
1920
+ return totalPages === void 0 ? `Page ${page + 1}` : `Page ${page + 1} of ${totalPages}`;
1921
+ }
1922
+ };
1923
+
1924
+ //#endregion
1925
+ //#region src/pagination/render.ts
1926
+ var PageContainer = class extends BuilderComponent {
1927
+ constructor(view, renderItem, controlRow) {
1928
+ super("container");
1929
+ const base = view.page * view.perPage;
1930
+ let lines = [];
1931
+ const flush = () => {
1932
+ if (lines.length === 0) return;
1933
+ this.instance.addTextDisplayComponents(new TextDisplayBuilder().setContent(lines.join("\n")));
1934
+ lines = [];
1935
+ };
1936
+ view.items.forEach((item, offset) => {
1937
+ const rendered = renderItem(item, base + offset);
1938
+ if (typeof rendered === "string") {
1939
+ lines.push(rendered);
1940
+ return;
1941
+ }
1942
+ flush();
1943
+ this.instance.addSectionComponents(rendered.component);
1944
+ });
1945
+ flush();
1946
+ this.instance.addActionRowComponents(controlRow);
1947
+ }
1948
+ };
1949
+ function toReplyResponse(renderable) {
1950
+ if (typeof renderable === "string") return { components: [new TextDisplayBuilder().setContent(renderable)] };
1951
+ if (Array.isArray(renderable)) return { components: renderable };
1952
+ return renderable;
1953
+ }
1954
+ const ARRAY_KEYS = [
1955
+ "first",
1956
+ "prev",
1957
+ "indicator",
1958
+ "next",
1959
+ "last"
1960
+ ];
1961
+ const CURSOR_KEYS = [
1962
+ "prev",
1963
+ "indicator",
1964
+ "next"
1965
+ ];
1966
+ /**
1967
+ * Build a page's V2 reply. A `render` override builds the whole tree, otherwise the default container lists
1968
+ * the items and appends the controls (all five for a known total, prev/indicator/next for a cursor source).
1969
+ */
1970
+ function renderPage(view, cursor, config) {
1971
+ const controls = new Controls(cursor, view);
1972
+ if (config.render) return toReplyResponse(config.render(view, controls));
1973
+ return { components: [new PageContainer(view, config.renderItem ?? String, controls.row(...view.totalPages === void 0 ? CURSOR_KEYS : ARRAY_KEYS)).component] };
1974
+ }
1975
+
1976
+ //#endregion
1977
+ //#region src/pagination/Paginator.ts
1978
+ function contextOf(interaction, core) {
1979
+ return {
1980
+ interaction,
1981
+ user: interaction.user,
1982
+ guild: interaction.guild,
1983
+ ...core && { core }
1984
+ };
1985
+ }
1986
+ /**
1987
+ * A restart-proof paginator. Each nav button's customId encodes its full target page, so clicks are
1988
+ * idempotent and survive a restart. A persistent `@ButtonRoute` on `Handler` dispatches the clicks.
1989
+ *
1990
+ * @typeParam Item - The item type, inferred from the source.
1991
+ * @typeParam Prefix - The route prefix, inferred from `config.prefix`.
1992
+ *
1993
+ * @example
1994
+ * ```ts
1995
+ * export const Bans = new Paginator({
1996
+ * prefix: 'bans',
1997
+ * source: new ArraySource((ctx) => ctx.guild.bans.fetch().then((b) => [...b.values()]), { perPage: 10 }),
1998
+ * renderItem: (ban) => ban.user.tag
1999
+ * });
2000
+ *
2001
+ * \@ButtonRoute(Bans.cursor)
2002
+ * export class BansNav extends Bans.Handler {}
2003
+ * ```
2004
+ */
2005
+ var Paginator = class {
2006
+ /** The page cursor, pass it to your `@ButtonRoute`. */
2007
+ cursor;
2008
+ /** The nav handler base. Extend it with an empty body and decorate it, `@ButtonRoute(p.cursor)`. */
2009
+ Handler;
2010
+ config;
2011
+ constructor(config) {
2012
+ this.cursor = pageCursor(config.prefix);
2013
+ this.config = config;
2014
+ const loadPage = (ctx, n) => this.page(ctx, n);
2015
+ this.Handler = class Nav extends ButtonHandler {
2016
+ async execute() {
2017
+ await this.event.deferUpdate();
2018
+ const response = await loadPage(contextOf(this.event, this.core), this.params.page);
2019
+ await new ReplySender(this.event).edit(this.event.message, response);
2020
+ }
2021
+ };
2022
+ }
2023
+ /** Render page 0 and send it, picking reply or followUp from the interaction's state. */
2024
+ async start(interaction, core) {
2025
+ const response = await this.page(contextOf(interaction, core), 0);
2026
+ return new ReplySender(interaction).send(response, this.config.ephemeral ?? false);
2027
+ }
2028
+ /** Render a page as a {@link ReplyResponse}. To post it elsewhere, add `flags: MessageFlags.IsComponentsV2`. */
2029
+ async page(ctx, n) {
2030
+ return renderPage(await this.config.source.page(ctx, n), this.cursor, this.config);
2031
+ }
2032
+ };
2033
+
2034
+ //#endregion
2035
+ //#region src/pagination/sources.ts
2036
+ const DEFAULT_PER_PAGE = 10;
2037
+ /**
2038
+ * A source for a bounded list you can load whole. It loads the full list on every click, then slices the
2039
+ * page via {@link paginate}, so the real total is known (a real last button, "Page X of Y"). Cache inside
2040
+ * your loader if the load is expensive.
2041
+ *
2042
+ * @typeParam Item - The item type, inferred from the loader's return.
2043
+ */
2044
+ var ArraySource = class {
2045
+ load;
2046
+ perPage;
2047
+ constructor(load, opts) {
2048
+ this.load = load;
2049
+ this.perPage = opts?.perPage ?? DEFAULT_PER_PAGE;
2050
+ if (!Number.isSafeInteger(this.perPage) || this.perPage <= 0) throw new SeedcordRangeError(SeedcordErrorCode.PaginationInvalidPerPage, [this.perPage]);
2051
+ }
2052
+ async page(ctx, n) {
2053
+ return paginate(await this.load(ctx), n, this.perPage);
2054
+ }
2055
+ };
2056
+ /**
2057
+ * A source for a large or unknown-length set you fetch one page at a time (SQL LIMIT/OFFSET, a paged API).
2058
+ * The fetcher receives the page index and the page size and reports whether a next page exists. A cursor
2059
+ * source has no cheap total, so `totalPages` is undefined, the last button is omitted, and the indicator
2060
+ * reads "Page X".
2061
+ *
2062
+ * @typeParam Item - The item type, inferred from the fetcher's slice.
2063
+ */
2064
+ var CursorSource = class {
2065
+ fetch;
2066
+ perPage;
2067
+ constructor(fetch, opts) {
2068
+ this.fetch = fetch;
2069
+ this.perPage = opts?.perPage ?? DEFAULT_PER_PAGE;
2070
+ if (!Number.isSafeInteger(this.perPage) || this.perPage <= 0) throw new SeedcordRangeError(SeedcordErrorCode.PaginationInvalidPerPage, [this.perPage]);
2071
+ }
2072
+ async page(ctx, n) {
2073
+ const page = Math.max(0, Math.trunc(n));
2074
+ const { items, hasNext } = await this.fetch(ctx, page, this.perPage);
2075
+ return {
2076
+ items: [...items],
2077
+ page,
2078
+ perPage: this.perPage,
2079
+ hasPrev: page > 0,
2080
+ hasNext
2081
+ };
2082
+ }
2083
+ };
2084
+
2085
+ //#endregion
2086
+ //#region src/subscribers/Subscriber.ts
2087
+ /**
2088
+ * Abstract base class for handling application subscribers.
2089
+ *
2090
+ * Provides type-safe access to subscribers data and the core framework instance.
2091
+ * Extend this class to create custom subscriber handlers.
2092
+ *
2093
+ * @typeParam KeyOfSubscribers - The specific subscriber type this handler processes
2094
+ */
2095
+ var Subscriber = class {
2096
+ data;
2097
+ core;
2098
+ logger;
2099
+ /**
2100
+ * Instantiates the subscriber with event data and core.
2101
+ *
2102
+ * @param data - The subscriber event data
2103
+ * @param core - The core framework instance
2104
+ */
2105
+ constructor(data, core) {
2106
+ this.data = data;
2107
+ this.core = core;
2108
+ this.logger = new Logger(this.constructor.name);
2109
+ }
2110
+ };
2111
+
2112
+ //#endregion
2113
+ //#region src/subscribers/decorators/Subscribe.ts
2114
+ /**
2115
+ * Registers a subscriber handler class with a specific subscriber event.
2116
+ *
2117
+ * Associates the decorated class with a subscriber event type for automatic
2118
+ * registration and execution when the subscriber is emitted.
2119
+ *
2120
+ * @typeParam TSubscriber - The subscriber event name to register for
2121
+ * @param subscriber - The subscriber event name to register for
2122
+ * @param options - Options to configure the subscriber handler registration.
2123
+ * @decorator
2124
+ * @example
2125
+ * ```typescript
2126
+ * \@Subscribe('userJoin')
2127
+ * class WelcomeHandler extends Subscriber<'userJoin'> {
2128
+ * async execute() {
2129
+ * // Handle user join event
2130
+ * }
2131
+ * }
2132
+ * ```
2133
+ * @example
2134
+ * ```ts
2135
+ * \@Subscribe('userJoin', { frequency: 'once' })
2136
+ * // or
2137
+ * \@Subscribe('userJoin')
2138
+ * ```
2139
+ */
2140
+ function Subscribe(subscriber, options) {
2141
+ return function(constructor) {
2142
+ const meta = {
2143
+ subscriber,
2144
+ frequency: options?.frequency
2145
+ };
2146
+ Reflect.defineMetadata(SubscribeMetadataKey, meta, constructor);
2147
+ };
2148
+ }
2149
+
2150
+ //#endregion
2151
+ //#region src/subscribers/bases/WebhookLog.ts
2152
+ /**
2153
+ * Abstract webhook logging handler for subscriber events.
2154
+ *
2155
+ * Extends Subscriber to provide webhook-based logging capabilities.
2156
+ * Implementations must define the webhook client to send messages to by implementing the webhook property.
2157
+ *
2158
+ * @typeParam KeyOfSubscribers - The specific subscriber type this handler processes
2159
+ */
2160
+ var WebhookLog = class extends Subscriber {
2161
+ constructor(data, core) {
2162
+ super(data, core);
2163
+ }
2164
+ };
2165
+
2166
+ //#endregion
2167
+ //#region src/hmr/HmrModuleHandler.ts
2168
+ /**
2169
+ * Reloads THandler and optional TMiddleware modules on HMR updates.
2170
+ *
2171
+ * You can either implement a custom `onHmr()` method in your class by extending `HmrAware`, or if it's a plugin, override the existing `onHmr()` with fully custom logic. Or, use this class's `handle()` method inside your `onHmr()` to get standard HMR handling for your modules based on the provided options you give to the constructor.
2172
+ *
2173
+ * This is only useful during development.
2174
+ */
2175
+ var HmrModuleHandler = class {
2176
+ store;
2177
+ options;
2178
+ constructor(options) {
2179
+ this.options = {
2180
+ ...options,
2181
+ logger: options.logger.inChannel("hmr")
2182
+ };
2183
+ this.store = {
2184
+ fileToHandlers: /* @__PURE__ */ new Map(),
2185
+ fileToMiddlewares: /* @__PURE__ */ new Map(),
2186
+ handlerArtifacts: /* @__PURE__ */ new Map()
2187
+ };
2188
+ }
2189
+ /**
2190
+ * Handles an HMR update event by reloading affected modules based on the event details and config. It receives an {@link HmrUpdateEvent}, then checks the type of update.
2191
+ *
2192
+ * - If it's a deletion, it unloads the module.
2193
+ * - If it's an update/creation, it checks if the file is tracked, unloads it if so, then reloads the file if it is in the handlers or middlewares directory and is a valid handler/middleware.
2194
+ */
2195
+ async handle(event) {
2196
+ const { file, affectedModules, type } = event;
2197
+ const { logger, handlersDir, middlewaresDir } = this.options;
2198
+ if (type === "delete" || type === "deleteDir") {
2199
+ this.unload(file);
2200
+ return;
2201
+ }
2202
+ if (type === "update" && !existsSync(file)) {
2203
+ if (this.isTracked(file)) {
2204
+ logger.info(`Received update for non-existent file: ${formatFilePath(file)}, treating as delete`);
2205
+ this.unload(file);
2206
+ }
2207
+ return;
2208
+ }
2209
+ const rollbackEnabled = event.rollback ?? true;
2210
+ const filesToReload = affectedModules && affectedModules.length > 0 ? affectedModules : [file];
2211
+ const absHandlersDir = resolve(process.cwd(), handlersDir);
2212
+ const absMiddlewaresDir = middlewaresDir ? resolve(process.cwd(), middlewaresDir) : null;
2213
+ for (const fileToReload of filesToReload) {
2214
+ const isHandler = fileToReload.startsWith(absHandlersDir);
2215
+ const isMiddleware = absMiddlewaresDir ? fileToReload.startsWith(absMiddlewaresDir) : false;
2216
+ if (!isHandler && !isMiddleware) continue;
2217
+ await this.reloadWithRollback(fileToReload, rollbackEnabled);
2218
+ }
2219
+ }
2220
+ async reloadWithRollback(file, rollbackEnabled) {
2221
+ const { logger } = this.options;
2222
+ const snapshot = this.snapshotUnits(file);
2223
+ this.unload(file);
2224
+ if (await this.reloadFile(file)) return;
2225
+ this.unload(file);
2226
+ if (!rollbackEnabled) return;
2227
+ this.restoreUnits(file, snapshot);
2228
+ logger.warn(`${chalk.yellow.bold("Rolled back")} ${chalk.gray(formatFilePath(file))} to the last-good version`);
2229
+ }
2230
+ /**
2231
+ * Tracks a handler module as being loaded from a specific file.
2232
+ * @param file - The file path the handler was loaded from.
2233
+ * @param handler - The handler module instance.
2234
+ */
2235
+ trackHandler(file, handler) {
2236
+ let set = this.store.fileToHandlers.get(file);
2237
+ if (!set) {
2238
+ set = /* @__PURE__ */ new Set();
2239
+ this.store.fileToHandlers.set(file, set);
2240
+ }
2241
+ set.add(handler);
2242
+ if (this.options.getArtifacts) {
2243
+ const artifacts = this.options.getArtifacts(handler);
2244
+ this.store.handlerArtifacts.set(handler, artifacts);
2245
+ }
2246
+ }
2247
+ /**
2248
+ * Tracks a middleware module as being loaded from a specific file.
2249
+ * @param file - The file path the middleware was loaded from.
2250
+ * @param middleware - The middleware module instance.
2251
+ */
2252
+ trackMiddleware(file, middleware) {
2253
+ let set = this.store.fileToMiddlewares.get(file);
2254
+ if (!set) {
2255
+ set = /* @__PURE__ */ new Set();
2256
+ this.store.fileToMiddlewares.set(file, set);
2257
+ }
2258
+ set.add(middleware);
2259
+ }
2260
+ isTracked(file) {
2261
+ return this.store.fileToHandlers.has(file) || this.store.fileToMiddlewares.has(file);
2262
+ }
2263
+ unload(file) {
2264
+ const { logger } = this.options;
2265
+ const handlers = this.store.fileToHandlers.get(file);
2266
+ if (handlers) {
2267
+ for (const handler of handlers) {
2268
+ const artifacts = this.store.handlerArtifacts.get(handler);
2269
+ this.options.unregisterHandler(handler, artifacts);
2270
+ this.store.handlerArtifacts.delete(handler);
2271
+ const name = handler.name ?? "Handler";
2272
+ logger.info(`${chalk.red.bold("Unloaded")} ${chalk.cyan.bold(name)} from ${chalk.gray(formatFilePath(file))}`);
2273
+ }
2274
+ this.store.fileToHandlers.delete(file);
2275
+ }
2276
+ const middlewares = this.store.fileToMiddlewares.get(file);
2277
+ if (middlewares) {
2278
+ for (const middleware of middlewares) {
2279
+ this.options.unregisterMiddleware?.(middleware);
2280
+ const name = middleware.name ?? "Middleware";
2281
+ logger.info(`${chalk.red.bold("Unloaded")} ${chalk.cyan.bold(name)} from ${chalk.gray(formatFilePath(file))}`);
2282
+ }
2283
+ this.store.fileToMiddlewares.delete(file);
2284
+ }
2285
+ }
2286
+ async reloadFile(file) {
2287
+ const { logger, isHandler, isMiddleware, registerHandler, registerMiddleware } = this.options;
2288
+ if (!existsSync(file)) {
2289
+ logger.info(`File does not exist, skipping reload: ${formatFilePath(file)}`);
2290
+ return false;
2291
+ }
2292
+ try {
2293
+ let fileUrl = pathToFileURL(file).href;
2294
+ if (process.env.VITEST === "true") fileUrl += `?update=${Date.now()}`;
2295
+ const imported = await import(fileUrl);
2296
+ for (const val of Object.values(imported)) if (isHandler(val)) {
2297
+ registerHandler(val, file);
2298
+ this.trackHandler(file, val);
2299
+ const name = val.name ?? "Handler";
2300
+ logger.info(`${chalk.blue.bold("Reloaded")} ${chalk.cyan.bold(name)} from ${chalk.gray(formatFilePath(file))}`);
2301
+ } else if (isMiddleware && registerMiddleware && isMiddleware(val)) {
2302
+ registerMiddleware(val, file);
2303
+ this.trackMiddleware(file, val);
2304
+ const name = val.name ?? "Middleware";
2305
+ logger.info(`${chalk.blue.bold("Reloaded")} ${chalk.cyan.bold(name)} from ${chalk.gray(formatFilePath(file))}`);
2306
+ }
2307
+ return true;
2308
+ } catch (error) {
2309
+ logger.error(`Failed to reload file: ${file}`, error);
2310
+ return false;
2311
+ }
2312
+ }
2313
+ snapshotUnits(file) {
2314
+ return {
2315
+ handlers: [...this.store.fileToHandlers.get(file) ?? []],
2316
+ middlewares: [...this.store.fileToMiddlewares.get(file) ?? []]
2317
+ };
2318
+ }
2319
+ restoreUnits(file, snapshot) {
2320
+ for (const handler of snapshot.handlers) {
2321
+ this.options.registerHandler(handler, file);
2322
+ this.trackHandler(file, handler);
2323
+ }
2324
+ if (this.options.registerMiddleware) for (const middleware of snapshot.middlewares) {
2325
+ this.options.registerMiddleware(middleware, file);
2326
+ this.trackMiddleware(file, middleware);
2327
+ }
2328
+ }
2329
+ };
2330
+
2331
+ //#endregion
2332
+ //#region src/bot/utilities/miscellaneous/contextMenuLeaves.ts
2333
+ /**
2334
+ * Collects the names of every registered context-menu command across a set of command builders, split into a
2335
+ * user set and a message set. The same builder may appear more than once (a guild command is pushed once per
2336
+ * guild), and slash commands carry no context-menu name, so both collapse here. The split mirrors the
2337
+ * controller's two name-keyed maps, so the boot guard checks each name against its own kind.
2338
+ *
2339
+ * @internal
2340
+ */
2341
+ function contextMenuLeaves(commands) {
2342
+ const user = /* @__PURE__ */ new Set();
2343
+ const message = /* @__PURE__ */ new Set();
2344
+ for (const command of commands) {
2345
+ if (!(command instanceof ContextMenuCommandBuilder)) continue;
2346
+ if (command.type === ApplicationCommandType.User) user.add(command.name);
2347
+ else message.add(command.name);
2348
+ }
2349
+ return {
2350
+ user,
2351
+ message
2352
+ };
2353
+ }
2354
+
2355
+ //#endregion
2356
+ //#region src/bot/utilities/miscellaneous/slashRouteLeaves.ts
2357
+ /**
2358
+ * Collects the route keys of every executable slash leaf across a set of command builders, deduplicated. The
2359
+ * same builder may appear more than once (a guild command is pushed once per guild), and context-menu
2360
+ * commands carry no slash route, so both collapse here. Route keys come from the same {@link routeLeavesOf}
2361
+ * that `seedcord codegen` reads, so the boot-time check compares against the generated registry's keys.
2362
+ *
2363
+ * @internal
2364
+ */
2365
+ function slashRouteLeaves(commands) {
2366
+ const leaves = /* @__PURE__ */ new Set();
2367
+ for (const command of commands) {
2368
+ if (!(command instanceof SlashCommandBuilder)) continue;
2369
+ for (const leaf of routeLeavesOf(command.toJSON())) leaves.add(leaf.route);
2370
+ }
2371
+ return leaves;
2372
+ }
2373
+
2374
+ //#endregion
2375
+ //#region src/bot/controllers/CommandRegistry.ts
2376
+ /**
2377
+ * Manages Discord application command registration and deployment.
2378
+ *
2379
+ * Scans command directories, builds command structures, and registers both global and guild-scoped commands
2380
+ * to Discord's API. Accessed via `core.bot.commands`. Do not construct it directly.
2381
+ */
2382
+ var CommandRegistry = class {
2383
+ core;
2384
+ onDeployed;
2385
+ name = "Commands";
2386
+ logger = new Logger("Commands");
2387
+ isInitialised = false;
2388
+ globalCommands = [];
2389
+ guildCommands = new Collection();
2390
+ ctorToCommand = /* @__PURE__ */ new Map();
2391
+ hmrHandler;
2392
+ pendingEvents = /* @__PURE__ */ new Map();
2393
+ constructor(core, onDeployed) {
2394
+ this.core = core;
2395
+ this.onDeployed = onDeployed;
2396
+ const commandsDir = this.core.config.bot.commands.path;
2397
+ if (!commandsDir) throw new SeedcordError(SeedcordErrorCode.CoreControllerPathMissing, ["CommandRegistry", "commands"]);
2398
+ if (!Envapter.isDevelopment && !Envapter.isTest) return;
2399
+ this.hmrHandler = new HmrModuleHandler({
2400
+ handlersDir: commandsDir,
2401
+ isHandler: this.isCommandClass.bind(this),
2402
+ registerHandler: this.registerCommand.bind(this),
2403
+ unregisterHandler: this.unregisterCommand.bind(this),
2404
+ getArtifacts: this.getArtifacts.bind(this),
2405
+ logger: this.logger
2406
+ });
2407
+ }
2408
+ getArtifacts(ctor) {
2409
+ return this.ctorToCommand.get(ctor);
2410
+ }
2411
+ /** @internal */
2412
+ async init() {
2413
+ if (this.isInitialised) return;
2414
+ this.isInitialised = true;
2415
+ const commandsDir = this.core.config.bot.commands.path;
2416
+ if (!commandsDir) return;
2417
+ this.logger.info(chalk.bold(commandsDir));
2418
+ await this.loadCommands(commandsDir);
2419
+ this.logger.utils.summary("Loaded commands", {
2420
+ global: this.globalCommands.length,
2421
+ "guild groups": this.guildCommands.size
2422
+ });
2423
+ getDevChannel()?.on("seedcord:refresh-commands", (data) => {
2424
+ this.refresh(data.shouldRefresh);
2425
+ });
2426
+ }
2427
+ /** @internal */
2428
+ async refresh(shouldRefresh = true) {
2429
+ if (!shouldRefresh) {
2430
+ this.logger.info(chalk.italic("Command refresh cancelled."));
2431
+ this.pendingEvents.clear();
2432
+ return;
2433
+ }
2434
+ this.logger.info(chalk.italic("Refreshing commands..."));
2435
+ for (const event of this.pendingEvents.values()) await this.hmrHandler?.handle(event);
2436
+ this.pendingEvents.clear();
2437
+ await this.setCommands();
2438
+ }
2439
+ /** @internal */
2440
+ async onHmr(event) {
2441
+ const commandsDir = this.core.config.bot.commands.path;
2442
+ if (commandsDir && event.file.startsWith(resolve(process.cwd(), commandsDir))) {
2443
+ this.pendingEvents.delete(event.file);
2444
+ this.pendingEvents.set(event.file, event);
2445
+ getDevChannel()?.send("seedcord:commands-update-prompt", { files: [...this.pendingEvents.keys()].map((f) => formatFilePath(f)) });
2446
+ } else await this.hmrHandler?.handle(event);
2447
+ }
2448
+ async loadCommands(dir) {
2449
+ await traverseDirectory(dir, (fullPath, rel, mod) => {
2450
+ for (const exported of Object.values(mod)) if (this.isCommandClass(exported)) {
2451
+ this.registerCommand(exported, rel);
2452
+ this.hmrHandler?.trackHandler(fullPath, exported);
2453
+ }
2454
+ }, this.logger);
2455
+ }
2456
+ isCommandClass(obj) {
2457
+ if (typeof obj !== "function") return false;
2458
+ return obj.prototype instanceof BuilderComponent && Reflect.hasMetadata(CommandMetadataKey, obj);
2459
+ }
2460
+ registerCommand(ctor, rel) {
2461
+ const meta = Reflect.getMetadata(CommandMetadataKey, ctor);
2462
+ if (!meta) return;
2463
+ const comp = new ctor().component;
2464
+ const commandType = comp instanceof SlashCommandBuilder ? "slash command" : "context menu command";
2465
+ if (meta.scope === "global") {
2466
+ this.globalCommands.push(comp);
2467
+ this.logger.utils.registration(ctor.name, rel);
2468
+ this.logger.utils.item(`Global ${commandType}: ${chalk.bold.cyan(comp.name)}`);
2469
+ } else {
2470
+ for (const g of meta.guilds) {
2471
+ const arr = this.guildCommands.get(g) ?? [];
2472
+ arr.push(comp);
2473
+ this.guildCommands.set(g, arr);
2474
+ }
2475
+ this.logger.utils.registration(ctor.name, rel);
2476
+ this.logger.utils.item(`Guild ${commandType}: ${chalk.bold.cyan(comp.name)} for ${chalk.magenta.bold(meta.guilds.length)} guild(s)`);
2477
+ }
2478
+ this.ctorToCommand.set(ctor, {
2479
+ name: comp.name,
2480
+ scope: meta.scope,
2481
+ ...meta.scope === "guild" && { guilds: meta.guilds }
2482
+ });
2483
+ }
2484
+ unregisterCommand(ctor, artifacts) {
2485
+ const info = artifacts ?? this.ctorToCommand.get(ctor);
2486
+ if (!info) return;
2487
+ if (info.scope === "global") {
2488
+ const idx = this.globalCommands.findIndex((c) => c.name === info.name);
2489
+ if (idx !== -1) this.globalCommands.splice(idx, 1);
2490
+ } else for (const g of info.guilds ?? []) {
2491
+ const arr = this.guildCommands.get(g);
2492
+ if (arr) {
2493
+ const idx = arr.findIndex((c) => c.name === info.name);
2494
+ if (idx !== -1) arr.splice(idx, 1);
2495
+ }
2496
+ }
2497
+ this.ctorToCommand.delete(ctor);
2498
+ }
2499
+ /** @internal */
2500
+ async setCommands() {
2501
+ const result = {
2502
+ global: new Collection(),
2503
+ guilds: new Collection()
2504
+ };
2505
+ if (this.globalCommands.length > 0) {
2506
+ const deployed = await this.core.bot.client.application?.commands.set(this.globalCommands);
2507
+ if (deployed) result.global = deployed;
2508
+ const tag = this.globalCommands.length === 1 ? "command" : "commands";
2509
+ this.logger.utils.summary("Configured global", { [tag]: this.globalCommands.length });
2510
+ this.logger.utils.item(`${this.globalCommands.map((command) => chalk.bold.cyan(command.name)).join(", ")}`);
2511
+ }
2512
+ for (const [guildId, commands] of this.guildCommands.entries()) {
2513
+ const guild = this.core.bot.client.guilds.cache.get(guildId);
2514
+ if (!guild) {
2515
+ this.logger.warn(`Guild with ID ${guildId} not found, skipping command registration.`);
2516
+ continue;
2517
+ }
2518
+ const deployed = await guild.commands.set(commands);
2519
+ result.guilds.set(guildId, deployed);
2520
+ const tag = commands.length === 1 ? "command" : "commands";
2521
+ this.logger.utils.summary(`Configured commands for ${chalk.bold.yellow(guild.name)}`, { [tag]: commands.length });
2522
+ this.logger.utils.item(`${commands.map((command) => chalk.bold.cyan(command.name)).join(", ")}`);
2523
+ }
2524
+ this.onDeployed?.(result);
2525
+ return result;
2526
+ }
2527
+ /** The deduplicated slash route keys across every global and guild command. @internal */
2528
+ routeLeaves() {
2529
+ return slashRouteLeaves([...this.globalCommands, ...this.guildCommands.values()].flat());
2530
+ }
2531
+ /** The registered context-menu command names, split by kind, across every global and guild command. @internal */
2532
+ contextMenuLeaves() {
2533
+ return contextMenuLeaves([...this.globalCommands, ...this.guildCommands.values()].flat());
2534
+ }
2535
+ };
2536
+
2537
+ //#endregion
2538
+ //#region src/miscellaneous/deriveEventActor.ts
2539
+ function deriveEventActor(args) {
2540
+ const tuple = Array.isArray(args) ? args : [args];
2541
+ for (const arg of tuple) {
2542
+ if (arg instanceof Message) return {
2543
+ guild: arg.guild,
2544
+ member: arg.member,
2545
+ user: arg.author,
2546
+ channelId: arg.channelId
2547
+ };
2548
+ if (arg instanceof GuildMember) return {
2549
+ guild: arg.guild,
2550
+ member: arg,
2551
+ user: arg.user,
2552
+ channelId: null
2553
+ };
2554
+ if (arg instanceof User) return {
2555
+ guild: null,
2556
+ member: null,
2557
+ user: arg,
2558
+ channelId: null
2559
+ };
2560
+ }
2561
+ return {
2562
+ guild: null,
2563
+ member: null,
2564
+ user: null,
2565
+ channelId: null
2566
+ };
2567
+ }
2568
+
2569
+ //#endregion
2570
+ //#region src/bot/gates/runGates.ts
2571
+ function interactionGateContext(interaction, core) {
2572
+ const rawMember = interaction.member;
2573
+ const memberRoleIds = rawMember instanceof GuildMember ? [...rawMember.roles.cache.keys()].filter((id) => id !== interaction.guildId) : rawMember?.roles ?? [];
2574
+ return {
2575
+ kind: "interaction",
2576
+ interaction,
2577
+ core,
2578
+ user: interaction.user,
2579
+ guild: interaction.guild,
2580
+ member: rawMember instanceof GuildMember ? rawMember : null,
2581
+ userId: interaction.user.id,
2582
+ guildId: interaction.guildId,
2583
+ channelId: interaction.channelId,
2584
+ memberRoleIds,
2585
+ memberPermissions: interaction.memberPermissions?.bitfield ?? null
2586
+ };
2587
+ }
2588
+ function eventGateContext(eventName, args, core) {
2589
+ const actor = deriveEventActor(args);
2590
+ return {
2591
+ kind: "event",
2592
+ core,
2593
+ eventName,
2594
+ payload: args,
2595
+ user: actor.user,
2596
+ guild: actor.guild,
2597
+ member: actor.member,
2598
+ userId: actor.user?.id ?? null,
2599
+ guildId: actor.guild?.id ?? null,
2600
+ channelId: actor.channelId,
2601
+ memberRoleIds: actor.member ? [...actor.member.roles.cache.keys()].filter((id) => id !== actor.guild?.id) : [],
2602
+ memberPermissions: actor.member?.permissions.bitfield ?? null
2603
+ };
2604
+ }
2605
+
2606
+ //#endregion
2607
+ //#region src/miscellaneous/FaultThrottle.ts
2608
+ /**
2609
+ * Drops duplicate fault reports inside a fixed window so a recurring fault (a database outage on a
2610
+ * hot path) reports once per window instead of flooding the webhook. Keyed on a structural string, so
2611
+ * the map stays small, and a stale entry is evicted on the next read of its key.
2612
+ *
2613
+ * @internal
2614
+ */
2615
+ var FaultThrottle = class {
2616
+ windowMs;
2617
+ now;
2618
+ lastReportedAt = /* @__PURE__ */ new Map();
2619
+ constructor(windowMs = 6e4, now = () => Date.now()) {
2620
+ this.windowMs = windowMs;
2621
+ this.now = now;
2622
+ }
2623
+ /** Evicts the entry for this key if it has aged out, so the map never holds stale keys forever. */
2624
+ shouldReport(key) {
2625
+ const last = this.lastReportedAt.get(key);
2626
+ if (last === void 0) return true;
2627
+ if (this.now() - last < this.windowMs) return false;
2628
+ this.lastReportedAt.delete(key);
2629
+ return true;
2630
+ }
2631
+ markReported(key) {
2632
+ this.lastReportedAt.set(key, this.now());
2633
+ }
2634
+ clear() {
2635
+ this.lastReportedAt.clear();
2636
+ }
2637
+ };
2638
+
2639
+ //#endregion
2640
+ //#region src/miscellaneous/extractErrorResponse.ts
2641
+ const logger$2 = new Logger("ErrorsHandling");
2642
+ /**
2643
+ * The single throttle for every fault publish, so a recurring fault reports once per window across both
2644
+ * the interaction and event paths. Exported so tests reset it between cases.
2645
+ *
2646
+ * @internal
2647
+ */
2648
+ const faultThrottle = new FaultThrottle();
2649
+ /**
2650
+ * Processes an error into a user-facing reply and routes its report.
2651
+ *
2652
+ * A {@link Notice} always renders its own reply. A reporting denial (`report: true`) additionally
2653
+ * publishes `handledException` on the interaction path. A raw, non-denial throw publishes
2654
+ * `unknownException` and renders the configured `defaultError` (or a generic {@link Fault}). One uuid is
2655
+ * threaded into both the reply and the bus payload.
2656
+ *
2657
+ * @internal
2658
+ */
2659
+ function extractErrorResponse(error, core, origin) {
2660
+ const uuid = crypto.randomUUID();
2661
+ const developerUsername = core.config.notifications?.developerUsername;
2662
+ const ctx = developerUsername === void 0 ? { uuid } : {
2663
+ uuid,
2664
+ developerUsername
2665
+ };
2666
+ if (error instanceof Notice) {
2667
+ if (error.report) reportFault(error, core, origin, uuid);
2668
+ return {
2669
+ uuid,
2670
+ response: error.render(ctx)
2671
+ };
2672
+ }
2673
+ reportRawFault(error, core, origin, uuid);
2674
+ const override = core.config.errors?.defaultError;
2675
+ return {
2676
+ uuid,
2677
+ response: override ? new override(uuid).render(ctx) : new Fault().render(ctx)
2678
+ };
2679
+ }
2680
+ function withThrottle(origin, error, publish) {
2681
+ const key = faultKey(origin, error);
2682
+ if (!faultThrottle.shouldReport(key)) {
2683
+ logger$2.info(`throttled duplicate fault ${key}`);
2684
+ return;
2685
+ }
2686
+ publish();
2687
+ faultThrottle.markReported(key);
2688
+ }
2689
+ function reportFault(denial, core, origin, uuid) {
2690
+ withThrottle(origin, denial, () => {
2691
+ logger$2.error(`${denial.name}: ${uuid}`, denial);
2692
+ if (origin.interaction) core.bus.publish("handledException", {
2693
+ denial,
2694
+ uuid,
2695
+ source: buildInteractionSource(origin.interaction)
2696
+ });
2697
+ else if (origin.event) core.bus.publish("handledException", {
2698
+ denial,
2699
+ uuid,
2700
+ source: buildEventSource(origin.event, origin)
2701
+ });
2702
+ else core.bus.publish("unknownException", {
2703
+ uuid,
2704
+ error: denial,
2705
+ guild: origin.guild,
2706
+ user: origin.user,
2707
+ metadata: metadataFor(origin)
2708
+ });
2709
+ });
2710
+ }
2711
+ function reportRawFault(error, core, origin, uuid) {
2712
+ withThrottle(origin, error, () => {
2713
+ if (core.config.errors?.errorStack ?? false) logger$2.error(uuid, error);
2714
+ else logger$2.error(`${uuid} | ${error.message}`);
2715
+ core.bus.publish("unknownException", {
2716
+ uuid,
2717
+ error,
2718
+ guild: origin.guild,
2719
+ user: origin.user,
2720
+ metadata: metadataFor(origin)
2721
+ });
2722
+ });
2723
+ }
2724
+ function metadataFor(origin) {
2725
+ if (origin.event) return {
2726
+ eventName: origin.event.name,
2727
+ handler: origin.event.handler,
2728
+ args: origin.event.args
2729
+ };
2730
+ return origin.metadata;
2731
+ }
2732
+ function buildEventSource(event, origin) {
2733
+ return {
2734
+ kind: "event",
2735
+ eventName: event.name,
2736
+ handler: event.handler,
2737
+ userId: origin.user?.id ?? null,
2738
+ guildId: origin.guild?.id ?? null,
2739
+ channelId: event.channelId,
2740
+ raw: event.args
2741
+ };
2742
+ }
2743
+ function faultKey(origin, error) {
2744
+ const name = error instanceof Notice ? error.name : error instanceof DiscordAPIError ? String(error.code) : error.constructor.name;
2745
+ if (origin.event) return `${origin.event.name}:${origin.event.handler}:${name}`;
2746
+ if (origin.interaction) return `${interactionRoute(origin.interaction)}:${name}`;
2747
+ if (origin.route) return `autocomplete:${origin.route}:${name}`;
2748
+ return `autocomplete:${name}`;
2749
+ }
2750
+ function interactionRoute(interaction) {
2751
+ if (interaction.isChatInputCommand()) return slashRouteOf(interaction);
2752
+ if (interaction.isContextMenuCommand()) return interaction.commandName;
2753
+ if (interaction.isButton() || interaction.isAnySelectMenu() || interaction.isModalSubmit()) return prefixOf(interaction.customId) || interaction.customId;
2754
+ return "interaction";
2755
+ }
2756
+ function buildInteractionSource(interaction) {
2757
+ const command = interaction.isChatInputCommand() ? slashRouteOf(interaction) : interaction.isContextMenuCommand() ? interaction.commandName : null;
2758
+ const customId = interaction.isButton() || interaction.isAnySelectMenu() || interaction.isModalSubmit() ? interaction.customId : null;
2759
+ return {
2760
+ kind: "interaction",
2761
+ interactionKind: interactionKind(interaction),
2762
+ command,
2763
+ customId,
2764
+ userId: interaction.user.id,
2765
+ guildId: interaction.guildId,
2766
+ channelId: interaction.channelId,
2767
+ interactionId: interaction.id,
2768
+ raw: interaction
2769
+ };
2770
+ }
2771
+ function interactionKind(interaction) {
2772
+ if (interaction.isChatInputCommand()) return "slash";
2773
+ if (interaction.isContextMenuCommand()) return "context-menu";
2774
+ if (interaction.isButton()) return "button";
2775
+ if (interaction.isAnySelectMenu()) return "select";
2776
+ return "modal";
2777
+ }
2778
+
2779
+ //#endregion
2780
+ //#region src/bot/handleEventFault.ts
2781
+ const logger$1 = new Logger("EventBoundary");
2782
+ /**
2783
+ * The event controller boundary. Reports a throw from an event handler and never replies, since a
2784
+ * generic event has no reply target. A {@link Silence} or a non-reporting {@link Notice} stops quietly, a
2785
+ * reporting denial or a raw error publishes a fault with a best-effort actor derived from the args.
2786
+ *
2787
+ * @internal
2788
+ */
2789
+ function handleEventFault(caught, eventName, handlerName, args, core) {
2790
+ if (caught instanceof Silence) {
2791
+ if (caught.reason !== void 0) logger$1.debug(`Silence: ${caught.reason}`);
2792
+ return;
2793
+ }
2794
+ if (!Error.isError(caught)) throw caught;
2795
+ const ignore = new Set(core.config.errors?.ignoreEventApiCodes ?? []);
2796
+ if (caught instanceof DiscordAPIError && ignore.has(caught.code)) {
2797
+ logger$1.debug(`swallowed api code ${caught.code}`);
2798
+ return;
2799
+ }
2800
+ if (caught instanceof Notice && !caught.report) return;
2801
+ const actor = deriveEventActor(args);
2802
+ extractErrorResponse(caught, core, {
2803
+ event: {
2804
+ name: eventName,
2805
+ handler: handlerName,
2806
+ args,
2807
+ channelId: actor.channelId
2808
+ },
2809
+ guild: actor.guild,
2810
+ user: actor.user
2811
+ });
2812
+ }
2813
+
2814
+ //#endregion
2815
+ //#region src/bot/controllers/EventDispatcher.ts
2816
+ /**
2817
+ * Scans event handler directories, registers handlers with Discord client events,
2818
+ * and coordinates event execution through the handler system. Does not handle interactions.
2819
+ * Multiple handlers can point to one event.
2820
+ *
2821
+ * @internal
2822
+ */
2823
+ var EventDispatcher = class {
2824
+ core;
2825
+ logger = new Logger("Events");
2826
+ isInitialized = false;
2827
+ name = "Events";
2828
+ eventMap = /* @__PURE__ */ new Map();
2829
+ middlewares = [];
2830
+ executedOnceHandlers = /* @__PURE__ */ new Set();
2831
+ attachedEvents = /* @__PURE__ */ new Set();
2832
+ hmrHandler;
2833
+ constructor(core) {
2834
+ this.core = core;
2835
+ const eventsDir = this.core.config.bot.events.path;
2836
+ if (!eventsDir) throw new SeedcordError(SeedcordErrorCode.CoreControllerPathMissing, ["EventDispatcher", "events"]);
2837
+ if (!Envapter.isDevelopment && !Envapter.isTest) return;
2838
+ this.hmrHandler = new HmrModuleHandler({
2839
+ handlersDir: eventsDir,
2840
+ ...hasKeys(this.core.config.bot.events, ["middlewares"]) && { middlewaresDir: this.core.config.bot.events.middlewares },
2841
+ isHandler: this.isEventHandlerClass.bind(this),
2842
+ isMiddleware: this.isMiddlewareClass.bind(this),
2843
+ registerHandler: this.registerHandler.bind(this),
2844
+ registerMiddleware: this.registerMiddleware.bind(this),
2845
+ unregisterHandler: this.unregisterHandler.bind(this),
2846
+ unregisterMiddleware: this.unregisterMiddleware.bind(this),
2847
+ getArtifacts: this.getArtifacts.bind(this),
2848
+ logger: this.logger
2849
+ });
2850
+ }
2851
+ getArtifacts(ctor) {
2852
+ const events = [];
2853
+ for (const [event, handlers] of this.eventMap.entries()) if (handlers.some((h) => h.ctor === ctor)) events.push(event);
2854
+ return events;
2855
+ }
2856
+ async init() {
2857
+ if (this.isInitialized) return;
2858
+ this.isInitialized = true;
2859
+ const handlersDir = this.core.config.bot.events.path;
2860
+ if (!handlersDir) return;
2861
+ this.logger.info(chalk.bold(handlersDir));
2862
+ const middlewareDir = hasKeys(this.core.config.bot.events, ["middlewares"]) ? this.core.config.bot.events.middlewares : void 0;
2863
+ if (middlewareDir) {
2864
+ this.logger.info(`${chalk.bold(middlewareDir)} ${chalk.gray("(middlewares)")}`);
2865
+ await this.loadMiddlewares(middlewareDir);
2866
+ }
2867
+ await this.loadHandlers(handlersDir);
2868
+ this.attachToClient();
2869
+ this.logger.info(`${chalk.bold.green("Loaded event handlers:")}`);
2870
+ const eventList = [`${chalk.magenta.bold(this.middlewares.length)} middlewares`];
2871
+ this.eventMap.forEach((handlers, eventName) => {
2872
+ eventList.push(`${chalk.magenta.bold(handlers.length)} ${eventName}`);
2873
+ });
2874
+ this.logger.utils.list(eventList);
2875
+ }
2876
+ async loadHandlers(dir) {
2877
+ await traverseDirectory(dir, (fullPath, relativePath, imported) => {
2878
+ for (const val of Object.values(imported)) {
2879
+ if (!this.isEventHandlerClass(val)) continue;
2880
+ this.registerHandler(val, relativePath);
2881
+ this.hmrHandler?.trackHandler(fullPath, val);
2882
+ }
2883
+ }, this.logger);
2884
+ }
2885
+ async loadMiddlewares(dir) {
2886
+ await traverseDirectory(dir, (fullPath, relativePath, imported) => {
2887
+ for (const val of Object.values(imported)) {
2888
+ if (!this.isMiddlewareClass(val)) continue;
2889
+ this.registerMiddleware(val, relativePath);
2890
+ this.hmrHandler?.trackMiddleware(fullPath, val);
2891
+ }
2892
+ }, this.logger);
2893
+ }
2894
+ /** @internal For use in dev mode */
2895
+ async onHmr(event) {
2896
+ await this.hmrHandler?.handle(event);
2897
+ }
2898
+ unregisterHandler(handlerClass, artifacts) {
2899
+ const events = artifacts ?? [...this.eventMap.keys()];
2900
+ for (const event of events) {
2901
+ const handlers = this.eventMap.get(event);
2902
+ if (!handlers) continue;
2903
+ const index = handlers.findIndex((h) => h.ctor === handlerClass);
2904
+ if (index !== -1) {
2905
+ handlers.splice(index, 1);
2906
+ if (handlers.length === 0) this.eventMap.delete(event);
2907
+ }
2908
+ }
2909
+ }
2910
+ unregisterMiddleware(middlewareCtor) {
2911
+ const index = this.middlewares.findIndex((entry) => entry.ctor === middlewareCtor);
2912
+ if (index !== -1) this.middlewares.splice(index, 1);
2913
+ }
2914
+ registerMiddleware(middlewareCtor, relativePath) {
2915
+ const metadata = Reflect.getMetadata(MiddlewareMetadataKey, middlewareCtor);
2916
+ if (metadata?.type !== "event") return;
2917
+ if (this.middlewares.some((entry) => entry.ctor === middlewareCtor)) return;
2918
+ this.middlewares.push({
2919
+ ctor: middlewareCtor,
2920
+ priority: metadata.priority,
2921
+ ...metadata.events && { events: metadata.events }
2922
+ });
2923
+ this.middlewares.sort((a, b) => a.priority - b.priority);
2924
+ this.logger.utils.registration(`${middlewareCtor.name} ${chalk.gray(`(${metadata.priority})`)}`, relativePath, "event middleware");
2925
+ }
2926
+ async runMiddlewares(eventName, args) {
2927
+ for (const { ctor, events } of this.middlewares) {
2928
+ if (events && !events.includes(eventName)) continue;
2929
+ try {
2930
+ await new ctor(args, this.core, eventName).execute();
2931
+ } catch (caught) {
2932
+ handleEventFault(caught, String(eventName), ctor.name, args, this.core);
2933
+ return false;
2934
+ }
2935
+ }
2936
+ return true;
2937
+ }
2938
+ isEventHandlerClass(obj) {
2939
+ if (typeof obj !== "function") return false;
2940
+ return obj.prototype instanceof EventHandler && Reflect.hasMetadata(EventMetadataKey, obj);
2941
+ }
2942
+ isMiddlewareClass(obj) {
2943
+ if (typeof obj !== "function") return false;
2944
+ return obj.prototype instanceof EventMiddleware && Reflect.hasMetadata(MiddlewareMetadataKey, obj);
2945
+ }
2946
+ registerHandler(handlerClass, relativePath) {
2947
+ const raw = Reflect.getMetadata(EventMetadataKey, handlerClass);
2948
+ const register = (key, frequency) => {
2949
+ let handlers = this.eventMap.get(key);
2950
+ if (!handlers) {
2951
+ handlers = [];
2952
+ this.eventMap.set(key, handlers);
2953
+ }
2954
+ handlers.push({
2955
+ ctor: handlerClass,
2956
+ frequency
2957
+ });
2958
+ if (this.isInitialized && !this.attachedEvents.has(key)) this.attachListener(key);
2959
+ };
2960
+ if (Array.isArray(raw)) for (const entry of raw) register(entry.event, entry.frequency);
2961
+ else {
2962
+ const names = areRoutes(raw) ? raw : typeof raw === "string" ? [raw] : [];
2963
+ for (const name of names) register(name, "on");
2964
+ }
2965
+ this.logger.utils.registration(handlerClass.name, relativePath);
2966
+ }
2967
+ attachToClient() {
2968
+ for (const [eventName] of this.eventMap) this.attachListener(eventName);
2969
+ }
2970
+ attachListener(eventName) {
2971
+ if (this.attachedEvents.has(eventName)) return;
2972
+ this.attachedEvents.add(eventName);
2973
+ const handlerEntries = this.eventMap.get(eventName);
2974
+ this.logger.debug(`Attaching ${chalk.bold.green(eventName)} to the client with ${chalk.gray(handlerEntries?.length ?? 0)} handler(s)`);
2975
+ this.core.bot.client.on(eventName, (...args) => {
2976
+ this.core.bot.emit("any:event", eventName, ...args);
2977
+ (async () => {
2978
+ await this.processEvent(eventName, args).catch((err) => {
2979
+ this.logger.error(`[${chalk.bold.red("UNHANDLED ERROR AT ROOT")}] ${err.name}`, err.stack);
2980
+ this.core.bot.emit("error:unhandled:event", err);
2981
+ });
2982
+ })();
2983
+ });
2984
+ }
2985
+ async processEvent(eventName, args) {
2986
+ const handlerEntries = this.eventMap.get(eventName);
2987
+ if (!handlerEntries || handlerEntries.length === 0) return;
2988
+ const handlersToExecute = handlerEntries.filter((entry) => entry.frequency !== "once" || !this.executedOnceHandlers.has(entry.ctor));
2989
+ if (handlersToExecute.length === 0) return;
2990
+ if (!await this.runMiddlewares(eventName, args)) return;
2991
+ for (const entry of handlersToExecute) {
2992
+ if (entry.frequency === "once") {
2993
+ if (this.executedOnceHandlers.has(entry.ctor)) continue;
2994
+ this.executedOnceHandlers.add(entry.ctor);
2995
+ }
2996
+ await this.processHandler(eventName, entry.ctor, args);
2997
+ }
2998
+ }
2999
+ async processHandler(eventName, ctor, args) {
3000
+ try {
3001
+ this.logger.debug(`Processing ${chalk.bold.green(eventName)} with ${chalk.gray(ctor.name)}`);
3002
+ const handler = new ctor(args, this.core, eventName);
3003
+ await runHandlerGates(ctor, eventGateContext(eventName, args, this.core));
3004
+ await handler.execute();
3005
+ } catch (caught) {
3006
+ handleEventFault(caught, String(eventName), ctor.name, args, this.core);
3007
+ }
3008
+ }
3009
+ };
3010
+
3011
+ //#endregion
3012
+ //#region src/bot/defaults/UnhandledEvent.ts
3013
+ /**
3014
+ * Default handler for unhandled interactions. A reply failure here rides the controller boundary as a
3015
+ * raw fault, so it needs no decorator of its own.
3016
+ *
3017
+ * @internal
3018
+ */
3019
+ var UnhandledEvent = class extends InteractionHandler {
3020
+ async execute() {
3021
+ await this.event.reply({
3022
+ content: `Feature not implemented yet.`,
3023
+ flags: MessageFlags.Ephemeral
3024
+ });
3025
+ }
3026
+ };
3027
+
3028
+ //#endregion
3029
+ //#region src/bot/handleInteractionFault.ts
3030
+ const logger = new Logger("InteractionBoundary");
3031
+ /**
3032
+ * The interaction controller boundary. Sorts a throw from any handler-lifecycle phase into the right
3033
+ * user reply plus the right bus event, building a {@link ReplySender} lazily so it reads the live
3034
+ * acknowledgement state at catch time.
3035
+ *
3036
+ * @internal
3037
+ */
3038
+ async function handleInteractionFault(caught, interaction, core) {
3039
+ if (caught instanceof Silence) {
3040
+ if (caught.reason !== void 0) logger.debug(`Silence: ${caught.reason}`);
3041
+ return;
3042
+ }
3043
+ if (!Error.isError(caught)) throw caught;
3044
+ const ignore = new Set(core.config.errors?.ignoreApiCodes ?? []);
3045
+ if (caught instanceof DiscordAPIError && ignore.has(caught.code)) {
3046
+ logger.debug(`swallowed api code ${caught.code}`);
3047
+ return;
3048
+ }
3049
+ if (interaction.isAutocomplete()) {
3050
+ extractErrorResponse(caught, core, {
3051
+ guild: interaction.guild,
3052
+ user: interaction.user,
3053
+ metadata: interaction,
3054
+ route: slashRouteOf(interaction)
3055
+ });
3056
+ return;
3057
+ }
3058
+ const { response } = extractErrorResponse(caught, core, {
3059
+ interaction,
3060
+ guild: interaction.guild,
3061
+ user: interaction.user,
3062
+ metadata: interaction
3063
+ });
3064
+ await new ReplySender(interaction).send(response, caught instanceof Notice ? caught.ephemeral : true);
3065
+ }
3066
+
3067
+ //#endregion
3068
+ //#region src/bot/controllers/InteractionDispatcher.ts
3069
+ /**
3070
+ * Scans handler directories, routes each interaction to its registered handler, and runs the handler.
3071
+ * One handler per interaction.
3072
+ *
3073
+ * @internal
3074
+ */
3075
+ var InteractionDispatcher = class {
3076
+ core;
3077
+ logger = new Logger("Interactions");
3078
+ isInitialized = false;
3079
+ name = "Interactions";
3080
+ slashMap = /* @__PURE__ */ new Map();
3081
+ buttonMap = /* @__PURE__ */ new Map();
3082
+ modalMap = /* @__PURE__ */ new Map();
3083
+ stringSelectMap = /* @__PURE__ */ new Map();
3084
+ userSelectMap = /* @__PURE__ */ new Map();
3085
+ roleSelectMap = /* @__PURE__ */ new Map();
3086
+ channelSelectMap = /* @__PURE__ */ new Map();
3087
+ mentionableSelectMap = /* @__PURE__ */ new Map();
3088
+ messageContextMenuMap = /* @__PURE__ */ new Map();
3089
+ userContextMenuMap = /* @__PURE__ */ new Map();
3090
+ autocompleteMap = /* @__PURE__ */ new Map();
3091
+ keysToIgnore = /* @__PURE__ */ new Set();
3092
+ middlewares = [];
3093
+ hmrHandler;
3094
+ routeTypes = [
3095
+ [InteractionRoutes.Slash, this.slashMap],
3096
+ [InteractionRoutes.Button, this.buttonMap],
3097
+ [InteractionRoutes.Modal, this.modalMap],
3098
+ [InteractionRoutes.StringMenu, this.stringSelectMap],
3099
+ [InteractionRoutes.UserMenu, this.userSelectMap],
3100
+ [InteractionRoutes.RoleMenu, this.roleSelectMap],
3101
+ [InteractionRoutes.ChannelMenu, this.channelSelectMap],
3102
+ [InteractionRoutes.MentionableMenu, this.mentionableSelectMap],
3103
+ [InteractionRoutes.MessageContextMenu, this.messageContextMenuMap],
3104
+ [InteractionRoutes.UserContextMenu, this.userContextMenuMap],
3105
+ [InteractionRoutes.Autocomplete, this.autocompleteMap]
3106
+ ];
3107
+ constructor(core) {
3108
+ this.core = core;
3109
+ const ignoredKeysFromConfig = hasKeys(this.core.config.bot.interactions, ["ignoreCustomIds"]) ? this.core.config.bot.interactions.ignoreCustomIds : void 0;
3110
+ if (ignoredKeysFromConfig) for (const ignoredKey of ignoredKeysFromConfig) this.keysToIgnore.add(ignoredKey);
3111
+ this.keysToIgnore.add(CONFIRM_DEF);
3112
+ const interactionsDir = this.core.config.bot.interactions.path;
3113
+ if (!interactionsDir) throw new SeedcordError(SeedcordErrorCode.CoreControllerPathMissing, ["InteractionDispatcher", "interactions"]);
3114
+ if (!Envapter.isDevelopment && !Envapter.isTest) return;
3115
+ this.hmrHandler = new HmrModuleHandler({
3116
+ handlersDir: interactionsDir,
3117
+ ...hasKeys(this.core.config.bot.interactions, ["middlewares"]) && this.core.config.bot.interactions.middlewares && { middlewaresDir: this.core.config.bot.interactions.middlewares },
3118
+ isHandler: this.isHandlerClass.bind(this),
3119
+ isMiddleware: this.isMiddlewareClass.bind(this),
3120
+ registerHandler: this.registerHandler.bind(this),
3121
+ registerMiddleware: this.registerMiddleware.bind(this),
3122
+ unregisterHandler: this.unregisterHandler.bind(this),
3123
+ unregisterMiddleware: this.unregisterMiddleware.bind(this),
3124
+ getArtifacts: this.getArtifacts.bind(this),
3125
+ logger: this.logger
3126
+ });
3127
+ }
3128
+ /**
3129
+ * Warns for each command route with no registered `@SlashRoute` handler, which would fall through to
3130
+ * UnhandledEvent at runtime. A bot may route commands outside the registry, so this does not throw.
3131
+ *
3132
+ * @internal
3133
+ */
3134
+ warnUnhandledRoutes(commandLeaves) {
3135
+ for (const route of commandLeaves) if (!this.slashMap.has(route)) this.logger.warn(`Slash route ${chalk.bold.cyan(route)} has no registered ${chalk.bold("@SlashRoute")} handler.`);
3136
+ }
3137
+ /**
3138
+ * Warns for each context-menu command with no matching handler, which would fall through to UnhandledEvent
3139
+ * at runtime. Checked per kind since a user and a message command can share a name.
3140
+ *
3141
+ * @internal
3142
+ */
3143
+ warnUnhandledContextMenuRoutes(leaves) {
3144
+ for (const name of leaves.user) if (!this.userContextMenuMap.has(name)) this.logger.warn(`User context menu ${chalk.bold.cyan(name)} has no registered ${chalk.bold("@ContextMenuRoute")} handler.`);
3145
+ for (const name of leaves.message) if (!this.messageContextMenuMap.has(name)) this.logger.warn(`Message context menu ${chalk.bold.cyan(name)} has no registered ${chalk.bold("@ContextMenuRoute")} handler.`);
3146
+ }
3147
+ getArtifacts(handlerClass) {
3148
+ const artifacts = [];
3149
+ for (const [routeType] of this.routeTypes) {
3150
+ const meta = Reflect.getMetadata(InteractionRouteKeys[routeType], handlerClass);
3151
+ if (areRoutes(meta)) artifacts.push({
3152
+ routeType,
3153
+ routes: meta
3154
+ });
3155
+ }
3156
+ return artifacts;
3157
+ }
3158
+ async init() {
3159
+ if (this.isInitialized) return;
3160
+ this.isInitialized = true;
3161
+ const handlersDir = this.core.config.bot.interactions.path;
3162
+ if (!handlersDir) return;
3163
+ this.logger.info(chalk.bold(handlersDir));
3164
+ const middlewareDir = hasKeys(this.core.config.bot.interactions, ["middlewares"]) ? this.core.config.bot.interactions.middlewares : void 0;
3165
+ if (middlewareDir) {
3166
+ this.logger.info(`${chalk.bold(middlewareDir)} ${chalk.gray("(middlewares)")}`);
3167
+ await this.loadMiddlewares(middlewareDir);
3168
+ }
3169
+ await this.loadHandlers(handlersDir);
3170
+ this.attachToClient();
3171
+ this.logger.info(`${chalk.bold.green("Loaded interaction handlers:")}`);
3172
+ this.logger.utils.list([
3173
+ `${chalk.magenta.bold(this.middlewares.length)} middlewares`,
3174
+ `${chalk.magenta.bold(this.slashMap.size)} slash commands`,
3175
+ `${chalk.magenta.bold(this.buttonMap.size)} buttons`,
3176
+ `${chalk.magenta.bold(this.modalMap.size)} modals`,
3177
+ `${chalk.magenta.bold(this.stringSelectMap.size)} string selects`,
3178
+ `${chalk.magenta.bold(this.userSelectMap.size)} user selects`,
3179
+ `${chalk.magenta.bold(this.roleSelectMap.size)} role selects`,
3180
+ `${chalk.magenta.bold(this.channelSelectMap.size)} channel selects`,
3181
+ `${chalk.magenta.bold(this.mentionableSelectMap.size)} mentionable selects`,
3182
+ `${chalk.magenta.bold(this.messageContextMenuMap.size)} message context menus`,
3183
+ `${chalk.magenta.bold(this.userContextMenuMap.size)} user context menus`,
3184
+ `${chalk.magenta.bold(this.autocompleteMap.size)} autocomplete`
3185
+ ]);
3186
+ }
3187
+ async loadHandlers(dir) {
3188
+ await traverseDirectory(dir, (fullPath, relativePath, imported) => {
3189
+ for (const val of Object.values(imported)) {
3190
+ if (!this.isHandlerClass(val)) continue;
3191
+ this.registerHandler(val, relativePath);
3192
+ this.hmrHandler?.trackHandler(fullPath, val);
3193
+ }
3194
+ }, this.logger);
3195
+ }
3196
+ async loadMiddlewares(dir) {
3197
+ await traverseDirectory(dir, (fullPath, relativePath, imported) => {
3198
+ for (const val of Object.values(imported)) {
3199
+ if (!this.isMiddlewareClass(val)) continue;
3200
+ this.registerMiddleware(val, relativePath);
3201
+ this.hmrHandler?.trackMiddleware(fullPath, val);
3202
+ }
3203
+ }, this.logger);
3204
+ }
3205
+ registerMiddleware(middlewareCtor, relativePath) {
3206
+ const metadata = Reflect.getMetadata(MiddlewareMetadataKey, middlewareCtor);
3207
+ if (metadata?.type !== "interaction") return;
3208
+ if (this.middlewares.some((entry) => entry.ctor === middlewareCtor)) return;
3209
+ if (this.middlewares.some((entry) => entry.ctor.name === middlewareCtor.name)) throw new SeedcordError(SeedcordErrorCode.InteractionDuplicateMiddleware, [middlewareCtor.name]);
3210
+ this.middlewares.push({
3211
+ ctor: middlewareCtor,
3212
+ priority: metadata.priority
3213
+ });
3214
+ this.middlewares.sort((a, b) => a.priority - b.priority);
3215
+ this.logger.utils.registration(`${middlewareCtor.name} ${chalk.gray(`(${metadata.priority})`)}`, relativePath, "middleware");
3216
+ }
3217
+ isHandlerClass(obj) {
3218
+ if (typeof obj !== "function") return false;
3219
+ return obj.prototype instanceof InteractionHandler && Reflect.hasMetadata(InteractionMetadataKey, obj) || obj.prototype instanceof AutocompleteHandler && Reflect.hasMetadata(InteractionMetadataKey, obj);
3220
+ }
3221
+ isMiddlewareClass(obj) {
3222
+ if (typeof obj !== "function") return false;
3223
+ return obj.prototype instanceof InteractionMiddleware && Reflect.hasMetadata(MiddlewareMetadataKey, obj);
3224
+ }
3225
+ registerHandler(handlerClass, relativePath) {
3226
+ const writes = [];
3227
+ for (const [routeType, map] of this.routeTypes) {
3228
+ const meta = Reflect.getMetadata(InteractionRouteKeys[routeType], handlerClass);
3229
+ if (!areRoutes(meta)) continue;
3230
+ for (const route of meta) {
3231
+ const existing = map.get(route);
3232
+ if (existing && existing !== handlerClass) throw new SeedcordError(SeedcordErrorCode.InteractionDuplicateRoute, [
3233
+ route,
3234
+ existing.name,
3235
+ handlerClass.name
3236
+ ]);
3237
+ writes.push([map, route]);
3238
+ }
3239
+ this.logger.utils.registration(handlerClass.name, formatFilePath(relativePath));
3240
+ }
3241
+ for (const [map, route] of writes) map.set(route, handlerClass);
3242
+ }
3243
+ /** @internal For use in dev mode */
3244
+ async onHmr(event) {
3245
+ await this.hmrHandler?.handle(event);
3246
+ }
3247
+ unregisterHandler(handlerClass, artifacts) {
3248
+ if (artifacts) {
3249
+ for (const { routeType, routes } of artifacts) {
3250
+ const map = this.routeTypes.find(([type]) => type === routeType)?.[1];
3251
+ if (map) routes.forEach((route) => map.delete(route));
3252
+ }
3253
+ return;
3254
+ }
3255
+ for (const [routeType, map] of this.routeTypes) {
3256
+ const meta = Reflect.getMetadata(InteractionRouteKeys[routeType], handlerClass);
3257
+ if (!areRoutes(meta)) continue;
3258
+ meta.forEach((route) => map.delete(route));
3259
+ }
3260
+ }
3261
+ unregisterMiddleware(middlewareCtor) {
3262
+ const index = this.middlewares.findIndex((entry) => entry.ctor === middlewareCtor);
3263
+ if (index !== -1) this.middlewares.splice(index, 1);
3264
+ }
3265
+ attachToClient() {
3266
+ this.core.bot.client.on(Events.InteractionCreate, (interaction) => {
3267
+ this.core.bot.emit("any:interaction", interaction);
3268
+ this.handleInteraction(interaction).catch((err) => {
3269
+ this.logger.error(`[${chalk.bold.red("UNHANDLED ERROR AT ROOT")}] ${err.name}`, err.stack);
3270
+ this.core.bot.emit("error:unhandled:interaction", err);
3271
+ });
3272
+ });
3273
+ }
3274
+ async handleCustomIdInteraction(interaction, getMap, interactionType) {
3275
+ if ([...this.keysToIgnore].some((matcher) => matcher.owns(interaction.customId))) return;
3276
+ const prefix = prefixOf(interaction.customId);
3277
+ if (!prefix) return this.logger.warn(`${interactionType} has invalid customId: ${interaction.customId}`);
3278
+ await this.processInteraction(interaction, () => prefix, (key) => getMap().get(key));
3279
+ }
3280
+ async processInteraction(interaction, extractKey, getHandler) {
3281
+ const key = extractKey(interaction);
3282
+ try {
3283
+ if (!interaction.isAutocomplete()) for (const { ctor } of this.middlewares) await new ctor(interaction, this.core).execute();
3284
+ let HandlerCtor = getHandler(key);
3285
+ if (!HandlerCtor) {
3286
+ this.logger.warn(`No handler found for key ${chalk.bold.cyan(key)}. Falling back to UnhandledEvent.`);
3287
+ HandlerCtor = UnhandledEvent;
3288
+ }
3289
+ this.logger.debug(`Processing ${chalk.bold.green(key)} with ${chalk.gray(HandlerCtor.name)}`);
3290
+ const handler = new HandlerCtor(interaction, this.core);
3291
+ if (!interaction.isAutocomplete()) await runHandlerGates(HandlerCtor, interactionGateContext(interaction, this.core));
3292
+ await handler.execute();
3293
+ } catch (caught) {
3294
+ await handleInteractionFault(caught, interaction, this.core);
3295
+ }
3296
+ }
3297
+ async handleInteraction(interaction) {
3298
+ switch (true) {
3299
+ case interaction.isChatInputCommand():
3300
+ await this.handleSlashCommand(interaction);
3301
+ break;
3302
+ case interaction.isButton():
3303
+ await this.handleButton(interaction);
3304
+ break;
3305
+ case interaction.isModalSubmit():
3306
+ await this.handleModal(interaction);
3307
+ break;
3308
+ case interaction.isStringSelectMenu():
3309
+ await this.handleStringSelectMenu(interaction);
3310
+ break;
3311
+ case interaction.isUserSelectMenu():
3312
+ await this.handleUserSelectMenu(interaction);
3313
+ break;
3314
+ case interaction.isRoleSelectMenu():
3315
+ await this.handleRoleSelectMenu(interaction);
3316
+ break;
3317
+ case interaction.isChannelSelectMenu():
3318
+ await this.handleChannelSelectMenu(interaction);
3319
+ break;
3320
+ case interaction.isMentionableSelectMenu():
3321
+ await this.handleMentionableSelectMenu(interaction);
3322
+ break;
3323
+ case interaction.isMessageContextMenuCommand():
3324
+ await this.handleMessageContextMenu(interaction);
3325
+ break;
3326
+ case interaction.isUserContextMenuCommand():
3327
+ await this.handleUserContextMenu(interaction);
3328
+ break;
3329
+ case interaction.isAutocomplete():
3330
+ await this.handleAutocomplete(interaction);
3331
+ break;
3332
+ default:
3333
+ this.logger.warn(`Unhandled interaction type: ${interaction.type}`);
3334
+ break;
3335
+ }
3336
+ }
3337
+ async handleSlashCommand(interaction) {
3338
+ const route = slashRouteOf(interaction);
3339
+ await this.processInteraction(interaction, () => route, (key) => this.slashMap.get(key));
3340
+ }
3341
+ async handleButton(interaction) {
3342
+ await this.handleCustomIdInteraction(interaction, () => this.buttonMap, "Button");
3343
+ }
3344
+ async handleModal(interaction) {
3345
+ await this.handleCustomIdInteraction(interaction, () => this.modalMap, "Modal");
3346
+ }
3347
+ async handleStringSelectMenu(interaction) {
3348
+ await this.handleCustomIdInteraction(interaction, () => this.stringSelectMap, "String select menu");
3349
+ }
3350
+ async handleUserSelectMenu(interaction) {
3351
+ await this.handleCustomIdInteraction(interaction, () => this.userSelectMap, "User select menu");
3352
+ }
3353
+ async handleRoleSelectMenu(interaction) {
3354
+ await this.handleCustomIdInteraction(interaction, () => this.roleSelectMap, "Role select menu");
3355
+ }
3356
+ async handleChannelSelectMenu(interaction) {
3357
+ await this.handleCustomIdInteraction(interaction, () => this.channelSelectMap, "Channel select menu");
3358
+ }
3359
+ async handleMentionableSelectMenu(interaction) {
3360
+ await this.handleCustomIdInteraction(interaction, () => this.mentionableSelectMap, "Mentionable select menu");
3361
+ }
3362
+ async handleMessageContextMenu(interaction) {
3363
+ await this.processInteraction(interaction, () => interaction.commandName, (key) => this.messageContextMenuMap.get(key));
3364
+ }
3365
+ async handleUserContextMenu(interaction) {
3366
+ await this.processInteraction(interaction, () => interaction.commandName, (key) => this.userContextMenuMap.get(key));
3367
+ }
3368
+ async handleAutocomplete(interaction) {
3369
+ const route = slashRouteOf(interaction);
3370
+ if (!this.autocompleteMap.has(route)) {
3371
+ this.logger.warn(`No autocomplete handler for ${chalk.bold.cyan(route)}.`);
3372
+ await interaction.respond([]);
3373
+ return;
3374
+ }
3375
+ await this.processInteraction(interaction, () => route, (key) => this.autocompleteMap.get(key));
3376
+ }
3377
+ };
3378
+
3379
+ //#endregion
3380
+ //#region \0@oxc-project+runtime@0.135.0/helpers/esm/decorateMetadata.js
3381
+ function __decorateMetadata(k, v) {
3382
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
3383
+ }
3384
+
3385
+ //#endregion
3386
+ //#region \0@oxc-project+runtime@0.135.0/helpers/esm/decorate.js
3387
+ function __decorate(decorators, target, key, desc) {
3388
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3389
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
3390
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
3391
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
3392
+ }
3393
+
3394
+ //#endregion
3395
+ //#region src/bot/Bot.ts
3396
+ /**
3397
+ * Discord bot implementation that manages client and controllers
3398
+ *
3399
+ * Don't instantiate this class directly. Use `core.bot` instead.
3400
+ */
3401
+ var Bot = class extends Plugin {
3402
+ /** @internal */
3403
+ logger = new Logger("Bot");
3404
+ isInitialized = false;
3405
+ _client;
3406
+ interactions;
3407
+ events;
3408
+ commands;
3409
+ emojiInjector;
3410
+ emojis = Emojis;
3411
+ mentions = CommandMentions;
3412
+ /** @internal For use in dev mode */
3413
+ async onHmr(event) {
3414
+ if (this.interactions) await this.interactions.onHmr(event);
3415
+ if (this.events) await this.events.onHmr(event);
3416
+ if (this.commands) await this.commands.onHmr(event);
3417
+ }
3418
+ /** @internal */
3419
+ constructor(core) {
3420
+ super(core);
3421
+ this._client = new Client(core.config.bot.clientOptions);
3422
+ if (core.config.bot.interactions.path) this.interactions = new InteractionDispatcher(core);
3423
+ if (core.config.bot.events.path) this.events = new EventDispatcher(core);
3424
+ if (core.config.bot.commands.path) {
3425
+ const mentionInjector = new CommandMentionInjector(core);
3426
+ this.commands = new CommandRegistry(core, (result) => {
3427
+ mentionInjector.inject(result);
3428
+ });
3429
+ }
3430
+ this.emojiInjector = new EmojiInjector(core);
3431
+ core.shutdown.addTask(ShutdownPhase.DiscordCleanup, "stop-bot", async () => await this.stop(), 2e3);
3432
+ }
3433
+ /**
3434
+ * Initializes Discord client and all controllers
3435
+ * @internal
3436
+ */
3437
+ async init() {
3438
+ if (this.isInitialized) return;
3439
+ this.isInitialized = true;
3440
+ const token = this.botToken;
3441
+ if (this.interactions) await this.interactions.init();
3442
+ if (this.events) await this.events.init();
3443
+ await this.login(token);
3444
+ await this.emojiInjector.init();
3445
+ if (this.commands) {
3446
+ await this.commands.init();
3447
+ await this.commands.setCommands();
3448
+ this.interactions?.warnUnhandledRoutes(this.commands.routeLeaves());
3449
+ this.interactions?.warnUnhandledContextMenuRoutes(this.commands.contextMenuLeaves());
3450
+ }
3451
+ }
3452
+ /**
3453
+ * Stops the bot and cleans up connections
3454
+ * @internal
3455
+ */
3456
+ async stop() {
3457
+ this._client.removeAllListeners();
3458
+ await this.logout();
3459
+ }
3460
+ /**
3461
+ * Logs the bot into Discord using the configured token
3462
+ */
3463
+ async login(token) {
3464
+ await this._client.login(token);
3465
+ this.logger.info(`Logged in as ${chalk.bold.magenta(this._client.user?.username)}!`);
3466
+ return this;
3467
+ }
3468
+ /**
3469
+ * Logs out and destroys the Discord client connection
3470
+ */
3471
+ async logout() {
3472
+ await this._client.destroy();
3473
+ this.logger.info(chalk.bold.red("Logged out of Discord!"));
3474
+ }
3475
+ get client() {
3476
+ return this._client;
3477
+ }
3478
+ emit(event, ...args) {
3479
+ return super.emit(event, ...args);
3480
+ }
3481
+ };
3482
+ __decorate([Envapt("DISCORD_BOT_TOKEN", { converter: (raw) => validateDiscordToken(raw) }), __decorateMetadata("design:type", String)], Bot.prototype, "botToken", void 0);
3483
+
3484
+ //#endregion
3485
+ //#region src/hmr/HmrManager.ts
3486
+ var HmrManager = class {
3487
+ logger = new Logger("HMR", { channel: "hmr" });
3488
+ listeners = /* @__PURE__ */ new Set();
3489
+ constructor() {}
3490
+ /** @internal */
3491
+ init() {
3492
+ if (!import.meta.hot) return;
3493
+ setDevChannel(wrapHot(import.meta.hot));
3494
+ if (Envapter.isDevelopment || Envapter.isTest) {
3495
+ this.logger.info("Enabled");
3496
+ getDevChannel()?.on("seedcord:hmr", (payload) => {
3497
+ const affected = payload.affectedModules?.length ?? 0;
3498
+ this.logger.info(`${chalk.bold("1")} module changed, ${chalk.bold(affected)} affected modules`);
3499
+ if (payload.affectedModules) this.logger.utils.list(payload.affectedModules.map((mod) => formatFilePath(mod)), "Affected modules: ");
3500
+ this.handleUpdate(payload);
3501
+ });
3502
+ }
3503
+ }
3504
+ /** @internal */
3505
+ register(listener) {
3506
+ this.listeners.add(listener);
3507
+ }
3508
+ /** @internal */
3509
+ unregister(listener) {
3510
+ this.listeners.delete(listener);
3511
+ }
3512
+ async handleUpdate(event) {
3513
+ const promises = [...this.listeners].map(async (listener) => {
3514
+ try {
3515
+ await listener.onHmr(event);
3516
+ } catch (error) {
3517
+ this.logger.error(`Error handling HMR update in ${chalk.bold(listener.name)}: `, error);
3518
+ }
3519
+ });
3520
+ await Promise.all(promises);
3521
+ }
3522
+ };
3523
+
3524
+ //#endregion
3525
+ //#region src/subscribers/bases/webhookHelpers.ts
3526
+ const DISCORD_WEBHOOK_REGEX = new RegExp(String.raw`^https?:\/\/(?:canary\.|ptb\.)?discord(?:app)?\.com\/api\/webhooks\/\d+\/[\w$-]+$`);
3527
+ /**
3528
+ * Whether a string is a well-formed Discord webhook URL.
3529
+ *
3530
+ * @internal
3531
+ */
3532
+ function isDiscordWebhookUrl(value) {
3533
+ return URL.canParse(value) && DISCORD_WEBHOOK_REGEX.test(value);
3534
+ }
3535
+ /**
3536
+ * Serializes a value to a JSON attachment, made circular-safe first.
3537
+ *
3538
+ * @internal
3539
+ */
3540
+ function jsonAttachment(name, description, data) {
3541
+ const content = filterCirculars(data);
3542
+ return new AttachmentBuilder(Buffer.from(JSON.stringify(content, void 0, 2), "utf8"), {
3543
+ name,
3544
+ description
3545
+ });
3546
+ }
3547
+ /**
3548
+ * The small divider the default webhook reporters place between sections.
3549
+ *
3550
+ * @internal
3551
+ */
3552
+ var WebhookSeparator = class extends BuilderComponent {
3553
+ constructor() {
3554
+ super("separator");
3555
+ this.instance.setSpacing(SeparatorSpacingSize.Small).setDivider(true);
3556
+ }
3557
+ };
3558
+
3559
+ //#endregion
3560
+ //#region src/subscribers/default/HandledException.ts
3561
+ var _HandledException;
3562
+ function webhookUrlValidator$1(raw) {
3563
+ if (raw !== null && typeof raw !== "string") throw new SeedcordError(SeedcordErrorCode.ConfigHandledExceptionWebhookInvalid);
3564
+ const value = raw?.trim() ?? "";
3565
+ if (value === "") throw new SeedcordError(SeedcordErrorCode.ConfigHandledExceptionWebhookMissing);
3566
+ if (!isDiscordWebhookUrl(value)) throw new SeedcordError(SeedcordErrorCode.ConfigHandledExceptionWebhookInvalid);
3567
+ return value;
3568
+ }
3569
+ let HandledException = class HandledException extends WebhookLog {
3570
+ static {
3571
+ _HandledException = this;
3572
+ }
3573
+ webhook = new WebhookClient({ url: _HandledException.handledExceptionWebhookUrl });
3574
+ async execute() {
3575
+ const { source } = this.data;
3576
+ try {
3577
+ await this.webhook.send({
3578
+ flags: flagsFor(false),
3579
+ withComponents: true,
3580
+ username: "Handled Exception",
3581
+ components: [new HandledExceptionContainer(this.data).component],
3582
+ files: [jsonAttachment("source.json", "The raw source the fault came from", source.raw)]
3583
+ });
3584
+ } catch (error) {
3585
+ this.logger.error("Failed to send handled exception webhook", error);
3586
+ }
3587
+ }
3588
+ };
3589
+ __decorate([Envapt("HANDLED_EXCEPTION_WEBHOOK_URL", { converter: (raw) => webhookUrlValidator$1(raw) }), __decorateMetadata("design:type", String)], HandledException, "handledExceptionWebhookUrl", void 0);
3590
+ HandledException = _HandledException = __decorate([Subscribe("handledException")], HandledException);
3591
+ var HandledExceptionContainer = class extends BuilderComponent {
3592
+ constructor(data) {
3593
+ super("container");
3594
+ const { denial, uuid, source } = data;
3595
+ this.instance.addTextDisplayComponents((text) => text.setContent(faultSummary(denial, source))).addSeparatorComponents(new WebhookSeparator().component).addTextDisplayComponents((text) => text.setContent(`### UUID \`${uuid}\`\n\`\`\`${causeStack(denial)}\`\`\``)).addSeparatorComponents(new WebhookSeparator().component).addTextDisplayComponents((text) => text.setContent("### Source")).addFileComponents((file) => file.setURL("attachment://source.json"));
3596
+ }
3597
+ };
3598
+ /**
3599
+ * The summary block of a fault report, narrowed per source kind so an interaction fault shows its
3600
+ * command and customId while an event fault shows its event name and handler.
3601
+ *
3602
+ * @internal
3603
+ */
3604
+ function faultSummary(denial, source) {
3605
+ const head = `### A handled fault was reported: \`${denial.name}\`\n**Message:** ${denial.message}\n`;
3606
+ if (source.kind === "event") return `${head}**Event:** ${source.eventName}\n**Handler:** ${source.handler}\n**User ID:** \`${source.userId ?? "n/a"}\`\n**Guild ID:** \`${source.guildId ?? "n/a"}\`\n**Channel ID:** \`${source.channelId ?? "n/a"}\``;
3607
+ return `${head}**Kind:** ${source.interactionKind}\n**Command:** ${source.command ?? "n/a"}\n**CustomId:** ${source.customId ?? "n/a"}\n**User ID:** \`${source.userId}\`\n**Guild ID:** \`${source.guildId ?? "n/a"}\`\n**Channel ID:** \`${source.channelId ?? "n/a"}\`\n**Interaction ID:** \`${source.interactionId}\``;
3608
+ }
3609
+ /**
3610
+ * The text shown for a denial's cause in the report. Tolerates a non-serializable cause (a bigint or a
3611
+ * circular object) so building the report never throws.
3612
+ *
3613
+ * @internal
3614
+ */
3615
+ function causeStack(denial) {
3616
+ const { cause } = denial;
3617
+ if (Error.isError(cause)) return cause.stack ?? cause.message;
3618
+ if (typeof cause === "string") return cause;
3619
+ if (typeof cause === "bigint" || typeof cause === "symbol" || typeof cause === "function") return cause.toString();
3620
+ if (cause !== void 0) try {
3621
+ return JSON.stringify(cause);
3622
+ } catch {
3623
+ return "[unserializable cause]";
3624
+ }
3625
+ return denial.stack ?? "No cause recorded.";
3626
+ }
3627
+
3628
+ //#endregion
3629
+ //#region src/subscribers/default/UnknownException.ts
3630
+ var _UnknownException;
3631
+ function webhookUrlValidator(raw) {
3632
+ if (raw !== null && typeof raw !== "string") throw new SeedcordError(SeedcordErrorCode.ConfigUnknownExceptionWebhookInvalid);
3633
+ const value = raw?.trim() ?? "";
3634
+ if (value === "") throw new SeedcordError(SeedcordErrorCode.ConfigUnknownExceptionWebhookMissing);
3635
+ if (!isDiscordWebhookUrl(value)) throw new SeedcordError(SeedcordErrorCode.ConfigUnknownExceptionWebhookInvalid);
3636
+ return value;
3637
+ }
3638
+ let UnknownException = class UnknownException extends WebhookLog {
3639
+ static {
3640
+ _UnknownException = this;
3641
+ }
3642
+ webhook = new WebhookClient({ url: _UnknownException.unknownExceptionWebhookUrl });
3643
+ async execute() {
3644
+ const { metadata } = this.data;
3645
+ const metadataFile = metadata ? jsonAttachment("metadata.json", "Metadata associated with the error", metadata) : null;
3646
+ try {
3647
+ await this.webhook.send({
3648
+ flags: flagsFor(false),
3649
+ withComponents: true,
3650
+ username: "Unknown Exception",
3651
+ components: [new UnhandledErrorContainer(this.data).component],
3652
+ files: metadataFile ? [metadataFile] : []
3653
+ });
3654
+ } catch (error) {
3655
+ this.logger.error("Failed to send unknown exception webhook", error);
3656
+ }
3657
+ }
3658
+ };
3659
+ __decorate([Envapt("UNKNOWN_EXCEPTION_WEBHOOK_URL", { converter: (raw) => webhookUrlValidator(raw) }), __decorateMetadata("design:type", String)], UnknownException, "unknownExceptionWebhookUrl", void 0);
3660
+ UnknownException = _UnknownException = __decorate([Subscribe("unknownException")], UnknownException);
3661
+ var UnhandledErrorContainer = class extends BuilderComponent {
3662
+ constructor(data) {
3663
+ super("container");
3664
+ const { uuid, error, guild, user, metadata } = data;
3665
+ this.instance.addTextDisplayComponents((text) => text.setContent(`### An unknown exception was thrown\n**Guild ID:** \`${guild?.id ?? "Not used in a guild"}\`\n**Guild Name:** ${guild?.name ?? "Not used in a guild"}\n**User ID:** \`${user?.id ?? "Missing user info"}\`\n**Username:** ${user?.username ?? "Missing user info"}\n`)).addSeparatorComponents(new WebhookSeparator().component).addTextDisplayComponents((text) => text.setContent(`### UUID \`${uuid}\`\n\`\`\`${error.stack}\`\`\``));
3666
+ this.addTimestampsIfAvailable(error);
3667
+ this.addMetadataIfAvailable(metadata);
3668
+ }
3669
+ addTimestampsIfAvailable(error) {
3670
+ if (!(error instanceof DiscordAPIError)) return;
3671
+ const now = Date.now();
3672
+ const snowflake = error.url.match(/\/interactions\/(\d+)\//)?.[1];
3673
+ if (!snowflake) return void 0;
3674
+ const interactionTs = Number(SnowflakeUtil.deconstruct(snowflake).timestamp);
3675
+ const diff = now - interactionTs;
3676
+ const seconds = Math.floor(diff / 1e3);
3677
+ const millis = diff % 1e3;
3678
+ this.instance.addSeparatorComponents(new WebhookSeparator().component).addTextDisplayComponents((text) => text.setContent(`### Timestamps\n- **\`Interaction sent\` :** ${new Date(interactionTs).toISOString()} (${interactionTs})\n- **\`Error logged \` :** ${new Date(now).toISOString()} (${now})\n- **\`Offset \` :** ${seconds}s ${millis}ms`));
3679
+ }
3680
+ addMetadataIfAvailable(metadata) {
3681
+ if (!metadata) return;
3682
+ this.instance.addSeparatorComponents(new WebhookSeparator().component).addTextDisplayComponents((text) => text.setContent("### Metadata")).addFileComponents((file) => file.setURL("attachment://metadata.json"));
3683
+ }
3684
+ };
3685
+
3686
+ //#endregion
3687
+ //#region src/subscribers/Bus.ts
3688
+ /**
3689
+ * Manages application subscribers and event handling
3690
+ *
3691
+ * Provides a centralized system for registering and executing custom subscribers
3692
+ * throughout the application lifecycle. Bus subscribers are loaded from configured directories
3693
+ * and can be triggered programmatically or by framework events. Accessed via `core.bus`. Do not
3694
+ * construct it directly.
3695
+ */
3696
+ var Bus = class extends Plugin {
3697
+ core;
3698
+ logger = new Logger("Subscribers");
3699
+ /** @internal */
3700
+ name = "Subscribers";
3701
+ isInitialized = false;
3702
+ subscribersMap = /* @__PURE__ */ new Map();
3703
+ executedOnceHandlers = /* @__PURE__ */ new Set();
3704
+ hmrHandler;
3705
+ constructor(core) {
3706
+ super(core);
3707
+ this.core = core;
3708
+ if (this.core.config.subscribers.path) {
3709
+ if (!Envapter.isDevelopment && !Envapter.isTest) return;
3710
+ this.hmrHandler = new HmrModuleHandler({
3711
+ handlersDir: this.core.config.subscribers.path,
3712
+ isHandler: this.isSubscriber.bind(this),
3713
+ registerHandler: this.registerSubscriber.bind(this),
3714
+ unregisterHandler: this.unregisterSubscriber.bind(this),
3715
+ getArtifacts: this.getArtifacts.bind(this),
3716
+ logger: this.logger
3717
+ });
3718
+ }
3719
+ }
3720
+ getArtifacts(ctor) {
3721
+ return [Reflect.getMetadata(SubscribeMetadataKey, ctor).subscriber];
3722
+ }
3723
+ /** @internal */
3724
+ async init() {
3725
+ if (this.isInitialized) return;
3726
+ this.isInitialized = true;
3727
+ this.registerSubscriber(UnknownException);
3728
+ this.registerSubscriber(HandledException);
3729
+ Envapter.require("UNKNOWN_EXCEPTION_WEBHOOK_URL", "HANDLED_EXCEPTION_WEBHOOK_URL");
3730
+ const subscribersDir = this.core.config.subscribers.path;
3731
+ if (subscribersDir) {
3732
+ this.logger.info(chalk.bold(subscribersDir));
3733
+ await this.loadSubscribers(subscribersDir);
3734
+ const totalSubscribers = [...this.subscribersMap.values()].reduce((acc, handlers) => acc + handlers.length, 0);
3735
+ this.logger.utils.list([`${chalk.bold.magenta(totalSubscribers)} subscribers`], chalk.bold.green("Loaded"));
3736
+ }
3737
+ }
3738
+ /** @internal For use in dev mode */
3739
+ async onHmr(event) {
3740
+ if (this.hmrHandler) await this.hmrHandler.handle(event);
3741
+ }
3742
+ async loadSubscribers(dir) {
3743
+ await traverseDirectory(dir, (fullPath, relativePath, imported) => {
3744
+ for (const exportName of Object.keys(imported)) {
3745
+ const val = imported[exportName];
3746
+ if (this.isSubscriber(val)) {
3747
+ this.registerSubscriber(val);
3748
+ this.hmrHandler?.trackHandler(fullPath, val);
3749
+ this.logger.utils.registration(val.name, relativePath);
3750
+ }
3751
+ }
3752
+ }, this.logger);
3753
+ }
3754
+ registerSubscriber(handler) {
3755
+ const options = Reflect.getMetadata(SubscribeMetadataKey, handler);
3756
+ let handlers = this.subscribersMap.get(options.subscriber);
3757
+ if (!handlers) {
3758
+ handlers = [];
3759
+ this.subscribersMap.set(options.subscriber, handlers);
3760
+ }
3761
+ handlers.push({
3762
+ ctor: handler,
3763
+ frequency: options.frequency ?? "on"
3764
+ });
3765
+ }
3766
+ unregisterSubscriber(handler, artifacts) {
3767
+ const subscribers = artifacts ?? [...this.subscribersMap.keys()];
3768
+ for (const subscriber of subscribers) {
3769
+ const handlers = this.subscribersMap.get(subscriber);
3770
+ if (!handlers) continue;
3771
+ const index = handlers.findIndex((entry) => entry.ctor === handler);
3772
+ if (index !== -1) handlers.splice(index, 1);
3773
+ }
3774
+ }
3775
+ isSubscriber(obj) {
3776
+ if (typeof obj !== "function") return false;
3777
+ return obj.prototype instanceof Subscriber && Reflect.hasMetadata(SubscribeMetadataKey, obj);
3778
+ }
3779
+ /**
3780
+ * Publishes an event to its subscribers and native listeners.
3781
+ *
3782
+ * Fire-and-forget, so subscriber handlers run asynchronously and this returns before they
3783
+ * complete, and callers must not assume side effects have landed. Errors thrown by a subscriber
3784
+ * are caught and logged, never surfaced here. A `'once'` subscriber is marked as executed when
3785
+ * it starts (even if it throws), so it never runs twice.
3786
+ *
3787
+ * @param event - The subscription key to publish
3788
+ * @param data - Payload passed to each subscriber
3789
+ * @returns Whether the underlying emitter had native listeners for the event
3790
+ */
3791
+ publish(event, data) {
3792
+ this.processSubscriber(event, data);
3793
+ return super.emit(event, ...[data]);
3794
+ }
3795
+ async processSubscriber(subscriberName, data) {
3796
+ const handlers = this.subscribersMap.get(subscriberName);
3797
+ if (!handlers) return;
3798
+ for (const entry of handlers) {
3799
+ if (entry.frequency === "once" && this.executedOnceHandlers.has(entry.ctor)) continue;
3800
+ try {
3801
+ if (entry.frequency === "once") this.executedOnceHandlers.add(entry.ctor);
3802
+ const Ctor = entry.ctor;
3803
+ await new Ctor(data, this.core).execute();
3804
+ } catch (err) {
3805
+ this.logger.error(`Error in subscriber ${String(subscriberName)} handler ${entry.ctor.name}:`, err);
3806
+ }
3807
+ }
3808
+ }
3809
+ };
3810
+
3811
+ //#endregion
3812
+ //#region src/version.ts
2
3813
  /** Package version */
3
- const version = "0.0.1";
3814
+ const version = "0.1.0-next.0";
3815
+
3816
+ //#endregion
3817
+ //#region src/Seedcord.ts
3818
+ /**
3819
+ * Main Seedcord bot framework class
3820
+ *
3821
+ * Primary entry point for creating Discord bots with Seedcord.
3822
+ * Manages component lifecycle and provides plugin support.
3823
+ */
3824
+ var Seedcord = class Seedcord extends Pluggable {
3825
+ config;
3826
+ /** @internal */
3827
+ [SeedcordBrand] = true;
3828
+ /** @internal */
3829
+ augmentTarget = "@seedcord/gateway";
3830
+ /** @internal */
3831
+ version = version;
3832
+ static isInstantiated = false;
3833
+ /** @see {@link CoordinatedShutdown} */
3834
+ shutdown;
3835
+ /** @see {@link CoordinatedStartup} */
3836
+ startup;
3837
+ /** @see {@link Bus} */
3838
+ bus;
3839
+ /** @see {@link Bot} */
3840
+ bot;
3841
+ /** @see {@link IRateLimiter} */
3842
+ rateLimiter;
3843
+ /** @see {@link HealthCheck} */
3844
+ healthCheck;
3845
+ /** @see {@link HmrManager} */
3846
+ hmrManager;
3847
+ /**
3848
+ * Creates a new Seedcord instance
3849
+ *
3850
+ * @param config - Bot configuration including paths and Discord client options
3851
+ * @throws A **SeedcordError** When attempting to create multiple instances (singleton)
3852
+ */
3853
+ constructor(config) {
3854
+ if (Seedcord.isInstantiated) throw new SeedcordError(SeedcordErrorCode.CoreSingletonViolation);
3855
+ Seedcord.isInstantiated = true;
3856
+ const shutdown = new CoordinatedShutdown(config.shutdownEnabled);
3857
+ const startup = new CoordinatedStartup();
3858
+ super(shutdown, startup);
3859
+ this.config = config;
3860
+ setBotColor(config.botColor);
3861
+ this.shutdown = shutdown;
3862
+ this.startup = startup;
3863
+ this.hmrManager = new HmrManager();
3864
+ this.hmrManager.init();
3865
+ this.bus = new Bus(this);
3866
+ this.bot = new Bot(this);
3867
+ this.rateLimiter = new MemoryRateLimiter();
3868
+ this.healthCheck = new HealthCheck(this.shutdown, config.healthCheck);
3869
+ this.registerStartupTasks();
3870
+ }
3871
+ /** @internal */
3872
+ static reset() {
3873
+ Seedcord.isInstantiated = false;
3874
+ }
3875
+ /**
3876
+ * Registers default startup tasks
3877
+ * @internal
3878
+ */
3879
+ registerStartupTasks() {
3880
+ if (Envapter.isDevelopment || Envapter.isTest) this.registerHmrAwareModules();
3881
+ this.startup.addTask(StartupPhase.Configuration, "Bus Initialization", async () => {
3882
+ this.bus.logger.utils.initialization("Subscribers", "start");
3883
+ await this.bus.init();
3884
+ this.bus.logger.utils.initialization("Subscribers", "end");
3885
+ });
3886
+ this.startup.addTask(StartupPhase.Instantiation, "Bot Initialization", async () => {
3887
+ this.bot.logger.utils.initialization("Bot", "start");
3888
+ await this.bot.init();
3889
+ this.bot.logger.utils.initialization("Bot", "end");
3890
+ });
3891
+ this.startup.addTask(StartupPhase.Ready, "Health Check", async () => {
3892
+ this.healthCheck.logger.utils.initialization("HealthCheck", "start");
3893
+ await this.healthCheck.init();
3894
+ this.healthCheck.logger.utils.initialization("HealthCheck", "end");
3895
+ });
3896
+ }
3897
+ /**
3898
+ * Starts the bot and runs all initialization tasks
3899
+ *
3900
+ * @returns This Seedcord instance when fully initialized
3901
+ */
3902
+ async start() {
3903
+ await super.init();
3904
+ return this;
3905
+ }
3906
+ registerHmrAwareModules() {
3907
+ this.startup.addTask(StartupPhase.Configuration, "HMR Registration", async () => {
3908
+ this.hmrManager.register(this.bot);
3909
+ this.hmrManager.register(this.bus);
3910
+ for (const plugin of this.plugins) this.hmrManager.register(plugin);
3911
+ await Promise.resolve();
3912
+ });
3913
+ }
3914
+ };
4
3915
 
5
3916
  //#endregion
6
- export { version };
3917
+ export { ArraySource, AutocompleteHandler, AutocompleteRoute, ButtonHandler, ButtonRoute, CommandMentions, ContextMenuHandler, ContextMenuRoute, CursorSource, Emojis, EventHandler, EventMiddleware, Gated, HmrModuleHandler, IgnoreBots, InteractionHandler, InteractionMiddleware, Middleware, MiddlewareType, ModalHandler, ModalRoute, Nsfw, Paginator, Pluggable, Plugin, RegisterCommand, RegisterEvent, ReplySender, RequireBotPermissions, RequirePermissions, RequireRole, Seedcord, SelectMenuHandler, SelectMenuKind, SelectMenuRoute, SlashHandler, SlashRoute, Subscribe, Subscriber, WebhookLog, checkBotPermissions, checkPermissions, fetchGuildMember, fetchManyGuildMembers, fetchManyUsers, fetchRole, fetchText, fetchUser, getBotRole, getConfirmation, hasPermsToAssign, updateMemberRoles, version };
7
3918
  //# sourceMappingURL=index.mjs.map