"use strict";
/**
 * Copyright: (c) Myia SAS 2026.
 * This file and its contents are licensed under the AGPLv3 License.
 * Please see the LICENSE file at the root of this repository
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.wireAllPages = wireAllPages;
exports.wireInitialPage = wireInitialPage;
/** Returns a `restore()` thunk that undoes all patches. */
function wireAllPages(sessions, opts) {
    const { browser, apiRequest } = opts;
    // (1) Wire every existing BrowserContext.
    for (const ctx of browser.contexts()) {
        for (const session of sessions)
            session.attachToContext(ctx);
    }
    // (2) Patch newly-created contexts. We hold references to the
    // ORIGINAL methods (no `.bind`) so `restore()` returns the exact
    // same function reference user code may have captured before
    // wiring. Inside our wrapper we use `.call(browser, …)` to keep
    // `this` correctly bound on invocation.
    const originalNewContext = browser.newContext;
    const originalNewPage = browser.newPage;
    browser.newContext = async (...args) => {
        const ctx = await originalNewContext.call(browser, ...args);
        for (const session of sessions)
            session.attachToContext(ctx);
        return ctx;
    };
    browser.newPage = async (...args) => {
        const page = await originalNewPage.call(browser, ...args);
        const ctx = page.context();
        for (const session of sessions)
            session.attachToContext(ctx);
        return page;
    };
    // (3) Patch the global APIRequest factory if we were handed one
    // and any session implements `attachToApiRequestContext`.
    let originalApiNewContext;
    if (apiRequest && sessions.some((s) => s.attachToApiRequestContext)) {
        originalApiNewContext = apiRequest.newContext;
        apiRequest.newContext = async (...args) => {
            const api = await originalApiNewContext.call(apiRequest, ...args);
            for (const session of sessions) {
                session.attachToApiRequestContext?.(api);
            }
            return api;
        };
    }
    return function restore() {
        // Always restore. If user code re-patched our wrapper in the
        // meantime, theirs gets reverted too — they own the conflict.
        browser.newContext = originalNewContext;
        browser.newPage = originalNewPage;
        if (apiRequest && originalApiNewContext) {
            apiRequest.newContext = originalApiNewContext;
        }
    };
}
/**
 * Wire a single page (and its context) eagerly. Used by the fixture
 * for the test's initial `page` so the first request fired by the
 * test body is captured even if it races with the `attachToContext`
 * call for a sibling context.
 */
function wireInitialPage(sessions, page) {
    const ctx = page.context();
    for (const session of sessions)
        session.attachToContext(ctx);
}
