Skip to main content

phoenix_cli/
scaffold.rs

1use std::{
2    collections::{BTreeMap, BTreeSet},
3    env, fs,
4    io::ErrorKind,
5    path::{Component, Path, PathBuf},
6    process::Command,
7    str::FromStr,
8    time::{SystemTime, UNIX_EPOCH},
9};
10
11use thiserror::Error;
12
13const MODULES_START: &str = "// <phoenix:modules>";
14const MODULES_END: &str = "// </phoenix:modules>";
15const MODELS_START: &str = "// <phoenix:model-registry>";
16const MODELS_END: &str = "// </phoenix:model-registry>";
17const MIGRATIONS_START: &str = "// <phoenix:migration-registry>";
18const MIGRATIONS_END: &str = "// </phoenix:migration-registry>";
19const COMMANDS_START: &str = "// <phoenix:commands>";
20const COMMANDS_END: &str = "// </phoenix:commands>";
21const PROJECT_OPTIONS_FILE: &str = ".phoenix";
22const PHOENIXRS_VERSION: &str = "0.1.3";
23const APIZERO_REACT_VERSION: &str = "0.1.2";
24const APIZERO_REACT_SSR_VERSION: &str = "0.1.2";
25const APIZERO_VITE_VERSION: &str = "0.1.3";
26
27#[derive(Clone, Debug, Eq, PartialEq)]
28pub enum DependencySource {
29    Registry,
30    Local(PathBuf),
31}
32
33/// Options for [`ProjectGenerator::update_core`] / `px update`.
34#[derive(Clone, Debug)]
35pub struct UpdateProjectOptions {
36    pub dependencies: DependencySource,
37    pub install_dependencies: bool,
38    pub dry_run: bool,
39}
40
41impl UpdateProjectOptions {
42    #[must_use]
43    pub fn new() -> Self {
44        Self {
45            dependencies: DependencySource::discover(),
46            install_dependencies: true,
47            dry_run: false,
48        }
49    }
50
51    #[must_use]
52    pub fn dependencies(mut self, dependencies: DependencySource) -> Self {
53        self.dependencies = dependencies;
54        self
55    }
56
57    #[must_use]
58    pub const fn install_dependencies(mut self, install: bool) -> Self {
59        self.install_dependencies = install;
60        self
61    }
62
63    #[must_use]
64    pub const fn dry_run(mut self, dry_run: bool) -> Self {
65        self.dry_run = dry_run;
66        self
67    }
68}
69
70impl Default for UpdateProjectOptions {
71    fn default() -> Self {
72        Self::new()
73    }
74}
75
76#[derive(Clone, Debug, Eq, PartialEq)]
77struct StoredProjectOptions {
78    frontend: ProjectFrontend,
79    database: Option<ProjectDatabase>,
80    render_mode: ProjectRenderMode,
81    tailwind: bool,
82    features: Vec<ProjectFeature>,
83}
84
85/// One optional official Feature selected during `px new --feature ...`.
86#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
87pub enum ProjectFeature {
88    Captcha,
89    Pay,
90    Notify,
91}
92
93impl ProjectFeature {
94    pub const ALL: [Self; 3] = [Self::Captcha, Self::Pay, Self::Notify];
95
96    /// Cargo feature name on the `phoenixrs` facade and `config/<key>.toml` stem.
97    #[must_use]
98    pub const fn key(self) -> &'static str {
99        match self {
100            Self::Captcha => "captcha",
101            Self::Pay => "pay",
102            Self::Notify => "notify",
103        }
104    }
105
106    /// One-line Chinese description used by the interactive wizard.
107    #[must_use]
108    pub const fn summary(self) -> &'static str {
109        match self {
110            Self::Captcha => "图形验证码(SVG、一次一用,GET /captcha)",
111            Self::Pay => "聚合支付(微信 Native / 支付宝当面付 / Mock)",
112            Self::Notify => "通知(邮件 + 数据库双通道)",
113        }
114    }
115
116    /// Whether this Feature registers database migrations through its plugin.
117    #[must_use]
118    pub const fn has_migrations(self) -> bool {
119        matches!(self, Self::Pay | Self::Notify)
120    }
121}
122
123impl FromStr for ProjectFeature {
124    type Err = String;
125
126    fn from_str(value: &str) -> Result<Self, Self::Err> {
127        match value.trim().to_ascii_lowercase().as_str() {
128            "captcha" => Ok(Self::Captcha),
129            "pay" | "payment" | "payments" => Ok(Self::Pay),
130            "notify" | "notification" | "notifications" => Ok(Self::Notify),
131            _ => Err(format!(
132                "unknown feature `{value}`; expected captcha, pay, or notify"
133            )),
134        }
135    }
136}
137
138/// Parse a comma-separated `--feature` list; deduplicates and keeps a stable order.
139///
140/// # Errors
141///
142/// Returns an error naming the first unknown feature.
143pub fn parse_feature_list(value: &str) -> Result<Vec<ProjectFeature>, String> {
144    let mut features = Vec::new();
145    for part in value.split(',') {
146        let part = part.trim();
147        if part.is_empty() {
148            continue;
149        }
150        let feature = part.parse::<ProjectFeature>()?;
151        if !features.contains(&feature) {
152            features.push(feature);
153        }
154    }
155    features.sort_unstable();
156    Ok(features)
157}
158
159/// Initial React rendering mode selected by `px new`.
160#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
161pub enum ProjectRenderMode {
162    Spa,
163    Ssr,
164    #[default]
165    Islands,
166}
167
168impl ProjectRenderMode {
169    #[must_use]
170    pub const fn page_builder(self) -> &'static str {
171        match self {
172            Self::Spa => ".spa()",
173            Self::Ssr => ".ssr()",
174            Self::Islands => ".islands()",
175        }
176    }
177}
178
179impl FromStr for ProjectRenderMode {
180    type Err = String;
181
182    fn from_str(value: &str) -> Result<Self, Self::Err> {
183        match value.trim().to_ascii_lowercase().as_str() {
184            "spa" => Ok(Self::Spa),
185            "ssr" => Ok(Self::Ssr),
186            "islands" | "island" => Ok(Self::Islands),
187            _ => Err("render mode must be spa, ssr, or islands".to_owned()),
188        }
189    }
190}
191
192/// One optional database driver selected when a project is created.
193#[derive(Clone, Copy, Debug, Eq, PartialEq)]
194pub enum ProjectDatabase {
195    Sqlite,
196    Pgsql,
197    Mysql,
198    All,
199}
200
201/// Source format used for generated React components.
202#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
203pub enum ProjectFrontend {
204    Jsx,
205    #[default]
206    Tsx,
207}
208
209impl ProjectFrontend {
210    #[must_use]
211    pub const fn extension(self) -> &'static str {
212        match self {
213            Self::Jsx => "jsx",
214            Self::Tsx => "tsx",
215        }
216    }
217}
218
219impl FromStr for ProjectFrontend {
220    type Err = String;
221
222    fn from_str(value: &str) -> Result<Self, Self::Err> {
223        match value.trim().to_ascii_lowercase().as_str() {
224            "jsx" | "js" => Ok(Self::Jsx),
225            "tsx" | "ts" => Ok(Self::Tsx),
226            _ => Err("frontend must be jsx or tsx".to_owned()),
227        }
228    }
229}
230
231impl ProjectDatabase {
232    #[must_use]
233    pub const fn cargo_feature(self) -> &'static str {
234        match self {
235            Self::Sqlite => "sqlite",
236            Self::Pgsql => "pgsql",
237            Self::Mysql => "mysql",
238            Self::All => "all-databases",
239        }
240    }
241
242    #[must_use]
243    pub const fn toasty_features(self) -> &'static str {
244        match self {
245            Self::Sqlite => "serde\", \"sqlite",
246            Self::Pgsql => "postgresql\", \"serde",
247            Self::Mysql => "mysql\", \"serde",
248            Self::All => "mysql\", \"postgresql\", \"serde\", \"sqlite",
249        }
250    }
251}
252
253impl FromStr for ProjectDatabase {
254    type Err = String;
255
256    fn from_str(value: &str) -> Result<Self, Self::Err> {
257        match value.trim().to_ascii_lowercase().as_str() {
258            "sqlite" => Ok(Self::Sqlite),
259            "pgsql" | "postgres" | "postgresql" => Ok(Self::Pgsql),
260            "mysql" | "mariadb" => Ok(Self::Mysql),
261            "all" => Ok(Self::All),
262            _ => Err("database must be sqlite, pgsql, mysql, or all".to_owned()),
263        }
264    }
265}
266
267impl DependencySource {
268    #[must_use]
269    pub fn discover() -> Self {
270        if let Some(path) = env::var_os("PHOENIX_FRAMEWORK_PATH") {
271            let path = PathBuf::from(path);
272            if is_framework_root(&path) {
273                return Self::Local(path);
274            }
275        }
276        let Ok(executable) = env::current_exe() else {
277            return Self::Registry;
278        };
279        for ancestor in executable.ancestors() {
280            if is_framework_root(ancestor) {
281                return Self::Local(ancestor.to_path_buf());
282            }
283        }
284        let build_root = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
285            .join("../..")
286            .canonicalize()
287            .unwrap_or_else(|_| PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../.."));
288        if is_framework_root(&build_root) {
289            return Self::Local(build_root);
290        }
291        Self::Registry
292    }
293}
294
295fn is_framework_root(path: &Path) -> bool {
296    path.join("crates/phoenix/Cargo.toml").is_file()
297        && path.join("packages/phoenix-react/package.json").is_file()
298        && path.join("packages/phoenix-vite/package.json").is_file()
299}
300
301#[derive(Clone, Debug)]
302pub struct NewProjectOptions {
303    pub target: PathBuf,
304    pub dependencies: DependencySource,
305    pub initialize_git: bool,
306    pub install_dependencies: bool,
307    pub render_mode: ProjectRenderMode,
308    pub database: Option<ProjectDatabase>,
309    pub frontend: ProjectFrontend,
310    pub tailwind: bool,
311    pub features: Vec<ProjectFeature>,
312}
313
314impl NewProjectOptions {
315    #[must_use]
316    pub fn new(target: impl Into<PathBuf>) -> Self {
317        Self {
318            target: target.into(),
319            dependencies: DependencySource::discover(),
320            initialize_git: false,
321            install_dependencies: true,
322            render_mode: ProjectRenderMode::default(),
323            database: None,
324            frontend: ProjectFrontend::default(),
325            tailwind: false,
326            features: Vec::new(),
327        }
328    }
329
330    #[must_use]
331    pub fn dependencies(mut self, dependencies: DependencySource) -> Self {
332        self.dependencies = dependencies;
333        self
334    }
335
336    #[must_use]
337    pub const fn initialize_git(mut self, initialize: bool) -> Self {
338        self.initialize_git = initialize;
339        self
340    }
341
342    #[must_use]
343    pub const fn install_dependencies(mut self, install: bool) -> Self {
344        self.install_dependencies = install;
345        self
346    }
347
348    #[must_use]
349    pub const fn render_mode(mut self, render_mode: ProjectRenderMode) -> Self {
350        self.render_mode = render_mode;
351        self
352    }
353
354    #[must_use]
355    pub const fn database(mut self, database: Option<ProjectDatabase>) -> Self {
356        self.database = database;
357        self
358    }
359
360    #[must_use]
361    pub const fn frontend(mut self, frontend: ProjectFrontend) -> Self {
362        self.frontend = frontend;
363        self
364    }
365
366    #[must_use]
367    pub const fn tailwind(mut self, tailwind: bool) -> Self {
368        self.tailwind = tailwind;
369        self
370    }
371
372    #[must_use]
373    pub fn features(mut self, features: Vec<ProjectFeature>) -> Self {
374        self.features = features;
375        self
376    }
377}
378
379#[derive(Clone, Copy, Debug, Default)]
380pub struct GenerateOptions {
381    pub force: bool,
382}
383
384#[derive(Clone, Copy, Debug, Default)]
385pub struct ControllerOptions {
386    pub force: bool,
387    pub resource: bool,
388    pub route: bool,
389}
390
391#[derive(Clone, Debug, Default)]
392#[allow(clippy::struct_excessive_bools)]
393pub struct ModelOptions {
394    pub all: bool,
395    pub api_resource: bool,
396    pub controller: bool,
397    pub factory: bool,
398    pub force: bool,
399    pub migration: bool,
400    pub page: bool,
401    pub relations: Vec<Relation>,
402    pub request: bool,
403    pub resource_controller: bool,
404}
405
406/// How a generated model relates to another one.
407///
408/// The whole point of naming these is that picking the *kind* and the *target*
409/// is all the information a relation needs — the foreign key, the column it
410/// maps to, and the pairing are conventions `#[phoenix::model]` fills in.
411#[derive(Clone, Copy, Debug, Eq, PartialEq)]
412pub enum RelationKind {
413    /// This model holds the foreign key (`Post` → `User`).
414    BelongsTo,
415    /// The other model holds the foreign key, and there are many (`User` → `Post`).
416    HasMany,
417    /// The other model holds the foreign key, and there is at most one.
418    HasOne,
419}
420
421impl RelationKind {
422    /// The attribute this kind writes.
423    const fn attribute(self) -> &'static str {
424        match self {
425            Self::BelongsTo => "belongs_to",
426            Self::HasMany => "has_many",
427            Self::HasOne => "has_one",
428        }
429    }
430
431    /// The CLI flag that selects it.
432    #[must_use]
433    pub const fn flag(self) -> &'static str {
434        match self {
435            Self::BelongsTo => "--belongs-to",
436            Self::HasMany => "--has-many",
437            Self::HasOne => "--has-one",
438        }
439    }
440}
441
442/// One relation declared on the command line.
443#[derive(Clone, Debug, Eq, PartialEq)]
444pub struct Relation {
445    /// Which side of the foreign key this model is on.
446    pub kind: RelationKind,
447    /// The model being related to, exactly as typed (`User`, `blog::Post`).
448    pub target: String,
449}
450
451#[derive(Debug, Error)]
452pub enum ScaffoldError {
453    #[error("invalid Phoenix name `{0}`; use letters, numbers, dashes, underscores, / or ::")]
454    InvalidName(String),
455    #[error("project target {0} already exists and is not empty")]
456    ProjectNotEmpty(PathBuf),
457    #[error("{0} is not a Phoenix project root")]
458    NotProject(PathBuf),
459    #[error("refusing to overwrite existing file {0}; pass --force to replace it")]
460    AlreadyExists(PathBuf),
461    #[error("Phoenix managed markers are missing or malformed in {0}")]
462    InvalidManagedFile(PathBuf),
463    #[error("local Phoenix framework root is invalid: {0}")]
464    InvalidFrameworkRoot(PathBuf),
465    #[error("failed to read or write {path}: {source}")]
466    Io {
467        path: PathBuf,
468        source: std::io::Error,
469    },
470    #[error("{program} exited unsuccessfully while preparing the project")]
471    CommandFailed { program: &'static str },
472    #[error("the current time is before the Unix epoch")]
473    InvalidClock,
474    #[error(
475        "make:auth needs a database for the persistent User model; recreate with \
476         `px new <app> --database sqlite` (or pgsql/mysql) and try again"
477    )]
478    AuthRequiresDatabase,
479}
480
481/// Write the project skeleton only (no `git init`, no `npm install`).
482///
483/// Returns the number of files written so callers can report progress.
484///
485/// # Errors
486///
487/// Returns an error for invalid names, non-empty targets, invalid local
488/// framework paths, or file-system failures.
489pub fn scaffold_project(options: &NewProjectOptions) -> Result<usize, ScaffoldError> {
490    let target = absolute_path(&options.target)?;
491    ensure_empty_target(&target)?;
492    let directory_name = target
493        .file_name()
494        .and_then(|value| value.to_str())
495        .ok_or_else(|| ScaffoldError::InvalidName(target.display().to_string()))?;
496    let package = package_name(directory_name)?;
497    if let DependencySource::Local(root) = &options.dependencies
498        && !is_framework_root(root)
499    {
500        return Err(ScaffoldError::InvalidFrameworkRoot(root.clone()));
501    }
502
503    let mut editor = ProjectEditor::new(&target, false);
504    for (path, content) in project_files(&package, options)? {
505        editor.create(path, content)?;
506    }
507    Ok(editor.commit()?.len())
508}
509
510/// Create a complete Phoenix application that can immediately run `px dev`.
511///
512/// # Errors
513///
514/// Returns an error for invalid names, non-empty targets, invalid local framework
515/// paths, file-system failures, or dependency/bootstrap command failures.
516pub fn create_project(options: &NewProjectOptions) -> Result<(), ScaffoldError> {
517    scaffold_project(options)?;
518    let target = absolute_path(&options.target)?;
519    if options.initialize_git {
520        run_optional("git", &["init", "--quiet"], &target)?;
521    }
522    if options.install_dependencies {
523        run_required("npm", &["install"], &target)?;
524        run_required("npm", &["run", "types", "--silent"], &target)?;
525    }
526    Ok(())
527}
528
529#[derive(Clone, Debug)]
530pub struct ProjectGenerator {
531    root: PathBuf,
532}
533
534impl ProjectGenerator {
535    /// Locate the Phoenix project containing `start`.
536    ///
537    /// # Errors
538    ///
539    /// Returns an error when no parent contains the expected Phoenix layout.
540    pub fn discover(start: impl AsRef<Path>) -> Result<Self, ScaffoldError> {
541        let start = absolute_path(start.as_ref())?;
542        for candidate in start.ancestors() {
543            if is_project_root(candidate) {
544                return Ok(Self {
545                    root: candidate.to_path_buf(),
546                });
547            }
548        }
549        Err(ScaffoldError::NotProject(start))
550    }
551
552    #[must_use]
553    pub fn root(&self) -> &Path {
554        &self.root
555    }
556
557    /// Refresh generated TypeScript contracts after a Rust generator runs.
558    ///
559    /// Returns `Ok(false)` before JavaScript dependencies are installed; Vite
560    /// will still generate the files when development starts.
561    ///
562    /// # Errors
563    ///
564    /// Returns an error when the installed Phoenix Vite generator fails.
565    pub fn refresh_types(&self) -> Result<bool, ScaffoldError> {
566        if !self.root.join("node_modules/@apizero/vite").is_dir() {
567            return Ok(false);
568        }
569        run_required("npm", &["run", "types", "--silent"], &self.root)?;
570        Ok(true)
571    }
572
573    /// Generate a controller and optionally its conventional resource route.
574    ///
575    /// # Errors
576    ///
577    /// Returns an error for invalid names, conflicts, or malformed managed files.
578    pub fn controller(
579        &self,
580        name: &str,
581        options: ControllerOptions,
582    ) -> Result<Vec<PathBuf>, ScaffoldError> {
583        let name = QualifiedName::parse_with_suffix(name, "Controller")?;
584        let mut editor = ProjectEditor::new(&self.root, options.force);
585        add_rust_item(
586            &mut editor,
587            "app/controllers",
588            &name,
589            &controller_template(&name.class, options.resource),
590        )?;
591        if options.route || options.resource {
592            add_controller_route(&mut editor, &name, options.resource, None)?;
593        }
594        editor.commit()
595    }
596
597    /// Generate a Toasty model and any requested companion artifacts.
598    ///
599    /// `--all` creates the currently supported cohesive business slice: model,
600    /// migration, request, API resource, resource controller/route, and index page.
601    ///
602    /// # Errors
603    ///
604    /// Returns an error for invalid names, conflicts, or malformed managed files.
605    pub fn model(
606        &self,
607        name: &str,
608        mut options: ModelOptions,
609    ) -> Result<Vec<PathBuf>, ScaffoldError> {
610        if options.all {
611            options.factory = true;
612            options.migration = true;
613            options.request = true;
614            options.api_resource = true;
615            options.controller = true;
616            options.resource_controller = true;
617            options.page = true;
618        }
619        let model = QualifiedName::parse(name)?;
620        let request = model.with_leaf(format!("Store{}Request", model.class));
621        let resource = model.with_leaf(format!("{}Resource", model.class));
622        let controller = model.with_leaf(format!("{}Controller", model.class));
623        let page = model.index_page_name();
624        let props = page_props_name(&page);
625        let cohesive = options.request
626            && options.api_resource
627            && options.controller
628            && options.resource_controller
629            && options.page;
630        let mut editor = ProjectEditor::new(&self.root, options.force);
631        add_model(&mut editor, &model, &options.relations)?;
632        if options.factory {
633            add_factory(&mut editor, &model, &options.relations)?;
634        }
635        if options.migration {
636            add_model_migration(&mut editor, &model)?;
637        }
638        if options.request {
639            add_rust_item(
640                &mut editor,
641                "app/requests",
642                &request,
643                &request_template(&request.class),
644            )?;
645        }
646        if options.api_resource {
647            add_rust_item(
648                &mut editor,
649                "app/resources",
650                &resource,
651                &resource_template(&resource.class),
652            )?;
653        }
654        if options.controller || options.resource_controller {
655            let content = if cohesive {
656                model_controller_template(&controller, &request, &resource, &props, &page.route)
657            } else {
658                controller_template(&controller.class, options.resource_controller)
659            };
660            add_rust_item(&mut editor, "app/controllers", &controller, &content)?;
661            let action = cohesive.then_some((&request, &resource));
662            add_controller_route(
663                &mut editor,
664                &controller,
665                options.resource_controller,
666                action,
667            )?;
668        }
669        if options.page {
670            add_page(&mut editor, &page, self.frontend())?;
671        }
672        editor.commit()
673    }
674
675    /// Generate one migration and register it in `database/migrations/mod.rs`.
676    ///
677    /// # Errors
678    ///
679    /// Returns an error for invalid names, conflicts, time, or managed files.
680    pub fn migration(
681        &self,
682        name: &str,
683        options: GenerateOptions,
684    ) -> Result<Vec<PathBuf>, ScaffoldError> {
685        let migration_name = snake_identifier(name)?;
686        let mut editor = ProjectEditor::new(&self.root, options.force);
687        add_migration(
688            &mut editor,
689            &migration_name,
690            inferred_table(&migration_name),
691        )?;
692        editor.commit()
693    }
694
695    /// Generate a validated request DTO and update its Rust module.
696    ///
697    /// # Errors
698    ///
699    /// Returns an error for invalid names, conflicts, or malformed managed files.
700    pub fn request(
701        &self,
702        name: &str,
703        options: GenerateOptions,
704    ) -> Result<Vec<PathBuf>, ScaffoldError> {
705        self.rust_contract(name, "Request", "app/requests", request_template, options)
706    }
707
708    /// Generate a browser-safe API resource and update its Rust module.
709    ///
710    /// # Errors
711    ///
712    /// Returns an error for invalid names, conflicts, or malformed managed files.
713    pub fn resource(
714        &self,
715        name: &str,
716        options: GenerateOptions,
717    ) -> Result<Vec<PathBuf>, ScaffoldError> {
718        self.rust_contract(
719            name,
720            "Resource",
721            "app/resources",
722            resource_template,
723            options,
724        )
725    }
726
727    /// Generate a pass-through middleware ready for application logic.
728    ///
729    /// # Errors
730    ///
731    /// Returns an error for invalid names, conflicts, or malformed managed files.
732    pub fn middleware(
733        &self,
734        name: &str,
735        options: GenerateOptions,
736    ) -> Result<Vec<PathBuf>, ScaffoldError> {
737        let name = QualifiedName::parse_with_suffix(name, "Middleware")?;
738        let mut editor = ProjectEditor::new(&self.root, options.force);
739        add_rust_item(
740            &mut editor,
741            "app/middleware",
742            &name,
743            &middleware_template(&name.class),
744        )?;
745        editor.commit()
746    }
747
748    /// Generate a React page plus its Rust Page Props contract.
749    ///
750    /// # Errors
751    ///
752    /// Returns an error for invalid names, conflicts, or malformed managed files.
753    pub fn page(
754        &self,
755        name: &str,
756        options: GenerateOptions,
757    ) -> Result<Vec<PathBuf>, ScaffoldError> {
758        let page = PageName::parse(name)?;
759        let mut editor = ProjectEditor::new(&self.root, options.force);
760        add_page(&mut editor, &page, self.frontend())?;
761        editor.commit()
762    }
763
764    /// Generate a React Island component.
765    ///
766    /// # Errors
767    ///
768    /// Returns an error for invalid names, conflicts, or file-system failures.
769    pub fn island(
770        &self,
771        name: &str,
772        options: GenerateOptions,
773    ) -> Result<Vec<PathBuf>, ScaffoldError> {
774        let name = QualifiedName::parse(name)?;
775        let mut editor = ProjectEditor::new(&self.root, options.force);
776        let mut path = PathBuf::from("views/islands");
777        path.extend(name.modules.iter().map(|module| kebab_case(module)));
778        let frontend = self.frontend();
779        path.push(format!(
780            "{}.{}",
781            kebab_case(&name.class),
782            frontend.extension()
783        ));
784        editor.create(path, island_template(&name.class, frontend))?;
785        editor.commit()
786    }
787
788    /// Generate a console command and register it in `app/commands/mod.rs`.
789    ///
790    /// # Errors
791    ///
792    /// Returns an error for invalid names, conflicts, or malformed managed files.
793    pub fn command(
794        &self,
795        name: &str,
796        options: GenerateOptions,
797    ) -> Result<Vec<PathBuf>, ScaffoldError> {
798        let name = QualifiedName::parse(name)?;
799        let mut editor = ProjectEditor::new(&self.root, options.force);
800        add_command(&mut editor, &name)?;
801        editor.commit()
802    }
803
804    /// Generate the authentication starter kit (`px make:auth`).
805    ///
806    /// Creates named login / logout / register / password-reset routes with a
807    /// stricter rate limit, an `AuthController`, validated request contracts,
808    /// browser-safe resources, page props, and React form pages.
809    ///
810    /// # Errors
811    ///
812    /// Returns an error for conflicts or malformed managed files.
813    pub fn auth(&self, options: GenerateOptions) -> Result<Vec<PathBuf>, ScaffoldError> {
814        // The generated slice authenticates against a persistent `users` table,
815        // so a database driver must have been selected at `px new`.
816        if self.stored_options().database.is_none() {
817            return Err(ScaffoldError::AuthRequiresDatabase);
818        }
819        let frontend = self.frontend();
820        let mut editor = ProjectEditor::new(&self.root, options.force);
821        // Persistent User model + migration; registered like `px make:model`.
822        add_rust_item(
823            &mut editor,
824            "app/models",
825            &QualifiedName {
826                modules: Vec::new(),
827                class: "User".to_owned(),
828            },
829            &auth_user_model_template(),
830        )?;
831        editor.update_registry(
832            "app/models/mod.rs",
833            MODELS_START,
834            MODELS_END,
835            "model",
836            "User",
837            render_model_registry,
838        )?;
839        add_auth_user_migration(&mut editor)?;
840        // Credentials use Argon2id (`password`) and the guard lives in the
841        // `phoenix-auth` crate (`auth`); enable both facade features.
842        enable_project_features(&mut editor, &["password", "auth"])?;
843        for (class, content) in [
844            ("LoginInput", login_input_template()),
845            ("RegisterInput", register_input_template()),
846            ("PasswordResetInput", password_reset_input_template()),
847        ] {
848            add_rust_item(
849                &mut editor,
850                "app/requests",
851                &QualifiedName {
852                    modules: Vec::new(),
853                    class: class.to_owned(),
854                },
855                &content,
856            )?;
857        }
858        for (class, content) in [
859            ("AuthSessionResource", auth_session_resource_template()),
860            ("AuthMessageResource", auth_message_resource_template()),
861        ] {
862            add_rust_item(
863                &mut editor,
864                "app/resources",
865                &QualifiedName {
866                    modules: Vec::new(),
867                    class: class.to_owned(),
868                },
869                &content,
870            )?;
871        }
872        add_rust_item(
873            &mut editor,
874            "app/controllers",
875            &QualifiedName {
876                modules: Vec::new(),
877                class: "AuthController".to_owned(),
878            },
879            &auth_controller_template(),
880        )?;
881        for (page, content) in [
882            ("auth/login", auth_login_page_template(frontend)),
883            ("auth/register", auth_register_page_template(frontend)),
884            (
885                "auth/forgot-password",
886                auth_forgot_password_page_template(frontend),
887            ),
888        ] {
889            add_auth_page(&mut editor, page, content, frontend)?;
890        }
891        editor.create("routes/auth.rs", auth_routes_template())?;
892        editor.commit()
893    }
894
895    fn rust_contract(
896        &self,
897        name: &str,
898        suffix: &str,
899        directory: &str,
900        template: fn(&str) -> String,
901        options: GenerateOptions,
902    ) -> Result<Vec<PathBuf>, ScaffoldError> {
903        let name = QualifiedName::parse_with_suffix(name, suffix)?;
904        let mut editor = ProjectEditor::new(&self.root, options.force);
905        add_rust_item(&mut editor, directory, &name, &template(&name.class))?;
906        editor.commit()
907    }
908
909    fn frontend(&self) -> ProjectFrontend {
910        self.stored_options().frontend
911    }
912
913    fn stored_options(&self) -> StoredProjectOptions {
914        read_stored_options(&self.root)
915    }
916
917    /// Refresh framework-owned core files without touching business code.
918    ///
919    /// Updates `src/lib.rs` / `src/main.rs`, Vite/TS config, config schemas, dependency
920    /// pins for `phoenixrs` / `@apizero/*`, and (when the project uses a database)
921    /// `src/bin/phoenix-manage.rs`. Leaves controllers, routes, pages, and user TOML alone.
922    ///
923    /// # Errors
924    ///
925    /// Returns an error for invalid local framework roots, I/O failures, or npm failures.
926    pub fn update_core(
927        &self,
928        options: &UpdateProjectOptions,
929    ) -> Result<Vec<PathBuf>, ScaffoldError> {
930        if let DependencySource::Local(root) = &options.dependencies
931            && !is_framework_root(root)
932        {
933            return Err(ScaffoldError::InvalidFrameworkRoot(root.clone()));
934        }
935
936        let package = read_package_name(&self.root)?;
937        let crate_name = package.replace('-', "_");
938        let stored = self.stored_options();
939        let has_database = stored.database.is_some();
940        let (rust_dependency, react, react_ssr, vite) =
941            framework_dependency_pins(&options.dependencies, &stored.features)?;
942
943        let mut planned: BTreeMap<PathBuf, String> = BTreeMap::new();
944        planned.insert("src/main.rs".into(), main_template(&crate_name));
945        planned.insert(
946            "src/lib.rs".into(),
947            lib_template(has_database, &stored.features),
948        );
949        planned.insert("config/mod.rs".into(), config_template(has_database));
950        planned.insert(
951            "vite.config.ts".into(),
952            vite_template(false, stored.tailwind),
953        );
954        planned.insert(
955            "vite.ssr.config.ts".into(),
956            vite_template(true, stored.tailwind),
957        );
958        planned.insert("tsconfig.json".into(), tsconfig_template());
959        planned.insert(
960            ".gitignore".into(),
961            "/target\n/node_modules\n/public/assets\n/public/ssr\n/views/generated/*.ts\n/dist\n/storage/*.sqlite\n/storage/*.sqlite-*\n.env\n.DS_Store\n".to_owned(),
962        );
963        planned.insert(PROJECT_OPTIONS_FILE.into(), format_stored_options(&stored));
964
965        if stored.database.is_some() {
966            planned.insert(
967                "src/bin/phoenix-manage.rs".into(),
968                management_template(
969                    &crate_name,
970                    stored
971                        .features
972                        .iter()
973                        .any(|feature| feature.has_migrations()),
974                ),
975            );
976            // Ensure empty registries exist when upgrading a no-db project that later
977            // recorded a database in `.phoenix` — do not overwrite populated registries.
978            for (path, content) in [
979                ("app/models/mod.rs", empty_model_registry()),
980                ("database/migrations/mod.rs", empty_migration_registry()),
981                ("database/seeders/mod.rs", seeder_template()),
982            ] {
983                if !self.root.join(path).is_file() {
984                    planned.insert(path.into(), content);
985                }
986            }
987        }
988
989        // Feature config files carry user values: create only when missing.
990        for feature in &stored.features {
991            let path = format!("config/{}.toml", feature.key());
992            if !self.root.join(&path).is_file() {
993                planned.insert(path.into(), feature_config_template(*feature));
994            }
995        }
996
997        let cargo_path = PathBuf::from("Cargo.toml");
998        let cargo = fs::read_to_string(self.root.join(&cargo_path)).map_err(|source| {
999            ScaffoldError::Io {
1000                path: self.root.join(&cargo_path),
1001                source,
1002            }
1003        })?;
1004        let cargo = patch_cargo_toml_core(&cargo, &rust_dependency);
1005        planned.insert(cargo_path, cargo);
1006
1007        let package_json_path = PathBuf::from("package.json");
1008        let package_json =
1009            fs::read_to_string(self.root.join(&package_json_path)).map_err(|source| {
1010                ScaffoldError::Io {
1011                    path: self.root.join(&package_json_path),
1012                    source,
1013                }
1014            })?;
1015        let package_json =
1016            patch_package_json_core(&package_json, &react, &react_ssr, &vite, stored.tailwind)?;
1017        planned.insert(package_json_path, package_json);
1018
1019        let mut changed = Vec::new();
1020        for (relative, content) in &planned {
1021            let absolute = self.root.join(relative);
1022            let existing = match fs::read_to_string(&absolute) {
1023                Ok(text) => text,
1024                Err(error) if error.kind() == ErrorKind::NotFound => String::new(),
1025                Err(source) => {
1026                    return Err(ScaffoldError::Io {
1027                        path: absolute,
1028                        source,
1029                    });
1030                }
1031            };
1032            if existing == *content {
1033                continue;
1034            }
1035            changed.push(absolute.clone());
1036            if options.dry_run {
1037                continue;
1038            }
1039            if let Some(parent) = absolute.parent() {
1040                fs::create_dir_all(parent).map_err(|source| ScaffoldError::Io {
1041                    path: parent.to_path_buf(),
1042                    source,
1043                })?;
1044            }
1045            fs::write(&absolute, content).map_err(|source| ScaffoldError::Io {
1046                path: absolute,
1047                source,
1048            })?;
1049        }
1050
1051        if !options.dry_run
1052            && options.install_dependencies
1053            && self.root.join("package.json").is_file()
1054        {
1055            run_required("npm", &["install"], &self.root)?;
1056            let _ = self.refresh_types()?;
1057        }
1058
1059        Ok(changed)
1060    }
1061}
1062
1063fn is_project_root(path: &Path) -> bool {
1064    path.join("Cargo.toml").is_file()
1065        && path.join("package.json").is_file()
1066        && path.join("app").is_dir()
1067        && path.join("routes").is_dir()
1068        && path.join("views").is_dir()
1069}
1070
1071fn framework_dependency_pins(
1072    source: &DependencySource,
1073    features: &[ProjectFeature],
1074) -> Result<(String, String, String, String), ScaffoldError> {
1075    // Comma-separated `"captcha", "pay"` fragment for the phoenix dependency line.
1076    let feature_list = features
1077        .iter()
1078        .map(|feature| format!("\"{}\"", feature.key()))
1079        .collect::<Vec<_>>()
1080        .join(", ");
1081    let feature_suffix = if feature_list.is_empty() {
1082        String::new()
1083    } else {
1084        format!(", features = [{feature_list}]")
1085    };
1086    match source {
1087        // Plain semver ranges: the user's own npm registry (npmmirror and
1088        // friends included) resolves them. Never emit registry.npmjs.org
1089        // tarball URLs — they bypass configured mirrors.
1090        DependencySource::Registry => Ok((
1091            format!(
1092                "phoenix = {{ package = \"phoenixrs\", version = \"{PHOENIXRS_VERSION}\", default-features = false{feature_suffix} }}"
1093            ),
1094            format!("^{APIZERO_REACT_VERSION}"),
1095            format!("^{APIZERO_REACT_SSR_VERSION}"),
1096            format!("^{APIZERO_VITE_VERSION}"),
1097        )),
1098        DependencySource::Local(root) => {
1099            let root = absolute_path(root)?;
1100            Ok((
1101                format!(
1102                    "phoenix = {{ package = \"phoenixrs\", path = {}, default-features = false{feature_suffix} }}",
1103                    json_string(&root.join("crates/phoenix").to_string_lossy())
1104                ),
1105                format!("file:{}", root.join("packages/phoenix-react").display()),
1106                format!("file:{}", root.join("packages/phoenix-react-ssr").display()),
1107                format!("file:{}", root.join("packages/phoenix-vite").display()),
1108            ))
1109        }
1110    }
1111}
1112
1113fn format_stored_options(options: &StoredProjectOptions) -> String {
1114    let database = options.database.map_or("none", database_option_key);
1115    let render_mode = match options.render_mode {
1116        ProjectRenderMode::Spa => "spa",
1117        ProjectRenderMode::Ssr => "ssr",
1118        ProjectRenderMode::Islands => "islands",
1119    };
1120    let features = options
1121        .features
1122        .iter()
1123        .map(|feature| feature.key())
1124        .collect::<Vec<_>>()
1125        .join(",");
1126    format!(
1127        "frontend={}\nrender_mode={render_mode}\ndatabase={database}\ntailwind={}\nfeatures={features}\n",
1128        options.frontend.extension(),
1129        if options.tailwind { "true" } else { "false" },
1130    )
1131}
1132
1133fn database_option_key(database: ProjectDatabase) -> &'static str {
1134    match database {
1135        ProjectDatabase::Sqlite => "sqlite",
1136        ProjectDatabase::Pgsql => "pgsql",
1137        ProjectDatabase::Mysql => "mysql",
1138        ProjectDatabase::All => "all",
1139    }
1140}
1141
1142fn read_stored_options(root: &Path) -> StoredProjectOptions {
1143    let mut options = StoredProjectOptions {
1144        frontend: ProjectFrontend::default(),
1145        database: None,
1146        render_mode: ProjectRenderMode::default(),
1147        tailwind: false,
1148        features: Vec::new(),
1149    };
1150    let mut render_mode_recorded = false;
1151
1152    if let Ok(source) = fs::read_to_string(root.join(PROJECT_OPTIONS_FILE)) {
1153        for line in source.lines() {
1154            if let Some(value) = line.strip_prefix("frontend=") {
1155                if let Ok(frontend) = value.parse() {
1156                    options.frontend = frontend;
1157                }
1158            } else if let Some(value) = line.strip_prefix("render_mode=") {
1159                if let Ok(render_mode) = value.parse() {
1160                    options.render_mode = render_mode;
1161                    render_mode_recorded = true;
1162                }
1163            } else if let Some(value) = line.strip_prefix("database=") {
1164                options.database = match value.trim() {
1165                    "" | "none" | "no" => None,
1166                    other => other.parse().ok(),
1167                };
1168            } else if let Some(value) = line.strip_prefix("tailwind=") {
1169                options.tailwind = matches!(value.trim(), "1" | "true" | "yes");
1170            } else if let Some(value) = line.strip_prefix("features=")
1171                && let Ok(features) = parse_feature_list(value)
1172            {
1173                options.features = features;
1174            }
1175        }
1176    }
1177
1178    if options.database.is_none() && root.join("src/bin/phoenix-manage.rs").is_file() {
1179        options.database = Some(infer_database(root));
1180    }
1181    if !options.tailwind
1182        && fs::read_to_string(root.join("package.json"))
1183            .ok()
1184            .is_some_and(|text| text.contains("tailwindcss"))
1185    {
1186        options.tailwind = true;
1187    }
1188    if !render_mode_recorded
1189        && let Ok(controller) = fs::read_to_string(root.join("app/controllers/home_controller.rs"))
1190        && let Some(render_mode) = sniff_home_render_mode(&controller)
1191    {
1192        options.render_mode = render_mode;
1193    }
1194    if options.frontend == ProjectFrontend::default()
1195        && root.join("views/pages/home.jsx").is_file()
1196        && !root.join("views/pages/home.tsx").is_file()
1197    {
1198        options.frontend = ProjectFrontend::Jsx;
1199    }
1200    options
1201}
1202
1203/// Legacy fallback for projects without `render_mode=` in `.phoenix`: the mode
1204/// marker closest after `Page::new("home"` wins, so the demo-page methods in
1205/// the same controller do not confuse the detection.
1206fn sniff_home_render_mode(controller: &str) -> Option<ProjectRenderMode> {
1207    let start = controller.find("\"home\"").unwrap_or(0);
1208    let tail = &controller[start..];
1209    [
1210        (".spa()", ProjectRenderMode::Spa),
1211        (".ssr()", ProjectRenderMode::Ssr),
1212        (".islands()", ProjectRenderMode::Islands),
1213    ]
1214    .into_iter()
1215    .filter_map(|(marker, mode)| tail.find(marker).map(|index| (index, mode)))
1216    .min_by_key(|(index, _)| *index)
1217    .map(|(_, mode)| mode)
1218}
1219
1220/// Infer the driver for legacy projects (no `database=` line in `.phoenix`)
1221/// from the Cargo feature default, falling back to the `.env` `DATABASE_URL`.
1222fn infer_database(root: &Path) -> ProjectDatabase {
1223    if let Ok(cargo) = fs::read_to_string(root.join("Cargo.toml")) {
1224        if cargo.contains("default = [\"all-databases\"]") || cargo.contains("all-databases =") {
1225            return ProjectDatabase::All;
1226        }
1227        if cargo.contains("default = [\"mysql\"]") {
1228            return ProjectDatabase::Mysql;
1229        }
1230        if cargo.contains("default = [\"pgsql\"]") {
1231            return ProjectDatabase::Pgsql;
1232        }
1233        if cargo.contains("default = [\"sqlite\"]") {
1234            return ProjectDatabase::Sqlite;
1235        }
1236    }
1237    for env_file in [".env", ".env.example"] {
1238        if let Ok(env) = fs::read_to_string(root.join(env_file)) {
1239            for line in env.lines() {
1240                let Some(url) = line.trim().strip_prefix("DATABASE_URL=") else {
1241                    continue;
1242                };
1243                let url = url.trim();
1244                if url.starts_with("sqlite:") {
1245                    return ProjectDatabase::Sqlite;
1246                }
1247                if url.starts_with("postgres") {
1248                    return ProjectDatabase::Pgsql;
1249                }
1250                if url.starts_with("mysql:") {
1251                    return ProjectDatabase::Mysql;
1252                }
1253            }
1254        }
1255    }
1256    ProjectDatabase::Sqlite
1257}
1258
1259fn read_package_name(root: &Path) -> Result<String, ScaffoldError> {
1260    let path = root.join("Cargo.toml");
1261    let text = fs::read_to_string(&path).map_err(|source| ScaffoldError::Io {
1262        path: path.clone(),
1263        source,
1264    })?;
1265    let mut in_package = false;
1266    for line in text.lines() {
1267        let trimmed = line.trim();
1268        if trimmed.starts_with('[') && trimmed.ends_with(']') {
1269            in_package = trimmed == "[package]";
1270            continue;
1271        }
1272        if in_package && let Some(value) = trimmed.strip_prefix("name = ") {
1273            let value = value.trim();
1274            if value.starts_with('"') && value.ends_with('"') && value.len() >= 2 {
1275                return Ok(value[1..value.len() - 1].to_owned());
1276            }
1277        }
1278    }
1279    Err(ScaffoldError::InvalidManagedFile(path))
1280}
1281
1282fn patch_cargo_toml_core(cargo: &str, phoenix_dependency: &str) -> String {
1283    let mut lines = cargo.lines().map(str::to_owned).collect::<Vec<_>>();
1284    let mut replaced = false;
1285    for line in &mut lines {
1286        let trimmed = line.trim_start();
1287        if trimmed.starts_with("phoenix =") || trimmed.starts_with("phoenixrs =") {
1288            phoenix_dependency.clone_into(line);
1289            replaced = true;
1290        }
1291    }
1292    if !replaced {
1293        if let Some(index) = lines
1294            .iter()
1295            .position(|line| line.trim() == "[dependencies]")
1296        {
1297            lines.insert(index + 1, phoenix_dependency.to_owned());
1298        } else {
1299            lines.push(String::new());
1300            lines.push("[dependencies]".to_owned());
1301            lines.push(phoenix_dependency.to_owned());
1302        }
1303    }
1304
1305    let required_features = [
1306        ("tls =", "tls = [\"phoenix/tls\"]"),
1307        ("websocket =", "websocket = [\"phoenix/websocket\"]"),
1308        ("sse =", "sse = [\"phoenix/sse\"]"),
1309        ("auth =", "auth = [\"phoenix/auth\"]"),
1310        ("jwt =", "jwt = [\"phoenix/jwt\"]"),
1311        ("password =", "password = [\"phoenix/password\"]"),
1312        ("metrics =", "metrics = [\"phoenix/metrics\"]"),
1313        ("redis =", "redis = [\"phoenix/redis\"]"),
1314        ("storage =", "storage = [\"phoenix/storage\"]"),
1315        ("queue =", "queue = [\"phoenix/queue\"]"),
1316        ("mail =", "mail = [\"phoenix/mail\"]"),
1317        ("testing =", "testing = [\"phoenix/testing\"]"),
1318        ("factory =", "factory = [\"phoenix/factory\"]"),
1319    ];
1320    let mut missing = Vec::new();
1321    for (prefix, line) in required_features {
1322        if !lines
1323            .iter()
1324            .any(|existing| existing.trim_start().starts_with(prefix))
1325        {
1326            missing.push(line.to_owned());
1327        }
1328    }
1329    if !missing.is_empty() {
1330        let insert_at = lines
1331            .iter()
1332            .position(|line| line.trim() == "[dependencies]")
1333            .unwrap_or(lines.len());
1334        for (offset, line) in missing.into_iter().enumerate() {
1335            lines.insert(insert_at + offset, line);
1336        }
1337    }
1338
1339    let mut body = lines.join("\n");
1340    if !body.ends_with('\n') {
1341        body.push('\n');
1342    }
1343    body
1344}
1345
1346fn patch_package_json_core(
1347    raw: &str,
1348    react: &str,
1349    react_ssr: &str,
1350    vite: &str,
1351    tailwind: bool,
1352) -> Result<String, ScaffoldError> {
1353    let mut value: serde_json::Value =
1354        serde_json::from_str(raw).map_err(|source| ScaffoldError::Io {
1355            path: PathBuf::from("package.json"),
1356            source: std::io::Error::new(ErrorKind::InvalidData, source.to_string()),
1357        })?;
1358    let object = value.as_object_mut().ok_or_else(|| ScaffoldError::Io {
1359        path: PathBuf::from("package.json"),
1360        source: std::io::Error::new(
1361            ErrorKind::InvalidData,
1362            "package.json root must be an object",
1363        ),
1364    })?;
1365
1366    let dependencies = object
1367        .entry("dependencies")
1368        .or_insert_with(|| serde_json::json!({}));
1369    if let Some(deps) = dependencies.as_object_mut() {
1370        deps.insert(
1371            "@apizero/react".to_owned(),
1372            serde_json::Value::String(react.to_owned()),
1373        );
1374        deps.insert(
1375            "@apizero/react-ssr".to_owned(),
1376            serde_json::Value::String(react_ssr.to_owned()),
1377        );
1378        deps.insert(
1379            "@apizero/vite".to_owned(),
1380            serde_json::Value::String(vite.to_owned()),
1381        );
1382    }
1383
1384    let scripts = object
1385        .entry("scripts")
1386        .or_insert_with(|| serde_json::json!({}));
1387    if let Some(scripts) = scripts.as_object_mut() {
1388        scripts.insert(
1389            "dev".to_owned(),
1390            serde_json::Value::String("vite --host 127.0.0.1".to_owned()),
1391        );
1392        scripts.insert(
1393            "build".to_owned(),
1394            serde_json::Value::String("npm run build:client && npm run build:ssr".to_owned()),
1395        );
1396        scripts.insert(
1397            "build:client".to_owned(),
1398            serde_json::Value::String("vite build".to_owned()),
1399        );
1400        scripts.insert(
1401            "build:ssr".to_owned(),
1402            serde_json::Value::String("vite build --config vite.ssr.config.ts".to_owned()),
1403        );
1404        scripts.insert(
1405            "types".to_owned(),
1406            serde_json::Value::String(
1407                "node -e \"import('@apizero/vite').then(({ generateRouteTypes }) => generateRouteTypes('routes', 'views/generated/routes.ts', '.', 'views/generated/contracts.ts'))\""
1408                    .to_owned(),
1409            ),
1410        );
1411        scripts.insert(
1412            "typecheck".to_owned(),
1413            serde_json::Value::String("npm run types && tsc --noEmit".to_owned()),
1414        );
1415    }
1416
1417    if tailwind {
1418        let dev_dependencies = object
1419            .entry("devDependencies")
1420            .or_insert_with(|| serde_json::json!({}));
1421        if let Some(deps) = dev_dependencies.as_object_mut() {
1422            deps.entry("@tailwindcss/vite".to_owned())
1423                .or_insert_with(|| serde_json::Value::String("^4.3.0".to_owned()));
1424            deps.entry("tailwindcss".to_owned())
1425                .or_insert_with(|| serde_json::Value::String("^4.3.0".to_owned()));
1426        }
1427    }
1428
1429    let mut rendered =
1430        serde_json::to_string_pretty(&value).map_err(|source| ScaffoldError::Io {
1431            path: PathBuf::from("package.json"),
1432            source: std::io::Error::new(ErrorKind::InvalidData, source.to_string()),
1433        })?;
1434    rendered.push('\n');
1435    Ok(rendered)
1436}
1437
1438// The body is the flat scaffold file list; the length is data, not logic.
1439#[allow(clippy::too_many_lines)]
1440fn project_files(
1441    package: &str,
1442    options: &NewProjectOptions,
1443) -> Result<Vec<(PathBuf, String)>, ScaffoldError> {
1444    let (rust_dependency, react, react_ssr, vite) =
1445        framework_dependency_pins(&options.dependencies, &options.features)?;
1446    let crate_name = package.replace('-', "_");
1447    let tailwind = if options.tailwind {
1448        ",\n    \"@tailwindcss/vite\": \"^4.3.0\",\n    \"tailwindcss\": \"^4.3.0\""
1449    } else {
1450        ""
1451    };
1452    let package_json = format!(
1453        r#"{{
1454  "name": {package},
1455  "version": "0.1.0",
1456  "private": true,
1457  "type": "module",
1458  "scripts": {{
1459    "dev": "vite --host 127.0.0.1",
1460    "build": "npm run build:client && npm run build:ssr",
1461    "build:client": "vite build",
1462    "build:ssr": "vite build --config vite.ssr.config.ts",
1463    "types": "node -e \"import('@apizero/vite').then(({{ generateRouteTypes }}) => generateRouteTypes('routes', 'views/generated/routes.ts', '.', 'views/generated/contracts.ts'))\"",
1464    "typecheck": "npm run types && tsc --noEmit"
1465  }},
1466  "dependencies": {{
1467    "@apizero/react": {react},
1468    "@apizero/react-ssr": {react_ssr},
1469    "@apizero/vite": {vite},
1470    "react": "^19.1.0",
1471    "react-dom": "^19.1.0"
1472  }},
1473  "devDependencies": {{
1474    "@types/react": "^19.0.0",
1475    "@types/react-dom": "^19.0.0",
1476    "typescript": "^5.8.0",
1477    "vite": "^7.3.6"{tailwind}
1478  }}
1479}}
1480"#,
1481        package = json_string(package),
1482        react = json_string(&react),
1483        react_ssr = json_string(&react_ssr),
1484        vite = json_string(&vite),
1485        tailwind = tailwind,
1486    );
1487    let (database_features, toasty_dependency) = options.database.map_or_else(
1488        || ("default = []\ndatabase = []\n".to_owned(), String::new()),
1489        |database| {
1490            let app_feature = database.cargo_feature();
1491            let phoenix_features = match database {
1492                ProjectDatabase::All => "\"database\", \"phoenix/sqlite\", \"phoenix/pgsql\", \"phoenix/mysql\"".to_owned(),
1493                _ => format!("\"database\", \"phoenix/{app_feature}\""),
1494            };
1495            let toasty_features = database.toasty_features();
1496            (
1497                format!(
1498                    "default = [\"{app_feature}\"]\ndatabase = [\"phoenix/database\"]\n{app_feature} = [{phoenix_features}]\n"
1499                ),
1500                format!(
1501                    "toasty = {{ version = \"0.8\", default-features = false, features = [\"migration\", \"{toasty_features}\"] }}\n"
1502                ),
1503            )
1504        },
1505    );
1506    let cargo_toml = format!(
1507        "[package]\nname = {package}\nversion = \"0.1.0\"\nedition = \"2024\"\nrust-version = \"1.95\"\npublish = false\ndefault-run = {package}\n\n[features]\n# Database support is omitted unless selected during `px new`.\n{database_features}tls = [\"phoenix/tls\"]\nwebsocket = [\"phoenix/websocket\"]\nsse = [\"phoenix/sse\"]\nauth = [\"phoenix/auth\"]\njwt = [\"phoenix/jwt\"]\npassword = [\"phoenix/password\"]\nmetrics = [\"phoenix/metrics\"]\nredis = [\"phoenix/redis\"]\nstorage = [\"phoenix/storage\"]\nqueue = [\"phoenix/queue\"]\nmail = [\"phoenix/mail\"]\ntesting = [\"phoenix/testing\"]\n# Batch test data. Development and test only; never enable in a release build.\nfactory = [\"phoenix/factory\"]\n\n[dependencies]\n{rust_dependency}\nserde = {{ version = \"1\", features = [\"derive\"] }}\nserde_json = \"1\"\n{toasty_dependency}tokio = {{ version = \"1\", features = [\"macros\", \"rt-multi-thread\", \"signal\"] }}\n\n[profile.release]\ncodegen-units = 1\nlto = true\nopt-level = \"z\"\npanic = \"unwind\"\nstrip = \"symbols\"\n\n[workspace]\n",
1508        package = json_string(package),
1509        database_features = database_features,
1510        rust_dependency = rust_dependency,
1511        toasty_dependency = toasty_dependency,
1512    );
1513
1514    let stored = StoredProjectOptions {
1515        frontend: options.frontend,
1516        database: options.database,
1517        render_mode: options.render_mode,
1518        tailwind: options.tailwind,
1519        features: options.features.clone(),
1520    };
1521    let extension = options.frontend.extension();
1522
1523    let mut files = vec![
1524        ("Cargo.toml".into(), cargo_toml),
1525        (
1526            PROJECT_OPTIONS_FILE.into(),
1527            format_stored_options(&stored),
1528        ),
1529        ("package.json".into(), package_json),
1530        (".gitignore".into(), "/target\n/node_modules\n/public/assets\n/public/ssr\n/views/generated/*.ts\n/dist\n/storage/*.sqlite\n/storage/*.sqlite-*\n.env\n.DS_Store\n".to_owned()),
1531        (".env.example".into(), env_example_template(options.database, &options.features)),
1532        ("README.md".into(), project_readme(package, options)),
1533        ("src/main.rs".into(), main_template(&crate_name)),
1534        ("src/lib.rs".into(), lib_template(options.database.is_some(), &options.features)),
1535        ("config/mod.rs".into(), config_template(options.database.is_some())),
1536        ("app/controllers/mod.rs".into(), managed_modules(&["pub mod home_controller;", "pub use home_controller::HomeController;"])),
1537        ("app/controllers/home_controller.rs".into(), home_controller_template(options.render_mode)),
1538        ("app/props/mod.rs".into(), managed_modules(&[
1539            "pub mod demo_ssr_props;",
1540            "pub mod home_props;",
1541            "pub use demo_ssr_props::DemoSsrProps;",
1542            "pub use home_props::HomeProps;",
1543        ])),
1544        ("app/props/home_props.rs".into(), home_props_template()),
1545        ("app/props/demo_ssr_props.rs".into(), demo_ssr_props_template()),
1546        ("app/requests/mod.rs".into(), managed_modules(&[])),
1547        ("app/resources/mod.rs".into(), managed_modules(&[])),
1548        ("app/middleware/mod.rs".into(), managed_modules(&[])),
1549        ("app/commands/mod.rs".into(), commands_mod_template()),
1550        ("routes/web.rs".into(), home_route_template()),
1551        (
1552            format!("views/pages/home.{extension}").into(),
1553            home_page_template(options.frontend),
1554        ),
1555        (
1556            format!("views/pages/demo/spa.{extension}").into(),
1557            demo_spa_page_template(),
1558        ),
1559        (
1560            format!("views/pages/demo/ssr.{extension}").into(),
1561            demo_ssr_page_template(options.frontend),
1562        ),
1563        (
1564            format!("views/pages/demo/islands.{extension}").into(),
1565            demo_islands_page_template(),
1566        ),
1567        (
1568            format!("views/islands/counter.{extension}").into(),
1569            island_template("Counter", options.frontend),
1570        ),
1571        ("views/styles.css".into(), styles_template(options.tailwind)),
1572        ("views/generated/contracts.ts".into(), generated_contracts_template()),
1573        ("views/generated/routes.ts".into(), generated_routes_template()),
1574        ("vite.config.ts".into(), vite_template(false, options.tailwind)),
1575        ("vite.ssr.config.ts".into(), vite_template(true, options.tailwind)),
1576        ("tsconfig.json".into(), tsconfig_template()),
1577        ("public/.gitkeep".into(), String::new()),
1578        ("storage/cache/.gitkeep".into(), String::new()),
1579        ("storage/logs/.gitkeep".into(), String::new()),
1580    ];
1581    if options.database.is_some() {
1582        files.extend([
1583            ("app/models/mod.rs".into(), empty_model_registry()),
1584            (
1585                "database/migrations/mod.rs".into(),
1586                empty_migration_registry(),
1587            ),
1588            ("database/seeders/mod.rs".into(), seeder_template()),
1589            (
1590                "src/bin/phoenix-manage.rs".into(),
1591                management_template(
1592                    &crate_name,
1593                    options
1594                        .features
1595                        .iter()
1596                        .any(|feature| feature.has_migrations()),
1597                ),
1598            ),
1599        ]);
1600    }
1601    for feature in &options.features {
1602        files.push((
1603            format!("config/{}.toml", feature.key()).into(),
1604            feature_config_template(*feature),
1605        ));
1606    }
1607    Ok(files)
1608}
1609
1610// One grouped template literal per section; the length is the generated file.
1611#[allow(clippy::too_many_lines)]
1612fn env_example_template(database: Option<ProjectDatabase>, features: &[ProjectFeature]) -> String {
1613    let database_block = match database {
1614        None => {
1615            "# ── 数据库(创建时未启用)────────────────────────────\n# 需要时用 `px new --database sqlite|pgsql|mysql` 重新创建,\n# 或按 docs/CONFIG.md 手动启用驱动 feature 后设置:\n# DATABASE_URL=sqlite:storage/app.sqlite\n".to_owned()
1616        }
1617        Some(driver) => {
1618            let (active, hints) = match driver {
1619                ProjectDatabase::Sqlite => (
1620                    "DATABASE_URL=sqlite:storage/app.sqlite",
1621                    "# DATABASE_URL=postgresql://phoenix:secret@127.0.0.1:5432/phoenix\n# DATABASE_URL=mysql://phoenix:secret@127.0.0.1:3306/phoenix\n",
1622                ),
1623                ProjectDatabase::Pgsql => (
1624                    "DATABASE_URL=postgresql://phoenix:secret@127.0.0.1:5432/phoenix",
1625                    "# DATABASE_URL=sqlite:storage/app.sqlite\n",
1626                ),
1627                ProjectDatabase::Mysql => (
1628                    "DATABASE_URL=mysql://phoenix:secret@127.0.0.1:3306/phoenix",
1629                    "# DATABASE_URL=sqlite:storage/app.sqlite\n",
1630                ),
1631                ProjectDatabase::All => (
1632                    "DATABASE_URL=sqlite:storage/app.sqlite",
1633                    "# 已编译全部驱动,改 URL 即可换库:\n# DATABASE_URL=postgresql://phoenix:secret@127.0.0.1:5432/phoenix\n# DATABASE_URL=mysql://phoenix:secret@127.0.0.1:3306/phoenix\n",
1634                ),
1635            };
1636            format!("# ── 数据库 ──────────────────────────────────────────\n{active}\n{hints}")
1637        }
1638    };
1639    let feature_block = if features.is_empty() {
1640        String::new()
1641    } else {
1642        let mut block =
1643            String::from("\n# ── Feature 密钥(config/*.toml 里以 ${VAR} 引用)─────\n");
1644        if features.contains(&ProjectFeature::Pay) {
1645            block.push_str(
1646                "# PAY_WECHAT_API_V3_KEY=\n# PAY_ALIPAY_APP_PRIVATE_KEY=\n# PAY_ALIPAY_PUBLIC_KEY=\n",
1647            );
1648        }
1649        if features.contains(&ProjectFeature::Captcha) {
1650            block.push_str("# 验证码无密钥;参数见 config/captcha.toml。\n");
1651        }
1652        if features.contains(&ProjectFeature::Notify) {
1653            block.push_str("# 通知本地用内存邮件传输;接真实 SMTP 时在此加对应密钥。\n");
1654        }
1655        block
1656    };
1657    format!(
1658        "# 复制为 `.env`:前后端启动 + 数据库的运行时配置都在这里。\n# 优先级:.env < 进程环境变量。config/ 目录只放 Feature 配置(TOML)。\n\n# ── 应用 ────────────────────────────────────────────\nAPP_ENV=development\nAPP_ADDR=127.0.0.1:3000\nAPP_URL=http://127.0.0.1:3000\n\n# ── 前端(Vite 开发服务器,`px dev` 使用)───────────\nVITE_DEV_URL=http://127.0.0.1:5173\n\n{database_block}\n# ── 日志 ────────────────────────────────────────────\nPHOENIX_LOG=info,hyper=warn\n\n# ── 限流与信任代理 ──────────────────────────────────\nRATE_LIMIT_REQUESTS=60\nRATE_LIMIT_WINDOW_SECONDS=60\nTRUSTED_PROXIES=none\nALLOWED_HOSTS=127.0.0.1,localhost,[::1]\n{feature_block}"
1659    )
1660}
1661
1662/// `config/<feature>.toml` starter: non-secret parameters live here, secrets
1663/// are injected from `.env` through `${VAR}` (see `load_feature_config`).
1664// One template literal per Feature; the length is the generated files.
1665#[allow(clippy::too_many_lines)]
1666fn feature_config_template(feature: ProjectFeature) -> String {
1667    match feature {
1668        ProjectFeature::Captcha => {
1669            r"# 图形验证码 Feature(phoenix-captcha)。详见 docs/CAPTCHA.md。
1670#
1671# CaptchaConfig 目前在代码中构造(src/lib.rs 的 features()),本文件记录默认
1672# 可调项;修改后把对应值同步到 `CaptchaFeature::with_config(...)`。
1673#
1674# length = 5        # 每次挑战的字符数(1–16)
1675# width = 160       # SVG 画布宽度
1676# height = 60       # SVG 画布高度
1677# noise_curves = 3  # 干扰曲线条数
1678# noise_dots = 28   # 噪点数量
1679"
1680            .to_owned()
1681        }
1682        ProjectFeature::Pay => r#"# 聚合支付 Feature(phoenix-pay)。详见 docs/PAYMENTS.md。
1683#
1684# 结构留在本文件,密钥放 `.env`:字符串值支持 `${VAR}` 占位符,加载时从
1685# 环境注入(src/lib.rs 的 pay_manager() 通过 load_feature_config("pay") 读取)。
1686# 两个渠道段都注释时仅启用 MockProvider——本地/测试即可完整跑通下单与回调。
1687
1688# [wechat_native]                                       # 微信支付 Native(APIv3)
1689# app_id = "wx1234567890"
1690# mch_id = "1900000001"
1691# mch_serial_no = ""                                    # 商户 API 证书序列号
1692# api_v3_key = "${PAY_WECHAT_API_V3_KEY}"               # 密钥进 .env
1693# private_key_path = "storage/certs/apiclient_key.pem"  # 商户私钥(不进仓库)
1694# notify_url = "https://example.com/pay/notify/wechat"
1695
1696# [alipay_f2f]                                          # 支付宝当面付(RSA2)
1697# app_id = "2021000000000000"
1698# app_private_key = "${PAY_ALIPAY_APP_PRIVATE_KEY}"     # 密钥进 .env
1699# alipay_public_key = "${PAY_ALIPAY_PUBLIC_KEY}"        # 支付宝公钥(非应用公钥)
1700# notify_url = "https://example.com/pay/notify/alipay"
1701"#
1702        .to_owned(),
1703        ProjectFeature::Notify => {
1704            r#"# 通知 Feature(phoenix-notify):邮件 + 数据库双通道。详见 docs/NOTIFICATIONS.md。
1705#
1706# 本地默认内存邮件传输 + 内存存储(src/lib.rs 的 notifier());
1707# 生产环境在代码中替换真实 MailTransport 与数据库 store。
1708#
1709# from = "noreply@example.com"   # 通知邮件的默认发件地址(应用代码中使用)
1710"#
1711            .to_owned()
1712        }
1713    }
1714}
1715
1716fn config_template(database: bool) -> String {
1717    let database = if database {
1718        " (`DATABASE_URL` selects the database)"
1719    } else {
1720        ""
1721    };
1722    format!(
1723        "pub use phoenix::config::{{\n    AppConfig, AppConfigBuilder, ConfigError, Environment, SecretValue, load_feature_config,\n}};\n\n/// Load this application's configuration.\n///\n/// Runtime settings come from `.env`, then the process environment{database}.\n/// Feature settings live in `config/<feature>.toml` via `load_feature_config`.\n///\n/// # Errors\n///\n/// Returns a source, validation, or production-requirement error.\npub fn load() -> Result<AppConfig, ConfigError> {{\n    AppConfig::load()\n}}\n"
1724    )
1725}
1726
1727// The body is one template literal; the line count is the generated file.
1728#[allow(clippy::too_many_lines)]
1729fn management_template(crate_name: &str, feature_migrations: bool) -> String {
1730    let migrations_expr = if feature_migrations {
1731        // Official Features (pay / notify) contribute migrations through their plugins.
1732        "{\n        let mut migrations = __PHOENIX_APP_CRATE__::migrations::all();\n        let features = __PHOENIX_APP_CRATE__::features()\n            .map_err(|error| error as Box<dyn Error>)?;\n        migrations.extend(features.into_parts().migrations);\n        migrations\n    }"
1733    } else {
1734        "__PHOENIX_APP_CRATE__::migrations::all()"
1735    };
1736    r#"#[cfg(feature = "database")]
1737use std::{env, error::Error, io};
1738
1739#[cfg(feature = "database")]
1740use phoenix::database::MigrationRunner;
1741
1742#[cfg(feature = "database")]
1743type CommandResult<T = ()> = Result<T, Box<dyn Error>>;
1744
1745#[cfg(not(feature = "database"))]
1746fn main() {
1747    println!("Database support is disabled; enable the sqlite, pgsql, or mysql feature.");
1748}
1749
1750#[cfg(feature = "database")]
1751#[tokio::main]
1752async fn main() -> CommandResult {
1753    let arguments = env::args().skip(1).collect::<Vec<_>>();
1754    let command = arguments
1755        .first()
1756        .map(String::as_str)
1757        .ok_or_else(|| input_error("expected migrate, status, rollback, fresh, or seed"))?;
1758    let options = &arguments[1..];
1759    if !matches!(command, "migrate" | "status" | "rollback" | "fresh" | "seed") {
1760        return Err(input_error(format!("unknown management command `{command}`")).into());
1761    }
1762
1763    let config = __PHOENIX_APP_CRATE__::config::load()?;
1764    let mut database = __PHOENIX_APP_CRATE__::database(&config).await?;
1765    if command == "seed" {
1766        require_no_options(options)?;
1767        __PHOENIX_APP_CRATE__::seeders::run(&mut database).await?;
1768        println!("Seeders completed.");
1769        return Ok(());
1770    }
1771
1772    let mut runner = MigrationRunner::new(
1773        &mut database,
1774        __PHOENIX_MIGRATIONS__,
1775    )?;
1776    match command {
1777        "migrate" => {
1778            require_no_options(options)?;
1779            let applied = runner.up().await?;
1780            println!("Applied {applied} migration(s).");
1781        }
1782        "status" => {
1783            require_no_options(options)?;
1784            let plan = runner.plan().await?;
1785            if plan.applied.is_empty() && plan.pending.is_empty() {
1786                println!("No migrations registered or applied.");
1787            }
1788            for migration in plan.applied {
1789                println!(
1790                    "APPLIED  {}  batch={}  {}  {}",
1791                    migration.id, migration.batch, migration.applied_at, migration.name
1792                );
1793            }
1794            for id in plan.pending {
1795                println!("PENDING  {id}");
1796            }
1797        }
1798        "rollback" => {
1799            let steps = parse_rollback_steps(options)?;
1800            let rolled_back = runner.down(steps).await?;
1801            println!("Rolled back {rolled_back} migration(s).");
1802        }
1803        "fresh" => {
1804            let run_seeders = parse_fresh_options(options)?;
1805            let applied = runner.plan().await?.applied.len();
1806            let rolled_back = runner.down(applied).await?;
1807            let migrated = runner.up().await?;
1808            println!(
1809                "Rebuilt the database: rolled back {rolled_back}, applied {migrated} migration(s)."
1810            );
1811            drop(runner);
1812            if run_seeders {
1813                __PHOENIX_APP_CRATE__::seeders::run(&mut database).await?;
1814                println!("Seeders completed.");
1815            }
1816        }
1817        "seed" => unreachable!("seed is handled before creating the migration runner"),
1818        _ => unreachable!("management commands are validated before connecting"),
1819    }
1820    Ok(())
1821}
1822
1823#[cfg(feature = "database")]
1824fn require_no_options(options: &[String]) -> CommandResult {
1825    if options.is_empty() {
1826        Ok(())
1827    } else {
1828        Err(input_error(format!("unexpected arguments: {}", options.join(" "))).into())
1829    }
1830}
1831
1832#[cfg(feature = "database")]
1833fn parse_rollback_steps(options: &[String]) -> CommandResult<usize> {
1834    let [steps] = options else {
1835        return Err(input_error("rollback expects one positive step count").into());
1836    };
1837    steps
1838        .parse::<usize>()
1839        .ok()
1840        .filter(|steps| *steps > 0)
1841        .ok_or_else(|| input_error("rollback step count must be a positive integer").into())
1842}
1843
1844#[cfg(feature = "database")]
1845fn parse_fresh_options(options: &[String]) -> CommandResult<bool> {
1846    match options {
1847        [] => Ok(false),
1848        [option] if option == "--seed" => Ok(true),
1849        _ => Err(input_error("fresh only accepts --seed").into()),
1850    }
1851}
1852
1853#[cfg(feature = "database")]
1854fn input_error(message: impl Into<String>) -> io::Error {
1855    io::Error::new(io::ErrorKind::InvalidInput, message.into())
1856}
1857"#
1858    .replace("__PHOENIX_MIGRATIONS__", migrations_expr)
1859    .replace("__PHOENIX_APP_CRATE__", crate_name)
1860}
1861
1862fn seeder_template() -> String {
1863    format!(
1864        r"use std::error::Error;
1865
1866use phoenix::database::Database;
1867
1868{MODULES_START}
1869{MODULES_END}
1870
1871/// Insert repeatable development or test data.
1872///
1873/// Factories generated by `px make:model --factory` land in this directory and
1874/// are registered above. They compile only with the `factory` feature, so none
1875/// of this reaches a release build.
1876///
1877/// # Errors
1878///
1879/// Returns the first application or database error raised by a seeder.
1880pub async fn run(_database: &mut Database) -> Result<(), Box<dyn Error>> {{
1881    Ok(())
1882}}
1883"
1884    )
1885}
1886
1887fn empty_model_registry() -> String {
1888    format!(
1889        "{MODULES_START}\n{MODULES_END}\n\n{MODELS_START}\n{}\n{MODELS_END}\n",
1890        render_model_registry(&BTreeSet::new()).join("\n")
1891    )
1892}
1893
1894fn empty_migration_registry() -> String {
1895    format!(
1896        "{MIGRATIONS_START}\n{}\n{MIGRATIONS_END}\n",
1897        render_migration_registry(&BTreeSet::new()).join("\n")
1898    )
1899}
1900
1901fn project_readme(package: &str, options: &NewProjectOptions) -> String {
1902    let mode = match options.render_mode {
1903        ProjectRenderMode::Spa => "SPA",
1904        ProjectRenderMode::Ssr => "SSR",
1905        ProjectRenderMode::Islands => "Islands",
1906    };
1907    let database = options.database.map_or_else(
1908        || "This project has no database dependency. Create one with `px new --database sqlite|pgsql|mysql`.".to_owned(),
1909        |database| format!("Selected driver: `{}` (`DATABASE_URL` in `.env`). Use `px migrate` and `px status` for migrations.", database.cargo_feature()),
1910    );
1911    let tailwind = if options.tailwind {
1912        "Tailwind CSS v4 is enabled through `@tailwindcss/vite`."
1913    } else {
1914        "Tailwind CSS is not enabled; add it at creation time with `px new --tailwind`."
1915    };
1916    let features = if options.features.is_empty() {
1917        String::new()
1918    } else {
1919        use std::fmt::Write as _;
1920
1921        let mut list = String::new();
1922        for feature in &options.features {
1923            let _ = writeln!(
1924                list,
1925                "- `{key}` — {summary}(配置:`config/{key}.toml`)",
1926                key = feature.key(),
1927                summary = feature.summary(),
1928            );
1929        }
1930        format!(
1931            "\n## 已启用 Feature\n\n{list}\n装配代码在 `src/lib.rs` 的 `features()`;密钥放 `.env`,非敏感参数放 `config/*.toml`。\n\n> 注意:crates.io 上已发布的 `phoenixrs` 尚未包含 `captcha` / `pay` / `notify`\n> feature(需要 > {PHOENIXRS_VERSION} 的后续版本)。在其发布前请使用\n> `px new --framework-path <Phoenix-rs 检出>` 的本地依赖模式。\n"
1932        )
1933    };
1934    format!(
1935        "# {package}\n\nPhoenix Rust + React application.\n\n## Start\n\n```bash\ncp .env.example .env\npx dev\n```\n\n`px dev` builds the browser and renderer bundles before it starts the app, then rebuilds them whenever Rust or React source changes. The development document therefore uses the same Vite assets and renderer contract as `npm run build`.\n\n运行时配置(地址 / 数据库 / 日志 / 限流)都在 `.env`;`config/` 目录只存放 Feature 的 TOML 配置。\n\n## Rendering mode\n\nThis application starts in **{mode}** mode. Change only the page chain in `app/controllers/home_controller.rs`:\n\n```rust\n.spa()       // SPA\n.ssr()       // SSR\n.islands()   // Islands\n```\n\nThe controller, routes, renderer and build pipeline stay unchanged.\n\n首页链接了三种渲染模式的最小演示页:`/demo/spa`、`/demo/ssr`、`/demo/islands`\n(`views/pages/demo/` 与 `HomeController`,确认理解后即可删除)。\n\n## Optional integrations\n\n- {database}\n- {tailwind}\n{features}\n## Release\n\n```bash\npx release --version 0.1.0 --tarball\n```\n\n`px release:install` / `px release:rollback` 可在切换版本后执行 `deploy/restart.sh`\n(或 `--restart-cmd`);需要自动重启时创建该脚本并 `chmod +x`。\n"
1936    )
1937}
1938
1939fn main_template(crate_name: &str) -> String {
1940    format!(
1941        r#"use phoenix::prelude::{{CommandResult, Console, LogFormat, Logging}};
1942
1943use {crate_name}::commands;
1944
1945#[tokio::main]
1946async fn main() -> CommandResult {{
1947    Console::new(env!("CARGO_PKG_NAME"))
1948        .about("Phoenix application")
1949        .serve(|_ctx| async move {{
1950            let config = {crate_name}::config::load()?;
1951            let address = config.address().to_owned();
1952            let public_url = config.public_url().to_owned();
1953            let production = config.environment().is_production();
1954            let _logging = Logging::new()
1955                .format(if production {{ LogFormat::Json }} else {{ LogFormat::Compact }})
1956                .ansi(!production)
1957                .init()?;
1958            let server = {crate_name}::application(config).await?.bind(&address).await?;
1959            println!(
1960                "Phoenix application ready at {{public_url}} (listening on {{}})",
1961                server.local_addr()
1962            );
1963            server
1964                .run_with_shutdown(async {{
1965                    let _ = tokio::signal::ctrl_c().await;
1966                }})
1967                .await?;
1968            Ok(())
1969        }})
1970        .commands(commands::registry())
1971        .run()
1972        .await
1973}}
1974"#
1975    )
1976}
1977
1978// The body is one template literal; the line count is the generated file.
1979#[allow(clippy::too_many_lines)]
1980fn lib_template(database: bool, features: &[ProjectFeature]) -> String {
1981    if !features.is_empty() {
1982        return lib_template_with_features(database, features);
1983    }
1984    r#"#[path = "../config/mod.rs"]
1985pub mod config;
1986#[path = "../app/commands/mod.rs"]
1987pub mod commands;
1988#[path = "../app/controllers/mod.rs"]
1989pub mod controllers;
1990#[path = "../app/middleware/mod.rs"]
1991pub mod middleware;
1992#[cfg(feature = "database")]
1993#[path = "../app/models/mod.rs"]
1994pub mod models;
1995#[path = "../app/props/mod.rs"]
1996pub mod props;
1997#[path = "../app/requests/mod.rs"]
1998pub mod requests;
1999#[path = "../app/resources/mod.rs"]
2000pub mod resources;
2001#[cfg(feature = "database")]
2002#[path = "../database/migrations/mod.rs"]
2003pub mod migrations;
2004#[cfg(feature = "database")]
2005#[path = "../database/seeders/mod.rs"]
2006pub mod seeders;
2007
2008use phoenix::prelude::{
2009    AccessLog, Application, AssetManifest, Csrf, HostAllowlist, NodeRenderer,
2010    NonceSecurityPolicy, RateLimit, RateLimitConfig, RendererConfig, RendererManifest, RequestId, Routes, ServeProductionAssets, SessionConfig, SessionMiddleware,
2011    SessionStore, StateMiddleware, TrustedProxies,
2012};
2013#[cfg(feature = "database")]
2014use phoenix::prelude::{Database, DatabaseError};
2015
2016use config::AppConfig;
2017
2018#[must_use]
2019#[allow(clippy::duplicate_mod)]
2020pub fn routes(
2021    config: &AppConfig,
2022    assets: Option<&AssetManifest>,
2023    renderer: &NodeRenderer,
2024) -> Routes {
2025    let session_config = SessionConfig {
2026        secure: config.public_url().starts_with("https://"),
2027        ..SessionConfig::default()
2028    };
2029    let session_store = SessionStore::memory(session_config.max_age);
2030
2031    let mut routes = phoenix::mount_routes!()
2032        .with_middleware(TrustedProxies::new(config.trusted_proxies().iter().copied()))
2033        .with_middleware(RequestId)
2034        .with_middleware(AccessLog);
2035    if let Some(assets) = assets.cloned() {
2036        // Serve hashed Vite assets before session/CSRF so static GETs stay cheap.
2037        routes = routes.with_middleware(ServeProductionAssets::new(assets, "public/assets"));
2038    }
2039    routes
2040        .with_middleware(HostAllowlist::new(config.allowed_hosts().iter().cloned()))
2041        .with_middleware(RateLimit::new(RateLimitConfig {
2042            requests: config.rate_limit_requests(),
2043            window: config.rate_limit_window(),
2044        }))
2045        .with_middleware(content_security_policy(config))
2046        .with_middleware(SessionMiddleware::new(session_store, session_config))
2047        .with_middleware(Csrf)
2048        .with_middleware(StateMiddleware::new(config.clone()))
2049        .with_middleware(StateMiddleware::new(assets.cloned()))
2050        .with_middleware(StateMiddleware::new(renderer.clone()))
2051}
2052
2053fn content_security_policy(config: &AppConfig) -> NonceSecurityPolicy {
2054    if !config.environment().is_production() {
2055        return NonceSecurityPolicy::development(
2056            config
2057                .vite_dev_url()
2058                .expect("development configuration always has a Vite origin"),
2059        )
2060        .expect("AppConfig validates VITE_DEV_URL as one trusted HTTP(S) origin");
2061    }
2062    NonceSecurityPolicy::default()
2063}
2064
2065/// Build the Phoenix application.
2066///
2067/// # Errors
2068///
2069/// Returns a route error when route names or patterns conflict.
2070pub async fn application(
2071    config: AppConfig,
2072) -> Result<Application, Box<dyn std::error::Error + Send + Sync>> {
2073    let vite_dev_server = std::env::var_os("PHOENIX_VITE_DEV").is_some();
2074    let (assets, renderer) = if !vite_dev_server {
2075        let assets = AssetManifest::load("public/assets/phoenix-manifest.json")?;
2076        let renderer_manifest = RendererManifest::load("public/ssr/phoenix-renderer.json")?;
2077        let renderer = NodeRenderer::new(
2078            RendererConfig::production(&assets, &renderer_manifest, "public/ssr")?,
2079        );
2080        (Some(assets), renderer)
2081    } else {
2082        // `px dev` sets PHOENIX_VITE_DEV so JS comes from Vite HMR.
2083        // Still load the hashed CSS manifest so Islands SSR can link stylesheets
2084        // in <head> before the Vite client runs — otherwise hard refresh FOUCs.
2085        let assets = AssetManifest::load("public/assets/phoenix-manifest.json").ok();
2086        (
2087            assets,
2088            NodeRenderer::new(RendererConfig::node("public/ssr/renderer.js")),
2089        )
2090    };
2091    renderer.warm_up().await?;
2092    let built = routes(&config, assets.as_ref(), &renderer);
2093    // Connect the database once at startup and share it with every handler via
2094    // request state (`State<Database>` / `extensions().get::<Database>()`).
2095    #[cfg(feature = "database")]
2096    let built = built.with_middleware(StateMiddleware::new(database(&config).await?));
2097    Ok(Application::new(built)?)
2098}
2099
2100/// Connect the configured database with every registered Toasty model.
2101///
2102/// # Errors
2103///
2104/// Returns a database error when the URL or connection is invalid.
2105#[cfg(feature = "database")]
2106pub async fn database(config: &AppConfig) -> Result<Database, DatabaseError> {
2107    Database::builder(models::all())
2108        .connect(config.database_url())
2109        .await
2110}
2111"#
2112    .to_owned()
2113}
2114
2115/// `src/lib.rs` variant that assembles the official Features selected by
2116/// `px new --feature ...` (docs/FEATURES.md).
2117// The body is one template literal; the line count is the generated file.
2118#[allow(clippy::too_many_lines)]
2119fn lib_template_with_features(_database: bool, features: &[ProjectFeature]) -> String {
2120    let captcha = features.contains(&ProjectFeature::Captcha);
2121    let pay = features.contains(&ProjectFeature::Pay);
2122    let notify = features.contains(&ProjectFeature::Notify);
2123
2124    let arc_import = if pay || notify {
2125        "\nuse std::sync::Arc;\n"
2126    } else {
2127        ""
2128    };
2129
2130    let mut plugin_lines = String::new();
2131    if captcha {
2132        plugin_lines.push_str(
2133            "    // 图形验证码:注册 GET /captcha(路由名 captcha.image),依赖 Session。\n    // 自定义样式用 CaptchaFeature::with_config(...)(参数见 config/captcha.toml),\n    // 登录表单接入见 docs/CAPTCHA.md(CaptchaProtected 提取器)。\n    let features = features.plugin(phoenix::captcha::CaptchaFeature::new())?;\n",
2134        );
2135    }
2136    if pay {
2137        plugin_lines.push_str(
2138            "    // 聚合支付:注册回调路由(pay.notify.*)与 payments 迁移。docs/PAYMENTS.md。\n    let features = features.plugin(phoenix::pay::PayFeature::new(pay_manager()?))?;\n",
2139        );
2140    }
2141    if notify {
2142        plugin_lines.push_str(
2143            "    // 通知:注册 notifications 迁移;发送入口见下方 notifier()。docs/NOTIFICATIONS.md。\n    let features = features.plugin(phoenix::notify::NotifyFeature::new())?;\n",
2144        );
2145    }
2146
2147    let mut helper_fns = String::new();
2148    if pay {
2149        helper_fns.push_str(
2150            r#"
2151/// 从 `config/pay.toml` 装配支付渠道;文件缺省时仅启用 Mock(本地即可闭环)。
2152///
2153/// 密钥经 `.env` 注入(`${VAR}` 占位符),非敏感参数留在 TOML。
2154fn pay_manager() -> Result<
2155    Arc<phoenix::pay::PayManager>,
2156    Box<dyn std::error::Error + Send + Sync>,
2157> {
2158    use phoenix::pay::{AlipayF2FProvider, MockProvider, PayManager, WechatNativeProvider};
2159
2160    #[derive(Default, serde::Deserialize)]
2161    struct PayFileConfig {
2162        wechat_native: Option<phoenix::pay::WechatNativeConfig>,
2163        alipay_f2f: Option<phoenix::pay::AlipayF2FConfig>,
2164    }
2165
2166    let file: PayFileConfig = phoenix::config::load_feature_config("pay")?;
2167    let mut builder = PayManager::builder().provider(Arc::new(MockProvider::new()));
2168    if let Some(wechat) = file.wechat_native {
2169        builder = builder.provider(Arc::new(WechatNativeProvider::new(wechat)));
2170    }
2171    if let Some(alipay) = file.alipay_f2f {
2172        builder = builder.provider(Arc::new(AlipayF2FProvider::new(alipay)));
2173    }
2174    Ok(Arc::new(builder.build()))
2175}
2176"#,
2177        );
2178    }
2179    if notify {
2180        helper_fns.push_str(
2181            r"
2182/// 通知发送器:本地为内存邮件传输 + 内存存储,重启即清空。
2183/// 上线前替换为真实 MailTransport 与数据库 store(docs/NOTIFICATIONS.md)。
2184#[must_use]
2185pub fn notifier() -> phoenix::notify::Notifier {
2186    let (mailer, _outbox) = phoenix::mail::Mailer::memory();
2187    phoenix::notify::Notifier::new()
2188        .with_mailer(mailer)
2189        .with_store(Arc::new(phoenix::notify::MemoryNotificationStore::new()))
2190}
2191",
2192        );
2193    }
2194
2195    format!(
2196        r#"#[path = "../config/mod.rs"]
2197pub mod config;
2198#[path = "../app/commands/mod.rs"]
2199pub mod commands;
2200#[path = "../app/controllers/mod.rs"]
2201pub mod controllers;
2202#[path = "../app/middleware/mod.rs"]
2203pub mod middleware;
2204#[cfg(feature = "database")]
2205#[path = "../app/models/mod.rs"]
2206pub mod models;
2207#[path = "../app/props/mod.rs"]
2208pub mod props;
2209#[path = "../app/requests/mod.rs"]
2210pub mod requests;
2211#[path = "../app/resources/mod.rs"]
2212pub mod resources;
2213#[cfg(feature = "database")]
2214#[path = "../database/migrations/mod.rs"]
2215pub mod migrations;
2216#[cfg(feature = "database")]
2217#[path = "../database/seeders/mod.rs"]
2218pub mod seeders;
2219{arc_import}
2220use phoenix::plugin::FeatureSet;
2221use phoenix::prelude::{{
2222    AccessLog, Application, AssetManifest, Csrf, HostAllowlist, NodeRenderer,
2223    NonceSecurityPolicy, RateLimit, RateLimitConfig, RendererConfig, RendererManifest, RequestId, RouteGroup, Routes, ServeProductionAssets, SessionConfig, SessionMiddleware,
2224    SessionStore, StateMiddleware, TrustedProxies,
2225}};
2226#[cfg(feature = "database")]
2227use phoenix::prelude::{{Database, DatabaseError}};
2228
2229use config::AppConfig;
2230
2231/// `px new --feature` 选中的官方 Feature 装配(docs/FEATURES.md)。
2232///
2233/// # Errors
2234///
2235/// 返回 Feature 安装冲突(名称 / 能力 / 迁移 ID 重复)或 Feature 配置错误。
2236pub fn features() -> Result<FeatureSet, Box<dyn std::error::Error + Send + Sync>> {{
2237    let features = FeatureSet::new();
2238{plugin_lines}    Ok(features)
2239}}
2240{helper_fns}
2241/// # Errors
2242///
2243/// 返回路由冲突或 Feature 装配错误。
2244#[allow(clippy::duplicate_mod)]
2245pub fn routes(
2246    config: &AppConfig,
2247    assets: Option<&AssetManifest>,
2248    renderer: &NodeRenderer,
2249) -> Result<Routes, Box<dyn std::error::Error + Send + Sync>> {{
2250    let session_config = SessionConfig {{
2251        secure: config.public_url().starts_with("https://"),
2252        ..SessionConfig::default()
2253    }};
2254    let session_store = SessionStore::memory(session_config.max_age);
2255
2256    let mut routes = phoenix::mount_routes!()
2257        // 业务路由启用 CSRF;Feature 路由不在此列——支付回调等由平台服务器
2258        // 调用,真实性靠验签(docs/PAYMENTS.md),挂 CSRF 会拒掉合法通知。
2259        .scoped(RouteGroup::new().middleware(Csrf))
2260        .merge(features()?.into_routes())
2261        .with_middleware(TrustedProxies::new(config.trusted_proxies().iter().copied()))
2262        .with_middleware(RequestId)
2263        .with_middleware(AccessLog);
2264    if let Some(assets) = assets.cloned() {{
2265        // Serve hashed Vite assets before session/CSRF so static GETs stay cheap.
2266        routes = routes.with_middleware(ServeProductionAssets::new(assets, "public/assets"));
2267    }}
2268    Ok(routes
2269        .with_middleware(HostAllowlist::new(config.allowed_hosts().iter().cloned()))
2270        .with_middleware(RateLimit::new(RateLimitConfig {{
2271            requests: config.rate_limit_requests(),
2272            window: config.rate_limit_window(),
2273        }}))
2274        .with_middleware(content_security_policy(config))
2275        // 会话全局挂载:验证码等 Feature 路由依赖 Session。
2276        .with_middleware(SessionMiddleware::new(session_store, session_config))
2277        .with_middleware(StateMiddleware::new(config.clone()))
2278        .with_middleware(StateMiddleware::new(assets.cloned()))
2279        .with_middleware(StateMiddleware::new(renderer.clone())))
2280}}
2281
2282fn content_security_policy(config: &AppConfig) -> NonceSecurityPolicy {{
2283    if !config.environment().is_production() {{
2284        return NonceSecurityPolicy::development(
2285            config
2286                .vite_dev_url()
2287                .expect("development configuration always has a Vite origin"),
2288        )
2289        .expect("AppConfig validates VITE_DEV_URL as one trusted HTTP(S) origin");
2290    }}
2291    NonceSecurityPolicy::default()
2292}}
2293
2294/// Build the Phoenix application.
2295///
2296/// # Errors
2297///
2298/// Returns a route error when route names or patterns conflict.
2299pub async fn application(
2300    config: AppConfig,
2301) -> Result<Application, Box<dyn std::error::Error + Send + Sync>> {{
2302    let vite_dev_server = std::env::var_os("PHOENIX_VITE_DEV").is_some();
2303    let (assets, renderer) = if !vite_dev_server {{
2304        let assets = AssetManifest::load("public/assets/phoenix-manifest.json")?;
2305        let renderer_manifest = RendererManifest::load("public/ssr/phoenix-renderer.json")?;
2306        let renderer = NodeRenderer::new(
2307            RendererConfig::production(&assets, &renderer_manifest, "public/ssr")?,
2308        );
2309        (Some(assets), renderer)
2310    }} else {{
2311        // `px dev` sets PHOENIX_VITE_DEV so JS comes from Vite HMR.
2312        // Still load the hashed CSS manifest so Islands SSR can link stylesheets
2313        // in <head> before the Vite client runs — otherwise hard refresh FOUCs.
2314        let assets = AssetManifest::load("public/assets/phoenix-manifest.json").ok();
2315        (
2316            assets,
2317            NodeRenderer::new(RendererConfig::node("public/ssr/renderer.js")),
2318        )
2319    }};
2320    renderer.warm_up().await?;
2321    let built = routes(&config, assets.as_ref(), &renderer)?;
2322    // Connect the database once at startup and share it with every handler via
2323    // request state (`State<Database>` / `extensions().get::<Database>()`).
2324    #[cfg(feature = "database")]
2325    let built = built.with_middleware(StateMiddleware::new(database(&config).await?));
2326    Ok(Application::new(built)?)
2327}}
2328
2329/// Connect the configured database with every registered Toasty model.
2330///
2331/// # Errors
2332///
2333/// Returns a database error when the URL or connection is invalid.
2334#[cfg(feature = "database")]
2335pub async fn database(config: &AppConfig) -> Result<Database, DatabaseError> {{
2336    Database::builder(models::all())
2337        .connect(config.database_url())
2338        .await
2339}}
2340"#
2341    )
2342}
2343
2344fn commands_mod_template() -> String {
2345    format!(
2346        "use phoenix::prelude::commands;\n\n{MODULES_START}\n{MODULES_END}\n\ncommands! {{\n{COMMANDS_START}\n{COMMANDS_END}\n}}\n"
2347    )
2348}
2349
2350fn command_template(function_name: &str) -> String {
2351    format!(
2352        r#"use phoenix::prelude::{{CommandContext, CommandResult}};
2353
2354/// Application console command.
2355#[allow(clippy::unused_async)]
2356pub async fn {function_name}(_ctx: CommandContext<'_>) -> CommandResult {{
2357    println!("{function_name} ran.");
2358    Ok(())
2359}}
2360"#
2361    )
2362}
2363
2364// The body is one template literal; the line count is the generated file.
2365#[allow(clippy::too_many_lines)]
2366fn home_controller_template(render_mode: ProjectRenderMode) -> String {
2367    format!(
2368        r#"use std::time::{{SystemTime, UNIX_EPOCH}};
2369
2370use phoenix::prelude::{{AssetManifest, NodeRenderer, Page, Request, Response, StatusCode}};
2371
2372use crate::config::AppConfig;
2373use crate::props::{{DemoSsrProps, HomeProps}};
2374
2375pub struct HomeController;
2376
2377impl HomeController {{
2378    /// 首页;渲染模式由 `px new` 的选择决定(当前 `{render_mode}`)。
2379    pub async fn index(request: Request) -> Response {{
2380        let page = Page::new(
2381            "home",
2382            HomeProps {{
2383                title: "Phoenix is ready".to_owned(),
2384                description: "Rust owns the application contract; React renders the page.".to_owned(),
2385            }},
2386        )
2387        {render_mode};
2388        render(&request, page).await
2389    }}
2390
2391    /// SPA 演示:整页交给浏览器 React 渲染,任意组件可直接交互。
2392    pub async fn demo_spa(request: Request) -> Response {{
2393        render(&request, Page::new("demo/spa", serde_json::json!({{}})).spa()).await
2394    }}
2395
2396    /// SSR 演示:服务端先渲染完整 HTML,首屏即含数据(查看网页源代码可见)。
2397    pub async fn demo_ssr(request: Request) -> Response {{
2398        let rendered_at = SystemTime::now()
2399            .duration_since(UNIX_EPOCH)
2400            .map_or_else(|_| "epoch".to_owned(), |at| at.as_secs().to_string());
2401        render(&request, Page::new("demo/ssr", DemoSsrProps {{ rendered_at }}).ssr()).await
2402    }}
2403
2404    /// Islands 演示:静态 HTML 中只有标记 `client:load` 的岛屿被水合。
2405    pub async fn demo_islands(request: Request) -> Response {{
2406        render(&request, Page::new("demo/islands", serde_json::json!({{}})).islands()).await
2407    }}
2408}}
2409
2410/// 注入 Vite 资源并交给 Node renderer 输出(三种渲染模式共用)。
2411async fn render(request: &Request, mut page: Page) -> Response {{
2412    let renderer = request.extensions().get::<NodeRenderer>().cloned();
2413    let assets = request
2414        .extensions()
2415        .get::<Option<AssetManifest>>()
2416        .and_then(Option::as_ref);
2417    let vite_dev_url = request
2418        .extensions()
2419        .get::<AppConfig>()
2420        .and_then(AppConfig::vite_dev_url);
2421    if let Some(assets) = assets {{
2422        page = match page.production_assets(assets, "client") {{
2423            Ok(page) => page,
2424            Err(error) => {{
2425                return Response::text(format!("asset manifest error: {{error}}"))
2426                    .with_status(StatusCode::INTERNAL_SERVER_ERROR);
2427            }}
2428        }};
2429    }}
2430    // Only `px dev` (PHOENIX_VITE_DEV) may override the browser entry with Vite.
2431    // Packaged binaries must keep hashed assets even when APP_ENV=development /
2432    // VITE_DEV_URL is set — otherwise HTML leaks the Vite origin.
2433    if std::env::var_os("PHOENIX_VITE_DEV").is_some()
2434        && let Some(vite_dev_url) = vite_dev_url
2435    {{
2436        page = page.script_src(format!(
2437            "{{}}/@id/__x00__virtual:phoenix/client",
2438            vite_dev_url.trim_end_matches('/'),
2439        ));
2440    }}
2441    match renderer {{
2442        Some(renderer) => page.respond_with_renderer(request, &renderer).await,
2443        None => Response::text("Phoenix renderer is unavailable")
2444            .with_status(StatusCode::INTERNAL_SERVER_ERROR),
2445    }}
2446}}
2447"#,
2448        render_mode = render_mode.page_builder(),
2449    )
2450}
2451
2452fn home_props_template() -> String {
2453    r#"use serde::Serialize;
2454
2455#[phoenix::contract(page, page = "home")]
2456#[derive(Serialize)]
2457pub struct HomeProps {
2458    pub title: String,
2459    pub description: String,
2460}
2461"#
2462    .to_owned()
2463}
2464
2465fn demo_ssr_props_template() -> String {
2466    r#"use serde::Serialize;
2467
2468/// SSR 演示页数据:由服务端注入,首屏 HTML 即包含(`views/pages/demo/ssr`)。
2469#[phoenix::contract(page, page = "demo/ssr")]
2470#[derive(Serialize)]
2471#[serde(rename_all = "camelCase")]
2472pub struct DemoSsrProps {
2473    pub rendered_at: String,
2474}
2475"#
2476    .to_owned()
2477}
2478
2479fn home_route_template() -> String {
2480    r#"use phoenix::prelude::Routes;
2481
2482use crate::controllers::HomeController;
2483
2484#[must_use]
2485pub fn routes() -> Routes {
2486    Routes::new()
2487        .get("/", HomeController::index)
2488        .name("home")
2489        // 三种渲染模式的最小演示页(确认理解后可整组删除)。
2490        .get("/demo/spa", HomeController::demo_spa)
2491        .name("demo.spa")
2492        .get("/demo/ssr", HomeController::demo_ssr)
2493        .name("demo.ssr")
2494        .get("/demo/islands", HomeController::demo_islands)
2495        .name("demo.islands")
2496}
2497"#
2498    .to_owned()
2499}
2500
2501const HOME_PAGE_BODY: &str = r#"  return (
2502    <main className="welcome">
2503      <p className="eyebrow">PHOENIX / RUST + REACT</p>
2504      <h1>{title}</h1>
2505      <p>{description}</p>
2506      {/* 同一套控制器 / 路由下的三种渲染模式,每页一个最小演示。 */}
2507      <ul className="demo-links">
2508        <li>
2509          <Link href={demo.spa()}>SPA</Link> — 整页浏览器渲染,交互最自由
2510        </li>
2511        <li>
2512          <Link href={demo.ssr()}>SSR</Link> — 服务端渲染完整 HTML,首屏即含数据
2513        </li>
2514        <li>
2515          <Link href={demo.islands()}>Islands</Link> — 静态页里只水合少量交互岛
2516        </li>
2517      </ul>
2518      <code>px make:model Post --all</code>
2519    </main>
2520  );
2521}
2522"#;
2523
2524fn home_page_template(frontend: ProjectFrontend) -> String {
2525    let (imports, signature) = match frontend {
2526        ProjectFrontend::Tsx => (
2527            concat!(
2528                "import { Link } from \"@apizero/react\";\n",
2529                "import type { HomeProps } from \"../generated/contracts.js\";\n",
2530                "import { demo } from \"../generated/routes.js\";",
2531            ),
2532            "export default function Home({ title, description }: HomeProps) {",
2533        ),
2534        ProjectFrontend::Jsx => (
2535            concat!(
2536                "import { Link } from \"@apizero/react\";\n",
2537                "import { demo } from \"../generated/routes.js\";",
2538            ),
2539            "export default function Home({ title, description }) {",
2540        ),
2541    };
2542    format!("{imports}\n\n{signature}\n{HOME_PAGE_BODY}")
2543}
2544
2545/// SPA 演示页:整页 hydrate,`useState` 计数器即时生效(TSX/JSX 同文)。
2546fn demo_spa_page_template() -> String {
2547    r#"import { useState } from "react";
2548import { Link } from "@apizero/react";
2549import { home } from "../../generated/routes.js";
2550
2551// SPA:整页都在浏览器渲染——查看网页源代码只有挂载点,没有正文。
2552export default function DemoSpa() {
2553  const [count, setCount] = useState(0);
2554  return (
2555    <main className="welcome">
2556      <p className="eyebrow">DEMO / SPA</p>
2557      <h1>SPA 模式</h1>
2558      <p>本页任何组件都可以直接使用浏览器状态与事件。</p>
2559      <button type="button" onClick={() => setCount((value) => value + 1)}>
2560        点击了 {count} 次
2561      </button>
2562      <p>
2563        <Link href={home()}>← 返回首页</Link>
2564      </p>
2565    </main>
2566  );
2567}
2568"#
2569    .to_owned()
2570}
2571
2572fn demo_ssr_page_template(frontend: ProjectFrontend) -> String {
2573    let (imports, signature) = match frontend {
2574        ProjectFrontend::Tsx => (
2575            concat!(
2576                "import { Link } from \"@apizero/react\";\n",
2577                "import type { DemoSsrProps } from \"../../generated/contracts.js\";\n",
2578                "import { home } from \"../../generated/routes.js\";",
2579            ),
2580            "export default function DemoSsr({ renderedAt }: DemoSsrProps) {",
2581        ),
2582        ProjectFrontend::Jsx => (
2583            concat!(
2584                "import { Link } from \"@apizero/react\";\n",
2585                "import { home } from \"../../generated/routes.js\";",
2586            ),
2587            "export default function DemoSsr({ renderedAt }) {",
2588        ),
2589    };
2590    // SSR:完整 HTML 在服务端生成后再 hydrate。
2591    format!(
2592        r#"{imports}
2593
2594// SSR:服务端渲染完整 HTML——查看网页源代码能直接看到下面的数据。
2595{signature}
2596  return (
2597    <main className="welcome">
2598      <p className="eyebrow">DEMO / SSR</p>
2599      <h1>SSR 模式</h1>
2600      <p>本页由服务端渲染,Rust 注入的时间戳:{{renderedAt}}。</p>
2601      <p>刷新后时间戳变化;右键「查看网页源代码」可在 HTML 里找到它。</p>
2602      <p>
2603        <Link href={{home()}}>← 返回首页</Link>
2604      </p>
2605    </main>
2606  );
2607}}
2608"#
2609    )
2610}
2611
2612/// Islands 演示页:静态正文 + 一个 `client:load` 岛(TSX/JSX 同文)。
2613fn demo_islands_page_template() -> String {
2614    r#"import { Link } from "@apizero/react";
2615import Counter from "../../islands/counter";
2616import { home } from "../../generated/routes.js";
2617
2618// Islands:页面主体是静态 HTML,只有标记 client:load 的组件会加载浏览器代码。
2619export default function DemoIslands() {
2620  return (
2621    <main className="welcome">
2622      <p className="eyebrow">DEMO / ISLANDS</p>
2623      <h1>Islands 模式</h1>
2624      <p>下面的计数器是本页唯一被水合的交互岛,其余内容零 JS。</p>
2625      <Counter client:load />
2626      <p>
2627        <Link href={home()}>← 返回首页</Link>
2628      </p>
2629    </main>
2630  );
2631}
2632"#
2633    .to_owned()
2634}
2635
2636fn styles_template(tailwind: bool) -> String {
2637    let tailwind = if tailwind {
2638        "@import \"tailwindcss\";\n\n"
2639    } else {
2640        ""
2641    };
2642    format!(
2643        r"{tailwind}:root {{
2644  font-family: Inter, ui-sans-serif, system-ui, sans-serif;
2645  color: #172033;
2646  background: #f5f7fb;
2647}}
2648* {{ box-sizing: border-box; }}
2649body {{ margin: 0; min-width: 320px; min-height: 100vh; }}
2650.welcome {{ width: min(760px, calc(100% - 40px)); margin: 16vh auto 0; }}
2651.eyebrow {{ color: #315bd6; font-size: 12px; font-weight: 800; letter-spacing: 0.14em; }}
2652h1 {{ margin: 12px 0; font-size: clamp(42px, 8vw, 76px); line-height: 0.98; }}
2653.welcome > p:not(.eyebrow) {{ max-width: 640px; color: #5d6879; font-size: 18px; line-height: 1.7; }}
2654code {{ display: inline-block; margin-top: 18px; padding: 12px 14px; border: 1px solid #d7dce5; background: white; }}
2655a {{ color: #315bd6; }}
2656button {{ margin-top: 8px; padding: 10px 16px; border: 1px solid #d7dce5; background: white; font-size: 16px; cursor: pointer; }}
2657.demo-links {{ margin: 18px 0 0; padding-left: 20px; }}
2658.demo-links li {{ margin: 6px 0; color: #5d6879; }}
2659"
2660    )
2661}
2662
2663fn generated_contracts_template() -> String {
2664    r#"// Generated by Phoenix. Vite will refresh this file from Rust contracts.
2665export interface HomeProps {
2666  title: string;
2667  description: string;
2668}
2669export interface DemoSsrProps {
2670  renderedAt: string;
2671}
2672export interface PhoenixPageProps {
2673  home: HomeProps;
2674  "demo/ssr": DemoSsrProps;
2675}
2676export type PhoenixSharedProps = Record<string, never>;
2677export const contractHash = "scaffold" as const;
2678"#
2679    .to_owned()
2680}
2681
2682fn generated_routes_template() -> String {
2683    r#"// Generated by Phoenix. Vite will refresh this file from Rust routes.
2684export const routes = {
2685  home: "home",
2686  demo: { spa: "demo.spa", ssr: "demo.ssr", islands: "demo.islands" },
2687} as const;
2688export type PhoenixRouteName = "home" | "demo.spa" | "demo.ssr" | "demo.islands";
2689export const home = routes.home;
2690export const demo = routes.demo;
2691"#
2692    .to_owned()
2693}
2694
2695fn vite_template(renderer: bool, tailwind: bool) -> String {
2696    let tailwind_import = if tailwind {
2697        "import tailwindcss from \"@tailwindcss/vite\";\n"
2698    } else {
2699        ""
2700    };
2701    let tailwind_plugin = if tailwind { ", tailwindcss()" } else { "" };
2702    format!(
2703        "import {{ defineConfig }} from \"vite\";\nimport {{ phoenix }} from \"@apizero/vite\";\n{tailwind_import}\nexport default defineConfig({{\n  plugins: [phoenix({renderer}){tailwind_plugin}],\n}});\n",
2704        renderer = if renderer { "{ renderer: true }" } else { "" },
2705    )
2706}
2707
2708fn tsconfig_template() -> String {
2709    r#"{
2710  "compilerOptions": {
2711    "target": "ES2022",
2712    "lib": ["ES2022", "DOM", "DOM.Iterable"],
2713    "module": "ESNext",
2714    "moduleResolution": "Bundler",
2715    "jsx": "react-jsx",
2716    "strict": true,
2717    "noEmit": true,
2718    "preserveSymlinks": true,
2719    "skipLibCheck": true,
2720    "types": ["vite/client"]
2721  },
2722  "include": ["views/**/*.js", "views/**/*.jsx", "views/**/*.ts", "views/**/*.tsx", "vite.config.ts", "vite.ssr.config.ts"]
2723}
2724"#
2725    .to_owned()
2726}
2727
2728fn managed_modules(entries: &[&str]) -> String {
2729    let body = entries.join("\n");
2730    if body.is_empty() {
2731        format!("{MODULES_START}\n{MODULES_END}\n")
2732    } else {
2733        format!("{MODULES_START}\n{body}\n{MODULES_END}\n")
2734    }
2735}
2736
2737fn add_rust_item(
2738    editor: &mut ProjectEditor,
2739    base: &str,
2740    name: &QualifiedName,
2741    content: &str,
2742) -> Result<(), ScaffoldError> {
2743    let mut directory = PathBuf::from(base);
2744    let mut parent_module = directory.join("mod.rs");
2745    for namespace in &name.modules {
2746        let module = snake_case(namespace);
2747        editor.update_managed_lines(
2748            &parent_module,
2749            MODULES_START,
2750            MODULES_END,
2751            &[format!("pub mod {module};")],
2752        )?;
2753        directory.push(&module);
2754        parent_module = directory.join("mod.rs");
2755    }
2756    let module = snake_case(&name.class);
2757    editor.create(directory.join(format!("{module}.rs")), content.to_owned())?;
2758    editor.update_managed_lines(
2759        &parent_module,
2760        MODULES_START,
2761        MODULES_END,
2762        &[
2763            format!("pub mod {module};"),
2764            format!("pub use {module}::{};", name.class),
2765        ],
2766    )?;
2767    Ok(())
2768}
2769
2770fn add_command(editor: &mut ProjectEditor, name: &QualifiedName) -> Result<(), ScaffoldError> {
2771    let function_name = snake_case(&name.class);
2772    if matches!(function_name.as_str(), "serve" | "help") {
2773        return Err(ScaffoldError::InvalidName(function_name));
2774    }
2775
2776    let mut directory = PathBuf::from("app/commands");
2777    let mut parent_module = directory.join("mod.rs");
2778    let mut export_path = Vec::new();
2779    for namespace in &name.modules {
2780        let module = snake_case(namespace);
2781        editor.update_managed_lines(
2782            &parent_module,
2783            MODULES_START,
2784            MODULES_END,
2785            &[format!("pub mod {module};")],
2786        )?;
2787        directory.push(&module);
2788        parent_module = directory.join("mod.rs");
2789        export_path.push(module);
2790    }
2791
2792    editor.create(
2793        directory.join(format!("{function_name}.rs")),
2794        command_template(&function_name),
2795    )?;
2796    editor.update_managed_lines(
2797        &parent_module,
2798        MODULES_START,
2799        MODULES_END,
2800        &[
2801            format!("pub mod {function_name};"),
2802            format!("pub use {function_name}::{function_name};"),
2803        ],
2804    )?;
2805
2806    if !export_path.is_empty() {
2807        let path = format!("{}::{function_name}", export_path.join("::"));
2808        editor.update_managed_lines(
2809            "app/commands/mod.rs",
2810            MODULES_START,
2811            MODULES_END,
2812            &[format!("pub use {path};")],
2813        )?;
2814    }
2815
2816    editor.update_managed_lines(
2817        "app/commands/mod.rs",
2818        COMMANDS_START,
2819        COMMANDS_END,
2820        &[format!("{function_name},")],
2821    )?;
2822    Ok(())
2823}
2824
2825/// A factory for `model`, wired to whichever parent it belongs to.
2826///
2827/// Development and test only: the file is compiled behind the `factory`
2828/// feature, so it never reaches a release build.
2829fn factory_template(model: &QualifiedName, relations: &[Relation]) -> String {
2830    let class = &model.class;
2831    let parent = relations
2832        .iter()
2833        .find(|relation| relation.kind == RelationKind::BelongsTo);
2834
2835    let (signature, extra) = parent.map_or_else(
2836        || (String::from("|f|"), String::new()),
2837        |relation| {
2838            let leaf = relation
2839                .target
2840                .rsplit("::")
2841                .next()
2842                .unwrap_or(&relation.target);
2843            let key = format!("{}_id", snake_case(leaf));
2844            (
2845                format!("|f, {key}: i64|"),
2846                format!("\n        .{key}({key})"),
2847            )
2848        },
2849    );
2850    let usage = parent.map_or_else(
2851        || format!("seeder.create::<{class}>(10).await?"),
2852        |relation| {
2853            let leaf = relation
2854                .target
2855                .rsplit("::")
2856                .next()
2857                .unwrap_or(&relation.target);
2858            format!(
2859                "seeder.create_with::<{class}, _>(5, {}.id).await?",
2860                snake_case(leaf)
2861            )
2862        },
2863    );
2864
2865    format!(
2866        r#"//! Generated rows for `{class}`. **Development and test only** — the
2867//! whole file disappears without the `factory` feature.
2868//!
2869//! Seed with: `{usage}`
2870#![cfg(feature = "factory")]
2871
2872use crate::models::{class};
2873
2874phoenix::factory! {{
2875    {class}, {signature} {class}::create()
2876        .name(f.name()){extra},
2877}}
2878"#
2879    )
2880}
2881
2882/// Write a factory and register its module.
2883///
2884/// Not `add_rust_item`: that also re-exports a type named after the file, and a
2885/// factory file declares no type — it only implements a trait for the model.
2886fn add_factory(
2887    editor: &mut ProjectEditor,
2888    model: &QualifiedName,
2889    relations: &[Relation],
2890) -> Result<(), ScaffoldError> {
2891    let module = format!("{}_factory", snake_case(&model.class));
2892    editor.create(
2893        PathBuf::from("database/seeders").join(format!("{module}.rs")),
2894        factory_template(model, relations),
2895    )?;
2896    editor.update_managed_lines(
2897        Path::new("database/seeders/mod.rs"),
2898        MODULES_START,
2899        MODULES_END,
2900        &[format!("pub mod {module};")],
2901    )
2902}
2903
2904fn add_model(
2905    editor: &mut ProjectEditor,
2906    model: &QualifiedName,
2907    relations: &[Relation],
2908) -> Result<(), ScaffoldError> {
2909    add_rust_item(
2910        editor,
2911        "app/models",
2912        model,
2913        &model_template(&model.class, relations),
2914    )?;
2915    let path = if model.modules.is_empty() {
2916        model.class.clone()
2917    } else {
2918        format!(
2919            "{}::{}",
2920            model
2921                .modules
2922                .iter()
2923                .map(|part| snake_case(part))
2924                .collect::<Vec<_>>()
2925                .join("::"),
2926            model.class
2927        )
2928    };
2929    editor.update_registry(
2930        "app/models/mod.rs",
2931        MODELS_START,
2932        MODELS_END,
2933        "model",
2934        &path,
2935        render_model_registry,
2936    )
2937}
2938
2939fn add_model_migration(
2940    editor: &mut ProjectEditor,
2941    model: &QualifiedName,
2942) -> Result<(), ScaffoldError> {
2943    let table = pluralize(&snake_case(&model.class));
2944    add_migration(editor, &format!("create_{table}_table"), &table)
2945}
2946
2947/// Register the `users` table migration generated by `px make:auth`.
2948///
2949/// Idempotent: a `--force` rebuild reuses the existing migration rather than
2950/// stacking a second, duplicate `create_users_table` file.
2951fn add_auth_user_migration(editor: &mut ProjectEditor) -> Result<(), ScaffoldError> {
2952    if editor
2953        .read(Path::new("database/migrations/mod.rs"))?
2954        .contains("create_users_table")
2955    {
2956        return Ok(());
2957    }
2958    let milliseconds = SystemTime::now()
2959        .duration_since(UNIX_EPOCH)
2960        .map_err(|_| ScaffoldError::InvalidClock)?
2961        .as_millis();
2962    let id = milliseconds.to_string();
2963    let module = format!("m_{id}_create_users_table");
2964    editor.create(
2965        format!("database/migrations/{module}.rs"),
2966        auth_user_migration_template(&id),
2967    )?;
2968    editor.update_registry(
2969        "database/migrations/mod.rs",
2970        MIGRATIONS_START,
2971        MIGRATIONS_END,
2972        "migration",
2973        &module,
2974        render_migration_registry,
2975    )
2976}
2977
2978/// Ensure every named feature is present in the project's `[features] default`
2979/// array so a bare `cargo check` compiles the generated slice.
2980fn enable_project_features(
2981    editor: &mut ProjectEditor,
2982    features: &[&str],
2983) -> Result<(), ScaffoldError> {
2984    let relative = PathBuf::from("Cargo.toml");
2985    let manifest = editor.read(&relative)?;
2986    if manifest.is_empty() {
2987        return Err(ScaffoldError::InvalidManagedFile(
2988            editor.root.join(&relative),
2989        ));
2990    }
2991    editor.set(relative, ensure_default_features(&manifest, features))
2992}
2993
2994/// Add `features` to the `default = [...]` array in a Cargo manifest, keeping
2995/// existing entries and order, and leaving the rest of the file untouched.
2996fn ensure_default_features(manifest: &str, features: &[&str]) -> String {
2997    let mut updated = manifest
2998        .lines()
2999        .map(|line| {
3000            let trimmed = line.trim_start();
3001            let is_default = trimmed
3002                .strip_prefix("default")
3003                .is_some_and(|rest| rest.trim_start().starts_with('='));
3004            if is_default
3005                && let Some(open) = line.find('[')
3006                && let Some(close_offset) = line[open..].find(']')
3007            {
3008                let close = open + close_offset;
3009                let mut entries = line[open + 1..close]
3010                    .split(',')
3011                    .map(|entry| entry.trim().trim_matches('"').to_owned())
3012                    .filter(|entry| !entry.is_empty())
3013                    .collect::<Vec<_>>();
3014                for feature in features {
3015                    if !entries.iter().any(|entry| entry == feature) {
3016                        entries.push((*feature).to_owned());
3017                    }
3018                }
3019                let indent = &line[..line.len() - trimmed.len()];
3020                let rendered = entries
3021                    .iter()
3022                    .map(|entry| format!("\"{entry}\""))
3023                    .collect::<Vec<_>>()
3024                    .join(", ");
3025                return format!("{indent}default = [{rendered}]");
3026            }
3027            line.to_owned()
3028        })
3029        .collect::<Vec<_>>()
3030        .join("\n");
3031    if manifest.ends_with('\n') {
3032        updated.push('\n');
3033    }
3034    updated
3035}
3036
3037fn add_migration(editor: &mut ProjectEditor, name: &str, table: &str) -> Result<(), ScaffoldError> {
3038    let milliseconds = SystemTime::now()
3039        .duration_since(UNIX_EPOCH)
3040        .map_err(|_| ScaffoldError::InvalidClock)?
3041        .as_millis();
3042    let id = milliseconds.to_string();
3043    let module = format!("m_{id}_{name}");
3044    editor.create(
3045        format!("database/migrations/{module}.rs"),
3046        migration_template(&id, name, table),
3047    )?;
3048    editor.update_registry(
3049        "database/migrations/mod.rs",
3050        MIGRATIONS_START,
3051        MIGRATIONS_END,
3052        "migration",
3053        &module,
3054        render_migration_registry,
3055    )
3056}
3057
3058fn add_controller_route(
3059    editor: &mut ProjectEditor,
3060    controller: &QualifiedName,
3061    resource: bool,
3062    action: Option<(&QualifiedName, &QualifiedName)>,
3063) -> Result<(), ScaffoldError> {
3064    let base = controller
3065        .class
3066        .strip_suffix("Controller")
3067        .unwrap_or(&controller.class);
3068    let plural = pluralize(&snake_case(base));
3069    let namespace_modules = controller
3070        .modules
3071        .iter()
3072        .map(|part| snake_case(part))
3073        .collect::<Vec<_>>();
3074    let route_file = if namespace_modules.is_empty() {
3075        plural.clone()
3076    } else {
3077        format!("{}_{}", namespace_modules.join("_"), plural)
3078    };
3079    let import = if namespace_modules.is_empty() {
3080        format!("crate::controllers::{}", controller.class)
3081    } else {
3082        format!(
3083            "crate::controllers::{}::{}",
3084            namespace_modules.join("::"),
3085            controller.class
3086        )
3087    };
3088    let route_name = if namespace_modules.is_empty() {
3089        plural.clone()
3090    } else {
3091        format!("{}.{}", namespace_modules.join("."), plural)
3092    };
3093    let path = if namespace_modules.is_empty() {
3094        format!("/{}", plural.replace('_', "-"))
3095    } else {
3096        format!(
3097            "/{}/{}",
3098            namespace_modules
3099                .iter()
3100                .map(|part| kebab_case(part))
3101                .collect::<Vec<_>>()
3102                .join("/"),
3103            plural.replace('_', "-")
3104        )
3105    };
3106    editor.create(
3107        format!("routes/{route_file}.rs"),
3108        controller_route_template(
3109            &import,
3110            &route_name,
3111            &path,
3112            &controller.class,
3113            resource,
3114            action,
3115        ),
3116    )
3117}
3118
3119fn add_page(
3120    editor: &mut ProjectEditor,
3121    page: &PageName,
3122    frontend: ProjectFrontend,
3123) -> Result<(), ScaffoldError> {
3124    let props = page_props_name(page);
3125    add_rust_item(
3126        editor,
3127        "app/props",
3128        &props,
3129        &page_props_template(&props.class, &page.route),
3130    )?;
3131    let mut path = PathBuf::from("views/pages");
3132    for part in &page.parts[..page.parts.len() - 1] {
3133        path.push(kebab_case(part));
3134    }
3135    path.push(format!(
3136        "{}.{}",
3137        kebab_case(page.parts.last().expect("page has one part")),
3138        frontend.extension()
3139    ));
3140    editor.create(
3141        path,
3142        page_template(&page.class, &props.class, page.parts.len(), frontend),
3143    )
3144}
3145
3146fn page_props_name(page: &PageName) -> QualifiedName {
3147    QualifiedName {
3148        modules: page.parts[..page.parts.len() - 1].to_vec(),
3149        class: format!("{}Props", page.class),
3150    }
3151}
3152
3153/// Register the Rust page-props contract and write one auth page component.
3154fn add_auth_page(
3155    editor: &mut ProjectEditor,
3156    name: &str,
3157    content: String,
3158    frontend: ProjectFrontend,
3159) -> Result<(), ScaffoldError> {
3160    let page = PageName::parse(name)?;
3161    let props = page_props_name(&page);
3162    add_rust_item(
3163        editor,
3164        "app/props",
3165        &props,
3166        &page_props_template(&props.class, &page.route),
3167    )?;
3168    let mut path = PathBuf::from("views/pages");
3169    for part in &page.parts[..page.parts.len() - 1] {
3170        path.push(kebab_case(part));
3171    }
3172    path.push(format!(
3173        "{}.{}",
3174        kebab_case(page.parts.last().expect("page has one part")),
3175        frontend.extension()
3176    ));
3177    editor.create(path, content)
3178}
3179
3180/// A model written the short way: conventions filled in by `#[phoenix::model]`,
3181/// relations expressed as one line each.
3182fn model_template(name: &str, relations: &[Relation]) -> String {
3183    use std::fmt::Write as _;
3184
3185    let mut imports = String::from("use phoenix::model;\n");
3186    if !relations.is_empty() {
3187        imports.push_str("use phoenix::database::Deferred;\n\n");
3188        // Related models are reachable through the registry's re-exports, so a
3189        // relation never needs the target's module path spelled out.
3190        let mut targets: Vec<&str> = relations
3191            .iter()
3192            .map(|relation| {
3193                let target = relation.target.as_str();
3194                target.rsplit("::").next().unwrap_or(target)
3195            })
3196            .collect();
3197        targets.sort_unstable();
3198        targets.dedup();
3199        let _ = writeln!(imports, "use crate::models::{{{}}};", targets.join(", "));
3200    }
3201
3202    let mut fields = String::from("    pub name: String,\n");
3203    for relation in relations {
3204        let attribute = relation.kind.attribute();
3205        let target = &relation.target;
3206        let leaf = target.rsplit("::").next().unwrap_or(target);
3207        let field = snake_case(leaf);
3208        let (field, ty) = match relation.kind {
3209            // `#[belongs_to] user: Deferred<User>` — the foreign key and the
3210            // column it maps to are conventions, so neither is written here.
3211            RelationKind::BelongsTo | RelationKind::HasOne => {
3212                (field, format!("Deferred<{target}>"))
3213            }
3214            RelationKind::HasMany => (pluralize(&field), format!("Deferred<Vec<{target}>>")),
3215        };
3216        let _ = write!(fields, "    #[{attribute}]\n    pub {field}: {ty},\n");
3217    }
3218
3219    format!(
3220        "{imports}
3221/// `#[phoenix::model]` fills in the table name, an auto-increment `id`, the
3222/// derives, and every relation's foreign key. Write any of them yourself to
3223/// take that part back.
3224#[model]
3225pub struct {name} {{
3226{fields}}}
3227"
3228    )
3229}
3230
3231/// The persistent `User` model backing `px make:auth`.
3232fn auth_user_model_template() -> String {
3233    r"use phoenix::database::Model;
3234
3235/// Registered account. Passwords are stored only as Argon2id PHC hashes
3236/// (`password_hash`); the plaintext never touches the database.
3237#[derive(Clone, Debug, Model)]
3238pub struct User {
3239    #[key]
3240    #[auto]
3241    pub id: u64,
3242    #[unique]
3243    pub email: String,
3244    pub name: String,
3245    pub password_hash: String,
3246    pub created_at: String,
3247}
3248"
3249    .to_owned()
3250}
3251
3252/// The `users` table migration (portable across sqlite / pgsql / mysql).
3253fn auth_user_migration_template(id: &str) -> String {
3254    format!(
3255        r#"use phoenix::database::Migration;
3256
3257#[must_use]
3258pub fn migration() -> Migration {{
3259    Migration::new("{id}", "create users table")
3260        .up(
3261            "CREATE TABLE users (\
3262             id BIGINT PRIMARY KEY, \
3263             email VARCHAR(255) NOT NULL UNIQUE, \
3264             name VARCHAR(255) NOT NULL, \
3265             password_hash VARCHAR(255) NOT NULL, \
3266             created_at VARCHAR(64) NOT NULL)",
3267        )
3268        .down("DROP TABLE users")
3269}}
3270"#
3271    )
3272}
3273
3274fn request_template(name: &str) -> String {
3275    format!(
3276        r#"use phoenix::prelude::{{Validate, ValidationErrors, Validator, max_length, required, rules, string}};
3277use serde::Deserialize;
3278
3279#[phoenix::contract(input)]
3280#[derive(Debug, Deserialize)]
3281pub struct {name} {{
3282    pub name: String,
3283}}
3284
3285impl Validate for {name} {{
3286    fn validate(&self) -> Result<(), ValidationErrors> {{
3287        let data = serde_json::json!({{ "name": self.name }});
3288        Validator::new(&data)
3289            .field("name", rules![required(), string(), max_length(255)])
3290            .validate()
3291    }}
3292}}
3293"#
3294    )
3295}
3296
3297fn resource_template(name: &str) -> String {
3298    format!(
3299        r#"use serde::Serialize;
3300
3301#[phoenix::contract(resource)]
3302#[derive(Clone, Debug, Serialize)]
3303#[serde(rename_all = "camelCase")]
3304pub struct {name} {{
3305    pub id: String,
3306    pub name: String,
3307}}
3308"#
3309    )
3310}
3311
3312fn controller_template(name: &str, resource: bool) -> String {
3313    if !resource {
3314        return format!(
3315            r#"use phoenix::prelude::{{Request, Response}};
3316
3317pub struct {name};
3318
3319impl {name} {{
3320    #[allow(clippy::unused_async)]
3321    pub async fn index(_request: Request) -> Response {{
3322        Response::text("{name}@index")
3323    }}
3324}}
3325"#
3326        );
3327    }
3328    format!(
3329        r#"use phoenix::prelude::{{Request, Response, StatusCode}};
3330
3331pub struct {name};
3332
3333impl {name} {{
3334    #[allow(clippy::unused_async)]
3335    pub async fn index(_request: Request) -> Response {{ Response::text("{name}@index") }}
3336
3337    #[allow(clippy::unused_async)]
3338    pub async fn create(_request: Request) -> Response {{ Response::text("{name}@create") }}
3339
3340    #[allow(clippy::unused_async)]
3341    pub async fn store(_request: Request) -> Response {{
3342        Response::text("{name}@store").with_status(StatusCode::CREATED)
3343    }}
3344
3345    #[allow(clippy::unused_async)]
3346    pub async fn show(_request: Request) -> Response {{ Response::text("{name}@show") }}
3347
3348    #[allow(clippy::unused_async)]
3349    pub async fn edit(_request: Request) -> Response {{ Response::text("{name}@edit") }}
3350
3351    #[allow(clippy::unused_async)]
3352    pub async fn update(_request: Request) -> Response {{ Response::text("{name}@update") }}
3353
3354    #[allow(clippy::unused_async)]
3355    pub async fn destroy(_request: Request) -> Response {{
3356        Response::new(StatusCode::NO_CONTENT, phoenix::http::Bytes::new())
3357    }}
3358}}
3359"#
3360    )
3361}
3362
3363fn model_controller_template(
3364    controller: &QualifiedName,
3365    request: &QualifiedName,
3366    resource: &QualifiedName,
3367    props: &QualifiedName,
3368    page: &str,
3369) -> String {
3370    let request_path = rust_item_path("requests", request);
3371    let resource_path = rust_item_path("resources", resource);
3372    let props_path = rust_item_path("props", props);
3373    let name = &controller.class;
3374    let title = page
3375        .split('/')
3376        .next()
3377        .map_or_else(|| "Items".to_owned(), pascal_case);
3378    format!(
3379        r#"use phoenix::prelude::{{Json, Page, PageResponseError, Request, Response, StatusCode, Validated}};
3380
3381use {props_path};
3382use {request_path};
3383use {resource_path};
3384
3385pub struct {name};
3386
3387impl {name} {{
3388    pub async fn index(request: Request) -> Result<Response, PageResponseError> {{
3389        Page::new("{page}", {props_class} {{ title: "{title}".to_owned() }})
3390            .spa()
3391            .respond_to(&request, None)
3392    }}
3393
3394    #[allow(clippy::unused_async)]
3395    pub async fn create(_request: Request) -> Response {{ Response::text("{name}@create") }}
3396
3397    #[allow(clippy::unused_async)]
3398    pub async fn store(
3399        Validated(Json(input)): Validated<Json<{request_class}>>,
3400    ) -> (StatusCode, Json<{resource_class}>) {{
3401        (
3402            StatusCode::CREATED,
3403            Json({resource_class} {{ id: "generated".to_owned(), name: input.name }}),
3404        )
3405    }}
3406
3407    #[allow(clippy::unused_async)]
3408    pub async fn show(_request: Request) -> Response {{ Response::text("{name}@show") }}
3409
3410    #[allow(clippy::unused_async)]
3411    pub async fn edit(_request: Request) -> Response {{ Response::text("{name}@edit") }}
3412
3413    #[allow(clippy::unused_async)]
3414    pub async fn update(_request: Request) -> Response {{ Response::text("{name}@update") }}
3415
3416    #[allow(clippy::unused_async)]
3417    pub async fn destroy(_request: Request) -> Response {{
3418        Response::new(StatusCode::NO_CONTENT, phoenix::http::Bytes::new())
3419    }}
3420}}
3421"#,
3422        props_class = props.class,
3423        request_class = request.class,
3424        resource_class = resource.class,
3425    )
3426}
3427
3428fn middleware_template(name: &str) -> String {
3429    format!(
3430        r"use phoenix::prelude::{{BoxFuture, Middleware, Next, Request, Response}};
3431
3432pub struct {name};
3433
3434impl Middleware for {name} {{
3435    fn handle(&self, request: Request, next: Next) -> BoxFuture<Response> {{
3436        Box::pin(async move {{
3437            // Add authorization, request context, or response policy here.
3438            next.run(request).await
3439        }})
3440    }}
3441}}
3442"
3443    )
3444}
3445
3446fn migration_template(id: &str, name: &str, table: &str) -> String {
3447    format!(
3448        r#"use phoenix::database::Migration;
3449
3450#[must_use]
3451pub fn migration() -> Migration {{
3452    Migration::new("{id}", "{description}")
3453        .up("CREATE TABLE {table} (id BIGINT PRIMARY KEY, name TEXT NOT NULL)")
3454        .down("DROP TABLE {table}")
3455}}
3456"#,
3457        description = name.replace('_', " "),
3458    )
3459}
3460
3461fn controller_route_template(
3462    import: &str,
3463    route_name: &str,
3464    path: &str,
3465    controller: &str,
3466    resource: bool,
3467    action: Option<(&QualifiedName, &QualifiedName)>,
3468) -> String {
3469    if !resource {
3470        return format!(
3471            "use phoenix::prelude::Routes;\n\nuse {import};\n\n#[must_use]\npub fn routes() -> Routes {{\n    Routes::new()\n        .get(\"{path}\", {controller}::index)\n        .name(\"{route_name}.index\")\n}}\n"
3472        );
3473    }
3474    let parameter = snake_case(controller.strip_suffix("Controller").unwrap_or(controller));
3475    let (prelude, action_imports, store, action_binding) = action.map_or_else(
3476        || {
3477            (
3478                "Routes".to_owned(),
3479                String::new(),
3480                format!("{controller}::store"),
3481                String::new(),
3482            )
3483        },
3484        |(input, output)| {
3485            (
3486                "Routes, typed".to_owned(),
3487                format!(
3488                    "use {};\nuse {};\n",
3489                    rust_item_path("requests", input),
3490                    rust_item_path("resources", output),
3491                ),
3492                format!("typed({controller}::store)"),
3493                format!("\n        .action::<{}, {}>()", input.class, output.class),
3494            )
3495        },
3496    );
3497    format!(
3498        r#"use phoenix::prelude::{{{prelude}}};
3499
3500use {import};
3501{action_imports}
3502
3503#[must_use]
3504pub fn routes() -> Routes {{
3505    let member = "{path}/{{{parameter}}}";
3506    Routes::new()
3507        .get("{path}", {controller}::index)
3508        .name("{route_name}.index")
3509        .get("{path}/create", {controller}::create)
3510        .name("{route_name}.create")
3511        .post("{path}", {store})
3512        .name("{route_name}.store"){action_binding}
3513        .get(member, {controller}::show)
3514        .name("{route_name}.show")
3515        .get(format!("{{member}}/edit"), {controller}::edit)
3516        .name("{route_name}.edit")
3517        .put(member, {controller}::update)
3518        .name("{route_name}.update")
3519        .patch(member, {controller}::update)
3520        .delete(member, {controller}::destroy)
3521        .name("{route_name}.destroy")
3522}}
3523"#
3524    )
3525}
3526
3527fn auth_routes_template() -> String {
3528    r#"//! 认证路由:由 `px make:auth` 生成,`mount_routes!()` 自动收集本文件。
3529//!
3530//! 图形验证码(可选,默认以注释交付):`CaptchaFeature` 位于独立 crate
3531//! `phoenix-captcha`,未随 `phoenix` 门面导出,因此**不是零配置能力**,
3532//! 脚手架不默认开启。启用步骤(详见 docs/CAPTCHA.md):
3533//! 1. 应用 `Cargo.toml` 添加依赖 `phoenix-captcha`;
3534//! 2. `FeatureSet::new().plugin(CaptchaFeature::new())?` 注册 `GET /captcha`
3535//!    (命名路由 `captcha.image`),并把 Feature 路由合并进应用路由;
3536//! 3. `LoginInput` 增加 `captcha` 字段并实现 `CaptchaInput`,登录 handler
3537//!    换用 `CaptchaProtected` 提取器;
3538//! 4. 解开 `views/pages/auth/login` 页面里的 `CaptchaImage` 注释块。
3539
3540use std::time::Duration;
3541
3542use phoenix::prelude::{RateLimit, RateLimitConfig, RouteGroup, Routes, typed};
3543
3544use crate::controllers::AuthController;
3545use crate::requests::{LoginInput, PasswordResetInput, RegisterInput};
3546use crate::resources::{AuthMessageResource, AuthSessionResource};
3547
3548#[must_use]
3549pub fn routes() -> Routes {
3550    // 认证提交接口在全局限流之上叠加更严格的默认(每客户端 IP 每秒 2 次),
3551    // 抑制凭据爆破与重置邮件轰炸;次数与窗口按业务调整。
3552    let auth_rate_limit = RateLimit::new(RateLimitConfig {
3553        requests: 2,
3554        window: Duration::from_secs(1),
3555    });
3556
3557    Routes::new()
3558        .get("/login", AuthController::show_login)
3559        .name("login.show")
3560        .get("/register", AuthController::show_register)
3561        .name("register.show")
3562        .get("/forgot-password", AuthController::show_forgot_password)
3563        .name("password-reset.show")
3564        .group(RouteGroup::new().middleware(auth_rate_limit), |routes| {
3565            routes
3566                .post("/login", AuthController::login)
3567                .name("login.store")
3568                .action::<LoginInput, AuthSessionResource>()
3569                .post("/logout", AuthController::logout)
3570                .name("logout.store")
3571                .post("/register", AuthController::register)
3572                .name("register.store")
3573                .action::<RegisterInput, AuthSessionResource>()
3574                .post(
3575                    "/password-reset",
3576                    typed(AuthController::request_password_reset),
3577                )
3578                .name("password-reset.store")
3579                .action::<PasswordResetInput, AuthMessageResource>()
3580        })
3581}
3582"#
3583    .to_owned()
3584}
3585
3586// The body is one template literal; the line count is the generated file, not logic.
3587#[allow(clippy::too_many_lines)]
3588fn auth_controller_template() -> String {
3589    r#"use phoenix::auth::{AuthError, AuthGuard, AuthUser, UserProvider};
3590use phoenix::database::create;
3591use phoenix::prelude::{
3592    AssetManifest, BoxFuture, Database, FromRequest, IntoResponse, Json, Page, PageResponseError,
3593    Password, Request, Response, Session, StatusCode, Validated,
3594};
3595use serde_json::json;
3596
3597use crate::config::AppConfig;
3598use crate::models::User;
3599use crate::props::auth::{AuthForgotPasswordProps, AuthLoginProps, AuthRegisterProps};
3600use crate::requests::{LoginInput, PasswordResetInput, RegisterInput};
3601use crate::resources::{AuthMessageResource, AuthSessionResource};
3602
3603/// `UserProvider` backed by the persistent `users` table.
3604///
3605/// Holds a cloned `Database` handle (a shared connection pool), so each lookup
3606/// runs on its own executor without borrowing the request.
3607struct DatabaseUserProvider {
3608    database: Database,
3609}
3610
3611impl DatabaseUserProvider {
3612    fn new(database: Database) -> Self {
3613        Self { database }
3614    }
3615}
3616
3617impl UserProvider for DatabaseUserProvider {
3618    fn find_by_identifier(
3619        &self,
3620        identifier: &str,
3621    ) -> BoxFuture<Result<Option<AuthUser>, AuthError>> {
3622        let mut executor = self.database.toasty().clone();
3623        let email = identifier.trim().to_ascii_lowercase();
3624        Box::pin(async move {
3625            match User::filter_by_email(email).get(&mut executor).await {
3626                Ok(user) => Ok(Some(auth_user(&user))),
3627                Err(error) if error.is_record_not_found() => Ok(None),
3628                Err(error) => Err(AuthError::provider(error.to_string())),
3629            }
3630        })
3631    }
3632
3633    fn find_by_id(&self, id: &str) -> BoxFuture<Result<Option<AuthUser>, AuthError>> {
3634        let mut executor = self.database.toasty().clone();
3635        let parsed = id.parse::<u64>();
3636        Box::pin(async move {
3637            let Ok(id) = parsed else { return Ok(None) };
3638            match User::filter_by_id(id).get(&mut executor).await {
3639                Ok(user) => Ok(Some(auth_user(&user))),
3640                Err(error) if error.is_record_not_found() => Ok(None),
3641                Err(error) => Err(AuthError::provider(error.to_string())),
3642            }
3643        })
3644    }
3645}
3646
3647/// Map a persisted row onto the framework's minimal `AuthUser` (password hash
3648/// included so the guard can verify it with Argon2id).
3649fn auth_user(user: &User) -> AuthUser {
3650    AuthUser::new(
3651        user.id.to_string(),
3652        user.email.clone(),
3653        user.password_hash.clone(),
3654    )
3655    .with_name(user.name.clone())
3656    .with_role("member")
3657}
3658
3659pub struct AuthController;
3660
3661impl AuthController {
3662    #[allow(clippy::unused_async)]
3663    pub async fn show_login(request: Request) -> Response {
3664        render_auth_page(
3665            &request,
3666            Page::new(
3667                "auth/login",
3668                AuthLoginProps {
3669                    title: "登录".to_owned(),
3670                },
3671            ),
3672        )
3673    }
3674
3675    #[allow(clippy::unused_async)]
3676    pub async fn show_register(request: Request) -> Response {
3677        render_auth_page(
3678            &request,
3679            Page::new(
3680                "auth/register",
3681                AuthRegisterProps {
3682                    title: "注册".to_owned(),
3683                },
3684            ),
3685        )
3686    }
3687
3688    #[allow(clippy::unused_async)]
3689    pub async fn show_forgot_password(request: Request) -> Response {
3690        render_auth_page(
3691            &request,
3692            Page::new(
3693                "auth/forgot-password",
3694                AuthForgotPasswordProps {
3695                    title: "找回密码".to_owned(),
3696                },
3697            ),
3698        )
3699    }
3700
3701    /// 邮箱 + 密码登录,成功后开启会话。
3702    ///
3703    /// 校验交给 `phoenix::auth::AuthGuard`:内部用 Argon2id 比对 `password_hash`,
3704    /// 成功后轮换会话 id(OWASP 会话固定防护)并写入 subject。
3705    /// 可选图形验证码:启用 `phoenix-captcha` 后改用
3706    /// `CaptchaProtected<Validated<Json<LoginInput>>>` 提取器(docs/CAPTCHA.md)。
3707    pub async fn login(request: Request) -> Response {
3708        let Validated(Json(input)) = match Validated::<Json<LoginInput>>::from_request(&request) {
3709            Ok(input) => input,
3710            Err(rejection) => return rejection.into_response(),
3711        };
3712        let Some(session) = request.extensions().get::<Session>().cloned() else {
3713            return session_unavailable();
3714        };
3715        let Some(database) = request.extensions().get::<Database>().cloned() else {
3716            return database_unavailable();
3717        };
3718        let provider = DatabaseUserProvider::new(database);
3719        let guard = AuthGuard::new(&provider, &session);
3720        match guard.attempt(&input.email, &input.password).await {
3721            Ok(Some(user)) => Json(AuthSessionResource {
3722                subject: user.identifier().to_owned(),
3723                name: user.name().to_owned(),
3724                role: "member".to_owned(),
3725            })
3726            .into_response(),
3727            Ok(None) => (
3728                StatusCode::UNAUTHORIZED,
3729                Json(AuthMessageResource {
3730                    message: "邮箱或密码不正确。".to_owned(),
3731                }),
3732            )
3733                .into_response(),
3734            Err(error) => provider_error(&error),
3735        }
3736    }
3737
3738    /// 注册新用户:唯一邮箱查重、Argon2id 哈希入库,随后自动登录。
3739    pub async fn register(request: Request) -> Response {
3740        let Validated(Json(input)) = match Validated::<Json<RegisterInput>>::from_request(&request)
3741        {
3742            Ok(input) => input,
3743            Err(rejection) => return rejection.into_response(),
3744        };
3745        let Some(session) = request.extensions().get::<Session>().cloned() else {
3746            return session_unavailable();
3747        };
3748        let Some(mut database) = request.extensions().get::<Database>().cloned() else {
3749            return database_unavailable();
3750        };
3751        let email = input.email.trim().to_ascii_lowercase();
3752        let provider = DatabaseUserProvider::new(database.clone());
3753        match provider.find_by_identifier(&email).await {
3754            Ok(Some(_)) => return email_taken(),
3755            Ok(None) => {}
3756            Err(error) => return provider_error(&error),
3757        }
3758        let password_hash = match Password::hash(&input.password) {
3759            Ok(hash) => hash,
3760            Err(error) => {
3761                return Response::text(format!("password hashing failed: {error}"))
3762                    .with_status(StatusCode::INTERNAL_SERVER_ERROR);
3763            }
3764        };
3765        let created_at = std::time::SystemTime::now()
3766            .duration_since(std::time::UNIX_EPOCH)
3767            .map(|value| value.as_secs().to_string())
3768            .unwrap_or_default();
3769        let created = create!(User {
3770            email: email.clone(),
3771            name: input.name.clone(),
3772            password_hash: password_hash,
3773            created_at: created_at,
3774        })
3775        .exec(database.toasty_mut())
3776        .await;
3777        match created {
3778            Ok(user) => {
3779                // AuthGuard::login rotates the session id and stores the subject.
3780                AuthGuard::new(&provider, &session).login(&auth_user(&user));
3781                (
3782                    StatusCode::CREATED,
3783                    Json(AuthSessionResource {
3784                        subject: user.email,
3785                        name: user.name,
3786                        role: "member".to_owned(),
3787                    }),
3788                )
3789                    .into_response()
3790            }
3791            Err(error) => Response::text(format!("failed to create user: {error}"))
3792                .with_status(StatusCode::INTERNAL_SERVER_ERROR),
3793        }
3794    }
3795
3796    /// 退出登录并销毁会话。
3797    #[allow(clippy::unused_async)]
3798    pub async fn logout(request: Request) -> Json<AuthMessageResource> {
3799        if let Some(session) = request.extensions().get::<Session>() {
3800            session.destroy();
3801        }
3802        Json(AuthMessageResource {
3803            message: "已退出登录。".to_owned(),
3804        })
3805    }
3806
3807    /// 密码重置请求:为防账号枚举,无论邮箱是否存在都返回同一响应。
3808    #[allow(clippy::unused_async)]
3809    pub async fn request_password_reset(
3810        Validated(Json(_input)): Validated<Json<PasswordResetInput>>,
3811    ) -> (StatusCode, Json<AuthMessageResource>) {
3812        // TODO: 生成重置 token 并通过 phoenix-mail 发送(脚手架不落地邮件)。
3813        (
3814            StatusCode::ACCEPTED,
3815            Json(AuthMessageResource {
3816                message: "如果该邮箱已注册,稍后会收到重置说明。".to_owned(),
3817            }),
3818        )
3819    }
3820}
3821
3822/// 邮箱已注册:返回 422 校验错误信封,字段错误对齐 `Validated` 的响应形状。
3823fn email_taken() -> Response {
3824    (
3825        StatusCode::UNPROCESSABLE_ENTITY,
3826        Json(json!({
3827            "message": "The submitted data is invalid.",
3828            "errors": {
3829                "email": [{ "rule": "unique", "message": "该邮箱已注册。" }]
3830            }
3831        })),
3832    )
3833        .into_response()
3834}
3835
3836fn session_unavailable() -> Response {
3837    Response::text("SessionMiddleware is not mounted")
3838        .with_status(StatusCode::INTERNAL_SERVER_ERROR)
3839}
3840
3841fn database_unavailable() -> Response {
3842    // application() connects the database and mounts it via StateMiddleware.
3843    Response::text("database is unavailable")
3844        .with_status(StatusCode::INTERNAL_SERVER_ERROR)
3845}
3846
3847fn provider_error(error: &AuthError) -> Response {
3848    Response::text(format!("auth store error: {error}"))
3849        .with_status(StatusCode::INTERNAL_SERVER_ERROR)
3850}
3851
3852/// 认证页以 SPA 协议渲染(表单需要可交互),并把 CSRF token 注入页面信封,
3853/// 生成的 typed action 会自动携带 `X-CSRF-Token`。
3854fn render_auth_page(request: &Request, page: Page) -> Response {
3855    let mut page = page.spa();
3856    if let Some(token) = request
3857        .extensions()
3858        .get::<Session>()
3859        .and_then(Session::csrf_token)
3860    {
3861        page = page.csrf_token(token);
3862    }
3863    let assets = request
3864        .extensions()
3865        .get::<Option<AssetManifest>>()
3866        .and_then(Option::as_ref);
3867    if let Some(assets) = assets {
3868        page = match page.production_assets(assets, "client") {
3869            Ok(page) => page,
3870            Err(error) => {
3871                return Response::text(format!("asset manifest error: {error}"))
3872                    .with_status(StatusCode::INTERNAL_SERVER_ERROR);
3873            }
3874        };
3875    }
3876    // Only `px dev` (PHOENIX_VITE_DEV) may override the browser entry with Vite.
3877    if std::env::var_os("PHOENIX_VITE_DEV").is_some()
3878        && let Some(vite_dev_url) = request
3879            .extensions()
3880            .get::<AppConfig>()
3881            .and_then(AppConfig::vite_dev_url)
3882    {
3883        page = page.script_src(format!(
3884            "{}/@id/__x00__virtual:phoenix/client",
3885            vite_dev_url.trim_end_matches('/'),
3886        ));
3887    }
3888    page.respond_to(request, None)
3889        .unwrap_or_else(PageResponseError::into_response)
3890}
3891"#
3892    .to_owned()
3893}
3894
3895fn login_input_template() -> String {
3896    r#"use phoenix::prelude::{
3897    Validate, ValidationErrors, Validator, max_length, min_length, required, rules, string,
3898};
3899use serde::Deserialize;
3900
3901/// 登录表单入参。
3902///
3903/// 启用图形验证码后:增加 `pub captcha: String` 字段并实现
3904/// `phoenix_captcha::CaptchaInput`(见 routes/auth.rs 顶部说明)。
3905#[phoenix::contract(input)]
3906#[derive(Debug, Deserialize)]
3907pub struct LoginInput {
3908    pub email: String,
3909    pub password: String,
3910}
3911
3912impl Validate for LoginInput {
3913    fn validate(&self) -> Result<(), ValidationErrors> {
3914        let data = serde_json::json!({ "email": self.email, "password": self.password });
3915        Validator::new(&data)
3916            .field(
3917                "email",
3918                rules![required(), string(), min_length(3), max_length(120)],
3919            )
3920            .field(
3921                "password",
3922                rules![required(), string(), min_length(8), max_length(1024)],
3923            )
3924            .validate()
3925    }
3926}
3927"#
3928    .to_owned()
3929}
3930
3931fn register_input_template() -> String {
3932    r#"use phoenix::prelude::{
3933    Validate, ValidationErrors, Validator, max_length, min_length, required, rules, string,
3934};
3935use serde::Deserialize;
3936
3937/// 注册表单入参。
3938#[phoenix::contract(input)]
3939#[derive(Debug, Deserialize)]
3940pub struct RegisterInput {
3941    pub name: String,
3942    pub email: String,
3943    pub password: String,
3944}
3945
3946impl Validate for RegisterInput {
3947    fn validate(&self) -> Result<(), ValidationErrors> {
3948        let data = serde_json::json!({
3949            "name": self.name,
3950            "email": self.email,
3951            "password": self.password,
3952        });
3953        Validator::new(&data)
3954            .field(
3955                "name",
3956                rules![required(), string(), min_length(1), max_length(40)],
3957            )
3958            .field(
3959                "email",
3960                rules![required(), string(), min_length(3), max_length(120)],
3961            )
3962            .field(
3963                "password",
3964                rules![required(), string(), min_length(8), max_length(1024)],
3965            )
3966            .validate()
3967    }
3968}
3969"#
3970    .to_owned()
3971}
3972
3973fn password_reset_input_template() -> String {
3974    r#"use phoenix::prelude::{
3975    Validate, ValidationErrors, Validator, max_length, min_length, required, rules, string,
3976};
3977use serde::Deserialize;
3978
3979/// 密码重置请求入参。
3980#[phoenix::contract(input)]
3981#[derive(Debug, Deserialize)]
3982pub struct PasswordResetInput {
3983    pub email: String,
3984}
3985
3986impl Validate for PasswordResetInput {
3987    fn validate(&self) -> Result<(), ValidationErrors> {
3988        let data = serde_json::json!({ "email": self.email });
3989        Validator::new(&data)
3990            .field(
3991                "email",
3992                rules![required(), string(), min_length(3), max_length(120)],
3993            )
3994            .validate()
3995    }
3996}
3997"#
3998    .to_owned()
3999}
4000
4001fn auth_session_resource_template() -> String {
4002    r#"use serde::Serialize;
4003
4004/// 登录 / 注册成功后返回给浏览器的会话信息。
4005#[phoenix::contract(resource)]
4006#[derive(Clone, Debug, Serialize)]
4007#[serde(rename_all = "camelCase")]
4008pub struct AuthSessionResource {
4009    pub subject: String,
4010    pub name: String,
4011    pub role: String,
4012}
4013"#
4014    .to_owned()
4015}
4016
4017fn auth_message_resource_template() -> String {
4018    r#"use serde::Serialize;
4019
4020/// 认证流程的通用提示消息。
4021#[phoenix::contract(resource)]
4022#[derive(Clone, Debug, Serialize)]
4023#[serde(rename_all = "camelCase")]
4024pub struct AuthMessageResource {
4025    pub message: String,
4026}
4027"#
4028    .to_owned()
4029}
4030
4031const AUTH_LOGIN_PAGE_BODY: &str = r#"  return (
4032    <main className="auth-page">
4033      <h1>{title}</h1>
4034      <Form
4035        action={login.store}
4036        initialValues={{ email: "", password: "" }}
4037        fields={LoginInputFields}
4038        onSuccess={() => redirect(home())}
4039      >
4040        {(form) => (
4041          <>
4042            <label htmlFor="login-email">邮箱</label>
4043            <input id="login-email" type="email" autoComplete="email" {...form.field("email")} />
4044            <FieldError errors={form.errors} name="email" />
4045
4046            <label htmlFor="login-password">密码</label>
4047            <input
4048              id="login-password"
4049              type="password"
4050              autoComplete="current-password"
4051              {...form.field("password")}
4052            />
4053            <FieldError errors={form.errors} name="password" />
4054
4055            {/* 启用图形验证码后解开(Rust 侧装配见 routes/auth.rs 顶部注释与 docs/CAPTCHA.md):
4056            <CaptchaImage />
4057            <input autoComplete="off" {...form.field("captcha")} />
4058            <FieldError errors={form.errors} name="captcha" />
4059            */}
4060
4061            <button type="submit" disabled={form.processing}>
4062              {form.processing ? "登录中…" : "登录"}
4063            </button>
4064          </>
4065        )}
4066      </Form>
4067      <p>
4068        还没有账号?<Link href={register.show()}>注册</Link>
4069        <span> · </span>
4070        <Link href={routes["password-reset"].show()}>忘记密码?</Link>
4071      </p>
4072    </main>
4073  );
4074}
4075"#;
4076
4077fn auth_login_page_template(frontend: ProjectFrontend) -> String {
4078    let (imports, signature) = match frontend {
4079        ProjectFrontend::Tsx => (
4080            concat!(
4081                "import { FieldError, Form, Link, redirect } from \"@apizero/react\";\n",
4082                "// 启用图形验证码后解开:\n",
4083                "// import { CaptchaImage } from \"@apizero/react\";\n",
4084                "import type { AuthLoginProps } from \"../../generated/contracts.js\";\n",
4085                "import { LoginInputFields } from \"../../generated/contracts.js\";\n",
4086                "import { home, login, register, routes } from \"../../generated/routes.js\";",
4087            ),
4088            "export default function AuthLogin({ title }: AuthLoginProps) {",
4089        ),
4090        ProjectFrontend::Jsx => (
4091            concat!(
4092                "import { FieldError, Form, Link, redirect } from \"@apizero/react\";\n",
4093                "// 启用图形验证码后解开:\n",
4094                "// import { CaptchaImage } from \"@apizero/react\";\n",
4095                "import { LoginInputFields } from \"../../generated/contracts.js\";\n",
4096                "import { home, login, register, routes } from \"../../generated/routes.js\";",
4097            ),
4098            "export default function AuthLogin({ title }) {",
4099        ),
4100    };
4101    format!("{imports}\n\n{signature}\n{AUTH_LOGIN_PAGE_BODY}")
4102}
4103
4104const AUTH_REGISTER_PAGE_BODY: &str = r#"  return (
4105    <main className="auth-page">
4106      <h1>{title}</h1>
4107      <Form
4108        action={register.store}
4109        initialValues={{ name: "", email: "", password: "" }}
4110        fields={RegisterInputFields}
4111        onSuccess={() => redirect(home())}
4112      >
4113        {(form) => (
4114          <>
4115            <label htmlFor="register-name">昵称</label>
4116            <input id="register-name" autoComplete="nickname" {...form.field("name")} />
4117            <FieldError errors={form.errors} name="name" />
4118
4119            <label htmlFor="register-email">邮箱</label>
4120            <input
4121              id="register-email"
4122              type="email"
4123              autoComplete="email"
4124              {...form.field("email")}
4125            />
4126            <FieldError errors={form.errors} name="email" />
4127
4128            <label htmlFor="register-password">密码</label>
4129            <input
4130              id="register-password"
4131              type="password"
4132              autoComplete="new-password"
4133              {...form.field("password")}
4134            />
4135            <FieldError errors={form.errors} name="password" />
4136
4137            <button type="submit" disabled={form.processing}>
4138              {form.processing ? "注册中…" : "注册"}
4139            </button>
4140          </>
4141        )}
4142      </Form>
4143      <p>
4144        已有账号?<Link href={login.show()}>登录</Link>
4145      </p>
4146    </main>
4147  );
4148}
4149"#;
4150
4151fn auth_register_page_template(frontend: ProjectFrontend) -> String {
4152    let (imports, signature) = match frontend {
4153        ProjectFrontend::Tsx => (
4154            concat!(
4155                "import { FieldError, Form, Link, redirect } from \"@apizero/react\";\n",
4156                "import type { AuthRegisterProps } from \"../../generated/contracts.js\";\n",
4157                "import { RegisterInputFields } from \"../../generated/contracts.js\";\n",
4158                "import { home, login, register } from \"../../generated/routes.js\";",
4159            ),
4160            "export default function AuthRegister({ title }: AuthRegisterProps) {",
4161        ),
4162        ProjectFrontend::Jsx => (
4163            concat!(
4164                "import { FieldError, Form, Link, redirect } from \"@apizero/react\";\n",
4165                "import { RegisterInputFields } from \"../../generated/contracts.js\";\n",
4166                "import { home, login, register } from \"../../generated/routes.js\";",
4167            ),
4168            "export default function AuthRegister({ title }) {",
4169        ),
4170    };
4171    format!("{imports}\n\n{signature}\n{AUTH_REGISTER_PAGE_BODY}")
4172}
4173
4174const AUTH_FORGOT_PASSWORD_PAGE_BODY: &str = r#"  const [notice, setNotice] = useState("");
4175  return (
4176    <main className="auth-page">
4177      <h1>{title}</h1>
4178      {notice ? <p role="status">{notice}</p> : null}
4179      <Form
4180        action={passwordReset.store}
4181        initialValues={{ email: "" }}
4182        fields={PasswordResetInputFields}
4183        onSuccess={(result) => setNotice(result.message)}
4184      >
4185        {(form) => (
4186          <>
4187            <label htmlFor="reset-email">邮箱</label>
4188            <input id="reset-email" type="email" autoComplete="email" {...form.field("email")} />
4189            <FieldError errors={form.errors} name="email" />
4190
4191            <button type="submit" disabled={form.processing}>
4192              {form.processing ? "发送中…" : "发送重置说明"}
4193            </button>
4194          </>
4195        )}
4196      </Form>
4197      <p>
4198        想起密码了?<Link href={login.show()}>返回登录</Link>
4199      </p>
4200    </main>
4201  );
4202}
4203"#;
4204
4205fn auth_forgot_password_page_template(frontend: ProjectFrontend) -> String {
4206    let (imports, signature) = match frontend {
4207        ProjectFrontend::Tsx => (
4208            concat!(
4209                "import { useState } from \"react\";\n",
4210                "import { FieldError, Form, Link } from \"@apizero/react\";\n",
4211                "import type { AuthForgotPasswordProps } from \"../../generated/contracts.js\";\n",
4212                "import { PasswordResetInputFields } from \"../../generated/contracts.js\";\n",
4213                "import { login, routes } from \"../../generated/routes.js\";\n",
4214                "\n",
4215                "const passwordReset = routes[\"password-reset\"];",
4216            ),
4217            "export default function AuthForgotPassword({ title }: AuthForgotPasswordProps) {",
4218        ),
4219        ProjectFrontend::Jsx => (
4220            concat!(
4221                "import { useState } from \"react\";\n",
4222                "import { FieldError, Form, Link } from \"@apizero/react\";\n",
4223                "import { PasswordResetInputFields } from \"../../generated/contracts.js\";\n",
4224                "import { login, routes } from \"../../generated/routes.js\";\n",
4225                "\n",
4226                "const passwordReset = routes[\"password-reset\"];",
4227            ),
4228            "export default function AuthForgotPassword({ title }) {",
4229        ),
4230    };
4231    format!("{imports}\n\n{signature}\n{AUTH_FORGOT_PASSWORD_PAGE_BODY}")
4232}
4233
4234fn rust_item_path(category: &str, name: &QualifiedName) -> String {
4235    if name.modules.is_empty() {
4236        format!("crate::{category}::{}", name.class)
4237    } else {
4238        format!(
4239            "crate::{category}::{}::{}",
4240            name.modules
4241                .iter()
4242                .map(|part| snake_case(part))
4243                .collect::<Vec<_>>()
4244                .join("::"),
4245            name.class,
4246        )
4247    }
4248}
4249
4250fn page_props_template(name: &str, route: &str) -> String {
4251    format!(
4252        r#"use serde::Serialize;
4253
4254#[phoenix::contract(page, page = "{route}")]
4255#[derive(Serialize)]
4256#[serde(rename_all = "camelCase")]
4257pub struct {name} {{
4258    pub title: String,
4259}}
4260"#
4261    )
4262}
4263
4264fn page_template(component: &str, props: &str, depth: usize, frontend: ProjectFrontend) -> String {
4265    let contracts = format!("{}generated/contracts.js", "../".repeat(depth));
4266    if frontend == ProjectFrontend::Jsx {
4267        return format!(
4268            r"export default function {component}({{ title }}) {{
4269  return (
4270    <main>
4271      <h1>{{title}}</h1>
4272    </main>
4273  );
4274}}
4275"
4276        );
4277    }
4278    format!(
4279        r#"import type {{ {props} }} from "{contracts}";
4280
4281export default function {component}({{ title }}: {props}) {{
4282  return (
4283    <main>
4284      <h1>{{title}}</h1>
4285    </main>
4286  );
4287}}
4288"#
4289    )
4290}
4291
4292fn island_template(component: &str, frontend: ProjectFrontend) -> String {
4293    if frontend == ProjectFrontend::Jsx {
4294        return format!(
4295            r#"import {{ useState }} from "react";
4296
4297export default function {component}({{ initialCount = 0 }}) {{
4298  const [count, setCount] = useState(initialCount);
4299  return <button type="button" onClick={{() => setCount((value) => value + 1)}}>{{count}}</button>;
4300}}
4301"#
4302        );
4303    }
4304    format!(
4305        r#"import {{ useState }} from "react";
4306
4307export interface {component}Props {{
4308  initialCount?: number;
4309}}
4310
4311export default function {component}({{ initialCount = 0 }}: {component}Props) {{
4312  const [count, setCount] = useState(initialCount);
4313  return <button type="button" onClick={{() => setCount((value) => value + 1)}}>{{count}}</button>;
4314}}
4315"#
4316    )
4317}
4318
4319fn render_model_registry(values: &BTreeSet<String>) -> Vec<String> {
4320    let mut lines = values
4321        .iter()
4322        .map(|value| format!("// phoenix:model: {value}"))
4323        .collect::<Vec<_>>();
4324    if !lines.is_empty() {
4325        lines.push(String::new());
4326    }
4327    lines.extend([
4328        "#[must_use]".to_owned(),
4329        "pub fn all() -> phoenix::database::ModelSet {".to_owned(),
4330        "    phoenix::database::models!(".to_owned(),
4331    ]);
4332    lines.extend(values.iter().map(|value| format!("        {value},")));
4333    lines.extend(["    )".to_owned(), "}".to_owned()]);
4334    lines
4335}
4336
4337fn render_migration_registry(values: &BTreeSet<String>) -> Vec<String> {
4338    let mut lines = Vec::new();
4339    for value in values {
4340        lines.push(format!("// phoenix:migration: {value}"));
4341        lines.push(format!("pub mod {value};"));
4342    }
4343    if !lines.is_empty() {
4344        lines.push(String::new());
4345    }
4346    lines.extend([
4347        "#[must_use]".to_owned(),
4348        "pub fn all() -> Vec<phoenix::database::Migration> {".to_owned(),
4349        "    vec![".to_owned(),
4350    ]);
4351    lines.extend(
4352        values
4353            .iter()
4354            .map(|value| format!("        {value}::migration(),")),
4355    );
4356    lines.extend(["    ]".to_owned(), "}".to_owned()]);
4357    lines
4358}
4359
4360struct ProjectEditor {
4361    root: PathBuf,
4362    force: bool,
4363    changes: BTreeMap<PathBuf, String>,
4364}
4365
4366impl ProjectEditor {
4367    fn new(root: &Path, force: bool) -> Self {
4368        Self {
4369            root: root.to_path_buf(),
4370            force,
4371            changes: BTreeMap::new(),
4372        }
4373    }
4374
4375    fn create(
4376        &mut self,
4377        relative: impl Into<PathBuf>,
4378        content: String,
4379    ) -> Result<(), ScaffoldError> {
4380        let relative = safe_relative(relative.into())?;
4381        let absolute = self.root.join(&relative);
4382        if !self.force && (absolute.exists() || self.changes.contains_key(&relative)) {
4383            return Err(ScaffoldError::AlreadyExists(absolute));
4384        }
4385        self.changes.insert(relative, content);
4386        Ok(())
4387    }
4388
4389    /// Overwrite a file unconditionally (used to patch existing managed files
4390    /// such as `Cargo.toml` that have no marker regions).
4391    fn set(&mut self, relative: impl Into<PathBuf>, content: String) -> Result<(), ScaffoldError> {
4392        let relative = safe_relative(relative.into())?;
4393        self.changes.insert(relative, content);
4394        Ok(())
4395    }
4396
4397    fn read(&self, relative: &Path) -> Result<String, ScaffoldError> {
4398        if let Some(content) = self.changes.get(relative) {
4399            return Ok(content.clone());
4400        }
4401        let absolute = self.root.join(relative);
4402        match fs::read_to_string(&absolute) {
4403            Ok(content) => Ok(content),
4404            Err(error) if error.kind() == ErrorKind::NotFound => Ok(String::new()),
4405            Err(source) => Err(ScaffoldError::Io {
4406                path: absolute,
4407                source,
4408            }),
4409        }
4410    }
4411
4412    fn update_managed_lines(
4413        &mut self,
4414        relative: impl AsRef<Path>,
4415        start: &str,
4416        end: &str,
4417        added: &[String],
4418    ) -> Result<(), ScaffoldError> {
4419        let relative = safe_relative(relative.as_ref().to_path_buf())?;
4420        let existing = self.read(&relative)?;
4421        let initialized = if existing.is_empty() {
4422            format!("{start}\n{end}\n")
4423        } else {
4424            existing
4425        };
4426        let (before, managed, after) = managed_parts(&initialized, start, end)
4427            .ok_or_else(|| ScaffoldError::InvalidManagedFile(self.root.join(&relative)))?;
4428        let mut lines = managed
4429            .lines()
4430            .map(str::trim)
4431            .filter(|line| !line.is_empty())
4432            .map(str::to_owned)
4433            .collect::<BTreeSet<_>>();
4434        lines.extend(added.iter().cloned());
4435        let body = lines.into_iter().collect::<Vec<_>>().join("\n");
4436        let body = if body.is_empty() {
4437            body
4438        } else {
4439            format!("{body}\n")
4440        };
4441        self.changes
4442            .insert(relative, format!("{before}{start}\n{body}{end}{after}"));
4443        Ok(())
4444    }
4445
4446    fn update_registry(
4447        &mut self,
4448        relative: impl AsRef<Path>,
4449        start: &str,
4450        end: &str,
4451        key: &str,
4452        value: &str,
4453        render: fn(&BTreeSet<String>) -> Vec<String>,
4454    ) -> Result<(), ScaffoldError> {
4455        let relative = safe_relative(relative.as_ref().to_path_buf())?;
4456        let existing = self.read(&relative)?;
4457        let initialized = if existing.is_empty() {
4458            format!("{start}\n{end}\n")
4459        } else {
4460            existing
4461        };
4462        let (before, managed, after) = managed_parts(&initialized, start, end)
4463            .ok_or_else(|| ScaffoldError::InvalidManagedFile(self.root.join(&relative)))?;
4464        let prefix = format!("// phoenix:{key}: ");
4465        let mut values = managed
4466            .lines()
4467            .filter_map(|line| line.trim().strip_prefix(&prefix).map(str::to_owned))
4468            .collect::<BTreeSet<_>>();
4469        values.insert(value.to_owned());
4470        let rendered = render(&values).join("\n");
4471        let body = if rendered.is_empty() {
4472            rendered
4473        } else {
4474            format!("{rendered}\n")
4475        };
4476        self.changes
4477            .insert(relative, format!("{before}{start}\n{body}{end}{after}"));
4478        Ok(())
4479    }
4480
4481    fn commit(self) -> Result<Vec<PathBuf>, ScaffoldError> {
4482        let mut written = Vec::with_capacity(self.changes.len());
4483        for (relative, content) in self.changes {
4484            let path = self.root.join(relative);
4485            if let Some(parent) = path.parent() {
4486                fs::create_dir_all(parent).map_err(|source| ScaffoldError::Io {
4487                    path: parent.to_path_buf(),
4488                    source,
4489                })?;
4490            }
4491            fs::write(&path, content).map_err(|source| ScaffoldError::Io {
4492                path: path.clone(),
4493                source,
4494            })?;
4495            written.push(path);
4496        }
4497        Ok(written)
4498    }
4499}
4500
4501fn managed_parts<'a>(
4502    content: &'a str,
4503    start: &str,
4504    end: &str,
4505) -> Option<(&'a str, &'a str, &'a str)> {
4506    let start_index = content.find(start)?;
4507    let managed_start = start_index + start.len();
4508    let end_relative = content[managed_start..].find(end)?;
4509    let end_index = managed_start + end_relative;
4510    if content[end_index + end.len()..].contains(end) || content[..start_index].contains(start) {
4511        return None;
4512    }
4513    Some((
4514        &content[..start_index],
4515        content[managed_start..end_index].trim_matches('\n'),
4516        &content[end_index + end.len()..],
4517    ))
4518}
4519
4520#[derive(Clone, Debug)]
4521struct QualifiedName {
4522    modules: Vec<String>,
4523    class: String,
4524}
4525
4526impl QualifiedName {
4527    fn parse(value: &str) -> Result<Self, ScaffoldError> {
4528        let parts = name_parts(value)?;
4529        let class = pascal_case(parts.last().expect("validated names have a leaf"));
4530        let modules = parts[..parts.len() - 1]
4531            .iter()
4532            .map(|part| pascal_case(part))
4533            .collect();
4534        Ok(Self { modules, class })
4535    }
4536
4537    fn parse_with_suffix(value: &str, suffix: &str) -> Result<Self, ScaffoldError> {
4538        let mut name = Self::parse(value)?;
4539        if !name.class.ends_with(suffix) {
4540            name.class.push_str(suffix);
4541        }
4542        Ok(name)
4543    }
4544
4545    fn with_leaf(&self, class: String) -> Self {
4546        Self {
4547            modules: self.modules.clone(),
4548            class,
4549        }
4550    }
4551
4552    fn index_page_name(&self) -> PageName {
4553        let mut parts = self.modules.clone();
4554        parts.push(pluralize(&self.class));
4555        parts.push("Index".to_owned());
4556        PageName::from_parts(parts)
4557    }
4558}
4559
4560#[derive(Clone, Debug)]
4561struct PageName {
4562    parts: Vec<String>,
4563    route: String,
4564    class: String,
4565}
4566
4567impl PageName {
4568    fn parse(value: &str) -> Result<Self, ScaffoldError> {
4569        let parts = name_parts(value)?
4570            .into_iter()
4571            .map(|part| pascal_case(&part))
4572            .collect();
4573        Ok(Self::from_parts(parts))
4574    }
4575
4576    fn from_parts(parts: Vec<String>) -> Self {
4577        let route = parts
4578            .iter()
4579            .map(|part| kebab_case(part))
4580            .collect::<Vec<_>>()
4581            .join("/");
4582        let class = parts.iter().map(String::as_str).collect::<String>();
4583        Self {
4584            parts,
4585            route,
4586            class,
4587        }
4588    }
4589}
4590
4591fn name_parts(value: &str) -> Result<Vec<String>, ScaffoldError> {
4592    let normalized = value.replace("::", "/").replace('\\', "/");
4593    let parts = normalized
4594        .split('/')
4595        .filter(|part| !part.is_empty())
4596        .map(str::to_owned)
4597        .collect::<Vec<_>>();
4598    if parts.is_empty()
4599        || parts.iter().any(|part| {
4600            !part.chars().all(|character| {
4601                character.is_ascii_alphanumeric() || character == '_' || character == '-'
4602            }) || !part
4603                .chars()
4604                .any(|character| character.is_ascii_alphabetic())
4605        })
4606    {
4607        return Err(ScaffoldError::InvalidName(value.to_owned()));
4608    }
4609    Ok(parts)
4610}
4611
4612fn package_name(value: &str) -> Result<String, ScaffoldError> {
4613    let value = kebab_case(value).trim_matches('-').to_owned();
4614    if value.is_empty()
4615        || value.starts_with(|character: char| character.is_ascii_digit())
4616        || !value.chars().all(|character| {
4617            character.is_ascii_lowercase() || character.is_ascii_digit() || character == '-'
4618        })
4619    {
4620        return Err(ScaffoldError::InvalidName(value));
4621    }
4622    Ok(value)
4623}
4624
4625fn snake_identifier(value: &str) -> Result<String, ScaffoldError> {
4626    let parts = name_parts(value)?;
4627    Ok(parts
4628        .iter()
4629        .map(|part| snake_case(part))
4630        .collect::<Vec<_>>()
4631        .join("_"))
4632}
4633
4634fn pascal_case(value: &str) -> String {
4635    words(value)
4636        .into_iter()
4637        .map(|word| {
4638            let mut characters = word.chars();
4639            characters.next().map_or_else(String::new, |first| {
4640                format!(
4641                    "{}{}",
4642                    first.to_ascii_uppercase(),
4643                    characters.as_str().to_ascii_lowercase()
4644                )
4645            })
4646        })
4647        .collect()
4648}
4649
4650fn snake_case(value: &str) -> String {
4651    words(value).join("_").to_ascii_lowercase()
4652}
4653
4654fn kebab_case(value: &str) -> String {
4655    words(value).join("-").to_ascii_lowercase()
4656}
4657
4658fn words(value: &str) -> Vec<String> {
4659    let mut output = String::new();
4660    let mut previous_lower_or_digit = false;
4661    for character in value.chars() {
4662        if character == '-' || character == '_' || character.is_ascii_whitespace() {
4663            if !output.ends_with('_') && !output.is_empty() {
4664                output.push('_');
4665            }
4666            previous_lower_or_digit = false;
4667        } else {
4668            if character.is_ascii_uppercase() && previous_lower_or_digit {
4669                output.push('_');
4670            }
4671            output.push(character);
4672            previous_lower_or_digit = character.is_ascii_lowercase() || character.is_ascii_digit();
4673        }
4674    }
4675    output
4676        .split('_')
4677        .filter(|part| !part.is_empty())
4678        .map(str::to_owned)
4679        .collect()
4680}
4681
4682fn pluralize(value: &str) -> String {
4683    if let Some(stem) = value.strip_suffix('y')
4684        && !stem.ends_with(['a', 'e', 'i', 'o', 'u'])
4685    {
4686        return format!("{stem}ies");
4687    }
4688    if value.ends_with(['s', 'x', 'z']) || value.ends_with("ch") || value.ends_with("sh") {
4689        format!("{value}es")
4690    } else {
4691        format!("{value}s")
4692    }
4693}
4694
4695fn inferred_table(migration: &str) -> &str {
4696    migration
4697        .strip_prefix("create_")
4698        .and_then(|name| name.strip_suffix("_table"))
4699        .unwrap_or(migration)
4700}
4701
4702fn safe_relative(path: PathBuf) -> Result<PathBuf, ScaffoldError> {
4703    if path.is_absolute()
4704        || path
4705            .components()
4706            .any(|component| !matches!(component, Component::Normal(_)))
4707    {
4708        return Err(ScaffoldError::InvalidName(path.display().to_string()));
4709    }
4710    Ok(path)
4711}
4712
4713fn absolute_path(path: impl AsRef<Path>) -> Result<PathBuf, ScaffoldError> {
4714    let path = path.as_ref();
4715    if path.is_absolute() {
4716        return Ok(path.to_path_buf());
4717    }
4718    env::current_dir()
4719        .map(|current| current.join(path))
4720        .map_err(|source| ScaffoldError::Io {
4721            path: path.to_path_buf(),
4722            source,
4723        })
4724}
4725
4726fn ensure_empty_target(path: &Path) -> Result<(), ScaffoldError> {
4727    match fs::read_dir(path) {
4728        Ok(mut entries) => {
4729            if entries.next().is_some() {
4730                Err(ScaffoldError::ProjectNotEmpty(path.to_path_buf()))
4731            } else {
4732                Ok(())
4733            }
4734        }
4735        Err(error) if error.kind() == ErrorKind::NotFound => Ok(()),
4736        Err(source) => Err(ScaffoldError::Io {
4737            path: path.to_path_buf(),
4738            source,
4739        }),
4740    }
4741}
4742
4743fn json_string(value: &str) -> String {
4744    serde_json::to_string(value).expect("strings always serialize")
4745}
4746
4747fn run_optional(program: &'static str, args: &[&str], cwd: &Path) -> Result<(), ScaffoldError> {
4748    match Command::new(program).args(args).current_dir(cwd).status() {
4749        Ok(status) if status.success() => Ok(()),
4750        Ok(_) => Err(ScaffoldError::CommandFailed { program }),
4751        Err(error) if error.kind() == ErrorKind::NotFound => Ok(()),
4752        Err(source) => Err(ScaffoldError::Io {
4753            path: cwd.to_path_buf(),
4754            source,
4755        }),
4756    }
4757}
4758
4759fn run_required(program: &'static str, args: &[&str], cwd: &Path) -> Result<(), ScaffoldError> {
4760    match Command::new(program).args(args).current_dir(cwd).status() {
4761        Ok(status) if status.success() => Ok(()),
4762        Ok(_) => Err(ScaffoldError::CommandFailed { program }),
4763        Err(source) => Err(ScaffoldError::Io {
4764            path: cwd.to_path_buf(),
4765            source,
4766        }),
4767    }
4768}
4769
4770#[cfg(test)]
4771mod tests {
4772    use super::*;
4773
4774    fn temporary_directory(label: &str) -> PathBuf {
4775        let id = SystemTime::now()
4776            .duration_since(UNIX_EPOCH)
4777            .unwrap()
4778            .as_nanos();
4779        env::temp_dir().join(format!("phoenix-cli-{label}-{}-{id}", std::process::id()))
4780    }
4781
4782    fn framework_root() -> PathBuf {
4783        PathBuf::from(env!("CARGO_MANIFEST_DIR"))
4784            .join("../..")
4785            .canonicalize()
4786            .unwrap()
4787    }
4788
4789    #[test]
4790    fn creates_a_complete_local_project_without_installing() {
4791        let root = temporary_directory("new");
4792        create_project(
4793            &NewProjectOptions::new(&root)
4794                .dependencies(DependencySource::Local(framework_root()))
4795                .database(Some(ProjectDatabase::Sqlite))
4796                .initialize_git(false)
4797                .install_dependencies(false),
4798        )
4799        .unwrap();
4800
4801        assert!(root.join("src/main.rs").is_file());
4802        assert!(root.join("src/bin/phoenix-manage.rs").is_file());
4803        // Runtime settings converged into `.env`; config/ holds Feature TOML only.
4804        assert!(!root.join("config/app.toml").exists());
4805        assert!(!root.join("config/database.toml").exists());
4806        assert!(!root.join("config/schemas").exists());
4807        assert!(!root.join("taplo.toml").exists());
4808        assert!(!root.join("deploy").exists());
4809        let env_example = fs::read_to_string(root.join(".env.example")).unwrap();
4810        assert!(env_example.contains("DATABASE_URL=sqlite:storage/app.sqlite"));
4811        assert!(env_example.contains("APP_ADDR=127.0.0.1:3000"));
4812        assert!(env_example.contains("VITE_DEV_URL="));
4813        assert!(env_example.contains("PHOENIX_LOG="));
4814        assert!(root.join("app/commands/mod.rs").is_file());
4815        assert!(root.join("config/mod.rs").is_file());
4816        assert!(root.join("database/seeders/mod.rs").is_file());
4817        assert!(root.join("routes/web.rs").is_file());
4818        assert!(root.join("views/pages/home.tsx").is_file());
4819        let manifest = fs::read_to_string(root.join("Cargo.toml")).unwrap();
4820        assert!(manifest.contains("crates/phoenix"));
4821        assert!(manifest.contains("default-run = \"phoenix-cli-new-"));
4822        assert!(manifest.contains("default = [\"sqlite\"]"));
4823        assert!(manifest.contains("sqlite = [\"database\", \"phoenix/sqlite\"]"));
4824        assert!(manifest.contains("features = [\"migration\", \"serde\", \"sqlite\"]"));
4825        assert!(manifest.contains("tls = [\"phoenix/tls\"]"));
4826        assert!(manifest.contains("websocket = [\"phoenix/websocket\"]"));
4827        assert!(manifest.contains("sse = [\"phoenix/sse\"]"));
4828        assert!(manifest.contains("default-features = false"));
4829        assert!(manifest.contains("opt-level = \"z\""));
4830        assert!(manifest.contains("strip = \"symbols\""));
4831        assert!(
4832            fs::read_to_string(root.join("package.json"))
4833                .unwrap()
4834                .contains("file:")
4835        );
4836        let main = fs::read_to_string(root.join("src/main.rs")).unwrap();
4837        assert!(main.contains("Console::new"));
4838        assert!(main.contains("commands::registry()"));
4839        assert!(main.contains(".serve("));
4840        let commands = fs::read_to_string(root.join("app/commands/mod.rs")).unwrap();
4841        assert!(commands.contains("commands!"));
4842        assert!(commands.contains("<phoenix:commands>"));
4843        let application = fs::read_to_string(root.join("src/lib.rs")).unwrap();
4844        assert!(application.contains("pub mod commands"));
4845        assert!(application.contains("NonceSecurityPolicy::development"));
4846        assert!(application.contains("with_middleware(content_security_policy(config))"));
4847        assert!(application.contains("with_middleware(RequestId)"));
4848        assert!(application.contains("with_middleware(AccessLog)"));
4849        assert!(application.contains("SessionMiddleware::new"));
4850        assert!(application.contains("with_middleware(Csrf)"));
4851        assert!(application.contains("TrustedProxies::new"));
4852        assert!(application.contains("HostAllowlist::new"));
4853        assert!(application.contains("RateLimit::new"));
4854        assert!(application.contains("StateMiddleware::new(config.clone())"));
4855        assert!(application.contains("StateMiddleware::new(renderer.clone())"));
4856        assert!(application.contains("RendererConfig::production"));
4857        assert!(application.contains("renderer.warm_up().await"));
4858        assert!(
4859            application
4860                .contains("let vite_dev_server = std::env::var_os(\"PHOENIX_VITE_DEV\").is_some()")
4861        );
4862        assert!(application.contains("RendererConfig::node(\"public/ssr/renderer.js\")"));
4863        let home_controller =
4864            fs::read_to_string(root.join("app/controllers/home_controller.rs")).unwrap();
4865        assert!(home_controller.contains("get::<NodeRenderer>().cloned()"));
4866        assert!(home_controller.contains("respond_with_renderer(request, &renderer).await"));
4867        assert!(
4868            home_controller.contains("PHOENIX_VITE_DEV"),
4869            "scaffold must gate Vite client injection on PHOENIX_VITE_DEV"
4870        );
4871        let home_route = fs::read_to_string(root.join("routes/web.rs")).unwrap();
4872        assert!(home_route.contains(".get(\"/\", HomeController::index)"));
4873        assert!(home_route.contains(".name(\"demo.spa\")"));
4874        assert!(home_route.contains(".name(\"demo.ssr\")"));
4875        assert!(home_route.contains(".name(\"demo.islands\")"));
4876        let cargo = env::var_os("CARGO").unwrap_or_else(|| "cargo".into());
4877        let status = Command::new(cargo)
4878            .args(["check", "--quiet"])
4879            .current_dir(&root)
4880            .status()
4881            .unwrap();
4882        assert!(status.success());
4883        let config = fs::read_to_string(root.join("config/mod.rs")).unwrap();
4884        assert!(config.contains("AppConfig::load()"));
4885        assert!(config.lines().count() < 20);
4886        let manager = fs::read_to_string(root.join("src/bin/phoenix-manage.rs")).unwrap();
4887        assert!(manager.contains("MigrationRunner::new"));
4888        assert!(manager.contains("migrations::all()"));
4889        assert!(manager.contains("seeders::run"));
4890        let models = fs::read_to_string(root.join("app/models/mod.rs")).unwrap();
4891        let migrations = fs::read_to_string(root.join("database/migrations/mod.rs")).unwrap();
4892        assert!(models.contains("pub fn all()"));
4893        assert!(migrations.contains("pub fn all()"));
4894        fs::remove_dir_all(root).unwrap();
4895    }
4896
4897    #[test]
4898    fn default_project_is_islands_without_database_or_git() {
4899        let root = temporary_directory("default-options");
4900        let options = NewProjectOptions::new(&root)
4901            .dependencies(DependencySource::Local(framework_root()))
4902            .install_dependencies(false);
4903        assert!(!options.initialize_git);
4904        assert_eq!(options.render_mode, ProjectRenderMode::Islands);
4905        assert_eq!(options.database, None);
4906        assert_eq!(options.frontend, ProjectFrontend::Tsx);
4907        create_project(&options).unwrap();
4908
4909        let cargo = fs::read_to_string(root.join("Cargo.toml")).unwrap();
4910        assert!(cargo.contains("default = []"));
4911        assert!(!cargo.contains("toasty ="));
4912        assert!(!root.join("config/database.toml").exists());
4913        assert!(!root.join("src/bin/phoenix-manage.rs").exists());
4914        let home_controller =
4915            fs::read_to_string(root.join("app/controllers/home_controller.rs")).unwrap();
4916        // The chosen mode drives the home page; every mode has a demo action.
4917        assert!(home_controller.contains("Page::new(\n            \"home\""));
4918        assert!(home_controller.contains(".islands();"));
4919        assert!(home_controller.contains("Page::new(\"demo/spa\", serde_json::json!({})).spa()"));
4920        assert!(home_controller.contains("DemoSsrProps { rendered_at }).ssr()"));
4921        assert!(
4922            home_controller
4923                .contains("Page::new(\"demo/islands\", serde_json::json!({})).islands()")
4924        );
4925        // One demo page per render mode, plus the hydrated counter island.
4926        let spa = fs::read_to_string(root.join("views/pages/demo/spa.tsx")).unwrap();
4927        assert!(spa.contains("useState"));
4928        let ssr = fs::read_to_string(root.join("views/pages/demo/ssr.tsx")).unwrap();
4929        assert!(ssr.contains("renderedAt"));
4930        let islands = fs::read_to_string(root.join("views/pages/demo/islands.tsx")).unwrap();
4931        assert!(islands.contains("client:load"));
4932        assert!(root.join("views/islands/counter.tsx").is_file());
4933        let home = fs::read_to_string(root.join("views/pages/home.tsx")).unwrap();
4934        assert!(home.contains("<Link href={demo.spa()}"));
4935        assert!(home.contains("<Link href={demo.ssr()}"));
4936        assert!(home.contains("<Link href={demo.islands()}"));
4937        assert!(!root.join(".git").exists());
4938
4939        let cargo = env::var_os("CARGO").unwrap_or_else(|| "cargo".into());
4940        let status = Command::new(cargo)
4941            .args(["check", "--quiet"])
4942            .current_dir(&root)
4943            .status()
4944            .unwrap();
4945        assert!(status.success());
4946        fs::remove_dir_all(root).unwrap();
4947    }
4948
4949    #[test]
4950    fn project_options_select_jsx_tailwind_and_database() {
4951        let root = temporary_directory("options");
4952        create_project(
4953            &NewProjectOptions::new(&root)
4954                .dependencies(DependencySource::Local(framework_root()))
4955                .database(Some(ProjectDatabase::Pgsql))
4956                .render_mode(ProjectRenderMode::Ssr)
4957                .frontend(ProjectFrontend::Jsx)
4958                .tailwind(true)
4959                .install_dependencies(false),
4960        )
4961        .unwrap();
4962
4963        let cargo = fs::read_to_string(root.join("Cargo.toml")).unwrap();
4964        assert!(cargo.contains("default = [\"pgsql\"]"));
4965        assert!(cargo.contains("\"postgresql\""));
4966        assert!(root.join("views/pages/home.jsx").is_file());
4967        assert!(!root.join("views/pages/home.tsx").exists());
4968        assert!(
4969            fs::read_to_string(root.join("app/controllers/home_controller.rs"))
4970                .unwrap()
4971                .contains(".ssr()")
4972        );
4973        assert!(
4974            fs::read_to_string(root.join("package.json"))
4975                .unwrap()
4976                .contains("@tailwindcss/vite")
4977        );
4978        assert!(
4979            fs::read_to_string(root.join("views/styles.css"))
4980                .unwrap()
4981                .starts_with("@import \"tailwindcss\";")
4982        );
4983        assert!(
4984            fs::read_to_string(root.join("vite.config.ts"))
4985                .unwrap()
4986                .contains("tailwindcss()")
4987        );
4988        let generator = ProjectGenerator::discover(&root).unwrap();
4989        generator
4990            .page("reports/index", GenerateOptions::default())
4991            .unwrap();
4992        generator
4993            .island("LikeButton", GenerateOptions::default())
4994            .unwrap();
4995        assert!(root.join("views/pages/reports/index.jsx").is_file());
4996        assert!(root.join("views/islands/like-button.jsx").is_file());
4997        // The scaffolded demo island is already there in the selected frontend.
4998        assert!(root.join("views/islands/counter.jsx").is_file());
4999        assert!(
5000            !fs::read_to_string(root.join("views/pages/reports/index.jsx"))
5001                .unwrap()
5002                .contains("import type")
5003        );
5004        generator.auth(GenerateOptions::default()).unwrap();
5005        assert!(root.join("views/pages/auth/login.jsx").is_file());
5006        assert!(
5007            !fs::read_to_string(root.join("views/pages/auth/login.jsx"))
5008                .unwrap()
5009                .contains("import type")
5010        );
5011        fs::remove_dir_all(root).unwrap();
5012    }
5013
5014    #[test]
5015    fn all_database_option_writes_all_toasty_drivers() {
5016        let root = temporary_directory("all-databases");
5017        create_project(
5018            &NewProjectOptions::new(&root)
5019                .dependencies(DependencySource::Local(framework_root()))
5020                .database(Some(ProjectDatabase::All))
5021                .install_dependencies(false),
5022        )
5023        .unwrap();
5024        let cargo = fs::read_to_string(root.join("Cargo.toml")).unwrap();
5025        assert!(cargo.contains(
5026            "toasty = { version = \"0.8\", default-features = false, features = [\"migration\", \"mysql\", \"postgresql\", \"serde\", \"sqlite\"] }"
5027        ));
5028        assert!(cargo.contains("all-databases = [\"database\", \"phoenix/sqlite\", \"phoenix/pgsql\", \"phoenix/mysql\"]"));
5029        let cargo = env::var_os("CARGO").unwrap_or_else(|| "cargo".into());
5030        let status = Command::new(cargo)
5031            .args(["check", "--quiet"])
5032            .current_dir(&root)
5033            .status()
5034            .unwrap();
5035        assert!(status.success());
5036        fs::remove_dir_all(root).unwrap();
5037    }
5038
5039    #[test]
5040    fn registry_dependencies_use_plain_versions_not_npmjs_tarballs() {
5041        let (phoenix, react, react_ssr, vite) =
5042            framework_dependency_pins(&DependencySource::Registry, &[]).unwrap();
5043        for pin in [&phoenix, &react, &react_ssr, &vite] {
5044            assert!(
5045                !pin.contains("registry.npmjs.org"),
5046                "registry pins must not bypass the user's npm mirror: {pin}"
5047            );
5048        }
5049        assert_eq!(react, format!("^{APIZERO_REACT_VERSION}"));
5050        assert_eq!(react_ssr, format!("^{APIZERO_REACT_SSR_VERSION}"));
5051        assert_eq!(vite, format!("^{APIZERO_VITE_VERSION}"));
5052        assert!(phoenix.contains(&format!("version = \"{PHOENIXRS_VERSION}\"")));
5053        assert!(!phoenix.contains("features = ["));
5054
5055        let (phoenix, ..) = framework_dependency_pins(
5056            &DependencySource::Registry,
5057            &[ProjectFeature::Captcha, ProjectFeature::Pay],
5058        )
5059        .unwrap();
5060        assert!(phoenix.contains("features = [\"captcha\", \"pay\"]"));
5061    }
5062
5063    #[test]
5064    fn feature_selection_generates_config_and_assembly() {
5065        let root = temporary_directory("features");
5066        create_project(
5067            &NewProjectOptions::new(&root)
5068                .dependencies(DependencySource::Local(framework_root()))
5069                .database(Some(ProjectDatabase::Sqlite))
5070                .features(vec![
5071                    ProjectFeature::Captcha,
5072                    ProjectFeature::Pay,
5073                    ProjectFeature::Notify,
5074                ])
5075                .install_dependencies(false),
5076        )
5077        .unwrap();
5078
5079        let cargo_manifest = fs::read_to_string(root.join("Cargo.toml")).unwrap();
5080        assert!(cargo_manifest.contains("features = [\"captcha\", \"pay\", \"notify\"]"));
5081
5082        let pay_config = fs::read_to_string(root.join("config/pay.toml")).unwrap();
5083        assert!(pay_config.contains("${PAY_WECHAT_API_V3_KEY}"));
5084        assert!(root.join("config/captcha.toml").is_file());
5085        assert!(root.join("config/notify.toml").is_file());
5086
5087        let lib = fs::read_to_string(root.join("src/lib.rs")).unwrap();
5088        assert!(lib.contains("pub fn features()"));
5089        assert!(lib.contains("CaptchaFeature::new()"));
5090        assert!(lib.contains("PayFeature::new(pay_manager()?)"));
5091        assert!(lib.contains("NotifyFeature::new()"));
5092        assert!(lib.contains("load_feature_config(\"pay\")"));
5093        assert!(lib.contains("pub fn notifier()"));
5094        // Webhooks stay outside CSRF; business routes keep it via the scope.
5095        assert!(lib.contains(".scoped(RouteGroup::new().middleware(Csrf))"));
5096        assert!(lib.contains(".merge(features()?.into_routes())"));
5097
5098        let manage = fs::read_to_string(root.join("src/bin/phoenix-manage.rs")).unwrap();
5099        assert!(manage.contains("features.into_parts().migrations"));
5100
5101        let env_example = fs::read_to_string(root.join(".env.example")).unwrap();
5102        assert!(env_example.contains("PAY_WECHAT_API_V3_KEY"));
5103        let stored = fs::read_to_string(root.join(".phoenix")).unwrap();
5104        assert!(stored.contains("features=captcha,pay,notify"));
5105        let readme = fs::read_to_string(root.join("README.md")).unwrap();
5106        assert!(readme.contains("已启用 Feature"));
5107
5108        let cargo = env::var_os("CARGO").unwrap_or_else(|| "cargo".into());
5109        let status = Command::new(cargo)
5110            .args(["check", "--quiet"])
5111            .current_dir(&root)
5112            .status()
5113            .unwrap();
5114        assert!(status.success());
5115        fs::remove_dir_all(root).unwrap();
5116    }
5117
5118    #[test]
5119    fn stored_feature_options_survive_update_core() {
5120        let root = temporary_directory("features-update");
5121        create_project(
5122            &NewProjectOptions::new(&root)
5123                .dependencies(DependencySource::Local(framework_root()))
5124                .features(vec![ProjectFeature::Captcha])
5125                .install_dependencies(false),
5126        )
5127        .unwrap();
5128        // User values in feature config files must survive `px update`.
5129        fs::write(root.join("config/captcha.toml"), "length = 6\n").unwrap();
5130
5131        let generator = ProjectGenerator::discover(&root).unwrap();
5132        let _ = generator
5133            .update_core(
5134                &UpdateProjectOptions::new()
5135                    .dependencies(DependencySource::Local(framework_root()))
5136                    .install_dependencies(false),
5137            )
5138            .unwrap();
5139
5140        let lib = fs::read_to_string(root.join("src/lib.rs")).unwrap();
5141        assert!(lib.contains("CaptchaFeature::new()"));
5142        let cargo_manifest = fs::read_to_string(root.join("Cargo.toml")).unwrap();
5143        assert!(cargo_manifest.contains("features = [\"captcha\"]"));
5144        assert_eq!(
5145            fs::read_to_string(root.join("config/captcha.toml")).unwrap(),
5146            "length = 6\n"
5147        );
5148        fs::remove_dir_all(root).unwrap();
5149    }
5150
5151    #[test]
5152    fn make_command_registers_async_handler() {
5153        let root = temporary_directory("command");
5154        create_project(
5155            &NewProjectOptions::new(&root)
5156                .dependencies(DependencySource::Local(framework_root()))
5157                .database(Some(ProjectDatabase::Sqlite))
5158                .initialize_git(false)
5159                .install_dependencies(false),
5160        )
5161        .unwrap();
5162        let generator = ProjectGenerator::discover(&root).unwrap();
5163        generator
5164            .command("Update", GenerateOptions::default())
5165            .unwrap();
5166
5167        assert!(root.join("app/commands/update.rs").is_file());
5168        let module = fs::read_to_string(root.join("app/commands/mod.rs")).unwrap();
5169        assert!(module.contains("pub mod update;"));
5170        assert!(module.contains("pub use update::update;"));
5171        assert!(module.contains("update,"));
5172        let command = fs::read_to_string(root.join("app/commands/update.rs")).unwrap();
5173        assert!(command.contains("pub async fn update"));
5174        assert!(command.contains("CommandContext<'_>"));
5175        fs::remove_dir_all(root).unwrap();
5176    }
5177
5178    #[test]
5179    fn model_all_registers_every_supported_business_artifact() {
5180        let root = temporary_directory("model-all");
5181        create_project(
5182            &NewProjectOptions::new(&root)
5183                .dependencies(DependencySource::Local(framework_root()))
5184                .database(Some(ProjectDatabase::Sqlite))
5185                .initialize_git(false)
5186                .install_dependencies(false),
5187        )
5188        .unwrap();
5189        let generator = ProjectGenerator::discover(&root).unwrap();
5190        generator
5191            .model(
5192                "Admin/Post",
5193                ModelOptions {
5194                    all: true,
5195                    ..ModelOptions::default()
5196                },
5197            )
5198            .unwrap();
5199        generator.model("Comment", ModelOptions::default()).unwrap();
5200
5201        assert!(root.join("app/models/admin/post.rs").is_file());
5202        assert!(
5203            root.join("app/controllers/admin/post_controller.rs")
5204                .is_file()
5205        );
5206        assert!(
5207            root.join("app/requests/admin/store_post_request.rs")
5208                .is_file()
5209        );
5210        assert!(root.join("app/resources/admin/post_resource.rs").is_file());
5211        assert!(root.join("routes/admin_posts.rs").is_file());
5212        assert!(root.join("views/pages/admin/posts/index.tsx").is_file());
5213        let routes = fs::read_to_string(root.join("routes/admin_posts.rs")).unwrap();
5214        assert!(routes.contains(".name(\"admin.posts.index\")"));
5215        assert!(routes.contains(".name(\"admin.posts.destroy\")"));
5216        assert!(routes.contains("typed(PostController::store)"));
5217        assert!(routes.contains(".action::<StorePostRequest, PostResource>()"));
5218        let controller =
5219            fs::read_to_string(root.join("app/controllers/admin/post_controller.rs")).unwrap();
5220        assert!(controller.contains("Validated(Json(input))"));
5221        assert!(controller.contains("Page::new(\"admin/posts/index\""));
5222        let page = fs::read_to_string(root.join("views/pages/admin/posts/index.tsx")).unwrap();
5223        assert!(page.contains("../../../generated/contracts.js"));
5224        let models = fs::read_to_string(root.join("app/models/mod.rs")).unwrap();
5225        assert!(models.contains("admin::Post"));
5226        assert!(models.contains("Comment"));
5227        let migrations = fs::read_to_string(root.join("database/migrations/mod.rs")).unwrap();
5228        assert!(migrations.contains("pub fn all()"));
5229        fs::remove_dir_all(root).unwrap();
5230    }
5231
5232    #[test]
5233    fn relations_and_factories_generate_a_compiling_slice() {
5234        let root = temporary_directory("relations");
5235        create_project(
5236            &NewProjectOptions::new(&root)
5237                .dependencies(DependencySource::Local(framework_root()))
5238                .database(Some(ProjectDatabase::Sqlite))
5239                .initialize_git(false)
5240                .install_dependencies(false),
5241        )
5242        .unwrap();
5243        let generator = ProjectGenerator::discover(&root).unwrap();
5244
5245        // The parent side: one line to say "a user has many posts".
5246        generator
5247            .model(
5248                "User",
5249                ModelOptions {
5250                    migration: true,
5251                    factory: true,
5252                    relations: vec![Relation {
5253                        kind: RelationKind::HasMany,
5254                        target: "Post".to_owned(),
5255                    }],
5256                    ..ModelOptions::default()
5257                },
5258            )
5259            .unwrap();
5260        // The child side: one line to say "a post belongs to a user". No
5261        // foreign key, no key mapping, no table name.
5262        generator
5263            .model(
5264                "Post",
5265                ModelOptions {
5266                    migration: true,
5267                    factory: true,
5268                    relations: vec![Relation {
5269                        kind: RelationKind::BelongsTo,
5270                        target: "User".to_owned(),
5271                    }],
5272                    ..ModelOptions::default()
5273                },
5274            )
5275            .unwrap();
5276
5277        let post = fs::read_to_string(root.join("app/models/post.rs")).unwrap();
5278        assert!(post.contains("#[model]"), "{post}");
5279        assert!(post.contains("#[belongs_to]"), "{post}");
5280        assert!(post.contains("pub user: Deferred<User>"), "{post}");
5281        assert!(
5282            !post.contains("user_id"),
5283            "the foreign key is a convention, not something to write: {post}"
5284        );
5285        assert!(
5286            !post.contains("#[key]") && !post.contains("#[table"),
5287            "neither is the key or the table name: {post}"
5288        );
5289
5290        let user = fs::read_to_string(root.join("app/models/user.rs")).unwrap();
5291        assert!(user.contains("#[has_many]"), "{user}");
5292        assert!(user.contains("pub posts: Deferred<Vec<Post>>"), "{user}");
5293
5294        // The child factory takes its parent's key; the parent factory does not.
5295        let factory = fs::read_to_string(root.join("database/seeders/post_factory.rs")).unwrap();
5296        assert!(factory.contains("|f, user_id: i64|"), "{factory}");
5297        assert!(factory.contains(".user_id(user_id)"), "{factory}");
5298        assert!(
5299            factory.contains(r#"#![cfg(feature = "factory")]"#),
5300            "a factory never reaches a release build: {factory}"
5301        );
5302        let factory = fs::read_to_string(root.join("database/seeders/user_factory.rs")).unwrap();
5303        assert!(factory.contains("|f|"), "{factory}");
5304
5305        let seeders = fs::read_to_string(root.join("database/seeders/mod.rs")).unwrap();
5306        assert!(seeders.contains("pub mod post_factory;"), "{seeders}");
5307        assert!(seeders.contains("pub mod user_factory;"), "{seeders}");
5308
5309        // The real assertion: all of it compiles, with factories on and off.
5310        let cargo = env::var_os("CARGO").unwrap_or_else(|| "cargo".into());
5311        for features in [None, Some("factory")] {
5312            let mut command = Command::new(&cargo);
5313            command.args(["check", "--quiet"]).current_dir(&root);
5314            if let Some(features) = features {
5315                command.args(["--features", features]);
5316            }
5317            assert!(
5318                command.status().unwrap().success(),
5319                "generated project must compile with features {features:?}"
5320            );
5321        }
5322        fs::remove_dir_all(root).unwrap();
5323    }
5324
5325    #[test]
5326    fn make_auth_requires_a_database() {
5327        let root = temporary_directory("auth-no-db");
5328        create_project(
5329            &NewProjectOptions::new(&root)
5330                .dependencies(DependencySource::Local(framework_root()))
5331                .initialize_git(false)
5332                .install_dependencies(false),
5333        )
5334        .unwrap();
5335        let generator = ProjectGenerator::discover(&root).unwrap();
5336        // No driver was selected at `px new`, so the persistent User model has
5337        // nowhere to live: refuse with a clear, actionable error and write nothing.
5338        assert!(matches!(
5339            generator.auth(GenerateOptions::default()),
5340            Err(ScaffoldError::AuthRequiresDatabase)
5341        ));
5342        assert!(!root.join("routes/auth.rs").exists());
5343        assert!(!root.join("app/models/user.rs").exists());
5344        fs::remove_dir_all(root).unwrap();
5345    }
5346
5347    #[test]
5348    #[allow(clippy::too_many_lines, reason = "one assertion per generated file")]
5349    fn make_auth_generates_a_working_authentication_slice() {
5350        let root = temporary_directory("auth");
5351        create_project(
5352            &NewProjectOptions::new(&root)
5353                .dependencies(DependencySource::Local(framework_root()))
5354                .database(Some(ProjectDatabase::Sqlite))
5355                .initialize_git(false)
5356                .install_dependencies(false),
5357        )
5358        .unwrap();
5359        let generator = ProjectGenerator::discover(&root).unwrap();
5360        generator.auth(GenerateOptions::default()).unwrap();
5361
5362        for path in [
5363            "routes/auth.rs",
5364            "app/controllers/auth_controller.rs",
5365            "app/models/user.rs",
5366            "app/requests/login_input.rs",
5367            "app/requests/register_input.rs",
5368            "app/requests/password_reset_input.rs",
5369            "app/resources/auth_session_resource.rs",
5370            "app/resources/auth_message_resource.rs",
5371            "app/props/auth/auth_login_props.rs",
5372            "app/props/auth/auth_register_props.rs",
5373            "app/props/auth/auth_forgot_password_props.rs",
5374            "views/pages/auth/login.tsx",
5375            "views/pages/auth/register.tsx",
5376            "views/pages/auth/forgot-password.tsx",
5377        ] {
5378            assert!(root.join(path).is_file(), "missing {path}");
5379        }
5380
5381        // Persistent User model + migration registered like `px make:model`.
5382        let user_model = fs::read_to_string(root.join("app/models/user.rs")).unwrap();
5383        assert!(user_model.contains("#[derive(Clone, Debug, Model)]"));
5384        assert!(user_model.contains("#[unique]"));
5385        assert!(user_model.contains("pub email: String"));
5386        assert!(user_model.contains("pub password_hash: String"));
5387        assert!(user_model.contains("pub created_at: String"));
5388        let models = fs::read_to_string(root.join("app/models/mod.rs")).unwrap();
5389        assert!(models.contains("// phoenix:model: User"));
5390        assert!(models.contains("pub use user::User;"));
5391        let migrations = fs::read_to_string(root.join("database/migrations/mod.rs")).unwrap();
5392        assert!(migrations.contains("create_users_table"));
5393        // The Argon2id (`password`) and guard (`auth`) facade features are on by default.
5394        let cargo = fs::read_to_string(root.join("Cargo.toml")).unwrap();
5395        let default_line = cargo
5396            .lines()
5397            .find(|line| line.trim_start().starts_with("default ="))
5398            .expect("default features line");
5399        assert!(default_line.contains("\"sqlite\""));
5400        assert!(default_line.contains("\"password\""));
5401        assert!(default_line.contains("\"auth\""));
5402
5403        let routes = fs::read_to_string(root.join("routes/auth.rs")).unwrap();
5404        assert!(routes.contains(".name(\"login.show\")"));
5405        assert!(routes.contains(".name(\"login.store\")"));
5406        assert!(routes.contains(".name(\"logout.store\")"));
5407        assert!(routes.contains(".name(\"register.store\")"));
5408        assert!(routes.contains(".name(\"password-reset.store\")"));
5409        assert!(routes.contains(".action::<LoginInput, AuthSessionResource>()"));
5410        assert!(routes.contains(".action::<RegisterInput, AuthSessionResource>()"));
5411        assert!(routes.contains(".action::<PasswordResetInput, AuthMessageResource>()"));
5412        assert!(routes.contains("RateLimit::new(RateLimitConfig {"));
5413        assert!(routes.contains("phoenix-captcha"), "captcha assembly notes");
5414
5415        let controller =
5416            fs::read_to_string(root.join("app/controllers/auth_controller.rs")).unwrap();
5417        // Credentials go through Argon2id + the phoenix-auth guard, never plaintext.
5418        assert!(
5419            controller
5420                .contains("use phoenix::auth::{AuthError, AuthGuard, AuthUser, UserProvider}")
5421        );
5422        assert!(controller.contains("impl UserProvider for DatabaseUserProvider"));
5423        assert!(controller.contains("guard.attempt(&input.email, &input.password)"));
5424        assert!(controller.contains("Password::hash(&input.password)"));
5425        assert!(controller.contains("StatusCode::UNPROCESSABLE_ENTITY"));
5426        assert!(controller.contains("Validated::<Json<LoginInput>>::from_request"));
5427        assert!(controller.contains("CaptchaProtected"));
5428        assert!(!controller.contains("DemoUser"), "no in-memory demo store");
5429        assert!(
5430            !controller.contains("user.password == input.password"),
5431            "no plaintext password comparison"
5432        );
5433        let controllers = fs::read_to_string(root.join("app/controllers/mod.rs")).unwrap();
5434        assert!(controllers.contains("pub use auth_controller::AuthController;"));
5435        let requests = fs::read_to_string(root.join("app/requests/login_input.rs")).unwrap();
5436        assert!(requests.contains("#[phoenix::contract(input)]"));
5437        assert!(requests.contains("impl Validate for LoginInput"));
5438        let props = fs::read_to_string(root.join("app/props/auth/auth_login_props.rs")).unwrap();
5439        assert!(props.contains("#[phoenix::contract(page, page = \"auth/login\")]"));
5440
5441        let login_page = fs::read_to_string(root.join("views/pages/auth/login.tsx")).unwrap();
5442        assert!(login_page.contains("<Form"));
5443        assert!(login_page.contains("form.field(\"email\")"));
5444        assert!(login_page.contains("form.field(\"password\")"));
5445        assert!(login_page.contains("<FieldError errors={form.errors} name=\"password\" />"));
5446        assert!(login_page.contains("fields={LoginInputFields}"));
5447        assert!(login_page.contains("CaptchaImage"));
5448        let reset_page =
5449            fs::read_to_string(root.join("views/pages/auth/forgot-password.tsx")).unwrap();
5450        assert!(reset_page.contains("fields={PasswordResetInputFields}"));
5451        assert!(reset_page.contains("routes[\"password-reset\"]"));
5452
5453        assert!(matches!(
5454            generator.auth(GenerateOptions::default()),
5455            Err(ScaffoldError::AlreadyExists(_))
5456        ));
5457        generator.auth(GenerateOptions { force: true }).unwrap();
5458        // The forced rebuild must not stack a second users migration. Assert on
5459        // the registration itself rather than counting substrings: one
5460        // migration is named three times in the registry (marker comment,
5461        // `pub mod`, and the `all()` entry).
5462        let migrations = fs::read_to_string(root.join("database/migrations/mod.rs")).unwrap();
5463        assert_eq!(
5464            migrations.matches("pub mod m_").count(),
5465            1,
5466            "exactly one migration is registered:\n{migrations}"
5467        );
5468        let migration_files = fs::read_dir(root.join("database/migrations"))
5469            .unwrap()
5470            .filter_map(Result::ok)
5471            .filter(|entry| entry.file_name() != "mod.rs")
5472            .count();
5473        assert_eq!(migration_files, 1, "and exactly one migration file exists");
5474
5475        let cargo = env::var_os("CARGO").unwrap_or_else(|| "cargo".into());
5476        let status = Command::new(cargo)
5477            .args(["check", "--quiet"])
5478            .current_dir(&root)
5479            .status()
5480            .unwrap();
5481        assert!(status.success());
5482        fs::remove_dir_all(root).unwrap();
5483    }
5484
5485    #[test]
5486    fn update_core_refreshes_framework_files_only() {
5487        let root = temporary_directory("update-core");
5488        create_project(
5489            &NewProjectOptions::new(&root)
5490                .dependencies(DependencySource::Local(framework_root()))
5491                .initialize_git(false)
5492                .install_dependencies(false),
5493        )
5494        .unwrap();
5495
5496        let route_before = fs::read_to_string(root.join("routes/web.rs")).unwrap();
5497        let page_before = fs::read_to_string(root.join("views/pages/home.tsx")).unwrap();
5498        fs::write(root.join("src/lib.rs"), "// stale core\n").unwrap();
5499        fs::write(
5500            root.join("routes/web.rs"),
5501            format!("{route_before}\n// business marker\n"),
5502        )
5503        .unwrap();
5504
5505        let generator = ProjectGenerator::discover(&root).unwrap();
5506        let changed = generator
5507            .update_core(
5508                &UpdateProjectOptions::new()
5509                    .dependencies(DependencySource::Local(framework_root()))
5510                    .install_dependencies(false),
5511            )
5512            .unwrap();
5513        assert!(
5514            changed.iter().any(|path| path.ends_with("src/lib.rs")),
5515            "expected src/lib.rs to be refreshed"
5516        );
5517
5518        let lib = fs::read_to_string(root.join("src/lib.rs")).unwrap();
5519        assert!(
5520            lib.contains("let vite_dev_server = std::env::var_os(\"PHOENIX_VITE_DEV\").is_some()")
5521        );
5522        assert!(!lib.contains("// stale core"));
5523        let route_after = fs::read_to_string(root.join("routes/web.rs")).unwrap();
5524        assert!(route_after.contains("// business marker"));
5525        assert_eq!(
5526            fs::read_to_string(root.join("views/pages/home.tsx")).unwrap(),
5527            page_before
5528        );
5529        let options = fs::read_to_string(root.join(".phoenix")).unwrap();
5530        assert!(options.contains("render_mode=islands"));
5531        assert!(options.contains("database=none"));
5532        fs::remove_dir_all(root).unwrap();
5533    }
5534
5535    #[test]
5536    fn generators_refuse_overwrites_and_path_traversal() {
5537        let root = temporary_directory("safety");
5538        create_project(
5539            &NewProjectOptions::new(&root)
5540                .dependencies(DependencySource::Local(framework_root()))
5541                .database(Some(ProjectDatabase::Sqlite))
5542                .initialize_git(false)
5543                .install_dependencies(false),
5544        )
5545        .unwrap();
5546        let generator = ProjectGenerator::discover(&root).unwrap();
5547        generator
5548            .controller("Report", ControllerOptions::default())
5549            .unwrap();
5550        assert!(matches!(
5551            generator.controller("Report", ControllerOptions::default()),
5552            Err(ScaffoldError::AlreadyExists(_))
5553        ));
5554        assert!(matches!(
5555            generator.page("../outside", GenerateOptions::default()),
5556            Err(ScaffoldError::InvalidName(_))
5557        ));
5558        fs::remove_dir_all(root).unwrap();
5559    }
5560}