import{debugError}from"../common/helper.js";import{isNode}from"../environment.js";import{assert}from"./assert.js";import{Browser}from"./Browser.js";import{Connection}from"./Connection.js";import{getFetch}from"./fetch.js";const getWebSocketTransportClass=async()=>isNode?(await import("../node/NodeWebSocketTransport.js")).NodeWebSocketTransport:(await import("./BrowserWebSocketTransport.js")).BrowserWebSocketTransport;export const connectToBrowser=async e=>{const{browserWSEndpoint:t,browserURL:o,ignoreHTTPSErrors:r=!1,defaultViewport:s={width:800,height:600},transport:n,slowMo:a=0}=e;assert(Number(!!t)+Number(!!o)+Number(!!n)===1,"Exactly one of browserWSEndpoint, browserURL or transport must be passed to puppeteer.connect");let c=null;if(n)c=new Connection("",n,a);else if(t){const e=await getWebSocketTransportClass(),o=await e.create(t);c=new Connection(t,o,a)}else if(o){const e=await getWSEndpoint(o),t=await getWebSocketTransportClass(),r=await t.create(e);c=new Connection(e,r,a)}const{browserContextIds:i}=await c.send("Target.getBrowserContexts");return Browser.create(c,i,r,s,null,(()=>c.send("Browser.close").catch(debugError)))};async function getWSEndpoint(e){const t=new URL("/json/version",e),o=await getFetch();try{const e=await o(t.toString(),{method:"GET"});if(!e.ok)throw new Error(`HTTP ${e.statusText}`);return(await e.json()).webSocketDebuggerUrl}catch(r){throw r.message=`Failed to fetch browser webSocket URL from ${t}: `+r.message,r}}