esa-cli 0.0.5 → 1.0.0

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 (85) hide show
  1. package/README.md +32 -149
  2. package/dist/commands/commit/index.js +49 -104
  3. package/dist/commands/commit/prodBuild.js +2 -3
  4. package/dist/commands/common/constant.js +4 -4
  5. package/dist/commands/common/utils.js +419 -0
  6. package/dist/commands/config.js +2 -2
  7. package/dist/commands/deploy/helper.js +43 -49
  8. package/dist/commands/deploy/index.js +51 -174
  9. package/dist/commands/deployments/delete.js +32 -22
  10. package/dist/commands/deployments/index.js +4 -4
  11. package/dist/commands/deployments/list.js +21 -34
  12. package/dist/commands/dev/build.js +3 -3
  13. package/dist/commands/dev/doProcess.js +5 -5
  14. package/dist/commands/dev/ew2/cacheService.js +33 -0
  15. package/dist/commands/dev/ew2/devEntry.js +2 -1
  16. package/dist/commands/dev/ew2/devPack.js +31 -20
  17. package/dist/commands/dev/ew2/kvService.js +50 -0
  18. package/dist/commands/dev/ew2/mock/cache.js +99 -15
  19. package/dist/commands/dev/ew2/mock/kv.js +142 -21
  20. package/dist/commands/dev/ew2/server.js +163 -28
  21. package/dist/commands/dev/index.js +17 -18
  22. package/dist/commands/dev/mockWorker/devPack.js +19 -10
  23. package/dist/commands/dev/mockWorker/server.js +7 -6
  24. package/dist/commands/domain/add.js +4 -4
  25. package/dist/commands/domain/delete.js +3 -3
  26. package/dist/commands/domain/index.js +4 -4
  27. package/dist/commands/domain/list.js +7 -7
  28. package/dist/commands/init/helper.js +654 -21
  29. package/dist/commands/init/index.js +88 -152
  30. package/dist/commands/init/snippets/nextjs/next.config.mjs +6 -0
  31. package/dist/commands/init/snippets/nextjs/next.config.ts +7 -0
  32. package/dist/commands/init/snippets/react-router/react-router.config.ts +7 -0
  33. package/dist/commands/init/template.jsonc +84 -0
  34. package/dist/commands/init/types.js +1 -0
  35. package/dist/commands/lang.js +2 -2
  36. package/dist/commands/login/index.js +74 -34
  37. package/dist/commands/logout.js +6 -6
  38. package/dist/commands/route/add.js +101 -43
  39. package/dist/commands/route/delete.js +6 -6
  40. package/dist/commands/route/helper.js +9 -10
  41. package/dist/commands/route/index.js +4 -4
  42. package/dist/commands/route/list.js +4 -4
  43. package/dist/commands/routine/delete.js +9 -8
  44. package/dist/commands/routine/index.js +6 -5
  45. package/dist/commands/routine/list.js +45 -39
  46. package/dist/commands/site/index.js +3 -3
  47. package/dist/commands/site/list.js +6 -7
  48. package/dist/commands/utils.js +61 -25
  49. package/dist/components/descriptionInput.js +1 -1
  50. package/dist/components/filterSelector.js +1 -1
  51. package/dist/components/mutiLevelSelect.js +19 -20
  52. package/dist/components/mutiSelectTable.js +1 -1
  53. package/dist/components/routeBuilder.js +68 -0
  54. package/dist/components/selectInput.js +2 -3
  55. package/dist/components/selectItem.js +1 -1
  56. package/dist/docs/Commands_en.md +164 -117
  57. package/dist/docs/Commands_zh_CN.md +155 -107
  58. package/dist/docs/Config_en.md +70 -0
  59. package/dist/docs/Config_zh_CN.md +68 -0
  60. package/dist/i18n/index.js +2 -2
  61. package/dist/i18n/locales.json +414 -82
  62. package/dist/index.js +28 -13
  63. package/dist/libs/api.js +3 -6
  64. package/dist/libs/apiService.js +192 -69
  65. package/dist/libs/git/index.js +86 -9
  66. package/dist/libs/interface.js +0 -1
  67. package/dist/libs/logger.js +162 -10
  68. package/dist/libs/service.js +2 -2
  69. package/dist/libs/templates/index.js +1 -1
  70. package/dist/utils/checkAssetsExist.js +80 -0
  71. package/dist/utils/checkDevPort.js +5 -19
  72. package/dist/utils/checkEntryFileExist.js +10 -0
  73. package/dist/utils/checkIsRoutineCreated.js +27 -21
  74. package/dist/utils/checkVersion.js +119 -1
  75. package/dist/utils/command.js +149 -0
  76. package/dist/utils/compress.js +142 -0
  77. package/dist/utils/download.js +8 -8
  78. package/dist/utils/fileMd5.js +1 -1
  79. package/dist/utils/fileUtils/index.js +136 -45
  80. package/dist/utils/installDeno.js +4 -4
  81. package/dist/utils/installEw2.js +9 -9
  82. package/dist/utils/openInBrowser.js +1 -1
  83. package/dist/utils/prompt.js +97 -0
  84. package/package.json +23 -12
  85. package/zh_CN.md +29 -154
@@ -0,0 +1,419 @@
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 chalk from 'chalk';
11
+ import t from '../../i18n/index.js';
12
+ import { ApiService } from '../../libs/apiService.js';
13
+ import logger from '../../libs/logger.js';
14
+ import { ensureRoutineExists } from '../../utils/checkIsRoutineCreated.js';
15
+ import compress from '../../utils/compress.js';
16
+ import { getProjectConfig } from '../../utils/fileUtils/index.js';
17
+ import sleep from '../../utils/sleep.js';
18
+ import { checkIsLoginSuccess } from '../utils.js';
19
+ function normalizeNotFoundStrategy(value) {
20
+ if (!value)
21
+ return undefined;
22
+ const lower = value.toLowerCase();
23
+ if (lower === 'singlepageapplication') {
24
+ return 'SinglePageApplication';
25
+ }
26
+ return value;
27
+ }
28
+ export function commitRoutineWithAssets(requestParams, zipBuffer) {
29
+ return __awaiter(this, void 0, void 0, function* () {
30
+ try {
31
+ const server = yield ApiService.getInstance();
32
+ const apiResult = yield server.CreateRoutineWithAssetsCodeVersion(requestParams);
33
+ if (!apiResult || !apiResult.data.OssPostConfig) {
34
+ return {
35
+ isSuccess: false,
36
+ res: null
37
+ };
38
+ }
39
+ const ossConfig = apiResult.data.OssPostConfig;
40
+ if (!ossConfig.OSSAccessKeyId ||
41
+ !ossConfig.Signature ||
42
+ !ossConfig.Url ||
43
+ !ossConfig.Key ||
44
+ !ossConfig.Policy) {
45
+ console.error('Missing required OSS configuration fields');
46
+ return {
47
+ isSuccess: false,
48
+ res: null
49
+ };
50
+ }
51
+ let uploadSuccess = false;
52
+ for (let i = 0; i < 3; i++) {
53
+ uploadSuccess = yield server.uploadToOss({
54
+ OSSAccessKeyId: ossConfig.OSSAccessKeyId,
55
+ Signature: ossConfig.Signature,
56
+ Url: ossConfig.Url,
57
+ Key: ossConfig.Key,
58
+ Policy: ossConfig.Policy,
59
+ XOssSecurityToken: ossConfig.XOssSecurityToken || ''
60
+ }, zipBuffer);
61
+ if (uploadSuccess) {
62
+ break;
63
+ }
64
+ if (i < 2) {
65
+ yield new Promise((resolve) => setTimeout(resolve, 2000));
66
+ }
67
+ }
68
+ return {
69
+ isSuccess: uploadSuccess,
70
+ res: apiResult
71
+ };
72
+ }
73
+ catch (error) {
74
+ console.error('Error in createRoutineWithAssetsCodeVersion:', error);
75
+ return {
76
+ isSuccess: false,
77
+ res: null
78
+ };
79
+ }
80
+ });
81
+ }
82
+ /**
83
+ * 通用的项目验证和初始化函数
84
+ * 包含目录检查、项目配置获取、登录检查、routine存在性检查
85
+ */
86
+ export function validateAndInitializeProject(name, projectPath) {
87
+ return __awaiter(this, void 0, void 0, function* () {
88
+ const projectConfig = getProjectConfig(projectPath);
89
+ // allow missing config, derive name from cwd when not provided
90
+ const projectName = name ||
91
+ (projectConfig === null || projectConfig === void 0 ? void 0 : projectConfig.name) ||
92
+ process.cwd().split(/[\\/]/).pop();
93
+ if (!projectName) {
94
+ logger.notInProject();
95
+ return null;
96
+ }
97
+ logger.startSubStep('Checking login status');
98
+ const isSuccess = yield checkIsLoginSuccess();
99
+ if (!isSuccess) {
100
+ logger.endSubStep('You are not logged in');
101
+ return null;
102
+ }
103
+ logger.endSubStep('Logged in');
104
+ yield ensureRoutineExists(projectName);
105
+ return { projectConfig: projectConfig || null, projectName };
106
+ });
107
+ }
108
+ /**
109
+ * 通用的routine详情获取函数
110
+ */
111
+ export function getRoutineDetails(projectName) {
112
+ return __awaiter(this, void 0, void 0, function* () {
113
+ const server = yield ApiService.getInstance();
114
+ const req = { Name: projectName };
115
+ return yield server.getRoutine(req, false);
116
+ });
117
+ }
118
+ /**
119
+ * 通用的代码压缩和提交函数
120
+ * 支持assets和普通代码两种模式
121
+ */
122
+ export function generateCodeVersion(projectName_1, description_1, entry_1, assets_1) {
123
+ return __awaiter(this, arguments, void 0, function* (projectName, description, entry, assets, minify = false, projectPath) {
124
+ var _a;
125
+ const { zip, sourceList, dynamicSources } = yield compress(entry, assets, minify, projectPath);
126
+ // Pretty print upload directory tree
127
+ const buildTree = (paths, decorateTopLevel) => {
128
+ const root = { children: new Map(), isFile: false };
129
+ const sorted = [...paths].sort((a, b) => a.localeCompare(b));
130
+ for (const p of sorted) {
131
+ const parts = p.split('/').filter(Boolean);
132
+ let node = root;
133
+ for (let i = 0; i < parts.length; i++) {
134
+ const part = parts[i];
135
+ if (!node.children.has(part)) {
136
+ node.children.set(part, { children: new Map(), isFile: false });
137
+ }
138
+ const child = node.children.get(part);
139
+ if (i === parts.length - 1)
140
+ child.isFile = true;
141
+ node = child;
142
+ }
143
+ }
144
+ const lines = [];
145
+ const render = (node, prefix, depth) => {
146
+ const entries = [...node.children.entries()];
147
+ entries.forEach(([_name, _child], idx) => {
148
+ const isLast = idx === entries.length - 1;
149
+ const connector = isLast ? '└ ' : '├ ';
150
+ const nextPrefix = prefix + (isLast ? ' ' : '│ ');
151
+ const displayName = depth === 0 ? decorateTopLevel(_name) : _name;
152
+ lines.push(prefix + connector + displayName);
153
+ render(_child, nextPrefix, depth + 1);
154
+ });
155
+ };
156
+ render(root, '', 0);
157
+ return lines.length ? lines : ['-'];
158
+ };
159
+ const header = chalk.hex('#22c55e')('UPLOAD') + ' Files to be uploaded (source paths)';
160
+ logger.block();
161
+ logger.log(header);
162
+ const dynamicSet = new Set(dynamicSources);
163
+ const LIMIT = 300;
164
+ const staticPaths = sourceList
165
+ .filter((p) => !dynamicSet.has(p))
166
+ .sort((a, b) => a.localeCompare(b));
167
+ const dynamicPaths = sourceList
168
+ .filter((p) => dynamicSet.has(p))
169
+ .sort((a, b) => a.localeCompare(b));
170
+ let omitted = 0;
171
+ let shownStatic = staticPaths;
172
+ if (staticPaths.length > LIMIT) {
173
+ shownStatic = staticPaths.slice(0, LIMIT);
174
+ omitted = staticPaths.length - LIMIT;
175
+ }
176
+ // Compute top-level markers based on whether a top-level bucket contains dynamic/static files
177
+ const topLevelStats = new Map();
178
+ const addStat = (p, isDynamic) => {
179
+ const top = p.split('/')[0] || p;
180
+ const stat = topLevelStats.get(top) || {
181
+ hasDynamic: false,
182
+ hasStatic: false
183
+ };
184
+ if (isDynamic)
185
+ stat.hasDynamic = true;
186
+ else
187
+ stat.hasStatic = true;
188
+ topLevelStats.set(top, stat);
189
+ };
190
+ dynamicPaths.forEach((p) => addStat(p, true));
191
+ shownStatic.forEach((p) => addStat(p, false));
192
+ const dynamicMarker = chalk.bold.yellowBright(' (dynamic)');
193
+ const staticMarker = chalk.bold.greenBright(' (static)');
194
+ const decorateTopLevel = (name) => {
195
+ const stat = topLevelStats.get(name);
196
+ if (!stat)
197
+ return name;
198
+ if (stat.hasDynamic && stat.hasStatic) {
199
+ return `${name}${dynamicMarker}${staticMarker}`;
200
+ }
201
+ if (stat.hasDynamic)
202
+ return `${name}${dynamicMarker}`;
203
+ if (stat.hasStatic)
204
+ return `${name}${staticMarker}`;
205
+ return name;
206
+ };
207
+ const combined = [...dynamicPaths, ...shownStatic];
208
+ const treeLines = buildTree(combined, decorateTopLevel);
209
+ for (const line of treeLines) {
210
+ logger.log(line);
211
+ }
212
+ if (omitted > 0) {
213
+ const note = chalk.gray(`Only show the first ${LIMIT} static files, omitted ${omitted} files`);
214
+ logger.log(note);
215
+ }
216
+ logger.block();
217
+ const projectConfig = getProjectConfig(projectPath);
218
+ const notFoundStrategy = normalizeNotFoundStrategy((_a = projectConfig === null || projectConfig === void 0 ? void 0 : projectConfig.assets) === null || _a === void 0 ? void 0 : _a.notFoundStrategy);
219
+ logger.startSubStep('Generating code version');
220
+ const requestParams = {
221
+ Name: projectName,
222
+ CodeDescription: description,
223
+ ExtraInfo: JSON.stringify({ Source: 'CLI' })
224
+ };
225
+ if (notFoundStrategy) {
226
+ requestParams.ConfOptions = {
227
+ NotFoundStrategy: notFoundStrategy
228
+ };
229
+ }
230
+ const res = yield commitRoutineWithAssets(requestParams, zip === null || zip === void 0 ? void 0 : zip.toBuffer());
231
+ if (res === null || res === void 0 ? void 0 : res.isSuccess) {
232
+ return {
233
+ isSuccess: true,
234
+ res: res === null || res === void 0 ? void 0 : res.res
235
+ };
236
+ }
237
+ else {
238
+ return {
239
+ isSuccess: false,
240
+ res: null
241
+ };
242
+ }
243
+ });
244
+ }
245
+ /**
246
+ * 根据 env 在一个或多个环境部署
247
+ */
248
+ export function deployToEnvironments(name, codeVersion, env) {
249
+ return __awaiter(this, void 0, void 0, function* () {
250
+ if (env === 'all') {
251
+ const isStagingSuccess = yield deployCodeVersion(name, codeVersion, 'staging');
252
+ const isProdSuccess = yield deployCodeVersion(name, codeVersion, 'production');
253
+ return isStagingSuccess && isProdSuccess;
254
+ }
255
+ return yield deployCodeVersion(name, codeVersion, env);
256
+ });
257
+ }
258
+ /**
259
+ * 通用的快速部署函数
260
+ * 结合了压缩、提交和部署的完整流程
261
+ */
262
+ export function commitAndDeployVersion(projectName_1, scriptEntry_1, assets_1) {
263
+ return __awaiter(this, arguments, void 0, function* (projectName, scriptEntry, assets, description = '', projectPath, env = 'production', minify = false, version) {
264
+ var _a, _b, _c;
265
+ const projectInfo = yield validateAndInitializeProject(projectName, projectPath);
266
+ if (!projectInfo) {
267
+ return false;
268
+ }
269
+ const { projectConfig } = projectInfo;
270
+ // 2) Use existing version or generate a new one
271
+ if (version) {
272
+ logger.startSubStep(`Using existing version ${version}`);
273
+ const deployed = yield deployToEnvironments(projectInfo.projectName, version, env);
274
+ logger.endSubStep(deployed ? 'Deploy finished' : 'Deploy failed');
275
+ return deployed;
276
+ }
277
+ const res = yield generateCodeVersion(projectInfo.projectName, description, scriptEntry || (projectConfig === null || projectConfig === void 0 ? void 0 : projectConfig.entry), assets || ((_a = projectConfig === null || projectConfig === void 0 ? void 0 : projectConfig.assets) === null || _a === void 0 ? void 0 : _a.directory), minify || (projectConfig === null || projectConfig === void 0 ? void 0 : projectConfig.minify), projectPath);
278
+ const isCommitSuccess = res === null || res === void 0 ? void 0 : res.isSuccess;
279
+ if (!isCommitSuccess) {
280
+ logger.endSubStep('Generate version failed');
281
+ return false;
282
+ }
283
+ const codeVersion = (_c = (_b = res === null || res === void 0 ? void 0 : res.res) === null || _b === void 0 ? void 0 : _b.data) === null || _c === void 0 ? void 0 : _c.CodeVersion;
284
+ if (!codeVersion) {
285
+ logger.endSubStep('Missing CodeVersion in response');
286
+ return false;
287
+ }
288
+ logger.endSubStep(`Version generated: ${codeVersion}`);
289
+ // 3) Deploy to specified environment(s)
290
+ const deployed = yield deployToEnvironments(projectInfo.projectName, codeVersion, env);
291
+ return deployed;
292
+ });
293
+ }
294
+ /**
295
+ * 通用的版本部署函数
296
+ */
297
+ export function deployCodeVersion(name, codeVersion, environment) {
298
+ return __awaiter(this, void 0, void 0, function* () {
299
+ const server = yield ApiService.getInstance();
300
+ // Ensure the committed code version is ready before deploying
301
+ const isReady = yield waitForCodeVersionReady(name, codeVersion, environment);
302
+ if (!isReady) {
303
+ logger.error('The code version is not ready for deployment.');
304
+ return false;
305
+ }
306
+ const res = yield server.createRoutineCodeDeployment({
307
+ Name: name,
308
+ CodeVersions: [{ Percentage: 100, CodeVersion: codeVersion }],
309
+ Strategy: 'percentage',
310
+ Env: environment
311
+ });
312
+ if (res) {
313
+ return true;
314
+ }
315
+ else {
316
+ return false;
317
+ }
318
+ });
319
+ }
320
+ /**
321
+ * Poll routine code version status until it becomes ready
322
+ */
323
+ export function waitForCodeVersionReady(name_1, codeVersion_1, env_1) {
324
+ return __awaiter(this, arguments, void 0, function* (name, codeVersion, env, timeoutMs = 5 * 60 * 1000, intervalMs = 1000) {
325
+ var _a, _b;
326
+ if (!name || !codeVersion) {
327
+ return false;
328
+ }
329
+ const server = yield ApiService.getInstance();
330
+ const start = Date.now();
331
+ logger.startSubStep(`Waiting for code version ${codeVersion} to be ready...`);
332
+ while (Date.now() - start < timeoutMs) {
333
+ try {
334
+ const info = yield server.getRoutineCodeVersionInfo({
335
+ Name: name,
336
+ CodeVersion: codeVersion
337
+ });
338
+ const status = (_b = (_a = info === null || info === void 0 ? void 0 : info.data) === null || _a === void 0 ? void 0 : _a.Status) === null || _b === void 0 ? void 0 : _b.toLowerCase();
339
+ if (status === 'init') {
340
+ yield sleep(intervalMs);
341
+ continue;
342
+ }
343
+ else if (status === 'available') {
344
+ logger.endSubStep(`Code version ${chalk.cyan(codeVersion)} is deployed to ${env}.`);
345
+ return true;
346
+ }
347
+ else {
348
+ logger.error(`Code version ${chalk.cyan(codeVersion)} build ${status}.`);
349
+ return false;
350
+ }
351
+ }
352
+ catch (e) {
353
+ // swallow and retry until timeout
354
+ }
355
+ }
356
+ logger.error(`⏰ Waiting for code version ${chalk.cyan(codeVersion)} timed out.`);
357
+ return false;
358
+ });
359
+ }
360
+ /**
361
+ * 通用的部署成功显示函数
362
+ * 显示部署成功信息、访问链接和后续操作指南
363
+ */
364
+ export function displayDeploySuccess(projectName_1) {
365
+ return __awaiter(this, arguments, void 0, function* (projectName, showDomainGuide = true, showRouteGuide = true) {
366
+ var _a;
367
+ const service = yield ApiService.getInstance();
368
+ const res = yield service.getRoutine({ Name: projectName });
369
+ const defaultUrl = (_a = res === null || res === void 0 ? void 0 : res.data) === null || _a === void 0 ? void 0 : _a.DefaultRelatedRecord;
370
+ const visitUrl = defaultUrl ? 'https://' + defaultUrl : '';
371
+ const accent = chalk.hex('#7C3AED');
372
+ const label = chalk.hex('#22c55e');
373
+ const subtle = chalk.gray;
374
+ const title = `${chalk.bold('🚀 ')}${chalk.bold(t('init_deploy_success').d('Deploy Success'))}`;
375
+ const lineUrl = `${label('URL')} ${visitUrl ? chalk.yellowBright(visitUrl) : subtle('-')}`;
376
+ const lineProject = `${label('APP')} ${chalk.cyan(projectName || '-')}`;
377
+ const lineCd = projectName
378
+ ? `${label('TIP')} ${t('deploy_success_cd').d('Enter project directory')}: ${chalk.green(`cd ${projectName}`)}`
379
+ : '';
380
+ const guides = [];
381
+ if (showDomainGuide) {
382
+ guides.push(`${label('TIP')} ${t('deploy_success_guide').d('Add a custom domain')}: ${chalk.green('esa-cli domain add <DOMAIN>')}`);
383
+ }
384
+ if (showRouteGuide) {
385
+ guides.push(`${label('TIP')} ${t('deploy_success_guide_2').d('Add routes for a site')}: ${chalk.green('esa-cli route add -r <ROUTE> -s <SITE>')}`);
386
+ }
387
+ const tip = `${subtle(t('deploy_url_warn').d('The domain may take some time to take effect, please try again later.'))}`;
388
+ const lines = [
389
+ accent(title),
390
+ '',
391
+ lineProject,
392
+ lineUrl,
393
+ lineCd ? '' : '',
394
+ lineCd || '',
395
+ guides.length ? '' : '',
396
+ ...guides,
397
+ guides.length ? '' : '',
398
+ tip
399
+ ];
400
+ const stripAnsi = (s) => s.replace(/\x1B\[[0-?]*[ -\/]*[@-~]/g, '');
401
+ const contentWidth = Math.max(...lines.map((l) => stripAnsi(l).length));
402
+ const borderColor = chalk.hex('#00D4FF').bold;
403
+ const top = `${borderColor('╔')}${borderColor('═'.repeat(contentWidth + 2))}${borderColor('╗')}`;
404
+ const bottom = `${borderColor('╚')}${borderColor('═'.repeat(contentWidth + 2))}${borderColor('╝')}`;
405
+ const boxLines = [
406
+ top,
407
+ ...lines.map((l) => {
408
+ const pad = ' '.repeat(contentWidth - stripAnsi(l).length);
409
+ const left = borderColor('║');
410
+ const right = borderColor('║');
411
+ return `${left} ${l}${pad} ${right}`;
412
+ }),
413
+ bottom
414
+ ];
415
+ logger.block();
416
+ boxLines.forEach((l) => logger.log(l));
417
+ logger.block();
418
+ });
419
+ }
@@ -1,8 +1,8 @@
1
1
  import fs from 'fs';
2
2
  import spawn from 'cross-spawn';
3
- import { projectConfigPath, cliConfigPath } from '../utils/fileUtils/index.js';
4
3
  import t from '../i18n/index.js';
5
4
  import logger from '../libs/logger.js';
5
+ import { projectConfigPath, cliConfigPath } from '../utils/fileUtils/index.js';
6
6
  const editConfigFile = (configPath) => {
7
7
  const editor = process.env.EDITOR || 'vi';
8
8
  spawn(editor, [configPath], {
@@ -26,7 +26,7 @@ const check = {
26
26
  type: 'boolean',
27
27
  default: false
28
28
  })
29
- .usage(`${t('common_usage').d('Usage')}: esa config [-l | -g]`)
29
+ .usage(`${t('common_usage').d('Usage')}: esa-cli config [-l | -g]`)
30
30
  .check((argv) => {
31
31
  if (!argv.local && !argv.global) {
32
32
  yargs.showHelp();
@@ -7,27 +7,24 @@ 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 chalk from 'chalk';
11
+ import moment from 'moment';
10
12
  import SelectItems from '../../components/selectInput.js';
11
- import { yesNoPrompt } from '../../components/yesNoPrompt.js';
13
+ import t from '../../i18n/index.js';
12
14
  import { PublishType } from '../../libs/interface.js';
13
- import { ApiService } from '../../libs/apiService.js';
14
- import { descriptionInput } from '../../components/descriptionInput.js';
15
- import { readEdgeRoutineFile } from '../../utils/fileUtils/index.js';
16
- import { createEdgeRoutine, releaseOfficialVersion, uploadEdgeRoutineCode } from '../commit/index.js';
17
15
  import logger from '../../libs/logger.js';
18
- import t from '../../i18n/index.js';
19
- import prodBuild from '../commit/prodBuild.js';
16
+ import promptParameter from '../../utils/prompt.js';
20
17
  export function yesNoPromptAndExecute(message, execute) {
21
- return new Promise((resolve) => {
22
- yesNoPrompt((item) => __awaiter(this, void 0, void 0, function* () {
23
- if (item.value === 'yes') {
24
- const result = yield execute();
25
- resolve(result);
26
- }
27
- else {
28
- resolve(false);
29
- }
30
- }), message);
18
+ return __awaiter(this, void 0, void 0, function* () {
19
+ const confirmed = (yield promptParameter({
20
+ type: 'confirm',
21
+ question: message,
22
+ label: 'Confirm',
23
+ defaultValue: true
24
+ }));
25
+ if (!confirmed)
26
+ return false;
27
+ return yield execute();
31
28
  });
32
29
  }
33
30
  export function promptSelectVersion(versionList) {
@@ -47,15 +44,14 @@ export function promptSelectVersion(versionList) {
47
44
  SelectItems({ items, handleSelect: handleSelection });
48
45
  });
49
46
  }
50
- export function displaySelectDeployType() {
47
+ export function displaySelectDeployEnv() {
51
48
  logger.log(`📃 ${t('deploy_env_select_description').d('Please select which environment you want to deploy')}`);
52
49
  const selectItems = [
53
50
  { label: t('deploy_env_staging').d('Staging'), value: PublishType.Staging },
54
51
  {
55
52
  label: t('deploy_env_production').d('Production'),
56
53
  value: PublishType.Production
57
- },
58
- { label: t('deploy_env_canary').d('Canary'), value: PublishType.Canary }
54
+ }
59
55
  ];
60
56
  return new Promise((resolve) => {
61
57
  const handleSelection = (item) => __awaiter(this, void 0, void 0, function* () {
@@ -64,35 +60,33 @@ export function displaySelectDeployType() {
64
60
  SelectItems({ items: selectItems, handleSelect: handleSelection });
65
61
  });
66
62
  }
67
- export function createAndDeployVersion(projectConfig_1) {
68
- return __awaiter(this, arguments, void 0, function* (projectConfig, createUnstable = false, customEntry) {
69
- try {
70
- const server = yield ApiService.getInstance();
71
- const description = yield descriptionInput(createUnstable
72
- ? `🖊️ ${t('deploy_description_routine').d('Enter the description of the routine')}:`
73
- : `🖊️ ${t('deploy_description_version').d('Enter the description of the code version')}:`, false);
74
- yield prodBuild(false, customEntry);
75
- const code = readEdgeRoutineFile();
76
- const edgeRoutine = {
77
- name: projectConfig.name,
78
- code: code || '',
79
- description: description
80
- };
81
- if (createUnstable) {
82
- return yield createEdgeRoutine(edgeRoutine);
83
- }
84
- else {
85
- const uploadResult = yield uploadEdgeRoutineCode(edgeRoutine);
86
- if (!uploadResult) {
87
- return false;
88
- }
89
- return yield releaseOfficialVersion(edgeRoutine);
90
- }
91
- }
92
- catch (error) {
93
- logger.error(`
94
- ${t('deploy_error').d('An error occurred during the creation or publishing process')}: ${error}`);
95
- return false;
63
+ export function displayVersionList(allVersions, stagingVersions, productionVersions) {
64
+ return __awaiter(this, void 0, void 0, function* () {
65
+ var _a, _b, _c;
66
+ logger.log(`${chalk.bgYellow('Active')} ${t('deploy_env_staging').d('Staging')}`);
67
+ logger.log(`${chalk.bgGreen('Active')} ${t('deploy_env_production').d('Production')}`);
68
+ const data = [];
69
+ for (let i = 0; i < allVersions.length; i++) {
70
+ const version = allVersions[i];
71
+ const createTime = moment(version.createTime).format('YYYY/MM/DD HH:mm:ss');
72
+ const tags = [
73
+ stagingVersions.includes((_a = version.codeVersion) !== null && _a !== void 0 ? _a : '')
74
+ ? chalk.bgYellow('Active')
75
+ : '',
76
+ productionVersions.includes((_b = version.codeVersion) !== null && _b !== void 0 ? _b : '')
77
+ ? chalk.bgGreen('Active')
78
+ : ''
79
+ ];
80
+ data.push([
81
+ `${version.codeVersion} ${tags.join(' ')}`,
82
+ createTime,
83
+ (_c = version.codeDescription) !== null && _c !== void 0 ? _c : ''
84
+ ]);
96
85
  }
86
+ logger.table([
87
+ t('deploy_table_header_version').d('Version'),
88
+ t('deploy_table_header_created').d('Created'),
89
+ t('deploy_table_header_description').d('Description')
90
+ ], data);
97
91
  });
98
92
  }