Skip to main content

capy_cli/
frontend.rs

1use anyhow::{bail, Context, Result};
2use clap::ValueEnum;
3use figment::{
4    providers::{Format, Toml},
5    Figment,
6};
7use serde::Deserialize;
8use std::{path::Path, process::Command};
9
10/// The frontend stacks supported by Capy.
11#[derive(Clone, Copy, Debug, Default, Deserialize, PartialEq, Eq, ValueEnum)]
12#[serde(rename_all = "lowercase")]
13pub enum FrontendDriver {
14    /// Vite, React, and TypeScript.
15    React,
16    /// A backend-only application (also the default for legacy projects).
17    #[default]
18    None,
19}
20
21/// Small, explicit project metadata loaded from `capy.toml`.
22#[derive(Debug, Default, Deserialize)]
23#[serde(deny_unknown_fields)]
24pub struct ProjectConfig {
25    /// Frontend selection. Legacy projects without a manifest are backend-only.
26    pub frontend: FrontendConfig,
27}
28
29/// Frontend configuration; the directory is conventionally `frontend/`.
30#[derive(Debug, Default, Deserialize)]
31#[serde(deny_unknown_fields)]
32pub struct FrontendConfig {
33    /// Tooling to generate, develop, and build the frontend.
34    pub driver: FrontendDriver,
35}
36
37impl ProjectConfig {
38    /// Load explicit metadata. Never infer a frontend from directory contents.
39    pub fn load(root: &Path) -> Result<Self> {
40        let path = root.join("capy.toml");
41        match std::fs::metadata(&path) {
42            Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(Self::default()),
43            Err(error) => Err(error).context("Could not read capy.toml"),
44            Ok(_) => Figment::from(Toml::file(path))
45                .extract()
46                .context("Invalid capy.toml. Set [frontend] driver to \"react\" or \"none\"."),
47        }
48    }
49}
50
51// All package-manager-specific execution stays here. More managers can be added
52// later without changing the process supervisor or application framework.
53struct Pnpm;
54impl Pnpm {
55    fn command(root: &Path, args: &[&str]) -> Command {
56        let mut command = Command::new(if cfg!(windows) { "pnpm.cmd" } else { "pnpm" });
57        command.args(args).current_dir(root.join("frontend"));
58        command
59    }
60}
61
62impl FrontendDriver {
63    /// Stable value written into project metadata.
64    pub fn as_str(self) -> &'static str {
65        match self {
66            Self::React => "react",
67            Self::None => "none",
68        }
69    }
70
71    /// Check required frontend files before starting any subprocesses.
72    pub fn validate(self, root: &Path) -> Result<()> {
73        if self == Self::React && !root.join("frontend/package.json").is_file() {
74            bail!("Capy expects a React frontend in frontend/. Restore frontend/package.json or set [frontend] driver = \"none\" in capy.toml.");
75        }
76        Ok(())
77    }
78
79    /// Install missing dependencies; honor a committed lockfile when present.
80    pub fn install_command(self, root: &Path) -> Option<Command> {
81        if self == Self::None || root.join("frontend/node_modules/.bin/vite").is_file() {
82            return None;
83        }
84        let mut command = Pnpm::command(root, &["install"]);
85        if root.join("frontend/pnpm-lock.yaml").is_file() {
86            command.arg("--frozen-lockfile");
87        }
88        Some(command)
89    }
90
91    /// Vite's development server with its backend origin provided by the CLI.
92    pub fn dev_command(self, root: &Path, backend_url: &str, port: u16) -> Option<Command> {
93        match self {
94            Self::None => None,
95            Self::React => {
96                let mut command = Pnpm::command(root, &["run", "dev", "--logLevel", "info"]);
97                command
98                    .env("CAPY_BACKEND_URL", backend_url)
99                    .env("CAPY_FRONTEND_PORT", port.to_string());
100                Some(command)
101            }
102        }
103    }
104
105    /// Build assets, including TypeScript checking via the package build script.
106    pub fn build_command(self, root: &Path) -> Option<Command> {
107        match self {
108            Self::None => None,
109            Self::React => Some(Pnpm::command(root, &["run", "build"])),
110        }
111    }
112
113    pub(crate) fn files(self) -> &'static [(&'static str, &'static str)] {
114        match self {
115            Self::None => &[],
116            Self::React => REACT_FILES,
117        }
118    }
119}
120
121macro_rules! frontend_file {
122    ($path:literal) => {
123        (
124            concat!("frontend/", $path),
125            include_str!(concat!("../templates/frontend/", $path, ".txt")),
126        )
127    };
128}
129
130const REACT_FILES: &[(&str, &str)] = &[
131    frontend_file!("package.json"),
132    frontend_file!("index.html"),
133    frontend_file!("vite.config.ts"),
134    frontend_file!("tsconfig.json"),
135    frontend_file!("tsconfig.app.json"),
136    frontend_file!("tsconfig.node.json"),
137    frontend_file!("src/App.tsx"),
138    frontend_file!("src/main.tsx"),
139    frontend_file!("src/style.css"),
140    frontend_file!("src/lib/api.ts"),
141    ("frontend/src/components/.gitkeep", ""),
142    ("frontend/src/pages/.gitkeep", ""),
143    ("frontend/src/hooks/.gitkeep", ""),
144    (
145        "frontend/public/capy.svg",
146        include_str!("../templates/frontend/public/capy.svg"),
147    ),
148    ("frontend/.gitignore", "/node_modules\n/dist\n*.local\n"),
149    ("routes/web.rs", "//! Web routes. React pages use the frontend SPA fallback.\n//! Register explicit HTTP routes here when needed; server-rendered Capy Views\n//! are a future feature.\nuse capy::Routes;\n\n/// Explicit web routes take precedence over the SPA.\npub fn routes() -> Routes {\n    Routes::new()\n}\n"),
150];