wu-framework 1.1.7 → 1.1.9

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