code:
"use strict";
/* eslint-disable prefer-rest-params */
Object.defineProperty(exports, "__esModule", { value: true });
exports.getArrow = exports.getInstance = void 0;
const util = require("util");
let loggerInstance;
const defaultProvider = {
    // tslint:disable: no-console
    log: console.log,
    debug: console.log,
    info: console.info,
    warn: console.warn,
    error: console.error,
};
// log level 'weight'
var LEVELS;
(function (LEVELS) {
    LEVELS[LEVELS["debug"] = 10] = "debug";
    LEVELS[LEVELS["info"] = 20] = "info";
    LEVELS[LEVELS["warn"] = 30] = "warn";
    LEVELS[LEVELS["error"] = 50] = "error";
    LEVELS[LEVELS["silent"] = 80] = "silent";
})(LEVELS || (LEVELS = {}));
function getInstance() {
    if (!loggerInstance) {
        loggerInstance = new Logger();
    }
    return loggerInstance;
}
exports.getInstance = getInstance;
class Logger {
    constructor() {
        this.setLevel('info');
        this.setProvider(() => defaultProvider);
    }
    // log will log messages, regardless of logLevels
    log() {
        this.provider.log(this._interpolate.apply(null, arguments));
    }
    debug() {
        if (this._showLevel('debug')) {
            this.provider.debug(this._interpolate.apply(null, arguments));
        }
    }
    info() {
        if (this._showLevel('info')) {
            this.provider.info(this._interpolate.apply(null, arguments));
        }
    }
    warn() {
        if (this._showLevel('warn')) {
            this.provider.warn(this._interpolate.apply(null, arguments));
        }
    }
    error() {
        if (this._showLevel('error')) {
            this.provider.error(this._interpolate.apply(null, arguments));
        }
    }
    setLevel(v) {
        if (this.isValidLevel(v)) {
            this.logLevel = v;
        }
    }
    setProvider(fn) {
        if (fn && this.isValidProvider(fn)) {
            this.provider = fn(defaultProvider);
        }
    }
    isValidProvider(fnProvider) {
        const result = true;
        if (fnProvider && typeof fnProvider !== 'function') {
            throw new Error('[HPM] Log provider config error. Expecting a function.');
        }
        return result;
    }
    isValidLevel(levelName) {
        const validLevels = Object.keys(LEVELS);
        const isValid = validLevels.includes(levelName);
        if (!isValid) {
            throw new Error('[HPM] Log level error. Invalid logLevel.');
        }
        return isValid;
    }
    /**
     * Decide to log or not to log, based on the log levels 'weight'
     * @param  {String}  showLevel [debug, info, warn, error, silent]
     * @return {Boolean}
     */
    _showLevel(showLevel) {
        let result = false;
        const currentLogLevel = LEVELS[this.logLevel];
        if (currentLogLevel && currentLogLevel <= LEVELS[showLevel]) {
            result = true;
        }
        return result;
    }
    // make sure logged messages and its data are return interpolated
    // make it possible for additional log data, such date/time or custom prefix.
    _interpolate(format, ...args) {
        const result = util.format(format, ...args);
        return result;
    }
}
/**
 * -> normal proxy
 * => router
 * ~> pathRewrite
 * ≈> router + pathRewrite
 *
 * @param  {String} originalPath
 * @param  {String} newPath
 * @param  {String} originalTarget
 * @param  {String} newTarget
 * @return {String}
 */
function getArrow(originalPath, newPath, originalTarget, newTarget) {
    const arrow = ['>'];
    const isNewTarget = originalTarget !== newTarget; // router
    const isNewPath = originalPath !== newPath; // pathRewrite
    if (isNewPath && !isNewTarget) {
        arrow.unshift('~');
    }
    else if (!isNewPath && isNewTarget) {
        arrow.unshift('=');
    }
    else if (isNewPath && isNewTarget) {
        arrow.unshift('≈');
    }
    else {
        arrow.unshift('-');
    }
    return arrow.join('');
}
exports.getArrow = getArrow;


code:
/**
 * Create rewrite function, to cache parsed rewrite rules.
 *
 * @param {Object} rewriteConfig
 * @return {Function} Function to rewrite paths; This function should accept `path` (request.url) as parameter
 */
export declare function createPathRewriter(rewriteConfig: any): any;

license: mit


code:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createPathRewriter = void 0;
const isPlainObj = require("is-plain-obj");
const errors_1 = require("./errors");
const logger_1 = require("./logger");
const logger = (0, logger_1.getInstance)();
/**
 * Create rewrite function, to cache parsed rewrite rules.
 *
 * @param {Object} rewriteConfig
 * @return {Function} Function to rewrite paths; This function should accept `path` (request.url) as parameter
 */
function createPathRewriter(rewriteConfig) {
    let rulesCache;
    if (!isValidRewriteConfig(rewriteConfig)) {
        return;
    }
    if (typeof rewriteConfig === 'function') {
        const customRewriteFn = rewriteConfig;
        return customRewriteFn;
    }
    else {
        rulesCache = parsePathRewriteRules(rewriteConfig);
        return rewritePath;
    }
    function rewritePath(path) {
        let result = path;
        for (const rule of rulesCache) {
            if (rule.regex.test(path)) {
                result = result.replace(rule.regex, rule.value);
                logger.debug('[HPM] Rewriting path from "%s" to "%s"', path, result);
                break;
            }
        }
        return result;
    }
}
exports.createPathRewriter = createPathRewriter;
function isValidRewriteConfig(rewriteConfig) {
    if (typeof rewriteConfig === 'function') {
        return true;
    }
    else if (isPlainObj(rewriteConfig)) {
        return Object.keys(rewriteConfig).length !== 0;
    }
    else if (rewriteConfig === undefined || rewriteConfig === null) {
        return false;
    }
    else {
        throw new Error(errors_1.ERRORS.ERR_PATH_REWRITER_CONFIG);
    }
}
function parsePathRewriteRules(rewriteConfig) {
    const rules = [];
    if (isPlainObj(rewriteConfig)) {
        for (const [key] of Object.entries(rewriteConfig)) {
            rules.push({
                regex: new RegExp(key),
                value: rewriteConfig[key],
            });
            logger.info('[HPM] Proxy rewrite rule created: "%s" ~> "%s"', key, rewriteConfig[key]);
        }
    }
    return rules;
}


code: export declare function getTarget(req: any, config: any): Promise<any>;


code:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getTarget = void 0;
const isPlainObj = require("is-plain-obj");
const logger_1 = require("./logger");
const logger = (0, logger_1.getInstance)();
async function getTarget(req, config) {
    let newTarget;
    const router = config.router;
    if (isPlainObj(router)) {
        newTarget = getTargetFromProxyTable(req, router);
    }
    else if (typeof router === 'function') {
        newTarget = await router(req);
    }
    return newTarget;
}
exports.getTarget = getTarget;
function getTargetFromProxyTable(req, table) {
    let result;
    const host = req.headers.host;
    const path = req.url;
    const hostAndPath = host + path;
    for (const [key] of Object.entries(table)) {
        if (containsPath(key)) {
            if (hostAndPath.indexOf(key) > -1) {
                // match 'localhost:3000/api'
                result = table[key];
                logger.debug('[HPM] Router table match: "%s"', key);
                break;
            }
        }
        else {
            if (key === host) {
                // match 'localhost:3000'
                result = table[key];
                logger.debug('[HPM] Router table match: "%s"', host);
                break;
            }
        }
    }
    return result;
}
function containsPath(v) {
    return v.indexOf('/') > -1;
}


code:
/**
 * Based on definition by DefinitelyTyped:
 * https://github.com/DefinitelyTyped/DefinitelyTyped/blob/6f529c6c67a447190f86bfbf894d1061e41e07b7/types/http-proxy-middleware/index.d.ts
 */
/// <reference types="node" />
import type * as express from 'express';
import type * as http from 'http';
import type * as httpProxy from 'http-proxy';
import type * as net from 'net';
import type * as url from 'url';
export interface Request extends express.Request {
}
export interface Response extends express.Response {
}
export interface RequestHandler extends express.RequestHandler {
    upgrade?: (req: Request, socket: net.Socket, head: any) => void;
}
export declare type Filter = string | string[] | ((pathname: string, req: Request) => boolean);
export interface Options extends httpProxy.ServerOptions {
    pathRewrite?: {
        [regexp: string]: string;
    } | ((path: string, req: Request) => string) | ((path: string, req: Request) => Promise<string>);
    router?: {
        [hostOrPath: string]: httpProxy.ServerOptions['target'];
    } | ((req: Request) => httpProxy.ServerOptions['target']) | ((req: Request) => Promise<httpProxy.ServerOptions['target']>);
    logLevel?: 'debug' | 'info' | 'warn' | 'error' | 'silent';
    logProvider?: LogProviderCallback;
    onError?: OnErrorCallback;
    onProxyRes?: OnProxyResCallback;
    onProxyReq?: OnProxyReqCallback;
    onProxyReqWs?: OnProxyReqWsCallback;
    onOpen?: OnOpenCallback;
    onClose?: OnCloseCallback;
}
interface LogProvider {
    log: Logger;
    debug?: Logger;
    info?: Logger;
    warn?: Logger;
    error?: Logger;
}
declare type Logger = (...args: any[]) => void;
export declare type LogProviderCallback = (provider: LogProvider) => LogProvider;
/**
 * Use types based on the events listeners from http-proxy
 * https://github.com/DefinitelyTyped/DefinitelyTyped/blob/51504fd999031b7f025220fab279f1b2155cbaff/types/http-proxy/index.d.ts
 */
export declare type OnErrorCallback = (err: Error, req: Request, res: Response, target?: string | Partial<url.Url>) => void;
export declare type OnProxyResCallback = (proxyRes: http.IncomingMessage, req: Request, res: Response) => void;
export declare type OnProxyReqCallback = (proxyReq: http.ClientRequest, req: Request, res: Response, options: httpProxy.ServerOptions) => void;
export declare type OnProxyReqWsCallback = (proxyReq: http.ClientRequest, req: Request, socket: net.Socket, options: httpProxy.ServerOptions, head: any) => void;
export declare type OnCloseCallback = (proxyRes: Response, proxySocket: net.Socket, proxyHead: any) => void;
export declare type OnOpenCallback = (proxySocket: net.Socket) => void;
export {};


code:
"use strict";
/**
 * Based on definition by DefinitelyTyped:
 * https://github.com/DefinitelyTyped/DefinitelyTyped/blob/6f529c6c67a447190f86bfbf894d1061e41e07b7/types/http-proxy-middleware/index.d.ts
 */
Object.defineProperty(exports, "__esModule", { value: true });


http-proxy-middleware

description: The one-liner node.js proxy middleware for connect, express and browser-sync

clean: rm -rf dist && rm -rf coverage

lint: yarn prettier && yarn eslint

lint:fix: yarn prettier:fix && yarn eslint:fix

eslint: eslint '{src,test}/**/*.ts'

eslint:fix: yarn eslint --fix

prebuild: yarn clean

build: tsc

pretest: yarn build

test: jest

precoverage: yarn build

prepare: husky install

prepack: yarn build && rm dist/tsconfig.tsbuildinfo

spellcheck: npx --yes cspell --show-context --show-suggestions '**/*.*'

type: git

keywords: reverse proxy middleware http https connect express fastify polka browser-sync gulp grunt-contrib-connect websocket ws cors

author: Steven Chim

license: MIT


output: CHANGELOG.md

template: keepachangelog