xbp 10.40.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
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
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
use crate::strategies::{
    get_all_workers, get_worker_by_name, normalize_config_paths_for_persistence,
    resolve_config_paths_for_runtime, WorkerConfig, XbpConfig,
};
use crate::utils::{find_xbp_config_upwards, parse_config_with_auto_heal};
use regex::Regex;
use serde_json::{json, Value};
use std::collections::HashMap;
use std::env;
use std::fs;
use std::path::{Path, PathBuf};
use walkdir::WalkDir;

const DEFAULT_WORKER_NAME: &str = "xbp";
const KNOWN_WORKER_APP_DIRS: &[&str] = &["apps/web", "apps/api", "apps/pkg"];

#[derive(Debug, Clone)]
pub struct DiscoveredWorkerApp {
    pub label: String,
    pub root: PathBuf,
    pub base_script_name: String,
    pub config: Option<WorkerConfig>,
}

#[derive(Debug, Clone)]
pub struct WorkerTargetResolution {
    pub project_root: PathBuf,
    pub config_path: PathBuf,
    pub config: XbpConfig,
    pub selected: Vec<DiscoveredWorkerApp>,
}

pub fn pick_first_non_empty<I>(values: I) -> Option<String>
where
    I: IntoIterator<Item = Option<String>>,
{
    values
        .into_iter()
        .flatten()
        .map(|value| value.trim().to_string())
        .find(|value| !value.is_empty() && !value.starts_with('<'))
}

pub fn discover_worker_apps(start: &Path) -> Vec<DiscoveredWorkerApp> {
    let (project_root, config) = match load_project_config_from_start(start) {
        Ok((project_root, _, config)) => (project_root, Some(config)),
        Err(_) => (
            find_xbp_config_upwards(start)
                .map(|found| found.project_root)
                .unwrap_or_else(|| start.to_path_buf()),
            None,
        ),
    };

    discover_worker_apps_for_project(&project_root, config.as_ref())
}

pub fn discover_worker_apps_for_project(
    project_root: &Path,
    config: Option<&XbpConfig>,
) -> Vec<DiscoveredWorkerApp> {
    let mut apps = Vec::new();

    if let Some(config) = config {
        for worker in get_all_workers(config) {
            let root = PathBuf::from(&worker.root);
            if !looks_like_worker_root(&root) {
                continue;
            }
            push_worker_app(&mut apps, worker_app_from_config(&root, worker));
        }
    }

    for relative in KNOWN_WORKER_APP_DIRS {
        let candidate = project_root.join(relative);
        if !looks_like_worker_root(&candidate)
            || apps.iter().any(|app| path_eq(&app.root, &candidate))
        {
            continue;
        }
        let label = relative
            .split('/')
            .next_back()
            .unwrap_or(relative)
            .to_string();
        push_worker_app(&mut apps, worker_app_from_root(&candidate, label));
    }

    for candidate in scan_worker_roots(project_root) {
        if apps.iter().any(|app| path_eq(&app.root, &candidate)) {
            continue;
        }
        push_worker_app(
            &mut apps,
            worker_app_from_root(&candidate, infer_worker_label(&candidate, project_root)),
        );
    }

    if looks_like_worker_root(project_root)
        && !apps.iter().any(|app| path_eq(&app.root, project_root))
    {
        push_worker_app(
            &mut apps,
            worker_app_from_root(project_root, "worker".to_string()),
        );
    }

    apps.sort_by(|left, right| left.label.cmp(&right.label));
    apps
}

pub fn resolve_worker_targets(
    start: &Path,
    root_override: Option<&Path>,
    app_override: Option<&str>,
    all: bool,
) -> Result<WorkerTargetResolution, String> {
    let start = root_override
        .map(Path::to_path_buf)
        .unwrap_or_else(|| start.to_path_buf());
    let (project_root, config_path, config) = load_project_config_from_start(&start)?;
    let apps = discover_worker_apps_for_project(&project_root, Some(&config));

    if apps.is_empty() {
        return Err(format!(
            "No Worker apps were found for {}. Add a `workers:` section to {} or run `xbp workers deploy configure --write-config`.",
            project_root.display(),
            config_path.display()
        ));
    }

    let selected = if all {
        apps.clone()
    } else if let Some(app_name) = app_override
        .map(str::trim)
        .filter(|value| !value.is_empty())
    {
        let selected = find_worker_app_by_alias(&apps, app_name)
            .or_else(|| {
                get_worker_by_name(&config, app_name).ok().and_then(|worker| {
                    apps.iter()
                        .find(|app| app.label == worker.name || app.base_script_name == worker.name)
                        .cloned()
                        .or_else(|| {
                            let root = PathBuf::from(&worker.root);
                            if looks_like_worker_root(&root) {
                                Some(worker_app_from_config(&root, worker))
                            } else {
                                None
                            }
                        })
                })
            })
            .ok_or_else(|| {
                format!(
                    "Worker app `{app_name}` was not found. Pass a configured workers[].name, directory label, wrangler script name, or custom domain. Known workers: {}",
                    format_worker_names(&apps)
                )
            })?;
        vec![selected]
    } else {
        match select_worker_for_current_dir(&start, &project_root, &apps) {
            Ok(app) => vec![app],
            Err(_) if apps.len() == 1 => vec![apps[0].clone()],
            Err(message) => return Err(message),
        }
    };

    Ok(WorkerTargetResolution {
        project_root,
        config_path,
        config,
        selected,
    })
}

/// Ensure every selected Worker has a `workers:` entry in `.xbp/xbp.yaml`.
///
/// Disk-discovered apps (path / Wrangler name / routes) are materialised automatically so
/// `xbp cloudflare doctor` and `xbp workers *` work from an app directory without a manual
/// `init` / `configure --write-config` step first.
pub fn ensure_selected_workers_configured(
    resolution: &mut WorkerTargetResolution,
) -> Result<usize, String> {
    let mut discovered = Vec::new();
    for app in &resolution.selected {
        if app.config.is_some() {
            continue;
        }
        discovered.push(WorkerConfig {
            name: app.label.clone(),
            root: collapse_worker_root(&resolution.project_root, &app.root),
            script_name: Some(app.base_script_name.clone()),
            service: None,
            deploy: None,
            container: None,
            containers: None,
            durable_objects: None,
        });
    }

    if discovered.is_empty() {
        return Ok(0);
    }

    let inserted = upsert_worker_configs(&mut resolution.config, discovered);
    write_worker_configs_to_project(
        &resolution.project_root,
        &resolution.config_path,
        &mut resolution.config,
    )?;

    // Re-attach configs onto selected apps after persistence.
    for selected in &mut resolution.selected {
        if selected.config.is_some() {
            continue;
        }
        let matched = get_all_workers(&resolution.config).into_iter().find(|worker| {
            worker.name == selected.label
                || worker
                    .script_name
                    .as_deref()
                    .is_some_and(|name| name == selected.base_script_name)
                || {
                    let configured_root = PathBuf::from(&worker.root);
                    let absolute = if configured_root.is_absolute() {
                        configured_root.clone()
                    } else {
                        resolution.project_root.join(&configured_root)
                    };
                    path_eq(&absolute, &selected.root) || path_eq(&configured_root, &selected.root)
                }
        });
        if let Some(worker) = matched {
            *selected = worker_app_from_config(&selected.root, worker);
        }
    }

    Ok(inserted)
}

fn find_worker_app_by_alias(apps: &[DiscoveredWorkerApp], query: &str) -> Option<DiscoveredWorkerApp> {
    let query = query.trim();
    if query.is_empty() {
        return None;
    }
    let normalized = normalize_worker_alias(query);

    let mut matches = apps
        .iter()
        .filter(|app| {
            worker_app_aliases(app)
                .into_iter()
                .any(|alias| normalize_worker_alias(&alias) == normalized)
        })
        .cloned()
        .collect::<Vec<_>>();

    matches.sort_by(|left, right| left.label.cmp(&right.label));
    matches.dedup_by(|left, right| path_eq(&left.root, &right.root));
    if matches.len() == 1 {
        Some(matches.remove(0))
    } else {
        None
    }
}

fn worker_app_aliases(app: &DiscoveredWorkerApp) -> Vec<String> {
    let mut aliases = vec![app.label.clone(), app.base_script_name.clone()];
    if let Some(worker) = app.config.as_ref() {
        aliases.push(worker.name.clone());
        if let Some(script_name) = worker.script_name.as_ref() {
            aliases.push(script_name.clone());
        }
    }
    aliases.extend(read_worker_route_aliases(&app.root));
    aliases
        .into_iter()
        .map(|value| value.trim().to_string())
        .filter(|value| !value.is_empty())
        .collect()
}

fn read_worker_route_aliases(worker_root: &Path) -> Vec<String> {
    let mut aliases = Vec::new();

    for route in read_configured_custom_domain_routes(worker_root) {
        if let Some(pattern) = route.get("pattern").and_then(Value::as_str) {
            aliases.push(pattern.to_string());
        }
        if let Some(zone) = route.get("zone_name").and_then(Value::as_str) {
            aliases.push(zone.to_string());
        }
    }

    for config_name in ["wrangler.jsonc", "wrangler.json", "wrangler.toml"] {
        let path = worker_root.join(config_name);
        if !path.exists() {
            continue;
        }
        aliases.extend(read_route_aliases_from_wrangler_config(&path));
    }

    aliases
}

fn read_route_aliases_from_wrangler_config(path: &Path) -> Vec<String> {
    let Ok(content) = fs::read_to_string(path) else {
        return Vec::new();
    };

    // Prefer structured JSON/JSONC when available.
    if path
        .extension()
        .and_then(|value| value.to_str())
        .is_some_and(|ext| ext == "json" || ext == "jsonc")
    {
        let stripped = strip_jsonc_comments_light(&content);
        if let Ok(value) = serde_json::from_str::<Value>(&stripped) {
            let mut aliases = Vec::new();
            if let Some(name) = value.get("name").and_then(Value::as_str) {
                aliases.push(name.to_string());
            }
            push_route_value_aliases(value.get("route"), &mut aliases);
            push_route_value_aliases(value.get("routes"), &mut aliases);
            return aliases;
        }
    }

    // Fallback: regex over pattern/zone strings for TOML or unparsable JSONC.
    let mut aliases = Vec::new();
    let pattern_re =
        Regex::new(r#"(?i)(?:pattern|zone_name|zone)\s*[:=]\s*["']([^"']+)["']"#).expect("regex");
    for captures in pattern_re.captures_iter(&content) {
        if let Some(value) = captures.get(1) {
            aliases.push(value.as_str().to_string());
        }
    }
    aliases
}

fn push_route_value_aliases(value: Option<&Value>, aliases: &mut Vec<String>) {
    let Some(value) = value else {
        return;
    };
    match value {
        Value::String(pattern) => aliases.push(pattern.clone()),
        Value::Object(map) => {
            if let Some(pattern) = map.get("pattern").and_then(Value::as_str) {
                aliases.push(pattern.to_string());
            }
            if let Some(zone) = map
                .get("zone_name")
                .or_else(|| map.get("zone"))
                .and_then(Value::as_str)
            {
                aliases.push(zone.to_string());
            }
        }
        Value::Array(items) => {
            for item in items {
                push_route_value_aliases(Some(item), aliases);
            }
        }
        _ => {}
    }
}

fn normalize_worker_alias(value: &str) -> String {
    value
        .trim()
        .trim_start_matches("https://")
        .trim_start_matches("http://")
        .trim_end_matches('/')
        .to_ascii_lowercase()
}

/// Minimal JSONC stripper for alias discovery (comments + trailing commas).
fn strip_jsonc_comments_light(input: &str) -> String {
    let mut output = String::with_capacity(input.len());
    let bytes = input.as_bytes();
    let mut i = 0usize;
    let mut in_string = false;
    let mut escaped = false;
    while i < bytes.len() {
        let ch = bytes[i] as char;
        if in_string {
            output.push(ch);
            if escaped {
                escaped = false;
            } else if ch == '\\' {
                escaped = true;
            } else if ch == '"' {
                in_string = false;
            }
            i += 1;
            continue;
        }
        if ch == '"' {
            in_string = true;
            output.push(ch);
            i += 1;
            continue;
        }
        if ch == '/' && i + 1 < bytes.len() {
            let next = bytes[i + 1] as char;
            if next == '/' {
                i += 2;
                while i < bytes.len() && bytes[i] != b'\n' {
                    i += 1;
                }
                continue;
            }
            if next == '*' {
                i += 2;
                while i + 1 < bytes.len() && !(bytes[i] == b'*' && bytes[i + 1] == b'/') {
                    i += 1;
                }
                i = (i + 2).min(bytes.len());
                continue;
            }
        }
        output.push(ch);
        i += 1;
    }

    // Drop trailing commas before } or ].
    let mut cleaned = String::with_capacity(output.len());
    let chars: Vec<char> = output.chars().collect();
    let mut idx = 0usize;
    while idx < chars.len() {
        if chars[idx] == ',' {
            let mut look = idx + 1;
            while look < chars.len() && chars[look].is_whitespace() {
                look += 1;
            }
            if look < chars.len() && (chars[look] == '}' || chars[look] == ']') {
                idx += 1;
                continue;
            }
        }
        cleaned.push(chars[idx]);
        idx += 1;
    }
    cleaned
}

pub fn scan_worker_roots(project_root: &Path) -> Vec<PathBuf> {
    const SKIP_DIRS: &[&str] = &[
        ".git",
        ".xbp",
        "node_modules",
        "target",
        "dist",
        "build",
        ".next",
        ".open-next",
        ".wrangler",
        ".turbo",
        "coverage",
    ];

    let mut discovered = Vec::new();
    for entry in WalkDir::new(project_root)
        .follow_links(false)
        .into_iter()
        .filter_map(Result::ok)
        .filter(|entry| entry.file_type().is_dir())
    {
        let depth = entry.depth();
        if depth == 0 || depth > 6 {
            continue;
        }
        let relative_path = entry
            .path()
            .strip_prefix(project_root)
            .unwrap_or(entry.path());
        if relative_path.components().any(|component| {
            let name = component.as_os_str().to_string_lossy();
            SKIP_DIRS.iter().any(|skip| name == *skip)
        }) {
            continue;
        }
        let candidate = entry.into_path();
        if looks_like_worker_root(&candidate) {
            discovered.push(candidate);
        }
    }

    discovered.sort();
    discovered
}

pub fn discover_worker_configs_on_disk(project_root: &Path) -> Vec<WorkerConfig> {
    discover_worker_apps_for_project(project_root, None)
        .into_iter()
        .map(|app| WorkerConfig {
            name: app.label.clone(),
            root: collapse_worker_root(project_root, &app.root),
            script_name: Some(app.base_script_name),
            service: None,
            deploy: None,
            container: None,
            containers: None,
            durable_objects: None,
        })
        .collect()
}

pub fn upsert_worker_configs(config: &mut XbpConfig, discovered: Vec<WorkerConfig>) -> usize {
    let workers = config.workers.get_or_insert_with(Vec::new);
    let mut inserted = 0usize;

    for candidate in discovered {
        let existing_index = workers.iter().position(|existing| {
            existing.name == candidate.name
                || existing.root == candidate.root
                || existing
                    .script_name
                    .as_deref()
                    .is_some_and(|name| candidate.script_name.as_deref() == Some(name))
        });

        if let Some(index) = existing_index {
            let existing = workers.get_mut(index).expect("worker index");
            if existing.script_name.is_none() {
                existing.script_name = candidate.script_name;
            }
            if existing.service.is_none() {
                existing.service = candidate.service;
            }
            if existing.deploy.is_none() {
                existing.deploy = candidate.deploy;
            }
        } else {
            workers.push(candidate);
            inserted += 1;
        }
    }

    workers.sort_by(|left, right| left.name.cmp(&right.name));
    inserted
}

pub fn write_worker_configs_to_project(
    project_root: &Path,
    config_path: &Path,
    config: &mut XbpConfig,
) -> Result<(), String> {
    normalize_config_paths_for_persistence(config, project_root);
    let yaml = serde_yaml::to_string(config)
        .map_err(|error| format!("Failed to encode {}: {}", config_path.display(), error))?;
    fs::write(config_path, yaml).map_err(|error| {
        format!(
            "Failed to write worker config to {}: {}",
            config_path.display(),
            error
        )
    })
}

fn load_project_config_from_start(start: &Path) -> Result<(PathBuf, PathBuf, XbpConfig), String> {
    let found = find_xbp_config_upwards(start).ok_or_else(|| {
        format!(
            "Could not find .xbp/xbp.yaml from {}. Run `xbp setup` or pass `--root`.",
            start.display()
        )
    })?;
    let content = fs::read_to_string(&found.config_path)
        .map_err(|error| format!("Failed to read {}: {}", found.config_path.display(), error))?;
    let (mut config, healed_content) = parse_config_with_auto_heal(&content, found.kind)
        .map_err(|error| format!("Failed to parse {}: {}", found.config_path.display(), error))?;
    if let Some(healed_content) = healed_content {
        let _ = fs::write(&found.config_path, healed_content);
    }
    resolve_config_paths_for_runtime(&mut config, &found.project_root);
    Ok((found.project_root, found.config_path, config))
}

fn select_worker_for_current_dir(
    start: &Path,
    project_root: &Path,
    apps: &[DiscoveredWorkerApp],
) -> Result<DiscoveredWorkerApp, String> {
    let start = fs::canonicalize(start).unwrap_or_else(|_| start.to_path_buf());
    let _project_root =
        fs::canonicalize(project_root).unwrap_or_else(|_| project_root.to_path_buf());

    let mut matches = apps
        .iter()
        .filter(|app| {
            let root = fs::canonicalize(&app.root).unwrap_or_else(|_| app.root.clone());
            start == root || start.starts_with(&root)
        })
        .cloned()
        .collect::<Vec<_>>();

    matches.sort_by_key(|app| std::cmp::Reverse(path_depth(&app.root)));
    matches.dedup_by(|left, right| path_eq(&left.root, &right.root));

    match matches.len() {
        0 => Err(format!(
            "Could not infer a Worker app from {}. Pass `--app <name>` or `--all`. Known workers: {}",
            start.display(),
            format_worker_names(apps)
        )),
        1 => Ok(matches.remove(0)),
        _ => Err(format!(
            "Multiple Worker apps match {}: {}. Pass `--app <name>` to choose one.",
            start.display(),
            format_worker_names(&matches)
        )),
    }
}

fn worker_app_from_config(root: &Path, worker: WorkerConfig) -> DiscoveredWorkerApp {
    let local_env = parse_multiline_env_file(&root.join(".env.local")).unwrap_or_default();
    let base_script_name = pick_first_non_empty([
        worker.script_name.clone(),
        Some(resolve_dashboard_worker_name(root, &local_env)),
    ])
    .unwrap_or_else(|| worker.name.clone());

    DiscoveredWorkerApp {
        label: worker.name.clone(),
        root: root.to_path_buf(),
        base_script_name,
        config: Some(worker),
    }
}

fn worker_app_from_root(root: &Path, label: String) -> DiscoveredWorkerApp {
    let local_env = parse_multiline_env_file(&root.join(".env.local")).unwrap_or_default();
    DiscoveredWorkerApp {
        label: label.clone(),
        base_script_name: resolve_dashboard_worker_name(root, &local_env),
        root: root.to_path_buf(),
        config: None,
    }
}

fn push_worker_app(apps: &mut Vec<DiscoveredWorkerApp>, app: DiscoveredWorkerApp) {
    if apps
        .iter()
        .any(|existing| path_eq(&existing.root, &app.root))
    {
        return;
    }
    apps.push(app);
}

fn infer_worker_label(root: &Path, project_root: &Path) -> String {
    read_worker_name_from_config(&root.join("wrangler.jsonc"))
        .or_else(|| read_worker_name_from_config(&root.join("wrangler.jsonc.example")))
        .or_else(|| {
            root.strip_prefix(project_root)
                .ok()
                .and_then(|relative| relative.to_str())
                .map(|relative| relative.replace('\\', "/"))
        })
        .and_then(|value| {
            value
                .split('/')
                .next_back()
                .map(str::to_string)
                .filter(|value| !value.is_empty())
        })
        .unwrap_or_else(|| "worker".to_string())
}

fn collapse_worker_root(project_root: &Path, worker_root: &Path) -> String {
    crate::utils::collapse_project_path(project_root, &worker_root.to_string_lossy())
}

fn format_worker_names(apps: &[DiscoveredWorkerApp]) -> String {
    apps.iter()
        .map(|app| format!("{} ({})", app.label, app.base_script_name))
        .collect::<Vec<_>>()
        .join(", ")
}

fn path_depth(path: &Path) -> usize {
    path.components().count()
}

pub fn resolve_project_script_names(apps: &[DiscoveredWorkerApp]) -> Vec<String> {
    let mut names = Vec::new();
    for app in apps {
        names.push(app.base_script_name.clone());
        for environment in ["production", "preview"] {
            names.push(format!("{}-{}", app.base_script_name, environment));
        }
    }
    names.sort();
    names.dedup();
    names
}

pub fn script_belongs_to_project(script_id: &str, project_scripts: &[String]) -> bool {
    project_scripts.iter().any(|expected| {
        script_id == expected
            || script_id.starts_with(&format!("{expected}-"))
            || expected.starts_with(&format!("{script_id}-"))
    })
}

pub fn label_for_script(script_id: &str, apps: &[DiscoveredWorkerApp]) -> Option<String> {
    apps.iter()
        .find(|app| {
            script_id == app.base_script_name
                || script_id.starts_with(&format!("{}-", app.base_script_name))
        })
        .map(|app| app.label.clone())
}

pub fn worker_root_for_script<'a>(
    script_id: &str,
    apps: &'a [DiscoveredWorkerApp],
) -> Option<&'a Path> {
    apps.iter()
        .find(|app| {
            script_id == app.base_script_name
                || script_id.starts_with(&format!("{}-", app.base_script_name))
        })
        .map(|app| app.root.as_path())
}

pub fn resolve_workers_project_root(
    root_override: Option<&Path>,
    app_override: Option<&str>,
) -> Result<PathBuf, String> {
    let current_dir =
        env::current_dir().map_err(|error| format!("Failed to read current dir: {}", error))?;
    let resolution = resolve_worker_targets(&current_dir, root_override, app_override, false)?;
    resolution
        .selected
        .first()
        .map(|app| app.root.clone())
        .ok_or_else(|| "No Worker app was selected.".to_string())
}

fn looks_like_worker_root(path: &Path) -> bool {
    path.join("package.json").exists()
        && (path
            .join("scripts")
            .join("generate-wrangler-dashboard-config.mjs")
            .exists()
            || path.join("wrangler.jsonc").exists()
            || path.join("wrangler.json").exists()
            || path.join("wrangler.toml").exists()
            || path.join("wrangler.jsonc.example").exists())
}

pub fn resolve_dashboard_worker_name(
    worker_root: &Path,
    local_env: &HashMap<String, String>,
) -> String {
    pick_first_non_empty([
        local_env.get("DASHBOARD_PROD_WORKER_NAME").cloned(),
        env::var("DASHBOARD_PROD_WORKER_NAME").ok(),
        local_env.get("CLOUDFLARE_WORKER_NAME").cloned(),
        env::var("CLOUDFLARE_WORKER_NAME").ok(),
        local_env.get("WORKER_NAME").cloned(),
        env::var("WORKER_NAME").ok(),
        read_worker_name_from_config(&worker_root.join("wrangler.jsonc")),
        read_worker_name_from_config(&worker_root.join("wrangler.json")),
        read_worker_name_from_config(&worker_root.join("wrangler.toml")),
        read_worker_name_from_config(&worker_root.join("wrangler.jsonc.example")),
        Some(DEFAULT_WORKER_NAME.to_string()),
    ])
    .unwrap_or_else(|| DEFAULT_WORKER_NAME.to_string())
}

pub fn resolve_remote_script_name(
    worker_root: &Path,
    script_override: Option<&str>,
    worker_override: Option<&str>,
    environment: Option<&str>,
    local_env: &HashMap<String, String>,
) -> String {
    if let Some(script) = script_override
        .map(str::trim)
        .filter(|value| !value.is_empty())
    {
        return script.to_string();
    }

    let base_name = pick_first_non_empty([
        worker_override.map(str::trim).map(ToOwned::to_owned),
        Some(resolve_dashboard_worker_name(worker_root, local_env)),
    ])
    .unwrap_or_else(|| DEFAULT_WORKER_NAME.to_string());

    match environment.map(str::trim).filter(|value| !value.is_empty()) {
        Some(environment) => format!("{base_name}-{environment}"),
        None => base_name,
    }
}

pub fn resolve_wrangler_config_path(
    worker_root: &Path,
    command_name: &str,
    mode: &str,
) -> Option<String> {
    let is_dev_command =
        command_name.eq_ignore_ascii_case("serve") && !mode.eq_ignore_ascii_case("production");

    if !is_dev_command {
        return None;
    }

    for name in [
        "wrangler.dev.jsonc",
        "wrangler.dev.json",
        "wrangler.dev.toml",
        "wrangler.jsonc",
        "wrangler.json",
        "wrangler.toml",
    ] {
        if worker_root.join(name).exists() {
            return Some(name.to_string());
        }
    }
    None
}

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

pub fn parse_multiline_env_content(content: &str) -> HashMap<String, String> {
    let mut vars = HashMap::new();
    let lines = content.lines().collect::<Vec<_>>();
    let mut key: Option<String> = None;
    let mut value_lines = Vec::new();

    let flush = |vars: &mut HashMap<String, String>,

                 key: &mut Option<String>,
                 value_lines: &mut Vec<String>| {
        let Some(current_key) = key.take() else {
            return;
        };
        let mut value = value_lines.join("\n").trim().to_string();
        if (value.starts_with('"') && value.ends_with('"'))
            || (value.starts_with('\'') && value.ends_with('\''))
        {
            value = value[1..value.len().saturating_sub(1)].to_string();
        }
        vars.insert(current_key, value);
        value_lines.clear();
    };

    for line in lines {
        let trimmed = line.trim();
        if key.is_none() && (trimmed.is_empty() || trimmed.starts_with('#')) {
            continue;
        }

        if key.is_none() {
            let Some((raw_key, raw_value)) = line.split_once('=') else {
                continue;
            };
            let parsed_key = raw_key.trim();
            if parsed_key.is_empty() {
                continue;
            }
            key = Some(parsed_key.to_string());
            value_lines.push(raw_value.to_string());
            let joined = value_lines.join("\n");
            let unquoted = joined.trim();
            let is_complete_quoted = (unquoted.starts_with('"') && unquoted.ends_with('"'))
                || (unquoted.starts_with('\'') && unquoted.ends_with('\''));
            if is_complete_quoted || !unquoted.starts_with('"') {
                flush(&mut vars, &mut key, &mut value_lines);
            }
            continue;
        }

        value_lines.push(line.to_string());
        let joined = value_lines.join("\n").trim().to_string();
        if joined.ends_with('"') || joined.ends_with('\'') {
            flush(&mut vars, &mut key, &mut value_lines);
        }
    }

    flush(&mut vars, &mut key, &mut value_lines);
    vars
}

pub fn read_configured_custom_domain_routes(worker_root: &Path) -> Vec<Value> {
    let site_config_path = worker_root.join("src").join("lib").join("site-config.ts");
    let Ok(content) = fs::read_to_string(site_config_path) else {
        return Vec::new();
    };

    let domain_pattern = Regex::new(r#"domain:\s*"([^"]+)""#).expect("domain regex");
    let Some(captures) = domain_pattern.captures(&content) else {
        return Vec::new();
    };
    let Some(domain) = captures.get(1).map(|value| value.as_str().trim()) else {
        return Vec::new();
    };
    if domain.is_empty() {
        return Vec::new();
    }

    vec![json!({
        "pattern": domain,
        "zone_name": domain,
        "custom_domain": true
    })]
}

fn read_worker_name_from_config(path: &Path) -> Option<String> {
    if !path.exists() {
        return None;
    }
    read_top_level_string_property(path, "name")
}

fn read_top_level_string_property(path: &Path, property_name: &str) -> Option<String> {
    let content = fs::read_to_string(path).ok()?;
    if path.extension().and_then(|value| value.to_str()) == Some("toml") {
        let property_pattern = Regex::new(&format!(
            r#"(?m)^\s*{}\s*=\s*["']([^"']+)["']"#,
            regex::escape(property_name)
        ))
        .ok()?;
        return property_pattern
            .captures(&content)
            .and_then(|captures| captures.get(1))
            .map(|value| value.as_str().trim().to_string())
            .filter(|value| !value.is_empty());
    }
    let property_pattern = Regex::new(&format!(
        r#"^\s*"{}"\s*:\s*"([^"]+)""#,
        regex::escape(property_name)
    ))
    .ok()?;

    let mut brace_depth = 0usize;
    let mut in_string = false;
    let mut escaped = false;
    let mut line_start = 0usize;

    let maybe_read_line = |line_end: usize, brace_depth: usize, line_start: usize| {
        if brace_depth != 1 {
            return None;
        }

        let line = &content[line_start..line_end];
        property_pattern
            .captures(line)
            .and_then(|captures| captures.get(1))
            .map(|value| value.as_str().trim().to_string())
            .filter(|value| !value.is_empty())
    };

    for (index, ch) in content.char_indices() {
        if ch == '\n' {
            if let Some(value) = maybe_read_line(index, brace_depth, line_start) {
                return Some(value);
            }
            line_start = index + 1;
            continue;
        }

        if in_string {
            if escaped {
                escaped = false;
                continue;
            }
            if ch == '\\' {
                escaped = true;
                continue;
            }
            if ch == '"' {
                in_string = false;
            }
            continue;
        }

        if ch == '"' {
            in_string = true;
            continue;
        }

        if ch == '{' {
            brace_depth += 1;
        } else if ch == '}' {
            brace_depth = brace_depth.saturating_sub(1);
        }
    }

    maybe_read_line(content.len(), brace_depth, line_start)
}

fn path_eq(left: &Path, right: &Path) -> bool {
    normalize_path(left) == normalize_path(right)
}

fn normalize_path(path: &Path) -> String {
    path.to_string_lossy()
        .replace('\\', "/")
        .to_ascii_lowercase()
}

#[cfg(test)]
mod tests {
    use super::{
        discover_worker_apps, parse_multiline_env_content, read_configured_custom_domain_routes,
        resolve_project_script_names, resolve_remote_script_name, resolve_wrangler_config_path,
        script_belongs_to_project,
    };
    use std::collections::HashMap;
    use std::fs;

    fn temp_dir(label: &str) -> std::path::PathBuf {
        let dir = std::env::temp_dir().join(format!(
            "xbp-workers-project-{label}-{}",
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .expect("system time")
                .as_nanos()
        ));
        fs::create_dir_all(&dir).expect("create temp dir");
        dir
    }

    #[test]
    fn parse_multiline_env_content_handles_quoted_blocks() {
        let parsed =
            parse_multiline_env_content("A=plain\nB=\"line 1\nline 2\"\nC='single quoted'\n");

        assert_eq!(parsed.get("A").map(String::as_str), Some("plain"));
        assert_eq!(parsed.get("B").map(String::as_str), Some("line 1\nline 2"));
        assert_eq!(parsed.get("C").map(String::as_str), Some("single quoted"));
    }

    #[test]
    fn resolve_remote_script_name_appends_environment() {
        let root = temp_dir("script-name");
        fs::write(root.join("wrangler.jsonc"), "{\n  \"name\": \"xbp\"\n}\n").expect("write");

        let name =
            resolve_remote_script_name(&root, None, None, Some("production"), &HashMap::new());

        assert_eq!(name, "xbp-production");
        let _ = fs::remove_dir_all(root);
    }

    #[test]
    fn resolve_wrangler_config_prefers_dev_for_local_serve() {
        let root = temp_dir("config-path");
        fs::write(root.join("wrangler.dev.jsonc"), "{}\n").expect("write dev config");
        fs::write(root.join("wrangler.jsonc"), "{}\n").expect("write default config");

        assert_eq!(
            resolve_wrangler_config_path(&root, "serve", "development").as_deref(),
            Some("wrangler.dev.jsonc")
        );
        assert_eq!(
            resolve_wrangler_config_path(&root, "serve", "production"),
            None
        );

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

    #[test]
    fn recognizes_toml_wrangler_projects_and_reads_local_config() {
        let root = temp_dir("toml-config");
        fs::write(root.join("package.json"), "{}\n").expect("package json");
        fs::write(
            root.join("wrangler.toml"),
            "name = \"toml-worker\"\nmain = \"src/index.js\"\n",
        )
        .expect("wrangler toml");

        assert!(super::looks_like_worker_root(&root));
        assert_eq!(
            super::read_worker_name_from_config(&root.join("wrangler.toml")).as_deref(),
            Some("toml-worker")
        );
        assert_eq!(
            resolve_wrangler_config_path(&root, "serve", "development").as_deref(),
            Some("wrangler.toml")
        );

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

    #[test]
    fn discover_worker_apps_finds_known_apps_under_repo_root() {
        let repo_root = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
            .join("..")
            .join("..");
        let apps = discover_worker_apps(&repo_root);
        let labels = apps
            .iter()
            .map(|app| app.label.as_str())
            .collect::<Vec<_>>();

        assert!(labels.contains(&"web"));
        assert!(labels.contains(&"api"));
        assert!(labels.contains(&"pkg"));
    }

    #[test]
    fn resolve_project_script_names_include_environment_suffixes() {
        let root = temp_dir("project-script-names");
        fs::write(
            root.join("wrangler.jsonc"),
            "{\n  \"name\": \"xbp-api\"\n}\n",
        )
        .expect("write");
        let apps = vec![super::DiscoveredWorkerApp {
            label: "api".to_string(),
            root: root.clone(),
            base_script_name: "xbp-api".to_string(),
            config: None,
        }];
        let names = resolve_project_script_names(&apps);

        assert!(names.iter().any(|name| name == "xbp-api"));
        assert!(names.iter().any(|name| name == "xbp-api-production"));
        assert!(script_belongs_to_project("xbp-api-production", &names));

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

    #[test]
    fn scan_worker_roots_finds_nested_wrangler_projects() {
        let project_root = temp_dir("scan-workers");
        let nested = project_root.join("apps").join("studio");
        fs::create_dir_all(&nested).expect("nested worker dir");
        fs::write(nested.join("package.json"), "{}\n").expect("package json");
        fs::write(
            nested.join("wrangler.jsonc"),
            "{\n  \"name\": \"athena-studio\"\n}\n",
        )
        .expect("wrangler config");

        let discovered = super::scan_worker_roots(&project_root);
        assert_eq!(discovered.len(), 1);
        assert!(discovered[0].ends_with("apps/studio") || discovered[0].ends_with("apps\\studio"));

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

    #[test]
    fn discover_worker_apps_prefers_configured_workers() {
        let project_root = temp_dir("configured-workers");
        let worker_root = project_root.join("apps").join("gateway");
        fs::create_dir_all(&worker_root).expect("worker dir");
        fs::write(worker_root.join("package.json"), "{}\n").expect("package json");
        fs::write(
            worker_root.join("wrangler.jsonc"),
            "{\n  \"name\": \"athena\"\n}\n",
        )
        .expect("wrangler config");

        let config = crate::strategies::XbpConfig {
            project_name: "athena".to_string(),
            version: "1.0.0".to_string(),
            port: 3000,
            build_dir: "./".to_string(),
            workers: Some(vec![crate::strategies::WorkerConfig {
                name: "athena".to_string(),
                root: worker_root.to_string_lossy().to_string(),
                script_name: Some("athena".to_string()),
                service: None,
                deploy: None,
                container: None,
                containers: None,
                durable_objects: None,
            }]),
            app_type: None,
            build_command: None,
            start_command: None,
            install_command: None,
            environment: None,
            services: None,
            openapi: None,
            systemd_service_name: None,
            systemd: None,
            kafka_brokers: None,
            kafka_topic: None,
            kafka_public_url: None,
            log_files: None,
            monitor_url: None,
            monitor_method: None,
            monitor_expected_code: None,
            monitor_interval: None,
            database: None,
            oci: None,
            kubernetes: None,
            deploy: None,
            target: None,
            branch: None,
            crate_name: None,
            npm_script: None,
            port_storybook: None,
            url: None,
            url_storybook: None,
            linear: None,
            github: None,
            publish: None,
            version_targets: Vec::new(),
            version_domains: Vec::new(),
            ignore_paths: Vec::new(),
            watch_ignore_paths: Vec::new(),
            versioning_disabled: Vec::new(),
            release_disabled: Vec::new(),
        };

        let apps = super::discover_worker_apps_for_project(&project_root, Some(&config));
        assert_eq!(apps.len(), 1);
        assert_eq!(apps[0].label, "athena");
        assert_eq!(apps[0].base_script_name, "athena");

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

    #[test]
    fn read_configured_custom_domain_routes_extracts_site_domain() {
        let root = temp_dir("routes");
        let site_config_dir = root.join("src").join("lib");
        fs::create_dir_all(&site_config_dir).expect("site config dir");
        fs::write(
            site_config_dir.join("site-config.ts"),
            "export const siteConfig = {\n  domain: \"xbp.app\",\n};\n",
        )
        .expect("write site config");

        let routes = read_configured_custom_domain_routes(&root);
        assert_eq!(routes.len(), 1);
        assert_eq!(routes[0]["pattern"], "xbp.app");

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

    #[test]
    fn find_worker_app_by_alias_matches_script_name_and_route() {
        let root = temp_dir("alias-match");
        fs::write(root.join("package.json"), "{}\n").expect("package");
        fs::write(
            root.join("wrangler.jsonc"),
            r#"{
              "name": "xbp",
              "routes": [{ "pattern": "xbp.app", "custom_domain": true, "zone_name": "xbp.app" }]
            }"#,
        )
        .expect("wrangler");

        let app = super::worker_app_from_root(&root, "web".to_string());
        let apps = vec![app];

        assert_eq!(
            super::find_worker_app_by_alias(&apps, "web")
                .expect("label")
                .label,
            "web"
        );
        assert_eq!(
            super::find_worker_app_by_alias(&apps, "xbp")
                .expect("script")
                .base_script_name,
            "xbp"
        );
        assert_eq!(
            super::find_worker_app_by_alias(&apps, "xbp.app")
                .expect("domain")
                .label,
            "web"
        );
        assert_eq!(
            super::find_worker_app_by_alias(&apps, "https://xbp.app/")
                .expect("url")
                .label,
            "web"
        );
        assert!(super::find_worker_app_by_alias(&apps, "missing").is_none());

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

    #[test]
    fn ensure_selected_workers_configured_writes_missing_entries() {
        let project_root = temp_dir("auto-config");
        let worker_root = project_root.join("apps").join("web");
        let config_dir = project_root.join(".xbp");
        fs::create_dir_all(&worker_root).expect("worker");
        fs::create_dir_all(&config_dir).expect("config dir");
        fs::write(worker_root.join("package.json"), "{}\n").expect("package");
        fs::write(
            worker_root.join("wrangler.jsonc"),
            "{\n  \"name\": \"xbp\"\n}\n",
        )
        .expect("wrangler");
        let config_path = config_dir.join("xbp.yaml");
        fs::write(
            &config_path,
            "project_name: demo\nversion: 1.0.0\nport: 3000\nbuild_dir: ./\nworkers: null\n",
        )
        .expect("config");

        let mut resolution = super::WorkerTargetResolution {
            project_root: project_root.clone(),
            config_path: config_path.clone(),
            config: crate::strategies::XbpConfig {
                project_name: "demo".to_string(),
                version: "1.0.0".to_string(),
                port: 3000,
                build_dir: "./".to_string(),
                workers: None,
                app_type: None,
                build_command: None,
                start_command: None,
                install_command: None,
                environment: None,
                services: None,
                openapi: None,
                systemd_service_name: None,
                systemd: None,
                kafka_brokers: None,
                kafka_topic: None,
                kafka_public_url: None,
                log_files: None,
                monitor_url: None,
                monitor_method: None,
                monitor_expected_code: None,
                monitor_interval: None,
                database: None,
                oci: None,
                kubernetes: None,
                deploy: None,
                target: None,
                branch: None,
                crate_name: None,
                npm_script: None,
                port_storybook: None,
                url: None,
                url_storybook: None,
                linear: None,
                github: None,
                publish: None,
                version_targets: Vec::new(),
                version_domains: Vec::new(),
                ignore_paths: Vec::new(),
                watch_ignore_paths: Vec::new(),
                versioning_disabled: Vec::new(),
                release_disabled: Vec::new(),
            },
            selected: vec![super::worker_app_from_root(&worker_root, "web".to_string())],
        };

        let inserted = super::ensure_selected_workers_configured(&mut resolution).expect("ensure");
        assert_eq!(inserted, 1);
        assert!(resolution.selected[0].config.is_some());
        let written = fs::read_to_string(&config_path).expect("read config");
        assert!(written.contains("name: web") || written.contains("name: \"web\""));
        assert!(written.contains("apps/web") || written.contains("apps\\web"));

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