unplugin-https-reverse-proxy 0.0.11 → 0.0.13

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/webpack.cjs CHANGED
@@ -3,8 +3,22 @@ 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;
6
7
  var __getProtoOf = Object.getPrototypeOf;
7
8
  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
+ };
8
22
  var __export = (target, all) => {
9
23
  for (var name in all)
10
24
  __defProp(target, name, { get: all[name], enumerable: true });
@@ -45,6 +59,15 @@ var import_consola = require("consola");
45
59
  var consola = (0, import_consola.createConsola)({
46
60
  level: 3
47
61
  }).withTag("reverse-proxy");
62
+ function once(fn) {
63
+ let called = false;
64
+ return (...args) => {
65
+ if (called)
66
+ return;
67
+ called = true;
68
+ return fn(...args);
69
+ };
70
+ }
48
71
 
49
72
  // src/caddy/index.ts
50
73
  var import_node_os = require("os");
@@ -54,7 +77,7 @@ var import_node_child_process = require("child_process");
54
77
  var import_got_cjs = require("got-cjs");
55
78
  var import_http_proxy_agent = require("http-proxy-agent");
56
79
  var import_https_proxy_agent = require("https-proxy-agent");
57
- var hostile = __toESM(require("hostile"), 1);
80
+ var import_hosts_so_easy = __toESM(require("hosts-so-easy"), 1);
58
81
  var import_kill_port = __toESM(require("kill-port"), 1);
59
82
 
60
83
  // src/caddy/constants.ts
@@ -176,6 +199,8 @@ var supportList = [
176
199
 
177
200
  // src/caddy/utils.ts
178
201
  var import_node_net = require("net");
202
+ var import_ora = __toESM(require("ora"), 1);
203
+ var spinner;
179
204
  function tryPort(port) {
180
205
  return new Promise((resolve, reject) => {
181
206
  try {
@@ -194,8 +219,41 @@ function tryPort(port) {
194
219
  }
195
220
  });
196
221
  }
222
+ function getNumber(number) {
223
+ if (number <= 0)
224
+ return "0%";
225
+ else if (number < 100)
226
+ return `${number.toFixed(2)}%`;
227
+ else
228
+ return "100%";
229
+ }
230
+ function logProgress(percent) {
231
+ if (!spinner) {
232
+ consola.log("");
233
+ spinner = (0, import_ora.default)({
234
+ text: "Start Download Caddy: 0%",
235
+ indent: 2
236
+ });
237
+ spinner.start();
238
+ } else {
239
+ spinner.text = `Download Caddy: ${getNumber(Number(percent) * 100)}`;
240
+ }
241
+ }
242
+ function logProgressOver() {
243
+ if (!spinner) {
244
+ spinner = (0, import_ora.default)({
245
+ text: "Start Download Caddy: 100%",
246
+ indent: 2
247
+ });
248
+ spinner.start();
249
+ } else {
250
+ spinner.succeed();
251
+ consola.log("");
252
+ }
253
+ }
197
254
 
198
255
  // src/caddy/index.ts
256
+ var Hosts = import_hosts_so_easy.default.default || import_hosts_so_easy.default;
199
257
  async function download() {
200
258
  if (await testCaddy())
201
259
  return caddyPath;
@@ -219,7 +277,10 @@ async function download() {
219
277
  http: httpAgent,
220
278
  https: httpsAgent
221
279
  }
280
+ }).on("downloadProgress", (progress) => {
281
+ logProgress(progress.percent);
222
282
  }).pipe(file).on("finish", () => {
283
+ logProgressOver();
223
284
  if (import_node_process2.default.platform === "win32")
224
285
  return resolve(caddyPath);
225
286
  (0, import_node_fs.chmodSync)(caddyPath, 493);
@@ -234,7 +295,7 @@ function testCaddy() {
234
295
  if (!(0, import_node_fs.existsSync)(caddyPath))
235
296
  return resolve(false);
236
297
  (0, import_node_fs.chmodSync)(caddyPath, 493);
237
- const child = import_node_process2.default.platform === "win32" ? (0, import_node_child_process.spawn)(caddyPath, []) : (0, import_node_child_process.spawn)("sudo", [caddyPath]);
298
+ const child = import_node_process2.default.platform === "win32" ? (0, import_node_child_process.spawn)(caddyPath, []) : (0, import_node_child_process.spawn)("sudo", ["-E", caddyPath]);
238
299
  child.on("close", () => {
239
300
  return resolve(false);
240
301
  });
@@ -249,6 +310,8 @@ function testCaddy() {
249
310
  var CaddyInstant = class {
250
311
  constructor() {
251
312
  this.inited = false;
313
+ this.stoped = false;
314
+ this.host = new Hosts();
252
315
  testCaddy().then(() => {
253
316
  this.inited = true;
254
317
  });
@@ -257,52 +320,46 @@ var CaddyInstant = class {
257
320
  await download();
258
321
  this.inited = true;
259
322
  }
260
- async updateHost(ip, host) {
323
+ updateHost(ip, host) {
261
324
  ["localhost", "0.0.0.0"].includes(ip) && (ip = "127.0.0.1");
325
+ this.host.add(ip, host);
262
326
  return new Promise((resolve, reject) => {
263
- hostile.set(ip, host, (err) => {
264
- if (err) {
265
- return reject(err);
266
- } else {
267
- if (import_node_process2.default.platform === "win32") {
268
- (0, import_node_child_process.spawn)("ipconfig", ["/flushdns"]).on("error", (err2) => {
269
- return reject(err2);
270
- }).on("close", () => {
271
- resolve(true);
272
- });
273
- } else {
274
- (0, import_node_child_process.spawn)("sudo", ["killall", "-HUP", "mDNSResponder"]).on("error", (err2) => {
275
- return reject(err2);
276
- }).on("close", () => {
277
- resolve(true);
278
- });
279
- }
280
- }
281
- });
327
+ if (import_node_process2.default.platform === "win32") {
328
+ (0, import_node_child_process.spawn)("ipconfig", ["/flushdns"]).on("error", (err) => {
329
+ consola.error(err);
330
+ return resolve(false);
331
+ }).on("close", () => {
332
+ resolve(true);
333
+ });
334
+ } else {
335
+ (0, import_node_child_process.spawn)("sudo", ["-E", "killall", "-HUP", "mDNSResponder"]).on("error", (err) => {
336
+ consola.error(err);
337
+ return resolve(false);
338
+ }).on("close", () => {
339
+ resolve(true);
340
+ });
341
+ }
282
342
  });
283
343
  }
284
- async restoreHost(ip, host) {
344
+ restoreHost(ip, host) {
285
345
  ["localhost", "0.0.0.0"].includes(ip) && (ip = "127.0.0.1");
346
+ this.host.remove(ip, host);
286
347
  return new Promise((resolve, reject) => {
287
- hostile.remove(ip, host, (err) => {
288
- if (err) {
289
- return reject(err);
290
- } else {
291
- if (import_node_process2.default.platform === "win32") {
292
- (0, import_node_child_process.spawn)("ipconfig", ["/flushdns"]).on("error", (err2) => {
293
- return reject(err2);
294
- }).on("close", () => {
295
- resolve(true);
296
- });
297
- } else {
298
- (0, import_node_child_process.spawn)("sudo", ["killall", "-HUP", "mDNSResponder"]).on("error", (err2) => {
299
- return reject(err2);
300
- }).on("close", () => {
301
- resolve(true);
302
- });
303
- }
304
- }
305
- });
348
+ if (import_node_process2.default.platform === "win32") {
349
+ (0, import_node_child_process.spawn)("ipconfig", ["/flushdns"]).on("error", (err) => {
350
+ consola.error(err);
351
+ return resolve(false);
352
+ }).on("close", () => {
353
+ resolve(true);
354
+ });
355
+ } else {
356
+ (0, import_node_child_process.spawn)("sudo", ["-E", "killall", "-HUP", "mDNSResponder"]).on("error", (err) => {
357
+ consola.error(err);
358
+ return resolve(false);
359
+ }).on("close", () => {
360
+ resolve(true);
361
+ });
362
+ }
306
363
  });
307
364
  }
308
365
  /**
@@ -319,14 +376,15 @@ var CaddyInstant = class {
319
376
  } = options || {};
320
377
  if (!this.inited)
321
378
  await this.init();
322
- if (!await this.updateHost(source.split(":")[0], target.split(":")[0]))
323
- throw new Error("update host failed");
324
379
  if (await tryPort(443))
325
380
  await (0, import_kill_port.default)(443, "tcp");
326
381
  if (import_node_process2.default.platform === "win32" && await tryPort(80))
327
382
  await (0, import_kill_port.default)(80, "tcp");
383
+ if (!await this.updateHost(source.split(":")[0], target.split(":")[0]))
384
+ throw new Error("update host failed");
385
+ consola.success("update host success\n");
328
386
  return new Promise((resolve, reject) => {
329
- const child = import_node_process2.default.platform !== "win32" ? (0, import_node_child_process.spawn)("sudo", [caddyPath, "reverse-proxy", "--from", `${target.split(":")[0]}`, "--to", `${source}`, "--internal-certs"]) : (0, import_node_child_process.spawn)(caddyPath, ["reverse-proxy", "--from", `${target.split(":")[0]}`, "--to", `${source}`, "--internal-certs"]);
387
+ const child = import_node_process2.default.platform !== "win32" ? (0, import_node_child_process.spawn)("sudo", ["-E", caddyPath, "reverse-proxy", "--from", `${target.split(":")[0]}`, "--to", `${source}`, "--internal-certs"]) : (0, import_node_child_process.spawn)(caddyPath, ["reverse-proxy", "--from", `${target.split(":")[0]}`, "--to", `${source}`, "--internal-certs"]);
330
388
  child.on("error", (err) => {
331
389
  return reject(err);
332
390
  });
@@ -334,7 +392,7 @@ var CaddyInstant = class {
334
392
  const lines = data.toString().split("\n").map((line) => line.trim());
335
393
  for (const line of lines) {
336
394
  showCaddyLog && line && console.info(line);
337
- if (line && JSON.parse(line).level === "error") {
395
+ if (line.includes("Error:") || line && JSON.parse(line).level === "error") {
338
396
  consola.error(line);
339
397
  return reject(line);
340
398
  }
@@ -342,14 +400,21 @@ var CaddyInstant = class {
342
400
  });
343
401
  child.stdout.on("data", (_data) => {
344
402
  consola.info(_data.toString());
345
- resolve(async () => {
346
- if (!restore)
403
+ resolve(async (callback) => {
404
+ if (!restore || this.stoped)
347
405
  return;
348
- if (await this.restoreHost(source.split(":")[0], target.split(":")[0]))
349
- consola.success("restore host success\n");
350
- else
406
+ try {
407
+ if (await this.restoreHost(source.split(":")[0], target.split(":")[0]))
408
+ consola.success("restore host success\n");
409
+ else
410
+ consola.fail("restore host failed\n");
411
+ } catch (e) {
412
+ consola.error(e);
351
413
  consola.fail("restore host failed\n");
414
+ }
415
+ this.stoped = true;
352
416
  child.kill();
417
+ callback && callback();
353
418
  });
354
419
  });
355
420
  });
@@ -359,21 +424,66 @@ var CaddyInstant = class {
359
424
  // src/index.ts
360
425
  var config;
361
426
  var caddy;
427
+ var _stop;
428
+ var _servce;
429
+ function registerExit(clear) {
430
+ import_node_process3.default.on("beforeExit", async (_code) => {
431
+ await clear();
432
+ });
433
+ import_node_process3.default.on("uncaughtException", async (err) => {
434
+ console.error("An uncaught error occurred!", err.stack);
435
+ await clear();
436
+ import_node_process3.default.nextTick(() => {
437
+ import_node_process3.default.exit(1);
438
+ });
439
+ });
440
+ import_node_process3.default.on("unhandledRejection", async (reason, promise) => {
441
+ console.error("Unhandled Rejection at:", promise, "reason:", reason);
442
+ await clear();
443
+ import_node_process3.default.nextTick(() => {
444
+ import_node_process3.default.exit(1);
445
+ });
446
+ });
447
+ import_node_process3.default.once("SIGINT", async () => {
448
+ await clear();
449
+ import_node_process3.default.emit("SIGINT");
450
+ });
451
+ import_node_process3.default.once("SIGTERM", async () => {
452
+ await clear();
453
+ import_node_process3.default.emit("SIGTERM");
454
+ });
455
+ }
362
456
  var unpluginFactory = (options) => ({
363
457
  name: "unplugin-https-reverse-proxy",
364
- enforce: "post",
458
+ enforce: "pre",
365
459
  vite: {
366
460
  configResolved(_config) {
367
461
  config = _config;
462
+ registerExit(async () => {
463
+ var _a;
464
+ try {
465
+ _servce && _servce.close();
466
+ (_a = _servce.httpServer) == null ? void 0 : _a.close(async () => {
467
+ _stop && await _stop();
468
+ });
469
+ _stop && await _stop();
470
+ } catch (e) {
471
+ consola.error(e);
472
+ }
473
+ });
368
474
  },
369
475
  configureServer(server) {
370
476
  const {
477
+ enable = true,
371
478
  target = ""
372
479
  } = options;
480
+ if (!enable)
481
+ return;
373
482
  if (!target) {
374
483
  consola.fail("please provide target");
375
484
  return;
376
485
  }
486
+ _servce = server;
377
487
  const _printUrls = server.printUrls;
378
488
  server.printUrls = () => {
379
489
  var _a;
@@ -386,51 +496,73 @@ var unpluginFactory = (options) => ({
386
496
  }
387
497
  const base = server.config.base || "/";
388
498
  try {
389
- const caddy2 = new CaddyInstant();
390
- caddy2.run(source, target, {
499
+ if (caddy)
500
+ return;
501
+ caddy = new CaddyInstant();
502
+ caddy.run(source, target, {
391
503
  base,
392
504
  showCaddyLog: options.showCaddyLog
393
505
  }).then((stop) => {
394
506
  const colorUrl = (url2) => import_picocolors.default.green(url2.replace(/:(\d+)\//, (_, port) => `:${import_picocolors.default.bold(port)}/`));
395
507
  consola.success(` ${import_picocolors.default.green("\u279C")} ${import_picocolors.default.bold("run caddy reverse proxy success")}: ${colorUrl(`https://${target}${base}`)}`);
396
- import_node_process3.default.on("SIGINT", async () => {
397
- await stop();
398
- server.close();
399
- import_node_process3.default.exit();
400
- });
508
+ !_stop && (_stop = once(stop));
509
+ }).catch((e) => {
510
+ throw e;
401
511
  });
402
512
  } catch (e) {
403
513
  consola.error(e);
404
514
  }
405
515
  };
516
+ },
517
+ async buildEnd() {
518
+ _stop && await _stop();
406
519
  }
407
520
  },
408
521
  webpack(compiler) {
409
522
  const {
523
+ enable = true,
410
524
  target = ""
411
525
  } = options;
526
+ if (!enable)
527
+ return;
412
528
  if (!target) {
413
529
  consola.fail("please provide target");
414
530
  return;
415
531
  }
416
532
  try {
417
- const devServer = compiler.options.devServer || import_node_process3.default.VUE_CLI_SERVICE.projectOptions.devServer;
418
- const source = `${(devServer == null ? void 0 : devServer.host) || "127.0.0.1"}:${(devServer == null ? void 0 : devServer.port) || "8080"}`;
533
+ registerExit(async () => {
534
+ try {
535
+ _stop && await _stop();
536
+ } catch (e) {
537
+ consola.error(e);
538
+ }
539
+ });
540
+ const devServer = __spreadValues(__spreadValues({
541
+ host: "127.0.0.1",
542
+ port: 8080
543
+ }, compiler.options.devServer), import_node_process3.default.VUE_CLI_SERVICE.projectOptions.devServer);
544
+ const source = `${devServer.host}:${devServer.port}`;
419
545
  if (caddy)
420
546
  return;
547
+ const _close = compiler.close.bind(compiler);
548
+ compiler.close = async (callback) => {
549
+ try {
550
+ _stop && await _stop(() => {
551
+ _close && _close(callback);
552
+ });
553
+ } catch (e) {
554
+ consola.error(e);
555
+ import_node_process3.default.exit(1);
556
+ }
557
+ };
421
558
  caddy = new CaddyInstant();
422
559
  caddy.run(source, target, {
423
560
  showCaddyLog: options.showCaddyLog
424
561
  }).then((stop) => {
425
562
  const colorUrl = (url) => import_picocolors.default.green(url.replace(/:(\d+)\//, (_, port) => `:${import_picocolors.default.bold(port)}/`));
426
- compiler.hooks.done.tap("unplugin-https-reverse-proxy", (stats) => {
427
- if (stats.hasErrors())
428
- return;
563
+ compiler.hooks.done.tap("unplugin-https-reverse-proxy", () => {
429
564
  consola.success(` ${import_picocolors.default.green("\u279C")} ${import_picocolors.default.bold("run caddy reverse proxy success")}: ${colorUrl(`https://${target}`)}`);
430
- });
431
- import_node_process3.default.on("SIGINT", async () => {
432
- await stop();
433
- import_node_process3.default.exit();
565
+ !_stop && (_stop = once(stop));
434
566
  });
435
567
  }).catch((e) => {
436
568
  throw e;
package/dist/webpack.js CHANGED
@@ -1,8 +1,8 @@
1
1
  import {
2
2
  webpack_default
3
- } from "./chunk-BFAT7WWW.js";
4
- import "./chunk-5K6D2TTS.js";
5
- import "./chunk-3HKPYCSE.js";
3
+ } from "./chunk-RTEXFW4L.js";
4
+ import "./chunk-DH6VMKTP.js";
5
+ import "./chunk-CQC5SSJR.js";
6
6
  export {
7
7
  webpack_default as default
8
8
  };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "unplugin-https-reverse-proxy",
3
3
  "type": "module",
4
- "version": "0.0.11",
4
+ "version": "0.0.13",
5
5
  "packageManager": "pnpm@8.6.12",
6
6
  "description": "",
7
7
  "license": "MIT",
@@ -106,10 +106,11 @@
106
106
  "consola": "^3.2.3",
107
107
  "esno": "^0.17.0",
108
108
  "got-cjs": "^12.5.4",
109
- "hostile": "^1.3.3",
109
+ "hosts-so-easy": "^1.2.9",
110
110
  "http-proxy-agent": "^7.0.0",
111
111
  "https-proxy-agent": "^7.0.2",
112
112
  "kill-port": "^2.0.1",
113
+ "ora": "5",
113
114
  "picocolors": "^1.0.0",
114
115
  "unplugin": "^1.4.0"
115
116
  },
@@ -117,7 +118,6 @@
117
118
  "@antfu/eslint-config": "^0.40.2",
118
119
  "@nuxt/kit": "^3.6.5",
119
120
  "@nuxt/schema": "^3.6.5",
120
- "@types/hostile": "^1.3.3",
121
121
  "@types/kill-port": "^2.0.3",
122
122
  "@types/node": "^20.5.2",
123
123
  "bumpp": "^9.2.0",
@@ -5,11 +5,15 @@ import { spawn } from 'node:child_process'
5
5
  import { got } from 'got-cjs'
6
6
  import { HttpProxyAgent } from 'http-proxy-agent'
7
7
  import { HttpsProxyAgent } from 'https-proxy-agent'
8
- import * as hostile from 'hostile'
8
+
9
+ // @ts-expect-error no type
10
+ import _Hosts from 'hosts-so-easy'
9
11
  import kill from 'kill-port'
10
12
  import { consola } from '../utils'
11
13
  import { caddyPath, supportList } from './constants'
12
- import { tryPort } from './utils'
14
+ import { logProgress, logProgressOver, tryPort } from './utils'
15
+
16
+ const Hosts = _Hosts.default || _Hosts
13
17
 
14
18
  export async function download() {
15
19
  if (await testCaddy())
@@ -47,7 +51,10 @@ export async function download() {
47
51
  http: httpAgent,
48
52
  https: httpsAgent,
49
53
  },
54
+ }).on('downloadProgress', (progress) => {
55
+ logProgress(progress.percent)
50
56
  }).pipe(file).on('finish', () => {
57
+ logProgressOver()
51
58
  if (process.platform === 'win32')
52
59
  return resolve(caddyPath)
53
60
  // chmod +x
@@ -65,7 +72,7 @@ function testCaddy() {
65
72
  if (!existsSync(caddyPath))
66
73
  return resolve(false)
67
74
  chmodSync(caddyPath, 0o755)
68
- const child = process.platform === 'win32' ? spawn(caddyPath, []) : spawn('sudo', [caddyPath])
75
+ const child = process.platform === 'win32' ? spawn(caddyPath, []) : spawn('sudo', ['-E', caddyPath])
69
76
  child.on('close', () => {
70
77
  return resolve(false)
71
78
  })
@@ -86,8 +93,11 @@ interface RunOptions {
86
93
 
87
94
  export class CaddyInstant {
88
95
  private inited = false
96
+ private stoped = false
97
+ private host: typeof Hosts
89
98
 
90
99
  constructor() {
100
+ this.host = new Hosts()
91
101
  testCaddy().then(() => {
92
102
  this.inited = true
93
103
  })
@@ -98,57 +108,49 @@ export class CaddyInstant {
98
108
  this.inited = true
99
109
  }
100
110
 
101
- private async updateHost(ip: string, host: string) {
111
+ private updateHost(ip: string, host: string) {
102
112
  ['localhost', '0.0.0.0'].includes(ip) && (ip = '127.0.0.1')
113
+ this.host.add(ip, host)
103
114
  return new Promise<boolean>((resolve, reject) => {
104
- hostile.set(ip, host, (err) => {
105
- if (err) {
106
- return reject(err)
107
- }
108
- else {
109
- if (process.platform === 'win32') {
110
- spawn('ipconfig', ['/flushdns']).on('error', (err) => {
111
- return reject(err)
112
- }).on('close', () => {
113
- resolve(true)
114
- })
115
- }
116
- else {
117
- spawn('sudo', ['killall', '-HUP', 'mDNSResponder']).on('error', (err) => {
118
- return reject(err)
119
- }).on('close', () => {
120
- resolve(true)
121
- })
122
- }
123
- }
124
- })
115
+ if (process.platform === 'win32') {
116
+ spawn('ipconfig', ['/flushdns']).on('error', (err) => {
117
+ consola.error(err)
118
+ return resolve(false)
119
+ }).on('close', () => {
120
+ resolve(true)
121
+ })
122
+ }
123
+ else {
124
+ spawn('sudo', ['-E', 'killall', '-HUP', 'mDNSResponder']).on('error', (err) => {
125
+ consola.error(err)
126
+ return resolve(false)
127
+ }).on('close', () => {
128
+ resolve(true)
129
+ })
130
+ }
125
131
  })
126
132
  }
127
133
 
128
- private async restoreHost(ip: string, host: string) {
134
+ private restoreHost(ip: string, host: string) {
129
135
  ['localhost', '0.0.0.0'].includes(ip) && (ip = '127.0.0.1')
136
+ this.host.remove(ip, host)
130
137
  return new Promise<boolean>((resolve, reject) => {
131
- hostile.remove(ip, host, (err) => {
132
- if (err) {
133
- return reject(err)
134
- }
135
- else {
136
- if (process.platform === 'win32') {
137
- spawn('ipconfig', ['/flushdns']).on('error', (err) => {
138
- return reject(err)
139
- }).on('close', () => {
140
- resolve(true)
141
- })
142
- }
143
- else {
144
- spawn('sudo', ['killall', '-HUP', 'mDNSResponder']).on('error', (err) => {
145
- return reject(err)
146
- }).on('close', () => {
147
- resolve(true)
148
- })
149
- }
150
- }
151
- })
138
+ if (process.platform === 'win32') {
139
+ spawn('ipconfig', ['/flushdns']).on('error', (err) => {
140
+ consola.error(err)
141
+ return resolve(false)
142
+ }).on('close', () => {
143
+ resolve(true)
144
+ })
145
+ }
146
+ else {
147
+ spawn('sudo', ['-E', 'killall', '-HUP', 'mDNSResponder']).on('error', (err) => {
148
+ consola.error(err)
149
+ return resolve(false)
150
+ }).on('close', () => {
151
+ resolve(true)
152
+ })
153
+ }
152
154
  })
153
155
  }
154
156
 
@@ -168,18 +170,19 @@ export class CaddyInstant {
168
170
  if (!this.inited)
169
171
  await this.init()
170
172
 
171
- if (!await this.updateHost(source.split(':')[0], target.split(':')[0]))
172
- throw new Error('update host failed')
173
-
174
173
  if (await tryPort(443))
175
174
  await kill(443, 'tcp')
176
175
  if (process.platform === 'win32' && await tryPort(80))
177
176
  await kill(80, 'tcp')
178
177
 
179
- return new Promise<() => Promise<void>>((resolve, reject) => {
178
+ if (!await this.updateHost(source.split(':')[0], target.split(':')[0]))
179
+ throw new Error('update host failed')
180
+ consola.success('update host success\n')
181
+
182
+ return new Promise<(callback?: () => any) => Promise<void>>((resolve, reject) => {
180
183
  // caddy reverse-proxy --from target --to source --internal-certs
181
184
  const child = process.platform !== 'win32'
182
- ? spawn('sudo', [caddyPath, 'reverse-proxy', '--from', `${target.split(':')[0]}`, '--to', `${source}`, '--internal-certs'])
185
+ ? spawn('sudo', ['-E', caddyPath, 'reverse-proxy', '--from', `${target.split(':')[0]}`, '--to', `${source}`, '--internal-certs'])
183
186
  : spawn(caddyPath, ['reverse-proxy', '--from', `${target.split(':')[0]}`, '--to', `${source}`, '--internal-certs'])
184
187
 
185
188
  child.on('error', (err) => {
@@ -192,7 +195,7 @@ export class CaddyInstant {
192
195
  // caddy log
193
196
  // eslint-disable-next-line no-console
194
197
  showCaddyLog && line && console.info(line)
195
- if (line && JSON.parse(line).level === 'error') {
198
+ if (line.includes('Error:') || (line && JSON.parse(line).level === 'error')) {
196
199
  consola.error(line)
197
200
  // child.kill()
198
201
  return reject(line)
@@ -202,17 +205,25 @@ export class CaddyInstant {
202
205
 
203
206
  child.stdout.on('data', (_data) => {
204
207
  consola.info(_data.toString())
205
- resolve(async () => {
206
- if (!restore)
208
+ resolve(async (callback?: () => any) => {
209
+ if (!restore || this.stoped)
207
210
  return
208
211
 
209
- if (await this.restoreHost(source.split(':')[0], target.split(':')[0]))
210
- consola.success('restore host success\n')
212
+ try {
213
+ if (await this.restoreHost(source.split(':')[0], target.split(':')[0]))
214
+ consola.success('restore host success\n')
211
215
 
212
- else
216
+ else
217
+ consola.fail('restore host failed\n')
218
+ }
219
+ catch (e) {
220
+ consola.error(e)
213
221
  consola.fail('restore host failed\n')
222
+ }
214
223
 
224
+ this.stoped = true
215
225
  child.kill()
226
+ callback && callback()
216
227
  })
217
228
  })
218
229
  })