env-plugin 0.5.9 → 0.6.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.
package/bin/index.js CHANGED
@@ -1,12 +1,18 @@
1
1
  #!/usr/bin/env node
2
2
 
3
+ import fs from "node:fs";
4
+ import path from "node:path";
5
+ import { fileURLToPath } from "node:url";
3
6
  import { program } from "commander";
4
7
  import { EnvManage } from "../dist/index.js";
8
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
9
+ const packageJsonPath = path.resolve(__dirname, "../package.json");
10
+ const packageVersion = JSON.parse(fs.readFileSync(packageJsonPath, "utf-8")).version;
5
11
 
6
12
  program
13
+ .name("envm")
7
14
  .description("Environment management tool")
8
- .name("envm")
9
- // 添加命令行选项
15
+ .version(packageVersion, "-v, --version", "output the current version")
10
16
  .option("-p, --port <number>", "specify the port number", Number)
11
17
  .option("-a, --api-prefix <string>", "specify the API prefix", String)
12
18
  .option("-c, --cookie-suffix <string>", "specify the cookie suffix", String)
@@ -5,10 +5,10 @@
5
5
  <link rel="icon" href="/favicon.ico" />
6
6
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
7
7
  <title>ENVM (环境管理)</title>
8
- <script type="module" crossorigin src="/assets/index-C-jtdEqj.js"></script>
9
- <link rel="modulepreload" crossorigin href="/assets/vue-BGFZjnqd.js">
10
- <link rel="modulepreload" crossorigin href="/assets/element-plus-ketO_xfq.js">
11
- <link rel="stylesheet" crossorigin href="/assets/index-Crqzm-vz.css">
8
+ <script type="module" crossorigin src="/assets/index-Db97pusF.js"></script>
9
+ <link rel="modulepreload" crossorigin href="/assets/vue-CRjr1oeH.js">
10
+ <link rel="modulepreload" crossorigin href="/assets/element-plus-4FTV-s7u.js">
11
+ <link rel="stylesheet" crossorigin href="/assets/index-C2AH0x8U.css">
12
12
  </head>
13
13
  <body>
14
14
  <div id="app"></div>
@@ -98,5 +98,23 @@ class DevServerController {
98
98
  next(error);
99
99
  }
100
100
  }
101
+ /**
102
+ * 处理更新排序顺序
103
+ * @param req
104
+ * @param res
105
+ * @param next
106
+ * @returns
107
+ */
108
+ handleUpdateSortOrder(req, res, next) {
109
+ try {
110
+ const sortData = req.dto;
111
+ devServerLogger.info(sortData, "接收排序更新请求");
112
+ this.devServerService.handleUpdateSortOrder(sortData);
113
+ res.success({ message: "排序更新成功" });
114
+ }
115
+ catch (error) {
116
+ next(error);
117
+ }
118
+ }
101
119
  }
102
120
  export { DevServerController };
@@ -173,5 +173,24 @@ class EnvController {
173
173
  next(error);
174
174
  }
175
175
  }
176
+ /**
177
+ * 更新环境排序顺序
178
+ * @description 处理更新环境排序的PUT请求
179
+ * @param req - Express请求对象,包含排序数据(在req.dto中)
180
+ * @param res - Express响应对象,用于返回处理结果
181
+ * @param next - Express下一步中间件函数,用于错误处理
182
+ */
183
+ handleUpdateSortOrder(req, res, next) {
184
+ try {
185
+ const sortData = req.dto;
186
+ envLogger.info(sortData, "接收排序更新请求");
187
+ this.envService.handleUpdateSortOrder(sortData);
188
+ res.success({ message: "排序更新成功" });
189
+ }
190
+ catch (error) {
191
+ envLogger.error(error, "排序更新请求处理失败");
192
+ next(error);
193
+ }
194
+ }
176
195
  }
177
196
  export { EnvController };
@@ -97,5 +97,18 @@ class DevServerRepo {
97
97
  return server;
98
98
  });
99
99
  }
100
+ /**
101
+ * 更新开发服务器排序顺序
102
+ * @param id - 开发服务器ID
103
+ * @param sortOrder - 排序顺序
104
+ */
105
+ updateSortOrder(id, sortOrder) {
106
+ this.getCollection().findAndUpdate({ id }, (server) => {
107
+ if (server) {
108
+ server.sortOrder = sortOrder;
109
+ }
110
+ return server;
111
+ });
112
+ }
100
113
  }
101
114
  export { DevServerRepo };
@@ -19,10 +19,14 @@ class EnvRepo {
19
19
  constructor() { }
20
20
  /**
21
21
  * 获取所有环境信息
22
- * @returns 所有环境信息的数组
22
+ * @returns 所有环境信息的数组(按sortOrder排序)
23
23
  */
24
24
  getAll() {
25
- return this.getCollection().find();
25
+ return this.getCollection().find().sort((a, b) => {
26
+ const orderA = a.sortOrder ?? 0;
27
+ const orderB = b.sortOrder ?? 0;
28
+ return orderA - orderB;
29
+ });
26
30
  }
27
31
  /**
28
32
  * 添加新环境
@@ -4,7 +4,7 @@ import * as libCookie from "cookie";
4
4
  import { Container } from "../Container.js";
5
5
  import { getConfig } from "../utils/ResolveConfig.js";
6
6
  import { toDTO } from "../middleware/dto.middleware.js";
7
- import { EnvPrimarySchema, EnvCreateSchema, EnvUpdateSchema, DevServerCreateSchema, DevServerDeleteSchema, DevServerUpdateSchema, RouteRuleCreateSchema, RouteRuleDeleteSchema, RouteRuleUpdateSchema, PasswordCreateSchema, PasswordDeleteSchema, PasswordUpdateSchema, } from "../types/index.js";
7
+ import { EnvPrimarySchema, EnvCreateSchema, EnvUpdateSchema, EnvSortSchema, DevServerCreateSchema, DevServerDeleteSchema, DevServerUpdateSchema, DevServerSortSchema, RouteRuleCreateSchema, RouteRuleDeleteSchema, RouteRuleUpdateSchema, PasswordCreateSchema, PasswordDeleteSchema, PasswordUpdateSchema, } from "../types/index.js";
8
8
  // 1. 创建各模块路由
9
9
  const createEnvRoutes = (controller) => {
10
10
  const router = Router();
@@ -14,6 +14,7 @@ const createEnvRoutes = (controller) => {
14
14
  router.post("/update", toDTO(EnvUpdateSchema), (...res) => controller.handleUpdateEnv(...res));
15
15
  router.post("/start", toDTO(EnvPrimarySchema), (...res) => controller.handleStartServer(...res));
16
16
  router.post("/stop", toDTO(EnvPrimarySchema), (...res) => controller.handleStopServer(...res));
17
+ router.put("/sort", toDTO(EnvSortSchema), (...res) => controller.handleUpdateSortOrder(...res));
17
18
  return router;
18
19
  };
19
20
  const createDevServerRoutes = (controller) => {
@@ -21,6 +22,7 @@ const createDevServerRoutes = (controller) => {
21
22
  router.get("/list", (...res) => controller.handleGetDevServerList(...res));
22
23
  router.post("/add", toDTO(DevServerCreateSchema), (...res) => controller.handleCreateDevServer(...res));
23
24
  router.put("/update", toDTO(DevServerUpdateSchema), (...res) => controller.handleUpdateDevServer(...res));
25
+ router.put("/sort", toDTO(DevServerSortSchema), (...res) => controller.handleUpdateSortOrder(...res));
24
26
  router.delete("/", toDTO(DevServerDeleteSchema), (...res) => controller.handleDeleteDevServer(...res));
25
27
  return router;
26
28
  };
@@ -37,6 +37,7 @@ class DevServerService {
37
37
  const newDevServer = {
38
38
  ...validData,
39
39
  id: uuidv4(),
40
+ sortOrder: 0,
40
41
  };
41
42
  // 保存开发服务器
42
43
  this.devServerRepo.addDevServer(newDevServer);
@@ -106,13 +107,18 @@ class DevServerService {
106
107
  devServerLogger.info(updatedServer, "开发服务器更新成功");
107
108
  }
108
109
  /**
109
- * 获取所有开发服务器列表
110
+ * 获取所有开发服务器列表(按 sortOrder 排序)
110
111
  * @returns {DevServerModel[]} 开发服务器信息数组
111
112
  */
112
113
  handleGetList() {
113
114
  const list = this.devServerRepo.getAll();
115
+ const sortedList = [...list].sort((a, b) => {
116
+ const orderA = a.sortOrder ?? 0;
117
+ const orderB = b.sortOrder ?? 0;
118
+ return orderA - orderB;
119
+ });
114
120
  devServerLogger.info(`查询到${list.length}个开发服务器`);
115
- return list;
121
+ return sortedList;
116
122
  }
117
123
  /**
118
124
  * 根据ID查询单个开发服务器
@@ -185,5 +191,23 @@ class DevServerService {
185
191
  // });
186
192
  devServerLogger.info(`开发服务器【${devServerId}】已解除环境关联`);
187
193
  }
194
+ /**
195
+ * 批量更新排序顺序
196
+ * @param sortData - 排序数据
197
+ * @returns {void}
198
+ * @throws {AppError} 当数据不合法时抛出
199
+ */
200
+ handleUpdateSortOrder(sortData) {
201
+ const { orders } = sortData;
202
+ devServerLogger.info(orders, "准备更新排序顺序");
203
+ for (const item of orders) {
204
+ const existing = this.devServerRepo.findOneById({ id: item.id });
205
+ if (!existing) {
206
+ throw new AppError(`排序更新失败,开发服务器【${item.id}】不存在`);
207
+ }
208
+ this.devServerRepo.updateSortOrder(item.id, item.sortOrder);
209
+ }
210
+ devServerLogger.info("排序顺序更新成功");
211
+ }
188
212
  }
189
213
  export { DevServerService };
@@ -2,6 +2,7 @@ import { v4 as uuidv4 } from "uuid";
2
2
  import PreProxyServer from "./PreProxyServer.js";
3
3
  import { AppError } from "../utils/errors.js";
4
4
  import { envLogger } from "../utils/logger.js";
5
+ import * as os from "os";
5
6
  /**
6
7
  * 环境服务类
7
8
  * 负责处理与环境相关的核心业务逻辑,包括环境的增删改查、服务器启停等操作
@@ -18,6 +19,7 @@ class EnvService {
18
19
  this.envRepo = envRepo;
19
20
  this.devServerRepo = devServerRepo;
20
21
  this.routeRuleRepo = routeRuleRepo;
22
+ this.serverIp = `${this.getLocalIp()}`;
21
23
  }
22
24
  /**
23
25
  * 添加新环境
@@ -90,6 +92,25 @@ class EnvService {
90
92
  this.envRepo.update(envItem);
91
93
  envLogger.info({ envItem }, "环境更新成功");
92
94
  }
95
+ /**
96
+ * 获取本机 IP 地址
97
+ * @returns 本机 IP 地址
98
+ */
99
+ getLocalIp() {
100
+ const interfaces = os.networkInterfaces();
101
+ for (const name of Object.keys(interfaces)) {
102
+ const iface = interfaces[name];
103
+ if (!iface)
104
+ continue;
105
+ for (const info of iface) {
106
+ // 跳过 IPv6 和内部地址
107
+ if (info.family === "IPv4" && !info.internal) {
108
+ return info.address;
109
+ }
110
+ }
111
+ }
112
+ return "127.0.0.1";
113
+ }
93
114
  /**
94
115
  * 获取所有环境列表
95
116
  * @returns {Array<EnvModel & {routeRuleCount?: number}>} 环境信息数组
@@ -101,6 +122,7 @@ class EnvService {
101
122
  const result = list.map((env) => ({
102
123
  ...env,
103
124
  routeRuleCount: this.routeRuleRepo?.countByEnvId(env.id) ?? 0,
125
+ serverIp: this.serverIp,
104
126
  }));
105
127
  envLogger.info({ count: list.length }, `查询到${list.length}个环境`);
106
128
  return result;
@@ -210,5 +232,26 @@ class EnvService {
210
232
  envLogger.info({ env, updatedEnv }, `环境【${env.id}】状态已更新为${updatedEnv.status}`);
211
233
  return updatedEnv;
212
234
  }
235
+ /**
236
+ * 批量更新排序顺序
237
+ * @param sortData - 排序数据
238
+ * @returns {void}
239
+ * @throws {AppError} 当数据不合法时抛出
240
+ */
241
+ handleUpdateSortOrder(sortData) {
242
+ const { orders } = sortData;
243
+ envLogger.info(orders, "准备更新排序顺序");
244
+ for (const item of orders) {
245
+ const existing = this.envRepo.findOneById(item.id);
246
+ if (!existing) {
247
+ throw new AppError(`环境【${item.id}】不存在,无法更新排序`);
248
+ }
249
+ this.envRepo.update({
250
+ id: item.id,
251
+ sortOrder: item.sortOrder,
252
+ });
253
+ }
254
+ envLogger.info("排序更新成功");
255
+ }
213
256
  }
214
257
  export { EnvService };
@@ -32,7 +32,7 @@ class PreProxyServer {
32
32
  this.devServerRepo = devServerRepo;
33
33
  this.routeRuleRepo = routeRuleRepo;
34
34
  this.app = app;
35
- app.use([`${getConfig().apiPrefix}/inject/getcurrentenv`], (req, res) => {
35
+ app.use([`${getConfig().apiPrefix}/inject/getcurrentenv`], (_req, res) => {
36
36
  res.json({ envId: this.envId });
37
37
  res.end();
38
38
  });
@@ -247,16 +247,16 @@ class PreProxyServer {
247
247
  return "";
248
248
  }
249
249
  const fullPath = path.resolve(scriptDir);
250
+ // 检查目录是否存在且是一个文件夹
250
251
  if (!fs.existsSync(fullPath) || !fs.statSync(fullPath).isDirectory()) {
251
- devServerLogger.warn(`注入脚本目录不存在: ${fullPath}`);
252
252
  return "";
253
253
  }
254
254
  const files = fs.readdirSync(fullPath);
255
255
  const jsFiles = files
256
256
  .filter((file) => file.endsWith(".js") && !file.startsWith("#"))
257
257
  .sort();
258
+ // 如果没有符合要求的 js 文件,返回空字符串
258
259
  if (jsFiles.length === 0) {
259
- devServerLogger.warn(`注入脚本目录没有 js 文件: ${fullPath}`);
260
260
  return "";
261
261
  }
262
262
  const importStatements = jsFiles
@@ -24,11 +24,24 @@ export const BaseDevServerSchema = z.object({
24
24
  */
25
25
  devServerUrl: z.string().describe("开发服务器地址"),
26
26
  });
27
+ /**
28
+ * 开发服务器排序Schema
29
+ * 用于保存排序顺序
30
+ */
31
+ export const DevServerSortSchema = z.object({
32
+ orders: z.array(z.object({
33
+ id: z.string(),
34
+ sortOrder: z.number(),
35
+ })),
36
+ });
27
37
  /**
28
38
  * 完整开发服务器模型Schema
29
39
  * 合并了主键和基础信息,用于创建完整的开发服务器模型
30
40
  */
31
- export const DevServerModelSchema = DevServerPrimarySchema.extend(BaseDevServerSchema.shape);
41
+ export const DevServerModelSchema = DevServerPrimarySchema.extend({
42
+ ...BaseDevServerSchema.shape,
43
+ sortOrder: z.number().optional().default(0),
44
+ });
32
45
  /**
33
46
  * 新增开发服务器Schema
34
47
  * 用于创建新开发服务器时的参数验证,不需要提供id(由系统生成)
@@ -27,6 +27,7 @@ export const EnvItemBaseSchema = z.object({
27
27
  .describe("环境绑定的开发服务器ID"),
28
28
  homePage: z.string().optional().describe("环境首页"),
29
29
  status: z.enum(["running", "stopped"]).optional(),
30
+ sortOrder: z.number().optional().describe("排序顺序"),
30
31
  });
31
32
  /**
32
33
  * 完整环境模型Schema
@@ -55,3 +56,13 @@ export const EnvUpdateSchema = EnvPrimarySchema.extend(EnvItemBaseSchema.partial
55
56
  * 用于查询环境信息时的参数验证,只需要提供环境id
56
57
  */
57
58
  export const EnvQuerySchema = EnvPrimarySchema;
59
+ /**
60
+ * 环境排序Schema
61
+ * 用于保存排序顺序
62
+ */
63
+ export const EnvSortSchema = z.object({
64
+ orders: z.array(z.object({
65
+ id: z.string(),
66
+ sortOrder: z.number(),
67
+ })),
68
+ });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "env-plugin",
3
- "version": "0.5.9",
3
+ "version": "0.6.0",
4
4
  "type": "module",
5
5
  "description": "A dev env plugin that integrates an Express server with request proxying capabilities.",
6
6
  "keywords": [
@@ -20,7 +20,7 @@
20
20
  "import": "./dist/Plugin.js"
21
21
  }
22
22
  },
23
- "author": "lcn",
23
+ "author": "lumos934",
24
24
  "license": "MIT",
25
25
  "dependencies": {
26
26
  "commander": "^13.1.0",
@@ -28,7 +28,7 @@
28
28
  "dotenv": "^17.1.0",
29
29
  "express": "^4.21.2",
30
30
  "express-static-gzip": "^2.2.0",
31
- "http-proxy-middleware": "^3.0.3",
31
+ "http-proxy-middleware": "^3.0.5",
32
32
  "lokijs": "^1.5.12",
33
33
  "minimatch": "^10.2.4",
34
34
  "pino": "^9.9.0",