@seedcord/http 0.0.1 → 0.1.0-next.1

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