BUILDING BLOCKS ARCHITECTURE

Ecosistema completo para organización y gestión de contenido con interfaces espaciales

🧱 Building Blocks Architecture

MCP Documentation - This document is designed for AI agents to understand and use the platform's building block system.

Overview

The GoGrab Space platform is built on a hierarchical building blocks architecture where simpler components compose into more complex ones:

┌─────────────────────────────────────────────────────────────────┐
│ LEVEL 5: UNIVERSE (Platform)                                    │
│   Complete applications (SaaS, E-commerce, Blog, etc.)          │
│   Composed of: Multiple Galaxies + Tenant Config + Theme        │
├─────────────────────────────────────────────────────────────────┤
│ LEVEL 4: GALAXY                                                 │
│   Feature collections with shared navigation (2+ modules)       │
│   Composed of: Related Modules + Shared Routes + Navigation     │
├─────────────────────────────────────────────────────────────────┤
│ LEVEL 3: MODULES                                                │
│   Business features (User Management, E-commerce, Auth)         │
│   Composed of: Widgets, Actions, Events, Services               │
├─────────────────────────────────────────────────────────────────┤
│ LEVEL 2: WIDGETS                                                │
│   UI Components (Button, Card, Form, Container)                 │
│   Composed of: Properties with Inputs/Outputs                   │
├─────────────────────────────────────────────────────────────────┤
│ LEVEL 1: PROPERTIES                                             │
│   Atomic values (width, color, fontSize, padding)               │
│   Stored in: MongoDB, consumed by all widgets                   │
└─────────────────────────────────────────────────────────────────┘

Level 1: Properties (Atomic Building Blocks)

What Are Properties?

Properties are the smallest reusable building blocks. They define individual configuration values that can be applied to any widget.

Property Types

Control Type Description Example
text Single-line text input Widget name, label
number Numeric value with optional min/max Width, height, padding
boolean Toggle switch Disabled, visible
color Color picker Background, text color
select Dropdown options Size (sm/md/lg), variant
slider Range slider Opacity, volume
icon Icon picker Button icon
richtext Rich text editor Content

Property Templates

Templates group related properties for easy reuse:

// Example: Spacing Template
{
  id: 'spacing',
  name: 'Spacing',
  category: 'layout',
  properties: [
    { key: 'padding', label: 'Padding', controlType: 'text' },
    { key: 'margin', label: 'Margin', controlType: 'text' },
    { key: 'gap', label: 'Gap', controlType: 'text' },
  ]
}

Backend Storage

Key Files

File Purpose
apis/backend-api/src/app/properties/properties.service.ts Backend CRUD
libs/libs-widgets/widget-builder/src/lib/services/properties-api.service.ts Frontend API
libs/libs-widgets/widgets/src/lib/services/property-bridge.service.ts Backend → Widget mapping

Level 2: Widgets (UI Components)

What Are Widgets?

Widgets are visual components that users can place on pages. They have:

Widget Structure

// Widget Definition
interface Widget {
  id: string;
  type: 'button' | 'text' | 'card' | 'container' | ...;
  properties: Record<string, unknown>;  // From properties layer
  styles: WidgetStyles;                  // CSS values
  position: { x, y, width, height };
  children?: Widget[];                   // For containers
}

Standard Widget Events

Widgets emit events through WidgetEventEmitterService:

// Emit an event
eventEmitter.emitWidgetEvent(
  'btn-1',           // widgetId
  'button',          // widgetType
  'clicked',         // eventType
  { eventName: 'submit_form' }  // payload
);

// Subscribe to events
eventEmitter.getEventsByPattern('widget.button.*').subscribe(event => {
  console.log('Button event:', event);
});

Common Widget Types

Widget Category Key Inputs Key Events
button Interactive text, buttonType, size, action clicked, actionTriggered
text Content content, tag, fontSize, textAlign -
image Media src, alt, objectFit, loading loaded, error
container Layout layout, direction, gap, padding -
card Content title, subtitle, imageUrl, variant clicked, selected
input Form value, placeholder, type, required valueChanged, validated
form Form fields, submitLabel submitted, validationFailed

Key Files

File Purpose
libs/libs-widgets/widgets/src/lib/components/ Widget components
libs/libs-widgets/widgets/src/lib/services/widget-event-emitter.service.ts Event emission
libs/libs-widgets/widgets/src/lib/services/building-blocks-registry.service.ts Block registry
libs/libs-widgets/widgets/src/lib/models/property-group.model.ts Property group UI

Level 3: Modules (Business Features) & Level 4: Galaxies

What Are Galaxies?

Galaxies are collections of 2+ related modules with shared navigation. They represent feature groupings:

// Galaxy Definition
interface Galaxy {
  id: string;
  name: string;
  slug: string;
  baseRoute: string;
  moduleIds: string[];           // At least 2 modules
  moduleRoutes: Array<{
    moduleId: string;
    route: string;
    label: string;
    order: number;
  }>;
  navigation?: {
    showInSidebar: boolean;
    sidebarGroup?: string;
    icon?: string;
  };
}

Galaxy Examples

Galaxy Modules Base Route Description
Soccer Players PlayerList, PlayerCreate, PlayerStats, TeamManagement /players Complete player management
E-Commerce Cart CartView, Checkout, OrderHistory, Wishlist /shop Shopping experience
User Administration UserList, UserCreate, UserProfile, RoleManagement /admin/users User management suite

Galaxy API

// Create a galaxy
POST /api/spaces/:spaceId/universes/:universeId/galaxies
{
  "name": "Soccer Players",
  "moduleIds": ["mod-player-list", "mod-player-create"],
  "baseRoute": "/players",
  "moduleRoutes": [
    { "moduleId": "mod-player-list", "route": "/list", "label": "All Players", "order": 1 },
    { "moduleId": "mod-player-create", "route": "/create", "label": "Add Player", "order": 2 }
  ]
}

// Add module to galaxy
POST /api/spaces/:spaceId/universes/:universeId/galaxies/:galaxyId/modules
{
  "moduleId": "mod-player-stats",
  "route": "/stats",
  "label": "Statistics",
  "order": 3
}

Key Galaxy Files

File Purpose
apis/backend-api/src/app/spaces/schemas/galaxy.schema.ts MongoDB schema
apis/backend-api/src/app/spaces/galaxies.service.ts Galaxy CRUD operations
apis/backend-api/src/app/spaces/galaxies.controller.ts REST API endpoints
libs/libs-ai/ai-generation-hub/src/lib/components/galaxy-builder/ AI generation UI
libs/libs-ai/ai-generation-hub/src/lib/services/galaxy-generation.service.ts Frontend API

What Are Modules?

What Are Modules?

Modules are self-contained business features that provide:

Module Structure

@ModuleDecorator({
  id: 'user-management',
  version: '1.0.0',
  name: 'User Management',
  repositories: [UserRepository, RoleRepository],
  permissions: [
    { id: 'users:read', resource: 'users', action: 'read' },
    { id: 'users:create', resource: 'users', action: 'create' },
  ],
})
export class UserManagementModule implements BrowserModuleContract {
  readonly manifest: ModuleManifest = {
    embeddableComponents: [
      {
        id: 'users:list-widget',
        componentType: UserListWidgetComponent,
        inputs: [
          ActionParameterBuilder.number('limit').defaultValue(5).build(),
          ActionParameterBuilder.string('roleFilter').build(),
        ],
      },
    ],
    publicActions: [
      NavigateToUserAction,
      CreateUserAction,
      UpdateUserAction,
    ],
  };
}

Module Events

Modules emit domain events for cross-module communication:

// User created event
export class UserCreatedEvent extends DomainEvent<UserCreatedPayload> {
  public override readonly eventName = 'user.created';
  
  constructor(payload: UserCreatedPayload) {
    super(payload, 'normal', {
      source: 'user-management',
      context: { tags: ['user', 'create', 'lifecycle'] },
    });
  }
}

// Subscribe in another module
eventBus.subscribe('user.created', (event) => {
  // React to user creation
});

Existing Modules

Module Path Status Description
user-management modules/new-user-management/ ✅ Complete User CRUD, roles, permissions
ecommerce modules/ecommerce/ ✅ Real Products, cart, orders
blog modules/blog/ ⚠️ Basic Blog posts
portfolio modules/portfolio/ ⚠️ Basic Portfolio items
space-management modules/space-management/ ✅ Real Space configuration

Key Files

File Purpose
libs/core/module-base/src/lib/contracts/ Module contracts
libs/core/event-system/src/lib/ Event bus
libs/libs-structural/modularity-lib/src/lib/services/module-export.service.ts Code generation

Level 5: Universe (Complete Platform)

What Is a Universe?

A Universe is a complete platform built by combining multiple galaxies:

// Universe = Multiple Galaxies + Tenant Config + Theme + Navigation
interface Universe {
  id: string;
  name: string;
  slug: string;
  tenant: TenantConfig;          // Company info, branding, settings
  galaxies: Galaxy[];            // Feature collections
  navigation: NavigationConfig;  // Sidebar, top nav, breadcrumbs
  dashboard: DashboardConfig;    // Landing page widgets
  theme: ThemeConfig;            // Visual styling
  branding: BrandingConfig;      // Logo, colors, identity
}

// Example
SaaSPlatform = {
  galaxies: [
    AuthGalaxy,          // Login, Register, Forgot Password
    UserGalaxy,          // User Management suite
    BillingGalaxy,       // Subscription, Invoices, Payments
    DashboardGalaxy,     // Analytics, Reports, Stats
  ],
  theme: { mode: 'dark', preset: 'modern' },
  domain: 'myapp.gograb.space',
}

AI-Driven Universe Generation

The AI Generation Hub generates universes from natural language using incremental sessions:

// Create a configuration session
POST /ai-api/workflow/sessions
{
  businessDescription: 'Soccer player management platform...',
  businessType: 'sports',
  companyName: 'Soccer Pro Manager',
}

// Generate sections incrementally
POST /ai-api/workflow/sessions/:sessionId/sections/tenant
POST /ai-api/workflow/sessions/:sessionId/sections/modules
POST /ai-api/workflow/sessions/:sessionId/sections/navigation
POST /ai-api/workflow/sessions/:sessionId/sections/dashboard
POST /ai-api/workflow/sessions/:sessionId/sections/theme

// Each section is validated before proceeding
// Sessions can be resumed if interrupted

Generation Modes

The AI Generation Hub supports three modes:

Mode Min Complexity Output Use Case
Module 1 entity Single module Individual feature
Galaxy 2+ modules Module collection Feature group
Universe 5+ modules Complete platform Full application

Key Universe Files

File Purpose
apis/backend-ai-api/src/app/workflow/schemas/configuration-session.schema.ts Session persistence
apis/backend-ai-api/src/app/workflow/services/section-generation.service.ts Section-by-section generation
apis/backend-ai-api/src/app/workflow/services/enhanced-validation.service.ts Validation with errors/warnings
libs/libs-ai/ai-generation-hub/ Frontend generation UI

Deployment

Platforms can be deployed to:

Key Files

File Purpose
apis/backend-ai-api/src/app/workflow/workflow.service.ts AI workflow orchestration
libs/libs-structural/modularity-lib/src/lib/components/ai-platform-generator/ Platform generation UI
apis/backend-api/src/app/modules/module-export.controller.ts File writing

Composition Rules

How Blocks Connect

Parent Child Connection Example
Widget Property Widget contains properties as inputs ButtonWidget has text, size, color
Module Widget Module contains widgets as embeddables UserModule has UserListWidget
Module Module Module uses another module EcommerceModule uses AuthModule
Galaxy Module Galaxy groups related modules (2+) PlayerGalaxy = List + Create + Stats
Universe Galaxy Universe contains multiple galaxies SaaSPlatform = Auth + Users + Billing galaxies
Container Widget Container holds child widgets CardWidget contains TextWidget + ButtonWidget

Event Flow

User Action (click button)
    ↓
Widget emits WidgetEvent
    ↓
EventBus broadcasts
    ↓
Module Action handles / Other Widget reacts
    ↓
Module emits DomainEvent
    ↓
Other Modules react / AI learns

For AI Agents

Quick Reference

// Get all building blocks
const registry = inject(BuildingBlocksRegistryService);
const allBlocks = registry.getBlocksForAI();

// Find blocks for a use case
const cartBlocks = registry.findBlocksForUseCase('shopping cart');

// Get widget events
const eventEmitter = inject(WidgetEventEmitterService);
const buttonEvents = eventEmitter.getStandardEventsForWidget('button');

// Load property templates
const propertyBridge = inject(PropertyBridgeService);
await propertyBridge.loadTemplates(spaceId);
const buttonGroups = propertyBridge.getPropertyGroupsForWidget('button');

Creating New Building Blocks

  1. New Property: Add to properties.service.ts built-in templates
  2. New Widget: Create in libs/libs-widgets/widgets/src/lib/components/
  3. New Module: Use ModuleExportService or manual creation in modules/
  4. New Galaxy: Use AI Galaxy Builder or Galaxy API in backend-api
  5. New Universe: Use AI Universe Builder with ConfigurationSession

Session 11.4 Enhancements

  1. PropertyBridgeService - Maps backend properties to widget UI
  2. BuildingBlocksRegistryService - Central registry for MCP/agents
  3. WidgetEventEmitterService - Standardized widget event emission
  4. ModuleExportController - Backend file writing for modules
  5. ModuleExportApiService - Frontend API for deployment

All building blocks are now properly documented and can be discovered programmatically by AI agents.


Session 11.5+ Enhancements (Galaxy & Universe)

Backend (backend-ai-api)

  1. ConfigurationSession Schema - MongoDB persistence for incremental generation
  2. ConfigurationSessionRepository - Data access for sessions
  3. ConfigurationSessionController - REST API for session management
  4. SectionGenerationService - Section-by-section generation with dependencies
  5. EnhancedValidationService - Validation with errors, warnings, and suggestions

Backend (backend-api)

  1. Galaxy Schema - MongoDB persistence for module groups
  2. GalaxiesService - CRUD operations for galaxies
  3. GalaxiesController - REST API for galaxy management

Frontend (libs-ai/ai-generation-hub)

  1. GenerationModeSelectorComponent - Choose Module/Galaxy/Universe mode
  2. ModuleBuilderComponent - Single module AI generation
  3. GalaxyBuilderComponent - Multi-module AI generation (2+)
  4. UniverseBuilderComponent - Full platform generation with sections
  5. LinearProgressViewerComponent - Visual progress tracking
  6. GenerationHubService - Main orchestration service
  7. GalaxyGenerationService - Galaxy API integration

Visual Canvas (libs-structural/space-map-lib)

  1. GalaxyFlowCanvasComponent (Revived) - Visual galaxy connection editor

Key Concepts

All building blocks now support the 5-level hierarchy: Properties → Widgets → Modules → Galaxies → Universe.