wu-framework 1.1.14 → 1.1.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (90) hide show
  1. package/LICENSE +39 -39
  2. package/README.md +408 -408
  3. package/dist/wu-framework.cjs.js.map +1 -1
  4. package/dist/wu-framework.dev.js +15151 -15151
  5. package/dist/wu-framework.dev.js.map +1 -1
  6. package/dist/wu-framework.esm.js.map +1 -1
  7. package/dist/wu-framework.umd.js.map +1 -1
  8. package/integrations/astro/README.md +127 -127
  9. package/integrations/astro/WuApp.astro +63 -63
  10. package/integrations/astro/WuShell.astro +39 -39
  11. package/integrations/astro/index.js +68 -68
  12. package/integrations/astro/package.json +38 -38
  13. package/integrations/astro/types.d.ts +53 -53
  14. package/package.json +161 -161
  15. package/src/adapters/angular/ai.js +30 -30
  16. package/src/adapters/angular/index.d.ts +154 -154
  17. package/src/adapters/angular/index.js +932 -932
  18. package/src/adapters/angular.d.ts +3 -3
  19. package/src/adapters/angular.js +3 -3
  20. package/src/adapters/index.js +168 -168
  21. package/src/adapters/lit/ai.js +20 -20
  22. package/src/adapters/lit/index.d.ts +120 -120
  23. package/src/adapters/lit/index.js +721 -721
  24. package/src/adapters/lit.d.ts +3 -3
  25. package/src/adapters/lit.js +3 -3
  26. package/src/adapters/preact/ai.js +33 -33
  27. package/src/adapters/preact/index.d.ts +108 -108
  28. package/src/adapters/preact/index.js +661 -661
  29. package/src/adapters/preact.d.ts +3 -3
  30. package/src/adapters/preact.js +3 -3
  31. package/src/adapters/react/index.js +48 -54
  32. package/src/adapters/react.d.ts +3 -3
  33. package/src/adapters/react.js +3 -3
  34. package/src/adapters/shared.js +64 -64
  35. package/src/adapters/solid/ai.js +32 -32
  36. package/src/adapters/solid/index.d.ts +101 -101
  37. package/src/adapters/solid/index.js +586 -586
  38. package/src/adapters/solid.d.ts +3 -3
  39. package/src/adapters/solid.js +3 -3
  40. package/src/adapters/svelte/ai.js +31 -31
  41. package/src/adapters/svelte/index.d.ts +166 -166
  42. package/src/adapters/svelte/index.js +798 -798
  43. package/src/adapters/svelte.d.ts +3 -3
  44. package/src/adapters/svelte.js +3 -3
  45. package/src/adapters/vanilla/ai.js +30 -30
  46. package/src/adapters/vanilla/index.d.ts +179 -179
  47. package/src/adapters/vanilla/index.js +785 -785
  48. package/src/adapters/vanilla.d.ts +3 -3
  49. package/src/adapters/vanilla.js +3 -3
  50. package/src/adapters/vue/ai.js +52 -52
  51. package/src/adapters/vue/index.d.ts +299 -299
  52. package/src/adapters/vue/index.js +610 -610
  53. package/src/adapters/vue.d.ts +3 -3
  54. package/src/adapters/vue.js +3 -3
  55. package/src/ai/wu-ai-actions.js +261 -261
  56. package/src/ai/wu-ai-agent.js +546 -546
  57. package/src/ai/wu-ai-browser-primitives.js +354 -354
  58. package/src/ai/wu-ai-browser.js +380 -380
  59. package/src/ai/wu-ai-context.js +332 -332
  60. package/src/ai/wu-ai-conversation.js +613 -613
  61. package/src/ai/wu-ai-orchestrate.js +1021 -1021
  62. package/src/ai/wu-ai-permissions.js +381 -381
  63. package/src/ai/wu-ai-provider.js +700 -700
  64. package/src/ai/wu-ai-schema.js +225 -225
  65. package/src/ai/wu-ai-triggers.js +396 -396
  66. package/src/ai/wu-ai.js +804 -804
  67. package/src/core/wu-app.js +236 -236
  68. package/src/core/wu-cache.js +477 -477
  69. package/src/core/wu-core.js +1398 -1398
  70. package/src/core/wu-error-boundary.js +382 -382
  71. package/src/core/wu-event-bus.js +348 -348
  72. package/src/core/wu-hooks.js +350 -350
  73. package/src/core/wu-html-parser.js +190 -190
  74. package/src/core/wu-iframe-sandbox.js +328 -328
  75. package/src/core/wu-loader.js +272 -272
  76. package/src/core/wu-logger.js +134 -134
  77. package/src/core/wu-manifest.js +509 -509
  78. package/src/core/wu-mcp-bridge.js +432 -432
  79. package/src/core/wu-overrides.js +510 -510
  80. package/src/core/wu-performance.js +228 -228
  81. package/src/core/wu-plugin.js +348 -348
  82. package/src/core/wu-prefetch.js +414 -414
  83. package/src/core/wu-proxy-sandbox.js +476 -476
  84. package/src/core/wu-sandbox.js +779 -779
  85. package/src/core/wu-script-executor.js +113 -113
  86. package/src/core/wu-snapshot-sandbox.js +227 -227
  87. package/src/core/wu-strategies.js +256 -256
  88. package/src/core/wu-style-bridge.js +477 -477
  89. package/src/index.js +224 -224
  90. package/src/utils/dependency-resolver.js +327 -327
@@ -1,348 +1,348 @@
1
- /**
2
- * 🔌 WU-PLUGIN: SECURE PLUGIN SYSTEM
3
- *
4
- * Sistema de plugins con sandboxing de seguridad
5
- * - Plugin lifecycle (install, beforeMount, afterMount, etc.)
6
- * - Sandboxed API (plugins no tienen acceso completo al core)
7
- * - Permission system
8
- * - Timeout protection
9
- */
10
- import { logger } from './wu-logger.js';
11
-
12
-
13
- export class WuPluginSystem {
14
- constructor(core) {
15
- this._core = core; // Privado - no expuesto a plugins
16
- this.plugins = new Map();
17
- this.hooks = new Map();
18
-
19
- // Hooks disponibles
20
- this.availableHooks = [
21
- 'beforeInit', 'afterInit',
22
- 'beforeMount', 'afterMount',
23
- 'beforeUnmount', 'afterUnmount',
24
- 'onError', 'onDestroy'
25
- ];
26
-
27
- // 🔐 Permisos disponibles
28
- this.availablePermissions = [
29
- 'mount', // Puede montar/desmontar apps
30
- 'events', // Puede emitir/escuchar eventos
31
- 'store', // Puede leer/escribir store
32
- 'apps', // Puede ver lista de apps
33
- 'config', // Puede modificar configuración
34
- 'unsafe' // Acceso completo (peligroso)
35
- ];
36
-
37
- // 🔐 Timeout para hooks (evita que plugins bloqueen)
38
- this.hookTimeout = 5000; // 5 segundos
39
-
40
- this.availableHooks.forEach(hook => {
41
- this.hooks.set(hook, []);
42
- });
43
- }
44
-
45
- /**
46
- * 🔐 CREATE SANDBOXED API: Crea API limitada para el plugin
47
- * @param {Array} permissions - Permisos del plugin
48
- * @returns {Object} API sandboxeada
49
- */
50
- _createSandboxedApi(permissions) {
51
- const api = {
52
- // Info básica siempre disponible
53
- version: this._core.version,
54
- info: this._core.info,
55
-
56
- // 📊 Métodos de solo lectura
57
- getAppInfo: (appName) => {
58
- const mounted = this._core.mounted.get(appName);
59
- if (!mounted) return null;
60
- return {
61
- name: appName,
62
- state: mounted.state,
63
- timestamp: mounted.timestamp
64
- };
65
- },
66
-
67
- getMountedApps: () => {
68
- return Array.from(this._core.mounted.keys());
69
- },
70
-
71
- getStats: () => this._core.getStats()
72
- };
73
-
74
- // 🔐 Agregar métodos según permisos
75
- if (permissions.includes('events') || permissions.includes('unsafe')) {
76
- api.emit = (event, data) => this._core.eventBus.emit(event, data, { appName: 'plugin' });
77
- api.on = (event, cb) => this._core.eventBus.on(event, cb);
78
- api.off = (event, cb) => this._core.eventBus.off(event, cb);
79
- }
80
-
81
- if (permissions.includes('store') || permissions.includes('unsafe')) {
82
- api.getState = (path) => this._core.store.get(path);
83
- api.setState = (path, value) => this._core.store.set(path, value);
84
- }
85
-
86
- if (permissions.includes('mount') || permissions.includes('unsafe')) {
87
- api.mount = (appName, container) => this._core.mount(appName, container);
88
- api.unmount = (appName) => this._core.unmount(appName);
89
- }
90
-
91
- if (permissions.includes('config') || permissions.includes('unsafe')) {
92
- api.configure = (config) => {
93
- // Solo permitir configuración segura
94
- const safeKeys = ['debug', 'logLevel'];
95
- const safeConfig = {};
96
- for (const key of safeKeys) {
97
- if (key in config) safeConfig[key] = config[key];
98
- }
99
- Object.assign(this._core, safeConfig);
100
- };
101
- }
102
-
103
- // 🚨 Acceso completo solo con permiso 'unsafe'
104
- if (permissions.includes('unsafe')) {
105
- api._unsafeCore = this._core;
106
- logger.warn('[WuPlugin] ⚠️ Plugin has unsafe access to core!');
107
- }
108
-
109
- // Congelar API para evitar modificaciones
110
- return Object.freeze(api);
111
- }
112
-
113
- /**
114
- * 🔐 VALIDATE PLUGIN: Validar estructura del plugin
115
- * @param {Object} plugin
116
- * @returns {boolean}
117
- */
118
- _validatePlugin(plugin) {
119
- if (!plugin || typeof plugin !== 'object') {
120
- throw new Error('[WuPlugin] Invalid plugin: must be an object');
121
- }
122
-
123
- if (!plugin.name || typeof plugin.name !== 'string') {
124
- throw new Error('[WuPlugin] Invalid plugin: must have a name (string)');
125
- }
126
-
127
- if (plugin.name.length > 50) {
128
- throw new Error('[WuPlugin] Invalid plugin: name too long (max 50 chars)');
129
- }
130
-
131
- // Validar que los hooks sean funciones
132
- for (const hookName of this.availableHooks) {
133
- if (plugin[hookName] && typeof plugin[hookName] !== 'function') {
134
- throw new Error(`[WuPlugin] Invalid plugin: ${hookName} must be a function`);
135
- }
136
- }
137
-
138
- // Validar permisos
139
- if (plugin.permissions) {
140
- if (!Array.isArray(plugin.permissions)) {
141
- throw new Error('[WuPlugin] Invalid plugin: permissions must be an array');
142
- }
143
-
144
- for (const perm of plugin.permissions) {
145
- if (!this.availablePermissions.includes(perm)) {
146
- throw new Error(`[WuPlugin] Invalid permission: ${perm}`);
147
- }
148
- }
149
- }
150
-
151
- return true;
152
- }
153
-
154
- /**
155
- * 📦 USE: Instalar plugin con sandboxing
156
- * @param {Object|Function} plugin - Plugin o factory function
157
- * @param {Object} options - Opciones del plugin
158
- */
159
- use(plugin, options = {}) {
160
- // Si es una función, ejecutarla para obtener el plugin
161
- // Nota: factory functions NO reciben acceso al core
162
- if (typeof plugin === 'function') {
163
- plugin = plugin(options);
164
- }
165
-
166
- // Validar plugin
167
- this._validatePlugin(plugin);
168
-
169
- // Verificar si ya está instalado
170
- if (this.plugins.has(plugin.name)) {
171
- logger.warn(`[WuPlugin] Plugin "${plugin.name}" already installed`);
172
- return;
173
- }
174
-
175
- // Determinar permisos (por defecto: solo eventos)
176
- const permissions = plugin.permissions || ['events'];
177
-
178
- // 🔐 Crear API sandboxeada
179
- const sandboxedApi = this._createSandboxedApi(permissions);
180
-
181
- // Ejecutar install del plugin con API sandboxeada
182
- if (plugin.install) {
183
- try {
184
- plugin.install(sandboxedApi, options);
185
- } catch (error) {
186
- console.error(`[WuPlugin] Error installing "${plugin.name}":`, error);
187
- throw error;
188
- }
189
- }
190
-
191
- // Registrar hooks del plugin con protección
192
- this.availableHooks.forEach(hookName => {
193
- if (typeof plugin[hookName] === 'function') {
194
- // Wrap el hook con timeout y try-catch
195
- const wrappedHook = this._wrapHook(plugin[hookName].bind(plugin), plugin.name, hookName);
196
- this.registerHook(hookName, wrappedHook);
197
- }
198
- });
199
-
200
- // Guardar plugin
201
- this.plugins.set(plugin.name, {
202
- plugin,
203
- options,
204
- permissions,
205
- sandboxedApi,
206
- installedAt: Date.now()
207
- });
208
-
209
- logger.debug(`[WuPlugin] ✅ Plugin "${plugin.name}" installed (permissions: ${permissions.join(', ')})`);
210
- }
211
-
212
- /**
213
- * 🔐 WRAP HOOK: Envolver hook con timeout y error handling
214
- */
215
- _wrapHook(hookFn, pluginName, hookName) {
216
- return async (context) => {
217
- const timeoutPromise = new Promise((_, reject) => {
218
- setTimeout(() => {
219
- reject(new Error(`Plugin "${pluginName}" hook "${hookName}" timed out after ${this.hookTimeout}ms`));
220
- }, this.hookTimeout);
221
- });
222
-
223
- try {
224
- // Race entre el hook y el timeout
225
- return await Promise.race([
226
- hookFn(context),
227
- timeoutPromise
228
- ]);
229
- } catch (error) {
230
- console.error(`[WuPlugin] Error in ${pluginName}.${hookName}:`, error);
231
- // No propagar error para no romper otros plugins
232
- return undefined;
233
- }
234
- };
235
- }
236
-
237
- /**
238
- * 🪝 REGISTER HOOK
239
- */
240
- registerHook(hookName, callback) {
241
- if (!this.hooks.has(hookName)) {
242
- logger.warn(`[WuPlugin] Unknown hook: ${hookName}`);
243
- return;
244
- }
245
- this.hooks.get(hookName).push(callback);
246
- }
247
-
248
- /**
249
- * 🎯 CALL HOOK
250
- */
251
- async callHook(hookName, context) {
252
- const callbacks = this.hooks.get(hookName) || [];
253
-
254
- for (const callback of callbacks) {
255
- try {
256
- const result = await callback(context);
257
- if (result === false) {
258
- return false;
259
- }
260
- } catch (error) {
261
- console.error(`[WuPlugin] Error in hook ${hookName}:`, error);
262
- }
263
- }
264
-
265
- return true;
266
- }
267
-
268
- /**
269
- * 🗑️ UNINSTALL
270
- */
271
- uninstall(pluginName) {
272
- const pluginData = this.plugins.get(pluginName);
273
- if (!pluginData) {
274
- logger.warn(`[WuPlugin] Plugin "${pluginName}" not found`);
275
- return;
276
- }
277
-
278
- const { plugin, sandboxedApi } = pluginData;
279
-
280
- if (plugin.uninstall) {
281
- try {
282
- plugin.uninstall(sandboxedApi);
283
- } catch (error) {
284
- console.error(`[WuPlugin] Error uninstalling "${pluginName}":`, error);
285
- }
286
- }
287
-
288
- this.plugins.delete(pluginName);
289
- logger.debug(`[WuPlugin] ✅ Plugin "${pluginName}" uninstalled`);
290
- }
291
-
292
- /**
293
- * 📋 GET PLUGIN
294
- */
295
- getPlugin(pluginName) {
296
- return this.plugins.get(pluginName)?.plugin;
297
- }
298
-
299
- /**
300
- * 📊 GET STATS
301
- */
302
- getStats() {
303
- return {
304
- totalPlugins: this.plugins.size,
305
- plugins: Array.from(this.plugins.entries()).map(([name, data]) => ({
306
- name,
307
- permissions: data.permissions,
308
- installedAt: data.installedAt
309
- })),
310
- hooks: Array.from(this.hooks.entries()).map(([name, callbacks]) => ({
311
- name,
312
- callbacks: callbacks.length
313
- }))
314
- };
315
- }
316
-
317
- /**
318
- * 🧹 CLEANUP
319
- */
320
- cleanup() {
321
- for (const [name] of this.plugins) {
322
- this.uninstall(name);
323
- }
324
- }
325
- }
326
-
327
- /**
328
- * 📦 PLUGIN HELPER: Helper para crear plugins
329
- * @param {Object} config - Configuración del plugin
330
- * @param {string} config.name - Nombre del plugin
331
- * @param {Array} config.permissions - Permisos requeridos
332
- */
333
- export const createPlugin = (config) => {
334
- return {
335
- name: config.name,
336
- permissions: config.permissions || ['events'],
337
- install: config.install,
338
- uninstall: config.uninstall,
339
- beforeInit: config.beforeInit,
340
- afterInit: config.afterInit,
341
- beforeMount: config.beforeMount,
342
- afterMount: config.afterMount,
343
- beforeUnmount: config.beforeUnmount,
344
- afterUnmount: config.afterUnmount,
345
- onError: config.onError,
346
- onDestroy: config.onDestroy
347
- };
348
- };
1
+ /**
2
+ * 🔌 WU-PLUGIN: SECURE PLUGIN SYSTEM
3
+ *
4
+ * Sistema de plugins con sandboxing de seguridad
5
+ * - Plugin lifecycle (install, beforeMount, afterMount, etc.)
6
+ * - Sandboxed API (plugins no tienen acceso completo al core)
7
+ * - Permission system
8
+ * - Timeout protection
9
+ */
10
+ import { logger } from './wu-logger.js';
11
+
12
+
13
+ export class WuPluginSystem {
14
+ constructor(core) {
15
+ this._core = core; // Privado - no expuesto a plugins
16
+ this.plugins = new Map();
17
+ this.hooks = new Map();
18
+
19
+ // Hooks disponibles
20
+ this.availableHooks = [
21
+ 'beforeInit', 'afterInit',
22
+ 'beforeMount', 'afterMount',
23
+ 'beforeUnmount', 'afterUnmount',
24
+ 'onError', 'onDestroy'
25
+ ];
26
+
27
+ // 🔐 Permisos disponibles
28
+ this.availablePermissions = [
29
+ 'mount', // Puede montar/desmontar apps
30
+ 'events', // Puede emitir/escuchar eventos
31
+ 'store', // Puede leer/escribir store
32
+ 'apps', // Puede ver lista de apps
33
+ 'config', // Puede modificar configuración
34
+ 'unsafe' // Acceso completo (peligroso)
35
+ ];
36
+
37
+ // 🔐 Timeout para hooks (evita que plugins bloqueen)
38
+ this.hookTimeout = 5000; // 5 segundos
39
+
40
+ this.availableHooks.forEach(hook => {
41
+ this.hooks.set(hook, []);
42
+ });
43
+ }
44
+
45
+ /**
46
+ * 🔐 CREATE SANDBOXED API: Crea API limitada para el plugin
47
+ * @param {Array} permissions - Permisos del plugin
48
+ * @returns {Object} API sandboxeada
49
+ */
50
+ _createSandboxedApi(permissions) {
51
+ const api = {
52
+ // Info básica siempre disponible
53
+ version: this._core.version,
54
+ info: this._core.info,
55
+
56
+ // 📊 Métodos de solo lectura
57
+ getAppInfo: (appName) => {
58
+ const mounted = this._core.mounted.get(appName);
59
+ if (!mounted) return null;
60
+ return {
61
+ name: appName,
62
+ state: mounted.state,
63
+ timestamp: mounted.timestamp
64
+ };
65
+ },
66
+
67
+ getMountedApps: () => {
68
+ return Array.from(this._core.mounted.keys());
69
+ },
70
+
71
+ getStats: () => this._core.getStats()
72
+ };
73
+
74
+ // 🔐 Agregar métodos según permisos
75
+ if (permissions.includes('events') || permissions.includes('unsafe')) {
76
+ api.emit = (event, data) => this._core.eventBus.emit(event, data, { appName: 'plugin' });
77
+ api.on = (event, cb) => this._core.eventBus.on(event, cb);
78
+ api.off = (event, cb) => this._core.eventBus.off(event, cb);
79
+ }
80
+
81
+ if (permissions.includes('store') || permissions.includes('unsafe')) {
82
+ api.getState = (path) => this._core.store.get(path);
83
+ api.setState = (path, value) => this._core.store.set(path, value);
84
+ }
85
+
86
+ if (permissions.includes('mount') || permissions.includes('unsafe')) {
87
+ api.mount = (appName, container) => this._core.mount(appName, container);
88
+ api.unmount = (appName) => this._core.unmount(appName);
89
+ }
90
+
91
+ if (permissions.includes('config') || permissions.includes('unsafe')) {
92
+ api.configure = (config) => {
93
+ // Solo permitir configuración segura
94
+ const safeKeys = ['debug', 'logLevel'];
95
+ const safeConfig = {};
96
+ for (const key of safeKeys) {
97
+ if (key in config) safeConfig[key] = config[key];
98
+ }
99
+ Object.assign(this._core, safeConfig);
100
+ };
101
+ }
102
+
103
+ // 🚨 Acceso completo solo con permiso 'unsafe'
104
+ if (permissions.includes('unsafe')) {
105
+ api._unsafeCore = this._core;
106
+ logger.warn('[WuPlugin] ⚠️ Plugin has unsafe access to core!');
107
+ }
108
+
109
+ // Congelar API para evitar modificaciones
110
+ return Object.freeze(api);
111
+ }
112
+
113
+ /**
114
+ * 🔐 VALIDATE PLUGIN: Validar estructura del plugin
115
+ * @param {Object} plugin
116
+ * @returns {boolean}
117
+ */
118
+ _validatePlugin(plugin) {
119
+ if (!plugin || typeof plugin !== 'object') {
120
+ throw new Error('[WuPlugin] Invalid plugin: must be an object');
121
+ }
122
+
123
+ if (!plugin.name || typeof plugin.name !== 'string') {
124
+ throw new Error('[WuPlugin] Invalid plugin: must have a name (string)');
125
+ }
126
+
127
+ if (plugin.name.length > 50) {
128
+ throw new Error('[WuPlugin] Invalid plugin: name too long (max 50 chars)');
129
+ }
130
+
131
+ // Validar que los hooks sean funciones
132
+ for (const hookName of this.availableHooks) {
133
+ if (plugin[hookName] && typeof plugin[hookName] !== 'function') {
134
+ throw new Error(`[WuPlugin] Invalid plugin: ${hookName} must be a function`);
135
+ }
136
+ }
137
+
138
+ // Validar permisos
139
+ if (plugin.permissions) {
140
+ if (!Array.isArray(plugin.permissions)) {
141
+ throw new Error('[WuPlugin] Invalid plugin: permissions must be an array');
142
+ }
143
+
144
+ for (const perm of plugin.permissions) {
145
+ if (!this.availablePermissions.includes(perm)) {
146
+ throw new Error(`[WuPlugin] Invalid permission: ${perm}`);
147
+ }
148
+ }
149
+ }
150
+
151
+ return true;
152
+ }
153
+
154
+ /**
155
+ * 📦 USE: Instalar plugin con sandboxing
156
+ * @param {Object|Function} plugin - Plugin o factory function
157
+ * @param {Object} options - Opciones del plugin
158
+ */
159
+ use(plugin, options = {}) {
160
+ // Si es una función, ejecutarla para obtener el plugin
161
+ // Nota: factory functions NO reciben acceso al core
162
+ if (typeof plugin === 'function') {
163
+ plugin = plugin(options);
164
+ }
165
+
166
+ // Validar plugin
167
+ this._validatePlugin(plugin);
168
+
169
+ // Verificar si ya está instalado
170
+ if (this.plugins.has(plugin.name)) {
171
+ logger.warn(`[WuPlugin] Plugin "${plugin.name}" already installed`);
172
+ return;
173
+ }
174
+
175
+ // Determinar permisos (por defecto: solo eventos)
176
+ const permissions = plugin.permissions || ['events'];
177
+
178
+ // 🔐 Crear API sandboxeada
179
+ const sandboxedApi = this._createSandboxedApi(permissions);
180
+
181
+ // Ejecutar install del plugin con API sandboxeada
182
+ if (plugin.install) {
183
+ try {
184
+ plugin.install(sandboxedApi, options);
185
+ } catch (error) {
186
+ console.error(`[WuPlugin] Error installing "${plugin.name}":`, error);
187
+ throw error;
188
+ }
189
+ }
190
+
191
+ // Registrar hooks del plugin con protección
192
+ this.availableHooks.forEach(hookName => {
193
+ if (typeof plugin[hookName] === 'function') {
194
+ // Wrap el hook con timeout y try-catch
195
+ const wrappedHook = this._wrapHook(plugin[hookName].bind(plugin), plugin.name, hookName);
196
+ this.registerHook(hookName, wrappedHook);
197
+ }
198
+ });
199
+
200
+ // Guardar plugin
201
+ this.plugins.set(plugin.name, {
202
+ plugin,
203
+ options,
204
+ permissions,
205
+ sandboxedApi,
206
+ installedAt: Date.now()
207
+ });
208
+
209
+ logger.debug(`[WuPlugin] ✅ Plugin "${plugin.name}" installed (permissions: ${permissions.join(', ')})`);
210
+ }
211
+
212
+ /**
213
+ * 🔐 WRAP HOOK: Envolver hook con timeout y error handling
214
+ */
215
+ _wrapHook(hookFn, pluginName, hookName) {
216
+ return async (context) => {
217
+ const timeoutPromise = new Promise((_, reject) => {
218
+ setTimeout(() => {
219
+ reject(new Error(`Plugin "${pluginName}" hook "${hookName}" timed out after ${this.hookTimeout}ms`));
220
+ }, this.hookTimeout);
221
+ });
222
+
223
+ try {
224
+ // Race entre el hook y el timeout
225
+ return await Promise.race([
226
+ hookFn(context),
227
+ timeoutPromise
228
+ ]);
229
+ } catch (error) {
230
+ console.error(`[WuPlugin] Error in ${pluginName}.${hookName}:`, error);
231
+ // No propagar error para no romper otros plugins
232
+ return undefined;
233
+ }
234
+ };
235
+ }
236
+
237
+ /**
238
+ * 🪝 REGISTER HOOK
239
+ */
240
+ registerHook(hookName, callback) {
241
+ if (!this.hooks.has(hookName)) {
242
+ logger.warn(`[WuPlugin] Unknown hook: ${hookName}`);
243
+ return;
244
+ }
245
+ this.hooks.get(hookName).push(callback);
246
+ }
247
+
248
+ /**
249
+ * 🎯 CALL HOOK
250
+ */
251
+ async callHook(hookName, context) {
252
+ const callbacks = this.hooks.get(hookName) || [];
253
+
254
+ for (const callback of callbacks) {
255
+ try {
256
+ const result = await callback(context);
257
+ if (result === false) {
258
+ return false;
259
+ }
260
+ } catch (error) {
261
+ console.error(`[WuPlugin] Error in hook ${hookName}:`, error);
262
+ }
263
+ }
264
+
265
+ return true;
266
+ }
267
+
268
+ /**
269
+ * 🗑️ UNINSTALL
270
+ */
271
+ uninstall(pluginName) {
272
+ const pluginData = this.plugins.get(pluginName);
273
+ if (!pluginData) {
274
+ logger.warn(`[WuPlugin] Plugin "${pluginName}" not found`);
275
+ return;
276
+ }
277
+
278
+ const { plugin, sandboxedApi } = pluginData;
279
+
280
+ if (plugin.uninstall) {
281
+ try {
282
+ plugin.uninstall(sandboxedApi);
283
+ } catch (error) {
284
+ console.error(`[WuPlugin] Error uninstalling "${pluginName}":`, error);
285
+ }
286
+ }
287
+
288
+ this.plugins.delete(pluginName);
289
+ logger.debug(`[WuPlugin] ✅ Plugin "${pluginName}" uninstalled`);
290
+ }
291
+
292
+ /**
293
+ * 📋 GET PLUGIN
294
+ */
295
+ getPlugin(pluginName) {
296
+ return this.plugins.get(pluginName)?.plugin;
297
+ }
298
+
299
+ /**
300
+ * 📊 GET STATS
301
+ */
302
+ getStats() {
303
+ return {
304
+ totalPlugins: this.plugins.size,
305
+ plugins: Array.from(this.plugins.entries()).map(([name, data]) => ({
306
+ name,
307
+ permissions: data.permissions,
308
+ installedAt: data.installedAt
309
+ })),
310
+ hooks: Array.from(this.hooks.entries()).map(([name, callbacks]) => ({
311
+ name,
312
+ callbacks: callbacks.length
313
+ }))
314
+ };
315
+ }
316
+
317
+ /**
318
+ * 🧹 CLEANUP
319
+ */
320
+ cleanup() {
321
+ for (const [name] of this.plugins) {
322
+ this.uninstall(name);
323
+ }
324
+ }
325
+ }
326
+
327
+ /**
328
+ * 📦 PLUGIN HELPER: Helper para crear plugins
329
+ * @param {Object} config - Configuración del plugin
330
+ * @param {string} config.name - Nombre del plugin
331
+ * @param {Array} config.permissions - Permisos requeridos
332
+ */
333
+ export const createPlugin = (config) => {
334
+ return {
335
+ name: config.name,
336
+ permissions: config.permissions || ['events'],
337
+ install: config.install,
338
+ uninstall: config.uninstall,
339
+ beforeInit: config.beforeInit,
340
+ afterInit: config.afterInit,
341
+ beforeMount: config.beforeMount,
342
+ afterMount: config.afterMount,
343
+ beforeUnmount: config.beforeUnmount,
344
+ afterUnmount: config.afterUnmount,
345
+ onError: config.onError,
346
+ onDestroy: config.onDestroy
347
+ };
348
+ };