import { HttpFlows } from './HttpFlows.js';
export class HttpFlowRunner extends HttpFlows {
    /**
     * Runs flows before the HTTP request is sent to the remote machine.
     * The request has to be pre-processed, that is, variables should already be applied to it.
     */
    async request(request, flows) {
        if (!flows || !flows.length) {
            return;
        }
        await this.runFlows(request, flows);
    }
    async response(request, response, flows) {
        if (!flows || !flows.length) {
            return;
        }
        await this.runFlows(request, flows, response);
    }
    async runFlows(request, flows, response) {
        for (const flow of flows) {
            const { condition, actions } = flow;
            const passedCondition = await this.checkCondition(request, condition, response);
            if (!passedCondition) {
                continue;
            }
            for (const action of actions) {
                try {
                    await this.runAction(action, request, response);
                }
                catch (e) {
                    // eslint-disable-next-line no-console
                    console.warn(e);
                    // if the step fails then we stop execution.
                    // TODO: we should generate a report with the list of execution errors and present it in the UI.
                    break;
                }
            }
        }
    }
    async runAction(action, request, response) {
        const { steps } = action;
        if (!Array.isArray(steps) || !steps.length) {
            return;
        }
        await this.runSteps(steps, request, response);
    }
    async checkCondition(request, condition, response) {
        if (!condition) {
            return true;
        }
        const { steps = [] } = condition;
        if (!Array.isArray(steps) || !steps.length) {
            return true;
        }
        // the condition works with assertions. If the condition throws then it is not satisfied.
        try {
            await this.runSteps(steps, request, response);
            return true;
        }
        catch {
            return false;
        }
    }
    async runSteps(steps, request, response) {
        // this keeps a value from the last step to be passed to the next step.
        let lastResult = {
            value: undefined,
        };
        for (const step of steps) {
            lastResult = await this.runStep(request, step, lastResult, response);
        }
    }
}
//# sourceMappingURL=HttpFlowRunner.js.map