"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.compose = exports.functionList = void 0;
const flatten = (values) => [].concat(...values), noop = function noop() {
    return Promise.resolve();
};
function functionList(list, ...args) {
    const arrayList = Symbol.iterator in list ? Array.from(list) : [list];
    return arrayList.map((x) => {
        return (_, next) => Promise.resolve(x(...args)).then(next);
    });
}
exports.functionList = functionList;
class Executor {
    constructor(mw, continuation) {
        this.mw = mw;
        this.continuation = continuation;
    }
    tryInvokeMiddleware(context, middleware, next = noop) {
        try {
            const resolved = middleware ? middleware(context, next) : context;
            return Promise.resolve(resolved);
        }
        catch (error) {
            return Promise.reject(error);
        }
    }
    get middleware() {
        return (context, next) => {
            return this.tryInvokeMiddleware(context, this.mw, this.continuation.bind(null, context, next));
        };
    }
}
/**
 * Create a function to invoke all passed middleware functions
 * with a single argument <T>context
 * @param middleware
 */
function compose(...middleware) {
    return flatten(middleware)
        .filter((x) => {
        if ('function' !== typeof x) {
            throw new TypeError(`${x}, must be a middleware function accepting (context, next) arguments`);
        }
        return x;
    })
        .reduceRight((composed, mw) => {
        return new Executor(mw, composed).middleware;
    }, Executor.prototype.tryInvokeMiddleware);
}
exports.compose = compose;
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiY29tcG9zZS5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9jb21wb3NlLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7OztBQVFBLE1BQU0sT0FBTyxHQUFHLENBQUksTUFBMkIsRUFBRSxFQUFFLENBQUUsRUFBVSxDQUFDLE1BQU0sQ0FBQyxHQUFHLE1BQU0sQ0FBUSxFQUN0RixJQUFJLEdBQUcsU0FBUyxJQUFJO0lBQ2xCLE9BQU8sT0FBTyxDQUFDLE9BQU8sRUFBRSxDQUFBO0FBQzFCLENBQUMsQ0FBQTtBQUVILFNBQWdCLFlBQVksQ0FDMUIsSUFBMkIsRUFDM0IsR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