Add Brave CDP automation, replace Oracle browser mode

Connects to user's running Brave via Chrome DevTools Protocol
to automate ChatGPT interaction. Uses puppeteer-core to open a
tab, send the prompt, wait for response, and extract the result.

No cookies, no separate profiles, no copy/paste. Just connects
to the browser where the user is already logged in.

One-time setup: relaunch Brave with --remote-debugging-port=9222

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
Taylor Eernisse
2026-02-07 16:16:41 -05:00
parent d776a266a8
commit e7882b917b
4163 changed files with 782828 additions and 148 deletions

View File

@@ -0,0 +1,56 @@
/**
* Copyright 2022 Google LLC.
* Copyright (c) Microsoft Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import type { GoogChannel } from '../../../protocol/chromium-bidi.js';
import { type Browser, ChromiumBidi, type BrowsingContext } from '../../../protocol/protocol.js';
import { EventEmitter } from '../../../utils/EventEmitter.js';
import type { Result } from '../../../utils/result.js';
import { OutgoingMessage } from '../../OutgoingMessage.js';
import type { UserContextStorage } from '../browser/UserContextStorage.js';
import type { BrowsingContextStorage } from '../context/BrowsingContextStorage.js';
import { SubscriptionManager } from './SubscriptionManager.js';
export declare const enum EventManagerEvents {
Event = "event"
}
interface EventManagerEventsMap extends Record<string | symbol, unknown> {
[EventManagerEvents.Event]: {
message: Promise<Result<OutgoingMessage>>;
event: string;
};
}
/**
* Subscription item is a pair of event name and context id.
*/
export interface SubscriptionItem {
contextId: BrowsingContext.BrowsingContext;
event: ChromiumBidi.EventNames;
}
export declare class EventManager extends EventEmitter<EventManagerEventsMap> {
#private;
constructor(browsingContextStorage: BrowsingContextStorage, userContextStorage: UserContextStorage);
get subscriptionManager(): SubscriptionManager;
addSubscribeHook(event: ChromiumBidi.EventNames, hook: (contextId: BrowsingContext.BrowsingContext) => Promise<void>): void;
registerEvent(event: ChromiumBidi.Event, contextId: BrowsingContext.BrowsingContext): void;
registerGlobalEvent(event: ChromiumBidi.Event): void;
registerPromiseEvent(event: Promise<Result<ChromiumBidi.Event>>, contextId: BrowsingContext.BrowsingContext, eventName: ChromiumBidi.EventNames): void;
registerGlobalPromiseEvent(event: Promise<Result<ChromiumBidi.Event>>, eventName: ChromiumBidi.EventNames): void;
subscribe(eventNames: ChromiumBidi.EventNames[], contextIds: BrowsingContext.BrowsingContext[], userContextIds: Browser.UserContext[], googChannel: GoogChannel): Promise<string>;
unsubscribe(eventNames: ChromiumBidi.EventNames[], googChannel: GoogChannel): Promise<void>;
unsubscribeByIds(subscriptionIds: string[]): Promise<void>;
toggleModulesIfNeeded(): Promise<void>;
clearBufferedEvents(contextId: string): void;
}
export {};

View File

@@ -0,0 +1,269 @@
"use strict";
/**
* Copyright 2022 Google LLC.
* Copyright (c) Microsoft Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var _a;
Object.defineProperty(exports, "__esModule", { value: true });
exports.EventManager = void 0;
const protocol_js_1 = require("../../../protocol/protocol.js");
const Buffer_js_1 = require("../../../utils/Buffer.js");
const DefaultMap_js_1 = require("../../../utils/DefaultMap.js");
const EventEmitter_js_1 = require("../../../utils/EventEmitter.js");
const IdWrapper_js_1 = require("../../../utils/IdWrapper.js");
const OutgoingMessage_js_1 = require("../../OutgoingMessage.js");
const events_js_1 = require("./events.js");
const SubscriptionManager_js_1 = require("./SubscriptionManager.js");
class EventWrapper {
#idWrapper = new IdWrapper_js_1.IdWrapper();
#contextId;
#event;
constructor(event, contextId) {
this.#event = event;
this.#contextId = contextId;
}
get id() {
return this.#idWrapper.id;
}
get contextId() {
return this.#contextId;
}
get event() {
return this.#event;
}
}
/**
* Maps event name to a desired buffer length.
*/
const eventBufferLength = new Map([[protocol_js_1.ChromiumBidi.Log.EventNames.LogEntryAdded, 100]]);
class EventManager extends EventEmitter_js_1.EventEmitter {
/**
* Maps event name to a set of contexts where this event already happened.
* Needed for getting buffered events from all the contexts in case of
* subscripting to all contexts.
*/
#eventToContextsMap = new DefaultMap_js_1.DefaultMap(() => new Set());
/**
* Maps `eventName` + `browsingContext` to buffer. Used to get buffered events
* during subscription. Channel-agnostic.
*/
#eventBuffers = new Map();
/**
* Maps `eventName` + `browsingContext` to Map of goog:channel to last id.
* Used to avoid sending duplicated events when user
* subscribes -> unsubscribes -> subscribes.
*/
#lastMessageSent = new Map();
#subscriptionManager;
#browsingContextStorage;
/**
* Map of event name to hooks to be called when client is subscribed to the event.
*/
#subscribeHooks;
#userContextStorage;
constructor(browsingContextStorage, userContextStorage) {
super();
this.#browsingContextStorage = browsingContextStorage;
this.#userContextStorage = userContextStorage;
this.#subscriptionManager = new SubscriptionManager_js_1.SubscriptionManager(browsingContextStorage);
this.#subscribeHooks = new DefaultMap_js_1.DefaultMap(() => []);
}
get subscriptionManager() {
return this.#subscriptionManager;
}
/**
* Returns consistent key to be used to access value maps.
*/
static #getMapKey(eventName, browsingContext) {
return JSON.stringify({ eventName, browsingContext });
}
addSubscribeHook(event, hook) {
this.#subscribeHooks.get(event).push(hook);
}
registerEvent(event, contextId) {
this.registerPromiseEvent(Promise.resolve({
kind: 'success',
value: event,
}), contextId, event.method);
}
registerGlobalEvent(event) {
this.registerGlobalPromiseEvent(Promise.resolve({
kind: 'success',
value: event,
}), event.method);
}
registerPromiseEvent(event, contextId, eventName) {
const eventWrapper = new EventWrapper(event, contextId);
const sortedGoogChannels = this.#subscriptionManager.getGoogChannelsSubscribedToEvent(eventName, contextId);
this.#bufferEvent(eventWrapper, eventName);
// Send events to channels in the subscription priority.
for (const googChannel of sortedGoogChannels) {
this.emit("event" /* EventManagerEvents.Event */, {
message: OutgoingMessage_js_1.OutgoingMessage.createFromPromise(event, googChannel),
event: eventName,
});
this.#markEventSent(eventWrapper, googChannel, eventName);
}
}
registerGlobalPromiseEvent(event, eventName) {
const eventWrapper = new EventWrapper(event, null);
const sortedGoogChannels = this.#subscriptionManager.getGoogChannelsSubscribedToEventGlobally(eventName);
this.#bufferEvent(eventWrapper, eventName);
// Send events to goog:channels in the subscription priority.
for (const googChannel of sortedGoogChannels) {
this.emit("event" /* EventManagerEvents.Event */, {
message: OutgoingMessage_js_1.OutgoingMessage.createFromPromise(event, googChannel),
event: eventName,
});
this.#markEventSent(eventWrapper, googChannel, eventName);
}
}
async subscribe(eventNames, contextIds, userContextIds, googChannel) {
for (const name of eventNames) {
(0, events_js_1.assertSupportedEvent)(name);
}
if (userContextIds.length && contextIds.length) {
throw new protocol_js_1.InvalidArgumentException('Both userContexts and contexts cannot be specified.');
}
// First check if all the contexts are known.
this.#browsingContextStorage.verifyContextsList(contextIds);
// Validate user contexts.
await this.#userContextStorage.verifyUserContextIdList(userContextIds);
const unrolledEventNames = new Set((0, SubscriptionManager_js_1.unrollEvents)(eventNames));
const subscribeStepEvents = new Map();
const subscriptionNavigableIds = new Set(contextIds.length
? contextIds.map((contextId) => {
const id = this.#browsingContextStorage.findTopLevelContextId(contextId);
if (!id) {
throw new protocol_js_1.InvalidArgumentException('Invalid context id');
}
return id;
})
: this.#browsingContextStorage.getTopLevelContexts().map((c) => c.id));
for (const eventName of unrolledEventNames) {
const subscribedNavigableIds = new Set(this.#browsingContextStorage
.getTopLevelContexts()
.map((c) => c.id)
.filter((id) => {
return this.#subscriptionManager.isSubscribedTo(eventName, id);
}));
subscribeStepEvents.set(eventName, (0, SubscriptionManager_js_1.difference)(subscriptionNavigableIds, subscribedNavigableIds));
}
const subscription = this.#subscriptionManager.subscribe(eventNames, contextIds, userContextIds, googChannel);
for (const eventName of subscription.eventNames) {
for (const contextId of subscriptionNavigableIds) {
for (const eventWrapper of this.#getBufferedEvents(eventName, contextId, googChannel)) {
// The order of the events is important.
this.emit("event" /* EventManagerEvents.Event */, {
message: OutgoingMessage_js_1.OutgoingMessage.createFromPromise(eventWrapper.event, googChannel),
event: eventName,
});
this.#markEventSent(eventWrapper, googChannel, eventName);
}
}
}
for (const [eventName, contextIds] of subscribeStepEvents) {
for (const contextId of contextIds) {
this.#subscribeHooks.get(eventName).forEach((hook) => hook(contextId));
}
}
await this.toggleModulesIfNeeded();
return subscription.id;
}
async unsubscribe(eventNames, googChannel) {
for (const name of eventNames) {
(0, events_js_1.assertSupportedEvent)(name);
}
this.#subscriptionManager.unsubscribe(eventNames, googChannel);
await this.toggleModulesIfNeeded();
}
async unsubscribeByIds(subscriptionIds) {
this.#subscriptionManager.unsubscribeById(subscriptionIds);
await this.toggleModulesIfNeeded();
}
async toggleModulesIfNeeded() {
// TODO(1): Only update changed subscribers
// TODO(2): Enable for Worker Targets
await Promise.all(this.#browsingContextStorage.getAllContexts().map(async (context) => {
return await context.toggleModulesIfNeeded();
}));
}
clearBufferedEvents(contextId) {
for (const eventName of eventBufferLength.keys()) {
const bufferMapKey = _a.#getMapKey(eventName, contextId);
this.#eventBuffers.delete(bufferMapKey);
}
}
/**
* If the event is buffer-able, put it in the buffer.
*/
#bufferEvent(eventWrapper, eventName) {
if (!eventBufferLength.has(eventName)) {
// Do nothing if the event is no buffer-able.
return;
}
const bufferMapKey = _a.#getMapKey(eventName, eventWrapper.contextId);
if (!this.#eventBuffers.has(bufferMapKey)) {
this.#eventBuffers.set(bufferMapKey, new Buffer_js_1.Buffer(eventBufferLength.get(eventName)));
}
this.#eventBuffers.get(bufferMapKey).add(eventWrapper);
// Add the context to the list of contexts having `eventName` events.
this.#eventToContextsMap.get(eventName).add(eventWrapper.contextId);
}
/**
* If the event is buffer-able, mark it as sent to the given contextId and goog:channel.
*/
#markEventSent(eventWrapper, googChannel, eventName) {
if (!eventBufferLength.has(eventName)) {
// Do nothing if the event is no buffer-able.
return;
}
const lastSentMapKey = _a.#getMapKey(eventName, eventWrapper.contextId);
const lastId = Math.max(this.#lastMessageSent.get(lastSentMapKey)?.get(googChannel) ?? 0, eventWrapper.id);
const googChannelMap = this.#lastMessageSent.get(lastSentMapKey);
if (googChannelMap) {
googChannelMap.set(googChannel, lastId);
}
else {
this.#lastMessageSent.set(lastSentMapKey, new Map([[googChannel, lastId]]));
}
}
/**
* Returns events which are buffered and not yet sent to the given goog:channel events.
*/
#getBufferedEvents(eventName, contextId, googChannel) {
const bufferMapKey = _a.#getMapKey(eventName, contextId);
const lastSentMessageId = this.#lastMessageSent.get(bufferMapKey)?.get(googChannel) ?? -Infinity;
const result = this.#eventBuffers
.get(bufferMapKey)
?.get()
.filter((wrapper) => wrapper.id > lastSentMessageId) ?? [];
if (contextId === null) {
// For global subscriptions, events buffered in each context should be sent back.
Array.from(this.#eventToContextsMap.get(eventName).keys())
.filter((_contextId) =>
// Events without context are already in the result.
_contextId !== null &&
// Events from deleted contexts should not be sent.
this.#browsingContextStorage.hasContext(_contextId))
.map((_contextId) => this.#getBufferedEvents(eventName, _contextId, googChannel))
.forEach((events) => result.push(...events));
}
return result.sort((e1, e2) => e1.id - e2.id);
}
}
exports.EventManager = EventManager;
_a = EventManager;
//# sourceMappingURL=EventManager.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,29 @@
/**
* Copyright 2023 Google LLC.
* Copyright (c) Microsoft Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import type { CdpClient } from '../../../cdp/CdpClient.js';
import type { GoogChannel } from '../../../protocol/chromium-bidi.js';
import { type EmptyResult, Session } from '../../../protocol/protocol.js';
import type { MapperOptions } from '../../MapperOptions.js';
import type { EventManager } from './EventManager.js';
export declare class SessionProcessor {
#private;
constructor(eventManager: EventManager, browserCdpClient: CdpClient, initConnection: (opts: MapperOptions) => Promise<void>);
status(): Session.StatusResult;
new(params: Session.NewParameters): Promise<Session.NewResult>;
subscribe(params: Session.SubscribeParameters, googChannel?: GoogChannel): Promise<Session.SubscribeResult>;
unsubscribe(params: Session.UnsubscribeParameters, googChannel?: GoogChannel): Promise<EmptyResult>;
}

View File

@@ -0,0 +1,131 @@
"use strict";
/**
* Copyright 2023 Google LLC.
* Copyright (c) Microsoft Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.SessionProcessor = void 0;
const protocol_js_1 = require("../../../protocol/protocol.js");
class SessionProcessor {
#eventManager;
#browserCdpClient;
#initConnection;
#created = false;
constructor(eventManager, browserCdpClient, initConnection) {
this.#eventManager = eventManager;
this.#browserCdpClient = browserCdpClient;
this.#initConnection = initConnection;
}
status() {
return { ready: false, message: 'already connected' };
}
#mergeCapabilities(capabilitiesRequest) {
// Roughly following https://www.w3.org/TR/webdriver2/#dfn-capabilities-processing.
// Validations should already be done by the parser.
const mergedCapabilities = [];
for (const first of capabilitiesRequest.firstMatch ?? [{}]) {
const result = {
...capabilitiesRequest.alwaysMatch,
};
for (const key of Object.keys(first)) {
if (result[key] !== undefined) {
throw new protocol_js_1.InvalidArgumentException(`Capability ${key} in firstMatch is already defined in alwaysMatch`);
}
result[key] = first[key];
}
mergedCapabilities.push(result);
}
const match = mergedCapabilities.find((c) => c.browserName === 'chrome') ??
mergedCapabilities[0] ??
{};
match.unhandledPromptBehavior = this.#getUnhandledPromptBehavior(match.unhandledPromptBehavior);
return match;
}
#getUnhandledPromptBehavior(capabilityValue) {
if (capabilityValue === undefined) {
return undefined;
}
if (typeof capabilityValue === 'object') {
// Do not validate capabilities. Incorrect ones will be ignored by Mapper.
return capabilityValue;
}
if (typeof capabilityValue !== 'string') {
throw new protocol_js_1.InvalidArgumentException(`Unexpected 'unhandledPromptBehavior' type: ${typeof capabilityValue}`);
}
switch (capabilityValue) {
// `beforeUnload: accept` has higher priority over string capability, as the latest
// one is set to "fallbackDefault".
// https://w3c.github.io/webdriver/#dfn-deserialize-as-an-unhandled-prompt-behavior
// https://w3c.github.io/webdriver/#dfn-get-the-prompt-handler
case 'accept':
case 'accept and notify':
return {
default: "accept" /* Session.UserPromptHandlerType.Accept */,
beforeUnload: "accept" /* Session.UserPromptHandlerType.Accept */,
};
case 'dismiss':
case 'dismiss and notify':
return {
default: "dismiss" /* Session.UserPromptHandlerType.Dismiss */,
beforeUnload: "accept" /* Session.UserPromptHandlerType.Accept */,
};
case 'ignore':
return {
default: "ignore" /* Session.UserPromptHandlerType.Ignore */,
beforeUnload: "accept" /* Session.UserPromptHandlerType.Accept */,
};
default:
throw new protocol_js_1.InvalidArgumentException(`Unexpected 'unhandledPromptBehavior' value: ${capabilityValue}`);
}
}
async new(params) {
if (this.#created) {
throw new Error('Session has been already created.');
}
this.#created = true;
const matchedCapabitlites = this.#mergeCapabilities(params.capabilities);
await this.#initConnection(matchedCapabitlites);
const version = await this.#browserCdpClient.sendCommand('Browser.getVersion');
return {
sessionId: 'unknown',
capabilities: {
...matchedCapabitlites,
acceptInsecureCerts: matchedCapabitlites.acceptInsecureCerts ?? false,
browserName: version.product,
browserVersion: version.revision,
platformName: '',
setWindowRect: false,
webSocketUrl: '',
userAgent: version.userAgent,
},
};
}
async subscribe(params, googChannel = null) {
const subscription = await this.#eventManager.subscribe(params.events, params.contexts ?? [], params.userContexts ?? [], googChannel);
return {
subscription,
};
}
async unsubscribe(params, googChannel = null) {
if ('subscriptions' in params) {
await this.#eventManager.unsubscribeByIds(params.subscriptions);
return {};
}
await this.#eventManager.unsubscribe(params.events, googChannel);
return {};
}
}
exports.SessionProcessor = SessionProcessor;
//# sourceMappingURL=SessionProcessor.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"SessionProcessor.js","sourceRoot":"","sources":["../../../../../src/bidiMapper/modules/session/SessionProcessor.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG;;;AAIH,+DAKuC;AAKvC,MAAa,gBAAgB;IAC3B,aAAa,CAAe;IAC5B,iBAAiB,CAAY;IAC7B,eAAe,CAAyC;IACxD,QAAQ,GAAG,KAAK,CAAC;IAEjB,YACE,YAA0B,EAC1B,gBAA2B,EAC3B,cAAsD;QAEtD,IAAI,CAAC,aAAa,GAAG,YAAY,CAAC;QAClC,IAAI,CAAC,iBAAiB,GAAG,gBAAgB,CAAC;QAC1C,IAAI,CAAC,eAAe,GAAG,cAAc,CAAC;IACxC,CAAC;IAED,MAAM;QACJ,OAAO,EAAC,KAAK,EAAE,KAAK,EAAE,OAAO,EAAE,mBAAmB,EAAC,CAAC;IACtD,CAAC;IAED,kBAAkB,CAChB,mBAAgD;QAEhD,mFAAmF;QACnF,oDAAoD;QAEpD,MAAM,kBAAkB,GAAG,EAAE,CAAC;QAE9B,KAAK,MAAM,KAAK,IAAI,mBAAmB,CAAC,UAAU,IAAI,CAAC,EAAE,CAAC,EAAE,CAAC;YAC3D,MAAM,MAAM,GAAG;gBACb,GAAG,mBAAmB,CAAC,WAAW;aACnC,CAAC;YACF,KAAK,MAAM,GAAG,IAAI,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC;gBACrC,IAAI,MAAM,CAAC,GAAG,CAAC,KAAK,SAAS,EAAE,CAAC;oBAC9B,MAAM,IAAI,sCAAwB,CAChC,cAAc,GAAG,k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IAAI,CAAC,aAAa,CAAC,gBAAgB,CAAC,MAAM,CAAC,aAAa,CAAC,CAAC;YAChE,OAAO,EAAE,CAAC;QACZ,CAAC;QACD,MAAM,IAAI,CAAC,aAAa,CAAC,WAAW,CAClC,MAAM,CAAC,MAAmC,EAC1C,WAAW,CACZ,CAAC;QACF,OAAO,EAAE,CAAC;IACZ,CAAC;CACF;AA7JD,4CA6JC"}

View File

@@ -0,0 +1,64 @@
/**
* Copyright 2022 Google LLC.
* Copyright (c) Microsoft Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import type { GoogChannel } from '../../../protocol/chromium-bidi.js';
import { type Browser, type BrowsingContext, ChromiumBidi } from '../../../protocol/protocol.js';
import type { BrowsingContextStorage } from '../context/BrowsingContextStorage.js';
/**
* Returns the cartesian product of the given arrays.
*
* Example:
* cartesian([1, 2], ['a', 'b']); => [[1, 'a'], [1, 'b'], [2, 'a'], [2, 'b']]
*/
export declare function cartesianProduct(...a: any[][]): any[];
/** Expands "AllEvents" events into atomic events. */
export declare function unrollEvents(events: ChromiumBidi.EventNames[]): Iterable<ChromiumBidi.EventNames>;
export interface Subscription {
id: string;
topLevelTraversableIds: Set<BrowsingContext.BrowsingContext>;
userContextIds: Set<string>;
eventNames: Set<ChromiumBidi.EventNames>;
googChannel: GoogChannel;
}
export declare class SubscriptionManager {
#private;
constructor(browsingContextStorage: BrowsingContextStorage);
getGoogChannelsSubscribedToEvent(eventName: ChromiumBidi.EventNames, contextId: BrowsingContext.BrowsingContext): GoogChannel[];
getGoogChannelsSubscribedToEventGlobally(eventName: ChromiumBidi.EventNames): GoogChannel[];
isSubscribedTo(moduleOrEvent: ChromiumBidi.EventNames, contextId: BrowsingContext.BrowsingContext): boolean;
/**
* Subscribes to event in the given context and goog:channel.
* @return {SubscriptionItem[]} List of
* subscriptions. If the event is a whole module, it will return all the specific
* events. If the contextId is null, it will return all the top-level contexts which were
* not subscribed before the command.
*/
subscribe(eventNames: ChromiumBidi.EventNames[], contextIds: BrowsingContext.BrowsingContext[], userContextIds: Browser.UserContext[], googChannel: GoogChannel): Subscription;
/**
* Unsubscribes atomically from all events in the given contexts and channel.
*
* This is a legacy spec branch to unsubscribe by attributes.
*/
unsubscribe(inputEventNames: ChromiumBidi.EventNames[], googChannel: GoogChannel): void;
/**
* Unsubscribes by subscriptionId.
*/
unsubscribeById(subscriptionIds: string[]): void;
}
/**
* Replace with Set.prototype.difference once Node 20 is dropped.
*/
export declare function difference<T>(setA: Set<T>, setB: Set<T>): Set<T>;

View File

@@ -0,0 +1,273 @@
"use strict";
/**
* Copyright 2022 Google LLC.
* Copyright (c) Microsoft Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.SubscriptionManager = void 0;
exports.cartesianProduct = cartesianProduct;
exports.unrollEvents = unrollEvents;
exports.difference = difference;
const protocol_js_1 = require("../../../protocol/protocol.js");
const uuid_js_1 = require("../../../utils/uuid.js");
/**
* Returns the cartesian product of the given arrays.
*
* Example:
* cartesian([1, 2], ['a', 'b']); => [[1, 'a'], [1, 'b'], [2, 'a'], [2, 'b']]
*/
function cartesianProduct(...a) {
return a.reduce((a, b) => a.flatMap((d) => b.map((e) => [d, e].flat())));
}
/** Expands "AllEvents" events into atomic events. */
function unrollEvents(events) {
const allEvents = new Set();
function addEvents(events) {
for (const event of events) {
allEvents.add(event);
}
}
for (const event of events) {
switch (event) {
case protocol_js_1.ChromiumBidi.BiDiModule.Bluetooth:
addEvents(Object.values(protocol_js_1.ChromiumBidi.Bluetooth.EventNames));
break;
case protocol_js_1.ChromiumBidi.BiDiModule.BrowsingContext:
addEvents(Object.values(protocol_js_1.ChromiumBidi.BrowsingContext.EventNames));
break;
case protocol_js_1.ChromiumBidi.BiDiModule.Input:
addEvents(Object.values(protocol_js_1.ChromiumBidi.Input.EventNames));
break;
case protocol_js_1.ChromiumBidi.BiDiModule.Log:
addEvents(Object.values(protocol_js_1.ChromiumBidi.Log.EventNames));
break;
case protocol_js_1.ChromiumBidi.BiDiModule.Network:
addEvents(Object.values(protocol_js_1.ChromiumBidi.Network.EventNames));
break;
case protocol_js_1.ChromiumBidi.BiDiModule.Script:
addEvents(Object.values(protocol_js_1.ChromiumBidi.Script.EventNames));
break;
case protocol_js_1.ChromiumBidi.BiDiModule.Speculation:
addEvents(Object.values(protocol_js_1.ChromiumBidi.Speculation.EventNames));
break;
default:
allEvents.add(event);
}
}
return allEvents.values();
}
class SubscriptionManager {
#subscriptions = [];
#knownSubscriptionIds = new Set();
#browsingContextStorage;
constructor(browsingContextStorage) {
this.#browsingContextStorage = browsingContextStorage;
}
getGoogChannelsSubscribedToEvent(eventName, contextId) {
const googChannels = new Set();
for (const subscription of this.#subscriptions) {
if (this.#isSubscribedTo(subscription, eventName, contextId)) {
googChannels.add(subscription.googChannel);
}
}
return Array.from(googChannels);
}
getGoogChannelsSubscribedToEventGlobally(eventName) {
const googChannels = new Set();
for (const subscription of this.#subscriptions) {
if (this.#isSubscribedTo(subscription, eventName)) {
googChannels.add(subscription.googChannel);
}
}
return Array.from(googChannels);
}
#isSubscribedTo(subscription, moduleOrEvent, browsingContextId) {
let includesEvent = false;
for (const eventName of subscription.eventNames) {
// This also covers the `goog:cdp` case where
// we don't unroll the event names
if (
// Event explicitly subscribed
eventName === moduleOrEvent ||
// Event subscribed via module
eventName === moduleOrEvent.split('.').at(0) ||
// Event explicitly subscribed compared to module
eventName.split('.').at(0) === moduleOrEvent) {
includesEvent = true;
break;
}
}
if (!includesEvent) {
return false;
}
// user context subscription.
if (subscription.userContextIds.size !== 0) {
if (!browsingContextId) {
return false;
}
const context = this.#browsingContextStorage.findContext(browsingContextId);
if (!context) {
return false;
}
return subscription.userContextIds.has(context.userContext);
}
// context subscription.
if (subscription.topLevelTraversableIds.size !== 0) {
if (!browsingContextId) {
return false;
}
const topLevelContext = this.#browsingContextStorage.findTopLevelContextId(browsingContextId);
return (topLevelContext !== null &&
subscription.topLevelTraversableIds.has(topLevelContext));
}
// global subscription.
return true;
}
isSubscribedTo(moduleOrEvent, contextId) {
for (const subscription of this.#subscriptions) {
if (this.#isSubscribedTo(subscription, moduleOrEvent, contextId)) {
return true;
}
}
return false;
}
/**
* Subscribes to event in the given context and goog:channel.
* @return {SubscriptionItem[]} List of
* subscriptions. If the event is a whole module, it will return all the specific
* events. If the contextId is null, it will return all the top-level contexts which were
* not subscribed before the command.
*/
subscribe(eventNames, contextIds, userContextIds, googChannel) {
// All the subscriptions are handled on the top-level contexts.
const subscription = {
id: (0, uuid_js_1.uuidv4)(),
eventNames: new Set(unrollEvents(eventNames)),
topLevelTraversableIds: new Set(contextIds.map((contextId) => {
const topLevelContext = this.#browsingContextStorage.findTopLevelContextId(contextId);
if (!topLevelContext) {
throw new protocol_js_1.NoSuchFrameException(`Top-level navigable not found for context id ${contextId}`);
}
return topLevelContext;
})),
userContextIds: new Set(userContextIds),
googChannel,
};
this.#subscriptions.push(subscription);
this.#knownSubscriptionIds.add(subscription.id);
return subscription;
}
/**
* Unsubscribes atomically from all events in the given contexts and channel.
*
* This is a legacy spec branch to unsubscribe by attributes.
*/
unsubscribe(inputEventNames, googChannel) {
const eventNames = new Set(unrollEvents(inputEventNames));
const newSubscriptions = [];
const eventsMatched = new Set();
for (const subscription of this.#subscriptions) {
if (subscription.googChannel !== googChannel) {
newSubscriptions.push(subscription);
continue;
}
// Skip user context subscriptions.
if (subscription.userContextIds.size !== 0) {
newSubscriptions.push(subscription);
continue;
}
// Skip subscriptions when none of the event names match.
if (intersection(subscription.eventNames, eventNames).size === 0) {
newSubscriptions.push(subscription);
continue;
}
// Skip non-global subscriptions.
if (subscription.topLevelTraversableIds.size !== 0) {
newSubscriptions.push(subscription);
continue;
}
const subscriptionEventNames = new Set(subscription.eventNames);
for (const eventName of eventNames) {
if (subscriptionEventNames.has(eventName)) {
eventsMatched.add(eventName);
subscriptionEventNames.delete(eventName);
}
}
if (subscriptionEventNames.size !== 0) {
newSubscriptions.push({
...subscription,
eventNames: subscriptionEventNames,
});
}
}
// If some events did not match, it is an invalid request.
if (!equal(eventsMatched, eventNames)) {
throw new protocol_js_1.InvalidArgumentException('No subscription found');
}
// Committing the new subscriptions.
this.#subscriptions = newSubscriptions;
}
/**
* Unsubscribes by subscriptionId.
*/
unsubscribeById(subscriptionIds) {
const subscriptionIdsSet = new Set(subscriptionIds);
const unknownIds = difference(subscriptionIdsSet, this.#knownSubscriptionIds);
if (unknownIds.size !== 0) {
throw new protocol_js_1.InvalidArgumentException('No subscription found');
}
this.#subscriptions = this.#subscriptions.filter((subscription) => {
return !subscriptionIdsSet.has(subscription.id);
});
this.#knownSubscriptionIds = difference(this.#knownSubscriptionIds, subscriptionIdsSet);
}
}
exports.SubscriptionManager = SubscriptionManager;
/**
* Replace with Set.prototype.intersection once Node 20 is dropped.
*/
function intersection(setA, setB) {
const result = new Set();
for (const a of setA) {
if (setB.has(a)) {
result.add(a);
}
}
return result;
}
/**
* Replace with Set.prototype.difference once Node 20 is dropped.
*/
function difference(setA, setB) {
const result = new Set();
for (const a of setA) {
if (!setB.has(a)) {
result.add(a);
}
}
return result;
}
function equal(setA, setB) {
if (setA.size !== setB.size) {
return false;
}
for (const a of setA) {
if (!setB.has(a)) {
return false;
}
}
return true;
}
//# sourceMappingURL=SubscriptionManager.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,26 @@
/**
* Copyright 2023 Google LLC.
* Copyright (c) Microsoft Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { ChromiumBidi } from '../../../protocol/protocol.js';
/**
* Returns true if the given event is a CDP event.
* @see https://chromedevtools.github.io/devtools-protocol/
*/
export declare function isCdpEvent(name: string): boolean;
/**
* Asserts that the given event is known to BiDi or BiDi+, or throws otherwise.
*/
export declare function assertSupportedEvent(name: string): asserts name is ChromiumBidi.EventNames;

View File

@@ -0,0 +1,37 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.isCdpEvent = isCdpEvent;
exports.assertSupportedEvent = assertSupportedEvent;
/**
* Copyright 2023 Google LLC.
* Copyright (c) Microsoft Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
const protocol_js_1 = require("../../../protocol/protocol.js");
/**
* Returns true if the given event is a CDP event.
* @see https://chromedevtools.github.io/devtools-protocol/
*/
function isCdpEvent(name) {
return (name.split('.').at(0)?.startsWith(protocol_js_1.ChromiumBidi.BiDiModule.Cdp) ?? false);
}
/**
* Asserts that the given event is known to BiDi or BiDi+, or throws otherwise.
*/
function assertSupportedEvent(name) {
if (!protocol_js_1.ChromiumBidi.EVENT_NAMES.has(name) && !isCdpEvent(name)) {
throw new protocol_js_1.InvalidArgumentException(`Unknown event: ${name}`);
}
}
//# sourceMappingURL=events.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"events.js","sourceRoot":"","sources":["../../../../../src/bidiMapper/modules/session/events.ts"],"names":[],"mappings":";;AAyBA,gCAIC;AAKD,oDAMC;AAxCD;;;;;;;;;;;;;;;GAeG;AACH,+DAGuC;AAEvC;;;GAGG;AACH,SAAgB,UAAU,CAAC,IAAY;IACrC,OAAO,CACL,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,UAAU,CAAC,0BAAY,CAAC,UAAU,CAAC,GAAG,CAAC,IAAI,KAAK,CACxE,CAAC;AACJ,CAAC;AAED;;GAEG;AACH,SAAgB,oBAAoB,CAClC,IAAY;IAEZ,IAAI,CAAC,0BAAY,CAAC,WAAW,CAAC,GAAG,CAAC,IAAa,CAAC,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,EAAE,CAAC;QACtE,MAAM,IAAI,sCAAwB,CAAC,kBAAkB,IAAI,EAAE,CAAC,CAAC;IAC/D,CAAC;AACH,CAAC"}