@seedcord/http 0.2.0 → 0.2.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.
@@ -1 +0,0 @@
1
- {"version":3,"file":"edge.index-He_ZHDqC.cjs","names":["BaseReplySender","InteractionResponseType","sendFlags","deferFlags","MessageFlags","Routes","API","CoreRepliableHandler","ApplicationCommandOptionType","buildSlashRoute","logger","Logger","FaultThrottle","paint","Notice","PublishDefault","InteractionType","ApplicationCommandType","prefixOf","DiscordAPIError","ComponentType","Logger","MemoryRateLimiter","REST","Bus","BaseHandler","RESTJSONErrorCodes","DiscordAPIError","paint","reportedWrite","Routes","InteractionResponseType","Fault","Silence","Notice","asError","queuedMsFor","outcomeFor","DispatchContext","InteractionType","slowGateMonitor","runHandlerGates","SeedcordError","SeedcordErrorCode","Subscriber","ApplicationCommandOptionType","BaseHandler","SeedcordError","SeedcordErrorCode","reportedWrite","Routes","InteractionResponseType","ApplicationCommandType","ComponentType","SeedcordError","SeedcordErrorCode","InteractionType","prefixOf","SeedcordError","SeedcordErrorCode","InteractionType","Envapter","SeedcordError","SeedcordErrorCode","Converters","Logger","asError","PublishDefault","paint","InteractionResponseType","validateDiscordToken","Envapter","Routes","SeedcordError","SeedcordErrorCode","accessorStore","guardedAccessor","Logger","isEmojiTuple","SeedcordError","SeedcordErrorCode","Routes","SeedcordError","SeedcordErrorCode","ApplicationCommandType","decodeComponentRoute","SeedcordError","SeedcordErrorCode","SeedcordError","SeedcordErrorCode","CoreSubscriber","CoreWebhookLog","PaginatorBase","BaseArraySource","BaseCursorSource","GatedMetadataKey"],"sources":["../src/reply/ReplySender.ts","../src/api.ts","../src/handlers/RepliableHandler.ts","../src/gates/context.ts","../src/dispatch/slashRouteOf.ts","../src/dispatch/reportFault.ts","../src/dispatch/dispatchInteraction.ts","../src/dispatch/registerSubscribers.ts","../src/inputs/HttpSlashOptions.ts","../src/handlers/interaction/AutocompleteHandler.ts","../src/handlers/defaults/UnhandledAutocomplete.ts","../src/handlers/interaction/InteractionHandler.ts","../src/handlers/defaults/UnhandledRepliable.ts","../src/dispatch/resolve.ts","../src/receiver/Ed25519Verifier.ts","../src/receiver/ReplayGuard.ts","../src/engine.ts","../src/createSeedcord.ts","../src/applicationId.ts","../src/emojis/EmojiInjector.ts","../src/handlers/interaction/SlashHandler.ts","../src/handlers/interaction/ContextMenuHandler.ts","../src/handlers/interaction/components/ComponentHandler.ts","../src/handlers/interaction/components/ButtonHandler.ts","../src/handlers/interaction/components/SelectMenuHandler.ts","../src/handlers/interaction/components/ModalHandler.ts","../src/subscribers/index.ts","../src/pagination/Paginator.ts","../src/pagination/sources.ts","../src/gates/Gated.ts","../src/version.ts"],"sourcesContent":["import { BaseReplySender, deferFlags, sendFlags } from '@seedcord/core/internal';\nimport { InteractionResponseType, MessageFlags, Routes } from 'discord-api-types/v10';\n\nimport type { REST, RawFile } from '@discordjs/rest';\nimport type { Bus } from '@seedcord/core';\nimport type { SerializedReply } from '@seedcord/core/internal';\nimport type { DeferOpts, ReplyResponse, SendOpts, TypedOmit } from '@seedcord/types';\nimport type { APIMessage, APIModalInteractionResponseCallbackData } from 'discord-api-types/v10';\n\n/** The interaction payload fields the sender writes its wire from. */\nexport interface InteractionRef {\n readonly application_id: string;\n readonly id: string;\n readonly token: string;\n}\n\n/** The created message an http reply resolves to (the http `SentMessage` lens). */\nexport type SentMessage = APIMessage;\n\n// the framework's allowedMentions keys are camelCase, and the wire reads replied_user\ntype WireAllowedMentions = TypedOmit<NonNullable<ReplyResponse['allowedMentions']>, 'repliedUser'> & {\n replied_user?: boolean;\n};\n\ninterface WireAttachment {\n id: number;\n filename: string;\n description?: string;\n title?: string;\n}\n\ninterface MessageBody {\n flags: number;\n components: SerializedReply['components'];\n allowed_mentions?: WireAllowedMentions;\n attachments?: WireAttachment[];\n}\n\nfunction wireAllowedMentions(mentions: NonNullable<ReplyResponse['allowedMentions']>): WireAllowedMentions {\n const { repliedUser, ...wire } = mentions;\n return { ...wire, ...(repliedUser !== undefined && { replied_user: repliedUser }) };\n}\n\n// RawFile has no description field, so alt text goes on the wire attachments entries\nfunction wireAttachments(files: SerializedReply['files']): WireAttachment[] | null {\n if (!files?.some((file) => file.description ?? file.title)) return null;\n return files.map((file, index) => ({\n id: index,\n filename: file.name,\n ...(file.description && { description: file.description }),\n ...(file.title && { title: file.title })\n }));\n}\n\nfunction callbackData(reply: SerializedReply, flags: number): MessageBody {\n const attachments = wireAttachments(reply.files);\n return {\n flags,\n components: reply.components,\n ...(reply.allowedMentions && { allowed_mentions: wireAllowedMentions(reply.allowedMentions) }),\n ...(attachments && { attachments })\n };\n}\n\n/**\n * Writes interaction responses over the Discord REST callback and webhook endpoints. Construction is\n * internal to the repliable handler bases and the dispatcher.\n */\nexport class ReplySender extends BaseReplySender<SentMessage> {\n public constructor(\n private readonly ref: InteractionRef,\n private readonly rest: REST,\n routeId: string,\n bus: Bus\n ) {\n super(routeId, { bus, interactionId: ref.id });\n }\n\n protected async writeReply(response: ReplyResponse | string, opts?: SendOpts): Promise<SentMessage | undefined> {\n const reply = this.serialize(response);\n const result = await this.callback(\n InteractionResponseType.ChannelMessageWithSource,\n callbackData(reply, sendFlags(opts)),\n reply.files\n );\n return this.createdMessage(result);\n }\n\n protected async writeDefer(opts?: DeferOpts): Promise<void> {\n await this.callback(InteractionResponseType.DeferredChannelMessageWithSource, { flags: deferFlags(opts) });\n }\n\n protected async writeDeferUpdate(): Promise<void> {\n await this.callback(InteractionResponseType.DeferredMessageUpdate);\n }\n\n protected async writeUpdate(response: ReplyResponse | string): Promise<SentMessage | undefined> {\n const reply = this.serialize(response);\n const result = await this.callback(\n InteractionResponseType.UpdateMessage,\n callbackData(reply, MessageFlags.IsComponentsV2),\n reply.files\n );\n return this.createdMessage(result);\n }\n\n protected async writeFollowUp(response: ReplyResponse | string, opts?: SendOpts): Promise<SentMessage> {\n const reply = this.serialize(response);\n // discord returns the created message for interaction-token followups either way. wait=true pins\n // that contract and matches the djs webhook client\n const result = await this.rest.post(Routes.webhook(this.ref.application_id, this.ref.token), {\n body: callbackData(reply, sendFlags(opts)),\n query: new URLSearchParams({ wait: 'true' }),\n ...(reply.files && { files: this.rawFiles(reply.files) })\n });\n // justified: a webhook POST returns the created message\n return result as SentMessage;\n }\n\n protected writeEditOriginal(response: ReplyResponse | string): Promise<SentMessage> {\n return this.editMessage(\n Routes.webhookMessage(this.ref.application_id, this.ref.token),\n this.serialize(response)\n );\n }\n\n protected writeEditTarget(targetId: string, response: ReplyResponse | string): Promise<SentMessage> {\n const route = Routes.webhookMessage(this.ref.application_id, this.ref.token, targetId);\n return this.editMessage(route, this.serialize(response));\n }\n\n protected async writeDeleteOriginal(): Promise<void> {\n await this.rest.delete(Routes.webhookMessage(this.ref.application_id, this.ref.token));\n }\n\n protected async writeDeleteTarget(targetId: string): Promise<void> {\n await this.rest.delete(Routes.webhookMessage(this.ref.application_id, this.ref.token, targetId));\n }\n\n protected async writeModal(data: APIModalInteractionResponseCallbackData): Promise<void> {\n await this.callback(InteractionResponseType.Modal, data);\n }\n\n private async callback(\n type: InteractionResponseType,\n data?: unknown,\n files?: SerializedReply['files']\n ): Promise<unknown> {\n const withResponse =\n type === InteractionResponseType.ChannelMessageWithSource || type === InteractionResponseType.UpdateMessage;\n return await this.rest.post(Routes.interactionCallback(this.ref.id, this.ref.token), {\n body: { type, ...(data !== undefined && { data }) },\n ...(withResponse && { query: new URLSearchParams({ with_response: 'true' }) }),\n ...(files && { files: this.rawFiles(files) })\n });\n }\n\n private async editMessage(route: `/${string}`, reply: SerializedReply): Promise<SentMessage> {\n const result = await this.rest.patch(route, {\n body: callbackData(reply, MessageFlags.IsComponentsV2),\n ...(reply.files && { files: this.rawFiles(reply.files) })\n });\n // justified: a webhook message PATCH returns the edited message\n return result as SentMessage;\n }\n\n private rawFiles(files: NonNullable<SerializedReply['files']>): RawFile[] {\n return files.map((file) => ({ name: file.name, data: file.data }));\n }\n\n private createdMessage(result: unknown): SentMessage | undefined {\n // justified: the with_response callback wire shape\n return (result as { resource?: { message?: SentMessage } }).resource?.message;\n }\n}\n","import { API } from '@discordjs/core/http-only';\n\nimport type { REST } from '@discordjs/rest';\n\nconst apis = new WeakMap<REST, API>();\n\n// one API per rest client, constructed on first access\nexport function apiFor(rest: REST): API {\n let api = apis.get(rest);\n if (!api) {\n api = new API(rest);\n apis.set(rest, api);\n }\n return api;\n}\n","import { RepliableHandler as CoreRepliableHandler } from '@seedcord/core';\n\nimport { ReplySender } from '@reply/ReplySender';\nimport { apiFor } from '@src/api';\n\nimport type { Repliables } from './interactionTypes';\nimport type { API } from '@discordjs/core/http-only';\nimport type { Core } from '@interfaces/Core';\nimport type { SentMessage } from '@reply/ReplySender';\n\n/**\n * Shared base the repliable HTTP interaction handlers extend.\n *\n * Not a public entry point. Extend {@link SlashHandler}, {@link ButtonHandler}, {@link ModalHandler},\n * {@link SelectMenuHandler}, or {@link ContextMenuHandler} instead. This class binds the core reply base\n * to the http sender.\n *\n * @typeParam Event - The repliable interaction type this handler processes\n */\nexport abstract class RepliableHandler<Event extends Repliables> extends CoreRepliableHandler<\n Event,\n Core,\n SentMessage,\n never,\n ReplySender\n> {\n // core's base keeps event protected, and Paginator.start reads it from outside the class\n /** @internal */\n public getEvent(): Event {\n return this.event;\n }\n\n protected buildSender(event: Event, core: Core, routeId: string): ReplySender {\n const ref = { application_id: event.application_id, id: event.id, token: event.token };\n return new ReplySender(ref, core.rest, routeId, core.bus);\n }\n\n /**\n * Typed Discord REST API (`@discordjs/core/http-only`) over `core.rest`, one instance per core.\n * The interaction callbacks on `api.interactions` bypass the reply surface. The\n * `no-raw-interaction-acks` rule flags them in handler classes.\n */\n protected get api(): API {\n return apiFor(this.core.rest);\n }\n}\n","import type { InteractionGateContext } from './Gate';\nimport type { Core } from '@interfaces/Core';\nimport type { Repliables } from '@src/handlers/interactionTypes';\nimport type { APIUser } from 'discord-api-types/v10';\n\n// autocomplete is skipped before gates run, so the payload here always carries a reply target\nexport function interactionGateContext(\n payload: Repliables,\n core: Core,\n routeId: string | null\n): InteractionGateContext {\n const member = payload.member ?? null;\n // the wrapper types leave member and user both optional. Discord sends member.user in a guild and the\n // top-level user in a DM\n const resolved = member?.user ?? payload.user;\n return {\n kind: 'interaction',\n core,\n interaction: payload,\n // justified: every repliable interaction Discord delivers carries a user, the wrapper types don't say so\n user: resolved as APIUser,\n member,\n userId: resolved?.id ?? null,\n guildId: payload.guild_id ?? null,\n channelId: payload.channel?.id ?? null,\n memberRoleIds: member?.roles ?? [],\n memberPermissions: member ? BigInt(member.permissions) : null,\n // app_permissions is present on every interaction Discord delivers, including DMs, so it is never null here\n appPermissions: BigInt(payload.app_permissions),\n routeId\n };\n}\n","import { buildSlashRoute } from '@seedcord/utils/internal';\nimport { ApplicationCommandOptionType } from 'discord-api-types/v10';\n\nimport type {\n APIApplicationCommandAutocompleteInteraction,\n APIChatInputApplicationCommandInteraction\n} from 'discord-api-types/v10';\n\nexport type SlashLikeData = (\n APIChatInputApplicationCommandInteraction | APIApplicationCommandAutocompleteInteraction\n)['data'];\n\n/**\n * Computes the dispatch route for a chat-input or autocomplete payload, the raw-payload port of the\n * gateway's `slashRouteOf`. Both assemble keys through `buildSlashRoute`, so a dispatched interaction\n * and a generated registry key always match.\n */\nexport function slashRouteOf(data: SlashLikeData): string {\n const first = data.options?.[0];\n if (first?.type === ApplicationCommandOptionType.SubcommandGroup) {\n return buildSlashRoute(data.name, first.options[0]?.name, first.name);\n }\n if (first?.type === ApplicationCommandOptionType.Subcommand) {\n return buildSlashRoute(data.name, first.name);\n }\n return data.name;\n}\n","import { DiscordAPIError } from '@discordjs/rest';\nimport { Notice } from '@seedcord/core';\nimport { FaultThrottle, prefixOf, PublishDefault } from '@seedcord/core/internal';\nimport { Logger, paint } from '@seedcord/logger';\nimport { ApplicationCommandType, ComponentType, InteractionType } from 'discord-api-types/v10';\n\nimport { slashRouteOf } from './slashRouteOf';\n\nimport type { ValidInteractionTypes } from '@handlers/interactionTypes';\nimport type { Core } from '@interfaces/Core';\nimport type { FaultSource, SubscriptionData } from '@seedcord/core';\nimport type { RenderContext } from '@seedcord/types';\n\ntype InteractionFaultSource = Extract<FaultSource, { kind: 'interaction' }>;\n\n// lazy because the logger reads the environment, which binds after this module loads\nlet faultLogger: Logger | undefined;\nfunction logger(): Logger {\n faultLogger ??= new Logger('Faults', { channel: 'errors' });\n return faultLogger;\n}\n\n/**\n * Publishes a fault on the bus, the raw-payload equivalent of the reporting half of gateway's\n * `extractErrorResponse`. A reported {@link Notice} publishes `handledException`, everything else\n * publishes `unknownException`.\n *\n * @internal\n */\nexport function reportFault(\n error: Error,\n uuid: RenderContext['uuid'],\n payload: ValidInteractionTypes,\n core: Core\n): void {\n const throttle = FaultThrottle.for(core);\n const key = `${routeKeyOf(payload)}:${nameOf(error)}`;\n if (!throttle.shouldReport(key)) {\n logger().debug(`throttled duplicate fault ${paint.mute(key)}`);\n return;\n }\n\n const source = interactionSource(payload);\n if (error instanceof Notice && source)\n core.bus[PublishDefault]('handledException', { denial: error, uuid, source });\n else core.bus[PublishDefault]('unknownException', { uuid, error, ...actors(payload), metadata: payload });\n\n throttle.markReported(key);\n}\n\n// the stable route plus the error name, so a parameterized component collapses to one key\nfunction routeKeyOf(payload: ValidInteractionTypes): string {\n if (payload.type === InteractionType.ApplicationCommandAutocomplete)\n return `autocomplete:${slashRouteOf(payload.data)}`;\n if (payload.type === InteractionType.ApplicationCommand) {\n return payload.data.type === ApplicationCommandType.ChatInput ? slashRouteOf(payload.data) : payload.data.name;\n }\n // || not ??, an empty prefix (a too-short routeKey) must fall back to the full wire\n return prefixOf(payload.data.custom_id) || payload.data.custom_id;\n}\n\nfunction nameOf(error: Error): string {\n if (error instanceof Notice) return error.name;\n if (error instanceof DiscordAPIError) return String(error.code);\n return error.constructor.name;\n}\n\n// the raw payload carries guild_id but no guild name, so the guild arm of the payload stays empty here\nfunction actors(payload: ValidInteractionTypes): Pick<SubscriptionData<'unknownException'>, 'guild' | 'user'> {\n const user = payload.member?.user ?? payload.user;\n return { guild: undefined, user: user ? { id: user.id, username: user.username } : undefined };\n}\n\n// a null return reports through unknownException, which carries no interactionKind and no required userId\nfunction interactionSource(payload: ValidInteractionTypes): InteractionFaultSource | null {\n // discord sends member.user in a guild and user in a dm\n const user = payload.member?.user ?? payload.user;\n if (!user) return null;\n\n const common = {\n kind: 'interaction',\n userId: user.id,\n guildId: payload.guild_id ?? null,\n channelId: payload.channel?.id ?? null,\n interactionId: payload.id,\n raw: payload\n } as const;\n\n if (payload.type === InteractionType.ApplicationCommand) {\n const isSlash = payload.data.type === ApplicationCommandType.ChatInput;\n return {\n ...common,\n interactionKind: isSlash ? 'slash' : 'context-menu',\n command: routeKeyOf(payload),\n customId: null\n };\n }\n if (payload.type === InteractionType.ModalSubmit) {\n return { ...common, interactionKind: 'modal', command: null, customId: payload.data.custom_id };\n }\n if (payload.type === InteractionType.MessageComponent) {\n const isButton = payload.data.component_type === ComponentType.Button;\n return {\n ...common,\n interactionKind: isButton ? 'button' : 'select',\n command: null,\n customId: payload.data.custom_id\n };\n }\n return null;\n}\n","import { DiscordAPIError, REST } from '@discordjs/rest';\nimport { BaseHandler, Bus, DispatchContext, Fault, Notice, Silence } from '@seedcord/core';\nimport {\n asError,\n outcomeFor,\n queuedMsFor,\n reportDispatch,\n reportedWrite,\n runHandlerGates,\n slowGateMonitor\n} from '@seedcord/core/internal';\nimport { Logger, paint } from '@seedcord/logger';\nimport { MemoryRateLimiter } from '@seedcord/rate-limiter';\nimport { InteractionResponseType, InteractionType, RESTJSONErrorCodes, Routes } from 'discord-api-types/v10';\n\nimport { RepliableHandler } from '@handlers/RepliableHandler';\nimport { ReplySender } from '@reply/ReplySender';\nimport { interactionGateContext } from '@src/gates/context';\n\nimport { reportFault } from './reportFault';\n\nimport type { ResolvedRoute } from './resolve';\nimport type { ValidInteractionTypes } from '@handlers/interactionTypes';\nimport type { HttpConfig } from '@interfaces/Config';\nimport type { Core } from '@interfaces/Core';\nimport type { DispatchOutcome } from '@seedcord/core';\nimport type { IRateLimiter, RenderContext, TypedOmit } from '@seedcord/types';\n\n// lazy because the logger reads the environment, which binds after this module loads\nlet dispatchLogger: Logger | undefined;\nfunction logger(): Logger {\n dispatchLogger ??= new Logger('Dispatcher', { channel: 'interactions' });\n return dispatchLogger;\n}\n\ninterface HttpHandler {\n execute(): Promise<void>;\n}\n\ntype HandlerCtor = new (event: ValidInteractionTypes, core: Core, dispatch?: DispatchContext) => HttpHandler;\n\n// a writable view of Core, so the bus assignment below needs no second cast\ntype CoreDraft = TypedOmit<Core, 'bus'> & { bus: Bus };\n\nexport function createCore(config: HttpConfig, token: string): Core {\n const rateLimiter: IRateLimiter = config.store ?? new MemoryRateLimiter();\n // justified: bus completes the shape on the next line, and the Bus reads core at dispatch\n const draft = { config, rateLimiter, rest: new REST().setToken(token) } as CoreDraft;\n draft.bus = new Bus(draft);\n return draft;\n}\n\nfunction isHandlerCtor(value: unknown): value is HandlerCtor {\n return typeof value === 'function' && value.prototype instanceof BaseHandler;\n}\n\ninterface FaultScope {\n readonly core: Core;\n readonly payload: ValidInteractionTypes;\n readonly routeId: string;\n // null on autocomplete, whose only legal refusal is an empty type 8\n readonly sender: ReplySender | null;\n}\n\n// these codes from the boundary's own send mean the interaction is gone\nconst HARMLESS_API_CODES: ReadonlySet<number | string> = new Set([\n RESTJSONErrorCodes.UnknownInteraction,\n RESTJSONErrorCodes.InteractionHasAlreadyBeenAcknowledged,\n RESTJSONErrorCodes.UnknownMessage\n]);\n\n// never rethrows\nasync function sendGuarded(routeId: string, send: () => Promise<unknown>): Promise<void> {\n try {\n await send();\n } catch (error) {\n if (error instanceof DiscordAPIError && HARMLESS_API_CODES.has(error.code)) {\n logger().debug(`boundary send hit harmless code ${paint.amber(String(error.code))}`);\n return;\n }\n logger().error(`boundary send failed for route ${paint.sky.bold(routeId)}`, error);\n }\n}\n\n// a Notice is illegal on autocomplete, so empty choices clear the pending state. reports like any\n// other write, so a faulted autocomplete still shows its discord round trip\nasync function respondEmptyChoices(scope: FaultScope): Promise<void> {\n const telemetry = { bus: scope.core.bus, interactionId: scope.payload.id };\n await reportedWrite(telemetry, scope.routeId, 'respond', () =>\n scope.core.rest.post(Routes.interactionCallback(scope.payload.id, scope.payload.token), {\n body: { type: InteractionResponseType.ApplicationCommandAutocompleteResult, data: { choices: [] } }\n })\n );\n}\n\nfunction renderContext(core: Core, uuid: RenderContext['uuid']): RenderContext {\n const developerUsername = core.config.notifications?.developerUsername;\n return developerUsername === undefined ? { uuid } : { uuid, developerUsername };\n}\n\nasync function handleNotice(notice: Notice, uuid: RenderContext['uuid'], scope: FaultScope): Promise<void> {\n if (notice.report) {\n logger().error(`${notice.name}: ${paint.mute(uuid)}`, notice);\n reportFault(notice, uuid, scope.payload, scope.core);\n }\n const { sender } = scope;\n if (!sender) {\n await sendGuarded(scope.routeId, () => respondEmptyChoices(scope));\n return;\n }\n const response = notice.render(renderContext(scope.core, uuid));\n await sendGuarded(scope.routeId, () => sender.send(response, { ephemeral: notice.ephemeral }));\n}\n\nasync function handleRawFault(error: Error, uuid: RenderContext['uuid'], scope: FaultScope): Promise<void> {\n const { core, sender } = scope;\n\n if (core.config.errors?.errorStack ?? false) logger().error(paint.mute(uuid), error);\n else logger().error(`${paint.mute(uuid)} | ${error.message}`);\n\n reportFault(error, uuid, scope.payload, core);\n\n if (!sender) {\n await sendGuarded(scope.routeId, () => respondEmptyChoices(scope));\n return;\n }\n\n const override = core.config.errors?.defaultError;\n const card = override ? new override(uuid) : new Fault();\n const response = card.render(renderContext(core, uuid));\n await sendGuarded(scope.routeId, () => sender.send(response, { ephemeral: true }));\n}\n\nasync function handleFault(caught: unknown, scope: FaultScope): Promise<void> {\n if (caught instanceof Silence) {\n if (caught.reason !== undefined && (scope.core.config.errors?.logSilences ?? true)) {\n logger().debug(`Silence: ${caught.reason}`);\n }\n return;\n }\n\n const uuid = crypto.randomUUID();\n if (caught instanceof Notice) {\n await handleNotice(caught, uuid, scope);\n return;\n }\n\n const error = asError(caught);\n\n // empty by default, so every api code from the handler's own work reports\n const ignore = new Set<number | string>(scope.core.config.errors?.ignoreApiCodes ?? []);\n if (error instanceof DiscordAPIError && ignore.has(error.code)) {\n logger().debug(`swallowed api code ${paint.amber(String(error.code))}`);\n return;\n }\n\n await handleRawFault(error, uuid, scope);\n}\n\ninterface DispatchArgs {\n readonly match: ResolvedRoute;\n readonly payload: ValidInteractionTypes;\n readonly core: Core;\n}\n\nfunction unhandledRouteId(match: ResolvedRoute): string {\n if (match.routeId) return match.routeId;\n // an empty key means a customId seedcord never minted, since a minted routeKey always outlives its 3-char hash\n const key = match.attemptedKey ?? '';\n return `${match.kind}:${key.length > 0 ? key : 'unrouted'}`;\n}\n\n// nothing is acked in the pre-handler failure paths, so a fresh sender can reply the card\nfunction freshScope(match: ResolvedRoute, payload: ValidInteractionTypes, core: Core): FaultScope {\n const ref = { application_id: payload.application_id, id: payload.id, token: payload.token };\n const routeId = unhandledRouteId(match);\n return {\n core,\n payload,\n routeId,\n sender: match.kind === 'autocomplete' ? null : new ReplySender(ref, core.rest, routeId, core.bus)\n };\n}\n\n// the clock starts when the reporter is built, which is the first statement of the dispatch\nfunction dispatchReporter(\n match: ResolvedRoute,\n payload: ValidInteractionTypes,\n core: Core\n): (outcome: DispatchOutcome) => void {\n const startedAt = performance.now();\n // read here, since a read at publish time would count the handler run into the queue too\n const queuedMs = queuedMsFor(payload.id);\n return (outcome) => {\n reportDispatch(core.bus, {\n routeId: unhandledRouteId(match),\n interactionId: payload.id,\n kind: match.kind,\n outcome,\n fallback: match.routeId === null,\n startedAt,\n queuedMs\n });\n };\n}\n\n// reports in a finally, so a throw from the boundary still publishes\nasync function answer(\n caught: unknown,\n scope: FaultScope,\n report: (outcome: DispatchOutcome) => void,\n outcome: DispatchOutcome = outcomeFor(caught)\n): Promise<void> {\n try {\n await handleFault(caught, scope);\n } finally {\n report(outcome);\n }\n}\n\n// sends a response on either failure, so a null return means nothing can run\nasync function loadHandlerCtor(\n match: ResolvedRoute,\n payload: ValidInteractionTypes,\n core: Core,\n report: (outcome: DispatchOutcome) => void\n): Promise<HandlerCtor | null> {\n const routeId = unhandledRouteId(match);\n let exported: unknown;\n try {\n exported = await match.load();\n } catch (caught) {\n logger().error(`Route ${paint.sky.bold(routeId)} failed to load its handler.`, caught);\n await answer(caught, freshScope(match, payload, core), report, 'failed');\n return null;\n }\n\n if (isHandlerCtor(exported)) return exported;\n\n logger().error(`Route ${paint.sky.bold(routeId)} loaded an export that is not a handler class.`);\n const wrong = new Error(`route ${routeId} loaded an export that is not a handler class`);\n await answer(wrong, freshScope(match, payload, core), report, 'failed');\n return null;\n}\n\n/**\n * Runs the pre-ack phase for a matched interaction. Loads the route's handler class, constructs it, and\n * runs its gates. The sender posts any refusal. Returns the post-ack execute continuation, or null when a\n * gate refuses or nothing can run.\n */\nexport async function dispatchInteraction(args: DispatchArgs): Promise<(() => Promise<void>) | null> {\n const { match, payload, core } = args;\n const report = dispatchReporter(match, payload, core);\n\n const ctor = await loadHandlerCtor(match, payload, core, report);\n if (!ctor) return null;\n\n const routeId = unhandledRouteId(match);\n logger().debug(`Processing ${paint.mint.bold(routeId)} with ${paint.mute(ctor.name)}`);\n\n const dispatch = new DispatchContext(routeId);\n let handler: HttpHandler;\n try {\n handler = new ctor(payload, core, dispatch);\n } catch (caught) {\n await answer(caught, freshScope(match, payload, core), report);\n return null;\n }\n const scope: FaultScope = {\n core,\n payload,\n routeId,\n sender: handler instanceof RepliableHandler ? handler.getSender() : null\n };\n\n const refusal = await gateRefusal(ctor, match, payload, core);\n if (refusal) {\n await answer(refusal.caught, scope, report);\n return null;\n }\n\n return async () => {\n try {\n await handler.execute();\n report('handled');\n } catch (caught) {\n await answer(caught, scope, report);\n }\n };\n}\n\n// autocomplete has no reply target, so @Gated rejects it at compile time and this is the runtime backstop.\n// the caller answers the refusal, so one code path reports and replies\nasync function gateRefusal(\n ctor: HandlerCtor,\n match: ResolvedRoute,\n payload: ValidInteractionTypes,\n core: Core\n): Promise<{ caught: unknown } | null> {\n // the router derives match.kind from payload.type, so the two would be the same. the payload.type clause narrows\n // the union to Repliables for interactionGateContext below\n if (match.kind === 'autocomplete' || payload.type === InteractionType.ApplicationCommandAutocomplete) return null;\n const monitor = slowGateMonitor();\n try {\n await runHandlerGates(\n ctor,\n interactionGateContext(payload, core, match.routeId),\n match.routeId ?? undefined,\n monitor?.observe\n );\n return null;\n } catch (caught) {\n return { caught };\n } finally {\n // a refusing gate ate budget too, report either way\n monitor?.report(match.routeId);\n }\n}\n","import { Subscriber } from '@seedcord/core';\nimport { SeedcordErrorCode } from '@seedcord/errors';\nimport { SeedcordError } from '@seedcord/errors/internal';\n\nimport type { Bus } from '@seedcord/core';\nimport type { StoredSubscriberCtor, SubscriberRegistration } from '@seedcord/core/internal';\nimport type { RouteManifest } from '@src/manifest/RouteManifest';\n\n/**\n * Registers a manifest's subscribers on the bus without importing them. Each row's module loads on\n * the first publish of one of its keys, which keeps an isolate that never publishes free of the cost.\n *\n * @internal\n */\nexport function registerSubscribers(bus: Bus, manifest: RouteManifest): void {\n for (const row of manifest.subscriberRoutes) {\n bus.register({\n keys: row.keys,\n frequency: row.frequency,\n resolve: async () => {\n const keys = row.keys.join(', ');\n let module: Awaited<ReturnType<typeof row.load>>;\n try {\n module = await row.load();\n } catch (caught) {\n throw new SeedcordError(SeedcordErrorCode.RouteModuleLoadFailed, [keys, row.from], {\n cause: caught\n });\n }\n if (!Object.hasOwn(module, row.exportName)) {\n throw new SeedcordError(SeedcordErrorCode.InteractionRouteExportMissing, [\n keys,\n row.exportName,\n row.from\n ]);\n }\n\n // a hand-authored manifest reaches here too, so the check cannot rest on codegen\n const exported = module[row.exportName];\n if (typeof exported !== 'function' || !(exported.prototype instanceof Subscriber)) {\n throw new SeedcordError(SeedcordErrorCode.SubscriberRouteNotASubscriber, [\n keys,\n row.exportName,\n row.from\n ]);\n }\n // justified: the two checks above prove it is a Subscriber subclass\n return exported as StoredSubscriberCtor;\n }\n } satisfies SubscriberRegistration);\n }\n}\n","import { ApplicationCommandOptionType } from 'discord-api-types/v10';\n\nimport type { SlashLikeData } from '@src/dispatch/slashRouteOf';\nimport type {\n APIApplicationCommandInteractionDataBasicOption,\n APIApplicationCommandInteractionDataOption,\n APIAttachment,\n APIInteractionDataResolved,\n APIInteractionDataResolvedChannel,\n APIInteractionDataResolvedGuildMember,\n APIRole,\n APIUser,\n InteractionType\n} from 'discord-api-types/v10';\n\ntype AnyOption = APIApplicationCommandInteractionDataOption<InteractionType>;\ntype Leaf = APIApplicationCommandInteractionDataBasicOption<InteractionType>;\n\ninterface FocusedOption {\n name: string;\n value: string;\n}\n\n// the raw-payload option reader for the typed SlashOptions/AutocompleteOptions views.\nexport class HttpSlashOptions {\n private readonly leaves = new Map<string, Leaf>();\n private readonly resolved: APIInteractionDataResolved | undefined;\n\n constructor(data: SlashLikeData) {\n this.resolved = data.resolved;\n let options: readonly AnyOption[] = data.options ?? [];\n const first = options[0];\n if (first?.type === ApplicationCommandOptionType.SubcommandGroup) options = first.options;\n const second = options[0];\n if (second?.type === ApplicationCommandOptionType.Subcommand) options = second.options ?? [];\n for (const option of options) {\n if (\n option.type !== ApplicationCommandOptionType.Subcommand &&\n option.type !== ApplicationCommandOptionType.SubcommandGroup\n ) {\n this.leaves.set(option.name, option);\n }\n }\n }\n\n getString(name: string): string | null {\n const leaf = this.leaves.get(name);\n return leaf?.type === ApplicationCommandOptionType.String ? leaf.value : null;\n }\n\n getInteger(name: string): number | null {\n const leaf = this.leaves.get(name);\n return leaf?.type === ApplicationCommandOptionType.Integer ? numeric(leaf.value) : null;\n }\n\n getNumber(name: string): number | null {\n const leaf = this.leaves.get(name);\n return leaf?.type === ApplicationCommandOptionType.Number ? numeric(leaf.value) : null;\n }\n\n getBoolean(name: string): boolean | null {\n const leaf = this.leaves.get(name);\n return leaf?.type === ApplicationCommandOptionType.Boolean ? leaf.value : null;\n }\n\n getUser(name: string): APIUser | null {\n const leaf = this.leaves.get(name);\n if (leaf?.type !== ApplicationCommandOptionType.User) return null;\n return this.resolved?.users?.[leaf.value] ?? null;\n }\n\n getMember(name: string): APIInteractionDataResolvedGuildMember | null {\n const leaf = this.leaves.get(name);\n if (leaf?.type !== ApplicationCommandOptionType.User) return null;\n return this.resolved?.members?.[leaf.value] ?? null;\n }\n\n getChannel(name: string): APIInteractionDataResolvedChannel | null {\n const leaf = this.leaves.get(name);\n if (leaf?.type !== ApplicationCommandOptionType.Channel) return null;\n return this.resolved?.channels?.[leaf.value] ?? null;\n }\n\n getRole(name: string): APIRole | null {\n const leaf = this.leaves.get(name);\n if (leaf?.type !== ApplicationCommandOptionType.Role) return null;\n return this.resolved?.roles?.[leaf.value] ?? null;\n }\n\n getAttachment(name: string): APIAttachment | null {\n const leaf = this.leaves.get(name);\n if (leaf?.type !== ApplicationCommandOptionType.Attachment) return null;\n return this.resolved?.attachments?.[leaf.value] ?? null;\n }\n\n getMentionable(name: string): APIUser | APIInteractionDataResolvedGuildMember | APIRole | null {\n const leaf = this.leaves.get(name);\n if (leaf?.type !== ApplicationCommandOptionType.Mentionable) return null;\n const resolved = this.resolved;\n return (\n resolved?.members?.[leaf.value] ?? resolved?.users?.[leaf.value] ?? resolved?.roles?.[leaf.value] ?? null\n );\n }\n\n getFocused(): FocusedOption | null {\n for (const leaf of this.leaves.values()) {\n if ('focused' in leaf && leaf.focused === true) return { name: leaf.name, value: String(leaf.value) };\n }\n return null;\n }\n}\n\n// the autocomplete wire carries integer/number values as strings\nfunction numeric(value: number | string): number | null {\n if (typeof value === 'number') return value;\n if (value.trim() === '') return null;\n const parsed = Number(value);\n return Number.isNaN(parsed) ? null : parsed;\n}\n","import { BaseHandler } from '@seedcord/core';\nimport { reportedWrite } from '@seedcord/core/internal';\nimport { SeedcordErrorCode } from '@seedcord/errors';\nimport { SeedcordError } from '@seedcord/errors/internal';\nimport { InteractionResponseType, Routes } from 'discord-api-types/v10';\n\nimport { HttpSlashOptions } from '@inputs/HttpSlashOptions';\nimport { apiFor } from '@src/api';\nimport { slashRouteOf } from '@src/dispatch/slashRouteOf';\n\nimport type { API } from '@discordjs/core/http-only';\nimport type { Core } from '@interfaces/Core';\nimport type { AutocompleteOptions, DispatchContext, SlashOptionRegistry } from '@seedcord/core';\nimport type { AutocompletableNames, ChoiceValueOf, EntryFor, FocusedField } from '@seedcord/core/internal';\nimport type {\n APIApplicationCommandOptionChoice,\n APIApplicationCommandAutocompleteInteraction\n} from 'discord-api-types/v10';\nimport type { Promisable } from 'type-fest';\n\ntype FocusedArms<Route extends keyof SlashOptionRegistry, Ret> = {\n [Name in AutocompletableNames<Route>]: (\n value: string,\n respond: (\n choices: readonly APIApplicationCommandOptionChoice<ChoiceValueOf<EntryFor<Route, Name>>>[]\n ) => Promise<void>\n ) => Promisable<Ret>;\n};\n\n/**\n * Base class for an autocomplete handler on the HTTP transport.\n *\n * Pass the command route(s) from the generated registry as the generic. Branch on the focused field with\n * `this.match`, read already-entered sibling options with `this.options`, and find which command fired\n * with `this.route`.\n *\n * @typeParam Route - One or more route keys from {@link SlashOptionRegistry}, e.g. `'search'`.\n */\nexport abstract class AutocompleteHandler<Route extends keyof SlashOptionRegistry> extends BaseHandler<\n APIApplicationCommandAutocompleteInteraction,\n Core\n> {\n // keep this ctor. it gives typeof AutocompleteHandler a public construct signature the dispatcher\n // needs, and dropping it (inheriting BaseHandler's protected ctor) collapses the handler ctor type to never.\n constructor(event: APIApplicationCommandAutocompleteInteraction, core: Core, dispatch?: DispatchContext) {\n super(event, core, dispatch, 'interactions');\n }\n\n // phantom, never set at runtime.\n /** @internal */\n declare readonly __autocompleteRoute?: Route;\n\n /**\n * Typed Discord REST API (`@discordjs/core/http-only`) over `core.rest`, one instance per core.\n */\n protected get api(): API {\n return apiFor(this.core.rest);\n }\n\n private resolver?: HttpSlashOptions;\n\n private get reader(): HttpSlashOptions {\n this.resolver ??= new HttpSlashOptions(this.event.data);\n return this.resolver;\n }\n\n /**\n * The focused option for this interaction. `value` is always the raw partial string the user is typing,\n * even for an integer or number option, so coerce it yourself when you need a number.\n */\n protected get focused(): FocusedField<Route> {\n const focused = this.reader.getFocused();\n if (!focused) throw new SeedcordError(SeedcordErrorCode.AutocompleteNoFocusedOption);\n // the registry constrains the names, a focused field outside the set has no arm.\n return focused as FocusedField<Route>;\n }\n\n /**\n * Run the arm for the focused field. An autocomplete always dispatches by which field is focused, so\n * match is how you read it.\n *\n * Provide one arm per autocompletable field across the registered commands, keyed by field name. Each\n * arm receives the focused partial value and a `respond` typed to that field's choice value. The\n * arms must cover every autocompletable field, a missing field or an unknown key is a compile error. A\n * focused field with no arm, only reachable from a stale-deployed command, throws at runtime.\n *\n * @param arms - One handler per autocompletable field, keyed by field name.\n * @returns The result of the arm that ran.\n */\n protected async match<Ret>(arms: FocusedArms<Route, Ret>): Promise<Ret> {\n const { name, value } = this.focused;\n const respond = (choices: readonly APIApplicationCommandOptionChoice[]): Promise<void> => this.respond(choices);\n // justified: FocusedArms is keyed by field literals, the Record cast indexes it with the runtime field name.\n type Arm = (\n value: string,\n respond: (choices: readonly APIApplicationCommandOptionChoice[]) => Promise<void>\n ) => Promisable<Ret>;\n const arm = Object.hasOwn(arms, name) ? (arms as Record<string, Arm>)[name] : undefined;\n if (!arm) throw new SeedcordError(SeedcordErrorCode.AutocompleteMatchArmMissing, [name]);\n return await arm(value, respond);\n }\n\n /** Send autocomplete suggestions, callback type 8. Prefer {@link match}, which restricts each field's choices to its declared type. */\n protected async respond(choices: readonly APIApplicationCommandOptionChoice[]): Promise<void> {\n // a hand-built handler outside a dispatch carries no route id\n const routeId = this.dispatch?.routeId ?? 'autocomplete';\n await reportedWrite({ bus: this.core.bus, interactionId: this.event.id }, routeId, 'respond', () =>\n this.core.rest.post(Routes.interactionCallback(this.event.id, this.event.token), {\n body: { type: InteractionResponseType.ApplicationCommandAutocompleteResult, data: { choices } }\n })\n );\n }\n\n /** The firing command route, for a field whose completion differs per registered command. */\n protected get route(): Route {\n return slashRouteOf(this.event.data) as Route;\n }\n\n /**\n * The already-entered options on this command, restricted to the kinds Discord resolves during autocomplete\n * (string, integer, number, boolean) with every read nullable, since a sibling is partial while the user\n * types the focused field. The focused field is on `this.focused`.\n */\n protected get options(): AutocompleteOptions<Route> {\n // the reader exposes these getters, AutocompleteOptions is the registry-typed view over it.\n return this.reader as AutocompleteOptions<Route>;\n }\n}\n","import { AutocompleteHandler } from '@handlers/interaction/AutocompleteHandler';\n\n/**\n * Default handler for autocomplete no manifest row matches.\n * Empty choices are the only legal answer, they clear the pending state.\n *\n * @internal\n */\nexport class UnhandledAutocomplete extends AutocompleteHandler<never> {\n async execute(): Promise<void> {\n await this.respond([]);\n }\n}\n","import { RepliableHandler } from '@handlers/RepliableHandler';\n\nimport type { Repliables } from '@handlers/interactionTypes';\nimport type { Core } from '@interfaces/Core';\nimport type { DispatchContext } from '@seedcord/core';\nimport type { ModalLike } from '@seedcord/core/internal';\nimport type { APIModalSubmitInteraction } from 'discord-api-types/v10';\n\n/**\n * Shared base the repliable interaction handlers extend.\n *\n * Not a public entry point. Extend {@link SlashHandler}, {@link ContextMenuHandler}, {@link ButtonHandler},\n * {@link SelectMenuHandler}, or {@link ModalHandler} instead. This class adds `showModal` on top of the\n * reply members.\n *\n * @typeParam Event - The repliable interaction type this handler processes\n */\nexport abstract class InteractionHandler<Event extends Repliables> extends RepliableHandler<Event> {\n // the dispatcher needs a public construct signature, RepliableHandler's ctor is protected\n constructor(event: Event, core: Core, dispatch?: DispatchContext) {\n super(event, core, dispatch);\n }\n\n /**\n * Open a modal. Must be the initial response to this interaction. The modal kind rejects this call at\n * compile time (Discord forbids a modal in response to a modal).\n */\n protected showModal(\n this: InteractionHandler<Exclude<Repliables, APIModalSubmitInteraction>>,\n modal: ModalLike\n ): Promise<void> {\n return this.sender.showModal(modal);\n }\n}\n","import { InteractionHandler } from '@handlers/interaction/InteractionHandler';\n\nimport type { Repliables } from '@handlers/interactionTypes';\n\n/**\n * Default handler for interactions no manifest row matches. A reply failure here\n * goes directly to the dispatch fault boundary, so it needs no guard of its own.\n *\n * @internal\n */\nexport class UnhandledRepliable extends InteractionHandler<Repliables> {\n async execute(): Promise<void> {\n await this.reply('Feature not implemented yet.');\n }\n}\n","import { prefixOf, type InteractionRoutes } from '@seedcord/core/internal';\nimport { SeedcordErrorCode } from '@seedcord/errors';\nimport { SeedcordError } from '@seedcord/errors/internal';\nimport { ApplicationCommandType, ComponentType, InteractionType } from 'discord-api-types/v10';\n\nimport { UnhandledAutocomplete } from '@handlers/defaults/UnhandledAutocomplete';\nimport { UnhandledRepliable } from '@handlers/defaults/UnhandledRepliable';\n\nimport { slashRouteOf } from './slashRouteOf';\n\nimport type { ComponentRoute, RouteManifest, RouteModule } from '@src/manifest/RouteManifest';\nimport type { APIInteraction } from 'discord-api-types/v10';\n\ntype ResolvedKind = `${InteractionRoutes}`;\n\n/** A manifest row matched to an incoming interaction, keyed the way the gateway dispatcher keys. */\nexport interface ResolvedRoute {\n readonly kind: ResolvedKind;\n /**\n * The stable dispatch id, `kind:key` (`slash:ban`), the shape core's `routeIdOf` builds. Null for the\n * unhandled default, which matches no row.\n */\n readonly routeId: string | null;\n /** The key the router looked up. */\n readonly attemptedKey?: string;\n /** Resolves the one export the row registers. */\n readonly load: () => Promise<unknown>;\n}\n\n/** @internal */\nexport type RouteMap = Map<string, ResolvedRoute>;\n\ntype ComponentMapKey = ComponentRoute['kind'];\n\nexport interface RouteMaps {\n readonly slash: RouteMap;\n readonly userContextMenu: RouteMap;\n readonly messageContextMenu: RouteMap;\n readonly autocomplete: RouteMap;\n readonly components: Readonly<Record<ComponentMapKey, RouteMap>>;\n}\n\n// the manifest names selects `xSelect`, the resolved kinds name them `xMenu`\ntype ResolvedKindOf<Kind extends ComponentMapKey> = Kind extends `${infer Base}Select` ? `${Base}Menu` : Kind;\n\nconst COMPONENT_KIND = {\n button: 'button',\n stringSelect: 'stringMenu',\n userSelect: 'userMenu',\n roleSelect: 'roleMenu',\n channelSelect: 'channelMenu',\n mentionableSelect: 'mentionableMenu',\n modal: 'modal'\n} satisfies { [Kind in ComponentMapKey]: ResolvedKindOf<Kind> & ResolvedKind };\n\ntype CommandMapKey = Exclude<keyof RouteMaps, 'components' | 'autocomplete'>;\n\nfunction commandKind(type: ApplicationCommandType): CommandMapKey | null {\n switch (type) {\n case ApplicationCommandType.ChatInput: {\n return 'slash';\n }\n case ApplicationCommandType.User: {\n return 'userContextMenu';\n }\n case ApplicationCommandType.Message: {\n return 'messageContextMenu';\n }\n default: {\n return null;\n }\n }\n}\n\nfunction componentMapKey(type: ComponentType): Exclude<ComponentMapKey, 'modal'> | null {\n switch (type) {\n case ComponentType.Button: {\n return 'button';\n }\n case ComponentType.StringSelect: {\n return 'stringSelect';\n }\n case ComponentType.UserSelect: {\n return 'userSelect';\n }\n case ComponentType.RoleSelect: {\n return 'roleSelect';\n }\n case ComponentType.ChannelSelect: {\n return 'channelSelect';\n }\n case ComponentType.MentionableSelect: {\n return 'mentionableSelect';\n }\n default: {\n return null;\n }\n }\n}\n\nfunction namedExport(routeId: string, row: RouteModule): () => Promise<unknown> {\n return async () => {\n let moduleExports: Awaited<ReturnType<typeof row.load>>;\n try {\n moduleExports = await row.load();\n } catch (caught) {\n throw new SeedcordError(SeedcordErrorCode.RouteModuleLoadFailed, [routeId, row.from], { cause: caught });\n }\n if (!Object.hasOwn(moduleExports, row.exportName)) {\n throw new SeedcordError(SeedcordErrorCode.InteractionRouteExportMissing, [\n routeId,\n row.exportName,\n row.from\n ]);\n }\n return moduleExports[row.exportName];\n };\n}\n\nfunction describeRow(row: RouteModule): string {\n return `${row.exportName} (${row.from})`;\n}\n\n/**\n * Builds the per-kind lookup maps.\n *\n * @throws A **SeedcordError** when two rows resolve to the same route.\n */\nexport function buildRouteMaps(manifest: RouteManifest): RouteMaps {\n const maps: RouteMaps = {\n slash: new Map(),\n userContextMenu: new Map(),\n messageContextMenu: new Map(),\n autocomplete: new Map(),\n components: {\n button: new Map(),\n stringSelect: new Map(),\n userSelect: new Map(),\n roleSelect: new Map(),\n channelSelect: new Map(),\n mentionableSelect: new Map(),\n modal: new Map()\n }\n };\n const owners = new Map<string, RouteModule>();\n\n function set(map: RouteMap, kind: ResolvedKind, key: string, row: RouteModule): void {\n const routeId = `${kind}:${key}`;\n const owner = owners.get(routeId);\n if (owner) {\n // a bare map.set would let a later row shadow an earlier one\n throw new SeedcordError(SeedcordErrorCode.InteractionDuplicateRoute, [\n routeId,\n describeRow(owner),\n describeRow(row)\n ]);\n }\n owners.set(routeId, row);\n map.set(key, { kind, routeId, load: namedExport(routeId, row) });\n }\n\n for (const row of manifest.commandRoutes) {\n const kind = commandKind(row.type);\n if (kind) set(maps[kind], kind, row.name, row);\n }\n for (const row of manifest.autocompleteRoutes) {\n set(maps.autocomplete, 'autocomplete', row.name, row);\n }\n for (const row of manifest.componentRoutes) {\n set(maps.components[row.kind], COMPONENT_KIND[row.kind], row.prefix, row);\n }\n return maps;\n}\n\n// dispatched through the normal pipeline like the gateway's unhandled default\nfunction unhandled(kind: ResolvedKind, attemptedKey: string): ResolvedRoute {\n return {\n kind,\n routeId: null,\n attemptedKey,\n load: () => Promise.resolve(kind === 'autocomplete' ? UnhandledAutocomplete : UnhandledRepliable)\n };\n}\n\n/**\n * Matches a verified non-PING interaction to its manifest row. A known kind with no row resolves to the\n * unhandled default, whose handler replies \"Feature not implemented yet.\" (empty choices on autocomplete).\n * Null is an unrecognized payload shape, which the engine acks with a 202 without dispatching.\n * Components and modals route by the stable customId prefix, so a wire whose layout hash drifted still\n * routes to its handler, where decode refuses with `StaleCustomId`.\n */\nexport function resolve(maps: RouteMaps, interaction: APIInteraction): ResolvedRoute | null {\n switch (interaction.type) {\n case InteractionType.ApplicationCommand: {\n if (interaction.data.type === ApplicationCommandType.ChatInput) {\n const route = slashRouteOf(interaction.data);\n return maps.slash.get(route) ?? unhandled('slash', route);\n }\n const kind = commandKind(interaction.data.type);\n return kind ? (maps[kind].get(interaction.data.name) ?? unhandled(kind, interaction.data.name)) : null;\n }\n case InteractionType.ApplicationCommandAutocomplete: {\n const route = slashRouteOf(interaction.data);\n return maps.autocomplete.get(route) ?? unhandled('autocomplete', route);\n }\n case InteractionType.MessageComponent: {\n const key = componentMapKey(interaction.data.component_type);\n if (!key) return null;\n const prefix = prefixOf(interaction.data.custom_id);\n return maps.components[key].get(prefix) ?? unhandled(COMPONENT_KIND[key], prefix);\n }\n case InteractionType.ModalSubmit: {\n const prefix = prefixOf(interaction.data.custom_id);\n return maps.components.modal.get(prefix) ?? unhandled('modal', prefix);\n }\n default: {\n return null;\n }\n }\n}\n","import { SeedcordErrorCode } from '@seedcord/errors';\nimport { SeedcordError } from '@seedcord/errors/internal';\n\nconst PUBLIC_KEY_BYTES = 32;\nconst SIGNATURE_BYTES = 64;\nconst HEX_RADIX = 16;\nconst HEX_PATTERN = /^[0-9a-f]+$/i;\n\nfunction hexToBytes(hex: string, byteLength: number): Uint8Array<ArrayBuffer> | null {\n if (hex.length !== byteLength * 2 || !HEX_PATTERN.test(hex)) return null;\n\n const bytes = new Uint8Array(byteLength);\n for (let index = 0; index < byteLength; index++) {\n bytes[index] = Number.parseInt(hex.slice(index * 2, index * 2 + 2), HEX_RADIX);\n }\n return bytes;\n}\n\nconst encoder = new TextEncoder();\n\nexport class Ed25519Verifier {\n private readonly key: Promise<CryptoKey>;\n\n constructor(publicKeyHex: string) {\n const publicKey = hexToBytes(publicKeyHex, PUBLIC_KEY_BYTES);\n if (!publicKey) throw new SeedcordError(SeedcordErrorCode.ConfigIncorrectPublicKey);\n\n this.key = crypto.subtle.importKey('raw', publicKey, 'Ed25519', false, ['verify']);\n }\n\n async verify(signatureHex: string, timestamp: string, body: Uint8Array): Promise<boolean> {\n const signature = hexToBytes(signatureHex, SIGNATURE_BYTES);\n if (!signature) return false;\n\n const timestampBytes = encoder.encode(timestamp);\n const message = new Uint8Array(timestampBytes.length + body.length);\n message.set(timestampBytes, 0);\n message.set(body, timestampBytes.length);\n\n return crypto.subtle.verify('Ed25519', await this.key, signature, message);\n }\n}\n","const REPLAY_WINDOW_MS = 300_000; // compared in both directions, clock skew stays inside the window\nconst SWEEP_GAP_MS = 60_000;\nconst MS_PER_SECOND = 1000;\nconst TIMESTAMP_PATTERN = /^\\d+$/;\n\n// the seen map is per-isolate on edge, so a fresh isolate rejects a replay on freshness alone\nexport class ReplayGuard {\n private readonly seen = new Map<string, number>();\n private lastSweep = Date.now();\n\n // the parsed value feeds unseen(), which only ever sees timestamps this already accepted\n public fresh(timestampHeader: string): number | null {\n if (!TIMESTAMP_PATTERN.test(timestampHeader)) return null;\n const timestampMs = Number(timestampHeader) * MS_PER_SECOND;\n return Math.abs(Date.now() - timestampMs) <= REPLAY_WINDOW_MS ? timestampMs : null;\n }\n\n public unseen(signatureHex: string, timestampMs: number): boolean {\n const now = Date.now();\n this.maybeSweep(now);\n\n // >= because a timestamp at the exact stale edge is accepted and its entry expires at `now`\n const rejectUntil = this.seen.get(signatureHex);\n if (rejectUntil !== undefined && rejectUntil >= now) return false;\n\n // expires when the freshness check starts rejecting this timestamp\n this.seen.set(signatureHex, timestampMs + REPLAY_WINDOW_MS);\n return true;\n }\n\n // swept on access, a construction-time timer throws in workers global scope\n private maybeSweep(now: number): void {\n if (now - this.lastSweep < SWEEP_GAP_MS) return;\n this.lastSweep = now;\n // strict, the sweep runs before the dedup lookup and must keep an entry expiring exactly at `now`\n for (const [signature, rejectUntil] of this.seen) {\n if (rejectUntil < now) this.seen.delete(signature);\n }\n }\n}\n","import { asError, PublishDefault } from '@seedcord/core/internal';\nimport { SeedcordErrorCode } from '@seedcord/errors';\nimport { SeedcordError } from '@seedcord/errors/internal';\nimport { Logger, paint } from '@seedcord/logger';\nimport { InteractionResponseType, InteractionType } from 'discord-api-types/v10';\nimport { Converters, Envapter } from 'envapt';\n\nimport { dispatchInteraction } from './dispatch/dispatchInteraction';\nimport { resolve } from './dispatch/resolve';\nimport { Ed25519Verifier } from './receiver/Ed25519Verifier';\nimport { ReplayGuard } from './receiver/ReplayGuard';\n\nimport type { RouteMaps } from './dispatch/resolve';\nimport type { ValidInteractionTypes } from '@handlers/interactionTypes';\nimport type { Core } from '@interfaces/Core';\nimport type { APIInteraction } from 'discord-api-types/v10';\n\nconst SIGNATURE_HEADER = 'x-signature-ed25519';\nconst TIMESTAMP_HEADER = 'x-signature-timestamp';\n\nconst ACCEPTED = 202;\nconst BAD_REQUEST = 400;\nconst UNAUTHORIZED = 401;\nconst METHOD_NOT_ALLOWED = 405;\n\n// widened so the raw payload's number field compares without an unsafe enum comparison\nconst PING: number = InteractionType.Ping;\n\nconst decoder = new TextDecoder();\n\ntype Outcome = 'not-post' | 'unsigned' | 'stale' | 'bad-signature' | 'bad-body' | 'ping' | 'replay' | 'dispatched';\ntype Answer = readonly [Response, Outcome];\n\nfunction hasInteractionType(payload: unknown): payload is { type: number } {\n return typeof payload === 'object' && payload !== null && 'type' in payload && typeof payload.type === 'number';\n}\n\n/** Structural match for the Workers `ExecutionContext`. Pass it from the edge entry so post-202 work runs under `waitUntil`. */\nexport interface EngineContext {\n waitUntil(promise: Promise<unknown>): void;\n}\n\nexport interface EngineParts {\n readonly handle: (request: Request, ctx?: EngineContext) => Promise<Response>;\n /** In-flight post-202 work on the node paths, drained at shutdown. */\n readonly inFlight: ReadonlySet<Promise<void>>;\n}\n\n// shared by createSeedcord (frozen manifest maps) and the node host (live dispatcher maps)\nexport function buildEngine(core: Core, maps: RouteMaps): EngineParts {\n if (!Envapter.has('DISCORD_PUBLIC_KEY')) throw new SeedcordError(SeedcordErrorCode.ConfigMissingPublicKey);\n const publicKey = Envapter.getRequired('DISCORD_PUBLIC_KEY', Converters.String);\n\n const verifier = new Ed25519Verifier(publicKey);\n const replays = new ReplayGuard();\n const inFlight = new Set<Promise<void>>();\n // constructed here because the logger reads the environment, which binds before this factory runs\n const logger = new Logger('Engine', { channel: 'bot' });\n\n async function dispatchMatched(\n match: NonNullable<ReturnType<typeof resolve>>,\n payload: ValidInteractionTypes,\n ctx: EngineContext | undefined\n ): Promise<void> {\n const start = await dispatchInteraction({ match, payload, core });\n if (!start) return;\n\n // the post-ack phase runs unawaited, so its own catch is the only thing between a throw and\n // an unhandled rejection\n const work = start().catch(rootFault);\n if (ctx) {\n ctx.waitUntil(work);\n } else {\n inFlight.add(work);\n void work.finally(() => inFlight.delete(work));\n }\n }\n\n // make sure an escaped error doesn't crash the process\n function rootFault(caught: unknown): void {\n const error = asError(caught);\n logger.error('dispatch failed past the boundary', error);\n core.bus[PublishDefault]('unhandledInteractionError', { error });\n }\n\n const handle = async (request: Request, ctx?: EngineContext): Promise<Response> => {\n const [response, outcome] = await respond(request, ctx);\n logger.debug(`${request.method} ${outcome} ${paint.amber(String(response.status))}`);\n return response;\n };\n\n const respond = async (request: Request, ctx?: EngineContext): Promise<Answer> => {\n if (request.method !== 'POST') {\n return [new Response(null, { status: METHOD_NOT_ALLOWED, headers: { allow: 'POST' } }), 'not-post'];\n }\n\n const signature = request.headers.get(SIGNATURE_HEADER);\n const timestamp = request.headers.get(TIMESTAMP_HEADER);\n if (signature === null || timestamp === null) return [new Response(null, { status: UNAUTHORIZED }), 'unsigned'];\n\n const timestampMs = replays.fresh(timestamp);\n if (timestampMs === null) return [new Response(null, { status: UNAUTHORIZED }), 'stale'];\n\n const body = new Uint8Array(await request.arrayBuffer());\n if (!(await verifier.verify(signature, timestamp, body))) {\n return [new Response(null, { status: UNAUTHORIZED }), 'bad-signature'];\n }\n\n let payload: unknown;\n try {\n payload = JSON.parse(decoder.decode(body));\n } catch {\n return [new Response(null, { status: BAD_REQUEST }), 'bad-body'];\n }\n if (!hasInteractionType(payload)) return [new Response(null, { status: BAD_REQUEST }), 'bad-body'];\n\n // discord resends the same signed ping while verifying an endpoint, and a 401 there reads as a broken endpoint\n if (payload.type === PING) {\n return [Response.json({ type: InteractionResponseType.Pong }), 'ping'];\n }\n\n if (!replays.unseen(signature, timestampMs)) return [new Response(null, { status: UNAUTHORIZED }), 'replay'];\n\n try {\n // justified: the payload is signed by Discord, and the type field anchors the discriminated union\n core.bus[PublishDefault]('anyInteraction', { interaction: payload as APIInteraction });\n const match = resolve(maps, payload as APIInteraction);\n if (match) await dispatchMatched(match, payload as ValidInteractionTypes, ctx);\n } catch (caught) {\n // a throw here must never eat the ack\n rootFault(caught);\n }\n\n return [new Response(null, { status: ACCEPTED }), 'dispatched'];\n };\n\n return { handle, inFlight };\n}\n","import { validateDiscordToken } from '@seedcord/errors/internal';\nimport { Envapter } from 'envapt';\n\nimport { createCore } from './dispatch/dispatchInteraction';\nimport { registerSubscribers } from './dispatch/registerSubscribers';\nimport { buildRouteMaps } from './dispatch/resolve';\nimport { buildEngine } from './engine';\n\nimport type { EngineContext } from './engine';\nimport type { HttpConfig } from '@interfaces/Config';\nimport type { RouteManifest } from '@src/manifest/RouteManifest';\n\nexport type { EngineContext } from './engine';\n\n/**\n * Builds the HTTP-interactions engine, a `(request, ctx?) => Promise<Response>` handler.\n *\n * The handler verifies the Ed25519 signature over the raw request bytes, rejects stale or replayed\n * requests, answers a PING with an in-body PONG, and acks every other interaction with an empty 202.\n * The engine dispatches a matched interaction through the manifest before the 202 goes out. Gates run\n * first and the sender posts any refusal over the REST callback. `execute()` continues past the 202 under\n * `ctx.waitUntil` when the caller passes one (the edge entry), and an engine-held in-flight set tracks\n * it otherwise (node paths). It reads only the method, headers, and body. Mount it at any path.\n *\n * Reads `DISCORD_PUBLIC_KEY` and `DISCORD_BOT_TOKEN` from the environment through envapt and throws a\n * `SeedcordError` when either is missing or malformed.\n */\nexport function createSeedcord(\n config: HttpConfig,\n manifest: RouteManifest\n): (request: Request, ctx?: EngineContext) => Promise<Response> {\n const token = validateDiscordToken(Envapter.get('DISCORD_BOT_TOKEN'));\n const core = createCore(config, token);\n core.bus.registerDefaults();\n registerSubscribers(core.bus, manifest);\n return buildEngine(core, buildRouteMaps(manifest)).handle;\n}\n","import { SeedcordErrorCode } from '@seedcord/errors';\nimport { SeedcordError } from '@seedcord/errors/internal';\nimport { Routes } from 'discord-api-types/v10';\n\nimport type { REST } from '@discordjs/rest';\nimport type { APIApplication } from 'discord-api-types/v10';\n\n/**\n * Reads the bot's own application id over REST. A gateway host takes it off the logged-in client, and\n * an http host has no session to read it from.\n *\n * @internal\n */\nexport async function fetchApplicationId(rest: REST): Promise<string> {\n try {\n // justified: the discord api contract for this route\n const application = (await rest.get(Routes.currentApplication())) as APIApplication;\n return application.id;\n } catch (error) {\n throw new SeedcordError(SeedcordErrorCode.CoreApplicationUnavailable, { cause: error });\n }\n}\n","import { accessorStore, clearStore, guardedAccessor, isEmojiTuple } from '@seedcord/core/internal';\nimport { SeedcordErrorCode } from '@seedcord/errors';\nimport { SeedcordError } from '@seedcord/errors/internal';\nimport { Logger } from '@seedcord/logger';\nimport { Routes } from 'discord-api-types/v10';\n\nimport { fetchApplicationId } from '@src/applicationId';\n\nimport type { Core } from '@interfaces/Core';\nimport type { EmojiMap } from '@seedcord/types';\nimport type { APIEmoji, APIMessageComponentEmoji } from 'discord-api-types/v10';\n\n/** A resolved emoji. Renders as `<:name:id>` in message content, or `<a:name:id>` when animated. */\nexport interface ResolvedEmoji extends APIMessageComponentEmoji {\n readonly id: string;\n readonly name: string;\n readonly animated: boolean;\n toString(): string;\n}\n\n// a class keeps toString off the own keys, which setEmoji rejects past the three wire fields\nclass Emoji implements ResolvedEmoji {\n constructor(\n public readonly name: string,\n public readonly id: string,\n public readonly animated = false\n ) {}\n\n public toString(): string {\n return `<${this.animated ? 'a' : ''}:${this.name}:${this.id}>`;\n }\n}\n\nconst emojiStorage = accessorStore<ResolvedEmoji>();\n\nfunction reasonOf(error: unknown): string {\n return Error.isError(error) ? error.message : String(error);\n}\n\nfunction byName(list: readonly APIEmoji[]): Map<string, APIEmoji> {\n const map = new Map<string, APIEmoji>();\n for (const entry of list) if (entry.name) map.set(entry.name, entry);\n return map;\n}\n\n/** The global {@link Emojis} accessor type. */\nexport type InjectedEmojiMap = {\n [K in keyof EmojiMap]: ResolvedEmoji;\n};\n\n/**\n * The bot's resolved emojis, keyed by {@link EmojiMap}. Filled by {@link EmojiInjector} during startup.\n * A read before that throws.\n */\nexport const Emojis = guardedAccessor('Emojis', emojiStorage) as InjectedEmojiMap;\n\n/**\n * Resolves the configured emojis over REST at startup.\n *\n * @internal\n */\nexport class EmojiInjector {\n private readonly logger = new Logger('Emojis', { channel: 'bot' });\n\n constructor(\n private readonly core: Core,\n // the host passes its memoized one so a boot that also deploys commands resolves the id once\n private readonly applicationId: () => Promise<string> = () => fetchApplicationId(core.rest)\n ) {}\n\n public async init(): Promise<void> {\n clearStore(emojiStorage);\n\n const configured = this.core.config.bot.emojis;\n if (!configured || Object.keys(configured).length === 0) {\n this.logger.debug('No emojis configured, skipping emoji injection.');\n return;\n }\n\n const failures: string[] = [];\n const guilds = new Map<string, Map<string, APIEmoji>>();\n let application: Map<string, APIEmoji> | undefined;\n\n for (const [key, value] of Object.entries(configured)) {\n if (isEmojiTuple(value)) await this.resolveTuple(key, value, guilds, failures);\n else if (typeof value === 'string') {\n application ??= await this.applicationEmojis(failures);\n this.resolve(key, value, application, failures, 'the application');\n } else failures.push(` - \"${key}\" has an invalid value (expected a name or [name, guildId])`);\n }\n\n // surface every unresolved emoji at once so the user fixes the whole config in one pass\n if (failures.length > 0) {\n throw new SeedcordError(SeedcordErrorCode.ConfigEmojiUnresolved, [failures.length, failures.join('\\n')]);\n }\n\n this.logger.utils.summary('Loaded emojis', { emojis: Object.keys(emojiStorage).length });\n }\n\n private async applicationEmojis(failures: string[]): Promise<Map<string, APIEmoji>> {\n try {\n const appId = await this.applicationId();\n // justified: the discord api contract for this route\n const listed = (await this.core.rest.get(Routes.applicationEmojis(appId))) as {\n items: APIEmoji[];\n };\n return byName(listed.items);\n } catch (error) {\n failures.push(` - the application emojis could not be read (${reasonOf(error)})`);\n return new Map();\n }\n }\n\n private async resolveTuple(\n key: string,\n [name, guildId]: readonly [string, string],\n guilds: Map<string, Map<string, APIEmoji>>,\n failures: string[]\n ): Promise<void> {\n let guild = guilds.get(guildId);\n if (!guild) {\n try {\n // justified: the discord api contract for this route\n guild = byName((await this.core.rest.get(Routes.guildEmojis(guildId))) as APIEmoji[]);\n } catch (error) {\n failures.push(\n ` - \"${name}\" for \"${key}\" targets guild ${guildId}, which could not be read (${reasonOf(error)})`\n );\n return;\n }\n guilds.set(guildId, guild);\n }\n\n this.resolve(key, name, guild, failures, `guild ${guildId}`);\n }\n\n private resolve(key: string, name: string, source: Map<string, APIEmoji>, failures: string[], where: string): void {\n const found = source.get(name);\n if (!found?.id) {\n failures.push(` - \"${name}\" for \"${key}\" was not found in ${where}`);\n return;\n }\n\n emojiStorage[key] = new Emoji(name, found.id, found.animated ?? false);\n }\n}\n","import { SeedcordErrorCode } from '@seedcord/errors';\nimport { SeedcordError } from '@seedcord/errors/internal';\n\nimport { InteractionHandler } from '@handlers/interaction/InteractionHandler';\nimport { HttpSlashOptions } from '@inputs/HttpSlashOptions';\nimport { slashRouteOf } from '@src/dispatch/slashRouteOf';\n\nimport type { SlashOptions } from '@inputs/SlashOptions';\nimport type { SlashOptionRegistry } from '@seedcord/core';\nimport type { APIChatInputApplicationCommandInteraction } from 'discord-api-types/v10';\nimport type { Promisable } from 'type-fest';\n\ntype SlashMatchArms<Route extends keyof SlashOptionRegistry, Ret> = {\n [Key in Route]: (options: SlashOptions<Key>) => Promisable<Ret>;\n};\n\n/**\n * Base class for a chat-input (slash) command handler on the HTTP transport.\n *\n * Pass the route from the generated registry as the generic, then read `this.options` for a single\n * command or `this.match` for several. Command authoring stays plain discord.js, `seedcord codegen`\n * reads its `toJSON()` to type these options.\n *\n * @typeParam Route - One or more route keys from {@link SlashOptionRegistry}, e.g. `'ban'` or `'ban' | 'kick'`.\n */\nexport abstract class SlashHandler<\n Route extends keyof SlashOptionRegistry\n> extends InteractionHandler<APIChatInputApplicationCommandInteraction> {\n // phantom, never set at runtime.\n /** @internal */\n declare readonly __slashRoute?: Route;\n\n private resolver?: HttpSlashOptions;\n\n /**\n * The typed options for this command's route. Required options drop the null, choices narrow to their\n * literal union, and only the getters for kinds this command actually uses appear. Rich kinds resolve\n * from the interaction's `resolved` data.\n */\n protected get options(): SlashOptions<Route> {\n this.resolver ??= new HttpSlashOptions(this.event.data);\n // the reader exposes every getter, SlashOptions is the registry-typed view over it.\n return this.resolver as SlashOptions<Route>;\n }\n\n /**\n * Run the arm for whichever command fired. Use this only when the handler is registered for several\n * routes.\n *\n * Provide one arm per registered route, keyed by its route string, and each arm receives that route's\n * own narrowed options. The arms must cover every route in the generic, a missing route or an unknown\n * key is a compile error.\n *\n * @param arms - One handler per registered route, keyed by route string.\n * @returns The result of the arm that ran.\n */\n protected async match<Ret>(arms: SlashMatchArms<Route, Ret>): Promise<Ret> {\n const route = slashRouteOf(this.event.data);\n // justified: SlashMatchArms is keyed by Route literals, the Record cast indexes it with the runtime route string.\n const arm = Object.hasOwn(arms, route)\n ? (arms as Record<string, (options: SlashOptions<Route>) => Promisable<Ret>>)[route]\n : undefined;\n if (!arm) throw new SeedcordError(SeedcordErrorCode.SlashMatchArmMissing, [route]);\n return await arm(this.options);\n }\n}\n","import { ApplicationCommandType } from 'discord-api-types/v10';\n\nimport { InteractionHandler } from '@handlers/interaction/InteractionHandler';\n\nimport type { ContextMenuKind } from '@seedcord/core';\nimport type {\n APIInteractionDataResolvedGuildMember,\n APIMessage,\n APIMessageApplicationCommandInteraction,\n APIUser,\n APIUserApplicationCommandInteraction\n} from 'discord-api-types/v10';\n\ntype InteractionFor<Kind extends ContextMenuKind> = Kind extends ApplicationCommandType.User\n ? APIUserApplicationCommandInteraction\n : APIMessageApplicationCommandInteraction;\n\ntype TargetFor<Kind extends ContextMenuKind> = Kind extends ApplicationCommandType.User ? APIUser : APIMessage;\n\ntype TargetMemberFor<Kind extends ContextMenuKind> = Kind extends ApplicationCommandType.User\n ? APIInteractionDataResolvedGuildMember | null\n : never;\n\n/**\n * Base class for a context-menu command handler on the HTTP transport (right-click a user or a message).\n *\n * Pass the kind from {@link ApplicationCommandType} as the generic. Read the right-clicked entity from\n * `this.target`, an `APIUser` for a user menu and an `APIMessage` for a message menu. Context menus carry\n * no options, so a handler registered for several names reads `this.target` uniformly with no per-name\n * branch.\n *\n * @typeParam Kind - `ApplicationCommandType.User` or `ApplicationCommandType.Message`.\n */\nexport abstract class ContextMenuHandler<Kind extends ContextMenuKind> extends InteractionHandler<\n InteractionFor<Kind>\n> {\n // phantom, never set at runtime.\n /** @internal */\n declare readonly __ctxKind?: Kind;\n\n protected get target(): TargetFor<Kind> {\n const data = this.event.data;\n const target =\n data.type === ApplicationCommandType.User\n ? data.resolved.users[data.target_id]\n : data.resolved.messages[data.target_id];\n // justified: Discord resolves the target it delivered target_id for, the Kind generic picks the arm.\n return target as TargetFor<Kind>;\n }\n\n /**\n * The right-clicked user's guild member, resolved only on user menus fired in a guild. Reading it on a\n * message menu is a compile error.\n */\n protected get targetMember(): TargetMemberFor<Kind> {\n const data = this.event.data;\n const member =\n data.type === ApplicationCommandType.User ? (data.resolved.members?.[data.target_id] ?? null) : null;\n // justified: only the User-kind event includes resolved members, the Message-kind read is unreachable per the type.\n return member as TargetMemberFor<Kind>;\n }\n}\n","import { decodeComponentRoute } from '@seedcord/core/internal';\nimport { SeedcordErrorCode } from '@seedcord/errors';\nimport { SeedcordError } from '@seedcord/errors/internal';\n\nimport { InteractionHandler } from '@handlers/interaction/InteractionHandler';\n\nimport type { SentMessage } from '@reply/ReplySender';\nimport type {\n AnyCustomId,\n DecodedComponentRoute,\n HasComponentDefs,\n MatchArms,\n SingleParams\n} from '@seedcord/core/internal';\nimport type { ReplyResponse } from '@seedcord/types';\nimport type { APIMessageComponentInteraction, APIModalSubmitInteraction } from 'discord-api-types/v10';\nimport type { Promisable } from 'type-fest';\n\n/**\n * Shared base the customId-routed component handlers extend on the HTTP transport.\n *\n * Not a public entry point. Extend {@link ButtonHandler}, {@link SelectMenuHandler}, or {@link ModalHandler}\n * instead. This class defines the customId decode, the route matching, and the source-message verbs\n * `update` and `deferUpdate`.\n *\n * @typeParam Event - The component or modal interaction type this handler processes\n * @typeParam Defs - The customId route definitions registered on the concrete handler\n */\nexport abstract class ComponentHandler<\n Event extends APIMessageComponentInteraction | APIModalSubmitInteraction,\n Defs extends readonly AnyCustomId[]\n>\n extends InteractionHandler<Event>\n implements HasComponentDefs<Defs>\n{\n // phantom, never set at runtime.\n /** @internal */\n declare readonly __componentDefs?: Defs;\n\n /** Rewrite the source message this component interaction came from. */\n protected update(response: ReplyResponse | string): Promise<SentMessage> {\n return this.sender.update(response);\n }\n\n /** Acknowledge the component without changing the source message. */\n protected deferUpdate(): Promise<void> {\n return this.sender.deferUpdate();\n }\n\n private decoded?: DecodedComponentRoute;\n\n private get route(): DecodedComponentRoute {\n this.decoded ??= decodeComponentRoute(this.constructor, this.event.data.custom_id);\n return this.decoded;\n }\n\n /**\n * The decoded params of the single route this handler is registered for.\n *\n * Reading this decodes `this.event.data.custom_id` once (cached after the first read) and throws\n * `StaleCustomId` or `InvalidCustomId` when the wire no longer matches the current shape, which the\n * dispatcher boundary turns into a reply. On a handler registered for several routes this is\n * `never`, so use {@link match} instead.\n */\n protected get params(): SingleParams<Defs> {\n return this.route.params as SingleParams<Defs>;\n }\n\n /**\n * Run the arm for whichever route the component was minted from. Use this only when the handler is\n * registered for several routes. A single-route handler reads `this.params` directly. On a multi-route\n * handler `this.params` is `never`, so match is the only way to read the decoded params.\n *\n * Provide one arm per registered route, keyed by its prefix, and each arm receives that route's own\n * decoded params. The arms cover every registered route prefix, checked at compile time, and a prefix\n * unmatched at runtime throws `CustomIdMatchArmMissing`. Decoding runs before any arm, so a stale or\n * corrupt wire throws before an arm body executes.\n *\n * @param arms - One callback per registered route, keyed by prefix.\n * @returns The result of the arm that ran.\n *\n * @example\n * ```ts\n * \\@ButtonRoute(Approve, Reject)\n * class ReviewButtons extends ButtonHandler<[typeof Approve, typeof Reject]> {\n * async execute() {\n * await this.match({\n * approve: ({ userId }) => this.reply(`approved <@${userId}>`),\n * reject: ({ userId }) => this.reply(`rejected <@${userId}>`)\n * });\n * }\n * }\n * ```\n */\n protected async match<Ret>(arms: MatchArms<Defs, Ret>): Promise<Ret> {\n const { prefix, params } = this.route;\n // justified: MatchArms is keyed by prefix literals, the Record cast indexes it with the runtime prefix.\n const arm = Object.hasOwn(arms, prefix)\n ? (arms as Record<string, (params: Record<string, unknown>) => Promisable<Ret>>)[prefix]\n : undefined;\n if (!arm) throw new SeedcordError(SeedcordErrorCode.CustomIdMatchArmMissing, [prefix]);\n return await arm(params);\n }\n}\n","import { ComponentHandler } from './ComponentHandler';\n\nimport type { AnyCustomId } from '@seedcord/core/internal';\nimport type { APIMessageComponentButtonInteraction } from 'discord-api-types/v10';\n\n/**\n * Base class for a button interaction handler on the HTTP transport.\n *\n * Register the customId definitions this handler decodes with `@ButtonRoute`, list the same ones in the\n * generic, then read `this.params` for a single route or `this.match` for several. Reply through the\n * handler members, or rewrite the source message with `this.update`. Passing different definitions to the\n * decorator and the generic is a compile error.\n *\n * @typeParam Defs - The customId definitions this handler decodes, e.g. `[typeof ApproveId]`.\n */\nexport abstract class ButtonHandler<Defs extends readonly AnyCustomId[]> extends ComponentHandler<\n APIMessageComponentButtonInteraction,\n Defs\n> {\n // phantom, never set at runtime.\n /** @internal */\n declare readonly __component?: 'button';\n}\n","import { ComponentHandler } from './ComponentHandler';\n\nimport type { SelectMenuKind } from '@seedcord/core';\nimport type { AnyCustomId } from '@seedcord/core/internal';\nimport type {\n APIMessageChannelSelectInteractionData,\n APIMessageComponentSelectMenuInteraction,\n APIMessageMentionableSelectInteractionData,\n APIMessageRoleSelectInteractionData,\n APIMessageStringSelectInteractionData,\n APIMessageUserSelectInteractionData\n} from 'discord-api-types/v10';\n\ntype SelectMenuInteractionFor<Kind extends SelectMenuKind> = APIMessageComponentSelectMenuInteraction & {\n data: Kind extends SelectMenuKind.String\n ? APIMessageStringSelectInteractionData\n : Kind extends SelectMenuKind.User\n ? APIMessageUserSelectInteractionData\n : Kind extends SelectMenuKind.Role\n ? APIMessageRoleSelectInteractionData\n : Kind extends SelectMenuKind.Channel\n ? APIMessageChannelSelectInteractionData\n : Kind extends SelectMenuKind.Mentionable\n ? APIMessageMentionableSelectInteractionData\n : never;\n};\n\n/**\n * Base class for a select menu handler on the HTTP transport.\n *\n * Pass the select kind first and the customId definitions second, the same order as `@SelectMenuRoute`,\n * so `this.event.data` and its `values`/`resolved` are narrowed to that kind. Read `this.params` for a\n * single route or `this.match` for several, and reply through the handler members or rewrite the source\n * message with `this.update`.\n *\n * @typeParam Kind - The select kind from {@link SelectMenuKind}, e.g. `SelectMenuKind.User`.\n * @typeParam Defs - The customId definitions this handler decodes, e.g. `[typeof AssignId]`.\n */\nexport abstract class SelectMenuHandler<\n Kind extends SelectMenuKind,\n Defs extends readonly AnyCustomId[]\n> extends ComponentHandler<SelectMenuInteractionFor<Kind>, Defs> {\n // phantom, never set at runtime.\n /** @internal */\n declare readonly __component?: Kind;\n}\n","import { SeedcordErrorCode } from '@seedcord/errors';\nimport { SeedcordError } from '@seedcord/errors/internal';\n\nimport { ComponentHandler } from './ComponentHandler';\n\nimport type { SentMessage } from '@reply/ReplySender';\nimport type { AnyCustomId } from '@seedcord/core/internal';\nimport type { ReplyResponse } from '@seedcord/types';\nimport type { APIModalSubmitInteraction } from 'discord-api-types/v10';\n\n/**\n * Base class for a modal submit handler on the HTTP transport.\n *\n * Register the customId definitions this handler decodes with `@ModalRoute` and list the same ones in the\n * generic. Read the submitted inputs off `this.event.data.components`. Reply through the handler members.\n * Discord forbids opening a modal in response to a modal, so `showModal` fails compilation on this kind.\n *\n * @typeParam Defs - The customId definitions this handler decodes, e.g. `[typeof ConfigId]`.\n */\nexport abstract class ModalHandler<Defs extends readonly AnyCustomId[]> extends ComponentHandler<\n APIModalSubmitInteraction,\n Defs\n> {\n // phantom, never set at runtime.\n /** @internal */\n declare readonly __component?: 'modal';\n\n /** Rewrite the message this modal was opened from. Throws when a command opened the modal. */\n protected override update(response: ReplyResponse | string): Promise<SentMessage> {\n this.ensureSourceMessage('update');\n return super.update(response);\n }\n\n /** Acknowledge the submit without changing the source message. Throws when a command opened the modal. */\n protected override deferUpdate(): Promise<void> {\n this.ensureSourceMessage('deferUpdate');\n return super.deferUpdate();\n }\n\n // discord omits the message when a command opened the modal, so update and deferUpdate have no target\n private ensureSourceMessage(method: string): void {\n if (this.event.message) return;\n throw new SeedcordError(SeedcordErrorCode.ReplyUpdateWithoutSource, [method, this.routeId]);\n }\n}\n","import { Subscriber as CoreSubscriber, WebhookLog as CoreWebhookLog } from '@seedcord/core';\n\nimport type { Core } from '@interfaces/Core';\nimport type { SubscriptionKey } from '@seedcord/core';\n\n/**\n * Base class for an HTTP subscriber, binding `this.core` to the HTTP {@link Core}.\n *\n * @typeParam KeyOfSubscribers - The subscription key this handler receives\n */\nexport abstract class Subscriber<KeyOfSubscribers extends SubscriptionKey> extends CoreSubscriber<\n KeyOfSubscribers,\n Core\n> {}\n\n/**\n * Base class for an HTTP subscriber that delivers its event to a Discord webhook, binding\n * `this.core` to the HTTP {@link Core}.\n *\n * @typeParam KeyOfSubscribers - The subscription key this reporter receives\n */\nexport abstract class WebhookLog<KeyOfSubscribers extends SubscriptionKey> extends CoreWebhookLog<\n KeyOfSubscribers,\n Core\n> {}\n","import { PaginatorBase } from '@seedcord/core';\n\nimport { ButtonHandler } from '@handlers/interaction/components';\n\nimport type { PageContext } from './PageContext';\nimport type { RepliableHandler } from '@handlers/RepliableHandler';\nimport type { Core } from '@interfaces/Core';\nimport type { SentMessage } from '@reply/ReplySender';\nimport type { PaginatorConfig } from '@seedcord/core';\nimport type { PageCursor } from '@seedcord/core/internal';\nimport type { ReplyResponse } from '@seedcord/types';\nimport type { Repliables } from '@src/handlers/interactionTypes';\nimport type { APIMessageComponentButtonInteraction, APIUser } from 'discord-api-types/v10';\n\n// `& { execute }` concretizes the abstract execute so the empty `extends Bans.Handler {}` stays concrete\n// (no TS2515) and a concrete Nav assigns with no cast.\ntype PaginatorHandlerCtor<Prefix extends string> = new (\n event: APIMessageComponentButtonInteraction,\n core: Core\n) => ButtonHandler<[PageCursor<Prefix>]> & { execute(): Promise<void> };\n\nfunction contextOf(interaction: Repliables, core: Core): PageContext {\n // discord sends member.user in a guild and the top-level user in a dm\n const resolved = interaction.member?.user ?? interaction.user;\n return {\n interaction,\n // justified: every repliable interaction Discord delivers carries a user, the wrapper types don't say so\n user: resolved as APIUser,\n guildId: interaction.guild_id ?? null,\n core\n };\n}\n\n/**\n * A restart-proof paginator. Each nav button's customId encodes its full target page, so clicks are\n * idempotent and survive a restart. A persistent `@ButtonRoute` on `Handler` dispatches the clicks.\n *\n * @typeParam Item - The item type, inferred from the source.\n * @typeParam Prefix - The route prefix, inferred from `config.prefix`.\n *\n * @example\n * ```ts\n * export const Bans = new Paginator({\n * prefix: 'bans',\n * source: new ArraySource((ctx) => loadBans(ctx.guildId), { perPage: 10 }),\n * renderItem: (ban) => ban.user.username\n * });\n *\n * \\@ButtonRoute(Bans.cursor)\n * export class BansNav extends Bans.Handler {}\n * ```\n */\nexport class Paginator<Item, const Prefix extends string> extends PaginatorBase<Item, Prefix, PageContext> {\n /** The nav handler base. Extend it with an empty body and decorate it, `@ButtonRoute(p.cursor)`. */\n public readonly Handler: PaginatorHandlerCtor<Prefix>;\n\n constructor(config: PaginatorConfig<Item, Prefix, PageContext>) {\n super(config);\n\n // an arrow captures the paginator lexically so Nav.execute can reach it without aliasing `this`.\n const loadPage = (ctx: PageContext, n: number): Promise<ReplyResponse> => this.page(ctx, n);\n this.Handler = class Nav extends ButtonHandler<[PageCursor<Prefix>]> {\n async execute(): Promise<void> {\n await this.deferUpdate();\n const response = await loadPage(contextOf(this.event, this.core), this.params.page);\n // deferUpdate seeds the sender deferred-update, so update PATCHes @original\n await this.update(response);\n }\n };\n }\n\n /**\n * Render page 0 and send it through the handler's sender, which picks reply, edit, or followUp from its\n * ack state.\n *\n * @param handler - The handler starting the paginator, normally `this`.\n */\n async start(handler: RepliableHandler<Repliables>): Promise<SentMessage> {\n const interaction = handler.getEvent();\n const response = await this.page(contextOf(interaction, handler.core), 0);\n return handler.getSender().send(response, { ephemeral: this.config.ephemeral ?? false });\n }\n}\n","import { ArraySource as BaseArraySource, CursorSource as BaseCursorSource } from '@seedcord/core';\n\nimport type { PageContext } from './PageContext';\n\n/**\n * A source for a bounded list you can load whole. It loads the full list on every click, then slices the\n * page, so the real total is known (a real last button, \"Page X of Y\"). Cache inside your loader if the\n * load is expensive.\n *\n * @typeParam Item - The item type, inferred from the loader's return.\n */\nexport class ArraySource<Item> extends BaseArraySource<Item, PageContext> {}\n\n/**\n * A source for a large or unknown-length set you fetch one page at a time (SQL LIMIT/OFFSET, a paged API).\n * The fetcher receives the page index and the page size and reports whether a next page exists. A cursor\n * source has no cheap total, so `totalPages` is undefined, the last button is omitted, and the indicator\n * reads \"Page X\".\n *\n * @typeParam Item - The item type, inferred from the fetcher's slice.\n */\nexport class CursorSource<Item> extends BaseCursorSource<Item, PageContext> {}\n","import { GatedMetadataKey } from '@seedcord/core/internal';\n\nimport type { AnyHandlerCtor, FitAll } from './matching';\nimport type { Gate, GateContextBase } from '@seedcord/core';\nimport type { NonEmptyTuple } from 'type-fest';\n\n/**\n * Attaches gates to an HTTP interaction handler. The gates run before `execute`, and a gate refusing stops\n * the handler with the reply or drop the gate threw. Multiple gates are ANDed, so each must pass. A gate\n * that requires a context the handler does not provide (a button gate on a slash handler, a gate on an\n * autocomplete handler, or a `RequirePermissions([...], { in: 'guild' })` gate the http transport cannot\n * satisfy) is a compile error at this line, and the error names the gate and the handler kind. Place it\n * above the route decorator.\n *\n * Combine gates with {@link and} or {@link or} to build a single gate from multiple arms.\n *\n * @example\n * ```ts\n * import { PermissionFlagsBits } from 'discord-api-types/v10';\n *\n * \\@Gated(GuildOnly(), RequirePermissions([PermissionFlagsBits.ManageMessages]))\n * \\@SlashRoute('purge')\n * class Purge extends SlashHandler<'purge'> {\n * async execute() {\n * // both gates passed, so this runs in a guild with a caller who can moderate this channel\n * }\n * }\n * ```\n *\n * @typeParam Gates - The non-empty tuple of gates to run, in order, against the handler's context.\n * @typeParam TCtor - The decorated handler's constructor, checked against every gate's required context.\n * @param gates - One or more gates to attach, each ANDed so the handler runs only when all pass.\n * @param ctor - The handler class being decorated, rejected at compile time when a gate requires a context it lacks.\n *\n * @see {@link defineGate}\n * @see {@link defineEffectGate}\n * @decorator\n */\nexport function Gated<const Gates extends NonEmptyTuple<Gate<GateContextBase>>>(...gates: Gates) {\n // mismatch resolves to the error tuple, so the class fails to assign and TS names the gate\n return function <TCtor extends AnyHandlerCtor>(\n ctor: FitAll<TCtor, Gates> extends Gates ? TCtor : FitAll<TCtor, Gates>\n ): void {\n const existing = (Reflect.getMetadata(GatedMetadataKey, ctor) as readonly Gate[] | undefined) ?? [];\n Reflect.defineMetadata(GatedMetadataKey, [...existing, ...gates], ctor);\n };\n}\n","/** Package version */\nexport const version = process.env.PACKAGE_VERSION ?? '0.0.0';\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsCA,SAAS,oBAAoB,UAA8E;CACvG,MAAM,EAAE,aAAa,GAAG,SAAS;CACjC,OAAO;EAAE,GAAG;EAAM,GAAI,gBAAgB,UAAa,EAAE,cAAc,YAAY;CAAG;AACtF;AAGA,SAAS,gBAAgB,OAA0D;CAC/E,IAAI,CAAC,OAAO,MAAM,SAAS,KAAK,eAAe,KAAK,KAAK,GAAG,OAAO;CACnE,OAAO,MAAM,KAAK,MAAM,WAAW;EAC/B,IAAI;EACJ,UAAU,KAAK;EACf,GAAI,KAAK,eAAe,EAAE,aAAa,KAAK,YAAY;EACxD,GAAI,KAAK,SAAS,EAAE,OAAO,KAAK,MAAM;CAC1C,EAAE;AACN;AAEA,SAAS,aAAa,OAAwB,OAA4B;CACtE,MAAM,cAAc,gBAAgB,MAAM,KAAK;CAC/C,OAAO;EACH;EACA,YAAY,MAAM;EAClB,GAAI,MAAM,mBAAmB,EAAE,kBAAkB,oBAAoB,MAAM,eAAe,EAAE;EAC5F,GAAI,eAAe,EAAE,YAAY;CACrC;AACJ;;;;;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