esa-cli 0.0.2-beta.8 → 0.0.2-beta.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -9,13 +9,11 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
9
9
  };
10
10
  import { getProjectConfig, readEdgeRoutineFile } from '../../utils/fileUtils/index.js';
11
11
  import { checkDirectory, checkIsLoginSuccess } from '../utils.js';
12
- import { displaySelectSpec } from '../deploy/index.js';
13
12
  import { descriptionInput } from '../../components/descriptionInput.js';
14
13
  import { ApiService } from '../../libs/apiService.js';
15
14
  import prodBuild from './prodBuild.js';
16
15
  import logger from '../../libs/logger.js';
17
16
  import t from '../../i18n/index.js';
18
- import { exit } from 'process';
19
17
  const commit = {
20
18
  command: 'commit [entry]',
21
19
  describe: `📥 ${t('commit_describe').d('Commit your code, save as a new version')}`,
@@ -40,7 +38,6 @@ const commit = {
40
38
  export default commit;
41
39
  export function handleCommit(argv) {
42
40
  return __awaiter(this, void 0, void 0, function* () {
43
- var _a, _b, _c;
44
41
  if (!checkDirectory())
45
42
  return;
46
43
  const projectConfig = getProjectConfig();
@@ -53,19 +50,11 @@ export function handleCommit(argv) {
53
50
  const server = yield ApiService.getInstance();
54
51
  const req = { Name: projectConfig.name };
55
52
  const response = yield server.getRoutine(req, false);
56
- let specName = (_a = response === null || response === void 0 ? void 0 : response.data.Envs[0].SpecName) !== null && _a !== void 0 ? _a : '50ms';
57
53
  let action = 'Creating';
58
54
  let description;
59
55
  if (!response) {
60
56
  logger.log(`🙅 ${t('commit_er_not_exist').d('No routine found, creating a new one')}`);
61
57
  description = yield descriptionInput(`🖊️ ${t('commit_er_description').d('Enter a description for the routine')}:`, false);
62
- const specList = ((_c = (_b = (yield server.ListRoutineOptionalSpecs())) === null || _b === void 0 ? void 0 : _b.data.Specs) !== null && _c !== void 0 ? _c : []).reduce((acc, item) => {
63
- if (item.IsAvailable) {
64
- acc.push(item.SpecName);
65
- }
66
- return acc;
67
- }, []);
68
- specName = yield displaySelectSpec(specList);
69
58
  }
70
59
  else {
71
60
  logger.log(`🔄 ${t('commit_er_exist').d('Routine exists, updating the code')}`);
@@ -76,8 +65,7 @@ export function handleCommit(argv) {
76
65
  const edgeRoutine = {
77
66
  name: projectConfig.name,
78
67
  code,
79
- description,
80
- specName
68
+ description
81
69
  };
82
70
  if (action === 'Creating') {
83
71
  yield createEdgeRoutine(edgeRoutine);
@@ -87,7 +75,6 @@ export function handleCommit(argv) {
87
75
  return;
88
76
  yield releaseOfficialVersion(edgeRoutine);
89
77
  }
90
- exit(0);
91
78
  }
92
79
  catch (error) {
93
80
  logger.error(`${t('common_error_occurred').d('An error occurred:')} ${error}`);
@@ -126,6 +113,7 @@ export function uploadEdgeRoutineCode(edgeRoutine) {
126
113
  return true;
127
114
  }
128
115
  catch (error) {
116
+ logger.error('123');
129
117
  logger.error(`${t('common_error_occurred').d('An error occurred:')} ${error}`);
130
118
  process.exit(0);
131
119
  }
@@ -1,23 +1,4 @@
1
1
  import t from '../../i18n/index.js';
2
- export const SUMMARIES_LIST = [
3
- {
4
- title: t('summery_cd').d('Enter your routine project folder'),
5
- command: '💡 cd [Your Routine Name]'
6
- },
7
- {
8
- title: t('summery_dev').d('Start a local development server for your project'),
9
- command: '💡 esa dev'
10
- },
11
- {
12
- title: t('summery_commit').d('Save a new version of code'),
13
- command: '💡 esa commit'
14
- },
15
- // Use Deploy or Release?
16
- {
17
- title: t('summery_deploy').d('Deploy your project to different environments'),
18
- command: '💡 esa deploy'
19
- }
20
- ];
21
2
  export const getSummary = (routineName) => {
22
3
  return [
23
4
  {
@@ -13,7 +13,6 @@ import { PublishType } from '../../libs/interface.js';
13
13
  import { ApiService } from '../../libs/apiService.js';
14
14
  import { descriptionInput } from '../../components/descriptionInput.js';
15
15
  import { readEdgeRoutineFile } from '../../utils/fileUtils/index.js';
16
- import { displaySelectSpec } from './index.js';
17
16
  import { createEdgeRoutine, releaseOfficialVersion, uploadEdgeRoutineCode } from '../commit/index.js';
18
17
  import logger from '../../libs/logger.js';
19
18
  import t from '../../i18n/index.js';
@@ -64,7 +63,6 @@ export function displaySelectDeployType() {
64
63
  }
65
64
  export function createAndDeployVersion(projectConfig_1) {
66
65
  return __awaiter(this, arguments, void 0, function* (projectConfig, createUnstable = false, customEntry) {
67
- var _a, _b, _c, _d;
68
66
  try {
69
67
  const server = yield ApiService.getInstance();
70
68
  const description = yield descriptionInput(createUnstable
@@ -72,26 +70,10 @@ export function createAndDeployVersion(projectConfig_1) {
72
70
  : `🖊️ ${t('deploy_description_version').d('Enter the description of the code version')}:`, false);
73
71
  yield prodBuild(false, customEntry);
74
72
  const code = readEdgeRoutineFile();
75
- const specList = ((_b = (_a = (yield server.ListRoutineOptionalSpecs())) === null || _a === void 0 ? void 0 : _a.data.Specs) !== null && _b !== void 0 ? _b : []).reduce((acc, item) => {
76
- if (item.IsAvailable) {
77
- acc.push(item.SpecName);
78
- }
79
- return acc;
80
- }, []);
81
- let specName;
82
- if (createUnstable) {
83
- specName = yield displaySelectSpec(specList);
84
- }
85
- else {
86
- const req = { Name: (_c = projectConfig.name) !== null && _c !== void 0 ? _c : '' };
87
- const response = yield server.getRoutine(req);
88
- specName = (_d = response === null || response === void 0 ? void 0 : response.data.Envs[0].SpecName) !== null && _d !== void 0 ? _d : '50ms';
89
- }
90
73
  const edgeRoutine = {
91
74
  name: projectConfig.name,
92
75
  code: code || '',
93
- description: description,
94
- specName: specName
76
+ description: description
95
77
  };
96
78
  if (createUnstable) {
97
79
  return yield createEdgeRoutine(edgeRoutine);
@@ -9,7 +9,6 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
9
9
  };
10
10
  import chalk from 'chalk';
11
11
  import { getProjectConfig, readEdgeRoutineFile } from '../../utils/fileUtils/index.js';
12
- import SelectItems from '../../components/selectInput.js';
13
12
  import { Environment, PublishType } from '../../libs/interface.js';
14
13
  import logger from '../../libs/logger.js';
15
14
  import { checkDirectory, checkIsLoginSuccess, getRoutineVersionList } from '../utils.js';
@@ -59,7 +58,7 @@ export function quickDeploy(entry, projectConfig) {
59
58
  }
60
59
  else {
61
60
  logger.error(t('quick_deploy_failed').d('Quick deploy failed'));
62
- process.exit(0);
61
+ throw Error(t('quick_deploy_failed').d('Quick deploy failed'));
63
62
  }
64
63
  });
65
64
  }
@@ -101,20 +100,6 @@ export function handleDeploy(argv) {
101
100
  }
102
101
  });
103
102
  }
104
- export function displaySelectSpec(specList) {
105
- return __awaiter(this, void 0, void 0, function* () {
106
- logger.log(`📃 ${t('deploy_spec_select').d('Please select the spec of the routine you want to create')}`);
107
- const selectItems = specList.map((spec) => {
108
- return { label: spec, value: spec };
109
- });
110
- return new Promise((resolve) => {
111
- const handleSelection = (item) => __awaiter(this, void 0, void 0, function* () {
112
- resolve(item.value);
113
- });
114
- SelectItems({ items: selectItems, handleSelect: handleSelection });
115
- });
116
- });
117
- }
118
103
  function handleNoVersionsFound(projectConfig, customEntry) {
119
104
  return __awaiter(this, void 0, void 0, function* () {
120
105
  logger.log(`😄 ${t('deploy_first_time').d("This is first time to deploy. Let's create a version first!")}`);
@@ -62,11 +62,8 @@ function displayListPrompt(routineDetail) {
62
62
  const coloredStagingIpList = stagingIpList.map((ip) => {
63
63
  return chalk.green(ip);
64
64
  });
65
- const showEnvTable = (version, spec, region) => {
66
- const data = [
67
- { Version: version },
68
- { Specification: spec }
69
- ];
65
+ const showEnvTable = (version, region) => {
66
+ const data = [{ Version: version }];
70
67
  if (region) {
71
68
  data.push({ Region: region });
72
69
  }
@@ -76,13 +73,13 @@ function displayListPrompt(routineDetail) {
76
73
  if (stagingIpList.length > 0) {
77
74
  logger.log(`Staging IP: ${coloredStagingIpList.join(', ')}`);
78
75
  }
79
- showEnvTable(stagingEnv.CodeVersion, stagingEnv.SpecName);
76
+ showEnvTable(stagingEnv.CodeVersion);
80
77
  logger.block();
81
78
  logger.log(`${chalk.bold(`${t('deploy_env_production').d('Production')} ${!isCanary ? chalk.green('●') : ''}`)}`);
82
- showEnvTable(canaryEnv.CodeVersion, canaryEnv.SpecName);
79
+ showEnvTable(canaryEnv.CodeVersion);
83
80
  logger.block();
84
81
  logger.log(`${chalk.bold(`${t('deploy_env_canary').d('Canary')} ${isCanary ? chalk.green('●') : ''}`)}`);
85
- showEnvTable((_d = canaryEnv.CanaryCodeVersion) !== null && _d !== void 0 ? _d : '', canaryEnv.SpecName, (_e = canaryEnv.CanaryAreaList) === null || _e === void 0 ? void 0 : _e.join(', '));
82
+ showEnvTable((_d = canaryEnv.CanaryCodeVersion) !== null && _d !== void 0 ? _d : '', (_e = canaryEnv.CanaryAreaList) === null || _e === void 0 ? void 0 : _e.join(', '));
86
83
  logger.log(`${t('show_default_url').d(`You can visit:`)} ${chalk.yellowBright(routineDetail.data.DefaultRelatedRecord)}`);
87
84
  logger.info(routineDetail.data.DefaultRelatedRecord);
88
85
  logger.block();
@@ -0,0 +1,117 @@
1
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
+ return new (P || (P = Promise))(function (resolve, reject) {
4
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
8
+ });
9
+ };
10
+ import fs from 'fs-extra';
11
+ import path from 'path';
12
+ import Template from '../../libs/templates/index.js';
13
+ import { getProjectConfig } from '../../utils/fileUtils/index.js';
14
+ import logger from '../../libs/logger.js';
15
+ import { execSync } from 'child_process';
16
+ import t from '../../i18n/index.js';
17
+ import chalk from 'chalk';
18
+ import { getDirName } from '../../utils/fileUtils/base.js';
19
+ import inquirer from 'inquirer';
20
+ export const getTemplateInstances = (templateHubPath) => {
21
+ return fs
22
+ .readdirSync(templateHubPath)
23
+ .filter((item) => {
24
+ const itemPath = path.join(templateHubPath, item);
25
+ return (fs.statSync(itemPath).isDirectory() &&
26
+ !['.git', 'node_modules', 'lib'].includes(item));
27
+ })
28
+ .map((item) => {
29
+ var _a;
30
+ const projectPath = path.join(templateHubPath, item);
31
+ const projectConfig = getProjectConfig(projectPath);
32
+ const templateName = (_a = projectConfig === null || projectConfig === void 0 ? void 0 : projectConfig.name) !== null && _a !== void 0 ? _a : '';
33
+ return new Template(projectPath, templateName);
34
+ });
35
+ };
36
+ export const transferTemplatesToSelectItem = (configs, templateInstanceList, lang) => {
37
+ if (!configs)
38
+ return [];
39
+ return configs.map((config) => {
40
+ var _a, _b;
41
+ const title = config.Title_EN;
42
+ const value = (_b = (_a = templateInstanceList.find((template) => {
43
+ return title === template.title;
44
+ })) === null || _a === void 0 ? void 0 : _a.path) !== null && _b !== void 0 ? _b : '';
45
+ const children = transferTemplatesToSelectItem(config.children, templateInstanceList, lang);
46
+ return {
47
+ label: lang === 'en' ? config.Title_EN : config.Title_ZH,
48
+ value: value,
49
+ children
50
+ };
51
+ });
52
+ };
53
+ export const preInstallDependencies = (targetPath) => __awaiter(void 0, void 0, void 0, function* () {
54
+ const packageJsonPath = path.join(targetPath, 'package.json');
55
+ if (fs.existsSync(packageJsonPath)) {
56
+ logger.log(t('init_install_dependence').d('⌛️ Installing dependencies...'));
57
+ execSync('npm install', { stdio: 'inherit', cwd: targetPath });
58
+ logger.success(t('init_install_dependencies_success').d('Dependencies installed successfully.'));
59
+ // Read and parse package.json to check for build script
60
+ const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf-8'));
61
+ if (packageJson.scripts && packageJson.scripts.build) {
62
+ logger.log(t('init_build_project').d('⌛️ Building project...'));
63
+ execSync('npm run build', { stdio: 'inherit', cwd: targetPath });
64
+ logger.success(t('init_build_project_success').d('Project built successfully.'));
65
+ }
66
+ else {
67
+ logger.log(t('no_build_script').d('No build script found in package.json, skipping build step.'));
68
+ }
69
+ }
70
+ });
71
+ export function checkAndUpdatePackage(packageName) {
72
+ return __awaiter(this, void 0, void 0, function* () {
73
+ try {
74
+ // 获取当前安装的版本
75
+ const __dirname = getDirName(import.meta.url);
76
+ const packageJsonPath = path.join(__dirname, '../../../');
77
+ const versionInfo = execSync(`npm list ${packageName}`, {
78
+ cwd: packageJsonPath
79
+ }).toString();
80
+ const match = versionInfo.match(new RegExp(`(${packageName})@([0-9.]+)`));
81
+ const currentVersion = match ? match[2] : '';
82
+ // 获取最新版本
83
+ const latestVersion = execSync(`npm view ${packageName} version`, {
84
+ cwd: packageJsonPath
85
+ })
86
+ .toString()
87
+ .trim();
88
+ if (currentVersion !== latestVersion) {
89
+ logger.log(t('display_current_esa_template_version').d(`Current esa-template version:`) +
90
+ chalk.green(currentVersion) +
91
+ ' ' +
92
+ t('display_latest_esa_template_version').d(`Latest esa-template version:`) +
93
+ chalk.green(latestVersion));
94
+ const { isUpdate } = yield inquirer.prompt({
95
+ type: 'confirm',
96
+ name: 'isUpdate',
97
+ message: t('is_update_to_latest_version').d('Do you want to update templates to latest version?')
98
+ });
99
+ if (isUpdate) {
100
+ execSync(`rm -rf node_modules/${packageName} &&rm -rf package-lock.json &&npm install ${packageName}@latest`, {
101
+ cwd: packageJsonPath
102
+ });
103
+ logger.log(t('updated_esa_template_to_latest_version', { packageName }).d(`${packageName} updated successfully`));
104
+ }
105
+ }
106
+ else {
107
+ logger.log(t('esa_template_is_latest_version', { packageName }).d(`${packageName} is latest.`));
108
+ }
109
+ }
110
+ catch (error) {
111
+ console.log(error);
112
+ if (error instanceof Error) {
113
+ logger.error('检测和更新包时发生错误,跳过更新模版');
114
+ }
115
+ }
116
+ });
117
+ }
@@ -9,43 +9,20 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
9
9
  };
10
10
  import fs from 'fs-extra';
11
11
  import path from 'path';
12
+ import inquirer from 'inquirer';
13
+ import { exit } from 'process';
12
14
  import Template from '../../libs/templates/index.js';
13
15
  import { installGit } from '../../libs/git/index.js';
14
- import { descriptionInput } from '../../components/descriptionInput.js';
16
+ import multiLevelSelect from '../../components/mutiLevelSelect.js';
15
17
  import { generateConfigFile, getCliConfig, getProjectConfig, getTemplatesConfig, templateHubPath, updateProjectConfigFile } from '../../utils/fileUtils/index.js';
16
18
  import t from '../../i18n/index.js';
17
19
  import logger from '../../libs/logger.js';
18
- import SelectItems from '../../components/selectInput.js';
19
20
  import { quickDeploy } from '../deploy/index.js';
20
- import chalk from 'chalk';
21
21
  import { ApiService } from '../../libs/apiService.js';
22
- import { exit } from 'process';
23
22
  import { checkRoutineExist } from '../../utils/checkIsRoutineCreated.js';
24
- import { execSync } from 'child_process';
25
- import MultiLevelSelect from '../../components/mutiLevelSelect.js';
26
- import { getDirName } from '../../utils/fileUtils/base.js';
27
- import { yesNoPromptAndExecute } from '../deploy/helper.js';
28
23
  import { checkIsLoginSuccess } from '../utils.js';
29
- export const getTemplateInstances = (templateHubPath) => {
30
- return fs
31
- .readdirSync(templateHubPath)
32
- .filter((item) => {
33
- const itemPath = path.join(templateHubPath, item);
34
- return (fs.statSync(itemPath).isDirectory() &&
35
- !['.git', 'node_modules', 'lib'].includes(item));
36
- })
37
- .map((item) => {
38
- var _a;
39
- const projectPath = path.join(templateHubPath, item);
40
- const projectConfig = getProjectConfig(projectPath);
41
- const templateName = (_a = projectConfig === null || projectConfig === void 0 ? void 0 : projectConfig.name) !== null && _a !== void 0 ? _a : '';
42
- return new Template(projectPath, templateName);
43
- });
44
- };
45
- const secondSetOfItems = [
46
- { label: 'Yes', value: 'yesInstall' },
47
- { label: 'No', value: 'noInstall' }
48
- ];
24
+ import chalk from 'chalk';
25
+ import { checkAndUpdatePackage, getTemplateInstances, preInstallDependencies, transferTemplatesToSelectItem } from './helper.js';
49
26
  const init = {
50
27
  command: 'init',
51
28
  describe: `📥 ${t('init_describe').d('Initialize a routine with a template')}`,
@@ -58,186 +35,141 @@ const init = {
58
35
  },
59
36
  handler: (argv) => __awaiter(void 0, void 0, void 0, function* () {
60
37
  yield handleInit(argv);
38
+ exit(0);
61
39
  })
62
40
  };
63
41
  export default init;
64
- export const preInstallDependencies = (targetPath) => __awaiter(void 0, void 0, void 0, function* () {
65
- const packageJsonPath = path.join(targetPath, 'package.json');
66
- if (fs.existsSync(packageJsonPath)) {
67
- logger.log(t('init_install_dependence').d('⌛️ Installing dependencies...'));
68
- execSync('npm install esa-template', {
69
- stdio: 'inherit',
70
- cwd: targetPath
71
- });
72
- logger.success(t('init_install_dependencies_success').d('Dependencies installed successfully.'));
73
- logger.log(t('init_build_project').d('⌛️ Building project...'));
74
- execSync('npm run build', { stdio: 'inherit', cwd: targetPath });
75
- logger.success(t('init_build_project_success').d('Project built successfully.'));
76
- }
77
- });
78
- export const transferTemplatesToSelectItem = (configs, templateInstanceList, lang) => {
79
- if (!configs)
80
- return [];
81
- return configs.map((config) => {
82
- var _a, _b;
83
- const name = config.Title_EN;
84
- const value = (_b = (_a = templateInstanceList.find((template) => {
85
- return name === template.title;
86
- })) === null || _a === void 0 ? void 0 : _a.path) !== null && _b !== void 0 ? _b : '';
87
- const children = transferTemplatesToSelectItem(config.children, templateInstanceList);
88
- return {
89
- label: lang === 'en' ? config.Title_EN : config.Title_ZH,
90
- value: value,
91
- key: name,
92
- children
93
- };
94
- });
95
- };
96
- function checkAndUpdatePackage(packageName) {
42
+ export function promptProjectName() {
97
43
  return __awaiter(this, void 0, void 0, function* () {
98
- try {
99
- // 获取当前安装的版本
100
- const __dirname = getDirName(import.meta.url);
101
- const packageJsonPath = path.join(__dirname, '../../../');
102
- const versionInfo = execSync(`npm list ${packageName}`, {
103
- cwd: packageJsonPath
104
- }).toString();
105
- const match = versionInfo.match(new RegExp(`(${packageName})@([0-9.]+)`));
106
- const currentVersion = match ? match[2] : '';
107
- // 获取最新版本
108
- const latestVersion = execSync(`npm view ${packageName} version`)
109
- .toString()
110
- .trim();
111
- if (currentVersion !== latestVersion) {
112
- logger.log(t('display_current_esa_template_version').d(`Current esa-template version:`) +
113
- chalk.green(currentVersion) +
114
- ' ' +
115
- t('display_latest_esa_template_version').d(`Latest esa-template version:`) +
116
- chalk.green(latestVersion));
117
- yield yesNoPromptAndExecute(t('is_update_to_latest_version').d('Do you want to update templates to latest version?'), () => __awaiter(this, void 0, void 0, function* () {
118
- logger.log(t('updating_esa_template_to_latest_version', { packageName }).d(`Updating ${packageName} to the latest version...`));
119
- execSync(`rm -rf node_modules/${packageName} &&rm -rf package-lock.json &&npm install ${packageName}@latest`, {
120
- cwd: packageJsonPath
121
- });
122
- logger.log(t('updated_esa_template_to_latest_version', { packageName }).d(`${packageName} updated successfully`));
44
+ const { name } = yield inquirer.prompt([
45
+ {
46
+ type: 'input',
47
+ name: 'name',
48
+ message: `🖊️ ${t('init_input_name').d('Enter the name of edgeRoutine:')}`,
49
+ validate: (input) => {
50
+ const regex = /^[a-z0-9-]{2,}$/;
51
+ if (!regex.test(input)) {
52
+ return t('init_name_error').d('Error: The project name must be at least 2 characters long and can only contain lowercase letters, numbers, and hyphens.');
53
+ }
123
54
  return true;
124
- }));
55
+ }
125
56
  }
126
- else {
127
- logger.log(t('esa_template_is_latest_version', { packageName }).d(`${packageName} is latest.`));
57
+ ]);
58
+ return name;
59
+ });
60
+ }
61
+ export function prepareTemplateItems() {
62
+ var _a;
63
+ const templateInstanceList = getTemplateInstances(templateHubPath);
64
+ const templateConfig = getTemplatesConfig();
65
+ const cliConfig = getCliConfig();
66
+ const lang = (_a = cliConfig === null || cliConfig === void 0 ? void 0 : cliConfig.lang) !== null && _a !== void 0 ? _a : 'en';
67
+ return transferTemplatesToSelectItem(templateConfig, templateInstanceList, lang);
68
+ }
69
+ export function selectTemplate(items) {
70
+ return __awaiter(this, void 0, void 0, function* () {
71
+ const selectedTemplatePath = yield multiLevelSelect(items, 'Select a template:');
72
+ if (!selectedTemplatePath) {
73
+ logger.log(t('init_cancel').d('User canceled the operation.'));
74
+ return null;
75
+ }
76
+ return selectedTemplatePath;
77
+ });
78
+ }
79
+ export function initializeProject(selectedTemplatePath, name) {
80
+ return __awaiter(this, void 0, void 0, function* () {
81
+ const selectTemplate = new Template(selectedTemplatePath, name);
82
+ const projectConfig = getProjectConfig(selectedTemplatePath);
83
+ if (!projectConfig) {
84
+ logger.notInProject();
85
+ return null;
86
+ }
87
+ const targetPath = path.join(process.cwd(), name);
88
+ if (fs.existsSync(targetPath)) {
89
+ logger.error(t('already_exist_file_error').d('Error: The project already exists. It looks like a folder named "<project-name>" is already present in the current directory. Please try the following options: 1. Choose a different project name. 2. Delete the existing folder if it\'s not needed: `rm -rf <project-name>` (use with caution!). 3. Move to a different directory before running the init command.'));
90
+ return null;
91
+ }
92
+ yield fs.copy(selectedTemplatePath, targetPath);
93
+ projectConfig.name = name;
94
+ yield updateProjectConfigFile(projectConfig, targetPath);
95
+ yield preInstallDependencies(targetPath);
96
+ return { template: selectTemplate, targetPath };
97
+ });
98
+ }
99
+ export function handleGitInitialization(targetPath) {
100
+ return __awaiter(this, void 0, void 0, function* () {
101
+ const { initGit } = yield inquirer.prompt([
102
+ {
103
+ type: 'list',
104
+ name: 'initGit',
105
+ message: t('init_git').d('Do you want to init git in your project?'),
106
+ choices: ['Yes', 'No']
128
107
  }
108
+ ]);
109
+ if (initGit === 'Yes') {
110
+ installGit(targetPath);
111
+ }
112
+ else {
113
+ logger.log(t('init_skip_git').d('Git installation was skipped.'));
129
114
  }
130
- catch (error) {
131
- if (error instanceof Error) {
132
- logger.error('检测和更新包时发生错误,跳过更新模版');
115
+ });
116
+ }
117
+ export function handleDeployment(targetPath, projectConfig) {
118
+ return __awaiter(this, void 0, void 0, function* () {
119
+ var _a, _b, _c;
120
+ const isLoginSuccess = yield checkIsLoginSuccess();
121
+ if (!isLoginSuccess) {
122
+ logger.log(chalk.yellow(t('not_login_auto_deploy').d('You are not logged in, automatic deployment cannot be performed. Please log in later and manually deploy.')));
123
+ return;
124
+ }
125
+ const { deploy } = yield inquirer.prompt([
126
+ {
127
+ type: 'list',
128
+ name: 'deploy',
129
+ message: t('auto_deploy').d('Do you want to deploy your project?'),
130
+ choices: ['Yes', 'No']
133
131
  }
132
+ ]);
133
+ if (deploy === 'Yes') {
134
+ yield checkRoutineExist((_a = projectConfig === null || projectConfig === void 0 ? void 0 : projectConfig.name) !== null && _a !== void 0 ? _a : '', targetPath);
135
+ yield quickDeploy(targetPath, projectConfig);
136
+ const service = yield ApiService.getInstance();
137
+ const res = yield service.getRoutine({ Name: (_b = projectConfig === null || projectConfig === void 0 ? void 0 : projectConfig.name) !== null && _b !== void 0 ? _b : '' });
138
+ const defaultUrl = (_c = res === null || res === void 0 ? void 0 : res.data) === null || _c === void 0 ? void 0 : _c.DefaultRelatedRecord;
139
+ const visitUrl = defaultUrl ? 'http://' + defaultUrl : '';
140
+ logger.success(`${t('init_deploy_success').d('Project deployment completed. Visit: ')}${chalk.yellowBright(visitUrl)}`);
141
+ logger.warn(t('deploy_url_warn').d('The domain may take some time to take effect, please try again later.'));
134
142
  }
135
143
  });
136
144
  }
137
145
  export function handleInit(argv) {
138
146
  return __awaiter(this, void 0, void 0, function* () {
139
- var _a;
140
- const { config } = argv;
141
- // 更新template npm包
147
+ // Update the template package (currently commented out)
142
148
  yield checkAndUpdatePackage('esa-template');
143
- if (config !== undefined) {
149
+ // If config option is provided, generate config file and exit
150
+ const config = getCliConfig();
151
+ if (config === undefined) {
144
152
  yield generateConfigFile(String(config));
145
- return;
146
153
  }
147
- const name = yield descriptionInput(`🖊️ ${t('init_input_name').d('Enter the name of edgeRoutine:')}`, true);
148
- const regex = /^[a-z0-9-]{2,}$/;
149
- if (!regex.test(name)) {
150
- logger.error(t('init_name_error').d('Error: The project name must be at least 2 characters long and can only contain lowercase letters, numbers, and hyphens.'));
154
+ const name = yield promptProjectName();
155
+ const templateItems = prepareTemplateItems();
156
+ // Select a template
157
+ const selectedTemplatePath = yield selectTemplate(templateItems);
158
+ if (!selectedTemplatePath) {
151
159
  return;
152
160
  }
153
- const templateInstanceList = getTemplateInstances(templateHubPath);
154
- const templateConfig = getTemplatesConfig();
155
- const cliConfig = getCliConfig();
156
- const lang = (_a = cliConfig === null || cliConfig === void 0 ? void 0 : cliConfig.lang) !== null && _a !== void 0 ? _a : 'en';
157
- const firstSetOfItems = transferTemplatesToSelectItem(templateConfig, templateInstanceList, lang);
158
- let selectTemplate;
159
- let targetPath;
160
- let projectConfig;
161
- const preInstallDependencies = () => __awaiter(this, void 0, void 0, function* () {
162
- const packageJsonPath = path.join(targetPath, 'package.json');
163
- if (fs.existsSync(packageJsonPath)) {
164
- logger.log('Install dependencies');
165
- logger.log(t('init_install_dependence').d('⌛️ Installing dependencies...'));
166
- execSync('npm install', { stdio: 'inherit', cwd: targetPath });
167
- logger.success(t('init_install_dependencies_success').d('Dependencies installed successfully.'));
168
- logger.log(t('init_build_project').d('⌛️ Building project...'));
169
- execSync('npm run build', { stdio: 'inherit', cwd: targetPath });
170
- logger.success(t('init_build_project_success').d('Project built successfully.'));
171
- }
172
- });
173
- const handleFirstSelection = (item) => __awaiter(this, void 0, void 0, function* () {
174
- if (item.key === 'exit') {
175
- process.exit(0);
176
- }
177
- const configPath = item.value;
178
- selectTemplate = new Template(configPath, name);
179
- projectConfig = getProjectConfig(configPath);
180
- if (!projectConfig)
181
- return logger.notInProject();
182
- const newPath = process.cwd() + '/' + name;
183
- targetPath = newPath;
184
- if (fs.existsSync(newPath)) {
185
- logger.error(t('already_exist_file_error').d('Error: The project already exists. It looks like a folder named "<project-name>" is already present in the current directory. Please try the following options: 1. Choose a different project name. 2. Delete the existing folder if it\'s not needed: `rm -rf <project-name>` (use with caution!). 3. Move to a different directory before running the init command.'));
186
- exit(0);
187
- }
188
- yield fs.copy(configPath, newPath);
189
- projectConfig.name = name;
190
- updateProjectConfigFile(projectConfig, newPath);
191
- preInstallDependencies();
192
- logger.log(t('init_git').d('Do you want to init git in your project?'));
193
- SelectItems({
194
- items: secondSetOfItems,
195
- handleSelect: handleSecondSelection
196
- });
197
- });
198
- const handleSecondSelection = (item) => __awaiter(this, void 0, void 0, function* () {
199
- if (item.value === 'yesInstall') {
200
- installGit(targetPath);
201
- }
202
- else {
203
- logger.log(t('init_skip_git').d('Git installation was skipped.'));
204
- }
205
- const isLoginSuccess = yield checkIsLoginSuccess();
206
- if (!isLoginSuccess) {
207
- logger.log(chalk.yellow(t('not_login_auto_deploy').d('You are not logged in, automatic deployment cannot be performed. Please log in later and manually deploy.')));
208
- process.exit(0);
209
- }
210
- logger.log(t('auto_deploy').d('Do you want to deploy your project?'));
211
- SelectItems({
212
- items: secondSetOfItems,
213
- handleSelect: handleThirdSelection
214
- });
215
- });
216
- const handleThirdSelection = (item) => __awaiter(this, void 0, void 0, function* () {
217
- var _a, _b, _c;
218
- // 选择自动生成版本并发布
219
- if (item.value === 'yesInstall') {
220
- yield checkRoutineExist((_a = projectConfig === null || projectConfig === void 0 ? void 0 : projectConfig.name) !== null && _a !== void 0 ? _a : '', targetPath);
221
- projectConfig && (yield quickDeploy(targetPath, projectConfig));
222
- const service = yield ApiService.getInstance();
223
- const res = yield service.getRoutine({ Name: (_b = projectConfig === null || projectConfig === void 0 ? void 0 : projectConfig.name) !== null && _b !== void 0 ? _b : '' });
224
- const defaultUrl = (_c = res === null || res === void 0 ? void 0 : res.data) === null || _c === void 0 ? void 0 : _c.DefaultRelatedRecord;
225
- const visitUrl = defaultUrl ? 'http://' + defaultUrl : '';
226
- logger.success(`${t('init_deploy_success').d('Project deployment completed. Visit: ')}${chalk.yellowBright(visitUrl)}`);
227
- logger.warn(t('deploy_url_warn').d('The domain may take some time to take effect, please try again later.'));
228
- }
229
- selectTemplate.printSummary();
230
- exit(0);
231
- });
232
- try {
233
- MultiLevelSelect({
234
- items: firstSetOfItems,
235
- handleSelect: handleFirstSelection
236
- });
237
- }
238
- catch (error) {
239
- logger.error(t('init_error').d('An error occurred while initializing.'));
240
- console.log(error);
161
+ // Initialize project files and configuration
162
+ const project = yield initializeProject(selectedTemplatePath, name);
163
+ if (!project) {
164
+ return;
241
165
  }
166
+ const { template, targetPath } = project;
167
+ // Handle Git initialization
168
+ yield handleGitInitialization(targetPath);
169
+ // Handle deployment
170
+ const projectConfig = getProjectConfig(targetPath);
171
+ yield handleDeployment(targetPath, projectConfig);
172
+ template.printSummary();
173
+ return;
242
174
  });
243
175
  }
@@ -7,63 +7,52 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
7
7
  step((generator = generator.apply(thisArg, _arguments || [])).next());
8
8
  });
9
9
  };
10
- import React, { useState } from 'react';
11
- import { render, Text, useApp } from 'ink';
12
- import SelectInput from 'ink-select-input';
13
- import Item from './selectItem.js';
14
- import t from '../i18n/index.js';
15
- const Indicator = ({ isSelected }) => {
16
- return React.createElement(Text, null, isSelected ? '👉 ' : ' ');
17
- };
18
- const EXIT_ITEM = {
19
- label: t('exit_select_init_template').d('Exit'),
20
- key: 'exit',
21
- value: '__exit__'
22
- };
23
- const RETURN_ITEM = {
24
- label: t('return_select_init_template').d('Return'),
25
- key: 'return',
26
- value: '__return__'
27
- };
28
- const MultiLevelSelect = ({ items, handleSelect, handleExit }) => {
29
- const { exit } = useApp();
30
- const [stack, setStack] = useState([[...items, EXIT_ITEM]]);
31
- const currentItems = stack[stack.length - 1];
32
- const onSelect = (item) => {
33
- if (item.value === '__return__') {
34
- if (stack.length > 1) {
35
- // 返回上一级菜单
36
- setStack(stack.slice(0, -1));
10
+ import inquirer from 'inquirer';
11
+ import logger from '../libs/logger.js';
12
+ /**
13
+ * Perform multi-level selection and return the final selected template path
14
+ * @param items Array of selection items (including categories and sub-templates)
15
+ * @param message Initial prompt message
16
+ * @returns Selected template path, or null if the user exits
17
+ */
18
+ export default function multiLevelSelect(items_1) {
19
+ return __awaiter(this, arguments, void 0, function* (items, message = 'Select a template:') {
20
+ let currentItems = items; // Current level options
21
+ const stack = []; // Stack to store previous level options for back navigation
22
+ let selectedPath = null;
23
+ while (selectedPath === null) {
24
+ const { choice } = yield inquirer.prompt([
25
+ {
26
+ type: 'list',
27
+ name: 'choice',
28
+ message,
29
+ pageSize: 10,
30
+ choices: [
31
+ ...currentItems.map((item) => ({ name: item.label, value: item })),
32
+ ...(stack.length > 0 ? [{ name: 'Back', value: 'back' }] : []), // Show "Back" if there’s a previous level
33
+ { name: 'Exit', value: 'exit' }
34
+ ]
35
+ }
36
+ ]);
37
+ if (choice === 'exit') {
38
+ logger.log('User canceled the operation.');
39
+ return null;
40
+ }
41
+ if (choice === 'back') {
42
+ currentItems = stack.pop(); // Return to the previous level
43
+ continue;
44
+ }
45
+ // If a category with children is selected
46
+ if (choice.children && choice.children.length > 0) {
47
+ stack.push(currentItems); // Save the current level
48
+ currentItems = choice.children; // Move to the next level
49
+ message = `Select a template under ${choice.label}:`;
37
50
  }
38
51
  else {
39
- // 顶层菜单,执行退出逻辑
40
- handleExit();
41
- exit();
52
+ // A leaf node (no children) is selected, end the selection
53
+ selectedPath = choice.value;
42
54
  }
43
- return;
44
- }
45
- if (item.children && item.children.length > 0) {
46
- setStack([...stack, [...item.children, RETURN_ITEM]]); // 在子层级中添加“退出”选项
47
55
  }
48
- else {
49
- handleSelect(item);
50
- exit();
51
- }
52
- };
53
- return (React.createElement(SelectInput, { items: currentItems, onSelect: onSelect, itemComponent: Item, indicatorComponent: Indicator, limit: 10 }));
54
- };
55
- export const MultiLevelSelectComponent = (props) => __awaiter(void 0, void 0, void 0, function* () {
56
- const { items, handleSelect, handleExit } = props;
57
- return new Promise((resolve) => {
58
- const { unmount } = render(React.createElement(MultiLevelSelect, { items: items, handleSelect: (item) => {
59
- unmount();
60
- handleSelect && handleSelect(item);
61
- resolve(item);
62
- }, handleExit: () => {
63
- unmount();
64
- handleExit && handleExit();
65
- resolve(null);
66
- } }));
56
+ return selectedPath;
67
57
  });
68
- });
69
- export default MultiLevelSelectComponent;
58
+ }
@@ -918,5 +918,21 @@
918
918
  "deno_install_success_tips": {
919
919
  "en": "Please run ${dev} again",
920
920
  "zh_CN": "请重新运行 ${dev}"
921
+ },
922
+ "no_build_script": {
923
+ "en": "No build script found in package.json, skipping build step.",
924
+ "zh_CN": "在 package.json 中未找到构建脚本,跳过构建步骤。"
925
+ },
926
+ "init_cancel": {
927
+ "en": "User canceled the operation.",
928
+ "zh_CN": "用户取消了操作。"
929
+ },
930
+ "routine_create_success": {
931
+ "en": "Routine created successfully.",
932
+ "zh_CN": "边缘函数创建成功"
933
+ },
934
+ "routine_create_fail": {
935
+ "en": "Routine created failed.",
936
+ "zh_CN": "边缘函数创建失败"
921
937
  }
922
938
  }
@@ -640,8 +640,7 @@ export class ApiService {
640
640
  let request = new $OpenApi.OpenApiRequest({
641
641
  query: {
642
642
  Name: edgeRoutine.name,
643
- Description: edgeRoutine.description,
644
- SpecName: edgeRoutine.specName
643
+ Description: edgeRoutine.description
645
644
  }
646
645
  });
647
646
  let runtime = {
@@ -772,47 +771,6 @@ export class ApiService {
772
771
  return null;
773
772
  });
774
773
  }
775
- ListRoutineOptionalSpecs() {
776
- return __awaiter(this, void 0, void 0, function* () {
777
- try {
778
- let params = {
779
- action: 'ListRoutineOptionalSpecs',
780
- version: '2024-09-10',
781
- protocol: 'https',
782
- method: 'GET',
783
- authType: 'AK',
784
- bodyType: 'json',
785
- reqBodyType: 'json',
786
- style: 'RPC',
787
- pathname: '/',
788
- toMap: function () {
789
- return this;
790
- }
791
- };
792
- let request = new $OpenApi.OpenApiRequest();
793
- let runtime = {
794
- toMap: function () {
795
- return this;
796
- }
797
- };
798
- const res = yield this.client.callApi(params, request, runtime);
799
- if (res.statusCode === 200 && res.body) {
800
- const ret = {
801
- code: res.statusCode,
802
- data: {
803
- RequestId: res.body.RequestId,
804
- Specs: res.body.Specs
805
- }
806
- };
807
- return ret;
808
- }
809
- }
810
- catch (error) {
811
- console.log(error);
812
- }
813
- return null;
814
- });
815
- }
816
774
  createRoutineRelatedRecord(requestParams) {
817
775
  return __awaiter(this, void 0, void 0, function* () {
818
776
  try {
@@ -1,5 +1,6 @@
1
1
  import { getSummary } from '../../commands/common/constant.js';
2
2
  import chalk from 'chalk';
3
+ import logger from '../logger.js';
3
4
  export default class Template {
4
5
  constructor(path, title) {
5
6
  this.path = path;
@@ -10,7 +11,7 @@ export default class Template {
10
11
  list.forEach((summary) => {
11
12
  const title = chalk.bold(summary.title);
12
13
  const command = chalk.green(summary.command);
13
- console.log(`${title}: ${command}`);
14
+ logger.log(`${title}: ${command}`);
14
15
  });
15
16
  }
16
17
  }
@@ -9,7 +9,6 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
9
9
  };
10
10
  import path from 'path';
11
11
  import { createEdgeRoutine } from '../commands/commit/index.js';
12
- import { displaySelectSpec } from '../commands/deploy/index.js';
13
12
  import { ApiService } from '../libs/apiService.js';
14
13
  import { readEdgeRoutineFile } from './fileUtils/index.js';
15
14
  import logger from '../libs/logger.js';
@@ -36,26 +35,22 @@ export function validRoutine(name) {
36
35
  }
37
36
  export function checkRoutineExist(name, entry) {
38
37
  return __awaiter(this, void 0, void 0, function* () {
39
- var _a, _b;
40
38
  const isCreatedRoutine = yield isRoutineExist(name);
41
39
  if (!isCreatedRoutine) {
42
40
  logger.log(t('first_deploy').d('This is the first time to deploy, we will create a new routine for you.'));
43
41
  const entryFile = path.resolve(entry !== null && entry !== void 0 ? entry : '', 'src/index.js');
44
42
  yield prodBuild(false, entryFile, entry);
45
43
  const code = readEdgeRoutineFile(entry) || '';
46
- const server = yield ApiService.getInstance();
47
- const specList = ((_b = (_a = (yield server.ListRoutineOptionalSpecs())) === null || _a === void 0 ? void 0 : _a.data.Specs) !== null && _b !== void 0 ? _b : []).reduce((acc, item) => {
48
- if (item.IsAvailable) {
49
- acc.push(item.SpecName);
50
- }
51
- return acc;
52
- }, []);
53
- const spec = yield displaySelectSpec(specList);
54
- yield createEdgeRoutine({
44
+ const res = yield createEdgeRoutine({
55
45
  name: name,
56
- specName: spec,
57
46
  code: code
58
47
  });
48
+ if (res) {
49
+ logger.success(t('routine_create_success').d('Routine created successfully.'));
50
+ }
51
+ else {
52
+ logger.error(t('routine_create_fail').d('Routine created failed.'));
53
+ }
59
54
  }
60
55
  });
61
56
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "esa-cli",
3
- "version": "0.0.2-beta.8",
3
+ "version": "0.0.2-beta.9",
4
4
  "description": "A CLI for operating Alibaba Cloud ESA EdgeRoutine (Edge Functions).",
5
5
  "main": "bin/enter.cjs",
6
6
  "type": "module",
@@ -80,7 +80,7 @@
80
80
  "chokidar": "^3.5.3",
81
81
  "cli-table3": "^0.6.5",
82
82
  "cross-spawn": "^7.0.3",
83
- "esa-template": "^0.0.3",
83
+ "esa-template": "0.0.4-beta.1",
84
84
  "esbuild": "^0.21.1",
85
85
  "esbuild-plugin-less": "^1.3.8",
86
86
  "form-data": "^4.0.0",