xbp 10.32.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
use crate::utils::find_xbp_config_upwards;
use regex::Regex;
use serde_json::{json, Value};
use std::collections::HashMap;
use std::env;
use std::fs;
use std::path::{Path, PathBuf};

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 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 mut apps: Vec<DiscoveredWorkerApp> = Vec::new();
    let mut roots_to_scan = vec![start.to_path_buf()];

    if let Some(found) = find_xbp_config_upwards(start) {
        if !roots_to_scan
            .iter()
            .any(|root| path_eq(root, &found.project_root))
        {
            roots_to_scan.push(found.project_root.clone());
        }
    }

    for project_root in roots_to_scan {
        for relative in KNOWN_WORKER_APP_DIRS {
            let candidate = project_root.join(relative);
            if !looks_like_worker_root(&candidate) {
                continue;
            }
            let label = relative
                .split('/')
                .next_back()
                .unwrap_or(relative)
                .to_string();
            let local_env =
                parse_multiline_env_file(&candidate.join(".env.local")).unwrap_or_default();
            let base_script_name = resolve_dashboard_worker_name(&candidate, &local_env);
            if apps.iter().any(|app| path_eq(&app.root, &candidate)) {
                continue;
            }
            apps.push(DiscoveredWorkerApp {
                label,
                root: candidate,
                base_script_name,
            });
        }

        if looks_like_worker_root(&project_root)
            && !apps.iter().any(|app| path_eq(&app.root, &project_root))
        {
            let local_env =
                parse_multiline_env_file(&project_root.join(".env.local")).unwrap_or_default();
            apps.push(DiscoveredWorkerApp {
                label: "worker".to_string(),
                root: project_root.clone(),
                base_script_name: resolve_dashboard_worker_name(&project_root, &local_env),
            });
        }
    }

    apps
}

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>) -> Result<PathBuf, String> {
    let current_dir =
        env::current_dir().map_err(|error| format!("Failed to read current dir: {}", error))?;
    let start = root_override
        .map(Path::to_path_buf)
        .unwrap_or_else(|| current_dir.clone());

    let mut candidates = vec![start.clone(), start.join("apps").join("web")];
    if let Some(found) = find_xbp_config_upwards(&start) {
        candidates.push(found.project_root.clone());
        candidates.push(found.project_root.join("apps").join("web"));
    }

    dedupe_paths(&mut candidates);

    for candidate in candidates {
        if looks_like_worker_root(&candidate) {
            return Ok(candidate);
        }
    }

    Err(format!(
        "Could not resolve a Cloudflare Workers project root from {}. Pass `xbp workers --root <path>`.",
        start.display()
    ))
}

fn dedupe_paths(paths: &mut Vec<PathBuf>) {
    let mut deduped = Vec::with_capacity(paths.len());
    for path in paths.drain(..) {
        if deduped
            .iter()
            .any(|existing: &PathBuf| path_eq(existing, &path))
        {
            continue;
        }
        deduped.push(path);
    }
    *paths = deduped;
}

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.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.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;
    }

    if worker_root.join("wrangler.dev.jsonc").exists() {
        return Some("wrangler.dev.jsonc".to_string());
    }
    if worker_root.join("wrangler.jsonc").exists() {
        return Some("wrangler.jsonc".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()?;
    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 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(),
        }];
        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 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);
    }
}