import { EkbError } from "../core/errors.js"; export type CliExitCode = 1 | 2 | 10 | 11 | 12; 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); } export function confirmationRequired(message: string, nextAction: string): CliError { return new CliError(message, 10, nextAction); } export function classifyCliError(error: unknown): { exitCode: CliExitCode; nextAction?: string; } { if (error instanceof CliError) { return { exitCode: error.exitCode, nextAction: error.nextAction }; } if (error instanceof EkbError) { if (error.code === "NOT_LOGGED_IN" || error.code === "AUTH_FAILED" || error.status === 401) { return { exitCode: 11, nextAction: "hose-use auth login" }; } if (error.code === "VALIDATION_ERROR") { return { exitCode: 2 }; } } 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, nextAction: "hose-use auth login" }; } if (/^(?:Usage:|用法:|未知(?:命令|.*子命令)|缺少|请提供|请指定|Invalid|Missing|required)/i.test(value)) { return { exitCode: 2 }; } if (/without --(?:yes|confirm)|请显式添加 --yes|需要 --(?:yes|confirm)/i.test(value)) { return { exitCode: 10 }; } return { exitCode: 1 }; } 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; }