"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.NetworkProcessor = void 0;
const protocol_js_1 = require("../../../protocol/protocol.js");
const assert_js_1 = require("../../../utils/assert.js");
const NetworkUtils_js_1 = require("./NetworkUtils.js");
/** Dispatches Network domain commands. */
class NetworkProcessor {
    #networkStorage;
    constructor(networkStorage) {
        this.#networkStorage = networkStorage;
    }
    async addIntercept(params) {
        const urlPatterns = params.urlPatterns ?? [];
        const parsedUrlPatterns = NetworkProcessor.parseUrlPatterns(urlPatterns);
        const intercept = await this.#networkStorage.addIntercept({
            urlPatterns: parsedUrlPatterns,
            phases: params.phases,
        });
        return {
            intercept,
        };
    }
    async continueRequest(params) {
        const networkId = params.request;
        if (params.url !== undefined) {
            NetworkProcessor.parseUrlString(params.url);
        }
        const request = this.#getBlockedRequestOrFail(networkId, "beforeRequestSent" /* Network.InterceptPhase.BeforeRequestSent */);
        const { url, method, headers } = params;
        // TODO: Set / expand.
        // ; Step 9. cookies
        // ; Step 10. body
        const requestHeaders = (0, NetworkUtils_js_1.cdpFetchHeadersFromBidiNetworkHeaders)(headers);
        await request.continueRequest(url, method, requestHeaders);
        return {};
    }
    async continueResponse(params) {
        const networkId = params.request;
        const { statusCode, reasonPhrase, headers } = params;
        const request = this.#getBlockedRequestOrFail(networkId, "responseStarted" /* Network.InterceptPhase.ResponseStarted */);
        const responseHeaders = (0, NetworkUtils_js_1.cdpFetchHeadersFromBidiNetworkHeaders)(headers);
        // TODO: Set / expand.
        // ; Step 10. cookies
        // ; Step 11. credentials
        await request.continueResponse({
            responseCode: statusCode,
            responsePhrase: reasonPhrase,
            responseHeaders,
        });
        return {};
    }
    async continueWithAuth(params) {
        const networkId = params.request;
        const request = this.#getBlockedRequestOrFail(networkId, "authRequired" /* Network.InterceptPhase.AuthRequired */);
        let username;
        let password;
        if (params.action === 'provideCredentials') {
            const { credentials } = params;
            username = credentials.username;
            password = credentials.password;
            // TODO: This should be invalid argument exception.
            // Spec may need to be updated.
            (0, assert_js_1.assert)(credentials.type === 'password', `Credentials type ${credentials.type} must be 'password'`);
        }
        const response = (0, NetworkUtils_js_1.cdpAuthChallengeResponseFromBidiAuthContinueWithAuthAction)(params.action);
        await request.continueWithAuth({
            response,
            username,
            password,
        });
        return {};
    }
    async failRequest({ request: networkId, }) {
        const request = this.#getRequestOrFail(networkId);
        if (request.phase === "authRequired" /* Network.InterceptPhase.AuthRequired */) {
            throw new protocol_js_1.InvalidArgumentException(`Request '${networkId}' in 'authRequired' phase cannot be failed`);
        }
        if (!request.blocked) {
            throw new protocol_js_1.NoSuchRequestException(`No blocked request found for network id '${networkId}'`);
        }
        await request.failRequest('Failed');
        return {};
    }
    async provideResponse(params) {
        const { statusCode, reasonPhrase, headers, body, request: networkId, } = params;
        // TODO: Step 6
        // https://w3c.github.io/webdriver-bidi/#command-network-continueResponse
        const responseHeaders = (0, NetworkUtils_js_1.cdpFetchHeadersFromBidiNetworkHeaders)(headers);
        // TODO: Set / expand.
        // ; Step 10. cookies
        // ; Step 11. credentials
        const request = this.#getBlockedRequestOrFail(networkId, null);
        await request.provideResponse({
            responseCode: statusCode ?? request.statusCode,
            responsePhrase: reasonPhrase,
            responseHeaders,
            body: body?.value, // TODO: Differ base64 / string
        });
        return {};
    }
    async removeIntercept(params) {
        await this.#networkStorage.removeIntercept(params.intercept);
        return {};
    }
    #getRequestOrFail(id) {
        const request = this.#networkStorage.getRequestById(id);
        if (!request) {
            throw new protocol_js_1.NoSuchRequestException(`Network request with ID '${id}' doesn't exist`);
        }
        return request;
    }
    #getBlockedRequestOrFail(id, phase) {
        const request = this.#getRequestOrFail(id);
        if (!request.blocked) {
            throw new protocol_js_1.NoSuchRequestException(`No blocked request found for network id '${id}'`);
        }
        if (phase && request.phase !== phase) {
            throw new protocol_js_1.InvalidArgumentException(`Blocked request for network id '${id}' is in '${request.phase}' phase`);
        }
        return request;
    }
    /**
     * Attempts to parse the given url.
     * Throws an InvalidArgumentException if the url is invalid.
     */
    static parseUrlString(url) {
        try {
            return new URL(url);
        }
        catch (error) {
            throw new protocol_js_1.InvalidArgumentException(`Invalid URL '${url}': ${error}`);
        }
    }
    static parseUrlPatterns(urlPatterns) {
        return urlPatterns.map((urlPattern) => {
            switch (urlPattern.type) {
                case 'string': {
                    NetworkProcessor.parseUrlString(urlPattern.pattern);
                    return urlPattern;
                }
                case 'pattern':
                    // No params signifies intercept all
                    if (urlPattern.protocol === undefined &&
                        urlPattern.hostname === undefined &&
                        urlPattern.port === undefined &&
                        urlPattern.pathname === undefined &&
                        urlPattern.search === undefined) {
                        return urlPattern;
                    }
                    if (urlPattern.protocol === '') {
                        throw new protocol_js_1.InvalidArgumentException(`URL pattern must specify a protocol`);
                    }
                    if (urlPattern.hostname === '') {
                        throw new protocol_js_1.InvalidArgumentException(`URL pattern must specify a hostname`);
                    }
                    if ((urlPattern.hostname?.length ?? 0) > 0) {
                        if (urlPattern.protocol?.match(/^file/i)) {
                            throw new protocol_js_1.InvalidArgumentException(`URL pattern protocol cannot be 'file'`);
                        }
                        if (urlPattern.hostname?.includes(':')) {
                            throw new protocol_js_1.InvalidArgumentException(`URL pattern hostname must not contain a colon`);
                        }
                    }
                    if (urlPattern.port === '') {
                        throw new protocol_js_1.InvalidArgumentException(`URL pattern must specify a port`);
                    }
                    try {
                        new URL((0, NetworkUtils_js_1.buildUrlPatternString)(urlPattern));
                    }
                    catch (error) {
                        throw new protocol_js_1.InvalidArgumentException(`${error}`);
                    }
                    return urlPattern;
            }
        });
    }
}
exports.NetworkProcessor = NetworkProcessor;
//# sourceMappingURL=NetworkProcessor.js.map