whisker-cli 0.2.0

Whisker CLI: `whisker` and `cargo-whisker` (hybrid) — scaffold, doctor, and dev-loop Whisker apps.
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
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
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
//! `whisker new-module <name>` — scaffold a Whisker module crate.
//!
//! Creates a directory matching the supplied crate name with a
//! complete module skeleton: `Cargo.toml` (carrying the
//! `[package.metadata.whisker]` discovery marker), `Package.swift`,
//! `build.gradle.kts`, `src/lib.rs`, and the platform sources under
//! `ios/` and `android/` (Expo-style layout). The skeleton compiles
//! standalone — the consumer just runs `cargo build` and adds the
//! crate as a dep to their Whisker app.
//!
//! Naming convention: input is the cargo crate name (kebab-case,
//! `whisker-foo`). The PascalCase tag (`Foo`), the module class
//! (`FooModule`), and (for view-bearing modules) the view class
//! (`FooView`) are derived. Lynx registers a view-bearing module's
//! element under `<crate-name>:<tag>` (`whisker-foo:Foo`).
//!
//! Modules are authored with the ModuleDefinition DSL: a class
//! subclasses `Module` and overrides `definition()`. Subclassing
//! the base IS the registration trigger — the per-platform
//! codegen (SwiftPM build plugin / KSP) finds every concrete
//! `Module` subclass and emits the Lynx registration. Phase M
//! (Issue #59) dropped the previously-companion `@WhiskerModule`
//! marker annotation.
//!
//! This is a minimal scaffolder — it copies a small set of inline
//! templates and substitutes a handful of variables. For a richer
//! template story (multiple module types, custom dirs, …) the
//! `whisker new-module` subcommand can grow later without breaking
//! the contract documented in `docs/module-author-guide.md`.

use anyhow::{anyhow, bail, Context, Result};
use clap::Args;
use std::path::{Path, PathBuf};

/// `whisker new-module` CLI arguments.
#[derive(Args, Debug)]
pub struct NewModuleArgs {
    /// The cargo crate name. Convention: kebab-case, prefixed with
    /// `whisker-` (e.g. `whisker-camera`, `whisker-blur-view`). Must
    /// be a valid cargo package name — letters / digits / `-` / `_`,
    /// must start with a letter.
    pub name: String,

    /// Optional parent directory. Defaults to the current working
    /// directory. The new crate lands at `<parent>/<name>/`.
    #[arg(long)]
    pub path: Option<PathBuf>,

    /// Module shape. `view-bearing` (the default) generates a
    /// `#[whisker::module_component]` shim + a DSL module with a
    /// `View(...)` block and a `WhiskerUI<View>` subclass.
    /// `function-only` generates a `#[whisker::platform_module]`
    /// proxy + a DSL module with module-level `Function`s and no
    /// `View(...)` — for modules that only expose function calls
    /// (e.g. `whisker-local-store`-style key-value stores).
    #[arg(long, value_enum, default_value_t = ModuleShape::ViewBearing)]
    pub shape: ModuleShape,
}

#[derive(clap::ValueEnum, Clone, Debug, PartialEq, Eq)]
pub enum ModuleShape {
    /// View-bearing — renders a native view + supports prop / method
    /// dispatch via `ElementRef<T>`.
    #[value(name = "view-bearing")]
    ViewBearing,
    /// Function-only — Rust calls platform-side functions; no UI.
    #[value(name = "function-only")]
    FunctionOnly,
}

pub fn run(args: NewModuleArgs) -> Result<()> {
    validate_crate_name(&args.name)?;
    let parent = args.path.unwrap_or_else(|| PathBuf::from("."));
    let target_dir = parent.join(&args.name);
    if target_dir.exists() {
        bail!(
            "{}: directory already exists. Pick a different name or remove it.",
            target_dir.display(),
        );
    }

    let tag = pascal_case_tag(&args.name);
    let spm = crate_to_spm_target(&args.name);
    let ns = args.name.replace('-', "_");
    let ident = args
        .name
        .replace('-', "_")
        .trim_start_matches("whisker_")
        .to_string();
    let module_class = format!("{tag}Module");
    let view_class = format!("{tag}View");

    let v = Vars {
        crate_name: &args.name,
        tag: &tag,
        spm: &spm,
        ns: &ns,
        ident: &ident,
        module_class: &module_class,
        view_class: &view_class,
    };

    // Expo-style layout — platform code under `ios/` and `android/`,
    // each openable directly in Xcode / Android Studio.
    let ios_src = format!("ios/Sources/{spm}");
    let android_src = format!("android/src/main/kotlin/rs/whisker/modules/{ns}");
    std::fs::create_dir_all(target_dir.join(&ios_src))
        .with_context(|| format!("create {}/{ios_src}", target_dir.display()))?;
    std::fs::create_dir_all(target_dir.join(&android_src))
        .with_context(|| format!("create {}/{android_src}", target_dir.display()))?;

    write(&target_dir, "Cargo.toml", &cargo_toml(&v))?;
    write(&target_dir, "README.md", &readme(&v))?;
    write(&target_dir, "Package.swift", &package_swift(&v))?;
    write(&target_dir, "build.gradle.kts", &build_gradle(&v))?;

    match args.shape {
        ModuleShape::ViewBearing => {
            write(&target_dir, "src/lib.rs", &lib_rs_view(&v))?;
            write(
                &target_dir,
                &format!("{ios_src}/{module_class}.swift"),
                &swift_view_module(&v),
            )?;
            write(
                &target_dir,
                &format!("{ios_src}/{view_class}.swift"),
                &swift_view(&v),
            )?;
            write(
                &target_dir,
                &format!("{android_src}/{module_class}.kt"),
                &kotlin_view_module(&v),
            )?;
            write(
                &target_dir,
                &format!("{android_src}/{view_class}.kt"),
                &kotlin_view(&v),
            )?;
        }
        ModuleShape::FunctionOnly => {
            write(&target_dir, "src/lib.rs", &lib_rs_module(&v))?;
            write(
                &target_dir,
                &format!("{ios_src}/{module_class}.swift"),
                &swift_function_module(&v),
            )?;
            write(
                &target_dir,
                &format!("{android_src}/{module_class}.kt"),
                &kotlin_function_module(&v),
            )?;
        }
    }

    eprintln!(
        "Created Whisker module skeleton at {}\n\
         \n\
         Next steps:\n  \
         1. cd {}\n  \
         2. Implement the platform-side logic in ios/ and android/.\n  \
         3. From your Whisker app: `cargo add --path {}` (or publish to crates.io).\n  \
         4. See docs/module-author-guide.md for the full reference.",
        target_dir.display(),
        target_dir.display(),
        target_dir.display(),
    );
    Ok(())
}

// ============================================================================
// Template variables + rendering
// ============================================================================

struct Vars<'a> {
    /// Cargo crate name, e.g. `whisker-foo`.
    crate_name: &'a str,
    /// PascalCase local tag, e.g. `Foo`.
    tag: &'a str,
    /// SwiftPM target name == PascalCased full crate name, e.g.
    /// `WhiskerFoo`.
    spm: &'a str,
    /// Android package leaf == crate name with `-` → `_`, e.g.
    /// `whisker_foo`.
    ns: &'a str,
    /// Rust fn identifier == crate name minus the `whisker_` prefix,
    /// e.g. `foo`.
    ident: &'a str,
    /// DSL module class, e.g. `FooModule`.
    module_class: &'a str,
    /// View-bearing Lynx UI subclass, e.g. `FooView`.
    view_class: &'a str,
}

fn write(root: &Path, rel: &str, content: &str) -> Result<()> {
    let path = root.join(rel);
    if let Some(parent) = path.parent() {
        std::fs::create_dir_all(parent).with_context(|| format!("create {}", parent.display()))?;
    }
    std::fs::write(&path, content).with_context(|| format!("write {}", path.display()))?;
    Ok(())
}

fn cargo_toml(v: &Vars) -> String {
    format!(
        r#"[package]
name = "{name}"
version = "0.1.0"
edition = "2021"
license = "MIT OR Apache-2.0"
description = "Whisker module — short tagline shown on crates.io."

include = [
    "Cargo.toml",
    "Package.swift",
    "build.gradle.kts",
    "src/lib.rs",
    "android/**/*.kt",
    "ios/**/*.swift",
    "README.md",
]

[lib]
crate-type = ["rlib"]

# Module-system opt-in marker — the bare table identifies this cargo
# crate as a Whisker module, so `whisker-build` wires its `android/`
# Gradle subproject + `ios/` SwiftPM package into the host build.
[package.metadata.whisker]

[dependencies]
# The umbrella `whisker` crate. The proc macros' emit paths
# (::whisker::ElementRef, ::whisker::platform_module::WhiskerValue, ...)
# resolve under the `whisker` name — the same dep app crates use.
whisker = "0.1"
"#,
        name = v.crate_name,
    )
}

fn readme(v: &Vars) -> String {
    format!(
        r#"# {name}

A Whisker module — registers the `{name}:{tag}` element under Lynx
and exposes `{tag}` for use in Whisker app `render!` trees.

## Usage

```toml
[dependencies]
{name} = "0.1"
```

```rust
use whisker::prelude::*;
use {ident}::*;

#[whisker::main]
fn app() -> Element {{
    render! {{
        {tag}()
    }}
}}
```

See [the Whisker Module Author Guide](https://github.com/whiskerrs/whisker/blob/main/docs/module-author-guide.md)
for the full reference.
"#,
        name = v.crate_name,
        tag = v.tag,
        ident = v.ident,
    )
}

fn package_swift(v: &Vars) -> String {
    format!(
        r#"// swift-tools-version:5.9
//
// SwiftPM manifest for the `{name}` module's iOS half. The consumer
// app's `whisker-build`-generated aggregator depends on the library
// product below via `.product(name: "{spm}", package: "{name}")`.
//
// Package.swift lives at the package root (SwiftPM requires it
// there); the Swift sources live under the `ios/` subdir alongside
// `android/` + `src/`.

import PackageDescription

// whisker-build injects the absolute location of Whisker's iOS
// runtime + macros packages via these env vars, so this module
// resolves them wherever it lives — in a whisker project, or unpacked
// from the cargo registry. A Whisker module is only ever built through
// `whisker run` (which set these), never standalone.
guard let whiskerRuntimePath = Context.environment["WHISKER_IOS_RUNTIME"],
      let whiskerMacrosPath = Context.environment["WHISKER_IOS_MACROS"]
else {{
    fatalError("""
        WHISKER_IOS_RUNTIME / WHISKER_IOS_MACROS not set. Build this Whisker \
        module through `whisker run`, which inject these paths.
        """)
}}

let package = Package(
    name: "{name}",
    platforms: [.iOS(.v13), .macOS(.v13)],
    products: [
        .library(name: "{spm}", targets: ["{spm}"]),
    ],
    dependencies: [
        .package(name: "macros", path: whiskerMacrosPath),
        .package(name: "WhiskerRuntime", path: whiskerRuntimePath),
    ],
    targets: [
        .target(
            name: "{spm}",
            dependencies: [
                .product(name: "WhiskerModule", package: "WhiskerRuntime"),
            ],
            path: "ios/Sources/{spm}",
            plugins: [
                .plugin(name: "WhiskerModuleCodegenPlugin", package: "macros"),
            ]
        ),
    ]
)
"#,
        name = v.crate_name,
        spm = v.spm,
    )
}

fn build_gradle(v: &Vars) -> String {
    format!(
        r#"// Gradle subproject for the `{name}` Whisker module on Android.
// Wired into the consumer app's settings.gradle.kts by whisker-build.
// build.gradle.kts sits at the package root, alongside Package.swift
// + Cargo.toml; the Kotlin source set points at the `android/` subdir.

plugins {{
    id("com.android.library")
    id("org.jetbrains.kotlin.android")
    id("com.google.devtools.ksp") version "2.0.21-1.0.27"
}}

android {{
    namespace = "rs.whisker.modules.{ns}"
    compileSdk = 34

    defaultConfig {{
        minSdk = 21
    }}

    compileOptions {{
        sourceCompatibility = JavaVersion.VERSION_17
        targetCompatibility = JavaVersion.VERSION_17
    }}
    kotlinOptions {{
        jvmTarget = "17"
    }}

    sourceSets {{
        getByName("main") {{
            kotlin.srcDirs("android/src/main/kotlin")
        }}
    }}
}}

ksp {{
    arg("whisker.moduleName", "{spm}")
    arg("whisker.crateName", "{name}")
}}

dependencies {{
    // Single Whisker runtime dep. ksp(rs.whisker:ksp) stays
    // separate because it's a build-time processor, not on the
    // runtime classpath. The KSP processor discovers Module
    // subclasses by inheritance (no marker annotation needed).
    implementation(project(":module"))
    ksp("rs.whisker:ksp")
}}
"#,
        name = v.crate_name,
        ns = v.ns,
        spm = v.spm,
    )
}

fn lib_rs_view(v: &Vars) -> String {
    format!(
        r#"//! `{name}` — Whisker view-bearing module.
//!
//! Registers a Lynx element under `{name}:{tag}` and exposes the
//! `{tag}` symbol for use inside `render!`. Platform-side classes
//! live under `ios/` and `android/`.

use whisker::Signal;

/// View-bearing element. The Lynx tag the bridge registers against
/// is `{name}:{tag}` — the crate name namespace is auto-prepended by
/// `#[whisker::module_component]`. Imperative methods on a mounted
/// instance go through an `ElementRef` (the `ref:` prop) — wrap one
/// in a typed `{tag}Handle` struct for the public API.
#[whisker::module_component("{tag}")]
pub fn {ident}(style: Signal<String>) {{}}
"#,
        name = v.crate_name,
        tag = v.tag,
        ident = v.ident,
    )
}

fn lib_rs_module(v: &Vars) -> String {
    format!(
        r#"//! `{name}` — Whisker function-only platform module.
//!
//! Exposes typed Rust -> Kotlin/Swift function calls without
//! rendering UI. Platform-side classes live under `ios/` and
//! `android/`.

use whisker::platform_module::{{WhiskerModuleError, WhiskerValue}};

/// Typed Rust API for the `Whisker{tag}` platform module.
///
/// Hand-written wrapper over the framework primitive: each method
/// builds the raw `Vec<WhiskerValue>` arg list, dispatches via
/// `whisker::module!("Whisker{tag}").invoke(method, args)`, and lifts
/// the returned `WhiskerValue` into a typed `Result`. The `module!`
/// name MUST match the `Name("...")` in the platform-side
/// `definition()`; `module!` auto-prepends this crate's name so two
/// crates can ship same-named modules without colliding.
pub struct Whisker{tag};
impl Whisker{tag} {{
    pub fn placeholder() -> Result<(), WhiskerModuleError> {{
        // Build args, dispatch, lift the WhiskerValue into a typed result.
        match whisker::module!("Whisker{tag}").invoke("_placeholder", vec![]) {{
            WhiskerValue::Error(msg) => Err(WhiskerModuleError(msg)),
            _ => Ok(()),
        }}
    }}
}}
"#,
        name = v.crate_name,
        tag = v.tag,
    )
}

fn swift_view_module(v: &Vars) -> String {
    format!(
        r#"// `{module_class}` — iOS side of the `{name}:{tag}` Whisker module.
//
// Declares the Lynx element `{name}:{tag}` via the ModuleDefinition
// DSL. Subclassing `Module` is the registration signal — the SwiftPM
// codegen plugin walks every `Module` subclass and emits the Lynx
// behavior registration. The `{view_class}` Lynx UI subclass lives
// in `{view_class}.swift`.

import WhiskerModule    // Module, ModuleDefinition, DSL

public final class {module_class}: Module {{
    public override func definition() -> ModuleDefinition {{
        ModuleDefinition {{
            Name("{tag}")
            View({view_class}.self) {{
                // Declare Prop / Function entries here, e.g.:
                //   Prop("title") {{ (view: {view_class}, value: String) in
                //       view.setTitle(value)
                //   }}
                //   Function("focus") {{ (view: {view_class}) in view.focus() }}
            }}
        }}
    }}
}}
"#,
        name = v.crate_name,
        tag = v.tag,
        module_class = v.module_class,
        view_class = v.view_class,
    )
}

fn swift_view(v: &Vars) -> String {
    format!(
        r#"// `{view_class}` — the Lynx UI subclass backing `{name}:{tag}`.
// Instantiated by Lynx via the behavior `{module_class}.definition()`
// registers. `@objc({view_class})` pins the Obj-C class name so the
// codegen plugin's `NSClassFromString` lookup resolves it.

import UIKit
import WhiskerModule

@objc({view_class})
public final class {view_class}: WhiskerUI<UIView> {{
    @objc public override func createView() -> UIView {{
        let v = UIView()
        v.backgroundColor = .systemPink
        return v
    }}
}}
"#,
        name = v.crate_name,
        tag = v.tag,
        module_class = v.module_class,
        view_class = v.view_class,
    )
}

fn kotlin_view_module(v: &Vars) -> String {
    format!(
        r#"// `{module_class}` -- Android side of the `{name}:{tag}` Whisker module.
//
// Subclassing `Module` is the registration signal — the KSP processor
// walks every concrete subclass and emits the Lynx behavior
// registration. The `{view_class}` Lynx UI subclass lives in
// `{view_class}.kt`.
//
// Note the explicit `import rs.whisker.runtime.Module` — without it
// the unqualified `Module` resolves to `java.lang.Module` (a Kotlin
// JVM default import).

package rs.whisker.modules.{ns}

import rs.whisker.runtime.Module
import rs.whisker.runtime.ModuleDefinition

class {module_class} : Module() {{
    override fun definition() = ModuleDefinition {{
        Name("{tag}")
        View({view_class}::class.java) {{
            // Declare Prop / Function entries here, e.g.:
            //   Prop("title") {{ view: {view_class}, value: String ->
            //       view.setTitle(value)
            //   }}
            //   Function("focus") {{ view: {view_class} -> view.focus() }}
        }}
    }}
}}
"#,
        name = v.crate_name,
        tag = v.tag,
        ns = v.ns,
        module_class = v.module_class,
        view_class = v.view_class,
    )
}

fn kotlin_view(v: &Vars) -> String {
    format!(
        r#"// `{view_class}` -- the Lynx UI subclass backing `{name}:{tag}`.
// Instantiated by the Lynx behavior `{module_class}.definition()`
// registers. The single-arg `(WhiskerContext)` constructor matches
// the convention the KSP registration code expects.

package rs.whisker.modules.{ns}

import android.content.Context
import android.graphics.Color
import android.view.View
import rs.whisker.runtime.WhiskerContext
import rs.whisker.runtime.WhiskerUI

open class {view_class}(context: WhiskerContext) : WhiskerUI<View>(context) {{
    override fun createView(context: Context): View {{
        val v = View(context)
        v.setBackgroundColor(Color.argb(0xff, 0xff, 0x80, 0xa0))
        return v
    }}
}}
"#,
        name = v.crate_name,
        tag = v.tag,
        ns = v.ns,
        module_class = v.module_class,
        view_class = v.view_class,
    )
}

fn swift_function_module(v: &Vars) -> String {
    format!(
        r#"// `{module_class}` — iOS side of the `{name}` Whisker function-only module.
//
// A view-less DSL module: `definition()` has no `View(...)` block,
// just module-level `Function`s. Subclassing `Module` is the
// registration signal — the SwiftPM codegen plugin emits a dispatch
// shim registered under the `Name("...")`, so
// `Whisker{tag}::placeholder()` on the Rust side routes here.

import WhiskerModule    // Module, ModuleDefinition, DSL

public final class {module_class}: Module {{
    public override func definition() -> ModuleDefinition {{
        ModuleDefinition {{
            // The Name MUST match the Rust sys trait's
            // `#[whisker::platform_module(name = "...")]`.
            Name("Whisker{tag}")
            Function("_placeholder") {{
                // TODO: implement the function the Rust sys trait declares.
            }}
        }}
    }}
}}
"#,
        name = v.crate_name,
        tag = v.tag,
        module_class = v.module_class,
    )
}

fn kotlin_function_module(v: &Vars) -> String {
    format!(
        r#"// `{module_class}` -- Android side of the `{name}` Whisker function-only module.
//
// A view-less DSL module: module-level `Function`s, no `View(...)`.
// Subclassing `Module` is the registration signal. See the note in
// the view-bearing template re: the explicit `Module` import.

package rs.whisker.modules.{ns}

import rs.whisker.runtime.Module
import rs.whisker.runtime.ModuleDefinition

class {module_class} : Module() {{
    override fun definition() = ModuleDefinition {{
        // The Name MUST match the Rust sys trait's
        // `#[whisker::platform_module(name = "...")]`.
        Name("Whisker{tag}")
        Function("_placeholder") {{
            // TODO: implement the function the Rust sys trait declares.
        }}
    }}
}}
"#,
        name = v.crate_name,
        tag = v.tag,
        ns = v.ns,
        module_class = v.module_class,
    )
}

// ============================================================================
// Name helpers
// ============================================================================

/// Validate a cargo crate name. Rejects empty / non-letter-prefixed /
/// non-`[a-z0-9_-]+` inputs with an actionable message.
fn validate_crate_name(name: &str) -> Result<()> {
    if name.is_empty() {
        bail!("crate name must not be empty");
    }
    let first = name.chars().next().unwrap();
    if !first.is_ascii_alphabetic() {
        bail!(
            "crate name must start with a letter, got {first:?}. Try \
             `whisker-{name}` instead."
        );
    }
    for ch in name.chars() {
        if !(ch.is_ascii_alphanumeric() || ch == '-' || ch == '_') {
            return Err(anyhow!(
                "crate name {name:?} contains invalid character {ch:?}. \
                 Use only ASCII letters / digits / `-` / `_`."
            ));
        }
    }
    Ok(())
}

/// Derive the PascalCase tag from the crate name.
///
/// - `whisker-foo` -> `Foo`
/// - `whisker-blur-view` -> `BlurView`
/// - `foo-bar` -> `FooBar` (no `whisker-` prefix → tag is the whole name)
fn pascal_case_tag(crate_name: &str) -> String {
    let stripped = crate_name.strip_prefix("whisker-").unwrap_or(crate_name);
    let mut out = String::new();
    let mut upper = true;
    for ch in stripped.chars() {
        if ch == '-' || ch == '_' {
            upper = true;
        } else if upper {
            out.extend(ch.to_uppercase());
            upper = false;
        } else {
            out.push(ch);
        }
    }
    out
}

/// Same convention as `whisker_build::ios::crate_to_spm_target`:
/// `whisker-foo-bar` -> `WhiskerFooBar`.
fn crate_to_spm_target(crate_name: &str) -> String {
    let mut out = String::new();
    let mut upper = true;
    for ch in crate_name.chars() {
        if ch == '-' || ch == '_' {
            upper = true;
        } else if upper {
            out.extend(ch.to_uppercase());
            upper = false;
        } else {
            out.push(ch);
        }
    }
    out
}

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

    #[test]
    fn pascal_strips_whisker_prefix() {
        assert_eq!(pascal_case_tag("whisker-foo"), "Foo");
        assert_eq!(pascal_case_tag("whisker-blur-view"), "BlurView");
    }

    #[test]
    fn pascal_keeps_full_name_when_no_whisker_prefix() {
        assert_eq!(pascal_case_tag("foo-bar"), "FooBar");
    }

    #[test]
    fn spm_target_pascals_full_crate_name() {
        assert_eq!(crate_to_spm_target("whisker-foo"), "WhiskerFoo");
        assert_eq!(crate_to_spm_target("whisker-blur-view"), "WhiskerBlurView");
    }

    #[test]
    fn validate_rejects_invalid() {
        assert!(validate_crate_name("").is_err());
        assert!(validate_crate_name("1foo").is_err());
        assert!(validate_crate_name("whisker foo").is_err());
        assert!(validate_crate_name("whisker-foo").is_ok());
        assert!(validate_crate_name("whisker_foo").is_ok());
    }
}