Skip to content

[js] Add Javascript/Typescript CDDL code generator for WebDriver BiDi#17574

Open
pujagani wants to merge 1 commit into
SeleniumHQ:trunkfrom
pujagani:js-bidi-codegen
Open

[js] Add Javascript/Typescript CDDL code generator for WebDriver BiDi#17574
pujagani wants to merge 1 commit into
SeleniumHQ:trunkfrom
pujagani:js-bidi-codegen

Conversation

@pujagani
Copy link
Copy Markdown
Contributor

🔗 Related Issues

Part of the CDDL WebDriver BiDi API generator. Implemented as defined in the spec https://gist.github.com/AutomatedTester/148437f846a3759f7678c7ff6debb210

💥 What does this PR do?

Adds a code generator (generate_bidi.mjs) that reads the merged WebDriver BiDi CDDL
specification and emits one typed TypeScript module per domain into bidi/generated/.
The generator is wired into the Bazel build so the output is compiled and included in
the npm package automatically.

Each generated domain class (Browser, BrowsingContext, Input, Log, Network,
Script, Storage, etc.) exposes typed command methods and event subscription helpers
via a static async create(driver) factory. An enhancements manifest
(private/bidi_enhancements_manifest.json) allows hand-written additions (deprecated
compatibility shims, convenience wrappers, and method overloads) to be injected at
build time without modifying generated files.

🔧 Implementation Notes

Why a two-pass generator?
cddl2ts only produces type declarations; it has no concept of the BiDi command/event
distinction. A second pass walks the raw CDDL AST to identify commands (groups with a
method literal and params) and events (same structure plus type: "event") and
emits the implementation class from that.

Why throw on error responses?
bidi/index.js always resolves — it never rejects on BiDi error responses. Both void
and non-void generated methods inspect the response payload and throw if
response.type === 'error', so unhandled server errors surface as test failures rather
than being silently swallowed.

Why an enhancements manifest?
The existing hand-crafted modules use a positional-argument / builder pattern
(getBrowserInstance(driver), AddInterceptParameters). The generated API uses typed
params objects. Replacing the old exports directly would be a breaking change. The
manifest lets deprecated compatibility wrappers live alongside generated code until a
major version bump removes them.

🤖 AI assistance

  • AI assisted (complete below)
    • Tool(s): Claude (Anthropic)
    • What was generated: generator implementation, Bazel macro, enhancements manifest,
      integration tests under test/bidi/generated/
    • I reviewed all AI output and can explain the change

💡 Additional Considerations

Breaking change: The generated API shape (Domain.create(driver), typed params
objects) differs from the existing hand-crafted modules (positional args, builder
classes). Deprecated compatibility shims are in place for the most-used modules but a
full audit is needed before the old modules can be removed. See the Phase 7 audit in
the PR description or tracking issue for the complete list.

Follow-on work required:

  • Add missing convenience wrappers to the enhancements manifest:
    captureBoxScreenshot, captureElementScreenshot, locateNode, locateElement,
    locateElements (BrowsingContext); filtered log level variants (Log).
  • Decide if deprecation is required for browsingContextInspector.js and networkInspector.js — superseded by
    event methods on the generated BrowsingContext and Network classes
  • Decide fate of the builder/DTO classes (AddInterceptParameters,
    ContinueRequestParameters, CookieFilter, etc.).

🔄 Types of changes

  • New feature (non-breaking change which adds functionality and tests)

@selenium-ci selenium-ci added C-py Python Bindings C-nodejs JavaScript Bindings B-build Includes scripting, bazel and CI integrations B-devtools Includes everything BiDi or Chrome DevTools related labels May 26, 2026
@qodo-code-review
Copy link
Copy Markdown
Contributor

Review Summary by Qodo

Add JavaScript/TypeScript CDDL code generator for WebDriver BiDi with comprehensive test coverage

✨ Enhancement 🧪 Tests

Grey Divider

Walkthroughs

Description
• Implements a comprehensive WebDriver BiDi code generator (generate_bidi.mjs) that transforms
  CDDL specifications into typed TypeScript domain classes
• Two-pass generation approach: Pass 1 uses cddl2ts for type declarations with post-processing;
  Pass 2 walks raw CDDL AST to extract commands and events for implementation
• Generates per-domain modules (Browser, BrowsingContext, Input, Log, Network, Script,
  Storage, Emulation) with typed command methods and event subscription helpers
• Introduces enhancements manifest (bidi_enhancements_manifest.json) for injecting hand-written
  additions (deprecated compatibility shims, convenience wrappers) without modifying generated code
• Integrates code generation into Bazel build pipeline via generate_bidi_library() macro that
  orchestrates CDDL merging, TypeScript generation, and compilation
• Comprehensive integration test suite covering all generated BiDi domains with Chrome and Firefox
  browser validation
• Adds cddl@^0.20.1 and cddl2ts@^0.9.1 dev dependencies and updates pnpm workspace configuration
  for dependency resolution
• Expands visibility of CDDL merge tool to JavaScript build pipeline
Diagram
flowchart LR
  CDDL["CDDL Specifications<br/>WebDriver BiDi, Permissions,<br/>Prefetch, UA Client Hints"]
  Merge["Merge CDDL<br/>merge_cddl"]
  Gen["Two-Pass Generator<br/>generate_bidi.mjs"]
  Types["Type Declarations<br/>cddl2ts Pass 1"]
  Impl["Implementation Classes<br/>Pass 2 AST Walk"]
  Manifest["Enhancements Manifest<br/>bidi_enhancements_manifest.json"]
  Output["Generated Domain Modules<br/>Browser, BrowsingContext,<br/>Input, Log, Network,<br/>Script, Storage, Emulation"]
  Tests["Integration Tests<br/>All domains + browsers"]
  Package["npm Package"]
  
  CDDL --> Merge
  Merge --> Gen
  Gen --> Types
  Gen --> Impl
  Manifest --> Gen
  Types --> Output
  Impl --> Output
  Output --> Tests
  Output --> Package
  Tests -.-> Package

Loading

Grey Divider

File Changes

1. javascript/selenium-webdriver/test/bidi/generated/browsing_context_test.js 🧪 Tests +324/-0

Integration tests for generated BrowsingContext BiDi domain

• Comprehensive integration tests for the generated BrowsingContext domain class
• Tests cover context creation/closure, navigation, viewport/screenshot, user prompts, and event
 listeners
• Validates typed command methods (create(), navigate(), reload()) and event subscriptions
 (onContextCreated(), onNavigationCommitted())
• Tests both Chrome and Firefox browsers

javascript/selenium-webdriver/test/bidi/generated/browsing_context_test.js


2. javascript/selenium-webdriver/test/bidi/generated/script_test.js 🧪 Tests +314/-0

Integration tests for generated Script BiDi domain

• Integration tests for the generated Script domain class covering script evaluation and execution
• Tests evaluate(), callFunction(), getRealms(), and preload script management
• Validates realm creation/destruction events and exception handling
• Tests both Chrome and Firefox browsers

javascript/selenium-webdriver/test/bidi/generated/script_test.js


3. javascript/selenium-webdriver/test/bidi/generated/emulation_test.js 🧪 Tests +297/-0

Integration tests for generated Emulation BiDi domain

• Integration tests for the generated Emulation domain class
• Tests user agent override, timezone/locale override, network conditions, geolocation, screen
 orientation, and scripting/touch emulation
• Validates context-specific and global emulation settings
• Tests both Chrome and Firefox browsers with browser-specific test skipping

javascript/selenium-webdriver/test/bidi/generated/emulation_test.js


View more (15)
4. javascript/selenium-webdriver/test/bidi/generated/network_test.js 🧪 Tests +268/-0

Integration tests for generated Network BiDi domain

• Integration tests for the generated Network domain class
• Tests request/response events, interception, cache behavior, and extra headers
• Validates onBeforeRequestSent(), onResponseCompleted(), addIntercept(), and
 continueRequest() methods
• Tests both Chrome and Firefox browsers

javascript/selenium-webdriver/test/bidi/generated/network_test.js


5. javascript/selenium-webdriver/test/bidi/generated/storage_test.js 🧪 Tests +229/-0

Integration tests for generated Storage BiDi domain

• Integration tests for the generated Storage domain class
• Tests cookie management: setCookie(), getCookies(), deleteCookies() with various filters
• Validates partition key handling and domain/context-specific cookie operations
• Tests both Chrome and Firefox browsers

javascript/selenium-webdriver/test/bidi/generated/storage_test.js


6. javascript/selenium-webdriver/test/bidi/generated/input_test.js 🧪 Tests +203/-0

Integration tests for generated Input BiDi domain

• Integration tests for the generated Input domain class
• Tests keyboard and pointer actions via performActions(), and releaseActions()
• Validates file dialog event handling with browser-specific test skipping
• Tests both Chrome and Firefox browsers

javascript/selenium-webdriver/test/bidi/generated/input_test.js


7. javascript/selenium-webdriver/test/bidi/generated/log_test.js 🧪 Tests +193/-0

Integration tests for generated Log BiDi domain

• Integration tests for the generated Log domain class
• Tests console entry listening, JavaScript exception capture, and log entry filtering
• Validates onConsoleEntry(), onJavascriptException(), and onEntryAdded() event methods
• Tests both Chrome and Firefox browsers

javascript/selenium-webdriver/test/bidi/generated/log_test.js


8. javascript/selenium-webdriver/test/bidi/generated/browser_test.js 🧪 Tests +121/-0

Integration tests for generated Browser BiDi domain

• Integration tests for the generated Browser domain class
• Tests user context creation/removal and client window information retrieval
• Validates createUserContext(), getUserContexts(), removeUserContext(), and
 getClientWindows() methods
• Tests both Chrome and Firefox browsers

javascript/selenium-webdriver/test/bidi/generated/browser_test.js


9. javascript/selenium-webdriver/private/generate_bidi.bzl ⚙️ Configuration changes +154/-0

Bazel build rules for WebDriver BiDi code generation

• Bazel macro generate_bidi_library() that orchestrates CDDL merging, TypeScript generation, and
 compilation
• Implements three-step build process: merge CDDL files, run generate_bidi.mjs generator, compile
 TypeScript to JavaScript
• Custom _compile_bidi_ts rule handles TypeScript compilation with proper output directory
 handling
• Supports enhancements manifest for per-domain customizations

javascript/selenium-webdriver/private/generate_bidi.bzl


10. pnpm-lock.yaml Dependencies +122/-15

Lock file updates for CDDL code generation tools

• Adds cddl@0.20.1 and cddl2ts@0.9.1 as dev dependencies for CDDL parsing and TypeScript
 generation
• Updates package extension checksums and adds new transitive dependencies (ast-types, recast,
 yargs, etc.)
• Removes obsolete ts-declaration-location dependency

pnpm-lock.yaml


11. javascript/selenium-webdriver/private/bidi_enhancements_manifest.json ⚙️ Configuration changes +123/-0

Enhancements manifest for generated BiDi domains

• JSON manifest defining per-domain enhancements for generated BiDi modules
• Specifies deprecated compatibility wrappers (e.g., getBrowserInstance(), getNetworkInstance())
• Defines convenience method overloads for Network, Script, BrowsingContext, and Input
 domains
• Allows hand-written additions without modifying generated code

javascript/selenium-webdriver/private/bidi_enhancements_manifest.json


12. javascript/selenium-webdriver/BUILD.bazel ⚙️ Configuration changes +30/-1

Bazel build integration for BiDi code generation

• Adds js_binary import for the generator script
• Defines generate_bidi_script target wrapping generate_bidi.mjs with CDDL and cddl2ts
 dependencies
• Calls generate_bidi_library() macro to generate BiDi modules from merged CDDL specs (WebDriver
 BiDi, Permissions, Prefetch, UA Client Hints, Web Bluetooth)
• Includes generated BiDi source in the npm package

javascript/selenium-webdriver/BUILD.bazel


13. javascript/selenium-webdriver/package.json Dependencies +2/-0

Dev dependencies for CDDL code generation

• Adds cddl@^0.20.1 and cddl2ts@^0.9.1 as dev dependencies for CDDL parsing and TypeScript code
 generation

javascript/selenium-webdriver/package.json


14. pnpm-workspace.yaml ⚙️ Configuration changes +20/-0

pnpm workspace configuration for dependency resolution

• Adds onlyBuiltDependencies configuration
• Defines packageExtensions for transitive dependency resolution (google-closure-deps,
 minimatch, brace-expansion, recast)
• Ensures forward compatibility with pnpm v11+ by using workspace-level configuration

pnpm-workspace.yaml


15. javascript/selenium-webdriver/private/BUILD.bazel ⚙️ Configuration changes +11/-0

Bazel build file for private BiDi enhancements

• New Bazel build file for the private directory
• Copies bidi_enhancements_manifest.json to bin directory for build-time access
• Exports the manifest file for use by the code generator

javascript/selenium-webdriver/private/BUILD.bazel


16. py/private/BUILD.bazel ⚙️ Configuration changes +4/-1

Visibility update for CDDL merge tool

• Expands visibility of merge_cddl Python binary to include
 //javascript/selenium-webdriver:__pkg__
• Allows the JavaScript BiDi code generation pipeline to use the CDDL merging tool

py/private/BUILD.bazel


17. javascript/selenium-webdriver/generate_bidi.mjs ✨ Enhancement +929/-0

WebDriver BiDi TypeScript code generator from CDDL specification

• Implements a two-pass code generator that transforms WebDriver BiDi CDDL specifications into typed
 TypeScript domain classes
• Pass 1 uses cddl2ts to generate type declarations, then post-processes to deduplicate exports
 and replace any with unknown
• Pass 2 walks the raw CDDL AST to extract commands (groups with method literal and params) and
 events, generating implementation classes with typed methods
• Generates per-domain files with cross-domain import resolution, error handling for BiDi responses,
 and support for enhancements manifest for compatibility shims

javascript/selenium-webdriver/generate_bidi.mjs


18. package.json Additional files +0/-20

...

package.json


Grey Divider

Qodo Logo

@qodo-code-review
Copy link
Copy Markdown
Contributor

qodo-code-review Bot commented May 26, 2026

Code Review by Qodo

🐞 Bugs (2) 📘 Rule violations (3)

Grey Divider


Action required

1. username! in continueWithAuth 📘 Rule violation ≡ Correctness
Description
The injected deprecated overload for Network.continueWithAuth uses non-null assertions
(username!, password!) on optional parameters, so invalid calls can produce undefined
credentials or unclear runtime failures. Protocol-derived/user inputs should be validated and
rejected with deterministic, actionable errors.
Code

javascript/selenium-webdriver/private/bidi_enhancements_manifest.json[51]

Evidence
PR Compliance ID 11 requires early validation of external/protocol/user-derived inputs and
discourages null-forgiving operators like !. The new injected method body constructs credentials
using username! and password! without checking they are present.

javascript/selenium-webdriver/private/bidi_enhancements_manifest.json[51-51]
Best Practice: Learned patterns

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The deprecated overload implementation for `Network.continueWithAuth` uses `username!`/`password!` non-null assertions even though the implementation signature allows them to be omitted, which can lead to undefined credentials being sent or confusing runtime errors.

## Issue Context
This code is injected from the enhancements manifest and becomes part of the published/generated JS/TS API surface.

## Fix Focus Areas
- javascript/selenium-webdriver/private/bidi_enhancements_manifest.json[51-51]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


2. Empty context in back/forward 🐞 Bug ≡ Correctness
Description
The BrowsingContext enhancement methods back() and forward() always call traverseHistory with
context: '' (empty string), so these convenience methods will consistently fail with an invalid
browsing context id.
Code

javascript/selenium-webdriver/private/bidi_enhancements_manifest.json[R12-13]

Evidence
The manifest hard-codes an empty string for context, while the generated API (and its tests) use a
real contextId for traverseHistory, demonstrating the required value cannot be empty.

javascript/selenium-webdriver/private/bidi_enhancements_manifest.json[8-16]
javascript/selenium-webdriver/test/bidi/generated/browsing_context_test.js[98-113]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

### Issue description
`back()`/`forward()` in the enhancements manifest hard-code `context: ''` and therefore cannot work against any BiDi server.

### Issue Context
The generated API is params-object based; these helpers must either accept a context id or be removed until a proper abstraction exists.

### Fix Focus Areas
- javascript/selenium-webdriver/private/bidi_enhancements_manifest.json[8-16]

### Suggested fix
- Change the shim signatures to accept a context id:
 - `async back(context: BrowsingContextBrowsingContext): Promise<void>`
 - `async forward(context: BrowsingContextBrowsingContext): Promise<void>`
- Delegate to `traverseHistory({ context, delta: ±1 })` (no empty string).

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


3. continueWithAuth ignores errors 🐞 Bug ≡ Correctness
Description
The Network enhancement overrides continueWithAuth() and calls this.bidi.send() directly without
checking for BiDi error responses, so server-side errors are silently ignored instead of thrown like
other generated commands.
Code

javascript/selenium-webdriver/private/bidi_enhancements_manifest.json[R49-51]

Evidence
The enhancements manifest’s override sends the command but does not inspect the returned payload for
error responses. The generator explicitly emits an error-check for all commands, and the underlying
transport resolves with raw payloads, so skipping the check makes errors silent.

javascript/selenium-webdriver/private/bidi_enhancements_manifest.json[45-57]
javascript/selenium-webdriver/generate_bidi.mjs[860-888]
javascript/selenium-webdriver/bidi/index.js[177-208]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

### Issue description
The `continueWithAuth` enhancement override bypasses the generator’s standard `response.type === 'error'` check. Since `bidi.send()` resolves with the raw payload, this makes failures silent.

### Issue Context
`generate_bidi.mjs` intentionally makes generated commands throw on `response['type'] === 'error'`. Overriding a command should preserve this behavior.

### Fix Focus Areas
- javascript/selenium-webdriver/private/bidi_enhancements_manifest.json[45-57]
- javascript/selenium-webdriver/generate_bidi.mjs[860-891]
- javascript/selenium-webdriver/bidi/index.js[177-208]

### Suggested fix
- In the override, capture the response from `this.bidi.send(...)` and apply the same error check pattern as generated methods.
 - If `response.type === 'error'`, throw an `Error` with the server-provided details.
- Alternatively, avoid overriding the generated `continueWithAuth(params)` method:
 - Keep the generated method intact.
 - Add a separate deprecated wrapper name for the legacy positional signature that calls the generated method with a constructed params object.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools



Remediation recommended

4. ws.on('message') listener leaks 📘 Rule violation ☼ Reliability
Description
Generated on<Event>() helpers add a new WebSocket message listener every time they’re called and
provide no unsubscribe/cleanup mechanism, leading to leaked listeners and duplicate callbacks over
time. The listener also blindly JSON.parses incoming frames without guarding or validation,
risking MaxListenersExceededWarning and unhandled exceptions/crashes on malformed or non-JSON data.
Code

javascript/selenium-webdriver/generate_bidi.mjs[R902-918]

Evidence
PR Compliance ID 10 requires cleanup/rollback for async workflows that register state/resources, but
the new generateEventMethod emits code that registers a persistent WebSocket message listener
without any disposal path, so repeated on<Event>() calls accumulate listeners. PR Compliance ID 11
requires early validation of protocol-derived inputs and deterministic failures, yet the generated
handler trusts arbitrary WebSocket payloads and calls JSON.parse without try/catch or shape
checks, allowing malformed frames to throw asynchronously. The existing BiDi transport
(bidi/index.js) is cited as already documenting the MaxListenersExceededWarning risk and using a
single shared dispatcher with guarded JSON parsing, indicating the generated approach reintroduces
known failure modes.

javascript/selenium-webdriver/generate_bidi.mjs[902-918]
javascript/selenium-webdriver/generate_bidi.mjs[897-918]
javascript/selenium-webdriver/bidi/index.js[58-81]
javascript/selenium-webdriver/generate_bidi.mjs[909-916]
Best Practice: Learned patterns

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The generated `on…` event methods install a new `ws.on('message', ...)` listener on every call and never remove it, which can leak listeners, multiply callbacks, and trigger MaxListeners warnings over time. The handler also performs an unguarded `JSON.parse` on protocol-derived WebSocket frames (without try/catch or validation), which can throw on malformed/non-JSON payloads and crash or produce unclear asynchronous failures.

## Issue Context
This event-handling code is emitted into the generated BiDi domain classes and may be invoked repeatedly by consumers across many domains and events. The existing BiDi transport implementation in `bidi/index.js` already explains why adding many message listeners is problematic and uses a single shared dispatcher with guarded JSON parsing; the generator should align with that approach. Protocol/WebSocket payloads are external inputs and should be validated early to produce deterministic, actionable failures.

## Fix Focus Areas
- javascript/selenium-webdriver/generate_bidi.mjs[897-920]
- javascript/selenium-webdriver/bidi/index.js[58-81]
- javascript/selenium-webdriver/generate_bidi.mjs[909-916]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


5. Genrule uses unquoted args 📘 Rule violation ☼ Reliability
Description
The new genrule command constructs a shell invocation with $@ and $(SRCS) unquoted, which is
unsafe if paths contain spaces/special characters and can cause non-deterministic CI/tooling
behavior. Build/tooling scripts should use safe argument handling.
Code

javascript/selenium-webdriver/private/generate_bidi.bzl[R113-119]

Evidence
PR Compliance ID 13 requires safe argument handling in build/CI/scripts/tooling. The added genrule
uses a raw cmd string with unquoted $@/$(SRCS), which is not robust to special characters in
paths.

javascript/selenium-webdriver/private/generate_bidi.bzl[113-119]
Best Practice: Learned patterns

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The `native.genrule` command string passes `$@` and `$(SRCS)` without robust quoting/argument handling, which is a common source of brittle CI behavior.

## Issue Context
Compliance requires build/tooling glue to use safe argument handling; consider replacing the genrule with a small Starlark rule using `ctx.actions.run` so arguments are passed as an argv list.

## Fix Focus Areas
- javascript/selenium-webdriver/private/generate_bidi.bzl[113-119]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


Grey Divider

Qodo Logo

"extraMethods": {
"cancelAuth": " async cancelAuth(requestId: NetworkRequest): Promise<void> {\n await this.continueWithAuth({ request: requestId, action: 'cancel' } as NetworkContinueWithAuthParameters)\n }",
"continueWithAuthNoCredentials": " async continueWithAuthNoCredentials(requestId: NetworkRequest): Promise<void> {\n await this.continueWithAuth({ request: requestId, action: 'default' } as NetworkContinueWithAuthParameters)\n }",
"continueWithAuth": " async continueWithAuth(params: NetworkContinueWithAuthParameters): Promise<void>\n /** @deprecated Pass a NetworkContinueWithAuthParameters object instead — will be removed in a future major version. */\n async continueWithAuth(requestId: NetworkRequest, username: string, password: string): Promise<void>\n async continueWithAuth(\n paramsOrRequestId: NetworkContinueWithAuthParameters | NetworkRequest,\n username?: string,\n password?: string,\n ): Promise<void> {\n const params: NetworkContinueWithAuthParameters =\n typeof paramsOrRequestId === 'string'\n ? ({\n request: paramsOrRequestId,\n action: 'provideCredentials',\n credentials: { type: 'password', username: username!, password: password! },\n } as NetworkContinueWithAuthParameters)\n : (paramsOrRequestId as NetworkContinueWithAuthParameters)\n await this.bidi.send({\n method: 'network.continueWithAuth',\n params: params as unknown as Record<string, unknown>,\n })\n }",
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Action required

1. username! in continuewithauth 📘 Rule violation ≡ Correctness

The injected deprecated overload for Network.continueWithAuth uses non-null assertions
(username!, password!) on optional parameters, so invalid calls can produce undefined
credentials or unclear runtime failures. Protocol-derived/user inputs should be validated and
rejected with deterministic, actionable errors.
Agent Prompt
## Issue description
The deprecated overload implementation for `Network.continueWithAuth` uses `username!`/`password!` non-null assertions even though the implementation signature allows them to be omitted, which can lead to undefined credentials being sent or confusing runtime errors.

## Issue Context
This code is injected from the enhancements manifest and becomes part of the published/generated JS/TS API surface.

## Fix Focus Areas
- javascript/selenium-webdriver/private/bidi_enhancements_manifest.json[51-51]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools

Comment on lines +12 to +13
"back": " async back(): Promise<void> {\n await this.traverseHistory({ context: '', delta: -1 } as BrowsingContextTraverseHistoryParameters)\n }",
"forward": " async forward(): Promise<void> {\n await this.traverseHistory({ context: '', delta: 1 } as BrowsingContextTraverseHistoryParameters)\n }",
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Action required

2. Empty context in back/forward 🐞 Bug ≡ Correctness

The BrowsingContext enhancement methods back() and forward() always call traverseHistory with
context: '' (empty string), so these convenience methods will consistently fail with an invalid
browsing context id.
Agent Prompt
### Issue description
`back()`/`forward()` in the enhancements manifest hard-code `context: ''` and therefore cannot work against any BiDi server.

### Issue Context
The generated API is params-object based; these helpers must either accept a context id or be removed until a proper abstraction exists.

### Fix Focus Areas
- javascript/selenium-webdriver/private/bidi_enhancements_manifest.json[8-16]

### Suggested fix
- Change the shim signatures to accept a context id:
  - `async back(context: BrowsingContextBrowsingContext): Promise<void>`
  - `async forward(context: BrowsingContextBrowsingContext): Promise<void>`
- Delegate to `traverseHistory({ context, delta: ±1 })` (no empty string).

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools

Comment on lines +49 to +51
"cancelAuth": " async cancelAuth(requestId: NetworkRequest): Promise<void> {\n await this.continueWithAuth({ request: requestId, action: 'cancel' } as NetworkContinueWithAuthParameters)\n }",
"continueWithAuthNoCredentials": " async continueWithAuthNoCredentials(requestId: NetworkRequest): Promise<void> {\n await this.continueWithAuth({ request: requestId, action: 'default' } as NetworkContinueWithAuthParameters)\n }",
"continueWithAuth": " async continueWithAuth(params: NetworkContinueWithAuthParameters): Promise<void>\n /** @deprecated Pass a NetworkContinueWithAuthParameters object instead — will be removed in a future major version. */\n async continueWithAuth(requestId: NetworkRequest, username: string, password: string): Promise<void>\n async continueWithAuth(\n paramsOrRequestId: NetworkContinueWithAuthParameters | NetworkRequest,\n username?: string,\n password?: string,\n ): Promise<void> {\n const params: NetworkContinueWithAuthParameters =\n typeof paramsOrRequestId === 'string'\n ? ({\n request: paramsOrRequestId,\n action: 'provideCredentials',\n credentials: { type: 'password', username: username!, password: password! },\n } as NetworkContinueWithAuthParameters)\n : (paramsOrRequestId as NetworkContinueWithAuthParameters)\n await this.bidi.send({\n method: 'network.continueWithAuth',\n params: params as unknown as Record<string, unknown>,\n })\n }",
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Action required

3. Continuewithauth ignores errors 🐞 Bug ≡ Correctness

The Network enhancement overrides continueWithAuth() and calls this.bidi.send() directly without
checking for BiDi error responses, so server-side errors are silently ignored instead of thrown like
other generated commands.
Agent Prompt
### Issue description
The `continueWithAuth` enhancement override bypasses the generator’s standard `response.type === 'error'` check. Since `bidi.send()` resolves with the raw payload, this makes failures silent.

### Issue Context
`generate_bidi.mjs` intentionally makes generated commands throw on `response['type'] === 'error'`. Overriding a command should preserve this behavior.

### Fix Focus Areas
- javascript/selenium-webdriver/private/bidi_enhancements_manifest.json[45-57]
- javascript/selenium-webdriver/generate_bidi.mjs[860-891]
- javascript/selenium-webdriver/bidi/index.js[177-208]

### Suggested fix
- In the override, capture the response from `this.bidi.send(...)` and apply the same error check pattern as generated methods.
  - If `response.type === 'error'`, throw an `Error` with the server-provided details.
- Alternatively, avoid overriding the generated `continueWithAuth(params)` method:
  - Keep the generated method intact.
  - Add a separate deprecated wrapper name for the legacy positional signature that calls the generated method with a constructed params object.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

B-build Includes scripting, bazel and CI integrations B-devtools Includes everything BiDi or Chrome DevTools related C-nodejs JavaScript Bindings C-py Python Bindings

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants