import type { WebhookMode } from "../domains/seal/types.js"; import type { MaterialPackFilePolicyPatch } from "../domains/seal/material-pack/policy.js"; import type { ParsedArgs } from "./types.js"; import { type DurationToken, EXPIRE_UNITS, expireSeconds, tokenizeDuration } from "../core/duration.js"; import { usageError, validationError } from "../core/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([ "allow-empty", "allowEmpty", "clear", "clear-max-file-size", "clearMaxFileSize", "latest", "show-secret", "showSecret", "V", "add", "all", "allow-unreviewed", "allowUnreviewed", "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", "extract", "extract-expenses", "extractExpenses", "fail-on-flips", "flow", "force", "full", "glossary", "has-input", "has-output", "help", "has-extra-risk", "hasExtraRisk", "hose", "hose-outbound", "hose-sso", "hoseOutbound", "hoseSso", "include-deleted", "include-io-preview", "include-simulation", "include-unchanged", "includeBridge", "includeSimulation", "includeUnchanged", "local", "no-attachments", "no-flow", "no-glossary", "no-wait", "noWait", "outbound", "overwrite", "plain", "publish", "quiet", "r", "raw-json", "rawJson", "recode", "refresh", "refresh-if-missing", "reveal", "rotate-secret", "rotateSecret", "save", "silent", "silent-save", "simulation", "skip-expense-extraction", "skip-extract", "skip-invoice-generation", "skipExpenseExtraction", "skipExtract", "skipInvoiceGeneration", "snippet-only", "snippetOnly", "sso", "strict", "summary", "to-downloads", "toDownloads", "v", "wait", "with-expense-extraction", "withExpenseExtraction", "with-flow", "workspace", "yes" ]); // Read with stringOption/numberOption/splitOption(...). export const VALUE_FLAGS = new Set([ "allowed-extensions", "allowedExtensions", "extensions", "auto-approval-rate", "autoApprovalRate", "approval-rate", "min-file-size", "min-file-size-bytes", "minFileSize", "minFileSizeBytes", "max-file-size", "max-file-size-bytes", "maxFileSize", "maxFileSizeBytes", "templates", "access-token", "accessToken", "action", "add-approver-ids", "addApproverIds", "ai", "ai-accuracy", "aiAccuracy", "app-key", "app-security", "appKey", "appSecurity", "base-url", "batch", "batch-id", "batchId", "both", "both-accurate", "bothAccurate", "business-codes", "businessCodes", "channel", "chrome", "code", "comment", "concurrency", "confirm-code", "confirmCode", "content", "content-file", "content-hints", "content-type", "contentFile", "content-format", "contentFormat", "contentType", "context-chars", "contextLines", "corp", "corp-id", "corpId", "corporation-id", "corporationId", "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", "expires-in", "expiresIn", "fields", "file", "file-id", "file-name", "flow-concurrency", "flow-id", "flow-ids", "flow-status-list", "flowId", "flowIds", "flowStatusList", "format", "from", "from-link", "host", "human", "human-accuracy", "humanAccuracy", "humanResult", "id", "input", "integration", "json", "json-path", "key-id", "keyId", "keyword", "ledger", "level", "limit", "lines", "link", "linter", "manual-status", "manualApprovalStatus", "manualStatus", "max-chars", "max-preview-chars", "maxChars", "maxResults", "max-results", "message-id", "messageId", "metadata", "metadata-key", "min-score", "minScore", "mode", "max-runs", "max-scan", "maxScan", "month", "n", "name", "name-contains", "node-id", "nodeId", "note", "observation-id", "observation-types", "o", "offset", "out", "out-dir", "outDir", "outgoing-result-webhook", "outgoingResultWebhook", "output", "output-file", "outputFile", "p", "package-id", "package-ids", "packageId", "packageIds", "path", "phone", "policy", "policyId", "poll-interval", "pollInterval", "port", "prod", "prod-corp", "prodCorp", "purpose", "q", "query", "record-id", "record-ids", "recordId", "recordIds", "reject-node", "rejectNode", "reject-to", "rejectTo", "rejection-num", "rejectionNum", "reviewed-by", "reviewedBy", "report-id", "repo", "request-ids", "requestIds", "resubmit-method", "resubmitMethod", "result-url", "resultUrl", "reuse-window", "reuseWindow", "rule", "rule-hints", "rule-id", "ruleId", "ruleVersion", "runtime-id", "runtimeId", "samples", "scenarios", "schema-config", "schemaConfig", "scope", "sealUrl", "search", "secret", "selector", "session-id", "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", "template", "taskMode", "template-id", "templateId", "test-corp", "thinking-depth", "thinkingDepth", "timeout", "timezone", "title", "to", "token", "tokenId", "trace-id", "trace-limit", "type", "until", "url", "userId", "version-name", "versionName", "verdict", "webhook", "width", "workflow-type-id", "workflowTypeId" ]); // Registered flags. Unknown flags are rejected. export const KNOWN_FLAGS = new Set([ ...BOOLEAN_FLAGS, ...VALUE_FLAGS, "f", "h", "version" ]); export function parseArgs(argv: string[]): ParsedArgs { const command: string[] = []; const options: Record = {}; let json: unknown; for (let index = 0; index < argv.length; index += 1) { const arg = argv[index]; if (!arg) continue; if (arg === "--json") { const raw = argv[index + 1]; if (!raw) throw usageError("--json requires a JSON object argument"); try { json = JSON.parse(raw); } catch (error) { throw usageError(`Invalid JSON: ${error instanceof Error ? error.message : String(error)}`); } index += 1; continue; } if (arg.startsWith("-")) { const raw = arg.replace(/^-+/, ""); if (raw.includes("=")) { const eqIdx = raw.indexOf("="); const key = raw.slice(0, eqIdx); const val = raw.slice(eqIdx + 1); if (key === "python") throw usageError("--python 已移除:报告工具不再依赖 Python。"); if (!KNOWN_FLAGS.has(key)) { throw usageError(`Unknown option: --${key}.${suggestFlag(key)}`); } 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; } else { options[raw] = next; index += 1; } continue; } command.push(arg); } 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 { if (value === undefined) return {}; if (!value || typeof value !== "object" || Array.isArray(value)) { throw usageError("--json must be an object"); } return value as Record; } export function stringOption(value: string | boolean | undefined): string | undefined { return typeof value === "string" ? value : undefined; } export function numberOption(value: string | boolean | undefined): number | undefined { if (typeof value !== "string") return undefined; const number = Number(value); if (!Number.isFinite(number)) throw usageError(`Invalid number: ${value}`); return number; } export function splitOption(value: string | boolean | undefined): string[] | undefined { if (typeof value !== "string") return undefined; const items = value.split(",").map((item) => item.trim()).filter(Boolean); return items.length ? items : undefined; } export function booleanOption(value: string | boolean | undefined): boolean | undefined { if (value === undefined) return undefined; if (typeof value === "boolean") return value; if (value === "true") return true; if (value === "false") return false; throw usageError(`Invalid boolean: ${value}`); } export function requiredString(input: Record, key: string): string { const value = optionalString(input, key); if (!value) throw usageError(`Missing required JSON field: ${key}`); return value; } export function requiredStringAlias(input: Record, keys: string[]): string { for (const key of keys) { const value = optionalString(input, key); if (value) return value; } throw usageError(`Missing required JSON field: ${keys.join(" or ")}`); } export function optionalString(input: Record, key: string): string | undefined { const value = input[key]; return typeof value === "string" && value.trim() ? value.trim() : undefined; } export function optionalNumber(input: Record, key: string): number | undefined { const value = input[key]; return typeof value === "number" && Number.isFinite(value) ? value : undefined; } export function inferCorpIdFromStaffId(staffId: string): string | undefined { const [corpId] = staffId.split(":", 1); return corpId || undefined; } export function safeFileName(value: string): string { return value.replace(/[^a-zA-Z0-9._-]/g, "_"); } export function parseStateMode(value: string): boolean { const normalized = value.trim().toLowerCase(); if (["stateful", "state", "有状态"].includes(normalized)) return true; if (["stateless", "无状态"].includes(normalized)) return false; throw validationError("Invalid config mode. Use stateful or stateless."); } export function parseRuleVersionSelector(value: string) { if (value === "latest") return { latest: true }; const versionNumber = Number(value); if (Number.isInteger(versionNumber) && versionNumber > 0) { return { versionNumber }; } return { versionId: value }; } export function ruleVersionSearchOptions(value?: string) { if (!value) return {}; const selector = parseRuleVersionSelector(value); if ("latest" in selector) { return { ruleVersionScope: "version", latestRuleVersion: true }; } if ("versionNumber" in selector) { return { ruleVersionScope: "version", ruleVersionNumber: selector.versionNumber }; } return { ruleVersionScope: "version", ruleVersionId: selector.versionId }; } export function ruleVersionContextOptions(value?: string) { if (!value) return {}; const selector = parseRuleVersionSelector(value); if ("latest" in selector) { return { latestRuleVersion: true }; } if ("versionNumber" in selector) { return { ruleVersionNumber: selector.versionNumber }; } return { ruleVersionId: selector.versionId }; } export function ruleVersionGetOptions(value?: string) { if (!value) return {}; const selector = parseRuleVersionSelector(value); if ("latest" in selector) { return { latest: true }; } if ("versionNumber" in selector) { return { versionNumber: selector.versionNumber }; } return { versionId: selector.versionId }; } export function parseWebhookMode(value?: string): WebhookMode | undefined { if (!value) return undefined; const normalized = value.trim().toLowerCase().replace(/[\s-]+/g, "_"); const aliases: Record = { assisted: "assisted", 辅助: "assisted", semi_automatic: "semi_automatic", 半自动: "semi_automatic", fully_automatic: "fully_automatic", 全自动: "fully_automatic" }; const mode = aliases[normalized]; if (!mode) { throw validationError("Invalid Webhook mode. Use assisted, semi_automatic, or fully_automatic"); } return mode; } export function webhookRateOption(options: Record): number | undefined { const value = numberOption( options.autoApprovalRate ?? options["auto-approval-rate"] ?? options["approval-rate"] ); if (value !== undefined && (!Number.isInteger(value) || value < 0 || value > 100)) { throw validationError("Webhook auto approval rate must be an integer between 0 and 100"); } return value; } export function webhookShowSecretOption(options: Record): boolean | undefined { return booleanOption(options.showSecret) ?? booleanOption(options["show-secret"]); } export function materialPackFilePolicyOptions( options: Record ): MaterialPackFilePolicyPatch | undefined { const clearMaxFileSize = booleanOption( options.clearMaxFileSize ?? options["clear-max-file-size"] ) === true; const minFileSizeBytes = numberOption( options.minFileSizeBytes ?? options["min-file-size-bytes"] ?? options.minFileSize ?? options["min-file-size"] ); const maxFileSizeBytes = numberOption( options.maxFileSizeBytes ?? options["max-file-size-bytes"] ?? options.maxFileSize ?? options["max-file-size"] ); const allowedExtensions = splitOption( options.allowedExtensions ?? options["allowed-extensions"] ?? options.extensions ); if ( minFileSizeBytes === undefined && maxFileSizeBytes === undefined && allowedExtensions === undefined && !clearMaxFileSize ) { return undefined; } return { minFileSizeBytes, maxFileSizeBytes: clearMaxFileSize ? null : maxFileSizeBytes, allowedExtensions }; } /** * Read an `--expire` literal through the shared tokenizer, raising the two * usage errors both link flags share. The format hint differs per flag only in * which example it recommends. */ function readExpireToken( value: string | boolean | number, options: { formatHint: string; unitlessHint?: string } ): DurationToken { if (typeof value === "number") { if (!Number.isFinite(value) || value <= 0) { throw usageError( `Invalid --expire: ${value}。必须为大于 0 的有效时长${options.unitlessHint ? `,推荐使用 ${options.unitlessHint}` : ""}。` ); } const token = tokenizeDuration(value, { units: EXPIRE_UNITS }); if (!token) throw usageError(`Invalid --expire: ${value}。`); return token; } if (typeof value !== "string") { throw usageError(`Invalid --expire: ${String(value)}。`); } const token = tokenizeDuration(value, { units: EXPIRE_UNITS }); if (!token) { throw usageError(`Invalid --expire: '${value}'。必须为有效时长格式${options.formatHint}`); } if (token.value <= 0) { throw usageError( `Invalid --expire: '${value}'。必须为大于 0 的有效时长${options.unitlessHint ? `,推荐使用 ${options.unitlessHint}` : ""}。` ); } return token; } export function parseDelegationExpireHours( value: string | boolean | number | undefined, defaultHours = 24 ): number { if (value === undefined || value === null || value === "") { return defaultHours; } const token = readExpireToken(value, { formatHint: ",推荐使用 '7d' 或 '24h'(支持 d/h/m/s 及秒数)", unitlessHint: ",推荐使用 '7d' 或 '24h'" }); // Seal delegation links are hourly and capped at 7 days. const rawHours = expireSeconds(token) / 3600; if (rawHours > 168) { throw usageError( `Invalid --expire: 计算得 ${rawHours > 168.1 ? Math.floor(rawHours) : rawHours} 小时。Seal delegation 授权有效期最多为 7 天 (168h)。建议使用 --expire 7d。` ); } const finalHours = Math.floor(rawHours); if (finalHours < 1) { console.error( `👉 提示: Seal 协助链接按整小时生效(最少 1 小时),输入值 ${String(value)} 已自动保底设置为 1 小时 (1h)。建议后续使用 --expire 1h。` ); return 1; } if (!Number.isInteger(rawHours)) { console.error( `👉 提示: Seal 协助链接按整小时生效,输入值 ${String(value)} 已自动向下取整为 ${finalHours} 小时 (${finalHours}h)。建议后续使用 --expire ${finalHours}h 或 --expire 7d。` ); } return finalHours; } export function parseHoseExpireSeconds( value: string | boolean | number | undefined, defaultSeconds = 7200 ): number { if (value === undefined || value === null || value === "") { return defaultSeconds; } const token = readExpireToken(value, { formatHint: ",推荐使用 '7d' 或 '2h'(支持 d/h/m/s 及秒数)" }); // A bare number is ambiguous: <=168 is read as hours, larger as seconds. if (token.unit === undefined && token.value <= 168) { console.error( `👉 提示: 检测到未加单位的数值 ${token.value},已按 ${token.value} 小时 (${Math.round(token.value * 3600)}s) 自动换算。建议明确使用 --expire ${token.value}h。` ); } const seconds = Math.round(expireSeconds(token)); if (!Number.isFinite(seconds) || seconds <= 0) { throw usageError(`Invalid --expire: 计算得 ${seconds} 秒。必须为大于 0 的有效时长。`); } return seconds; }