puerto 0.34.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
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
use std::collections::BTreeMap;
use std::path::Path;

use serde::{Deserialize, Serialize};

use crate::diagnostics::Diagnostic;
use crate::validation::{is_pascal_case, pascal_help};

// ── Config types ──────────────────────────────────────────────────────────────

#[derive(Debug, Default, Deserialize, Serialize)]
pub struct PuertoConfig {
    #[serde(rename = "proyecto")]
    pub project: Project,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    #[serde(rename = "entidad")]
    pub entity: Vec<Entity>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    #[serde(rename = "objeto_valor")]
    pub value_object: Vec<ValueObjectDefinition>,
    /// The worker's consumers (ADR-0018 § 5) — `events` projects.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    #[serde(rename = "consumidor")]
    pub consumer: Vec<Consumer>,
    /// The project's mails (ADR-0020) — wiring only: each one's data, text and recipient live in
    /// its files.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    #[serde(rename = "correo")]
    pub mail: Vec<Mail>,
    /// The worker's scheduled tasks (ADR-0036) — `db` projects.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    #[serde(rename = "tarea_programada")]
    pub scheduled: Vec<ScheduledTask>,
}

/// One `[[tarea_programada]]`: `presentacion/worker/src/tareas_programadas/<name>.rs`, run at `cron`.
#[derive(Debug, Deserialize, Serialize, Clone, PartialEq)]
pub struct ScheduledTask {
    /// snake_case, unique among the tasks and the consumers: the module and the runs log's key.
    #[serde(rename = "nombre")]
    pub name: String,
    /// 5 fields, minute hour day month weekday.
    pub cron: String,
    /// The IANA zone the cron is read in; none: UTC.
    #[serde(default, skip_serializing_if = "Option::is_none", rename = "zona")]
    pub zone: Option<String>,
}

/// One `[[correo]]`: its port, its template mailer and its templates, in the `correo` context.
#[derive(Debug, Deserialize, Serialize, Clone, PartialEq)]
pub struct Mail {
    /// snake_case, unique: the modules, the template folder, `{Name}Mail` / `{Name}Mailer`.
    #[serde(rename = "nombre")]
    pub name: String,
    /// The event types the worker sends it on — `events` projects. Empty: nothing sends it yet.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    #[serde(rename = "tras")]
    pub on: Vec<String>,
}

/// One `[[consumidor]]`: `presentacion/worker/src/consumidores/<name>.rs`, subscribed to `events`.
#[derive(Debug, Deserialize, Serialize, Clone, PartialEq)]
pub struct Consumer {
    /// snake_case, unique: the module, the `db` transport's consumer name and the Kafka group id.
    #[serde(rename = "nombre")]
    pub name: String,
    /// The event types it is delivered (`product_created`), each declared by some entity.
    #[serde(rename = "eventos")]
    pub events: Vec<String>,
}

#[derive(Debug, Deserialize, Serialize, Clone, Default)]
pub struct ValueObjectDefinition {
    #[serde(rename = "nombre")]
    pub name: String,
    /// The primitive it wraps; empty for a composite one (Fase 31), which has `fields` instead.
    #[serde(default, skip_serializing_if = "String::is_empty", rename = "tipo")]
    pub inner_type: String,
    /// The valid value its fields' tests use instead of the registry's (27.15): `ana@ejemplo.es`.
    #[serde(default, skip_serializing_if = "Option::is_none", rename = "ejemplo")]
    pub example: Option<String>,
    /// A class with a rule (27.16): `email` (a `String`) or `dinero` (an `i64` of cents).
    #[serde(default, skip_serializing_if = "Option::is_none", rename = "clase")]
    pub class: Option<String>,
    /// A composite value object's fields (Fase 31: `Direccion { calle, ciudad, cp }`), one column
    /// each. Last: TOML writes its tables after the values above.
    #[serde(default, skip_serializing_if = "Vec::is_empty", rename = "campos")]
    pub fields: Vec<Field>,
}

/// The value object classes with a rule (27.16), and the primitive each wraps.
pub const VO_CLASSES: &[(&str, &str)] = &[("email", "String"), ("dinero", "i64")];

/// Where the app goes under a portada unless `puerto nuevo --ruta-app` says otherwise.
pub const DEFAULT_APP_PATH: &str = "/panel";

#[derive(Debug, Clone, Deserialize, Serialize, Default)]
pub struct Project {
    #[serde(rename = "nombre")]
    pub name: String,
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub db: bool,
    /// The project has a `web/` frontend (`puerto nuevo` without `--sin-web`).
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub web: bool,
    /// Domain events (ADR-0018): the transport, `"db"` or `"kafka"`. Absent: no events. Set by
    /// `puerto nuevo --db --eventos <transport>`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    #[serde(rename = "eventos")]
    pub events: Option<String>,
    /// Auth (ADR-0021): `"oidc"` or `"local"`. Absent: no auth. Set by `puerto nuevo --auth <mode>`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub auth: Option<String>,
    /// A public portada at `/` and the app under `app_path` (ADR-0028). Set by `puerto nuevo
    /// --portada`.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub portada: bool,
    /// Where the app goes when there is a portada: `/panel` unless `puerto nuevo --ruta-app` says.
    #[serde(default, skip_serializing_if = "Option::is_none", rename = "ruta_app")]
    pub app_path: Option<String>,
    /// The notifications inbox of the runtime (Fase 41.4, ADR-0037). Set by `puerto generar
    /// notificaciones`; needs auth and events.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub notificaciones: bool,
}

impl Project {
    /// Every CRUD write goes through a unit of work and records an event in the outbox.
    pub fn has_events(&self) -> bool {
        self.events.is_some()
    }

    /// Routes take `auth: BearerAuth` unless the entity lists them as `public`.
    pub fn has_auth(&self) -> bool {
        self.auth.is_some()
    }

    /// Where the frontend mounts the app: under the portada, or at the root without one.
    pub fn app_path(&self) -> &str {
        match (&self.app_path, self.portada) {
            (Some(path), true) => path,
            (None, true) => DEFAULT_APP_PATH,
            _ => "/",
        }
    }
}

#[derive(Debug, Deserialize, Serialize, Default, Clone)]
pub struct Entity {
    /// PascalCase entity name, e.g. "Product"
    #[serde(rename = "nombre")]
    pub name: String,
    /// snake_case use case action names, e.g. ["create_product"]
    #[serde(rename = "casos_de_uso")]
    pub use_cases: Vec<String>,
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub db: bool,
    /// Uniques over several fields (`--unico jugador_id,partido_id`): one partial unique index
    /// each, checked by the in-memory repository too. Values, so written before any table.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    #[serde(rename = "unicos")]
    pub uniques: Vec<Vec<String>>,
    /// The order of its list (`--orden=-puntos,nombre`): own fields, a `-` for descending; then
    /// `creado_en DESC, id`. Empty: the newest first.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    #[serde(rename = "orden")]
    pub order: Vec<String>,
    /// Auth projects: the use cases whose routes take no `BearerAuth` — what scaffold wrote
    /// (`--publico`); after it, `rutas.rs` is the user's.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    #[serde(rename = "publicos")]
    pub public: Vec<String>,
    /// Auth projects: the roles a use case's route requires (`#[requiere_rol]`), by use case —
    /// what scaffold wrote (`--rol`). Declared before `fields`: written after the
    /// `[[entidad.campos]]`, `[entity.roles]` would read as if it belonged to the last field.
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub roles: BTreeMap<String, Vec<String>>,
    #[serde(default)]
    #[serde(rename = "campos")]
    pub fields: Vec<Field>,
    /// Custom events beyond the CRUD ones (`product_published`), snake_case — `events` projects.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    #[serde(rename = "eventos")]
    pub events: Vec<String>,
    /// State changes written by `generar transicion` (27.12), by verb: `cancelar` is the method
    /// `dominio/src/cancelar.rs`, the use case `cancelar_<entity>` (also in `use_cases`) and the
    /// route `rest/src/cancelar_<entity>.rs`, mounted on its own `Api<UseCase>`.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    #[serde(rename = "transiciones")]
    pub transitions: Vec<String>,
    /// Use cases with no route (27.13, `--interno`): their params take no caller, `Api{Entity}`
    /// has no field for them and a transition among them no `Api{UseCase}`. `cableado` builds them.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    #[serde(rename = "internos")]
    pub internal: Vec<String>,
    /// The `Uuid` field that holds who owns each row (27.18, `--propietario`): `crear` sets it to the
    /// caller, and `obtener`, `actualizar` and `borrar` let through only its owner or who holds
    /// every role of the route.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    #[serde(rename = "propietario")]
    pub owner: Option<String>,
    /// Use cases of an owned entity that only their roles reach (28.2, `--solo-rol`): the owner
    /// does not pass, the route keeps its `#[requiere_rol]`.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    #[serde(rename = "solo_rol")]
    pub role_only: Vec<String>,
}

impl Entity {
    /// The use cases `Api{Entity}` holds: every one but its transitions' and its internal ones.
    pub fn api_use_cases(&self) -> Vec<String> {
        let transitions = self.transition_use_cases();
        self.use_cases
            .iter()
            .filter(|uc| !transitions.contains(uc) && !self.internal.contains(uc))
            .cloned()
            .collect()
    }

    /// The use cases of its transitions with a route, each on its own `Api{UseCase}`.
    pub fn routed_transition_use_cases(&self) -> Vec<String> {
        self.transition_use_cases()
            .into_iter()
            .filter(|uc| !self.internal.contains(uc))
            .collect()
    }

    /// The use cases of its transitions: `cancelar_producto` for `cancelar`.
    pub fn transition_use_cases(&self) -> Vec<String> {
        let snake = crate::generators::naming::pascal_to_snake(&self.name);
        self.transitions
            .iter()
            .map(|verb| crate::generators::naming::transition_use_case(verb, &snake))
            .collect()
    }
}

#[derive(Debug, Deserialize, Serialize, Clone, Default)]
pub struct Field {
    /// Snake_case field name, e.g. "name"
    #[serde(rename = "nombre")]
    pub name: String,
    /// Rust type string, e.g. "String", "i64", "Option<String>"
    #[serde(rename = "tipo")]
    pub field_type: String,
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    #[serde(rename = "unico")]
    pub unique: bool,
    /// Auth projects: public routes answer it only to a caller with a session (`--privado`).
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    #[serde(rename = "privado")]
    pub private: bool,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    #[serde(rename = "objeto_valor")]
    pub value_object: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    #[serde(rename = "clase_objeto_valor")]
    pub value_object_kind: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    #[serde(rename = "variantes")]
    pub enum_variants: Option<Vec<String>>,
    /// A reference (ADR-0022): the CRUD entity whose id this `Uuid` / `Option<Uuid>` holds. The
    /// domain holds that entity's id type; a `--db` project's column is a foreign key to it.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    #[serde(rename = "referencia")]
    pub references: Option<String>,
    /// What the screens call it (27.5); without it, [`crate::generators::naming::etiqueta`].
    #[serde(default, skip_serializing_if = "Option::is_none")]
    #[serde(rename = "etiqueta")]
    pub label: Option<String>,
    /// The value `crear` gives it (27.17, `--por-defecto`): a variant, or a literal of its type. The
    /// field is not in what `crear` asks for; `actualizar` still changes it.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        rename = "por_defecto"
    )]
    pub default: Option<String>,
    /// A unique `String` the domain makes up (27.17, `--generado`): `crear` asks
    /// `<Entity>::generar_<field>()` (`dominio/src/generados.rs`) and `actualizar` keeps it.
    #[serde(
        default,
        skip_serializing_if = "std::ops::Not::not",
        rename = "generado"
    )]
    pub generated: bool,
    /// It is its entity's `propietario` (27.18), never written: [`read`] sets it.
    #[serde(skip)]
    pub owner: bool,
    /// Its shared value object's `ejemplo` (27.15), or its own (28.3), never written: [`read`] and
    /// [`apply_shared_vo_inference`] give it to every field of that value object.
    #[serde(skip)]
    pub example: Option<String>,
    /// The `ejemplo` of a field with a local value object (28.3, `scaffold --ejemplo`): what its
    /// tests use, as a shared one's `[[objeto_valor]] ejemplo`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    #[serde(rename = "ejemplo")]
    pub own_example: Option<String>,
    /// What the screens show for each variant of an enum (27.9: `{ AlaVenta = "A la venta" }`);
    /// a variant it leaves out, [`crate::generators::naming::texto_variante`].
    #[serde(default, skip_serializing_if = "Option::is_none")]
    #[serde(rename = "textos")]
    pub texts: Option<BTreeMap<String, String>>,
    /// Its composite value object's fields (Fase 31), never written: [`read`] and
    /// [`apply_shared_vo_inference`] give them, as they give `example`.
    #[serde(skip)]
    pub parts: Vec<Field>,
}

/// Parse a CLI field argument into a `Field`.
///
/// Shell-safe syntax (no quoting required):
///
/// ```text
/// name:Type                          primitive (String, i64, bool, f64, Uuid, DateTime, map)
/// name:opt:Type                      Option<Type> primitive
/// name:vec:Type                      Vec<Type> primitive
/// name:VoName:Type                   VO wrapping a primitive
/// name:VoName:opt:Type               Option<VO> field
/// name:VoName:vec:Type               Vec<VO> field
/// name:VoName:enum:V1/V2/V3          Enum VO (variants separated by /)
/// name:ref:Entity                    Reference to another entity: its id (ADR-0022)
/// name:ref:opt:Entity                Optional reference
/// ```
///
/// Append `!` to the whole argument to mark the field as `unique = true`.
/// Type shorthands: `DateTime` → `DateTime<Utc>`, `map` → `HashMap<String, String>`.
pub fn parse_field_arg(s: &str) -> Result<Field, String> {
    let (raw, unique) = if let Some(stripped) = s.strip_suffix('!') {
        (stripped, true)
    } else {
        (s, false)
    };

    let parts: Vec<&str> = raw.split(':').collect();

    if parts[0].is_empty() {
        return Err(Diagnostic::new("falta el nombre del campo")
            .at(s, 0..0)
            .help("un campo es nombre:tipo, p. ej. `titulo:String`")
            .into());
    }
    if parts.len() == 1 || (parts.len() == 2 && parts[1].is_empty()) {
        return Err(missing_type(s, parts[0]));
    }

    let name = parts[0].to_string();
    crate::validation::validate_field_name(&name).map_err(|e| {
        let snake = crate::generators::naming::pascal_to_snake(&name.replace('-', "_"));
        Diagnostic::new(e)
            .at(s, 0..name.len())
            .maybe_help(
                (snake != name && crate::validation::is_valid_field_name(&snake))
                    .then(|| format!("en snake_case: `{snake}`")),
            )
            .to_string()
    })?;

    let field = parse_field_shape(s, name, &parts, unique)?;
    // Fail at the command that caused it, not at `cargo build` inside the generated project.
    crate::validation::validate_field(&field)
        .map_err(|e| Diagnostic::new(e).at(s, 0..raw.len()).to_string())?;
    Ok(field)
}

/// Where `parts[at]` starts in the argument they were split from.
fn offset(parts: &[&str], at: usize) -> usize {
    parts[..at].iter().map(|p| p.len() + 1).sum()
}

fn part(parts: &[&str], at: usize) -> std::ops::Range<usize> {
    let start = offset(parts, at);
    start..start + parts[at].len()
}

fn missing_type(arg: &str, name: &str) -> String {
    let end = arg.trim_end_matches('!').len();
    Diagnostic::new(format!("falta el tipo del campo `{name}`"))
        .at(arg, end..end)
        .help(format!("un campo es nombre:tipo, p. ej. `{name}:String`"))
        .note(crate::generators::types::CLI_TYPES_NOTE)
        .into()
}

/// A CLI field whose type is not in the registry, told in the syntax that was typed (37.3):
/// `precio:opt:i46` is `i46`, never `Option<i46>`. `shared` are the declared value objects, which a
/// misspelt `email:Emial` may have meant.
pub fn check_field_type(arg: &str, field: &Field, shared: &[&str]) -> Result<(), String> {
    use crate::generators::types::{self, CLI_TYPES_NOTE};
    let Err(error) = types::validate_fields(std::slice::from_ref(field)) else {
        return Ok(());
    };
    let raw = arg.strip_suffix('!').unwrap_or(arg);
    if field.references.is_some() || types::resolve_type(&field.field_type).is_ok() {
        return Err(Diagnostic::new(error).at(arg, 0..raw.len()).into());
    }
    let parts: Vec<&str> = raw.split(':').collect();
    let last = parts.len() - 1;
    let token = parts[last];
    let modifier = (last >= 2)
        .then(|| parts[last - 1])
        .filter(|m| ["opt", "vec"].contains(m));
    let prefix = modifier.map(|m| format!("{m}:")).unwrap_or_default();
    let spelled: Vec<String> = types::TYPE_REGISTRY
        .iter()
        .map(|m| types::cli_spelling(m.rust_type))
        .collect();
    let bases = |prefix: &str| -> Vec<&str> {
        spelled
            .iter()
            .filter_map(|s| s.strip_prefix(prefix))
            .filter(|s| !s.contains(':'))
            .collect()
    };
    let takes = bases(&prefix);
    let name = &field.name;

    if modifier.is_some() && bases("").contains(&token) {
        let (rest, tail) = takes.split_at(takes.len() - 1);
        let list = if rest.is_empty() {
            tail[0].to_string()
        } else {
            format!("{} o {}", rest.join(", "), tail[0])
        };
        return Err(Diagnostic::new(format!(
            "tipo no admitido `{prefix}{token}` en el campo `{name}`"
        ))
        .at(arg, offset(&parts, last - 1)..raw.len())
        .note(format!("con {prefix}, {list}"))
        .into());
    }

    let candidates = takes
        .iter()
        .copied()
        .chain(shared.iter().copied().filter(|_| modifier.is_none()));
    let help = crate::diagnostics::did_you_mean(token, candidates).or_else(|| {
        is_pascal_case(token).then(|| {
            format!(
                "si `{token}` es un objeto valor compartido, se declara antes: `puerto generar \
                 objeto-valor {token} <tipo>`"
            )
        })
    });
    Err(
        Diagnostic::new(format!("tipo desconocido `{token}` en el campo `{name}`"))
            .at(arg, part(&parts, last))
            .maybe_help(help)
            .note(CLI_TYPES_NOTE)
            .into(),
    )
}

fn parse_field_shape(s: &str, name: String, parts: &[&str], unique: bool) -> Result<Field, String> {
    match parts[1..] {
        ["ref", target] => return Ok(reference(name, target, "Uuid", unique)),
        ["ref", "opt", target] => return Ok(reference(name, target, "Option<Uuid>", unique)),
        // Fase 32: many to many, the ids of a set of rows, kept in a join table.
        ["vec", "ref", target] => return Ok(reference(name, target, "Vec<Uuid>", unique)),
        // Fase 38: a file, or a list of them. Always optional: the entity exists before its file.
        ["fichero"] | ["vec", "fichero"] => {
            if unique {
                let end = s.len();
                return Err(Diagnostic::new(format!(
                    "el campo `{name}` es un fichero: no puede ser único"
                ))
                .at(s, end - 1..end)
                .help(format!("sin `!`: `{}`", s.trim_end_matches('!')))
                .into());
            }
            let ty = if parts.len() == 2 {
                "Option<Fichero>"
            } else {
                "Vec<Fichero>"
            };
            return Ok(Field {
                name,
                field_type: ty.to_string(),
                ..Default::default()
            });
        }
        ["opt", "fichero"] => {
            return Err(Diagnostic::new(format!(
                "el campo `{name}` es un fichero, y un fichero ya es opcional"
            ))
            .at(s, part(parts, 1))
            .help(format!("sin `opt:`: `{name}:fichero`"))
            .into());
        }
        _ => {}
    }
    match parts.len() {
        1 => unreachable!("handled above"),
        2 => {
            // name:PrimitiveType
            let ft = expand_type(parts[1]);
            if ft.is_empty() {
                return Err(missing_type(s, &name));
            }
            Ok(Field {
                name,
                field_type: ft,
                unique,
                ..Default::default()
            })
        }
        3 => {
            let second = parts[1];
            let third = parts[2];
            match second {
                "opt" => Ok(Field {
                    name,
                    field_type: format!("Option<{}>", expand_type(third)),
                    unique,
                    ..Default::default()
                }),
                "vec" => Ok(Field {
                    name,
                    field_type: format!("Vec<{}>", expand_type(third)),
                    unique,
                    ..Default::default()
                }),
                vo_name if is_pascal_case(vo_name) => {
                    // A class with a rule (27.16) says its primitive: `email:Email:email`.
                    let class = VO_CLASSES.iter().find(|(class, _)| *class == third);
                    Ok(Field {
                        name,
                        field_type: class
                            .map_or_else(|| expand_type(third), |(_, ty)| ty.to_string()),
                        unique,
                        value_object: Some(vo_name.to_string()),
                        value_object_kind: class.map(|(class, _)| class.to_string()),
                        ..Default::default()
                    })
                }
                _ => Err(Diagnostic::new(format!(
                    "`{second}` no es una palabra conocida (opt, vec, ref) ni un objeto valor en \
                     PascalCase"
                ))
                .at(s, part(parts, 1))
                .maybe_help(
                    crate::diagnostics::did_you_mean(second, ["opt", "vec", "ref"])
                        .or_else(|| pascal_help(second).map(|h| format!("un objeto valor va {h}"))),
                )
                .into()),
            }
        }
        4 => {
            let vo_name = parts[1];
            let modifier = parts[2];
            let rest = parts[3];

            if !is_pascal_case(vo_name) {
                return Err(Diagnostic::new(format!(
                    "nombre de objeto valor inválido `{vo_name}`: va en PascalCase (una mayúscula \
                     seguida de letras y dígitos)"
                ))
                .at(s, part(parts, 1))
                .maybe_help(pascal_help(vo_name))
                .into());
            }

            match modifier {
                "opt" => Ok(Field {
                    name,
                    field_type: format!("Option<{}>", expand_type(rest)),
                    unique,
                    value_object: Some(vo_name.to_string()),
                    ..Default::default()
                }),
                "vec" => Ok(Field {
                    name,
                    field_type: format!("Vec<{}>", expand_type(rest)),
                    unique,
                    value_object: Some(vo_name.to_string()),
                    ..Default::default()
                }),
                "enum" => {
                    if rest.is_empty() {
                        let end = s.trim_end_matches('!').len();
                        return Err(Diagnostic::new(format!(
                            "faltan las variantes del enum `{vo_name}`"
                        ))
                        .at(s, end..end)
                        .help(format!(
                            "separadas por /: `{}:{vo_name}:enum:Activo/Inactivo`",
                            parts[0]
                        ))
                        .into());
                    }
                    let variants: Vec<String> =
                        rest.split('/').map(|v| v.trim().to_string()).collect();
                    let mut at = offset(parts, 3);
                    for (variant, typed) in variants.iter().zip(rest.split('/')) {
                        if !is_pascal_case(variant) {
                            return Err(Diagnostic::new(format!(
                                "variante de enum inválida `{variant}`: va en PascalCase (una \
                                 mayúscula seguida de letras y dígitos)"
                            ))
                            .at(s, at..at + typed.len())
                            .maybe_help(pascal_help(variant))
                            .into());
                        }
                        at += typed.len() + 1;
                    }
                    Ok(Field {
                        name,
                        field_type: "String".to_string(),
                        unique,
                        value_object: Some(vo_name.to_string()),
                        value_object_kind: Some("enum".to_string()),
                        enum_variants: Some(variants),
                        ..Default::default()
                    })
                }
                _ => Err(Diagnostic::new(format!(
                    "el modificador `{modifier}` no existe (valen: opt, vec, enum)"
                ))
                .at(s, part(parts, 2))
                .maybe_help(crate::diagnostics::did_you_mean(
                    modifier,
                    ["opt", "vec", "enum"],
                ))
                .into()),
            }
        }
        _ => Err(
            Diagnostic::new("demasiadas partes separadas por dos puntos (van de 2 a 4)")
                .at(s, offset(parts, 4)..s.trim_end_matches('!').len())
                .note("la más larga: nombre:Objeto:opt:Tipo (p. ej. apodo:Apodo:opt:String)")
                .into(),
        ),
    }
}

fn reference(name: String, target: &str, field_type: &str, unique: bool) -> Field {
    Field {
        name,
        field_type: field_type.to_string(),
        unique,
        references: Some(target.to_string()),
        ..Default::default()
    }
}

/// Expands CLI type shorthands to full Rust type strings.
/// `DateTime` → `DateTime<Utc>`, `map` → `HashMap<String, String>`.
pub fn expand_type(t: &str) -> String {
    match t {
        "DateTime" => "DateTime<Utc>".to_string(),
        "map" => "HashMap<String, String>".to_string(),
        other => other.to_string(),
    }
}

// ── I/O helpers ───────────────────────────────────────────────────────────────

pub fn read(base: &Path) -> Result<PuertoConfig, Box<dyn std::error::Error>> {
    let path = base.join("puerto.toml");
    let src = std::fs::read_to_string(&path)?;
    let mut config: PuertoConfig = toml::from_str(&src)?;
    for entity in &mut config.entity {
        give_examples(&mut entity.fields, &config.value_object);
        for field in &mut entity.fields {
            field.owner = entity.owner.as_deref() == Some(field.name.as_str());
        }
    }
    Ok(config)
}

/// Each field of a shared value object takes its `ejemplo` (27.15) and, when the field names
/// none, its `clase` (27.16).
fn give_examples(fields: &mut [Field], shared_vos: &[ValueObjectDefinition]) {
    for field in fields {
        let shared = field
            .value_object
            .as_ref()
            .and_then(|vo| shared_vos.iter().find(|s| &s.name == vo));
        field.example = shared
            .and_then(|s| s.example.clone())
            .or_else(|| field.own_example.clone());
        field.parts = shared.map(|s| s.fields.clone()).unwrap_or_default();
        if field.value_object_kind.is_none() {
            field.value_object_kind = shared.and_then(|s| s.class.clone());
        }
    }
}

pub fn write(base: &Path, config: &PuertoConfig) -> Result<(), Box<dyn std::error::Error>> {
    let path = base.join("puerto.toml");
    std::fs::write(path, toml::to_string_pretty(config)?)?;
    Ok(())
}

/// Insert the entity, or update it in place if already present.
///
/// Upsert rather than no-op: re-scaffolding an entity with a different field list used to leave
/// puerto.toml describing the *old* fields while the code on disk had the new ones — a divergence
/// neither `puerto validar` nor `puerto generar bootstrap` could see, in the one file documented
/// as the source of truth.
///
/// Use cases are **merged**, not replaced: actions added by `puerto generar caso-de-uso` survive a
/// re-scaffold. Fields are replaced — they are what the caller just regenerated the code from.
pub fn add_entity(
    base: &Path,
    name: &str,
    use_cases: Vec<String>,
    db: bool,
    fields: Vec<Field>,
) -> Result<(), Box<dyn std::error::Error>> {
    let mut config = read(base)?;
    match config.entity.iter_mut().find(|e| e.name == name) {
        Some(existing) => {
            for uc in use_cases {
                if !existing.use_cases.contains(&uc) {
                    existing.use_cases.push(uc);
                }
            }
            existing.db = db;
            existing.fields = fields;
        }
        None => config.entity.push(Entity {
            name: name.to_string(),
            use_cases,
            db,
            fields,
            ..Default::default()
        }),
    }
    write(base, &config)
}

/// For fields written as `name:VoName` (no explicit inner type), infer the inner type
/// and VO name from the shared VO registry. Only applies when `value_object` is unset
/// and `field_type` matches a declared shared VO name.
pub fn apply_shared_vo_inference(
    fields: Vec<Field>,
    shared_vos: &[ValueObjectDefinition],
) -> Vec<Field> {
    if shared_vos.is_empty() {
        return fields;
    }
    let mut fields: Vec<Field> = fields
        .into_iter()
        .map(|f| {
            if f.value_object.is_none() {
                if let Some(svo) = shared_vos.iter().find(|v| v.name == f.field_type) {
                    // A composite one (Fase 31) has no primitive: its type is its name.
                    let field_type = if svo.fields.is_empty() {
                        svo.inner_type.clone()
                    } else {
                        svo.name.clone()
                    };
                    return Field {
                        field_type,
                        value_object: Some(svo.name.clone()),
                        ..f
                    };
                }
                // `opt:Direccion` / `vec:Direccion`: named, so `validate_vo_coherence` says why not.
                let inner = crate::generators::types::vo_inner_type(&f);
                if shared_vos
                    .iter()
                    .any(|v| v.name == inner && !v.fields.is_empty())
                {
                    return Field {
                        value_object: Some(inner),
                        ..f
                    };
                }
            }
            f
        })
        .collect();
    give_examples(&mut fields, shared_vos);
    fields
}

/// Append a shared VO declaration to puerto.toml. No-op if already present.
pub fn add_value_object(
    base: &Path,
    name: &str,
    inner_type: &str,
) -> Result<(), Box<dyn std::error::Error>> {
    let mut config = read(base)?;
    if config.value_object.iter().any(|vo| vo.name == name) {
        return Ok(());
    }
    config.value_object.push(ValueObjectDefinition {
        name: name.to_string(),
        inner_type: inner_type.to_string(),
        ..Default::default()
    });
    write(base, &config)
}

/// Whether the project at `base` has domain events. `false` when puerto.toml cannot be read.
pub fn events_enabled(base: &Path) -> bool {
    read(base).is_ok_and(|c| c.project.has_events())
}

/// Append a custom event to an existing entity. Errors if the entity is not declared.
pub fn add_event(
    base: &Path,
    entity_name: &str,
    event: &str,
) -> Result<(), Box<dyn std::error::Error>> {
    let mut config = read(base)?;
    let entity = config
        .entity
        .iter_mut()
        .find(|e| e.name == entity_name)
        .ok_or_else(|| format!("la entidad '{entity_name}' no está en puerto.toml"))?;
    if !entity.events.iter().any(|e| e == event) {
        entity.events.push(event.to_string());
        write(base, &config)?;
    }
    Ok(())
}

/// Append a consumer. Errors if one with the same name is already declared.
pub fn add_consumer(base: &Path, consumer: Consumer) -> Result<(), Box<dyn std::error::Error>> {
    let mut config = read(base)?;
    if config.consumer.iter().any(|c| c.name == consumer.name) {
        return Err(format!("el consumidor '{}' ya está declarado", consumer.name).into());
    }
    config.consumer.push(consumer);
    write(base, &config)
}

/// Append a scheduled task. Errors if one with the same name is already declared.
pub fn add_scheduled_task(
    base: &Path,
    task: ScheduledTask,
) -> Result<(), Box<dyn std::error::Error>> {
    let mut config = read(base)?;
    if config.scheduled.iter().any(|t| t.name == task.name) {
        return Err(format!("la tarea programada '{}' ya está declarada", task.name).into());
    }
    config.scheduled.push(task);
    write(base, &config)
}

pub fn add_mail(base: &Path, mail: Mail) -> Result<(), Box<dyn std::error::Error>> {
    let mut config = read(base)?;
    if config.mail.iter().any(|m| m.name == mail.name) {
        return Err(format!("el correo '{}' ya está declarado", mail.name).into());
    }
    config.mail.push(mail);
    write(base, &config)
}

/// Marks a use case of an existing entity as internal (27.13). No-op if it already is.
pub fn add_internal(
    base: &Path,
    entity_name: &str,
    use_case: &str,
) -> Result<(), Box<dyn std::error::Error>> {
    let mut config = read(base)?;
    let entity = config
        .entity
        .iter_mut()
        .find(|e| e.name == entity_name)
        .ok_or_else(|| format!("la entidad '{entity_name}' no está en puerto.toml"))?;
    if !entity.internal.iter().any(|uc| uc == use_case) {
        entity.internal.push(use_case.to_string());
        write(base, &config)?;
    }
    Ok(())
}

/// Append a use case action to an existing entity. Errors if entity not found. No-op if action already present.
pub fn add_use_case(
    base: &Path,
    entity_name: &str,
    action: &str,
) -> Result<(), Box<dyn std::error::Error>> {
    let mut config = read(base)?;
    let entity = config
        .entity
        .iter_mut()
        .find(|e| e.name == entity_name)
        .ok_or_else(|| format!("la entidad '{entity_name}' no está en puerto.toml"))?;
    if !entity.use_cases.contains(&action.to_string()) {
        entity.use_cases.push(action.to_string());
        write(base, &config)?;
    }
    Ok(())
}