esa-cli 0.0.2-beta.2 → 0.0.2-beta.20

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.
Files changed (82) hide show
  1. package/dist/commands/commit/index.js +48 -115
  2. package/dist/commands/commit/prodBuild.js +2 -3
  3. package/dist/commands/common/constant.js +0 -19
  4. package/dist/commands/common/utils.js +416 -0
  5. package/dist/commands/config.js +1 -1
  6. package/dist/commands/deploy/helper.js +51 -72
  7. package/dist/commands/deploy/index.js +50 -188
  8. package/dist/commands/deployments/delete.js +32 -22
  9. package/dist/commands/deployments/index.js +2 -2
  10. package/dist/commands/deployments/list.js +22 -38
  11. package/dist/commands/dev/build.js +3 -3
  12. package/dist/commands/dev/doProcess.js +5 -5
  13. package/dist/commands/dev/ew2/cacheService.js +33 -0
  14. package/dist/commands/dev/ew2/devEntry.js +2 -1
  15. package/dist/commands/dev/ew2/devPack.js +39 -43
  16. package/dist/commands/dev/ew2/kvService.js +27 -0
  17. package/dist/commands/dev/ew2/mock/cache.js +99 -15
  18. package/dist/commands/dev/ew2/mock/kv.js +142 -21
  19. package/dist/commands/dev/ew2/server.js +165 -29
  20. package/dist/commands/dev/index.js +17 -17
  21. package/dist/commands/dev/mockWorker/devPack.js +35 -24
  22. package/dist/commands/dev/mockWorker/server.js +7 -6
  23. package/dist/commands/domain/add.js +2 -2
  24. package/dist/commands/domain/delete.js +7 -7
  25. package/dist/commands/domain/index.js +2 -2
  26. package/dist/commands/domain/list.js +10 -10
  27. package/dist/commands/init/helper.js +759 -0
  28. package/dist/commands/init/index.js +88 -220
  29. package/dist/commands/init/snippets/nextjs/next.config.mjs +6 -0
  30. package/dist/commands/init/snippets/nextjs/next.config.ts +7 -0
  31. package/dist/commands/init/snippets/react-router/react-router.config.ts +7 -0
  32. package/dist/commands/init/template.jsonc +84 -0
  33. package/dist/commands/init/types.js +1 -0
  34. package/dist/commands/lang.js +2 -2
  35. package/dist/commands/login/index.js +74 -34
  36. package/dist/commands/logout.js +5 -5
  37. package/dist/commands/route/add.js +105 -49
  38. package/dist/commands/route/delete.js +33 -27
  39. package/dist/commands/route/helper.js +123 -0
  40. package/dist/commands/route/index.js +2 -2
  41. package/dist/commands/route/list.js +56 -17
  42. package/dist/commands/routine/delete.js +2 -2
  43. package/dist/commands/routine/index.js +2 -2
  44. package/dist/commands/routine/list.js +43 -37
  45. package/dist/commands/site/index.js +1 -1
  46. package/dist/commands/site/list.js +6 -7
  47. package/dist/commands/utils.js +59 -23
  48. package/dist/components/descriptionInput.js +1 -1
  49. package/dist/components/filterSelector.js +1 -1
  50. package/dist/components/mutiLevelSelect.js +43 -55
  51. package/dist/components/mutiSelectTable.js +1 -1
  52. package/dist/components/routeBuilder.js +68 -0
  53. package/dist/components/selectInput.js +2 -3
  54. package/dist/components/selectItem.js +1 -1
  55. package/dist/docs/Commands_en.md +142 -131
  56. package/dist/docs/Commands_zh_CN.md +139 -127
  57. package/dist/i18n/index.js +2 -2
  58. package/dist/i18n/locales.json +435 -23
  59. package/dist/index.js +27 -20
  60. package/dist/libs/api.js +32 -9
  61. package/dist/libs/apiService.js +267 -88
  62. package/dist/libs/git/index.js +86 -9
  63. package/dist/libs/interface.js +0 -1
  64. package/dist/libs/logger.js +162 -10
  65. package/dist/libs/service.js +2 -2
  66. package/dist/libs/templates/index.js +3 -2
  67. package/dist/utils/checkAssetsExist.js +80 -0
  68. package/dist/utils/checkDevPort.js +3 -17
  69. package/dist/utils/checkEntryFileExist.js +10 -0
  70. package/dist/utils/checkIsRoutineCreated.js +28 -27
  71. package/dist/utils/checkVersion.js +119 -1
  72. package/dist/utils/command.js +149 -0
  73. package/dist/utils/compress.js +136 -0
  74. package/dist/utils/download.js +182 -0
  75. package/dist/utils/fileMd5.js +1 -1
  76. package/dist/utils/fileUtils/base.js +1 -1
  77. package/dist/utils/fileUtils/index.js +136 -44
  78. package/dist/utils/installDeno.js +8 -8
  79. package/dist/utils/installEw2.js +7 -7
  80. package/dist/utils/openInBrowser.js +1 -1
  81. package/dist/utils/prompt.js +97 -0
  82. package/package.json +19 -12
@@ -7,237 +7,105 @@ 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 fs from 'fs-extra';
11
- import path from 'path';
12
- import Template from '../../libs/templates/index.js';
13
- import { installGit } from '../../libs/git/index.js';
14
- import { descriptionInput } from '../../components/descriptionInput.js';
15
- import { generateConfigFile, getCliConfig, getProjectConfig, getTemplatesConfig, templateHubPath, updateProjectConfigFile } from '../../utils/fileUtils/index.js';
16
- import t from '../../i18n/index.js';
17
- import logger from '../../libs/logger.js';
18
- import SelectItems from '../../components/selectInput.js';
19
- import { quickDeploy } from '../deploy/index.js';
20
- import chalk from 'chalk';
21
- import { ApiService } from '../../libs/apiService.js';
22
10
  import { exit } from 'process';
23
- 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
- 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
- ];
11
+ import { intro, outro } from '@clack/prompts';
12
+ import chalk from 'chalk';
13
+ import t from '../../i18n/index.js';
14
+ import { promptParameter } from '../../utils/prompt.js';
15
+ import { displayDeploySuccess } from '../common/utils.js';
16
+ import { applyFileEdits, buildProject, checkAndUpdatePackage, configCategory, configLanguage, configProjectName, configTemplate, createProject, deployProject, getInitParamsFromArgv, initGit, installDependencies, installESACli, updateConfigFile } from './helper.js';
49
17
  const init = {
50
- command: 'init',
18
+ command: 'init [name]',
51
19
  describe: `📥 ${t('init_describe').d('Initialize a routine with a template')}`,
52
20
  builder: (yargs) => {
53
- return yargs.option('config', {
54
- alias: 'c',
55
- describe: t('init_config_file').d('Generate a config file for your project'),
21
+ return yargs
22
+ .positional('name', {
23
+ describe: t('init_project_name').d('Project name'),
24
+ type: 'string'
25
+ })
26
+ .option('framework', {
27
+ alias: 'f',
28
+ describe: 'Choose a frontend framework (react/vue/nextjs...)',
29
+ type: 'string'
30
+ })
31
+ .option('language', {
32
+ alias: 'l',
33
+ describe: 'Choose programming language (typescript/javascript)',
34
+ type: 'string',
35
+ choices: ['typescript', 'javascript']
36
+ })
37
+ .option('template', {
38
+ alias: 't',
39
+ describe: t('init_template_name').d('Template name to use'),
40
+ type: 'string'
41
+ })
42
+ .option('yes', {
43
+ alias: 'y',
44
+ describe: t('init_yes').d('Answer "Yes" to all prompts.'),
45
+ type: 'boolean',
46
+ default: false
47
+ })
48
+ .option('git', {
49
+ alias: 'g',
50
+ describe: 'Initialize git repository',
51
+ type: 'boolean'
52
+ })
53
+ .option('deploy', {
54
+ alias: 'd',
55
+ describe: 'Deploy after initialization',
56
56
  type: 'boolean'
57
57
  });
58
58
  },
59
59
  handler: (argv) => __awaiter(void 0, void 0, void 0, function* () {
60
60
  yield handleInit(argv);
61
+ exit(0);
61
62
  })
62
63
  };
63
64
  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.'));
65
+ const handleInit = (argv) => __awaiter(void 0, void 0, void 0, function* () {
66
+ yield checkAndUpdatePackage('esa-template');
67
+ const initParams = getInitParamsFromArgv(argv);
68
+ yield create(initParams);
69
+ yield config(initParams);
70
+ yield deploy(initParams);
71
+ });
72
+ const create = (initParams) => __awaiter(void 0, void 0, void 0, function* () {
73
+ intro(`Create an application with ESA ${chalk.gray('Step 1 of 3')}`);
74
+ yield configProjectName(initParams);
75
+ yield configCategory(initParams);
76
+ yield configTemplate(initParams);
77
+ if (initParams.category === 'framework') {
78
+ yield configLanguage(initParams);
76
79
  }
80
+ yield createProject(initParams);
81
+ yield installDependencies(initParams);
82
+ outro(`Application created`);
83
+ });
84
+ const config = (initParams) => __awaiter(void 0, void 0, void 0, function* () {
85
+ intro(`Configure an application with ESA ${chalk.gray('Step 2 of 3')}`);
86
+ yield applyFileEdits(initParams);
87
+ yield installESACli(initParams);
88
+ yield updateConfigFile(initParams);
89
+ yield initGit(initParams);
90
+ outro(`Project configured`);
91
+ });
92
+ const deploy = (initParams) => __awaiter(void 0, void 0, void 0, function* () {
93
+ intro(`Deploy an application with ESA ${chalk.gray('Step 3 of 3')}`);
94
+ if (!initParams.deploy) {
95
+ const deploy = (yield promptParameter({
96
+ type: 'confirm',
97
+ question: t('auto_deploy').d('Do you want to deploy your project?'),
98
+ label: 'Auto deploy',
99
+ defaultValue: false
100
+ }));
101
+ initParams.deploy = deploy;
102
+ }
103
+ if (!initParams.deploy) {
104
+ outro(`Deploy project skipped`);
105
+ return;
106
+ }
107
+ yield buildProject(initParams);
108
+ yield deployProject(initParams);
109
+ outro(`Deploy project finished`);
110
+ yield displayDeploySuccess(initParams.name, true, true);
77
111
  });
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) {
97
- 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`));
123
- return true;
124
- }));
125
- }
126
- else {
127
- logger.log(t('esa_template_is_latest_version', { packageName }).d(`${packageName} is latest.`));
128
- }
129
- }
130
- catch (error) {
131
- if (error instanceof Error) {
132
- logger.error('检测和更新包时发生错误,跳过更新模版');
133
- }
134
- }
135
- });
136
- }
137
- export function handleInit(argv) {
138
- return __awaiter(this, void 0, void 0, function* () {
139
- var _a;
140
- const { config } = argv;
141
- // 更新template npm包
142
- yield checkAndUpdatePackage('esa-template');
143
- if (config !== undefined) {
144
- yield generateConfigFile(String(config));
145
- return;
146
- }
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.'));
151
- return;
152
- }
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);
241
- }
242
- });
243
- }
@@ -0,0 +1,6 @@
1
+ /** @type {import('next').NextConfig} */
2
+ const nextConfig = {
3
+ output: 'export'
4
+ };
5
+
6
+ export default nextConfig;
@@ -0,0 +1,7 @@
1
+ import type { NextConfig } from 'next';
2
+
3
+ const nextConfig: NextConfig = {
4
+ output: 'export'
5
+ };
6
+
7
+ export default nextConfig;
@@ -0,0 +1,7 @@
1
+ import type { Config } from '@react-router/dev/config';
2
+
3
+ export default {
4
+ // Config options...
5
+ // Server-side render by default, to enable SPA mode set this to `false`
6
+ ssr: false
7
+ } satisfies Config;
@@ -0,0 +1,84 @@
1
+ {
2
+ "react": {
3
+ "label": "React",
4
+ "command": "npm create vite@latest",
5
+ "useGit": true,
6
+ "language": {
7
+ "typescript": "-- --template react-ts",
8
+ "javascript": "-- --template react"
9
+ },
10
+ "interactive": false,
11
+ "assets": {
12
+ "directory": "./dist",
13
+ "notFoundStrategy": "singlePageApplication"
14
+ }
15
+ },
16
+ "vue": {
17
+ "label": "Vue",
18
+ "command": "npm create vite@latest",
19
+ "useGit": true,
20
+ "language": {
21
+ "typescript": "-- --template vue-ts -- --use-npm",
22
+ "javascript": "-- --template vue"
23
+ },
24
+ "interactive": false,
25
+ "assets": {
26
+ "directory": "./dist",
27
+ "notFoundStrategy": "singlePageApplication"
28
+ }
29
+ },
30
+ "nextjs": {
31
+ "label": "Next.js",
32
+ "useGit": false,
33
+ "command": "npx create-next-app@latest",
34
+ "hint": "Only support static export",
35
+ "assets": {
36
+ "directory": "./out"
37
+ },
38
+ "fileEdits": [
39
+ {
40
+ "match": "next.config.ts",
41
+ "matchType": "exact",
42
+ "action": "overwrite",
43
+ "fromFile": "snippets/nextjs/next.config.ts",
44
+ "createIfMissing": true
45
+ },
46
+ {
47
+ "match": "next.config.mjs",
48
+ "matchType": "exact",
49
+ "action": "overwrite",
50
+ "fromFile": "snippets/nextjs/next.config.mjs",
51
+ "createIfMissing": true
52
+ }
53
+ ]
54
+ },
55
+ "astro": {
56
+ "label": "Astro",
57
+ "useGit": false,
58
+ "command": "npm create astro@4.13.1",
59
+ "params": "--no-install",
60
+ "assets": {
61
+ "directory": "./dist"
62
+ }
63
+ },
64
+ "react-router": {
65
+ "label": "React Router",
66
+ "useGit": false,
67
+ "command": "npx create-react-router",
68
+ "hint": "SPA mode",
69
+ "interactive": true,
70
+ "assets": {
71
+ "directory": "./build/client",
72
+ "notFoundStrategy": "singlePageApplication"
73
+ },
74
+ "fileEdits": [
75
+ {
76
+ "match": "react-router.config.ts",
77
+ "matchType": "exact",
78
+ "action": "overwrite",
79
+ "fromFile": "snippets/react-router/react-router.config.ts",
80
+ "createIfMissing": true
81
+ }
82
+ ]
83
+ }
84
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -8,9 +8,9 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
8
8
  });
9
9
  };
10
10
  import SelectItems from '../components/selectInput.js';
11
- import { updateCliConfigFile } from '../utils/fileUtils/index.js';
12
- import logger from '../libs/logger.js';
13
11
  import t from '../i18n/index.js';
12
+ import logger from '../libs/logger.js';
13
+ import { updateCliConfigFile } from '../utils/fileUtils/index.js';
14
14
  const docs = {
15
15
  command: 'lang',
16
16
  describe: `🌐 ${t('lang_describe').d('Set the language of the CLI')}`,
@@ -7,24 +7,48 @@ 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 inquirer from 'inquirer';
11
- import { getApiConfig, getCliConfig, updateCliConfigFile, generateDefaultConfig } from '../../utils/fileUtils/index.js';
10
+ import { isCancel, select as clackSelect, text as clackText } from '@clack/prompts';
12
11
  import chalk from 'chalk';
13
- import { ApiService } from '../../libs/apiService.js';
14
12
  import t from '../../i18n/index.js';
13
+ import { ApiService } from '../../libs/apiService.js';
15
14
  import logger from '../../libs/logger.js';
15
+ import { getApiConfig, getCliConfig, updateCliConfigFile, generateDefaultConfig } from '../../utils/fileUtils/index.js';
16
16
  const login = {
17
17
  command: 'login',
18
18
  describe: `🔑 ${t('login_describe').d('Login to the server')}`,
19
- builder: {},
19
+ builder: (yargs) => {
20
+ var _a, _b;
21
+ return yargs
22
+ .option('access-key-id', {
23
+ alias: 'ak',
24
+ describe: (_a = t('login_option_access_key_id')) === null || _a === void 0 ? void 0 : _a.d('AccessKey ID'),
25
+ type: 'string'
26
+ })
27
+ .option('access-key-secret', {
28
+ alias: 'sk',
29
+ describe: (_b = t('login_option_access_key_secret')) === null || _b === void 0 ? void 0 : _b.d('AccessKey Secret'),
30
+ type: 'string'
31
+ });
32
+ },
20
33
  handler: (argv) => __awaiter(void 0, void 0, void 0, function* () {
21
- handleLogin();
34
+ handleLogin(argv);
22
35
  })
23
36
  };
24
37
  export default login;
25
- export function handleLogin() {
38
+ export function handleLogin(argv) {
26
39
  return __awaiter(this, void 0, void 0, function* () {
27
40
  generateDefaultConfig();
41
+ const accessKeyId = argv === null || argv === void 0 ? void 0 : argv['access-key-id'];
42
+ const accessKeySecret = argv === null || argv === void 0 ? void 0 : argv['access-key-secret'];
43
+ if (accessKeyId && accessKeySecret) {
44
+ yield handleLoginWithAKSK(accessKeyId, accessKeySecret);
45
+ return;
46
+ }
47
+ if (process.env.ESA_ACCESS_KEY_ID && process.env.ESA_ACCESS_KEY_SECRET) {
48
+ logger.log(`🔑 ${t('login_get_from_env').d(`Get AccessKey ID and AccessKey Secret from environment variables.`)}`);
49
+ yield handleLoginWithAKSK(process.env.ESA_ACCESS_KEY_ID, process.env.ESA_ACCESS_KEY_SECRET);
50
+ return;
51
+ }
28
52
  const cliConfig = getCliConfig();
29
53
  if (!cliConfig)
30
54
  return;
@@ -33,21 +57,20 @@ export function handleLogin() {
33
57
  cliConfig.auth.accessKeyId &&
34
58
  cliConfig.auth.accessKeySecret) {
35
59
  const service = yield ApiService.getInstance();
36
- const loginStatus = yield service.checkLogin(false);
60
+ const loginStatus = yield service.checkLogin();
37
61
  if (loginStatus.success) {
38
62
  logger.warn(t('login_already').d('You are already logged in.'));
39
- const action = yield inquirer.prompt([
40
- {
41
- type: 'list',
42
- name: 'action',
43
- message: t('login_existing_credentials_message').d('Existing credentials found. What do you want to do?'),
44
- choices: [
45
- t('login_existing_credentials_action_overwrite').d('Overwrite existing credentials'),
46
- t('common_exit').d('Exit')
47
- ]
48
- }
49
- ]);
50
- if (action.action === t('common_exit').d('Exit')) {
63
+ const selected = (yield clackSelect({
64
+ message: t('login_existing_credentials_message').d('Existing credentials found. What do you want to do?'),
65
+ options: [
66
+ {
67
+ label: t('login_existing_credentials_action_overwrite').d('Overwrite existing credentials'),
68
+ value: 'overwrite'
69
+ },
70
+ { label: t('common_exit').d('Exit'), value: 'exit' }
71
+ ]
72
+ }));
73
+ if (isCancel(selected) || selected === 'exit') {
51
74
  return;
52
75
  }
53
76
  yield getUserInputAuthInfo();
@@ -64,28 +87,45 @@ export function handleLogin() {
64
87
  }
65
88
  });
66
89
  }
90
+ function handleLoginWithAKSK(accessKeyId, accessKeySecret) {
91
+ return __awaiter(this, void 0, void 0, function* () {
92
+ let apiConfig = getApiConfig();
93
+ apiConfig.auth = {
94
+ accessKeyId,
95
+ accessKeySecret
96
+ };
97
+ try {
98
+ yield updateCliConfigFile({
99
+ auth: apiConfig.auth
100
+ });
101
+ const service = yield ApiService.getInstance();
102
+ service.updateConfig(apiConfig);
103
+ const loginStatus = yield service.checkLogin();
104
+ if (loginStatus.success) {
105
+ logger.success(t('login_success').d('Login success!'));
106
+ }
107
+ else {
108
+ logger.error(loginStatus.message || 'Login failed');
109
+ }
110
+ }
111
+ catch (error) {
112
+ logger.error(t('login_failed').d('An error occurred while trying to log in.'));
113
+ }
114
+ });
115
+ }
67
116
  export function getUserInputAuthInfo() {
68
117
  return __awaiter(this, void 0, void 0, function* () {
69
118
  const styledUrl = chalk.underline.blue('https://ram.console.aliyun.com/manage/ak');
70
119
  logger.log(`🔑 ${chalk.underline(t('login_get_ak_sk').d(`Please go to the following link to get your account's AccessKey ID and AccessKey Secret`))}`);
71
120
  logger.log(`👉 ${styledUrl}`);
72
- const answers = yield inquirer.prompt([
73
- {
74
- type: 'input',
75
- name: 'accessKeyId',
76
- message: 'AccessKey ID:'
77
- },
78
- {
79
- type: 'password',
80
- name: 'accessKeySecret',
81
- message: 'AccessKey Secret:',
82
- mask: '*'
83
- }
84
- ]);
121
+ const accessKeyId = (yield clackText({ message: 'AccessKey ID:' }));
122
+ const accessKeySecret = (yield clackText({
123
+ message: 'AccessKey Secret:'
124
+ }));
85
125
  let apiConfig = getApiConfig();
86
126
  apiConfig.auth = {
87
- accessKeyId: answers.accessKeyId,
88
- accessKeySecret: answers.accessKeySecret
127
+ accessKeyId,
128
+ accessKeySecret
89
129
  };
90
130
  try {
91
131
  yield updateCliConfigFile({
@@ -7,21 +7,21 @@ 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 { getCliConfig, updateCliConfigFile } from '../utils/fileUtils/index.js';
11
- import logger from '../libs/logger.js';
12
10
  import t from '../i18n/index.js';
11
+ import logger from '../libs/logger.js';
12
+ import { getCliConfig, updateCliConfigFile } from '../utils/fileUtils/index.js';
13
13
  const logout = {
14
14
  command: 'logout',
15
15
  describe: `📥 ${t('logout_describe').d('Logout')}`,
16
16
  builder: (yargs) => {
17
17
  return yargs;
18
18
  },
19
- handler: (argv) => {
20
- handleLogout(argv);
19
+ handler: () => {
20
+ handleLogout();
21
21
  }
22
22
  };
23
23
  export default logout;
24
- export function handleLogout(argv) {
24
+ export function handleLogout() {
25
25
  return __awaiter(this, void 0, void 0, function* () {
26
26
  let cliConfig = getCliConfig();
27
27
  if (!cliConfig) {