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    /// Whether Vite's platform-specific executable is installed.
64    pub fn dependencies_installed(self, root: &Path) -> bool {
65        self == Self::None
66            || root
67                .join(if cfg!(windows) {
68                    "frontend/node_modules/.bin/vite.cmd"
69                } else {
70                    "frontend/node_modules/.bin/vite"
71                })
72                .is_file()
73    }
74
75    /// Read the package manager version without installing or changing anything.
76    pub fn version_command(self, root: &Path) -> Option<Command> {
77        (self == Self::React).then(|| Pnpm::command(root, &["--version"]))
78    }
79
80    /// Stable value written into project metadata.
81    pub fn as_str(self) -> &'static str {
82        match self {
83            Self::React => "react",
84            Self::None => "none",
85        }
86    }
87
88    /// Check required frontend files before starting any subprocesses.
89    pub fn validate(self, root: &Path) -> Result<()> {
90        if self == Self::React && !root.join("frontend/package.json").is_file() {
91            bail!("Capy expects a React frontend in frontend/. Restore frontend/package.json or set [frontend] driver = \"none\" in capy.toml.");
92        }
93        Ok(())
94    }
95
96    /// Install missing dependencies; honor a committed lockfile when present.
97    pub fn install_command(self, root: &Path) -> Option<Command> {
98        if self.dependencies_installed(root) {
99            return None;
100        }
101        let mut command = Pnpm::command(root, &["install"]);
102        if root.join("frontend/pnpm-lock.yaml").is_file() {
103            command.arg("--frozen-lockfile");
104        }
105        Some(command)
106    }
107
108    /// Vite's development server with its backend origin provided by the CLI.
109    pub fn dev_command(self, root: &Path, backend_url: &str, port: u16) -> Option<Command> {
110        match self {
111            Self::None => None,
112            Self::React => {
113                let mut command = Pnpm::command(root, &["run", "dev", "--logLevel", "info"]);
114                command
115                    .env("CAPY_BACKEND_URL", backend_url)
116                    .env("CAPY_FRONTEND_PORT", port.to_string());
117                Some(command)
118            }
119        }
120    }
121
122    /// Build assets, including TypeScript checking via the package build script.
123    pub fn build_command(self, root: &Path) -> Option<Command> {
124        match self {
125            Self::None => None,
126            Self::React => Some(Pnpm::command(root, &["run", "build"])),
127        }
128    }
129
130    pub(crate) fn files(self) -> &'static [(&'static str, &'static str)] {
131        match self {
132            Self::None => &[],
133            Self::React => REACT_FILES,
134        }
135    }
136}
137
138macro_rules! frontend_file {
139    ($path:literal) => {
140        (
141            concat!("frontend/", $path),
142            include_str!(concat!("../templates/frontend/", $path, ".txt")),
143        )
144    };
145}
146
147const REACT_FILES: &[(&str, &str)] = &[
148    frontend_file!("package.json"),
149    frontend_file!("pnpm-lock.yaml"),
150    frontend_file!("index.html"),
151    frontend_file!("vite.config.ts"),
152    frontend_file!("tsconfig.json"),
153    frontend_file!("tsconfig.app.json"),
154    frontend_file!("tsconfig.node.json"),
155    frontend_file!("src/App.tsx"),
156    frontend_file!("src/main.tsx"),
157    frontend_file!("src/style.css"),
158    frontend_file!("src/lib/api.ts"),
159    ("frontend/src/components/.gitkeep", ""),
160    ("frontend/src/pages/.gitkeep", ""),
161    ("frontend/src/hooks/.gitkeep", ""),
162    (
163        "frontend/public/capy.svg",
164        include_str!("../templates/frontend/public/capy.svg"),
165    ),
166    ("frontend/.gitignore", "/node_modules\n/dist\n*.local\n"),
167    ("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"),
168];