Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

chromium-bidi

Package Overview
Dependencies
Maintainers
2
Versions
73
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

chromium-bidi - npm Package Compare versions

Comparing version 0.4.27 to 0.4.28

lib/cjs/bidiMapper/domains/events/events.d.ts

6

lib/cjs/bidiMapper/bidiMapper.d.ts

@@ -23,7 +23,7 @@ /**

export { BidiServer } from './BidiServer.js';
export type { ICdpConnection, ICdpConnection as CdpConnection, } from '../cdp/cdpConnection.js';
export type { ICdpClient, ICdpClient as CdpClient } from '../cdp/cdpClient.js';
export type { ICdpConnection, ICdpConnection as CdpConnection, } from '../cdp/CdpConnection.js';
export type { ICdpClient, ICdpClient as CdpClient } from '../cdp/CdpClient.js';
export { EventEmitter } from '../utils/EventEmitter.js';
export type { IBidiTransport as BidiTransport } from './BidiTransport.js';
export { OutgoingMessage } from './OutgoingMessage.js';
export type { IBidiParser as BidiParser } from './BidiParser.js';
export type { IBidiParser } from './BidiParser.js';

@@ -17,3 +17,3 @@ /**

*/
import type { ICdpConnection } from '../cdp/cdpConnection.js';
import type { ICdpConnection } from '../cdp/CdpConnection.js';
import type { ChromiumBidi } from '../protocol/protocol.js';

@@ -20,0 +20,0 @@ import { EventEmitter } from '../utils/EventEmitter.js';

@@ -22,3 +22,3 @@ "use strict";

const log_js_1 = require("../utils/log.js");
const processingQueue_js_1 = require("../utils/processingQueue.js");
const ProcessingQueue_js_1 = require("../utils/ProcessingQueue.js");
const CommandProcessor_js_1 = require("./CommandProcessor.js");

@@ -49,3 +49,3 @@ const BrowsingContextStorage_js_1 = require("./domains/context/BrowsingContextStorage.js");

this.#logger = logger;
this.#messageQueue = new processingQueue_js_1.ProcessingQueue(this.#processOutgoingMessage, this.#logger);
this.#messageQueue = new ProcessingQueue_js_1.ProcessingQueue(this.#processOutgoingMessage, this.#logger);
this.#transport = bidiTransport;

@@ -52,0 +52,0 @@ this.#transport.setOnMessage(this.#handleIncomingMessage);

@@ -17,3 +17,3 @@ /**

*/
import type { ICdpConnection } from '../cdp/cdpConnection.js';
import type { ICdpConnection } from '../cdp/CdpConnection.js';
import { type ChromiumBidi } from '../protocol/protocol.js';

@@ -20,0 +20,0 @@ import { EventEmitter } from '../utils/EventEmitter.js';

@@ -22,3 +22,3 @@ "use strict";

const assert_js_1 = require("../../../utils/assert.js");
const deferred_js_1 = require("../../../utils/deferred.js");
const Deferred_js_1 = require("../../../utils/Deferred.js");
const log_js_1 = require("../../../utils/log.js");

@@ -41,8 +41,8 @@ const unitConversions_js_1 = require("../../../utils/unitConversions.js");

Page: {
navigatedWithinDocument: new deferred_js_1.Deferred(),
navigatedWithinDocument: new Deferred_js_1.Deferred(),
lifecycleEvent: {
DOMContentLoaded: new deferred_js_1.Deferred(),
load: new deferred_js_1.Deferred(),
DOMContentLoaded: new Deferred_js_1.Deferred(),
load: new Deferred_js_1.Deferred(),
},
frameStartedLoading: new deferred_js_1.Deferred(),
frameStartedLoading: new Deferred_js_1.Deferred(),
},

@@ -387,3 +387,3 @@ };

this.#deferreds.Page.navigatedWithinDocument =
new deferred_js_1.Deferred();
new Deferred_js_1.Deferred();
}

@@ -401,3 +401,3 @@ else {

this.#deferreds.Page.lifecycleEvent.DOMContentLoaded =
new deferred_js_1.Deferred();
new Deferred_js_1.Deferred();
}

@@ -409,3 +409,3 @@ else {

this.#deferreds.Page.lifecycleEvent.load =
new deferred_js_1.Deferred();
new Deferred_js_1.Deferred();
}

@@ -617,3 +617,3 @@ else {

'invalid print parameters: content area is empty') {
throw new protocol_js_1.InvalidArgumentException(error.message);
throw new protocol_js_1.UnsupportedOperationException(error.message);
}

@@ -620,0 +620,0 @@ throw error;

@@ -1,2 +0,2 @@

import type { ICdpConnection } from '../../../cdp/cdpConnection.js';
import type { ICdpConnection } from '../../../cdp/CdpConnection.js';
import { BrowsingContext, type EmptyResult } from '../../../protocol/protocol.js';

@@ -3,0 +3,0 @@ import { type LoggerFn } from '../../../utils/log.js';

import type Protocol from 'devtools-protocol';
import type { ICdpClient } from '../../../cdp/cdpClient.js';
import { Deferred } from '../../../utils/deferred.js';
import type { ICdpClient } from '../../../cdp/CdpClient.js';
import { Deferred } from '../../../utils/Deferred.js';
import type { Result } from '../../../utils/result.js';

@@ -5,0 +5,0 @@ import type { EventManager } from '../events/EventManager.js';

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.CdpTarget = void 0;
const deferred_js_1 = require("../../../utils/deferred.js");
const Deferred_js_1 = require("../../../utils/Deferred.js");
const LogManager_js_1 = require("../log/LogManager.js");

@@ -14,3 +14,3 @@ const NetworkManager_js_1 = require("../network/NetworkManager.js");

#networkStorage;
#targetUnblocked = new deferred_js_1.Deferred();
#targetUnblocked = new Deferred_js_1.Deferred();
static create(targetId, cdpClient, cdpSessionId, realmStorage, eventManager, preloadScriptStorage, networkStorage) {

@@ -17,0 +17,0 @@ const cdpTarget = new CdpTarget(targetId, cdpClient, cdpSessionId, eventManager, preloadScriptStorage, networkStorage);

@@ -22,8 +22,9 @@ "use strict";

const DefaultMap_js_1 = require("../../../utils/DefaultMap.js");
const buffer_js_1 = require("../../../utils/buffer.js");
const idWrapper_js_1 = require("../../../utils/idWrapper.js");
const Buffer_js_1 = require("../../../utils/Buffer.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();
#idWrapper = new IdWrapper_js_1.IdWrapper();
#contextId;

@@ -97,3 +98,3 @@ #event;

for (const name of eventNames) {
checkEventName(name);
(0, events_js_1.assertSupportedEvent)(name);
}

@@ -120,3 +121,3 @@ // First check if all the contexts are known.

for (const name of eventNames) {
checkEventName(name);
(0, events_js_1.assertSupportedEvent)(name);
}

@@ -135,3 +136,3 @@ this.#subscriptionManager.unsubscribeAll(eventNames, contextIds, channel);

if (!this.#eventBuffers.has(bufferMapKey)) {
this.#eventBuffers.set(bufferMapKey, new buffer_js_1.Buffer(eventBufferLength.get(eventName)));
this.#eventBuffers.set(bufferMapKey, new Buffer_js_1.Buffer(eventBufferLength.get(eventName)));
}

@@ -179,18 +180,2 @@ this.#eventBuffers.get(bufferMapKey).add(eventWrapper);

exports.EventManager = EventManager;
const EVENT_NAMES = new Set([
// keep-sorted start
...Object.values(protocol_js_1.ChromiumBidi.BiDiModule),
...Object.values(protocol_js_1.ChromiumBidi.BrowsingContext.EventNames),
...Object.values(protocol_js_1.ChromiumBidi.Log.EventNames),
...Object.values(protocol_js_1.ChromiumBidi.Network.EventNames),
...Object.values(protocol_js_1.ChromiumBidi.Script.EventNames),
// keep-sorted end
]);
function checkEventName(name) {
if (!EVENT_NAMES.has(name) &&
!name.startsWith('cdp.') &&
name !== 'cdp') {
throw new protocol_js_1.InvalidArgumentException(`Unknown event: ${name}`);
}
}
//# sourceMappingURL=EventManager.js.map

@@ -21,2 +21,3 @@ "use strict";

const protocol_js_1 = require("../../../protocol/protocol.js");
const events_js_1 = require("./events.js");
/**

@@ -93,3 +94,22 @@ * Returns the cartesian product of the given arrays.

const priorities = relevantContexts
.map((c) => contextToEventMap.get(c)?.get(eventMethod))
.map((context) => {
// Get the priority for exact event name
const priority = contextToEventMap.get(context)?.get(eventMethod);
// For CDP we can't provide specific event name when subscribing
// to the module directly.
// Because of that we need to see event `cdp` exits in the map.
if ((0, events_js_1.isCdpEvent)(eventMethod)) {
const cdpPriority = contextToEventMap
.get(context)
?.get(protocol_js_1.ChromiumBidi.BiDiModule.Cdp);
// If we subscribe to the event directly and `cdp` module as well
// priority will be different we take minimal priority
return priority && cdpPriority
? Math.min(priority, cdpPriority)
: // At this point we know that we have subscribed
// to only one of the two
priority ?? cdpPriority;
}
return priority;
})
.filter((p) => p !== undefined);

@@ -96,0 +116,0 @@ if (priorities.length === 0) {

@@ -22,2 +22,3 @@ "use strict";

const assert_js_1 = require("../../../utils/assert.js");
const InputSource_js_1 = require("./InputSource.js");
const USKeyboardLayout_js_1 = require("./USKeyboardLayout.js");

@@ -157,3 +158,2 @@ const keyUtils_js_1 = require("./keyUtils.js");

case "pen" /* Input.PointerType.Pen */:
source.setClickCount({ x, y, timeStamp: performance.now() });
// TODO: Implement width and height when available.

@@ -167,3 +167,3 @@ return this.#context.cdpTarget.cdpClient.sendCommand('Input.dispatchMouseEvent', {

buttons: source.buttons,
clickCount: source.clickCount,
clickCount: source.setClickCount(button, new InputSource_js_1.PointerSource.ClickContext(x, y, performance.now())),
pointerType,

@@ -218,3 +218,3 @@ tangentialPressure,

buttons: source.buttons,
clickCount: source.clickCount,
clickCount: source.getClickCount(button),
pointerType,

@@ -221,0 +221,0 @@ });

@@ -41,7 +41,2 @@ /**

}
interface ClickContext {
x: number;
y: number;
timeStamp: number;
}
export declare class PointerSource {

@@ -57,4 +52,15 @@ #private;

get buttons(): number;
setClickCount(context: ClickContext): void;
get clickCount(): number;
static ClickContext: {
new (x: number, y: number, time: number): {
count: number;
"__#82212@#x": number;
"__#82212@#y": number;
"__#82212@#time": number;
compare(context: any): boolean;
};
"__#82212@#DOUBLE_CLICK_TIME_MS": number;
"__#82212@#MAX_DOUBLE_CLICK_RADIUS": number;
};
setClickCount(button: number, context: InstanceType<typeof PointerSource.ClickContext>): number;
getClickCount(button: number): number;
}

@@ -66,2 +72,1 @@ export declare class WheelSource {

export type InputSourceFor<Type extends SourceType> = Type extends SourceType.Key ? KeySource : Type extends SourceType.Pointer ? PointerSource : Type extends SourceType.Wheel ? WheelSource : NoneSource;
export {};

@@ -103,27 +103,40 @@ "use strict";

}
// --- Platform-specific state starts here ---
// --- Platform-specific code starts here ---
// Input.dispatchMouseEvent doesn't know the concept of double click, so we
// need to create it like for OSes:
// need to create the logic, similar to how it's done for OSes:
// https://source.chromium.org/chromium/chromium/src/+/refs/heads/main:ui/events/event.cc;l=479
static #DOUBLE_CLICK_TIME_MS = 500;
static #MAX_DOUBLE_CLICK_RADIUS = 2;
#clickCount = 0;
#lastClick;
setClickCount(context) {
if (!this.#lastClick ||
static ClickContext = class ClickContext {
static #DOUBLE_CLICK_TIME_MS = 500;
static #MAX_DOUBLE_CLICK_RADIUS = 2;
count = 0;
#x;
#y;
#time;
constructor(x, y, time) {
this.#x = x;
this.#y = y;
this.#time = time;
}
compare(context) {
return (
// The click needs to be within a certain amount of ms.
context.timeStamp - this.#lastClick.timeStamp >
PointerSource.#DOUBLE_CLICK_TIME_MS ||
// The click needs to be within a square radius.
Math.abs(this.#lastClick.x - context.x) >
PointerSource.#MAX_DOUBLE_CLICK_RADIUS ||
Math.abs(this.#lastClick.y - context.y) >
PointerSource.#MAX_DOUBLE_CLICK_RADIUS) {
this.#clickCount = 0;
context.#time - this.#time > ClickContext.#DOUBLE_CLICK_TIME_MS ||
// The click needs to be within a certain square radius.
Math.abs(context.#x - this.#x) >
ClickContext.#MAX_DOUBLE_CLICK_RADIUS ||
Math.abs(context.#y - this.#y) > ClickContext.#MAX_DOUBLE_CLICK_RADIUS);
}
++this.#clickCount;
this.#lastClick = context;
};
#clickContexts = new Map();
setClickCount(button, context) {
let storedContext = this.#clickContexts.get(button);
if (!storedContext || storedContext.compare(context)) {
storedContext = context;
}
++storedContext.count;
this.#clickContexts.set(button, storedContext);
return storedContext.count;
}
get clickCount() {
return this.#clickCount;
getClickCount(button) {
return this.#clickContexts.get(button)?.count ?? 0;
}

@@ -130,0 +143,0 @@ }

@@ -87,13 +87,3 @@ "use strict";

});
// Try the best to get the exception text.
const textPromise = (async () => {
if (!params.exceptionDetails.exception) {
return params.exceptionDetails.text;
}
if (realm === undefined) {
return JSON.stringify(params.exceptionDetails.exception);
}
return realm.stringifyObject(params.exceptionDetails.exception);
})();
this.#eventManager.registerPromiseEvent(textPromise.then((text) => ({
this.#eventManager.registerPromiseEvent(LogManager.#getExceptionText(params, realm).then((text) => ({
kind: 'success',

@@ -118,4 +108,16 @@ value: {

}
/**
* Try the best to get the exception text.
*/
static async #getExceptionText(params, realm) {
if (!params.exceptionDetails.exception) {
return params.exceptionDetails.text;
}
if (realm === undefined) {
return JSON.stringify(params.exceptionDetails.exception);
}
return realm.stringifyObject(params.exceptionDetails.exception);
}
}
exports.LogManager = LogManager;
//# sourceMappingURL=LogManager.js.map

@@ -32,5 +32,2 @@ "use strict";

}
#forgetNetworkRequest(requestId) {
this.#networkStorage.deleteRequest(requestId);
}
#getOrCreateNetworkRequest(id) {

@@ -55,4 +52,4 @@ const request = this.#networkStorage.getRequest(id);

if (request && request.isRedirecting()) {
request.handleRedirect();
networkManager.#forgetNetworkRequest(params.requestId);
request.handleRedirect(params);
networkManager.#networkStorage.deleteRequest(params.requestId);
networkManager.#networkStorage

@@ -96,2 +93,14 @@ .createRequest(params.requestId, request.redirectCount + 1)

});
cdpTarget.cdpClient.on('Fetch.requestPaused', (params) => {
if (params.networkId) {
networkManager.#networkStorage.addBlockedRequest(params.networkId, {
request: params.requestId,
// TODO: Populate phase.
// TODO: Populate response / ResponseData.
});
networkManager
.#getOrCreateNetworkRequest(params.networkId)
.onRequestPaused(params);
}
});
return networkManager;

@@ -98,0 +107,0 @@ }

@@ -23,3 +23,3 @@ /**

isRedirecting(): boolean;
handleRedirect(): void;
handleRedirect(event: Protocol.Network.RequestWillBeSentEvent): void;
onRequestWillBeSentEvent(event: Protocol.Network.RequestWillBeSentEvent): void;

@@ -31,3 +31,5 @@ onRequestWillBeSentExtraInfoEvent(event: Protocol.Network.RequestWillBeSentExtraInfoEvent): void;

onLoadingFailedEvent(event: Protocol.Network.LoadingFailedEvent): void;
/** Fired whenever a network request interception is hit. */
onRequestPaused(_event: Protocol.Fetch.RequestPausedEvent): void;
dispose(): void;
}

@@ -21,3 +21,3 @@ "use strict";

exports.NetworkRequest = void 0;
const deferred_js_1 = require("../../../utils/deferred.js");
const Deferred_js_1 = require("../../../utils/Deferred.js");
const protocol_js_1 = require("../../../protocol/protocol.js");

@@ -36,2 +36,4 @@ const assert_js_1 = require("../../../utils/assert.js");

requestId;
/** Indicates whether the request is blocked by a network intercept. */
#isBlocked = false;
#servedFromCache = false;

@@ -42,4 +44,4 @@ #redirectCount;

#response = {};
#beforeRequestSentDeferred = new deferred_js_1.Deferred();
#responseCompletedDeferred = new deferred_js_1.Deferred();
#beforeRequestSentDeferred = new Deferred_js_1.Deferred();
#responseCompletedDeferred = new Deferred_js_1.Deferred();
constructor(requestId, eventManager, redirectCount = 0) {

@@ -59,8 +61,9 @@ this.requestId = requestId;

}
handleRedirect() {
handleRedirect(event) {
this.#queueResponseCompletedEvent();
this.#response.info = {
hasExtraInfo: event.redirectHasExtraInfo,
response: event.redirectResponse,
};
this.#emitEventsIfReady(true);
this.#responseCompletedDeferred.resolve({
kind: 'error',
error: new Error('Redirects produce no response'),
});
}

@@ -135,2 +138,6 @@ #emitEventsIfReady(wasRedirected = false) {

}
/** Fired whenever a network request interception is hit. */
onRequestPaused(_event) {
this.#isBlocked = true;
}
dispose() {

@@ -149,7 +156,5 @@ const result = {

return {
// TODO: implement.
isBlocked: false,
isBlocked: this.#isBlocked,
context: this.#context,
navigation: this.#getNavigationId(),
// TODO: implement.
redirectCount: this.#redirectCount,

@@ -156,0 +161,0 @@ request: this.#getRequestData(),

@@ -63,7 +63,8 @@ /**

static isSpecialScheme(protocol: string): boolean;
get blockedRequestMap(): Map<string, {
request: string;
phase: Network.InterceptPhase;
response: Network.ResponseData;
}>;
addBlockedRequest(requestId: Network.Request, value: {
request: Protocol.Fetch.RequestId;
phase?: Network.InterceptPhase;
response?: Network.ResponseData;
}): void;
removeBlockedRequest(requestId: Network.Request): void;
/** #@see https://w3c.github.io/webdriver-bidi/#get-the-network-intercepts */

@@ -70,0 +71,0 @@ getNetworkIntercepts(event: Exclude<ChromiumBidi.Network.EventNames, ChromiumBidi.Network.EventNames.FetchError>, requestId: Network.Request): Network.Intercept[];

@@ -12,9 +12,9 @@ "use strict";

/**
* Map of request ID to NetworkRequest objects. Needed as long as information
* about requests comes from different events.
* A map from network request ID to Network Request objects.
* Needed as long as information about requests comes from different events.
*/
#requestMap = new Map();
/** A map to define the properties of active network intercepts. */
/** A map from intercept ID to track active network intercepts. */
#interceptMap = new Map();
/** A map to track the requests which are actively being blocked. */
/** A map from network request ID to track actively blocked requests. */
#blockedRequestMap = new Map();

@@ -161,6 +161,8 @@ constructor(eventManager) {

}
// XXX: Replace getters with custom operations, follow suit of Browsing Context Storage.
get blockedRequestMap() {
return this.#blockedRequestMap;
addBlockedRequest(requestId, value) {
this.#blockedRequestMap.set(requestId, value);
}
removeBlockedRequest(requestId) {
this.#blockedRequestMap.delete(requestId);
}
/** #@see https://w3c.github.io/webdriver-bidi/#get-the-network-intercepts */

@@ -167,0 +169,0 @@ getNetworkIntercepts(event, requestId) {

@@ -137,9 +137,4 @@ "use strict";

serialization: "deep" /* Protocol.Runtime.SerializationOptionsSerialization.Deep */,
...(this.#properties.serializationOptions?.maxObjectDepth ===
undefined ||
this.#properties.serializationOptions.maxObjectDepth === null
? {}
: {
maxDepth: this.#properties.serializationOptions.maxObjectDepth,
}),
maxDepth: this.#properties.serializationOptions?.maxObjectDepth ??
undefined,
},

@@ -146,0 +141,0 @@ });

@@ -21,3 +21,3 @@ /**

import type { EventManager } from '../events/EventManager.js';
import type { ICdpClient } from '../../../cdp/cdpClient.js';
import type { ICdpClient } from '../../../cdp/CdpClient.js';
import { type LoggerFn } from '../../../utils/log.js';

@@ -24,0 +24,0 @@ import type { RealmStorage } from './RealmStorage.js';

@@ -30,16 +30,2 @@ "use strict";

const debugRecv = (0, debug_1.default)('bidi:server:RECV ◂');
function getHttpRequestPayload(request) {
return new Promise((resolve, reject) => {
let data = '';
request.on('data', (chunk) => {
data += chunk;
});
request.on('end', () => {
resolve(data);
});
request.on('error', (error) => {
reject(error);
});
});
}
class BidiServerRunner {

@@ -86,3 +72,3 @@ /**

else if (request.url.startsWith('/session')) {
debugInternal(`Unknown session command ${request.method ?? 'UNKNOWN METHOD'} request for ${request.url} with payload ${await getHttpRequestPayload(request)}. 200 returned.`);
debugInternal(`Unknown session command ${request.method ?? 'UNKNOWN METHOD'} request for ${request.url} with payload ${await BidiServerRunner.#getHttpRequestPayload(request)}. 200 returned.`);
response.writeHead(200, {

@@ -97,3 +83,3 @@ 'Content-Type': 'application/json;charset=utf-8',

else {
debugInternal(`Unknown ${JSON.stringify(request.method)} request for ${JSON.stringify(request.url)} with payload ${JSON.stringify(await getHttpRequestPayload(request))}. 404 returned.`);
debugInternal(`Unknown ${JSON.stringify(request.method)} request for ${JSON.stringify(request.url)} with payload ${JSON.stringify(await BidiServerRunner.#getHttpRequestPayload(request))}. 404 returned.`);
response.writeHead(404);

@@ -167,2 +153,16 @@ }

}
static #getHttpRequestPayload(request) {
return new Promise((resolve, reject) => {
let data = '';
request.on('data', (chunk) => {
data += chunk;
});
request.on('end', () => {
resolve(data);
});
request.on('error', (error) => {
reject(error);
});
});
}
}

@@ -169,0 +169,0 @@ exports.BidiServerRunner = BidiServerRunner;

@@ -25,4 +25,4 @@ "use strict";

const debug_1 = __importDefault(require("debug"));
const cdpConnection_js_1 = require("../cdp/cdpConnection.js");
const websocketTransport_js_1 = require("../utils/websocketTransport.js");
const CdpConnection_js_1 = require("../cdp/CdpConnection.js");
const WebsocketTransport_js_1 = require("../utils/WebsocketTransport.js");
const debugInternal = (0, debug_1.default)('bidi:mapper:internal');

@@ -81,4 +81,4 @@ const debugInfo = (0, debug_1.default)('bidi:mapper:info');

debugInternal('Session established.');
const transport = new websocketTransport_js_1.WebSocketTransport(ws);
const connection = new cdpConnection_js_1.CdpConnection(transport);
const transport = new WebsocketTransport_js_1.WebSocketTransport(ws);
const connection = new CdpConnection_js_1.CdpConnection(transport);
resolve(connection);

@@ -85,0 +85,0 @@ });

@@ -22,5 +22,6 @@ "use strict";

const bidiMapper_js_1 = require("../bidiMapper/bidiMapper.js");
const cdpConnection_js_1 = require("../cdp/cdpConnection.js");
const CdpConnection_js_1 = require("../cdp/CdpConnection.js");
const log_js_1 = require("../utils/log.js");
const BidiParserImpl_1 = require("./BidiParserImpl");
const BidiParser_js_1 = require("./BidiParser.js");
const Transport_js_1 = require("./Transport.js");
const mapperTabPage_js_1 = require("./mapperTabPage.js");

@@ -33,3 +34,8 @@ // Initiate `setSelfTargetId` as soon as possible to prevent race condition.

const selfTargetId = await waitSelfTargetIdPromise;
const bidiServer = await createBidiServer(selfTargetId);
const bidiServer = await bidiMapper_js_1.BidiServer.createAndStart(new Transport_js_1.WindowBidiTransport(),
/**
* A CdpTransport implementation that uses the window.cdp bindings
* injected by Target.exposeDevToolsProtocol.
*/
new CdpConnection_js_1.CdpConnection(new Transport_js_1.WindowCdpTransport(), mapperTabPage_js_1.log), selfTargetId, new BidiParser_js_1.BidiParser(), mapperTabPage_js_1.log);
(0, mapperTabPage_js_1.log)(log_js_1.LogType.debugInfo, 'Launched');

@@ -40,145 +46,2 @@ bidiServer.emitOutgoingMessage(bidiMapper_js_1.OutgoingMessage.createResolved({

})();
function createCdpConnection() {
/**
* A CdpTransport implementation that uses the window.cdp bindings
* injected by Target.exposeDevToolsProtocol.
*/
class WindowCdpTransport {
#onMessage = null;
constructor() {
window.cdp.onmessage = (message) => {
this.#onMessage?.call(null, message);
};
}
setOnMessage(onMessage) {
this.#onMessage = onMessage;
}
sendMessage(message) {
window.cdp.send(message);
}
close() {
this.#onMessage = null;
window.cdp.onmessage = null;
}
}
return new cdpConnection_js_1.CdpConnection(new WindowCdpTransport(), mapperTabPage_js_1.log);
}
function createBidiServer(selfTargetId) {
class WindowBidiTransport {
static LOGGER_PREFIX_RECV = `${log_js_1.LogType.bidi}:RECV ◂`;
static LOGGER_PREFIX_SEND = `${log_js_1.LogType.bidi}:SEND ▸`;
#onMessage = null;
constructor() {
window.onBidiMessage = (message) => {
(0, mapperTabPage_js_1.log)(WindowBidiTransport.LOGGER_PREFIX_RECV, message);
let command;
try {
command = WindowBidiTransport.#parseBidiMessage(message);
}
catch (e) {
// Transport-level error does not provide channel.
this.#respondWithError(message, "invalid argument" /* ErrorCode.InvalidArgument */, e.message, null);
return;
}
this.#onMessage?.call(null, command);
};
}
setOnMessage(onMessage) {
this.#onMessage = onMessage;
}
sendMessage(message) {
const messageStr = JSON.stringify(message);
window.sendBidiResponse(messageStr);
(0, mapperTabPage_js_1.log)(WindowBidiTransport.LOGGER_PREFIX_SEND, message);
}
close() {
this.#onMessage = null;
window.onBidiMessage = null;
}
#respondWithError(plainCommandData, errorCode, errorMessage, channel) {
const errorResponse = WindowBidiTransport.#getErrorResponse(plainCommandData, errorCode, errorMessage);
if (channel) {
// XXX: get rid of any, same code existed in BidiServer.
this.sendMessage({
...errorResponse,
channel,
});
}
else {
this.sendMessage(errorResponse);
}
}
static #getJsonType(value) {
if (value === null) {
return 'null';
}
if (Array.isArray(value)) {
return 'array';
}
return typeof value;
}
static #getErrorResponse(message, errorCode, errorMessage) {
// XXX: this is bizarre per spec. We reparse the payload and
// extract the ID, regardless of what kind of value it was.
let messageId;
try {
const command = JSON.parse(message);
if (WindowBidiTransport.#getJsonType(command) === 'object' &&
'id' in command) {
messageId = command.id;
}
}
catch { }
return {
type: 'error',
id: messageId,
error: errorCode,
message: errorMessage,
// XXX: optional stacktrace field.
};
}
static #parseBidiMessage(messageStr) {
let messageObject;
try {
messageObject = JSON.parse(messageStr);
}
catch {
throw new Error('Cannot parse data as JSON');
}
const parsedType = WindowBidiTransport.#getJsonType(messageObject);
if (parsedType !== 'object') {
throw new Error(`Expected JSON object but got ${parsedType}`);
}
// Extract and validate id, method and params.
const { id, method, params } = messageObject;
const idType = WindowBidiTransport.#getJsonType(id);
if (idType !== 'number' || !Number.isInteger(id) || id < 0) {
// TODO: should uint64_t be the upper limit?
// https://tools.ietf.org/html/rfc7049#section-2.1
throw new Error(`Expected unsigned integer but got ${idType}`);
}
const methodType = WindowBidiTransport.#getJsonType(method);
if (methodType !== 'string') {
throw new Error(`Expected string method but got ${methodType}`);
}
const paramsType = WindowBidiTransport.#getJsonType(params);
if (paramsType !== 'object') {
throw new Error(`Expected object params but got ${paramsType}`);
}
let channel = messageObject.channel;
if (channel !== undefined) {
const channelType = WindowBidiTransport.#getJsonType(channel);
if (channelType !== 'string') {
throw new Error(`Expected string channel but got ${channelType}`);
}
// Empty string channel is considered as no channel provided.
if (channel === '') {
channel = undefined;
}
}
return { id, method, params, channel };
}
}
return bidiMapper_js_1.BidiServer.createAndStart(new WindowBidiTransport(), createCdpConnection(), selfTargetId, new BidiParserImpl_1.BidiParserImpl(), mapperTabPage_js_1.log);
}
// Needed to filter out info related to BiDi target.

@@ -185,0 +48,0 @@ async function waitSelfTargetId() {

@@ -20,2 +20,3 @@ /**

import type { BrowsingContext, JsUint } from './webdriver-bidi.js';
export type EventNames = Event['method'];
export type Message = CommandResponse | Event;

@@ -32,6 +33,2 @@ export type Command = {

export type ResultData = SendCommandResult | GetSessionResult;
export type Event = {
type: 'event';
} & EventData;
export type EventData = EventReceivedEvent;
export type SendCommandCommand = {

@@ -60,7 +57,11 @@ method: 'cdp.sendCommand';

};
export type EventReceivedEvent = {
method: EventNames;
params: EventParameters;
export type Event = {
type: 'event';
} & EventData;
export type EventData = EventDataFor<keyof ProtocolMapping.Events>;
export type EventDataFor<EventName extends keyof ProtocolMapping.Events> = {
method: `cdp.${EventName}`;
params: EventParametersFor<EventName>;
};
export type EventParameters<EventName extends keyof ProtocolMapping.Events = keyof ProtocolMapping.Events> = {
export type EventParametersFor<EventName extends keyof ProtocolMapping.Events> = {
event: EventName;

@@ -70,2 +71,1 @@ params: ProtocolMapping.Events[EventName][0];

};
export type EventNames = 'cdp' | `cdp.${keyof ProtocolMapping.Events}`;
"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 });
//# sourceMappingURL=cdp.js.map

@@ -21,6 +21,10 @@ /**

export declare enum BiDiModule {
Browser = "browser",
BrowsingContext = "browsingContext",
Cdp = "cdp",
Input = "input",
Log = "log",
Network = "network",
Script = "script"
Script = "script",
Session = "session"
}

@@ -68,2 +72,3 @@ export declare namespace Script {

export type Event = WebDriverBidi.Event | Cdp.Event;
export declare const EVENT_NAMES: Set<BiDiModule | BrowsingContext.EventNames | Log.EventNames.LogEntryAdded | Network.EventNames | Script.EventNames>;
export type ResultData = WebDriverBidi.ResultData | Cdp.ResultData;

@@ -70,0 +75,0 @@ export type Message = (WebDriverBidi.Message | Cdp.Message | {

@@ -19,3 +19,3 @@ "use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.Network = exports.BrowsingContext = exports.Log = exports.Script = exports.BiDiModule = void 0;
exports.EVENT_NAMES = exports.Network = exports.BrowsingContext = exports.Log = exports.Script = exports.BiDiModule = void 0;
// keep-sorted end

@@ -25,6 +25,10 @@ var BiDiModule;

// keep-sorted start
BiDiModule["Browser"] = "browser";
BiDiModule["BrowsingContext"] = "browsingContext";
BiDiModule["Cdp"] = "cdp";
BiDiModule["Input"] = "input";
BiDiModule["Log"] = "log";
BiDiModule["Network"] = "network";
BiDiModule["Script"] = "script";
BiDiModule["Session"] = "session";
// keep-sorted end

@@ -82,2 +86,11 @@ })(BiDiModule || (exports.BiDiModule = BiDiModule = {}));

})(Network || (exports.Network = Network = {}));
exports.EVENT_NAMES = new Set([
// keep-sorted start
...Object.values(BiDiModule),
...Object.values(BrowsingContext.EventNames),
...Object.values(Log.EventNames),
...Object.values(Network.EventNames),
...Object.values(Script.EventNames),
// keep-sorted end
]);
//# sourceMappingURL=chromium-bidi.js.map
"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.
*/
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {

@@ -46,2 +30,18 @@ if (k2 === undefined) k2 = k;

exports.ChromiumBidi = exports.Cdp = void 0;
/**
* 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.
*/
exports.Cdp = __importStar(require("./cdp.js"));

@@ -48,0 +48,0 @@ exports.ChromiumBidi = __importStar(require("./chromium-bidi.js"));

{
"name": "chromium-bidi",
"version": "0.4.27",
"version": "0.4.28",
"description": "An implementation of the WebDriver BiDi protocol for Chromium implemented as a JavaScript layer translating between BiDi and CDP, running inside a Chrome tab.",

@@ -204,3 +204,3 @@ "scripts": {

"debug": "4.3.4",
"devtools-protocol": "0.0.1168520",
"devtools-protocol": "0.0.1195796",
"eslint": "8.46.0",

@@ -207,0 +207,0 @@ "eslint-config-prettier": "8.10.0",

@@ -405,15 +405,26 @@ # WebDriver BiDi for Chromium [![chromium-bidi on npm](https://img.shields.io/npm/v/chromium-bidi)](https://www.npmjs.com/package/chromium-bidi)

> Assuming that you already have a Chromium set-up locally, and knowledge on how to submit changes to the repo.
> Else submit an issue for a project maintainer to do.
This section assumes you already have a Chromium set-up locally,
and knowledge on [how to submit changes to the repo](https://chromium.googlesource.com/chromium/src/+/refs/heads/main/docs/contributing.md).
Otherwise submit an issue for a project maintainer.
1. Create a new branch.
2. Navigate to `third_party/bidimapper/`.
3. Then run the following commands:
1. Create a new branch in chromium `src/`.
2. Update the mapper version:
```bash
./pull.sh
./build.sh
```shell
third_party/bidimapper/pull.sh
third_party/bidimapper/build.sh
```
4. Submit a CL with bug `chromedriver:4226`
5. Add appropriate reviewers or comment the CL link on the PR
3. Submit a CL with bug `chromedriver:4226`.
4. [Regenerate WPT expectations metadata](https://chromium.googlesource.com/chromium/src/+/HEAD/docs/testing/web_platform_tests_wptrunner.md#updating-expectations):
4.1. Trigger a build and test run:
```shell
third_party/blink/tools/blink_tool.py update-metadata --build="linux-blink-rel"
```
4.2. Once the test completes on the builder, rerun that command to update the metadata.
Commit the changes (if any), and upload the new patch to the CL.
5. Add appropriate reviewers or comment the CL link on the PR.

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc