all repos — sz-chrome-remote-cdp @ 9e9bf2a3badb59d0ce5bdb47c4e9d09ffb259e69

pi-browser-harness, patched to drive a Chrome on another host over CDP, with castle_cdp_search web search

src/cdp/evaluate.ts (view raw)

 1
 2
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
import { type Result, err, ok } from "../util/result";
import { type CdpError, cdpError } from "./errors";
import type { CdpSession } from "./session";

/**
 * Runtime.evaluate, unwrapped and narrowed. Runs `expression`, surfaces a page
 * exception as an error, then applies `check` to the returned value — the
 * sanctioned way to turn `unknown` evaluate output into a typed `T` without a
 * cast.
 */
export const evaluateJson = async <T>(
  session: CdpSession,
  expression: string,
  check: (v: unknown) => v is T,
): Promise<Result<T, CdpError>> => {
  const r = await session.call("Runtime.evaluate", {
    expression,
    returnByValue: true,
    awaitPromise: true,
  });
  if (!r.success) return r;
  const { result, exceptionDetails } = r.data;
  if (exceptionDetails !== undefined) {
    return err(cdpError("remote_error", exceptionDetails.text, "Runtime.evaluate"));
  }
  const value = result.value;
  if (!check(value)) {
    return err(cdpError("invalid_response", `unexpected evaluate shape for: ${expression.slice(0, 60)}`, "Runtime.evaluate"));
  }
  return ok(value);
};