From 9e9bf2a3badb59d0ce5bdb47c4e9d09ffb259e69 Mon Sep 17 00:00:00 2001 From: amankumarsingh77 Date: Mon, 27 Jul 2026 01:17:32 +0530 Subject: refactor(cdp): extract attachTo, getWindowId, evaluateJson helpers Target.attachToTarget was decoded at 5 sites, Browser.getWindowForTarget at 5, and Runtime.evaluate unwrapped at another. Each is now one typed helper. Deletes the dead cdp/window-binding.ts. Co-Authored-By: Claude Opus 5 (1M context) --- src/cdp/evaluate.ts | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 src/cdp/evaluate.ts (limited to 'src/cdp/evaluate.ts') diff --git a/src/cdp/evaluate.ts b/src/cdp/evaluate.ts new file mode 100644 index 0000000..cd68d61 --- /dev/null +++ b/src/cdp/evaluate.ts @@ -0,0 +1,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 ( + session: CdpSession, + expression: string, + check: (v: unknown) => v is T, +): Promise> => { + 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); +}; -- cgit v1.2.3