nativ 0.3.0

Nativ CLI — compile .nativ DSL to real SwiftUI and Jetpack Compose
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
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
use clap::Args;
use nativ_config::NativConfig;
use nativ_pipeline::{self, BuildOptions, Target};
use std::io::{self, IsTerminal, Write};
use std::path::Path;
use std::time::Instant;

#[derive(Args)]
pub struct BuildArgs {
    /// Build only for iOS
    #[arg(long)]
    pub ios: bool,

    /// Build only for Android
    #[arg(long)]
    pub android: bool,

    /// Also (or only) emit a static HTML site under build/web/ (#104)
    #[arg(long)]
    pub web: bool,

    /// Emit experimental native development helpers (#128)
    #[arg(long)]
    pub dev: bool,

    /// Project directory (default: current directory)
    #[arg(short, long, default_value = ".")]
    pub dir: String,
}

pub fn run(args: BuildArgs, verbose: bool, quiet: bool) -> Result<(), Box<dyn std::error::Error>> {
    let project_dir = Path::new(&args.dir);
    let config_path = project_dir.join("nativ.toml");

    let config = NativConfig::load(&config_path)?;

    let selection = if should_prompt_build_targets(&args, quiet) {
        prompt_build_targets(&config)?
    } else {
        build_selection_from_args(&args, &config)
    };
    let targets = selection.targets;
    let web = selection.web;

    if targets.is_empty() && !web {
        return Err(
            "No target platform specified. Enable ios, android, or web in nativ.toml".into(),
        );
    }

    if !quiet {
        let mut target_names: Vec<&str> = targets
            .iter()
            .map(|t| match t {
                Target::Ios => "iOS",
                Target::Android => "Android",
            })
            .collect();
        if web {
            target_names.push("Web");
        }
        println!(
            "Compiling: {} -> {}",
            config.app.name,
            target_names.join(", ")
        );
    }

    let start = Instant::now();

    // The native pipeline validates (parse + semantics + IR) even when the
    // native target list is empty, so a web-only build still fails fast on a
    // bad source instead of emitting silent HTML.
    let results = nativ_pipeline::build_with_options(
        project_dir,
        &config,
        &targets,
        BuildOptions { dev: args.dev },
    )?;

    let mut web_files: Vec<std::path::PathBuf> = Vec::new();
    if web {
        let output_dir = project_dir.join(&config.output.directory).join("web");
        std::fs::create_dir_all(&output_dir)?;
        // Web target = a navigable single-frame app (one phone, screens
        // switched by an inline JS router) with the preview renderer's nodes
        // plus a small state runtime.
        let (html, _screens) = crate::commands::preview::render_web_project(project_dir)?;
        let index = output_dir.join("index.html");
        std::fs::write(&index, html)?;
        web_files.push(index);
    }

    let elapsed = start.elapsed();

    if !quiet {
        for result in &results {
            let platform = match result.target {
                Target::Ios => "iOS",
                Target::Android => "Android",
            };
            println!(
                "  {platform}: {} files generated",
                result.generated_files.len()
            );

            if verbose {
                for file in &result.generated_files {
                    println!("    -> {}", file.display());
                }
            }
        }
        if !web_files.is_empty() {
            println!("  Web: {} files generated", web_files.len());
            if verbose {
                for file in &web_files {
                    println!("    -> {}", file.display());
                }
            }
        }

        let total: usize = results
            .iter()
            .map(|r| r.generated_files.len())
            .sum::<usize>()
            + web_files.len();
        println!(
            "Build complete: {total} files, {:.2}s",
            elapsed.as_secs_f32()
        );
    }

    Ok(())
}

struct BuildSelection {
    targets: Vec<Target>,
    web: bool,
}

fn build_selection_from_args(args: &BuildArgs, config: &NativConfig) -> BuildSelection {
    BuildSelection {
        targets: nativ_pipeline::resolve_targets(args.ios, args.android, config),
        web: args.web || config.build.web,
    }
}

fn should_prompt_build_targets(args: &BuildArgs, quiet: bool) -> bool {
    !quiet
        && !args.ios
        && !args.android
        && !args.web
        && io::stdin().is_terminal()
        && io::stdout().is_terminal()
}

fn prompt_build_targets(
    config: &NativConfig,
) -> Result<BuildSelection, Box<dyn std::error::Error>> {
    println!("Build target:");
    println!("  1) iOS");
    println!("  2) Android");
    println!("  3) iOS + Android");
    println!("  4) Web");
    println!("  5) All");
    print!("Select [Enter = nativ.toml defaults]: ");
    io::stdout().flush()?;

    let mut input = String::new();
    io::stdin().read_line(&mut input)?;
    parse_build_menu_choice(input.trim(), config)
        .ok_or_else(|| "Invalid build target selection".into())
}

fn parse_build_menu_choice(choice: &str, config: &NativConfig) -> Option<BuildSelection> {
    let targets = |ios, android| nativ_pipeline::resolve_targets(ios, android, config);
    Some(match choice {
        "" | "0" => BuildSelection {
            targets: nativ_pipeline::resolve_targets(false, false, config),
            web: config.build.web,
        },
        "1" => BuildSelection {
            targets: targets(true, false),
            web: false,
        },
        "2" => BuildSelection {
            targets: targets(false, true),
            web: false,
        },
        "3" => BuildSelection {
            targets: targets(true, true),
            web: false,
        },
        "4" => BuildSelection {
            targets: Vec::new(),
            web: true,
        },
        "5" => BuildSelection {
            targets: targets(true, true),
            web: true,
        },
        _ => return None,
    })
}

#[cfg(test)]
mod tests {
    use super::*;

    fn args_for(dir: &Path, ios: bool, android: bool) -> BuildArgs {
        BuildArgs {
            ios,
            android,
            web: false,
            dev: false,
            dir: dir.display().to_string(),
        }
    }

    fn args_for_web(dir: &Path) -> BuildArgs {
        BuildArgs {
            ios: false,
            android: false,
            web: true,
            dev: false,
            dir: dir.display().to_string(),
        }
    }

    #[test]
    fn build_menu_default_uses_config_targets() {
        let config = NativConfig::parse(
            "[app]\nname = \"Demo\"\n\n[build]\nios = false\nandroid = true\nweb = true\n",
        )
        .unwrap();

        let selection = parse_build_menu_choice("", &config).unwrap();
        assert_eq!(selection.targets, vec![Target::Android]);
        assert!(selection.web);
    }

    #[test]
    fn build_menu_can_select_web_only() {
        let config = NativConfig::parse("[app]\nname = \"Demo\"\n").unwrap();

        let selection = parse_build_menu_choice("4", &config).unwrap();
        assert!(selection.targets.is_empty());
        assert!(selection.web);
    }

    #[test]
    fn build_menu_rejects_unknown_choice() {
        let config = NativConfig::parse("[app]\nname = \"Demo\"\n").unwrap();

        assert!(parse_build_menu_choice("x", &config).is_none());
    }

    #[test]
    fn fails_when_config_is_missing() {
        let tmp = tempfile::tempdir().unwrap();

        let err = run(args_for(tmp.path(), true, false), false, true).unwrap_err();
        assert!(err.to_string().contains("nativ.toml"), "{err}");
    }

    #[test]
    fn fails_when_no_target_platform_enabled() {
        let tmp = tempfile::tempdir().unwrap();
        std::fs::write(
            tmp.path().join("nativ.toml"),
            "[app]\nname = \"t\"\n\n[build]\nios = false\nandroid = false\n",
        )
        .unwrap();

        let err = run(args_for(tmp.path(), false, false), false, true).unwrap_err();
        assert!(err.to_string().contains("No target platform"), "{err}");
    }

    #[test]
    fn fails_when_src_dir_is_missing() {
        let tmp = tempfile::tempdir().unwrap();
        std::fs::write(tmp.path().join("nativ.toml"), "[app]\nname = \"t\"\n").unwrap();

        let err = run(args_for(tmp.path(), true, false), false, true).unwrap_err();
        assert!(err.to_string().contains("not found"), "{err}");
    }

    /// `nativ build --web` emits a navigable single-frame app under build/web/
    /// and is a valid target on its own. The native pipeline still validates
    /// the source first.
    #[test]
    fn web_build_emits_navigable_app() {
        let tmp = tempfile::tempdir().unwrap();
        let src = tmp.path().join("src");
        std::fs::create_dir_all(&src).unwrap();
        std::fs::write(
            tmp.path().join("nativ.toml"),
            "[app]\nname = \"Web\"\n\n[build]\nios = false\nandroid = false\n",
        )
        .unwrap();
        std::fs::write(
            src.join("app.nativ"),
            "app App:\n  name: \"Web\"\n  start: Home\n",
        )
        .unwrap();
        std::fs::write(
            src.join("home.nativ"),
            "screen Home:\n  text \"Hello web\"\n",
        )
        .unwrap();

        run(args_for_web(tmp.path()), false, true).expect("web build succeeds");

        let index = tmp.path().join("build").join("web").join("index.html");
        assert!(index.is_file(), "build/web/index.html not written");
        let html = std::fs::read_to_string(&index).unwrap();
        assert!(html.starts_with("<!DOCTYPE html>"), "not an HTML document");
        // One phone frame (not a gallery of frames).
        assert_eq!(
            html.matches("class=\"phone\"").count(),
            1,
            "single phone frame"
        );
        // The screen is a data-screen section; the start screen is active.
        assert!(
            html.contains("data-screen=\"Home\""),
            "screen section missing"
        );
        assert!(
            html.contains("class=\"screen active\" data-screen=\"Home\""),
            "start screen must be active:\n{html}"
        );
        // Inline JS router present.
        assert!(html.contains("<script>"), "router script missing");
        assert!(html.contains("screen-bar"), "screen bar header missing");
    }

    /// A `go to` button is wired with data-goto so the router can switch
    /// screens; the target screen section exists even though it is not active.
    #[test]
    fn web_build_wires_go_to_buttons_to_the_router() {
        let tmp = tempfile::tempdir().unwrap();
        let src = tmp.path().join("src");
        std::fs::create_dir_all(&src).unwrap();
        std::fs::write(
            tmp.path().join("nativ.toml"),
            "[app]\nname = \"Nav\"\n\n[build]\nios = false\nandroid = false\n",
        )
        .unwrap();
        std::fs::write(
            src.join("app.nativ"),
            "app App:\n  name: \"Nav\"\n  start: Home\n",
        )
        .unwrap();
        std::fs::write(
            src.join("home.nativ"),
            "screen Home:\n  button \"Open detail\":\n    go to Detail\n",
        )
        .unwrap();
        std::fs::write(
            src.join("detail.nativ"),
            "screen Detail:\n  text \"Detail page\"\n  button \"Back\":\n    go back\n",
        )
        .unwrap();

        run(args_for_web(tmp.path()), false, true).expect("web build succeeds");

        let html = std::fs::read_to_string(tmp.path().join("build").join("web").join("index.html"))
            .unwrap();
        // go to button carries data-goto; go back carries data-back.
        assert!(
            html.contains("data-goto=\"Detail\""),
            "go to button must be wired:\n{html}"
        );
        assert!(
            html.contains("data-back="),
            "go back button must be wired:\n{html}"
        );
        // Both screens are sections; only Home (start) is active.
        assert!(
            html.contains("data-screen=\"Detail\""),
            "Detail section missing"
        );
        assert!(
            !html.contains("class=\"screen active\" data-screen=\"Detail\""),
            "non-start screen must not be active:\n{html}"
        );
    }

    /// State + reactivity: state is initialized in JS, interpolation is bound
    /// via data-bind, and a counter button's `+= 1` is wired via data-on-tap.
    #[test]
    fn web_build_emits_reactive_state_and_bindings() {
        let tmp = tempfile::tempdir().unwrap();
        let src = tmp.path().join("src");
        std::fs::create_dir_all(&src).unwrap();
        std::fs::write(
            tmp.path().join("nativ.toml"),
            "[app]\nname = \"Count\"\n\n[build]\nios = false\nandroid = false\n",
        )
        .unwrap();
        std::fs::write(
            src.join("app.nativ"),
            "app App:\n  name: \"Count\"\n  start: Home\n",
        )
        .unwrap();
        std::fs::write(
            src.join("home.nativ"),
            "screen Home:\n  state count = 0\n  text \"Taps: {count}\"\n  button \"Add\":\n    count += 1\n",
        )
        .unwrap();

        run(args_for_web(tmp.path()), false, true).expect("web build succeeds");
        let html = std::fs::read_to_string(tmp.path().join("build").join("web").join("index.html"))
            .unwrap();
        // State initialized from the declaration.
        assert!(
            html.contains("state.count = 0;"),
            "state init missing:\n{html}"
        );
        // Interpolation becomes a reactive binding that reads state.count.
        assert!(
            html.contains("data-bind=") && html.contains("state.count"),
            "data-bind on interpolation missing:\n{html}"
        );
        // Counter button wired: count += 1 as an on-tap statement.
        assert!(
            html.contains("data-on-tap=") && html.contains("state.count += 1;"),
            "assign on-tap missing:\n{html}"
        );
        // The runtime's render/val helpers are present.
        assert!(html.contains("function render()"), "render fn missing");
        assert!(html.contains("new Function"), "eval-based runtime missing");
    }

    /// Conditional re-render: an `if`/`else` emits both branches, the then
    /// visible and the else hidden inline, both gated by data-bind-if so the
    /// runtime shows the matching branch as state changes.
    #[test]
    fn web_build_gates_conditional_branches() {
        let tmp = tempfile::tempdir().unwrap();
        let src = tmp.path().join("src");
        std::fs::create_dir_all(&src).unwrap();
        std::fs::write(
            tmp.path().join("nativ.toml"),
            "[app]\nname = \"Cond\"\n\n[build]\nios = false\nandroid = false\n",
        )
        .unwrap();
        std::fs::write(
            src.join("app.nativ"),
            "app App:\n  name: \"Cond\"\n  start: Home\n",
        )
        .unwrap();
        std::fs::write(
            src.join("home.nativ"),
            "screen Home:\n  state count = 0\n  if count > 5:\n    text \"a lot\"\n  else:\n    text \"few\"\n",
        )
        .unwrap();

        run(args_for_web(tmp.path()), false, true).expect("web build succeeds");
        let html = std::fs::read_to_string(tmp.path().join("build").join("web").join("index.html"))
            .unwrap();
        // Both branches present, each gated by the condition (else negated).
        assert!(
            html.contains("data-bind-if=\"((state.count > 5))\""),
            "then-branch gate missing:\n{html}"
        );
        assert!(
            html.contains("data-bind-if=\"!((state.count > 5))\"") && html.contains("display:none"),
            "else-branch gate + hidden missing:\n{html}"
        );
        // The runtime toggles data-bind-if display.
        assert!(
            html.contains("[data-bind-if]"),
            "runtime must toggle conditional branches:\n{html}"
        );
    }

    /// Two-way textfield binding + toggle flip/state: a bound textfield writes
    /// back to state via data-bind-input; a toggle flips its boolean and the
    /// runtime syncs its visual state.
    #[test]
    fn web_build_wires_textfield_and_toggle_bindings() {
        let tmp = tempfile::tempdir().unwrap();
        let src = tmp.path().join("src");
        std::fs::create_dir_all(&src).unwrap();
        std::fs::write(
            tmp.path().join("nativ.toml"),
            "[app]\nname = \"Form\"\n\n[build]\nios = false\nandroid = false\n",
        )
        .unwrap();
        std::fs::write(
            src.join("app.nativ"),
            "app App:\n  name: \"Form\"\n  start: Home\n",
        )
        .unwrap();
        std::fs::write(
            src.join("home.nativ"),
            "screen Home:\n  state email = \"\"\n  state done = false\n  textfield \"Email\", bind: email\n  toggle \"Done\", bind: done\n",
        )
        .unwrap();

        run(args_for_web(tmp.path()), false, true).expect("web build succeeds");
        let html = std::fs::read_to_string(tmp.path().join("build").join("web").join("index.html"))
            .unwrap();
        // Textfield wired to state.email (and not disabled).
        assert!(
            html.contains("data-bind-input=\"state.email\"") && !html.contains("disabled>"),
            "textfield binding missing:\n{html}"
        );
        // Toggle flips state.done.
        assert!(
            html.contains("data-on-tap=\"state.done = !(state.done);\""),
            "toggle flip missing:\n{html}"
        );
        assert!(
            html.contains("data-bind-toggle=\"state.done\"")
                && html.contains("classList.toggle('is-on'")
                && html.contains(".toggle.is-on .switch"),
            "toggle visual state missing:\n{html}"
        );
        // The runtime has an input listener.
        assert!(html.contains("'input'"), "input listener missing");
    }

    /// Each-loop reactivity: the loop emits a container (data-each) plus a
    /// hidden template whose bindings read the per-item `__it`, and the runtime
    /// clones the template once per real list item.
    #[test]
    fn web_build_renders_each_loop_from_state() {
        let tmp = tempfile::tempdir().unwrap();
        let src = tmp.path().join("src");
        std::fs::create_dir_all(&src).unwrap();
        std::fs::write(
            tmp.path().join("nativ.toml"),
            "[app]\nname = \"List\"\n\n[build]\nios = false\nandroid = false\n",
        )
        .unwrap();
        std::fs::write(
            src.join("app.nativ"),
            "app App:\n  name: \"List\"\n  start: Home\n",
        )
        .unwrap();
        std::fs::write(
            src.join("home.nativ"),
            "model Item:\n  title: text\n\nscreen Home:\n  state items: list of Item = [Item(title: \"A\"), Item(title: \"B\")]\n  each item in items:\n    text item.title\n",
        )
        .unwrap();

        run(args_for_web(tmp.path()), false, true).expect("web build succeeds");
        let html = std::fs::read_to_string(tmp.path().join("build").join("web").join("index.html"))
            .unwrap();
        // Container references the state list; the hidden template is present.
        assert!(
            html.contains("data-each=\"state.items\""),
            "each container missing:\n{html}"
        );
        assert!(
            html.contains("data-each-tpl"),
            "each template missing:\n{html}"
        );
        // Template bindings read the per-item variable (__it), not state.
        assert!(
            html.contains("data-bind=\"__it.title\""),
            "loop-var binding must use __it:\n{html}"
        );
        // The runtime clones the template per item.
        assert!(html.contains("renderEach"), "each renderer missing");
    }

    /// List mutations: `items.add(x)` / `items.remove(x)` / `items.clear()`
    /// on buttons are wired to JS push / filter / length=0.
    #[test]
    fn web_build_wires_list_mutations() {
        let tmp = tempfile::tempdir().unwrap();
        let src = tmp.path().join("src");
        std::fs::create_dir_all(&src).unwrap();
        std::fs::write(
            tmp.path().join("nativ.toml"),
            "[app]\nname = \"Tags\"\n\n[build]\nios = false\nandroid = false\n",
        )
        .unwrap();
        std::fs::write(
            src.join("app.nativ"),
            "app App:\n  name: \"Tags\"\n  start: Home\n",
        )
        .unwrap();
        std::fs::write(
            src.join("home.nativ"),
            "screen Home:\n  state tags = []\n  button \"Add\":\n    tags.add(\"new\")\n  button \"Clear\":\n    tags.clear()\n",
        )
        .unwrap();

        run(args_for_web(tmp.path()), false, true).expect("web build succeeds");
        let html = std::fs::read_to_string(tmp.path().join("build").join("web").join("index.html"))
            .unwrap();
        assert!(
            html.contains("state.tags.push(") && html.contains("data-on-tap="),
            "add -> push missing:\n{html}"
        );
        assert!(
            html.contains("state.tags.length = 0;"),
            "clear -> length=0 missing:\n{html}"
        );
    }

    /// Model constructor list adds: `items.add(Item(newTitle))` emits a JS
    /// object literal with model field names and defaults, not `null`.
    #[test]
    fn web_build_wires_model_constructor_list_adds() {
        let tmp = tempfile::tempdir().unwrap();
        let src = tmp.path().join("src");
        std::fs::create_dir_all(&src).unwrap();
        std::fs::write(
            tmp.path().join("nativ.toml"),
            "[app]\nname = \"Todo\"\n\n[build]\nios = false\nandroid = false\n",
        )
        .unwrap();
        std::fs::write(
            src.join("app.nativ"),
            "app App:\n  name: \"Todo\"\n  start: Home\n",
        )
        .unwrap();
        std::fs::write(
            src.join("home.nativ"),
            "model Item:\n  title: text\n  done: boolean = false\n\nscreen Home:\n  state newTitle = \"A\"\n  state items: list of Item = []\n  button \"Add\":\n    items.add(Item(newTitle))\n",
        )
        .unwrap();

        run(args_for_web(tmp.path()), false, true).expect("web build succeeds");
        let html = std::fs::read_to_string(tmp.path().join("build").join("web").join("index.html"))
            .unwrap();
        assert!(
            html.contains("state.items.push({title: state.newTitle, done: false});"),
            "constructor add must emit object literal:\n{html}"
        );
        assert!(
            !html.contains("state.items.push(null);"),
            "constructor add must not degrade to null:\n{html}"
        );
    }

    /// Form submit: web build emits enabled fields, minimal client validation,
    /// and gates submit actions behind a valid form.
    #[test]
    fn web_build_wires_form_submit_validation() {
        let tmp = tempfile::tempdir().unwrap();
        let src = tmp.path().join("src");
        std::fs::create_dir_all(&src).unwrap();
        std::fs::write(
            tmp.path().join("nativ.toml"),
            "[app]\nname = \"Signup\"\n\n[build]\nios = false\nandroid = false\n",
        )
        .unwrap();
        std::fs::write(
            src.join("app.nativ"),
            "app App:\n  name: \"Signup\"\n  start: Home\n",
        )
        .unwrap();
        std::fs::write(
            src.join("home.nativ"),
            "screen Home:\n  state email = \"\"\n  state submitted = false\n  form:\n    input \"Email\", bind: email, required, email\n    button \"Submit\":\n      submitted = true\n",
        )
        .unwrap();

        run(args_for_web(tmp.path()), false, true).expect("web build succeeds");
        let html = std::fs::read_to_string(tmp.path().join("build").join("web").join("index.html"))
            .unwrap();
        assert!(
            html.contains("data-form-field=\"email\"")
                && html.contains("data-bind-input=\"state.email\"")
                && html.contains("data-required=\"1\"")
                && html.contains("data-email=\"1\"")
                && html.contains("data-error-for=\"email\""),
            "form field validation attrs missing:\n{html}"
        );
        assert!(
            html.contains("data-submit-form=\"1\"")
                && html.contains("data-submit-tap=\"state.submitted = true;\"")
                && html.contains("validateForm(form)")
                && html.contains("Invalid email"),
            "form submit runtime missing:\n{html}"
        );
    }

    /// Web form endpoint submit: `submit to "/path"` keeps the validation gate
    /// and posts a JSON payload with native browser fetch.
    #[test]
    fn web_build_posts_form_submit_endpoint() {
        let tmp = tempfile::tempdir().unwrap();
        let src = tmp.path().join("src");
        std::fs::create_dir_all(&src).unwrap();
        std::fs::write(
            tmp.path().join("nativ.toml"),
            "[app]\nname = \"Signup\"\n\n[build]\nios = false\nandroid = false\n",
        )
        .unwrap();
        std::fs::write(
            src.join("app.nativ"),
            "app App:\n  name: \"Signup\"\n  start: Home\n",
        )
        .unwrap();
        std::fs::write(
            src.join("home.nativ"),
            "screen Home:\n  state email = \"\"\n  form:\n    input \"Email\", bind: email, required, email\n    button \"Submit\":\n      submit to \"/register\"\n",
        )
        .unwrap();

        run(args_for_web(tmp.path()), false, true).expect("web build succeeds");
        let html = std::fs::read_to_string(tmp.path().join("build").join("web").join("index.html"))
            .unwrap();
        assert!(
            html.contains("data-submit-endpoint=\"/register\"")
                && html.contains("submitForm(form, endpoint)")
                && html.contains("fetch(endpoint, { method: 'POST'")
                && html.contains("JSON.stringify(formPayload(form))"),
            "form endpoint submit missing:\n{html}"
        );
    }
}