ChromeDevTools / devtools-protocol

Chrome DevTools Protocol
https://chromedevtools.github.io/devtools-protocol/
BSD 3-Clause "New" or "Revised" License
1.15k stars 226 forks source link

Method names not available #284

Open slhck opened 2 years ago

slhck commented 2 years ago

While I can use TypeScript to type-check method parameters and response objects, I cannot actually ensure that the method I am calling exists, let alone that the parameters and response match what I am trying to call.

Consider this (simplified) function:

let baseId = 0;

async function _sendAndGetResponse<
  ResponseType,
  RequestParams = Record<string, unknown>
>(method: string, params?: RequestParams): Promise<ResponseType> {
  const id = baseId++;
  const request = { id, method, params };

  webSocket.send(JSON.stringify(request));

  return new Promise((resolve, _) => {
    webSocket?.on("message", (data: string) => {
      const response = JSON.parse(data);
      if (response.id === id) {
        resolve(response.result as ResponseType);
      }
    });
  });
}

I can invoke it with

this._sendAndGetResponse<Protocol.Runtime.EvaluateResponse, Protocol.Runtime.EvaluateRequest>(
        'Runtime.evaluate',
        {
          expression: "...",
        },
      );

But I could easily pass Runtime.foo instead of Runtime.evaluate and it'd still pass.

What I think would be required is:

paulirish commented 2 years ago

Kinda sidestepping your question.. but you may want to look at leveraging https://www.npmjs.com/package/noice-json-rpc

I only found it recently but a few excellent tools use it. And the expression of CDP in the API is quite attractive.

Edit: Oh, you already found it. :)

slhck commented 2 years ago

Yes, I did! :)

I actually also found https://github.com/cyrus-and/chrome-remote-interface which is actively maintained and provides a similarly expressive API.

I also found that the file node_modules/devtools-protocol/types/protocol-proxy-api.d.ts does contain the individual methods, albeit in a slightly different manner.

Feel free to close this issue if it's not worth implementing this.