Skip to content

Write HTML. Render video. Built for agents.

fix(cli): reject a swallowed --json when catalog's string flags have no value (#3992)

miga-heygen1de8b5ae3360
diff --git a/packages/cli/src/commands/check.test.ts b/packages/cli/src/commands/check.test.ts
index 7415104133..cd6957ca04 100644
--- a/packages/cli/src/commands/check.test.ts
+++ b/packages/cli/src/commands/check.test.ts
@@ -10,6 +10,17 @@ vi.mock("../telemetry/events.js", () => ({
import { contrastRatio, parseColorRGBA } from "./contrast-bg.js";
import { createCheckCommand } from "./check.js";
+import { trackCommandFailures } from "../utils/command-failure-tracking.js";
+import type { CommandDef } from "citty";
+
+// Bare `--frame-check` is rewritten by the wrapCommand gate, so run through cli.ts's wrapping.
+async function runViaCli(
+ command: CommandDef<any>,
+ opts: Parameters<typeof runCommand>[1],
+): Promise<ReturnType<typeof runCommand>> {
+ const wrapped = await trackCommandFailures(() => Promise.resolve(command))();
+ return runCommand(wrapped, opts);
+}
import {
DEFAULT_CHECK_OPTIONS,
checkExitCode,
@@ -375,7 +386,7 @@ it("preserves caption-zone after bare --frame-check", async () => {
withMeta: (value) => value,
});
- await runCommand(command, {
+ await runViaCli(command, {
rawArgs: [
"--frame-check",
"--caption-zone",
@@ -410,7 +421,7 @@ it("preserves --json after bare --frame-check", async () => {
withMeta: (value) => value,
});
- await runCommand(command, {
+ await runViaCli(command, {
rawArgs: ["--snapshots", "--samples", "15", "--frame-check", "--json"],
});
@@ -425,6 +436,44 @@ it("preserves --json after bare --frame-check", async () => {
expect(log).toHaveBeenCalledWith(expect.stringContaining('"ok"'));
});
+it("prints a dash-prefixed --frame-check value's parse failure exactly once, not doubled", async () => {
+ // run()'s own try/catch prints parseFrameCheck's error, so the throw site must not print too.
+ const { report } = await runScenario(fakeDriver());
+ const runPipeline = vi.fn(async (_project: ProjectDir, _options: CheckOptions) => report);
+ const errorLog = vi.spyOn(console, "error").mockImplementation(() => undefined);
+ const command = createCheckCommand({
+ resolveProject: () => PROJECT,
+ runPipeline,
+ withMeta: (value) => value,
+ });
+
+ await runViaCli(command, { rawArgs: ["--frame-check=--json"] });
+
+ expect(runPipeline).not.toHaveBeenCalled();
+ const matching = errorLog.mock.calls.filter(
+ ([arg]) => typeof arg === "string" && arg.includes("Missing value for --frame-check"),
+ );
+ expect(matching).toHaveLength(1);
+});
+
+it("no longer swallows --json after a --layout value (the wider bug class beyond --frame-check)", async () => {
+ const { report } = await runScenario(fakeDriver());
+ const runPipeline = vi.fn(async (_project: ProjectDir, _options: CheckOptions) => report);
+ const log = vi.spyOn(console, "log").mockImplementation(() => undefined);
+ const command = createCheckCommand({
+ resolveProject: () => PROJECT,
+ runPipeline,
+ withMeta: (value) => value,
+ });
+
+ await expect(runViaCli(command, { rawArgs: ["--layout", "--json"] })).rejects.toThrow(
+ /Missing value for --layout/,
+ );
+
+ expect(runPipeline).not.toHaveBeenCalled();
+ expect(log).not.toHaveBeenCalled();
+});
+
it("includes local HDR auto-promotion attribution in --json output", async () => {
const { report } = await runScenario(
fakeDriver(),
@@ -1649,7 +1698,7 @@ describe("frame-check flag grammar", () => {
const { parseFrameCheck } = await import("./check.js");
expect(() => parseFrameCheck("--json")).toThrow(
- 'Invalid --frame-check: value "--json" appears to have swallowed the next option; use --frame-check= or move --frame-check to the end',
+ 'Missing value for --frame-check: value "--json" appears to have swallowed the next option; use --frame-check= or move --frame-check to the end',
);
expect(() => parseFrameCheck("severity")).toThrow("Invalid --frame-check");
});
diff --git a/packages/cli/src/commands/check.ts b/packages/cli/src/commands/check.ts
index 354b01b67e..96ae03c9c5 100644
--- a/packages/cli/src/commands/check.ts
+++ b/packages/cli/src/commands/check.ts
@@ -6,6 +6,7 @@ import { parseAt } from "./layout.js";
import { c } from "../ui/colors.js";
import { normalizeErrorMessage } from "../utils/errorMessage.js";
import { setCommandExitCode } from "../utils/commandResult.js";
+import { swallowedFlagUsageError } from "../utils/reject-unknown-flags.js";
import { formatLayoutIssue } from "../utils/layoutAudit.js";
import { resolveProject, type ProjectDir } from "../utils/project.js";
import { withMeta } from "../utils/updateCheck.js";
@@ -138,7 +139,7 @@ export function createCheckCommand(
},
args: CHECK_COMMAND_ARGS,
async run({ rawArgs }) {
- const args = parseArgs(normalizeFrameCheckRawArgs(rawArgs), CHECK_COMMAND_ARGS);
+ const args = parseArgs(rawArgs, CHECK_COMMAND_ARGS);
const asJson = args.json === true;
try {
@@ -169,14 +170,6 @@ export function createCheckCommand(
});
}
-function normalizeFrameCheckRawArgs(rawArgs: string[]): string[] {
- return rawArgs.map((arg, index) => {
- if (arg !== "--frame-check") return arg;
- const next = rawArgs[index + 1];
- return next === undefined || next.startsWith("-") ? "--frame-check=" : arg;
- });
-}
-
function parseCheckOptions(args: Record<string, unknown>): CheckOptions {
const maxTransitionSamples = positiveInteger(args["max-transition-samples"], 0);
return {
@@ -212,7 +205,7 @@ export function parseFrameCheck(value: unknown): FrameCheckOptions | undefined {
if (value === undefined || value === null || value === false) return undefined;
if (value === true || value === "") return {};
if (typeof value !== "string") throw frameCheckError();
- if (value.startsWith("-")) throw swallowedOptionError("frame-check", value);
+ if (value.startsWith("-")) throw swallowedFlagUsageError("frame-check", value);
const fields = parseFrameCheckFields(value);
const severity = captionSeverity(fields.get("severity"), frameCheckError);
const seek = captionSeeks(fields.get("seek"), frameCheckError);
@@ -247,12 +240,6 @@ function frameCheckError(): Error {
);
}
-function swallowedOptionError(flag: string, value: string): Error {
- return new Error(
- `Invalid --${flag}: value "${value}" appears to have swallowed the next option; use --${flag}= or move --${flag} to the end`,
- );
-}
-
/** Parse `--layout "proseCoverageFloor=0.05"` (semicolon-separated key=value, like caption-zone). */
export function parseLayout(value: unknown): LayoutOptions | undefined {
if (value === undefined || value === null || value === false) return undefined;
diff --git a/packages/cli/src/commands/init.test.ts b/packages/cli/src/commands/init.test.ts
index 0eb27cbf52..5012febad1 100644
--- a/packages/cli/src/commands/init.test.ts
+++ b/packages/cli/src/commands/init.test.ts
@@ -92,7 +92,7 @@ describe("hyperframes init flag rename", () => {
try {
const res = runInit([target, "--example", "--non-interactive"]);
expect(res.status).toBe(1);
- expect(res.stderr).toContain("--example requires a value");
+ expect(res.stderr).toContain("Missing value for --example");
expect(existsSync(target)).toBe(false);
} finally {
rmSync(dir, { recursive: true, force: true });
diff --git a/packages/cli/src/commands/init.ts b/packages/cli/src/commands/init.ts
index 2841470777..055b5aafd6 100644
--- a/packages/cli/src/commands/init.ts
+++ b/packages/cli/src/commands/init.ts
@@ -777,10 +777,6 @@ export default defineCommand({
failCommand();
}
const exampleFlag = args.example;
- if (exampleFlag?.startsWith("-")) {
- console.error(c.error(`--example requires a value; received flag "${exampleFlag}" instead.`));
- failCommand();
- }
const videoFlag = args.video;
const audioFlag = args.audio;
const skipTranscribe = args["skip-transcribe"] === true;
diff --git a/packages/cli/src/utils/command-failure-tracking.ts b/packages/cli/src/utils/command-failure-tracking.ts
index 6773ab0caf..6e7eada554 100644
--- a/packages/cli/src/utils/command-failure-tracking.ts
+++ b/packages/cli/src/utils/command-failure-tracking.ts
@@ -1,6 +1,7 @@
-import type { CommandDef } from "citty";
+import { parseArgs } from "citty";
+import type { ArgsDef, CommandContext, CommandDef } from "citty";
import { resolveExtraPositionals } from "./reject-extra-positionals.js";
-import { assertKnownFlags } from "./reject-unknown-flags.js";
+import { assertKnownFlags, guardSwallowedFlagValues } from "./reject-unknown-flags.js";
// citty types subcommands as `CommandDef<any>` (SubCommandsDef); mirror that so
// each command's specific args type is accepted without per-command generics.
@@ -59,7 +60,7 @@ function wrapCommand(cmd: AnyCommandDef, path: string): AnyCommandDef {
cmd.subCommands != null &&
firstPositional != null &&
Object.prototype.hasOwnProperty.call(cmd.subCommands, firstPositional);
- if (!delegatesToSub) assertKnownFlags(cmd, rawArgs);
+ if (!delegatesToSub) guardLeafFlags(cmd, path, ctx, rawArgs);
// Groups read `args._[0]` to pick fallback help, so only leaves get the count check.
if (!cmd.subCommands) resolveExtraPositionals(cmd, path, ctx?.args);
return await run(ctx);
@@ -80,6 +81,20 @@ function wrapCommand(cmd: AnyCommandDef, path: string): AnyCommandDef {
return wrapped;
}
+// citty built ctx.args before this ran; re-parse when the swallow guard rewrites rawArgs.
+function guardLeafFlags(
+ cmd: AnyCommandDef,
+ path: string,
+ ctx: CommandContext<any>,
+ rawArgs: string[],
+): void {
+ assertKnownFlags(cmd, rawArgs);
+ const guarded = guardSwallowedFlagValues(cmd, path, rawArgs);
+ if (!guarded.rewritten) return;
+ ctx.rawArgs = guarded.rawArgs;
+ ctx.args = parseArgs(guarded.rawArgs, (cmd.args ?? {}) as ArgsDef);
+}
+
/**
* Report a command failure to telemetry, loading the telemetry module on demand
* (keeps it off the CLI cold-start path) and awaiting it so the event is
diff --git a/packages/cli/src/utils/reject-unknown-flags.test.ts b/packages/cli/src/utils/reject-unknown-flags.test.ts
index 09dd114e7e..c3f544f671 100644
--- a/packages/cli/src/utils/reject-unknown-flags.test.ts
+++ b/packages/cli/src/utils/reject-unknown-flags.test.ts
@@ -1,6 +1,18 @@
-import { describe, expect, it } from "vitest";
+import { describe, expect, it, vi } from "vitest";
+import { runCommand } from "citty";
import type { ArgsDef, CommandDef } from "citty";
-import { assertKnownFlags } from "./reject-unknown-flags.js";
+import { spawnSync } from "node:child_process";
+import { fileURLToPath } from "node:url";
+import { resolve } from "node:path";
+import { assertKnownFlags, guardSwallowedFlagValues } from "./reject-unknown-flags.js";
+import { trackCommandFailures } from "./command-failure-tracking.js";
+
+// Spawns the real CLI under bun (like init.test.ts's runInit) to measure literal stdout bytes.
+const cliEntry = resolve(fileURLToPath(import.meta.url), "..", "..", "cli.ts");
+function runCli(args: string[]): { status: number; stdout: string; stderr: string } {
+ const res = spawnSync("bun", ["run", cliEntry, ...args], { encoding: "utf-8", timeout: 30_000 });
+ return { status: res.status ?? -1, stdout: res.stdout, stderr: res.stderr };
+}
const cmd = {
args: {
@@ -50,3 +62,180 @@ describe("assertKnownFlags", () => {
expect(ok(["-ox"])).toThrow(/Unknown flag: -x/); // x unknown
});
});
+
+describe("guardSwallowedFlagValues", () => {
+ const guard = (raw: string[]) => () => guardSwallowedFlagValues(cmd, "render", raw);
+
+ it("rejects a string flag's value that is itself a known flag spelling (default: throw)", () => {
+ expect(guard(["--output", "--json"])).toThrow(/Missing value for --output/);
+ expect(guard(["--output", "--help"])).toThrow(/Missing value for --output/);
+ });
+
+ it("tells a value-taking flag to pass a value, not to move it to the end", () => {
+ expect(guard(["--output", "--json"])).toThrow(/pass one: --output <value> or --output=<value>/);
+ });
+
+ it("does not reject a trailing --no-<flag> negation, which citty never swallows", () => {
+ expect(guard(["--output", "--no-docker"])).not.toThrow();
+ });
+
+ it("looks past --no-<flag> negations, which citty drops before parsing", () => {
+ expect(guard(["--output", "--no-docker", "--json"])).toThrow(/value "--json"/);
+ });
+
+ it("rewrites a bare opted-in flag followed by a --no-<flag> negation", () => {
+ const checkCmd = { args: { "frame-check": { type: "string" }, json: { type: "boolean" } } };
+ const raw = ["--frame-check", "--no-json", "dir"];
+ const result = guardSwallowedFlagValues(checkCmd as never, "check", raw);
+ expect(result).toEqual({ rawArgs: ["--frame-check=", "--no-json", "dir"], rewritten: true });
+ });
+
+ it("accepts the equals form even when the inline value looks like a flag", () => {
+ expect(guard(["--output=--json"])).not.toThrow();
+ expect(guardSwallowedFlagValues(cmd, "render", ["--output=--json"])).toEqual({
+ rawArgs: ["--output=--json"],
+ rewritten: false,
+ });
+ });
+
+ it("does not reject an ordinary value, even one that starts with a dash but isn't a known flag", () => {
+ expect(guard(["--output", "-out.mp4"])).not.toThrow();
+ });
+
+ it("does not reject a trailing bare string flag with nothing after it", () => {
+ expect(guard(["--output"])).not.toThrow();
+ });
+
+ it("does not reject boolean-typed args, even if the next token looks flag-shaped", () => {
+ expect(guard(["--docker", "--json"])).not.toThrow();
+ });
+
+ it("rejects with corrected wording when '--' ends option parsing right after the flag", () => {
+ const message = () => {
+ try {
+ guardSwallowedFlagValues(cmd, "render", ["--output", "--", "--json"]);
+ return undefined;
+ } catch (error) {
+ return (error as Error).message;
+ }
+ };
+ expect(message()).toMatch(/Missing value for --output: "--" ends option parsing here/);
+ expect(message()).not.toMatch(/which is itself a flag/);
+ });
+
+ it("rewrites an opted-in command+flag to the equals form instead of throwing", () => {
+ const checkCmd: CommandDef<any> = {
+ meta: { name: "check" },
+ args: { "frame-check": { type: "string" }, json: { type: "boolean" } },
+ };
+ const result = guardSwallowedFlagValues(checkCmd, "check", ["--frame-check", "--json"]);
+ expect(result).toEqual({ rawArgs: ["--frame-check=", "--json"], rewritten: true });
+ });
+
+ it("scopes the opt-in by command path, not the leaf's short name", () => {
+ const otherCmd: CommandDef<any> = {
+ meta: { name: "check" },
+ args: { "frame-check": { type: "string" }, json: { type: "boolean" } },
+ };
+ expect(() =>
+ guardSwallowedFlagValues(otherCmd, "skills check", ["--frame-check", "--json"]),
+ ).toThrow(/Missing value for --frame-check/);
+ });
+
+ it("ignores an opted-out command+flag entirely, leaving rawArgs untouched for its own recovery logic", async () => {
+ const upgradeCommand = (await import("../commands/upgrade.js")).default as CommandDef<any>;
+ const result = guardSwallowedFlagValues(upgradeCommand, "upgrade", ["--project", "--check"]);
+ expect(result).toEqual({ rawArgs: ["--project", "--check"], rewritten: false });
+ });
+});
+
+// Wraps `cmd` like cli.ts does, so wrapCommand's gate runs before citty's runCommand.
+const wrapTestCommand = (cmd: CommandDef<any>) =>
+ trackCommandFailures(() => Promise.resolve(cmd))();
+
+describe("guardSwallowedFlagValues end-to-end (via citty's real runCommand + the real wrapCommand gate)", () => {
+ it("rejects the exact reported repro: `catalog --query --json`, before catalog's own run() executes", async () => {
+ const catalogCommand = (await import("../commands/catalog.js")).default as CommandDef<any>;
+ const wrapped = await wrapTestCommand(catalogCommand);
+ await expect(runCommand(wrapped, { rawArgs: ["--query", "--json"] })).rejects.toThrow(
+ /Missing value for --query/,
+ );
+ });
+
+ it("accepts the equals form and rejects the space-separated swallow, both through the real pipeline", async () => {
+ let capturedArgs: Record<string, unknown> | undefined;
+ const testCommand: CommandDef<any> = {
+ meta: { name: "test-cmd" },
+ args: { query: { type: "string" }, json: { type: "boolean" } },
+ run: ({ args }) => {
+ capturedArgs = args;
+ },
+ };
+ const wrapped = await wrapTestCommand(testCommand);
+
+ await runCommand(wrapped, { rawArgs: ["--query=--json", "--json"] });
+ expect(capturedArgs).toEqual(expect.objectContaining({ query: "--json", json: true }));
+
+ capturedArgs = undefined;
+ await expect(runCommand(wrapped, { rawArgs: ["--query", "--json"] })).rejects.toThrow(
+ /Missing value for --query/,
+ );
+ expect(capturedArgs).toBeUndefined();
+ });
+
+ it("rewrites correctly with a positional argument ahead of the flags (check's own opt-in)", async () => {
+ let capturedArgs: Record<string, unknown> | undefined;
+ const testCommand: CommandDef<any> = {
+ meta: { name: "check" },
+ args: {
+ dir: { type: "positional" },
+ "frame-check": { type: "string" },
+ json: { type: "boolean" },
+ },
+ run: ({ args }) => {
+ capturedArgs = args;
+ },
+ };
+ const wrapped = await wrapTestCommand(testCommand);
+
+ await runCommand(wrapped, { rawArgs: ["some-dir", "--frame-check", "--json"] });
+ expect(capturedArgs).toEqual(
+ expect.objectContaining({ "frame-check": "", json: true, _: ["some-dir"] }),
+ );
+ });
+
+ it("passes a nested command's full path, so `skills check` does not inherit check's rewrite", async () => {
+ const leaf: CommandDef<any> = {
+ meta: { name: "check" },
+ args: { "frame-check": { type: "string" }, json: { type: "boolean" } },
+ run: () => {},
+ };
+ const group: CommandDef<any> = { meta: { name: "skills" }, subCommands: { check: leaf } };
+ const wrapped = await wrapTestCommand(group);
+ await expect(
+ runCommand(wrapped, { rawArgs: ["check", "--frame-check", "--json"] }),
+ ).rejects.toThrow(/Missing value for --frame-check/);
+ });
+
+ it("throws with `presented: true` so cli.ts's executeCli does not ALSO dump full command usage to stdout", async () => {
+ // `presented` keeps executeCli from dumping usage to stdout; the spawn test below checks bytes.
+ const catalogCommand = (await import("../commands/catalog.js")).default as CommandDef<any>;
+ const wrapped = await wrapTestCommand(catalogCommand);
+ const errorLog = vi.spyOn(console, "error").mockImplementation(() => {});
+ try {
+ await expect(runCommand(wrapped, { rawArgs: ["--query", "--json"] })).rejects.toMatchObject({
+ result: { presented: true },
+ });
+ expect(errorLog).toHaveBeenCalledWith(expect.stringContaining("Missing value for --query"));
+ } finally {
+ errorLog.mockRestore();
+ }
+ });
+
+ it("leaves stdout genuinely empty on the real built CLI, not just presented:true internally", () => {
+ const res = runCli(["catalog", "--query", "--json"]);
+ expect(res.status).toBe(1);
+ expect(res.stderr).toContain("Missing value for --query");
+ expect(res.stdout).toBe("");
+ });
+});
diff --git a/packages/cli/src/utils/reject-unknown-flags.ts b/packages/cli/src/utils/reject-unknown-flags.ts
index e8007b879b..a4392644cf 100644
--- a/packages/cli/src/utils/reject-unknown-flags.ts
+++ b/packages/cli/src/utils/reject-unknown-flags.ts
@@ -1,4 +1,6 @@
-import type { ArgsDef, CommandDef } from "citty";
+import type { ArgDef, ArgsDef, CommandDef } from "citty";
+import { CliUsageError } from "./commandResult.js";
+import { c } from "../ui/colors.js";
// citty is permissive: an unrecognized flag (e.g. `render --out x` when the flag
// is `--output`/`-o`) is silently ignored instead of rejected, so the value is
@@ -16,13 +18,18 @@ function nameVariants(name: string): string[] {
return [name, kebab, camel];
}
+// Every spelling of one declared arg: name variants plus aliases. `def` may be undefined.
+function* spellingsOf(name: string, def: ArgDef | undefined): Generator<string> {
+ yield* nameVariants(name);
+ const alias = def && "alias" in def ? def.alias : undefined;
+ if (typeof alias === "string") yield alias;
+ else if (Array.isArray(alias)) yield* alias;
+}
+
function knownFlags(args: ArgsDef | undefined): Set<string> {
const known = new Set(ALWAYS_KNOWN);
for (const [name, def] of Object.entries(args ?? {})) {
- for (const v of nameVariants(name)) known.add(v);
- const alias = (def as { alias?: string | string[] })?.alias;
- if (typeof alias === "string") known.add(alias);
- else if (Array.isArray(alias)) for (const a of alias) known.add(a);
+ for (const s of spellingsOf(name, def)) known.add(s);
}
return known;
}
@@ -67,3 +74,122 @@ export function assertKnownFlags(cmd: CommandDef<ArgsDef>, rawArgs: string[]): v
if (bad) throw new Error(`Unknown flag: ${bad}`);
}
}
+
+// Spellings of a command's own string/enum args (the types citty lets swallow the next
+// token), mapped to the canonical arg name. Args in `ignore` are left out.
+function stringValueFlagOwners(
+ args: ArgsDef | undefined,
+ ignore: ReadonlySet<string> | undefined,
+): Map<string, string> {
+ const owners = new Map<string, string>();
+ for (const [name, def] of Object.entries(args ?? {})) {
+ if (def?.type !== "string" && def?.type !== "enum") continue;
+ if (ignore?.has(name)) continue;
+ for (const s of spellingsOf(name, def)) owners.set(s, name);
+ }
+ return owners;
+}
+
+// `--flag` -> "flag", `-f` -> "f"; null for `--flag=value` or a non-flag token.
+function ownableFlagSpelling(tok: string): string | null {
+ if (tok.includes("=")) return null;
+ if (tok.startsWith("--")) return tok.slice(2);
+ if (tok.length === 2 && tok.startsWith("-")) return tok.slice(1);
+ return null;
+}
+
+// Keyed by command path. "rewrite": bare flag becomes `--flag=` (check's parseFrameCheck reads
+// that as defaults). "ignore": the command recovers the swallowed value itself
+// (upgrade's resolveProjectArgs).
+const SWALLOW_REWRITE_FLAGS: Readonly<Record<string, ReadonlySet<string>>> = {
+ check: new Set(["frame-check"]),
+};
+const SWALLOW_IGNORE_FLAGS: Readonly<Record<string, ReadonlySet<string>>> = {
+ upgrade: new Set(["project"]),
+};
+
+function swallowedValueMessage(flagName: string, next: string, hint: string): string {
+ if (next === "--")
+ return `Missing value for --${flagName}: "--" ends option parsing here; ${hint}`;
+ return `Missing value for --${flagName}: value "${next}" appears to have swallowed the next option; ${hint}`;
+}
+
+/** For a caller whose own try/catch prints the error (check.ts's run()). */
+export function swallowedFlagUsageError(flagName: string, next: string): CliUsageError {
+ const hint = `use --${flagName}= or move --${flagName} to the end`;
+ return new CliUsageError(swallowedValueMessage(flagName, next, hint));
+}
+
+// Prints and marks `presented`: otherwise executeCli dumps usage to stdout, breaking `--json`.
+function throwSwallowedFlagError(flagName: string, next: string): never {
+ const hint = `pass one: --${flagName} <value> or --${flagName}=<value>`;
+ const message = swallowedValueMessage(flagName, next, hint);
+ console.error(c.error(message));
+ throw new CliUsageError(message, { presented: true });
+}
+
+export interface SwallowGuardResult {
+ rawArgs: string[];
+ rewritten: boolean;
+}
+
+// End of argv and a bare `-` (stdin) are never a swallow; `--` or a known flag spelling is.
+function looksLikeSwallowedFlag(next: string | undefined, known: Set<string>): boolean {
+ if (next === undefined || next === "-") return false;
+ return next === "--" || (next.startsWith("-") && unknownFlagIn(next, known) === null);
+}
+
+// The arg `tok` spells when citty would swallow `next` as its value, else undefined.
+function swallowingArgName(
+ tok: string,
+ next: string | undefined,
+ owners: Map<string, string>,
+ known: Set<string>,
+): string | undefined {
+ const spelling = ownableFlagSpelling(tok);
+ const ownerArgName = spelling ? owners.get(spelling) : undefined;
+ return ownerArgName && looksLikeSwallowedFlag(next, known) ? ownerArgName : undefined;
+}
+
+// A rewrite flag directly followed by `--no-x` is bare too (check's `--frame-check --no-browser-gpu`).
+function rewriteArgName(
+ tok: string,
+ after: string | undefined,
+ owners: Map<string, string>,
+ rewriteFlags: ReadonlySet<string> | undefined,
+): string | undefined {
+ if (!after?.startsWith("--no-")) return undefined;
+ const spelling = ownableFlagSpelling(tok);
+ const name = spelling ? owners.get(spelling) : undefined;
+ return name && rewriteFlags?.has(name) ? name : undefined;
+}
+
+// Reject a string/enum flag whose value citty swallowed from the next flag (`catalog --query --json`).
+// Scans rawArgs: parsed args cannot tell `--query --json` from the legitimate `--query=--json`.
+export function guardSwallowedFlagValues(
+ // `CommandDef<any>`: citty's CommandContext is invariant in its args type.
+ cmd: CommandDef<any> | undefined,
+ path: string,
+ rawArgs: string[],
+): SwallowGuardResult {
+ if (!Array.isArray(rawArgs)) return { rawArgs, rewritten: false };
+ const rawDef = cmd?.args;
+ const argsDef = rawDef && typeof rawDef === "object" ? (rawDef as ArgsDef) : undefined;
+ const known = knownFlags(argsDef);
+ const owners = stringValueFlagOwners(argsDef, SWALLOW_IGNORE_FLAGS[path]);
+ const rewriteFlags = SWALLOW_REWRITE_FLAGS[path];
+
+ let out: string[] | undefined;
+ for (const [i, tok] of rawArgs.entries()) {
+ if (tok === "--") break;
+ // citty drops every `--no-x` before parsing, so the token after them is what gets swallowed.
+ const next = rawArgs.slice(i + 1).find((t) => !t.startsWith("--no-"));
+ const ownerArgName = swallowingArgName(tok, next, owners, known);
+ const rewrite = rewriteArgName(tok, rawArgs[i + 1], owners, rewriteFlags) ?? ownerArgName;
+ if (!rewrite) continue;
+ if (!rewriteFlags?.has(rewrite)) throwSwallowedFlagError(rewrite, next as string);
+ out ??= rawArgs.slice();
+ out[i] = `${tok}=`;
+ }
+ return { rawArgs: out ?? rawArgs, rewritten: out !== undefined };
+}