unplugin-https-reverse-proxy 1.0.0-beta.9 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -3,8 +3,8 @@ import {
3
3
  unplugin,
4
4
  unpluginFactory,
5
5
  vitePrintUrls
6
- } from "./chunk-ZSHTX2B6.js";
7
- import "./chunk-RUJE3YFB.js";
6
+ } from "./chunk-SO2FMQ2Q.js";
7
+ import "./chunk-2P7SUCQ3.js";
8
8
  export {
9
9
  src_default as default,
10
10
  unplugin,
package/dist/nuxt.cjs CHANGED
@@ -3,22 +3,8 @@ var __create = Object.create;
3
3
  var __defProp = Object.defineProperty;
4
4
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
5
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getOwnPropSymbols = Object.getOwnPropertySymbols;
7
6
  var __getProtoOf = Object.getPrototypeOf;
8
7
  var __hasOwnProp = Object.prototype.hasOwnProperty;
9
- var __propIsEnum = Object.prototype.propertyIsEnumerable;
10
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
11
- var __spreadValues = (a, b) => {
12
- for (var prop in b || (b = {}))
13
- if (__hasOwnProp.call(b, prop))
14
- __defNormalProp(a, prop, b[prop]);
15
- if (__getOwnPropSymbols)
16
- for (var prop of __getOwnPropSymbols(b)) {
17
- if (__propIsEnum.call(b, prop))
18
- __defNormalProp(a, prop, b[prop]);
19
- }
20
- return a;
21
- };
22
8
  var __export = (target, all) => {
23
9
  for (var name in all)
24
10
  __defProp(target, name, { get: all[name], enumerable: true });
@@ -49,14 +35,41 @@ __export(nuxt_exports, {
49
35
  module.exports = __toCommonJS(nuxt_exports);
50
36
  var import_node_process6 = __toESM(require("process"), 1);
51
37
  var import_kit = require("@nuxt/kit");
52
- var import_schema = require("@nuxt/schema");
38
+
39
+ // src/index.ts
40
+ var import_node_process5 = __toESM(require("process"), 1);
41
+ var import_console_table_printer = require("console-table-printer");
42
+ var import_picocolors2 = __toESM(require("picocolors"), 1);
43
+ var import_unplugin = require("unplugin");
44
+
45
+ // src/caddy/index.ts
46
+ var import_node_child_process4 = require("child_process");
47
+ var import_node_fs2 = require("fs");
48
+ var import_promises2 = require("fs/promises");
49
+ var import_node_os3 = require("os");
50
+ var import_node_path3 = require("path");
51
+ var import_node_process4 = __toESM(require("process"), 1);
52
+ var import_got_cjs = require("got-cjs");
53
+ var import_http_proxy_agent = require("http-proxy-agent");
54
+ var import_https_proxy_agent = require("https-proxy-agent");
55
+ var lockfile = __toESM(require("proper-lockfile"), 1);
56
+
57
+ // src/host/index.ts
58
+ var import_node_child_process2 = require("child_process");
59
+ var import_node_fs = require("fs");
60
+ var import_node_process2 = __toESM(require("process"), 1);
61
+ var import_node_util = require("util");
62
+ var import_hostile = __toESM(require("hostile"), 1);
53
63
 
54
64
  // src/utils.ts
55
- var import_node_process = __toESM(require("process"), 1);
56
- var import_node_path = __toESM(require("path"), 1);
57
- var import_promises = require("fs/promises");
58
65
  var import_node_child_process = require("child_process");
66
+ var import_promises = require("fs/promises");
67
+ var import_node_os = require("os");
68
+ var import_node_path = __toESM(require("path"), 1);
69
+ var import_node_process = __toESM(require("process"), 1);
59
70
  var import_consola = require("consola");
71
+ var import_picocolors = __toESM(require("picocolors"), 1);
72
+ var import_qrcode_terminal = __toESM(require("qrcode-terminal"), 1);
60
73
  var consola = (0, import_consola.createConsola)({
61
74
  level: 3
62
75
  }).withTag("reverse-proxy");
@@ -82,47 +95,38 @@ function isAdmin() {
82
95
  try {
83
96
  (0, import_node_child_process.execSync)("net session", { stdio: "ignore" });
84
97
  return true;
85
- } catch (e) {
98
+ } catch {
86
99
  return false;
87
100
  }
88
101
  } else {
89
- return import_node_process.default.getuid && import_node_process.default.getuid() === 0;
102
+ return !!(import_node_process.default.getuid && import_node_process.default.getuid() === 0);
90
103
  }
91
104
  }
92
-
93
- // src/index.ts
94
- var import_node_process5 = __toESM(require("process"), 1);
95
- var import_unplugin = require("unplugin");
96
- var import_picocolors = __toESM(require("picocolors"), 1);
97
-
98
- // src/caddy/index.ts
99
- var import_node_os2 = require("os");
100
- var import_node_process4 = __toESM(require("process"), 1);
101
- var import_node_fs2 = require("fs");
102
- var import_node_child_process3 = require("child_process");
103
- var import_got_cjs = require("got-cjs");
104
- var import_http_proxy_agent = require("http-proxy-agent");
105
- var import_https_proxy_agent = require("https-proxy-agent");
106
- var import_kill_port = __toESM(require("kill-port"), 1);
105
+ function getIpv4List() {
106
+ const interfaces = (0, import_node_os.networkInterfaces)();
107
+ return Object.values(interfaces).flatMap((nInterface) => nInterface ?? []).filter(
108
+ (detail) => detail.address && (detail.family === "IPv4" || detail.family === 4)
109
+ ).filter((detail) => detail.family === "IPv4" && !detail.internal).map((detail) => detail.address);
110
+ }
111
+ async function generateQrcode(input) {
112
+ return new Promise((resolve) => {
113
+ import_qrcode_terminal.default.generate(input, { small: true }, (code) => {
114
+ resolve(code.split("\n").map((line) => import_picocolors.default.bgBlack(import_picocolors.default.white(line))).join("\n"));
115
+ });
116
+ });
117
+ }
107
118
 
108
119
  // src/host/index.ts
109
- var import_node_process2 = __toESM(require("process"), 1);
110
- var import_node_child_process2 = require("child_process");
111
- var import_node_fs = require("fs");
112
- var import_hosts_so_easy = __toESM(require("hosts-so-easy"), 1);
113
- var Hosts = import_hosts_so_easy.default.default || import_hosts_so_easy.default;
114
- var hostInstance = new Hosts({
115
- debounceTime: 50,
116
- hostsFile: getPathOfSystemHostsPath()
117
- });
120
+ var _setHost = (0, import_node_util.promisify)(import_hostile.default.set);
121
+ var _removeHost = (0, import_node_util.promisify)(import_hostile.default.remove);
118
122
  function getPathOfSystemHostsPath() {
119
123
  return import_node_process2.default.platform === "win32" ? `${import_node_process2.default.env.windir || "C:\\WINDOWS"}\\system32\\drivers\\etc\\hosts` : "/etc/hosts";
120
124
  }
121
125
  async function syncHost() {
122
- return new Promise((resolve, reject) => {
126
+ return new Promise((resolve, _reject) => {
123
127
  (0, import_node_child_process2.exec)(
124
128
  import_node_process2.default.platform === "win32" ? "ipconfig /flushdns" : "sudo -E killall -HUP mDNSResponder",
125
- (error, stdout, stderr) => {
129
+ (error, _stdout, _stderr) => {
126
130
  if (error) {
127
131
  consola.error(`exec error: ${error}`);
128
132
  return resolve(false);
@@ -135,26 +139,24 @@ async function syncHost() {
135
139
  async function addHost(ip, host) {
136
140
  if (import_node_process2.default.platform !== "win32")
137
141
  (0, import_node_fs.chmodSync)(getPathOfSystemHostsPath(), 511);
138
- hostInstance.add("127.0.0.1", "localhost");
139
- hostInstance.add(ip, host);
142
+ await _setHost("127.0.0.1", "localhost");
143
+ await _setHost(ip, host);
140
144
  if (ip === "localhost")
141
- hostInstance.add("127.0.0.1", host);
142
- await hostInstance.updateFinish();
145
+ await _setHost("127.0.0.1", host);
143
146
  return await syncHost();
144
147
  }
145
148
  async function removeHost(ip, host) {
146
149
  if (import_node_process2.default.platform !== "win32")
147
150
  (0, import_node_fs.chmodSync)(getPathOfSystemHostsPath(), 511);
148
- hostInstance.remove(ip, host);
151
+ await _removeHost(ip, host);
149
152
  if (ip === "localhost")
150
- hostInstance.remove("127.0.0.1", host);
151
- await hostInstance.updateFinish();
153
+ await _removeHost("127.0.0.1", host);
152
154
  return await syncHost();
153
155
  }
154
156
 
155
157
  // src/caddy/constants.ts
158
+ var import_node_os2 = __toESM(require("os"), 1);
156
159
  var import_node_path2 = require("path");
157
- var import_node_os = __toESM(require("os"), 1);
158
160
  var import_node_process3 = __toESM(require("process"), 1);
159
161
  var import_dotenv_flow = __toESM(require("dotenv-flow"), 1);
160
162
  import_dotenv_flow.default.config({
@@ -162,12 +164,13 @@ import_dotenv_flow.default.config({
162
164
  });
163
165
  function resolvePath(path2) {
164
166
  if (path2.startsWith("~"))
165
- return (0, import_node_path2.join)(import_node_os.default.homedir() || "", path2.slice(1));
167
+ return (0, import_node_path2.join)(import_node_os2.default.homedir() || "", path2.slice(1));
166
168
  return path2;
167
169
  }
168
170
  var TEMP_DIR = resolvePath(import_node_process3.default.env.UHRP_CADDY_PATH || import_node_process3.default.env.TEMP || import_node_process3.default.env.TMPDIR || "/tmp");
169
171
  var caddyPath = (0, import_node_path2.join)(TEMP_DIR, `caddy${import_node_process3.default.platform === "win32" ? ".exe" : ""}`);
170
172
  var caddyFilePath = (0, import_node_path2.join)(TEMP_DIR, "CADDYFILE");
173
+ var caddyLockFilePath = (0, import_node_path2.join)(TEMP_DIR, "caddylock");
171
174
  var supportList = [
172
175
  {
173
176
  platform: "dragonfly",
@@ -280,11 +283,12 @@ var supportList = [
280
283
  ];
281
284
 
282
285
  // src/caddy/utils.ts
286
+ var import_node_child_process3 = require("child_process");
283
287
  var import_node_net = require("net");
284
288
  var import_ora = __toESM(require("ora"), 1);
285
289
  var spinner;
286
290
  function tryPort(port) {
287
- return new Promise((resolve, reject) => {
291
+ return new Promise((resolve, _reject) => {
288
292
  try {
289
293
  const server = (0, import_node_net.createServer)().listen(port);
290
294
  server.on("listening", () => {
@@ -296,11 +300,23 @@ function tryPort(port) {
296
300
  resolve(true);
297
301
  server.close();
298
302
  });
299
- } catch (e) {
303
+ } catch {
300
304
  resolve(true);
301
305
  }
302
306
  });
303
307
  }
308
+ async function kill(port) {
309
+ return new Promise((resolve, reject) => {
310
+ (0, import_node_child_process3.exec)(`npx @maxbo/free-port ${port} -s`, (err, stdout, _stderr) => {
311
+ if (err) {
312
+ reject(err);
313
+ } else {
314
+ consola.log(stdout);
315
+ resolve();
316
+ }
317
+ });
318
+ });
319
+ }
304
320
  function getNumber(number) {
305
321
  if (number <= 0)
306
322
  return "0%";
@@ -344,14 +360,14 @@ async function download() {
344
360
  (0, import_node_fs2.chmodSync)(TEMP_DIR, 511);
345
361
  }
346
362
  const file = (0, import_node_fs2.createWriteStream)(caddyPath);
347
- let _platform = (0, import_node_os2.platform)().toString();
363
+ let _platform = (0, import_node_os3.platform)().toString();
348
364
  _platform === "win32" && (_platform = "windows");
349
365
  let _arch = import_node_process4.default.arch.toString();
350
366
  _arch === "x64" && (_arch = "amd64");
351
367
  const support = supportList.find((item) => item.platform === _platform && item.arch === _arch);
352
368
  if (!support)
353
369
  return reject(new Error("not support"));
354
- const dowmloadLink = `https://caddyserver.com/api/download?os=${support.platform}&arch=${support.arch}`;
370
+ const dowmloadLink = `https://caddyserver.com/api/download?os=${support.platform}&arch=${support.arch}&p=github.com%2Fcaddyserver%2Fforwardproxy`;
355
371
  (0, import_node_fs2.existsSync)(caddyPath) && (0, import_node_fs2.unlinkSync)(caddyPath);
356
372
  const httpProxy = import_node_process4.default.env.HTTP_PROXY || import_node_process4.default.env.http_proxy;
357
373
  const httpsProxy = import_node_process4.default.env.HTTPS_PROXY || import_node_process4.default.env.https_proxy;
@@ -384,7 +400,7 @@ function testCaddy() {
384
400
  if (!(0, import_node_fs2.existsSync)(caddyPath))
385
401
  return resolve(false);
386
402
  (0, import_node_fs2.chmodSync)(caddyPath, 511);
387
- const child = import_node_process4.default.platform === "win32" ? (0, import_node_child_process3.spawn)(caddyPath, []) : (0, import_node_child_process3.spawn)("sudo", ["-E", caddyPath]);
403
+ const child = import_node_process4.default.platform === "win32" ? (0, import_node_child_process4.spawn)(caddyPath, []) : (0, import_node_child_process4.spawn)("sudo", ["-E", caddyPath]);
388
404
  child.on("close", () => {
389
405
  return resolve(false);
390
406
  });
@@ -400,9 +416,61 @@ var CaddyInstant = class {
400
416
  constructor() {
401
417
  this.inited = false;
402
418
  this.stoped = false;
403
- testCaddy().then(() => {
419
+ /** has locked */
420
+ this.locked = false;
421
+ testCaddy().then(async () => {
422
+ await this.getCaddyfile();
404
423
  this.inited = true;
405
424
  });
425
+ this.locked = this.checkLock();
426
+ }
427
+ checkLock() {
428
+ if (!(0, import_node_fs2.existsSync)(caddyLockFilePath))
429
+ (0, import_node_fs2.writeFileSync)(caddyLockFilePath, "");
430
+ return lockfile.checkSync(caddyLockFilePath);
431
+ }
432
+ async getCaddyfile() {
433
+ if (!(0, import_node_fs2.existsSync)(caddyFilePath))
434
+ await this.initCaddyfile();
435
+ this.caddyfile = await (0, import_promises2.readFile)(caddyFilePath, "utf-8");
436
+ return this.caddyfile;
437
+ }
438
+ async initCaddyfile() {
439
+ const contet = `
440
+ {
441
+ debug
442
+ auto_https disable_redirects
443
+ }
444
+
445
+ :7601 {
446
+ root * "${(0, import_node_path3.join)(
447
+ import_node_process4.default.platform === "win32" ? `${import_node_process4.default.env.AppData}/Caddy` : `${import_node_process4.default.env.HOME}/Library/Application Support/Caddy`,
448
+ "./pki/authorities/local"
449
+ )}"
450
+ file_server browse
451
+ }
452
+
453
+ # \u6B63\u5411\u4EE3\u7406\u914D\u7F6E
454
+ :7600 {
455
+ bind 0.0.0.0
456
+
457
+ forward_proxy {
458
+ hide_ip
459
+ hide_via
460
+ acl {
461
+ allow all
462
+ }
463
+ }
464
+ }
465
+ `;
466
+ await (0, import_promises2.writeFile)(caddyFilePath, contet);
467
+ this.caddyfile = contet;
468
+ }
469
+ async writeCaddyfile() {
470
+ return await (0, import_promises2.writeFile)(caddyFilePath, this.caddyfile || "");
471
+ }
472
+ async deleteCaddyfile() {
473
+ return await (0, import_promises2.unlink)(caddyFilePath);
406
474
  }
407
475
  async init() {
408
476
  await download();
@@ -411,7 +479,6 @@ var CaddyInstant = class {
411
479
  /**
412
480
  * @param source like `127.0.0.1:8080`
413
481
  * @param target like `test.abc.com`. And if you provide a port ,it will be ignore.
414
- * @returns
415
482
  */
416
483
  async run(source, target, options) {
417
484
  source = source.replace("0.0.0.0", "127.0.0.1");
@@ -421,107 +488,223 @@ var CaddyInstant = class {
421
488
  showCaddyLog = false,
422
489
  https = false
423
490
  } = options || {};
491
+ this._source = source;
492
+ this._target = target;
424
493
  if (!this.inited)
425
494
  await this.init();
426
- if (https && await tryPort(443))
427
- await (0, import_kill_port.default)(443, "tcp");
428
- if ((import_node_process4.default.platform === "win32" || !https) && await tryPort(80))
429
- await (0, import_kill_port.default)(80, "tcp");
430
495
  if (!await addHost(source.split(":")[0], target.split(":")[0]))
431
496
  throw new Error("update host failed");
432
497
  consola.success("update host success\n");
498
+ await this.getCaddyfile();
499
+ if (!(this.caddyfile || "").includes(`${target.split(":")[0]}${https ? "" : ":80"}`)) {
500
+ this.caddyfile = `${this.caddyfile}
501
+ ${target.split(":")[0]}${https ? "" : ":80"} {
502
+ ${https ? "tls internal" : ""}
503
+ reverse_proxy http://${source} {
504
+ health_uri ${base}
505
+ health_interval 2s
506
+ health_timeout 5s
507
+ fail_duration 2s
508
+ unhealthy_status 502 503 504 404
509
+ lb_try_duration 3s
510
+ lb_try_interval 300ms
511
+ health_headers {
512
+ Accept text/html
513
+ Accept-Encoding gzip, deflate, br
514
+ User-Agent Caddy-Health-Check
515
+ }
516
+
517
+ @error status 502 503 504 404
518
+ handle_response @error {
519
+ respond * 503 {
520
+ body "Service Unavailable"
521
+ close
522
+ }
523
+ }
524
+ }
525
+ }
526
+ `;
527
+ await this.writeCaddyfile();
528
+ }
529
+ if (!(0, import_node_fs2.existsSync)(caddyLockFilePath))
530
+ (0, import_node_fs2.writeFileSync)(caddyLockFilePath, "");
531
+ if (!this.locked) {
532
+ if (await tryPort(443))
533
+ await kill(443);
534
+ if ((import_node_process4.default.platform === "win32" || !https) && await tryPort(80))
535
+ await kill(80);
536
+ }
433
537
  return new Promise((resolve, reject) => {
434
- const child = import_node_process4.default.platform !== "win32" ? (0, import_node_child_process3.spawn)("sudo", ["-E", caddyPath, "reverse-proxy", "--from", `${target.split(":")[0]}${https ? "" : ":80"}`, "--to", `${source}`, "--internal-certs", "--insecure", "--disable-redirects"]) : (0, import_node_child_process3.spawn)(caddyPath, ["reverse-proxy", "--from", `${target.split(":")[0]}`, "--to", `${source}`, "--internal-certs"]);
435
- child.on("error", (err) => {
436
- return reject(err);
437
- });
438
- import_node_process4.default.on("SIGINT", async () => {
439
- if (!restore || this.stoped)
440
- return;
441
- try {
442
- if (await removeHost(source.split(":")[0], target.split(":")[0]))
443
- consola.success("restore host success\n");
444
- else
445
- consola.fail("restore host failed\n");
446
- } catch (e) {
447
- consola.error(e);
448
- consola.fail("restore host failed\n");
449
- } finally {
450
- this.stoped = true;
451
- import_node_process4.default.nextTick(() => {
452
- import_node_process4.default.exit();
453
- });
454
- }
455
- });
456
- const originalExit = import_node_process4.default.exit.bind(import_node_process4.default);
457
- import_node_process4.default.exit = async (code) => {
458
- const port = Number(source.split(":")[1]);
459
- if (!Number.isNaN(port) && await tryPort(port))
460
- await (0, import_kill_port.default)(port, "tcp");
461
- const pwd = import_node_process4.default.cwd();
462
- const viteCacheDir = `${pwd}/node_modules/.vite`;
463
- if ((0, import_node_fs2.existsSync)(viteCacheDir))
464
- chmodRecursive(viteCacheDir, 511);
465
- const nuxtCacheDir = `${pwd}/.nuxt`;
466
- if ((0, import_node_fs2.existsSync)(nuxtCacheDir))
467
- await chmodRecursive(nuxtCacheDir, 511);
468
- const webpackCacheDir = `${pwd}/node_modules/.cache`;
469
- if ((0, import_node_fs2.existsSync)(webpackCacheDir))
470
- chmodRecursive(webpackCacheDir, 511);
471
- if (!restore || this.stoped)
472
- return originalExit(code);
473
- try {
474
- if (await removeHost(source.split(":")[0], target.split(":")[0]))
475
- consola.success("restore host success\n");
476
- else
477
- consola.fail("restore host failed\n");
478
- } catch (e) {
479
- consola.error(e);
480
- consola.fail("restore host failed\n");
481
- } finally {
482
- this.stoped = true;
483
- import_node_process4.default.nextTick(() => {
484
- originalExit(code);
485
- });
486
- }
538
+ var _a, _b;
539
+ const setupCleanup = () => {
540
+ import_node_process4.default.on("SIGINT", async () => {
541
+ if (this.stoped)
542
+ return;
543
+ import_node_process4.default.stdin.resume();
544
+ try {
545
+ await this.baseCleanup(restore);
546
+ } finally {
547
+ this.stoped = true;
548
+ import_node_process4.default.nextTick(() => {
549
+ import_node_process4.default.exit();
550
+ });
551
+ }
552
+ });
553
+ const originalExit = import_node_process4.default.exit.bind(import_node_process4.default);
554
+ import_node_process4.default.exit = async (code) => {
555
+ const port = Number(source.split(":")[1]);
556
+ if (!Number.isNaN(port) && await tryPort(port))
557
+ await kill(port);
558
+ const pwd = import_node_process4.default.cwd();
559
+ const viteCacheDir = `${pwd}/node_modules/.vite`;
560
+ if ((0, import_node_fs2.existsSync)(viteCacheDir))
561
+ await chmodRecursive(viteCacheDir, 511).catch(() => {
562
+ });
563
+ const nuxtCacheDir = `${pwd}/.nuxt`;
564
+ if ((0, import_node_fs2.existsSync)(nuxtCacheDir))
565
+ await chmodRecursive(nuxtCacheDir, 511).catch(() => {
566
+ });
567
+ const webpackCacheDir = `${pwd}/node_modules/.cache`;
568
+ if ((0, import_node_fs2.existsSync)(webpackCacheDir))
569
+ await chmodRecursive(webpackCacheDir, 511).catch(() => {
570
+ });
571
+ if (this.stoped)
572
+ return originalExit(code);
573
+ import_node_process4.default.stdin.resume();
574
+ try {
575
+ await this.baseCleanup();
576
+ } finally {
577
+ this.stoped = true;
578
+ import_node_process4.default.nextTick(() => {
579
+ originalExit(code);
580
+ });
581
+ }
582
+ };
487
583
  };
488
- child.stderr.on("data", (data) => {
489
- const lines = data.toString().split("\n").map((line) => line.trim());
490
- for (const line of lines) {
491
- showCaddyLog && line && console.info(line);
492
- if (line.includes("Error:") || line && JSON.parse(line).level === "error") {
493
- consola.error(line);
494
- return reject(line);
584
+ if (!this.locked) {
585
+ this._caddyChild = import_node_process4.default.platform !== "win32" ? (0, import_node_child_process4.spawn)("sudo", ["-E", caddyPath, "run", "--config", caddyFilePath, "--watch"]) : (0, import_node_child_process4.spawn)(caddyPath, ["run", "--config", caddyFilePath, "--watch"]);
586
+ lockfile.lockSync(caddyLockFilePath);
587
+ this._caddyChild.on("error", (err) => {
588
+ return reject(err);
589
+ });
590
+ (_a = this._caddyChild.stderr) == null ? void 0 : _a.on("data", async (data) => {
591
+ const lines = data.toString().split("\n").map((line) => line.trim());
592
+ for (const line of lines) {
593
+ showCaddyLog && line && console.info(line);
594
+ if (line.includes("Error:") || line && JSON.parse(line).level === "error") {
595
+ if (line.includes("parsing caddyfile tokens")) {
596
+ consola.error("Caddyfile syntax error, please contact the author:\n", `${this.caddyfile}
597
+
598
+ ${line}
599
+ `);
600
+ await this.baseCleanup();
601
+ import_node_process4.default.exit();
602
+ } else {
603
+ consola.error(`${line}
604
+ `);
605
+ return reject(line);
606
+ }
607
+ }
608
+ if (line.includes("config file changed"))
609
+ consola.success("Detect added a new reverse proxy config, restarted.\n");
610
+ if (line.includes("caddy proxying") || line.includes("serving initial"))
611
+ return resolve();
495
612
  }
496
- }
497
- });
498
- child.stdout.on("data", (_data) => {
499
- consola.info(_data.toString());
500
- resolve();
501
- });
613
+ });
614
+ (_b = this._caddyChild.stdout) == null ? void 0 : _b.on("data", (_data) => {
615
+ consola.info(_data.toString());
616
+ resolve();
617
+ });
618
+ setupCleanup();
619
+ } else {
620
+ consola.info("Caddy is running in another process.");
621
+ setupCleanup();
622
+ return resolve();
623
+ }
502
624
  });
503
625
  }
626
+ async baseCleanup(restore = true) {
627
+ var _a;
628
+ try {
629
+ if (restore && this._source && this._target) {
630
+ if (await removeHost(this._source.split(":")[0], this._target.split(":")[0]))
631
+ consola.success("Restore host success.\n");
632
+ else
633
+ consola.fail("Restore host failed.\n");
634
+ }
635
+ } catch (e) {
636
+ consola.error(e);
637
+ consola.fail("Restore host failed.\n");
638
+ }
639
+ if (!this.locked && !this.stoped) {
640
+ (_a = this._caddyChild) == null ? void 0 : _a.kill();
641
+ try {
642
+ await lockfile.unlock(caddyLockFilePath).catch(() => {
643
+ });
644
+ await (0, import_promises2.unlink)(caddyFilePath).catch(() => {
645
+ });
646
+ await (0, import_promises2.unlink)(caddyLockFilePath).catch(() => {
647
+ });
648
+ } catch (e) {
649
+ consola.error(e);
650
+ }
651
+ }
652
+ }
504
653
  };
505
654
 
506
655
  // src/index.ts
507
656
  var caddy;
508
657
  var cwd = import_node_process5.default.cwd();
658
+ function colorUrl(url) {
659
+ return import_picocolors2.default.green(url.replace(/:(\d+)\//, (_, port) => `:${import_picocolors2.default.bold(port)}/`));
660
+ }
661
+ async function printForwardProxy() {
662
+ const ipv4List = getIpv4List();
663
+ if (ipv4List.length) {
664
+ const ips = ipv4List.map((ip) => import_picocolors2.default.cyan(ip)).join(", ");
665
+ consola.info(`${import_picocolors2.default.bold("Mobile device proxy access")}:
666
+ `);
667
+ consola.info("1. Install certificate: scan the QR code and download the `root.crt` file,");
668
+ consola.info(" then install it on your mobile device");
669
+ const ipTable = await Promise.all(
670
+ ipv4List.map(async (ip) => ({
671
+ target: `http://${ip}:7601`,
672
+ certificate: await generateQrcode(`http://${ip}:7601`)
673
+ }))
674
+ );
675
+ const table = new import_console_table_printer.Table({
676
+ columns: [
677
+ { name: "target", alignment: "left" },
678
+ { name: "certificate", alignment: "center", minLen: 28 }
679
+ ]
680
+ });
681
+ ipTable.forEach((ip) => {
682
+ table.addRow(ip);
683
+ });
684
+ table.printTable();
685
+ consola.info(`2. Set proxy on mobile device (Available IPs: ${ips}):${import_picocolors2.default.bold(7600)}
686
+
687
+ `);
688
+ }
689
+ }
509
690
  var vitePrintUrls = once((options, source, target, base = "/", _printUrls) => {
510
691
  _printUrls == null ? void 0 : _printUrls();
511
692
  if (caddy)
512
693
  return;
513
694
  caddy = new CaddyInstant();
514
- caddy.run(source, target, __spreadValues({
515
- base
516
- }, options)).then(() => {
517
- const colorUrl = (url) => import_picocolors.default.green(url.replace(/:(\d+)\//, (_, port) => `:${import_picocolors.default.bold(port)}/`));
518
- consola.success(` ${import_picocolors.default.green("\u279C")} ${import_picocolors.default.bold("run caddy reverse proxy success")}: ${colorUrl(`${options.https ? "https" : "http"}://${target}${base}`)}`);
695
+ caddy.run(source, target, {
696
+ base,
697
+ ...options
698
+ }).then(async () => {
699
+ await printForwardProxy();
700
+ consola.success(` ${import_picocolors2.default.green("\u279C")} ${import_picocolors2.default.bold("run caddy reverse proxy success")}: ${colorUrl(`${options.https ? "https" : "http"}://${target}${base}`)}`);
519
701
  }).catch((e) => {
520
702
  throw e;
521
703
  });
522
704
  });
523
705
 
524
706
  // src/nuxt.ts
707
+ var import_schema = require("@nuxt/schema");
525
708
  var nuxt_default = (0, import_kit.defineNuxtModule)({
526
709
  meta: {
527
710
  name: "nuxt-unplugin-https-reverse-proxy",
@@ -530,16 +713,16 @@ var nuxt_default = (0, import_kit.defineNuxtModule)({
530
713
  setup(options, _nuxt) {
531
714
  if (import_node_process6.default.env.NODE_ENV !== "development")
532
715
  return;
533
- if (!isAdmin()) {
534
- consola.warn("please run as administrator");
535
- return;
536
- }
537
716
  const {
538
717
  enable = true,
539
718
  target = ""
540
719
  } = options;
541
720
  if (!enable)
542
721
  return;
722
+ if (!isAdmin()) {
723
+ consola.warn("please run as administrator");
724
+ return;
725
+ }
543
726
  if (!target) {
544
727
  consola.fail("please provide target");
545
728
  return;
@@ -552,4 +735,4 @@ var nuxt_default = (0, import_kit.defineNuxtModule)({
552
735
  });
553
736
  }
554
737
  });
555
- exports.default = module.exports;
738
+ module.exports = module.exports;exports.default = module.exports;
package/dist/nuxt.d.cts CHANGED
@@ -3,6 +3,6 @@ import { Options } from './types.cjs';
3
3
 
4
4
  interface ModuleOptions extends Options {
5
5
  }
6
- declare const _default: _nuxt_schema.NuxtModule<ModuleOptions>;
6
+ declare const _default: _nuxt_schema.NuxtModule<ModuleOptions, ModuleOptions, false>;
7
7
 
8
8
  export { type ModuleOptions, _default as default };
package/dist/nuxt.d.ts CHANGED
@@ -3,6 +3,6 @@ import { Options } from './types.js';
3
3
 
4
4
  interface ModuleOptions extends Options {
5
5
  }
6
- declare const _default: _nuxt_schema.NuxtModule<ModuleOptions>;
6
+ declare const _default: _nuxt_schema.NuxtModule<ModuleOptions, ModuleOptions, false>;
7
7
 
8
8
  export { type ModuleOptions, _default as default };