1use std::collections::BTreeMap;
39use std::fmt;
40use std::path::{Component, Path, PathBuf};
41
42use serde::{Deserialize, Serialize};
43
44use crate::diagnostic::Diagnostic;
45use crate::mode::RenderingMode;
46
47pub const TOML_FILE: &str = "next-rust.toml";
48pub const JSON_FILE: &str = "next-rust.json";
49
50#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
51#[serde(default, deny_unknown_fields)]
52pub struct Config {
53 #[serde(skip)]
55 pub root: PathBuf,
56 #[serde(skip)]
58 pub source: Option<PathBuf>,
59
60 pub app: AppConfig,
61 pub api: ApiConfig,
62 pub server: ServerConfig,
63 pub build: BuildConfig,
64 pub assets: AssetsConfig,
65 pub rendering: RenderingConfig,
66 pub images: ImagesConfig,
67 pub security: SecurityConfig,
68 pub env: EnvConfig,
69 pub dev: DevConfig,
70 pub logging: LoggingConfig,
71 pub redirects: Vec<RedirectRule>,
72 pub headers: Vec<HeaderRule>,
73 pub plugins: BTreeMap<String, serde_json::Value>,
75 pub tailwind: TailwindConfig,
77}
78
79impl Default for Config {
80 fn default() -> Self {
81 Self {
82 root: PathBuf::from("."),
83 source: None,
84 app: AppConfig::default(),
85 api: ApiConfig::default(),
86 server: ServerConfig::default(),
87 build: BuildConfig::default(),
88 assets: AssetsConfig::default(),
89 rendering: RenderingConfig::default(),
90 images: ImagesConfig::default(),
91 security: SecurityConfig::default(),
92 env: EnvConfig::default(),
93 dev: DevConfig::default(),
94 logging: LoggingConfig::default(),
95 redirects: Vec::new(),
96 headers: Vec::new(),
97 plugins: BTreeMap::new(),
98 tailwind: TailwindConfig::default(),
99 }
100 }
101}
102
103#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
123#[serde(default, deny_unknown_fields)]
124pub struct TailwindConfig {
125 pub enabled: bool,
127 pub preflight: bool,
129 pub dark_mode: TailwindDarkMode,
131 pub theme: BTreeMap<String, String>,
134 pub utilities: BTreeMap<String, TailwindUtility>,
137 pub variants: BTreeMap<String, String>,
139 pub plugins: Vec<String>,
142 pub safelist: Vec<String>,
144 pub sources: Vec<PathBuf>,
146 pub css: String,
149 pub minify_classes: bool,
153 pub keep_classes: Vec<String>,
157}
158
159impl Default for TailwindConfig {
160 fn default() -> Self {
161 Self {
162 enabled: false,
163 preflight: true,
164 dark_mode: TailwindDarkMode::Media,
165 theme: BTreeMap::new(),
166 utilities: BTreeMap::new(),
167 variants: BTreeMap::new(),
168 plugins: Vec::new(),
169 safelist: Vec::new(),
170 sources: Vec::new(),
171 css: String::new(),
172 minify_classes: true,
173 keep_classes: Vec::new(),
174 }
175 }
176}
177
178#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
180#[serde(rename_all = "lowercase")]
181pub enum TailwindDarkMode {
182 #[default]
184 Media,
185 Class,
187 Attribute,
189}
190
191#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
193#[serde(untagged)]
194pub enum TailwindUtility {
195 Apply(String),
197 Declarations(BTreeMap<String, String>),
199}
200
201impl From<&str> for TailwindUtility {
202 fn from(classes: &str) -> Self {
203 Self::Apply(classes.to_owned())
204 }
205}
206
207impl From<String> for TailwindUtility {
208 fn from(classes: String) -> Self {
209 Self::Apply(classes)
210 }
211}
212
213#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
214#[serde(default, deny_unknown_fields)]
215pub struct AppConfig {
216 pub directory: PathBuf,
218 pub public: PathBuf,
220 pub base_path: String,
222 pub trailing_slash: bool,
224 pub lang: String,
226 pub html_precedence: HtmlPrecedence,
228 pub follow_symlinks: bool,
230}
231
232impl Default for AppConfig {
233 fn default() -> Self {
234 Self {
235 directory: PathBuf::from("app"),
236 public: PathBuf::from("public"),
237 base_path: String::new(),
238 trailing_slash: false,
239 lang: "en".into(),
240 html_precedence: HtmlPrecedence::Error,
241 follow_symlinks: true,
242 }
243 }
244}
245
246#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
247#[serde(rename_all = "lowercase")]
248pub enum HtmlPrecedence {
249 #[default]
251 Error,
252 Rs,
254 Html,
256}
257
258#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
259#[serde(default, deny_unknown_fields)]
260pub struct ApiConfig {
261 pub directory: Option<PathBuf>,
263 pub prefix: String,
265}
266
267impl Default for ApiConfig {
268 fn default() -> Self {
269 Self { directory: None, prefix: "/api".into() }
270 }
271}
272
273#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
274#[serde(default, deny_unknown_fields)]
275pub struct ServerConfig {
276 pub host: String,
277 pub port: u16,
278 pub body_limit: usize,
280 pub header_timeout: u64,
282 pub request_timeout: u64,
284 pub shutdown_timeout: u64,
286 pub compression: bool,
287 pub http2: bool,
288 pub trust_proxy: bool,
290}
291
292impl Default for ServerConfig {
293 fn default() -> Self {
294 Self {
295 host: "0.0.0.0".into(),
296 port: 3000,
297 body_limit: 2 * 1024 * 1024,
298 header_timeout: 10,
299 request_timeout: 60,
300 shutdown_timeout: 10,
301 compression: true,
302 http2: false,
303 trust_proxy: false,
304 }
305 }
306}
307
308#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
309#[serde(default, deny_unknown_fields)]
310pub struct BuildConfig {
311 pub output: PathBuf,
312 pub concurrency: usize,
314 pub optimize: Optimize,
316 pub panic: PanicStrategy,
318}
319
320impl Default for BuildConfig {
321 fn default() -> Self {
322 Self {
323 output: PathBuf::from(".next-rust"),
324 concurrency: 8,
325 optimize: Optimize::Size,
326 panic: PanicStrategy::Unwind,
327 }
328 }
329}
330
331#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
333#[serde(rename_all = "lowercase")]
334pub enum Optimize {
335 #[default]
337 Size,
338 Speed,
340}
341
342#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
344#[serde(rename_all = "lowercase")]
345pub enum PanicStrategy {
346 #[default]
348 Unwind,
349 Abort,
352}
353
354#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
355#[serde(default, deny_unknown_fields)]
356pub struct AssetsConfig {
357 pub optimize: bool,
359 pub public_max_age: u64,
361 pub prune_css: bool,
364 pub css_safelist: Vec<String>,
367}
368
369impl Default for AssetsConfig {
370 fn default() -> Self {
371 Self { optimize: true, public_max_age: 0, prune_css: true, css_safelist: Vec::new() }
372 }
373}
374
375#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
376#[serde(default, deny_unknown_fields)]
377pub struct RenderingConfig {
378 pub default: RenderingMode,
379 pub streaming: bool,
381 pub revalidate: Option<u64>,
383 pub client_navigation: bool,
385}
386
387impl Default for RenderingConfig {
388 fn default() -> Self {
389 Self { default: RenderingMode::Auto, streaming: true, revalidate: None, client_navigation: true }
390 }
391}
392
393#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
394#[serde(default, deny_unknown_fields)]
395pub struct ImagesConfig {
396 pub sizes: Vec<u32>,
398 pub quality: u8,
399 pub max_age: u64,
401}
402
403impl Default for ImagesConfig {
404 fn default() -> Self {
405 Self { sizes: vec![640, 750, 828, 1080, 1200, 1920, 2048, 3840], quality: 75, max_age: 60 * 60 * 24 * 30 }
406 }
407}
408
409#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
410#[serde(default, deny_unknown_fields)]
411pub struct SecurityConfig {
412 pub headers: bool,
414 pub csp: Option<String>,
416 pub csrf: CsrfMode,
418 pub hsts_max_age: u64,
420 pub allowed_origins: Vec<String>,
422}
423
424impl Default for SecurityConfig {
425 fn default() -> Self {
426 Self { headers: true, csp: None, csrf: CsrfMode::Origin, hsts_max_age: 0, allowed_origins: Vec::new() }
427 }
428}
429
430#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
431#[serde(rename_all = "lowercase")]
432pub enum CsrfMode {
433 #[default]
435 Origin,
436 Token,
438 Off,
440}
441
442#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
443#[serde(default, deny_unknown_fields)]
444pub struct EnvConfig {
445 pub public_prefix: String,
447}
448
449impl Default for EnvConfig {
450 fn default() -> Self {
451 Self { public_prefix: "NEXT_RUST_PUBLIC_".into() }
452 }
453}
454
455#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
456#[serde(default, deny_unknown_fields)]
457pub struct DevConfig {
458 pub poll_interval: u64,
460 pub overlay: bool,
462 pub watch: Vec<PathBuf>,
464 pub scaffold: bool,
467}
468
469impl Default for DevConfig {
470 fn default() -> Self {
471 Self { poll_interval: 250, overlay: true, watch: Vec::new(), scaffold: true }
472 }
473}
474
475#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
476#[serde(default, deny_unknown_fields)]
477pub struct LoggingConfig {
478 pub format: LogFormat,
479 pub level: Option<String>,
482 pub requests: Option<bool>,
484}
485
486impl Default for LoggingConfig {
487 fn default() -> Self {
488 Self { format: LogFormat::Auto, level: None, requests: None }
489 }
490}
491
492impl LoggingConfig {
493 pub fn level(&self, env: crate::Environment) -> &str {
495 match &self.level {
496 Some(level) => level,
497 None if env.is_dev() => "info",
498 None => "error",
499 }
500 }
501
502 pub fn requests(&self, env: crate::Environment) -> bool {
504 self.requests.unwrap_or(env.is_dev())
505 }
506}
507
508#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
509#[serde(rename_all = "lowercase")]
510pub enum LogFormat {
511 #[default]
513 Auto,
514 Pretty,
515 Json,
516}
517
518#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
519#[serde(deny_unknown_fields)]
520pub struct RedirectRule {
521 pub source: String,
523 pub destination: String,
525 #[serde(default)]
526 pub permanent: bool,
527}
528
529#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
530#[serde(deny_unknown_fields)]
531pub struct HeaderRule {
532 pub source: String,
533 pub headers: BTreeMap<String, String>,
534}
535
536#[derive(Debug)]
537pub enum ConfigError {
538 Io { path: PathBuf, error: std::io::Error },
539 Parse { path: PathBuf, message: String },
540 Ambiguous { dir: PathBuf },
541}
542
543impl fmt::Display for ConfigError {
544 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
545 match self {
546 ConfigError::Io { path, error } => write!(f, "could not read {}: {error}", path.display()),
547 ConfigError::Parse { path, message } => {
548 write!(f, "invalid configuration in {}:\n{message}", path.display())
549 }
550 ConfigError::Ambiguous { dir } => write!(
551 f,
552 "both {TOML_FILE} and {JSON_FILE} exist in {}; keep only one (TOML is preferred)",
553 dir.display()
554 ),
555 }
556 }
557}
558
559impl std::error::Error for ConfigError {}
560
561pub type TomlParser = fn(&str) -> Result<Config, String>;
565
566impl Config {
567 pub fn discover(start: impl AsRef<Path>) -> Result<Self, ConfigError> {
569 Self::discover_with(start, Some(Self::from_toml_str))
570 }
571
572 pub fn discover_with(start: impl AsRef<Path>, toml: Option<TomlParser>) -> Result<Self, ConfigError> {
576 if let Ok(explicit) = std::env::var("NEXT_RUST_CONFIG") {
577 return Self::load_with(explicit, toml);
578 }
579 let start = absolutize(start.as_ref());
580 for dir in start.ancestors() {
581 let toml_file = dir.join(TOML_FILE);
582 let json = dir.join(JSON_FILE);
583 match (toml_file.is_file(), json.is_file()) {
584 (true, true) => return Err(ConfigError::Ambiguous { dir: dir.to_path_buf() }),
585 (true, false) => return Self::load_with(toml_file, toml),
586 (false, true) => return Self::load_with(json, toml),
587 _ => {}
588 }
589 if dir.join("Cargo.toml").is_file() && dir.join("app").is_dir() {
592 break;
593 }
594 }
595 let mut config = Config { root: start, ..Config::default() };
596 config.apply_env_overrides();
597 Ok(config)
598 }
599
600 pub fn load(path: impl AsRef<Path>) -> Result<Self, ConfigError> {
602 Self::load_with(path, Some(Self::from_toml_str))
603 }
604
605 pub fn load_with(path: impl AsRef<Path>, toml: Option<TomlParser>) -> Result<Self, ConfigError> {
607 let path = absolutize(path.as_ref());
608 let text = std::fs::read_to_string(&path).map_err(|error| ConfigError::Io { path: path.clone(), error })?;
609 let mut config = if path.extension().is_some_and(|e| e == "json") {
610 Self::from_json_str(&text)
611 } else {
612 match toml {
613 Some(parse) => parse(&text),
614 None => Err("this binary reads JSON configuration only (its configuration was embedded at build \
615 time); point NEXT_RUST_CONFIG at a .json file"
616 .to_owned()),
617 }
618 }
619 .map_err(|message| ConfigError::Parse { path: path.clone(), message })?;
620 config.root = path.parent().map(Path::to_path_buf).unwrap_or_else(|| PathBuf::from("."));
621 config.source = Some(path);
622 config.apply_env_overrides();
623 Ok(config)
624 }
625
626 pub fn from_toml_str(text: &str) -> Result<Self, String> {
627 toml::from_str(text).map_err(|e| e.to_string())
628 }
629
630 pub fn from_json_str(text: &str) -> Result<Self, String> {
631 serde_json::from_str(text).map_err(|e| e.to_string())
632 }
633
634 pub fn apply_env_overrides(&mut self) {
636 if let Some(port) = std::env::var("PORT").ok().and_then(|p| p.parse().ok()) {
637 self.server.port = port;
638 }
639 if let Ok(host) = std::env::var("HOST")
640 && !host.is_empty()
641 {
642 self.server.host = host;
643 }
644 }
645
646 pub fn resolve(&self, path: impl AsRef<Path>) -> PathBuf {
648 let path = path.as_ref();
649 if path.is_absolute() { normalize(path) } else { normalize(&self.root.join(path)) }
650 }
651
652 pub fn app_dir(&self) -> PathBuf {
653 self.resolve(&self.app.directory)
654 }
655
656 pub fn public_dir(&self) -> PathBuf {
657 self.resolve(&self.app.public)
658 }
659
660 pub fn api_dir(&self) -> Option<PathBuf> {
661 self.api.directory.as_ref().map(|d| self.resolve(d))
662 }
663
664 pub fn output_dir(&self) -> PathBuf {
665 self.resolve(&self.build.output)
666 }
667
668 pub fn validate(&self) -> Vec<Diagnostic> {
670 let mut out = Vec::new();
671 let app = self.app_dir();
672 if !app.exists() {
673 out.push(
674 Diagnostic::error("NR0001", "App directory not found")
675 .location(&app)
676 .message(format!(
677 "The routing directory configured as `app.directory = {:?}`\nresolves to {}, which does not exist.",
678 self.app.directory,
679 app.display()
680 ))
681 .help("create the directory or change `[app] directory` in next-rust.toml"),
682 );
683 } else if !app.is_dir() {
684 out.push(
685 Diagnostic::error("NR0002", "App directory is not a directory")
686 .location(&app)
687 .help("`[app] directory` must point to a directory"),
688 );
689 }
690 if let Some(api) = self.api_dir() {
691 if !api.is_dir() {
692 out.push(Diagnostic::error("NR0003", "API directory not found").location(api));
693 }
694 if !self.api.prefix.starts_with('/') {
695 out.push(
696 Diagnostic::error("NR0004", "API prefix must start with `/`")
697 .message(format!("found `api.prefix = {:?}`", self.api.prefix)),
698 );
699 }
700 }
701 if !self.app.base_path.is_empty() && (!self.app.base_path.starts_with('/') || self.app.base_path.ends_with('/'))
702 {
703 out.push(
704 Diagnostic::error("NR0005", "Invalid base path")
705 .message(format!("`app.base_path = {:?}`", self.app.base_path))
706 .help("use a leading slash and no trailing slash, e.g. `/docs`"),
707 );
708 }
709 for rule in &self.redirects {
710 if !rule.source.starts_with('/') {
711 out.push(
712 Diagnostic::error("NR0006", "Redirect source must start with `/`")
713 .message(format!("source = {:?}", rule.source)),
714 );
715 }
716 }
717 if let Some(level) = &self.logging.level
718 && !matches!(level.as_str(), "error" | "warn" | "info" | "debug" | "trace")
719 {
720 out.push(
721 Diagnostic::warning("NR0007", "Unknown log level")
722 .message(format!("`logging.level = {level:?}`; falling back to `info`")),
723 );
724 }
725 out
726 }
727
728 pub fn socket_addr_string(&self) -> String {
729 if self.server.host.contains(':') {
730 format!("[{}]:{}", self.server.host, self.server.port)
731 } else {
732 format!("{}:{}", self.server.host, self.server.port)
733 }
734 }
735}
736
737fn absolutize(p: &Path) -> PathBuf {
738 if p.is_absolute() {
739 normalize(p)
740 } else {
741 normalize(&std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")).join(p))
742 }
743}
744
745pub fn normalize(path: &Path) -> PathBuf {
748 let mut out = PathBuf::new();
749 for comp in path.components() {
750 match comp {
751 Component::CurDir => {}
752 Component::ParentDir => {
753 if !out.pop() {
754 out.push("..");
755 }
756 }
757 other => out.push(other.as_os_str()),
758 }
759 }
760 if out.as_os_str().is_empty() { PathBuf::from(".") } else { out }
761}
762
763#[cfg(test)]
764mod tests {
765 use super::*;
766
767 #[test]
768 fn defaults_are_zero_config() {
769 let c = Config::from_toml_str("").unwrap();
770 assert_eq!(c.app.directory, PathBuf::from("app"));
771 assert_eq!(c.server.port, 3000);
772 assert_eq!(c.build.output, PathBuf::from(".next-rust"));
773 assert_eq!(c.rendering.default, RenderingMode::Auto);
774 }
775
776 #[test]
777 fn parses_sections() {
778 let c = Config::from_toml_str(
779 r#"
780 [app]
781 directory = "src/web"
782 [server]
783 port = 8080
784 [rendering]
785 default = "server"
786 [[redirects]]
787 source = "/old"
788 destination = "/new"
789 permanent = true
790 [plugins.analytics]
791 id = "x"
792 "#,
793 )
794 .unwrap();
795 assert_eq!(c.app.directory, PathBuf::from("src/web"));
796 assert_eq!(c.server.port, 8080);
797 assert_eq!(c.rendering.default, RenderingMode::Dynamic);
798 assert!(c.redirects[0].permanent);
799 assert_eq!(c.plugins["analytics"]["id"], "x");
800 }
801
802 #[test]
803 fn rejects_unknown_keys() {
804 let err = Config::from_toml_str("[app]\ndirectroy = \"x\"").unwrap_err();
805 assert!(err.contains("directroy"), "{err}");
806 }
807
808 #[test]
809 fn json_is_supported() {
810 let c = Config::from_json_str(r#"{"app":{"directory":"frontend"}}"#).unwrap();
811 assert_eq!(c.app.directory, PathBuf::from("frontend"));
812 }
813
814 #[test]
815 fn resolves_relative_to_root() {
816 let c = Config {
817 root: PathBuf::from("/work/repo/apps/site"),
818 app: AppConfig { directory: PathBuf::from("../shared/my-pages"), ..Default::default() },
819 ..Default::default()
820 };
821 assert_eq!(c.app_dir(), PathBuf::from("/work/repo/apps/shared/my-pages"));
822 let c = Config {
823 root: PathBuf::from("/work"),
824 app: AppConfig { directory: PathBuf::from("/abs/pages/./x/.."), ..Default::default() },
825 ..Default::default()
826 };
827 assert_eq!(c.app_dir(), PathBuf::from("/abs/pages"));
828 }
829
830 #[test]
831 fn discovery_walks_up() {
832 let base = std::env::temp_dir().join(format!("nr-config-{}", std::process::id()));
833 let nested = base.join("a/b");
834 std::fs::create_dir_all(&nested).unwrap();
835 std::fs::write(base.join(TOML_FILE), "[app]\ndirectory = \"website/routes\"\n").unwrap();
836 let c = Config::discover(&nested).unwrap();
837 assert_eq!(c.root, base);
838 assert_eq!(c.app_dir(), base.join("website/routes"));
839 let diags = c.validate();
840 assert_eq!(diags[0].code, "NR0001");
841 std::fs::write(base.join(JSON_FILE), "{}").unwrap();
842 assert!(matches!(Config::discover(&nested), Err(ConfigError::Ambiguous { .. })));
843 std::fs::remove_dir_all(&base).unwrap();
844 }
845}