crepuscularity-cli 0.7.22

crepus CLI — scaffolding and builds for Crepuscularity (UNSTABLE; in active development).
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
//! crepus — the Crepuscularity CLI
//!
//! COMMANDS
//!   crepus new NAME                              scaffold a new GPUI app
//!   crepus init KIND NAME                        scaffold web, webext, tui, native, ios, or gpui
//!   crepus dev [--bin NAME] [--release] [--emit-events]  watch → rebuild → relaunch
//!   crepus build [TYPE|ID] [--target ID] [--manifest FILE] build crepus.toml targets, or cargo fallback
//!   crepus preview FILE                          live-preview a .crepus template
//!   crepus render FILE [--ctx FILE] [--var k=v] [--component Name]
//!   crepus web new NAME                          scaffold index.crepus + runtime/ + crepus.toml
//!   crepus web build [--site DIR] [--out-dir DIR]   dist/ with WASM + crepus-bundle.json
//!   crepus web site-json [--site DIR]             pretty-print site.json (deprecated)
//!   crepus webext new NAME                       scaffold a browser extension
//!   crepus webext build [--app PATH]             build browser extension
//!   crepus webext manifest [--app PATH]          print manifest.json
//!   crepus ios new NAME                      XcodeGen + SwiftPM NativeShell host app
//!   crepus ios generate [--dir PATH]         run xcodegen (brew install xcodegen)
//!   crepus ios build [--dir] [--scheme] [...]  xcodegen + xcodebuild; toml = defaults
//!   crepus tui new NAME                         scaffold TUI app with Ratatui
//!   crepus tui build [--release]                 build TUI app
//!   crepus tui run                               run TUI app
//!   crepus tui preview FILE                      hot-reload preview a .crepus template in the terminal
//!   crepus native new NAME                       scaffold cross-platform native app
//!   crepus native ir FILE                        emit View IR JSON
//!   crepus native build ios [--scheme S]         build iOS app
//!   crepus native build android [--flavor F]     build Android app
//!   crepus native run ios                        run iOS app (Xcode)
//!   crepus native run android                    install Android app
//!   crepus embedded check FILE
//!   crepus embedded snapshot FILE --width W --height H --out path.ppm
//!   crepus aurora dev [--watch DIR] [--port N]
//!   crepus aurora build --watch DIR --out DIR
//!   crepus aurora new NAME
//!   crepus aurora swiftgen --view FILE --out DIR --view-name NAME
//!   crepus benchmark [all|run|check] [flags…]    benchmark.toml run or prereq check (examples/benchmarks)

mod aurora;
mod benchmark;
mod benchmark_tui;
#[cfg(feature = "desktop")]
mod builder;
mod crepus_toml;
#[cfg(feature = "desktop")]
mod dev;
mod embedded;
#[cfg(feature = "desktop")]
pub mod events;
#[cfg(feature = "desktop")]
mod hud;
mod ios;
mod native;
mod new;
mod render;
mod target_build;
mod tui;
pub mod ui;
mod wasm_bundle;
mod web;
mod web_docs_hook;
mod web_islands;
mod web_serve;
mod webext;

use console::style;
#[cfg(feature = "desktop")]
use std::time::Instant;

fn main() {
    tracing_subscriber::fmt()
        .with_env_filter(
            tracing_subscriber::EnvFilter::from_default_env()
                .add_directive("crepuscularity=info".parse().unwrap()),
        )
        .with_target(false)
        .init();

    let args: Vec<String> = std::env::args().collect();

    match args.get(1).map(|s| s.as_str()) {
        Some("--version") | Some("-V") => {
            println!("crepus cli {}", env!("CARGO_PKG_VERSION"));
            std::process::exit(0);
        }

        Some("--help") | Some("-h") => {
            print_usage();
            std::process::exit(0);
        }

        Some("new") => {
            let name = args.get(2).map(|s| s.as_str()).unwrap_or_else(|| {
                ui::error("Usage: crepus new <name>");
            });
            new::run(name);
        }

        Some("init") => {
            run_init(&args[2..]);
        }

        #[cfg(feature = "desktop")]
        Some("dev") => {
            let mut bin: Option<String> = None;
            let mut release = false;
            let mut emit_events = false;
            let mut i = 2;
            while i < args.len() {
                match args[i].as_str() {
                    "--bin" => {
                        i += 1;
                        bin = args.get(i).cloned();
                    }
                    "--release" => release = true,
                    "--emit-events" => emit_events = true,
                    _ => {}
                }
                i += 1;
            }
            dev::run(bin, release, emit_events);
        }

        #[cfg(feature = "desktop")]
        Some("build") => {
            let manifest_arg = manifest_arg(&args[2..]);
            if args[2..]
                .iter()
                .any(|a| matches!(a.as_str(), "--target" | "-t" | "--manifest" | "--all"))
                || args[2..]
                    .iter()
                    .any(|a| !a.starts_with('-') && a.as_str() != "release")
                || target_build::has_manifest_targets(manifest_arg)
            {
                target_build::run(&args[2..]);
                return;
            }
            let t0 = Instant::now();
            let release = args.iter().any(|a| a == "--release");
            let cwd = std::env::current_dir().unwrap_or_else(|e| {
                ui::error(&format!("cannot determine current directory: {e}"));
            });
            let sp = ui::spinner(if release {
                "cargo build --release"
            } else {
                "cargo build"
            });
            let outcome = builder::cargo_build(&cwd, release, None);
            if outcome.success {
                ui::spinner_ok(&sp, "build succeeded");
                ui::done_in(t0.elapsed());
            } else {
                sp.finish_and_clear();
                ui::error("build failed");
            }
        }

        #[cfg(feature = "desktop")]
        Some("preview") => {
            let path = args
                .get(2)
                .map(std::path::PathBuf::from)
                .unwrap_or_else(|| {
                    ui::error("Usage: crepus preview <file.crepus>");
                });
            if !path.exists() {
                ui::error(&format!("file not found: {}", path.display()));
            }
            eprintln!(
                "{} previewing {}",
                style("crepus").dim(),
                style(path.display().to_string()).cyan().bold()
            );
            run_preview(path);
        }

        Some("render") => {
            render::run(&args[2..]);
        }

        Some("web") => {
            web::run(&args[2..]);
        }

        Some("webext") => {
            webext::run(&args[2..]);
        }

        Some("ios") => {
            ios::run(&args[2..]);
        }

        Some("tui") => {
            tui::run(&args[2..]);
        }

        Some("native") => {
            native::run(&args[2..]);
        }

        Some("aurora") => {
            aurora::run(&args[2..]);
        }

        Some("embedded") => {
            embedded::run(&args[2..]);
        }

        Some("benchmark") => match args.get(2).map(|s| s.as_str()) {
            Some("check") => benchmark::run_check(args.get(3..).unwrap_or(&[])),
            _ => benchmark::run(args.get(2..).unwrap_or(&[])),
        },

        _ => {
            print_usage();
            std::process::exit(1);
        }
    }
}

fn manifest_arg(args: &[String]) -> Option<std::path::PathBuf> {
    let mut i = 0;
    while i < args.len() {
        if args[i] == "--manifest" {
            return args.get(i + 1).map(std::path::PathBuf::from);
        }
        i += 1;
    }
    None
}

fn run_init(args: &[String]) {
    let kind = args
        .first()
        .map(|s| s.as_str())
        .unwrap_or_else(|| ui::error("Usage: crepus init <kind> <name>"));
    let name = args
        .get(1)
        .map(|s| s.as_str())
        .unwrap_or_else(|| ui::error("Usage: crepus init <kind> <name>"));
    if args.len() > 2 {
        ui::error("Usage: crepus init <kind> <name>");
    }
    let sub_args = vec!["new".to_string(), name.to_string()];
    match kind {
        "web" => web::run(&sub_args),
        "webext" | "extension" | "browser-extension" => webext::run(&sub_args),
        "tui" => tui::run(&sub_args),
        "native" => native::run(&sub_args),
        "ios" => ios::run(&sub_args),
        "gpui" | "app" | "desktop" => new::run(name),
        other => ui::error(&format!(
            "unknown init kind {other:?}; expected web, webext, tui, native, ios, or gpui"
        )),
    }
}

fn print_usage() {
    eprintln!(
        "{} cli {}",
        style("crepus").cyan().bold(),
        style(env!("CARGO_PKG_VERSION")).dim()
    );
    eprintln!();
    eprintln!("{}", style("COMMANDS").dim());
    eprintln!(
        "  {}  {}",
        style("new <name>                           ").green(),
        style("scaffold a new GPUI app").dim()
    );
    eprintln!(
        "  {}  {}",
        style("init <kind> <name>                    ").green(),
        style("scaffold web, webext, tui, native, ios, or gpui").dim()
    );
    eprintln!(
        "  {}  {}",
        style("dev [--bin NAME] [--release]         ").green(),
        style("hot-reload dev loop").dim()
    );
    eprintln!(
        "  {}  {}",
        style("build [TYPE|ID] [--target ID] [--manifest FILE]").green(),
        style("build crepus.toml targets, or cargo fallback").dim()
    );
    eprintln!(
        "  {}  {}",
        style("preview <file.crepus>                ").green(),
        style("live-preview a template (GPUI window)").dim()
    );
    eprintln!(
        "  {}  {}",
        style("render <file.crepus> [--ctx] [--var] ").green(),
        style("render template to HTML on stdout").dim()
    );
    eprintln!(
        "  {}  {}",
        style("web new <name>                       ").green(),
        style("scaffold .crepus site + WASM runtime/").dim()
    );
    eprintln!(
        "  {}  {}",
        style("web build [--site] [--out-dir]       ").green(),
        style("static dist/ — HTML shell + WASM bundle").dim()
    );
    eprintln!(
        "  {}  {}",
        style("web site-json [--site DIR]           ").green(),
        style("pretty-print site.json").dim()
    );
    eprintln!(
        "  {}  {}",
        style("web dev [--site DIR] [--port N]      ").green(),
        style("live-reload dev server (alias: serve)").dim()
    );
    eprintln!();
    eprintln!(
        "  {}  {}",
        style("webext new <name>                    ").green(),
        style("scaffold a browser extension").dim()
    );
    eprintln!(
        "  {}  {}",
        style("webext build [--app PATH]            ").green(),
        style("build extension to dist/unpacked/").dim()
    );
    eprintln!(
        "  {}  {}",
        style("webext manifest [--app PATH]         ").green(),
        style("print manifest.json").dim()
    );
    eprintln!(
        "  {}  {}",
        style("ios new <name>                         ").green(),
        style("XcodeGen + NativeShell SwiftPM app").dim()
    );
    eprintln!(
        "  {}  {}",
        style("ios generate [--dir] [--spec]          ").green(),
        style("xcodegen; finds crepus.toml [ios] up-tree").dim()
    );
    eprintln!(
        "  {}  {}",
        style("ios build [--dir] [--scheme] [...]     ").green(),
        style("xcodegen + xcodebuild; toml = defaults").dim()
    );
    eprintln!(
        "  {}  {}",
        style("tui new <name>                         ").green(),
        style("scaffold TUI app with Ratatui").dim()
    );
    eprintln!(
        "  {}  {}",
        style("tui build [--release]                   ").green(),
        style("build TUI app").dim()
    );
    eprintln!(
        "  {}  {}",
        style("tui preview <file.crepus>               ").green(),
        style("hot-reload preview a .crepus template in the terminal").dim()
    );
    eprintln!(
        "  {}  {}",
        style("native new <name>                       ").green(),
        style("scaffold native iOS/Android app").dim()
    );
    eprintln!(
        "  {}  {}",
        style("native ir <file.crepus>                  ").green(),
        style("emit View IR JSON").dim()
    );
    eprintln!(
        "  {}  {}",
        style("native build ios [--scheme]             ").green(),
        style("build native iOS app").dim()
    );
    eprintln!(
        "  {}  {}",
        style("native build android [--flavor]         ").green(),
        style("build native Android app").dim()
    );
    eprintln!(
        "  {}  {}",
        style("embedded check <file> [--component Name]  ").green(),
        style("validate .crepus for CI / build.rs").dim()
    );
    eprintln!(
        "  {}  {}",
        style("embedded snapshot <file> -W -H --out ppm").green(),
        style("debug PPM only (use Rust API in firmware)").dim()
    );
    eprintln!(
        "  {}  {}",
        style("aurora dev [--watch DIR]           ").green(),
        style("hot-reload preview window (SwiftUI Runner).").dim()
    );
    eprintln!(
        "  {}  {}",
        style("aurora run [PROJECT] [--macos|--ios]").green(),
        style("build & launch a SwiftUI project.").dim()
    );
    eprintln!(
        "  {}  {}",
        style("benchmark [all|run|check] [flags…]   ").green(),
        style("benchmark.toml run or prereq probe (see examples/benchmarks)").dim()
    );
    eprintln!();
    eprintln!("{}", style("OPTIONS").dim());
    eprintln!(
        "  {}  {}",
        style("-h, --help                           ").green(),
        style("show this help").dim()
    );
    eprintln!(
        "  {}  {}",
        style("-V, --version                        ").green(),
        style("show version").dim()
    );
    eprintln!(
        "  {}  {}",
        style("--emit-events                        ").green(),
        style("emit JSON events to stdout (IDE integration)").dim()
    );
}

#[cfg(feature = "desktop")]
fn run_preview(path: std::path::PathBuf) {
    use crepuscularity_runtime::{HotReloadState, HotReloadView, TemplateContext};
    use gpui::{
        bounds, point, prelude::*, px, size, Application, WindowBackgroundAppearance, WindowKind,
        WindowOptions,
    };

    let display_name = path
        .file_name()
        .and_then(|n| n.to_str())
        .unwrap_or("preview")
        .to_string();

    let mut ctx = TemplateContext::new();
    if let Some(dir) = path.parent() {
        let ctx_path = dir.join("context.toml");
        if ctx_path.exists() {
            load_context_toml(&ctx_path, &mut ctx);
        }
    }

    Application::new().run(move |cx: &mut gpui::App| {
        let opts = WindowOptions {
            window_bounds: Some(gpui::WindowBounds::Windowed(bounds(
                point(px(100.), px(100.)),
                size(px(1200.), px(800.)),
            ))),
            titlebar: None,
            focus: true,
            show: true,
            kind: WindowKind::Normal,
            is_movable: true,
            is_resizable: true,
            is_minimizable: true,
            display_id: None,
            window_background: WindowBackgroundAppearance::Opaque,
            app_id: Some(format!("crepuscularity.preview.{display_name}")),
            window_min_size: None,
            window_decorations: None,
            tabbing_identifier: None,
        };

        let p = path.clone();
        let c = ctx.clone();
        match cx.open_window(opts, move |_window, cx| {
            let state = cx.new(|cx| HotReloadState::new(p.clone(), c.clone(), cx));
            cx.new(|_| HotReloadView::new(state))
        }) {
            Ok(_) => {}
            Err(e) => eprintln!("preview: failed to open window: {e}"),
        }
    });
}

#[cfg(feature = "desktop")]
fn load_context_toml(path: &std::path::Path, ctx: &mut crepuscularity_runtime::TemplateContext) {
    use crepuscularity_runtime::TemplateValue;
    let Ok(content) = std::fs::read_to_string(path) else {
        return;
    };

    for line in content.lines() {
        let line = line.trim();
        if line.is_empty() || line.starts_with('#') {
            continue;
        }
        if let Some(eq) = line.find('=') {
            let key = line[..eq].trim();
            let val = line[eq + 1..].trim();
            if val == "true" {
                ctx.set(key, TemplateValue::Bool(true));
            } else if val == "false" {
                ctx.set(key, TemplateValue::Bool(false));
            } else if let Ok(n) = val.parse::<i64>() {
                ctx.set(key, TemplateValue::Int(n));
            } else if let Ok(f) = val.parse::<f64>() {
                ctx.set(key, TemplateValue::Float(f));
            } else {
                ctx.set(key, val.trim_matches('"').trim_matches('\'').to_string());
            }
        }
    }
}