Skip to content

Commit

Permalink
Feat: Discrete connect handling
Browse files Browse the repository at this point in the history
  • Loading branch information
chaosharmonic committed Nov 22, 2024
1 parent 326a000 commit fd83ddf
Showing 1 changed file with 32 additions and 17 deletions.
49 changes: 32 additions & 17 deletions src/browser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -223,23 +223,45 @@ export class Browser {
}
}

export interface LaunchOptions {
headless?: boolean;
export type LaunchOptions = BrowserOptions & {
path?: string;
product?: "chrome" | "firefox";
args?: string[];
wsEndpoint?: string;
cache?: string;
}

export type ConnectOptions = BrowserOptions & {
// ASK: I assume path doesn't matter for this, right?
wsEndpoint: string;
// cache?: string; // ASK: is this relevant here?
// based on the return, I doubt it
}

/**
* Connects to a given browser over a WebSockets endpoint.
*/
export async function connect(opts: ConnectOptions): Promise<Browser> {
const headless = opts?.headless ?? true; // ASK: are either of
const product = opts?.product ?? "chrome"; // these necessary here?
const { wsEndpoint } = opts;

const options: BrowserOptions = {
headless,
product,
};

// Connect to endpoint directly if one was specified
const ws = new WebSocket(wsEndpoint);
await websocketReady(ws);
return new Browser(ws, null, options);
}

/**
* Launches a browser instance with given arguments and options when specified.
*/
export async function launch(opts?: LaunchOptions): Promise<Browser> {
const headless = opts?.headless ?? true;
const product = opts?.product ?? "chrome";
const args = opts?.args ?? [];
const wsEndpoint = opts?.wsEndpoint;
const cache = opts?.cache;
let path = opts?.path;

Expand All @@ -248,22 +270,10 @@ export async function launch(opts?: LaunchOptions): Promise<Browser> {
product,
};

// Connect to endpoint directly if one was specified
if (wsEndpoint) {
const ws = new WebSocket(wsEndpoint);
await websocketReady(ws);
return new Browser(ws, null, options);
}

if (!path) {
path = await getBinary(product, { cache });
}

if (!args.find((arg) => arg.startsWith("--user-data-dir="))) {
const tempDir = Deno.makeTempDirSync();
args.push(`--user-data-dir=${tempDir}`);
}

// Launch child process
const binArgs = [
"--remote-debugging-port=0",
Expand All @@ -280,6 +290,11 @@ export async function launch(opts?: LaunchOptions): Promise<Browser> {
...args,
];

if (!args.find((arg) => arg.startsWith("--user-data-dir="))) {
const tempDir = Deno.makeTempDirSync();
args.push(`--user-data-dir=${tempDir}`);
}

if (DEBUG) {
console.log(`Launching: ${path} ${binArgs.join(" ")}`);
}
Expand Down

0 comments on commit fd83ddf

Please sign in to comment.