@gylautorun/dev-proxy-cookie 1.0.0 → 1.0.2

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/index.js CHANGED
@@ -36,13 +36,12 @@ __export(index_exports, {
36
36
  createAutoProxyConfig: () => createAutoProxyConfig,
37
37
  createAutoProxyCookie: () => createAutoProxyCookie,
38
38
  createCookieGetter: () => createCookieGetter,
39
- createDevProxyCookie: () => createDevProxyCookie,
40
39
  createFileCookieGetter: () => createFileCookieGetter,
41
40
  createVueProxyConfig: () => createVueProxyConfig,
42
- getViteMajorVersion: () => getViteMajorVersion,
43
- getViteVersion: () => getViteVersion,
44
- viteAutoProxyCookie: () => viteAutoProxyCookie,
45
- viteDevProxyCookie: () => viteDevProxyCookie,
41
+ detectProductionEnvironment: () => detectProductionEnvironment,
42
+ isProductionValue: () => isProductionValue,
43
+ shouldEnableWatch: () => shouldEnableWatch,
44
+ viteMiddlewareProxy: () => viteMiddlewareProxy,
46
45
  watchCookieFile: () => watchCookieFile
47
46
  });
48
47
  module.exports = __toCommonJS(index_exports);
@@ -57,26 +56,62 @@ var import_http_proxy = __toESM(require("http-proxy"));
57
56
  var fs = __toESM(require("fs"));
58
57
  var path = __toESM(require("path"));
59
58
  var CookieReader = class {
60
- constructor(options) {
59
+ /**
60
+ * 构造函数
61
+ * @param options - 配置选项
62
+ * @param debug - 是否启用调试模式
63
+ */
64
+ constructor(options, debug = false) {
61
65
  this.options = {
62
66
  encoding: "utf-8",
63
67
  ...options
64
68
  };
69
+ this.debug = debug;
65
70
  }
71
+ /**
72
+ * 读取 Cookie 文件内容
73
+ *
74
+ * 支持过滤注释行(以 # 开头)和空行,将有效行用分号连接。
75
+ *
76
+ * @returns Cookie 字符串
77
+ */
66
78
  readCookie() {
67
79
  try {
68
80
  const filePath = path.resolve(this.options.cookieFile);
81
+ if (this.debug) {
82
+ console.log("[CookieReader] Resolved cookie file path:", filePath);
83
+ console.log("[CookieReader] File exists:", fs.existsSync(filePath));
84
+ }
69
85
  if (fs.existsSync(filePath)) {
70
86
  const content = fs.readFileSync(filePath, this.options.encoding || "utf-8");
87
+ if (this.debug) {
88
+ console.log("[CookieReader] File content length:", content.length);
89
+ }
71
90
  const lines = content.split("\n");
72
91
  const cookieLines = lines.map((line) => line.trim()).filter((line) => line && !line.startsWith("#"));
73
- return cookieLines.join("; ");
92
+ const result = cookieLines.join("; ");
93
+ if (this.debug) {
94
+ console.log("[CookieReader] Parsed cookie:", result ? "(has cookie)" : "(empty)");
95
+ }
96
+ return result;
97
+ }
98
+ if (this.debug) {
99
+ console.log("[CookieReader] Cookie file not found:", filePath);
74
100
  }
75
101
  return "";
76
- } catch {
102
+ } catch (err) {
103
+ if (this.debug) {
104
+ console.error("[CookieReader] Error reading cookie file:", err.message);
105
+ }
77
106
  return "";
78
107
  }
79
108
  }
109
+ /**
110
+ * 确保 Cookie 文件存在
111
+ *
112
+ * 如果文件不存在,会自动创建空文件。
113
+ * 如果父目录不存在,会自动创建目录。
114
+ */
80
115
  ensureCookieFile() {
81
116
  const filePath = path.resolve(this.options.cookieFile);
82
117
  const dir = path.dirname(filePath);
@@ -97,9 +132,20 @@ function createCookieGetter(cookieFile) {
97
132
  var path2 = __toESM(require("path"));
98
133
  var import_chokidar = __toESM(require("chokidar"));
99
134
  var CookieWatcher = class {
135
+ /**
136
+ * 构造函数
137
+ * @param options - 配置选项
138
+ */
100
139
  constructor(options) {
140
+ /** 文件监听器实例 */
101
141
  this.watcher = null;
142
+ /** 上次读取的 Cookie 内容 */
102
143
  this.lastContent = "";
144
+ /**
145
+ * 文件变化处理函数
146
+ *
147
+ * 读取新的 Cookie 内容,如果与上次不同则触发回调。
148
+ */
103
149
  this.handleChange = () => {
104
150
  const newContent = this.cookieReader.readCookie();
105
151
  if (newContent !== this.lastContent) {
@@ -114,6 +160,9 @@ var CookieWatcher = class {
114
160
  };
115
161
  this.cookieReader = new CookieReader({ cookieFile: options.cookieFile });
116
162
  }
163
+ /**
164
+ * 启动文件监听
165
+ */
117
166
  start() {
118
167
  if (this.options.autoCreateFile) {
119
168
  this.cookieReader.ensureCookieFile();
@@ -139,6 +188,9 @@ var CookieWatcher = class {
139
188
  this.options.onError?.(error);
140
189
  }
141
190
  }
191
+ /**
192
+ * 停止文件监听
193
+ */
142
194
  stop() {
143
195
  if (this.watcher) {
144
196
  this.watcher.close();
@@ -146,6 +198,10 @@ var CookieWatcher = class {
146
198
  console.log(`[CookieWatcher] Stopped watching: ${this.options.cookieFile}`);
147
199
  }
148
200
  }
201
+ /**
202
+ * 获取当前 Cookie 值
203
+ * @returns 当前 Cookie 字符串
204
+ */
149
205
  getCurrentCookie() {
150
206
  return this.lastContent;
151
207
  }
@@ -160,21 +216,145 @@ function watchCookieFile(cookieFile, onCookieChange, onError) {
160
216
  return watcher;
161
217
  }
162
218
 
219
+ // src/utils/env-detector.ts
220
+ function isProductionValue(value) {
221
+ const productionValues = [
222
+ "production",
223
+ // 生产环境
224
+ "prod",
225
+ // 生产环境
226
+ "prd",
227
+ // 生产环境
228
+ "release",
229
+ // 发布环境
230
+ "staging",
231
+ // 预发布环境
232
+ "uat"
233
+ // 预发布环境
234
+ ];
235
+ return productionValues.includes(value.toLowerCase().trim());
236
+ }
237
+ function detectProductionEnvironment(customEnvs = [], debug = false, loggerPrefix = "[env-detector]") {
238
+ const env = process.env;
239
+ if (customEnvs.length > 0) {
240
+ for (const envName of customEnvs) {
241
+ const envValue = env[envName];
242
+ if (envValue && isProductionValue(envValue)) {
243
+ if (debug) {
244
+ console.log(`${loggerPrefix} Detected production via custom env: ${envName}=${envValue}`);
245
+ }
246
+ return true;
247
+ }
248
+ }
249
+ }
250
+ const commonEnvNames = [
251
+ "NODE_ENV",
252
+ "BUILD_MODE",
253
+ "VUE_APP_ENV",
254
+ "VITE_NODE_ENV",
255
+ "WEBPACK_MODE",
256
+ "CI_ENV",
257
+ "APP_ENV",
258
+ "ENV",
259
+ "DEPLOY_ENV",
260
+ "RUN_MODE"
261
+ ];
262
+ for (const envName of commonEnvNames) {
263
+ const envValue = env[envName];
264
+ if (envValue && isProductionValue(envValue)) {
265
+ if (debug) {
266
+ console.log(`${loggerPrefix} Detected production via env: ${envName}=${envValue}`);
267
+ }
268
+ return true;
269
+ }
270
+ }
271
+ if (env.CI === "true" || env.CI === "1" || env.CI === "yes") {
272
+ if (debug) {
273
+ console.log(`${loggerPrefix} Detected production via CI env`);
274
+ }
275
+ return true;
276
+ }
277
+ if (env.npm_lifecycle_event) {
278
+ const lifecycleEvent = env.npm_lifecycle_event.toLowerCase();
279
+ if (lifecycleEvent.includes("build") || lifecycleEvent.includes("prod") || lifecycleEvent.includes("prd") || lifecycleEvent.includes("release")) {
280
+ if (debug) {
281
+ console.log(`${loggerPrefix} Detected production via lifecycle event: ${env.npm_lifecycle_event}`);
282
+ }
283
+ return true;
284
+ }
285
+ }
286
+ const processArgs = process.argv.join("").toLowerCase();
287
+ if (processArgs.includes("build") || processArgs.includes("production") || processArgs.includes("--mode=production") || processArgs.includes("--prod") || processArgs.includes("--release")) {
288
+ if (debug) {
289
+ console.log(`${loggerPrefix} Detected production via process arguments`);
290
+ }
291
+ return true;
292
+ }
293
+ return false;
294
+ }
295
+ function shouldEnableWatch(watch, customEnvs = [], debug = false, loggerPrefix = "[env-detector]") {
296
+ if (typeof watch === "boolean") {
297
+ if (debug && !watch) {
298
+ console.log(`${loggerPrefix} Watch disabled by user setting`);
299
+ }
300
+ return watch;
301
+ }
302
+ const isProduction = detectProductionEnvironment(customEnvs, debug, loggerPrefix);
303
+ if (isProduction) {
304
+ if (debug) {
305
+ console.log(`${loggerPrefix} Auto-detected production mode - disabling watch`);
306
+ }
307
+ return false;
308
+ }
309
+ if (debug) {
310
+ console.log(`${loggerPrefix} Auto-detected development mode - enabling watch`);
311
+ }
312
+ return true;
313
+ }
314
+
163
315
  // src/proxy/apply-dev-cookie-header.ts
164
316
  function applyDevCookieHeader(proxyReq, cookie) {
165
- if (!cookie) return;
317
+ console.log("[applyDevCookieHeader] === START ===");
318
+ console.log("[applyDevCookieHeader] Cookie to apply:", cookie ? `(length: ${cookie.length})` : "(empty)");
319
+ if (!cookie) {
320
+ console.log("[applyDevCookieHeader] Cookie is empty, returning");
321
+ console.log("[applyDevCookieHeader] === END ===");
322
+ return;
323
+ }
324
+ const existingCookie = proxyReq.getHeader?.("Cookie");
325
+ console.log("[applyDevCookieHeader] Cookie current:", existingCookie ? `(length: ${String(existingCookie).length})` : "(none)");
326
+ if (existingCookie === cookie) {
327
+ console.log("[applyDevCookieHeader] Cookie is already set, skipping");
328
+ console.log("[applyDevCookieHeader] === END ===");
329
+ return;
330
+ }
166
331
  proxyReq.removeHeader("cookie");
167
332
  proxyReq.removeHeader("Cookie");
168
333
  proxyReq.setHeader("Cookie", cookie);
334
+ const newCookie = proxyReq.getHeader?.("Cookie");
335
+ console.log("[applyDevCookieHeader] Cookie new:", newCookie ? `(length: ${String(newCookie).length})` : "(failed)");
336
+ console.log("[applyDevCookieHeader] === END ===");
169
337
  }
170
338
 
171
339
  // src/proxy/core.ts
172
340
  var AutoProxyCookie = class {
341
+ /**
342
+ * 构造函数
343
+ * @param options - 配置选项
344
+ */
173
345
  constructor(options) {
346
+ /** 当前 Cookie 值 */
174
347
  this.currentCookie = "";
348
+ /** Vite 开发服务器实例 */
175
349
  this.server = null;
350
+ /** HTTP 代理服务器实例 */
176
351
  this.proxyServer = null;
352
+ /** Cookie 文件监听器 */
177
353
  this.watcher = null;
354
+ /**
355
+ * Cookie 变化处理函数
356
+ * @param newCookie - 新的 Cookie 值
357
+ */
178
358
  this.handleCookieChange = (newCookie) => {
179
359
  if (newCookie !== this.currentCookie) {
180
360
  this.currentCookie = newCookie;
@@ -190,9 +370,23 @@ var AutoProxyCookie = class {
190
370
  }
191
371
  }
192
372
  };
373
+ /**
374
+ * 代理请求处理函数
375
+ * @param proxyReq - 代理请求对象
376
+ * @param req - 原始请求对象
377
+ * @param res - 响应对象
378
+ * @param _options - 服务器选项
379
+ */
193
380
  this.handleOnProxyReq = (proxyReq, req, res, _options) => {
381
+ console.log("[AutoProxyCookie] === handleOnProxyReq START ===");
382
+ console.log("[AutoProxyCookie] Request URL:", req.method, req.url);
383
+ console.log("[AutoProxyCookie] Current cookie:", this.currentCookie ? `(length: ${this.currentCookie.length})` : "(empty)");
194
384
  if (this.currentCookie) {
385
+ console.log("[AutoProxyCookie] Applying cookie header...");
195
386
  applyDevCookieHeader(proxyReq, this.currentCookie);
387
+ console.log("[AutoProxyCookie] Cookie header applied successfully");
388
+ } else {
389
+ console.log("[AutoProxyCookie] No cookie to apply - currentCookie is empty!");
196
390
  }
197
391
  this.log("debug", "[AutoProxyCookie] Proxy Request:", req.method, req.url);
198
392
  if (this.options.hooks.onProxyReq) {
@@ -202,7 +396,14 @@ var AutoProxyCookie = class {
202
396
  this.log("error", "[AutoProxyCookie] onProxyReq hook error:", err.message);
203
397
  }
204
398
  }
399
+ console.log("[AutoProxyCookie] === handleOnProxyReq END ===");
205
400
  };
401
+ /**
402
+ * 代理响应处理函数
403
+ * @param proxyRes - 代理响应对象
404
+ * @param req - 原始请求对象
405
+ * @param res - 响应对象
406
+ */
206
407
  this.handleOnProxyRes = (proxyRes, req, res) => {
207
408
  const allowedHeaders = [
208
409
  "Content-Type",
@@ -226,6 +427,12 @@ var AutoProxyCookie = class {
226
427
  }
227
428
  }
228
429
  };
430
+ /**
431
+ * HTTP 代理错误处理函数
432
+ * @param err - 错误对象
433
+ * @param req - 请求对象
434
+ * @param res - 响应对象或 Socket
435
+ */
229
436
  this.handleOnError = (err, req, res) => {
230
437
  this.log("error", "[AutoProxyCookie] Proxy Error:", err.message);
231
438
  this.log("error", "[AutoProxyCookie] URL:", req.url);
@@ -245,6 +452,12 @@ var AutoProxyCookie = class {
245
452
  }
246
453
  }
247
454
  };
455
+ /**
456
+ * WebSocket 代理错误处理函数
457
+ * @param err - 错误对象
458
+ * @param req - 请求对象
459
+ * @param socket - WebSocket 连接的 Socket
460
+ */
248
461
  this.handleOnWsError = (err, req, socket) => {
249
462
  this.log("error", "[AutoProxyCookie] WebSocket Proxy Error:", err.message);
250
463
  this.log("error", "[AutoProxyCookie] WebSocket URL:", req.url);
@@ -281,6 +494,7 @@ var AutoProxyCookie = class {
281
494
  autoRestart: false,
282
495
  restartMarkerFile: ".cookie-restart-marker",
283
496
  proxyMap: {},
497
+ proxyPaths: [],
284
498
  ignorePaths: [],
285
499
  ws: true,
286
500
  changeOrigin: true,
@@ -294,27 +508,60 @@ var AutoProxyCookie = class {
294
508
  headers: {},
295
509
  ...mergedOptions
296
510
  };
297
- this.cookieReader = new CookieReader({ cookieFile: options.cookieFile });
511
+ this.cookieReader = new CookieReader({ cookieFile: options.cookieFile }, options.debug ?? false);
298
512
  }
513
+ /**
514
+ * 根据请求路径获取代理目标 URL
515
+ * @param req - HTTP 请求对象
516
+ * @returns 代理目标 URL
517
+ */
299
518
  getProxyUrl(req) {
300
- const pathname = req.url?.split("?")[0] || "/";
519
+ const fullUrl = req.url || "/";
520
+ const pathname = new URL(fullUrl, "http://localhost").pathname;
301
521
  const proxyMap = this.options.proxyMap || {};
522
+ const proxyPaths = this.options.proxyPaths || [];
523
+ this.log("debug", "[AutoProxyCookie] getProxyUrl - Request path:", pathname);
524
+ this.log("debug", "[AutoProxyCookie] getProxyUrl - Available proxyMap paths:", Object.keys(proxyMap));
525
+ this.log("debug", "[AutoProxyCookie] getProxyUrl - Available proxyPaths:", proxyPaths);
302
526
  for (const [prefix, target] of Object.entries(proxyMap)) {
303
- if (pathname.startsWith(prefix)) {
527
+ const matches = pathname.startsWith(prefix);
528
+ this.log("debug", "[AutoProxyCookie] getProxyUrl - Checking proxyMap:", prefix, "- matches:", matches);
529
+ if (matches) {
530
+ this.log("debug", "[AutoProxyCookie] getProxyUrl - Matched proxyMap:", prefix, "->", target);
304
531
  return target;
305
532
  }
306
533
  }
534
+ for (const prefix of proxyPaths) {
535
+ const matches = pathname.startsWith(prefix);
536
+ this.log("debug", "[AutoProxyCookie] getProxyUrl - Checking proxyPaths:", prefix, "- matches:", matches);
537
+ if (matches) {
538
+ this.log("debug", "[AutoProxyCookie] getProxyUrl - Matched proxyPaths:", prefix, "->", this.options.target);
539
+ return this.options.target;
540
+ }
541
+ }
542
+ this.log("debug", "[AutoProxyCookie] getProxyUrl - No match found, using default target:", this.options.target);
307
543
  return this.options.target;
308
544
  }
545
+ /**
546
+ * 判断路径是否应该被忽略(不代理)
547
+ * @param pathname - 请求路径
548
+ * @returns 是否忽略
549
+ */
309
550
  isIgnoredPath(pathname) {
310
551
  const ignorePaths = this.options.ignorePaths || [];
311
552
  return ignorePaths.some(
312
553
  (ignored) => pathname.startsWith(ignored)
313
554
  );
314
555
  }
556
+ /**
557
+ * 日志输出函数
558
+ * @param level - 日志级别
559
+ * @param args - 日志参数
560
+ */
315
561
  log(level, ...args) {
316
562
  const levels = { debug: 0, info: 1, warn: 2, error: 3 };
317
- const currentLevel = levels[this.options.logLevel || "info"];
563
+ const effectiveLogLevel = this.options.debug ? "debug" : this.options.logLevel || "info";
564
+ const currentLevel = levels[effectiveLogLevel];
318
565
  const msgLevel = levels[level];
319
566
  if (msgLevel >= currentLevel) {
320
567
  if (level === "error") {
@@ -326,6 +573,11 @@ var AutoProxyCookie = class {
326
573
  }
327
574
  }
328
575
  }
576
+ /**
577
+ * 创建代理服务器配置选项
578
+ * @param target - 代理目标地址
579
+ * @returns 代理服务器配置
580
+ */
329
581
  createProxyOptions(target) {
330
582
  const {
331
583
  ws,
@@ -354,6 +606,10 @@ var AutoProxyCookie = class {
354
606
  ignorePath: false
355
607
  };
356
608
  }
609
+ /**
610
+ * 初始化代理中间件
611
+ * @param server - Vite 开发服务器实例
612
+ */
357
613
  async setup(server) {
358
614
  this.server = server;
359
615
  this.currentCookie = this.cookieReader.readCookie();
@@ -381,25 +637,42 @@ var AutoProxyCookie = class {
381
637
  this.log("warn", "[AutoProxyCookie] http-proxy create failed, using basic mode:", err.message);
382
638
  }
383
639
  server.middlewares.use((req, res, next) => {
384
- const pathname = new URL(req.url || "/", "http://localhost").pathname;
640
+ const fullUrl = req.url || "/";
641
+ const pathname = new URL(fullUrl, "http://localhost").pathname;
642
+ console.log("[AutoProxyCookie] === Incoming Request ===");
643
+ console.log("[AutoProxyCookie] Method:", req.method);
644
+ console.log("[AutoProxyCookie] Full URL:", fullUrl);
645
+ console.log("[AutoProxyCookie] Pathname:", pathname);
646
+ console.log("[AutoProxyCookie] Headers:", JSON.stringify(req.headers, null, 2));
385
647
  if (this.isIgnoredPath(pathname)) {
648
+ console.log("[AutoProxyCookie] Path ignored, passing to next middleware");
386
649
  next();
387
650
  return;
388
651
  }
389
652
  this.currentCookie = this.cookieReader.readCookie();
653
+ console.log("[AutoProxyCookie] Current cookie:", this.currentCookie ? `(length: ${this.currentCookie.length})` : "(empty)");
654
+ if (this.currentCookie) {
655
+ console.log("[AutoProxyCookie] Cookie preview:", this.currentCookie);
656
+ }
657
+ const proxyMapKeys = Object.keys(this.options.proxyMap || {});
658
+ const proxyPaths = this.options.proxyPaths || [];
659
+ const allProxyPrefixes = [...proxyMapKeys, ...proxyPaths];
660
+ const matched = allProxyPrefixes.some((prefix) => pathname.startsWith(prefix));
661
+ console.log("[AutoProxyCookie] Path matches proxy rules:", matched);
390
662
  if (this.proxyServer) {
391
663
  const target = this.getProxyUrl(req);
392
- if (this.options.debug || this.options.logLevel === "debug") {
393
- this.log("info", `[AutoProxyCookie] ${pathname} -> ${target}`);
394
- }
664
+ console.log(`[AutoProxyCookie] Proxying ${req.method} ${pathname} -> ${target}`);
395
665
  const proxyOptions = this.createProxyOptions(target);
396
666
  try {
667
+ console.log("[AutoProxyCookie] Calling proxyServer.web...");
397
668
  this.proxyServer.web(req, res, proxyOptions);
669
+ console.log("[AutoProxyCookie] proxyServer.web called successfully");
398
670
  } catch (err) {
399
- this.log("error", "[AutoProxyCookie] Proxy web error:", err.message);
671
+ console.error("[AutoProxyCookie] Proxy web error:", err.message);
400
672
  next(err);
401
673
  }
402
674
  } else {
675
+ console.log("[AutoProxyCookie] No proxy server, passing to next middleware");
403
676
  next();
404
677
  }
405
678
  });
@@ -431,15 +704,37 @@ var AutoProxyCookie = class {
431
704
  this.log("info", "[AutoProxyCookie] WebSocket support enabled");
432
705
  }
433
706
  }
707
+ /**
708
+ * 启动 Cookie 文件监听
709
+ */
434
710
  startFileWatch() {
435
- this.watcher = watchCookieFile(
436
- this.options.cookieFile,
437
- this.handleCookieChange,
438
- (error) => {
439
- this.log("error", "[AutoProxyCookie] File watch error:", error.message);
711
+ let shouldWatch;
712
+ if (this.options.isDev !== void 0) {
713
+ shouldWatch = this.options.isDev;
714
+ if (this.options.debug) {
715
+ console.log(`[AutoProxyCookie] isDev=${this.options.isDev}, ${shouldWatch ? "enabling" : "disabling"} watch`);
440
716
  }
441
- );
717
+ } else {
718
+ shouldWatch = true;
719
+ if (this.options.debug) {
720
+ console.log("[AutoProxyCookie] Default behavior: enabling watch (dev mode)");
721
+ }
722
+ }
723
+ if (shouldWatch) {
724
+ this.watcher = watchCookieFile(
725
+ this.options.cookieFile,
726
+ this.handleCookieChange,
727
+ (error) => {
728
+ this.log("error", "[AutoProxyCookie] File watch error:", error.message);
729
+ }
730
+ );
731
+ } else if (this.options.debug) {
732
+ console.log("[AutoProxyCookie] File watch disabled");
733
+ }
442
734
  }
735
+ /**
736
+ * 停止代理服务
737
+ */
443
738
  stop() {
444
739
  if (this.watcher) {
445
740
  this.watcher.stop();
@@ -451,6 +746,10 @@ var AutoProxyCookie = class {
451
746
  }
452
747
  this.log("info", "[AutoProxyCookie] Stopped");
453
748
  }
749
+ /**
750
+ * 获取当前 Cookie 值
751
+ * @returns 当前 Cookie 字符串
752
+ */
454
753
  getCurrentCookie() {
455
754
  return this.currentCookie;
456
755
  }
@@ -459,77 +758,80 @@ function createAutoProxyCookie(options) {
459
758
  return new AutoProxyCookie(options);
460
759
  }
461
760
 
462
- // src/proxy/vite-plugin.ts
463
- function viteAutoProxyCookie(options) {
464
- const {
465
- name = "vite-auto-proxy-cookie",
466
- ...autoProxyOptions
467
- } = options;
468
- let autoProxy = null;
469
- return {
470
- name,
471
- apply: "serve",
472
- async configureServer(server) {
473
- autoProxy = createAutoProxyCookie({
474
- ...autoProxyOptions,
475
- debug: options.debug ?? false,
476
- autoRestart: options.autoRestart ?? true
477
- });
478
- try {
479
- await autoProxy.setup(server);
480
- } catch (error) {
481
- console.error("[vite-auto-proxy-cookie] Failed to setup proxy:", error);
482
- if (options.debug) {
483
- console.log("[vite-auto-proxy-cookie] Falling back to middleware mode");
484
- }
485
- }
486
- },
487
- closeBundle() {
488
- autoProxy?.stop();
761
+ // src/proxy/vite-middleware-plugin.ts
762
+ function isIgnoredPath(pathname, ignorePaths) {
763
+ return ignorePaths.some((ignored) => pathname.startsWith(ignored));
764
+ }
765
+ function shouldProxy(pathname, proxyPrefixes) {
766
+ return proxyPrefixes.some((prefix) => pathname.startsWith(prefix));
767
+ }
768
+ function getProxyTarget(pathname, proxyMap, defaultTarget) {
769
+ for (const [prefix, target] of Object.entries(proxyMap)) {
770
+ if (pathname.startsWith(prefix)) {
771
+ return target;
489
772
  }
490
- };
773
+ }
774
+ return defaultTarget;
491
775
  }
492
-
493
- // src/proxy/vite-cookie-plugin.ts
494
- function viteDevProxyCookie(options) {
495
- const { cookieFile, debug = false, onCookieChange } = options;
496
- let watcher = null;
497
- let currentCookie = "";
498
- const cookieReader = new CookieReader({ cookieFile });
776
+ function viteMiddlewareProxy(options) {
777
+ const {
778
+ cookieFile,
779
+ target,
780
+ debug = false,
781
+ proxyMap = {},
782
+ proxyPaths = [],
783
+ ignorePaths = []
784
+ } = options;
785
+ const cookieReader = new CookieReader({ cookieFile }, debug);
786
+ let currentCookie = cookieReader.readCookie();
787
+ const allProxyPrefixes = [
788
+ ...Object.keys(proxyMap),
789
+ ...proxyPaths
790
+ ];
499
791
  return {
500
- name: "vite-dev-proxy-cookie",
792
+ name: "vite-middleware-proxy",
501
793
  apply: "serve",
502
794
  configureServer(server) {
503
- currentCookie = cookieReader.readCookie();
795
+ const httpProxy2 = require("http-proxy");
796
+ const proxyServer = httpProxy2.createProxyServer({});
504
797
  if (debug) {
505
- console.log("[vite-dev-proxy-cookie] Initial cookie loaded");
506
- }
507
- const middlewares = server.middlewares || server._middlewares || server.app;
508
- if (middlewares && typeof middlewares.use === "function") {
509
- middlewares.use((req, _res, next) => {
510
- if (currentCookie && req.url?.startsWith("/")) {
511
- req.headers = req.headers || {};
512
- req.headers["cookie"] = currentCookie;
798
+ console.log("[ViteMiddlewareProxy] Watching cookie file:", cookieFile);
799
+ }
800
+ server.middlewares.use((req, res, next) => {
801
+ const pathname = new URL(req.url || "/", "http://localhost").pathname;
802
+ if (isIgnoredPath(pathname, ignorePaths)) {
803
+ if (debug) {
804
+ console.log("[ViteMiddlewareProxy] Ignoring:", pathname);
513
805
  }
514
806
  next();
515
- });
516
- } else {
517
- console.warn("[vite-dev-proxy-cookie] Could not access middleware stack, cookie injection disabled");
518
- }
519
- watcher = watchCookieFile(
520
- cookieFile,
521
- (newCookie) => {
522
- currentCookie = newCookie;
523
- onCookieChange?.(newCookie);
524
- console.log("[vite-dev-proxy-cookie] Cookie changed, please restart server for full effect");
525
- },
526
- (error) => {
527
- console.error("[vite-dev-proxy-cookie] Watch error:", error.message);
807
+ return;
528
808
  }
529
- );
530
- },
531
- closeBundle() {
532
- watcher?.stop();
809
+ if (!shouldProxy(pathname, allProxyPrefixes)) {
810
+ next();
811
+ return;
812
+ }
813
+ const proxyTarget = getProxyTarget(pathname, proxyMap, target);
814
+ if (debug) {
815
+ console.log("[ViteMiddlewareProxy] Proxying:", req.method, pathname, "->", proxyTarget);
816
+ }
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
+ proxyServer.web(req, res, {
826
+ target: proxyTarget,
827
+ changeOrigin: true,
828
+ secure: false,
829
+ ignorePath: false
830
+ });
831
+ });
832
+ proxyServer.on("error", (err, req) => {
833
+ console.error("[ViteMiddlewareProxy] Proxy error:", err.message, "for", req.url);
834
+ });
533
835
  }
534
836
  };
535
837
  }
@@ -569,9 +871,23 @@ function createVueProxyConfig(target, options = {}) {
569
871
  return config;
570
872
  }
571
873
  function createFileCookieGetter(cookieFile, options = {}) {
572
- const { watch = true, debug = false } = options;
573
- const reader = new CookieReader({ cookieFile: path4.resolve(cookieFile) });
574
- if (watch) {
874
+ const {
875
+ watch = "auto",
876
+ debug = true,
877
+ productionEnvs = [],
878
+ isDev
879
+ } = options;
880
+ const reader = new CookieReader({ cookieFile: path4.resolve(cookieFile) }, debug);
881
+ let shouldWatch;
882
+ if (isDev !== void 0) {
883
+ shouldWatch = isDev;
884
+ if (debug) {
885
+ console.log(`[CookieFile] isDev=${isDev}, ${shouldWatch ? "enabling" : "disabling"} watch`);
886
+ }
887
+ } else {
888
+ shouldWatch = shouldEnableWatch(watch, productionEnvs, debug, "[CookieFile]");
889
+ }
890
+ if (shouldWatch) {
575
891
  watchCookieFile(
576
892
  path4.resolve(cookieFile),
577
893
  (newCookie) => {
@@ -583,6 +899,8 @@ function createFileCookieGetter(cookieFile, options = {}) {
583
899
  console.error("[CookieFile] Watch error:", error.message);
584
900
  }
585
901
  );
902
+ } else if (debug) {
903
+ console.log("[CookieFile] File watch disabled");
586
904
  }
587
905
  return () => reader.readCookie();
588
906
  }
@@ -624,57 +942,6 @@ function createAutoProxyConfig(options) {
624
942
  }
625
943
  return result;
626
944
  }
627
-
628
- // src/proxy/vite-adapter.ts
629
- var viteVersion = "";
630
- var majorVersion = null;
631
- function detectViteVersion() {
632
- if (majorVersion !== null) {
633
- return majorVersion;
634
- }
635
- try {
636
- const pkg = require("vite/package.json");
637
- viteVersion = pkg.version;
638
- majorVersion = parseInt(viteVersion.split(".")[0], 10);
639
- } catch {
640
- majorVersion = 5;
641
- }
642
- return majorVersion;
643
- }
644
- function createDevProxyCookie(options) {
645
- const {
646
- mode = "auto",
647
- ...restOptions
648
- } = options;
649
- const version = detectViteVersion();
650
- if (options.debug) {
651
- console.log(`[dev-proxy-cookie] Detected Vite ${version}.x`);
652
- }
653
- if (mode === "cookie" || mode === "auto" && !options.target) {
654
- return viteDevProxyCookie({
655
- cookieFile: options.cookieFile,
656
- debug: options.debug,
657
- onCookieChange: options.onCookieChange
658
- });
659
- }
660
- const pluginOptions = {
661
- cookieFile: options.cookieFile,
662
- target: options.target,
663
- debug: options.debug,
664
- autoRestart: options.autoRestart ?? true,
665
- restartMarkerFile: options.restartMarkerFile,
666
- proxyMap: options.proxyMap,
667
- ignorePaths: options.ignorePaths
668
- };
669
- return viteAutoProxyCookie(pluginOptions);
670
- }
671
- function getViteVersion() {
672
- detectViteVersion();
673
- return viteVersion;
674
- }
675
- function getViteMajorVersion() {
676
- return detectViteVersion();
677
- }
678
945
  // Annotate the CommonJS export names for ESM import in node:
679
946
  0 && (module.exports = {
680
947
  AutoProxyCookie,
@@ -683,12 +950,11 @@ function getViteMajorVersion() {
683
950
  createAutoProxyConfig,
684
951
  createAutoProxyCookie,
685
952
  createCookieGetter,
686
- createDevProxyCookie,
687
953
  createFileCookieGetter,
688
954
  createVueProxyConfig,
689
- getViteMajorVersion,
690
- getViteVersion,
691
- viteAutoProxyCookie,
692
- viteDevProxyCookie,
955
+ detectProductionEnvironment,
956
+ isProductionValue,
957
+ shouldEnableWatch,
958
+ viteMiddlewareProxy,
693
959
  watchCookieFile
694
960
  });