Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: implement capabilities handling in session.new #2448

Merged
merged 6 commits into from
Aug 1, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
68 changes: 36 additions & 32 deletions src/bidiMapper/BidiServer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,6 @@ export class BidiServer extends EventEmitter<BidiServerEvent> {
browserCdpClient: CdpClient,
selfTargetId: string,
defaultUserContextId: Browser.UserContext,
options?: MapperOptions,
parser?: BidiCommandParameterParser,
logger?: LoggerFn
) {
Expand All @@ -99,19 +98,6 @@ export class BidiServer extends EventEmitter<BidiServerEvent> {
browserCdpClient,
logger
);
new CdpTargetManager(
cdpConnection,
browserCdpClient,
selfTargetId,
this.#eventManager,
this.#browsingContextStorage,
this.#realmStorage,
networkStorage,
this.#preloadScriptStorage,
defaultUserContextId,
options?.unhandledPromptBehavior,
logger
);
this.#commandProcessor = new CommandProcessor(
cdpConnection,
browserCdpClient,
Expand All @@ -121,6 +107,42 @@ export class BidiServer extends EventEmitter<BidiServerEvent> {
this.#preloadScriptStorage,
networkStorage,
parser,
async (options: MapperOptions) => {
// This is required to ignore certificate errors when service worker is fetched.
await browserCdpClient.sendCommand(
'Security.setIgnoreCertificateErrors',
{
ignore: options.acceptInsecureCerts ?? false,
}
);
new CdpTargetManager(
cdpConnection,
browserCdpClient,
selfTargetId,
this.#eventManager,
this.#browsingContextStorage,
this.#realmStorage,
networkStorage,
this.#preloadScriptStorage,
defaultUserContextId,
options?.unhandledPromptBehavior,
logger
);

// Needed to get events about new targets.
await browserCdpClient.sendCommand('Target.setDiscoverTargets', {
discover: true,
});

// Needed to automatically attach to new targets.
await browserCdpClient.sendCommand('Target.setAutoAttach', {
autoAttach: true,
waitForDebuggerOnStart: true,
flatten: true,
});

await this.#topLevelContextsLoaded();
},
this.#logger
);
this.#eventManager.on(EventManagerEvents.Event, ({message, event}) => {
Expand All @@ -142,7 +164,6 @@ export class BidiServer extends EventEmitter<BidiServerEvent> {
cdpConnection: CdpConnection,
browserCdpClient: CdpClient,
selfTargetId: string,
options?: MapperOptions,
parser?: BidiCommandParameterParser,
logger?: LoggerFn
): Promise<BidiServer> {
Expand All @@ -153,10 +174,6 @@ export class BidiServer extends EventEmitter<BidiServerEvent> {
const [{browserContextIds}, {targetInfos}] = await Promise.all([
browserCdpClient.sendCommand('Target.getBrowserContexts'),
browserCdpClient.sendCommand('Target.getTargets'),
// This is required to ignore certificate errors when service worker is fetched.
browserCdpClient.sendCommand('Security.setIgnoreCertificateErrors', {
ignore: options?.acceptInsecureCerts ?? false,
}),
]);
let defaultUserContextId = 'default';
for (const info of targetInfos) {
Expand All @@ -175,23 +192,10 @@ export class BidiServer extends EventEmitter<BidiServerEvent> {
browserCdpClient,
selfTargetId,
defaultUserContextId,
options,
parser,
logger
);
// Needed to get events about new targets.
await browserCdpClient.sendCommand('Target.setDiscoverTargets', {
discover: true,
});

// Needed to automatically attach to new targets.
await browserCdpClient.sendCommand('Target.setAutoAttach', {
autoAttach: true,
waitForDebuggerOnStart: true,
flatten: true,
});

await server.#topLevelContextsLoaded();
return server;
}

Expand Down
5 changes: 4 additions & 1 deletion src/bidiMapper/CommandProcessor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ import type {Result} from '../utils/result.js';

import {BidiNoOpParser} from './BidiNoOpParser.js';
import type {BidiCommandParameterParser} from './BidiParser.js';
import type {MapperOptions} from './BidiServer.js';
import {BrowserProcessor} from './modules/browser/BrowserProcessor.js';
import {CdpProcessor} from './modules/cdp/CdpProcessor.js';
import {BrowsingContextProcessor} from './modules/context/BrowsingContextProcessor.js';
Expand Down Expand Up @@ -82,6 +83,7 @@ export class CommandProcessor extends EventEmitter<CommandProcessorEventsMap> {
preloadScriptStorage: PreloadScriptStorage,
networkStorage: NetworkStorage,
parser: BidiCommandParameterParser = new BidiNoOpParser(),
initConnection: (options: MapperOptions) => Promise<void>,
logger?: LoggerFn
) {
super();
Expand Down Expand Up @@ -118,7 +120,8 @@ export class CommandProcessor extends EventEmitter<CommandProcessorEventsMap> {
);
this.#sessionProcessor = new SessionProcessor(
eventManager,
browserCdpClient
browserCdpClient,
initConnection
);
this.#storageProcessor = new StorageProcessor(
browserCdpClient,
Expand Down
71 changes: 65 additions & 6 deletions src/bidiMapper/modules/session/SessionProcessor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,38 +17,97 @@

import type {CdpClient} from '../../../cdp/CdpClient.js';
import type {BidiPlusChannel} from '../../../protocol/chromium-bidi.js';
import type {
ChromiumBidi,
EmptyResult,
import {
InvalidArgumentException,
Session,
type ChromiumBidi,
type EmptyResult,
} from '../../../protocol/protocol.js';
import type {MapperOptions} from '../../BidiServer.js';

import type {EventManager} from './EventManager.js';

export class SessionProcessor {
#eventManager: EventManager;
#browserCdpClient: CdpClient;
#initConnection: (opts: MapperOptions) => Promise<void>;
#created = false;

constructor(eventManager: EventManager, browserCdpClient: CdpClient) {
constructor(
eventManager: EventManager,
browserCdpClient: CdpClient,
initConnection: (opts: MapperOptions) => Promise<void>
) {
this.#eventManager = eventManager;
this.#browserCdpClient = browserCdpClient;
this.#initConnection = initConnection;
}

status(): Session.StatusResult {
return {ready: false, message: 'already connected'};
}

async new(_params: Session.NewParameters): Promise<Session.NewResult> {
#getMapperOptions(capabilities: any): MapperOptions {
const acceptInsecureCerts =
capabilities?.alwaysMatch?.acceptInsecureCerts ?? false;
const unhandledPromptBehavior = this.#getUnhandledPromptBehavior(
capabilities?.alwaysMatch?.unhandledPromptBehavior
);

return {acceptInsecureCerts, unhandledPromptBehavior};
}

#getUnhandledPromptBehavior(
capabilityValue: unknown
): Session.UserPromptHandler | undefined {
if (capabilityValue === undefined) {
return undefined;
}
if (typeof capabilityValue === 'object') {
// Do not validate capabilities. Incorrect ones will be ignored by Mapper.
return capabilityValue as Session.UserPromptHandler;
}
if (typeof capabilityValue !== 'string') {
throw new InvalidArgumentException(
`Unexpected 'unhandledPromptBehavior' type: ${typeof capabilityValue}`
);
}
switch (capabilityValue) {
case 'accept':
case 'accept and notify':
return {default: Session.UserPromptHandlerType.Accept};
case 'dismiss':
case 'dismiss and notify':
return {default: Session.UserPromptHandlerType.Dismiss};
case 'ignore':
return {default: Session.UserPromptHandlerType.Ignore};
default:
throw new InvalidArgumentException(
`Unexpected 'unhandledPromptBehavior' value: ${capabilityValue}`
);
}
}

async new(params: Session.NewParameters): Promise<Session.NewResult> {
if (this.#created) {
throw new Error('Session has been already created.');
}
this.#created = true;
// Since mapper exists, there is a session already.
// Still the mapper can handle capabilities for us.
// Currently, only Puppeteer calls here but, eventually, every client
// should delegrate capability processing here.
await this.#initConnection(this.#getMapperOptions(params.capabilities));

const version =
await this.#browserCdpClient.sendCommand('Browser.getVersion');

return {
sessionId: 'unknown',
capabilities: {
acceptInsecureCerts: false,
acceptInsecureCerts: Boolean(
params.capabilities.alwaysMatch?.acceptInsecureCerts
),
browserName: version.product,
browserVersion: version.revision,
platformName: '',
Expand Down
5 changes: 1 addition & 4 deletions src/bidiServer/BrowserInstance.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,6 @@ import {
import debug from 'debug';
import WebSocket from 'ws';

import type {MapperOptions} from '../bidiMapper/BidiServer.js';
import {MapperCdpConnection} from '../cdp/CdpConnection.js';
import {WebSocketTransport} from '../utils/WebsocketTransport.js';

Expand Down Expand Up @@ -58,7 +57,6 @@ export class BrowserInstance {

static async run(
chromeOptions: ChromeOptions,
mapperOptions: MapperOptions,
verbose: boolean
): Promise<BrowserInstance> {
const profileDir = await mkdtemp(
Expand Down Expand Up @@ -121,8 +119,7 @@ export class BrowserInstance {
const mapperCdpConnection = await MapperServerCdpConnection.create(
cdpConnection,
mapperTabSource,
verbose,
mapperOptions
verbose
);

return new BrowserInstance(mapperCdpConnection, browserProcess);
Expand Down
17 changes: 6 additions & 11 deletions src/bidiServer/MapperCdpConnection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@
import debug, {type Debugger} from 'debug';
import type {Protocol} from 'devtools-protocol';

import type {MapperOptions} from '../bidiMapper/BidiServer.js';
import type {MapperCdpClient} from '../cdp/CdpClient.js';
import type {MapperCdpConnection} from '../cdp/CdpConnection.js';
import type {LogPrefix, LogType} from '../utils/log.js';
Expand Down Expand Up @@ -47,15 +46,13 @@ export class MapperServerCdpConnection {
static async create(
cdpConnection: MapperCdpConnection,
mapperTabSource: string,
verbose: boolean,
mapperOptions: MapperOptions
verbose: boolean
): Promise<MapperServerCdpConnection> {
try {
const bidiSession = await this.#initMapper(
cdpConnection,
mapperTabSource,
verbose,
mapperOptions
verbose
);
return new MapperServerCdpConnection(cdpConnection, bidiSession);
} catch (e) {
Expand Down Expand Up @@ -140,10 +137,9 @@ export class MapperServerCdpConnection {
static async #initMapper(
cdpConnection: MapperCdpConnection,
mapperTabSource: string,
verbose: boolean,
mapperOptions: MapperOptions
verbose: boolean
): Promise<SimpleTransport> {
debugInternal('Initializing Mapper.', mapperOptions);
debugInternal('Initializing Mapper.');

const browserClient = await cdpConnection.createBrowserSession();

Expand Down Expand Up @@ -214,10 +210,9 @@ export class MapperServerCdpConnection {
expression: mapperTabSource,
});

// TODO: handle errors in all these evaluate calls!
await mapperCdpClient.sendCommand('Runtime.evaluate', {
expression: `window.runMapperInstance('${mapperTabTargetId}', ${JSON.stringify(
mapperOptions
)})`,
expression: `window.runMapperInstance('${mapperTabTargetId}')`,
awaitPromise: true,
});

Expand Down
Loading
Loading