Skip to main content

day_piece_webview/
content.rs

1// Copyright © The Daybrite Project
2// SPDX-License-Identifier: MPL-2.0
3
4//! Content blocking and page scripts (docs/webview.md, "Content blocking and page scripts"):
5//! the engine-agnostic half of [`crate::WebView::request_filter`],
6//! [`crate::WebView::content_rules`], [`crate::WebView::user_script`],
7//! [`crate::WebView::user_style`], [`crate::WebView::on_script_message`],
8//! [`crate::WebView::on_blocked`] and [`crate::WebView::on_media_request`].
9//!
10//! These are hooks, not a blocker: the app supplies the decisions, the rule lists and the
11//! scripts, and each backend wires them into its engine's own mechanism.
12
13use std::collections::BTreeMap;
14use std::sync::{Arc, Mutex, MutexGuard};
15
16use day_spec::Support;
17
18/// Decides whether a web view may load a request. Engines with a per-request hook (Android
19/// `WebView`, WebView2, QtWebEngine, ArkWeb) call it for every request a page makes, before the
20/// request leaves the device.
21///
22/// It runs on whatever thread the engine calls back on: a `WebView` background thread on
23/// Android, the UI thread on WebView2 and Qt, ArkWeb's IO thread. Keep it fast, in memory and
24/// free of locks the UI thread holds, and never touch Day's reactive graph from it. Every
25/// request of every page waits for the answer.
26pub trait RequestFilter: Send + Sync + 'static {
27    /// The verdict for one request.
28    fn decide(&self, request: &RequestInfo<'_>) -> RequestDecision;
29}
30
31impl<F> RequestFilter for F
32where
33    F: Fn(&RequestInfo<'_>) -> RequestDecision + Send + Sync + 'static,
34{
35    fn decide(&self, request: &RequestInfo<'_>) -> RequestDecision {
36        self(request)
37    }
38}
39
40/// One request, as the engine describes it to a [`RequestFilter`].
41#[derive(Clone, Copy, Debug, PartialEq, Eq)]
42pub struct RequestInfo<'a> {
43    /// The URL being requested.
44    pub url: &'a str,
45    /// The page shown in the view (the top-level document). Engines that do not report it
46    /// (Android, WebView2) get it from the piece, which follows each main-frame navigation.
47    /// `None` before the first page.
48    pub top_url: Option<&'a str>,
49    /// The URL of the frame making the request, where the engine reports it (ArkWeb).
50    pub frame_url: Option<&'a str>,
51    /// What the request loads. [`ResourceKind::infer`] guesses it on engines that do not say.
52    pub kind: ResourceKind,
53    /// Whether this is the top-level frame's own document: a navigation of the whole view.
54    pub main_frame: bool,
55    /// The HTTP method, upper case (`GET`, `POST`, …).
56    pub method: &'a str,
57}
58
59/// What a request loads.
60#[derive(
61    Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize,
62)]
63#[serde(rename_all = "kebab-case")]
64pub enum ResourceKind {
65    /// A page loaded into a frame; with `main_frame` set, a navigation of the whole view.
66    Document,
67    /// A page loaded into an iframe.
68    Subdocument,
69    /// JavaScript.
70    Script,
71    /// CSS.
72    Stylesheet,
73    /// An image.
74    Image,
75    /// A web font.
76    Font,
77    /// Audio or video.
78    Media,
79    /// `XMLHttpRequest`.
80    Xhr,
81    /// `fetch()`.
82    Fetch,
83    /// A WebSocket connection.
84    WebSocket,
85    /// A beacon, `<a ping>` or CSP report.
86    Ping,
87    /// A plug-in object (`<object>`, `<embed>`).
88    Object,
89    /// Anything else the engine names (a worker, a manifest, a prefetch).
90    Other,
91    /// The engine does not say, and nothing suggests a kind.
92    #[default]
93    Unknown,
94}
95
96impl ResourceKind {
97    /// The kind an engine without request types (Android `WebView`) implies, from the request's
98    /// `Accept` header and the URL's extension. The header wins where it is specific: browsers
99    /// send `text/html` for documents, `text/css` for style sheets and `image/…` for images,
100    /// while scripts and `fetch` both send `*/*`, so those fall back to the extension.
101    pub fn infer(url: &str, accept: Option<&str>, main_frame: bool) -> ResourceKind {
102        if main_frame {
103            return ResourceKind::Document;
104        }
105        let accept = accept.unwrap_or_default().to_ascii_lowercase();
106        let first = accept.split(',').next().unwrap_or_default().trim();
107        if first.starts_with("text/html") || first.starts_with("application/xhtml") {
108            return ResourceKind::Subdocument;
109        }
110        if first.starts_with("text/css") {
111            return ResourceKind::Stylesheet;
112        }
113        if first.starts_with("image/") {
114            return ResourceKind::Image;
115        }
116        if first.starts_with("video/") || first.starts_with("audio/") {
117            return ResourceKind::Media;
118        }
119        if first.starts_with("font/") || first.starts_with("application/font") {
120            return ResourceKind::Font;
121        }
122        if first == "text/event-stream" {
123            return ResourceKind::Xhr;
124        }
125        match ResourceKind::from_extension(url) {
126            ResourceKind::Unknown if first.starts_with("application/json") => ResourceKind::Xhr,
127            kind => kind,
128        }
129    }
130
131    /// The kind a URL's file extension suggests, or [`ResourceKind::Unknown`].
132    fn from_extension(url: &str) -> ResourceKind {
133        let path = url.split(['?', '#']).next().unwrap_or_default();
134        let path = path.split_once("://").map_or(path, |(_, rest)| {
135            rest.split_once('/').map_or("", |(_, p)| p)
136        });
137        let last = path.rsplit('/').next().unwrap_or_default();
138        let Some((_, ext)) = last.rsplit_once('.') else {
139            return ResourceKind::Unknown;
140        };
141        match ext.to_ascii_lowercase().as_str() {
142            "js" | "mjs" | "cjs" => ResourceKind::Script,
143            "css" => ResourceKind::Stylesheet,
144            "png" | "jpg" | "jpeg" | "gif" | "webp" | "avif" | "svg" | "ico" | "bmp" => {
145                ResourceKind::Image
146            }
147            "woff" | "woff2" | "ttf" | "otf" | "eot" => ResourceKind::Font,
148            "mp4" | "webm" | "mp3" | "m4a" | "m4v" | "ogg" | "oga" | "wav" | "m3u8" | "mpd" => {
149                ResourceKind::Media
150            }
151            "html" | "htm" => ResourceKind::Subdocument,
152            "json" | "xml" => ResourceKind::Xhr,
153            _ => ResourceKind::Unknown,
154        }
155    }
156
157    /// The kind a Chromium `ResourceType` names (QtWebEngine's `ResourceType`, ArkWeb's
158    /// `ArkWeb_ResourceType`: the same numbering, 0 = main frame … 20). Qt's later additions
159    /// (21 = WebSocket, 22 = JSON) follow it.
160    #[allow(
161        dead_code,
162        reason = "only the Qt and ArkUI arms see Chromium resource types"
163    )]
164    pub(crate) fn from_chromium(code: i32) -> ResourceKind {
165        match code {
166            0 | 19 => ResourceKind::Document,
167            1 | 20 => ResourceKind::Subdocument,
168            2 => ResourceKind::Stylesheet,
169            3 => ResourceKind::Script,
170            4 | 12 => ResourceKind::Image,
171            5 => ResourceKind::Font,
172            7 | 17 => ResourceKind::Object,
173            8 => ResourceKind::Media,
174            13 | 22 => ResourceKind::Xhr,
175            14 | 16 => ResourceKind::Ping,
176            21 => ResourceKind::WebSocket,
177            6 | 9 | 10 | 11 | 15 | 18 => ResourceKind::Other,
178            _ => ResourceKind::Unknown,
179        }
180    }
181
182    /// The kind a WebView2 `COREWEBVIEW2_WEB_RESOURCE_CONTEXT` names.
183    #[allow(
184        dead_code,
185        reason = "only the WinUI arm sees WebView2 resource contexts"
186    )]
187    #[expect(
188        clippy::match_same_arms,
189        reason = "one arm per WebView2 context value, in numeric order"
190    )]
191    pub(crate) fn from_webview2(context: i32) -> ResourceKind {
192        match context {
193            1 => ResourceKind::Document,
194            2 => ResourceKind::Stylesheet,
195            3 => ResourceKind::Image,
196            4 => ResourceKind::Media,
197            5 => ResourceKind::Font,
198            6 => ResourceKind::Script,
199            7 => ResourceKind::Xhr,
200            8 => ResourceKind::Fetch,
201            10 => ResourceKind::Xhr, // EventSource
202            11 => ResourceKind::WebSocket,
203            14 | 15 => ResourceKind::Ping, // Ping, CspViolationReport
204            9 | 12 | 13 | 16 => ResourceKind::Other,
205            _ => ResourceKind::Unknown,
206        }
207    }
208}
209
210/// A [`RequestFilter`]'s verdict.
211#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
212pub enum RequestDecision {
213    /// Load the request.
214    #[default]
215    Allow,
216    /// Refuse it. The page sees a failed load (an empty `403` where the engine answers with a
217    /// response).
218    Block,
219}
220
221/// A request a [`RequestFilter`] blocked, as [`crate::WebView::on_blocked`] reports it.
222#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
223pub struct BlockedLoad {
224    /// The URL that was not loaded.
225    pub url: String,
226    /// The page that asked for it: the top-level page the view showed, or the frame's address
227    /// where the engine reports one.
228    pub page_url: String,
229    /// What it would have loaded.
230    pub kind: ResourceKind,
231}
232
233/// A WebKit content rule list ([`crate::WebView::content_rules`]): a JSON array of
234/// `{"trigger": …, "action": …}` rules in WebKit's content blocker format, compiled by the
235/// engine once and kept compiled across launches.
236#[derive(Clone, Debug, PartialEq, Eq)]
237pub struct ContentRuleList {
238    /// Names the list in the engine's compiled store. Keep it stable across launches.
239    pub id: String,
240    /// The list's version. A compiled list whose version differs is compiled again; one whose
241    /// version matches is loaded as it is, without reading `json`.
242    pub version: String,
243    /// The rules, as JSON text.
244    pub json: Arc<str>,
245}
246
247impl ContentRuleList {
248    /// A list named `id` at `version`.
249    pub fn new(
250        id: impl Into<String>,
251        version: impl Into<String>,
252        json: impl Into<Arc<str>>,
253    ) -> Self {
254        ContentRuleList {
255            id: id.into(),
256            version: version.into(),
257            json: json.into(),
258        }
259    }
260
261    /// The identifier the compiled list is stored under: the id and version together, so a
262    /// relaunch finds the compiled list for this version and a new version compiles afresh.
263    #[allow(
264        dead_code,
265        reason = "only the Apple arms keep compiled rule lists in a store"
266    )]
267    pub(crate) fn store_identifier(&self) -> String {
268        format!("{}@{}", self.id, self.version)
269    }
270}
271
272/// A content rule list failed to compile ([`crate::WebView::on_content_rules_error`]).
273#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
274pub struct ContentRulesError {
275    /// The list's [`ContentRuleList::id`].
276    pub id: String,
277    /// The engine's message.
278    pub message: String,
279}
280
281/// When a [`UserScript`] runs.
282#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
283pub enum InjectAt {
284    /// As the document is created, before the page's own scripts.
285    #[default]
286    DocumentStart,
287    /// Once the document has been parsed (`DOMContentLoaded`), before subresources finish.
288    DocumentEnd,
289}
290
291/// Which frames a [`UserScript`] runs in.
292#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
293pub enum Frames {
294    /// The top-level document and every iframe.
295    #[default]
296    All,
297    /// The top-level document only.
298    Main,
299}
300
301/// A script the view runs in every page it loads ([`crate::WebView::user_script`]), in the
302/// page's own JavaScript world.
303#[derive(Clone, Debug, PartialEq, Eq)]
304#[must_use]
305pub struct UserScript {
306    /// The script.
307    pub source: Arc<str>,
308    /// When it runs.
309    pub at: InjectAt,
310    /// Which frames it runs in.
311    pub frames: Frames,
312}
313
314impl UserScript {
315    /// `source`, at document start, in every frame.
316    pub fn new(source: impl Into<Arc<str>>) -> Self {
317        UserScript {
318            source: source.into(),
319            at: InjectAt::DocumentStart,
320            frames: Frames::All,
321        }
322    }
323
324    /// Run at `at` instead.
325    pub fn at(mut self, at: InjectAt) -> Self {
326        self.at = at;
327        self
328    }
329
330    /// Run in `frames` instead.
331    pub fn frames(mut self, frames: Frames) -> Self {
332        self.frames = frames;
333        self
334    }
335}
336
337/// A message a page posted with `window.dayMessage(name, payload)`
338/// ([`crate::WebView::on_script_message`]).
339///
340/// Every frame the message shim runs in can post one, ads and other third-party frames
341/// included. Treat the payload as untrusted input.
342#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
343pub struct ScriptMessage {
344    /// The handler's name.
345    pub name: String,
346    /// What the page sent, as text.
347    pub payload: String,
348    /// The security origin of the frame that sent it, where the engine vouches for it (WebKit,
349    /// Android, WebView2); empty elsewhere.
350    #[serde(default)]
351    pub origin: String,
352    /// Whether the top-level document sent it.
353    #[serde(default)]
354    pub main_frame: bool,
355}
356
357/// A page asked for the camera or microphone (`getUserMedia`), the question
358/// [`crate::WebView::on_media_request`] answers.
359#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
360pub struct MediaRequest {
361    /// The origin of the page asking.
362    pub origin: String,
363    /// It asks for the camera.
364    pub camera: bool,
365    /// It asks for the microphone.
366    pub microphone: bool,
367}
368
369/// The view's request filter as a backend receives it in [`crate::WebProps::content`]. Call
370/// [`RequestHooks::decide`] from the engine's request callback on any thread: it fills in the
371/// top-level page the piece tracked, never lets the filter block the crate's own resource
372/// namespace, and reports what it blocked to [`crate::WebView::on_blocked`].
373#[derive(Clone)]
374pub struct RequestHooks(Arc<Hooks>);
375
376struct Hooks {
377    filter: Arc<dyn RequestFilter>,
378    /// The top-level page, as the last allowed main-frame document request (or the backend,
379    /// through [`RequestHooks::set_top_url`]) left it.
380    top: Mutex<String>,
381    blocked: Option<Arc<BlockedSink>>,
382    /// The resource namespace is the app's own site here (a provider's site or a bundled one),
383    /// so the filter never sees it.
384    exempt_internal: bool,
385}
386
387impl RequestHooks {
388    pub(crate) fn new(
389        filter: Arc<dyn RequestFilter>,
390        blocked: Option<Arc<BlockedSink>>,
391        exempt_internal: bool,
392    ) -> Self {
393        RequestHooks(Arc::new(Hooks {
394            filter,
395            top: Mutex::new(String::new()),
396            blocked,
397            exempt_internal,
398        }))
399    }
400
401    /// Whether requests in the crate's resource namespace go to the filter too: a view that
402    /// browses anywhere with a provider beside it (`WebView::resources`) serves pages that stand
403    /// for other sites, while a provider's own site or a bundled site is the app's own.
404    pub fn filters_internal(&self) -> bool {
405        !self.0.exempt_internal
406    }
407
408    /// Ask the filter about `request`. Safe on any thread.
409    ///
410    /// The crate's own resource namespace (every form `ResourceProvider::base_url` gives) is
411    /// allowed without asking where it is the app's own site ([`Self::filters_internal`]).
412    /// A filter that panics allows the request rather than unwinding into the engine.
413    pub fn decide(&self, request: &RequestInfo<'_>) -> RequestDecision {
414        if self.0.exempt_internal && is_internal(request.url) {
415            return RequestDecision::Allow;
416        }
417        let tracked = match request.top_url {
418            Some(_) => None,
419            None => Some(lock(&self.0.top).clone()).filter(|top| !top.is_empty()),
420        };
421        let info = RequestInfo {
422            top_url: request.top_url.or(tracked.as_deref()),
423            ..*request
424        };
425        let filter = &self.0.filter;
426        let decision =
427            std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| filter.decide(&info)))
428                .unwrap_or_else(|_| {
429                    log::warn!(
430                        "day-piece-webview: a request filter panicked; allowing {}",
431                        info.url
432                    );
433                    RequestDecision::Allow
434                });
435        match decision {
436            RequestDecision::Allow if info.main_frame && info.kind == ResourceKind::Document => {
437                self.set_top_url(info.url);
438            }
439            RequestDecision::Block => {
440                if let Some(sink) = &self.0.blocked {
441                    sink.push(BlockedLoad {
442                        url: info.url.to_owned(),
443                        page_url: info
444                            .frame_url
445                            .or(info.top_url)
446                            .unwrap_or(info.url)
447                            .to_owned(),
448                        kind: info.kind,
449                    });
450                }
451            }
452            RequestDecision::Allow => {}
453        }
454        decision
455    }
456
457    /// Record the page the view now shows, for engines that report main-frame navigations
458    /// separately from requests (WebView2's `NavigationStarting`).
459    pub fn set_top_url(&self, url: &str) {
460        let mut top = lock(&self.0.top);
461        if *top != url {
462            url.clone_into(&mut top);
463        }
464    }
465
466    /// The page the view shows, as far as the hooks know.
467    pub fn top_url(&self) -> String {
468        lock(&self.0.top).clone()
469    }
470}
471
472impl PartialEq for RequestHooks {
473    fn eq(&self, other: &Self) -> bool {
474        Arc::ptr_eq(&self.0, &other.0)
475    }
476}
477
478impl std::fmt::Debug for RequestHooks {
479    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
480        f.write_str("RequestHooks")
481    }
482}
483
484/// A lock that a panicking holder did not poison for everyone else: the data is plain values.
485fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
486    mutex
487        .lock()
488        .unwrap_or_else(std::sync::PoisonError::into_inner)
489}
490
491/// URLs in the crate's resource namespace, in every form
492/// [`crate::ResourceProvider::base_url`] gives it: `day-resource://p<id>/`,
493/// `https://day-resource.invalid/<id>/`, and `http://day-resource.p<id>/` on Windows without
494/// WebView2.
495fn is_internal(url: &str) -> bool {
496    url.starts_with("day-resource:")
497        || url.starts_with("https://day-resource.invalid/")
498        || url
499            .strip_prefix("http://day-resource.p")
500            .and_then(|rest| rest.split_once('/'))
501            .is_some_and(|(id, _)| !id.is_empty() && id.bytes().all(|b| b.is_ascii_digit()))
502}
503
504/// The most blocked loads kept between two deliveries. A page that blocks more within one
505/// delivery period loses the excess from the report (never from blocking).
506const BLOCKED_BACKLOG: usize = 2000;
507
508/// How often blocked loads reach [`crate::WebView::on_blocked`], at most: one call per
509/// period with everything blocked in it.
510pub(crate) const BLOCKED_PERIOD_MS: u32 = 100;
511
512/// Blocked loads on their way to the UI thread. Filled from any thread; drained by the
513/// front-end's delivery task, which it wakes when the first load of a batch arrives.
514#[derive(Default)]
515pub(crate) struct BlockedSink {
516    state: Mutex<SinkState>,
517}
518
519#[derive(Default)]
520struct SinkState {
521    loads: Vec<BlockedLoad>,
522    wake: Option<day_async::Deliver<()>>,
523    dropped: usize,
524}
525
526impl BlockedSink {
527    pub(crate) fn push(&self, load: BlockedLoad) {
528        self.extend(std::iter::once(load));
529    }
530
531    pub(crate) fn extend(&self, loads: impl IntoIterator<Item = BlockedLoad>) {
532        let wake = {
533            let mut state = lock(&self.state);
534            for load in loads {
535                if state.loads.len() < BLOCKED_BACKLOG {
536                    state.loads.push(load);
537                } else {
538                    state.dropped += 1;
539                }
540            }
541            if state.loads.is_empty() {
542                None
543            } else {
544                state.wake.take()
545            }
546        };
547        if let Some(wake) = wake {
548            wake.send(());
549        }
550    }
551
552    /// Everything waiting, or a future that resolves when something arrives.
553    fn take_or_wait(&self) -> Result<Vec<BlockedLoad>, day_async::Oneshot<()>> {
554        let mut state = lock(&self.state);
555        if !state.loads.is_empty() {
556            if state.dropped > 0 {
557                log::debug!(
558                    "day-piece-webview: {} blocked loads not reported (backlog full)",
559                    state.dropped
560                );
561                state.dropped = 0;
562            }
563            return Ok(std::mem::take(&mut state.loads));
564        }
565        let (tx, rx) = day_async::oneshot();
566        state.wake = Some(tx);
567        Err(rx)
568    }
569}
570
571/// What [`crate::WebView::on_blocked`] stores.
572pub(crate) type BlockedCallback = std::rc::Rc<dyn Fn(&[BlockedLoad])>;
573
574/// Deliver `sink`'s loads to `callback` on the UI thread: one call per
575/// [`BLOCKED_PERIOD_MS`] at most, carrying everything blocked since the last one.
576pub(crate) fn deliver_blocked(
577    sink: Arc<BlockedSink>,
578    callback: BlockedCallback,
579) -> day_core::TaskHandle {
580    day_core::task(async move {
581        loop {
582            match sink.take_or_wait() {
583                Ok(loads) => {
584                    callback(&loads);
585                    day_core::sleep(BLOCKED_PERIOD_MS).await;
586                }
587                Err(arrival) => {
588                    if arrival.await.is_err() {
589                        return;
590                    }
591                    // Let the rest of the burst arrive before the first delivery.
592                    day_core::sleep(BLOCKED_PERIOD_MS).await;
593                }
594            }
595        }
596    })
597}
598
599/// Request hooks by token, for backends whose engine callback arrives through Java or C
600/// carrying a number rather than a Rust reference. The registry holds them weakly: the
601/// front-end keeps a view's hooks alive for as long as its node lives, and a callback that
602/// arrives after that finds nothing and allows the request.
603static TOKENS: Mutex<BTreeMap<u64, std::sync::Weak<Hooks>>> = Mutex::new(BTreeMap::new());
604
605/// Register `hooks` and return the token that finds them again (never 0).
606#[allow(
607    dead_code,
608    reason = "only the Android, Qt, WinUI and ArkUI arms reach their hooks by token"
609)]
610pub(crate) fn register(hooks: &RequestHooks) -> u64 {
611    let token = day_async::next_token();
612    let mut tokens = lock(&TOKENS);
613    tokens.retain(|_, hooks| hooks.strong_count() > 0);
614    tokens.insert(token, Arc::downgrade(&hooks.0));
615    token
616}
617
618/// Forget a [`register`]ed token at once.
619#[cfg(test)]
620pub(crate) fn unregister(token: u64) {
621    lock(&TOKENS).remove(&token);
622}
623
624/// The hooks a token names, while their view lives.
625#[allow(
626    dead_code,
627    reason = "only the Android, Qt, WinUI and ArkUI arms reach their hooks by token"
628)]
629pub(crate) fn hooks(token: u64) -> Option<RequestHooks> {
630    if token == 0 {
631        return None;
632    }
633    lock(&TOKENS)
634        .get(&token)
635        .and_then(std::sync::Weak::upgrade)
636        .map(RequestHooks)
637}
638
639/// Everything [`crate::WebView`]'s content hooks hand a backend: part of [`crate::WebProps`].
640/// Changes to the rule lists arrive later as [`crate::WebPatch::ContentRules`]; the rest is fixed
641/// when the view is built.
642#[derive(Clone, Debug, Default, PartialEq)]
643pub struct PageContent {
644    /// The request filter, wrapped for any-thread use ([`crate::WebView::request_filter`]).
645    pub requests: Option<RequestHooks>,
646    /// Content rule lists for WebKit engines ([`crate::WebView::content_rules`]).
647    pub rules: Vec<ContentRuleList>,
648    /// The app's user scripts, in the order they were added ([`crate::WebView::user_script`]).
649    pub scripts: Vec<UserScript>,
650    /// User style sheets ([`crate::WebView::user_style`]), applied to every frame.
651    pub styles: Vec<Arc<str>>,
652    /// The names pages may post to with `window.dayMessage(name, payload)`
653    /// ([`crate::WebView::on_script_message`]).
654    pub messages: Vec<String>,
655    /// The app decides camera and microphone requests itself
656    /// ([`crate::WebView::on_media_request`]); without it the backend's default applies.
657    pub media_handler: bool,
658}
659
660impl PageContent {
661    /// Whether the view has page scripts of any kind to install.
662    #[allow(
663        dead_code,
664        reason = "only the Android, Qt, WinUI and ArkUI arms ask before injecting the bridge"
665    )]
666    pub(crate) fn has_scripts(&self) -> bool {
667        !self.scripts.is_empty() || !self.styles.is_empty() || !self.messages.is_empty()
668    }
669
670    /// The scripts a backend installs, in order: the message shim (for `transport`, when pages
671    /// may post messages), each user style as a script that adds a `<style>` (unless the engine
672    /// has native user style sheets), then the app's scripts.
673    #[allow(
674        dead_code,
675        reason = "every native arm injects scripts; the web arm and a build with none do not"
676    )]
677    pub(crate) fn page_scripts(
678        &self,
679        transport: Transport,
680        native_styles: bool,
681    ) -> Vec<UserScript> {
682        let mut scripts = Vec::new();
683        if !self.messages.is_empty() {
684            scripts.push(UserScript::new(message_shim(transport, &self.messages)));
685        }
686        if !native_styles {
687            scripts.extend(
688                self.styles
689                    .iter()
690                    .map(|css| UserScript::new(style_script(css))),
691            );
692        }
693        scripts.extend(self.scripts.iter().cloned());
694        scripts
695    }
696}
697
698/// How a backend's message shim reaches the app.
699#[allow(
700    dead_code,
701    reason = "each arm builds its own transport, so the others' variants are never built"
702)]
703#[derive(Clone, Copy, Debug, PartialEq, Eq)]
704pub(crate) enum Transport {
705    /// WebKit: `webkit.messageHandlers[name]`, a handler with replies, so `postMessage` itself
706    /// returns the reply promise.
707    WebKit,
708    /// Android: `window[name]`, a web message listener object; replies come back as messages
709    /// on it, tagged with the request id.
710    Android,
711    /// WebView2: `chrome.webview.postMessage` with a JSON envelope; replies as web messages.
712    WebView2,
713    /// Qt and ArkWeb: a host object or console line carrying a JSON envelope; replies arrive
714    /// through `window.__dayMessageReply(id, value)`, evaluated in the top-level document.
715    Envelope(&'static str),
716}
717
718/// `window.dayMessage(name, payload)`: the one page-side API for every engine. It returns a
719/// promise of the handler's reply (`null` without one). Where the engine has no object of its
720/// own per name, it also defines `window[name].postMessage(text)`, fire-and-forget, so a page
721/// script written against WebKit's or Android's spelling works unchanged.
722pub(crate) fn message_shim(transport: Transport, names: &[String]) -> String {
723    let names = serde_json::to_string(names).unwrap_or_else(|_| "[]".into());
724    let send = match transport {
725        Transport::WebKit => {
726            "const h=window.webkit&&window.webkit.messageHandlers&&window.webkit.messageHandlers[name];\
727             if(!h)return Promise.reject(new Error('no handler '+name));\
728             return Promise.resolve(h.postMessage(text)).then(v=>v===undefined?null:v);"
729                .to_owned()
730        }
731        Transport::Android => {
732            // Replies are messages on the same object, `\u0002<id>\u0002<0|1><text>`.
733            "const o=window[name];if(!o||typeof o.postMessage!=='function')return Promise.reject(new Error('no handler '+name));\
734             if(!hooked.has(name)){hooked.add(name);o.addEventListener('message',e=>{const d=String(e.data);if(d.charCodeAt(0)!==2)return;\
735             const i=d.indexOf('\\u0002',1);settle(+d.slice(1,i),d.charAt(i+1)==='1'?d.slice(i+2):null);});}\
736             const id=next++;return new Promise(r=>{waiting.set(id,r);o.postMessage('\\u0002'+id+'\\u0002'+text);});"
737                .to_owned()
738        }
739        Transport::WebView2 => {
740            "const w=window.chrome&&window.chrome.webview;if(!w)return Promise.reject(new Error('no host'));\
741             if(!hooked.has('')){hooked.add('');w.addEventListener('message',e=>{const d=e.data;if(d&&typeof d==='object'&&'dayMessageReply' in d)settle(d.dayMessageReply,d.value);});}\
742             const id=next++;return new Promise(r=>{waiting.set(id,r);w.postMessage(JSON.stringify({dayMessage:name,id:id,payload:text}));});"
743                .to_owned()
744        }
745        // Replies reach the top-level document only, so a frame's promise settles at once.
746        Transport::Envelope(post) => format!(
747            "const id=next++;const e=JSON.stringify({{dayMessage:name,id:id,payload:text}});\
748             if(window!==window.top){{{post}(e);return Promise.resolve(null);}}\
749             return new Promise(r=>{{waiting.set(id,r);{post}(e);}});"
750        ),
751    };
752    let aliases = match transport {
753        // These engines define `window[name]` (or `webkit.messageHandlers[name]`) natively.
754        Transport::WebKit | Transport::Android => "",
755        Transport::WebView2 | Transport::Envelope(_) => {
756            "for(const n of NAMES){if(!(n in window))Object.defineProperty(window,n,{value:Object.freeze({postMessage:t=>{send(n,String(t)).catch(()=>{});}})});}"
757        }
758    };
759    format!(
760        "(()=>{{if(window.dayMessage)return;const NAMES={names};let next=1+Math.floor(Math.random()*1e9);const waiting=new Map();const hooked=new Set();\
761         const settle=(id,v)=>{{const r=waiting.get(id);if(r){{waiting.delete(id);r(v===undefined?null:v);}}}};\
762         Object.defineProperty(window,'__dayMessageReply',{{value:settle}});\
763         const send=(name,text)=>{{{send}}};\
764         Object.defineProperty(window,'dayMessage',{{value:(name,payload)=>{{try{{return send(String(name),payload==null?'':String(payload));}}catch(e){{return Promise.reject(e);}}}}}});\
765         {aliases}}})();"
766    )
767}
768
769/// A script that applies `css` to the document as a `<style>` element: user styles on engines
770/// without a native user style sheet. It runs at document start and adds the element as soon
771/// as the document has a root to add it to.
772pub(crate) fn style_script(css: &str) -> String {
773    let css = crate::js_string_literal(css);
774    format!(
775        "(()=>{{const css={css};const add=()=>{{const r=document.head||document.documentElement;if(!r)return false;\
776         const s=document.createElement('style');s.setAttribute('data-day-user-style','');s.textContent=css;r.appendChild(s);return true;}};\
777         if(!add())document.addEventListener('readystatechange',add,{{once:true}});}})();"
778    )
779}
780
781/// `script` as a script that engines with only "every frame, at document start" injection
782/// (Android's `addDocumentStartJavaScript`, WebView2, ArkWeb) run with its own timing and frames:
783/// a main-frame script returns early in iframes, and a document-end script waits for
784/// `DOMContentLoaded`.
785#[allow(
786    dead_code,
787    reason = "only the Android, WinUI and ArkUI arms lack a native document-start injection"
788)]
789pub(crate) fn document_start_everywhere(script: &UserScript) -> String {
790    let mut source = script.source.to_string();
791    if script.at == InjectAt::DocumentEnd {
792        source = format!(
793            "(()=>{{const run=()=>{{{source}\n}};if(document.readyState==='loading')document.addEventListener('DOMContentLoaded',run,{{once:true}});else run();}})();"
794        );
795    }
796    if script.frames == Frames::Main {
797        source = format!("if(window===window.top){{{source}\n}}");
798    }
799    source
800}
801
802/// The JavaScript that settles request `id` in the top-level document with `reply`, for the
803/// envelope transports.
804#[allow(
805    dead_code,
806    reason = "only the Qt and ArkUI arms answer the page through a script"
807)]
808pub(crate) fn reply_script(id: u64, reply: Option<&str>) -> String {
809    let value = reply.map_or_else(|| "null".to_owned(), crate::js_string_literal);
810    format!("window.__dayMessageReply&&window.__dayMessageReply({id},{value})")
811}
812
813/// A message as a backend reports it on the event channel (`SCRIPT_MESSAGE`): the message and
814/// the id its reply ([`crate::WebPatch::ScriptReply`]) goes back under.
815#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
816pub(crate) struct MessageReport {
817    pub id: u64,
818    #[serde(flatten)]
819    pub message: ScriptMessage,
820}
821
822/// A media request as a backend reports it on the event channel (`MEDIA_REPORT`).
823#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
824pub(crate) struct MediaReport {
825    pub id: u64,
826    #[serde(flatten)]
827    pub request: MediaRequest,
828}
829
830/// Split an envelope a shim posted (`{"dayMessage":name,"id":n,"payload":text}`).
831#[allow(
832    dead_code,
833    reason = "only the Qt and WinUI arms receive messages in an envelope"
834)]
835pub(crate) fn parse_envelope(text: &str) -> Option<(String, u64, String)> {
836    #[derive(serde::Deserialize)]
837    struct Envelope {
838        #[serde(rename = "dayMessage")]
839        name: String,
840        id: u64,
841        #[serde(default)]
842        payload: String,
843    }
844    let envelope: Envelope = serde_json::from_str(text).ok()?;
845    Some((envelope.name, envelope.id, envelope.payload))
846}
847
848/// Whether [`crate::WebView::request_filter`] runs on this build's engine. `Native` where the
849/// engine calls the app for each request (Android `WebView`, WebView2, QtWebEngine, ArkWeb);
850/// WebKit has no such hook (use [`content_rules_support`]), and an iframe sees nothing.
851pub fn request_filter_support() -> Support {
852    if cfg!(any(
853        all(feature = "material", target_os = "android"),
854        all(feature = "xaml", windows),
855        feature = "qt",
856        all(feature = "arkui", target_env = "ohos"),
857    )) {
858        Support::Native
859    } else {
860        Support::Unsupported
861    }
862}
863
864/// Whether [`crate::WebView::on_blocked`] reports anything: wherever the request filter runs.
865pub fn blocked_report_support() -> Support {
866    request_filter_support()
867}
868
869/// Whether [`crate::WebView::content_rules`] applies: the WebKit engines (AppKit, UIKit, GTK on
870/// macOS through `WKWebView`, WebKitGTK on Linux).
871pub fn content_rules_support() -> Support {
872    if cfg!(any(
873        all(
874            any(feature = "appkit", feature = "gtk"),
875            target_os = "macos"
876        ),
877        all(feature = "uikit", target_os = "ios"),
878        all(feature = "gtk", not(target_os = "macos"), not(windows)),
879    )) {
880        Support::Native
881    } else {
882        Support::Unsupported
883    }
884}
885
886/// Whether [`crate::WebView::user_script`] and [`crate::WebView::user_style`] run in pages.
887/// `Emulated` on Android WebViews too old for document-start scripts, which the backend runs
888/// as each page starts instead (main frame only, possibly after the page's first scripts).
889pub fn user_script_support() -> Support {
890    #[cfg(all(feature = "material", target_os = "android"))]
891    if !crate::android_impl::document_start_scripts() {
892        return Support::Emulated;
893    }
894    if cfg!(any(
895        all(
896            any(feature = "appkit", feature = "gtk"),
897            target_os = "macos"
898        ),
899        all(feature = "uikit", target_os = "ios"),
900        all(feature = "gtk", not(target_os = "macos"), not(windows)),
901        all(feature = "material", target_os = "android"),
902        all(feature = "xaml", windows),
903        feature = "qt",
904        all(feature = "arkui", target_env = "ohos"),
905    )) {
906        Support::Native
907    } else {
908        Support::Unsupported
909    }
910}
911
912/// Whether pages can reach [`crate::WebView::on_script_message`] handlers.
913pub fn script_message_support() -> Support {
914    user_script_support()
915}
916
917/// A view's rule-list generations and its held first page load, for the engines that compile
918/// rule lists asynchronously (WebKit, WebKitGTK). Every rule change starts a generation; only
919/// the newest one's completion attaches its lists and releases the load. A superseded compile
920/// that finishes first neither attaches nor loads, so the first page never loads under rules
921/// that are about to be replaced, or none.
922#[derive(Default)]
923// Only the WebKit backends compile rule lists; other builds keep it for its tests.
924#[allow(
925    dead_code,
926    reason = "only the Apple and Linux GTK arms hold loads while rules compile"
927)]
928pub(crate) struct RuleGate {
929    generation: std::cell::Cell<u64>,
930    pending_load: std::cell::RefCell<Option<Box<dyn FnOnce()>>>,
931}
932
933#[allow(
934    dead_code,
935    reason = "only the Apple and Linux GTK arms hold loads while rules compile"
936)]
937impl RuleGate {
938    /// Start a generation for a new set of lists, holding `load` (the first page load) when
939    /// there is one. Returns the generation to hand to [`RuleGate::finish`].
940    pub(crate) fn begin(&self, load: Option<Box<dyn FnOnce()>>) -> u64 {
941        let generation = self.generation.get() + 1;
942        self.generation.set(generation);
943        if let Some(load) = load {
944            *self.pending_load.borrow_mut() = Some(load);
945        }
946        generation
947    }
948
949    /// Whether `generation` is still the newest: only then may its lists attach.
950    pub(crate) fn is_current(&self, generation: u64) -> bool {
951        self.generation.get() == generation
952    }
953
954    /// Whether the first page load is still held for the rule lists.
955    pub(crate) fn is_holding(&self) -> bool {
956        self.pending_load.borrow().is_some()
957    }
958
959    /// A navigation the app asked for (`WebPatch::Load`). While the first page load is held, it
960    /// takes that load's place, so the page the app asked for last is the one that loads, and
961    /// only once the newest rules are attached; `None` then. Otherwise it comes back to run now.
962    pub(crate) fn redirect(&self, load: Box<dyn FnOnce()>) -> Option<Box<dyn FnOnce()>> {
963        let mut pending = self.pending_load.borrow_mut();
964        if pending.is_some() {
965            *pending = Some(load);
966            None
967        } else {
968            Some(load)
969        }
970    }
971
972    /// Release the held load, once `generation`'s lists are attached (or could not be). Does
973    /// nothing for a superseded generation; the newer one releases it.
974    pub(crate) fn finish(&self, generation: u64) {
975        if !self.is_current(generation) {
976            return;
977        }
978        // Taken before the call: the load may change the rules again.
979        let load = self.pending_load.borrow_mut().take();
980        if let Some(load) = load {
981            load();
982        }
983    }
984}
985
986#[cfg(test)]
987mod tests {
988    use super::*;
989
990    #[test]
991    fn every_namespace_form_is_internal() {
992        for url in [
993            "day-resource://p3/ads.css",
994            "https://day-resource.invalid/3/ads.css",
995            "http://day-resource.p3/ads.css",
996        ] {
997            assert!(is_internal(url), "{url}");
998        }
999        for url in [
1000            "http://day-resource.pages.example/ads.css",
1001            "http://day-resource.p/ads.css",
1002            "https://day-resource.p3/ads.css",
1003            "https://news.example/day-resource:",
1004        ] {
1005            assert!(!is_internal(url), "{url}");
1006        }
1007    }
1008
1009    #[test]
1010    fn only_the_newest_rules_release_the_first_load() {
1011        use std::cell::Cell;
1012        use std::rc::Rc;
1013        let gate = RuleGate::default();
1014        let loaded = Rc::new(Cell::new(false));
1015        let first = gate.begin(Some(Box::new({
1016            let loaded = loaded.clone();
1017            move || loaded.set(true)
1018        })));
1019        // New lists arrive before the first compile finishes.
1020        let second = gate.begin(None);
1021        // The superseded compile finishes first: no attach, no load.
1022        assert!(!gate.is_current(first));
1023        gate.finish(first);
1024        assert!(!loaded.get());
1025        // The newest finishes: it attaches and the page loads, once.
1026        assert!(gate.is_current(second));
1027        gate.finish(second);
1028        assert!(loaded.get());
1029        loaded.set(false);
1030        gate.finish(second);
1031        assert!(!loaded.get());
1032    }
1033
1034    #[test]
1035    fn a_navigation_while_held_replaces_the_first_load() {
1036        use std::cell::RefCell;
1037        use std::rc::Rc;
1038        let gate = RuleGate::default();
1039        let page = Rc::new(RefCell::new(Vec::new()));
1040        let load = |name: &'static str| -> Box<dyn FnOnce()> {
1041            let page = page.clone();
1042            Box::new(move || page.borrow_mut().push(name))
1043        };
1044        let generation = gate.begin(Some(load("initial")));
1045        assert!(gate.is_holding());
1046        // Navigations while the rules compile wait, and the last one wins.
1047        assert!(gate.redirect(load("first")).is_none());
1048        assert!(gate.redirect(load("requested")).is_none());
1049        assert!(page.borrow().is_empty());
1050        gate.finish(generation);
1051        assert_eq!(*page.borrow(), ["requested"]);
1052        // Once the page is out, a navigation runs at once.
1053        assert!(!gate.is_holding());
1054        match gate.redirect(load("later")) {
1055            Some(now) => now(),
1056            None => panic!("a navigation after the first load was held"),
1057        }
1058        assert_eq!(*page.borrow(), ["requested", "later"]);
1059    }
1060
1061    #[test]
1062    fn kinds_follow_the_accept_header_then_the_extension() {
1063        let infer = |url, accept| ResourceKind::infer(url, accept, false);
1064        assert_eq!(
1065            ResourceKind::infer("https://a.test/", Some("text/html"), true),
1066            ResourceKind::Document
1067        );
1068        assert_eq!(
1069            infer(
1070                "https://a.test/frame",
1071                Some("text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
1072            ),
1073            ResourceKind::Subdocument
1074        );
1075        assert_eq!(
1076            infer("https://a.test/x?y", Some("text/css,*/*;q=0.1")),
1077            ResourceKind::Stylesheet
1078        );
1079        assert_eq!(
1080            infer("https://a.test/pixel", Some("image/avif,image/webp,*/*")),
1081            ResourceKind::Image
1082        );
1083        // Scripts and fetch send */*: the extension decides, and nothing is a guess.
1084        assert_eq!(
1085            infer("https://ads.test/tag.JS?v=2#x", Some("*/*")),
1086            ResourceKind::Script
1087        );
1088        assert_eq!(infer("https://a.test/font.woff2", None), ResourceKind::Font);
1089        assert_eq!(
1090            infer("https://a.test/clip.m3u8", Some("*/*")),
1091            ResourceKind::Media
1092        );
1093        assert_eq!(
1094            infer("https://a.test/api/feed.json", Some("*/*")),
1095            ResourceKind::Xhr
1096        );
1097        assert_eq!(
1098            infer("https://a.test/api/feed", Some("application/json")),
1099            ResourceKind::Xhr
1100        );
1101        assert_eq!(
1102            infer("https://a.test/collect", Some("*/*")),
1103            ResourceKind::Unknown
1104        );
1105        assert_eq!(infer("https://a.test", None), ResourceKind::Unknown);
1106        assert_eq!(infer("https://a.test/dir.v2/", None), ResourceKind::Unknown);
1107    }
1108
1109    #[test]
1110    fn engine_type_codes_map_to_kinds() {
1111        assert_eq!(ResourceKind::from_chromium(0), ResourceKind::Document);
1112        assert_eq!(ResourceKind::from_chromium(1), ResourceKind::Subdocument);
1113        assert_eq!(ResourceKind::from_chromium(3), ResourceKind::Script);
1114        assert_eq!(ResourceKind::from_chromium(13), ResourceKind::Xhr);
1115        assert_eq!(ResourceKind::from_chromium(21), ResourceKind::WebSocket);
1116        assert_eq!(ResourceKind::from_chromium(255), ResourceKind::Unknown);
1117        assert_eq!(ResourceKind::from_webview2(8), ResourceKind::Fetch);
1118        assert_eq!(ResourceKind::from_webview2(11), ResourceKind::WebSocket);
1119        assert_eq!(ResourceKind::from_webview2(0), ResourceKind::Unknown);
1120    }
1121
1122    #[test]
1123    fn hooks_track_the_top_page_and_never_filter_the_resource_namespace() {
1124        let filter = |request: &RequestInfo<'_>| {
1125            if request.url.contains("ads") || request.url.starts_with("day-resource:") {
1126                RequestDecision::Block
1127            } else {
1128                RequestDecision::Allow
1129            }
1130        };
1131        let sink = Arc::new(BlockedSink::default());
1132        let hooks = RequestHooks::new(Arc::new(filter), Some(sink.clone()), true);
1133        #[expect(
1134            clippy::items_after_statements,
1135            reason = "the helper sits beside the test steps that use it"
1136        )]
1137        fn request(url: &str, kind: ResourceKind, main_frame: bool) -> RequestInfo<'_> {
1138            RequestInfo {
1139                url,
1140                top_url: None,
1141                frame_url: None,
1142                kind,
1143                main_frame,
1144                method: "GET",
1145            }
1146        }
1147        assert_eq!(
1148            hooks.decide(&request("https://news.test/", ResourceKind::Document, true)),
1149            RequestDecision::Allow
1150        );
1151        assert_eq!(hooks.top_url(), "https://news.test/");
1152        assert_eq!(
1153            hooks.decide(&request(
1154                "https://ads.test/a.js",
1155                ResourceKind::Script,
1156                false
1157            )),
1158            RequestDecision::Block
1159        );
1160        assert_eq!(
1161            hooks.decide(&request(
1162                "day-resource://p1/ads.html",
1163                ResourceKind::Subdocument,
1164                false
1165            )),
1166            RequestDecision::Allow
1167        );
1168        // A blocked navigation does not become the page.
1169        assert_eq!(
1170            hooks.decide(&request("https://ads.test/", ResourceKind::Document, true)),
1171            RequestDecision::Block
1172        );
1173        assert_eq!(hooks.top_url(), "https://news.test/");
1174        let loads = sink.take_or_wait().ok().unwrap();
1175        assert_eq!(
1176            loads[0],
1177            BlockedLoad {
1178                url: "https://ads.test/a.js".into(),
1179                page_url: "https://news.test/".into(),
1180                kind: ResourceKind::Script,
1181            }
1182        );
1183        assert_eq!(loads.len(), 2);
1184        assert!(sink.take_or_wait().is_err());
1185        // A view browsing with a provider beside it filters the provider's pages too.
1186        let sees_all = RequestHooks::new(
1187            Arc::new(|r: &RequestInfo<'_>| {
1188                if r.url.contains("ads") {
1189                    RequestDecision::Block
1190                } else {
1191                    RequestDecision::Allow
1192                }
1193            }),
1194            None,
1195            false,
1196        );
1197        assert!(sees_all.filters_internal());
1198        assert_eq!(
1199            sees_all.decide(&request(
1200                "https://day-resource.invalid/p1/https/ads.example/a.js",
1201                ResourceKind::Script,
1202                false
1203            )),
1204            RequestDecision::Block
1205        );
1206        // A panicking filter allows rather than unwinding into the engine.
1207        let panicky = RequestHooks::new(
1208            Arc::new(|_: &RequestInfo<'_>| -> RequestDecision { panic!("filter bug") }),
1209            None,
1210            true,
1211        );
1212        assert_eq!(
1213            panicky.decide(&request("https://x.test/", ResourceKind::Image, false)),
1214            RequestDecision::Allow
1215        );
1216        // Engines call the filter from their own threads.
1217        let workers: Vec<_> = (0..3)
1218            .map(|worker| {
1219                let hooks = hooks.clone();
1220                std::thread::spawn(move || {
1221                    for i in 0..100 {
1222                        let url = format!("https://ads.test/{worker}/{i}.js");
1223                        assert_eq!(
1224                            hooks.decide(&request(&url, ResourceKind::Script, false)),
1225                            RequestDecision::Block
1226                        );
1227                    }
1228                })
1229            })
1230            .collect();
1231        for worker in workers {
1232            worker.join().unwrap();
1233        }
1234        assert_eq!(sink.take_or_wait().ok().map(|loads| loads.len()), Some(300));
1235        let token = register(&hooks);
1236        assert!(hooks_eq(super::hooks(token), &hooks));
1237        unregister(token);
1238        assert!(super::hooks(token).is_none());
1239    }
1240
1241    fn hooks_eq(found: Option<RequestHooks>, hooks: &RequestHooks) -> bool {
1242        found.is_some_and(|found| found == *hooks)
1243    }
1244
1245    #[test]
1246    fn envelopes_round_trip_and_shims_name_their_handlers() {
1247        assert_eq!(
1248            parse_envelope(r#"{"dayMessage":"dayAdblock","id":7,"payload":"{\"a\":1}"}"#),
1249            Some(("dayAdblock".into(), 7, "{\"a\":1}".into()))
1250        );
1251        assert_eq!(parse_envelope("plain text"), None);
1252        let names = vec!["dayAdblock".to_owned()];
1253        for transport in [
1254            Transport::WebKit,
1255            Transport::Android,
1256            Transport::WebView2,
1257            Transport::Envelope("console.debug"),
1258        ] {
1259            let shim = message_shim(transport, &names);
1260            assert!(shim.contains("\"dayAdblock\""), "{shim}");
1261            assert!(
1262                shim.starts_with("(()=>{") && shim.ends_with("})();"),
1263                "{shim}"
1264            );
1265        }
1266        assert_eq!(
1267            reply_script(3, None),
1268            "window.__dayMessageReply&&window.__dayMessageReply(3,null)"
1269        );
1270        assert!(reply_script(3, Some("a\"b")).ends_with("(3,\"a\\\"b\")"));
1271        assert!(style_script("a{b:'c'}\n").contains("\"a{b:'c'}\\n\""));
1272    }
1273}