Skip to main content

proa_cli/
config.rs

1// Copyright Proa Labs, Inc.
2// SPDX-License-Identifier: Apache-2.0
3
4use std::{
5    collections::BTreeMap,
6    fs,
7    path::{Component, Path, PathBuf},
8};
9
10use anyhow::{Context, Result};
11use reqwest::Url;
12use serde::{Deserialize, Serialize};
13
14pub const CONFIG_FILE: &str = "proa.config.json";
15pub const LOCK_FILE: &str = "proa.lock.json";
16pub const CONFIG_SCHEMA_URL: &str = "https://proa.so/schema/proa.config.json";
17pub const LOCK_SCHEMA_URL: &str = "https://proa.so/schema/proa.lock.json";
18
19#[derive(Debug, Clone, Deserialize, Serialize)]
20#[serde(default)]
21pub struct ProjectConfig {
22    #[serde(rename = "$schema", skip_serializing_if = "Option::is_none")]
23    pub schema: Option<String>,
24    #[serde(skip_serializing_if = "Option::is_none")]
25    pub application: Option<serde_json::Value>,
26    #[serde(skip_serializing_if = "Option::is_none")]
27    pub database: Option<serde_json::Value>,
28    #[serde(skip_serializing_if = "Option::is_none")]
29    pub ui: Option<serde_json::Value>,
30    #[serde(skip_serializing_if = "Option::is_none")]
31    pub representations: Option<serde_json::Value>,
32    #[serde(skip_serializing_if = "Option::is_none")]
33    pub styling: Option<serde_json::Value>,
34    #[serde(skip_serializing_if = "Option::is_none")]
35    pub deploy: Option<serde_json::Value>,
36    #[serde(skip_serializing_if = "Option::is_none")]
37    pub content: Option<serde_json::Value>,
38    #[serde(skip_serializing_if = "BTreeMap::is_empty")]
39    pub tasks: BTreeMap<String, serde_json::Value>,
40    #[serde(skip_serializing_if = "Option::is_none")]
41    pub test: Option<serde_json::Value>,
42    pub paths: ProjectPaths,
43    pub registries: BTreeMap<String, String>,
44    pub dev: DevConfig,
45    pub build: BuildConfig,
46}
47
48#[derive(Debug, Clone, Deserialize, Serialize)]
49#[serde(default)]
50pub struct ProjectPaths {
51    pub components: PathBuf,
52    pub assets: PathBuf,
53    #[serde(skip_serializing_if = "Option::is_none")]
54    pub pages: Option<PathBuf>,
55    #[serde(skip_serializing_if = "Option::is_none")]
56    pub endpoints: Option<PathBuf>,
57    #[serde(skip_serializing_if = "Option::is_none")]
58    pub layouts: Option<PathBuf>,
59    #[serde(skip_serializing_if = "Option::is_none")]
60    pub models: Option<PathBuf>,
61    #[serde(skip_serializing_if = "Option::is_none")]
62    pub public: Option<PathBuf>,
63    #[serde(rename = "runtimeData", skip_serializing_if = "Option::is_none")]
64    pub runtime_data: Option<PathBuf>,
65}
66
67#[derive(Debug, Clone, Deserialize, Serialize)]
68#[serde(default)]
69pub struct DevConfig {
70    pub command: Vec<String>,
71    pub host: String,
72    pub port: u16,
73    #[serde(skip_serializing_if = "Vec::is_empty")]
74    pub before: Vec<String>,
75    pub watch: Vec<PathBuf>,
76}
77
78#[derive(Debug, Clone, Deserialize, Serialize)]
79#[serde(default)]
80pub struct BuildConfig {
81    pub command: Vec<String>,
82    #[serde(skip_serializing_if = "Vec::is_empty")]
83    pub before: Vec<String>,
84    /// `None` when the key is absent, so a Tailwind asset can be inferred.
85    /// `Some(vec![])` is an explicit "build no assets" and is left alone --
86    /// with a plain `Vec` the two were indistinguishable and an empty array
87    /// silently grew a Tailwind step back.
88    #[serde(skip_serializing_if = "Option::is_none")]
89    pub assets: Option<Vec<AssetConfig>>,
90}
91
92impl BuildConfig {
93    pub fn assets(&self) -> &[AssetConfig] {
94        self.assets.as_deref().unwrap_or_default()
95    }
96}
97
98#[derive(Debug, Clone, Deserialize, Serialize)]
99#[serde(default)]
100pub struct AssetConfig {
101    pub kind: String,
102    pub command: Vec<String>,
103    pub input: PathBuf,
104    pub output: PathBuf,
105    #[serde(skip_serializing_if = "Option::is_none")]
106    pub config: Option<PathBuf>,
107}
108
109#[derive(Debug, Clone, Deserialize, Serialize)]
110#[serde(default)]
111pub struct ComponentLockFile {
112    #[serde(rename = "$schema", skip_serializing_if = "Option::is_none")]
113    pub schema: Option<String>,
114    pub components: BTreeMap<String, InstalledComponent>,
115}
116
117#[derive(Debug, Clone, Deserialize, Serialize)]
118#[serde(default, rename_all = "camelCase")]
119pub struct InstalledComponent {
120    pub version: String,
121    pub registry: String,
122    pub mode: String,
123    pub source_hash: String,
124    pub local_hash_at_install: String,
125    pub installed_files: Vec<PathBuf>,
126    pub dependencies: Vec<String>,
127    pub rust_modules: Vec<InstalledRustModules>,
128    pub cargo_dependencies: Vec<InstalledCargoDependency>,
129}
130
131#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
132#[serde(rename_all = "camelCase")]
133pub struct InstalledRustModules {
134    pub target: PathBuf,
135    pub modules: Vec<String>,
136}
137
138#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
139#[serde(rename_all = "camelCase")]
140pub struct InstalledCargoDependency {
141    pub name: String,
142    #[serde(skip_serializing_if = "Option::is_none")]
143    pub path: Option<PathBuf>,
144    #[serde(skip_serializing_if = "Option::is_none")]
145    pub version: Option<String>,
146    #[serde(default, skip_serializing_if = "Option::is_none")]
147    pub git: Option<String>,
148    #[serde(skip_serializing_if = "Option::is_none")]
149    pub registry: Option<String>,
150    pub features: Vec<String>,
151    #[serde(skip_serializing_if = "Option::is_none")]
152    pub default_features: Option<bool>,
153}
154
155#[derive(Debug, Clone, Deserialize, Serialize)]
156pub struct ConfigInitReport {
157    pub root: PathBuf,
158    pub config_path: PathBuf,
159    pub lock_path: PathBuf,
160    pub wrote_config: bool,
161    pub wrote_lock: bool,
162}
163
164impl Default for ProjectConfig {
165    fn default() -> Self {
166        Self {
167            schema: Some(CONFIG_SCHEMA_URL.into()),
168            application: None,
169            database: None,
170            ui: None,
171            representations: None,
172            styling: None,
173            deploy: None,
174            content: None,
175            tasks: BTreeMap::new(),
176            test: None,
177            paths: ProjectPaths::default(),
178            registries: default_registries(),
179            dev: DevConfig::default(),
180            build: BuildConfig::default(),
181        }
182    }
183}
184
185impl Default for ProjectPaths {
186    fn default() -> Self {
187        Self {
188            components: PathBuf::from("src/components"),
189            // Must sit under the directory the generated server actually serves.
190            // `static/` is the URL prefix, not the folder: the axum scaffold mounts
191            // `public/` at `/static`, so assets written to `static/proa` were never
192            // reachable and every documented `/static/proa/...` link 404'd.
193            assets: PathBuf::from("public/proa"),
194            pages: None,
195            endpoints: None,
196            layouts: None,
197            models: None,
198            public: None,
199            runtime_data: None,
200        }
201    }
202}
203
204impl Default for DevConfig {
205    fn default() -> Self {
206        Self {
207            command: vec!["cargo".into(), "run".into()],
208            host: "127.0.0.1".into(),
209            port: 3000,
210            before: Vec::new(),
211            watch: default_watch_paths(),
212        }
213    }
214}
215
216impl Default for BuildConfig {
217    fn default() -> Self {
218        Self {
219            command: vec!["cargo".into(), "build".into(), "--release".into()],
220            before: Vec::new(),
221            assets: None,
222        }
223    }
224}
225
226impl Default for AssetConfig {
227    fn default() -> Self {
228        Self {
229            kind: "command".into(),
230            command: Vec::new(),
231            input: PathBuf::new(),
232            output: PathBuf::new(),
233            config: None,
234        }
235    }
236}
237
238impl Default for ComponentLockFile {
239    fn default() -> Self {
240        Self {
241            schema: Some(LOCK_SCHEMA_URL.into()),
242            components: BTreeMap::new(),
243        }
244    }
245}
246
247impl Default for InstalledComponent {
248    fn default() -> Self {
249        Self {
250            version: String::new(),
251            registry: String::new(),
252            mode: "source".into(),
253            source_hash: String::new(),
254            local_hash_at_install: String::new(),
255            installed_files: Vec::new(),
256            dependencies: Vec::new(),
257            rust_modules: Vec::new(),
258            cargo_dependencies: Vec::new(),
259        }
260    }
261}
262
263pub fn load_project_config(root: &Path) -> Result<ProjectConfig> {
264    let (config, unknown_keys) = load_project_config_with_unknown_keys(root)?;
265    // A misspelled key silently falling back to its default is the most
266    // confusing config failure mode; always say something.
267    for key in &unknown_keys {
268        eprintln!("warning: {CONFIG_FILE}: unknown key `{key}` is ignored");
269    }
270    Ok(config)
271}
272
273pub fn load_project_config_with_unknown_keys(root: &Path) -> Result<(ProjectConfig, Vec<String>)> {
274    let path = root.join(CONFIG_FILE);
275    if path.exists() {
276        let source =
277            fs::read_to_string(&path).with_context(|| format!("read {}", path.display()))?;
278        let mut unknown_keys = Vec::new();
279        let mut deserializer = serde_json::Deserializer::from_str(&source);
280        let mut config: ProjectConfig = serde_ignored::deserialize(&mut deserializer, |ignored| {
281            unknown_keys.push(ignored.to_string());
282        })
283        .with_context(|| format!("parse {}", path.display()))?;
284        fill_inferred_defaults(root, &mut config);
285        Ok((config, unknown_keys))
286    } else {
287        Ok((inferred_project_config(root), Vec::new()))
288    }
289}
290
291#[derive(Debug, Serialize)]
292pub struct ConfigValidation {
293    pub config_path: Option<PathBuf>,
294    pub warnings: Vec<String>,
295    pub errors: Vec<String>,
296}
297
298pub fn validate_project_config(root: &Path) -> Result<ConfigValidation> {
299    let path = root.join(CONFIG_FILE);
300    let mut validation = ConfigValidation {
301        config_path: path.exists().then_some(path),
302        warnings: Vec::new(),
303        errors: Vec::new(),
304    };
305
306    let (config, unknown_keys) = load_project_config_with_unknown_keys(root)?;
307    if validation.config_path.is_none() {
308        validation
309            .warnings
310            .push(format!("{CONFIG_FILE} not found; using inferred defaults"));
311    }
312    for key in unknown_keys {
313        validation
314            .warnings
315            .push(format!("unknown key `{key}` is ignored"));
316    }
317
318    if config.dev.command.is_empty() {
319        validation
320            .errors
321            .push("dev.command is empty; `proa dev` cannot start a server".to_string());
322    }
323    if config.build.command.is_empty() {
324        validation
325            .errors
326            .push("build.command is empty; `proa build` has nothing to run".to_string());
327    }
328    if config.dev.watch.is_empty() {
329        validation
330            .warnings
331            .push("dev.watch is empty; `proa dev` will never restart on changes".to_string());
332    }
333
334    for (name, path) in [
335        ("paths.components", &config.paths.components),
336        ("paths.assets", &config.paths.assets),
337    ] {
338        if let Err(error) = validate_project_relative_path(path) {
339            validation.errors.push(format!("{name}: {error}"));
340        }
341    }
342    if config.paths.components == config.paths.assets {
343        validation
344            .errors
345            .push("paths.components and paths.assets must be different".to_string());
346    }
347
348    if !config.registries.contains_key("@proa") {
349        validation
350            .errors
351            .push("registries.@proa is required".to_string());
352    }
353    for (registry, template) in &config.registries {
354        if let Err(error) = validate_registry_template(template) {
355            validation
356                .errors
357                .push(format!("registries.{registry}: {error}"));
358        }
359    }
360
361    for (index, asset) in config.build.assets().iter().enumerate() {
362        match asset.kind.as_str() {
363            "tailwind" => {
364                if !root.join(&asset.input).exists() {
365                    validation.warnings.push(format!(
366                        "build.assets[{index}]: tailwind input `{}` does not exist; the asset build will be skipped",
367                        asset.input.display()
368                    ));
369                }
370                if asset.output.as_os_str().is_empty() {
371                    validation.errors.push(format!(
372                        "build.assets[{index}]: tailwind asset has no output path"
373                    ));
374                }
375            }
376            "command" => {
377                if asset.command.is_empty() {
378                    validation.warnings.push(format!(
379                        "build.assets[{index}]: command asset with an empty command does nothing"
380                    ));
381                }
382            }
383            other => validation.errors.push(format!(
384                "build.assets[{index}]: unknown kind `{other}` (expected `tailwind` or `command`)"
385            )),
386        }
387    }
388
389    Ok(validation)
390}
391
392fn validate_project_relative_path(path: &Path) -> std::result::Result<(), String> {
393    if path.as_os_str().is_empty() || path.is_absolute() {
394        return Err(format!(
395            "`{}` must be a non-empty project-relative path",
396            path.display()
397        ));
398    }
399    if path
400        .components()
401        .any(|component| !matches!(component, Component::Normal(_)))
402    {
403        return Err(format!(
404            "`{}` contains an unsafe path component",
405            path.display()
406        ));
407    }
408    Ok(())
409}
410
411fn validate_registry_template(template: &str) -> std::result::Result<(), String> {
412    if template.matches("{name}").count() != 1 {
413        return Err(format!(
414            "`{template}` must contain exactly one `{{name}}` placeholder"
415        ));
416    }
417    let rendered = template.replace("{name}", "button");
418    if rendered.starts_with("https://") || rendered.starts_with("http://") {
419        let url = Url::parse(&rendered)
420            .map_err(|error| format!("`{template}` is not a valid registry URL: {error}"))?;
421        if url.scheme() == "http"
422            && !matches!(url.host_str(), Some("localhost" | "127.0.0.1" | "::1"))
423        {
424            return Err("HTTP is only allowed for localhost registries; use HTTPS".to_string());
425        }
426        return Ok(());
427    }
428    if rendered.starts_with("file://") {
429        let url = Url::parse(&rendered)
430            .map_err(|error| format!("`{template}` is not a valid file URL: {error}"))?;
431        url.to_file_path()
432            .map_err(|_| format!("`{template}` is not a valid file URL"))?;
433        return Ok(());
434    }
435    if rendered.contains("://") {
436        return Err(format!("`{template}` uses an unsupported URL scheme"));
437    }
438    if rendered.trim().is_empty() {
439        return Err("registry path cannot be empty".to_string());
440    }
441    Ok(())
442}
443
444pub fn load_component_lock(root: &Path) -> Result<ComponentLockFile> {
445    let path = root.join(LOCK_FILE);
446    if path.exists() {
447        let source =
448            fs::read_to_string(&path).with_context(|| format!("read {}", path.display()))?;
449        let mut lock: ComponentLockFile =
450            serde_json::from_str(&source).with_context(|| format!("parse {}", path.display()))?;
451        if lock.schema.is_none() {
452            lock.schema = Some(LOCK_SCHEMA_URL.into());
453        }
454        Ok(lock)
455    } else {
456        Ok(ComponentLockFile::default())
457    }
458}
459
460pub fn generated_project_config(tailwind: bool) -> Result<String> {
461    let mut config = ProjectConfig::default();
462    // Always write the key, even empty. A generated `--no-tailwind` project
463    // states "no asset builds" outright, so dropping a `styles/input.css` in
464    // later cannot silently reintroduce a Tailwind step nobody configured.
465    config.build.assets = Some(if tailwind {
466        vec![tailwind_asset()]
467    } else {
468        Vec::new()
469    });
470    Ok(serde_json::to_string_pretty(&config)? + "\n")
471}
472
473pub fn generated_component_lock() -> Result<String> {
474    Ok(serde_json::to_string_pretty(&ComponentLockFile::default())? + "\n")
475}
476
477pub fn init_project_files(root: &Path, force: bool) -> Result<ConfigInitReport> {
478    fs::create_dir_all(root).with_context(|| format!("create {}", root.display()))?;
479
480    let config_path = root.join(CONFIG_FILE);
481    let lock_path = root.join(LOCK_FILE);
482    let mut wrote_config = false;
483    let mut wrote_lock = false;
484
485    if force || !config_path.exists() {
486        fs::write(&config_path, generated_project_config(false)?)
487            .with_context(|| format!("write {}", config_path.display()))?;
488        wrote_config = true;
489    }
490
491    if force || !lock_path.exists() {
492        fs::write(&lock_path, generated_component_lock()?)
493            .with_context(|| format!("write {}", lock_path.display()))?;
494        wrote_lock = true;
495    }
496
497    Ok(ConfigInitReport {
498        root: root.to_path_buf(),
499        config_path,
500        lock_path,
501        wrote_config,
502        wrote_lock,
503    })
504}
505
506fn inferred_project_config(root: &Path) -> ProjectConfig {
507    let mut config = ProjectConfig::default();
508    fill_inferred_defaults(root, &mut config);
509    config
510}
511
512fn fill_inferred_defaults(root: &Path, config: &mut ProjectConfig) {
513    if config.schema.is_none() {
514        config.schema = Some(CONFIG_SCHEMA_URL.into());
515    }
516    if config.paths.components.as_os_str().is_empty() {
517        config.paths.components = ProjectPaths::default().components;
518    }
519    if config.paths.assets.as_os_str().is_empty() {
520        config.paths.assets = ProjectPaths::default().assets;
521    }
522    if config.registries.is_empty() {
523        config.registries = default_registries();
524    }
525    if config.dev.command.is_empty() {
526        config.dev.command = DevConfig::default().command;
527    }
528    if config.dev.host.is_empty() {
529        config.dev.host = DevConfig::default().host;
530    }
531    if config.dev.port == 0 {
532        config.dev.port = DevConfig::default().port;
533    }
534    if config.dev.watch.is_empty() {
535        config.dev.watch = default_watch_paths();
536    }
537    if config.build.command.is_empty() {
538        config.build.command = BuildConfig::default().command;
539    }
540    if config.build.assets.is_none() && root.join("styles/input.css").exists() {
541        config.build.assets = Some(vec![tailwind_asset()]);
542    }
543}
544
545fn default_registries() -> BTreeMap<String, String> {
546    [
547        ("@proa", "https://ui.proa.so/r/{name}.json"),
548        ("@proa-pro", "https://console.proa.so/r/{name}.json"),
549    ]
550    .into_iter()
551    .map(|(key, value)| (key.to_string(), value.to_string()))
552    .collect()
553}
554
555// Cargo.lock is intentionally not watched: `cargo run` can rewrite it during
556// the build the watcher just triggered, which restarts the dev loop forever.
557fn default_watch_paths() -> Vec<PathBuf> {
558    ["src", "styles", "Cargo.toml", "build.rs", CONFIG_FILE]
559        .into_iter()
560        .map(PathBuf::from)
561        .collect()
562}
563
564fn tailwind_asset() -> AssetConfig {
565    AssetConfig {
566        kind: "tailwind".into(),
567        command: Vec::new(),
568        input: PathBuf::from("styles/input.css"),
569        output: PathBuf::from("public/styles.css"),
570        // Tailwind v4 discovers sources from the CSS entrypoint's `@source`
571        // directives. The optional config field remains supported for older
572        // and custom projects, but generated v4 sites do not need `-c`.
573        config: None,
574    }
575}
576
577#[cfg(test)]
578mod tests {
579    use super::*;
580
581    #[test]
582    fn validate_reports_unknown_keys_and_bad_asset_kinds() {
583        let temp = tempfile::tempdir().unwrap();
584        fs::write(
585            temp.path().join(CONFIG_FILE),
586            r#"{
587                "dev": { "comand": ["cargo", "run"] },
588                "build": { "assets": [{ "kind": "webpack", "input": "a", "output": "b" }] }
589            }"#,
590        )
591        .unwrap();
592
593        let validation = validate_project_config(temp.path()).unwrap();
594        assert!(
595            validation
596                .warnings
597                .iter()
598                .any(|warning| warning.contains("dev.comand")),
599            "{validation:?}"
600        );
601        assert!(
602            validation
603                .errors
604                .iter()
605                .any(|error| error.contains("unknown kind `webpack`")),
606            "{validation:?}"
607        );
608    }
609
610    #[test]
611    fn validate_passes_defaults_and_flags_missing_config() {
612        let temp = tempfile::tempdir().unwrap();
613        let validation = validate_project_config(temp.path()).unwrap();
614        assert!(validation.errors.is_empty(), "{validation:?}");
615        assert!(
616            validation
617                .warnings
618                .iter()
619                .any(|warning| warning.contains("not found")),
620            "{validation:?}"
621        );
622    }
623
624    #[test]
625    fn validate_rejects_unsafe_paths_and_broken_registry_templates() {
626        let temp = tempfile::tempdir().unwrap();
627        fs::write(
628            temp.path().join(CONFIG_FILE),
629            r#"{
630                "paths": { "components": "../outside", "assets": "/tmp/assets" },
631                "registries": {
632                    "@proa": "https://ui.proa.so/r/component.json",
633                    "@proa-pro": "http://console.proa.so/r/{name}.json"
634                }
635            }"#,
636        )
637        .unwrap();
638
639        let validation = validate_project_config(temp.path()).unwrap();
640        assert!(
641            validation
642                .errors
643                .iter()
644                .any(|error| error.contains("paths.components")),
645            "{validation:?}"
646        );
647        assert!(
648            validation
649                .errors
650                .iter()
651                .any(|error| error.contains("paths.assets")),
652            "{validation:?}"
653        );
654        assert!(
655            validation
656                .errors
657                .iter()
658                .any(|error| error.contains("exactly one `{name}`")),
659            "{validation:?}"
660        );
661        assert!(
662            validation
663                .errors
664                .iter()
665                .any(|error| error.contains("use HTTPS")),
666            "{validation:?}"
667        );
668    }
669
670    #[test]
671    fn load_reports_unknown_keys() {
672        let temp = tempfile::tempdir().unwrap();
673        fs::write(temp.path().join(CONFIG_FILE), r#"{ "prot": 3001 }"#).unwrap();
674
675        let (_, unknown) = load_project_config_with_unknown_keys(temp.path()).unwrap();
676        assert_eq!(unknown, ["prot"]);
677    }
678
679    #[test]
680    fn generated_config_includes_tailwind_asset_when_requested() {
681        let json = generated_project_config(true).unwrap();
682
683        assert!(json.contains("\"$schema\": \"https://proa.so/schema/proa.config.json\""));
684        assert!(json.contains("\"components\": \"src/components\""));
685        assert!(json.contains("\"@proa\""));
686        assert!(json.contains("https://console.proa.so/r/{name}.json"));
687        assert!(json.contains("\"command\": ["));
688        assert!(json.contains("\"cargo\""));
689        assert!(json.contains("\"kind\": \"tailwind\""));
690        assert!(json.contains("\"styles/input.css\""));
691        assert!(!json.contains("\"config\""));
692        assert!(!json.contains("frontend"));
693    }
694
695    #[test]
696    fn generated_config_can_omit_assets() {
697        let json = generated_project_config(false).unwrap();
698
699        assert!(json.contains("\"assets\": []"));
700        assert!(!json.contains("\"kind\": \"tailwind\""));
701    }
702
703    #[test]
704    fn generated_lock_starts_empty() {
705        let json = generated_component_lock().unwrap();
706
707        assert!(json.contains("\"$schema\": \"https://proa.so/schema/proa.lock.json\""));
708        assert!(json.contains("\"components\": {}"));
709    }
710
711    #[test]
712    fn init_project_files_writes_config_and_lock() {
713        let temp = tempfile::tempdir().unwrap();
714        let report = init_project_files(temp.path(), false).unwrap();
715
716        assert!(report.wrote_config);
717        assert!(report.wrote_lock);
718        assert!(temp.path().join(CONFIG_FILE).exists());
719        assert!(temp.path().join(LOCK_FILE).exists());
720
721        let second = init_project_files(temp.path(), false).unwrap();
722        assert!(!second.wrote_config);
723        assert!(!second.wrote_lock);
724    }
725}