xbp 10.46.0

XBP is a zero-config build pack that can also interact with proxies, kafka, sockets, synthetic monitors.
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
use std::collections::HashMap;
use std::fs;
use std::path::Path;

pub const CLOUDFLARE_ACCOUNT_ID_ENV_KEYS: &[&str] =
    &["CLOUDFLARE_ACCOUNT_ID", "XBP_CLOUDFLARE_ACCOUNT_ID"];

/// Strip a leading UTF-8 BOM (U+FEFF). Editors on Windows often prepend this to
/// the first line of `.env`, which then becomes part of the first key name and
/// is rejected by providers like GitHub Actions variables.
pub fn strip_utf8_bom(content: &str) -> &str {
    content.strip_prefix('\u{feff}').unwrap_or(content)
}

/// Normalize an env key: trim whitespace, strip BOM / zero-width junk.
pub fn normalize_env_key(raw: &str) -> String {
    let stripped = strip_utf8_bom(raw.trim());
    stripped
        .chars()
        .filter(|ch| {
            // Keep normal identifier characters; drop invisible format chars that
            // sneak in via BOM / copy-paste (ZWSP, ZWNJ, etc.).
            !matches!(
                ch,
                '\u{200b}' | '\u{200c}' | '\u{200d}' | '\u{2060}' | '\u{feff}'
            )
        })
        .collect::<String>()
        .trim()
        .to_string()
}

/// Normalize a raw `.env` value:
/// - strip matching outer single/double quotes
/// - expand escapes in double-quoted values (`\n`, `\r`, `\t`, `\\`, `\"`, `\'`, `\0`)
/// - leave single-quoted values mostly literal (ideal for JSON payloads)
/// - still unwrap a single redundant nested quote layer when it wraps the whole value
pub fn normalize_env_value(raw: &str) -> String {
    let trimmed = strip_utf8_bom(raw.trim());
    if trimmed.is_empty() {
        return String::new();
    }

    match detect_quote_style(trimmed) {
        QuoteStyle::Double => {
            let inner = unwrap_outer_quotes(trimmed, '"');
            expand_double_quoted_escapes(&inner)
        }
        QuoteStyle::Single => {
            let inner = unwrap_outer_quotes(trimmed, '\'');
            // Single-quoted dotenv values are literal (JSON-friendly). Only unwrap
            // one extra full-wrap of double quotes when the entire payload is `"..."`.
            unwrap_full_double_wrap_if_present(&inner)
        }
        QuoteStyle::Unquoted => trimmed.to_string(),
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum QuoteStyle {
    Double,
    Single,
    Unquoted,
}

fn detect_quote_style(value: &str) -> QuoteStyle {
    let mut chars = value.chars();
    match chars.next() {
        Some('"') => QuoteStyle::Double,
        Some('\'') => QuoteStyle::Single,
        _ => QuoteStyle::Unquoted,
    }
}

fn unwrap_outer_quotes(value: &str, quote: char) -> String {
    let trimmed = value.trim();
    if trimmed.len() >= 2 && trimmed.starts_with(quote) && ends_with_unescaped_quote(trimmed, quote)
    {
        trimmed[quote.len_utf8()..trimmed.len() - quote.len_utf8()].to_string()
    } else if trimmed.len() >= 2 && trimmed.starts_with(quote) && trimmed.ends_with(quote) {
        // Fallback for values that already had the closing quote collected.
        trimmed[quote.len_utf8()..trimmed.len() - quote.len_utf8()].to_string()
    } else {
        trimmed.to_string()
    }
}

fn unwrap_full_double_wrap_if_present(value: &str) -> String {
    let trimmed = value.trim();
    if trimmed.len() >= 2
        && trimmed.starts_with('"')
        && ends_with_unescaped_quote(trimmed, '"')
        && is_fully_double_quoted(trimmed)
    {
        expand_double_quoted_escapes(&trimmed[1..trimmed.len() - 1])
    } else {
        // Preserve literal content including JSON with embedded double quotes.
        trimmed.to_string()
    }
}

/// True when the entire string is one double-quoted scalar (no unescaped `"` inside
/// except the outer pair). Used to peel `'"hello"'` style nesting without breaking JSON.
fn is_fully_double_quoted(value: &str) -> bool {
    if !value.starts_with('"') || value.len() < 2 {
        return false;
    }
    match find_closing_quote_index(value, '"') {
        Some(end) => end + 1 == value.len(),
        None => false,
    }
}

fn ends_with_unescaped_quote(value: &str, quote: char) -> bool {
    if !value.ends_with(quote) {
        return false;
    }
    // Count trailing backslashes before the final quote (double-quoted only).
    if quote != '"' {
        return true;
    }
    let bytes = value.as_bytes();
    let mut slash_count = 0usize;
    for byte in bytes[..bytes.len() - 1].iter().rev() {
        if *byte == b'\\' {
            slash_count += 1;
        } else {
            break;
        }
    }
    slash_count % 2 == 0
}

/// Expand common dotenv / shell double-quoted escapes.
fn expand_double_quoted_escapes(input: &str) -> String {
    let mut out = String::with_capacity(input.len());
    let mut chars = input.chars().peekable();

    while let Some(ch) = chars.next() {
        if ch != '\\' {
            out.push(ch);
            continue;
        }

        match chars.next() {
            Some('n') => out.push('\n'),
            Some('r') => out.push('\r'),
            Some('t') => out.push('\t'),
            Some('0') => out.push('\0'),
            Some('\\') => out.push('\\'),
            Some('"') => out.push('"'),
            Some('\'') => out.push('\''),
            // Keep unknown escapes as the escaped character (dotenv-like).
            Some(other) => out.push(other),
            // Trailing lone backslash.
            None => out.push('\\'),
        }
    }

    out
}

/// True when the line is a full-line env comment and must be ignored entirely.
/// A line is a comment when, after BOM strip + trim, it is empty or starts with `#`.
pub fn is_env_comment_line(line: &str) -> bool {
    let trimmed = strip_utf8_bom(line.trim());
    trimmed.is_empty() || trimmed.starts_with('#')
}

pub fn parse_env_content(content: &str) -> HashMap<String, String> {
    let mut result = HashMap::new();
    let mut lines = strip_utf8_bom(content).lines().peekable();

    while let Some(line) = lines.next() {
        // Full-line comments: `# ...` (any leading whitespace) — drop the whole line.
        if is_env_comment_line(line) {
            continue;
        }

        let mut trimmed = strip_utf8_bom(line.trim());

        if let Some(rest) = trimmed
            .strip_prefix("export ")
            .or_else(|| trimmed.strip_prefix("export\t"))
        {
            trimmed = rest.trim();
            // `export # comment` or `export` alone
            if is_env_comment_line(trimmed) {
                continue;
            }
        }

        let Some((key, value)) = trimmed.split_once('=') else {
            continue;
        };

        let key = normalize_env_key(key);
        // Keys must not start with `#` (defensive; comment lines already skipped).
        if key.is_empty() || key.starts_with('#') {
            continue;
        }

        let raw_value = collect_env_value(value, &mut lines);
        result.insert(key, normalize_env_value(&raw_value));
    }

    result
}

/// Collect a value that may span multiple lines when wrapped in quotes, including
/// multi-line JSON objects like:
/// ```text
/// AMOUNT='{
///   "currency": "EUR",
///   "value": "10.00"
/// }'
/// ```
fn collect_env_value<'a, I>(first_line_value: &str, lines: &mut std::iter::Peekable<I>) -> String
where
    I: Iterator<Item = &'a str>,
{
    let leading = first_line_value.to_string();
    let trimmed_start = leading.trim_start();
    let Some(quote) = starts_with_quote(trimmed_start) else {
        // Unquoted: single line only (inline `#` comments stripped).
        return strip_unquoted_inline_comment(first_line_value.trim()).to_string();
    };

    // Preserve original spacing after `=`; only the value body matters after normalize.
    let mut raw = leading;
    while !quoted_value_is_complete(&raw, quote) {
        let Some(next_line) = lines.next() else {
            break;
        };
        raw.push('\n');
        raw.push_str(next_line);
    }
    raw
}

fn strip_unquoted_inline_comment(value: &str) -> &str {
    // Only treat ` #` as a comment start so `FOO=bar#baz` stays intact.
    match value.find(" #") {
        Some(idx) => value[..idx].trim_end(),
        None => value,
    }
}

fn starts_with_quote(value: &str) -> Option<char> {
    value
        .chars()
        .next()
        .filter(|quote| *quote == '"' || *quote == '\'')
}

fn quoted_value_is_complete(value: &str, quote: char) -> bool {
    let trimmed = value.trim_start();
    if !trimmed.starts_with(quote) {
        return true;
    }
    find_closing_quote_index(trimmed, quote).is_some()
}

/// Index of the closing quote that matches the opening quote at `value[0]`.
/// For double quotes, `\"` does not terminate. Single quotes are literal (no escapes),
/// so the first later `'` closes — standard dotenv / bash single-quote rules.
fn find_closing_quote_index(value: &str, quote: char) -> Option<usize> {
    let mut chars = value.char_indices();
    let Some((_, first)) = chars.next() else {
        return None;
    };
    if first != quote {
        return None;
    }

    let mut escaped = false;
    for (idx, ch) in chars {
        if quote == '"' {
            if escaped {
                escaped = false;
                continue;
            }
            if ch == '\\' {
                escaped = true;
                continue;
            }
        }
        if ch == quote {
            return Some(idx);
        }
    }
    None
}

pub fn parse_env_file(path: &Path) -> Result<HashMap<String, String>, String> {
    let content = fs::read_to_string(path)
        .map_err(|e| format!("Failed to read {}: {}", path.display(), e))?;
    Ok(parse_env_content(&content))
}

/// Peel redundant outer quote layers until the logical value is left.
///
/// Handles nested dotenv wrappers such as `"'SECRET'"`, `'"SECRET"'`, and
/// `"\"SECRET\""` so writers never re-emit quote garbage around secrets.
pub fn canonicalize_env_value(raw: &str) -> String {
    let mut current = strip_utf8_bom(raw.trim()).to_string();
    for _ in 0..8 {
        let next = normalize_env_value(&current);
        if next == current {
            break;
        }
        current = next;
    }
    current
}

/// Escape a logical env value for double-quoted dotenv form.
///
/// Newlines stay as real newlines (valid multi-line dotenv, readable PEMs).
/// Only `\` and `"` are escaped so parse/expand round-trips cleanly.
pub fn escape_env_value_double_quoted(value: &str) -> String {
    let mut out = String::with_capacity(value.len() + 8);
    for ch in value.chars() {
        match ch {
            '\\' => out.push_str("\\\\"),
            '"' => out.push_str("\\\""),
            other => out.push(other),
        }
    }
    out
}

/// Always wrap in double quotes after canonicalizing (peeling nested quotes).
///
/// Default write style for `xbp secrets pull` and other env emitters.
pub fn format_env_value_double_quoted(raw: &str) -> String {
    let canonical = canonicalize_env_value(raw);
    format!("\"{}\"", escape_env_value_double_quoted(&canonical))
}

/// One dotenv assignment line: `KEY="value"` (no trailing newline).
pub fn format_env_assignment(key: &str, value: &str) -> String {
    format!(
        "{}={}",
        normalize_env_key(key),
        format_env_value_double_quoted(value)
    )
}

/// Serialize key/value pairs to dotenv text with sorted keys and trailing newline.
pub fn format_env_file_content<'a, I, K, V>(entries: I) -> String
where
    I: IntoIterator<Item = (K, V)>,
    K: AsRef<str> + 'a,
    V: AsRef<str> + 'a,
{
    let mut pairs: Vec<(String, String)> = entries
        .into_iter()
        .map(|(k, v)| (normalize_env_key(k.as_ref()), v.as_ref().to_string()))
        .filter(|(k, _)| !k.is_empty() && !k.starts_with('#'))
        .collect();
    pairs.sort_by(|a, b| a.0.cmp(&b.0));

    let mut content = String::new();
    for (key, value) in pairs {
        content.push_str(&format_env_assignment(&key, &value));
        content.push('\n');
    }
    content
}

pub fn to_env_references(vars: &HashMap<String, String>) -> HashMap<String, String> {
    vars.keys()
        .map(|key| (key.clone(), format!("${{{}}}", key)))
        .collect()
}

pub fn resolve_env_placeholders(
    project_root: &Path,
    envs: &HashMap<String, String>,
) -> HashMap<String, String> {
    let lookup = load_env_lookup(project_root);

    envs.iter()
        .map(|(key, value)| {
            let resolved = env_reference_name(value)
                .and_then(|name| lookup.get(name).cloned())
                .unwrap_or_else(|| value.clone());
            (key.clone(), resolved)
        })
        .collect()
}

pub fn first_lookup_value(lookup: &HashMap<String, String>, keys: &[&str]) -> Option<String> {
    keys.iter()
        .find_map(|key| lookup.get(*key))
        .map(|value| normalize_env_value(value))
        .filter(|value| !value.is_empty())
}

pub fn load_env_lookup(project_root: &Path) -> HashMap<String, String> {
    let mut lookup = HashMap::new();

    for name in [".env", ".env.local", ".env.development", ".env.production"] {
        let path = project_root.join(name);
        if !path.exists() {
            continue;
        }

        if let Ok(parsed) = parse_env_file(&path) {
            lookup.extend(parsed);
        }
    }

    lookup.extend(std::env::vars());
    lookup
}

/// Preferred local env file for secrets written by project setup wizards.
///
/// Rust workspaces default to `.env`; other stacks default to `.env.local`.
pub fn preferred_local_secret_env_path(project_root: &Path) -> std::path::PathBuf {
    let is_rust = project_root.join("Cargo.toml").exists() || project_root.join("crates").is_dir();
    if is_rust {
        project_root.join(".env")
    } else {
        project_root.join(".env.local")
    }
}

/// Upsert `KEY=value` into a dotenv file, replacing an existing assignment for `key`.
///
/// Creates the file (and parent directory) when missing. Comments and unrelated
/// keys are preserved; multi-line values are not specially rewritten (callers
/// should pass single-line secrets such as webhook URLs).
pub fn upsert_env_key(path: &Path, key: &str, value: &str) -> Result<(), String> {
    let key = normalize_env_key(key);
    if key.is_empty() {
        return Err("Env key must not be empty".to_string());
    }
    let assignment = format_env_assignment(&key, value);

    let existing = if path.exists() {
        fs::read_to_string(path)
            .map_err(|e| format!("Failed to read {}: {e}", path.display()))?
    } else {
        String::new()
    };
    let content = strip_utf8_bom(&existing);

    let mut out_lines: Vec<String> = Vec::new();
    let mut replaced = false;
    for line in content.lines() {
        let trimmed = strip_utf8_bom(line.trim());
        if is_env_comment_line(trimmed) {
            out_lines.push(line.to_string());
            continue;
        }
        let candidate = trimmed
            .strip_prefix("export ")
            .or_else(|| trimmed.strip_prefix("export\t"))
            .map(str::trim)
            .unwrap_or(trimmed);
        if let Some((raw_key, _)) = candidate.split_once('=') {
            if normalize_env_key(raw_key) == key {
                out_lines.push(assignment.clone());
                replaced = true;
                continue;
            }
        }
        out_lines.push(line.to_string());
    }
    if !replaced {
        if let Some(last) = out_lines.last() {
            if !last.is_empty() {
                // keep a blank separation only when appending after content
            }
        }
        out_lines.push(assignment);
    }

    let mut out = out_lines.join("\n");
    if !out.ends_with('\n') {
        out.push('\n');
    }

    if let Some(parent) = path.parent() {
        if !parent.as_os_str().is_empty() {
            fs::create_dir_all(parent)
                .map_err(|e| format!("Failed to create {}: {e}", parent.display()))?;
        }
    }
    fs::write(path, out).map_err(|e| format!("Failed to write {}: {e}", path.display()))?;
    Ok(())
}

fn env_reference_name(value: &str) -> Option<&str> {
    let trimmed = value.trim();
    if let Some(name) = trimmed
        .strip_prefix("${")
        .and_then(|rest| rest.strip_suffix('}'))
    {
        return (!name.trim().is_empty()).then_some(name.trim());
    }

    trimmed
        .strip_prefix('$')
        .map(str::trim)
        .filter(|name| !name.is_empty())
}

#[cfg(test)]
mod tests {
    use super::{
        canonicalize_env_value, expand_double_quoted_escapes, format_env_assignment,
        format_env_file_content, format_env_value_double_quoted, is_env_comment_line,
        normalize_env_key, normalize_env_value, parse_env_content, resolve_env_placeholders,
        to_env_references,
    };
    use std::collections::HashMap;
    use std::fs;
    use std::path::PathBuf;

    fn make_temp_dir(label: &str) -> PathBuf {
        let nanos = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .expect("system clock should be after epoch")
            .as_nanos();
        let dir = std::env::temp_dir().join(format!("xbp-env-files-{label}-{nanos}"));
        fs::create_dir_all(&dir).expect("temp dir should be created");
        dir
    }

    #[test]
    fn normalize_env_value_strips_redundant_wrapping_quotes() {
        assert_eq!(normalize_env_value(r#""hello""#), "hello");
        assert_eq!(normalize_env_value("'hello'"), "hello");
        assert_eq!(normalize_env_value(r#"'\"hello\"'"#), r#"\"hello\""#);
        assert_eq!(normalize_env_value("''hello''"), "'hello'");
        assert_eq!(normalize_env_value("hello"), "hello");
    }

    #[test]
    fn normalize_env_value_expands_double_quoted_escapes() {
        assert_eq!(normalize_env_value(r#""line1\nline2""#), "line1\nline2");
        assert_eq!(normalize_env_value(r#""a\tb\r\nc\\d""#), "a\tb\r\nc\\d");
        assert_eq!(normalize_env_value(r#""say \"hi\"""#), "say \"hi\"");
        assert_eq!(
            expand_double_quoted_escapes(r#"hello\nworld"#),
            "hello\nworld"
        );
    }

    #[test]
    fn normalize_env_value_keeps_single_quoted_json_literal() {
        let raw = r#"'{"column": "value", "column2": "value2"}'"#;
        assert_eq!(
            normalize_env_value(raw),
            r#"{"column": "value", "column2": "value2"}"#
        );

        // Single-quoted: `\n` stays literal (JSON / bash style).
        assert_eq!(
            normalize_env_value(r#"'{"note":"a\nb"}'"#),
            r#"{"note":"a\nb"}"#
        );
    }

    #[test]
    fn parse_env_content_supports_json_amount_style_values() {
        let parsed = parse_env_content(
            r#"
AMOUNT='{"currency":"EUR","value":"10.00"}'
NESTED='{"column": "value", "column2": "value2"}'
ESCAPED_JSON="{\"currency\":\"EUR\",\"value\":\"10.00\"}"
CURRENCY="EUR"
"#,
        );

        assert_eq!(
            parsed.get("AMOUNT"),
            Some(&r#"{"currency":"EUR","value":"10.00"}"#.to_string())
        );
        assert_eq!(
            parsed.get("NESTED"),
            Some(&r#"{"column": "value", "column2": "value2"}"#.to_string())
        );
        assert_eq!(
            parsed.get("ESCAPED_JSON"),
            Some(&r#"{"currency":"EUR","value":"10.00"}"#.to_string())
        );
        assert_eq!(parsed.get("CURRENCY"), Some(&"EUR".to_string()));
    }

    #[test]
    fn parse_env_content_supports_multiline_json() {
        let parsed = parse_env_content(
            r#"
AMOUNT='{
  "currency": "EUR",
  "value": "10.00"
}'
NEXT=ok
"#,
        );

        let amount = parsed.get("AMOUNT").expect("AMOUNT");
        assert!(amount.contains("\"currency\": \"EUR\""));
        assert!(amount.contains("\"value\": \"10.00\""));
        assert!(amount.starts_with('{'));
        assert!(amount.ends_with('}'));
        assert_eq!(parsed.get("NEXT"), Some(&"ok".to_string()));
    }

    #[test]
    fn parse_env_content_expands_double_quoted_newlines() {
        let parsed = parse_env_content(
            r#"
NOTE="hello\nworld"
MULTI="line1
line2"
"#,
        );
        assert_eq!(parsed.get("NOTE"), Some(&"hello\nworld".to_string()));
        assert_eq!(parsed.get("MULTI"), Some(&"line1\nline2".to_string()));
    }

    #[test]
    fn parse_env_content_normalizes_quotes_and_exports() {
        let parsed = parse_env_content(
            r#"
                export FIRST='"hello"'
                SECOND='world'
                THIRD=plain
            "#,
        );

        assert_eq!(parsed.get("FIRST"), Some(&"hello".to_string()));
        assert_eq!(parsed.get("SECOND"), Some(&"world".to_string()));
        assert_eq!(parsed.get("THIRD"), Some(&"plain".to_string()));
    }

    #[test]
    fn parse_env_content_dismisses_full_line_hash_comments() {
        assert!(is_env_comment_line("# pure comment"));
        assert!(is_env_comment_line("   # indented comment"));
        assert!(is_env_comment_line("\u{feff}# bom comment"));
        assert!(!is_env_comment_line("KEY=value"));
        assert!(!is_env_comment_line("KEY=#not-a-line-comment"));

        let parsed = parse_env_content(
            r#"
# EXAMPLE DRIVEN VARS
# PROFILE_ID="pfl_YwS9pVTnEy"  # disabled entirely
  # indented comment with KEY=looks_like_assignment
export # bare export comment
MOLLIE_API_KEY="live_xxx"
CURRENCY="EUR"
# TRAILING=should_not_parse
"#,
        );

        assert_eq!(parsed.len(), 2);
        assert_eq!(parsed.get("MOLLIE_API_KEY"), Some(&"live_xxx".to_string()));
        assert_eq!(parsed.get("CURRENCY"), Some(&"EUR".to_string()));
        assert!(!parsed.contains_key("PROFILE_ID"));
        assert!(!parsed.contains_key("TRAILING"));
        assert!(!parsed.contains_key("KEY"));
    }

    #[test]
    fn parse_env_content_strips_utf8_bom_from_first_key() {
        // Windows editors often save .env with a leading BOM; GitHub then rejects
        // the first key because the name starts with U+FEFF.
        let parsed = parse_env_content("\u{feff}MOLLIE_API_KEY=\"secret\"\nCURRENCY=EUR\n");
        assert!(parsed.contains_key("MOLLIE_API_KEY"));
        assert!(!parsed.keys().any(|k| k.starts_with('\u{feff}')));
        assert_eq!(parsed.get("MOLLIE_API_KEY"), Some(&"secret".to_string()));
        assert_eq!(parsed.get("CURRENCY"), Some(&"EUR".to_string()));
    }

    #[test]
    fn normalize_env_key_strips_bom_and_zero_width() {
        assert_eq!(normalize_env_key("\u{feff}MOLLIE_API_KEY"), "MOLLIE_API_KEY");
        assert_eq!(
            normalize_env_key("MOL\u{200b}LIE_API_KEY"),
            "MOLLIE_API_KEY"
        );
    }

    #[test]
    fn parse_env_content_preserves_multiline_quoted_values() {
        let parsed = parse_env_content(
            r#"APP_ID="2995603"
APP_PRIVATE_KEY="-----BEGIN RSA PRIVATE KEY-----
line-1
line-2
-----END RSA PRIVATE KEY-----"
DISABLE_AUTO_UPDATE="true""#,
        );

        assert_eq!(parsed.get("APP_ID"), Some(&"2995603".to_string()));
        assert_eq!(
            parsed.get("APP_PRIVATE_KEY"),
            Some(
                &"-----BEGIN RSA PRIVATE KEY-----\nline-1\nline-2\n-----END RSA PRIVATE KEY-----"
                    .to_string()
            )
        );
        assert_eq!(parsed.get("DISABLE_AUTO_UPDATE"), Some(&"true".to_string()));
    }

    #[test]
    fn canonicalize_env_value_peels_nested_quote_wrappers() {
        assert_eq!(canonicalize_env_value(r#""hello""#), "hello");
        assert_eq!(canonicalize_env_value("'hello'"), "hello");
        assert_eq!(canonicalize_env_value(r#"'"hello"'"#), "hello");
        assert_eq!(canonicalize_env_value(r#""'hello'""#), "hello");
        assert_eq!(canonicalize_env_value(r#""\"hello\"""#), "hello");
        assert_eq!(canonicalize_env_value("plain"), "plain");
        // JSON-shaped single-quoted payloads keep outer braces after peel.
        assert_eq!(
            canonicalize_env_value(r#"'{"a":"b"}'"#),
            r#"{"a":"b"}"#
        );
    }

    #[test]
    fn format_env_value_always_double_quotes_and_avoids_nested_garbage() {
        assert_eq!(format_env_value_double_quoted("secret"), r#""secret""#);
        assert_eq!(format_env_value_double_quoted(r#""secret""#), r#""secret""#);
        assert_eq!(format_env_value_double_quoted("'secret'"), r#""secret""#);
        assert_eq!(
            format_env_value_double_quoted(r#""'secret'""#),
            r#""secret""#
        );
        assert_eq!(
            format_env_value_double_quoted(r#"'"secret"'"#),
            r#""secret""#
        );
        assert_eq!(
            format_env_value_double_quoted(r#"say "hi""#),
            r#""say \"hi\"""#
        );
        assert_eq!(
            format_env_value_double_quoted("path\\to"),
            r#""path\\to""#
        );
    }

    #[test]
    fn format_env_assignment_multiline_pem_round_trips() {
        let pem = "-----BEGIN RSA PRIVATE KEY-----\nMIIEline1\nMIIEline2\n-----END RSA PRIVATE KEY-----";
        let line = format_env_assignment("APP_PRIVATE_KEY", pem);
        assert!(line.starts_with("APP_PRIVATE_KEY=\""));
        assert!(line.ends_with('"'));
        assert!(line.contains('\n'));
        assert!(!line.contains(r#"'"#));
        assert!(!line.contains("\"'"));

        let file = format!("{line}\nAPP_ID=\"2995603\"\n");
        let parsed = parse_env_content(&file);
        assert_eq!(parsed.get("APP_PRIVATE_KEY"), Some(&pem.to_string()));
        assert_eq!(parsed.get("APP_ID"), Some(&"2995603".to_string()));
    }

    #[test]
    fn format_env_file_content_sorts_and_quotes_all_values() {
        let content = format_env_file_content([
            ("ZZ_LAST", "z"),
            ("APP_ID", "2995603"),
            ("APP_PRIVATE_KEY", "-----BEGIN\nKEY\n-----END"),
            ("NESTED", r#""'already-wrapped'""#),
        ]);
        let parsed = parse_env_content(&content);
        assert_eq!(parsed.get("APP_ID"), Some(&"2995603".to_string()));
        assert_eq!(
            parsed.get("APP_PRIVATE_KEY"),
            Some(&"-----BEGIN\nKEY\n-----END".to_string())
        );
        assert_eq!(parsed.get("NESTED"), Some(&"already-wrapped".to_string()));
        assert_eq!(parsed.get("ZZ_LAST"), Some(&"z".to_string()));

        // Every assignment is double-quoted; no nested quote soup on NESTED.
        assert!(content.contains("NESTED=\"already-wrapped\"\n"));
        assert!(content.contains("APP_PRIVATE_KEY=\"-----BEGIN\nKEY\n-----END\"\n"));
        let keys: Vec<&str> = content
            .lines()
            .filter_map(|l| l.split_once('=').map(|(k, _)| k))
            .collect();
        assert_eq!(keys, vec!["APP_ID", "APP_PRIVATE_KEY", "NESTED", "ZZ_LAST"]);
    }

    #[test]
    fn parse_env_content_preserves_multiline_exported_values() {
        let parsed = parse_env_content(
            r#"export GITHUB_APP_PRIVATE_KEY="-----BEGIN KEY-----
abc123
-----END KEY-----""#,
        );

        assert_eq!(
            parsed.get("GITHUB_APP_PRIVATE_KEY"),
            Some(&"-----BEGIN KEY-----\nabc123\n-----END KEY-----".to_string())
        );
    }

    #[test]
    fn to_env_references_maps_values_to_placeholders() {
        let mut vars = HashMap::new();
        vars.insert("DATABASE_URL".to_string(), "postgres://demo".to_string());

        let refs = to_env_references(&vars);
        assert_eq!(
            refs.get("DATABASE_URL"),
            Some(&"${DATABASE_URL}".to_string())
        );
    }

    #[test]
    fn first_lookup_value_reads_cloudflare_account_id_aliases() {
        use super::{first_lookup_value, CLOUDFLARE_ACCOUNT_ID_ENV_KEYS};

        let mut lookup = HashMap::new();
        lookup.insert(
            "XBP_CLOUDFLARE_ACCOUNT_ID".to_string(),
            "acc-from-xbp-key".to_string(),
        );

        assert_eq!(
            first_lookup_value(&lookup, CLOUDFLARE_ACCOUNT_ID_ENV_KEYS).as_deref(),
            Some("acc-from-xbp-key")
        );
    }

    #[test]
    fn resolve_env_placeholders_reads_local_env_files() {
        let project_root = make_temp_dir("resolve-placeholders");
        fs::write(
            project_root.join(".env.local"),
            "DATABASE_URL='postgres://demo'\nAPI_KEY='\"secret\"'\n",
        )
        .expect("env file should be written");

        let mut envs = HashMap::new();
        envs.insert("DATABASE_URL".to_string(), "${DATABASE_URL}".to_string());
        envs.insert("API_KEY".to_string(), "${API_KEY}".to_string());
        envs.insert("NODE_ENV".to_string(), "production".to_string());

        let resolved = resolve_env_placeholders(&project_root, &envs);
        assert_eq!(
            resolved.get("DATABASE_URL"),
            Some(&"postgres://demo".to_string())
        );
        assert_eq!(resolved.get("API_KEY"), Some(&"secret".to_string()));
        assert_eq!(resolved.get("NODE_ENV"), Some(&"production".to_string()));

        let _ = fs::remove_dir_all(project_root);
    }

    #[test]
    fn preferred_local_secret_env_path_prefers_dotenv_for_rust() {
        use super::preferred_local_secret_env_path;

        let rust_root = make_temp_dir("rust-env");
        fs::write(rust_root.join("Cargo.toml"), "[package]\nname=\"demo\"\n").unwrap();
        assert_eq!(
            preferred_local_secret_env_path(&rust_root),
            rust_root.join(".env")
        );
        let _ = fs::remove_dir_all(rust_root);

        let node_root = make_temp_dir("node-env");
        fs::write(node_root.join("package.json"), "{}\n").unwrap();
        assert_eq!(
            preferred_local_secret_env_path(&node_root),
            node_root.join(".env.local")
        );
        let _ = fs::remove_dir_all(node_root);
    }

    #[test]
    fn upsert_env_key_creates_and_replaces() {
        use super::{parse_env_file, upsert_env_key};

        let dir = make_temp_dir("upsert-env");
        let path = dir.join(".env");
        upsert_env_key(&path, "DISCORD_WEBHOOK_URL", "https://example.com/a").unwrap();
        upsert_env_key(&path, "OTHER", "keep-me").unwrap();
        upsert_env_key(&path, "DISCORD_WEBHOOK_URL", "https://example.com/b").unwrap();

        let parsed = parse_env_file(&path).unwrap();
        assert_eq!(
            parsed.get("DISCORD_WEBHOOK_URL").map(String::as_str),
            Some("https://example.com/b")
        );
        assert_eq!(parsed.get("OTHER").map(String::as_str), Some("keep-me"));
        let raw = fs::read_to_string(&path).unwrap();
        assert_eq!(raw.matches("DISCORD_WEBHOOK_URL=").count(), 1);
        let _ = fs::remove_dir_all(dir);
    }
}