feat(debugger): replace the responses a debugged page receives (#3329)

A page session can answer requests itself: rules (URL part → status, content type, body) are kept per project, edited from the Network tab (Overrides, Override Response… on a request), and applied through js-debug's CDP proxy with Fetch.enable / Fetch.fulfillRequest. Interception is switched off before the connection is dropped, unknown statuses get a reason phrase, cross-origin pages get CORS headers and preflight answers, and rules present at page start wait for the launch response.

The Network list marks a request overridden only when it was sent after the rule that answers it was saved or enabled.

Co-authored-by: ntbang0901 <121003585+ntbang0901@users.noreply.github.com>
This commit is contained in:
ntbang0901
2026-11-15 00:15:09 +08:00
committed by GitHub
parent 10b7340e2a
commit 112ac05052
24 changed files with 1597 additions and 7 deletions
Generated
+2
View File
@@ -4269,6 +4269,7 @@ dependencies = [
name = "ide-dap"
version = "0.1.45"
dependencies = [
"base64 0.22.1",
"futures",
"ide-core",
"ide-heap",
@@ -4287,6 +4288,7 @@ dependencies = [
"specta",
"tempfile",
"tokio",
"tokio-tungstenite",
"tracing",
"tracing-subscriber",
"windows-sys 0.61.2",
+2
View File
@@ -7,6 +7,8 @@ license.workspace = true
[dependencies]
futures.workspace = true
tokio-tungstenite.workspace = true
base64.workspace = true
tempfile.workspace = true
ide-core.workspace = true
ide-language.workspace = true
+528
View File
@@ -0,0 +1,528 @@
//! Replacing the responses a debugged page receives. js-debug hands out a WebSocket that
//! speaks the browser's own protocol (`requestCDPProxy`); over it the browser is told to hold
//! the requests whose URL matches a rule (`Fetch.enable`) and each held request is answered
//! here, with the rule's response or by letting it through.
//!
//! A held request stays held until it is answered, so interception is always switched off
//! (`Fetch.disable`) before the connection is given up: a page whose requests nobody answers hangs.
use crate::{DebugManager, DebugSessionId, REQUEST_TIMEOUT, js_debug};
use base64::Engine;
use futures::{SinkExt, StreamExt};
use ide_core::{IdeError, IdeResult};
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use specta::Type;
use std::collections::HashMap;
use tokio::sync::{oneshot, watch};
use tokio_tungstenite::tungstenite::{Message, http::StatusCode};
/// A response given in place of the server's to every request whose URL contains `url_contains`.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct JsResponseRule {
pub url_contains: String,
pub status: u16,
pub content_type: String,
pub body: String,
}
/// The browser's URL pattern (`*` any text, `?` one character, `\` escapes) for "contains `part`".
pub(crate) fn url_pattern(part: &str) -> String {
let mut pattern = String::with_capacity(part.len() + 2);
pattern.push('*');
for c in part.chars() {
if matches!(c, '*' | '?' | '\\') {
pattern.push('\\');
}
pattern.push(c);
}
pattern.push('*');
pattern
}
pub(crate) fn rule_for<'a>(rules: &'a [JsResponseRule], url: &str) -> Option<&'a JsResponseRule> {
rules.iter().find(|rule| url.contains(&rule.url_contains))
}
/// What to tell the browser about a request it holds: the first matching rule's response, or
/// to send the request on. Every held request gets one of the two.
pub(crate) fn answer(held: &Value, rules: &[JsResponseRule]) -> (&'static str, Value) {
let request_id = held.get("requestId").and_then(Value::as_str).unwrap_or_default();
let url = held.pointer("/request/url").and_then(Value::as_str).unwrap_or_default();
let Some(rule) = rule_for(rules, url) else {
return ("Fetch.continueRequest", json!({ "requestId": request_id }));
};
let header = |name: &str, value: &str| json!({ "name": name, "value": value });
// A page on another origin only reads a response that names its origin. The server would
// say so; the response given in its place has to.
let mut cross_origin = Vec::new();
if let Some(origin) = request_header(held, "Origin") {
cross_origin.push(header("Access-Control-Allow-Origin", origin));
cross_origin.push(header("Access-Control-Allow-Credentials", "true"));
}
let method = held.pointer("/request/method").and_then(Value::as_str).unwrap_or_default();
// The browser's question before such a request: allowed here, the server may not exist.
if method == "OPTIONS"
&& let Some(asked) = request_header(held, "Access-Control-Request-Method")
{
cross_origin.push(header("Access-Control-Allow-Methods", asked));
if let Some(asked) = request_header(held, "Access-Control-Request-Headers") {
cross_origin.push(header("Access-Control-Allow-Headers", asked));
}
let allowed = json!({
"requestId": request_id,
"responseCode": 204,
"responsePhrase": phrase(204),
"responseHeaders": cross_origin,
});
return ("Fetch.fulfillRequest", allowed);
}
let mut headers = vec![header("Content-Type", &rule.content_type)];
headers.extend(cross_origin);
let replaced = json!({
"requestId": request_id,
"responseCode": rule.status,
"responsePhrase": phrase(rule.status),
"responseHeaders": headers,
"body": base64::engine::general_purpose::STANDARD.encode(rule.body.as_bytes()),
});
("Fetch.fulfillRequest", replaced)
}
/// A header of the held request; the browser reports names as the page wrote them.
fn request_header<'a>(held: &'a Value, name: &str) -> Option<&'a str> {
held.pointer("/request/headers")?.as_object()?.iter().find(|(key, _)| key.eq_ignore_ascii_case(name))?.1.as_str()
}
/// The browser refuses a response without a phrase when it has none of its own for the status.
fn phrase(status: u16) -> &'static str {
StatusCode::from_u16(status).ok().and_then(|status| status.canonical_reason()).unwrap_or("Unknown")
}
fn interception(rules: &[JsResponseRule]) -> Value {
let patterns: Vec<Value> = rules
.iter()
.map(|rule| json!({ "urlPattern": url_pattern(&rule.url_contains), "requestStage": "Request" }))
.collect();
json!({ "patterns": patterns })
}
/// Applies `rules` to the page behind js-debug's CDP proxy at `ws_url` until their sender is
/// dropped (the session is gone) or the proxy closes the connection. The browser holds
/// requests only while there are rules. `ready` hears whether the proxy reports held
/// requests at all; nothing is held before it has agreed to.
pub(crate) async fn serve(
ws_url: String,
mut rules: watch::Receiver<Vec<JsResponseRule>>,
ready: oneshot::Sender<Result<(), String>>,
) {
let socket = match tokio_tungstenite::connect_async(ws_url.as_str()).await {
Ok((socket, _)) => socket,
Err(e) => {
let _ = ready.send(Err(e.to_string()));
return;
}
};
let (mut write, mut read) = socket.split();
let mut last_id = 0u64;
let mut call = |method: &str, params: Value| {
last_id += 1;
(last_id, Message::text(json!({ "id": last_id, "method": method, "params": params }).to_string()))
};
let (subscription, subscribe) = call("JsDebug.subscribe", json!({ "events": ["Fetch.requestPaused"] }));
let subscribed = tokio::time::timeout(REQUEST_TIMEOUT, async {
write.send(subscribe).await.map_err(|e| e.to_string())?;
loop {
let reply = read.next().await.ok_or("the connection closed")?.map_err(|e| e.to_string())?;
let Some(reply) = reply.to_text().ok().and_then(|text| serde_json::from_str::<Value>(text).ok()) else {
continue;
};
if reply.get("id").and_then(Value::as_u64) != Some(subscription) {
continue;
}
break match reply.get("error") {
Some(error) => Err(error.get("message").and_then(Value::as_str).unwrap_or("refused").to_owned()),
None => Ok(()),
};
}
})
.await
.unwrap_or_else(|_| Err("no answer".to_owned()));
if let Err(why) = subscribed {
let _ = ready.send(Err(why));
let _ = write.close().await;
return;
}
let _ = ready.send(Ok(()));
let mut current = rules.borrow_and_update().clone();
let mut holding = !current.is_empty();
if holding && write.send(call("Fetch.enable", interception(&current)).1).await.is_err() {
return;
}
// The request each sent replacement is for, by command id, until the browser has taken it.
let mut replacing: HashMap<u64, String> = HashMap::new();
loop {
tokio::select! {
changed = rules.changed() => {
if changed.is_err() {
break;
}
current = rules.borrow_and_update().clone();
let (_, command) = match (current.is_empty(), holding) {
(true, false) => continue,
(true, true) => call("Fetch.disable", json!({})),
(false, _) => call("Fetch.enable", interception(&current)),
};
holding = !current.is_empty();
if write.send(command).await.is_err() {
return;
}
}
message = read.next() => {
// The proxy closed (the page or the session ended): nothing is held any more.
let Some(Ok(message)) = message else { return };
let Ok(text) = message.to_text() else { continue };
let Ok(message) = serde_json::from_str::<Value>(text) else { continue };
if let Some(id) = message.get("id").and_then(Value::as_u64) {
// The browser did not take the replacement: let the request through, or
// it stays held and the page waits for it.
if let Some(request_id) = replacing.remove(&id)
&& message.get("error").is_some()
{
let (_, go_on) = call("Fetch.continueRequest", json!({ "requestId": request_id }));
if write.send(go_on).await.is_err() {
return;
}
}
continue;
}
if message.get("method").and_then(Value::as_str) != Some("Fetch.requestPaused") {
continue;
}
let Some(held) = message.get("params") else { continue };
let Some(request_id) = held.get("requestId").and_then(Value::as_str) else { continue };
let (method, params) = answer(held, &current);
let (id, command) = call(method, params);
if method == "Fetch.fulfillRequest" {
replacing.insert(id, request_id.to_owned());
}
if write.send(command).await.is_err() {
return;
}
}
}
}
if holding {
let _ = write.send(call("Fetch.disable", json!({})).1).await;
}
let _ = write.close().await;
}
impl DebugManager {
/// Makes `rules` the page's response rules; none switches the replacing off. The first
/// rules of a session open the connection to js-debug's CDP proxy, later ones go over it.
/// An error means the rules are not applied.
pub async fn js_set_response_overrides(&self, s: DebugSessionId, rules: Vec<JsResponseRule>) -> IdeResult<()> {
let session = self.session(s)?;
if !js_debug::is_page(&session) {
return Err(IdeError::unavailable("this debug session is not a page in a browser"));
}
// Held to the end: two callers at once would each open a connection.
let mut applied = session.js_overrides.lock().await;
if applied.as_ref().is_some_and(|sender| sender.send(rules.clone()).is_ok()) {
return Ok(());
}
// No connection yet, or the proxy closed it.
applied.take();
if rules.is_empty() {
return Ok(());
}
let refused =
|why: String| IdeError::unavailable(format!("the JavaScript debugger has no browser connection: {why}"));
if !js_debug::launched(&session).await {
return Err(refused("the page's debug session did not finish starting".into()));
}
let proxy = session
.conn
.request_timeout("requestCDPProxy", json!({}), REQUEST_TIMEOUT)
.await
.map_err(|e| refused(e.to_string()))?;
let (Some(host), Some(port)) =
(proxy.get("host").and_then(Value::as_str), proxy.get("port").and_then(Value::as_u64))
else {
return Err(refused("no address".into()));
};
let path = proxy.get("path").and_then(Value::as_str).unwrap_or_default();
let (sender, receiver) = watch::channel(rules);
let (ready, is_ready) = oneshot::channel();
tokio::spawn(serve(format!("ws://{host}:{port}{path}"), receiver, ready));
match is_ready.await {
Ok(Ok(())) => {
*applied = Some(sender);
Ok(())
}
Ok(Err(why)) => Err(refused(why)),
Err(_) => Err(refused("no answer".into())),
}
}
}
#[cfg(test)]
pub(crate) mod tests {
use super::*;
use futures::{SinkExt, StreamExt};
use serde_json::json;
use tokio::sync::mpsc;
use tokio_tungstenite::tungstenite::Message;
pub(crate) fn rule(url_contains: &str, status: u16, body: &str) -> JsResponseRule {
JsResponseRule {
url_contains: url_contains.into(),
status,
content_type: "application/json".into(),
body: body.into(),
}
}
#[test]
fn a_part_of_a_url_becomes_a_pattern_that_matches_it_anywhere() {
assert_eq!(url_pattern("api/items"), "*api/items*");
// The pattern's own wildcards and escape character are taken literally.
assert_eq!(url_pattern(r"a*b?c\d"), r"*a\*b\?c\\d*");
}
#[test]
fn the_first_rule_whose_text_is_in_the_url_answers() {
let rules = [rule("api/items", 201, "{\"a\":\"é\"}"), rule("api", 500, "later")];
assert_eq!(rule_for(&rules, "http://h/api/items?x=1").map(|r| r.status), Some(201));
assert_eq!(rule_for(&rules, "http://h/api/users").map(|r| r.status), Some(500));
assert!(rule_for(&rules, "http://h/logo.png").is_none());
let (command, params) = answer(&held("7", "http://h/api/items")["params"], &rules);
assert_eq!(command, "Fetch.fulfillRequest");
assert_eq!(
params,
json!({
"requestId": "7",
"responseCode": 201,
"responsePhrase": "Created",
"responseHeaders": [{ "name": "Content-Type", "value": "application/json" }],
// base64 of the UTF-8 text `{"a":"é"}`
"body": "eyJhIjoiw6kifQ==",
})
);
// A request the browser held that no rule is for goes on to the network.
assert_eq!(
answer(&held("8", "http://h/logo.png")["params"], &rules),
("Fetch.continueRequest", json!({ "requestId": "8" }))
);
}
#[test]
fn a_status_the_browser_has_no_phrase_for_is_given_one() {
// The browser refuses a response whose status it cannot name.
let (_, params) = answer(&held("1", "http://h/api")["params"], &[rule("api", 419, "")]);
assert_eq!((&params["responseCode"], &params["responsePhrase"]), (&json!(419), &json!("Unknown")));
}
fn header<'a>(params: &'a Value, name: &str) -> Option<&'a str> {
params["responseHeaders"].as_array()?.iter().find(|h| h["name"] == name)?["value"].as_str()
}
#[test]
fn a_replaced_response_passes_the_pages_cross_origin_check() {
let rules = [rule("api/items", 200, "[]")];
let from_page = |method: &str, headers: Value| json!({ "requestId": "3", "request": { "url": "http://localhost:8080/api/items", "method": method, "headers": headers } });
// A page on another origin: the response names that origin, as the real server would.
let (_, params) = answer(&from_page("GET", json!({ "origin": "http://localhost:5173" })), &rules);
assert_eq!(header(&params, "Access-Control-Allow-Origin"), Some("http://localhost:5173"));
assert_eq!(header(&params, "Access-Control-Allow-Credentials"), Some("true"));
assert_eq!(params["body"], "W10=");
// The browser's question before such a request is answered too: the server may not exist.
let preflight = from_page(
"OPTIONS",
json!({
"Origin": "http://localhost:5173",
"Access-Control-Request-Method": "PUT",
"Access-Control-Request-Headers": "content-type,x-token",
}),
);
let (command, params) = answer(&preflight, &rules);
assert_eq!((command, &params["responseCode"]), ("Fetch.fulfillRequest", &json!(204)));
assert_eq!(header(&params, "Access-Control-Allow-Origin"), Some("http://localhost:5173"));
assert_eq!(header(&params, "Access-Control-Allow-Methods"), Some("PUT"));
assert_eq!(header(&params, "Access-Control-Allow-Headers"), Some("content-type,x-token"));
assert_eq!(params.get("body"), None);
// Same origin: nothing but the rule's own header.
let (_, params) = answer(&from_page("GET", json!({})), &rules);
assert_eq!(params["responseHeaders"], json!([{ "name": "Content-Type", "value": "application/json" }]));
}
/// A stand-in for js-debug's CDP proxy: what it receives, and a way to send it events.
pub(crate) async fn proxy() -> (String, mpsc::UnboundedReceiver<Value>, mpsc::UnboundedSender<Value>) {
proxy_refusing(|_| false).await
}
/// A proxy that answers the commands `refused` picks with an error, like the real one does
/// for what it or the browser does not accept.
pub(crate) async fn proxy_refusing(
refused: fn(&Value) -> bool,
) -> (String, mpsc::UnboundedReceiver<Value>, mpsc::UnboundedSender<Value>) {
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let url = format!("ws://127.0.0.1:{}/session", listener.local_addr().unwrap().port());
let (received_tx, received) = mpsc::unbounded_channel();
let (events, mut events_rx) = mpsc::unbounded_channel::<Value>();
tokio::spawn(async move {
let (stream, _) = listener.accept().await.unwrap();
let (mut write, mut read) = tokio_tungstenite::accept_async(stream).await.unwrap().split();
loop {
tokio::select! {
message = read.next() => {
let Some(Ok(message)) = message else { break };
let Ok(text) = message.to_text() else { continue };
let Ok(request) = serde_json::from_str::<Value>(text) else { continue };
let reply = if refused(&request) {
json!({ "id": request["id"], "error": { "code": -32602, "message": "refused" } })
} else {
json!({ "id": request["id"], "result": {} })
};
let _ = write.send(Message::text(reply.to_string())).await;
let _ = received_tx.send(request);
}
Some(event) = events_rx.recv() => {
let _ = write.send(Message::text(event.to_string())).await;
}
}
}
});
(url, received, events)
}
pub(crate) async fn next(received: &mut mpsc::UnboundedReceiver<Value>) -> (String, Value) {
let request = tokio::time::timeout(std::time::Duration::from_secs(5), received.recv())
.await
.expect("the proxy got a request in time")
.expect("the connection is open");
(request["method"].as_str().unwrap().to_owned(), request["params"].clone())
}
/// The browser's event for a request it holds.
fn held(request_id: &str, url: &str) -> Value {
json!({ "method": "Fetch.requestPaused", "params": { "requestId": request_id, "request": { "url": url } } })
}
type Serving = (tokio::task::JoinHandle<()>, oneshot::Receiver<Result<(), String>>);
fn serving(url: String, rules: watch::Receiver<Vec<JsResponseRule>>) -> Serving {
let (ready, is_ready) = oneshot::channel();
(tokio::spawn(serve(url, rules, ready)), is_ready)
}
async fn ended(task: tokio::task::JoinHandle<()>) {
tokio::time::timeout(std::time::Duration::from_secs(5), task).await.unwrap().unwrap();
}
#[tokio::test]
async fn held_requests_are_answered_and_interception_ends_before_the_connection() {
let (url, mut received, events) = proxy().await;
let (rules, watched) = tokio::sync::watch::channel(vec![rule("api/items", 200, "[]")]);
let (serving, ready) = serving(url, watched);
assert_eq!(ready.await.unwrap(), Ok(()));
assert_eq!(
next(&mut received).await,
("JsDebug.subscribe".into(), json!({ "events": ["Fetch.requestPaused"] }))
);
assert_eq!(
next(&mut received).await,
(
"Fetch.enable".into(),
json!({ "patterns": [{ "urlPattern": "*api/items*", "requestStage": "Request" }] })
)
);
events.send(held("1", "http://h/api/items")).unwrap();
let (command, params) = next(&mut received).await;
assert_eq!(
(command.as_str(), &params["requestId"], &params["responseCode"]),
("Fetch.fulfillRequest", &json!("1"), &json!(200))
);
events.send(held("2", "http://h/other")).unwrap();
assert_eq!(next(&mut received).await, ("Fetch.continueRequest".into(), json!({ "requestId": "2" })));
// New rules replace the browser's patterns.
rules.send(vec![rule("api/users", 404, "{}")]).unwrap();
assert_eq!(
next(&mut received).await,
(
"Fetch.enable".into(),
json!({ "patterns": [{ "urlPattern": "*api/users*", "requestStage": "Request" }] })
)
);
// No rules left: the browser stops holding requests. The connection stays for the
// rules that come next, and goes with the session.
rules.send(Vec::new()).unwrap();
assert_eq!(next(&mut received).await.0, "Fetch.disable");
rules.send(vec![rule("api/items", 200, "[]")]).unwrap();
assert_eq!(next(&mut received).await.0, "Fetch.enable");
rules.send(Vec::new()).unwrap();
assert_eq!(next(&mut received).await.0, "Fetch.disable");
drop(rules);
ended(serving).await;
// Already off: not switched off a second time.
assert!(received.try_recv().is_err());
}
#[tokio::test]
async fn a_session_that_goes_away_switches_interception_off() {
let (url, mut received, _events) = proxy().await;
let (rules, watched) = tokio::sync::watch::channel(vec![rule("api", 200, "[]")]);
let (serving, _ready) = serving(url, watched);
assert_eq!(next(&mut received).await.0, "JsDebug.subscribe");
assert_eq!(next(&mut received).await.0, "Fetch.enable");
drop(rules);
assert_eq!(next(&mut received).await.0, "Fetch.disable");
ended(serving).await;
}
#[tokio::test]
async fn a_response_the_browser_refuses_lets_the_request_through() {
let (url, mut received, events) = proxy_refusing(|request| request["method"] == "Fetch.fulfillRequest").await;
let (_rules, watched) = tokio::sync::watch::channel(vec![rule("api", 200, "[]")]);
let (_serving, _ready) = serving(url, watched);
assert_eq!(next(&mut received).await.0, "JsDebug.subscribe");
assert_eq!(next(&mut received).await.0, "Fetch.enable");
events.send(held("9", "http://h/api")).unwrap();
assert_eq!(next(&mut received).await.0, "Fetch.fulfillRequest");
// Unanswered, the request would hang the page.
assert_eq!(next(&mut received).await, ("Fetch.continueRequest".into(), json!({ "requestId": "9" })));
}
#[tokio::test]
async fn a_proxy_that_does_not_report_held_requests_is_not_asked_to_hold_any() {
let (url, mut received, _events) = proxy_refusing(|request| request["method"] == "JsDebug.subscribe").await;
let (_rules, watched) = tokio::sync::watch::channel(vec![rule("api", 200, "[]")]);
let (serving, ready) = serving(url, watched);
assert_eq!(next(&mut received).await.0, "JsDebug.subscribe");
assert_eq!(ready.await.unwrap(), Err("refused".to_owned()));
ended(serving).await;
assert!(received.try_recv().is_err());
}
#[tokio::test]
async fn no_connection_to_the_proxy_is_reported() {
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let url = format!("ws://127.0.0.1:{}/session", listener.local_addr().unwrap().port());
drop(listener);
let (_rules, watched) = tokio::sync::watch::channel(vec![rule("api", 200, "[]")]);
let (serving, ready) = serving(url, watched);
assert!(ready.await.unwrap().is_err());
ended(serving).await;
}
}
+1 -1
View File
@@ -27,7 +27,7 @@ pub(crate) fn is_page(session: &Session) -> bool {
/// Waits until the adapter answered the `launch` of `session`. js-debug sets a page's session
/// up between `configurationDone` and that answer; a request of its own that arrives then is
/// answered and has no effect.
async fn launched(session: &Session) -> bool {
pub(crate) async fn launched(session: &Session) -> bool {
let mut launched = session.launched.subscribe();
let answered = tokio::time::timeout(REQUEST_TIMEOUT, launched.wait_for(|answered| *answered)).await;
matches!(answered, Ok(Ok(_)))
+2
View File
@@ -13,6 +13,7 @@ pub mod attach;
mod cargo;
pub mod connection;
pub mod jdwp;
mod js_cdp;
mod js_debug;
mod jvm_memory;
pub mod kotlin;
@@ -24,6 +25,7 @@ use connection::{Connection, DapError};
use futures::future::join_all;
use ide_core::{DebugSessionId, IdeError, IdeResult, SharedSink};
use ide_language::LanguageRegistry;
pub use js_cdp::JsResponseRule;
pub use js_debug::JsResponseBody;
pub use jvm_memory::*;
use parking_lot::Mutex;
+4
View File
@@ -94,6 +94,9 @@ pub(crate) struct Session {
/// The `type` of the launch or attach request (js-debug's `pwa-node`, `pwa-chrome`); a child
/// session's comes from the configuration the adapter started it with.
pub launch_type: std::sync::OnceLock<String>,
/// The response rules of a page once a connection applies them (`js_cdp::serve`).
/// Dropped with the session, which switches the browser's interception off.
pub js_overrides: tokio::sync::Mutex<Option<tokio::sync::watch::Sender<Vec<crate::JsResponseRule>>>>,
/// The file js-debug records the page's CPU profile into, while one is being recorded.
pub js_profile: parking_lot::Mutex<Option<std::path::PathBuf>>,
pub jvm_inspector: parking_lot::Mutex<Option<Arc<dyn ide_jvm_inspect::JvmInspector>>>,
@@ -257,6 +260,7 @@ impl Session {
progress: Mutex::new(HashMap::new()),
jdwp_link: parking_lot::Mutex::new(None),
launch_type: std::sync::OnceLock::new(),
js_overrides: tokio::sync::Mutex::new(None),
js_profile: parking_lot::Mutex::new(None),
jvm_inspector: parking_lot::Mutex::new(None),
inspect_lock: tokio::sync::Mutex::default(),
+90
View File
@@ -1104,6 +1104,96 @@ async fn a_page_whose_requests_the_adapter_does_not_report_says_so() {
h.wait_event(|e| matches!(e, DebugEvent::JsNetworkUnavailable)).await;
}
/// Where the fake adapter says its CDP proxy listens (`requestCDPProxy`).
static CDP_PROXY_PORT: std::sync::atomic::AtomicU16 = std::sync::atomic::AtomicU16::new(0);
fn proxy_adapter(msg: &Value) -> Option<CustomReply> {
let port = CDP_PROXY_PORT.load(std::sync::atomic::Ordering::Relaxed);
(msg["command"] == "requestCDPProxy")
.then(|| (json!({ "host": "127.0.0.1", "port": port, "path": "/session" }), Vec::new()))
}
#[tokio::test]
async fn response_overrides_reach_the_page_through_the_adapters_proxy() {
use crate::js_cdp::tests::{next, proxy, rule};
let (url, mut received, _events) = proxy().await;
let port: u16 = url.trim_start_matches("ws://127.0.0.1:").trim_end_matches("/session").parse().unwrap();
CDP_PROXY_PORT.store(port, std::sync::atomic::Ordering::Relaxed);
let h = harness(Script {
start_debugging: true,
custom: Some(proxy_adapter),
child_launch_delay: Duration::from_millis(150),
..Script::default()
});
let browser = h.start(js_config("pwa-chrome")).await.unwrap();
let page = child_of(&h, browser).await;
// Rules that are there as the page starts wait until its session takes requests.
tokio::time::sleep(Duration::from_millis(50)).await;
h.manager.js_set_response_overrides(page, vec![rule("api/items", 200, "[]")]).await.unwrap();
let dropped = h.log.lock().iter().filter(|m| m["type"] == "dropped").count();
assert_eq!(dropped, 0, "the proxy was asked for before the page took requests");
assert_eq!(next(&mut received).await.0, "JsDebug.subscribe");
assert_eq!(
next(&mut received).await,
("Fetch.enable".into(), json!({ "patterns": [{ "urlPattern": "*api/items*", "requestStage": "Request" }] }))
);
// Changed rules go over the connection that is open: the proxy is asked for once.
h.manager.js_set_response_overrides(page, vec![rule("api/users", 200, "[]")]).await.unwrap();
assert_eq!(next(&mut received).await.1["patterns"][0]["urlPattern"], "*api/users*");
assert_eq!(requests(&h, "requestCDPProxy").len(), 1);
h.manager.js_set_response_overrides(page, Vec::new()).await.unwrap();
assert_eq!(next(&mut received).await.0, "Fetch.disable");
// A rule switched back on.
h.manager.js_set_response_overrides(page, vec![rule("api/items", 200, "[]")]).await.unwrap();
assert_eq!(next(&mut received).await.0, "Fetch.enable");
assert_eq!(requests(&h, "requestCDPProxy").len(), 1);
let not_a_page = h.manager.js_set_response_overrides(browser, vec![rule("api", 200, "")]).await.unwrap_err();
assert_eq!(not_a_page.kind, ide_core::error::ErrorKind::Unavailable);
}
#[tokio::test]
async fn response_overrides_are_unavailable_without_the_adapters_proxy() {
use crate::js_cdp::tests::rule;
let h = harness(Script { start_debugging: true, ..Script::default() });
let browser = h.start(js_config("pwa-chrome")).await.unwrap();
let page = child_of(&h, browser).await;
let refused = h.manager.js_set_response_overrides(page, vec![rule("api", 200, "")]).await.unwrap_err();
assert_eq!(refused.kind, ide_core::error::ErrorKind::Unavailable);
// Nothing to switch off is not an error.
h.manager.js_set_response_overrides(page, Vec::new()).await.unwrap();
}
/// A port nothing listens on, which the fake adapter gives as its CDP proxy.
static DEAD_PROXY_PORT: std::sync::atomic::AtomicU16 = std::sync::atomic::AtomicU16::new(0);
fn dead_proxy_adapter(msg: &Value) -> Option<CustomReply> {
let port = DEAD_PROXY_PORT.load(std::sync::atomic::Ordering::Relaxed);
(msg["command"] == "requestCDPProxy")
.then(|| (json!({ "host": "127.0.0.1", "port": port, "path": "/session" }), Vec::new()))
}
#[tokio::test]
async fn response_overrides_that_cannot_reach_the_browser_are_an_error() {
use crate::js_cdp::tests::rule;
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
DEAD_PROXY_PORT.store(listener.local_addr().unwrap().port(), std::sync::atomic::Ordering::Relaxed);
drop(listener);
let h = harness(Script { start_debugging: true, custom: Some(dead_proxy_adapter), ..Script::default() });
let browser = h.start(js_config("pwa-chrome")).await.unwrap();
let page = child_of(&h, browser).await;
let unreachable = h.manager.js_set_response_overrides(page, vec![rule("api", 200, "")]).await.unwrap_err();
assert_eq!(unreachable.kind, ide_core::error::ErrorKind::Unavailable);
// The next rules try again instead of going to a connection that never was.
let again = h.manager.js_set_response_overrides(page, vec![rule("api", 200, "")]).await.unwrap_err();
assert_eq!(again.kind, ide_core::error::ErrorKind::Unavailable);
assert_eq!(requests(&h, "requestCDPProxy").len(), 2);
}
/// The file the fake adapter says it records a CPU profile into (`profileStarted`).
static PROFILE_FILE: parking_lot::Mutex<String> = parking_lot::Mutex::new(String::new());
+12
View File
@@ -382,6 +382,15 @@ pub async fn debug_js_custom_breakpoints(
host.debugger.js_set_custom_breakpoints(session, ids, xhr).await
}
pub async fn debug_js_response_overrides(
host: &Host,
_window: &str,
session: DebugSessionId,
rules: Vec<ide_dap::JsResponseRule>,
) -> IdeResult<()> {
host.debugger.js_set_response_overrides(session, rules).await
}
pub async fn debug_js_response_body(
host: &Host,
_window: &str,
@@ -619,6 +628,9 @@ pub(crate) fn register(d: &mut Dispatcher) {
debug_restart_frame(&c.host, &c.window, c.arg("session")?, c.arg("frameId")?).await
});
d.add("debug_capabilities", |c| async move { debug_capabilities(&c.host, &c.window, c.arg("session")?) });
d.add("debug_js_response_overrides", |c| async move {
debug_js_response_overrides(&c.host, &c.window, c.arg("session")?, c.arg("rules")?).await
});
d.add("debug_js_response_body", |c| async move {
debug_js_response_body(&c.host, &c.window, c.arg("session")?, c.arg("requestId")?).await
});
+12
View File
@@ -244,6 +244,18 @@ pub async fn debug_restart_frame(state: State<'_, AppState>, session: DebugSessi
ide_host::ops::debug::debug_restart_frame(&state.host, "", session, frame_id).await
}
/// The responses a debugged page gets in place of the server's, by a part of the URL; none
/// switches the replacing off.
#[tauri::command]
#[specta::specta]
pub async fn debug_js_response_overrides(
state: State<'_, AppState>,
session: DebugSessionId,
rules: Vec<ide_dap::JsResponseRule>,
) -> IdeResult<()> {
ide_host::ops::debug::debug_js_response_overrides(&state.host, "", session, rules).await
}
/// The body of a response a debugged page received.
#[tauri::command]
#[specta::specta]
+1
View File
@@ -533,6 +533,7 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
debug::debug_capabilities,
debug::debug_js_custom_breakpoints,
debug::debug_js_response_body,
debug::debug_js_response_overrides,
debug::debug_js_start_profile,
debug::debug_js_stop_profile,
debug::debug_set_function_breakpoints,
+13
View File
@@ -1259,6 +1259,11 @@ export const commands = {
debugJsCustomBreakpoints: (session: DebugSessionId, ids: string[], xhr: string[]) => typedError<null, IdeError>(__TAURI_INVOKE("debug_js_custom_breakpoints", { session, ids, xhr })),
/** The body of a response a debugged page received. */
debugJsResponseBody: (session: DebugSessionId, requestId: string) => typedError<JsResponseBody, IdeError>(__TAURI_INVOKE("debug_js_response_body", { session, requestId })),
/**
* The responses a debugged page gets in place of the server's, by a part of the URL; none
* switches the replacing off.
*/
debugJsResponseOverrides: (session: DebugSessionId, rules: JsResponseRule[]) => typedError<null, IdeError>(__TAURI_INVOKE("debug_js_response_overrides", { session, rules })),
/** Starts recording a debugged page's CPU profile. */
debugJsStartProfile: (session: DebugSessionId) => typedError<null, IdeError>(__TAURI_INVOKE("debug_js_start_profile", { session })),
/** Ends the recording: a directory holding the profile as `page.cpuprofile`. */
@@ -6571,6 +6576,14 @@ export type JsResponseBody = {
truncated: boolean,
};
/** A response given in place of the server's to every request whose URL contains `url_contains`. */
export type JsResponseRule = {
urlContains: string,
status: number,
contentType: string,
body: string,
};
/** The backend that reads a debugged JVM's objects (instances, fields, referrers). */
export type JvmBackendState = { kind: "ready" } |
/** Turned off for the rest of the session: the debug adapter lacks what it needs. */
@@ -19,6 +19,7 @@ vi.mock("@/platform/ipc", async (orig) => {
evaluated.push(args);
return Promise.resolve({ status: "ok", data: { value: "", variablesReference: 0 } });
},
debugJsResponseOverrides: () => Promise.resolve({ status: "ok", data: null }),
},
};
});
@@ -26,6 +27,7 @@ vi.mock("@/platform/ipc", async (orig) => {
const { applyNetworkEvents, useJsNetwork } = await import("../js/network");
const { NetworkView } = await import("../js/NetworkView");
const { useJsBreakpoints } = await import("../js/eventBreakpoints");
const { loadResponseOverrides, saveOverride } = await import("../js/responseOverrides");
const { setRefused } = await import("../js/refusals");
const { handleDebugEvent, useDebug } = await import("../state");
@@ -66,6 +68,8 @@ function load() {
}
beforeEach(() => {
localStorage.clear();
loadResponseOverrides(null);
useJsNetwork.setState({ rows: {} });
asked.length = 0;
evaluated.length = 0;
@@ -197,4 +201,58 @@ describe("Network view", () => {
).toBeInTheDocument();
setRefused(7, "network", null);
});
it("marks the requests whose response a rule replaces", () => {
loadResponseOverrides("/p");
saveOverride({ pattern: "/api/items", status: 200, contentType: "application/json", body: "[]", enabled: true });
load();
render(<NetworkView session={7} />);
const rows = screen.getAllByRole("row").slice(1);
expect(rows[0]).toHaveTextContent("overridden");
expect(rows[1]).not.toHaveTextContent("overridden");
expect(screen.getByRole("button", { name: "Overrides (1)" })).toBeInTheDocument();
});
it("does not mark a request as overridden when the page's debugger refused the rules, and says why", () => {
loadResponseOverrides("/p");
saveOverride({ pattern: "/api/items", status: 200, contentType: "application/json", body: "[]", enabled: true });
load();
setRefused(7, "overrides", "no browser connection");
render(<NetworkView session={7} />);
expect(screen.getAllByRole("row")[1]).not.toHaveTextContent("overridden");
expect(screen.getByRole("alert")).toHaveTextContent(
"Responses are not replaced in this page: no browser connection",
);
setRefused(7, "overrides", null);
});
it("opens the override editor on a request, filled with its response", async () => {
loadResponseOverrides("/p");
load();
render(<NetworkView session={7} />);
fireEvent.click(screen.getAllByRole("row")[1]!);
fireEvent.click(screen.getByRole("button", { name: "Override Response…" }));
await waitFor(() => expect(screen.getByLabelText("Part of the URL")).toHaveValue("/api/items"));
expect(screen.getByLabelText("Status")).toHaveValue("200");
expect(screen.getByLabelText("Content type")).toHaveValue("application/json");
expect(screen.getByLabelText("Response body")).toHaveValue('{"items":[]}');
});
it("starts from an empty body when the request's own can't be read", async () => {
loadResponseOverrides("/p");
load();
answer = { status: "error", error: { kind: "unavailable", message: "gone" } };
render(<NetworkView session={7} />);
fireEvent.click(screen.getAllByRole("row")[1]!);
fireEvent.click(screen.getByRole("button", { name: "Override Response…" }));
await waitFor(() => expect(screen.getByLabelText("Part of the URL")).toHaveValue("/api/items"));
expect(screen.getByLabelText("Response body")).toHaveValue("");
});
it("opens the list of overrides from the toolbar", () => {
loadResponseOverrides("/p");
render(<NetworkView session={7} />);
fireEvent.click(screen.getByRole("button", { name: "Overrides" }));
expect(screen.getByText("No overrides yet")).toBeInTheDocument();
});
});
@@ -0,0 +1,94 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import { fireEvent, render, screen, within } from "@testing-library/react";
vi.mock("@/platform/ipc", async (orig) => {
const real = await orig<typeof import("@/platform/ipc")>();
return {
...real,
commands: { ...real.commands, debugJsResponseOverrides: () => Promise.resolve({ status: "ok", data: null }) },
};
});
const { loadResponseOverrides, saveOverride, useResponseOverrides } = await import("../js/responseOverrides");
const { OverridesDialog } = await import("../js/OverridesDialog");
const draft = { pattern: "/api/items", status: 200, contentType: "application/json", body: '{"items":[]}' };
const rules = () => useResponseOverrides.getState().rules;
const field = (label: string) => screen.getByLabelText(label) as HTMLInputElement | HTMLTextAreaElement;
beforeEach(() => {
localStorage.clear();
loadResponseOverrides("/p");
});
describe("Response Overrides dialog", () => {
it("opens on a request with its address, status, type and body filled in", () => {
render(<OverridesDialog open onClose={() => {}} draft={draft} />);
expect(field("Part of the URL").value).toBe("/api/items");
expect(field("Status").value).toBe("200");
expect(field("Content type").value).toBe("application/json");
expect(field("Response body").value).toBe('{"items":[]}');
expect(rules()).toEqual([]);
});
it("saves the edited response as a rule that is on", () => {
render(<OverridesDialog open onClose={() => {}} draft={draft} />);
fireEvent.change(field("Response body"), { target: { value: '{"items":["from the IDE"]}' } });
fireEvent.change(field("Status"), { target: { value: "201" } });
fireEvent.click(screen.getByRole("button", { name: "Save" }));
expect(rules()).toMatchObject([
{
pattern: "/api/items",
status: 201,
contentType: "application/json",
body: '{"items":["from the IDE"]}',
enabled: true,
},
]);
// Saved once more, it is the same rule.
fireEvent.change(field("Response body"), { target: { value: "[]" } });
fireEvent.click(screen.getByRole("button", { name: "Save" }));
expect(rules()).toHaveLength(1);
expect(rules()[0]!.body).toBe("[]");
});
it("edits the rule a request already has instead of adding a second one", () => {
const id = saveOverride({ ...draft, body: "old", enabled: true });
render(<OverridesDialog open onClose={() => {}} draft={draft} />);
expect(field("Response body").value).toBe("old");
fireEvent.change(field("Response body"), { target: { value: "new" } });
fireEvent.click(screen.getByRole("button", { name: "Save" }));
expect(rules()).toMatchObject([{ id, body: "new" }]);
});
it("warns that a very short text replaces many responses, and saves nothing without one", () => {
render(<OverridesDialog open onClose={() => {}} draft={{ ...draft, pattern: "/" }} />);
expect(screen.getByText("This also replaces every other response whose URL contains it")).toBeInTheDocument();
fireEvent.change(field("Part of the URL"), { target: { value: " " } });
expect(screen.getByRole("button", { name: "Save" })).toBeDisabled();
});
it("lists the rules, switches them on and off, and removes the selected one", () => {
saveOverride({ ...draft, enabled: true });
saveOverride({ ...draft, pattern: "/api/users", enabled: true });
render(<OverridesDialog open onClose={() => {}} />);
const list = screen.getByRole("list", { name: "Overrides" });
expect(within(list).getAllByRole("listitem")).toHaveLength(2);
fireEvent.click(within(list).getByLabelText("/api/users"));
expect(rules().map((r) => r.enabled)).toEqual([true, false]);
fireEvent.click(within(list).getByText("/api/items"));
expect(field("Part of the URL").value).toBe("/api/items");
fireEvent.click(screen.getByRole("button", { name: "Remove" }));
expect(rules().map((r) => r.pattern)).toEqual(["/api/users"]);
});
it("starts an empty rule from the list", () => {
render(<OverridesDialog open onClose={() => {}} />);
expect(screen.getByText("No overrides yet")).toBeInTheDocument();
fireEvent.click(screen.getByRole("button", { name: "Add Override" }));
fireEvent.change(field("Part of the URL"), { target: { value: "/api/new" } });
fireEvent.click(screen.getByRole("button", { name: "Save" }));
expect(rules()).toMatchObject([{ pattern: "/api/new", status: 200, contentType: "application/json", body: "" }]);
});
});
@@ -0,0 +1,191 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import type { JsResponseRule } from "@/platform/ipc";
const sent: Array<[number, JsResponseRule[]]> = [];
let refuse: number | null = null;
vi.mock("@/platform/ipc", async (orig) => {
const real = await orig<typeof import("@/platform/ipc")>();
return {
...real,
commands: {
...real.commands,
debugJsResponseOverrides: (session: number, rules: JsResponseRule[]) => {
sent.push([session, rules]);
return Promise.resolve(
session === refuse
? { status: "error", error: { kind: "unavailable", message: "refused" } }
: { status: "ok", data: null },
);
},
},
};
});
const { useDebug } = await import("../state");
const {
activeRules,
answeredBy,
loadResponseOverrides,
overriddenBy,
removeOverride,
saveOverride,
syncResponseOverrides,
toggleOverride,
useResponseOverrides,
watchOverrideSessions,
} = await import("../js/responseOverrides");
const { refusedIn } = await import("../js/refusals");
type Sessions = ReturnType<typeof useDebug.getState>["sessions"];
function sessions(list: Array<{ id: number; page: boolean; status?: string }>) {
const out: Record<number, unknown> = {};
for (const s of list)
out[s.id] = { id: s.id, name: `s${s.id}`, status: s.status ?? "running", caps: { jsPage: s.page } };
useDebug.setState({ sessions: out as Sessions });
}
const rules = () => useResponseOverrides.getState().rules;
const items = { pattern: "/api/items", status: 200, contentType: "application/json", body: "[]", enabled: true };
beforeEach(async () => {
localStorage.clear();
sessions([]);
loadResponseOverrides(null);
await Promise.resolve();
sent.length = 0;
refuse = null;
});
describe("response overrides", () => {
it("sends the rules that are on and name a part of a URL", () => {
const sentRules = activeRules([
{ id: "a", ...items },
{ id: "b", ...items, pattern: "/api/off", enabled: false },
{ id: "c", ...items, pattern: " " },
]);
expect(sentRules).toEqual([
{ urlContains: "/api/items", status: 200, contentType: "application/json", body: "[]" },
]);
});
it("adds a rule, and updates it under the same id", () => {
loadResponseOverrides("/a");
const id = saveOverride({ ...items, pattern: " /api/items " });
expect(rules()).toEqual([{ id, ...items }]);
expect(saveOverride({ ...items, id, body: "[1]" })).toBe(id);
expect(rules()).toEqual([{ id, ...items, body: "[1]" }]);
toggleOverride(id, false);
expect(rules()[0]!.enabled).toBe(false);
removeOverride(id);
expect(rules()).toEqual([]);
});
it("answers 200 when the status is not an HTTP status", () => {
loadResponseOverrides("/a");
saveOverride({ ...items, status: 99 });
saveOverride({ ...items, pattern: "/b", status: 600 });
saveOverride({ ...items, pattern: "/c", status: Number.NaN });
saveOverride({ ...items, pattern: "/d", status: 404 });
expect(rules().map((r) => r.status)).toEqual([200, 200, 200, 404]);
});
it("is stored per project", () => {
loadResponseOverrides("/a");
saveOverride(items);
loadResponseOverrides("/b");
expect(rules()).toEqual([]);
loadResponseOverrides("/a");
expect(rules().map((r) => r.pattern)).toEqual(["/api/items"]);
});
it("tells which rule replaces a URL's response", () => {
const list = [
{ id: "off", ...items, pattern: "/api", enabled: false },
{ id: "on", ...items },
];
expect(overriddenBy("http://h/api/items?x=1", list)?.id).toBe("on");
expect(overriddenBy("http://h/api/users", list)).toBeNull();
});
it("marks only the requests sent after a rule came into force", async () => {
const { networkSerial } = await import("../js/network");
const before = { url: "http://x/api/items?page=1", seq: networkSerial() - 1 };
const id = saveOverride({
pattern: "/api/items",
status: 200,
contentType: "application/json",
body: "[]",
enabled: true,
});
const rules = useResponseOverrides.getState().rules;
const after = { url: "http://x/api/items?page=2", seq: networkSerial() };
expect(answeredBy(before, rules)).toBe(false);
expect(answeredBy(after, rules)).toBe(true);
// Rules the project has when it opens answer every request of its sessions.
loadResponseOverrides(useResponseOverrides.getState().root);
const loaded = useResponseOverrides.getState().rules;
expect(answeredBy(before, loaded)).toBe(loaded.some((r) => r.id === id));
});
it("syncs every live page session and swallows a refusal", async () => {
sessions([
{ id: 1, page: true },
{ id: 2, page: false },
{ id: 3, page: true },
{ id: 4, page: true, status: "terminated" },
]);
loadResponseOverrides("/a");
useResponseOverrides.setState({ rules: [{ id: "a", ...items }] });
await Promise.resolve();
sent.length = 0;
refuse = 1;
await expect(syncResponseOverrides()).resolves.toBeUndefined();
expect(sent.map(([id, r]) => [id, r.length])).toEqual([
[1, 1],
[3, 1],
]);
// The page whose responses are not replaced is remembered, with the reason.
expect([1, 3].map((id) => refusedIn(id, "overrides"))).toEqual(["refused", undefined]);
refuse = null;
await syncResponseOverrides();
expect(refusedIn(1, "overrides")).toBeUndefined();
});
it("gives a page that starts later the rules, once, and nothing when none is on", async () => {
loadResponseOverrides("/a");
const stop = watchOverrideSessions();
sessions([{ id: 5, page: true }]);
await Promise.resolve();
expect(sent).toEqual([]);
saveOverride(items);
await Promise.resolve();
sent.length = 0;
sessions([
{ id: 5, page: true },
{ id: 7, page: true },
]);
sessions([
{ id: 5, page: true },
{ id: 7, page: true },
]);
await Promise.resolve();
expect(sent.map(([id]) => id)).toEqual([7]);
stop();
});
it("gives a new page the rules when its session id was used before", async () => {
loadResponseOverrides("/a");
saveOverride(items);
const stop = watchOverrideSessions();
sessions([{ id: 1, page: true }]);
await Promise.resolve();
// Ids start over after the backend restarts.
sessions([]);
sent.length = 0;
sessions([{ id: 1, page: true }]);
await Promise.resolve();
expect(sent.map(([id]) => id)).toEqual([1]);
stop();
});
});
+4
View File
@@ -22,6 +22,7 @@ import { loadBreakpoints } from "./breakpoints/store";
import { loadExceptionBreakpoints } from "./breakpoints/exceptions";
import { loadJsBreakpoints, watchPageSessions } from "./js/eventBreakpoints";
import { watchNetworkSessions } from "./js/networkSessions";
import { loadResponseOverrides, watchOverrideSessions } from "./js/responseOverrides";
import { watchProfiledSessions } from "./js/profile";
import { loadSpecialBreakpoints } from "./breakpoints/special";
import { breakpointGutter } from "./editor/breakpointGutter";
@@ -67,6 +68,7 @@ export function activate(): () => void {
loadExceptionBreakpoints(useProject.getState().project?.root ?? null);
loadSpecialBreakpoints(useProject.getState().project?.root ?? null);
loadJsBreakpoints(useProject.getState().project?.root ?? null);
loadResponseOverrides(useProject.getState().project?.root ?? null);
const disposers = [
() => useDebugRunSessions.setState({ sessions: [], serviceSessions: [], Console: null }),
registerDebugActions(),
@@ -147,10 +149,12 @@ export function activate(): () => void {
loadExceptionBreakpoints(root);
loadSpecialBreakpoints(root);
loadJsBreakpoints(root);
loadResponseOverrides(root);
}
}),
watchPageSessions(),
watchNetworkSessions(),
watchOverrideSessions(),
watchProfiledSessions(),
];
return () => disposers.reverse().forEach((d) => d());
@@ -48,9 +48,20 @@
}
.actions {
display: flex;
gap: 4px;
padding-top: 6px;
}
.badge {
margin-left: 6px;
border-radius: 3px;
padding: 0 4px;
background: var(--bg-selected);
color: var(--fg-muted);
font-size: var(--fs-small);
}
.split {
display: flex;
flex: 1;
+60 -4
View File
@@ -11,7 +11,9 @@ import {
type NetworkCategory,
type NetworkRow,
} from "./network";
import { OverridesDialog, type OverrideDraft } from "./OverridesDialog";
import { useRefused } from "./refusals";
import { answeredBy, useResponseOverrides } from "./responseOverrides";
import styles from "./Network.module.css";
const NO_ROWS: NetworkRow[] = [];
@@ -39,10 +41,13 @@ export function formatDuration(ms: number | null): string {
const Row = memo(function Row({
row,
selected,
overridden,
onSelect,
}: {
row: NetworkRow;
selected: boolean;
/** A response override applies to requests to this URL. */
overridden: boolean;
onSelect: (key: string) => void;
}) {
return (
@@ -56,7 +61,14 @@ const Row = memo(function Row({
<span role="cell" className={styles.name}>
{row.name}
</span>
<span role="cell">{row.error ?? row.status ?? ""}</span>
<span role="cell">
{row.error ?? row.status ?? ""}
{overridden && (
<span className={styles.badge}>
<T>overridden</T>
</span>
)}
</span>
<span role="cell">{row.method}</span>
<span role="cell">{row.type}</span>
<span role="cell" className={styles.number}>
@@ -126,7 +138,15 @@ function ResponseBody({ session, requestId }: { session: number; requestId: stri
);
}
function Detail({ session, row }: { session: number; row: NetworkRow }) {
function Detail({
session,
row,
onOverride,
}: {
session: number;
row: NetworkRow;
onOverride: (row: NetworkRow) => void;
}) {
const tx = useTx();
return (
<div className={styles.detail} aria-label={tx("Request details")}>
@@ -144,6 +164,9 @@ function Detail({ session, row }: { session: number; row: NetworkRow }) {
<Button size="small" variant="ghost" onClick={() => addRequestBreakpoint(requestPattern(row.url))}>
<T>Break on Next Request</T>
</Button>
<Button size="small" variant="ghost" onClick={() => onOverride(row)}>
<T>Override Response…</T>
</Button>
</div>
<Headers title={tx("Request Headers")} headers={row.requestHeaders} />
<Headers title={tx("Response Headers")} headers={row.responseHeaders} />
@@ -176,6 +199,23 @@ export function NetworkView({ session }: { session: number }) {
const shown = useMemo(() => filterRows(rows, query, category, mine), [rows, query, category, mine]);
const selected = rows.find((r) => r.key === selectedKey) ?? null;
const notReported = useRefused(session, "network") != null;
const overrides = useResponseOverrides((s) => s.rules);
const overridesOn = overrides.filter((r) => r.enabled).length;
const notReplaced = useRefused(session, "overrides");
// The override editor: open on the list (`draft` null) or on a request's response.
const [editing, setEditing] = useState<{ draft: OverrideDraft | null } | null>(null);
const overrideResponse = async (row: NetworkRow) => {
// The request's own body is where the edit starts; one that can't be read as text starts empty.
const own = await call(commands.debugJsResponseBody(session, row.requestId)).catch(() => null);
setEditing({
draft: {
pattern: requestPattern(row.url),
status: row.status ?? 200,
contentType: row.mimeType ?? "application/json",
body: own && !own.base64Encoded ? own.body : "",
},
});
};
return (
<div className={styles.root}>
<div className={styles.toolbar}>
@@ -199,12 +239,21 @@ export function NetworkView({ session }: { session: number }) {
))}
</div>
<Checkbox checked={mine} onChange={setMine} label="My code only" />
<Button size="small" variant="ghost" onClick={() => setEditing({ draft: null })}>
{tx("Overrides")}
{overridesOn ? ` (${overridesOn})` : ""}
</Button>
<IconButton icon="refresh" title="Reload Page" size="small" onClick={() => reloadPage(session)} />
<IconButton icon="trash" title="Clear" size="small" onClick={() => clearNetwork(session)} />
<span className={styles.count}>
{shown.length === rows.length ? rows.length : `${shown.length} / ${rows.length}`}
</span>
</div>
{notReplaced != null && overridesOn > 0 && (
<div className={styles.refused} role="alert">
{tx`Responses are not replaced in this page: ${notReplaced}`}
</div>
)}
<div className={styles.split}>
<div className={styles.table} role="table" aria-label={tx("Requests")}>
<div role="row" className={styles.head}>
@@ -225,11 +274,18 @@ export function NetworkView({ session }: { session: number }) {
</div>
)}
{shown.map((row) => (
<Row key={row.key} row={row} selected={row.key === selectedKey} onSelect={setSelectedKey} />
<Row
key={row.key}
row={row}
selected={row.key === selectedKey}
overridden={notReplaced == null && answeredBy(row, overrides)}
onSelect={setSelectedKey}
/>
))}
</div>
{selected && <Detail session={session} row={selected} />}
{selected && <Detail session={session} row={selected} onOverride={(row) => void overrideResponse(row)} />}
</div>
<OverridesDialog open={editing != null} onClose={() => setEditing(null)} draft={editing?.draft} />
</div>
);
}
@@ -0,0 +1,135 @@
.root {
display: flex;
height: 420px;
min-height: 0;
font-size: var(--fs-ui);
}
.side {
flex: 0 0 240px;
display: flex;
flex-direction: column;
min-width: 0;
border-right: 1px solid var(--border-popup);
}
.sideHead {
display: flex;
align-items: center;
justify-content: space-between;
padding: 6px 8px 4px 12px;
}
.sideTitle {
font-size: var(--fs-small);
font-weight: 600;
color: var(--fg-muted);
}
.list {
list-style: none;
margin: 0;
padding: 0;
overflow: auto;
}
.item {
display: flex;
align-items: center;
gap: 6px;
min-height: 24px;
padding: 0 8px 0 12px;
}
.item:hover {
background: var(--bg-hover);
}
.itemOn,
.itemOn:hover {
background: var(--bg-list-selected);
}
.itemName {
flex: 1;
min-width: 0;
border: 0;
padding: 0;
background: transparent;
color: inherit;
font-family: var(--font-mono);
font-size: var(--fs-small);
text-align: left;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
cursor: default;
}
.itemStatus {
color: var(--fg-subtle);
font-size: var(--fs-small);
}
.editor {
flex: 1;
min-width: 0;
display: flex;
flex-direction: column;
gap: 8px;
padding: 10px 12px;
}
.row {
display: flex;
gap: 10px;
}
.field {
display: flex;
flex-direction: column;
gap: 3px;
min-height: 0;
}
.grow {
flex: 1;
}
.label {
font-size: var(--fs-small);
color: var(--fg-muted);
}
.body {
flex: 1;
min-height: 120px;
resize: none;
border: 1px solid var(--border);
border-radius: 4px;
padding: 6px 8px;
background: transparent;
color: inherit;
font-family: var(--font-mono);
font-size: var(--fs-small);
outline: none;
}
.body:focus {
border-color: var(--border-popup);
}
.warning {
color: var(--danger);
font-size: var(--fs-small);
}
.actions {
display: flex;
gap: 8px;
}
.note {
padding: 8px 12px;
color: var(--fg-subtle);
}
@@ -0,0 +1,201 @@
import { useState } from "react";
import { useTx } from "@/platform/i18n";
import { Button, Checkbox, Dialog, IconButton, Input, T } from "@/ui";
import {
removeOverride,
saveOverride,
toggleOverride,
useResponseOverrides,
type ResponseOverride,
} from "./responseOverrides";
import styles from "./Overrides.module.css";
/** A response to start a rule from: a request's own, as the Network tab shows it. */
export interface OverrideDraft {
pattern: string;
status: number;
contentType: string;
body: string;
}
interface Form {
/** The rule being edited; absent for one not saved yet. */
id?: string;
pattern: string;
status: string;
contentType: string;
body: string;
}
const EMPTY: Form = { pattern: "", status: "200", contentType: "application/json", body: "" };
const formOf = (rule: ResponseOverride): Form => ({
id: rule.id,
pattern: rule.pattern,
status: String(rule.status),
contentType: rule.contentType,
body: rule.body,
});
/** The rule a request already has is edited; otherwise the request's response starts a new one. */
function initialForm(draft: OverrideDraft | null | undefined, rules: readonly ResponseOverride[]): Form | null {
if (!draft) return null;
const pattern = draft.pattern.trim();
const existing = rules.find((r) => r.pattern === pattern);
return existing
? formOf(existing)
: { pattern, status: String(draft.status), contentType: draft.contentType, body: draft.body };
}
function OverridesBody({ onClose, draft }: { onClose: () => void; draft?: OverrideDraft | null }) {
const tx = useTx();
const rules = useResponseOverrides((s) => s.rules);
const [form, setForm] = useState<Form | null>(() => initialForm(draft, useResponseOverrides.getState().rules));
const set = (patch: Partial<Form>) => setForm((f) => (f ? { ...f, ...patch } : f));
const pattern = form?.pattern.trim() ?? "";
const save = () => {
if (!form || !pattern) return;
const enabled = rules.find((r) => r.id === form.id)?.enabled ?? true;
const id = saveOverride({
id: form.id,
pattern,
status: Number(form.status),
contentType: form.contentType.trim() || "text/plain",
body: form.body,
enabled,
});
setForm({ ...form, id, pattern });
};
return (
<Dialog
open
onClose={onClose}
title="Response Overrides"
width={760}
aria-label="Response Overrides"
buttons={[{ label: "Done", role: "default", onClick: onClose }]}
>
<div className={styles.root}>
<div className={styles.side}>
<div className={styles.sideHead}>
<span className={styles.sideTitle}>
<T>Overrides</T>
</span>
<IconButton icon="plus" title="Add Override" size="small" onClick={() => setForm({ ...EMPTY })} />
</div>
{rules.length === 0 ? (
<div className={styles.note}>
<T>No overrides yet</T>
</div>
) : (
<ul className={styles.list} aria-label={tx("Overrides")}>
{rules.map((rule) => (
<li key={rule.id} className={`${styles.item} ${rule.id === form?.id ? styles.itemOn : ""}`}>
<Checkbox
checked={rule.enabled}
onChange={(on) => toggleOverride(rule.id, on)}
aria-label={rule.pattern}
/>
<button type="button" className={styles.itemName} onClick={() => setForm(formOf(rule))}>
{rule.pattern}
</button>
<span className={styles.itemStatus}>{rule.status}</span>
</li>
))}
</ul>
)}
</div>
{form ? (
<div className={styles.editor}>
<label className={styles.field}>
<span className={styles.label}>
<T>Requests whose URL contains</T>
</span>
<Input
mono
value={form.pattern}
onChange={(e) => set({ pattern: e.target.value })}
placeholder="e.g. /api/items"
aria-label="Part of the URL"
/>
</label>
{pattern.length > 0 && pattern.length < 3 && (
<div className={styles.warning}>
<T>This also replaces every other response whose URL contains it</T>
</div>
)}
<div className={styles.row}>
<label className={styles.field}>
<span className={styles.label}>
<T>Status</T>
</span>
<Input mono value={form.status} onChange={(e) => set({ status: e.target.value })} aria-label="Status" />
</label>
<label className={`${styles.field} ${styles.grow}`}>
<span className={styles.label}>
<T>Content type</T>
</span>
<Input
mono
value={form.contentType}
onChange={(e) => set({ contentType: e.target.value })}
aria-label="Content type"
/>
</label>
</div>
<label className={`${styles.field} ${styles.grow}`}>
<span className={styles.label}>
<T>Response body</T>
</span>
<textarea
className={styles.body}
value={form.body}
onChange={(e) => set({ body: e.target.value })}
spellCheck={false}
aria-label={tx("Response body")}
/>
</label>
<div className={styles.actions}>
<Button size="small" variant="primary" disabled={!pattern} onClick={save}>
<T>Save</T>
</Button>
{form.id && (
<Button
size="small"
variant="ghost"
onClick={() => {
removeOverride(form.id!);
setForm(null);
}}
>
<T>Remove</T>
</Button>
)}
</div>
</div>
) : (
<div className={`${styles.editor} ${styles.note}`}>
<T>Select an override, or add one, to edit the response it gives.</T>
</div>
)}
</div>
</Dialog>
);
}
/**
* The page's response overrides: the list, and the editor of one. Opened on a request
* (`draft`), the editor starts from that request's response.
*/
export function OverridesDialog({
open,
onClose,
draft,
}: {
open: boolean;
onClose: () => void;
draft?: OverrideDraft | null;
}) {
// Mounted per opening, so the editor starts from the request it was opened on.
return open ? <OverridesBody onClose={onClose} draft={draft} /> : null;
}
+7 -1
View File
@@ -8,6 +8,8 @@ import type { JsInitiator, JsNetworkEvent } from "@/platform/ipc";
export interface NetworkRow {
/** Unique among rows; a browser reuses request ids. */
key: string;
/** Order in which the IDE saw the requests (`networkSerial`). */
seq: number;
requestId: string;
url: string;
name: string;
@@ -37,6 +39,9 @@ export const useJsNetwork = create<{ rows: Record<number, NetworkRow[]> }>(() =>
let serial = 0;
/** The end of the URL's path with its query, or the host for the root path. */
/** The `seq` the next request will get. */
export const networkSerial = () => serial;
export function rowName(url: string): string {
try {
const u = new URL(url);
@@ -59,6 +64,7 @@ function apply(rows: NetworkRow[], e: JsNetworkEvent) {
if (e.kind === "request") {
const url = e.url ?? "";
const started: NetworkRow = {
seq: serial,
key: `${e.requestId}#${serial++}`,
requestId: e.requestId,
url,
@@ -77,7 +83,7 @@ function apply(rows: NetworkRow[], e: JsNetworkEvent) {
initiator: e.initiator,
};
// Sent again while open: the request was redirected, and goes on under its new URL.
if (at >= 0) rows[at] = { ...started, key: rows[at]!.key, startedAt: rows[at]!.startedAt };
if (at >= 0) rows[at] = { ...started, key: rows[at]!.key, seq: rows[at]!.seq, startedAt: rows[at]!.startedAt };
else rows.push(started);
return;
}
+1 -1
View File
@@ -4,7 +4,7 @@
*/
import { create } from "zustand";
export type JsTool = "eventBreakpoints" | "network";
export type JsTool = "eventBreakpoints" | "network" | "overrides";
/** Per session, the reason each refused tool was refused for. */
export const useJsRefusals = create<{ refused: Record<number, Partial<Record<JsTool, string>>> }>(() => ({
@@ -0,0 +1,144 @@
/**
* Responses a debugged page gets in place of the server's: "a request whose URL contains
* this text is answered with this status, content type and body". Kept per project and
* given to every page session, to try a screen against data the backend doesn't return yet.
*/
import { create } from "zustand";
import { call, commands, type JsResponseRule } from "@/platform/ipc";
import { isLive, isLiveSession, useDebug } from "../state";
import { networkSerial } from "./network";
import { recordRefusal } from "./refusals";
export interface ResponseOverride {
id: string;
/** Part of the URL. */
pattern: string;
status: number;
contentType: string;
body: string;
enabled: boolean;
}
const PREFIX = "openidea.debugger.jsOverrides:";
export const useResponseOverrides = create<{ root: string | null; rules: ResponseOverride[] }>(() => ({
root: null,
rules: [],
}));
/** A status a browser accepts for a response; anything else answers 200. */
const validStatus = (status: number) => (Number.isInteger(status) && status >= 100 && status <= 599 ? status : 200);
function stored(root: string): ResponseOverride[] {
try {
const raw = JSON.parse(localStorage.getItem(PREFIX + root) ?? "[]") as unknown;
if (!Array.isArray(raw)) return [];
return (raw as Array<Partial<ResponseOverride>>)
.filter((r) => typeof r?.id === "string" && typeof r.pattern === "string")
.map((r) => ({
id: r.id!,
pattern: r.pattern!,
status: validStatus(Number(r.status)),
contentType: typeof r.contentType === "string" ? r.contentType : "application/json",
body: typeof r.body === "string" ? r.body : "",
enabled: r.enabled !== false,
}));
} catch {
return [];
}
}
/**
* The first request (`NetworkRow.seq`) each rule can have answered, for rules added, turned on or
* pointed at other URLs while pages ran; rules loaded with the project answer from the start.
*/
const since = new Map<string, number>();
export function loadResponseOverrides(root: string | null) {
since.clear();
useResponseOverrides.setState({ root, rules: root ? stored(root) : [] });
void syncResponseOverrides();
}
function change(rules: ResponseOverride[]) {
useResponseOverrides.setState({ rules });
const { root } = useResponseOverrides.getState();
if (root) {
try {
localStorage.setItem(PREFIX + root, JSON.stringify(rules));
} catch {
// Storage unavailable: the rules last for this session only.
}
}
void syncResponseOverrides();
}
/** Adds a rule, or replaces the one with `rule.id`. Returns the rule's id. */
/** Whether the rule that matches `row` was in force when the page sent it. */
export function answeredBy(row: { url: string; seq: number }, rules: readonly ResponseOverride[]): boolean {
const rule = overriddenBy(row.url, rules);
return rule != null && row.seq >= (since.get(rule.id) ?? 0);
}
export function saveOverride(rule: Omit<ResponseOverride, "id"> & { id?: string }): string {
const { rules } = useResponseOverrides.getState();
const id = rule.id ?? `o${Date.now().toString(36)}${Math.random().toString(36).slice(2, 6)}`;
const saved = { ...rule, id, pattern: rule.pattern.trim(), status: validStatus(rule.status) };
const before = rules.find((r) => r.id === id);
if (saved.enabled && (!before?.enabled || before.pattern !== saved.pattern)) since.set(id, networkSerial());
change(rules.some((r) => r.id === id) ? rules.map((r) => (r.id === id ? saved : r)) : [...rules, saved]);
return id;
}
export function removeOverride(id: string) {
change(useResponseOverrides.getState().rules.filter((r) => r.id !== id));
}
export function toggleOverride(id: string, on: boolean) {
if (on && !useResponseOverrides.getState().rules.find((r) => r.id === id)?.enabled) since.set(id, networkSerial());
change(useResponseOverrides.getState().rules.map((r) => (r.id === id ? { ...r, enabled: on } : r)));
}
/** What the debugger is given: the rules that are on and name a part of a URL. */
export function activeRules(rules: readonly ResponseOverride[]): JsResponseRule[] {
return rules
.filter((r) => r.enabled && r.pattern.trim())
.map((r) => ({ urlContains: r.pattern.trim(), status: r.status, contentType: r.contentType, body: r.body }));
}
/** The rule that replaces the response of `url`, as the debugger picks it: the first that is on and matches. */
export function overriddenBy(url: string, rules: readonly ResponseOverride[]): ResponseOverride | null {
return rules.find((r) => r.enabled && r.pattern.trim() && url.includes(r.pattern.trim())) ?? null;
}
/**
* Gives the live page sessions (`only` those, when given) the rules. A page whose debugger
* refuses keeps the server's responses, which is recorded for the views to say.
*/
export async function syncResponseOverrides(only?: readonly number[]): Promise<void> {
const rules = activeRules(useResponseOverrides.getState().rules);
const pages = Object.values(useDebug.getState().sessions).filter(
(s) => isLive(s) && s.caps?.jsPage && (!only || only.includes(s.id)),
);
await Promise.all(
pages.map((s) =>
recordRefusal(s.id, "overrides", call(commands.debugJsResponseOverrides(s.id, rules)), () => isLiveSession(s.id)),
),
);
}
/** Gives each page session the rules when it appears. Returns the unsubscribe function. */
export function watchOverrideSessions(): () => void {
const seen = new Set<number>();
return useDebug.subscribe((s) => {
// Ids start over after the backend restarts: a removed session's id may come back as a new page.
for (const id of seen) if (!s.sessions[id]) seen.delete(id);
for (const session of Object.values(s.sessions)) {
if (seen.has(session.id) || !session.caps?.jsPage || !isLive(session)) continue;
seen.add(session.id);
// A new page has none: nothing to send.
if (activeRules(useResponseOverrides.getState().rules).length) void syncResponseOverrides([session.id]);
}
});
}
+12
View File
@@ -1689,6 +1689,17 @@
"Showing the first 1 MB": "Showing the first 1 MB",
"Time": "Time",
"Break on Next Request": "Break on Next Request",
"Add Override": "Add Override",
"Content type": "Content type",
"e.g. /api/items": "e.g. /api/items",
"No overrides yet": "No overrides yet",
"overridden": "overridden",
"Override Response…": "Override Response…",
"Overrides": "Overrides",
"Part of the URL": "Part of the URL",
"Response Overrides": "Response Overrides",
"Select an override, or add one, to edit the response it gives.": "Select an override, or add one, to edit the response it gives.",
"This also replaces every other response whose URL contains it": "This also replaces every other response whose URL contains it",
"My code only": "My code only",
"Resource type": "Resource type",
"Doc": "Doc",
@@ -1699,6 +1710,7 @@
"Where the debugger can do it without suspending (JavaScript). A watch with side effects runs again on each refresh.": "Where the debugger can do it without suspending (JavaScript). A watch with side effects runs again on each refresh.",
"Stash Selected Files…": "Stash Selected Files…",
"Select the files to stash in the Commit view first": "Select the files to stash in the Commit view first",
"Responses are not replaced in this page: {why}": "Responses are not replaced in this page: {why}",
"Start CPU Profile": "Start CPU Profile",
"Stop CPU Profile": "Stop CPU Profile",
"Show CPU Profile": "Show CPU Profile",
+12
View File
@@ -8077,6 +8077,17 @@
"Showing the first 1 MB": "仅显示前 1 MB",
"Time": "时间",
"Break on Next Request": "下次请求时中断",
"Add Override": "添加覆盖",
"Content type": "内容类型",
"e.g. /api/items": "例如 /api/items",
"No overrides yet": "还没有覆盖",
"overridden": "已覆盖",
"Override Response…": "覆盖响应…",
"Overrides": "覆盖",
"Part of the URL": "URL 的一部分",
"Response Overrides": "响应覆盖",
"Select an override, or add one, to edit the response it gives.": "选择或添加一个覆盖,以编辑它返回的响应。",
"This also replaces every other response whose URL contains it": "URL 包含它的其他所有响应也会被替换",
"My code only": "仅我的代码",
"Resource type": "资源类型",
"Doc": "文档",
@@ -8085,6 +8096,7 @@
"No requests yet. Reload the page to see the requests of its load.": "还没有请求。重新加载页面即可看到加载时的请求。",
"Evaluate watches while the program runs": "程序运行时计算监视表达式",
"Where the debugger can do it without suspending (JavaScript). A watch with side effects runs again on each refresh.": "仅适用于无需暂停即可计算的调试器(JavaScript)。带副作用的监视表达式在每次刷新时都会再次执行。",
"Responses are not replaced in this page: {why}": "此页面的响应未被替换:{why}",
"Start CPU Profile": "开始 CPU 性能分析",
"Stop CPU Profile": "停止 CPU 性能分析",
"Show CPU Profile": "显示 CPU 性能分析",