visual-ai-staging 0.0.1 → 0.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -10,6 +10,8 @@ on:
10
10
  jobs:
11
11
  publish:
12
12
  runs-on: ubuntu-latest
13
+ env:
14
+ FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: true
13
15
  steps:
14
16
  - name: Checkout repository
15
17
  uses: actions/checkout@v4
@@ -17,7 +19,7 @@ jobs:
17
19
  - name: Set up Node.js
18
20
  uses: actions/setup-node@v4
19
21
  with:
20
- node-version: '20'
22
+ node-version: '24'
21
23
  registry-url: 'https://registry.npmjs.org'
22
24
 
23
25
  - name: Run Milestone 4 Unit Tests
@@ -26,6 +28,13 @@ jobs:
26
28
  - name: Run Milestone 5 Unit Tests
27
29
  run: node verify_r4.js
28
30
 
31
+ - name: Sync version with Git Tag
32
+ run: |
33
+ # Extract clean version number from tag (e.g., v0.0.2 -> 0.0.2)
34
+ CLEAN_VERSION=$(echo "${{ github.ref_name }}" | sed 's/^v//')
35
+ echo "Syncing package.json version to $CLEAN_VERSION"
36
+ npm version $CLEAN_VERSION --no-git-tag-version
37
+
29
38
  - name: Publish Package to NPM Registry
30
39
  run: npm publish
31
40
  env:
package/README.md CHANGED
@@ -1,86 +1,117 @@
1
- # Visual AI Staging Companion (Fase 1: Motor Web y Sandbox)
2
- ## Guía de Pruebas Rápidas y Manual de Usuario
1
+ # Visual AI Staging (vais) 🚀
3
2
 
4
- Este repositorio contiene el prototipo funcional y de alta fidelidad de la **Fase 1 del Visual AI Staging Companion**. El sistema ha sido desarrollado bajo un flujo de trabajo riguroso de co-programación y auditoría forense de código, garantizando la ligereza (cero dependencias externas), seguridad contra XSS y total cumplimiento con políticas CSP estrictas (sin scripts ni eventos inline).
3
+ **Visual AI Staging** is a lightweight, secure, and production-ready development companion designed to bridge the gap between visual UI design staging and AI coding assistants (such as Cursor, Claude Code, ChatGPT, or custom LLM developers).
4
+
5
+ It provides frontend developers with an interactive visual sandbox to tweak styles, draw components, and record voice feedback, compiling all sessions into **high-context structured Markdown prompt recipes** optimized for AI generation.
6
+
7
+ ---
8
+
9
+ ## Key Capabilities
10
+
11
+ * **🔍 Interactive Visual Sandbox:** Inspect active DOM elements, alter dimensions (padding, margins, width, height, border radius, font-size), edit text contents, and experiment with HSL background and text colors in hot memory.
12
+ * **📐 Vector Bounding Boxes (Free-Zone Drawing):** Draw spatial annotation rectangles directly on top of your page. The engine automatically resolves the nearest structural parent container and logs your component templates.
13
+ * **🎙️ Multimodal Localized Audio:** Record voice notes attached to specific components. The engine automatically anchors floating interactive microphone badges (`🎤`) above selected elements with relative position layout compensation.
14
+ * **⚡ Smart Design Token Mapping:** Sliders automatically approximate manual pixel values to standard design tokens (e.g., `--spacing-md`, `--border-radius-lg`) to prevent the generation of static inline styling.
15
+ * **💾 Secure Hot-Persistence CLI Server:** A lightweight, pure Node.js local development server that intercepts AJAX requests to silently persist recording `.wav` assets and Markdown recipe `.md` files directly into your workspace disk.
16
+ * **📦 Safe Distribution Filters:** Strict packaging excludes configured via `.npmignore` to prevent uploading development, testing, and system metadata files.
17
+ * **🤖 Production AI-Pipeline Guardrails:** Exported prompts include pre-prompts that instruct receiving LLMs to halt execution if referred local voice recording files are not attached to the chat session, ensuring absolute context alignment.
18
+
19
+ ---
20
+
21
+ ## Installation
22
+
23
+ Install **Visual AI Staging** globally in your system using NPM:
24
+
25
+ ```bash
26
+ npm install -g visual-ai-staging
27
+ ```
28
+
29
+ *(Note: The global `-g` flag is required to register the CLI command globally in your terminal variables).*
30
+
31
+ ---
32
+
33
+ ## Quick Start
34
+
35
+ ### 1. Initialize the Staging Environment
36
+ Navigate to your project root folder and initialize the workspace to create the local staging directories:
37
+
38
+ ```bash
39
+ # Prepare the Visual AI Staging local workspace
40
+ vais init
41
+ ```
42
+
43
+ *Console Output:*
44
+ ```bash
45
+ Successfully initialized Visual AI Staging workspace!
46
+ Created directories:
47
+ - .ai-staging/audio/
48
+ - .ai-staging/feedback/
49
+ ```
50
+
51
+ ### 2. Start the Development Server
52
+ Launch the native local HTTP staging server:
53
+
54
+ ```bash
55
+ # Start the local staging daemon
56
+ vais dev
57
+ ```
58
+
59
+ *Console Output:*
60
+ ```bash
61
+ Visual AI Staging Dev Server running at http://localhost:3000/
62
+ ```
63
+
64
+ ### 3. Run Visual Staging
65
+ 1. Open your web browser and navigate to `http://localhost:3000/`.
66
+ 2. Activate **Inspection Mode** or **Free-Zone Drawing** on the toolbar.
67
+ 3. Select elements, alter visual parameters, record voice notes, and staging your layout options.
68
+ 4. Open the floating action button menu (`⚡`) and click **"Copy AI Recipe Prompt"** to copy the compiled Markdown recipe to your clipboard.
69
+ 5. Paste the recipe directly into your AI coding assistant to apply perfect-fidelity visual and structural modifications to your codebase.
5
70
 
6
71
  ---
7
72
 
8
- ## 1. ¿Cómo Probar la Aplicación de Forma Inmediata?
9
-
10
- Dado que el prototipo está construido enteramente sobre un stack web estándar (Vanilla HTML5, CSS3 y ES6+ JavaScript), **no requiere ningún proceso de compilación, instalación de paquetes npm ni servidores locales complejos.**
11
-
12
- ### Paso 1: Ejecutar la Interfaz Web
13
- 1. Abre tu navegador web (preferiblemente Google Chrome o navegadores basados en Chromium).
14
- 2. Abre el explorador de archivos y haz doble clic en el archivo `index.html` ubicado en la carpeta del proyecto:
15
- * Ruta física: `d:\Github Repos\Extensiones_Ideas\visual_ai_staging\index.html`
16
- * O arrastra y suelta el archivo `index.html` directamente dentro de una pestaña en blanco del navegador.
17
-
18
- ### Paso 2: Ejecutar las Pruebas Automatizadas (Unit Tests en Node.js)
19
- Si deseas verificar programáticamente los estados de grabación, anclajes de badges y compilación del prompt:
20
- 1. Abre tu terminal de comandos en el directorio del proyecto:
21
- ```powershell
22
- cd "d:\Github Repos\Extensiones_Ideas\visual_ai_staging"
23
- ```
24
- 2. Ejecuta los scripts de verificación unitaria con Node.js:
25
- ```powershell
26
- node verify_r3.js
27
- node verify_r4.js
28
- ```
29
- Ambas pruebas simularán el entorno completo del navegador e informarán un estado de éxito del `100% [PASS]` en la consola.
73
+ ## CLI Command Guide
74
+
75
+ ```bash
76
+ Usage: vais [options] [command]
77
+
78
+ Options:
79
+ -v, --version Output the version number
80
+ -h, --help Output usage information
81
+
82
+ Commands:
83
+ init Initialize Visual AI Staging workspace (.ai-staging/ directories)
84
+ dev Start the Visual AI Staging native development server
85
+ ```
30
86
 
31
87
  ---
32
88
 
33
- ## 2. Manual de Pruebas de Características (Paso a Paso)
34
-
35
- Una vez abierta la interfaz en el navegador, sigue este manual de usuario para experimentar la potencia del prototipo:
36
-
37
- ### A. Inspección del DOM y Sandbox Visual (Hito 2)
38
- 1. **Activar Inspección:** En la barra superior, haz clic en **"🔍 Inspection Mode"** (o abre el menú del botón flotante inferior derecho `⚡` y selecciona *"Toggle Inspector Mode"*). El cursor cambiará e indicará el modo de selección.
39
- 2. **Explorar Elementos:** Pasa el cursor por encima del área izquierda del lienzo simulado (**DOM Mock Page**). Verás cómo los botones, tarjetas de características, textos y contenedores se resaltan con contornos discontinuos en color azul.
40
- 3. **Seleccionar un Elemento:** Haz clic en cualquier elemento (ej. el botón azul *"Launch Sandbox"* o el título *"Engineered for the Autonomous Web"*).
41
- 4. **Modificar Estilos en Caliente:**
42
- * Observa el panel de staging de la derecha. Ahora muestra los metadatos exactos (Tag, Clases y Selector CSS único).
43
- * Mueve los controles deslizantes (sliders) de **Padding, Margin, Width, Height, Border Radius y Font Size**. Verás cómo el elemento del DOM en la izquierda se deforma y actualiza en tiempo real de forma suave.
44
- * Modifica los colores de **Fondo y de Texto** usando los sliders H (Tono), S (Saturación) y L (Luminosidad) en el panel de color. El swatch de color y el elemento inspectado se actualizarán al instante.
45
- 5. **Mapeador Inteligente de Tokens:** Al mover los sliders de Padding o Border Radius a valores comunes (ej. `8px` o `16px`), verás cómo se activa automáticamente un distintivo de token (ej. `--spacing-sm` o `--border-radius-md`), demostrando que la herramienta aproxima tus ajustes visuales a los estándares de diseño del proyecto.
46
- 6. **Ver Cambios Acumulados:** Observa la sección inferior derecha **"Staged Changes"**. Verás una tarjeta que resume el selector CSS del elemento y el listado de propiedades modificadas con sus valores originales frente a los nuevos.
47
- 7. **Revertir Cambios:** Haz clic en el botón rojo **"Revert"** de la tarjeta del elemento modificado en la lista lateral para restaurar sus estilos originales de forma limpia.
48
-
49
- ### B. Spatial Annotations y Bounding Boxes (Hito 3)
50
- 1. **Activar Modo Zona:** En la barra de herramientas superior, haz clic en el botón **"📐 Free-Zone Drawing"**.
51
- 2. **Dibujar una Zona:** Haz clic y arrastra con el ratón sobre cualquier área vacía o encima de componentes en el DOM Mock Page de la izquierda. Verás cómo se dibuja una caja con guías vectoriales en color violeta.
52
- 3. **Configurar la Inserción:** Al soltar el ratón, se desplegará de forma automática un modal glassmorphic premium con desenfoque de fondo. El modal ya contiene:
53
- * El selector CSS del contenedor padre más cercano resuelto automáticamente por el algoritmo de escalado semántico.
54
- * Los límites espaciales del área trazada en píxeles.
55
- 4. **Guardar Nota e Inserción:** Elige una plantilla predefinida (ej. *Carrusel de imágenes*), escribe una nota explicativa en el campo de texto (ej. *"Inyectar un slider de logos de clientes aquí"*) y haz clic en **"Confirm Staging Area"**.
56
- 5. **Revisar Registro:** En el listado lateral, verás la tarjeta de inserción en color violeta, detallando la ubicación del rectángulo vectorizado y tu nota técnica. Al salir de este modo, el lienzo SVG se limpia automáticamente.
57
-
58
- ### C. Notas de Voz y DOM Badges Flotantes (Hito 4)
59
- 1. **Seleccionar Elemento:** Selecciona un elemento del Mock Page mediante el modo inspección.
60
- 2. **Iniciar Grabación:** En el panel lateral, localiza el control del micrófono y haz clic en el botón circular **"Record Voice Note"**. (Concede permiso de micrófono en tu navegador si te lo solicita).
61
- 3. **Grabar Audio:** Verás una animación de onda interactiva palpitando y un contador de tiempo. Habla a tu micrófono de forma natural para describir el cambio de diseño (ej. *"IA, haz que esta tarjeta tenga un degradado suave y separa el texto del borde"*).
62
- 4. **Finalizar Grabación:** Haz clic en **"Stop Recording"**. Verás cómo:
63
- * El botón cambia a *"Re-record Voice Note"* y aparece un botón de reproducción de audio nativo en el panel lateral para escuchar tu mensaje.
64
- * Se crea automáticamente un archivo de audio simulado persistido en el subdirectorio local del proyecto.
65
- * **DOM Badge Reactivo:** Aparece un pequeño icono flotante de micrófono (`🎤`) pulsando visualmente **directamente encima** del elemento inspectado en la pantalla de la izquierda.
66
- 5. **Borrar Nota:** Haz clic en el botón de borrar en el panel lateral. Verás cómo el audio se destruye limpiamente de la memoria y el badge `🎤` del DOM se elimina, restaurando los offsets de diseño originales.
67
-
68
- ### D. Exportar Receta e Integración Local (Hito 5)
69
- 1. **Abrir Menú de Acción Rápida (FAB):** Haz clic en el botón circular flotante con el icono de rayo (`⚡`) ubicado en la esquina inferior derecha.
70
- 2. **Copiar Receta de Prompt:** Haz clic en **"Copy AI Recipe Prompt"**.
71
- 3. **Notificación Visual:** Verás emerger en pantalla una elegante notificación Toast glassmorphic en la esquina superior derecha informando del copiado exitoso.
72
- 4. **Revisar Receta Copiada:** Pega el portapapeles en un editor de texto (o en el chat de tu IA). Verás el pre-prompt de sistema estructurado, seguido de los selectores, cambios exactos en tokens y la referencia física absoluta a los audios grabados en tu disco (ej. `[Escuchar audio](file:///d:/Github%20Repos/Extensiones_Ideas/visual_ai_staging/.ai-staging/audio/...)`).
73
- 5. **Autoguardado en Carpeta Local:** Ve al explorador de archivos y entra en la carpeta oculta del proyecto:
74
- `visual_ai_staging/.ai-staging/feedback/`
75
- Verás un archivo Markdown autogenerado de forma silenciosa con el nombre en formato `YYYY-MM-DD_HHMMSS_feedback.md`, consolidando tu historial de diseño listo para que Git lo rastree.
89
+ ## Folder Architecture
90
+
91
+ When running `vais dev` in your workspace, the local daemon writes data locally under the `.ai-staging/` directory:
92
+
93
+ ```
94
+ your-project-root/
95
+ ├── .ai-staging/ # Local feedback data directory (Git-ignored)
96
+ │ ├── audio/ # Staged .wav voice annotation files
97
+ │ └── feedback/ # Exported markdown prompt recipes (.md)
98
+ ├── index.html # Entry page of your sandbox
99
+ ├── app.js # Staging controller, drawing layers, and audio recorder
100
+ ├── cli.js # Native Node.js CLI server binary
101
+ └── package.json # Distribution manifest
102
+ ```
103
+
104
+ ---
105
+
106
+ ## Safety & Security Guardrails
107
+
108
+ * **Zero Production Dependencies:** The CLI dev server is built entirely using Node.js native standard libraries (`http`, `fs`, `path`, `url`), eliminating third-party package security risks.
109
+ * **Path Traversal Prevention:** The HTTP dev server implements strict `path.resolve` checks to ensure no requests can access, read, or write files outside the workspace root directory (returns `403 Forbidden` on traversal attempts).
110
+ * **Filename Sanitization:** The REST backend sanitizes names using `path.basename` extraction and regex assertions (`^[a-zA-Z0-9_\-\.]+\.(wav|md)$`) to block command injection.
111
+ * **CSP & XSS Compliance:** The web engine uses event listeners (`addEventListener`) and programmatic node creations (`document.createElement` / `.textContent`) to strictly prevent DOM-based XSS vulnerabilities.
76
112
 
77
113
  ---
78
114
 
79
- ## 3. Estructura del Código del Prototipo
115
+ ## License
80
116
 
81
- El código está limpio, documentado con estándares JSDoc y estructurado para facilitar la lectura:
82
- * **Estructura e Interfaces Visuales:** `visual_ai_staging/index.html`
83
- * **Estilos del Tema Oscuro Premium y Sandbox CSS:** `visual_ai_staging/styles.css`
84
- * **Controlador Principal y Estados en Hot Memory:** `visual_ai_staging/app.js`
85
- * **Reportes de Auditoría Firmados:** `visual_ai_staging/.ai-staging/audit_reports/`
86
- * **Suites de Pruebas Node.js:** `visual_ai_staging/verify_r3.js` y `verify_r4.js`
117
+ This project is licensed under the permissive **MIT License** — feel free to use, modify, and distribute it for both commercial and personal use.
package/cli.js CHANGED
@@ -28,15 +28,64 @@ Options:
28
28
  -h, --help Output usage information
29
29
 
30
30
  Commands:
31
+ init Initialize Visual AI Staging workspace (.ai-staging/ directories)
31
32
  dev Start the Visual AI Staging native development server
32
33
  `);
33
34
  process.exit(0);
34
35
  }
35
36
 
37
+ if (command === 'init') {
38
+ const resolvedBase = path.resolve(__dirname);
39
+ const audioDir = path.join(resolvedBase, '.ai-staging', 'audio');
40
+ const feedbackDir = path.join(resolvedBase, '.ai-staging', 'feedback');
41
+
42
+ try {
43
+ let alreadyExists = fs.existsSync(audioDir) && fs.existsSync(feedbackDir);
44
+
45
+ fs.mkdirSync(audioDir, { recursive: true });
46
+ fs.mkdirSync(feedbackDir, { recursive: true });
47
+
48
+ // Create .gitkeep to ensure empty directories are tracked by Git
49
+ const gitkeepAudio = path.join(audioDir, '.gitkeep');
50
+ const gitkeepFeedback = path.join(feedbackDir, '.gitkeep');
51
+
52
+ if (!fs.existsSync(gitkeepAudio)) fs.writeFileSync(gitkeepAudio, '');
53
+ if (!fs.existsSync(gitkeepFeedback)) fs.writeFileSync(gitkeepFeedback, '');
54
+
55
+ if (alreadyExists) {
56
+ console.log('Visual AI Staging environment already initialized in this workspace.');
57
+ } else {
58
+ console.log('Successfully initialized Visual AI Staging workspace!');
59
+ console.log('Created directories:');
60
+ console.log(' - .ai-staging/audio/');
61
+ console.log(' - .ai-staging/feedback/');
62
+ }
63
+ } catch (err) {
64
+ console.error('Error initializing workspace:', err.message);
65
+ process.exit(1);
66
+ }
67
+ process.exit(0);
68
+ }
69
+
36
70
  if (command === 'dev') {
37
71
  const port = 3000;
38
72
  const resolvedBase = path.resolve(__dirname);
39
73
 
74
+ // Auto-initialize directories silently on server startup if they do not exist
75
+ const audioDir = path.join(resolvedBase, '.ai-staging', 'audio');
76
+ const feedbackDir = path.join(resolvedBase, '.ai-staging', 'feedback');
77
+ try {
78
+ fs.mkdirSync(audioDir, { recursive: true });
79
+ fs.mkdirSync(feedbackDir, { recursive: true });
80
+
81
+ const gitkeepAudio = path.join(audioDir, '.gitkeep');
82
+ const gitkeepFeedback = path.join(feedbackDir, '.gitkeep');
83
+ if (!fs.existsSync(gitkeepAudio)) fs.writeFileSync(gitkeepAudio, '');
84
+ if (!fs.existsSync(gitkeepFeedback)) fs.writeFileSync(gitkeepFeedback, '');
85
+ } catch (err) {
86
+ console.warn('Warning: Failed to auto-initialize staging directories on startup:', err.message);
87
+ }
88
+
40
89
  const server = http.createServer((req, res) => {
41
90
  const parsedUrl = url.parse(req.url, true);
42
91
  const pathname = parsedUrl.pathname;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "visual-ai-staging",
3
- "version": "0.0.1",
3
+ "version": "0.0.3",
4
4
  "description": "Visual AI Staging Companion — Bridge the gap between UI design staging and AI coding assistants.",
5
5
  "license": "MIT",
6
6
  "main": "app.js",