@seedcord/core 0.1.0-next.2 → 0.1.0-next.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{CustomId-Ddwg48VY.d.mts → CustomId--QizzBOn.d.mts} +12 -6
- package/dist/{CustomId-DQ6ZH4s-.cjs → CustomId-DV7daU7r.cjs} +2 -2
- package/dist/CustomId-DV7daU7r.cjs.map +1 -0
- package/dist/{CustomId-Bq6WagiA.mjs → CustomId-epJayEGO.mjs} +2 -2
- package/dist/CustomId-epJayEGO.mjs.map +1 -0
- package/dist/index.cjs +31 -9
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.mts +33 -11
- package/dist/index.mjs +31 -10
- package/dist/index.mjs.map +1 -1
- package/dist/internal.index.cjs +13 -2
- package/dist/internal.index.cjs.map +1 -1
- package/dist/internal.index.d.mts +3 -2
- package/dist/internal.index.mjs +13 -3
- package/dist/internal.index.mjs.map +1 -1
- package/package.json +6 -6
- package/dist/CustomId-Bq6WagiA.mjs.map +0 -1
- package/dist/CustomId-DQ6ZH4s-.cjs.map +0 -1
|
@@ -227,15 +227,21 @@ interface GateContextBase {
|
|
|
227
227
|
/** The channel id, or null when the source carries none. */
|
|
228
228
|
readonly channelId: string | null;
|
|
229
229
|
/**
|
|
230
|
-
* The
|
|
231
|
-
*
|
|
230
|
+
* The member's role ids without the everyone role, the shape a raw interaction payload
|
|
231
|
+
* contains. Empty outside a guild or when the source contains none.
|
|
232
232
|
*/
|
|
233
233
|
readonly memberRoleIds: readonly string[];
|
|
234
234
|
/**
|
|
235
|
-
* The
|
|
236
|
-
* channel-scoped permissions the payload
|
|
235
|
+
* The member's permission bits, or null outside a guild. On an interaction these are the
|
|
236
|
+
* channel-scoped permissions the payload contains, on a gateway event the member's guild-level ones.
|
|
237
237
|
*/
|
|
238
238
|
readonly memberPermissions: bigint | null;
|
|
239
|
+
/**
|
|
240
|
+
* The dispatched handler as `kind:route` (`slash:daily`, `button:confirm`), or null off a route (a
|
|
241
|
+
* plain event handler, or a gate run outside a handler). `runHandlerGates` populates it from the handler's
|
|
242
|
+
* metadata. `Cooldown` uses it so its window is stable across restarts and isolates.
|
|
243
|
+
*/
|
|
244
|
+
readonly routeId: string | null;
|
|
239
245
|
}
|
|
240
246
|
declare const GateBrand: unique symbol;
|
|
241
247
|
/**
|
|
@@ -391,7 +397,7 @@ type RequiredOf<TGate> = TGate extends Gate<infer Ctx> ? Ctx : never;
|
|
|
391
397
|
*
|
|
392
398
|
* @example
|
|
393
399
|
* ```ts
|
|
394
|
-
* import { Notice, BuilderComponent, type RenderContext, type ReplyResponse } from 'seedcord';
|
|
400
|
+
* import { Notice, BuilderComponent, type RenderContext, type ReplyResponse } from '@seedcord/gateway';
|
|
395
401
|
* import { TextDisplayBuilder } from '@discordjs/builders';
|
|
396
402
|
*
|
|
397
403
|
* // reading `.component` applies the configured bot color to the container accent
|
|
@@ -651,4 +657,4 @@ type DecodedRoute<Defs extends readonly AnyCustomId[]> = { [Index in keyof Defs]
|
|
|
651
657
|
declare function decodeFor<Defs extends readonly AnyCustomId[]>(defs: Defs, wire: string): DecodedRoute<Defs>;
|
|
652
658
|
//#endregion
|
|
653
659
|
export { BuilderComponent as C, RowType as E, RegisterCommand as S, BuilderType as T, RequiredOf as _, CustomIdField as a, CoreBase as b, pickNotice as c, JoinNames as d, TwoOrMore as f, GateContextBase as g, Gate as h, prefixOf as i, GateFitsWith as l, EffectGate as m, CustomId as n, DecodedParams as o, Notice as p, decodeFor as r, GateNoticeOptions as s, AnyCustomId as t, IntersectRequired as u, defineEffectGate as v, RowComponent as w, CommandMeta as x, defineGate as y };
|
|
654
|
-
//# sourceMappingURL=CustomId
|
|
660
|
+
//# sourceMappingURL=CustomId--QizzBOn.d.mts.map
|
|
@@ -51,7 +51,7 @@ const SubscribeMetadataKey = Symbol("seedcord:subscribe:metadata");
|
|
|
51
51
|
*
|
|
52
52
|
* @example
|
|
53
53
|
* ```ts
|
|
54
|
-
* import { Notice, BuilderComponent, type RenderContext, type ReplyResponse } from 'seedcord';
|
|
54
|
+
* import { Notice, BuilderComponent, type RenderContext, type ReplyResponse } from '@seedcord/gateway';
|
|
55
55
|
* import { TextDisplayBuilder } from '@discordjs/builders';
|
|
56
56
|
*
|
|
57
57
|
* // reading `.component` applies the configured bot color to the container accent
|
|
@@ -990,4 +990,4 @@ Object.defineProperty(exports, 'setBotColor', {
|
|
|
990
990
|
return setBotColor;
|
|
991
991
|
}
|
|
992
992
|
});
|
|
993
|
-
//# sourceMappingURL=CustomId-
|
|
993
|
+
//# sourceMappingURL=CustomId-DV7daU7r.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"CustomId-DV7daU7r.cjs","names":["SlashCommandBuilder","ContextMenuCommandBuilder","SlashCommandSubcommandBuilder","SlashCommandSubcommandGroupBuilder","EmbedBuilder","ModalBuilder","LabelBuilder","TextInputBuilder","FileUploadBuilder","CheckboxBuilder","CheckboxGroupBuilder","CheckboxGroupOptionBuilder","RadioGroupBuilder","RadioGroupOptionBuilder","ButtonBuilder","StringSelectMenuBuilder","StringSelectMenuOptionBuilder","UserSelectMenuBuilder","ChannelSelectMenuBuilder","MentionableSelectMenuBuilder","RoleSelectMenuBuilder","ContainerBuilder","TextDisplayBuilder","FileBuilder","MediaGalleryBuilder","SectionBuilder","SeparatorBuilder","ActionRowBuilder","SeedcordTypeError","SeedcordErrorCode","SeedcordRangeError","SlashCommandBuilder","ContextMenuCommandBuilder","InteractionContextType","EmbedBuilder","ContainerBuilder","TextDisplayBuilder","SeedcordRangeError","SeedcordErrorCode","SeedcordError","SeedcordErrorCode","SeedcordRangeError"],"sources":["../src/metadataKeys.ts","../src/stops/Notice.ts","../src/components/botColorHolder.ts","../src/components/builderTypes.ts","../src/components/colors.ts","../src/components/resolveColor.ts","../src/components/Component.ts","../src/stops/NoticeCard.ts","../src/notices/index.ts","../src/gates/effects.ts","../src/gates/catalog/options.ts","../src/customId/Errors.ts","../src/customId/codec.ts","../src/customId/CustomId.ts"],"sourcesContent":["export enum InteractionRoutes {\n Slash = 'slash',\n Button = 'button',\n Modal = 'modal',\n StringMenu = 'stringMenu',\n UserMenu = 'userMenu',\n RoleMenu = 'roleMenu',\n ChannelMenu = 'channelMenu',\n MentionableMenu = 'mentionableMenu',\n MessageContextMenu = 'messageContextMenu',\n UserContextMenu = 'userContextMenu',\n Autocomplete = 'autocomplete'\n}\n\nexport const InteractionMetadataKey = Symbol('seedcord:interaction:metadata');\n\nexport const InteractionRouteKeys: Record<InteractionRoutes, symbol> = {\n [InteractionRoutes.Slash]: Symbol('seedcord:interaction:slash'),\n [InteractionRoutes.Button]: Symbol('seedcord:interaction:button'),\n [InteractionRoutes.Modal]: Symbol('seedcord:interaction:modal'),\n [InteractionRoutes.StringMenu]: Symbol('seedcord:interaction:stringMenu'),\n [InteractionRoutes.UserMenu]: Symbol('seedcord:interaction:userMenu'),\n [InteractionRoutes.RoleMenu]: Symbol('seedcord:interaction:roleMenu'),\n [InteractionRoutes.ChannelMenu]: Symbol('seedcord:interaction:channelMenu'),\n [InteractionRoutes.MentionableMenu]: Symbol('seedcord:interaction:mentionableMenu'),\n [InteractionRoutes.MessageContextMenu]: Symbol('seedcord:interaction:messageContextMenu'),\n [InteractionRoutes.UserContextMenu]: Symbol('seedcord:interaction:userContextMenu'),\n [InteractionRoutes.Autocomplete]: Symbol('seedcord:interaction:autocomplete')\n};\n\nexport const MiddlewareMetadataKey = Symbol('seedcord:middleware:metadata');\n\nexport const EventMetadataKey = Symbol('seedcord:event:metadata');\n\nexport const CommandMetadataKey = Symbol('seedcord:command:metadata');\n\nexport const GatedMetadataKey = Symbol('seedcord:gated:metadata');\n\nexport const SubscribeMetadataKey = Symbol('seedcord:subscribe:metadata');\n","import type { RenderContext, ReplyResponse } from '@seedcord/types';\n\n/**\n * Base class for a user-facing refusal or a reported fault.\n *\n * Throw a `Notice` to stop a handler and reply to the user. The framework catches it at the controller\n * boundary and renders {@link Notice.render}, which always decides what the user sees. With `report`\n * false that render is all that happens. With `report` true the framework also logs the fault and\n * publishes it to the `handledException` bus. A raw, non-Notice throw shows the generic message.\n *\n * @example\n * ```ts\n * import { Notice, BuilderComponent, type RenderContext, type ReplyResponse } from '@seedcord/gateway';\n * import { TextDisplayBuilder } from '@discordjs/builders';\n *\n * // reading `.component` applies the configured bot color to the container accent\n * class TooPoorCard extends BuilderComponent<'container'> {\n * constructor(balance: number) {\n * super('container');\n * this.instance.addTextDisplayComponents(\n * new TextDisplayBuilder().setContent(`### Insufficient balance\\nYou need more than ${balance} coins.`)\n * );\n * }\n * }\n *\n * class TooPoor extends Notice {\n * constructor(private readonly balance: number) {\n * super(`balance ${balance} is below the cost`);\n * }\n *\n * render(_ctx: RenderContext): ReplyResponse {\n * return { components: [new TooPoorCard(this.balance).component] };\n * }\n * }\n *\n * // in a handler, throwing stops the handler and replies with render(ctx)\n * if (wallet.balance < cost) throw new TooPoor(wallet.balance);\n * ```\n */\nexport abstract class Notice extends Error {\n /**\n * Whether this denial is a reported fault. True also logs it and publishes it to the `handledException`\n * bus. The user always sees {@link Notice.render} either way.\n *\n * @defaultValue `false`\n */\n public report = false;\n\n /**\n * Whether the reply is ephemeral, so only the invoking user sees it. Set it false for a refusal the\n * whole channel should see.\n *\n * @defaultValue `true`\n */\n public ephemeral = true;\n\n /**\n * A short one-line reason. When every arm of an `or` gate refuses and each refusal sets this, `or`\n * lists them instead of showing a neutral message.\n */\n public summary?: string;\n\n protected constructor(message: string, options?: ErrorOptions) {\n super(message, options);\n\n // Error sets name to 'Error', so stamp the concrete subclass name for logs and the fault report\n this.name = new.target.name;\n Error.captureStackTrace(this, this.constructor);\n }\n\n /**\n * Builds what the user sees. Called fresh each time the denial is shown, so the builders are new\n * and the bot color resolves at render time rather than at construction time.\n */\n public abstract render(ctx: RenderContext): ReplyResponse;\n}\n","import type { BotColor } from '@seedcord/types';\n\n// must be 'Default' so the container guard in applyBotColor leaves the accent unset\nconst DEFAULT_COLOR: BotColor = 'Default';\n\nlet current: BotColor = DEFAULT_COLOR;\n\nexport function setBotColor(color: BotColor | undefined): void {\n current = color ?? DEFAULT_COLOR;\n}\n\nexport function getBotColor(): BotColor {\n return current;\n}\n","import {\n ActionRowBuilder,\n ButtonBuilder,\n ChannelSelectMenuBuilder,\n CheckboxBuilder,\n CheckboxGroupBuilder,\n CheckboxGroupOptionBuilder,\n ContainerBuilder,\n ContextMenuCommandBuilder,\n EmbedBuilder,\n FileBuilder,\n FileUploadBuilder,\n LabelBuilder,\n MediaGalleryBuilder,\n MentionableSelectMenuBuilder,\n ModalBuilder,\n RadioGroupBuilder,\n RadioGroupOptionBuilder,\n RoleSelectMenuBuilder,\n SectionBuilder,\n SeparatorBuilder,\n SlashCommandBuilder,\n SlashCommandSubcommandBuilder,\n SlashCommandSubcommandGroupBuilder,\n StringSelectMenuBuilder,\n StringSelectMenuOptionBuilder,\n TextDisplayBuilder,\n TextInputBuilder,\n UserSelectMenuBuilder\n} from '@discordjs/builders';\n\n/**\n * Available Discord.js builder classes for use with BuilderComponent for commands, embeds, modals, etc.\n *\n * @internal\n */\nexport const BuilderTypes = {\n // Command Components\n command: SlashCommandBuilder,\n context_menu: ContextMenuCommandBuilder,\n subcommand: SlashCommandSubcommandBuilder,\n group: SlashCommandSubcommandGroupBuilder,\n\n // Embed Components\n embed: EmbedBuilder,\n\n // Modal Components\n modal: ModalBuilder,\n label: LabelBuilder,\n text_input: TextInputBuilder,\n file_upload: FileUploadBuilder,\n checkbox: CheckboxBuilder,\n checkbox_group: CheckboxGroupBuilder,\n checkbox_group_option: CheckboxGroupOptionBuilder,\n radio_group: RadioGroupBuilder,\n radio_group_option: RadioGroupOptionBuilder,\n\n // Action Row Components\n button: ButtonBuilder,\n menu_string: StringSelectMenuBuilder,\n menu_option_string: StringSelectMenuOptionBuilder,\n menu_user: UserSelectMenuBuilder,\n menu_channel: ChannelSelectMenuBuilder,\n menu_mentionable: MentionableSelectMenuBuilder,\n menu_role: RoleSelectMenuBuilder,\n\n // ComponentsV2\n container: ContainerBuilder,\n text_display: TextDisplayBuilder,\n file: FileBuilder,\n media: MediaGalleryBuilder,\n section: SectionBuilder,\n separator: SeparatorBuilder\n};\n\n/**\n * Available Discord.js action row classes for use with RowComponent for Select Menus and Buttons\n *\n * @internal\n */\nexport const RowTypes: {\n button: typeof ActionRowBuilder<ButtonBuilder>;\n menu_string: typeof ActionRowBuilder<StringSelectMenuBuilder>;\n menu_user: typeof ActionRowBuilder<UserSelectMenuBuilder>;\n menu_channel: typeof ActionRowBuilder<ChannelSelectMenuBuilder>;\n menu_mentionable: typeof ActionRowBuilder<MentionableSelectMenuBuilder>;\n menu_role: typeof ActionRowBuilder<RoleSelectMenuBuilder>;\n} = {\n button: ActionRowBuilder<ButtonBuilder>,\n menu_string: ActionRowBuilder<StringSelectMenuBuilder>,\n menu_user: ActionRowBuilder<UserSelectMenuBuilder>,\n menu_channel: ActionRowBuilder<ChannelSelectMenuBuilder>,\n menu_mentionable: ActionRowBuilder<MentionableSelectMenuBuilder>,\n menu_role: ActionRowBuilder<RoleSelectMenuBuilder>\n};\n\n/**\n * Available Discord.js builder types for use with BuilderComponent\n */\nexport type BuilderType = keyof typeof BuilderTypes;\n\n/**\n * @internal\n */\nexport type InstantiatedBuilder<BuilderKey extends BuilderType> = InstanceType<(typeof BuilderTypes)[BuilderKey]>;\n\n/**\n * Available Discord.js action row types for use with RowComponent\n */\nexport type RowType = keyof typeof RowTypes;\n\n/**\n * @internal\n */\nexport type InstantiatedActionRow<RowKey extends RowType> = InstanceType<(typeof RowTypes)[RowKey]>;\n","import type { ColorName, TypedOmit } from '@seedcord/types';\n\n// Ported verbatim from discord.js (Apache-2.0), src/util/Colors.js.\nexport const Colors: TypedOmit<Record<ColorName, number>, 'Random'> = {\n Aqua: 0x1a_bc_9c,\n Blue: 0x34_98_db,\n Blurple: 0x58_65_f2,\n DarkAqua: 0x11_80_6a,\n DarkBlue: 0x20_66_94,\n DarkButNotBlack: 0x2c_2f_33,\n DarkerGrey: 0x7f_8c_8d,\n DarkGold: 0xc2_7c_0e,\n DarkGreen: 0x1f_8b_4c,\n DarkGrey: 0x97_9c_9f,\n DarkNavy: 0x2c_3e_50,\n DarkOrange: 0xa8_43_00,\n DarkPurple: 0x71_36_8a,\n DarkRed: 0x99_2d_22,\n DarkVividPink: 0xad_14_57,\n Default: 0x00_00_00,\n Fuchsia: 0xeb_45_9e,\n Gold: 0xf1_c4_0f,\n Green: 0x57_f2_87,\n Grey: 0x95_a5_a6,\n Greyple: 0x99_aa_b5,\n LightGrey: 0xbc_c0_c0,\n LuminousVividPink: 0xe9_1e_63,\n Navy: 0x34_49_5e,\n NotQuiteBlack: 0x23_27_2a,\n Orange: 0xe6_7e_22,\n Purple: 0x9b_59_b6,\n Red: 0xed_42_45,\n White: 0xff_ff_ff,\n Yellow: 0xfe_e7_5c\n} as const;\n","import { SeedcordErrorCode } from '@seedcord/errors';\nimport { SeedcordRangeError, SeedcordTypeError } from '@seedcord/errors/internal';\n\nimport { Colors } from './colors';\n\nimport type { BotColor } from '@seedcord/types';\n\nconst MAX_COLOR = 0xff_ff_ff;\nconst RED_SHIFT = 16;\nconst GREEN_SHIFT = 8;\n\nconst palette: Record<string, number | undefined> = Colors;\n\n/**\n * Resolves a {@link BotColor} to the integer Discord expects.\n *\n * Ported from discord.js (Apache-2.0), `resolveColor` in src/util/Util.js.\n */\nexport function resolveColor(color: BotColor): number {\n let resolved: number | undefined;\n\n if (typeof color === 'string') {\n if (color === 'Random') return Math.floor(Math.random() * (MAX_COLOR + 1));\n if (color === 'Default') return 0;\n if (/^#?[\\da-f]{6}$/i.test(color)) return Number.parseInt(color.replace('#', ''), 16);\n resolved = palette[color];\n } else if (typeof color === 'number') {\n resolved = color;\n } else {\n resolved = (color[0] << RED_SHIFT) + (color[1] << GREEN_SHIFT) + color[2];\n }\n\n if (resolved === undefined || !Number.isSafeInteger(resolved)) {\n throw new SeedcordTypeError(SeedcordErrorCode.ColorUnresolvable, [JSON.stringify(color)]);\n }\n if (resolved < 0 || resolved > MAX_COLOR) {\n throw new SeedcordRangeError(SeedcordErrorCode.ColorOutOfRange);\n }\n\n return resolved;\n}\n","import { ContainerBuilder, ContextMenuCommandBuilder, EmbedBuilder, SlashCommandBuilder } from '@discordjs/builders';\nimport { InteractionContextType } from 'discord-api-types/v10';\n\nimport { getBotColor } from './botColorHolder';\nimport { BuilderTypes, RowTypes } from './builderTypes';\nimport { resolveColor } from './resolveColor';\n\nimport type { BuilderType, InstantiatedActionRow, InstantiatedBuilder, RowType } from './builderTypes';\n\n/**\n * Base class for Discord component wrappers.\n *\n * @typeParam TComponent - The Discord.js component type being wrapped\n *\n * @internal\n */\nabstract class BaseComponent<TComponent> {\n private readonly _component: TComponent;\n\n protected constructor(ComponentClass: new () => TComponent) {\n this._component = new ComponentClass();\n }\n\n /**\n * Returns the live builder, ready to send in a Discord message or nest in another component.\n *\n * Configure it through `this.instance`. Reading this can apply the bot color (see\n * {@link BuilderComponent}), so it has a side effect.\n * @example new SomeComponent().component\n */\n public abstract get component(): InstantiatedBuilder<BuilderType> | InstantiatedActionRow<RowType>;\n\n /**\n * The wrapped builder, for calling Discord.js methods like setTitle() and setDescription() inside a subclass.\n *\n * @example this.instance.setTitle('My Modal')\n */\n protected get instance(): TComponent {\n return this._component;\n }\n}\n\n/**\n * Base class for Discord.js builder components\n *\n * Wraps Discord.js builders (SlashCommandBuilder, EmbedBuilder, etc.) with\n * Seedcord-specific defaults and helper methods.\n *\n * @typeParam BuilderKey - The type of Discord.js builder being wrapped\n */\nexport abstract class BuilderComponent<BuilderKey extends BuilderType> extends BaseComponent<\n InstantiatedBuilder<BuilderKey>\n> {\n private colorApplied = false;\n\n protected constructor(public readonly type: BuilderKey) {\n const ComponentClass = BuilderTypes[type] as unknown;\n super(ComponentClass as new () => InstantiatedBuilder<BuilderKey>);\n\n if (this.instance instanceof SlashCommandBuilder || this.instance instanceof ContextMenuCommandBuilder) {\n this.instance.setContexts(InteractionContextType.Guild);\n }\n }\n\n get component(): InstantiatedBuilder<BuilderKey> {\n this.applyBotColor();\n return this.instance;\n }\n\n // Resolving in the constructor would capture the default for a component built before setBotColor()\n // ran. The unset check keeps a color the subclass set for itself.\n private applyBotColor(): void {\n if (this.colorApplied) return;\n this.colorApplied = true;\n\n const color = getBotColor();\n if (this.instance instanceof EmbedBuilder) {\n if (this.instance.data.color === undefined) this.instance.setColor(resolveColor(color));\n } else if (this.instance instanceof ContainerBuilder) {\n const accent = this.instance.data.accent_color;\n if (accent === null || accent === undefined) {\n this.instance.setAccentColor(color === 'Default' ? undefined : resolveColor(color));\n }\n }\n }\n}\n\n/**\n * Base class for Discord action row components\n *\n * Wraps Discord.js action row builder with Seedcord-specific defaults and helper methods.\n *\n * @typeParam RowKey - The Discord.js action row type being wrapped\n */\nexport abstract class RowComponent<RowKey extends RowType> extends BaseComponent<InstantiatedActionRow<RowKey>> {\n protected constructor(public readonly type: RowKey) {\n const ComponentClass = RowTypes[type] as unknown;\n super(ComponentClass as new () => InstantiatedActionRow<RowKey>);\n }\n\n get component(): InstantiatedActionRow<RowKey> {\n return this.instance;\n }\n}\n","import { TextDisplayBuilder } from '@discordjs/builders';\n\nimport { BuilderComponent } from '@components/Component';\n\n/**\n * Built fresh inside a {@link Notice}'s `render` to back its ComponentsV2 reply. The title renders as\n * an h3 line with the description on the next line.\n */\nexport class NoticeCard extends BuilderComponent<'container'> {\n public constructor(description: string, title = 'Cannot Proceed') {\n super('container');\n this.instance.addTextDisplayComponents(new TextDisplayBuilder().setContent(`### ${title}\\n${description}`));\n }\n}\n","import { toEpochSeconds } from '@seedcord/utils';\n\nimport { Notice } from '@stops/Notice';\nimport { NoticeCard } from '@stops/NoticeCard';\n\nimport type { EpochMs, ReplyResponse } from '@seedcord/types';\n\nexport abstract class GateNotice extends Notice {\n public render(): ReplyResponse {\n return { components: [new NoticeCard(this.message).component] };\n }\n}\n\nexport class NotOwner extends GateNotice {\n public constructor(message = 'Only the bot owner can use this.') {\n super(message);\n }\n}\n\nexport class NotInGuild extends GateNotice {\n public constructor(message = 'This can only be used in a server.') {\n super(message);\n }\n}\n\nexport class NotInDm extends GateNotice {\n public constructor(message = 'This can only be used in a direct message.') {\n super(message);\n }\n}\n\nexport class OnCooldown extends GateNotice {\n public constructor(\n public readonly resetAt: EpochMs,\n message?: string\n ) {\n super(message ?? `You are doing that too fast. Try again <t:${toEpochSeconds(resetAt)}:R>.`);\n }\n}\n\nexport class NotAllowed extends Notice {\n public constructor() {\n super('not allowed');\n }\n\n public render(): ReplyResponse {\n return { components: [new NoticeCard('You are not allowed to use this command.').component] };\n }\n}\n\nexport class NeedsAny extends Notice {\n public constructor(private readonly summaries: readonly string[]) {\n super('not allowed');\n }\n\n public render(): ReplyResponse {\n const bullets = this.summaries.map((summary) => `• ${summary}`).join('\\n');\n return { components: [new NoticeCard(`You need any of:\\n${bullets}`).component] };\n }\n}\n","import type { EffectGate, Gate, GateContextBase } from './Gate';\n\ntype CommitFn = () => Promise<void>;\n\n// per-request commit queue keyed on the context, so an effect gate's commit runs only after the whole\n// set passes. WeakMap so each entry is dropped once its request's context is gone\nconst commitQueues = new WeakMap<GateContextBase, CommitFn[]>();\n\nfunction isEffectGate(gate: Gate<GateContextBase>): gate is EffectGate<GateContextBase> {\n return typeof (gate as Partial<EffectGate<GateContextBase>>).commit === 'function';\n}\n\n// a refusal throws before the queue, so a refused effect gate never commits. the combinators and the\n// runner both route through here, so an effect gate inside `and`/`or` queues the same way\nexport async function runCheck(gate: Gate<GateContextBase>, ctx: GateContextBase): Promise<void> {\n await gate.check(ctx);\n if (!isEffectGate(gate)) return;\n\n let queue = commitQueues.get(ctx);\n if (!queue) {\n queue = [];\n commitQueues.set(ctx, queue);\n }\n queue.push(() => gate.commit(ctx));\n}\n\nexport async function runCommits(ctx: GateContextBase): Promise<void> {\n const queue = commitQueues.get(ctx);\n if (!queue) return;\n for (const commit of queue) await commit();\n}\n\n// the runner calls this after every run, so a refused or drained run leaves no stale queue behind\nexport function discardCommits(ctx: GateContextBase): void {\n commitQueues.delete(ctx);\n}\n\n// the queued-commit count, the mark an `or` arm rolls back to if it refuses\nexport function markCommits(ctx: GateContextBase): number {\n return commitQueues.get(ctx)?.length ?? 0;\n}\n\n// drops commits queued after `mark`, so a refused `or` arm leaves no commit behind\nexport function rollbackCommits(ctx: GateContextBase, mark: number): void {\n const queue = commitQueues.get(ctx);\n if (queue && queue.length > mark) queue.length = mark;\n}\n","import type { Notice } from '@stops/Notice';\n\n/**\n * The override a catalog gate accepts, a one-line `message` reword or a full `notice` replacement. Accepted by\n * the agnostic gates ({@link OwnerOnly}, {@link GuildOnly}, {@link DmOnly}, {@link Cooldown}) and the gateway's\n * `RequireRole` and `Nsfw`. The gateway's `RequirePermissions` and `RequireBotPermissions` take\n * `RequirePermissionsOptions` instead.\n *\n * @example\n * ```ts\n * // reword the default refusal\n * OwnerOnly({ message: 'Bot owners only.' });\n * ```\n *\n * @example\n * ```ts\n * // replace the refusal entirely, for example a translated Notice\n * GuildOnly({ notice: new MyTranslatedNotice() });\n * ```\n */\nexport interface GateNoticeOptions {\n /** Reword the default refusal, keeping its embed styling. */\n message?: string;\n /** Replace the default refusal Notice entirely, for full control or a translated copy. */\n notice?: Notice;\n}\n\nexport function pickNotice(options: GateNoticeOptions | undefined, makeDefault: (message?: string) => Notice): Notice {\n return options?.notice ?? makeDefault(options?.message);\n}\n","import { Notice } from '@stops/Notice';\nimport { NoticeCard } from '@stops/NoticeCard';\n\nimport type { ReplyResponse } from '@seedcord/types';\n\n/**\n * Thrown when a customId was minted by an older version of its shape.\n *\n * This is normal after the shape changes. The reply tells the user to run the command again.\n */\nexport class StaleCustomId extends Notice {\n constructor(prefix: string) {\n super(`Stale customId for \"${prefix}\".`);\n }\n\n render(): ReplyResponse {\n const card = new NoticeCard(\n 'This button or menu is from an older version. Please run the command again.',\n 'Outdated'\n );\n return { components: [card.component] };\n }\n}\n\n/**\n * Thrown when a customId wire is corrupt or tampered with and cannot be trusted.\n *\n * This should not happen in normal use, so it reports.\n */\nexport class InvalidCustomId extends Notice {\n constructor(detail: string) {\n super(`Invalid customId. ${detail}`);\n this.report = true;\n }\n\n render(): ReplyResponse {\n const card = new NoticeCard('Something went wrong. Please try again.');\n return { components: [card.component] };\n }\n}\n","/* eslint-disable no-magic-numbers -- lots of bigints */\n\nimport { SeedcordErrorCode } from '@seedcord/errors';\nimport { SeedcordRangeError } from '@seedcord/errors/internal';\n\nimport { InvalidCustomId } from './Errors';\n\nimport type { CustomIdField, CustomIdShape } from './Field';\n\n// wire is routeKey, a colon, then the body. the routeKey is the stable prefix plus a short shape\n// hash, so a shape change produces a new routeKey and decode rejects an old wire as stale. bounded\n// fields (known range) fold into one base64 integer by mixed-radix packing, unbounded ones (free\n// string, unbounded int) trail it as delimited tokens.\n//\n// works on runtime values (unknown), CustomId.ts adds the typed layer.\n\n// url-safe base64, one utf-16 unit per char so encode's wire.length cap counts chars exactly.\nconst ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_';\nconst BASE = 64n;\nconst CHAR_TO_VALUE = new Map([...ALPHABET].map((char, index) => [char, index] as const));\n\nconst DELIMITER = '\\u{1F}';\nconst ESCAPE = '\\u{1B}';\n\n/** @internal */\nexport const HASH_LENGTH = 3;\n\nconst SAFE_MAX = BigInt(Number.MAX_SAFE_INTEGER);\nconst SAFE_MIN = BigInt(Number.MIN_SAFE_INTEGER);\n\n// toString and parseInt top out at base 36, and float64 loses integers past 2^53.\nfunction bigintToBase64(value: bigint): string {\n if (value === 0n) return ALPHABET.charAt(0);\n let text = '';\n for (let remaining = value; remaining > 0n; remaining /= BASE) {\n text = ALPHABET.charAt(Number(remaining % BASE)) + text;\n }\n return text;\n}\n\nfunction base64ToBigint(text: string): bigint {\n let value = 0n;\n for (const char of text) {\n const digit = CHAR_TO_VALUE.get(char);\n if (digit === undefined) throw new InvalidCustomId(`bad character ${JSON.stringify(char)}`);\n value = value * BASE + BigInt(digit);\n }\n return value;\n}\n\n// zigzag keeps a small negative number short on the wire.\nfunction zigzagEncode(value: number): bigint {\n const big = BigInt(value);\n return big >= 0n ? big << 1n : (-big << 1n) - 1n;\n}\nfunction zigzagDecode(encoded: bigint): bigint {\n return (encoded & 1n) === 1n ? -((encoded + 1n) >> 1n) : encoded >> 1n;\n}\n\nfunction escapeToken(text: string): string {\n return text.replaceAll(/[\\x1B\\x1F]/g, (char) => ESCAPE + char);\n}\nfunction unescapeToken(text: string): string {\n let out = '';\n for (let i = 0; i < text.length; i++) {\n if (text.charAt(i) !== ESCAPE) {\n out += text.charAt(i);\n continue;\n }\n const next = text.charAt(i + 1);\n if (next === '') throw new InvalidCustomId('dangling escape at end of token');\n out += next;\n i++;\n }\n return out;\n}\nfunction splitTokens(body: string): string[] {\n const pieces: string[] = [];\n let current = '';\n for (let i = 0; i < body.length; i++) {\n const char = body.charAt(i);\n if (char === ESCAPE) {\n current += char + body.charAt(i + 1);\n i++;\n } else if (char === DELIMITER) {\n pieces.push(current);\n current = '';\n } else {\n current += char;\n }\n }\n pieces.push(current);\n return pieces;\n}\n\n// bounded means the full range is known, so the field can fold into the shared packed integer.\nfunction isBounded(field: CustomIdField<unknown>): boolean {\n if (field.kind === 'int') return field.min !== undefined && field.max !== undefined;\n return field.kind === 'snowflake' || field.kind === 'uuid' || field.kind === 'bool' || field.kind === 'oneOf';\n}\n\n// how many distinct values the field can hold.\nfunction radixOf(field: CustomIdField<unknown>): bigint {\n switch (field.kind) {\n case 'snowflake': {\n return 1n << 64n;\n }\n case 'uuid': {\n return 1n << 128n;\n }\n case 'bool': {\n return 2n;\n }\n case 'oneOf': {\n // oneOf() rejects an empty list at define time, so no choices here means a hand-built\n // corrupt shape.\n if (!field.choices?.length) throw new InvalidCustomId('oneOf field has no choices');\n return BigInt(field.choices.length);\n }\n case 'int': {\n // isBounded only routes a min-and-max int here, so a missing bound means a corrupt shape.\n if (field.min === undefined || field.max === undefined)\n throw new InvalidCustomId('bounded int field is missing a bound');\n // bigint before the math, max - min + 1 in float64 drops the +1 at 2^53.\n return BigInt(field.max) - BigInt(field.min) + 1n;\n }\n default: {\n throw new InvalidCustomId(`field kind ${field.kind} has no radix`);\n }\n }\n}\n\nfunction boundedToBigint(field: CustomIdField<unknown>, name: string, value: unknown): bigint {\n const slot = boundedSlot(field, name, value);\n // out of range would carry into the neighbouring field on decode.\n if (slot < 0n || slot >= radixOf(field)) outOfRange(name, value);\n return slot;\n}\n\n// a slot is the value as an integer in [0, radix).\nfunction boundedSlot(field: CustomIdField<unknown>, name: string, value: unknown): bigint {\n switch (field.kind) {\n case 'snowflake': {\n // BigInt() throws a bare TypeError or SyntaxError on a bad value, so the guard throws\n // the branded error first.\n if (typeof value !== 'string' || !/^\\d+$/.test(value)) return outOfRange(name, value);\n return BigInt(value);\n }\n case 'uuid': {\n if (typeof value !== 'string') return outOfRange(name, value);\n const hex = value.replaceAll('-', '');\n if (!/^[0-9a-fA-F]{32}$/.test(hex)) return outOfRange(name, value);\n return BigInt(`0x${hex}`);\n }\n case 'bool': {\n return value ? 1n : 0n;\n }\n case 'oneOf': {\n const index = (field.choices ?? []).indexOf(value as string);\n return index === -1 ? outOfRange(name, value) : BigInt(index);\n }\n case 'int': {\n // eslint-disable-next-line unicorn/prefer-number-is-safe-integer -- a bounded int field may declare max up to 2**53 exactly (a power of two, exact in float64)\n if (!Number.isInteger(value)) return outOfRange(name, value);\n return BigInt((value as number) - (field.min ?? 0));\n }\n default: {\n return outOfRange(name, value);\n }\n }\n}\n\nfunction outOfRange(name: string, value: unknown): never {\n throw new SeedcordRangeError(SeedcordErrorCode.CustomIdValueOutOfRange, [name, String(value)]);\n}\n\n// inverse of boundedSlot.\nfunction bigintToBoundedValue(field: CustomIdField<unknown>, slot: bigint): unknown {\n switch (field.kind) {\n case 'snowflake': {\n return slot.toString();\n }\n case 'uuid': {\n return bigintToUuid(slot);\n }\n case 'bool': {\n return slot === 1n;\n }\n case 'oneOf': {\n return (field.choices ?? [])[Number(slot)];\n }\n case 'int': {\n return Number(slot) + (field.min ?? 0);\n }\n default: {\n throw new InvalidCustomId(`field kind ${field.kind} is not bounded`);\n }\n }\n}\n\nfunction bigintToUuid(value: bigint): string {\n const hex = value.toString(16).padStart(32, '0');\n return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;\n}\n\nfunction encodeUnboundedToken(field: CustomIdField<unknown>, name: string, value: unknown): string {\n if (field.kind === 'int') {\n if (!Number.isSafeInteger(value)) outOfRange(name, value);\n return bigintToBase64(zigzagEncode(value as number));\n }\n return escapeToken(value as string);\n}\nfunction decodeUnboundedToken(field: CustomIdField<unknown>, piece: string): unknown {\n if (field.kind !== 'int') return unescapeToken(piece);\n // an int always encodes to at least one char, so an empty piece is a truncated wire\n if (piece === '') throw new InvalidCustomId('empty integer token');\n const decoded = zigzagDecode(base64ToBigint(piece));\n // an unbounded int is authored as a js number, so a value past 2^53 cannot come from encode.\n if (decoded > SAFE_MAX || decoded < SAFE_MIN) throw new InvalidCustomId('integer out of safe range');\n return Number(decoded);\n}\n\n/** @internal */\nexport function computeLayoutHash(shape: CustomIdShape): string {\n // stringify escapes the choice strings, so two different shapes cannot produce the same signature.\n const signature = JSON.stringify(\n Object.entries(shape).map(([name, field]) => [\n name,\n field.kind,\n isBounded(field),\n field.kind === 'oneOf' ? (field.choices ?? []) : null,\n field.kind === 'int' ? [field.min ?? null, field.max ?? null] : null\n ])\n );\n const modulus = BASE ** BigInt(HASH_LENGTH);\n let hash = 0n;\n for (const char of signature) hash = (hash * 131n + BigInt(char.charCodeAt(0))) % modulus;\n\n let text = '';\n for (let i = 0; i < HASH_LENGTH; i++) {\n text = ALPHABET.charAt(Number(hash % BASE)) + text;\n hash /= BASE;\n }\n return text;\n}\n\n/** @internal */\nexport function encodeBody(shape: CustomIdShape, values: Record<string, unknown>): string {\n const fields = Object.entries(shape);\n const pieces: string[] = [];\n\n const bounded = fields.filter(([, field]) => isBounded(field));\n if (bounded.length > 0) {\n let packed = 0n;\n for (const [name, field] of bounded)\n packed = packed * radixOf(field) + boundedToBigint(field, name, values[name]);\n pieces.push(bigintToBase64(packed));\n }\n for (const [name, field] of fields) {\n if (!isBounded(field)) pieces.push(encodeUnboundedToken(field, name, values[name]));\n }\n return pieces.join(DELIMITER);\n}\n\nfunction unpackBounded(\n bounded: [string, CustomIdField<unknown>][],\n blob: string | undefined,\n result: Record<string, unknown>\n): void {\n // zero packs to one char, so an empty block means the body was truncated.\n if (blob === undefined || blob === '') throw new InvalidCustomId('empty packed block');\n let packed = base64ToBigint(blob);\n // last field packed is the first one back out.\n for (const [name, field] of [...bounded].reverse()) {\n const radix = radixOf(field);\n result[name] = bigintToBoundedValue(field, packed % radix);\n packed /= radix;\n }\n if (packed !== 0n) throw new InvalidCustomId('leftover bits after unpacking');\n}\n\n/** @internal */\nexport function decodeBody(shape: CustomIdShape, body: string): Record<string, unknown> {\n const fields = Object.entries(shape);\n const bounded = fields.filter(([, field]) => isBounded(field));\n const unbounded = fields.filter(([, field]) => !isBounded(field));\n\n // a shape with no fields encodes to an empty body.\n const expected = (bounded.length > 0 ? 1 : 0) + unbounded.length;\n if (expected === 0) {\n if (body !== '') throw new InvalidCustomId(`expected an empty body, got ${JSON.stringify(body)}`);\n return {};\n }\n\n const pieces = splitTokens(body);\n if (pieces.length !== expected) throw new InvalidCustomId(`expected ${expected} piece(s), got ${pieces.length}`);\n\n const result: Record<string, unknown> = {};\n let cursor = 0;\n\n if (bounded.length > 0) {\n unpackBounded(bounded, pieces[cursor], result);\n cursor++;\n }\n\n for (const [name, field] of unbounded) {\n const piece = pieces[cursor];\n cursor++;\n if (piece === undefined) throw new InvalidCustomId('missing trailing piece');\n result[name] = decodeUnboundedToken(field, piece);\n }\n\n return result;\n}\n","import { SeedcordErrorCode } from '@seedcord/errors';\nimport { SeedcordError, SeedcordRangeError } from '@seedcord/errors/internal';\n\nimport { computeLayoutHash, decodeBody, encodeBody, HASH_LENGTH } from './codec';\nimport { InvalidCustomId, StaleCustomId } from './Errors';\n\nimport type { CustomIdField, CustomIdShape, DecodedParams } from './Field';\nimport type { Snowflake } from 'discord-api-types/v10';\nimport type { NonEmptyTuple } from 'type-fest';\n\n// discord caps a customId at 100 chars.\nconst MAX_WIRE_LENGTH = 100;\n\nfunction routeKeyOf(wire: string): string {\n const colon = wire.indexOf(':');\n return colon === -1 ? '' : wire.slice(0, colon);\n}\n\n/** Strip the layout hash off the routeKey to recover the stable prefix the controller routes by. @internal */\nexport function prefixOf(wire: string): string {\n const key = routeKeyOf(wire);\n return key.length <= HASH_LENGTH ? '' : key.slice(0, key.length - HASH_LENGTH);\n}\n\n/**\n * A typed customId. The single source of truth shared by the component that mints it and the handler\n * that reads it. This gives you typed reads on the `.customId` field in components. Values are packed into a compact wire string rather than plain stringified tokens, so the 100-char Discord limit goes further. More string per string, basically.\n *\n * @typeParam Prefix - The stable route prefix, e.g. 'approve'.\n * @typeParam Shape - The accumulated fields, filled in by the chain.\n *\n * @example\n * ```ts\n * const ApproveId = new CustomId('approve')\n * .snowflake('userId')\n * .oneOf('action', ['approve', 'deny']);\n *\n * // Set the custom id on a button when creating it.\n * new ButtonBuilder().setCustomId(ApproveId.encode({ userId: '123', action: 'approve' }));\n *\n * // reading in the handler: userId comes back a string\n * const { userId, action } = this.params; // userId: string, action: 'approve' | 'deny'\n * await this.event.guild?.members.fetch(userId);\n * ```\n */\nexport class CustomId<Prefix extends string, Shape extends CustomIdShape = {}> {\n /** The stable route prefix, e.g. 'approve'. */\n readonly prefix: Prefix;\n /** Like a zod shape */\n readonly shape: Shape;\n /** The prefix plus a short hash of the shape, the part of the wire before the colon. */\n readonly routeKey: string;\n\n constructor(prefix: Prefix, shape: Shape = {} as Shape) {\n // an empty prefix would make the routeKey all-hash so prefixOf strips it to nothing and the\n // controller cannot route it, and a colon or control char would break the wire framing.\n if (!prefix || /[:\\x1B\\x1F]/.test(prefix)) {\n throw new SeedcordError(SeedcordErrorCode.CustomIdInvalidPrefix, [prefix]);\n }\n this.prefix = prefix;\n this.shape = shape;\n this.routeKey = prefix + computeLayoutHash(shape);\n }\n\n // a fresh immutable CustomId with one more field so we don't need a `as unknown as this` cast.\n private add<Name extends string, Decoded>(\n name: Name,\n field: CustomIdField<Decoded>\n ): CustomId<Prefix, Shape & Record<Name, CustomIdField<Decoded>>> {\n // integer-like keys get reordered by js, which would scramble the field order.\n if (/^(?:0|[1-9]\\d*)$/.test(name)) throw new SeedcordError(SeedcordErrorCode.CustomIdReservedFieldName, [name]);\n // a repeat name collapses the field's decoded type to never and overwrites the earlier field\n // at runtime, so reject it here at define time.\n if (name in this.shape) throw new SeedcordError(SeedcordErrorCode.CustomIdDuplicateFieldName, [name]);\n // justified, the spread plus a computed key cannot be proven to the exact intersection\n const shape = { ...this.shape, [name]: field } as Shape & Record<Name, CustomIdField<Decoded>>;\n return new CustomId(this.prefix, shape);\n }\n\n /**\n * Add a Discord ID field, decoded as a string (the `Snowflake` type from discord-api-types).\n *\n * @example\n * ```ts\n * new CustomId('ban').snowflake('userId');\n * ```\n */\n snowflake<Name extends string>(name: Name): CustomId<Prefix, Shape & Record<Name, CustomIdField<Snowflake>>> {\n return this.add<Name, Snowflake>(name, { kind: 'snowflake' });\n }\n\n /**\n * Add a UUID field, decoded as a lowercase uuid string.\n *\n * @example\n * ```ts\n * new CustomId('ticket').uuid('ticketId');\n * ```\n */\n uuid<Name extends string>(name: Name): CustomId<Prefix, Shape & Record<Name, CustomIdField<string>>> {\n return this.add<Name, string>(name, { kind: 'uuid' });\n }\n\n /**\n * Add an integer field with no bounds, for a value up to 2^53.\n *\n * @example\n * ```ts\n * new CustomId('shop').int('amount');\n * ```\n */\n int<Name extends string>(name: Name): CustomId<Prefix, Shape & Record<Name, CustomIdField<number>>>;\n /**\n * Add an integer field bounded by min and max, so it packs into fewer characters on the wire.\n *\n * @example\n * ```ts\n * new CustomId('paginate').int('page', 1, 50);\n * ```\n */\n int<Name extends string>(\n name: Name,\n min: number,\n max: number\n ): CustomId<Prefix, Shape & Record<Name, CustomIdField<number>>>;\n int<Name extends string>(\n name: Name,\n min?: number,\n max?: number\n ): CustomId<Prefix, Shape & Record<Name, CustomIdField<number>>> {\n if (min !== undefined && max !== undefined && min > max) {\n throw new SeedcordError(SeedcordErrorCode.CustomIdInvalidBounds, [name, min, max]);\n }\n const field: CustomIdField<number> =\n min === undefined || max === undefined ? { kind: 'int' } : { kind: 'int', min, max };\n return this.add<Name, number>(name, field);\n }\n\n /**\n * Add a boolean flag.\n *\n * @example\n * ```ts\n * new CustomId('settings').bool('silent');\n * ```\n */\n bool<Name extends string>(name: Name): CustomId<Prefix, Shape & Record<Name, CustomIdField<boolean>>> {\n return this.add<Name, boolean>(name, { kind: 'bool' });\n }\n\n /**\n * Add a field that is one value from a fixed list, decoded as the literal union. No `as const` needed.\n *\n * @example\n * ```ts\n * new CustomId('poll').oneOf('choice', ['yes', 'no', 'abstain']);\n * ```\n */\n oneOf<Name extends string, const Choices extends NonEmptyTuple<string>>(\n name: Name,\n choices: Choices\n ): CustomId<Prefix, Shape & Record<Name, CustomIdField<Choices[number]>>> {\n if (choices.length === 0) throw new SeedcordError(SeedcordErrorCode.CustomIdEmptyChoices, [name]);\n return this.add<Name, Choices[number]>(name, { kind: 'oneOf', choices });\n }\n\n /**\n * Add a free short text field. Avoid it where possible, it cannot be packed so it costs the most wire space.\n *\n * @example\n * ```ts\n * new CustomId('note').str('message');\n * ```\n */\n str<Name extends string>(name: Name): CustomId<Prefix, Shape & Record<Name, CustomIdField<string>>> {\n return this.add<Name, string>(name, { kind: 'string' });\n }\n\n /**\n * Mint a wire string from values. Throws if a value is out of its field's range or the wire is over 100 chars.\n *\n * @param values - One value per field, typed by the chain.\n * @returns The wire string to put on the component's customId.\n */\n encode(values: DecodedParams<Shape>): string {\n const wire = `${this.routeKey}:${encodeBody(this.shape, values)}`;\n if (wire.length > MAX_WIRE_LENGTH) {\n throw new SeedcordRangeError(SeedcordErrorCode.CustomIdWireTooLong, [wire.length]);\n }\n return wire;\n }\n\n /**\n * Read a wire string back into values.\n *\n * - This will refuse with a default Notice when the shape changed since the wire was minted.\n * - Or refuse with a different default Notice on a corrupt or foreign wire.\n *\n * @param wire - The customId string from the interaction.\n * @returns The decoded values, typed by the chain.\n */\n decode(wire: string): DecodedParams<Shape> {\n const key = routeKeyOf(wire);\n if (key !== this.routeKey) {\n // same prefix but a different hash means the shape changed since this wire was minted.\n if (prefixOf(wire) === this.prefix) throw new StaleCustomId(this.prefix);\n throw new InvalidCustomId(`routeKey ${JSON.stringify(key)} is not ${JSON.stringify(this.routeKey)}`);\n }\n // justified, the codec returns runtime values and the shape guarantees their decoded types.\n return decodeBody(this.shape, wire.slice(key.length + 1)) as DecodedParams<Shape>;\n }\n\n /** True if this wire was minted from this customId's prefix, ignoring the shape hash. */\n owns(wire: string): boolean {\n return prefixOf(wire) === this.prefix;\n }\n}\n\n/**\n * Any customId, for places where the exact prefix and shape do not matter.\n *\n * @internal\n */\nexport type AnyCustomId = CustomId<string, CustomIdShape>;\n\n/**\n * The outcome of decoding a wire against several customIds, the matched prefix paired with its values.\n *\n * @internal\n */\nexport type DecodedRoute<Defs extends readonly AnyCustomId[]> = {\n [Index in keyof Defs]: Defs[Index] extends AnyCustomId\n ? { readonly prefix: Defs[Index]['prefix']; readonly params: DecodedParams<Defs[Index]['shape']> }\n : never;\n}[number];\n\n/**\n * Find the customId whose prefix owns this wire, decode against it, and report which one matched.\n *\n * @internal\n */\nexport function decodeFor<Defs extends readonly AnyCustomId[]>(defs: Defs, wire: string): DecodedRoute<Defs> {\n const match = defs.find((def) => def.owns(wire));\n if (!match) throw new InvalidCustomId(`no customId owns ${JSON.stringify(routeKeyOf(wire))}`);\n // justified, the matched customId fixes both prefix and params together but find() loses that link.\n return { prefix: match.prefix, params: match.decode(wire) } as DecodedRoute<Defs>;\n}\n"],"mappings":";;;;;;;AAAA,IAAY,oBAAL;CACH;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA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AAC,KAAK,MAAM,CAAC;EAErF,OAAO;CACX;;;;;;;;;;CAWA,OAAO,MAAoC;EACvC,MAAM,MAAM,WAAW,IAAI;EAC3B,IAAI,QAAQ,KAAK,UAAU;GAEvB,IAAI,SAAS,IAAI,MAAM,KAAK,QAAQ,MAAM,IAAI,cAAc,KAAK,MAAM;GACvE,MAAM,IAAI,gBAAgB,YAAY,KAAK,UAAU,GAAG,EAAE,UAAU,KAAK,UAAU,KAAK,QAAQ,GAAG;EACvG;EAEA,OAAO,WAAW,KAAK,OAAO,KAAK,MAAM,IAAI,SAAS,CAAC,CAAC;CAC5D;;CAGA,KAAK,MAAuB;EACxB,OAAO,SAAS,IAAI,MAAM,KAAK;CACnC;AACJ;;;;;;AAyBA,SAAgB,UAA+C,MAAY,MAAkC;CACzG,MAAM,QAAQ,KAAK,MAAM,QAAQ,IAAI,KAAK,IAAI,CAAC;CAC/C,IAAI,CAAC,OAAO,MAAM,IAAI,gBAAgB,oBAAoB,KAAK,UAAU,WAAW,IAAI,CAAC,GAAG;CAE5F,OAAO;EAAE,QAAQ,MAAM;EAAQ,QAAQ,MAAM,OAAO,IAAI;CAAE;AAC9D"}
|
|
@@ -51,7 +51,7 @@ const SubscribeMetadataKey = Symbol("seedcord:subscribe:metadata");
|
|
|
51
51
|
*
|
|
52
52
|
* @example
|
|
53
53
|
* ```ts
|
|
54
|
-
* import { Notice, BuilderComponent, type RenderContext, type ReplyResponse } from 'seedcord';
|
|
54
|
+
* import { Notice, BuilderComponent, type RenderContext, type ReplyResponse } from '@seedcord/gateway';
|
|
55
55
|
* import { TextDisplayBuilder } from '@discordjs/builders';
|
|
56
56
|
*
|
|
57
57
|
* // reading `.component` applies the configured bot color to the container accent
|
|
@@ -817,4 +817,4 @@ function decodeFor(defs, wire) {
|
|
|
817
817
|
|
|
818
818
|
//#endregion
|
|
819
819
|
export { EventMetadataKey as C, InteractionRoutes as D, InteractionRouteKeys as E, MiddlewareMetadataKey as O, CommandMetadataKey as S, InteractionMetadataKey as T, NoticeCard as _, discardCommits as a, setBotColor as b, runCheck as c, NeedsAny as d, NotAllowed as f, OnCooldown as g, NotOwner as h, pickNotice as i, SubscribeMetadataKey as k, runCommits as l, NotInGuild as m, decodeFor as n, markCommits as o, NotInDm as p, prefixOf as r, rollbackCommits as s, CustomId as t, GateNotice as u, BuilderComponent as v, GatedMetadataKey as w, Notice as x, RowComponent as y };
|
|
820
|
-
//# sourceMappingURL=CustomId-
|
|
820
|
+
//# sourceMappingURL=CustomId-epJayEGO.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"CustomId-epJayEGO.mjs","names":[],"sources":["../src/metadataKeys.ts","../src/stops/Notice.ts","../src/components/botColorHolder.ts","../src/components/builderTypes.ts","../src/components/colors.ts","../src/components/resolveColor.ts","../src/components/Component.ts","../src/stops/NoticeCard.ts","../src/notices/index.ts","../src/gates/effects.ts","../src/gates/catalog/options.ts","../src/customId/Errors.ts","../src/customId/codec.ts","../src/customId/CustomId.ts"],"sourcesContent":["export enum InteractionRoutes {\n Slash = 'slash',\n Button = 'button',\n Modal = 'modal',\n StringMenu = 'stringMenu',\n UserMenu = 'userMenu',\n RoleMenu = 'roleMenu',\n ChannelMenu = 'channelMenu',\n MentionableMenu = 'mentionableMenu',\n MessageContextMenu = 'messageContextMenu',\n UserContextMenu = 'userContextMenu',\n Autocomplete = 'autocomplete'\n}\n\nexport const InteractionMetadataKey = Symbol('seedcord:interaction:metadata');\n\nexport const InteractionRouteKeys: Record<InteractionRoutes, symbol> = {\n [InteractionRoutes.Slash]: Symbol('seedcord:interaction:slash'),\n [InteractionRoutes.Button]: Symbol('seedcord:interaction:button'),\n [InteractionRoutes.Modal]: Symbol('seedcord:interaction:modal'),\n [InteractionRoutes.StringMenu]: Symbol('seedcord:interaction:stringMenu'),\n [InteractionRoutes.UserMenu]: Symbol('seedcord:interaction:userMenu'),\n [InteractionRoutes.RoleMenu]: Symbol('seedcord:interaction:roleMenu'),\n [InteractionRoutes.ChannelMenu]: Symbol('seedcord:interaction:channelMenu'),\n [InteractionRoutes.MentionableMenu]: Symbol('seedcord:interaction:mentionableMenu'),\n [InteractionRoutes.MessageContextMenu]: Symbol('seedcord:interaction:messageContextMenu'),\n [InteractionRoutes.UserContextMenu]: Symbol('seedcord:interaction:userContextMenu'),\n [InteractionRoutes.Autocomplete]: Symbol('seedcord:interaction:autocomplete')\n};\n\nexport const MiddlewareMetadataKey = Symbol('seedcord:middleware:metadata');\n\nexport const EventMetadataKey = Symbol('seedcord:event:metadata');\n\nexport const CommandMetadataKey = Symbol('seedcord:command:metadata');\n\nexport const GatedMetadataKey = Symbol('seedcord:gated:metadata');\n\nexport const SubscribeMetadataKey = Symbol('seedcord:subscribe:metadata');\n","import type { RenderContext, ReplyResponse } from '@seedcord/types';\n\n/**\n * Base class for a user-facing refusal or a reported fault.\n *\n * Throw a `Notice` to stop a handler and reply to the user. The framework catches it at the controller\n * boundary and renders {@link Notice.render}, which always decides what the user sees. With `report`\n * false that render is all that happens. With `report` true the framework also logs the fault and\n * publishes it to the `handledException` bus. A raw, non-Notice throw shows the generic message.\n *\n * @example\n * ```ts\n * import { Notice, BuilderComponent, type RenderContext, type ReplyResponse } from '@seedcord/gateway';\n * import { TextDisplayBuilder } from '@discordjs/builders';\n *\n * // reading `.component` applies the configured bot color to the container accent\n * class TooPoorCard extends BuilderComponent<'container'> {\n * constructor(balance: number) {\n * super('container');\n * this.instance.addTextDisplayComponents(\n * new TextDisplayBuilder().setContent(`### Insufficient balance\\nYou need more than ${balance} coins.`)\n * );\n * }\n * }\n *\n * class TooPoor extends Notice {\n * constructor(private readonly balance: number) {\n * super(`balance ${balance} is below the cost`);\n * }\n *\n * render(_ctx: RenderContext): ReplyResponse {\n * return { components: [new TooPoorCard(this.balance).component] };\n * }\n * }\n *\n * // in a handler, throwing stops the handler and replies with render(ctx)\n * if (wallet.balance < cost) throw new TooPoor(wallet.balance);\n * ```\n */\nexport abstract class Notice extends Error {\n /**\n * Whether this denial is a reported fault. True also logs it and publishes it to the `handledException`\n * bus. The user always sees {@link Notice.render} either way.\n *\n * @defaultValue `false`\n */\n public report = false;\n\n /**\n * Whether the reply is ephemeral, so only the invoking user sees it. Set it false for a refusal the\n * whole channel should see.\n *\n * @defaultValue `true`\n */\n public ephemeral = true;\n\n /**\n * A short one-line reason. When every arm of an `or` gate refuses and each refusal sets this, `or`\n * lists them instead of showing a neutral message.\n */\n public summary?: string;\n\n protected constructor(message: string, options?: ErrorOptions) {\n super(message, options);\n\n // Error sets name to 'Error', so stamp the concrete subclass name for logs and the fault report\n this.name = new.target.name;\n Error.captureStackTrace(this, this.constructor);\n }\n\n /**\n * Builds what the user sees. Called fresh each time the denial is shown, so the builders are new\n * and the bot color resolves at render time rather than at construction time.\n */\n public abstract render(ctx: RenderContext): ReplyResponse;\n}\n","import type { BotColor } from '@seedcord/types';\n\n// must be 'Default' so the container guard in applyBotColor leaves the accent unset\nconst DEFAULT_COLOR: BotColor = 'Default';\n\nlet current: BotColor = DEFAULT_COLOR;\n\nexport function setBotColor(color: BotColor | undefined): void {\n current = color ?? DEFAULT_COLOR;\n}\n\nexport function getBotColor(): BotColor {\n return current;\n}\n","import {\n ActionRowBuilder,\n ButtonBuilder,\n ChannelSelectMenuBuilder,\n CheckboxBuilder,\n CheckboxGroupBuilder,\n CheckboxGroupOptionBuilder,\n ContainerBuilder,\n ContextMenuCommandBuilder,\n EmbedBuilder,\n FileBuilder,\n FileUploadBuilder,\n LabelBuilder,\n MediaGalleryBuilder,\n MentionableSelectMenuBuilder,\n ModalBuilder,\n RadioGroupBuilder,\n RadioGroupOptionBuilder,\n RoleSelectMenuBuilder,\n SectionBuilder,\n SeparatorBuilder,\n SlashCommandBuilder,\n SlashCommandSubcommandBuilder,\n SlashCommandSubcommandGroupBuilder,\n StringSelectMenuBuilder,\n StringSelectMenuOptionBuilder,\n TextDisplayBuilder,\n TextInputBuilder,\n UserSelectMenuBuilder\n} from '@discordjs/builders';\n\n/**\n * Available Discord.js builder classes for use with BuilderComponent for commands, embeds, modals, etc.\n *\n * @internal\n */\nexport const BuilderTypes = {\n // Command Components\n command: SlashCommandBuilder,\n context_menu: ContextMenuCommandBuilder,\n subcommand: SlashCommandSubcommandBuilder,\n group: SlashCommandSubcommandGroupBuilder,\n\n // Embed Components\n embed: EmbedBuilder,\n\n // Modal Components\n modal: ModalBuilder,\n label: LabelBuilder,\n text_input: TextInputBuilder,\n file_upload: FileUploadBuilder,\n checkbox: CheckboxBuilder,\n checkbox_group: CheckboxGroupBuilder,\n checkbox_group_option: CheckboxGroupOptionBuilder,\n radio_group: RadioGroupBuilder,\n radio_group_option: RadioGroupOptionBuilder,\n\n // Action Row Components\n button: ButtonBuilder,\n menu_string: StringSelectMenuBuilder,\n menu_option_string: StringSelectMenuOptionBuilder,\n menu_user: UserSelectMenuBuilder,\n menu_channel: ChannelSelectMenuBuilder,\n menu_mentionable: MentionableSelectMenuBuilder,\n menu_role: RoleSelectMenuBuilder,\n\n // ComponentsV2\n container: ContainerBuilder,\n text_display: TextDisplayBuilder,\n file: FileBuilder,\n media: MediaGalleryBuilder,\n section: SectionBuilder,\n separator: SeparatorBuilder\n};\n\n/**\n * Available Discord.js action row classes for use with RowComponent for Select Menus and Buttons\n *\n * @internal\n */\nexport const RowTypes: {\n button: typeof ActionRowBuilder<ButtonBuilder>;\n menu_string: typeof ActionRowBuilder<StringSelectMenuBuilder>;\n menu_user: typeof ActionRowBuilder<UserSelectMenuBuilder>;\n menu_channel: typeof ActionRowBuilder<ChannelSelectMenuBuilder>;\n menu_mentionable: typeof ActionRowBuilder<MentionableSelectMenuBuilder>;\n menu_role: typeof ActionRowBuilder<RoleSelectMenuBuilder>;\n} = {\n button: ActionRowBuilder<ButtonBuilder>,\n menu_string: ActionRowBuilder<StringSelectMenuBuilder>,\n menu_user: ActionRowBuilder<UserSelectMenuBuilder>,\n menu_channel: ActionRowBuilder<ChannelSelectMenuBuilder>,\n menu_mentionable: ActionRowBuilder<MentionableSelectMenuBuilder>,\n menu_role: ActionRowBuilder<RoleSelectMenuBuilder>\n};\n\n/**\n * Available Discord.js builder types for use with BuilderComponent\n */\nexport type BuilderType = keyof typeof BuilderTypes;\n\n/**\n * @internal\n */\nexport type InstantiatedBuilder<BuilderKey extends BuilderType> = InstanceType<(typeof BuilderTypes)[BuilderKey]>;\n\n/**\n * Available Discord.js action row types for use with RowComponent\n */\nexport type RowType = keyof typeof RowTypes;\n\n/**\n * @internal\n */\nexport type InstantiatedActionRow<RowKey extends RowType> = InstanceType<(typeof RowTypes)[RowKey]>;\n","import type { ColorName, TypedOmit } from '@seedcord/types';\n\n// Ported verbatim from discord.js (Apache-2.0), src/util/Colors.js.\nexport const Colors: TypedOmit<Record<ColorName, number>, 'Random'> = {\n Aqua: 0x1a_bc_9c,\n Blue: 0x34_98_db,\n Blurple: 0x58_65_f2,\n DarkAqua: 0x11_80_6a,\n DarkBlue: 0x20_66_94,\n DarkButNotBlack: 0x2c_2f_33,\n DarkerGrey: 0x7f_8c_8d,\n DarkGold: 0xc2_7c_0e,\n DarkGreen: 0x1f_8b_4c,\n DarkGrey: 0x97_9c_9f,\n DarkNavy: 0x2c_3e_50,\n DarkOrange: 0xa8_43_00,\n DarkPurple: 0x71_36_8a,\n DarkRed: 0x99_2d_22,\n DarkVividPink: 0xad_14_57,\n Default: 0x00_00_00,\n Fuchsia: 0xeb_45_9e,\n Gold: 0xf1_c4_0f,\n Green: 0x57_f2_87,\n Grey: 0x95_a5_a6,\n Greyple: 0x99_aa_b5,\n LightGrey: 0xbc_c0_c0,\n LuminousVividPink: 0xe9_1e_63,\n Navy: 0x34_49_5e,\n NotQuiteBlack: 0x23_27_2a,\n Orange: 0xe6_7e_22,\n Purple: 0x9b_59_b6,\n Red: 0xed_42_45,\n White: 0xff_ff_ff,\n Yellow: 0xfe_e7_5c\n} as const;\n","import { SeedcordErrorCode } from '@seedcord/errors';\nimport { SeedcordRangeError, SeedcordTypeError } from '@seedcord/errors/internal';\n\nimport { Colors } from './colors';\n\nimport type { BotColor } from '@seedcord/types';\n\nconst MAX_COLOR = 0xff_ff_ff;\nconst RED_SHIFT = 16;\nconst GREEN_SHIFT = 8;\n\nconst palette: Record<string, number | undefined> = Colors;\n\n/**\n * Resolves a {@link BotColor} to the integer Discord expects.\n *\n * Ported from discord.js (Apache-2.0), `resolveColor` in src/util/Util.js.\n */\nexport function resolveColor(color: BotColor): number {\n let resolved: number | undefined;\n\n if (typeof color === 'string') {\n if (color === 'Random') return Math.floor(Math.random() * (MAX_COLOR + 1));\n if (color === 'Default') return 0;\n if (/^#?[\\da-f]{6}$/i.test(color)) return Number.parseInt(color.replace('#', ''), 16);\n resolved = palette[color];\n } else if (typeof color === 'number') {\n resolved = color;\n } else {\n resolved = (color[0] << RED_SHIFT) + (color[1] << GREEN_SHIFT) + color[2];\n }\n\n if (resolved === undefined || !Number.isSafeInteger(resolved)) {\n throw new SeedcordTypeError(SeedcordErrorCode.ColorUnresolvable, [JSON.stringify(color)]);\n }\n if (resolved < 0 || resolved > MAX_COLOR) {\n throw new SeedcordRangeError(SeedcordErrorCode.ColorOutOfRange);\n }\n\n return resolved;\n}\n","import { ContainerBuilder, ContextMenuCommandBuilder, EmbedBuilder, SlashCommandBuilder } from '@discordjs/builders';\nimport { InteractionContextType } from 'discord-api-types/v10';\n\nimport { getBotColor } from './botColorHolder';\nimport { BuilderTypes, RowTypes } from './builderTypes';\nimport { resolveColor } from './resolveColor';\n\nimport type { BuilderType, InstantiatedActionRow, InstantiatedBuilder, RowType } from './builderTypes';\n\n/**\n * Base class for Discord component wrappers.\n *\n * @typeParam TComponent - The Discord.js component type being wrapped\n *\n * @internal\n */\nabstract class BaseComponent<TComponent> {\n private readonly _component: TComponent;\n\n protected constructor(ComponentClass: new () => TComponent) {\n this._component = new ComponentClass();\n }\n\n /**\n * Returns the live builder, ready to send in a Discord message or nest in another component.\n *\n * Configure it through `this.instance`. Reading this can apply the bot color (see\n * {@link BuilderComponent}), so it has a side effect.\n * @example new SomeComponent().component\n */\n public abstract get component(): InstantiatedBuilder<BuilderType> | InstantiatedActionRow<RowType>;\n\n /**\n * The wrapped builder, for calling Discord.js methods like setTitle() and setDescription() inside a subclass.\n *\n * @example this.instance.setTitle('My Modal')\n */\n protected get instance(): TComponent {\n return this._component;\n }\n}\n\n/**\n * Base class for Discord.js builder components\n *\n * Wraps Discord.js builders (SlashCommandBuilder, EmbedBuilder, etc.) with\n * Seedcord-specific defaults and helper methods.\n *\n * @typeParam BuilderKey - The type of Discord.js builder being wrapped\n */\nexport abstract class BuilderComponent<BuilderKey extends BuilderType> extends BaseComponent<\n InstantiatedBuilder<BuilderKey>\n> {\n private colorApplied = false;\n\n protected constructor(public readonly type: BuilderKey) {\n const ComponentClass = BuilderTypes[type] as unknown;\n super(ComponentClass as new () => InstantiatedBuilder<BuilderKey>);\n\n if (this.instance instanceof SlashCommandBuilder || this.instance instanceof ContextMenuCommandBuilder) {\n this.instance.setContexts(InteractionContextType.Guild);\n }\n }\n\n get component(): InstantiatedBuilder<BuilderKey> {\n this.applyBotColor();\n return this.instance;\n }\n\n // Resolving in the constructor would capture the default for a component built before setBotColor()\n // ran. The unset check keeps a color the subclass set for itself.\n private applyBotColor(): void {\n if (this.colorApplied) return;\n this.colorApplied = true;\n\n const color = getBotColor();\n if (this.instance instanceof EmbedBuilder) {\n if (this.instance.data.color === undefined) this.instance.setColor(resolveColor(color));\n } else if (this.instance instanceof ContainerBuilder) {\n const accent = this.instance.data.accent_color;\n if (accent === null || accent === undefined) {\n this.instance.setAccentColor(color === 'Default' ? undefined : resolveColor(color));\n }\n }\n }\n}\n\n/**\n * Base class for Discord action row components\n *\n * Wraps Discord.js action row builder with Seedcord-specific defaults and helper methods.\n *\n * @typeParam RowKey - The Discord.js action row type being wrapped\n */\nexport abstract class RowComponent<RowKey extends RowType> extends BaseComponent<InstantiatedActionRow<RowKey>> {\n protected constructor(public readonly type: RowKey) {\n const ComponentClass = RowTypes[type] as unknown;\n super(ComponentClass as new () => InstantiatedActionRow<RowKey>);\n }\n\n get component(): InstantiatedActionRow<RowKey> {\n return this.instance;\n }\n}\n","import { TextDisplayBuilder } from '@discordjs/builders';\n\nimport { BuilderComponent } from '@components/Component';\n\n/**\n * Built fresh inside a {@link Notice}'s `render` to back its ComponentsV2 reply. The title renders as\n * an h3 line with the description on the next line.\n */\nexport class NoticeCard extends BuilderComponent<'container'> {\n public constructor(description: string, title = 'Cannot Proceed') {\n super('container');\n this.instance.addTextDisplayComponents(new TextDisplayBuilder().setContent(`### ${title}\\n${description}`));\n }\n}\n","import { toEpochSeconds } from '@seedcord/utils';\n\nimport { Notice } from '@stops/Notice';\nimport { NoticeCard } from '@stops/NoticeCard';\n\nimport type { EpochMs, ReplyResponse } from '@seedcord/types';\n\nexport abstract class GateNotice extends Notice {\n public render(): ReplyResponse {\n return { components: [new NoticeCard(this.message).component] };\n }\n}\n\nexport class NotOwner extends GateNotice {\n public constructor(message = 'Only the bot owner can use this.') {\n super(message);\n }\n}\n\nexport class NotInGuild extends GateNotice {\n public constructor(message = 'This can only be used in a server.') {\n super(message);\n }\n}\n\nexport class NotInDm extends GateNotice {\n public constructor(message = 'This can only be used in a direct message.') {\n super(message);\n }\n}\n\nexport class OnCooldown extends GateNotice {\n public constructor(\n public readonly resetAt: EpochMs,\n message?: string\n ) {\n super(message ?? `You are doing that too fast. Try again <t:${toEpochSeconds(resetAt)}:R>.`);\n }\n}\n\nexport class NotAllowed extends Notice {\n public constructor() {\n super('not allowed');\n }\n\n public render(): ReplyResponse {\n return { components: [new NoticeCard('You are not allowed to use this command.').component] };\n }\n}\n\nexport class NeedsAny extends Notice {\n public constructor(private readonly summaries: readonly string[]) {\n super('not allowed');\n }\n\n public render(): ReplyResponse {\n const bullets = this.summaries.map((summary) => `• ${summary}`).join('\\n');\n return { components: [new NoticeCard(`You need any of:\\n${bullets}`).component] };\n }\n}\n","import type { EffectGate, Gate, GateContextBase } from './Gate';\n\ntype CommitFn = () => Promise<void>;\n\n// per-request commit queue keyed on the context, so an effect gate's commit runs only after the whole\n// set passes. WeakMap so each entry is dropped once its request's context is gone\nconst commitQueues = new WeakMap<GateContextBase, CommitFn[]>();\n\nfunction isEffectGate(gate: Gate<GateContextBase>): gate is EffectGate<GateContextBase> {\n return typeof (gate as Partial<EffectGate<GateContextBase>>).commit === 'function';\n}\n\n// a refusal throws before the queue, so a refused effect gate never commits. the combinators and the\n// runner both route through here, so an effect gate inside `and`/`or` queues the same way\nexport async function runCheck(gate: Gate<GateContextBase>, ctx: GateContextBase): Promise<void> {\n await gate.check(ctx);\n if (!isEffectGate(gate)) return;\n\n let queue = commitQueues.get(ctx);\n if (!queue) {\n queue = [];\n commitQueues.set(ctx, queue);\n }\n queue.push(() => gate.commit(ctx));\n}\n\nexport async function runCommits(ctx: GateContextBase): Promise<void> {\n const queue = commitQueues.get(ctx);\n if (!queue) return;\n for (const commit of queue) await commit();\n}\n\n// the runner calls this after every run, so a refused or drained run leaves no stale queue behind\nexport function discardCommits(ctx: GateContextBase): void {\n commitQueues.delete(ctx);\n}\n\n// the queued-commit count, the mark an `or` arm rolls back to if it refuses\nexport function markCommits(ctx: GateContextBase): number {\n return commitQueues.get(ctx)?.length ?? 0;\n}\n\n// drops commits queued after `mark`, so a refused `or` arm leaves no commit behind\nexport function rollbackCommits(ctx: GateContextBase, mark: number): void {\n const queue = commitQueues.get(ctx);\n if (queue && queue.length > mark) queue.length = mark;\n}\n","import type { Notice } from '@stops/Notice';\n\n/**\n * The override a catalog gate accepts, a one-line `message` reword or a full `notice` replacement. Accepted by\n * the agnostic gates ({@link OwnerOnly}, {@link GuildOnly}, {@link DmOnly}, {@link Cooldown}) and the gateway's\n * `RequireRole` and `Nsfw`. The gateway's `RequirePermissions` and `RequireBotPermissions` take\n * `RequirePermissionsOptions` instead.\n *\n * @example\n * ```ts\n * // reword the default refusal\n * OwnerOnly({ message: 'Bot owners only.' });\n * ```\n *\n * @example\n * ```ts\n * // replace the refusal entirely, for example a translated Notice\n * GuildOnly({ notice: new MyTranslatedNotice() });\n * ```\n */\nexport interface GateNoticeOptions {\n /** Reword the default refusal, keeping its embed styling. */\n message?: string;\n /** Replace the default refusal Notice entirely, for full control or a translated copy. */\n notice?: Notice;\n}\n\nexport function pickNotice(options: GateNoticeOptions | undefined, makeDefault: (message?: string) => Notice): Notice {\n return options?.notice ?? makeDefault(options?.message);\n}\n","import { Notice } from '@stops/Notice';\nimport { NoticeCard } from '@stops/NoticeCard';\n\nimport type { ReplyResponse } from '@seedcord/types';\n\n/**\n * Thrown when a customId was minted by an older version of its shape.\n *\n * This is normal after the shape changes. The reply tells the user to run the command again.\n */\nexport class StaleCustomId extends Notice {\n constructor(prefix: string) {\n super(`Stale customId for \"${prefix}\".`);\n }\n\n render(): ReplyResponse {\n const card = new NoticeCard(\n 'This button or menu is from an older version. Please run the command again.',\n 'Outdated'\n );\n return { components: [card.component] };\n }\n}\n\n/**\n * Thrown when a customId wire is corrupt or tampered with and cannot be trusted.\n *\n * This should not happen in normal use, so it reports.\n */\nexport class InvalidCustomId extends Notice {\n constructor(detail: string) {\n super(`Invalid customId. ${detail}`);\n this.report = true;\n }\n\n render(): ReplyResponse {\n const card = new NoticeCard('Something went wrong. Please try again.');\n return { components: [card.component] };\n }\n}\n","/* eslint-disable no-magic-numbers -- lots of bigints */\n\nimport { SeedcordErrorCode } from '@seedcord/errors';\nimport { SeedcordRangeError } from '@seedcord/errors/internal';\n\nimport { InvalidCustomId } from './Errors';\n\nimport type { CustomIdField, CustomIdShape } from './Field';\n\n// wire is routeKey, a colon, then the body. the routeKey is the stable prefix plus a short shape\n// hash, so a shape change produces a new routeKey and decode rejects an old wire as stale. bounded\n// fields (known range) fold into one base64 integer by mixed-radix packing, unbounded ones (free\n// string, unbounded int) trail it as delimited tokens.\n//\n// works on runtime values (unknown), CustomId.ts adds the typed layer.\n\n// url-safe base64, one utf-16 unit per char so encode's wire.length cap counts chars exactly.\nconst ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_';\nconst BASE = 64n;\nconst CHAR_TO_VALUE = new Map([...ALPHABET].map((char, index) => [char, index] as const));\n\nconst DELIMITER = '\\u{1F}';\nconst ESCAPE = '\\u{1B}';\n\n/** @internal */\nexport const HASH_LENGTH = 3;\n\nconst SAFE_MAX = BigInt(Number.MAX_SAFE_INTEGER);\nconst SAFE_MIN = BigInt(Number.MIN_SAFE_INTEGER);\n\n// toString and parseInt top out at base 36, and float64 loses integers past 2^53.\nfunction bigintToBase64(value: bigint): string {\n if (value === 0n) return ALPHABET.charAt(0);\n let text = '';\n for (let remaining = value; remaining > 0n; remaining /= BASE) {\n text = ALPHABET.charAt(Number(remaining % BASE)) + text;\n }\n return text;\n}\n\nfunction base64ToBigint(text: string): bigint {\n let value = 0n;\n for (const char of text) {\n const digit = CHAR_TO_VALUE.get(char);\n if (digit === undefined) throw new InvalidCustomId(`bad character ${JSON.stringify(char)}`);\n value = value * BASE + BigInt(digit);\n }\n return value;\n}\n\n// zigzag keeps a small negative number short on the wire.\nfunction zigzagEncode(value: number): bigint {\n const big = BigInt(value);\n return big >= 0n ? big << 1n : (-big << 1n) - 1n;\n}\nfunction zigzagDecode(encoded: bigint): bigint {\n return (encoded & 1n) === 1n ? -((encoded + 1n) >> 1n) : encoded >> 1n;\n}\n\nfunction escapeToken(text: string): string {\n return text.replaceAll(/[\\x1B\\x1F]/g, (char) => ESCAPE + char);\n}\nfunction unescapeToken(text: string): string {\n let out = '';\n for (let i = 0; i < text.length; i++) {\n if (text.charAt(i) !== ESCAPE) {\n out += text.charAt(i);\n continue;\n }\n const next = text.charAt(i + 1);\n if (next === '') throw new InvalidCustomId('dangling escape at end of token');\n out += next;\n i++;\n }\n return out;\n}\nfunction splitTokens(body: string): string[] {\n const pieces: string[] = [];\n let current = '';\n for (let i = 0; i < body.length; i++) {\n const char = body.charAt(i);\n if (char === ESCAPE) {\n current += char + body.charAt(i + 1);\n i++;\n } else if (char === DELIMITER) {\n pieces.push(current);\n current = '';\n } else {\n current += char;\n }\n }\n pieces.push(current);\n return pieces;\n}\n\n// bounded means the full range is known, so the field can fold into the shared packed integer.\nfunction isBounded(field: CustomIdField<unknown>): boolean {\n if (field.kind === 'int') return field.min !== undefined && field.max !== undefined;\n return field.kind === 'snowflake' || field.kind === 'uuid' || field.kind === 'bool' || field.kind === 'oneOf';\n}\n\n// how many distinct values the field can hold.\nfunction radixOf(field: CustomIdField<unknown>): bigint {\n switch (field.kind) {\n case 'snowflake': {\n return 1n << 64n;\n }\n case 'uuid': {\n return 1n << 128n;\n }\n case 'bool': {\n return 2n;\n }\n case 'oneOf': {\n // oneOf() rejects an empty list at define time, so no choices here means a hand-built\n // corrupt shape.\n if (!field.choices?.length) throw new InvalidCustomId('oneOf field has no choices');\n return BigInt(field.choices.length);\n }\n case 'int': {\n // isBounded only routes a min-and-max int here, so a missing bound means a corrupt shape.\n if (field.min === undefined || field.max === undefined)\n throw new InvalidCustomId('bounded int field is missing a bound');\n // bigint before the math, max - min + 1 in float64 drops the +1 at 2^53.\n return BigInt(field.max) - BigInt(field.min) + 1n;\n }\n default: {\n throw new InvalidCustomId(`field kind ${field.kind} has no radix`);\n }\n }\n}\n\nfunction boundedToBigint(field: CustomIdField<unknown>, name: string, value: unknown): bigint {\n const slot = boundedSlot(field, name, value);\n // out of range would carry into the neighbouring field on decode.\n if (slot < 0n || slot >= radixOf(field)) outOfRange(name, value);\n return slot;\n}\n\n// a slot is the value as an integer in [0, radix).\nfunction boundedSlot(field: CustomIdField<unknown>, name: string, value: unknown): bigint {\n switch (field.kind) {\n case 'snowflake': {\n // BigInt() throws a bare TypeError or SyntaxError on a bad value, so the guard throws\n // the branded error first.\n if (typeof value !== 'string' || !/^\\d+$/.test(value)) return outOfRange(name, value);\n return BigInt(value);\n }\n case 'uuid': {\n if (typeof value !== 'string') return outOfRange(name, value);\n const hex = value.replaceAll('-', '');\n if (!/^[0-9a-fA-F]{32}$/.test(hex)) return outOfRange(name, value);\n return BigInt(`0x${hex}`);\n }\n case 'bool': {\n return value ? 1n : 0n;\n }\n case 'oneOf': {\n const index = (field.choices ?? []).indexOf(value as string);\n return index === -1 ? outOfRange(name, value) : BigInt(index);\n }\n case 'int': {\n // eslint-disable-next-line unicorn/prefer-number-is-safe-integer -- a bounded int field may declare max up to 2**53 exactly (a power of two, exact in float64)\n if (!Number.isInteger(value)) return outOfRange(name, value);\n return BigInt((value as number) - (field.min ?? 0));\n }\n default: {\n return outOfRange(name, value);\n }\n }\n}\n\nfunction outOfRange(name: string, value: unknown): never {\n throw new SeedcordRangeError(SeedcordErrorCode.CustomIdValueOutOfRange, [name, String(value)]);\n}\n\n// inverse of boundedSlot.\nfunction bigintToBoundedValue(field: CustomIdField<unknown>, slot: bigint): unknown {\n switch (field.kind) {\n case 'snowflake': {\n return slot.toString();\n }\n case 'uuid': {\n return bigintToUuid(slot);\n }\n case 'bool': {\n return slot === 1n;\n }\n case 'oneOf': {\n return (field.choices ?? [])[Number(slot)];\n }\n case 'int': {\n return Number(slot) + (field.min ?? 0);\n }\n default: {\n throw new InvalidCustomId(`field kind ${field.kind} is not bounded`);\n }\n }\n}\n\nfunction bigintToUuid(value: bigint): string {\n const hex = value.toString(16).padStart(32, '0');\n return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;\n}\n\nfunction encodeUnboundedToken(field: CustomIdField<unknown>, name: string, value: unknown): string {\n if (field.kind === 'int') {\n if (!Number.isSafeInteger(value)) outOfRange(name, value);\n return bigintToBase64(zigzagEncode(value as number));\n }\n return escapeToken(value as string);\n}\nfunction decodeUnboundedToken(field: CustomIdField<unknown>, piece: string): unknown {\n if (field.kind !== 'int') return unescapeToken(piece);\n // an int always encodes to at least one char, so an empty piece is a truncated wire\n if (piece === '') throw new InvalidCustomId('empty integer token');\n const decoded = zigzagDecode(base64ToBigint(piece));\n // an unbounded int is authored as a js number, so a value past 2^53 cannot come from encode.\n if (decoded > SAFE_MAX || decoded < SAFE_MIN) throw new InvalidCustomId('integer out of safe range');\n return Number(decoded);\n}\n\n/** @internal */\nexport function computeLayoutHash(shape: CustomIdShape): string {\n // stringify escapes the choice strings, so two different shapes cannot produce the same signature.\n const signature = JSON.stringify(\n Object.entries(shape).map(([name, field]) => [\n name,\n field.kind,\n isBounded(field),\n field.kind === 'oneOf' ? (field.choices ?? []) : null,\n field.kind === 'int' ? [field.min ?? null, field.max ?? null] : null\n ])\n );\n const modulus = BASE ** BigInt(HASH_LENGTH);\n let hash = 0n;\n for (const char of signature) hash = (hash * 131n + BigInt(char.charCodeAt(0))) % modulus;\n\n let text = '';\n for (let i = 0; i < HASH_LENGTH; i++) {\n text = ALPHABET.charAt(Number(hash % BASE)) + text;\n hash /= BASE;\n }\n return text;\n}\n\n/** @internal */\nexport function encodeBody(shape: CustomIdShape, values: Record<string, unknown>): string {\n const fields = Object.entries(shape);\n const pieces: string[] = [];\n\n const bounded = fields.filter(([, field]) => isBounded(field));\n if (bounded.length > 0) {\n let packed = 0n;\n for (const [name, field] of bounded)\n packed = packed * radixOf(field) + boundedToBigint(field, name, values[name]);\n pieces.push(bigintToBase64(packed));\n }\n for (const [name, field] of fields) {\n if (!isBounded(field)) pieces.push(encodeUnboundedToken(field, name, values[name]));\n }\n return pieces.join(DELIMITER);\n}\n\nfunction unpackBounded(\n bounded: [string, CustomIdField<unknown>][],\n blob: string | undefined,\n result: Record<string, unknown>\n): void {\n // zero packs to one char, so an empty block means the body was truncated.\n if (blob === undefined || blob === '') throw new InvalidCustomId('empty packed block');\n let packed = base64ToBigint(blob);\n // last field packed is the first one back out.\n for (const [name, field] of [...bounded].reverse()) {\n const radix = radixOf(field);\n result[name] = bigintToBoundedValue(field, packed % radix);\n packed /= radix;\n }\n if (packed !== 0n) throw new InvalidCustomId('leftover bits after unpacking');\n}\n\n/** @internal */\nexport function decodeBody(shape: CustomIdShape, body: string): Record<string, unknown> {\n const fields = Object.entries(shape);\n const bounded = fields.filter(([, field]) => isBounded(field));\n const unbounded = fields.filter(([, field]) => !isBounded(field));\n\n // a shape with no fields encodes to an empty body.\n const expected = (bounded.length > 0 ? 1 : 0) + unbounded.length;\n if (expected === 0) {\n if (body !== '') throw new InvalidCustomId(`expected an empty body, got ${JSON.stringify(body)}`);\n return {};\n }\n\n const pieces = splitTokens(body);\n if (pieces.length !== expected) throw new InvalidCustomId(`expected ${expected} piece(s), got ${pieces.length}`);\n\n const result: Record<string, unknown> = {};\n let cursor = 0;\n\n if (bounded.length > 0) {\n unpackBounded(bounded, pieces[cursor], result);\n cursor++;\n }\n\n for (const [name, field] of unbounded) {\n const piece = pieces[cursor];\n cursor++;\n if (piece === undefined) throw new InvalidCustomId('missing trailing piece');\n result[name] = decodeUnboundedToken(field, piece);\n }\n\n return result;\n}\n","import { SeedcordErrorCode } from '@seedcord/errors';\nimport { SeedcordError, SeedcordRangeError } from '@seedcord/errors/internal';\n\nimport { computeLayoutHash, decodeBody, encodeBody, HASH_LENGTH } from './codec';\nimport { InvalidCustomId, StaleCustomId } from './Errors';\n\nimport type { CustomIdField, CustomIdShape, DecodedParams } from './Field';\nimport type { Snowflake } from 'discord-api-types/v10';\nimport type { NonEmptyTuple } from 'type-fest';\n\n// discord caps a customId at 100 chars.\nconst MAX_WIRE_LENGTH = 100;\n\nfunction routeKeyOf(wire: string): string {\n const colon = wire.indexOf(':');\n return colon === -1 ? '' : wire.slice(0, colon);\n}\n\n/** Strip the layout hash off the routeKey to recover the stable prefix the controller routes by. @internal */\nexport function prefixOf(wire: string): string {\n const key = routeKeyOf(wire);\n return key.length <= HASH_LENGTH ? '' : key.slice(0, key.length - HASH_LENGTH);\n}\n\n/**\n * A typed customId. The single source of truth shared by the component that mints it and the handler\n * that reads it. This gives you typed reads on the `.customId` field in components. Values are packed into a compact wire string rather than plain stringified tokens, so the 100-char Discord limit goes further. More string per string, basically.\n *\n * @typeParam Prefix - The stable route prefix, e.g. 'approve'.\n * @typeParam Shape - The accumulated fields, filled in by the chain.\n *\n * @example\n * ```ts\n * const ApproveId = new CustomId('approve')\n * .snowflake('userId')\n * .oneOf('action', ['approve', 'deny']);\n *\n * // Set the custom id on a button when creating it.\n * new ButtonBuilder().setCustomId(ApproveId.encode({ userId: '123', action: 'approve' }));\n *\n * // reading in the handler: userId comes back a string\n * const { userId, action } = this.params; // userId: string, action: 'approve' | 'deny'\n * await this.event.guild?.members.fetch(userId);\n * ```\n */\nexport class CustomId<Prefix extends string, Shape extends CustomIdShape = {}> {\n /** The stable route prefix, e.g. 'approve'. */\n readonly prefix: Prefix;\n /** Like a zod shape */\n readonly shape: Shape;\n /** The prefix plus a short hash of the shape, the part of the wire before the colon. */\n readonly routeKey: string;\n\n constructor(prefix: Prefix, shape: Shape = {} as Shape) {\n // an empty prefix would make the routeKey all-hash so prefixOf strips it to nothing and the\n // controller cannot route it, and a colon or control char would break the wire framing.\n if (!prefix || /[:\\x1B\\x1F]/.test(prefix)) {\n throw new SeedcordError(SeedcordErrorCode.CustomIdInvalidPrefix, [prefix]);\n }\n this.prefix = prefix;\n this.shape = shape;\n this.routeKey = prefix + computeLayoutHash(shape);\n }\n\n // a fresh immutable CustomId with one more field so we don't need a `as unknown as this` cast.\n private add<Name extends string, Decoded>(\n name: Name,\n field: CustomIdField<Decoded>\n ): CustomId<Prefix, Shape & Record<Name, CustomIdField<Decoded>>> {\n // integer-like keys get reordered by js, which would scramble the field order.\n if (/^(?:0|[1-9]\\d*)$/.test(name)) throw new SeedcordError(SeedcordErrorCode.CustomIdReservedFieldName, [name]);\n // a repeat name collapses the field's decoded type to never and overwrites the earlier field\n // at runtime, so reject it here at define time.\n if (name in this.shape) throw new SeedcordError(SeedcordErrorCode.CustomIdDuplicateFieldName, [name]);\n // justified, the spread plus a computed key cannot be proven to the exact intersection\n const shape = { ...this.shape, [name]: field } as Shape & Record<Name, CustomIdField<Decoded>>;\n return new CustomId(this.prefix, shape);\n }\n\n /**\n * Add a Discord ID field, decoded as a string (the `Snowflake` type from discord-api-types).\n *\n * @example\n * ```ts\n * new CustomId('ban').snowflake('userId');\n * ```\n */\n snowflake<Name extends string>(name: Name): CustomId<Prefix, Shape & Record<Name, CustomIdField<Snowflake>>> {\n return this.add<Name, Snowflake>(name, { kind: 'snowflake' });\n }\n\n /**\n * Add a UUID field, decoded as a lowercase uuid string.\n *\n * @example\n * ```ts\n * new CustomId('ticket').uuid('ticketId');\n * ```\n */\n uuid<Name extends string>(name: Name): CustomId<Prefix, Shape & Record<Name, CustomIdField<string>>> {\n return this.add<Name, string>(name, { kind: 'uuid' });\n }\n\n /**\n * Add an integer field with no bounds, for a value up to 2^53.\n *\n * @example\n * ```ts\n * new CustomId('shop').int('amount');\n * ```\n */\n int<Name extends string>(name: Name): CustomId<Prefix, Shape & Record<Name, CustomIdField<number>>>;\n /**\n * Add an integer field bounded by min and max, so it packs into fewer characters on the wire.\n *\n * @example\n * ```ts\n * new CustomId('paginate').int('page', 1, 50);\n * ```\n */\n int<Name extends string>(\n name: Name,\n min: number,\n max: number\n ): CustomId<Prefix, Shape & Record<Name, CustomIdField<number>>>;\n int<Name extends string>(\n name: Name,\n min?: number,\n max?: number\n ): CustomId<Prefix, Shape & Record<Name, CustomIdField<number>>> {\n if (min !== undefined && max !== undefined && min > max) {\n throw new SeedcordError(SeedcordErrorCode.CustomIdInvalidBounds, [name, min, max]);\n }\n const field: CustomIdField<number> =\n min === undefined || max === undefined ? { kind: 'int' } : { kind: 'int', min, max };\n return this.add<Name, number>(name, field);\n }\n\n /**\n * Add a boolean flag.\n *\n * @example\n * ```ts\n * new CustomId('settings').bool('silent');\n * ```\n */\n bool<Name extends string>(name: Name): CustomId<Prefix, Shape & Record<Name, CustomIdField<boolean>>> {\n return this.add<Name, boolean>(name, { kind: 'bool' });\n }\n\n /**\n * Add a field that is one value from a fixed list, decoded as the literal union. No `as const` needed.\n *\n * @example\n * ```ts\n * new CustomId('poll').oneOf('choice', ['yes', 'no', 'abstain']);\n * ```\n */\n oneOf<Name extends string, const Choices extends NonEmptyTuple<string>>(\n name: Name,\n choices: Choices\n ): CustomId<Prefix, Shape & Record<Name, CustomIdField<Choices[number]>>> {\n if (choices.length === 0) throw new SeedcordError(SeedcordErrorCode.CustomIdEmptyChoices, [name]);\n return this.add<Name, Choices[number]>(name, { kind: 'oneOf', choices });\n }\n\n /**\n * Add a free short text field. Avoid it where possible, it cannot be packed so it costs the most wire space.\n *\n * @example\n * ```ts\n * new CustomId('note').str('message');\n * ```\n */\n str<Name extends string>(name: Name): CustomId<Prefix, Shape & Record<Name, CustomIdField<string>>> {\n return this.add<Name, string>(name, { kind: 'string' });\n }\n\n /**\n * Mint a wire string from values. Throws if a value is out of its field's range or the wire is over 100 chars.\n *\n * @param values - One value per field, typed by the chain.\n * @returns The wire string to put on the component's customId.\n */\n encode(values: DecodedParams<Shape>): string {\n const wire = `${this.routeKey}:${encodeBody(this.shape, values)}`;\n if (wire.length > MAX_WIRE_LENGTH) {\n throw new SeedcordRangeError(SeedcordErrorCode.CustomIdWireTooLong, [wire.length]);\n }\n return wire;\n }\n\n /**\n * Read a wire string back into values.\n *\n * - This will refuse with a default Notice when the shape changed since the wire was minted.\n * - Or refuse with a different default Notice on a corrupt or foreign wire.\n *\n * @param wire - The customId string from the interaction.\n * @returns The decoded values, typed by the chain.\n */\n decode(wire: string): DecodedParams<Shape> {\n const key = routeKeyOf(wire);\n if (key !== this.routeKey) {\n // same prefix but a different hash means the shape changed since this wire was minted.\n if (prefixOf(wire) === this.prefix) throw new StaleCustomId(this.prefix);\n throw new InvalidCustomId(`routeKey ${JSON.stringify(key)} is not ${JSON.stringify(this.routeKey)}`);\n }\n // justified, the codec returns runtime values and the shape guarantees their decoded types.\n return decodeBody(this.shape, wire.slice(key.length + 1)) as DecodedParams<Shape>;\n }\n\n /** True if this wire was minted from this customId's prefix, ignoring the shape hash. */\n owns(wire: string): boolean {\n return prefixOf(wire) === this.prefix;\n }\n}\n\n/**\n * Any customId, for places where the exact prefix and shape do not matter.\n *\n * @internal\n */\nexport type AnyCustomId = CustomId<string, CustomIdShape>;\n\n/**\n * The outcome of decoding a wire against several customIds, the matched prefix paired with its values.\n *\n * @internal\n */\nexport type DecodedRoute<Defs extends readonly AnyCustomId[]> = {\n [Index in keyof Defs]: Defs[Index] extends AnyCustomId\n ? { readonly prefix: Defs[Index]['prefix']; readonly params: DecodedParams<Defs[Index]['shape']> }\n : never;\n}[number];\n\n/**\n * Find the customId whose prefix owns this wire, decode against it, and report which one matched.\n *\n * @internal\n */\nexport function decodeFor<Defs extends readonly AnyCustomId[]>(defs: Defs, wire: string): DecodedRoute<Defs> {\n const match = defs.find((def) => def.owns(wire));\n if (!match) throw new InvalidCustomId(`no customId owns ${JSON.stringify(routeKeyOf(wire))}`);\n // justified, the matched customId fixes both prefix and params together but find() loses that link.\n return { prefix: match.prefix, params: match.decode(wire) } as DecodedRoute<Defs>;\n}\n"],"mappings":";;;;;;;AAAA,IAAY,oBAAL;CACH;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;;AACJ;AAEA,MAAa,yBAAyB,OAAO,+BAA+B;AAE5E,MAAa,uBAA0D;YACxC,OAAO,4BAA4B;aAClC,OAAO,6BAA6B;YACrC,OAAO,4BAA4B;iBAC9B,OAAO,iCAAiC;eAC1C,OAAO,+BAA+B;eACtC,OAAO,+BAA+B;kBACnC,OAAO,kCAAkC;sBACrC,OAAO,sCAAsC;yBAC1C,OAAO,yCAAyC;sBACnD,OAAO,sCAAsC;mBAChD,OAAO,mCAAmC;AAChF;AAEA,MAAa,wBAAwB,OAAO,8BAA8B;AAE1E,MAAa,mBAAmB,OAAO,yBAAyB;AAEhE,MAAa,qBAAqB,OAAO,2BAA2B;AAEpE,MAAa,mBAAmB,OAAO,yBAAyB;AAEhE,MAAa,uBAAuB,OAAO,6BAA6B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACCxE,IAAsB,SAAtB,cAAqC,MAAM;;;;;;;CAOvC,AAAO,SAAS;;;;;;;CAQhB,AAAO,YAAY;;;;;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AM,OAAO,IAAI;CAAE;AAC9D"}
|
package/dist/index.cjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
2
|
-
const require_CustomId = require('./CustomId-
|
|
2
|
+
const require_CustomId = require('./CustomId-DV7daU7r.cjs');
|
|
3
3
|
require("reflect-metadata");
|
|
4
4
|
let _seedcord_errors = require("@seedcord/errors");
|
|
5
5
|
let _seedcord_errors_internal = require("@seedcord/errors/internal");
|
|
@@ -24,6 +24,27 @@ function RegisterCommand(scope, guilds = []) {
|
|
|
24
24
|
};
|
|
25
25
|
}
|
|
26
26
|
|
|
27
|
+
//#endregion
|
|
28
|
+
//#region src/dispatch/DispatchContext.ts
|
|
29
|
+
/**
|
|
30
|
+
* A typed bag allocated once per interaction dispatch and handed to the handler. The middleware and i18n
|
|
31
|
+
* work reads and writes it through {@link DispatchState}. Today the bag is empty, so it only carries the
|
|
32
|
+
* dispatched `routeId`.
|
|
33
|
+
*/
|
|
34
|
+
var DispatchContext = class {
|
|
35
|
+
routeId;
|
|
36
|
+
state = {};
|
|
37
|
+
constructor(routeId) {
|
|
38
|
+
this.routeId = routeId;
|
|
39
|
+
}
|
|
40
|
+
set(key, value) {
|
|
41
|
+
this.state[key] = value;
|
|
42
|
+
}
|
|
43
|
+
get(key) {
|
|
44
|
+
return this.state[key];
|
|
45
|
+
}
|
|
46
|
+
};
|
|
47
|
+
|
|
27
48
|
//#endregion
|
|
28
49
|
//#region src/gates/Gate.ts
|
|
29
50
|
/**
|
|
@@ -124,7 +145,7 @@ function defineEffectGate(name, check, commit) {
|
|
|
124
145
|
*
|
|
125
146
|
* @example
|
|
126
147
|
* ```ts
|
|
127
|
-
* import { Fault } from 'seedcord';
|
|
148
|
+
* import { Fault } from '@seedcord/gateway';
|
|
128
149
|
*
|
|
129
150
|
* try {
|
|
130
151
|
* await db.write(record);
|
|
@@ -277,7 +298,7 @@ function DmOnly(options) {
|
|
|
277
298
|
|
|
278
299
|
//#endregion
|
|
279
300
|
//#region src/gates/catalog/Cooldown.ts
|
|
280
|
-
let
|
|
301
|
+
let anonSeq = 0;
|
|
281
302
|
function scopeValue(ctx, per) {
|
|
282
303
|
if (per === "guild") return ctx.guildId ?? "global";
|
|
283
304
|
if (per === "channel") return ctx.channelId ?? "global";
|
|
@@ -288,8 +309,8 @@ function scopeValue(ctx, per) {
|
|
|
288
309
|
* a duration like `30m` or `24h`. An unparseable string throws a **SeedcordTypeError** at construction. The
|
|
289
310
|
* slot is charged in commit, only after the whole gate set passes, so a later refusal never burns the cooldown.
|
|
290
311
|
* That split also means two requests racing the same key can both pass before either charges the slot.
|
|
291
|
-
*
|
|
292
|
-
* or replace it with {@link CooldownOptions.notice}.
|
|
312
|
+
* The key combines the handler's route with the window settings, so two different handlers keep separate
|
|
313
|
+
* windows. Reword the refusal with {@link CooldownOptions.message} or replace it with {@link CooldownOptions.notice}.
|
|
293
314
|
*
|
|
294
315
|
* @param duration - A number is seconds, a string is a duration like `30m` or `24h`. An unparseable string throws a **SeedcordTypeError**.
|
|
295
316
|
* @param options - Sets the scope with `per`, the uses per window with `limit`, and the refusal text with `message` or `notice`.
|
|
@@ -336,13 +357,13 @@ function Cooldown(duration, options) {
|
|
|
336
357
|
windowMs = parsed;
|
|
337
358
|
}
|
|
338
359
|
if (windowMs <= 0) throw new _seedcord_errors_internal.SeedcordTypeError(_seedcord_errors.SeedcordErrorCode.GateInvalidCooldownDuration, [String(duration)]);
|
|
339
|
-
const bucket = `cooldown:${bucketSeq++}`;
|
|
340
360
|
const per = options?.per ?? "user";
|
|
341
361
|
const window = options?.limit === void 0 ? { windowMs } : {
|
|
342
362
|
windowMs,
|
|
343
363
|
limit: options.limit
|
|
344
364
|
};
|
|
345
|
-
const
|
|
365
|
+
const anonId = anonSeq++;
|
|
366
|
+
const keyOf = (ctx) => `cooldown:${ctx.routeId ?? `anon${anonId}`}:${per}:w${windowMs}:l${options?.limit ?? 1}:${scopeValue(ctx, per)}`;
|
|
346
367
|
return defineEffectGate("Cooldown", async (ctx) => {
|
|
347
368
|
const result = await ctx.core.rateLimiter.peek(keyOf(ctx), window);
|
|
348
369
|
if (!result.limited) return;
|
|
@@ -364,7 +385,7 @@ function Cooldown(duration, options) {
|
|
|
364
385
|
*
|
|
365
386
|
* @example
|
|
366
387
|
* ```ts
|
|
367
|
-
* import { Silence } from 'seedcord';
|
|
388
|
+
* import { Silence } from '@seedcord/gateway';
|
|
368
389
|
*
|
|
369
390
|
* // before any reply or defer, drop the interaction with no reply and no report
|
|
370
391
|
* if (await isBlacklisted(interaction.user.id)) throw new Silence('blacklisted user');
|
|
@@ -411,12 +432,13 @@ function paginate(items, page, perPage) {
|
|
|
411
432
|
//#endregion
|
|
412
433
|
//#region src/index.ts
|
|
413
434
|
/** Package version */
|
|
414
|
-
const version = "0.1.0-next.
|
|
435
|
+
const version = "0.1.0-next.3";
|
|
415
436
|
|
|
416
437
|
//#endregion
|
|
417
438
|
exports.BuilderComponent = require_CustomId.BuilderComponent;
|
|
418
439
|
exports.Cooldown = Cooldown;
|
|
419
440
|
exports.CustomId = require_CustomId.CustomId;
|
|
441
|
+
exports.DispatchContext = DispatchContext;
|
|
420
442
|
exports.DmOnly = DmOnly;
|
|
421
443
|
exports.Fault = Fault;
|
|
422
444
|
exports.GuildOnly = GuildOnly;
|