unplugin-https-reverse-proxy 1.0.0-beta.1 → 1.0.0-beta.12

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/README.md CHANGED
@@ -2,10 +2,19 @@
2
2
 
3
3
  [![NPM version](https://img.shields.io/npm/v/unplugin-https-reverse-proxy?color=a1b858&label=)](https://www.npmjs.com/package/unplugin-https-reverse-proxy)
4
4
 
5
- A plugin for https reverse proxy, support `vite` and `webpack`.
5
+ A plugin for https reverse proxy, support `vite`、`webpack` and `rspack`.
6
6
 
7
7
  ## Install
8
8
 
9
+
10
+ Support set caddy file path by environment variable `UHRP_CADDY_PATH`, default is system cache folder.
11
+
12
+ ```env
13
+ #.env.local
14
+ UHRP_CADDY_PATH=~/tmp/.uhrp
15
+ ```
16
+
17
+
9
18
  ```bash
10
19
  # not auto install caddy when postinstall
11
20
  npm i unplugin-https-reverse-proxy --save-dev
@@ -115,6 +124,90 @@ module.exports = {
115
124
 
116
125
  <br></details>
117
126
 
127
+ <details>
128
+ <summary>Rspack</summary><br>
129
+
130
+ ```js
131
+ // rspack.config.js
132
+
133
+ /** @type {Parameters<import('unplugin-https-reverse-proxy/webpack')['default']>[0]} */
134
+ const reverseProxyOptions = {
135
+ enable: false,
136
+ target: 'xxx',
137
+ https: false,
138
+ }
139
+
140
+ module.exports = {
141
+ /* ... */
142
+ devServer: {
143
+ client: {
144
+ // ↓ for HMR
145
+ webSocketURL: {
146
+ ...(reverseProxyOptions.enable
147
+ ? {
148
+ hostname: reverseProxyOptions.target,
149
+ }
150
+ : {}),
151
+ ...(reverseProxyOptions.enable && reverseProxyOptions.https
152
+ ? {
153
+ protocol: 'wss',
154
+ port: 443,
155
+ }
156
+ : {})
157
+ }
158
+ },
159
+ },
160
+ plugins: [
161
+ require('unplugin-https-reverse-proxy/rspack')(reverseProxyOptions)
162
+ ]
163
+ }
164
+ ```
165
+
166
+ <br></details>
167
+
168
+ <details>
169
+ <summary>Rsbuild</summary><br>
170
+
171
+ ```js
172
+ // rsbuild.config.js
173
+
174
+ /** @type {Parameters<import('unplugin-https-reverse-proxy/webpack')['default']>[0]} */
175
+ const reverseProxyOptions = {
176
+ enable: false,
177
+ target: 'xxx',
178
+ https: false,
179
+ }
180
+
181
+ module.exports = {
182
+ /* ... */
183
+ dev: {
184
+ client: {
185
+ // ↓ for HMR
186
+ ...(reverseProxyOptions.enable
187
+ ? {
188
+ host: reverseProxyOptions.target,
189
+ }
190
+ : {}),
191
+ ...(reverseProxyOptions.enable && reverseProxyOptions.https
192
+ ? {
193
+ protocol: 'wss',
194
+ port: '443',
195
+ }
196
+ : {})
197
+ },
198
+ },
199
+ tools: {
200
+ rspack: {
201
+ plugins: [
202
+ require('unplugin-https-reverse-proxy/rspack')(reverseProxyOptions)
203
+ ]
204
+ },
205
+ },
206
+ }
207
+ ```
208
+
209
+ <br></details>
210
+
118
211
  <details>
119
212
  <summary>Nuxt</summary><br>
120
213
 
@@ -17,11 +17,21 @@ var __spreadValues = (a, b) => {
17
17
 
18
18
  // src/utils.ts
19
19
  import process from "process";
20
+ import path from "path";
21
+ import { chmod, readdir, stat } from "fs/promises";
20
22
  import { execSync } from "child_process";
21
23
  import { createConsola } from "consola";
22
24
  var consola = createConsola({
23
25
  level: 3
24
26
  }).withTag("reverse-proxy");
27
+ async function chmodRecursive(_path, mode) {
28
+ await chmod(_path, mode);
29
+ if ((await stat(_path)).isDirectory()) {
30
+ const children = await readdir(_path);
31
+ for (const child of children)
32
+ await chmodRecursive(path.join(_path, child), mode);
33
+ }
34
+ }
25
35
  function once(fn) {
26
36
  let called = false;
27
37
  return (...args) => {
@@ -47,6 +57,7 @@ function isAdmin() {
47
57
  export {
48
58
  __spreadValues,
49
59
  consola,
60
+ chmodRecursive,
50
61
  once,
51
62
  isAdmin
52
63
  };
@@ -1,19 +1,20 @@
1
1
  import {
2
2
  __spreadValues,
3
+ chmodRecursive,
3
4
  consola,
4
- isAdmin
5
- } from "./chunk-NNO3ZUSU.js";
5
+ isAdmin,
6
+ once
7
+ } from "./chunk-RUJE3YFB.js";
6
8
 
7
9
  // src/index.ts
8
10
  import process4 from "process";
9
- import { chmodSync as chmodSync3, existsSync as existsSync2 } from "fs";
10
11
  import { createUnplugin } from "unplugin";
11
12
  import c from "picocolors";
12
13
 
13
14
  // src/caddy/index.ts
14
15
  import { platform } from "os";
15
16
  import process3 from "process";
16
- import { chmodSync as chmodSync2, createWriteStream, existsSync, unlinkSync } from "fs";
17
+ import { chmodSync as chmodSync2, createWriteStream, existsSync, mkdirSync, unlinkSync } from "fs";
17
18
  import { spawn } from "child_process";
18
19
  import { got } from "got-cjs";
19
20
  import { HttpProxyAgent } from "http-proxy-agent";
@@ -69,8 +70,18 @@ async function removeHost(ip, host) {
69
70
 
70
71
  // src/caddy/constants.ts
71
72
  import { join } from "path";
73
+ import os from "os";
72
74
  import process2 from "process";
73
- var TEMP_DIR = process2.env.TEMP || process2.env.TMPDIR || "/tmp";
75
+ import dotenvFlow from "dotenv-flow";
76
+ dotenvFlow.config({
77
+ silent: true
78
+ });
79
+ function resolvePath(path) {
80
+ if (path.startsWith("~"))
81
+ return join(os.homedir() || "", path.slice(1));
82
+ return path;
83
+ }
84
+ var TEMP_DIR = resolvePath(process2.env.UHRP_CADDY_PATH || process2.env.TEMP || process2.env.TMPDIR || "/tmp");
74
85
  var caddyPath = join(TEMP_DIR, `caddy${process2.platform === "win32" ? ".exe" : ""}`);
75
86
  var caddyFilePath = join(TEMP_DIR, "CADDYFILE");
76
87
  var supportList = [
@@ -244,6 +255,10 @@ async function download() {
244
255
  if (await testCaddy())
245
256
  return caddyPath;
246
257
  return new Promise((resolve, reject) => {
258
+ if (!existsSync(TEMP_DIR)) {
259
+ mkdirSync(TEMP_DIR, { recursive: true });
260
+ chmodSync2(TEMP_DIR, 511);
261
+ }
247
262
  const file = createWriteStream(caddyPath);
248
263
  let _platform = platform().toString();
249
264
  _platform === "win32" && (_platform = "windows");
@@ -258,6 +273,9 @@ async function download() {
258
273
  const httpsProxy = process3.env.HTTPS_PROXY || process3.env.https_proxy;
259
274
  const httpAgent = httpProxy ? new HttpProxyAgent(httpProxy) : void 0;
260
275
  const httpsAgent = httpsProxy ? new HttpsProxyAgent(httpsProxy) : void 0;
276
+ const chmodCaddyOnce = once(() => {
277
+ chmodSync2(caddyPath, 511);
278
+ });
261
279
  got.stream(dowmloadLink, {
262
280
  agent: {
263
281
  http: httpAgent,
@@ -265,11 +283,12 @@ async function download() {
265
283
  }
266
284
  }).on("downloadProgress", (progress) => {
267
285
  logProgress(progress.percent);
286
+ chmodCaddyOnce();
268
287
  }).pipe(file).on("finish", () => {
269
288
  logProgressOver();
270
289
  if (process3.platform === "win32")
271
290
  return resolve(caddyPath);
272
- chmodSync2(caddyPath, 493);
291
+ chmodSync2(caddyPath, 511);
273
292
  resolve(caddyPath);
274
293
  }).on("error", (err) => {
275
294
  reject(err);
@@ -280,7 +299,7 @@ function testCaddy() {
280
299
  return new Promise((resolve, reject) => {
281
300
  if (!existsSync(caddyPath))
282
301
  return resolve(false);
283
- chmodSync2(caddyPath, 493);
302
+ chmodSync2(caddyPath, 511);
284
303
  const child = process3.platform === "win32" ? spawn(caddyPath, []) : spawn("sudo", ["-E", caddyPath]);
285
304
  child.on("close", () => {
286
305
  return resolve(false);
@@ -352,6 +371,19 @@ var CaddyInstant = class {
352
371
  });
353
372
  const originalExit = process3.exit.bind(process3);
354
373
  process3.exit = async (code) => {
374
+ const port = Number(source.split(":")[1]);
375
+ if (!Number.isNaN(port) && await tryPort(port))
376
+ await kill(port, "tcp");
377
+ const pwd = process3.cwd();
378
+ const viteCacheDir = `${pwd}/node_modules/.vite`;
379
+ if (existsSync(viteCacheDir))
380
+ chmodRecursive(viteCacheDir, 511);
381
+ const nuxtCacheDir = `${pwd}/.nuxt`;
382
+ if (existsSync(nuxtCacheDir))
383
+ await chmodRecursive(nuxtCacheDir, 511);
384
+ const webpackCacheDir = `${pwd}/node_modules/.cache`;
385
+ if (existsSync(webpackCacheDir))
386
+ chmodRecursive(webpackCacheDir, 511);
355
387
  if (!restore || this.stoped)
356
388
  return originalExit(code);
357
389
  try {
@@ -390,31 +422,21 @@ var CaddyInstant = class {
390
422
  // src/index.ts
391
423
  var config;
392
424
  var caddy;
393
- function vitePrintUrls(server, options, source, target, base = "/", _printUrls) {
425
+ var cwd = process4.cwd();
426
+ var vitePrintUrls = once((options, source, target, base = "/", _printUrls) => {
394
427
  _printUrls == null ? void 0 : _printUrls();
395
- const pwd = process4.cwd();
396
- const viteCacheDir = `${pwd}/node_modules/.vite`;
397
- if (existsSync2(viteCacheDir))
398
- chmodSync3(viteCacheDir, 511);
399
- const nuxtCacheDir = `${pwd}/.nuxt`;
400
- if (existsSync2(nuxtCacheDir))
401
- chmodSync3(nuxtCacheDir, 511);
402
- try {
403
- if (caddy)
404
- return;
405
- caddy = new CaddyInstant();
406
- caddy.run(source, target, __spreadValues({
407
- base
408
- }, options)).then(() => {
409
- const colorUrl = (url) => c.green(url.replace(/:(\d+)\//, (_, port) => `:${c.bold(port)}/`));
410
- consola.success(` ${c.green("\u279C")} ${c.bold("run caddy reverse proxy success")}: ${colorUrl(`${options.https ? "https" : "http"}://${target}${base}`)}`);
411
- }).catch((e) => {
412
- throw e;
413
- });
414
- } catch (e) {
415
- consola.error(e);
416
- }
417
- }
428
+ if (caddy)
429
+ return;
430
+ caddy = new CaddyInstant();
431
+ caddy.run(source, target, __spreadValues({
432
+ base
433
+ }, options)).then(() => {
434
+ const colorUrl = (url) => c.green(url.replace(/:(\d+)\//, (_, port) => `:${c.bold(port)}/`));
435
+ consola.success(` ${c.green("\u279C")} ${c.bold("run caddy reverse proxy success")}: ${colorUrl(`${options.https ? "https" : "http"}://${target}${base}`)}`);
436
+ }).catch((e) => {
437
+ throw e;
438
+ });
439
+ });
418
440
  var unpluginFactory = (options) => ({
419
441
  name: "unplugin-https-reverse-proxy",
420
442
  enforce: "pre",
@@ -424,11 +446,7 @@ var unpluginFactory = (options) => ({
424
446
  },
425
447
  configureServer(server) {
426
448
  var _a;
427
- if (!isAdmin()) {
428
- consola.warn("please run as administrator");
429
- return;
430
- }
431
- if (config.command === "build")
449
+ if (config.command !== "serve")
432
450
  return;
433
451
  const {
434
452
  enable = true,
@@ -436,6 +454,10 @@ var unpluginFactory = (options) => ({
436
454
  } = options;
437
455
  if (!enable)
438
456
  return;
457
+ if (!isAdmin()) {
458
+ consola.warn("please run as administrator");
459
+ return;
460
+ }
439
461
  if (!target) {
440
462
  consola.fail("please provide target");
441
463
  return;
@@ -448,15 +470,56 @@ var unpluginFactory = (options) => ({
448
470
  source = u.host;
449
471
  }
450
472
  const base = server.config.base || "/";
451
- server.printUrls = () => vitePrintUrls(server, options, source, target, base, _printUrls);
473
+ server.printUrls = () => vitePrintUrls(options, source, target, base, _printUrls);
452
474
  }
453
475
  },
454
476
  webpack(compiler) {
455
- var _a;
477
+ var _a, _b;
478
+ if (process4.env.NODE_ENV !== "development")
479
+ return;
480
+ const {
481
+ enable = true,
482
+ target = ""
483
+ } = options;
484
+ if (!enable)
485
+ return;
456
486
  if (!isAdmin()) {
457
487
  consola.warn("please run as administrator");
458
488
  return;
459
489
  }
490
+ if (!target) {
491
+ consola.fail("please provide target");
492
+ return;
493
+ }
494
+ const devServer = __spreadValues(__spreadValues({
495
+ host: "localhost",
496
+ port: 8080
497
+ }, compiler.options.devServer), (_a = process4.VUE_CLI_SERVICE) == null ? void 0 : _a.projectOptions.devServer);
498
+ const source = `${devServer.host}:${devServer.port}`;
499
+ if (caddy)
500
+ return;
501
+ const _close = (_b = compiler.close) == null ? void 0 : _b.bind(compiler);
502
+ if (_close) {
503
+ compiler.close = async (callback) => {
504
+ process4.on("exit", () => {
505
+ _close && _close(callback);
506
+ });
507
+ };
508
+ } else {
509
+ options.https = false;
510
+ }
511
+ caddy = new CaddyInstant();
512
+ caddy.run(source, target, __spreadValues({}, options)).then(() => {
513
+ const colorUrl = (url) => c.green(url.replace(/:(\d+)\//, (_, port) => `:${c.bold(port)}/`));
514
+ compiler.hooks.done.tap("unplugin-https-reverse-proxy", () => {
515
+ consola.success(` ${c.green("\u279C")} ${c.bold("run caddy reverse proxy success")}: ${colorUrl(`${options.https ? "https" : "http"}://${target}`)}`);
516
+ });
517
+ }).catch((e) => {
518
+ throw e;
519
+ });
520
+ },
521
+ async rspack(compiler) {
522
+ var _a, _b, _c;
460
523
  if (process4.env.NODE_ENV !== "development")
461
524
  return;
462
525
  const {
@@ -465,40 +528,30 @@ var unpluginFactory = (options) => ({
465
528
  } = options;
466
529
  if (!enable)
467
530
  return;
531
+ if (!isAdmin()) {
532
+ consola.warn("please run as administrator");
533
+ return;
534
+ }
468
535
  if (!target) {
469
536
  consola.fail("please provide target");
470
537
  return;
471
538
  }
472
- try {
473
- const devServer = __spreadValues(__spreadValues({
474
- host: "localhost",
475
- port: 8080
476
- }, compiler.options.devServer), process4.VUE_CLI_SERVICE.projectOptions.devServer);
477
- const source = `${devServer.host}:${devServer.port}`;
478
- if (caddy)
479
- return;
480
- const _close = (_a = compiler.close) == null ? void 0 : _a.bind(compiler);
481
- if (_close) {
482
- compiler.close = async (callback) => {
483
- process4.on("exit", () => {
484
- _close && _close(callback);
485
- });
486
- };
487
- } else {
488
- options.https = false;
489
- }
490
- caddy = new CaddyInstant();
491
- caddy.run(source, target, __spreadValues({}, options)).then(() => {
492
- const colorUrl = (url) => c.green(url.replace(/:(\d+)\//, (_, port) => `:${c.bold(port)}/`));
493
- compiler.hooks.done.tap("unplugin-https-reverse-proxy", () => {
494
- consola.success(` ${c.green("\u279C")} ${c.bold("run caddy reverse proxy success")}: ${colorUrl(`${options.https ? "https" : "http"}://${target}`)}`);
495
- });
496
- }).catch((e) => {
497
- throw e;
498
- });
499
- } catch (e) {
500
- consola.error(e);
501
- }
539
+ const devServer = __spreadValues(__spreadValues({
540
+ host: "localhost",
541
+ port: 8080
542
+ }, compiler.options.devServer), (_c = (_b = await ((_a = await import("@rsbuild/core")) == null ? void 0 : _a.loadConfig({
543
+ cwd
544
+ }))) == null ? void 0 : _b.content) == null ? void 0 : _c.server);
545
+ const source = `${devServer.host}:${devServer.port}`;
546
+ if (caddy)
547
+ return;
548
+ caddy = new CaddyInstant();
549
+ caddy.run(source, target, __spreadValues({}, options)).then(() => {
550
+ const colorUrl = (url) => c.green(url.replace(/:(\d+)\//, (_, port) => `:${c.bold(port)}/`));
551
+ consola.success(` ${c.green("\u279C")} ${c.bold("run caddy reverse proxy success")}: ${colorUrl(`${options.https ? "https" : "http"}://${target}`)}`);
552
+ }).catch((e) => {
553
+ throw e;
554
+ });
502
555
  }
503
556
  });
504
557
  var unplugin = /* @__PURE__ */ createUnplugin(unpluginFactory);