Add flag metadata to the argv parser: reject unknown flags, fix boolean/value ambiguity

parseArgs decided a flag's kind from whatever token followed it, so
`corps list --all now` fed "now" into --all and crashed with Invalid boolean,
a bare `--limit` was silently dropped (full dataset pull), and `--limitt` was
silently ignored with exit 0.

Add BOOLEAN_FLAGS / VALUE_FLAGS / KNOWN_FLAGS registries derived from how the
code reads each flag (booleanOption vs stringOption/numberOption). Booleans
never consume the next token, value flags must receive one, unknown flags
fail with a did-you-mean suggestion, and the three dual-use flags (f, h,
version) keep the legacy heuristic. parser.test.ts — previously zero tests on
the entry point — locks all of it plus a help.ts cross-check.
This commit is contained in:
gitea committed 2026-09-29 22:04:58 +08:00
1 parent 935ca015b1
commit 68fd90dbda
2 files changed
+339

No files matched your search

+155
View File
@@ -0,0 +1,155 @@
import { describe, expect, test } from "bun:test";
import { readFileSync } from "node:fs";
import { join } from "node:path";
import {
booleanOption,
BOOLEAN_FLAGS,
KNOWN_FLAGS,
numberOption,
parseArgs,
splitOption,
stringOption,
VALUE_FLAGS
} from "./parser.js";
describe("parseArgs flag handling", () => {
test("boolean flags never consume the next token", () => {
// Before the metadata registry, `--all now` fed "now" into --all and
// booleanOption("now") threw `Invalid boolean: now`.
const parsed = parseArgs(["corps", "list", "--all", "now"]);
expect(parsed.options.all).toBe(true);
expect(parsed.command).toEqual(["corps", "list", "now"]);
});
test("boolean flags at the end of argv stay boolean", () => {
expect(parseArgs(["corps", "list", "--all"]).options.all).toBe(true);
});
test("value flags consume exactly one token", () => {
const parsed = parseArgs(["approval-runs", "list", "--limit", "25", "--status", "completed"]);
expect(parsed.options.limit).toBe("25");
expect(parsed.options.status).toBe("completed");
expect(parsed.command).toEqual(["approval-runs", "list"]);
});
test("value flag with a missing value is a usage error, not a silent drop", () => {
// numberOption(true) previously returned undefined, so a bare `--limit`
// silently meant "no limit" and pulled the full dataset.
expect(() => parseArgs(["approval-runs", "list", "--limit"])).toThrow(
"Option --limit requires a value."
);
expect(() => parseArgs(["approval-runs", "list", "--limit", "--status", "completed"])).toThrow(
"Option --limit requires a value."
);
});
test("value flags accept negative numbers as values", () => {
expect(parseArgs(["corps", "search", "x", "--offset", "-5"]).options.offset).toBe("-5");
});
test("unknown flags are rejected with a did-you-mean suggestion", () => {
// `corps list --limitt 5` used to exit 0 while silently ignoring the flag.
expect(() => parseArgs(["corps", "list", "--limitt", "5"])).toThrow(
"Unknown option: --limitt. Did you mean --limit?"
);
expect(() => parseArgs(["corps", "list", "--bogus-flag"])).toThrow(
"Unknown option: --bogus-flag."
);
});
test("kebab and camel spellings of the same flag both stay registered", () => {
const kebab = parseArgs(["corps", "list", "--record-id", "abc"]);
const camel = parseArgs(["corps", "list", "--recordId", "abc"]);
expect(kebab.options["record-id"]).toBe("abc");
expect(camel.options.recordId).toBe("abc");
});
test("the = value form bypasses next-token consumption", () => {
expect(parseArgs(["rules", "get", "--code=0038"]).options.code).toBe("0038");
expect(parseArgs(["corps", "list", "--all=true"]).options.all).toBe("true");
});
test("ambiguous flags (f / h / version) keep the legacy heuristic", () => {
expect(parseArgs(["rules", "lint", "--f", "/tmp/rules.json"]).options.f).toBe("/tmp/rules.json");
expect(parseArgs(["auth", "hose-link", "--f"]).options.f).toBe(true);
expect(parseArgs(["http", "--h", "127.0.0.1"]).options.h).toBe("127.0.0.1");
expect(parseArgs(["corps", "list", "--help"]).options.help).toBe(true);
// Bare --version (no area) must stay boolean: it is the version alias.
expect(parseArgs(["--version"]).options.version).toBe(true);
expect(parseArgs(["--v"]).options.v).toBe(true);
expect(parseArgs(["--V"]).options.V).toBe(true);
// With a value it must consume it: rules/update read --version as a value.
expect(parseArgs(["rules", "get", "--version", "latest"]).options.version).toBe("latest");
});
test("--json still parses its payload and rejects non-objects downstream", () => {
expect(parseArgs(["corps", "add", "--json", '{"name":"Acme"}']).json).toEqual({ name: "Acme" });
expect(() => parseArgs(["corps", "add", "--json"])).toThrow("--json requires a JSON object argument");
expect(() => parseArgs(["corps", "add", "--json", "not-json"])).toThrow("Invalid JSON:");
});
});
describe("option helpers", () => {
test("numberOption rejects non-numeric input", () => {
expect(numberOption("25")).toBe(25);
expect(numberOption(undefined)).toBeUndefined();
expect(() => numberOption("abc")).toThrow("Invalid number: abc");
});
test("booleanOption accepts true/false strings and rejects other values", () => {
expect(booleanOption("true")).toBe(true);
expect(booleanOption("false")).toBe(false);
expect(booleanOption(true)).toBe(true);
expect(() => booleanOption("now")).toThrow("Invalid boolean: now");
});
test("stringOption drops bare booleans so a missing value cannot masquerade", () => {
expect(stringOption("x")).toBe("x");
expect(stringOption(true)).toBeUndefined();
});
test("splitOption trims and drops empty entries", () => {
expect(splitOption("a, b ,,c")).toEqual(["a", "b", "c"]);
expect(splitOption("")).toBeUndefined();
expect(splitOption(true)).toBeUndefined();
});
});
describe("flag registry cross-check", () => {
test("every flag documented in help.ts is registered", () => {
const help = readFileSync(join(import.meta.dirname, "help.ts"), "utf-8");
const documented = new Set(
[...help.matchAll(/flag: "--([a-z][a-z0-9-]*)"/g)].map((match) => match[1]!)
);
for (const flag of documented) {
expect(KNOWN_FLAGS.has(flag)).toBe(true);
}
expect(documented.size).toBeGreaterThanOrEqual(20);
});
test("every flag shown in a help usage line is registered", () => {
const help = readFileSync(join(import.meta.dirname, "help.ts"), "utf-8");
const usageFlags = new Set(
[...help.matchAll(/ --([a-z][a-z0-9-]*)/g)].map((match) => match[1]!)
);
const missing = [...usageFlags].filter((flag) => !KNOWN_FLAGS.has(flag));
expect(missing).toEqual([]);
});
test("boolean and value sets partition the registry apart from the ambiguous three", () => {
// Guards the invariant the parser relies on: no flag may be in both sets.
const both = [...KNOWN_FLAGS].filter(
(flag) => BOOLEAN_FLAGS.has(flag) && VALUE_FLAGS.has(flag)
);
expect(both).toEqual([]);
// The union plus the ambiguous three must cover the whole registry, so a
// flag can never fall through to an unintended branch.
const union = new Set([...BOOLEAN_FLAGS, ...VALUE_FLAGS, "f", "h", "version"]);
expect([...KNOWN_FLAGS].every((flag) => union.has(flag))).toBe(true);
expect(KNOWN_FLAGS.size).toBe(union.size);
});
});
+184
View File
@@ -3,6 +3,131 @@ import type { MaterialPackFilePolicyPatch } from "../domains/seal/material-pack/
import type { ParsedArgs } from "./types.js";
import { usageError } from "./errors.js";
/**
* Flag metadata for argv parsing, derived from how the code reads each flag:
*
* - 74 boolean flags never consume the next token, so
* `corps list --all now` no longer feeds "now" into --all.
* - 207 value flags must consume a value, so a bare `--limit` is a
* usage error instead of being silently dropped.
* - `f` / `h` / `version` are read as boolean in one command and as a value in
* another (force vs file, help vs host, bare --version vs --version latest),
* so they keep the legacy next-token heuristic.
*
* Anything not in KNOWN_FLAGS is rejected as a typo (`--limitt` used to pass
* silently). Add a flag here whenever you add one to a command: the
* cross-check test in parser.test.ts fails when help.ts documents a flag this
* set lacks.
*/
// Read with booleanOption(...) / Boolean(...) / presence check.
export const BOOLEAN_FLAGS = new Set([
"V", "add", "all", "as-hose", "attachments", "auto",
"auto-login", "autoLogin", "bg-save", "changelog", "check", "check-only",
"completed-only", "completedOnly", "confirm", "count", "disable-attachment-cache", "disableAttachmentCache",
"download", "downloads", "dry-run", "dryRun", "elevate-hose", "enabled",
"exclude-deleted", "fail-on-flips", "flow", "force", "full", "help",
"hose", "hose-sso", "hoseSso", "include-deleted", "include-simulation", "include-unchanged",
"includeBridge", "includeSimulation", "includeUnchanged", "local", "no-attachments", "no-flow",
"no-wait", "noWait", "overwrite", "plain", "publish", "quiet",
"r", "recode", "refresh", "reveal", "rotate-secret", "rotateSecret",
"save", "silent", "silent-save", "simulation", "skip-expense-extraction", "skip-invoice-generation",
"skipExpenseExtraction", "skipInvoiceGeneration", "snippet-only", "snippetOnly", "sso", "strict",
"summary", "to-downloads", "toDownloads", "v", "wait", "with-flow",
"workspace", "yes"
]);
// Read with stringOption/numberOption/splitOption(...).
export const VALUE_FLAGS = new Set([
"access-token", "accessToken", "app-key", "app-security", "appKey", "appSecurity",
"base-url", "batch", "batch-id", "batchId", "business-codes", "businessCodes",
"code", "concurrency", "content", "content-file", "content-type", "contentFile",
"contentType", "contextLines", "corp", "corp-id", "corpId", "date",
"dedupe-by", "dedupeBy", "default", "departmentId", "dept", "desc",
"description", "description-file", "descriptionFile", "dir", "doc-id-prefix", "doc-id-suffix",
"docIdPrefix", "docIdSuffix", "document-id", "document-sn", "document-sns", "document-type",
"documentId", "documentLimit", "documentSn", "documentType", "domain", "enable",
"end", "end-date", "end-time", "endDate", "endTime", "env",
"environment", "expire", "expiresIn", "fields", "file", "flow-concurrency",
"flow-ids", "flow-status-list", "flowIds", "flowStatusList", "format", "from",
"from-link", "host", "humanResult", "id", "input", "integration",
"json", "key-id", "keyId", "keyword", "level", "limit",
"lines", "link", "linter", "manual-status", "manualApprovalStatus", "manualStatus",
"max-chars", "maxChars", "maxResults", "min-score", "minScore", "mode",
"n", "name", "note", "o", "offset", "out",
"out-dir", "outDir", "outgoing-result-webhook", "outgoingResultWebhook", "output", "output-file",
"outputFile", "p", "package-id", "package-ids", "packageId", "packageIds",
"path", "phone", "policyId", "poll-interval", "pollInterval", "port",
"prod", "prod-corp", "prodCorp", "purpose", "q", "query",
"record-id", "record-ids", "recordId", "recordIds", "reject-node", "rejectNode",
"repo", "request-ids", "requestIds", "result-url", "resultUrl", "reuse-window",
"reuseWindow", "rule", "rule-id", "ruleId", "ruleVersion", "runtime-id",
"runtimeId", "samples", "scenarios", "schema-config", "schemaConfig", "scope",
"sealUrl", "search", "secret", "selector", "sign-key", "signKey",
"simulationBatchId", "since", "sn", "sn-prefix", "sn-suffix", "snPrefix",
"snSuffix", "sns", "source-corp", "source-system", "sourceCorp", "sourceDocumentId",
"sourceDocumentSN", "sourceSystem", "staff-id", "staff-name", "staff-phone", "staffId",
"staffName", "staffPhone", "start", "start-date", "start-time", "startDate",
"startTime", "state", "status", "strictness", "tag", "tag-id",
"tagId", "tags", "target", "target-corp", "targetCorp", "task-mode",
"taskMode", "template-id", "templateId", "test-corp", "thinking-depth", "thinkingDepth",
"timeout", "timezone", "title", "to", "token", "tokenId",
"type", "until", "url", "userId", "version-name", "versionName",
"webhook", "workflow-type-id", "workflowTypeId"
]);
// Registered flags. Unknown flags are rejected.
export const KNOWN_FLAGS = new Set([
"V", "access-token", "accessToken", "add", "all", "app-key",
"app-security", "appKey", "appSecurity", "as-hose", "attachments", "auto",
"auto-login", "autoLogin", "base-url", "batch", "batch-id", "batchId",
"bg-save", "business-codes", "businessCodes", "changelog", "check", "check-only",
"code", "completed-only", "completedOnly", "concurrency", "confirm", "content",
"content-file", "content-type", "contentFile", "contentType", "contextLines", "corp",
"corp-id", "corpId", "count", "date", "dedupe-by", "dedupeBy",
"default", "departmentId", "dept", "desc", "description", "description-file",
"descriptionFile", "dir", "disable-attachment-cache", "disableAttachmentCache", "doc-id-prefix", "doc-id-suffix",
"docIdPrefix", "docIdSuffix", "document-id", "document-sn", "document-sns", "document-type",
"documentId", "documentLimit", "documentSn", "documentType", "domain", "download",
"downloads", "dry-run", "dryRun", "elevate-hose", "enable", "enabled",
"end", "end-date", "end-time", "endDate", "endTime", "env",
"environment", "exclude-deleted", "expire", "expiresIn", "f", "fail-on-flips",
"fields", "file", "flow", "flow-concurrency", "flow-ids", "flow-status-list",
"flowIds", "flowStatusList", "force", "format", "from", "from-link",
"full", "h", "help", "hose", "hose-sso", "hoseSso",
"host", "humanResult", "id", "include-deleted", "include-simulation", "include-unchanged",
"includeBridge", "includeSimulation", "includeUnchanged", "input", "integration", "json",
"key-id", "keyId", "keyword", "level", "limit", "lines",
"link", "linter", "local", "manual-status", "manualApprovalStatus", "manualStatus",
"max-chars", "maxChars", "maxResults", "min-score", "minScore", "mode",
"n", "name", "no-attachments", "no-flow", "no-wait", "noWait",
"note", "o", "offset", "out", "out-dir", "outDir",
"outgoing-result-webhook", "outgoingResultWebhook", "output", "output-file", "outputFile", "overwrite",
"p", "package-id", "package-ids", "packageId", "packageIds", "path",
"phone", "plain", "policyId", "poll-interval", "pollInterval", "port",
"prod", "prod-corp", "prodCorp", "publish", "purpose", "q",
"query", "quiet", "r", "recode", "record-id", "record-ids",
"recordId", "recordIds", "refresh", "reject-node", "rejectNode", "repo",
"request-ids", "requestIds", "result-url", "resultUrl", "reuse-window", "reuseWindow",
"reveal", "rotate-secret", "rotateSecret", "rule", "rule-id", "ruleId",
"ruleVersion", "runtime-id", "runtimeId", "samples", "save", "scenarios",
"schema-config", "schemaConfig", "scope", "sealUrl", "search", "secret",
"selector", "sign-key", "signKey", "silent", "silent-save", "simulation",
"simulationBatchId", "since", "skip-expense-extraction", "skip-invoice-generation", "skipExpenseExtraction", "skipInvoiceGeneration",
"sn", "sn-prefix", "sn-suffix", "snPrefix", "snSuffix", "snippet-only",
"snippetOnly", "sns", "source-corp", "source-system", "sourceCorp", "sourceDocumentId",
"sourceDocumentSN", "sourceSystem", "sso", "staff-id", "staff-name", "staff-phone",
"staffId", "staffName", "staffPhone", "start", "start-date", "start-time",
"startDate", "startTime", "state", "status", "strict", "strictness",
"summary", "tag", "tag-id", "tagId", "tags", "target",
"target-corp", "targetCorp", "task-mode", "taskMode", "template-id", "templateId",
"test-corp", "thinking-depth", "thinkingDepth", "timeout", "timezone", "title",
"to", "to-downloads", "toDownloads", "token", "tokenId", "type",
"until", "url", "userId", "v", "version", "version-name",
"versionName", "wait", "webhook", "with-flow", "workflow-type-id", "workflowTypeId",
"workspace", "yes"
]);
export function parseArgs(argv: string[]): ParsedArgs {
const command: string[] = [];
const options: Record<string, string | boolean> = {};
@@ -33,6 +158,27 @@ export function parseArgs(argv: string[]): ParsedArgs {
options[key] = val;
continue;
}
if (!KNOWN_FLAGS.has(raw)) {
throw usageError(`Unknown option: --${raw}.${suggestFlag(raw)}`);
}
if (BOOLEAN_FLAGS.has(raw)) {
options[raw] = true;
continue;
}
if (VALUE_FLAGS.has(raw)) {
const next = argv[index + 1];
if (next === undefined || next.startsWith("--") || (next.startsWith("-") && !isNegativeNumber(next))) {
throw usageError(`Option --${raw} requires a value.`);
}
options[raw] = next;
index += 1;
continue;
}
// Ambiguous flag (f / h / version): legacy next-token heuristic.
const next = argv[index + 1];
if (!next || next.startsWith("-")) {
options[raw] = true;
@@ -49,6 +195,44 @@ export function parseArgs(argv: string[]): ParsedArgs {
return { command, options, json };
}
function isNegativeNumber(token: string): boolean {
return /^-\d/.test(token) || /^-\.\d/.test(token);
}
/** Closest registered flag within edit distance 2, for `--limitt` -> `--limit`. */
function suggestFlag(flag: string): string {
let best: string | undefined;
let bestDistance = 3;
for (const candidate of KNOWN_FLAGS) {
const distance = editDistance(flag, candidate);
if (distance < bestDistance) {
bestDistance = distance;
best = candidate;
}
}
return best ? ` Did you mean --${best}?` : "";
}
function editDistance(a: string, b: string): number {
if (a === b) return 0;
const rows = a.length + 1;
const cols = b.length + 1;
const matrix: number[][] = Array.from({ length: rows }, (_, i) =>
Array.from({ length: cols }, (_, j) => (i === 0 ? j : j === 0 ? i : 0))
);
for (let i = 1; i < rows; i += 1) {
for (let j = 1; j < cols; j += 1) {
const cost = a[i - 1] === b[j - 1] ? 0 : 1;
matrix[i]![j] = Math.min(
matrix[i - 1]![j]! + 1,
matrix[i]![j - 1]! + 1,
matrix[i - 1]![j - 1]! + cost
);
}
}
return matrix[rows - 1]![cols - 1]!;
}
export function jsonObject(value: unknown): Record<string, unknown> {
if (value === undefined) return {};
if (!value || typeof value !== "object" || Array.isArray(value)) {