esa-cli 0.0.2-beta.0 → 0.0.2-beta.10

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.
package/README.md CHANGED
@@ -7,7 +7,7 @@ English | [简体中文](./zh_CN.md)
7
7
  #### Reference
8
8
 
9
9
  - [Edge Security Acceleration (ESA)](https://www.aliyun.com/product/esa)
10
- - [What is EdgeRoutine?](https://help.aliyun.com/document_detail/2710021.html)
10
+ - [What is EdgeRoutine?](https://help.aliyun.com/document_detail/2710021.html)
11
11
 
12
12
  > **Note**: **In version 0.0.2 and above, the local development mode of the ESA CLI has been replaced with the same runtime as the ESA edge functions, ensuring that its actual behavior now matches the live environment. We invite you to experience it.**
13
13
 
@@ -15,7 +15,6 @@ import { ApiService } from '../../libs/apiService.js';
15
15
  import prodBuild from './prodBuild.js';
16
16
  import logger from '../../libs/logger.js';
17
17
  import t from '../../i18n/index.js';
18
- import { exit } from 'process';
19
18
  const commit = {
20
19
  command: 'commit [entry]',
21
20
  describe: `📥 ${t('commit_describe').d('Commit your code, save as a new version')}`,
@@ -87,7 +86,6 @@ export function handleCommit(argv) {
87
86
  return;
88
87
  yield releaseOfficialVersion(edgeRoutine);
89
88
  }
90
- exit(0);
91
89
  }
92
90
  catch (error) {
93
91
  logger.error(`${t('common_error_occurred').d('An error occurred:')} ${error}`);
@@ -126,6 +124,7 @@ export function uploadEdgeRoutineCode(edgeRoutine) {
126
124
  return true;
127
125
  }
128
126
  catch (error) {
127
+ logger.error('123');
129
128
  logger.error(`${t('common_error_occurred').d('An error occurred:')} ${error}`);
130
129
  process.exit(0);
131
130
  }
@@ -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
  {
@@ -81,7 +81,7 @@ const generateEntry = (id, projectEntry, userRoot) => __awaiter(void 0, void 0,
81
81
  const destPath = path.resolve(mockDevDir, file);
82
82
  yield fs.promises.copyFile(srcPath, destPath);
83
83
  }
84
- return fs.promises.writeFile(devEntry, devEntryTempFile.replace(/'\$userPath'/g, `'${projectEntry}'`));
84
+ return fs.promises.writeFile(devEntry, devEntryTempFile.replace(/'\$userPath'/g, `'${projectEntry.replace(/\\/g, '/')}'`));
85
85
  });
86
86
  // 前期准备
87
87
  const prepare = (configPath, entry, port, localUpstream, userRoot) => __awaiter(void 0, void 0, void 0, function* () {
@@ -106,27 +106,13 @@ const prepare = (configPath, entry, port, localUpstream, userRoot) => __awaiter(
106
106
  if (currentIds[0] && /^\d+$/.test(currentIds[0])) {
107
107
  // 删除没有用到的入口
108
108
  for (let currentId of currentIds) {
109
- const useful = yield checkPort(currentConfigObj[currentId].port);
110
- if (useful) {
111
- const unusedEntry = path.resolve(userRoot, `.dev/index-${currentId}.js`);
112
- const unusedTemp = path.resolve(userRoot, `.dev/devEntry-${currentId}.js`);
113
- const unusedConfig = path.resolve(userRoot, `.dev/config-${currentId}.toml`);
114
- if (fs.existsSync(unusedEntry)) {
115
- fs.rmSync(unusedEntry, {
116
- force: true,
117
- recursive: true,
118
- maxRetries: 5
119
- });
120
- }
121
- if (fs.existsSync(unusedTemp)) {
122
- fs.rmSync(unusedTemp, {
123
- force: true,
124
- recursive: true,
125
- maxRetries: 5
126
- });
127
- }
128
- if (fs.existsSync(unusedConfig)) {
129
- fs.rmSync(unusedConfig, {
109
+ const unused = yield checkPort(currentConfigObj[currentId].port);
110
+ if (unused) {
111
+ const devDir = path.resolve(userRoot, '.dev');
112
+ const files = fs.readdirSync(devDir);
113
+ const filesToDelete = files.filter((file) => file.includes(currentId));
114
+ for (const file of filesToDelete) {
115
+ fs.rmSync(path.resolve(devDir, file), {
130
116
  force: true,
131
117
  recursive: true,
132
118
  maxRetries: 5
@@ -164,8 +150,7 @@ const devPack = (...args_1) => __awaiter(void 0, [...args_1], void 0, function*
164
150
  .then(() => {
165
151
  logger.ora.succeed(t('dev_pack_config_success').d('Config created successfully'));
166
152
  return devBuild({
167
- minify,
168
- isNode: true
153
+ minify
169
154
  });
170
155
  })
171
156
  .then(() => {
@@ -128,7 +128,6 @@ class Ew2Server {
128
128
  }
129
129
  createServer() {
130
130
  this.server = http.createServer((req, res) => __awaiter(this, void 0, void 0, function* () {
131
- var _a;
132
131
  try {
133
132
  const host = req.headers.host;
134
133
  const url = req.url;
@@ -148,18 +147,20 @@ class Ew2Server {
148
147
  // 解决 gzip 兼容性问题,防止net::ERR_CONTENT_DECODING_FAILED
149
148
  workerHeaders['content-encoding'] = 'identity';
150
149
  if (workerRes.body) {
151
- if ((_a = workerRes.headers.get('content-type')) === null || _a === void 0 ? void 0 : _a.includes('text/')) {
152
- const text = yield workerRes.text();
153
- // 出现换行符之类会导致 content-length 不一致
154
- workerHeaders['content-length'] =
155
- Buffer.byteLength(text).toString();
156
- res.writeHead(workerRes.status, workerHeaders);
157
- res.end(text);
158
- }
159
- else {
160
- res.writeHead(workerRes.status, workerHeaders);
161
- workerRes.body.pipe(res);
162
- }
150
+ // if (workerRes.headers.get('content-type')?.includes('text/')) {
151
+ // const text = await workerRes.text();
152
+ // // 出现换行符之类会导致 content-length 不一致
153
+ // workerHeaders['content-length'] =
154
+ // Buffer.byteLength(text).toString();
155
+ // console.log(workerHeaders['content-length']);
156
+ // res.writeHead(workerRes.status, workerHeaders);
157
+ // res.end(text);
158
+ // } else {
159
+ // res.writeHead(workerRes.status, workerHeaders);
160
+ // workerRes.body.pipe(res);
161
+ // }
162
+ res.writeHead(workerRes.status, workerHeaders);
163
+ workerRes.body.pipe(res);
163
164
  logger.log(`[ESA Dev] ${req.method} ${url} ${getColorForStatusCode(workerRes.status, workerRes.statusText)}`);
164
165
  }
165
166
  else {
@@ -27,7 +27,8 @@ import checkAndInputPort from '../../utils/checkDevPort.js';
27
27
  import { checkOS, Platforms } from '../../utils/checkOS.js';
28
28
  let yargsIns;
29
29
  const OS = checkOS();
30
- const useEw2 = OS === Platforms.AppleArm || Platforms.AppleIntel || Platforms.LinuxX86;
30
+ const EW2OS = [Platforms.AppleArm, Platforms.AppleIntel, Platforms.LinuxX86];
31
+ const useEw2 = EW2OS.includes(OS);
31
32
  const dev = {
32
33
  command: 'dev [entry]',
33
34
  describe: `💻 ${t('dev_describe').d('Start a local server for developing your routine')}`,
@@ -35,7 +35,7 @@ const generateEntry = (id, projectEntry, userRoot) => __awaiter(void 0, void 0,
35
35
  const destPath = path.resolve(mockDevDir, file);
36
36
  yield fs.promises.copyFile(srcPath, destPath);
37
37
  }
38
- return fs.promises.writeFile(devEntry, devEntryTempFile.replace(/'\$userPath'/g, `'${projectEntry}'`));
38
+ return fs.promises.writeFile(devEntry, devEntryTempFile.replace(/'\$userPath'/g, `'${projectEntry.replace(/\\/g, '/')}'`));
39
39
  });
40
40
  const prepare = (configPath, entry, port, localUpstream, userRoot) => __awaiter(void 0, void 0, void 0, function* () {
41
41
  const options = {};
@@ -51,22 +51,24 @@ const prepare = (configPath, entry, port, localUpstream, userRoot) => __awaiter(
51
51
  .readFileSync(configPath, 'utf-8')
52
52
  .replace('export default ', '');
53
53
  const currentConfigObj = JSON.parse(currentConfig);
54
- const cIds = Object.keys(currentConfigObj);
55
- if (cIds[0] && /^\d+$/.test(cIds[0])) {
56
- for (let cid of cIds) {
57
- const useful = yield checkPort(currentConfigObj[cid].port);
58
- if (useful) {
59
- const unusedEntry = path.resolve(userRoot, `.dev/index-${cid}.js`);
60
- const unusedTemp = path.resolve(userRoot, `.dev/devEntry-${cid}.js`);
61
- if (fs.existsSync(unusedEntry)) {
62
- fs.rmSync(unusedEntry);
63
- }
64
- if (fs.existsSync(unusedTemp)) {
65
- fs.rmSync(unusedTemp);
54
+ const currentIds = Object.keys(currentConfigObj);
55
+ if (currentIds[0] && /^\d+$/.test(currentIds[0])) {
56
+ for (let currentId of currentIds) {
57
+ const unused = yield checkPort(currentConfigObj[currentId].port);
58
+ if (unused) {
59
+ const devDir = path.resolve(userRoot, '.dev');
60
+ const files = fs.readdirSync(devDir);
61
+ const filesToDelete = files.filter((file) => file.includes(currentId));
62
+ for (const file of filesToDelete) {
63
+ fs.rmSync(path.resolve(devDir, file), {
64
+ force: true,
65
+ recursive: true,
66
+ maxRetries: 5
67
+ });
66
68
  }
67
69
  }
68
70
  else {
69
- options[cid] = currentConfigObj[cid];
71
+ options[currentId] = currentConfigObj[currentId];
70
72
  }
71
73
  }
72
74
  }
@@ -0,0 +1,113 @@
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}`).toString();
78
+ const match = versionInfo.match(new RegExp(`(${packageName})@([0-9.]+)`));
79
+ const currentVersion = match ? match[2] : '';
80
+ // 获取最新版本
81
+ const latestVersion = execSync(`npm view ${packageName} version`)
82
+ .toString()
83
+ .trim();
84
+ if (currentVersion !== latestVersion) {
85
+ logger.log(t('display_current_esa_template_version').d(`Current esa-template version:`) +
86
+ chalk.green(currentVersion) +
87
+ ' ' +
88
+ t('display_latest_esa_template_version').d(`Latest esa-template version:`) +
89
+ chalk.green(latestVersion));
90
+ const { isUpdate } = yield inquirer.prompt({
91
+ type: 'confirm',
92
+ name: 'isUpdate',
93
+ message: t('is_update_to_latest_version').d('Do you want to update templates to latest version?')
94
+ });
95
+ if (isUpdate) {
96
+ execSync(`rm -rf node_modules/${packageName} &&rm -rf package-lock.json &&npm install ${packageName}@latest`, {
97
+ cwd: packageJsonPath
98
+ });
99
+ logger.log(t('updated_esa_template_to_latest_version', { packageName }).d(`${packageName} updated successfully`));
100
+ }
101
+ }
102
+ else {
103
+ logger.log(t('esa_template_is_latest_version', { packageName }).d(`${packageName} is latest.`));
104
+ }
105
+ }
106
+ catch (error) {
107
+ console.log(error);
108
+ if (error instanceof Error) {
109
+ logger.error('检测和更新包时发生错误,跳过更新模版');
110
+ }
111
+ }
112
+ });
113
+ }