wu-framework 1.1.14 → 1.1.16

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.
Files changed (90) hide show
  1. package/LICENSE +39 -39
  2. package/README.md +408 -408
  3. package/dist/wu-framework.cjs.js.map +1 -1
  4. package/dist/wu-framework.dev.js +15151 -15151
  5. package/dist/wu-framework.dev.js.map +1 -1
  6. package/dist/wu-framework.esm.js.map +1 -1
  7. package/dist/wu-framework.umd.js.map +1 -1
  8. package/integrations/astro/README.md +127 -127
  9. package/integrations/astro/WuApp.astro +63 -63
  10. package/integrations/astro/WuShell.astro +39 -39
  11. package/integrations/astro/index.js +68 -68
  12. package/integrations/astro/package.json +38 -38
  13. package/integrations/astro/types.d.ts +53 -53
  14. package/package.json +161 -161
  15. package/src/adapters/angular/ai.js +30 -30
  16. package/src/adapters/angular/index.d.ts +154 -154
  17. package/src/adapters/angular/index.js +932 -932
  18. package/src/adapters/angular.d.ts +3 -3
  19. package/src/adapters/angular.js +3 -3
  20. package/src/adapters/index.js +168 -168
  21. package/src/adapters/lit/ai.js +20 -20
  22. package/src/adapters/lit/index.d.ts +120 -120
  23. package/src/adapters/lit/index.js +721 -721
  24. package/src/adapters/lit.d.ts +3 -3
  25. package/src/adapters/lit.js +3 -3
  26. package/src/adapters/preact/ai.js +33 -33
  27. package/src/adapters/preact/index.d.ts +108 -108
  28. package/src/adapters/preact/index.js +661 -661
  29. package/src/adapters/preact.d.ts +3 -3
  30. package/src/adapters/preact.js +3 -3
  31. package/src/adapters/react/index.js +48 -54
  32. package/src/adapters/react.d.ts +3 -3
  33. package/src/adapters/react.js +3 -3
  34. package/src/adapters/shared.js +64 -64
  35. package/src/adapters/solid/ai.js +32 -32
  36. package/src/adapters/solid/index.d.ts +101 -101
  37. package/src/adapters/solid/index.js +586 -586
  38. package/src/adapters/solid.d.ts +3 -3
  39. package/src/adapters/solid.js +3 -3
  40. package/src/adapters/svelte/ai.js +31 -31
  41. package/src/adapters/svelte/index.d.ts +166 -166
  42. package/src/adapters/svelte/index.js +798 -798
  43. package/src/adapters/svelte.d.ts +3 -3
  44. package/src/adapters/svelte.js +3 -3
  45. package/src/adapters/vanilla/ai.js +30 -30
  46. package/src/adapters/vanilla/index.d.ts +179 -179
  47. package/src/adapters/vanilla/index.js +785 -785
  48. package/src/adapters/vanilla.d.ts +3 -3
  49. package/src/adapters/vanilla.js +3 -3
  50. package/src/adapters/vue/ai.js +52 -52
  51. package/src/adapters/vue/index.d.ts +299 -299
  52. package/src/adapters/vue/index.js +610 -610
  53. package/src/adapters/vue.d.ts +3 -3
  54. package/src/adapters/vue.js +3 -3
  55. package/src/ai/wu-ai-actions.js +261 -261
  56. package/src/ai/wu-ai-agent.js +546 -546
  57. package/src/ai/wu-ai-browser-primitives.js +354 -354
  58. package/src/ai/wu-ai-browser.js +380 -380
  59. package/src/ai/wu-ai-context.js +332 -332
  60. package/src/ai/wu-ai-conversation.js +613 -613
  61. package/src/ai/wu-ai-orchestrate.js +1021 -1021
  62. package/src/ai/wu-ai-permissions.js +381 -381
  63. package/src/ai/wu-ai-provider.js +700 -700
  64. package/src/ai/wu-ai-schema.js +225 -225
  65. package/src/ai/wu-ai-triggers.js +396 -396
  66. package/src/ai/wu-ai.js +804 -804
  67. package/src/core/wu-app.js +236 -236
  68. package/src/core/wu-cache.js +477 -477
  69. package/src/core/wu-core.js +1398 -1398
  70. package/src/core/wu-error-boundary.js +382 -382
  71. package/src/core/wu-event-bus.js +348 -348
  72. package/src/core/wu-hooks.js +350 -350
  73. package/src/core/wu-html-parser.js +190 -190
  74. package/src/core/wu-iframe-sandbox.js +328 -328
  75. package/src/core/wu-loader.js +272 -272
  76. package/src/core/wu-logger.js +134 -134
  77. package/src/core/wu-manifest.js +509 -509
  78. package/src/core/wu-mcp-bridge.js +432 -432
  79. package/src/core/wu-overrides.js +510 -510
  80. package/src/core/wu-performance.js +228 -228
  81. package/src/core/wu-plugin.js +348 -348
  82. package/src/core/wu-prefetch.js +414 -414
  83. package/src/core/wu-proxy-sandbox.js +476 -476
  84. package/src/core/wu-sandbox.js +779 -779
  85. package/src/core/wu-script-executor.js +113 -113
  86. package/src/core/wu-snapshot-sandbox.js +227 -227
  87. package/src/core/wu-strategies.js +256 -256
  88. package/src/core/wu-style-bridge.js +477 -477
  89. package/src/index.js +224 -224
  90. package/src/utils/dependency-resolver.js +327 -327
@@ -1,610 +1,610 @@
1
- /**
2
- * 🚀 WU-FRAMEWORK VUE ADAPTER
3
- *
4
- * Simplifica la integración de Vue 3 con Wu Framework.
5
- * Convierte componentes Vue en microfrontends con UNA línea de código.
6
- *
7
- * @example
8
- * // Microfrontend (main.ts)
9
- * import { wuVue } from 'wu-framework/adapters/vue';
10
- * import App from './App.vue';
11
- *
12
- * wuVue.register('my-app', App);
13
- *
14
- * @example
15
- * // Shell (cargar microfrontend)
16
- * import { WuSlot } from 'wu-framework/adapters/vue';
17
- *
18
- * <WuSlot name="my-app" url="http://localhost:3001" />
19
- */
20
-
21
- import { logger } from '../../core/wu-logger.js';
22
-
23
- // Estado global del adapter
24
- const adapterState = {
25
- apps: new Map(),
26
- Vue: null,
27
- createApp: null,
28
- initialized: false
29
- };
30
-
31
- /**
32
- * Detecta y obtiene Vue del contexto global o lo importa
33
- */
34
- async function ensureVue() {
35
- if (adapterState.initialized) return true;
36
-
37
- try {
38
- // Intentar obtener de window
39
- if (typeof window !== 'undefined' && window.Vue) {
40
- adapterState.Vue = window.Vue;
41
- adapterState.createApp = window.Vue.createApp;
42
- adapterState.initialized = true;
43
- return true;
44
- }
45
-
46
- // Intentar import dinámico
47
- const Vue = await import('vue');
48
- adapterState.Vue = Vue;
49
- adapterState.createApp = Vue.createApp;
50
- adapterState.initialized = true;
51
- return true;
52
-
53
- } catch (error) {
54
- console.error('[WuVue] Failed to load Vue:', error);
55
- return false;
56
- }
57
- }
58
-
59
- /**
60
- * Obtiene la instancia de Wu Framework
61
- */
62
- function getWuInstance() {
63
- if (typeof window === 'undefined') return null;
64
-
65
- return window.wu
66
- || window.parent?.wu
67
- || window.top?.wu
68
- || null;
69
- }
70
-
71
- /**
72
- * Espera a que Wu Framework esté disponible
73
- */
74
- function waitForWu(timeout = 5000) {
75
- return new Promise((resolve, reject) => {
76
- const wu = getWuInstance();
77
- if (wu) {
78
- resolve(wu);
79
- return;
80
- }
81
-
82
- const startTime = Date.now();
83
-
84
- const handleWuReady = () => {
85
- cleanup();
86
- resolve(getWuInstance());
87
- };
88
-
89
- window.addEventListener('wu:ready', handleWuReady);
90
- window.addEventListener('wu:app:ready', handleWuReady);
91
-
92
- const checkInterval = setInterval(() => {
93
- const wu = getWuInstance();
94
- if (wu) {
95
- cleanup();
96
- resolve(wu);
97
- return;
98
- }
99
-
100
- if (Date.now() - startTime > timeout) {
101
- cleanup();
102
- reject(new Error(`Wu Framework not found after ${timeout}ms`));
103
- }
104
- }, 200);
105
-
106
- function cleanup() {
107
- clearInterval(checkInterval);
108
- window.removeEventListener('wu:ready', handleWuReady);
109
- window.removeEventListener('wu:app:ready', handleWuReady);
110
- }
111
- });
112
- }
113
-
114
- /**
115
- * Registra un componente Vue como microfrontend
116
- *
117
- * @param {string} appName - Nombre único del microfrontend (debe coincidir con wu.json)
118
- * @param {Object} RootComponent - Componente Vue principal (App.vue)
119
- * @param {Object} options - Opciones adicionales
120
- * @param {Function} options.setup - Función para configurar la app Vue (plugins, router, etc.)
121
- * @param {Object} options.props - Props iniciales para el componente
122
- * @param {Function} options.onMount - Callback después de montar
123
- * @param {Function} options.onUnmount - Callback antes de desmontar
124
- * @param {boolean} options.standalone - Permitir ejecución standalone (default: true)
125
- * @param {string} options.standaloneContainer - Selector para modo standalone (default: '#app')
126
- *
127
- * @example
128
- * // Básico
129
- * wuVue.register('my-app', App);
130
- *
131
- * @example
132
- * // Con plugins (Pinia, Router, etc.)
133
- * wuVue.register('my-app', App, {
134
- * setup: (app) => {
135
- * app.use(createPinia());
136
- * app.use(router);
137
- * app.component('MyGlobal', MyComponent);
138
- * }
139
- * });
140
- */
141
- async function register(appName, RootComponent, options = {}) {
142
- const {
143
- setup = null,
144
- props = {},
145
- onMount = null,
146
- onUnmount = null,
147
- standalone = true,
148
- standaloneContainer = '#app'
149
- } = options;
150
-
151
- // Asegurar que Vue está disponible
152
- const hasVue = await ensureVue();
153
- if (!hasVue) {
154
- console.error(`[WuVue] Cannot register ${appName}: Vue not available`);
155
- return false;
156
- }
157
-
158
- const { createApp } = adapterState;
159
-
160
- // Función de mount interna
161
- const mountApp = (container) => {
162
- if (!container) {
163
- console.error(`[WuVue] Mount failed for ${appName}: container is null`);
164
- return;
165
- }
166
-
167
- // Evitar doble mount
168
- if (adapterState.apps.has(appName)) {
169
- logger.warn(`[WuVue] ${appName} already mounted, unmounting first`);
170
- unmountApp();
171
- }
172
-
173
- try {
174
- // Detectar si el container está dentro de un Shadow DOM
175
- let shadowRoot = null;
176
- let element = container;
177
- while (element && element !== document.body) {
178
- if (element.getRootNode && element.getRootNode() instanceof ShadowRoot) {
179
- shadowRoot = element.getRootNode();
180
- break;
181
- }
182
- element = element.parentElement || element.host;
183
- }
184
-
185
- // Crear la aplicación Vue
186
- const app = createApp(RootComponent, props);
187
-
188
- // Ejecutar setup personalizado (plugins, router, etc.)
189
- if (setup && typeof setup === 'function') {
190
- setup(app);
191
- }
192
-
193
- // Proveer información del contexto Wu
194
- app.provide('wuAppName', appName);
195
- app.provide('wuInstance', getWuInstance());
196
-
197
- // Montar
198
- app.mount(container);
199
-
200
- // Si está en Shadow DOM, copiar estilos de Vue al Shadow DOM
201
- if (shadowRoot) {
202
- // Esperar un poco para que Vue inyecte los estilos en el head
203
- setTimeout(() => {
204
- const vueStyles = document.querySelectorAll('style[data-vite-dev-id*="/' + appName + '/"], style[data-vite-dev-id*="\\' + appName + '\\"]');
205
- vueStyles.forEach(style => {
206
- // Verificar que no esté ya en el Shadow DOM
207
- const viteId = style.getAttribute('data-vite-dev-id');
208
- if (viteId && !shadowRoot.querySelector(`style[data-vite-dev-id="${viteId}"]`)) {
209
- const clonedStyle = style.cloneNode(true);
210
- shadowRoot.insertBefore(clonedStyle, shadowRoot.firstChild);
211
- logger.debug(`[WuVue] ✅ Injected style into Shadow DOM: ${viteId}`);
212
- }
213
- });
214
-
215
- // También copiar estilos que contengan rutas del app en el viteId
216
- const allStyles = document.querySelectorAll('style[data-vite-dev-id]');
217
- allStyles.forEach(style => {
218
- const viteId = style.getAttribute('data-vite-dev-id');
219
- if (viteId && (viteId.includes(`/${appName}/`) || viteId.includes(`\\${appName}\\`))) {
220
- if (!shadowRoot.querySelector(`style[data-vite-dev-id="${viteId}"]`)) {
221
- const clonedStyle = style.cloneNode(true);
222
- shadowRoot.insertBefore(clonedStyle, shadowRoot.firstChild);
223
- logger.debug(`[WuVue] ✅ Injected app style into Shadow DOM: ${viteId}`);
224
- }
225
- }
226
- });
227
- }, 100);
228
- }
229
-
230
- // Guardar referencia
231
- adapterState.apps.set(appName, { app, container });
232
-
233
- logger.debug(`[WuVue] ✅ ${appName} mounted successfully`);
234
-
235
- if (onMount) {
236
- onMount(container, app);
237
- }
238
- } catch (error) {
239
- console.error(`[WuVue] Mount error for ${appName}:`, error);
240
- throw error;
241
- }
242
- };
243
-
244
- // Función de unmount interna
245
- const unmountApp = (container) => {
246
- const instance = adapterState.apps.get(appName);
247
-
248
- if (instance) {
249
- try {
250
- if (onUnmount) {
251
- onUnmount(instance.container, instance.app);
252
- }
253
-
254
- instance.app.unmount();
255
- adapterState.apps.delete(appName);
256
-
257
- logger.debug(`[WuVue] ✅ ${appName} unmounted successfully`);
258
- } catch (error) {
259
- console.error(`[WuVue] Unmount error for ${appName}:`, error);
260
- }
261
- }
262
-
263
- // Limpiar container si se proporciona
264
- if (container) {
265
- container.innerHTML = '';
266
- }
267
- };
268
-
269
- // Intentar registrar con Wu Framework
270
- try {
271
- const wu = await waitForWu(3000);
272
-
273
- wu.define(appName, {
274
- mount: mountApp,
275
- unmount: unmountApp
276
- });
277
-
278
- logger.debug(`[WuVue] ✅ ${appName} registered with Wu Framework`);
279
- return true;
280
-
281
- } catch (error) {
282
- logger.warn(`[WuVue] Wu Framework not available for ${appName}`);
283
-
284
- // Modo standalone si está habilitado
285
- if (standalone) {
286
- const containerElement = document.querySelector(standaloneContainer);
287
-
288
- if (containerElement) {
289
- logger.debug(`[WuVue] Running ${appName} in standalone mode`);
290
- mountApp(containerElement);
291
- return true;
292
- } else {
293
- logger.warn(`[WuVue] Standalone container ${standaloneContainer} not found`);
294
- }
295
- }
296
-
297
- return false;
298
- }
299
- }
300
-
301
- /**
302
- * Crea un componente Vue para cargar microfrontends (para el Shell)
303
- *
304
- * @example
305
- * <script setup>
306
- * import { WuSlot } from 'wu-framework/adapters/vue';
307
- * </script>
308
- *
309
- * <template>
310
- * <WuSlot name="my-app" url="http://localhost:3001" />
311
- * </template>
312
- */
313
- const WuSlot = {
314
- name: 'WuSlot',
315
-
316
- props: {
317
- name: {
318
- type: String,
319
- required: true
320
- },
321
- url: {
322
- type: String,
323
- required: true
324
- },
325
- appName: {
326
- type: String,
327
- default: null
328
- },
329
- fallbackText: {
330
- type: String,
331
- default: 'Loading...'
332
- }
333
- },
334
-
335
- emits: ['load', 'error', 'mount', 'unmount'],
336
-
337
- data() {
338
- return {
339
- loading: true,
340
- error: null,
341
- appInstance: null,
342
- containerId: null
343
- };
344
- },
345
-
346
- computed: {
347
- actualAppName() {
348
- return this.appName || this.name;
349
- }
350
- },
351
-
352
- async mounted() {
353
- await this.mountMicrofrontend();
354
- },
355
-
356
- beforeUnmount() {
357
- this.unmountMicrofrontend();
358
- },
359
-
360
- methods: {
361
- async mountMicrofrontend() {
362
- try {
363
- this.loading = true;
364
- this.error = null;
365
-
366
- const wu = getWuInstance();
367
- if (!wu) {
368
- throw new Error('Wu Framework not initialized');
369
- }
370
-
371
- // Crear container único
372
- this.containerId = `wu-slot-${this.actualAppName}-${Date.now()}`;
373
- const innerContainer = document.createElement('div');
374
- innerContainer.id = this.containerId;
375
- innerContainer.style.width = '100%';
376
- innerContainer.style.height = '100%';
377
-
378
- this.$refs.container.innerHTML = '';
379
- this.$refs.container.appendChild(innerContainer);
380
-
381
- // Crear y montar la app
382
- const app = wu.app(this.actualAppName, {
383
- url: this.url,
384
- container: `#${this.containerId}`,
385
- autoInit: true
386
- });
387
-
388
- this.appInstance = app;
389
- await app.mount();
390
-
391
- this.loading = false;
392
- this.$emit('load', { name: this.actualAppName, url: this.url });
393
- this.$emit('mount', { name: this.actualAppName, container: innerContainer });
394
-
395
- } catch (err) {
396
- console.error(`[WuSlot] Error loading ${this.actualAppName}:`, err);
397
- this.error = err.message || 'Failed to load microfrontend';
398
- this.loading = false;
399
- this.$emit('error', err);
400
- }
401
- },
402
-
403
- async unmountMicrofrontend() {
404
- if (this.appInstance) {
405
- this.$emit('unmount', { name: this.actualAppName });
406
-
407
- try {
408
- await this.appInstance.unmount();
409
- } catch (err) {
410
- logger.warn(`[WuSlot] Error unmounting ${this.actualAppName}:`, err);
411
- }
412
-
413
- this.appInstance = null;
414
- }
415
- }
416
- },
417
-
418
- template: `
419
- <div
420
- ref="container"
421
- class="wu-slot"
422
- :class="{ 'wu-slot-loading': loading, 'wu-slot-error': error }"
423
- :data-wu-app="actualAppName"
424
- :data-wu-url="url"
425
- style="min-height: 100px; position: relative;"
426
- >
427
- <div v-if="error" class="wu-slot-error-message" style="padding: 1rem; border: 1px solid #f5c6cb; border-radius: 4px; background: #f8d7da; color: #721c24;">
428
- <strong>Error loading {{ name }}</strong>
429
- <p style="margin: 0.5rem 0 0 0;">{{ error }}</p>
430
- </div>
431
- <div v-else-if="loading" class="wu-slot-loading-message" style="display: flex; align-items: center; justify-content: center; padding: 2rem; color: #666;">
432
- {{ fallbackText || 'Loading ' + name + '...' }}
433
- </div>
434
- </div>
435
- `
436
- };
437
-
438
- /**
439
- * Composable para usar el EventBus de Wu Framework en Vue 3
440
- *
441
- * @example
442
- * <script setup>
443
- * import { useWuEvents } from 'wu-framework/adapters/vue';
444
- *
445
- * const { emit, on } = useWuEvents();
446
- *
447
- * onMounted(() => {
448
- * on('user:login', (data) => logger.debug(data));
449
- * });
450
- * </script>
451
- */
452
- function useWuEvents() {
453
- const subscriptions = [];
454
-
455
- const emit = (event, data, options) => {
456
- const wu = getWuInstance();
457
- if (wu?.eventBus) {
458
- wu.eventBus.emit(event, data, options);
459
- } else {
460
- logger.warn('[useWuEvents] Wu Framework not available');
461
- }
462
- };
463
-
464
- const on = (event, callback) => {
465
- const wu = getWuInstance();
466
- if (wu?.eventBus) {
467
- const unsubscribe = wu.eventBus.on(event, callback);
468
- subscriptions.push(unsubscribe);
469
- return unsubscribe;
470
- }
471
- logger.warn('[useWuEvents] Wu Framework not available');
472
- return () => {};
473
- };
474
-
475
- const once = (event, callback) => {
476
- const wu = getWuInstance();
477
- if (wu?.eventBus) {
478
- return wu.eventBus.once(event, callback);
479
- }
480
- logger.warn('[useWuEvents] Wu Framework not available');
481
- return () => {};
482
- };
483
-
484
- const off = (event, callback) => {
485
- const wu = getWuInstance();
486
- if (wu?.eventBus) {
487
- wu.eventBus.off(event, callback);
488
- }
489
- };
490
-
491
- // Cleanup - llamar en onUnmounted
492
- const cleanup = () => {
493
- subscriptions.forEach(unsub => unsub());
494
- subscriptions.length = 0;
495
- };
496
-
497
- return { emit, on, once, off, cleanup };
498
- }
499
-
500
- /**
501
- * Composable para usar el Store de Wu Framework en Vue 3
502
- *
503
- * @example
504
- * <script setup>
505
- * import { useWuStore } from 'wu-framework/adapters/vue';
506
- *
507
- * const { state, setState, getState } = useWuStore('user');
508
- *
509
- * // state es reactivo!
510
- * logger.debug(state.value);
511
- * </script>
512
- */
513
- function useWuStore(namespace = '') {
514
- // Importar ref y watch de Vue si están disponibles
515
- const Vue = adapterState.Vue;
516
- let state;
517
- let unsubscribe = null;
518
-
519
- // Crear estado reactivo si Vue está disponible
520
- if (Vue?.ref) {
521
- const wu = getWuInstance();
522
- const initialValue = wu?.store?.get(namespace) || null;
523
- state = Vue.ref(initialValue);
524
-
525
- // Suscribirse a cambios
526
- if (wu?.store) {
527
- const pattern = namespace ? `${namespace}.*` : '*';
528
- unsubscribe = wu.store.on(pattern, () => {
529
- state.value = wu.store.get(namespace);
530
- });
531
- }
532
- } else {
533
- // Fallback sin reactividad
534
- state = { value: null };
535
- }
536
-
537
- const setState = (path, value) => {
538
- const wu = getWuInstance();
539
- if (wu?.store) {
540
- const fullPath = namespace ? `${namespace}.${path}` : path;
541
- wu.store.set(fullPath, value);
542
- }
543
- };
544
-
545
- const getState = (path = '') => {
546
- const wu = getWuInstance();
547
- if (wu?.store) {
548
- const fullPath = namespace ? (path ? `${namespace}.${path}` : namespace) : path;
549
- return wu.store.get(fullPath);
550
- }
551
- return null;
552
- };
553
-
554
- const cleanup = () => {
555
- if (unsubscribe) {
556
- unsubscribe();
557
- unsubscribe = null;
558
- }
559
- };
560
-
561
- return { state, setState, getState, cleanup };
562
- }
563
-
564
- /**
565
- * Plugin de Vue para instalar Wu Framework globalmente
566
- *
567
- * @example
568
- * import { createApp } from 'vue';
569
- * import { wuVuePlugin } from 'wu-framework/adapters/vue';
570
- *
571
- * const app = createApp(App);
572
- * app.use(wuVuePlugin);
573
- */
574
- const wuVuePlugin = {
575
- install(app, options = {}) {
576
- // Registrar componente WuSlot globalmente
577
- app.component('WuSlot', WuSlot);
578
-
579
- // Proveer acceso global a Wu
580
- app.provide('wu', getWuInstance());
581
-
582
- // Agregar propiedades globales
583
- app.config.globalProperties.$wu = getWuInstance();
584
- app.config.globalProperties.$wuEvents = useWuEvents();
585
- app.config.globalProperties.$wuStore = (ns) => useWuStore(ns);
586
-
587
- logger.debug('[WuVue] Plugin installed');
588
- }
589
- };
590
-
591
- // ============================================
592
- // AI INTEGRATION
593
- // ============================================
594
- export { createUseWuAI, useWuAI } from './ai.js';
595
- import { createUseWuAI, useWuAI } from './ai.js';
596
-
597
- // API pública del adapter
598
- export const wuVue = {
599
- register,
600
- WuSlot,
601
- useWuEvents,
602
- useWuStore,
603
- wuVuePlugin,
604
- createUseWuAI,
605
- useWuAI,
606
- getWuInstance,
607
- waitForWu
608
- };
609
-
610
- export default wuVue;
1
+ /**
2
+ * 🚀 WU-FRAMEWORK VUE ADAPTER
3
+ *
4
+ * Simplifica la integración de Vue 3 con Wu Framework.
5
+ * Convierte componentes Vue en microfrontends con UNA línea de código.
6
+ *
7
+ * @example
8
+ * // Microfrontend (main.ts)
9
+ * import { wuVue } from 'wu-framework/adapters/vue';
10
+ * import App from './App.vue';
11
+ *
12
+ * wuVue.register('my-app', App);
13
+ *
14
+ * @example
15
+ * // Shell (cargar microfrontend)
16
+ * import { WuSlot } from 'wu-framework/adapters/vue';
17
+ *
18
+ * <WuSlot name="my-app" url="http://localhost:3001" />
19
+ */
20
+
21
+ import { logger } from '../../core/wu-logger.js';
22
+
23
+ // Estado global del adapter
24
+ const adapterState = {
25
+ apps: new Map(),
26
+ Vue: null,
27
+ createApp: null,
28
+ initialized: false
29
+ };
30
+
31
+ /**
32
+ * Detecta y obtiene Vue del contexto global o lo importa
33
+ */
34
+ async function ensureVue() {
35
+ if (adapterState.initialized) return true;
36
+
37
+ try {
38
+ // Intentar obtener de window
39
+ if (typeof window !== 'undefined' && window.Vue) {
40
+ adapterState.Vue = window.Vue;
41
+ adapterState.createApp = window.Vue.createApp;
42
+ adapterState.initialized = true;
43
+ return true;
44
+ }
45
+
46
+ // Intentar import dinámico
47
+ const Vue = await import('vue');
48
+ adapterState.Vue = Vue;
49
+ adapterState.createApp = Vue.createApp;
50
+ adapterState.initialized = true;
51
+ return true;
52
+
53
+ } catch (error) {
54
+ console.error('[WuVue] Failed to load Vue:', error);
55
+ return false;
56
+ }
57
+ }
58
+
59
+ /**
60
+ * Obtiene la instancia de Wu Framework
61
+ */
62
+ function getWuInstance() {
63
+ if (typeof window === 'undefined') return null;
64
+
65
+ return window.wu
66
+ || window.parent?.wu
67
+ || window.top?.wu
68
+ || null;
69
+ }
70
+
71
+ /**
72
+ * Espera a que Wu Framework esté disponible
73
+ */
74
+ function waitForWu(timeout = 5000) {
75
+ return new Promise((resolve, reject) => {
76
+ const wu = getWuInstance();
77
+ if (wu) {
78
+ resolve(wu);
79
+ return;
80
+ }
81
+
82
+ const startTime = Date.now();
83
+
84
+ const handleWuReady = () => {
85
+ cleanup();
86
+ resolve(getWuInstance());
87
+ };
88
+
89
+ window.addEventListener('wu:ready', handleWuReady);
90
+ window.addEventListener('wu:app:ready', handleWuReady);
91
+
92
+ const checkInterval = setInterval(() => {
93
+ const wu = getWuInstance();
94
+ if (wu) {
95
+ cleanup();
96
+ resolve(wu);
97
+ return;
98
+ }
99
+
100
+ if (Date.now() - startTime > timeout) {
101
+ cleanup();
102
+ reject(new Error(`Wu Framework not found after ${timeout}ms`));
103
+ }
104
+ }, 200);
105
+
106
+ function cleanup() {
107
+ clearInterval(checkInterval);
108
+ window.removeEventListener('wu:ready', handleWuReady);
109
+ window.removeEventListener('wu:app:ready', handleWuReady);
110
+ }
111
+ });
112
+ }
113
+
114
+ /**
115
+ * Registra un componente Vue como microfrontend
116
+ *
117
+ * @param {string} appName - Nombre único del microfrontend (debe coincidir con wu.json)
118
+ * @param {Object} RootComponent - Componente Vue principal (App.vue)
119
+ * @param {Object} options - Opciones adicionales
120
+ * @param {Function} options.setup - Función para configurar la app Vue (plugins, router, etc.)
121
+ * @param {Object} options.props - Props iniciales para el componente
122
+ * @param {Function} options.onMount - Callback después de montar
123
+ * @param {Function} options.onUnmount - Callback antes de desmontar
124
+ * @param {boolean} options.standalone - Permitir ejecución standalone (default: true)
125
+ * @param {string} options.standaloneContainer - Selector para modo standalone (default: '#app')
126
+ *
127
+ * @example
128
+ * // Básico
129
+ * wuVue.register('my-app', App);
130
+ *
131
+ * @example
132
+ * // Con plugins (Pinia, Router, etc.)
133
+ * wuVue.register('my-app', App, {
134
+ * setup: (app) => {
135
+ * app.use(createPinia());
136
+ * app.use(router);
137
+ * app.component('MyGlobal', MyComponent);
138
+ * }
139
+ * });
140
+ */
141
+ async function register(appName, RootComponent, options = {}) {
142
+ const {
143
+ setup = null,
144
+ props = {},
145
+ onMount = null,
146
+ onUnmount = null,
147
+ standalone = true,
148
+ standaloneContainer = '#app'
149
+ } = options;
150
+
151
+ // Asegurar que Vue está disponible
152
+ const hasVue = await ensureVue();
153
+ if (!hasVue) {
154
+ console.error(`[WuVue] Cannot register ${appName}: Vue not available`);
155
+ return false;
156
+ }
157
+
158
+ const { createApp } = adapterState;
159
+
160
+ // Función de mount interna
161
+ const mountApp = (container) => {
162
+ if (!container) {
163
+ console.error(`[WuVue] Mount failed for ${appName}: container is null`);
164
+ return;
165
+ }
166
+
167
+ // Evitar doble mount
168
+ if (adapterState.apps.has(appName)) {
169
+ logger.warn(`[WuVue] ${appName} already mounted, unmounting first`);
170
+ unmountApp();
171
+ }
172
+
173
+ try {
174
+ // Detectar si el container está dentro de un Shadow DOM
175
+ let shadowRoot = null;
176
+ let element = container;
177
+ while (element && element !== document.body) {
178
+ if (element.getRootNode && element.getRootNode() instanceof ShadowRoot) {
179
+ shadowRoot = element.getRootNode();
180
+ break;
181
+ }
182
+ element = element.parentElement || element.host;
183
+ }
184
+
185
+ // Crear la aplicación Vue
186
+ const app = createApp(RootComponent, props);
187
+
188
+ // Ejecutar setup personalizado (plugins, router, etc.)
189
+ if (setup && typeof setup === 'function') {
190
+ setup(app);
191
+ }
192
+
193
+ // Proveer información del contexto Wu
194
+ app.provide('wuAppName', appName);
195
+ app.provide('wuInstance', getWuInstance());
196
+
197
+ // Montar
198
+ app.mount(container);
199
+
200
+ // Si está en Shadow DOM, copiar estilos de Vue al Shadow DOM
201
+ if (shadowRoot) {
202
+ // Esperar un poco para que Vue inyecte los estilos en el head
203
+ setTimeout(() => {
204
+ const vueStyles = document.querySelectorAll('style[data-vite-dev-id*="/' + appName + '/"], style[data-vite-dev-id*="\\' + appName + '\\"]');
205
+ vueStyles.forEach(style => {
206
+ // Verificar que no esté ya en el Shadow DOM
207
+ const viteId = style.getAttribute('data-vite-dev-id');
208
+ if (viteId && !shadowRoot.querySelector(`style[data-vite-dev-id="${viteId}"]`)) {
209
+ const clonedStyle = style.cloneNode(true);
210
+ shadowRoot.insertBefore(clonedStyle, shadowRoot.firstChild);
211
+ logger.debug(`[WuVue] ✅ Injected style into Shadow DOM: ${viteId}`);
212
+ }
213
+ });
214
+
215
+ // También copiar estilos que contengan rutas del app en el viteId
216
+ const allStyles = document.querySelectorAll('style[data-vite-dev-id]');
217
+ allStyles.forEach(style => {
218
+ const viteId = style.getAttribute('data-vite-dev-id');
219
+ if (viteId && (viteId.includes(`/${appName}/`) || viteId.includes(`\\${appName}\\`))) {
220
+ if (!shadowRoot.querySelector(`style[data-vite-dev-id="${viteId}"]`)) {
221
+ const clonedStyle = style.cloneNode(true);
222
+ shadowRoot.insertBefore(clonedStyle, shadowRoot.firstChild);
223
+ logger.debug(`[WuVue] ✅ Injected app style into Shadow DOM: ${viteId}`);
224
+ }
225
+ }
226
+ });
227
+ }, 100);
228
+ }
229
+
230
+ // Guardar referencia
231
+ adapterState.apps.set(appName, { app, container });
232
+
233
+ logger.debug(`[WuVue] ✅ ${appName} mounted successfully`);
234
+
235
+ if (onMount) {
236
+ onMount(container, app);
237
+ }
238
+ } catch (error) {
239
+ console.error(`[WuVue] Mount error for ${appName}:`, error);
240
+ throw error;
241
+ }
242
+ };
243
+
244
+ // Función de unmount interna
245
+ const unmountApp = (container) => {
246
+ const instance = adapterState.apps.get(appName);
247
+
248
+ if (instance) {
249
+ try {
250
+ if (onUnmount) {
251
+ onUnmount(instance.container, instance.app);
252
+ }
253
+
254
+ instance.app.unmount();
255
+ adapterState.apps.delete(appName);
256
+
257
+ logger.debug(`[WuVue] ✅ ${appName} unmounted successfully`);
258
+ } catch (error) {
259
+ console.error(`[WuVue] Unmount error for ${appName}:`, error);
260
+ }
261
+ }
262
+
263
+ // Limpiar container si se proporciona
264
+ if (container) {
265
+ container.innerHTML = '';
266
+ }
267
+ };
268
+
269
+ // Intentar registrar con Wu Framework
270
+ try {
271
+ const wu = await waitForWu(3000);
272
+
273
+ wu.define(appName, {
274
+ mount: mountApp,
275
+ unmount: unmountApp
276
+ });
277
+
278
+ logger.debug(`[WuVue] ✅ ${appName} registered with Wu Framework`);
279
+ return true;
280
+
281
+ } catch (error) {
282
+ logger.warn(`[WuVue] Wu Framework not available for ${appName}`);
283
+
284
+ // Modo standalone si está habilitado
285
+ if (standalone) {
286
+ const containerElement = document.querySelector(standaloneContainer);
287
+
288
+ if (containerElement) {
289
+ logger.debug(`[WuVue] Running ${appName} in standalone mode`);
290
+ mountApp(containerElement);
291
+ return true;
292
+ } else {
293
+ logger.warn(`[WuVue] Standalone container ${standaloneContainer} not found`);
294
+ }
295
+ }
296
+
297
+ return false;
298
+ }
299
+ }
300
+
301
+ /**
302
+ * Crea un componente Vue para cargar microfrontends (para el Shell)
303
+ *
304
+ * @example
305
+ * <script setup>
306
+ * import { WuSlot } from 'wu-framework/adapters/vue';
307
+ * </script>
308
+ *
309
+ * <template>
310
+ * <WuSlot name="my-app" url="http://localhost:3001" />
311
+ * </template>
312
+ */
313
+ const WuSlot = {
314
+ name: 'WuSlot',
315
+
316
+ props: {
317
+ name: {
318
+ type: String,
319
+ required: true
320
+ },
321
+ url: {
322
+ type: String,
323
+ required: true
324
+ },
325
+ appName: {
326
+ type: String,
327
+ default: null
328
+ },
329
+ fallbackText: {
330
+ type: String,
331
+ default: 'Loading...'
332
+ }
333
+ },
334
+
335
+ emits: ['load', 'error', 'mount', 'unmount'],
336
+
337
+ data() {
338
+ return {
339
+ loading: true,
340
+ error: null,
341
+ appInstance: null,
342
+ containerId: null
343
+ };
344
+ },
345
+
346
+ computed: {
347
+ actualAppName() {
348
+ return this.appName || this.name;
349
+ }
350
+ },
351
+
352
+ async mounted() {
353
+ await this.mountMicrofrontend();
354
+ },
355
+
356
+ beforeUnmount() {
357
+ this.unmountMicrofrontend();
358
+ },
359
+
360
+ methods: {
361
+ async mountMicrofrontend() {
362
+ try {
363
+ this.loading = true;
364
+ this.error = null;
365
+
366
+ const wu = getWuInstance();
367
+ if (!wu) {
368
+ throw new Error('Wu Framework not initialized');
369
+ }
370
+
371
+ // Crear container único
372
+ this.containerId = `wu-slot-${this.actualAppName}-${Date.now()}`;
373
+ const innerContainer = document.createElement('div');
374
+ innerContainer.id = this.containerId;
375
+ innerContainer.style.width = '100%';
376
+ innerContainer.style.height = '100%';
377
+
378
+ this.$refs.container.innerHTML = '';
379
+ this.$refs.container.appendChild(innerContainer);
380
+
381
+ // Crear y montar la app
382
+ const app = wu.app(this.actualAppName, {
383
+ url: this.url,
384
+ container: `#${this.containerId}`,
385
+ autoInit: true
386
+ });
387
+
388
+ this.appInstance = app;
389
+ await app.mount();
390
+
391
+ this.loading = false;
392
+ this.$emit('load', { name: this.actualAppName, url: this.url });
393
+ this.$emit('mount', { name: this.actualAppName, container: innerContainer });
394
+
395
+ } catch (err) {
396
+ console.error(`[WuSlot] Error loading ${this.actualAppName}:`, err);
397
+ this.error = err.message || 'Failed to load microfrontend';
398
+ this.loading = false;
399
+ this.$emit('error', err);
400
+ }
401
+ },
402
+
403
+ async unmountMicrofrontend() {
404
+ if (this.appInstance) {
405
+ this.$emit('unmount', { name: this.actualAppName });
406
+
407
+ try {
408
+ await this.appInstance.unmount();
409
+ } catch (err) {
410
+ logger.warn(`[WuSlot] Error unmounting ${this.actualAppName}:`, err);
411
+ }
412
+
413
+ this.appInstance = null;
414
+ }
415
+ }
416
+ },
417
+
418
+ template: `
419
+ <div
420
+ ref="container"
421
+ class="wu-slot"
422
+ :class="{ 'wu-slot-loading': loading, 'wu-slot-error': error }"
423
+ :data-wu-app="actualAppName"
424
+ :data-wu-url="url"
425
+ style="min-height: 100px; position: relative;"
426
+ >
427
+ <div v-if="error" class="wu-slot-error-message" style="padding: 1rem; border: 1px solid #f5c6cb; border-radius: 4px; background: #f8d7da; color: #721c24;">
428
+ <strong>Error loading {{ name }}</strong>
429
+ <p style="margin: 0.5rem 0 0 0;">{{ error }}</p>
430
+ </div>
431
+ <div v-else-if="loading" class="wu-slot-loading-message" style="display: flex; align-items: center; justify-content: center; padding: 2rem; color: #666;">
432
+ {{ fallbackText || 'Loading ' + name + '...' }}
433
+ </div>
434
+ </div>
435
+ `
436
+ };
437
+
438
+ /**
439
+ * Composable para usar el EventBus de Wu Framework en Vue 3
440
+ *
441
+ * @example
442
+ * <script setup>
443
+ * import { useWuEvents } from 'wu-framework/adapters/vue';
444
+ *
445
+ * const { emit, on } = useWuEvents();
446
+ *
447
+ * onMounted(() => {
448
+ * on('user:login', (data) => logger.debug(data));
449
+ * });
450
+ * </script>
451
+ */
452
+ function useWuEvents() {
453
+ const subscriptions = [];
454
+
455
+ const emit = (event, data, options) => {
456
+ const wu = getWuInstance();
457
+ if (wu?.eventBus) {
458
+ wu.eventBus.emit(event, data, options);
459
+ } else {
460
+ logger.warn('[useWuEvents] Wu Framework not available');
461
+ }
462
+ };
463
+
464
+ const on = (event, callback) => {
465
+ const wu = getWuInstance();
466
+ if (wu?.eventBus) {
467
+ const unsubscribe = wu.eventBus.on(event, callback);
468
+ subscriptions.push(unsubscribe);
469
+ return unsubscribe;
470
+ }
471
+ logger.warn('[useWuEvents] Wu Framework not available');
472
+ return () => {};
473
+ };
474
+
475
+ const once = (event, callback) => {
476
+ const wu = getWuInstance();
477
+ if (wu?.eventBus) {
478
+ return wu.eventBus.once(event, callback);
479
+ }
480
+ logger.warn('[useWuEvents] Wu Framework not available');
481
+ return () => {};
482
+ };
483
+
484
+ const off = (event, callback) => {
485
+ const wu = getWuInstance();
486
+ if (wu?.eventBus) {
487
+ wu.eventBus.off(event, callback);
488
+ }
489
+ };
490
+
491
+ // Cleanup - llamar en onUnmounted
492
+ const cleanup = () => {
493
+ subscriptions.forEach(unsub => unsub());
494
+ subscriptions.length = 0;
495
+ };
496
+
497
+ return { emit, on, once, off, cleanup };
498
+ }
499
+
500
+ /**
501
+ * Composable para usar el Store de Wu Framework en Vue 3
502
+ *
503
+ * @example
504
+ * <script setup>
505
+ * import { useWuStore } from 'wu-framework/adapters/vue';
506
+ *
507
+ * const { state, setState, getState } = useWuStore('user');
508
+ *
509
+ * // state es reactivo!
510
+ * logger.debug(state.value);
511
+ * </script>
512
+ */
513
+ function useWuStore(namespace = '') {
514
+ // Importar ref y watch de Vue si están disponibles
515
+ const Vue = adapterState.Vue;
516
+ let state;
517
+ let unsubscribe = null;
518
+
519
+ // Crear estado reactivo si Vue está disponible
520
+ if (Vue?.ref) {
521
+ const wu = getWuInstance();
522
+ const initialValue = wu?.store?.get(namespace) || null;
523
+ state = Vue.ref(initialValue);
524
+
525
+ // Suscribirse a cambios
526
+ if (wu?.store) {
527
+ const pattern = namespace ? `${namespace}.*` : '*';
528
+ unsubscribe = wu.store.on(pattern, () => {
529
+ state.value = wu.store.get(namespace);
530
+ });
531
+ }
532
+ } else {
533
+ // Fallback sin reactividad
534
+ state = { value: null };
535
+ }
536
+
537
+ const setState = (path, value) => {
538
+ const wu = getWuInstance();
539
+ if (wu?.store) {
540
+ const fullPath = namespace ? `${namespace}.${path}` : path;
541
+ wu.store.set(fullPath, value);
542
+ }
543
+ };
544
+
545
+ const getState = (path = '') => {
546
+ const wu = getWuInstance();
547
+ if (wu?.store) {
548
+ const fullPath = namespace ? (path ? `${namespace}.${path}` : namespace) : path;
549
+ return wu.store.get(fullPath);
550
+ }
551
+ return null;
552
+ };
553
+
554
+ const cleanup = () => {
555
+ if (unsubscribe) {
556
+ unsubscribe();
557
+ unsubscribe = null;
558
+ }
559
+ };
560
+
561
+ return { state, setState, getState, cleanup };
562
+ }
563
+
564
+ /**
565
+ * Plugin de Vue para instalar Wu Framework globalmente
566
+ *
567
+ * @example
568
+ * import { createApp } from 'vue';
569
+ * import { wuVuePlugin } from 'wu-framework/adapters/vue';
570
+ *
571
+ * const app = createApp(App);
572
+ * app.use(wuVuePlugin);
573
+ */
574
+ const wuVuePlugin = {
575
+ install(app, options = {}) {
576
+ // Registrar componente WuSlot globalmente
577
+ app.component('WuSlot', WuSlot);
578
+
579
+ // Proveer acceso global a Wu
580
+ app.provide('wu', getWuInstance());
581
+
582
+ // Agregar propiedades globales
583
+ app.config.globalProperties.$wu = getWuInstance();
584
+ app.config.globalProperties.$wuEvents = useWuEvents();
585
+ app.config.globalProperties.$wuStore = (ns) => useWuStore(ns);
586
+
587
+ logger.debug('[WuVue] Plugin installed');
588
+ }
589
+ };
590
+
591
+ // ============================================
592
+ // AI INTEGRATION
593
+ // ============================================
594
+ export { createUseWuAI, useWuAI } from './ai.js';
595
+ import { createUseWuAI, useWuAI } from './ai.js';
596
+
597
+ // API pública del adapter
598
+ export const wuVue = {
599
+ register,
600
+ WuSlot,
601
+ useWuEvents,
602
+ useWuStore,
603
+ wuVuePlugin,
604
+ createUseWuAI,
605
+ useWuAI,
606
+ getWuInstance,
607
+ waitForWu
608
+ };
609
+
610
+ export default wuVue;