wu-framework 1.1.6 → 1.1.8

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/README.md +511 -977
  2. package/dist/wu-framework.cjs.js +3 -1
  3. package/dist/wu-framework.cjs.js.map +1 -0
  4. package/dist/wu-framework.dev.js +7533 -2761
  5. package/dist/wu-framework.dev.js.map +1 -1
  6. package/dist/wu-framework.esm.js +3 -0
  7. package/dist/wu-framework.esm.js.map +1 -0
  8. package/dist/wu-framework.umd.js +3 -1
  9. package/dist/wu-framework.umd.js.map +1 -0
  10. package/integrations/astro/README.md +127 -0
  11. package/integrations/astro/WuApp.astro +63 -0
  12. package/integrations/astro/WuShell.astro +39 -0
  13. package/integrations/astro/index.js +68 -0
  14. package/integrations/astro/package.json +38 -0
  15. package/integrations/astro/types.d.ts +53 -0
  16. package/package.json +94 -74
  17. package/src/adapters/angular/ai.js +30 -0
  18. package/src/adapters/angular/index.d.ts +154 -0
  19. package/src/adapters/angular/index.js +932 -0
  20. package/src/adapters/angular.d.ts +3 -154
  21. package/src/adapters/angular.js +3 -813
  22. package/src/adapters/index.js +35 -24
  23. package/src/adapters/lit/ai.js +20 -0
  24. package/src/adapters/lit/index.d.ts +120 -0
  25. package/src/adapters/lit/index.js +721 -0
  26. package/src/adapters/lit.d.ts +3 -120
  27. package/src/adapters/lit.js +3 -726
  28. package/src/adapters/preact/ai.js +33 -0
  29. package/src/adapters/preact/index.d.ts +108 -0
  30. package/src/adapters/preact/index.js +661 -0
  31. package/src/adapters/preact.d.ts +3 -108
  32. package/src/adapters/preact.js +3 -665
  33. package/src/adapters/react/ai.js +135 -0
  34. package/src/adapters/react/index.d.ts +246 -0
  35. package/src/adapters/react/index.js +689 -0
  36. package/src/adapters/react.d.ts +3 -212
  37. package/src/adapters/react.js +3 -513
  38. package/src/adapters/shared.js +64 -0
  39. package/src/adapters/solid/ai.js +32 -0
  40. package/src/adapters/solid/index.d.ts +101 -0
  41. package/src/adapters/solid/index.js +586 -0
  42. package/src/adapters/solid.d.ts +3 -101
  43. package/src/adapters/solid.js +3 -591
  44. package/src/adapters/svelte/ai.js +31 -0
  45. package/src/adapters/svelte/index.d.ts +166 -0
  46. package/src/adapters/svelte/index.js +798 -0
  47. package/src/adapters/svelte.d.ts +3 -166
  48. package/src/adapters/svelte.js +3 -803
  49. package/src/adapters/vanilla/ai.js +30 -0
  50. package/src/adapters/vanilla/index.d.ts +179 -0
  51. package/src/adapters/vanilla/index.js +785 -0
  52. package/src/adapters/vanilla.d.ts +3 -179
  53. package/src/adapters/vanilla.js +3 -791
  54. package/src/adapters/vue/ai.js +52 -0
  55. package/src/adapters/vue/index.d.ts +299 -0
  56. package/src/adapters/vue/index.js +608 -0
  57. package/src/adapters/vue.d.ts +3 -299
  58. package/src/adapters/vue.js +3 -611
  59. package/src/ai/wu-ai-actions.js +261 -0
  60. package/src/ai/wu-ai-browser.js +663 -0
  61. package/src/ai/wu-ai-context.js +332 -0
  62. package/src/ai/wu-ai-conversation.js +554 -0
  63. package/src/ai/wu-ai-permissions.js +381 -0
  64. package/src/ai/wu-ai-provider.js +605 -0
  65. package/src/ai/wu-ai-schema.js +225 -0
  66. package/src/ai/wu-ai-triggers.js +396 -0
  67. package/src/ai/wu-ai.js +474 -0
  68. package/src/core/wu-app.js +50 -8
  69. package/src/core/wu-cache.js +1 -1
  70. package/src/core/wu-core.js +645 -677
  71. package/src/core/wu-html-parser.js +121 -211
  72. package/src/core/wu-iframe-sandbox.js +328 -0
  73. package/src/core/wu-mcp-bridge.js +647 -0
  74. package/src/core/wu-overrides.js +510 -0
  75. package/src/core/wu-prefetch.js +414 -0
  76. package/src/core/wu-proxy-sandbox.js +398 -75
  77. package/src/core/wu-sandbox.js +86 -268
  78. package/src/core/wu-script-executor.js +79 -182
  79. package/src/core/wu-snapshot-sandbox.js +149 -106
  80. package/src/core/wu-strategies.js +13 -0
  81. package/src/core/wu-style-bridge.js +0 -2
  82. package/src/index.js +139 -665
  83. package/dist/wu-framework.hex.js +0 -23
  84. package/dist/wu-framework.min.js +0 -1
  85. package/dist/wu-framework.obf.js +0 -1
  86. package/scripts/build-protected.js +0 -366
  87. package/scripts/build.js +0 -212
  88. package/scripts/rollup-plugin-hex.js +0 -143
  89. package/src/core/wu-registry.js +0 -60
  90. package/src/core/wu-sandbox-pool.js +0 -390
@@ -0,0 +1,689 @@
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
+ const mountMicrofrontend = useCallback(async () => {
284
+ if (!containerRef.current) return;
285
+
286
+ try {
287
+ setLoading(true);
288
+ setError(null);
289
+
290
+ const wu = getWuInstance();
291
+ if (!wu) {
292
+ throw new Error('Wu Framework not initialized');
293
+ }
294
+
295
+ // Crear container interno
296
+ const containerId = `wu-slot-${actualAppName}-${Date.now()}`;
297
+ const innerContainer = document.createElement('div');
298
+ innerContainer.id = containerId;
299
+ innerContainer.style.width = '100%';
300
+ innerContainer.style.height = '100%';
301
+ containerRef.current.innerHTML = '';
302
+ containerRef.current.appendChild(innerContainer);
303
+
304
+ // Crear y montar la app
305
+ const app = wu.app(actualAppName, {
306
+ url,
307
+ container: `#${containerId}`,
308
+ autoInit: true
309
+ });
310
+
311
+ appInstanceRef.current = app;
312
+ await app.mount();
313
+
314
+ setLoading(false);
315
+
316
+ if (onLoad) onLoad({ name: actualAppName, url });
317
+ if (onMount) onMount({ name: actualAppName, container: innerContainer });
318
+
319
+ } catch (err) {
320
+ console.error(`[WuSlot] Error loading ${actualAppName}:`, err);
321
+ setError(err.message || 'Failed to load microfrontend');
322
+ setLoading(false);
323
+
324
+ if (onError) onError(err);
325
+ }
326
+ }, [actualAppName, url, onLoad, onError, onMount]);
327
+
328
+ useEffect(() => {
329
+ mountMicrofrontend();
330
+
331
+ return () => {
332
+ if (appInstanceRef.current) {
333
+ if (onUnmount) onUnmount({ name: actualAppName });
334
+
335
+ appInstanceRef.current.unmount().catch(err => {
336
+ console.warn(`[WuSlot] Error unmounting ${actualAppName}:`, err);
337
+ });
338
+ appInstanceRef.current = null;
339
+ }
340
+ };
341
+ }, [mountMicrofrontend, actualAppName, onUnmount]);
342
+
343
+ // Render 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
363
+ return React.createElement('div', {
364
+ ref: containerRef,
365
+ className: `wu-slot ${loading ? 'wu-slot-loading' : 'wu-slot-loaded'} ${className}`,
366
+ style: {
367
+ minHeight: '100px',
368
+ position: 'relative',
369
+ ...style
370
+ },
371
+ 'data-wu-app': actualAppName,
372
+ 'data-wu-url': url,
373
+ ...props
374
+ }, loading && (fallback || React.createElement('div', {
375
+ style: {
376
+ display: 'flex',
377
+ alignItems: 'center',
378
+ justifyContent: 'center',
379
+ padding: '2rem',
380
+ color: '#666'
381
+ }
382
+ }, `Loading ${name}...`)));
383
+ };
384
+ }
385
+
386
+ /**
387
+ * Hook para usar el EventBus de Wu Framework en React
388
+ *
389
+ * @example
390
+ * const { emit, on } = useWuEvents();
391
+ *
392
+ * useEffect(() => {
393
+ * const unsub = on('user:login', (data) => console.log(data));
394
+ * return unsub;
395
+ * }, [on]);
396
+ */
397
+ function createUseWuEvents(React) {
398
+ const { useCallback, useEffect, useRef } = React;
399
+
400
+ return function useWuEvents() {
401
+ const subscriptionsRef = useRef([]);
402
+
403
+ const emit = useCallback((event, data, options) => {
404
+ const wu = getWuInstance();
405
+ if (wu?.eventBus) {
406
+ wu.eventBus.emit(event, data, options);
407
+ } else {
408
+ console.warn('[useWuEvents] Wu Framework not available');
409
+ }
410
+ }, []);
411
+
412
+ const on = useCallback((event, callback) => {
413
+ const wu = getWuInstance();
414
+ if (wu?.eventBus) {
415
+ const unsubscribe = wu.eventBus.on(event, callback);
416
+ subscriptionsRef.current.push(unsubscribe);
417
+ return unsubscribe;
418
+ }
419
+ console.warn('[useWuEvents] Wu Framework not available');
420
+ return () => {};
421
+ }, []);
422
+
423
+ const once = useCallback((event, callback) => {
424
+ const wu = getWuInstance();
425
+ if (wu?.eventBus) {
426
+ return wu.eventBus.once(event, callback);
427
+ }
428
+ console.warn('[useWuEvents] Wu Framework not available');
429
+ return () => {};
430
+ }, []);
431
+
432
+ // Cleanup on unmount
433
+ useEffect(() => {
434
+ return () => {
435
+ subscriptionsRef.current.forEach(unsub => unsub());
436
+ subscriptionsRef.current = [];
437
+ };
438
+ }, []);
439
+
440
+ return { emit, on, once };
441
+ };
442
+ }
443
+
444
+ /**
445
+ * Hook para usar el Store de Wu Framework en React
446
+ *
447
+ * @example
448
+ * const { state, setState, subscribe } = useWuStore('user');
449
+ */
450
+ function createUseWuStore(React) {
451
+ const { useState, useCallback, useEffect } = React;
452
+
453
+ return function useWuStore(namespace = '') {
454
+ const [state, setLocalState] = useState(() => {
455
+ const wu = getWuInstance();
456
+ return wu?.store?.get(namespace) || null;
457
+ });
458
+
459
+ const setState = useCallback((path, value) => {
460
+ const wu = getWuInstance();
461
+ if (wu?.store) {
462
+ const fullPath = namespace ? `${namespace}.${path}` : path;
463
+ wu.store.set(fullPath, value);
464
+ }
465
+ }, [namespace]);
466
+
467
+ const getState = useCallback((path = '') => {
468
+ const wu = getWuInstance();
469
+ if (wu?.store) {
470
+ const fullPath = namespace ? (path ? `${namespace}.${path}` : namespace) : path;
471
+ return wu.store.get(fullPath);
472
+ }
473
+ return null;
474
+ }, [namespace]);
475
+
476
+ // Subscribe to changes
477
+ useEffect(() => {
478
+ const wu = getWuInstance();
479
+ if (!wu?.store) return;
480
+
481
+ const pattern = namespace ? `${namespace}.*` : '*';
482
+ const unsubscribe = wu.store.on(pattern, () => {
483
+ setLocalState(wu.store.get(namespace));
484
+ });
485
+
486
+ return unsubscribe;
487
+ }, [namespace]);
488
+
489
+ return { state, setState, getState };
490
+ };
491
+ }
492
+
493
+ /**
494
+ * Hook para integrar wu.ai con React (Paradigma C: IA como Director de Orquesta)
495
+ *
496
+ * Manages messages, streaming state, and AI interaction lifecycle.
497
+ * The AI calls business-level actions that orchestrate the UI via wu.emit/wu.store.
498
+ *
499
+ * @example
500
+ * const { messages, send, isStreaming } = useWuAI();
501
+ *
502
+ * await send('Navigate to users page');
503
+ * // AI calls 'navigate' action → wu.emit('shell:navigate') → UI reacts
504
+ */
505
+ function createUseWuAI(React) {
506
+ const { useState, useCallback, useRef, useEffect } = React;
507
+
508
+ return function useWuAI(options = {}) {
509
+ const { namespace = 'default', onActionExecuted = null } = options;
510
+
511
+ const [messages, setMessages] = useState([]);
512
+ const [isStreaming, setIsStreaming] = useState(false);
513
+ const [error, setError] = useState(null);
514
+ const abortRef = useRef(null);
515
+ const actionListenerRef = useRef(null);
516
+
517
+ // Listen for action execution events to provide visual feedback
518
+ useEffect(() => {
519
+ const wu = getWuInstance();
520
+ if (!wu?.eventBus) return;
521
+
522
+ const unsub = wu.eventBus.on('ai:action:executed', (event) => {
523
+ const actionMsg = {
524
+ id: `action-${Date.now()}`,
525
+ role: 'action',
526
+ content: event.data?.action || 'action',
527
+ result: event.data?.result,
528
+ timestamp: Date.now(),
529
+ };
530
+ setMessages((prev) => [...prev, actionMsg]);
531
+ if (onActionExecuted) onActionExecuted(event.data);
532
+ });
533
+
534
+ actionListenerRef.current = unsub;
535
+ return () => { if (unsub) unsub(); };
536
+ }, [onActionExecuted]);
537
+
538
+ /**
539
+ * Send a message and stream the response in real-time.
540
+ */
541
+ const send = useCallback(async (text) => {
542
+ if (!text?.trim()) return;
543
+
544
+ const wu = getWuInstance();
545
+ if (!wu?.ai) {
546
+ setError('Wu AI not available');
547
+ return;
548
+ }
549
+
550
+ // Add user message
551
+ const userMsg = {
552
+ id: `user-${Date.now()}`,
553
+ role: 'user',
554
+ content: text,
555
+ timestamp: Date.now(),
556
+ };
557
+ setMessages((prev) => [...prev, userMsg]);
558
+ setError(null);
559
+ setIsStreaming(true);
560
+
561
+ // Create assistant placeholder
562
+ const assistantId = `assistant-${Date.now()}`;
563
+ setMessages((prev) => [...prev, {
564
+ id: assistantId,
565
+ role: 'assistant',
566
+ content: '',
567
+ timestamp: Date.now(),
568
+ }]);
569
+
570
+ try {
571
+ let fullContent = '';
572
+
573
+ for await (const chunk of wu.ai.stream(text, { namespace })) {
574
+ if (chunk.type === 'text') {
575
+ fullContent += chunk.content;
576
+ const captured = fullContent;
577
+ setMessages((prev) =>
578
+ prev.map((m) =>
579
+ m.id === assistantId ? { ...m, content: captured } : m,
580
+ ),
581
+ );
582
+ }
583
+
584
+ if (chunk.type === 'tool_result') {
585
+ // Tool results are handled by the ai:action:executed listener
586
+ }
587
+
588
+ if (chunk.type === 'error') {
589
+ setError(chunk.error?.message || 'AI request failed');
590
+ }
591
+ }
592
+ } catch (err) {
593
+ setError(err.message || 'AI request failed');
594
+ // Remove empty assistant message on error
595
+ setMessages((prev) => prev.filter((m) => m.id !== assistantId || m.content));
596
+ } finally {
597
+ setIsStreaming(false);
598
+ }
599
+ }, [namespace]);
600
+
601
+ /**
602
+ * Send without streaming (simpler, waits for full response).
603
+ */
604
+ const sendSync = useCallback(async (text) => {
605
+ if (!text?.trim()) return null;
606
+
607
+ const wu = getWuInstance();
608
+ if (!wu?.ai) {
609
+ setError('Wu AI not available');
610
+ return null;
611
+ }
612
+
613
+ const userMsg = {
614
+ id: `user-${Date.now()}`,
615
+ role: 'user',
616
+ content: text,
617
+ timestamp: Date.now(),
618
+ };
619
+ setMessages((prev) => [...prev, userMsg]);
620
+ setError(null);
621
+ setIsStreaming(true);
622
+
623
+ try {
624
+ const response = await wu.ai.send(text, { namespace });
625
+
626
+ const assistantMsg = {
627
+ id: `assistant-${Date.now()}`,
628
+ role: 'assistant',
629
+ content: response.content,
630
+ timestamp: Date.now(),
631
+ };
632
+ setMessages((prev) => [...prev, assistantMsg]);
633
+ return response;
634
+ } catch (err) {
635
+ setError(err.message || 'AI request failed');
636
+ return null;
637
+ } finally {
638
+ setIsStreaming(false);
639
+ }
640
+ }, [namespace]);
641
+
642
+ const abort = useCallback(() => {
643
+ const wu = getWuInstance();
644
+ if (wu?.ai) wu.ai.abort(namespace);
645
+ setIsStreaming(false);
646
+ }, [namespace]);
647
+
648
+ const clear = useCallback(() => {
649
+ setMessages([]);
650
+ setError(null);
651
+ const wu = getWuInstance();
652
+ if (wu?.ai) wu.ai.conversation.clear(namespace);
653
+ }, [namespace]);
654
+
655
+ return {
656
+ messages,
657
+ isStreaming,
658
+ error,
659
+ send,
660
+ sendSync,
661
+ abort,
662
+ clear,
663
+ };
664
+ };
665
+ }
666
+
667
+ // API pública del adapter
668
+ export const wuReact = {
669
+ register,
670
+ createWuSlot,
671
+ createUseWuEvents,
672
+ createUseWuStore,
673
+ createUseWuAI,
674
+ getWuInstance,
675
+ waitForWu
676
+ };
677
+
678
+ // Named exports para conveniencia
679
+ export {
680
+ register,
681
+ createWuSlot,
682
+ createUseWuEvents,
683
+ createUseWuStore,
684
+ createUseWuAI,
685
+ getWuInstance,
686
+ waitForWu
687
+ };
688
+
689
+ export default wuReact;