unplugin-https-reverse-proxy 4.1.0-beta.2 → 4.1.0-beta.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/dist/nuxt.cjs CHANGED
@@ -33,11 +33,11 @@ __export(nuxt_exports, {
33
33
  default: () => nuxt_default
34
34
  });
35
35
  module.exports = __toCommonJS(nuxt_exports);
36
- var import_node_process9 = __toESM(require("process"), 1);
36
+ var import_node_process10 = __toESM(require("process"), 1);
37
37
  var import_kit = require("@nuxt/kit");
38
38
 
39
39
  // src/index.ts
40
- var import_node_process8 = __toESM(require("process"), 1);
40
+ var import_node_process9 = __toESM(require("process"), 1);
41
41
  var import_console_table_printer = require("console-table-printer");
42
42
  var import_picocolors2 = __toESM(require("picocolors"), 1);
43
43
  var import_unplugin = require("unplugin");
@@ -45,450 +45,13 @@ var import_unplugin = require("unplugin");
45
45
  // src/caddy/index.ts
46
46
  var import_node_child_process3 = require("child_process");
47
47
  var import_node_fs4 = require("fs");
48
- var import_promises3 = require("fs/promises");
48
+ var import_promises2 = require("fs/promises");
49
49
  var import_node_os5 = require("os");
50
50
  var import_node_path5 = require("path");
51
- var import_node_process7 = __toESM(require("process"), 1);
52
-
53
- // node_modules/.pnpm/alien-signals@2.0.7/node_modules/alien-signals/esm/system.mjs
54
- var ReactiveFlags;
55
- (function(ReactiveFlags2) {
56
- ReactiveFlags2[ReactiveFlags2["None"] = 0] = "None";
57
- ReactiveFlags2[ReactiveFlags2["Mutable"] = 1] = "Mutable";
58
- ReactiveFlags2[ReactiveFlags2["Watching"] = 2] = "Watching";
59
- ReactiveFlags2[ReactiveFlags2["RecursedCheck"] = 4] = "RecursedCheck";
60
- ReactiveFlags2[ReactiveFlags2["Recursed"] = 8] = "Recursed";
61
- ReactiveFlags2[ReactiveFlags2["Dirty"] = 16] = "Dirty";
62
- ReactiveFlags2[ReactiveFlags2["Pending"] = 32] = "Pending";
63
- })(ReactiveFlags || (ReactiveFlags = {}));
64
- function createReactiveSystem({ update, notify: notify2, unwatched }) {
65
- let currentVersion = 0;
66
- return {
67
- link: link2,
68
- unlink: unlink4,
69
- propagate: propagate2,
70
- checkDirty: checkDirty2,
71
- endTracking: endTracking2,
72
- startTracking: startTracking2,
73
- shallowPropagate: shallowPropagate2
74
- };
75
- function link2(dep, sub) {
76
- const prevDep = sub.depsTail;
77
- if (prevDep !== void 0 && prevDep.dep === dep) {
78
- return;
79
- }
80
- const nextDep = prevDep !== void 0 ? prevDep.nextDep : sub.deps;
81
- if (nextDep !== void 0 && nextDep.dep === dep) {
82
- nextDep.version = currentVersion;
83
- sub.depsTail = nextDep;
84
- return;
85
- }
86
- const prevSub = dep.subsTail;
87
- if (prevSub !== void 0 && prevSub.version === currentVersion && prevSub.sub === sub) {
88
- return;
89
- }
90
- const newLink = sub.depsTail = dep.subsTail = {
91
- version: currentVersion,
92
- dep,
93
- sub,
94
- prevDep,
95
- nextDep,
96
- prevSub,
97
- nextSub: void 0
98
- };
99
- if (nextDep !== void 0) {
100
- nextDep.prevDep = newLink;
101
- }
102
- if (prevDep !== void 0) {
103
- prevDep.nextDep = newLink;
104
- } else {
105
- sub.deps = newLink;
106
- }
107
- if (prevSub !== void 0) {
108
- prevSub.nextSub = newLink;
109
- } else {
110
- dep.subs = newLink;
111
- }
112
- }
113
- function unlink4(link3, sub = link3.sub) {
114
- const dep = link3.dep;
115
- const prevDep = link3.prevDep;
116
- const nextDep = link3.nextDep;
117
- const nextSub = link3.nextSub;
118
- const prevSub = link3.prevSub;
119
- if (nextDep !== void 0) {
120
- nextDep.prevDep = prevDep;
121
- } else {
122
- sub.depsTail = prevDep;
123
- }
124
- if (prevDep !== void 0) {
125
- prevDep.nextDep = nextDep;
126
- } else {
127
- sub.deps = nextDep;
128
- }
129
- if (nextSub !== void 0) {
130
- nextSub.prevSub = prevSub;
131
- } else {
132
- dep.subsTail = prevSub;
133
- }
134
- if (prevSub !== void 0) {
135
- prevSub.nextSub = nextSub;
136
- } else if ((dep.subs = nextSub) === void 0) {
137
- unwatched(dep);
138
- }
139
- return nextDep;
140
- }
141
- function propagate2(link3) {
142
- let next2 = link3.nextSub;
143
- let stack;
144
- top:
145
- do {
146
- const sub = link3.sub;
147
- let flags = sub.flags;
148
- if (!(flags & 60)) {
149
- sub.flags = flags | 32;
150
- } else if (!(flags & 12)) {
151
- flags = 0;
152
- } else if (!(flags & 4)) {
153
- sub.flags = flags & ~8 | 32;
154
- } else if (!(flags & 48) && isValidLink(link3, sub)) {
155
- sub.flags = flags | 40;
156
- flags &= 1;
157
- } else {
158
- flags = 0;
159
- }
160
- if (flags & 2) {
161
- notify2(sub);
162
- }
163
- if (flags & 1) {
164
- const subSubs = sub.subs;
165
- if (subSubs !== void 0) {
166
- const nextSub = (link3 = subSubs).nextSub;
167
- if (nextSub !== void 0) {
168
- stack = { value: next2, prev: stack };
169
- next2 = nextSub;
170
- }
171
- continue;
172
- }
173
- }
174
- if ((link3 = next2) !== void 0) {
175
- next2 = link3.nextSub;
176
- continue;
177
- }
178
- while (stack !== void 0) {
179
- link3 = stack.value;
180
- stack = stack.prev;
181
- if (link3 !== void 0) {
182
- next2 = link3.nextSub;
183
- continue top;
184
- }
185
- }
186
- break;
187
- } while (true);
188
- }
189
- function startTracking2(sub) {
190
- ++currentVersion;
191
- sub.depsTail = void 0;
192
- sub.flags = sub.flags & ~56 | 4;
193
- }
194
- function endTracking2(sub) {
195
- const depsTail = sub.depsTail;
196
- let toRemove = depsTail !== void 0 ? depsTail.nextDep : sub.deps;
197
- while (toRemove !== void 0) {
198
- toRemove = unlink4(toRemove, sub);
199
- }
200
- sub.flags &= ~4;
201
- }
202
- function checkDirty2(link3, sub) {
203
- let stack;
204
- let checkDepth = 0;
205
- top:
206
- do {
207
- const dep = link3.dep;
208
- const flags = dep.flags;
209
- let dirty = false;
210
- if (sub.flags & 16) {
211
- dirty = true;
212
- } else if ((flags & 17) === 17) {
213
- if (update(dep)) {
214
- const subs = dep.subs;
215
- if (subs.nextSub !== void 0) {
216
- shallowPropagate2(subs);
217
- }
218
- dirty = true;
219
- }
220
- } else if ((flags & 33) === 33) {
221
- if (link3.nextSub !== void 0 || link3.prevSub !== void 0) {
222
- stack = { value: link3, prev: stack };
223
- }
224
- link3 = dep.deps;
225
- sub = dep;
226
- ++checkDepth;
227
- continue;
228
- }
229
- if (!dirty) {
230
- const nextDep = link3.nextDep;
231
- if (nextDep !== void 0) {
232
- link3 = nextDep;
233
- continue;
234
- }
235
- }
236
- while (checkDepth--) {
237
- const firstSub = sub.subs;
238
- const hasMultipleSubs = firstSub.nextSub !== void 0;
239
- if (hasMultipleSubs) {
240
- link3 = stack.value;
241
- stack = stack.prev;
242
- } else {
243
- link3 = firstSub;
244
- }
245
- if (dirty) {
246
- if (update(sub)) {
247
- if (hasMultipleSubs) {
248
- shallowPropagate2(firstSub);
249
- }
250
- sub = link3.sub;
251
- continue;
252
- }
253
- } else {
254
- sub.flags &= ~32;
255
- }
256
- sub = link3.sub;
257
- const nextDep = link3.nextDep;
258
- if (nextDep !== void 0) {
259
- link3 = nextDep;
260
- continue top;
261
- }
262
- dirty = false;
263
- }
264
- return dirty;
265
- } while (true);
266
- }
267
- function shallowPropagate2(link3) {
268
- do {
269
- const sub = link3.sub;
270
- const flags = sub.flags;
271
- if ((flags & 48) === 32) {
272
- sub.flags = flags | 16;
273
- if (flags & 2) {
274
- notify2(sub);
275
- }
276
- }
277
- } while ((link3 = link3.nextSub) !== void 0);
278
- }
279
- function isValidLink(checkLink, sub) {
280
- let link3 = sub.depsTail;
281
- while (link3 !== void 0) {
282
- if (link3 === checkLink) {
283
- return true;
284
- }
285
- link3 = link3.prevDep;
286
- }
287
- return false;
288
- }
289
- }
290
-
291
- // node_modules/.pnpm/alien-signals@2.0.7/node_modules/alien-signals/esm/index.mjs
292
- var queuedEffects = [];
293
- var { link, unlink, propagate, checkDirty, endTracking, startTracking, shallowPropagate } = createReactiveSystem({
294
- update(signal2) {
295
- if ("getter" in signal2) {
296
- return updateComputed(signal2);
297
- } else {
298
- return updateSignal(signal2, signal2.value);
299
- }
300
- },
301
- notify,
302
- unwatched(node2) {
303
- if ("getter" in node2) {
304
- let toRemove = node2.deps;
305
- if (toRemove !== void 0) {
306
- node2.flags = 17;
307
- do {
308
- toRemove = unlink(toRemove, node2);
309
- } while (toRemove !== void 0);
310
- }
311
- } else if (!("previousValue" in node2)) {
312
- effectOper.call(node2);
313
- }
314
- }
315
- });
316
- var batchDepth = 0;
317
- var notifyIndex = 0;
318
- var queuedEffectsLength = 0;
319
- var activeSub;
320
- var activeScope;
321
- function setCurrentSub(sub) {
322
- const prevSub = activeSub;
323
- activeSub = sub;
324
- return prevSub;
325
- }
326
- function signal(initialValue) {
327
- return signalOper.bind({
328
- previousValue: initialValue,
329
- value: initialValue,
330
- subs: void 0,
331
- subsTail: void 0,
332
- flags: 1
333
- });
334
- }
335
- function computed(getter) {
336
- return computedOper.bind({
337
- value: void 0,
338
- subs: void 0,
339
- subsTail: void 0,
340
- deps: void 0,
341
- depsTail: void 0,
342
- flags: 17,
343
- getter
344
- });
345
- }
346
- function effect(fn) {
347
- const e = {
348
- fn,
349
- subs: void 0,
350
- subsTail: void 0,
351
- deps: void 0,
352
- depsTail: void 0,
353
- flags: 2
354
- };
355
- if (activeSub !== void 0) {
356
- link(e, activeSub);
357
- } else if (activeScope !== void 0) {
358
- link(e, activeScope);
359
- }
360
- const prev = setCurrentSub(e);
361
- try {
362
- e.fn();
363
- } finally {
364
- setCurrentSub(prev);
365
- }
366
- return effectOper.bind(e);
367
- }
368
- function updateComputed(c3) {
369
- const prevSub = setCurrentSub(c3);
370
- startTracking(c3);
371
- try {
372
- const oldValue = c3.value;
373
- return oldValue !== (c3.value = c3.getter(oldValue));
374
- } finally {
375
- setCurrentSub(prevSub);
376
- endTracking(c3);
377
- }
378
- }
379
- function updateSignal(s, value2) {
380
- s.flags = 1;
381
- return s.previousValue !== (s.previousValue = value2);
382
- }
383
- function notify(e) {
384
- const flags = e.flags;
385
- if (!(flags & 64)) {
386
- e.flags = flags | 64;
387
- const subs = e.subs;
388
- if (subs !== void 0) {
389
- notify(subs.sub);
390
- } else {
391
- queuedEffects[queuedEffectsLength++] = e;
392
- }
393
- }
394
- }
395
- function run(e, flags) {
396
- if (flags & 16 || flags & 32 && checkDirty(e.deps, e)) {
397
- const prev = setCurrentSub(e);
398
- startTracking(e);
399
- try {
400
- e.fn();
401
- } finally {
402
- setCurrentSub(prev);
403
- endTracking(e);
404
- }
405
- return;
406
- } else if (flags & 32) {
407
- e.flags = flags & ~32;
408
- }
409
- let link2 = e.deps;
410
- while (link2 !== void 0) {
411
- const dep = link2.dep;
412
- const depFlags = dep.flags;
413
- if (depFlags & 64) {
414
- run(dep, dep.flags = depFlags & ~64);
415
- }
416
- link2 = link2.nextDep;
417
- }
418
- }
419
- function flush() {
420
- while (notifyIndex < queuedEffectsLength) {
421
- const effect2 = queuedEffects[notifyIndex];
422
- queuedEffects[notifyIndex++] = void 0;
423
- run(effect2, effect2.flags &= ~64);
424
- }
425
- notifyIndex = 0;
426
- queuedEffectsLength = 0;
427
- }
428
- function computedOper() {
429
- const flags = this.flags;
430
- if (flags & 16 || flags & 32 && checkDirty(this.deps, this)) {
431
- if (updateComputed(this)) {
432
- const subs = this.subs;
433
- if (subs !== void 0) {
434
- shallowPropagate(subs);
435
- }
436
- }
437
- } else if (flags & 32) {
438
- this.flags = flags & ~32;
439
- }
440
- if (activeSub !== void 0) {
441
- link(this, activeSub);
442
- } else if (activeScope !== void 0) {
443
- link(this, activeScope);
444
- }
445
- return this.value;
446
- }
447
- function signalOper(...value2) {
448
- if (value2.length) {
449
- if (this.value !== (this.value = value2[0])) {
450
- this.flags = 17;
451
- const subs = this.subs;
452
- if (subs !== void 0) {
453
- propagate(subs);
454
- if (!batchDepth) {
455
- flush();
456
- }
457
- }
458
- }
459
- } else {
460
- const value3 = this.value;
461
- if (this.flags & 16) {
462
- if (updateSignal(this, value3)) {
463
- const subs = this.subs;
464
- if (subs !== void 0) {
465
- shallowPropagate(subs);
466
- }
467
- }
468
- }
469
- if (activeSub !== void 0) {
470
- link(this, activeSub);
471
- }
472
- return value3;
473
- }
474
- }
475
- function effectOper() {
476
- let dep = this.deps;
477
- while (dep !== void 0) {
478
- dep = unlink(dep, this);
479
- }
480
- const sub = this.subs;
481
- if (sub !== void 0) {
482
- unlink(sub);
483
- }
484
- this.flags = 0;
485
- }
486
-
487
- // src/caddy/index.ts
51
+ var import_node_process8 = __toESM(require("process"), 1);
488
52
  var import_got_cjs = require("got-cjs");
489
53
  var import_http_proxy_agent = require("http-proxy-agent");
490
54
  var import_https_proxy_agent = require("https-proxy-agent");
491
- var lockfile = __toESM(require("proper-lockfile"), 1);
492
55
 
493
56
  // src/utils.ts
494
57
  var import_node_os = require("os");
@@ -13470,7 +13033,8 @@ async function genCaddyfile(ctx) {
13470
13033
 
13471
13034
  // src/caddy/config.ts
13472
13035
  var import_node_fs = require("fs");
13473
- var import_promises = require("fs/promises");
13036
+ var import_node_process2 = __toESM(require("process"), 1);
13037
+ var lockfile = __toESM(require("proper-lockfile"), 1);
13474
13038
 
13475
13039
  // src/caddy/constants.ts
13476
13040
  var import_node_os2 = __toESM(require("os"), 1);
@@ -13602,56 +13166,108 @@ var supportList = [
13602
13166
  ];
13603
13167
 
13604
13168
  // src/caddy/config.ts
13605
- function useCaddyConfig() {
13606
- const configContentRef = signal("{}");
13607
- const configJsonRef = computed(() => {
13608
- try {
13609
- return JSON.parse(configContentRef());
13610
- } catch {
13611
- return void 0;
13612
- }
13613
- });
13614
- function setConfigContent() {
13615
- if (!(0, import_node_fs.existsSync)(caddyConfigPath)) {
13616
- (0, import_node_fs.writeFileSync)(caddyConfigPath, "{}");
13617
- }
13618
- try {
13619
- configContentRef((0, import_node_fs.readFileSync)(caddyConfigPath, "utf-8"));
13620
- } catch {
13621
- configContentRef("");
13622
- }
13169
+ function isAlive(pid) {
13170
+ if (pid === void 0)
13171
+ return true;
13172
+ try {
13173
+ import_node_process2.default.kill(pid, 0);
13174
+ return true;
13175
+ } catch {
13176
+ return false;
13623
13177
  }
13624
- if (!(0, import_node_fs.existsSync)(caddyConfigPath)) {
13625
- (0, import_node_fs.writeFileSync)(caddyConfigPath, "{}");
13178
+ }
13179
+ function readConfig() {
13180
+ if (!(0, import_node_fs.existsSync)(caddyConfigPath))
13181
+ return {};
13182
+ let parsed2;
13183
+ try {
13184
+ parsed2 = JSON.parse((0, import_node_fs.readFileSync)(caddyConfigPath, "utf-8"));
13185
+ } catch {
13186
+ return {};
13626
13187
  }
13627
- const watchCaddyConfig = (0, import_node_fs.watch)(caddyConfigPath, () => {
13628
- setConfigContent();
13629
- });
13630
- function writeCaddyConfig(_proxies) {
13631
- const proxies = configJsonRef() || {};
13632
- _proxies.forEach((p) => {
13633
- let base = p.base || "/";
13634
- if (!base.startsWith("/"))
13635
- base = `/${base}`;
13636
- if (base !== "/" && !base.endsWith("/"))
13637
- base = `${base}/`;
13638
- const index = `${p.target}${p.portSuffix}${base}`;
13639
- proxies[index] = { ...p, base };
13640
- });
13641
- const content = JSON.stringify(proxies, null, 2);
13642
- configContentRef(content);
13643
- return (0, import_node_fs.writeFileSync)(caddyConfigPath, content);
13188
+ const alive = {};
13189
+ for (const [key, entry] of Object.entries(parsed2)) {
13190
+ if (isAlive(entry == null ? void 0 : entry.ownerPid))
13191
+ alive[key] = entry;
13644
13192
  }
13645
- async function cleanUp() {
13646
- await (0, import_promises.unlink)(caddyConfigPath).catch(() => {
13647
- });
13648
- configContentRef("{}");
13649
- watchCaddyConfig.close();
13193
+ return alive;
13194
+ }
13195
+ function writeConfig(proxies) {
13196
+ const content = JSON.stringify(proxies, null, 2);
13197
+ const temp = `${caddyConfigPath}.${import_node_process2.default.pid}.tmp`;
13198
+ (0, import_node_fs.writeFileSync)(temp, content);
13199
+ (0, import_node_fs.renameSync)(temp, caddyConfigPath);
13200
+ }
13201
+ async function mutateConfig(lock3, mutate) {
13202
+ const release = await lock3.acquire();
13203
+ try {
13204
+ const proxies = readConfig();
13205
+ mutate(proxies);
13206
+ writeConfig(proxies);
13207
+ return proxies;
13208
+ } finally {
13209
+ release();
13650
13210
  }
13211
+ }
13212
+ function useCaddyConfig(options = {}) {
13213
+ const lock3 = options.lock ?? createFileLock();
13214
+ return {
13215
+ configJsonRef: () => (0, import_node_fs.existsSync)(caddyConfigPath) ? readConfig() : void 0,
13216
+ async writeCaddyConfig(_proxies, key) {
13217
+ await mutateConfig(lock3, (proxies) => {
13218
+ for (const p of _proxies)
13219
+ proxies[routeKey(p, key)] = { ...p, base: normalizeBase(p.base), ownerPid: import_node_process2.default.pid };
13220
+ });
13221
+ },
13222
+ async removeProxy(key) {
13223
+ const proxies = await mutateConfig(lock3, (current) => {
13224
+ for (const route of Object.keys(current)) {
13225
+ if (route.endsWith(`#${key}`))
13226
+ delete current[route];
13227
+ }
13228
+ });
13229
+ if (Object.keys(proxies).length === 0)
13230
+ removeConfigFile();
13231
+ },
13232
+ readProxies: () => readConfig(),
13233
+ async cleanUp() {
13234
+ removeConfigFile();
13235
+ }
13236
+ };
13237
+ }
13238
+ function removeConfigFile() {
13239
+ try {
13240
+ if ((0, import_node_fs.existsSync)(caddyConfigPath))
13241
+ (0, import_node_fs.unlinkSync)(caddyConfigPath);
13242
+ } catch {
13243
+ }
13244
+ }
13245
+ function normalizeBase(base) {
13246
+ let out = base || "/";
13247
+ if (!out.startsWith("/"))
13248
+ out = `/${out}`;
13249
+ if (out !== "/" && !out.endsWith("/"))
13250
+ out = `${out}/`;
13251
+ return out;
13252
+ }
13253
+ function routeKey(proxy, ownerKey) {
13254
+ return `${proxy.target}${proxy.portSuffix}${normalizeBase(proxy.base)}#${ownerKey}`;
13255
+ }
13256
+ function createFileLock() {
13651
13257
  return {
13652
- configJsonRef,
13653
- writeCaddyConfig,
13654
- cleanUp
13258
+ async acquire() {
13259
+ if (!(0, import_node_fs.existsSync)(caddyConfigPath))
13260
+ (0, import_node_fs.writeFileSync)(caddyConfigPath, "{}");
13261
+ const release = await lockfile.lock(caddyConfigPath, {
13262
+ realpath: false,
13263
+ stale: 1e4,
13264
+ retries: { retries: 20, minTimeout: 10, maxTimeout: 100 }
13265
+ });
13266
+ return () => {
13267
+ void release().catch(() => {
13268
+ });
13269
+ };
13270
+ }
13655
13271
  };
13656
13272
  }
13657
13273
 
@@ -13669,43 +13285,56 @@ function isCaddyReloadCancellation(line) {
13669
13285
  var import_node_buffer2 = require("buffer");
13670
13286
  var import_node_events = require("events");
13671
13287
  var import_node_path4 = require("path");
13672
- var import_node_process6 = __toESM(require("process"), 1);
13288
+ var import_node_process7 = __toESM(require("process"), 1);
13673
13289
  var import_node_url = require("url");
13674
13290
 
13675
13291
  // src/privileged/entry.ts
13676
13292
  var import_node_fs2 = require("fs");
13677
13293
  var import_node_path2 = require("path");
13678
- var import_node_process2 = __toESM(require("process"), 1);
13294
+ var import_node_process3 = __toESM(require("process"), 1);
13679
13295
  function resolveHelperEntry(options) {
13680
- const { moduleDir, nodeBin = import_node_process2.default.execPath, exists: exists2 = import_node_fs2.existsSync } = options;
13296
+ const { moduleDir, nodeBin = import_node_process3.default.execPath, exists: exists2 = import_node_fs2.existsSync } = options;
13681
13297
  for (const name of ["privileged-helper.js", "privileged-helper.cjs", "privileged-helper.mjs"]) {
13682
- const candidate = (0, import_node_path2.join)(moduleDir, name);
13683
- if (exists2(candidate))
13298
+ const candidate = findUp(moduleDir, name, exists2);
13299
+ if (candidate)
13684
13300
  return { entry: nodeBin, args: [candidate] };
13685
13301
  }
13686
- const source = (0, import_node_path2.join)(moduleDir, "privileged-helper.ts");
13687
- const tsxCli = (0, import_node_path2.join)(moduleDir, "../node_modules/tsx/dist/cli.mjs");
13688
- if (exists2(source) && exists2(tsxCli))
13302
+ const source = findUp(moduleDir, "privileged-helper.ts", exists2);
13303
+ const tsxCli = findUp(moduleDir, "node_modules/tsx/dist/cli.mjs", exists2);
13304
+ if (source && tsxCli)
13689
13305
  return { entry: nodeBin, args: [tsxCli, source] };
13690
13306
  throw new Error(`privileged helper entry not found in ${moduleDir}. Build the package first.`);
13691
13307
  }
13308
+ function findUp(from, relative, exists2) {
13309
+ let current = from;
13310
+ while (true) {
13311
+ const candidate = (0, import_node_path2.join)(current, relative);
13312
+ if (exists2(candidate))
13313
+ return candidate;
13314
+ const parent = (0, import_node_path2.dirname)(current);
13315
+ if (parent === current)
13316
+ return void 0;
13317
+ current = parent;
13318
+ }
13319
+ }
13692
13320
 
13693
13321
  // src/privileged/session.ts
13694
13322
  var import_node_buffer = require("buffer");
13695
13323
  var import_node_fs3 = require("fs");
13696
- var import_promises2 = require("fs/promises");
13324
+ var import_promises = require("fs/promises");
13697
13325
  var import_node_os4 = require("os");
13698
13326
  var import_node_path3 = require("path");
13327
+ var lockfile2 = __toESM(require("proper-lockfile"), 1);
13699
13328
 
13700
13329
  // src/privileged/launch.ts
13701
13330
  var import_node_child_process2 = require("child_process");
13702
13331
  var import_node_crypto = require("crypto");
13703
13332
  var import_node_os3 = require("os");
13704
- var import_node_process5 = __toESM(require("process"), 1);
13333
+ var import_node_process6 = __toESM(require("process"), 1);
13705
13334
 
13706
13335
  // src/privileged/client.ts
13707
13336
  var import_node_net = require("net");
13708
- var import_node_process3 = __toESM(require("process"), 1);
13337
+ var import_node_process4 = __toESM(require("process"), 1);
13709
13338
 
13710
13339
  // src/privileged/protocol.ts
13711
13340
  function serializeMessage(message) {
@@ -13768,7 +13397,7 @@ var FORWARDED_ENV_KEYS = [
13768
13397
  "NO_PROXY",
13769
13398
  "no_proxy"
13770
13399
  ];
13771
- function collectForwardedEnv(source = import_node_process3.default.env) {
13400
+ function collectForwardedEnv(source = import_node_process4.default.env) {
13772
13401
  const result = {};
13773
13402
  for (const key of FORWARDED_ENV_KEYS) {
13774
13403
  const value2 = source[key];
@@ -13945,7 +13574,7 @@ function createClient(socket, initialBuffer, callTimeoutMs) {
13945
13574
 
13946
13575
  // src/privileged/windows-elevation.ts
13947
13576
  var import_node_child_process = require("child_process");
13948
- var import_node_process4 = __toESM(require("process"), 1);
13577
+ var import_node_process5 = __toESM(require("process"), 1);
13949
13578
  function quotePowerShell(value2) {
13950
13579
  return `'${value2.replace(/'/g, "''")}'`;
13951
13580
  }
@@ -13987,18 +13616,42 @@ function spawnElevatedOnWindows(options) {
13987
13616
  function createHelperToken() {
13988
13617
  return (0, import_node_crypto.randomBytes)(24).toString("hex");
13989
13618
  }
13990
- function authenticateSudo(sudoCommand = "sudo") {
13619
+ function describePasswordReason(target, https) {
13620
+ const port = https ? "443" : "80";
13621
+ return [
13622
+ `reverse proxy needs administrator permission for ${target}`,
13623
+ ` \xB7 bind port ${port}${https ? ` for https://${target}` : ""}`,
13624
+ ` \xB7 add ${target} to the hosts file`,
13625
+ "",
13626
+ "This is the only prompt; the rest of the dev server keeps running as you.",
13627
+ "Press Ctrl+C at the prompt to skip the proxy and keep the dev server."
13628
+ ];
13629
+ }
13630
+ function authenticateSudo(sudoCommand = "sudo", options = {}) {
13991
13631
  if ((0, import_node_os3.platform)() === "win32")
13992
13632
  return { ok: true };
13993
13633
  if ((0, import_node_child_process2.spawnSync)(sudoCommand, ["-n", "true"], { stdio: "ignore" }).status === 0)
13994
13634
  return { ok: true };
13635
+ if (options.target) {
13636
+ for (const line of describePasswordReason(options.target, options.https ?? false))
13637
+ import_node_process6.default.stderr.write(`${line}
13638
+ `);
13639
+ import_node_process6.default.stderr.write("\n");
13640
+ }
13995
13641
  if ((0, import_node_child_process2.spawnSync)(sudoCommand, ["-v"], { stdio: "inherit" }).status === 0)
13996
13642
  return { ok: true };
13997
13643
  return {
13998
13644
  ok: false,
13645
+ denied: true,
13999
13646
  message: "administrator permission is required to edit the hosts file and bind ports 80/443"
14000
13647
  };
14001
13648
  }
13649
+ var PrivilegeDeniedError = class extends Error {
13650
+ constructor(message) {
13651
+ super(message);
13652
+ this.name = "PrivilegeDeniedError";
13653
+ }
13654
+ };
14002
13655
  async function startPrivilegedHelper(options) {
14003
13656
  var _a4, _b3;
14004
13657
  const {
@@ -14009,14 +13662,16 @@ async function startPrivilegedHelper(options) {
14009
13662
  sudoCommand = "sudo",
14010
13663
  skipAuth = false,
14011
13664
  direct = false,
14012
- env: env2 = import_node_process5.default.env,
13665
+ env: env2 = import_node_process6.default.env,
14013
13666
  log,
14014
13667
  connectTimeoutMs = 12e4
14015
13668
  } = options;
14016
13669
  if (!skipAuth && !direct) {
14017
- const auth = authenticateSudo(sudoCommand);
14018
- if (!auth.ok)
14019
- throw new Error(auth.message);
13670
+ const auth = authenticateSudo(sudoCommand, options.reason);
13671
+ if (!auth.ok) {
13672
+ const message = auth.message ?? "administrator permission is required";
13673
+ throw auth.denied ? new PrivilegeDeniedError(message) : new Error(message);
13674
+ }
14020
13675
  }
14021
13676
  const forwarded = collectForwardedEnv(env2);
14022
13677
  const forwardedArgs = Object.entries(forwarded).map(([key, value2]) => `${key}=${value2}`);
@@ -14026,8 +13681,8 @@ async function startPrivilegedHelper(options) {
14026
13681
  socketPath,
14027
13682
  "--token",
14028
13683
  token,
14029
- ...typeof import_node_process5.default.getuid === "function" ? ["--owner-uid", String(import_node_process5.default.getuid())] : [],
14030
- ...typeof import_node_process5.default.getgid === "function" ? ["--owner-gid", String(import_node_process5.default.getgid())] : [],
13684
+ ...typeof import_node_process6.default.getuid === "function" ? ["--owner-uid", String(import_node_process6.default.getuid())] : [],
13685
+ ...typeof import_node_process6.default.getgid === "function" ? ["--owner-gid", String(import_node_process6.default.getgid())] : [],
14031
13686
  ...options.caddyStoragePath ? ["--caddy-storage", options.caddyStoragePath] : [],
14032
13687
  "--caddy",
14033
13688
  options.caddyBin,
@@ -14036,7 +13691,7 @@ async function startPrivilegedHelper(options) {
14036
13691
  ];
14037
13692
  let child;
14038
13693
  if (!direct && (0, import_node_os3.platform)() === "win32") {
14039
- await spawnElevatedOnWindows({ file: helperEntry, args: childArgv, cwd: import_node_process5.default.cwd() });
13694
+ await spawnElevatedOnWindows({ file: helperEntry, args: childArgv, cwd: import_node_process6.default.cwd() });
14040
13695
  } else {
14041
13696
  const command = direct ? helperEntry : sudoCommand;
14042
13697
  const spawnArgs = direct ? childArgv : ["-n", "env", ...forwardedArgs, helperEntry, ...childArgv];
@@ -14093,21 +13748,34 @@ function sessionSocketPath(runtimeDir) {
14093
13748
  }
14094
13749
  async function openHelperSession(scope2) {
14095
13750
  const socketPath = sessionSocketPath(scope2.runtimeDir);
14096
- if ((0, import_node_fs3.existsSync)(socketPath) || (0, import_node_os4.platform)() === "win32") {
14097
- const token2 = await readToken(scope2.runtimeDir);
14098
- if (token2) {
14099
- const reused = await connectExistingHelper(socketPath, token2);
14100
- if (reused) {
14101
- return {
14102
- client: reused,
14103
- reused: true,
14104
- close: async () => {
14105
- await reused.close();
14106
- }
14107
- };
14108
- }
14109
- }
13751
+ const release = await acquireStartLock(scope2.runtimeDir);
13752
+ try {
13753
+ const reused = await tryReuse(socketPath, scope2);
13754
+ if (reused)
13755
+ return reused;
13756
+ return await startNew(socketPath, scope2);
13757
+ } finally {
13758
+ release();
14110
13759
  }
13760
+ }
13761
+ async function tryReuse(socketPath, scope2) {
13762
+ if (!(0, import_node_fs3.existsSync)(socketPath) && (0, import_node_os4.platform)() !== "win32")
13763
+ return void 0;
13764
+ const token = await readToken(scope2.runtimeDir);
13765
+ if (!token)
13766
+ return void 0;
13767
+ const reused = await connectExistingHelper(socketPath, token);
13768
+ if (!reused)
13769
+ return void 0;
13770
+ return {
13771
+ client: reused,
13772
+ reused: true,
13773
+ close: async () => {
13774
+ await reused.close();
13775
+ }
13776
+ };
13777
+ }
13778
+ async function startNew(socketPath, scope2) {
14111
13779
  const token = createHelperToken();
14112
13780
  const started = await startPrivilegedHelper({
14113
13781
  socketPath,
@@ -14121,6 +13789,7 @@ async function openHelperSession(scope2) {
14121
13789
  caddyStoragePath: scope2.caddyStoragePath,
14122
13790
  caddyBin: scope2.caddyBin,
14123
13791
  caddyConfigPath: scope2.caddyConfigPath,
13792
+ reason: scope2.reason,
14124
13793
  log: scope2.log
14125
13794
  });
14126
13795
  await writeToken(scope2.runtimeDir, token);
@@ -14132,9 +13801,25 @@ async function openHelperSession(scope2) {
14132
13801
  }
14133
13802
  };
14134
13803
  }
13804
+ async function acquireStartLock(runtimeDir) {
13805
+ const lockPath = (0, import_node_path3.join)(runtimeDir, "helper.start.lock");
13806
+ try {
13807
+ await (0, import_promises.writeFile)(lockPath, "", { flag: "a" });
13808
+ } catch {
13809
+ }
13810
+ const release = await lockfile2.lock(lockPath, {
13811
+ realpath: false,
13812
+ stale: 3e4,
13813
+ retries: { retries: 100, minTimeout: 50, maxTimeout: 200 }
13814
+ });
13815
+ return () => {
13816
+ void release().catch(() => {
13817
+ });
13818
+ };
13819
+ }
14135
13820
  async function readToken(runtimeDir) {
14136
13821
  try {
14137
- const content = await (0, import_promises2.readFile)(tokenPath(runtimeDir), "utf8");
13822
+ const content = await (0, import_promises.readFile)(tokenPath(runtimeDir), "utf8");
14138
13823
  const token = content.trim();
14139
13824
  return token === "" ? void 0 : token;
14140
13825
  } catch {
@@ -14143,7 +13828,7 @@ async function readToken(runtimeDir) {
14143
13828
  }
14144
13829
  async function writeToken(runtimeDir, token) {
14145
13830
  try {
14146
- await (0, import_promises2.writeFile)(tokenPath(runtimeDir), token, { mode: 384 });
13831
+ await (0, import_promises.writeFile)(tokenPath(runtimeDir), token, { mode: 384 });
14147
13832
  } catch {
14148
13833
  }
14149
13834
  }
@@ -14191,7 +13876,7 @@ var HelperCaddyProcess = class extends import_node_events.EventEmitter {
14191
13876
  }
14192
13877
  };
14193
13878
  function caddyStoragePath() {
14194
- return import_node_process6.default.platform === "win32" ? (0, import_node_path4.join)(import_node_process6.default.env.AppData ?? "", "Caddy") : (0, import_node_path4.join)(import_node_process6.default.env.HOME ?? "", "Library/Application Support/Caddy");
13879
+ return import_node_process7.default.platform === "win32" ? (0, import_node_path4.join)(import_node_process7.default.env.AppData ?? "", "Caddy") : (0, import_node_path4.join)(import_node_process7.default.env.HOME ?? "", "Library/Application Support/Caddy");
14195
13880
  }
14196
13881
  function openPrivilegedSession(runtimeDir, options) {
14197
13882
  const env2 = resolvePrivilegedEnv();
@@ -14207,6 +13892,7 @@ function openPrivilegedSession(runtimeDir, options) {
14207
13892
  // execute a path supplied over the socket.
14208
13893
  caddyBin: options.caddyBin,
14209
13894
  caddyConfigPath: options.caddyConfigPath,
13895
+ reason: options.reason,
14210
13896
  log: options.log
14211
13897
  });
14212
13898
  }
@@ -14340,15 +14026,15 @@ async function download() {
14340
14026
  const file = (0, import_node_fs4.createWriteStream)(caddyPath);
14341
14027
  let _platform = (0, import_node_os5.platform)().toString();
14342
14028
  _platform === "win32" && (_platform = "windows");
14343
- let _arch = import_node_process7.default.arch.toString();
14029
+ let _arch = import_node_process8.default.arch.toString();
14344
14030
  _arch === "x64" && (_arch = "amd64");
14345
14031
  const support = supportList.find((item) => item.platform === _platform && item.arch === _arch);
14346
14032
  if (!support)
14347
14033
  return reject2(new Error("not support"));
14348
14034
  const dowmloadLink = `https://caddyserver.com/api/download?os=${support.platform}&arch=${support.arch}&p=github.com%2Fcaddyserver%2Fforwardproxy`;
14349
14035
  (0, import_node_fs4.existsSync)(caddyPath) && (0, import_node_fs4.unlinkSync)(caddyPath);
14350
- const httpProxy = import_node_process7.default.env.HTTP_PROXY || import_node_process7.default.env.http_proxy;
14351
- const httpsProxy = import_node_process7.default.env.HTTPS_PROXY || import_node_process7.default.env.https_proxy;
14036
+ const httpProxy = import_node_process8.default.env.HTTP_PROXY || import_node_process8.default.env.http_proxy;
14037
+ const httpsProxy = import_node_process8.default.env.HTTPS_PROXY || import_node_process8.default.env.https_proxy;
14352
14038
  const httpAgent = httpProxy ? new import_http_proxy_agent.HttpProxyAgent(httpProxy) : void 0;
14353
14039
  const httpsAgent = httpsProxy ? new import_https_proxy_agent.HttpsProxyAgent(httpsProxy) : void 0;
14354
14040
  const chmodCaddyOnce = once(() => {
@@ -14364,7 +14050,7 @@ async function download() {
14364
14050
  chmodCaddyOnce();
14365
14051
  }).pipe(file).on("finish", () => {
14366
14052
  logProgressOver();
14367
- if (import_node_process7.default.platform === "win32")
14053
+ if (import_node_process8.default.platform === "win32")
14368
14054
  return resolve2(caddyPath);
14369
14055
  (0, import_node_fs4.chmodSync)(caddyPath, 493);
14370
14056
  resolve2(caddyPath);
@@ -14407,43 +14093,35 @@ function splitHostPort(addr) {
14407
14093
  return { host: addr.slice(0, lastColon), port: addr.slice(lastColon + 1) };
14408
14094
  }
14409
14095
  var defaultDependencies = {
14410
- openSession: (runtimeDir) => openPrivilegedSession(runtimeDir, {
14096
+ openSession: (runtimeDir, reason) => openPrivilegedSession(runtimeDir, {
14411
14097
  log: (message) => consola.debug(message),
14412
14098
  // Both paths are fixed here, before any socket traffic: the privileged
14413
14099
  // helper must never execute something named in a request.
14414
14100
  caddyBin: caddyPath,
14415
- caddyConfigPath: caddyFilePath
14416
- })
14101
+ caddyConfigPath: caddyFilePath,
14102
+ reason
14103
+ }),
14104
+ config: () => getCaddyConfig()
14417
14105
  };
14418
14106
  var CaddyInstant = class {
14419
14107
  constructor(deps = {}) {
14420
14108
  this.inited = false;
14421
14109
  this.stoped = false;
14422
- /** has locked when start */
14423
- this.locked = false;
14424
14110
  this._stopEffects = [];
14111
+ /** Identifies this instance's routes in the shared config. */
14112
+ this.proxyKey = `${import_node_process8.default.pid}-${Math.random().toString(36).slice(2, 8)}`;
14425
14113
  this.deps = { ...defaultDependencies, ...deps };
14426
- this.locked = this.checkLock();
14427
- }
14428
- checkLock() {
14429
- if (!(0, import_node_fs4.existsSync)(caddyLockFilePath))
14430
- (0, import_node_fs4.writeFileSync)(caddyLockFilePath, "");
14431
- try {
14432
- return lockfile.checkSync(caddyLockFilePath);
14433
- } catch {
14434
- return false;
14435
- }
14436
14114
  }
14437
14115
  /**
14438
14116
  * Connects to the privileged helper, starting it once if needed. It is
14439
14117
  * reused across instances so a second dev server does not ask for a
14440
14118
  * password again.
14441
14119
  */
14442
- async session() {
14120
+ async session(reason) {
14443
14121
  if (this._session && !this._session.client.connected)
14444
14122
  this._session = void 0;
14445
14123
  if (!this._session)
14446
- this._session = await this.deps.openSession(TEMP_DIR);
14124
+ this._session = await this.deps.openSession(TEMP_DIR, reason);
14447
14125
  return this._session;
14448
14126
  }
14449
14127
  async getCaddyfile() {
@@ -14451,20 +14129,20 @@ var CaddyInstant = class {
14451
14129
  this.caddyfile = "";
14452
14130
  return "";
14453
14131
  }
14454
- this.caddyfile = await (0, import_promises3.readFile)(caddyFilePath, "utf-8");
14132
+ this.caddyfile = await (0, import_promises2.readFile)(caddyFilePath, "utf-8");
14455
14133
  return this.caddyfile;
14456
14134
  }
14457
14135
  get caddyRoot() {
14458
14136
  return (0, import_node_path5.join)(
14459
- import_node_process7.default.platform === "win32" ? `${import_node_process7.default.env.AppData}/Caddy` : `${import_node_process7.default.env.HOME}/Library/Application Support/Caddy`,
14137
+ import_node_process8.default.platform === "win32" ? `${import_node_process8.default.env.AppData}/Caddy` : `${import_node_process8.default.env.HOME}/Library/Application Support/Caddy`,
14460
14138
  "./pki/authorities/local"
14461
14139
  );
14462
14140
  }
14463
14141
  async writeCaddyfile() {
14464
- return await (0, import_promises3.writeFile)(caddyFilePath, this.caddyfile || "");
14142
+ return await (0, import_promises2.writeFile)(caddyFilePath, this.caddyfile || "");
14465
14143
  }
14466
14144
  async deleteCaddyfile() {
14467
- return await (0, import_promises3.unlink)(caddyFilePath);
14145
+ return await (0, import_promises2.unlink)(caddyFilePath);
14468
14146
  }
14469
14147
  async init() {
14470
14148
  await download();
@@ -14502,9 +14180,15 @@ Run \`${caddyPath} trust\` manually if the browser warns about the certificate.`
14502
14180
  if (!health.healthy)
14503
14181
  throw new Error(formatTlsHealthFailure(targetHost, health));
14504
14182
  }
14183
+ /**
14184
+ * Regenerates the Caddyfile from the config on disk.
14185
+ *
14186
+ * Reading the file rather than a cached view matters here: another project
14187
+ * may have added its route since this instance last looked.
14188
+ */
14505
14189
  async updateCaddyfile() {
14506
- const { configJsonRef } = getCaddyConfig();
14507
- const proxies = Object.values(configJsonRef() || {});
14190
+ const { readProxies } = this.deps.config();
14191
+ const proxies = Object.values(readProxies());
14508
14192
  const ctx = validateTemplateContext({
14509
14193
  caddy_root: this.caddyRoot,
14510
14194
  proxies
@@ -14548,12 +14232,12 @@ Run \`${caddyPath} trust\` manually if the browser warns about the certificate.`
14548
14232
  this._target = target;
14549
14233
  if (!this.inited)
14550
14234
  await this.init();
14551
- const session = await this.session();
14552
14235
  const sourceHost = splitHostPort(source).host;
14553
14236
  const targetHost = splitHostPort(target).host;
14237
+ const session = await this.session({ target: targetHost, https });
14554
14238
  await session.client.call("hosts.add", { ip: sourceHost, host: targetHost });
14555
14239
  consola.success("update host success\n");
14556
- const normalizeBase = (b) => {
14240
+ const normalizeBase2 = (b) => {
14557
14241
  let out = b || "/";
14558
14242
  if (!out.startsWith("/"))
14559
14243
  out = `/${out}`;
@@ -14561,7 +14245,7 @@ Run \`${caddyPath} trust\` manually if the browser warns about the certificate.`
14561
14245
  out = `${out}/`;
14562
14246
  return out;
14563
14247
  };
14564
- const baseNormalized = normalizeBase(base);
14248
+ const baseNormalized = normalizeBase2(base);
14565
14249
  const proxies = [
14566
14250
  {
14567
14251
  target: targetHost,
@@ -14572,27 +14256,12 @@ Run \`${caddyPath} trust\` manually if the browser warns about the certificate.`
14572
14256
  healthCheck
14573
14257
  }
14574
14258
  ];
14575
- const { writeCaddyConfig } = getCaddyConfig();
14576
- writeCaddyConfig(proxies);
14259
+ const { writeCaddyConfig } = this.deps.config();
14260
+ await writeCaddyConfig(proxies, this.proxyKey);
14577
14261
  await this.updateCaddyfile();
14578
- let skipInitialCaddyfileEffect = true;
14579
- this._stopEffects.push(
14580
- effect(() => {
14581
- getCaddyConfig().configJsonRef();
14582
- if (skipInitialCaddyfileEffect) {
14583
- skipInitialCaddyfileEffect = false;
14584
- return;
14585
- }
14586
- void this.updateCaddyfile();
14587
- })
14588
- );
14589
- if (!(0, import_node_fs4.existsSync)(caddyLockFilePath))
14590
- (0, import_node_fs4.writeFileSync)(caddyLockFilePath, "");
14591
- if (!this.locked) {
14592
- await session.client.call("port.free", { port: 443 });
14593
- if (import_node_process7.default.platform === "win32" || !https)
14594
- await session.client.call("port.free", { port: 80 });
14595
- }
14262
+ await session.client.call("port.free", { port: 443 });
14263
+ if (import_node_process8.default.platform === "win32" || !https)
14264
+ await session.client.call("port.free", { port: 80 });
14596
14265
  return new Promise((resolve2, reject2) => {
14597
14266
  let startupCheckStarted = false;
14598
14267
  const resolveWhenReady = async () => {
@@ -14606,106 +14275,89 @@ Run \`${caddyPath} trust\` manually if the browser warns about the certificate.`
14606
14275
  }
14607
14276
  resolve2();
14608
14277
  } catch (error) {
14609
- if (!this.locked)
14610
- await this.baseCleanup(restore);
14278
+ await this.baseCleanup(restore);
14611
14279
  reject2(error);
14612
14280
  }
14613
14281
  };
14614
14282
  const setupCleanup = () => {
14615
- import_node_process7.default.on("SIGINT", async () => {
14283
+ import_node_process8.default.on("SIGINT", async () => {
14616
14284
  if (this.stoped)
14617
14285
  return;
14618
- import_node_process7.default.stdin.resume();
14286
+ import_node_process8.default.stdin.resume();
14619
14287
  try {
14620
14288
  await this.baseCleanup(restore);
14621
14289
  } finally {
14622
14290
  this.stoped = true;
14623
- import_node_process7.default.nextTick(() => {
14624
- import_node_process7.default.exit();
14291
+ import_node_process8.default.nextTick(() => {
14292
+ import_node_process8.default.exit();
14625
14293
  });
14626
14294
  }
14627
14295
  });
14628
- const originalExit = import_node_process7.default.exit.bind(import_node_process7.default);
14629
- import_node_process7.default.exit = async (code) => {
14296
+ const originalExit = import_node_process8.default.exit.bind(import_node_process8.default);
14297
+ import_node_process8.default.exit = async (code) => {
14630
14298
  if (this.stoped)
14631
14299
  return originalExit(code);
14632
- import_node_process7.default.stdin.resume();
14300
+ import_node_process8.default.stdin.resume();
14633
14301
  try {
14634
14302
  await this.baseCleanup();
14635
14303
  } finally {
14636
14304
  this.stoped = true;
14637
- import_node_process7.default.nextTick(() => {
14305
+ import_node_process8.default.nextTick(() => {
14638
14306
  originalExit(code);
14639
14307
  });
14640
14308
  }
14641
14309
  };
14642
14310
  };
14643
- if (!this.locked) {
14644
- lockfile.lockSync(caddyLockFilePath);
14645
- setupCleanup();
14646
- void (async () => {
14647
- try {
14648
- const child = new HelperCaddyProcess(session.client);
14649
- this._caddyChild = child;
14650
- await session.client.call("caddy.start");
14651
- child.on("exit", (code) => {
14652
- if (code !== null && code !== 0)
14653
- reject2(new Error(`Caddy exited with code ${code}`));
14654
- });
14655
- child.stderr.on("data", async (data) => {
14656
- const lines = data.toString().split("\n").map((line) => line.trim());
14657
- for (const line of lines) {
14658
- showCaddyLog && line && console.info(line);
14659
- if (isCaddyReloadCancellation(line)) {
14660
- consola.info("Caddy restarted before TLS issuance completed; retrying.\n");
14661
- continue;
14662
- }
14663
- try {
14664
- if (line.includes("Error:") || line && JSON.parse(line).level === "error") {
14665
- if (line.includes("parsing caddyfile tokens")) {
14666
- consola.error("Caddyfile syntax error, please contact the author:\n", `${this.caddyfile}
14311
+ setupCleanup();
14312
+ void (async () => {
14313
+ try {
14314
+ const child = new HelperCaddyProcess(session.client);
14315
+ this._caddyChild = child;
14316
+ await session.client.call("caddy.start");
14317
+ child.on("exit", (code) => {
14318
+ if (code !== null && code !== 0)
14319
+ reject2(new Error(`Caddy exited with code ${code}`));
14320
+ });
14321
+ child.stderr.on("data", async (data) => {
14322
+ const lines = data.toString().split("\n").map((line) => line.trim());
14323
+ for (const line of lines) {
14324
+ showCaddyLog && line && console.info(line);
14325
+ if (isCaddyReloadCancellation(line)) {
14326
+ consola.info("Caddy restarted before TLS issuance completed; retrying.\n");
14327
+ continue;
14328
+ }
14329
+ try {
14330
+ if (line.includes("Error:") || line && JSON.parse(line).level === "error") {
14331
+ if (line.includes("parsing caddyfile tokens")) {
14332
+ consola.error("Caddyfile syntax error, please contact the author:\n", `${this.caddyfile}
14667
14333
 
14668
14334
  ${line}
14669
14335
  `);
14670
- await this.baseCleanup();
14671
- import_node_process7.default.exit();
14672
- } else {
14673
- consola.error(`${line}
14336
+ await this.baseCleanup();
14337
+ import_node_process8.default.exit();
14338
+ } else {
14339
+ consola.error(`${line}
14674
14340
  `);
14675
- return reject2(line);
14676
- }
14341
+ return reject2(line);
14677
14342
  }
14678
- } catch {
14679
14343
  }
14680
- if (line.includes("config file changed"))
14681
- consola.success("Detect added a new reverse proxy config, restarted.\n");
14682
- if (line.includes("caddy proxying") || line.includes("serving initial"))
14683
- void resolveWhenReady();
14344
+ } catch {
14684
14345
  }
14685
- });
14686
- child.stdout.on("data", (data) => {
14687
- consola.info(data.toString());
14688
- void resolveWhenReady();
14689
- });
14690
- } catch (error) {
14691
- if (!this.locked)
14692
- await this.baseCleanup(restore);
14693
- reject2(error);
14694
- }
14695
- })();
14696
- } else {
14697
- consola.info("Caddy is running in another process.");
14698
- void (async () => {
14699
- try {
14700
- if (https)
14701
- await this.ensureTlsReady(targetHost);
14702
- setupCleanup();
14703
- resolve2();
14704
- } catch (error) {
14705
- reject2(error);
14706
- }
14707
- })();
14708
- }
14346
+ if (line.includes("config file changed"))
14347
+ consola.success("Detect added a new reverse proxy config, restarted.\n");
14348
+ if (line.includes("caddy proxying") || line.includes("serving initial"))
14349
+ void resolveWhenReady();
14350
+ }
14351
+ });
14352
+ child.stdout.on("data", (data) => {
14353
+ consola.info(data.toString());
14354
+ void resolveWhenReady();
14355
+ });
14356
+ } catch (error) {
14357
+ await this.baseCleanup(restore);
14358
+ reject2(error);
14359
+ }
14360
+ })();
14709
14361
  });
14710
14362
  }
14711
14363
  async baseCleanup(restore = true) {
@@ -14729,18 +14381,9 @@ ${line}
14729
14381
  consola.fail("Restore host failed.\n");
14730
14382
  }
14731
14383
  }
14732
- if (!this.locked && !this.stoped) {
14733
- await this.stopCaddy();
14384
+ if (!this.stoped) {
14734
14385
  try {
14735
- await lockfile.unlock(caddyLockFilePath).catch(() => {
14736
- });
14737
- await (0, import_promises3.unlink)(caddyFilePath).catch(() => {
14738
- });
14739
- await (0, import_promises3.unlink)(caddyLockFilePath).catch(() => {
14740
- });
14741
- if (caddyConfig) {
14742
- await caddyConfig.cleanUp();
14743
- }
14386
+ await this.deps.config().removeProxy(this.proxyKey);
14744
14387
  } catch (e) {
14745
14388
  consola.error(e);
14746
14389
  }
@@ -14885,9 +14528,18 @@ var hmrSseBridgeClientScript = `
14885
14528
  })();
14886
14529
  `;
14887
14530
 
14531
+ // src/privilege-state.ts
14532
+ var denied = false;
14533
+ function markPrivilegeDenied() {
14534
+ denied = true;
14535
+ }
14536
+ function isPrivilegeDenied() {
14537
+ return denied;
14538
+ }
14539
+
14888
14540
  // src/index.ts
14889
14541
  var caddy;
14890
- var cwd = import_node_process8.default.cwd();
14542
+ var cwd = import_node_process9.default.cwd();
14891
14543
  function colorUrl(url2) {
14892
14544
  return import_picocolors2.default.green(url2.replace(/:(\d+)\//, (_, port) => `:${import_picocolors2.default.bold(port)}/`));
14893
14545
  }
@@ -14922,16 +14574,27 @@ async function printForwardProxy() {
14922
14574
  }
14923
14575
  var vitePrintUrls = once((options, source, target, base = "/", _printUrls) => {
14924
14576
  _printUrls == null ? void 0 : _printUrls();
14577
+ if (isPrivilegeDenied())
14578
+ return;
14925
14579
  if (caddy)
14926
14580
  return;
14927
- caddy = new CaddyInstant();
14928
- caddy.run(source, target, {
14581
+ const instance = new CaddyInstant();
14582
+ caddy = instance;
14583
+ instance.run(source, target, {
14929
14584
  base,
14930
14585
  ...options
14931
14586
  }).then(async () => {
14932
14587
  await printForwardProxy();
14933
14588
  consola.success(` ${import_picocolors2.default.green("\u279C")} ${import_picocolors2.default.bold("run caddy reverse proxy success")}: ${colorUrl(`${options.https ? "https" : "http"}://${target}${base}`)}`);
14934
14589
  }).catch((e) => {
14590
+ if (caddy === instance)
14591
+ caddy = void 0;
14592
+ if (e instanceof PrivilegeDeniedError) {
14593
+ markPrivilegeDenied();
14594
+ consola.warn("reverse proxy skipped: administrator permission was not granted.");
14595
+ consola.info("Restart the dev server to enable it again.");
14596
+ return;
14597
+ }
14935
14598
  throw e;
14936
14599
  });
14937
14600
  });
@@ -14944,7 +14607,7 @@ var nuxt_default = (0, import_kit.defineNuxtModule)({
14944
14607
  configKey: "unpluginHttpsReverseProxy"
14945
14608
  },
14946
14609
  setup(options, _nuxt) {
14947
- if (import_node_process9.default.env.NODE_ENV !== "development")
14610
+ if (import_node_process10.default.env.NODE_ENV !== "development")
14948
14611
  return;
14949
14612
  const {
14950
14613
  enable = true,