import mkdirp from 'mkdirp'; import fs from 'fs'; import path from 'path'; import { cachedir } from '../utils/util'; import { readJSON } from '../utils/fs.promise'; import { readJSONSync } from 'fs-extra'; /** * 获取配置文件的地址 */ function getCliConfigPath() { return path.join(cachedir(), 'config.json'); } interface CommonConfig { /** * 服务端地址 * @default 'https://ideservice.alipay.com' */ endpoint?: string; /** * 请求代理地址 */ proxy?: string; } interface Config extends CommonConfig { /** * 工具id */ toolId?: string; /** * 工具私钥 */ privateKey?: string; /** * 当前小程序配置 */ mini?: { appId: string; appName: string; }; /** * 当前云服务空间 */ cloud?: { spaceId: string; spaceName: string; }; } // 运行环境, 区分是cli还是sdk方式 let runEnv = 'SDK'; /** * CLI模式下,工具信息配置,使用工具前必须配置 */ export function setCliConfig(options: Config) { const dir = cachedir(); mkdirp.sync(dir); const filePath = getCliConfigPath(); let initConfig; try { const data = fs.readFileSync(filePath, { encoding: 'utf8', }); initConfig = JSON.parse(data); } catch (e) { initConfig = {}; } const data = JSON.stringify( { ...initConfig, ...options, }, function (k, v) { return v; }, 2 ); fs.writeFileSync(filePath, data, { encoding: 'utf8', }); return filePath; } /** * CLI模式下,获取工具的所有配置 */ async function getCliConfig(): Promise { const filePath = getCliConfigPath(); try { const result: Config = await readJSON(filePath); return result; } catch (e) { return {}; } } export function setRunAtCli() { runEnv = 'CLI'; } export function getRunAt() { return runEnv; } interface SDKConfig extends CommonConfig { /** * 工具id */ toolId: string; /** * 工具私钥 */ privateKey: string; } let sdkConfig: SDKConfig = { toolId: '', privateKey: '', }; /** *工具信息配置,使用工具前必须配置 */ export function setConfig(options: SDKConfig) { sdkConfig = options; } /** * 根据运行环境,获取配置 */ export async function getConfigByRunEnv(): Promise { const cliConfig = runEnv === 'CLI' ? await getCliConfig() : { ...sdkConfig, }; return cliConfig; } export function getCliConfigSync(): Config { const filePath = getCliConfigPath(); try { const result: Config = readJSONSync(filePath); return result; } catch (e) { return {}; } } export function getConfigByRunEnvSync(): Config { const cliConfig = runEnv === 'CLI' ? getCliConfigSync() : { ...sdkConfig, }; return cliConfig; }