env-plugin 0.6.0 → 0.7.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/dist/Container.js +20 -1
- package/dist/PostProxyServer.js +37 -12
- package/dist/client/assets/element-plus-BN_JcO6B.js +19 -0
- package/dist/client/assets/element-plus-SrDBYmqw.css +1 -0
- package/dist/client/assets/index-CcOgzo-G.js +1 -0
- package/dist/client/assets/index-DcxBCPsx.css +1 -0
- package/dist/client/index.html +4 -4
- package/dist/controllers/DevServerController.js +10 -2
- package/dist/controllers/EnvController.js +43 -3
- package/dist/controllers/ImportExportController.js +44 -0
- package/dist/controllers/PasswordController.js +1 -0
- package/dist/controllers/RequestLogController.js +34 -0
- package/dist/controllers/RouteRuleController.js +1 -0
- package/dist/controllers/SystemSettingController.js +43 -0
- package/dist/index.js +13 -11
- package/dist/models/EnvModel.js +31 -3
- package/dist/repositories/DevServerRepo.js +14 -69
- package/dist/repositories/EnvRepo.js +30 -95
- package/dist/repositories/PasswordRepo.js +44 -106
- package/dist/repositories/RouteRuleRepo.js +26 -79
- package/dist/repositories/SystemSettingRepo.js +21 -0
- package/dist/repositories/database.js +11 -84
- package/dist/repositories/migrate.js +198 -0
- package/dist/repositories/store.js +118 -0
- package/dist/routes/index.js +197 -29
- package/dist/service/DevServerService.js +4 -2
- package/dist/service/EnvService.js +67 -7
- package/dist/service/ImportExportService.js +337 -0
- package/dist/service/PasswordService.js +11 -9
- package/dist/service/PreProxyServer.js +158 -36
- package/dist/service/ProxyAutoStarterService.js +3 -0
- package/dist/service/RequestLogService.js +77 -0
- package/dist/service/RouteRuleService.js +18 -16
- package/dist/service/SystemSettingService.js +90 -0
- package/dist/types/index.js +3 -0
- package/dist/types/shared/EnvItem.js +8 -0
- package/dist/types/shared/ImportExport.js +55 -0
- package/dist/types/shared/RequestLog.js +28 -0
- package/dist/types/shared/SystemSetting.js +18 -0
- package/dist/utils/ResolveConfig.js +4 -2
- package/dist/utils/asyncHandler.js +12 -0
- package/dist/utils/errors.js +2 -0
- package/dist/utils/resourceType.js +42 -0
- package/dist/utils/routeBuilder.js +19 -0
- package/package.json +36 -29
- package/templates/inject/envm-switcher.js +1418 -0
- package/dist/client/assets/element-plus-4FTV-s7u.js.gz +0 -0
- package/dist/client/assets/index-C2AH0x8U.css.gz +0 -0
- package/dist/client/assets/index-Db97pusF.js.gz +0 -0
- package/dist/client/assets/vue-CRjr1oeH.js.gz +0 -0
|
@@ -5,9 +5,29 @@ import * as libCookie from "cookie";
|
|
|
5
5
|
import { minimatch } from "minimatch";
|
|
6
6
|
import * as fs from "fs";
|
|
7
7
|
import * as path from "path";
|
|
8
|
+
import * as zlib from "zlib";
|
|
8
9
|
import { getConfig } from "../utils/ResolveConfig.js";
|
|
9
10
|
import { devServerLogger } from "../utils/logger.js";
|
|
11
|
+
import { requestLogEmitter } from "./RequestLogService.js";
|
|
12
|
+
import { getInjectEnabled } from "./SystemSettingService.js";
|
|
13
|
+
import { classifyResourceType } from "../utils/resourceType.js";
|
|
14
|
+
import { randomUUID } from "node:crypto";
|
|
15
|
+
// 以原始请求对象为 key 的请求级缓存,请求结束后自动被 GC 回收
|
|
16
|
+
const requestContextMap = new WeakMap();
|
|
10
17
|
class PreProxyServer {
|
|
18
|
+
envId;
|
|
19
|
+
envRepo;
|
|
20
|
+
devServerRepo;
|
|
21
|
+
routeRuleRepo;
|
|
22
|
+
app;
|
|
23
|
+
/**
|
|
24
|
+
* 代理服务器
|
|
25
|
+
*/
|
|
26
|
+
server;
|
|
27
|
+
/**
|
|
28
|
+
* 保存当前代理的 socket 连接 关闭前先断开所有链接
|
|
29
|
+
*/
|
|
30
|
+
sockets;
|
|
11
31
|
/**
|
|
12
32
|
* 判断该端口是否已经有服务存在
|
|
13
33
|
* @param port
|
|
@@ -16,6 +36,10 @@ class PreProxyServer {
|
|
|
16
36
|
static getAppInsByPort(port) {
|
|
17
37
|
return this.appMap[port];
|
|
18
38
|
}
|
|
39
|
+
/**
|
|
40
|
+
* 保存启动的环境实例
|
|
41
|
+
*/
|
|
42
|
+
static appMap = {};
|
|
19
43
|
static async create(envId, envRepo, devServerRepo, routeRuleRepo) {
|
|
20
44
|
if (this.appMap[envId]) {
|
|
21
45
|
devServerLogger.info(`环境 ${envId} 已经启动`);
|
|
@@ -66,15 +90,30 @@ class PreProxyServer {
|
|
|
66
90
|
const envItem = this.envRepo.findOneById(this.envId);
|
|
67
91
|
return envItem;
|
|
68
92
|
}
|
|
93
|
+
/**
|
|
94
|
+
* 获取(或创建)请求级上下文,缓存当前环境信息与路由规则,
|
|
95
|
+
* 保证一次代理请求内各钩子共享同一份数据、只查询一次数据库。
|
|
96
|
+
*/
|
|
97
|
+
getRequestContext(req) {
|
|
98
|
+
const cached = requestContextMap.get(req);
|
|
99
|
+
if (cached) {
|
|
100
|
+
return cached;
|
|
101
|
+
}
|
|
102
|
+
const ctx = {
|
|
103
|
+
envItem: this.envRepo.findOneById(this.envId) ?? null,
|
|
104
|
+
routeRules: this.routeRuleRepo.getByEnvId(this.envId),
|
|
105
|
+
};
|
|
106
|
+
requestContextMap.set(req, ctx);
|
|
107
|
+
return ctx;
|
|
108
|
+
}
|
|
69
109
|
/**
|
|
70
110
|
* 获取绑定的服务器详情
|
|
71
111
|
*/
|
|
72
112
|
getDevServer() { }
|
|
73
113
|
/**
|
|
74
|
-
*
|
|
114
|
+
* 根据环境信息生成代理 cookie 后缀
|
|
75
115
|
*/
|
|
76
|
-
|
|
77
|
-
const envItem = this.getEnvItem();
|
|
116
|
+
getCookieSuffix(envItem) {
|
|
78
117
|
return `-${envItem?.port}-${PreProxyServer.configCookieSuffix}`;
|
|
79
118
|
}
|
|
80
119
|
/**
|
|
@@ -88,8 +127,7 @@ class PreProxyServer {
|
|
|
88
127
|
* @param requestPath 请求路径
|
|
89
128
|
* @returns 匹配到的目标环境地址,如果没有匹配则返回 null
|
|
90
129
|
*/
|
|
91
|
-
matchRouteRule(requestPath) {
|
|
92
|
-
const routeRules = this.routeRuleRepo.getByEnvId(this.envId);
|
|
130
|
+
matchRouteRule(requestPath, routeRules) {
|
|
93
131
|
// 过滤出已启用的规则
|
|
94
132
|
const enabledRules = routeRules.filter((rule) => rule.enabled !== false);
|
|
95
133
|
// 按 pathPrefix 长度降序排序,确保最长前缀匹配优先
|
|
@@ -109,6 +147,23 @@ class PreProxyServer {
|
|
|
109
147
|
}
|
|
110
148
|
return null;
|
|
111
149
|
}
|
|
150
|
+
/**
|
|
151
|
+
* 根据请求路径匹配路由规则,返回命中的 pathPrefix
|
|
152
|
+
* @param requestPath 请求路径
|
|
153
|
+
* @returns 命中的规则 pathPrefix,未命中返回 'default'
|
|
154
|
+
*/
|
|
155
|
+
getMatchedRule(requestPath, routeRules) {
|
|
156
|
+
// 过滤出已启用的规则
|
|
157
|
+
const enabledRules = routeRules.filter((rule) => rule.enabled !== false);
|
|
158
|
+
// 按 pathPrefix 长度降序排序,确保最长前缀匹配优先
|
|
159
|
+
const sortedRules = [...enabledRules].sort((a, b) => b.pathPrefix.length - a.pathPrefix.length);
|
|
160
|
+
for (const rule of sortedRules) {
|
|
161
|
+
if (minimatch(requestPath, rule.pathPrefix, { dot: true })) {
|
|
162
|
+
return rule.pathPrefix;
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
return "default";
|
|
166
|
+
}
|
|
112
167
|
/**
|
|
113
168
|
* 生成代理中间件
|
|
114
169
|
* @returns
|
|
@@ -121,36 +176,77 @@ class PreProxyServer {
|
|
|
121
176
|
selfHandleResponse: true,
|
|
122
177
|
router: (req) => {
|
|
123
178
|
const requestPath = req.path || "/";
|
|
179
|
+
const ctx = this.getRequestContext(req);
|
|
124
180
|
// 1. 检查是否配置了路由规则
|
|
125
|
-
const customTarget = this.matchRouteRule(requestPath);
|
|
181
|
+
const customTarget = this.matchRouteRule(requestPath, ctx.routeRules);
|
|
126
182
|
if (customTarget) {
|
|
127
183
|
return customTarget;
|
|
128
184
|
}
|
|
129
185
|
// 2. 默认转发到 devServer
|
|
130
|
-
const envItem = this.getEnvItem();
|
|
131
186
|
const devServerConfig = this.devServerRepo.findOneById({
|
|
132
|
-
id: envItem?.devServerId ?? "",
|
|
187
|
+
id: ctx.envItem?.devServerId ?? "",
|
|
133
188
|
});
|
|
134
189
|
return `${devServerConfig?.devServerUrl}`;
|
|
135
190
|
},
|
|
136
191
|
on: {
|
|
137
192
|
proxyReq: (proxyReq, req) => {
|
|
138
193
|
const requestPath = req.path || "/";
|
|
194
|
+
const ctx = this.getRequestContext(req);
|
|
195
|
+
// 记录请求开始时间和日志 ID(用于 proxyRes 中的日志捕获)
|
|
196
|
+
req.__logStartTime = Date.now();
|
|
197
|
+
req.__logId = randomUUID();
|
|
139
198
|
// 优先使用路由规则的目标地址,否则使用环境默认的 apiBaseUrl
|
|
140
|
-
const customTarget = this.matchRouteRule(requestPath);
|
|
141
|
-
const target = customTarget || `${
|
|
199
|
+
const customTarget = this.matchRouteRule(requestPath, ctx.routeRules);
|
|
200
|
+
const target = customTarget || `${ctx.envItem?.apiBaseUrl}`;
|
|
142
201
|
proxyReq.setHeader("x-api-server", `${target}`);
|
|
143
|
-
this._rewrieCookieOnProxyReq(proxyReq, req);
|
|
202
|
+
this._rewrieCookieOnProxyReq(proxyReq, req, ctx.envItem);
|
|
144
203
|
},
|
|
145
204
|
proxyRes: (proxyRes, req, res) => {
|
|
146
|
-
this.
|
|
205
|
+
const ctx = this.getRequestContext(req);
|
|
206
|
+
// --- 请求日志捕获 ---
|
|
207
|
+
const startTime = req
|
|
208
|
+
.__logStartTime;
|
|
209
|
+
if (startTime) {
|
|
210
|
+
const duration = Date.now() - startTime;
|
|
211
|
+
const requestPath = req.path || "/";
|
|
212
|
+
// 确定命中的路由规则
|
|
213
|
+
const matchedRule = this.getMatchedRule(requestPath, ctx.routeRules);
|
|
214
|
+
requestLogEmitter.emit("log", {
|
|
215
|
+
id: req.__logId || randomUUID(),
|
|
216
|
+
timestamp: startTime,
|
|
217
|
+
method: req.method || "UNKNOWN",
|
|
218
|
+
url: requestPath,
|
|
219
|
+
statusCode: proxyRes.statusCode || 0,
|
|
220
|
+
duration,
|
|
221
|
+
matchedRule,
|
|
222
|
+
resourceType: classifyResourceType(matchedRule, proxyRes.headers["content-type"], requestPath),
|
|
223
|
+
envId: this.envId,
|
|
224
|
+
envName: ctx.envItem?.name || ctx.envItem?.apiBaseUrl || "",
|
|
225
|
+
});
|
|
226
|
+
}
|
|
227
|
+
this._rewriteSetCookieOnProxyRes(proxyRes, ctx.envItem);
|
|
147
228
|
this._rewriteLoginRedirect(proxyRes, req, res);
|
|
148
229
|
},
|
|
149
230
|
proxyReqWs: (proxyReq, req) => {
|
|
150
231
|
const requestPath = req.path || "/";
|
|
151
|
-
const
|
|
152
|
-
const
|
|
232
|
+
const ctx = this.getRequestContext(req);
|
|
233
|
+
const customTarget = this.matchRouteRule(requestPath, ctx.routeRules);
|
|
234
|
+
const target = customTarget || `${ctx.envItem?.apiBaseUrl}`;
|
|
153
235
|
proxyReq.setHeader("x-api-server", `${target}`);
|
|
236
|
+
// WebSocket 连接日志(无真实 HTTP 状态码,约定 101 Switching Protocols)
|
|
237
|
+
const matchedRule = this.getMatchedRule(requestPath, ctx.routeRules);
|
|
238
|
+
requestLogEmitter.emit("log", {
|
|
239
|
+
id: randomUUID(),
|
|
240
|
+
timestamp: Date.now(),
|
|
241
|
+
method: "WS",
|
|
242
|
+
url: requestPath,
|
|
243
|
+
statusCode: 101,
|
|
244
|
+
duration: 0,
|
|
245
|
+
matchedRule,
|
|
246
|
+
resourceType: "websocket",
|
|
247
|
+
envId: this.envId,
|
|
248
|
+
envName: ctx.envItem?.name || ctx.envItem?.apiBaseUrl || "",
|
|
249
|
+
});
|
|
154
250
|
},
|
|
155
251
|
},
|
|
156
252
|
});
|
|
@@ -160,17 +256,17 @@ class PreProxyServer {
|
|
|
160
256
|
* 给 每一个 setcookie 追加保存一个 代理cookie
|
|
161
257
|
* @param proxyRes
|
|
162
258
|
*/
|
|
163
|
-
_rewriteSetCookieOnProxyRes(proxyRes) {
|
|
164
|
-
const envItem = this.getEnvItem();
|
|
259
|
+
_rewriteSetCookieOnProxyRes(proxyRes, envItem) {
|
|
165
260
|
const setCookie = proxyRes.headers["set-cookie"];
|
|
166
261
|
if (envItem && setCookie) {
|
|
167
262
|
const setCookies = setCookieParser.parse(setCookie);
|
|
263
|
+
const cookieSuffix = this.getCookieSuffix(envItem);
|
|
168
264
|
const proxyCookie = setCookies.map((item) => {
|
|
169
265
|
const cookie = {
|
|
170
266
|
...item,
|
|
171
|
-
name: `${item.name}${
|
|
267
|
+
name: `${item.name}${cookieSuffix}`,
|
|
172
268
|
};
|
|
173
|
-
return libCookie.
|
|
269
|
+
return libCookie.stringifySetCookie(cookie);
|
|
174
270
|
});
|
|
175
271
|
setCookie.push(...proxyCookie);
|
|
176
272
|
}
|
|
@@ -178,20 +274,20 @@ class PreProxyServer {
|
|
|
178
274
|
/**
|
|
179
275
|
* 代理 转发的时候,将对应端口的cookie 重写回去
|
|
180
276
|
*/
|
|
181
|
-
_rewrieCookieOnProxyReq(proxyReq, req) {
|
|
182
|
-
const envItem = this.getEnvItem();
|
|
277
|
+
_rewrieCookieOnProxyReq(proxyReq, req, envItem) {
|
|
183
278
|
if (envItem && req.headers.cookie) {
|
|
184
|
-
const cookie = libCookie.
|
|
279
|
+
const cookie = libCookie.parseCookie(req.headers.cookie || "");
|
|
280
|
+
const cookieSuffix = this.getCookieSuffix(envItem);
|
|
185
281
|
const newCookies = [];
|
|
186
282
|
Object.keys(cookie).forEach((item) => {
|
|
187
283
|
if (item.endsWith(PreProxyServer.configCookieSuffix)) {
|
|
188
284
|
return;
|
|
189
285
|
}
|
|
190
|
-
let cookieName = `${item}${
|
|
286
|
+
let cookieName = `${item}${cookieSuffix}`;
|
|
191
287
|
if (!cookie[cookieName]) {
|
|
192
288
|
cookieName = item;
|
|
193
289
|
}
|
|
194
|
-
newCookies.push(libCookie.
|
|
290
|
+
newCookies.push(libCookie.stringifyCookie({ [item]: cookie[cookieName] || "" }));
|
|
195
291
|
});
|
|
196
292
|
proxyReq.setHeader("cookie", newCookies.join(";"));
|
|
197
293
|
}
|
|
@@ -211,18 +307,48 @@ class PreProxyServer {
|
|
|
211
307
|
try {
|
|
212
308
|
const body = Buffer.concat(chunks);
|
|
213
309
|
// 只对 HTML 且配置了注入脚本目录
|
|
214
|
-
|
|
310
|
+
// 且注入资源功能开关开启时,才执行脚本注入
|
|
311
|
+
if (contentType.includes("text/html") && getInjectEnabled()) {
|
|
215
312
|
const config = getConfig();
|
|
216
313
|
const scriptDir = config.injectScriptDir;
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
314
|
+
// 开发服务器(Vite/Webpack/Rspack 等)可能对响应开启 gzip/br 压缩,
|
|
315
|
+
// 此时 body 是压缩后的二进制数据:直接按 utf8 解码会得到乱码,
|
|
316
|
+
// 注入后返回的未压缩内容却仍带着 Content-Encoding 头,浏览器按
|
|
317
|
+
// 该编码解压就会报 ERR_CONTENT_DECODING_FAILED。
|
|
318
|
+
// 因此先解压再注入,最后按原编码重新压缩,保持响应头与响应体一致。
|
|
319
|
+
const contentEncoding = String(proxyRes.headers["content-encoding"] || "").toLowerCase();
|
|
320
|
+
let decodedBody = body;
|
|
321
|
+
if (contentEncoding === "gzip" || contentEncoding === "x-gzip") {
|
|
322
|
+
decodedBody = zlib.gunzipSync(body);
|
|
323
|
+
}
|
|
324
|
+
else if (contentEncoding === "deflate") {
|
|
325
|
+
decodedBody = zlib.inflateSync(body);
|
|
326
|
+
}
|
|
327
|
+
else if (contentEncoding === "br") {
|
|
328
|
+
decodedBody = zlib.brotliDecompressSync(body);
|
|
329
|
+
}
|
|
330
|
+
let html = decodedBody.toString("utf8");
|
|
331
|
+
// 读取用户自定义文件夹下所有 js 文件(排除 # 开头的文件)
|
|
332
|
+
const userScriptTags = scriptDir
|
|
333
|
+
? this.generateImportScripts(scriptDir)
|
|
334
|
+
: "";
|
|
335
|
+
// 始终注入内置的环境快速切换面板脚本
|
|
336
|
+
const builtInScriptTag = '<script type="module" src="/envm-inject/envm-switcher.js"></script>';
|
|
337
|
+
const allScriptTags = [userScriptTags, builtInScriptTag]
|
|
338
|
+
.filter(Boolean)
|
|
339
|
+
.join("\n");
|
|
340
|
+
html = html.replace(/<\/body>\s*<\/html>/gi, `${allScriptTags}</body></html>`);
|
|
341
|
+
let newBody = Buffer.from(html, "utf8");
|
|
342
|
+
// 若原响应为压缩内容,注入后按相同编码重新压缩
|
|
343
|
+
if (contentEncoding === "gzip" || contentEncoding === "x-gzip") {
|
|
344
|
+
newBody = zlib.gzipSync(newBody);
|
|
345
|
+
}
|
|
346
|
+
else if (contentEncoding === "deflate") {
|
|
347
|
+
newBody = zlib.deflateSync(newBody);
|
|
348
|
+
}
|
|
349
|
+
else if (contentEncoding === "br") {
|
|
350
|
+
newBody = zlib.brotliCompressSync(newBody);
|
|
220
351
|
}
|
|
221
|
-
let html = body.toString("utf8");
|
|
222
|
-
// 读取文件夹下所有 js 文件(排除 # 开头的文件)
|
|
223
|
-
const scriptTags = this.generateImportScripts(scriptDir);
|
|
224
|
-
html = html.replace(/<\/body>\s*<\/html>/gi, `${scriptTags}</body></html>`);
|
|
225
|
-
const newBody = Buffer.from(html, "utf8");
|
|
226
352
|
res.setHeader("Content-Length", newBody.length);
|
|
227
353
|
res.end(newBody);
|
|
228
354
|
}
|
|
@@ -322,8 +448,4 @@ class PreProxyServer {
|
|
|
322
448
|
});
|
|
323
449
|
}
|
|
324
450
|
}
|
|
325
|
-
/**
|
|
326
|
-
* 保存启动的环境实例
|
|
327
|
-
*/
|
|
328
|
-
PreProxyServer.appMap = {};
|
|
329
451
|
export default PreProxyServer;
|
|
@@ -5,6 +5,9 @@ import { logger } from "../utils/logger.js";
|
|
|
5
5
|
* 负责在应用启动时检查并启动数据库中状态为运行的代理
|
|
6
6
|
*/
|
|
7
7
|
export class ProxyAutoStarter {
|
|
8
|
+
envRepo;
|
|
9
|
+
proxyService;
|
|
10
|
+
routeRuleRepo;
|
|
8
11
|
constructor(envRepo, proxyService, routeRuleRepo) {
|
|
9
12
|
this.envRepo = envRepo;
|
|
10
13
|
this.proxyService = proxyService;
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import { EventEmitter } from "events";
|
|
2
|
+
import { proxyLogger } from "../utils/logger.js";
|
|
3
|
+
import { getLogEnabled } from "./SystemSettingService.js";
|
|
4
|
+
const MAX_LOG_ENTRIES = 500;
|
|
5
|
+
/** 模块级单例 EventEmitter — PreProxyServer 直接导入使用 */
|
|
6
|
+
export const requestLogEmitter = new EventEmitter();
|
|
7
|
+
class RequestLogService {
|
|
8
|
+
logs = [];
|
|
9
|
+
logSubscribers = new Set();
|
|
10
|
+
handleLog = (entry) => {
|
|
11
|
+
this.addLog(entry);
|
|
12
|
+
};
|
|
13
|
+
constructor() {
|
|
14
|
+
// 监听 PreProxyServer 发出的日志事件
|
|
15
|
+
requestLogEmitter.on("log", this.handleLog);
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* 释放资源:从全局事件总线移除本实例的日志监听器。
|
|
19
|
+
* 重复实例化(如测试中多次 createTestApp)时务必调用,避免监听器累积。
|
|
20
|
+
*/
|
|
21
|
+
dispose() {
|
|
22
|
+
requestLogEmitter.off("log", this.handleLog);
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* 添加日志条目(环形缓冲区,最多保留 MAX_LOG_ENTRIES 条)
|
|
26
|
+
*/
|
|
27
|
+
addLog(entry) {
|
|
28
|
+
// 请求日志记录开关关闭(默认暂停)时不记录、不推送
|
|
29
|
+
if (!getLogEnabled()) {
|
|
30
|
+
return;
|
|
31
|
+
}
|
|
32
|
+
if (this.logs.length >= MAX_LOG_ENTRIES) {
|
|
33
|
+
this.logs.shift();
|
|
34
|
+
}
|
|
35
|
+
this.logs.push(entry);
|
|
36
|
+
// 通知所有订阅者(用于 WebSocket 实时推送)
|
|
37
|
+
for (const subscriber of this.logSubscribers) {
|
|
38
|
+
try {
|
|
39
|
+
subscriber(entry);
|
|
40
|
+
}
|
|
41
|
+
catch (err) {
|
|
42
|
+
proxyLogger.error(err, "日志订阅者通知失败");
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* 获取日志列表(支持 URL 模糊匹配和状态码精确过滤)
|
|
48
|
+
*/
|
|
49
|
+
getLogs(filter) {
|
|
50
|
+
let result = [...this.logs];
|
|
51
|
+
if (filter?.url) {
|
|
52
|
+
const lower = filter.url.toLowerCase();
|
|
53
|
+
result = result.filter((e) => e.url.toLowerCase().includes(lower));
|
|
54
|
+
}
|
|
55
|
+
if (filter?.statusCode !== undefined) {
|
|
56
|
+
result = result.filter((e) => e.statusCode === filter.statusCode);
|
|
57
|
+
}
|
|
58
|
+
return result;
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* 获取全部日志历史
|
|
62
|
+
*/
|
|
63
|
+
getAllLogs() {
|
|
64
|
+
return [...this.logs];
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* 订阅新日志条目(用于 WebSocket 客户端推送)
|
|
68
|
+
* 返回取消订阅函数
|
|
69
|
+
*/
|
|
70
|
+
subscribe(callback) {
|
|
71
|
+
this.logSubscribers.add(callback);
|
|
72
|
+
return () => {
|
|
73
|
+
this.logSubscribers.delete(callback);
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
export { RequestLogService };
|
|
@@ -1,10 +1,13 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { AppError } from "../utils/errors.js";
|
|
2
3
|
/**
|
|
3
4
|
* 路由规则服务类
|
|
4
5
|
* 负责处理与路由规则相关的核心业务逻辑,包括路由规则的增删改查等操作
|
|
5
6
|
* 依赖路由规则仓库(RouteRuleRepo)和环境仓库(EnvRepo)实现数据持久化和关联操作
|
|
6
7
|
*/
|
|
7
8
|
class RouteRuleService {
|
|
9
|
+
routeRuleRepo;
|
|
10
|
+
envRepo;
|
|
8
11
|
/**
|
|
9
12
|
* 构造函数 - 通过依赖注入初始化仓库实例
|
|
10
13
|
* @param routeRuleRepo - 路由规则仓库实例,用于路由规则数据的持久化操作
|
|
@@ -39,7 +42,7 @@ class RouteRuleService {
|
|
|
39
42
|
* 1. 校验输入参数合法性 2. 检查目标环境是否存在 3. 生成唯一ID 4. 保存
|
|
40
43
|
* @param routeRuleItem - 待添加的路由规则信息(不含ID)
|
|
41
44
|
* @returns 新创建的路由规则
|
|
42
|
-
* @throws {
|
|
45
|
+
* @throws {AppError} 当输入参数不合法或目标环境不存在时抛出
|
|
43
46
|
*/
|
|
44
47
|
handleAdd(routeRuleItem) {
|
|
45
48
|
const { envId, pathPrefix, targetEnvId } = routeRuleItem;
|
|
@@ -47,22 +50,22 @@ class RouteRuleService {
|
|
|
47
50
|
if (targetEnvId) {
|
|
48
51
|
const targetEnv = this.envRepo.findOneById(targetEnvId);
|
|
49
52
|
if (!targetEnv) {
|
|
50
|
-
throw new
|
|
53
|
+
throw new AppError(`添加失败,目标环境【${targetEnvId}】不存在`);
|
|
51
54
|
}
|
|
52
55
|
}
|
|
53
56
|
// 目标环境不能为空
|
|
54
57
|
if (!targetEnvId) {
|
|
55
|
-
throw new
|
|
58
|
+
throw new AppError("添加失败,目标环境不能为空");
|
|
56
59
|
}
|
|
57
60
|
// 检查是否已存在相同路径前缀的规则(同一环境下)
|
|
58
61
|
if (this.routeRuleRepo.existsByEnvIdAndPathPrefix(envId, pathPrefix)) {
|
|
59
|
-
throw new
|
|
62
|
+
throw new AppError(`添加失败,该环境下已存在路径前缀【${pathPrefix}】的规则`);
|
|
60
63
|
}
|
|
61
64
|
// 生成唯一ID并组装完整路由规则信息
|
|
62
65
|
const now = new Date().toISOString();
|
|
63
66
|
const newRouteRule = {
|
|
64
67
|
...routeRuleItem,
|
|
65
|
-
id:
|
|
68
|
+
id: randomUUID(),
|
|
66
69
|
createdAt: now,
|
|
67
70
|
updatedAt: now,
|
|
68
71
|
};
|
|
@@ -75,33 +78,32 @@ class RouteRuleService {
|
|
|
75
78
|
* 1. 校验输入参数 2. 检查规则是否存在 3. 检查目标环境是否存在 4. 执行更新
|
|
76
79
|
* @param routeRuleItem - 包含待更新路由规则ID及字段的对象
|
|
77
80
|
* @returns 更新后的路由规则
|
|
78
|
-
* @throws {
|
|
81
|
+
* @throws {AppError} 当输入参数不合法或规则/目标环境不存在时抛出
|
|
79
82
|
*/
|
|
80
83
|
handleUpdate(routeRuleItem) {
|
|
81
84
|
const { id, targetEnvId } = routeRuleItem;
|
|
82
85
|
// 检查路由规则是否存在
|
|
83
86
|
const existingRule = this.routeRuleRepo.findOneById(id);
|
|
84
87
|
if (!existingRule) {
|
|
85
|
-
throw new
|
|
88
|
+
throw new AppError(`更新失败,路由规则【${id}】不存在`);
|
|
86
89
|
}
|
|
87
|
-
//
|
|
88
|
-
|
|
89
|
-
if (shouldClearTarget) {
|
|
90
|
+
// 判断是否需要清空目标环境(只有明确发送空字符串时才清空)
|
|
91
|
+
if (targetEnvId === "") {
|
|
90
92
|
// 清空目标环境
|
|
91
93
|
routeRuleItem.targetEnvId = "";
|
|
92
94
|
}
|
|
93
|
-
else if (targetEnvId !== existingRule.targetEnvId) {
|
|
95
|
+
else if (targetEnvId !== undefined && targetEnvId !== existingRule.targetEnvId) {
|
|
94
96
|
// 更新了目标环境,检查目标环境是否存在
|
|
95
97
|
const targetEnv = this.envRepo.findOneById(targetEnvId);
|
|
96
98
|
if (!targetEnv) {
|
|
97
|
-
throw new
|
|
99
|
+
throw new AppError(`更新失败,目标环境【${targetEnvId}】不存在`);
|
|
98
100
|
}
|
|
99
101
|
}
|
|
100
102
|
// 如果更新了路径前缀,检查是否与其他规则冲突
|
|
101
103
|
if (routeRuleItem.pathPrefix &&
|
|
102
104
|
routeRuleItem.pathPrefix !== existingRule.pathPrefix) {
|
|
103
105
|
if (this.routeRuleRepo.existsByEnvIdAndPathPrefix(existingRule.envId, routeRuleItem.pathPrefix)) {
|
|
104
|
-
throw new
|
|
106
|
+
throw new AppError(`更新失败,该环境下已存在路径前缀【${routeRuleItem.pathPrefix}】的规则`);
|
|
105
107
|
}
|
|
106
108
|
}
|
|
107
109
|
// 添加更新时间
|
|
@@ -115,14 +117,14 @@ class RouteRuleService {
|
|
|
115
117
|
* 删除指定路由规则
|
|
116
118
|
* 1. 校验输入参数 2. 检查规则是否存在 3. 执行删除操作
|
|
117
119
|
* @param routeRuleItem - 包含待删除路由规则ID的对象
|
|
118
|
-
* @throws {
|
|
120
|
+
* @throws {AppError} 当输入参数不合法或规则不存在时抛出
|
|
119
121
|
*/
|
|
120
122
|
handleDelete(routeRuleItem) {
|
|
121
123
|
const { id } = routeRuleItem;
|
|
122
124
|
// 检查路由规则是否存在
|
|
123
125
|
const existingRule = this.routeRuleRepo.findOneById(id);
|
|
124
126
|
if (!existingRule) {
|
|
125
|
-
throw new
|
|
127
|
+
throw new AppError(`删除失败,路由规则【${id}】不存在`);
|
|
126
128
|
}
|
|
127
129
|
// 执行删除
|
|
128
130
|
this.routeRuleRepo.delete(routeRuleItem);
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import { SystemSettingRepo } from "../repositories/SystemSettingRepo.js";
|
|
2
|
+
/**
|
|
3
|
+
* 模块级内存缓存:系统设置开关的单一事实来源。
|
|
4
|
+
*
|
|
5
|
+
* - 注入资源开关默认关闭(false)
|
|
6
|
+
* - 请求日志记录开关默认暂停(false)
|
|
7
|
+
*
|
|
8
|
+
* 这些函数必须纯内存同步、不访问 getDatabase(),否则会破坏
|
|
9
|
+
* PreProxyServer 集成测试(该测试未初始化数据库)。
|
|
10
|
+
*/
|
|
11
|
+
let injectEnabled = false;
|
|
12
|
+
let logEnabled = false;
|
|
13
|
+
/**
|
|
14
|
+
* 获取注入资源开关状态(纯内存、同步,供 PreProxyServer 直接使用)
|
|
15
|
+
* @returns 是否开启注入资源
|
|
16
|
+
*/
|
|
17
|
+
export function getInjectEnabled() {
|
|
18
|
+
return injectEnabled;
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* 获取请求日志记录开关状态(纯内存、同步,供 RequestLogService 直接使用)
|
|
22
|
+
* @returns 是否开启请求日志记录
|
|
23
|
+
*/
|
|
24
|
+
export function getLogEnabled() {
|
|
25
|
+
return logEnabled;
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* 系统设置服务
|
|
29
|
+
* 负责系统设置的读取与更新,通过 Repository 实现持久化
|
|
30
|
+
*/
|
|
31
|
+
class SystemSettingService {
|
|
32
|
+
repo;
|
|
33
|
+
constructor(repo = new SystemSettingRepo()) {
|
|
34
|
+
this.repo = repo;
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* 获取注入资源开关状态
|
|
38
|
+
* @returns 是否开启注入资源
|
|
39
|
+
*/
|
|
40
|
+
getInjectEnabled() {
|
|
41
|
+
return injectEnabled;
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* 获取请求日志记录开关状态
|
|
45
|
+
* @returns 是否开启请求日志记录
|
|
46
|
+
*/
|
|
47
|
+
getLogEnabled() {
|
|
48
|
+
return logEnabled;
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* 一次性更新全部系统设置开关。
|
|
52
|
+
* 先落库、成功后再更新内存缓存,避免写入失败导致内存态与库不一致。
|
|
53
|
+
* @param nextInjectEnabled - 是否开启注入资源
|
|
54
|
+
* @param nextLogEnabled - 是否开启请求日志记录
|
|
55
|
+
*/
|
|
56
|
+
setSettings(nextInjectEnabled, nextLogEnabled) {
|
|
57
|
+
this.persist(nextInjectEnabled, nextLogEnabled);
|
|
58
|
+
injectEnabled = nextInjectEnabled;
|
|
59
|
+
logEnabled = nextLogEnabled;
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* 初始化:从数据库读取持久化值同步到内存缓存。
|
|
63
|
+
* 数据库就绪后调用(在 index.ts 的 startDatabase 之后)。
|
|
64
|
+
* 空库时 seed 默认记录(注入关闭、日志暂停)。
|
|
65
|
+
*/
|
|
66
|
+
init() {
|
|
67
|
+
const existing = this.repo.getGlobal();
|
|
68
|
+
if (existing) {
|
|
69
|
+
injectEnabled = existing.injectEnabled;
|
|
70
|
+
// 兼容旧数据:早期版本可能没有 logEnabled 字段
|
|
71
|
+
logEnabled = existing.logEnabled ?? false;
|
|
72
|
+
}
|
|
73
|
+
else {
|
|
74
|
+
injectEnabled = false;
|
|
75
|
+
logEnabled = false;
|
|
76
|
+
this.persist(injectEnabled, logEnabled);
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* 将给定状态全量写入数据库
|
|
81
|
+
*/
|
|
82
|
+
persist(nextInjectEnabled, nextLogEnabled) {
|
|
83
|
+
this.repo.upsert({
|
|
84
|
+
id: "global",
|
|
85
|
+
injectEnabled: nextInjectEnabled,
|
|
86
|
+
logEnabled: nextLogEnabled,
|
|
87
|
+
});
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
export { SystemSettingService };
|
package/dist/types/index.js
CHANGED
|
@@ -3,3 +3,6 @@ export * from "./shared/DevServerItem.js";
|
|
|
3
3
|
export * from "./shared/EnvmConfig.js";
|
|
4
4
|
export * from "./shared/RouteRule.js";
|
|
5
5
|
export * from "./shared/Password.js";
|
|
6
|
+
export * from "./shared/RequestLog.js";
|
|
7
|
+
export * from "./shared/ImportExport.js";
|
|
8
|
+
export * from "./shared/SystemSetting.js";
|
|
@@ -66,3 +66,11 @@ export const EnvSortSchema = z.object({
|
|
|
66
66
|
sortOrder: z.number(),
|
|
67
67
|
})),
|
|
68
68
|
});
|
|
69
|
+
/**
|
|
70
|
+
* 环境切换Schema
|
|
71
|
+
* 用于切换环境时的参数验证
|
|
72
|
+
*/
|
|
73
|
+
export const EnvSwitchSchema = z.object({
|
|
74
|
+
currentEnvId: z.string().describe("当前环境ID"),
|
|
75
|
+
targetEnvId: z.string().describe("目标环境ID"),
|
|
76
|
+
});
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
// ---- 导出数据子 Schema ----
|
|
3
|
+
/** 导出的开发服务器(不含 id,通过 devServerUrl 做跨安装匹配) */
|
|
4
|
+
export const ExportDevServerSchema = z.object({
|
|
5
|
+
name: z.string(),
|
|
6
|
+
devServerUrl: z.string(),
|
|
7
|
+
description: z.string().optional(),
|
|
8
|
+
});
|
|
9
|
+
/** 导出的路由规则(targetEnvId 转为 targetEnvApiBaseUrl 做跨安装引用) */
|
|
10
|
+
export const ExportRouteRuleSchema = z.object({
|
|
11
|
+
pathPrefix: z.string().min(1),
|
|
12
|
+
targetEnvApiBaseUrl: z.string().optional(),
|
|
13
|
+
description: z.string().optional(),
|
|
14
|
+
enabled: z.boolean().optional().default(true),
|
|
15
|
+
});
|
|
16
|
+
/** 导出的密码 */
|
|
17
|
+
export const ExportPasswordSchema = z.object({
|
|
18
|
+
name: z.string().min(1),
|
|
19
|
+
username: z.string().min(1),
|
|
20
|
+
password: z.string().min(1),
|
|
21
|
+
description: z.string().optional(),
|
|
22
|
+
isDefault: z.boolean().optional().default(false),
|
|
23
|
+
});
|
|
24
|
+
/** 导出的环境(包含关联的 routeRules 和 passwords) */
|
|
25
|
+
export const ExportEnvSchema = z.object({
|
|
26
|
+
apiBaseUrl: z.string(),
|
|
27
|
+
port: z.number().int().min(1).max(65535),
|
|
28
|
+
name: z.string().optional(),
|
|
29
|
+
description: z.string().optional(),
|
|
30
|
+
devServerUrl: z.string().optional(),
|
|
31
|
+
homePage: z.string().optional(),
|
|
32
|
+
routeRules: z.array(ExportRouteRuleSchema).optional().default([]),
|
|
33
|
+
passwords: z.array(ExportPasswordSchema).optional().default([]),
|
|
34
|
+
});
|
|
35
|
+
// ---- 顶层导出文件 Schema ----
|
|
36
|
+
export const EXPORT_VERSION = "1.0.0";
|
|
37
|
+
export const ExportDataSchema = z.object({
|
|
38
|
+
version: z.literal(EXPORT_VERSION),
|
|
39
|
+
exportedAt: z.string(),
|
|
40
|
+
encrypted: z.boolean().optional().default(false),
|
|
41
|
+
devServers: z.array(ExportDevServerSchema).optional().default([]),
|
|
42
|
+
envs: z.array(ExportEnvSchema),
|
|
43
|
+
});
|
|
44
|
+
// ---- 导入/导出请求 Schema ----
|
|
45
|
+
export const ExportRequestSchema = z.object({
|
|
46
|
+
/** 要导出的环境 ID 列表;为空则导出全部 */
|
|
47
|
+
envIds: z.array(z.string()).optional(),
|
|
48
|
+
/** 加密密码;提供则对 passwords 中的 password 字段做 AES 加密 */
|
|
49
|
+
encryptPassword: z.string().optional(),
|
|
50
|
+
});
|
|
51
|
+
export const ImportRequestSchema = z.object({
|
|
52
|
+
data: ExportDataSchema,
|
|
53
|
+
conflictStrategy: z.enum(["skip", "overwrite"]).optional().default("skip"),
|
|
54
|
+
decryptPassword: z.string().optional(),
|
|
55
|
+
});
|