puerto 0.31.0

Puerto: la CLI de un framework full-stack DDD en Rust. Genera proyectos con Clean Architecture, la inyección de dependencias cableada sola y soporte de SQLx, sin cablear nada a mano. Antes, puerto-framework.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
use crate::generators::layout;
use std::path::Path;

use crate::generators::conflict::{OverwritePolicy, guard_entity_overwrite};
use crate::generators::{
    application::write_application_files,
    domain::write_domain_files,
    infrastructure::write_repository_files,
    migration::run_create_table_migration,
    naming::{crud_use_cases, pascal_to_snake, to_pascal_case},
    presentation::write_presentation_files,
    web::write_web_files,
};
use crate::puerto_toml::{Field, ValueObjectDefinition};

/// Low-level scaffold: the four crates of the entity's context (ADR-0023), its web slice, its
/// `[[entidad]]` block and the regenerated wiring. Always the five CRUD use cases.
pub fn run(
    name: &str,
    base: &Path,
    db: bool,
    fields: &[Field],
    shared_vos: &[ValueObjectDefinition],
) -> Result<(), Box<dyn std::error::Error>> {
    write_entity(name, base, db, fields, shared_vos)?;

    let pascal = to_pascal_case(name);
    let snake = pascal_to_snake(&pascal);
    let web = crate::puerto_toml::read(base).is_ok_and(|c| c.project.web);
    let repo_name = if db {
        format!("Repositorio{pascal}Postgres")
    } else {
        format!("Repositorio{pascal}EnMemoria")
    };
    let dir = layout::context_dir(&snake);
    println!("✓ {dir}/dominio/         modelo, errores, puerto del repositorio, Madre{pascal}");
    println!("✓ {dir}/aplicacion/      crear, obtener, listar, actualizar, borrar");
    println!("✓ {dir}/infraestructura/ {repo_name}");
    println!("✓ {dir}/rest/            rutas, dto, respuestas, errores");
    if web {
        let width = format!("{dir}/infraestructura/").len();
        println!(
            "✓ {:<width$} pantallas de lista, detalle y formulario",
            "web/"
        );
    }
    println!("✓ Hecho. Sin cablear nada a mano.");
    if web {
        println!(
            "\nLa API cambió. Siguiente: task web:sync   (exporta la especificación y regenera los \
             tipos de la web)"
        );
    }

    Ok(())
}

/// What [`run`] writes, without a word to the user: `generar campo` renders an entity in throwaway
/// copies of the project (Fase 33.3).
pub fn write_entity(
    name: &str,
    base: &Path,
    db: bool,
    fields: &[Field],
    shared_vos: &[ValueObjectDefinition],
) -> Result<(), Box<dyn std::error::Error>> {
    let pascal = to_pascal_case(name);
    let snake = pascal_to_snake(&pascal);
    let web = crate::puerto_toml::read(base).is_ok_and(|c| c.project.web);

    write_domain_files(&pascal, &snake, base, fields, shared_vos)?;
    write_application_files(&pascal, &snake, base, fields, shared_vos)?;
    write_repository_files(&pascal, &snake, base, db, fields, shared_vos)?;
    write_presentation_files(&pascal, &snake, base, fields)?;
    if web {
        write_web_files(&pascal, base, fields)?;
    }

    let mut use_cases = crud_use_cases(&snake);
    // 27.18: an owned entity also lists its caller's rows.
    if fields.iter().any(|f| f.owner) {
        use_cases.push(crate::generators::naming::mine_use_case(&snake));
    }
    crate::puerto_toml::add_entity(base, &pascal, use_cases, db, fields.to_vec())?;
    crate::patchers::routes_rs::patch_routes_from_manifest(base, &pascal, &snake)?;
    crate::generators::bootstrap::regenerate_bootstrap(base)?;
    Ok(())
}

/// `--publico` and `--rol` of `puerto generar scaffold` in an auth project (ADR-0021 § 4): the
/// CRUD use cases whose routes take no `BearerAuth`, and the roles a route requires.
#[derive(Debug, Default, Clone)]
pub struct ScaffoldAccess {
    pub public: Vec<String>,
    pub roles: std::collections::BTreeMap<String, Vec<String>>,
    /// `--solo-rol` (28.2): the use cases of an owned entity only their roles reach.
    pub role_only: Vec<String>,
}

impl ScaffoldAccess {
    /// `--publico list_products,get_product` and `--rol create_product=admin,…` as the CLI got them.
    pub fn from_args(public: &[String], roles: &[String]) -> Result<Self, String> {
        let mut access = Self {
            public: public.to_vec(),
            ..Default::default()
        };
        for arg in roles {
            let (use_case, role) = arg.split_once('=').ok_or_else(|| {
                format!(
                    "--rol inválido '{arg}'. El formato es <caso_de_uso>=<rol>, p. ej. \
                     borrar_producto=admin"
                )
            })?;
            let roles = access.roles.entry(use_case.to_string()).or_default();
            if !roles.iter().any(|r| r == role) {
                roles.push(role.to_string());
            }
        }
        Ok(access)
    }

    /// `--solo-rol actualizar_entrada,…` (28.2) as the CLI got it.
    pub fn with_role_only(mut self, role_only: &[String]) -> Self {
        self.role_only = role_only.iter().map(|uc| uc.trim().to_string()).collect();
        self
    }

    fn is_empty(&self) -> bool {
        self.public.is_empty() && self.roles.is_empty() && self.role_only.is_empty()
    }
}

/// What a scaffold says about the entity beyond its field list: its uniques over several fields
/// (`--unico a,b`, repeatable), the order of its list (`--orden=-a,b`) and its private fields
/// (`--privado a,b`, auth projects). A re-scaffold without one keeps what the block says.
#[derive(Default)]
pub struct EntityShape {
    pub uniques: Vec<Vec<String>>,
    pub order: Vec<String>,
    pub private: Vec<String>,
    /// `--por-defecto estado=Pendiente` (27.17): `(field, value)`.
    pub defaults: Vec<(String, String)>,
    /// `--generado codigo` (27.17).
    pub generated: Vec<String>,
    /// `--propietario comprador_id` (27.18).
    pub owner: Option<String>,
    /// `--ejemplo cantidad=3` (28.3): `(field, value)`.
    pub examples: Vec<(String, String)>,
    /// `--textos 'estado.AlaVenta=A la venta'` (28.4), as the CLI got them.
    pub texts: Vec<String>,
}

impl EntityShape {
    /// `--unico jugador_id,partido_id` (one group each), `--orden` and `--privado` as the CLI got
    /// them.
    pub fn from_args(uniques: &[String], order: &[String], private: &[String]) -> Self {
        let trimmed = |args: &[String]| args.iter().map(|a| a.trim().to_string()).collect();
        Self {
            uniques: uniques
                .iter()
                .map(|group| group.split(',').map(|f| f.trim().to_string()).collect())
                .collect(),
            order: trimmed(order),
            private: trimmed(private),
            ..Default::default()
        }
    }

    /// `--propietario <field>` (27.18).
    pub fn with_owner(mut self, owner: Option<String>) -> Self {
        self.owner = owner
            .map(|o| o.trim().to_string())
            .filter(|o| !o.is_empty());
        self
    }

    /// `--ejemplo <field>=<value>,…` (28.3) as the CLI got it.
    pub fn with_examples(mut self, examples: &[String]) -> Self {
        self.examples = examples
            .iter()
            .map(|arg| match arg.split_once('=') {
                Some((field, value)) => (field.trim().to_string(), value.trim().to_string()),
                None => (arg.trim().to_string(), String::new()),
            })
            .collect();
        self
    }

    /// `--textos '<field>.<Variant>=<text>'` (28.4), repeatable, as the CLI got them.
    pub fn with_texts(mut self, texts: &[String]) -> Self {
        self.texts = texts.to_vec();
        self
    }

    /// [`Self::texts`] as `(field, variant, text)`; a malformed one is refused.
    fn parsed_texts(&self) -> Result<Vec<(String, String, String)>, String> {
        self.texts
            .iter()
            .map(|arg| {
                arg.split_once('=')
                    .and_then(|(key, text)| {
                        let (field, variant) = key.split_once('.')?;
                        Some((field.trim().into(), variant.trim().into(), text.into()))
                    })
                    .ok_or_else(|| {
                        format!(
                            "--textos inválido '{arg}': el formato es campo.Variante=texto, p. ej. \
                             'estado.AlaVenta=A la venta'"
                        )
                    })
            })
            .collect()
    }

    /// `--por-defecto <field>=<value>,…` and `--generado <field>,…` (27.17) as the CLI got them.
    pub fn with_server_set(mut self, defaults: &[String], generated: &[String]) -> Self {
        self.defaults = defaults
            .iter()
            .map(|arg| match arg.split_once('=') {
                Some((field, value)) => (field.trim().to_string(), value.trim().to_string()),
                None => (arg.trim().to_string(), String::new()),
            })
            .collect();
        self.generated = generated.iter().map(|g| g.trim().to_string()).collect();
        self
    }

    fn is_empty(&self) -> bool {
        self.uniques.is_empty() && self.order.is_empty() && self.owner.is_none()
    }

    /// `fields` with `--privado` applied: the named ones private. Without `--privado`, a field keeps
    /// what the block (`declared`) said of it — a re-scaffold that passes its fields again. A name
    /// that is no field is refused, before anything is written.
    pub(crate) fn mark_private(
        &self,
        pascal: &str,
        fields: Vec<Field>,
        declared: &[Field],
    ) -> Result<Vec<Field>, String> {
        let named = |flag: &str, names: Vec<&String>| -> Result<(), String> {
            match names
                .into_iter()
                .find(|name| !fields.iter().any(|f| &f.name == *name))
            {
                Some(unknown) => Err(format!(
                    "{pascal}: {flag}: '{unknown}' no es un campo de {pascal}"
                )),
                None => Ok(()),
            }
        };
        named("privado", self.private.iter().collect())?;
        named(
            "por-defecto",
            self.defaults.iter().map(|(f, _)| f).collect(),
        )?;
        named("generado", self.generated.iter().collect())?;
        named("propietario", self.owner.iter().collect())?;
        named("ejemplo", self.examples.iter().map(|(f, _)| f).collect())?;
        let texts = self.parsed_texts().map_err(|e| format!("{pascal}: {e}"))?;
        named("textos", texts.iter().map(|(f, _, _)| f).collect())?;
        let before = |f: &Field| declared.iter().find(|d| d.name == f.name);
        // 27.17: without the flags, a field keeps what the block said of it.
        let server_set = self.defaults.is_empty() && self.generated.is_empty();
        let marked: Vec<Field> = fields
            .into_iter()
            .map(|f| Field {
                private: if self.private.is_empty() {
                    f.private || before(&f).is_some_and(|d| d.private)
                } else {
                    self.private.contains(&f.name)
                },
                default: if server_set {
                    f.default
                        .clone()
                        .or_else(|| before(&f).and_then(|d| d.default.clone()))
                } else {
                    self.defaults
                        .iter()
                        .find(|(name, _)| *name == f.name)
                        .map(|(_, value)| value.clone())
                },
                generated: if server_set {
                    f.generated || before(&f).is_some_and(|d| d.generated)
                } else {
                    self.generated.contains(&f.name)
                },
                // 27.18: without `--propietario`, the block's owner stays.
                owner: match &self.owner {
                    Some(owner) => *owner == f.name,
                    None => f.owner || before(&f).is_some_and(|d| d.owner),
                },
                // 28.4: `--textos` adds to (or changes) what the field, or else the block, says.
                texts: {
                    let mut kept = f
                        .texts
                        .clone()
                        .or_else(|| before(&f).and_then(|d| d.texts.clone()));
                    for (_, variant, text) in texts.iter().filter(|(name, _, _)| *name == f.name) {
                        kept.get_or_insert_with(Default::default)
                            .insert(variant.clone(), text.clone());
                    }
                    kept
                },
                // 28.3: without `--ejemplo`, a field keeps the block's.
                own_example: match self.examples.iter().find(|(name, _)| *name == f.name) {
                    Some((_, value)) => Some(value.clone()),
                    None => f
                        .own_example
                        .clone()
                        .or_else(|| before(&f).and_then(|d| d.own_example.clone())),
                },
                ..f
            })
            .map(|f| Field {
                example: f.example.clone().or_else(|| f.own_example.clone()),
                ..f
            })
            .collect();
        let errors: Vec<String> = marked
            .iter()
            .filter_map(|f| crate::validation::validate_server_set(f).err())
            .collect();
        if !errors.is_empty() {
            return Err(format!("{pascal}: {}", errors.join("\n  ")));
        }
        Ok(marked)
    }
}

/// `shape` checked against the entity's fields, before anything is written.
pub(crate) fn check_shape(
    pascal: &str,
    fields: &[Field],
    shape: &EntityShape,
) -> Result<(), Box<dyn std::error::Error>> {
    let errors = crate::validation::validate_entity_shape(&crate::puerto_toml::Entity {
        name: pascal.to_string(),
        fields: fields.to_vec(),
        uniques: shape.uniques.clone(),
        order: shape.order.clone(),
        ..Default::default()
    });
    if errors.is_empty() {
        Ok(())
    } else {
        Err(format!("{pascal}: {}", errors.join("\n  ")).into())
    }
}

/// Writes a checked `shape` to the entity's `[[entidad]]` block (creating the block) before any
/// file is rendered: the generators read it back from there.
pub(crate) fn record_shape(
    base: &Path,
    pascal: &str,
    db: bool,
    fields: &[Field],
    shape: &EntityShape,
) -> Result<(), Box<dyn std::error::Error>> {
    if shape.is_empty() {
        return Ok(());
    }
    let mut config = crate::puerto_toml::read(base)?;
    match config.entity.iter_mut().find(|e| e.name == pascal) {
        // What is not given stays as the block says.
        Some(entity) => {
            if !shape.uniques.is_empty() {
                entity.uniques = shape.uniques.clone();
            }
            if !shape.order.is_empty() {
                entity.order = shape.order.clone();
            }
            if shape.owner.is_some() {
                entity.owner = shape.owner.clone();
            }
        }
        None => config.entity.push(crate::puerto_toml::Entity {
            name: pascal.to_string(),
            use_cases: crud_use_cases(&pascal_to_snake(pascal)),
            db,
            fields: fields.to_vec(),
            uniques: shape.uniques.clone(),
            order: shape.order.clone(),
            owner: shape.owner.clone(),
            ..Default::default()
        }),
    }
    crate::puerto_toml::write(base, &config)
}

/// Checks `access` against the entity's CRUD use cases and writes it to its `[[entidad]]` block,
/// before any file is rendered: the generators read it back from there. A re-scaffold without
/// flags keeps what the block says.
fn record_access(
    base: &Path,
    pascal: &str,
    db: bool,
    fields: &[Field],
    access: &ScaffoldAccess,
) -> Result<(), Box<dyn std::error::Error>> {
    let mut config = crate::puerto_toml::read(base)?;
    if !config.project.has_auth() {
        if !access.is_empty() {
            return Err(
                "--publico, --rol y --solo-rol necesitan un proyecto con auth (`puerto nuevo \
                 --auth oidc`)"
                    .into(),
            );
        }
        return Ok(());
    }
    let snake = pascal_to_snake(pascal);
    let crud = crud_use_cases(&snake);
    let block = config.entity.iter().find(|e| e.name == pascal);
    // What the flags say of the CRUD use cases, next to what the block says of the rest (its
    // transitions'), which a scaffold does not write.
    let kept = |uc: &String| !crud.contains(uc);
    let mut roles = access.roles.clone();
    let mut role_only = access.role_only.clone();
    if let Some(block) = block {
        for (uc, r) in block.roles.iter().filter(|(uc, _)| kept(uc)) {
            roles.entry(uc.clone()).or_insert_with(|| r.clone());
        }
        role_only.extend(block.role_only.iter().filter(|uc| kept(uc)).cloned());
    }
    let checked = crate::puerto_toml::Entity {
        name: pascal.to_string(),
        use_cases: block.map_or_else(|| crud.clone(), |b| b.use_cases.clone()),
        public: access.public.clone(),
        roles,
        role_only,
        owner: fields.iter().find(|f| f.owner).map(|f| f.name.clone()),
        transitions: block.map(|b| b.transitions.clone()).unwrap_or_default(),
        internal: block.map(|b| b.internal.clone()).unwrap_or_default(),
        ..Default::default()
    };
    // A re-scaffold: the routes are rewritten as the block already says.
    if block.is_some() && access.is_empty() {
        return Ok(());
    }
    let errors = crate::validation::validate_entity_access(&checked);
    if !errors.is_empty() {
        return Err(format!("{pascal}: {}", errors.join("\n  ")).into());
    }
    match config.entity.iter_mut().find(|e| e.name == pascal) {
        Some(entity) => {
            entity.public = checked.public;
            entity.roles = checked.roles;
            entity.role_only = checked.role_only;
        }
        None => config.entity.push(crate::puerto_toml::Entity {
            db,
            fields: fields.to_vec(),
            use_cases: crud,
            transitions: vec![],
            internal: vec![],
            owner: None,
            ..checked
        }),
    }
    crate::puerto_toml::write(base, &config)
}

/// `puerto generar scaffold <Name>` without `--publico` / `--rol`.
/// Reads `project.db` from `puerto.toml`, always generates full CRUD.
/// `cli_fields` are fields passed from the CLI (e.g. `title:String price:i64`).
///
/// Refuses to overwrite an already-generated entity unless `--forzar`; see `conflict.rs`.
#[cfg(test)]
pub fn run_scaffold(
    name: &str,
    base: &Path,
    cli_fields: &[Field],
    overwrite: OverwritePolicy,
) -> Result<(), Box<dyn std::error::Error>> {
    run_scaffold_with_access(
        name,
        base,
        cli_fields,
        overwrite,
        &ScaffoldAccess::default(),
    )
}

/// [`run_scaffold`] with `--publico` / `--rol`. In an auth project every CRUD route takes
/// `BearerAuth` except the `public` ones; outside one, `access` must be empty.
#[cfg(test)]
pub fn run_scaffold_with_access(
    name: &str,
    base: &Path,
    cli_fields: &[Field],
    overwrite: OverwritePolicy,
    access: &ScaffoldAccess,
) -> Result<(), Box<dyn std::error::Error>> {
    run_scaffold_with_options(
        name,
        base,
        cli_fields,
        overwrite,
        access,
        &EntityShape::default(),
    )
}

/// [`run_scaffold_with_access`] with `--unico`.
pub fn run_scaffold_with_options(
    name: &str,
    base: &Path,
    cli_fields: &[Field],
    overwrite: OverwritePolicy,
    access: &ScaffoldAccess,
    shape: &EntityShape,
) -> Result<(), Box<dyn std::error::Error>> {
    let config = crate::puerto_toml::read(base)?;
    let db = config.project.db;
    let shared_vos = config.value_object.clone();
    let pascal = to_pascal_case(name);
    let declared = config
        .entity
        .iter()
        .find(|e| e.name == pascal)
        .map(|e| e.fields.clone())
        .unwrap_or_default();
    let fields = if !cli_fields.is_empty() {
        cli_fields.to_vec()
    } else {
        declared.clone()
    };
    let fields = shape.mark_private(&pascal, fields, &declared)?;
    let example_errors: Vec<String> = fields
        .iter()
        .filter_map(|f| crate::validation::validate_own_example(f, &shared_vos).err())
        .chain(
            fields
                .iter()
                .filter(|f| f.texts.is_some())
                .filter_map(|f| crate::validation::validate_field(f).err()),
        )
        .collect();
    if !example_errors.is_empty() {
        return Err(format!("{pascal}: {}", example_errors.join("\n  ")).into());
    }
    if !config.project.has_auth() && fields.iter().any(|f| f.private) {
        return Err(
            "--privado necesita un proyecto con auth (`puerto nuevo --auth oidc`): sin sesión, \
             nadie vería nunca el campo"
                .into(),
        );
    }

    // Checked before the first byte is written — a half-overwritten project is worse than a
    // refused command.
    crate::validation::validate_entity_name(&pascal)?;
    if config.project.has_auth() {
        crate::validation::validate_auth_entity_name(&pascal)?;
    }
    crate::validation::validate_unique_field_names(&fields)?;
    if db {
        for c in fields.iter().flat_map(crate::generators::types::columns) {
            crate::validation::validate_sql_field_name(&c.name)?;
        }
    }
    let vo_conflicts = crate::validation::validate_vo_coherence(&fields, &shared_vos);
    if !vo_conflicts.is_empty() {
        return Err(vo_conflicts.join("\n  ").into());
    }
    crate::validation::validate_references_before_writing(&pascal, &fields, &config, base)?;
    guard_entity_overwrite(
        base,
        &pascal_to_snake(&pascal),
        db,
        config.project.web,
        overwrite,
    )?;
    // Checked before the access is written: a refused shape leaves nothing behind.
    check_shape(&pascal, &fields, shape)?;
    if let Some(owner) = fields.iter().find(|f| f.owner) {
        let public = if access.is_empty() {
            config
                .entity
                .iter()
                .find(|e| e.name == pascal)
                .map(|e| e.public.clone())
                .unwrap_or_default()
        } else {
            access.public.clone()
        };
        crate::validation::validate_owner(
            &pascal_to_snake(&pascal),
            owner,
            config.project.has_auth(),
            &public,
        )?;
    }
    record_access(base, &pascal, db, &fields, access)?;
    record_shape(base, &pascal, db, &fields, shape)?;

    run(name, base, db, &fields, &shared_vos)?;
    if db {
        let snake = pascal_to_snake(&pascal);
        let groups = crate::puerto_toml::read(base)?
            .entity
            .into_iter()
            .find(|e| e.name == pascal)
            .map(|e| e.uniques)
            .unwrap_or_default();
        let migration_sql =
            crate::generators::infrastructure::create_table_sql_with(&snake, &fields, &groups);
        run_create_table_migration(&snake, base, &migration_sql)?;
    }
    Ok(())
}

/// CLI entry point for `puerto generar objeto-valor <Name> <type>`.
///
/// Validated here, at the command that writes it: an invalid declaration used to land in
/// puerto.toml and only surface later, in `puerto validar` or as uncompilable generated code.
/// `example` (27.15, `--ejemplo`): the value its fields' tests use, checked against `inner_type`.
pub fn run_value_object(
    name: &str,
    inner_type: &str,
    example: Option<&str>,
    base: &Path,
) -> Result<(), Box<dyn std::error::Error>> {
    // A class with a rule (27.16) stands for its primitive: `Email email`.
    let class = crate::puerto_toml::VO_CLASSES
        .iter()
        .find(|(class, _)| *class == inner_type);
    let inner_type = &class.map_or_else(
        || crate::puerto_toml::expand_type(inner_type),
        |(_, ty)| ty.to_string(),
    );
    crate::validation::validate_vo_name(name)?;
    crate::validation::validate_shared_vo_inner_type(inner_type)?;
    if let Some(example) = example {
        crate::validation::validate_vo_example(inner_type, example)?;
    }

    let config = crate::puerto_toml::read(base)?;
    if config.value_object.iter().any(|vo| vo.name == name) {
        return Err(format!(
            "el objeto valor compartido '{name}' ya está declarado en puerto.toml"
        )
        .into());
    }
    crate::puerto_toml::add_value_object(base, name, inner_type)?;
    if example.is_some() || class.is_some() {
        let mut config = crate::puerto_toml::read(base)?;
        if let Some(vo) = config.value_object.iter_mut().find(|vo| vo.name == name) {
            vo.example = example.map(str::to_string);
            vo.class = class.map(|(class, _)| class.to_string());
        }
        crate::puerto_toml::write(base, &config)?;
    }
    println!("✓ Objeto valor compartido '{name}' añadido a puerto.toml");
    Ok(())
}

/// CLI entry point for `puerto generar objeto-valor <Name> -- campo:Tipo …` (Fase 31): a composite
/// value object, one column per field. Validated here, like [`run_value_object`].
pub fn run_composite_value_object(
    name: &str,
    raw_fields: &[String],
    example: Option<&str>,
    base: &Path,
) -> Result<(), Box<dyn std::error::Error>> {
    crate::validation::validate_vo_name(name)?;
    let fields: Vec<crate::puerto_toml::Field> = raw_fields
        .iter()
        .map(|arg| crate::puerto_toml::parse_field_arg(arg))
        .collect::<Result<_, _>>()?;
    let vo = crate::puerto_toml::ValueObjectDefinition {
        name: name.to_string(),
        example: example.map(str::to_string),
        fields,
        ..Default::default()
    };
    let errors = crate::validation::validate_composite_vo(&vo);
    if !errors.is_empty() {
        return Err(errors.join("\n  ").into());
    }

    let mut config = crate::puerto_toml::read(base)?;
    if config.value_object.iter().any(|v| v.name == name) {
        return Err(format!(
            "el objeto valor compartido '{name}' ya está declarado en puerto.toml"
        )
        .into());
    }
    config.value_object.push(vo);
    crate::puerto_toml::write(base, &config)?;
    println!("✓ Objeto valor compuesto '{name}' añadido a puerto.toml");
    Ok(())
}