lingxia-webview 0.11.1

WebView abstraction layer for LingXia framework (Android, iOS, HarmonyOS, Windows)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
use crate::{LogLevel, WebViewError, WebViewInputError, WebViewScriptError};
use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use std::future::Future;
use std::path::PathBuf;
use std::pin::Pin;
use std::sync::Arc;

/// Outcome of handling a scheme request.
#[derive(Debug)]
pub enum SchemeOutcome {
    /// Handler produced a response.
    Handled(WebResourceResponse),
    /// Handler intentionally declined the request.
    PassThrough,
}

/// Async scheme handler signature.
pub(crate) type AsyncSchemeFuture = Pin<Box<dyn Future<Output = SchemeOutcome> + Send + 'static>>;
pub(crate) type AsyncSchemeHandler =
    Arc<dyn Fn(http::Request<Vec<u8>>) -> AsyncSchemeFuture + Send + Sync>;

/// Navigation policy decision returned by the navigation handler.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum NavigationPolicy {
    /// Allow the WebView to navigate to this URL.
    Allow,
    /// Cancel the navigation. The handler is responsible for any side effects
    /// (e.g., opening the URL externally via `AppRuntime::open_url()`).
    Cancel,
}

/// A platform navigation request passed to the registered policy handler.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct NavigationRequest {
    pub url: String,
    pub has_user_gesture: bool,
    pub is_main_frame: bool,
}

impl NavigationRequest {
    pub fn new(url: impl Into<String>, has_user_gesture: bool, is_main_frame: bool) -> Self {
        Self {
            url: url.into(),
            has_user_gesture,
            is_main_frame,
        }
    }
}

/// New-window policy decision returned by the new-window handler.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum NewWindowPolicy {
    /// Load the URL in the current WebView (replaces current page).
    LoadInSelf,
    /// Cancel the new-window request without doing anything.
    Cancel,
}

pub type NavigationHandler = Box<dyn Fn(&NavigationRequest) -> NavigationPolicy + Send + Sync>;
pub type NewWindowHandler = Box<dyn Fn(&str) -> NewWindowPolicy + Send + Sync>;

/// Per-WebView user-agent override.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum UserAgentOverride {
    /// Restore the user agent supplied by the platform WebView engine.
    Default,
    /// Replace the complete user-agent string. The value must be non-empty and
    /// engine-compatible. This does not emulate other browser capabilities or
    /// synchronize User-Agent Client Hints.
    Custom(String),
}

impl UserAgentOverride {
    pub(crate) fn validate(&self) -> Result<(), WebViewError> {
        if let Self::Custom(value) = self
            && value.trim().is_empty()
        {
            return Err(WebViewError::WebView(
                "custom user-agent override must not be empty".to_string(),
            ));
        }
        Ok(())
    }
}

#[cfg(test)]
mod user_agent_override_tests {
    use super::*;

    #[test]
    fn custom_user_agent_must_not_be_blank() {
        assert!(UserAgentOverride::Custom(String::new()).validate().is_err());
        assert!(UserAgentOverride::Custom("   ".into()).validate().is_err());
        assert!(
            UserAgentOverride::Custom("Mozilla/5.0 valid".into())
                .validate()
                .is_ok()
        );
        assert!(UserAgentOverride::Default.validate().is_ok());
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DownloadRequest {
    /// Final download URL reported by the platform callback.
    pub url: String,
    /// Request user-agent if available on this platform.
    pub user_agent: Option<String>,
    /// `Content-Disposition` response header if exposed by the platform.
    pub content_disposition: Option<String>,
    /// Response MIME type if exposed by the platform.
    pub mime_type: Option<String>,
    /// Response content length if known.
    pub content_length: Option<u64>,
    /// Platform-suggested filename (may be absent).
    pub suggested_filename: Option<String>,
    /// Source page URL that initiated the download when available.
    pub source_page_url: Option<String>,
    /// Cookie header string for `url` when available.
    pub cookie: Option<String>,
}

/// Download callback.
///
/// In browser profile, registering this callback makes download requests flow through the host
/// app callback path instead of in-WebView download UI.
pub type DownloadHandler = Box<dyn Fn(DownloadRequest) + Send + Sync>;

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum WebViewCookieSameSite {
    Lax,
    Strict,
    None,
}

impl WebViewCookieSameSite {
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Lax => "lax",
            Self::Strict => "strict",
            Self::None => "none",
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct WebViewCookie {
    pub name: String,
    pub value: String,
    pub domain: String,
    pub path: String,
    #[serde(default, skip_serializing_if = "is_false")]
    pub host_only: bool,
    #[serde(default)]
    pub secure: bool,
    #[serde(default)]
    pub http_only: bool,
    #[serde(default)]
    pub session: bool,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub expires_unix_ms: Option<i64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub same_site: Option<WebViewCookieSameSite>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct WebViewCookieSetRequest {
    #[serde(default)]
    pub url: String,
    pub name: String,
    pub value: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub domain: Option<String>,
    #[serde(default = "default_cookie_path")]
    pub path: String,
    #[serde(default)]
    pub secure: bool,
    #[serde(default)]
    pub http_only: bool,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub expires_unix_ms: Option<i64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub same_site: Option<WebViewCookieSameSite>,
}

fn default_cookie_path() -> String {
    "/".to_string()
}

fn is_false(value: &bool) -> bool {
    !*value
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FileChooserRequest {
    /// Accepted MIME types / extensions requested by the page.
    pub accept_types: Vec<String>,
    /// Whether multiple files may be selected.
    pub allow_multiple: bool,
    /// Whether directories may be selected.
    pub allow_directories: bool,
    /// Whether the page requested capture/live media.
    pub capture: bool,
    /// Source page URL that initiated the chooser when available.
    pub source_page_url: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FileChooserFile {
    pub path: Option<String>,
    pub uri: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum FileChooserResponse {
    Cancel,
    Error(String),
    Files(Vec<FileChooserFile>),
}

/// Body source for WebResourceResponse
#[derive(Debug)]
pub enum WebResourceBody {
    /// Serve data from a regular file path on disk
    Path(PathBuf),
    /// Serve data from a system pipe (read end)
    Pipe(SystemPipeReader),
    /// Serve data directly from memory
    Bytes(Vec<u8>),
}

/// Cross‑platform system pipe reader (read end)
#[derive(Debug)]
pub struct SystemPipeReader {
    #[cfg(unix)]
    fd: std::os::fd::RawFd,
    #[cfg(windows)]
    handle: std::os::windows::io::RawHandle,
}

impl SystemPipeReader {
    /// Consume and return the raw file descriptor (Unix).
    /// Caller becomes responsible for closing it.
    #[cfg(unix)]
    pub fn into_raw_fd(self) -> std::os::fd::RawFd {
        self.fd
    }

    /// Construct from a raw file descriptor (Unix).
    ///
    /// # Safety
    ///
    /// Caller guarantees that `fd` is a valid read end of a pipe file descriptor.
    #[cfg(unix)]
    pub unsafe fn from_raw_fd(fd: std::os::fd::RawFd) -> Self {
        Self { fd }
    }

    /// Convert into a File for reading (consumes self).
    #[cfg(unix)]
    pub fn into_file(self) -> std::fs::File {
        use std::os::fd::FromRawFd;
        unsafe { std::fs::File::from_raw_fd(self.into_raw_fd()) }
    }

    /// Consume and return the raw handle (Windows).
    /// Caller becomes responsible for closing it.
    #[cfg(windows)]
    pub fn into_raw_handle(self) -> std::os::windows::io::RawHandle {
        self.handle
    }

    /// Construct from a raw handle (Windows).
    ///
    /// # Safety
    ///
    /// Caller guarantees that `handle` is a valid readable OS handle.
    #[cfg(windows)]
    pub unsafe fn from_raw_handle(handle: std::os::windows::io::RawHandle) -> Self {
        Self { handle }
    }

    /// Convert into a File for reading (consumes self).
    #[cfg(windows)]
    pub fn into_file(self) -> std::fs::File {
        use std::os::windows::io::FromRawHandle;
        unsafe { std::fs::File::from_raw_handle(self.into_raw_handle()) }
    }
}

/// Interface for controlling WebView (100% copy from lxapp)
#[async_trait]
pub trait WebViewController: Send + Sync {
    /// Load a URL in the WebView
    fn load_url(&self, url: &str) -> Result<(), WebViewError>;

    /// Load HTML data into the WebView.
    fn load_data(&self, request: LoadDataRequest<'_>) -> Result<(), WebViewError>;

    /// Execute JavaScript in the WebView without observing its return value.
    fn exec_js(&self, js: &str) -> Result<(), WebViewError>;

    /// Evaluate JavaScript in the WebView and return the decoded JSON value.
    ///
    /// Implementations are required to be both CSP-safe (no `(0,eval)` /
    /// `new Function` — pages whose CSP omits `'unsafe-eval'` must still
    /// work) and `await`-aware (top-level `await` in the user expression
    /// resolves before the future returns). Platforms achieve this by
    /// dispatching through the native await-capable API
    /// (`callAsyncJavaScript:` on Apple, `LingXiaProxy.resolveEval` JS
    /// bridge on Android/Harmony).
    async fn eval_js(&self, js: &str) -> Result<serde_json::Value, WebViewScriptError>;

    /// Return the platform WebView's current URL.
    async fn current_url(&self) -> Result<Option<String>, WebViewError> {
        Err(WebViewError::WebView(
            "current_url is not implemented for this platform".to_string(),
        ))
    }

    /// Post a message to the WebView
    fn post_message(&self, message: &str) -> Result<(), WebViewError>;

    /// Clear browsing data from the WebView
    fn clear_browsing_data(&self) -> Result<(), WebViewError>;

    /// Override or restore the WebView user agent.
    fn set_user_agent_override(&self, user_agent: UserAgentOverride) -> Result<(), WebViewError>;

    /// Reload the current WebView document.
    fn reload(&self) -> Result<(), WebViewError> {
        Err(WebViewError::WebView(
            "reload is not implemented for this platform".to_string(),
        ))
    }

    /// Navigate back in WebView history.
    fn go_back(&self) -> Result<(), WebViewError> {
        Err(WebViewError::WebView(
            "go_back is not implemented for this platform".to_string(),
        ))
    }

    /// Navigate forward in WebView history.
    fn go_forward(&self) -> Result<(), WebViewError> {
        Err(WebViewError::WebView(
            "go_forward is not implemented for this platform".to_string(),
        ))
    }

    /// List HTTP cookies from the platform WebView cookie store.
    async fn list_cookies(&self) -> Result<Vec<WebViewCookie>, WebViewError> {
        Err(WebViewError::WebView(
            "cookie store is not implemented for this platform".to_string(),
        ))
    }

    /// Set an HTTP cookie through the platform WebView cookie store.
    async fn set_cookie(&self, _request: WebViewCookieSetRequest) -> Result<(), WebViewError> {
        Err(WebViewError::WebView(
            "cookie store is not implemented for this platform".to_string(),
        ))
    }

    /// Delete an HTTP cookie from the platform WebView cookie store.
    async fn delete_cookie(
        &self,
        _name: &str,
        _domain: &str,
        _path: &str,
    ) -> Result<(), WebViewError> {
        Err(WebViewError::WebView(
            "cookie store is not implemented for this platform".to_string(),
        ))
    }

    /// Clear all HTTP cookies from the platform WebView cookie store.
    async fn clear_cookies(&self) -> Result<(), WebViewError> {
        Err(WebViewError::WebView(
            "cookie store is not implemented for this platform".to_string(),
        ))
    }

    /// Clear data owned by the current website without clearing the shared
    /// browser profile. Platforms report whether their network cache supports
    /// site-scoped removal.
    async fn clear_site_data(
        &self,
        _url: &str,
        _options: ClearSiteDataOptions,
    ) -> Result<ClearSiteDataResult, WebViewError> {
        Err(WebViewError::WebView(
            "site-scoped data clearing is not implemented for this platform".to_string(),
        ))
    }

    /// Capture a PNG screenshot of the WebView's visible content.
    /// Returns raw PNG-encoded bytes ready to be base64'd over the wire.
    async fn take_screenshot(&self) -> Result<Vec<u8>, WebViewError> {
        Err(WebViewError::WebView(
            "screenshot is not implemented for this platform".to_string(),
        ))
    }

    /// Begin recording network requests/responses into a bounded per-webview
    /// buffer, retrievable via [`Self::network_entries`]. Dev-tooling only;
    /// implemented on platforms whose WebView exposes an inspection protocol
    /// (currently Windows/WebView2 via the Chrome DevTools Protocol).
    async fn start_network_capture(&self) -> Result<(), WebViewError> {
        Err(WebViewError::WebView(
            "network capture is not implemented for this platform".to_string(),
        ))
    }

    /// Stop recording network traffic. Captured entries are kept until
    /// [`Self::clear_network_capture`] or the webview is torn down.
    async fn stop_network_capture(&self) -> Result<(), WebViewError> {
        Err(WebViewError::WebView(
            "network capture is not implemented for this platform".to_string(),
        ))
    }

    /// Snapshot the captured network entries (oldest first). `dropped` counts
    /// entries evicted from the ring buffer since the last clear.
    async fn network_entries(&self) -> Result<NetworkCaptureSnapshot, WebViewError> {
        Err(WebViewError::WebView(
            "network capture is not implemented for this platform".to_string(),
        ))
    }

    /// Drop all captured entries (leaves capture enabled if it was on).
    async fn clear_network_capture(&self) -> Result<(), WebViewError> {
        Err(WebViewError::WebView(
            "network capture is not implemented for this platform".to_string(),
        ))
    }
}

/// Data categories to remove for one site via
/// [`WebViewController::clear_site_data`].
#[derive(Debug, Clone, Copy)]
pub struct ClearSiteDataOptions {
    pub cache: bool,
    pub site_data: bool,
}

/// Outcome of [`WebViewController::clear_site_data`]. Each flag means "this
/// category was requested AND the platform fully honored it" — `false` both
/// when the category was not requested and when it could not be fully cleared.
///
/// Windows caveat: WebView2 clears the site's Cache Storage/appcache but
/// cannot site-scope the shared HTTP cache, so it reports
/// `cache_cleared: false` even when cache clearing was requested.
#[derive(Debug, Clone, Copy)]
pub struct ClearSiteDataResult {
    pub cache_cleared: bool,
    pub site_data_cleared: bool,
}

/// One captured network request and its response (when it completed).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NetworkEntry {
    /// Protocol request id, stable across the request/response events.
    pub request_id: String,
    pub url: String,
    pub method: String,
    /// Resource kind reported by the engine (document, xhr, fetch, script,
    /// image, ...), when available.
    pub resource_type: Option<String>,
    pub request_headers: Vec<(String, String)>,
    /// Request payload (POST body) as reported by the engine, when present.
    pub request_body: Option<String>,
    pub status: Option<u16>,
    pub response_headers: Vec<(String, String)>,
    pub mime_type: Option<String>,
    pub response_body: NetworkBody,
    pub from_cache: bool,
    /// Populated when the request failed (engine error text) instead of
    /// producing a response.
    pub failed: Option<String>,
    /// Wall-clock start time (Unix epoch seconds), when the engine reports it.
    pub wall_time: Option<f64>,
    /// Monotonic engine timestamps (seconds), for ordering and durations.
    pub started: f64,
    pub finished: Option<f64>,
}

impl NetworkEntry {
    /// Request duration in milliseconds, once the response has completed.
    pub fn duration_ms(&self) -> Option<f64> {
        self.finished
            .filter(|finished| *finished >= self.started)
            .map(|finished| (finished - self.started) * 1000.0)
    }
}

/// Response body of a captured entry.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum NetworkBody {
    /// No body captured yet (in flight) or the response had none.
    #[default]
    None,
    /// UTF-8 text body.
    Text { text: String },
    /// Base64-encoded binary body.
    Base64 { base64: String },
    /// Body deliberately not captured (e.g. over the size cap, or evicted
    /// before it could be read); `reason` says which.
    Skipped { reason: String },
}

/// A point-in-time view of the capture buffer.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct NetworkCaptureSnapshot {
    pub entries: Vec<NetworkEntry>,
    /// Entries evicted from the ring buffer since the last clear (buffer
    /// full). Surfaced so truncation is never silent.
    pub dropped: u64,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct ClickOptions {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub index: Option<usize>,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct TypeOptions {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub index: Option<usize>,
    #[serde(default)]
    pub replace: bool,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct FillOptions {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub index: Option<usize>,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct PressOptions {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub selector: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub index: Option<usize>,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct ScrollOptions;

#[async_trait]
pub trait WebViewInputController: WebViewController {
    async fn click(
        &self,
        _selector: &str,
        _options: ClickOptions,
    ) -> Result<(), WebViewInputError> {
        Err(WebViewInputError::Unsupported(
            "input control is not implemented for this platform",
        ))
    }

    async fn type_text(
        &self,
        _selector: &str,
        _text: &str,
        _options: TypeOptions,
    ) -> Result<(), WebViewInputError> {
        Err(WebViewInputError::Unsupported(
            "input control is not implemented for this platform",
        ))
    }

    async fn fill(
        &self,
        _selector: &str,
        _text: &str,
        _options: FillOptions,
    ) -> Result<(), WebViewInputError> {
        Err(WebViewInputError::Unsupported(
            "input control is not implemented for this platform",
        ))
    }

    async fn press(&self, _key: &str, _options: PressOptions) -> Result<(), WebViewInputError> {
        Err(WebViewInputError::Unsupported(
            "input control is not implemented for this platform",
        ))
    }

    async fn scroll(
        &self,
        _dx: f64,
        _dy: f64,
        _options: ScrollOptions,
    ) -> Result<(), WebViewInputError> {
        Err(WebViewInputError::Unsupported(
            "input control is not implemented for this platform",
        ))
    }

    async fn scroll_to(
        &self,
        _selector: &str,
        _options: ScrollOptions,
    ) -> Result<(), WebViewInputError> {
        Err(WebViewInputError::Unsupported(
            "input control is not implemented for this platform",
        ))
    }
}

#[derive(Debug, Clone, Copy)]
pub struct LoadDataRequest<'a> {
    pub data: &'a str,
    pub base_url: &'a str,
    pub history_url: Option<&'a str>,
}

impl<'a> LoadDataRequest<'a> {
    pub fn new(data: &'a str, base_url: &'a str) -> Self {
        Self {
            data,
            base_url,
            history_url: None,
        }
    }

    pub fn with_history_url(mut self, history_url: &'a str) -> Self {
        self.history_url = Some(history_url);
        self
    }
}

/// Normalized category for a main-frame page load failure.
///
/// Cancellation is deliberately not a kind: a cancelled navigation is control
/// flow and terminates as `NavigationEvent::Cancelled`, never as a load error.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LoadErrorKind {
    Dns,
    Network,
    Timeout,
    Security,
    InvalidUrl,
    NotFound,
    Unknown,
}

/// Error reported when a main-frame page load fails (DNS, network, TLS, etc.).
///
/// `kind` is the stable value for program logic; `description` is platform
/// diagnostic text for logs and must not be parsed or shown directly as
/// localized product copy.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LoadError {
    /// URL that failed to load, if the platform exposes it.
    pub failing_url: Option<String>,
    /// Cross-platform error category for application logic and UI.
    pub kind: LoadErrorKind,
    /// Human-readable description from the platform.
    pub description: String,
}

/// WebView delegate: typed navigation lifecycle, observable state, page
/// messaging, and logging for one WebView. Exactly one owner per WebView
/// (an lxapp `PageInstance` or a browser tab delegate); read-only watchers
/// use [`crate::events::normalizer::add_observer`]-registered observers.
///
/// Delivery contract (enforced by the event normalizer):
/// - events arrive by value, serially, synchronously on the submitting
///   thread, flattened FIFO — a callback is never re-entered for the same
///   WebView;
/// - callbacks may arrive on the WebView's own UI thread; fire-and-forget
///   commands (`exec_js`) are safe there, but result-awaiting APIs must not
///   block the callback thread;
/// - every `Started` gets exactly one terminal event; success owns a
///   non-empty final URL; cancellation is control flow, never a load error;
/// - state changes are snapshots, not lifecycle: `Location` alone is never
///   evidence of a successful visit, and `None` clears title/favicon.
///
/// Fold navigation through [`crate::events::NavigationProgress`] and state
/// through [`crate::events::ObservedWebViewState`] instead of hand-rolling
/// attempt correlation:
///
/// ```ignore
/// fn on_navigation_event(&self, event: NavigationEvent) {
///     let mut progress = self.progress.lock().unwrap();
///     progress.apply(&event);
///     if let NavigationEvent::Succeeded { id, final_url } = &event
///         && progress.is_current(*id)
///     {
///         self.loaded(final_url);
///     }
/// }
/// ```
pub trait WebViewDelegate: Send + Sync {
    /// One correlated top-level navigation lifecycle event.
    ///
    /// Required: after the typed-event migration every delegate must decide
    /// how it handles the lifecycle — a silent default would lose page loads.
    fn on_navigation_event(&self, event: crate::events::NavigationEvent);

    /// One observable-state snapshot (location, title, favicon,
    /// back/forward availability), coalesced and generation-scoped by the
    /// normalizer.
    fn on_webview_state_change(&self, _change: crate::events::WebViewStateChange) {}

    /// Handles a postMessage from the page View(WebView)
    fn handle_post_message(&self, msg: String);

    /// Handles a native-component message posted by the page through the
    /// embedded-component channel (`window.NativeComponentBridge`), where
    /// the platform routes it in-process (currently Windows/WebView2).
    /// `message_json` is the raw component message (`component.mount`,
    /// `component.update`, ...).
    fn handle_native_component_message(&self, _message_json: String) {}

    /// Receive log from WebView
    fn log(&self, level: LogLevel, message: &str);
}

/// Represents an HTTP response whose body is provided by a file path, pipe, or in-memory bytes.
#[derive(Debug)]
pub struct WebResourceResponse {
    parts: http::response::Parts,
    body: WebResourceBody,
}

impl From<Option<WebResourceResponse>> for SchemeOutcome {
    fn from(value: Option<WebResourceResponse>) -> Self {
        match value {
            Some(response) => SchemeOutcome::Handled(response),
            None => SchemeOutcome::PassThrough,
        }
    }
}

impl WebResourceResponse {
    /// Borrow the response parts (status, headers, etc.).
    pub fn parts(&self) -> &http::response::Parts {
        &self.parts
    }

    /// Consume the struct and return the owned parts and file path.
    pub fn into_parts(self) -> (http::response::Parts, WebResourceBody) {
        (self.parts, self.body)
    }
}

/// Convenience conversion from (Parts, PathBuf)
impl From<(http::response::Parts, PathBuf)> for WebResourceResponse {
    fn from(value: (http::response::Parts, PathBuf)) -> Self {
        WebResourceResponse {
            parts: value.0,
            body: WebResourceBody::Path(value.1),
        }
    }
}

/// Convenience conversion from (Parts, SystemPipeReader)
impl From<(http::response::Parts, SystemPipeReader)> for WebResourceResponse {
    fn from(value: (http::response::Parts, SystemPipeReader)) -> Self {
        WebResourceResponse {
            parts: value.0,
            body: WebResourceBody::Pipe(value.1),
        }
    }
}

/// Convenience conversion from (Parts, Vec<u8>)
impl From<(http::response::Parts, Vec<u8>)> for WebResourceResponse {
    fn from(value: (http::response::Parts, Vec<u8>)) -> Self {
        WebResourceResponse {
            parts: value.0,
            body: WebResourceBody::Bytes(value.1),
        }
    }
}

impl WebResourceResponse {
    fn response_parts_with_status(status: u16) -> http::response::Parts {
        let response = match http::Response::builder().status(status).body(()) {
            Ok(response) => response,
            Err(_) => http::Response::new(()),
        };
        let (parts, _) = response.into_parts();
        parts
    }

    /// Create a response serving a file from disk (status 200).
    pub fn file(path: impl Into<PathBuf>) -> Self {
        let path = path.into();
        let content_length = std::fs::metadata(&path).ok().map(|m| m.len());
        let mut parts = Self::response_parts_with_status(200);
        if let Some(len) = content_length {
            parts
                .headers
                .insert(http::header::CONTENT_LENGTH, http::HeaderValue::from(len));
        }
        Self {
            parts,
            body: WebResourceBody::Path(path),
        }
    }

    /// Create a response serving in-memory bytes (status 200).
    pub fn bytes(data: impl Into<Vec<u8>>) -> Self {
        let data = data.into();
        let len = data.len();
        let mut parts = Self::response_parts_with_status(200);
        parts
            .headers
            .insert(http::header::CONTENT_LENGTH, http::HeaderValue::from(len));
        Self {
            parts,
            body: WebResourceBody::Bytes(data),
        }
    }

    /// Create a response serving data from a system pipe (status 200).
    pub fn stream(reader: SystemPipeReader) -> Self {
        let parts = Self::response_parts_with_status(200);
        Self {
            parts,
            body: WebResourceBody::Pipe(reader),
        }
    }

    /// Set the Content-Type header (builder pattern).
    pub fn mime(mut self, content_type: &str) -> Self {
        if let Ok(value) = http::HeaderValue::from_str(content_type) {
            self.parts.headers.insert(http::header::CONTENT_TYPE, value);
        }
        self
    }

    /// Set the HTTP status code (builder pattern).
    pub fn status(mut self, code: u16) -> Self {
        self.parts.status = http::StatusCode::from_u16(code).unwrap_or(self.parts.status);
        self
    }

    /// Add a response header (builder pattern).
    pub fn header(mut self, name: &str, value: &str) -> Self {
        if let (Ok(header_name), Ok(header_value)) = (
            name.parse::<http::header::HeaderName>(),
            http::HeaderValue::from_str(value),
        ) {
            self.parts.headers.insert(header_name, header_value);
        }
        self
    }

    /// Add CORS header `Access-Control-Allow-Origin: null` (builder pattern).
    pub fn cors(self) -> Self {
        self.header("access-control-allow-origin", "null")
    }
}