http-proxy-middleware 0.20.0 → 0.21.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/CHANGELOG.md CHANGED
@@ -1,5 +1,12 @@
1
1
  # Changelog
2
2
 
3
+ ## [v0.21.0](https://github.com/chimurai/http-proxy-middleware/releases/tag/v0.21.0)
4
+
5
+ - feat(http-proxy): bump to v1.18.0
6
+ - feat: async router ([#379](https://github.com/chimurai/http-proxy-middleware/issues/335)) ([LiranBri](https://github.com/LiranBri))
7
+ - feat(typescript): types support ([#369](https://github.com/chimurai/http-proxy-middleware/pull/369))
8
+ - feat: async pathRewrite ([#397](https://github.com/chimurai/http-proxy-middleware/pull/397)) ([rsethc](https://github.com/rsethc))
9
+
3
10
  ## [v0.20.0](https://github.com/chimurai/http-proxy-middleware/releases/tag/v0.20.0)
4
11
 
5
12
  - fix(ws): concurrent websocket requests do not get upgraded ([#335](https://github.com/chimurai/http-proxy-middleware/issues/335))
package/README.md CHANGED
@@ -199,6 +199,14 @@ Providing an alternative way to decide which requests should be proxied; In case
199
199
 
200
200
  // custom rewriting
201
201
  pathRewrite: function (path, req) { return path.replace('/api', '/base/api') }
202
+
203
+ // custom rewriting, returning Promise
204
+ pathRewrite: async function (path, req) {
205
+ var should_add_something = await httpRequestToDecideSomething(path);
206
+ if (should_add_something) path += "something";
207
+ return path;
208
+ }
209
+
202
210
  ```
203
211
 
204
212
  - **option.router**: object/function, re-target `option.target` for specific requests.
@@ -217,6 +225,12 @@ Providing an alternative way to decide which requests should be proxied; In case
217
225
  router: function(req) {
218
226
  return 'http://localhost:8004';
219
227
  }
228
+
229
+ // Asynchronous router function which returns promise
230
+ router: async function(req) {
231
+ const url = await doSomeIO();
232
+ return url;
233
+ }
220
234
  ```
221
235
 
222
236
  - **option.logLevel**: string, ['debug', 'info', 'warn', 'error', 'silent']. Default: `'info'`
@@ -234,7 +248,7 @@ Providing an alternative way to decide which requests should be proxied; In case
234
248
  ```javascript
235
249
  // verbose replacement
236
250
  function logProvider(provider) {
237
- var logger = new (require('winston')).Logger();
251
+ var logger = new (require('winston').Logger)();
238
252
 
239
253
  var myCustomProvider = {
240
254
  log: logger.log,
@@ -495,4 +509,4 @@ $ yarn cover
495
509
 
496
510
  The MIT License (MIT)
497
511
 
498
- Copyright (c) 2015-2019 Steven Chim
512
+ Copyright (c) 2015-2020 Steven Chim
@@ -0,0 +1,5 @@
1
+ import { Options } from './types';
2
+ export declare function createConfig(context: any, opts?: any): {
3
+ context: any;
4
+ options: Options;
5
+ };
@@ -1,7 +1,10 @@
1
1
  "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
2
5
  Object.defineProperty(exports, "__esModule", { value: true });
3
- const _ = require("lodash");
4
- const url = require("url");
6
+ const lodash_1 = __importDefault(require("lodash"));
7
+ const url_1 = __importDefault(require("url"));
5
8
  const errors_1 = require("./errors");
6
9
  const logger_1 = require("./logger");
7
10
  const logger = logger_1.getInstance();
@@ -14,15 +17,15 @@ function createConfig(context, opts) {
14
17
  // app.use('/api', proxy({target:'http://localhost:9000'}));
15
18
  if (isContextless(context, opts)) {
16
19
  config.context = '/';
17
- config.options = _.assign(config.options, context);
20
+ config.options = lodash_1.default.assign(config.options, context);
18
21
  // app.use('/api', proxy('http://localhost:9000'));
19
22
  // app.use(proxy('http://localhost:9000/api'));
20
23
  }
21
24
  else if (isStringShortHand(context)) {
22
- const oUrl = url.parse(context);
25
+ const oUrl = url_1.default.parse(context);
23
26
  const target = [oUrl.protocol, '//', oUrl.host].join('');
24
27
  config.context = oUrl.pathname || '/';
25
- config.options = _.assign(config.options, { target }, opts);
28
+ config.options = lodash_1.default.assign(config.options, { target }, opts);
26
29
  if (oUrl.protocol === 'ws:' || oUrl.protocol === 'wss:') {
27
30
  config.options.ws = true;
28
31
  }
@@ -30,7 +33,7 @@ function createConfig(context, opts) {
30
33
  }
31
34
  else {
32
35
  config.context = context;
33
- config.options = _.assign(config.options, opts);
36
+ config.options = lodash_1.default.assign(config.options, opts);
34
37
  }
35
38
  configureLogger(config.options);
36
39
  if (!config.options.target) {
@@ -51,8 +54,8 @@ exports.createConfig = createConfig;
51
54
  * @return {Boolean} [description]
52
55
  */
53
56
  function isStringShortHand(context) {
54
- if (_.isString(context)) {
55
- return !!url.parse(context).host;
57
+ if (lodash_1.default.isString(context)) {
58
+ return !!url_1.default.parse(context).host;
56
59
  }
57
60
  }
58
61
  /**
@@ -67,7 +70,7 @@ function isStringShortHand(context) {
67
70
  * @return {Boolean} [description]
68
71
  */
69
72
  function isContextless(context, opts) {
70
- return _.isPlainObject(context) && _.isEmpty(opts);
73
+ return lodash_1.default.isPlainObject(context) && lodash_1.default.isEmpty(opts);
71
74
  }
72
75
  function configureLogger(options) {
73
76
  if (options.logLevel) {
@@ -0,0 +1 @@
1
+ export declare function match(context: any, uri: any, req: any): any;
@@ -1,9 +1,12 @@
1
1
  "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
2
5
  Object.defineProperty(exports, "__esModule", { value: true });
3
- const isGlob = require("is-glob");
4
- const _ = require("lodash");
5
- const micromatch = require("micromatch");
6
- const url = require("url");
6
+ const is_glob_1 = __importDefault(require("is-glob"));
7
+ const lodash_1 = __importDefault(require("lodash"));
8
+ const micromatch_1 = __importDefault(require("micromatch"));
9
+ const url_1 = __importDefault(require("url"));
7
10
  const errors_1 = require("./errors");
8
11
  function match(context, uri, req) {
9
12
  // single path
@@ -25,7 +28,7 @@ function match(context, uri, req) {
25
28
  throw new Error(errors_1.ERRORS.ERR_CONTEXT_MATCHER_INVALID_ARRAY);
26
29
  }
27
30
  // custom matching
28
- if (_.isFunction(context)) {
31
+ if (lodash_1.default.isFunction(context)) {
29
32
  const pathname = getUrlPathName(uri);
30
33
  return context(pathname, req);
31
34
  }
@@ -43,7 +46,7 @@ function matchSingleStringPath(context, uri) {
43
46
  }
44
47
  function matchSingleGlobPath(pattern, uri) {
45
48
  const pathname = getUrlPathName(uri);
46
- const matches = micromatch([pathname], pattern);
49
+ const matches = micromatch_1.default([pathname], pattern);
47
50
  return matches && matches.length > 0;
48
51
  }
49
52
  function matchMultiGlobPath(patternList, uri) {
@@ -71,11 +74,11 @@ function matchMultiPath(contextList, uri) {
71
74
  * @return {String} RFC 3986 path
72
75
  */
73
76
  function getUrlPathName(uri) {
74
- return uri && url.parse(uri).pathname;
77
+ return uri && url_1.default.parse(uri).pathname;
75
78
  }
76
79
  function isStringPath(context) {
77
- return _.isString(context) && !isGlob(context);
80
+ return lodash_1.default.isString(context) && !is_glob_1.default(context);
78
81
  }
79
82
  function isGlobPath(context) {
80
- return isGlob(context);
83
+ return is_glob_1.default(context);
81
84
  }
@@ -0,0 +1,6 @@
1
+ export declare enum ERRORS {
2
+ ERR_CONFIG_FACTORY_TARGET_MISSING = "[HPM] Missing \"target\" option. Example: {target: \"http://www.example.org\"}",
3
+ ERR_CONTEXT_MATCHER_GENERIC = "[HPM] Invalid context. Expecting something like: \"/api\" or [\"/api\", \"/ajax\"]",
4
+ ERR_CONTEXT_MATCHER_INVALID_ARRAY = "[HPM] Invalid context. Expecting something like: [\"/api\", \"/ajax\"] or [\"/api/**\", \"!**.html\"]",
5
+ ERR_PATH_REWRITER_CONFIG = "[HPM] Invalid pathRewrite config. Expecting object with pathRewrite config or a rewrite function"
6
+ }
@@ -0,0 +1,2 @@
1
+ export declare function init(proxy: any, option: any): void;
2
+ export declare function getHandlers(options: any): any;
package/dist/handlers.js CHANGED
@@ -1,6 +1,9 @@
1
1
  "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
2
5
  Object.defineProperty(exports, "__esModule", { value: true });
3
- const _ = require("lodash");
6
+ const lodash_1 = __importDefault(require("lodash"));
4
7
  const logger_1 = require("./logger");
5
8
  const logger = logger_1.getInstance();
6
9
  function init(proxy, option) {
@@ -26,18 +29,18 @@ function getHandlers(options) {
26
29
  // all handlers for the http-proxy events are prefixed with 'on'.
27
30
  // loop through options and try to find these handlers
28
31
  // and add them to the handlers object for subscription in init().
29
- const eventName = _.camelCase('on ' + event);
30
- const fnHandler = _.get(options, eventName);
31
- if (_.isFunction(fnHandler)) {
32
+ const eventName = lodash_1.default.camelCase('on ' + event);
33
+ const fnHandler = lodash_1.default.get(options, eventName);
34
+ if (lodash_1.default.isFunction(fnHandler)) {
32
35
  handlers[event] = fnHandler;
33
36
  }
34
37
  }
35
38
  // add default error handler in absence of error handler
36
- if (!_.isFunction(handlers.error)) {
39
+ if (!lodash_1.default.isFunction(handlers.error)) {
37
40
  handlers.error = defaultErrorHandler;
38
41
  }
39
42
  // add default close handler in absence of close handler
40
- if (!_.isFunction(handlers.close)) {
43
+ if (!lodash_1.default.isFunction(handlers.close)) {
41
44
  handlers.close = logClose;
42
45
  }
43
46
  return handlers;
@@ -0,0 +1,34 @@
1
+ import { Filter, IRequestHandler, Options } from './types';
2
+ export declare class HttpProxyMiddleware {
3
+ private logger;
4
+ private config;
5
+ private wsInternalSubscribed;
6
+ private proxyOptions;
7
+ private proxy;
8
+ private pathRewriter;
9
+ constructor(context: Filter | Options, opts?: Options);
10
+ middleware: IRequestHandler;
11
+ private catchUpgradeRequest;
12
+ private handleUpgrade;
13
+ /**
14
+ * Determine whether request should be proxied.
15
+ *
16
+ * @private
17
+ * @param {String} context [description]
18
+ * @param {Object} req [description]
19
+ * @return {Boolean}
20
+ */
21
+ private shouldProxy;
22
+ /**
23
+ * Apply option.router and option.pathRewrite
24
+ * Order matters:
25
+ * Router uses original path for routing;
26
+ * NOT the modified path, after it has been rewritten by pathRewrite
27
+ * @param {Object} req
28
+ * @return {Object} proxy options
29
+ */
30
+ private prepareProxyRequest;
31
+ private applyRouter;
32
+ private applyPathRewrite;
33
+ private logError;
34
+ }
@@ -1,21 +1,32 @@
1
1
  "use strict";
2
2
  var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
4
  return new (P || (P = Promise))(function (resolve, reject) {
4
5
  function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
6
  function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
- function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
8
  step((generator = generator.apply(thisArg, _arguments || [])).next());
8
9
  });
9
10
  };
11
+ var __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
14
+ var __importStar = (this && this.__importStar) || function (mod) {
15
+ if (mod && mod.__esModule) return mod;
16
+ var result = {};
17
+ if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
18
+ result["default"] = mod;
19
+ return result;
20
+ };
10
21
  Object.defineProperty(exports, "__esModule", { value: true });
11
- const httpProxy = require("http-proxy");
12
- const _ = require("lodash");
22
+ const http_proxy_1 = __importDefault(require("http-proxy"));
23
+ const lodash_1 = __importDefault(require("lodash"));
13
24
  const config_factory_1 = require("./config-factory");
14
- const contextMatcher = require("./context-matcher");
15
- const handlers = require("./handlers");
25
+ const contextMatcher = __importStar(require("./context-matcher"));
26
+ const handlers = __importStar(require("./handlers"));
16
27
  const logger_1 = require("./logger");
17
- const PathRewriter = require("./path-rewriter");
18
- const Router = require("./router");
28
+ const PathRewriter = __importStar(require("./path-rewriter"));
29
+ const Router = __importStar(require("./router"));
19
30
  class HttpProxyMiddleware {
20
31
  constructor(context, opts) {
21
32
  this.logger = logger_1.getInstance();
@@ -23,7 +34,7 @@ class HttpProxyMiddleware {
23
34
  // https://github.com/Microsoft/TypeScript/wiki/'this'-in-TypeScript#red-flags-for-this
24
35
  this.middleware = (req, res, next) => __awaiter(this, void 0, void 0, function* () {
25
36
  if (this.shouldProxy(this.config.context, req)) {
26
- const activeProxyOptions = this.prepareProxyRequest(req);
37
+ const activeProxyOptions = yield this.prepareProxyRequest(req);
27
38
  this.proxy.web(req, res, activeProxyOptions);
28
39
  }
29
40
  else {
@@ -42,13 +53,13 @@ class HttpProxyMiddleware {
42
53
  this.wsInternalSubscribed = true;
43
54
  }
44
55
  };
45
- this.handleUpgrade = (req, socket, head) => {
56
+ this.handleUpgrade = (req, socket, head) => __awaiter(this, void 0, void 0, function* () {
46
57
  if (this.shouldProxy(this.config.context, req)) {
47
- const activeProxyOptions = this.prepareProxyRequest(req);
58
+ const activeProxyOptions = yield this.prepareProxyRequest(req);
48
59
  this.proxy.ws(req, socket, head, activeProxyOptions);
49
60
  this.logger.info('[HPM] Upgrading to WebSocket');
50
61
  }
51
- };
62
+ });
52
63
  /**
53
64
  * Determine whether request should be proxied.
54
65
  *
@@ -69,40 +80,40 @@ class HttpProxyMiddleware {
69
80
  * @param {Object} req
70
81
  * @return {Object} proxy options
71
82
  */
72
- this.prepareProxyRequest = req => {
83
+ this.prepareProxyRequest = (req) => __awaiter(this, void 0, void 0, function* () {
73
84
  // https://github.com/chimurai/http-proxy-middleware/issues/17
74
85
  // https://github.com/chimurai/http-proxy-middleware/issues/94
75
86
  req.url = req.originalUrl || req.url;
76
87
  // store uri before it gets rewritten for logging
77
88
  const originalPath = req.url;
78
- const newProxyOptions = _.assign({}, this.proxyOptions);
89
+ const newProxyOptions = lodash_1.default.assign({}, this.proxyOptions);
79
90
  // Apply in order:
80
91
  // 1. option.router
81
92
  // 2. option.pathRewrite
82
- this.applyRouter(req, newProxyOptions);
83
- this.applyPathRewrite(req, this.pathRewriter);
93
+ yield this.applyRouter(req, newProxyOptions);
94
+ yield this.applyPathRewrite(req, this.pathRewriter);
84
95
  // debug logging for both http(s) and websockets
85
96
  if (this.proxyOptions.logLevel === 'debug') {
86
97
  const arrow = logger_1.getArrow(originalPath, req.url, this.proxyOptions.target, newProxyOptions.target);
87
98
  this.logger.debug('[HPM] %s %s %s %s', req.method, originalPath, arrow, newProxyOptions.target);
88
99
  }
89
100
  return newProxyOptions;
90
- };
101
+ });
91
102
  // Modify option.target when router present.
92
- this.applyRouter = (req, options) => {
103
+ this.applyRouter = (req, options) => __awaiter(this, void 0, void 0, function* () {
93
104
  let newTarget;
94
105
  if (options.router) {
95
- newTarget = Router.getTarget(req, options);
106
+ newTarget = yield Router.getTarget(req, options);
96
107
  if (newTarget) {
97
108
  this.logger.debug('[HPM] Router new target: %s -> "%s"', options.target, newTarget);
98
109
  options.target = newTarget;
99
110
  }
100
111
  }
101
- };
112
+ });
102
113
  // rewrite path
103
- this.applyPathRewrite = (req, pathRewriter) => {
114
+ this.applyPathRewrite = (req, pathRewriter) => __awaiter(this, void 0, void 0, function* () {
104
115
  if (pathRewriter) {
105
- const path = pathRewriter(req.url, req);
116
+ const path = yield pathRewriter(req.url, req);
106
117
  if (typeof path === 'string') {
107
118
  req.url = path;
108
119
  }
@@ -110,9 +121,9 @@ class HttpProxyMiddleware {
110
121
  this.logger.info('[HPM] pathRewrite: No rewritten path found. (%s)', req.url);
111
122
  }
112
123
  }
113
- };
124
+ });
114
125
  this.logError = (err, req, res) => {
115
- const hostname = (req.headers && req.headers.host) || (req.hostname || req.host); // (websocket) || (node0.10 || node 4/5)
126
+ const hostname = (req.headers && req.headers.host) || req.hostname || req.host; // (websocket) || (node0.10 || node 4/5)
116
127
  const target = this.proxyOptions.target.host || this.proxyOptions.target;
117
128
  const errorMessage = '[HPM] Error occurred while trying to proxy request %s from %s to %s (%s) (%s)';
118
129
  const errReference = 'https://nodejs.org/api/errors.html#errors_common_system_errors'; // link to Node Common Systems Errors page
@@ -121,7 +132,7 @@ class HttpProxyMiddleware {
121
132
  this.config = config_factory_1.createConfig(context, opts);
122
133
  this.proxyOptions = this.config.options;
123
134
  // create proxy
124
- this.proxy = httpProxy.createProxyServer({});
135
+ this.proxy = http_proxy_1.default.createProxyServer({});
125
136
  this.logger.info(`[HPM] Proxy created: ${this.config.context} -> ${this.proxyOptions.target}`);
126
137
  this.pathRewriter = PathRewriter.createPathRewriter(this.proxyOptions.pathRewrite); // returns undefined when "pathRewrite" is not provided
127
138
  // attach handler to http-proxy events
@@ -0,0 +1,3 @@
1
+ import { Filter, Options } from './types';
2
+ declare function middleware(context: Filter | Options, options?: Options): import("./types").IRequestHandler;
3
+ export = middleware;
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  "use strict";
2
2
  const http_proxy_middleware_1 = require("./http-proxy-middleware");
3
- function proxy(context, opts) {
4
- const { middleware } = new http_proxy_middleware_1.HttpProxyMiddleware(context, opts);
3
+ function middleware(context, options) {
4
+ const { middleware } = new http_proxy_middleware_1.HttpProxyMiddleware(context, options);
5
5
  return middleware;
6
6
  }
7
- module.exports = proxy;
7
+ module.exports = middleware;
@@ -0,0 +1,14 @@
1
+ export declare function getInstance(): any;
2
+ /**
3
+ * -> normal proxy
4
+ * => router
5
+ * ~> pathRewrite
6
+ * ≈> router + pathRewrite
7
+ *
8
+ * @param {String} originalPath
9
+ * @param {String} newPath
10
+ * @param {String} originalTarget
11
+ * @param {String} newTarget
12
+ * @return {String}
13
+ */
14
+ export declare function getArrow(originalPath: any, newPath: any, originalTarget: any, newTarget: any): string;
package/dist/logger.js CHANGED
@@ -1,7 +1,10 @@
1
1
  "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
2
5
  Object.defineProperty(exports, "__esModule", { value: true });
3
- const _ = require("lodash");
4
- const util = require("util");
6
+ const lodash_1 = __importDefault(require("lodash"));
7
+ const util_1 = __importDefault(require("util"));
5
8
  let loggerInstance;
6
9
  const defaultProvider = {
7
10
  // tslint:disable: no-console
@@ -68,7 +71,7 @@ class Logger {
68
71
  }
69
72
  isValidProvider(fnProvider) {
70
73
  const result = true;
71
- if (fnProvider && !_.isFunction(fnProvider)) {
74
+ if (fnProvider && !lodash_1.default.isFunction(fnProvider)) {
72
75
  throw new Error('[HPM] Log provider config error. Expecting a function.');
73
76
  }
74
77
  return result;
@@ -97,8 +100,8 @@ class Logger {
97
100
  // make sure logged messages and its data are return interpolated
98
101
  // make it possible for additional log data, such date/time or custom prefix.
99
102
  _interpolate() {
100
- const fn = _.spread(util.format);
101
- const result = fn(_.slice(arguments));
103
+ const fn = lodash_1.default.spread(util_1.default.format);
104
+ const result = fn(lodash_1.default.slice(arguments));
102
105
  return result;
103
106
  }
104
107
  }
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Create rewrite function, to cache parsed rewrite rules.
3
+ *
4
+ * @param {Object} rewriteConfig
5
+ * @return {Function} Function to rewrite paths; This function should accept `path` (request.url) as parameter
6
+ */
7
+ export declare function createPathRewriter(rewriteConfig: any): (...args: any[]) => any;
@@ -1,6 +1,9 @@
1
1
  "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
2
5
  Object.defineProperty(exports, "__esModule", { value: true });
3
- const _ = require("lodash");
6
+ const lodash_1 = __importDefault(require("lodash"));
4
7
  const errors_1 = require("./errors");
5
8
  const logger_1 = require("./logger");
6
9
  const logger = logger_1.getInstance();
@@ -15,7 +18,7 @@ function createPathRewriter(rewriteConfig) {
15
18
  if (!isValidRewriteConfig(rewriteConfig)) {
16
19
  return;
17
20
  }
18
- if (_.isFunction(rewriteConfig)) {
21
+ if (lodash_1.default.isFunction(rewriteConfig)) {
19
22
  const customRewriteFn = rewriteConfig;
20
23
  return customRewriteFn;
21
24
  }
@@ -25,7 +28,7 @@ function createPathRewriter(rewriteConfig) {
25
28
  }
26
29
  function rewritePath(path) {
27
30
  let result = path;
28
- _.forEach(rulesCache, rule => {
31
+ lodash_1.default.forEach(rulesCache, rule => {
29
32
  if (rule.regex.test(path)) {
30
33
  result = result.replace(rule.regex, rule.value);
31
34
  logger.debug('[HPM] Rewriting path from "%s" to "%s"', path, result);
@@ -37,15 +40,15 @@ function createPathRewriter(rewriteConfig) {
37
40
  }
38
41
  exports.createPathRewriter = createPathRewriter;
39
42
  function isValidRewriteConfig(rewriteConfig) {
40
- if (_.isFunction(rewriteConfig)) {
43
+ if (lodash_1.default.isFunction(rewriteConfig)) {
41
44
  return true;
42
45
  }
43
- else if (!_.isEmpty(rewriteConfig) && _.isPlainObject(rewriteConfig)) {
46
+ else if (!lodash_1.default.isEmpty(rewriteConfig) && lodash_1.default.isPlainObject(rewriteConfig)) {
44
47
  return true;
45
48
  }
46
- else if (_.isUndefined(rewriteConfig) ||
47
- _.isNull(rewriteConfig) ||
48
- _.isEqual(rewriteConfig, {})) {
49
+ else if (lodash_1.default.isUndefined(rewriteConfig) ||
50
+ lodash_1.default.isNull(rewriteConfig) ||
51
+ lodash_1.default.isEqual(rewriteConfig, {})) {
49
52
  return false;
50
53
  }
51
54
  else {
@@ -54,8 +57,8 @@ function isValidRewriteConfig(rewriteConfig) {
54
57
  }
55
58
  function parsePathRewriteRules(rewriteConfig) {
56
59
  const rules = [];
57
- if (_.isPlainObject(rewriteConfig)) {
58
- _.forIn(rewriteConfig, (value, key) => {
60
+ if (lodash_1.default.isPlainObject(rewriteConfig)) {
61
+ lodash_1.default.forIn(rewriteConfig, (value, key) => {
59
62
  rules.push({
60
63
  regex: new RegExp(key),
61
64
  value: rewriteConfig[key]
@@ -0,0 +1 @@
1
+ export declare function getTarget(req: any, config: any): Promise<any>;
package/dist/router.js CHANGED
@@ -1,18 +1,32 @@
1
1
  "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
2
14
  Object.defineProperty(exports, "__esModule", { value: true });
3
- const _ = require("lodash");
15
+ const lodash_1 = __importDefault(require("lodash"));
4
16
  const logger_1 = require("./logger");
5
17
  const logger = logger_1.getInstance();
6
18
  function getTarget(req, config) {
7
- let newTarget;
8
- const router = config.router;
9
- if (_.isPlainObject(router)) {
10
- newTarget = getTargetFromProxyTable(req, router);
11
- }
12
- else if (_.isFunction(router)) {
13
- newTarget = router(req);
14
- }
15
- return newTarget;
19
+ return __awaiter(this, void 0, void 0, function* () {
20
+ let newTarget;
21
+ const router = config.router;
22
+ if (lodash_1.default.isPlainObject(router)) {
23
+ newTarget = getTargetFromProxyTable(req, router);
24
+ }
25
+ else if (lodash_1.default.isFunction(router)) {
26
+ newTarget = yield router(req);
27
+ }
28
+ return newTarget;
29
+ });
16
30
  }
17
31
  exports.getTarget = getTarget;
18
32
  function getTargetFromProxyTable(req, table) {
@@ -20,7 +34,7 @@ function getTargetFromProxyTable(req, table) {
20
34
  const host = req.headers.host;
21
35
  const path = req.url;
22
36
  const hostAndPath = host + path;
23
- _.forIn(table, (value, key) => {
37
+ lodash_1.default.forIn(table, (value, key) => {
24
38
  if (containsPath(key)) {
25
39
  if (hostAndPath.indexOf(key) > -1) {
26
40
  // match 'localhost:3000/api'
@@ -0,0 +1,38 @@
1
+ /// <reference types="node" />
2
+ import express from 'express';
3
+ import http from 'http';
4
+ import httpProxy from 'http-proxy';
5
+ import net from 'net';
6
+ export interface IRequest extends express.Request {
7
+ }
8
+ export interface IResponse extends express.Response {
9
+ }
10
+ export interface IRequestHandler extends express.RequestHandler {
11
+ upgrade?: (req: IRequest, socket: net.Socket, head: any) => void;
12
+ }
13
+ export declare type Filter = string | string[] | ((pathname: string, req: IRequest) => boolean);
14
+ export interface Options extends httpProxy.ServerOptions {
15
+ pathRewrite?: {
16
+ [regexp: string]: string;
17
+ } | ((path: string, req: IRequest) => string) | ((path: string, req: IRequest) => Promise<string>);
18
+ router?: {
19
+ [hostOrPath: string]: string;
20
+ } | ((req: IRequest) => string) | ((req: IRequest) => Promise<string>);
21
+ logLevel?: 'debug' | 'info' | 'warn' | 'error' | 'silent';
22
+ logProvider?(provider: LogProvider): LogProvider;
23
+ onError?(err: Error, req: IRequest, res: IResponse): void;
24
+ onProxyRes?(proxyRes: http.ServerResponse, req: IRequest, res: IResponse): void;
25
+ onProxyReq?(proxyReq: http.ClientRequest, req: IRequest, res: IResponse): void;
26
+ onProxyReqWs?(proxyReq: http.ClientRequest, req: IRequest, socket: net.Socket, options: httpProxy.ServerOptions, head: any): void;
27
+ onOpen?(proxySocket: net.Socket): void;
28
+ onClose?(res: IResponse, socket: net.Socket, head: any): void;
29
+ }
30
+ interface LogProvider {
31
+ log: Logger;
32
+ debug?: Logger;
33
+ info?: Logger;
34
+ warn?: Logger;
35
+ error?: Logger;
36
+ }
37
+ declare type Logger = (...args: any[]) => void;
38
+ export {};
package/dist/types.js ADDED
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
package/package.json CHANGED
@@ -1,8 +1,9 @@
1
1
  {
2
2
  "name": "http-proxy-middleware",
3
- "version": "0.20.0",
3
+ "version": "0.21.0",
4
4
  "description": "The one-liner node.js proxy middleware for connect, express and browser-sync",
5
5
  "main": "dist/index.js",
6
+ "types": "dist/index.d.ts",
6
7
  "files": [
7
8
  "dist"
8
9
  ],
@@ -51,30 +52,30 @@
51
52
  "@commitlint/cli": "^8.0.0",
52
53
  "@commitlint/config-conventional": "^8.0.0",
53
54
  "@types/express": "^4.17.0",
54
- "@types/http-proxy": "^1.17.0",
55
55
  "@types/is-glob": "^4.0.0",
56
- "@types/jest": "^24.0.15",
57
- "@types/lodash": "^4.14.136",
58
- "@types/micromatch": "^3.1.0",
56
+ "@types/jest": "^25.1.2",
57
+ "@types/lodash": "^4.14.149",
58
+ "@types/micromatch": "^4.0.1",
59
59
  "@types/node": "^12.6.2",
60
60
  "browser-sync": "^2.26.7",
61
61
  "connect": "^3.6.6",
62
62
  "coveralls": "^3.0.5",
63
63
  "express": "^4.16.4",
64
64
  "husky": "^3.0.0",
65
- "jest": "^24.5.0",
66
- "open": "^6.4.0",
67
- "prettier": "^1.18.2",
68
- "ts-jest": "^24.0.0",
69
- "tslint": "^5.18.0",
65
+ "jest": "^25.1.0",
66
+ "open": "^7.0.2",
67
+ "prettier": "^1.19.1",
68
+ "ts-jest": "^25.2.0",
69
+ "tslint": "^6.0.0",
70
70
  "tslint-config-prettier": "^1.18.0",
71
- "typescript": "^3.5.3",
71
+ "typescript": "^3.7.5",
72
72
  "ws": "^7.1.0"
73
73
  },
74
74
  "dependencies": {
75
- "http-proxy": "^1.17.0",
75
+ "@types/http-proxy": "^1.17.3",
76
+ "http-proxy": "^1.18.0",
76
77
  "is-glob": "^4.0.1",
77
- "lodash": "^4.17.14",
78
+ "lodash": "^4.17.15",
78
79
  "micromatch": "^4.0.2"
79
80
  },
80
81
  "engines": {