⎇ f5987d9cfc47146e2a8b32a670cd38ccf9e89ed8
crates/modules/ui_engine/libs/meta-schema/src/lib.rs
Historia
Quién tocó qué
crudo
refactor(yahweh): Fase 1 — nakui-ui-schema → yahweh-meta-schema
1//! Schema declarativo de la metainterfaz (yahweh meta-schema).
2//!
3//! Cada **módulo** declara aquí qué menús, vistas, listas y
4//! formularios expone, sin escribir código GPUI ni Rust. Cualquier
5//! runtime de UI dirigida por datos (Nakui hoy, otros mañana) lo
6//! carga y monta la UI correspondiente.
7//!
8//! ## Filosofía
9//!
10//! - **UI como datos**: agregar un módulo = escribir un JSON o un
11//! `.ncl`. Ningún recompile, ningún acoplamiento con el binario
12//! del runtime.
13//! - **Backend-agnostic**: este crate sólo describe la *forma* de
14//! la UI. La conexión a un store/log/executor concretos vive en
15//! el runtime que lo consume (ej: el meta-runtime de Nakui que
16//! wirea esto a `nakui_core` + KCL post-checks).
17//! - **Schema primero, semántica después**: validación semántica
18//! (referencias rotas a entities, campos faltantes, etc.) vive
19//! en el runtime que lo carga, no acá.
20//!
21//! ## Anatomía de un módulo
22//!
23//! ```json
24//! {
25//! "id": "customers",
26//! "label": "Clientes",
27//! "entities": [
28//! { "name": "customer", "fields": [ ... ] }
29//! ],
30//! "menu": [
31//! { "label": "Listar", "view": "list" },
32//! { "label": "Nuevo", "view": "form" }
33//! ],
34//! "views": {
35//! "list": { "kind": "list", "entity": "customer", "columns": [...] },
36//! "form": { "kind": "form", "entity": "customer", "fields": [...] }
37//! }
38//! }
39//! ```
40
41#![forbid(unsafe_code)]
42#![warn(rust_2018_idioms)]
43
44use std::collections::BTreeMap;
45use std::path::{Path, PathBuf};
46
47use serde::{Deserialize, Serialize};
48use thiserror::Error;
49
50/// Manifiesto de un módulo declarativo de UI.
51#[derive(Debug, Clone, Serialize, Deserialize)]
52pub struct Module {
53 /// Identificador estable. Único dentro del directorio cargado.
54 pub id: String,
55
56 /// Nombre legible para mostrar en el sidebar.
57 pub label: String,
58
59 /// Descripción corta opcional (tooltip / subtítulo).
60 #[serde(default)]
61 pub description: Option<String>,
62
63 /// Entities que el módulo introduce o consume. El runtime las
64 /// usa para validar columns/fields y para inicializar el store
65 /// cuando son nuevas.
66 #[serde(default)]
67 pub entities: Vec<EntitySpec>,
68
69 /// Path opaco al backend que va a manejar este módulo. Lo
70 /// interpreta el runtime concreto (no este schema).
71 ///
72 /// Convención actual de Nakui: directorio con `nsmc.json` +
73 /// schemas KCL + scripts Rhai. Cuando está set, el runtime
74 /// Nakui carga un `Executor` para ese path y permite que las
75 /// acciones `Morphism { name }` despachen al pipeline real
76 /// (compute → log → apply). Otro backend puede ignorar este
77 /// campo o darle un significado distinto.
78 ///
79 /// Path resuelto relativo al directorio del `module.json`
80 /// o absoluto.
81 ///
82 /// Si es `None`, los backends que requieren manifest deberían
83 /// degradar (toast informativo, deshabilitar morphisms, etc.);
84 /// los `SeedEntity` siguen funcionando — son altas
85 /// administrativas que no necesitan validación de manifest.
86 ///
87 /// Nombre conservado por compat con módulos ya escritos.
88 /// Renombrar a `backend_module_dir` o similar si emerge un
89 /// segundo backend que también lo use.
90 #[serde(default, alias = "backend_module_dir")]
91 pub nakui_module_dir: Option<String>,
92
93 /// Items del menú. Cada uno apunta a una key de `views`. Orden
94 /// importa (es el orden en que se presentan en el sidebar).
95 pub menu: Vec<MenuItem>,
96
97 /// Vistas indexadas por key. Las keys son referenciadas por
98 /// `MenuItem.view` y por `Action::OpenView.view`.
99 pub views: BTreeMap<String, View>,
100}
101
102/// Item del menú lateral.
103#[derive(Debug, Clone, Serialize, Deserialize)]
104pub struct MenuItem {
105 pub label: String,
106 /// Key de la vista a abrir. Debe existir en `Module.views`.
107 pub view: String,
108 /// Icono opcional (texto unicode o emoji; el runtime decide
109 /// renderización).
110 #[serde(default)]
111 pub icon: Option<String>,
112}
113
114/// Una vista renderizada en el área principal cuando su menú es seleccionado.
115#[derive(Debug, Clone, Serialize, Deserialize)]
116#[serde(tag = "kind", rename_all = "snake_case")]
117pub enum View {
118 /// Tabla de instancias de una entity, columnas + acciones por fila.
119 List(ListView),
120 /// Formulario de creación / edición.
121 Form(FormView),
122}
123
124#[derive(Debug, Clone, Serialize, Deserialize)]
125pub struct ListView {
126 pub title: String,
127 /// Entity (del nakui store) cuyas instancias se listan.
128 pub entity: String,
129 /// Columnas a mostrar. Orden importa.
130 pub columns: Vec<Column>,
131 /// Acciones disponibles a nivel de la lista (ej. "Nuevo" → form).
132 /// Renderizadas como botones en el header.
133 #[serde(default)]
134 pub actions: Vec<Action>,
135 /// Cuando está set, se muestra una caja de búsqueda que filtra
136 /// las filas por substring contra los valores de estas columnas.
137 #[serde(default)]
138 pub search_in: Vec<String>,
139}
140
141#[derive(Debug, Clone, Serialize, Deserialize)]
142pub struct Column {
143 /// Path del campo dentro del record. Para tipos planos: nombre.
144 /// Para nested: puntos (`address.city`). El runtime navega.
145 pub field: String,
146 /// Texto del header.
147 pub label: String,
148 /// Ancho relativo (peso flex). Default 1.
149 #[serde(default = "default_weight")]
150 pub weight: f32,
151}
152
153fn default_weight() -> f32 {
154 1.0
155}
156
157#[derive(Debug, Clone, Serialize, Deserialize)]
158pub struct FormView {
159 pub title: String,
160 /// Entity destino del seed/morphism al submit.
161 pub entity: String,
162 pub fields: Vec<FieldSpec>,
163 /// Acción al submit. Típicamente `Action::SeedEntity` para alta
164 /// directa o `Action::Morphism` cuando hay validación/cálculo.
165 pub on_submit: Action,
166}
167
168/// Especificación de un campo de formulario o columna implícita.
169#[derive(Debug, Clone, Serialize, Deserialize)]
170pub struct FieldSpec {
171 /// Nombre del campo en el record (clave del JSON).
172 pub name: String,
173 /// Etiqueta legible.
174 pub label: String,
175 /// Tipo del valor — define el widget de input + parseo.
176 pub kind: FieldKind,
177 /// Valor por defecto al abrir el form (string raw; el parseo
178 /// según `kind` lo hace el runtime).
179 #[serde(default)]
180 pub default: Option<String>,
181 /// Si `true`, el form rechaza submit con campo vacío.
182 #[serde(default)]
183 pub required: bool,
184 /// Texto de ayuda mostrado bajo el input.
185 #[serde(default)]
186 pub help: Option<String>,
187 /// Si `kind == EntityRef`, indica qué entity referencia. Sin
188 /// esto, el runtime no sabe qué records ofrecer en el selector
189 /// y la validación `Module::validate` rechaza el manifest.
190 /// Para los demás kinds, este campo se ignora.
191 #[serde(default)]
192 pub ref_entity: Option<String>,
193}
194
195#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
196#[serde(rename_all = "snake_case")]
197pub enum FieldKind {
198 /// Texto libre.
199 Text,
200 /// Texto multilínea.
201 Multiline,
202 /// Número (i64 o f64; runtime intenta parsear como i64 primero).
203 Number,
204 /// Booleano (renderizado como checkbox).
205 Boolean,
206 /// Fecha (formato ISO YYYY-MM-DD; almacenada como string).
207 Date,
208 /// Referencia a otro record. El runtime renderiza un selector
209 /// clickable de records existentes de la entity declarada en
210 /// `FieldSpec.ref_entity`; el value almacenado es el UUID del
211 /// seleccionado, parseable como cualquier text/UUID al submit.
212 EntityRef,
213}
214
215/// Acciones disparables por menús, botones o submit de formularios.
216#[derive(Debug, Clone, Serialize, Deserialize)]
217#[serde(tag = "kind", rename_all = "snake_case")]
218pub enum Action {
219 /// Cambia la vista activa a otra del mismo módulo.
220 OpenView {
221 view: String,
222 /// Etiqueta del botón / item; default = nombre humano de la vista.
223 #[serde(default)]
224 label: Option<String>,
225 },
226 /// Crea un seed directo en la entity con los valores del form.
227 /// Equivalente a `nakui_core::event_log::seed_and_log`.
228 /// Sin pipeline de morphism — alta administrativa.
229 SeedEntity {
230 entity: String,
231 /// Tras el submit exitoso, opcionalmente abrir esta vista
232 /// (por convención: `"list"` para volver al listado).
233 #[serde(default)]
234 next_view: Option<String>,
235 },
236 /// Ejecuta un morphism declarado en el manifest del módulo
237 /// nakui-core (cuyo path vive en `Module.nakui_module_dir`).
238 /// Inputs (records existentes) y params (valores escalares) se
239 /// mapean desde los campos del form.
240 Morphism {
241 /// Nombre del morphism declarado en `nsmc.json` del manifest
242 /// nakui apuntado por el módulo.
243 name: String,
244 /// Mapeo `role → field_name`: por cada input declarado en
245 /// el `MorphismSpec.inputs`, indica qué field del form
246 /// contiene el UUID del record. El runtime parsea el value
247 /// como `Uuid` y lo pasa como input al `execute_and_log`.
248 ///
249 /// Ej: `{ "stock": "stock_id", "caja": "caja_id" }` para un
250 /// morphism `vender` que toma roles `stock` y `caja`.
251 #[serde(default)]
252 inputs: BTreeMap<String, String>,
253 /// Lista de fields del form cuyos values van al `params`
254 /// JSON object pasado al morphism. Si está vacío, todos los
255 /// fields que no estén en `inputs` van a params.
256 #[serde(default)]
257 params: Vec<String>,
258 #[serde(default)]
259 next_view: Option<String>,
260 },
261}
262
263#[derive(Debug, Clone, Serialize, Deserialize)]
264pub struct EntitySpec {
265 /// Nombre de la entity (clave en el store). Único dentro del módulo.
266 pub name: String,
267 /// Label legible (singular).
268 pub label: String,
269 /// Campos esperados en records de esta entity. Usados por el
270 /// runtime para inferir columnas / validar formularios.
271 #[serde(default)]
272 pub fields: Vec<FieldSpec>,
273}
274
275#[derive(Debug, Error)]
276pub enum SchemaError {
277 #[error("io leyendo {path}: {source}")]
278 Io {
279 path: PathBuf,
280 #[source]
281 source: std::io::Error,
282 },
283 #[error("parseo de {path}: {source}")]
284 Parse {
285 path: PathBuf,
286 #[source]
287 source: serde_json::Error,
288 },
289 #[error("módulo {id}: la vista '{view}' referenciada por menu_item '{item}' no existe")]
290 DanglingMenuView {
291 id: String,
292 item: String,
293 view: String,
294 },
295 #[error("módulos con id duplicado: '{id}' aparece en {first} y {second}")]
296 DuplicateModuleId {
297 id: String,
298 first: PathBuf,
299 second: PathBuf,
300 },
301 #[error(
302 "módulo {id} vista '{view}': field '{field}' tiene kind=entity_ref \
303 pero no declaró ref_entity"
304 )]
305 EntityRefMissingTarget {
306 id: String,
307 view: String,
308 field: String,
309 },
310}
311
312impl Module {
313 /// Carga un module.json desde disco. Validación estructural
314 /// posterior (vistas referenciadas existen, etc.) la ejecuta el
315 /// runtime — acá sólo parseamos.
316 pub fn from_path(path: impl AsRef<Path>) -> Result<Self, SchemaError> {
317 let path = path.as_ref();
318 let bytes = std::fs::read(path).map_err(|source| SchemaError::Io {
319 path: path.to_path_buf(),
320 source,
321 })?;
322 serde_json::from_slice(&bytes).map_err(|source| SchemaError::Parse {
323 path: path.to_path_buf(),
324 source,
325 })
326 }
327
328 /// Validación post-parse:
329 /// - Cada `MenuItem.view` debe existir en `views`.
330 /// - Cada `FieldSpec` con `kind=EntityRef` debe declarar
331 /// `ref_entity`.
332 pub fn validate(&self) -> Result<(), SchemaError> {
333 for item in &self.menu {
334 if !self.views.contains_key(&item.view) {
335 return Err(SchemaError::DanglingMenuView {
336 id: self.id.clone(),
337 item: item.label.clone(),
338 view: item.view.clone(),
339 });
340 }
341 }
342 for (view_key, view) in &self.views {
343 if let View::Form(form) = view {
344 for f in &form.fields {
345 if f.kind == FieldKind::EntityRef && f.ref_entity.is_none() {
346 return Err(SchemaError::EntityRefMissingTarget {
347 id: self.id.clone(),
348 view: view_key.clone(),
349 field: f.name.clone(),
350 });
351 }
352 }
353 }
354 }
355 Ok(())
356 }
357}
358
359/// Carga todos los `module.json` encontrados bajo `dir` (recursivo
360/// 1 nivel — espera `dir/<modulo>/module.json`). Devuelve la lista
361/// ordenada por id, validada.
362///
363/// Falla si: I/O, parseo, módulo inválido, o ids duplicados.
364pub fn load_modules_from_dir(dir: impl AsRef<Path>) -> Result<Vec<Module>, SchemaError> {
365 let dir = dir.as_ref();
366 let mut modules: Vec<(PathBuf, Module)> = Vec::new();
367 let entries = std::fs::read_dir(dir).map_err(|source| SchemaError::Io {
368 path: dir.to_path_buf(),
369 source,
370 })?;
371 for entry in entries.flatten() {
372 let p = entry.path();
373 if p.is_dir() {
374 let manifest = p.join("module.json");
375 if manifest.exists() {
376 let m = Module::from_path(&manifest)?;
377 m.validate()?;
378 modules.push((manifest, m));
379 }
380 }
381 }
382 // Detectar duplicados de id.
383 modules.sort_by(|a, b| a.1.id.cmp(&b.1.id));
384 let mut prev: Option<&(PathBuf, Module)> = None;
385 for cur in &modules {
386 if let Some(p) = prev {
387 if p.1.id == cur.1.id {
388 return Err(SchemaError::DuplicateModuleId {
389 id: cur.1.id.clone(),
390 first: p.0.clone(),
391 second: cur.0.clone(),
392 });
393 }
394 }
395 prev = Some(cur);
396 }
397 Ok(modules.into_iter().map(|(_, m)| m).collect())
398}
399
400#[cfg(test)]
401mod tests {
402 use super::*;
403
404 fn sample_module() -> Module {
405 Module {
406 id: "customers".into(),
407 label: "Clientes".into(),
408 description: Some("Gestión de clientes".into()),
409 nakui_module_dir: None,
410 entities: vec![EntitySpec {
411 name: "customer".into(),
412 label: "Cliente".into(),
413 fields: vec![
414 FieldSpec {
415 name: "name".into(),
416 label: "Nombre".into(),
417 kind: FieldKind::Text,
418 default: None,
419 required: true,
420 help: None,
421 ref_entity: None,
422 },
423 FieldSpec {
424 name: "email".into(),
425 label: "Email".into(),
426 kind: FieldKind::Text,
427 default: None,
428 required: false,
429 help: Some("Opcional".into()),
430 ref_entity: None,
431 },
432 ],
433 }],
434 menu: vec![
435 MenuItem {
436 label: "Listar".into(),
437 view: "list".into(),
438 icon: None,
439 },
440 MenuItem {
441 label: "Nuevo".into(),
442 view: "form".into(),
443 icon: None,
444 },
445 ],
446 views: BTreeMap::from([
447 (
448 "list".into(),
449 View::List(ListView {
450 title: "Clientes".into(),
451 entity: "customer".into(),
452 columns: vec![
453 Column {
454 field: "name".into(),
455 label: "Nombre".into(),
456 weight: 2.0,
457 },
458 Column {
459 field: "email".into(),
460 label: "Email".into(),
461 weight: 3.0,
462 },
463 ],
464 actions: vec![Action::OpenView {
465 view: "form".into(),
466 label: Some("Nuevo".into()),
467 }],
468 search_in: vec!["name".into(), "email".into()],
469 }),
470 ),
471 (
472 "form".into(),
473 View::Form(FormView {
474 title: "Nuevo cliente".into(),
475 entity: "customer".into(),
476 fields: vec![FieldSpec {
477 name: "name".into(),
478 label: "Nombre".into(),
479 kind: FieldKind::Text,
480 default: None,
481 required: true,
482 help: None,
483 ref_entity: None,
484 }],
485 on_submit: Action::SeedEntity {
486 entity: "customer".into(),
487 next_view: Some("list".into()),
488 },
489 }),
490 ),
491 ]),
492 }
493 }
494
495 #[test]
496 fn module_serialize_deserialize_roundtrip() {
497 let m = sample_module();
498 let s = serde_json::to_string_pretty(&m).unwrap();
499 let m2: Module = serde_json::from_str(&s).unwrap();
500 assert_eq!(m.id, m2.id);
501 assert_eq!(m.menu.len(), m2.menu.len());
502 assert_eq!(m.views.len(), m2.views.len());
503 }
504
505 #[test]
506 fn validate_passes_for_well_formed_module() {
507 sample_module().validate().unwrap();
508 }
509
510 #[test]
511 fn validate_catches_dangling_menu_view() {
512 let mut m = sample_module();
513 m.menu.push(MenuItem {
514 label: "Roto".into(),
515 view: "no_existe".into(),
516 icon: None,
517 });
518 let err = m.validate().unwrap_err();
519 assert!(matches!(err, SchemaError::DanglingMenuView { .. }));
520 }
521
522 #[test]
523 fn from_path_loads_real_file() {
524 let tmp = tempfile::tempdir().unwrap();
525 let path = tmp.path().join("module.json");
526 std::fs::write(&path, serde_json::to_vec_pretty(&sample_module()).unwrap()).unwrap();
527 let m = Module::from_path(&path).unwrap();
528 assert_eq!(m.id, "customers");
529 }
530
531 #[test]
532 fn load_modules_from_dir_finds_subdirs() {
533 let tmp = tempfile::tempdir().unwrap();
534 let cust_dir = tmp.path().join("customers");
535 std::fs::create_dir(&cust_dir).unwrap();
536 let mut m1 = sample_module();
537 m1.id = "customers".into();
538 std::fs::write(
539 cust_dir.join("module.json"),
540 serde_json::to_vec_pretty(&m1).unwrap(),
541 )
542 .unwrap();
543 let prod_dir = tmp.path().join("products");
544 std::fs::create_dir(&prod_dir).unwrap();
545 let mut m2 = sample_module();
546 m2.id = "products".into();
547 std::fs::write(
548 prod_dir.join("module.json"),
549 serde_json::to_vec_pretty(&m2).unwrap(),
550 )
551 .unwrap();
552
553 let mods = load_modules_from_dir(tmp.path()).unwrap();
554 assert_eq!(mods.len(), 2);
555 assert_eq!(mods[0].id, "customers");
556 assert_eq!(mods[1].id, "products");
557 }
558
559 #[test]
560 fn validate_catches_entity_ref_without_target() {
561 let mut m = sample_module();
562 // Inyectamos un form con un campo EntityRef sin ref_entity.
563 m.views.insert(
564 "broken_form".into(),
565 View::Form(FormView {
566 title: "Roto".into(),
567 entity: "customer".into(),
568 fields: vec![FieldSpec {
569 name: "ref_to_nowhere".into(),
570 label: "Referencia".into(),
571 kind: FieldKind::EntityRef,
572 default: None,
573 required: true,
574 help: None,
575 ref_entity: None,
576 }],
577 on_submit: Action::SeedEntity {
578 entity: "customer".into(),
579 next_view: None,
580 },
581 }),
582 );
583 let err = m.validate().unwrap_err();
584 assert!(
585 matches!(err, SchemaError::EntityRefMissingTarget { .. }),
586 "got: {err:?}"
587 );
588 }
589
590 #[test]
591 fn entity_ref_with_target_validates_clean() {
592 let mut m = sample_module();
593 m.views.insert(
594 "ok_form".into(),
595 View::Form(FormView {
596 title: "OK".into(),
597 entity: "customer".into(),
598 fields: vec![FieldSpec {
599 name: "supplier".into(),
600 label: "Proveedor".into(),
601 kind: FieldKind::EntityRef,
602 default: None,
603 required: true,
604 help: None,
605 ref_entity: Some("supplier".into()),
606 }],
607 on_submit: Action::SeedEntity {
608 entity: "customer".into(),
609 next_view: None,
610 },
611 }),
612 );
613 m.menu.push(MenuItem {
614 label: "OK".into(),
615 view: "ok_form".into(),
616 icon: None,
617 });
618 m.validate().unwrap();
619 }
620
621 #[test]
622 fn load_modules_detects_duplicate_id() {
623 let tmp = tempfile::tempdir().unwrap();
624 let a_dir = tmp.path().join("a");
625 let b_dir = tmp.path().join("b");
626 std::fs::create_dir_all(&a_dir).unwrap();
627 std::fs::create_dir_all(&b_dir).unwrap();
628 let m = sample_module(); // id = "customers"
629 std::fs::write(
630 a_dir.join("module.json"),
631 serde_json::to_vec(&m).unwrap(),
632 )
633 .unwrap();
634 std::fs::write(
635 b_dir.join("module.json"),
636 serde_json::to_vec(&m).unwrap(),
637 )
638 .unwrap();
639 let err = load_modules_from_dir(tmp.path()).unwrap_err();
640 assert!(matches!(err, SchemaError::DuplicateModuleId { .. }));
641 }
642}