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.
@@ -0,0 +1,182 @@
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 fetch from 'node-fetch';
11
+ import * as fs from 'fs/promises';
12
+ import * as path from 'path';
13
+ import os from 'os';
14
+ import AdmZip from 'adm-zip';
15
+ import { exec } from 'child_process';
16
+ import { promisify } from 'util';
17
+ import t from '../i18n/index.js';
18
+ import logger from '../libs/logger.js';
19
+ import chalk from 'chalk';
20
+ const execAsync = promisify(exec);
21
+ function getBinDir() {
22
+ const home = os.homedir();
23
+ return path.join(home || '', '.deno', 'bin');
24
+ }
25
+ /**
26
+ * 下载文件
27
+ * @param url 远程文件URL
28
+ * @param dest 本地保存路径
29
+ */
30
+ export function downloadFile(url, dest) {
31
+ return __awaiter(this, void 0, void 0, function* () {
32
+ const response = yield fetch(url);
33
+ if (!response.ok) {
34
+ throw new Error(`Error downloading file: ${response.status} ${response.statusText}`);
35
+ }
36
+ const fileStream = yield fs.open(dest, 'w');
37
+ return new Promise((resolve, reject) => {
38
+ var _a, _b;
39
+ (_a = response.body) === null || _a === void 0 ? void 0 : _a.pipe(fileStream.createWriteStream());
40
+ (_b = response.body) === null || _b === void 0 ? void 0 : _b.on('error', (err) => {
41
+ fileStream.close();
42
+ reject(err);
43
+ });
44
+ fileStream.createWriteStream().on('finish', () => {
45
+ fileStream.close();
46
+ resolve();
47
+ });
48
+ });
49
+ });
50
+ }
51
+ /**
52
+ * 解压Zip文件 adm 是同步的
53
+ * @param zipPath Zip文件路径
54
+ * @param extractPath 解压目标目录
55
+ */
56
+ export function unzipFile(zipPath, extractPath) {
57
+ const zip = new AdmZip(zipPath);
58
+ zip.extractAllTo(extractPath, true);
59
+ logger.info(`UnzipFile success: from ${zipPath} to ${extractPath}`);
60
+ }
61
+ /**
62
+ * 获取用户的 PATH 环境变量(win下专用)
63
+ * @returns 用户 PATH
64
+ */
65
+ function getUserPath() {
66
+ return __awaiter(this, void 0, void 0, function* () {
67
+ const { stdout } = yield execAsync('reg query "HKCU\\Environment" /v Path');
68
+ const match = stdout.match(/Path\s+REG_EXPAND_SZ\s+(.*)/i);
69
+ if (match && match[1]) {
70
+ return match[1].trim();
71
+ }
72
+ return '';
73
+ });
74
+ }
75
+ /**
76
+ * 检查 BinDir 是否在用户的 PATH 中(win下专用)
77
+ * @param binDir BinDir 路径
78
+ * @returns 是否包含
79
+ */
80
+ function isBinDirInPath(binDir) {
81
+ return __awaiter(this, void 0, void 0, function* () {
82
+ const userPath = yield getUserPath();
83
+ return userPath
84
+ .split(';')
85
+ .map((p) => p.toLowerCase())
86
+ .includes(binDir.toLowerCase());
87
+ });
88
+ }
89
+ /**
90
+ * 将 BinDir 添加到用户的 PATH 环境变量(win下专用)
91
+ * @param binDir BinDir 路径
92
+ */
93
+ function addBinDirToPath(binDir) {
94
+ return __awaiter(this, void 0, void 0, function* () {
95
+ // 使用 setx 添加到 PATH
96
+ // setx 对 PATH 的长度有2047字符的限制
97
+ const command = `setx Path "%Path%;${binDir}"`;
98
+ try {
99
+ yield execAsync(command);
100
+ logger.info(`Path add success: ${binDir}`);
101
+ }
102
+ catch (error) {
103
+ throw new Error(`Add BinDir to Path failed: ${error}`);
104
+ }
105
+ });
106
+ }
107
+ export function downloadRuntimeAndUnzipForWindows() {
108
+ return __awaiter(this, void 0, void 0, function* () {
109
+ try {
110
+ const BinDir = getBinDir();
111
+ const DenoZip = path.join(BinDir, 'deno.zip');
112
+ const Target = 'x86_64-pc-windows-msvc';
113
+ const DownloadUrl = `http://esa-runtime.myalicdn.com/runtime/deno-${Target}.zip`;
114
+ logger.ora.start('Downloading...');
115
+ try {
116
+ yield fs.mkdir(BinDir, { recursive: true });
117
+ }
118
+ catch (error) {
119
+ const err = error;
120
+ logger.ora.fail();
121
+ logger.error(`mkdir error ${BinDir}: ${err.message}`);
122
+ process.exit(1);
123
+ }
124
+ try {
125
+ yield downloadFile(DownloadUrl, DenoZip);
126
+ }
127
+ catch (error) {
128
+ const err = error;
129
+ logger.ora.fail();
130
+ logger.error(`${t('deno_download_failed').d('Download failed')}: ${err.message}`);
131
+ process.exit(1);
132
+ }
133
+ logger.info(`Unzip file to: ${BinDir}`);
134
+ try {
135
+ logger.ora.text = 'Unzip...';
136
+ unzipFile(DenoZip, BinDir);
137
+ }
138
+ catch (error) {
139
+ const err = error;
140
+ logger.ora.fail();
141
+ logger.error(`${t('deno_unzip_failed').d('Unzip failed')}: ${err.message}`);
142
+ process.exit(1);
143
+ }
144
+ try {
145
+ logger.ora.text = 'Deleting temp file...';
146
+ yield fs.unlink(DenoZip);
147
+ logger.ora.succeed('Download success');
148
+ logger.info(`Delete temp file: ${DenoZip}`);
149
+ }
150
+ catch (error) {
151
+ logger.warn(`Delete temp file ${DenoZip} failed: ${error}`);
152
+ }
153
+ try {
154
+ logger.ora.text = 'Adding Bin dir to PATH...';
155
+ const inPath = yield isBinDirInPath(BinDir);
156
+ if (!inPath) {
157
+ logger.info(`${BinDir} not in PATH`);
158
+ yield addBinDirToPath(BinDir);
159
+ }
160
+ else {
161
+ logger.info(`${BinDir} in PATH already`);
162
+ }
163
+ }
164
+ catch (error) {
165
+ const err = error;
166
+ logger.ora.fail();
167
+ logger.error(`${t('deno_add_path_failed').d('Add BinDir to Path failed')}: ${err.message}`);
168
+ process.exit(1);
169
+ }
170
+ logger.success(t('deno_install_success').d('Runtime install success!'));
171
+ logger.block();
172
+ const dev = chalk.green('esa dev');
173
+ logger.log(t('deno_install_success_tips', { dev }).d(`Please run ${dev} again`));
174
+ }
175
+ catch (error) {
176
+ const err = error;
177
+ logger.ora.fail();
178
+ logger.error(`Download Error: ${err.message}`);
179
+ process.exit(1);
180
+ }
181
+ });
182
+ }
@@ -11,7 +11,7 @@ export const getRoot = (root) => {
11
11
  if (typeof root === 'undefined') {
12
12
  root = process.cwd();
13
13
  }
14
- if (root === '/') {
14
+ if (path.parse(root).root === root) {
15
15
  return process.cwd();
16
16
  }
17
17
  const file = path.join(root, cliConfigFile);
@@ -188,7 +188,7 @@ export const getApiConfig = () => {
188
188
  };
189
189
  return config;
190
190
  };
191
- export const templateHubPath = path.join(getDirName(import.meta.url), '../../node_modules/esa-template/src');
191
+ export const templateHubPath = path.join(getDirName(import.meta.url), '../../../node_modules/esa-template/src');
192
192
  export const getTemplatesConfig = () => {
193
193
  const manifestPath = path.join(templateHubPath, 'manifest.json');
194
194
  const config = JSON.parse(fs.readFileSync(manifestPath, 'utf-8'));
@@ -9,16 +9,17 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
9
9
  };
10
10
  import { exec, execSync } from 'child_process';
11
11
  import os from 'os';
12
- import { getDirName } from './fileUtils/base.js';
13
- import logger from '../libs/logger.js';
14
12
  import path from 'path';
13
+ import logger from '../libs/logger.js';
14
+ import { getDirName } from './fileUtils/base.js';
15
+ import { downloadRuntimeAndUnzipForWindows } from './download.js';
15
16
  import t from '../i18n/index.js';
16
17
  export function preCheckDeno() {
17
18
  return __awaiter(this, void 0, void 0, function* () {
18
19
  const command = yield checkDenoInstalled();
19
20
  if (!command) {
20
- logger.error(t('install_runtime_explain').d('Under the beta phase, we are temporarily using Deno as the local development runtime. It needs to be installed first.'));
21
- installDeno();
21
+ logger.error(t('install_runtime_explain').d('Our runtime does not yet support this OS. We are temporarily using Deno as the local development runtime, which needs to be installed first.'));
22
+ yield installDeno();
22
23
  return false;
23
24
  }
24
25
  return command;
@@ -45,7 +46,6 @@ export function checkDenoInstalled() {
45
46
  resolve(res);
46
47
  })
47
48
  .catch((err) => {
48
- console.log(err);
49
49
  resolve(false);
50
50
  });
51
51
  });
@@ -57,8 +57,8 @@ export function installDeno() {
57
57
  const p = path.join(__dirname, './install');
58
58
  switch (os.platform()) {
59
59
  case 'win32':
60
- installCommand = `powershell.exe -Command "Get-Content '${p}/install.ps1' | iex"`;
61
- break;
60
+ yield downloadRuntimeAndUnzipForWindows();
61
+ return true;
62
62
  case 'darwin':
63
63
  case 'linux':
64
64
  installCommand = `sh ${p}/install.sh`;
package/package.json CHANGED
@@ -1,15 +1,18 @@
1
1
  {
2
2
  "name": "esa-cli",
3
- "version": "0.0.2-beta.0",
3
+ "version": "0.0.2-beta.10",
4
4
  "description": "A CLI for operating Alibaba Cloud ESA EdgeRoutine (Edge Functions).",
5
5
  "main": "bin/enter.cjs",
6
6
  "type": "module",
7
- "files": [
8
- "dist/"
9
- ],
10
7
  "bin": {
11
8
  "esa": "bin/enter.cjs"
12
9
  },
10
+ "files": [
11
+ "bin",
12
+ "dist/",
13
+ "zh_CN.md",
14
+ "README.md"
15
+ ],
13
16
  "scripts": {
14
17
  "build": "rm -rf ./dist && rm -rf ./build && node ./genLocale.cjs && tsc && node ./copy.cjs",
15
18
  "watch": "tsc --watch",
@@ -34,6 +37,7 @@
34
37
  "@testing-library/dom": "^10.4.0",
35
38
  "@testing-library/jest-dom": "^6.5.0",
36
39
  "@testing-library/react": "^16.0.1",
40
+ "@types/adm-zip": "^0.5.7",
37
41
  "@types/babel__generator": "^7.6.8",
38
42
  "@types/babel__traverse": "^7.20.6",
39
43
  "@types/cli-table": "^0.3.4",
@@ -71,7 +75,7 @@
71
75
  "@iarna/toml": "^2.2.5",
72
76
  "@types/inquirer": "^9.0.7",
73
77
  "@vitest/coverage-istanbul": "^2.0.4",
74
- "axios": "^1.7.7",
78
+ "adm-zip": "^0.5.16",
75
79
  "chalk": "^5.3.0",
76
80
  "chokidar": "^3.5.3",
77
81
  "cli-table3": "^0.6.5",
package/dist/README.md DELETED
@@ -1,173 +0,0 @@
1
- # ESA CLI
2
-
3
- A CLI for operating Alibaba Cloud ESA EdgeRoutine (Edge Functions). It supports quick creation of edge functions, local debugging, version publishing and deployment, and trigger management.
4
-
5
- English | [简体中文](./zh_CN.md)
6
-
7
- #### Reference
8
-
9
- - [Edge Security Acceleration (ESA)](https://www.aliyun.com/product/esa)
10
- - [What is EdgeRoutine?](https://help.aliyun.com/document_detail/2710021.html)》
11
-
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
-
14
- ESA CLI is in public beta. If you encounter any issues or have any suggestions while using it, please feel free to submit an issue or a pull request.We are actively working to improve this tool and welcome any feedback. Thank you for your understanding and support!
15
-
16
- ## Installation
17
-
18
- Install and run the CLI using npm:
19
-
20
- ```bash
21
- $ npm install esa-cli -g # Install globally
22
- $ esa -v # Check the version
23
- ```
24
-
25
- ## Usage
26
-
27
- ### 1. Initialize Routine Project
28
-
29
- ```bash
30
- & esa init
31
- ```
32
-
33
- The initialization command has a complete process guide. Follow the prompts to enter the project name and choose a template.
34
-
35
- ### 2. Start a local server for developing your routine
36
-
37
- Local dev is the core feature of the CLI, offering a more convenient debugging experience compared to the Alibaba Cloud ESA console.
38
-
39
- ```bash
40
- & cd <Project Name>
41
- & esa dev [options]
42
- ```
43
-
44
- #### Write Code
45
-
46
- In an EdgeRoutine project, the entry file is `src/index.js`, and the basic structure is as follows:
47
-
48
- ```javascript
49
- const html = `<!DOCTYPE html>
50
- <body>
51
- <h1>Hello World!</h1>
52
- </body>`;
53
-
54
- async function handleRequest(request) {
55
- return new Response(html, {
56
- headers: {
57
- 'content-type': 'text/html;charset=UTF-8'
58
- }
59
- });
60
- }
61
-
62
- export default {
63
- async fetch(event) {
64
- return event.respondWith(handleRequest(event));
65
- }
66
- };
67
- ```
68
-
69
- For more EdgeRoutine APIs and syntax, please refer to the [API Reference](https://help.aliyun.com/document_detail/2710024.html)
70
-
71
- #### Local Debugging
72
-
73
- After executing `esa dev`, the entry file will be automatically packaged and a local debugging service will be started. The interface looks like this:
74
-
75
- ![dev png](https://github.com/aliyun/alibabacloud-esa-cli/blob/master/docs/dev.png)
76
-
77
- - Press `b` to open the debugging page in the browser.
78
- - Press `c` to clear the panel.
79
- - Press `x` to exit debugging.
80
- - You can use `esa dev --port <port>` to temporarily specify the port or use `esa config -l` to set the port by project configuration.
81
-
82
- ### 3. Log in to Alibaba Cloud Account
83
-
84
- You need to log in to your Alibaba Cloud account to perform remote management operations.
85
-
86
- First, visit the [Alibaba Cloud RAM Console](https://ram.console.aliyun.com/manage/ak) to get your AccessKey ID and AccessKey Secret, then execute `esa login` and follow the prompts to enter them.
87
-
88
- ```bash
89
- & esa login
90
- & esa logout
91
- ```
92
-
93
- ### 4. Create a Version
94
-
95
- After local debugging is complete, you need to create a code version for deployment.
96
-
97
- ```bash
98
- & esa commit # Create a Version
99
- ```
100
-
101
- ### 5. Deploy to Environment & Manage Versions and Deployments
102
-
103
- After the code version is created, it needs to be deployed to edge nodes.
104
-
105
- Use the `esa deployments [script]` command to manage versions and deployments.
106
-
107
- ```bash
108
- & esa deploy # Deploy versions to the target environment
109
- & esa deployments list # View deployments
110
- & esa deployments delete <versionId> # Delete a version
111
- ```
112
-
113
- _Note: Deployed versions cannot be deleted._
114
-
115
- ### 6. Manage Triggers
116
-
117
- Once deployed to the nodes, you can configure triggers to access your edge functions. There are two types of triggers:
118
-
119
- - Domain: After you associate the routine with a domain name, you can use the domain name to access the routine.
120
- - Route: After you add a route for requested URLs, the routine is called from the edge to respond to the request.
121
-
122
- ```bash
123
- & esa domain list
124
- & esa domain add <domainName>
125
- & esa domain delete <domainName>
126
-
127
- & esa route list
128
- & esa route add [route] [site]
129
- & esa route delete <route>
130
- ```
131
-
132
- ### 7. Manage Functions
133
-
134
- You can view and delete Routine functions through the CLI.
135
-
136
- ```bash
137
- & esa routine list
138
- & esa routine delete <routineName>
139
- ```
140
-
141
- ## Commands
142
-
143
- see [Commands](./docs/Commands_en.md)
144
-
145
- ## Config files
146
-
147
- ### Global config file
148
-
149
- ```toml
150
- endpoint = "" # ESA API Endpoint
151
- lang = "zh_CN" # language
152
-
153
- [auth]
154
- accessKeyId = "" # AccessKey ID
155
- accessKeySecret = "" # AccessKey Secret
156
- ```
157
-
158
- ### Project config file
159
-
160
- ```toml
161
- name = "Hello World" # Project name
162
- description = "Hello World" # Project description
163
- entry = "src/index.js" # Entry file
164
- codeVersions = [ ] # Code version
165
-
166
- [dev]
167
- port = 18080 # Debug port
168
- localUpstream = '' # When debugging locally, the upstream source site will replace the current origin when returning to the source
169
- ```
170
-
171
- ## LICENSE
172
-
173
- [The MIT License](./LICENSE)
package/dist/package.json DELETED
@@ -1,104 +0,0 @@
1
- {
2
- "name": "esa-cli",
3
- "version": "0.0.2-beta.0",
4
- "description": "A CLI for operating Alibaba Cloud ESA EdgeRoutine (Edge Functions).",
5
- "main": "bin/enter.cjs",
6
- "type": "module",
7
- "files": [
8
- "dist/"
9
- ],
10
- "bin": {
11
- "esa": "bin/enter.cjs"
12
- },
13
- "scripts": {
14
- "build": "rm -rf ./dist && rm -rf ./build && node ./genLocale.cjs && tsc && node ./copy.cjs",
15
- "watch": "tsc --watch",
16
- "eslint": "eslint src/ --ext .js,.jsx,.ts,.tsx",
17
- "lint-staged": "lint-staged",
18
- "prepare": "npm run build",
19
- "test": "FORCE_COLOR=0 npx vitest ",
20
- "coverage": "vitest --coverage"
21
- },
22
- "keywords": [
23
- "cli",
24
- "edge",
25
- "esa",
26
- "edgeRoutine",
27
- "alibaba",
28
- "ali"
29
- ],
30
- "author": "Kinice, Shengyuan Ma",
31
- "license": "MIT",
32
- "devDependencies": {
33
- "@babel/plugin-syntax-import-attributes": "^7.24.7",
34
- "@testing-library/dom": "^10.4.0",
35
- "@testing-library/jest-dom": "^6.5.0",
36
- "@testing-library/react": "^16.0.1",
37
- "@types/babel__generator": "^7.6.8",
38
- "@types/babel__traverse": "^7.20.6",
39
- "@types/cli-table": "^0.3.4",
40
- "@types/cross-spawn": "^6.0.6",
41
- "@types/fs-extra": "^11.0.4",
42
- "@types/jest": "^29.5.12",
43
- "@types/lodash": "^4.14.202",
44
- "@types/node": "^20.8.10",
45
- "@types/node-fetch": "^2.6.9",
46
- "@types/portscanner": "^2.1.4",
47
- "@types/react": "^18.2.47",
48
- "@types/yargs": "^17.0.32",
49
- "@typescript-eslint/parser": "^6.9.1",
50
- "eslint": "^8.52.0",
51
- "eslint-config-prettier": "^9.0.0",
52
- "eslint-plugin-react": "^7.33.2",
53
- "eslint-plugin-react-hooks": "^4.6.0",
54
- "husky": "^8.0.3",
55
- "jsdom": "^25.0.1",
56
- "lint-staged": "^15.0.2",
57
- "prettier": "^3.0.3",
58
- "react": "^18.2.0",
59
- "react-dom": "^18.2.0",
60
- "rimraf": "^6.0.1",
61
- "tsc-files": "^1.1.4",
62
- "typescript": "^5.2.2",
63
- "vitest": "^2.0.4"
64
- },
65
- "dependencies": {
66
- "@alicloud/esa20240910": "2.8.1",
67
- "@alicloud/openapi-client": "^0.4.7",
68
- "@babel/generator": "^7.26.3",
69
- "@babel/parser": "^7.24.4",
70
- "@babel/traverse": "^7.24.1",
71
- "@iarna/toml": "^2.2.5",
72
- "@types/inquirer": "^9.0.7",
73
- "@vitest/coverage-istanbul": "^2.0.4",
74
- "axios": "^1.7.7",
75
- "chalk": "^5.3.0",
76
- "chokidar": "^3.5.3",
77
- "cli-table3": "^0.6.5",
78
- "cross-spawn": "^7.0.3",
79
- "esa-template": "^0.0.3",
80
- "esbuild": "^0.21.1",
81
- "esbuild-plugin-less": "^1.3.8",
82
- "form-data": "^4.0.0",
83
- "fs-extra": "^11.2.0",
84
- "http-proxy-agent": "^7.0.2",
85
- "ink": "^5.0.1",
86
- "ink-select-input": "^6.0.0",
87
- "ink-text-input": "^6.0.0",
88
- "inquirer": "^9.2.15",
89
- "js-base64": "^3.7.7",
90
- "moment": "^2.30.1",
91
- "node-fetch": "^3.3.2",
92
- "open": "^9.1.0",
93
- "ora": "^7.0.1",
94
- "os-locale": "^6.0.2",
95
- "portscanner": "^2.2.0",
96
- "winston": "^3.11.0",
97
- "winston-daily-rotate-file": "^5.0.0",
98
- "yargs": "^17.7.2"
99
- },
100
- "repository": {
101
- "type": "git",
102
- "url": "git+ssh://git@github.com/aliyun/alibabacloud-esa-cli.git"
103
- }
104
- }
File without changes