wu-framework 1.1.16 → 1.1.18
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.
- package/README.md +52 -20
- package/package.json +48 -3
- package/src/adapters/alpine/index.d.ts +60 -0
- package/src/adapters/alpine/index.js +231 -0
- package/src/adapters/alpine.d.ts +3 -0
- package/src/adapters/alpine.js +3 -0
- package/src/adapters/htmx/index.d.ts +60 -0
- package/src/adapters/htmx/index.js +242 -0
- package/src/adapters/htmx.d.ts +3 -0
- package/src/adapters/htmx.js +3 -0
- package/src/adapters/index.js +60 -3
- package/src/adapters/qwik/index.d.ts +52 -0
- package/src/adapters/qwik/index.js +214 -0
- package/src/adapters/qwik.d.ts +3 -0
- package/src/adapters/qwik.js +3 -0
- package/src/adapters/react/ai.js +135 -135
- package/src/adapters/react/index.d.ts +246 -246
- package/src/adapters/react/index.js +695 -695
- package/src/adapters/stencil/index.d.ts +54 -0
- package/src/adapters/stencil/index.js +228 -0
- package/src/adapters/stencil.d.ts +3 -0
- package/src/adapters/stencil.js +3 -0
- package/src/adapters/stimulus/index.d.ts +60 -0
- package/src/adapters/stimulus/index.js +255 -0
- package/src/adapters/stimulus.d.ts +3 -0
- package/src/adapters/stimulus.js +3 -0
- package/src/adapters/svelte/index.js +1 -1
- package/src/adapters/vanilla/index.js +1 -1
- package/src/adapters/vue/index.js +8 -0
- package/src/core/wu-cache.js +24 -3
- package/src/core/wu-core.js +15 -1
- package/src/core/wu-error-boundary.js +17 -3
- package/src/core/wu-event-bus.js +43 -1
- package/src/core/wu-html-parser.js +13 -4
- package/src/core/wu-loader.js +162 -50
- package/src/core/wu-logger.js +21 -13
- package/src/core/wu-manifest.js +23 -0
- package/src/core/wu-plugin.js +57 -4
- package/src/core/wu-proxy-sandbox.js +2 -1
- package/src/core/wu-script-executor.js +48 -0
- package/src/core/wu-store.js +13 -3
- package/src/index.d.ts +317 -0
- package/src/index.js +11 -1
- package/dist/wu-framework.cjs.js +0 -3
- package/dist/wu-framework.cjs.js.map +0 -1
- package/dist/wu-framework.dev.js +0 -15302
- package/dist/wu-framework.dev.js.map +0 -1
- package/dist/wu-framework.esm.js +0 -3
- package/dist/wu-framework.esm.js.map +0 -1
- package/dist/wu-framework.umd.js +0 -3
- package/dist/wu-framework.umd.js.map +0 -1
|
@@ -1,695 +1,695 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* 🚀 WU-FRAMEWORK REACT ADAPTER
|
|
3
|
-
*
|
|
4
|
-
* Simplifica la integración de React con Wu Framework.
|
|
5
|
-
* Convierte componentes React en microfrontends con UNA línea de código.
|
|
6
|
-
*
|
|
7
|
-
* @example
|
|
8
|
-
* // Microfrontend (main.tsx)
|
|
9
|
-
* import { wuReact } from 'wu-framework/adapters/react';
|
|
10
|
-
* import App from './App';
|
|
11
|
-
*
|
|
12
|
-
* wuReact.register('my-app', App);
|
|
13
|
-
*
|
|
14
|
-
* @example
|
|
15
|
-
* // Shell (cargar microfrontend)
|
|
16
|
-
* import { WuSlot } from 'wu-framework/adapters/react';
|
|
17
|
-
*
|
|
18
|
-
* <WuSlot name="my-app" url="http://localhost:3001" />
|
|
19
|
-
*/
|
|
20
|
-
|
|
21
|
-
// Estado global del adapter
|
|
22
|
-
const adapterState = {
|
|
23
|
-
roots: new Map(),
|
|
24
|
-
React: null,
|
|
25
|
-
ReactDOM: null,
|
|
26
|
-
createRoot: null,
|
|
27
|
-
initialized: false
|
|
28
|
-
};
|
|
29
|
-
|
|
30
|
-
/**
|
|
31
|
-
* Detecta y obtiene React del contexto global o lo importa
|
|
32
|
-
*/
|
|
33
|
-
async function ensureReact() {
|
|
34
|
-
if (adapterState.initialized) return true;
|
|
35
|
-
|
|
36
|
-
try {
|
|
37
|
-
// Intentar obtener de window (común en microfrontends)
|
|
38
|
-
if (typeof window !== 'undefined' && window.React && window.ReactDOM) {
|
|
39
|
-
adapterState.React = window.React;
|
|
40
|
-
adapterState.ReactDOM = window.ReactDOM;
|
|
41
|
-
|
|
42
|
-
// createRoot puede estar en window.ReactDOM (si importaron de react-dom/client)
|
|
43
|
-
// o no existir (si importaron de react-dom). Intentar ambos caminos.
|
|
44
|
-
if (window.ReactDOM.createRoot) {
|
|
45
|
-
adapterState.createRoot = window.ReactDOM.createRoot;
|
|
46
|
-
} else {
|
|
47
|
-
// Fallback: importar react-dom/client para obtener createRoot
|
|
48
|
-
try {
|
|
49
|
-
const clientModule = await import('react-dom/client');
|
|
50
|
-
adapterState.createRoot = (clientModule.default || clientModule).createRoot;
|
|
51
|
-
} catch {
|
|
52
|
-
console.error('[WuReact] createRoot not found. Expose window.ReactDOM from "react-dom/client", not "react-dom".');
|
|
53
|
-
return false;
|
|
54
|
-
}
|
|
55
|
-
}
|
|
56
|
-
|
|
57
|
-
adapterState.initialized = true;
|
|
58
|
-
return true;
|
|
59
|
-
}
|
|
60
|
-
|
|
61
|
-
// Intentar import dinámico
|
|
62
|
-
const [React, ReactDOMClient] = await Promise.all([
|
|
63
|
-
import('react'),
|
|
64
|
-
import('react-dom/client')
|
|
65
|
-
]);
|
|
66
|
-
|
|
67
|
-
adapterState.React = React.default || React;
|
|
68
|
-
adapterState.ReactDOM = ReactDOMClient.default || ReactDOMClient;
|
|
69
|
-
adapterState.createRoot = (ReactDOMClient.default || ReactDOMClient).createRoot;
|
|
70
|
-
adapterState.initialized = true;
|
|
71
|
-
return true;
|
|
72
|
-
|
|
73
|
-
} catch (error) {
|
|
74
|
-
console.error('[WuReact] Failed to load React:', error);
|
|
75
|
-
return false;
|
|
76
|
-
}
|
|
77
|
-
}
|
|
78
|
-
|
|
79
|
-
/**
|
|
80
|
-
* Obtiene la instancia de Wu Framework
|
|
81
|
-
*/
|
|
82
|
-
function getWuInstance() {
|
|
83
|
-
if (typeof window === 'undefined') return null;
|
|
84
|
-
|
|
85
|
-
return window.wu
|
|
86
|
-
|| window.parent?.wu
|
|
87
|
-
|| window.top?.wu
|
|
88
|
-
|| null;
|
|
89
|
-
}
|
|
90
|
-
|
|
91
|
-
/**
|
|
92
|
-
* Espera a que Wu Framework esté disponible (sin polling agresivo)
|
|
93
|
-
*/
|
|
94
|
-
function waitForWu(timeout = 5000) {
|
|
95
|
-
return new Promise((resolve, reject) => {
|
|
96
|
-
// Check inmediato
|
|
97
|
-
const wu = getWuInstance();
|
|
98
|
-
if (wu) {
|
|
99
|
-
resolve(wu);
|
|
100
|
-
return;
|
|
101
|
-
}
|
|
102
|
-
|
|
103
|
-
// Usar MutationObserver + evento en lugar de polling
|
|
104
|
-
const startTime = Date.now();
|
|
105
|
-
|
|
106
|
-
// Escuchar evento de Wu Framework
|
|
107
|
-
const handleWuReady = (event) => {
|
|
108
|
-
cleanup();
|
|
109
|
-
resolve(getWuInstance());
|
|
110
|
-
};
|
|
111
|
-
|
|
112
|
-
window.addEventListener('wu:ready', handleWuReady);
|
|
113
|
-
window.addEventListener('wu:app:ready', handleWuReady);
|
|
114
|
-
|
|
115
|
-
// Fallback con polling conservador (cada 200ms, no 100ms)
|
|
116
|
-
const checkInterval = setInterval(() => {
|
|
117
|
-
const wu = getWuInstance();
|
|
118
|
-
if (wu) {
|
|
119
|
-
cleanup();
|
|
120
|
-
resolve(wu);
|
|
121
|
-
return;
|
|
122
|
-
}
|
|
123
|
-
|
|
124
|
-
if (Date.now() - startTime > timeout) {
|
|
125
|
-
cleanup();
|
|
126
|
-
reject(new Error(`Wu Framework not found after ${timeout}ms`));
|
|
127
|
-
}
|
|
128
|
-
}, 200);
|
|
129
|
-
|
|
130
|
-
function cleanup() {
|
|
131
|
-
clearInterval(checkInterval);
|
|
132
|
-
window.removeEventListener('wu:ready', handleWuReady);
|
|
133
|
-
window.removeEventListener('wu:app:ready', handleWuReady);
|
|
134
|
-
}
|
|
135
|
-
});
|
|
136
|
-
}
|
|
137
|
-
|
|
138
|
-
/**
|
|
139
|
-
* Registra un componente React como microfrontend
|
|
140
|
-
*
|
|
141
|
-
* @param {string} appName - Nombre único del microfrontend (debe coincidir con wu.json)
|
|
142
|
-
* @param {React.ComponentType} Component - Componente React principal
|
|
143
|
-
* @param {Object} options - Opciones adicionales
|
|
144
|
-
* @param {boolean} options.strictMode - Envolver en StrictMode (default: true)
|
|
145
|
-
* @param {Object} options.props - Props iniciales para el componente
|
|
146
|
-
* @param {Function} options.onMount - Callback después de montar
|
|
147
|
-
* @param {Function} options.onUnmount - Callback antes de desmontar
|
|
148
|
-
* @param {boolean} options.standalone - Permitir ejecución standalone (default: true)
|
|
149
|
-
* @param {string} options.standaloneContainer - Selector para modo standalone (default: '#root')
|
|
150
|
-
*/
|
|
151
|
-
async function register(appName, Component, options = {}) {
|
|
152
|
-
const {
|
|
153
|
-
strictMode = true,
|
|
154
|
-
props = {},
|
|
155
|
-
onMount = null,
|
|
156
|
-
onUnmount = null,
|
|
157
|
-
standalone = true,
|
|
158
|
-
standaloneContainer = '#root'
|
|
159
|
-
} = options;
|
|
160
|
-
|
|
161
|
-
// Asegurar que React está disponible
|
|
162
|
-
const hasReact = await ensureReact();
|
|
163
|
-
if (!hasReact) {
|
|
164
|
-
console.error(`[WuReact] Cannot register ${appName}: React not available`);
|
|
165
|
-
return false;
|
|
166
|
-
}
|
|
167
|
-
|
|
168
|
-
const { React, createRoot } = adapterState;
|
|
169
|
-
|
|
170
|
-
// Función de mount interna
|
|
171
|
-
const mountApp = (container) => {
|
|
172
|
-
if (!container) {
|
|
173
|
-
console.error(`[WuReact] Mount failed for ${appName}: container is null`);
|
|
174
|
-
return;
|
|
175
|
-
}
|
|
176
|
-
|
|
177
|
-
// Si ya está montado en el MISMO container, ignorar
|
|
178
|
-
const existing = adapterState.roots.get(appName);
|
|
179
|
-
if (existing) {
|
|
180
|
-
if (existing.container === container) {
|
|
181
|
-
return; // Ya montado aquí, nada que hacer
|
|
182
|
-
}
|
|
183
|
-
// Diferente container → desmontar primero
|
|
184
|
-
unmountApp();
|
|
185
|
-
}
|
|
186
|
-
|
|
187
|
-
try {
|
|
188
|
-
container.innerHTML = '';
|
|
189
|
-
const root = createRoot(container);
|
|
190
|
-
|
|
191
|
-
let element = React.createElement(Component, props);
|
|
192
|
-
if (strictMode && React.StrictMode) {
|
|
193
|
-
element = React.createElement(React.StrictMode, null, element);
|
|
194
|
-
}
|
|
195
|
-
|
|
196
|
-
root.render(element);
|
|
197
|
-
adapterState.roots.set(appName, { root, container });
|
|
198
|
-
|
|
199
|
-
if (onMount) {
|
|
200
|
-
onMount(container);
|
|
201
|
-
}
|
|
202
|
-
} catch (error) {
|
|
203
|
-
console.error(`[WuReact] Mount error for ${appName}:`, error);
|
|
204
|
-
throw error;
|
|
205
|
-
}
|
|
206
|
-
};
|
|
207
|
-
|
|
208
|
-
// Unmount inmediato — la protección contra StrictMode (deferred unmount)
|
|
209
|
-
// se maneja en wu-core.js, no aquí en el adapter.
|
|
210
|
-
const unmountApp = (container) => {
|
|
211
|
-
const instance = adapterState.roots.get(appName);
|
|
212
|
-
if (instance) {
|
|
213
|
-
try {
|
|
214
|
-
if (onUnmount) onUnmount(instance.container);
|
|
215
|
-
instance.root.unmount();
|
|
216
|
-
adapterState.roots.delete(appName);
|
|
217
|
-
} catch (error) {
|
|
218
|
-
console.error(`[WuReact] Unmount error for ${appName}:`, error);
|
|
219
|
-
}
|
|
220
|
-
}
|
|
221
|
-
const target = container || instance?.container;
|
|
222
|
-
if (target) target.innerHTML = '';
|
|
223
|
-
};
|
|
224
|
-
|
|
225
|
-
// Intentar registrar con Wu Framework
|
|
226
|
-
try {
|
|
227
|
-
const wu = await waitForWu(3000);
|
|
228
|
-
|
|
229
|
-
wu.define(appName, {
|
|
230
|
-
mount: mountApp,
|
|
231
|
-
unmount: unmountApp
|
|
232
|
-
});
|
|
233
|
-
|
|
234
|
-
console.log(`[WuReact] ✅ ${appName} registered with Wu Framework`);
|
|
235
|
-
return true;
|
|
236
|
-
|
|
237
|
-
} catch (error) {
|
|
238
|
-
// Wu no disponible
|
|
239
|
-
console.warn(`[WuReact] Wu Framework not available for ${appName}`);
|
|
240
|
-
|
|
241
|
-
// Modo standalone si está habilitado
|
|
242
|
-
if (standalone) {
|
|
243
|
-
const containerElement = document.querySelector(standaloneContainer);
|
|
244
|
-
|
|
245
|
-
if (containerElement) {
|
|
246
|
-
console.log(`[WuReact] Running ${appName} in standalone mode`);
|
|
247
|
-
mountApp(containerElement);
|
|
248
|
-
return true;
|
|
249
|
-
} else {
|
|
250
|
-
console.warn(`[WuReact] Standalone container ${standaloneContainer} not found`);
|
|
251
|
-
}
|
|
252
|
-
}
|
|
253
|
-
|
|
254
|
-
return false;
|
|
255
|
-
}
|
|
256
|
-
}
|
|
257
|
-
|
|
258
|
-
/**
|
|
259
|
-
* Crea un componente React para cargar microfrontends (para el Shell)
|
|
260
|
-
*
|
|
261
|
-
* @example
|
|
262
|
-
* import { createWuSlot } from 'wu-framework/adapters/react';
|
|
263
|
-
* const WuSlot = createWuSlot(React);
|
|
264
|
-
*
|
|
265
|
-
* <WuSlot name="my-app" url="http://localhost:3001" />
|
|
266
|
-
*/
|
|
267
|
-
function createWuSlot(React) {
|
|
268
|
-
const { useState, useEffect, useRef } = React;
|
|
269
|
-
|
|
270
|
-
return function WuSlot({
|
|
271
|
-
name,
|
|
272
|
-
url,
|
|
273
|
-
appName = null,
|
|
274
|
-
fallback = null,
|
|
275
|
-
onLoad = null,
|
|
276
|
-
onError = null,
|
|
277
|
-
onMount = null,
|
|
278
|
-
onUnmount = null,
|
|
279
|
-
className = '',
|
|
280
|
-
style = {},
|
|
281
|
-
...props
|
|
282
|
-
}) {
|
|
283
|
-
const actualAppName = appName || name;
|
|
284
|
-
|
|
285
|
-
// ID estable derivado del nombre: el div ya tiene este id desde el primer render.
|
|
286
|
-
// wu.mount(name, '#id') lo encuentra sin necesidad de innerHTML ni appendChild.
|
|
287
|
-
const containerId = `wu-slot-${actualAppName}`;
|
|
288
|
-
const mountedRef = useRef(false);
|
|
289
|
-
const [loading, setLoading] = useState(true);
|
|
290
|
-
const [error, setError] = useState(null);
|
|
291
|
-
|
|
292
|
-
useEffect(() => {
|
|
293
|
-
let cancelled = false;
|
|
294
|
-
|
|
295
|
-
// Delay 50ms + flag cancelled: patrón StrictMode-safe.
|
|
296
|
-
// En StrictMode React monta → desmonta → monta; el primer ciclo cancela
|
|
297
|
-
// el timeout antes de ejecutarse; solo el segundo ciclo monta el MF.
|
|
298
|
-
const timer = setTimeout(async () => {
|
|
299
|
-
if (cancelled) return;
|
|
300
|
-
|
|
301
|
-
try {
|
|
302
|
-
setLoading(true);
|
|
303
|
-
setError(null);
|
|
304
|
-
|
|
305
|
-
const wu = getWuInstance();
|
|
306
|
-
if (!wu) throw new Error('Wu Framework not initialized');
|
|
307
|
-
|
|
308
|
-
// El div#containerId ya está en el DOM (renderizado abajo).
|
|
309
|
-
// wu.mount lo usa como target; no tocamos su DOM desde JS imperativo.
|
|
310
|
-
await wu.mount(actualAppName, `#${containerId}`);
|
|
311
|
-
|
|
312
|
-
if (!cancelled) {
|
|
313
|
-
mountedRef.current = true;
|
|
314
|
-
setLoading(false);
|
|
315
|
-
|
|
316
|
-
const container = document.getElementById(containerId);
|
|
317
|
-
if (onLoad) onLoad({ name: actualAppName, url });
|
|
318
|
-
if (onMount) onMount({ name: actualAppName, container });
|
|
319
|
-
}
|
|
320
|
-
} catch (err) {
|
|
321
|
-
if (!cancelled) {
|
|
322
|
-
console.error(`[WuSlot] Error loading ${actualAppName}:`, err);
|
|
323
|
-
setError(err.message || 'Failed to load microfrontend');
|
|
324
|
-
setLoading(false);
|
|
325
|
-
if (onError) onError(err);
|
|
326
|
-
}
|
|
327
|
-
}
|
|
328
|
-
}, 50);
|
|
329
|
-
|
|
330
|
-
return () => {
|
|
331
|
-
cancelled = true;
|
|
332
|
-
clearTimeout(timer);
|
|
333
|
-
|
|
334
|
-
if (mountedRef.current) {
|
|
335
|
-
if (onUnmount) onUnmount({ name: actualAppName });
|
|
336
|
-
const wu = getWuInstance();
|
|
337
|
-
if (wu) wu.unmount(actualAppName).catch(() => {});
|
|
338
|
-
mountedRef.current = false;
|
|
339
|
-
}
|
|
340
|
-
};
|
|
341
|
-
}, [actualAppName, url, onLoad, onError, onMount, onUnmount]);
|
|
342
|
-
|
|
343
|
-
// Estado de error
|
|
344
|
-
if (error) {
|
|
345
|
-
return React.createElement('div', {
|
|
346
|
-
className: `wu-slot wu-slot-error ${className}`,
|
|
347
|
-
style: {
|
|
348
|
-
padding: '1rem',
|
|
349
|
-
border: '1px solid #f5c6cb',
|
|
350
|
-
borderRadius: '4px',
|
|
351
|
-
backgroundColor: '#f8d7da',
|
|
352
|
-
color: '#721c24',
|
|
353
|
-
...style
|
|
354
|
-
},
|
|
355
|
-
...props
|
|
356
|
-
}, [
|
|
357
|
-
React.createElement('strong', { key: 'title' }, `Error loading ${name}`),
|
|
358
|
-
React.createElement('p', { key: 'message', style: { margin: '0.5rem 0 0 0' } }, error)
|
|
359
|
-
]);
|
|
360
|
-
}
|
|
361
|
-
|
|
362
|
-
// Render principal: Fragment con fallback y div de montaje como HERMANOS.
|
|
363
|
-
//
|
|
364
|
-
// REGLA CRÍTICA: el div#containerId NO debe tener hijos React.
|
|
365
|
-
// wu.mount inyecta el MF (otro createRoot) dentro de ese div. Si React también
|
|
366
|
-
// administra hijos ahí, al desmontar el fallback llama removeChild sobre nodos
|
|
367
|
-
// que el MF ya reemplazó → "The node to be removed is not a child of this node".
|
|
368
|
-
//
|
|
369
|
-
// Solución: fallback y mount-target como hermanos en un Fragment pasados como
|
|
370
|
-
// argumentos separados a createElement (NO como array; el array rompe la
|
|
371
|
-
// reconciliación). React solo gestiona el fallback; el interior del mount-target
|
|
372
|
-
// lo controla exclusivamente el MF.
|
|
373
|
-
const defaultFallback = React.createElement('div', {
|
|
374
|
-
style: { display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '2rem', color: '#666' }
|
|
375
|
-
}, `Loading ${name}...`);
|
|
376
|
-
|
|
377
|
-
return React.createElement(React.Fragment, null,
|
|
378
|
-
loading
|
|
379
|
-
? React.createElement('div', { className: `wu-slot-fallback ${className}` }, fallback || defaultFallback)
|
|
380
|
-
: null,
|
|
381
|
-
React.createElement('div', Object.assign({
|
|
382
|
-
id: containerId,
|
|
383
|
-
className: `wu-slot ${loading ? 'wu-slot-loading' : 'wu-slot-loaded'}`,
|
|
384
|
-
'data-wu-app': actualAppName,
|
|
385
|
-
'data-wu-url': url,
|
|
386
|
-
style: Object.assign({ width: '100%', minHeight: loading ? 0 : '200px' }, style)
|
|
387
|
-
}, props))
|
|
388
|
-
);
|
|
389
|
-
};
|
|
390
|
-
}
|
|
391
|
-
|
|
392
|
-
/**
|
|
393
|
-
* Hook para usar el EventBus de Wu Framework en React
|
|
394
|
-
*
|
|
395
|
-
* @example
|
|
396
|
-
* const { emit, on } = useWuEvents();
|
|
397
|
-
*
|
|
398
|
-
* useEffect(() => {
|
|
399
|
-
* const unsub = on('user:login', (data) => console.log(data));
|
|
400
|
-
* return unsub;
|
|
401
|
-
* }, [on]);
|
|
402
|
-
*/
|
|
403
|
-
function createUseWuEvents(React) {
|
|
404
|
-
const { useCallback, useEffect, useRef } = React;
|
|
405
|
-
|
|
406
|
-
return function useWuEvents() {
|
|
407
|
-
const subscriptionsRef = useRef([]);
|
|
408
|
-
|
|
409
|
-
const emit = useCallback((event, data, options) => {
|
|
410
|
-
const wu = getWuInstance();
|
|
411
|
-
if (wu?.eventBus) {
|
|
412
|
-
wu.eventBus.emit(event, data, options);
|
|
413
|
-
} else {
|
|
414
|
-
console.warn('[useWuEvents] Wu Framework not available');
|
|
415
|
-
}
|
|
416
|
-
}, []);
|
|
417
|
-
|
|
418
|
-
const on = useCallback((event, callback) => {
|
|
419
|
-
const wu = getWuInstance();
|
|
420
|
-
if (wu?.eventBus) {
|
|
421
|
-
const unsubscribe = wu.eventBus.on(event, callback);
|
|
422
|
-
subscriptionsRef.current.push(unsubscribe);
|
|
423
|
-
return unsubscribe;
|
|
424
|
-
}
|
|
425
|
-
console.warn('[useWuEvents] Wu Framework not available');
|
|
426
|
-
return () => {};
|
|
427
|
-
}, []);
|
|
428
|
-
|
|
429
|
-
const once = useCallback((event, callback) => {
|
|
430
|
-
const wu = getWuInstance();
|
|
431
|
-
if (wu?.eventBus) {
|
|
432
|
-
return wu.eventBus.once(event, callback);
|
|
433
|
-
}
|
|
434
|
-
console.warn('[useWuEvents] Wu Framework not available');
|
|
435
|
-
return () => {};
|
|
436
|
-
}, []);
|
|
437
|
-
|
|
438
|
-
// Cleanup on unmount
|
|
439
|
-
useEffect(() => {
|
|
440
|
-
return () => {
|
|
441
|
-
subscriptionsRef.current.forEach(unsub => unsub());
|
|
442
|
-
subscriptionsRef.current = [];
|
|
443
|
-
};
|
|
444
|
-
}, []);
|
|
445
|
-
|
|
446
|
-
return { emit, on, once };
|
|
447
|
-
};
|
|
448
|
-
}
|
|
449
|
-
|
|
450
|
-
/**
|
|
451
|
-
* Hook para usar el Store de Wu Framework en React
|
|
452
|
-
*
|
|
453
|
-
* @example
|
|
454
|
-
* const { state, setState, subscribe } = useWuStore('user');
|
|
455
|
-
*/
|
|
456
|
-
function createUseWuStore(React) {
|
|
457
|
-
const { useState, useCallback, useEffect } = React;
|
|
458
|
-
|
|
459
|
-
return function useWuStore(namespace = '') {
|
|
460
|
-
const [state, setLocalState] = useState(() => {
|
|
461
|
-
const wu = getWuInstance();
|
|
462
|
-
return wu?.store?.get(namespace) || null;
|
|
463
|
-
});
|
|
464
|
-
|
|
465
|
-
const setState = useCallback((path, value) => {
|
|
466
|
-
const wu = getWuInstance();
|
|
467
|
-
if (wu?.store) {
|
|
468
|
-
const fullPath = namespace ? `${namespace}.${path}` : path;
|
|
469
|
-
wu.store.set(fullPath, value);
|
|
470
|
-
}
|
|
471
|
-
}, [namespace]);
|
|
472
|
-
|
|
473
|
-
const getState = useCallback((path = '') => {
|
|
474
|
-
const wu = getWuInstance();
|
|
475
|
-
if (wu?.store) {
|
|
476
|
-
const fullPath = namespace ? (path ? `${namespace}.${path}` : namespace) : path;
|
|
477
|
-
return wu.store.get(fullPath);
|
|
478
|
-
}
|
|
479
|
-
return null;
|
|
480
|
-
}, [namespace]);
|
|
481
|
-
|
|
482
|
-
// Subscribe to changes
|
|
483
|
-
useEffect(() => {
|
|
484
|
-
const wu = getWuInstance();
|
|
485
|
-
if (!wu?.store) return;
|
|
486
|
-
|
|
487
|
-
const pattern = namespace ? `${namespace}.*` : '*';
|
|
488
|
-
const unsubscribe = wu.store.on(pattern, () => {
|
|
489
|
-
setLocalState(wu.store.get(namespace));
|
|
490
|
-
});
|
|
491
|
-
|
|
492
|
-
return unsubscribe;
|
|
493
|
-
}, [namespace]);
|
|
494
|
-
|
|
495
|
-
return { state, setState, getState };
|
|
496
|
-
};
|
|
497
|
-
}
|
|
498
|
-
|
|
499
|
-
/**
|
|
500
|
-
* Hook para integrar wu.ai con React (Paradigma C: IA como Director de Orquesta)
|
|
501
|
-
*
|
|
502
|
-
* Manages messages, streaming state, and AI interaction lifecycle.
|
|
503
|
-
* The AI calls business-level actions that orchestrate the UI via wu.emit/wu.store.
|
|
504
|
-
*
|
|
505
|
-
* @example
|
|
506
|
-
* const { messages, send, isStreaming } = useWuAI();
|
|
507
|
-
*
|
|
508
|
-
* await send('Navigate to users page');
|
|
509
|
-
* // AI calls 'navigate' action → wu.emit('shell:navigate') → UI reacts
|
|
510
|
-
*/
|
|
511
|
-
function createUseWuAI(React) {
|
|
512
|
-
const { useState, useCallback, useRef, useEffect } = React;
|
|
513
|
-
|
|
514
|
-
return function useWuAI(options = {}) {
|
|
515
|
-
const { namespace = 'default', onActionExecuted = null } = options;
|
|
516
|
-
|
|
517
|
-
const [messages, setMessages] = useState([]);
|
|
518
|
-
const [isStreaming, setIsStreaming] = useState(false);
|
|
519
|
-
const [error, setError] = useState(null);
|
|
520
|
-
const abortRef = useRef(null);
|
|
521
|
-
const actionListenerRef = useRef(null);
|
|
522
|
-
|
|
523
|
-
// Listen for action execution events to provide visual feedback
|
|
524
|
-
useEffect(() => {
|
|
525
|
-
const wu = getWuInstance();
|
|
526
|
-
if (!wu?.eventBus) return;
|
|
527
|
-
|
|
528
|
-
const unsub = wu.eventBus.on('ai:action:executed', (event) => {
|
|
529
|
-
const actionMsg = {
|
|
530
|
-
id: `action-${Date.now()}`,
|
|
531
|
-
role: 'action',
|
|
532
|
-
content: event.data?.action || 'action',
|
|
533
|
-
result: event.data?.result,
|
|
534
|
-
timestamp: Date.now(),
|
|
535
|
-
};
|
|
536
|
-
setMessages((prev) => [...prev, actionMsg]);
|
|
537
|
-
if (onActionExecuted) onActionExecuted(event.data);
|
|
538
|
-
});
|
|
539
|
-
|
|
540
|
-
actionListenerRef.current = unsub;
|
|
541
|
-
return () => { if (unsub) unsub(); };
|
|
542
|
-
}, [onActionExecuted]);
|
|
543
|
-
|
|
544
|
-
/**
|
|
545
|
-
* Send a message and stream the response in real-time.
|
|
546
|
-
*/
|
|
547
|
-
const send = useCallback(async (text) => {
|
|
548
|
-
if (!text?.trim()) return;
|
|
549
|
-
|
|
550
|
-
const wu = getWuInstance();
|
|
551
|
-
if (!wu?.ai) {
|
|
552
|
-
setError('Wu AI not available');
|
|
553
|
-
return;
|
|
554
|
-
}
|
|
555
|
-
|
|
556
|
-
// Add user message
|
|
557
|
-
const userMsg = {
|
|
558
|
-
id: `user-${Date.now()}`,
|
|
559
|
-
role: 'user',
|
|
560
|
-
content: text,
|
|
561
|
-
timestamp: Date.now(),
|
|
562
|
-
};
|
|
563
|
-
setMessages((prev) => [...prev, userMsg]);
|
|
564
|
-
setError(null);
|
|
565
|
-
setIsStreaming(true);
|
|
566
|
-
|
|
567
|
-
// Create assistant placeholder
|
|
568
|
-
const assistantId = `assistant-${Date.now()}`;
|
|
569
|
-
setMessages((prev) => [...prev, {
|
|
570
|
-
id: assistantId,
|
|
571
|
-
role: 'assistant',
|
|
572
|
-
content: '',
|
|
573
|
-
timestamp: Date.now(),
|
|
574
|
-
}]);
|
|
575
|
-
|
|
576
|
-
try {
|
|
577
|
-
let fullContent = '';
|
|
578
|
-
|
|
579
|
-
for await (const chunk of wu.ai.stream(text, { namespace })) {
|
|
580
|
-
if (chunk.type === 'text') {
|
|
581
|
-
fullContent += chunk.content;
|
|
582
|
-
const captured = fullContent;
|
|
583
|
-
setMessages((prev) =>
|
|
584
|
-
prev.map((m) =>
|
|
585
|
-
m.id === assistantId ? { ...m, content: captured } : m,
|
|
586
|
-
),
|
|
587
|
-
);
|
|
588
|
-
}
|
|
589
|
-
|
|
590
|
-
if (chunk.type === 'tool_result') {
|
|
591
|
-
// Tool results are handled by the ai:action:executed listener
|
|
592
|
-
}
|
|
593
|
-
|
|
594
|
-
if (chunk.type === 'error') {
|
|
595
|
-
setError(chunk.error?.message || 'AI request failed');
|
|
596
|
-
}
|
|
597
|
-
}
|
|
598
|
-
} catch (err) {
|
|
599
|
-
setError(err.message || 'AI request failed');
|
|
600
|
-
// Remove empty assistant message on error
|
|
601
|
-
setMessages((prev) => prev.filter((m) => m.id !== assistantId || m.content));
|
|
602
|
-
} finally {
|
|
603
|
-
setIsStreaming(false);
|
|
604
|
-
}
|
|
605
|
-
}, [namespace]);
|
|
606
|
-
|
|
607
|
-
/**
|
|
608
|
-
* Send without streaming (simpler, waits for full response).
|
|
609
|
-
*/
|
|
610
|
-
const sendSync = useCallback(async (text) => {
|
|
611
|
-
if (!text?.trim()) return null;
|
|
612
|
-
|
|
613
|
-
const wu = getWuInstance();
|
|
614
|
-
if (!wu?.ai) {
|
|
615
|
-
setError('Wu AI not available');
|
|
616
|
-
return null;
|
|
617
|
-
}
|
|
618
|
-
|
|
619
|
-
const userMsg = {
|
|
620
|
-
id: `user-${Date.now()}`,
|
|
621
|
-
role: 'user',
|
|
622
|
-
content: text,
|
|
623
|
-
timestamp: Date.now(),
|
|
624
|
-
};
|
|
625
|
-
setMessages((prev) => [...prev, userMsg]);
|
|
626
|
-
setError(null);
|
|
627
|
-
setIsStreaming(true);
|
|
628
|
-
|
|
629
|
-
try {
|
|
630
|
-
const response = await wu.ai.send(text, { namespace });
|
|
631
|
-
|
|
632
|
-
const assistantMsg = {
|
|
633
|
-
id: `assistant-${Date.now()}`,
|
|
634
|
-
role: 'assistant',
|
|
635
|
-
content: response.content,
|
|
636
|
-
timestamp: Date.now(),
|
|
637
|
-
};
|
|
638
|
-
setMessages((prev) => [...prev, assistantMsg]);
|
|
639
|
-
return response;
|
|
640
|
-
} catch (err) {
|
|
641
|
-
setError(err.message || 'AI request failed');
|
|
642
|
-
return null;
|
|
643
|
-
} finally {
|
|
644
|
-
setIsStreaming(false);
|
|
645
|
-
}
|
|
646
|
-
}, [namespace]);
|
|
647
|
-
|
|
648
|
-
const abort = useCallback(() => {
|
|
649
|
-
const wu = getWuInstance();
|
|
650
|
-
if (wu?.ai) wu.ai.abort(namespace);
|
|
651
|
-
setIsStreaming(false);
|
|
652
|
-
}, [namespace]);
|
|
653
|
-
|
|
654
|
-
const clear = useCallback(() => {
|
|
655
|
-
setMessages([]);
|
|
656
|
-
setError(null);
|
|
657
|
-
const wu = getWuInstance();
|
|
658
|
-
if (wu?.ai) wu.ai.conversation.clear(namespace);
|
|
659
|
-
}, [namespace]);
|
|
660
|
-
|
|
661
|
-
return {
|
|
662
|
-
messages,
|
|
663
|
-
isStreaming,
|
|
664
|
-
error,
|
|
665
|
-
send,
|
|
666
|
-
sendSync,
|
|
667
|
-
abort,
|
|
668
|
-
clear,
|
|
669
|
-
};
|
|
670
|
-
};
|
|
671
|
-
}
|
|
672
|
-
|
|
673
|
-
// API pública del adapter
|
|
674
|
-
export const wuReact = {
|
|
675
|
-
register,
|
|
676
|
-
createWuSlot,
|
|
677
|
-
createUseWuEvents,
|
|
678
|
-
createUseWuStore,
|
|
679
|
-
createUseWuAI,
|
|
680
|
-
getWuInstance,
|
|
681
|
-
waitForWu
|
|
682
|
-
};
|
|
683
|
-
|
|
684
|
-
// Named exports para conveniencia
|
|
685
|
-
export {
|
|
686
|
-
register,
|
|
687
|
-
createWuSlot,
|
|
688
|
-
createUseWuEvents,
|
|
689
|
-
createUseWuStore,
|
|
690
|
-
createUseWuAI,
|
|
691
|
-
getWuInstance,
|
|
692
|
-
waitForWu
|
|
693
|
-
};
|
|
694
|
-
|
|
695
|
-
export default wuReact;
|
|
1
|
+
/**
|
|
2
|
+
* 🚀 WU-FRAMEWORK REACT ADAPTER
|
|
3
|
+
*
|
|
4
|
+
* Simplifica la integración de React con Wu Framework.
|
|
5
|
+
* Convierte componentes React en microfrontends con UNA línea de código.
|
|
6
|
+
*
|
|
7
|
+
* @example
|
|
8
|
+
* // Microfrontend (main.tsx)
|
|
9
|
+
* import { wuReact } from 'wu-framework/adapters/react';
|
|
10
|
+
* import App from './App';
|
|
11
|
+
*
|
|
12
|
+
* wuReact.register('my-app', App);
|
|
13
|
+
*
|
|
14
|
+
* @example
|
|
15
|
+
* // Shell (cargar microfrontend)
|
|
16
|
+
* import { WuSlot } from 'wu-framework/adapters/react';
|
|
17
|
+
*
|
|
18
|
+
* <WuSlot name="my-app" url="http://localhost:3001" />
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
// Estado global del adapter
|
|
22
|
+
const adapterState = {
|
|
23
|
+
roots: new Map(),
|
|
24
|
+
React: null,
|
|
25
|
+
ReactDOM: null,
|
|
26
|
+
createRoot: null,
|
|
27
|
+
initialized: false
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Detecta y obtiene React del contexto global o lo importa
|
|
32
|
+
*/
|
|
33
|
+
async function ensureReact() {
|
|
34
|
+
if (adapterState.initialized) return true;
|
|
35
|
+
|
|
36
|
+
try {
|
|
37
|
+
// Intentar obtener de window (común en microfrontends)
|
|
38
|
+
if (typeof window !== 'undefined' && window.React && window.ReactDOM) {
|
|
39
|
+
adapterState.React = window.React;
|
|
40
|
+
adapterState.ReactDOM = window.ReactDOM;
|
|
41
|
+
|
|
42
|
+
// createRoot puede estar en window.ReactDOM (si importaron de react-dom/client)
|
|
43
|
+
// o no existir (si importaron de react-dom). Intentar ambos caminos.
|
|
44
|
+
if (window.ReactDOM.createRoot) {
|
|
45
|
+
adapterState.createRoot = window.ReactDOM.createRoot;
|
|
46
|
+
} else {
|
|
47
|
+
// Fallback: importar react-dom/client para obtener createRoot
|
|
48
|
+
try {
|
|
49
|
+
const clientModule = await import('react-dom/client');
|
|
50
|
+
adapterState.createRoot = (clientModule.default || clientModule).createRoot;
|
|
51
|
+
} catch {
|
|
52
|
+
console.error('[WuReact] createRoot not found. Expose window.ReactDOM from "react-dom/client", not "react-dom".');
|
|
53
|
+
return false;
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
adapterState.initialized = true;
|
|
58
|
+
return true;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
// Intentar import dinámico
|
|
62
|
+
const [React, ReactDOMClient] = await Promise.all([
|
|
63
|
+
import('react'),
|
|
64
|
+
import('react-dom/client')
|
|
65
|
+
]);
|
|
66
|
+
|
|
67
|
+
adapterState.React = React.default || React;
|
|
68
|
+
adapterState.ReactDOM = ReactDOMClient.default || ReactDOMClient;
|
|
69
|
+
adapterState.createRoot = (ReactDOMClient.default || ReactDOMClient).createRoot;
|
|
70
|
+
adapterState.initialized = true;
|
|
71
|
+
return true;
|
|
72
|
+
|
|
73
|
+
} catch (error) {
|
|
74
|
+
console.error('[WuReact] Failed to load React:', error);
|
|
75
|
+
return false;
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* Obtiene la instancia de Wu Framework
|
|
81
|
+
*/
|
|
82
|
+
function getWuInstance() {
|
|
83
|
+
if (typeof window === 'undefined') return null;
|
|
84
|
+
|
|
85
|
+
return window.wu
|
|
86
|
+
|| window.parent?.wu
|
|
87
|
+
|| window.top?.wu
|
|
88
|
+
|| null;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* Espera a que Wu Framework esté disponible (sin polling agresivo)
|
|
93
|
+
*/
|
|
94
|
+
function waitForWu(timeout = 5000) {
|
|
95
|
+
return new Promise((resolve, reject) => {
|
|
96
|
+
// Check inmediato
|
|
97
|
+
const wu = getWuInstance();
|
|
98
|
+
if (wu) {
|
|
99
|
+
resolve(wu);
|
|
100
|
+
return;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
// Usar MutationObserver + evento en lugar de polling
|
|
104
|
+
const startTime = Date.now();
|
|
105
|
+
|
|
106
|
+
// Escuchar evento de Wu Framework
|
|
107
|
+
const handleWuReady = (event) => {
|
|
108
|
+
cleanup();
|
|
109
|
+
resolve(getWuInstance());
|
|
110
|
+
};
|
|
111
|
+
|
|
112
|
+
window.addEventListener('wu:ready', handleWuReady);
|
|
113
|
+
window.addEventListener('wu:app:ready', handleWuReady);
|
|
114
|
+
|
|
115
|
+
// Fallback con polling conservador (cada 200ms, no 100ms)
|
|
116
|
+
const checkInterval = setInterval(() => {
|
|
117
|
+
const wu = getWuInstance();
|
|
118
|
+
if (wu) {
|
|
119
|
+
cleanup();
|
|
120
|
+
resolve(wu);
|
|
121
|
+
return;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
if (Date.now() - startTime > timeout) {
|
|
125
|
+
cleanup();
|
|
126
|
+
reject(new Error(`Wu Framework not found after ${timeout}ms`));
|
|
127
|
+
}
|
|
128
|
+
}, 200);
|
|
129
|
+
|
|
130
|
+
function cleanup() {
|
|
131
|
+
clearInterval(checkInterval);
|
|
132
|
+
window.removeEventListener('wu:ready', handleWuReady);
|
|
133
|
+
window.removeEventListener('wu:app:ready', handleWuReady);
|
|
134
|
+
}
|
|
135
|
+
});
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* Registra un componente React como microfrontend
|
|
140
|
+
*
|
|
141
|
+
* @param {string} appName - Nombre único del microfrontend (debe coincidir con wu.json)
|
|
142
|
+
* @param {React.ComponentType} Component - Componente React principal
|
|
143
|
+
* @param {Object} options - Opciones adicionales
|
|
144
|
+
* @param {boolean} options.strictMode - Envolver en StrictMode (default: true)
|
|
145
|
+
* @param {Object} options.props - Props iniciales para el componente
|
|
146
|
+
* @param {Function} options.onMount - Callback después de montar
|
|
147
|
+
* @param {Function} options.onUnmount - Callback antes de desmontar
|
|
148
|
+
* @param {boolean} options.standalone - Permitir ejecución standalone (default: true)
|
|
149
|
+
* @param {string} options.standaloneContainer - Selector para modo standalone (default: '#root')
|
|
150
|
+
*/
|
|
151
|
+
async function register(appName, Component, options = {}) {
|
|
152
|
+
const {
|
|
153
|
+
strictMode = true,
|
|
154
|
+
props = {},
|
|
155
|
+
onMount = null,
|
|
156
|
+
onUnmount = null,
|
|
157
|
+
standalone = true,
|
|
158
|
+
standaloneContainer = '#root'
|
|
159
|
+
} = options;
|
|
160
|
+
|
|
161
|
+
// Asegurar que React está disponible
|
|
162
|
+
const hasReact = await ensureReact();
|
|
163
|
+
if (!hasReact) {
|
|
164
|
+
console.error(`[WuReact] Cannot register ${appName}: React not available`);
|
|
165
|
+
return false;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
const { React, createRoot } = adapterState;
|
|
169
|
+
|
|
170
|
+
// Función de mount interna
|
|
171
|
+
const mountApp = (container) => {
|
|
172
|
+
if (!container) {
|
|
173
|
+
console.error(`[WuReact] Mount failed for ${appName}: container is null`);
|
|
174
|
+
return;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
// Si ya está montado en el MISMO container, ignorar
|
|
178
|
+
const existing = adapterState.roots.get(appName);
|
|
179
|
+
if (existing) {
|
|
180
|
+
if (existing.container === container) {
|
|
181
|
+
return; // Ya montado aquí, nada que hacer
|
|
182
|
+
}
|
|
183
|
+
// Diferente container → desmontar primero
|
|
184
|
+
unmountApp();
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
try {
|
|
188
|
+
container.innerHTML = '';
|
|
189
|
+
const root = createRoot(container);
|
|
190
|
+
|
|
191
|
+
let element = React.createElement(Component, props);
|
|
192
|
+
if (strictMode && React.StrictMode) {
|
|
193
|
+
element = React.createElement(React.StrictMode, null, element);
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
root.render(element);
|
|
197
|
+
adapterState.roots.set(appName, { root, container });
|
|
198
|
+
|
|
199
|
+
if (onMount) {
|
|
200
|
+
onMount(container);
|
|
201
|
+
}
|
|
202
|
+
} catch (error) {
|
|
203
|
+
console.error(`[WuReact] Mount error for ${appName}:`, error);
|
|
204
|
+
throw error;
|
|
205
|
+
}
|
|
206
|
+
};
|
|
207
|
+
|
|
208
|
+
// Unmount inmediato — la protección contra StrictMode (deferred unmount)
|
|
209
|
+
// se maneja en wu-core.js, no aquí en el adapter.
|
|
210
|
+
const unmountApp = (container) => {
|
|
211
|
+
const instance = adapterState.roots.get(appName);
|
|
212
|
+
if (instance) {
|
|
213
|
+
try {
|
|
214
|
+
if (onUnmount) onUnmount(instance.container);
|
|
215
|
+
instance.root.unmount();
|
|
216
|
+
adapterState.roots.delete(appName);
|
|
217
|
+
} catch (error) {
|
|
218
|
+
console.error(`[WuReact] Unmount error for ${appName}:`, error);
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
const target = container || instance?.container;
|
|
222
|
+
if (target) target.innerHTML = '';
|
|
223
|
+
};
|
|
224
|
+
|
|
225
|
+
// Intentar registrar con Wu Framework
|
|
226
|
+
try {
|
|
227
|
+
const wu = await waitForWu(3000);
|
|
228
|
+
|
|
229
|
+
wu.define(appName, {
|
|
230
|
+
mount: mountApp,
|
|
231
|
+
unmount: unmountApp
|
|
232
|
+
});
|
|
233
|
+
|
|
234
|
+
console.log(`[WuReact] ✅ ${appName} registered with Wu Framework`);
|
|
235
|
+
return true;
|
|
236
|
+
|
|
237
|
+
} catch (error) {
|
|
238
|
+
// Wu no disponible
|
|
239
|
+
console.warn(`[WuReact] Wu Framework not available for ${appName}`);
|
|
240
|
+
|
|
241
|
+
// Modo standalone si está habilitado
|
|
242
|
+
if (standalone) {
|
|
243
|
+
const containerElement = document.querySelector(standaloneContainer);
|
|
244
|
+
|
|
245
|
+
if (containerElement) {
|
|
246
|
+
console.log(`[WuReact] Running ${appName} in standalone mode`);
|
|
247
|
+
mountApp(containerElement);
|
|
248
|
+
return true;
|
|
249
|
+
} else {
|
|
250
|
+
console.warn(`[WuReact] Standalone container ${standaloneContainer} not found`);
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
return false;
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
/**
|
|
259
|
+
* Crea un componente React para cargar microfrontends (para el Shell)
|
|
260
|
+
*
|
|
261
|
+
* @example
|
|
262
|
+
* import { createWuSlot } from 'wu-framework/adapters/react';
|
|
263
|
+
* const WuSlot = createWuSlot(React);
|
|
264
|
+
*
|
|
265
|
+
* <WuSlot name="my-app" url="http://localhost:3001" />
|
|
266
|
+
*/
|
|
267
|
+
function createWuSlot(React) {
|
|
268
|
+
const { useState, useEffect, useRef } = React;
|
|
269
|
+
|
|
270
|
+
return function WuSlot({
|
|
271
|
+
name,
|
|
272
|
+
url,
|
|
273
|
+
appName = null,
|
|
274
|
+
fallback = null,
|
|
275
|
+
onLoad = null,
|
|
276
|
+
onError = null,
|
|
277
|
+
onMount = null,
|
|
278
|
+
onUnmount = null,
|
|
279
|
+
className = '',
|
|
280
|
+
style = {},
|
|
281
|
+
...props
|
|
282
|
+
}) {
|
|
283
|
+
const actualAppName = appName || name;
|
|
284
|
+
|
|
285
|
+
// ID estable derivado del nombre: el div ya tiene este id desde el primer render.
|
|
286
|
+
// wu.mount(name, '#id') lo encuentra sin necesidad de innerHTML ni appendChild.
|
|
287
|
+
const containerId = `wu-slot-${actualAppName}`;
|
|
288
|
+
const mountedRef = useRef(false);
|
|
289
|
+
const [loading, setLoading] = useState(true);
|
|
290
|
+
const [error, setError] = useState(null);
|
|
291
|
+
|
|
292
|
+
useEffect(() => {
|
|
293
|
+
let cancelled = false;
|
|
294
|
+
|
|
295
|
+
// Delay 50ms + flag cancelled: patrón StrictMode-safe.
|
|
296
|
+
// En StrictMode React monta → desmonta → monta; el primer ciclo cancela
|
|
297
|
+
// el timeout antes de ejecutarse; solo el segundo ciclo monta el MF.
|
|
298
|
+
const timer = setTimeout(async () => {
|
|
299
|
+
if (cancelled) return;
|
|
300
|
+
|
|
301
|
+
try {
|
|
302
|
+
setLoading(true);
|
|
303
|
+
setError(null);
|
|
304
|
+
|
|
305
|
+
const wu = getWuInstance();
|
|
306
|
+
if (!wu) throw new Error('Wu Framework not initialized');
|
|
307
|
+
|
|
308
|
+
// El div#containerId ya está en el DOM (renderizado abajo).
|
|
309
|
+
// wu.mount lo usa como target; no tocamos su DOM desde JS imperativo.
|
|
310
|
+
await wu.mount(actualAppName, `#${containerId}`);
|
|
311
|
+
|
|
312
|
+
if (!cancelled) {
|
|
313
|
+
mountedRef.current = true;
|
|
314
|
+
setLoading(false);
|
|
315
|
+
|
|
316
|
+
const container = document.getElementById(containerId);
|
|
317
|
+
if (onLoad) onLoad({ name: actualAppName, url });
|
|
318
|
+
if (onMount) onMount({ name: actualAppName, container });
|
|
319
|
+
}
|
|
320
|
+
} catch (err) {
|
|
321
|
+
if (!cancelled) {
|
|
322
|
+
console.error(`[WuSlot] Error loading ${actualAppName}:`, err);
|
|
323
|
+
setError(err.message || 'Failed to load microfrontend');
|
|
324
|
+
setLoading(false);
|
|
325
|
+
if (onError) onError(err);
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
}, 50);
|
|
329
|
+
|
|
330
|
+
return () => {
|
|
331
|
+
cancelled = true;
|
|
332
|
+
clearTimeout(timer);
|
|
333
|
+
|
|
334
|
+
if (mountedRef.current) {
|
|
335
|
+
if (onUnmount) onUnmount({ name: actualAppName });
|
|
336
|
+
const wu = getWuInstance();
|
|
337
|
+
if (wu) wu.unmount(actualAppName).catch(() => {});
|
|
338
|
+
mountedRef.current = false;
|
|
339
|
+
}
|
|
340
|
+
};
|
|
341
|
+
}, [actualAppName, url, onLoad, onError, onMount, onUnmount]);
|
|
342
|
+
|
|
343
|
+
// Estado de error
|
|
344
|
+
if (error) {
|
|
345
|
+
return React.createElement('div', {
|
|
346
|
+
className: `wu-slot wu-slot-error ${className}`,
|
|
347
|
+
style: {
|
|
348
|
+
padding: '1rem',
|
|
349
|
+
border: '1px solid #f5c6cb',
|
|
350
|
+
borderRadius: '4px',
|
|
351
|
+
backgroundColor: '#f8d7da',
|
|
352
|
+
color: '#721c24',
|
|
353
|
+
...style
|
|
354
|
+
},
|
|
355
|
+
...props
|
|
356
|
+
}, [
|
|
357
|
+
React.createElement('strong', { key: 'title' }, `Error loading ${name}`),
|
|
358
|
+
React.createElement('p', { key: 'message', style: { margin: '0.5rem 0 0 0' } }, error)
|
|
359
|
+
]);
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
// Render principal: Fragment con fallback y div de montaje como HERMANOS.
|
|
363
|
+
//
|
|
364
|
+
// REGLA CRÍTICA: el div#containerId NO debe tener hijos React.
|
|
365
|
+
// wu.mount inyecta el MF (otro createRoot) dentro de ese div. Si React también
|
|
366
|
+
// administra hijos ahí, al desmontar el fallback llama removeChild sobre nodos
|
|
367
|
+
// que el MF ya reemplazó → "The node to be removed is not a child of this node".
|
|
368
|
+
//
|
|
369
|
+
// Solución: fallback y mount-target como hermanos en un Fragment pasados como
|
|
370
|
+
// argumentos separados a createElement (NO como array; el array rompe la
|
|
371
|
+
// reconciliación). React solo gestiona el fallback; el interior del mount-target
|
|
372
|
+
// lo controla exclusivamente el MF.
|
|
373
|
+
const defaultFallback = React.createElement('div', {
|
|
374
|
+
style: { display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '2rem', color: '#666' }
|
|
375
|
+
}, `Loading ${name}...`);
|
|
376
|
+
|
|
377
|
+
return React.createElement(React.Fragment, null,
|
|
378
|
+
loading
|
|
379
|
+
? React.createElement('div', { className: `wu-slot-fallback ${className}` }, fallback || defaultFallback)
|
|
380
|
+
: null,
|
|
381
|
+
React.createElement('div', Object.assign({
|
|
382
|
+
id: containerId,
|
|
383
|
+
className: `wu-slot ${loading ? 'wu-slot-loading' : 'wu-slot-loaded'}`,
|
|
384
|
+
'data-wu-app': actualAppName,
|
|
385
|
+
'data-wu-url': url,
|
|
386
|
+
style: Object.assign({ width: '100%', minHeight: loading ? 0 : '200px' }, style)
|
|
387
|
+
}, props))
|
|
388
|
+
);
|
|
389
|
+
};
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
/**
|
|
393
|
+
* Hook para usar el EventBus de Wu Framework en React
|
|
394
|
+
*
|
|
395
|
+
* @example
|
|
396
|
+
* const { emit, on } = useWuEvents();
|
|
397
|
+
*
|
|
398
|
+
* useEffect(() => {
|
|
399
|
+
* const unsub = on('user:login', (data) => console.log(data));
|
|
400
|
+
* return unsub;
|
|
401
|
+
* }, [on]);
|
|
402
|
+
*/
|
|
403
|
+
function createUseWuEvents(React) {
|
|
404
|
+
const { useCallback, useEffect, useRef } = React;
|
|
405
|
+
|
|
406
|
+
return function useWuEvents() {
|
|
407
|
+
const subscriptionsRef = useRef([]);
|
|
408
|
+
|
|
409
|
+
const emit = useCallback((event, data, options) => {
|
|
410
|
+
const wu = getWuInstance();
|
|
411
|
+
if (wu?.eventBus) {
|
|
412
|
+
wu.eventBus.emit(event, data, options);
|
|
413
|
+
} else {
|
|
414
|
+
console.warn('[useWuEvents] Wu Framework not available');
|
|
415
|
+
}
|
|
416
|
+
}, []);
|
|
417
|
+
|
|
418
|
+
const on = useCallback((event, callback) => {
|
|
419
|
+
const wu = getWuInstance();
|
|
420
|
+
if (wu?.eventBus) {
|
|
421
|
+
const unsubscribe = wu.eventBus.on(event, callback);
|
|
422
|
+
subscriptionsRef.current.push(unsubscribe);
|
|
423
|
+
return unsubscribe;
|
|
424
|
+
}
|
|
425
|
+
console.warn('[useWuEvents] Wu Framework not available');
|
|
426
|
+
return () => {};
|
|
427
|
+
}, []);
|
|
428
|
+
|
|
429
|
+
const once = useCallback((event, callback) => {
|
|
430
|
+
const wu = getWuInstance();
|
|
431
|
+
if (wu?.eventBus) {
|
|
432
|
+
return wu.eventBus.once(event, callback);
|
|
433
|
+
}
|
|
434
|
+
console.warn('[useWuEvents] Wu Framework not available');
|
|
435
|
+
return () => {};
|
|
436
|
+
}, []);
|
|
437
|
+
|
|
438
|
+
// Cleanup on unmount
|
|
439
|
+
useEffect(() => {
|
|
440
|
+
return () => {
|
|
441
|
+
subscriptionsRef.current.forEach(unsub => unsub());
|
|
442
|
+
subscriptionsRef.current = [];
|
|
443
|
+
};
|
|
444
|
+
}, []);
|
|
445
|
+
|
|
446
|
+
return { emit, on, once };
|
|
447
|
+
};
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
/**
|
|
451
|
+
* Hook para usar el Store de Wu Framework en React
|
|
452
|
+
*
|
|
453
|
+
* @example
|
|
454
|
+
* const { state, setState, subscribe } = useWuStore('user');
|
|
455
|
+
*/
|
|
456
|
+
function createUseWuStore(React) {
|
|
457
|
+
const { useState, useCallback, useEffect } = React;
|
|
458
|
+
|
|
459
|
+
return function useWuStore(namespace = '') {
|
|
460
|
+
const [state, setLocalState] = useState(() => {
|
|
461
|
+
const wu = getWuInstance();
|
|
462
|
+
return wu?.store?.get(namespace) || null;
|
|
463
|
+
});
|
|
464
|
+
|
|
465
|
+
const setState = useCallback((path, value) => {
|
|
466
|
+
const wu = getWuInstance();
|
|
467
|
+
if (wu?.store) {
|
|
468
|
+
const fullPath = namespace ? `${namespace}.${path}` : path;
|
|
469
|
+
wu.store.set(fullPath, value);
|
|
470
|
+
}
|
|
471
|
+
}, [namespace]);
|
|
472
|
+
|
|
473
|
+
const getState = useCallback((path = '') => {
|
|
474
|
+
const wu = getWuInstance();
|
|
475
|
+
if (wu?.store) {
|
|
476
|
+
const fullPath = namespace ? (path ? `${namespace}.${path}` : namespace) : path;
|
|
477
|
+
return wu.store.get(fullPath);
|
|
478
|
+
}
|
|
479
|
+
return null;
|
|
480
|
+
}, [namespace]);
|
|
481
|
+
|
|
482
|
+
// Subscribe to changes
|
|
483
|
+
useEffect(() => {
|
|
484
|
+
const wu = getWuInstance();
|
|
485
|
+
if (!wu?.store) return;
|
|
486
|
+
|
|
487
|
+
const pattern = namespace ? `${namespace}.*` : '*';
|
|
488
|
+
const unsubscribe = wu.store.on(pattern, () => {
|
|
489
|
+
setLocalState(wu.store.get(namespace));
|
|
490
|
+
});
|
|
491
|
+
|
|
492
|
+
return unsubscribe;
|
|
493
|
+
}, [namespace]);
|
|
494
|
+
|
|
495
|
+
return { state, setState, getState };
|
|
496
|
+
};
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
/**
|
|
500
|
+
* Hook para integrar wu.ai con React (Paradigma C: IA como Director de Orquesta)
|
|
501
|
+
*
|
|
502
|
+
* Manages messages, streaming state, and AI interaction lifecycle.
|
|
503
|
+
* The AI calls business-level actions that orchestrate the UI via wu.emit/wu.store.
|
|
504
|
+
*
|
|
505
|
+
* @example
|
|
506
|
+
* const { messages, send, isStreaming } = useWuAI();
|
|
507
|
+
*
|
|
508
|
+
* await send('Navigate to users page');
|
|
509
|
+
* // AI calls 'navigate' action → wu.emit('shell:navigate') → UI reacts
|
|
510
|
+
*/
|
|
511
|
+
function createUseWuAI(React) {
|
|
512
|
+
const { useState, useCallback, useRef, useEffect } = React;
|
|
513
|
+
|
|
514
|
+
return function useWuAI(options = {}) {
|
|
515
|
+
const { namespace = 'default', onActionExecuted = null } = options;
|
|
516
|
+
|
|
517
|
+
const [messages, setMessages] = useState([]);
|
|
518
|
+
const [isStreaming, setIsStreaming] = useState(false);
|
|
519
|
+
const [error, setError] = useState(null);
|
|
520
|
+
const abortRef = useRef(null);
|
|
521
|
+
const actionListenerRef = useRef(null);
|
|
522
|
+
|
|
523
|
+
// Listen for action execution events to provide visual feedback
|
|
524
|
+
useEffect(() => {
|
|
525
|
+
const wu = getWuInstance();
|
|
526
|
+
if (!wu?.eventBus) return;
|
|
527
|
+
|
|
528
|
+
const unsub = wu.eventBus.on('ai:action:executed', (event) => {
|
|
529
|
+
const actionMsg = {
|
|
530
|
+
id: `action-${Date.now()}`,
|
|
531
|
+
role: 'action',
|
|
532
|
+
content: event.data?.action || 'action',
|
|
533
|
+
result: event.data?.result,
|
|
534
|
+
timestamp: Date.now(),
|
|
535
|
+
};
|
|
536
|
+
setMessages((prev) => [...prev, actionMsg]);
|
|
537
|
+
if (onActionExecuted) onActionExecuted(event.data);
|
|
538
|
+
});
|
|
539
|
+
|
|
540
|
+
actionListenerRef.current = unsub;
|
|
541
|
+
return () => { if (unsub) unsub(); };
|
|
542
|
+
}, [onActionExecuted]);
|
|
543
|
+
|
|
544
|
+
/**
|
|
545
|
+
* Send a message and stream the response in real-time.
|
|
546
|
+
*/
|
|
547
|
+
const send = useCallback(async (text) => {
|
|
548
|
+
if (!text?.trim()) return;
|
|
549
|
+
|
|
550
|
+
const wu = getWuInstance();
|
|
551
|
+
if (!wu?.ai) {
|
|
552
|
+
setError('Wu AI not available');
|
|
553
|
+
return;
|
|
554
|
+
}
|
|
555
|
+
|
|
556
|
+
// Add user message
|
|
557
|
+
const userMsg = {
|
|
558
|
+
id: `user-${Date.now()}`,
|
|
559
|
+
role: 'user',
|
|
560
|
+
content: text,
|
|
561
|
+
timestamp: Date.now(),
|
|
562
|
+
};
|
|
563
|
+
setMessages((prev) => [...prev, userMsg]);
|
|
564
|
+
setError(null);
|
|
565
|
+
setIsStreaming(true);
|
|
566
|
+
|
|
567
|
+
// Create assistant placeholder
|
|
568
|
+
const assistantId = `assistant-${Date.now()}`;
|
|
569
|
+
setMessages((prev) => [...prev, {
|
|
570
|
+
id: assistantId,
|
|
571
|
+
role: 'assistant',
|
|
572
|
+
content: '',
|
|
573
|
+
timestamp: Date.now(),
|
|
574
|
+
}]);
|
|
575
|
+
|
|
576
|
+
try {
|
|
577
|
+
let fullContent = '';
|
|
578
|
+
|
|
579
|
+
for await (const chunk of wu.ai.stream(text, { namespace })) {
|
|
580
|
+
if (chunk.type === 'text') {
|
|
581
|
+
fullContent += chunk.content;
|
|
582
|
+
const captured = fullContent;
|
|
583
|
+
setMessages((prev) =>
|
|
584
|
+
prev.map((m) =>
|
|
585
|
+
m.id === assistantId ? { ...m, content: captured } : m,
|
|
586
|
+
),
|
|
587
|
+
);
|
|
588
|
+
}
|
|
589
|
+
|
|
590
|
+
if (chunk.type === 'tool_result') {
|
|
591
|
+
// Tool results are handled by the ai:action:executed listener
|
|
592
|
+
}
|
|
593
|
+
|
|
594
|
+
if (chunk.type === 'error') {
|
|
595
|
+
setError(chunk.error?.message || 'AI request failed');
|
|
596
|
+
}
|
|
597
|
+
}
|
|
598
|
+
} catch (err) {
|
|
599
|
+
setError(err.message || 'AI request failed');
|
|
600
|
+
// Remove empty assistant message on error
|
|
601
|
+
setMessages((prev) => prev.filter((m) => m.id !== assistantId || m.content));
|
|
602
|
+
} finally {
|
|
603
|
+
setIsStreaming(false);
|
|
604
|
+
}
|
|
605
|
+
}, [namespace]);
|
|
606
|
+
|
|
607
|
+
/**
|
|
608
|
+
* Send without streaming (simpler, waits for full response).
|
|
609
|
+
*/
|
|
610
|
+
const sendSync = useCallback(async (text) => {
|
|
611
|
+
if (!text?.trim()) return null;
|
|
612
|
+
|
|
613
|
+
const wu = getWuInstance();
|
|
614
|
+
if (!wu?.ai) {
|
|
615
|
+
setError('Wu AI not available');
|
|
616
|
+
return null;
|
|
617
|
+
}
|
|
618
|
+
|
|
619
|
+
const userMsg = {
|
|
620
|
+
id: `user-${Date.now()}`,
|
|
621
|
+
role: 'user',
|
|
622
|
+
content: text,
|
|
623
|
+
timestamp: Date.now(),
|
|
624
|
+
};
|
|
625
|
+
setMessages((prev) => [...prev, userMsg]);
|
|
626
|
+
setError(null);
|
|
627
|
+
setIsStreaming(true);
|
|
628
|
+
|
|
629
|
+
try {
|
|
630
|
+
const response = await wu.ai.send(text, { namespace });
|
|
631
|
+
|
|
632
|
+
const assistantMsg = {
|
|
633
|
+
id: `assistant-${Date.now()}`,
|
|
634
|
+
role: 'assistant',
|
|
635
|
+
content: response.content,
|
|
636
|
+
timestamp: Date.now(),
|
|
637
|
+
};
|
|
638
|
+
setMessages((prev) => [...prev, assistantMsg]);
|
|
639
|
+
return response;
|
|
640
|
+
} catch (err) {
|
|
641
|
+
setError(err.message || 'AI request failed');
|
|
642
|
+
return null;
|
|
643
|
+
} finally {
|
|
644
|
+
setIsStreaming(false);
|
|
645
|
+
}
|
|
646
|
+
}, [namespace]);
|
|
647
|
+
|
|
648
|
+
const abort = useCallback(() => {
|
|
649
|
+
const wu = getWuInstance();
|
|
650
|
+
if (wu?.ai) wu.ai.abort(namespace);
|
|
651
|
+
setIsStreaming(false);
|
|
652
|
+
}, [namespace]);
|
|
653
|
+
|
|
654
|
+
const clear = useCallback(() => {
|
|
655
|
+
setMessages([]);
|
|
656
|
+
setError(null);
|
|
657
|
+
const wu = getWuInstance();
|
|
658
|
+
if (wu?.ai) wu.ai.conversation.clear(namespace);
|
|
659
|
+
}, [namespace]);
|
|
660
|
+
|
|
661
|
+
return {
|
|
662
|
+
messages,
|
|
663
|
+
isStreaming,
|
|
664
|
+
error,
|
|
665
|
+
send,
|
|
666
|
+
sendSync,
|
|
667
|
+
abort,
|
|
668
|
+
clear,
|
|
669
|
+
};
|
|
670
|
+
};
|
|
671
|
+
}
|
|
672
|
+
|
|
673
|
+
// API pública del adapter
|
|
674
|
+
export const wuReact = {
|
|
675
|
+
register,
|
|
676
|
+
createWuSlot,
|
|
677
|
+
createUseWuEvents,
|
|
678
|
+
createUseWuStore,
|
|
679
|
+
createUseWuAI,
|
|
680
|
+
getWuInstance,
|
|
681
|
+
waitForWu
|
|
682
|
+
};
|
|
683
|
+
|
|
684
|
+
// Named exports para conveniencia
|
|
685
|
+
export {
|
|
686
|
+
register,
|
|
687
|
+
createWuSlot,
|
|
688
|
+
createUseWuEvents,
|
|
689
|
+
createUseWuStore,
|
|
690
|
+
createUseWuAI,
|
|
691
|
+
getWuInstance,
|
|
692
|
+
waitForWu
|
|
693
|
+
};
|
|
694
|
+
|
|
695
|
+
export default wuReact;
|