fraiseql-cli 2.17.1

CLI tools for FraiseQL v2 - Schema compilation and development utilities
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
//! `fraiseql run` — compile schema in-memory and serve the GraphQL API.
//!
//! This command compiles the schema without writing any artifacts to disk and
//! immediately starts the HTTP server.  With `--watch`, the schema file is
//! monitored for changes and the server is hot-reloaded on every save.
//!
//! ## Configuration resolution
//!
//! Settings are resolved in descending priority order:
//!
//! 1. CLI flags (`--port`, `--bind`, `--database`)
//! 2. Environment variables (`DATABASE_URL`, `FRAISEQL_PORT`, `FRAISEQL_HOST`)
//! 3. `fraiseql.toml` `[server]` / `[database]` sections
//! 4. Built-in defaults (`0.0.0.0:8080`, pool 2-20)

use std::{
    net::SocketAddr,
    path::{Path, PathBuf},
    sync::{
        Arc,
        atomic::{AtomicBool, Ordering},
    },
    time::Duration,
};

use anyhow::{Context, Result};
use fraiseql_core::{db::postgres::PostgresAdapter, schema::CompiledSchema};
use fraiseql_server::{
    Server, ServerConfig,
    server_config::{DatabaseTlsConfig, TlsServerConfig},
    url_guard::{DatabaseScheme, parse_database_url},
};
use notify::{
    Config as NotifyConfig, Event, EventKind, RecommendedWatcher, RecursiveMode, Watcher,
};
use tracing::{info, warn};

use super::compile::{CompileOptions, compile_to_schema};
use crate::config::{
    ConfigSource, DatabaseRuntimeConfig, ServerRuntimeConfig, TomlProjectConfig, TomlSchema,
    runtime::TlsRuntimeConfig,
};

/// Run the `fraiseql run` command.
///
/// # Arguments
///
/// * `input`         - Path to input file; `None` triggers auto-detection.
/// * `database`      - Database URL override; falls back to `DATABASE_URL` env var, then to
///   `[database].url` in `fraiseql.toml`.
/// * `port`          - TCP port override; `None` means fall back to TOML / default.
/// * `bind`          - Bind host override; `None` means fall back to TOML / default.
/// * `watch`         - Watch input file for changes and hot-reload.
/// * `introspection` - Enable the `/introspection` endpoint (no auth).
///
/// # Errors
///
/// Returns error if the input file cannot be found, the schema fails to compile,
/// the database URL is missing from all sources, or the server cannot bind.
pub async fn run(
    input: Option<&str>,
    database: Option<String>,
    port: Option<u16>,
    bind: Option<String>,
    watch: bool,
    introspection: bool,
) -> Result<()> {
    let input_path = resolve_input(input)?;

    let (db_url, bind_addr, server_cfg, db_cfg) =
        resolve_runtime_config(&input_path, database, port, bind)?;

    println!("FraiseQL");
    println!("   Schema: {}", input_path.display());
    println!("   Server: http://{bind_addr}/graphql");
    println!();

    // Box::pin both branches: each holds the per-adapter init futures the
    // dispatch helper splits into. Heap-allocating once per `fraiseql run`
    // invocation keeps clippy's `large_futures` lint satisfied.
    if watch {
        Box::pin(run_watch_loop(
            &input_path,
            &db_url,
            bind_addr,
            introspection,
            &server_cfg,
            &db_cfg,
        ))
        .await
    } else {
        Box::pin(run_once(&input_path, &db_url, bind_addr, introspection, &server_cfg, &db_cfg))
            .await
    }
}

// ─── helpers ─────────────────────────────────────────────────────────────────

/// Compile the schema and start the server once (no watch).
async fn run_once(
    input_path: &Path,
    db_url: &str,
    bind_addr: SocketAddr,
    introspection: bool,
    server_cfg: &ServerRuntimeConfig,
    db_cfg: &DatabaseRuntimeConfig,
) -> Result<()> {
    let scheme = parse_database_url(db_url)?;
    let schema = compile_schema(input_path).await?;
    let config = build_config_from(db_url, bind_addr, server_cfg, db_cfg, introspection)?;

    println!("Server ready at http://{bind_addr}/graphql");
    println!("   Press Ctrl+C to stop");
    println!();

    Box::pin(dispatch_serve(scheme, config, schema, None)).await
}

/// Watch-loop: compile -> serve -> detect file change -> restart.
async fn run_watch_loop(
    input_path: &Path,
    db_url: &str,
    bind_addr: SocketAddr,
    introspection: bool,
    server_cfg: &ServerRuntimeConfig,
    db_cfg: &DatabaseRuntimeConfig,
) -> Result<()> {
    let scheme = parse_database_url(db_url)?;

    loop {
        let schema = compile_schema(input_path).await?;
        let config = build_config_from(db_url, bind_addr, server_cfg, db_cfg, introspection)?;

        println!("Server ready at http://{bind_addr}/graphql");
        println!("   Watching {} for changes...  (Ctrl+C to stop)", input_path.display());
        println!();

        // oneshot channel: file watcher signals server to shut down
        let (change_tx, change_rx) = tokio::sync::oneshot::channel::<()>();

        // AtomicBool: was the shutdown triggered by a file change?
        let restarting = Arc::new(AtomicBool::new(false));
        let restarting_for_watcher = restarting.clone();

        // Spawn file watcher on a blocking thread (notify uses std channels)
        let watch_path = input_path.to_path_buf();
        let _watcher_guard = spawn_file_watcher(watch_path, move |_event| {
            restarting_for_watcher.store(true, Ordering::SeqCst);
            let _ = change_tx.send(());
        })?;

        Box::pin(dispatch_serve(
            scheme,
            config,
            schema,
            Some(Box::pin(async move {
                tokio::select! {
                    () = sigint_signal() => {},
                    result = change_rx => {
                        if result.is_err() {
                            // Sender dropped without sending — treat as OS signal
                        }
                    },
                }
            })),
        ))
        .await?;

        if !restarting.load(Ordering::SeqCst) {
            // Shutdown was triggered by Ctrl+C / SIGTERM — exit cleanly
            break;
        }

        // Small delay to ensure the file write is complete before re-reading
        tokio::time::sleep(Duration::from_millis(200)).await;
        println!("Schema changed, recompiling...");
    }

    Ok(())
}

/// Wait for the OS-level shutdown signal (SIGINT / Ctrl-C), wrapped so that
/// each [`dispatch_serve`] call can wire it into a `serve_with_shutdown`
/// future without taking a turbofish on the concrete `Server<…>` type.
async fn sigint_signal() {
    let _ = tokio::signal::ctrl_c().await;
}

/// Type alias for the per-loop shutdown future passed to
/// [`dispatch_serve`]. `None` means "use the default `serve()` shutdown
/// handling"; `Some(fut)` is forwarded to `serve_with_shutdown(fut)`.
type ShutdownFuture =
    Option<std::pin::Pin<Box<dyn std::future::Future<Output = ()> + Send + 'static>>>;

/// Dispatch the configured database URL scheme to the matching adapter and
/// hand the resulting `Server` to either `serve()` or `serve_with_shutdown()`.
async fn dispatch_serve(
    scheme: DatabaseScheme,
    config: ServerConfig,
    schema: CompiledSchema,
    shutdown: ShutdownFuture,
) -> Result<()> {
    // Box::pin: the adapter-init future exceeds clippy's `large_futures`
    // 16-KiB stack threshold. Heap-allocating once at server startup is free.
    match scheme {
        DatabaseScheme::Postgres => Box::pin(serve_postgres(config, schema, shutdown)).await,
    }
}

async fn serve_postgres(
    config: ServerConfig,
    schema: CompiledSchema,
    shutdown: ShutdownFuture,
) -> Result<()> {
    let tls = config.postgres_tls().map_err(|e| anyhow::anyhow!(e))?;
    tls.warn_if_unverified();

    let adapter = Arc::new(
        PostgresAdapter::with_pool_config(
            &config.database_url,
            fraiseql_core::db::postgres::PoolPrewarmConfig {
                min_size:            config.pool_min_size,
                max_size:            config.pool_max_size,
                timeout_secs:        Some(config.pool_timeout_secs),
                search_path:         None,
                // `[database] ssl_mode` arrives here through `ServerConfig.database_tls`,
                // the single seam both binaries read. It used to stop at `validate()`
                // (#824).
                tls:                 tls.clone(),
                read_replicas:       config.read_replicas(),
                max_streaming_reads: config.pool_max_streaming_reads,
                // The same accessor the server binary reads (#1116).
                vector_scan:         config.vector_scan(),
            },
        )
        .await
        .with_context(|| {
            format!("Failed to connect to database (ssl_mode = {})", tls.effective_mode())
        })?,
    );
    let server: Server =
        // Box the server-init future: it exceeds clippy's `large_futures` stack
        // threshold once the platform features are compiled in (`--all-features`).
        Box::pin(Server::new(config, schema, adapter, None))
            .await
            .context("Failed to initialize server")?;
    Box::pin(finish_serve(server, shutdown)).await
}

async fn finish_serve(server: Server, shutdown: ShutdownFuture) -> Result<()> {
    if let Some(shutdown) = shutdown {
        server.serve_with_shutdown(shutdown).await.context("Server error")
    } else {
        // Boxed for the same reason as `fraiseql-server`'s own main: `Server` is large
        // and this future carries it, past clippy::large_futures' 16 KiB threshold as of
        // #1102. One allocation, once, on a future that runs for the process's life.
        Box::pin(server.serve()).await.context("Server error")
    }
}

/// Resolve all runtime configuration, applying the override precedence chain.
///
/// Priority (highest first):
/// 1. CLI flags (`db_cli`, `port_cli`, `bind_cli`)
/// 2. Standard environment variables (`DATABASE_URL`, `FRAISEQL_PORT`, `FRAISEQL_HOST`)
/// 3. `fraiseql.toml` `[server]` / `[database]` sections
/// 4. Built-in defaults
///
/// Returns `(db_url, bind_addr, server_runtime_config, database_runtime_config)`.
pub(crate) fn resolve_runtime_config(
    input_path: &Path,
    db_cli: Option<String>,
    port_cli: Option<u16>,
    bind_cli: Option<String>,
) -> Result<(String, SocketAddr, ServerRuntimeConfig, DatabaseRuntimeConfig)> {
    // 1. Load [server] and [database] from TOML (fatal for primary .toml, best-effort otherwise)
    let (server_cfg, db_cfg) = load_runtime_config_from_toml(input_path)?;

    // 2. Resolve database URL Priority: CLI flag > DATABASE_URL env > TOML [database].url
    let db_url = db_cli
        .or_else(|| std::env::var("DATABASE_URL").ok())
        .or_else(|| db_cfg.url.clone())
        .ok_or_else(|| {
            anyhow::anyhow!(
                "No database URL provided. Use --database, set DATABASE_URL env var, \
                 or set [database].url in fraiseql.toml."
            )
        })?;

    // 3. Resolve host and port Priority: CLI flags > FRAISEQL_HOST/FRAISEQL_PORT env > TOML
    //    [server].*
    let host = bind_cli
        .or_else(|| std::env::var("FRAISEQL_HOST").ok())
        .unwrap_or_else(|| server_cfg.host.clone());

    let port = port_cli
        .or_else(|| std::env::var("FRAISEQL_PORT").ok().and_then(|v| v.parse::<u16>().ok()))
        .unwrap_or(server_cfg.port);

    let bind_addr: SocketAddr = format!("{host}:{port}").parse().context("Invalid bind address")?;

    server_cfg.validate()?;
    db_cfg.validate()?;

    Ok((db_url, bind_addr, server_cfg, db_cfg))
}

/// Load `[server]` and `[database]` runtime config from the input file.
///
/// For `.toml` input files the sections are embedded directly. For `.json` input
/// files the project config is the one [`ConfigSource::resolve`] names — the same
/// file the compile step reads (#1387) — loaded as `TomlProjectConfig`. Defaults
/// apply only when no config applies; one that fails to parse is an error.
fn load_runtime_config_from_toml(
    input_path: &Path,
) -> Result<(ServerRuntimeConfig, DatabaseRuntimeConfig)> {
    let ext = input_path.extension().and_then(|e| e.to_str()).unwrap_or("");

    if ext == "toml" {
        // Workflow A: the input IS the fraiseql.toml — parse errors are fatal
        let schema =
            TomlSchema::from_file(input_path.to_str().unwrap_or("")).with_context(|| {
                format!("Failed to load runtime config from {}", input_path.display())
            })?;
        info!("Loaded [server] and [database] config from {}", input_path.display());
        warn_ignored_config_sections(input_path);
        return Ok((schema.server, schema.database));
    }

    // Workflow B: input is schema.json — the config the compile step reads too.
    let source = ConfigSource::resolve(input_path, None)?;
    let Some(toml_path) = source.project_config() else {
        info!("Project config: {source}");
        return Ok((ServerRuntimeConfig::default(), DatabaseRuntimeConfig::default()));
    };
    let cfg = TomlProjectConfig::from_file(toml_path.to_str().unwrap_or_default())
        .with_context(|| format!("Failed to load runtime config from {}", toml_path.display()))?;
    info!("Loaded [server] and [database] config from {}", toml_path.display());
    warn_ignored_config_sections(toml_path);
    Ok((cfg.server, cfg.database))
}

/// Config-file sections that a full `server.toml` deployment relies on but that
/// `fraiseql run` does not consume. `run` is a development quick-launcher: it reads
/// only `[server]` and `[database]` (see [`load_runtime_config_from_toml`]) and builds
/// the rest of the server from `ServerConfig::default()`, so every table below is
/// dropped. The production entrypoint that honors them is the `fraiseql-server` binary
/// (shipped in the `-full` release tarball) run with `--config`.
const RUN_IGNORED_CONFIG_SECTIONS: &[&str] = &[
    "auth",
    "federation",
    "observers",
    "enrichment",
    "tenancy",
    "storage",
    "security",
];

/// Return the ignored platform sections that are present in a raw TOML config, in
/// [`RUN_IGNORED_CONFIG_SECTIONS`] order (stable for a testable/greppable message).
///
/// The typed `[server]`/`[database]` structs cannot see the other tables, so this
/// re-parses the raw contents into a generic [`toml::Table`] — the same technique the
/// server binary uses to surface a `[observers]` section built without the feature. A
/// parse failure yields an empty list: the config was already loaded for
/// `[server]`/`[database]`, so this stays a best-effort advisory, never a second hard
/// parse gate.
pub(crate) fn ignored_config_sections(contents: &str) -> Vec<&'static str> {
    let Ok(table) = toml::from_str::<toml::Table>(contents) else {
        return Vec::new();
    };
    RUN_IGNORED_CONFIG_SECTIONS
        .iter()
        .copied()
        .filter(|section| table.contains_key(*section))
        .collect()
}

/// Warn (never fail) when the loaded config declares sections `fraiseql run` ignores.
///
/// Pointing the dev quick-launcher at a full `server.toml` is legitimate
/// quick-iteration, so this is a warning rather than a boot refusal — but silently
/// dropping the sections would be the same class of defect as #612 (config accepted
/// then ignored). Naming each dropped section and the entrypoint that honors it keeps
/// the behavior honest and loud.
fn warn_ignored_config_sections(config_path: &Path) {
    let Ok(contents) = std::fs::read_to_string(config_path) else {
        return;
    };
    let present = ignored_config_sections(&contents);
    if present.is_empty() {
        return;
    }
    let named = present.iter().map(|s| format!("[{s}]")).collect::<Vec<_>>().join(", ");
    warn!(
        ignored_sections = %present.join(", "),
        "`fraiseql run` is a development quick-launcher that consumes only [server] and \
         [database]; the config section(s) {named} in {} are ignored. For a deployment \
         that honors them, run the `fraiseql-server` binary (shipped in the -full release \
         tarball) with `--config {}`.",
        config_path.display(),
        config_path.display(),
    );
}

/// Build a `ServerConfig` from resolved runtime parameters.
///
/// Constructs the config from TOML-derived values and CLI overrides, then
/// applies any server-production overrides (metrics, admin, rate limiting)
/// from env vars via [`fraiseql_server::ServerArgs`].
pub(crate) fn build_config_from(
    db_url: &str,
    bind_addr: SocketAddr,
    server: &ServerRuntimeConfig,
    db_cfg: &DatabaseRuntimeConfig,
    introspection: bool,
) -> Result<ServerConfig> {
    let tls = server.tls.enabled.then(|| build_tls_config(&server.tls));

    let mut config = ServerConfig {
        database_url: db_url.to_string(),
        bind_addr,
        cors_enabled: true,
        cors_origins: server.cors.origins.clone(),
        tls,
        // `[database] ssl_mode` is carried as a `[database_tls]` section so both the
        // `fraiseql run` launcher and the `fraiseql-server` binary reach the pool
        // through one seam (`ServerConfig::postgres_tls`) rather than two that can
        // disagree — which is how one of them came to drop the setting entirely (#824).
        database_tls: Some(DatabaseTlsConfig {
            postgres_ssl_mode:   db_cfg.ssl_mode.clone(),
            verify_certificates: true,
            ca_bundle_path:      None,
            redis_ssl:           None,
            clickhouse_https:    None,
            elasticsearch_https: None,
        }),
        pool_min_size: db_cfg.pool_min,
        pool_max_size: db_cfg.pool_max,
        pool_timeout_secs: db_cfg.pool_timeout_secs(),
        introspection_enabled: introspection,
        // When introspection is requested via CLI flag, serve it without requiring auth
        // (development convenience; production setups use fraiseql-server directly).
        introspection_require_auth: false,
        ..ServerConfig::default()
    };

    // Apply any server-production env var overrides (metrics, admin, rate
    // limiting, etc.) via the shared ServerArgs struct.  This picks up env
    // vars like FRAISEQL_METRICS_ENABLED without duplicating the parsing
    // logic here.
    let server_args = fraiseql_server::ServerArgs::from_env()
        .map_err(|e| anyhow::anyhow!("invalid server environment variable: {e}"))?;
    server_args.apply_to_config(&mut config);

    Ok(config)
}

/// Convert `TlsRuntimeConfig` → `TlsServerConfig`.
fn build_tls_config(tls: &TlsRuntimeConfig) -> TlsServerConfig {
    TlsServerConfig {
        enabled:             true,
        cert_path:           tls.cert_file.clone().into(),
        key_path:            tls.key_file.clone().into(),
        min_version:         tls.min_version.clone(),
        require_client_cert: false,
        client_ca_path:      None,
    }
}

/// Compile the schema at `path`, printing progress to stdout.
pub(crate) async fn compile_schema(path: &Path) -> Result<fraiseql_core::schema::CompiledSchema> {
    let input = path.to_str().ok_or_else(|| anyhow::anyhow!("Input path is not valid UTF-8"))?;

    println!("Compiling schema...");

    let (artifact, _report) = compile_to_schema(CompileOptions::new(input))
        .await
        .context("Schema compilation failed")?;
    refuse_declared_functions(artifact.functions.as_ref(), &artifact.schema.sources)?;
    let schema = artifact.schema;

    println!(
        "   Schema compiled ({} types, {} queries, {} mutations)",
        schema.types.len(),
        schema.queries.len(),
        schema.mutations.len(),
    );
    println!();

    Ok(schema)
}

/// Refuse a schema that declares functions or enabled sources: `fraiseql run` has no
/// function runtime (#1339), and a source's connector is a Deno module (#1399).
///
/// The rule the server applies at boot (#1326), at the seam that bypasses its loader:
/// `fraiseql run` hands the compiled schema straight to the server, so the server's
/// refusal never sees the `functions` section, and the section used to be dropped here —
/// the server started clean and every declared function silently never ran. A declared
/// section a build cannot serve is a misconfiguration, not a note.
///
/// # Errors
///
/// When the schema declares a function, or an enabled source whose connector would
/// never run.
pub(crate) fn refuse_declared_functions(
    functions: Option<&fraiseql_functions::FunctionsConfig>,
    sources: &[fraiseql_core::schema::SourceDefinition],
) -> Result<()> {
    let unrunnable: Vec<String> =
        functions
            .iter()
            .flat_map(|functions| &functions.definitions)
            .map(|definition| format!("function `{}`", definition.name))
            .chain(sources.iter().filter(|source| source.enabled).map(|source| {
                format!("source `{}` (connector `{}`)", source.name, source.function)
            }))
            .collect();
    if unrunnable.is_empty() {
        return Ok(());
    }
    anyhow::bail!(
        "this schema declares code that `fraiseql run` cannot run: {}. It has no function \
         runtime, so none of it would ever run — the server would start clean and drop it. To \
         run it, serve the compiled schema with `fraiseql-server` built with the \
         `functions-runtime` feature (`sources` for a source; the `-full` release tarball). To \
         run without it, remove the functions and disable the sources.",
        unrunnable.join(", ")
    )
}

/// Spawn a file watcher that calls `on_change` once when a write event is detected.
///
/// Returns the watcher guard — drop it to stop watching.
fn spawn_file_watcher<F>(path: PathBuf, on_change: F) -> Result<RecommendedWatcher>
where
    F: FnOnce(Event) + Send + 'static,
{
    use std::sync::mpsc::channel;

    let (tx, rx) = channel::<Result<Event, notify::Error>>();

    let mut watcher = RecommendedWatcher::new(
        move |res| {
            let _ = tx.send(res);
        },
        NotifyConfig::default().with_poll_interval(Duration::from_millis(500)),
    )
    .context("Failed to create file watcher")?;

    watcher
        .watch(&path, RecursiveMode::NonRecursive)
        .context("Failed to watch input file")?;

    // Drain events on a dedicated blocking thread — fires once then exits
    std::thread::spawn(move || {
        for event in rx.into_iter().flatten() {
            if matches!(event.kind, EventKind::Modify(_)) {
                info!("Schema file changed");
                on_change(event);
                break;
            }
        }
    });

    Ok(watcher)
}

/// Resolve the input file path from an optional argument or by auto-detection.
///
/// Priority: explicit arg -> `fraiseql.toml` -> `schema.json` -> error.
pub(crate) fn resolve_input(input: Option<&str>) -> Result<PathBuf> {
    if let Some(path) = input {
        let p = PathBuf::from(path);
        if p.exists() {
            return Ok(p);
        }
        anyhow::bail!("Input file not found: {path}");
    }

    auto_detect_input(&std::env::current_dir().unwrap_or_default())
}

/// Search `base` for the first of `fraiseql.toml` / `schema.json`.
pub(crate) fn auto_detect_input(base: &Path) -> Result<PathBuf> {
    let candidates = ["fraiseql.toml", "schema.json"];
    for candidate in &candidates {
        let p = base.join(candidate);
        if p.exists() {
            info!("Auto-detected input file: {candidate}");
            return Ok(p);
        }
    }

    anyhow::bail!(
        "No input file found. Create a fraiseql.toml (or schema.json) in the current \
         directory, or pass an explicit path: fraiseql run <INPUT>"
    )
}