@seedcord/http 0.1.0-next.0 → 0.1.0-next.2
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/RouteManifest-DE-HCMwd.d.mts +65 -0
- package/dist/edge.index-BBRnxxkS.mjs +1285 -0
- package/dist/edge.index-BBRnxxkS.mjs.map +1 -0
- package/dist/edge.index-C30OZ55m.d.mts +525 -0
- package/dist/edge.index-joDL39cK.cjs +1426 -0
- package/dist/edge.index-joDL39cK.cjs.map +1 -0
- package/dist/edge.index.cjs +24 -0
- package/dist/edge.index.d.cts +1 -0
- package/dist/edge.index.d.mts +4 -0
- package/dist/edge.index.mjs +5 -0
- package/dist/index.cjs +377 -964
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.mts +64 -489
- package/dist/index.mjs +367 -957
- package/dist/index.mjs.map +1 -1
- package/dist/manifest.index.cjs +33 -0
- package/dist/manifest.index.cjs.map +1 -0
- package/dist/manifest.index.d.cts +1 -0
- package/dist/manifest.index.d.mts +11 -0
- package/dist/manifest.index.mjs +32 -0
- package/dist/manifest.index.mjs.map +1 -0
- package/dist/rolldown-runtime-BUUfjzRC.mjs +36 -0
- package/package.json +31 -9
package/dist/index.cjs
CHANGED
|
@@ -1,1026 +1,439 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
2
|
-
|
|
2
|
+
const require_edge_index = require('./edge.index-joDL39cK.cjs');
|
|
3
3
|
let _seedcord_errors_internal = require("@seedcord/errors/internal");
|
|
4
|
-
let _seedcord_logger = require("@seedcord/logger");
|
|
5
|
-
let discord_api_types_v10 = require("discord-api-types/v10");
|
|
6
4
|
let envapt = require("envapt");
|
|
7
5
|
let _discordjs_rest = require("@discordjs/rest");
|
|
8
6
|
let _seedcord_core = require("@seedcord/core");
|
|
9
7
|
let _seedcord_core_internal = require("@seedcord/core/internal");
|
|
8
|
+
let _seedcord_logger = require("@seedcord/logger");
|
|
10
9
|
let _seedcord_rate_limiter = require("@seedcord/rate-limiter");
|
|
11
|
-
let
|
|
10
|
+
let discord_api_types_v10 = require("discord-api-types/v10");
|
|
11
|
+
let _seedcord_errors = require("@seedcord/errors");
|
|
12
|
+
let node_events = require("node:events");
|
|
13
|
+
let node_http = require("node:http");
|
|
14
|
+
let _seedcord_core_node_internal = require("@seedcord/core/node/internal");
|
|
15
|
+
let _seedcord_logger_node = require("@seedcord/logger/node");
|
|
16
|
+
let _seedcord_types_internal = require("@seedcord/types/internal");
|
|
17
|
+
let _seedcord_core_hmr = require("@seedcord/core/hmr");
|
|
18
|
+
let _seedcord_utils = require("@seedcord/utils");
|
|
19
|
+
let _seedcord_utils_node = require("@seedcord/utils/node");
|
|
20
|
+
let _seedcord_core_plugin = require("@seedcord/core/plugin");
|
|
12
21
|
|
|
13
|
-
//#region src/
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
function wireAttachments(files) {
|
|
22
|
-
if (!files?.some((file) => file.description)) return null;
|
|
23
|
-
return files.map((file, index) => ({
|
|
24
|
-
id: index,
|
|
25
|
-
...file.name && { filename: file.name },
|
|
26
|
-
...file.description && { description: file.description }
|
|
27
|
-
}));
|
|
28
|
-
}
|
|
29
|
-
function callbackData(reply, flags) {
|
|
30
|
-
const attachments = wireAttachments(reply.files);
|
|
31
|
-
return {
|
|
32
|
-
flags,
|
|
33
|
-
components: reply.components,
|
|
34
|
-
...reply.allowedMentions && { allowed_mentions: wireAllowedMentions(reply.allowedMentions) },
|
|
35
|
-
...attachments && { attachments }
|
|
36
|
-
};
|
|
37
|
-
}
|
|
38
|
-
/**
|
|
39
|
-
* Writes interaction responses over the Discord REST callback and webhook endpoints. Construction is
|
|
40
|
-
* internal to the repliable handler bases and the dispatcher.
|
|
41
|
-
*/
|
|
42
|
-
var ReplySender = class extends _seedcord_core_internal.BaseReplySender {
|
|
43
|
-
ref;
|
|
44
|
-
rest;
|
|
45
|
-
constructor(ref, rest, routeId) {
|
|
46
|
-
super(routeId);
|
|
47
|
-
this.ref = ref;
|
|
48
|
-
this.rest = rest;
|
|
49
|
-
}
|
|
50
|
-
async writeReply(response, opts) {
|
|
51
|
-
const reply = this.serialize(response);
|
|
52
|
-
const result = await this.callback(discord_api_types_v10.InteractionResponseType.ChannelMessageWithSource, callbackData(reply, (0, _seedcord_core_internal.sendFlags)(opts)), reply.files);
|
|
53
|
-
return this.createdMessage(result);
|
|
54
|
-
}
|
|
55
|
-
async writeDefer(opts) {
|
|
56
|
-
await this.callback(discord_api_types_v10.InteractionResponseType.DeferredChannelMessageWithSource, { flags: (0, _seedcord_core_internal.deferFlags)(opts) });
|
|
57
|
-
}
|
|
58
|
-
async writeDeferUpdate() {
|
|
59
|
-
await this.callback(discord_api_types_v10.InteractionResponseType.DeferredMessageUpdate);
|
|
60
|
-
}
|
|
61
|
-
async writeUpdate(response) {
|
|
62
|
-
const reply = this.serialize(response);
|
|
63
|
-
const result = await this.callback(discord_api_types_v10.InteractionResponseType.UpdateMessage, callbackData(reply, discord_api_types_v10.MessageFlags.IsComponentsV2), reply.files);
|
|
64
|
-
return this.createdMessage(result);
|
|
65
|
-
}
|
|
66
|
-
async writeFollowUp(response, opts) {
|
|
67
|
-
const reply = this.serialize(response);
|
|
68
|
-
return await this.rest.post(discord_api_types_v10.Routes.webhook(this.ref.application_id, this.ref.token), {
|
|
69
|
-
body: callbackData(reply, (0, _seedcord_core_internal.sendFlags)(opts)),
|
|
70
|
-
query: new URLSearchParams({ wait: "true" }),
|
|
71
|
-
...reply.files && { files: this.rawFiles(reply.files) }
|
|
72
|
-
});
|
|
73
|
-
}
|
|
74
|
-
writeEditOriginal(response) {
|
|
75
|
-
return this.editMessage(discord_api_types_v10.Routes.webhookMessage(this.ref.application_id, this.ref.token), this.serialize(response));
|
|
76
|
-
}
|
|
77
|
-
writeEditTarget(targetId, response) {
|
|
78
|
-
const route = discord_api_types_v10.Routes.webhookMessage(this.ref.application_id, this.ref.token, targetId);
|
|
79
|
-
return this.editMessage(route, this.serialize(response));
|
|
80
|
-
}
|
|
81
|
-
async writeDeleteOriginal() {
|
|
82
|
-
await this.rest.delete(discord_api_types_v10.Routes.webhookMessage(this.ref.application_id, this.ref.token));
|
|
83
|
-
}
|
|
84
|
-
async writeDeleteTarget(targetId) {
|
|
85
|
-
await this.rest.delete(discord_api_types_v10.Routes.webhookMessage(this.ref.application_id, this.ref.token, targetId));
|
|
86
|
-
}
|
|
87
|
-
async writeModal(data) {
|
|
88
|
-
await this.callback(discord_api_types_v10.InteractionResponseType.Modal, data);
|
|
89
|
-
}
|
|
90
|
-
async callback(type, data, files) {
|
|
91
|
-
const withResponse = type === discord_api_types_v10.InteractionResponseType.ChannelMessageWithSource || type === discord_api_types_v10.InteractionResponseType.UpdateMessage;
|
|
92
|
-
return await this.rest.post(discord_api_types_v10.Routes.interactionCallback(this.ref.id, this.ref.token), {
|
|
93
|
-
body: {
|
|
94
|
-
type,
|
|
95
|
-
...data !== void 0 && { data }
|
|
96
|
-
},
|
|
97
|
-
...withResponse && { query: new URLSearchParams({ with_response: "true" }) },
|
|
98
|
-
...files && { files: this.rawFiles(files) }
|
|
99
|
-
});
|
|
100
|
-
}
|
|
101
|
-
async editMessage(route, reply) {
|
|
102
|
-
return await this.rest.patch(route, {
|
|
103
|
-
body: callbackData(reply, discord_api_types_v10.MessageFlags.IsComponentsV2),
|
|
104
|
-
...reply.files && { files: this.rawFiles(reply.files) }
|
|
105
|
-
});
|
|
106
|
-
}
|
|
107
|
-
rawFiles(files) {
|
|
108
|
-
return files.map((file, index) => ({
|
|
109
|
-
name: file.name ?? `file-${index}`,
|
|
110
|
-
data: file.attachment
|
|
111
|
-
}));
|
|
112
|
-
}
|
|
113
|
-
createdMessage(result) {
|
|
114
|
-
return result.resource?.message;
|
|
115
|
-
}
|
|
22
|
+
//#region src/manifest/RouteManifest.ts
|
|
23
|
+
/** @internal */
|
|
24
|
+
const EMPTY_MANIFEST = {
|
|
25
|
+
commandRoutes: [],
|
|
26
|
+
componentRoutes: [],
|
|
27
|
+
autocompleteRoutes: [],
|
|
28
|
+
subscriberRoutes: [],
|
|
29
|
+
middlewareRoutes: []
|
|
116
30
|
};
|
|
117
31
|
|
|
118
32
|
//#endregion
|
|
119
|
-
//#region src/
|
|
33
|
+
//#region src/node/InteractionDispatcher.ts
|
|
120
34
|
/**
|
|
121
|
-
*
|
|
122
|
-
*
|
|
123
|
-
* Not a public entry point. Extend {@link SlashHandler}, {@link ButtonHandler}, {@link ModalHandler},
|
|
124
|
-
* {@link SelectMenuHandler}, or {@link ContextMenuHandler} instead. This class binds the core reply base
|
|
125
|
-
* to the http sender.
|
|
35
|
+
* Discovers interaction handlers from the filesystem into the engine's live route maps.
|
|
126
36
|
*
|
|
127
|
-
*
|
|
37
|
+
* The node host runs it at startup and dev HMR swaps map entries in place. The engine's `resolve`
|
|
38
|
+
* reads `maps` per request. The edge path builds its maps from the generated manifest.
|
|
128
39
|
*/
|
|
129
|
-
var
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
memberRoleIds: member?.roles ?? [],
|
|
154
|
-
memberPermissions: member ? BigInt(member.permissions) : null,
|
|
155
|
-
appPermissions: BigInt(payload.app_permissions),
|
|
156
|
-
routeId
|
|
157
|
-
};
|
|
158
|
-
}
|
|
159
|
-
|
|
160
|
-
//#endregion
|
|
161
|
-
//#region src/dispatch/dispatchInteraction.ts
|
|
162
|
-
let dispatchLogger;
|
|
163
|
-
function logger() {
|
|
164
|
-
dispatchLogger ??= new _seedcord_logger.Logger("Dispatcher");
|
|
165
|
-
return dispatchLogger;
|
|
166
|
-
}
|
|
167
|
-
function createCore(config, token) {
|
|
168
|
-
return {
|
|
169
|
-
config,
|
|
170
|
-
rateLimiter: config.store ?? new _seedcord_rate_limiter.MemoryRateLimiter(),
|
|
171
|
-
rest: new _discordjs_rest.REST().setToken(token),
|
|
172
|
-
version: "0.1.0-next.0",
|
|
173
|
-
username: void 0,
|
|
174
|
-
augmentTarget: "@seedcord/http"
|
|
175
|
-
};
|
|
176
|
-
}
|
|
177
|
-
function isHandlerCtor(value) {
|
|
178
|
-
return typeof value === "function" && value.prototype instanceof _seedcord_core.BaseHandler;
|
|
179
|
-
}
|
|
180
|
-
function handlerCtorOf(moduleExports) {
|
|
181
|
-
if (typeof moduleExports !== "object" || moduleExports === null) return null;
|
|
182
|
-
for (const value of Object.values(moduleExports)) if (isHandlerCtor(value)) return value;
|
|
183
|
-
return null;
|
|
184
|
-
}
|
|
185
|
-
const HARMLESS_API_CODES = new Set([
|
|
186
|
-
discord_api_types_v10.RESTJSONErrorCodes.UnknownInteraction,
|
|
187
|
-
discord_api_types_v10.RESTJSONErrorCodes.InteractionHasAlreadyBeenAcknowledged,
|
|
188
|
-
discord_api_types_v10.RESTJSONErrorCodes.UnknownMessage
|
|
189
|
-
]);
|
|
190
|
-
async function sendGuarded(routeId, send) {
|
|
191
|
-
try {
|
|
192
|
-
await send();
|
|
193
|
-
} catch (error) {
|
|
194
|
-
if (error instanceof _discordjs_rest.DiscordAPIError && HARMLESS_API_CODES.has(error.code)) {
|
|
195
|
-
logger().debug(`boundary send hit harmless code ${_seedcord_logger.paint.amber(String(error.code))}`);
|
|
196
|
-
return;
|
|
197
|
-
}
|
|
198
|
-
logger().error(`boundary send failed for route ${_seedcord_logger.paint.sky.bold(routeId)}`, error);
|
|
199
|
-
}
|
|
200
|
-
}
|
|
201
|
-
async function respondEmptyChoices(scope) {
|
|
202
|
-
await scope.core.rest.post(discord_api_types_v10.Routes.interactionCallback(scope.payload.id, scope.payload.token), { body: {
|
|
203
|
-
type: discord_api_types_v10.InteractionResponseType.ApplicationCommandAutocompleteResult,
|
|
204
|
-
data: { choices: [] }
|
|
205
|
-
} });
|
|
206
|
-
}
|
|
207
|
-
function renderContext(core, uuid) {
|
|
208
|
-
const developerUsername = core.config.notifications?.developerUsername;
|
|
209
|
-
return developerUsername === void 0 ? { uuid } : {
|
|
210
|
-
uuid,
|
|
211
|
-
developerUsername
|
|
212
|
-
};
|
|
213
|
-
}
|
|
214
|
-
async function handleNotice(notice, uuid, scope) {
|
|
215
|
-
if (notice.report) logger().error(`${notice.name}: ${_seedcord_logger.paint.mute(uuid)}`, notice);
|
|
216
|
-
const { sender } = scope;
|
|
217
|
-
if (!sender) {
|
|
218
|
-
await sendGuarded(scope.routeId, () => respondEmptyChoices(scope));
|
|
219
|
-
return;
|
|
220
|
-
}
|
|
221
|
-
const response = notice.render(renderContext(scope.core, uuid));
|
|
222
|
-
await sendGuarded(scope.routeId, () => sender.send(response, { ephemeral: notice.ephemeral }));
|
|
223
|
-
}
|
|
224
|
-
async function handleRawFault(error, uuid, scope) {
|
|
225
|
-
const { core, sender } = scope;
|
|
226
|
-
if (core.config.errors?.errorStack ?? false) logger().error(_seedcord_logger.paint.mute(uuid), error);
|
|
227
|
-
else logger().error(`${_seedcord_logger.paint.mute(uuid)} | ${error.message}`);
|
|
228
|
-
if (!sender) {
|
|
229
|
-
await sendGuarded(scope.routeId, () => respondEmptyChoices(scope));
|
|
230
|
-
return;
|
|
231
|
-
}
|
|
232
|
-
const override = core.config.errors?.defaultError;
|
|
233
|
-
const response = (override ? new override(uuid) : new _seedcord_core.Fault()).render(renderContext(core, uuid));
|
|
234
|
-
await sendGuarded(scope.routeId, () => sender.send(response, { ephemeral: true }));
|
|
235
|
-
}
|
|
236
|
-
async function handleFault(caught, scope) {
|
|
237
|
-
if (caught instanceof _seedcord_core.Silence) {
|
|
238
|
-
if (caught.reason !== void 0) logger().debug(`Silence: ${caught.reason}`);
|
|
239
|
-
return;
|
|
240
|
-
}
|
|
241
|
-
const uuid = crypto.randomUUID();
|
|
242
|
-
if (caught instanceof _seedcord_core.Notice) {
|
|
243
|
-
await handleNotice(caught, uuid, scope);
|
|
244
|
-
return;
|
|
245
|
-
}
|
|
246
|
-
const error = Error.isError(caught) ? caught : new Error(String(caught));
|
|
247
|
-
const ignore = new Set(scope.core.config.errors?.ignoreApiCodes ?? []);
|
|
248
|
-
if (error instanceof _discordjs_rest.DiscordAPIError && ignore.has(error.code)) {
|
|
249
|
-
logger().debug(`swallowed api code ${_seedcord_logger.paint.amber(String(error.code))}`);
|
|
250
|
-
return;
|
|
251
|
-
}
|
|
252
|
-
await handleRawFault(error, uuid, scope);
|
|
253
|
-
}
|
|
254
|
-
function freshScope(match, payload, core) {
|
|
255
|
-
const ref = {
|
|
256
|
-
application_id: payload.application_id,
|
|
257
|
-
id: payload.id,
|
|
258
|
-
token: payload.token
|
|
259
|
-
};
|
|
260
|
-
const routeId = match.routeId ?? "unhandled";
|
|
261
|
-
return {
|
|
262
|
-
core,
|
|
263
|
-
payload,
|
|
264
|
-
routeId,
|
|
265
|
-
sender: match.kind === "autocomplete" ? null : new ReplySender(ref, core.rest, routeId)
|
|
266
|
-
};
|
|
267
|
-
}
|
|
268
|
-
/**
|
|
269
|
-
* Runs the pre-ack phase for a matched interaction. Loads the route module, constructs the handler, and
|
|
270
|
-
* runs its gates, and the sender posts any refusal. Returns the post-ack execute continuation, or null
|
|
271
|
-
* when a gate refuses or nothing can run.
|
|
272
|
-
*/
|
|
273
|
-
async function dispatchInteraction(args) {
|
|
274
|
-
const { match, payload, core } = args;
|
|
275
|
-
let moduleExports;
|
|
276
|
-
try {
|
|
277
|
-
moduleExports = await match.load();
|
|
278
|
-
} catch (caught) {
|
|
279
|
-
logger().error(`Route ${_seedcord_logger.paint.sky.bold(match.routeId ?? "unhandled")} failed to load its module.`, caught);
|
|
280
|
-
await handleFault(caught, freshScope(match, payload, core));
|
|
281
|
-
return null;
|
|
282
|
-
}
|
|
283
|
-
const ctor = handlerCtorOf(moduleExports);
|
|
284
|
-
if (!ctor) {
|
|
285
|
-
const routeId = match.routeId ?? "unhandled";
|
|
286
|
-
logger().error(`Route ${_seedcord_logger.paint.sky.bold(routeId)} loaded a module with no handler class.`);
|
|
287
|
-
await handleFault(/* @__PURE__ */ new Error(`route ${routeId} loaded a module with no handler class`), freshScope(match, payload, core));
|
|
288
|
-
return null;
|
|
289
|
-
}
|
|
290
|
-
const dispatch = new _seedcord_core.DispatchContext(match.routeId);
|
|
291
|
-
let handler;
|
|
292
|
-
try {
|
|
293
|
-
handler = new ctor(payload, core, dispatch);
|
|
294
|
-
} catch (caught) {
|
|
295
|
-
await handleFault(caught, freshScope(match, payload, core));
|
|
296
|
-
return null;
|
|
40
|
+
var InteractionDispatcher = class {
|
|
41
|
+
handlersDir;
|
|
42
|
+
maps;
|
|
43
|
+
targets;
|
|
44
|
+
/** @internal */
|
|
45
|
+
logger = new _seedcord_logger.Logger("Interactions", { channel: "interactions" });
|
|
46
|
+
isInitialized = false;
|
|
47
|
+
hmrHandler;
|
|
48
|
+
rowOwners = /* @__PURE__ */ new Map();
|
|
49
|
+
loading = false;
|
|
50
|
+
loadedHandlers = [];
|
|
51
|
+
constructor(handlersDir) {
|
|
52
|
+
this.handlersDir = handlersDir;
|
|
53
|
+
this.maps = require_edge_index.buildRouteMaps(EMPTY_MANIFEST);
|
|
54
|
+
this.targets = this.buildTargets();
|
|
55
|
+
if (!envapt.Envapter.isDevelopment && !envapt.Envapter.isTest) return;
|
|
56
|
+
this.hmrHandler = new _seedcord_core_hmr.HmrModuleHandler({
|
|
57
|
+
handlersDir,
|
|
58
|
+
isHandler: this.isHandler.bind(this),
|
|
59
|
+
registerHandler: this.registerHandler.bind(this),
|
|
60
|
+
unregisterHandler: this.unregisterHandler.bind(this),
|
|
61
|
+
getArtifacts: this.getArtifacts.bind(this),
|
|
62
|
+
logger: this.logger
|
|
63
|
+
});
|
|
297
64
|
}
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
if (!await passedGates(ctor, match, payload, core, scope)) return null;
|
|
305
|
-
return async () => {
|
|
65
|
+
/** @internal */
|
|
66
|
+
async init() {
|
|
67
|
+
if (this.isInitialized) return;
|
|
68
|
+
this.isInitialized = true;
|
|
69
|
+
this.loading = true;
|
|
70
|
+
this.loadedHandlers.length = 0;
|
|
306
71
|
try {
|
|
307
|
-
await
|
|
308
|
-
|
|
309
|
-
|
|
72
|
+
await (0, _seedcord_utils_node.traverseDirectory)(this.handlersDir, (fullPath, relativePath, imported) => {
|
|
73
|
+
for (const value of Object.values(imported)) {
|
|
74
|
+
if (!this.isHandler(value)) continue;
|
|
75
|
+
this.registerHandler(value, relativePath);
|
|
76
|
+
this.hmrHandler?.trackHandler(fullPath, value);
|
|
77
|
+
}
|
|
78
|
+
});
|
|
79
|
+
} finally {
|
|
80
|
+
this.loading = false;
|
|
310
81
|
}
|
|
311
|
-
|
|
312
|
-
}
|
|
313
|
-
async function passedGates(ctor, match, payload, core, scope) {
|
|
314
|
-
if (match.kind === "autocomplete" || payload.type === discord_api_types_v10.InteractionType.ApplicationCommandAutocomplete) return true;
|
|
315
|
-
const monitor = (0, _seedcord_core_internal.slowGateMonitor)();
|
|
316
|
-
try {
|
|
317
|
-
await (0, _seedcord_core_internal.runHandlerGates)(ctor, interactionGateContext(payload, core, match.routeId), match.routeId ?? void 0, monitor?.observe);
|
|
318
|
-
return true;
|
|
319
|
-
} catch (caught) {
|
|
320
|
-
await handleFault(caught, scope);
|
|
321
|
-
return false;
|
|
322
|
-
} finally {
|
|
323
|
-
monitor?.report(match.routeId);
|
|
324
|
-
}
|
|
325
|
-
}
|
|
326
|
-
|
|
327
|
-
//#endregion
|
|
328
|
-
//#region src/inputs/HttpSlashOptions.ts
|
|
329
|
-
var HttpSlashOptions = class {
|
|
330
|
-
leaves = /* @__PURE__ */ new Map();
|
|
331
|
-
resolved;
|
|
332
|
-
constructor(data) {
|
|
333
|
-
this.resolved = data.resolved;
|
|
334
|
-
let options = data.options ?? [];
|
|
335
|
-
const first = options[0];
|
|
336
|
-
if (first?.type === discord_api_types_v10.ApplicationCommandOptionType.SubcommandGroup) options = first.options;
|
|
337
|
-
const second = options[0];
|
|
338
|
-
if (second?.type === discord_api_types_v10.ApplicationCommandOptionType.Subcommand) options = second.options ?? [];
|
|
339
|
-
for (const option of options) if (option.type !== discord_api_types_v10.ApplicationCommandOptionType.Subcommand && option.type !== discord_api_types_v10.ApplicationCommandOptionType.SubcommandGroup) this.leaves.set(option.name, option);
|
|
340
|
-
}
|
|
341
|
-
getString(name) {
|
|
342
|
-
const leaf = this.leaves.get(name);
|
|
343
|
-
return leaf?.type === discord_api_types_v10.ApplicationCommandOptionType.String ? leaf.value : null;
|
|
344
|
-
}
|
|
345
|
-
getInteger(name) {
|
|
346
|
-
const leaf = this.leaves.get(name);
|
|
347
|
-
return leaf?.type === discord_api_types_v10.ApplicationCommandOptionType.Integer ? numeric(leaf.value) : null;
|
|
348
|
-
}
|
|
349
|
-
getNumber(name) {
|
|
350
|
-
const leaf = this.leaves.get(name);
|
|
351
|
-
return leaf?.type === discord_api_types_v10.ApplicationCommandOptionType.Number ? numeric(leaf.value) : null;
|
|
82
|
+
this.logger.utils.block("Loaded handlers", [...this.logger.utils.entries(this.loadedHandlers), ...this.logger.utils.counts({ routes: this.rowOwners.size })]);
|
|
352
83
|
}
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
84
|
+
/** @internal */
|
|
85
|
+
async onHmr(event) {
|
|
86
|
+
await this.hmrHandler?.handle(event);
|
|
356
87
|
}
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
return this.resolved?.users?.[leaf.value] ?? null;
|
|
88
|
+
isHandler(value) {
|
|
89
|
+
if (typeof value !== "function") return false;
|
|
90
|
+
return (value.prototype instanceof require_edge_index.InteractionHandler || value.prototype instanceof require_edge_index.AutocompleteHandler) && Reflect.hasMetadata(_seedcord_core_internal.InteractionMetadataKey, value);
|
|
361
91
|
}
|
|
362
|
-
|
|
363
|
-
const
|
|
364
|
-
|
|
365
|
-
return
|
|
92
|
+
getArtifacts(ctor) {
|
|
93
|
+
const routeIds = [];
|
|
94
|
+
for (const [routeId, owner] of this.rowOwners) if (owner.ctor === ctor) routeIds.push(routeId);
|
|
95
|
+
return routeIds;
|
|
366
96
|
}
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
if (leaf?.type !== discord_api_types_v10.ApplicationCommandOptionType.Channel) return null;
|
|
370
|
-
return this.resolved?.channels?.[leaf.value] ?? null;
|
|
97
|
+
targetFor(route) {
|
|
98
|
+
return this.targets[route];
|
|
371
99
|
}
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
100
|
+
buildTargets() {
|
|
101
|
+
return {
|
|
102
|
+
[_seedcord_core_internal.InteractionRoutes.Slash]: {
|
|
103
|
+
map: this.maps.slash,
|
|
104
|
+
kind: "slash"
|
|
105
|
+
},
|
|
106
|
+
[_seedcord_core_internal.InteractionRoutes.UserContextMenu]: {
|
|
107
|
+
map: this.maps.userContextMenu,
|
|
108
|
+
kind: "userContextMenu"
|
|
109
|
+
},
|
|
110
|
+
[_seedcord_core_internal.InteractionRoutes.MessageContextMenu]: {
|
|
111
|
+
map: this.maps.messageContextMenu,
|
|
112
|
+
kind: "messageContextMenu"
|
|
113
|
+
},
|
|
114
|
+
[_seedcord_core_internal.InteractionRoutes.Autocomplete]: {
|
|
115
|
+
map: this.maps.autocomplete,
|
|
116
|
+
kind: "autocomplete"
|
|
117
|
+
},
|
|
118
|
+
[_seedcord_core_internal.InteractionRoutes.Button]: {
|
|
119
|
+
map: this.maps.components.button,
|
|
120
|
+
kind: "button"
|
|
121
|
+
},
|
|
122
|
+
[_seedcord_core_internal.InteractionRoutes.StringMenu]: {
|
|
123
|
+
map: this.maps.components.stringSelect,
|
|
124
|
+
kind: "stringMenu"
|
|
125
|
+
},
|
|
126
|
+
[_seedcord_core_internal.InteractionRoutes.UserMenu]: {
|
|
127
|
+
map: this.maps.components.userSelect,
|
|
128
|
+
kind: "userMenu"
|
|
129
|
+
},
|
|
130
|
+
[_seedcord_core_internal.InteractionRoutes.RoleMenu]: {
|
|
131
|
+
map: this.maps.components.roleSelect,
|
|
132
|
+
kind: "roleMenu"
|
|
133
|
+
},
|
|
134
|
+
[_seedcord_core_internal.InteractionRoutes.ChannelMenu]: {
|
|
135
|
+
map: this.maps.components.channelSelect,
|
|
136
|
+
kind: "channelMenu"
|
|
137
|
+
},
|
|
138
|
+
[_seedcord_core_internal.InteractionRoutes.MentionableMenu]: {
|
|
139
|
+
map: this.maps.components.mentionableSelect,
|
|
140
|
+
kind: "mentionableMenu"
|
|
141
|
+
},
|
|
142
|
+
[_seedcord_core_internal.InteractionRoutes.Modal]: {
|
|
143
|
+
map: this.maps.components.modal,
|
|
144
|
+
kind: "modal"
|
|
145
|
+
}
|
|
392
146
|
};
|
|
393
|
-
|
|
147
|
+
}
|
|
148
|
+
registerHandler(ctor, relativePath) {
|
|
149
|
+
const from = (0, _seedcord_utils.formatFilePath)(relativePath);
|
|
150
|
+
const writes = [];
|
|
151
|
+
for (const [route, keys] of (0, _seedcord_core_internal.interactionRoutesOf)(ctor)) {
|
|
152
|
+
const target = this.targetFor(route);
|
|
153
|
+
for (const key of keys) {
|
|
154
|
+
const routeId = `${target.kind}:${key}`;
|
|
155
|
+
const existing = this.rowOwners.get(routeId);
|
|
156
|
+
if (existing && existing.ctor !== ctor) throw new _seedcord_errors_internal.SeedcordError(_seedcord_errors.SeedcordErrorCode.InteractionDuplicateRoute, [
|
|
157
|
+
routeId,
|
|
158
|
+
`${existing.ctor.name} (${existing.from})`,
|
|
159
|
+
`${ctor.name} (${from})`
|
|
160
|
+
]);
|
|
161
|
+
writes.push([target, key]);
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
if (writes.length === 0) return;
|
|
165
|
+
for (const [target, key] of writes) {
|
|
166
|
+
const routeId = `${target.kind}:${key}`;
|
|
167
|
+
target.map.set(key, {
|
|
168
|
+
kind: target.kind,
|
|
169
|
+
routeId,
|
|
170
|
+
load: () => Promise.resolve(ctor)
|
|
171
|
+
});
|
|
172
|
+
this.rowOwners.set(routeId, {
|
|
173
|
+
ctor,
|
|
174
|
+
target,
|
|
175
|
+
key,
|
|
176
|
+
from
|
|
177
|
+
});
|
|
178
|
+
}
|
|
179
|
+
if (this.loading) this.loadedHandlers.push({
|
|
180
|
+
name: ctor.name,
|
|
181
|
+
from
|
|
182
|
+
});
|
|
183
|
+
else this.logger.utils.registration(ctor.name, from);
|
|
184
|
+
}
|
|
185
|
+
unregisterHandler(ctor, artifacts) {
|
|
186
|
+
const routeIds = artifacts ?? this.getArtifacts(ctor);
|
|
187
|
+
for (const routeId of routeIds) {
|
|
188
|
+
const owner = this.rowOwners.get(routeId);
|
|
189
|
+
if (owner?.ctor !== ctor) continue;
|
|
190
|
+
this.rowOwners.delete(routeId);
|
|
191
|
+
owner.target.map.delete(owner.key);
|
|
192
|
+
}
|
|
394
193
|
}
|
|
395
194
|
};
|
|
396
|
-
function numeric(value) {
|
|
397
|
-
if (typeof value === "number") return value;
|
|
398
|
-
if (value.trim() === "") return null;
|
|
399
|
-
const parsed = Number(value);
|
|
400
|
-
return Number.isNaN(parsed) ? null : parsed;
|
|
401
|
-
}
|
|
402
195
|
|
|
403
196
|
//#endregion
|
|
404
|
-
//#region src/
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
197
|
+
//#region src/node/webBridge.ts
|
|
198
|
+
function toHeaders(raw) {
|
|
199
|
+
const headers = new Headers();
|
|
200
|
+
for (const [name, value] of Object.entries(raw)) {
|
|
201
|
+
if (value === void 0) continue;
|
|
202
|
+
if (Array.isArray(value)) for (const item of value) headers.append(name, item);
|
|
203
|
+
else headers.set(name, value);
|
|
204
|
+
}
|
|
205
|
+
return headers;
|
|
206
|
+
}
|
|
207
|
+
async function toWebRequest(request) {
|
|
208
|
+
const chunks = [];
|
|
209
|
+
for await (const chunk of request) chunks.push(chunk);
|
|
210
|
+
const method = request.method ?? "GET";
|
|
211
|
+
const body = method === "GET" || method === "HEAD" ? void 0 : new Uint8Array(Buffer.concat(chunks));
|
|
212
|
+
return new Request(`http://${request.headers.host ?? "localhost"}${request.url ?? "/"}`, {
|
|
213
|
+
method,
|
|
214
|
+
headers: toHeaders(request.headers),
|
|
215
|
+
...body !== void 0 && { body }
|
|
216
|
+
});
|
|
217
|
+
}
|
|
218
|
+
async function writeWebResponse(response, out) {
|
|
219
|
+
const headers = Object.fromEntries(response.headers);
|
|
220
|
+
const cookies = response.headers.getSetCookie();
|
|
221
|
+
if (cookies.length > 0) headers["set-cookie"] = cookies;
|
|
222
|
+
out.writeHead(response.status, headers);
|
|
223
|
+
out.end(response.body === null ? void 0 : Buffer.from(await response.arrayBuffer()));
|
|
415
224
|
}
|
|
416
225
|
|
|
417
226
|
//#endregion
|
|
418
|
-
//#region src/
|
|
227
|
+
//#region src/node/Seedcord.ts
|
|
228
|
+
const DEFAULT_PORT = 3e3;
|
|
229
|
+
const SERVER_SHUTDOWN_TIMEOUT_MS = 5e3;
|
|
230
|
+
const DRAIN_TIMEOUT_MS = 1e4;
|
|
419
231
|
/**
|
|
420
|
-
*
|
|
421
|
-
*
|
|
422
|
-
* Pass the command route(s) from the generated registry as the generic. Branch on the focused field with
|
|
423
|
-
* `this.match`, read already-entered sibling options with `this.options`, and find which command fired
|
|
424
|
-
* with `this.route`.
|
|
232
|
+
* The HTTP-interactions bot host, a long-running node server around the engine.
|
|
425
233
|
*
|
|
426
|
-
*
|
|
234
|
+
* Discovers handlers from `config.bot.interactions.path`, verifies and dispatches interactions on
|
|
235
|
+
* `start(port)`, and runs coordinated shutdown with an in-flight drain. The edge deploy path calls
|
|
236
|
+
* `createSeedcord` from a generated entry.
|
|
427
237
|
*/
|
|
428
|
-
var
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
*/
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
238
|
+
var Seedcord = class Seedcord extends _seedcord_core_node_internal.Pluggable {
|
|
239
|
+
config;
|
|
240
|
+
/** @internal */
|
|
241
|
+
[_seedcord_types_internal.SeedcordBrand] = true;
|
|
242
|
+
/** @internal */
|
|
243
|
+
augmentTarget = "@seedcord/http";
|
|
244
|
+
/** @internal */
|
|
245
|
+
version = require_edge_index.version;
|
|
246
|
+
/** Workerd-compatible Discord REST client. `start()` sets the token. */
|
|
247
|
+
rest = new _discordjs_rest.REST();
|
|
248
|
+
/** @see {@link IRateLimiter} */
|
|
249
|
+
rateLimiter;
|
|
250
|
+
/** @see {@link Bus} */
|
|
251
|
+
bus;
|
|
252
|
+
subscribers;
|
|
253
|
+
interactions;
|
|
254
|
+
healthCheck;
|
|
255
|
+
hmrManager;
|
|
256
|
+
logger = new _seedcord_logger.Logger("Server", { channel: "bot" });
|
|
257
|
+
server;
|
|
258
|
+
boundPort;
|
|
259
|
+
requestedPort = DEFAULT_PORT;
|
|
260
|
+
fetchedUsername;
|
|
261
|
+
constructor(config) {
|
|
262
|
+
super(new _seedcord_core_node_internal.CoordinatedShutdown(), new _seedcord_core_node_internal.CoordinatedStartup());
|
|
263
|
+
this.config = config;
|
|
264
|
+
(0, _seedcord_logger_node.installNodeDefaults)(config.logger);
|
|
265
|
+
(0, _seedcord_core_internal.setBotColor)(config.botColor);
|
|
266
|
+
this.hmrManager = new _seedcord_core_internal.HmrManager();
|
|
267
|
+
this.hmrManager.init();
|
|
268
|
+
if (this.config.bot.interactions.path) this.interactions = new InteractionDispatcher(this.config.bot.interactions.path);
|
|
269
|
+
this.rateLimiter = config.store ?? new _seedcord_rate_limiter.MemoryRateLimiter();
|
|
270
|
+
this.bus = new _seedcord_core.Bus(this);
|
|
271
|
+
this.subscribers = new _seedcord_core_node_internal.SubscriberLoader(this.bus, config.subscribers.path);
|
|
272
|
+
this.healthCheck = config.runtime === "edge" ? void 0 : _seedcord_core_node_internal.HealthCheck.fromOption(this.shutdown, config.healthCheck);
|
|
273
|
+
this.registerStartupTasks();
|
|
274
|
+
}
|
|
275
|
+
/** The bot's discord username, populated by the ready fetch. */
|
|
276
|
+
get username() {
|
|
277
|
+
return this.fetchedUsername;
|
|
278
|
+
}
|
|
279
|
+
/** The bound server port, populated once `start()` is listening. */
|
|
280
|
+
get port() {
|
|
281
|
+
return this.boundPort;
|
|
282
|
+
}
|
|
283
|
+
pluginCapabilities() {
|
|
284
|
+
const token = envapt.Envapter.get("DISCORD_BOT_TOKEN");
|
|
285
|
+
return {
|
|
286
|
+
rest: this.rest,
|
|
287
|
+
...token !== void 0 && { token }
|
|
288
|
+
};
|
|
445
289
|
}
|
|
446
290
|
/**
|
|
447
|
-
*
|
|
448
|
-
* match is how you read it.
|
|
449
|
-
*
|
|
450
|
-
* Provide one arm per autocompletable field across the registered commands, keyed by field name. Each
|
|
451
|
-
* arm receives the focused partial value and a `respond` typed to that field's choice value. The
|
|
452
|
-
* arms must cover every autocompletable field, a missing field or an unknown key is a compile error. A
|
|
453
|
-
* focused field with no arm, only reachable from a stale-deployed command, throws at runtime.
|
|
291
|
+
* Starts the host and runs the startup tasks.
|
|
454
292
|
*
|
|
455
|
-
* @param
|
|
456
|
-
* @returns The result of the arm that ran.
|
|
457
|
-
*/
|
|
458
|
-
async match(arms) {
|
|
459
|
-
const { name, value } = this.focused;
|
|
460
|
-
const respond = (choices) => this.respond(choices);
|
|
461
|
-
const arm = Object.hasOwn(arms, name) ? arms[name] : void 0;
|
|
462
|
-
if (!arm) throw new _seedcord_errors_internal.SeedcordError(_seedcord_errors.SeedcordErrorCode.AutocompleteMatchArmMissing, [name]);
|
|
463
|
-
return await arm(value, respond);
|
|
464
|
-
}
|
|
465
|
-
/** Send autocomplete suggestions, callback type 8. Prefer {@link match}, which restricts each field's choices to its declared type. */
|
|
466
|
-
async respond(choices) {
|
|
467
|
-
await this.core.rest.post(discord_api_types_v10.Routes.interactionCallback(this.event.id, this.event.token), { body: {
|
|
468
|
-
type: discord_api_types_v10.InteractionResponseType.ApplicationCommandAutocompleteResult,
|
|
469
|
-
data: { choices }
|
|
470
|
-
} });
|
|
471
|
-
}
|
|
472
|
-
/** The firing command route, for a field whose completion differs per registered command. */
|
|
473
|
-
get route() {
|
|
474
|
-
return slashRouteOf(this.event.data);
|
|
475
|
-
}
|
|
476
|
-
/**
|
|
477
|
-
* The already-entered options on this command, restricted to the kinds Discord resolves during autocomplete
|
|
478
|
-
* (string, integer, number, boolean) with every read nullable, since a sibling is partial while the user
|
|
479
|
-
* types the focused field. The focused field is on `this.focused`.
|
|
480
|
-
*/
|
|
481
|
-
get options() {
|
|
482
|
-
return this.reader;
|
|
483
|
-
}
|
|
484
|
-
};
|
|
485
|
-
|
|
486
|
-
//#endregion
|
|
487
|
-
//#region src/handlers/defaults/UnhandledAutocomplete.ts
|
|
488
|
-
/**
|
|
489
|
-
* Default handler for autocomplete no manifest row matches.
|
|
490
|
-
* Empty choices are the only legal answer, they clear the pending state.
|
|
491
|
-
*
|
|
492
|
-
* @internal
|
|
493
|
-
*/
|
|
494
|
-
var UnhandledAutocomplete = class extends AutocompleteHandler {
|
|
495
|
-
async execute() {
|
|
496
|
-
await this.respond([]);
|
|
497
|
-
}
|
|
498
|
-
};
|
|
499
|
-
|
|
500
|
-
//#endregion
|
|
501
|
-
//#region src/handlers/interaction/InteractionHandler.ts
|
|
502
|
-
/**
|
|
503
|
-
* Shared base the repliable interaction handlers extend.
|
|
504
|
-
*
|
|
505
|
-
* Not a public entry point. Extend {@link SlashHandler}, {@link ContextMenuHandler}, {@link ButtonHandler},
|
|
506
|
-
* {@link SelectMenuHandler}, or {@link ModalHandler} instead. This class adds `showModal` on top of the
|
|
507
|
-
* reply members.
|
|
508
|
-
*
|
|
509
|
-
* @typeParam Event - The repliable interaction type this handler processes
|
|
510
|
-
*/
|
|
511
|
-
var InteractionHandler = class extends RepliableHandler {
|
|
512
|
-
constructor(event, core, dispatch) {
|
|
513
|
-
super(event, core, dispatch);
|
|
514
|
-
}
|
|
515
|
-
/**
|
|
516
|
-
* Open a modal. Must be the initial response to this interaction. The modal kind rejects this call at
|
|
517
|
-
* compile time (Discord forbids a modal in response to a modal).
|
|
293
|
+
* @param port - The port the interaction server binds. {@default `3000` }
|
|
518
294
|
*/
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
* Default handler for interactions no manifest row matches. A reply failure here
|
|
528
|
-
* goes directly to the dispatch fault boundary, so it needs no guard of its own.
|
|
529
|
-
*
|
|
530
|
-
* @internal
|
|
531
|
-
*/
|
|
532
|
-
var UnhandledRepliable = class extends InteractionHandler {
|
|
533
|
-
async execute() {
|
|
534
|
-
await this.reply("Feature not implemented yet.");
|
|
535
|
-
}
|
|
536
|
-
};
|
|
537
|
-
|
|
538
|
-
//#endregion
|
|
539
|
-
//#region src/dispatch/resolve.ts
|
|
540
|
-
const COMPONENT_KIND = {
|
|
541
|
-
button: "button",
|
|
542
|
-
stringSelect: "stringMenu",
|
|
543
|
-
userSelect: "userMenu",
|
|
544
|
-
roleSelect: "roleMenu",
|
|
545
|
-
channelSelect: "channelMenu",
|
|
546
|
-
mentionableSelect: "mentionableMenu",
|
|
547
|
-
modal: "modal"
|
|
548
|
-
};
|
|
549
|
-
function commandKind(type) {
|
|
550
|
-
switch (type) {
|
|
551
|
-
case discord_api_types_v10.ApplicationCommandType.ChatInput: return "slash";
|
|
552
|
-
case discord_api_types_v10.ApplicationCommandType.User: return "userContextMenu";
|
|
553
|
-
case discord_api_types_v10.ApplicationCommandType.Message: return "messageContextMenu";
|
|
554
|
-
default: return null;
|
|
555
|
-
}
|
|
556
|
-
}
|
|
557
|
-
function componentMapKey(type) {
|
|
558
|
-
switch (type) {
|
|
559
|
-
case discord_api_types_v10.ComponentType.Button: return "button";
|
|
560
|
-
case discord_api_types_v10.ComponentType.StringSelect: return "stringSelect";
|
|
561
|
-
case discord_api_types_v10.ComponentType.UserSelect: return "userSelect";
|
|
562
|
-
case discord_api_types_v10.ComponentType.RoleSelect: return "roleSelect";
|
|
563
|
-
case discord_api_types_v10.ComponentType.ChannelSelect: return "channelSelect";
|
|
564
|
-
case discord_api_types_v10.ComponentType.MentionableSelect: return "mentionableSelect";
|
|
565
|
-
default: return null;
|
|
566
|
-
}
|
|
567
|
-
}
|
|
568
|
-
function set(map, kind, key, load) {
|
|
569
|
-
map.set(key, {
|
|
570
|
-
kind,
|
|
571
|
-
routeId: `${kind}:${key}`,
|
|
572
|
-
load
|
|
573
|
-
});
|
|
574
|
-
}
|
|
575
|
-
/** Builds the per-kind lookup maps. */
|
|
576
|
-
function buildRouteMaps(manifest) {
|
|
577
|
-
const maps = {
|
|
578
|
-
slash: /* @__PURE__ */ new Map(),
|
|
579
|
-
userContextMenu: /* @__PURE__ */ new Map(),
|
|
580
|
-
messageContextMenu: /* @__PURE__ */ new Map(),
|
|
581
|
-
autocomplete: /* @__PURE__ */ new Map(),
|
|
582
|
-
components: {
|
|
583
|
-
button: /* @__PURE__ */ new Map(),
|
|
584
|
-
stringSelect: /* @__PURE__ */ new Map(),
|
|
585
|
-
userSelect: /* @__PURE__ */ new Map(),
|
|
586
|
-
roleSelect: /* @__PURE__ */ new Map(),
|
|
587
|
-
channelSelect: /* @__PURE__ */ new Map(),
|
|
588
|
-
mentionableSelect: /* @__PURE__ */ new Map(),
|
|
589
|
-
modal: /* @__PURE__ */ new Map()
|
|
590
|
-
}
|
|
591
|
-
};
|
|
592
|
-
for (const row of manifest.commands) {
|
|
593
|
-
const kind = commandKind(row.type);
|
|
594
|
-
if (kind) set(maps[kind], kind, row.name, row.load);
|
|
595
|
-
}
|
|
596
|
-
for (const row of manifest.autocomplete) set(maps.autocomplete, "autocomplete", row.name, row.load);
|
|
597
|
-
for (const row of manifest.components) set(maps.components[row.kind], COMPONENT_KIND[row.kind], row.prefix, row.load);
|
|
598
|
-
return maps;
|
|
599
|
-
}
|
|
600
|
-
function unhandled(kind) {
|
|
601
|
-
return {
|
|
602
|
-
kind,
|
|
603
|
-
routeId: null,
|
|
604
|
-
load: () => Promise.resolve(kind === "autocomplete" ? { UnhandledAutocomplete } : { UnhandledRepliable })
|
|
605
|
-
};
|
|
606
|
-
}
|
|
607
|
-
/**
|
|
608
|
-
* Matches a verified non-PING interaction to its manifest row. A known kind with no row resolves to the
|
|
609
|
-
* unhandled default, whose handler replies "Feature not implemented yet." (empty choices on autocomplete).
|
|
610
|
-
* Null is an unrecognized payload shape, which the engine acks with a 202 without dispatching.
|
|
611
|
-
* Components and modals route by the stable customId prefix, so a wire whose layout hash drifted still
|
|
612
|
-
* routes to its handler, where decode refuses with `StaleCustomId`.
|
|
613
|
-
*/
|
|
614
|
-
function resolve(maps, interaction) {
|
|
615
|
-
switch (interaction.type) {
|
|
616
|
-
case discord_api_types_v10.InteractionType.ApplicationCommand: {
|
|
617
|
-
if (interaction.data.type === discord_api_types_v10.ApplicationCommandType.ChatInput) return maps.slash.get(slashRouteOf(interaction.data)) ?? unhandled("slash");
|
|
618
|
-
const kind = commandKind(interaction.data.type);
|
|
619
|
-
return kind ? maps[kind].get(interaction.data.name) ?? unhandled(kind) : null;
|
|
620
|
-
}
|
|
621
|
-
case discord_api_types_v10.InteractionType.ApplicationCommandAutocomplete: return maps.autocomplete.get(slashRouteOf(interaction.data)) ?? unhandled("autocomplete");
|
|
622
|
-
case discord_api_types_v10.InteractionType.MessageComponent: {
|
|
623
|
-
const key = componentMapKey(interaction.data.component_type);
|
|
624
|
-
if (!key) return null;
|
|
625
|
-
return maps.components[key].get((0, _seedcord_core_internal.prefixOf)(interaction.data.custom_id)) ?? unhandled(COMPONENT_KIND[key]);
|
|
295
|
+
async start(port = DEFAULT_PORT) {
|
|
296
|
+
this.requestedPort = port;
|
|
297
|
+
try {
|
|
298
|
+
await super.init();
|
|
299
|
+
} catch (caught) {
|
|
300
|
+
await this.shutdown.run(1, false);
|
|
301
|
+
Seedcord.reset();
|
|
302
|
+
throw caught;
|
|
626
303
|
}
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
const
|
|
649
|
-
if (
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
if (!signature) return false;
|
|
655
|
-
const timestampBytes = encoder.encode(timestamp);
|
|
656
|
-
const message = new Uint8Array(timestampBytes.length + body.length);
|
|
657
|
-
message.set(timestampBytes, 0);
|
|
658
|
-
message.set(body, timestampBytes.length);
|
|
659
|
-
return crypto.subtle.verify("Ed25519", await this.key, signature, message);
|
|
660
|
-
}
|
|
661
|
-
};
|
|
662
|
-
|
|
663
|
-
//#endregion
|
|
664
|
-
//#region src/receiver/ReplayGuard.ts
|
|
665
|
-
const REPLAY_WINDOW_MS = 3e5;
|
|
666
|
-
const SWEEP_GAP_MS = 6e4;
|
|
667
|
-
const MS_PER_SECOND = 1e3;
|
|
668
|
-
const TIMESTAMP_PATTERN = /^\d+$/;
|
|
669
|
-
var ReplayGuard = class {
|
|
670
|
-
seen = /* @__PURE__ */ new Map();
|
|
671
|
-
lastSweep = Date.now();
|
|
672
|
-
accepts(signatureHex, timestampHeader) {
|
|
673
|
-
const now = Date.now();
|
|
674
|
-
this.maybeSweep(now);
|
|
675
|
-
if (!TIMESTAMP_PATTERN.test(timestampHeader)) return false;
|
|
676
|
-
const timestampMs = Number(timestampHeader) * MS_PER_SECOND;
|
|
677
|
-
if (Math.abs(now - timestampMs) > REPLAY_WINDOW_MS) return false;
|
|
678
|
-
const rejectUntil = this.seen.get(signatureHex);
|
|
679
|
-
if (rejectUntil !== void 0 && rejectUntil >= now) return false;
|
|
680
|
-
this.seen.set(signatureHex, timestampMs + REPLAY_WINDOW_MS);
|
|
681
|
-
return true;
|
|
682
|
-
}
|
|
683
|
-
maybeSweep(now) {
|
|
684
|
-
if (now - this.lastSweep < SWEEP_GAP_MS) return;
|
|
685
|
-
this.lastSweep = now;
|
|
686
|
-
for (const [signature, rejectUntil] of this.seen) if (rejectUntil < now) this.seen.delete(signature);
|
|
304
|
+
return this;
|
|
305
|
+
}
|
|
306
|
+
static reset() {
|
|
307
|
+
super.reset();
|
|
308
|
+
_seedcord_logger.LoggerChannelRegistry.instance.reset();
|
|
309
|
+
}
|
|
310
|
+
registerStartupTasks() {
|
|
311
|
+
if (envapt.Envapter.isDevelopment || envapt.Envapter.isTest) this.registerHmrAwareModules();
|
|
312
|
+
this.startup.addTask(_seedcord_core_node_internal.StartupPhase.Configuration, "bus-initialization", async () => {
|
|
313
|
+
this.bus.logger.utils.initialization("Subscribers", "start");
|
|
314
|
+
await this.subscribers.init();
|
|
315
|
+
this.bus.logger.utils.initialization("Subscribers", "end");
|
|
316
|
+
});
|
|
317
|
+
const { interactions } = this;
|
|
318
|
+
if (interactions) this.startup.addTask(_seedcord_core_node_internal.StartupPhase.Configuration, "interactions-initialization", async () => {
|
|
319
|
+
interactions.logger.utils.initialization("Interactions", "start");
|
|
320
|
+
await interactions.init();
|
|
321
|
+
interactions.logger.utils.initialization("Interactions", "end");
|
|
322
|
+
});
|
|
323
|
+
this.startup.addTask(_seedcord_core_node_internal.StartupPhase.Ready, "http-server", () => this.listen());
|
|
324
|
+
if (!envapt.Envapter.isTest) this.startup.addTask(_seedcord_core_node_internal.StartupPhase.Ready, "identity", () => this.fetchUsername());
|
|
325
|
+
const { healthCheck } = this;
|
|
326
|
+
if (healthCheck) this.startup.addTask(_seedcord_core_node_internal.StartupPhase.Ready, "health-check", async () => {
|
|
327
|
+
healthCheck.logger.utils.initialization("HealthCheck", "start");
|
|
328
|
+
await healthCheck.init();
|
|
329
|
+
healthCheck.logger.utils.initialization("HealthCheck", "end");
|
|
330
|
+
});
|
|
687
331
|
}
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
const
|
|
693
|
-
|
|
694
|
-
const ACCEPTED = 202;
|
|
695
|
-
const BAD_REQUEST = 400;
|
|
696
|
-
const UNAUTHORIZED = 401;
|
|
697
|
-
const METHOD_NOT_ALLOWED = 405;
|
|
698
|
-
const PING = discord_api_types_v10.InteractionType.Ping;
|
|
699
|
-
const decoder = new TextDecoder();
|
|
700
|
-
function hasInteractionType(payload) {
|
|
701
|
-
return typeof payload === "object" && payload !== null && "type" in payload && typeof payload.type === "number";
|
|
702
|
-
}
|
|
703
|
-
/**
|
|
704
|
-
* Builds the HTTP-interactions engine, a `(request, ctx?) => Promise<Response>` handler.
|
|
705
|
-
*
|
|
706
|
-
* The handler verifies the Ed25519 signature over the raw request bytes, rejects stale or replayed
|
|
707
|
-
* requests, answers a PING with an in-body PONG, and acks every other interaction with an empty 202.
|
|
708
|
-
* The engine dispatches a matched interaction through the manifest before the 202 goes out. Gates run
|
|
709
|
-
* first and the sender posts any refusal over the REST callback. `execute()` continues past the 202 under
|
|
710
|
-
* `ctx.waitUntil` when the caller passes one (the edge entry), and an engine-held in-flight set tracks
|
|
711
|
-
* it otherwise (node paths). It reads only the method, headers, and body. Mount it at any path.
|
|
712
|
-
*
|
|
713
|
-
* Reads `DISCORD_PUBLIC_KEY` and `DISCORD_BOT_TOKEN` from the environment through envapt and throws a
|
|
714
|
-
* `SeedcordError` when either is missing or malformed.
|
|
715
|
-
*/
|
|
716
|
-
function createSeedcord(config, manifest) {
|
|
717
|
-
if (!envapt.Envapter.has("DISCORD_PUBLIC_KEY")) throw new _seedcord_errors_internal.SeedcordError(_seedcord_errors.SeedcordErrorCode.ConfigMissingPublicKey);
|
|
718
|
-
const publicKey = envapt.Envapter.getRequired("DISCORD_PUBLIC_KEY", envapt.Converters.String);
|
|
719
|
-
const token = (0, _seedcord_errors_internal.validateDiscordToken)(envapt.Envapter.get("DISCORD_BOT_TOKEN"));
|
|
720
|
-
const verifier = new Ed25519Verifier(publicKey);
|
|
721
|
-
const replays = new ReplayGuard();
|
|
722
|
-
const maps = buildRouteMaps(manifest);
|
|
723
|
-
const inFlight = /* @__PURE__ */ new Set();
|
|
724
|
-
const core = createCore(config, token);
|
|
725
|
-
const logger = new _seedcord_logger.Logger("Engine");
|
|
726
|
-
async function dispatchMatched(match, payload, ctx) {
|
|
727
|
-
const start = await dispatchInteraction({
|
|
728
|
-
match,
|
|
729
|
-
payload,
|
|
730
|
-
core
|
|
332
|
+
registerHmrAwareModules() {
|
|
333
|
+
this.startup.addTask(_seedcord_core_node_internal.StartupPhase.Configuration, "hmr-registration", async () => {
|
|
334
|
+
if (this.interactions) this.hmrManager.register(this.interactions);
|
|
335
|
+
this.hmrManager.register(this.subscribers);
|
|
336
|
+
for (const plugin of this.plugins) this.hmrManager.register(plugin);
|
|
337
|
+
await Promise.resolve();
|
|
731
338
|
});
|
|
732
|
-
if (!start) return;
|
|
733
|
-
const work = start();
|
|
734
|
-
if (ctx) ctx.waitUntil(work);
|
|
735
|
-
else {
|
|
736
|
-
inFlight.add(work);
|
|
737
|
-
work.finally(() => inFlight.delete(work));
|
|
738
|
-
}
|
|
739
339
|
}
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
340
|
+
async listen() {
|
|
341
|
+
const token = (0, _seedcord_errors_internal.validateDiscordToken)(envapt.Envapter.get("DISCORD_BOT_TOKEN"));
|
|
342
|
+
this.rest.setToken(token);
|
|
343
|
+
const maps = this.interactions?.maps ?? require_edge_index.buildRouteMaps(EMPTY_MANIFEST);
|
|
344
|
+
const { handle, inFlight } = require_edge_index.buildEngine(this, maps);
|
|
345
|
+
const server = (0, node_http.createServer)((incoming, outgoing) => {
|
|
346
|
+
(async () => {
|
|
347
|
+
await writeWebResponse(await handle(await toWebRequest(incoming)), outgoing);
|
|
348
|
+
})().catch((error) => {
|
|
349
|
+
outgoing.destroy(Error.isError(error) ? error : new Error(String(error)));
|
|
350
|
+
});
|
|
744
351
|
});
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
}
|
|
757
|
-
if (!hasInteractionType(payload)) return new Response(null, { status: BAD_REQUEST });
|
|
758
|
-
if (payload.type === PING) return Response.json({ type: discord_api_types_v10.InteractionResponseType.Pong });
|
|
352
|
+
this.server = server;
|
|
353
|
+
server.listen(this.requestedPort);
|
|
354
|
+
await (0, node_events.once)(server, "listening");
|
|
355
|
+
this.boundPort = server.address().port;
|
|
356
|
+
this.logger.info(`Interactions server listening on port ${_seedcord_logger.paint.sky.bold(String(this.boundPort))}`);
|
|
357
|
+
this.shutdown.addTask(_seedcord_core_node_internal.ShutdownPhase.Unbind, "stop-http-server", () => this.stopServer(), SERVER_SHUTDOWN_TIMEOUT_MS);
|
|
358
|
+
this.shutdown.addTask(_seedcord_core_node_internal.ShutdownPhase.Drain, "drain-inflight", async () => {
|
|
359
|
+
await Promise.allSettled(inFlight);
|
|
360
|
+
}, DRAIN_TIMEOUT_MS);
|
|
361
|
+
}
|
|
362
|
+
async fetchUsername() {
|
|
759
363
|
try {
|
|
760
|
-
const
|
|
761
|
-
|
|
364
|
+
const me = await this.rest.get(discord_api_types_v10.Routes.user("@me"));
|
|
365
|
+
this.fetchedUsername = me.username;
|
|
762
366
|
} catch (caught) {
|
|
763
|
-
logger.
|
|
367
|
+
this.logger.warn("could not fetch the bot identity", caught);
|
|
764
368
|
}
|
|
765
|
-
return new Response(null, { status: ACCEPTED });
|
|
766
|
-
};
|
|
767
|
-
}
|
|
768
|
-
|
|
769
|
-
//#endregion
|
|
770
|
-
//#region src/handlers/interaction/SlashHandler.ts
|
|
771
|
-
/**
|
|
772
|
-
* Base class for a chat-input (slash) command handler on the HTTP transport.
|
|
773
|
-
*
|
|
774
|
-
* Pass the route from the generated registry as the generic, then read `this.options` for a single
|
|
775
|
-
* command or `this.match` for several. Command authoring stays plain discord.js, `seedcord codegen`
|
|
776
|
-
* reads its `toJSON()` to type these options.
|
|
777
|
-
*
|
|
778
|
-
* @typeParam Route - One or more route keys from {@link SlashOptionRegistry}, e.g. `'ban'` or `'ban' | 'kick'`.
|
|
779
|
-
*/
|
|
780
|
-
var SlashHandler = class extends InteractionHandler {
|
|
781
|
-
resolver;
|
|
782
|
-
/**
|
|
783
|
-
* The typed options for this command's route. Required options drop the null, choices narrow to their
|
|
784
|
-
* literal union, and only the getters for kinds this command actually uses appear. Rich kinds resolve
|
|
785
|
-
* from the interaction's `resolved` data.
|
|
786
|
-
*/
|
|
787
|
-
get options() {
|
|
788
|
-
this.resolver ??= new HttpSlashOptions(this.event.data);
|
|
789
|
-
return this.resolver;
|
|
790
|
-
}
|
|
791
|
-
/**
|
|
792
|
-
* Run the arm for whichever command fired. Use this only when the handler is registered for several
|
|
793
|
-
* routes.
|
|
794
|
-
*
|
|
795
|
-
* Provide one arm per registered route, keyed by its route string, and each arm receives that route's
|
|
796
|
-
* own narrowed options. The arms must cover every route in the generic, a missing route or an unknown
|
|
797
|
-
* key is a compile error.
|
|
798
|
-
*
|
|
799
|
-
* @param arms - One handler per registered route, keyed by route string.
|
|
800
|
-
* @returns The result of the arm that ran.
|
|
801
|
-
*/
|
|
802
|
-
async match(arms) {
|
|
803
|
-
const route = slashRouteOf(this.event.data);
|
|
804
|
-
const arm = Object.hasOwn(arms, route) ? arms[route] : void 0;
|
|
805
|
-
if (!arm) throw new _seedcord_errors_internal.SeedcordError(_seedcord_errors.SeedcordErrorCode.SlashMatchArmMissing, [route]);
|
|
806
|
-
return await arm(this.options);
|
|
807
|
-
}
|
|
808
|
-
};
|
|
809
|
-
|
|
810
|
-
//#endregion
|
|
811
|
-
//#region src/handlers/interaction/ContextMenuHandler.ts
|
|
812
|
-
/**
|
|
813
|
-
* Base class for a context-menu command handler on the HTTP transport (right-click a user or a message).
|
|
814
|
-
*
|
|
815
|
-
* Pass the kind from {@link ApplicationCommandType} as the generic. Read the right-clicked entity from
|
|
816
|
-
* `this.target`, an `APIUser` for a user menu and an `APIMessage` for a message menu. Context menus carry
|
|
817
|
-
* no options, so a handler registered for several names reads `this.target` uniformly with no per-name
|
|
818
|
-
* branch.
|
|
819
|
-
*
|
|
820
|
-
* @typeParam Kind - `ApplicationCommandType.User` or `ApplicationCommandType.Message`.
|
|
821
|
-
*/
|
|
822
|
-
var ContextMenuHandler = class extends InteractionHandler {
|
|
823
|
-
get target() {
|
|
824
|
-
const data = this.event.data;
|
|
825
|
-
return data.type === discord_api_types_v10.ApplicationCommandType.User ? data.resolved.users[data.target_id] : data.resolved.messages[data.target_id];
|
|
826
|
-
}
|
|
827
|
-
/**
|
|
828
|
-
* The right-clicked user's guild member, resolved only on user menus fired in a guild. Reading it on a
|
|
829
|
-
* message menu is a compile error.
|
|
830
|
-
*/
|
|
831
|
-
get targetMember() {
|
|
832
|
-
const data = this.event.data;
|
|
833
|
-
return data.type === discord_api_types_v10.ApplicationCommandType.User ? data.resolved.members?.[data.target_id] ?? null : null;
|
|
834
|
-
}
|
|
835
|
-
};
|
|
836
|
-
|
|
837
|
-
//#endregion
|
|
838
|
-
//#region src/handlers/interaction/components/ComponentHandler.ts
|
|
839
|
-
/**
|
|
840
|
-
* Shared base the customId-routed component handlers extend on the HTTP transport.
|
|
841
|
-
*
|
|
842
|
-
* Not a public entry point. Extend {@link ButtonHandler}, {@link SelectMenuHandler}, or {@link ModalHandler}
|
|
843
|
-
* instead. This class defines the customId decode, the route matching, and the source-message verbs
|
|
844
|
-
* `update` and `deferUpdate`.
|
|
845
|
-
*
|
|
846
|
-
* @typeParam Event - The component or modal interaction type this handler processes
|
|
847
|
-
* @typeParam Defs - The customId route definitions registered on the concrete handler
|
|
848
|
-
*/
|
|
849
|
-
var ComponentHandler = class extends InteractionHandler {
|
|
850
|
-
/** Rewrite the source message this component interaction came from. */
|
|
851
|
-
update(response) {
|
|
852
|
-
return this.sender.update(response);
|
|
853
|
-
}
|
|
854
|
-
/** Acknowledge the component without changing the source message. */
|
|
855
|
-
deferUpdate() {
|
|
856
|
-
return this.sender.deferUpdate();
|
|
857
|
-
}
|
|
858
|
-
decoded;
|
|
859
|
-
get route() {
|
|
860
|
-
this.decoded ??= (0, _seedcord_core_internal.decodeComponentRoute)(this.constructor, this.event.data.custom_id);
|
|
861
|
-
return this.decoded;
|
|
862
|
-
}
|
|
863
|
-
/**
|
|
864
|
-
* The decoded params of the single route this handler is registered for.
|
|
865
|
-
*
|
|
866
|
-
* Reading this decodes `this.event.data.custom_id` once (cached after the first read) and throws
|
|
867
|
-
* `StaleCustomId` or `InvalidCustomId` when the wire no longer matches the current shape, which the
|
|
868
|
-
* dispatcher boundary turns into a reply. On a handler registered for several routes this is
|
|
869
|
-
* `never`, so use {@link match} instead.
|
|
870
|
-
*/
|
|
871
|
-
get params() {
|
|
872
|
-
return this.route.params;
|
|
873
|
-
}
|
|
874
|
-
/**
|
|
875
|
-
* Run the arm for whichever route the component was minted from. Use this only when the handler is
|
|
876
|
-
* registered for several routes. A single-route handler reads `this.params` directly. On a multi-route
|
|
877
|
-
* handler `this.params` is `never`, so match is the only way to read the decoded params.
|
|
878
|
-
*
|
|
879
|
-
* Provide one arm per registered route, keyed by its prefix, and each arm receives that route's own
|
|
880
|
-
* decoded params. The arms cover every registered route prefix, checked at compile time, and a prefix
|
|
881
|
-
* unmatched at runtime throws `CustomIdMatchArmMissing`. Decoding runs before any arm, so a stale or
|
|
882
|
-
* corrupt wire throws before an arm body executes.
|
|
883
|
-
*
|
|
884
|
-
* @param arms - One callback per registered route, keyed by prefix.
|
|
885
|
-
* @returns The result of the arm that ran.
|
|
886
|
-
*
|
|
887
|
-
* @example
|
|
888
|
-
* ```ts
|
|
889
|
-
* \@ButtonRoute(Approve, Reject)
|
|
890
|
-
* class ReviewButtons extends ButtonHandler<[typeof Approve, typeof Reject]> {
|
|
891
|
-
* async execute() {
|
|
892
|
-
* await this.match({
|
|
893
|
-
* approve: ({ userId }) => this.reply(`approved <@${userId}>`),
|
|
894
|
-
* reject: ({ userId }) => this.reply(`rejected <@${userId}>`)
|
|
895
|
-
* });
|
|
896
|
-
* }
|
|
897
|
-
* }
|
|
898
|
-
* ```
|
|
899
|
-
*/
|
|
900
|
-
async match(arms) {
|
|
901
|
-
const { prefix, params } = this.route;
|
|
902
|
-
const arm = Object.hasOwn(arms, prefix) ? arms[prefix] : void 0;
|
|
903
|
-
if (!arm) throw new _seedcord_errors_internal.SeedcordError(_seedcord_errors.SeedcordErrorCode.CustomIdMatchArmMissing, [prefix]);
|
|
904
|
-
return await arm(params);
|
|
905
369
|
}
|
|
906
|
-
|
|
907
|
-
|
|
908
|
-
|
|
909
|
-
|
|
910
|
-
|
|
911
|
-
|
|
912
|
-
|
|
913
|
-
|
|
914
|
-
|
|
915
|
-
|
|
916
|
-
|
|
917
|
-
|
|
918
|
-
|
|
919
|
-
|
|
920
|
-
var ButtonHandler = class extends ComponentHandler {};
|
|
921
|
-
|
|
922
|
-
//#endregion
|
|
923
|
-
//#region src/handlers/interaction/components/SelectMenuHandler.ts
|
|
924
|
-
/**
|
|
925
|
-
* Base class for a select menu handler on the HTTP transport.
|
|
926
|
-
*
|
|
927
|
-
* Pass the select kind first and the customId definitions second, the same order as `@SelectMenuRoute`,
|
|
928
|
-
* so `this.event.data` and its `values`/`resolved` are narrowed to that kind. Read `this.params` for a
|
|
929
|
-
* single route or `this.match` for several, and reply through the handler members or rewrite the source
|
|
930
|
-
* message with `this.update`.
|
|
931
|
-
*
|
|
932
|
-
* @typeParam Kind - The select kind from {@link SelectMenuKind}, e.g. `SelectMenuKind.User`.
|
|
933
|
-
* @typeParam Defs - The customId definitions this handler decodes, e.g. `[typeof AssignId]`.
|
|
934
|
-
*/
|
|
935
|
-
var SelectMenuHandler = class extends ComponentHandler {};
|
|
936
|
-
|
|
937
|
-
//#endregion
|
|
938
|
-
//#region src/handlers/interaction/components/ModalHandler.ts
|
|
939
|
-
/**
|
|
940
|
-
* Base class for a modal submit handler on the HTTP transport.
|
|
941
|
-
*
|
|
942
|
-
* Register the customId definitions this handler decodes with `@ModalRoute` and list the same ones in the
|
|
943
|
-
* generic. Read the submitted inputs off `this.event.data.components`. Reply through the handler members.
|
|
944
|
-
* Discord forbids opening a modal in response to a modal, so `showModal` fails compilation on this kind.
|
|
945
|
-
*
|
|
946
|
-
* @typeParam Defs - The customId definitions this handler decodes, e.g. `[typeof ConfigId]`.
|
|
947
|
-
*/
|
|
948
|
-
var ModalHandler = class extends ComponentHandler {
|
|
949
|
-
/** Rewrite the message this modal was opened from (only when a component opened it). */
|
|
950
|
-
update(response) {
|
|
951
|
-
this.ensureSourceMessage("update");
|
|
952
|
-
return super.update(response);
|
|
953
|
-
}
|
|
954
|
-
/** Silently acknowledge, leaving the source message untouched. */
|
|
955
|
-
deferUpdate() {
|
|
956
|
-
this.ensureSourceMessage("deferUpdate");
|
|
957
|
-
return super.deferUpdate();
|
|
958
|
-
}
|
|
959
|
-
ensureSourceMessage(method) {
|
|
960
|
-
if (this.event.message) return;
|
|
961
|
-
throw new _seedcord_errors_internal.SeedcordError(_seedcord_errors.SeedcordErrorCode.ReplyUpdateWithoutSource, [method, this.routeId]);
|
|
370
|
+
stopServer() {
|
|
371
|
+
const server = this.server;
|
|
372
|
+
if (!server?.listening) return Promise.resolve();
|
|
373
|
+
return new Promise((resolveClose, rejectClose) => {
|
|
374
|
+
server.close((err) => {
|
|
375
|
+
if (err) {
|
|
376
|
+
rejectClose(err);
|
|
377
|
+
return;
|
|
378
|
+
}
|
|
379
|
+
this.logger.info(_seedcord_logger.paint.coral.bold("Interactions server stopped"));
|
|
380
|
+
resolveClose();
|
|
381
|
+
});
|
|
382
|
+
server.closeIdleConnections();
|
|
383
|
+
});
|
|
962
384
|
}
|
|
963
385
|
};
|
|
964
386
|
|
|
965
387
|
//#endregion
|
|
966
|
-
//#region src/
|
|
388
|
+
//#region src/plugin.ts
|
|
967
389
|
/**
|
|
968
|
-
*
|
|
969
|
-
* the handler with the reply or drop the gate threw. Multiple gates are ANDed, so each must pass. A gate
|
|
970
|
-
* that requires a context the handler does not provide (a button gate on a slash handler, a gate on an
|
|
971
|
-
* autocomplete handler, or a `RequirePermissions([...], { in: 'guild' })` gate the http transport cannot
|
|
972
|
-
* satisfy) is a compile error at this line, and the error names the gate and the handler kind. Place it
|
|
973
|
-
* above the route decorator.
|
|
974
|
-
*
|
|
975
|
-
* Combine gates with {@link and} or {@link or} to build a single gate from multiple arms.
|
|
976
|
-
*
|
|
977
|
-
* @example
|
|
978
|
-
* ```ts
|
|
979
|
-
* import { PermissionFlagsBits } from 'discord-api-types/v10';
|
|
390
|
+
* Base class for an HTTP plugin, binding `this.core` to the HTTP {@link Core}.
|
|
980
391
|
*
|
|
981
|
-
*
|
|
982
|
-
*
|
|
983
|
-
* class Purge extends SlashHandler<'purge'> {
|
|
984
|
-
* async execute() {
|
|
985
|
-
* // both gates passed, so this runs in a guild with a caller who can moderate this channel
|
|
986
|
-
* }
|
|
987
|
-
* }
|
|
988
|
-
* ```
|
|
392
|
+
* A plugin that runs on either transport extends the base from `@seedcord/core/plugin`, whose
|
|
393
|
+
* `this.core` carries the shared members only.
|
|
989
394
|
*
|
|
990
|
-
* @typeParam
|
|
991
|
-
* @typeParam TCtor - The decorated handler's constructor, checked against every gate's required context.
|
|
992
|
-
* @param gates - One or more gates to attach, each ANDed so the handler runs only when all pass.
|
|
993
|
-
* @param ctor - The handler class being decorated, rejected at compile time when a gate requires a context it lacks.
|
|
994
|
-
*
|
|
995
|
-
* @see {@link defineGate}
|
|
996
|
-
* @see {@link defineEffectGate}
|
|
997
|
-
* @decorator
|
|
395
|
+
* @typeParam Opts - The transport, runtime, and capabilities the plugin declares.
|
|
998
396
|
*/
|
|
999
|
-
|
|
1000
|
-
return function(ctor) {
|
|
1001
|
-
const existing = Reflect.getMetadata(_seedcord_core_internal.GatedMetadataKey, ctor) ?? [];
|
|
1002
|
-
Reflect.defineMetadata(_seedcord_core_internal.GatedMetadataKey, [...existing, ...gates], ctor);
|
|
1003
|
-
};
|
|
1004
|
-
}
|
|
397
|
+
var Plugin = class extends _seedcord_core_plugin.Plugin {};
|
|
1005
398
|
|
|
1006
399
|
//#endregion
|
|
1007
400
|
//#region src/index.ts
|
|
1008
|
-
|
|
1009
|
-
|
|
401
|
+
var src_exports = /* @__PURE__ */ require_edge_index.__exportAll({
|
|
402
|
+
AutocompleteHandler: () => require_edge_index.AutocompleteHandler,
|
|
403
|
+
ButtonHandler: () => require_edge_index.ButtonHandler,
|
|
404
|
+
ComponentHandler: () => require_edge_index.ComponentHandler,
|
|
405
|
+
ContextMenuHandler: () => require_edge_index.ContextMenuHandler,
|
|
406
|
+
Gated: () => require_edge_index.Gated,
|
|
407
|
+
InteractionHandler: () => require_edge_index.InteractionHandler,
|
|
408
|
+
ModalHandler: () => require_edge_index.ModalHandler,
|
|
409
|
+
Plugin: () => Plugin,
|
|
410
|
+
RepliableHandler: () => require_edge_index.RepliableHandler,
|
|
411
|
+
Seedcord: () => Seedcord,
|
|
412
|
+
SelectMenuHandler: () => require_edge_index.SelectMenuHandler,
|
|
413
|
+
SlashHandler: () => require_edge_index.SlashHandler,
|
|
414
|
+
Subscriber: () => require_edge_index.Subscriber,
|
|
415
|
+
WebhookLog: () => require_edge_index.WebhookLog,
|
|
416
|
+
createSeedcord: () => require_edge_index.createSeedcord,
|
|
417
|
+
version: () => require_edge_index.version
|
|
418
|
+
});
|
|
1010
419
|
|
|
1011
420
|
//#endregion
|
|
1012
|
-
exports.AutocompleteHandler = AutocompleteHandler;
|
|
1013
|
-
exports.ButtonHandler = ButtonHandler;
|
|
1014
|
-
exports.ComponentHandler = ComponentHandler;
|
|
1015
|
-
exports.ContextMenuHandler = ContextMenuHandler;
|
|
1016
|
-
exports.Gated = Gated;
|
|
1017
|
-
exports.InteractionHandler = InteractionHandler;
|
|
1018
|
-
exports.ModalHandler = ModalHandler;
|
|
1019
|
-
exports.
|
|
1020
|
-
exports.
|
|
1021
|
-
exports.
|
|
1022
|
-
exports.
|
|
1023
|
-
exports.
|
|
421
|
+
exports.AutocompleteHandler = require_edge_index.AutocompleteHandler;
|
|
422
|
+
exports.ButtonHandler = require_edge_index.ButtonHandler;
|
|
423
|
+
exports.ComponentHandler = require_edge_index.ComponentHandler;
|
|
424
|
+
exports.ContextMenuHandler = require_edge_index.ContextMenuHandler;
|
|
425
|
+
exports.Gated = require_edge_index.Gated;
|
|
426
|
+
exports.InteractionHandler = require_edge_index.InteractionHandler;
|
|
427
|
+
exports.ModalHandler = require_edge_index.ModalHandler;
|
|
428
|
+
exports.Plugin = Plugin;
|
|
429
|
+
exports.RepliableHandler = require_edge_index.RepliableHandler;
|
|
430
|
+
exports.Seedcord = Seedcord;
|
|
431
|
+
exports.SelectMenuHandler = require_edge_index.SelectMenuHandler;
|
|
432
|
+
exports.SlashHandler = require_edge_index.SlashHandler;
|
|
433
|
+
exports.Subscriber = require_edge_index.Subscriber;
|
|
434
|
+
exports.WebhookLog = require_edge_index.WebhookLog;
|
|
435
|
+
exports.createSeedcord = require_edge_index.createSeedcord;
|
|
436
|
+
exports.version = require_edge_index.version;
|
|
1024
437
|
Object.keys(_seedcord_core).forEach(function (k) {
|
|
1025
438
|
if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, {
|
|
1026
439
|
enumerable: true,
|