UNPKG

esa-cli

Version:

A CLI for operating Alibaba Cloud ESA Functions and Pages.

288 lines (287 loc) 11.8 kB
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; import fs, { promises as fsPromises } from 'fs'; import os from 'os'; import path from 'path'; import toml from '@iarna/toml'; import t from '../../i18n/index.js'; import logger from '../../libs/logger.js'; import { getDirName, getRoot } from './base.js'; const __dirname = getDirName(import.meta.url); const root = getRoot(); // Function to get the actual project config file path (supports both .jsonc and .toml) export const getProjectConfigPath = (filePath = root) => { const configFormats = ['esa.jsonc', 'esa.toml']; for (const format of configFormats) { const configPath = path.join(filePath, format); if (fs.existsSync(configPath)) { return configPath; } } // Default to .jsonc if no config file exists return path.join(filePath, 'esa.jsonc'); }; export const projectConfigPath = getProjectConfigPath(); export const cliConfigPath = path.join(os.homedir(), '.esa/config/default.toml'); // Function to get the actual config file path (supports both .toml and .jsonc) export const getCliConfigPath = () => { const configDir = path.join(os.homedir(), '.esa/config'); const jsoncPath = path.join(configDir, 'default.jsonc'); const tomlPath = path.join(configDir, 'default.toml'); // Check if JSONC file exists first, then fallback to TOML if (fs.existsSync(jsoncPath)) { return jsoncPath; } return tomlPath; }; export const hiddenConfigDir = path.join(os.homedir(), '.esa/config'); export const generateHiddenConfigDir = () => { if (!fs.existsSync(hiddenConfigDir)) { fs.mkdirSync(hiddenConfigDir, { recursive: true }); } }; export const generateToml = (path) => { if (!fs.existsSync(path)) { fs.writeFileSync(path, '', 'utf-8'); // Add default endpoint const defaultConfig = { endpoint: 'esa.cn-hangzhou.aliyuncs.com' }; updateCliConfigFile(defaultConfig); } }; export const generateDefaultConfig = () => { generateHiddenConfigDir(); const configPath = getCliConfigPath(); generateToml(configPath); }; export function updateProjectConfigFile(configUpdate_1) { return __awaiter(this, arguments, void 0, function* (configUpdate, filePath = root) { const configPath = getProjectConfigPath(filePath); try { let configFileContent = yield fsPromises.readFile(configPath, 'utf8'); let config; let updatedConfigString; // Detect file format based on file extension if (configPath.endsWith('.jsonc') || configPath.endsWith('.json')) { // Handle JSONC format const jsonContent = configFileContent.replace(/\/\*[\s\S]*?\*\/|\/\/.*$/gm, ''); config = JSON.parse(jsonContent); config = Object.assign(Object.assign({}, config), configUpdate); updatedConfigString = JSON.stringify(config, null, 2) + '\n'; } else { // Handle TOML format (default) config = toml.parse(configFileContent); config = Object.assign(Object.assign({}, config), configUpdate); updatedConfigString = toml.stringify(config); } yield fsPromises.writeFile(configPath, updatedConfigString); } catch (error) { logger.error(`Error updating config file: ${error}`); logger.pathEacces(__dirname); } }); } export function updateCliConfigFile(configUpdate) { return __awaiter(this, void 0, void 0, function* () { try { const configPath = getCliConfigPath(); let configFileContent = yield fsPromises.readFile(configPath, 'utf8'); let config; let updatedConfigString; // Detect file format based on file extension if (configPath.endsWith('.jsonc') || configPath.endsWith('.json')) { // Handle JSONC format const jsonContent = configFileContent.replace(/\/\*[\s\S]*?\*\/|\/\/.*$/gm, ''); config = JSON.parse(jsonContent); config = Object.assign(Object.assign({}, config), configUpdate); updatedConfigString = JSON.stringify(config, null, 2) + '\n'; } else { // Handle TOML format (default) config = toml.parse(configFileContent); config = Object.assign(Object.assign({}, config), configUpdate); updatedConfigString = toml.stringify(config); } yield fsPromises.writeFile(configPath, updatedConfigString); } catch (error) { logger.error(`Error updating config file: ${error}`); logger.pathEacces(__dirname); throw new Error('Config update error'); } }); } export function readConfigFile(configPath) { if (fs.existsSync(configPath)) { const configFileContent = fs.readFileSync(configPath, 'utf-8'); try { if (configPath.endsWith('.jsonc') || configPath.endsWith('.json')) { // Remove comments for JSON parsing const jsonContent = configFileContent.replace(/\/\*[\s\S]*?\*\/|\/\/.*$/gm, ''); const config = JSON.parse(jsonContent); return config; } else { // TOML format const config = toml.parse(configFileContent); return config; } } catch (error) { logger.error(`Error parsing config file: ${error}`); process.exit(1); } } return null; } export function getCliConfig() { const configPath = getCliConfigPath(); const res = readConfigFile(configPath); if (!res) { return null; } return res; } export function getProjectConfig(filePath = root) { // Try to find config file in order of preference: .jsonc, .toml const configFormats = ['esa.jsonc', 'esa.toml']; for (const format of configFormats) { const configPath = path.join(filePath, format); const config = readConfigFile(configPath); if (config) { return config; } } return null; } export function readEdgeRoutineFile(projectPath = root) { const pubFilePath = `.dev/pub.js`; const edgeRoutinePath = path.join(projectPath, pubFilePath); if (fs.existsSync(edgeRoutinePath)) { const edgeRoutineFile = fs.readFileSync(edgeRoutinePath, 'utf-8'); return edgeRoutineFile; } return null; } export function getConfigurations() { try { const [cliConfig, projectConfig] = [getCliConfig(), getProjectConfig()]; return [cliConfig, projectConfig]; } catch (error) { return [null, null]; } } export function generateConfigFile(projectName_1, initConfigs_1, targetDir_1) { return __awaiter(this, arguments, void 0, function* (projectName, initConfigs, targetDir, configFormat = 'jsonc', notFoundStrategy) { var _a, _b; const outputDir = targetDir !== null && targetDir !== void 0 ? targetDir : process.cwd(); const currentDirName = path.basename(outputDir); const entry = (_a = initConfigs === null || initConfigs === void 0 ? void 0 : initConfigs.dev) === null || _a === void 0 ? void 0 : _a.entry; const port = (initConfigs === null || initConfigs === void 0 ? void 0 : initConfigs.port) || 18080; const name = projectName || currentDirName; const assetsDirectory = (_b = initConfigs === null || initConfigs === void 0 ? void 0 : initConfigs.assets) === null || _b === void 0 ? void 0 : _b.directory; let newFilePath; let genConfig; if (configFormat === 'jsonc') { newFilePath = path.join(outputDir, 'esa.jsonc'); const configObj = { name }; if (entry) configObj.entry = entry; if (assetsDirectory) { configObj.assets = { directory: assetsDirectory }; if (notFoundStrategy) { configObj.assets.notFoundStrategy = notFoundStrategy; } } configObj.dev = { port }; genConfig = JSON.stringify(configObj, null, 2) + '\n'; } else { // Default to TOML format newFilePath = path.join(outputDir, 'esa.toml'); const configObj = { name, dev: { port } }; if (entry) configObj.entry = entry; if (assetsDirectory) { configObj.assets = { directory: assetsDirectory }; if (notFoundStrategy) { configObj.assets.notFoundStrategy = notFoundStrategy; } } genConfig = toml.stringify(configObj); } if (fs.existsSync(newFilePath)) { logger.error(`${path.basename(newFilePath)}` + t('generate_config_error').d('already exists')); return; } else { yield fsPromises.writeFile(newFilePath, genConfig, 'utf-8'); } }); } export function getConfigValue(globalValue, configValue, defaultValue) { if (globalValue !== undefined) { return globalValue; } if (configValue !== undefined) { return configValue; } return defaultValue; } export function getDevConf(name, type, defaultValue) { const projectConfig = getProjectConfig(); const configPath = `${type ? type + '.' : ''}${name}`; const userConf = configPath.split('.').reduce((current, key) => { return current && key in current ? current[key] : undefined; }, projectConfig); // @ts-ignore const globalConf = global[name]; return getConfigValue(globalConf, userConf, defaultValue); } export function getDevOpenBrowserUrl() { const port = getDevConf('port', 'dev', 18080); return `http://localhost:${port}`; } export const getApiConfig = () => { var _a, _b; const [cliConfig, projectConfig] = getConfigurations(); let defaultConfig = { auth: { accessKeyId: '', accessKeySecret: '' }, endpoint: `esa.cn-hangzhou.aliyuncs.com` }; const combinedConfig = Object.assign(Object.assign(Object.assign({}, defaultConfig), cliConfig), projectConfig); const config = { auth: { accessKeyId: (_a = combinedConfig.auth) === null || _a === void 0 ? void 0 : _a.accessKeyId, accessKeySecret: (_b = combinedConfig.auth) === null || _b === void 0 ? void 0 : _b.accessKeySecret }, endpoint: combinedConfig.endpoint }; return config; }; export const templateHubPath = path.join(getDirName(import.meta.url), '../../../node_modules/esa-template/src'); export const getTemplatesConfig = () => { const manifestPath = path.join(templateHubPath, 'manifest.json'); const config = JSON.parse(fs.readFileSync(manifestPath, 'utf-8')); return config; };