Skip to content

armgit / moli

Public Imported from GitHub
0

Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust

7.9 KB
Raw Blame
//! Page handlers whose terminal result is produced entirely by the renderer.
//! Browser-owned options are frozen at admission; observations generated by
//! the operation are settled before the handler publishes its response.

use super::*;
use crate::domains::native::{self, NativeCommandStep};
use moli_core::{
    RendererNativeOperation as Operation, RendererNativeProtocolResponse as Response,
    RendererPageCommand as Command, RendererPageReply as Reply,
};

pub(crate) fn try_start(conn: &mut CdpConnection, cmd: &Cmd<'_>) -> Option<NativeCommandStep> {
    let action = cmd.parse_action::<PageAction>()?;
    match prepare(conn, cmd, action) {
        Ok(Some(operation)) => Some(native::start_operation(conn, cmd, operation)),
        Ok(None) => preload::native::try_start(conn, cmd, action),
        Err(plan) => Some(NativeCommandStep::Complete(plan)),
    }
}

fn prepare(
    conn: &mut CdpConnection,
    cmd: &Cmd<'_>,
    action: PageAction,
) -> Result<Option<Operation>, CommandOutputPlan> {
    let operation = match action {
        PageAction::GetFrameTree | PageAction::GetResourceTree => {
            resource_tree::prepare_native_tree(conn, cmd, action == PageAction::GetResourceTree)
        }
        PageAction::GetLayoutMetrics => {
            Ok(Operation::new(
                Command::LayoutMetrics,
                |reply| match reply {
                    Ok(Reply::LayoutMetrics(metrics)) => {
                        Response::success(CommandOutputPlan::devtools_result_payload(
                            AutomationResult::LayoutMetrics(layout_metrics_result_from_renderer(
                                metrics,
                            )),
                        ))
                    }
                    Err(error) => Response::error(
                        -32000,
                        format!("Failed to produce layout metrics: {error}"),
                    ),
                    _ => unreachable!("Page layout metrics reply"),
                },
            ))
        }
        PageAction::CaptureScreenshot => {
            let command = capture::build_cdp_capture_screenshot_command(conn, cmd)?;
            capture::validate_page_capture_target_context(conn, &command.context)
                .map_err(CommandOutputPlan::from_devtools_error)?;
            if conn.layout_policy() == moli_core::LayoutPolicy::Mock {
                return Err(CommandOutputPlan::error(
                    -32000,
                    CAPTURE_SCREENSHOT_LAYOUT_DISABLED_MESSAGE,
                ));
            }
            let owner = CommandOwnerScope::capture(conn, cmd.session_id);
            let request = renderer_screenshot_request(
                &command,
                conn.default_background_color_for_owner(&owner),
            )
            .map_err(CommandOutputPlan::from_devtools_error)?;
            Ok(Operation::new(
                Command::CaptureScreenshot(request),
                |reply| match reply {
                    Ok(Reply::CaptureScreenshot(RendererCaptureScreenshotReply::Captured(
                        image,
                    ))) => Response::success(CommandOutputPlan::devtools_result_payload(
                        AutomationResult::CaptureScreenshot(DevToolsCaptureScreenshotResult {
                            mime_type: image.mime_type,
                            width: image.width,
                            height: image.height,
                            bytes: image.bytes,
                        }),
                    )),
                    Ok(Reply::CaptureScreenshot(
                        RendererCaptureScreenshotReply::LayoutDisabled,
                    )) => Response::error(-32000, CAPTURE_SCREENSHOT_LAYOUT_DISABLED_MESSAGE),
                    Ok(Reply::CaptureScreenshot(RendererCaptureScreenshotReply::NoDocument)) => {
                        Response::error(-32000, "NoDocumentLoaded")
                    }
                    Err(error) => Response::error(
                        -32000,
                        format!("Failed to capture page screenshot: {error}"),
                    ),
                    _ => unreachable!("Page screenshot reply"),
                },
            ))
        }
        PageAction::CaptureSnapshot => {
            #[derive(Default, Deserialize)]
            struct Params {
                #[serde(default)]
                format: Option<String>,
            }
            let params: Params = cmd
                .get_params()
                .map_err(|error| CommandOutputPlan::error(-32602, error))?
                .unwrap_or_default();
            if !matches!(params.format.as_deref(), None | Some("mhtml")) {
                return Err(CommandOutputPlan::error(
                    -32000,
                    "unsupported snapshot format.",
                ));
            }
            Ok(Operation::new(
                Command::SerializeDocument,
                |reply| match reply {
                    Ok(Reply::SerializedDocument { url, html }) => {
                        Response::success(json!({"data": build_mhtml_snapshot(&url, &html)}))
                    }
                    Err(error) => Response::error(
                        -32000,
                        format!("Failed to serialize page snapshot: {error}"),
                    ),
                    _ => unreachable!("Page snapshot reply"),
                },
            ))
        }
        PageAction::SetDocumentContent => {
            let params: SetDocumentContentParams = cmd
                .get_params()
                .ok()
                .flatten()
                .ok_or_else(|| CommandOutputPlan::error(-32602, "Invalid parameters"))?;
            Ok(Operation::new(
                Command::SetDocumentContent {
                    frame_id: params.frame_id.into(),
                    html: params.html,
                },
                |reply| match reply {
                    Ok(Reply::SetDocumentContentResult(
                        RendererSetDocumentContentResult::Updated,
                    )) => Response::success(json!({})),
                    Ok(Reply::SetDocumentContentResult(
                        RendererSetDocumentContentResult::FrameNotFound,
                    )) => Response::error(-32000, "No frame for given id found"),
                    Ok(Reply::SetDocumentContentResult(
                        RendererSetDocumentContentResult::DocumentNotFound,
                    )) => Response::error(-32000, "No Document instance to set HTML for"),
                    Err(error) => Response::error(-32000, error.to_string()),
                    _ => unreachable!("Page content reply"),
                },
            ))
        }
        PageAction::SetBypassCsp => {
            let params: SetBypassCspParams = cmd
                .get_params()
                .ok()
                .flatten()
                .ok_or_else(|| CommandOutputPlan::error(-32602, "InvalidParams"))?;
            if !conn.set_page_bypass_csp_enabled_for_session_owner(cmd.session_id, params.enabled) {
                return Err(CommandOutputPlan::error(-31998, "BrowserContextNotLoaded"));
            }
            let enabled = conn
                .effective_page_bypass_csp_enabled_for_session_owner(cmd.session_id)
                .ok_or_else(|| CommandOutputPlan::error(-31998, "BrowserContextNotLoaded"))?;
            Ok(Operation::new(
                Command::SetBypassContentSecurityPolicy(enabled),
                native::unit_response,
            ))
        }
        PageAction::ResetNavigationHistory => Ok(Operation::new(
            Command::ResetNavigationHistory,
            |reply| match reply {
                Ok(Reply::Bool(true)) => Response::success(json!({})),
                Ok(Reply::Bool(false)) => Response::error(-32000, "History cannot be pruned"),
                Err(error) => Response::error(-32000, error.to_string()),
                _ => unreachable!("Page history reset reply"),
            },
        )),
        _ => return Ok(None),
    };
    operation.map(Some)
}