fauna-api 1.0.859

The Fauna SDK for Rust: accounts, Drive, groups, calendar, chats, payments, Parrot and live rooms.
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
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
//! Marmot-owned live web-room client: HTTP bootstrap/assets, CSS and asset URL
//! rewriting, and the WebRoom socket. DOM capture and replay stay in the
//! TypeScript SDK, which runs in the page.

use std::collections::{BTreeMap, HashMap};
use std::ops::Deref;
use std::sync::{Arc, Mutex, MutexGuard, PoisonError, RwLock};
use std::time::Duration;

use base64::Engine;
use base64::engine::general_purpose::STANDARD;
use futures_util::StreamExt;
use futures_util::future::BoxFuture;
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value, json};
use tokio::sync::oneshot;

use crate::authentification::CredentialsOrApiKey;
use crate::drive::Progress;
use crate::error::{Error, Result};
use crate::http::{client, ok, progress_body};
use crate::shared::server::{Authorization, Hooks, Presence, Room, connect};

/// A single serialized DOM node. `id` is a synthetic stable key assigned by the
/// recorder; it is NOT the element's DOM id attribute.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "lowercase")]
pub enum WebNode {
    Element {
        id: u64,
        tag: String,
        #[serde(default)]
        attributes: BTreeMap<String, String>,
        #[serde(default)]
        children: Vec<u64>,
    },
    Text {
        id: u64,
        #[serde(default)]
        text: String,
    },
}

/// `{ width, height }` in the TypeScript SDK.
#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize, Deserialize)]
pub struct WebViewport {
    pub width: f64,
    pub height: f64,
}

/// A full document snapshot: the root node id plus every node reachable from
/// it, flattened into an id->node map for O(1) patching on the viewer.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct WebSnapshot {
    pub root: u64,
    pub nodes: HashMap<u64, WebNode>,
    /// Viewport the host captured at (viewers use it only for reference; they
    /// render at their own size).
    pub viewport: WebViewport,
}

/// An incremental change to a previously-snapshotted tree.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "lowercase")]
pub enum WebMutation {
    Insert {
        parent: u64,
        node: WebNode,
        #[serde(default)]
        subtree: Vec<WebNode>,
        before: Option<u64>,
    },
    Remove {
        id: u64,
    },
    Text {
        id: u64,
        text: String,
    },
    Attribute {
        id: u64,
        name: String,
        value: Option<String>,
    },
    /// The host's viewport changed. Viewers may use this to hint responsive
    /// re-layout, but are never forced to match the host's dimensions.
    Viewport {
        width: f64,
        height: f64,
    },
}

/// Agent or host pointer. Sibling of WebMutation, not a DOM change.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct HtmlPointer {
    pub x: f64,
    pub y: f64,
    #[serde(default)]
    pub scroll_x: f64,
    #[serde(default)]
    pub scroll_y: f64,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub visible: Option<bool>,
    /// The CSS cursor under the pointer (`pointer`, `text`, `nwse-resize`...), `default` for `auto`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub shape: Option<String>,
}

/// Placeholder scheme rewritten into guest blob: URLs after asset download.
pub const WEB_ASSET_SCHEME: &str = "fauna-web-asset:";

/// `{ data, contentType }` in the TypeScript SDK: fetched bytes and their type.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FetchedMedia {
    pub data: Vec<u8>,
    pub content_type: String,
}

/// Optional privileged fetcher (extension background).
pub type MediaFetcher =
    Arc<dyn Fn(String) -> BoxFuture<'static, Option<FetchedMedia>> + Send + Sync>;

static MEDIA_FETCHER: RwLock<Option<MediaFetcher>> = RwLock::new(None);

/// Install a privileged media fetcher.
pub fn set_media_fetcher(fetcher: Option<MediaFetcher>) {
    *MEDIA_FETCHER
        .write()
        .unwrap_or_else(PoisonError::into_inner) = fetcher;
}

fn consider_url(raw: Option<&str>, into: &mut Vec<String>) {
    let Some(raw) = raw else {
        return;
    };
    let trimmed = raw.trim();
    if trimmed.is_empty()
        || trimmed.starts_with(WEB_ASSET_SCHEME)
        || trimmed.starts_with("javascript:")
    {
        return;
    }
    if trimmed.starts_with('#') || trimmed.starts_with("mailto:") || trimmed.starts_with("tel:") {
        return;
    }
    if trimmed.starts_with("blob:") {
        return;
    }
    // Leave data: URIs inline. Harvesting them is unnecessary (already self-
    // contained) and a naive url() scan can truncate SVG data URIs at the
    // first quote/paren, then rewrite the prefix and leave a base64 tail that
    // the browser fetches as a relative path.
    if trimmed.starts_with("data:") {
        return;
    }
    if !into.iter().any(|known| known == trimmed) {
        into.push(trimmed.to_string());
    }
}

fn find_ignore_case(haystack: &str, needle: &str, from: usize) -> Option<usize> {
    let bytes = haystack.as_bytes();
    let needle = needle.as_bytes();
    (from..=bytes.len().saturating_sub(needle.len())).find(|&index| {
        bytes.len() >= index + needle.len()
            && bytes[index..index + needle.len()].eq_ignore_ascii_case(needle)
    })
}

fn skip_whitespace(text: &str, mut index: usize) -> usize {
    while let Some(c) = text[index..].chars().next() {
        if !c.is_whitespace() {
            break;
        }
        index += c.len_utf8();
    }
    index
}

/// Walk `url(...)` tokens in CSS. Quoted values may contain `)` / quotes that
/// would break a naive character class (common in SVG data URIs).
fn for_each_css_url_token(css: &str, mut visit: impl FnMut(&str, &str, usize, usize)) {
    let mut from = 0;
    while let Some(start) = find_ignore_case(css, "url(", from) {
        let i = skip_whitespace(css, start + 4);
        if i >= css.len() {
            break;
        }
        let first = css.as_bytes()[i];
        if first == b'"' || first == b'\'' {
            let quote = if first == b'"' { "\"" } else { "'" };
            let begin = i + 1;
            let Some(close_quote) = css[begin..].find(quote).map(|offset| begin + offset) else {
                break;
            };
            let Some(close_paren) = css[close_quote + 1..]
                .find(')')
                .map(|offset| close_quote + 1 + offset)
            else {
                break;
            };
            visit(&css[begin..close_quote], quote, start, close_paren + 1);
            from = close_paren + 1;
            continue;
        }
        let Some(close_paren) = css[i..].find(')').map(|offset| i + offset) else {
            break;
        };
        visit(css[i..close_paren].trim(), "", start, close_paren + 1);
        from = close_paren + 1;
    }
}

/// One `@import url(...)` or `@import "..."` rule: its start, end and target.
fn next_import(css: &str, mut from: usize) -> Option<(usize, usize, String)> {
    while let Some(start) = find_ignore_case(css, "@import", from) {
        from = start + 1;
        let after = start + "@import".len();
        let i = skip_whitespace(css, after);
        if i == after {
            continue;
        }
        let bytes = css.as_bytes();
        let mut target = None;
        let mut end = i;
        if find_ignore_case(css, "url(", i) == Some(i) {
            let j = skip_whitespace(css, i + 4);
            let quote = bytes.get(j).copied().filter(|c| *c == b'"' || *c == b'\'');
            let begin = if quote.is_some() { j + 1 } else { j };
            let stop = css[begin..]
                .find(['\'', '"', ')'])
                .map_or(css.len(), |offset| begin + offset);
            if stop > begin {
                let mut k = stop;
                let closed = match quote {
                    Some(quote) => {
                        bytes.get(k) == Some(&quote) && {
                            k += 1;
                            true
                        }
                    }
                    None => true,
                };
                if closed {
                    let k = skip_whitespace(css, k);
                    if bytes.get(k) == Some(&b')') {
                        target = Some(css[begin..stop].to_string());
                        end = k + 1;
                    }
                }
            }
        } else if let Some(&quote) = bytes.get(i).filter(|c| **c == b'"' || **c == b'\'') {
            let begin = i + 1;
            if let Some(stop) = css[begin..].find(['\'', '"']).map(|offset| begin + offset)
                && stop > begin
                && bytes[stop] == quote
            {
                target = Some(css[begin..stop].to_string());
                end = stop + 1;
            }
        }
        let Some(target) = target else {
            continue;
        };
        let mut end = skip_whitespace(css, end);
        if bytes.get(end) == Some(&b';') {
            end += 1;
        }
        return Some((start, end, target));
    }
    None
}

/// Pull url(...) and @import targets out of CSS text (preserves @media as-is).
pub fn extract_css_urls(css: &str) -> Vec<String> {
    let mut found = Vec::new();
    for_each_css_url_token(css, |raw, _, _, _| consider_url(Some(raw), &mut found));
    let mut from = 0;
    while let Some((_, end, target)) = next_import(css, from) {
        consider_url(Some(&target), &mut found);
        from = end;
    }
    found
}

/// Rewrite url()/ @import targets in CSS using fauna-web-asset codes.
pub fn rewrite_css_urls(css: &str, map: &HashMap<String, String>) -> String {
    let mut out = String::new();
    let mut cursor = 0;
    for_each_css_url_token(css, |raw, quote, start, end| {
        out.push_str(&css[cursor..start]);
        match map.get(raw.trim()) {
            None => out.push_str(&css[start..end]),
            Some(code) => out.push_str(&format!("url({quote}{WEB_ASSET_SCHEME}{code}{quote})")),
        }
        cursor = end;
    });
    out.push_str(&css[cursor..]);

    let mut rewritten = String::new();
    let mut cursor = 0;
    while let Some((start, end, target)) = next_import(&out, cursor) {
        rewritten.push_str(&out[cursor..start]);
        let trimmed = target.trim();
        match map.get(trimmed) {
            Some(code) if !trimmed.starts_with("data:") => {
                rewritten.push_str(&format!("@import url(\"{WEB_ASSET_SCHEME}{code}\");"))
            }
            _ => rewritten.push_str(&out[start..end]),
        }
        cursor = end;
    }
    rewritten.push_str(&out[cursor..]);
    rewritten
}

fn asset_code_at(html: &str, from: usize) -> Option<(usize, usize, &str)> {
    let mut from = from;
    while let Some(offset) = html[from..].find(WEB_ASSET_SCHEME) {
        let start = from + offset;
        let begin = start + WEB_ASSET_SCHEME.len();
        let length = html[begin..]
            .bytes()
            .take_while(|c| c.is_ascii_alphanumeric() || *c == b'_' || *c == b'-')
            .count();
        if length > 0 {
            return Some((start, begin + length, &html[begin..begin + length]));
        }
        from = begin;
    }
    None
}

pub fn extract_asset_codes(html: &str) -> Vec<String> {
    let mut codes: Vec<String> = Vec::new();
    let mut from = 0;
    while let Some((_, end, code)) = asset_code_at(html, from) {
        if !codes.iter().any(|known| known == code) {
            codes.push(code.to_string());
        }
        from = end;
    }
    codes
}

/// Replace `fauna-web-asset:CODE` markers with blob/object URLs from `blobs`.
pub fn materialize_asset_urls(html: &str, blobs: &HashMap<String, String>) -> String {
    let mut out = String::new();
    let mut cursor = 0;
    while let Some((start, end, code)) = asset_code_at(html, cursor) {
        out.push_str(&html[cursor..start]);
        match blobs.get(code) {
            Some(url) => out.push_str(url),
            None => out.push_str(&html[start..end]),
        }
        cursor = end;
    }
    out.push_str(&html[cursor..]);
    out
}

fn decode_data_url(url: &str) -> Option<FetchedMedia> {
    let comma = url.find(',')?;
    let header = &url[5..comma];
    let payload = &url[comma + 1..];
    let content_type = header
        .split(';')
        .next()
        .filter(|kind| !kind.is_empty())
        .unwrap_or("application/octet-stream")
        .to_string();
    if header.contains(";base64") {
        return Some(FetchedMedia {
            data: STANDARD.decode(payload).ok()?,
            content_type,
        });
    }
    Some(FetchedMedia {
        data: percent_encoding::percent_decode_str(payload).collect(),
        content_type,
    })
}

/// Best-effort fetch of a media URL; prefers a privileged `set_media_fetcher`.
pub async fn fetch_media_bytes(url: &str) -> Option<FetchedMedia> {
    if url.starts_with("data:") {
        return decode_data_url(url);
    }
    let fetcher = MEDIA_FETCHER
        .read()
        .unwrap_or_else(PoisonError::into_inner)
        .clone();
    if let Some(fetcher) = fetcher
        && let Some(via) = fetcher(url.to_string()).await
    {
        return Some(via);
    }
    let response = client().get(url).send().await.ok()?;
    if !response.status().is_success() {
        return None;
    }
    let content_type = response
        .headers()
        .get("Content-Type")
        .and_then(|value| value.to_str().ok())
        .filter(|value| !value.is_empty())
        .unwrap_or("application/octet-stream")
        .to_string();
    Some(FetchedMedia {
        data: response.bytes().await.ok()?.to_vec(),
        content_type,
    })
}

/// Absolute-resolve a URL against a base (`https://localhost/` without one).
pub fn absolute_url(url: &str, base: Option<&str>) -> String {
    if url.starts_with("data:") || url.starts_with("blob:") || url.starts_with(WEB_ASSET_SCHEME) {
        return url.to_string();
    }
    let base = base
        .filter(|base| !base.is_empty())
        .unwrap_or("https://localhost/");
    reqwest::Url::parse(base)
        .and_then(|base| base.join(url))
        .map(|resolved| resolved.to_string())
        .unwrap_or_else(|_| url.to_string())
}

/// A web room addressed by an access code or a room reference.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum WebTarget {
    Code { code: String },
    Reference { reference: String },
}

fn target_header(request: reqwest::RequestBuilder, target: &WebTarget) -> reqwest::RequestBuilder {
    match target {
        WebTarget::Code { code } => request.header("Access-Code", code),
        WebTarget::Reference { reference } => request.header("Server", reference),
    }
}

#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BootstrapMeta {
    pub version: u64,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub viewport: Option<WebViewport>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub content_length: Option<u64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub content_type: Option<String>,
    /// In-band HTML for server-hosted rooms (MachineRoom). Extension share uses HTTP.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub html: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AssetUploadResult {
    pub asset_id: String,
    pub access_code: String,
    pub content_type: String,
}

/// The `options` argument of `upload_bootstrap`.
#[derive(Clone, Default)]
pub struct BootstrapOptions {
    pub version: Option<u64>,
    pub viewport: Option<WebViewport>,
    pub content_type: Option<String>,
    pub on_progress: Option<Progress>,
}

/// `{ ok, version }` in the TypeScript SDK.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct BootstrapUpload {
    pub ok: bool,
    pub version: u64,
}

fn authorization_header(authorization: &CredentialsOrApiKey) -> String {
    match authorization {
        CredentialsOrApiKey::Credentials(credentials) => format!("Token {}", credentials.token),
        CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
    }
}

/// Upload cleaned HTML as a raw stream, reporting upload progress.
pub async fn upload_bootstrap(
    authorization: &CredentialsOrApiKey,
    target: &WebTarget,
    html: &[u8],
    options: BootstrapOptions,
) -> Result<BootstrapUpload> {
    let version = options.version.unwrap_or(1);
    let mut request = target_header(
        client()
            .post(format!("{}/extensions/web/bootstrap", super::get_url()))
            .header("Authorization", authorization_header(authorization)),
        target,
    )
    .header(
        "Content-Type",
        options
            .content_type
            .as_deref()
            .unwrap_or("text/html; charset=utf-8"),
    )
    .header("Bootstrap-Version", version.to_string());
    if let Some(viewport) = options.viewport {
        request = request
            .header("Viewport-Width", viewport.width.to_string())
            .header("Viewport-Height", viewport.height.to_string());
    }
    let response = request
        .header("Content-Length", html.len())
        .body(progress_body(html.to_vec(), options.on_progress.clone()))
        .send()
        .await
        .map_err(|_| Error::Message("Failed to upload bootstrap.".to_string()))?;
    if let Some(progress) = &options.on_progress {
        progress(1.0);
    }
    let status = response.status();
    let text = response.text().await.unwrap_or_default();
    if !status.is_success() {
        return Err(Error::Message(if text.is_empty() {
            format!("{}: bootstrap upload failed", status.as_u16())
        } else {
            text
        }));
    }
    Ok(serde_json::from_str(&text).unwrap_or(BootstrapUpload { ok: true, version }))
}

async fn read_body(
    response: reqwest::Response,
    content_length: u64,
    on_progress: Option<Progress>,
) -> Result<Vec<u8>> {
    let mut out = Vec::new();
    let mut body = response.bytes_stream();
    while let Some(chunk) = body.next().await {
        out.extend_from_slice(&chunk?);
        if let Some(progress) = &on_progress
            && content_length > 0
        {
            progress((out.len() as f64 / content_length as f64).min(1.0));
        }
    }
    if let Some(progress) = &on_progress {
        progress(1.0);
    }
    Ok(out)
}

fn header_text(response: &reqwest::Response, name: &str) -> Option<String> {
    response
        .headers()
        .get(name)
        .and_then(|value| value.to_str().ok())
        .filter(|value| !value.is_empty())
        .map(str::to_string)
}

/// `{ html, contentLength, contentType }` in the TypeScript SDK.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Bootstrap {
    pub html: String,
    pub content_length: u64,
    pub content_type: String,
}

/// Download the room HTML bootstrap with download progress when Content-Length is known.
pub async fn download_bootstrap(
    authorization: &CredentialsOrApiKey,
    target: &WebTarget,
    on_progress: Option<Progress>,
) -> Result<Bootstrap> {
    let response = target_header(
        client()
            .get(format!("{}/extensions/web/bootstrap", super::get_url()))
            .header("Authorization", authorization_header(authorization)),
        target,
    )
    .send()
    .await?;
    let response = ok(response).await?;
    let content_type = header_text(&response, "Content-Type")
        .unwrap_or_else(|| "text/html; charset=utf-8".to_string());
    let content_length = header_text(&response, "Content-Length")
        .and_then(|length| length.parse().ok())
        .unwrap_or(0);
    let buffer = read_body(response, content_length, on_progress).await?;
    Ok(Bootstrap {
        html: String::from_utf8_lossy(&buffer).into_owned(),
        content_length,
        content_type,
    })
}

/// The `options` argument of `upload_asset`.
#[derive(Clone, Default)]
pub struct AssetOptions {
    pub asset_id: Option<String>,
    pub on_progress: Option<Progress>,
}

/// Upload one media asset; returns a per-asset access code for guest download.
pub async fn upload_asset(
    authorization: &CredentialsOrApiKey,
    target: &WebTarget,
    data: &[u8],
    content_type: &str,
    options: AssetOptions,
) -> Result<AssetUploadResult> {
    let safe_type = content_type
        .split(';')
        .next()
        .map(str::trim)
        .filter(|kind| !kind.is_empty())
        .unwrap_or("application/octet-stream");
    let mut request = target_header(
        client()
            .post(format!("{}/extensions/web/asset", super::get_url()))
            .header("Authorization", authorization_header(authorization)),
        target,
    )
    .header("Content-Type", safe_type);
    if let Some(asset_id) = &options.asset_id {
        request = request.header("Asset-Id", asset_id);
    }
    let response = request
        .header("Content-Length", data.len())
        .body(progress_body(data.to_vec(), options.on_progress.clone()))
        .send()
        .await
        .map_err(|_| Error::Message("Failed to upload asset.".to_string()))?;
    if let Some(progress) = &options.on_progress {
        progress(1.0);
    }
    let status = response.status();
    let text = response.text().await.unwrap_or_default();
    if !status.is_success() {
        return Err(Error::Message(if text.is_empty() {
            format!("{}: asset upload failed", status.as_u16())
        } else {
            text
        }));
    }
    Ok(serde_json::from_str(&text)?)
}

/// Download one asset by its file access code.
pub async fn download_asset(
    authorization: &CredentialsOrApiKey,
    access_code: &str,
    on_progress: Option<Progress>,
) -> Result<FetchedMedia> {
    let response = client()
        .get(format!("{}/extensions/web/asset", super::get_url()))
        .header("Authorization", authorization_header(authorization))
        .header("File-Access-Code", access_code)
        .send()
        .await?;
    let response = ok(response).await?;
    let content_type = header_text(&response, "Content-Type")
        .unwrap_or_else(|| "application/octet-stream".to_string());
    let content_length = header_text(&response, "Content-Length")
        .and_then(|length| length.parse().ok())
        .unwrap_or(0);
    let data = read_body(response, content_length, on_progress).await?;
    Ok(FetchedMedia { data, content_type })
}

/// One stage of `weighted_progress`: its share of the whole, and the work, which
/// reports its own progress from 0 to 1.
pub struct ProgressStage {
    pub weight: f64,
    pub run: Box<dyn FnOnce(Progress) -> BoxFuture<'static, Result<()>> + Send>,
}

/// Aggregate sequential upload/download stages into a single 0..1 progress.
pub async fn weighted_progress(
    stages: Vec<ProgressStage>,
    on_progress: Option<Progress>,
) -> Result<()> {
    let total = stages
        .iter()
        .map(|stage| stage.weight.max(0.0))
        .sum::<f64>();
    let total = if total == 0.0 { 1.0 } else { total };
    let mut completed = 0.0;
    for stage in stages {
        let weight = stage.weight.max(0.0);
        let outer = on_progress.clone();
        let done = completed;
        (stage.run)(Arc::new(move |p: f64| {
            if let Some(progress) = &outer {
                progress((done + p.clamp(0.0, 1.0) * weight) / total);
            }
        }))
        .await?;
        completed += weight;
        if let Some(progress) = &on_progress {
            progress(completed / total);
        }
    }
    Ok(())
}

/// Web room hooks. Every method defaults to a no-op, like the optional members
/// of the TypeScript `WebRoomHooks` object.
pub trait WebRoomHooks: Send + Sync {
    /// Host published bootstrap meta: guests should HTTP GET the HTML.
    fn on_bootstrap(&self, _room: &WebRoom, _bootstrap: &BootstrapMeta) {}
    /// The host published a fresh full-page snapshot (fallback).
    fn on_snapshot(&self, _room: &WebRoom, _snapshot: &WebSnapshot) {}
    /// The host emitted one incremental DOM mutation.
    fn on_mutation(&self, _room: &WebRoom, _mutation: &WebMutation) {}
    /// The host disconnected / stopped sharing: the room is closing.
    fn on_closed(&self, _room: &WebRoom) {}
    /// Presence roster changed (join/leave/update).
    fn on_presence(&self, _room: &WebRoom) {}
}

impl WebRoomHooks for () {}

/// What a host runs for a `web-tool-call`: the tool's name and parameters in,
/// its result out.
pub type WebToolHandler =
    Arc<dyn Fn(String, Map<String, Value>) -> BoxFuture<'static, Result<String>> + Send + Sync>;

struct WebState {
    hooks: Arc<dyn WebRoomHooks>,
    latest: Option<WebSnapshot>,
    bootstrap: Option<BootstrapMeta>,
    tool_handler: Option<(u64, WebToolHandler)>,
    next_handler: u64,
    pending_tools: HashMap<String, oneshot::Sender<Result<String>>>,
    // Tagged host principal from the live connection (`credentials:` / `group:` / ...).
    host_principal: Option<String>,
    // Server-computed: whether this caller may invite others to the share.
    can_invite: bool,
    owned: bool,
}

/// A live web room for page sharing. `WebRoom` wraps `Room` and carries presence
/// and small DOM mutations. Initial HTML and media bytes travel over HTTP
/// bootstrap/asset routes, not this socket.
#[derive(Clone)]
pub struct WebRoom {
    room: Room,
    state: Arc<Mutex<WebState>>,
}

impl Deref for WebRoom {
    type Target = Room;
    fn deref(&self) -> &Room {
        &self.room
    }
}

impl WebRoom {
    fn new(
        room: Room,
        hooks: Arc<dyn WebRoomHooks>,
        connection_state: &Value,
        owned: bool,
    ) -> WebRoom {
        let meta = &connection_state["room"];
        WebRoom {
            room,
            state: Arc::new(Mutex::new(WebState {
                hooks,
                latest: None,
                bootstrap: None,
                tool_handler: None,
                next_handler: 0,
                pending_tools: HashMap::new(),
                host_principal: meta["hostPrincipal"]
                    .as_str()
                    .filter(|principal| !principal.is_empty())
                    .map(str::to_string),
                can_invite: meta["canInvite"].as_bool().unwrap_or(false),
                owned,
            })),
        }
    }

    fn state(&self) -> MutexGuard<'_, WebState> {
        self.state.lock().unwrap_or_else(PoisonError::into_inner)
    }

    fn hooks(&self) -> Arc<dyn WebRoomHooks> {
        self.state().hooks.clone()
    }

    pub fn set_hooks(&self, hooks: Arc<dyn WebRoomHooks>) {
        self.state().hooks = hooks;
    }

    /// Ingest-only child of a MachineRoom (same socket).
    pub fn from_parent(
        parent: &Room,
        hooks: Option<Arc<dyn WebRoomHooks>>,
        connection_state: &Value,
    ) -> WebRoom {
        WebRoom::new(
            parent.clone(),
            hooks.unwrap_or_else(|| Arc::new(())),
            connection_state,
            false,
        )
    }

    /// Host principal tagged string, if the connection provided it.
    pub fn get_host_principal(&self) -> Option<String> {
        self.state().host_principal.clone()
    }

    /// Whether this signed-in caller may invite others (server-gated).
    pub fn can_invite(&self) -> bool {
        self.state().can_invite
    }

    pub fn get_snapshot(&self) -> Option<WebSnapshot> {
        self.state().latest.clone()
    }

    pub fn get_bootstrap(&self) -> Option<BootstrapMeta> {
        self.state().bootstrap.clone()
    }

    pub fn disconnect(&self) {
        if !self.state().owned {
            return;
        }
        self.room.disconnect();
    }

    pub fn ingest_snapshot(&self, snapshot: WebSnapshot) {
        self.state().latest = Some(snapshot.clone());
        self.hooks().on_snapshot(self, &snapshot);
    }

    pub fn ingest_bootstrap(&self, meta: BootstrapMeta) {
        self.state().bootstrap = Some(meta.clone());
        self.hooks().on_bootstrap(self, &meta);
    }

    pub fn publish_bootstrap(&self, meta: BootstrapMeta) {
        self.post(&json!({ "event": "web-bootstrap", "data": { "bootstrap": meta } }));
        self.state().bootstrap = Some(meta);
    }

    pub fn publish_snapshot(&self, snapshot: WebSnapshot) {
        self.post(&json!({ "event": "web-snapshot", "data": { "snapshot": snapshot } }));
        self.state().latest = Some(snapshot);
    }

    pub fn publish_mutation(&self, mutation: &WebMutation) {
        self.post(&json!({ "event": "web-mutation", "data": { "mutation": mutation } }));
    }

    pub fn publish_closed(&self) {
        self.post(&json!({ "event": "web-closed", "data": {} }));
    }

    /// Host: fulfill inbound `web-tool-call` frames. Returns a function that removes the handler.
    pub fn set_tool_handler(&self, handler: WebToolHandler) -> Box<dyn FnOnce() + Send + Sync> {
        let id = {
            let mut state = self.state();
            state.next_handler += 1;
            let id = state.next_handler;
            state.tool_handler = Some((id, handler));
            id
        };
        let state = Arc::downgrade(&self.state);
        Box::new(move || {
            if let Some(state) = state.upgrade() {
                let mut state = state.lock().unwrap_or_else(PoisonError::into_inner);
                if state
                    .tool_handler
                    .as_ref()
                    .is_some_and(|(current, _)| *current == id)
                {
                    state.tool_handler = None;
                }
            }
        })
    }

    /// Any member: ask the host to run a page tool. Times out after `timeout_ms`
    /// (30 seconds by default).
    pub async fn invoke_tool(
        &self,
        name: &str,
        params: Map<String, Value>,
        timeout_ms: Option<u64>,
    ) -> Result<String> {
        let handler = self
            .state()
            .tool_handler
            .as_ref()
            .map(|(_, handler)| handler.clone());
        if let Some(handler) = handler {
            return handler(name.to_string(), params).await;
        }
        let id = uuid::Uuid::new_v4().to_string();
        let (resolve, result) = oneshot::channel();
        self.state().pending_tools.insert(id.clone(), resolve);
        self.post(&json!({ "event": "web-tool-call", "data": { "id": id, "name": name, "params": params } }));
        match tokio::time::timeout(Duration::from_millis(timeout_ms.unwrap_or(30_000)), result)
            .await
        {
            Ok(Ok(result)) => result,
            _ => {
                self.state().pending_tools.remove(&id);
                Err(Error::Message(format!("Tool timed out: {name}")))
            }
        }
    }

    pub fn handle_event(&self, packet: &Value) -> bool {
        let data = &packet["data"];
        match packet["event"].as_str().unwrap_or_default() {
            "web-bootstrap" => {
                let bootstrap: Option<BootstrapMeta> =
                    serde_json::from_value(data["bootstrap"].clone()).ok();
                self.state().bootstrap = bootstrap.clone();
                if let Some(bootstrap) = bootstrap {
                    self.hooks().on_bootstrap(self, &bootstrap);
                }
                true
            }
            "web-snapshot" => {
                let snapshot: Option<WebSnapshot> =
                    serde_json::from_value(data["snapshot"].clone()).ok();
                self.state().latest = snapshot.clone();
                if let Some(snapshot) = snapshot {
                    self.hooks().on_snapshot(self, &snapshot);
                }
                true
            }
            "web-mutation" => {
                if let Ok(mutation) =
                    serde_json::from_value::<WebMutation>(data["mutation"].clone())
                {
                    self.hooks().on_mutation(self, &mutation);
                }
                true
            }
            "web-tool-call" => {
                self.handle_tool_call(data);
                true
            }
            "web-tool-result" => {
                let Some(id) = data["id"].as_str().filter(|id| !id.is_empty()) else {
                    return true;
                };
                let Some(pending) = self.state().pending_tools.remove(id) else {
                    return true;
                };
                let result =
                    if data["error"].is_null() || data["error"] == false || data["error"] == "" {
                        Ok(match &data["result"] {
                            Value::Null => String::new(),
                            Value::String(result) => result.clone(),
                            result => result.to_string(),
                        })
                    } else {
                        Err(Error::Message(match &data["error"] {
                            Value::String(error) => error.clone(),
                            error => error.to_string(),
                        }))
                    };
                let _ = pending.send(result);
                true
            }
            "web-closed" | "server-closed" => {
                self.hooks().on_closed(self);
                true
            }
            _ => false,
        }
    }

    fn handle_tool_call(&self, data: &Value) {
        let id = data["id"].clone();
        let Some(name) = data["name"]
            .as_str()
            .filter(|name| !name.is_empty())
            .map(str::to_string)
        else {
            return;
        };
        if id.is_null() || id == "" {
            return;
        }
        let Some(handler) = self
            .state()
            .tool_handler
            .as_ref()
            .map(|(_, handler)| handler.clone())
        else {
            return;
        };
        let params = data["params"].as_object().cloned().unwrap_or_default();
        let room = self.clone();
        tokio::spawn(async move {
            match handler(name, params).await {
                Ok(result) => room.post(
                    &json!({ "event": "web-tool-result", "data": { "id": id, "result": result } }),
                ),
                Err(error) => room.post(&json!({
                    "event": "web-tool-result",
                    "data": { "id": id, "error": error.to_string() },
                })),
            }
        });
    }
}

struct WebHooks {
    room: Mutex<Option<WebRoom>>,
    hooks: Arc<dyn WebRoomHooks>,
}

impl WebHooks {
    fn room(&self, room: &Room, state: &Value) -> WebRoom {
        let mut slot = self.room.lock().unwrap_or_else(PoisonError::into_inner);
        slot.get_or_insert_with(|| WebRoom::new(room.clone(), self.hooks.clone(), state, true))
            .clone()
    }
}

impl Hooks for WebHooks {
    fn create_room(&self, room: &Room, state: &Value) {
        let created = self.room(room, state);
        if let Ok(bootstrap) = serde_json::from_value::<BootstrapMeta>(state["bootstrap"].clone()) {
            created.ingest_bootstrap(bootstrap);
        }
        if let Ok(snapshot) = serde_json::from_value::<WebSnapshot>(state["snapshot"].clone()) {
            created.ingest_snapshot(snapshot);
        }
    }

    fn on_event(&self, room: &Room, packet: &Value) -> bool {
        self.room(room, &Value::Null).handle_event(packet)
    }

    fn on_presence(&self, room: &Room) {
        let room = self.room(room, &Value::Null);
        room.hooks().on_presence(&room);
    }

    fn on_closed(&self, room: &Room, _reason: Option<&str>) {
        let room = self.room(room, &Value::Null);
        room.hooks().on_closed(&room);
    }
}

/// Connect to a web room. `target` is an access code (viewer joining a shared
/// page) or a room reference (host opening its own room).
pub async fn connect_web_room(
    authorization: &CredentialsOrApiKey,
    target: &WebTarget,
    hooks: Option<Arc<dyn WebRoomHooks>>,
) -> Result<(WebRoom, Presence)> {
    let auth = match target {
        WebTarget::Code { code } => Authorization::AccessCode {
            authorization: authorization.clone(),
            access_code: code.clone(),
        },
        WebTarget::Reference { reference } => Authorization::Server {
            authorization: authorization.clone(),
            server: reference.clone(),
            group: None,
        },
    };
    let web_hooks = Arc::new(WebHooks {
        room: Mutex::new(None),
        hooks: hooks.unwrap_or_else(|| Arc::new(())),
    });
    let me = connect(
        auth,
        &format!("{}/extensions/web/live", super::get_url()),
        web_hooks.clone(),
    )
    .await?;
    let room = web_hooks.room(me.room(), &Value::Null);
    room.hooks().on_presence(&room);
    Ok((room, me))
}