proa-cli 0.2.2

CLI for scaffolding, inspecting, formatting, and validating Proa web projects
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
// Copyright Proa Labs, Inc.
// SPDX-License-Identifier: Apache-2.0

use std::{
    collections::BTreeMap,
    fs,
    path::{Component, Path, PathBuf},
};

use anyhow::{Context, Result};
use reqwest::Url;
use serde::{Deserialize, Serialize};

mod model;
mod rust;
pub(crate) use rust::DevConfigRunner;

pub use model::{Config, DatabaseDriver, CONFIG_FILE};
pub(crate) use model::{DEFAULT_BUILD_COMMAND, DEFAULT_DEV_COMMAND, DEFAULT_PUBLIC_DIRECTORY};
pub type ProjectConfig = Config<String, PathBuf>;

macro_rules! owned_config_sections {
    ($($name:ident <$($storage:ty),+ $(,)?>),+ $(,)?) => {
        $(pub type $name = model::$name<$($storage),+>;)*
    };
}

owned_config_sections! {
    ApplicationConfig<String>,
    AssetConfig<String, PathBuf>,
    BuildConfig<String, PathBuf>,
    CdnConfig<String>,
    DatabaseConfig<String, PathBuf>,
    DeployConfig<String>,
    ProjectPaths<PathBuf>,
    RegistriesConfig<String>,
    ScriptConfig<String, PathBuf>,
    ScriptHooks<String>,
    ScriptsConfig<String, PathBuf>,
}

pub const LOCK_FILE: &str = "proa.lock.json";
pub const LOCK_SCHEMA_URL: &str = "https://proa.so/schema/proa.lock.json";

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(default)]
pub struct ComponentLockFile {
    #[serde(rename = "$schema", skip_serializing_if = "Option::is_none")]
    pub schema: Option<String>,
    pub components: BTreeMap<String, InstalledComponent>,
    // Component installs rewrite this lock. Preserve scaffold metadata and
    // version keys written by the site generator and capability commands.
    #[serde(flatten)]
    pub metadata: BTreeMap<String, serde_json::Value>,
}

impl ComponentLockFile {
    pub(crate) fn scaffold_capabilities(&self) -> impl Iterator<Item = &str> {
        self.metadata
            .get("scaffold")
            .and_then(|scaffold| scaffold.get("capabilities"))
            .and_then(serde_json::Value::as_array)
            .into_iter()
            .flatten()
            .filter_map(|capability| capability.get("id")?.as_str())
    }

    pub(crate) fn scaffold_markdown(&self) -> Option<bool> {
        if self
            .scaffold_capabilities()
            .any(|id| id == "representation:markdown")
        {
            Some(true)
        } else if self.scaffold_capabilities().any(|id| id == "base:site") {
            Some(false)
        } else {
            None
        }
    }
}

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(default, rename_all = "camelCase")]
pub struct InstalledComponent {
    pub version: String,
    pub registry: String,
    pub mode: String,
    pub source_hash: String,
    pub local_hash_at_install: String,
    pub installed_files: Vec<PathBuf>,
    pub dependencies: Vec<String>,
    pub rust_modules: Vec<InstalledRustModules>,
    pub cargo_dependencies: Vec<InstalledCargoDependency>,
}

#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct InstalledRustModules {
    pub target: PathBuf,
    pub modules: Vec<String>,
}

#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct InstalledCargoDependency {
    pub name: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub path: Option<PathBuf>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub version: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub git: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub registry: Option<String>,
    pub features: Vec<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub default_features: Option<bool>,
}

#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct ConfigInitReport {
    pub root: PathBuf,
    pub config_path: PathBuf,
    pub lock_path: PathBuf,
    pub wrote_config: bool,
    pub wrote_lock: bool,
}

impl Default for ComponentLockFile {
    fn default() -> Self {
        Self {
            schema: Some(LOCK_SCHEMA_URL.into()),
            components: BTreeMap::new(),
            metadata: BTreeMap::new(),
        }
    }
}

impl Default for InstalledComponent {
    fn default() -> Self {
        Self {
            version: String::new(),
            registry: String::new(),
            mode: "source".into(),
            source_hash: String::new(),
            local_hash_at_install: String::new(),
            installed_files: Vec::new(),
            dependencies: Vec::new(),
            rust_modules: Vec::new(),
            cargo_dependencies: Vec::new(),
        }
    }
}

pub fn load_project_config(root: &Path) -> Result<ProjectConfig> {
    load_project_config_with_runner(root, None)
}

pub(crate) fn load_project_config_with_runner(
    root: &Path,
    runner: Option<&mut DevConfigRunner>,
) -> Result<ProjectConfig> {
    let mut config = match project_config_path(root) {
        Some(path) => rust::load(root, &path, runner)
            .with_context(|| format!("evaluate {}", path.display()))?,
        None if root.join("proa.config.json").exists() => {
            anyhow::bail!(
                "`proa.config.json` is no longer supported; migrate settings to `{CONFIG_FILE}` (run `proa init` for a starter file)"
            );
        }
        None => ProjectConfig::default(),
    };
    fill_inferred_defaults(root, &mut config);
    Ok(config)
}

pub(crate) fn project_config_path(root: &Path) -> Option<PathBuf> {
    let path = root.join(CONFIG_FILE);
    path.exists().then_some(path)
}

pub(crate) fn generated_rust_config(config: &ProjectConfig) -> Result<String> {
    rust::source(config)
}

pub(crate) fn add_rust_capability(
    source: &str,
    before: &ProjectConfig,
    after: &ProjectConfig,
) -> Result<String> {
    rust::with_capability_changes(source, before, after)
}

#[derive(Debug, Serialize)]
pub struct ConfigValidation {
    pub config_path: Option<PathBuf>,
    pub warnings: Vec<String>,
    pub errors: Vec<String>,
}

pub fn validate_project_config(root: &Path) -> Result<ConfigValidation> {
    let config = load_project_config(root)?;
    let mut validation = validate_build_config(root, &config);
    for (name, command) in [
        ("dev", &config.scripts.dev),
        ("build", &config.scripts.build),
    ] {
        if let Err(error) = crate::commands::script::validate(name, command) {
            validation.errors.push(error.to_string());
        }
    }
    Ok(validation)
}

pub(crate) fn validate_build_config(root: &Path, config: &ProjectConfig) -> ConfigValidation {
    let mut validation = ConfigValidation {
        config_path: project_config_path(root),
        warnings: Vec::new(),
        errors: Vec::new(),
    };

    if validation.config_path.is_none() {
        validation
            .warnings
            .push(format!("{CONFIG_FILE} not found; using inferred defaults"));
    }

    if !config.scripts.css.trim().is_empty() {
        if let Err(error) = crate::commands::script::validate("css", &config.scripts.css) {
            validation.errors.push(error.to_string());
        }
    }
    for (phase, hooks) in [
        ("dev", &config.scripts.before.dev),
        ("build", &config.scripts.before.build),
        ("test", &config.scripts.before.test),
    ] {
        if let Err(error) = crate::commands::task::validate_lifecycle_tasks(config, hooks) {
            validation
                .errors
                .push(format!("scripts.before.{phase}: {error}"));
        }
    }
    for name in config.scripts.named.keys() {
        if crate::commands::script::shell_entries(&config.scripts).any(|(script, _)| script == name)
        {
            validation.warnings.push(format!(
                "scripts.named.{name} is shadowed by scripts.{name}"
            ));
        }
    }
    for (name, path) in [
        ("paths.components", &config.paths.components),
        ("paths.assets", &config.paths.assets),
    ] {
        if let Err(error) = validate_project_relative_path(path) {
            validation.errors.push(format!("{name}: {error}"));
        }
    }
    if let Some(path) = &config.paths.public {
        if let Err(error) = validate_project_relative_path(path) {
            validation.errors.push(format!("paths.public: {error}"));
        }
    }
    if config.paths.components == config.paths.assets {
        validation
            .errors
            .push("paths.components and paths.assets must be different".to_string());
    }

    if config.registries.proa.is_none() {
        validation
            .errors
            .push("registries.@proa is required".to_string());
    }
    for (registry, template) in config.registries.iter() {
        if let Err(error) = validate_registry_template(template) {
            validation
                .errors
                .push(format!("registries.{registry}: {error}"));
        }
    }

    for (index, asset) in config.build.assets().iter().enumerate() {
        match asset.kind.as_str() {
            "tailwind" => {
                if !root.join(&asset.input).exists() {
                    validation.warnings.push(format!(
                        "build.assets[{index}]: tailwind input `{}` does not exist; the asset build will be skipped",
                        asset.input.display()
                    ));
                }
                if asset.output.as_os_str().is_empty() {
                    validation.errors.push(format!(
                        "build.assets[{index}]: tailwind asset has no output path"
                    ));
                }
            }
            "command" => {
                if asset.command.is_empty() {
                    validation.warnings.push(format!(
                        "build.assets[{index}]: command asset with an empty command does nothing"
                    ));
                }
            }
            other => validation.errors.push(format!(
                "build.assets[{index}]: unknown kind `{other}` (expected `tailwind` or `command`)"
            )),
        }
    }

    validation
}

pub(crate) fn validate_project_relative_path(path: &Path) -> std::result::Result<(), String> {
    if path.as_os_str().is_empty() || path.is_absolute() {
        return Err(format!(
            "`{}` must be a non-empty project-relative path",
            path.display()
        ));
    }
    if path
        .components()
        .any(|component| !matches!(component, Component::Normal(_)))
    {
        return Err(format!(
            "`{}` contains an unsafe path component",
            path.display()
        ));
    }
    Ok(())
}

fn validate_registry_template(template: &str) -> std::result::Result<(), String> {
    if template.matches("{name}").count() != 1 {
        return Err(format!(
            "`{template}` must contain exactly one `{{name}}` placeholder"
        ));
    }
    let rendered = template.replace("{name}", "button");
    if rendered.starts_with("https://") || rendered.starts_with("http://") {
        let url = Url::parse(&rendered)
            .map_err(|error| format!("`{template}` is not a valid registry URL: {error}"))?;
        if url.scheme() == "http"
            && !matches!(url.host_str(), Some("localhost" | "127.0.0.1" | "::1"))
        {
            return Err("HTTP is only allowed for localhost registries; use HTTPS".to_string());
        }
        return Ok(());
    }
    if rendered.starts_with("file://") {
        let url = Url::parse(&rendered)
            .map_err(|error| format!("`{template}` is not a valid file URL: {error}"))?;
        url.to_file_path()
            .map_err(|_| format!("`{template}` is not a valid file URL"))?;
        return Ok(());
    }
    if rendered.contains("://") {
        return Err(format!("`{template}` uses an unsupported URL scheme"));
    }
    if rendered.trim().is_empty() {
        return Err("registry path cannot be empty".to_string());
    }
    Ok(())
}

pub fn load_component_lock(root: &Path) -> Result<ComponentLockFile> {
    let path = root.join(LOCK_FILE);
    if path.exists() {
        let source =
            fs::read_to_string(&path).with_context(|| format!("read {}", path.display()))?;
        let mut lock: ComponentLockFile =
            serde_json::from_str(&source).with_context(|| format!("parse {}", path.display()))?;
        if lock.schema.is_none() {
            lock.schema = Some(LOCK_SCHEMA_URL.into());
        }
        Ok(lock)
    } else {
        Ok(ComponentLockFile::default())
    }
}

pub fn generated_project_config(tailwind: bool) -> Result<String> {
    generated_rust_config(&ProjectConfig {
        build: BuildConfig {
            assets: (!tailwind).then(Vec::new),
            ..Default::default()
        },
        ..Default::default()
    })
}

pub fn generated_component_lock() -> Result<String> {
    Ok(serde_json::to_string_pretty(&ComponentLockFile::default())? + "\n")
}

pub fn init_project_files(root: &Path, force: bool) -> Result<ConfigInitReport> {
    fs::create_dir_all(root).with_context(|| format!("create {}", root.display()))?;

    let config_path = root.join(CONFIG_FILE);
    let lock_path = root.join(LOCK_FILE);
    let mut wrote_config = false;
    let mut wrote_lock = false;

    if force || !config_path.exists() {
        fs::write(&config_path, generated_project_config(true)?)
            .with_context(|| format!("write {}", config_path.display()))?;
        wrote_config = true;
    }

    if force || !lock_path.exists() {
        fs::write(&lock_path, generated_component_lock()?)
            .with_context(|| format!("write {}", lock_path.display()))?;
        wrote_lock = true;
    }

    Ok(ConfigInitReport {
        root: root.to_path_buf(),
        config_path,
        lock_path,
        wrote_config,
        wrote_lock,
    })
}

fn fill_inferred_defaults(root: &Path, config: &mut ProjectConfig) {
    if config.paths.components.as_os_str().is_empty() {
        config.paths.components = ProjectPaths::default().components;
    }
    if config.paths.assets.as_os_str().is_empty() {
        config.paths.assets = ProjectPaths::default().assets;
    }
    if config.registries.proa.is_none() && config.registries.proa_pro.is_none() {
        config.registries = RegistriesConfig::default();
    }
    if config.scripts.css.trim().is_empty()
        && config.build.assets.is_none()
        && root.join("styles/input.css").exists()
    {
        config.build.assets = Some(vec![tailwind_asset(stylesheet_output(config))]);
    }
}

pub(crate) fn css_script_output(config: &ProjectConfig) -> Option<PathBuf> {
    (!config.scripts.css.trim().is_empty()).then(|| stylesheet_output(config))
}

fn stylesheet_output(config: &ProjectConfig) -> PathBuf {
    config
        .paths
        .public
        .as_deref()
        .unwrap_or(Path::new(DEFAULT_PUBLIC_DIRECTORY))
        .join("styles.css")
}

fn tailwind_asset(output: PathBuf) -> AssetConfig {
    AssetConfig {
        kind: "tailwind".into(),
        command: Vec::new(),
        input: PathBuf::from("styles/input.css"),
        output,
        // Tailwind v4 discovers sources from the CSS entrypoint's `@source`
        // directives. The optional config field remains supported for older
        // and custom projects, but generated v4 sites do not need `-c`.
        config: None,
    }
}

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

    #[test]
    fn adding_a_capability_preserves_an_async_config_and_its_error_type() {
        let temp = tempfile::tempdir().unwrap();
        let source = r#"
use proa::config::{CdnConfig, Config, DeployConfig, ProjectPaths, ScriptsConfig, tokio};

pub async fn config() -> std::io::Result<Config<&'static str, String>> {
    let public = tokio::fs::read_to_string("public-dir.txt").await?;
    return Ok(Config {
        scripts: ScriptsConfig {
            dev: "cargo run",
            build: "cargo build --release",
            ..Default::default()
        },
        paths: ProjectPaths { public: Some(public), ..Default::default() },
        deploy: Some(DeployConfig {
            cdn: Some(CdnConfig::Command { command: vec!["purge-cache"] }),
            ..Default::default()
        }),
        ..Config::default()
    });
}
"#;
        let before = ProjectConfig::default();
        let mut after = before.clone();
        after.database = Some(DatabaseConfig {
            driver: DatabaseDriver::Sqlite,
            ..Default::default()
        });
        after.deploy = Some(DeployConfig {
            provider: "docker".into(),
            ..Default::default()
        });
        let patched = add_rust_capability(source, &before, &after).unwrap();
        fs::write(temp.path().join(CONFIG_FILE), patched).unwrap();
        fs::write(temp.path().join("public-dir.txt"), "public").unwrap();
        let actual = load_project_config(temp.path()).unwrap();
        assert_eq!(actual.paths.public, Some("public".into()));
        assert_eq!(actual.database, after.database);
        let deploy = actual.deploy.unwrap();
        assert_eq!(deploy.provider, "docker");
        assert_eq!(
            deploy.cdn,
            Some(CdnConfig::Command {
                command: vec!["purge-cache".into()]
            })
        );
    }

    #[test]
    fn validate_passes_defaults_and_flags_missing_config() {
        let temp = tempfile::tempdir().unwrap();
        let validation = validate_project_config(temp.path()).unwrap();
        assert!(validation.errors.is_empty(), "{validation:?}");
        assert!(
            validation
                .warnings
                .iter()
                .any(|warning| warning.contains("not found")),
            "{validation:?}"
        );
    }

    #[test]
    fn validate_rejects_unsafe_paths_and_broken_registry_templates() {
        let temp = tempfile::tempdir().unwrap();
        fs::write(
            temp.path().join(CONFIG_FILE),
            generated_rust_config(&ProjectConfig {
                paths: ProjectPaths {
                    components: "../outside".into(),
                    assets: "/tmp/assets".into(),
                    public: Some("../public".into()),
                },
                registries: RegistriesConfig {
                    proa: Some("https://ui.proa.so/r/component.json".into()),
                    proa_pro: Some("http://console.proa.so/r/{name}.json".into()),
                },
                ..ProjectConfig::default()
            })
            .unwrap(),
        )
        .unwrap();

        let validation = validate_project_config(temp.path()).unwrap();
        assert!(
            validation
                .errors
                .iter()
                .any(|error| error.contains("paths.components")),
            "{validation:?}"
        );
        assert!(
            validation
                .errors
                .iter()
                .any(|error| error.contains("paths.assets")),
            "{validation:?}"
        );
        assert!(
            validation
                .errors
                .iter()
                .any(|error| error.contains("paths.public")),
            "{validation:?}"
        );
        assert!(
            validation
                .errors
                .iter()
                .any(|error| error.contains("exactly one `{name}`")),
            "{validation:?}"
        );
        assert!(
            validation
                .errors
                .iter()
                .any(|error| error.contains("use HTTPS")),
            "{validation:?}"
        );
    }

    #[test]
    fn generated_config_has_a_typed_entry_and_explicit_asset_choice() {
        for tailwind in [false, true] {
            let source = generated_project_config(tailwind).unwrap();
            assert!(syn::parse_file(&source).is_ok());
            assert!(source.contains("dev: \"proa dev\""));
            assert!(source.contains("build: \"proa build\""));
            assert_eq!(source.contains("assets: Some(vec![])"), !tailwind);
        }
    }

    #[test]
    fn generated_lock_starts_empty() {
        let json = generated_component_lock().unwrap();

        assert!(json.contains("\"$schema\": \"https://proa.so/schema/proa.lock.json\""));
        assert!(json.contains("\"components\": {}"));
    }

    #[test]
    fn init_project_files_writes_config_and_lock() {
        let temp = tempfile::tempdir().unwrap();
        let report = init_project_files(temp.path(), false).unwrap();

        assert!(report.wrote_config);
        assert!(report.wrote_lock);
        assert!(temp.path().join(CONFIG_FILE).exists());
        assert!(temp.path().join(LOCK_FILE).exists());

        let second = init_project_files(temp.path(), false).unwrap();
        assert!(!second.wrote_config);
        assert!(!second.wrote_lock);
    }

    #[test]
    fn load_rejects_stale_json_config_without_rust_config() {
        let temp = tempfile::tempdir().unwrap();
        fs::write(temp.path().join("proa.config.json"), "{}").unwrap();

        let error = load_project_config(temp.path()).unwrap_err().to_string();
        assert!(error.contains("proa.config.json"), "{error}");
        assert!(error.contains(CONFIG_FILE), "{error}");
    }

    #[test]
    fn validate_flags_missing_before_hooks_and_shadowed_named_scripts() {
        let temp = tempfile::tempdir().unwrap();
        let config = ProjectConfig {
            scripts: ScriptsConfig {
                before: ScriptHooks {
                    dev: vec!["missing-task".into()],
                    ..Default::default()
                },
                named: BTreeMap::from([(
                    "dev".into(),
                    ScriptConfig {
                        command: vec!["echo".into(), "shadowed".into()],
                        ..Default::default()
                    },
                )]),
                ..Default::default()
            },
            ..Default::default()
        };
        let validation = validate_build_config(temp.path(), &config);
        assert!(
            validation
                .errors
                .iter()
                .any(|error| error.contains("scripts.before.dev")
                    && error.contains("missing-task")),
            "{validation:?}"
        );
        assert!(
            validation
                .warnings
                .iter()
                .any(|warning| warning.contains("scripts.named.dev")),
            "{validation:?}"
        );
    }
}