"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const test_1 = require("@playwright/test");
const v3_js_1 = require("../../lib/v3/v3.js");
const v3_dynamic_config_js_1 = require("./v3.dynamic.config.js");
const testUtils_js_1 = require("./testUtils.js");
const PAGE_TARGET_COUNT = 5;
test_1.test.describe("connect to existing Browserbase session", () => {
    (0, test_1.test)("new Stagehand instance reuses an existing Browserbase session", async () => {
        const browserTarget = (process.env.STAGEHAND_BROWSER_TARGET ?? "local").toLowerCase();
        const isBrowserbase = browserTarget === "browserbase";
        test_1.test.skip(!isBrowserbase, "Requires STAGEHAND_BROWSER_TARGET=browserbase");
        test_1.test.skip(!process.env.BROWSERBASE_API_KEY || !process.env.BROWSERBASE_PROJECT_ID, "BROWSERBASE credentials are required");
        const initialStagehand = new v3_js_1.V3({
            ...v3_dynamic_config_js_1.v3DynamicTestConfig,
            disableAPI: true,
        });
        await initialStagehand.init();
        let resumedStagehand = null;
        try {
            const ctx = initialStagehand.context;
            const initialPage = ctx.pages()[0];
            (0, test_1.expect)(initialPage).toBeDefined();
            for (let i = 0; i < PAGE_TARGET_COUNT; i++) {
                await ctx.newPage(`https://example.com/?tab=${i}`);
            }
            await initialPage?.close();
            await test_1.expect
                .poll(() => ctx.pages().length, { timeout: 15_000 })
                .toBe(PAGE_TARGET_COUNT);
            const sessionUrl = initialStagehand.connectURL();
            (0, test_1.expect)(sessionUrl).toBeTruthy();
            resumedStagehand = new v3_js_1.V3({
                env: "LOCAL",
                verbose: 0,
                disablePino: true,
                disableAPI: true,
                logger: v3_dynamic_config_js_1.v3DynamicTestConfig.logger,
                localBrowserLaunchOptions: {
                    cdpUrl: sessionUrl,
                },
            });
            await resumedStagehand.init();
            await test_1.expect
                .poll(() => resumedStagehand.context.pages().length, {
                timeout: 15_000,
            })
                .toBe(PAGE_TARGET_COUNT);
            const resumedPagesCount = resumedStagehand.context.pages().length;
            (0, test_1.expect)(resumedPagesCount).toBe(PAGE_TARGET_COUNT);
        }
        finally {
            await (0, testUtils_js_1.closeV3)(resumedStagehand);
            await (0, testUtils_js_1.closeV3)(initialStagehand);
        }
    });
});
//# sourceMappingURL=connect-to-existing-browser.spec.js.map