1use std::collections::{BTreeMap, BTreeSet};
11use std::path::{Path, PathBuf};
12
13use luxid_core::error::{Error, Result};
14
15use crate::naming::Names;
16
17#[derive(Debug, Clone, PartialEq, Eq)]
19pub struct NewFile {
20 pub path: PathBuf,
21 pub contents: String,
22}
23
24#[derive(Debug, Clone, PartialEq, Eq)]
26pub struct Insertion {
27 pub path: PathBuf,
28 pub marker: &'static str,
29 pub line: String,
30}
31
32#[derive(Debug, Default, Clone, PartialEq, Eq)]
33pub struct Plan {
34 pub files: Vec<NewFile>,
35 pub insertions: Vec<Insertion>,
36}
37
38impl Plan {
39 fn file(&mut self, path: impl Into<PathBuf>, contents: impl Into<String>) {
40 self.files.push(NewFile {
41 path: path.into(),
42 contents: contents.into(),
43 });
44 }
45
46 fn insert(&mut self, path: impl Into<PathBuf>, marker: &'static str, line: impl Into<String>) {
47 self.insertions.push(Insertion {
48 path: path.into(),
49 marker,
50 line: line.into(),
51 });
52 }
53
54 pub fn touched(&self) -> BTreeSet<&Path> {
56 self.files
57 .iter()
58 .map(|file| file.path.as_path())
59 .chain(
60 self.insertions
61 .iter()
62 .map(|insertion| insertion.path.as_path()),
63 )
64 .collect()
65 }
66}
67
68pub const MARK_MODULES: &str = "// <luxid:modules>";
71pub const MARK_ROUTES: &str = "// <luxid:routes>";
72pub const MARK_MIGRATIONS: &str = "// <luxid:migrations>";
73pub const MARK_MIGRATION_MODULES: &str = "// <luxid:migration-modules>";
74
75#[derive(Debug, Clone)]
79pub enum Dependency {
80 Version(String),
82 Path(String),
84}
85
86impl Dependency {
87 fn luxid(&self) -> String {
88 match self {
89 Self::Version(version) => format!("luxid = \"{version}\""),
90 Self::Path(root) => format!("luxid = {{ path = \"{root}/crates/luxid\" }}"),
91 }
92 }
93
94 fn testing(&self) -> String {
95 match self {
96 Self::Version(version) => format!("luxid-testing = \"{version}\""),
97 Self::Path(root) => {
98 format!("luxid-testing = {{ path = \"{root}/crates/luxid-testing\" }}")
99 }
100 }
101 }
102}
103
104#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
112pub enum Stack {
113 #[default]
115 Api,
116 Inertia(Client),
119}
120
121#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
123pub enum Client {
124 #[default]
125 React,
126 Vue,
127 Svelte,
128}
129
130impl Client {
131 pub fn label(self) -> &'static str {
132 match self {
133 Self::React => "react",
134 Self::Vue => "vue",
135 Self::Svelte => "svelte",
136 }
137 }
138
139 pub fn parse(raw: &str) -> Option<Self> {
140 match raw.trim().to_ascii_lowercase().as_str() {
141 "react" => Some(Self::React),
142 "vue" => Some(Self::Vue),
143 "svelte" => Some(Self::Svelte),
144 _ => None,
145 }
146 }
147
148 fn entry_ext(self) -> &'static str {
151 match self {
152 Self::React => "jsx",
154 Self::Vue | Self::Svelte => "js",
155 }
156 }
157
158 fn entry(self) -> String {
159 format!("resources/js/app.{}", self.entry_ext())
160 }
161
162 fn page_ext(self) -> &'static str {
164 match self {
165 Self::React => "jsx",
166 Self::Vue => "vue",
167 Self::Svelte => "svelte",
168 }
169 }
170}
171
172pub fn new_app(name: &str, dependency: &Dependency, stack: Stack) -> Plan {
173 let mut plan = Plan::default();
174 let crate_name = crate::naming::to_snake(name);
175
176 plan.file(
177 "Cargo.toml",
178 format!(
179 r#"[package]
180name = "{crate_name}"
181version = "0.1.0"
182edition = "2024"
183
184# Declares this package its own workspace root, so `luxid new` works inside an
185# existing workspace — a monorepo, or the Luxid checkout itself. Without it
186# Cargo refuses to build ("believes it's in a workspace when it's not"), and
187# the `[profile]` sections below are ignored rather than applied.
188[workspace]
189
190[dependencies]
191{}
192migration = {{ path = "migration" }}
193
194tokio = {{ version = "1", features = ["macros", "rt-multi-thread"] }}
195serde = {{ version = "1", features = ["derive"] }}
196serde_json = "1"
197sea-orm = {{ version = "2.0", features = [
198 "macros",
199 "runtime-tokio-rustls",
200 "sqlx-sqlite",
201 "sqlx-postgres",
202 "with-chrono",
203] }}
204dotenvy = "0.15"
205
206# Declared directly because their derive macros emit crate-qualified paths:
207# re-exporting them through `luxid` is not enough for `#[derive(..)]` to resolve.
208schemars = "1.2"
209
210[dev-dependencies]
211{}
212
213[profile.dev]
214opt-level = 0
215
216# Dependencies are built optimised once; your own crate stays quick to rebuild.
217[profile.dev.package."*"]
218opt-level = 3
219"#,
220 dependency.luxid(),
221 dependency.testing(),
222 ),
223 );
224
225 plan.file(
226 "migration/Cargo.toml",
227 r#"[package]
228name = "migration"
229version = "0.1.0"
230edition = "2024"
231publish = false
232
233[dependencies]
234sea-orm-migration = { version = "2.0", default-features = false, features = [
235 "runtime-tokio-rustls",
236 "sqlx-sqlite",
237 "sqlx-postgres",
238] }
239"#,
240 );
241
242 plan.file(
243 "migration/src/lib.rs",
244 format!(
245 r#"pub use sea_orm_migration::prelude::*;
246
247{MARK_MIGRATION_MODULES}
248
249pub struct Migrator;
250
251#[async_trait::async_trait]
252impl MigratorTrait for Migrator {{
253 fn migrations() -> Vec<Box<dyn MigrationTrait>> {{
254 vec![
255 {MARK_MIGRATIONS}
256 ]
257 }}
258}}
259"#
260 ),
261 );
262
263 plan.file(
264 "src/main.rs",
265 r#"mod app;
266mod config;
267mod controllers;
268mod entities;
269mod factories;
270mod middleware;
271mod models;
272mod policies;
273mod routes;
274mod seeders;
275mod services;
276mod validators;
277
278#[tokio::main]
279async fn main() -> luxid::Result<()> {
280 let _ = dotenvy::dotenv();
281
282 // `cargo run` serves; `cargo luxid routes`, `migrate`, `openapi`
283 // and friends are all the same binary.
284 luxid::cli::run::<migration::Migrator>(app::build().await?).await
285}
286"#,
287 );
288
289 match stack {
291 Stack::Api => api_shell(&mut plan),
292 Stack::Inertia(client) => inertia_shell(&mut plan, &crate_name, client),
293 }
294
295 plan.file(
296 "src/controllers/health_controller.rs",
297 r#"use luxid::prelude::*;
298use serde_json::json;
299
300pub struct HealthController;
301
302#[luxid::controller]
303impl HealthController {
304 #[openapi(summary = "Liveness probe", tag = "system")]
305 async fn show(ctx: HttpContext) -> Result<Response> {
306 ctx.response.ok(json!({ "status": "ok" }))
307 }
308}
309"#,
310 );
311
312 for module in ["models", "entities", "validators", "services", "middleware"] {
315 plan.file(format!("src/{module}/mod.rs"), format!("{MARK_MODULES}\n"));
316 }
317
318 for module in ["policies", "factories", "seeders"] {
323 plan.file(
324 format!("src/{module}/mod.rs"),
325 format!("#![allow(dead_code)]\n\n{MARK_MODULES}\n"),
326 );
327 }
328
329 plan.file(
330 "src/config/mod.rs",
331 r#"//! Application configuration. Read from the environment here, and bind the
332//! result as a singleton in `app::providers` so actions can resolve it.
333"#,
334 );
335
336 plan.file(
337 ".env.example",
338 r#"# Copy to .env and adjust. These override luxid.toml.
339DATABASE_URL=sqlite://./app.db?mode=rwc
340APP_KEY=change-me-before-deploying
341LUXID_ADDR=127.0.0.1:3000
342"#,
343 );
344
345 plan.file(
346 ".gitignore",
347 match stack {
348 Stack::Api => "/target\n/app.db\n/app.db-*\n.env\n".to_owned(),
349 Stack::Inertia(_) => {
352 "/target\n/app.db\n/app.db-*\n.env\n/node_modules\n/public/build\n".to_owned()
353 }
354 },
355 );
356
357 plan.file(
358 "luxid.toml",
359 format!(
360 r#"# Read at boot by `app::build`, and available in any action as
361# `ctx.config`. Environment variables override these: `app.name` is also
362# `APP_NAME`, `database.url` is also `DATABASE_URL`.
363
364[app]
365name = "{crate_name}"
366per_page = 20
367
368[database]
369# url = "postgres://localhost/{crate_name}"
370
371# Reading a relation that was not eager-loaded becomes an error.
372strict_relations = true
373"#
374 ),
375 );
376
377 plan.file(
387 ".cargo/config.toml",
388 r#"# `cargo luxid <command>` runs this application's own command line.
389#
390# It expands to `cargo run --`, so `cargo luxid migrate` and
391# `cargo run -- migrate` are the same thing. Copy this section into any
392# existing project to get the shorter form.
393[alias]
394luxid = "run --"
395
396# A faster linker is the single biggest lever on rebuild time.
397#
398# Uncomment after installing mold (https://github.com/rui314/mold), or swap in
399# `lld`. Left off by default so this project builds anywhere.
400#
401# [target.x86_64-unknown-linux-gnu]
402# rustflags = ["-C", "link-arg=-fuse-ld=mold", "-C", "debuginfo=1"]
403"#,
404 );
405
406 plan.file(
407 "README.md",
408 match stack {
409 Stack::Api => format!(
410 r#"# {crate_name}
411
412```sh
413cargo run # serve on http://127.0.0.1:3000
414cargo luxid routes # the routing table
415cargo luxid migrate # apply migrations
416cargo luxid openapi # the OpenAPI 3.1 document
417```
418
419Generated by `luxid new`.
420"#
421 ),
422 Stack::Inertia(client) => format!(
423 r#"# {crate_name}
424
425Server-driven pages over the [Inertia.js](https://inertiajs.com) protocol, with
426a {client} client. Controllers return components and props; there is no API
427client, no client-side router and no CORS.
428
429## Running it
430
431Two terminals.
432
433```sh
434npm install
435npm run dev # Vite on http://localhost:5173
436```
437
438```sh
439cargo luxid migrate # apply migrations
440cargo run # serve on http://127.0.0.1:3000
441```
442
443Open http://127.0.0.1:3000 — the Rust server, not Vite. Vite only serves the
444JavaScript modules the page asks for, and hot-reloads them.
445
446```sh
447cargo luxid routes # the routing table
448cargo luxid openapi # the OpenAPI 3.1 document (the /api group)
449```
450
451## How a page works
452
453`src/controllers/pages_controller.rs` renders a component by name:
454
455```rust
456ctx.inertia("Home", json!({{ "app": "{crate_name}" }}))
457```
458
459`"Home"` resolves to `resources/js/Pages/Home.{page_ext}`, and the props arrive
460as that component's props. A fresh browser load gets an HTML shell with the page
461embedded in `data-page`; a link click gets JSON. The action does not know which.
462
463## Forms and validation
464
465Validation failures are **not** a 422 here. The Inertia middleware flashes the
466errors to the session and redirects back, and they arrive on the next page as
467the shared `errors` prop — the post-redirect-get pattern the client adapters
468expect.
469
470The `/api` group has no Inertia middleware, so the same action and the same
471validator answer a JSON client with the ordinary 422 problem document.
472
473## Deploying
474
475```sh
476npm run build # writes public/build + its manifest
477cargo build --release
478```
479
480A release build reads `public/build/.vite/manifest.json` for the hashed
481filenames instead of talking to Vite, and `src/routes.rs` serves that directory
482at `/build`. Bump the `.version(..)` in `src/routes.rs` on each deploy so open
483tabs reload rather than requesting a bundle that no longer exists.
484
485Generated by `luxid new --stack inertia --client {client}`.
486"#,
487 client = client.label(),
488 page_ext = client.page_ext(),
489 ),
490 },
491 );
492
493 plan
494}
495
496fn api_shell(plan: &mut Plan) {
498 plan.file(
499 "src/app.rs",
500 r#"use luxid::prelude::*;
501
502/// Assemble the application: configuration, services, middleware, routes.
503pub async fn build() -> luxid::Result<App> {
504 // luxid.toml, with the environment layered over it.
505 let config = Config::load("luxid.toml")?;
506
507 // Accessing a relation that was not eager-loaded becomes an error, which
508 // turns an N+1 into a failing test rather than a production surprise.
509 luxid::set_strict_relations(config.get_or("database.strict_relations", cfg!(debug_assertions))?);
510
511 // SQLite by default so a fresh app runs with no infrastructure. Point
512 // DATABASE_URL at Postgres when you want one.
513 let url = config
514 .get_or("database.url", "sqlite://./app.db?mode=rwc".to_owned())?;
515
516 let db = Db::connect(url).await?;
517
518 Ok(App::new()
519 .config(config)
520 .providers(providers(db))
521 .middleware(WithDatabase)
522 .routes(crate::routes::register))
523}
524
525fn providers(db: Db) -> Providers {
526 Providers::new().singleton(move |_| db.clone())
527}
528"#,
529 );
530
531 plan.file(
532 "src/routes.rs",
533 format!(
534 r#"use luxid::prelude::*;
535
536use crate::controllers;
537
538pub fn register(r: &mut Router) {{
539 r.group("/api", |r| {{
540 r.get("/health", controllers::health_controller::HealthController::show);
541
542 {MARK_ROUTES}
543 }});
544}}
545"#
546 ),
547 );
548
549 plan.file(
550 "src/controllers/mod.rs",
551 format!("pub mod health_controller;\n\n{MARK_MODULES}\n"),
552 );
553}
554
555fn inertia_shell(plan: &mut Plan, crate_name: &str, client: Client) {
558 let entry = client.entry();
559
560 plan.file(
561 "src/app.rs",
562 r#"use std::sync::Arc;
563
564use luxid::prelude::*;
565
566/// Assemble the application: configuration, services, middleware, routes.
567pub async fn build() -> luxid::Result<App> {
568 // luxid.toml, with the environment layered over it.
569 let config = Config::load("luxid.toml")?;
570
571 // Accessing a relation that was not eager-loaded becomes an error, which
572 // turns an N+1 into a failing test rather than a production surprise.
573 luxid::set_strict_relations(config.get_or("database.strict_relations", cfg!(debug_assertions))?);
574
575 // SQLite by default so a fresh app runs with no infrastructure. Point
576 // DATABASE_URL at Postgres when you want one.
577 let url = config
578 .get_or("database.url", "sqlite://./app.db?mode=rwc".to_owned())?;
579
580 let db = Db::connect(url).await?;
581
582 Ok(App::new()
583 .config(config)
584 .providers(providers(db))
585 .middleware(WithDatabase)
586 .routes(crate::routes::register))
587}
588
589fn providers(db: Db) -> Providers {
590 Providers::new()
591 .singleton(move |_| db.clone())
592 // Inertia is session-based: validation errors are flashed to the
593 // session and read back after a redirect.
594 //
595 // `MemoryStore` keeps sessions in this process, so every restart signs
596 // everybody out and a second instance shares nothing. Fine for
597 // development; swap in a database- or cache-backed `SessionStore`
598 // before running more than one process.
599 .bind::<dyn SessionStore, _>(|_| Arc::new(MemoryStore::new()))
600}
601"#,
602 );
603
604 plan.file(
605 "src/routes.rs",
606 format!(
607 r#"use luxid::prelude::*;
608
609use crate::controllers;
610
611pub fn register(r: &mut Router) {{
612 // The built frontend. In development the Vite dev server serves these
613 // files instead, so this route goes unused until `npm run build`.
614 r.static_files("/build", "public/build");
615
616 // ---- Inertia pages ------------------------------------------------
617 //
618 // Ordering is load-bearing. `Auth::session()` must be OUTSIDE `Inertia`:
619 // the session guard writes back with `next.run(ctx).await?`, so it never
620 // sees an `Err`. Inertia converts a validation failure into a redirect
621 // before that happens, which is what lets the flashed errors survive.
622 r.group("/", |r| {{
623 r.middleware(Auth::session());
624 r.middleware(
625 Inertia::new("{entry}")
626 .title("{crate_name}")
627 // Bump on deploy so open tabs hard-reload instead of asking
628 // for a bundle that no longer exists.
629 .version(env!("CARGO_PKG_VERSION")),
630 );
631
632 r.get("/", controllers::pages_controller::PagesController::home);
633 }});
634
635 // ---- JSON API -----------------------------------------------------
636 //
637 // Unchanged by Inertia. The same action and the same validator can serve
638 // both: a request here answers a validation failure with a 422 problem
639 // document, because this group has no Inertia middleware.
640 r.group("/api", |r| {{
641 r.get("/health", controllers::health_controller::HealthController::show);
642
643 {MARK_ROUTES}
644 }});
645}}
646"#
647 ),
648 );
649
650 plan.file(
651 "src/controllers/mod.rs",
652 format!("pub mod health_controller;\npub mod pages_controller;\n\n{MARK_MODULES}\n"),
653 );
654
655 plan.file(
656 "src/controllers/pages_controller.rs",
657 format!(
658 r#"use luxid::prelude::*;
659use serde_json::json;
660
661pub struct PagesController;
662
663#[luxid::controller]
664impl PagesController {{
665 /// `GET /`
666 ///
667 /// `ctx.inertia(..)` serves both a fresh browser load (an HTML shell with
668 /// the page embedded in `data-page`) and an Inertia navigation (JSON). The
669 /// action does not know or care which — that is the whole point.
670 ///
671 /// The component name is a path under `resources/js/Pages`, so "Home"
672 /// resolves to `resources/js/Pages/Home.{page_ext}`.
673 async fn home(ctx: HttpContext) -> Result<Response> {{
674 ctx.inertia("Home", json!({{ "app": "{crate_name}" }}))
675 }}
676}}
677"#,
678 page_ext = client.page_ext(),
679 ),
680 );
681
682 frontend(plan, crate_name, client);
683}
684
685fn frontend(plan: &mut Plan, crate_name: &str, client: Client) {
687 let entry = client.entry();
688 let entry_ext = client.entry_ext();
689 let page_ext = client.page_ext();
690
691 let (deps, dev_deps) = match client {
694 Client::React => (
695 r#""@inertiajs/react": "^2.0.0",
696 "react": "^18.3.1",
697 "react-dom": "^18.3.1""#,
698 r#""@vitejs/plugin-react": "^4.3.4",
699 "vite": "^6.0.7""#,
700 ),
701 Client::Vue => (
702 r#""@inertiajs/vue3": "^2.0.0",
703 "vue": "^3.5.13""#,
704 r#""@vitejs/plugin-vue": "^5.2.1",
705 "vite": "^6.0.7""#,
706 ),
707 Client::Svelte => (
708 r#""@inertiajs/svelte": "^2.0.0",
709 "svelte": "^5.16.0""#,
710 r#""@sveltejs/vite-plugin-svelte": "^5.0.3",
711 "vite": "^6.0.7""#,
712 ),
713 };
714
715 plan.file(
716 "package.json",
717 format!(
718 r#"{{
719 "name": "{crate_name}",
720 "private": true,
721 "type": "module",
722 "scripts": {{
723 "dev": "vite",
724 "build": "vite build"
725 }},
726 "dependencies": {{
727 {deps}
728 }},
729 "devDependencies": {{
730 {dev_deps}
731 }}
732}}
733"#
734 ),
735 );
736
737 let (plugin_import, plugin_call) = match client {
740 Client::React => ("import react from '@vitejs/plugin-react'", "react()"),
741 Client::Vue => ("import vue from '@vitejs/plugin-vue'", "vue()"),
742 Client::Svelte => (
743 "import { svelte } from '@sveltejs/vite-plugin-svelte'",
744 "svelte()",
745 ),
746 };
747
748 plan.file(
749 "vite.config.js",
750 format!(
751 r#"import {{ defineConfig }} from 'vite'
752{plugin_import}
753
754// The server reads `public/build/.vite/manifest.json` to find the hashed
755// filenames, so `manifest`, `outDir` and `input` must stay in step with
756// `Inertia::new(..)` in src/routes.rs.
757export default defineConfig(({{ command }}) => ({{
758 plugins: [{plugin_call}],
759
760 // Only on build. In development Vite serves from its own root, and a base
761 // here would break the dev-server URLs the HTML shell emits.
762 base: command === 'build' ? '/build/' : '/',
763
764 build: {{
765 manifest: true,
766 outDir: 'public/build',
767 emptyOutDir: true,
768 rollupOptions: {{ input: '{entry}' }},
769 }},
770
771 server: {{
772 // Pinned: the shell hardcodes this origin in development. `strictPort`
773 // makes a clash fail loudly rather than silently moving to 5174 and
774 // serving a page whose scripts 404.
775 port: 5173,
776 strictPort: true,
777 }},
778}}))
779"#
780 ),
781 );
782
783 let entry_source = match client {
786 Client::React => format!(
787 r#"import {{ createInertiaApp }} from '@inertiajs/react'
788import {{ createRoot }} from 'react-dom/client'
789
790import '../css/app.css'
791
792// `createInertiaApp` reads the page object the server embedded in
793// `<div id="app" data-page="...">`, resolves the named component, and takes
794// over navigation from there. There is no client-side route table: the server
795// decides which component renders, exactly as it would with templates.
796createInertiaApp({{
797 // Eagerly bundling every page keeps this scaffold simple. Swap `eager: true`
798 // for a dynamic import once the app is big enough to want code splitting.
799 resolve: (name) => {{
800 const pages = import.meta.glob('./Pages/**/*.{page_ext}', {{ eager: true }})
801
802 return pages[`./Pages/${{name}}.{page_ext}`]
803 }},
804
805 setup({{ el, App, props }}) {{
806 createRoot(el).render(<App {{...props}} />)
807 }},
808}})
809"#
810 ),
811 Client::Vue => format!(
812 r#"import {{ createInertiaApp }} from '@inertiajs/vue3'
813import {{ createApp, h }} from 'vue'
814
815import '../css/app.css'
816
817// `createInertiaApp` reads the page object the server embedded in
818// `<div id="app" data-page="...">`, resolves the named component, and takes
819// over navigation from there. There is no client-side route table: the server
820// decides which component renders, exactly as it would with templates.
821createInertiaApp({{
822 // Eagerly bundling every page keeps this scaffold simple. Swap `eager: true`
823 // for a dynamic import once the app is big enough to want code splitting.
824 resolve: (name) => {{
825 const pages = import.meta.glob('./Pages/**/*.{page_ext}', {{ eager: true }})
826
827 return pages[`./Pages/${{name}}.{page_ext}`]
828 }},
829
830 setup({{ el, App, props, plugin }}) {{
831 createApp({{ render: () => h(App, props) }})
832 .use(plugin)
833 .mount(el)
834 }},
835}})
836"#
837 ),
838 Client::Svelte => format!(
839 r#"import {{ createInertiaApp }} from '@inertiajs/svelte'
840import {{ mount }} from 'svelte'
841
842import '../css/app.css'
843
844// `createInertiaApp` reads the page object the server embedded in
845// `<div id="app" data-page="...">`, resolves the named component, and takes
846// over navigation from there. There is no client-side route table: the server
847// decides which component renders, exactly as it would with templates.
848createInertiaApp({{
849 // Eagerly bundling every page keeps this scaffold simple. Swap `eager: true`
850 // for a dynamic import once the app is big enough to want code splitting.
851 resolve: (name) => {{
852 const pages = import.meta.glob('./Pages/**/*.{page_ext}', {{ eager: true }})
853
854 return pages[`./Pages/${{name}}.{page_ext}`]
855 }},
856
857 setup({{ el, App, props }}) {{
858 mount(App, {{ target: el, props }})
859 }},
860}})
861"#
862 ),
863 };
864
865 plan.file(format!("resources/js/app.{entry_ext}"), entry_source);
866
867 let page = match client {
870 Client::React => r#"// Props come from `ctx.inertia("Home", json!({ .. }))` in
871// src/controllers/pages_controller.rs. No fetch, no loading state, no API
872// client: the server rendered this page's data into the response that carried
873// the component name.
874export default function Home({ app, errors }) {
875 return (
876 <main>
877 <h1>{app}</h1>
878 <p>Inertia is working. Edit resources/js/Pages/Home.jsx.</p>
879
880 {/* `errors` is a shared prop, present on every page. After a failed
881 form submit the server redirects back and it arrives populated. */}
882 {errors && Object.keys(errors).length > 0 && (
883 <pre>{JSON.stringify(errors, null, 2)}</pre>
884 )}
885 </main>
886 )
887}
888"#
889 .to_owned(),
890 Client::Vue => r#"<script setup>
891// Props come from `ctx.inertia("Home", json!({ .. }))` in
892// src/controllers/pages_controller.rs. No fetch, no loading state, no API
893// client: the server rendered this page's data into the response that carried
894// the component name.
895defineProps({
896 app: String,
897 // A shared prop, present on every page. After a failed form submit the
898 // server redirects back and it arrives populated.
899 errors: { type: Object, default: () => ({}) },
900})
901</script>
902
903<template>
904 <main>
905 <h1>{{ app }}</h1>
906 <p>Inertia is working. Edit resources/js/Pages/Home.vue.</p>
907
908 <pre v-if="Object.keys(errors).length">{{ errors }}</pre>
909 </main>
910</template>
911"#
912 .to_owned(),
913 Client::Svelte => r#"<script>
914 // Props come from `ctx.inertia("Home", json!({ .. }))` in
915 // src/controllers/pages_controller.rs. No fetch, no loading state, no API
916 // client: the server rendered this page's data into the response that
917 // carried the component name.
918 //
919 // `errors` is a shared prop, present on every page. After a failed form
920 // submit the server redirects back and it arrives populated.
921 let { app, errors = {} } = $props()
922</script>
923
924<main>
925 <h1>{app}</h1>
926 <p>Inertia is working. Edit resources/js/Pages/Home.svelte.</p>
927
928 {#if Object.keys(errors).length}
929 <pre>{JSON.stringify(errors, null, 2)}</pre>
930 {/if}
931</main>
932"#
933 .to_owned(),
934 };
935
936 plan.file(format!("resources/js/Pages/Home.{page_ext}"), page);
937
938 plan.file(
939 "resources/css/app.css",
940 r#":root {
941 color-scheme: light dark;
942}
943
944body {
945 margin: 0;
946 padding: 2rem;
947 font: 15px/1.6 ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif;
948}
949
950main {
951 max-width: 40rem;
952 margin: 0 auto;
953}
954"#,
955 );
956}
957
958#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
962pub struct ModelFlags {
963 pub migration: bool,
964 pub factory: bool,
965 pub seeder: bool,
966 pub controller: bool,
967 pub policy: bool,
968 pub requests: bool,
969}
970
971impl ModelFlags {
972 pub fn all() -> Self {
974 Self {
975 migration: true,
976 factory: true,
977 seeder: true,
978 controller: true,
979 policy: true,
980 requests: true,
981 }
982 }
983}
984
985pub fn make_model(names: &Names, flags: ModelFlags, timestamp: &str) -> Plan {
986 let mut plan = Plan::default();
987 let Names {
988 model,
989 snake,
990 plural,
991 ..
992 } = names;
993
994 plan.file(
995 format!("src/models/{snake}.rs"),
996 format!(
997 r#"pub use crate::entities::{plural}::Model as {model};
998
999// Relations, scopes and hooks go here. Declare relations in the attribute and
1000// scopes as `#[scope]` functions:
1001//
1002// #[luxid::model(has_many(posts = Post, fk = "{snake}_id"))]
1003// impl {model} {{
1004// #[scope]
1005// fn active(query: Query<crate::entities::{plural}::Entity>)
1006// -> Query<crate::entities::{plural}::Entity>
1007// {{
1008// query.where_null({model}::deleted_at)
1009// }}
1010// }}
1011#[luxid::model()]
1012impl {model} {{}}
1013"#
1014 ),
1015 );
1016 plan.insert(
1017 "src/models/mod.rs",
1018 MARK_MODULES,
1019 format!("pub mod {snake};"),
1020 );
1021
1022 plan.file(
1025 format!("src/entities/{plural}.rs"),
1026 format!(
1027 r#"//! Generated from the database schema. Re-run `luxid db:sync` after a
1028//! migration rather than editing this by hand.
1029
1030use sea_orm::entity::prelude::*;
1031
1032#[derive(Clone, Debug, PartialEq, DeriveEntityModel, serde::Serialize, luxid::Model)]
1033#[sea_orm(table_name = "{plural}")]
1034pub struct Model {{
1035 // <luxid:fields> refreshed by `cargo luxid db:sync`
1036 #[sea_orm(primary_key)]
1037 pub id: i64,
1038 // </luxid:fields>
1039 #[sea_orm(ignore)]
1040 #[serde(flatten)]
1041 pub relations: luxid::Relations,
1042}}
1043
1044#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
1045pub enum Relation {{}}
1046
1047impl ActiveModelBehavior for ActiveModel {{}}
1048"#
1049 ),
1050 );
1051 plan.insert(
1052 "src/entities/mod.rs",
1053 MARK_MODULES,
1054 format!("pub mod {plural};"),
1055 );
1056
1057 if flags.migration {
1058 let migration = format!("m{timestamp}_create_{plural}");
1059
1060 plan.file(
1061 format!("migration/src/{migration}.rs"),
1062 format!(
1063 r#"use sea_orm_migration::prelude::*;
1064use sea_orm_migration::schema::*;
1065
1066#[derive(DeriveIden)]
1067enum {} {{
1068 Table,
1069 Id,
1070}}
1071
1072pub struct Migration;
1073
1074impl MigrationName for Migration {{
1075 fn name(&self) -> &str {{
1076 "{migration}"
1077 }}
1078}}
1079
1080#[async_trait::async_trait]
1081impl MigrationTrait for Migration {{
1082 async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {{
1083 manager
1084 .create_table(
1085 Table::create()
1086 .table({0}::Table)
1087 .if_not_exists()
1088 .col(pk_auto({0}::Id))
1089 // Add your columns here.
1090 .to_owned(),
1091 )
1092 .await
1093 }}
1094
1095 async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {{
1096 manager.drop_table(Table::drop().table({0}::Table).to_owned()).await
1097 }}
1098}}
1099"#,
1100 crate::naming::to_pascal(plural)
1101 ),
1102 );
1103
1104 plan.insert(
1105 "migration/src/lib.rs",
1106 MARK_MIGRATION_MODULES,
1107 format!("mod {migration};"),
1108 );
1109 plan.insert(
1110 "migration/src/lib.rs",
1111 MARK_MIGRATIONS,
1112 format!("Box::new({migration}::Migration),"),
1113 );
1114 }
1115
1116 if flags.requests {
1117 let store = &names.store_request;
1118 let update = &names.update_request;
1119
1120 plan.file(
1121 format!("src/validators/{snake}.rs"),
1122 format!(
1123 r#"use luxid::prelude::*;
1124use serde::Deserialize;
1125
1126// `JsonSchema` lets `#[openapi(body = ..)]` describe this request.
1127#[derive(Debug, Deserialize, Validate, luxid::JsonSchema)]
1128pub struct {store} {{
1129 // #[validate(length(min = 1, max = 255))]
1130 // pub name: String,
1131}}
1132
1133#[derive(Debug, Deserialize, Validate, luxid::JsonSchema)]
1134pub struct {update} {{
1135 // #[validate(length(min = 1, max = 255))]
1136 // pub name: Option<String>,
1137}}
1138"#
1139 ),
1140 );
1141 plan.insert(
1142 "src/validators/mod.rs",
1143 MARK_MODULES,
1144 format!("pub mod {snake};"),
1145 );
1146 }
1147
1148 if flags.policy {
1149 let policy = &names.policy;
1150
1151 plan.file(
1152 format!("src/policies/{snake}_policy.rs"),
1153 format!(
1154 r#"use luxid::prelude::*;
1155
1156use crate::models::{snake}::{model};
1157
1158pub struct {policy};
1159
1160/// A policy is an ordinary function of `(&Auth, &T) -> bool`. Enforce one with
1161/// `ctx.authorize({policy}::update, &{snake})?`, or ask without consequence
1162/// with `ctx.can({policy}::update, &{snake})`.
1163impl {policy} {{
1164 pub fn view(_auth: &Auth, _{snake}: &{model}) -> bool {{
1165 true
1166 }}
1167
1168 pub fn update(auth: &Auth, {snake}: &{model}) -> bool {{
1169 // Replace with your rule, e.g. comparing the owner to the identity.
1170 let _ = {snake};
1171 auth.check()
1172 }}
1173}}
1174"#
1175 ),
1176 );
1177 plan.insert(
1178 "src/policies/mod.rs",
1179 MARK_MODULES,
1180 format!("pub mod {snake}_policy;"),
1181 );
1182 }
1183
1184 if flags.factory {
1185 let factory = &names.factory;
1186
1187 plan.file(
1188 format!("src/factories/{snake}_factory.rs"),
1189 format!(
1190 r#"use luxid::prelude::*;
1191
1192// Used by the field list below, which `cargo luxid db:sync` fills in from the
1193// live schema. Allowed rather than left to warn: a table whose columns are all
1194// nullable syncs to an empty list, so the import can be legitimately unused.
1195#[allow(unused_imports)]
1196use sea_orm::ActiveValue::Set;
1197
1198use crate::entities::{plural};
1199
1200/// The typical {model}. Tests override only what they care about:
1201///
1202/// ```ignore
1203/// {factory}::new().create_one().await?;
1204/// {factory}::new().count(3).create().await?;
1205/// {factory}::new().state(|row| row.name = Set("Ada".into())).create_one().await?;
1206/// ```
1207pub struct {factory};
1208
1209impl Factory for {factory} {{
1210 type Active = {plural}::ActiveModel;
1211
1212 fn definition() -> Self::Active {{
1213 {plural}::ActiveModel {{
1214 // <luxid:fields> refreshed by `cargo luxid db:sync`
1215 // </luxid:fields>
1216 ..Default::default()
1217 }}
1218 }}
1219}}
1220"#
1221 ),
1222 );
1223 plan.insert(
1224 "src/factories/mod.rs",
1225 MARK_MODULES,
1226 format!("pub mod {snake}_factory;"),
1227 );
1228 }
1229
1230 if flags.seeder {
1231 let seeder = &names.seeder;
1232 let factory = &names.factory;
1233
1234 plan.file(
1235 format!("src/seeders/{snake}_seeder.rs"),
1236 format!(
1237 r#"use luxid::prelude::*;
1238
1239use crate::factories::{snake}_factory::{factory};
1240
1241pub struct {seeder};
1242
1243impl {seeder} {{
1244 pub async fn run() -> luxid::Result<()> {{
1245 {factory}::new().count(10).create().await?;
1246 Ok(())
1247 }}
1248}}
1249"#
1250 ),
1251 );
1252 plan.insert(
1253 "src/seeders/mod.rs",
1254 MARK_MODULES,
1255 format!("pub mod {snake}_seeder;"),
1256 );
1257 }
1258
1259 if flags.controller {
1260 let controller = &names.controller;
1261 let controller_file = &names.controller_file;
1262
1263 plan.file(
1264 format!("src/controllers/{controller_file}.rs"),
1265 format!(
1266 r#"use luxid::prelude::*;
1267
1268use crate::models::{snake}::{model};
1269
1270pub struct {controller};
1271
1272#[luxid::controller]
1273impl {controller} {{
1274 #[openapi(tag = "{plural}")]
1275 async fn index(ctx: HttpContext) -> Result<Response> {{
1276 let page = ctx.request.input::<u64>("page")?.unwrap_or(1);
1277
1278 ctx.response.ok({model}::query().paginate(page, 20).await?)
1279 }}
1280
1281 #[openapi(tag = "{plural}", errors = [404])]
1282 async fn show(ctx: HttpContext) -> Result<Response> {{
1283 let id: i64 = ctx.params.get("id")?;
1284
1285 ctx.response.ok({model}::find_or_fail(id).await?)
1286 }}
1287
1288 #[openapi(tag = "{plural}", errors = [422])]
1289 async fn store(ctx: HttpContext) -> Result<Response> {{
1290 let _input = ctx.request.validate::<crate::validators::{snake}::{}>().await?;
1291
1292 ctx.response.status(501).json("not implemented")
1293 }}
1294
1295 #[openapi(tag = "{plural}", errors = [404, 422])]
1296 async fn update(ctx: HttpContext) -> Result<Response> {{
1297 let id: i64 = ctx.params.get("id")?;
1298 let existing = {model}::find_or_fail(id).await?;
1299
1300 ctx.authorize(crate::policies::{snake}_policy::{}::update, &existing)?;
1301
1302 let _input = ctx.request.validate::<crate::validators::{snake}::{}>().await?;
1303
1304 ctx.response.status(501).json("not implemented")
1305 }}
1306
1307 #[openapi(tag = "{plural}", no_content, errors = [404])]
1308 async fn destroy(ctx: HttpContext) -> Result<Response> {{
1309 let id: i64 = ctx.params.get("id")?;
1310 {model}::find_or_fail(id).await?;
1311
1312 ctx.response.no_content()
1313 }}
1314}}
1315"#,
1316 names.store_request, names.policy, names.update_request
1317 ),
1318 );
1319 plan.insert(
1320 "src/controllers/mod.rs",
1321 MARK_MODULES,
1322 format!("pub mod {controller_file};"),
1323 );
1324
1325 plan.insert(
1327 "src/routes.rs",
1328 MARK_ROUTES,
1329 format!("r.resource(\"/{plural}\", controllers::{controller_file}::{controller});"),
1330 );
1331 }
1332
1333 plan
1334}
1335
1336pub fn write(plan: &Plan, root: &Path) -> Result<Vec<PathBuf>> {
1343 let mut clashes = Vec::new();
1344 for file in &plan.files {
1345 if root.join(&file.path).exists() {
1346 clashes.push(file.path.display().to_string());
1347 }
1348 }
1349
1350 if !clashes.is_empty() {
1351 return Err(Error::internal(format!(
1352 "these files already exist, so nothing was written: {}",
1353 clashes.join(", ")
1354 )));
1355 }
1356
1357 let mut written = Vec::new();
1358
1359 for file in &plan.files {
1360 let target = root.join(&file.path);
1361
1362 if let Some(parent) = target.parent() {
1363 std::fs::create_dir_all(parent)
1364 .map_err(|err| Error::internal(format!("could not create {parent:?}: {err}")))?;
1365 }
1366
1367 std::fs::write(&target, &file.contents)
1368 .map_err(|err| Error::internal(format!("could not write {target:?}: {err}")))?;
1369
1370 written.push(file.path.clone());
1371 }
1372
1373 for insertion in &plan.insertions {
1374 let target = root.join(&insertion.path);
1375
1376 let existing = std::fs::read_to_string(&target)
1377 .map_err(|err| Error::internal(format!("could not read {target:?}: {err}")))?;
1378
1379 let updated = apply(&existing, insertion.marker, &insertion.line).ok_or_else(|| {
1380 Error::internal(format!(
1381 "{:?} has no `{}` marker, so there is nowhere to register this. \
1382 Add the marker back, or wire it up by hand.",
1383 insertion.path, insertion.marker
1384 ))
1385 })?;
1386
1387 std::fs::write(&target, updated)
1388 .map_err(|err| Error::internal(format!("could not write {target:?}: {err}")))?;
1389
1390 written.push(insertion.path.clone());
1391 }
1392
1393 written.sort();
1394 written.dedup();
1395
1396 Ok(written)
1397}
1398
1399pub fn apply(source: &str, marker: &str, line: &str) -> Option<String> {
1404 let position = source.find(marker)?;
1405 let line_start = source[..position]
1406 .rfind('\n')
1407 .map(|index| index + 1)
1408 .unwrap_or(0);
1409 let indent = &source[line_start..position];
1410
1411 let inserted: String = line
1412 .lines()
1413 .map(|part| format!("{indent}{part}\n"))
1414 .collect::<Vec<_>>()
1415 .join("");
1416
1417 let mut out = String::with_capacity(source.len() + inserted.len());
1418 out.push_str(&source[..line_start]);
1419 out.push_str(&inserted);
1420 out.push_str(&source[line_start..]);
1421
1422 Some(out)
1423}
1424
1425#[cfg(test)]
1426mod tests {
1427 use super::*;
1428
1429 #[test]
1430 fn inserts_above_the_marker_with_its_indentation() {
1431 let source = "fn main() {\n let x = 1;\n // <luxid:routes>\n}\n";
1432 let updated = apply(source, MARK_ROUTES, "call_me();").expect("marker present");
1433
1434 assert_eq!(
1435 updated,
1436 "fn main() {\n let x = 1;\n call_me();\n // <luxid:routes>\n}\n"
1437 );
1438 }
1439
1440 #[test]
1441 fn repeated_insertion_keeps_order() {
1442 let source = "// <luxid:modules>\n";
1443 let once = apply(source, MARK_MODULES, "pub mod a;").expect("marker");
1444 let twice = apply(&once, MARK_MODULES, "pub mod b;").expect("marker");
1445
1446 assert_eq!(twice, "pub mod a;\npub mod b;\n// <luxid:modules>\n");
1447 }
1448
1449 #[test]
1450 fn multi_line_insertions_are_indented_line_by_line() {
1451 let source = " // <luxid:routes>\n";
1452 let updated = apply(source, MARK_ROUTES, "one();\ntwo();").expect("marker");
1453
1454 assert_eq!(
1455 updated,
1456 " one();\n two();\n // <luxid:routes>\n"
1457 );
1458 }
1459
1460 #[test]
1461 fn a_missing_marker_is_reported_rather_than_guessed() {
1462 assert!(apply("fn main() {}\n", MARK_ROUTES, "x();").is_none());
1463 }
1464
1465 #[test]
1466 fn a_new_app_carries_every_marker_make_model_needs() {
1467 let plan = new_app("my-app", &Dependency::Version("0.3".into()), Stack::Api);
1468
1469 let find = |path: &str| {
1470 plan.files
1471 .iter()
1472 .find(|file| file.path == Path::new(path))
1473 .unwrap_or_else(|| panic!("{path} missing from the plan"))
1474 };
1475
1476 assert!(find("src/routes.rs").contents.contains(MARK_ROUTES));
1477 assert!(find("src/models/mod.rs").contents.contains(MARK_MODULES));
1478 assert!(find("src/entities/mod.rs").contents.contains(MARK_MODULES));
1479 assert!(
1480 find("src/controllers/mod.rs")
1481 .contents
1482 .contains(MARK_MODULES)
1483 );
1484 assert!(find("src/factories/mod.rs").contents.contains(MARK_MODULES));
1485 assert!(find("src/seeders/mod.rs").contents.contains(MARK_MODULES));
1486 assert!(
1487 find("migration/src/lib.rs")
1488 .contents
1489 .contains(MARK_MIGRATIONS)
1490 );
1491 assert!(
1492 find("migration/src/lib.rs")
1493 .contents
1494 .contains(MARK_MIGRATION_MODULES)
1495 );
1496 }
1497
1498 fn assert_unique_paths(plan: &Plan) {
1501 let mut seen = std::collections::BTreeSet::new();
1502
1503 for file in &plan.files {
1504 assert!(
1505 seen.insert(file.path.clone()),
1506 "{} is planned twice",
1507 file.path.display()
1508 );
1509 }
1510 }
1511
1512 #[test]
1513 fn an_api_app_has_no_frontend() {
1514 let plan = new_app("shop", &Dependency::Version("0.3".into()), Stack::Api);
1515 assert_unique_paths(&plan);
1516
1517 let paths: Vec<_> = plan
1518 .touched()
1519 .iter()
1520 .map(|p| p.display().to_string())
1521 .collect();
1522
1523 assert!(
1524 !paths.iter().any(|p| p.starts_with("resources/")),
1525 "{paths:?}"
1526 );
1527 assert!(!paths.contains(&"package.json".to_owned()), "{paths:?}");
1528 assert!(!paths.contains(&"vite.config.js".to_owned()), "{paths:?}");
1529 }
1530
1531 #[test]
1532 fn each_client_scaffolds_its_own_entry_and_page() {
1533 for (client, entry, page) in [
1534 (
1535 Client::React,
1536 "resources/js/app.jsx",
1537 "resources/js/Pages/Home.jsx",
1538 ),
1539 (
1540 Client::Vue,
1541 "resources/js/app.js",
1542 "resources/js/Pages/Home.vue",
1543 ),
1544 (
1545 Client::Svelte,
1546 "resources/js/app.js",
1547 "resources/js/Pages/Home.svelte",
1548 ),
1549 ] {
1550 let plan = new_app(
1551 "shop",
1552 &Dependency::Version("0.3".into()),
1553 Stack::Inertia(client),
1554 );
1555 assert_unique_paths(&plan);
1556
1557 let paths: Vec<_> = plan
1558 .touched()
1559 .iter()
1560 .map(|p| p.display().to_string())
1561 .collect();
1562
1563 assert!(paths.contains(&entry.to_owned()), "{client:?}: {paths:?}");
1564 assert!(paths.contains(&page.to_owned()), "{client:?}: {paths:?}");
1565 assert!(paths.contains(&"package.json".to_owned()), "{client:?}");
1566 }
1567 }
1568
1569 #[test]
1570 fn the_vite_input_matches_the_entry_the_server_looks_up() {
1571 for client in [Client::React, Client::Vue, Client::Svelte] {
1575 let plan = new_app(
1576 "shop",
1577 &Dependency::Version("0.3".into()),
1578 Stack::Inertia(client),
1579 );
1580
1581 let find = |path: &str| {
1582 plan.files
1583 .iter()
1584 .find(|file| file.path == Path::new(path))
1585 .unwrap_or_else(|| panic!("{path} missing"))
1586 .contents
1587 .clone()
1588 };
1589
1590 let entry = client.entry();
1591
1592 assert!(
1593 find("vite.config.js").contains(&format!("input: '{entry}'")),
1594 "{client:?} vite input"
1595 );
1596 assert!(
1597 find("src/routes.rs").contains(&format!("Inertia::new(\"{entry}\")")),
1598 "{client:?} server entry"
1599 );
1600 }
1601 }
1602
1603 #[test]
1604 fn an_inertia_app_keeps_the_api_group_and_its_marker() {
1605 let plan = new_app(
1608 "shop",
1609 &Dependency::Version("0.3".into()),
1610 Stack::Inertia(Client::React),
1611 );
1612
1613 let routes = plan
1614 .files
1615 .iter()
1616 .find(|file| file.path == Path::new("src/routes.rs"))
1617 .expect("routes.rs")
1618 .contents
1619 .clone();
1620
1621 assert!(routes.contains(MARK_ROUTES), "{routes}");
1622 assert!(routes.contains("r.group(\"/api\""), "{routes}");
1623 assert!(
1624 routes.contains("static_files(\"/build\", \"public/build\")"),
1625 "{routes}"
1626 );
1627 }
1628
1629 #[test]
1630 fn the_session_guard_wraps_the_inertia_middleware() {
1631 let plan = new_app(
1635 "shop",
1636 &Dependency::Version("0.3".into()),
1637 Stack::Inertia(Client::React),
1638 );
1639
1640 let routes = plan
1641 .files
1642 .iter()
1643 .find(|file| file.path == Path::new("src/routes.rs"))
1644 .expect("routes.rs")
1645 .contents
1646 .clone();
1647
1648 let session = routes.find("Auth::session()").expect("session middleware");
1649 let inertia = routes.find("Inertia::new").expect("inertia middleware");
1650
1651 assert!(
1652 session < inertia,
1653 "Auth::session() must be registered first"
1654 );
1655 }
1656
1657 #[test]
1658 fn a_generated_app_is_its_own_workspace_root() {
1659 for stack in [Stack::Api, Stack::Inertia(Client::React)] {
1663 let plan = new_app("shop", &Dependency::Version("0.3".into()), stack);
1664 let manifest = &plan.files[0].contents;
1665
1666 assert!(manifest.contains("[workspace]"), "{stack:?}: {manifest}");
1667 }
1668 }
1669
1670 #[test]
1671 fn a_hyphenated_app_name_becomes_a_valid_crate_name() {
1672 let plan = new_app("my-app", &Dependency::Version("0.3".into()), Stack::Api);
1673 let manifest = &plan.files[0].contents;
1674
1675 assert!(manifest.contains(r#"name = "my_app""#), "{manifest}");
1676 }
1677
1678 #[test]
1679 fn a_bare_model_generates_only_the_model_and_entity() {
1680 let plan = make_model(
1681 &Names::new("User"),
1682 ModelFlags::default(),
1683 "20260101_000001",
1684 );
1685
1686 let paths: Vec<_> = plan
1687 .files
1688 .iter()
1689 .map(|file| file.path.display().to_string())
1690 .collect();
1691
1692 assert_eq!(paths, vec!["src/models/user.rs", "src/entities/users.rs"]);
1693 }
1694
1695 #[test]
1696 fn the_all_flag_generates_every_artefact() {
1697 let plan = make_model(&Names::new("User"), ModelFlags::all(), "20260101_000001");
1698
1699 let paths: Vec<_> = plan
1700 .files
1701 .iter()
1702 .map(|file| file.path.display().to_string())
1703 .collect();
1704
1705 for expected in [
1706 "src/models/user.rs",
1707 "src/entities/users.rs",
1708 "migration/src/m20260101_000001_create_users.rs",
1709 "src/validators/user.rs",
1710 "src/policies/user_policy.rs",
1711 "src/factories/user_factory.rs",
1712 "src/seeders/user_seeder.rs",
1713 "src/controllers/users_controller.rs",
1714 ] {
1715 assert!(
1716 paths.contains(&expected.to_owned()),
1717 "{expected} missing from {paths:?}"
1718 );
1719 }
1720 }
1721
1722 #[test]
1723 fn a_controller_registers_one_resource_line() {
1724 let plan = make_model(
1725 &Names::new("User"),
1726 ModelFlags {
1727 controller: true,
1728 ..ModelFlags::default()
1729 },
1730 "20260101_000001",
1731 );
1732
1733 let routes = plan
1734 .insertions
1735 .iter()
1736 .find(|insertion| insertion.marker == MARK_ROUTES)
1737 .expect("routes registered");
1738
1739 assert_eq!(routes.line.lines().count(), 1);
1742 assert!(
1743 routes.line.starts_with(r#"r.resource("/users", "#),
1744 "{}",
1745 routes.line
1746 );
1747 assert!(routes.line.contains("UsersController"));
1748 }
1749
1750 #[test]
1751 fn migrations_register_both_the_module_and_the_boxed_value() {
1752 let plan = make_model(
1753 &Names::new("User"),
1754 ModelFlags {
1755 migration: true,
1756 ..ModelFlags::default()
1757 },
1758 "20260101_000001",
1759 );
1760
1761 let markers: Vec<_> = plan
1762 .insertions
1763 .iter()
1764 .map(|insertion| insertion.marker)
1765 .collect();
1766
1767 assert!(markers.contains(&MARK_MIGRATION_MODULES));
1768 assert!(markers.contains(&MARK_MIGRATIONS));
1769 }
1770}
1771
1772pub const MARK_FIELDS_OPEN: &str = "// <luxid:fields>";
1773pub const MARK_FIELDS_CLOSE: &str = "// </luxid:fields>";
1774
1775pub fn refresh_fields(source: &str, body: &str) -> Option<String> {
1781 let open = source.find(MARK_FIELDS_OPEN)?;
1782 let close = source[open..].find(MARK_FIELDS_CLOSE)? + open;
1783
1784 let line_start = source[..open]
1785 .rfind('\n')
1786 .map(|index| index + 1)
1787 .unwrap_or(0);
1788 let indent = &source[line_start..open];
1789
1790 let open_line_end = source[open..].find('\n')? + open + 1;
1791
1792 let rendered: String = body
1793 .lines()
1794 .map(|line| format!("{indent}{line}\n"))
1795 .collect::<Vec<_>>()
1796 .join("");
1797
1798 let mut out = String::with_capacity(source.len() + rendered.len());
1799 out.push_str(&source[..open_line_end]);
1800 out.push_str(&rendered);
1801 out.push_str(&source[line_start..]);
1802
1803 let tail_start = close - indent.len();
1805 out.truncate(open_line_end + rendered.len());
1806 out.push_str(&source[tail_start..]);
1807
1808 Some(out)
1809}
1810
1811#[cfg(test)]
1812mod refresh_tests {
1813 use super::*;
1814
1815 const SOURCE: &str = "fn definition() {\n ActiveModel {\n // <luxid:fields>\n old: Set(1),\n // </luxid:fields>\n ..Default::default()\n }\n}\n";
1816
1817 #[test]
1818 fn replaces_only_the_marked_region() {
1819 let updated = refresh_fields(SOURCE, "name: Set(\"name\".to_owned()),").expect("markers");
1820
1821 assert!(updated.contains("name: Set(\"name\".to_owned()),"));
1822 assert!(
1823 !updated.contains("old: Set(1)"),
1824 "the old body was replaced"
1825 );
1826
1827 assert!(updated.contains("..Default::default()"));
1829 assert!(updated.starts_with("fn definition() {"));
1830 assert!(updated.trim_end().ends_with('}'));
1831 }
1832
1833 #[test]
1834 fn is_idempotent() {
1835 let once = refresh_fields(SOURCE, "a: Set(1),").expect("markers");
1836 let twice = refresh_fields(&once, "a: Set(1),").expect("markers");
1837
1838 assert_eq!(once, twice, "resyncing an unchanged schema changes nothing");
1839 }
1840
1841 #[test]
1842 fn keeps_the_marker_indentation() {
1843 let updated = refresh_fields(SOURCE, "a: Set(1),").expect("markers");
1844 assert!(updated.contains("\n a: Set(1),\n"), "{updated}");
1845 }
1846
1847 #[test]
1848 fn an_empty_body_clears_the_region() {
1849 let updated = refresh_fields(SOURCE, "").expect("markers");
1850 assert!(!updated.contains("old: Set(1)"));
1851 }
1852
1853 #[test]
1854 fn a_file_without_markers_is_left_alone() {
1855 assert!(refresh_fields("fn nothing() {}", "a: Set(1),").is_none());
1856 }
1857}
1858
1859pub fn field_attributes(source: &str) -> BTreeMap<String, Vec<String>> {
1868 let mut found: BTreeMap<String, Vec<String>> = BTreeMap::new();
1869
1870 let Some(open) = source.find(MARK_FIELDS_OPEN) else {
1871 return found;
1872 };
1873 let Some(close) = source[open..]
1874 .find(MARK_FIELDS_CLOSE)
1875 .map(|index| index + open)
1876 else {
1877 return found;
1878 };
1879
1880 let mut pending: Vec<String> = Vec::new();
1881
1882 for line in source[open..close].lines() {
1883 let trimmed = line.trim();
1884
1885 if trimmed.starts_with("#[") {
1886 if trimmed != "#[sea_orm(primary_key)]" {
1887 pending.push(trimmed.to_owned());
1888 }
1889 continue;
1890 }
1891
1892 if let Some(rest) = trimmed.strip_prefix("pub ")
1893 && let Some((name, _)) = rest.split_once(':')
1894 && !pending.is_empty()
1895 {
1896 found.insert(name.trim().to_owned(), std::mem::take(&mut pending));
1897 continue;
1898 }
1899
1900 pending.clear();
1901 }
1902
1903 found
1904}
1905
1906#[cfg(test)]
1907mod attribute_tests {
1908 use super::*;
1909
1910 const SOURCE: &str = "pub struct Model {\n // <luxid:fields>\n #[sea_orm(primary_key)]\n pub id: i64,\n #[serde(skip_serializing)]\n pub password: String,\n pub email: String,\n // </luxid:fields>\n}\n";
1911
1912 #[test]
1913 fn carries_user_written_attributes_across_a_resync() {
1914 let found = field_attributes(SOURCE);
1915
1916 assert_eq!(
1917 found.get("password"),
1918 Some(&vec!["#[serde(skip_serializing)]".to_owned()])
1919 );
1920 assert_eq!(found.get("email"), None, "no attributes, nothing to carry");
1921 }
1922
1923 #[test]
1924 fn the_generated_primary_key_attribute_is_not_carried() {
1925 assert_eq!(field_attributes(SOURCE).get("id"), None);
1927 }
1928
1929 #[test]
1930 fn a_file_without_markers_yields_nothing() {
1931 assert!(field_attributes("pub struct Model {}").is_empty());
1932 }
1933}