///|
/// WebDriver BiDi WebSocket Server (Deno backend)
///
/// Uses Deno.serve with WebSocket upgrade for BiDi protocol.

///|
/// BiDi server configuration
pub(all) struct BidiServerConfig {
  host : String
  port : Int
  /// Optional auth token. If set, clients must connect to /session/.
  /// If empty, authentication is disabled (legacy behavior).
  auth_token : String
}

///|
/// Default configuration (generates a random auth token)
pub fn BidiServerConfig::default() -> BidiServerConfig {
  { host: "127.0.0.1", port: 9222, auth_token: generate_auth_token() }
}

///|
pub fn BidiServerConfig::web_socket_url(self : BidiServerConfig) -> String {
  if self.auth_token.is_empty() {
    "ws://\{self.host}:\{self.port}"
  } else {
    "ws://\{self.host}:\{self.port}/session/\{self.auth_token}"
  }
}

///|
/// Generate a random auth token using crypto.randomUUID
extern "js" fn js_generate_auth_token() -> String =
  #| () => {
  #|   try {
  #|     return crypto.randomUUID().replace(/-/g, "");
  #|   } catch (_e) {
  #|     return Math.random().toString(36).slice(2) + Math.random().toString(36).slice(2);
  #|   }
  #| }

///|
pub fn generate_auth_token() -> String {
  js_generate_auth_token()
}

///|
/// Extract URL pathname from a request
extern "js" fn js_get_request_pathname(request : @core.Any) -> String =
  #| (req) => {
  #|   try {
  #|     return new URL(req.url).pathname;
  #|   } catch (_e) {
  #|     return "/";
  #|   }
  #| }

///|
/// BiDi server state
pub struct BidiServer {
  config : BidiServerConfig
  priv protocol : BidiProtocol
  mut server : @core.Any?
}

///|
/// Create new BiDi server
pub fn BidiServer::new(
  config? : BidiServerConfig = BidiServerConfig::default(),
) -> BidiServer {
  { config, protocol: BidiProtocol::new(), server: None }
}

///|
/// Validate auth token from request path.
/// Expected path: /session/ when auth is enabled.
fn BidiServer::validate_auth(self : BidiServer, request : @core.Any) -> Bool {
  let token = self.config.auth_token
  if token.is_empty() {
    return true // Auth disabled
  }
  let path = js_get_request_pathname(request)
  path == "/session/" + token
}

///|
/// Deno.upgradeWebSocket FFI
extern "js" fn upgrade_websocket(request : @core.Any) -> @core.Any =
  #| (req) => Deno.upgradeWebSocket(req)

///|
/// Env flag helper for optional debug tracing.
extern "js" fn env_flag_enabled(name : String) -> Bool =
  #| (name) => {
  #|   try {
  #|     return typeof Deno !== "undefined" && Deno.env.get(name) === "1";
  #|   } catch (_e) {
  #|     return false;
  #|   }
  #| }

///|
/// Console log helper for optional server tracing.
extern "js" fn js_console_log(message : String) -> Unit =
  #| (message) => console.log(message)

///|
/// Convert JS value to string for debug logs.
extern "js" fn js_value_to_string(value : @core.Any) -> String =
  #| (value) => {
  #|   try {
  #|     if (value && typeof value === "object") {
  #|       const msg = value.message ?? value.reason ?? value.type;
  #|       if (msg !== undefined) return String(msg);
  #|     }
  #|     return String(value);
  #|   } catch (_e) {
  #|     return "[unprintable]";
  #|   }
  #| }

///|
/// Reset JS-side runtime globals between WebSocket sessions.
extern "js" fn reset_runtime_js_state() -> Unit =
  #| () => {
  #|   try {
  #|     globalThis.__bidiCurrentContext = "default-context";
  #|     globalThis.__bidiContextWindows = new Map();
  #|     globalThis.__bidiContextViewportState = new Map();
  #|     globalThis.__bidiPatchNavigatorTarget = (target, patch) => {
  #|       if (!target || typeof target !== "object") return null;
  #|       const current = target.navigator && typeof target.navigator === "object"
  #|         ? target.navigator
  #|         : null;
  #|       const next = (() => {
  #|         try {
  #|           const proto = current && typeof current === "object"
  #|             ? Object.getPrototypeOf(current)
  #|             : Object.prototype;
  #|           const value = Object.create(proto || Object.prototype);
  #|           if (current && typeof current === "object") {
  #|             try {
  #|               Object.defineProperties(value, Object.getOwnPropertyDescriptors(current));
  #|             } catch (_e) {
  #|               for (const key of Object.keys(current)) {
  #|                 try { value[key] = current[key]; } catch (_e2) {}
  #|               }
  #|             }
  #|           }
  #|           return value;
  #|         } catch (_e) {
  #|           const value = {};
  #|           if (current && typeof current === "object") {
  #|             for (const key of Object.keys(current)) {
  #|               try { value[key] = current[key]; } catch (_e2) {}
  #|             }
  #|           }
  #|           return value;
  #|         }
  #|       })();
  #|       const setField = (holder, name, value) => {
  #|         if (!holder || typeof holder !== "object") return;
  #|         try {
  #|           Object.defineProperty(holder, name, {
  #|             configurable: true,
  #|             enumerable: true,
  #|             writable: true,
  #|             value,
  #|           });
  #|           return;
  #|         } catch (_e) {}
  #|         try { holder[name] = value; } catch (_e) {}
  #|       };
  #|       const resolvedLanguage = String(
  #|         patch && patch.language !== undefined
  #|           ? patch.language
  #|           : (current && current.language !== undefined ? current.language : "en-US")
  #|       );
  #|       const resolvedLanguages =
  #|         patch && Array.isArray(patch.languages)
  #|           ? Array.from(patch.languages)
  #|           : (
  #|             current && Array.isArray(current.languages)
  #|               ? Array.from(current.languages)
  #|               : [resolvedLanguage]
  #|           );
  #|       setField(
  #|         next,
  #|         "userAgent",
  #|         String(
  #|           patch && patch.userAgent !== undefined
  #|             ? patch.userAgent
  #|             : (current && current.userAgent !== undefined
  #|                 ? current.userAgent
  #|                 : "Crater/1.0 (MoonBit; BiDi)")
  #|         ),
  #|       );
  #|       setField(
  #|         next,
  #|         "platform",
  #|         String(current && current.platform !== undefined ? current.platform : "Crater"),
  #|       );
  #|       setField(next, "language", resolvedLanguage);
  #|       setField(next, "languages", resolvedLanguages);
  #|       setField(
  #|         next,
  #|         "onLine",
  #|         patch && patch.onLine !== undefined
  #|           ? !!patch.onLine
  #|           : (current ? current.onLine !== false : true),
  #|       );
  #|       setField(
  #|         next,
  #|         "cookieEnabled",
  #|         Boolean(current && current.cookieEnabled !== undefined ? current.cookieEnabled : false),
  #|       );
  #|       const userActivation =
  #|         current && current.userActivation && typeof current.userActivation === "object"
  #|           ? { ...current.userActivation }
  #|           : { isActive: false, hasBeenActive: false };
  #|       setField(next, "userActivation", userActivation);
  #|       try {
  #|         Object.defineProperty(target, "navigator", {
  #|           configurable: true,
  #|           enumerable: true,
  #|           writable: true,
  #|           value: next,
  #|         });
  #|         return next;
  #|       } catch (_e) {}
  #|       try {
  #|         target.navigator = next;
  #|         return target.navigator;
  #|       } catch (_e) {}
  #|       if (current && typeof current === "object") {
  #|         for (const name of ["userAgent", "platform", "language", "languages", "onLine", "cookieEnabled", "userActivation"]) {
  #|           try { setField(current, name, next[name]); } catch (_e) {}
  #|         }
  #|         return current;
  #|       }
  #|       return null;
  #|     };
  #|     if (!globalThis.__bidiProxyInstances) {
  #|       globalThis.__bidiProxyInstances = new WeakSet();
  #|     }
  #|     globalThis.allEvents = undefined;
  #|     globalThis.recordedEvents = undefined;
  #|     globalThis._shadowRoot = undefined;
  #|     globalThis.__bidiLastClickHref = undefined;
  #|     globalThis.__bidiChannelMessages = [];
  #|     globalThis.__bidiSharedNodeStore = new Map();
  #|     globalThis.__bidiHandleStore = new Map();
  #|     globalThis.__bidiNextHandleId = 1;
  #|   } catch (_e) {}
  #| }

///|
/// Ensure JS-side navigator patch helper exists for runtime emulation overrides.
extern "js" fn ensure_runtime_navigator_patch_helper() -> Unit =
  #| () => {
  #|   if (typeof globalThis.__bidiPatchNavigatorTarget === "function") return;
  #|   try { globalThis.__bidiCurrentContext = globalThis.__bidiCurrentContext || "default-context"; } catch (_e) {}
  #|   try { globalThis.__bidiContextWindows = globalThis.__bidiContextWindows || new Map(); } catch (_e) {}
  #|   try {
  #|     globalThis.__bidiPatchNavigatorTarget = (target, patch) => {
  #|       if (!target || typeof target !== "object") return null;
  #|       const current = target.navigator && typeof target.navigator === "object"
  #|         ? target.navigator
  #|         : null;
  #|       const next = (() => {
  #|         try {
  #|           const proto = current && typeof current === "object"
  #|             ? Object.getPrototypeOf(current)
  #|             : Object.prototype;
  #|           const value = Object.create(proto || Object.prototype);
  #|           if (current && typeof current === "object") {
  #|             try {
  #|               Object.defineProperties(value, Object.getOwnPropertyDescriptors(current));
  #|             } catch (_e) {
  #|               for (const key of Object.keys(current)) {
  #|                 try { value[key] = current[key]; } catch (_e2) {}
  #|               }
  #|             }
  #|           }
  #|           return value;
  #|         } catch (_e) {
  #|           const value = {};
  #|           if (current && typeof current === "object") {
  #|             for (const key of Object.keys(current)) {
  #|               try { value[key] = current[key]; } catch (_e2) {}
  #|             }
  #|           }
  #|           return value;
  #|         }
  #|       })();
  #|       const setField = (holder, name, value) => {
  #|         if (!holder || typeof holder !== "object") return;
  #|         try {
  #|           Object.defineProperty(holder, name, {
  #|             configurable: true,
  #|             enumerable: true,
  #|             writable: true,
  #|             value,
  #|           });
  #|           return;
  #|         } catch (_e) {}
  #|         try { holder[name] = value; } catch (_e) {}
  #|       };
  #|       const resolvedLanguage = String(
  #|         patch && patch.language !== undefined
  #|           ? patch.language
  #|           : (current && current.language !== undefined ? current.language : "en-US")
  #|       );
  #|       const resolvedLanguages =
  #|         patch && Array.isArray(patch.languages)
  #|           ? Array.from(patch.languages)
  #|           : (
  #|             current && Array.isArray(current.languages)
  #|               ? Array.from(current.languages)
  #|               : [resolvedLanguage]
  #|           );
  #|       setField(
  #|         next,
  #|         "userAgent",
  #|         String(
  #|           patch && patch.userAgent !== undefined
  #|             ? patch.userAgent
  #|             : (current && current.userAgent !== undefined
  #|                 ? current.userAgent
  #|                 : "Crater/1.0 (MoonBit; BiDi)")
  #|         ),
  #|       );
  #|       setField(
  #|         next,
  #|         "platform",
  #|         String(current && current.platform !== undefined ? current.platform : "Crater"),
  #|       );
  #|       setField(next, "language", resolvedLanguage);
  #|       setField(next, "languages", resolvedLanguages);
  #|       setField(
  #|         next,
  #|         "onLine",
  #|         patch && patch.onLine !== undefined
  #|           ? !!patch.onLine
  #|           : (current ? current.onLine !== false : true),
  #|       );
  #|       setField(
  #|         next,
  #|         "cookieEnabled",
  #|         Boolean(current && current.cookieEnabled !== undefined ? current.cookieEnabled : false),
  #|       );
  #|       const userActivation =
  #|         current && current.userActivation && typeof current.userActivation === "object"
  #|           ? { ...current.userActivation }
  #|           : { isActive: false, hasBeenActive: false };
  #|       setField(next, "userActivation", userActivation);
  #|       try {
  #|         Object.defineProperty(target, "navigator", {
  #|           configurable: true,
  #|           enumerable: true,
  #|           writable: true,
  #|           value: next,
  #|         });
  #|         return next;
  #|       } catch (_e) {}
  #|       try {
  #|         target.navigator = next;
  #|         return target.navigator;
  #|       } catch (_e) {}
  #|       if (current && typeof current === "object") {
  #|         for (const name of ["userAgent", "platform", "language", "languages", "onLine", "cookieEnabled", "userActivation"]) {
  #|           try { setField(current, name, next[name]); } catch (_e) {}
  #|         }
  #|         return current;
  #|       }
  #|       return null;
  #|     };
  #|   } catch (_e) {}
  #| }

///|
/// Debug trace hook (disabled unless CRATER_BIDI_SERVER_TRACE=1).
fn bidi_server_trace(message : String) -> Unit {
  if env_flag_enabled("CRATER_BIDI_SERVER_TRACE") {
    js_console_log("[bidi-server] " + message)
  }
}

///|
/// Check if request is WebSocket upgrade
fn is_websocket_request(request : @core.Any) -> Bool {
  let headers : @core.Any = request._get("headers")
  let upgrade_any = headers._call("get", [@core.any("upgrade")])
  // Check if upgrade header exists (not null/undefined)
  if @core.is_nullish(upgrade_any) {
    return false
  }
  let upgrade : String = upgrade_any.cast()
  upgrade.to_lower() == "websocket"
}

///|
/// Handle WebSocket message, returns all response/event messages
fn BidiServer::handle_message(
  self : BidiServer,
  data : String,
) -> Array[String] {
  match self.protocol.process_message(data) {
    Ok(_) => {
      let messages = self.protocol.take_messages()
      let result : Array[String] = []
      for msg in messages {
        result.push(msg.to_json())
      }
      result
    }
    Err(e) =>
      [
        "{\"type\":\"error\",\"error\":\"unknown error\",\"message\":\"" +
        e +
        "\"}",
      ]
  }
}

///|
/// Setup WebSocket event handlers with async support
fn BidiServer::setup_websocket(self : BidiServer, socket : @core.Any) -> Unit {
  reset_runtime_js_state()
  reset_paint_provider()
  bidi_server_trace("setup_websocket: begin reset")
  self.protocol.reset_session_runtime_state()
  bidi_server_trace("setup_websocket: reset done")
  // Store socket reference for async responses
  let socket_epoch = self.protocol.set_socket(socket)
  bidi_server_trace("setup_websocket: socket epoch=" + socket_epoch.to_string())

  // onopen
  socket["onopen"] = @core.any(
    @core.from_fn1(fn(_event : @core.Any) {
      // Connection opened, could log or initialize
      bidi_server_trace("ws onopen")
    }),
  )

  // onmessage - process BiDi messages (supports async via socket)
  socket["onmessage"] = @core.any(
    @core.from_fn1(fn(event : @core.Any) {
      bidi_server_trace("ws onmessage: received")
      let raw_data = event._get("data")
      if @core.is_nullish(raw_data) {
        bidi_server_trace("ws onmessage: nullish data")
        return
      }
      let data : String = raw_data.cast()
      // handle_message returns sync responses; async responses sent via socket
      let messages = self.handle_message(data)
      bidi_server_trace(
        "ws onmessage: responses=" + messages.length().to_string(),
      )
      for msg in messages {
        socket._call("send", [@core.any(msg)]) |> ignore
      }
    }),
  )

  // onerror
  socket["onerror"] = @core.any(
    @core.from_fn1(fn(event : @core.Any) {
      // Error handling
      bidi_server_trace("ws onerror: " + js_value_to_string(event))
    }),
  )

  // onclose
  socket["onclose"] = @core.any(
    @core.from_fn1(fn(_event : @core.Any) {
      // Connection closed
      bidi_server_trace("ws onclose: epoch=" + socket_epoch.to_string())
      if self.protocol.is_current_socket_epoch(socket_epoch) {
        bidi_server_trace("ws onclose: reset current epoch")
        self.protocol.reset_session_runtime_state()
        self.protocol.clear_socket()
        bidi_server_trace("ws onclose: reset done")
      }
    }),
  )
}

///|
/// Create HTTP response for non-WebSocket requests
extern "js" fn create_response(body : String, status : Int) -> @core.Any =
  #| (body, status) => new Response(body, { status, headers: { "Content-Type": "application/json" } })

///|
fn bidi_status_response_body(config : BidiServerConfig) -> String {
  let auth_enabled = if config.auth_token.is_empty() { "false" } else { "true" }
  let web_socket_url = escape_json_string(config.web_socket_url())
  "{\"ready\":true,\"message\":\"Crater WebDriver BiDi Server\",\"webSocketUrl\":\"" +
  web_socket_url +
  "\",\"authEnabled\":" +
  auth_enabled +
  "}"
}

///|
/// Start the BiDi server using Deno.serve
pub fn BidiServer::start(self : BidiServer) -> Unit {
  let d = @deno.deno()

  // Create request handler
  let handler = @core.from_fn1(fn(request : @core.Any) -> @core.Any {
    if is_websocket_request(request) {
      // Security: validate auth token before upgrading
      if !self.validate_auth(request) {
        let body = "{\"error\":\"unauthorized\",\"message\":\"Invalid or missing auth token\"}"
        return create_response(body, 403)
      }
      // Upgrade to WebSocket
      let upgrade_result = upgrade_websocket(request)
      let socket : @core.Any = upgrade_result._get("socket")
      let response : @core.Any = upgrade_result._get("response")
      self.setup_websocket(socket)
      response
    } else {
      // Return status response for HTTP requests
      let body = bidi_status_response_body(self.config)
      create_response(body, 200)
    }
  })

  // Start server with Deno.serve
  let opts : @core.Any = @core.from_entries([
    ("port", @core.any(self.config.port)),
    ("hostname", @core.any(self.config.host)),
  ]).cast()

  // Call Deno.serve with options and handler
  self.server = Some(d.as_any()._call("serve", [opts, @core.any(handler)]))
}

///|
/// Stop the server
pub fn BidiServer::stop(self : BidiServer) -> Unit {
  match self.server {
    Some(srv) => {
      srv._call("shutdown", []) |> ignore
      self.server = None
    }
    None => ()
  }
}

// =============================================================================
// JavaScript Evaluation for BiDi script.evaluate
// =============================================================================

///|
/// FFI: Evaluate JavaScript expression and return BiDi remote value JSON
/// Returns: { "type": "success"|"exception", "result"|"exceptionDetails": ..., "consoleEntries": [...] }
extern "js" fn js_evaluate_expression(
  expression : String,
  capture_console : Bool,
  user_activation : Bool,
  root_ownership : Bool,
  serialization_options_json : String,
) -> String =
  #| (expression, captureConsole, userActivation, rootOwnership, serializationOptionsJson) => {
  #|   const consoleEntries = [];
  #|   let originalConsole = null;
  #|   const resolveCurrentLogUrl = () => {
  #|     try {
  #|       if (globalThis.location && typeof globalThis.location.href === "string" && globalThis.location.href !== "") {
  #|         return String(globalThis.location.href);
  #|       }
  #|     } catch (_e) {}
  #|     try {
  #|       if (typeof globalThis.__pageUrl === "string" && globalThis.__pageUrl !== "") {
  #|         return String(globalThis.__pageUrl);
  #|       }
  #|     } catch (_e) {}
  #|     return "about:blank";
  #|   };
  #|   const resolveInlineScriptOffsets = () => {
  #|     const url = resolveCurrentLogUrl();
  #|     if (!url.startsWith("data:")) {
  #|       return { lineOffset: 0, columnOffset: 0 };
  #|     }
  #|     try {
  #|       const comma = url.indexOf(",");
  #|       if (comma < 0) return { lineOffset: 0, columnOffset: 0 };
  #|       const meta = url.slice(0, comma).toLowerCase();
  #|       const payload = url.slice(comma + 1);
  #|       let decoded = "";
  #|       if (meta.includes(";base64")) {
  #|         decoded = atob(payload);
  #|       } else {
  #|         decoded = decodeURIComponent(payload);
  #|       }
  #|       const lines = decoded.replace(/\r\n/g, "\n").split("\n");
  #|       let inScript = false;
  #|       for (let index = 0; index < lines.length; index++) {
  #|         const line = String(lines[index] || "");
  #|         const lower = line.toLowerCase();
  #|         if (!inScript) {
  #|           if (lower.includes(" {
  #|     const frames = [];
  #|     const stack = String(stackText || "");
  #|     const lines = stack.split("\n");
  #|     for (let i = 0; i < lines.length; i++) {
  #|       const rawLine = String(lines[i] || "").trim();
  #|       if (!rawLine.startsWith("at ")) continue;
  #|       const body = rawLine.slice(3);
  #|       let functionName = "";
  #|       let location = body;
  #|       const withParens = body.match(/^(.*?)\s+\((.*)\)$/);
  #|       if (withParens) {
  #|         functionName = String(withParens[1] || "");
  #|         location = String(withParens[2] || "");
  #|       } else {
  #|         functionName = "";
  #|         location = body;
  #|       }
  #|       if (
  #|         functionName.includes("pushConsoleEntry") ||
  #|         functionName.includes("makeInterceptor")
  #|       ) {
  #|         continue;
  #|       }
  #|       let lineNumber = 0;
  #|       let columnNumber = 0;
  #|       let url = resolveCurrentLogUrl();
  #|       const anonymousLocationMatch = location.match(/:(\d+):(\d+)$/);
  #|       if (anonymousLocationMatch) {
  #|         const leadingColumnOffset = frames.length === 0
  #|           ? Number(inlineScriptOffsets.columnOffset || 0)
  #|           : 0;
  #|         lineNumber = Number(anonymousLocationMatch[1]) + Number(inlineScriptOffsets.lineOffset || 0);
  #|         columnNumber = Math.max(
  #|           0,
  #|           Number(anonymousLocationMatch[2]) + leadingColumnOffset - 1,
  #|         );
  #|       } else {
  #|         const locationMatch = location.match(/^(.*):(\d+):(\d+)$/);
  #|         if (!locationMatch) continue;
  #|         url = String(locationMatch[1] || "");
  #|         if (url.includes("bidi_main.js")) continue;
  #|         lineNumber = Number(locationMatch[2]);
  #|         columnNumber = Math.max(0, Number(locationMatch[3]) - 1);
  #|       }
  #|       if (functionName === "eval") {
  #|         functionName = "";
  #|       }
  #|       frames.push({
  #|         columnNumber,
  #|         functionName,
  #|         lineNumber,
  #|         url,
  #|       });
  #|       if (frames.length >= 3) break;
  #|     }
  #|     return { callFrames: frames };
  #|   };
  #|   const pushJavascriptErrorEntry = (errorValue) => {
  #|     if (!captureConsole) return;
  #|     const stackTrace = buildStackTraceFromStack(errorValue && errorValue.stack ? errorValue.stack : "");
  #|     const entry = {
  #|       type: "javascript",
  #|       level: "error",
  #|       text: String(errorValue),
  #|       timestamp: Date.now(),
  #|       realm: String(globalThis.__bidiCurrentRealm || ""),
  #|     };
  #|     if (Array.isArray(stackTrace.callFrames) && stackTrace.callFrames.length > 0) {
  #|       entry.stackTrace = stackTrace;
  #|     }
  #|     consoleEntries.push(entry);
  #|   };
  #|   globalThis.__bidiPushJavascriptErrorEntry = pushJavascriptErrorEntry;
  #|   if (captureConsole) {
  #|     originalConsole = {
  #|       log: console.log,
  #|       warn: console.warn,
  #|       error: console.error,
  #|       info: console.info,
  #|       debug: console.debug,
  #|       assert: console.assert,
  #|       table: console.table,
  #|       trace: console.trace,
  #|       time: console.time,
  #|       timeEnd: console.timeEnd
  #|     };
  #|
  #|     const consoleArgToText = (arg) => {
  #|       if (typeof arg === "string") return arg;
  #|       if (arg === undefined) return "undefined";
  #|       if (typeof arg === "bigint") return `${arg}n`;
  #|       try {
  #|         const json = JSON.stringify(arg);
  #|         if (json !== undefined) return json;
  #|       } catch (_e) {}
  #|       return String(arg);
  #|     };
  #|
  #|     const pushConsoleEntry = (level, method, args, textArgs = args) => {
  #|       const stackTrace = buildStackTraceFromStack(new Error().stack || "");
  #|       const entry = {
  #|         type: "console",
  #|         level,
  #|         method,
  #|         text: textArgs.map(consoleArgToText).join(" "),
  #|         args: args.map(toBidiValue),
  #|         timestamp: Date.now(),
  #|         realm: String(globalThis.__bidiCurrentRealm || ""),
  #|       };
  #|       if (Array.isArray(stackTrace.callFrames) && stackTrace.callFrames.length > 0) {
  #|         entry.stackTrace = stackTrace;
  #|       }
  #|       consoleEntries.push(entry);
  #|     };
  #|
  #|     // Intercept console calls
  #|     const makeInterceptor = (level, method) => (...args) => {
  #|       pushConsoleEntry(level, method, args);
  #|       originalConsole[method](...args);
  #|     };
  #|
  #|     console.log = makeInterceptor('info', 'log');
  #|     console.warn = makeInterceptor('warn', 'warn');
  #|     console.error = makeInterceptor('error', 'error');
  #|     console.info = makeInterceptor('info', 'info');
  #|     console.debug = makeInterceptor('debug', 'debug');
  #|     console.table = makeInterceptor('info', 'table');
  #|     console.trace = makeInterceptor('debug', 'trace');
  #|     console.assert = (...args) => {
  #|       if (args.length > 0 && args[0]) {
  #|         return;
  #|       }
  #|       const textArgs = args.length > 1 ? args.slice(1) : ["Assertion failed"];
  #|       pushConsoleEntry("error", "assert", textArgs);
  #|       originalConsole.assert(...args);
  #|     };
  #|     console.time = (...args) => {
  #|       originalConsole.time(...args);
  #|     };
  #|     console.timeEnd = (...args) => {
  #|       const textArgs = args.length > 0 ? args : ["default"];
  #|       pushConsoleEntry("info", "timeEnd", textArgs);
  #|       originalConsole.timeEnd(...args);
  #|     };
  #|   }
  #|
  #|   let serializationOptions = {};
  #|   try {
  #|     serializationOptions =
  #|       serializationOptionsJson && serializationOptionsJson.length > 0
  #|         ? JSON.parse(serializationOptionsJson)
  #|         : {};
  #|   } catch (_e) {
  #|     serializationOptions = {};
  #|   }
  #|   const hasMaxDomDepth = Object.prototype.hasOwnProperty.call(serializationOptions, "maxDomDepth");
  #|   const hasMaxObjectDepth = Object.prototype.hasOwnProperty.call(serializationOptions, "maxObjectDepth");
  #|   const rawMaxDomDepth = hasMaxDomDepth ? serializationOptions.maxDomDepth : undefined;
  #|   const rawMaxObjectDepth = hasMaxObjectDepth ? serializationOptions.maxObjectDepth : undefined;
  #|   const maxDomDepth =
  #|     rawMaxDomDepth === null
  #|       ? null
  #|       : (typeof rawMaxDomDepth === "number" && rawMaxDomDepth >= 0 ? rawMaxDomDepth : undefined);
  #|   const maxObjectDepth =
  #|     rawMaxObjectDepth === null
  #|       ? null
  #|       : (typeof rawMaxObjectDepth === "number" && rawMaxObjectDepth >= 0 ? rawMaxObjectDepth : undefined);
  #|   const includeShadowTree =
  #|     serializationOptions.includeShadowTree === "open" || serializationOptions.includeShadowTree === "all"
  #|       ? serializationOptions.includeShadowTree
  #|       : "none";
  #|
  #|   const applyUserActivation = (active) => {
  #|     const isActive = !!active;
  #|     globalThis.__bidiUserActivation = isActive;
  #|     if (!globalThis.navigator) globalThis.navigator = {};
  #|     globalThis.navigator.userActivation = {
  #|       isActive,
  #|       hasBeenActive: isActive
  #|     };
  #|     if (globalThis.document) {
  #|       globalThis.document.execCommand = function(command) {
  #|         const cmd = String(command || '').toLowerCase();
  #|         if (cmd === 'selectall') return true;
  #|         if (cmd === 'copy') return !!globalThis.__bidiUserActivation;
  #|         return false;
  #|       };
  #|     }
  #|   };
  #|
  #|   // Setup Mock DOM if not already present
  #|   if (!globalThis.document) {
  #|     // MutationObserver implementation
  #|     const _mutationObservers = [];
  #|     let _mutationScheduled = false;
  #|     const _pendingMutations = new Map();
  #|
  #|     const shouldNotify = (mutatedNode, observedTarget, options, type) => {
  #|       if (type === 'childList' && !options.childList) return false;
  #|       if (type === 'attributes' && !options.attributes) return false;
  #|       if (type === 'characterData' && !options.characterData) return false;
  #|       if (mutatedNode === observedTarget) return true;
  #|       if (options.subtree) {
  #|         let node = mutatedNode;
  #|         while (node) {
  #|           if (node === observedTarget) return true;
  #|           node = node._parent;
  #|         }
  #|       }
  #|       return false;
  #|     };
  #|
  #|     const createMutationRecord = (type, target, opts = {}) => ({
  #|       type,
  #|       target,
  #|       addedNodes: opts.addedNodes || [],
  #|       removedNodes: opts.removedNodes || [],
  #|       previousSibling: opts.previousSibling || null,
  #|       nextSibling: opts.nextSibling || null,
  #|       attributeName: opts.attributeName || null,
  #|       attributeNamespace: opts.attributeNamespace || null,
  #|       oldValue: opts.oldValue || null
  #|     });
  #|
  #|     const notifyMutation = (record) => {
  #|       for (const observer of _mutationObservers) {
  #|         for (const { target, options } of observer._targets) {
  #|           if (shouldNotify(record.target, target, options, record.type)) {
  #|             if (!_pendingMutations.has(observer)) {
  #|               _pendingMutations.set(observer, []);
  #|             }
  #|             _pendingMutations.get(observer).push(record);
  #|             break;
  #|           }
  #|         }
  #|       }
  #|       // Schedule microtask to batch notifications
  #|       if (!_mutationScheduled && _pendingMutations.size > 0) {
  #|         _mutationScheduled = true;
  #|         // Use Promise.resolve for microtask scheduling (works in Deno)
  #|         Promise.resolve().then(() => {
  #|           _mutationScheduled = false;
  #|           for (const [observer, records] of _pendingMutations) {
  #|             if (records.length > 0) {
  #|               try {
  #|                 observer._callback(records, observer);
  #|               } catch (e) {
  #|                 console.error('MutationObserver callback error:', e);
  #|               }
  #|             }
  #|           }
  #|           _pendingMutations.clear();
  #|         });
  #|       }
  #|     };
  #|
  #|     globalThis.MutationObserver = class MutationObserver {
  #|       constructor(callback) {
  #|         this._callback = callback;
  #|         this._targets = [];
  #|       }
  #|       observe(target, options = {}) {
  #|         this._targets.push({ target, options });
  #|         if (!_mutationObservers.includes(this)) {
  #|           _mutationObservers.push(this);
  #|         }
  #|       }
  #|       disconnect() {
  #|         this._targets = [];
  #|         const idx = _mutationObservers.indexOf(this);
  #|         if (idx !== -1) _mutationObservers.splice(idx, 1);
  #|         _pendingMutations.delete(this);
  #|       }
  #|       takeRecords() {
  #|         const records = _pendingMutations.get(this) || [];
  #|         _pendingMutations.delete(this);
  #|         return records;
  #|       }
  #|     };
  #|
  #|     const toCollection = (items, collectionType) => {
  #|       if (!Array.isArray(items)) return items;
  #|       if (collectionType) {
  #|         Object.defineProperty(items, "__bidiCollectionType", {
  #|           value: String(collectionType),
  #|           configurable: true,
  #|           enumerable: false,
  #|           writable: true
  #|         });
  #|       }
  #|       if (typeof items.item !== "function") {
  #|         items.item = function(index) {
  #|           return this[index] ?? null;
  #|         };
  #|       }
  #|       return items;
  #|     };
  #|
  #|     // Minimal Mock DOM for Preact compatibility
  #|     const getContainingShadowRoot = (node) => {
  #|       let current = node;
  #|       while (current) {
  #|         if (current._isShadowRoot) return current;
  #|         current = current._parent || current.parentNode || null;
  #|       }
  #|       return null;
  #|     };
  #|     const getFocusAttr = (node, name) => {
  #|       if (!node || typeof node !== "object") return null;
  #|       try {
  #|         if (typeof node.getAttribute === "function") {
  #|           const value = node.getAttribute(name);
  #|           if (value !== null && value !== undefined) return String(value);
  #|         }
  #|       } catch (_e) {}
  #|       if (node._attrs && Object.prototype.hasOwnProperty.call(node._attrs, name)) {
  #|         const value = node._attrs[name];
  #|         return value === null || value === undefined ? null : String(value);
  #|       }
  #|       return null;
  #|     };
  #|     const getFocusChildren = (node) => {
  #|       if (!node || typeof node !== "object") return [];
  #|       if (Array.isArray(node._children)) return node._children;
  #|       if (Array.isArray(node.children)) return Array.from(node.children);
  #|       if (Array.isArray(node.childNodes)) return Array.from(node.childNodes);
  #|       return [];
  #|     };
  #|     const nodeContains = (root, node) => {
  #|       if (!root || !node) return false;
  #|       if (root === node) return true;
  #|       try {
  #|         if (typeof root.contains === "function") return !!root.contains(node);
  #|       } catch (_e) {}
  #|       const children = getFocusChildren(root);
  #|       for (let i = 0; i < children.length; i += 1) {
  #|         if (nodeContains(children[i], node)) return true;
  #|       }
  #|       return false;
  #|     };
  #|     const isSlotElementForFocus = (node) => {
  #|       if (!node || node.nodeType !== 1) return false;
  #|       const localName = String(node.localName || node.tagName || node.nodeName || "").toLowerCase();
  #|       return localName === "slot";
  #|     };
  #|     const findFirstSlotForFocusName = (root, slotName) => {
  #|       const children = getFocusChildren(root);
  #|       for (let i = 0; i < children.length; i += 1) {
  #|         const child = children[i];
  #|         if (!child || child.nodeType !== 1) continue;
  #|         if (isSlotElementForFocus(child) && String(getFocusAttr(child, "name") || "") === slotName) {
  #|           return child;
  #|         }
  #|         const nested = findFirstSlotForFocusName(child, slotName);
  #|         if (nested) return nested;
  #|       }
  #|       return null;
  #|     };
  #|     const getAssignedChildrenForFocusSlot = (slot) => {
  #|       const shadowRoot = getContainingShadowRoot(slot);
  #|       if (!shadowRoot || !shadowRoot.host) return getFocusChildren(slot);
  #|       const slotName = String(getFocusAttr(slot, "name") || "");
  #|       const firstMatch = findFirstSlotForFocusName(shadowRoot, slotName);
  #|       if (firstMatch && firstMatch !== slot) return [];
  #|       const assigned = [];
  #|       const hostChildren = getFocusChildren(shadowRoot.host);
  #|       for (let i = 0; i < hostChildren.length; i += 1) {
  #|         const child = hostChildren[i];
  #|         if (!child) continue;
  #|         const childSlotName = String(getFocusAttr(child, "slot") || "");
  #|         if (childSlotName === slotName) assigned.push(child);
  #|       }
  #|       return assigned.length > 0 ? assigned : getFocusChildren(slot);
  #|     };
  #|     const getDelegatesFocusChildren = (node) => {
  #|       if (!node || typeof node !== "object") return [];
  #|       if (isSlotElementForFocus(node)) return getAssignedChildrenForFocusSlot(node);
  #|       const shadowRoot = node.shadowRoot || null;
  #|       if (shadowRoot) return getFocusChildren(shadowRoot);
  #|       return getFocusChildren(node);
  #|     };
  #|     const hasExplicitSequentialTabIndexForFocus = (node) => {
  #|       if (!node || typeof node !== "object") return false;
  #|       try {
  #|         if (typeof node.getAttribute === "function" && node.getAttribute("tabindex") !== null) {
  #|           return true;
  #|         }
  #|       } catch (_e) {}
  #|       return !!(node._attrs && Object.prototype.hasOwnProperty.call(node._attrs, "tabindex"));
  #|     };
  #|     const isSequentiallyFocusableForFocus = (node) => {
  #|       if (!node || node.nodeType !== 1) return false;
  #|       if (node.disabled || node.hidden) return false;
  #|       const style = node.style || {};
  #|       if (style.display === "none" || style.visibility === "hidden") return false;
  #|       if (hasExplicitSequentialTabIndexForFocus(node)) {
  #|         try {
  #|           return Number(node.tabIndex) >= 0;
  #|         } catch (_e) {
  #|           return false;
  #|         }
  #|       }
  #|       const tag = String(node.tagName || node.nodeName || "").toLowerCase();
  #|       if (["input", "textarea", "select", "button"].includes(tag)) return true;
  #|       if (tag === "a") {
  #|         try {
  #|           return !!(typeof node.getAttribute === "function" ? node.getAttribute("href") : null);
  #|         } catch (_e) {
  #|           return false;
  #|         }
  #|       }
  #|       return !!node.isContentEditable;
  #|     };
  #|     const findDelegatesFocusTarget = (node) => {
  #|       const shadowRoot = node && node.shadowRoot ? node.shadowRoot : null;
  #|       if (!shadowRoot || !shadowRoot.delegatesFocus) return null;
  #|       const visit = (current) => {
  #|         const children = getDelegatesFocusChildren(current);
  #|         for (let i = 0; i < children.length; i += 1) {
  #|           const child = children[i];
  #|           if (!child || child.nodeType !== 1) continue;
  #|           if (isSequentiallyFocusableForFocus(child)) return child;
  #|           const nested = visit(child);
  #|           if (nested) return nested;
  #|         }
  #|         return null;
  #|       };
  #|       return visit(shadowRoot);
  #|     };
  #|     const clearDocumentActiveChain = (doc) => {
  #|       if (!doc) return;
  #|       const current = doc.activeElement || null;
  #|       if (current && current.shadowRoot && current.shadowRoot.activeElement) {
  #|         current.shadowRoot.activeElement = null;
  #|       }
  #|       doc.activeElement = doc.body || null;
  #|     };
  #|     const getDeepActiveElement = (doc) => {
  #|       if (!doc) return null;
  #|       let current = doc.activeElement || null;
  #|       const visited = new Set();
  #|       while (current && !visited.has(current)) {
  #|         visited.add(current);
  #|         const next =
  #|           current.shadowRoot && current.shadowRoot.activeElement
  #|             ? current.shadowRoot.activeElement
  #|             : null;
  #|         if (!next) break;
  #|         current = next;
  #|       }
  #|       return current;
  #|     };
  #|     const retargetEventTarget = (originalTarget, currentTarget) => {
  #|       let candidate = originalTarget;
  #|       while (candidate) {
  #|         const shadowRoot = getContainingShadowRoot(candidate);
  #|         if (!shadowRoot) return candidate;
  #|         if (currentTarget === shadowRoot || nodeContains(shadowRoot, currentTarget)) {
  #|           return candidate;
  #|         }
  #|         candidate = shadowRoot.host || candidate;
  #|         if (!shadowRoot.host) return candidate;
  #|       }
  #|       return originalTarget;
  #|     };
  #|     const prepareEventForCurrentTarget = (event, currentTarget) => {
  #|       const originalTarget = event.__originalTarget || event.target || currentTarget;
  #|       const originalRelatedTarget =
  #|         event.__originalRelatedTarget !== undefined
  #|           ? event.__originalRelatedTarget
  #|           : (event.relatedTarget || null);
  #|       event.__originalTarget = originalTarget;
  #|       event.__originalRelatedTarget = originalRelatedTarget;
  #|       const adjustedTarget = retargetEventTarget(originalTarget, currentTarget);
  #|       const adjustedRelatedTarget = originalRelatedTarget
  #|         ? retargetEventTarget(originalRelatedTarget, currentTarget)
  #|         : null;
  #|       event.__retargetSuppressed =
  #|         !!(adjustedTarget && adjustedRelatedTarget && adjustedTarget === adjustedRelatedTarget);
  #|       try { event.target = adjustedTarget; } catch (_e) {}
  #|       try { event.relatedTarget = adjustedRelatedTarget; } catch (_e) {}
  #|       try { event.currentTarget = currentTarget; } catch (_e) {}
  #|     };
  #|     const dispatchFocusFamilyEvent = (target, type, bubbles, relatedTarget) => {
  #|       if (!target || typeof target.dispatchEvent !== "function") return;
  #|       const event = globalThis.__bidiCreateEvent(type, {
  #|         bubbles: !!bubbles,
  #|         cancelable: false,
  #|       });
  #|       event.relatedTarget = relatedTarget || null;
  #|       event.__originalRelatedTarget = relatedTarget || null;
  #|       target.dispatchEvent(event);
  #|     };
  #|     const focusNode = (node) => {
  #|       const doc = node && node.ownerDocument ? node.ownerDocument : globalThis.document;
  #|       if (!doc) return;
  #|       const delegatedTarget = findDelegatesFocusTarget(node);
  #|       if (delegatedTarget && delegatedTarget !== node) {
  #|         focusNode(delegatedTarget);
  #|         return;
  #|       }
  #|       const previous = getDeepActiveElement(doc);
  #|       if (previous === node) return;
  #|       if (previous) {
  #|         dispatchFocusFamilyEvent(previous, "blur", false, node);
  #|         dispatchFocusFamilyEvent(previous, "focusout", true, node);
  #|       }
  #|       clearDocumentActiveChain(doc);
  #|       const shadowRoot = getContainingShadowRoot(node);
  #|       if (shadowRoot && shadowRoot.host) {
  #|         shadowRoot.activeElement = node;
  #|         doc.activeElement = shadowRoot.host;
  #|       } else {
  #|         doc.activeElement = node;
  #|       }
  #|       dispatchFocusFamilyEvent(node, "focus", false, previous);
  #|       dispatchFocusFamilyEvent(node, "focusin", true, previous);
  #|     };
  #|     const blurNode = (node) => {
  #|       const doc = node && node.ownerDocument ? node.ownerDocument : globalThis.document;
  #|       if (!doc) return;
  #|       let target = node;
  #|       const ownShadowRoot = node && node.shadowRoot ? node.shadowRoot : null;
  #|       if (ownShadowRoot && ownShadowRoot.activeElement) {
  #|         target = ownShadowRoot.activeElement;
  #|       }
  #|       const active = getDeepActiveElement(doc);
  #|       if (active && active !== target && active !== node) return;
  #|       const shadowRoot = getContainingShadowRoot(target);
  #|       dispatchFocusFamilyEvent(target, "blur", false, null);
  #|       dispatchFocusFamilyEvent(target, "focusout", true, null);
  #|       if (shadowRoot && shadowRoot.activeElement === target) {
  #|         shadowRoot.activeElement = null;
  #|         if (doc.activeElement === shadowRoot.host) {
  #|           doc.activeElement = doc.body || null;
  #|         }
  #|       }
  #|       if (doc.activeElement === target || doc.activeElement === node) {
  #|         doc.activeElement = doc.body || null;
  #|       }
  #|     };
  #|
  #|     // Minimal Mock DOM for Preact compatibility
  #|     const createMockElement = (tagName) => {
  #|       const lowerTag = String(tagName || "").toLowerCase();
  #|       const defaultNamespace =
  #|         lowerTag === "svg"
  #|           ? "http://www.w3.org/2000/svg"
  #|           : "http://www.w3.org/1999/xhtml";
  #|       const el = {
  #|         tagName: tagName.toUpperCase(),
  #|         nodeName: tagName.toUpperCase(),
  #|         nodeType: 1,
  #|         namespaceURI: defaultNamespace,
  #|         _attrs: {},
  #|         _attrNamespaces: {},
  #|         _children: [],
  #|         _parent: null,
  #|         _textContent: '',
  #|         _listeners: {},
  #|         _style: {},
  #|         shadowRoot: null,
  #|         ownerDocument: null, // Set after document is created
  #|         get localName() { return this.tagName.toLowerCase(); },
  #|         get parentNode() { return this._parent; },
  #|         get parentElement() { return this._parent; },
  #|         get childNodes() { return this._children; },
  #|         get children() { return this._children.filter(c => c.nodeType === 1); },
  #|         get firstChild() { return this._children[0] || null; },
  #|         get lastChild() { return this._children[this._children.length - 1] || null; },
  #|         get nextSibling() {
  #|           if (!this._parent) return null;
  #|           const idx = this._parent._children.indexOf(this);
  #|           return this._parent._children[idx + 1] || null;
  #|         },
  #|         get previousSibling() {
  #|           if (!this._parent) return null;
  #|           const idx = this._parent._children.indexOf(this);
  #|           return this._parent._children[idx - 1] || null;
  #|         },
  #|         get nextElementSibling() {
  #|           let sibling = this.nextSibling;
  #|           while (sibling && sibling.nodeType !== 1) sibling = sibling.nextSibling;
  #|           return sibling || null;
  #|         },
  #|         get previousElementSibling() {
  #|           let sibling = this.previousSibling;
  #|           while (sibling && sibling.nodeType !== 1) sibling = sibling.previousSibling;
  #|           return sibling || null;
  #|         },
  #|         matches(sel) { return matchesSelector(this, String(sel)); },
  #|         webkitMatchesSelector(sel) { return this.matches(sel); },
  #|         closest(sel) {
  #|           let node = this;
  #|           while (node) {
  #|             if (node.nodeType === 1 && matchesSelector(node, String(sel))) return node;
  #|             node = node._parent || node.parentElement || node.parentNode || null;
  #|           }
  #|           return null;
  #|         },
  #|         get textContent() {
  #|           if (this.nodeType === 3) return this._textContent;
  #|           return this._children.map(c => c.textContent).join('');
  #|         },
  #|         set textContent(v) {
  #|           this._children = [];
  #|           if (v) {
  #|             const text = createMockTextNode(v);
  #|             text._parent = this;
  #|             this._children.push(text);
  #|           }
  #|         },
  #|         get innerHTML() {
  #|           return this._children.map(c => {
  #|             if (c.nodeType === 3) return c._textContent;
  #|             let html = '<' + c.tagName.toLowerCase();
  #|             for (const [k, v] of Object.entries(c._attrs)) {
  #|               html += ' ' + k + '="' + v + '"';
  #|             }
  #|             html += '>' + c.innerHTML + '';
  #|             return html;
  #|           }).join('');
  #|         },
  #|         set innerHTML(v) {
  #|           this._children = [];
  #|           if (!v) return;
  #|           const nodes = parseHTMLFragment(
  #|             String(v),
  #|             this.ownerDocument || globalThis.document || null,
  #|           );
  #|           if (nodes.length === 0) {
  #|             const text = createMockTextNode(v);
  #|             text._parent = this;
  #|             text.ownerDocument = this.ownerDocument || null;
  #|             this._children.push(text);
  #|             return;
  #|           }
  #|           for (const node of nodes) {
  #|             node._parent = this;
  #|             node.ownerDocument = this.ownerDocument || node.ownerDocument || null;
  #|             this._children.push(node);
  #|           }
  #|         },
  #|         get id() { return this._attrs.id || ''; },
  #|         set id(v) { this._attrs.id = v; },
  #|         get className() { return this._attrs.class || ''; },
  #|         set className(v) { this._attrs.class = v; },
  #|         get slot() { return this._attrs.slot || ''; },
  #|         set slot(v) {
  #|           const next = String(v || '');
  #|           if (next === '') delete this._attrs.slot;
  #|           else this._attrs.slot = next;
  #|         },
  #|         get classList() {
  #|           const self = this;
  #|           return {
  #|             _getClasses() { return (self._attrs.class || '').split(/\s+/).filter(Boolean); },
  #|             add(...cls) { const c = new Set(this._getClasses()); cls.forEach(x => c.add(x)); self._attrs.class = [...c].join(' '); },
  #|             remove(...cls) { const c = new Set(this._getClasses()); cls.forEach(x => c.delete(x)); self._attrs.class = [...c].join(' '); },
  #|             toggle(cls, force) { if (force === undefined) force = !this.contains(cls); if (force) this.add(cls); else this.remove(cls); return force; },
  #|             contains(cls) { return this._getClasses().includes(cls); },
  #|             [Symbol.iterator]() { return this._getClasses()[Symbol.iterator](); }
  #|           };
  #|         },
  #|         get style() {
  #|           const self = this;
  #|           return new Proxy(self._style, {
  #|             get(t, p) { return t[p] || ''; },
  #|             set(t, p, v) { t[p] = v; return true; }
  #|           });
  #|         },
  #|         get value() { return this._attrs.value || ''; },
  #|         set value(v) { this._attrs.value = v; },
  #|         get checked() { return !!this._attrs.checked; },
  #|         set checked(v) { this._attrs.checked = v; },
  #|         get type() { return this._attrs.type || ''; },
  #|         set type(v) { this._attrs.type = v; },
  #|         get hidden() { return 'hidden' in this._attrs; },
  #|         set hidden(v) { if (v) this._attrs.hidden = ''; else delete this._attrs.hidden; },
  #|         get clientWidth() {
  #|           if (this.tagName === "HTML" || this.tagName === "BODY") {
  #|             return Number(
  #|               (globalThis.window && globalThis.window.innerWidth) ||
  #|               globalThis.innerWidth ||
  #|               1024,
  #|             );
  #|           }
  #|           const rect = this.getBoundingClientRect ? this.getBoundingClientRect() : null;
  #|           return Number(rect && rect.width ? rect.width : 0);
  #|         },
  #|         get clientHeight() {
  #|           if (this.tagName === "HTML" || this.tagName === "BODY") {
  #|             return Number(
  #|               (globalThis.window && globalThis.window.innerHeight) ||
  #|               globalThis.innerHeight ||
  #|               768,
  #|             );
  #|           }
  #|           const rect = this.getBoundingClientRect ? this.getBoundingClientRect() : null;
  #|           return Number(rect && rect.height ? rect.height : 0);
  #|         },
  #|         get scrollWidth() {
  #|           let maxWidth = Number(this.clientWidth || 0);
  #|           if (Array.isArray(this._children)) {
  #|             for (const child of this._children) {
  #|               if (!child || typeof child.getBoundingClientRect !== "function") continue;
  #|               const rect = child.getBoundingClientRect();
  #|               const right = Number(rect && rect.right ? rect.right : rect && rect.width ? rect.width : 0);
  #|               if (right > maxWidth) maxWidth = right;
  #|             }
  #|           }
  #|           return maxWidth;
  #|         },
  #|         get scrollHeight() {
  #|           let maxHeight = Number(this.clientHeight || 0);
  #|           if (Array.isArray(this._children)) {
  #|             for (const child of this._children) {
  #|               if (!child || typeof child.getBoundingClientRect !== "function") continue;
  #|               const rect = child.getBoundingClientRect();
  #|               const bottom = Number(rect && rect.bottom ? rect.bottom : rect && rect.height ? rect.height : 0);
  #|               if (bottom > maxHeight) maxHeight = bottom;
  #|             }
  #|           }
  #|           return maxHeight;
  #|         },
  #|         get attributes() {
  #|           const attrs = Object.entries(this._attrs).map(([name, value]) => ({
  #|             localName: String(name).includes(":") ? String(name).split(":").pop() : String(name),
  #|             namespaceURI:
  #|               this._attrNamespaces?.[name] ??
  #|               (String(name).startsWith("svg:") ? "http://www.w3.org/2000/svg" : null),
  #|             nodeType: 2,
  #|             nodeName: String(name),
  #|             name: String(name),
  #|             value: String(value),
  #|             nodeValue: String(value),
  #|             ownerElement: this,
  #|             ownerDocument: this.ownerDocument,
  #|             parentNode: null,
  #|             cloneNode() {
  #|               return {
  #|                 nodeType: 2,
  #|                 nodeName: this.nodeName,
  #|                 name: this.name,
  #|                 value: this.value,
  #|                 nodeValue: this.nodeValue,
  #|                 ownerElement: this.ownerElement,
  #|                 ownerDocument: this.ownerDocument,
  #|                 parentNode: null
  #|               };
  #|             }
  #|           }));
  #|           return toCollection(attrs, "namednodemap");
  #|         },
  #|         get dataset() {
  #|           const self = this;
  #|           // Convert data-foo-bar to fooBar
  #|           const toCamelCase = (name) => name.replace(/^data-/, '').replace(/-([a-z])/g, (_, c) => c.toUpperCase());
  #|           // Convert fooBar to data-foo-bar
  #|           const toDataAttr = (name) => 'data-' + name.replace(/([A-Z])/g, '-$1').toLowerCase();
  #|           return new Proxy({}, {
  #|             get(_, prop) {
  #|               if (typeof prop !== 'string') return undefined;
  #|               const attrName = toDataAttr(prop);
  #|               return self._attrs[attrName];
  #|             },
  #|             set(_, prop, value) {
  #|               if (typeof prop !== 'string') return false;
  #|               const attrName = toDataAttr(prop);
  #|               self._attrs[attrName] = String(value);
  #|               return true;
  #|             },
  #|             has(_, prop) {
  #|               if (typeof prop !== 'string') return false;
  #|               const attrName = toDataAttr(prop);
  #|               return attrName in self._attrs;
  #|             },
  #|             deleteProperty(_, prop) {
  #|               if (typeof prop !== 'string') return false;
  #|               const attrName = toDataAttr(prop);
  #|               delete self._attrs[attrName];
  #|               return true;
  #|             },
  #|             ownKeys(_) {
  #|               return Object.keys(self._attrs)
  #|                 .filter(k => k.startsWith('data-'))
  #|                 .map(k => toCamelCase(k));
  #|             },
  #|             getOwnPropertyDescriptor(_, prop) {
  #|               if (typeof prop !== 'string') return undefined;
  #|               const attrName = toDataAttr(prop);
  #|               if (attrName in self._attrs) {
  #|                 return { value: self._attrs[attrName], writable: true, enumerable: true, configurable: true };
  #|               }
  #|               return undefined;
  #|             }
  #|           });
  #|         },
  #|         setAttribute(name, value) {
  #|           const oldValue = this._attrs[name];
  #|           this._attrs[name] = String(value);
  #|           this._attrNamespaces[name] = null;
  #|           if (typeof name === "string" && name.toLowerCase().startsWith("on")) {
  #|             try {
  #|               this[name.toLowerCase()] = Function("event", String(value));
  #|             } catch (_e) {
  #|               this[name.toLowerCase()] = function() { return undefined; };
  #|             }
  #|           }
  #|           // Parse style attribute into _style object
  #|           if (name === 'style') {
  #|             this._style = {};
  #|             String(value).split(';').forEach(part => {
  #|               const [prop, val] = part.split(':').map(s => s.trim());
  #|               if (prop && val) {
  #|                 // Convert kebab-case to camelCase
  #|                 const camelProp = prop.replace(/-([a-z])/g, (_, c) => c.toUpperCase());
  #|                 this._style[camelProp] = val;
  #|                 this._style[prop] = val; // Also store original kebab-case
  #|               }
  #|             });
  #|           }
  #|           notifyMutation(createMutationRecord('attributes', this, { attributeName: name, oldValue }));
  #|         },
  #|         setAttributeNS(namespace, name, value) {
  #|           const attrName = String(name);
  #|           const oldValue = this._attrs[attrName];
  #|           this._attrs[attrName] = String(value);
  #|           this._attrNamespaces[attrName] = namespace ?? null;
  #|           notifyMutation(
  #|             createMutationRecord('attributes', this, {
  #|               attributeName: attrName,
  #|               oldValue,
  #|             }),
  #|           );
  #|         },
  #|         getAttribute(name) { return this._attrs[name] ?? null; },
  #|         removeAttribute(name) {
  #|           const oldValue = this._attrs[name];
  #|           delete this._attrs[name];
  #|           delete this._attrNamespaces[name];
  #|           if (typeof name === "string" && name.toLowerCase().startsWith("on")) {
  #|             delete this[name.toLowerCase()];
  #|           }
  #|           notifyMutation(createMutationRecord('attributes', this, { attributeName: name, oldValue }));
  #|         },
  #|         hasAttribute(name) { return name in this._attrs; },
  #|         appendChild(child) {
  #|           if (child._parent) child._parent.removeChild(child);
  #|           const prevSibling = this._children[this._children.length - 1] || null;
  #|           child._parent = this;
  #|           child.ownerDocument = this.ownerDocument;
  #|           this._children.push(child);
  #|           notifyMutation(createMutationRecord('childList', this, { addedNodes: [child], previousSibling: prevSibling }));
  #|           try {
  #|             const childTag = String(child && child.tagName ? child.tagName : "").toUpperCase();
  #|             const parentTag = String(this && this.tagName ? this.tagName : "").toUpperCase();
  #|             if (
  #|               !globalThis.__suppressScriptAppendExecution &&
  #|               childTag === "SCRIPT" &&
  #|               (parentTag === "BODY" || parentTag === "HEAD" || parentTag === "HTML")
  #|             ) {
  #|               const code = String(child.textContent || "");
  #|               if (code.trim() !== "") {
  #|                 try {
  #|                   (0, eval)(code);
  #|                 } catch (scriptError) {
  #|                   const pushError = globalThis.__bidiPushJavascriptErrorEntry;
  #|                   if (typeof pushError === "function") {
  #|                     pushError(scriptError);
  #|                   }
  #|                 }
  #|               }
  #|             }
  #|           } catch (_e) {}
  #|           return child;
  #|         },
  #|         append(...nodes) {
  #|           for (const node of nodes) {
  #|             if (node === null || node === undefined) continue;
  #|             if (
  #|               typeof node === "string" ||
  #|               typeof node === "number" ||
  #|               typeof node === "boolean" ||
  #|               typeof node === "bigint"
  #|             ) {
  #|               this.appendChild(createMockTextNode(String(node)));
  #|               continue;
  #|             }
  #|             if (node.nodeType === 11 && Array.isArray(node._children)) {
  #|               const fragmentChildren = Array.from(node._children);
  #|               for (const fragmentChild of fragmentChildren) {
  #|                 this.appendChild(fragmentChild);
  #|               }
  #|               node._children = [];
  #|               continue;
  #|             }
  #|             this.appendChild(node);
  #|           }
  #|         },
  #|         insertBefore(newChild, refChild) {
  #|           if (newChild._parent) newChild._parent.removeChild(newChild);
  #|           newChild._parent = this;
  #|           newChild.ownerDocument = this.ownerDocument;
  #|           const idx = refChild ? this._children.indexOf(refChild) : this._children.length;
  #|           const prevSibling = idx > 0 ? this._children[idx - 1] : null;
  #|           if (idx === -1) this._children.push(newChild);
  #|           else this._children.splice(idx, 0, newChild);
  #|           notifyMutation(createMutationRecord('childList', this, { addedNodes: [newChild], previousSibling: prevSibling, nextSibling: refChild }));
  #|           return newChild;
  #|         },
  #|         removeChild(child) {
  #|           const idx = this._children.indexOf(child);
  #|           if (idx !== -1) {
  #|             const prevSibling = idx > 0 ? this._children[idx - 1] : null;
  #|             const nextSibling = this._children[idx + 1] || null;
  #|             this._children.splice(idx, 1);
  #|             child._parent = null;
  #|             notifyMutation(createMutationRecord('childList', this, { removedNodes: [child], previousSibling: prevSibling, nextSibling }));
  #|           }
  #|           return child;
  #|         },
  #|         replaceChild(newChild, oldChild) {
  #|           const idx = this._children.indexOf(oldChild);
  #|           if (idx !== -1) {
  #|             if (newChild._parent) newChild._parent.removeChild(newChild);
  #|             const prevSibling = idx > 0 ? this._children[idx - 1] : null;
  #|             const nextSibling = this._children[idx + 1] || null;
  #|             newChild._parent = this;
  #|             newChild.ownerDocument = this.ownerDocument;
  #|             this._children[idx] = newChild;
  #|             oldChild._parent = null;
  #|             notifyMutation(createMutationRecord('childList', this, { addedNodes: [newChild], removedNodes: [oldChild], previousSibling: prevSibling, nextSibling }));
  #|           }
  #|           return oldChild;
  #|         },
  #|         cloneNode(deep) {
  #|           const clone = createMockElement(this.tagName);
  #|           clone._attrs = { ...this._attrs };
  #|           clone._attrNamespaces = { ...this._attrNamespaces };
  #|           clone._style = { ...this._style };
  #|           if (deep) {
  #|             for (const child of this._children) {
  #|               clone.appendChild(child.cloneNode(true));
  #|             }
  #|           }
  #|           return clone;
  #|         },
  #|         addEventListener(type, fn) {
  #|           if (!this._listeners[type]) this._listeners[type] = [];
  #|           this._listeners[type].push(fn);
  #|         },
  #|         removeEventListener(type, fn) {
  #|           if (this._listeners[type]) {
  #|             this._listeners[type] = this._listeners[type].filter(f => f !== fn);
  #|           }
  #|         },
  #|         dispatchEvent(event) {
  #|           prepareEventForCurrentTarget(event, this);
  #|           if (event.__retargetSuppressed) return !event.defaultPrevented;
  #|           const listeners = this._listeners[event.type] || [];
  #|           const previousEvent = globalThis.event;
  #|           globalThis.event = event;
  #|           try {
  #|             for (const fn of listeners) {
  #|               try { fn.call(this, event); } catch (_e) {}
  #|             }
  #|             if (event.bubbles) {
  #|               const parent = this._parent || this.parentElement || this.parentNode || null;
  #|               if (parent && parent !== this && typeof parent.dispatchEvent === "function") {
  #|                 parent.dispatchEvent(event);
  #|               } else {
  #|                 if (
  #|                   this.ownerDocument &&
  #|                   this.ownerDocument !== this &&
  #|                   typeof this.ownerDocument.dispatchEvent === "function"
  #|                 ) {
  #|                   this.ownerDocument.dispatchEvent(event);
  #|                 }
  #|                 if (globalThis.window && typeof globalThis.window.dispatchEvent === "function") {
  #|                   globalThis.window.dispatchEvent(event);
  #|                 }
  #|               }
  #|             }
  #|           } finally {
  #|             globalThis.event = previousEvent;
  #|           }
  #|           return !event.defaultPrevented;
  #|         },
  #|         click() {
  #|           this.dispatchEvent(globalThis.__bidiCreateEvent('click', { bubbles: true }));
  #|         },
  #|         focus() {
  #|           focusNode(this);
  #|           try { globalThis.__bidiFocusedElement = this; } catch (_e) {}
  #|         },
  #|         blur() {
  #|           blurNode(this);
  #|           try {
  #|             if (globalThis.__bidiFocusedElement === this) {
  #|               globalThis.__bidiFocusedElement = null;
  #|             }
  #|           } catch (_e) {}
  #|         },
  #|         setSelectionRange(start, end) {
  #|           const value = typeof this.value === "string" ? this.value : "";
  #|           const safeStart = Math.max(0, Math.min(value.length, Number(start)));
  #|           const safeEnd = Math.max(0, Math.min(value.length, Number(end)));
  #|           this.selectionStart = safeStart;
  #|           this.selectionEnd = safeEnd;
  #|         },
  #|         select() {
  #|           const value = typeof this.value === "string" ? this.value : "";
  #|           this.selectionStart = 0;
  #|           this.selectionEnd = value.length;
  #|         },
  #|         attachShadow(opts) {
  #|           if (this.shadowRoot) return this.shadowRoot;
  #|           const root = createMockElement('shadow-root');
  #|           root.nodeType = 11;
  #|           root.nodeName = '#document-fragment';
  #|           root.mode = opts && typeof opts.mode === "string" ? String(opts.mode) : "open";
  #|           root.delegatesFocus = !!(opts && opts.delegatesFocus);
  #|           root._parent = this;
  #|           root._isShadowRoot = true;
  #|           root.host = this;
  #|           root.activeElement = null;
  #|           root.ownerDocument = this.ownerDocument;
  #|           this.shadowRoot = root;
  #|           return root;
  #|         },
  #|         contains(node) {
  #|           if (node === this) return true;
  #|           for (const child of this._children) {
  #|             if (child === node || (child.contains && child.contains(node))) return true;
  #|           }
  #|           return false;
  #|         },
  #|         getBoundingClientRect() {
  #|           const toNumber = (value, fallback = 0) => {
  #|             const num = Number.parseFloat(String(value ?? ""));
  #|             return Number.isFinite(num) ? num : fallback;
  #|           };
  #|           const width = toNumber(this._style?.width ?? this._attrs?.width, 1);
  #|           const height = toNumber(this._style?.height ?? this._attrs?.height, 1);
  #|           let left = toNumber(this._style?.left, 0);
  #|           let top = toNumber(this._style?.top, 0);
  #|           if (this._parent && typeof this._parent.getBoundingClientRect === "function") {
  #|             try {
  #|               const parentRect = this._parent.getBoundingClientRect();
  #|               left += Number(parentRect?.left || 0);
  #|               top += Number(parentRect?.top || 0);
  #|             } catch (_e) {}
  #|           }
  #|           const right = left + width;
  #|           const bottom = top + height;
  #|           return {
  #|             x: left,
  #|             y: top,
  #|             left,
  #|             top,
  #|             right,
  #|             bottom,
  #|             width,
  #|             height,
  #|             toJSON() {
  #|               return {
  #|                 x: this.x,
  #|                 y: this.y,
  #|                 left: this.left,
  #|                 top: this.top,
  #|                 right: this.right,
  #|                 bottom: this.bottom,
  #|                 width: this.width,
  #|                 height: this.height,
  #|               };
  #|             },
  #|           };
  #|         },
  #|         querySelector(sel) { return querySelect(this, sel, false); },
  #|         querySelectorAll(sel) { return querySelect(this, sel, true); },
  #|         getElementsByTagName(tag) {
  #|           const results = [];
  #|           const search = (node) => {
  #|             for (const child of node._children) {
  #|               if (child.nodeType === 1) {
  #|                 if (tag === '*' || child.tagName === tag.toUpperCase()) results.push(child);
  #|                 search(child);
  #|               }
  #|             }
  #|           };
  #|           search(this);
  #|           return toCollection(results, "htmlcollection");
  #|         },
  #|         getElementsByClassName(cls) {
  #|           const results = [];
  #|           const search = (node) => {
  #|             for (const child of node._children) {
  #|               if (child.nodeType === 1) {
  #|                 if (child.classList.contains(cls)) results.push(child);
  #|                 search(child);
  #|               }
  #|             }
  #|           };
  #|           search(this);
  #|           return toCollection(results, "htmlcollection");
  #|         }
  #|       };
  #|       return el;
  #|     };
  #|
  #|     const createMockTextNode = (text) => ({
  #|       nodeType: 3,
  #|       nodeName: '#text',
  #|       _textContent: String(text),
  #|       _parent: null,
  #|       ownerDocument: null,
  #|       get textContent() { return this._textContent; },
  #|       set textContent(v) { this._textContent = String(v); },
  #|       get nodeValue() { return this._textContent; },
  #|       set nodeValue(v) { this._textContent = String(v); },
  #|       get parentNode() { return this._parent; },
  #|       cloneNode() { return createMockTextNode(this._textContent); }
  #|     });
  #|
  #|     const createMockCommentNode = (text) => ({
  #|       nodeType: 8,
  #|       nodeName: '#comment',
  #|       _textContent: String(text),
  #|       _parent: null,
  #|       ownerDocument: null,
  #|       get textContent() { return this._textContent; },
  #|       set textContent(v) { this._textContent = String(v); },
  #|       get nodeValue() { return this._textContent; },
  #|       set nodeValue(v) { this._textContent = String(v); },
  #|       get parentNode() { return this._parent; },
  #|       cloneNode() { return createMockCommentNode(this._textContent); }
  #|     });
  #|
  #|     const createMockCDataNode = (text) => ({
  #|       nodeType: 4,
  #|       nodeName: '#cdata-section',
  #|       _textContent: String(text),
  #|       _parent: null,
  #|       ownerDocument: null,
  #|       get textContent() { return this._textContent; },
  #|       set textContent(v) { this._textContent = String(v); },
  #|       get nodeValue() { return this._textContent; },
  #|       set nodeValue(v) { this._textContent = String(v); },
  #|       get parentNode() { return this._parent; },
  #|       cloneNode() { return createMockCDataNode(this._textContent); }
  #|     });
  #|
  #|     const createMockProcessingInstruction = (target, data) => ({
  #|       nodeType: 7,
  #|       nodeName: String(target),
  #|       target: String(target),
  #|       data: String(data),
  #|       _textContent: String(data),
  #|       _parent: null,
  #|       ownerDocument: null,
  #|       get textContent() { return this._textContent; },
  #|       set textContent(v) { this._textContent = String(v); this.data = String(v); },
  #|       get nodeValue() { return this._textContent; },
  #|       set nodeValue(v) { this._textContent = String(v); this.data = String(v); },
  #|       get parentNode() { return this._parent; },
  #|       cloneNode() { return createMockProcessingInstruction(this.target, this.data); }
  #|     });
  #|
  #|     const parseHTMLFragment = (fragmentHtml, ownerDocument) => {
  #|       const source = String(fragmentHtml || "");
  #|       const root = { _children: [] };
  #|       const stack = [root];
  #|       const voidElements = new Set([
  #|         "area", "base", "br", "col", "embed", "hr", "img", "input",
  #|         "link", "meta", "param", "source", "track", "wbr"
  #|       ]);
  #|       const pushNode = (parent, node) => {
  #|         if (parent && typeof parent.appendChild === "function") {
  #|           parent.appendChild(node);
  #|           return;
  #|         }
  #|         node._parent = null;
  #|         root._children.push(node);
  #|       };
  #|       const tokenRe = /|<\/?[a-zA-Z][^>]*>|[^<]+/g;
  #|       let tokenMatch;
  #|       while ((tokenMatch = tokenRe.exec(source))) {
  #|         const token = tokenMatch[0];
  #|         if (!token) continue;
  #|         if (token.startsWith("', i);
  #|             const text = endIdx >= 0 ? htmlStr.slice(i + 3, endIdx) : "";
  #|             i = endIdx >= 0 ? endIdx + 3 : len;
  #|             return globalThis.document.createComment(text);
  #|           }
  #|
  #|           // CDATA
  #|           if (htmlStr.slice(i, i + 8) === '![CDATA[') {
  #|             const endIdx = htmlStr.indexOf(']]>', i + 8);
  #|             const text = endIdx >= 0 ? htmlStr.slice(i + 8, endIdx) : "";
  #|             i = endIdx >= 0 ? endIdx + 3 : len;
  #|             return globalThis.document.createCDATASection(text);
  #|           }
  #|
  #|           // DOCTYPE
  #|           if (htmlStr[i] === '!' && getLowerHtml().slice(i, i + 8) === '!doctype') {
  #|             while (i < len && htmlStr[i] !== '>') i++;
  #|             i++; // skip >
  #|             return null;
  #|           }
  #|
  #|           // Closing tag
  #|           if (htmlStr[i] === '/') {
  #|             i++; // skip /
  #|             const tagName = parseTagName();
  #|             while (i < len && htmlStr[i] !== '>') i++;
  #|             i++; // skip >
  #|             return { type: 'close', tagName };
  #|           }
  #|
  #|           const tagName = parseTagName();
  #|           if (!tagName) return null;
  #|
  #|           const attrs = parseAttributes();
  #|
  #|           // Self-closing or void
  #|           const selfClosing = htmlStr[i] === '/';
  #|           if (selfClosing) i++;
  #|           if (htmlStr[i] === '>') i++;
  #|
  #|           const el = globalThis.document.createElement(tagName);
  #|           for (const [k, v] of Object.entries(attrs)) {
  #|             el.setAttribute(k, v);
  #|           }
  #|
  #|           if (selfClosing || voidElements.has(tagName)) {
  #|             return el;
  #|           }
  #|
  #|           // Parse children for script/style (raw text)
  #|           if (tagName === 'script' || tagName === 'style') {
  #|             const endTag = '= 0) {
  #|               const content = htmlStr.slice(i, endIdx);
  #|               if (content.trim()) {
  #|                 el.appendChild(globalThis.document.createTextNode(content));
  #|               }
  #|               i = endIdx + endTag.length;
  #|               while (i < len && htmlStr[i] !== '>') i++;
  #|               i++; // skip >
  #|             }
  #|             return el;
  #|           }
  #|
  #|           // Parse children
  #|           while (i < len) {
  #|             if (i >= len) break;
  #|
  #|             // Check for closing tag
  #|             if (htmlStr[i] === '<' && htmlStr[i + 1] === '/') {
  #|               const saved = i;
  #|               i += 2;
  #|               const closeName = parseTagName();
  #|               if (closeName === tagName) {
  #|                 while (i < len && htmlStr[i] !== '>') i++;
  #|                 i++; // skip >
  #|                 break;
  #|               } else {
  #|                 i = saved; // restore and break (mismatched tag)
  #|                 break;
  #|               }
  #|             }
  #|
  #|             if (htmlStr[i] === '<') {
  #|               const child = parseElement();
  #|               if (child && child.nodeType) {
  #|                 el.appendChild(child);
  #|               }
  #|             } else {
  #|               // Text node
  #|               let text = '';
  #|               while (i < len && htmlStr[i] !== '<') {
  #|                 text += htmlStr[i++];
  #|               }
  #|               if (text.trim()) {
  #|                 el.appendChild(globalThis.document.createTextNode(text));
  #|               }
  #|             }
  #|           }
  #|
  #|           return el;
  #|         };
  #|
  #|         // Parse all top-level elements
  #|         while (i < len) {
  #|           skipWhitespace();
  #|           if (i >= len) break;
  #|
  #|           if (htmlStr[i] === '<') {
  #|             const el = parseElement();
  #|             if (el && el.nodeType) {
  #|               nodes.push(el);
  #|             }
  #|           } else {
  #|             // Skip text at top level
  #|             while (i < len && htmlStr[i] !== '<') i++;
  #|           }
  #|         }
  #|
  #|         return nodes;
  #|       };
  #|
  #|       // Parse and build DOM. Parser-created script nodes must not execute
  #|       // through appendChild; callers decide when document scripts run.
  #|       const previousSuppressScriptAppendExecution = globalThis.__suppressScriptAppendExecution;
  #|       globalThis.__suppressScriptAppendExecution = true;
  #|       let parsed;
  #|       try {
  #|         parsed = parseHTML(html);
  #|       } finally {
  #|         globalThis.__suppressScriptAppendExecution = previousSuppressScriptAppendExecution;
  #|       }
  #|
  #|       // Find html, head, body elements
  #|       let htmlEl = null, headEl = null, bodyEl = null;
  #|       for (const node of parsed) {
  #|         if (node.tagName === 'HTML') htmlEl = node;
  #|         else if (node.tagName === 'HEAD') headEl = node;
  #|         else if (node.tagName === 'BODY') bodyEl = node;
  #|       }
  #|
  #|       // If we have an html element, extract head and body from it
  #|       if (htmlEl) {
  #|         // Copy  attributes to document.documentElement
  #|         const docEl = globalThis.document.documentElement;
  #|         if (docEl && htmlEl._attrs) {
  #|           for (const [k, v] of Object.entries(htmlEl._attrs)) {
  #|             if (typeof docEl.setAttribute === 'function') docEl.setAttribute(k, v);
  #|             else docEl._attrs[k] = v;
  #|           }
  #|         }
  #|         for (const child of Array.from(htmlEl.childNodes)) {
  #|           if (child.tagName === 'HEAD') headEl = child;
  #|           else if (child.tagName === 'BODY') bodyEl = child;
  #|         }
  #|       }
  #|
  #|       const headCache = [];
  #|       const bodyCache = [];
  #|       // Move head children to document.head
  #|       if (headEl) {
  #|         const headChildren = Array.from(headEl.childNodes);
  #|         for (const child of headChildren) {
  #|           const cloned = cloneNodeFast(child);
  #|           if (cloned) headCache.push(cloned);
  #|         }
  #|         attachChildren(head, headChildren);
  #|       }
  #|
  #|       // Move body children to document.body
  #|       if (bodyEl) {
  #|         if (body && typeof body.setAttribute === "function" && bodyEl._attrs) {
  #|           for (const [k, v] of Object.entries(bodyEl._attrs)) {
  #|             body.setAttribute(k, v);
  #|           }
  #|         }
  #|         const bodyChildren = Array.from(bodyEl.childNodes);
  #|         for (const child of bodyChildren) {
  #|           const cloned = cloneNodeFast(child);
  #|           if (cloned) bodyCache.push(cloned);
  #|         }
  #|         attachChildren(body, bodyChildren);
  #|       } else {
  #|         // No body found, append all parsed nodes
  #|         const bodyChildren = [];
  #|         for (const node of parsed) {
  #|           if (node.tagName !== 'HTML' && node.tagName !== 'HEAD') {
  #|             bodyChildren.push(node);
  #|             const cloned = cloneNodeFast(node);
  #|             if (cloned) bodyCache.push(cloned);
  #|           }
  #|         }
  #|         attachChildren(body, bodyChildren);
  #|       }
  #|       // Ensure  attributes are on documentElement (parser may miss for large HTML)
  #|       const docEl = globalThis.document.documentElement;
  #|       if (docEl && (!docEl._attrs || !docEl._attrs.class)) {
  #|         const htmlMatch = html.match(/]*)>/i);
  #|         if (htmlMatch) {
  #|           const attrStr = htmlMatch[1];
  #|           const attrRegex = /([a-z][a-z0-9-]*)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|(\S+)))?/gi;
  #|           let m;
  #|           while ((m = attrRegex.exec(attrStr)) !== null) {
  #|             const name = m[1].toLowerCase();
  #|             const value = m[2] || m[3] || m[4] || name;
  #|             if (typeof docEl.setAttribute === 'function') docEl.setAttribute(name, value);
  #|             else if (docEl._attrs) docEl._attrs[name] = value;
  #|           }
  #|         }
  #|       }
  #|       globalThis.__lastHTML = html;
  #|       globalThis.__lastParsed = { headNodes: headCache, bodyNodes: bodyCache };
  #|
  #|       return true;
  #|     };
  #|
  #|     // Get current page URL
  #|     globalThis.__getPageUrl = function() {
  #|       return globalThis.__pageUrl || 'about:blank';
  #|     };
  #|
  #|     // Helper to resolve URL
  #|     const resolveUrl = (src, baseUrl) => {
  #|       return globalThis.__resolveUrl ? globalThis.__resolveUrl(src, baseUrl) : src;
  #|     };
  #|
  #|     // Execute all script tags in the document
  #|     globalThis.__executeScripts = async function(options) {
  #|       options = options || {};
  #|       const baseUrl = options.baseUrl || globalThis.__pageUrl || '';
  #|       const scripts = Array.from(globalThis.document.querySelectorAll('script'));
  #|       const results = [];
  #|
  #|       for (const script of scripts) {
  #|         const src = script.getAttribute('src');
  #|         const type = script.getAttribute('type') || 'text/javascript';
  #|
  #|         // Skip non-JavaScript types (like application/json)
  #|         if (type && !type.includes('javascript') && type !== 'module') {
  #|           results.push({ skipped: true, type, reason: 'non-js type' });
  #|           continue;
  #|         }
  #|
  #|         try {
  #|           if (type === 'module') {
  #|             // ES Module handling
  #|             if (src) {
  #|               // External module - use dynamic import
  #|               const fullUrl = resolveUrl(src, baseUrl);
  #|               try {
  #|                 const sourceOrigin = getOrigin(baseUrl || globalThis.__pageUrl || '');
  #|                 const targetOrigin = getOrigin(fullUrl);
  #|                 if (!sandboxAllows(targetOrigin, sourceOrigin)) {
  #|                   throw new Error('Blocked by request sandbox');
  #|                 }
  #|                 if (sourceOrigin && targetOrigin && sourceOrigin !== targetOrigin) {
  #|                   await globalThis.fetch(fullUrl, { mode: 'cors' });
  #|                 }
  #|                 await import(fullUrl);
  #|                 results.push({ executed: true, module: true, src: fullUrl });
  #|               } catch (e) {
  #|                 results.push({ error: true, module: true, src: fullUrl, message: String(e) });
  #|               }
  #|             } else {
  #|               // Inline module - convert to data URL and import
  #|               const code = script.textContent;
  #|               if (code && code.trim()) {
  #|                 try {
  #|                   // Create a data URL for the module
  #|                   const dataUrl = 'data:text/javascript;base64,' + btoa(unescape(encodeURIComponent(code)));
  #|                   await import(dataUrl);
  #|                   results.push({ executed: true, module: true, inline: true, length: code.length });
  #|                 } catch (e) {
  #|                   results.push({ error: true, module: true, inline: true, message: String(e) });
  #|                 }
  #|               }
  #|             }
  #|           } else if (src) {
  #|             // External classic script - fetch and execute
  #|             const fullUrl = resolveUrl(src, baseUrl);
  #|             const fetchFn = globalThis.__craterUseObservableFetch
  #|               ? (globalThis.__craterObservableFetch || globalThis.__fetchInternal || globalThis.fetch)
  #|               : (globalThis.__fetchInternal || globalThis.fetch);
  #|             const response = await fetchFn(fullUrl, { mode: 'no-cors' });
  #|             if (response.ok) {
  #|               const code = await response.text();
  #|               (0, eval)(code);
  #|               results.push({ executed: true, src: fullUrl });
  #|             } else {
  #|               results.push({ error: true, src: fullUrl, status: response.status });
  #|             }
  #|           } else {
  #|             // Inline classic script
  #|             const code = script.textContent;
  #|             if (code && code.trim()) {
  #|               (0, eval)(code);
  #|               results.push({ executed: true, inline: true, length: code.length });
  #|             }
  #|           }
  #|         } catch (e) {
  #|           results.push({ error: true, message: String(e), src: src || 'inline' });
  #|         }
  #|       }
  #|
  #|       return results;
  #|     };
  #|
  #|     // Load page and execute scripts
  #|     globalThis.__loadPageWithScripts = async function(url, options) {
  #|       options = options || {};
  #|       const loadResult = await globalThis.__loadPage(url);
  #|
  #|       // Execute scripts if requested (default: true)
  #|       if (options.executeScripts !== false) {
  #|         const scriptResults = await globalThis.__executeScripts({ baseUrl: url });
  #|         loadResult.scripts = scriptResults;
  #|       }
  #|
  #|       return loadResult;
  #|     };
  #|   }
  #|
  #|   applyUserActivation(userActivation);
  #|   const currentCtx = String(globalThis.__bidiCurrentContext || "default-context");
  #|   if (!globalThis.__bidiContextWindows) globalThis.__bidiContextWindows = new Map();
  #|   if (!globalThis.__bidiContextWindows.has(currentCtx)) {
  #|     const win = {};
  #|     win.__bidiContextId = currentCtx;
  #|     win.window = win;
  #|     const baseNavigator = globalThis.navigator && typeof globalThis.navigator === 'object'
  #|       ? globalThis.navigator
  #|       : {
  #|           userAgent: 'Crater/1.0 (MoonBit; BiDi)',
  #|           platform: 'Crater',
  #|           language: 'en-US',
  #|           languages: ['en-US', 'en'],
  #|           onLine: true,
  #|           cookieEnabled: false,
  #|           userActivation: {
  #|             isActive: false,
  #|             hasBeenActive: false,
  #|           },
  #|         };
  #|     win.navigator = {
  #|       userAgent: String(baseNavigator.userAgent ?? 'Crater/1.0 (MoonBit; BiDi)'),
  #|       platform: String(baseNavigator.platform ?? 'Crater'),
  #|       language: String(baseNavigator.language ?? 'en-US'),
  #|       languages: Array.isArray(baseNavigator.languages)
  #|         ? Array.from(baseNavigator.languages)
  #|         : ['en-US', 'en'],
  #|       onLine: baseNavigator.onLine !== false,
  #|       cookieEnabled: Boolean(baseNavigator.cookieEnabled ?? false),
  #|       userActivation: baseNavigator.userActivation && typeof baseNavigator.userActivation === 'object'
  #|         ? { ...baseNavigator.userActivation }
  #|         : { isActive: false, hasBeenActive: false },
  #|     };
  #|     win.innerWidth = Number(globalThis.innerWidth || 1024);
  #|     win.innerHeight = Number(globalThis.innerHeight || 768);
  #|     win.outerWidth = Number(globalThis.outerWidth || win.innerWidth);
  #|     win.outerHeight = Number(globalThis.outerHeight || win.innerHeight);
  #|     win.devicePixelRatio = Number(globalThis.devicePixelRatio || 1);
  #|     win.pageXOffset = 0;
  #|     win.pageYOffset = 0;
  #|     win._listeners = {};
  #|     win.addEventListener = function(type, fn) {
  #|       if (!this._listeners[type]) this._listeners[type] = [];
  #|       this._listeners[type].push(fn);
  #|     };
  #|     win.removeEventListener = function(type, fn) {
  #|       if (!this._listeners[type]) return;
  #|       this._listeners[type] = this._listeners[type].filter((f) => f !== fn);
  #|     };
  #|     win.dispatchEvent = function(event) {
  #|       prepareEventForCurrentTarget(event, this);
  #|       if (event.__retargetSuppressed) return !event.defaultPrevented;
  #|       try { event.currentTarget = this; } catch (_e) {}
  #|       const listeners = this._listeners[event.type] || [];
  #|       for (const fn of listeners) {
  #|         try { fn.call(this, event); } catch (_e) {}
  #|       }
  #|       return !event.defaultPrevented;
  #|     };
  #|     globalThis.__bidiContextWindows.set(currentCtx, win);
  #|   }
  #|   const contextWindow = globalThis.__bidiContextWindows.get(currentCtx);
  #|   if (!contextWindow.window) contextWindow.window = contextWindow;
  #|   const frameWindows = Array.isArray(contextWindow.frames) ? contextWindow.frames : [];
  #|   globalThis.window = contextWindow;
  #|   globalThis.frames = frameWindows;
  #|   if (contextWindow.navigator && typeof contextWindow.navigator === 'object') {
  #|     globalThis.navigator = contextWindow.navigator;
  #|   } else if (globalThis.navigator && typeof globalThis.navigator === 'object') {
  #|     contextWindow.navigator = globalThis.navigator;
  #|   }
  #|   if (contextWindow.document && typeof contextWindow.document === "object") {
  #|     globalThis.document = contextWindow.document;
  #|   } else if (globalThis.document && typeof globalThis.document === "object") {
  #|     contextWindow.document = globalThis.document;
  #|   }
  #|   if (contextWindow.location && typeof contextWindow.location === "object") {
  #|     globalThis.location = contextWindow.location;
  #|     try { globalThis.__pageUrl = String(contextWindow.location.href || "about:blank"); } catch (_e) {}
  #|   } else {
  #|     const locationHref = "about:blank";
  #|     contextWindow.location = {
  #|       href: locationHref,
  #|       origin: '',
  #|       protocol: 'about:',
  #|       host: '',
  #|       hostname: '',
  #|       port: '',
  #|       pathname: 'blank',
  #|       search: '',
  #|       hash: '',
  #|       assign: function(url) { const next = String(url); globalThis.__pageUrl = next; this.href = next; },
  #|       replace: function(url) { const next = String(url); globalThis.__pageUrl = next; this.href = next; },
  #|       reload: function() {}
  #|     };
  #|     globalThis.location = contextWindow.location;
  #|     globalThis.__pageUrl = locationHref;
  #|   }
  #|   if (!globalThis.__bidiProxyInstances) globalThis.__bidiProxyInstances = new WeakSet();
  #|   if (!globalThis.__bidiNativeProxy && typeof globalThis.Proxy === "function") {
  #|     const NativeProxy = globalThis.Proxy;
  #|     const tracked = globalThis.__bidiProxyInstances;
  #|     function TrackedProxy(target, handler) {
  #|       const proxied = new NativeProxy(target, handler);
  #|       tracked.add(proxied);
  #|       return proxied;
  #|     }
  #|     TrackedProxy.revocable = function(target, handler) {
  #|       const revocable = NativeProxy.revocable(target, handler);
  #|       tracked.add(revocable.proxy);
  #|       return revocable;
  #|     };
  #|     globalThis.__bidiNativeProxy = NativeProxy;
  #|     globalThis.Proxy = TrackedProxy;
  #|   }
  #|
  #|   if (!globalThis.__bidiHandleStore) globalThis.__bidiHandleStore = new Map();
  #|   if (!globalThis.__bidiHandleContextStore) globalThis.__bidiHandleContextStore = new Map();
  #|   if (typeof globalThis.__bidiNextHandleId !== "number") {
  #|     globalThis.__bidiNextHandleId = 1;
  #|   }
  #|   const attachHandle = (value, serialized, includeHandle) => {
  #|     if (!includeHandle) return serialized;
  #|     if (value === null || value === undefined) return serialized;
  #|     const valueType = typeof value;
  #|     if (valueType !== "object" && valueType !== "function" && valueType !== "symbol") return serialized;
  #|     if (!serialized || typeof serialized !== "object" || serialized.handle) return serialized;
  #|     const handle = `handle-${globalThis.__bidiNextHandleId++}`;
  #|     globalThis.__bidiHandleStore.set(handle, value);
  #|     globalThis.__bidiHandleContextStore.set(
  #|       handle,
  #|       String(globalThis.__bidiCurrentContext || ""),
  #|     );
  #|     return { ...serialized, handle };
  #|   };
  #|   const toBidiValueFn = (value, includeHandle = false) =>
  #|     attachHandle(value, toBidiValue(value), includeHandle);
  #|
  #|   function getNodeSharedId(node) {
  #|     const sharedIds = globalThis.__bidiNodeSharedIds || (globalThis.__bidiNodeSharedIds = new WeakMap());
  #|     const nodeStore = globalThis.__bidiSharedNodeStore || (globalThis.__bidiSharedNodeStore = new Map());
  #|     if (typeof globalThis.__bidiNextNodeSharedId !== "number") {
  #|       globalThis.__bidiNextNodeSharedId = 1;
  #|     }
  #|     let sharedId = sharedIds.get(node);
  #|     if (!sharedId) {
  #|       sharedId = `node-${globalThis.__bidiNextNodeSharedId++}`;
  #|       sharedIds.set(node, sharedId);
  #|     }
  #|     nodeStore.set(sharedId, node);
  #|     return sharedId;
  #|   }
  #|
  #|   function getNodeAttributes(node) {
  #|     const attrs = {};
  #|     if (!node || typeof node !== "object") return attrs;
  #|     if (node._attrs && typeof node._attrs === "object") {
  #|       for (const [k, v] of Object.entries(node._attrs)) attrs[k] = String(v);
  #|       return attrs;
  #|     }
  #|     if (node.attributes && typeof node.attributes.length === "number") {
  #|       for (const attr of Array.from(node.attributes)) {
  #|         if (attr && typeof attr.name === "string") attrs[attr.name] = String(attr.value ?? "");
  #|       }
  #|     }
  #|     return attrs;
  #|   }
  #|
  #|   function getNodeChildren(node) {
  #|     if (Array.isArray(node?._children)) return node._children;
  #|     if (Array.isArray(node?.childNodes)) return node.childNodes;
  #|     return [];
  #|   }
  #|
  #|   function shouldIncludeDomChildren(depth) {
  #|     if (maxDomDepth === null) return true;
  #|     if (typeof maxDomDepth === "number") return depth < maxDomDepth;
  #|     return false;
  #|   }
  #|
  #|   function getShadowMode(node) {
  #|     if (!node || typeof node !== "object") return "open";
  #|     if (typeof node.mode === "string") return String(node.mode);
  #|     if (typeof node._mode === "string") return String(node._mode);
  #|     return "open";
  #|   }
  #|
  #|   function serializeShadowRootReference(root, depth) {
  #|     const childNodes = getNodeChildren(root);
  #|     const mode = getShadowMode(root);
  #|     const includeTree =
  #|       includeShadowTree === "all" ||
  #|       (includeShadowTree === "open" && mode === "open");
  #|     const value = {
  #|       nodeType: 11,
  #|       childNodeCount: childNodes.length,
  #|     };
  #|     if (includeTree) {
  #|       value.mode = mode;
  #|       if (shouldIncludeDomChildren(depth)) {
  #|         value.children = childNodes.map((child) => toBidiNodeValue(child, depth + 1));
  #|       }
  #|     } else if (!hasMaxDomDepth && !hasMaxObjectDepth && includeShadowTree === "none") {
  #|       // Default (without serialization options) keeps mode for compatibility tests.
  #|       value.mode = mode;
  #|     }
  #|     return {
  #|       type: "node",
  #|       sharedId: getNodeSharedId(root),
  #|       value,
  #|     };
  #|   }
  #|
  #|   function toBidiNodeValue(node, domDepth = 0) {
  #|     const childNodes = getNodeChildren(node);
  #|     const nodeType = typeof node?.nodeType === "number" ? node.nodeType : 1;
  #|     const value = {
  #|       nodeType,
  #|       childNodeCount: childNodes.length,
  #|     };
  #|
  #|     if (nodeType === 1) {
  #|       const localName =
  #|         node.localName ||
  #|         node._tagName ||
  #|         (node.tagName ? String(node.tagName).toLowerCase() : "");
  #|       value.localName = String(localName);
  #|       value.namespaceURI = node.namespaceURI || "http://www.w3.org/1999/xhtml";
  #|       value.attributes = getNodeAttributes(node);
  #|       if (shouldIncludeDomChildren(domDepth)) {
  #|         value.children = childNodes.map((child) => toBidiNodeValue(child, domDepth + 1));
  #|       }
  #|       value.shadowRoot = node.shadowRoot
  #|         ? serializeShadowRootReference(node.shadowRoot, domDepth)
  #|         : null;
  #|     } else if (nodeType === 2) {
  #|       const attrName = String(node.name || node.nodeName || "");
  #|       value.localName = attrName.includes(":") ? attrName.split(":").pop() : attrName;
  #|       value.namespaceURI =
  #|         node.namespaceURI ??
  #|         (attrName.startsWith("svg:") ? "http://www.w3.org/2000/svg" : null);
  #|       value.nodeValue = String(node.nodeValue ?? node.value ?? "");
  #|     } else if (nodeType === 3 || nodeType === 4 || nodeType === 7 || nodeType === 8) {
  #|       value.nodeValue = String(node.nodeValue ?? node.textContent ?? "");
  #|     } else if (nodeType === 9) {
  #|       if (shouldIncludeDomChildren(domDepth)) {
  #|         value.children = childNodes.map((child) => toBidiNodeValue(child, domDepth + 1));
  #|       }
  #|     } else if (nodeType === 11) {
  #|       const isShadowRoot = !!node.host;
  #|       if (isShadowRoot) {
  #|         value.mode = getShadowMode(node);
  #|         const includeShadowChildren =
  #|           shouldIncludeDomChildren(domDepth) &&
  #|           (includeShadowTree === "all" || includeShadowTree === "open");
  #|         if (includeShadowChildren) {
  #|           value.children = childNodes.map((child) => toBidiNodeValue(child, domDepth + 1));
  #|         }
  #|       } else if (shouldIncludeDomChildren(domDepth)) {
  #|         value.children = childNodes.map((child) => toBidiNodeValue(child, domDepth + 1));
  #|       }
  #|     }
  #|
  #|     return {
  #|       type: "node",
  #|       sharedId: getNodeSharedId(node),
  #|       value,
  #|     };
  #|   }
  #|
  #|   const internalIds = new WeakMap();
  #|   const referenceCounts = new WeakMap();
  #|   let nextInternalId = 1;
  #|
  #|   const trackReference = (obj) => {
  #|     const prev = referenceCounts.get(obj) || 0;
  #|     referenceCounts.set(obj, prev + 1);
  #|   };
  #|
  #|   const collectReferences = (value, seen = new WeakSet()) => {
  #|     if (!value || typeof value !== "object") return;
  #|     if (typeof value.nodeType === "number") {
  #|       trackReference(value);
  #|       return;
  #|     }
  #|     if (
  #|       value instanceof Date ||
  #|       value instanceof RegExp ||
  #|       value instanceof Error ||
  #|       value instanceof Promise ||
  #|       value instanceof WeakMap ||
  #|       value instanceof WeakSet ||
  #|       value instanceof ArrayBuffer ||
  #|       ArrayBuffer.isView(value)
  #|     ) {
  #|       return;
  #|     }
  #|     if (globalThis.__bidiProxyInstances && globalThis.__bidiProxyInstances.has(value)) return;
  #|
  #|     const isContainer =
  #|       Array.isArray(value) ||
  #|       value instanceof Map ||
  #|       value instanceof Set ||
  #|       value.constructor === Object;
  #|     if (!isContainer) return;
  #|
  #|     trackReference(value);
  #|     if (seen.has(value)) return;
  #|     seen.add(value);
  #|
  #|     if (Array.isArray(value)) {
  #|       for (const item of value) collectReferences(item, seen);
  #|       return;
  #|     }
  #|     if (value instanceof Map) {
  #|       for (const [k, v] of value) {
  #|         if (typeof k !== "string") collectReferences(k, seen);
  #|         collectReferences(v, seen);
  #|       }
  #|       return;
  #|     }
  #|     if (value instanceof Set) {
  #|       for (const item of value) collectReferences(item, seen);
  #|       return;
  #|     }
  #|     for (const entryValue of Object.values(value)) {
  #|       collectReferences(entryValue, seen);
  #|     }
  #|   };
  #|
  #|   const withInternalId = (originalValue, serialized) => {
  #|     if (!serialized || typeof serialized !== "object") return serialized;
  #|     if (maxObjectDepth !== undefined) return serialized;
  #|     if (!originalValue || (typeof originalValue !== "object" && typeof originalValue !== "function")) {
  #|       return serialized;
  #|     }
  #|     const serializedType = serialized.type;
  #|     if (serializedType !== "array" && serializedType !== "map" && serializedType !== "set" && serializedType !== "object" && serializedType !== "node") {
  #|       return serialized;
  #|     }
  #|     const count = referenceCounts.get(originalValue) || 0;
  #|     if (count <= 1) return serialized;
  #|     let internalId = internalIds.get(originalValue);
  #|     if (!internalId) {
  #|       internalId = `internal-${nextInternalId++}`;
  #|       internalIds.set(originalValue, internalId);
  #|     }
  #|     if (serialized.internalId) return serialized;
  #|     return { ...serialized, internalId };
  #|   };
  #|
  #|   function toBidiValue(value, objectDepth = 0, domDepth = 0) {
  #|     if (value === undefined) return { type: "undefined" };
  #|     if (value === null) return { type: "null" };
  #|
  #|     const type = typeof value;
  #|     if (type === "boolean") return { type: "boolean", value };
  #|     if (type === "number") {
  #|       if (Number.isNaN(value)) return { type: "number", value: "NaN" };
  #|       if (!Number.isFinite(value)) return { type: "number", value: value > 0 ? "Infinity" : "-Infinity" };
  #|       if (Object.is(value, -0)) return { type: "number", value: "-0" };
  #|       return { type: "number", value };
  #|     }
  #|     if (type === "string") return { type: "string", value };
  #|     if (type === "bigint") return { type: "bigint", value: String(value) };
  #|     if (type === "symbol") return { type: "symbol" };
  #|     if (type === "function") return { type: "function" };
  #|
  #|     const limitReached =
  #|       typeof maxObjectDepth === "number" &&
  #|       objectDepth >= maxObjectDepth;
  #|
  #|     const objectTag = type === "object" ? Object.prototype.toString.call(value) : "";
  #|     if (objectTag === "[object Generator]" || objectTag === "[object AsyncGenerator]") {
  #|       return { type: "generator" };
  #|     }
  #|     if (globalThis.__bidiProxyInstances && globalThis.__bidiProxyInstances.has(value)) {
  #|       return { type: "proxy" };
  #|     }
  #|     if (value && type === "object" && typeof value.__bidiContextId === "string") {
  #|       return { type: "window", value: { context: String(value.__bidiContextId) } };
  #|     }
  #|     if (value === globalThis || value === globalThis.window) {
  #|       return {
  #|         type: "window",
  #|         value: { context: String(globalThis.__bidiCurrentContext || "default-context") }
  #|       };
  #|     }
  #|     if (value && type === "object" && typeof value.nodeType === "number") {
  #|       return withInternalId(value, toBidiNodeValue(value, domDepth));
  #|     }
  #|
  #|     if (value instanceof RegExp) {
  #|       return { type: "regexp", value: { pattern: value.source, flags: value.flags } };
  #|     }
  #|     if (value instanceof Date) {
  #|       return { type: "date", value: value.toISOString() };
  #|     }
  #|     if (value instanceof Error) return { type: "error" };
  #|     if (value instanceof Promise) return { type: "promise" };
  #|     if (value instanceof WeakMap) return { type: "weakmap" };
  #|     if (value instanceof WeakSet) return { type: "weakset" };
  #|     if (ArrayBuffer.isView(value)) return { type: "typedarray" };
  #|     if (value instanceof ArrayBuffer) return { type: "arraybuffer" };
  #|
  #|     if (Array.isArray(value) && value.__bidiCollectionType === "htmlcollection") {
  #|       const items = value.map((item) => toBidiValue(item, objectDepth + 1, domDepth));
  #|       return { type: "htmlcollection", value: items };
  #|     }
  #|     if (Array.isArray(value) && value.__bidiCollectionType === "nodelist") {
  #|       const items = value.map((item) => toBidiValue(item, objectDepth + 1, domDepth));
  #|       return { type: "nodelist", value: items };
  #|     }
  #|
  #|     if (value instanceof Map) {
  #|       if (limitReached) return { type: "map" };
  #|       const entries = [];
  #|       for (const [k, v] of value) {
  #|         entries.push([
  #|           typeof k === "string" ? k : toBidiValue(k, objectDepth + 1, domDepth),
  #|           toBidiValue(v, objectDepth + 1, domDepth),
  #|         ]);
  #|       }
  #|       return withInternalId(value, { type: "map", value: entries });
  #|     }
  #|     if (value instanceof Set) {
  #|       if (limitReached) return { type: "set" };
  #|       return withInternalId(
  #|         value,
  #|         { type: "set", value: Array.from(value).map((item) => toBidiValue(item, objectDepth + 1, domDepth)) },
  #|       );
  #|     }
  #|     if (Array.isArray(value)) {
  #|       if (limitReached) return { type: "array" };
  #|       return withInternalId(
  #|         value,
  #|         { type: "array", value: value.map((item) => toBidiValue(item, objectDepth + 1, domDepth)) },
  #|       );
  #|     }
  #|
  #|     if (value && value.constructor === Object) {
  #|       if (limitReached) return { type: "object" };
  #|       const entries = Object.entries(value).map(([k, v]) => [
  #|         k,
  #|         toBidiValue(v, objectDepth + 1, domDepth),
  #|       ]);
  #|       return withInternalId(value, { type: "object", value: entries });
  #|     }
  #|
  #|     return { type: "object" };
  #|   }
  #|
  #|   try {
  #|     let result = (0, eval)(expression);  // Indirect eval for global scope
  #|     if (result instanceof Promise) {
  #|       // Avoid process-level unhandled rejection when awaitPromise=false.
  #|       result.catch(() => {});
  #|     }
  #|     collectReferences(result);
  #|     return JSON.stringify({
  #|       type: "success",
  #|       result: toBidiValueFn(result, !!rootOwnership),
  #|       consoleEntries,
  #|     });
  #|   } catch (e) {
  #|     const stackTrace = buildStackTraceFromStack(e && e.stack ? e.stack : "");
  #|     const topFrame = Array.isArray(stackTrace.callFrames) && stackTrace.callFrames.length > 0
  #|       ? stackTrace.callFrames[0]
  #|       : null;
  #|     return JSON.stringify({
  #|       type: "exception",
  #|       exceptionDetails: {
  #|         columnNumber: topFrame ? Number(topFrame.columnNumber || 0) : 0,
  #|         lineNumber: topFrame ? Number(topFrame.lineNumber || 0) : 0,
  #|         text: String(e),
  #|         exception: toBidiValueFn(e, !!rootOwnership),
  #|         stackTrace
  #|       },
  #|       consoleEntries
  #|     });
  #|   } finally {
  #|     // Restore original console (for sync path)
  #|     // Note: For async path, cleanup is in .finally()
  #|     if (captureConsole && originalConsole) {
  #|       console.log = originalConsole.log;
  #|       console.warn = originalConsole.warn;
  #|       console.error = originalConsole.error;
  #|       console.info = originalConsole.info;
  #|       console.debug = originalConsole.debug;
  #|       console.assert = originalConsole.assert;
  #|       console.table = originalConsole.table;
  #|       console.trace = originalConsole.trace;
  #|       console.time = originalConsole.time;
  #|       console.timeEnd = originalConsole.timeEnd;
  #|     }
  #|   }
  #| }

///|
/// FFI: Evaluate expression and return a fully serialized BiDi response (fast path)
extern "js" fn js_evaluate_expression_fast(
  id : Int,
  expression : String,
  user_activation : Bool,
  realm_id : String,
  ctx_id : String,
) -> String =
  #| (id, expression, userActivation, realmId, ctxId) => {
  #|   const isActive = !!userActivation;
  #|   globalThis.__bidiUserActivation = isActive;
  #|   globalThis.__bidiCurrentContext = ctxId;
  #|   if (!globalThis.__bidiProxyInstances) globalThis.__bidiProxyInstances = new WeakSet();
  #|   if (!globalThis.__bidiNativeProxy && typeof globalThis.Proxy === "function") {
  #|     const NativeProxy = globalThis.Proxy;
  #|     const tracked = globalThis.__bidiProxyInstances;
  #|     function TrackedProxy(target, handler) {
  #|       const proxied = new NativeProxy(target, handler);
  #|       tracked.add(proxied);
  #|       return proxied;
  #|     }
  #|     TrackedProxy.revocable = function(target, handler) {
  #|       const revocable = NativeProxy.revocable(target, handler);
  #|       tracked.add(revocable.proxy);
  #|       return revocable;
  #|     };
  #|     globalThis.__bidiNativeProxy = NativeProxy;
  #|     globalThis.Proxy = TrackedProxy;
  #|   }
  #|   if (!globalThis.navigator) globalThis.navigator = {};
  #|   globalThis.navigator.userActivation = {
  #|     isActive,
  #|     hasBeenActive: isActive
  #|   };
  #|   if (globalThis.document) {
  #|     globalThis.document.execCommand = function(command) {
  #|       const cmd = String(command || '').toLowerCase();
  #|       if (cmd === 'selectall') return true;
  #|       if (cmd === 'copy') return !!globalThis.__bidiUserActivation;
  #|       return false;
  #|     };
  #|   }
  #|
  #|   function getNodeSharedId(node) {
  #|     const sharedIds = globalThis.__bidiNodeSharedIds || (globalThis.__bidiNodeSharedIds = new WeakMap());
  #|     const nodeStore = globalThis.__bidiSharedNodeStore || (globalThis.__bidiSharedNodeStore = new Map());
  #|     if (typeof globalThis.__bidiNextNodeSharedId !== "number") {
  #|       globalThis.__bidiNextNodeSharedId = 1;
  #|     }
  #|     let sharedId = sharedIds.get(node);
  #|     if (!sharedId) {
  #|       sharedId = `node-${globalThis.__bidiNextNodeSharedId++}`;
  #|       sharedIds.set(node, sharedId);
  #|     }
  #|     nodeStore.set(sharedId, node);
  #|     return sharedId;
  #|   }
  #|
  #|   function getNodeAttributes(node) {
  #|     const attrs = {};
  #|     if (!node || typeof node !== "object") return attrs;
  #|     if (node._attrs && typeof node._attrs === "object") {
  #|       for (const [k, v] of Object.entries(node._attrs)) attrs[k] = String(v);
  #|       return attrs;
  #|     }
  #|     if (node.attributes && typeof node.attributes.length === "number") {
  #|       for (const attr of Array.from(node.attributes)) {
  #|         if (attr && typeof attr.name === "string") attrs[attr.name] = String(attr.value ?? "");
  #|       }
  #|     }
  #|     return attrs;
  #|   }
  #|
  #|   function toBidiNodeValue(node) {
  #|     const childNodes = Array.isArray(node._children)
  #|       ? node._children
  #|       : (Array.isArray(node.childNodes) ? node.childNodes : []);
  #|     const nodeType = typeof node.nodeType === "number" ? node.nodeType : 1;
  #|     const localName = node.localName || node._tagName || (node.tagName ? String(node.tagName).toLowerCase() : "");
  #|     const namespaceURI = node.namespaceURI || "http://www.w3.org/1999/xhtml";
  #|     const shadowRoot = node.shadowRoot
  #|       ? { type: "node", sharedId: getNodeSharedId(node.shadowRoot) }
  #|       : null;
  #|     return {
  #|       type: "node",
  #|       sharedId: getNodeSharedId(node),
  #|       value: {
  #|         nodeType,
  #|         localName: String(localName),
  #|         namespaceURI: String(namespaceURI),
  #|         childNodeCount: childNodes.length,
  #|         children: [],
  #|         attributes: getNodeAttributes(node),
  #|         shadowRoot
  #|       }
  #|     };
  #|   }
  #|
  #|   const internalIds = new WeakMap();
  #|   const referenceCounts = new WeakMap();
  #|   let nextInternalId = 1;
  #|   const trackReference = (obj) => {
  #|     const prev = referenceCounts.get(obj) || 0;
  #|     referenceCounts.set(obj, prev + 1);
  #|   };
  #|   const collectReferences = (value, seen = new WeakSet()) => {
  #|     if (!value || typeof value !== "object") return;
  #|     if (typeof value.nodeType === "number") {
  #|       trackReference(value);
  #|       return;
  #|     }
  #|     if (
  #|       value instanceof Date ||
  #|       value instanceof RegExp ||
  #|       value instanceof Error ||
  #|       value instanceof Promise ||
  #|       value instanceof WeakMap ||
  #|       value instanceof WeakSet ||
  #|       value instanceof ArrayBuffer ||
  #|       ArrayBuffer.isView(value)
  #|     ) {
  #|       return;
  #|     }
  #|     if (globalThis.__bidiProxyInstances && globalThis.__bidiProxyInstances.has(value)) return;
  #|     const isContainer =
  #|       Array.isArray(value) ||
  #|       value instanceof Map ||
  #|       value instanceof Set ||
  #|       value.constructor === Object;
  #|     if (!isContainer) return;
  #|     trackReference(value);
  #|     if (seen.has(value)) return;
  #|     seen.add(value);
  #|     if (Array.isArray(value)) {
  #|       for (const item of value) collectReferences(item, seen);
  #|       return;
  #|     }
  #|     if (value instanceof Map) {
  #|       for (const [k, v] of value) {
  #|         if (typeof k !== "string") collectReferences(k, seen);
  #|         collectReferences(v, seen);
  #|       }
  #|       return;
  #|     }
  #|     if (value instanceof Set) {
  #|       for (const item of value) collectReferences(item, seen);
  #|       return;
  #|     }
  #|     for (const entryValue of Object.values(value)) {
  #|       collectReferences(entryValue, seen);
  #|     }
  #|   };
  #|   const withInternalId = (originalValue, serialized) => {
  #|     if (!serialized || typeof serialized !== "object") return serialized;
  #|     if (!originalValue || (typeof originalValue !== "object" && typeof originalValue !== "function")) {
  #|       return serialized;
  #|     }
  #|     const serializedType = serialized.type;
  #|     if (serializedType !== "array" && serializedType !== "map" && serializedType !== "set" && serializedType !== "object" && serializedType !== "node") {
  #|       return serialized;
  #|     }
  #|     const count = referenceCounts.get(originalValue) || 0;
  #|     if (count <= 1) return serialized;
  #|     let internalId = internalIds.get(originalValue);
  #|     if (!internalId) {
  #|       internalId = `internal-${nextInternalId++}`;
  #|       internalIds.set(originalValue, internalId);
  #|     }
  #|     if (serialized.internalId) return serialized;
  #|     return { ...serialized, internalId };
  #|   };
  #|
  #|   function toBidiValue(value) {
  #|     if (value === undefined) return { type: "undefined" };
  #|     if (value === null) return { type: "null" };
  #|     const type = typeof value;
  #|     if (type === "boolean") return { type: "boolean", value };
  #|     if (type === "number") {
  #|       if (Number.isNaN(value)) return { type: "number", value: "NaN" };
  #|       if (!Number.isFinite(value)) return { type: "number", value: value > 0 ? "Infinity" : "-Infinity" };
  #|       if (Object.is(value, -0)) return { type: "number", value: "-0" };
  #|       return { type: "number", value };
  #|     }
  #|     if (type === "string") return { type: "string", value };
  #|     if (type === "bigint") return { type: "bigint", value: String(value) };
  #|     if (type === "symbol") return { type: "symbol" };
  #|     if (type === "function") return { type: "function" };
  #|     const objectTag = type === "object" ? Object.prototype.toString.call(value) : "";
  #|     if (objectTag === "[object Generator]" || objectTag === "[object AsyncGenerator]") {
  #|       return { type: "generator" };
  #|     }
  #|     if (globalThis.__bidiProxyInstances && globalThis.__bidiProxyInstances.has(value)) {
  #|       return { type: "proxy" };
  #|     }
  #|     if (value && type === "object" && typeof value.__bidiContextId === "string") {
  #|       return { type: "window", value: { context: String(value.__bidiContextId) } };
  #|     }
  #|     if (value === globalThis || value === globalThis.window) {
  #|       return {
  #|         type: "window",
  #|         value: { context: String(globalThis.__bidiCurrentContext || "default-context") }
  #|       };
  #|     }
  #|     if (value && type === "object" && typeof value.nodeType === "number") {
  #|       return withInternalId(value, toBidiNodeValue(value));
  #|     }
  #|     if (value instanceof RegExp) return { type: "regexp", value: { pattern: value.source, flags: value.flags } };
  #|     if (value instanceof Date) return { type: "date", value: value.toISOString() };
  #|     if (value instanceof Error) return { type: "error" };
  #|     if (value instanceof Promise) return { type: "promise" };
  #|     if (value instanceof Map) {
  #|       const entries = [];
  #|       for (const [k, v] of value) {
  #|         entries.push([typeof k === "string" ? k : toBidiValue(k), toBidiValue(v)]);
  #|       }
  #|       return withInternalId(value, { type: "map", value: entries });
  #|     }
  #|     if (value instanceof Set) {
  #|       return withInternalId(
  #|         value,
  #|         { type: "set", value: Array.from(value).map(toBidiValue) },
  #|       );
  #|     }
  #|     if (value instanceof WeakMap) return { type: "weakmap" };
  #|     if (value instanceof WeakSet) return { type: "weakset" };
  #|     if (ArrayBuffer.isView(value)) return { type: "typedarray" };
  #|     if (value instanceof ArrayBuffer) return { type: "arraybuffer" };
  #|     if (Array.isArray(value)) {
  #|       return withInternalId(
  #|         value,
  #|         { type: "array", value: value.map(toBidiValue) },
  #|       );
  #|     }
  #|     if (value && value.constructor === Object) {
  #|       const entries = Object.entries(value).map(([k, v]) => [k, toBidiValue(v)]);
  #|       return withInternalId(value, { type: "object", value: entries });
  #|     }
  #|     return { type: "object" };
  #|   }
  #|
  #|   const realm = realmId;
  #|   const wrapResult = (valueJson) =>
  #|     `{"id":${id},"type":"success","result":{"realm":${JSON.stringify(realm)},"result":${valueJson}}}`;
  #|   try {
  #|     const result = (0, eval)(expression);
  #|     if (result instanceof Promise) {
  #|       // Avoid process-level unhandled rejection when awaitPromise=false.
  #|       result.catch(() => {});
  #|     }
  #|     collectReferences(result);
  #|     if (result === undefined) return wrapResult('{"type":"undefined"}');
  #|     if (result === null) return wrapResult('{"type":"null"}');
  #|     const type = typeof result;
  #|     if (type === "boolean") {
  #|       return wrapResult(`{"type":"boolean","value":${result}}`);
  #|     }
  #|     if (type === "number") {
  #|       if (Number.isNaN(result)) {
  #|         return wrapResult('{"type":"number","value":"NaN"}');
  #|       }
  #|       if (!Number.isFinite(result)) {
  #|         return wrapResult(
  #|           `{"type":"number","value":"${result > 0 ? "Infinity" : "-Infinity"}"}`
  #|         );
  #|       }
  #|       if (Object.is(result, -0)) {
  #|         return wrapResult('{"type":"number","value":"-0"}');
  #|       }
  #|       return wrapResult(`{"type":"number","value":${result}}`);
  #|     }
  #|     if (type === "string") {
  #|       return wrapResult(
  #|         `{"type":"string","value":${JSON.stringify(result)}}`
  #|       );
  #|     }
  #|     if (type === "bigint") {
  #|       return wrapResult(
  #|         `{"type":"bigint","value":${JSON.stringify(String(result))}}`
  #|       );
  #|     }
  #|     if (type === "symbol") return wrapResult('{"type":"symbol"}');
  #|     if (type === "function") return wrapResult('{"type":"function"}');
  #|     const payload = { realm, result: toBidiValue(result) };
  #|     return JSON.stringify({ id, type: "success", result: payload });
  #|   } catch (e) {
  #|     const payload = {
  #|       realm,
  #|       exceptionDetails: {
  #|         columnNumber: 0,
  #|         lineNumber: 0,
  #|         text: String(e),
  #|         exception: toBidiValue(e),
  #|         stackTrace: { callFrames: [] }
  #|       }
  #|     };
  #|     return JSON.stringify({ id, type: "success", result: payload });
  #|   }
  #| }

///|
/// Evaluate JavaScript expression and return result as JSON (sync)
fn evaluate_js_with_console(
  expression : String,
  capture_console : Bool,
  user_activation : Bool,
  root_ownership : Bool,
  serialization_options_json : String,
) -> String {
  js_evaluate_expression(
    expression, capture_console, user_activation, root_ownership, serialization_options_json,
  )
}

///|
/// Evaluate JavaScript expression and return result as JSON (sync)
pub fn evaluate_js(expression : String) -> String {
  evaluate_js_with_console(expression, true, false, false, "{}")
}

///|
/// FFI: Evaluate JavaScript expression asynchronously (awaits Promise)
/// Returns a Promise that resolves to JSON string
extern "js" fn js_evaluate_expression_async(
  expression : String,
  user_activation : Bool,
  ctx_id : String,
) -> @core.Any =
  #| async (expression, userActivation, ctxId) => {
  #|   const consoleEntries = [];
  #|   const captureConsole = true;
  #|   const originalConsole = {
  #|     log: console.log,
  #|     warn: console.warn,
  #|     error: console.error,
  #|     info: console.info,
  #|     debug: console.debug,
  #|     assert: console.assert,
  #|     table: console.table,
  #|     trace: console.trace,
  #|     time: console.time,
  #|     timeEnd: console.timeEnd
  #|   };
  #|
  #|   const consoleArgToText = (arg) => {
  #|     if (typeof arg === "string") return arg;
  #|     if (arg === undefined) return "undefined";
  #|     if (typeof arg === "bigint") return `${arg}n`;
  #|     try {
  #|       const json = JSON.stringify(arg);
  #|       if (json !== undefined) return json;
  #|     } catch (_e) {}
  #|     return String(arg);
  #|   };
  #|
  #|   const pushConsoleEntry = (level, method, args, textArgs = args) => {
  #|     consoleEntries.push({
  #|       level,
  #|       method,
  #|       text: textArgs.map(consoleArgToText).join(" "),
  #|       args: args.map(toBidiValue),
  #|       timestamp: Date.now()
  #|     });
  #|   };
  #|
  #|   const makeInterceptor = (level, method) => (...args) => {
  #|     pushConsoleEntry(level, method, args);
  #|     originalConsole[method](...args);
  #|   };
  #|
  #|   console.log = makeInterceptor('info', 'log');
  #|   console.warn = makeInterceptor('warn', 'warn');
  #|   console.error = makeInterceptor('error', 'error');
  #|   console.info = makeInterceptor('info', 'info');
  #|   console.debug = makeInterceptor('debug', 'debug');
  #|   console.table = makeInterceptor('info', 'table');
  #|   console.trace = makeInterceptor('debug', 'trace');
  #|   console.assert = (...args) => {
  #|     if (args.length > 0 && args[0]) {
  #|       return;
  #|     }
  #|     const textArgs = args.length > 1 ? args.slice(1) : ["Assertion failed"];
  #|     pushConsoleEntry("error", "assert", textArgs);
  #|     originalConsole.assert(...args);
  #|   };
  #|   console.time = (...args) => {
  #|     originalConsole.time(...args);
  #|   };
  #|   console.timeEnd = (...args) => {
  #|     const textArgs = args.length > 0 ? args : ["default"];
  #|     pushConsoleEntry("info", "timeEnd", textArgs);
  #|     originalConsole.timeEnd(...args);
  #|   };
  #|
  #|   const isActive = !!userActivation;
  #|   globalThis.__bidiUserActivation = isActive;
  #|   globalThis.__bidiCurrentContext = ctxId;
  #|   if (!globalThis.__bidiProxyInstances) globalThis.__bidiProxyInstances = new WeakSet();
  #|   if (!globalThis.__bidiNativeProxy && typeof globalThis.Proxy === "function") {
  #|     const NativeProxy = globalThis.Proxy;
  #|     const tracked = globalThis.__bidiProxyInstances;
  #|     function TrackedProxy(target, handler) {
  #|       const proxied = new NativeProxy(target, handler);
  #|       tracked.add(proxied);
  #|       return proxied;
  #|     }
  #|     TrackedProxy.revocable = function(target, handler) {
  #|       const revocable = NativeProxy.revocable(target, handler);
  #|       tracked.add(revocable.proxy);
  #|       return revocable;
  #|     };
  #|     globalThis.__bidiNativeProxy = NativeProxy;
  #|     globalThis.Proxy = TrackedProxy;
  #|   }
  #|   if (!globalThis.navigator) globalThis.navigator = {};
  #|   globalThis.navigator.userActivation = {
  #|     isActive,
  #|     hasBeenActive: isActive
  #|   };
  #|   if (!globalThis.__bidiContextWindows) globalThis.__bidiContextWindows = new Map();
  #|   if (!globalThis.__bidiContextWindows.has(ctxId)) {
  #|     const win = {};
  #|     win.__bidiContextId = String(ctxId);
  #|     win.window = win;
  #|     win.innerWidth = Number(globalThis.innerWidth || 1024);
  #|     win.innerHeight = Number(globalThis.innerHeight || 768);
  #|     win.outerWidth = Number(globalThis.outerWidth || win.innerWidth);
  #|     win.outerHeight = Number(globalThis.outerHeight || win.innerHeight);
  #|     win.devicePixelRatio = Number(globalThis.devicePixelRatio || 1);
  #|     win.pageXOffset = 0;
  #|     win.pageYOffset = 0;
  #|     win._listeners = {};
  #|     win.addEventListener = function(type, fn) {
  #|       if (!this._listeners[type]) this._listeners[type] = [];
  #|       this._listeners[type].push(fn);
  #|     };
  #|     win.removeEventListener = function(type, fn) {
  #|       if (!this._listeners[type]) return;
  #|       this._listeners[type] = this._listeners[type].filter((f) => f !== fn);
  #|     };
  #|     win.dispatchEvent = function(event) {
  #|       try { event.currentTarget = this; } catch (_e) {}
  #|       const listeners = this._listeners[event.type] || [];
  #|       for (const fn of listeners) {
  #|         try { fn.call(this, event); } catch (_e) {}
  #|       }
  #|       return !event.defaultPrevented;
  #|     };
  #|     globalThis.__bidiContextWindows.set(ctxId, win);
  #|   }
  #|   const contextWindow = globalThis.__bidiContextWindows.get(ctxId);
  #|   if (!contextWindow.window) contextWindow.window = contextWindow;
  #|   const frameWindows = Array.isArray(contextWindow.frames) ? contextWindow.frames : [];
  #|   globalThis.window = contextWindow;
  #|   globalThis.frames = frameWindows;
  #|   if (contextWindow.document && typeof contextWindow.document === "object") {
  #|     globalThis.document = contextWindow.document;
  #|   }
  #|   if (contextWindow.location && typeof contextWindow.location === "object") {
  #|     globalThis.location = contextWindow.location;
  #|     try { globalThis.__pageUrl = String(contextWindow.location.href || "about:blank"); } catch (_e) {}
  #|   } else {
  #|     const locationHref = "about:blank";
  #|     contextWindow.location = {
  #|       href: locationHref,
  #|       origin: '',
  #|       protocol: 'about:',
  #|       host: '',
  #|       hostname: '',
  #|       port: '',
  #|       pathname: 'blank',
  #|       search: '',
  #|       hash: '',
  #|       assign: function(url) { const next = String(url); globalThis.__pageUrl = next; this.href = next; },
  #|       replace: function(url) { const next = String(url); globalThis.__pageUrl = next; this.href = next; },
  #|       reload: function() {}
  #|     };
  #|     globalThis.location = contextWindow.location;
  #|     globalThis.__pageUrl = locationHref;
  #|   }
  #|   if (!globalThis.document) {
  #|     const body = {
  #|       appendChild(node) { return node; }
  #|     };
  #|     const createElement = (tagName) => {
  #|       const name = String(tagName || "div");
  #|       return {
  #|         tagName: name.toUpperCase(),
  #|         localName: name.toLowerCase(),
  #|         nodeType: 1,
  #|         namespaceURI: "http://www.w3.org/1999/xhtml",
  #|         _attrs: {},
  #|         _children: [],
  #|         childNodes: [],
  #|         shadowRoot: null,
  #|         setAttribute(name, value) { this._attrs[String(name)] = String(value); },
  #|       };
  #|     };
  #|     globalThis.document = {
  #|       body,
  #|       createElement,
  #|       createTextNode(text) { return { nodeType: 3, textContent: String(text) }; },
  #|       createDocumentFragment() {
  #|         return {
  #|           nodeType: 11,
  #|           nodeName: "#document-fragment",
  #|           _children: [],
  #|           childNodes: [],
  #|         };
  #|       },
  #|       execCommand(command) {
  #|         const cmd = String(command || '').toLowerCase();
  #|         if (cmd === 'selectall') return true;
  #|         if (cmd === 'copy') return !!globalThis.__bidiUserActivation;
  #|         return false;
  #|       }
  #|     };
  #|     if (!globalThis.DocumentFragment) {
  #|       globalThis.DocumentFragment = class DocumentFragment {
  #|         constructor() {
  #|           return globalThis.document.createDocumentFragment();
  #|         }
  #|       };
  #|     }
  #|   }
  #|   if (globalThis.document && !globalThis.window.document) {
  #|     contextWindow.document = globalThis.document;
  #|   }
  #|   if (globalThis.document) {
  #|     globalThis.document.execCommand = function(command) {
  #|       const cmd = String(command || '').toLowerCase();
  #|       if (cmd === 'selectall') return true;
  #|       if (cmd === 'copy') return !!globalThis.__bidiUserActivation;
  #|       return false;
  #|     };
  #|   }
  #|
  #|   function getNodeSharedId(node) {
  #|     const sharedIds = globalThis.__bidiNodeSharedIds || (globalThis.__bidiNodeSharedIds = new WeakMap());
  #|     const nodeStore = globalThis.__bidiSharedNodeStore || (globalThis.__bidiSharedNodeStore = new Map());
  #|     if (typeof globalThis.__bidiNextNodeSharedId !== "number") {
  #|       globalThis.__bidiNextNodeSharedId = 1;
  #|     }
  #|     let sharedId = sharedIds.get(node);
  #|     if (!sharedId) {
  #|       sharedId = `node-${globalThis.__bidiNextNodeSharedId++}`;
  #|       sharedIds.set(node, sharedId);
  #|     }
  #|     nodeStore.set(sharedId, node);
  #|     return sharedId;
  #|   }
  #|
  #|   function getNodeAttributes(node) {
  #|     const attrs = {};
  #|     if (!node || typeof node !== "object") return attrs;
  #|     if (node._attrs && typeof node._attrs === "object") {
  #|       for (const [k, v] of Object.entries(node._attrs)) attrs[k] = String(v);
  #|       return attrs;
  #|     }
  #|     if (node.attributes && typeof node.attributes.length === "number") {
  #|       for (const attr of Array.from(node.attributes)) {
  #|         if (attr && typeof attr.name === "string") attrs[attr.name] = String(attr.value ?? "");
  #|       }
  #|     }
  #|     return attrs;
  #|   }
  #|
  #|   function toBidiNodeValue(node) {
  #|     const childNodes = Array.isArray(node._children)
  #|       ? node._children
  #|       : (Array.isArray(node.childNodes) ? node.childNodes : []);
  #|     const nodeType = typeof node.nodeType === "number" ? node.nodeType : 1;
  #|     const localName = node.localName || node._tagName || (node.tagName ? String(node.tagName).toLowerCase() : "");
  #|     const namespaceURI = node.namespaceURI || "http://www.w3.org/1999/xhtml";
  #|     const shadowRoot = node.shadowRoot
  #|       ? { type: "node", sharedId: getNodeSharedId(node.shadowRoot) }
  #|       : null;
  #|     return {
  #|       type: "node",
  #|       sharedId: getNodeSharedId(node),
  #|       value: {
  #|         nodeType,
  #|         localName: String(localName),
  #|         namespaceURI: String(namespaceURI),
  #|         childNodeCount: childNodes.length,
  #|         children: [],
  #|         attributes: getNodeAttributes(node),
  #|         shadowRoot
  #|       }
  #|     };
  #|   }
  #|
  #|   const internalIds = new WeakMap();
  #|   const referenceCounts = new WeakMap();
  #|   let nextInternalId = 1;
  #|   const trackReference = (obj) => {
  #|     const prev = referenceCounts.get(obj) || 0;
  #|     referenceCounts.set(obj, prev + 1);
  #|   };
  #|   const collectReferences = (value, seen = new WeakSet()) => {
  #|     if (!value || typeof value !== "object") return;
  #|     if (typeof value.nodeType === "number") {
  #|       trackReference(value);
  #|       return;
  #|     }
  #|     if (
  #|       value instanceof Date ||
  #|       value instanceof RegExp ||
  #|       value instanceof Error ||
  #|       value instanceof Promise ||
  #|       value instanceof WeakMap ||
  #|       value instanceof WeakSet ||
  #|       value instanceof ArrayBuffer ||
  #|       ArrayBuffer.isView(value)
  #|     ) {
  #|       return;
  #|     }
  #|     if (globalThis.__bidiProxyInstances && globalThis.__bidiProxyInstances.has(value)) return;
  #|     const isContainer =
  #|       Array.isArray(value) ||
  #|       value instanceof Map ||
  #|       value instanceof Set ||
  #|       value.constructor === Object;
  #|     if (!isContainer) return;
  #|     trackReference(value);
  #|     if (seen.has(value)) return;
  #|     seen.add(value);
  #|     if (Array.isArray(value)) {
  #|       for (const item of value) collectReferences(item, seen);
  #|       return;
  #|     }
  #|     if (value instanceof Map) {
  #|       for (const [k, v] of value) {
  #|         if (typeof k !== "string") collectReferences(k, seen);
  #|         collectReferences(v, seen);
  #|       }
  #|       return;
  #|     }
  #|     if (value instanceof Set) {
  #|       for (const item of value) collectReferences(item, seen);
  #|       return;
  #|     }
  #|     for (const entryValue of Object.values(value)) {
  #|       collectReferences(entryValue, seen);
  #|     }
  #|   };
  #|   const withInternalId = (originalValue, serialized) => {
  #|     if (!serialized || typeof serialized !== "object") return serialized;
  #|     if (!originalValue || (typeof originalValue !== "object" && typeof originalValue !== "function")) {
  #|       return serialized;
  #|     }
  #|     const serializedType = serialized.type;
  #|     if (serializedType !== "array" && serializedType !== "map" && serializedType !== "set" && serializedType !== "object" && serializedType !== "node") {
  #|       return serialized;
  #|     }
  #|     const count = referenceCounts.get(originalValue) || 0;
  #|     if (count <= 1) return serialized;
  #|     let internalId = internalIds.get(originalValue);
  #|     if (!internalId) {
  #|       internalId = `internal-${nextInternalId++}`;
  #|       internalIds.set(originalValue, internalId);
  #|     }
  #|     if (serialized.internalId) return serialized;
  #|     return { ...serialized, internalId };
  #|   };
  #|
  #|   function toBidiValue(value) {
  #|     if (value === undefined) return { type: "undefined" };
  #|     if (value === null) return { type: "null" };
  #|     const type = typeof value;
  #|     if (type === "boolean") return { type: "boolean", value };
  #|     if (type === "number") {
  #|       if (Number.isNaN(value)) return { type: "number", value: "NaN" };
  #|       if (!Number.isFinite(value)) return { type: "number", value: value > 0 ? "Infinity" : "-Infinity" };
  #|       if (Object.is(value, -0)) return { type: "number", value: "-0" };
  #|       return { type: "number", value };
  #|     }
  #|     if (type === "string") return { type: "string", value };
  #|     if (type === "bigint") return { type: "bigint", value: String(value) };
  #|     if (type === "symbol") return { type: "symbol" };
  #|     if (type === "function") return { type: "function" };
  #|     const objectTag = type === "object" ? Object.prototype.toString.call(value) : "";
  #|     if (objectTag === "[object Generator]" || objectTag === "[object AsyncGenerator]") {
  #|       return { type: "generator" };
  #|     }
  #|     if (globalThis.__bidiProxyInstances && globalThis.__bidiProxyInstances.has(value)) {
  #|       return { type: "proxy" };
  #|     }
  #|     if (value && type === "object" && typeof value.__bidiContextId === "string") {
  #|       return { type: "window", value: { context: String(value.__bidiContextId) } };
  #|     }
  #|     if (value === globalThis || value === globalThis.window) {
  #|       return {
  #|         type: "window",
  #|         value: { context: String(globalThis.__bidiCurrentContext || "default-context") }
  #|       };
  #|     }
  #|     if (value && type === "object" && typeof value.nodeType === "number") {
  #|       return withInternalId(value, toBidiNodeValue(value));
  #|     }
  #|     if (value instanceof RegExp) return { type: "regexp", value: { pattern: value.source, flags: value.flags } };
  #|     if (value instanceof Date) return { type: "date", value: value.toISOString() };
  #|     if (value instanceof Error) return { type: "error" };
  #|     if (value instanceof Promise) return { type: "promise" };
  #|     if (value instanceof Map) {
  #|       const entries = [];
  #|       for (const [k, v] of value) entries.push([typeof k === "string" ? k : toBidiValue(k), toBidiValue(v)]);
  #|       return withInternalId(value, { type: "map", value: entries });
  #|     }
  #|     if (value instanceof Set) {
  #|       return withInternalId(
  #|         value,
  #|         { type: "set", value: Array.from(value).map(toBidiValue) },
  #|       );
  #|     }
  #|     if (value instanceof WeakMap) return { type: "weakmap" };
  #|     if (value instanceof WeakSet) return { type: "weakset" };
  #|     if (ArrayBuffer.isView(value)) return { type: "typedarray" };
  #|     if (value instanceof ArrayBuffer) return { type: "arraybuffer" };
  #|     if (Array.isArray(value)) {
  #|       return withInternalId(
  #|         value,
  #|         { type: "array", value: value.map(toBidiValue) },
  #|       );
  #|     }
  #|     if (value.constructor === Object) {
  #|       const entries = Object.entries(value).map(([k, v]) => [k, toBidiValue(v)]);
  #|       return withInternalId(value, { type: "object", value: entries });
  #|     }
  #|     return { type: "object" };
  #|   }
  #|
  #|   try {
  #|     let result = (0, eval)(expression);
  #|     // Await if result is a Promise
  #|     if (result instanceof Promise) {
  #|       result = await result;
  #|     }
  #|     collectReferences(result);
  #|     return JSON.stringify({ type: "success", result: toBidiValue(result), consoleEntries });
  #|   } catch (e) {
  #|     return JSON.stringify({
  #|       type: "exception",
  #|       exceptionDetails: {
  #|         columnNumber: 0,
  #|         lineNumber: 0,
  #|         text: String(e),
  #|         exception: toBidiValue(e),
  #|         stackTrace: { callFrames: [] }
  #|       },
  #|       consoleEntries
  #|     });
  #|   } finally {
  #|     if (captureConsole && originalConsole) {
  #|       console.log = originalConsole.log;
  #|       console.warn = originalConsole.warn;
  #|       console.error = originalConsole.error;
  #|       console.info = originalConsole.info;
  #|       console.debug = originalConsole.debug;
  #|       console.assert = originalConsole.assert;
  #|       console.table = originalConsole.table;
  #|       console.trace = originalConsole.trace;
  #|       console.time = originalConsole.time;
  #|       console.timeEnd = originalConsole.timeEnd;
  #|     }
  #|   }
  #| }

///|
/// FFI: Await a JavaScript Promise and return the result as string
extern "js" fn js_await_promise(promise : @core.Any) -> String =
  #| async (promise) => await promise

///|
/// Evaluate JavaScript expression asynchronously (awaits Promise if awaitPromise=true)
/// Returns a Promise (@core.Any) that resolves to JSON string
pub fn evaluate_js_async(expression : String) -> @core.Any {
  js_evaluate_expression_async(expression, false, "")
}

///|
/// FFI: Evaluate expression asynchronously and send result via WebSocket
/// This runs the evaluation, awaits any Promise result, and sends response directly
extern "js" fn js_eval_and_send_async(
  socket : @core.Any,
  request_id : Int,
  expression : String,
  ctx_id : String,
  realm_id : String,
  capture_console : Bool,
  user_activation : Bool,
  root_ownership : Bool,
  unwrap_result : Bool,
) -> Unit =
  #| async (socket, requestId, expression, ctxId, realmId, captureConsole, userActivation, rootOwnership, unwrapResult) => {
  #|   const consoleEntries = [];
  #|   let originalConsole = null;
  #|   if (captureConsole) {
  #|     originalConsole = {
  #|       log: console.log, warn: console.warn, error: console.error,
  #|       info: console.info, debug: console.debug,
  #|       assert: console.assert, table: console.table, trace: console.trace,
  #|       time: console.time, timeEnd: console.timeEnd
  #|     };
  #|
  #|     const consoleArgToText = (arg) => {
  #|       if (typeof arg === "string") return arg;
  #|       if (arg === undefined) return "undefined";
  #|       if (typeof arg === "bigint") return `${arg}n`;
  #|       try {
  #|         const json = JSON.stringify(arg);
  #|         if (json !== undefined) return json;
  #|       } catch (_e) {}
  #|       return String(arg);
  #|     };
  #|
  #|     const pushConsoleEntry = (level, method, args, textArgs = args) => {
  #|       consoleEntries.push({
  #|         level, method,
  #|         text: textArgs.map(consoleArgToText).join(" "),
  #|         args: args.map(toBidiValue),
  #|         timestamp: Date.now()
  #|       });
  #|     };
  #|
  #|     const makeInterceptor = (level, method) => (...args) => {
  #|       pushConsoleEntry(level, method, args);
  #|       originalConsole[method](...args);
  #|     };
  #|
  #|     console.log = makeInterceptor('info', 'log');
  #|     console.warn = makeInterceptor('warn', 'warn');
  #|     console.error = makeInterceptor('error', 'error');
  #|     console.info = makeInterceptor('info', 'info');
  #|     console.debug = makeInterceptor('debug', 'debug');
  #|     console.table = makeInterceptor('info', 'table');
  #|     console.trace = makeInterceptor('debug', 'trace');
  #|     console.assert = (...args) => {
  #|       if (args.length > 0 && args[0]) {
  #|         return;
  #|       }
  #|       const textArgs = args.length > 1 ? args.slice(1) : ["Assertion failed"];
  #|       pushConsoleEntry("error", "assert", textArgs);
  #|       originalConsole.assert(...args);
  #|     };
  #|     console.time = (...args) => {
  #|       originalConsole.time(...args);
  #|     };
  #|     console.timeEnd = (...args) => {
  #|       const textArgs = args.length > 0 ? args : ["default"];
  #|       pushConsoleEntry("info", "timeEnd", textArgs);
  #|       originalConsole.timeEnd(...args);
  #|     };
  #|   }
  #|
  #|   const isActive = !!userActivation;
  #|   globalThis.__bidiUserActivation = isActive;
  #|   globalThis.__bidiCurrentContext = ctxId;
  #|   if (!globalThis.__bidiProxyInstances) globalThis.__bidiProxyInstances = new WeakSet();
  #|   if (!globalThis.__bidiNativeProxy && typeof globalThis.Proxy === "function") {
  #|     const NativeProxy = globalThis.Proxy;
  #|     const tracked = globalThis.__bidiProxyInstances;
  #|     function TrackedProxy(target, handler) {
  #|       const proxied = new NativeProxy(target, handler);
  #|       tracked.add(proxied);
  #|       return proxied;
  #|     }
  #|     TrackedProxy.revocable = function(target, handler) {
  #|       const revocable = NativeProxy.revocable(target, handler);
  #|       tracked.add(revocable.proxy);
  #|       return revocable;
  #|     };
  #|     globalThis.__bidiNativeProxy = NativeProxy;
  #|     globalThis.Proxy = TrackedProxy;
  #|   }
  #|   if (!globalThis.navigator) globalThis.navigator = {};
  #|   globalThis.navigator.userActivation = {
  #|     isActive,
  #|     hasBeenActive: isActive
  #|   };
  #|   if (!globalThis.__bidiContextWindows) globalThis.__bidiContextWindows = new Map();
  #|   if (!globalThis.__bidiContextWindows.has(ctxId)) {
  #|     const win = {};
  #|     win.__bidiContextId = String(ctxId);
  #|     win.window = win;
  #|     win.innerWidth = Number(globalThis.innerWidth || 1024);
  #|     win.innerHeight = Number(globalThis.innerHeight || 768);
  #|     win.outerWidth = Number(globalThis.outerWidth || win.innerWidth);
  #|     win.outerHeight = Number(globalThis.outerHeight || win.innerHeight);
  #|     win.devicePixelRatio = Number(globalThis.devicePixelRatio || 1);
  #|     win.pageXOffset = 0;
  #|     win.pageYOffset = 0;
  #|     win._listeners = {};
  #|     win.addEventListener = function(type, fn) {
  #|       if (!this._listeners[type]) this._listeners[type] = [];
  #|       this._listeners[type].push(fn);
  #|     };
  #|     win.removeEventListener = function(type, fn) {
  #|       if (!this._listeners[type]) return;
  #|       this._listeners[type] = this._listeners[type].filter((f) => f !== fn);
  #|     };
  #|     win.dispatchEvent = function(event) {
  #|       try { event.currentTarget = this; } catch (_e) {}
  #|       const listeners = this._listeners[event.type] || [];
  #|       for (const fn of listeners) {
  #|         try { fn.call(this, event); } catch (_e) {}
  #|       }
  #|       return !event.defaultPrevented;
  #|     };
  #|     globalThis.__bidiContextWindows.set(ctxId, win);
  #|   }
  #|   const contextWindow = globalThis.__bidiContextWindows.get(ctxId);
  #|   if (!contextWindow.window) contextWindow.window = contextWindow;
  #|   const frameWindows = Array.isArray(contextWindow.frames) ? contextWindow.frames : [];
  #|   globalThis.window = contextWindow;
  #|   globalThis.frames = frameWindows;
  #|   if (contextWindow.document && typeof contextWindow.document === "object") {
  #|     globalThis.document = contextWindow.document;
  #|   }
  #|   if (contextWindow.location && typeof contextWindow.location === "object") {
  #|     globalThis.location = contextWindow.location;
  #|     try { globalThis.__pageUrl = String(contextWindow.location.href || "about:blank"); } catch (_e) {}
  #|   } else {
  #|     const locationHref = "about:blank";
  #|     contextWindow.location = {
  #|       href: locationHref,
  #|       origin: '',
  #|       protocol: 'about:',
  #|       host: '',
  #|       hostname: '',
  #|       port: '',
  #|       pathname: 'blank',
  #|       search: '',
  #|       hash: '',
  #|       assign: function(url) { const next = String(url); globalThis.__pageUrl = next; this.href = next; },
  #|       replace: function(url) { const next = String(url); globalThis.__pageUrl = next; this.href = next; },
  #|       reload: function() {}
  #|     };
  #|     globalThis.location = contextWindow.location;
  #|     globalThis.__pageUrl = locationHref;
  #|   }
  #|   if (!globalThis.document) {
  #|     const body = {
  #|       appendChild(node) { return node; }
  #|     };
  #|     const createElement = (tagName) => {
  #|       const name = String(tagName || "div");
  #|       return {
  #|         tagName: name.toUpperCase(),
  #|         localName: name.toLowerCase(),
  #|         nodeType: 1,
  #|         namespaceURI: "http://www.w3.org/1999/xhtml",
  #|         _attrs: {},
  #|         _children: [],
  #|         childNodes: [],
  #|         shadowRoot: null,
  #|         setAttribute(name, value) { this._attrs[String(name)] = String(value); },
  #|       };
  #|     };
  #|     globalThis.document = {
  #|       body,
  #|       createElement,
  #|       createTextNode(text) { return { nodeType: 3, textContent: String(text) }; },
  #|       createDocumentFragment() {
  #|         return {
  #|           nodeType: 11,
  #|           nodeName: "#document-fragment",
  #|           _children: [],
  #|           childNodes: [],
  #|         };
  #|       },
  #|       execCommand(command) {
  #|         const cmd = String(command || '').toLowerCase();
  #|         if (cmd === 'selectall') return true;
  #|         if (cmd === 'copy') return !!globalThis.__bidiUserActivation;
  #|         return false;
  #|       }
  #|     };
  #|     if (!globalThis.DocumentFragment) {
  #|       globalThis.DocumentFragment = class DocumentFragment {
  #|         constructor() {
  #|           return globalThis.document.createDocumentFragment();
  #|         }
  #|       };
  #|     }
  #|   }
  #|   if (globalThis.document) {
  #|     globalThis.document.execCommand = function(command) {
  #|       const cmd = String(command || '').toLowerCase();
  #|       if (cmd === 'selectall') return true;
  #|       if (cmd === 'copy') return !!globalThis.__bidiUserActivation;
  #|       return false;
  #|     };
  #|   }
  #|   if (globalThis.document && !contextWindow.document) {
  #|     contextWindow.document = globalThis.document;
  #|   }
  #|
  #|   function getNodeSharedId(node) {
  #|     const sharedIds = globalThis.__bidiNodeSharedIds || (globalThis.__bidiNodeSharedIds = new WeakMap());
  #|     const nodeStore = globalThis.__bidiSharedNodeStore || (globalThis.__bidiSharedNodeStore = new Map());
  #|     if (typeof globalThis.__bidiNextNodeSharedId !== "number") {
  #|       globalThis.__bidiNextNodeSharedId = 1;
  #|     }
  #|     let sharedId = sharedIds.get(node);
  #|     if (!sharedId) {
  #|       sharedId = `node-${globalThis.__bidiNextNodeSharedId++}`;
  #|       sharedIds.set(node, sharedId);
  #|     }
  #|     nodeStore.set(sharedId, node);
  #|     return sharedId;
  #|   }
  #|
  #|   function getNodeAttributes(node) {
  #|     const attrs = {};
  #|     if (!node || typeof node !== "object") return attrs;
  #|     if (node._attrs && typeof node._attrs === "object") {
  #|       for (const [k, v] of Object.entries(node._attrs)) attrs[k] = String(v);
  #|       return attrs;
  #|     }
  #|     if (node.attributes && typeof node.attributes.length === "number") {
  #|       for (const attr of Array.from(node.attributes)) {
  #|         if (attr && typeof attr.name === "string") attrs[attr.name] = String(attr.value ?? "");
  #|       }
  #|     }
  #|     return attrs;
  #|   }
  #|
  #|   function toBidiNodeValue(node) {
  #|     const childNodes = Array.isArray(node._children)
  #|       ? node._children
  #|       : (Array.isArray(node.childNodes) ? node.childNodes : []);
  #|     const nodeType = typeof node.nodeType === "number" ? node.nodeType : 1;
  #|     const localName = node.localName || node._tagName || (node.tagName ? String(node.tagName).toLowerCase() : "");
  #|     const namespaceURI = node.namespaceURI || "http://www.w3.org/1999/xhtml";
  #|     const shadowRoot = node.shadowRoot
  #|       ? { type: "node", sharedId: getNodeSharedId(node.shadowRoot) }
  #|       : null;
  #|     return {
  #|       type: "node",
  #|       sharedId: getNodeSharedId(node),
  #|       value: {
  #|         nodeType,
  #|         localName: String(localName),
  #|         namespaceURI: String(namespaceURI),
  #|         childNodeCount: childNodes.length,
  #|         children: [],
  #|         attributes: getNodeAttributes(node),
  #|         shadowRoot
  #|       }
  #|     };
  #|   }
  #|
  #|   const internalIds = new WeakMap();
  #|   const referenceCounts = new WeakMap();
  #|   let nextInternalId = 1;
  #|   const trackReference = (obj) => {
  #|     const prev = referenceCounts.get(obj) || 0;
  #|     referenceCounts.set(obj, prev + 1);
  #|   };
  #|   const collectReferences = (value, seen = new WeakSet()) => {
  #|     if (!value || typeof value !== "object") return;
  #|     if (typeof value.nodeType === "number") {
  #|       trackReference(value);
  #|       return;
  #|     }
  #|     if (
  #|       value instanceof Date ||
  #|       value instanceof RegExp ||
  #|       value instanceof Error ||
  #|       value instanceof Promise ||
  #|       value instanceof WeakMap ||
  #|       value instanceof WeakSet ||
  #|       value instanceof ArrayBuffer ||
  #|       ArrayBuffer.isView(value)
  #|     ) {
  #|       return;
  #|     }
  #|     if (globalThis.__bidiProxyInstances && globalThis.__bidiProxyInstances.has(value)) return;
  #|     const isContainer =
  #|       Array.isArray(value) ||
  #|       value instanceof Map ||
  #|       value instanceof Set ||
  #|       value.constructor === Object;
  #|     if (!isContainer) return;
  #|     trackReference(value);
  #|     if (seen.has(value)) return;
  #|     seen.add(value);
  #|     if (Array.isArray(value)) {
  #|       for (const item of value) collectReferences(item, seen);
  #|       return;
  #|     }
  #|     if (value instanceof Map) {
  #|       for (const [k, v] of value) {
  #|         if (typeof k !== "string") collectReferences(k, seen);
  #|         collectReferences(v, seen);
  #|       }
  #|       return;
  #|     }
  #|     if (value instanceof Set) {
  #|       for (const item of value) collectReferences(item, seen);
  #|       return;
  #|     }
  #|     for (const entryValue of Object.values(value)) {
  #|       collectReferences(entryValue, seen);
  #|     }
  #|   };
  #|   const withInternalId = (originalValue, serialized) => {
  #|     if (!serialized || typeof serialized !== "object") return serialized;
  #|     if (!originalValue || (typeof originalValue !== "object" && typeof originalValue !== "function")) {
  #|       return serialized;
  #|     }
  #|     const serializedType = serialized.type;
  #|     if (serializedType !== "array" && serializedType !== "map" && serializedType !== "set" && serializedType !== "object" && serializedType !== "node") {
  #|       return serialized;
  #|     }
  #|     const count = referenceCounts.get(originalValue) || 0;
  #|     if (count <= 1) return serialized;
  #|     let internalId = internalIds.get(originalValue);
  #|     if (!internalId) {
  #|       internalId = `internal-${nextInternalId++}`;
  #|       internalIds.set(originalValue, internalId);
  #|     }
  #|     if (serialized.internalId) return serialized;
  #|     return { ...serialized, internalId };
  #|   };
  #|
  #|   function toBidiValue(value) {
  #|     if (value === undefined) return { type: "undefined" };
  #|     if (value === null) return { type: "null" };
  #|     const type = typeof value;
  #|     if (type === "boolean") return { type: "boolean", value };
  #|     if (type === "number") {
  #|       if (Number.isNaN(value)) return { type: "number", value: "NaN" };
  #|       if (!Number.isFinite(value)) return { type: "number", value: value > 0 ? "Infinity" : "-Infinity" };
  #|       if (Object.is(value, -0)) return { type: "number", value: "-0" };
  #|       return { type: "number", value };
  #|     }
  #|     if (type === "string") return { type: "string", value };
  #|     if (type === "bigint") return { type: "bigint", value: String(value) };
  #|     if (type === "symbol") return { type: "symbol" };
  #|     if (type === "function") return { type: "function" };
  #|     const objectTag = type === "object" ? Object.prototype.toString.call(value) : "";
  #|     if (objectTag === "[object Generator]" || objectTag === "[object AsyncGenerator]") {
  #|       return { type: "generator" };
  #|     }
  #|     if (globalThis.__bidiProxyInstances && globalThis.__bidiProxyInstances.has(value)) {
  #|       return { type: "proxy" };
  #|     }
  #|     if (value && type === "object" && typeof value.__bidiContextId === "string") {
  #|       return { type: "window", value: { context: String(value.__bidiContextId) } };
  #|     }
  #|     if (value === globalThis || value === globalThis.window) {
  #|       return {
  #|         type: "window",
  #|         value: { context: String(globalThis.__bidiCurrentContext || "default-context") }
  #|       };
  #|     }
  #|     if (value && type === "object" && typeof value.nodeType === "number") {
  #|       return withInternalId(value, toBidiNodeValue(value));
  #|     }
  #|     if (value instanceof RegExp) return { type: "regexp", value: { pattern: value.source, flags: value.flags } };
  #|     if (value instanceof Date) return { type: "date", value: value.toISOString() };
  #|     if (value instanceof Error) return { type: "error" };
  #|     if (value instanceof Promise) return { type: "promise" };
  #|     if (value instanceof Map) {
  #|       const entries = [];
  #|       for (const [k, v] of value) entries.push([typeof k === "string" ? k : toBidiValue(k), toBidiValue(v)]);
  #|       return withInternalId(value, { type: "map", value: entries });
  #|     }
  #|     if (value instanceof Set) {
  #|       return withInternalId(
  #|         value,
  #|         { type: "set", value: Array.from(value).map(toBidiValue) },
  #|       );
  #|     }
  #|     if (value instanceof WeakMap) return { type: "weakmap" };
  #|     if (value instanceof WeakSet) return { type: "weakset" };
  #|     if (ArrayBuffer.isView(value)) return { type: "typedarray" };
  #|     if (value instanceof ArrayBuffer) return { type: "arraybuffer" };
  #|     if (Array.isArray(value)) {
  #|       return withInternalId(
  #|         value,
  #|         { type: "array", value: value.map(toBidiValue) },
  #|       );
  #|     }
  #|     if (value.constructor === Object) {
  #|       const entries = Object.entries(value).map(([k, v]) => [k, toBidiValue(v)]);
  #|       return withInternalId(value, { type: "object", value: entries });
  #|     }
  #|     return { type: "object" };
  #|   }
  #|   if (!globalThis.__bidiHandleStore) globalThis.__bidiHandleStore = new Map();
  #|   if (!globalThis.__bidiHandleContextStore) globalThis.__bidiHandleContextStore = new Map();
  #|   if (typeof globalThis.__bidiNextHandleId !== "number") {
  #|     globalThis.__bidiNextHandleId = 1;
  #|   }
  #|   const attachHandle = (value, serialized, includeHandle) => {
  #|     if (!includeHandle) return serialized;
  #|     if (value === null || value === undefined) return serialized;
  #|     const valueType = typeof value;
  #|     if (valueType !== "object" && valueType !== "function" && valueType !== "symbol") return serialized;
  #|     if (!serialized || typeof serialized !== "object" || serialized.handle) return serialized;
  #|     const handle = `handle-${globalThis.__bidiNextHandleId++}`;
  #|     globalThis.__bidiHandleStore.set(handle, value);
  #|     globalThis.__bidiHandleContextStore.set(
  #|       handle,
  #|       String(globalThis.__bidiCurrentContext || ""),
  #|     );
  #|     return { ...serialized, handle };
  #|   };
  #|   const toBidiValueFn = (value, includeHandle = false) =>
  #|     attachHandle(value, toBidiValue(value), includeHandle);
  #|
  #|   let response;
  #|   try {
  #|     const runInContext = (code) => {
  #|       // Use indirect eval so script.evaluate keeps script-style sloppy mode
  #|       // unless the expression explicitly opts into strict mode.
  #|       return (0, eval)(code);
  #|     };
  #|     let result = runInContext(expression);
  #|     // Await if result is a Promise
  #|     if (result instanceof Promise) {
  #|       result = await result;
  #|     }
  #|     collectReferences(result);
  #|     response = {
  #|       id: requestId,
  #|       type: "success",
  #|       result: unwrapResult
  #|         ? toBidiValueFn(result, !!rootOwnership)
  #|         : {
  #|             realm: realmId,
  #|             result: toBidiValueFn(result, !!rootOwnership)
  #|           }
  #|     };
  #|   } catch (e) {
  #|     const exceptionResult = {
  #|       realm: realmId,
  #|       exceptionDetails: {
  #|         columnNumber: 0,
  #|         lineNumber: 0,
  #|         text: String(e),
  #|         exception: toBidiValueFn(e, !!rootOwnership),
  #|         stackTrace: { callFrames: [] }
  #|       }
  #|     };
  #|     response = {
  #|       id: requestId,
  #|       type: "success",
  #|       result: exceptionResult
  #|     };
  #|   } finally {
  #|     if (captureConsole && originalConsole) {
  #|       console.log = originalConsole.log;
  #|       console.warn = originalConsole.warn;
  #|       console.error = originalConsole.error;
  #|       console.info = originalConsole.info;
  #|       console.debug = originalConsole.debug;
  #|       console.assert = originalConsole.assert;
  #|       console.table = originalConsole.table;
  #|       console.trace = originalConsole.trace;
  #|       console.time = originalConsole.time;
  #|       console.timeEnd = originalConsole.timeEnd;
  #|     }
  #|   }
  #|
  #|   // Send console log events before response
  #|   for (const entry of consoleEntries) {
  #|     const logEvent = {
  #|       type: "event",
  #|       method: "log.entryAdded",
  #|       params: {
  #|         level: entry.level,
  #|         source: { realm: realmId, context: ctxId },
  #|         text: entry.text,
  #|         timestamp: entry.timestamp,
  #|         method: entry.method,
  #|         args: entry.args || [],
  #|         type: "console"
  #|       }
  #|     };
  #|     socket.send(JSON.stringify(logEvent));
  #|   }
  #|
  #|   // Send the response
  #|   socket.send(JSON.stringify(response));
  #| }

///|
/// Evaluate expression asynchronously and send result via WebSocket
fn eval_and_send_async_with_console(
  socket : @core.Any,
  request_id : Int,
  expression : String,
  ctx_id : String,
  realm_id : String,
  capture_console : Bool,
  user_activation : Bool,
  root_ownership : Bool,
  unwrap_result : Bool,
) -> Unit {
  js_eval_and_send_async(
    socket, request_id, expression, ctx_id, realm_id, capture_console, user_activation,
    root_ownership, unwrap_result,
  )
}

///|
/// Evaluate expression asynchronously and send result via WebSocket
pub fn eval_and_send_async(
  socket : @core.Any,
  request_id : Int,
  expression : String,
  ctx_id : String,
) -> Unit {
  eval_and_send_async_with_console(
    socket, request_id, expression, ctx_id, "default-realm", true, false, false,
    false,
  )
}

///|
/// Await a Promise and return result as String
pub fn await_promise(promise : @core.Any) -> String {
  js_await_promise(promise)
}

///|
/// Set current BiDi context for value serialization helpers.
extern "js" fn js_set_runtime_context(ctx_id : String) -> Unit =
  #| (ctxId) => {
  #|   globalThis.__bidiCurrentContext = ctxId;
  #|   if (!globalThis.__bidiContextWindows) globalThis.__bidiContextWindows = new Map();
  #|   if (!globalThis.__bidiContextViewportState) globalThis.__bidiContextViewportState = new Map();
  #|   const resolveViewportState = (id) => {
  #|     const fallback = { width: 1024, height: 768, devicePixelRatio: 1 };
  #|     const map = globalThis.__bidiContextViewportState;
  #|     if (!map || !map.has(id)) return fallback;
  #|     const raw = map.get(id) || {};
  #|     const width = Number(raw.width);
  #|     const height = Number(raw.height);
  #|     const dpr = Number(raw.devicePixelRatio);
  #|     return {
  #|       width: Number.isFinite(width) && width >= 0 ? width : fallback.width,
  #|       height: Number.isFinite(height) && height >= 0 ? height : fallback.height,
  #|       devicePixelRatio: Number.isFinite(dpr) && dpr > 0 ? dpr : fallback.devicePixelRatio,
  #|     };
  #|   };
  #|   const resolveScreenOrientationState = (id) => {
  #|     const fallback = { type: "portrait-primary", angle: 0 };
  #|     const map = globalThis.__bidiContextScreenOrientationState;
  #|     if (!map || !map.has(id)) return fallback;
  #|     const raw = map.get(id) || {};
  #|     const type = typeof raw.type === "string" && raw.type ? raw.type : fallback.type;
  #|     const angle = Number(raw.angle);
  #|     return {
  #|       type,
  #|       angle: Number.isFinite(angle) ? angle : fallback.angle,
  #|     };
  #|   };
  #|   const resolveScreenAreaState = (id, fallbackMetrics) => {
  #|     const fallback = {
  #|       width: fallbackMetrics.width,
  #|       height: fallbackMetrics.height,
  #|       availWidth: fallbackMetrics.width,
  #|       availHeight: fallbackMetrics.height,
  #|     };
  #|     const map = globalThis.__bidiContextScreenAreaState;
  #|     if (!map || !map.has(id)) return fallback;
  #|     const raw = map.get(id) || {};
  #|     const width = Number(raw.width);
  #|     const height = Number(raw.height);
  #|     const availWidth = Number(raw.availWidth);
  #|     const availHeight = Number(raw.availHeight);
  #|     return {
  #|       width: Number.isFinite(width) && width >= 0 ? width : fallback.width,
  #|       height: Number.isFinite(height) && height >= 0 ? height : fallback.height,
  #|       availWidth: Number.isFinite(availWidth) && availWidth >= 0 ? availWidth : fallback.availWidth,
  #|       availHeight: Number.isFinite(availHeight) && availHeight >= 0 ? availHeight : fallback.availHeight,
  #|     };
  #|   };
  #|   const ensureOrientationTarget = (orientation, state) => {
  #|     const target = orientation && typeof orientation === "object" ? orientation : {};
  #|     target.type = state.type;
  #|     target.angle = state.angle;
  #|     if (!target._listeners || typeof target._listeners !== "object") target._listeners = {};
  #|     if (typeof target.addEventListener !== "function") {
  #|       target.addEventListener = function(type, fn) {
  #|         if (!this._listeners[type]) this._listeners[type] = [];
  #|         this._listeners[type].push(fn);
  #|       };
  #|     }
  #|     if (typeof target.removeEventListener !== "function") {
  #|       target.removeEventListener = function(type, fn) {
  #|         if (!this._listeners[type]) return;
  #|         this._listeners[type] = this._listeners[type].filter((entry) => entry !== fn);
  #|       };
  #|     }
  #|     if (typeof target.dispatchEvent !== "function") {
  #|       target.dispatchEvent = function(event) {
  #|         try { event.currentTarget = this; } catch (_e) {}
  #|         try { event.target = this; } catch (_e) {}
  #|         const listeners = this._listeners[event.type] || [];
  #|         for (const fn of listeners) {
  #|           try { fn.call(this, event); } catch (_e) {}
  #|         }
  #|         return !event.defaultPrevented;
  #|       };
  #|     }
  #|     return target;
  #|   };
  #|   const ensureScreenObject = (win, orientationState, screenMetrics) => {
  #|     if (!win || typeof win !== "object") return null;
  #|     const screen = win.screen && typeof win.screen === "object" ? win.screen : {};
  #|     screen.width = screenMetrics.width;
  #|     screen.height = screenMetrics.height;
  #|     screen.availWidth = screenMetrics.availWidth;
  #|     screen.availHeight = screenMetrics.availHeight;
  #|     screen.orientation = ensureOrientationTarget(screen.orientation, orientationState);
  #|     win.screen = screen;
  #|     return screen;
  #|   };
  #|   const metrics = resolveViewportState(String(ctxId));
  #|   const screenOrientationState = resolveScreenOrientationState(String(ctxId));
  #|   const screenAreaState = resolveScreenAreaState(String(ctxId), metrics);
  #|   if (!globalThis.__bidiContextWindows.has(ctxId)) {
  #|     const win = {};
  #|     win.__bidiContextId = String(ctxId);
  #|     win.window = win;
  #|     win.innerWidth = metrics.width;
  #|     win.innerHeight = metrics.height;
  #|     win.outerWidth = metrics.width;
  #|     win.outerHeight = metrics.height;
  #|     win.devicePixelRatio = metrics.devicePixelRatio;
  #|     win.pageXOffset = 0;
  #|     win.pageYOffset = 0;
  #|     win._listeners = {};
  #|     win.addEventListener = function(type, fn) {
  #|       if (!this._listeners[type]) this._listeners[type] = [];
  #|       this._listeners[type].push(fn);
  #|     };
  #|     win.removeEventListener = function(type, fn) {
  #|       if (!this._listeners[type]) return;
  #|       this._listeners[type] = this._listeners[type].filter((f) => f !== fn);
  #|     };
  #|     win.dispatchEvent = function(event) {
  #|       try { event.currentTarget = this; } catch (_e) {}
  #|       const listeners = this._listeners[event.type] || [];
  #|       for (const fn of listeners) {
  #|         try { fn.call(this, event); } catch (_e) {}
  #|       }
  #|       return !event.defaultPrevented;
  #|     };
  #|     globalThis.__bidiContextWindows.set(ctxId, win);
  #|   }
  #|   const contextWindow = globalThis.__bidiContextWindows.get(ctxId);
  #|   if (contextWindow) {
  #|     if (!contextWindow.window) contextWindow.window = contextWindow;
  #|     contextWindow.innerWidth = metrics.width;
  #|     contextWindow.innerHeight = metrics.height;
  #|     contextWindow.outerWidth = metrics.width;
  #|     contextWindow.outerHeight = metrics.height;
  #|     contextWindow.devicePixelRatio = metrics.devicePixelRatio;
  #|     const screen = ensureScreenObject(contextWindow, screenOrientationState, screenAreaState);
  #|     const frameWindows = Array.isArray(contextWindow.frames) ? contextWindow.frames : [];
  #|     globalThis.window = contextWindow;
  #|     contextWindow.matchMedia = globalThis.matchMedia;
  #|     globalThis.frames = frameWindows;
  #|     globalThis.screen = screen;
  #|     globalThis.innerWidth = metrics.width;
  #|     globalThis.innerHeight = metrics.height;
  #|     globalThis.outerWidth = metrics.width;
  #|     globalThis.outerHeight = metrics.height;
  #|     globalThis.devicePixelRatio = metrics.devicePixelRatio;
  #|     if (!globalThis.__bidiContextStorage) globalThis.__bidiContextStorage = new Map();
  #|     const ensureStorage = (kind) => {
  #|       const key = String(ctxId) + ":" + String(kind);
  #|       if (!globalThis.__bidiContextStorage.has(key)) {
  #|         globalThis.__bidiContextStorage.set(key, {});
  #|       }
  #|       const backing = globalThis.__bidiContextStorage.get(key);
  #|       return {
  #|         getItem(name) {
  #|           const storageKey = String(name);
  #|           return Object.prototype.hasOwnProperty.call(backing, storageKey)
  #|             ? backing[storageKey]
  #|             : null;
  #|         },
  #|         setItem(name, value) {
  #|           backing[String(name)] = String(value);
  #|         },
  #|         removeItem(name) {
  #|           delete backing[String(name)];
  #|         },
  #|         clear() {
  #|           for (const storageKey of Object.keys(backing)) {
  #|             delete backing[storageKey];
  #|           }
  #|         },
  #|         get length() {
  #|           return Object.keys(backing).length;
  #|         },
  #|         key(index) {
  #|           const keys = Object.keys(backing);
  #|           return keys[Number(index)] || null;
  #|         }
  #|       };
  #|     };
  #|     if (!contextWindow.localStorage) contextWindow.localStorage = ensureStorage("localStorage");
  #|     if (!contextWindow.sessionStorage) contextWindow.sessionStorage = ensureStorage("sessionStorage");
  #|     globalThis.localStorage = contextWindow.localStorage;
  #|     globalThis.sessionStorage = contextWindow.sessionStorage;
  #|     if (typeof contextWindow.alert !== "function") {
  #|       contextWindow.alert = function(_message) { return undefined; };
  #|     }
  #|     if (typeof contextWindow.confirm !== "function") {
  #|       contextWindow.confirm = function(_message) { return false; };
  #|     }
  #|     if (typeof contextWindow.prompt !== "function") {
  #|       contextWindow.prompt = function(_message, defaultValue) {
  #|         return defaultValue === undefined ? "" : String(defaultValue);
  #|       };
  #|     }
  #|     globalThis.alert = contextWindow.alert.bind(contextWindow);
  #|     globalThis.confirm = contextWindow.confirm.bind(contextWindow);
  #|     globalThis.prompt = contextWindow.prompt.bind(contextWindow);
  #|     if (contextWindow.document && typeof contextWindow.document === "object") {
  #|       globalThis.document = contextWindow.document;
  #|     } else if (globalThis.document && typeof globalThis.document === "object") {
  #|       contextWindow.document = globalThis.document;
  #|     }
  #|     if (contextWindow.location && typeof contextWindow.location === "object") {
  #|       globalThis.location = contextWindow.location;
  #|       try { globalThis.__pageUrl = String(contextWindow.location.href || "about:blank"); } catch (_e) {}
  #|     } else {
  #|       const locationHref = "about:blank";
  #|       contextWindow.location = {
  #|         href: locationHref,
  #|         origin: '',
  #|         protocol: 'about:',
  #|         host: '',
  #|         hostname: '',
  #|         port: '',
  #|         pathname: 'blank',
  #|         search: '',
  #|         hash: '',
  #|         assign: function(url) { const next = String(url); globalThis.__pageUrl = next; this.href = next; },
  #|         replace: function(url) { const next = String(url); globalThis.__pageUrl = next; this.href = next; },
  #|         reload: function() {}
  #|       };
  #|       globalThis.location = contextWindow.location;
  #|       globalThis.__pageUrl = locationHref;
  #|     }
  #|   }
  #| }

///|
/// Set current BiDi context for value serialization helpers.
pub fn set_runtime_context(ctx_id : String) -> Unit {
  js_set_runtime_context(ctx_id)
}

///|
/// Reset runtime event buffers/listeners for a specific context.
extern "js" fn js_reset_runtime_event_buffers(ctx_id : String) -> Unit =
  #| (ctxId) => {
  #|   try {
  #|     if (globalThis.__bidiContextWindows && globalThis.__bidiContextWindows.has(ctxId)) {
  #|       const win = globalThis.__bidiContextWindows.get(ctxId);
  #|       if (win && typeof win === "object") {
  #|         if (!win.allEvents || !Array.isArray(win.allEvents.events)) {
  #|           win.allEvents = { events: [] };
  #|         } else {
  #|           win.allEvents.events.length = 0;
  #|         }
  #|         if (win._listeners && typeof win._listeners === "object") {
  #|           win._listeners = {};
  #|         }
  #|         try { win.__bidiFocusedElement = null; } catch (_e) {}
  #|         win.__craterAllEventsFallbackInit = false;
  #|         win.__bidiLastClickHref = null;
  #|       }
  #|     }
  #|     if (globalThis.allEvents && Array.isArray(globalThis.allEvents.events)) {
  #|       globalThis.allEvents.events.length = 0;
  #|     } else {
  #|       globalThis.allEvents = { events: [] };
  #|     }
  #|     if (
  #|       globalThis.document &&
  #|       globalThis.document._listeners &&
  #|       typeof globalThis.document._listeners === "object"
  #|     ) {
  #|       globalThis.document._listeners = {};
  #|     }
  #|     try { globalThis.__bidiFocusedElement = null; } catch (_e) {}
  #|     globalThis.__bidiLastClickHref = null;
  #|   } catch (_e) {}
  #| }

///|
/// Reset runtime event buffers/listeners for a specific context.
pub fn reset_runtime_event_buffers(ctx_id : String) -> Unit {
  js_reset_runtime_event_buffers(ctx_id)
}

///|
/// Set frame window contexts for current runtime context.
extern "js" fn js_set_runtime_context_frames(
  ctx_id : String,
  frame_ctx_ids : Array[String],
) -> Unit =
  #| (ctxId, frameCtxIds) => {
  #|   if (!globalThis.__bidiContextWindows) globalThis.__bidiContextWindows = new Map();
  #|   if (!globalThis.__bidiContextViewportState) globalThis.__bidiContextViewportState = new Map();
  #|   const resolveViewportState = (id) => {
  #|     const fallback = { width: 1024, height: 768, devicePixelRatio: 1 };
  #|     const map = globalThis.__bidiContextViewportState;
  #|     if (!map || !map.has(id)) return fallback;
  #|     const raw = map.get(id) || {};
  #|     const width = Number(raw.width);
  #|     const height = Number(raw.height);
  #|     const dpr = Number(raw.devicePixelRatio);
  #|     return {
  #|       width: Number.isFinite(width) && width >= 0 ? width : fallback.width,
  #|       height: Number.isFinite(height) && height >= 0 ? height : fallback.height,
  #|       devicePixelRatio: Number.isFinite(dpr) && dpr > 0 ? dpr : fallback.devicePixelRatio,
  #|     };
  #|   };
  #|   const ensureWindow = (id) => {
  #|     if (!globalThis.__bidiContextWindows.has(id)) {
  #|       const metrics = resolveViewportState(String(id));
  #|       const win = {};
  #|       win.__bidiContextId = String(id);
  #|       win.window = win;
  #|       win.innerWidth = metrics.width;
  #|       win.innerHeight = metrics.height;
  #|       win.outerWidth = metrics.width;
  #|       win.outerHeight = metrics.height;
  #|       win.devicePixelRatio = metrics.devicePixelRatio;
  #|       win.pageXOffset = 0;
  #|       win.pageYOffset = 0;
  #|       win._listeners = {};
  #|       win.addEventListener = function(type, fn) {
  #|         if (!this._listeners[type]) this._listeners[type] = [];
  #|         this._listeners[type].push(fn);
  #|       };
  #|       win.removeEventListener = function(type, fn) {
  #|         if (!this._listeners[type]) return;
  #|         this._listeners[type] = this._listeners[type].filter((f) => f !== fn);
  #|       };
  #|       win.dispatchEvent = function(event) {
  #|         try { event.currentTarget = this; } catch (_e) {}
  #|         const listeners = this._listeners[event.type] || [];
  #|         for (const fn of listeners) {
  #|           try { fn.call(this, event); } catch (_e) {}
  #|         }
  #|         return !event.defaultPrevented;
  #|       };
  #|       globalThis.__bidiContextWindows.set(id, win);
  #|     }
  #|     return globalThis.__bidiContextWindows.get(id);
  #|   };
  #|   const currentWindow = ensureWindow(ctxId);
  #|   const frames = Array.isArray(frameCtxIds)
  #|     ? frameCtxIds.map((id) => ensureWindow(String(id)))
  #|     : [];
  #|   currentWindow.frames = frames;
  #|   globalThis.frames = frames;
  #| }

///|
/// Set frame window contexts for current runtime context.
pub fn set_runtime_context_frames(
  ctx_id : String,
  frame_ctx_ids : Array[String],
) -> Unit {
  js_set_runtime_context_frames(ctx_id, frame_ctx_ids)
}

///|
/// Set runtime viewport metrics for a specific context.
extern "js" fn js_set_runtime_context_viewport(
  ctx_id : String,
  width : Int,
  height : Int,
  device_pixel_ratio : Double,
) -> Unit =
  #| (ctxId, width, height, devicePixelRatio) => {
  #|   if (!globalThis.__bidiContextViewportState) globalThis.__bidiContextViewportState = new Map();
  #|   const w = Number(width);
  #|   const h = Number(height);
  #|   const dpr = Number(devicePixelRatio);
  #|   const normalized = {
  #|     width: Number.isFinite(w) && w >= 0 ? w : 1024,
  #|     height: Number.isFinite(h) && h >= 0 ? h : 768,
  #|     devicePixelRatio: Number.isFinite(dpr) && dpr > 0 ? dpr : 1,
  #|   };
  #|   globalThis.__bidiContextViewportState.set(String(ctxId), normalized);
  #|   if (globalThis.__bidiContextWindows && globalThis.__bidiContextWindows.has(ctxId)) {
  #|     const win = globalThis.__bidiContextWindows.get(ctxId);
  #|     if (win && typeof win === "object") {
  #|       win.innerWidth = normalized.width;
  #|       win.innerHeight = normalized.height;
  #|       win.outerWidth = normalized.width;
  #|       win.outerHeight = normalized.height;
  #|       win.devicePixelRatio = normalized.devicePixelRatio;
  #|     }
  #|   }
  #|   if (String(globalThis.__bidiCurrentContext || "") === String(ctxId)) {
  #|     globalThis.innerWidth = normalized.width;
  #|     globalThis.innerHeight = normalized.height;
  #|     globalThis.outerWidth = normalized.width;
  #|     globalThis.outerHeight = normalized.height;
  #|     globalThis.devicePixelRatio = normalized.devicePixelRatio;
  #|   }
  #| }

///|
/// Set runtime viewport metrics for a specific context.
pub fn set_runtime_context_viewport(
  ctx_id : String,
  width : Int,
  height : Int,
  device_pixel_ratio : Double,
) -> Unit {
  js_set_runtime_context_viewport(ctx_id, width, height, device_pixel_ratio)
}

///|
/// Set runtime navigator.userAgent for a specific context.
extern "js" fn js_set_runtime_context_user_agent(
  ctx_id : String,
  user_agent : String,
) -> Unit =
  #| (ctxId, userAgent) => {
  #|   const normalized = String(userAgent ?? "Crater/1.0 (MoonBit; BiDi)");
  #|   const patchNavigator = globalThis.__bidiPatchNavigatorTarget;
  #|   if (globalThis.__bidiContextWindows && globalThis.__bidiContextWindows.has(ctxId)) {
  #|     const win = globalThis.__bidiContextWindows.get(ctxId);
  #|     if (win && typeof win === "object") {
  #|       patchNavigator(win, { userAgent: normalized });
  #|     }
  #|   }
  #|   if (String(globalThis.__bidiCurrentContext || "") === String(ctxId)) {
  #|     patchNavigator(globalThis, { userAgent: normalized });
  #|   }
  #| }

///|
/// Set runtime navigator.userAgent for a specific context.
pub fn set_runtime_context_user_agent(
  ctx_id : String,
  user_agent : String,
) -> Unit {
  ensure_runtime_navigator_patch_helper()
  js_set_runtime_context_user_agent(ctx_id, user_agent)
}

///|
/// Set runtime navigator.language(s) for a specific context.
extern "js" fn js_set_runtime_context_locale(
  ctx_id : String,
  locale : String,
) -> Unit =
  #| (ctxId, locale) => {
  #|   const normalized = String(locale ?? "en-US");
  #|   const languages = [normalized];
  #|   const patchNavigator = globalThis.__bidiPatchNavigatorTarget;
  #|   if (globalThis.__bidiContextWindows && globalThis.__bidiContextWindows.has(ctxId)) {
  #|     const win = globalThis.__bidiContextWindows.get(ctxId);
  #|     if (win && typeof win === "object") {
  #|       patchNavigator(win, { language: normalized, languages });
  #|     }
  #|   }
  #|   if (String(globalThis.__bidiCurrentContext || "") === String(ctxId)) {
  #|     patchNavigator(globalThis, { language: normalized, languages });
  #|   }
  #| }

///|
/// Set runtime navigator.language(s) for a specific context.
pub fn set_runtime_context_locale(ctx_id : String, locale : String) -> Unit {
  ensure_runtime_navigator_patch_helper()
  js_set_runtime_context_locale(ctx_id, locale)
}

///|
extern "js" fn js_set_runtime_context_network_online(
  ctx_id : String,
  is_online : Bool,
) -> Unit =
  #| (ctxId, isOnline) => {
  #|   const normalized = !!isOnline;
  #|   const dispatchStateEvent = (target, type) => {
  #|     if (!target || typeof target.dispatchEvent !== "function") return;
  #|     let event;
  #|     if (typeof globalThis.__bidiCreateEvent === "function") {
  #|       event = globalThis.__bidiCreateEvent(type, { bubbles: false, cancelable: false });
  #|     } else {
  #|       event = { type, bubbles: false, cancelable: false, defaultPrevented: false };
  #|     }
  #|     try { event.isTrusted = true; } catch (_e) {}
  #|     try { target.dispatchEvent(event); } catch (_e) {}
  #|   };
  #|   const patchNavigator = globalThis.__bidiPatchNavigatorTarget;
  #|   const ensureNavigator = (target) => patchNavigator(target, { onLine: normalized });
  #|   let contextWindow = null;
  #|   let previousOnline = null;
  #|   if (globalThis.__bidiContextWindows && globalThis.__bidiContextWindows.has(ctxId)) {
  #|     contextWindow = globalThis.__bidiContextWindows.get(ctxId);
  #|     const navigator = ensureNavigator(contextWindow);
  #|     if (navigator) {
  #|       previousOnline = navigator.onLine !== false;
  #|       navigator.onLine = normalized;
  #|     }
  #|   }
  #|   if (String(globalThis.__bidiCurrentContext || "") === String(ctxId)) {
  #|     const globalNavigator = ensureNavigator(globalThis);
  #|     if (globalNavigator) globalNavigator.onLine = normalized;
  #|     const activeWindow = globalThis.window && typeof globalThis.window === "object"
  #|       ? globalThis.window
  #|       : null;
  #|     if (activeWindow && activeWindow !== contextWindow) {
  #|       const windowNavigator = ensureNavigator(activeWindow);
  #|       if (windowNavigator) {
  #|         const prev = windowNavigator.onLine !== false;
  #|         windowNavigator.onLine = normalized;
  #|         if (prev !== normalized) {
  #|           dispatchStateEvent(activeWindow, normalized ? "online" : "offline");
  #|         }
  #|       }
  #|     }
  #|   }
  #|   if (contextWindow && previousOnline !== null && previousOnline !== normalized) {
  #|     dispatchStateEvent(contextWindow, normalized ? "online" : "offline");
  #|   }
  #| }

///|
pub fn set_runtime_context_network_online(
  ctx_id : String,
  is_online : Bool,
) -> Unit {
  ensure_runtime_navigator_patch_helper()
  js_set_runtime_context_network_online(ctx_id, is_online)
}

///|
extern "js" fn js_set_runtime_context_screen_orientation(
  ctx_id : String,
  orientation_type : String,
  angle : Int,
) -> Unit =
  #| (ctxId, orientationType, angle) => {
  #|   if (!globalThis.__bidiContextScreenOrientationState) {
  #|     globalThis.__bidiContextScreenOrientationState = new Map();
  #|   }
  #|   const normalizedType =
  #|     typeof orientationType === "string" && orientationType
  #|       ? orientationType
  #|       : "portrait-primary";
  #|   const normalizedAngle = Number.isFinite(Number(angle)) ? Number(angle) : 0;
  #|   globalThis.__bidiContextScreenOrientationState.set(String(ctxId), {
  #|     type: normalizedType,
  #|     angle: normalizedAngle,
  #|   });
  #|   const dispatchChange = (target) => {
  #|     if (!target || typeof target.dispatchEvent !== "function") return;
  #|     let event;
  #|     if (typeof globalThis.__bidiCreateEvent === "function") {
  #|       event = globalThis.__bidiCreateEvent("change", { bubbles: false, cancelable: false });
  #|     } else {
  #|       event = { type: "change", bubbles: false, cancelable: false, defaultPrevented: false };
  #|     }
  #|     try { event.isTrusted = true; } catch (_e) {}
  #|     try { event.target = target; } catch (_e) {}
  #|     try { target.dispatchEvent(event); } catch (_e) {}
  #|   };
  #|   const ensureOrientationTarget = (orientation) => {
  #|     const target = orientation && typeof orientation === "object" ? orientation : {};
  #|     if (!target._listeners || typeof target._listeners !== "object") target._listeners = {};
  #|     if (typeof target.addEventListener !== "function") {
  #|       target.addEventListener = function(type, fn) {
  #|         if (!this._listeners[type]) this._listeners[type] = [];
  #|         this._listeners[type].push(fn);
  #|       };
  #|     }
  #|     if (typeof target.removeEventListener !== "function") {
  #|       target.removeEventListener = function(type, fn) {
  #|         if (!this._listeners[type]) return;
  #|         this._listeners[type] = this._listeners[type].filter((entry) => entry !== fn);
  #|       };
  #|     }
  #|     if (typeof target.dispatchEvent !== "function") {
  #|       target.dispatchEvent = function(event) {
  #|         try { event.currentTarget = this; } catch (_e) {}
  #|         try { event.target = this; } catch (_e) {}
  #|         const listeners = this._listeners[event.type] || [];
  #|         for (const fn of listeners) {
  #|           try { fn.call(this, event); } catch (_e) {}
  #|         }
  #|         return !event.defaultPrevented;
  #|       };
  #|     }
  #|     return target;
  #|   };
  #|   const ensureScreenObject = (target) => {
  #|     if (!target || typeof target !== "object") return null;
  #|     const screen = target.screen && typeof target.screen === "object" ? target.screen : {};
  #|     screen.orientation = ensureOrientationTarget(screen.orientation);
  #|     target.screen = screen;
  #|     return screen;
  #|   };
  #|   const apply = (target) => {
  #|     const screen = ensureScreenObject(target);
  #|     if (!screen || !screen.orientation) return;
  #|     const orientation = screen.orientation;
  #|     const previousType = typeof orientation.type === "string" ? orientation.type : "";
  #|     const previousAngle = Number.isFinite(Number(orientation.angle)) ? Number(orientation.angle) : 0;
  #|     orientation.type = normalizedType;
  #|     orientation.angle = normalizedAngle;
  #|     if (previousType !== normalizedType || previousAngle !== normalizedAngle) {
  #|       dispatchChange(orientation);
  #|     }
  #|   };
  #|   let contextWindow = null;
  #|   if (globalThis.__bidiContextWindows && globalThis.__bidiContextWindows.has(ctxId)) {
  #|     contextWindow = globalThis.__bidiContextWindows.get(ctxId);
  #|     apply(contextWindow);
  #|   }
  #|   if (String(globalThis.__bidiCurrentContext || "") === String(ctxId)) {
  #|     const activeWindow = globalThis.window && typeof globalThis.window === "object"
  #|       ? globalThis.window
  #|       : globalThis;
  #|     if (activeWindow !== contextWindow) {
  #|       apply(activeWindow);
  #|     }
  #|     if (globalThis.window && typeof globalThis.window === "object" && globalThis.window.screen) {
  #|       globalThis.screen = globalThis.window.screen;
  #|     }
  #|   }
  #| }

///|
pub fn set_runtime_context_screen_orientation(
  ctx_id : String,
  orientation_type : String,
  angle : Int,
) -> Unit {
  js_set_runtime_context_screen_orientation(ctx_id, orientation_type, angle)
}

///|
extern "js" fn js_set_runtime_context_screen_area(
  ctx_id : String,
  width : Int,
  height : Int,
  avail_width : Int,
  avail_height : Int,
) -> Unit =
  #| (ctxId, width, height, availWidth, availHeight) => {
  #|   if (!globalThis.__bidiContextScreenAreaState) {
  #|     globalThis.__bidiContextScreenAreaState = new Map();
  #|   }
  #|   const normalizedWidth = Number.isFinite(Number(width)) && Number(width) >= 0 ? Number(width) : 1024;
  #|   const normalizedHeight = Number.isFinite(Number(height)) && Number(height) >= 0 ? Number(height) : 768;
  #|   const normalizedAvailWidth = Number.isFinite(Number(availWidth)) && Number(availWidth) >= 0
  #|     ? Number(availWidth)
  #|     : normalizedWidth;
  #|   const normalizedAvailHeight = Number.isFinite(Number(availHeight)) && Number(availHeight) >= 0
  #|     ? Number(availHeight)
  #|     : normalizedHeight;
  #|   globalThis.__bidiContextScreenAreaState.set(String(ctxId), {
  #|     width: normalizedWidth,
  #|     height: normalizedHeight,
  #|     availWidth: normalizedAvailWidth,
  #|     availHeight: normalizedAvailHeight,
  #|   });
  #|   const apply = (target) => {
  #|     if (!target || typeof target !== "object") return null;
  #|     const screen = target.screen && typeof target.screen === "object" ? target.screen : {};
  #|     screen.width = normalizedWidth;
  #|     screen.height = normalizedHeight;
  #|     screen.availWidth = normalizedAvailWidth;
  #|     screen.availHeight = normalizedAvailHeight;
  #|     target.screen = screen;
  #|     return screen;
  #|   };
  #|   let contextWindow = null;
  #|   if (globalThis.__bidiContextWindows && globalThis.__bidiContextWindows.has(ctxId)) {
  #|     contextWindow = globalThis.__bidiContextWindows.get(ctxId);
  #|     apply(contextWindow);
  #|   }
  #|   if (String(globalThis.__bidiCurrentContext || "") === String(ctxId)) {
  #|     const activeWindow = globalThis.window && typeof globalThis.window === "object"
  #|       ? globalThis.window
  #|       : globalThis;
  #|     const screen = activeWindow === contextWindow ? activeWindow.screen : apply(activeWindow);
  #|     if (screen) {
  #|       globalThis.screen = screen;
  #|     }
  #|   }
  #| }

///|
pub fn set_runtime_context_screen_area(
  ctx_id : String,
  width : Int,
  height : Int,
  avail_width : Int,
  avail_height : Int,
) -> Unit {
  js_set_runtime_context_screen_area(
    ctx_id, width, height, avail_width, avail_height,
  )
}

///|
/// Check if runtime handle exists in current JS handle store.
extern "js" fn js_has_runtime_handle(handle_id : String) -> Bool =
  #| (handleId) => {
  #|   const store = globalThis.__bidiHandleStore;
  #|   if (!store || !store.has(handleId)) return false;
  #|   const contextStore = globalThis.__bidiHandleContextStore;
  #|   if (!contextStore || !contextStore.has(handleId)) return true;
  #|   return (
  #|     String(contextStore.get(handleId)) ===
  #|     String(globalThis.__bidiCurrentContext || "")
  #|   );
  #| }

///|
/// Check if runtime handle exists in current JS handle store.
pub fn has_runtime_handle(handle_id : String) -> Bool {
  js_has_runtime_handle(handle_id)
}

///|
/// Remove handle from current JS handle store (no-op when absent).
extern "js" fn js_delete_runtime_handle(handle_id : String) -> Unit =
  #| (handleId) => {
  #|   const store = globalThis.__bidiHandleStore;
  #|   if (!store) return;
  #|   const contextStore = globalThis.__bidiHandleContextStore;
  #|   if (contextStore && contextStore.has(handleId)) {
  #|     const owner = String(contextStore.get(handleId));
  #|     const current = String(globalThis.__bidiCurrentContext || "");
  #|     if (owner !== current) return;
  #|     contextStore.delete(handleId);
  #|   }
  #|   store.delete(handleId);
  #| }

///|
/// Remove handle from current JS handle store (no-op when absent).
pub fn delete_runtime_handle(handle_id : String) -> Unit {
  js_delete_runtime_handle(handle_id)
}

///|
/// Check if runtime shared node exists in current JS shared node store.
extern "js" fn js_has_runtime_shared_node(shared_id : String) -> Bool =
  #| (sharedId) => {
  #|   return !!(globalThis.__bidiSharedNodeStore && globalThis.__bidiSharedNodeStore.has(sharedId));
  #| }

///|
/// Check if runtime shared node exists in current JS shared node store.
pub fn has_runtime_shared_node(shared_id : String) -> Bool {
  js_has_runtime_shared_node(shared_id)
}

///|
/// Check if runtime shared node exists and is an element node.
extern "js" fn js_runtime_shared_node_is_element(shared_id : String) -> Bool =
  #| (sharedId) => {
  #|   const store = globalThis.__bidiSharedNodeStore;
  #|   if (!store) return false;
  #|   const node = store.get(sharedId);
  #|   return !!(node && node.nodeType === 1);
  #| }

///|
/// Check if runtime shared node exists and is an element node.
pub fn runtime_shared_node_is_element(shared_id : String) -> Bool {
  js_runtime_shared_node_is_element(shared_id)
}

///|
/// Check if runtime shared node exists and is a document node.
extern "js" fn js_runtime_shared_node_is_document(shared_id : String) -> Bool =
  #| (sharedId) => {
  #|   const store = globalThis.__bidiSharedNodeStore;
  #|   if (!store) return false;
  #|   const node = store.get(sharedId);
  #|   return !!(node && node.nodeType === 9);
  #| }

///|
/// Check if runtime shared node exists and is a document node.
pub fn runtime_shared_node_is_document(shared_id : String) -> Bool {
  js_runtime_shared_node_is_document(shared_id)
}

///|
/// Check if runtime shared node exists and is a shadow root node.
extern "js" fn js_runtime_shared_node_is_shadow_root(
  shared_id : String,
) -> Bool =
  #| (sharedId) => {
  #|   const store = globalThis.__bidiSharedNodeStore;
  #|   if (!store) return false;
  #|   const node = store.get(sharedId);
  #|   return !!(node && node.nodeType === 11 && node.host);
  #| }

///|
/// Check if runtime shared node exists and is a shadow root node.
pub fn runtime_shared_node_is_shadow_root(shared_id : String) -> Bool {
  js_runtime_shared_node_is_shadow_root(shared_id)
}

///|
/// Check if runtime shared node has draggable attribute enabled.
extern "js" fn js_runtime_shared_node_is_draggable(shared_id : String) -> Bool =
  #| (sharedId) => {
  #|   const store = globalThis.__bidiSharedNodeStore;
  #|   if (!store) return false;
  #|   const node = store.get(sharedId);
  #|   if (!node || node.nodeType !== 1) return false;
  #|   let draggable = null;
  #|   if (typeof node.getAttribute === "function") {
  #|     try { draggable = node.getAttribute("draggable"); } catch (_e) {}
  #|   }
  #|   if ((draggable === null || draggable === undefined) && node._attrs) {
  #|     draggable = node._attrs.draggable;
  #|   }
  #|   if (draggable === null || draggable === undefined) return false;
  #|   if (draggable === true) return true;
  #|   const value = String(draggable).toLowerCase();
  #|   return value === "" || value === "true";
  #| }

///|
/// Check if runtime shared node has draggable attribute enabled.
pub fn runtime_shared_node_is_draggable(shared_id : String) -> Bool {
  js_runtime_shared_node_is_draggable(shared_id)
}

///|
/// Get center coordinate of shared element as JSON string.
extern "js" fn js_runtime_shared_node_center_json(shared_id : String) -> String =
  #| (sharedId) => {
  #|   const store = globalThis.__bidiSharedNodeStore;
  #|   const node = store && store.get(sharedId);
  #|   if (!node || node.nodeType !== 1) {
  #|     return JSON.stringify({ ok: false });
  #|   }
  #|   let x = 0;
  #|   let y = 0;
  #|   if (typeof node.getBoundingClientRect === "function") {
  #|     try {
  #|       const rect = node.getBoundingClientRect();
  #|       if (rect && typeof rect.left === "number" && typeof rect.top === "number") {
  #|         const left = Number(rect.left);
  #|         const top = Number(rect.top);
  #|         const right = typeof rect.right === "number"
  #|           ? Number(rect.right)
  #|           : left + (typeof rect.width === "number" ? Number(rect.width) : 0);
  #|         const bottom = typeof rect.bottom === "number"
  #|           ? Number(rect.bottom)
  #|           : top + (typeof rect.height === "number" ? Number(rect.height) : 0);
  #|         const viewportWidth =
  #|           Number(
  #|             (globalThis.window && globalThis.window.innerWidth) ||
  #|             (globalThis.document &&
  #|               globalThis.document.documentElement &&
  #|               globalThis.document.documentElement.clientWidth) ||
  #|             1024
  #|           );
  #|         const viewportHeight =
  #|           Number(
  #|             (globalThis.window && globalThis.window.innerHeight) ||
  #|             (globalThis.document &&
  #|               globalThis.document.documentElement &&
  #|               globalThis.document.documentElement.clientHeight) ||
  #|             768
  #|           );
  #|         const clippedLeft = Math.max(0, Math.min(left, right));
  #|         const clippedRight = Math.min(viewportWidth, Math.max(left, right));
  #|         const clippedTop = Math.max(0, Math.min(top, bottom));
  #|         const clippedBottom = Math.min(viewportHeight, Math.max(top, bottom));
  #|         if (clippedRight > clippedLeft && clippedBottom > clippedTop) {
  #|           x = (clippedLeft + clippedRight) / 2;
  #|           y = (clippedTop + clippedBottom) / 2;
  #|         } else {
  #|           x = (left + right) / 2;
  #|           y = (top + bottom) / 2;
  #|         }
  #|       }
  #|     } catch (_e) {}
  #|   }
  #|   if (x === 0 && y === 0) {
  #|     const style = node._style || node.style || {};
  #|     const left = Number.parseFloat(style.left ?? "0");
  #|     const top = Number.parseFloat(style.top ?? "0");
  #|     const width = Number.parseFloat(style.width ?? "0");
  #|     const height = Number.parseFloat(style.height ?? "0");
  #|     const safe = (n) => Number.isFinite(n) ? n : 0;
  #|     x = safe(left) + safe(width) / 2;
  #|     y = safe(top) + safe(height) / 2;
  #|   }
  #|   return JSON.stringify({ ok: true, x, y });
  #| }

///|
/// Get center coordinate of shared element as JSON string.
pub fn get_runtime_shared_node_center_json(shared_id : String) -> String {
  js_runtime_shared_node_center_json(shared_id)
}

///|
/// Resolve shared node at viewport point, allocating sharedId if needed.
extern "js" fn js_runtime_shared_node_at_point(
  x : Double,
  y : Double,
) -> String? =
  #| (x, y) => {
  #|   const doc = globalThis.document;
  #|   if (!doc || typeof doc.elementFromPoint !== "function") return null;
  #|   let node = null;
  #|   try { node = doc.elementFromPoint(Number(x), Number(y)); } catch (_e) {}
  #|   if (!node) return null;
  #|   const sharedIds = globalThis.__bidiNodeSharedIds || (globalThis.__bidiNodeSharedIds = new WeakMap());
  #|   const nodeStore = globalThis.__bidiSharedNodeStore || (globalThis.__bidiSharedNodeStore = new Map());
  #|   if (typeof globalThis.__bidiNextNodeSharedId !== "number") {
  #|     globalThis.__bidiNextNodeSharedId = 1;
  #|   }
  #|   let sharedId = sharedIds.get(node);
  #|   if (!sharedId) {
  #|     sharedId = `node-${globalThis.__bidiNextNodeSharedId++}`;
  #|     sharedIds.set(node, sharedId);
  #|   }
  #|   nodeStore.set(sharedId, node);
  #|   return sharedId;
  #| }

///|
/// Resolve shared node at viewport point, allocating sharedId if needed.
pub fn get_runtime_shared_node_at_point(x : Double, y : Double) -> String? {
  js_runtime_shared_node_at_point(x, y)
}

///|
/// Resolve href attribute from a shared element node.
extern "js" fn js_runtime_shared_node_href(shared_id : String) -> String? =
  #| (sharedId) => {
  #|   const store = globalThis.__bidiSharedNodeStore;
  #|   const node = store && store.get(sharedId);
  #|   if (!node || node.nodeType !== 1) return "";
  #|   let href = null;
  #|   try {
  #|     if (typeof node.getAttribute === "function") {
  #|       href = node.getAttribute("href");
  #|     }
  #|   } catch (_e) {}
  #|   if ((href === null || href === undefined || href === "") && node._attrs) {
  #|     href = node._attrs.href;
  #|   }
  #|   if (href === null || href === undefined || href === "") return "";
  #|   const rawHref = String(href);
  #|   try {
  #|     const base =
  #|       (globalThis.location && globalThis.location.href) ||
  #|       globalThis.__pageUrl ||
  #|       "about:blank";
  #|     return new URL(rawHref, base).href;
  #|   } catch (_e) {
  #|     return rawHref;
  #|   }
  #| }

///|
/// Resolve href attribute from a shared element node.
pub fn get_runtime_shared_node_href(shared_id : String) -> String? {
  js_runtime_shared_node_href(shared_id)
}

///|
/// Resolve absolute href from an anchor identified by id or global symbol.
extern "js" fn js_runtime_anchor_href_by_id(anchor_id : String) -> String? =
  #| (anchorId) => {
  #|   const id = String(anchorId || "");
  #|   if (!id) return "";
  #|   const doc = globalThis.document;
  #|   if (!doc) return "";
  #|   let node = null;
  #|   try {
  #|     if (typeof doc.getElementById === "function") {
  #|       node = doc.getElementById(id);
  #|     }
  #|   } catch (_e) {}
  #|   if (!node) {
  #|     try {
  #|       const candidate = globalThis[id];
  #|       if (candidate && typeof candidate === "object") {
  #|         node = candidate;
  #|       }
  #|     } catch (_e) {}
  #|   }
  #|   if (!node) return "";
  #|   let href = null;
  #|   try {
  #|     if (typeof node.getAttribute === "function") {
  #|       href = node.getAttribute("href");
  #|     }
  #|   } catch (_e) {}
  #|   if ((href === null || href === undefined || href === "") && node._attrs) {
  #|     href = node._attrs.href;
  #|   }
  #|   if (href === null || href === undefined || href === "") return "";
  #|   const rawHref = String(href);
  #|   try {
  #|     const base =
  #|       (globalThis.location && globalThis.location.href) ||
  #|       globalThis.__pageUrl ||
  #|       "about:blank";
  #|     return new URL(rawHref, base).href;
  #|   } catch (_e) {
  #|     return rawHref;
  #|   }
  #| }

///|
/// Resolve absolute href from an anchor identified by id or global symbol.
pub fn get_runtime_anchor_href_by_id(anchor_id : String) -> String? {
  js_runtime_anchor_href_by_id(anchor_id)
}

///|
/// Resolve `download` attribute value from an anchor identified by id or global symbol.
extern "js" fn js_runtime_anchor_download_attr_by_id(
  anchor_id : String,
) -> String? =
  #| (anchorId) => {
  #|   const id = String(anchorId || "");
  #|   if (!id) return "";
  #|   const doc = globalThis.document;
  #|   if (!doc) return "";
  #|   let node = null;
  #|   try {
  #|     if (typeof doc.getElementById === "function") {
  #|       node = doc.getElementById(id);
  #|     }
  #|   } catch (_e) {}
  #|   if (!node) {
  #|     try {
  #|       const candidate = globalThis[id];
  #|       if (candidate && typeof candidate === "object") {
  #|         node = candidate;
  #|       }
  #|     } catch (_e) {}
  #|   }
  #|   if (!node) return "";
  #|   let value = null;
  #|   try {
  #|     if (typeof node.getAttribute === "function") {
  #|       value = node.getAttribute("download");
  #|     }
  #|   } catch (_e) {}
  #|   if ((value === null || value === undefined) && node._attrs) {
  #|     value = node._attrs.download;
  #|   }
  #|   if (value === null || value === undefined) return "";
  #|   return String(value);
  #| }

///|
/// Resolve `download` attribute value from an anchor identified by id or global symbol.
pub fn get_runtime_anchor_download_attr_by_id(anchor_id : String) -> String? {
  js_runtime_anchor_download_attr_by_id(anchor_id)
}

///|
/// Extract query parameter value from an URL string.
extern "js" fn js_runtime_url_query_param(
  url : String,
  key : String,
) -> String? =
  #| (url, key) => {
  #|   const rawUrl = String(url || "");
  #|   const rawKey = String(key || "");
  #|   if (!rawUrl || !rawKey) return "";
  #|   try {
  #|     const base =
  #|       (globalThis.location && globalThis.location.href) ||
  #|       globalThis.__pageUrl ||
  #|       "about:blank";
  #|     const parsed = new URL(rawUrl, base);
  #|     const value = parsed.searchParams.get(rawKey);
  #|     if (value === null || value === undefined) return "";
  #|     return String(value);
  #|   } catch (_e) {
  #|     return "";
  #|   }
  #| }

///|
/// Extract query parameter value from an URL string.
pub fn get_runtime_url_query_param(url : String, key : String) -> String? {
  js_runtime_url_query_param(url, key)
}

///|
/// Write UTF-8 text file for synthetic download tests.
extern "js" fn js_runtime_write_text_file(
  path : String,
  content : String,
) -> Unit =
  #| (path, content) => {
  #|   const filePath = String(path || "");
  #|   if (!filePath) return;
  #|   try {
  #|     const deno = globalThis.Deno;
  #|     if (!deno || typeof deno.writeTextFileSync !== "function") return;
  #|     // Security: resolve to absolute path and reject path traversal
  #|     const resolved = deno.realPathSync ? (() => {
  #|       // Resolve parent directory to detect traversal
  #|       const sep = filePath.lastIndexOf("/");
  #|       if (sep <= 0) return filePath;
  #|       const dir = filePath.slice(0, sep);
  #|       const base = filePath.slice(sep + 1);
  #|       // Reject filenames with path separators or traversal
  #|       if (base.includes("/") || base.includes("\\") || base === ".." || base === ".") {
  #|         console.error("[security] rejected filename: " + base);
  #|         return null;
  #|       }
  #|       // Reject if directory contains traversal sequences
  #|       if (dir.includes("..")) {
  #|         console.error("[security] rejected path traversal in directory: " + dir);
  #|         return null;
  #|       }
  #|       return filePath;
  #|     })() : filePath;
  #|     if (!resolved) return;
  #|     const sep = resolved.lastIndexOf("/");
  #|     if (sep > 0 && typeof deno.mkdirSync === "function") {
  #|       const dir = resolved.slice(0, sep);
  #|       try { deno.mkdirSync(dir, { recursive: true }); } catch (_e) {}
  #|     }
  #|     deno.writeTextFileSync(resolved, String(content ?? ""));
  #|   } catch (_e) {}
  #| }

///|
/// Write UTF-8 text file for synthetic download tests.
pub fn runtime_write_text_file(path : String, content : String) -> Unit {
  js_runtime_write_text_file(path, content)
}

///|
/// Collect iframe src values from runtime document.
extern "js" fn js_runtime_iframe_sources() -> Array[String] =
  #| () => {
  #|   const doc = globalThis.document;
  #|   if (!doc || typeof doc.querySelectorAll !== "function") return [];
  #|   const nodes = doc.querySelectorAll("iframe");
  #|   const result = [];
  #|   for (const node of nodes) {
  #|     let src = null;
  #|     try {
  #|       if (node && typeof node.getAttribute === "function") {
  #|         src = node.getAttribute("src");
  #|       }
  #|     } catch (_e) {}
  #|     if ((src === null || src === undefined || src === "") && node && node._attrs) {
  #|       src = node._attrs.src;
  #|     }
  #|     if (src === null || src === undefined || src === "") {
  #|       result.push("about:blank");
  #|     } else {
  #|       result.push(String(src));
  #|     }
  #|   }
  #|   return result;
  #| }

///|
/// Collect iframe src values from runtime document.
pub fn get_runtime_iframe_sources() -> Array[String] {
  js_runtime_iframe_sources()
}

///|
/// Resolve href from the most recent synthetic click target.
extern "js" fn js_runtime_last_click_href() -> String? =
  #| () => {
  #|   const href = globalThis.__bidiLastClickHref;
  #|   if (href === null || href === undefined || href === "") return "";
  #|   return String(href);
  #| }

///|
/// Resolve href from the most recent synthetic click target.
pub fn get_runtime_last_click_href() -> String? {
  js_runtime_last_click_href()
}

///|
/// Resolve data/absolute URL assigned by inline event handlers like onkeydown/onmousedown.
extern "js" fn js_runtime_inline_navigation_url(
  attribute_name : String,
) -> String? =
  #| (attributeName) => {
  #|   const doc = globalThis.document;
  #|   if (!doc || typeof doc.querySelectorAll !== "function") return "";
  #|   const attr = String(attributeName || "");
  #|   if (attr === "") return "";
  #|   const selector = `[${attr}]`;
  #|   const nodes = doc.querySelectorAll(selector);
  #|   for (const node of nodes) {
  #|     let handler = "";
  #|     try {
  #|       if (node && typeof node.getAttribute === "function") {
  #|         handler = node.getAttribute(attr) || "";
  #|       }
  #|     } catch (_e) {}
  #|     if (!handler && node && node._attrs) {
  #|       handler = String(node._attrs[attr] || "");
  #|     }
  #|     if (!handler) continue;
  #|     const match = String(handler).match(/window\.location(?:\.href)?\s*=\s*["']([^"']+)["']/);
  #|     if (!match || !match[1]) continue;
  #|     const raw = String(match[1]);
  #|     try {
  #|       const base =
  #|         (globalThis.location && globalThis.location.href) ||
  #|         globalThis.__pageUrl ||
  #|         "about:blank";
  #|       return new URL(raw, base).href;
  #|     } catch (_e) {
  #|       return raw;
  #|     }
  #|   }
  #|   return "";
  #| }

///|
/// Resolve data/absolute URL assigned by inline event handlers like onkeydown/onmousedown.
pub fn get_runtime_inline_navigation_url(attribute_name : String) -> String? {
  js_runtime_inline_navigation_url(attribute_name)
}

///|
/// Resolve href from element under viewport coordinates.
extern "js" fn js_runtime_href_at_point(x : Double, y : Double) -> String? =
  #| (x, y) => {
  #|   const doc = globalThis.document;
  #|   if (!doc) return "";
  #|   let node = null;
  #|   if (typeof doc.elementFromPoint === "function") {
  #|     try {
  #|       node = doc.elementFromPoint(Number(x), Number(y));
  #|     } catch (_e) {}
  #|   }
  #|   const hrefFromNode = (candidate) => {
  #|     let current = candidate;
  #|     while (current) {
  #|       let href = null;
  #|       try {
  #|         if (typeof current.getAttribute === "function") {
  #|           href = current.getAttribute("href");
  #|         }
  #|       } catch (_e) {}
  #|       if ((href === null || href === undefined || href === "") && current._attrs) {
  #|         href = current._attrs.href;
  #|       }
  #|       if (href !== null && href !== undefined && href !== "") {
  #|         const rawHref = String(href);
  #|         try {
  #|           const base =
  #|             (globalThis.location && globalThis.location.href) ||
  #|             globalThis.__pageUrl ||
  #|             "about:blank";
  #|           return new URL(rawHref, base).href;
  #|         } catch (_e) {
  #|           return rawHref;
  #|         }
  #|       }
  #|       current = current._parent || current.parentNode || null;
  #|     }
  #|     return null;
  #|   };
  #|   let href = hrefFromNode(node);
  #|   if (href !== null && href !== undefined && href !== "") return href;
  #|   if (href === null || href === undefined || href === "") return "";
  #|   return href;
  #| }

///|
/// Resolve href from element under viewport coordinates.
pub fn get_runtime_href_at_point(x : Double, y : Double) -> String? {
  js_runtime_href_at_point(x, y)
}

///|
/// Dispatch synthetic keyboard event and keep `allEvents` in sync for WPT pages.
extern "js" fn js_input_dispatch_key_action(
  action_type : String,
  raw_value : String,
  ctrl : Bool,
  alt : Bool,
  shift : Bool,
  meta : Bool,
) -> Unit =
  #| (actionType, rawValue, ctrl, alt, shift, meta) => {
  #|   const value = String(rawValue ?? "");
  #|   const special = {
  #|     "\uE000": { key: "Unidentified", code: "", location: 0, printable: false, text: "" },
  #|     "\uE001": { key: "Cancel", code: "", location: 0, printable: false, text: "" },
  #|     "\uE002": { key: "Help", code: "Help", location: 0, printable: false, text: "" },
  #|     "\uE003": { key: "Backspace", code: "Backspace", which: 8, location: 0, printable: false, text: "" },
  #|     "\uE004": { key: "Tab", code: "Tab", which: 9, location: 0, printable: false, text: "" },
  #|     "\uE005": { key: "Clear", code: "", location: 0, printable: false, text: "" },
  #|     "\uE006": { key: "Enter", code: "Enter", which: 13, location: 0, printable: false, text: "" },
  #|     "\uE007": { key: "Enter", code: "NumpadEnter", which: 13, location: 1, printable: false, text: "" },
  #|     "\uE008": { key: "Shift", code: "ShiftLeft", which: 16, location: 1, printable: false, text: "" },
  #|     "Shift": { key: "Shift", code: "ShiftLeft", which: 16, location: 1, printable: false, text: "" },
  #|     "ShiftLeft": { key: "Shift", code: "ShiftLeft", which: 16, location: 1, printable: false, text: "" },
  #|     "shift": { key: "Shift", code: "ShiftLeft", which: 16, location: 1, printable: false, text: "" },
  #|     "\uE009": { key: "Control", code: "ControlLeft", which: 17, location: 1, printable: false, text: "" },
  #|     "Control": { key: "Control", code: "ControlLeft", which: 17, location: 1, printable: false, text: "" },
  #|     "ControlLeft": { key: "Control", code: "ControlLeft", which: 17, location: 1, printable: false, text: "" },
  #|     "control": { key: "Control", code: "ControlLeft", which: 17, location: 1, printable: false, text: "" },
  #|     "\uE00A": { key: "Alt", code: "AltLeft", which: 18, location: 1, printable: false, text: "" },
  #|     "Alt": { key: "Alt", code: "AltLeft", which: 18, location: 1, printable: false, text: "" },
  #|     "AltLeft": { key: "Alt", code: "AltLeft", which: 18, location: 1, printable: false, text: "" },
  #|     "alt": { key: "Alt", code: "AltLeft", which: 18, location: 1, printable: false, text: "" },
  #|     "\uE00B": { key: "Pause", code: "Pause", location: 0, printable: false, text: "" },
  #|     "\uE00C": { key: "Escape", code: "Escape", which: 27, location: 0, printable: false, text: "" },
  #|     "\uE00D": { key: " ", code: "Space", which: 32, location: 0, printable: true, text: " " },
  #|     "\uE00E": { key: "PageUp", code: "PageUp", location: 0, printable: false, text: "" },
  #|     "\uE00F": { key: "PageDown", code: "PageDown", location: 0, printable: false, text: "" },
  #|     "\uE010": { key: "End", code: "End", location: 0, printable: false, text: "" },
  #|     "\uE011": { key: "Home", code: "Home", location: 0, printable: false, text: "" },
  #|     "\uE012": { key: "ArrowLeft", code: "ArrowLeft", location: 0, printable: false, text: "" },
  #|     "\uE013": { key: "ArrowUp", code: "ArrowUp", location: 0, printable: false, text: "" },
  #|     "\uE014": { key: "ArrowRight", code: "ArrowRight", location: 0, printable: false, text: "" },
  #|     "\uE015": { key: "ArrowDown", code: "ArrowDown", location: 0, printable: false, text: "" },
  #|     "\uE016": { key: "Insert", code: "Insert", location: 0, printable: false, text: "" },
  #|     "\uE017": { key: "Delete", code: "Delete", location: 0, printable: false, text: "" },
  #|     "\uE018": { key: ";", code: "", location: 0, printable: true, text: ";" },
  #|     "\uE019": { key: "=", code: "NumpadEqual", location: 3, printable: true, text: "=" },
  #|     "\uE01A": { key: "0", code: "Numpad0", location: 3, printable: true, text: "0" },
  #|     "\uE01B": { key: "1", code: "Numpad1", location: 3, printable: true, text: "1" },
  #|     "\uE01C": { key: "2", code: "Numpad2", location: 3, printable: true, text: "2" },
  #|     "\uE01D": { key: "3", code: "Numpad3", location: 3, printable: true, text: "3" },
  #|     "\uE01E": { key: "4", code: "Numpad4", location: 3, printable: true, text: "4" },
  #|     "\uE01F": { key: "5", code: "Numpad5", location: 3, printable: true, text: "5" },
  #|     "\uE020": { key: "6", code: "Numpad6", location: 3, printable: true, text: "6" },
  #|     "\uE021": { key: "7", code: "Numpad7", location: 3, printable: true, text: "7" },
  #|     "\uE022": { key: "8", code: "Numpad8", location: 3, printable: true, text: "8" },
  #|     "\uE023": { key: "9", code: "Numpad9", location: 3, printable: true, text: "9" },
  #|     "\uE024": { key: "*", code: "NumpadMultiply", location: 3, printable: true, text: "*" },
  #|     "\uE025": { key: "+", code: "NumpadAdd", location: 3, printable: true, text: "+" },
  #|     "\uE026": { key: ",", code: "NumpadComma", location: 3, printable: true, text: "," },
  #|     "\uE027": { key: "-", code: "NumpadSubtract", location: 3, printable: true, text: "-" },
  #|     "\uE028": { key: ".", code: "NumpadDecimal", location: 3, printable: true, text: "." },
  #|     "\uE029": { key: "/", code: "NumpadDivide", location: 3, printable: true, text: "/" },
  #|     "\uE031": { key: "F1", code: "F1", location: 0, printable: false, text: "" },
  #|     "\uE032": { key: "F2", code: "F2", location: 0, printable: false, text: "" },
  #|     "\uE033": { key: "F3", code: "F3", location: 0, printable: false, text: "" },
  #|     "\uE034": { key: "F4", code: "F4", location: 0, printable: false, text: "" },
  #|     "\uE035": { key: "F5", code: "F5", location: 0, printable: false, text: "" },
  #|     "\uE036": { key: "F6", code: "F6", location: 0, printable: false, text: "" },
  #|     "\uE037": { key: "F7", code: "F7", location: 0, printable: false, text: "" },
  #|     "\uE038": { key: "F8", code: "F8", location: 0, printable: false, text: "" },
  #|     "\uE039": { key: "F9", code: "F9", location: 0, printable: false, text: "" },
  #|     "\uE03A": { key: "F10", code: "F10", location: 0, printable: false, text: "" },
  #|     "\uE03B": { key: "F11", code: "F11", location: 0, printable: false, text: "" },
  #|     "\uE03C": { key: "F12", code: "F12", location: 0, printable: false, text: "" },
  #|     "\uE03D": { key: "Meta", code: "MetaLeft", which: 91, location: 1, printable: false, text: "" },
  #|     "Meta": { key: "Meta", code: "MetaLeft", which: 91, location: 1, printable: false, text: "" },
  #|     "MetaLeft": { key: "Meta", code: "MetaLeft", which: 91, location: 1, printable: false, text: "" },
  #|     "meta": { key: "Meta", code: "MetaLeft", which: 91, location: 1, printable: false, text: "" },
  #|     "\uE040": { key: "ZenkakuHankaku", code: "", location: 0, printable: false, text: "" },
  #|     "\uE050": { key: "Shift", code: "ShiftRight", which: 16, location: 2, printable: false, text: "" },
  #|     "\uE051": { key: "Control", code: "ControlRight", which: 17, location: 2, printable: false, text: "" },
  #|     "\uE052": { key: "Alt", code: "AltRight", which: 18, location: 2, printable: false, text: "" },
  #|     "\uE053": { key: "Meta", code: "MetaRight", which: 91, location: 2, printable: false, text: "" },
  #|     "\uE054": { key: "PageUp", code: "Numpad9", location: 3, printable: false, text: "" },
  #|     "\uE055": { key: "PageDown", code: "Numpad3", location: 3, printable: false, text: "" },
  #|     "\uE056": { key: "End", code: "Numpad1", location: 3, printable: false, text: "" },
  #|     "\uE057": { key: "Home", code: "Numpad7", location: 3, printable: false, text: "" },
  #|     "\uE058": { key: "ArrowLeft", code: "Numpad4", location: 3, printable: false, text: "" },
  #|     "\uE059": { key: "ArrowUp", code: "Numpad8", location: 3, printable: false, text: "" },
  #|     "\uE05A": { key: "ArrowRight", code: "Numpad6", location: 3, printable: false, text: "" },
  #|     "\uE05B": { key: "ArrowDown", code: "Numpad2", location: 3, printable: false, text: "" },
  #|     "\uE05C": { key: "Insert", code: "Numpad0", location: 3, printable: false, text: "" },
  #|     "\uE05D": { key: "Delete", code: "NumpadDecimal", location: 3, printable: false, text: "" },
  #|   };
  #|   const resolved = special[value];
  #|   let key = resolved ? resolved.key : value;
  #|   let code = resolved ? resolved.code : "";
  #|   let which = resolved ? (resolved.which ?? 0) : 0;
  #|   let location = resolved ? resolved.location : 0;
  #|   let printable = resolved ? !!resolved.printable : true;
  #|   let text = resolved ? resolved.text : value;
  #|
  #|   if (!resolved) {
  #|     const printableCode = {
  #|       "\"": "Quote",
  #|       ",": "Comma",
  #|       "@": "Digit2",
  #|     };
  #|     if (value === " ") {
  #|       key = " ";
  #|       code = "Space";
  #|       which = 32;
  #|     } else if (/^[a-zA-Z]$/.test(value)) {
  #|       code = "Key" + value.toUpperCase();
  #|       which = value.toUpperCase().charCodeAt(0);
  #|     } else if (/^[0-9]$/.test(value)) {
  #|       code = "Digit" + value;
  #|       which = value.charCodeAt(0);
  #|     } else if (Object.prototype.hasOwnProperty.call(printableCode, value)) {
  #|       code = printableCode[value];
  #|       which = value.charCodeAt(0);
  #|     } else if (value.length > 0) {
  #|       which = value.charCodeAt(0);
  #|     }
  #|   }
  #|   if (which === 0 && key.length === 1) {
  #|     which = key.charCodeAt(0);
  #|   }
  #|
  #|   const doc = globalThis.document;
  #|   if (!doc) return;
  #|   const resolveDeepActiveElement = () => {
  #|     let current = doc.activeElement || null;
  #|     const visited = new Set();
  #|     while (current && !visited.has(current)) {
  #|       visited.add(current);
  #|       let next = null;
  #|       try {
  #|         if (current.shadowRoot && current.shadowRoot.activeElement) {
  #|           next = current.shadowRoot.activeElement;
  #|         }
  #|       } catch (_e) {}
  #|       if (!next) {
  #|         const globalShadow = globalThis._shadowRoot;
  #|         try {
  #|           if (globalShadow && globalShadow.activeElement) {
  #|             next = globalShadow.activeElement;
  #|           }
  #|         } catch (_e) {}
  #|       }
  #|       if (!next) break;
  #|       current = next;
  #|     }
  #|     return current;
  #|   };
  #|   let focused = globalThis.__bidiFocusedElement || null;
  #|   if (focused) {
  #|     const focusedDoc = focused.ownerDocument || null;
  #|     let detached = false;
  #|     if (focusedDoc && focusedDoc !== doc) {
  #|       detached = true;
  #|     } else if (focused && focused.isConnected === false) {
  #|       detached = true;
  #|     } else if (typeof doc.contains === "function") {
  #|       try {
  #|         detached = !doc.contains(focused);
  #|       } catch (_e) {}
  #|     }
  #|     if (detached) {
  #|       focused = null;
  #|       try { globalThis.__bidiFocusedElement = null; } catch (_e) {}
  #|     }
  #|   }
  #|   let element = focused || resolveDeepActiveElement();
  #|   const hasExplicitTarget = !!focused;
  #|   if (!element) {
  #|     element =
  #|       doc.activeElement ||
  #|       doc.body ||
  #|       doc.documentElement ||
  #|       doc;
  #|   }
  #|   if (!element) return;
  #|   if (hasExplicitTarget && typeof element.focus === "function") {
  #|     try { element.focus(); } catch (_e) {}
  #|   }
  #|   const getSequentialContainingShadowRoot = (node) => {
  #|     let current = node;
  #|     while (current) {
  #|       if (current._isShadowRoot) return current;
  #|       current = current._parent || current.parentNode || null;
  #|     }
  #|     return null;
  #|   };
  #|   const getSequentialChildren = (node) => {
  #|     if (!node || typeof node !== "object") return [];
  #|     const getAttr = (target, name) => {
  #|       if (!target || typeof target !== "object") return null;
  #|       try {
  #|         if (typeof target.getAttribute === "function") {
  #|           const value = target.getAttribute(name);
  #|           if (value !== null && value !== undefined) return String(value);
  #|         }
  #|       } catch (_e) {}
  #|       if (target._attrs && Object.prototype.hasOwnProperty.call(target._attrs, name)) {
  #|         const value = target._attrs[name];
  #|         return value === null || value === undefined ? null : String(value);
  #|       }
  #|       return null;
  #|     };
  #|     const isSlotElement = (target) => {
  #|       if (!target || target.nodeType !== 1) return false;
  #|       const localName = String(target.localName || target.tagName || target.nodeName || "").toLowerCase();
  #|       return localName === "slot";
  #|     };
  #|     const getDirectChildren = (target) => {
  #|       if (!target || typeof target !== "object") return [];
  #|       if (Array.isArray(target._children)) return target._children;
  #|       if (Array.isArray(target.children)) return Array.from(target.children);
  #|       if (Array.isArray(target.childNodes)) return Array.from(target.childNodes);
  #|       return [];
  #|     };
  #|     const findFirstSlotForName = (root, slotName) => {
  #|       const children = getDirectChildren(root);
  #|       for (let i = 0; i < children.length; i += 1) {
  #|         const child = children[i];
  #|         if (!child || child.nodeType !== 1) continue;
  #|         if (isSlotElement(child) && String(getAttr(child, "name") || "") === slotName) {
  #|           return child;
  #|         }
  #|         const nested = findFirstSlotForName(child, slotName);
  #|         if (nested) return nested;
  #|       }
  #|       return null;
  #|     };
  #|     const getAssignedChildrenForSlot = (slot) => {
  #|       const shadowRoot = getSequentialContainingShadowRoot(slot);
  #|       if (!shadowRoot || !shadowRoot.host) return getDirectChildren(slot);
  #|       const slotName = String(getAttr(slot, "name") || "");
  #|       const firstMatch = findFirstSlotForName(shadowRoot, slotName);
  #|       if (firstMatch && firstMatch !== slot) return [];
  #|       const assigned = [];
  #|       const hostChildren = getDirectChildren(shadowRoot.host);
  #|       for (let i = 0; i < hostChildren.length; i += 1) {
  #|         const child = hostChildren[i];
  #|         if (!child) continue;
  #|         const childSlotName = String(getAttr(child, "slot") || "");
  #|         if (childSlotName === slotName) assigned.push(child);
  #|       }
  #|       return assigned.length > 0 ? assigned : getDirectChildren(slot);
  #|     };
  #|     if (isSlotElement(node)) return getAssignedChildrenForSlot(node);
  #|     const shadowRoot = node.shadowRoot || null;
  #|     if (shadowRoot && Array.isArray(shadowRoot._children)) return shadowRoot._children;
  #|     return getDirectChildren(node);
  #|   };
  #|   const hasExplicitTabIndex = (node) => {
  #|     if (!node || typeof node !== "object") return false;
  #|     try {
  #|       if (typeof node.getAttribute === "function" && node.getAttribute("tabindex") !== null) {
  #|         return true;
  #|       }
  #|     } catch (_e) {}
  #|     return !!(node._attrs && Object.prototype.hasOwnProperty.call(node._attrs, "tabindex"));
  #|   };
  #|   const isSequentiallyFocusable = (node) => {
  #|     if (!node || node.nodeType !== 1) return false;
  #|     if (node.disabled) return false;
  #|     if (node.hidden) return false;
  #|     const style = node.style || {};
  #|     if (style.display === "none" || style.visibility === "hidden") return false;
  #|     if (hasExplicitTabIndex(node)) {
  #|       try {
  #|         return Number(node.tabIndex) >= 0;
  #|       } catch (_e) {
  #|         return false;
  #|       }
  #|     }
  #|     const tag = String(node.tagName || node.nodeName || "").toLowerCase();
  #|     if (["input", "textarea", "select", "button"].includes(tag)) return true;
  #|     if (tag === "a") {
  #|       try {
  #|         return !!(typeof node.getAttribute === "function" ? node.getAttribute("href") : null);
  #|       } catch (_e) {
  #|         return false;
  #|       }
  #|     }
  #|     return !!node.isContentEditable;
  #|   };
  #|   const collectSequentialFocusables = (node, results) => {
  #|     const children = getSequentialChildren(node);
  #|     for (let i = 0; i < children.length; i += 1) {
  #|       const child = children[i];
  #|       if (!child || child.nodeType !== 1) continue;
  #|       if (isSequentiallyFocusable(child)) results.push(child);
  #|       collectSequentialFocusables(child, results);
  #|     }
  #|   };
  #|   const moveSequentialFocus = (backward) => {
  #|     const root = doc.body || doc.documentElement || doc;
  #|     const order = [];
  #|     collectSequentialFocusables(root, order);
  #|     if (order.length === 0) return false;
  #|     const current = resolveDeepActiveElement();
  #|     const currentIndex = order.indexOf(current);
  #|     let nextIndex = 0;
  #|     if (currentIndex >= 0) {
  #|       nextIndex = currentIndex + (backward ? -1 : 1);
  #|       if (nextIndex < 0 || nextIndex >= order.length) return false;
  #|     } else if (backward) {
  #|       nextIndex = order.length - 1;
  #|     }
  #|     const next = order[nextIndex];
  #|     if (!next || typeof next.focus !== "function") return false;
  #|     try { next.focus(); } catch (_e) { return false; }
  #|     try { globalThis.__bidiFocusedElement = next; } catch (_e) {}
  #|     return true;
  #|   };
  #|
  #|   const makeEvent = (type) => {
  #|     const event = globalThis.__bidiCreateEvent(type, { bubbles: true, cancelable: true });
  #|     event.key = key;
  #|     event.code = code;
  #|     event.which = which;
  #|     event.keyCode = which;
  #|     event.location = location;
  #|     event.ctrlKey = !!ctrl;
  #|     event.altKey = !!alt;
  #|     event.shiftKey = !!shift;
  #|     event.metaKey = !!meta;
  #|     event.repeat = false;
  #|     return event;
  #|   };
  #|
  #|   let windowAllEvents =
  #|     globalThis.window &&
  #|     globalThis.window.allEvents &&
  #|     Array.isArray(globalThis.window.allEvents.events)
  #|       ? globalThis.window.allEvents
  #|       : null;
  #|   if (
  #|     !windowAllEvents &&
  #|     typeof allEvents !== "undefined" &&
  #|     allEvents &&
  #|     Array.isArray(allEvents.events)
  #|   ) {
  #|     windowAllEvents = allEvents;
  #|     if (globalThis.window && typeof globalThis.window === "object") {
  #|       try { globalThis.window.allEvents = windowAllEvents; } catch (_e) {}
  #|     }
  #|   }
  #|   const hadAllEvents = !!windowAllEvents;
  #|   if (hadAllEvents) {
  #|     globalThis.allEvents = windowAllEvents;
  #|   } else {
  #|     globalThis.allEvents = { events: [] };
  #|   }
  #|   if (globalThis.__bidiContextWindows && typeof globalThis.__bidiContextWindows.forEach === "function") {
  #|     try {
  #|       globalThis.__bidiContextWindows.forEach((ctxWindow) => {
  #|         try { ctxWindow.allEvents = globalThis.allEvents; } catch (_e) {}
  #|       });
  #|     } catch (_e) {}
  #|   }
  #|   if (globalThis.window && typeof globalThis.window === "object") {
  #|     try { globalThis.window.allEvents = globalThis.allEvents; } catch (_e) {}
  #|   }
  #|   const fallbackEnabled = !!(
  #|     globalThis.window &&
  #|     globalThis.window.__craterAllEventsFallbackInit
  #|   );
  #|   const shouldRecordFallback =
  #|     fallbackEnabled &&
  #|     hasExplicitTarget &&
  #|     !!(globalThis.allEvents && Array.isArray(globalThis.allEvents.events));
  #|   const pushFallback = (type) => {
  #|     if (!shouldRecordFallback) return;
  #|     globalThis.allEvents.events.push({
  #|       type,
  #|       code,
  #|       key,
  #|       which,
  #|       location,
  #|       ctrl: !!ctrl,
  #|       alt: !!alt,
  #|       meta: !!meta,
  #|       shift: !!shift,
  #|       repeat: false,
  #|       altKey: !!alt,
  #|       ctrlKey: !!ctrl,
  #|       metaKey: !!meta,
  #|       shiftKey: !!shift,
  #|     });
  #|   };
  #|   const dispatchWithFallback = (type) => {
  #|     const beforeCount = shouldRecordFallback ? globalThis.allEvents.events.length : 0;
  #|     const allowed = element.dispatchEvent(makeEvent(type));
  #|     if (shouldRecordFallback && globalThis.allEvents.events.length === beforeCount) {
  #|       pushFallback(type);
  #|     }
  #|     return allowed;
  #|   };
  #|   const getSelection = () => {
  #|     const value = typeof element.value === "string" ? element.value : "";
  #|     let start = typeof element.selectionStart === "number" ? element.selectionStart : null;
  #|     let end = typeof element.selectionEnd === "number" ? element.selectionEnd : null;
  #|     if (start === null || end === null) {
  #|       start = typeof element.__bidiSelectionStart === "number" ? element.__bidiSelectionStart : value.length;
  #|       end = typeof element.__bidiSelectionEnd === "number" ? element.__bidiSelectionEnd : value.length;
  #|     }
  #|     start = Math.max(0, Math.min(value.length, Number(start)));
  #|     end = Math.max(0, Math.min(value.length, Number(end)));
  #|     if (end < start) {
  #|       const tmp = start;
  #|       start = end;
  #|       end = tmp;
  #|     }
  #|     return { start, end, value };
  #|   };
  #|   const setSelection = (start, end) => {
  #|     const value = typeof element.value === "string" ? element.value : "";
  #|     const safeStart = Math.max(0, Math.min(value.length, Number(start)));
  #|     const safeEnd = Math.max(0, Math.min(value.length, Number(end)));
  #|     try { element.selectionStart = safeStart; } catch (_e) {}
  #|     try { element.selectionEnd = safeEnd; } catch (_e) {}
  #|     element.__bidiSelectionStart = safeStart;
  #|     element.__bidiSelectionEnd = safeEnd;
  #|   };
  #|   const replaceSelection = (insertText) => {
  #|     const { start, end, value } = getSelection();
  #|     const next = value.slice(0, start) + String(insertText ?? "") + value.slice(end);
  #|     element.value = next;
  #|     const caret = start + String(insertText ?? "").length;
  #|     setSelection(caret, caret);
  #|   };
  #|   const dispatchInputLike = (type, inputType, data) => {
  #|     const event = globalThis.__bidiCreateEvent(type, {
  #|       bubbles: true,
  #|       cancelable: type === "beforeinput",
  #|     });
  #|     event.inputType = String(inputType || "");
  #|     event.data = data == null ? null : String(data);
  #|     return element.dispatchEvent(event);
  #|   };
  #|   const replaceSelectionWithEvents = (insertText, inputType) => {
  #|     const textValue = String(insertText ?? "");
  #|     if (!dispatchInputLike("beforeinput", inputType, textValue)) {
  #|       return false;
  #|     }
  #|     replaceSelection(textValue);
  #|     dispatchInputLike("input", inputType, textValue);
  #|     return true;
  #|   };
  #|   const deleteSelectionWithEvents = (inputType, start, end) => {
  #|     if (!dispatchInputLike("beforeinput", inputType, null)) {
  #|       return false;
  #|     }
  #|     setSelection(start, end);
  #|     replaceSelection("");
  #|     dispatchInputLike("input", inputType, null);
  #|     return true;
  #|   };
  #|   const tagName = String(element.tagName || element.nodeName || "").toLowerCase();
  #|   const dispatchSimpleEvent = (type) => {
  #|     const event = globalThis.__bidiCreateEvent(type, { bubbles: true, cancelable: false });
  #|     return element.dispatchEvent(event);
  #|   };
  #|   const optionList = () => {
  #|     if (Array.isArray(element.options)) return element.options;
  #|     if (Array.isArray(element._children)) {
  #|       return element._children.filter((child) => {
  #|         const childTag = String(child && (child.tagName || child.nodeName) || "").toLowerCase();
  #|         return childTag === "option";
  #|       });
  #|     }
  #|     return [];
  #|   };
  #|   const syncSelectChoice = (nextIndex) => {
  #|     const options = optionList();
  #|     if (!options.length) return false;
  #|     const safeIndex = Math.max(0, Math.min(options.length - 1, Number(nextIndex)));
  #|     const currentIndex =
  #|       typeof element.selectedIndex === "number"
  #|         ? Number(element.selectedIndex)
  #|         : options.findIndex((option) => !!option.selected);
  #|     if (currentIndex === safeIndex) return false;
  #|     options.forEach((option, index) => {
  #|       option.selected = index === safeIndex;
  #|     });
  #|     element.selectedIndex = safeIndex;
  #|     const selected = options[safeIndex];
  #|     element.value =
  #|       selected && selected.value != null && selected.value !== ""
  #|         ? String(selected.value)
  #|         : String((selected && selected.textContent) || "");
  #|     dispatchSimpleEvent("input");
  #|     dispatchSimpleEvent("change");
  #|     return true;
  #|   };
  #|
  #|   if (actionType === "keyDown") {
  #|     const keydownAllowed = dispatchWithFallback("keydown");
  #|     if (key === "Tab") {
  #|       if (keydownAllowed) {
  #|         moveSequentialFocus(!!shift);
  #|       }
  #|       return;
  #|     }
  #|
  #|     const usesShortcut = (ctrl || meta) && !alt;
  #|     const lowerKey = key.length === 1 ? key.toLowerCase() : key;
  #|     if (usesShortcut && lowerKey === "a") {
  #|       if (typeof element.value === "string") {
  #|         setSelection(0, element.value.length);
  #|       }
  #|       return;
  #|     }
  #|     if (usesShortcut && lowerKey === "c") {
  #|       const { start, end, value } = getSelection();
  #|       globalThis.__bidiClipboardText = value.slice(start, end);
  #|       return;
  #|     }
  #|     if (usesShortcut && lowerKey === "x") {
  #|       const { start, end, value } = getSelection();
  #|       globalThis.__bidiClipboardText = value.slice(start, end);
  #|       deleteSelectionWithEvents("deleteByCut", start, end);
  #|       return;
  #|     }
  #|     if (usesShortcut && lowerKey === "v") {
  #|       const clip = typeof globalThis.__bidiClipboardText === "string" ? globalThis.__bidiClipboardText : "";
  #|       replaceSelectionWithEvents(clip, "insertFromPaste");
  #|       return;
  #|     }
  #|     if (key === "ArrowRight") {
  #|       const { start, end, value } = getSelection();
  #|       if (start !== end) {
  #|         setSelection(end, end);
  #|       } else {
  #|         const next = Math.min(value.length, end + 1);
  #|         setSelection(next, next);
  #|       }
  #|       return;
  #|     }
  #|     if (tagName === "select" && (key === "ArrowDown" || key === "ArrowUp")) {
  #|       const options = optionList();
  #|       if (options.length > 0) {
  #|         const currentIndex =
  #|           typeof element.selectedIndex === "number"
  #|             ? Number(element.selectedIndex)
  #|             : options.findIndex((option) => !!option.selected);
  #|         const baseIndex = currentIndex >= 0 ? currentIndex : -1;
  #|         const delta = key === "ArrowDown" ? 1 : -1;
  #|         syncSelectChoice(baseIndex + delta);
  #|       }
  #|       return;
  #|     }
  #|     if (key === "Backspace") {
  #|       const { start, end, value } = getSelection();
  #|       if (start !== end) {
  #|         deleteSelectionWithEvents("deleteContentBackward", start, end);
  #|       } else if (value.length > 0 && start > 0) {
  #|         deleteSelectionWithEvents("deleteContentBackward", start - 1, start);
  #|       } else if (value.length > 0 && start === value.length) {
  #|         deleteSelectionWithEvents("deleteContentBackward", value.length - 1, value.length);
  #|       }
  #|     } else if (key === "Delete") {
  #|       const { start, end, value } = getSelection();
  #|       if (start !== end) {
  #|         deleteSelectionWithEvents("deleteContentForward", start, end);
  #|       } else if (start < value.length) {
  #|         deleteSelectionWithEvents("deleteContentForward", start, start + 1);
  #|       }
  #|     } else if (printable && text.length > 0 && !usesShortcut && !alt) {
  #|       let insertText = text;
  #|       if (shift && insertText.length === 1 && /^[a-z]$/.test(insertText)) {
  #|         insertText = insertText.toUpperCase();
  #|       }
  #|       replaceSelectionWithEvents(insertText, "insertText");
  #|       dispatchWithFallback("keypress");
  #|     }
  #|     return;
  #|   }
  #|
  #|   dispatchWithFallback("keyup");
  #| }

///|
/// Dispatch synthetic keyboard event and keep `allEvents` in sync for WPT pages.
pub fn input_dispatch_key_action(
  action_type : String,
  raw_value : String,
  ctrl : Bool,
  alt : Bool,
  shift : Bool,
  meta : Bool,
) -> Unit {
  js_input_dispatch_key_action(action_type, raw_value, ctrl, alt, shift, meta)
}

///|
/// Check whether string contains exactly one grapheme cluster.
extern "js" fn js_input_is_single_grapheme(value : String) -> Bool =
  #| (value) => {
  #|   const text = String(value ?? "");
  #|   if (text.length === 0) return false;
  #|   if (typeof Intl !== "undefined" && typeof Intl.Segmenter === "function") {
  #|     try {
  #|       const segmenter = new Intl.Segmenter(undefined, { granularity: "grapheme" });
  #|       const segments = Array.from(segmenter.segment(text));
  #|       return segments.length === 1;
  #|     } catch (_e) {}
  #|   }
  #|   return Array.from(text).length === 1;
  #| }

///|
/// Check whether string contains exactly one grapheme cluster.
pub fn input_is_single_grapheme(value : String) -> Bool {
  js_input_is_single_grapheme(value)
}

///|
/// Set synthetic pointer event property overrides used by pointer dispatch.
extern "js" fn js_input_set_pointer_event_properties(
  width : Double,
  height : Double,
  pressure : Double,
  tangential_pressure : Double,
  twist : Double,
  altitude_angle : Double,
  azimuth_angle : Double,
) -> Unit =
  #| (
  #|   width,
  #|   height,
  #|   pressure,
  #|   tangentialPressure,
  #|   twist,
  #|   altitudeAngle,
  #|   azimuthAngle,
  #| ) => {
  #|   globalThis.__bidiPointerEventProps = {
  #|     width: Number(width),
  #|     height: Number(height),
  #|     pressure: Number(pressure),
  #|     tangentialPressure: Number(tangentialPressure),
  #|     twist: Number(twist),
  #|     altitudeAngle: Number(altitudeAngle),
  #|     azimuthAngle: Number(azimuthAngle),
  #|   };
  #| }

///|
/// Set synthetic pointer event property overrides used by pointer dispatch.
pub fn input_set_pointer_event_properties(
  width : Double,
  height : Double,
  pressure : Double,
  tangential_pressure : Double,
  twist : Double,
  altitude_angle : Double,
  azimuth_angle : Double,
) -> Unit {
  js_input_set_pointer_event_properties(
    width, height, pressure, tangential_pressure, twist, altitude_angle, azimuth_angle,
  )
}

///|
/// Clear synthetic pointer event property overrides.
extern "js" fn js_input_clear_pointer_event_properties() -> Unit =
  #| () => {
  #|   globalThis.__bidiPointerEventProps = null;
  #| }

///|
/// Clear synthetic pointer event property overrides.
pub fn input_clear_pointer_event_properties() -> Unit {
  js_input_clear_pointer_event_properties()
}

///|
/// Dispatch synthetic pointer/mouse event.
extern "js" fn js_input_dispatch_pointer_event_with_related(
  shared_id : String,
  event_type : String,
  x : Double,
  y : Double,
  button : Int,
  buttons : Int,
  pointer_type : String,
  ctrl : Bool,
  alt : Bool,
  shift : Bool,
  meta : Bool,
  related_shared_id : String,
) -> Unit =
  #| (sharedId, eventType, x, y, button, buttons, pointerType, ctrl, alt, shift, meta, relatedSharedId) => {
  #|   const doc = globalThis.document;
  #|   if (!doc) return;
  #|   const store = globalThis.__bidiSharedNodeStore;
  #|   let target = null;
  #|   if (sharedId && store) {
  #|     target = store.get(sharedId) || null;
  #|   }
  #|   if (!target && typeof doc.querySelector === "function") {
  #|     target = doc.querySelector("#outer") || doc.querySelector("#pointer-target");
  #|   }
  #|   if (!target && typeof doc.elementFromPoint === "function") {
  #|     try { target = doc.elementFromPoint(Number(x), Number(y)); } catch (_e) {}
  #|   }
  #|   const safeTarget = target || doc.body || doc.documentElement || doc;
  #|   let relatedTarget = null;
  #|   if (relatedSharedId && store) {
  #|     relatedTarget = store.get(relatedSharedId) || null;
  #|   }
  #|   const isFocusable = (node) => {
  #|     if (!node || typeof node !== "object") return false;
  #|     const tag = String(node.tagName || node.nodeName || "").toLowerCase();
  #|     if (["input", "textarea", "select", "button"].includes(tag)) return true;
  #|     if (tag === "a") {
  #|       try {
  #|         return !!(typeof node.getAttribute === "function" ? node.getAttribute("href") : null);
  #|       } catch (_e) {
  #|         return false;
  #|       }
  #|     }
  #|     try {
  #|       if (Number(node.tabIndex) >= 0) return true;
  #|     } catch (_e) {}
  #|     return !!node.isContentEditable;
  #|   };
  #|   const getFocusAttr = (node, name) => {
  #|     if (!node || typeof node !== "object") return null;
  #|     try {
  #|       if (typeof node.getAttribute === "function") {
  #|         const value = node.getAttribute(name);
  #|         if (value !== null && value !== undefined) return String(value);
  #|       }
  #|     } catch (_e) {}
  #|     if (node._attrs && Object.prototype.hasOwnProperty.call(node._attrs, name)) {
  #|       const value = node._attrs[name];
  #|       return value === null || value === undefined ? null : String(value);
  #|     }
  #|     return null;
  #|   };
  #|   const isSlotElement = (node) => {
  #|     if (!node || node.nodeType !== 1) return false;
  #|     const localName = String(node.localName || node.tagName || node.nodeName || "").toLowerCase();
  #|     return localName === "slot";
  #|   };
  #|   const getFocusChildren = (node) => {
  #|     if (!node || typeof node !== "object") return [];
  #|     if (Array.isArray(node._children)) return node._children;
  #|     if (Array.isArray(node.children)) return Array.from(node.children);
  #|     if (Array.isArray(node.childNodes)) return Array.from(node.childNodes);
  #|     return [];
  #|   };
  #|   const findFirstSlotForName = (root, slotName) => {
  #|     const children = getFocusChildren(root);
  #|     for (let i = 0; i < children.length; i += 1) {
  #|       const child = children[i];
  #|       if (!child || child.nodeType !== 1) continue;
  #|       if (isSlotElement(child) && String(getFocusAttr(child, "name") || "") === slotName) {
  #|         return child;
  #|       }
  #|       const nested = findFirstSlotForName(child, slotName);
  #|       if (nested) return nested;
  #|     }
  #|     return null;
  #|   };
  #|   const getContainingShadowRoot = (node) => {
  #|     let current = node;
  #|     while (current) {
  #|       if (current._isShadowRoot) return current;
  #|       current = current._parent || current.parentNode || null;
  #|     }
  #|     return null;
  #|   };
  #|   const getAssignedChildrenForSlot = (slot) => {
  #|     const shadowRoot = getContainingShadowRoot(slot);
  #|     if (!shadowRoot || !shadowRoot.host) return getFocusChildren(slot);
  #|     const slotName = String(getFocusAttr(slot, "name") || "");
  #|     const firstMatch = findFirstSlotForName(shadowRoot, slotName);
  #|     if (firstMatch && firstMatch !== slot) return [];
  #|     const assigned = [];
  #|     const hostChildren = getFocusChildren(shadowRoot.host);
  #|     for (let i = 0; i < hostChildren.length; i += 1) {
  #|       const child = hostChildren[i];
  #|       if (!child) continue;
  #|       const childSlotName = String(getFocusAttr(child, "slot") || "");
  #|       if (childSlotName === slotName) assigned.push(child);
  #|     }
  #|     return assigned.length > 0 ? assigned : getFocusChildren(slot);
  #|   };
  #|   const getDelegatesFocusChildren = (node) => {
  #|     if (!node || typeof node !== "object") return [];
  #|     if (isSlotElement(node)) return getAssignedChildrenForSlot(node);
  #|     const shadowRoot = node.shadowRoot || null;
  #|     if (shadowRoot) return getFocusChildren(shadowRoot);
  #|     return getFocusChildren(node);
  #|   };
  #|   const findDelegatesFocusTarget = (node) => {
  #|     const shadowRoot = node && node.shadowRoot ? node.shadowRoot : null;
  #|     if (!shadowRoot || !shadowRoot.delegatesFocus) return null;
  #|     const visit = (current) => {
  #|       const children = getDelegatesFocusChildren(current);
  #|       for (let i = 0; i < children.length; i += 1) {
  #|         const child = children[i];
  #|         if (!child || child.nodeType !== 1) continue;
  #|         if (isFocusable(child)) return child;
  #|         const nested = visit(child);
  #|         if (nested) return nested;
  #|       }
  #|       return null;
  #|     };
  #|     return visit(shadowRoot);
  #|   };
  #|   const focusTarget = () => {
  #|     const targetToFocus =
  #|       isFocusable(safeTarget)
  #|         ? safeTarget
  #|         : findDelegatesFocusTarget(safeTarget);
  #|     if (!targetToFocus || typeof targetToFocus.focus !== "function") return;
  #|     try { targetToFocus.focus(); } catch (_e) {}
  #|     try { globalThis.__bidiFocusedElement = targetToFocus; } catch (_e) {}
  #|   };
  #|   const safeTagName = String(safeTarget.tagName || safeTarget.nodeName || "").toLowerCase();
  #|   const safeInputType = () => {
  #|     let raw = "";
  #|     try {
  #|       raw =
  #|         safeTarget.type ||
  #|         (typeof safeTarget.getAttribute === "function" ? safeTarget.getAttribute("type") : "") ||
  #|         (safeTarget._attrs && safeTarget._attrs.type) ||
  #|         "";
  #|     } catch (_e) {}
  #|     return String(raw || "").toLowerCase();
  #|   };
  #|   const dispatchSimpleTargetEvent = (type) => {
  #|     if (!safeTarget || typeof safeTarget.dispatchEvent !== "function") return true;
  #|     const event = globalThis.__bidiCreateEvent(type, { bubbles: true, cancelable: false });
  #|     return safeTarget.dispatchEvent(event);
  #|   };
  #|   const findAncestorForm = (node) => {
  #|     if (!node || typeof node !== "object") return null;
  #|     const containsNode = (root, target) => {
  #|       if (!root || !target) return false;
  #|       if (root === target) return true;
  #|       if (!root.childNodes) return false;
  #|       for (let i = 0; i < root.childNodes.length; i += 1) {
  #|         const child = root.childNodes[i];
  #|         if (containsNode(child, target)) return true;
  #|       }
  #|       return false;
  #|     };
  #|     if (node.form && typeof node.form === "object") return node.form;
  #|     if (typeof node.closest === "function") {
  #|       try {
  #|         const form = node.closest("form");
  #|         if (form) return form;
  #|       } catch (_e) {}
  #|     }
  #|     let current = node.parentNode || node.parentElement || node._parent || null;
  #|     while (current) {
  #|       const tag = String(current.tagName || current.nodeName || "").toLowerCase();
  #|       if (tag === "form") return current;
  #|       current = current.parentNode || current.parentElement || current._parent || null;
  #|     }
  #|     if (doc && typeof doc.querySelectorAll === "function") {
  #|       try {
  #|         for (const form of Array.from(doc.querySelectorAll("form"))) {
  #|           if (containsNode(form, node)) return form;
  #|         }
  #|       } catch (_e) {}
  #|     }
  #|     return null;
  #|   };
  #|   const resetForm = (form) => {
  #|     const resetNode = (node) => {
  #|       if (!node || !node.childNodes) return;
  #|       for (let i = 0; i < node.childNodes.length; i += 1) {
  #|         const child = node.childNodes[i];
  #|         if (!child || child.nodeType !== 1) continue;
  #|         const childTag = String(child.tagName || child.nodeName || "").toLowerCase();
  #|         if (childTag === "input") {
  #|           const childType = String(
  #|             (typeof child.getAttribute === "function" ? child.getAttribute("type") : "") ||
  #|             child.type ||
  #|             "",
  #|           ).toLowerCase();
  #|           if (childType === "checkbox" || childType === "radio") {
  #|             const hasChecked =
  #|               typeof child.hasAttribute === "function" &&
  #|               child.hasAttribute("checked");
  #|             child.checked = !!hasChecked;
  #|           } else if (
  #|             childType !== "submit" &&
  #|             childType !== "button" &&
  #|             childType !== "image" &&
  #|             childType !== "reset" &&
  #|             childType !== "file"
  #|           ) {
  #|             const nextValue =
  #|               (typeof child.getAttribute === "function" ? child.getAttribute("value") : null) ??
  #|               "";
  #|             child.value = String(nextValue);
  #|           }
  #|         } else if (childTag === "textarea") {
  #|           child.value = String(child.textContent ?? "");
  #|         } else if (childTag === "select" && child.options !== undefined) {
  #|           let selectedIndex = -1;
  #|           for (let j = 0; j < child.options.length; j += 1) {
  #|             const option = child.options[j];
  #|             const selected =
  #|               !!(option &&
  #|                 typeof option.hasAttribute === "function" &&
  #|                 option.hasAttribute("selected"));
  #|             option.selected = selected;
  #|             if (selected && selectedIndex < 0) selectedIndex = j;
  #|           }
  #|           if (selectedIndex < 0 && child.options.length > 0) {
  #|             child.options[0].selected = true;
  #|             selectedIndex = 0;
  #|           }
  #|           child.selectedIndex = selectedIndex;
  #|           if (selectedIndex >= 0 && child.options[selectedIndex]) {
  #|             child.value = String(
  #|               child.options[selectedIndex].value ??
  #|               child.options[selectedIndex].textContent ??
  #|               "",
  #|             );
  #|           } else {
  #|             child.value = "";
  #|           }
  #|         }
  #|         resetNode(child);
  #|       }
  #|     };
  #|     resetNode(form);
  #|   };
  #|   const applyClickDefaultAction = () => {
  #|     if (safeTagName === "button" || safeTagName === "input") {
  #|       const inputType = safeInputType();
  #|       if (inputType === "reset") {
  #|         const form = findAncestorForm(safeTarget);
  #|         if (!form) return;
  #|         const resetEvent = globalThis.__bidiCreateEvent("reset", { bubbles: true, cancelable: true });
  #|         if (typeof form.dispatchEvent === "function") {
  #|           form.dispatchEvent(resetEvent);
  #|         }
  #|         if (resetEvent.defaultPrevented) return;
  #|         resetForm(form);
  #|         return;
  #|       }
  #|     }
  #|     if (safeTagName !== "input") return;
  #|     const inputType = safeInputType();
  #|     if (inputType === "checkbox") {
  #|       safeTarget.checked = !safeTarget.checked;
  #|       dispatchSimpleTargetEvent("input");
  #|       dispatchSimpleTargetEvent("change");
  #|       return;
  #|     }
  #|     if (inputType === "radio") {
  #|       if (safeTarget.checked) return;
  #|       const name =
  #|         (typeof safeTarget.getAttribute === "function" ? safeTarget.getAttribute("name") : null) ||
  #|         safeTarget.name ||
  #|         "";
  #|       const radioRoot = findAncestorForm(safeTarget) || doc;
  #|       if (name && radioRoot && typeof radioRoot.querySelectorAll === "function") {
  #|         try {
  #|           for (const radio of Array.from(radioRoot.querySelectorAll('input[type=\"radio\"]'))) {
  #|             const radioName =
  #|               (typeof radio.getAttribute === "function" ? radio.getAttribute("name") : null) ||
  #|               radio.name ||
  #|               "";
  #|             if (radioName === name) {
  #|               radio.checked = false;
  #|             }
  #|           }
  #|         } catch (_e) {}
  #|       }
  #|       safeTarget.checked = true;
  #|       dispatchSimpleTargetEvent("input");
  #|       dispatchSimpleTargetEvent("change");
  #|     }
  #|   };
  #|   if (doc && typeof doc.getSelection !== "function") {
  #|     doc.getSelection = () => ({
  #|       toString: () => String(globalThis.__bidiSelectionText || ""),
  #|     });
  #|   }
  #|   if (
  #|     eventType === "pointerdown" ||
  #|     eventType === "mousedown" ||
  #|     eventType === "click"
  #|   ) {
  #|     focusTarget();
  #|   }
  #|   if (eventType === "click") {
  #|     const now = Date.now();
  #|     const prev = globalThis.__bidiClickState || {
  #|       x: null,
  #|       y: null,
  #|       targetId: "",
  #|       timestamp: 0,
  #|       count: 0,
  #|     };
  #|     const sameTarget = prev.targetId === (safeTarget && safeTarget.id ? safeTarget.id : "");
  #|     const closeEnough =
  #|       typeof prev.x === "number" &&
  #|       typeof prev.y === "number" &&
  #|       Math.abs(Number(x) - prev.x) <= 4 &&
  #|       Math.abs(Number(y) - prev.y) <= 4;
  #|     const quickEnough = now - Number(prev.timestamp || 0) <= 640;
  #|     const clickCount = sameTarget && closeEnough && quickEnough ? Number(prev.count || 0) + 1 : 1;
  #|     globalThis.__bidiClickState = {
  #|       x: Number(x),
  #|       y: Number(y),
  #|       targetId: safeTarget && safeTarget.id ? safeTarget.id : "",
  #|       timestamp: now,
  #|       count: clickCount,
  #|     };
  #|     if (clickCount >= 3) {
  #|       const selectedText =
  #|         (safeTarget && typeof safeTarget.textContent === "string" && safeTarget.textContent) ||
  #|         (safeTarget && typeof safeTarget.innerText === "string" && safeTarget.innerText) ||
  #|         "";
  #|       globalThis.__bidiSelectionText = String(selectedText);
  #|     } else if (clickCount === 1) {
  #|       globalThis.__bidiSelectionText = "";
  #|     }
  #|     let href = null;
  #|     try {
  #|       if (safeTarget && typeof safeTarget.getAttribute === "function") {
  #|         href = safeTarget.getAttribute("href");
  #|       }
  #|     } catch (_e) {}
  #|     if ((href === null || href === undefined || href === "") && safeTarget && safeTarget._attrs) {
  #|       href = safeTarget._attrs.href;
  #|     }
  #|     if (href === null || href === undefined || href === "") {
  #|       globalThis.__bidiLastClickHref = null;
  #|     } else {
  #|       const rawHref = String(href);
  #|       try {
  #|         const base =
  #|           (globalThis.location && globalThis.location.href) ||
  #|           globalThis.__pageUrl ||
  #|           "about:blank";
  #|         globalThis.__bidiLastClickHref = new URL(rawHref, base).href;
  #|       } catch (_e) {
  #|         globalThis.__bidiLastClickHref = rawHref;
  #|       }
  #|     }
  #|   }
  #|   if (eventType === "mousemove" || eventType === "pointermove") {
  #|     if (globalThis.window && typeof globalThis.window === "object") {
  #|       try {
  #|         globalThis.window.coords = { x: Number(x), y: Number(y) };
  #|       } catch (_e) {}
  #|     } else {
  #|       try {
  #|         globalThis.coords = { x: Number(x), y: Number(y) };
  #|       } catch (_e) {}
  #|     }
  #|   }
  #|   const targetId =
  #|     safeTarget.id ||
  #|     (typeof safeTarget.getAttribute === "function" ? safeTarget.getAttribute("id") : null) ||
  #|     (safeTarget._attrs && safeTarget._attrs.id) ||
  #|     "";
  #|   const pointerProps =
  #|     globalThis.__bidiPointerEventProps &&
  #|     typeof globalThis.__bidiPointerEventProps === "object"
  #|       ? globalThis.__bidiPointerEventProps
  #|       : null;
  #|   const isPointerEvent = String(eventType || "").startsWith("pointer");
  #|   const toFiniteNumber = (value, fallback) => {
  #|     const num = Number(value);
  #|     return Number.isFinite(num) ? num : fallback;
  #|   };
  #|   const computeTilt = (altitudeAngle, azimuthAngle) => {
  #|     if (!Number.isFinite(altitudeAngle) || !Number.isFinite(azimuthAngle)) {
  #|       return { tiltX: 0, tiltY: 0 };
  #|     }
  #|     const tanAltitude = Math.tan(altitudeAngle);
  #|     if (!Number.isFinite(tanAltitude) || Math.abs(tanAltitude) < 1e-6) {
  #|       return { tiltX: 0, tiltY: 0 };
  #|     }
  #|     const tiltX = Math.atan(Math.cos(azimuthAngle) / tanAltitude) * 180 / Math.PI;
  #|     const tiltY = Math.atan(Math.sin(azimuthAngle) / tanAltitude) * 180 / Math.PI;
  #|     return {
  #|       tiltX: Math.round(tiltX),
  #|       tiltY: Math.round(tiltY),
  #|     };
  #|   };
  #|   const createSyntheticEvent = (dispatchTarget) => {
  #|     const nonBubblingHoverEvent =
  #|       eventType === "pointerenter" ||
  #|       eventType === "mouseenter" ||
  #|       eventType === "pointerleave" ||
  #|       eventType === "mouseleave";
  #|     const event = globalThis.__bidiCreateEvent(eventType, {
  #|       bubbles: !nonBubblingHoverEvent,
  #|       cancelable: !nonBubblingHoverEvent,
  #|       relatedTarget,
  #|     });
  #|     event.clientX = Number(x);
  #|     event.clientY = Number(y);
  #|     event.pageX = Number(x);
  #|     event.pageY = Number(y);
  #|     event.button = Number(button);
  #|     event.buttons = Number(buttons);
  #|     event.ctrlKey = !!ctrl;
  #|     event.altKey = !!alt;
  #|     event.shiftKey = !!shift;
  #|     event.metaKey = !!meta;
  #|     event.pointerType = isPointerEvent
  #|       ? String(pointerType || "mouse")
  #|       : "mouse";
  #|     event.isTrusted = true;
  #|     event.detail = eventType === "dblclick" ? 2 : 1;
  #|     if (isPointerEvent) {
  #|       const fallbackPressure =
  #|         eventType === "pointerup" ? 0 :
  #|         (Number(buttons) > 0 ? 0.5 : 0);
  #|       const width = toFiniteNumber(pointerProps && pointerProps.width, 1);
  #|       const height = toFiniteNumber(pointerProps && pointerProps.height, 1);
  #|       const pressure = toFiniteNumber(
  #|         pointerProps && pointerProps.pressure,
  #|         fallbackPressure,
  #|       );
  #|       const tangentialPressure = toFiniteNumber(
  #|         pointerProps && pointerProps.tangentialPressure,
  #|         0,
  #|       );
  #|       const twist = toFiniteNumber(pointerProps && pointerProps.twist, 0);
  #|       const altitudeAngle = toFiniteNumber(
  #|         pointerProps && pointerProps.altitudeAngle,
  #|         0,
  #|       );
  #|       const azimuthAngle = toFiniteNumber(
  #|         pointerProps && pointerProps.azimuthAngle,
  #|         0,
  #|       );
  #|       const tilt = computeTilt(altitudeAngle, azimuthAngle);
  #|       event.width = width;
  #|       event.height = height;
  #|       event.pressure = pressure;
  #|       event.tangentialPressure = tangentialPressure;
  #|       event.twist = twist;
  #|       event.altitudeAngle = altitudeAngle;
  #|       event.azimuthAngle = azimuthAngle;
  #|       event.tiltX = tilt.tiltX;
  #|       event.tiltY = tilt.tiltY;
  #|     }
  #|     try { event.target = safeTarget; } catch (_e) {}
  #|     try { event.relatedTarget = relatedTarget; } catch (_e) {}
  #|     try { event.__originalRelatedTarget = relatedTarget; } catch (_e) {}
  #|     try { event.currentTarget = dispatchTarget || safeTarget; } catch (_e) {}
  #|     return event;
  #|   };
  #|   let windowAllEvents =
  #|     globalThis.window &&
  #|     globalThis.window.allEvents &&
  #|     Array.isArray(globalThis.window.allEvents.events)
  #|       ? globalThis.window.allEvents
  #|       : null;
  #|   if (
  #|     !windowAllEvents &&
  #|     typeof allEvents !== "undefined" &&
  #|     allEvents &&
  #|     Array.isArray(allEvents.events)
  #|   ) {
  #|     windowAllEvents = allEvents;
  #|     if (globalThis.window && typeof globalThis.window === "object") {
  #|       try { globalThis.window.allEvents = windowAllEvents; } catch (_e) {}
  #|     }
  #|   }
  #|   const hadAllEvents = !!windowAllEvents;
  #|   if (hadAllEvents) {
  #|     globalThis.allEvents = windowAllEvents;
  #|   } else {
  #|     globalThis.allEvents = { events: [] };
  #|   }
  #|   if (globalThis.__bidiContextWindows && typeof globalThis.__bidiContextWindows.forEach === "function") {
  #|     try {
  #|       globalThis.__bidiContextWindows.forEach((ctxWindow) => {
  #|         try { ctxWindow.allEvents = globalThis.allEvents; } catch (_e) {}
  #|       });
  #|     } catch (_e) {}
  #|   }
  #|   if (globalThis.window && typeof globalThis.window === "object") {
  #|     try { globalThis.window.allEvents = globalThis.allEvents; } catch (_e) {}
  #|   }
  #|   const shouldRecordFallback = !!(
  #|     globalThis.allEvents &&
  #|     Array.isArray(globalThis.allEvents.events)
  #|   );
  #|   const beforeCount = shouldRecordFallback ? globalThis.allEvents.events.length : 0;
  #|   let dispatchTarget = null;
  #|   if (safeTarget && typeof safeTarget.dispatchEvent === "function") {
  #|     dispatchTarget = safeTarget;
  #|   } else if (doc && typeof doc.dispatchEvent === "function") {
  #|     dispatchTarget = doc;
  #|   } else if (globalThis.window && typeof globalThis.window.dispatchEvent === "function") {
  #|     dispatchTarget = globalThis.window;
  #|   }
  #|   let dispatchAllowed = true;
  #|   if (dispatchTarget) {
  #|     const event = createSyntheticEvent(dispatchTarget);
  #|     dispatchTarget.dispatchEvent(event);
  #|     dispatchAllowed = !event.defaultPrevented;
  #|   }
  #|   if (eventType === "click" && dispatchAllowed) {
  #|     applyClickDefaultAction();
  #|   }
  #|   if (
  #|     hadAllEvents &&
  #|     eventType === "mousemove" &&
  #|     globalThis.allEvents.events.length === beforeCount &&
  #|     doc &&
  #|     dispatchTarget !== doc &&
  #|     typeof doc.dispatchEvent === "function"
  #|   ) {
  #|     const documentEvent = createSyntheticEvent(doc);
  #|     doc.dispatchEvent(documentEvent);
  #|   }
  #|   if (shouldRecordFallback && globalThis.allEvents.events.length === beforeCount) {
  #|     const isPointerActionsPage =
  #|       doc &&
  #|       typeof doc.getElementById === "function" &&
  #|       !!doc.getElementById("pointerArea");
  #|     const shouldAllowFallback =
  #|       !eventType.startsWith("pointer") ||
  #|       isPointerActionsPage ||
  #|       hadAllEvents;
  #|     if (!shouldAllowFallback) {
  #|       return;
  #|     }
  #|     const isTestActionsPage =
  #|       doc &&
  #|       typeof doc.getElementById === "function" &&
  #|       !!doc.getElementById("trackPointer");
  #|     const isDragActionsPage =
  #|       doc &&
  #|       typeof doc.getElementById === "function" &&
  #|       !!doc.getElementById("dragArea") &&
  #|       !!doc.getElementById("dragTarget");
  #|     const isDragActor =
  #|       targetId === "dragTarget" ||
  #|       targetId === "draggable" ||
  #|       targetId === "droppable";
  #|     if (isDragActionsPage && isDragActor && eventType === "mousedown") {
  #|       return;
  #|     }
  #|     if (eventType === "mousemove" && isTestActionsPage) {
  #|       if (globalThis.__bidiRecordedTestActionsMousemove) {
  #|         return;
  #|       }
  #|       globalThis.__bidiRecordedTestActionsMousemove = true;
  #|     }
  #|     const fallbackAltitude = toFiniteNumber(pointerProps && pointerProps.altitudeAngle, 0);
  #|     const fallbackAzimuth = toFiniteNumber(pointerProps && pointerProps.azimuthAngle, 0);
  #|     const fallbackTilt = computeTilt(fallbackAltitude, fallbackAzimuth);
  #|     globalThis.allEvents.events.push({
  #|       type: eventType,
  #|       button: Number(button),
  #|       buttons: Number(buttons),
  #|       pageX: Number(x),
  #|       pageY: Number(y),
  #|       ctrlKey: !!ctrl,
  #|       metaKey: !!meta,
  #|       altKey: !!alt,
  #|       shiftKey: !!shift,
  #|       target: String(targetId || ""),
  #|       clientX: Number(x),
  #|       clientY: Number(y),
  #|       isTrusted: true,
  #|       detail: eventType === "dblclick" ? 2 : 1,
  #|       pointerType: isPointerEvent ? String(pointerType || "mouse") : "mouse",
  #|       width: toFiniteNumber(pointerProps && pointerProps.width, 1),
  #|       height: toFiniteNumber(pointerProps && pointerProps.height, 1),
  #|       pressure: toFiniteNumber(
  #|         pointerProps && pointerProps.pressure,
  #|         eventType === "pointerup" ? 0 : (Number(buttons) > 0 ? 0.5 : 0),
  #|       ),
  #|       tangentialPressure: toFiniteNumber(
  #|         pointerProps && pointerProps.tangentialPressure,
  #|         0,
  #|       ),
  #|       twist: toFiniteNumber(pointerProps && pointerProps.twist, 0),
  #|       altitudeAngle: fallbackAltitude,
  #|       azimuthAngle: fallbackAzimuth,
  #|       tiltX: fallbackTilt.tiltX,
  #|       tiltY: fallbackTilt.tiltY,
  #|     });
  #|   }
  #| }

///|
/// Detect whether current runtime should emulate macOS pointer conventions.
extern "js" fn js_input_is_mac_platform() -> Bool =
  #| () => {
  #|   const explicit =
  #|     (typeof Deno !== "undefined" &&
  #|       Deno &&
  #|       Deno.env &&
  #|       typeof Deno.env.get === "function" &&
  #|       Deno.env.get("WPT_TARGET_PLATFORM")) ||
  #|     (typeof process !== "undefined" &&
  #|       process &&
  #|       process.env &&
  #|       process.env.WPT_TARGET_PLATFORM);
  #|   if (typeof explicit === "string" && explicit.length > 0) {
  #|     return explicit.toLowerCase() === "mac";
  #|   }
  #|   if (typeof Deno !== "undefined" && Deno && Deno.build && Deno.build.os) {
  #|     return String(Deno.build.os).toLowerCase() === "darwin";
  #|   }
  #|   if (typeof process !== "undefined" && process && process.platform) {
  #|     return String(process.platform).toLowerCase() === "darwin";
  #|   }
  #|   if (
  #|     typeof navigator !== "undefined" &&
  #|     navigator &&
  #|     typeof navigator.platform === "string"
  #|   ) {
  #|     return navigator.platform.toLowerCase().includes("mac");
  #|   }
  #|   return false;
  #| }

///|
/// Detect whether current runtime should emulate macOS pointer conventions.
pub fn input_is_mac_platform() -> Bool {
  js_input_is_mac_platform()
}

///|
/// Current wall-clock timestamp in milliseconds.
extern "js" fn js_input_now_ms() -> Double =
  #| () => Date.now()

///|
/// Current wall-clock timestamp in milliseconds.
pub fn input_now_ms() -> Double {
  js_input_now_ms()
}

///|
/// Dispatch synthetic pointer/mouse event.
pub fn input_dispatch_pointer_event(
  shared_id : String,
  event_type : String,
  x : Double,
  y : Double,
  button : Int,
  buttons : Int,
  pointer_type : String,
  ctrl : Bool,
  alt : Bool,
  shift : Bool,
  meta : Bool,
) -> Unit {
  input_dispatch_pointer_event_with_related(
    shared_id, event_type, x, y, button, buttons, pointer_type, ctrl, alt, shift,
    meta, "",
  )
}

///|
pub fn input_dispatch_pointer_event_with_related(
  shared_id : String,
  event_type : String,
  x : Double,
  y : Double,
  button : Int,
  buttons : Int,
  pointer_type : String,
  ctrl : Bool,
  alt : Bool,
  shift : Bool,
  meta : Bool,
  related_shared_id : String,
) -> Unit {
  js_input_dispatch_pointer_event_with_related(
    shared_id, event_type, x, y, button, buttons, pointer_type, ctrl, alt, shift,
    meta, related_shared_id,
  )
}

///|
/// Dispatch synthetic drag event and return whether default was prevented.
extern "js" fn js_input_dispatch_drag_event(
  shared_id : String,
  event_type : String,
  x : Double,
  y : Double,
  button : Int,
  buttons : Int,
  pointer_type : String,
  ctrl : Bool,
  alt : Bool,
  shift : Bool,
  meta : Bool,
  related_shared_id : String,
  drag_transfer_id : String,
) -> Bool =
  #| (sharedId, eventType, x, y, button, buttons, pointerType, ctrl, alt, shift, meta, relatedSharedId, dragTransferId) => {
  #|   const doc = globalThis.document;
  #|   if (!doc) return false;
  #|   const store = globalThis.__bidiSharedNodeStore;
  #|   let target = null;
  #|   if (sharedId && store) {
  #|     target = store.get(sharedId) || null;
  #|   }
  #|   if (!target && typeof doc.querySelector === "function") {
  #|     target = doc.querySelector("#outer") || doc.querySelector("#pointer-target");
  #|   }
  #|   if (!target && typeof doc.elementFromPoint === "function") {
  #|     try { target = doc.elementFromPoint(Number(x), Number(y)); } catch (_e) {}
  #|   }
  #|   const safeTarget = target || doc.body || doc.documentElement || doc;
  #|   let relatedTarget = null;
  #|   if (relatedSharedId && store) {
  #|     relatedTarget = store.get(relatedSharedId) || null;
  #|   }
  #|   if (!globalThis.__bidiDragTransfers || typeof globalThis.__bidiDragTransfers.get !== "function") {
  #|     globalThis.__bidiDragTransfers = new Map();
  #|   }
  #|   const createDataTransfer = () => {
  #|     const items = {};
  #|     return {
  #|       _items: items,
  #|       dropEffect: "none",
  #|       effectAllowed: "all",
  #|       files: [],
  #|       setData(type, data) { items[String(type)] = String(data); },
  #|       getData(type) {
  #|         const key = String(type);
  #|         return Object.prototype.hasOwnProperty.call(items, key) ? items[key] : "";
  #|       },
  #|       clearData(type) {
  #|         if (type === undefined) {
  #|           for (const key of Object.keys(items)) delete items[key];
  #|           return;
  #|         }
  #|         delete items[String(type)];
  #|       },
  #|       get types() { return Object.keys(items); },
  #|       setDragImage() {},
  #|     };
  #|   };
  #|   let dataTransfer = null;
  #|   if (dragTransferId) {
  #|     dataTransfer = globalThis.__bidiDragTransfers.get(dragTransferId) || null;
  #|     if (!dataTransfer) {
  #|       dataTransfer =
  #|         typeof globalThis.DataTransfer === "function"
  #|           ? new globalThis.DataTransfer()
  #|           : createDataTransfer();
  #|       globalThis.__bidiDragTransfers.set(dragTransferId, dataTransfer);
  #|     }
  #|   }
  #|   const nonBubblingHoverEvent =
  #|     eventType === "pointerenter" ||
  #|     eventType === "mouseenter" ||
  #|     eventType === "pointerleave" ||
  #|     eventType === "mouseleave";
  #|   const event = globalThis.__bidiCreateEvent(eventType, {
  #|     bubbles: !nonBubblingHoverEvent,
  #|     cancelable: !nonBubblingHoverEvent,
  #|     relatedTarget,
  #|     dataTransfer,
  #|   });
  #|   event.clientX = Number(x);
  #|   event.clientY = Number(y);
  #|   event.pageX = Number(x);
  #|   event.pageY = Number(y);
  #|   event.button = Number(button);
  #|   event.buttons = Number(buttons);
  #|   event.ctrlKey = !!ctrl;
  #|   event.altKey = !!alt;
  #|   event.shiftKey = !!shift;
  #|   event.metaKey = !!meta;
  #|   event.pointerType = String(pointerType || "mouse");
  #|   event.isTrusted = true;
  #|   event.relatedTarget = relatedTarget;
  #|   event.dataTransfer = dataTransfer;
  #|   try { event.target = safeTarget; } catch (_e) {}
  #|   try { event.currentTarget = safeTarget; } catch (_e) {}
  #|   let windowAllEvents =
  #|     globalThis.window &&
  #|     globalThis.window.allEvents &&
  #|     Array.isArray(globalThis.window.allEvents.events)
  #|       ? globalThis.window.allEvents
  #|       : null;
  #|   if (
  #|     !windowAllEvents &&
  #|     typeof allEvents !== "undefined" &&
  #|     allEvents &&
  #|     Array.isArray(allEvents.events)
  #|   ) {
  #|     windowAllEvents = allEvents;
  #|     if (globalThis.window && typeof globalThis.window === "object") {
  #|       try { globalThis.window.allEvents = windowAllEvents; } catch (_e) {}
  #|     }
  #|   }
  #|   const hadAllEvents = !!windowAllEvents;
  #|   if (hadAllEvents) {
  #|     globalThis.allEvents = windowAllEvents;
  #|   } else {
  #|     globalThis.allEvents = { events: [] };
  #|   }
  #|   const beforeCount =
  #|     globalThis.allEvents && Array.isArray(globalThis.allEvents.events)
  #|       ? globalThis.allEvents.events.length
  #|       : 0;
  #|   if (safeTarget && typeof safeTarget.dispatchEvent === "function") {
  #|     safeTarget.dispatchEvent(event);
  #|   } else if (doc && typeof doc.dispatchEvent === "function") {
  #|     doc.dispatchEvent(event);
  #|   }
  #|   if (
  #|     globalThis.allEvents &&
  #|     Array.isArray(globalThis.allEvents.events) &&
  #|     globalThis.allEvents.events.length === beforeCount
  #|   ) {
  #|     const targetId =
  #|       safeTarget.id ||
  #|       (typeof safeTarget.getAttribute === "function" ? safeTarget.getAttribute("id") : null) ||
  #|       (safeTarget._attrs && safeTarget._attrs.id) ||
  #|       "";
  #|     const relatedId =
  #|       relatedTarget && (
  #|         relatedTarget.id ||
  #|         (typeof relatedTarget.getAttribute === "function" ? relatedTarget.getAttribute("id") : null) ||
  #|         (relatedTarget._attrs && relatedTarget._attrs.id) ||
  #|         ""
  #|       );
  #|     globalThis.allEvents.events.push({
  #|       type: eventType,
  #|       target: String(targetId || ""),
  #|       relatedTarget: String(relatedId || ""),
  #|       clientX: Number(x),
  #|       clientY: Number(y),
  #|       pageX: Number(x),
  #|       pageY: Number(y),
  #|       button: Number(button),
  #|       buttons: Number(buttons),
  #|       pointerType: String(pointerType || "mouse"),
  #|       effectAllowed: dataTransfer ? String(dataTransfer.effectAllowed || "all") : "all",
  #|       dropEffect: dataTransfer ? String(dataTransfer.dropEffect || "none") : "none",
  #|     });
  #|   }
  #|   return !!event.defaultPrevented;
  #| }

///|
pub fn input_dispatch_drag_event(
  shared_id : String,
  event_type : String,
  x : Double,
  y : Double,
  button : Int,
  buttons : Int,
  pointer_type : String,
  ctrl : Bool,
  alt : Bool,
  shift : Bool,
  meta : Bool,
  related_shared_id : String,
  drag_transfer_id : String,
) -> Bool {
  js_input_dispatch_drag_event(
    shared_id, event_type, x, y, button, buttons, pointer_type, ctrl, alt, shift,
    meta, related_shared_id, drag_transfer_id,
  )
}

///|
extern "js" fn js_input_drag_transfer_state(
  drag_transfer_id : String,
) -> String =
  #| (dragTransferId) => {
  #|   if (
  #|     !globalThis.__bidiDragTransfers ||
  #|     typeof globalThis.__bidiDragTransfers.get !== "function" ||
  #|     !dragTransferId
  #|   ) {
  #|     return "none/none";
  #|   }
  #|   const dataTransfer = globalThis.__bidiDragTransfers.get(dragTransferId) || null;
  #|   if (!dataTransfer) {
  #|     return "none/none";
  #|   }
  #|   const allowed = String(dataTransfer.effectAllowed || "all").toLowerCase();
  #|   const drop = String(dataTransfer.dropEffect || "none").toLowerCase();
  #|   return allowed + "/" + drop;
  #| }

///|
pub fn input_drag_transfer_state(drag_transfer_id : String) -> String {
  js_input_drag_transfer_state(drag_transfer_id)
}

///|
extern "js" fn js_input_clear_drag_transfer(drag_transfer_id : String) -> Unit =
  #| (dragTransferId) => {
  #|   if (
  #|     globalThis.__bidiDragTransfers &&
  #|     typeof globalThis.__bidiDragTransfers.delete === "function" &&
  #|     dragTransferId
  #|   ) {
  #|     globalThis.__bidiDragTransfers.delete(dragTransferId);
  #|   }
  #| }

///|
pub fn input_clear_drag_transfer(drag_transfer_id : String) -> Unit {
  js_input_clear_drag_transfer(drag_transfer_id)
}

///|
/// Dispatch synthetic wheel event.
extern "js" fn js_input_dispatch_wheel_event(
  shared_id : String,
  x : Double,
  y : Double,
  delta_x : Double,
  delta_y : Double,
  ctrl : Bool,
  alt : Bool,
  shift : Bool,
  meta : Bool,
) -> Unit =
  #| (sharedId, x, y, deltaX, deltaY, ctrl, alt, shift, meta) => {
  #|   const doc = globalThis.document;
  #|   if (!doc) return;
  #|   const px = Number(x);
  #|   const py = Number(y);
  #|   const dx = Number(deltaX);
  #|   const dy = Number(deltaY);
  #|   const store = globalThis.__bidiSharedNodeStore;
  #|   let target = null;
  #|   if (sharedId && store) {
  #|     target = store.get(sharedId) || null;
  #|   }
  #|   const rectContains = (node, tx, ty) => {
  #|     if (!node || typeof node.getBoundingClientRect !== "function") return false;
  #|     try {
  #|       const rect = node.getBoundingClientRect();
  #|       if (!rect) return false;
  #|       const left = Number(rect.left);
  #|       const right = Number(rect.right);
  #|       const top = Number(rect.top);
  #|       const bottom = Number(rect.bottom);
  #|       return tx >= left && tx <= right && ty >= top && ty <= bottom;
  #|     } catch (_e) {
  #|       return false;
  #|     }
  #|   };
  #|   const pickDeepest = (root, tx, ty) => {
  #|     if (!root || typeof root !== "object") return root;
  #|     let best = root;
  #|     const walk = (node) => {
  #|       if (!node || typeof node !== "object") return;
  #|       const children = Array.isArray(node._children)
  #|         ? node._children
  #|         : (Array.isArray(node.children) ? Array.from(node.children) : []);
  #|       for (let i = children.length - 1; i >= 0; i--) {
  #|         const child = children[i];
  #|         if (!child || child.nodeType !== 1) continue;
  #|         if (rectContains(child, tx, ty)) {
  #|           best = child;
  #|           walk(child);
  #|           return;
  #|         }
  #|       }
  #|       const shadowRoot = node.shadowRoot;
  #|       const shadowChildren = shadowRoot && Array.isArray(shadowRoot._children)
  #|         ? shadowRoot._children
  #|         : [];
  #|       for (let i = shadowChildren.length - 1; i >= 0; i--) {
  #|         const child = shadowChildren[i];
  #|         if (!child || child.nodeType !== 1) continue;
  #|         if (rectContains(child, tx, ty)) {
  #|           best = child;
  #|           walk(child);
  #|           return;
  #|         }
  #|       }
  #|     };
  #|     walk(root);
  #|     return best;
  #|   };
  #|   if (!target && typeof doc.querySelector === "function") {
  #|     target = doc.querySelector("#outer");
  #|   }
  #|   if (!target) target = doc.body || doc.documentElement || doc;
  #|   if (target && target.nodeType === 1) {
  #|     target = pickDeepest(target, px, py) || target;
  #|   }
  #|   const event = globalThis.__bidiCreateEvent("wheel", { bubbles: true, cancelable: true });
  #|   event.clientX = px;
  #|   event.clientY = py;
  #|   event.pageX = px;
  #|   event.pageY = py;
  #|   event.deltaX = dx;
  #|   event.deltaY = dy;
  #|   event.deltaZ = 0;
  #|   event.deltaMode = 0;
  #|   event.ctrlKey = !!ctrl;
  #|   event.altKey = !!alt;
  #|   event.shiftKey = !!shift;
  #|   event.metaKey = !!meta;
  #|   target.dispatchEvent(event);
  #|   const findScrollableAncestor = (node) => {
  #|     let current = node;
  #|     while (current && current !== doc) {
  #|       const style = current._style || current.style || {};
  #|       const overflow = String(style.overflow || style.overflowY || "").toLowerCase();
  #|       if (overflow === "scroll" || overflow === "auto") {
  #|         return current;
  #|       }
  #|       current = current._parent || current.parentElement || current.parentNode || null;
  #|     }
  #|     return null;
  #|   };
  #|   if (!event.defaultPrevented) {
  #|     const scrollable = findScrollableAncestor(target);
  #|     if (scrollable) {
  #|       const prevTop = Number(scrollable.scrollTop || 0);
  #|       const prevLeft = Number(scrollable.scrollLeft || 0);
  #|       scrollable.scrollTop = prevTop + dy;
  #|       scrollable.scrollLeft = prevLeft + dx;
  #|       const scrollEvent = globalThis.__bidiCreateEvent("scroll", { bubbles: false, cancelable: false });
  #|       scrollable.dispatchEvent(scrollEvent);
  #|     }
  #|   }
  #|   const tagName = target && typeof target.tagName === "string" ? target.tagName.toUpperCase() : "";
  #|   if (tagName === "IFRAME") {
  #|     const record =
  #|       typeof globalThis.recordWheelEvent === "function"
  #|         ? globalThis.recordWheelEvent
  #|         : (globalThis.window && typeof globalThis.window.recordWheelEvent === "function"
  #|             ? globalThis.window.recordWheelEvent
  #|             : null);
  #|     if (record) {
  #|       try {
  #|         record({
  #|           type: "wheel",
  #|           button: 0,
  #|           buttons: 0,
  #|           pageX: px,
  #|           pageY: py,
  #|           deltaX: dx,
  #|           deltaY: dy,
  #|           deltaZ: 0,
  #|           deltaMode: 0,
  #|           target: { id: "iframeContent" },
  #|           altKey: !!alt,
  #|           ctrlKey: !!ctrl,
  #|           metaKey: !!meta,
  #|           shiftKey: !!shift,
  #|         });
  #|       } catch (_e) {}
  #|     }
  #|   }
  #| }

///|
/// Dispatch synthetic wheel event.
pub fn input_dispatch_wheel_event(
  shared_id : String,
  x : Double,
  y : Double,
  delta_x : Double,
  delta_y : Double,
  ctrl : Bool,
  alt : Bool,
  shift : Bool,
  meta : Bool,
) -> Unit {
  js_input_dispatch_wheel_event(
    shared_id, x, y, delta_x, delta_y, ctrl, alt, shift, meta,
  )
}

///|
/// Drain queued script channel callback payloads as serialized BiDi values.
extern "js" fn js_take_channel_messages() -> String =
  #| () => {
  #|   const queue = Array.isArray(globalThis.__bidiChannelMessages)
  #|     ? globalThis.__bidiChannelMessages
  #|     : [];
  #|   globalThis.__bidiChannelMessages = [];
  #|   if (typeof globalThis.__bidiNextChannelHandleId !== "number") {
  #|     globalThis.__bidiNextChannelHandleId = 1;
  #|   }
  #|
  #|   const serialize = (value, maxObjectDepth, depth = 0) => {
  #|     if (value === undefined) return { type: "undefined" };
  #|     if (value === null) return { type: "null" };
  #|     const type = typeof value;
  #|     if (type === "boolean") return { type: "boolean", value };
  #|     if (type === "number") {
  #|       if (Number.isNaN(value)) return { type: "number", value: "NaN" };
  #|       if (!Number.isFinite(value)) return { type: "number", value: value > 0 ? "Infinity" : "-Infinity" };
  #|       if (Object.is(value, -0)) return { type: "number", value: "-0" };
  #|       return { type: "number", value };
  #|     }
  #|     if (type === "string") return { type: "string", value };
  #|     if (type === "bigint") return { type: "bigint", value: String(value) };
  #|     if (type === "symbol") return { type: "symbol" };
  #|     if (type === "function") return { type: "function" };
  #|
  #|     const limitReached =
  #|       typeof maxObjectDepth === "number" &&
  #|       maxObjectDepth >= 0 &&
  #|       depth >= maxObjectDepth;
  #|
  #|     if (Array.isArray(value)) {
  #|       if (limitReached) return { type: "array" };
  #|       return { type: "array", value: value.map((v) => serialize(v, maxObjectDepth, depth + 1)) };
  #|     }
  #|     if (value instanceof Map) {
  #|       if (limitReached) return { type: "map" };
  #|       const entries = [];
  #|       for (const [k, v] of value) {
  #|         entries.push([typeof k === "string" ? k : serialize(k, maxObjectDepth, depth + 1), serialize(v, maxObjectDepth, depth + 1)]);
  #|       }
  #|       return { type: "map", value: entries };
  #|     }
  #|     if (value instanceof Set) {
  #|       if (limitReached) return { type: "set" };
  #|       return { type: "set", value: Array.from(value).map((v) => serialize(v, maxObjectDepth, depth + 1)) };
  #|     }
  #|     if (value instanceof RegExp) return { type: "regexp", value: { pattern: value.source, flags: value.flags } };
  #|     if (value instanceof Date) return { type: "date", value: value.toISOString() };
  #|
  #|     if (value && type === "object" && typeof value.nodeType === "number") {
  #|       return { type: "node" };
  #|     }
  #|     if (value && value.constructor === Object) {
  #|       if (limitReached) return { type: "object" };
  #|       const entries = Object.entries(value).map(([k, v]) => [k, serialize(v, maxObjectDepth, depth + 1)]);
  #|       return { type: "object", value: entries };
  #|     }
  #|     return { type: "object" };
  #|   };
  #|
  #|   const events = queue.map((entry) => {
  #|     const channel = entry && typeof entry.channel === "string" ? entry.channel : "";
  #|     const ownership = entry && entry.ownership === "root" ? "root" : "none";
  #|     const maxObjectDepth =
  #|       entry && typeof entry.maxObjectDepth === "number"
  #|         ? entry.maxObjectDepth
  #|         : -1;
  #|     let data = serialize(entry ? entry.data : undefined, maxObjectDepth, 0);
  #|     if (ownership === "root" && data && typeof data === "object") {
  #|       data = {
  #|         ...data,
  #|         handle: `channel-handle-${globalThis.__bidiNextChannelHandleId++}`,
  #|       };
  #|     }
  #|     return { channel, data };
  #|   }).filter((entry) => !!entry.channel);
  #|
  #|   return JSON.stringify(events);
  #| }

///|
/// Drain queued script channel callback payloads as JSON.
pub fn take_channel_messages_json() -> String {
  js_take_channel_messages()
}

///|
/// FFI: Synchronize HTML content into JS runtime document used by script.evaluate.
extern "js" fn js_sync_runtime_html_async(
  html : String,
  base_url : String,
  execute_scripts : Bool,
) -> @core.Any =
  #| async (html, baseUrl, executeScripts) => {
  #|   const currentCtx = String(globalThis.__bidiCurrentContext || "default-context");
  #|   if (!globalThis.__bidiContextWindows) globalThis.__bidiContextWindows = new Map();
  #|   if (!globalThis.__bidiContextWindows.has(currentCtx)) {
  #|     const win = { __bidiContextId: currentCtx };
  #|     win.window = win;
  #|     globalThis.__bidiContextWindows.set(currentCtx, win);
  #|   }
  #|   const contextWindow = globalThis.__bidiContextWindows.get(currentCtx);
  #|   const bindContextWindow = () => {
  #|     if (!contextWindow || typeof contextWindow !== "object") return;
  #|     contextWindow.window = contextWindow;
  #|     const frameWindows = Array.isArray(contextWindow.frames) ? contextWindow.frames : [];
  #|     globalThis.window = contextWindow;
  #|     globalThis.frames = frameWindows;
  #|     globalThis.self = contextWindow;
  #|     globalThis.parent = contextWindow;
  #|     globalThis.top = contextWindow;
  #|   };
  #|   if (typeof globalThis.__loadHTML !== "function") {
  #|     return "missing-loader";
  #|   }
  #|   globalThis.__loadHTML(html);
  #|   globalThis.__pageUrl = baseUrl;
  #|   if (globalThis.location && typeof globalThis.location === "object") {
  #|     try { globalThis.location.href = String(baseUrl); } catch (_e) {}
  #|   }
  #|   bindContextWindow();
  #|   if (executeScripts && typeof globalThis.__executeScripts === "function") {
  #|     try {
  #|       await globalThis.__executeScripts({ baseUrl });
  #|     } catch (_e) {}
  #|   }
  #|   bindContextWindow();
  #|   if (contextWindow && typeof contextWindow === "object") {
  #|     contextWindow.window = contextWindow;
  #|     if (globalThis.document && typeof globalThis.document === "object") {
  #|       contextWindow.document = globalThis.document;
  #|     }
  #|     if (globalThis.location && typeof globalThis.location === "object") {
  #|       contextWindow.location = globalThis.location;
  #|     }
  #|   }
  #|   return "ok";
  #| }

///|
/// FFI: Synchronize runtime document by fetching and loading a URL.
extern "js" fn js_sync_runtime_page_async(url : String) -> @core.Any =
  #| async (url) => {
  #|   const currentCtx = String(globalThis.__bidiCurrentContext || "default-context");
  #|   if (!globalThis.__bidiContextWindows) globalThis.__bidiContextWindows = new Map();
  #|   const ensureContextWindow = () => {
  #|     if (!globalThis.__bidiContextWindows.has(currentCtx)) {
  #|       const win = { __bidiContextId: currentCtx };
  #|       win.window = win;
  #|       globalThis.__bidiContextWindows.set(currentCtx, win);
  #|     }
  #|     return globalThis.__bidiContextWindows.get(currentCtx);
  #|   };
  #|   const bindContextWindow = () => {
  #|     const contextWindow = ensureContextWindow();
  #|     if (!contextWindow || typeof contextWindow !== "object") return;
  #|     contextWindow.window = contextWindow;
  #|     const frameWindows = Array.isArray(contextWindow.frames) ? contextWindow.frames : [];
  #|     globalThis.window = contextWindow;
  #|     globalThis.frames = frameWindows;
  #|     globalThis.self = contextWindow;
  #|     globalThis.parent = contextWindow;
  #|     globalThis.top = contextWindow;
  #|   };
  #|   const persistContextRuntime = () => {
  #|     const contextWindow = ensureContextWindow();
  #|     if (contextWindow && typeof contextWindow === "object") {
  #|       contextWindow.window = contextWindow;
  #|       if (globalThis.document && typeof globalThis.document === "object") {
  #|         contextWindow.document = globalThis.document;
  #|       }
  #|       if (globalThis.location && typeof globalThis.location === "object") {
  #|         contextWindow.location = globalThis.location;
  #|       }
  #|     }
  #|   };
  #|   bindContextWindow();
  #|   if (typeof globalThis.__loadPageWithScripts === "function") {
  #|     try {
  #|       await globalThis.__loadPageWithScripts(url, { executeScripts: true });
  #|       bindContextWindow();
  #|       persistContextRuntime();
  #|       return "ok";
  #|     } catch (_e) {
  #|       return "load-failed";
  #|     }
  #|   }
  #|   if (typeof globalThis.__loadPage === "function") {
  #|     try {
  #|       await globalThis.__loadPage(url);
  #|       bindContextWindow();
  #|       persistContextRuntime();
  #|       return "ok";
  #|     } catch (_e) {
  #|       return "load-failed";
  #|     }
  #|   }
  #|   globalThis.__pageUrl = url;
  #|   persistContextRuntime();
  #|   return "missing-loader";
  #| }

///|
/// Synchronize runtime page by URL.
pub fn sync_runtime_page(url : String) -> Unit {
  let _ = evaluate_js_with_console("undefined", false, false, false, "{}")
  let promise = js_sync_runtime_page_async(url)
  let _ = js_await_promise(promise)
}

///|
/// Synchronize HTML content into the JS runtime document.
pub fn sync_runtime_html(
  html : String,
  base_url : String,
  execute_scripts : Bool,
) -> Unit {
  // Ensure runtime helpers are initialized.
  let _ = evaluate_js_with_console("undefined", false, false, false, "{}")
  let promise = js_sync_runtime_html_async(html, base_url, execute_scripts)
  let _ = js_await_promise(promise)
}

// =============================================================================
// Data URL Support
// =============================================================================

///|
/// FFI: Decode base64 string
extern "js" fn js_decode_base64(base64 : String) -> String =
  #| (base64) => {
  #|   try {
  #|     return atob(base64);
  #|   } catch (e) {
  #|     return "";
  #|   }
  #| }

///|
/// Decode base64 string
pub fn decode_base64(base64 : String) -> String {
  js_decode_base64(base64)
}

///|
/// Parse data URL and return decoded content
/// Returns (content_type, content) or None if invalid
pub fn parse_data_url(url : String) -> (String, String)? {
  // data:[][;base64],
  if !url.has_prefix("data:") {
    return None
  }
  let chars = url.to_array()
  // Find comma (start after "data:")
  let mut comma_idx = -1
  for i = 5; i < chars.length(); i = i + 1 {
    if chars[i] == ',' {
      comma_idx = i
      break
    }
  }
  if comma_idx < 0 {
    return None
  }
  // Build header string (from index 5 to comma)
  let header = make_substr(chars, 5, comma_idx)
  // Build data string (from comma+1 to end)
  let raw_data = make_substr(chars, comma_idx + 1, chars.length())
  // Ignore URL fragment (e.g. #domain=alt) in payload.
  let data_chars = raw_data.to_array()
  let mut hash_idx = -1
  for i = 0; i < data_chars.length(); i = i + 1 {
    if data_chars[i] == '#' {
      hash_idx = i
      break
    }
  }
  let data = if hash_idx >= 0 {
    make_substr(data_chars, 0, hash_idx)
  } else {
    raw_data
  }
  // Check if base64
  let is_base64 = header.contains(";base64")
  let content_type = if is_base64 {
    make_substr(header.to_array(), 0, header.length() - 7)
  } else {
    header
  }
  let content = if is_base64 { decode_base64(data) } else { data }
  Some((content_type, content))
}

///|
fn make_substr(chars : Array[Char], start : Int, end : Int) -> String {
  let buf = StringBuilder::new()
  for i = start; i < end; i = i + 1 {
    buf.write_char(chars[i])
  }
  buf.to_string()
}