@seedcord/core 0.11.0-next.0 → 0.12.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/Bus-W1K-uMeO.mjs +930 -0
- package/dist/Bus-W1K-uMeO.mjs.map +1 -0
- package/dist/{CoordinatedShutdown-H5YjZn8A.d.mts → CoordinatedShutdown-BVtNNSsF.d.mts} +13 -4
- package/dist/{CoordinatedStartup-CGnJrqcl.mjs → CoordinatedStartup-DA3gW8op.mjs} +22 -20
- package/dist/CoordinatedStartup-DA3gW8op.mjs.map +1 -0
- package/dist/Generated-ByC53_A2.d.mts +26 -0
- package/dist/{HmrModuleHandler-8ZC-UuZh.mjs → HmrModuleHandler-BMD7dg8N.mjs} +2 -2
- package/dist/HmrModuleHandler-BMD7dg8N.mjs.map +1 -0
- package/dist/PluginHost-CYe-UVpp.mjs +552 -0
- package/dist/PluginHost-CYe-UVpp.mjs.map +1 -0
- package/dist/{PluginHost-DB4j8unu.d.mts → PluginHost-DWBgBS6Q.d.mts} +35 -8
- package/dist/{PluginLifecycle-AhQ46NIr.mjs → PluginLifecycle-DdwRzcDj.mjs} +3 -3
- package/dist/PluginLifecycle-DdwRzcDj.mjs.map +1 -0
- package/dist/{ServerHost-CvGQr7oN.mjs → ServerHost-DHg-Y2_q.mjs} +20 -32
- package/dist/ServerHost-DHg-Y2_q.mjs.map +1 -0
- package/dist/{ServerHost-DYeh0KTk.d.mts → ServerHost-whpI0h4d.d.mts} +7 -6
- package/dist/bindViteEnv-BgFewlZ0.d.mts +11 -0
- package/dist/bindViteEnv-NFzvdqlT.mjs +32 -0
- package/dist/bindViteEnv-NFzvdqlT.mjs.map +1 -0
- package/dist/env-internal.index.d.mts +2 -0
- package/dist/env-internal.index.mjs +3 -0
- package/dist/hmr.index.mjs +1 -1
- package/dist/{index-Du71Xx69.d.mts → index-Boo33hh3.d.mts} +10 -11
- package/dist/index.d.mts +108 -6
- package/dist/index.mjs +118 -12
- package/dist/index.mjs.map +1 -1
- package/dist/internal.index.d.mts +26 -7
- package/dist/internal.index.mjs +8 -7
- package/dist/internal.index.mjs.map +1 -1
- package/dist/node-internal.index.d.mts +7 -4
- package/dist/node-internal.index.mjs +20 -7
- package/dist/node-internal.index.mjs.map +1 -1
- package/dist/node.index.d.mts +3 -3
- package/dist/node.index.mjs +22 -28
- package/dist/node.index.mjs.map +1 -1
- package/dist/{phases-FTM69J3a.d.mts → phases-Dojnr-ng.d.mts} +111 -12
- package/dist/plugin.index.d.mts +3 -2
- package/dist/plugin.index.mjs +1 -1
- package/dist/{subscribers-Ce3SWy23.mjs → subscribers-D4_HZcgw.mjs} +12 -829
- package/dist/subscribers-D4_HZcgw.mjs.map +1 -0
- package/dist/usingCtx-Cf2cZi96.mjs +58 -0
- package/package.json +24 -15
- package/dist/CoordinatedStartup-CGnJrqcl.mjs.map +0 -1
- package/dist/HmrModuleHandler-8ZC-UuZh.mjs.map +0 -1
- package/dist/PluginHost-B8kxLOeb.mjs +0 -245
- package/dist/PluginHost-B8kxLOeb.mjs.map +0 -1
- package/dist/PluginLifecycle-AhQ46NIr.mjs.map +0 -1
- package/dist/ServerHost-CvGQr7oN.mjs.map +0 -1
- package/dist/phases-BauKJOTT.mjs +0 -31
- package/dist/phases-BauKJOTT.mjs.map +0 -1
- package/dist/publishDefault-D3dAyzZ9.mjs +0 -7
- package/dist/publishDefault-D3dAyzZ9.mjs.map +0 -1
- package/dist/subscribers-Ce3SWy23.mjs.map +0 -1
|
@@ -0,0 +1,930 @@
|
|
|
1
|
+
import "reflect-metadata";
|
|
2
|
+
import { ActionRowBuilder, ButtonBuilder, ChannelSelectMenuBuilder, CheckboxBuilder, CheckboxGroupBuilder, CheckboxGroupOptionBuilder, ContainerBuilder, ContextMenuCommandBuilder, EmbedBuilder, FileBuilder, FileUploadBuilder, LabelBuilder, MediaGalleryBuilder, MentionableSelectMenuBuilder, ModalBuilder, RadioGroupBuilder, RadioGroupOptionBuilder, RoleSelectMenuBuilder, SectionBuilder, SeparatorBuilder, SlashCommandBuilder, SlashCommandSubcommandBuilder, SlashCommandSubcommandGroupBuilder, StringSelectMenuBuilder, StringSelectMenuOptionBuilder, TextDisplayBuilder, TextInputBuilder, UserSelectMenuBuilder } from "@discordjs/builders";
|
|
3
|
+
import { InteractionContextType, MessageFlags, Routes, SeparatorSpacingSize } from "discord-api-types/v10";
|
|
4
|
+
import { SeedcordErrorCode, paint } from "@seedcord/errors";
|
|
5
|
+
import { SeedcordError, SeedcordRangeError, SeedcordTypeError } from "@seedcord/errors/internal";
|
|
6
|
+
import { Logger } from "@seedcord/logger";
|
|
7
|
+
import { pluralize } from "@seedcord/utils/internal";
|
|
8
|
+
import { filterCirculars, stripAnsi, timestampFromSnowflake } from "@seedcord/utils";
|
|
9
|
+
import { TypedEventEmitter } from "@seedcord/event-emitter";
|
|
10
|
+
import { Envapter } from "envapt";
|
|
11
|
+
import { DiscordAPIError, REST } from "@discordjs/rest";
|
|
12
|
+
|
|
13
|
+
//#region src/components/botColorHolder.ts
|
|
14
|
+
const DEFAULT_COLOR = "Default";
|
|
15
|
+
let readBotColor = () => void 0;
|
|
16
|
+
function bindBotColor(read) {
|
|
17
|
+
readBotColor = read;
|
|
18
|
+
}
|
|
19
|
+
function getBotColor() {
|
|
20
|
+
return readBotColor() ?? DEFAULT_COLOR;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
//#endregion
|
|
24
|
+
//#region src/components/builderTypes.ts
|
|
25
|
+
/**
|
|
26
|
+
* Available Discord.js builder classes for use with BuilderComponent for commands, embeds, modals, etc.
|
|
27
|
+
*
|
|
28
|
+
* @internal
|
|
29
|
+
*/
|
|
30
|
+
const BuilderTypes = {
|
|
31
|
+
command: SlashCommandBuilder,
|
|
32
|
+
context_menu: ContextMenuCommandBuilder,
|
|
33
|
+
subcommand: SlashCommandSubcommandBuilder,
|
|
34
|
+
group: SlashCommandSubcommandGroupBuilder,
|
|
35
|
+
embed: EmbedBuilder,
|
|
36
|
+
modal: ModalBuilder,
|
|
37
|
+
label: LabelBuilder,
|
|
38
|
+
text_input: TextInputBuilder,
|
|
39
|
+
file_upload: FileUploadBuilder,
|
|
40
|
+
checkbox: CheckboxBuilder,
|
|
41
|
+
checkbox_group: CheckboxGroupBuilder,
|
|
42
|
+
checkbox_group_option: CheckboxGroupOptionBuilder,
|
|
43
|
+
radio_group: RadioGroupBuilder,
|
|
44
|
+
radio_group_option: RadioGroupOptionBuilder,
|
|
45
|
+
button: ButtonBuilder,
|
|
46
|
+
menu_string: StringSelectMenuBuilder,
|
|
47
|
+
menu_option_string: StringSelectMenuOptionBuilder,
|
|
48
|
+
menu_user: UserSelectMenuBuilder,
|
|
49
|
+
menu_channel: ChannelSelectMenuBuilder,
|
|
50
|
+
menu_mentionable: MentionableSelectMenuBuilder,
|
|
51
|
+
menu_role: RoleSelectMenuBuilder,
|
|
52
|
+
container: ContainerBuilder,
|
|
53
|
+
text_display: TextDisplayBuilder,
|
|
54
|
+
file: FileBuilder,
|
|
55
|
+
media: MediaGalleryBuilder,
|
|
56
|
+
section: SectionBuilder,
|
|
57
|
+
separator: SeparatorBuilder
|
|
58
|
+
};
|
|
59
|
+
/**
|
|
60
|
+
* Available Discord.js action row classes for use with RowComponent for Select Menus and Buttons
|
|
61
|
+
*
|
|
62
|
+
* @internal
|
|
63
|
+
*/
|
|
64
|
+
const RowTypes = {
|
|
65
|
+
button: ActionRowBuilder,
|
|
66
|
+
menu_string: ActionRowBuilder,
|
|
67
|
+
menu_user: ActionRowBuilder,
|
|
68
|
+
menu_channel: ActionRowBuilder,
|
|
69
|
+
menu_mentionable: ActionRowBuilder,
|
|
70
|
+
menu_role: ActionRowBuilder
|
|
71
|
+
};
|
|
72
|
+
|
|
73
|
+
//#endregion
|
|
74
|
+
//#region src/components/colors.ts
|
|
75
|
+
const Colors = {
|
|
76
|
+
Aqua: 1752220,
|
|
77
|
+
Blue: 3447003,
|
|
78
|
+
Blurple: 5793266,
|
|
79
|
+
DarkAqua: 1146986,
|
|
80
|
+
DarkBlue: 2123412,
|
|
81
|
+
DarkButNotBlack: 2895667,
|
|
82
|
+
DarkerGrey: 8359053,
|
|
83
|
+
DarkGold: 12745742,
|
|
84
|
+
DarkGreen: 2067276,
|
|
85
|
+
DarkGrey: 9936031,
|
|
86
|
+
DarkNavy: 2899536,
|
|
87
|
+
DarkOrange: 11027200,
|
|
88
|
+
DarkPurple: 7419530,
|
|
89
|
+
DarkRed: 10038562,
|
|
90
|
+
DarkVividPink: 11342935,
|
|
91
|
+
Default: 0,
|
|
92
|
+
Fuchsia: 15418782,
|
|
93
|
+
Gold: 15844367,
|
|
94
|
+
Green: 5763719,
|
|
95
|
+
Grey: 9807270,
|
|
96
|
+
Greyple: 10070709,
|
|
97
|
+
LightGrey: 12370112,
|
|
98
|
+
LuminousVividPink: 15277667,
|
|
99
|
+
Navy: 3426654,
|
|
100
|
+
NotQuiteBlack: 2303786,
|
|
101
|
+
Orange: 15105570,
|
|
102
|
+
Purple: 10181046,
|
|
103
|
+
Red: 15548997,
|
|
104
|
+
White: 16777215,
|
|
105
|
+
Yellow: 16705372
|
|
106
|
+
};
|
|
107
|
+
|
|
108
|
+
//#endregion
|
|
109
|
+
//#region src/components/resolveColor.ts
|
|
110
|
+
const MAX_COLOR = 16777215;
|
|
111
|
+
const RED_SHIFT = 16;
|
|
112
|
+
const GREEN_SHIFT = 8;
|
|
113
|
+
const palette = Colors;
|
|
114
|
+
/**
|
|
115
|
+
* Resolves a {@link BotColor} to the integer Discord expects.
|
|
116
|
+
*
|
|
117
|
+
* Ported from discord.js (Apache-2.0), `resolveColor` in src/util/Util.js.
|
|
118
|
+
*/
|
|
119
|
+
function resolveColor(color) {
|
|
120
|
+
let resolved;
|
|
121
|
+
if (typeof color === "string") {
|
|
122
|
+
if (color === "Random") return Math.floor(Math.random() * 16777216);
|
|
123
|
+
if (color === "Default") return 0;
|
|
124
|
+
if (/^#?[\da-f]{6}$/i.test(color)) return Number.parseInt(color.replace("#", ""), 16);
|
|
125
|
+
resolved = palette[color];
|
|
126
|
+
} else if (typeof color === "number") resolved = color;
|
|
127
|
+
else resolved = (color[0] << RED_SHIFT) + (color[1] << GREEN_SHIFT) + color[2];
|
|
128
|
+
if (resolved === void 0 || !Number.isSafeInteger(resolved)) throw new SeedcordTypeError(SeedcordErrorCode.ColorUnresolvable, [JSON.stringify(color)]);
|
|
129
|
+
if (resolved < 0 || resolved > MAX_COLOR) throw new SeedcordRangeError(SeedcordErrorCode.ColorOutOfRange, [resolved]);
|
|
130
|
+
return resolved;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
//#endregion
|
|
134
|
+
//#region src/components/Component.ts
|
|
135
|
+
/** @internal */
|
|
136
|
+
var BaseComponent = class {
|
|
137
|
+
_component;
|
|
138
|
+
constructor(ComponentClass) {
|
|
139
|
+
this._component = new ComponentClass();
|
|
140
|
+
}
|
|
141
|
+
/**
|
|
142
|
+
* The wrapped builder, for calling Discord.js methods like setTitle() and setDescription() inside a subclass.
|
|
143
|
+
*
|
|
144
|
+
* @example this.instance.setTitle('My Modal')
|
|
145
|
+
*/
|
|
146
|
+
get instance() {
|
|
147
|
+
return this._component;
|
|
148
|
+
}
|
|
149
|
+
};
|
|
150
|
+
/**
|
|
151
|
+
* Base class for Discord.js builder components
|
|
152
|
+
*
|
|
153
|
+
* Wraps Discord.js builders (SlashCommandBuilder, EmbedBuilder, etc.) with
|
|
154
|
+
* Seedcord-specific defaults and helper methods.
|
|
155
|
+
*
|
|
156
|
+
* @typeParam BuilderKey - The type of Discord.js builder being wrapped
|
|
157
|
+
*/
|
|
158
|
+
var BuilderComponent = class extends BaseComponent {
|
|
159
|
+
type;
|
|
160
|
+
colorApplied = false;
|
|
161
|
+
constructor(type) {
|
|
162
|
+
const ComponentClass = BuilderTypes[type];
|
|
163
|
+
super(ComponentClass);
|
|
164
|
+
this.type = type;
|
|
165
|
+
if (this.instance instanceof SlashCommandBuilder || this.instance instanceof ContextMenuCommandBuilder) this.instance.setContexts(InteractionContextType.Guild);
|
|
166
|
+
}
|
|
167
|
+
get component() {
|
|
168
|
+
this.applyBotColor();
|
|
169
|
+
return this.instance;
|
|
170
|
+
}
|
|
171
|
+
applyBotColor() {
|
|
172
|
+
if (this.colorApplied) return;
|
|
173
|
+
this.colorApplied = true;
|
|
174
|
+
const color = getBotColor();
|
|
175
|
+
if (this.instance instanceof EmbedBuilder) {
|
|
176
|
+
if (this.instance.data.color === void 0) this.instance.setColor(resolveColor(color));
|
|
177
|
+
} else if (this.instance instanceof ContainerBuilder) {
|
|
178
|
+
const accent = this.instance.data.accent_color;
|
|
179
|
+
if (accent === null || accent === void 0) this.instance.setAccentColor(color === "Default" ? void 0 : resolveColor(color));
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
};
|
|
183
|
+
const BUILDER_COMPONENT = Symbol.for("seedcord:core:builder-component");
|
|
184
|
+
Object.defineProperty(BuilderComponent.prototype, BUILDER_COMPONENT, { value: true });
|
|
185
|
+
/** @internal */
|
|
186
|
+
function isBuilderComponentClass(value) {
|
|
187
|
+
if (typeof value !== "function") return false;
|
|
188
|
+
const proto = value.prototype;
|
|
189
|
+
return typeof proto === "object" && proto !== null && BUILDER_COMPONENT in proto;
|
|
190
|
+
}
|
|
191
|
+
/**
|
|
192
|
+
* Base class for Discord action row components
|
|
193
|
+
*
|
|
194
|
+
* Wraps Discord.js action row builder with Seedcord-specific defaults and helper methods.
|
|
195
|
+
*
|
|
196
|
+
* @typeParam RowKey - The Discord.js action row type being wrapped
|
|
197
|
+
*/
|
|
198
|
+
var RowComponent = class extends BaseComponent {
|
|
199
|
+
type;
|
|
200
|
+
constructor(type) {
|
|
201
|
+
const ComponentClass = RowTypes[type];
|
|
202
|
+
super(ComponentClass);
|
|
203
|
+
this.type = type;
|
|
204
|
+
}
|
|
205
|
+
get component() {
|
|
206
|
+
return this.instance;
|
|
207
|
+
}
|
|
208
|
+
};
|
|
209
|
+
|
|
210
|
+
//#endregion
|
|
211
|
+
//#region src/metadataKeys.ts
|
|
212
|
+
/**
|
|
213
|
+
* Every interaction kind seedcord routes.
|
|
214
|
+
*/
|
|
215
|
+
let InteractionKind = /* @__PURE__ */ function(InteractionKind) {
|
|
216
|
+
InteractionKind["Slash"] = "slash";
|
|
217
|
+
InteractionKind["Button"] = "button";
|
|
218
|
+
InteractionKind["Modal"] = "modal";
|
|
219
|
+
InteractionKind["StringMenu"] = "stringMenu";
|
|
220
|
+
InteractionKind["UserMenu"] = "userMenu";
|
|
221
|
+
InteractionKind["RoleMenu"] = "roleMenu";
|
|
222
|
+
InteractionKind["ChannelMenu"] = "channelMenu";
|
|
223
|
+
InteractionKind["MentionableMenu"] = "mentionableMenu";
|
|
224
|
+
InteractionKind["MessageContextMenu"] = "messageContextMenu";
|
|
225
|
+
InteractionKind["UserContextMenu"] = "userContextMenu";
|
|
226
|
+
InteractionKind["Autocomplete"] = "autocomplete";
|
|
227
|
+
return InteractionKind;
|
|
228
|
+
}({});
|
|
229
|
+
const CommandMetadataKey = Symbol.for("seedcord:command:metadata");
|
|
230
|
+
const InteractionMetadataKey = Symbol.for("seedcord:interaction:metadata");
|
|
231
|
+
const InteractionMiddlewareMetadataKey = Symbol.for("seedcord:middleware:interaction:metadata");
|
|
232
|
+
const EventMiddlewareMetadataKey = Symbol.for("seedcord:middleware:event:metadata");
|
|
233
|
+
const SubscribeMetadataKey = Symbol.for("seedcord:subscribe:metadata");
|
|
234
|
+
const EventMetadataKey = Symbol.for("seedcord:event:metadata");
|
|
235
|
+
const GatedMetadataKey = Symbol.for("seedcord:gated:metadata");
|
|
236
|
+
const WebhookUrlMetadataKey = Symbol.for("seedcord:webhook-url:metadata");
|
|
237
|
+
const InteractionRouteKeys = {
|
|
238
|
+
["slash"]: Symbol.for("seedcord:interaction:slash"),
|
|
239
|
+
["button"]: Symbol.for("seedcord:interaction:button"),
|
|
240
|
+
["modal"]: Symbol.for("seedcord:interaction:modal"),
|
|
241
|
+
["stringMenu"]: Symbol.for("seedcord:interaction:string-menu"),
|
|
242
|
+
["userMenu"]: Symbol.for("seedcord:interaction:user-menu"),
|
|
243
|
+
["roleMenu"]: Symbol.for("seedcord:interaction:role-menu"),
|
|
244
|
+
["channelMenu"]: Symbol.for("seedcord:interaction:channel-menu"),
|
|
245
|
+
["mentionableMenu"]: Symbol.for("seedcord:interaction:mentionable-menu"),
|
|
246
|
+
["messageContextMenu"]: Symbol.for("seedcord:interaction:message-context-menu"),
|
|
247
|
+
["userContextMenu"]: Symbol.for("seedcord:interaction:user-context-menu"),
|
|
248
|
+
["autocomplete"]: Symbol.for("seedcord:interaction:autocomplete")
|
|
249
|
+
};
|
|
250
|
+
|
|
251
|
+
//#endregion
|
|
252
|
+
//#region src/subscribers/publishDefault.ts
|
|
253
|
+
/** @internal PublishableKey excludes this key so publish() never emits it externally. */
|
|
254
|
+
const PublishDefault = Symbol("seedcord:bus:publish-default");
|
|
255
|
+
|
|
256
|
+
//#endregion
|
|
257
|
+
//#region src/lifecycle/phases.ts
|
|
258
|
+
/**
|
|
259
|
+
* Startup phases, in run order.
|
|
260
|
+
*/
|
|
261
|
+
let StartupPhase = /* @__PURE__ */ function(StartupPhase) {
|
|
262
|
+
/** Nothing connected. Plugin init runs here by default. */
|
|
263
|
+
StartupPhase[StartupPhase["Configuration"] = 1] = "Configuration";
|
|
264
|
+
/** The gateway session opens, and http runs its REST-only startup work. */
|
|
265
|
+
StartupPhase[StartupPhase["Login"] = 2] = "Login";
|
|
266
|
+
/** Handlers are live and interactions dispatch. */
|
|
267
|
+
StartupPhase[StartupPhase["Ready"] = 3] = "Ready";
|
|
268
|
+
return StartupPhase;
|
|
269
|
+
}({});
|
|
270
|
+
/**
|
|
271
|
+
* Shutdown phases, in run order.
|
|
272
|
+
*/
|
|
273
|
+
let ShutdownPhase = /* @__PURE__ */ function(ShutdownPhase) {
|
|
274
|
+
/** Stop taking new interactions and requests. */
|
|
275
|
+
ShutdownPhase[ShutdownPhase["Unbind"] = 1] = "Unbind";
|
|
276
|
+
/** Waits for in-flight work to settle and stops internal services. */
|
|
277
|
+
ShutdownPhase[ShutdownPhase["Drain"] = 2] = "Drain";
|
|
278
|
+
/** External resources close. Plugin dispose runs here by default. */
|
|
279
|
+
ShutdownPhase[ShutdownPhase["Disconnect"] = 3] = "Disconnect";
|
|
280
|
+
/** The client disconnects last so in-flight handlers can still reference it during drain. */
|
|
281
|
+
ShutdownPhase[ShutdownPhase["Logout"] = 4] = "Logout";
|
|
282
|
+
/**
|
|
283
|
+
* Resources seedcord holds for the bot, like the `config.kv` driver, close after every plugin
|
|
284
|
+
* has stopped. Only seedcord runs work here.
|
|
285
|
+
*/
|
|
286
|
+
ShutdownPhase[ShutdownPhase["Release"] = 5] = "Release";
|
|
287
|
+
return ShutdownPhase;
|
|
288
|
+
}({});
|
|
289
|
+
|
|
290
|
+
//#endregion
|
|
291
|
+
//#region src/kv/MemoryDriver.ts
|
|
292
|
+
const SWEEP_GAP_MS = 6e4;
|
|
293
|
+
/**
|
|
294
|
+
* The default `config.kv`. It keeps every key in a `Map` and loses them on restart. On serverless,
|
|
295
|
+
* each running copy keeps its own.
|
|
296
|
+
*/
|
|
297
|
+
var MemoryDriver = class {
|
|
298
|
+
#entries = /* @__PURE__ */ new Map();
|
|
299
|
+
#lastSweep = Date.now();
|
|
300
|
+
get(key) {
|
|
301
|
+
this.#maybeSweep();
|
|
302
|
+
return this.#live(key)?.value;
|
|
303
|
+
}
|
|
304
|
+
set(key, value, ttlMs) {
|
|
305
|
+
this.#maybeSweep();
|
|
306
|
+
this.#entries.set(key, {
|
|
307
|
+
value,
|
|
308
|
+
expiresAt: ttlMs === void 0 ? void 0 : Date.now() + ttlMs
|
|
309
|
+
});
|
|
310
|
+
}
|
|
311
|
+
delete(key) {
|
|
312
|
+
this.#entries.delete(key);
|
|
313
|
+
}
|
|
314
|
+
*entries(prefix) {
|
|
315
|
+
this.#maybeSweep();
|
|
316
|
+
for (const key of this.#entries.keys()) {
|
|
317
|
+
const entry = key.startsWith(prefix) ? this.#live(key) : void 0;
|
|
318
|
+
if (entry) yield [key, entry.value];
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
[Symbol.dispose]() {
|
|
322
|
+
this.#entries.clear();
|
|
323
|
+
}
|
|
324
|
+
#live(key) {
|
|
325
|
+
const entry = this.#entries.get(key);
|
|
326
|
+
if (entry?.expiresAt !== void 0 && entry.expiresAt <= Date.now()) {
|
|
327
|
+
this.#entries.delete(key);
|
|
328
|
+
return;
|
|
329
|
+
}
|
|
330
|
+
return entry;
|
|
331
|
+
}
|
|
332
|
+
#maybeSweep() {
|
|
333
|
+
const now = Date.now();
|
|
334
|
+
if (now - this.#lastSweep < SWEEP_GAP_MS) return;
|
|
335
|
+
this.#lastSweep = now;
|
|
336
|
+
for (const key of this.#entries.keys()) this.#live(key);
|
|
337
|
+
}
|
|
338
|
+
};
|
|
339
|
+
|
|
340
|
+
//#endregion
|
|
341
|
+
//#region src/dispatch/OnceTracker.ts
|
|
342
|
+
var OnceTracker = class {
|
|
343
|
+
spent = /* @__PURE__ */ new WeakMap();
|
|
344
|
+
isSpent(entry, key) {
|
|
345
|
+
return entry.frequency === "once" && (this.spent.get(entry.ctor)?.has(key) ?? false);
|
|
346
|
+
}
|
|
347
|
+
claim(entry, key) {
|
|
348
|
+
if (entry.frequency !== "once") return true;
|
|
349
|
+
const keys = this.spent.get(entry.ctor) ?? /* @__PURE__ */ new Set();
|
|
350
|
+
if (keys.has(key)) return false;
|
|
351
|
+
this.spent.set(entry.ctor, keys.add(key));
|
|
352
|
+
return true;
|
|
353
|
+
}
|
|
354
|
+
};
|
|
355
|
+
|
|
356
|
+
//#endregion
|
|
357
|
+
//#region src/reply/flags.ts
|
|
358
|
+
function sendFlags(opts) {
|
|
359
|
+
let flags = MessageFlags.IsComponentsV2;
|
|
360
|
+
if (opts?.ephemeral ?? true) flags |= MessageFlags.Ephemeral;
|
|
361
|
+
if (opts?.silent) flags |= MessageFlags.SuppressNotifications;
|
|
362
|
+
return flags;
|
|
363
|
+
}
|
|
364
|
+
function deferFlags(opts) {
|
|
365
|
+
return opts?.ephemeral ?? true ? MessageFlags.Ephemeral : 0;
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
//#endregion
|
|
369
|
+
//#region src/subscribers/ReportThrottle.ts
|
|
370
|
+
var ReportThrottle = class ReportThrottle {
|
|
371
|
+
windowMs;
|
|
372
|
+
now;
|
|
373
|
+
static perCore = /* @__PURE__ */ new WeakMap();
|
|
374
|
+
static for(core) {
|
|
375
|
+
let throttle = ReportThrottle.perCore.get(core);
|
|
376
|
+
if (!throttle) {
|
|
377
|
+
throttle = new ReportThrottle();
|
|
378
|
+
ReportThrottle.perCore.set(core, throttle);
|
|
379
|
+
}
|
|
380
|
+
return throttle;
|
|
381
|
+
}
|
|
382
|
+
windows = /* @__PURE__ */ new Map();
|
|
383
|
+
constructor(windowMs = 6e4, now = () => Date.now()) {
|
|
384
|
+
this.windowMs = windowMs;
|
|
385
|
+
this.now = now;
|
|
386
|
+
}
|
|
387
|
+
take(key) {
|
|
388
|
+
const window = this.windows.get(key);
|
|
389
|
+
if (window && this.now() - window.lastSentAt < this.windowMs) {
|
|
390
|
+
window.suppressedSinceSend += 1;
|
|
391
|
+
return null;
|
|
392
|
+
}
|
|
393
|
+
const suppressed = window?.suppressedSinceSend ?? 0;
|
|
394
|
+
this.windows.set(key, {
|
|
395
|
+
lastSentAt: this.now(),
|
|
396
|
+
suppressedSinceSend: 0
|
|
397
|
+
});
|
|
398
|
+
return suppressed;
|
|
399
|
+
}
|
|
400
|
+
restore(key, suppressed) {
|
|
401
|
+
const window = this.windows.get(key);
|
|
402
|
+
if (window) window.suppressedSinceSend += suppressed + 1;
|
|
403
|
+
}
|
|
404
|
+
};
|
|
405
|
+
|
|
406
|
+
//#endregion
|
|
407
|
+
//#region src/subscribers/Subscriber.ts
|
|
408
|
+
/**
|
|
409
|
+
* Abstract base class for handling application subscribers.
|
|
410
|
+
*
|
|
411
|
+
* Provides type-safe access to subscribers data and the core framework instance.
|
|
412
|
+
* Extend this class to create custom subscriber handlers.
|
|
413
|
+
*
|
|
414
|
+
* @typeParam KeyOfSubscribers - The specific subscriber type this handler processes
|
|
415
|
+
* @typeParam TCore - The transport's Core
|
|
416
|
+
*/
|
|
417
|
+
var Subscriber = class {
|
|
418
|
+
data;
|
|
419
|
+
core;
|
|
420
|
+
logger;
|
|
421
|
+
/**
|
|
422
|
+
* Instantiates the subscriber with event data and core.
|
|
423
|
+
*
|
|
424
|
+
* @param data - The subscriber event data
|
|
425
|
+
* @param core - The core framework instance
|
|
426
|
+
*/
|
|
427
|
+
constructor(data, core) {
|
|
428
|
+
this.data = data;
|
|
429
|
+
this.core = core;
|
|
430
|
+
this.logger = new Logger(this.constructor.name, { channel: "subscribers" });
|
|
431
|
+
}
|
|
432
|
+
};
|
|
433
|
+
|
|
434
|
+
//#endregion
|
|
435
|
+
//#region src/subscribers/bases/webhookHelpers.ts
|
|
436
|
+
const DISCORD_WEBHOOK_REGEX = new RegExp(String.raw`^https?:\/\/(?:canary\.|ptb\.)?discord(?:app)?\.com\/api\/webhooks\/\d+\/[\w$-]+$`);
|
|
437
|
+
function isDiscordWebhookUrl(value) {
|
|
438
|
+
return URL.canParse(value) && DISCORD_WEBHOOK_REGEX.test(value);
|
|
439
|
+
}
|
|
440
|
+
function jsonAttachment(name, description, data) {
|
|
441
|
+
const content = filterCirculars(data);
|
|
442
|
+
return {
|
|
443
|
+
name,
|
|
444
|
+
description,
|
|
445
|
+
data: new TextEncoder().encode(JSON.stringify(content, void 0, 2))
|
|
446
|
+
};
|
|
447
|
+
}
|
|
448
|
+
function breakBackticks(text) {
|
|
449
|
+
return text.replaceAll("```", "```");
|
|
450
|
+
}
|
|
451
|
+
const REPORT_BUDGET = 1800;
|
|
452
|
+
function body(value) {
|
|
453
|
+
const raw = Error.isError(value) ? value.stack ?? `${value.name}: ${value.message}` : String(value);
|
|
454
|
+
return breakBackticks(stripAnsi(raw));
|
|
455
|
+
}
|
|
456
|
+
function clamp(text, budget) {
|
|
457
|
+
if (text.length <= budget) return text;
|
|
458
|
+
return budget > 0 ? `${text.slice(0, budget - 1)}…` : "";
|
|
459
|
+
}
|
|
460
|
+
function omittedLine(count) {
|
|
461
|
+
return `\n\nand ${count} more ${pluralize(count, "failure")}`;
|
|
462
|
+
}
|
|
463
|
+
function memberReport(members, budget) {
|
|
464
|
+
const room = Math.max(budget - omittedLine(members.length).length, 0);
|
|
465
|
+
const share = Math.floor(room / members.length);
|
|
466
|
+
let report = "";
|
|
467
|
+
let shown = 0;
|
|
468
|
+
for (const [index, member] of members.entries()) {
|
|
469
|
+
const heading = `\n\nFailure ${index + 1} of ${members.length}:\n`;
|
|
470
|
+
const entry = heading + clamp(body(member), Math.max(share - heading.length, 0));
|
|
471
|
+
if (report.length + entry.length > room) break;
|
|
472
|
+
report += entry;
|
|
473
|
+
shown++;
|
|
474
|
+
}
|
|
475
|
+
const hidden = members.length - shown;
|
|
476
|
+
return hidden > 0 ? report + omittedLine(hidden) : report;
|
|
477
|
+
}
|
|
478
|
+
function errorReport(error) {
|
|
479
|
+
let head = body(error);
|
|
480
|
+
if (Error.isError(error.cause)) head += `\n\nCaused by:\n${body(error.cause)}`;
|
|
481
|
+
const members = error instanceof AggregateError ? error.errors : [];
|
|
482
|
+
if (members.length === 0) return clamp(head, REPORT_BUDGET);
|
|
483
|
+
const report = clamp(head, REPORT_BUDGET - omittedLine(members.length).length);
|
|
484
|
+
return report + memberReport(members, REPORT_BUDGET - report.length);
|
|
485
|
+
}
|
|
486
|
+
var WebhookSeparator = class extends BuilderComponent {
|
|
487
|
+
constructor() {
|
|
488
|
+
super("separator");
|
|
489
|
+
this.instance.setSpacing(SeparatorSpacingSize.Small).setDivider(true);
|
|
490
|
+
}
|
|
491
|
+
};
|
|
492
|
+
|
|
493
|
+
//#endregion
|
|
494
|
+
//#region src/subscribers/bases/WebhookSender.ts
|
|
495
|
+
const HTTP_NOT_FOUND = 404;
|
|
496
|
+
const HTTP_UNAUTHORIZED = 401;
|
|
497
|
+
var WebhookSender = class {
|
|
498
|
+
rest = new REST();
|
|
499
|
+
route;
|
|
500
|
+
constructor(url) {
|
|
501
|
+
const match = /\/webhooks\/(\d+)\/([\w$-]+)$/.exec(url);
|
|
502
|
+
if (!match?.[1] || !match[2]) throw new SeedcordTypeError(SeedcordErrorCode.CoreWebhookUrlInvalid, [new.target.name]);
|
|
503
|
+
this.route = Routes.webhook(match[1], match[2]);
|
|
504
|
+
}
|
|
505
|
+
async verify() {
|
|
506
|
+
try {
|
|
507
|
+
await this.rest.get(this.route, { auth: false });
|
|
508
|
+
return "ok";
|
|
509
|
+
} catch (error) {
|
|
510
|
+
return error instanceof DiscordAPIError && (error.status === HTTP_NOT_FOUND || error.status === HTTP_UNAUTHORIZED) ? "missing" : "unreachable";
|
|
511
|
+
}
|
|
512
|
+
}
|
|
513
|
+
async send(options) {
|
|
514
|
+
const { flags, username, avatarUrl, components, files } = options;
|
|
515
|
+
await this.rest.post(this.route, {
|
|
516
|
+
auth: false,
|
|
517
|
+
query: new URLSearchParams({
|
|
518
|
+
with_components: "true",
|
|
519
|
+
wait: "true"
|
|
520
|
+
}),
|
|
521
|
+
body: {
|
|
522
|
+
flags,
|
|
523
|
+
username,
|
|
524
|
+
...avatarUrl && { avatar_url: avatarUrl },
|
|
525
|
+
components: components.map((component) => component.toJSON()),
|
|
526
|
+
...files?.length && { attachments: files.map((file, id) => ({
|
|
527
|
+
id,
|
|
528
|
+
filename: file.name,
|
|
529
|
+
description: file.description
|
|
530
|
+
})) }
|
|
531
|
+
},
|
|
532
|
+
...files?.length && { files: files.map((file) => ({
|
|
533
|
+
name: file.name,
|
|
534
|
+
data: file.data
|
|
535
|
+
})) }
|
|
536
|
+
});
|
|
537
|
+
}
|
|
538
|
+
};
|
|
539
|
+
|
|
540
|
+
//#endregion
|
|
541
|
+
//#region src/subscribers/bases/WebhookLog.ts
|
|
542
|
+
/**
|
|
543
|
+
* Base class for subscribers that deliver their event to a Discord webhook.
|
|
544
|
+
*
|
|
545
|
+
* Declare the url's environment variable with `@WebhookUrl` and implement {@link report}. The base
|
|
546
|
+
* resolves the url, validates it, reuses one sender per url, and sends. Registration skips a reporter
|
|
547
|
+
* whose variable is unset and warns at boot.
|
|
548
|
+
*
|
|
549
|
+
* @typeParam KeyOfSubscribers - The subscription key this reporter receives
|
|
550
|
+
* @typeParam TCore - The transport's Core
|
|
551
|
+
*/
|
|
552
|
+
var WebhookLog = class WebhookLog extends Subscriber {
|
|
553
|
+
static senders = /* @__PURE__ */ new Map();
|
|
554
|
+
/**
|
|
555
|
+
* Events sharing this key collapse into one card per minute. Return `null` to send every event.
|
|
556
|
+
*/
|
|
557
|
+
throttleKey() {
|
|
558
|
+
return null;
|
|
559
|
+
}
|
|
560
|
+
async execute() {
|
|
561
|
+
const envKey = WebhookLog.envKeyOf(this.constructor);
|
|
562
|
+
const url = WebhookLog.urlOf(envKey);
|
|
563
|
+
if (url === null) throw new SeedcordError(SeedcordErrorCode.ConfigMissingEnv, [envKey]);
|
|
564
|
+
const key = this.throttleKey();
|
|
565
|
+
const throttle = ReportThrottle.for(this.core);
|
|
566
|
+
const suppressed = key === null ? 0 : throttle.take(key);
|
|
567
|
+
if (suppressed === null) {
|
|
568
|
+
this.logger.trace(`counted a repeat into the next ${paint.sky.bold(this.constructor.name)} card`);
|
|
569
|
+
return;
|
|
570
|
+
}
|
|
571
|
+
try {
|
|
572
|
+
const { username, avatarUrl, components, files } = await this.report(suppressed);
|
|
573
|
+
await WebhookLog.senderFor(url).send({
|
|
574
|
+
flags: sendFlags({ ephemeral: false }),
|
|
575
|
+
username: username ?? this.constructor.name,
|
|
576
|
+
avatarUrl,
|
|
577
|
+
components,
|
|
578
|
+
files
|
|
579
|
+
});
|
|
580
|
+
} catch (error) {
|
|
581
|
+
if (key !== null) throttle.restore(key, suppressed);
|
|
582
|
+
this.logger.error("Webhook report failed", error);
|
|
583
|
+
}
|
|
584
|
+
}
|
|
585
|
+
/** @internal */
|
|
586
|
+
static senderFor(url) {
|
|
587
|
+
let sender = WebhookLog.senders.get(url);
|
|
588
|
+
if (!sender) {
|
|
589
|
+
sender = new WebhookSender(url);
|
|
590
|
+
WebhookLog.senders.set(url, sender);
|
|
591
|
+
}
|
|
592
|
+
return sender;
|
|
593
|
+
}
|
|
594
|
+
/** @internal */
|
|
595
|
+
static envKeyOf(ctor) {
|
|
596
|
+
const envKey = Reflect.getMetadata(WebhookUrlMetadataKey, ctor);
|
|
597
|
+
if (!envKey) throw new SeedcordTypeError(SeedcordErrorCode.DecoratorWebhookUrlMissing, [ctor.name]);
|
|
598
|
+
return envKey;
|
|
599
|
+
}
|
|
600
|
+
/** @internal Returns null when the env var is unset, throws when set but malformed. */
|
|
601
|
+
static urlOf(envKey) {
|
|
602
|
+
const raw = Envapter.get(envKey)?.trim();
|
|
603
|
+
if (!raw) return null;
|
|
604
|
+
if (!isDiscordWebhookUrl(raw)) throw new SeedcordError(SeedcordErrorCode.ConfigInvalidEnv, [envKey, "the webhook URL from the channel's Integrations settings"]);
|
|
605
|
+
return raw;
|
|
606
|
+
}
|
|
607
|
+
};
|
|
608
|
+
|
|
609
|
+
//#endregion
|
|
610
|
+
//#region src/subscribers/decorators/Subscribe.ts
|
|
611
|
+
/**
|
|
612
|
+
* Registers a subscriber handler class with a specific subscriber event.
|
|
613
|
+
*
|
|
614
|
+
* Associates the decorated class with a subscriber event type for automatic
|
|
615
|
+
* registration and execution when the subscriber is emitted.
|
|
616
|
+
*
|
|
617
|
+
* @typeParam TSubscriber - The subscriber event name to register for
|
|
618
|
+
* @param subscriber - The subscriber event name to register for
|
|
619
|
+
* @param options - Options to configure the subscriber handler registration.
|
|
620
|
+
* @decorator
|
|
621
|
+
* @example
|
|
622
|
+
* ```typescript
|
|
623
|
+
* \@Subscribe('userJoin')
|
|
624
|
+
* class WelcomeHandler extends Subscriber<'userJoin'> {
|
|
625
|
+
* async execute() {
|
|
626
|
+
* }
|
|
627
|
+
* }
|
|
628
|
+
* ```
|
|
629
|
+
* @example
|
|
630
|
+
* ```ts
|
|
631
|
+
* \@Subscribe('userJoin', { frequency: 'once' })
|
|
632
|
+
* // or
|
|
633
|
+
* \@Subscribe('userJoin')
|
|
634
|
+
* ```
|
|
635
|
+
*/
|
|
636
|
+
function Subscribe(subscriber, options) {
|
|
637
|
+
return function(constructor) {
|
|
638
|
+
const meta = {
|
|
639
|
+
subscriber,
|
|
640
|
+
frequency: options?.frequency
|
|
641
|
+
};
|
|
642
|
+
Reflect.defineMetadata(SubscribeMetadataKey, meta, constructor);
|
|
643
|
+
};
|
|
644
|
+
}
|
|
645
|
+
|
|
646
|
+
//#endregion
|
|
647
|
+
//#region src/subscribers/decorators/WebhookUrl.ts
|
|
648
|
+
/**
|
|
649
|
+
* Declares the environment variable a {@link WebhookLog} reporter reads its webhook url from.
|
|
650
|
+
*
|
|
651
|
+
* An unset variable disables the reporter with a boot warning. A set but malformed value throws
|
|
652
|
+
* at boot.
|
|
653
|
+
*
|
|
654
|
+
* @param envKey - The environment variable name holding the webhook url
|
|
655
|
+
* @decorator
|
|
656
|
+
* @example
|
|
657
|
+
* ```ts
|
|
658
|
+
* \@Subscribe('memberBanned')
|
|
659
|
+
* \@WebhookUrl('BAN_LOG_WEBHOOK_URL')
|
|
660
|
+
* class BanLog extends WebhookLog<'memberBanned'> {
|
|
661
|
+
* report() {
|
|
662
|
+
* return { components: [new BanCard(this.data).component] };
|
|
663
|
+
* }
|
|
664
|
+
* }
|
|
665
|
+
* ```
|
|
666
|
+
*/
|
|
667
|
+
function WebhookUrl(envKey) {
|
|
668
|
+
return function(constructor) {
|
|
669
|
+
Reflect.defineMetadata(WebhookUrlMetadataKey, envKey, constructor);
|
|
670
|
+
};
|
|
671
|
+
}
|
|
672
|
+
|
|
673
|
+
//#endregion
|
|
674
|
+
//#region \0@oxc-project+runtime@0.152.0/helpers/esm/decorate.js
|
|
675
|
+
function __decorate(decorators, target, key, desc) {
|
|
676
|
+
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
677
|
+
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
678
|
+
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;
|
|
679
|
+
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
680
|
+
}
|
|
681
|
+
|
|
682
|
+
//#endregion
|
|
683
|
+
//#region src/subscribers/default/HandledException.ts
|
|
684
|
+
let HandledException = class HandledException extends WebhookLog {
|
|
685
|
+
throttleKey() {
|
|
686
|
+
return `handledException:${this.data.origin}:${this.data.denial.name}`;
|
|
687
|
+
}
|
|
688
|
+
report(suppressed) {
|
|
689
|
+
return {
|
|
690
|
+
username: "Handled Exception",
|
|
691
|
+
components: [new HandledExceptionContainer(this.data, suppressed).component],
|
|
692
|
+
files: [jsonAttachment("source.json", "The raw source the fault came from", this.data.source.raw)]
|
|
693
|
+
};
|
|
694
|
+
}
|
|
695
|
+
};
|
|
696
|
+
HandledException = __decorate([Subscribe("handledException"), WebhookUrl("HANDLED_EXCEPTION_WEBHOOK_URL")], HandledException);
|
|
697
|
+
var HandledExceptionContainer = class extends BuilderComponent {
|
|
698
|
+
constructor(data, suppressed) {
|
|
699
|
+
super("container");
|
|
700
|
+
const { denial, uuid, source } = data;
|
|
701
|
+
this.instance.addTextDisplayComponents((text) => text.setContent(faultSummary(denial, source))).addSeparatorComponents(new WebhookSeparator().component).addTextDisplayComponents((text) => text.setContent(`### UUID \`${uuid}\`\n\`\`\`${breakBackticks(causeStack(denial))}\`\`\``)).addSeparatorComponents(new WebhookSeparator().component).addTextDisplayComponents((text) => text.setContent("### Source")).addFileComponents((file) => file.setURL("attachment://source.json"));
|
|
702
|
+
this.addSuppressedCount(suppressed);
|
|
703
|
+
}
|
|
704
|
+
addSuppressedCount(suppressed) {
|
|
705
|
+
if (suppressed === 0) return;
|
|
706
|
+
this.instance.addTextDisplayComponents((text) => text.setContent(`-# ${suppressed} more of these since the last report`));
|
|
707
|
+
}
|
|
708
|
+
};
|
|
709
|
+
function faultSummary(denial, source) {
|
|
710
|
+
const head = stripAnsi(`### A handled fault was reported: \`${denial.name}\`\n**Message:** ${denial.message}\n`);
|
|
711
|
+
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"}\``;
|
|
712
|
+
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}\``;
|
|
713
|
+
}
|
|
714
|
+
function causeStack(denial) {
|
|
715
|
+
const { cause } = denial;
|
|
716
|
+
if (Error.isError(cause)) return stripAnsi(cause.stack ?? cause.message);
|
|
717
|
+
if (typeof cause === "string") return stripAnsi(cause);
|
|
718
|
+
if (typeof cause === "bigint" || typeof cause === "symbol" || typeof cause === "function") return cause.toString();
|
|
719
|
+
if (cause !== void 0) try {
|
|
720
|
+
return JSON.stringify(cause);
|
|
721
|
+
} catch {
|
|
722
|
+
return "[unserializable cause]";
|
|
723
|
+
}
|
|
724
|
+
return stripAnsi(denial.stack ?? "No cause recorded.");
|
|
725
|
+
}
|
|
726
|
+
|
|
727
|
+
//#endregion
|
|
728
|
+
//#region src/subscribers/default/UnknownException.ts
|
|
729
|
+
let UnknownException = class UnknownException extends WebhookLog {
|
|
730
|
+
throttleKey() {
|
|
731
|
+
return `unknownException:${this.data.origin}:${nameOf(this.data.error)}`;
|
|
732
|
+
}
|
|
733
|
+
report(suppressed) {
|
|
734
|
+
const { metadata } = this.data;
|
|
735
|
+
return {
|
|
736
|
+
username: "Unknown Exception",
|
|
737
|
+
components: [new UnhandledErrorContainer(this.data, suppressed).component],
|
|
738
|
+
files: metadata ? [jsonAttachment("metadata.json", "Metadata associated with the error", metadata)] : void 0
|
|
739
|
+
};
|
|
740
|
+
}
|
|
741
|
+
};
|
|
742
|
+
UnknownException = __decorate([Subscribe("unknownException"), WebhookUrl("UNKNOWN_EXCEPTION_WEBHOOK_URL")], UnknownException);
|
|
743
|
+
function nameOf(error) {
|
|
744
|
+
return error.name === "Error" ? error.constructor.name : error.name;
|
|
745
|
+
}
|
|
746
|
+
var UnhandledErrorContainer = class extends BuilderComponent {
|
|
747
|
+
constructor(data, suppressed) {
|
|
748
|
+
super("container");
|
|
749
|
+
const { uuid, error, guild, user, metadata } = data;
|
|
750
|
+
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\`\`\`${errorReport(error)}\`\`\``));
|
|
751
|
+
this.addTimestampsIfAvailable(error);
|
|
752
|
+
this.addMetadataIfAvailable(metadata);
|
|
753
|
+
this.addSuppressedCount(suppressed);
|
|
754
|
+
}
|
|
755
|
+
addSuppressedCount(suppressed) {
|
|
756
|
+
if (suppressed === 0) return;
|
|
757
|
+
this.instance.addTextDisplayComponents((text) => text.setContent(`-# ${suppressed} more of these since the last report`));
|
|
758
|
+
}
|
|
759
|
+
addTimestampsIfAvailable(error) {
|
|
760
|
+
if (!(error instanceof DiscordAPIError)) return;
|
|
761
|
+
const now = Date.now();
|
|
762
|
+
const snowflake = error.url.match(/\/interactions\/(\d+)\//)?.[1];
|
|
763
|
+
if (!snowflake) return void 0;
|
|
764
|
+
const interactionTs = timestampFromSnowflake(snowflake);
|
|
765
|
+
const diff = now - interactionTs;
|
|
766
|
+
const seconds = Math.floor(diff / 1e3);
|
|
767
|
+
const millis = diff % 1e3;
|
|
768
|
+
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`));
|
|
769
|
+
}
|
|
770
|
+
addMetadataIfAvailable(metadata) {
|
|
771
|
+
if (!metadata) return;
|
|
772
|
+
this.instance.addSeparatorComponents(new WebhookSeparator().component).addTextDisplayComponents((text) => text.setContent("### Metadata")).addFileComponents((file) => file.setURL("attachment://metadata.json"));
|
|
773
|
+
}
|
|
774
|
+
};
|
|
775
|
+
|
|
776
|
+
//#endregion
|
|
777
|
+
//#region src/subscribers/slots.ts
|
|
778
|
+
const RegisterDefaults = Symbol("seedcord:bus:register-defaults");
|
|
779
|
+
const VerifyWebhooks = Symbol("seedcord:bus:verify-webhooks");
|
|
780
|
+
const RegisteredCount = Symbol("seedcord:bus:registered-count");
|
|
781
|
+
const RegisterSubscriber = Symbol("seedcord:bus:register");
|
|
782
|
+
const UnregisterSubscriber = Symbol("seedcord:bus:unregister");
|
|
783
|
+
|
|
784
|
+
//#endregion
|
|
785
|
+
//#region src/subscribers/Bus.ts
|
|
786
|
+
const loggerSlot = Symbol("seedcord:bus:logger");
|
|
787
|
+
/**
|
|
788
|
+
* Registers and dispatches subscribers. Subscribers run on a programmatic or framework publish.
|
|
789
|
+
* Accessed via `core.bus`. Do not construct it directly.
|
|
790
|
+
*/
|
|
791
|
+
var Bus = class extends TypedEventEmitter {
|
|
792
|
+
core;
|
|
793
|
+
logger = new Logger("Subscribers", { channel: "subscribers" });
|
|
794
|
+
/** @internal */
|
|
795
|
+
[loggerSlot] = this.logger;
|
|
796
|
+
subscribersMap = /* @__PURE__ */ new Map();
|
|
797
|
+
onceRuns = new OnceTracker();
|
|
798
|
+
webhookProbes = /* @__PURE__ */ new Map();
|
|
799
|
+
constructor(core) {
|
|
800
|
+
super();
|
|
801
|
+
this.core = core;
|
|
802
|
+
}
|
|
803
|
+
/** @internal keep this inside start(). a bad webhook url thrown outside it never resets the singleton guard */
|
|
804
|
+
[RegisterDefaults]() {
|
|
805
|
+
this[RegisterSubscriber](registrationFor(UnknownException));
|
|
806
|
+
this[RegisterSubscriber](registrationFor(HandledException));
|
|
807
|
+
}
|
|
808
|
+
/** @internal */
|
|
809
|
+
[RegisterSubscriber](registration) {
|
|
810
|
+
if (!this.probeWebhook(registration.ctor)) return;
|
|
811
|
+
for (const key of registration.keys) {
|
|
812
|
+
let registrations = this.subscribersMap.get(key);
|
|
813
|
+
if (!registrations) {
|
|
814
|
+
registrations = [];
|
|
815
|
+
this.subscribersMap.set(key, registrations);
|
|
816
|
+
}
|
|
817
|
+
registrations.push(registration);
|
|
818
|
+
}
|
|
819
|
+
}
|
|
820
|
+
/** @internal */
|
|
821
|
+
[UnregisterSubscriber](ctor, keys) {
|
|
822
|
+
for (const key of keys ?? [...this.subscribersMap.keys()]) {
|
|
823
|
+
const registrations = this.subscribersMap.get(key);
|
|
824
|
+
if (!registrations) continue;
|
|
825
|
+
const index = registrations.findIndex((entry) => entry.ctor === ctor);
|
|
826
|
+
if (index !== -1) registrations.splice(index, 1);
|
|
827
|
+
}
|
|
828
|
+
}
|
|
829
|
+
/** @internal */
|
|
830
|
+
get [RegisteredCount]() {
|
|
831
|
+
return [...this.subscribersMap.values()].reduce((total, entries) => total + entries.length, 0);
|
|
832
|
+
}
|
|
833
|
+
/** @internal registration already dropped every reporter with no url set */
|
|
834
|
+
async [VerifyWebhooks]() {
|
|
835
|
+
const missing = [];
|
|
836
|
+
await Promise.all([...this.webhookProbes].map(async ([url, envKeys]) => {
|
|
837
|
+
const result = await WebhookLog.senderFor(url).verify();
|
|
838
|
+
if (result === "missing") missing.push(...envKeys);
|
|
839
|
+
else if (result === "unreachable") this.logger.warn(`could not verify webhook at ${envKeys.map((key) => paint.amber.bold(key)).join(", ")}`);
|
|
840
|
+
}));
|
|
841
|
+
if (missing.length > 0) throw new SeedcordError(SeedcordErrorCode.ConfigWebhookNotFound, [missing.join(", ")]);
|
|
842
|
+
}
|
|
843
|
+
probeWebhook(ctor) {
|
|
844
|
+
if (!(ctor.prototype instanceof WebhookLog)) return true;
|
|
845
|
+
const envKey = WebhookLog.envKeyOf(ctor);
|
|
846
|
+
const url = WebhookLog.urlOf(envKey);
|
|
847
|
+
if (url === null) {
|
|
848
|
+
this.logger.warn(`${paint.sky.bold(ctor.name)} disabled, ${paint.amber.bold(envKey)} is not set`);
|
|
849
|
+
return false;
|
|
850
|
+
}
|
|
851
|
+
const envKeys = this.webhookProbes.get(url) ?? [];
|
|
852
|
+
if (!envKeys.includes(envKey)) envKeys.push(envKey);
|
|
853
|
+
this.webhookProbes.set(url, envKeys);
|
|
854
|
+
return true;
|
|
855
|
+
}
|
|
856
|
+
/**
|
|
857
|
+
* Publishes an event to its subscribers and native listeners.
|
|
858
|
+
*
|
|
859
|
+
* Fire-and-forget. Subscriber handlers run asynchronously and this returns before they finish.
|
|
860
|
+
* Errors thrown by a subscriber or by an `on()` listener are caught and logged, never surfaced
|
|
861
|
+
* here. One throwing listener does not stop the others. Subscribers on one key run concurrently
|
|
862
|
+
* and carry no ordering guarantee. A `'once'` subscriber is marked as executed when it starts,
|
|
863
|
+
* even if it throws. It never runs twice.
|
|
864
|
+
*
|
|
865
|
+
* The framework's own keys are excluded. Subscribe to those and listen with `on`. The framework
|
|
866
|
+
* is their only publisher.
|
|
867
|
+
*
|
|
868
|
+
* @param event - The subscription key to publish
|
|
869
|
+
* @param data - Payload passed to each subscriber
|
|
870
|
+
* @returns Whether the underlying emitter had native listeners for the event
|
|
871
|
+
*/
|
|
872
|
+
publish(event, data) {
|
|
873
|
+
return this.dispatchKey(event, data);
|
|
874
|
+
}
|
|
875
|
+
/**
|
|
876
|
+
* @deprecated Call {@link Bus.publish} to reach subscribers and listeners together.
|
|
877
|
+
* @throws A **SeedcordTypeError** every time, with `CoreBusEmitUnavailable`. `emit` reaches only the `on()` listeners.
|
|
878
|
+
*/
|
|
879
|
+
emit(event, ..._args) {
|
|
880
|
+
throw new SeedcordTypeError(SeedcordErrorCode.CoreBusEmitUnavailable, [String(event)]);
|
|
881
|
+
}
|
|
882
|
+
/** @internal the framework's own publish path, keyed by a symbol no public entry exports */
|
|
883
|
+
[PublishDefault](event, data) {
|
|
884
|
+
return this.dispatchKey(event, data);
|
|
885
|
+
}
|
|
886
|
+
dispatchKey(event, data) {
|
|
887
|
+
this.processSubscriber(event, data);
|
|
888
|
+
return this.emitSafe(event, ...[data]);
|
|
889
|
+
}
|
|
890
|
+
onListenerError(error, event) {
|
|
891
|
+
this.logger.error(`listener for ${String(event)} threw`, error);
|
|
892
|
+
}
|
|
893
|
+
async processSubscriber(subscriberName, data) {
|
|
894
|
+
const registrations = this.subscribersMap.get(subscriberName);
|
|
895
|
+
if (!registrations) return;
|
|
896
|
+
const pending = registrations.reduce((acc, entry) => {
|
|
897
|
+
if (!this.onceRuns.claim(entry, subscriberName)) return acc;
|
|
898
|
+
acc.push(this.runSubscriber(entry, subscriberName, data));
|
|
899
|
+
return acc;
|
|
900
|
+
}, []);
|
|
901
|
+
await Promise.allSettled(pending);
|
|
902
|
+
}
|
|
903
|
+
async runSubscriber(entry, subscriberName, data) {
|
|
904
|
+
let name = "<unresolved>";
|
|
905
|
+
try {
|
|
906
|
+
const Ctor = entry.ctor;
|
|
907
|
+
name = Ctor.name;
|
|
908
|
+
await new Ctor(data, this.core).execute();
|
|
909
|
+
} catch (err) {
|
|
910
|
+
this.logger.error(`Error in subscriber ${paint.mute(String(subscriberName))} handler ${paint.sky.bold(name)}:`, err);
|
|
911
|
+
}
|
|
912
|
+
}
|
|
913
|
+
};
|
|
914
|
+
/** @internal */
|
|
915
|
+
function registrationFor(ctor) {
|
|
916
|
+
const meta = Reflect.getMetadata(SubscribeMetadataKey, ctor);
|
|
917
|
+
return {
|
|
918
|
+
keys: [meta.subscriber],
|
|
919
|
+
frequency: meta.frequency ?? "on",
|
|
920
|
+
ctor
|
|
921
|
+
};
|
|
922
|
+
}
|
|
923
|
+
/** @internal */
|
|
924
|
+
function busLoggerOf(bus) {
|
|
925
|
+
return bus[loggerSlot];
|
|
926
|
+
}
|
|
927
|
+
|
|
928
|
+
//#endregion
|
|
929
|
+
export { WebhookUrlMetadataKey as A, EventMiddlewareMetadataKey as C, InteractionMiddlewareMetadataKey as D, InteractionMetadataKey as E, RowComponent as M, isBuilderComponentClass as N, InteractionRouteKeys as O, bindBotColor as P, EventMetadataKey as S, InteractionKind as T, MemoryDriver as _, RegisterSubscriber as a, PublishDefault as b, VerifyWebhooks as c, WebhookLog as d, Subscriber as f, OnceTracker as g, sendFlags as h, RegisterDefaults as i, BuilderComponent as j, SubscribeMetadataKey as k, WebhookUrl as l, deferFlags as m, busLoggerOf as n, RegisteredCount as o, ReportThrottle as p, registrationFor as r, UnregisterSubscriber as s, Bus as t, Subscribe as u, ShutdownPhase as v, GatedMetadataKey as w, CommandMetadataKey as x, StartupPhase as y };
|
|
930
|
+
//# sourceMappingURL=Bus-W1K-uMeO.mjs.map
|