diff --git a/.changeset/subcommand-piece-preconditions.md b/.changeset/subcommand-piece-preconditions.md new file mode 100644 index 00000000..fdcc609e --- /dev/null +++ b/.changeset/subcommand-piece-preconditions.md @@ -0,0 +1,5 @@ +--- +"@wolfstar/plugin-subcommands-advanced": patch +--- + +A subcommand piece registered with `RegisterAsSubcommand` or `RegisterAsSubcommandGroup` now has its `preconditions` option run before its `chatInputRun`, after those of the parent. A denial emits `chatInputCommandDenied` and the subcommand does not run; before, the option was ignored and the subcommand ran for everybody. Needs `@wolfstar/http-framework` 6.3.0 or later; on an older framework the option does not exist and nothing changes. diff --git a/packages/plugin-subcommands-advanced/README.md b/packages/plugin-subcommands-advanced/README.md index d47d7275..3f4539f0 100644 --- a/packages/plugin-subcommands-advanced/README.md +++ b/packages/plugin-subcommands-advanced/README.md @@ -153,7 +153,7 @@ export class PingCommand extends Command { `@wolfstar/http-framework` routes subcommands to **methods on the parent** command instance. This plugin: 1. Lets child command classes register themselves into in-memory registries (by parent name). -2. After all command pieces are constructed, rebuilds the parent’s chat-input resolver and `CommandRouter`, installing thin delegate methods that call each child’s `chatInputRun`. +2. After all command pieces are constructed, rebuilds the parent’s chat-input resolver and `CommandRouter`, installing thin delegate methods that run each child’s `preconditions`, then its `chatInputRun`. You do not need to call the optional `hooks.subcommands` / `hooks.groups` helpers unless you are registering the parent imperatively and want to attach builders yourself. @@ -162,4 +162,5 @@ You do not need to call the optional `hooks.subcommands` / `hooks.groups` helper - HTTP-only: there is no message-command support (unlike the Sapphire original). - Child classes should **not** use `@RegisterCommand` — only the parent registers the top-level slash command. - Subcommand groups must still be declared on the parent (via `@RegisterCommand` builder or `registerApplicationCommands`). +- Preconditions: the framework runs the global preconditions and the parent's `preconditions` option for every subcommand, then the delegate runs those of the child piece (`runPreconditions` with the child as the target) before its `chatInputRun`. A denial emits `chatInputCommandDenied`, as for any command. The child check needs `@wolfstar/http-framework` 6.3.0 or later, the release that added the option; since it goes through `runPreconditions`, the global preconditions run a second time for a modular subcommand, so keep them free of side effects such as a cooldown counter. - `Command.OptionsOf` / `Subcommand.OptionsOf` re-export the framework's `Command.OptionsOf` (options generated by `stars codegen`). The type needs `@wolfstar/http-framework` 6.2.0 or later; on an older framework it fails to resolve when type-checking with `skipLibCheck` off. diff --git a/packages/plugin-subcommands-advanced/package.json b/packages/plugin-subcommands-advanced/package.json index 2227ebe3..edf736f0 100644 --- a/packages/plugin-subcommands-advanced/package.json +++ b/packages/plugin-subcommands-advanced/package.json @@ -71,6 +71,7 @@ "discord-api-types": "^0.38.33" }, "devDependencies": { + "@sapphire/result": "^2.8.0", "@wolfstar/http-framework": "^6.5.1", "@wolfstar/http-framework-test-utils": "^4.0.4", "@wolfstar/kit": "^0.3.1", diff --git a/packages/plugin-subcommands-advanced/src/lib/utils/wiring.ts b/packages/plugin-subcommands-advanced/src/lib/utils/wiring.ts index 316dfe5e..c41eb901 100644 --- a/packages/plugin-subcommands-advanced/src/lib/utils/wiring.ts +++ b/packages/plugin-subcommands-advanced/src/lib/utils/wiring.ts @@ -1,3 +1,4 @@ +import * as framework from "@wolfstar/http-framework"; import { applicationCommandRegistry, CommandRouter, type Command } from "@wolfstar/http-framework"; import { ApplicationCommandOptionType, @@ -133,18 +134,41 @@ function installDelegate( configurable: true, enumerable: false, writable: true, - value(this: Command, interaction: Command.ApplicationCommandInteraction, args: object) { + async value(this: Command, interaction: Command.ApplicationCommandInteraction, args: object) { const resolved = lookupEntry(parentName, methodName); if (!resolved) { throw new Error( `[plugin-subcommands-advanced]: No child command registered for parent "${parentName}" method "${methodName}".`, ); } - return resolved.commandPiece.chatInputRun(interaction, args); + + const child = resolved.commandPiece; + const run = getRunPreconditions(); + if (run) { + // The framework has run the parent's preconditions; the subcommand piece is a command of its own, so its + // `preconditions` option is checked here. A thrown `UserError` makes the command store emit + // `chatInputCommandDenied` and reply as for any denied command. + const result = await run(child, "chatInput", interaction); + if (result.isErr()) throw result.unwrapErr(); + } + + return child.chatInputRun(interaction, args); }, }); } +type RunPreconditions = typeof framework.runPreconditions; + +/** + * `runPreconditions` exists since `@wolfstar/http-framework` 6.3.0, the release that added the `preconditions` option. + * It is read from the namespace at call time, so the plugin still loads on the older majors of its peer range, where a + * named import of a missing export would fail at link time. + */ +function getRunPreconditions(): RunPreconditions | undefined { + const run = (framework as Record)["runPreconditions"]; + return typeof run === "function" ? (run as RunPreconditions) : undefined; +} + function lookupEntry( parentName: string, methodName: string, diff --git a/packages/plugin-subcommands-advanced/tests/subcommands-advanced.test.ts b/packages/plugin-subcommands-advanced/tests/subcommands-advanced.test.ts index fcd9d75f..f4446a47 100644 --- a/packages/plugin-subcommands-advanced/tests/subcommands-advanced.test.ts +++ b/packages/plugin-subcommands-advanced/tests/subcommands-advanced.test.ts @@ -1,8 +1,11 @@ import { SlashCommandBuilder } from "@discordjs/builders"; +import { err, ok } from "@sapphire/result"; import { ApplicationCommandOptionType, InteractionResponseType } from "discord-api-types/v10"; import { applicationCommandRegistry, container, + PreconditionError, + type PreconditionFunction, RegisterCommand, RegisterSubcommand, RegisterSubcommandGroup, @@ -281,6 +284,128 @@ describe("plugin-subcommands-advanced", () => { }); }); + describe("preconditions of a subcommand piece", () => { + const deny = + (name: string): PreconditionFunction => + () => + err(new PreconditionError({ precondition: name, message: `${name} denied` })); + const allow: PreconditionFunction = () => ok(); + + function defineChildren(childPreconditions: Command.Options["preconditions"]) { + const calls: string[] = []; + + @RegisterCommand((builder) => + builder + .setName("settings") + .setDescription("Settings") + .addSubcommandGroup((group) => group.setName("roles").setDescription("Roles")), + ) + class SettingsCommand extends Subcommand {} + + @RegisterAsSubcommand("settings", (builder) => + builder.setName("server").setDescription("Server settings"), + ) + class ServerCommand extends Command { + public constructor(context: Command.LoaderContext, options: Command.Options) { + super(context, { ...options, preconditions: childPreconditions }); + } + + public override chatInputRun(interaction: Command.ChatInputInteraction) { + calls.push("server"); + return interaction.reply({ content: "server" }); + } + } + + @RegisterAsSubcommandGroup("settings", "roles", (builder) => + builder.setName("add").setDescription("Add a role"), + ) + class RolesAddCommand extends Command { + public constructor(context: Command.LoaderContext, options: Command.Options) { + super(context, { ...options, preconditions: childPreconditions }); + } + + public override chatInputRun(interaction: Command.ChatInputInteraction) { + calls.push("roles add"); + return interaction.reply({ content: "roles add" }); + } + } + + return { calls, SettingsCommand, ServerCommand, RolesAddCommand }; + } + + async function setup(childPreconditions: Command.Options["preconditions"]) { + const { calls, SettingsCommand, ServerCommand, RolesAddCommand } = + defineChildren(childPreconditions); + const { runner } = createTestHarness({ + subcommandsAdvanced: { nameCommandsAutogenerated: true }, + }); + + const denied: string[] = []; + container.client.on("chatInputCommandDenied", (error: PreconditionError) => { + denied.push(error.precondition); + }); + // A denial is handed to `handleError`, which emits `error`: without a listener it would throw. + container.client.on("error", () => {}); + + const children = [makeCommand(ServerCommand), makeCommand(RolesAddCommand)]; + const parent = makeCommand(SettingsCommand); + await loadParentAndChildren(parent, children); + + const run = (options: object[]) => + runner.run({ + ...ChatInputApplicationCommandInteractionData, + data: { id: "0", name: "settings", type: 1, options }, + }); + + return { calls, denied, parent, run }; + } + + const direct = [{ type: ApplicationCommandOptionType.Subcommand, name: "server", options: [] }]; + const grouped = [ + { + type: ApplicationCommandOptionType.SubcommandGroup, + name: "roles", + options: [{ type: ApplicationCommandOptionType.Subcommand, name: "add", options: [] }], + }, + ]; + + it.each([ + ["a direct subcommand", direct], + ["a grouped subcommand", grouped], + ])("denies %s whose piece precondition fails, without running it", async (_, options) => { + const { calls, denied, run } = await setup([deny("administrator")]); + + await run(options); + + expect(calls).toEqual([]); + expect(denied).toEqual(["administrator"]); + }); + + it.each([ + ["a direct subcommand", direct, "server"], + ["a grouped subcommand", grouped, "roles add"], + ])("runs %s whose piece preconditions pass", async (_, options, content) => { + const { calls, denied, run } = await setup([allow]); + + const result = await run(options); + + expect(calls).toEqual([content]); + expect(denied).toEqual([]); + expect(result.statusCode).toBe(200); + expect(result.json()).toMatchObject({ data: { content } }); + }); + + it("runs the parent preconditions before those of the subcommand piece", async () => { + const { calls, denied, parent, run } = await setup([deny("child")]); + Reflect.set(parent.options, "preconditions", [deny("parent")]); + + await run(direct); + + expect(calls).toEqual([]); + expect(denied).toEqual(["parent"]); + }); + }); + describe("subcommand order", () => { const childNames = ["unblock", "block", "history"]; diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 1db8e1d7..724ca14f 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -529,6 +529,9 @@ importers: specifier: ^0.38.33 version: 0.38.56 devDependencies: + '@sapphire/result': + specifier: ^2.8.0 + version: 2.8.0 '@wolfstar/http-framework': specifier: ^6.5.1 version: 6.5.1(acorn@8.19.0)(magicast@0.5.5)(oxc-parser@0.155.0)(rolldown@1.2.16)(tsdown@0.23.4(@arethetypeswrong/core@0.18.5)(oxc-resolver@11.24.2)(publint@0.3.25)(typescript@7.0.2)(unrun@0.3.1))(typescript@7.0.2)(vite@8.3.3(@types/node@22.15.21)(jiti@2.7.0)(yaml@2.9.1))