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#[derive(Clone, Copy, Debug, Default, Deserialize, PartialEq, Eq, ValueEnum)]
12#[serde(rename_all = "lowercase")]
13pub enum FrontendDriver {
14 React,
16 #[default]
18 None,
19}
20
21#[derive(Debug, Default, Deserialize)]
23#[serde(deny_unknown_fields)]
24pub struct ProjectConfig {
25 pub frontend: FrontendConfig,
27}
28
29#[derive(Debug, Default, Deserialize)]
31#[serde(deny_unknown_fields)]
32pub struct FrontendConfig {
33 pub driver: FrontendDriver,
35}
36
37impl ProjectConfig {
38 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
51struct 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 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 pub fn version_command(self, root: &Path) -> Option<Command> {
77 (self == Self::React).then(|| Pnpm::command(root, &["--version"]))
78 }
79
80 pub fn as_str(self) -> &'static str {
82 match self {
83 Self::React => "react",
84 Self::None => "none",
85 }
86 }
87
88 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 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 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 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!("pnpm-workspace.yaml"),
151 frontend_file!("tools/api-contracts/package.json"),
152 frontend_file!("tools/api-contracts/index.mjs"),
153 frontend_file!("index.html"),
154 frontend_file!("vite.config.ts"),
155 frontend_file!("tsconfig.json"),
156 frontend_file!("tsconfig.app.json"),
157 frontend_file!("tsconfig.node.json"),
158 frontend_file!("src/App.tsx"),
159 frontend_file!("src/main.tsx"),
160 frontend_file!("src/style.css"),
161 frontend_file!("src/lib/api.ts"),
162 frontend_file!("src/lib/router.tsx"),
163 frontend_file!("src/lib/providers.tsx"),
164 frontend_file!("src/lib/ApiErrors.tsx"),
165 frontend_file!("src/lib/useApi.ts"),
166 frontend_file!("src/features/index.ts"),
167 frontend_file!("src/feature.css"),
168 ("frontend/src/components/.gitkeep", ""),
169 ("frontend/src/pages/.gitkeep", ""),
170 ("frontend/src/hooks/.gitkeep", ""),
171 (
172 "frontend/public/capy.svg",
173 include_str!("../templates/frontend/public/capy.svg"),
174 ),
175 ("frontend/.gitignore", "node_modules/\n/dist\n*.local\n"),
176 ("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"),
177];