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