Skip to main content

next_rust_core/
config.rs

1//! `next-rust.toml` configuration.
2//!
3//! Every section and key is optional; an empty file (or no file at all) is a
4//! valid, fully working configuration.
5//!
6//! ```toml
7//! [app]
8//! directory = "app"          # any relative or absolute path
9//! public = "public"
10//!
11//! [server]
12//! host = "0.0.0.0"
13//! port = 3000
14//!
15//! [build]
16//! output = ".next-rust"
17//!
18//! [rendering]
19//! default = "auto"
20//! ```
21//!
22//! ## Discovery
23//!
24//! 1. If `NEXT_RUST_CONFIG` is set, that file is used.
25//! 2. Otherwise, starting from the working directory and walking up through
26//!    its ancestors, the first directory containing `next-rust.toml` or
27//!    `next-rust.json` wins. Having both in one directory is an error.
28//! 3. If nothing is found, defaults are used with the working directory as
29//!    the project root.
30//!
31//! ## Path resolution
32//!
33//! Relative paths are resolved against the directory containing the
34//! configuration file (the *project root*), never against the process working
35//! directory. `..` components are allowed, which makes monorepo layouts like
36//! `directory = "../shared/pages"` possible. Paths are normalized lexically.
37
38use 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    /// Project root (directory containing the config file). Not read from the file.
54    #[serde(skip)]
55    pub root: PathBuf,
56    /// The config file that was loaded, if any.
57    #[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    /// Free-form plugin configuration: `[plugins.my-plugin]`.
74    pub plugins: BTreeMap<String, serde_json::Value>,
75    /// Tailwind CSS: `[tailwind]`.
76    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/// `[tailwind]`: Tailwind CSS generated from the classes used in the app.
104///
105/// ```toml
106/// [tailwind]
107/// enabled = true
108/// dark_mode = "class"
109/// plugins = ["@tailwindcss/typography"]
110///
111/// [tailwind.theme]                 # becomes @theme { --color-brand: …; }
112/// color-brand = "#f26b2a"
113/// font-display = "Inter, sans-serif"
114///
115/// [tailwind.utilities]             # becomes @utility …
116/// btn = "rounded-lg bg-brand px-4 py-2 font-semibold text-white"
117/// content-auto = { content-visibility = "auto" }
118///
119/// [tailwind.variants]              # becomes @custom-variant …
120/// theme-midnight = "&:where([data-theme=midnight] *)"
121/// ```
122#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
123#[serde(default, deny_unknown_fields)]
124pub struct TailwindConfig {
125    /// Generate Tailwind CSS for the app. Off unless set.
126    pub enabled: bool,
127    /// Include Tailwind's base styles (Preflight).
128    pub preflight: bool,
129    /// When `dark:` applies.
130    pub dark_mode: TailwindDarkMode,
131    /// Theme variables, with or without the leading `--`:
132    /// `color-brand = "#f26b2a"`, `breakpoint-3xl = "120rem"`.
133    pub theme: BTreeMap<String, String>,
134    /// Custom utility classes: a list of Tailwind classes to combine, or CSS
135    /// declarations.
136    pub utilities: BTreeMap<String, TailwindUtility>,
137    /// Custom variants: name → selector (`&:where(…)`) or at-rule.
138    pub variants: BTreeMap<String, String>,
139    /// First-party plugins bundled with Tailwind, e.g. `@tailwindcss/typography`
140    /// and `@tailwindcss/forms`.
141    pub plugins: Vec<String>,
142    /// Classes to generate even if they don't appear in the source.
143    pub safelist: Vec<String>,
144    /// Extra directories to scan for classes, besides the app directory and `src/`.
145    pub sources: Vec<PathBuf>,
146    /// Raw CSS appended after everything else (`@keyframes`, `@layer`, …), for
147    /// what the options above can't express.
148    pub css: String,
149}
150
151impl Default for TailwindConfig {
152    fn default() -> Self {
153        Self {
154            enabled: false,
155            preflight: true,
156            dark_mode: TailwindDarkMode::Media,
157            theme: BTreeMap::new(),
158            utilities: BTreeMap::new(),
159            variants: BTreeMap::new(),
160            plugins: Vec::new(),
161            safelist: Vec::new(),
162            sources: Vec::new(),
163            css: String::new(),
164        }
165    }
166}
167
168/// `[tailwind] dark_mode`
169#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
170#[serde(rename_all = "lowercase")]
171pub enum TailwindDarkMode {
172    /// Follow the operating system (`prefers-color-scheme`).
173    #[default]
174    Media,
175    /// When an ancestor has the `dark` class.
176    Class,
177    /// When an ancestor has `data-theme="dark"`.
178    Attribute,
179}
180
181/// A custom utility in `[tailwind.utilities]`.
182#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
183#[serde(untagged)]
184pub enum TailwindUtility {
185    /// Tailwind classes combined with `@apply`: `"rounded-lg px-4 py-2"`.
186    Apply(String),
187    /// CSS declarations: `{ content-visibility = "auto" }`.
188    Declarations(BTreeMap<String, String>),
189}
190
191impl From<&str> for TailwindUtility {
192    fn from(classes: &str) -> Self {
193        Self::Apply(classes.to_owned())
194    }
195}
196
197impl From<String> for TailwindUtility {
198    fn from(classes: String) -> Self {
199        Self::Apply(classes)
200    }
201}
202
203#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
204#[serde(default, deny_unknown_fields)]
205pub struct AppConfig {
206    /// Routing directory, scanned recursively.
207    pub directory: PathBuf,
208    /// Static files served from the site root.
209    pub public: PathBuf,
210    /// Mount the whole application under a sub-path, e.g. `/docs`.
211    pub base_path: String,
212    /// `false`: `/about/` redirects to `/about`. `true`: the reverse.
213    pub trailing_slash: bool,
214    /// `lang` attribute of the `<html>` element.
215    pub lang: String,
216    /// What to do when a directory contains both `page.rs` and `page.html`.
217    pub html_precedence: HtmlPrecedence,
218    /// Follow symbolic links while scanning (loops are detected).
219    pub follow_symlinks: bool,
220}
221
222impl Default for AppConfig {
223    fn default() -> Self {
224        Self {
225            directory: PathBuf::from("app"),
226            public: PathBuf::from("public"),
227            base_path: String::new(),
228            trailing_slash: false,
229            lang: "en".into(),
230            html_precedence: HtmlPrecedence::Error,
231            follow_symlinks: true,
232        }
233    }
234}
235
236#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
237#[serde(rename_all = "lowercase")]
238pub enum HtmlPrecedence {
239    /// Report a build error (default).
240    #[default]
241    Error,
242    /// `page.rs` wins; `page.html` is ignored with a warning.
243    Rs,
244    /// `page.html` wins; `page.rs` is ignored with a warning.
245    Html,
246}
247
248#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
249#[serde(default, deny_unknown_fields)]
250pub struct ApiConfig {
251    /// Optional second routing root that only contains `route.rs` handlers.
252    pub directory: Option<PathBuf>,
253    /// URL prefix under which `api.directory` is mounted.
254    pub prefix: String,
255}
256
257impl Default for ApiConfig {
258    fn default() -> Self {
259        Self { directory: None, prefix: "/api".into() }
260    }
261}
262
263#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
264#[serde(default, deny_unknown_fields)]
265pub struct ServerConfig {
266    pub host: String,
267    pub port: u16,
268    /// Maximum buffered request body size in bytes.
269    pub body_limit: usize,
270    /// Seconds allowed for reading request headers (slowloris protection).
271    pub header_timeout: u64,
272    /// Seconds after which an in-flight request is aborted (0 = never).
273    pub request_timeout: u64,
274    /// Seconds to wait for in-flight requests on shutdown.
275    pub shutdown_timeout: u64,
276    pub compression: bool,
277    pub http2: bool,
278    /// Trust `X-Forwarded-For` / `X-Forwarded-Proto` from a reverse proxy.
279    pub trust_proxy: bool,
280}
281
282impl Default for ServerConfig {
283    fn default() -> Self {
284        Self {
285            host: "0.0.0.0".into(),
286            port: 3000,
287            body_limit: 2 * 1024 * 1024,
288            header_timeout: 10,
289            request_timeout: 60,
290            shutdown_timeout: 10,
291            compression: true,
292            http2: false,
293            trust_proxy: false,
294        }
295    }
296}
297
298#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
299#[serde(default, deny_unknown_fields)]
300pub struct BuildConfig {
301    pub output: PathBuf,
302    /// Reserved: static generation currently renders pages sequentially.
303    pub concurrency: usize,
304    /// What `next-rust build` optimizes the binary for.
305    pub optimize: Optimize,
306    /// What happens when code panics in a release binary.
307    pub panic: PanicStrategy,
308}
309
310impl Default for BuildConfig {
311    fn default() -> Self {
312        Self {
313            output: PathBuf::from(".next-rust"),
314            concurrency: 8,
315            optimize: Optimize::Size,
316            panic: PanicStrategy::Unwind,
317        }
318    }
319}
320
321/// `[build] optimize`
322#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
323#[serde(rename_all = "lowercase")]
324pub enum Optimize {
325    /// Smallest binary (`opt-level = "z"`).
326    #[default]
327    Size,
328    /// Fastest code (`opt-level = 3`), larger binary.
329    Speed,
330}
331
332/// `[build] panic`
333#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
334#[serde(rename_all = "lowercase")]
335pub enum PanicStrategy {
336    /// A panic fails only the request that caused it; the server keeps running.
337    #[default]
338    Unwind,
339    /// A panic stops the whole process. About 20% smaller; run it under a
340    /// supervisor that restarts it.
341    Abort,
342}
343
344#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
345#[serde(default, deny_unknown_fields)]
346pub struct AssetsConfig {
347    /// Reserved: CSS is always minified at compile time by the CSS macros.
348    pub optimize: bool,
349    /// `Cache-Control` max-age (seconds) for files from `public/`.
350    pub public_max_age: u64,
351    /// Release builds leave out CSS rules (from `global_css!` and
352    /// `css_module!`) whose classes or ids appear nowhere in the project.
353    pub prune_css: bool,
354    /// Class and id names to keep even though they don't appear in the
355    /// source, e.g. names assembled at runtime.
356    pub css_safelist: Vec<String>,
357}
358
359impl Default for AssetsConfig {
360    fn default() -> Self {
361        Self { optimize: true, public_max_age: 0, prune_css: true, css_safelist: Vec::new() }
362    }
363}
364
365#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
366#[serde(default, deny_unknown_fields)]
367pub struct RenderingConfig {
368    pub default: RenderingMode,
369    /// Stream HTML progressively when a route has `loading.rs` / suspense.
370    pub streaming: bool,
371    /// Default revalidation interval (seconds) for static pages. `None` = never.
372    pub revalidate: Option<u64>,
373    /// Client-side navigation for `Link!` (loads a ~4 KB gzipped script).
374    pub client_navigation: bool,
375}
376
377impl Default for RenderingConfig {
378    fn default() -> Self {
379        Self { default: RenderingMode::Auto, streaming: true, revalidate: None, client_navigation: true }
380    }
381}
382
383#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
384#[serde(default, deny_unknown_fields)]
385pub struct ImagesConfig {
386    /// Reserved for the image optimizer (`Image!` currently uses the same default widths).
387    pub sizes: Vec<u32>,
388    pub quality: u8,
389    /// Seconds optimized images are cached by clients.
390    pub max_age: u64,
391}
392
393impl Default for ImagesConfig {
394    fn default() -> Self {
395        Self { sizes: vec![640, 750, 828, 1080, 1200, 1920, 2048, 3840], quality: 75, max_age: 60 * 60 * 24 * 30 }
396    }
397}
398
399#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
400#[serde(default, deny_unknown_fields)]
401pub struct SecurityConfig {
402    /// Send a conservative set of security headers on every response.
403    pub headers: bool,
404    /// `Content-Security-Policy` value. `{nonce}` is replaced by the per-request nonce.
405    pub csp: Option<String>,
406    /// CSRF protection for server actions.
407    pub csrf: CsrfMode,
408    /// `Strict-Transport-Security` max-age in seconds (0 disables the header).
409    pub hsts_max_age: u64,
410    /// Additional origins allowed to invoke server actions.
411    pub allowed_origins: Vec<String>,
412}
413
414impl Default for SecurityConfig {
415    fn default() -> Self {
416        Self { headers: true, csp: None, csrf: CsrfMode::Origin, hsts_max_age: 0, allowed_origins: Vec::new() }
417    }
418}
419
420#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
421#[serde(rename_all = "lowercase")]
422pub enum CsrfMode {
423    /// Verify `Origin`/`Sec-Fetch-Site` against the request host (default).
424    #[default]
425    Origin,
426    /// Additionally require a double-submit token.
427    Token,
428    /// Disable (not recommended).
429    Off,
430}
431
432#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
433#[serde(default, deny_unknown_fields)]
434pub struct EnvConfig {
435    /// Only variables with this prefix may reach client-visible output.
436    pub public_prefix: String,
437}
438
439impl Default for EnvConfig {
440    fn default() -> Self {
441        Self { public_prefix: "NEXT_RUST_PUBLIC_".into() }
442    }
443}
444
445#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
446#[serde(default, deny_unknown_fields)]
447pub struct DevConfig {
448    /// File watcher polling interval in milliseconds.
449    pub poll_interval: u64,
450    /// Show the error overlay in the browser.
451    pub overlay: bool,
452    /// Extra paths (relative to the project root) that trigger rebuilds.
453    pub watch: Vec<PathBuf>,
454    /// Fill newly created, empty special files (`page.rs`, `layout.rs`,
455    /// `route.rs`, ...) with starter code while `next-rust dev` runs.
456    pub scaffold: bool,
457}
458
459impl Default for DevConfig {
460    fn default() -> Self {
461        Self { poll_interval: 250, overlay: true, watch: Vec::new(), scaffold: true }
462    }
463}
464
465#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
466#[serde(default, deny_unknown_fields)]
467pub struct LoggingConfig {
468    pub format: LogFormat,
469    /// `error`, `warn`, `info`, `debug` or `trace`.
470    /// Default: `info` in development, `error` in production and tests.
471    pub level: Option<String>,
472    /// Log one line per request. Default: on in development, off otherwise.
473    pub requests: Option<bool>,
474}
475
476impl Default for LoggingConfig {
477    fn default() -> Self {
478        Self { format: LogFormat::Auto, level: None, requests: None }
479    }
480}
481
482impl LoggingConfig {
483    /// Effective log level. Production prints only errors unless configured.
484    pub fn level(&self, env: crate::Environment) -> &str {
485        match &self.level {
486            Some(level) => level,
487            None if env.is_dev() => "info",
488            None => "error",
489        }
490    }
491
492    /// Whether request lines are logged. Off outside development unless configured.
493    pub fn requests(&self, env: crate::Environment) -> bool {
494        self.requests.unwrap_or(env.is_dev())
495    }
496}
497
498#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
499#[serde(rename_all = "lowercase")]
500pub enum LogFormat {
501    /// `pretty` in development, `json` in production.
502    #[default]
503    Auto,
504    Pretty,
505    Json,
506}
507
508#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
509#[serde(deny_unknown_fields)]
510pub struct RedirectRule {
511    /// Path pattern: `/old/:slug`, `/blog/:path*`.
512    pub source: String,
513    /// Destination; may reference captured parameters (`/new/:slug`).
514    pub destination: String,
515    #[serde(default)]
516    pub permanent: bool,
517}
518
519#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
520#[serde(deny_unknown_fields)]
521pub struct HeaderRule {
522    pub source: String,
523    pub headers: BTreeMap<String, String>,
524}
525
526#[derive(Debug)]
527pub enum ConfigError {
528    Io { path: PathBuf, error: std::io::Error },
529    Parse { path: PathBuf, message: String },
530    Ambiguous { dir: PathBuf },
531}
532
533impl fmt::Display for ConfigError {
534    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
535        match self {
536            ConfigError::Io { path, error } => write!(f, "could not read {}: {error}", path.display()),
537            ConfigError::Parse { path, message } => {
538                write!(f, "invalid configuration in {}:\n{message}", path.display())
539            }
540            ConfigError::Ambiguous { dir } => write!(
541                f,
542                "both {TOML_FILE} and {JSON_FILE} exist in {}; keep only one (TOML is preferred)",
543                dir.display()
544            ),
545        }
546    }
547}
548
549impl std::error::Error for ConfigError {}
550
551/// Parses TOML configuration. Passed explicitly so programs that never read
552/// TOML at runtime (release binaries, whose configuration is embedded as
553/// JSON) don't link a TOML parser.
554pub type TomlParser = fn(&str) -> Result<Config, String>;
555
556impl Config {
557    /// Discover and load the configuration starting at `start`.
558    pub fn discover(start: impl AsRef<Path>) -> Result<Self, ConfigError> {
559        Self::discover_with(start, Some(Self::from_toml_str))
560    }
561
562    /// [`Config::discover`] with an optional TOML parser. Without one,
563    /// `next-rust.toml` files are reported as an error and only JSON
564    /// configuration can be read.
565    pub fn discover_with(start: impl AsRef<Path>, toml: Option<TomlParser>) -> Result<Self, ConfigError> {
566        if let Ok(explicit) = std::env::var("NEXT_RUST_CONFIG") {
567            return Self::load_with(explicit, toml);
568        }
569        let start = absolutize(start.as_ref());
570        for dir in start.ancestors() {
571            let toml_file = dir.join(TOML_FILE);
572            let json = dir.join(JSON_FILE);
573            match (toml_file.is_file(), json.is_file()) {
574                (true, true) => return Err(ConfigError::Ambiguous { dir: dir.to_path_buf() }),
575                (true, false) => return Self::load_with(toml_file, toml),
576                (false, true) => return Self::load_with(json, toml),
577                _ => {}
578            }
579            // Stop at the Cargo package boundary if there is no config:
580            // zero-config projects are rooted at their manifest.
581            if dir.join("Cargo.toml").is_file() && dir.join("app").is_dir() {
582                break;
583            }
584        }
585        let mut config = Config { root: start, ..Config::default() };
586        config.apply_env_overrides();
587        Ok(config)
588    }
589
590    /// Load a specific file (`.toml` or `.json`).
591    pub fn load(path: impl AsRef<Path>) -> Result<Self, ConfigError> {
592        Self::load_with(path, Some(Self::from_toml_str))
593    }
594
595    /// [`Config::load`] with an optional TOML parser (see [`TomlParser`]).
596    pub fn load_with(path: impl AsRef<Path>, toml: Option<TomlParser>) -> Result<Self, ConfigError> {
597        let path = absolutize(path.as_ref());
598        let text = std::fs::read_to_string(&path).map_err(|error| ConfigError::Io { path: path.clone(), error })?;
599        let mut config = if path.extension().is_some_and(|e| e == "json") {
600            Self::from_json_str(&text)
601        } else {
602            match toml {
603                Some(parse) => parse(&text),
604                None => Err("this binary reads JSON configuration only (its configuration was embedded at build \
605                     time); point NEXT_RUST_CONFIG at a .json file"
606                    .to_owned()),
607            }
608        }
609        .map_err(|message| ConfigError::Parse { path: path.clone(), message })?;
610        config.root = path.parent().map(Path::to_path_buf).unwrap_or_else(|| PathBuf::from("."));
611        config.source = Some(path);
612        config.apply_env_overrides();
613        Ok(config)
614    }
615
616    pub fn from_toml_str(text: &str) -> Result<Self, String> {
617        toml::from_str(text).map_err(|e| e.to_string())
618    }
619
620    pub fn from_json_str(text: &str) -> Result<Self, String> {
621        serde_json::from_str(text).map_err(|e| e.to_string())
622    }
623
624    /// `PORT` and `HOST` (conventional on container platforms) override the file.
625    pub fn apply_env_overrides(&mut self) {
626        if let Some(port) = std::env::var("PORT").ok().and_then(|p| p.parse().ok()) {
627            self.server.port = port;
628        }
629        if let Ok(host) = std::env::var("HOST")
630            && !host.is_empty()
631        {
632            self.server.host = host;
633        }
634    }
635
636    /// Resolve a path from the configuration against the project root.
637    pub fn resolve(&self, path: impl AsRef<Path>) -> PathBuf {
638        let path = path.as_ref();
639        if path.is_absolute() { normalize(path) } else { normalize(&self.root.join(path)) }
640    }
641
642    pub fn app_dir(&self) -> PathBuf {
643        self.resolve(&self.app.directory)
644    }
645
646    pub fn public_dir(&self) -> PathBuf {
647        self.resolve(&self.app.public)
648    }
649
650    pub fn api_dir(&self) -> Option<PathBuf> {
651        self.api.directory.as_ref().map(|d| self.resolve(d))
652    }
653
654    pub fn output_dir(&self) -> PathBuf {
655        self.resolve(&self.build.output)
656    }
657
658    /// Validate paths and values; returns human friendly diagnostics.
659    pub fn validate(&self) -> Vec<Diagnostic> {
660        let mut out = Vec::new();
661        let app = self.app_dir();
662        if !app.exists() {
663            out.push(
664                Diagnostic::error("NR0001", "App directory not found")
665                    .location(&app)
666                    .message(format!(
667                        "The routing directory configured as `app.directory = {:?}`\nresolves to {}, which does not exist.",
668                        self.app.directory,
669                        app.display()
670                    ))
671                    .help("create the directory or change `[app] directory` in next-rust.toml"),
672            );
673        } else if !app.is_dir() {
674            out.push(
675                Diagnostic::error("NR0002", "App directory is not a directory")
676                    .location(&app)
677                    .help("`[app] directory` must point to a directory"),
678            );
679        }
680        if let Some(api) = self.api_dir() {
681            if !api.is_dir() {
682                out.push(Diagnostic::error("NR0003", "API directory not found").location(api));
683            }
684            if !self.api.prefix.starts_with('/') {
685                out.push(
686                    Diagnostic::error("NR0004", "API prefix must start with `/`")
687                        .message(format!("found `api.prefix = {:?}`", self.api.prefix)),
688                );
689            }
690        }
691        if !self.app.base_path.is_empty() && (!self.app.base_path.starts_with('/') || self.app.base_path.ends_with('/'))
692        {
693            out.push(
694                Diagnostic::error("NR0005", "Invalid base path")
695                    .message(format!("`app.base_path = {:?}`", self.app.base_path))
696                    .help("use a leading slash and no trailing slash, e.g. `/docs`"),
697            );
698        }
699        for rule in &self.redirects {
700            if !rule.source.starts_with('/') {
701                out.push(
702                    Diagnostic::error("NR0006", "Redirect source must start with `/`")
703                        .message(format!("source = {:?}", rule.source)),
704                );
705            }
706        }
707        if let Some(level) = &self.logging.level
708            && !matches!(level.as_str(), "error" | "warn" | "info" | "debug" | "trace")
709        {
710            out.push(
711                Diagnostic::warning("NR0007", "Unknown log level")
712                    .message(format!("`logging.level = {level:?}`; falling back to `info`")),
713            );
714        }
715        out
716    }
717
718    pub fn socket_addr_string(&self) -> String {
719        if self.server.host.contains(':') {
720            format!("[{}]:{}", self.server.host, self.server.port)
721        } else {
722            format!("{}:{}", self.server.host, self.server.port)
723        }
724    }
725}
726
727fn absolutize(p: &Path) -> PathBuf {
728    if p.is_absolute() {
729        normalize(p)
730    } else {
731        normalize(&std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")).join(p))
732    }
733}
734
735/// Lexically normalize a path: removes `.` and resolves `..` without
736/// touching the filesystem (so it works for paths that do not exist yet).
737pub fn normalize(path: &Path) -> PathBuf {
738    let mut out = PathBuf::new();
739    for comp in path.components() {
740        match comp {
741            Component::CurDir => {}
742            Component::ParentDir => {
743                if !out.pop() {
744                    out.push("..");
745                }
746            }
747            other => out.push(other.as_os_str()),
748        }
749    }
750    if out.as_os_str().is_empty() { PathBuf::from(".") } else { out }
751}
752
753#[cfg(test)]
754mod tests {
755    use super::*;
756
757    #[test]
758    fn defaults_are_zero_config() {
759        let c = Config::from_toml_str("").unwrap();
760        assert_eq!(c.app.directory, PathBuf::from("app"));
761        assert_eq!(c.server.port, 3000);
762        assert_eq!(c.build.output, PathBuf::from(".next-rust"));
763        assert_eq!(c.rendering.default, RenderingMode::Auto);
764    }
765
766    #[test]
767    fn parses_sections() {
768        let c = Config::from_toml_str(
769            r#"
770            [app]
771            directory = "src/web"
772            [server]
773            port = 8080
774            [rendering]
775            default = "server"
776            [[redirects]]
777            source = "/old"
778            destination = "/new"
779            permanent = true
780            [plugins.analytics]
781            id = "x"
782            "#,
783        )
784        .unwrap();
785        assert_eq!(c.app.directory, PathBuf::from("src/web"));
786        assert_eq!(c.server.port, 8080);
787        assert_eq!(c.rendering.default, RenderingMode::Dynamic);
788        assert!(c.redirects[0].permanent);
789        assert_eq!(c.plugins["analytics"]["id"], "x");
790    }
791
792    #[test]
793    fn rejects_unknown_keys() {
794        let err = Config::from_toml_str("[app]\ndirectroy = \"x\"").unwrap_err();
795        assert!(err.contains("directroy"), "{err}");
796    }
797
798    #[test]
799    fn json_is_supported() {
800        let c = Config::from_json_str(r#"{"app":{"directory":"frontend"}}"#).unwrap();
801        assert_eq!(c.app.directory, PathBuf::from("frontend"));
802    }
803
804    #[test]
805    fn resolves_relative_to_root() {
806        let c = Config {
807            root: PathBuf::from("/work/repo/apps/site"),
808            app: AppConfig { directory: PathBuf::from("../shared/my-pages"), ..Default::default() },
809            ..Default::default()
810        };
811        assert_eq!(c.app_dir(), PathBuf::from("/work/repo/apps/shared/my-pages"));
812        let c = Config {
813            root: PathBuf::from("/work"),
814            app: AppConfig { directory: PathBuf::from("/abs/pages/./x/.."), ..Default::default() },
815            ..Default::default()
816        };
817        assert_eq!(c.app_dir(), PathBuf::from("/abs/pages"));
818    }
819
820    #[test]
821    fn discovery_walks_up() {
822        let base = std::env::temp_dir().join(format!("nr-config-{}", std::process::id()));
823        let nested = base.join("a/b");
824        std::fs::create_dir_all(&nested).unwrap();
825        std::fs::write(base.join(TOML_FILE), "[app]\ndirectory = \"website/routes\"\n").unwrap();
826        let c = Config::discover(&nested).unwrap();
827        assert_eq!(c.root, base);
828        assert_eq!(c.app_dir(), base.join("website/routes"));
829        let diags = c.validate();
830        assert_eq!(diags[0].code, "NR0001");
831        std::fs::write(base.join(JSON_FILE), "{}").unwrap();
832        assert!(matches!(Config::discover(&nested), Err(ConfigError::Ambiguous { .. })));
833        std::fs::remove_dir_all(&base).unwrap();
834    }
835}