esa-cli 0.0.1-beta.9 → 0.0.2-beta.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 (44) hide show
  1. package/README.md +4 -6
  2. package/bin/enter.cjs +0 -1
  3. package/dist/README.md +4 -6
  4. package/dist/bin/enter.cjs +0 -1
  5. package/dist/commands/commit/index.js +2 -2
  6. package/dist/commands/deploy/index.js +4 -2
  7. package/dist/commands/deployments/list.js +2 -1
  8. package/dist/commands/dev/build.js +57 -0
  9. package/dist/commands/dev/doProcess.js +10 -2
  10. package/dist/commands/dev/ew2/devEntry.js +9 -0
  11. package/dist/commands/dev/ew2/devPack.js +185 -0
  12. package/dist/commands/dev/ew2/mock/cache.js +32 -0
  13. package/dist/commands/dev/ew2/mock/kv.js +45 -0
  14. package/dist/commands/dev/ew2/server.js +234 -0
  15. package/dist/commands/dev/index.js +111 -49
  16. package/dist/commands/dev/{config → mockWorker}/devEntry.js +3 -2
  17. package/dist/commands/dev/{devPack.js → mockWorker/devPack.js} +10 -8
  18. package/dist/commands/dev/{server.js → mockWorker/server.js} +43 -37
  19. package/dist/commands/init/index.js +117 -42
  20. package/dist/commands/login/index.js +2 -2
  21. package/dist/commands/logout.js +0 -4
  22. package/dist/commands/route/list.js +2 -1
  23. package/dist/commands/routine/list.js +6 -4
  24. package/dist/components/mutiLevelSelect.js +69 -0
  25. package/dist/i18n/locales.json +120 -4
  26. package/dist/index.js +8 -0
  27. package/dist/libs/api.js +155 -0
  28. package/dist/libs/logger.js +42 -31
  29. package/dist/libs/service.js +178 -0
  30. package/dist/package.json +13 -5
  31. package/dist/utils/checkDevPort.js +19 -14
  32. package/dist/utils/checkOS.js +32 -0
  33. package/dist/utils/fileMd5.js +18 -0
  34. package/dist/utils/fileUtils/index.js +1 -1
  35. package/dist/utils/install/installEw2.sh +33 -0
  36. package/dist/utils/{installRuntime.js → installDeno.js} +15 -15
  37. package/dist/utils/installEw2.js +127 -0
  38. package/dist/utils/stepsRunner.js +33 -0
  39. package/dist/zh_CN.md +4 -5
  40. package/package.json +13 -5
  41. package/dist/commands/dev/config/devBuild.js +0 -26
  42. package/dist/libs/request.js +0 -98
  43. /package/dist/commands/dev/{config → mockWorker}/mock/cache.js +0 -0
  44. /package/dist/commands/dev/{config → mockWorker}/mock/kv.js +0 -0
package/README.md CHANGED
@@ -7,11 +7,11 @@ 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
- > **Note**: 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.
13
- >
14
- > We are actively working to improve this tool and welcome any feedback. Thank you for your understanding and support!
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
15
 
16
16
  ## Installation
17
17
 
@@ -75,8 +75,6 @@ After executing `esa dev`, the entry file will be automatically packaged and a l
75
75
  ![dev png](https://github.com/aliyun/alibabacloud-esa-cli/blob/master/docs/dev.png)
76
76
 
77
77
  - Press `b` to open the debugging page in the browser.
78
- - Press `d` to view debugging instructions. **Chrome does not allow the command line to open the debugging page**.
79
- - Open `chrome://inspect#devices` in the Chrome browser to see a running Remote Target. Click inspect below it to view console information. **Note that the EdgeRoutine code is server-side, so the console on the preview page will not output console in the entry file. Use inspect for debugging.**
80
78
  - Press `c` to clear the panel.
81
79
  - Press `x` to exit debugging.
82
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.
package/bin/enter.cjs CHANGED
@@ -35,7 +35,6 @@ const main = () => {
35
35
  process.disconnect && process.disconnect();
36
36
  })
37
37
  .on('exit', (code) => {
38
- // console.log('Get exit', code);
39
38
  process.exit && process.exit(code);
40
39
  });
41
40
  };
package/dist/README.md CHANGED
@@ -7,11 +7,11 @@ 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
- > **Note**: 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.
13
- >
14
- > We are actively working to improve this tool and welcome any feedback. Thank you for your understanding and support!
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
15
 
16
16
  ## Installation
17
17
 
@@ -75,8 +75,6 @@ After executing `esa dev`, the entry file will be automatically packaged and a l
75
75
  ![dev png](https://github.com/aliyun/alibabacloud-esa-cli/blob/master/docs/dev.png)
76
76
 
77
77
  - Press `b` to open the debugging page in the browser.
78
- - Press `d` to view debugging instructions. **Chrome does not allow the command line to open the debugging page**.
79
- - Open `chrome://inspect#devices` in the Chrome browser to see a running Remote Target. Click inspect below it to view console information. **Note that the EdgeRoutine code is server-side, so the console on the preview page will not output console in the entry file. Use inspect for debugging.**
80
78
  - Press `c` to clear the panel.
81
79
  - Press `x` to exit debugging.
82
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.
@@ -35,7 +35,6 @@ const main = () => {
35
35
  process.disconnect && process.disconnect();
36
36
  })
37
37
  .on('exit', (code) => {
38
- // console.log('Get exit', code);
39
38
  process.exit && process.exit(code);
40
39
  });
41
40
  };
@@ -120,14 +120,14 @@ export function uploadEdgeRoutineCode(edgeRoutine) {
120
120
  const uploadResult = yield server.getRoutineStagingCodeUploadInfo(edgeRoutine);
121
121
  if (!uploadResult) {
122
122
  logger.error(t('commit_upload_fail').d('An error occurred while trying to upload your code'));
123
- return false;
123
+ process.exit(0);
124
124
  }
125
125
  logger.success(t('commit_upload_success').d('Code uploaded successfully.'));
126
126
  return true;
127
127
  }
128
128
  catch (error) {
129
129
  logger.error(`${t('common_error_occurred').d('An error occurred:')} ${error}`);
130
- return false;
130
+ process.exit(0);
131
131
  }
132
132
  });
133
133
  }
@@ -22,6 +22,7 @@ import prodBuild from '../commit/prodBuild.js';
22
22
  import { exit } from 'process';
23
23
  import path from 'path';
24
24
  import { checkRoutineExist } from '../../utils/checkIsRoutineCreated.js';
25
+ import moment from 'moment';
25
26
  const deploy = {
26
27
  command: 'deploy [entry]',
27
28
  builder: (yargs) => {
@@ -58,6 +59,7 @@ export function quickDeploy(entry, projectConfig) {
58
59
  }
59
60
  else {
60
61
  logger.error(t('quick_deploy_failed').d('Quick deploy failed'));
62
+ process.exit(0);
61
63
  }
62
64
  });
63
65
  }
@@ -197,7 +199,7 @@ export function displayVersionList(versionList_1) {
197
199
  const data = [];
198
200
  for (let i = 0; i < versionList.length; i++) {
199
201
  const version = versionList[i];
200
- const createTime = new Date(version.CreateTime).toLocaleString();
202
+ const createTime = moment(version.CreateTime).format('YYYY/MM/DD HH:mm:ss');
201
203
  const tags = [
202
204
  version.CodeVersion === stagingVersion ? chalk.bgYellow('Active') : '',
203
205
  version.CodeVersion === productionVersion ? chalk.bgGreen('Active') : ''
@@ -212,6 +214,6 @@ export function displayVersionList(versionList_1) {
212
214
  t('deploy_table_header_version').d('Version'),
213
215
  t('deploy_table_header_created').d('Created'),
214
216
  t('deploy_table_header_description').d('Description')
215
- ], data);
217
+ ], data, [30, 25, 15]);
216
218
  });
217
219
  }
@@ -83,7 +83,8 @@ function displayListPrompt(routineDetail) {
83
83
  logger.block();
84
84
  logger.log(`${chalk.bold(`${t('deploy_env_canary').d('Canary')} ${isCanary ? chalk.green('●') : ''}`)}`);
85
85
  showEnvTable((_d = canaryEnv.CanaryCodeVersion) !== null && _d !== void 0 ? _d : '', canaryEnv.SpecName, (_e = canaryEnv.CanaryAreaList) === null || _e === void 0 ? void 0 : _e.join(', '));
86
- logger.info(`${t('show_default_url').d(`You can visit:`)} ${chalk.yellowBright(routineDetail.data.DefaultRelatedRecord)}`);
86
+ logger.log(`${t('show_default_url').d(`You can visit:`)} ${chalk.yellowBright(routineDetail.data.DefaultRelatedRecord)}`);
87
+ logger.info(routineDetail.data.DefaultRelatedRecord);
87
88
  logger.block();
88
89
  });
89
90
  }
@@ -0,0 +1,57 @@
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+ import esbuild from 'esbuild';
4
+ import { lessLoader } from 'esbuild-plugin-less';
5
+ import { getRoot } from '../../utils/fileUtils/base.js';
6
+ import { NODE_EXTERNALS } from '../common/constant.js';
7
+ import parser from '@babel/parser';
8
+ import _traverse from '@babel/traverse';
9
+ import _generator from '@babel/generator';
10
+ const replacements = { cache: 'mockCache', EdgeKV: 'mockKV' };
11
+ const traverse = _traverse.default;
12
+ const generator = _generator.default;
13
+ const renameMock = {
14
+ name: 'rename-mock',
15
+ setup(build) {
16
+ build.onEnd(() => {
17
+ if (build.initialOptions.outfile) {
18
+ const outFile = fs.readFileSync(build.initialOptions.outfile, 'utf-8');
19
+ const ast = parser.parse(outFile, {
20
+ sourceType: 'module'
21
+ });
22
+ traverse(ast, {
23
+ Identifier(path) {
24
+ const name = path.node.name;
25
+ if (replacements.hasOwnProperty(name)) {
26
+ path.node.name = replacements[name];
27
+ }
28
+ }
29
+ });
30
+ const { code } = generator(ast);
31
+ fs.writeFileSync(build.initialOptions.outfile, code);
32
+ }
33
+ });
34
+ }
35
+ };
36
+ export default function (options) {
37
+ const userRoot = getRoot();
38
+ // @ts-ignore
39
+ const id = global.id;
40
+ const devEntry = path.resolve(userRoot, `.dev/devEntry-${id}.js`);
41
+ return esbuild.build({
42
+ entryPoints: [devEntry],
43
+ outfile: path.resolve(userRoot, `.dev/index-${id}.js`),
44
+ bundle: true,
45
+ minify: !!options.minify,
46
+ splitting: false,
47
+ format: 'esm',
48
+ platform: options.isNode ? 'node' : 'browser',
49
+ // EW2 support node externals
50
+ external: NODE_EXTERNALS,
51
+ // @ts-ignore
52
+ plugins: [lessLoader(), renameMock],
53
+ loader: {
54
+ '.client.js': 'text'
55
+ }
56
+ });
57
+ }
@@ -13,12 +13,15 @@ import chalk from 'chalk';
13
13
  import logger from '../../libs/logger.js';
14
14
  import openInBrowser from '../../utils/openInBrowser.js';
15
15
  import { getDevOpenBrowserUrl } from '../../utils/fileUtils/index.js';
16
+ import { checkOS, Platforms } from '../../utils/checkOS.js';
16
17
  import t from '../../i18n/index.js';
17
18
  const InteractionBox = ({ worker }) => {
18
19
  const { exit } = useApp();
19
20
  const inspectLink = chalk.underline.blue('chrome://inspect/#devices');
20
21
  const remoteTarget = chalk.blue('Remote Target');
21
22
  const inspect = chalk.blue('inspect');
23
+ const OS = checkOS();
24
+ const useEw2 = OS === Platforms.AppleArm || Platforms.AppleIntel || Platforms.LinuxX86;
22
25
  /* eslint-disable no-unused-vars */
23
26
  useInput((input) => __awaiter(void 0, void 0, void 0, function* () {
24
27
  switch (input.toLowerCase()) {
@@ -31,6 +34,8 @@ const InteractionBox = ({ worker }) => {
31
34
  break;
32
35
  }
33
36
  case 'd': {
37
+ if (useEw2)
38
+ return;
34
39
  logger.log(t('dev_input_inspect_tip1', { inspectLink }).d(`👉 Please visit ${inspectLink} in the Chrome browser`));
35
40
  logger.log(t('dev_input_inspect_tip2', { inspect, remoteTarget }).d(`👉 See your debugger under ${remoteTarget} and click the ${inspect} button`));
36
41
  break;
@@ -53,9 +58,9 @@ const InteractionBox = ({ worker }) => {
53
58
  React.createElement(Box, { borderStyle: "classic", paddingLeft: 1, paddingRight: 1 },
54
59
  React.createElement(Text, { bold: true }, "[b]"),
55
60
  React.createElement(Text, null, " open a browser, "),
56
- React.createElement(React.Fragment, null,
61
+ !useEw2 ? (React.createElement(React.Fragment, null,
57
62
  React.createElement(Text, { bold: true }, "[d]"),
58
- React.createElement(Text, null, " open Devtools, ")),
63
+ React.createElement(Text, null, " open Devtools, "))) : null,
59
64
  React.createElement(Text, { bold: true }, "[c]"),
60
65
  React.createElement(Text, null, " clear console, "),
61
66
  React.createElement(Text, { bold: true }, "[x]"),
@@ -67,6 +72,9 @@ const doProcess = (worker) => {
67
72
  devElement,
68
73
  exit: () => {
69
74
  devElement.unmount();
75
+ setTimeout(() => {
76
+ process.exit(0);
77
+ }, 500);
70
78
  }
71
79
  };
72
80
  };
@@ -0,0 +1,9 @@
1
+ import worker from '$userPath';
2
+ import Cache from './mock/cache.js';
3
+ import mockKV from './mock/kv.js';
4
+
5
+ var mock_cache = await Cache.init('mock');
6
+ globalThis.mockCache = mock_cache;
7
+ globalThis.mockKV = mockKV;
8
+
9
+ export default worker;
@@ -0,0 +1,185 @@
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 path from 'path';
11
+ import fs from 'fs';
12
+ import logger from '../../../libs/logger.js';
13
+ import devBuild from '../build.js';
14
+ import t from '../../../i18n/index.js';
15
+ import { getDevConf } from '../../../utils/fileUtils/index.js';
16
+ import { getRoot, getDirName } from '../../../utils/fileUtils/base.js';
17
+ import { checkPort } from '../../../utils/checkDevPort.js';
18
+ import { EW2Path } from '../../../utils/installEw2.js';
19
+ // 生成可用的Ew2端口
20
+ const generateEw2Port = () => __awaiter(void 0, void 0, void 0, function* () {
21
+ let ew2port = 3322;
22
+ let portAvailable = yield checkPort(ew2port);
23
+ while (!portAvailable) {
24
+ ew2port += 1;
25
+ portAvailable = yield checkPort(ew2port);
26
+ }
27
+ // @ts-ignore
28
+ global.ew2Port = ew2port;
29
+ return ew2port;
30
+ });
31
+ const writeEw2config = (id, port, userRoot) => {
32
+ const devDir = path.resolve(userRoot, '.dev');
33
+ const devIndex = path.resolve(devDir, `index-${id}.js`);
34
+ const devConfPath = path.resolve(devDir, `config-${id}.toml`);
35
+ const erConfPath = path.resolve(EW2Path, `er.conf`);
36
+ const config = `
37
+ port = ${port}
38
+ [debugger_cli_options]
39
+ enable = true
40
+ code_path = "${devIndex}"
41
+ conf_path = "${erConfPath}"
42
+ `;
43
+ const erConf = JSON.stringify({
44
+ Ttl: 301,
45
+ ServiceOptions: {
46
+ service_status: 'active'
47
+ },
48
+ InstanceOptions: {
49
+ allow_node_module: true
50
+ },
51
+ ContextOptions: {
52
+ vm_max_cpu_time: 100
53
+ },
54
+ ServiceOptionsMd5: '1',
55
+ InstanceOptionsMd5: '2',
56
+ ContextOptionsMd5: '3'
57
+ });
58
+ return Promise.all([
59
+ fs.promises.writeFile(devConfPath, config),
60
+ fs.promises.writeFile(erConfPath, erConf)
61
+ ]);
62
+ };
63
+ // 生成入口文件
64
+ const generateEntry = (id, projectEntry, userRoot) => __awaiter(void 0, void 0, void 0, function* () {
65
+ const __dirname = getDirName(import.meta.url);
66
+ const devDir = path.resolve(userRoot, '.dev');
67
+ const devEntry = path.resolve(devDir, `devEntry-${id}.js`);
68
+ const devEntryTemp = path.resolve(__dirname, './devEntry.js');
69
+ const devEntryTempFile = fs.readFileSync(devEntryTemp, 'utf-8');
70
+ const mockDevDir = path.resolve(userRoot, '.dev/mock');
71
+ const mockDir = path.resolve(__dirname, './mock');
72
+ if (!fs.existsSync(devDir)) {
73
+ yield fs.promises.mkdir(devDir);
74
+ }
75
+ if (!fs.existsSync(mockDevDir)) {
76
+ yield fs.promises.mkdir(mockDevDir);
77
+ }
78
+ const entries = yield fs.promises.readdir(mockDir);
79
+ for (const file of entries) {
80
+ const srcPath = path.resolve(mockDir, file);
81
+ const destPath = path.resolve(mockDevDir, file);
82
+ yield fs.promises.copyFile(srcPath, destPath);
83
+ }
84
+ return fs.promises.writeFile(devEntry, devEntryTempFile.replace(/'\$userPath'/g, `'${projectEntry}'`));
85
+ });
86
+ // 前期准备
87
+ const prepare = (configPath, entry, port, localUpstream, userRoot) => __awaiter(void 0, void 0, void 0, function* () {
88
+ const options = {};
89
+ const currentOptions = { entry, port, localUpstream };
90
+ // 支持同时跑多个 worker
91
+ const id = new Date().getTime().toString();
92
+ // @ts-ignore
93
+ global.id = id;
94
+ // 生成入口文件
95
+ yield generateEntry(id, entry, userRoot);
96
+ // 生成 Ew2 配置
97
+ const ew2port = yield generateEw2Port();
98
+ yield writeEw2config(id, ew2port, userRoot);
99
+ // 给每一次 dev 的配置项,在一个文件中通过 id 区分
100
+ if (fs.existsSync(configPath)) {
101
+ const currentConfig = fs
102
+ .readFileSync(configPath, 'utf-8')
103
+ .replace('export default ', '');
104
+ const currentConfigObj = JSON.parse(currentConfig);
105
+ const currentIds = Object.keys(currentConfigObj);
106
+ if (currentIds[0] && /^\d+$/.test(currentIds[0])) {
107
+ // 删除没有用到的入口
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, {
130
+ force: true,
131
+ recursive: true,
132
+ maxRetries: 5
133
+ });
134
+ }
135
+ }
136
+ else {
137
+ options[currentId] = currentConfigObj[currentId];
138
+ }
139
+ }
140
+ }
141
+ }
142
+ return fs.promises.writeFile(configPath, `export default ${JSON.stringify(Object.assign(options, { [id]: currentOptions }))}`);
143
+ });
144
+ const devPack = (...args_1) => __awaiter(void 0, [...args_1], void 0, function* (restarting = false) {
145
+ logger.ora.start('Processing...\n');
146
+ const userRoot = getRoot();
147
+ const configPath = path.resolve(userRoot, 'esa.toml');
148
+ let port, minify, localUpstream, entry;
149
+ let projectEntry = path.resolve(userRoot, 'src/index.js');
150
+ if (fs.existsSync(configPath)) {
151
+ port = getDevConf('port', 'dev', 18080);
152
+ minify = getDevConf('minify', 'dev', false);
153
+ localUpstream = getDevConf('localUpstream', 'dev', '');
154
+ entry = getDevConf('entry', '', '');
155
+ if (entry) {
156
+ projectEntry = path.resolve(userRoot, entry);
157
+ }
158
+ }
159
+ else {
160
+ logger.notInProject();
161
+ process.exit(0);
162
+ }
163
+ return prepare(path.resolve(userRoot, '.dev/devConfig.js'), projectEntry, port, localUpstream, userRoot)
164
+ .then(() => {
165
+ logger.ora.succeed(t('dev_pack_config_success').d('Config created successfully'));
166
+ return devBuild({
167
+ minify,
168
+ isNode: true
169
+ });
170
+ })
171
+ .then(() => {
172
+ logger.ora.succeed(t('dev_pack_success').d('Build finished successfully'));
173
+ logger.ora.stop();
174
+ logger.block();
175
+ })
176
+ .catch((err) => {
177
+ logger.ora.fail('Build Failed');
178
+ logger.error(`${t('common_error_occurred').d('An error occurred')}: ${err}`);
179
+ if (err.toString().includes('EACCES')) {
180
+ logger.pathEacces(getDirName(import.meta.url));
181
+ }
182
+ process.exit(1);
183
+ });
184
+ });
185
+ export default devPack;
@@ -0,0 +1,32 @@
1
+ class MockCache {
2
+ constructor() {
3
+ this.cache = new Map();
4
+ }
5
+
6
+ static async init(cacheName) {
7
+ const instance = await MockCache.open(cacheName);
8
+ return new MockCache(instance);
9
+ }
10
+
11
+ static async open(cacheName) {
12
+ return new Map();
13
+ }
14
+
15
+ async match(reqOrUrl) {
16
+ return this.cache.get(reqOrUrl) || null;
17
+ }
18
+
19
+ async delete(reqOrUrl) {
20
+ return this.cache.delete(reqOrUrl);
21
+ }
22
+
23
+ async put(reqOrUrl, response) {
24
+ this.cache.set(reqOrUrl, response);
25
+ }
26
+
27
+ async get(reqOrUrl) {
28
+ return this.match(reqOrUrl);
29
+ }
30
+ }
31
+
32
+ export default MockCache;
@@ -0,0 +1,45 @@
1
+ class EdgeKV {
2
+ constructor(options) {
3
+ this.namespace = options.namespace;
4
+ this.allData = {};
5
+ }
6
+
7
+ async get(key, options) {
8
+ const namespaceData = this.allData[this.namespace] || {};
9
+ if (!(key in namespaceData)) {
10
+ return undefined;
11
+ }
12
+ const value = namespaceData[key];
13
+ const type = options?.type || 'text';
14
+ switch (type) {
15
+ case 'text':
16
+ return value;
17
+ case 'json':
18
+ try {
19
+ return JSON.parse(value);
20
+ } catch (error) {
21
+ throw new Error('Failed to parse JSON');
22
+ }
23
+ case 'arrayBuffer':
24
+ const encoder = new TextEncoder();
25
+ const uint8Array = encoder.encode(value);
26
+ return uint8Array.buffer;
27
+ default:
28
+ throw new Error('Invalid type option');
29
+ }
30
+ }
31
+
32
+ async put(key, value) {
33
+ const namespaceData = this.allData[this.namespace] || {};
34
+ namespaceData[key] = value;
35
+ this.allData[this.namespace] = namespaceData;
36
+ }
37
+
38
+ async delete(key) {
39
+ const namespaceData = this.allData[this.namespace] || {};
40
+ delete namespaceData[key];
41
+ this.allData[this.namespace] = namespaceData;
42
+ }
43
+ }
44
+
45
+ export default EdgeKV;