Skip to content

Commit 4178a8f

Browse files
fix(cli): reject extra positional arguments on every command (#4905)
* fix(cli): reject extra positional arguments on every command * fix(cli): read the command name without assuming a resolved meta * fix(cli): join free-text words for catalog and tts, reject a bad repo root * test(cli): load the listed commands through static imports * fix(cli): keep a tts file path out of the word join and read the parsed json flag * fix(cli): apply the file exception only to a tts .txt path * fix(cli): keep usageLine private and test the json fallback for undeclared json * fix(cli): keep extra arguments and the repo root value out of telemetry * test(cli): type the skills update lookup * fix(cli): read json mode from the parsed flag, reject tts words with --text-file, restore add's hint * fix(cli): check tts words with --text-file before --list and test --json=false
1 parent fcc6370 commit 4178a8f

12 files changed

Lines changed: 444 additions & 39 deletions

‎packages/cli/src/cli.commands.test.ts‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,11 @@ import { readFileSync } from "node:fs";
22
import { dirname, join } from "node:path";
33
import { fileURLToPath } from "node:url";
44
import { describe, expect, it } from "vitest";
5+
import type { CommandDef } from "citty";
6+
import {
7+
ACCEPTS_EXTRA_POSITIONALS,
8+
JOINS_EXTRA_POSITIONALS,
9+
} from "./utils/reject-extra-positionals.js";
510

611
const cliSource = readFileSync(join(dirname(fileURLToPath(import.meta.url)), "cli.ts"), "utf8");
712
const helpSource = readFileSync(join(dirname(fileURLToPath(import.meta.url)), "help.ts"), "utf8");
@@ -12,7 +17,32 @@ function commandLoaderBlock(): string {
1217
return match![1]!;
1318
}
1419

20+
// Vite cannot resolve a template-string import, so each listed top-level command is named here.
21+
const LIST_COMMANDS: Record<string, () => Promise<{ default: unknown }>> = {
22+
catalog: () => import("./commands/catalog.js"),
23+
compare: () => import("./commands/compare.js"),
24+
figma: () => import("./commands/figma.js"),
25+
skills: () => import("./commands/skills.js"),
26+
timeline: () => import("./commands/timeline.js"),
27+
tts: () => import("./commands/tts.js"),
28+
};
29+
1530
describe("CLI command registration", () => {
31+
it.each([...ACCEPTS_EXTRA_POSITIONALS, ...JOINS_EXTRA_POSITIONALS])(
32+
"names a real command in the extra-positional lists: %s",
33+
async (path) => {
34+
const [top, ...subs] = path.split(" ");
35+
expect(commandLoaderBlock()).toMatch(new RegExp(`\\b${top}:\\s*\\(\\)\\s*=>`));
36+
let cmd = (await LIST_COMMANDS[top!]!()).default as CommandDef;
37+
expect(cmd.meta).toMatchObject({ name: top });
38+
for (const sub of subs) {
39+
const entry = (cmd.subCommands as Record<string, unknown>)[sub!];
40+
cmd = (typeof entry === "function" ? await entry() : entry) as CommandDef;
41+
expect(cmd, `${path} resolves to a subcommand`).toBeTruthy();
42+
}
43+
},
44+
);
45+
1646
it("registers keyframes as the only keyframe inspection command", () => {
1747
const loaders = commandLoaderBlock();
1848

‎packages/cli/src/commands/add.test.ts‎

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { describe, expect, it, vi, beforeEach, afterEach } from "vitest";
2-
import { parseArgs as parseCittyArgs, type ArgsDef } from "citty";
2+
import { runCommand as runCittyCommand, type CommandDef } from "citty";
33
import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
44
import { tmpdir } from "node:os";
55
import { join } from "node:path";
@@ -18,6 +18,7 @@ import addCommand, {
1818
} from "./add.js";
1919
import { trackRegistryItemAdded } from "../telemetry/events.js";
2020
import { CliUsageError } from "../utils/commandResult.js";
21+
import { trackCommandFailures } from "../utils/command-failure-tracking.js";
2122

2223
// Assert the emitted payload rather than the transport: `shouldTrack()` is
2324
// already false under test (dev mode / no PostHog key), so a real call would
@@ -539,30 +540,29 @@ describe("add command run() — extra positional arguments", () => {
539540
rmSync(dir, { recursive: true, force: true });
540541
});
541542

542-
async function runCommand(args: Record<string, unknown>): Promise<void> {
543-
await (addCommand.run as (ctx: { args: Record<string, unknown> }) => Promise<void>)({ args });
543+
async function runWrapped(rawArgs: string[]): Promise<void> {
544+
const cmd = await trackCommandFailures(() => Promise.resolve(addCommand as CommandDef))();
545+
await runCittyCommand(cmd, { rawArgs });
544546
}
545547

546-
it("rejects `add a --dir <dir> b c` under real citty parsing, before any registry call", async () => {
548+
it("rejects `add a --dir <dir> b c` through the CLI wrapper, before any registry call", async () => {
547549
const fetchSpy = vi.fn();
548550
vi.stubGlobal("fetch", fetchSpy);
549551

550-
const parsed = parseCittyArgs(["a", "--dir", dir, "b", "c"], addCommand.args as ArgsDef);
551-
expect(parsed._).toEqual(["a", "b", "c"]);
552-
553-
await expect(runCommand(parsed as unknown as Record<string, unknown>)).rejects.toThrow(
554-
CliUsageError,
555-
);
552+
await expect(runWrapped(["a", "--dir", dir, "b", "c"])).rejects.toThrow(CliUsageError);
556553
expect(fetchSpy).not.toHaveBeenCalled();
557-
expect(errorSpy.mock.calls.flat().join(" ")).toContain("extra arguments: b, c");
554+
expect(errorSpy.mock.calls.flat().join(" ")).toContain(
555+
"Unexpected extra arguments for hyperframes add: b, c",
556+
);
557+
expect(errorSpy.mock.calls.flat().join(" ")).toContain("Run add once per item");
558558
});
559559

560560
it("does not fire on a normal single-item invocation", async () => {
561561
mockFetch();
562562
writeRegistryConfig(dir);
563563

564564
await expect(
565-
runCommand({ name: "my-block", _: ["my-block"], dir, clipboard: false, json: true }),
565+
runWrapped(["my-block", "--dir", dir, "--no-clipboard", "--json"]),
566566
).resolves.toBeUndefined();
567567
});
568568
});

‎packages/cli/src/commands/add.ts‎

Lines changed: 1 addition & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { failCommand, failUsage } from "../utils/commandResult.js";
1+
import { failCommand } from "../utils/commandResult.js";
22
import { defineCommand } from "citty";
33
import type { Example } from "./_examples.js";
44

@@ -491,17 +491,6 @@ export default defineCommand({
491491
const json = args.json === true;
492492
const skipClipboard = args.clipboard === false;
493493

494-
// citty binds only the first positional to `name`; the rest land in `args._` and were silently dropped.
495-
const extra = args._.slice(1);
496-
if (extra.length > 0) {
497-
const msg =
498-
`add installs one item or tag per invocation. Got extra argument${extra.length === 1 ? "" : "s"}: ` +
499-
`${extra.join(", ")}. Run add once per item, or pass a single tag to install every item tagged with it.`;
500-
if (json) console.log(JSON.stringify({ ok: false, error: msg }));
501-
else console.error(c.error(msg));
502-
failUsage();
503-
}
504-
505494
const hasConfigBefore = existsSync(projectConfigPath(projectDir));
506495

507496
// Try single item first. If it fails, check if the name matches a tag.
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
2+
import { tmpdir } from "node:os";
3+
import { join } from "node:path";
4+
import { afterEach, describe, expect, it, vi } from "vitest";
5+
import { repoRoot } from "./repoRoot.js";
6+
7+
describe("repoRoot", () => {
8+
const dirs: string[] = [];
9+
const tempDir = () => {
10+
const dir = mkdtempSync(join(tmpdir(), "hf-repo-root-"));
11+
dirs.push(dir);
12+
return dir;
13+
};
14+
15+
afterEach(() => {
16+
vi.unstubAllEnvs();
17+
for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true });
18+
});
19+
20+
it("returns HYPERFRAMES_REPO_ROOT when it is a hyperframes checkout", () => {
21+
const root = tempDir();
22+
mkdirSync(join(root, "packages", "aws-lambda"), { recursive: true });
23+
writeFileSync(join(root, "packages", "aws-lambda", "package.json"), "{}");
24+
vi.stubEnv("HYPERFRAMES_REPO_ROOT", root);
25+
expect(repoRoot()).toBe(root);
26+
});
27+
28+
it("throws on a HYPERFRAMES_REPO_ROOT that is not a checkout instead of ignoring it", () => {
29+
const root = tempDir();
30+
vi.stubEnv("HYPERFRAMES_REPO_ROOT", root);
31+
expect(() => repoRoot()).toThrow("HYPERFRAMES_REPO_ROOT is not a hyperframes checkout");
32+
expect(() => repoRoot()).not.toThrow(root);
33+
});
34+
});

‎packages/cli/src/commands/lambda/repoRoot.ts‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,8 +14,12 @@ import { fileURLToPath } from "node:url";
1414

1515
export function repoRoot(): string {
1616
const override = process.env.HYPERFRAMES_REPO_ROOT;
17-
if (override && existsSync(resolve(override, "packages", "aws-lambda", "package.json"))) {
18-
return override;
17+
if (override) {
18+
if (existsSync(resolve(override, "packages", "aws-lambda", "package.json"))) return override;
19+
throw new Error(
20+
"[hyperframes lambda] HYPERFRAMES_REPO_ROOT is not a hyperframes checkout " +
21+
"(no packages/aws-lambda/package.json there). Point it at the repo root, or unset it.",
22+
);
1923
}
2024
let dir = dirname(fileURLToPath(import.meta.url));
2125
for (let depth = 0; depth < 12; depth++) {

‎packages/cli/src/commands/tts.test.ts‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
33
import { tmpdir } from "node:os";
44
import { join } from "node:path";
55
import { assertKnownFlags } from "../utils/reject-unknown-flags.js";
6+
import { CliUsageError } from "../utils/commandResult.js";
67

78
const synthesizeMock = vi.fn().mockResolvedValue({
89
durationSeconds: 1,
@@ -42,4 +43,26 @@ describe("tts command", () => {
4243
expect.objectContaining({ lang: "en-us" }),
4344
);
4445
});
46+
47+
it("rejects text words with --text-file even under --list", async () => {
48+
const input = join(dir, "script.txt");
49+
writeFileSync(input, "From the file\n");
50+
vi.spyOn(console, "error").mockImplementation(() => {});
51+
52+
await expect(
53+
ttsCommand.run!({ args: { "text-file": input, input: "hello", list: true } } as never),
54+
).rejects.toThrow(CliUsageError);
55+
});
56+
57+
it("rejects text words together with --text-file instead of dropping the words", async () => {
58+
const input = join(dir, "script.txt");
59+
writeFileSync(input, "From the file\n");
60+
const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});
61+
62+
await expect(
63+
ttsCommand.run!({ args: { "text-file": input, input: "hello world" } } as never),
64+
).rejects.toThrow(CliUsageError);
65+
expect(synthesizeMock).not.toHaveBeenCalled();
66+
expect(errorSpy.mock.calls.flat().join(" ")).toContain("not both");
67+
});
4568
});

‎packages/cli/src/commands/tts.ts‎

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
1-
import { failCommand } from "../utils/commandResult.js";
1+
import { failCommand, failUsage } from "../utils/commandResult.js";
2+
import { isTextFile } from "../utils/textFile.js";
23
// fallow-ignore-file code-duplication
34
import { defineCommand } from "citty";
45
import type { Example } from "./_examples.js";
5-
import { existsSync, readFileSync } from "node:fs";
6+
import { readFileSync } from "node:fs";
67

78
export const examples: Example[] = [
89
["Generate speech from text", 'hyperframes tts "Welcome to HyperFrames"'],
@@ -20,7 +21,7 @@ export const examples: Example[] = [
2021
["Read text from a file", "hyperframes tts script.txt"],
2122
["List available voices", "hyperframes tts --list"],
2223
];
23-
import { resolve, extname } from "node:path";
24+
import { resolve } from "node:path";
2425
import * as clack from "@clack/prompts";
2526
import { c } from "../ui/colors.js";
2627
import { errorBox } from "../ui/format.js";
@@ -84,6 +85,11 @@ export default defineCommand({
8485
},
8586
// fallow-ignore-next-line complexity
8687
async run({ args }) {
88+
if (args["text-file"] && args.input) {
89+
console.error(c.error("Pass text to speak or --text-file, not both."));
90+
failUsage();
91+
}
92+
8793
// ── List voices mode ──────────────────────────────────────────────
8894
if (args.list) {
8995
return listVoices(args.json);
@@ -97,10 +103,8 @@ export default defineCommand({
97103
}
98104

99105
let text: string;
100-
const maybeFile = resolve(input);
101-
102-
if (existsSync(maybeFile) && extname(maybeFile).toLowerCase() === ".txt") {
103-
text = readFileSync(maybeFile, "utf-8").trim();
106+
if (isTextFile(input)) {
107+
text = readFileSync(resolve(input), "utf-8").trim();
104108
if (!text) {
105109
console.error(c.error("File is empty."));
106110
failCommand();

‎packages/cli/src/telemetry/events.test.ts‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1130,6 +1130,25 @@ describe("trackCliError", () => {
11301130
});
11311131

11321132
describe("trackCommandFailure", () => {
1133+
it("reports an extra-positional usage error by count, never the arguments", async () => {
1134+
const { resolveExtraPositionals } = await import("../utils/reject-extra-positionals.js");
1135+
const quiet = vi.spyOn(console, "error").mockImplementation(() => {});
1136+
const cmd = { args: { dir: { type: "positional" } } } as Parameters<
1137+
typeof resolveExtraPositionals
1138+
>[0];
1139+
let thrown: unknown;
1140+
try {
1141+
resolveExtraPositionals(cmd, "render", { _: ["./p", "Jane", "555-0100"] });
1142+
} catch (error) {
1143+
thrown = error;
1144+
}
1145+
quiet.mockRestore();
1146+
trackCommandFailure("render", thrown);
1147+
const payload = JSON.stringify(trackEvent.mock.calls.at(-1));
1148+
expect(payload).toContain("2 unexpected extra arguments for hyperframes render");
1149+
expect(payload).not.toMatch(/Jane|555-0100/);
1150+
});
1151+
11331152
beforeEach(() => {
11341153
trackEvent.mockClear();
11351154
});

0 commit comments

Comments
 (0)