croft-software 0.2.132

VSCode-style TUI written in Rust
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
//! `.http` / `.rest` request files (#370): the REST-Client format — requests
//! separated by `###`, `Name: value` headers, a blank line before the body,
//! `{{variables}}` from the file's own `@name = value` lines or the env
//! files beside it (flat, or REST Client's and JetBrains' named
//! environments) — parsed, sent, and rendered as a response document the
//! editor opens as an ordinary tab.
//!
//! One divergence from REST Client worth knowing: `ureq` replaces duplicate
//! request headers, so two `Accept:` lines in a file send only the last.
//!
//! The split of responsibilities is deliberate: everything here is pure or
//! blocking-IO-free except [`send`], which the app runs on a worker thread.
//! Secrets never leave the substitution: history records the RAW request
//! text (variables unresolved), and the response document carries only the
//! raw request line plus what the server sent back.

use std::collections::BTreeMap;
use std::path::Path;
use std::time::Duration;

/// A response body larger than this is cut, and the document says so. The
/// viewer is an editor tab, not a download manager.
pub const RESPONSE_CAP_BYTES: usize = 8 * 1024 * 1024;

/// How long a request may take before the worker gives up.
pub const REQUEST_TIMEOUT: Duration = Duration::from_secs(30);

/// croft's env file beside a request file: a JSON object whose values fill
/// `{{name}}` holes, flat or split into named environments (#924).
pub const ENV_FILE: &str = ".http.env.json";

/// Every env file read beside a request file, a later one winning a name:
/// croft's own, then JetBrains' HTTP client's shared and private files.
pub const ENV_FILES: [&str; 3] = [
    ENV_FILE,
    "http-client.env.json",
    "http-client.private.env.json",
];

/// The environment whose values every environment shares, as REST Client
/// and JetBrains' HTTP client name it.
pub const SHARED_ENV: &str = "$shared";

/// One request block in a `.http` file, with the rows it spans so the app
/// can find the request under the caret.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct HttpRequest {
    pub method: String,
    pub url: String,
    pub headers: Vec<(String, String)>,
    pub body: Option<String>,
    /// First row of the block (its `###` separator or first content line).
    pub start: usize,
    /// Row of the request line itself.
    pub line: usize,
    /// One past the last row of the block.
    pub end: usize,
}

/// Whether `path` is a request file this module owns.
pub fn is_http_file(path: &Path) -> bool {
    matches!(
        path.extension().and_then(|e| e.to_str()),
        Some("http") | Some("rest")
    )
}

/// Parse every request block in `text`. Blocks are separated by lines
/// starting with `###`; within a block, `#` and `//` lines are comments and
/// `@name = value` lines are file variables, the first remaining line is
/// `[METHOD] URL [HTTP/version]`, headers follow until a blank line, and
/// everything after is the body. A block of only variables and comments is
/// no request (#1186).
pub fn parse_requests(text: &str) -> Vec<HttpRequest> {
    let lines = file_lines(text);
    let mut out = Vec::new();
    for (s, e) in blocks(&lines) {
        if let Some(req) = parse_block(&lines, s, e) {
            out.push(req);
        }
    }
    out
}

/// The file's lines. A leading BOM (routine from Windows editors) must not
/// defeat the method test on the first request line.
fn file_lines(text: &str) -> Vec<&str> {
    text.strip_prefix('\u{feff}')
        .unwrap_or(text)
        .lines()
        .collect()
}

/// The `[start, end)` rows of each `###`-separated block.
fn blocks(lines: &[&str]) -> Vec<(usize, usize)> {
    let mut blocks: Vec<(usize, usize)> = Vec::new();
    let mut start = 0usize;
    for (i, line) in lines.iter().enumerate() {
        if line.trim_start().starts_with("###") {
            if i > start {
                blocks.push((start, i));
            }
            start = i;
        }
    }
    if lines.len() > start {
        blocks.push((start, lines.len()));
    }
    blocks
}

/// The first row of a block that is neither the separator, a blank, a
/// comment nor a file variable: its request line, if it has one.
fn request_row(lines: &[&str], start: usize, end: usize) -> Option<usize> {
    (start..end).find(|&i| {
        let t = lines[i].trim();
        !(t.is_empty() || t.starts_with('#') || t.starts_with("//") || file_variable(t).is_some())
    })
}

/// REST Client's file variable, `@name = value` (#1186): the name and the
/// value with its outer blanks trimmed.
fn file_variable(line: &str) -> Option<(&str, &str)> {
    let rest = line.trim().strip_prefix('@')?;
    let (name, value) = rest.split_once('=')?;
    let name = name.trim_end();
    let mut chars = name.chars();
    let first = chars.next()?;
    let valid = (first.is_ascii_alphabetic() || first == '_')
        && chars.all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '.' | '-'));
    valid.then(|| (name, value.trim()))
}

/// Every `@name = value` file variable in `text`, from the lines before
/// each block's request line (a body that starts with `@` is not one). A
/// later definition of a name wins, as in REST Client.
pub fn file_variables(text: &str) -> BTreeMap<String, String> {
    let lines = file_lines(text);
    let mut out = BTreeMap::new();
    for (s, e) in blocks(&lines) {
        let stop = request_row(&lines, s, e).unwrap_or(e);
        for line in &lines[s..stop] {
            if let Some((name, value)) = file_variable(line) {
                out.insert(name.to_string(), value.to_string());
            }
        }
    }
    out
}

/// The variables a request in `text` resolves against: the file's own
/// `@name = value` lines over `env` (the `.http.env.json` values), as REST
/// Client ranks them (#1186).
pub fn variables(text: &str, env: BTreeMap<String, String>) -> BTreeMap<String, String> {
    let mut vars = env;
    vars.extend(file_variables(text));
    vars
}

fn parse_block(lines: &[&str], start: usize, end: usize) -> Option<HttpRequest> {
    // Skip the separator, blanks, comments and variables to the request line.
    let mut i = request_row(lines, start, end)?;
    let line_row = i;
    let mut parts = lines[i].split_whitespace();
    let first = parts.next()?;
    // `GET https://…` or a bare URL (GET implied). A method is an all-caps
    // token WITH a URL after it; a lone all-caps token is treated as the
    // URL, so a malformed line yields an honest send error rather than
    // silently dropping the whole block from `request_at`.
    let looks_like_method =
        first.len() <= 10 && !first.is_empty() && first.chars().all(|c| c.is_ascii_uppercase());
    let (method, url) = match parts.next() {
        Some(second) if looks_like_method => (first.to_string(), second.to_string()),
        _ => (String::from("GET"), first.to_string()),
    };
    i += 1;
    // Headers until the first blank line.
    let mut headers = Vec::new();
    while i < end {
        let t = lines[i].trim();
        if t.is_empty() {
            break;
        }
        if t.starts_with('#') || t.starts_with("//") {
            i += 1;
            continue;
        }
        if let Some((name, value)) = t.split_once(':') {
            headers.push((name.trim().to_string(), value.trim().to_string()));
        }
        i += 1;
    }
    // Body: the rest of the block, outer blank lines trimmed.
    let mut body_lines: Vec<&str> = lines[i.min(end)..end].to_vec();
    while body_lines.first().is_some_and(|l| l.trim().is_empty()) {
        body_lines.remove(0);
    }
    while body_lines.last().is_some_and(|l| l.trim().is_empty()) {
        body_lines.pop();
    }
    let body = if body_lines.is_empty() {
        None
    } else {
        Some(body_lines.join("\n"))
    };
    Some(HttpRequest {
        method,
        url,
        headers,
        body,
        start,
        line: line_row,
        end,
    })
}

/// The request whose block contains `row`, for "run the request under the
/// caret".
pub fn request_at(requests: &[HttpRequest], row: usize) -> Option<&HttpRequest> {
    requests.iter().find(|r| r.start <= row && row < r.end)
}

/// What the env files beside a request file hold for it.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct EnvFiles {
    /// The values a request resolves against: the files' flat top-level
    /// values, under `$shared`, under the active environment's.
    pub vars: BTreeMap<String, String>,
    /// Every named environment the files define (not `$shared`), sorted.
    pub environments: Vec<String>,
}

/// Read [`ENV_FILES`] in `dir` (#924). A top-level string, number or
/// boolean is a variable, as in croft's flat format; a top-level object is
/// an environment in REST Client's and JetBrains' shape, `$shared` applying
/// to all of them and `active` (picked with HTTP: Switch Environment) on
/// top. Numbers and booleans are stringified; deeper nesting is skipped.
pub fn load_env(dir: &Path, active: Option<&str>) -> EnvFiles {
    let (mut flat, mut shared, mut chosen) = (BTreeMap::new(), BTreeMap::new(), BTreeMap::new());
    let mut environments = std::collections::BTreeSet::new();
    for file in ENV_FILES {
        let Ok(bytes) = std::fs::read(dir.join(file)) else {
            continue;
        };
        let Ok(serde_json::Value::Object(map)) = serde_json::from_slice(&bytes) else {
            continue;
        };
        for (k, v) in map {
            let serde_json::Value::Object(env) = v else {
                if let Some(val) = scalar(v) {
                    flat.insert(k, val);
                }
                continue;
            };
            let layer = if k == SHARED_ENV {
                &mut shared
            } else {
                let on = active == Some(k.as_str());
                environments.insert(k);
                if !on {
                    continue;
                }
                &mut chosen
            };
            for (name, val) in env {
                if let Some(val) = scalar(val) {
                    layer.insert(name, val);
                }
            }
        }
    }
    flat.extend(shared);
    flat.extend(chosen);
    EnvFiles {
        vars: flat,
        environments: environments.into_iter().collect(),
    }
}

/// An env file value as the text it fills a hole with, if it is one.
fn scalar(v: serde_json::Value) -> Option<String> {
    match v {
        serde_json::Value::String(s) => Some(s),
        serde_json::Value::Number(n) => Some(n.to_string()),
        serde_json::Value::Bool(b) => Some(b.to_string()),
        _ => None,
    }
}

/// Fill every `{{name}}` hole from `vars` (or the process environment for
/// `{{$env.NAME}}`), returning the result and the names that had no value.
/// A value may itself hold holes (`@url = {{base}}/v1`), which are filled
/// the same way; a name whose value refers back to itself (`@a = {{a}}`),
/// or one past the expansion budget, counts as missing. An unknown hole is
/// left verbatim so the caller can refuse to send a request whose secrets
/// or hosts would otherwise go out literally.
pub fn substitute(text: &str, vars: &BTreeMap<String, String>) -> (String, Vec<String>) {
    let mut missing = Vec::new();
    let mut expanding = Vec::new();
    let mut budget = EXPANSION_BUDGET;
    let out = expand(text, vars, &mut expanding, &mut budget, &mut missing);
    (out, missing)
}

/// How many variable values one substitution may expand, so a file whose
/// variables each repeat the next many times cannot stall the send.
const EXPANSION_BUDGET: usize = 10_000;

fn expand<'a>(
    text: &str,
    vars: &'a BTreeMap<String, String>,
    expanding: &mut Vec<&'a str>,
    budget: &mut usize,
    missing: &mut Vec<String>,
) -> String {
    let mut out = String::with_capacity(text.len());
    let mut rest = text;
    while let Some(open) = rest.find("{{") {
        out.push_str(&rest[..open]);
        let after = &rest[open + 2..];
        let Some(close) = after.find("}}") else {
            out.push_str(&rest[open..]);
            rest = "";
            break;
        };
        let name = after[..close].trim();
        let value = if let Some(env_name) = name.strip_prefix("$env.") {
            std::env::var(env_name).ok()
        } else {
            match vars.get_key_value(name) {
                Some((key, v)) if *budget > 0 && !expanding.contains(&key.as_str()) => {
                    *budget -= 1;
                    expanding.push(key);
                    let v = expand(v, vars, expanding, budget, missing);
                    expanding.pop();
                    Some(v)
                }
                _ => None,
            }
        };
        match value {
            Some(v) => out.push_str(&v),
            None => {
                out.push_str(&rest[open..open + 2 + close + 2]);
                if !missing.contains(&name.to_string()) {
                    missing.push(name.to_string());
                }
            }
        }
        rest = &after[close + 2..];
    }
    out.push_str(rest);
    out
}

/// A request with its variables already substituted, ready to send.
#[derive(Clone, Debug)]
pub struct ResolvedRequest {
    pub method: String,
    pub url: String,
    pub headers: Vec<(String, String)>,
    pub body: Option<String>,
}

/// Substitute every hole in `req` from `vars`; the missing names cover the
/// method line, headers, and body together.
pub fn resolve(
    req: &HttpRequest,
    vars: &BTreeMap<String, String>,
) -> (ResolvedRequest, Vec<String>) {
    let mut missing: Vec<String> = Vec::new();
    let mut sub = |s: &str| {
        let (v, m) = substitute(s, vars);
        for name in m {
            // `Vec::dedup` removes only CONSECUTIVE duplicates; a name
            // missing in both the URL and a later header must still be
            // reported once.
            if !missing.contains(&name) {
                missing.push(name);
            }
        }
        v
    };
    let resolved = ResolvedRequest {
        method: req.method.clone(),
        url: sub(&req.url),
        headers: req
            .headers
            .iter()
            .map(|(k, v)| (k.clone(), sub(v)))
            .collect(),
        body: req.body.as_deref().map(&mut sub),
    };
    (resolved, missing)
}

/// The request as a `curl` command line, single-quoted for a POSIX shell.
/// The body goes in `--data-raw`, not `--data`: curl reads a `--data` value
/// that starts with `@` as a file name, so `@channel deploy finished` would
/// fail (or send a local file) instead of posting the text (#1064).
pub fn to_curl(req: &ResolvedRequest) -> String {
    fn sq(s: &str) -> String {
        format!("'{}'", s.replace('\'', "'\\''"))
    }
    let mut out = format!("curl -X {} {}", req.method, sq(&req.url));
    for (k, v) in &req.headers {
        out.push_str(&format!(" -H {}", sq(&format!("{k}: {v}"))));
    }
    if let Some(body) = &req.body {
        out.push_str(&format!(" --data-raw {}", sq(body)));
    }
    out
}

/// What came back: enough to render the response document, never more than
/// [`RESPONSE_CAP_BYTES`] of body.
#[derive(Clone, Debug)]
pub struct HttpResponse {
    pub status: u16,
    pub status_text: String,
    pub http_version: String,
    pub headers: Vec<(String, String)>,
    pub body: Vec<u8>,
    pub truncated: bool,
    pub elapsed_ms: u64,
}

impl HttpResponse {
    /// The `content-type` header's value, lowercased, parameters dropped.
    pub fn content_type(&self) -> String {
        self.headers
            .iter()
            .find(|(k, _)| k.eq_ignore_ascii_case("content-type"))
            .map(|(_, v)| {
                v.split(';')
                    .next()
                    .unwrap_or("")
                    .trim()
                    .to_ascii_lowercase()
            })
            .unwrap_or_default()
    }
}

/// Send `req` and read the response, on the caller's thread (the app runs
/// this on a worker). A non-2xx status is a RESPONSE, not an error; only a
/// transport failure (refused, DNS, TLS, timeout) is `Err`.
pub fn send(req: &ResolvedRequest, timeout: Duration) -> Result<HttpResponse, String> {
    use std::io::Read;
    let agent = crate::net::builder(&req.url)
        .timeout(timeout)
        .redirects(4)
        .build();
    let mut r = agent.request(&req.method, &req.url);
    for (k, v) in &req.headers {
        r = r.set(k, v);
    }
    let started = std::time::Instant::now();
    let result = match &req.body {
        Some(body) => r.send_string(body),
        None => r.call(),
    };
    let resp = match result {
        Ok(resp) => resp,
        // A status error still carries the whole response; show it.
        Err(ureq::Error::Status(_, resp)) => resp,
        // The KIND only, never the Display: ureq's transport Display opens
        // with the resolved URL, and a `?api_key={{token}}` request would
        // print the substituted secret into the status line on exactly the
        // failures (refused, DNS, timeout) a user reads it for.
        Err(ureq::Error::Transport(t)) => return Err(t.kind().to_string()),
    };
    let elapsed_ms = started.elapsed().as_millis() as u64;
    let status = resp.status();
    let status_text = resp.status_text().to_string();
    let http_version = resp.http_version().to_string();
    // `headers_names` lists a repeated header once per line while `header`
    // returns only its first value, so two `Set-Cookie`s showed the first
    // one twice. Each name once, with every value it carries.
    let mut headers: Vec<(String, String)> = Vec::new();
    let mut seen = std::collections::HashSet::new();
    for n in resp.headers_names() {
        if seen.insert(n.clone()) {
            for v in resp.all(&n) {
                headers.push((n.clone(), v.to_string()));
            }
        }
    }
    let mut body = Vec::new();
    let mut reader = resp.into_reader().take(RESPONSE_CAP_BYTES as u64 + 1);
    reader
        .read_to_end(&mut body)
        .map_err(|e| format!("reading the response body: {e}"))?;
    let truncated = body.len() > RESPONSE_CAP_BYTES;
    body.truncate(RESPONSE_CAP_BYTES);
    Ok(HttpResponse {
        status,
        status_text,
        http_version,
        headers,
        body,
        truncated,
        elapsed_ms,
    })
}

/// How the response body should be materialised for the viewer.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ResponseKind {
    /// A text document with the given extension (`jsonc`, `xml`, `txt`):
    /// status and headers ride along as comments, the body pretty-printed.
    Text(&'static str),
    /// An image: the raw bytes are written with this extension and the
    /// editor's image path renders them.
    Image(&'static str),
}

/// Classify `content_type` into how the response opens.
pub fn response_kind(content_type: &str) -> ResponseKind {
    match content_type {
        "image/png" => ResponseKind::Image("png"),
        "image/jpeg" | "image/jpg" => ResponseKind::Image("jpg"),
        "image/gif" => ResponseKind::Image("gif"),
        "image/webp" => ResponseKind::Image("webp"),
        "image/bmp" => ResponseKind::Image("bmp"),
        t if t == "application/json" || t.ends_with("+json") => ResponseKind::Text("jsonc"),
        t if t == "application/xml" || t == "text/xml" || t.ends_with("+xml") => {
            ResponseKind::Text("xml")
        }
        _ => ResponseKind::Text("txt"),
    }
}

/// Render a text response as the document the tab shows: the RAW request
/// line (variables unresolved, so a secret never lands in the file), the
/// status, timing and headers as comments in the target language, then the
/// body — pretty-printed for JSON, verbatim otherwise. Returns the file
/// extension and the text.
pub fn response_doc(raw_request_line: &str, resp: &HttpResponse) -> (&'static str, String) {
    let kind = response_kind(&resp.content_type());
    let ext = match kind {
        ResponseKind::Text(e) => e,
        // The caller routes images before coming here; falling through
        // renders the metadata alone rather than binary garbage.
        ResponseKind::Image(_) => "txt",
    };
    let (open, close): (&str, &str) = match ext {
        "xml" => ("<!-- ", " -->"),
        _ => ("// ", ""),
    };
    // A server header containing `-->` must not escape the XML comment
    // prologue into the document body: the tab is a viewer of untrusted
    // server output. (`//` comments are newline-delimited and ureq strips
    // newlines from header values, so the other branch needs no escape.)
    let esc = |s: &str| -> String {
        if ext == "xml" {
            s.replace("-->", "--&gt;")
        } else {
            s.to_string()
        }
    };
    let mut doc = String::new();
    let size = resp.body.len();
    doc.push_str(&format!(
        "{open}{} \u{2192} HTTP/{} {} {} \u{00b7} {} ms \u{00b7} {size} B{close}\n",
        esc(raw_request_line),
        resp.http_version.trim_start_matches("HTTP/"),
        resp.status,
        esc(&resp.status_text),
        resp.elapsed_ms,
    ));
    for (k, v) in &resp.headers {
        doc.push_str(&format!("{open}{}: {}{close}\n", esc(k), esc(v)));
    }
    if resp.truncated {
        doc.push_str(&format!(
            "{open}body cut at {RESPONSE_CAP_BYTES} bytes{close}\n"
        ));
    }
    doc.push('\n');
    let body_text = String::from_utf8_lossy(&resp.body);
    if ext == "jsonc" {
        match serde_json::from_str::<serde_json::Value>(&body_text) {
            Ok(v) => {
                doc.push_str(
                    &serde_json::to_string_pretty(&v).unwrap_or_else(|_| body_text.to_string()),
                );
            }
            Err(_) => doc.push_str(&body_text),
        }
    } else {
        doc.push_str(&body_text);
    }
    if !doc.ends_with('\n') {
        doc.push('\n');
    }
    (ext, doc)
}

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

    #[test]
    fn a_repeated_response_header_keeps_every_value() {
        use std::io::{Read, Write};
        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
        let port = listener.local_addr().unwrap().port();
        std::thread::spawn(move || {
            let (mut s, _) = listener.accept().unwrap();
            let mut buf = [0u8; 4096];
            let _ = s.read(&mut buf);
            let _ = s.write_all(
                b"HTTP/1.1 200 OK\r\nset-cookie: a=1\r\nset-cookie: b=2\r\ncontent-length: 0\r\nconnection: close\r\n\r\n",
            );
        });
        let resp = send(
            &ResolvedRequest {
                method: String::from("GET"),
                url: format!("http://127.0.0.1:{port}/"),
                headers: Vec::new(),
                body: None,
            },
            Duration::from_secs(10),
        )
        .unwrap();
        let cookies: Vec<_> = resp
            .headers
            .iter()
            .filter(|(n, _)| n == "set-cookie")
            .map(|(_, v)| v.as_str())
            .collect();
        assert_eq!(cookies, ["a=1", "b=2"]);
    }

    const THREE: &str = "\
# users, with a token from the env file
GET {{host}}/users\n\
Authorization: Bearer {{token}}\n\
\n\
###\n\
POST {{host}}/users HTTP/1.1\n\
Content-Type: application/json\n\
\n\
{\"name\": \"ada\"}\n\
\n\
### delete one\n\
DELETE {{host}}/users/1\n";

    /// The issue's shape: three requests split on `###`, each independent,
    /// with comments and a method-less line handled.
    #[test]
    fn parses_three_requests_with_separators_headers_and_bodies() {
        let reqs = parse_requests(THREE);
        assert_eq!(reqs.len(), 3);
        assert_eq!(reqs[0].method, "GET");
        assert_eq!(reqs[0].url, "{{host}}/users");
        assert_eq!(
            reqs[0].headers,
            vec![(
                String::from("Authorization"),
                String::from("Bearer {{token}}")
            )]
        );
        assert_eq!(reqs[0].body, None);
        assert_eq!(reqs[1].method, "POST");
        assert_eq!(reqs[1].body.as_deref(), Some("{\"name\": \"ada\"}"));
        assert_eq!(reqs[2].method, "DELETE");
        assert_eq!(reqs[2].line, 11, "the request line, not the ### above it");

        // A bare URL is a GET.
        let bare = parse_requests("example.com/health\n");
        assert_eq!(bare[0].method, "GET");
        assert_eq!(bare[0].url, "example.com/health");
    }

    /// The caret maps to the block it sits in, separators included, so the
    /// chord works from anywhere inside a request.
    #[test]
    fn request_at_covers_each_whole_block() {
        let reqs = parse_requests(THREE);
        assert_eq!(request_at(&reqs, 0).unwrap().method, "GET");
        assert_eq!(request_at(&reqs, 3).unwrap().method, "GET");
        assert_eq!(
            request_at(&reqs, 4).unwrap().method,
            "POST",
            "the ### row belongs to the next block"
        );
        assert_eq!(request_at(&reqs, 8).unwrap().method, "POST");
        assert_eq!(request_at(&reqs, 11).unwrap().method, "DELETE");
        assert!(request_at(&reqs, 99).is_none());
    }

    /// Variables fill from the map and `$env.`; a hole with no value is
    /// left verbatim and NAMED, so the caller can refuse to send it.
    #[test]
    fn substitution_fills_names_env_and_reports_missing() {
        let mut vars = BTreeMap::new();
        vars.insert(String::from("host"), String::from("http://x.test"));
        let (s, missing) = substitute("{{host}}/u/{{id}}", &vars);
        assert_eq!(s, "http://x.test/u/{{id}}");
        assert_eq!(missing, vec![String::from("id")]);

        // SAFETY: the var name is unique to this test and nothing else in
        // the tree reads it, so no concurrent reader races the mutation.
        unsafe { std::env::set_var("CROFT_HTTP_TEST_VAR", "7") };
        let (s, missing) = substitute("v={{$env.CROFT_HTTP_TEST_VAR}}", &vars);
        assert_eq!(s, "v=7");
        assert!(missing.is_empty());

        let (reqs, vars2) = (parse_requests(THREE), {
            let mut v = vars.clone();
            v.insert(String::from("token"), String::from("s3cret"));
            v
        });
        let (resolved, missing) = resolve(&reqs[0], &vars2);
        assert!(missing.is_empty());
        assert_eq!(resolved.url, "http://x.test/users");
        assert_eq!(resolved.headers[0].1, "Bearer s3cret");
    }

    /// A malformed request line and a BOM'd file degrade honestly rather
    /// than silently dropping a block (#428 review).
    #[test]
    fn malformed_lines_and_boms_degrade_honestly() {
        // A lone all-caps token is a URL, not a method with no URL: the
        // block survives, and the send fails with a real error later.
        let reqs = parse_requests("GET\nAccept: x\n\n###\nGET http://ok/\n");
        assert_eq!(reqs.len(), 2, "the malformed block is not dropped");
        assert_eq!(reqs[0].url, "GET");
        assert_eq!(request_at(&reqs, 1).unwrap().url, "GET");

        // A leading BOM does not become part of the first URL.
        let reqs = parse_requests("\u{feff}GET http://x/a\n");
        assert_eq!(reqs[0].method, "GET");
        assert_eq!(reqs[0].url, "http://x/a");
    }

    /// A name missing in two places is reported once, even with another
    /// missing name between the occurrences (`dedup` is consecutive-only).
    #[test]
    fn a_missing_name_is_reported_once_across_the_request() {
        let req = HttpRequest {
            method: String::from("GET"),
            url: String::from("{{tok}}/{{host}}"),
            headers: vec![(String::from("X-A"), String::from("{{tok}}"))],
            body: None,
            start: 0,
            line: 0,
            end: 1,
        };
        let (_, missing) = resolve(&req, &BTreeMap::new());
        assert_eq!(missing, vec![String::from("tok"), String::from("host")]);
    }

    /// A server header carrying `-->` cannot escape the XML comment
    /// prologue into the rendered document (#428 review).
    #[test]
    fn xml_prologue_survives_a_hostile_header_value() {
        let resp = HttpResponse {
            status: 200,
            status_text: String::from("OK"),
            http_version: String::from("HTTP/1.1"),
            headers: vec![
                (String::from("content-type"), String::from("text/xml")),
                (String::from("x-evil"), String::from("a --> <boom/> <!--")),
            ],
            body: b"<a/>".to_vec(),
            truncated: false,
            elapsed_ms: 1,
        };
        let (ext, doc) = response_doc("GET x", &resp);
        assert_eq!(ext, "xml");
        assert!(
            doc.contains("a --&gt; <boom/> <!-- -->"),
            "the header stays inside its comment: {doc}"
        );
        assert!(!doc.contains("a --> <boom/>"), "no raw escape survives");
    }

    /// The env file's top-level values: strings verbatim, numbers and
    /// booleans stringified, an object an environment rather than a value,
    /// absence empty.
    #[test]
    fn env_file_loads_flat_values_only() {
        let dir = tempfile::TempDir::new().unwrap();
        std::fs::write(
            dir.path().join(ENV_FILE),
            "{\"host\": \"http://a\", \"port\": 8080, \"on\": true, \"nested\": {\"x\": 1}}",
        )
        .unwrap();
        let EnvFiles { vars, environments } = load_env(dir.path(), None);
        assert_eq!(vars.get("host").map(String::as_str), Some("http://a"));
        assert_eq!(vars.get("port").map(String::as_str), Some("8080"));
        assert_eq!(vars.get("on").map(String::as_str), Some("true"));
        assert!(!vars.contains_key("nested") && !vars.contains_key("x"));
        assert_eq!(environments, ["nested"]);
        assert_eq!(
            load_env(&dir.path().join("missing"), None),
            EnvFiles::default()
        );
    }

    /// #924: REST Client's `$shared` + named environments in
    /// `.http.env.json`, and JetBrains' `http-client.env.json` with its
    /// private twin. With no environment active only `$shared` (and flat
    /// values) apply; the active one wins over both, and the private file
    /// wins over the public one.
    #[test]
    fn named_environments_layer_over_shared_values() {
        let dir = tempfile::TempDir::new().unwrap();
        std::fs::write(
            dir.path().join(ENV_FILE),
            r#"{"version": "v0", "$shared": {"version": "v1", "host": "http://shared"},
                "dev": {"host": "http://dev", "port": 8080}, "prod": {"host": "http://prod"}}"#,
        )
        .unwrap();
        std::fs::write(
            dir.path().join("http-client.env.json"),
            r#"{"staging": {"host": "http://staging", "token": "public"}}"#,
        )
        .unwrap();
        std::fs::write(
            dir.path().join("http-client.private.env.json"),
            r#"{"staging": {"token": "private"}}"#,
        )
        .unwrap();
        let get = |env: &EnvFiles, k: &str| env.vars.get(k).cloned();

        let none = load_env(dir.path(), None);
        assert_eq!(none.environments, ["dev", "prod", "staging"]);
        assert_eq!(get(&none, "host").as_deref(), Some("http://shared"));
        assert_eq!(get(&none, "version").as_deref(), Some("v1"));
        assert_eq!(
            get(&none, "port"),
            None,
            "an inactive environment is unread"
        );

        let dev = load_env(dir.path(), Some("dev"));
        assert_eq!(get(&dev, "host").as_deref(), Some("http://dev"));
        assert_eq!(get(&dev, "port").as_deref(), Some("8080"));
        assert_eq!(
            get(&dev, "version").as_deref(),
            Some("v1"),
            "$shared fills in"
        );

        let staging = load_env(dir.path(), Some("staging"));
        assert_eq!(get(&staging, "host").as_deref(), Some("http://staging"));
        assert_eq!(get(&staging, "token").as_deref(), Some("private"));

        let gone = load_env(dir.path(), Some("qa"));
        assert_eq!(gone.vars, none.vars, "an unknown name is no environment");
    }

    /// Copy as curl single-quotes for a POSIX shell, apostrophes included.
    #[test]
    fn curl_line_quotes_for_a_posix_shell() {
        let req = ResolvedRequest {
            method: String::from("POST"),
            url: String::from("http://x.test/it's"),
            headers: vec![(String::from("X-A"), String::from("b c"))],
            body: Some(String::from("{\"q\": \"a'b\"}")),
        };
        let curl = to_curl(&req);
        assert_eq!(
            curl,
            "curl -X POST 'http://x.test/it'\\''s' -H 'X-A: b c' --data-raw '{\"q\": \"a'\\''b\"}'"
        );
    }

    /// A body that starts with `@` is text to send, not a file for curl to
    /// read (#1064): `--data-raw` never treats `@` specially.
    #[test]
    fn curl_line_sends_an_at_body_as_text() {
        let req = ResolvedRequest {
            method: String::from("POST"),
            url: String::from("http://x.test/hook"),
            headers: Vec::new(),
            body: Some(String::from("@channel deploy finished")),
        };
        let curl = to_curl(&req);
        assert!(
            curl.ends_with(" --data-raw '@channel deploy finished'"),
            "{curl}"
        );
        assert!(!curl.contains(" --data '"), "{curl}");
    }

    /// A JSON response renders as a `.jsonc` document: the RAW request line
    /// and every header as `//` comments, the body pretty-printed; XML gets
    /// XML comments; anything else is a `.txt` with the body verbatim.
    #[test]
    fn response_documents_render_by_content_type() {
        let mut resp = HttpResponse {
            status: 200,
            status_text: String::from("OK"),
            http_version: String::from("HTTP/1.1"),
            headers: vec![(
                String::from("content-type"),
                String::from("application/json; charset=utf-8"),
            )],
            body: b"{\"a\":[1,2]}".to_vec(),
            truncated: false,
            elapsed_ms: 42,
        };
        let (ext, doc) = response_doc("GET {{host}}/users", &resp);
        assert_eq!(ext, "jsonc");
        assert!(doc.starts_with(
            "// GET {{host}}/users \u{2192} HTTP/1.1 200 OK \u{00b7} 42 ms \u{00b7} 11 B\n"
        ));
        assert!(doc.contains("// content-type: application/json"));
        assert!(
            doc.contains("{\n  \"a\": [\n    1,\n    2\n  ]\n}"),
            "pretty-printed: {doc}"
        );

        resp.headers[0].1 = String::from("text/xml");
        resp.body = b"<a/>".to_vec();
        let (ext, doc) = response_doc("GET x", &resp);
        assert_eq!(ext, "xml");
        assert!(doc.contains("<!-- GET x"));
        assert!(doc.ends_with("<a/>\n"));

        resp.headers.clear();
        resp.truncated = true;
        let (ext, doc) = response_doc("GET x", &resp);
        assert_eq!(ext, "txt");
        assert!(doc.contains("// body cut at"));

        assert_eq!(response_kind("image/png"), ResponseKind::Image("png"));
        assert_eq!(
            response_kind("application/hal+json"),
            ResponseKind::Text("jsonc")
        );
    }

    /// The issue's file: `@base` on line 1 fills `{{base}}` in the request
    /// below it, and the `@base` line is not itself a request (#1186).
    const VARS: &str = "@base = http://127.0.0.1:8765\n\n### Fetch the hello document\nGET {{base}}/hello.json\nAccept: application/json\n";

    #[test]
    fn file_variables_fill_the_requests_below_them() {
        let reqs = parse_requests(VARS);
        assert_eq!(reqs.len(), 1, "the @base block is no request: {reqs:?}");
        let req = request_at(&reqs, 3).unwrap();
        let (resolved, missing) = resolve(req, &variables(VARS, BTreeMap::new()));
        assert!(missing.is_empty(), "{missing:?}");
        assert_eq!(resolved.url, "http://127.0.0.1:8765/hello.json");
        assert!(request_at(&reqs, 0).is_none(), "nothing to send on line 1");
    }

    /// Variables may refer to each other and to `.http.env.json` values,
    /// and the file's own definition wins over the env file's.
    #[test]
    fn file_variables_nest_and_outrank_the_env_file() {
        let text = "@host = {{scheme}}://api.test\n@url = {{host}}/v{{version}}\n@version = 2\n\nGET {{url}}/users\nAuthorization: Bearer {{token}}\n";
        let env = BTreeMap::from([
            (String::from("scheme"), String::from("https")),
            (String::from("token"), String::from("t0k")),
            (String::from("version"), String::from("1")),
        ]);
        let reqs = parse_requests(text);
        assert_eq!(reqs.len(), 1);
        assert_eq!(reqs[0].line, 4);
        let (resolved, missing) = resolve(&reqs[0], &variables(text, env));
        assert!(missing.is_empty(), "{missing:?}");
        assert_eq!(resolved.url, "https://api.test/v2/users");
        assert_eq!(resolved.headers[0].1, "Bearer t0k");
    }

    /// Negative: a variable that refers to itself, or to a name nobody
    /// defines, refuses to send instead of sending its holes; a value that
    /// repeats the next one many times cannot stall the send.
    #[test]
    fn a_cyclic_or_undefined_file_variable_still_refuses() {
        let text = "@a = {{b}}\n@b = {{a}}\n@c = {{nope}}/x\n\nGET {{a}}/{{c}}\n";
        let reqs = parse_requests(text);
        let (_, missing) = resolve(&reqs[0], &variables(text, BTreeMap::new()));
        assert!(missing.contains(&String::from("a")), "{missing:?}");
        assert!(missing.contains(&String::from("nope")), "{missing:?}");

        let mut bomb = String::new();
        for i in 0..30 {
            bomb.push_str(&format!(
                "@v{i} = {{{{v{}}}}}{{{{v{}}}}}{{{{v{}}}}}\n",
                i + 1,
                i + 1,
                i + 1
            ));
        }
        bomb.push_str("@v30 = x\nGET http://h/{{v0}}\n");
        let started = std::time::Instant::now();
        let reqs = parse_requests(&bomb);
        let (_, missing) = resolve(&reqs[0], &variables(&bomb, BTreeMap::new()));
        assert!(
            !missing.is_empty(),
            "past the budget a name counts as unresolved"
        );
        assert!(started.elapsed() < std::time::Duration::from_secs(2));
    }

    /// Negative: only `@name = value` before a request line is a variable.
    /// A body or header starting with `@`, an `@` line with no `=`, and a
    /// `# @name` request-name comment are left as they were.
    #[test]
    fn only_a_variable_line_before_the_request_is_a_variable() {
        let text =
            "POST http://h/x\nX-At: @me\n\n@body = not a var\n\n###\n# @name login\n@notavar\n";
        assert!(
            file_variables(text).is_empty(),
            "{:?}",
            file_variables(text)
        );
        let reqs = parse_requests(text);
        assert_eq!(reqs.len(), 2);
        assert_eq!(reqs[0].body.as_deref(), Some("@body = not a var"));
        assert_eq!(reqs[0].headers[0].1, "@me");
        assert_eq!(
            reqs[1].url, "@notavar",
            "no `=`: still a (bad) request line"
        );
        // `.http.env.json` alone resolves exactly as before.
        let env = BTreeMap::from([(String::from("host"), String::from("http://x"))]);
        let reqs = parse_requests("GET {{host}}/a\n");
        let (resolved, missing) = resolve(&reqs[0], &variables("GET {{host}}/a\n", env));
        assert!(missing.is_empty());
        assert_eq!(resolved.url, "http://x/a");
    }
}