"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.BrowsingContextProcessor = void 0;
const protocol_js_1 = require("../../../protocol/protocol.js");
const log_js_1 = require("../../../utils/log.js");
const Realm_js_1 = require("../script/Realm.js");
const BrowsingContextImpl_js_1 = require("./BrowsingContextImpl.js");
const CdpTarget_js_1 = require("./CdpTarget.js");
class BrowsingContextProcessor {
    #browserCdpClient;
    #cdpConnection;
    #selfTargetId;
    #eventManager;
    #browsingContextStorage;
    #networkStorage;
    #acceptInsecureCerts;
    #preloadScriptStorage;
    #realmStorage;
    #logger;
    constructor(cdpConnection, browserCdpClient, selfTargetId, eventManager, browsingContextStorage, realmStorage, networkStorage, preloadScriptStorage, acceptInsecureCerts, logger) {
        this.#acceptInsecureCerts = acceptInsecureCerts;
        this.#cdpConnection = cdpConnection;
        this.#browserCdpClient = browserCdpClient;
        this.#selfTargetId = selfTargetId;
        this.#eventManager = eventManager;
        this.#browsingContextStorage = browsingContextStorage;
        this.#preloadScriptStorage = preloadScriptStorage;
        this.#networkStorage = networkStorage;
        this.#realmStorage = realmStorage;
        this.#logger = logger;
        this.#setEventListeners(browserCdpClient);
    }
    getTree(params) {
        const resultContexts = params.root === undefined
            ? this.#browsingContextStorage.getTopLevelContexts()
            : [this.#browsingContextStorage.getContext(params.root)];
        return {
            contexts: resultContexts.map((c) => c.serializeToBidiValue(params.maxDepth ?? Number.MAX_VALUE)),
        };
    }
    async create(params) {
        let referenceContext;
        if (params.referenceContext !== undefined) {
            referenceContext = this.#browsingContextStorage.getContext(params.referenceContext);
            if (!referenceContext.isTopLevelContext()) {
                throw new protocol_js_1.InvalidArgumentException(`referenceContext should be a top-level context`);
            }
        }
        let result;
        switch (params.type) {
            case "tab" /* BrowsingContext.CreateType.Tab */:
                result = await this.#browserCdpClient.sendCommand('Target.createTarget', {
                    url: 'about:blank',
                    newWindow: false,
                });
                break;
            case "window" /* BrowsingContext.CreateType.Window */:
                result = await this.#browserCdpClient.sendCommand('Target.createTarget', {
                    url: 'about:blank',
                    newWindow: true,
                });
                break;
        }
        // Wait for the new tab to be loaded to avoid race conditions in the
        // `browsingContext` events, when the `browsingContext.domContentLoaded` and
        // `browsingContext.load` events from the initial `about:blank` navigation
        // are emitted after the next navigation is started.
        // Details: https://github.com/web-platform-tests/wpt/issues/35846
        const contextId = result.targetId;
        const context = this.#browsingContextStorage.getContext(contextId);
        await context.lifecycleLoaded();
        return { context: context.id };
    }
    navigate(params) {
        const context = this.#browsingContextStorage.getContext(params.context);
        return context.navigate(params.url, params.wait ?? "none" /* BrowsingContext.ReadinessState.None */);
    }
    reload(params) {
        const context = this.#browsingContextStorage.getContext(params.context);
        return context.reload(params.ignoreCache ?? false, params.wait ?? "none" /* BrowsingContext.ReadinessState.None */);
    }
    async activate(params) {
        const context = this.#browsingContextStorage.getContext(params.context);
        if (!context.isTopLevelContext()) {
            throw new protocol_js_1.InvalidArgumentException('Activation is only supported on the top-level context');
        }
        await context.activate();
        return {};
    }
    async captureScreenshot(params) {
        const context = this.#browsingContextStorage.getContext(params.context);
        return await context.captureScreenshot(params);
    }
    async print(params) {
        const context = this.#browsingContextStorage.getContext(params.context);
        return await context.print(params);
    }
    async setViewport(params) {
        const context = this.#browsingContextStorage.getContext(params.context);
        if (!context.isTopLevelContext()) {
            throw new protocol_js_1.InvalidArgumentException('Emulating viewport is only supported on the top-level context');
        }
        await context.setViewport(params.viewport, params.devicePixelRatio);
        return {};
    }
    async traverseHistory(params) {
        const context = this.#browsingContextStorage.getContext(params.context);
        if (!context) {
            throw new protocol_js_1.InvalidArgumentException(`No browsing context with id ${params.context}`);
        }
        await context.traverseHistory(params.delta);
        return {};
    }
    async handleUserPrompt(params) {
        const context = this.#browsingContextStorage.getContext(params.context);
        await context.handleUserPrompt(params);
        return {};
    }
    async close(params) {
        const context = this.#browsingContextStorage.getContext(params.context);
        if (!context.isTopLevelContext()) {
            throw new protocol_js_1.InvalidArgumentException(`Non top-level browsing context ${context.id} cannot be closed.`);
        }
        try {
            const detachedFromTargetPromise = new Promise((resolve) => {
                const onContextDestroyed = (event) => {
                    if (event.targetId === params.context) {
                        this.#browserCdpClient.off('Target.detachedFromTarget', onContextDestroyed);
                        resolve();
                    }
                };
                this.#browserCdpClient.on('Target.detachedFromTarget', onContextDestroyed);
            });
            if (params.promptUnload) {
                await context.close();
            }
            else {
                await this.#browserCdpClient.sendCommand('Target.closeTarget', {
                    targetId: params.context,
                });
            }
            // Sometimes CDP command finishes before `detachedFromTarget` event,
            // sometimes after. Wait for the CDP command to be finished, and then wait
            // for `detachedFromTarget` if it hasn't emitted.
            await detachedFromTargetPromise;
        }
        catch (error) {
            // Swallow error that arise from the page being destroyed
            // Example is navigating to faulty SSL certificate
            if (!(error.code === -32000 /* CdpErrorConstants.GENERIC_ERROR */ &&
                error.message === 'Not attached to an active page')) {
                throw error;
            }
        }
        return {};
    }
    /**
     * This method is called for each CDP session, since this class is responsible
     * for creating and destroying all targets and browsing contexts.
     */
    #setEventListeners(cdpClient) {
        cdpClient.on('Target.attachedToTarget', (params) => {
            this.#handleAttachedToTargetEvent(params, cdpClient);
        });
        cdpClient.on('Target.detachedFromTarget', (params) => {
            this.#handleDetachedFromTargetEvent(params);
        });
        cdpClient.on('Target.targetInfoChanged', (params) => {
            this.#handleTargetInfoChangedEvent(params);
        });
        cdpClient.on('Page.frameAttached', (params) => {
            this.#handleFrameAttachedEvent(params);
        });
        cdpClient.on('Page.frameDetached', (params) => {
            this.#handleFrameDetachedEvent(params);
        });
    }
    #handleFrameAttachedEvent(params) {
        const parentBrowsingContext = this.#browsingContextStorage.findContext(params.parentFrameId);
        if (parentBrowsingContext !== undefined) {
            BrowsingContextImpl_js_1.BrowsingContextImpl.create(parentBrowsingContext.cdpTarget, this.#realmStorage, params.frameId, params.parentFrameId, this.#eventManager, this.#browsingContextStorage, this.#logger);
        }
    }
    #handleFrameDetachedEvent(params) {
        // In case of OOPiF no need in deleting BrowsingContext.
        if (params.reason === 'swap') {
            return;
        }
        this.#browsingContextStorage.findContext(params.frameId)?.dispose();
    }
    #handleAttachedToTargetEvent(params, parentSessionCdpClient) {
        const { sessionId, targetInfo } = params;
        const targetCdpClient = this.#cdpConnection.getCdpClient(sessionId);
        this.#logger?.(log_js_1.LogType.debugInfo, 'AttachedToTarget event received:', params);
        switch (targetInfo.type) {
            case 'page':
            case 'iframe': {
                if (targetInfo.targetId === this.#selfTargetId) {
                    break;
                }
                this.#setEventListeners(targetCdpClient);
                const cdpTarget = CdpTarget_js_1.CdpTarget.create(targetInfo.targetId, targetCdpClient, this.#browserCdpClient, sessionId, this.#realmStorage, this.#eventManager, this.#preloadScriptStorage, this.#networkStorage, this.#acceptInsecureCerts);
                const maybeContext = this.#browsingContextStorage.findContext(targetInfo.targetId);
                if (maybeContext) {
                    // OOPiF.
                    maybeContext.updateCdpTarget(cdpTarget);
                }
                else {
                    // New context.
                    BrowsingContextImpl_js_1.BrowsingContextImpl.create(cdpTarget, this.#realmStorage, targetInfo.targetId, null, this.#eventManager, this.#browsingContextStorage, this.#logger);
                }
                return;
            }
            case 'worker': {
                this.#setEventListeners(targetCdpClient);
                const cdpTarget = CdpTarget_js_1.CdpTarget.create(targetInfo.targetId, targetCdpClient, this.#browserCdpClient, sessionId, this.#realmStorage, this.#eventManager, this.#preloadScriptStorage, this.#networkStorage, this.#acceptInsecureCerts);
                const browsingContext = parentSessionCdpClient.sessionId &&
                    this.#browsingContextStorage.findContextBySession(parentSessionCdpClient.sessionId);
                // If there is no browsing context, this worker is already terminated.
                if (!browsingContext) {
                    break;
                }
                this.#handleWorkerTarget(cdpTarget, browsingContext.id);
                return;
            }
        }
        // DevTools or some other not supported by BiDi target. Just release
        // debugger and ignore them.
        targetCdpClient
            .sendCommand('Runtime.runIfWaitingForDebugger')
            .then(() => parentSessionCdpClient.sendCommand('Target.detachFromTarget', params))
            .catch((error) => this.#logger?.(log_js_1.LogType.debugError, error));
    }
    #workers = new Map();
    #handleWorkerTarget(cdpTarget, browsingContextId) {
        cdpTarget.cdpClient.on('Runtime.executionContextCreated', (params) => {
            const { uniqueId, id, origin } = params.context;
            const realm = new Realm_js_1.Realm(this.#realmStorage, this.#browsingContextStorage, uniqueId, browsingContextId, id, (0, BrowsingContextImpl_js_1.serializeOrigin)(origin), 'dedicated-worker', undefined, cdpTarget.cdpClient, this.#eventManager, this.#logger);
            this.#workers.set(cdpTarget.cdpSessionId, realm);
        });
    }
    #handleDetachedFromTargetEvent(params) {
        const context = this.#browsingContextStorage.findContextBySession(params.sessionId);
        if (context) {
            context.dispose();
            this.#preloadScriptStorage
                .find({ targetId: context.id })
                .map((preloadScript) => preloadScript.dispose(context.id));
            return;
        }
        const worker = this.#workers.get(params.sessionId);
        if (worker) {
            this.#realmStorage.deleteRealms({
                cdpSessionId: worker.cdpClient.sessionId,
            });
        }
    }
    #handleTargetInfoChangedEvent(params) {
        const context = this.#browsingContextStorage.findContext(params.targetInfo.targetId);
        if (context) {
            context.onTargetInfoChanged(params);
        }
    }
}
exports.BrowsingContextProcessor = BrowsingContextProcessor;
//# sourceMappingURL=BrowsingContextProcessor.js.map