import { findCorpConfigFile, loadCorpConfigs, loadGlobalConfig, saveGlobalConfig, updateCorpConfig } from "../../../core/config/loader.js"; import { filterCorpsFuzzy } from "../../../core/corp-search/rank.js"; import { getRecentCorpUsageScores, sortCorpsByUsageAndRecency } from "../../../core/stats/usage-tracker.js"; import type { CorpEnvironment } from "../../../core/config/types.js"; import { selectCorp } from "../../helpers.js"; import { confirmationRequired, usageError } from "../../../core/errors.js"; import { booleanOption, numberOption, stringOption } from "../../parser.js"; import { printJson } from "../../printer.js"; import type { ParsedArgs } from "../../types.js"; import { formatSafeSourceDetail, resolveCorpSealUrl } from "./shared.js"; export async function handleCorpOverview( action: string | undefined, maybeName: string | undefined, args: ParsedArgs ): Promise { if (!action || action === "list" || action === "search" || action === "find") { const rawQuery = ( maybeName ?? stringOption(args.options.query) ?? stringOption(args.options.q) )?.trim(); const isStrict = booleanOption(args.options.strict) === true; const envFilter = ( stringOption(args.options.env) ?? stringOption(args.options.environment) )?.trim().toLowerCase(); if ((action === "search" || action === "find") && !rawQuery && !envFilter) { throw usageError("Usage: seal-use corps search [--env ] [--strict]"); } const corpId = stringOption(args.options.corp); const allCorps = loadCorpConfigs(); const globalConfig = loadGlobalConfig(); const currentCorpId = corpId ?? ( globalConfig.stateful ? globalConfig.defaultCorpId ?? allCorps[0]?.id : undefined ); let filtered = allCorps; if (envFilter) { filtered = filtered.filter((item) => (item.environment ?? "production").toLowerCase() === envFilter); } if (rawQuery) { // Equal-relevance results are ordered by recent usage so frequent corps // surface on ties without ever beating a better match. const usageScores = getRecentCorpUsageScores(filtered.map((item) => item.id)); filtered = filterCorpsFuzzy(filtered, rawQuery, { strict: isStrict }, usageScores); } if (allCorps.length === 0) { console.error("提示:当前未检测到企业配置。你可以使用 seal-use corps add-hose-persistent、add-hose-web-session 或 add-seal-bearer 添加企业,或运行 seal-use help 查看说明。"); } else if (isStrict && filtered.length === 0 && (action === "search" || action === "find") && rawQuery) { console.error(`提示:未在严格模式下匹配到企业 "${rawQuery}"。可以尝试省略 --strict 进行智能软搜索。`); } // Search results are already ranked by match confidence. Usage sorting is // useful for an unfiltered list, but would otherwise discard relevance // ordering for a query. const sorted = rawQuery ? filtered : sortCorpsByUsageAndRecency(filtered, currentCorpId); const isList = !action || action === "list"; const isAll = booleanOption(args.options.all) === true; const limitOpt = numberOption(args.options.limit); const defaultLimit = 10; const effectiveLimit = limitOpt !== undefined ? Math.max(1, limitOpt) : (isList && !isAll ? defaultLimit : undefined); let displayList = sorted; if (effectiveLimit !== undefined && sorted.length > effectiveLimit) { displayList = sorted.slice(0, effectiveLimit); if (isList && !isAll && limitOpt === undefined) { console.error( `ℹ️ 当前共有 ${sorted.length} 家企业,已按最近 7 天使用频次展示前 ${effectiveLimit} 家。\n` + `👉 查看全部请添加: seal-use corps list --all\n` + `👉 检索指定企业请使用: seal-use corps search ` ); } } printJson(displayList.map((item) => ({ id: item.id, name: item.name, environment: item.environment ?? "production", sourceType: item.source.type, provider: (item.source as any).provider ?? item.source.type, staffId: item.source.staffId, testCorpId: item.testCorpId, prodCorpId: item.prodCorpId, current: item.id === currentCorpId }))); return true; } if (action === "get" || action === "show") { const targetCorpId = maybeName ?? stringOption(args.options.corp); if (!targetCorpId) { throw usageError("Usage: seal-use corps get "); } const corp = selectCorp(targetCorpId); const configFile = findCorpConfigFile(corp.id); const sealUrl = resolveCorpSealUrl(corp); printJson({ id: corp.id, name: corp.name, environment: corp.environment ?? "production", configFile, seal: { url: sealUrl, tenantSlug: corp.seal.tenantSlug ?? (corp.source as any).tenantSlug, customHeaderNames: corp.seal.headers ? Object.keys(corp.seal.headers) : [], customCookieNames: corp.seal.cookies ? Object.keys(corp.seal.cookies) : [], endpoints: corp.seal.endpoints }, source: formatSafeSourceDetail(corp.source), relations: { testCorpId: corp.testCorpId, prodCorpId: corp.prodCorpId }, auth: { refreshTtl: corp.auth.refreshTtl } }); return true; } if (action === "current") { const corp = selectCorp(stringOption(args.options.corp)); printJson({ id: corp.id, name: corp.name, environment: corp.environment ?? "production", sourceType: corp.source.type, provider: (corp.source as any).provider ?? corp.source.type, staffId: corp.source.staffId, testCorpId: corp.testCorpId, prodCorpId: corp.prodCorpId }); return true; } if (action === "mark" || action === "mark-test" || action === "mark-prod") { const corpId = maybeName ?? stringOption(args.options.corp); if (!corpId) { throw usageError("Usage: seal-use corps mark --env [--confirm]"); } const corp = selectCorp(corpId); const targetEnv = ( action === "mark-test" ? "test" : action === "mark-prod" ? "production" : (stringOption(args.options.env) ?? stringOption(args.options.environment)) ) as CorpEnvironment | undefined; if (targetEnv !== "production" && targetEnv !== "test") { throw usageError("Usage: seal-use corps mark --env [--confirm]"); } const confirmed = booleanOption(args.options.confirm) === true || booleanOption(args.options.yes) === true; if (!confirmed) { throw confirmationRequired( `Refusing to change environment tag of enterprise '${corp.name}' (${corp.id}) to '${targetEnv}' without --confirm. Marking alters synchronization safety guards.`, `seal-use corps mark ${corp.id} --env ${targetEnv} --confirm` ); } const updated = updateCorpConfig(corp.id, { environment: targetEnv }); printJson({ id: updated.id, name: updated.name, environment: updated.environment, testCorpId: updated.testCorpId, prodCorpId: updated.prodCorpId }); return true; } if (action === "rename") { const targetCorpId = maybeName ?? stringOption(args.options.corp) ?? stringOption(args.options.id); const newName = stringOption(args.options.name) ?? stringOption(args.options.to) ?? (args.command[3] && !args.command[3].startsWith("-") ? args.command[3] : undefined); if (!targetCorpId || !newName) { throw usageError("Usage: seal-use corps rename --name "); } const corp = selectCorp(targetCorpId); const updated = updateCorpConfig(corp.id, { name: newName }); printJson({ success: true, id: updated.id, name: updated.name, previousName: corp.name }); return true; } if (action === "switch") { const corpId = maybeName; if (!corpId) throw usageError("Usage: seal-use corps switch "); const globalConfig = loadGlobalConfig(); if (!globalConfig.stateful) { throw new Error( "Cannot switch the default enterprise while stateless mode is enabled. " + "Use `seal-use config mode stateful` first." ); } const corp = selectCorp(corpId); saveGlobalConfig({ ...globalConfig, stateful: true, defaultCorpId: corp.id }); printJson({ current: true, id: corp.id, name: corp.name }); return true; } return false; }