http-proxy-middleware 4.0.0-beta.0 → 4.0.0-beta.3

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.
Files changed (55) hide show
  1. package/README.md +41 -40
  2. package/dist/configuration.d.ts +3 -2
  3. package/dist/configuration.js +3 -6
  4. package/dist/debug.d.ts +1 -1
  5. package/dist/debug.js +2 -5
  6. package/dist/errors.js +2 -5
  7. package/dist/factory-hono.d.ts +25 -0
  8. package/dist/factory-hono.js +42 -0
  9. package/dist/factory.d.ts +2 -2
  10. package/dist/factory.js +3 -6
  11. package/dist/get-plugins.d.ts +3 -2
  12. package/dist/get-plugins.js +4 -7
  13. package/dist/handlers/fix-request-body.js +18 -7
  14. package/dist/handlers/index.d.ts +1 -1
  15. package/dist/handlers/index.js +1 -17
  16. package/dist/handlers/public.d.ts +2 -2
  17. package/dist/handlers/public.js +2 -7
  18. package/dist/handlers/response-interceptor.js +6 -9
  19. package/dist/http-proxy-middleware.d.ts +4 -3
  20. package/dist/http-proxy-middleware.js +30 -41
  21. package/dist/index.d.ts +5 -8
  22. package/dist/index.js +4 -23
  23. package/dist/logger.d.ts +1 -1
  24. package/dist/logger.js +1 -4
  25. package/dist/path-filter.d.ts +2 -2
  26. package/dist/path-filter.js +7 -11
  27. package/dist/path-rewriter.js +8 -11
  28. package/dist/plugins/default/debug-proxy-errors-plugin.d.ts +1 -1
  29. package/dist/plugins/default/debug-proxy-errors-plugin.js +3 -7
  30. package/dist/plugins/default/error-response-plugin.d.ts +1 -1
  31. package/dist/plugins/default/error-response-plugin.js +5 -9
  32. package/dist/plugins/default/index.d.ts +4 -4
  33. package/dist/plugins/default/index.js +4 -20
  34. package/dist/plugins/default/logger-plugin.d.ts +1 -1
  35. package/dist/plugins/default/logger-plugin.js +8 -12
  36. package/dist/plugins/default/proxy-events.d.ts +1 -1
  37. package/dist/plugins/default/proxy-events.js +5 -9
  38. package/dist/router.js +5 -8
  39. package/dist/status-code.js +1 -4
  40. package/dist/types.d.ts +6 -6
  41. package/dist/types.js +1 -2
  42. package/dist/utils/function.js +1 -4
  43. package/dist/utils/logger-plugin.js +1 -4
  44. package/dist/utils/sanitize.js +1 -4
  45. package/package.json +36 -27
  46. package/dist/legacy/create-proxy-middleware.d.ts +0 -12
  47. package/dist/legacy/create-proxy-middleware.js +0 -16
  48. package/dist/legacy/index.d.ts +0 -1
  49. package/dist/legacy/index.js +0 -17
  50. package/dist/legacy/options-adapter.d.ts +0 -6
  51. package/dist/legacy/options-adapter.js +0 -97
  52. package/dist/legacy/public.d.ts +0 -2
  53. package/dist/legacy/public.js +0 -5
  54. package/dist/legacy/types.d.ts +0 -111
  55. package/dist/legacy/types.js +0 -2
@@ -1,16 +1,13 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.HttpProxyMiddleware = void 0;
4
- const httpxy_1 = require("httpxy");
5
- const configuration_1 = require("./configuration");
6
- const debug_1 = require("./debug");
7
- const get_plugins_1 = require("./get-plugins");
8
- const logger_1 = require("./logger");
9
- const path_filter_1 = require("./path-filter");
10
- const PathRewriter = require("./path-rewriter");
11
- const Router = require("./router");
12
- const function_1 = require("./utils/function");
13
- class HttpProxyMiddleware {
1
+ import { createProxyServer } from 'httpxy';
2
+ import { verifyConfig } from './configuration.js';
3
+ import { Debug as debug } from './debug.js';
4
+ import { getPlugins } from './get-plugins.js';
5
+ import { getLogger } from './logger.js';
6
+ import { matchPathFilter } from './path-filter.js';
7
+ import * as PathRewriter from './path-rewriter.js';
8
+ import * as Router from './router.js';
9
+ import { getFunctionName } from './utils/function.js';
10
+ export class HttpProxyMiddleware {
14
11
  wsInternalSubscribed = false;
15
12
  serverOnCloseSubscribed = false;
16
13
  proxyOptions;
@@ -18,11 +15,11 @@ class HttpProxyMiddleware {
18
15
  pathRewriter;
19
16
  logger;
20
17
  constructor(options) {
21
- (0, configuration_1.verifyConfig)(options);
18
+ verifyConfig(options);
22
19
  this.proxyOptions = options;
23
- this.logger = (0, logger_1.getLogger)(options);
24
- (0, debug_1.Debug)(`create proxy server`);
25
- this.proxy = (0, httpxy_1.createProxyServer)({});
20
+ this.logger = getLogger(options);
21
+ debug(`create proxy server`);
22
+ this.proxy = createProxyServer({});
26
23
  this.registerPlugins(this.proxy, this.proxyOptions);
27
24
  this.pathRewriter = PathRewriter.createPathRewriter(this.proxyOptions.pathRewrite); // returns undefined when "pathRewrite" is not provided
28
25
  // https://github.com/chimurai/http-proxy-middleware/issues/19
@@ -54,7 +51,7 @@ class HttpProxyMiddleware {
54
51
  }
55
52
  try {
56
53
  // Proxying Phase: Handle the actual web request.
57
- (0, debug_1.Debug)(`proxy request to target: %O`, activeProxyOptions.target);
54
+ debug(`proxy request to target: %O`, activeProxyOptions.target);
58
55
  await this.proxy.web(req, res, activeProxyOptions);
59
56
  }
60
57
  catch (err) {
@@ -82,28 +79,28 @@ class HttpProxyMiddleware {
82
79
  const server = req.socket?.server;
83
80
  if (server && !this.serverOnCloseSubscribed) {
84
81
  server.on('close', () => {
85
- (0, debug_1.Debug)('server close signal received: closing proxy server');
82
+ debug('server close signal received: closing proxy server');
86
83
  this.proxy.close(() => {
87
- (0, debug_1.Debug)('proxy server closed');
84
+ debug('proxy server closed');
88
85
  });
89
86
  });
90
87
  this.serverOnCloseSubscribed = true;
91
88
  }
92
- if (this.proxyOptions.ws === true) {
89
+ if (this.proxyOptions.ws === true && server) {
93
90
  // use initial request to access the server object to subscribe to http upgrade event
94
91
  this.catchUpgradeRequest(server);
95
92
  }
96
93
  });
97
94
  registerPlugins(proxy, options) {
98
- const plugins = (0, get_plugins_1.getPlugins)(options);
95
+ const plugins = getPlugins(options);
99
96
  plugins.forEach((plugin) => {
100
- (0, debug_1.Debug)(`register plugin: "${(0, function_1.getFunctionName)(plugin)}"`);
97
+ debug(`register plugin: "${getFunctionName(plugin)}"`);
101
98
  plugin(proxy, options);
102
99
  });
103
100
  }
104
101
  catchUpgradeRequest = (server) => {
105
102
  if (!this.wsInternalSubscribed) {
106
- (0, debug_1.Debug)('subscribing to server upgrade event');
103
+ debug('subscribing to server upgrade event');
107
104
  server.on('upgrade', this.handleUpgrade);
108
105
  // prevent duplicate upgrade handling;
109
106
  // in case external upgrade is also configured
@@ -113,9 +110,10 @@ class HttpProxyMiddleware {
113
110
  handleUpgrade = async (req, socket, head) => {
114
111
  try {
115
112
  if (this.shouldProxy(this.proxyOptions.pathFilter, req)) {
116
- const activeProxyOptions = await this.prepareProxyRequest(req);
117
- await this.proxy.ws(req, socket, activeProxyOptions, head);
118
- (0, debug_1.Debug)('server upgrade event received. Proxying WebSocket');
113
+ const proxiedReq = req;
114
+ const activeProxyOptions = await this.prepareProxyRequest(proxiedReq);
115
+ await this.proxy.ws(proxiedReq, socket, activeProxyOptions, head);
116
+ debug('server upgrade event received. Proxying WebSocket');
119
117
  }
120
118
  }
121
119
  catch (err) {
@@ -136,10 +134,10 @@ class HttpProxyMiddleware {
136
134
  */
137
135
  shouldProxy = (pathFilter, req) => {
138
136
  try {
139
- return (0, path_filter_1.matchPathFilter)(pathFilter, req.url, req);
137
+ return matchPathFilter(pathFilter, req.url, req);
140
138
  }
141
139
  catch (err) {
142
- (0, debug_1.Debug)('Error: matchPathFilter() called with request url: ', `"${req.url}"`);
140
+ debug('Error: matchPathFilter() called with request url: ', `"${req.url}"`);
143
141
  this.logger.error(err);
144
142
  return false;
145
143
  }
@@ -153,14 +151,6 @@ class HttpProxyMiddleware {
153
151
  * @return {Object} proxy options
154
152
  */
155
153
  prepareProxyRequest = async (req) => {
156
- /**
157
- * Incorrect usage confirmed: https://github.com/expressjs/express/issues/4854#issuecomment-1066171160
158
- * Temporary restore req.url patch for {@link src/legacy/create-proxy-middleware.ts legacyCreateProxyMiddleware()}
159
- * FIXME: remove this patch in future release
160
- */
161
- if (this.middleware.__LEGACY_HTTP_PROXY_MIDDLEWARE__) {
162
- req.url = req.originalUrl || req.url;
163
- }
164
154
  const newProxyOptions = Object.assign({}, this.proxyOptions);
165
155
  // Apply in order:
166
156
  // 1. option.router
@@ -175,7 +165,7 @@ class HttpProxyMiddleware {
175
165
  if (options.router) {
176
166
  newTarget = await Router.getTarget(req, options);
177
167
  if (newTarget) {
178
- (0, debug_1.Debug)('router new target: "%s"', newTarget);
168
+ debug('router new target: "%s"', newTarget);
179
169
  options.target = newTarget;
180
170
  }
181
171
  }
@@ -185,13 +175,12 @@ class HttpProxyMiddleware {
185
175
  if (pathRewriter) {
186
176
  const path = await pathRewriter(req.url, req);
187
177
  if (typeof path === 'string') {
188
- (0, debug_1.Debug)('pathRewrite new path: %s', req.url);
178
+ debug('pathRewrite new path: %s', path);
189
179
  req.url = path;
190
180
  }
191
181
  else {
192
- (0, debug_1.Debug)('pathRewrite: no rewritten path found: %s', req.url);
182
+ debug('pathRewrite: no rewritten path found: %s', req.url);
193
183
  }
194
184
  }
195
185
  };
196
186
  }
197
- exports.HttpProxyMiddleware = HttpProxyMiddleware;
package/dist/index.d.ts CHANGED
@@ -1,11 +1,8 @@
1
- export * from './factory';
2
- export * from './handlers';
3
- export type { Plugin, Filter, Options, RequestHandler } from './types';
1
+ export * from './factory.js';
2
+ export * from './factory-hono.js';
3
+ export * from './handlers/index.js';
4
+ export type { Plugin, Filter, Options, RequestHandler } from './types.js';
4
5
  /**
5
6
  * Default plugins
6
7
  */
7
- export * from './plugins/default';
8
- /**
9
- * Legacy exports
10
- */
11
- export * from './legacy';
8
+ export * from './plugins/default/index.js';
package/dist/index.js CHANGED
@@ -1,26 +1,7 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
- for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
- };
16
- Object.defineProperty(exports, "__esModule", { value: true });
17
- __exportStar(require("./factory"), exports);
18
- __exportStar(require("./handlers"), exports);
1
+ export * from './factory.js';
2
+ export * from './factory-hono.js';
3
+ export * from './handlers/index.js';
19
4
  /**
20
5
  * Default plugins
21
6
  */
22
- __exportStar(require("./plugins/default"), exports);
23
- /**
24
- * Legacy exports
25
- */
26
- __exportStar(require("./legacy"), exports);
7
+ export * from './plugins/default/index.js';
package/dist/logger.d.ts CHANGED
@@ -1,2 +1,2 @@
1
- import { Logger, Options } from './types';
1
+ import { Logger, Options } from './types.js';
2
2
  export declare function getLogger(options: Options): Logger;
package/dist/logger.js CHANGED
@@ -1,6 +1,3 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getLogger = getLogger;
4
1
  /**
5
2
  * Compatibility matrix
6
3
  *
@@ -19,6 +16,6 @@ const noopLogger = {
19
16
  warn: () => { },
20
17
  error: () => { },
21
18
  };
22
- function getLogger(options) {
19
+ export function getLogger(options) {
23
20
  return options.logger || noopLogger;
24
21
  }
@@ -1,3 +1,3 @@
1
1
  import type * as http from 'node:http';
2
- import type { Filter } from './types';
3
- export declare function matchPathFilter<TReq = http.IncomingMessage>(pathFilter: Filter<TReq> | undefined, uri: string | undefined, req: http.IncomingMessage): boolean;
2
+ import type { Filter } from './types.js';
3
+ export declare function matchPathFilter<TReq extends http.IncomingMessage = http.IncomingMessage>(pathFilter: Filter<TReq> | undefined, uri: string | undefined, req: http.IncomingMessage): boolean;
@@ -1,11 +1,7 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.matchPathFilter = matchPathFilter;
4
- const url = require("node:url");
5
- const isGlob = require("is-glob");
6
- const micromatch = require("micromatch");
7
- const errors_1 = require("./errors");
8
- function matchPathFilter(pathFilter = '/', uri, req) {
1
+ import isGlob from 'is-glob';
2
+ import micromatch from 'micromatch';
3
+ import { ERRORS } from './errors.js';
4
+ export function matchPathFilter(pathFilter = '/', uri, req) {
9
5
  // single path
10
6
  if (isStringPath(pathFilter)) {
11
7
  return matchSingleStringPath(pathFilter, uri);
@@ -22,14 +18,14 @@ function matchPathFilter(pathFilter = '/', uri, req) {
22
18
  if (pathFilter.every(isGlobPath)) {
23
19
  return matchMultiGlobPath(pathFilter, uri);
24
20
  }
25
- throw new Error(errors_1.ERRORS.ERR_CONTEXT_MATCHER_INVALID_ARRAY);
21
+ throw new Error(ERRORS.ERR_CONTEXT_MATCHER_INVALID_ARRAY);
26
22
  }
27
23
  // custom matching
28
24
  if (typeof pathFilter === 'function') {
29
25
  const pathname = getUrlPathName(uri);
30
26
  return pathFilter(pathname, req);
31
27
  }
32
- throw new Error(errors_1.ERRORS.ERR_CONTEXT_MATCHER_GENERIC);
28
+ throw new Error(ERRORS.ERR_CONTEXT_MATCHER_GENERIC);
33
29
  }
34
30
  /**
35
31
  * @param {String} pathFilter '/api'
@@ -70,7 +66,7 @@ function matchMultiPath(pathFilterList, uri) {
70
66
  * @return {String} RFC 3986 path
71
67
  */
72
68
  function getUrlPathName(uri) {
73
- return uri && url.parse(uri).pathname;
69
+ return uri && new URL(uri, 'http://0.0.0.0').pathname;
74
70
  }
75
71
  function isStringPath(pathFilter) {
76
72
  return typeof pathFilter === 'string' && !isGlob(pathFilter);
@@ -1,17 +1,14 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.createPathRewriter = createPathRewriter;
4
- const is_plain_object_1 = require("is-plain-object");
5
- const debug_1 = require("./debug");
6
- const errors_1 = require("./errors");
7
- const debug = debug_1.Debug.extend('path-rewriter');
1
+ import isPlainObject from 'is-plain-obj';
2
+ import { Debug } from './debug.js';
3
+ import { ERRORS } from './errors.js';
4
+ const debug = Debug.extend('path-rewriter');
8
5
  /**
9
6
  * Create rewrite function, to cache parsed rewrite rules.
10
7
  *
11
8
  * @param {Object} rewriteConfig
12
9
  * @return {Function} Function to rewrite paths; This function should accept `path` (request.url) as parameter
13
10
  */
14
- function createPathRewriter(rewriteConfig) {
11
+ export function createPathRewriter(rewriteConfig) {
15
12
  let rulesCache;
16
13
  if (!isValidRewriteConfig(rewriteConfig)) {
17
14
  return;
@@ -40,19 +37,19 @@ function isValidRewriteConfig(rewriteConfig) {
40
37
  if (typeof rewriteConfig === 'function') {
41
38
  return true;
42
39
  }
43
- else if ((0, is_plain_object_1.isPlainObject)(rewriteConfig)) {
40
+ else if (isPlainObject(rewriteConfig)) {
44
41
  return Object.keys(rewriteConfig).length !== 0;
45
42
  }
46
43
  else if (rewriteConfig === undefined || rewriteConfig === null) {
47
44
  return false;
48
45
  }
49
46
  else {
50
- throw new Error(errors_1.ERRORS.ERR_PATH_REWRITER_CONFIG);
47
+ throw new Error(ERRORS.ERR_PATH_REWRITER_CONFIG);
51
48
  }
52
49
  }
53
50
  function parsePathRewriteRules(rewriteConfig) {
54
51
  const rules = [];
55
- if ((0, is_plain_object_1.isPlainObject)(rewriteConfig)) {
52
+ if (isPlainObject(rewriteConfig)) {
56
53
  for (const [key, value] of Object.entries(rewriteConfig)) {
57
54
  rules.push({
58
55
  regex: new RegExp(key),
@@ -1,4 +1,4 @@
1
- import { Plugin } from '../../types';
1
+ import { Plugin } from '../../types.js';
2
2
  /**
3
3
  * Subscribe to {@link https://www.npmjs.com/package/http-proxy#listening-for-proxy-events http-proxy error events} to prevent server from crashing.
4
4
  * Errors are logged with {@link https://www.npmjs.com/package/debug debug} library.
@@ -1,13 +1,10 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.debugProxyErrorsPlugin = void 0;
4
- const debug_1 = require("../../debug");
5
- const debug = debug_1.Debug.extend('debug-proxy-errors-plugin');
1
+ import { Debug } from '../../debug.js';
2
+ const debug = Debug.extend('debug-proxy-errors-plugin');
6
3
  /**
7
4
  * Subscribe to {@link https://www.npmjs.com/package/http-proxy#listening-for-proxy-events http-proxy error events} to prevent server from crashing.
8
5
  * Errors are logged with {@link https://www.npmjs.com/package/debug debug} library.
9
6
  */
10
- const debugProxyErrorsPlugin = (proxyServer) => {
7
+ export const debugProxyErrorsPlugin = (proxyServer) => {
11
8
  /**
12
9
  * http-proxy doesn't handle any errors by default (https://github.com/http-party/node-http-proxy#listening-for-proxy-events)
13
10
  * Prevent server from crashing when http-proxy errors (uncaught errors)
@@ -58,4 +55,3 @@ const debugProxyErrorsPlugin = (proxyServer) => {
58
55
  debug(`http-proxy econnreset event: \n%O`, error);
59
56
  });
60
57
  };
61
- exports.debugProxyErrorsPlugin = debugProxyErrorsPlugin;
@@ -1,2 +1,2 @@
1
- import { Plugin } from '../../types';
1
+ import { Plugin } from '../../types.js';
2
2
  export declare const errorResponsePlugin: Plugin;
@@ -1,15 +1,12 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.errorResponsePlugin = void 0;
4
- const status_code_1 = require("../../status-code");
5
- const sanitize_1 = require("../../utils/sanitize");
1
+ import { getStatusCode } from '../../status-code.js';
2
+ import { sanitize } from '../../utils/sanitize.js';
6
3
  function isResponseLike(obj) {
7
4
  return obj && typeof obj.writeHead === 'function';
8
5
  }
9
6
  function isSocketLike(obj) {
10
7
  return obj && typeof obj.write === 'function' && !('writeHead' in obj);
11
8
  }
12
- const errorResponsePlugin = (proxyServer, options) => {
9
+ export const errorResponsePlugin = (proxyServer, options) => {
13
10
  proxyServer.on('error', (err, req, res, target) => {
14
11
  // Re-throw error. Not recoverable since req & res are empty.
15
12
  if (!req || !res) {
@@ -17,15 +14,14 @@ const errorResponsePlugin = (proxyServer, options) => {
17
14
  }
18
15
  if (isResponseLike(res)) {
19
16
  if (!res.headersSent) {
20
- const statusCode = (0, status_code_1.getStatusCode)(err.code);
17
+ const statusCode = getStatusCode(err.code);
21
18
  res.writeHead(statusCode);
22
19
  }
23
20
  const host = req.headers && req.headers.host;
24
- res.end(`Error occurred while trying to proxy: ${(0, sanitize_1.sanitize)(host)}${(0, sanitize_1.sanitize)(req.url)}`);
21
+ res.end(`Error occurred while trying to proxy: ${sanitize(host)}${sanitize(req.url)}`);
25
22
  }
26
23
  else if (isSocketLike(res)) {
27
24
  res.destroy();
28
25
  }
29
26
  });
30
27
  };
31
- exports.errorResponsePlugin = errorResponsePlugin;
@@ -1,4 +1,4 @@
1
- export * from './debug-proxy-errors-plugin';
2
- export * from './error-response-plugin';
3
- export * from './logger-plugin';
4
- export * from './proxy-events';
1
+ export * from './debug-proxy-errors-plugin.js';
2
+ export * from './error-response-plugin.js';
3
+ export * from './logger-plugin.js';
4
+ export * from './proxy-events.js';
@@ -1,20 +1,4 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
- for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
- };
16
- Object.defineProperty(exports, "__esModule", { value: true });
17
- __exportStar(require("./debug-proxy-errors-plugin"), exports);
18
- __exportStar(require("./error-response-plugin"), exports);
19
- __exportStar(require("./logger-plugin"), exports);
20
- __exportStar(require("./proxy-events"), exports);
1
+ export * from './debug-proxy-errors-plugin.js';
2
+ export * from './error-response-plugin.js';
3
+ export * from './logger-plugin.js';
4
+ export * from './proxy-events.js';
@@ -1,2 +1,2 @@
1
- import { Plugin } from '../../types';
1
+ import { Plugin } from '../../types.js';
2
2
  export declare const loggerPlugin: Plugin;
@@ -1,11 +1,8 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.loggerPlugin = void 0;
4
- const node_url_1 = require("node:url");
5
- const logger_1 = require("../../logger");
6
- const logger_plugin_1 = require("../../utils/logger-plugin");
7
- const loggerPlugin = (proxyServer, options) => {
8
- const logger = (0, logger_1.getLogger)(options);
1
+ import { URL } from 'node:url';
2
+ import { getLogger } from '../../logger.js';
3
+ import { getPort } from '../../utils/logger-plugin.js';
4
+ export const loggerPlugin = (proxyServer, options) => {
5
+ const logger = getLogger(options);
9
6
  proxyServer.on('error', (err, req, res, target) => {
10
7
  const hostname = req?.headers?.host;
11
8
  const requestHref = `${hostname}${req?.url}`;
@@ -28,13 +25,13 @@ const loggerPlugin = (proxyServer, options) => {
28
25
  // construct targetUrl
29
26
  let target;
30
27
  try {
31
- const port = (0, logger_plugin_1.getPort)(proxyRes.req?.agent?.sockets);
28
+ const port = getPort(proxyRes.req?.agent?.sockets);
32
29
  const obj = {
33
30
  protocol: proxyRes.req.protocol,
34
31
  host: proxyRes.req.host,
35
32
  pathname: proxyRes.req.path,
36
33
  };
37
- target = new node_url_1.URL(`${obj.protocol}//${obj.host}${obj.pathname}`);
34
+ target = new URL(`${obj.protocol}//${obj.host}${obj.pathname}`);
38
35
  if (port) {
39
36
  target.port = port;
40
37
  }
@@ -43,7 +40,7 @@ const loggerPlugin = (proxyServer, options) => {
43
40
  catch (err) {
44
41
  // nock issue (https://github.com/chimurai/http-proxy-middleware/issues/1035)
45
42
  // fallback to old implementation (less correct - without port)
46
- target = new node_url_1.URL(options.target);
43
+ target = new URL(options.target);
47
44
  target.pathname = proxyRes.req.path;
48
45
  }
49
46
  const targetUrl = target.toString();
@@ -63,4 +60,3 @@ const loggerPlugin = (proxyServer, options) => {
63
60
  logger.info('[HPM] Client disconnected: %o', proxySocket.address());
64
61
  });
65
62
  };
66
- exports.loggerPlugin = loggerPlugin;
@@ -1,4 +1,4 @@
1
- import { Plugin } from '../../types';
1
+ import { Plugin } from '../../types.js';
2
2
  /**
3
3
  * Implements option.on object to subscribe to http-proxy events.
4
4
  *
@@ -1,9 +1,6 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.proxyEventsPlugin = void 0;
4
- const debug_1 = require("../../debug");
5
- const function_1 = require("../../utils/function");
6
- const debug = debug_1.Debug.extend('proxy-events-plugin');
1
+ import { Debug } from '../../debug.js';
2
+ import { getFunctionName } from '../../utils/function.js';
3
+ const debug = Debug.extend('proxy-events-plugin');
7
4
  /**
8
5
  * Implements option.on object to subscribe to http-proxy events.
9
6
  *
@@ -24,7 +21,7 @@ const debug = debug_1.Debug.extend('proxy-events-plugin');
24
21
  * });
25
22
  * ```
26
23
  */
27
- const proxyEventsPlugin = (proxyServer, options) => {
24
+ export const proxyEventsPlugin = (proxyServer, options) => {
28
25
  if (!options.on) {
29
26
  return;
30
27
  }
@@ -37,9 +34,8 @@ const proxyEventsPlugin = (proxyServer, options) => {
37
34
  if (!handler) {
38
35
  continue;
39
36
  }
40
- debug(`register event handler: "${eventName}" -> "${(0, function_1.getFunctionName)(handler)}"`);
37
+ debug(`register event handler: "${eventName}" -> "${getFunctionName(handler)}"`);
41
38
  proxyServer.on(eventName, handler);
42
39
  }
43
40
  }
44
41
  };
45
- exports.proxyEventsPlugin = proxyEventsPlugin;
package/dist/router.js CHANGED
@@ -1,13 +1,10 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getTarget = getTarget;
4
- const is_plain_object_1 = require("is-plain-object");
5
- const debug_1 = require("./debug");
6
- const debug = debug_1.Debug.extend('router');
7
- async function getTarget(req, config) {
1
+ import isPlainObject from 'is-plain-obj';
2
+ import { Debug } from './debug.js';
3
+ const debug = Debug.extend('router');
4
+ export async function getTarget(req, config) {
8
5
  let newTarget;
9
6
  const router = config.router;
10
- if ((0, is_plain_object_1.isPlainObject)(router)) {
7
+ if (isPlainObject(router)) {
11
8
  newTarget = getTargetFromProxyTable(req, router);
12
9
  }
13
10
  else if (typeof router === 'function') {
@@ -1,7 +1,4 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getStatusCode = getStatusCode;
4
- function getStatusCode(errorCode) {
1
+ export function getStatusCode(errorCode) {
5
2
  let statusCode;
6
3
  if (/HPE_INVALID/.test(errorCode)) {
7
4
  statusCode = 502;
package/dist/types.d.ts CHANGED
@@ -6,19 +6,19 @@ import type * as http from 'node:http';
6
6
  import type * as net from 'node:net';
7
7
  import type { ProxyServer, ProxyServerOptions } from 'httpxy';
8
8
  export type NextFunction<T = (err?: any) => void> = T;
9
- export interface RequestHandler<TReq = http.IncomingMessage, TRes = http.ServerResponse, TNext = NextFunction> {
9
+ export interface RequestHandler<TReq extends http.IncomingMessage = http.IncomingMessage, TRes extends http.ServerResponse = http.ServerResponse, TNext = NextFunction> {
10
10
  (req: TReq, res: TRes, next?: TNext): Promise<void>;
11
11
  upgrade: (req: http.IncomingMessage, socket: net.Socket, head: Buffer) => void;
12
12
  }
13
- export type Filter<TReq = http.IncomingMessage> = string | string[] | ((pathname: string, req: TReq) => boolean);
14
- export interface Plugin<TReq = http.IncomingMessage, TRes = http.ServerResponse> {
13
+ export type Filter<TReq extends http.IncomingMessage = http.IncomingMessage> = string | string[] | ((pathname: string, req: TReq) => boolean);
14
+ export interface Plugin<TReq extends http.IncomingMessage = http.IncomingMessage, TRes extends http.ServerResponse = http.ServerResponse> {
15
15
  (proxyServer: ProxyServer<TReq, TRes>, options: Options<TReq, TRes>): void;
16
16
  }
17
- export interface OnProxyEvent<TReq = http.IncomingMessage, TRes = http.ServerResponse> {
17
+ export interface OnProxyEvent<TReq extends http.IncomingMessage = http.IncomingMessage, TRes extends http.ServerResponse = http.ServerResponse> {
18
18
  error?: (err: Error, req: TReq, res: TRes | net.Socket, target?: string | Partial<URL>) => void;
19
19
  proxyReq?: (proxyReq: http.ClientRequest, req: TReq, res: TRes, options: ProxyServerOptions) => void;
20
20
  proxyReqWs?: (proxyReq: http.ClientRequest, req: TReq, socket: net.Socket, options: ProxyServerOptions, head: any) => void;
21
- proxyRes?: (proxyRes: TReq, req: TReq, res: TRes) => void;
21
+ proxyRes?: (proxyRes: TReq, req: TReq, res: TRes) => void | Promise<void>;
22
22
  open?: (proxySocket: net.Socket) => void;
23
23
  close?: (proxyRes: TReq, proxySocket: net.Socket, proxyHead: any) => void;
24
24
  start?: (req: TReq, res: TRes, target: string | Partial<URL>) => void;
@@ -26,7 +26,7 @@ export interface OnProxyEvent<TReq = http.IncomingMessage, TRes = http.ServerRes
26
26
  econnreset?: (err: Error, req: TReq, res: TRes, target: string | Partial<URL>) => void;
27
27
  }
28
28
  export type Logger = Pick<Console, 'info' | 'warn' | 'error'>;
29
- export interface Options<TReq = http.IncomingMessage, TRes = http.ServerResponse> extends ProxyServerOptions {
29
+ export interface Options<TReq extends http.IncomingMessage = http.IncomingMessage, TRes extends http.ServerResponse = http.ServerResponse> extends ProxyServerOptions {
30
30
  /**
31
31
  * Narrow down requests to proxy or not.
32
32
  * Filter on {@link http.IncomingMessage.url `pathname`} which is relative to the proxy's "mounting" point in the server.
package/dist/types.js CHANGED
@@ -1,2 +1 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
1
+ export {};
@@ -1,7 +1,4 @@
1
- "use strict";
2
1
  /* eslint-disable @typescript-eslint/no-unsafe-function-type */
3
- Object.defineProperty(exports, "__esModule", { value: true });
4
- exports.getFunctionName = getFunctionName;
5
- function getFunctionName(fn) {
2
+ export function getFunctionName(fn) {
6
3
  return fn.name || '[anonymous Function]';
7
4
  }
@@ -1,10 +1,7 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getPort = getPort;
4
1
  /**
5
2
  * Get port from target
6
3
  * Using proxyRes.req.agent.sockets to determine the target port
7
4
  */
8
- function getPort(sockets) {
5
+ export function getPort(sockets) {
9
6
  return Object.keys(sockets || {})?.[0]?.split(':')[1];
10
7
  }
@@ -1,6 +1,3 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.sanitize = sanitize;
4
- function sanitize(input) {
1
+ export function sanitize(input) {
5
2
  return input?.replace(/[<>]/g, (i) => encodeURIComponent(i)) ?? '';
6
3
  }