import { getYamlConfigContent, updateYamlConfigContent } from '@ones-open/cli-utils' import { GLOBAL_CLI_PLUGIN_CONFIG_FILE_PATH } from '@ones-open/cli-utils' import type { GlobalCLIPluginConfig, GlobalCLIPluginConfigScope } from '@ones-open/cli-utils' import { merge } from '@senojs/lodash' async function loadScopeMap(scopeConfigPath = GLOBAL_CLI_PLUGIN_CONFIG_FILE_PATH) { try { const { scopes } = await getYamlConfigContent(scopeConfigPath, { enableFileExistsCheck: true, }) const scopeConfigMap = new Map( Object.entries(scopes).map(([scope, scopeConfig]) => [scope, scopeConfig]), ) return scopeConfigMap } catch (error) { return new Map() } } async function getScopeList(scopeConfigMap?: Map) { const mapKeys = scopeConfigMap?.keys() ?? (await loadScopeMap()).keys() return Array.from(mapKeys) } async function getReadableScopeListStr(scopeConfigMap?: Map) { const map = scopeConfigMap ?? (await loadScopeMap()) if (map.size === 0) return undefined const mapValues = [...map.values()] const readableContent = '\nScope list information:' + '\n---------------------------------------------------------------' + `\n${JSON.stringify(mapValues, null, '\t')}` + '\n---------------------------------------------------------------' return readableContent } interface UpdateScopeIntoGlobalPluginConfigOptions { configPath: string strategy: 'merge' | 'replace' } async function updateScopeIntoGlobalPluginConfig( scopeConfigMap: Map, options?: UpdateScopeIntoGlobalPluginConfigOptions, ) { try { const { configPath, strategy } = options ?? { configPath: GLOBAL_CLI_PLUGIN_CONFIG_FILE_PATH, strategy: 'merge', } const rawPluginConfig = await getYamlConfigContent(configPath, { enableFileExistsCheck: true, }) const scopes = Object.fromEntries(scopeConfigMap) let newGlobalPluginConfig: GlobalCLIPluginConfig if (strategy === 'replace') { newGlobalPluginConfig = { ...rawPluginConfig, scopes } } else { const { scopes: rawScopes } = rawPluginConfig const newScopes = merge(rawScopes, scopes) newGlobalPluginConfig = { ...rawPluginConfig, scopes: newScopes } } await updateYamlConfigContent(configPath, newGlobalPluginConfig) } catch (error) { if (error instanceof Error) { error.message = `${error.message}` + `\nThis error message only indicates that the scope cache update failed and does not affect the login result.` + '\nYou can run `npx op init` on root of project to re-initialize the scope cache' throw error } } } export { loadScopeMap, getScopeList, getReadableScopeListStr, updateScopeIntoGlobalPluginConfig }