@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.mjs CHANGED
@@ -15,26 +15,62 @@ import httpProxy from "http-proxy";
15
15
  import * as fs from "fs";
16
16
  import * as path from "path";
17
17
  var CookieReader = class {
18
- constructor(options) {
18
+ /**
19
+ * 构造函数
20
+ * @param options - 配置选项
21
+ * @param debug - 是否启用调试模式
22
+ */
23
+ constructor(options, debug = false) {
19
24
  this.options = {
20
25
  encoding: "utf-8",
21
26
  ...options
22
27
  };
28
+ this.debug = debug;
23
29
  }
30
+ /**
31
+ * 读取 Cookie 文件内容
32
+ *
33
+ * 支持过滤注释行(以 # 开头)和空行,将有效行用分号连接。
34
+ *
35
+ * @returns Cookie 字符串
36
+ */
24
37
  readCookie() {
25
38
  try {
26
39
  const filePath = path.resolve(this.options.cookieFile);
40
+ if (this.debug) {
41
+ console.log("[CookieReader] Resolved cookie file path:", filePath);
42
+ console.log("[CookieReader] File exists:", fs.existsSync(filePath));
43
+ }
27
44
  if (fs.existsSync(filePath)) {
28
45
  const content = fs.readFileSync(filePath, this.options.encoding || "utf-8");
46
+ if (this.debug) {
47
+ console.log("[CookieReader] File content length:", content.length);
48
+ }
29
49
  const lines = content.split("\n");
30
50
  const cookieLines = lines.map((line) => line.trim()).filter((line) => line && !line.startsWith("#"));
31
- return cookieLines.join("; ");
51
+ const result = cookieLines.join("; ");
52
+ if (this.debug) {
53
+ console.log("[CookieReader] Parsed cookie:", result ? "(has cookie)" : "(empty)");
54
+ }
55
+ return result;
56
+ }
57
+ if (this.debug) {
58
+ console.log("[CookieReader] Cookie file not found:", filePath);
32
59
  }
33
60
  return "";
34
- } catch {
61
+ } catch (err) {
62
+ if (this.debug) {
63
+ console.error("[CookieReader] Error reading cookie file:", err.message);
64
+ }
35
65
  return "";
36
66
  }
37
67
  }
68
+ /**
69
+ * 确保 Cookie 文件存在
70
+ *
71
+ * 如果文件不存在,会自动创建空文件。
72
+ * 如果父目录不存在,会自动创建目录。
73
+ */
38
74
  ensureCookieFile() {
39
75
  const filePath = path.resolve(this.options.cookieFile);
40
76
  const dir = path.dirname(filePath);
@@ -55,9 +91,20 @@ function createCookieGetter(cookieFile) {
55
91
  import * as path2 from "path";
56
92
  import chokidar from "chokidar";
57
93
  var CookieWatcher = class {
94
+ /**
95
+ * 构造函数
96
+ * @param options - 配置选项
97
+ */
58
98
  constructor(options) {
99
+ /** 文件监听器实例 */
59
100
  this.watcher = null;
101
+ /** 上次读取的 Cookie 内容 */
60
102
  this.lastContent = "";
103
+ /**
104
+ * 文件变化处理函数
105
+ *
106
+ * 读取新的 Cookie 内容,如果与上次不同则触发回调。
107
+ */
61
108
  this.handleChange = () => {
62
109
  const newContent = this.cookieReader.readCookie();
63
110
  if (newContent !== this.lastContent) {
@@ -72,6 +119,9 @@ var CookieWatcher = class {
72
119
  };
73
120
  this.cookieReader = new CookieReader({ cookieFile: options.cookieFile });
74
121
  }
122
+ /**
123
+ * 启动文件监听
124
+ */
75
125
  start() {
76
126
  if (this.options.autoCreateFile) {
77
127
  this.cookieReader.ensureCookieFile();
@@ -97,6 +147,9 @@ var CookieWatcher = class {
97
147
  this.options.onError?.(error);
98
148
  }
99
149
  }
150
+ /**
151
+ * 停止文件监听
152
+ */
100
153
  stop() {
101
154
  if (this.watcher) {
102
155
  this.watcher.close();
@@ -104,6 +157,10 @@ var CookieWatcher = class {
104
157
  console.log(`[CookieWatcher] Stopped watching: ${this.options.cookieFile}`);
105
158
  }
106
159
  }
160
+ /**
161
+ * 获取当前 Cookie 值
162
+ * @returns 当前 Cookie 字符串
163
+ */
107
164
  getCurrentCookie() {
108
165
  return this.lastContent;
109
166
  }
@@ -118,21 +175,145 @@ function watchCookieFile(cookieFile, onCookieChange, onError) {
118
175
  return watcher;
119
176
  }
120
177
 
178
+ // src/utils/env-detector.ts
179
+ function isProductionValue(value) {
180
+ const productionValues = [
181
+ "production",
182
+ // 生产环境
183
+ "prod",
184
+ // 生产环境
185
+ "prd",
186
+ // 生产环境
187
+ "release",
188
+ // 发布环境
189
+ "staging",
190
+ // 预发布环境
191
+ "uat"
192
+ // 预发布环境
193
+ ];
194
+ return productionValues.includes(value.toLowerCase().trim());
195
+ }
196
+ function detectProductionEnvironment(customEnvs = [], debug = false, loggerPrefix = "[env-detector]") {
197
+ const env = process.env;
198
+ if (customEnvs.length > 0) {
199
+ for (const envName of customEnvs) {
200
+ const envValue = env[envName];
201
+ if (envValue && isProductionValue(envValue)) {
202
+ if (debug) {
203
+ console.log(`${loggerPrefix} Detected production via custom env: ${envName}=${envValue}`);
204
+ }
205
+ return true;
206
+ }
207
+ }
208
+ }
209
+ const commonEnvNames = [
210
+ "NODE_ENV",
211
+ "BUILD_MODE",
212
+ "VUE_APP_ENV",
213
+ "VITE_NODE_ENV",
214
+ "WEBPACK_MODE",
215
+ "CI_ENV",
216
+ "APP_ENV",
217
+ "ENV",
218
+ "DEPLOY_ENV",
219
+ "RUN_MODE"
220
+ ];
221
+ for (const envName of commonEnvNames) {
222
+ const envValue = env[envName];
223
+ if (envValue && isProductionValue(envValue)) {
224
+ if (debug) {
225
+ console.log(`${loggerPrefix} Detected production via env: ${envName}=${envValue}`);
226
+ }
227
+ return true;
228
+ }
229
+ }
230
+ if (env.CI === "true" || env.CI === "1" || env.CI === "yes") {
231
+ if (debug) {
232
+ console.log(`${loggerPrefix} Detected production via CI env`);
233
+ }
234
+ return true;
235
+ }
236
+ if (env.npm_lifecycle_event) {
237
+ const lifecycleEvent = env.npm_lifecycle_event.toLowerCase();
238
+ if (lifecycleEvent.includes("build") || lifecycleEvent.includes("prod") || lifecycleEvent.includes("prd") || lifecycleEvent.includes("release")) {
239
+ if (debug) {
240
+ console.log(`${loggerPrefix} Detected production via lifecycle event: ${env.npm_lifecycle_event}`);
241
+ }
242
+ return true;
243
+ }
244
+ }
245
+ const processArgs = process.argv.join("").toLowerCase();
246
+ if (processArgs.includes("build") || processArgs.includes("production") || processArgs.includes("--mode=production") || processArgs.includes("--prod") || processArgs.includes("--release")) {
247
+ if (debug) {
248
+ console.log(`${loggerPrefix} Detected production via process arguments`);
249
+ }
250
+ return true;
251
+ }
252
+ return false;
253
+ }
254
+ function shouldEnableWatch(watch, customEnvs = [], debug = false, loggerPrefix = "[env-detector]") {
255
+ if (typeof watch === "boolean") {
256
+ if (debug && !watch) {
257
+ console.log(`${loggerPrefix} Watch disabled by user setting`);
258
+ }
259
+ return watch;
260
+ }
261
+ const isProduction = detectProductionEnvironment(customEnvs, debug, loggerPrefix);
262
+ if (isProduction) {
263
+ if (debug) {
264
+ console.log(`${loggerPrefix} Auto-detected production mode - disabling watch`);
265
+ }
266
+ return false;
267
+ }
268
+ if (debug) {
269
+ console.log(`${loggerPrefix} Auto-detected development mode - enabling watch`);
270
+ }
271
+ return true;
272
+ }
273
+
121
274
  // src/proxy/apply-dev-cookie-header.ts
122
275
  function applyDevCookieHeader(proxyReq, cookie) {
123
- if (!cookie) return;
276
+ console.log("[applyDevCookieHeader] === START ===");
277
+ console.log("[applyDevCookieHeader] Cookie to apply:", cookie ? `(length: ${cookie.length})` : "(empty)");
278
+ if (!cookie) {
279
+ console.log("[applyDevCookieHeader] Cookie is empty, returning");
280
+ console.log("[applyDevCookieHeader] === END ===");
281
+ return;
282
+ }
283
+ const existingCookie = proxyReq.getHeader?.("Cookie");
284
+ console.log("[applyDevCookieHeader] Cookie current:", existingCookie ? `(length: ${String(existingCookie).length})` : "(none)");
285
+ if (existingCookie === cookie) {
286
+ console.log("[applyDevCookieHeader] Cookie is already set, skipping");
287
+ console.log("[applyDevCookieHeader] === END ===");
288
+ return;
289
+ }
124
290
  proxyReq.removeHeader("cookie");
125
291
  proxyReq.removeHeader("Cookie");
126
292
  proxyReq.setHeader("Cookie", cookie);
293
+ const newCookie = proxyReq.getHeader?.("Cookie");
294
+ console.log("[applyDevCookieHeader] Cookie new:", newCookie ? `(length: ${String(newCookie).length})` : "(failed)");
295
+ console.log("[applyDevCookieHeader] === END ===");
127
296
  }
128
297
 
129
298
  // src/proxy/core.ts
130
299
  var AutoProxyCookie = class {
300
+ /**
301
+ * 构造函数
302
+ * @param options - 配置选项
303
+ */
131
304
  constructor(options) {
305
+ /** 当前 Cookie 值 */
132
306
  this.currentCookie = "";
307
+ /** Vite 开发服务器实例 */
133
308
  this.server = null;
309
+ /** HTTP 代理服务器实例 */
134
310
  this.proxyServer = null;
311
+ /** Cookie 文件监听器 */
135
312
  this.watcher = null;
313
+ /**
314
+ * Cookie 变化处理函数
315
+ * @param newCookie - 新的 Cookie 值
316
+ */
136
317
  this.handleCookieChange = (newCookie) => {
137
318
  if (newCookie !== this.currentCookie) {
138
319
  this.currentCookie = newCookie;
@@ -148,9 +329,23 @@ var AutoProxyCookie = class {
148
329
  }
149
330
  }
150
331
  };
332
+ /**
333
+ * 代理请求处理函数
334
+ * @param proxyReq - 代理请求对象
335
+ * @param req - 原始请求对象
336
+ * @param res - 响应对象
337
+ * @param _options - 服务器选项
338
+ */
151
339
  this.handleOnProxyReq = (proxyReq, req, res, _options) => {
340
+ console.log("[AutoProxyCookie] === handleOnProxyReq START ===");
341
+ console.log("[AutoProxyCookie] Request URL:", req.method, req.url);
342
+ console.log("[AutoProxyCookie] Current cookie:", this.currentCookie ? `(length: ${this.currentCookie.length})` : "(empty)");
152
343
  if (this.currentCookie) {
344
+ console.log("[AutoProxyCookie] Applying cookie header...");
153
345
  applyDevCookieHeader(proxyReq, this.currentCookie);
346
+ console.log("[AutoProxyCookie] Cookie header applied successfully");
347
+ } else {
348
+ console.log("[AutoProxyCookie] No cookie to apply - currentCookie is empty!");
154
349
  }
155
350
  this.log("debug", "[AutoProxyCookie] Proxy Request:", req.method, req.url);
156
351
  if (this.options.hooks.onProxyReq) {
@@ -160,7 +355,14 @@ var AutoProxyCookie = class {
160
355
  this.log("error", "[AutoProxyCookie] onProxyReq hook error:", err.message);
161
356
  }
162
357
  }
358
+ console.log("[AutoProxyCookie] === handleOnProxyReq END ===");
163
359
  };
360
+ /**
361
+ * 代理响应处理函数
362
+ * @param proxyRes - 代理响应对象
363
+ * @param req - 原始请求对象
364
+ * @param res - 响应对象
365
+ */
164
366
  this.handleOnProxyRes = (proxyRes, req, res) => {
165
367
  const allowedHeaders = [
166
368
  "Content-Type",
@@ -184,6 +386,12 @@ var AutoProxyCookie = class {
184
386
  }
185
387
  }
186
388
  };
389
+ /**
390
+ * HTTP 代理错误处理函数
391
+ * @param err - 错误对象
392
+ * @param req - 请求对象
393
+ * @param res - 响应对象或 Socket
394
+ */
187
395
  this.handleOnError = (err, req, res) => {
188
396
  this.log("error", "[AutoProxyCookie] Proxy Error:", err.message);
189
397
  this.log("error", "[AutoProxyCookie] URL:", req.url);
@@ -203,6 +411,12 @@ var AutoProxyCookie = class {
203
411
  }
204
412
  }
205
413
  };
414
+ /**
415
+ * WebSocket 代理错误处理函数
416
+ * @param err - 错误对象
417
+ * @param req - 请求对象
418
+ * @param socket - WebSocket 连接的 Socket
419
+ */
206
420
  this.handleOnWsError = (err, req, socket) => {
207
421
  this.log("error", "[AutoProxyCookie] WebSocket Proxy Error:", err.message);
208
422
  this.log("error", "[AutoProxyCookie] WebSocket URL:", req.url);
@@ -239,6 +453,7 @@ var AutoProxyCookie = class {
239
453
  autoRestart: false,
240
454
  restartMarkerFile: ".cookie-restart-marker",
241
455
  proxyMap: {},
456
+ proxyPaths: [],
242
457
  ignorePaths: [],
243
458
  ws: true,
244
459
  changeOrigin: true,
@@ -252,27 +467,60 @@ var AutoProxyCookie = class {
252
467
  headers: {},
253
468
  ...mergedOptions
254
469
  };
255
- this.cookieReader = new CookieReader({ cookieFile: options.cookieFile });
470
+ this.cookieReader = new CookieReader({ cookieFile: options.cookieFile }, options.debug ?? false);
256
471
  }
472
+ /**
473
+ * 根据请求路径获取代理目标 URL
474
+ * @param req - HTTP 请求对象
475
+ * @returns 代理目标 URL
476
+ */
257
477
  getProxyUrl(req) {
258
- const pathname = req.url?.split("?")[0] || "/";
478
+ const fullUrl = req.url || "/";
479
+ const pathname = new URL(fullUrl, "http://localhost").pathname;
259
480
  const proxyMap = this.options.proxyMap || {};
481
+ const proxyPaths = this.options.proxyPaths || [];
482
+ this.log("debug", "[AutoProxyCookie] getProxyUrl - Request path:", pathname);
483
+ this.log("debug", "[AutoProxyCookie] getProxyUrl - Available proxyMap paths:", Object.keys(proxyMap));
484
+ this.log("debug", "[AutoProxyCookie] getProxyUrl - Available proxyPaths:", proxyPaths);
260
485
  for (const [prefix, target] of Object.entries(proxyMap)) {
261
- if (pathname.startsWith(prefix)) {
486
+ const matches = pathname.startsWith(prefix);
487
+ this.log("debug", "[AutoProxyCookie] getProxyUrl - Checking proxyMap:", prefix, "- matches:", matches);
488
+ if (matches) {
489
+ this.log("debug", "[AutoProxyCookie] getProxyUrl - Matched proxyMap:", prefix, "->", target);
262
490
  return target;
263
491
  }
264
492
  }
493
+ for (const prefix of proxyPaths) {
494
+ const matches = pathname.startsWith(prefix);
495
+ this.log("debug", "[AutoProxyCookie] getProxyUrl - Checking proxyPaths:", prefix, "- matches:", matches);
496
+ if (matches) {
497
+ this.log("debug", "[AutoProxyCookie] getProxyUrl - Matched proxyPaths:", prefix, "->", this.options.target);
498
+ return this.options.target;
499
+ }
500
+ }
501
+ this.log("debug", "[AutoProxyCookie] getProxyUrl - No match found, using default target:", this.options.target);
265
502
  return this.options.target;
266
503
  }
504
+ /**
505
+ * 判断路径是否应该被忽略(不代理)
506
+ * @param pathname - 请求路径
507
+ * @returns 是否忽略
508
+ */
267
509
  isIgnoredPath(pathname) {
268
510
  const ignorePaths = this.options.ignorePaths || [];
269
511
  return ignorePaths.some(
270
512
  (ignored) => pathname.startsWith(ignored)
271
513
  );
272
514
  }
515
+ /**
516
+ * 日志输出函数
517
+ * @param level - 日志级别
518
+ * @param args - 日志参数
519
+ */
273
520
  log(level, ...args) {
274
521
  const levels = { debug: 0, info: 1, warn: 2, error: 3 };
275
- const currentLevel = levels[this.options.logLevel || "info"];
522
+ const effectiveLogLevel = this.options.debug ? "debug" : this.options.logLevel || "info";
523
+ const currentLevel = levels[effectiveLogLevel];
276
524
  const msgLevel = levels[level];
277
525
  if (msgLevel >= currentLevel) {
278
526
  if (level === "error") {
@@ -284,6 +532,11 @@ var AutoProxyCookie = class {
284
532
  }
285
533
  }
286
534
  }
535
+ /**
536
+ * 创建代理服务器配置选项
537
+ * @param target - 代理目标地址
538
+ * @returns 代理服务器配置
539
+ */
287
540
  createProxyOptions(target) {
288
541
  const {
289
542
  ws,
@@ -312,6 +565,10 @@ var AutoProxyCookie = class {
312
565
  ignorePath: false
313
566
  };
314
567
  }
568
+ /**
569
+ * 初始化代理中间件
570
+ * @param server - Vite 开发服务器实例
571
+ */
315
572
  async setup(server) {
316
573
  this.server = server;
317
574
  this.currentCookie = this.cookieReader.readCookie();
@@ -339,25 +596,42 @@ var AutoProxyCookie = class {
339
596
  this.log("warn", "[AutoProxyCookie] http-proxy create failed, using basic mode:", err.message);
340
597
  }
341
598
  server.middlewares.use((req, res, next) => {
342
- const pathname = new URL(req.url || "/", "http://localhost").pathname;
599
+ const fullUrl = req.url || "/";
600
+ const pathname = new URL(fullUrl, "http://localhost").pathname;
601
+ console.log("[AutoProxyCookie] === Incoming Request ===");
602
+ console.log("[AutoProxyCookie] Method:", req.method);
603
+ console.log("[AutoProxyCookie] Full URL:", fullUrl);
604
+ console.log("[AutoProxyCookie] Pathname:", pathname);
605
+ console.log("[AutoProxyCookie] Headers:", JSON.stringify(req.headers, null, 2));
343
606
  if (this.isIgnoredPath(pathname)) {
607
+ console.log("[AutoProxyCookie] Path ignored, passing to next middleware");
344
608
  next();
345
609
  return;
346
610
  }
347
611
  this.currentCookie = this.cookieReader.readCookie();
612
+ console.log("[AutoProxyCookie] Current cookie:", this.currentCookie ? `(length: ${this.currentCookie.length})` : "(empty)");
613
+ if (this.currentCookie) {
614
+ console.log("[AutoProxyCookie] Cookie preview:", this.currentCookie);
615
+ }
616
+ const proxyMapKeys = Object.keys(this.options.proxyMap || {});
617
+ const proxyPaths = this.options.proxyPaths || [];
618
+ const allProxyPrefixes = [...proxyMapKeys, ...proxyPaths];
619
+ const matched = allProxyPrefixes.some((prefix) => pathname.startsWith(prefix));
620
+ console.log("[AutoProxyCookie] Path matches proxy rules:", matched);
348
621
  if (this.proxyServer) {
349
622
  const target = this.getProxyUrl(req);
350
- if (this.options.debug || this.options.logLevel === "debug") {
351
- this.log("info", `[AutoProxyCookie] ${pathname} -> ${target}`);
352
- }
623
+ console.log(`[AutoProxyCookie] Proxying ${req.method} ${pathname} -> ${target}`);
353
624
  const proxyOptions = this.createProxyOptions(target);
354
625
  try {
626
+ console.log("[AutoProxyCookie] Calling proxyServer.web...");
355
627
  this.proxyServer.web(req, res, proxyOptions);
628
+ console.log("[AutoProxyCookie] proxyServer.web called successfully");
356
629
  } catch (err) {
357
- this.log("error", "[AutoProxyCookie] Proxy web error:", err.message);
630
+ console.error("[AutoProxyCookie] Proxy web error:", err.message);
358
631
  next(err);
359
632
  }
360
633
  } else {
634
+ console.log("[AutoProxyCookie] No proxy server, passing to next middleware");
361
635
  next();
362
636
  }
363
637
  });
@@ -389,15 +663,37 @@ var AutoProxyCookie = class {
389
663
  this.log("info", "[AutoProxyCookie] WebSocket support enabled");
390
664
  }
391
665
  }
666
+ /**
667
+ * 启动 Cookie 文件监听
668
+ */
392
669
  startFileWatch() {
393
- this.watcher = watchCookieFile(
394
- this.options.cookieFile,
395
- this.handleCookieChange,
396
- (error) => {
397
- this.log("error", "[AutoProxyCookie] File watch error:", error.message);
670
+ let shouldWatch;
671
+ if (this.options.isDev !== void 0) {
672
+ shouldWatch = this.options.isDev;
673
+ if (this.options.debug) {
674
+ console.log(`[AutoProxyCookie] isDev=${this.options.isDev}, ${shouldWatch ? "enabling" : "disabling"} watch`);
398
675
  }
399
- );
676
+ } else {
677
+ shouldWatch = true;
678
+ if (this.options.debug) {
679
+ console.log("[AutoProxyCookie] Default behavior: enabling watch (dev mode)");
680
+ }
681
+ }
682
+ if (shouldWatch) {
683
+ this.watcher = watchCookieFile(
684
+ this.options.cookieFile,
685
+ this.handleCookieChange,
686
+ (error) => {
687
+ this.log("error", "[AutoProxyCookie] File watch error:", error.message);
688
+ }
689
+ );
690
+ } else if (this.options.debug) {
691
+ console.log("[AutoProxyCookie] File watch disabled");
692
+ }
400
693
  }
694
+ /**
695
+ * 停止代理服务
696
+ */
401
697
  stop() {
402
698
  if (this.watcher) {
403
699
  this.watcher.stop();
@@ -409,6 +705,10 @@ var AutoProxyCookie = class {
409
705
  }
410
706
  this.log("info", "[AutoProxyCookie] Stopped");
411
707
  }
708
+ /**
709
+ * 获取当前 Cookie 值
710
+ * @returns 当前 Cookie 字符串
711
+ */
412
712
  getCurrentCookie() {
413
713
  return this.currentCookie;
414
714
  }
@@ -417,77 +717,80 @@ function createAutoProxyCookie(options) {
417
717
  return new AutoProxyCookie(options);
418
718
  }
419
719
 
420
- // src/proxy/vite-plugin.ts
421
- function viteAutoProxyCookie(options) {
422
- const {
423
- name = "vite-auto-proxy-cookie",
424
- ...autoProxyOptions
425
- } = options;
426
- let autoProxy = null;
427
- return {
428
- name,
429
- apply: "serve",
430
- async configureServer(server) {
431
- autoProxy = createAutoProxyCookie({
432
- ...autoProxyOptions,
433
- debug: options.debug ?? false,
434
- autoRestart: options.autoRestart ?? true
435
- });
436
- try {
437
- await autoProxy.setup(server);
438
- } catch (error) {
439
- console.error("[vite-auto-proxy-cookie] Failed to setup proxy:", error);
440
- if (options.debug) {
441
- console.log("[vite-auto-proxy-cookie] Falling back to middleware mode");
442
- }
443
- }
444
- },
445
- closeBundle() {
446
- autoProxy?.stop();
720
+ // src/proxy/vite-middleware-plugin.ts
721
+ function isIgnoredPath(pathname, ignorePaths) {
722
+ return ignorePaths.some((ignored) => pathname.startsWith(ignored));
723
+ }
724
+ function shouldProxy(pathname, proxyPrefixes) {
725
+ return proxyPrefixes.some((prefix) => pathname.startsWith(prefix));
726
+ }
727
+ function getProxyTarget(pathname, proxyMap, defaultTarget) {
728
+ for (const [prefix, target] of Object.entries(proxyMap)) {
729
+ if (pathname.startsWith(prefix)) {
730
+ return target;
447
731
  }
448
- };
732
+ }
733
+ return defaultTarget;
449
734
  }
450
-
451
- // src/proxy/vite-cookie-plugin.ts
452
- function viteDevProxyCookie(options) {
453
- const { cookieFile, debug = false, onCookieChange } = options;
454
- let watcher = null;
455
- let currentCookie = "";
456
- const cookieReader = new CookieReader({ cookieFile });
735
+ function viteMiddlewareProxy(options) {
736
+ const {
737
+ cookieFile,
738
+ target,
739
+ debug = false,
740
+ proxyMap = {},
741
+ proxyPaths = [],
742
+ ignorePaths = []
743
+ } = options;
744
+ const cookieReader = new CookieReader({ cookieFile }, debug);
745
+ let currentCookie = cookieReader.readCookie();
746
+ const allProxyPrefixes = [
747
+ ...Object.keys(proxyMap),
748
+ ...proxyPaths
749
+ ];
457
750
  return {
458
- name: "vite-dev-proxy-cookie",
751
+ name: "vite-middleware-proxy",
459
752
  apply: "serve",
460
753
  configureServer(server) {
461
- currentCookie = cookieReader.readCookie();
754
+ const httpProxy2 = __require("http-proxy");
755
+ const proxyServer = httpProxy2.createProxyServer({});
462
756
  if (debug) {
463
- console.log("[vite-dev-proxy-cookie] Initial cookie loaded");
464
- }
465
- const middlewares = server.middlewares || server._middlewares || server.app;
466
- if (middlewares && typeof middlewares.use === "function") {
467
- middlewares.use((req, _res, next) => {
468
- if (currentCookie && req.url?.startsWith("/")) {
469
- req.headers = req.headers || {};
470
- req.headers["cookie"] = currentCookie;
757
+ console.log("[ViteMiddlewareProxy] Watching cookie file:", cookieFile);
758
+ }
759
+ server.middlewares.use((req, res, next) => {
760
+ const pathname = new URL(req.url || "/", "http://localhost").pathname;
761
+ if (isIgnoredPath(pathname, ignorePaths)) {
762
+ if (debug) {
763
+ console.log("[ViteMiddlewareProxy] Ignoring:", pathname);
471
764
  }
472
765
  next();
473
- });
474
- } else {
475
- console.warn("[vite-dev-proxy-cookie] Could not access middleware stack, cookie injection disabled");
476
- }
477
- watcher = watchCookieFile(
478
- cookieFile,
479
- (newCookie) => {
480
- currentCookie = newCookie;
481
- onCookieChange?.(newCookie);
482
- console.log("[vite-dev-proxy-cookie] Cookie changed, please restart server for full effect");
483
- },
484
- (error) => {
485
- console.error("[vite-dev-proxy-cookie] Watch error:", error.message);
766
+ return;
486
767
  }
487
- );
488
- },
489
- closeBundle() {
490
- watcher?.stop();
768
+ if (!shouldProxy(pathname, allProxyPrefixes)) {
769
+ next();
770
+ return;
771
+ }
772
+ const proxyTarget = getProxyTarget(pathname, proxyMap, target);
773
+ if (debug) {
774
+ console.log("[ViteMiddlewareProxy] Proxying:", req.method, pathname, "->", proxyTarget);
775
+ }
776
+ currentCookie = cookieReader.readCookie();
777
+ if (currentCookie) {
778
+ if (debug) {
779
+ console.log("[ViteMiddlewareProxy] Injecting cookie:", `(length: ${currentCookie.length})`);
780
+ }
781
+ req.headers["cookie"] = currentCookie;
782
+ req.headers["Cookie"] = currentCookie;
783
+ }
784
+ proxyServer.web(req, res, {
785
+ target: proxyTarget,
786
+ changeOrigin: true,
787
+ secure: false,
788
+ ignorePath: false
789
+ });
790
+ });
791
+ proxyServer.on("error", (err, req) => {
792
+ console.error("[ViteMiddlewareProxy] Proxy error:", err.message, "for", req.url);
793
+ });
491
794
  }
492
795
  };
493
796
  }
@@ -527,9 +830,23 @@ function createVueProxyConfig(target, options = {}) {
527
830
  return config;
528
831
  }
529
832
  function createFileCookieGetter(cookieFile, options = {}) {
530
- const { watch = true, debug = false } = options;
531
- const reader = new CookieReader({ cookieFile: path4.resolve(cookieFile) });
532
- if (watch) {
833
+ const {
834
+ watch = "auto",
835
+ debug = true,
836
+ productionEnvs = [],
837
+ isDev
838
+ } = options;
839
+ const reader = new CookieReader({ cookieFile: path4.resolve(cookieFile) }, debug);
840
+ let shouldWatch;
841
+ if (isDev !== void 0) {
842
+ shouldWatch = isDev;
843
+ if (debug) {
844
+ console.log(`[CookieFile] isDev=${isDev}, ${shouldWatch ? "enabling" : "disabling"} watch`);
845
+ }
846
+ } else {
847
+ shouldWatch = shouldEnableWatch(watch, productionEnvs, debug, "[CookieFile]");
848
+ }
849
+ if (shouldWatch) {
533
850
  watchCookieFile(
534
851
  path4.resolve(cookieFile),
535
852
  (newCookie) => {
@@ -541,6 +858,8 @@ function createFileCookieGetter(cookieFile, options = {}) {
541
858
  console.error("[CookieFile] Watch error:", error.message);
542
859
  }
543
860
  );
861
+ } else if (debug) {
862
+ console.log("[CookieFile] File watch disabled");
544
863
  }
545
864
  return () => reader.readCookie();
546
865
  }
@@ -582,57 +901,6 @@ function createAutoProxyConfig(options) {
582
901
  }
583
902
  return result;
584
903
  }
585
-
586
- // src/proxy/vite-adapter.ts
587
- var viteVersion = "";
588
- var majorVersion = null;
589
- function detectViteVersion() {
590
- if (majorVersion !== null) {
591
- return majorVersion;
592
- }
593
- try {
594
- const pkg = __require("vite/package.json");
595
- viteVersion = pkg.version;
596
- majorVersion = parseInt(viteVersion.split(".")[0], 10);
597
- } catch {
598
- majorVersion = 5;
599
- }
600
- return majorVersion;
601
- }
602
- function createDevProxyCookie(options) {
603
- const {
604
- mode = "auto",
605
- ...restOptions
606
- } = options;
607
- const version = detectViteVersion();
608
- if (options.debug) {
609
- console.log(`[dev-proxy-cookie] Detected Vite ${version}.x`);
610
- }
611
- if (mode === "cookie" || mode === "auto" && !options.target) {
612
- return viteDevProxyCookie({
613
- cookieFile: options.cookieFile,
614
- debug: options.debug,
615
- onCookieChange: options.onCookieChange
616
- });
617
- }
618
- const pluginOptions = {
619
- cookieFile: options.cookieFile,
620
- target: options.target,
621
- debug: options.debug,
622
- autoRestart: options.autoRestart ?? true,
623
- restartMarkerFile: options.restartMarkerFile,
624
- proxyMap: options.proxyMap,
625
- ignorePaths: options.ignorePaths
626
- };
627
- return viteAutoProxyCookie(pluginOptions);
628
- }
629
- function getViteVersion() {
630
- detectViteVersion();
631
- return viteVersion;
632
- }
633
- function getViteMajorVersion() {
634
- return detectViteVersion();
635
- }
636
904
  export {
637
905
  AutoProxyCookie,
638
906
  CookieReader,
@@ -640,12 +908,11 @@ export {
640
908
  createAutoProxyConfig,
641
909
  createAutoProxyCookie,
642
910
  createCookieGetter,
643
- createDevProxyCookie,
644
911
  createFileCookieGetter,
645
912
  createVueProxyConfig,
646
- getViteMajorVersion,
647
- getViteVersion,
648
- viteAutoProxyCookie,
649
- viteDevProxyCookie,
913
+ detectProductionEnvironment,
914
+ isProductionValue,
915
+ shouldEnableWatch,
916
+ viteMiddlewareProxy,
650
917
  watchCookieFile
651
918
  };