Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/subcommand-piece-preconditions.md
Original file line number Diff line number Diff line change
@@ -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.
3 changes: 2 additions & 1 deletion packages/plugin-subcommands-advanced/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand All @@ -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.
1 change: 1 addition & 0 deletions packages/plugin-subcommands-advanced/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
28 changes: 26 additions & 2 deletions packages/plugin-subcommands-advanced/src/lib/utils/wiring.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import * as framework from "@wolfstar/http-framework";
import { applicationCommandRegistry, CommandRouter, type Command } from "@wolfstar/http-framework";
import {
ApplicationCommandOptionType,
Expand Down Expand Up @@ -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<string, unknown>)["runPreconditions"];
return typeof run === "function" ? (run as RunPreconditions) : undefined;
Comment on lines +167 to +169

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Older framework loading goes untested

The new fallback protects supported frameworks that lack runPreconditions, but the tests import source code and use framework 6.5.1, where the export exists. They cannot catch a build change that turns this lookup into a required import and prevents older applications from starting.

Add a test that imports the built plugin with a framework version that lacks runPreconditions, then runs a modular subcommand.

Knowledge Base Used: Advanced subcommands plugin package

Prompt To Fix With AI
This is a comment left during a code review.
Path: packages/plugin-subcommands-advanced/src/lib/utils/wiring.ts
Line: 167-169

Comment:
**Older framework loading goes untested**

The new fallback protects supported frameworks that lack `runPreconditions`, but the tests import source code and use framework 6.5.1, where the export exists. They cannot catch a build change that turns this lookup into a required import and prevents older applications from starting.

Add a test that imports the built plugin with a framework version that lacks `runPreconditions`, then runs a modular subcommand.

**Knowledge Base Used:** [Advanced subcommands plugin package](https://app.greptile.com/-/switch-tenant?tenant=wolfstar-project&next=%2Fcustom-context%2Fknowledge-base%2Fwolfstar-project%2Fplugins%2F-%2Fdocs%2Fplugin-subcommands-advanced.md)

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

Fix in Claude Code Fix in Cursor

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed in #284 (#282 had already merged): older-framework.test.ts builds the entries and imports them in a Node process whose module hooks serve the framework without runPreconditions, and runs a modular subcommand with the export missing. Turning the lookup into a named import makes the build test fail with does not provide an export named 'runPreconditions'.

}

function lookupEntry(
parentName: string,
methodName: string,
Expand Down
Original file line number Diff line number Diff line change
@@ -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,
Expand Down Expand Up @@ -281,6 +284,128 @@
});
});

describe("preconditions of a subcommand piece", () => {
const deny =

Check warning on line 288 in packages/plugin-subcommands-advanced/tests/subcommands-advanced.test.ts

View workflow job for this annotation

GitHub Actions / Autofix code

unicorn(consistent-function-scoping)

packages/plugin-subcommands-advanced/tests/subcommands-advanced.test.ts:288:11: Function `deny` does not capture any variables from its parent scope

Check warning on line 288 in packages/plugin-subcommands-advanced/tests/subcommands-advanced.test.ts

View workflow job for this annotation

GitHub Actions / 🔠 Lint project

unicorn(consistent-function-scoping)

packages/plugin-subcommands-advanced/tests/subcommands-advanced.test.ts:288:11: Function `deny` does not capture any variables from its parent scope
(name: string): PreconditionFunction =>
() =>
err(new PreconditionError({ precondition: name, message: `${name} denied` }));
const allow: PreconditionFunction = () => ok();

Check warning on line 292 in packages/plugin-subcommands-advanced/tests/subcommands-advanced.test.ts

View workflow job for this annotation

GitHub Actions / Autofix code

unicorn(consistent-function-scoping)

packages/plugin-subcommands-advanced/tests/subcommands-advanced.test.ts:292:11: Function `allow` does not capture any variables from its parent scope

Check warning on line 292 in packages/plugin-subcommands-advanced/tests/subcommands-advanced.test.ts

View workflow job for this annotation

GitHub Actions / 🔠 Lint project

unicorn(consistent-function-scoping)

packages/plugin-subcommands-advanced/tests/subcommands-advanced.test.ts:292:11: Function `allow` does not capture any variables from its parent scope

function defineChildren(childPreconditions: Command.Options["preconditions"]) {

Check warning on line 294 in packages/plugin-subcommands-advanced/tests/subcommands-advanced.test.ts

View workflow job for this annotation

GitHub Actions / 🔠 Lint project

unicorn(consistent-function-scoping)

packages/plugin-subcommands-advanced/tests/subcommands-advanced.test.ts:294:14: Function `defineChildren` does not capture any variables from its parent scope
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"];

Expand Down
3 changes: 3 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading