@gylautorun/dev-proxy-cookie 1.0.2 → 1.0.4
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 +212 -236
- package/dist/index.d.mts +61 -2
- package/dist/index.d.ts +61 -2
- package/dist/index.js +105 -29
- package/dist/index.min.js +4 -4
- package/dist/index.min.mjs +4 -4
- package/dist/index.mjs +104 -29
- package/package.json +1 -1
- package/src/proxy/apply-dev-authentications.ts +40 -0
- package/src/proxy/core.ts +37 -6
- package/src/proxy/index.ts +1 -0
- package/src/proxy/vite-middleware-plugin.ts +50 -15
- package/src/proxy/vue-proxy-config.ts +53 -14
package/dist/index.d.mts
CHANGED
|
@@ -2,6 +2,26 @@ import * as net from 'net';
|
|
|
2
2
|
import { IncomingMessage, ServerResponse } from 'http';
|
|
3
3
|
import { ViteDevServer } from 'vite';
|
|
4
4
|
|
|
5
|
+
/**
|
|
6
|
+
* 应用开发环境自定义鉴权信息到代理请求头
|
|
7
|
+
*
|
|
8
|
+
* 将自定义鉴权信息数组展开为请求头键值对,注入到代理请求中。
|
|
9
|
+
* 支持多种鉴权方式,如 ticket、token、Authorization 等。
|
|
10
|
+
*
|
|
11
|
+
* @module apply-dev-authentications
|
|
12
|
+
*/
|
|
13
|
+
type AuthenticationItem = Record<string, string>;
|
|
14
|
+
/**
|
|
15
|
+
* 将自定义鉴权信息数组应用到代理请求头
|
|
16
|
+
*
|
|
17
|
+
* @param proxyReq - 代理请求对象
|
|
18
|
+
* @param authentications - 鉴权信息数组,每个元素是一个键值对对象
|
|
19
|
+
*/
|
|
20
|
+
declare function applyDevAuthentications(proxyReq: {
|
|
21
|
+
setHeader(name: string, value: string): void;
|
|
22
|
+
getHeader?(name: string): string | string[] | undefined;
|
|
23
|
+
}, authentications: AuthenticationItem[]): void;
|
|
24
|
+
|
|
5
25
|
/**
|
|
6
26
|
* 错误回调函数类型
|
|
7
27
|
* @param err - 错误对象
|
|
@@ -64,6 +84,19 @@ interface AutoProxyCookieOptions {
|
|
|
64
84
|
* 使用示例: isDev: process.env.NODE_ENV === 'development'
|
|
65
85
|
*/
|
|
66
86
|
isDev?: boolean;
|
|
87
|
+
/**
|
|
88
|
+
* 是否使用 Cookie 文件中的 Cookie 注入到请求中
|
|
89
|
+
* - true: 使用文件中的 Cookie(默认)
|
|
90
|
+
* - false: 不注入 Cookie,使用浏览器发送的 Cookie
|
|
91
|
+
*
|
|
92
|
+
* 当使用账号密码登录时,设置为 false,避免覆盖浏览器的登录 Cookie
|
|
93
|
+
*/
|
|
94
|
+
useCookie?: boolean;
|
|
95
|
+
/**
|
|
96
|
+
* 自定义鉴权信息数组,每个元素是一个键值对对象,会被注入到请求头中
|
|
97
|
+
* 例如: [{ 'ticket': 'xxxx' }, { 'X-Custom-Token': 'yyyy' }]
|
|
98
|
+
*/
|
|
99
|
+
authentications?: AuthenticationItem[];
|
|
67
100
|
}
|
|
68
101
|
/**
|
|
69
102
|
* 自动代理 Cookie 类
|
|
@@ -177,12 +210,25 @@ declare function createAutoProxyCookie(options: AutoProxyCookieOptions): AutoPro
|
|
|
177
210
|
* Vite 中间件代理 Cookie 插件配置选项
|
|
178
211
|
*/
|
|
179
212
|
interface ViteMiddlewareProxyOptions {
|
|
180
|
-
/** Cookie
|
|
213
|
+
/** Cookie 文件路径, 使用文件方便监听cookie 变化,避免手动启动更新 */
|
|
181
214
|
cookieFile: string;
|
|
182
215
|
/** 默认代理目标地址 */
|
|
183
216
|
target: string;
|
|
184
217
|
/** 是否启用调试日志 */
|
|
185
218
|
debug?: boolean;
|
|
219
|
+
/**
|
|
220
|
+
* 是否使用 Cookie 文件中的 Cookie 注入到请求中
|
|
221
|
+
* - true: 使用文件中的 Cookie(默认)
|
|
222
|
+
* - false: 不注入 Cookie,使用浏览器发送的 Cookie
|
|
223
|
+
*
|
|
224
|
+
* 当使用账号密码登录时,设置为 false,避免覆盖浏览器的登录 Cookie
|
|
225
|
+
*/
|
|
226
|
+
useCookie?: boolean;
|
|
227
|
+
/**
|
|
228
|
+
* 自定义鉴权信息数组,每个元素是一个键值对对象,会被注入到请求头中
|
|
229
|
+
* 例如: [{ 'ticket': 'xxxx' }, { 'X-Custom-Token': 'yyyy' }]
|
|
230
|
+
*/
|
|
231
|
+
authentications?: AuthenticationItem[];
|
|
186
232
|
/**
|
|
187
233
|
* 代理路径映射表
|
|
188
234
|
* 键:路径前缀,值:代理目标地址
|
|
@@ -252,6 +298,19 @@ interface VueProxyConfigOptions {
|
|
|
252
298
|
getCookie?: () => string;
|
|
253
299
|
/** 是否输出调试日志 */
|
|
254
300
|
debug?: boolean;
|
|
301
|
+
/**
|
|
302
|
+
* 是否使用 Cookie 文件中的 Cookie 注入到请求中
|
|
303
|
+
* - true: 使用文件中的 Cookie(默认)
|
|
304
|
+
* - false: 不注入 Cookie,使用浏览器发送的 Cookie
|
|
305
|
+
*
|
|
306
|
+
* 当使用账号密码登录时,设置为 false,避免覆盖浏览器的登录 Cookie
|
|
307
|
+
*/
|
|
308
|
+
useCookie?: boolean;
|
|
309
|
+
/**
|
|
310
|
+
* 自定义鉴权信息数组,每个元素是一个键值对对象,会被注入到请求头中
|
|
311
|
+
* 例如: [{ 'ticket': 'xxxx' }, { 'X-Custom-Token': 'yyyy' }]
|
|
312
|
+
*/
|
|
313
|
+
authentications?: AuthenticationItem[];
|
|
255
314
|
/** 自定义请求头 */
|
|
256
315
|
headers?: Record<string, string>;
|
|
257
316
|
/** 是否启用 WebSocket 代理 */
|
|
@@ -474,4 +533,4 @@ declare function detectProductionEnvironment(customEnvs?: string[], debug?: bool
|
|
|
474
533
|
*/
|
|
475
534
|
declare function shouldEnableWatch(watch: boolean | 'auto', customEnvs?: string[], debug?: boolean, loggerPrefix?: string): boolean;
|
|
476
535
|
|
|
477
|
-
export { type AutoProxyConfigOptions, AutoProxyCookie, type AutoProxyCookieOptions, CookieReader, type CookieReaderOptions, CookieWatcher, type CookieWatcherOptions, type CreateFileCookieGetterOptions, type ErrorCallback, type ProxyConfig, type ProxyHooks, type ViteMiddlewareProxyOptions, type VueProxyConfigOptions, createAutoProxyConfig, createAutoProxyCookie, createCookieGetter, createFileCookieGetter, createVueProxyConfig, detectProductionEnvironment, isProductionValue, shouldEnableWatch, viteMiddlewareProxy, watchCookieFile };
|
|
536
|
+
export { type AuthenticationItem, type AutoProxyConfigOptions, AutoProxyCookie, type AutoProxyCookieOptions, CookieReader, type CookieReaderOptions, CookieWatcher, type CookieWatcherOptions, type CreateFileCookieGetterOptions, type ErrorCallback, type ProxyConfig, type ProxyHooks, type ViteMiddlewareProxyOptions, type VueProxyConfigOptions, applyDevAuthentications, createAutoProxyConfig, createAutoProxyCookie, createCookieGetter, createFileCookieGetter, createVueProxyConfig, detectProductionEnvironment, isProductionValue, shouldEnableWatch, viteMiddlewareProxy, watchCookieFile };
|
package/dist/index.d.ts
CHANGED
|
@@ -2,6 +2,26 @@ import * as net from 'net';
|
|
|
2
2
|
import { IncomingMessage, ServerResponse } from 'http';
|
|
3
3
|
import { ViteDevServer } from 'vite';
|
|
4
4
|
|
|
5
|
+
/**
|
|
6
|
+
* 应用开发环境自定义鉴权信息到代理请求头
|
|
7
|
+
*
|
|
8
|
+
* 将自定义鉴权信息数组展开为请求头键值对,注入到代理请求中。
|
|
9
|
+
* 支持多种鉴权方式,如 ticket、token、Authorization 等。
|
|
10
|
+
*
|
|
11
|
+
* @module apply-dev-authentications
|
|
12
|
+
*/
|
|
13
|
+
type AuthenticationItem = Record<string, string>;
|
|
14
|
+
/**
|
|
15
|
+
* 将自定义鉴权信息数组应用到代理请求头
|
|
16
|
+
*
|
|
17
|
+
* @param proxyReq - 代理请求对象
|
|
18
|
+
* @param authentications - 鉴权信息数组,每个元素是一个键值对对象
|
|
19
|
+
*/
|
|
20
|
+
declare function applyDevAuthentications(proxyReq: {
|
|
21
|
+
setHeader(name: string, value: string): void;
|
|
22
|
+
getHeader?(name: string): string | string[] | undefined;
|
|
23
|
+
}, authentications: AuthenticationItem[]): void;
|
|
24
|
+
|
|
5
25
|
/**
|
|
6
26
|
* 错误回调函数类型
|
|
7
27
|
* @param err - 错误对象
|
|
@@ -64,6 +84,19 @@ interface AutoProxyCookieOptions {
|
|
|
64
84
|
* 使用示例: isDev: process.env.NODE_ENV === 'development'
|
|
65
85
|
*/
|
|
66
86
|
isDev?: boolean;
|
|
87
|
+
/**
|
|
88
|
+
* 是否使用 Cookie 文件中的 Cookie 注入到请求中
|
|
89
|
+
* - true: 使用文件中的 Cookie(默认)
|
|
90
|
+
* - false: 不注入 Cookie,使用浏览器发送的 Cookie
|
|
91
|
+
*
|
|
92
|
+
* 当使用账号密码登录时,设置为 false,避免覆盖浏览器的登录 Cookie
|
|
93
|
+
*/
|
|
94
|
+
useCookie?: boolean;
|
|
95
|
+
/**
|
|
96
|
+
* 自定义鉴权信息数组,每个元素是一个键值对对象,会被注入到请求头中
|
|
97
|
+
* 例如: [{ 'ticket': 'xxxx' }, { 'X-Custom-Token': 'yyyy' }]
|
|
98
|
+
*/
|
|
99
|
+
authentications?: AuthenticationItem[];
|
|
67
100
|
}
|
|
68
101
|
/**
|
|
69
102
|
* 自动代理 Cookie 类
|
|
@@ -177,12 +210,25 @@ declare function createAutoProxyCookie(options: AutoProxyCookieOptions): AutoPro
|
|
|
177
210
|
* Vite 中间件代理 Cookie 插件配置选项
|
|
178
211
|
*/
|
|
179
212
|
interface ViteMiddlewareProxyOptions {
|
|
180
|
-
/** Cookie
|
|
213
|
+
/** Cookie 文件路径, 使用文件方便监听cookie 变化,避免手动启动更新 */
|
|
181
214
|
cookieFile: string;
|
|
182
215
|
/** 默认代理目标地址 */
|
|
183
216
|
target: string;
|
|
184
217
|
/** 是否启用调试日志 */
|
|
185
218
|
debug?: boolean;
|
|
219
|
+
/**
|
|
220
|
+
* 是否使用 Cookie 文件中的 Cookie 注入到请求中
|
|
221
|
+
* - true: 使用文件中的 Cookie(默认)
|
|
222
|
+
* - false: 不注入 Cookie,使用浏览器发送的 Cookie
|
|
223
|
+
*
|
|
224
|
+
* 当使用账号密码登录时,设置为 false,避免覆盖浏览器的登录 Cookie
|
|
225
|
+
*/
|
|
226
|
+
useCookie?: boolean;
|
|
227
|
+
/**
|
|
228
|
+
* 自定义鉴权信息数组,每个元素是一个键值对对象,会被注入到请求头中
|
|
229
|
+
* 例如: [{ 'ticket': 'xxxx' }, { 'X-Custom-Token': 'yyyy' }]
|
|
230
|
+
*/
|
|
231
|
+
authentications?: AuthenticationItem[];
|
|
186
232
|
/**
|
|
187
233
|
* 代理路径映射表
|
|
188
234
|
* 键:路径前缀,值:代理目标地址
|
|
@@ -252,6 +298,19 @@ interface VueProxyConfigOptions {
|
|
|
252
298
|
getCookie?: () => string;
|
|
253
299
|
/** 是否输出调试日志 */
|
|
254
300
|
debug?: boolean;
|
|
301
|
+
/**
|
|
302
|
+
* 是否使用 Cookie 文件中的 Cookie 注入到请求中
|
|
303
|
+
* - true: 使用文件中的 Cookie(默认)
|
|
304
|
+
* - false: 不注入 Cookie,使用浏览器发送的 Cookie
|
|
305
|
+
*
|
|
306
|
+
* 当使用账号密码登录时,设置为 false,避免覆盖浏览器的登录 Cookie
|
|
307
|
+
*/
|
|
308
|
+
useCookie?: boolean;
|
|
309
|
+
/**
|
|
310
|
+
* 自定义鉴权信息数组,每个元素是一个键值对对象,会被注入到请求头中
|
|
311
|
+
* 例如: [{ 'ticket': 'xxxx' }, { 'X-Custom-Token': 'yyyy' }]
|
|
312
|
+
*/
|
|
313
|
+
authentications?: AuthenticationItem[];
|
|
255
314
|
/** 自定义请求头 */
|
|
256
315
|
headers?: Record<string, string>;
|
|
257
316
|
/** 是否启用 WebSocket 代理 */
|
|
@@ -474,4 +533,4 @@ declare function detectProductionEnvironment(customEnvs?: string[], debug?: bool
|
|
|
474
533
|
*/
|
|
475
534
|
declare function shouldEnableWatch(watch: boolean | 'auto', customEnvs?: string[], debug?: boolean, loggerPrefix?: string): boolean;
|
|
476
535
|
|
|
477
|
-
export { type AutoProxyConfigOptions, AutoProxyCookie, type AutoProxyCookieOptions, CookieReader, type CookieReaderOptions, CookieWatcher, type CookieWatcherOptions, type CreateFileCookieGetterOptions, type ErrorCallback, type ProxyConfig, type ProxyHooks, type ViteMiddlewareProxyOptions, type VueProxyConfigOptions, createAutoProxyConfig, createAutoProxyCookie, createCookieGetter, createFileCookieGetter, createVueProxyConfig, detectProductionEnvironment, isProductionValue, shouldEnableWatch, viteMiddlewareProxy, watchCookieFile };
|
|
536
|
+
export { type AuthenticationItem, type AutoProxyConfigOptions, AutoProxyCookie, type AutoProxyCookieOptions, CookieReader, type CookieReaderOptions, CookieWatcher, type CookieWatcherOptions, type CreateFileCookieGetterOptions, type ErrorCallback, type ProxyConfig, type ProxyHooks, type ViteMiddlewareProxyOptions, type VueProxyConfigOptions, applyDevAuthentications, createAutoProxyConfig, createAutoProxyCookie, createCookieGetter, createFileCookieGetter, createVueProxyConfig, detectProductionEnvironment, isProductionValue, shouldEnableWatch, viteMiddlewareProxy, watchCookieFile };
|
package/dist/index.js
CHANGED
|
@@ -33,6 +33,7 @@ __export(index_exports, {
|
|
|
33
33
|
AutoProxyCookie: () => AutoProxyCookie,
|
|
34
34
|
CookieReader: () => CookieReader,
|
|
35
35
|
CookieWatcher: () => CookieWatcher,
|
|
36
|
+
applyDevAuthentications: () => applyDevAuthentications,
|
|
36
37
|
createAutoProxyConfig: () => createAutoProxyConfig,
|
|
37
38
|
createAutoProxyCookie: () => createAutoProxyCookie,
|
|
38
39
|
createCookieGetter: () => createCookieGetter,
|
|
@@ -336,6 +337,24 @@ function applyDevCookieHeader(proxyReq, cookie) {
|
|
|
336
337
|
console.log("[applyDevCookieHeader] === END ===");
|
|
337
338
|
}
|
|
338
339
|
|
|
340
|
+
// src/proxy/apply-dev-authentications.ts
|
|
341
|
+
function applyDevAuthentications(proxyReq, authentications) {
|
|
342
|
+
console.log("[applyDevAuthentications] === START ===");
|
|
343
|
+
if (!authentications || authentications.length === 0) {
|
|
344
|
+
console.log("[applyDevAuthentications] Authentications is empty, returning");
|
|
345
|
+
console.log("[applyDevAuthentications] === END ===");
|
|
346
|
+
return;
|
|
347
|
+
}
|
|
348
|
+
console.log("[applyDevAuthentications] Applying authentications:", JSON.stringify(authentications));
|
|
349
|
+
for (const authItem of authentications) {
|
|
350
|
+
for (const [key, value] of Object.entries(authItem)) {
|
|
351
|
+
proxyReq.setHeader(key, value);
|
|
352
|
+
console.log("[applyDevAuthentications] Set header:", key, "->", value);
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
console.log("[applyDevAuthentications] === END ===");
|
|
356
|
+
}
|
|
357
|
+
|
|
339
358
|
// src/proxy/core.ts
|
|
340
359
|
var AutoProxyCookie = class {
|
|
341
360
|
/**
|
|
@@ -380,14 +399,23 @@ var AutoProxyCookie = class {
|
|
|
380
399
|
this.handleOnProxyReq = (proxyReq, req, res, _options) => {
|
|
381
400
|
console.log("[AutoProxyCookie] === handleOnProxyReq START ===");
|
|
382
401
|
console.log("[AutoProxyCookie] Request URL:", req.method, req.url);
|
|
402
|
+
console.log("[AutoProxyCookie] useCookie:", this.options.useCookie);
|
|
383
403
|
console.log("[AutoProxyCookie] Current cookie:", this.currentCookie ? `(length: ${this.currentCookie.length})` : "(empty)");
|
|
384
|
-
if (this.currentCookie) {
|
|
404
|
+
if (this.options.useCookie && this.currentCookie) {
|
|
385
405
|
console.log("[AutoProxyCookie] Applying cookie header...");
|
|
386
406
|
applyDevCookieHeader(proxyReq, this.currentCookie);
|
|
387
407
|
console.log("[AutoProxyCookie] Cookie header applied successfully");
|
|
408
|
+
} else if (!this.options.useCookie) {
|
|
409
|
+
console.log("[AutoProxyCookie] useCookie is false, skipping cookie injection");
|
|
388
410
|
} else {
|
|
389
411
|
console.log("[AutoProxyCookie] No cookie to apply - currentCookie is empty!");
|
|
390
412
|
}
|
|
413
|
+
const authentications = this.options.authentications || [];
|
|
414
|
+
if (authentications.length > 0) {
|
|
415
|
+
console.log("[AutoProxyCookie] Applying authentications headers...");
|
|
416
|
+
applyDevAuthentications(proxyReq, authentications);
|
|
417
|
+
console.log("[AutoProxyCookie] Authentications headers applied successfully");
|
|
418
|
+
}
|
|
391
419
|
this.log("debug", "[AutoProxyCookie] Proxy Request:", req.method, req.url);
|
|
392
420
|
if (this.options.hooks.onProxyReq) {
|
|
393
421
|
try {
|
|
@@ -506,6 +534,8 @@ var AutoProxyCookie = class {
|
|
|
506
534
|
cookieDomainRewrite: "*",
|
|
507
535
|
cookiePathRewrite: false,
|
|
508
536
|
headers: {},
|
|
537
|
+
useCookie: true,
|
|
538
|
+
authentications: [],
|
|
509
539
|
...mergedOptions
|
|
510
540
|
};
|
|
511
541
|
this.cookieReader = new CookieReader({ cookieFile: options.cookieFile }, options.debug ?? false);
|
|
@@ -643,16 +673,21 @@ var AutoProxyCookie = class {
|
|
|
643
673
|
console.log("[AutoProxyCookie] Method:", req.method);
|
|
644
674
|
console.log("[AutoProxyCookie] Full URL:", fullUrl);
|
|
645
675
|
console.log("[AutoProxyCookie] Pathname:", pathname);
|
|
676
|
+
console.log("[AutoProxyCookie] useCookie:", this.options.useCookie);
|
|
646
677
|
console.log("[AutoProxyCookie] Headers:", JSON.stringify(req.headers, null, 2));
|
|
647
678
|
if (this.isIgnoredPath(pathname)) {
|
|
648
679
|
console.log("[AutoProxyCookie] Path ignored, passing to next middleware");
|
|
649
680
|
next();
|
|
650
681
|
return;
|
|
651
682
|
}
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
683
|
+
if (this.options.useCookie) {
|
|
684
|
+
this.currentCookie = this.cookieReader.readCookie();
|
|
685
|
+
console.log("[AutoProxyCookie] Current cookie:", this.currentCookie ? `(length: ${this.currentCookie.length})` : "(empty)");
|
|
686
|
+
if (this.currentCookie) {
|
|
687
|
+
console.log("[AutoProxyCookie] Cookie preview:", this.currentCookie);
|
|
688
|
+
}
|
|
689
|
+
} else {
|
|
690
|
+
console.log("[AutoProxyCookie] useCookie is false, skipping cookie reading");
|
|
656
691
|
}
|
|
657
692
|
const proxyMapKeys = Object.keys(this.options.proxyMap || {});
|
|
658
693
|
const proxyPaths = this.options.proxyPaths || [];
|
|
@@ -778,12 +813,17 @@ function viteMiddlewareProxy(options) {
|
|
|
778
813
|
cookieFile,
|
|
779
814
|
target,
|
|
780
815
|
debug = false,
|
|
816
|
+
useCookie = true,
|
|
817
|
+
authentications = [],
|
|
781
818
|
proxyMap = {},
|
|
782
819
|
proxyPaths = [],
|
|
783
820
|
ignorePaths = []
|
|
784
821
|
} = options;
|
|
785
822
|
const cookieReader = new CookieReader({ cookieFile }, debug);
|
|
786
|
-
let currentCookie =
|
|
823
|
+
let currentCookie = "";
|
|
824
|
+
if (useCookie) {
|
|
825
|
+
currentCookie = cookieReader.readCookie();
|
|
826
|
+
}
|
|
787
827
|
const allProxyPrefixes = [
|
|
788
828
|
...Object.keys(proxyMap),
|
|
789
829
|
...proxyPaths
|
|
@@ -794,7 +834,7 @@ function viteMiddlewareProxy(options) {
|
|
|
794
834
|
configureServer(server) {
|
|
795
835
|
const httpProxy2 = require("http-proxy");
|
|
796
836
|
const proxyServer = httpProxy2.createProxyServer({});
|
|
797
|
-
if (debug) {
|
|
837
|
+
if (useCookie && debug) {
|
|
798
838
|
console.log("[ViteMiddlewareProxy] Watching cookie file:", cookieFile);
|
|
799
839
|
}
|
|
800
840
|
server.middlewares.use((req, res, next) => {
|
|
@@ -814,14 +854,6 @@ function viteMiddlewareProxy(options) {
|
|
|
814
854
|
if (debug) {
|
|
815
855
|
console.log("[ViteMiddlewareProxy] Proxying:", req.method, pathname, "->", proxyTarget);
|
|
816
856
|
}
|
|
817
|
-
currentCookie = cookieReader.readCookie();
|
|
818
|
-
if (currentCookie) {
|
|
819
|
-
if (debug) {
|
|
820
|
-
console.log("[ViteMiddlewareProxy] Injecting cookie:", `(length: ${currentCookie.length})`);
|
|
821
|
-
}
|
|
822
|
-
req.headers["cookie"] = currentCookie;
|
|
823
|
-
req.headers["Cookie"] = currentCookie;
|
|
824
|
-
}
|
|
825
857
|
proxyServer.web(req, res, {
|
|
826
858
|
target: proxyTarget,
|
|
827
859
|
changeOrigin: true,
|
|
@@ -829,6 +861,27 @@ function viteMiddlewareProxy(options) {
|
|
|
829
861
|
ignorePath: false
|
|
830
862
|
});
|
|
831
863
|
});
|
|
864
|
+
proxyServer.on("proxyReq", (proxyReq, req) => {
|
|
865
|
+
if (useCookie) {
|
|
866
|
+
currentCookie = cookieReader.readCookie();
|
|
867
|
+
if (currentCookie) {
|
|
868
|
+
if (debug) {
|
|
869
|
+
console.log("[ViteMiddlewareProxy] Injecting cookie:", `(length: ${currentCookie.length})`);
|
|
870
|
+
}
|
|
871
|
+
applyDevCookieHeader(proxyReq, currentCookie);
|
|
872
|
+
} else if (debug) {
|
|
873
|
+
console.log("[ViteMiddlewareProxy] Cookie file is empty");
|
|
874
|
+
}
|
|
875
|
+
} else if (debug) {
|
|
876
|
+
console.log("[ViteMiddlewareProxy] useCookie is false, skipping cookie injection");
|
|
877
|
+
}
|
|
878
|
+
if (authentications && authentications.length > 0) {
|
|
879
|
+
applyDevAuthentications(proxyReq, authentications);
|
|
880
|
+
if (debug) {
|
|
881
|
+
console.log("[ViteMiddlewareProxy] Injecting authentications:", JSON.stringify(authentications));
|
|
882
|
+
}
|
|
883
|
+
}
|
|
884
|
+
});
|
|
832
885
|
proxyServer.on("error", (err, req) => {
|
|
833
886
|
console.error("[ViteMiddlewareProxy] Proxy error:", err.message, "for", req.url);
|
|
834
887
|
});
|
|
@@ -842,6 +895,8 @@ function createVueProxyConfig(target, options = {}) {
|
|
|
842
895
|
const {
|
|
843
896
|
getCookie,
|
|
844
897
|
debug = false,
|
|
898
|
+
useCookie = true,
|
|
899
|
+
authentications = [],
|
|
845
900
|
headers = {},
|
|
846
901
|
ws = false,
|
|
847
902
|
changeOrigin = true,
|
|
@@ -855,13 +910,23 @@ function createVueProxyConfig(target, options = {}) {
|
|
|
855
910
|
secure,
|
|
856
911
|
headers,
|
|
857
912
|
onProxyReq: (proxyReq, req) => {
|
|
858
|
-
const
|
|
859
|
-
if (
|
|
860
|
-
|
|
913
|
+
const reqPath = req.url || "/";
|
|
914
|
+
if (useCookie) {
|
|
915
|
+
const cookie = getCookie ? getCookie() : "";
|
|
916
|
+
if (cookie) {
|
|
917
|
+
applyDevCookieHeader(proxyReq, cookie);
|
|
918
|
+
}
|
|
919
|
+
if (debug) {
|
|
920
|
+
console.log("[Proxy Request]", reqPath, req.method, cookie ? "(with cookie)" : "(no cookie)");
|
|
921
|
+
}
|
|
922
|
+
} else if (debug) {
|
|
923
|
+
console.log("[Proxy Request]", reqPath, req.method, "(useCookie is false, skipping cookie injection)");
|
|
861
924
|
}
|
|
862
|
-
if (
|
|
863
|
-
|
|
864
|
-
|
|
925
|
+
if (authentications && authentications.length > 0) {
|
|
926
|
+
applyDevAuthentications(proxyReq, authentications);
|
|
927
|
+
if (debug) {
|
|
928
|
+
console.log("[Proxy Request]", reqPath, req.method, "(with authentications)");
|
|
929
|
+
}
|
|
865
930
|
}
|
|
866
931
|
},
|
|
867
932
|
onError: customOnError || ((err) => {
|
|
@@ -905,11 +970,11 @@ function createFileCookieGetter(cookieFile, options = {}) {
|
|
|
905
970
|
return () => reader.readCookie();
|
|
906
971
|
}
|
|
907
972
|
function createAutoProxyConfig(options) {
|
|
908
|
-
const { target, ignorePaths = [], includePaths = [], additionalProxies = {}, getCookie, debug, headers } = options;
|
|
973
|
+
const { target, ignorePaths = [], includePaths = [], additionalProxies = {}, getCookie, debug, headers, useCookie = true, authentications = [] } = options;
|
|
909
974
|
const result = {};
|
|
910
975
|
if (includePaths.length > 0) {
|
|
911
976
|
for (const proxyPath of includePaths) {
|
|
912
|
-
result[proxyPath] = createVueProxyConfig(target, { getCookie, debug, headers });
|
|
977
|
+
result[proxyPath] = createVueProxyConfig(target, { getCookie, debug, headers, useCookie, authentications });
|
|
913
978
|
}
|
|
914
979
|
} else {
|
|
915
980
|
const defaultProxy = {
|
|
@@ -923,12 +988,22 @@ function createAutoProxyConfig(options) {
|
|
|
923
988
|
if (ignorePaths.some((p) => reqPath.startsWith(p))) {
|
|
924
989
|
return;
|
|
925
990
|
}
|
|
926
|
-
|
|
927
|
-
|
|
928
|
-
|
|
991
|
+
if (useCookie) {
|
|
992
|
+
const cookie = getCookie ? getCookie() : "";
|
|
993
|
+
if (cookie) {
|
|
994
|
+
applyDevCookieHeader(proxyReq, cookie);
|
|
995
|
+
}
|
|
996
|
+
if (debug) {
|
|
997
|
+
console.log("[Proxy Request]", reqPath, req.method, cookie ? "(with cookie)" : "(no cookie)");
|
|
998
|
+
}
|
|
999
|
+
} else if (debug) {
|
|
1000
|
+
console.log("[Proxy Request]", reqPath, req.method, "(useCookie is false, skipping cookie injection)");
|
|
929
1001
|
}
|
|
930
|
-
if (
|
|
931
|
-
|
|
1002
|
+
if (authentications && authentications.length > 0) {
|
|
1003
|
+
applyDevAuthentications(proxyReq, authentications);
|
|
1004
|
+
if (debug) {
|
|
1005
|
+
console.log("[Proxy Request]", reqPath, req.method, "(with authentications)");
|
|
1006
|
+
}
|
|
932
1007
|
}
|
|
933
1008
|
},
|
|
934
1009
|
onError: (err) => {
|
|
@@ -938,7 +1013,7 @@ function createAutoProxyConfig(options) {
|
|
|
938
1013
|
result["/"] = defaultProxy;
|
|
939
1014
|
}
|
|
940
1015
|
for (const [proxyPath, proxyTarget] of Object.entries(additionalProxies)) {
|
|
941
|
-
result[proxyPath] = createVueProxyConfig(proxyTarget, { getCookie, debug, headers });
|
|
1016
|
+
result[proxyPath] = createVueProxyConfig(proxyTarget, { getCookie, debug, headers, useCookie, authentications });
|
|
942
1017
|
}
|
|
943
1018
|
return result;
|
|
944
1019
|
}
|
|
@@ -947,6 +1022,7 @@ function createAutoProxyConfig(options) {
|
|
|
947
1022
|
AutoProxyCookie,
|
|
948
1023
|
CookieReader,
|
|
949
1024
|
CookieWatcher,
|
|
1025
|
+
applyDevAuthentications,
|
|
950
1026
|
createAutoProxyConfig,
|
|
951
1027
|
createAutoProxyCookie,
|
|
952
1028
|
createCookieGetter,
|
package/dist/index.min.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var
|
|
2
|
-
`).map(i=>i.trim()).filter(i=>i&&!i.startsWith("#")).join("; ");return this.debug&&console.log("[CookieReader] Parsed cookie:",n?"(has cookie)":"(empty)"),n}return this.debug&&console.log("[CookieReader] Cookie file not found:",o),""}catch(o){return this.debug&&console.error("[CookieReader] Error reading cookie file:",o.message),""}}ensureCookieFile(){let o=C.resolve(this.options.cookieFile),e=C.dirname(o);y.existsSync(e)||y.mkdirSync(e,{recursive:!0}),y.existsSync(o)||y.writeFileSync(o,"")}};function G(t){let o=new g({cookieFile:t});return()=>o.readCookie()}var F=f(require("path")),I=f(require("chokidar"));var w=class{constructor(o){this.watcher=null;this.lastContent="";this.handleChange=()=>{let o=this.cookieReader.readCookie();o!==this.lastContent&&(this.lastContent=o,this.options.onCookieChange(o),console.log(`[CookieWatcher] Cookie updated from file: ${this.options.cookieFile}`))};this.options={autoCreateFile:!0,...o},this.cookieReader=new g({cookieFile:o.cookieFile})}start(){this.options.autoCreateFile&&this.cookieReader.ensureCookieFile();let o=F.resolve(this.options.cookieFile);this.lastContent=this.cookieReader.readCookie(),console.log(`[CookieWatcher] Started watching: ${o}`);try{this.watcher=I.default.watch(o,{persistent:!0,ignoreInitial:!0,awaitWriteFinish:{stabilityThreshold:100,pollInterval:50}}),this.watcher.on("change",this.handleChange),this.watcher.on("add",this.handleChange),this.watcher.on("error",e=>{this.options.onError?.(e)})}catch(e){this.options.onError?.(e)}}stop(){this.watcher&&(this.watcher.close(),this.watcher=null,console.log(`[CookieWatcher] Stopped watching: ${this.options.cookieFile}`))}getCurrentCookie(){return this.lastContent}};function P(t,o,e){let r=new w({cookieFile:t,onCookieChange:o,onError:e});return r.start(),r}function b(t){return["production","prod","prd","release","staging","uat"].includes(t.toLowerCase().trim())}function W(t=[],o=!1,e="[env-detector]"){let r=process.env;if(t.length>0)for(let i of t){let a=r[i];if(a&&b(a))return o&&console.log(`${e} Detected production via custom env: ${i}=${a}`),!0}let s=["NODE_ENV","BUILD_MODE","VUE_APP_ENV","VITE_NODE_ENV","WEBPACK_MODE","CI_ENV","APP_ENV","ENV","DEPLOY_ENV","RUN_MODE"];for(let i of s){let a=r[i];if(a&&b(a))return o&&console.log(`${e} Detected production via env: ${i}=${a}`),!0}if(r.CI==="true"||r.CI==="1"||r.CI==="yes")return o&&console.log(`${e} Detected production via CI env`),!0;if(r.npm_lifecycle_event){let i=r.npm_lifecycle_event.toLowerCase();if(i.includes("build")||i.includes("prod")||i.includes("prd")||i.includes("release"))return o&&console.log(`${e} Detected production via lifecycle event: ${r.npm_lifecycle_event}`),!0}let n=process.argv.join("").toLowerCase();return n.includes("build")||n.includes("production")||n.includes("--mode=production")||n.includes("--prod")||n.includes("--release")?(o&&console.log(`${e} Detected production via process arguments`),!0):!1}function A(t,o=[],e=!1,r="[env-detector]"){return typeof t=="boolean"?(e&&!t&&console.log(`${r} Watch disabled by user setting`),t):W(o,e,r)?(e&&console.log(`${r} Auto-detected production mode - disabling watch`),!1):(e&&console.log(`${r} Auto-detected development mode - enabling watch`),!0)}function v(t,o){if(console.log("[applyDevCookieHeader] === START ==="),console.log("[applyDevCookieHeader] Cookie to apply:",o?`(length: ${o.length})`:"(empty)"),!o){console.log("[applyDevCookieHeader] Cookie is empty, returning"),console.log("[applyDevCookieHeader] === END ===");return}let e=t.getHeader?.("Cookie");if(console.log("[applyDevCookieHeader] Cookie current:",e?`(length: ${String(e).length})`:"(none)"),e===o){console.log("[applyDevCookieHeader] Cookie is already set, skipping"),console.log("[applyDevCookieHeader] === END ===");return}t.removeHeader("cookie"),t.removeHeader("Cookie"),t.setHeader("Cookie",o);let r=t.getHeader?.("Cookie");console.log("[applyDevCookieHeader] Cookie new:",r?`(length: ${String(r).length})`:"(failed)"),console.log("[applyDevCookieHeader] === END ===")}var R=class{constructor(o){this.currentCookie="";this.server=null;this.proxyServer=null;this.watcher=null;this.handleCookieChange=o=>{if(o!==this.currentCookie&&(this.currentCookie=o,this.log("info","[AutoProxyCookie] Cookie updated:",o?"(has cookie)":"(empty)"),this.options.autoRestart&&this.options.restartMarkerFile)){let e=V.resolve(this.options.restartMarkerFile);$.writeFileSync(e,JSON.stringify({timestamp:Date.now(),cookie:o},null,2)),this.log("info","[AutoProxyCookie] Restart marker written to:",e),this.log("info","[AutoProxyCookie] Please restart the dev server for changes to take effect")}};this.handleOnProxyReq=(o,e,r,s)=>{if(console.log("[AutoProxyCookie] === handleOnProxyReq START ==="),console.log("[AutoProxyCookie] Request URL:",e.method,e.url),console.log("[AutoProxyCookie] Current cookie:",this.currentCookie?`(length: ${this.currentCookie.length})`:"(empty)"),this.currentCookie?(console.log("[AutoProxyCookie] Applying cookie header..."),v(o,this.currentCookie),console.log("[AutoProxyCookie] Cookie header applied successfully")):console.log("[AutoProxyCookie] No cookie to apply - currentCookie is empty!"),this.log("debug","[AutoProxyCookie] Proxy Request:",e.method,e.url),this.options.hooks.onProxyReq)try{this.options.hooks.onProxyReq(o,e,r)}catch(n){this.log("error","[AutoProxyCookie] onProxyReq hook error:",n.message)}console.log("[AutoProxyCookie] === handleOnProxyReq END ===")};this.handleOnProxyRes=(o,e,r)=>{let s=["Content-Type","Content-Length","Authorization","Set-Cookie","X-Requested-With","Access-Control-Allow-Origin","Access-Control-Allow-Credentials"];if(r.setHeader("Access-Control-Allow-Origin","*"),r.setHeader("Access-Control-Allow-Methods","GET, POST, PUT, DELETE, OPTIONS"),r.setHeader("Access-Control-Allow-Headers",s.join(",")),r.setHeader("Access-Control-Allow-Credentials","true"),this.log("debug","[AutoProxyCookie] Proxy Response:",e.url,o.statusCode),this.options.hooks.onProxyRes)try{this.options.hooks.onProxyRes(o,e,r)}catch(n){this.log("error","[AutoProxyCookie] onProxyRes hook error:",n.message)}};this.handleOnError=(o,e,r)=>{if(this.log("error","[AutoProxyCookie] Proxy Error:",o.message),this.log("error","[AutoProxyCookie] URL:",e.url),r instanceof H.ServerResponse&&!r.headersSent&&(r.writeHead(503,{"Content-Type":"application/json; charset=utf-8"}),r.end(JSON.stringify({success:!1,message:"\u670D\u52A1\u6682\u4E0D\u53EF\u7528\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5",error:o.message}))),this.options.hooks.onError)try{this.options.hooks.onError(o,e,r)}catch(s){this.log("error","[AutoProxyCookie] onError hook error:",s.message)}};this.handleOnWsError=(o,e,r)=>{if(this.log("error","[AutoProxyCookie] WebSocket Proxy Error:",o.message),this.log("error","[AutoProxyCookie] WebSocket URL:",e.url),r&&r.close(),this.options.hooks.onWsError)try{this.options.hooks.onWsError(o,e,r)}catch(s){this.log("error","[AutoProxyCookie] onWsError hook error:",s.message)}};let r={...o,hooks:{...{onProxyReq:()=>{},onProxyRes:()=>{},onError:()=>{},onWsError:()=>{}},...o.hooks||{}}};this.options={debug:!1,autoRestart:!1,restartMarkerFile:".cookie-restart-marker",proxyMap:{},proxyPaths:[],ignorePaths:[],ws:!0,changeOrigin:!0,secure:!1,followRedirects:!0,autoRewrite:!1,protocolRewrite:void 0,logLevel:"info",cookieDomainRewrite:"*",cookiePathRewrite:!1,headers:{},...r},this.cookieReader=new g({cookieFile:o.cookieFile},o.debug??!1)}getProxyUrl(o){let e=o.url||"/",r=new URL(e,"http://localhost").pathname,s=this.options.proxyMap||{},n=this.options.proxyPaths||[];this.log("debug","[AutoProxyCookie] getProxyUrl - Request path:",r),this.log("debug","[AutoProxyCookie] getProxyUrl - Available proxyMap paths:",Object.keys(s)),this.log("debug","[AutoProxyCookie] getProxyUrl - Available proxyPaths:",n);for(let[i,a]of Object.entries(s)){let l=r.startsWith(i);if(this.log("debug","[AutoProxyCookie] getProxyUrl - Checking proxyMap:",i,"- matches:",l),l)return this.log("debug","[AutoProxyCookie] getProxyUrl - Matched proxyMap:",i,"->",a),a}for(let i of n){let a=r.startsWith(i);if(this.log("debug","[AutoProxyCookie] getProxyUrl - Checking proxyPaths:",i,"- matches:",a),a)return this.log("debug","[AutoProxyCookie] getProxyUrl - Matched proxyPaths:",i,"->",this.options.target),this.options.target}return this.log("debug","[AutoProxyCookie] getProxyUrl - No match found, using default target:",this.options.target),this.options.target}isIgnoredPath(o){return(this.options.ignorePaths||[]).some(r=>o.startsWith(r))}log(o,...e){let r={debug:0,info:1,warn:2,error:3},s=this.options.debug?"debug":this.options.logLevel||"info",n=r[s];r[o]>=n&&(o==="error"?console.error(...e):o==="warn"?console.warn(...e):console.log(...e))}createProxyOptions(o){let{ws:e,changeOrigin:r,secure:s,followRedirects:n,autoRewrite:i,protocolRewrite:a,cookieDomainRewrite:l,cookiePathRewrite:p,headers:h}=this.options;return{target:o,ws:e,changeOrigin:r,secure:s,followRedirects:n,autoRewrite:i,protocolRewrite:a,cookieDomainRewrite:l,cookiePathRewrite:p,headers:{...h},ignorePath:!1}}async setup(o){this.server=o,this.currentCookie=this.cookieReader.readCookie();try{let e={target:this.options.target,changeOrigin:this.options.changeOrigin,secure:this.options.secure,followRedirects:this.options.followRedirects,autoRewrite:this.options.autoRewrite,protocolRewrite:this.options.protocolRewrite,cookieDomainRewrite:this.options.cookieDomainRewrite,cookiePathRewrite:this.options.cookiePathRewrite,ws:this.options.ws};this.proxyServer=U.default.createProxyServer(e),this.proxyServer.on("proxyReq",this.handleOnProxyReq),this.proxyServer.on("proxyRes",this.handleOnProxyRes),this.proxyServer.on("error",this.handleOnError),this.options.ws&&this.proxyServer.on("wsError",this.handleOnWsError),this.log("info","[AutoProxyCookie] Proxy server created with WebSocket support")}catch(e){this.log("warn","[AutoProxyCookie] http-proxy create failed, using basic mode:",e.message)}o.middlewares.use((e,r,s)=>{let n=e.url||"/",i=new URL(n,"http://localhost").pathname;if(console.log("[AutoProxyCookie] === Incoming Request ==="),console.log("[AutoProxyCookie] Method:",e.method),console.log("[AutoProxyCookie] Full URL:",n),console.log("[AutoProxyCookie] Pathname:",i),console.log("[AutoProxyCookie] Headers:",JSON.stringify(e.headers,null,2)),this.isIgnoredPath(i)){console.log("[AutoProxyCookie] Path ignored, passing to next middleware"),s();return}this.currentCookie=this.cookieReader.readCookie(),console.log("[AutoProxyCookie] Current cookie:",this.currentCookie?`(length: ${this.currentCookie.length})`:"(empty)"),this.currentCookie&&console.log("[AutoProxyCookie] Cookie preview:",this.currentCookie);let a=Object.keys(this.options.proxyMap||{}),l=this.options.proxyPaths||[],h=[...a,...l].some(d=>i.startsWith(d));if(console.log("[AutoProxyCookie] Path matches proxy rules:",h),this.proxyServer){let d=this.getProxyUrl(e);console.log(`[AutoProxyCookie] Proxying ${e.method} ${i} -> ${d}`);let u=this.createProxyOptions(d);try{console.log("[AutoProxyCookie] Calling proxyServer.web..."),this.proxyServer.web(e,r,u),console.log("[AutoProxyCookie] proxyServer.web called successfully")}catch(c){console.error("[AutoProxyCookie] Proxy web error:",c.message),s(c)}}else console.log("[AutoProxyCookie] No proxy server, passing to next middleware"),s()}),this.options.ws&&this.server.httpServer&&this.proxyServer&&(this.server.httpServer.on("upgrade",(e,r,s)=>{let n=new URL(e.url||"/","http://localhost").pathname;if(this.isIgnoredPath(n)){r.destroy();return}let i=this.getProxyUrl(e);this.proxyServer?.ws(e,r,s,{target:i,ws:!0,changeOrigin:this.options.changeOrigin,secure:this.options.secure})}),this.log("info","[AutoProxyCookie] WebSocket upgrade handler registered")),this.startFileWatch(),this.log("info","[AutoProxyCookie] Auto-proxy middleware enabled"),this.log("info","[AutoProxyCookie] Target:",this.options.target),this.log("info","[AutoProxyCookie] Cookie file:",this.options.cookieFile),this.options.autoRestart&&this.log("info","[AutoProxyCookie] Auto-restart enabled"),this.options.ws&&this.log("info","[AutoProxyCookie] WebSocket support enabled")}startFileWatch(){let o;this.options.isDev!==void 0?(o=this.options.isDev,this.options.debug&&console.log(`[AutoProxyCookie] isDev=${this.options.isDev}, ${o?"enabling":"disabling"} watch`)):(o=!0,this.options.debug&&console.log("[AutoProxyCookie] Default behavior: enabling watch (dev mode)")),o?this.watcher=P(this.options.cookieFile,this.handleCookieChange,e=>{this.log("error","[AutoProxyCookie] File watch error:",e.message)}):this.options.debug&&console.log("[AutoProxyCookie] File watch disabled")}stop(){this.watcher&&(this.watcher.stop(),this.watcher=null),this.proxyServer&&(this.proxyServer.close(),this.proxyServer=null),this.log("info","[AutoProxyCookie] Stopped")}getCurrentCookie(){return this.currentCookie}};function J(t){return new R(t)}function K(t,o){return o.some(e=>t.startsWith(e))}function z(t,o){return o.some(e=>t.startsWith(e))}function X(t,o,e){for(let[r,s]of Object.entries(o))if(t.startsWith(r))return s;return e}function Y(t){let{cookieFile:o,target:e,debug:r=!1,proxyMap:s={},proxyPaths:n=[],ignorePaths:i=[]}=t,a=new g({cookieFile:o},r),l=a.readCookie(),p=[...Object.keys(s),...n];return{name:"vite-middleware-proxy",apply:"serve",configureServer(h){let u=require("http-proxy").createProxyServer({});r&&console.log("[ViteMiddlewareProxy] Watching cookie file:",o),h.middlewares.use((c,k,O)=>{let x=new URL(c.url||"/","http://localhost").pathname;if(K(x,i)){r&&console.log("[ViteMiddlewareProxy] Ignoring:",x),O();return}if(!z(x,p)){O();return}let M=X(x,s,e);r&&console.log("[ViteMiddlewareProxy] Proxying:",c.method,x,"->",M),l=a.readCookie(),l&&(r&&console.log("[ViteMiddlewareProxy] Injecting cookie:",`(length: ${l.length})`),c.headers.cookie=l,c.headers.Cookie=l),u.web(c,k,{target:M,changeOrigin:!0,secure:!1,ignorePath:!1})}),u.on("error",(c,k)=>{console.error("[ViteMiddlewareProxy] Proxy error:",c.message,"for",k.url)})}}}var E=f(require("path"));function S(t,o={}){let{getCookie:e,debug:r=!1,headers:s={},ws:n=!1,changeOrigin:i=!0,secure:a=!1,onError:l}=o;return{ws:n,target:t,changeOrigin:i,secure:a,headers:s,onProxyReq:(h,d)=>{let u=e?e():"";if(u&&v(h,u),r){let c=d.url||"/";console.log("[Proxy Request]",c,d.method,u?"(with cookie)":"(no cookie)")}},onError:l||(h=>{console.error(`
|
|
3
|
-
[Proxy Error]`,
|
|
4
|
-
[Proxy Error]`,
|
|
1
|
+
"use strict";var _=Object.create;var A=Object.defineProperty;var j=Object.getOwnPropertyDescriptor;var q=Object.getOwnPropertyNames;var B=Object.getPrototypeOf,G=Object.prototype.hasOwnProperty;var J=(r,o)=>{for(var e in o)A(r,e,{get:o[e],enumerable:!0})},W=(r,o,e,t)=>{if(o&&typeof o=="object"||typeof o=="function")for(let s of q(o))!G.call(r,s)&&s!==e&&A(r,s,{get:()=>o[s],enumerable:!(t=j(o,s))||t.enumerable});return r};var x=(r,o,e)=>(e=r!=null?_(B(r)):{},W(o||!r||!r.__esModule?A(e,"default",{value:r,enumerable:!0}):e,r)),K=r=>W(A({},"__esModule",{value:!0}),r);var ro={};J(ro,{AutoProxyCookie:()=>E,CookieReader:()=>f,CookieWatcher:()=>b,applyDevAuthentications:()=>C,createAutoProxyConfig:()=>to,createAutoProxyCookie:()=>X,createCookieGetter:()=>z,createFileCookieGetter:()=>eo,createVueProxyConfig:()=>M,detectProductionEnvironment:()=>$,isProductionValue:()=>S,shouldEnableWatch:()=>O,viteMiddlewareProxy:()=>oo,watchCookieFile:()=>w});module.exports=K(ro);var N=x(require("http")),U=x(require("fs")),L=x(require("path")),T=x(require("http-proxy"));var k=x(require("fs")),m=x(require("path")),f=class{constructor(o,e=!1){this.options={encoding:"utf-8",...o},this.debug=e}readCookie(){try{let o=m.resolve(this.options.cookieFile);if(this.debug&&(console.log("[CookieReader] Resolved cookie file path:",o),console.log("[CookieReader] File exists:",k.existsSync(o))),k.existsSync(o)){let e=k.readFileSync(o,this.options.encoding||"utf-8");this.debug&&console.log("[CookieReader] File content length:",e.length);let n=e.split(`
|
|
2
|
+
`).map(i=>i.trim()).filter(i=>i&&!i.startsWith("#")).join("; ");return this.debug&&console.log("[CookieReader] Parsed cookie:",n?"(has cookie)":"(empty)"),n}return this.debug&&console.log("[CookieReader] Cookie file not found:",o),""}catch(o){return this.debug&&console.error("[CookieReader] Error reading cookie file:",o.message),""}}ensureCookieFile(){let o=m.resolve(this.options.cookieFile),e=m.dirname(o);k.existsSync(e)||k.mkdirSync(e,{recursive:!0}),k.existsSync(o)||k.writeFileSync(o,"")}};function z(r){let o=new f({cookieFile:r});return()=>o.readCookie()}var H=x(require("path")),V=x(require("chokidar"));var b=class{constructor(o){this.watcher=null;this.lastContent="";this.handleChange=()=>{let o=this.cookieReader.readCookie();o!==this.lastContent&&(this.lastContent=o,this.options.onCookieChange(o),console.log(`[CookieWatcher] Cookie updated from file: ${this.options.cookieFile}`))};this.options={autoCreateFile:!0,...o},this.cookieReader=new f({cookieFile:o.cookieFile})}start(){this.options.autoCreateFile&&this.cookieReader.ensureCookieFile();let o=H.resolve(this.options.cookieFile);this.lastContent=this.cookieReader.readCookie(),console.log(`[CookieWatcher] Started watching: ${o}`);try{this.watcher=V.default.watch(o,{persistent:!0,ignoreInitial:!0,awaitWriteFinish:{stabilityThreshold:100,pollInterval:50}}),this.watcher.on("change",this.handleChange),this.watcher.on("add",this.handleChange),this.watcher.on("error",e=>{this.options.onError?.(e)})}catch(e){this.options.onError?.(e)}}stop(){this.watcher&&(this.watcher.close(),this.watcher=null,console.log(`[CookieWatcher] Stopped watching: ${this.options.cookieFile}`))}getCurrentCookie(){return this.lastContent}};function w(r,o,e){let t=new b({cookieFile:r,onCookieChange:o,onError:e});return t.start(),t}function S(r){return["production","prod","prd","release","staging","uat"].includes(r.toLowerCase().trim())}function $(r=[],o=!1,e="[env-detector]"){let t=process.env;if(r.length>0)for(let i of r){let a=t[i];if(a&&S(a))return o&&console.log(`${e} Detected production via custom env: ${i}=${a}`),!0}let s=["NODE_ENV","BUILD_MODE","VUE_APP_ENV","VITE_NODE_ENV","WEBPACK_MODE","CI_ENV","APP_ENV","ENV","DEPLOY_ENV","RUN_MODE"];for(let i of s){let a=t[i];if(a&&S(a))return o&&console.log(`${e} Detected production via env: ${i}=${a}`),!0}if(t.CI==="true"||t.CI==="1"||t.CI==="yes")return o&&console.log(`${e} Detected production via CI env`),!0;if(t.npm_lifecycle_event){let i=t.npm_lifecycle_event.toLowerCase();if(i.includes("build")||i.includes("prod")||i.includes("prd")||i.includes("release"))return o&&console.log(`${e} Detected production via lifecycle event: ${t.npm_lifecycle_event}`),!0}let n=process.argv.join("").toLowerCase();return n.includes("build")||n.includes("production")||n.includes("--mode=production")||n.includes("--prod")||n.includes("--release")?(o&&console.log(`${e} Detected production via process arguments`),!0):!1}function O(r,o=[],e=!1,t="[env-detector]"){return typeof r=="boolean"?(e&&!r&&console.log(`${t} Watch disabled by user setting`),r):$(o,e,t)?(e&&console.log(`${t} Auto-detected production mode - disabling watch`),!1):(e&&console.log(`${t} Auto-detected development mode - enabling watch`),!0)}function P(r,o){if(console.log("[applyDevCookieHeader] === START ==="),console.log("[applyDevCookieHeader] Cookie to apply:",o?`(length: ${o.length})`:"(empty)"),!o){console.log("[applyDevCookieHeader] Cookie is empty, returning"),console.log("[applyDevCookieHeader] === END ===");return}let e=r.getHeader?.("Cookie");if(console.log("[applyDevCookieHeader] Cookie current:",e?`(length: ${String(e).length})`:"(none)"),e===o){console.log("[applyDevCookieHeader] Cookie is already set, skipping"),console.log("[applyDevCookieHeader] === END ===");return}r.removeHeader("cookie"),r.removeHeader("Cookie"),r.setHeader("Cookie",o);let t=r.getHeader?.("Cookie");console.log("[applyDevCookieHeader] Cookie new:",t?`(length: ${String(t).length})`:"(failed)"),console.log("[applyDevCookieHeader] === END ===")}function C(r,o){if(console.log("[applyDevAuthentications] === START ==="),!o||o.length===0){console.log("[applyDevAuthentications] Authentications is empty, returning"),console.log("[applyDevAuthentications] === END ===");return}console.log("[applyDevAuthentications] Applying authentications:",JSON.stringify(o));for(let e of o)for(let[t,s]of Object.entries(e))r.setHeader(t,s),console.log("[applyDevAuthentications] Set header:",t,"->",s);console.log("[applyDevAuthentications] === END ===")}var E=class{constructor(o){this.currentCookie="";this.server=null;this.proxyServer=null;this.watcher=null;this.handleCookieChange=o=>{if(o!==this.currentCookie&&(this.currentCookie=o,this.log("info","[AutoProxyCookie] Cookie updated:",o?"(has cookie)":"(empty)"),this.options.autoRestart&&this.options.restartMarkerFile)){let e=L.resolve(this.options.restartMarkerFile);U.writeFileSync(e,JSON.stringify({timestamp:Date.now(),cookie:o},null,2)),this.log("info","[AutoProxyCookie] Restart marker written to:",e),this.log("info","[AutoProxyCookie] Please restart the dev server for changes to take effect")}};this.handleOnProxyReq=(o,e,t,s)=>{console.log("[AutoProxyCookie] === handleOnProxyReq START ==="),console.log("[AutoProxyCookie] Request URL:",e.method,e.url),console.log("[AutoProxyCookie] useCookie:",this.options.useCookie),console.log("[AutoProxyCookie] Current cookie:",this.currentCookie?`(length: ${this.currentCookie.length})`:"(empty)"),this.options.useCookie&&this.currentCookie?(console.log("[AutoProxyCookie] Applying cookie header..."),P(o,this.currentCookie),console.log("[AutoProxyCookie] Cookie header applied successfully")):this.options.useCookie?console.log("[AutoProxyCookie] No cookie to apply - currentCookie is empty!"):console.log("[AutoProxyCookie] useCookie is false, skipping cookie injection");let n=this.options.authentications||[];if(n.length>0&&(console.log("[AutoProxyCookie] Applying authentications headers..."),C(o,n),console.log("[AutoProxyCookie] Authentications headers applied successfully")),this.log("debug","[AutoProxyCookie] Proxy Request:",e.method,e.url),this.options.hooks.onProxyReq)try{this.options.hooks.onProxyReq(o,e,t)}catch(i){this.log("error","[AutoProxyCookie] onProxyReq hook error:",i.message)}console.log("[AutoProxyCookie] === handleOnProxyReq END ===")};this.handleOnProxyRes=(o,e,t)=>{let s=["Content-Type","Content-Length","Authorization","Set-Cookie","X-Requested-With","Access-Control-Allow-Origin","Access-Control-Allow-Credentials"];if(t.setHeader("Access-Control-Allow-Origin","*"),t.setHeader("Access-Control-Allow-Methods","GET, POST, PUT, DELETE, OPTIONS"),t.setHeader("Access-Control-Allow-Headers",s.join(",")),t.setHeader("Access-Control-Allow-Credentials","true"),this.log("debug","[AutoProxyCookie] Proxy Response:",e.url,o.statusCode),this.options.hooks.onProxyRes)try{this.options.hooks.onProxyRes(o,e,t)}catch(n){this.log("error","[AutoProxyCookie] onProxyRes hook error:",n.message)}};this.handleOnError=(o,e,t)=>{if(this.log("error","[AutoProxyCookie] Proxy Error:",o.message),this.log("error","[AutoProxyCookie] URL:",e.url),t instanceof N.ServerResponse&&!t.headersSent&&(t.writeHead(503,{"Content-Type":"application/json; charset=utf-8"}),t.end(JSON.stringify({success:!1,message:"\u670D\u52A1\u6682\u4E0D\u53EF\u7528\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5",error:o.message}))),this.options.hooks.onError)try{this.options.hooks.onError(o,e,t)}catch(s){this.log("error","[AutoProxyCookie] onError hook error:",s.message)}};this.handleOnWsError=(o,e,t)=>{if(this.log("error","[AutoProxyCookie] WebSocket Proxy Error:",o.message),this.log("error","[AutoProxyCookie] WebSocket URL:",e.url),t&&t.close(),this.options.hooks.onWsError)try{this.options.hooks.onWsError(o,e,t)}catch(s){this.log("error","[AutoProxyCookie] onWsError hook error:",s.message)}};let t={...o,hooks:{...{onProxyReq:()=>{},onProxyRes:()=>{},onError:()=>{},onWsError:()=>{}},...o.hooks||{}}};this.options={debug:!1,autoRestart:!1,restartMarkerFile:".cookie-restart-marker",proxyMap:{},proxyPaths:[],ignorePaths:[],ws:!0,changeOrigin:!0,secure:!1,followRedirects:!0,autoRewrite:!1,protocolRewrite:void 0,logLevel:"info",cookieDomainRewrite:"*",cookiePathRewrite:!1,headers:{},useCookie:!0,authentications:[],...t},this.cookieReader=new f({cookieFile:o.cookieFile},o.debug??!1)}getProxyUrl(o){let e=o.url||"/",t=new URL(e,"http://localhost").pathname,s=this.options.proxyMap||{},n=this.options.proxyPaths||[];this.log("debug","[AutoProxyCookie] getProxyUrl - Request path:",t),this.log("debug","[AutoProxyCookie] getProxyUrl - Available proxyMap paths:",Object.keys(s)),this.log("debug","[AutoProxyCookie] getProxyUrl - Available proxyPaths:",n);for(let[i,a]of Object.entries(s)){let l=t.startsWith(i);if(this.log("debug","[AutoProxyCookie] getProxyUrl - Checking proxyMap:",i,"- matches:",l),l)return this.log("debug","[AutoProxyCookie] getProxyUrl - Matched proxyMap:",i,"->",a),a}for(let i of n){let a=t.startsWith(i);if(this.log("debug","[AutoProxyCookie] getProxyUrl - Checking proxyPaths:",i,"- matches:",a),a)return this.log("debug","[AutoProxyCookie] getProxyUrl - Matched proxyPaths:",i,"->",this.options.target),this.options.target}return this.log("debug","[AutoProxyCookie] getProxyUrl - No match found, using default target:",this.options.target),this.options.target}isIgnoredPath(o){return(this.options.ignorePaths||[]).some(t=>o.startsWith(t))}log(o,...e){let t={debug:0,info:1,warn:2,error:3},s=this.options.debug?"debug":this.options.logLevel||"info",n=t[s];t[o]>=n&&(o==="error"?console.error(...e):o==="warn"?console.warn(...e):console.log(...e))}createProxyOptions(o){let{ws:e,changeOrigin:t,secure:s,followRedirects:n,autoRewrite:i,protocolRewrite:a,cookieDomainRewrite:l,cookiePathRewrite:p,headers:h}=this.options;return{target:o,ws:e,changeOrigin:t,secure:s,followRedirects:n,autoRewrite:i,protocolRewrite:a,cookieDomainRewrite:l,cookiePathRewrite:p,headers:{...h},ignorePath:!1}}async setup(o){this.server=o,this.currentCookie=this.cookieReader.readCookie();try{let e={target:this.options.target,changeOrigin:this.options.changeOrigin,secure:this.options.secure,followRedirects:this.options.followRedirects,autoRewrite:this.options.autoRewrite,protocolRewrite:this.options.protocolRewrite,cookieDomainRewrite:this.options.cookieDomainRewrite,cookiePathRewrite:this.options.cookiePathRewrite,ws:this.options.ws};this.proxyServer=T.default.createProxyServer(e),this.proxyServer.on("proxyReq",this.handleOnProxyReq),this.proxyServer.on("proxyRes",this.handleOnProxyRes),this.proxyServer.on("error",this.handleOnError),this.options.ws&&this.proxyServer.on("wsError",this.handleOnWsError),this.log("info","[AutoProxyCookie] Proxy server created with WebSocket support")}catch(e){this.log("warn","[AutoProxyCookie] http-proxy create failed, using basic mode:",e.message)}o.middlewares.use((e,t,s)=>{let n=e.url||"/",i=new URL(n,"http://localhost").pathname;if(console.log("[AutoProxyCookie] === Incoming Request ==="),console.log("[AutoProxyCookie] Method:",e.method),console.log("[AutoProxyCookie] Full URL:",n),console.log("[AutoProxyCookie] Pathname:",i),console.log("[AutoProxyCookie] useCookie:",this.options.useCookie),console.log("[AutoProxyCookie] Headers:",JSON.stringify(e.headers,null,2)),this.isIgnoredPath(i)){console.log("[AutoProxyCookie] Path ignored, passing to next middleware"),s();return}this.options.useCookie?(this.currentCookie=this.cookieReader.readCookie(),console.log("[AutoProxyCookie] Current cookie:",this.currentCookie?`(length: ${this.currentCookie.length})`:"(empty)"),this.currentCookie&&console.log("[AutoProxyCookie] Cookie preview:",this.currentCookie)):console.log("[AutoProxyCookie] useCookie is false, skipping cookie reading");let a=Object.keys(this.options.proxyMap||{}),l=this.options.proxyPaths||[],h=[...a,...l].some(u=>i.startsWith(u));if(console.log("[AutoProxyCookie] Path matches proxy rules:",h),this.proxyServer){let u=this.getProxyUrl(e);console.log(`[AutoProxyCookie] Proxying ${e.method} ${i} -> ${u}`);let g=this.createProxyOptions(u);try{console.log("[AutoProxyCookie] Calling proxyServer.web..."),this.proxyServer.web(e,t,g),console.log("[AutoProxyCookie] proxyServer.web called successfully")}catch(d){console.error("[AutoProxyCookie] Proxy web error:",d.message),s(d)}}else console.log("[AutoProxyCookie] No proxy server, passing to next middleware"),s()}),this.options.ws&&this.server.httpServer&&this.proxyServer&&(this.server.httpServer.on("upgrade",(e,t,s)=>{let n=new URL(e.url||"/","http://localhost").pathname;if(this.isIgnoredPath(n)){t.destroy();return}let i=this.getProxyUrl(e);this.proxyServer?.ws(e,t,s,{target:i,ws:!0,changeOrigin:this.options.changeOrigin,secure:this.options.secure})}),this.log("info","[AutoProxyCookie] WebSocket upgrade handler registered")),this.startFileWatch(),this.log("info","[AutoProxyCookie] Auto-proxy middleware enabled"),this.log("info","[AutoProxyCookie] Target:",this.options.target),this.log("info","[AutoProxyCookie] Cookie file:",this.options.cookieFile),this.options.autoRestart&&this.log("info","[AutoProxyCookie] Auto-restart enabled"),this.options.ws&&this.log("info","[AutoProxyCookie] WebSocket support enabled")}startFileWatch(){let o;this.options.isDev!==void 0?(o=this.options.isDev,this.options.debug&&console.log(`[AutoProxyCookie] isDev=${this.options.isDev}, ${o?"enabling":"disabling"} watch`)):(o=!0,this.options.debug&&console.log("[AutoProxyCookie] Default behavior: enabling watch (dev mode)")),o?this.watcher=w(this.options.cookieFile,this.handleCookieChange,e=>{this.log("error","[AutoProxyCookie] File watch error:",e.message)}):this.options.debug&&console.log("[AutoProxyCookie] File watch disabled")}stop(){this.watcher&&(this.watcher.stop(),this.watcher=null),this.proxyServer&&(this.proxyServer.close(),this.proxyServer=null),this.log("info","[AutoProxyCookie] Stopped")}getCurrentCookie(){return this.currentCookie}};function X(r){return new E(r)}function Y(r,o){return o.some(e=>r.startsWith(e))}function Q(r,o){return o.some(e=>r.startsWith(e))}function Z(r,o,e){for(let[t,s]of Object.entries(o))if(r.startsWith(t))return s;return e}function oo(r){let{cookieFile:o,target:e,debug:t=!1,useCookie:s=!0,authentications:n=[],proxyMap:i={},proxyPaths:a=[],ignorePaths:l=[]}=r,p=new f({cookieFile:o},t),h="";s&&(h=p.readCookie());let u=[...Object.keys(i),...a];return{name:"vite-middleware-proxy",apply:"serve",configureServer(g){let y=require("http-proxy").createProxyServer({});s&&t&&console.log("[ViteMiddlewareProxy] Watching cookie file:",o),g.middlewares.use((c,R,I)=>{let v=new URL(c.url||"/","http://localhost").pathname;if(Y(v,l)){t&&console.log("[ViteMiddlewareProxy] Ignoring:",v),I();return}if(!Q(v,u)){I();return}let F=Z(v,i,e);t&&console.log("[ViteMiddlewareProxy] Proxying:",c.method,v,"->",F),y.web(c,R,{target:F,changeOrigin:!0,secure:!1,ignorePath:!1})}),y.on("proxyReq",(c,R)=>{s?(h=p.readCookie(),h?(t&&console.log("[ViteMiddlewareProxy] Injecting cookie:",`(length: ${h.length})`),P(c,h)):t&&console.log("[ViteMiddlewareProxy] Cookie file is empty")):t&&console.log("[ViteMiddlewareProxy] useCookie is false, skipping cookie injection"),n&&n.length>0&&(C(c,n),t&&console.log("[ViteMiddlewareProxy] Injecting authentications:",JSON.stringify(n)))}),y.on("error",(c,R)=>{console.error("[ViteMiddlewareProxy] Proxy error:",c.message,"for",R.url)})}}}var D=x(require("path"));function M(r,o={}){let{getCookie:e,debug:t=!1,useCookie:s=!0,authentications:n=[],headers:i={},ws:a=!1,changeOrigin:l=!0,secure:p=!1,onError:h}=o;return{ws:a,target:r,changeOrigin:l,secure:p,headers:i,onProxyReq:(g,d)=>{let y=d.url||"/";if(s){let c=e?e():"";c&&P(g,c),t&&console.log("[Proxy Request]",y,d.method,c?"(with cookie)":"(no cookie)")}else t&&console.log("[Proxy Request]",y,d.method,"(useCookie is false, skipping cookie injection)");n&&n.length>0&&(C(g,n),t&&console.log("[Proxy Request]",y,d.method,"(with authentications)"))},onError:h||(g=>{console.error(`
|
|
3
|
+
[Proxy Error]`,g.message)})}}function eo(r,o={}){let{watch:e="auto",debug:t=!0,productionEnvs:s=[],isDev:n}=o,i=new f({cookieFile:D.resolve(r)},t),a;return n!==void 0?(a=n,t&&console.log(`[CookieFile] isDev=${n}, ${a?"enabling":"disabling"} watch`)):a=O(e,s,t,"[CookieFile]"),a?w(D.resolve(r),l=>{t&&console.log("[CookieFile] Updated:",l?"(has cookie)":"(empty)")},l=>{console.error("[CookieFile] Watch error:",l.message)}):t&&console.log("[CookieFile] File watch disabled"),()=>i.readCookie()}function to(r){let{target:o,ignorePaths:e=[],includePaths:t=[],additionalProxies:s={},getCookie:n,debug:i,headers:a,useCookie:l=!0,authentications:p=[]}=r,h={};if(t.length>0)for(let u of t)h[u]=M(o,{getCookie:n,debug:i,headers:a,useCookie:l,authentications:p});else{let u={ws:!1,target:o,changeOrigin:!0,secure:!1,headers:a,onProxyReq:(g,d)=>{let y=d.url||"/";if(!e.some(c=>y.startsWith(c))){if(l){let c=n?n():"";c&&P(g,c),i&&console.log("[Proxy Request]",y,d.method,c?"(with cookie)":"(no cookie)")}else i&&console.log("[Proxy Request]",y,d.method,"(useCookie is false, skipping cookie injection)");p&&p.length>0&&(C(g,p),i&&console.log("[Proxy Request]",y,d.method,"(with authentications)"))}},onError:g=>{console.error(`
|
|
4
|
+
[Proxy Error]`,g.message)}};h["/"]=u}for(let[u,g]of Object.entries(s))h[u]=M(g,{getCookie:n,debug:i,headers:a,useCookie:l,authentications:p});return h}0&&(module.exports={AutoProxyCookie,CookieReader,CookieWatcher,applyDevAuthentications,createAutoProxyConfig,createAutoProxyCookie,createCookieGetter,createFileCookieGetter,createVueProxyConfig,detectProductionEnvironment,isProductionValue,shouldEnableWatch,viteMiddlewareProxy,watchCookieFile});
|