unplugin-https-reverse-proxy 0.0.23 → 1.0.0-beta.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.cjs CHANGED
@@ -49,8 +49,8 @@ __export(src_exports, {
49
49
  unpluginFactory: () => unpluginFactory
50
50
  });
51
51
  module.exports = __toCommonJS(src_exports);
52
- var import_node_process4 = __toESM(require("process"), 1);
53
- var import_node_fs2 = require("fs");
52
+ var import_node_process5 = __toESM(require("process"), 1);
53
+ var import_node_fs3 = require("fs");
54
54
  var import_unplugin = require("unplugin");
55
55
  var import_picocolors = __toESM(require("picocolors"), 1);
56
56
 
@@ -61,15 +61,6 @@ var import_consola = require("consola");
61
61
  var consola = (0, import_consola.createConsola)({
62
62
  level: 3
63
63
  }).withTag("reverse-proxy");
64
- function once(fn) {
65
- let called = false;
66
- return (...args) => {
67
- if (called)
68
- return;
69
- called = true;
70
- return fn(...args);
71
- };
72
- }
73
64
  function isAdmin() {
74
65
  if (import_node_process.default.platform === "win32") {
75
66
  try {
@@ -85,20 +76,64 @@ function isAdmin() {
85
76
 
86
77
  // src/caddy/index.ts
87
78
  var import_node_os = require("os");
88
- var import_node_process3 = __toESM(require("process"), 1);
89
- var import_node_fs = require("fs");
90
- var import_node_child_process2 = require("child_process");
79
+ var import_node_process4 = __toESM(require("process"), 1);
80
+ var import_node_fs2 = require("fs");
81
+ var import_node_child_process3 = require("child_process");
91
82
  var import_got_cjs = require("got-cjs");
92
83
  var import_http_proxy_agent = require("http-proxy-agent");
93
84
  var import_https_proxy_agent = require("https-proxy-agent");
94
- var import_hosts_so_easy = __toESM(require("hosts-so-easy"), 1);
95
85
  var import_kill_port = __toESM(require("kill-port"), 1);
96
86
 
87
+ // src/host/index.ts
88
+ var import_node_process2 = __toESM(require("process"), 1);
89
+ var import_node_child_process2 = require("child_process");
90
+ var import_node_fs = require("fs");
91
+ var import_hosts_so_easy = __toESM(require("hosts-so-easy"), 1);
92
+ var Hosts = import_hosts_so_easy.default.default || import_hosts_so_easy.default;
93
+ var hostInstance = new Hosts({
94
+ debounceTime: 50,
95
+ hostsFile: getPathOfSystemHostsPath()
96
+ });
97
+ function getPathOfSystemHostsPath() {
98
+ return import_node_process2.default.platform === "win32" ? `${import_node_process2.default.env.windir || "C:\\WINDOWS"}\\system32\\drivers\\etc\\hosts` : "/etc/hosts";
99
+ }
100
+ async function syncHost() {
101
+ return new Promise((resolve, reject) => {
102
+ (0, import_node_child_process2.exec)(
103
+ import_node_process2.default.platform === "win32" ? "ipconfig /flushdns" : "sudo -E killall -HUP mDNSResponder",
104
+ (error, stdout, stderr) => {
105
+ if (error) {
106
+ console.error(`exec error: ${error}`);
107
+ return resolve(false);
108
+ }
109
+ return resolve(true);
110
+ }
111
+ );
112
+ });
113
+ }
114
+ async function addHost(ip, host) {
115
+ if (import_node_process2.default.platform !== "win32")
116
+ (0, import_node_fs.chmodSync)(getPathOfSystemHostsPath(), 511);
117
+ hostInstance.add("127.0.0.1", "localhost");
118
+ hostInstance.add(ip, host);
119
+ await hostInstance.updateFinish();
120
+ return await syncHost();
121
+ }
122
+ async function removeHost(ip, host) {
123
+ if (import_node_process2.default.platform !== "win32")
124
+ (0, import_node_fs.chmodSync)(getPathOfSystemHostsPath(), 511);
125
+ hostInstance.remove(ip, host);
126
+ if (ip === "localhost")
127
+ hostInstance.remove("127.0.0.1", host);
128
+ await hostInstance.updateFinish();
129
+ return await syncHost();
130
+ }
131
+
97
132
  // src/caddy/constants.ts
98
133
  var import_node_path = require("path");
99
- var import_node_process2 = __toESM(require("process"), 1);
100
- var TEMP_DIR = import_node_process2.default.env.TEMP || import_node_process2.default.env.TMPDIR || "/tmp";
101
- var caddyPath = (0, import_node_path.join)(TEMP_DIR, `caddy${import_node_process2.default.platform === "win32" ? ".exe" : ""}`);
134
+ var import_node_process3 = __toESM(require("process"), 1);
135
+ var TEMP_DIR = import_node_process3.default.env.TEMP || import_node_process3.default.env.TMPDIR || "/tmp";
136
+ var caddyPath = (0, import_node_path.join)(TEMP_DIR, `caddy${import_node_process3.default.platform === "win32" ? ".exe" : ""}`);
102
137
  var caddyFilePath = (0, import_node_path.join)(TEMP_DIR, "CADDYFILE");
103
138
  var supportList = [
104
139
  {
@@ -267,23 +302,22 @@ function logProgressOver() {
267
302
  }
268
303
 
269
304
  // src/caddy/index.ts
270
- var Hosts = import_hosts_so_easy.default.default || import_hosts_so_easy.default;
271
305
  async function download() {
272
306
  if (await testCaddy())
273
307
  return caddyPath;
274
308
  return new Promise((resolve, reject) => {
275
- const file = (0, import_node_fs.createWriteStream)(caddyPath);
309
+ const file = (0, import_node_fs2.createWriteStream)(caddyPath);
276
310
  let _platform = (0, import_node_os.platform)().toString();
277
311
  _platform === "win32" && (_platform = "windows");
278
- let _arch = import_node_process3.default.arch.toString();
312
+ let _arch = import_node_process4.default.arch.toString();
279
313
  _arch === "x64" && (_arch = "amd64");
280
314
  const support = supportList.find((item) => item.platform === _platform && item.arch === _arch);
281
315
  if (!support)
282
316
  return reject(new Error("not support"));
283
317
  const dowmloadLink = `https://caddyserver.com/api/download?os=${support.platform}&arch=${support.arch}`;
284
- (0, import_node_fs.existsSync)(caddyPath) && (0, import_node_fs.unlinkSync)(caddyPath);
285
- const httpProxy = import_node_process3.default.env.HTTP_PROXY || import_node_process3.default.env.http_proxy;
286
- const httpsProxy = import_node_process3.default.env.HTTPS_PROXY || import_node_process3.default.env.https_proxy;
318
+ (0, import_node_fs2.existsSync)(caddyPath) && (0, import_node_fs2.unlinkSync)(caddyPath);
319
+ const httpProxy = import_node_process4.default.env.HTTP_PROXY || import_node_process4.default.env.http_proxy;
320
+ const httpsProxy = import_node_process4.default.env.HTTPS_PROXY || import_node_process4.default.env.https_proxy;
287
321
  const httpAgent = httpProxy ? new import_http_proxy_agent.HttpProxyAgent(httpProxy) : void 0;
288
322
  const httpsAgent = httpsProxy ? new import_https_proxy_agent.HttpsProxyAgent(httpsProxy) : void 0;
289
323
  import_got_cjs.got.stream(dowmloadLink, {
@@ -295,9 +329,9 @@ async function download() {
295
329
  logProgress(progress.percent);
296
330
  }).pipe(file).on("finish", () => {
297
331
  logProgressOver();
298
- if (import_node_process3.default.platform === "win32")
332
+ if (import_node_process4.default.platform === "win32")
299
333
  return resolve(caddyPath);
300
- (0, import_node_fs.chmodSync)(caddyPath, 493);
334
+ (0, import_node_fs2.chmodSync)(caddyPath, 493);
301
335
  resolve(caddyPath);
302
336
  }).on("error", (err) => {
303
337
  reject(err);
@@ -306,10 +340,10 @@ async function download() {
306
340
  }
307
341
  function testCaddy() {
308
342
  return new Promise((resolve, reject) => {
309
- if (!(0, import_node_fs.existsSync)(caddyPath))
343
+ if (!(0, import_node_fs2.existsSync)(caddyPath))
310
344
  return resolve(false);
311
- (0, import_node_fs.chmodSync)(caddyPath, 493);
312
- const child = import_node_process3.default.platform === "win32" ? (0, import_node_child_process2.spawn)(caddyPath, []) : (0, import_node_child_process2.spawn)("sudo", ["-E", caddyPath]);
345
+ (0, import_node_fs2.chmodSync)(caddyPath, 493);
346
+ const child = import_node_process4.default.platform === "win32" ? (0, import_node_child_process3.spawn)(caddyPath, []) : (0, import_node_child_process3.spawn)("sudo", ["-E", caddyPath]);
313
347
  child.on("close", () => {
314
348
  return resolve(false);
315
349
  });
@@ -325,7 +359,6 @@ var CaddyInstant = class {
325
359
  constructor() {
326
360
  this.inited = false;
327
361
  this.stoped = false;
328
- this.host = new Hosts();
329
362
  testCaddy().then(() => {
330
363
  this.inited = true;
331
364
  });
@@ -334,51 +367,6 @@ var CaddyInstant = class {
334
367
  await download();
335
368
  this.inited = true;
336
369
  }
337
- async updateHost(ip, host) {
338
- ["localhost", "0.0.0.0"].includes(ip) && (ip = "127.0.0.1");
339
- this.host.add("127.0.0.1", "localhost");
340
- this.host.add(ip, host);
341
- await this.host.updateFinish();
342
- return new Promise((resolve, reject) => {
343
- if (import_node_process3.default.platform === "win32") {
344
- (0, import_node_child_process2.spawn)("ipconfig", ["/flushdns"]).on("error", (err) => {
345
- consola.error(err);
346
- return resolve(false);
347
- }).on("close", () => {
348
- resolve(true);
349
- });
350
- } else {
351
- (0, import_node_child_process2.spawn)("sudo", ["-E", "killall", "-HUP", "mDNSResponder"]).on("error", (err) => {
352
- consola.error(err);
353
- return resolve(false);
354
- }).on("close", () => {
355
- resolve(true);
356
- });
357
- }
358
- });
359
- }
360
- async restoreHost(ip, host) {
361
- ["localhost", "0.0.0.0"].includes(ip) && (ip = "127.0.0.1");
362
- this.host.remove(ip, host);
363
- await this.host.updateFinish();
364
- return new Promise((resolve, reject) => {
365
- if (import_node_process3.default.platform === "win32") {
366
- (0, import_node_child_process2.spawn)("ipconfig", ["/flushdns"]).on("error", (err) => {
367
- consola.error(err);
368
- return resolve(false);
369
- }).on("close", () => {
370
- resolve(true);
371
- });
372
- } else {
373
- (0, import_node_child_process2.spawn)("sudo", ["-E", "killall", "-HUP", "mDNSResponder"]).on("error", (err) => {
374
- consola.error(err);
375
- return resolve(false);
376
- }).on("close", () => {
377
- resolve(true);
378
- });
379
- }
380
- });
381
- }
382
370
  /**
383
371
  * @param source like `127.0.0.1:8080`
384
372
  * @param target like `test.abc.com`. And if you provide a port ,it will be ignore.
@@ -396,16 +384,53 @@ var CaddyInstant = class {
396
384
  await this.init();
397
385
  if (https && await tryPort(443))
398
386
  await (0, import_kill_port.default)(443, "tcp");
399
- if ((import_node_process3.default.platform === "win32" || !https) && await tryPort(80))
387
+ if ((import_node_process4.default.platform === "win32" || !https) && await tryPort(80))
400
388
  await (0, import_kill_port.default)(80, "tcp");
401
- if (!await this.updateHost(source.split(":")[0], target.split(":")[0]))
389
+ if (!await addHost(source.split(":")[0], target.split(":")[0]))
402
390
  throw new Error("update host failed");
403
391
  consola.success("update host success\n");
404
392
  return new Promise((resolve, reject) => {
405
- const child = import_node_process3.default.platform !== "win32" ? (0, import_node_child_process2.spawn)("sudo", ["-E", caddyPath, "reverse-proxy", "--from", `${target.split(":")[0]}${https ? "" : ":80"}`, "--to", `${source}`, "--internal-certs", "--insecure", "--disable-redirects"]) : (0, import_node_child_process2.spawn)(caddyPath, ["reverse-proxy", "--from", `${target.split(":")[0]}`, "--to", `${source}`, "--internal-certs"]);
393
+ 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"]);
406
394
  child.on("error", (err) => {
407
395
  return reject(err);
408
396
  });
397
+ import_node_process4.default.on("SIGINT", async () => {
398
+ if (!restore || this.stoped)
399
+ return;
400
+ try {
401
+ if (await removeHost(source.split(":")[0], target.split(":")[0]))
402
+ consola.success("restore host success\n");
403
+ else
404
+ consola.fail("restore host failed\n");
405
+ } catch (e) {
406
+ consola.error(e);
407
+ consola.fail("restore host failed\n");
408
+ } finally {
409
+ this.stoped = true;
410
+ import_node_process4.default.nextTick(() => {
411
+ import_node_process4.default.exit();
412
+ });
413
+ }
414
+ });
415
+ const originalExit = import_node_process4.default.exit.bind(import_node_process4.default);
416
+ import_node_process4.default.exit = async (code) => {
417
+ if (!restore || this.stoped)
418
+ return originalExit(code);
419
+ try {
420
+ if (await removeHost(source.split(":")[0], target.split(":")[0]))
421
+ consola.success("restore host success\n");
422
+ else
423
+ consola.fail("restore host failed\n");
424
+ } catch (e) {
425
+ consola.error(e);
426
+ consola.fail("restore host failed\n");
427
+ } finally {
428
+ this.stoped = true;
429
+ import_node_process4.default.nextTick(() => {
430
+ originalExit(code);
431
+ });
432
+ }
433
+ };
409
434
  child.stderr.on("data", (data) => {
410
435
  const lines = data.toString().split("\n").map((line) => line.trim());
411
436
  for (const line of lines) {
@@ -418,22 +443,7 @@ var CaddyInstant = class {
418
443
  });
419
444
  child.stdout.on("data", (_data) => {
420
445
  consola.info(_data.toString());
421
- resolve(async (callback) => {
422
- if (!restore || this.stoped)
423
- return;
424
- try {
425
- if (await this.restoreHost(source.split(":")[0], target.split(":")[0]))
426
- consola.success("restore host success\n");
427
- else
428
- consola.fail("restore host failed\n");
429
- } catch (e) {
430
- consola.error(e);
431
- consola.fail("restore host failed\n");
432
- }
433
- this.stoped = true;
434
- child.kill();
435
- callback && callback();
436
- });
446
+ resolve();
437
447
  });
438
448
  });
439
449
  }
@@ -442,55 +452,13 @@ var CaddyInstant = class {
442
452
  // src/index.ts
443
453
  var config;
444
454
  var caddy;
445
- var _stop;
446
455
  var _servce;
447
- function registerExit(clear) {
448
- import_node_process4.default.on("beforeExit", async (_code) => {
449
- await clear();
450
- });
451
- import_node_process4.default.on("uncaughtException", async (err) => {
452
- console.error("An uncaught error occurred!", err.stack);
453
- await clear();
454
- import_node_process4.default.nextTick(() => {
455
- import_node_process4.default.exit(1);
456
- });
457
- });
458
- import_node_process4.default.on("unhandledRejection", async (reason, promise) => {
459
- console.error("Unhandled Rejection at:", promise, "reason:", reason);
460
- await clear();
461
- import_node_process4.default.nextTick(() => {
462
- import_node_process4.default.exit(1);
463
- });
464
- });
465
- import_node_process4.default.once("SIGINT", async () => {
466
- await clear();
467
- import_node_process4.default.exit(0);
468
- });
469
- import_node_process4.default.once("SIGTERM", async () => {
470
- await clear();
471
- import_node_process4.default.exit(0);
472
- });
473
- }
474
456
  var unpluginFactory = (options) => ({
475
457
  name: "unplugin-https-reverse-proxy",
476
458
  enforce: "pre",
477
459
  vite: {
478
460
  configResolved(_config) {
479
461
  config = _config;
480
- registerExit(async () => {
481
- var _a;
482
- try {
483
- if (_servce) {
484
- (_a = _servce.httpServer) == null ? void 0 : _a.close(async () => {
485
- _stop && await _stop();
486
- });
487
- _servce.close();
488
- }
489
- _stop && await _stop();
490
- } catch (e) {
491
- consola.error(e);
492
- }
493
- });
494
462
  },
495
463
  configureServer(server) {
496
464
  if (!isAdmin()) {
@@ -514,10 +482,10 @@ var unpluginFactory = (options) => ({
514
482
  server.printUrls = () => {
515
483
  var _a;
516
484
  _printUrls();
517
- const pwd = import_node_process4.default.cwd();
485
+ const pwd = import_node_process5.default.cwd();
518
486
  const vireCacheDir = `${pwd}/node_modules/.vite`;
519
- if ((0, import_node_fs2.existsSync)(vireCacheDir))
520
- (0, import_node_fs2.chmodSync)(vireCacheDir, 511);
487
+ if ((0, import_node_fs3.existsSync)(vireCacheDir))
488
+ (0, import_node_fs3.chmodSync)(vireCacheDir, 511);
521
489
  let source = `localhost:${config.server.port}`;
522
490
  const url = (_a = server.resolvedUrls) == null ? void 0 : _a.local[0];
523
491
  if (url) {
@@ -531,10 +499,9 @@ var unpluginFactory = (options) => ({
531
499
  caddy = new CaddyInstant();
532
500
  caddy.run(source, target, __spreadValues({
533
501
  base
534
- }, options)).then((stop) => {
502
+ }, options)).then(() => {
535
503
  const colorUrl = (url2) => import_picocolors.default.green(url2.replace(/:(\d+)\//, (_, port) => `:${import_picocolors.default.bold(port)}/`));
536
504
  consola.success(` ${import_picocolors.default.green("\u279C")} ${import_picocolors.default.bold("run caddy reverse proxy success")}: ${colorUrl(`${options.https ? "https" : "http"}://${target}${base}`)}`);
537
- !_stop && (_stop = once(stop));
538
505
  }).catch((e) => {
539
506
  throw e;
540
507
  });
@@ -550,7 +517,7 @@ var unpluginFactory = (options) => ({
550
517
  consola.warn("please run as administrator");
551
518
  return;
552
519
  }
553
- if (import_node_process4.default.env.NODE_ENV !== "development")
520
+ if (import_node_process5.default.env.NODE_ENV !== "development")
554
521
  return;
555
522
  const {
556
523
  enable = true,
@@ -566,38 +533,25 @@ var unpluginFactory = (options) => ({
566
533
  const devServer = __spreadValues(__spreadValues({
567
534
  host: "localhost",
568
535
  port: 8080
569
- }, compiler.options.devServer), import_node_process4.default.VUE_CLI_SERVICE.projectOptions.devServer);
536
+ }, compiler.options.devServer), import_node_process5.default.VUE_CLI_SERVICE.projectOptions.devServer);
570
537
  const source = `${devServer.host}:${devServer.port}`;
571
538
  if (caddy)
572
539
  return;
573
540
  const _close = (_a = compiler.close) == null ? void 0 : _a.bind(compiler);
574
541
  if (_close) {
575
542
  compiler.close = async (callback) => {
576
- try {
577
- _stop && await _stop(() => {
578
- _close && _close(callback);
579
- });
580
- } catch (e) {
581
- consola.error(e);
582
- import_node_process4.default.exit(1);
583
- }
543
+ import_node_process5.default.on("exit", () => {
544
+ _close && _close(callback);
545
+ });
584
546
  };
585
547
  } else {
586
548
  options.https = false;
587
- registerExit(async () => {
588
- try {
589
- _stop && await _stop();
590
- } catch (e) {
591
- consola.error(e);
592
- }
593
- });
594
549
  }
595
550
  caddy = new CaddyInstant();
596
- caddy.run(source, target, __spreadValues({}, options)).then((stop) => {
551
+ caddy.run(source, target, __spreadValues({}, options)).then(() => {
597
552
  const colorUrl = (url) => import_picocolors.default.green(url.replace(/:(\d+)\//, (_, port) => `:${import_picocolors.default.bold(port)}/`));
598
553
  compiler.hooks.done.tap("unplugin-https-reverse-proxy", () => {
599
554
  consola.success(` ${import_picocolors.default.green("\u279C")} ${import_picocolors.default.bold("run caddy reverse proxy success")}: ${colorUrl(`${options.https ? "https" : "http"}://${target}`)}`);
600
- !_stop && (_stop = once(stop));
601
555
  });
602
556
  }).catch((e) => {
603
557
  throw e;
package/dist/index.js CHANGED
@@ -2,8 +2,8 @@ import {
2
2
  src_default,
3
3
  unplugin,
4
4
  unpluginFactory
5
- } from "./chunk-S4DC5XL4.js";
6
- import "./chunk-NNO3ZUSU.js";
5
+ } from "./chunk-KYMRDRAJ.js";
6
+ import "./chunk-3RTK3FSZ.js";
7
7
  export {
8
8
  src_default as default,
9
9
  unplugin,