Files
seal-use/src/core/errors.ts
T

135 lines
5.4 KiB
TypeScript

export type CliExitCode = 1 | 2 | 10 | 11 | 12 | 13 | 14;
export class CliError extends Error {
readonly exitCode: CliExitCode;
readonly nextAction?: string;
constructor(message: string, exitCode: CliExitCode, nextAction?: string) {
super(message);
this.name = "CliError";
this.exitCode = exitCode;
this.nextAction = nextAction;
}
}
export class PayloadTooLargeError extends CliError {
constructor(message: string, nextAction?: string) {
super(message, 12, nextAction);
this.name = "PayloadTooLargeError";
}
}
export function usageError(message: string, nextAction?: string): CliError {
return new CliError(message, 2, nextAction);
}
/**
* Local configuration/argument validation failure: the CLI was handed a value
* it cannot use (bad `--env` value, unparseable enterprise file, missing
* required parameter). Distinct from `2` (malformed command line) so callers
* can tell "your command line is wrong" from "your config/input data is wrong".
*/
export function validationError(message: string, nextAction?: string): CliError {
return new CliError(message, 13, nextAction);
}
/**
* Safety gate: the requested action is blocked by an environment guard rather
* than by the caller's input — replaying into production, running a regression
* matrix outside a test tenant. Passing the guard requires changing target or
* setting an explicit override flag.
*/
export function safetyBlocked(message: string, nextAction?: string): CliError {
return new CliError(message, 14, nextAction);
}
export function confirmationRequired(message: string, nextAction: string): CliError {
return new CliError(message, 10, nextAction);
}
/**
* Malformed command line: the invocation itself is wrong (unknown subcommand,
* bad flag value, missing positional). Exit `2` — the caller must retype.
*/
const USAGE_PREFIX =
/^(?:Usage:|Unknown (?:[a-z0-9_-]+ )*(?:command|action|subcommand|target)|Invalid (?:number|boolean|command)|--json must|Missing required JSON field|Invalid JSON:)/i;
// Wording a Chinese-language usage error uses when it names a flag/parameter
// the caller must supply, or rejects a value the caller chose. Exit `13`.
// Deliberately excludes generic recovery verbs like "请先"/"请重试" so post-write
// or upstream failures that offer recovery advice stay at exit `1`.
const CN_USAGE =
/(?:请通过|请指定|参数提供|需要提供|必须提供|缺少合思凭证|模式需要提供|参数。|为必填项|不能使用|无法用于|必须包含|必须为|顶层必须|格式错误|格式不合法|不支持的|未知的|无效的|请改用|请使用 --|请提供)/;
// Enterprise-selection failures: the caller must pass --corp or fix config. Exit `13`.
const CORP_SELECTION =
/^(?:Stateless mode is enabled\.|No enterprise config found|.*requires an authenticated enterprise|.*requires an enterprise\.)/;
// Local file input problems that are the caller's responsibility to fix. Exit `13`.
const LOCAL_FILE_INPUT =
/^(?:File not found:|本地规则文件(?: JSON 解析失败|格式错误|包含重复)|未找到本地规则文件|第 \d+ 条规则(?:格式错误|缺少有效的)|ZIP 根目录缺少|起始时间 .* 不能晚于结束时间)/;
// Safety-guard wording: blocked by target environment, not by input shape. Exit `14`.
const SAFETY_GUARD =
/(?:标记为生产正式环境|非测试环境|严禁在生产环境|禁止向生产环境)/;
export function classifyCliError(error: unknown): {
exitCode: CliExitCode;
nextAction?: string;
} {
if (error instanceof CliError) {
return { exitCode: error.exitCode, nextAction: error.nextAction };
}
const value = error instanceof Error ? error.message : String(error);
const status = responseStatus(error);
if (status === 401 || status === 403 || /(?:^|\s)(?:token|bearer|session) (?:expired|missing|invalid)/i.test(value)) {
return { exitCode: 11 };
}
if (USAGE_PREFIX.test(value)) {
return { exitCode: 2 };
}
if (/^Refusing to (?:clear|delete)|without --yes|without confirm=true/i.test(value)) {
return { exitCode: 10 };
}
if (SAFETY_GUARD.test(value)) {
return { exitCode: 14 };
}
if (CN_USAGE.test(value) || CORP_SELECTION.test(value) || LOCAL_FILE_INPUT.test(value)) {
return { exitCode: 13 };
}
// Structural validation: a ZodError carries an `issues` array rather than a
// message prefix, so it never matches a text pattern.
if (isValidationIssueList(error)) {
return { exitCode: 13 };
}
// JSON.parse failures (unquoted config, truncated file) are SyntaxErrors with
// no stable English wording across runtimes ("JSON Parse error: ..." under
// Bun, "Unexpected token ..." under Node).
if (error instanceof SyntaxError) {
return { exitCode: 13 };
}
return { exitCode: 1 };
}
function isValidationIssueList(error: unknown): boolean {
if (!error || typeof error !== "object") return false;
const issues = (error as { issues?: unknown }).issues;
if (!Array.isArray(issues)) return false;
return issues.every(
(issue) =>
issue &&
typeof issue === "object" &&
"path" in issue &&
"message" in issue
);
}
function responseStatus(error: unknown): number | undefined {
if (!error || typeof error !== "object") return undefined;
const response = (error as { response?: unknown }).response;
if (!response || typeof response !== "object") return undefined;
const status = (response as { status?: unknown }).status;
return typeof status === "number" ? status : undefined;
}