123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166 |
- "use strict";
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
- };
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.HttpProxyMiddleware = void 0;
- const httpProxy = require("http-proxy");
- const config_factory_1 = require("./config-factory");
- const contextMatcher = require("./context-matcher");
- const handlers = require("./_handlers");
- const logger_1 = require("./logger");
- const PathRewriter = require("./path-rewriter");
- const Router = require("./router");
- class HttpProxyMiddleware {
- constructor(context, opts) {
- this.logger = logger_1.getInstance();
- this.wsInternalSubscribed = false;
- this.serverOnCloseSubscribed = false;
-
- this.middleware = (req, res, next) => __awaiter(this, void 0, void 0, function* () {
- var _a, _b;
- if (this.shouldProxy(this.config.context, req)) {
- try {
- const activeProxyOptions = yield this.prepareProxyRequest(req);
- this.proxy.web(req, res, activeProxyOptions);
- }
- catch (err) {
- next(err);
- }
- }
- else {
- next();
- }
-
- const server = (_b = ((_a = req.socket) !== null && _a !== void 0 ? _a : req.connection)) === null || _b === void 0 ? void 0 : _b.server;
- if (server && !this.serverOnCloseSubscribed) {
- server.on('close', () => {
- this.logger.info('[HPM] server close signal received: closing proxy server');
- this.proxy.close();
- });
- this.serverOnCloseSubscribed = true;
- }
- if (this.proxyOptions.ws === true) {
-
- this.catchUpgradeRequest(server);
- }
- });
- this.catchUpgradeRequest = (server) => {
- if (!this.wsInternalSubscribed) {
- server.on('upgrade', this.handleUpgrade);
-
-
- this.wsInternalSubscribed = true;
- }
- };
- this.handleUpgrade = (req, socket, head) => __awaiter(this, void 0, void 0, function* () {
- if (this.shouldProxy(this.config.context, req)) {
- const activeProxyOptions = yield this.prepareProxyRequest(req);
- this.proxy.ws(req, socket, head, activeProxyOptions);
- this.logger.info('[HPM] Upgrading to WebSocket');
- }
- });
-
- this.shouldProxy = (context, req) => {
- const path = req.originalUrl || req.url;
- return contextMatcher.match(context, path, req);
- };
-
- this.prepareProxyRequest = (req) => __awaiter(this, void 0, void 0, function* () {
-
-
- req.url = req.originalUrl || req.url;
-
- const originalPath = req.url;
- const newProxyOptions = Object.assign({}, this.proxyOptions);
-
-
-
- yield this.applyRouter(req, newProxyOptions);
- yield this.applyPathRewrite(req, this.pathRewriter);
-
- if (this.proxyOptions.logLevel === 'debug') {
- const arrow = logger_1.getArrow(originalPath, req.url, this.proxyOptions.target, newProxyOptions.target);
- this.logger.debug('[HPM] %s %s %s %s', req.method, originalPath, arrow, newProxyOptions.target);
- }
- return newProxyOptions;
- });
-
- this.applyRouter = (req, options) => __awaiter(this, void 0, void 0, function* () {
- let newTarget;
- if (options.router) {
- newTarget = yield Router.getTarget(req, options);
- if (newTarget) {
- this.logger.debug('[HPM] Router new target: %s -> "%s"', options.target, newTarget);
- options.target = newTarget;
- }
- }
- });
-
- this.applyPathRewrite = (req, pathRewriter) => __awaiter(this, void 0, void 0, function* () {
- if (pathRewriter) {
- const path = yield pathRewriter(req.url, req);
- if (typeof path === 'string') {
- req.url = path;
- }
- else {
- this.logger.info('[HPM] pathRewrite: No rewritten path found. (%s)', req.url);
- }
- }
- });
- this.logError = (err, req, res, target) => {
- var _a;
- const hostname = ((_a = req.headers) === null || _a === void 0 ? void 0 : _a.host) || req.hostname || req.host;
- const requestHref = `${hostname}${req.url}`;
- const targetHref = `${target === null || target === void 0 ? void 0 : target.href}`;
- const errorMessage = '[HPM] Error occurred while proxying request %s to %s [%s] (%s)';
- const errReference = 'https://nodejs.org/api/errors.html#errors_common_system_errors';
- this.logger.error(errorMessage, requestHref, targetHref, err.code || err, errReference);
- };
- this.config = config_factory_1.createConfig(context, opts);
- this.proxyOptions = this.config.options;
-
- this.proxy = httpProxy.createProxyServer({});
- this.logger.info(`[HPM] Proxy created: ${this.config.context} -> ${this.proxyOptions.target}`);
- this.pathRewriter = PathRewriter.createPathRewriter(this.proxyOptions.pathRewrite);
-
- handlers.init(this.proxy, this.proxyOptions);
-
- this.proxy.on('error', this.logError);
-
-
- this.middleware.upgrade = (req, socket, head) => {
- if (!this.wsInternalSubscribed) {
- this.handleUpgrade(req, socket, head);
- }
- };
- }
- }
- exports.HttpProxyMiddleware = HttpProxyMiddleware;
|