wu-framework 1.1.13 โ†’ 1.1.15

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.
@@ -1,3 +1,3 @@
1
1
  /*! wu-framework v1.1.8 | MIT License */
2
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});class e{constructor(){this.isDevelopment=this.detectEnvironment(),this.logLevel=this.isDevelopment?"warn":"error",this.levels={debug:0,info:1,warn:2,error:3,silent:4}}detectEnvironment(){return"localhost"===window.location.hostname||"127.0.0.1"===window.location.hostname||""!==window.location.port||"undefined"!=typeof process&&"development"===process.env?.NODE_ENV||new URLSearchParams(window.location.search).has("wu-debug")||!0===window.WU_DEBUG}setLevel(e){return this.logLevel=e,this}setDevelopment(e){return this.isDevelopment=e,this.logLevel=e?"debug":"error",this}shouldLog(e){return this.levels[e]>=this.levels[this.logLevel]}debug(...e){this.shouldLog("debug")&&console.log(...e)}info(...e){this.shouldLog("info")&&console.info(...e)}warn(...e){this.shouldLog("warn")&&console.warn(...e)}error(...e){this.shouldLog("error")&&console.error(...e)}wu(e,...t){if(this.shouldLog(e)){console["debug"===e?"log":e]("[Wu]",...t)}}wuDebug(...e){this.wu("debug",...e)}wuInfo(...e){this.wu("info",...e)}wuWarn(...e){this.wu("warn",...e)}wuError(...e){this.wu("error",...e)}}const t=new e;function s(){t.setLevel("silent")}function r(){t.setLevel("debug")}var i=Object.freeze({__proto__:null,WuLogger:e,enableAllLogs:r,logger:t,silenceAllLogs:s});class n{constructor(){this.cache=new Map,this.loadingPromises=new Map,t.debug("[WuLoader] ๐Ÿ“ฆ Dynamic loader initialized")}async loadApp(e,s){const r=`${e}/${s?.entry||"index.js"}`;t.debug(`[WuLoader] ๐Ÿ“ฅ Loading app from: ${r}`);try{if(this.cache.has(r))return t.debug(`[WuLoader] โšก Cache hit for: ${r}`),this.cache.get(r);if(this.loadingPromises.has(r))return t.debug(`[WuLoader] โณ Loading in progress for: ${r}`),await this.loadingPromises.get(r);const e=this.fetchCode(r);this.loadingPromises.set(r,e);const s=await e;return this.loadingPromises.delete(r),this.cache.set(r,s),t.debug(`[WuLoader] โœ… App loaded successfully: ${r}`),s}catch(e){throw this.loadingPromises.delete(r),console.error(`[WuLoader] โŒ Failed to load app: ${r}`,e),new Error(`Failed to load app from ${r}: ${e.message}`)}}async loadComponent(e,s){let r=s;r.startsWith("./")&&(r=r.substring(2)),r.endsWith(".js")||r.endsWith(".jsx")||(r+=".js");const i=`${e}/${r}`;t.debug(`[WuLoader] ๐Ÿงฉ Loading component from: ${i}`);try{const e=await this.loadCode(i),r=new Function("require","module","exports",`\n ${e}\n return typeof module.exports === 'function' ? module.exports :\n typeof module.exports === 'object' && module.exports.default ? module.exports.default :\n exports.default || exports;\n `),n={exports:{}},o=r(e=>(t.warn(`[WuLoader] Component ${s} requires ${e} - not supported yet`),{}),n,n.exports);return t.debug(`[WuLoader] โœ… Component loaded: ${s}`),o}catch(e){throw console.error(`[WuLoader] โŒ Failed to load component: ${s}`,e),new Error(`Failed to load component ${s}: ${e.message}`)}}async loadCode(e){if(this.cache.has(e))return this.cache.get(e);if(this.loadingPromises.has(e))return await this.loadingPromises.get(e);const t=this.fetchCode(e);this.loadingPromises.set(e,t);try{const s=await t;return this.loadingPromises.delete(e),this.cache.set(e,s),s}catch(t){throw this.loadingPromises.delete(e),t}}async fetchCode(e){const t=await fetch(e,{cache:"no-cache",headers:{Accept:"application/javascript, text/javascript, */*"}});if(!t.ok)throw new Error(`HTTP ${t.status}: ${t.statusText}`);const s=await t.text();if(!s.trim())throw new Error("Empty response");return s}async preload(e){t.debug(`[WuLoader] ๐Ÿš€ Preloading ${e.length} apps...`);const s=e.map(async e=>{try{await this.loadApp(e.url,e.manifest),t.debug(`[WuLoader] โœ… Preloaded: ${e.name}`)}catch(s){t.warn(`[WuLoader] โš ๏ธ Failed to preload ${e.name}:`,s.message)}});await Promise.allSettled(s),t.debug("[WuLoader] ๐ŸŽ‰ Preload completed")}async isAvailable(e){try{return(await fetch(e,{method:"HEAD"})).ok}catch{return!1}}async resolveDependencies(e,s){const r=new Map;for(const i of e||[]){const[e,n]=i.split(".");if(!e||!n){t.warn(`[WuLoader] Invalid import format: ${i}`);continue}const o=s.get(e);if(!o){t.warn(`[WuLoader] Import app not found: ${e}`);continue}const a=o.manifest,c=a?.wu?.exports?.[n];if(c)try{const e=await this.loadComponent(o.url,c);r.set(i,e),t.debug(`[WuLoader] โœ… Resolved dependency: ${i}`)}catch(e){console.error(`[WuLoader] โŒ Failed to resolve: ${i}`,e)}else t.warn(`[WuLoader] Export not found: ${i}`)}return r}clearCache(e){if(e){const s=new RegExp(e);for(const[e]of this.cache)s.test(e)&&(this.cache.delete(e),t.debug(`[WuLoader] ๐Ÿ—‘๏ธ Cleared cache for: ${e}`))}else this.cache.clear(),t.debug("[WuLoader] ๐Ÿ—‘๏ธ Cache cleared completely")}getStats(){return{cached:this.cache.size,loading:this.loadingPromises.size,cacheKeys:Array.from(this.cache.keys())}}}class o{constructor(){this.styleObserver=null,this.fullyIsolatedApps=new Map,this.config={autoShareLibraries:["element-plus","vue-flow","@vue-flow","vueuse","@vueuse","normalize.css","reset.css"],sharePatterns:[/\/node_modules\//,/\/@vite\/client/,/\/dist\/index\.css$/,/\/dist\/style\.css$/],mode:"auto",cacheEnabled:!0},t.debug("[WuStyleBridge] ๐ŸŽจ Style sharing system initialized")}registerFullyIsolatedApp(e,s){this.fullyIsolatedApps.set(e,s),t.debug(`[WuStyleBridge] ๐Ÿ›ก๏ธ Registered fully-isolated app: ${e} (${s})`)}isStyleFromFullyIsolatedApp(e){let t="";if("string"==typeof e?t=e:e&&"function"==typeof e.getAttribute?t=e.getAttribute("data-vite-dev-id")||e.href||"":e&&(e.href?t=e.href:e.viteId?t=e.viteId:e.element&&("function"==typeof e.element.getAttribute?t=e.element.getAttribute("data-vite-dev-id")||e.element.href||"":e.element.href&&(t=e.element.href))),!t||""===t.trim())return!1;const s=t.replace(/\\/g,"/").toLowerCase();for(const[e,t]of this.fullyIsolatedApps.entries()){const r=t.replace(/\\/g,"/").toLowerCase(),i=e.toLowerCase();if(r&&s.includes(r))return!0;if(new RegExp(`[/\\\\]${i}[/\\\\]`,"i").test(s))return!0}return!1}detectDocumentStyles(){const e=[];document.querySelectorAll('link[rel="stylesheet"]').forEach(t=>{this.isStyleFromFullyIsolatedApp(t)||e.push({type:"link",href:t.href,element:t,library:this.extractLibraryName(t.href)})});return document.querySelectorAll("style").forEach((s,r)=>{if("true"===s.getAttribute("data-wu-shared"))return;const i=s.getAttribute("data-vite-dev-id"),n=s.textContent;this.isStyleFromFullyIsolatedApp(s)||i&&this.isStyleFromFullyIsolatedApp(i)?t.debug(`[WuStyleBridge] ๐Ÿ›ก๏ธ Filtered out style from fully-isolated app: ${i||"unknown"}`):n&&n.trim().length>0&&e.push({type:"inline",content:n,element:s,viteId:i,library:this.extractLibraryName(i||""),index:r})}),document.adoptedStyleSheets&&document.adoptedStyleSheets.length>0&&document.adoptedStyleSheets.forEach((t,s)=>{e.push({type:"adoptedStyleSheet",sheet:t,index:s})}),t.debug(`[WuStyleBridge] ๐Ÿ” Detected ${e.length} shareable styles`),e}shouldShareStyle(e){if(!e)return!1;if("all"===this.config.mode)return!0;for(const t of this.config.sharePatterns)if(t.test(e))return!0;for(const t of this.config.autoShareLibraries)if(e.includes(t))return!0;return!1}extractLibraryName(e){if(!e)return null;const t=e.match(/\/node_modules\/(@?[^/]+\/[^/]+|@?[^/]+)/);if(t)return t[1];const s=e.match(/\/node_modules\/(.+?)\/.*?\.css/);return s?s[1]:null}async injectStylesIntoShadow(e,s,r){if(!e)return t.warn("[WuStyleBridge] โš ๏ธ No shadow root provided"),0;if("fully-isolated"===r)return t.debug(`[WuStyleBridge] ๐Ÿ›ก๏ธ Style mode "fully-isolated" for ${s}, skipping shared style injection`),0;if("isolated"===r)return t.debug(`[WuStyleBridge] ๐Ÿ”’ Style mode "isolated" for ${s}, using native Shadow DOM encapsulation (no external styles)`),0;t.debug(`[WuStyleBridge] ๐ŸŒ Style mode "shared" for ${s}, injecting all shared styles...`);const i=this.detectDocumentStyles();let n=0;for(const s of i)try{switch(s.type){case"link":await this.injectLinkStyle(e,s),n++;break;case"inline":this.injectInlineStyle(e,s),n++;break;case"adoptedStyleSheet":this.injectAdoptedStyleSheet(e,s),n++}}catch(e){t.warn("[WuStyleBridge] โš ๏ธ Failed to inject style:",e)}return t.debug(`[WuStyleBridge] โœ… Injected ${n} shared styles into ${s}`),n}async injectLinkStyle(e,s){if(e.querySelector(`link[href="${s.href}"]`))return void t.debug(`[WuStyleBridge] โญ๏ธ Style already exists: ${s.library||s.href}`);const r=document.createElement("link");r.rel="stylesheet",r.href=s.href,r.setAttribute("data-wu-shared","true"),r.setAttribute("data-wu-library",s.library||"unknown"),e.insertBefore(r,e.firstChild),t.debug(`[WuStyleBridge] ๐Ÿ”— Injected link: ${s.library||s.href}`)}injectInlineStyle(e,s){const r=s.viteId;if(r){if(e.querySelector(`style[data-wu-vite-id="${r}"]`))return void t.debug(`[WuStyleBridge] โญ๏ธ Inline style already exists: ${r}`)}const i=document.createElement("style");i.textContent=s.content,i.setAttribute("data-wu-shared","true"),i.setAttribute("data-wu-library",s.library||"unknown"),r&&i.setAttribute("data-wu-vite-id",r),e.insertBefore(i,e.firstChild),t.debug(`[WuStyleBridge] ๐Ÿ“ Injected inline style: ${s.library||r}`)}injectAdoptedStyleSheet(e,s){try{if(e.adoptedStyleSheets||(e.adoptedStyleSheets=[]),e.adoptedStyleSheets.includes(s.sheet))return void t.debug("[WuStyleBridge] โญ๏ธ Adopted stylesheet already exists");e.adoptedStyleSheets=[...e.adoptedStyleSheets,s.sheet],t.debug("[WuStyleBridge] ๐Ÿ“‹ Injected adopted stylesheet")}catch(e){t.warn("[WuStyleBridge] โš ๏ธ Failed to inject adopted stylesheet:",e)}}observeStyleChanges(e){this.styleObserver&&this.styleObserver.disconnect(),this.styleObserver=new MutationObserver(s=>{let r=!1;for(const e of s)if("childList"===e.type){if(Array.from(e.addedNodes).some(e=>"LINK"===e.tagName||"STYLE"===e.tagName)){r=!0;break}}r&&e&&(t.debug("[WuStyleBridge] ๐Ÿ”„ Style changes detected"),e())}),this.styleObserver.observe(document.head,{childList:!0,subtree:!0}),t.debug("[WuStyleBridge] ๐Ÿ‘€ Observing style changes")}configure(e){this.config={...this.config,...e},t.debug("[WuStyleBridge] โš™๏ธ Configuration updated:",this.config)}cleanup(){this.styleObserver&&(this.styleObserver.disconnect(),this.styleObserver=null),t.debug("[WuStyleBridge] ๐Ÿงน StyleBridge cleaned up")}getStats(){const e=this.detectDocumentStyles();return{totalStyles:e.length,linkStyles:e.filter(e=>"link"===e.type).length,inlineStyles:e.filter(e=>"inline"===e.type).length,adoptedStyleSheets:e.filter(e=>"adoptedStyleSheet"===e.type).length,libraries:[...new Set(e.map(e=>e.library).filter(Boolean))],config:this.config}}}class a{constructor(e){this.appName=e,this.proxy=null,this.fakeWindow=Object.create(null),this.active=!1,this.modifiedKeys=new Set,this._timers=new Set,this._intervals=new Set,this._rafs=new Set,this._eventListeners=[],this._container=null,this._shadowRoot=null,this._scopedDocument=null,this._scopedLocalStorage=null,this._scopedSessionStorage=null,this._patched=!1,this._originals=null}setContainer(e,t){this._container=e,this._shadowRoot=t}activate(){if(this.active)return this.proxy;const e=this;return this.proxy=new Proxy(window,{get(t,s){if(s in e.fakeWindow)return e.fakeWindow[s];const r=e._intercept(s,t);if(void 0!==r)return r;const i=t[s];return"function"!=typeof i||e._isConstructor(i)?i:i.bind(t)},set:(t,s,r)=>(e.fakeWindow[s]=r,e.modifiedKeys.add(s),!0),has:(t,s)=>s in e.fakeWindow||s in t,deleteProperty:(t,s)=>s in e.fakeWindow&&(delete e.fakeWindow[s],e.modifiedKeys.delete(s),!0)}),this.active=!0,t.wuDebug(`[ProxySandbox] Activated for ${this.appName}`),this.proxy}deactivate(){if(!this.active)return;this.unpatchWindow();for(const e of this._timers)try{clearTimeout(e)}catch{}for(const e of this._intervals)try{clearInterval(e)}catch{}for(const e of this._rafs)try{cancelAnimationFrame(e)}catch{}const e=this._timers.size+this._intervals.size+this._rafs.size;this._timers.clear(),this._intervals.clear(),this._rafs.clear();const s=this._eventListeners.length;for(const{target:e,event:t,handler:s,options:r}of this._eventListeners)try{e.removeEventListener(t,s,r)}catch{}this._eventListeners=[],this.fakeWindow=Object.create(null),this.modifiedKeys.clear(),this._scopedDocument=null,this._scopedLocalStorage=null,this._scopedSessionStorage=null,this.proxy=null,this.active=!1,(e>0||s>0)&&t.wuDebug(`[ProxySandbox] ${this.appName} cleanup: ${e} timers, ${s} listeners`),t.wuDebug(`[ProxySandbox] Deactivated for ${this.appName}`)}patchWindow(){if(this._patched)return;const e=this,s={setTimeout:window.setTimeout,clearTimeout:window.clearTimeout,setInterval:window.setInterval,clearInterval:window.clearInterval,requestAnimationFrame:window.requestAnimationFrame,cancelAnimationFrame:window.cancelAnimationFrame,addEventListener:window.addEventListener,removeEventListener:window.removeEventListener};this._originals=s,window.setTimeout=function(t,r,...i){const n=s.setTimeout.call(window,t,r,...i);return e._patched&&e._timers.add(n),n},window.clearTimeout=function(t){return e._timers.delete(t),s.clearTimeout.call(window,t)},window.setInterval=function(t,r,...i){const n=s.setInterval.call(window,t,r,...i);return e._patched&&e._intervals.add(n),n},window.clearInterval=function(t){return e._intervals.delete(t),s.clearInterval.call(window,t)},window.requestAnimationFrame=function(t){const r=s.requestAnimationFrame.call(window,t);return e._patched&&e._rafs.add(r),r},window.cancelAnimationFrame=function(t){return e._rafs.delete(t),s.cancelAnimationFrame.call(window,t)},window.addEventListener=function(t,r,i){return e._patched&&e._eventListeners.push({target:window,event:t,handler:r,options:i}),s.addEventListener.call(window,t,r,i)},window.removeEventListener=function(t,r,i){return e._eventListeners=e._eventListeners.filter(e=>!(e.target===window&&e.event===t&&e.handler===r)),s.removeEventListener.call(window,t,r,i)},this._patched=!0,t.wuDebug(`[ProxySandbox] Window patched for ${this.appName}`)}unpatchWindow(){this._patched&&this._originals&&(window.setTimeout=this._originals.setTimeout,window.clearTimeout=this._originals.clearTimeout,window.setInterval=this._originals.setInterval,window.clearInterval=this._originals.clearInterval,window.requestAnimationFrame=this._originals.requestAnimationFrame,window.cancelAnimationFrame=this._originals.cancelAnimationFrame,window.addEventListener=this._originals.addEventListener,window.removeEventListener=this._originals.removeEventListener,this._patched=!1,t.wuDebug(`[ProxySandbox] Window unpatched for ${this.appName}`))}_intercept(e,t){const s=this;switch(e){case"setTimeout":return function(e,r,...i){const n=t.setTimeout(e,r,...i);return s._timers.add(n),n};case"clearTimeout":return function(e){s._timers.delete(e),t.clearTimeout(e)};case"setInterval":return function(e,r,...i){const n=t.setInterval(e,r,...i);return s._intervals.add(n),n};case"clearInterval":return function(e){s._intervals.delete(e),t.clearInterval(e)};case"requestAnimationFrame":return function(e){const r=t.requestAnimationFrame(e);return s._rafs.add(r),r};case"cancelAnimationFrame":return function(e){s._rafs.delete(e),t.cancelAnimationFrame(e)};case"addEventListener":return function(e,r,i){s._eventListeners.push({target:t,event:e,handler:r,options:i}),t.addEventListener(e,r,i)};case"removeEventListener":return function(e,r,i){s._eventListeners=s._eventListeners.filter(s=>!(s.target===t&&s.event===e&&s.handler===r)),t.removeEventListener(e,r,i)};case"document":return this._getScopedDocument();case"localStorage":return this._getScopedStorage("local");case"sessionStorage":return this._getScopedStorage("session")}}_getScopedDocument(){if(this._scopedDocument)return this._scopedDocument;const e=this._shadowRoot||this._container;if(!e)return document;const t=this;return this._scopedDocument=new Proxy(document,{get(s,r){switch(r){case"querySelector":return t=>e.querySelector(t);case"querySelectorAll":return t=>e.querySelectorAll(t);case"getElementById":return t=>e.querySelector(`#${CSS.escape(t)}`);case"getElementsByClassName":return t=>e.querySelectorAll(`.${CSS.escape(t)}`);case"getElementsByTagName":return t=>e.querySelectorAll(t);case"addEventListener":return function(e,r,i){t._eventListeners.push({target:s,event:e,handler:r,options:i}),s.addEventListener(e,r,i)};case"removeEventListener":return function(e,r,i){t._eventListeners=t._eventListeners.filter(t=>!(t.target===s&&t.event===e&&t.handler===r)),s.removeEventListener(e,r,i)};default:{const e=s[r];return"function"==typeof e?e.bind(s):e}}}}),this._scopedDocument}_getScopedStorage(e){const t="local"===e?"_scopedLocalStorage":"_scopedSessionStorage";if(this[t])return this[t];const s="local"===e?window.localStorage:window.sessionStorage;if(!s)return s;const r=`wu_${this.appName}_`;return this[t]={getItem:e=>s.getItem(r+e),setItem(e,t){s.setItem(r+e,String(t))},removeItem(e){s.removeItem(r+e)},clear(){const e=[];for(let t=0;t<s.length;t++){const i=s.key(t);i&&i.startsWith(r)&&e.push(i)}e.forEach(e=>s.removeItem(e))},key(e){let t=0;for(let i=0;i<s.length;i++){const n=s.key(i);if(n&&n.startsWith(r)){if(t===e)return n.slice(r.length);t++}}return null},get length(){let e=0;for(let t=0;t<s.length;t++)s.key(t)?.startsWith(r)&&e++;return e}},this[t]}_isConstructor(e){try{return e.prototype&&e.prototype.constructor===e}catch{return!1}}getProxy(){return this.active?this.proxy:null}isActive(){return this.active}getStats(){return{appName:this.appName,active:this.active,patched:this._patched,modifiedKeys:Array.from(this.modifiedKeys),isolatedPropsCount:Object.keys(this.fakeWindow).length,trackedTimers:this._timers.size,trackedIntervals:this._intervals.size,trackedRAFs:this._rafs.size,trackedEventListeners:this._eventListeners.length,hasContainer:!!this._container,hasShadowRoot:!!this._shadowRoot}}}class c{constructor(e){this.appName=e,this.proxy=window,this.snapshot=new Map,this.modifiedKeys=new Set,this.active=!1,this._timers=new Set,this._intervals=new Set,this._rafs=new Set,this._eventListeners=[],this._patched=!1,this._originals=null}activate(){if(this.active)return this.proxy;this.snapshot.clear(),this.modifiedKeys.clear();for(const e in window)try{this.snapshot.set(e,window[e])}catch{}return this.active=!0,t.wuDebug(`[SnapshotSandbox] Activated for ${this.appName} (${this.snapshot.size} props)`),this.proxy}deactivate(){if(!this.active)return;this.unpatchWindow();for(const e of this._timers)try{clearTimeout(e)}catch{}for(const e of this._intervals)try{clearInterval(e)}catch{}for(const e of this._rafs)try{cancelAnimationFrame(e)}catch{}const e=this._timers.size+this._intervals.size+this._rafs.size;this._timers.clear(),this._intervals.clear(),this._rafs.clear();const s=this._eventListeners.length;for(const{target:e,event:t,handler:s,options:r}of this._eventListeners)try{e.removeEventListener(t,s,r)}catch{}this._eventListeners=[];let r=0,i=0;for(const e in window)try{const t=window[e],s=this.snapshot.get(e);if(t!==s)if(this.snapshot.has(e))window[e]=s,r++;else try{delete window[e],i++}catch{}}catch{}this.snapshot.clear(),this.modifiedKeys.clear(),this.active=!1,(e>0||s>0)&&t.wuDebug(`[SnapshotSandbox] ${this.appName} cleanup: ${e} timers, ${s} listeners, ${r} restored, ${i} deleted`),t.wuDebug(`[SnapshotSandbox] Deactivated for ${this.appName}`)}patchWindow(){if(this._patched)return;const e=this,s={setTimeout:window.setTimeout,clearTimeout:window.clearTimeout,setInterval:window.setInterval,clearInterval:window.clearInterval,requestAnimationFrame:window.requestAnimationFrame,cancelAnimationFrame:window.cancelAnimationFrame,addEventListener:window.addEventListener,removeEventListener:window.removeEventListener};this._originals=s,window.setTimeout=function(t,r,...i){const n=s.setTimeout.call(window,t,r,...i);return e._patched&&e._timers.add(n),n},window.clearTimeout=function(t){return e._timers.delete(t),s.clearTimeout.call(window,t)},window.setInterval=function(t,r,...i){const n=s.setInterval.call(window,t,r,...i);return e._patched&&e._intervals.add(n),n},window.clearInterval=function(t){return e._intervals.delete(t),s.clearInterval.call(window,t)},window.requestAnimationFrame=function(t){const r=s.requestAnimationFrame.call(window,t);return e._patched&&e._rafs.add(r),r},window.cancelAnimationFrame=function(t){return e._rafs.delete(t),s.cancelAnimationFrame.call(window,t)},window.addEventListener=function(t,r,i){return e._patched&&e._eventListeners.push({target:window,event:t,handler:r,options:i}),s.addEventListener.call(window,t,r,i)},window.removeEventListener=function(t,r,i){return e._eventListeners=e._eventListeners.filter(e=>!(e.target===window&&e.event===t&&e.handler===r)),s.removeEventListener.call(window,t,r,i)},this._patched=!0,t.wuDebug(`[SnapshotSandbox] Window patched for ${this.appName}`)}unpatchWindow(){this._patched&&this._originals&&(window.setTimeout=this._originals.setTimeout,window.clearTimeout=this._originals.clearTimeout,window.setInterval=this._originals.setInterval,window.clearInterval=this._originals.clearInterval,window.requestAnimationFrame=this._originals.requestAnimationFrame,window.cancelAnimationFrame=this._originals.cancelAnimationFrame,window.addEventListener=this._originals.addEventListener,window.removeEventListener=this._originals.removeEventListener,this._patched=!1,t.wuDebug(`[SnapshotSandbox] Window unpatched for ${this.appName}`))}getProxy(){return this.active?this.proxy:null}isActive(){return this.active}getStats(){return{appName:this.appName,active:this.active,patched:this._patched,snapshotSize:this.snapshot.size,trackedTimers:this._timers.size,trackedIntervals:this._intervals.size,trackedRAFs:this._rafs.size,trackedEventListeners:this._eventListeners.length}}}class l{constructor(){this.sandboxes=new Map,this.styleBridge=new o,this.jsSandboxes=new Map,this.sandboxStrategy=this.detectSandboxStrategy(),t.wuDebug(`Advanced isolation system initialized (strategy: ${this.sandboxStrategy})`)}detectSandboxStrategy(){if("undefined"!=typeof Proxy)try{return new Proxy({},{get:(e,t)=>e[t]}).test="value",t.wuDebug("Proxy available - using ProxySandbox strategy"),"proxy"}catch(e){return t.wuWarn("Proxy not working - falling back to SnapshotSandbox"),"snapshot"}return t.wuWarn("Proxy not available - using SnapshotSandbox strategy"),"snapshot"}create(e,s,r={}){t.wuDebug(`Creating sandbox for: ${e}`);try{if(!s.attachShadow)throw new Error("Shadow DOM not supported in this browser");let i;s.shadowRoot?(t.wuDebug(`Existing shadow root detected for ${e}, performing cleanup...`),s.shadowRoot.innerHTML="",i=s.shadowRoot,t.wuDebug(`Existing shadow root cleaned and reused for ${e}`)):(i=s.attachShadow({mode:"open",delegatesFocus:!0}),t.wuDebug(`New shadow root created for ${e}`));const n=document.createElement("div");n.id=`wu-app-${e}`,n.className="wu-app-root",n.setAttribute("data-wu-enhanced","true"),n.setAttribute("data-wu-timestamp",Date.now().toString());const o=document.createElement("style");o.textContent=this.generateSandboxStyles(e),i.appendChild(o),i.appendChild(n);const a=this.createAdvancedJSSandbox(e);a.setContainer&&a.setContainer(n,i);const c=a.activate(),l=r.styleMode||r.manifest?.styleMode,u={appName:e,shadowRoot:i,container:n,hostContainer:s,jsSandbox:a,jsProxy:c,styles:o,styleMode:l,manifest:r.manifest,created:Date.now(),sandbox_state:"stable",recovery_count:0};if("isolated"===l)t.wuDebug(`Style mode "isolated" for ${e}, using native Shadow DOM encapsulation`),u.stylesReady=Promise.resolve(0);else if("fully-isolated"===l){t.wuDebug(`Style mode "fully-isolated" detected for ${e}, using enhanced style injection`);const s=r.appUrl||(r.manifest?.name?`/${r.manifest.name}/`:`/${e}/`);this.styleBridge.registerFullyIsolatedApp(e,s),u.appUrl=s;const n=this;u.stylesReady=new Promise(r=>{let o=!1;const a=async()=>{const a=await n.injectOwnStylesToShadow(i,e,s);return a>0&&(t.wuDebug(`Injected ${a} own styles for ${e} (fully-isolated)`),o||(o=!0,r(a))),a};t.wuDebug(`Setting up style observer for ${e} (fully-isolated)`);const c=new MutationObserver(s=>{let r=0;for(const i of s)if("childList"===i.type)for(const s of i.addedNodes)if("STYLE"===s.nodeName||"LINK"===s.nodeName){r++;const i=s.getAttribute?s.getAttribute("data-vite-dev-id"):null;i&&i.toLowerCase().includes(e.toLowerCase())&&t.wuDebug(`New ${e} style detected: ${i.split("/").pop()}`)}r>0&&(t.wuDebug(`${r} new styles detected in head, checking for ${e}...`),a())});c.observe(document.head,{childList:!0,subtree:!0}),u.styleObserver=c,setTimeout(async()=>{await a();o||setTimeout(()=>{if(!o){t.wuWarn(`No own styles found for ${e} after timeout, using FALLBACK`);const s=n.injectAllStylesToShadow(i,e);t.wuDebug(`FALLBACK: Injected ${s} styles for ${e}`),o=!0,r(s)}},3e3)},50)})}else t.wuDebug(`Style mode "shared" for ${e}, injecting all shared styles...`),u.stylesReady=this.styleBridge.injectStylesIntoShadow(i,e,l).then(s=>(t.wuDebug(`Shared ${s} styles with ${e}`),this.styleBridge.observeStyleChanges(()=>{t.wuDebug(`Reinjecting styles for ${e} due to changes`),this.styleBridge.injectStylesIntoShadow(i,e,l).catch(e=>{t.wuWarn(`Failed to reinject styles: ${e}`)})}),s)).catch(e=>(t.wuWarn(`Failed to inject styles: ${e}`),0));return this.sandboxes.set(e,u),t.wuDebug(`Enhanced sandbox created for ${e}`),u}catch(r){if(t.wuError(`Failed to create sandbox for ${e}: ${r}`),r.message.includes("Shadow root cannot be created"))return this.createFallbackSandbox(e,s);throw r}}createFallbackSandbox(e,s){t.wuDebug(`Creating fallback sandbox for ${e}...`);try{s.shadowRoot&&(s.shadowRoot.innerHTML="");const r=document.createElement("div");r.id=`wu-app-${e}`,r.className="wu-app-root wu-fallback",r.style.cssText="\n width: 100%;\n height: 100%;\n isolation: isolate;\n contain: layout style paint;\n ",s.innerHTML="",s.appendChild(r);const i={appName:e,shadowRoot:null,container:r,hostContainer:s,styles:null,created:Date.now(),sandbox_state:"fallback_mode",recovery_count:1,fallback_mode:!0};return this.sandboxes.set(e,i),t.wuDebug(`Fallback sandbox created successfully for ${e}`),i}catch(e){throw t.wuError(`Fallback sandbox creation failed: ${e}`),e}}generateSandboxStyles(e){return`\n /* Wu Framework - Shadow DOM Isolation Styles */\n :host {\n display: block;\n width: 100%;\n height: 100%;\n box-sizing: border-box;\n contain: layout style paint;\n --wu-sandbox-active: true;\n --wu-isolation-state: stable;\n }\n\n .wu-app-root {\n width: 100%;\n height: 100%;\n box-sizing: border-box;\n isolation: isolate;\n position: relative;\n overflow: hidden;\n }\n\n /* Loading animation for sandbox initialization */\n .wu-app-root[data-wu-loading="true"] {\n background: linear-gradient(45deg,\n rgba(74, 144, 226, 0.1) 0%,\n rgba(80, 227, 194, 0.1) 100%);\n animation: sandboxPulse 2s ease-in-out infinite;\n }\n\n @keyframes sandboxPulse {\n 0%, 100% { opacity: 0.8; }\n 50% { opacity: 1; }\n }\n\n /* CSS reset for shadow DOM stability */\n * {\n box-sizing: border-box;\n }\n\n /* CSS custom properties for sandbox */\n :host {\n --wu-app-name: "${e}";\n --wu-isolation: true;\n --wu-creation-timestamp: ${Date.now()};\n }\n\n /* ๐Ÿ›ก๏ธ Debug mode enhancements */\n :host([wu-debug]) {\n border: 2px dashed #4a90e2;\n background: rgba(74, 144, 226, 0.05);\n box-shadow: 0 0 10px rgba(74, 144, 226, 0.3);\n }\n\n :host([wu-debug])::before {\n content: "Wu Framework: " attr(wu-app);\n position: absolute;\n top: 0;\n left: 0;\n background: linear-gradient(45deg, #4a90e2, #50e3c2);\n color: white;\n padding: 4px 8px;\n font-size: 11px;\n font-family: 'SF Mono', Monaco, 'Cascadia Code', 'Roboto Mono', Consolas, 'Courier New', monospace;\n z-index: 10000;\n border-radius: 0 0 4px 0;\n font-weight: 600;\n }\n\n /* Sandbox state indicators */\n :host([data-sandbox-state="stable"]) {\n --wu-isolation-state: stable;\n }\n\n :host([data-sandbox-state="healing"]) {\n --wu-dimensional-stability: healing;\n animation: sandboxHealing 1s ease-in-out infinite;\n }\n\n @keyframes sandboxHealing {\n 0%, 100% { filter: hue-rotate(0deg); }\n 50% { filter: hue-rotate(180deg); }\n }\n `}createAdvancedJSSandbox(e){let s;return"proxy"===this.sandboxStrategy?(s=new a(e),t.wuDebug(`Created ProxySandbox for ${e}`)):(s=new c(e),t.wuDebug(`Created SnapshotSandbox for ${e}`)),this.jsSandboxes.set(e,s),s}addStyles(e,s){const r=this.sandboxes.get(e);if(!r)return void t.wuWarn(`Sandbox not found for: ${e}`);const i=document.createElement("style");i.textContent=s,i.setAttribute("wu-custom-styles",""),r.shadowRoot.appendChild(i),t.wuDebug(`Custom styles added to ${e}`)}loadExternalStyles(e,s){const r=this.sandboxes.get(e);if(!r)return void t.wuWarn(`Sandbox not found for: ${e}`);const i=document.createElement("link");i.rel="stylesheet",i.href=s,i.setAttribute("wu-external-styles",""),r.shadowRoot.appendChild(i),t.wuDebug(`External styles loaded in ${e}: ${s}`)}setDebugMode(e,s=!0){const r=this.sandboxes.get(e);r?(s?(r.hostContainer.setAttribute("wu-debug",""),r.hostContainer.setAttribute("wu-app",e)):(r.hostContainer.removeAttribute("wu-debug"),r.hostContainer.removeAttribute("wu-app")),t.wuDebug(`Debug mode ${s?"enabled":"disabled"} for ${e}`)):t.wuWarn(`Sandbox not found for: ${e}`)}cleanup(e){if(!e)return;const{appName:s,shadowRoot:r,hostContainer:i,jsSandbox:n}=e;t.wuDebug(`Cleaning up sandbox for: ${s}`);try{n&&n.isActive()&&(n.deactivate(),t.wuDebug(`JS Sandbox deactivated for ${s}`)),this.cleanupEventListeners(e),r&&(r.innerHTML=""),i&&(i.removeAttribute("wu-debug"),i.removeAttribute("wu-app"),i.removeAttribute("wu-no-scroll")),this.sandboxes.delete(s),this.jsSandboxes.delete(s),t.wuDebug(`Sandbox cleaned up: ${s}`)}catch(e){t.wuError(`Error cleaning up sandbox ${s}: ${e}`)}}cleanupEventListeners(e){const{shadowRoot:t}=e;if(!t)return;t.querySelectorAll("*").forEach(e=>{if(e.cloneNode){const t=e.cloneNode(!0);e.parentNode?.replaceChild(t,e)}})}getSandboxInfo(e){const t=this.sandboxes.get(e);return t?{appName:t.appName,created:t.created,hasContainer:!!t.container,hasShadowRoot:!!t.shadowRoot,elementCount:t.shadowRoot?.children?.length||0,uptime:Date.now()-t.created}:null}getStats(){return{strategy:this.sandboxStrategy,total:this.sandboxes.size,sandboxes:Array.from(this.sandboxes.keys()),jsSandboxes:Array.from(this.jsSandboxes.keys()),details:Array.from(this.sandboxes.entries()).map(([e,t])=>({name:e,uptime:Date.now()-t.created,elements:t.shadowRoot?.children?.length||0,hasJsSandbox:!!t.jsSandbox,jsSandboxActive:t.jsSandbox?.isActive()||!1}))}}cleanupAll(){t.wuDebug(`Cleaning up all ${this.sandboxes.size} sandboxes...`);for(const[e,t]of this.sandboxes)this.cleanup(t);this.styleBridge&&this.styleBridge.cleanup(),t.wuDebug("All sandboxes cleaned up")}configureStyleSharing(e){this.styleBridge&&(this.styleBridge.configure(e),t.wuDebug("StyleBridge configured"))}getStyleStats(){return this.styleBridge?this.styleBridge.getStats():null}async reinjectStyles(e){const s=this.sandboxes.get(e);if(!s||!s.shadowRoot)return void t.wuWarn(`Cannot reinject styles for ${e}`);const r=s.styleMode;if("isolated"===r)return void t.wuDebug(`Skipping reinject for ${e} (isolated mode - app manages own styles)`);if("fully-isolated"===r){t.wuDebug(`Reinjecting OWN styles for ${e} (fully-isolated)...`);const r=s.appUrl||s.manifest?.name?`/${s.manifest.name}/`:`/${e}/`,i=await this.injectOwnStylesToShadow(s.shadowRoot,e,r);return void t.wuDebug(`Reinjected ${i} own styles for ${e}`)}t.wuDebug(`Reinjecting shared styles for ${e}...`);const i=await this.styleBridge.injectStylesIntoShadow(s.shadowRoot,e,r);t.wuDebug(`Reinjected ${i} shared styles`)}async injectOwnStylesToShadow(e,s,r){if(!e)return 0;let i=0;const n=document.querySelectorAll("style"),o=s.toLowerCase(),a=[new RegExp(`packages[/\\\\]${o}[/\\\\]src[/\\\\]`,"i")];t.wuDebug(`Searching own styles for ${s}, found ${n.length} style tags in head`);let c=0;for(const e of n){(e.getAttribute("data-vite-dev-id")||"").toLowerCase().includes(o)&&c++}c>0&&t.wuDebug(`Found ${c} styles potentially matching ${s}`);for(const r of n){const n=r.getAttribute("data-vite-dev-id")||"",o=n.replace(/\\/g,"/").toLowerCase();let c=!1;if(n)for(const e of a)if(e instanceof RegExp){if(e.test(n)){c=!0;break}}else if(o.includes(e.toLowerCase())){c=!0;break}if(c){if(!e.querySelector(`style[data-vite-dev-id="${n}"]`)){const o=r.cloneNode(!0);o.setAttribute("data-wu-injected","true"),e.insertBefore(o,e.firstChild),i++;const a=n.substring(n.lastIndexOf("/")+1)||n.substring(n.lastIndexOf("\\")+1);t.wuDebug(`Injected own style for ${s}: ${a}`)}}}return t.wuDebug(`Total own styles injected for ${s}: ${i}`),i}injectAllStylesToShadow(e,s){if(!e)return 0;let r=0;const i=s.toLowerCase(),n=document.querySelectorAll("style");for(const s of n){const n=s.getAttribute("data-vite-dev-id")||"";if(!n.toLowerCase().includes(i))continue;if(e.querySelector(`style[data-vite-dev-id="${n}"]`))continue;const o=s.cloneNode(!0);o.setAttribute("data-wu-fallback","true"),e.insertBefore(o,e.firstChild),r++;const a=n.split("/").pop()||n.split("\\").pop();t.wuDebug(`FALLBACK injected: ${a}`)}return t.wuDebug(`FALLBACK: Total ${r} styles injected for ${s}`),r}}class u{constructor(){this.cache=new Map,this.schemas=new Map,this.security={maxManifestSize:102400,maxNameLength:50,maxEntryLength:200,maxExports:100,maxImports:50,maxRoutes:100,dangerousPatterns:[/\.\./,/^\/etc\//,/^\/proc\//,/^file:\/\//,/javascript:/i,/data:/i,/<script/i,/on\w+\s*=/i],blockedDomains:["evil.com","malware.com"]},this.defineSchema()}defineSchema(){this.schemas.set("wu.json",{required:["name","entry"],optional:["wu"],wu:{optional:["exports","imports","routes","permissions"],exports:"object",imports:"array",routes:"array",permissions:"array"}})}async load(e){const s=`${e}/wu.json`;t.debug(`[WuManifest] ๐Ÿ“ฅ Loading manifest: ${s}`);try{if(this.cache.has(s))return t.debug(`[WuManifest] โšก Cache hit: ${s}`),this.cache.get(s);const r=await fetch(s,{cache:"no-cache",headers:{Accept:"application/json"}});if(!r.ok){if(404===r.status)return t.debug(`[WuManifest] ๐Ÿ“„ No manifest found, creating default for: ${e}`),this.createDefaultManifest(e);throw new Error(`HTTP ${r.status}: ${r.statusText}`)}const i=await r.text();if(i.length>this.security.maxManifestSize)throw new Error(`Manifest too large (${i.length} bytes, max ${this.security.maxManifestSize})`);let n;try{n=JSON.parse(i)}catch(e){throw new Error(`Invalid JSON in manifest: ${e.message}`)}const o=this.validate(n);return this.cache.set(s,o),t.debug(`[WuManifest] โœ… Manifest loaded: ${n.name}`),o}catch(t){console.error(`[WuManifest] โŒ Failed to load manifest: ${s}`,t);try{return this.createDefaultManifest(e)}catch(e){throw new Error(`Failed to load manifest from ${s}: ${t.message}`)}}}createDefaultManifest(e){const s=this.extractAppNameFromUrl(e),r={name:s,entry:"index.js",wu:{exports:{},imports:[],routes:[],permissions:[]}};return t.debug(`[WuManifest] ๐Ÿ”ง Created default manifest for: ${s}`),r}extractAppNameFromUrl(e){try{const t=new URL(e).pathname.split("/").filter(Boolean);return t[t.length-1]||"unknown-app"}catch{return e.replace(/[^a-zA-Z0-9-]/g,"")||"unknown-app"}}_sanitizeString(e){return"string"!=typeof e?"":e.replace(/[<>'"]/g,"").replace(/[\x00-\x1F\x7F]/g,"").trim()}_hasDangerousPatterns(e){return"string"==typeof e&&this.security.dangerousPatterns.some(t=>t.test(e))}_isUrlSafe(e){if("string"!=typeof e)return!1;if(this._hasDangerousPatterns(e))return!1;try{const t=new URL(e,"http://localhost");if(this.security.blockedDomains.some(e=>t.hostname.includes(e)))return!1}catch{if(this._hasDangerousPatterns(e))return!1}return!0}validate(e){const t=this.schemas.get("wu.json");if(!e||"object"!=typeof e||Array.isArray(e))throw new Error("Manifest must be a valid object");for(const s of t.required)if(!e[s])throw new Error(`Required field missing: ${s}`);if("string"!=typeof e.name)throw new Error("name must be a string");if(e.name.length>this.security.maxNameLength)throw new Error(`name too long (max ${this.security.maxNameLength} chars)`);if(this._hasDangerousPatterns(e.name))throw new Error("name contains dangerous patterns");if("string"!=typeof e.entry)throw new Error("entry must be a string");if(e.entry.length>this.security.maxEntryLength)throw new Error(`entry too long (max ${this.security.maxEntryLength} chars)`);if(!this._isUrlSafe(e.entry))throw new Error("entry contains dangerous patterns");if(e.wu){const t=e.wu;if(t.exports&&"object"!=typeof t.exports)throw new Error("wu.exports must be an object");if(t.exports&&Object.keys(t.exports).length>this.security.maxExports)throw new Error(`Too many exports (max ${this.security.maxExports})`);if(t.exports)for(const[e,s]of Object.entries(t.exports))if(!this._isUrlSafe(s))throw new Error(`Dangerous export path: ${e}`);if(t.imports&&!Array.isArray(t.imports))throw new Error("wu.imports must be an array");if(t.imports&&t.imports.length>this.security.maxImports)throw new Error(`Too many imports (max ${this.security.maxImports})`);if(t.routes&&!Array.isArray(t.routes))throw new Error("wu.routes must be an array");if(t.routes&&t.routes.length>this.security.maxRoutes)throw new Error(`Too many routes (max ${this.security.maxRoutes})`);if(t.permissions&&!Array.isArray(t.permissions))throw new Error("wu.permissions must be an array")}return this.normalize(e)}normalize(e){const s={name:e.name.trim(),entry:this.normalizeEntry(e.entry),wu:{exports:e.wu?.exports||{},imports:e.wu?.imports||[],routes:e.wu?.routes||[],permissions:e.wu?.permissions||[]}};if(e.styleMode&&(s.styleMode=e.styleMode),e.version&&(s.version=e.version),e.folder&&(s.folder=e.folder),s.wu.exports){const e={};for(const[t,r]of Object.entries(s.wu.exports))e[t]=this.normalizeComponentPath(r);s.wu.exports=e}return s.wu.imports=s.wu.imports.filter(e=>!("string"!=typeof e||!e.includes("."))||(t.warn(`[WuManifest] Invalid import format: ${e}`),!1)),s}normalizeEntry(e){if(!e)return"index.js";let t=e.trim();return t.startsWith("./")&&(t=t.substring(2)),t.includes(".")||(t+=".js"),t}normalizeComponentPath(e){if(!e)return"";let t=e.trim();return t.startsWith("./")&&(t=t.substring(2)),t.includes(".")||(t+=".js"),t}validateDependencies(e,t){const s={valid:[],invalid:[],missing:[]};for(const r of e){const[e,i]=r.split(".");if(!e||!i){s.invalid.push({import:r,reason:'Invalid format. Use "app.component"'});continue}const n=t.get(e);if(!n){s.missing.push({import:r,app:e,reason:"App not registered"});continue}const o=n.manifest,a=o?.wu?.exports?.[i];a?s.valid.push({import:r,app:e,component:i,path:a}):s.invalid.push({import:r,reason:`Component ${i} not exported by ${e}`})}return s}create(e,t={}){const s={name:e,entry:t.entry||"index.js",wu:{exports:t.exports||{},imports:t.imports||[],routes:t.routes||[],permissions:t.permissions||[]}};return this.normalize(s)}clearCache(e){if(e){const s=new RegExp(e);for(const[e]of this.cache)s.test(e)&&(this.cache.delete(e),t.debug(`[WuManifest] ๐Ÿ—‘๏ธ Cleared cache for: ${e}`))}else this.cache.clear(),t.debug("[WuManifest] ๐Ÿ—‘๏ธ Manifest cache cleared completely")}getStats(){return{cached:this.cache.size,schemas:this.schemas.size,cacheKeys:Array.from(this.cache.keys())}}}class d{constructor(e=256){this.bufferSize=this.nextPowerOfTwo(e),this.mask=this.bufferSize-1,this.buffer=new Array(this.bufferSize),this.cursor=0,this.state={},this.listeners=new Map,this.patternListeners=new Map,this.metrics={reads:0,writes:0,notifications:0};for(let e=0;e<this.bufferSize;e++)this.buffer[e]={path:null,value:null,timestamp:0}}get(e){return this.metrics.reads++,e?e.split(".").reduce((e,t)=>e?.[t],this.state):this.state}set(e,t){this.metrics.writes++;const s=this.cursor++,r=s&this.mask,i=this.buffer[r];return i.path=e,i.value=t,i.timestamp=performance.now(),this.updateState(e,t),queueMicrotask(()=>{this.notify(e,t),this.notifyPatterns(e,t)}),s}on(e,t){return e.includes("*")?(this.patternListeners.has(e)||this.patternListeners.set(e,new Set),this.patternListeners.get(e).add(t),()=>{const s=this.patternListeners.get(e);s&&(s.delete(t),0===s.size&&this.patternListeners.delete(e))}):(this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t),()=>{const s=this.listeners.get(e);s&&(s.delete(t),0===s.size&&this.listeners.delete(e))})}batch(e){const t=[];for(const[s,r]of Object.entries(e))t.push(this.set(s,r));return t}getMetrics(){return{...this.metrics,bufferUtilization:this.cursor%this.bufferSize/this.bufferSize,listenerCount:this.listeners.size+this.patternListeners.size}}nextPowerOfTwo(e){return Math.pow(2,Math.ceil(Math.log2(e)))}updateState(e,t){if(!e)return void(this.state=t);const s=e.split("."),r=s.pop();let i=this.state;for(const e of s)e in i&&"object"==typeof i[e]||(i[e]={}),i=i[e];i[r]=t}notify(e,t){this.metrics.notifications++;const s=this.listeners.get(e);s&&s.forEach(s=>{try{s(t,e)}catch(e){console.error("[WuStore] Listener error:",e)}});const r=e.split(".");for(let e=r.length-1;e>0;e--){const t=r.slice(0,e).join("."),s=this.listeners.get(t);if(s){const e=this.get(t);s.forEach(s=>{try{s(e,t)}catch(e){console.error("[WuStore] Parent listener error:",e)}})}}}notifyPatterns(e,t){for(const[s,r]of this.patternListeners)this.matchesPattern(e,s)&&r.forEach(s=>{try{s({path:e,value:t})}catch(e){console.error("[WuStore] Pattern listener error:",e)}})}matchesPattern(e,t){if("*"===t)return!0;const s=t.split(".").map(e=>"*"===e?"[^.]+":e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("\\.");return new RegExp(`^${s}$`).test(e)}clear(){this.state={},this.listeners.clear(),this.patternListeners.clear(),this.cursor=0;for(let e=0;e<this.bufferSize;e++)this.buffer[e].path=null,this.buffer[e].value=null,this.buffer[e].timestamp=0}getRecentEvents(e=10){const t=[];for(let s=Math.max(0,this.cursor-e);s<this.cursor&&t.length<e;s++){const e=s&this.mask,r=this.buffer[e];r.path&&t.push({path:r.path,value:r.value,timestamp:r.timestamp})}return t.reverse()}}const h=new d;class p{constructor(e,t,s){this.name=e,this.url=t.url,this.container=t.container,this.keepAlive=t.keepAlive||!1,this._wu=s,this._mounted=!1,this._autoInit=!1!==t.autoInit,this._autoInit&&this._registerApp()}_registerApp(){this._wu.apps.has(this.name)||(this._wu.apps.set(this.name,{name:this.name,url:this.url,keepAlive:this.keepAlive,status:"registered"}),t.debug(`๐Ÿ“ฆ App registered: ${this.name} at ${this.url}`))}async mount(e){const t=e||this.container;if(!t)throw new Error(`Container not specified for app: ${this.name}`);return this._wu.isInitialized||await this._wu.init({apps:[{name:this.name,url:this.url}]}),await this._wu.mount(this.name,t),this._mounted=!0,this}async unmount(e={}){return this._mounted||this._wu.isHidden(this.name)?(await this._wu.unmount(this.name,e),this._mounted=!this._wu.isHidden(this.name),this):(t.warn(`โš ๏ธ App ${this.name} is not mounted`),this)}async hide(){return this._mounted?(await this._wu.hide(this.name),this._mounted=!1,this):(t.warn(`โš ๏ธ App ${this.name} is not mounted`),this)}async show(){return this._wu.isHidden(this.name)?(await this._wu.show(this.name),this._mounted=!0,this):(t.warn(`โš ๏ธ App ${this.name} is not in keep-alive state`),this)}async remount(e){return await this.unmount({force:!0}),await this.mount(e),this}get isMounted(){return this._mounted&&this._wu.mounted?.has(this.name)}get isHidden(){return this._wu.isHidden(this.name)}get info(){return{name:this.name,url:this.url,container:this.container,mounted:this.isMounted,status:this._wu.apps.get(this.name)?.status||"unknown"}}async reload(){return t.debug(`๐Ÿ”„ Reloading app: ${this.name}`),await this.unmount(),this._wu.loader?.clearCache&&this._wu.loader.clearCache(this.name),this._wu.manifest?.clearCache&&this._wu.manifest.clearCache(this.name),await this.mount(),t.debug(`โœ… App reloaded: ${this.name}`),this}async verify(){const e=document.querySelector(this.container),t=null!==e?.shadowRoot,s=(e?.shadowRoot?.children?.length||0)>0;return{name:this.name,mounted:this.isMounted,container:{found:!!e,selector:this.container,hasShadowDOM:t,hasContent:s},wu:{registered:this._wu.apps.has(this.name),mountedInWu:this._wu.mounted?.has(this.name)}}}async start(e){return await this.mount(e)}async stop(){return await this.unmount()}async destroy(){await this.unmount({force:!0}),this._wu.apps.delete(this.name),this._mounted=!1,t.debug(`๐Ÿ—‘๏ธ App destroyed: ${this.name}`)}}class m{constructor(e={}){this.config={maxSize:e.maxSize||50,maxItems:e.maxItems||100,defaultTTL:e.defaultTTL||36e5,persistent:!1!==e.persistent,storage:e.storage||"memory"},this.rateLimiting={enabled:!1!==e.rateLimiting,maxOpsPerSecond:e.maxOpsPerSecond||100,windowMs:1e3,cooldownMs:e.cooldownMs||5e3,operations:[],inCooldown:!1,cooldownUntil:0},this.memoryCache=new Map,this.accessOrder=new Map,this.stats={hits:0,misses:0,sets:0,evictions:0,size:0,rateLimited:0}}_checkRateLimit(){if(!this.rateLimiting.enabled)return!0;const e=Date.now();if(this.rateLimiting.inCooldown){if(e<this.rateLimiting.cooldownUntil)return this.stats.rateLimited++,!1;this.rateLimiting.inCooldown=!1,this.rateLimiting.operations=[]}const s=e-this.rateLimiting.windowMs;return this.rateLimiting.operations=this.rateLimiting.operations.filter(e=>e>s),this.rateLimiting.operations.length>=this.rateLimiting.maxOpsPerSecond?(this.rateLimiting.inCooldown=!0,this.rateLimiting.cooldownUntil=e+this.rateLimiting.cooldownMs,this.stats.rateLimited++,t.warn(`[WuCache] ๐Ÿšซ Rate limit exceeded. Cooldown for ${this.rateLimiting.cooldownMs}ms`),!1):(this.rateLimiting.operations.push(e),!0)}getRateLimitStatus(){const e=Date.now();return{enabled:this.rateLimiting.enabled,inCooldown:this.rateLimiting.inCooldown,cooldownRemaining:this.rateLimiting.inCooldown?Math.max(0,this.rateLimiting.cooldownUntil-e):0,currentOps:this.rateLimiting.operations.length,maxOps:this.rateLimiting.maxOpsPerSecond,rateLimited:this.stats.rateLimited}}get(e){if(!this._checkRateLimit())return null;if(this.memoryCache.has(e)){const t=this.memoryCache.get(e);return this.isExpired(t)?(this.delete(e),this.stats.misses++,null):(this.accessOrder.set(e,Date.now()),this.stats.hits++,t.value)}if(this.config.persistent){const t=this.getFromStorage(e);if(t)return this.memoryCache.set(e,t),this.accessOrder.set(e,Date.now()),this.stats.hits++,t.value}return this.stats.misses++,null}set(e,s,r){if(!this._checkRateLimit())return!1;try{const i={key:e,value:s,timestamp:Date.now(),ttl:r||this.config.defaultTTL,size:this.estimateSize(s)};return!1===this.ensureSpace(i.size)?(t.warn(`[WuCache] โš ๏ธ Cannot cache item: ${e} (too large)`),!1):(this.memoryCache.set(e,i),this.accessOrder.set(e,Date.now()),this.config.persistent&&this.saveToStorage(e,i),this.stats.sets++,this.stats.size+=i.size,!0)}catch(e){return t.warn("[WuCache] โš ๏ธ Failed to set cache:",e),!1}}delete(e){const t=this.memoryCache.get(e);t&&(this.stats.size-=t.size),this.memoryCache.delete(e),this.accessOrder.delete(e),this.config.persistent&&this.deleteFromStorage(e)}clear(){this.memoryCache.clear(),this.accessOrder.clear(),this.stats.size=0,this.config.persistent&&this.clearStorage(),t.debug("[WuCache] ๐Ÿงน Cache cleared")}isExpired(e){return!!e.ttl&&Date.now()-e.timestamp>e.ttl}estimateSize(e){if("string"==typeof e)return 2*e.length;if("object"==typeof e)try{return 2*JSON.stringify(e).length}catch{return 1e3}return 100}ensureSpace(e){const s=1024*this.config.maxSize*1024;if(e>s)return t.warn(`[WuCache] โš ๏ธ Item size (${e}) exceeds max cache size (${s}). Skipping.`),!1;const r=this.config.maxItems+10;let i=0;for(;(this.stats.size+e>s||this.memoryCache.size>=this.config.maxItems)&&i<r;){if(i++,0===this.memoryCache.size){t.warn("[WuCache] โš ๏ธ Cache empty but still no space. Breaking loop.");break}let e=null,s=1/0;for(const[t,r]of this.accessOrder)r<s&&(s=r,e=t);if(!e)break;t.debug(`[WuCache] ๐Ÿ—‘๏ธ Evicting LRU entry: ${e}`),this.delete(e),this.stats.evictions++}return i>=r&&console.error(`[WuCache] ๐Ÿšจ Max eviction iterations reached (${r}). Possible infinite loop prevented.`),!0}getFromStorage(e){try{const t=this.getStorage().getItem(`wu_cache_${e}`);if(t)return JSON.parse(t)}catch(e){t.warn("[WuCache] โš ๏ธ Failed to get from storage:",e)}return null}saveToStorage(e,s){const r=this.getStorage();try{r.setItem(`wu_cache_${e}`,JSON.stringify(s))}catch(i){t.warn("[WuCache] โš ๏ธ Storage full, cleaning old entries"),this.cleanOldStorageEntries();try{r.setItem(`wu_cache_${e}`,JSON.stringify(s))}catch{t.warn("[WuCache] โš ๏ธ Failed to save to storage after cleanup")}}}deleteFromStorage(e){try{this.getStorage().removeItem(`wu_cache_${e}`)}catch(e){t.warn("[WuCache] โš ๏ธ Failed to delete from storage:",e)}}clearStorage(){try{const e=this.getStorage();Object.keys(e).forEach(t=>{t.startsWith("wu_cache_")&&e.removeItem(t)})}catch(e){t.warn("[WuCache] โš ๏ธ Failed to clear storage:",e)}}cleanOldStorageEntries(){try{const e=this.getStorage(),s=Object.keys(e),r=[];s.forEach(t=>{if(t.startsWith("wu_cache_"))try{const s=JSON.parse(e.getItem(t));r.push({key:t,timestamp:s.timestamp})}catch{}}),r.sort((e,t)=>e.timestamp-t.timestamp);const i=Math.ceil(.25*r.length);for(let t=0;t<i;t++)e.removeItem(r[t].key);t.debug(`[WuCache] ๐Ÿงน Cleaned ${i} old storage entries`)}catch(e){t.warn("[WuCache] โš ๏ธ Failed to clean old storage entries:",e)}}getStorage(){return"localStorage"===this.config.storage?window.localStorage:"sessionStorage"===this.config.storage?window.sessionStorage:{getItem:()=>null,setItem:()=>{},removeItem:()=>{},clear:()=>{}}}getStats(){const e=this.stats.hits+this.stats.misses>0?(this.stats.hits/(this.stats.hits+this.stats.misses)*100).toFixed(2):0;return{...this.stats,hitRate:`${e}%`,items:this.memoryCache.size,sizeMB:(this.stats.size/1024/1024).toFixed(2)}}configure(e){this.config={...this.config,...e}}}class g{constructor(){this.listeners=new Map,this.history=[],this.authorizedApps=new Map,this.trustedEvents=new Set(["wu:*","system:*"]),this.config={maxHistory:100,enableReplay:!0,enableWildcards:!0,logEvents:!1,strictMode:!1,validateOrigin:!0},this.stats={emitted:0,subscriptions:0,rejected:0}}registerApp(e,t={}){const s=t.token||this._generateToken();return this.authorizedApps.set(e,{token:s,permissions:t.permissions||["*"],registeredAt:Date.now()}),s}unregisterApp(e){this.authorizedApps.delete(e)}_validateOrigin(e,t,s){if(this._isSystemEvent(e))return!0;if(!this.config.strictMode)return!0;const r=this.authorizedApps.get(t);return!!r&&((!s||r.token===s)&&this._hasPermission(r.permissions,e))}_hasPermission(e,t){return!!e.includes("*")||e.some(e=>e===t||!!e.includes("*")&&this.matchesWildcard(t,e))}_isSystemEvent(e){return e.startsWith("wu:")||e.startsWith("system:")||e.startsWith("app:")}_generateToken(){return`wu_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}emit(e,s,r={}){const i=r.appName||"unknown";if(this.config.validateOrigin&&this.config.strictMode&&!this._validateOrigin(e,i,r.token))return this.stats.rejected++,t.warn(`[WuEventBus] ๐Ÿšซ Event rejected: ${e} from ${i} (unauthorized)`),!1;const n={name:e,data:s,timestamp:r.timestamp||Date.now(),appName:i,meta:r.meta||{},verified:this.authorizedApps.has(i)};this.config.enableReplay&&this.addToHistory(n),this.config.logEvents&&t.debug(`[WuEventBus] ๐Ÿ“ข ${e}`,s);const o=this.listeners.get(e);return o&&o.forEach(t=>{try{t(n)}catch(t){console.error(`[WuEventBus] โŒ Error in listener for ${e}:`,t)}}),this.config.enableWildcards&&this.notifyWildcardListeners(e,n),this.stats.emitted++,!0}on(e,t){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t),this.stats.subscriptions++,()=>this.off(e,t)}off(e,t){const s=this.listeners.get(e);s&&(s.delete(t),0===s.size&&this.listeners.delete(e),this.stats.subscriptions--)}once(e,t){const s=r=>{t(r),this.off(e,s)};return this.on(e,s)}notifyWildcardListeners(e,t){for(const[s,r]of this.listeners)this.matchesWildcard(e,s)&&r.forEach(e=>{try{e(t)}catch(e){console.error(`[WuEventBus] โŒ Error in wildcard listener for ${s}:`,e)}})}matchesWildcard(e,t){if(!t.includes("*"))return!1;const s=t.replace(/\./g,"\\.").replace(/\*/g,".*");return new RegExp(`^${s}$`).test(e)}addToHistory(e){this.history.push(e),this.history.length>this.config.maxHistory&&this.history.shift()}replay(e,t){this.history.filter(t=>e.includes("*")?this.matchesWildcard(t.name,e):t.name===e).forEach(e=>{try{t(e)}catch(e){console.error("[WuEventBus] โŒ Error replaying event:",e)}})}clearHistory(e){this.history=e?this.history.filter(t=>e.includes("*")?!this.matchesWildcard(t.name,e):t.name!==e):[]}getStats(){return{...this.stats,activeListeners:this.listeners.size,historySize:this.history.length,authorizedApps:this.authorizedApps.size,listenersByEvent:Array.from(this.listeners.entries()).map(([e,t])=>({event:e,listeners:t.size}))}}configure(e){this.config={...this.config,...e}}enableStrictMode(){this.config.strictMode=!0}disableStrictMode(){this.config.strictMode=!1}removeAll(){this.listeners.clear(),this.stats.subscriptions=0}}class f{constructor(){this.metrics=new Map,this.measurements=[],this.marks=new Map,this.config={enabled:!0,maxMeasurements:1e3},this.thresholds={mount:3e3,unmount:1e3,load:5e3},t.debug("[WuPerformance] โšก Framework performance monitoring initialized")}startMeasure(e,s="global"){const r=`${s}:${e}:start`;this.marks.set(r,performance.now()),t.debug(`[WuPerformance] ๐Ÿ“Š Measure started: ${r}`)}endMeasure(e,s="global"){const r=`${s}:${e}:start`,i=this.marks.get(r);if(!i)return 0;const n=performance.now()-i;return this.marks.delete(r),this.recordMeasurement({name:e,appName:s,duration:n,timestamp:Date.now(),type:"duration"}),this.checkThreshold(e,n)&&t.warn(`[WuPerformance] โš ๏ธ Threshold exceeded for ${e}: ${n.toFixed(2)}ms`),t.debug(`[WuPerformance] โน๏ธ Measure ended: ${r} (${n.toFixed(2)}ms)`),n}recordMeasurement(e){this.measurements.push(e),this.measurements.length>this.config.maxMeasurements&&this.measurements.shift(),this.metrics.has(e.appName)||this.metrics.set(e.appName,{appName:e.appName,measurements:[],stats:{}});this.metrics.get(e.appName).measurements.push(e),this.calculateStats(e.appName)}calculateStats(e){const t=this.metrics.get(e);if(!t)return;const s=t.measurements;if(0===s.length)return;const r={};s.forEach(e=>{r[e.name]||(r[e.name]=[]),r[e.name].push(e.duration)}),t.stats={},Object.entries(r).forEach(([e,s])=>{t.stats[e]={count:s.length,avg:s.reduce((e,t)=>e+t,0)/s.length,min:Math.min(...s),max:Math.max(...s),last:s[s.length-1]}})}checkThreshold(e,t){const s=this.thresholds[e];return s&&t>s}generateReport(){const e={timestamp:Date.now(),totalMeasurements:this.measurements.length,apps:{}};for(const[t,s]of this.metrics)e.apps[t]={measurementCount:s.measurements.length,stats:s.stats};return e}getMetrics(e){return this.metrics.get(e)||null}getAllMetrics(){const e={};for(const[t,s]of this.metrics)e[t]=s;return e}clearMetrics(e){e?(this.metrics.delete(e),this.measurements=this.measurements.filter(t=>t.appName!==e)):(this.metrics.clear(),this.measurements=[]),t.debug("[WuPerformance] ๐Ÿงน Metrics cleared"+(e?` for ${e}`:""))}configure(e){this.config={...this.config,...e},e.thresholds&&(this.thresholds={...this.thresholds,...e.thresholds})}}class w{constructor(e){this._core=e,this.plugins=new Map,this.hooks=new Map,this.availableHooks=["beforeInit","afterInit","beforeMount","afterMount","beforeUnmount","afterUnmount","onError","onDestroy"],this.availablePermissions=["mount","events","store","apps","config","unsafe"],this.hookTimeout=5e3,this.availableHooks.forEach(e=>{this.hooks.set(e,[])})}_createSandboxedApi(e){const s={version:this._core.version,info:this._core.info,getAppInfo:e=>{const t=this._core.mounted.get(e);return t?{name:e,state:t.state,timestamp:t.timestamp}:null},getMountedApps:()=>Array.from(this._core.mounted.keys()),getStats:()=>this._core.getStats()};return(e.includes("events")||e.includes("unsafe"))&&(s.emit=(e,t)=>this._core.eventBus.emit(e,t,{appName:"plugin"}),s.on=(e,t)=>this._core.eventBus.on(e,t),s.off=(e,t)=>this._core.eventBus.off(e,t)),(e.includes("store")||e.includes("unsafe"))&&(s.getState=e=>this._core.store.get(e),s.setState=(e,t)=>this._core.store.set(e,t)),(e.includes("mount")||e.includes("unsafe"))&&(s.mount=(e,t)=>this._core.mount(e,t),s.unmount=e=>this._core.unmount(e)),(e.includes("config")||e.includes("unsafe"))&&(s.configure=e=>{const t=["debug","logLevel"],s={};for(const r of t)r in e&&(s[r]=e[r]);Object.assign(this._core,s)}),e.includes("unsafe")&&(s._unsafeCore=this._core,t.warn("[WuPlugin] โš ๏ธ Plugin has unsafe access to core!")),Object.freeze(s)}_validatePlugin(e){if(!e||"object"!=typeof e)throw new Error("[WuPlugin] Invalid plugin: must be an object");if(!e.name||"string"!=typeof e.name)throw new Error("[WuPlugin] Invalid plugin: must have a name (string)");if(e.name.length>50)throw new Error("[WuPlugin] Invalid plugin: name too long (max 50 chars)");for(const t of this.availableHooks)if(e[t]&&"function"!=typeof e[t])throw new Error(`[WuPlugin] Invalid plugin: ${t} must be a function`);if(e.permissions){if(!Array.isArray(e.permissions))throw new Error("[WuPlugin] Invalid plugin: permissions must be an array");for(const t of e.permissions)if(!this.availablePermissions.includes(t))throw new Error(`[WuPlugin] Invalid permission: ${t}`)}return!0}use(e,s={}){if("function"==typeof e&&(e=e(s)),this._validatePlugin(e),this.plugins.has(e.name))return void t.warn(`[WuPlugin] Plugin "${e.name}" already installed`);const r=e.permissions||["events"],i=this._createSandboxedApi(r);if(e.install)try{e.install(i,s)}catch(t){throw console.error(`[WuPlugin] Error installing "${e.name}":`,t),t}this.availableHooks.forEach(t=>{if("function"==typeof e[t]){const s=this._wrapHook(e[t].bind(e),e.name,t);this.registerHook(t,s)}}),this.plugins.set(e.name,{plugin:e,options:s,permissions:r,sandboxedApi:i,installedAt:Date.now()}),t.debug(`[WuPlugin] โœ… Plugin "${e.name}" installed (permissions: ${r.join(", ")})`)}_wrapHook(e,t,s){return async r=>{const i=new Promise((e,r)=>{setTimeout(()=>{r(new Error(`Plugin "${t}" hook "${s}" timed out after ${this.hookTimeout}ms`))},this.hookTimeout)});try{return await Promise.race([e(r),i])}catch(e){return void console.error(`[WuPlugin] Error in ${t}.${s}:`,e)}}}registerHook(e,s){this.hooks.has(e)?this.hooks.get(e).push(s):t.warn(`[WuPlugin] Unknown hook: ${e}`)}async callHook(e,t){const s=this.hooks.get(e)||[];for(const r of s)try{if(!1===await r(t))return!1}catch(t){console.error(`[WuPlugin] Error in hook ${e}:`,t)}return!0}uninstall(e){const s=this.plugins.get(e);if(!s)return void t.warn(`[WuPlugin] Plugin "${e}" not found`);const{plugin:r,sandboxedApi:i}=s;if(r.uninstall)try{r.uninstall(i)}catch(t){console.error(`[WuPlugin] Error uninstalling "${e}":`,t)}this.plugins.delete(e),t.debug(`[WuPlugin] โœ… Plugin "${e}" uninstalled`)}getPlugin(e){return this.plugins.get(e)?.plugin}getStats(){return{totalPlugins:this.plugins.size,plugins:Array.from(this.plugins.entries()).map(([e,t])=>({name:e,permissions:t.permissions,installedAt:t.installedAt})),hooks:Array.from(this.hooks.entries()).map(([e,t])=>({name:e,callbacks:t.length}))}}cleanup(){for(const[e]of this.plugins)this.uninstall(e)}}class y{constructor(e){this.core=e,this.strategies=new Map,this.loadingQueue=[],this.isIdle=!1,this.registerDefaultStrategies(),this.setupIdleCallback(),t.debug("[WuStrategies] ๐ŸŽฏ Loading strategies initialized")}registerDefaultStrategies(){this.register("lazy",{shouldPreload:!1,load:async(e,s)=>{t.debug(`[Strategy:Lazy] Loading ${e} on demand (no preload)`)}}),this.register("eager",{shouldPreload:!0,priority:"high",load:async(e,s)=>{t.debug(`[Strategy:Eager] Preloading ${e} immediately`);const r=this.core.apps.get(e);if(r){const s=await this.core.resolveModulePath(r);await import(s),t.debug(`[Strategy:Eager] โœ… ${e} preloaded`)}}}),this.register("preload",{shouldPreload:!0,priority:"medium",load:async(e,s)=>{t.debug(`[Strategy:Preload] Using resource hints for ${e}`);const r=this.core.apps.get(e);if(r){const s=await this.core.resolveModulePath(r),i=document.createElement("link");i.rel="prefetch",i.href=s,i.as="script",document.head.appendChild(i),t.debug(`[Strategy:Preload] โœ… Resource hint added for ${e}`)}}}),this.register("speculate",{shouldPreload:!0,priority:"medium",load:async(e,t)=>{this.core.prefetcher&&await this.core.prefetcher.prefetch(e,{eagerness:t.eagerness||"moderate"})}}),this.register("idle",{shouldPreload:!1,load:async(e,s)=>(t.debug(`[Strategy:Idle] Queueing ${e} for idle loading`),new Promise(t=>{this.loadingQueue.push({appName:e,config:s,resolve:t}),this.isIdle&&this.processIdleQueue()}))})}register(e,s){if(!s.load||"function"!=typeof s.load)throw new Error("[WuStrategies] Strategy must have a load function");this.strategies.set(e,{name:e,shouldPreload:s.shouldPreload||!1,priority:s.priority||"low",load:s.load}),t.debug(`[WuStrategies] Strategy "${e}" registered`)}async load(e,s){const r=s.strategy||"lazy",i=this.strategies.get(r);return i?await i.load(e,s):(t.warn(`[WuStrategies] Strategy "${r}" not found, using lazy`),await this.strategies.get("lazy").load(e,s))}async preload(e){const s=e.filter(e=>this.strategies.get(e.strategy||"lazy").shouldPreload);s.sort((e,t)=>{const s={high:0,medium:1,low:2},r=this.strategies.get(e.strategy)?.priority||"low",i=this.strategies.get(t.strategy)?.priority||"low";return s[r]-s[i]}),t.debug(`[WuStrategies] Preloading ${s.length} apps`);for(const e of s)try{await this.load(e.name,e)}catch(t){console.error(`[WuStrategies] Failed to preload ${e.name}:`,t)}}setupIdleCallback(){if("requestIdleCallback"in window){const e=t=>{this.isIdle=!0,this.processIdleQueue(t),requestIdleCallback(e)};requestIdleCallback(e)}else setTimeout(()=>{this.isIdle=!0,this.processIdleQueue()},2e3)}async processIdleQueue(e){for(;this.loadingQueue.length>0&&!(e&&e.timeRemaining()<=0);){const e=this.loadingQueue.shift();try{const s=this.core.apps.get(e.appName);if(s){const r=await this.core.resolveModulePath(s);await import(r),t.debug(`[Strategy:Idle] โœ… ${e.appName} loaded during idle time`),e.resolve(!0)}else e.resolve(null)}catch(t){console.error(`[Strategy:Idle] Failed to load ${e.appName}:`,t),e.resolve(null)}}}getStats(){return{totalStrategies:this.strategies.size,strategies:Array.from(this.strategies.keys()),idleQueueSize:this.loadingQueue.length,isIdle:this.isIdle}}cleanup(){this.loadingQueue=[],t.debug("[WuStrategies] ๐Ÿงน Strategies cleaned up")}}class _{constructor(e){this.core=e,this.handlers=[],this.errorLog=[],this.maxErrorLog=100,this.config={maxRetries:3,retryDelay:1e3,showErrorUI:!0},this.registerDefaultHandlers(),t.debug("[WuErrorBoundary] ๐Ÿ›ก๏ธ Error boundary initialized")}registerDefaultHandlers(){this.register({name:"network",canHandle:e=>"TypeError"===e.name&&(e.message.includes("fetch")||e.message.includes("network")),handle:async(e,s)=>{if(t.debug("[ErrorHandler:Network] Handling network error"),s.retryCount<this.config.maxRetries){const e=this.config.retryDelay*Math.pow(2,s.retryCount);return t.debug(`[ErrorHandler:Network] Retrying in ${e}ms...`),await new Promise(t=>setTimeout(t,e)),{recovered:!0,action:"retry",retryCount:s.retryCount+1}}return{recovered:!1,action:"fallback",message:"Network error: Please check your connection"}}}),this.register({name:"script-load",canHandle:e=>"Error"===e.name&&(e.message.includes("Loading")||e.message.includes("Failed to fetch")),handle:async(e,s)=>(t.debug("[ErrorHandler:ScriptLoad] Handling script load error"),s.fallbackUrl?(t.debug("[ErrorHandler:ScriptLoad] Trying fallback URL"),{recovered:!0,action:"use-fallback-url",url:s.fallbackUrl}):{recovered:!1,action:"fallback",message:"Failed to load microfrontend"})}),this.register({name:"mount",canHandle:e=>e.message&&e.message.includes("mount"),handle:async(e,s)=>{if(t.debug("[ErrorHandler:Mount] Handling mount error"),s.retryCount<2){t.debug("[ErrorHandler:Mount] Cleaning up and retrying...");try{await this.core.unmount(s.appName)}catch(e){t.warn("[ErrorHandler:Mount] Cleanup failed:",e)}return await new Promise(e=>setTimeout(e,500)),{recovered:!0,action:"retry",retryCount:s.retryCount+1}}return{recovered:!1,action:"fallback",message:"Failed to mount application"}}}),this.register({name:"timeout",canHandle:e=>"TimeoutError"===e.name||e.message.includes("timeout"),handle:async(e,s)=>(t.debug("[ErrorHandler:Timeout] Handling timeout error"),s.retryCount<2?{recovered:!0,action:"retry-with-longer-timeout",timeout:2*(s.timeout||5e3),retryCount:s.retryCount+1}:{recovered:!1,action:"fallback",message:"Operation timed out"})}),this.register({name:"generic",canHandle:()=>!0,handle:async(e,s)=>(t.debug("[ErrorHandler:Generic] Handling generic error"),{recovered:!1,action:"fallback",message:e.message||"An unexpected error occurred"})})}register(e){if(!e.name||!e.canHandle||!e.handle)throw new Error("[WuErrorBoundary] Handler must have name, canHandle, and handle");this.handlers.push(e),t.debug(`[WuErrorBoundary] Handler "${e.name}" registered`)}async handle(e,s={}){s={retryCount:0,timestamp:Date.now(),...s},this.logError(e,s);for(const r of this.handlers)try{if(r.canHandle(e,s)){t.debug(`[WuErrorBoundary] Using handler: ${r.name}`);const i=await r.handle(e,s);return i.recovered?(t.debug(`[WuErrorBoundary] โœ… Error recovered by ${r.name}`),i):("fallback"===i.action&&this.config.showErrorUI&&this.renderFallback(s,i),i)}}catch(e){console.error(`[WuErrorBoundary] Handler "${r.name}" failed:`,e)}return console.error("[WuErrorBoundary] โŒ No handler could handle the error"),{recovered:!1,action:"unhandled",message:"Unhandled error"}}renderFallback(e,s){if(!e.container)return void t.warn("[WuErrorBoundary] No container to render fallback");const r="string"==typeof e.container?document.querySelector(e.container):e.container;if(!r)return;r.innerHTML="";const i=document.createElement("div");i.className="wu-error-boundary",Object.assign(i.style,{padding:"2rem",borderRadius:"8px",background:"#fff3cd",border:"1px solid #ffc107",color:"#856404",fontFamily:"system-ui, -apple-system, sans-serif",textAlign:"center"});const n=document.createElement("div");n.textContent="โš ๏ธ",n.style.fontSize="3rem",n.style.marginBottom="1rem";const o=document.createElement("h3");o.textContent="Application Error",o.style.margin="0 0 0.5rem 0";const a=document.createElement("p");a.textContent=s.message||"An error occurred",a.style.margin="0 0 1rem 0";const c=document.createElement("button");c.textContent="๐Ÿ”„ Reload",Object.assign(c.style,{padding:"0.5rem 1rem",background:"#ffc107",border:"none",borderRadius:"4px",cursor:"pointer",fontWeight:"bold",color:"#000"}),c.addEventListener("click",()=>window.location.reload()),i.appendChild(n),i.appendChild(o),i.appendChild(a),i.appendChild(c),r.appendChild(i)}logError(e,t){const s={error:{name:e.name,message:e.message,stack:e.stack},context:t,timestamp:Date.now()};this.errorLog.push(s),this.errorLog.length>this.maxErrorLog&&this.errorLog.shift()}getErrorLog(e=10){return this.errorLog.slice(-e)}getStats(){const e={};return this.errorLog.forEach(t=>{const s=t.error.name||"Unknown";e[s]=(e[s]||0)+1}),{totalErrors:this.errorLog.length,handlers:this.handlers.length,errorsByType:e,recentErrors:this.getErrorLog(5)}}configure(e){this.config={...this.config,...e}}cleanup(){this.errorLog=[],t.debug("[WuErrorBoundary] ๐Ÿงน Error boundary cleaned up")}}class v{constructor(e){this.core=e,this.hooks=new Map,this.executionLog=[],this.maxLogSize=100,this.lifecyclePhases=["beforeInit","afterInit","beforeLoad","afterLoad","beforeMount","afterMount","beforeUnmount","afterUnmount","beforeDestroy","afterDestroy"],this.lifecyclePhases.forEach(e=>{this.hooks.set(e,[])}),t.debug("[WuHooks] ๐Ÿช Lifecycle hooks initialized")}use(e,s,r={}){if(!this.hooks.has(e))throw new Error(`[WuHooks] Unknown lifecycle phase: ${e}`);if("function"!=typeof s)throw new Error("[WuHooks] Middleware must be a function");const i={middleware:s,name:r.name||`hook_${Date.now()}`,priority:r.priority||0,registeredAt:Date.now()},n=this.hooks.get(e);return n.push(i),n.sort((e,t)=>t.priority-e.priority),t.debug(`[WuHooks] Hook "${i.name}" registered for ${e} (priority: ${i.priority})`),()=>this.remove(e,i.name)}remove(e,s){if(!this.hooks.has(e))return;const r=this.hooks.get(e),i=r.findIndex(e=>e.name===s);i>-1&&(r.splice(i,1),t.debug(`[WuHooks] Hook "${s}" removed from ${e}`))}async execute(e,s={}){const r=this.hooks.get(e);if(!r||0===r.length)return s;t.debug(`[WuHooks] Executing ${r.length} hooks for ${e}`);const i={phase:e,timestamp:Date.now(),hooksCount:r.length,hookNames:r.map(e=>e.name)};let n={...s},o=!1;const a=async e=>{if(e>=r.length)return n;const s=r[e],i=Date.now();try{let r=!1;const c=async t=>(r=!0,void 0!==t&&(n={...n,...t}),await a(e+1));if(await s.middleware(n,c),!r)return t.debug(`[WuHooks] Hook "${s.name}" cancelled execution`),o=!0,{cancelled:!0};const l=Date.now()-i;t.debug(`[WuHooks] Hook "${s.name}" executed in ${l}ms`)}catch(t){return console.error(`[WuHooks] Error in hook "${s.name}":`,t),await a(e+1)}return n},c=await a(0);return i.duration=Date.now()-i.timestamp,i.cancelled=o,i.success=!o,this.executionLog.push(i),this.executionLog.length>this.maxLogSize&&this.executionLog.shift(),c}useMultiple(e,t,s={}){const r=e.map(e=>this.use(e,t,{...s,name:`${s.name}_${e}`}));return()=>r.forEach(e=>e())}getHooks(e){if(e)return this.hooks.get(e)||[];const t={};return this.hooks.forEach((e,s)=>{t[s]=e.map(e=>({name:e.name,priority:e.priority,registeredAt:e.registeredAt}))}),t}getStats(){const e=Array.from(this.hooks.values()).reduce((e,t)=>e+t.length,0),t={};this.executionLog.forEach(e=>{t[e.phase]=(t[e.phase]||0)+1});const s=this.executionLog.length>0?this.executionLog.reduce((e,t)=>e+t.duration,0)/this.executionLog.length:0,r=this.executionLog.filter(e=>e.cancelled).length;return{totalHooks:e,totalExecutions:this.executionLog.length,executionsByPhase:t,avgDuration:Math.round(s),cancelledCount:r,recentExecutions:this.executionLog.slice(-10)}}cleanup(e){e?(this.hooks.set(e,[]),t.debug(`[WuHooks] Hooks cleaned for ${e}`)):(this.lifecyclePhases.forEach(e=>{this.hooks.set(e,[])}),this.executionLog=[],t.debug("[WuHooks] ๐Ÿงน All hooks cleaned"))}}class b{constructor(){this._cache=new Map}async fetchHtml(e,s){t.wuDebug(`[HtmlParser] Fetching HTML for ${s} from ${e}`);const r=await fetch(e,{method:"GET",headers:{Accept:"text/html,application/xhtml+xml,*/*"}});if(!r.ok)throw new Error(`[HtmlParser] Failed to fetch ${e}: HTTP ${r.status}`);const i=await r.text();if(!i||!i.trim())throw new Error(`[HtmlParser] Empty HTML response from ${e}`);return t.wuDebug(`[HtmlParser] Fetched ${i.length} chars for ${s}`),i}parse(e,s,r){const i=`${s}:${e.length}`;if(this._cache.has(i))return this._cache.get(i);const n=document.createElement("div");n.innerHTML=e;const o=[],a=[],c=[],l=[];this._extractResources(n,{inlineScripts:o,externalScripts:a,inlineStyles:c,externalStyles:l,baseUrl:r});const u={dom:n.innerHTML,scripts:{inline:o,external:a},styles:{inline:c,external:l}};return this._cache.set(i,u),t.wuDebug(`[HtmlParser] ${s}: ${o.length} inline scripts, ${a.length} external scripts, ${c.length+l.length} styles`),u}async fetchAndParse(e,t){const s=await this.fetchHtml(e,t);return this.parse(s,t,e)}_extractResources(e,t){const s=Array.from(e.children);for(const e of s){const s=e.nodeName.toLowerCase();if("script"!==s){if("style"===s){const s=e.textContent?.trim();s&&t.inlineStyles.push(s),e.replaceWith(document.createComment("wu:style"));continue}if("link"===s){const s=e.getAttribute("rel"),r=e.getAttribute("href");if("stylesheet"===s&&r){t.externalStyles.push(this._resolveUrl(r,t.baseUrl)),e.replaceWith(document.createComment("wu:link"));continue}}e.children.length>0&&this._extractResources(e,t)}else this._extractScript(e,t),e.replaceWith(document.createComment("wu:script"))}}_extractScript(e,s){const r=e.getAttribute("type")||"",i=e.getAttribute("src");if("module"!==r)if(i)s.externalScripts.push(this._resolveUrl(i,s.baseUrl));else{const t=e.textContent?.trim();t&&s.inlineScripts.push(t)}else t.wuDebug('[HtmlParser] Skipping type="module" script (use sandbox: "module" for ES modules)')}_resolveUrl(e,t){if(e.startsWith("http://")||e.startsWith("https://"))return e;if(e.startsWith("//"))return`https:${e}`;try{return new URL(e,t).href}catch{const s=t.replace(/\/$/,"");return e.startsWith("/")?s+e:`${s}/${e}`}}clearCache(){this._cache.clear()}}class x{execute(e,s,r,i={}){const{strictGlobal:n=!0,sourceUrl:o=""}=i;if(!e||!e.trim())return;const a=o?`\n//# sourceURL=wu-sandbox:///${s}/${o}\n`:"";let c;c=n?`;(function(window, self, globalThis, top, parent) {\n with(window) {\n ;${e}${a}\n }\n}).call(proxy, proxy, proxy, proxy, proxy, proxy);`:`;(function(window, self, globalThis, top, parent) {\n ;${e}${a}\n}).call(proxy, proxy, proxy, proxy, proxy, proxy);`;try{return new Function("proxy",c)(r)}catch(o){if(n)return t.wuWarn(`[ScriptExecutor] strictGlobal failed for ${s}, retrying without with(): ${o.message}`),this.execute(e,s,r,{...i,strictGlobal:!1});throw t.wuError(`[ScriptExecutor] Execution failed for ${s}:`,o),o}}async fetchScript(e){const t=await fetch(e);if(!t.ok)throw new Error(`Failed to fetch script ${e}: HTTP ${t.status}`);return t.text()}async executeAll(e,s,r,i={}){for(const n of e){let e=n.content;!e&&n.src&&(t.wuDebug(`[ScriptExecutor] Fetching external script: ${n.src}`),e=await this.fetchScript(n.src)),e&&e.trim()&&this.execute(e,s,r,{...i,sourceUrl:n.src||i.sourceUrl||""})}t.wuDebug(`[ScriptExecutor] Executed ${e.length} scripts for ${s}`)}}class S{constructor(e){this.appName=e,this.iframe=null,this._active=!1,this._timers=new Set,this._intervals=new Set,this._rafs=new Set,this._listeners=[]}activate(e,s,r){if(this._active)return this.iframe.contentWindow;const i=document.createElement("iframe");i.setAttribute("data-wu-sandbox",this.appName),i.style.cssText="display:none !important;position:absolute;width:0;height:0;border:0;",document.body.appendChild(i),this.iframe=i;const n=e.replace(/\/$/,""),o=i.contentWindow,a=o.document;return a.open(),a.write(`<!DOCTYPE html><html><head><base href="${n}/"></head><body></body></html>`),a.close(),o.wu=window.wu,this._patchDocument(o,s,r),this._patchTimers(o),this._active=!0,t.wuDebug(`[IframeSandbox] Activated for ${this.appName} (base: ${n})`),o}importModule(e,s=3e4){if(!this._active)throw new Error(`[IframeSandbox] Not active for ${this.appName}`);return new Promise((r,i)=>{const n=`wu_${this.appName}_${Date.now()}`,o=e=>{e.data?.channelId===n&&(c(),e.data.error?i(new Error(e.data.error)):r())},a=setTimeout(()=>{c(),i(new Error(`[IframeSandbox] import() timed out for ${this.appName}: ${e}`))},s),c=()=>{window.removeEventListener("message",o),clearTimeout(a)};window.addEventListener("message",o);const l=this.iframe.contentWindow.document,u=l.createElement("script");u.type="module",u.textContent=`import("${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}").then(() => parent.postMessage({ channelId: "${n}", success: true }, '*')).catch(e => parent.postMessage({ channelId: "${n}", error: e.message || String(e) }, '*'));`,l.head.appendChild(u),t.wuDebug(`[IframeSandbox] Importing module: ${e}`)})}_patchDocument(e,s,r){const i=e.document,n=r||s,o=document;i.createElement=(e,t)=>o.createElement(e,t),i.createElementNS=(e,t,s)=>o.createElementNS(e,t,s),i.createTextNode=e=>o.createTextNode(e),i.createComment=e=>o.createComment(e),i.createDocumentFragment=()=>o.createDocumentFragment(),i.querySelector=e=>n.querySelector(e),i.querySelectorAll=e=>n.querySelectorAll(e),i.getElementById=e=>n.querySelector(`#${e}`),i.getElementsByClassName=e=>n.querySelectorAll(`.${e}`),i.getElementsByTagName=e=>n.querySelectorAll(e);try{Object.defineProperty(i,"body",{get:()=>s,configurable:!0})}catch{t.wuDebug("[IframeSandbox] Could not redefine document.body")}const a=i.addEventListener.bind(i),c=i.removeEventListener.bind(i);i.addEventListener=(e,t,s)=>{this._listeners.push({target:i,event:e,handler:t,options:s}),a(e,t,s)},i.removeEventListener=(e,t,s)=>{this._listeners=this._listeners.filter(s=>!(s.target===i&&s.event===e&&s.handler===t)),c(e,t,s)},t.wuDebug(`[IframeSandbox] Document patched for ${this.appName}`)}_patchTimers(e){const s=e.setTimeout.bind(e),r=e.clearTimeout.bind(e),i=e.setInterval.bind(e),n=e.clearInterval.bind(e);if(e.setTimeout=(e,t,...r)=>{const i=s((...t)=>{this._timers.delete(i),"function"==typeof e&&e(...t)},t,...r);return this._timers.add(i),i},e.clearTimeout=e=>{this._timers.delete(e),r(e)},e.setInterval=(e,t,...s)=>{const r=i(e,t,...s);return this._intervals.add(r),r},e.clearInterval=e=>{this._intervals.delete(e),n(e)},e.requestAnimationFrame){const t=e.requestAnimationFrame.bind(e),s=e.cancelAnimationFrame.bind(e);e.requestAnimationFrame=e=>{const s=t((...t)=>{this._rafs.delete(s),e(...t)});return this._rafs.add(s),s},e.cancelAnimationFrame=e=>{this._rafs.delete(e),s(e)}}t.wuDebug(`[IframeSandbox] Timer tracking active for ${this.appName}`)}destroy(){if(this._active){this._active=!1;for(const e of this._timers)try{clearTimeout(e)}catch{}for(const e of this._intervals)try{clearInterval(e)}catch{}for(const e of this._rafs)try{cancelAnimationFrame(e)}catch{}this._timers.clear(),this._intervals.clear(),this._rafs.clear();for(const{target:e,event:t,handler:s,options:r}of this._listeners)try{e.removeEventListener(t,s,r)}catch{}if(this._listeners=[],this.iframe){try{const e=this.iframe.contentDocument;e&&(e.open(),e.write(""),e.close())}catch{}this.iframe.parentNode&&this.iframe.parentNode.removeChild(this.iframe),this.iframe=null}t.wuDebug(`[IframeSandbox] Destroyed for ${this.appName}`)}}isActive(){return this._active}}class ${constructor(e){this.core=e,this.prefetched=new Set,this._observers=new Map,this._listeners=[],this._speculationScript=null,this._speculationRules={prefetch:[],prerender:[]},this.supportsSpeculationRules=this._detectSpeculationRules(),this.supportsModulePreload=this._detectModulePreload(),t.wuDebug(`[WuPrefetch] Initialized โ€” Speculation Rules: ${this.supportsSpeculationRules?"yes":"no"}, Module Preload: `+(this.supportsModulePreload?"yes":"no"))}_detectSpeculationRules(){return"undefined"!=typeof HTMLScriptElement&&(HTMLScriptElement.supports?.("speculationrules")??!1)}_detectModulePreload(){if("undefined"==typeof document)return!1;const e=document.createElement("link");return e.relList?.supports?.("modulepreload")??!1}async prefetch(e,s={}){const r=Array.isArray(e)?e:[e],i=s.on||"immediate";switch(i){case"immediate":return this._prefetchImmediate(r,s);case"hover":return this._prefetchOnHover(r,s);case"visible":return this._prefetchOnVisible(r,s);case"idle":return this._prefetchOnIdle(r,s);default:return t.wuWarn(`[WuPrefetch] Unknown trigger "${i}", using immediate`),this._prefetchImmediate(r,s)}}async _prefetchImmediate(e,t){const s=await this._resolveAppUrls(e);0!==s.length&&(s.forEach(({name:e})=>this.prefetched.add(e)),this.supportsSpeculationRules?this._addSpeculationRules(s,t.eagerness||"moderate"):this.supportsModulePreload?s.forEach(({url:e})=>this._injectModulePreload(e)):s.forEach(({url:e})=>this._injectPrefetch(e)))}_prefetchOnHover(e,s){const r=this._resolveTarget(s.target);if(!r)return t.wuWarn("[WuPrefetch] hover trigger requires a target element or selector"),()=>{};let i=!1;const n=()=>{i||(i=!0,this._prefetchImmediate(e,s),r.removeEventListener("mouseenter",n),r.removeEventListener("focusin",n))};r.addEventListener("mouseenter",n,{passive:!0}),r.addEventListener("focusin",n,{passive:!0});const o=()=>{r.removeEventListener("mouseenter",n),r.removeEventListener("focusin",n)};return this._listeners.push(o),o}_prefetchOnVisible(e,s){const r=this._resolveTarget(s.target);if(!r)return t.wuWarn("[WuPrefetch] visible trigger requires a target element or selector"),()=>{};if("undefined"==typeof IntersectionObserver)return this._prefetchImmediate(e,s),()=>{};const i=new IntersectionObserver(t=>{for(const n of t)if(n.isIntersecting){this._prefetchImmediate(e,s),i.disconnect(),this._observers.delete(r);break}},{rootMargin:"200px"});i.observe(r),this._observers.set(r,i);return()=>{i.disconnect(),this._observers.delete(r)}}_prefetchOnIdle(e,t){const s=()=>this._prefetchImmediate(e,t);if("requestIdleCallback"in window){const e=requestIdleCallback(s,{timeout:3e3}),t=()=>cancelIdleCallback(e);return this._listeners.push(t),t}const r=setTimeout(s,2e3),i=()=>clearTimeout(r);return this._listeners.push(i),i}_addSpeculationRules(e,s){const r=e.filter(({name:e})=>!this.prefetched.has(e));if(0===r.length)return;r.forEach(({name:e})=>this.prefetched.add(e));const i=r.map(({url:e})=>e);this._speculationRules.prefetch.push({source:"list",urls:i,eagerness:s}),this._updateSpeculationScript(),t.wuDebug(`[WuPrefetch] Speculation Rules: prefetch ${r.map(e=>e.name).join(", ")} (eagerness: ${s})`)}_updateSpeculationScript(){this._speculationScript&&this._speculationScript.remove();const e=document.createElement("script");e.type="speculationrules",e.textContent=JSON.stringify(this._speculationRules),document.head.appendChild(e),this._speculationScript=e}_injectModulePreload(e){if(this.prefetched.has(e))return;this.prefetched.add(e);const s=document.createElement("link");s.rel="modulepreload",s.href=e,document.head.appendChild(s),t.wuDebug(`[WuPrefetch] modulepreload: ${e}`)}_injectPrefetch(e){if(this.prefetched.has(e))return;this.prefetched.add(e);const s=document.createElement("link");s.rel="prefetch",s.href=e,s.as="script",document.head.appendChild(s),t.wuDebug(`[WuPrefetch] prefetch: ${e}`)}async _resolveAppUrls(e){const s=[];for(const r of e){if(this.prefetched.has(r)){t.wuDebug(`[WuPrefetch] ${r} already prefetched, skipping`);continue}if(this.core.mounted.has(r)){t.wuDebug(`[WuPrefetch] ${r} already mounted, skipping`);continue}if(this.core.definitions.has(r)){t.wuDebug(`[WuPrefetch] ${r} already defined, skipping`);continue}const e=this.core.apps.get(r);if(e)try{const t=await this.core.resolveModulePath(e);s.push({name:r,url:t})}catch(e){t.wuWarn(`[WuPrefetch] Failed to resolve URL for "${r}":`,e.message)}else t.wuWarn(`[WuPrefetch] App "${r}" not registered, cannot prefetch`)}return s}_resolveTarget(e){return e?"string"==typeof e?document.querySelector(e):e instanceof Element?e:null:null}async prefetchAll(e={}){const s=[];for(const[e]of this.core.apps)this.core.mounted.has(e)||this.prefetched.has(e)||s.push(e);if(0!==s.length)return t.wuDebug(`[WuPrefetch] Prefetching all: ${s.join(", ")}`),this.prefetch(s,e);t.wuDebug("[WuPrefetch] No apps to prefetch")}getStats(){return{prefetched:[...this.prefetched],activeObservers:this._observers.size,activeListeners:this._listeners.length,speculationRulesSupported:this.supportsSpeculationRules,modulePreloadSupported:this.supportsModulePreload,speculationRules:this._speculationRules}}cleanup(){for(const[,e]of this._observers)e.disconnect();this._observers.clear();for(const e of this._listeners)e();this._listeners=[],this._speculationScript&&(this._speculationScript.remove(),this._speculationScript=null),this._speculationRules={prefetch:[],prerender:[]},this.prefetched.clear(),t.wuDebug("[WuPrefetch] Cleaned up")}}const k="wu-override:";class E{constructor(e={}){this._overrides=new Map,this._allowedDomains=e.allowedDomains||[],this._showIndicator=e.showIndicator??!0,this._indicatorElement=null,void 0!==e.enabled?this._enabled=e.enabled:this._enabled=this._isDevEnvironment(),this._enabled&&this._parseFromCookies()}_isDevEnvironment(){if("undefined"==typeof window)return!1;const e=window.location?.hostname||"",t=window.location?.port||"";return"localhost"===e||"127.0.0.1"===e||"0.0.0.0"===e||e.endsWith(".local")||""!==t&&"80"!==t&&"443"!==t}_isDomainAllowed(e){if(0===this._allowedDomains.length)return!0;const t=this._extractHostname(e);if(!t)return!1;for(const e of this._allowedDomains)if(this._matchDomain(t,e))return!0;return!1}_extractHostname(e){try{if(/^localhost(:\d+)?/.test(e))return"localhost";const t=e.startsWith("//")?`https:${e}`:e;return new URL(t).hostname}catch{return null}}_matchDomain(e,t){if(e===t)return!0;if(t.startsWith("*.")){const s=t.substring(2);return e===s||e.endsWith("."+s)}return!1}_parseFromCookies(){if(this._overrides.clear(),"undefined"==typeof document)return this._overrides;if(!this._enabled)return t.wuDebug("[WuOverrides] Overrides disabled โ€” skipping cookie parse"),this._overrides;const e=document.cookie;if(!e)return this._overrides;const s=e.split(";");for(const e of s){const s=e.trim();if(!s.startsWith(k))continue;const r=s.indexOf("=");if(-1===r)continue;const i=s.substring(12,r).trim(),n=s.substring(r+1).trim();i&&n&&(this._isValidUrl(n)?this._isDomainAllowed(n)?(this._overrides.set(i,n),t.wuDebug(`[WuOverrides] Parsed override: ${i} โ†’ ${n}`)):t.wuWarn(`[WuOverrides] BLOCKED: "${i}" override to "${n}" โ€” domain not in allowedDomains. Allowed: [${this._allowedDomains.join(", ")}]`):t.wuWarn(`[WuOverrides] Invalid override URL for "${i}": ${n}`))}return this._overrides.size>0&&t.wuInfo(`[WuOverrides] ${this._overrides.size} active override(s): `+[...this._overrides.keys()].join(", ")),this._overrides}applyToApps(e){if(!this._enabled||0===this._overrides.size)return e;for(const s of e){const e=this._overrides.get(s.name);e&&(s._originalUrl=s.url,s.url=e,t.wuInfo(`[WuOverrides] "${s.name}" overridden: ${s._originalUrl} โ†’ ${e}`))}return this._showIndicator&&this._overrides.size>0&&this._showOverrideIndicator(),e}getOverrideFor(e){return this._overrides.get(e)||null}set(e,s,r={}){if(!e||!s)throw new Error("[WuOverrides] appName and url are required");if(!this._enabled)throw new Error("[WuOverrides] Overrides are disabled in this environment. Enable with wu.init({ overrides: { enabled: true } })");if(!this._isValidUrl(s))throw new Error(`[WuOverrides] Invalid URL: ${s}`);if(!this._isDomainAllowed(s))throw new Error(`[WuOverrides] Domain not allowed: "${this._extractHostname(s)}". Allowed: [${this._allowedDomains.join(", ")}]`);const i=r.maxAge??86400,n=r.path??"/";"undefined"!=typeof document&&(document.cookie=`${k}${e}=${s}; path=${n}; max-age=${i}; SameSite=Lax`),this._overrides.set(e,s),this._showIndicator&&this._showOverrideIndicator(),t.wuInfo(`[WuOverrides] Override set: ${e} โ†’ ${s} (expires in ${i}s)`)}remove(e){"undefined"!=typeof document&&(document.cookie=`${k}${e}=; path=/; max-age=0`),this._overrides.delete(e),this._showIndicator&&(0===this._overrides.size?this._removeOverrideIndicator():this._showOverrideIndicator()),t.wuInfo(`[WuOverrides] Override removed: ${e}`)}clearAll(){for(const e of[...this._overrides.keys()])this.remove(e);this._removeOverrideIndicator(),t.wuInfo("[WuOverrides] All overrides cleared")}getAll(){return Object.fromEntries(this._overrides)}hasOverrides(){return this._overrides.size>0}isEnabled(){return this._enabled}configure(e={}){void 0!==e.enabled&&(this._enabled=e.enabled),e.allowedDomains&&(this._allowedDomains=e.allowedDomains),void 0!==e.showIndicator&&(this._showIndicator=e.showIndicator),this._enabled&&this._parseFromCookies()}refresh(){this._parseFromCookies()}_showOverrideIndicator(){if("undefined"==typeof document)return;this._removeOverrideIndicator();const e=document.createElement("div");e.id="wu-override-indicator";const t=[...this._overrides.entries()].map(([e,t])=>`${e} โ†’ ${t}`).join(" | ");e.textContent=`WU OVERRIDE ACTIVE: ${t}`,e.style.cssText=["position: fixed","bottom: 0","left: 0","right: 0","z-index: 2147483647","background: #f59e0b","color: #000","font-family: monospace","font-size: 12px","font-weight: bold","padding: 6px 12px","text-align: center","cursor: pointer","user-select: none","box-shadow: 0 -2px 8px rgba(0,0,0,0.2)"].join(";"),e.addEventListener("click",()=>{e.style.display="none"}),e.addEventListener("dblclick",e=>{e.preventDefault(),this.clearAll()}),e.title="Click to hide | Double-click to clear all overrides",document.body.appendChild(e),this._indicatorElement=e}_removeOverrideIndicator(){if(this._indicatorElement&&(this._indicatorElement.remove(),this._indicatorElement=null),"undefined"!=typeof document){const e=document.getElementById("wu-override-indicator");e&&e.remove()}}_isValidUrl(e){return!!(e.startsWith("http://")||e.startsWith("https://")||e.startsWith("//"))||!!/^localhost(:\d+)?/.test(e)}getStats(){return{enabled:this._enabled,activeOverrides:this._overrides.size,overrides:this.getAll(),allowedDomains:this._allowedDomains,showIndicator:this._showIndicator,environment:this._isDevEnvironment()?"development":"production"}}}class A{constructor(e={}){this.apps=new Map,this.definitions=new Map,this.manifests=new Map,this.mounted=new Map,this.hidden=new Map,this.loader=new n,this.sandbox=new l,this.manifest=new u,this.store=h,this.htmlParser=new b,this.scriptExecutor=new x,this.cache=new m({storage:"localStorage",maxSize:100}),this.eventBus=new g,this.performance=new f,this.pluginSystem=new w(this),this.strategies=new y(this),this.errorBoundary=new _(this),this.hooks=new v(this),this.prefetcher=new $(this),this.overrides=new E,this.isInitialized=!1,t.wuInfo("Wu Framework initialized - Universal Microfrontends")}async init(e){if(this.isInitialized)t.wuWarn("Framework already initialized");else{this._sandboxMode=e.sandbox||"module",t.wuDebug(`Initializing (sandbox: ${this._sandboxMode}) with apps:`,e.apps?.map(e=>e.name));try{if((await this.hooks.execute("beforeInit",{config:e})).cancelled)return void t.wuWarn("Initialization cancelled by beforeInit hook");await this.pluginSystem.callHook("beforeInit",{config:e}),e.overrides&&this.overrides.configure(e.overrides);const s=e.apps||[];this.overrides.refresh(),this.overrides.applyToApps(s);for(const e of s)await this.registerApp(e);await this.strategies.preload(e.apps||[]),this.isInitialized=!0,await this.hooks.execute("afterInit",{config:e}),await this.pluginSystem.callHook("afterInit",{config:e}),t.wuInfo("Framework initialized successfully")}catch(e){throw t.wuError("Initialization failed:",e),await this.pluginSystem.callHook("onError",{phase:"init",error:e}),e}}}async registerApp(e){const{name:s,url:r}=e;try{t.wuDebug(`Registering app: ${s} from ${r}`);const i=await this.manifest.load(r);this.manifests.set(s,i),this.apps.set(s,{...e,manifest:i,status:"registered"}),t.wuDebug(`App ${s} registered successfully`)}catch(e){throw t.wuError(`Failed to register app ${s}:`,e),e}}define(e,s){if(!s.mount)throw new Error(`[Wu] Mount function required for app: ${e}`);this.definitions.set(e,s);const r=new CustomEvent("wu:app:ready",{detail:{appName:e,timestamp:Date.now()}});window.dispatchEvent(r),t.wuDebug(`Lifecycle defined for: ${e}`)}async mount(e,t){const s=this.hidden.get(e);if(s){if(s.containerSelector===t)return await this.show(e);await this._destroyHidden(e)}return await this.mountWithRecovery(e,t,0)}async mountWithRecovery(e,s,r=0){try{this.performance.startMeasure("mount",e),t.wuDebug(`Mounting ${e} in ${s} (attempt ${r+1})`);if((await this.hooks.execute("beforeLoad",{appName:e,containerSelector:s,attempt:r})).cancelled)return void t.wuWarn("Mount cancelled by beforeLoad hook");if(!1===await this.pluginSystem.callHook("beforeMount",{appName:e,containerSelector:s}))return void t.wuWarn("Mount cancelled by plugin beforeMount hook");const i=this.apps.get(e);if(!i)throw new Error(`App ${e} not registered. Call wu.init() first.`);const n=document.querySelector(s);if(!n)throw new Error(`Container not found: ${s}`);const o=this.sandbox.create(e,n,{manifest:i.manifest,styleMode:i.manifest?.styleMode,appUrl:i.url});await this.hooks.execute("afterLoad",{appName:e,containerSelector:s,sandbox:o});let a=this.definitions.get(e);if(!a&&(await this.loadAndMountRemoteApp(i,o),a=this.definitions.get(e),!a))throw new Error(`App ${e} did not register with wu.define()`);if((await this.hooks.execute("beforeMount",{appName:e,containerSelector:s,sandbox:o,lifecycle:a})).cancelled)return void t.wuWarn("Mount cancelled by beforeMount hook");o.stylesReady&&(t.wuDebug(`Waiting for styles to be ready for ${e}...`),await o.stylesReady,t.wuDebug(`Styles ready for ${e}`)),await a.mount(o.container),this.mounted.set(e,{app:i,sandbox:o,lifecycle:a,container:o.container,hostContainer:n,containerSelector:s,timestamp:Date.now(),state:"stable"});const c=this.performance.endMeasure("mount",e);await this.hooks.execute("afterMount",{appName:e,containerSelector:s,sandbox:o,mountTime:c}),await this.pluginSystem.callHook("afterMount",{appName:e,containerSelector:s,mountTime:c}),this.eventBus.emit("app:mounted",{appName:e,mountTime:c,attempt:r},{appName:e}),t.wuInfo(`${e} mounted successfully in ${c.toFixed(2)}ms`)}catch(i){t.wuError(`Mount attempt ${r+1} failed for ${e}:`,i);const n=await this.errorBoundary.handle(i,{appName:e,containerSelector:s,retryCount:r,container:s});if(n.recovered)return void t.wuDebug("Error recovered by error boundary");if(r<2&&"retry"===n.action)return t.wuDebug("Initiating recovery protocol..."),await this.appStateCleanup(e,s),await new Promise(e=>setTimeout(e,1e3*(r+1))),await this.mountWithRecovery(e,s,r+1);throw await this.pluginSystem.callHook("onError",{phase:"mount",error:i,appName:e}),i}}async appStateCleanup(e,s){try{if(t.wuDebug(`Starting app state cleanup for ${e}...`),this.hidden.has(e))try{await this._destroyHidden(e)}catch(e){t.wuWarn("Hidden app cleanup failed:",e)}if(this.mounted.has(e))try{await this.unmount(e,{force:!0})}catch(e){t.wuWarn("Unmount failed during cleanup:",e)}const r=document.querySelector(s);if(r){if(r.shadowRoot)try{Array.from(r.shadowRoot.children).forEach(e=>{try{e.remove()}catch(e){t.wuWarn("Failed to remove shadow child:",e)}})}catch(e){t.wuWarn("Shadow root cleanup failed:",e)}if(!r.shadowRoot&&r.children.length>0)try{r.innerHTML=""}catch(e){t.wuWarn("Container innerHTML cleanup failed:",e)}r.removeAttribute("data-wu-app"),r.removeAttribute("data-quantum-state"),r.removeAttribute("wu-debug")}this.definitions.delete(e),this.sandbox&&this.sandbox.sandboxes&&this.sandbox.sandboxes.delete(e),t.wuDebug(`App state cleaned successfully for ${e}`)}catch(r){t.wuWarn(`App cleanup partial failure for ${e}:`,r);try{const e=document.querySelector(s);e&&(e.style.display="none",setTimeout(()=>{e&&(e.style.display="")},100))}catch(e){t.wuError("Emergency cleanup failed:",e)}}}async loadAndMountRemoteApp(e,t){const s=e.sandbox||this._sandboxMode||"module";"strict"===s?await this._loadStrict(e,t):"eval"===s?await this._loadEval(e,t):await this._loadModule(e,t)}async _loadModule(e,s){const r=await this.resolveModulePath(e);t.wuDebug(`[module] Loading ES module: ${r}`);const i=s.jsSandbox;i?.patchWindow&&i.patchWindow();try{await this.moduleLoader(r,e.name),t.wuDebug(`[module] ES module loaded: ${e.name}`)}catch(e){throw t.wuError(`[module] Failed to load ${r}:`,e),e}finally{i?.unpatchWindow&&i.unpatchWindow()}}async _loadStrict(e,s){t.wuDebug(`[strict] Loading ${e.name} via iframe sandbox`);const r=new S(e.name);r.activate(e.url,s.container,s.shadowRoot),s.iframeSandbox=r;try{const s=await this.resolveModulePath(e);t.wuDebug(`[strict] Importing module in iframe: ${s}`),await r.importModule(s),t.wuDebug(`[strict] Module imported for ${e.name}`)}catch(i){return t.wuWarn(`[strict] iframe import failed for ${e.name}: ${i.message}\nFalling back to eval mode (fetch + parse + execute with proxy).\nTo fix: ensure the app's dev server sets Access-Control-Allow-Origin: * headers,\nor use sandbox: 'eval' explicitly for UMD/IIFE bundles.`),r.destroy(),s.iframeSandbox=null,void await this._loadEval(e,s)}await this._waitForDefine(e.name,"strict"),t.wuDebug(`[strict] ${e.name} loaded and registered via iframe`)}async _loadEval(e,s){t.wuDebug(`[eval] Loading ${e.name} from ${e.url}`);const r=s.jsSandbox.getProxy();if(!r)throw new Error(`[eval] No active proxy for ${e.name}. Sandbox must be activated first.`);const i=await this.htmlParser.fetchAndParse(e.url,e.name);i.dom&&(s.container.innerHTML=i.dom);const n=s.shadowRoot||s.container;for(const e of i.styles.inline){const t=document.createElement("style");t.textContent=e,n.appendChild(t)}for(const e of i.styles.external){const t=document.createElement("link");t.rel="stylesheet",t.href=e,n.appendChild(t)}const o=[];for(const e of i.scripts.inline)o.push({content:e});for(const e of i.scripts.external)o.push({src:e});await this.scriptExecutor.executeAll(o,e.name,r),t.wuDebug(`[eval] Scripts executed for ${e.name}`),await this._waitForDefine(e.name,"eval"),t.wuDebug(`[eval] ${e.name} loaded and registered`)}async _waitForDefine(e,t){const s=Date.now();for(;!this.definitions.has(e);){if(Date.now()-s>=1e4)throw new Error(`[${t}] App '${e}' loaded but wu.define() was not called within 10000ms.\nMake sure your app calls: window.wu.define('${e}', { mount, unmount })`);await new Promise(e=>setTimeout(e,50))}}async resolveModulePath(e){let s=e.manifest?.entry||"main.js";const r=e.url.replace(/\/$/,"");if(/^(src|dist|public|build|assets|lib|es)\//.test(s)){t.wuDebug(`Entry already has folder prefix: ${s}`);const e=`${r}/${s}`;return t.wuDebug(`Using direct path: ${e}`),e}const i=[`${r}/src/${s}`,`${r}/${s}`,`${r}/dist/${s}`,`${r}/public/${s}`,`${r}/build/${s}`,`${r}/assets/${s}`,`${r}/lib/${s}`,`${r}/es/${s}`];t.wuDebug(`Attempting path resolution for ${e.name}...`);for(let e=0;e<i.length;e++){const s=i[e];try{t.wuDebug(`Testing path candidate ${e+1}/${i.length}: ${s}`);if(await this.validatePath(s))return t.wuDebug(`Path resolved successfully: ${s}`),s;t.wuDebug(`Path candidate ${e+1} failed validation: ${s}`)}catch(r){t.wuDebug(`Path candidate ${e+1} threw error: ${s} - ${r.message}`);continue}}const n=i[0];return t.wuWarn(`All path candidates failed, using fallback: ${n}`),n}async validatePath(e){try{t.wuDebug(`Testing path: ${e}`);const s=await fetch(e,{method:"GET",cache:"no-cache",signal:AbortSignal.timeout(2e3)});if(!s.ok)return t.wuDebug(`Path validation failed - HTTP ${s.status}: ${e}`),!1;const r=s.headers.get("content-type")||"";if(!(r.includes("javascript")||r.includes("module")||r.includes("text/plain")||e.endsWith(".js")||e.endsWith(".mjs")))return t.wuDebug(`Path validation failed - Invalid content type '${r}': ${e}`),!1;const i=await s.text(),n=i.trim().toLowerCase();if(n.startsWith("<!doctype")||n.startsWith("<html")||n.startsWith("<head")||n.startsWith("<body")||n.startsWith("<!-"))return t.wuDebug(`Path validation failed - Server returned HTML fallback page: ${e}`),!1;return i.includes("export")||i.includes("import")||i.includes("wu.define")||i.includes("module.exports")||i.includes("console.log")||i.includes("function")&&i.length>10?(t.wuDebug(`Path validation successful: ${e} (${i.length} chars)`),!0):(t.wuDebug(`Path validation failed - No valid module content: ${e}`),t.wuDebug(`Content preview: ${i.substring(0,100)}...`),!1)}catch(s){return t.wuDebug(`Path validation failed for ${e}: ${s.message}`),!1}}async moduleLoader(e,s){if(this.definitions.has(s))return void t.wuDebug(`App ${s} already registered`);t.wuDebug(`Using event-based registration for ${s}`);try{await import(e)}catch(s){throw t.wuError(`Failed to import module ${e}:`,s),s}const r=Date.now();for(;!this.definitions.has(s);){if(Date.now()-r>=1e4)throw new Error(`App '${s}' module loaded but wu.define() was not called within 10000ms.\n\nMake sure your module calls:\n wu.define('${s}', { mount, unmount })\n\nOr using window.wu:\n window.wu.define('${s}', { mount, unmount })`);await new Promise(e=>setTimeout(e,50))}t.wuDebug(`App ${s} loaded and registered (verified in definitions)`)}async unmount(e,s={}){try{t.wuDebug(`Unmounting ${e}`);const r=this.mounted.get(e);if(!r)return s.force&&this.hidden.has(e)?await this._destroyHidden(e):void t.wuWarn(`App ${e} not mounted`);if(!s.force&&(s.keepAlive??r.app?.keepAlive??!1))return await this.hide(e);if((await this.hooks.execute("beforeUnmount",{appName:e,mounted:r})).cancelled)return void t.wuWarn("Unmount cancelled by beforeUnmount hook");if(!1===await this.pluginSystem.callHook("beforeUnmount",{appName:e}))return void t.wuWarn("Unmount cancelled by plugin beforeUnmount hook");r.lifecycle?.unmount&&await r.lifecycle.unmount(r.container),r.sandbox.iframeSandbox&&(r.sandbox.iframeSandbox.destroy(),r.sandbox.iframeSandbox=null),this.sandbox.cleanup(r.sandbox),this.mounted.delete(e),await this.hooks.execute("afterUnmount",{appName:e}),await this.pluginSystem.callHook("afterUnmount",{appName:e}),this.eventBus.emit("app:unmounted",{appName:e},{appName:e}),t.wuDebug(`${e} unmounted successfully`)}catch(s){throw t.wuError(`Failed to unmount ${e}:`,s),await this.pluginSystem.callHook("onError",{phase:"unmount",error:s,appName:e}),this.eventBus.emit("app:error",{appName:e,error:s.message},{appName:e}),s}}async hide(e){const s=this.mounted.get(e);if(s){if(t.wuDebug(`Hiding ${e} (keep-alive)`),s.lifecycle?.deactivate)try{await s.lifecycle.deactivate(s.container)}catch(s){t.wuWarn(`deactivate() failed for ${e}:`,s)}await this.hooks.execute("beforeUnmount",{appName:e,mounted:s,keepAlive:!0}),await this.pluginSystem.callHook("beforeUnmount",{appName:e,keepAlive:!0}),s.hostContainer.style.display="none",s.state="hidden",s.hiddenAt=Date.now(),this.hidden.set(e,s),this.mounted.delete(e),await this.hooks.execute("afterUnmount",{appName:e,keepAlive:!0}),await this.pluginSystem.callHook("afterUnmount",{appName:e,keepAlive:!0}),this.eventBus.emit("app:hidden",{appName:e},{appName:e}),t.wuInfo(`${e} hidden (keep-alive) โ€” state preserved`)}else t.wuWarn(`Cannot hide ${e}: not mounted`)}async show(e){const s=this.hidden.get(e);if(!s)return void t.wuWarn(`Cannot show ${e}: not in keep-alive state`);if(this.performance.startMeasure("show",e),t.wuDebug(`Showing ${e} from keep-alive`),await this.hooks.execute("beforeMount",{appName:e,containerSelector:s.containerSelector,sandbox:s.sandbox,lifecycle:s.lifecycle,keepAlive:!0}),await this.pluginSystem.callHook("beforeMount",{appName:e,containerSelector:s.containerSelector,keepAlive:!0}),s.hostContainer.style.display="",s.state="stable",delete s.hiddenAt,this.mounted.set(e,s),this.hidden.delete(e),s.lifecycle?.activate)try{await s.lifecycle.activate(s.container)}catch(s){t.wuWarn(`activate() failed for ${e}:`,s)}const r=this.performance.endMeasure("show",e);await this.hooks.execute("afterMount",{appName:e,containerSelector:s.containerSelector,sandbox:s.sandbox,mountTime:r,keepAlive:!0}),await this.pluginSystem.callHook("afterMount",{appName:e,containerSelector:s.containerSelector,mountTime:r,keepAlive:!0}),this.eventBus.emit("app:shown",{appName:e,showTime:r},{appName:e}),t.wuInfo(`${e} shown from keep-alive in ${r.toFixed(2)}ms`)}async _destroyHidden(e){const s=this.hidden.get(e);s&&(t.wuDebug(`Force-destroying hidden app: ${e}`),s.hostContainer.style.display="",s.state="stable",this.mounted.set(e,s),this.hidden.delete(e),await this.unmount(e,{force:!0}))}isHidden(e){return this.hidden.has(e)}async use(e){const[t,s]=e.split(".");if(!t||!s)throw new Error(`Invalid component path: ${e}. Use format "app.component"`);const r=this.apps.get(t);if(!r)throw new Error(`App ${t} not registered`);const i=this.manifests.get(t),n=i?.wu?.exports?.[s];if(!n)throw new Error(`Component ${s} not exported by ${t}`);return await this.loader.loadComponent(r.url,n)}getAppInfo(e){return{registered:this.apps.get(e),manifest:this.manifests.get(e),mounted:this.mounted.get(e),definition:this.definitions.get(e)}}getStats(){return{registered:this.apps.size,defined:this.definitions.size,mounted:this.mounted.size,hidden:this.hidden.size,apps:Array.from(this.apps.keys())}}getState(e){return this.store.get(e)}setState(e,t){return this.store.set(e,t)}onStateChange(e,t){return this.store.on(e,t)}batchState(e){return this.store.batch(e)}getStoreMetrics(){return this.store.getMetrics()}clearState(){this.store.clear()}override(e,t,s){this.overrides.set(e,t,s)}removeOverride(e){this.overrides.remove(e)}getOverrides(){return this.overrides.getAll()}clearOverrides(){this.overrides.clearAll()}prefetch(e,t){return this.prefetcher.prefetch(e,t)}prefetchAll(e){return this.prefetcher.prefetchAll(e)}app(e,t){return new p(e,t,this)}async destroy(){t.wuDebug("Destroying framework...");try{await this.hooks.execute("beforeDestroy",{}),await this.pluginSystem.callHook("onDestroy",{});for(const e of[...this.hidden.keys()])await this._destroyHidden(e);for(const e of[...this.mounted.keys()])await this.unmount(e,{force:!0});this.cache.clear(),this.eventBus.removeAll(),this.eventBus.clearHistory(),this.performance.clearMetrics(),this.pluginSystem.cleanup(),this.strategies.cleanup(),this.errorBoundary.cleanup(),this.hooks.cleanup(),this.prefetcher.cleanup(),this.apps.clear(),this.definitions.clear(),this.manifests.clear(),this.mounted.clear(),this.hidden.clear(),this.store.clear(),this.isInitialized=!1,await this.hooks.execute("afterDestroy",{}),t.wuDebug("Framework destroyed")}catch(e){throw t.wuError("Error during destroy:",e),e}}}class C{constructor(e={}){this.model=e.model||""}formatRequest(){throw new Error("Adapter must implement formatRequest()")}parseResponse(){throw new Error("Adapter must implement parseResponse()")}parseStreamChunk(){throw new Error("Adapter must implement parseStreamChunk()")}getHeaders(){return{"Content-Type":"application/json"}}}class D extends C{constructor(e){super(e),this.model=e.model||"claude-sonnet-4-5-20250929"}getHeaders(e){const t={"Content-Type":"application/json"};return e.apiKey&&(t["x-api-key"]=e.apiKey,t["anthropic-version"]="2023-06-01"),t}formatRequest(e,t={}){const s=e.filter(e=>"system"===e.role),r=e.filter(e=>"system"!==e.role),i={model:t.model||this.model,max_tokens:t.maxTokens||4096,messages:r.map(e=>"tool"===e.role?{role:"user",content:[{type:"tool_result",tool_use_id:e.tool_call_id,content:e.content}]}:e.tool_calls?{role:"assistant",content:e.tool_calls.map(e=>({type:"tool_use",id:e.id,name:e.name,input:e.arguments}))}:{role:e.role,content:e.content})};if(s.length&&(i.system=s.map(e=>e.content).join("\n\n")),t.responseFormat){const e=t.responseFormat,s="\n\nYou MUST respond with valid JSON only. No markdown, no explanation.";if("json"===e||"json_object"===e?.type)i.system=(i.system||"")+s;else if("json_schema"===e?.type){const t=JSON.stringify(e.schema,null,2);i.system=(i.system||"")+s+`\n\nYour response MUST conform to this JSON schema:\n${t}`}i.messages.push({role:"assistant",content:"{"})}return t.tools?.length&&(i.tools=t.tools.map(e=>({name:e.name,description:e.description,input_schema:e.parameters}))),void 0!==t.temperature&&(i.temperature=t.temperature),t.stream&&(i.stream=!0),i}parseResponse(e){const t=(e.content||[]).filter(e=>"text"===e.type),s=(e.content||[]).filter(e=>"tool_use"===e.type),r=t.map(e=>e.text).join(""),i=s.map(e=>({id:e.id,name:e.name,arguments:e.input||{}}));return{content:r,tool_calls:i.length>0?i:void 0,usage:e.usage?{prompt_tokens:e.usage.input_tokens,completion_tokens:e.usage.output_tokens}:void 0}}parseStreamChunk(e){if(!e.startsWith("data: "))return null;const t=e.slice(6).trim();try{const e=JSON.parse(t);if("content_block_delta"===e.type){if("text_delta"===e.delta?.type)return{type:"text",content:e.delta.text};if("input_json_delta"===e.delta?.type)return{type:"tool_call_delta",argumentsDelta:e.delta.partial_json||""}}return"content_block_start"===e.type&&"tool_use"===e.content_block?.type?{type:"tool_call_start",id:e.content_block.id,name:e.content_block.name}:"message_delta"===e.type&&e.usage?{type:"usage",usage:{prompt_tokens:e.usage.input_tokens,completion_tokens:e.usage.output_tokens}}:"message_stop"===e.type?{type:"done"}:null}catch{return null}}}class L extends C{constructor(e){super(e),this._sendFn=e.send||null,this._streamFn=e.stream||null}get isCustom(){return!0}}const P={openai:class extends C{constructor(e){super(e),this.model=e.model||"gpt-4o"}getHeaders(e){const t={"Content-Type":"application/json"};return e.apiKey&&(t.Authorization=`Bearer ${e.apiKey}`),t}formatRequest(e,t={}){const s={model:t.model||this.model,messages:e.map(e=>{const t={role:e.role,content:e.content};return e.tool_call_id&&(t.tool_call_id=e.tool_call_id),e.tool_calls&&(t.tool_calls=e.tool_calls.map(e=>({id:e.id,type:"function",function:{name:e.name,arguments:JSON.stringify(e.arguments)}}))),t})};if(t.tools?.length&&(s.tools=t.tools.map(e=>({type:"function",function:{name:e.name,description:e.description,parameters:e.parameters}}))),void 0!==t.temperature&&(s.temperature=t.temperature),t.maxTokens&&(s.max_tokens=t.maxTokens),t.stream&&(s.stream=!0),t.responseFormat){const e=t.responseFormat;"json"===e||"json_object"===e?.type?s.response_format={type:"json_object"}:"json_schema"===e?.type&&(s.response_format={type:"json_schema",json_schema:{name:e.name||"response",schema:e.schema,strict:!1!==e.strict}})}return s}parseResponse(e){const t=e.choices?.[0];if(!t)return{content:"",tool_calls:[],usage:e.usage};const s=t.message||{},r=(s.tool_calls||[]).map(e=>({id:e.id,name:e.function?.name,arguments:this._safeParseArgs(e.function?.arguments)}));return{content:s.content||"",tool_calls:r.length>0?r:void 0,usage:e.usage?{prompt_tokens:e.usage.prompt_tokens,completion_tokens:e.usage.completion_tokens}:void 0}}parseStreamChunk(e){if(!e.startsWith("data: "))return null;const t=e.slice(6).trim();if("[DONE]"===t)return{type:"done"};try{const e=JSON.parse(t),s=e.choices?.[0]?.delta;if(!s)return null;if(s.tool_calls?.length){const e=s.tool_calls[0];return{type:"tool_call_delta",index:e.index,id:e.id,name:e.function?.name,argumentsDelta:e.function?.arguments||""}}return s.content?{type:"text",content:s.content}:e.usage?{type:"usage",usage:e.usage}:null}catch{return null}}_safeParseArgs(e){if(!e)return{};try{return JSON.parse(e)}catch{return{}}}},anthropic:D,ollama:class extends C{constructor(e){super(e),this.model=e.model||"llama3"}getHeaders(){return{"Content-Type":"application/json"}}formatRequest(e,t={}){const s={model:t.model||this.model,messages:e.map(e=>({role:e.role,content:e.content}))};if(t.tools?.length&&(s.tools=t.tools.map(e=>({type:"function",function:{name:e.name,description:e.description,parameters:e.parameters}}))),void 0!==t.temperature&&(s.options={temperature:t.temperature}),void 0!==t.stream&&(s.stream=t.stream),t.responseFormat){const e=t.responseFormat;"json"===e||"json_object"===e?.type?s.format="json":"json_schema"===e?.type&&(s.format=e.schema)}return s}parseResponse(e){const t=e.message||{},s=(t.tool_calls||[]).map((e,t)=>({id:`ollama_${t}_${Date.now()}`,name:e.function?.name,arguments:e.function?.arguments||{}}));return{content:t.content||"",tool_calls:s.length>0?s:void 0,usage:e.eval_count?{prompt_tokens:e.prompt_eval_count||0,completion_tokens:e.eval_count||0}:void 0}}parseStreamChunk(e){try{const t=JSON.parse(e);return t.done?{type:"done"}:t.message?.content?{type:"text",content:t.message.content}:null}catch{return null}}}};class W{constructor(){this._providers=new Map,this._active=null,this._activeName=null,this._activeConfig={},this._retryConfig={maxRetries:3,baseDelayMs:1e3}}register(e,s={}){const r=s.adapter||e,i=P[r];let n;if(s.send||s.stream)n=new L(s);else{if(!i)throw new Error(`[wu-ai] Unknown adapter '${r}'. Available: ${Object.keys(P).join(", ")}, or provide custom send/stream.`);n=new i(s)}this._providers.set(e,{adapter:n,config:s}),this._active&&!1===s.active||(this._active=n,this._activeName=e,this._activeConfig=s),t.wuInfo(`[wu-ai] Provider registered: '${e}' (adapter: ${r})`)}use(e){const t=this._providers.get(e);if(!t)throw new Error(`[wu-ai] Provider '${e}' not registered`);this._active=t.adapter,this._activeName=e,this._activeConfig=t.config}async send(e,s={}){const{adapter:r,config:i}=this._resolveProvider(s.provider);if(r.isCustom&&r._sendFn)return r._sendFn(e,s);const n=i.endpoint||i.baseUrl;if(!n)throw new Error("[wu-ai] No endpoint configured. Set config.endpoint or config.baseUrl.");const o=this._resolveUrl(n),a=r.formatRequest(e,{...s,stream:!1}),c=r.getHeaders(i),l=await this._fetchWithRetry(o,{method:"POST",headers:c,body:JSON.stringify(a),signal:s.signal}),u=await l.json(),d=r.parseResponse(u);if(r instanceof D&&s.responseFormat&&d.content&&(d.content="{"+d.content),s.responseFormat&&d.content)try{d.parsed=JSON.parse(d.content)}catch{d.parseError="Response is not valid JSON",t.wuDebug("[wu-ai] responseFormat requested but LLM returned invalid JSON")}return d}async*stream(e,t={}){const{adapter:s,config:r}=this._resolveProvider(t.provider);if(s.isCustom&&s._streamFn)return void(yield*s._streamFn(e,t));const i=r.endpoint||r.baseUrl;if(!i)throw new Error("[wu-ai] No endpoint configured. Set config.endpoint or config.baseUrl.");const n=this._resolveUrl(i),o=s.formatRequest(e,{...t,stream:!0}),a=s.getHeaders(r),c=await fetch(n,{method:"POST",headers:a,body:JSON.stringify(o),signal:t.signal});if(!c.ok)throw new Error(`[wu-ai] Stream request failed: ${c.status} ${c.statusText}`);const l=c.body.getReader(),u=new TextDecoder;let d="",h=s instanceof D&&!!t.responseFormat;try{for(;;){const{done:e,value:t}=await l.read();if(e)break;d+=u.decode(t,{stream:!0});const r=d.split("\n");d=r.pop()||"";for(const e of r){const t=e.trim();if(!t)continue;const r=s.parseStreamChunk(t);if(r&&(h&&"text"===r.type&&(r.content="{"+r.content,h=!1),yield r),"done"===r?.type)return}}if(d.trim()){const e=s.parseStreamChunk(d.trim());e&&(yield e)}}finally{l.releaseLock()}}async _fetchWithRetry(e,s){let r;for(let i=0;i<=this._retryConfig.maxRetries;i++)try{const n=await fetch(e,s);if(n.ok)return n;if((429===n.status||n.status>=500)&&(r=new Error(`HTTP ${n.status}: ${n.statusText}`),i<this._retryConfig.maxRetries)){const e=this._retryConfig.baseDelayMs*Math.pow(2,i);t.wuDebug(`[wu-ai] Retry ${i+1}/${this._retryConfig.maxRetries} in ${e}ms (${n.status})`),await new Promise(t=>setTimeout(t,e));continue}const o=new Error(`[wu-ai] Request failed: ${n.status} ${n.statusText}`);throw o._noRetry=!0,o}catch(e){if("AbortError"===e.name)throw e;if(e._noRetry)throw e;if(r=e,i<this._retryConfig.maxRetries){const e=this._retryConfig.baseDelayMs*Math.pow(2,i);await new Promise(t=>setTimeout(t,e));continue}}throw r}_resolveUrl(e){return e.startsWith("/")&&"undefined"!=typeof window?`${window.location.origin}${e}`:e}_resolveProvider(e){if(e){const t=this._providers.get(e);if(!t)throw new Error(`[wu-ai] Provider '${e}' not registered. Available: ${[...this._providers.keys()].join(", ")}`);return{adapter:t.adapter,config:t.config}}return this._ensureActive(),{adapter:this._active,config:this._activeConfig}}_ensureActive(){if(!this._active)throw new Error('[wu-ai] No provider configured. Call wu.ai.provider("name", { endpoint, adapter }) first.')}configureRetry(e){void 0!==e.maxRetries&&(this._retryConfig.maxRetries=e.maxRetries),void 0!==e.baseDelayMs&&(this._retryConfig.baseDelayMs=e.baseDelayMs)}getActiveProvider(){return this._activeName}getStats(){return{activeProvider:this._activeName,registeredProviders:[...this._providers.keys()]}}}const M={readStore:!0,writeStore:!1,emitEvents:!0,readDOM:!1,modifyDOM:!1,executeActions:!0,allowDirectKey:!1},I="closed",T="open",N="half-open";class R{constructor(e={}){this._maxPerMinute=e.requestsPerMinute??20,this._maxPerMinutePerNs=e.requestsPerMinutePerNs??10,this._maxConcurrent=e.maxConcurrent??3,this._globalTimestamps=[],this._nsTimestamps=new Map,this._concurrent=0}configure(e){void 0!==e.requestsPerMinute&&(this._maxPerMinute=e.requestsPerMinute),void 0!==e.requestsPerMinutePerNs&&(this._maxPerMinutePerNs=e.requestsPerMinutePerNs),void 0!==e.maxConcurrent&&(this._maxConcurrent=e.maxConcurrent)}canSend(e="default"){if(this._pruneOld(),this._concurrent>=this._maxConcurrent)return{allowed:!1,reason:`Max concurrent (${this._maxConcurrent}) reached`};if(this._globalTimestamps.length>=this._maxPerMinute)return{allowed:!1,reason:`Global rate limit (${this._maxPerMinute}/min) exceeded`};return(this._nsTimestamps.get(e)||[]).length>=this._maxPerMinutePerNs?{allowed:!1,reason:`Namespace '${e}' rate limit (${this._maxPerMinutePerNs}/min) exceeded`}:{allowed:!0}}recordStart(e="default"){const t=Date.now();this._globalTimestamps.push(t),this._nsTimestamps.has(e)||this._nsTimestamps.set(e,[]),this._nsTimestamps.get(e).push(t),this._concurrent++}recordEnd(){this._concurrent=Math.max(0,this._concurrent-1)}_pruneOld(){const e=Date.now()-6e4;this._globalTimestamps=this._globalTimestamps.filter(t=>t>e);for(const[t,s]of this._nsTimestamps){const r=s.filter(t=>t>e);0===r.length?this._nsTimestamps.delete(t):this._nsTimestamps.set(t,r)}}getStats(){return this._pruneOld(),{globalRequestsLastMinute:this._globalTimestamps.length,concurrent:this._concurrent,maxPerMinute:this._maxPerMinute,maxConcurrent:this._maxConcurrent}}}class O{constructor(e={}){this._state=I,this._failureCount=0,this._maxFailures=e.maxFailures??3,this._cooldownMs=e.cooldownMs??3e4,this._openedAt=0,this._rapidFireThreshold=e.rapidFireThreshold??5,this._rapidFireWindowMs=e.rapidFireWindowMs??2e3,this._recentRequests=[]}configure(e){void 0!==e.maxFailures&&(this._maxFailures=e.maxFailures),void 0!==e.cooldownMs&&(this._cooldownMs=e.cooldownMs)}canPass(){if(this._state===I)return{allowed:!0};if(this._state===T){if(Date.now()-this._openedAt>=this._cooldownMs)return this._state=N,t.wuDebug("[wu-ai] Circuit breaker โ†’ HALF-OPEN (testing)"),{allowed:!0};const e=this._cooldownMs-(Date.now()-this._openedAt);return{allowed:!1,reason:`Circuit breaker OPEN (${Math.ceil(e/1e3)}s remaining)`}}return{allowed:!0}}recordSuccess(){this._state===N?(this._state=I,this._failureCount=0,t.wuInfo("[wu-ai] Circuit breaker โ†’ CLOSED (recovered)")):this._failureCount=0,this._recordRequest()}recordFailure(){this._failureCount++,this._recordRequest(),this._state!==N?this._failureCount>=this._maxFailures&&this._tripOpen(`${this._failureCount} consecutive failures`):this._tripOpen("Failed during half-open test")}_recordRequest(){const e=Date.now();this._recentRequests.push(e),this._recentRequests=this._recentRequests.filter(t=>e-t<this._rapidFireWindowMs),this._state===I&&this._recentRequests.length>=this._rapidFireThreshold&&this._tripOpen(`${this._recentRequests.length} requests in ${this._rapidFireWindowMs}ms (rapid fire)`)}_tripOpen(e){this._state=T,this._openedAt=Date.now(),t.wuWarn(`[wu-ai] Circuit breaker โ†’ OPEN: ${e}. Cooldown: ${this._cooldownMs/1e3}s`)}getState(){return this._state}getStats(){return{state:this._state,failureCount:this._failureCount,maxFailures:this._maxFailures,cooldownMs:this._cooldownMs,openedAt:this._openedAt}}reset(){this._state=I,this._failureCount=0,this._openedAt=0,this._recentRequests=[]}}class j{constructor(e={}){this._maxDepth=e.maxDepth??3,this._activeTraces=new Map,this._traceLog=[],this._maxTraceLog=50}configure(e){void 0!==e.maxDepth&&(this._maxDepth=e.maxDepth)}canProceed(e,t){if(e>this._maxDepth)return{allowed:!1,reason:`Max AI depth (${this._maxDepth}) exceeded at depth ${e}`};if(t){const e=(this._activeTraces.get(t)||0)+1;if(e>this._maxDepth)return{allowed:!1,reason:`Causal chain '${t}' looped ${e} times (max ${this._maxDepth})`}}return{allowed:!0}}enter(e){if(!e)return;const t=(this._activeTraces.get(e)||0)+1;this._activeTraces.set(e,t),this._traceLog.push({traceId:e,count:t,timestamp:Date.now()}),this._traceLog.length>this._maxTraceLog&&this._traceLog.shift()}exit(e){if(!e)return;const t=(this._activeTraces.get(e)||0)-1;t<=0?this._activeTraces.delete(e):this._activeTraces.set(e,t)}createTraceId(){return`t_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,8)}`}getTraces(){return[...this._traceLog]}getStats(){return{maxDepth:this._maxDepth,activeTraces:this._activeTraces.size,traceLogSize:this._traceLog.length}}}class F{constructor(e={}){this._permissions={...M},this.rateLimiter=new R(e.rateLimit),this.circuitBreaker=new O(e.circuitBreaker),this.loopProtection=new j(e.loopProtection),this._allowedDomains=e.allowedDomains||[],e.permissions&&this.configure(e.permissions)}configure(e){Object.assign(this._permissions,e),this._isProduction()&&this._permissions.allowDirectKey&&(t.wuWarn("[wu-ai] allowDirectKey FORCED to false in production"),this._permissions.allowDirectKey=!1)}check(e){return!0===this._permissions[e]}getPermissions(){return{...this._permissions}}setAllowedDomains(e){this._allowedDomains=e}isDomainAllowed(e){if(0===this._allowedDomains.length)return!0;try{const t=new URL(e).hostname;return this._allowedDomains.some(e=>{if(e.startsWith("*.")){const s=e.slice(2);return t===s||t.endsWith("."+s)}return t===e})}catch{return!1}}preflight(e={}){const t=this.circuitBreaker.canPass();if(!t.allowed)return t;const s=this.rateLimiter.canSend(e.namespace);if(!s.allowed)return s;const r=this.loopProtection.canProceed(e.depth||0,e.traceId);return r.allowed?{allowed:!0}:r}getStats(){return{permissions:{...this._permissions},rateLimiter:this.rateLimiter.getStats(),circuitBreaker:this.circuitBreaker.getStats(),loopProtection:this.loopProtection.getStats(),allowedDomains:[...this._allowedDomains]}}_isProduction(){if("undefined"!=typeof process&&"production"===process.env?.NODE_ENV)return!0;if("undefined"!=typeof window){const e=window.location?.hostname||"";return"localhost"!==e&&"127.0.0.1"!==e&&"0.0.0.0"!==e&&!e.endsWith(".local")}return!1}}const B=["password","token","apiKey","secret","credential","authorization","cookie","session"];function z(e,t=2e3){if(null==e)return"null";if("function"==typeof e)return"[Function]";if("symbol"==typeof e)return"[Symbol]";if("string"==typeof e){return`<user_data>${e.length>t?e.slice(0,t)+"...[truncated]":e}</user_data>`}if("number"==typeof e||"boolean"==typeof e)return String(e);if("object"==typeof e){const s=H(e),r=JSON.stringify(s);return r.length>t?`<user_data>${r.slice(0,t)}...[truncated]</user_data>`:`<user_data>${r}</user_data>`}return String(e).slice(0,t)}function H(e,t=0){if(t>10)return"[MAX_DEPTH]";if(null==e)return e;if("object"!=typeof e)return e;if(Array.isArray(e))return e.map(e=>H(e,t+1));const s={};for(const[r,i]of Object.entries(e)){const e=r.toLowerCase();B.some(t=>e.includes(t.toLowerCase()))?s[r]="[REDACTED]":s[r]=H(i,t+1)}return s}function q(e,t){return e.replace(/\{\{(\w+(?:\.\w+)*)\}\}/g,(e,s)=>{const r=s.split(".").reduce((e,t)=>e?.[t],t);return null==r?"":"object"==typeof r?z(r):String(r)})}function U(e){const t=[];for(const[s,r]of e)t.push({name:s,description:r.description||`Execute action: ${s}`,parameters:J(r.parameters)});return t}function J(e){if(!e||"object"!=typeof e)return{type:"object",properties:{},required:[]};if("object"===e.type&&e.properties)return e;const t={},s=[];for(const[r,i]of Object.entries(e))if("string"==typeof i)t[r]={type:i};else if("object"==typeof i){const{required:e,...n}=i;t[r]=n.type?n:{type:"string",...n},e&&s.push(r)}return{type:"object",properties:t,required:s}}function K(e,t){const s=[];if(!t||!t.properties)return{valid:!0,errors:s};for(const r of t.required||[])void 0!==e[r]&&null!==e[r]||s.push(`'${r}' is required`);for(const[r,i]of Object.entries(t.properties)){const t=e[r];if(null!=t){if(i.type&&"any"!==i.type){const e=Array.isArray(t)?"array":typeof t;"integer"===i.type?"number"==typeof t&&Number.isInteger(t)||s.push(`'${r}' must be integer, got ${e}`):i.type!==e&&s.push(`'${r}' must be ${i.type}, got ${e}`)}i.enum&&!i.enum.includes(t)&&s.push(`'${r}' must be one of [${i.enum.join(", ")}], got '${t}'`)}}return{valid:0===s.length,errors:s}}class G{constructor({store:e,eventBus:t,core:s}){this._store=e,this._eventBus=t,this._core=s,this._config={budget:4e3,charRatio:4,sources:{store:{include:[],priority:"high"},events:{include:[],lastN:10,priority:"medium"},custom:[]}},this._collectors=new Map,this._lastSnapshot=null}configure(e){void 0!==e.budget&&(this._config.budget=e.budget),void 0!==e.charRatio&&(this._config.charRatio=e.charRatio),e.sources&&(e.sources.store&&Object.assign(this._config.sources.store,e.sources.store),e.sources.events&&Object.assign(this._config.sources.events,e.sources.events),e.sources.custom&&(this._config.sources.custom=e.sources.custom))}register(e,s){this._collectors.set(e,{collector:s.collector,priority:s.priority||"medium"}),t.wuDebug(`[wu-ai] Context collector registered: '${e}' (${s.priority||"medium"})`)}async collect(){const e={_timestamp:Date.now(),_mountedApps:this._getMountedApps()},s=this._collectStore();s&&Object.keys(s).length>0&&(e._store=s);const r=this._collectEvents();r.length>0&&(e._events=r);for(const s of this._config.sources.custom)try{const t="function"==typeof s.value?await s.value():s.value;e[s.key]=t}catch(e){t.wuDebug(`[wu-ai] Custom collector '${s.key}' failed: ${e.message}`)}for(const[s,r]of this._collectors)try{const t=await r.collector();e[s]=t}catch(e){t.wuDebug(`[wu-ai] Collector '${s}' failed: ${e.message}`)}return this._lastSnapshot=e,e}toSystemPrompt(e={}){const t=this._lastSnapshot;if(!t)return this._baseSystemPrompt(e);const s=[];s.push("You are an AI assistant connected to a live web application via Wu Framework.","You can observe application state and execute actions when appropriate.",""),t._mountedApps?.length&&s.push(`MOUNTED APPS: ${t._mountedApps.join(", ")}`,"");const r=this._config.budget*this._config.charRatio;let i=s.join("\n").length;const n=this._prioritizeSections(t);for(const e of n){const t=e.text;if(i+t.length>r){if("high"===e.priority){const e=r-i;e>100&&(s.push(t.slice(0,e)+"\n...[truncated]"),i+=e)}}else s.push(t),i+=t.length}if(e.tools?.length){s.push("","AVAILABLE TOOLS:");for(const t of e.tools)s.push(`- ${t.name}: ${t.description}`)}return s.join("\n")}getSnapshot(){return this._lastSnapshot}getInterpolationContext(){if(!this._lastSnapshot)return{};const{_timestamp:e,_mountedApps:t,_store:s,_events:r,...i}=this._lastSnapshot;return{apps:t,store:s,events:r,...i}}_collectStore(){if(!this._store)return{};const{include:e}=this._config.sources.store;if(!e||0===e.length)return{};const t={};for(const s of e)try{const e=this._store.get(s);void 0!==e&&(t[s]=H(e))}catch{}return t}_collectEvents(){if(!this._eventBus)return[];const{include:e,lastN:t}=this._config.sources.events;if(!e||0===e.length)return[];return(this._eventBus.history||[]).filter(t=>e.some(e=>this._matchPattern(t.name||t.event,e))).slice(-(t||10)).map(e=>({event:e.name||e.event,data:H(e.data),timestamp:e.timestamp}))}_getMountedApps(){if(!this._core)return[];try{if(this._core.mounted instanceof Map)return[...this._core.mounted.keys()];const e=this._core.getStats?.();return e?.apps||e?.mounted||[]}catch{return[]}}_prioritizeSections(e){const t=[],s=this._config.sources.store.priority||"high",r=this._config.sources.events.priority||"medium";if(e._store&&Object.keys(e._store).length>0&&t.push({priority:s,text:`APPLICATION STATE:\n${JSON.stringify(e._store,null,2)}`}),e._events?.length){const s=e._events.map(e=>` [${e.event}] ${JSON.stringify(e.data)}`).join("\n");t.push({priority:r,text:`RECENT EVENTS:\n${s}`})}for(const[s,r]of this._collectors)void 0!==e[s]&&t.push({priority:r.priority,text:`${s.toUpperCase()}:\n${JSON.stringify(e[s],null,2)}`});for(const s of this._config.sources.custom)void 0!==e[s.key]&&t.push({priority:s.priority||"low",text:`${s.key}: ${JSON.stringify(e[s.key])}`});const i={high:0,medium:1,low:2};return t.sort((e,t)=>(i[e.priority]??1)-(i[t.priority]??1)),t}_baseSystemPrompt(e={}){let t="You are an AI assistant connected to a web application via Wu Framework.";return e.tools?.length&&(t+="\n\nAVAILABLE TOOLS:\n"+e.tools.map(e=>`- ${e.name}: ${e.description}`).join("\n")),t}_matchPattern(e,t){if(!e||!t)return!1;if("*"===t)return!0;if(!t.includes("*"))return e===t;return new RegExp("^"+t.replace(/\*/g,"[^:]*")+"$").test(e)}getStats(){return{budget:this._config.budget,collectors:[...this._collectors.keys()],storePaths:this._config.sources.store.include,eventPatterns:this._config.sources.events.include,lastCollected:this._lastSnapshot?._timestamp||null}}}class V{constructor({eventBus:e,store:t,permissions:s}){this._eventBus=e,this._store=t,this._permissions=s,this._actions=new Map,this._executionLog=[],this._maxLogSize=100,this._pendingConfirms=new Map}register(e,s){if(!s.handler||"function"!=typeof s.handler)throw new Error(`[wu-ai] Action '${e}' must have a handler function`);this._actions.set(e,{description:s.description||`Execute: ${e}`,parameters:J(s.parameters),handler:s.handler,confirm:s.confirm||!1,permissions:s.permissions||[],dangerous:s.dangerous||!1}),t.wuDebug(`[wu-ai] Action registered: '${e}'${s.dangerous?" [DANGEROUS]":""}`)}unregister(e){this._actions.delete(e)}async execute(e,s,r={}){const i=this._actions.get(e);if(!i)return{success:!1,reason:`Action '${e}' not registered`};for(const t of i.permissions)if(!this._permissions.check(t))return this._emitDenied(e,s,`Missing permission: ${t}`),{success:!1,reason:`Permission denied: ${t}`};const n=K(s||{},i.parameters);if(!n.valid)return{success:!1,reason:`Invalid params: ${n.errors.join(", ")}`};if(i.confirm){if(!await this._requestConfirmation(e,s,r.callId))return{success:!1,reason:"User denied action"}}try{i.dangerous&&t.wuWarn(`[wu-ai] Executing DANGEROUS action: '${e}' with params: ${JSON.stringify(s)}`);const n=this._createSandboxedApi(i.permissions),o=await i.handler(s,n);return this._log(e,s,o,r),this._eventBus.emit("ai:action:executed",{action:e,params:s,result:o,traceId:r.traceId},{appName:"wu-ai"}),{success:!0,result:o}}catch(t){return this._eventBus.emit("ai:action:error",{action:e,params:s,error:t.message,traceId:r.traceId},{appName:"wu-ai"}),{success:!1,reason:t.message}}}getToolSchemas(){return U(this._actions)}has(e){return this._actions.has(e)}getNames(){return[...this._actions.keys()]}getLog(){return[...this._executionLog]}confirmTool(e){const t=this._pendingConfirms.get(e);t&&(clearTimeout(t.timeout),this._pendingConfirms.delete(e),t.resolve(!0))}rejectTool(e){const t=this._pendingConfirms.get(e);t&&(clearTimeout(t.timeout),this._pendingConfirms.delete(e),t.resolve(!1))}_createSandboxedApi(e){const t={},s=new Set(e);return this._permissions.check("readStore")&&(t.getState=e=>this._store.get(e)),this._permissions.check("writeStore")&&s.has("writeStore")&&(t.setState=(e,t)=>this._store.set(e,t)),this._permissions.check("emitEvents")&&(t.emit=(e,t)=>this._eventBus.emit(e,t,{appName:"wu-ai"})),t}_requestConfirmation(e,s,r){const i=r||`confirm_${Date.now()}_${Math.random().toString(36).slice(2,6)}`;return new Promise(r=>{const n=setTimeout(()=>{this._pendingConfirms.delete(i),r(!1),t.wuDebug(`[wu-ai] Confirmation timeout for action '${e}'`)},3e4);this._pendingConfirms.set(i,{resolve:r,timeout:n}),this._eventBus.emit("ai:tool:confirm",{callId:i,action:e,params:s,message:`AI wants to execute: ${e}`},{appName:"wu-ai"})})}_log(e,t,s,r){this._executionLog.push({action:e,params:t,result:"object"==typeof s?{...s}:s,timestamp:Date.now(),traceId:r.traceId}),this._executionLog.length>this._maxLogSize&&this._executionLog.shift()}_emitDenied(e,s,r){this._eventBus.emit("ai:action:denied",{action:e,params:s,reason:r},{appName:"wu-ai"}),t.wuWarn(`[wu-ai] Action denied: '${e}' โ€” ${r}`)}getStats(){return{registeredActions:[...this._actions.keys()],executionLogSize:this._executionLog.length,pendingConfirmations:this._pendingConfirms.size}}}const Q={maxHistoryMessages:50,maxToolRounds:5,defaultNamespace:"default",systemPrompt:null,temperature:void 0,maxTokens:void 0,namespaceTTL:18e5,gcInterval:3e5};class Y{constructor(e){this.name=e,this.messages=[],this.createdAt=Date.now(),this.lastActivity=Date.now(),this._abortController=null}addMessage(e){this.messages.push({...e,_ts:Date.now()}),this.lastActivity=Date.now()}getMessages(){return this.messages.map(({_ts:e,...t})=>t)}truncate(e){if(this.messages.length<=e)return;const t=this.messages.filter(e=>"system"===e.role),s=this.messages.filter(e=>"system"!==e.role).slice(-e);this.messages=[...t,...s]}clear(){this.messages=[],this.lastActivity=Date.now()}abort(){this._abortController&&(this._abortController.abort(),this._abortController=null)}createAbortController(){return this.abort(),this._abortController=new AbortController,this._abortController}}class X{constructor({provider:e,actions:t,context:s,permissions:r,eventBus:i}){this._provider=e,this._actions=t,this._context=s,this._permissions=r,this._eventBus=i,this._config={...Q},this._namespaces=new Map,this._activeRequests=new Map,this._lastGcRun=Date.now()}configure(e){Object.assign(this._config,e)}async send(e,s={}){const r=this._getOrCreateNamespace(s.namespace),i=this._permissions.loopProtection.createTraceId(),n={namespace:r.name,depth:0,traceId:i},o=this._permissions.preflight(n);if(!o.allowed)return{content:`[blocked] ${o.reason}`,namespace:r.name};const a=await this._buildSystemPrompt(s);this._setSystemMessage(r,a);const c=this._processMessage(e,s.templateVars);r.addMessage({role:"user",content:c}),r.truncate(this._config.maxHistoryMessages);const l=r.createAbortController(),u=this._mergeSignals(l.signal,s.signal);this._permissions.rateLimiter.recordStart(r.name);try{const e=[];let n=0;const o=this._config.maxToolRounds;for(;n<=o;){const a=this._actions.getToolSchemas(),c=await this._provider.send(r.getMessages(),{tools:a.length>0?a:void 0,temperature:s.temperature??this._config.temperature,maxTokens:s.maxTokens??this._config.maxTokens,responseFormat:s.responseFormat,provider:s.provider,signal:u}),l={role:"assistant",content:c.content||""};if(c.tool_calls&&(l.tool_calls=c.tool_calls),r.addMessage(l),!c.tool_calls||0===c.tool_calls.length)return this._permissions.circuitBreaker.recordSuccess(),this._eventBus.emit("ai:response",{namespace:r.name,content:c.content,toolResults:e.length>0?e:void 0,usage:c.usage,traceId:i},{appName:"wu-ai"}),{content:c.content||"",tool_results:e.length>0?e:void 0,usage:c.usage,namespace:r.name};if(n++,n>o){const s=`[wu-ai] Tool call loop limit (${o}) reached in namespace '${r.name}'`;return t.wuWarn(s),r.addMessage({role:"assistant",content:s}),{content:s,tool_results:e,namespace:r.name}}this._permissions.loopProtection.enter(i);for(const t of c.tool_calls){const s=await this._actions.execute(t.name,t.arguments,{traceId:i,depth:n,callId:t.id});e.push({tool:t.name,params:t.arguments,result:s.result,success:s.success}),r.addMessage({role:"tool",content:JSON.stringify(s.success?s.result:{error:s.reason}),tool_call_id:t.id})}this._permissions.loopProtection.exit(i)}return{content:"",tool_results:e,namespace:r.name}}catch(e){if(this._permissions.circuitBreaker.recordFailure(),"AbortError"===e.name)return{content:"[aborted]",namespace:r.name};throw this._eventBus.emit("ai:error",{namespace:r.name,error:e.message,traceId:i},{appName:"wu-ai"}),e}finally{this._permissions.rateLimiter.recordEnd(),r._abortController=null}}async*stream(e,s={}){const r=this._getOrCreateNamespace(s.namespace),i=this._permissions.loopProtection.createTraceId(),n={namespace:r.name,depth:0,traceId:i},o=this._permissions.preflight(n);if(!o.allowed)return void(yield{type:"error",error:o.reason});const a=await this._buildSystemPrompt(s);this._setSystemMessage(r,a);const c=this._processMessage(e,s.templateVars);r.addMessage({role:"user",content:c}),r.truncate(this._config.maxHistoryMessages);const l=r.createAbortController(),u=this._mergeSignals(l.signal,s.signal);this._permissions.rateLimiter.recordStart(r.name);try{let e=0;const n=this._config.maxToolRounds;for(;e<=n;){const o=this._actions.getToolSchemas();let a="";const c=new Map;let l=!1;for await(const e of this._provider.stream(r.getMessages(),{tools:o.length>0?o:void 0,temperature:s.temperature??this._config.temperature,maxTokens:s.maxTokens??this._config.maxTokens,responseFormat:s.responseFormat,provider:s.provider,signal:u}))if("text"===e.type)a+=e.content,yield e;else if("tool_call_start"===e.type)c.set(c.size,{id:e.id,name:e.name,args:""});else if("tool_call_delta"===e.type){const t=e.index??c.size-1,s=c.get(t);s?(e.id&&(s.id=e.id),e.name&&(s.name=e.name),s.args+=e.argumentsDelta||""):c.set(t,{id:e.id||`tc_${t}`,name:e.name||"",args:e.argumentsDelta||""})}else{if("done"===e.type){l=!0;break}("usage"===e.type||"error"===e.type)&&(yield e)}if(0===c.size)return a&&r.addMessage({role:"assistant",content:a}),this._permissions.circuitBreaker.recordSuccess(),void(yield{type:"done"});if(e++,e>n){const e=`[wu-ai] Tool call loop limit (${n}) reached in streaming namespace '${r.name}'`;return t.wuWarn(e),yield{type:"error",error:e},void(yield{type:"done"})}const d=[];for(const[,e]of c){let t={};try{t=JSON.parse(e.args)}catch{}d.push({id:e.id,name:e.name,arguments:t})}r.addMessage({role:"assistant",content:a,tool_calls:d}),this._permissions.loopProtection.enter(i);for(const t of d){const s=await this._actions.execute(t.name,t.arguments,{traceId:i,depth:e,callId:t.id});yield{type:"tool_result",tool:t.name,result:s.success?s.result:{error:s.reason},success:s.success},r.addMessage({role:"tool",content:JSON.stringify(s.success?s.result:{error:s.reason}),tool_call_id:t.id})}this._permissions.loopProtection.exit(i),yield{type:"tool_calls_done",count:d.length}}}catch(e){if(this._permissions.circuitBreaker.recordFailure(),"AbortError"===e.name)return void(yield{type:"error",error:"aborted"});yield{type:"error",error:e.message},this._eventBus.emit("ai:error",{namespace:r.name,error:e.message,traceId:i},{appName:"wu-ai"})}finally{this._permissions.rateLimiter.recordEnd(),r._abortController=null}}inject(e,t,s={}){this._getOrCreateNamespace(s.namespace).addMessage({role:e,content:t})}getHistory(e){const t=this._namespaces.get(e||this._config.defaultNamespace);return t?t.getMessages():[]}clear(e){const t=this._namespaces.get(e||this._config.defaultNamespace);t&&t.clear()}clearAll(){for(const e of this._namespaces.values())e.clear()}abort(e){const t=this._namespaces.get(e||this._config.defaultNamespace);t&&t.abort()}abortAll(){for(const e of this._namespaces.values())e.abort()}getNamespaces(){return[...this._namespaces.keys()]}deleteNamespace(e){const t=this._namespaces.get(e);t&&(t.abort(),this._namespaces.delete(e))}_getOrCreateNamespace(e){const t=e||this._config.defaultNamespace;this._maybeGcSweep(),this._namespaces.has(t)||this._namespaces.set(t,new Y(t));const s=this._namespaces.get(t);return s.lastActivity=Date.now(),s}_maybeGcSweep(){const e=this._config.namespaceTTL,s=this._config.gcInterval;if(!e||e<=0)return;const r=Date.now();if(r-this._lastGcRun<s)return;this._lastGcRun=r;const i=r-e,n=[];for(const[e,t]of this._namespaces)e!==this._config.defaultNamespace&&(t._abortController||t.lastActivity<i&&n.push(e));for(const e of n)this._namespaces.delete(e);n.length>0&&t.wuDebug(`[wu-ai] GC sweep: removed ${n.length} expired namespace(s): ${n.join(", ")}`)}async _buildSystemPrompt(e){if(e.systemPrompt)return"function"==typeof e.systemPrompt?await e.systemPrompt():e.systemPrompt;if(this._config.systemPrompt)return"function"==typeof this._config.systemPrompt?await this._config.systemPrompt():this._config.systemPrompt;if(this._context){await this._context.collect();const e=this._actions.getToolSchemas();return this._context.toSystemPrompt({tools:e})}return"You are an AI assistant connected to a web application via Wu Framework."}_setSystemMessage(e,t){e.messages.length>0&&"system"===e.messages[0].role?(e.messages[0].content=t,e.messages[0]._ts=Date.now()):e.messages.unshift({role:"system",content:t,_ts:Date.now()})}_processMessage(e,t){if(!t)return e;try{return q(e,{...this._context?.getInterpolationContext()||{},...t})}catch{return e}}_mergeSignals(e,t){if(!t)return e;if("undefined"!=typeof AbortSignal&&AbortSignal.any)return AbortSignal.any([e,t]);const s=new AbortController,r=()=>s.abort();return e.addEventListener("abort",r,{once:!0}),t.addEventListener("abort",r,{once:!0}),s.signal}getStats(){const e={};for(const[t,s]of this._namespaces)e[t]={messageCount:s.messages.length,lastActivity:s.lastActivity,hasActiveRequest:!!s._abortController};return{namespaces:e,config:{...this._config}}}}const Z={enabled:!0,maxActiveTriggers:20,defaultDebounceMs:1e3,batchIntervalMs:2e3};class ee{constructor(e,t){this.name=e,this.pattern=t.pattern,this.prompt=t.prompt,this.condition=t.condition||null,this.debounceMs=t.debounce??Z.defaultDebounceMs,this.priority=t.priority||"medium",this.namespace=t.namespace||`trigger:${e}`,this.systemPrompt=t.systemPrompt||null,this.onResult=t.onResult||null,this.enabled=!1!==t.enabled,this.maxTokens=t.maxTokens||void 0,this.temperature=t.temperature||void 0,this._debounceTimer=null,this._lastFired=0,this._fireCount=0,this._pendingEvent=null}matches(e){if(!this.pattern)return!1;if("*"===this.pattern)return!0;if(!this.pattern.includes("*"))return e===this.pattern;return new RegExp("^"+this.pattern.replace(/\*/g,"[^:]*")+"$").test(e)}buildPrompt(e){return"function"==typeof this.prompt?this.prompt(e):q(this.prompt,{event:e,data:e?.data,timestamp:Date.now()})}async checkCondition(e){if(!this.condition)return!0;try{const t=this.condition(e);return t instanceof Promise?await t:t}catch(e){return t.wuDebug(`[wu-ai] Trigger '${this.name}' condition error: ${e.message}`),!1}}}class te{constructor({eventBus:e,conversation:t,permissions:s}){this._eventBus=e,this._conversation=t,this._permissions=s,this._config={...Z},this._triggers=new Map,this._listeners=new Map,this._batchQueue=[],this._batchTimer=null,this._stats={totalFired:0,totalSkipped:0,totalErrors:0}}configure(e){Object.assign(this._config,e)}register(e,s){if(this._triggers.size>=this._config.maxActiveTriggers)return void t.wuWarn(`[wu-ai] Max triggers (${this._config.maxActiveTriggers}) reached. Cannot register '${e}'.`);this._triggers.has(e)&&this.unregister(e);const r=new ee(e,s);this._triggers.set(e,r);const i=this._eventBus.on(r.pattern,t=>this._handleEvent(e,t));this._listeners.set(e,i),t.wuDebug(`[wu-ai] Trigger registered: '${e}' โ†’ pattern '${r.pattern}' (${r.priority})`)}unregister(e){const t=this._triggers.get(e);t&&t._debounceTimer&&clearTimeout(t._debounceTimer);const s=this._listeners.get(e);"function"==typeof s&&s(),this._triggers.delete(e),this._listeners.delete(e)}setEnabled(e,t){const s=this._triggers.get(e);s&&(s.enabled=t)}setAllEnabled(e){this._config.enabled=e;for(const t of this._triggers.values())t.enabled=e}async fire(e,s={}){const r=this._triggers.get(e);return r?this._executeTrigger(r,s):(t.wuWarn(`[wu-ai] Trigger '${e}' not found`),null)}getNames(){return[...this._triggers.keys()]}getTrigger(e){const t=this._triggers.get(e);return t?{name:t.name,pattern:t.pattern,priority:t.priority,namespace:t.namespace,enabled:t.enabled,fireCount:t._fireCount,lastFired:t._lastFired}:null}destroy(){for(const e of[...this._triggers.keys()])this.unregister(e);this._batchTimer&&(clearTimeout(this._batchTimer),this._batchTimer=null),this._batchQueue=[]}async _handleEvent(e,t){if(!this._config.enabled)return;const s=this._triggers.get(e);if(!s||!s.enabled)return;await s.checkCondition(t)?"high"===s.priority?this._debouncedFire(s,t):"low"===s.priority?(this._batchQueue.push({trigger:s,eventData:t}),this._scheduleBatch()):this._debouncedFire(s,t):this._stats.totalSkipped++}_debouncedFire(e,t){e._pendingEvent=t,e._debounceTimer&&clearTimeout(e._debounceTimer),e.debounceMs<=0?this._executeTrigger(e,t):e._debounceTimer=setTimeout(()=>{e._debounceTimer=null;const t=e._pendingEvent;e._pendingEvent=null,t&&this._executeTrigger(e,t)},e.debounceMs)}_scheduleBatch(){this._batchTimer||(this._batchTimer=setTimeout(()=>{this._batchTimer=null,this._processBatch()},this._config.batchIntervalMs))}async _processBatch(){const e=[...this._batchQueue];this._batchQueue=[];const t=new Map;for(const{trigger:s,eventData:r}of e)t.set(s.name,{trigger:s,eventData:r});for(const{trigger:e,eventData:s}of t.values())await this._executeTrigger(e,s)}async _executeTrigger(e,s){try{const r=e.buildPrompt(s);if(!r)return this._stats.totalSkipped++,null;t.wuDebug(`[wu-ai] Trigger '${e.name}' firing with prompt: ${r.slice(0,100)}...`);const i=await this._conversation.send(r,{namespace:e.namespace,systemPrompt:e.systemPrompt,temperature:e.temperature,maxTokens:e.maxTokens});if(e._fireCount++,e._lastFired=Date.now(),this._stats.totalFired++,this._eventBus.emit("ai:trigger:result",{trigger:e.name,pattern:e.pattern,result:i},{appName:"wu-ai"}),e.onResult)try{await e.onResult(i,s)}catch(s){t.wuDebug(`[wu-ai] Trigger '${e.name}' onResult error: ${s.message}`)}return i}catch(s){return this._stats.totalErrors++,t.wuWarn(`[wu-ai] Trigger '${e.name}' error: ${s.message}`),this._eventBus.emit("ai:trigger:error",{trigger:e.name,error:s.message},{appName:"wu-ai"}),null}}getStats(){const e={};for(const[t,s]of this._triggers)e[t]={pattern:s.pattern,priority:s.priority,enabled:s.enabled,fireCount:s._fireCount,lastFired:s._lastFired};return{...this._stats,triggerCount:this._triggers.size,batchQueueSize:this._batchQueue.length,triggers:e}}}const se="[DONE]",re="agent:";class ie{constructor({conversation:e,actions:t,context:s,permissions:r,eventBus:i}){this._conversation=e,this._actions=t,this._context=s,this._permissions=r,this._eventBus=i,this._config={maxSteps:10,systemPrompt:null},this._activeRuns=new Map,this._stats={totalRuns:0,totalSteps:0,completedRuns:0,abortedRuns:0,errorRuns:0}}configure(e){void 0!==e.maxSteps&&(this._config.maxSteps=e.maxSteps),void 0!==e.systemPrompt&&(this._config.systemPrompt=e.systemPrompt)}async*run(e,s={}){const r=s.maxSteps??this._config.maxSteps,i=s.namespace||this._generateNamespace(),n=this._generateRunId(),o=new AbortController;this._activeRuns.set(n,o),s.signal&&(s.signal.aborted?o.abort():s.signal.addEventListener("abort",()=>o.abort(),{once:!0})),this._stats.totalRuns++;const a=await this._buildAgentSystemPrompt(e,s);this._eventBus.emit("ai:agent:start",{runId:n,goal:e,namespace:i,maxSteps:r},{appName:"wu-ai"}),t.wuInfo(`[wu-ai] Agent run started: "${e.slice(0,80)}${e.length>80?"...":""}" (max ${r} steps)`);let c=0,l=!1,u="max_steps";try{for(;c<r;){c++;const t=Date.now();if(o.signal.aborted){const e=this._buildStepResult(c,"aborted",{reason:"Aborted by caller",elapsed:Date.now()-t});return this._stats.abortedRuns++,u="aborted",this._emitStep(n,e),void(yield e)}const r=this._permissions.loopProtection.createTraceId(),d=this._permissions.preflight({namespace:i,depth:c,traceId:r});if(!d.allowed){const e=this._buildStepResult(c,"blocked",{reason:d.reason,elapsed:Date.now()-t});return u="blocked",this._emitStep(n,e),void(yield e)}const h=1===c?e:"Continue working toward the goal. If you are done, include [DONE] in your response.";let p;try{p=await this._conversation.send(h,{namespace:i,systemPrompt:a,provider:s.provider,temperature:s.temperature,maxTokens:s.maxTokens,signal:o.signal})}catch(e){if("AbortError"===e.name||o.signal.aborted){const e=this._buildStepResult(c,"aborted",{reason:"Aborted during LLM call",elapsed:Date.now()-t});return this._stats.abortedRuns++,u="aborted",this._emitStep(n,e),void(yield e)}throw e}const m=Date.now()-t;this._stats.totalSteps++;const g=p.tool_results&&p.tool_results.length>0,f=p.content||"";if(f.includes(se)){const e=this._buildStepResult(c,"done",{content:f.replace(se,"").trim(),toolResults:p.tool_results,usage:p.usage,reason:"Goal completed (DONE marker)",elapsed:m});return u="done",this._stats.completedRuns++,this._emitStep(n,e),s.onStep&&await this._safeCallback(s.onStep,e),void(yield e)}const w=g;if(l&&!w){const e=this._buildStepResult(c,"done",{content:f,toolResults:p.tool_results,usage:p.usage,reason:"Goal completed (no further tool calls)",elapsed:m});return u="done",this._stats.completedRuns++,this._emitStep(n,e),s.onStep&&await this._safeCallback(s.onStep,e),void(yield e)}l=w;const y=g?"tool_call":"thinking",_=this._buildStepResult(c,y,{content:f,toolResults:p.tool_results,usage:p.usage,elapsed:m});if(this._emitStep(n,_),s.onStep&&await this._safeCallback(s.onStep,_),yield _,s.shouldContinue){let e;try{e=await s.shouldContinue(_)}catch{e=!1}if(!e){const e=this._buildStepResult(c,"interrupted",{content:f,reason:"Stopped by shouldContinue callback",elapsed:0});return u="interrupted",this._emitStep(n,e),void(yield e)}}}const t=this._buildStepResult(c,"done",{reason:`Max steps (${r}) reached`,elapsed:0});u="max_steps",yield t}catch(s){throw this._stats.errorRuns++,u="error",t.wuWarn(`[wu-ai] Agent run error: ${s.message}`),this._eventBus.emit("ai:agent:error",{runId:n,goal:e,namespace:i,step:c,error:s.message},{appName:"wu-ai"}),s}finally{this._activeRuns.delete(n),!s.namespace&&i.startsWith(re)&&this._conversation.deleteNamespace(i),this._eventBus.emit("ai:agent:done",{runId:n,goal:e,namespace:i,totalSteps:c,reason:u},{appName:"wu-ai"}),t.wuDebug(`[wu-ai] Agent run finished: ${u} after ${c} step(s)`)}}abort(e){const s=this._activeRuns.get(e);s&&(s.abort(),t.wuDebug(`[wu-ai] Agent run aborted: ${e}`))}abortAll(){for(const[e,t]of this._activeRuns)t.abort();this._activeRuns.clear()}getActiveRuns(){return[...this._activeRuns.keys()]}getStats(){return{...this._stats,activeRuns:this._activeRuns.size,config:{...this._config}}}destroy(){this.abortAll(),this._stats={totalRuns:0,totalSteps:0,completedRuns:0,abortedRuns:0,errorRuns:0}}async _buildAgentSystemPrompt(e,t){const s=t.systemPrompt??this._config.systemPrompt??null;if(s){return"function"==typeof s?await s(e):s}const r=[];if(r.push("You are an autonomous AI agent connected to a live web application via Wu Framework.","You have been given a goal and must work step-by-step to achieve it.","","PROTOCOL:",'- Each message you send is one "step" in your execution.',"- You may call tools to read or modify application state.","- After each step, you will be prompted to continue.","- When the goal is fully achieved, include the marker [DONE] in your response.","- If you determine the goal cannot be achieved, include [DONE] and explain why.","- Be concise. Each step should make meaningful progress.",""),this._context)try{await this._context.collect();const e=this._context.getSnapshot();e?._mountedApps?.length&&r.push(`MOUNTED APPS: ${e._mountedApps.join(", ")}`,""),e?._store&&Object.keys(e._store).length>0&&r.push(`APPLICATION STATE:\n${JSON.stringify(e._store,null,2)}`,"")}catch{}const i=this._actions.getToolSchemas();if(i.length>0){r.push("AVAILABLE TOOLS:");for(const e of i){const t=e.parameters?.properties?Object.keys(e.parameters.properties).join(", "):"none";r.push(`- ${e.name}(${t}): ${e.description}`)}r.push("")}return r.push(`GOAL: ${e}`),r.join("\n")}_buildStepResult(e,t,s={}){return{step:e,type:t,content:s.content??null,toolResults:s.toolResults??null,usage:s.usage??null,reason:s.reason??null,elapsed:s.elapsed??0}}_emitStep(e,t){this._eventBus.emit("ai:agent:step",{runId:e,...t},{appName:"wu-ai"})}async _safeCallback(e,...s){try{const t=e(...s);t&&"function"==typeof t.then&&await t}catch(e){t.wuDebug(`[wu-ai] Agent callback error: ${e.message}`)}}_generateNamespace(){return re+Date.now().toString(36)+"_"+Math.random().toString(36).slice(2,6)}_generateRunId(){return"run_"+Date.now().toString(36)+"_"+Math.random().toString(36).slice(2,8)}}const ne=[],oe=300,ae=[];let ce=!1;function le(){ce||(!function(){const e=window.fetch;window.fetch=async function(...t){const s=Date.now(),r=t[0],i="string"==typeof r?r:r?.url||"",n=(t[1]?.method||r?.method||"GET").toUpperCase();try{const r=await e.apply(window,t),o=parseInt(r.headers?.get("content-length")||"0",10);return ne.push({type:"fetch",method:n,url:i,status:r.status,statusText:r.statusText,duration:Date.now()-s,size:o,timestamp:s}),ne.length>oe&&ne.shift(),r}catch(e){throw ne.push({type:"fetch",method:n,url:i,status:0,error:e.message,duration:Date.now()-s,timestamp:s}),ne.length>oe&&ne.shift(),e}};const t=XMLHttpRequest.prototype.open,s=XMLHttpRequest.prototype.send;XMLHttpRequest.prototype.open=function(e,s,...r){return this._wuAi={method:(e||"GET").toUpperCase(),url:String(s)},t.call(this,e,s,...r)},XMLHttpRequest.prototype.send=function(...e){return this._wuAi&&(this._wuAi.start=Date.now(),this.addEventListener("loadend",()=>{ne.push({type:"xhr",method:this._wuAi.method,url:this._wuAi.url,status:this.status,statusText:this.statusText,duration:Date.now()-this._wuAi.start,size:parseInt(this.getResponseHeader("content-length")||"0",10),timestamp:this._wuAi.start}),ne.length>oe&&ne.shift()})),s.apply(this,e)}}(),function(){const e=["log","warn","error"];for(const t of e){const e=console[t];console[t]=(...s)=>{ae.push({level:t,message:s.map(e=>"object"==typeof e?JSON.stringify(e):String(e)).join(" "),timestamp:Date.now()}),ae.length>500&&ae.shift(),e.apply(console,s)}}}(),ce=!0)}function ue(e,t=0,s=5){if(t>s||!e)return"";const r=" ".repeat(t),i=e.tagName?.toLowerCase()||"",n=e.getAttribute?.("role")||"",o=e.getAttribute?.("aria-label")||"",a=1===e.childNodes?.length&&3===e.childNodes[0].nodeType?e.textContent?.trim().slice(0,80):"";let c=`${r}<${i}`;if(e.id&&(c+=` id="${e.id}"`),n&&(c+=` role="${n}"`),o&&(c+=` aria-label="${o}"`),e.className&&"string"==typeof e.className){const t=e.className.trim().slice(0,60);t&&(c+=` class="${t}"`)}c+=">",a&&(c+=` "${a}"`);let l=c+"\n";const u=(e.shadowRoot||e).children||[];for(let e=0;e<u.length&&e<50;e++)l+=ue(u[e],t+1,s);return l}function de(e,t){const s=["color","background","background-color","font-family","font-size","font-weight","border","border-radius","padding","margin","display","flex-direction","align-items","justify-content","gap","width","height","max-width","max-height","overflow","opacity","box-shadow","text-align","line-height","position","top","left","right","bottom","z-index","transform","visibility"];try{const r=window.getComputedStyle(e);for(const e of s){const s=r.getPropertyValue(e);s&&t.style?.setProperty(e,s)}}catch(e){}const r=e.children||[],i=t.children||[],n=Math.min(r.length,i.length,200);for(let e=0;e<n;e++)de(r[e],i[e])}async function he(e,t=.8){const s=e?document.querySelector(e):document.documentElement;if(!s)return{error:`Element not found: ${e}`};const r=s.getBoundingClientRect(),i=Math.ceil(Math.min(r.width||window.innerWidth,1920)),n=Math.ceil(Math.min(r.height||window.innerHeight,1080)),o=s.cloneNode(!0);de(s,o);const a=(new XMLSerializer).serializeToString(o),c=[`<svg xmlns="http://www.w3.org/2000/svg" width="${i}" height="${n}">`,'<foreignObject width="100%" height="100%">',`<div xmlns="http://www.w3.org/1999/xhtml" style="width:${i}px;height:${n}px;overflow:hidden;">`,a,"</div>","</foreignObject>","</svg>"].join(""),l=new Blob([c],{type:"image/svg+xml;charset=utf-8"}),u=URL.createObjectURL(l),d=await new Promise(e=>{const s=new Image;s.onload=()=>{const r=document.createElement("canvas");r.width=i,r.height=n;r.getContext("2d").drawImage(s,0,0),URL.revokeObjectURL(u),e(r.toDataURL("image/png",t))},s.onerror=()=>{URL.revokeObjectURL(u),e(null)},s.src=u});if(!d)return{error:"Canvas rendering failed"};const h=d.split(",")[1];return{width:i,height:n,format:"png",base64:h,sizeKB:Math.round(3*h.length/4/1024)}}function pe(e,t){let s=null;if(e&&(s=document.querySelector(e)),!s&&t){const e=document.querySelectorAll('button, a, [role="button"], input[type="submit"], input[type="button"], [data-click], label, [onclick]'),r=t.toLowerCase();for(const t of e)if(t.textContent?.trim().toLowerCase().includes(r)){s=t;break}}if(!s)return{error:`Element not found: ${e||`text="${t}"`}`};s.scrollIntoView({behavior:"instant",block:"center"}),s.click();const r=s.tagName?.toLowerCase();return{clicked:`${r}${s.id?`#${s.id}`:""}`,text:s.textContent?.trim().slice(0,100)||"",rect:s.getBoundingClientRect().toJSON?.()||null}}function me(e,t,{clear:s=!1,submit:r=!1}={}){if(!e)return{error:"selector is required"};if(void 0===t)return{error:"text is required"};const i=document.querySelector(e);if(!i)return{error:`Element not found: ${e}`};i.focus(),s&&(i.value="",i.dispatchEvent(new Event("input",{bubbles:!0})));const n=Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype,"value")?.set||Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype,"value")?.set,o=s?t:(i.value||"")+t;if(n?n.call(i,o):i.value=o,i.dispatchEvent(new Event("input",{bubbles:!0})),i.dispatchEvent(new Event("change",{bubbles:!0})),r){const e=i.closest("form");e?e.dispatchEvent(new Event("submit",{bubbles:!0,cancelable:!0})):i.dispatchEvent(new KeyboardEvent("keydown",{key:"Enter",code:"Enter",bubbles:!0}))}return{selector:e,typed:t,currentValue:i.value?.slice(0,200),submitted:!!r}}function ge(e,t,s=30){let r=ne;return e&&(r=r.filter(t=>t.method===e.toUpperCase())),t&&(r="error"===t?r.filter(e=>0===e.status||e.status>=400):r.filter(e=>String(e.status).startsWith(String(t)))),{requests:r.slice(-s),total:ne.length,showing:Math.min(r.length,s)}}function fe(e,t=30){const s=e&&"all"!==e?ae.filter(t=>t.level===e):ae;return{messages:s.slice(-t),total:ae.length,showing:Math.min(s.length,t)}}function we(e,t,s){switch(e.action){case"click":{const t=pe(e.selector,e.text);return t.error?{success:!1,error:t.error}:{success:!0,detail:`Clicked: ${e.selector||e.text}`}}case"type":{const t=me(e.selector,e.value,{clear:e.clear??!0,submit:e.submit??!1});return t.error?{success:!1,error:t.error}:{success:!0,detail:`Typed "${e.value}" into ${e.selector}`}}case"navigate":if(t&&e.section)return t.emit("nav:section",{section:e.section},{appName:"wu-ai"}),{success:!0,detail:`Navigated to section: ${e.section}`};if(e.selector){const t=pe(e.selector,e.text);return t.error?{success:!1,error:t.error}:{success:!0,detail:`Navigated via click: ${e.selector}`}}return{success:!1,error:'navigate requires "section" or "selector"'};case"wait":return{success:!0,detail:`Wait: ${e.ms||0}ms`};case"emit":return t?(t.emit(e.event,e.data||{},{appName:"wu-ai"}),{success:!0,detail:`Emitted: ${e.event}`}):{success:!1,error:"eventBus not available"};case"setState":return s?(s.set(e.path,e.value),{success:!0,detail:`Set state: ${e.path}`}):{success:!1,error:"store not available"};default:return{success:!1,error:`Unknown action: ${e.action}`}}}function ye(e,t=5e3){return new Promise(s=>{if(document.querySelector(e))return void s(!0);let r=0;const i=setInterval(()=>{r+=100,document.querySelector(e)?(clearInterval(i),s(!0)):r>=t&&(clearInterval(i),s(!1))},100)})}function _e(e){return new Promise(t=>setTimeout(t,e))}class ve{constructor({actions:e,conversation:t,context:s,permissions:r,eventBus:i,agent:n,store:o}){this._actions=e,this._conversation=t,this._context=s,this._permissions=r,this._eventBus=i,this._agent=n,this._store=o,this._capabilities=new Map,this._workflows=new Map,this._config={defaultProvider:null,defaultTemperature:.3},this._stats={totalIntents:0,resolvedIntents:0,failedIntents:0,workflowsRegistered:0,workflowsExecuted:0}}configure(e){void 0!==e.defaultProvider&&(this._config.defaultProvider=e.defaultProvider),void 0!==e.defaultTemperature&&(this._config.defaultTemperature=e.defaultTemperature)}register(e,s,r){if(!e||!s)throw new Error("[wu-ai] capability() requires both appName and actionName");if(!r||"function"!=typeof r.handler)throw new Error(`[wu-ai] capability '${e}:${s}' must have a handler function`);const i=`${e}:${s}`;this._capabilities.has(e)||this._capabilities.set(e,new Map),this._capabilities.get(e).set(s,{description:r.description||s,qualifiedName:i}),this._actions.register(i,{...r,description:`[${e}] ${r.description||s}`}),t.wuDebug(`[wu-ai] Capability registered: ${i}`)}unregister(e,t){const s=this._capabilities.get(e);if(!s)return;const r=`${e}:${t}`;s.delete(t),this._actions.unregister(r),0===s.size&&this._capabilities.delete(e)}removeApp(e){const s=this._capabilities.get(e);if(!s)return 0;let r=0;for(const[t]of s){const s=`${e}:${t}`;this._actions.unregister(s),r++}return this._capabilities.delete(e),t.wuDebug(`[wu-ai] All capabilities removed for app '${e}' (${r})`),this._eventBus.emit("ai:app:removed",{appName:e,capabilitiesRemoved:r},{appName:"wu-ai"}),r}getCapabilityMap(){const e={};for(const[t,s]of this._capabilities){e[t]=[];for(const[,r]of s)e[t].push({action:r.qualifiedName,description:r.description})}return e}getRegisteredApps(){return[...this._capabilities.keys()]}hasApp(e){return this._capabilities.has(e)}getTotalCapabilities(){let e=0;for(const t of this._capabilities.values())e+=t.size;return e}async resolve(e,t={}){if(!e||"string"!=typeof e)throw new Error("[wu-ai] intent() requires a description string");this._stats.totalIntents++;const s=this._generateNamespace();if(this._context)try{await this._context.collect()}catch{}const r=this._buildOrchestratorPrompt(t);this._eventBus.emit("ai:intent:start",{description:e.slice(0,200),namespace:s,capabilities:this.getTotalCapabilities()},{appName:"wu-ai"});try{const i=await this._conversation.send(e,{namespace:s,systemPrompt:r,provider:t.provider||this._config.defaultProvider,temperature:t.temperature??this._config.defaultTemperature,maxTokens:t.maxTokens,signal:t.signal,responseFormat:t.responseFormat}),n=i.tool_results||[],o=this._extractInvolvedApps(n),a=!!i.content;a?this._stats.resolvedIntents++:this._stats.failedIntents++;const c={content:i.content||"",tool_results:n,usage:i.usage||null,resolved:a,appsInvolved:o};return this._eventBus.emit("ai:intent:resolved",{description:e.slice(0,200),resolved:a,appsInvolved:o},{appName:"wu-ai"}),c}catch(t){throw this._stats.failedIntents++,this._eventBus.emit("ai:intent:error",{description:e.slice(0,200),error:t.message},{appName:"wu-ai"}),t}finally{this._conversation.deleteNamespace(s)}}buildOrchestratorPrompt(e={}){return this._buildOrchestratorPrompt(e)}_buildOrchestratorPrompt(e={}){const t=[];t.push("You are an AI orchestrator for a microfrontend application.","Multiple independent apps are mounted, each with specific capabilities.","Resolve cross-app requests by calling the right capabilities in the right order.","","RULES:","- Call capabilities (tools) to gather data or trigger actions.","- You may call multiple capabilities from different apps if needed.","- Synthesize results into a clear, actionable response.","- If a required app is not available or lacks a capability, explain what is missing.","");const s=this.getCapabilityMap(),r=Object.keys(s);if(r.length>0){t.push("CAPABILITY MAP:");for(const e of r){t.push(` ${e}:`);for(const r of s[e])t.push(` - ${r.action}: ${r.description}`)}t.push("")}else t.push("NOTE: No app capabilities are registered. Answer based on available context only.","");if(e.plan&&e.plan.length>0){t.push("SUGGESTED PLAN (follow this unless a better approach is evident):");for(let s=0;s<e.plan.length;s++)t.push(` ${s+1}. ${e.plan[s]}`);t.push("")}const i=this._context?.getSnapshot();return i?._mountedApps?.length&&t.push(`MOUNTED APPS: ${i._mountedApps.join(", ")}`,""),i?._store&&Object.keys(i._store).length>0&&t.push("CURRENT STATE:",JSON.stringify(i._store,null,2),""),t.join("\n")}registerWorkflow(e,s){if(!e)throw new Error("[wu-ai] workflow() requires a name");if(!s||!s.steps||!Array.isArray(s.steps)||0===s.steps.length)throw new Error(`[wu-ai] workflow '${e}' must have a non-empty steps array`);const r=s.mode||(s.steps.length>0&&"object"==typeof s.steps[0]&&s.steps[0].action?"deterministic":"ai");this._workflows.set(e,{description:s.description||e,steps:s.steps,mode:r,parameters:s.parameters||{},maxSteps:s.maxSteps??15,provider:s.provider||null,temperature:s.temperature??.2}),this._stats.workflowsRegistered++,t.wuDebug(`[wu-ai] Workflow registered: '${e}' (${s.steps.length} steps)`)}async*executeWorkflow(e,t={},s={}){const r=this._workflows.get(e);if(!r)throw new Error(`[wu-ai] Workflow '${e}' is not registered`);for(const[s,i]of Object.entries(r.parameters))if(i.required&&(void 0===t[s]||null===t[s]))throw new Error(`[wu-ai] Workflow '${e}' requires parameter '${s}'`);this._stats.workflowsExecuted++,"deterministic"===r.mode?yield*this._executeDeterministic(e,r,t,s):yield*this._executeWithAgent(e,r,t,s)}async*_executeWithAgent(e,t,s,r){if(!this._agent)throw new Error("[wu-ai] Agent module not available for workflow execution");const i=t.steps.map(e=>{let t=e;for(const[e,r]of Object.entries(s))t=t.replace(new RegExp(`\\{\\{${e}\\}\\}`,"g"),String(r));return t}),n=this._buildWorkflowGoal(t,i,s);this._eventBus.emit("ai:workflow:start",{workflow:e,mode:"ai",params:s,steps:i.length},{appName:"wu-ai"});let o=null;try{yield*this._agent.run(n,{maxSteps:t.maxSteps,provider:r.provider||t.provider||this._config.defaultProvider,temperature:t.temperature??.2,onStep:e=>{o=e,r.onStep&&r.onStep(e)},shouldContinue:r.shouldContinue,signal:r.signal})}finally{this._eventBus.emit("ai:workflow:done",{workflow:e,params:s,totalSteps:o?.step||0,result:o?.type||"unknown"},{appName:"wu-ai"})}}async*_executeDeterministic(e,t,s,r){const i=t.steps.map(e=>{const t={...e};for(const[e,r]of Object.entries(s)){const s=new RegExp(`\\{\\{${e}\\}\\}`,"g");for(const e of["value","selector","text","section","event","path"])"string"==typeof t[e]&&(t[e]=t[e].replace(s,String(r)))}return t});this._eventBus?.emit("ai:workflow:start",{workflow:e,mode:"deterministic",params:s,steps:i.length},{appName:"wu-ai"});let n=null;try{for(let e=0;e<i.length;e++){const t=i[e],s=e+1,o=Date.now();if(r.signal?.aborted){const e={step:s,type:"aborted",content:"Workflow aborted",reason:"Aborted by caller",elapsed:0};return n=e,void(yield e)}if("wait"===t.action){if(t.selector){const e=await ye(t.selector,t.timeout||5e3),i=Date.now()-o,a={step:s,type:e?"action":"error",content:e?`Waited for "${t.selector}" โ€” found`:`Timeout waiting for "${t.selector}"`,elapsed:i};if(n=a,r.onStep&&r.onStep(a),yield a,!e)return}else if(t.ms){await _e(t.ms);const e={step:s,type:"action",content:`Waited ${t.ms}ms`,elapsed:t.ms};n=e,r.onStep&&r.onStep(e),yield e}continue}const a=we(t,this._eventBus,this._store),c=Date.now()-o,l={step:s,type:a.success?"action":"error",content:a.success?a.detail:a.error,elapsed:c};if(n=l,r.onStep&&r.onStep(l),yield l,r.shouldContinue){let e;try{e=await r.shouldContinue(l)}catch{e=!1}if(!e){const e={step:s,type:"interrupted",content:"Stopped by user",reason:"shouldContinue returned false",elapsed:0};return n=e,void(yield e)}}if(!a.success)return;e<i.length-1&&await _e(t.delay??200)}const t={step:i.length,type:"done",content:`Workflow "${e}" completed (${i.length} steps)`,reason:"All steps executed",elapsed:0};n=t,r.onStep&&r.onStep(t),yield t}finally{this._eventBus?.emit("ai:workflow:done",{workflow:e,mode:"deterministic",params:s,totalSteps:n?.step||0,result:n?.type||"unknown"},{appName:"wu-ai"})}}hasWorkflow(e){return this._workflows.has(e)}getWorkflow(e){const t=this._workflows.get(e);return t?{description:t.description,steps:[...t.steps],mode:t.mode,parameters:{...t.parameters},maxSteps:t.maxSteps}:null}removeWorkflow(e){this._workflows.delete(e)}getWorkflowNames(){return[...this._workflows.keys()]}_buildWorkflowGoal(e,t,s){const r=[];r.push(`WORKFLOW: ${e.description}`,"","You must follow these steps IN ORDER. Use browser tools (screenshot, click, type)","to interact with the application. After each step, take a screenshot to verify.","","STEPS:");for(let e=0;e<t.length;e++)r.push(` ${e+1}. ${t[e]}`);r.push("","After completing all steps successfully, respond with [DONE].","If a step fails, explain what went wrong.");const i=this.getCapabilityMap(),n=Object.keys(i);if(n.length>0){r.push("","AVAILABLE APP CAPABILITIES:");for(const e of n)for(const t of i[e])r.push(` - ${t.action}: ${t.description}`)}return r.join("\n")}getStats(){return{...this._stats,registeredApps:this.getRegisteredApps(),totalCapabilities:this.getTotalCapabilities(),capabilityMap:this.getCapabilityMap(),workflows:this.getWorkflowNames(),config:{...this._config}}}destroy(){for(const[e,t]of this._capabilities)for(const[s]of t)this._actions.unregister(`${e}:${s}`);this._capabilities.clear(),this._workflows.clear(),this._stats={totalIntents:0,resolvedIntents:0,failedIntents:0,workflowsRegistered:0,workflowsExecuted:0}}_extractInvolvedApps(e){if(!e||!Array.isArray(e))return[];const t=new Set;for(const s of e){const e=s.name||s.tool||"",r=e.indexOf(":");r>0&&t.add(e.slice(0,r))}return[...t]}_generateNamespace(){return"intent:"+Date.now().toString(36)+"_"+Math.random().toString(36).slice(2,6)}}function be(e,t){le(),e.action("browser_screenshot",{description:"Take a screenshot of the current page or a specific element. Returns a base64 PNG image. Use this to SEE what the user sees.",parameters:{selector:{type:"string",description:"CSS selector of the element to capture. Empty = full visible page.",required:!1}},handler:async e=>he(e.selector),permissions:[]}),e.action("browser_click",{description:"Click an element on the page. Find by CSS selector or by visible text content. Use this to interact with buttons, links, tabs, etc.",parameters:{selector:{type:"string",description:'CSS selector (e.g. "#submit-btn", ".nav-link", "button[type=submit]")',required:!1},text:{type:"string",description:'Visible text to find and click (e.g. "Submit", "Next", "Guardar"). Searches buttons, links, and clickable elements.',required:!1}},handler:async(e,t)=>{const s=pe(e.selector,e.text);return s.error||t.emit?.("browser:clicked",{selector:e.selector,text:e.text}),s},permissions:["emitEvents"]}),e.action("browser_type",{description:"Type text into an input, textarea, or contenteditable element. Works with React, Vue, Angular, and other frameworks. Can optionally clear existing text first and submit the form.",parameters:{selector:{type:"string",description:'CSS selector of the input (e.g. "#email", "input[name=search]", "textarea.comment")',required:!0},text:{type:"string",description:"Text to type into the element",required:!0},clear:{type:"boolean",description:"Clear existing value before typing (default: false)",required:!1},submit:{type:"boolean",description:"Submit the form or press Enter after typing (default: false)",required:!1}},handler:async(e,t)=>{const s=me(e.selector,e.text,{clear:e.clear,submit:e.submit});return s.error||t.emit?.("browser:typed",{selector:e.selector,length:e.text.length}),s},permissions:["emitEvents"]}),e.action("browser_select",{description:"Select an option in a <select> dropdown or a custom dropdown component.",parameters:{selector:{type:"string",description:"CSS selector of the <select> element",required:!0},value:{type:"string",description:'The value attribute of the option to select. Use "text:" prefix to match by visible text (e.g. "text:Mexico")',required:!0}},handler:async(e,t)=>{const s=document.querySelector(e.selector);if(!s)return{error:`Element not found: ${e.selector}`};if("select"===s.tagName?.toLowerCase()){const r=Array.from(s.options);let i;if(e.value.startsWith("text:")){const t=e.value.slice(5).toLowerCase();i=r.find(e=>e.textContent.trim().toLowerCase().includes(t))}else i=r.find(t=>t.value===e.value);return i?(s.value=i.value,s.dispatchEvent(new Event("change",{bubbles:!0})),s.dispatchEvent(new Event("input",{bubbles:!0})),t.emit?.("browser:selected",{selector:e.selector,value:i.value}),{selected:i.value,text:i.textContent.trim()}):{error:`Option not found: ${e.value}`}}return s.click(),{clicked:e.selector,note:"Custom dropdown โ€” clicked trigger. Use browser_click to select an option from the opened menu."}},permissions:["emitEvents"]}),e.action("browser_scroll",{description:"Scroll the page or a specific element. Use to reveal content that is not visible.",parameters:{direction:{type:"string",description:'Direction: "up", "down", "top", "bottom"',required:!0},selector:{type:"string",description:"CSS selector of scrollable container (empty = page)",required:!1},amount:{type:"number",description:'Pixels to scroll (default: 500). Ignored for "top"/"bottom".',required:!1}},handler:async e=>{const t=e.selector?document.querySelector(e.selector):window,s=e.amount||500;if(e.selector&&!t)return{error:`Element not found: ${e.selector}`};const r=t===window?document.documentElement:t;switch(e.direction){case"up":r.scrollBy({top:-s,behavior:"smooth"});break;case"down":r.scrollBy({top:s,behavior:"smooth"});break;case"top":r.scrollTo({top:0,behavior:"smooth"});break;case"bottom":r.scrollTo({top:r.scrollHeight,behavior:"smooth"});break;default:return{error:`Invalid direction: ${e.direction}`}}return{scrolled:e.direction,amount:"top"===e.direction||"bottom"===e.direction?"max":s,currentScroll:r.scrollTop}},permissions:[]}),e.action("browser_snapshot",{description:"Get a text representation of the visible DOM structure (accessibility tree). Use this to understand what elements are on the page, their roles, IDs, and text content. Cheaper and faster than a screenshot.",parameters:{selector:{type:"string",description:'CSS selector to snapshot (empty = full page). Use "[data-wu-app=appName]" for a specific micro-app.',required:!1},depth:{type:"number",description:"Max depth to traverse (default: 5)",required:!1}},handler:async e=>{const t=e.selector?document.querySelector(e.selector):document.body;if(!t)return{error:`Element not found: ${e.selector}`};return{snapshot:ue(t,0,e.depth||5)}},permissions:[]}),e.action("browser_navigate",{description:"Navigate to a route within the SPA application. Emits a shell:navigate event and updates the store.",parameters:{route:{type:"string",description:'Route path (e.g. "/dashboard", "/users", "/pos/cotizador")',required:!0}},handler:async(e,t)=>(t.emit?.("shell:navigate",{route:e.route}),t.setState?.("currentPath",e.route),{navigated:e.route}),permissions:["emitEvents","writeStore"]}),e.action("browser_network",{description:"View captured HTTP network requests (fetch and XHR). Shows URL, method, status code, duration, and size. Use to debug API calls, check for errors, or monitor performance.",parameters:{method:{type:"string",description:"Filter by HTTP method: GET, POST, PUT, DELETE (empty = all)",required:!1},status:{type:"string",description:'Filter: "2" (2xx success), "4" (4xx errors), "5" (5xx errors), "error" (all failures)',required:!1},limit:{type:"number",description:"Max requests to return (default: 30)",required:!1}},handler:async e=>ge(e.method,e.status,e.limit),permissions:[]}),e.action("browser_console",{description:"View captured browser console messages (log, warn, error). Use to check for errors, warnings, or debug output.",parameters:{level:{type:"string",description:'Filter by level: "log", "warn", "error" (empty = all)',required:!1},limit:{type:"number",description:"Max messages to return (default: 30)",required:!1}},handler:async e=>fe(e.level,e.limit),permissions:[]}),e.action("browser_info",{description:"Get an overview of the current page state: URL, viewport size, mounted micro-apps, store keys, visible elements summary. Use this FIRST to understand the page before taking actions.",parameters:{},handler:async(e,s)=>{const r=[];if(t._apps)for(const[e,s]of Object.entries(t._apps))r.push({name:e,mounted:s.mounted||s.isMounted||!1,status:s.status||"unknown"});0===r.length&&document.querySelectorAll("[data-wu-app]").forEach(e=>{r.push({name:e.getAttribute("data-wu-app"),mounted:!0})});const i=s.getState?.("")||{},n="object"==typeof i?Object.keys(i):[];return{url:window.location.href,title:document.title,viewport:{width:window.innerWidth,height:window.innerHeight},apps:r,storeKeys:n,networkRequests:ne.length,consoleMessages:ae.length,consoleErrors:ae.filter(e=>"error"===e.level).length}},permissions:["readStore"]})}class xe{constructor({eventBus:e,store:t,core:s}){this._eventBus=e,this._store=t,this._core=s,this._initialized=!1,this._modules={}}init(e={}){return this._initialized?(this._reconfigure(e),this):(this._modules.permissions=new F({permissions:e.permissions,rateLimit:e.rateLimit,circuitBreaker:e.circuitBreaker,loopProtection:e.loopProtection,allowedDomains:e.allowedDomains}),this._modules.provider=new W,this._modules.context=new G({store:this._store,eventBus:this._eventBus,core:this._core}),e.context&&this._modules.context.configure(e.context),this._modules.actions=new V({eventBus:this._eventBus,store:this._store,permissions:this._modules.permissions}),this._modules.conversation=new X({provider:this._modules.provider,actions:this._modules.actions,context:this._modules.context,permissions:this._modules.permissions,eventBus:this._eventBus}),e.conversation&&this._modules.conversation.configure(e.conversation),this._modules.triggers=new te({eventBus:this._eventBus,conversation:this._modules.conversation,permissions:this._modules.permissions}),e.triggers&&this._modules.triggers.configure(e.triggers),this._modules.agent=new ie({conversation:this._modules.conversation,actions:this._modules.actions,context:this._modules.context,permissions:this._modules.permissions,eventBus:this._eventBus}),e.agent&&this._modules.agent.configure(e.agent),this._modules.orchestrate=new ve({actions:this._modules.actions,conversation:this._modules.conversation,context:this._modules.context,permissions:this._modules.permissions,eventBus:this._eventBus,agent:this._modules.agent,store:this._store}),e.orchestrate&&this._modules.orchestrate.configure(e.orchestrate),this._initialized=!0,t.wuInfo("[wu-ai] Initialized"),"undefined"!=typeof window&&(be(this,this._core),t.wuInfo("[wu-ai] Browser actions registered (10 tools)")),this._eventBus.emit("ai:initialized",{},{appName:"wu-ai"}),this)}provider(e,t){return this._ensureInit(),this._modules.provider.register(e,t),this}async send(e,t={}){return this._ensureInit(),this._modules.conversation.send(e,t)}async*stream(e,t={}){this._ensureInit(),yield*this._modules.conversation.stream(e,t)}async json(e,t={}){this._ensureInit();const{schema:s,schemaName:r,...i}=t;let n;n=s?{type:"json_schema",schema:s,name:r||"response"}:t.responseFormat||"json";const o=await this._modules.conversation.send(e,{...i,responseFormat:n});let a,c=null;if(void 0!==o.parsed)c=o.parsed;else if(o.content)try{c=JSON.parse(o.content)}catch{a="LLM response is not valid JSON"}return{data:c,raw:o.content||"",error:a||o.parseError,usage:o.usage,namespace:o.namespace}}abort(e){this._initialized&&(e?this._modules.conversation.abort(e):this._modules.conversation.abortAll())}action(e,t){return this._ensureInit(),this._modules.actions.register(e,t),this}async execute(e,t){this._ensureInit();const s=this._modules.permissions.loopProtection.createTraceId();return this._modules.actions.execute(e,t,{traceId:s,depth:0})}trigger(e,t){return this._ensureInit(),this._modules.triggers.register(e,t),this}async fireTrigger(e,t){return this._ensureInit(),this._modules.triggers.fire(e,t)}async*agent(e,t={}){this._ensureInit(),yield*this._modules.agent.run(e,t)}capability(e,t,s){return this._ensureInit(),this._modules.orchestrate.register(e,t,s),this}async intent(e,t={}){return this._ensureInit(),this._modules.orchestrate.resolve(e,t)}removeApp(e){return this._ensureInit(),this._modules.orchestrate.removeApp(e),this}workflow(e,t){return this._ensureInit(),this._modules.orchestrate.registerWorkflow(e,t),this}async*runWorkflow(e,t={},s={}){this._ensureInit(),yield*this._modules.orchestrate.executeWorkflow(e,t,s)}get context(){return this._ensureInit(),{configure:e=>this._modules.context.configure(e),register:(e,t)=>this._modules.context.register(e,t),collect:()=>this._modules.context.collect(),getSnapshot:()=>this._modules.context.getSnapshot()}}get conversation(){return this._ensureInit(),{getHistory:e=>this._modules.conversation.getHistory(e),clear:e=>this._modules.conversation.clear(e),clearAll:()=>this._modules.conversation.clearAll(),inject:(e,t,s)=>this._modules.conversation.inject(e,t,s),getNamespaces:()=>this._modules.conversation.getNamespaces(),deleteNamespace:e=>this._modules.conversation.deleteNamespace(e)}}get permissions(){return this._ensureInit(),{configure:e=>this._modules.permissions.configure(e),check:e=>this._modules.permissions.check(e),getPermissions:()=>this._modules.permissions.getPermissions(),setAllowedDomains:e=>this._modules.permissions.setAllowedDomains(e)}}tools(){return this._ensureInit(),this._modules.actions.getToolSchemas()}expose(){if(this._ensureInit(),"undefined"==typeof navigator||!navigator.modelContext)return t.wuDebug("[wu-ai] WebMCP not available (navigator.modelContext missing)"),!1;const e=this._modules.actions.getToolSchemas(),s=this._modules.actions.getNames();for(let r=0;r<e.length;r++){const i=e[r],n=s[r];try{navigator.modelContext.registerTool({name:i.name,description:i.description,inputSchema:i.parameters,handler:async e=>{const t=await this.execute(n,e);return t.success?t.result:{error:t.reason}}})}catch(e){t.wuDebug(`[wu-ai] WebMCP register failed for '${i.name}': ${e.message}`)}}return t.wuInfo(`[wu-ai] Exposed ${e.length} tools via WebMCP`),this._eventBus.emit("ai:webmcp:exposed",{toolCount:e.length,tools:e.map(e=>e.name)},{appName:"wu-ai"}),!0}confirmTool(e){this._initialized&&this._modules.actions.confirmTool(e)}rejectTool(e){this._initialized&&this._modules.actions.rejectTool(e)}getStats(){return this._initialized?{initialized:!0,provider:this._modules.provider.getStats(),permissions:this._modules.permissions.getStats(),context:this._modules.context.getStats(),actions:this._modules.actions.getStats(),conversation:this._modules.conversation.getStats(),triggers:this._modules.triggers.getStats(),agent:this._modules.agent.getStats(),orchestrate:this._modules.orchestrate.getStats()}:{initialized:!1}}destroy(){this._initialized&&(this._modules.orchestrate.destroy(),this._modules.agent.destroy(),this._modules.conversation.abortAll(),this._modules.triggers.destroy(),this._modules={},this._initialized=!1,t.wuInfo("[wu-ai] Destroyed"),this._eventBus.emit("ai:destroyed",{},{appName:"wu-ai"}))}_ensureInit(){this._initialized||this.init()}_reconfigure(e){e.permissions&&this._modules.permissions.configure(e.permissions),e.rateLimit&&this._modules.permissions.rateLimiter.configure(e.rateLimit),e.circuitBreaker&&this._modules.permissions.circuitBreaker.configure(e.circuitBreaker),e.loopProtection&&this._modules.permissions.loopProtection.configure(e.loopProtection),e.context&&this._modules.context.configure(e.context),e.conversation&&this._modules.conversation.configure(e.conversation),e.triggers&&this._modules.triggers.configure(e.triggers),e.agent&&this._modules.agent.configure(e.agent),e.orchestrate&&this._modules.orchestrate.configure(e.orchestrate)}}function Se(e){let s=null,r=null,i=0,n=!1,o=null;const a=[];function c(t){if(e.ai&&e.ai.permissions)return e.ai.permissions.check(t);return["readStore","executeActions"].includes(t)}function l(t,s,r){e.eventBus&&e.eventBus.emit("mcp:bridge:operation",{operation:t,params:s,result:r?.error?{error:r.error}:{success:!0},timestamp:Date.now()},{appName:"wu-mcp-bridge"})}e.eventBus&&e.eventBus.on("*",e=>{a.push({name:e.name,data:e.data,timestamp:e.timestamp||Date.now(),source:e.source||"unknown"}),a.length>200&&a.shift()}),le();const u={status:()=>({connected:!0,framework:"wu-framework",apps:g(),storeKeys:e.store?Object.keys(e.store.get("")||{}):[],actionsCount:e.ai?e.ai.tools().length:0,eventLogSize:a.length}),list_apps:()=>g(),list_events:({limit:e=20})=>a.slice(-e),list_actions(){if(!e.ai)return{actions:[],note:"wu.ai not initialized"};const t=e.ai.tools();return{actions:t,count:t.length}},snapshot({appName:e}){try{const t=e?document.querySelector(`[data-wu-app="${e}"]`)||document.querySelector(`#wu-app-${e}`):document.body;return t?{app:e||"(page)",snapshot:ue(t,0,5),timestamp:Date.now()}:{error:`App "${e}" not found in DOM`}}catch(e){return{error:e.message}}},console:({level:e="all",limit:t=50})=>fe(e,t),async screenshot({selector:e,quality:t=.8}){const s=await he(e,t);return s.error||(s.timestamp=Date.now()),s},network:({method:e,status:t,limit:s=50})=>ge(e,t,s),get_state({path:t}){if(!e.store)return{error:"wu.store not available"};if(!c("readStore"))return{error:"Permission denied: readStore is disabled"};return{path:t||"(root)",value:e.store.get(t||"")}},set_state:({path:t,value:s})=>e.store?t?c("writeStore")?(e.store.set(t,s),l("set_state",{path:t,value:s},{}),{path:t,value:s,updated:!0}):(l("set_state",{path:t},{error:"Permission denied"}),{error:"Permission denied: writeStore is disabled"}):{error:"path is required"}:{error:"wu.store not available"},emit_event:({event:t,data:s})=>e.eventBus?t?c("emitEvents")?(e.eventBus.emit(t,s,{appName:"wu-mcp-bridge"}),l("emit_event",{event:t,data:s},{}),{emitted:t,data:s}):(l("emit_event",{event:t},{error:"Permission denied"}),{error:"Permission denied: emitEvents is disabled"}):{error:"event name is required"}:{error:"wu.eventBus not available"},navigate:({route:t})=>t?c("emitEvents")?(e.eventBus&&e.eventBus.emit("shell:navigate",{route:t},{appName:"wu-mcp-bridge"}),e.store&&c("writeStore")&&e.store.set("currentPath",t),l("navigate",{route:t},{}),{navigated:t}):(l("navigate",{route:t},{error:"Permission denied: emitEvents"}),{error:"Permission denied: emitEvents is disabled"}):{error:"Route is required"},mount_app({appName:t,container:s}){if(!t)return{error:"appName is required"};if(!c("modifyDOM"))return l("mount_app",{appName:t},{error:"Permission denied"}),{error:"Permission denied: modifyDOM is disabled"};try{return e.mount?(e.mount(t,s),l("mount_app",{appName:t,container:s},{success:!0}),{mounted:t,container:s}):{error:"wu.mount not available"}}catch(e){return{error:e.message}}},unmount_app({appName:t}){if(!t)return{error:"appName is required"};if(!c("modifyDOM"))return l("unmount_app",{appName:t},{error:"Permission denied"}),{error:"Permission denied: modifyDOM is disabled"};try{return e.unmount?(e.unmount(t),l("unmount_app",{appName:t},{success:!0}),{unmounted:t}):{error:"wu.unmount not available"}}catch(e){return{error:e.message}}},click({selector:e,text:t}){if(!c("modifyDOM"))return{error:"Permission denied: modifyDOM is disabled"};const s=pe(e,t);return l("click",{selector:e,text:t},s),s},type({selector:e,text:t,clear:s=!1,submit:r=!1}){if(!c("modifyDOM"))return{error:"Permission denied: modifyDOM is disabled"};const i=me(e,t,{clear:s,submit:r});return l("type",{selector:e,textLength:t?.length},i),i},async execute_action({action:t,params:s}){if(!e.ai)return{error:"wu.ai not available"};if(!t)return{error:"action name is required"};try{return{action:t,...await e.ai.execute(t,s||{})}}catch(e){return{error:e.message}}}};function d(e="ws://localhost:19100",r={}){if(s&&s.readyState<=1)t.warn("[wu-mcp-bridge] Already connected or connecting");else{o=r.token||null,n=!o;try{s=new WebSocket(e),s.onopen=()=>{t.debug("[wu-mcp-bridge] Connected to wu-mcp-server"),i=0,o&&s.send(JSON.stringify({type:"auth",token:o}))},s.onmessage=async e=>{try{const s=JSON.parse(e.data);if("auth_result"===s.type)return n=!0===s.success,void(n?t.debug("[wu-mcp-bridge] Authenticated successfully"):(console.error("[wu-mcp-bridge] Authentication failed:",s.reason||"Invalid token"),h()));if(!n)return void(s.id&&p(s.id,null,"Not authenticated. Send auth token first."));const{id:r,command:i,params:o}=s;if(!r||!i)return void t.warn("[wu-mcp-bridge] Invalid message:",s);const a=u[i];if(!a)return void p(r,null,`Unknown command: ${i}`);try{p(r,await a(o||{}))}catch(e){p(r,null,e.message)}}catch(e){console.error("[wu-mcp-bridge] Failed to handle message:",e)}},s.onclose=()=>{t.debug("[wu-mcp-bridge] Disconnected"),s=null,n=!1,m(e,r)},s.onerror=()=>{}}catch(t){console.error("[wu-mcp-bridge] Connection failed:",t.message),m(e,r)}}}function h(){r&&(clearTimeout(r),r=null),i=10,s&&(s.close(),s=null),n=!1}function p(e,t,r){if(!s||1!==s.readyState)return;const i=r?{id:e,error:r}:{id:e,result:t};s.send(JSON.stringify(i))}function m(e,t){if(i>=10)return;i++;const s=2e3*Math.min(i,5);r=setTimeout(()=>d(e,t),s)}function g(){const t=[];if(e._apps)for(const[s,r]of Object.entries(e._apps))t.push({name:s,mounted:r.mounted||r.isMounted||!1,url:r.url||r.info?.url||"",status:r.status||r.info?.status||"unknown"});return 0===t.length&&document.querySelectorAll("[data-wu-app]").forEach(e=>{t.push({name:e.getAttribute("data-wu-app"),mounted:!0,container:`#${e.id||"(no-id)"}`})}),t}return{connect:d,disconnect:h,isConnected:function(){return null!==s&&1===s.readyState&&n}}}var $e=Object.freeze({__proto__:null,createMcpBridge:Se});if(exports.wu=void 0,"undefined"!=typeof window&&window.wu&&window.wu._isWuFramework?exports.wu=window.wu:(exports.wu=new A,exports.wu._isWuFramework=!0),"undefined"!=typeof window){if(window.wu=exports.wu,exports.wu.version||(exports.wu.version="1.1.8",exports.wu.info={name:"Wu Framework",description:"Universal Microfrontends",features:["Framework Agnostic","Zero Config","Shadow DOM Isolation","Runtime Loading"]}),exports.wu.emit||(exports.wu.emit=(e,t,s)=>exports.wu.eventBus.emit(e,t,s),exports.wu.on=(e,t)=>exports.wu.eventBus.on(e,t),exports.wu.once=(e,t)=>exports.wu.eventBus.once(e,t),exports.wu.off=(e,t)=>exports.wu.eventBus.off(e,t)),exports.wu.prefetch||(exports.wu.prefetch=(e,t)=>exports.wu.prefetcher.prefetch(e,t),exports.wu.prefetchAll=e=>exports.wu.prefetcher.prefetchAll(e)),exports.wu.override||(exports.wu.override=(e,t,s)=>exports.wu.overrides.set(e,t,s),exports.wu.removeOverride=e=>exports.wu.overrides.remove(e),exports.wu.getOverrides=()=>exports.wu.overrides.getAll(),exports.wu.clearOverrides=()=>exports.wu.overrides.clearAll()),exports.wu.silence||(exports.wu.silence=async()=>{const{silenceAllLogs:e}=await Promise.resolve().then(function(){return i});e()},exports.wu.verbose=async()=>{const{enableAllLogs:e}=await Promise.resolve().then(function(){return i});e()}),!exports.wu.ai){let e=null;Object.defineProperty(exports.wu,"ai",{get:()=>(e||(e=new xe({eventBus:exports.wu.eventBus,store:exports.wu.store,core:exports.wu})),e),configurable:!0})}if(!exports.wu.mcp){let e=null;exports.wu.mcp={async connect(t="ws://localhost:19100",s={}){if(!e){const{createMcpBridge:t}=await Promise.resolve().then(function(){return $e});e=t(exports.wu)}e.connect(t,s)},disconnect(){e?.disconnect()},isConnected:()=>e?.isConnected()||!1}}}var ke=exports.wu;exports.WuAI=xe,exports.WuAIActions=V,exports.WuAIAgent=ie,exports.WuAIContext=G,exports.WuAIConversation=X,exports.WuAIOrchestrate=ve,exports.WuAIPermissions=F,exports.WuAIProvider=W,exports.WuAITriggers=te,exports.WuApp=p,exports.WuCache=m,exports.WuCore=A,exports.WuErrorBoundary=_,exports.WuEventBus=g,exports.WuHtmlParser=b,exports.WuIframeSandbox=S,exports.WuLifecycleHooks=v,exports.WuLoader=n,exports.WuLoadingStrategy=y,exports.WuManifest=u,exports.WuOverrides=E,exports.WuPerformance=f,exports.WuPluginSystem=w,exports.WuPrefetch=$,exports.WuProxySandbox=a,exports.WuSandbox=l,exports.WuScriptExecutor=x,exports.WuSnapshotSandbox=c,exports.WuStore=d,exports.WuStyleBridge=o,exports.app=(e,t)=>exports.wu.app(e,t),exports.buildA11yTree=ue,exports.buildToolSchemas=U,exports.captureScreenshot=he,exports.clearOverrides=()=>exports.wu.clearOverrides(),exports.clickElement=pe,exports.createConditionalHook=(e,t)=>async(s,r)=>{await e(s)&&await t(s),await r()},exports.createGuardHook=e=>async(t,s)=>{await e(t)&&await s()},exports.createMcpBridge=Se,exports.createPlugin=e=>({name:e.name,permissions:e.permissions||["events"],install:e.install,uninstall:e.uninstall,beforeInit:e.beforeInit,afterInit:e.afterInit,beforeMount:e.beforeMount,afterMount:e.afterMount,beforeUnmount:e.beforeUnmount,afterUnmount:e.afterUnmount,onError:e.onError,onDestroy:e.onDestroy}),exports.createSimpleHook=e=>async(t,s)=>{await e(t),await s()},exports.createTimedHook=(e,t=5e3)=>async(s,r)=>{const i=new Promise((e,s)=>setTimeout(()=>s(new Error("Hook timeout")),t));try{await Promise.race([e(s),i]),await r()}catch(e){console.error("[WuHooks] Timed hook failed:",e),await r()}},exports.createTransformHook=e=>async(t,s)=>{const r=await e(t);await s(r)},exports.default=ke,exports.define=(e,t)=>exports.wu.define(e,t),exports.destroy=()=>exports.wu.destroy(),exports.emit=(e,t,s)=>exports.wu.eventBus.emit(e,t,s),exports.enableAllLogs=r,exports.endMeasure=(e,t)=>exports.wu.performance.endMeasure(e,t),exports.ensureInterceptors=le,exports.estimateTokens=function(e,t=4){return Math.ceil(e.length/t)},exports.generatePerformanceReport=()=>exports.wu.performance.generateReport(),exports.getFilteredConsole=fe,exports.getFilteredNetwork=ge,exports.getOverrides=()=>exports.wu.getOverrides(),exports.getState=e=>exports.wu.store.get(e),exports.hide=e=>exports.wu.hide(e),exports.init=e=>exports.wu.init({apps:e}),exports.interpolate=q,exports.isHidden=e=>exports.wu.isHidden(e),exports.mount=(e,t)=>exports.wu.mount(e,t),exports.normalizeParameters=J,exports.off=(e,t)=>exports.wu.eventBus.off(e,t),exports.on=(e,t)=>exports.wu.eventBus.on(e,t),exports.onStateChange=(e,t)=>exports.wu.store.on(e,t),exports.once=(e,t)=>exports.wu.eventBus.once(e,t),exports.override=(e,t,s)=>exports.wu.override(e,t,s),exports.prefetch=(e,t)=>exports.wu.prefetch(e,t),exports.prefetchAll=e=>exports.wu.prefetchAll(e),exports.redactSensitive=H,exports.registerBrowserActions=be,exports.removeOverride=e=>exports.wu.removeOverride(e),exports.sanitizeForPrompt=z,exports.setState=(e,t)=>exports.wu.store.set(e,t),exports.show=e=>exports.wu.show(e),exports.silenceAllLogs=s,exports.startMeasure=(e,t)=>exports.wu.performance.startMeasure(e,t),exports.store=h,exports.truncateToTokenBudget=function(e,t,s=4){const r=t*s;return e.length<=r?e:e.slice(0,r)+"\n...[truncated to fit token budget]"},exports.typeIntoElement=me,exports.unmount=(e,t)=>exports.wu.unmount(e,t),exports.useHook=(e,t,s)=>exports.wu.hooks.use(e,t,s),exports.usePlugin=(e,t)=>exports.wu.pluginSystem.use(e,t),exports.validateParams=K;
2
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});class e{constructor(){this.isDevelopment=this.detectEnvironment(),this.logLevel=this.isDevelopment?"warn":"error",this.levels={debug:0,info:1,warn:2,error:3,silent:4}}detectEnvironment(){return"localhost"===window.location.hostname||"127.0.0.1"===window.location.hostname||""!==window.location.port||"undefined"!=typeof process&&"development"===process.env?.NODE_ENV||new URLSearchParams(window.location.search).has("wu-debug")||!0===window.WU_DEBUG}setLevel(e){return this.logLevel=e,this}setDevelopment(e){return this.isDevelopment=e,this.logLevel=e?"debug":"error",this}shouldLog(e){return this.levels[e]>=this.levels[this.logLevel]}debug(...e){this.shouldLog("debug")&&console.log(...e)}info(...e){this.shouldLog("info")&&console.info(...e)}warn(...e){this.shouldLog("warn")&&console.warn(...e)}error(...e){this.shouldLog("error")&&console.error(...e)}wu(e,...t){if(this.shouldLog(e)){console["debug"===e?"log":e]("[Wu]",...t)}}wuDebug(...e){this.wu("debug",...e)}wuInfo(...e){this.wu("info",...e)}wuWarn(...e){this.wu("warn",...e)}wuError(...e){this.wu("error",...e)}}const t=new e;function s(){t.setLevel("silent")}function r(){t.setLevel("debug")}var i=Object.freeze({__proto__:null,WuLogger:e,enableAllLogs:r,logger:t,silenceAllLogs:s});class n{constructor(){this.cache=new Map,this.loadingPromises=new Map,t.debug("[WuLoader] ๐Ÿ“ฆ Dynamic loader initialized")}async loadApp(e,s){const r=`${e}/${s?.entry||"index.js"}`;t.debug(`[WuLoader] ๐Ÿ“ฅ Loading app from: ${r}`);try{if(this.cache.has(r))return t.debug(`[WuLoader] โšก Cache hit for: ${r}`),this.cache.get(r);if(this.loadingPromises.has(r))return t.debug(`[WuLoader] โณ Loading in progress for: ${r}`),await this.loadingPromises.get(r);const e=this.fetchCode(r);this.loadingPromises.set(r,e);const s=await e;return this.loadingPromises.delete(r),this.cache.set(r,s),t.debug(`[WuLoader] โœ… App loaded successfully: ${r}`),s}catch(e){throw this.loadingPromises.delete(r),console.error(`[WuLoader] โŒ Failed to load app: ${r}`,e),new Error(`Failed to load app from ${r}: ${e.message}`)}}async loadComponent(e,s){let r=s;r.startsWith("./")&&(r=r.substring(2)),r.endsWith(".js")||r.endsWith(".jsx")||(r+=".js");const i=`${e}/${r}`;t.debug(`[WuLoader] ๐Ÿงฉ Loading component from: ${i}`);try{const e=await this.loadCode(i),r=new Function("require","module","exports",`\n ${e}\n return typeof module.exports === 'function' ? module.exports :\n typeof module.exports === 'object' && module.exports.default ? module.exports.default :\n exports.default || exports;\n `),n={exports:{}},o=r(e=>(t.warn(`[WuLoader] Component ${s} requires ${e} - not supported yet`),{}),n,n.exports);return t.debug(`[WuLoader] โœ… Component loaded: ${s}`),o}catch(e){throw console.error(`[WuLoader] โŒ Failed to load component: ${s}`,e),new Error(`Failed to load component ${s}: ${e.message}`)}}async loadCode(e){if(this.cache.has(e))return this.cache.get(e);if(this.loadingPromises.has(e))return await this.loadingPromises.get(e);const t=this.fetchCode(e);this.loadingPromises.set(e,t);try{const s=await t;return this.loadingPromises.delete(e),this.cache.set(e,s),s}catch(t){throw this.loadingPromises.delete(e),t}}async fetchCode(e){const t=await fetch(e,{cache:"no-cache",headers:{Accept:"application/javascript, text/javascript, */*"}});if(!t.ok)throw new Error(`HTTP ${t.status}: ${t.statusText}`);const s=await t.text();if(!s.trim())throw new Error("Empty response");return s}async preload(e){t.debug(`[WuLoader] ๐Ÿš€ Preloading ${e.length} apps...`);const s=e.map(async e=>{try{await this.loadApp(e.url,e.manifest),t.debug(`[WuLoader] โœ… Preloaded: ${e.name}`)}catch(s){t.warn(`[WuLoader] โš ๏ธ Failed to preload ${e.name}:`,s.message)}});await Promise.allSettled(s),t.debug("[WuLoader] ๐ŸŽ‰ Preload completed")}async isAvailable(e){try{return(await fetch(e,{method:"HEAD"})).ok}catch{return!1}}async resolveDependencies(e,s){const r=new Map;for(const i of e||[]){const[e,n]=i.split(".");if(!e||!n){t.warn(`[WuLoader] Invalid import format: ${i}`);continue}const o=s.get(e);if(!o){t.warn(`[WuLoader] Import app not found: ${e}`);continue}const a=o.manifest,c=a?.wu?.exports?.[n];if(c)try{const e=await this.loadComponent(o.url,c);r.set(i,e),t.debug(`[WuLoader] โœ… Resolved dependency: ${i}`)}catch(e){console.error(`[WuLoader] โŒ Failed to resolve: ${i}`,e)}else t.warn(`[WuLoader] Export not found: ${i}`)}return r}clearCache(e){if(e){const s=new RegExp(e);for(const[e]of this.cache)s.test(e)&&(this.cache.delete(e),t.debug(`[WuLoader] ๐Ÿ—‘๏ธ Cleared cache for: ${e}`))}else this.cache.clear(),t.debug("[WuLoader] ๐Ÿ—‘๏ธ Cache cleared completely")}getStats(){return{cached:this.cache.size,loading:this.loadingPromises.size,cacheKeys:Array.from(this.cache.keys())}}}class o{constructor(){this.styleObserver=null,this.fullyIsolatedApps=new Map,this.config={autoShareLibraries:["element-plus","vue-flow","@vue-flow","vueuse","@vueuse","normalize.css","reset.css"],sharePatterns:[/\/node_modules\//,/\/@vite\/client/,/\/dist\/index\.css$/,/\/dist\/style\.css$/],mode:"auto",cacheEnabled:!0},t.debug("[WuStyleBridge] ๐ŸŽจ Style sharing system initialized")}registerFullyIsolatedApp(e,s){this.fullyIsolatedApps.set(e,s),t.debug(`[WuStyleBridge] ๐Ÿ›ก๏ธ Registered fully-isolated app: ${e} (${s})`)}isStyleFromFullyIsolatedApp(e){let t="";if("string"==typeof e?t=e:e&&"function"==typeof e.getAttribute?t=e.getAttribute("data-vite-dev-id")||e.href||"":e&&(e.href?t=e.href:e.viteId?t=e.viteId:e.element&&("function"==typeof e.element.getAttribute?t=e.element.getAttribute("data-vite-dev-id")||e.element.href||"":e.element.href&&(t=e.element.href))),!t||""===t.trim())return!1;const s=t.replace(/\\/g,"/").toLowerCase();for(const[e,t]of this.fullyIsolatedApps.entries()){const r=t.replace(/\\/g,"/").toLowerCase(),i=e.toLowerCase();if(r&&s.includes(r))return!0;if(new RegExp(`[/\\\\]${i}[/\\\\]`,"i").test(s))return!0}return!1}detectDocumentStyles(){const e=[];document.querySelectorAll('link[rel="stylesheet"]').forEach(t=>{this.isStyleFromFullyIsolatedApp(t)||e.push({type:"link",href:t.href,element:t,library:this.extractLibraryName(t.href)})});return document.querySelectorAll("style").forEach((s,r)=>{if("true"===s.getAttribute("data-wu-shared"))return;const i=s.getAttribute("data-vite-dev-id"),n=s.textContent;this.isStyleFromFullyIsolatedApp(s)||i&&this.isStyleFromFullyIsolatedApp(i)?t.debug(`[WuStyleBridge] ๐Ÿ›ก๏ธ Filtered out style from fully-isolated app: ${i||"unknown"}`):n&&n.trim().length>0&&e.push({type:"inline",content:n,element:s,viteId:i,library:this.extractLibraryName(i||""),index:r})}),document.adoptedStyleSheets&&document.adoptedStyleSheets.length>0&&document.adoptedStyleSheets.forEach((t,s)=>{e.push({type:"adoptedStyleSheet",sheet:t,index:s})}),t.debug(`[WuStyleBridge] ๐Ÿ” Detected ${e.length} shareable styles`),e}shouldShareStyle(e){if(!e)return!1;if("all"===this.config.mode)return!0;for(const t of this.config.sharePatterns)if(t.test(e))return!0;for(const t of this.config.autoShareLibraries)if(e.includes(t))return!0;return!1}extractLibraryName(e){if(!e)return null;const t=e.match(/\/node_modules\/(@?[^/]+\/[^/]+|@?[^/]+)/);if(t)return t[1];const s=e.match(/\/node_modules\/(.+?)\/.*?\.css/);return s?s[1]:null}async injectStylesIntoShadow(e,s,r){if(!e)return t.warn("[WuStyleBridge] โš ๏ธ No shadow root provided"),0;if("fully-isolated"===r)return t.debug(`[WuStyleBridge] ๐Ÿ›ก๏ธ Style mode "fully-isolated" for ${s}, skipping shared style injection`),0;if("isolated"===r)return t.debug(`[WuStyleBridge] ๐Ÿ”’ Style mode "isolated" for ${s}, using native Shadow DOM encapsulation (no external styles)`),0;t.debug(`[WuStyleBridge] ๐ŸŒ Style mode "shared" for ${s}, injecting all shared styles...`);const i=this.detectDocumentStyles();let n=0;for(const s of i)try{switch(s.type){case"link":await this.injectLinkStyle(e,s),n++;break;case"inline":this.injectInlineStyle(e,s),n++;break;case"adoptedStyleSheet":this.injectAdoptedStyleSheet(e,s),n++}}catch(e){t.warn("[WuStyleBridge] โš ๏ธ Failed to inject style:",e)}return t.debug(`[WuStyleBridge] โœ… Injected ${n} shared styles into ${s}`),n}async injectLinkStyle(e,s){if(e.querySelector(`link[href="${s.href}"]`))return void t.debug(`[WuStyleBridge] โญ๏ธ Style already exists: ${s.library||s.href}`);const r=document.createElement("link");r.rel="stylesheet",r.href=s.href,r.setAttribute("data-wu-shared","true"),r.setAttribute("data-wu-library",s.library||"unknown"),e.insertBefore(r,e.firstChild),t.debug(`[WuStyleBridge] ๐Ÿ”— Injected link: ${s.library||s.href}`)}injectInlineStyle(e,s){const r=s.viteId;if(r){if(e.querySelector(`style[data-wu-vite-id="${r}"]`))return void t.debug(`[WuStyleBridge] โญ๏ธ Inline style already exists: ${r}`)}const i=document.createElement("style");i.textContent=s.content,i.setAttribute("data-wu-shared","true"),i.setAttribute("data-wu-library",s.library||"unknown"),r&&i.setAttribute("data-wu-vite-id",r),e.insertBefore(i,e.firstChild),t.debug(`[WuStyleBridge] ๐Ÿ“ Injected inline style: ${s.library||r}`)}injectAdoptedStyleSheet(e,s){try{if(e.adoptedStyleSheets||(e.adoptedStyleSheets=[]),e.adoptedStyleSheets.includes(s.sheet))return void t.debug("[WuStyleBridge] โญ๏ธ Adopted stylesheet already exists");e.adoptedStyleSheets=[...e.adoptedStyleSheets,s.sheet],t.debug("[WuStyleBridge] ๐Ÿ“‹ Injected adopted stylesheet")}catch(e){t.warn("[WuStyleBridge] โš ๏ธ Failed to inject adopted stylesheet:",e)}}observeStyleChanges(e){this.styleObserver&&this.styleObserver.disconnect(),this.styleObserver=new MutationObserver(s=>{let r=!1;for(const e of s)if("childList"===e.type){if(Array.from(e.addedNodes).some(e=>"LINK"===e.tagName||"STYLE"===e.tagName)){r=!0;break}}r&&e&&(t.debug("[WuStyleBridge] ๐Ÿ”„ Style changes detected"),e())}),this.styleObserver.observe(document.head,{childList:!0,subtree:!0}),t.debug("[WuStyleBridge] ๐Ÿ‘€ Observing style changes")}configure(e){this.config={...this.config,...e},t.debug("[WuStyleBridge] โš™๏ธ Configuration updated:",this.config)}cleanup(){this.styleObserver&&(this.styleObserver.disconnect(),this.styleObserver=null),t.debug("[WuStyleBridge] ๐Ÿงน StyleBridge cleaned up")}getStats(){const e=this.detectDocumentStyles();return{totalStyles:e.length,linkStyles:e.filter(e=>"link"===e.type).length,inlineStyles:e.filter(e=>"inline"===e.type).length,adoptedStyleSheets:e.filter(e=>"adoptedStyleSheet"===e.type).length,libraries:[...new Set(e.map(e=>e.library).filter(Boolean))],config:this.config}}}class a{constructor(e){this.appName=e,this.proxy=null,this.fakeWindow=Object.create(null),this.active=!1,this.modifiedKeys=new Set,this._timers=new Set,this._intervals=new Set,this._rafs=new Set,this._eventListeners=[],this._container=null,this._shadowRoot=null,this._scopedDocument=null,this._scopedLocalStorage=null,this._scopedSessionStorage=null,this._patched=!1,this._originals=null}setContainer(e,t){this._container=e,this._shadowRoot=t}activate(){if(this.active)return this.proxy;const e=this;return this.proxy=new Proxy(window,{get(t,s){if(s in e.fakeWindow)return e.fakeWindow[s];const r=e._intercept(s,t);if(void 0!==r)return r;const i=t[s];return"function"!=typeof i||e._isConstructor(i)?i:i.bind(t)},set:(t,s,r)=>(e.fakeWindow[s]=r,e.modifiedKeys.add(s),!0),has:(t,s)=>s in e.fakeWindow||s in t,deleteProperty:(t,s)=>s in e.fakeWindow&&(delete e.fakeWindow[s],e.modifiedKeys.delete(s),!0)}),this.active=!0,t.wuDebug(`[ProxySandbox] Activated for ${this.appName}`),this.proxy}deactivate(){if(!this.active)return;this.unpatchWindow();for(const e of this._timers)try{clearTimeout(e)}catch{}for(const e of this._intervals)try{clearInterval(e)}catch{}for(const e of this._rafs)try{cancelAnimationFrame(e)}catch{}const e=this._timers.size+this._intervals.size+this._rafs.size;this._timers.clear(),this._intervals.clear(),this._rafs.clear();const s=this._eventListeners.length;for(const{target:e,event:t,handler:s,options:r}of this._eventListeners)try{e.removeEventListener(t,s,r)}catch{}this._eventListeners=[],this.fakeWindow=Object.create(null),this.modifiedKeys.clear(),this._scopedDocument=null,this._scopedLocalStorage=null,this._scopedSessionStorage=null,this.proxy=null,this.active=!1,(e>0||s>0)&&t.wuDebug(`[ProxySandbox] ${this.appName} cleanup: ${e} timers, ${s} listeners`),t.wuDebug(`[ProxySandbox] Deactivated for ${this.appName}`)}patchWindow(){if(this._patched)return;const e=this,s={setTimeout:window.setTimeout,clearTimeout:window.clearTimeout,setInterval:window.setInterval,clearInterval:window.clearInterval,requestAnimationFrame:window.requestAnimationFrame,cancelAnimationFrame:window.cancelAnimationFrame,addEventListener:window.addEventListener,removeEventListener:window.removeEventListener};this._originals=s,window.setTimeout=function(t,r,...i){const n=s.setTimeout.call(window,t,r,...i);return e._patched&&e._timers.add(n),n},window.clearTimeout=function(t){return e._timers.delete(t),s.clearTimeout.call(window,t)},window.setInterval=function(t,r,...i){const n=s.setInterval.call(window,t,r,...i);return e._patched&&e._intervals.add(n),n},window.clearInterval=function(t){return e._intervals.delete(t),s.clearInterval.call(window,t)},window.requestAnimationFrame=function(t){const r=s.requestAnimationFrame.call(window,t);return e._patched&&e._rafs.add(r),r},window.cancelAnimationFrame=function(t){return e._rafs.delete(t),s.cancelAnimationFrame.call(window,t)},window.addEventListener=function(t,r,i){return e._patched&&e._eventListeners.push({target:window,event:t,handler:r,options:i}),s.addEventListener.call(window,t,r,i)},window.removeEventListener=function(t,r,i){return e._eventListeners=e._eventListeners.filter(e=>!(e.target===window&&e.event===t&&e.handler===r)),s.removeEventListener.call(window,t,r,i)},this._patched=!0,t.wuDebug(`[ProxySandbox] Window patched for ${this.appName}`)}unpatchWindow(){this._patched&&this._originals&&(window.setTimeout=this._originals.setTimeout,window.clearTimeout=this._originals.clearTimeout,window.setInterval=this._originals.setInterval,window.clearInterval=this._originals.clearInterval,window.requestAnimationFrame=this._originals.requestAnimationFrame,window.cancelAnimationFrame=this._originals.cancelAnimationFrame,window.addEventListener=this._originals.addEventListener,window.removeEventListener=this._originals.removeEventListener,this._patched=!1,t.wuDebug(`[ProxySandbox] Window unpatched for ${this.appName}`))}_intercept(e,t){const s=this;switch(e){case"setTimeout":return function(e,r,...i){const n=t.setTimeout(e,r,...i);return s._timers.add(n),n};case"clearTimeout":return function(e){s._timers.delete(e),t.clearTimeout(e)};case"setInterval":return function(e,r,...i){const n=t.setInterval(e,r,...i);return s._intervals.add(n),n};case"clearInterval":return function(e){s._intervals.delete(e),t.clearInterval(e)};case"requestAnimationFrame":return function(e){const r=t.requestAnimationFrame(e);return s._rafs.add(r),r};case"cancelAnimationFrame":return function(e){s._rafs.delete(e),t.cancelAnimationFrame(e)};case"addEventListener":return function(e,r,i){s._eventListeners.push({target:t,event:e,handler:r,options:i}),t.addEventListener(e,r,i)};case"removeEventListener":return function(e,r,i){s._eventListeners=s._eventListeners.filter(s=>!(s.target===t&&s.event===e&&s.handler===r)),t.removeEventListener(e,r,i)};case"document":return this._getScopedDocument();case"localStorage":return this._getScopedStorage("local");case"sessionStorage":return this._getScopedStorage("session")}}_getScopedDocument(){if(this._scopedDocument)return this._scopedDocument;const e=this._shadowRoot||this._container;if(!e)return document;const t=this;return this._scopedDocument=new Proxy(document,{get(s,r){switch(r){case"querySelector":return t=>e.querySelector(t);case"querySelectorAll":return t=>e.querySelectorAll(t);case"getElementById":return t=>e.querySelector(`#${CSS.escape(t)}`);case"getElementsByClassName":return t=>e.querySelectorAll(`.${CSS.escape(t)}`);case"getElementsByTagName":return t=>e.querySelectorAll(t);case"addEventListener":return function(e,r,i){t._eventListeners.push({target:s,event:e,handler:r,options:i}),s.addEventListener(e,r,i)};case"removeEventListener":return function(e,r,i){t._eventListeners=t._eventListeners.filter(t=>!(t.target===s&&t.event===e&&t.handler===r)),s.removeEventListener(e,r,i)};default:{const e=s[r];return"function"==typeof e?e.bind(s):e}}}}),this._scopedDocument}_getScopedStorage(e){const t="local"===e?"_scopedLocalStorage":"_scopedSessionStorage";if(this[t])return this[t];const s="local"===e?window.localStorage:window.sessionStorage;if(!s)return s;const r=`wu_${this.appName}_`;return this[t]={getItem:e=>s.getItem(r+e),setItem(e,t){s.setItem(r+e,String(t))},removeItem(e){s.removeItem(r+e)},clear(){const e=[];for(let t=0;t<s.length;t++){const i=s.key(t);i&&i.startsWith(r)&&e.push(i)}e.forEach(e=>s.removeItem(e))},key(e){let t=0;for(let i=0;i<s.length;i++){const n=s.key(i);if(n&&n.startsWith(r)){if(t===e)return n.slice(r.length);t++}}return null},get length(){let e=0;for(let t=0;t<s.length;t++)s.key(t)?.startsWith(r)&&e++;return e}},this[t]}_isConstructor(e){try{return e.prototype&&e.prototype.constructor===e}catch{return!1}}getProxy(){return this.active?this.proxy:null}isActive(){return this.active}getStats(){return{appName:this.appName,active:this.active,patched:this._patched,modifiedKeys:Array.from(this.modifiedKeys),isolatedPropsCount:Object.keys(this.fakeWindow).length,trackedTimers:this._timers.size,trackedIntervals:this._intervals.size,trackedRAFs:this._rafs.size,trackedEventListeners:this._eventListeners.length,hasContainer:!!this._container,hasShadowRoot:!!this._shadowRoot}}}class c{constructor(e){this.appName=e,this.proxy=window,this.snapshot=new Map,this.modifiedKeys=new Set,this.active=!1,this._timers=new Set,this._intervals=new Set,this._rafs=new Set,this._eventListeners=[],this._patched=!1,this._originals=null}activate(){if(this.active)return this.proxy;this.snapshot.clear(),this.modifiedKeys.clear();for(const e in window)try{this.snapshot.set(e,window[e])}catch{}return this.active=!0,t.wuDebug(`[SnapshotSandbox] Activated for ${this.appName} (${this.snapshot.size} props)`),this.proxy}deactivate(){if(!this.active)return;this.unpatchWindow();for(const e of this._timers)try{clearTimeout(e)}catch{}for(const e of this._intervals)try{clearInterval(e)}catch{}for(const e of this._rafs)try{cancelAnimationFrame(e)}catch{}const e=this._timers.size+this._intervals.size+this._rafs.size;this._timers.clear(),this._intervals.clear(),this._rafs.clear();const s=this._eventListeners.length;for(const{target:e,event:t,handler:s,options:r}of this._eventListeners)try{e.removeEventListener(t,s,r)}catch{}this._eventListeners=[];let r=0,i=0;for(const e in window)try{const t=window[e],s=this.snapshot.get(e);if(t!==s)if(this.snapshot.has(e))window[e]=s,r++;else try{delete window[e],i++}catch{}}catch{}this.snapshot.clear(),this.modifiedKeys.clear(),this.active=!1,(e>0||s>0)&&t.wuDebug(`[SnapshotSandbox] ${this.appName} cleanup: ${e} timers, ${s} listeners, ${r} restored, ${i} deleted`),t.wuDebug(`[SnapshotSandbox] Deactivated for ${this.appName}`)}patchWindow(){if(this._patched)return;const e=this,s={setTimeout:window.setTimeout,clearTimeout:window.clearTimeout,setInterval:window.setInterval,clearInterval:window.clearInterval,requestAnimationFrame:window.requestAnimationFrame,cancelAnimationFrame:window.cancelAnimationFrame,addEventListener:window.addEventListener,removeEventListener:window.removeEventListener};this._originals=s,window.setTimeout=function(t,r,...i){const n=s.setTimeout.call(window,t,r,...i);return e._patched&&e._timers.add(n),n},window.clearTimeout=function(t){return e._timers.delete(t),s.clearTimeout.call(window,t)},window.setInterval=function(t,r,...i){const n=s.setInterval.call(window,t,r,...i);return e._patched&&e._intervals.add(n),n},window.clearInterval=function(t){return e._intervals.delete(t),s.clearInterval.call(window,t)},window.requestAnimationFrame=function(t){const r=s.requestAnimationFrame.call(window,t);return e._patched&&e._rafs.add(r),r},window.cancelAnimationFrame=function(t){return e._rafs.delete(t),s.cancelAnimationFrame.call(window,t)},window.addEventListener=function(t,r,i){return e._patched&&e._eventListeners.push({target:window,event:t,handler:r,options:i}),s.addEventListener.call(window,t,r,i)},window.removeEventListener=function(t,r,i){return e._eventListeners=e._eventListeners.filter(e=>!(e.target===window&&e.event===t&&e.handler===r)),s.removeEventListener.call(window,t,r,i)},this._patched=!0,t.wuDebug(`[SnapshotSandbox] Window patched for ${this.appName}`)}unpatchWindow(){this._patched&&this._originals&&(window.setTimeout=this._originals.setTimeout,window.clearTimeout=this._originals.clearTimeout,window.setInterval=this._originals.setInterval,window.clearInterval=this._originals.clearInterval,window.requestAnimationFrame=this._originals.requestAnimationFrame,window.cancelAnimationFrame=this._originals.cancelAnimationFrame,window.addEventListener=this._originals.addEventListener,window.removeEventListener=this._originals.removeEventListener,this._patched=!1,t.wuDebug(`[SnapshotSandbox] Window unpatched for ${this.appName}`))}getProxy(){return this.active?this.proxy:null}isActive(){return this.active}getStats(){return{appName:this.appName,active:this.active,patched:this._patched,snapshotSize:this.snapshot.size,trackedTimers:this._timers.size,trackedIntervals:this._intervals.size,trackedRAFs:this._rafs.size,trackedEventListeners:this._eventListeners.length}}}class l{constructor(){this.sandboxes=new Map,this.styleBridge=new o,this.jsSandboxes=new Map,this.sandboxStrategy=this.detectSandboxStrategy(),t.wuDebug(`Advanced isolation system initialized (strategy: ${this.sandboxStrategy})`)}detectSandboxStrategy(){if("undefined"!=typeof Proxy)try{return new Proxy({},{get:(e,t)=>e[t]}).test="value",t.wuDebug("Proxy available - using ProxySandbox strategy"),"proxy"}catch(e){return t.wuWarn("Proxy not working - falling back to SnapshotSandbox"),"snapshot"}return t.wuWarn("Proxy not available - using SnapshotSandbox strategy"),"snapshot"}create(e,s,r={}){t.wuDebug(`Creating sandbox for: ${e}`);try{if(!s.attachShadow)throw new Error("Shadow DOM not supported in this browser");let i;s.shadowRoot?(t.wuDebug(`Existing shadow root detected for ${e}, performing cleanup...`),s.shadowRoot.innerHTML="",i=s.shadowRoot,t.wuDebug(`Existing shadow root cleaned and reused for ${e}`)):(i=s.attachShadow({mode:"open",delegatesFocus:!0}),t.wuDebug(`New shadow root created for ${e}`));const n=document.createElement("div");n.id=`wu-app-${e}`,n.className="wu-app-root",n.setAttribute("data-wu-enhanced","true"),n.setAttribute("data-wu-timestamp",Date.now().toString());const o=document.createElement("style");o.textContent=this.generateSandboxStyles(e),i.appendChild(o),i.appendChild(n);const a=this.createAdvancedJSSandbox(e);a.setContainer&&a.setContainer(n,i);const c=a.activate(),l=r.styleMode||r.manifest?.styleMode,u={appName:e,shadowRoot:i,container:n,hostContainer:s,jsSandbox:a,jsProxy:c,styles:o,styleMode:l,manifest:r.manifest,created:Date.now(),sandbox_state:"stable",recovery_count:0};if("isolated"===l)t.wuDebug(`Style mode "isolated" for ${e}, using native Shadow DOM encapsulation`),u.stylesReady=Promise.resolve(0);else if("fully-isolated"===l){t.wuDebug(`Style mode "fully-isolated" detected for ${e}, using enhanced style injection`);const s=r.appUrl||(r.manifest?.name?`/${r.manifest.name}/`:`/${e}/`);this.styleBridge.registerFullyIsolatedApp(e,s),u.appUrl=s;const n=this;u.stylesReady=new Promise(r=>{let o=!1;const a=async()=>{const a=await n.injectOwnStylesToShadow(i,e,s);return a>0&&(t.wuDebug(`Injected ${a} own styles for ${e} (fully-isolated)`),o||(o=!0,r(a))),a};t.wuDebug(`Setting up style observer for ${e} (fully-isolated)`);const c=new MutationObserver(s=>{let r=0;for(const i of s)if("childList"===i.type)for(const s of i.addedNodes)if("STYLE"===s.nodeName||"LINK"===s.nodeName){r++;const i=s.getAttribute?s.getAttribute("data-vite-dev-id"):null;i&&i.toLowerCase().includes(e.toLowerCase())&&t.wuDebug(`New ${e} style detected: ${i.split("/").pop()}`)}r>0&&(t.wuDebug(`${r} new styles detected in head, checking for ${e}...`),a())});c.observe(document.head,{childList:!0,subtree:!0}),u.styleObserver=c,setTimeout(async()=>{await a();o||setTimeout(()=>{if(!o){t.wuWarn(`No own styles found for ${e} after timeout, using FALLBACK`);const s=n.injectAllStylesToShadow(i,e);t.wuDebug(`FALLBACK: Injected ${s} styles for ${e}`),o=!0,r(s)}},3e3)},50)})}else t.wuDebug(`Style mode "shared" for ${e}, injecting all shared styles...`),u.stylesReady=this.styleBridge.injectStylesIntoShadow(i,e,l).then(s=>(t.wuDebug(`Shared ${s} styles with ${e}`),this.styleBridge.observeStyleChanges(()=>{t.wuDebug(`Reinjecting styles for ${e} due to changes`),this.styleBridge.injectStylesIntoShadow(i,e,l).catch(e=>{t.wuWarn(`Failed to reinject styles: ${e}`)})}),s)).catch(e=>(t.wuWarn(`Failed to inject styles: ${e}`),0));return this.sandboxes.set(e,u),t.wuDebug(`Enhanced sandbox created for ${e}`),u}catch(r){if(t.wuError(`Failed to create sandbox for ${e}: ${r}`),r.message.includes("Shadow root cannot be created"))return this.createFallbackSandbox(e,s);throw r}}createFallbackSandbox(e,s){t.wuDebug(`Creating fallback sandbox for ${e}...`);try{s.shadowRoot&&(s.shadowRoot.innerHTML="");const r=document.createElement("div");r.id=`wu-app-${e}`,r.className="wu-app-root wu-fallback",r.style.cssText="\n width: 100%;\n height: 100%;\n isolation: isolate;\n contain: layout style paint;\n ",s.innerHTML="",s.appendChild(r);const i={appName:e,shadowRoot:null,container:r,hostContainer:s,styles:null,created:Date.now(),sandbox_state:"fallback_mode",recovery_count:1,fallback_mode:!0};return this.sandboxes.set(e,i),t.wuDebug(`Fallback sandbox created successfully for ${e}`),i}catch(e){throw t.wuError(`Fallback sandbox creation failed: ${e}`),e}}generateSandboxStyles(e){return`\n /* Wu Framework - Shadow DOM Isolation Styles */\n :host {\n display: block;\n width: 100%;\n height: 100%;\n box-sizing: border-box;\n contain: layout style paint;\n --wu-sandbox-active: true;\n --wu-isolation-state: stable;\n }\n\n .wu-app-root {\n width: 100%;\n height: 100%;\n box-sizing: border-box;\n isolation: isolate;\n position: relative;\n overflow: hidden;\n }\n\n /* Loading animation for sandbox initialization */\n .wu-app-root[data-wu-loading="true"] {\n background: linear-gradient(45deg,\n rgba(74, 144, 226, 0.1) 0%,\n rgba(80, 227, 194, 0.1) 100%);\n animation: sandboxPulse 2s ease-in-out infinite;\n }\n\n @keyframes sandboxPulse {\n 0%, 100% { opacity: 0.8; }\n 50% { opacity: 1; }\n }\n\n /* CSS reset for shadow DOM stability */\n * {\n box-sizing: border-box;\n }\n\n /* CSS custom properties for sandbox */\n :host {\n --wu-app-name: "${e}";\n --wu-isolation: true;\n --wu-creation-timestamp: ${Date.now()};\n }\n\n /* ๐Ÿ›ก๏ธ Debug mode enhancements */\n :host([wu-debug]) {\n border: 2px dashed #4a90e2;\n background: rgba(74, 144, 226, 0.05);\n box-shadow: 0 0 10px rgba(74, 144, 226, 0.3);\n }\n\n :host([wu-debug])::before {\n content: "Wu Framework: " attr(wu-app);\n position: absolute;\n top: 0;\n left: 0;\n background: linear-gradient(45deg, #4a90e2, #50e3c2);\n color: white;\n padding: 4px 8px;\n font-size: 11px;\n font-family: 'SF Mono', Monaco, 'Cascadia Code', 'Roboto Mono', Consolas, 'Courier New', monospace;\n z-index: 10000;\n border-radius: 0 0 4px 0;\n font-weight: 600;\n }\n\n /* Sandbox state indicators */\n :host([data-sandbox-state="stable"]) {\n --wu-isolation-state: stable;\n }\n\n :host([data-sandbox-state="healing"]) {\n --wu-dimensional-stability: healing;\n animation: sandboxHealing 1s ease-in-out infinite;\n }\n\n @keyframes sandboxHealing {\n 0%, 100% { filter: hue-rotate(0deg); }\n 50% { filter: hue-rotate(180deg); }\n }\n `}createAdvancedJSSandbox(e){let s;return"proxy"===this.sandboxStrategy?(s=new a(e),t.wuDebug(`Created ProxySandbox for ${e}`)):(s=new c(e),t.wuDebug(`Created SnapshotSandbox for ${e}`)),this.jsSandboxes.set(e,s),s}addStyles(e,s){const r=this.sandboxes.get(e);if(!r)return void t.wuWarn(`Sandbox not found for: ${e}`);const i=document.createElement("style");i.textContent=s,i.setAttribute("wu-custom-styles",""),r.shadowRoot.appendChild(i),t.wuDebug(`Custom styles added to ${e}`)}loadExternalStyles(e,s){const r=this.sandboxes.get(e);if(!r)return void t.wuWarn(`Sandbox not found for: ${e}`);const i=document.createElement("link");i.rel="stylesheet",i.href=s,i.setAttribute("wu-external-styles",""),r.shadowRoot.appendChild(i),t.wuDebug(`External styles loaded in ${e}: ${s}`)}setDebugMode(e,s=!0){const r=this.sandboxes.get(e);r?(s?(r.hostContainer.setAttribute("wu-debug",""),r.hostContainer.setAttribute("wu-app",e)):(r.hostContainer.removeAttribute("wu-debug"),r.hostContainer.removeAttribute("wu-app")),t.wuDebug(`Debug mode ${s?"enabled":"disabled"} for ${e}`)):t.wuWarn(`Sandbox not found for: ${e}`)}cleanup(e){if(!e)return;const{appName:s,shadowRoot:r,hostContainer:i,jsSandbox:n}=e;t.wuDebug(`Cleaning up sandbox for: ${s}`);try{n&&n.isActive()&&(n.deactivate(),t.wuDebug(`JS Sandbox deactivated for ${s}`)),this.cleanupEventListeners(e),r&&(r.innerHTML=""),i&&(i.removeAttribute("wu-debug"),i.removeAttribute("wu-app"),i.removeAttribute("wu-no-scroll")),this.sandboxes.delete(s),this.jsSandboxes.delete(s),t.wuDebug(`Sandbox cleaned up: ${s}`)}catch(e){t.wuError(`Error cleaning up sandbox ${s}: ${e}`)}}cleanupEventListeners(e){const{shadowRoot:t}=e;if(!t)return;t.querySelectorAll("*").forEach(e=>{if(e.cloneNode){const t=e.cloneNode(!0);e.parentNode?.replaceChild(t,e)}})}getSandboxInfo(e){const t=this.sandboxes.get(e);return t?{appName:t.appName,created:t.created,hasContainer:!!t.container,hasShadowRoot:!!t.shadowRoot,elementCount:t.shadowRoot?.children?.length||0,uptime:Date.now()-t.created}:null}getStats(){return{strategy:this.sandboxStrategy,total:this.sandboxes.size,sandboxes:Array.from(this.sandboxes.keys()),jsSandboxes:Array.from(this.jsSandboxes.keys()),details:Array.from(this.sandboxes.entries()).map(([e,t])=>({name:e,uptime:Date.now()-t.created,elements:t.shadowRoot?.children?.length||0,hasJsSandbox:!!t.jsSandbox,jsSandboxActive:t.jsSandbox?.isActive()||!1}))}}cleanupAll(){t.wuDebug(`Cleaning up all ${this.sandboxes.size} sandboxes...`);for(const[e,t]of this.sandboxes)this.cleanup(t);this.styleBridge&&this.styleBridge.cleanup(),t.wuDebug("All sandboxes cleaned up")}configureStyleSharing(e){this.styleBridge&&(this.styleBridge.configure(e),t.wuDebug("StyleBridge configured"))}getStyleStats(){return this.styleBridge?this.styleBridge.getStats():null}async reinjectStyles(e){const s=this.sandboxes.get(e);if(!s||!s.shadowRoot)return void t.wuWarn(`Cannot reinject styles for ${e}`);const r=s.styleMode;if("isolated"===r)return void t.wuDebug(`Skipping reinject for ${e} (isolated mode - app manages own styles)`);if("fully-isolated"===r){t.wuDebug(`Reinjecting OWN styles for ${e} (fully-isolated)...`);const r=s.appUrl||s.manifest?.name?`/${s.manifest.name}/`:`/${e}/`,i=await this.injectOwnStylesToShadow(s.shadowRoot,e,r);return void t.wuDebug(`Reinjected ${i} own styles for ${e}`)}t.wuDebug(`Reinjecting shared styles for ${e}...`);const i=await this.styleBridge.injectStylesIntoShadow(s.shadowRoot,e,r);t.wuDebug(`Reinjected ${i} shared styles`)}async injectOwnStylesToShadow(e,s,r){if(!e)return 0;let i=0;const n=document.querySelectorAll("style"),o=s.toLowerCase(),a=[new RegExp(`packages[/\\\\]${o}[/\\\\]src[/\\\\]`,"i")];t.wuDebug(`Searching own styles for ${s}, found ${n.length} style tags in head`);let c=0;for(const e of n){(e.getAttribute("data-vite-dev-id")||"").toLowerCase().includes(o)&&c++}c>0&&t.wuDebug(`Found ${c} styles potentially matching ${s}`);for(const r of n){const n=r.getAttribute("data-vite-dev-id")||"",o=n.replace(/\\/g,"/").toLowerCase();let c=!1;if(n)for(const e of a)if(e instanceof RegExp){if(e.test(n)){c=!0;break}}else if(o.includes(e.toLowerCase())){c=!0;break}if(c){if(!e.querySelector(`style[data-vite-dev-id="${n}"]`)){const o=r.cloneNode(!0);o.setAttribute("data-wu-injected","true"),e.insertBefore(o,e.firstChild),i++;const a=n.substring(n.lastIndexOf("/")+1)||n.substring(n.lastIndexOf("\\")+1);t.wuDebug(`Injected own style for ${s}: ${a}`)}}}return t.wuDebug(`Total own styles injected for ${s}: ${i}`),i}injectAllStylesToShadow(e,s){if(!e)return 0;let r=0;const i=s.toLowerCase(),n=document.querySelectorAll("style");for(const s of n){const n=s.getAttribute("data-vite-dev-id")||"";if(!n.toLowerCase().includes(i))continue;if(e.querySelector(`style[data-vite-dev-id="${n}"]`))continue;const o=s.cloneNode(!0);o.setAttribute("data-wu-fallback","true"),e.insertBefore(o,e.firstChild),r++;const a=n.split("/").pop()||n.split("\\").pop();t.wuDebug(`FALLBACK injected: ${a}`)}return t.wuDebug(`FALLBACK: Total ${r} styles injected for ${s}`),r}}class u{constructor(){this.cache=new Map,this.schemas=new Map,this.security={maxManifestSize:102400,maxNameLength:50,maxEntryLength:200,maxExports:100,maxImports:50,maxRoutes:100,dangerousPatterns:[/\.\./,/^\/etc\//,/^\/proc\//,/^file:\/\//,/javascript:/i,/data:/i,/<script/i,/on\w+\s*=/i],blockedDomains:["evil.com","malware.com"]},this.defineSchema()}defineSchema(){this.schemas.set("wu.json",{required:["name","entry"],optional:["wu"],wu:{optional:["exports","imports","routes","permissions"],exports:"object",imports:"array",routes:"array",permissions:"array"}})}async load(e){const s=`${e}/wu.json`;t.debug(`[WuManifest] ๐Ÿ“ฅ Loading manifest: ${s}`);try{if(this.cache.has(s))return t.debug(`[WuManifest] โšก Cache hit: ${s}`),this.cache.get(s);const r=await fetch(s,{cache:"no-cache",headers:{Accept:"application/json"}});if(!r.ok){if(404===r.status)return t.debug(`[WuManifest] ๐Ÿ“„ No manifest found, creating default for: ${e}`),this.createDefaultManifest(e);throw new Error(`HTTP ${r.status}: ${r.statusText}`)}const i=await r.text();if(i.length>this.security.maxManifestSize)throw new Error(`Manifest too large (${i.length} bytes, max ${this.security.maxManifestSize})`);let n;try{n=JSON.parse(i)}catch(e){throw new Error(`Invalid JSON in manifest: ${e.message}`)}const o=this.validate(n);return this.cache.set(s,o),t.debug(`[WuManifest] โœ… Manifest loaded: ${n.name}`),o}catch(t){console.error(`[WuManifest] โŒ Failed to load manifest: ${s}`,t);try{return this.createDefaultManifest(e)}catch(e){throw new Error(`Failed to load manifest from ${s}: ${t.message}`)}}}createDefaultManifest(e){const s=this.extractAppNameFromUrl(e),r={name:s,entry:"index.js",wu:{exports:{},imports:[],routes:[],permissions:[]}};return t.debug(`[WuManifest] ๐Ÿ”ง Created default manifest for: ${s}`),r}extractAppNameFromUrl(e){try{const t=new URL(e).pathname.split("/").filter(Boolean);return t[t.length-1]||"unknown-app"}catch{return e.replace(/[^a-zA-Z0-9-]/g,"")||"unknown-app"}}_sanitizeString(e){return"string"!=typeof e?"":e.replace(/[<>'"]/g,"").replace(/[\x00-\x1F\x7F]/g,"").trim()}_hasDangerousPatterns(e){return"string"==typeof e&&this.security.dangerousPatterns.some(t=>t.test(e))}_isUrlSafe(e){if("string"!=typeof e)return!1;if(this._hasDangerousPatterns(e))return!1;try{const t=new URL(e,"http://localhost");if(this.security.blockedDomains.some(e=>t.hostname.includes(e)))return!1}catch{if(this._hasDangerousPatterns(e))return!1}return!0}validate(e){const t=this.schemas.get("wu.json");if(!e||"object"!=typeof e||Array.isArray(e))throw new Error("Manifest must be a valid object");for(const s of t.required)if(!e[s])throw new Error(`Required field missing: ${s}`);if("string"!=typeof e.name)throw new Error("name must be a string");if(e.name.length>this.security.maxNameLength)throw new Error(`name too long (max ${this.security.maxNameLength} chars)`);if(this._hasDangerousPatterns(e.name))throw new Error("name contains dangerous patterns");if("string"!=typeof e.entry)throw new Error("entry must be a string");if(e.entry.length>this.security.maxEntryLength)throw new Error(`entry too long (max ${this.security.maxEntryLength} chars)`);if(!this._isUrlSafe(e.entry))throw new Error("entry contains dangerous patterns");if(e.wu){const t=e.wu;if(t.exports&&"object"!=typeof t.exports)throw new Error("wu.exports must be an object");if(t.exports&&Object.keys(t.exports).length>this.security.maxExports)throw new Error(`Too many exports (max ${this.security.maxExports})`);if(t.exports)for(const[e,s]of Object.entries(t.exports))if(!this._isUrlSafe(s))throw new Error(`Dangerous export path: ${e}`);if(t.imports&&!Array.isArray(t.imports))throw new Error("wu.imports must be an array");if(t.imports&&t.imports.length>this.security.maxImports)throw new Error(`Too many imports (max ${this.security.maxImports})`);if(t.routes&&!Array.isArray(t.routes))throw new Error("wu.routes must be an array");if(t.routes&&t.routes.length>this.security.maxRoutes)throw new Error(`Too many routes (max ${this.security.maxRoutes})`);if(t.permissions&&!Array.isArray(t.permissions))throw new Error("wu.permissions must be an array")}return this.normalize(e)}normalize(e){const s={name:e.name.trim(),entry:this.normalizeEntry(e.entry),wu:{exports:e.wu?.exports||{},imports:e.wu?.imports||[],routes:e.wu?.routes||[],permissions:e.wu?.permissions||[]}};if(e.styleMode&&(s.styleMode=e.styleMode),e.version&&(s.version=e.version),e.folder&&(s.folder=e.folder),s.wu.exports){const e={};for(const[t,r]of Object.entries(s.wu.exports))e[t]=this.normalizeComponentPath(r);s.wu.exports=e}return s.wu.imports=s.wu.imports.filter(e=>!("string"!=typeof e||!e.includes("."))||(t.warn(`[WuManifest] Invalid import format: ${e}`),!1)),s}normalizeEntry(e){if(!e)return"index.js";let t=e.trim();return t.startsWith("./")&&(t=t.substring(2)),t.includes(".")||(t+=".js"),t}normalizeComponentPath(e){if(!e)return"";let t=e.trim();return t.startsWith("./")&&(t=t.substring(2)),t.includes(".")||(t+=".js"),t}validateDependencies(e,t){const s={valid:[],invalid:[],missing:[]};for(const r of e){const[e,i]=r.split(".");if(!e||!i){s.invalid.push({import:r,reason:'Invalid format. Use "app.component"'});continue}const n=t.get(e);if(!n){s.missing.push({import:r,app:e,reason:"App not registered"});continue}const o=n.manifest,a=o?.wu?.exports?.[i];a?s.valid.push({import:r,app:e,component:i,path:a}):s.invalid.push({import:r,reason:`Component ${i} not exported by ${e}`})}return s}create(e,t={}){const s={name:e,entry:t.entry||"index.js",wu:{exports:t.exports||{},imports:t.imports||[],routes:t.routes||[],permissions:t.permissions||[]}};return this.normalize(s)}clearCache(e){if(e){const s=new RegExp(e);for(const[e]of this.cache)s.test(e)&&(this.cache.delete(e),t.debug(`[WuManifest] ๐Ÿ—‘๏ธ Cleared cache for: ${e}`))}else this.cache.clear(),t.debug("[WuManifest] ๐Ÿ—‘๏ธ Manifest cache cleared completely")}getStats(){return{cached:this.cache.size,schemas:this.schemas.size,cacheKeys:Array.from(this.cache.keys())}}}class d{constructor(e=256){this.bufferSize=this.nextPowerOfTwo(e),this.mask=this.bufferSize-1,this.buffer=new Array(this.bufferSize),this.cursor=0,this.state={},this.listeners=new Map,this.patternListeners=new Map,this.metrics={reads:0,writes:0,notifications:0};for(let e=0;e<this.bufferSize;e++)this.buffer[e]={path:null,value:null,timestamp:0}}get(e){return this.metrics.reads++,e?e.split(".").reduce((e,t)=>e?.[t],this.state):this.state}set(e,t){this.metrics.writes++;const s=this.cursor++,r=s&this.mask,i=this.buffer[r];return i.path=e,i.value=t,i.timestamp=performance.now(),this.updateState(e,t),queueMicrotask(()=>{this.notify(e,t),this.notifyPatterns(e,t)}),s}on(e,t){return e.includes("*")?(this.patternListeners.has(e)||this.patternListeners.set(e,new Set),this.patternListeners.get(e).add(t),()=>{const s=this.patternListeners.get(e);s&&(s.delete(t),0===s.size&&this.patternListeners.delete(e))}):(this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t),()=>{const s=this.listeners.get(e);s&&(s.delete(t),0===s.size&&this.listeners.delete(e))})}batch(e){const t=[];for(const[s,r]of Object.entries(e))t.push(this.set(s,r));return t}getMetrics(){return{...this.metrics,bufferUtilization:this.cursor%this.bufferSize/this.bufferSize,listenerCount:this.listeners.size+this.patternListeners.size}}nextPowerOfTwo(e){return Math.pow(2,Math.ceil(Math.log2(e)))}updateState(e,t){if(!e)return void(this.state=t);const s=e.split("."),r=s.pop();let i=this.state;for(const e of s)e in i&&"object"==typeof i[e]||(i[e]={}),i=i[e];i[r]=t}notify(e,t){this.metrics.notifications++;const s=this.listeners.get(e);s&&s.forEach(s=>{try{s(t,e)}catch(e){console.error("[WuStore] Listener error:",e)}});const r=e.split(".");for(let e=r.length-1;e>0;e--){const t=r.slice(0,e).join("."),s=this.listeners.get(t);if(s){const e=this.get(t);s.forEach(s=>{try{s(e,t)}catch(e){console.error("[WuStore] Parent listener error:",e)}})}}}notifyPatterns(e,t){for(const[s,r]of this.patternListeners)this.matchesPattern(e,s)&&r.forEach(s=>{try{s({path:e,value:t})}catch(e){console.error("[WuStore] Pattern listener error:",e)}})}matchesPattern(e,t){if("*"===t)return!0;const s=t.split(".").map(e=>"*"===e?"[^.]+":e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("\\.");return new RegExp(`^${s}$`).test(e)}clear(){this.state={},this.listeners.clear(),this.patternListeners.clear(),this.cursor=0;for(let e=0;e<this.bufferSize;e++)this.buffer[e].path=null,this.buffer[e].value=null,this.buffer[e].timestamp=0}getRecentEvents(e=10){const t=[];for(let s=Math.max(0,this.cursor-e);s<this.cursor&&t.length<e;s++){const e=s&this.mask,r=this.buffer[e];r.path&&t.push({path:r.path,value:r.value,timestamp:r.timestamp})}return t.reverse()}}const h=new d;class p{constructor(e,t,s){this.name=e,this.url=t.url,this.container=t.container,this.keepAlive=t.keepAlive||!1,this._wu=s,this._mounted=!1,this._autoInit=!1!==t.autoInit,this._autoInit&&this._registerApp()}_registerApp(){this._wu.apps.has(this.name)||(this._wu.apps.set(this.name,{name:this.name,url:this.url,keepAlive:this.keepAlive,status:"registered"}),t.debug(`๐Ÿ“ฆ App registered: ${this.name} at ${this.url}`))}async mount(e){const t=e||this.container;if(!t)throw new Error(`Container not specified for app: ${this.name}`);return this._wu.isInitialized||await this._wu.init({apps:[{name:this.name,url:this.url}]}),await this._wu.mount(this.name,t),this._mounted=!0,this}async unmount(e={}){return this._mounted||this._wu.isHidden(this.name)?(await this._wu.unmount(this.name,e),this._mounted=!this._wu.isHidden(this.name),this):(t.warn(`โš ๏ธ App ${this.name} is not mounted`),this)}async hide(){return this._mounted?(await this._wu.hide(this.name),this._mounted=!1,this):(t.warn(`โš ๏ธ App ${this.name} is not mounted`),this)}async show(){return this._wu.isHidden(this.name)?(await this._wu.show(this.name),this._mounted=!0,this):(t.warn(`โš ๏ธ App ${this.name} is not in keep-alive state`),this)}async remount(e){return await this.unmount({force:!0}),await this.mount(e),this}get isMounted(){return this._mounted&&this._wu.mounted?.has(this.name)}get isHidden(){return this._wu.isHidden(this.name)}get info(){return{name:this.name,url:this.url,container:this.container,mounted:this.isMounted,status:this._wu.apps.get(this.name)?.status||"unknown"}}async reload(){return t.debug(`๐Ÿ”„ Reloading app: ${this.name}`),await this.unmount(),this._wu.loader?.clearCache&&this._wu.loader.clearCache(this.name),this._wu.manifest?.clearCache&&this._wu.manifest.clearCache(this.name),await this.mount(),t.debug(`โœ… App reloaded: ${this.name}`),this}async verify(){const e=document.querySelector(this.container),t=null!==e?.shadowRoot,s=(e?.shadowRoot?.children?.length||0)>0;return{name:this.name,mounted:this.isMounted,container:{found:!!e,selector:this.container,hasShadowDOM:t,hasContent:s},wu:{registered:this._wu.apps.has(this.name),mountedInWu:this._wu.mounted?.has(this.name)}}}async start(e){return await this.mount(e)}async stop(){return await this.unmount()}async destroy(){await this.unmount({force:!0}),this._wu.apps.delete(this.name),this._mounted=!1,t.debug(`๐Ÿ—‘๏ธ App destroyed: ${this.name}`)}}class m{constructor(e={}){this.config={maxSize:e.maxSize||50,maxItems:e.maxItems||100,defaultTTL:e.defaultTTL||36e5,persistent:!1!==e.persistent,storage:e.storage||"memory"},this.rateLimiting={enabled:!1!==e.rateLimiting,maxOpsPerSecond:e.maxOpsPerSecond||100,windowMs:1e3,cooldownMs:e.cooldownMs||5e3,operations:[],inCooldown:!1,cooldownUntil:0},this.memoryCache=new Map,this.accessOrder=new Map,this.stats={hits:0,misses:0,sets:0,evictions:0,size:0,rateLimited:0}}_checkRateLimit(){if(!this.rateLimiting.enabled)return!0;const e=Date.now();if(this.rateLimiting.inCooldown){if(e<this.rateLimiting.cooldownUntil)return this.stats.rateLimited++,!1;this.rateLimiting.inCooldown=!1,this.rateLimiting.operations=[]}const s=e-this.rateLimiting.windowMs;return this.rateLimiting.operations=this.rateLimiting.operations.filter(e=>e>s),this.rateLimiting.operations.length>=this.rateLimiting.maxOpsPerSecond?(this.rateLimiting.inCooldown=!0,this.rateLimiting.cooldownUntil=e+this.rateLimiting.cooldownMs,this.stats.rateLimited++,t.warn(`[WuCache] ๐Ÿšซ Rate limit exceeded. Cooldown for ${this.rateLimiting.cooldownMs}ms`),!1):(this.rateLimiting.operations.push(e),!0)}getRateLimitStatus(){const e=Date.now();return{enabled:this.rateLimiting.enabled,inCooldown:this.rateLimiting.inCooldown,cooldownRemaining:this.rateLimiting.inCooldown?Math.max(0,this.rateLimiting.cooldownUntil-e):0,currentOps:this.rateLimiting.operations.length,maxOps:this.rateLimiting.maxOpsPerSecond,rateLimited:this.stats.rateLimited}}get(e){if(!this._checkRateLimit())return null;if(this.memoryCache.has(e)){const t=this.memoryCache.get(e);return this.isExpired(t)?(this.delete(e),this.stats.misses++,null):(this.accessOrder.set(e,Date.now()),this.stats.hits++,t.value)}if(this.config.persistent){const t=this.getFromStorage(e);if(t)return this.memoryCache.set(e,t),this.accessOrder.set(e,Date.now()),this.stats.hits++,t.value}return this.stats.misses++,null}set(e,s,r){if(!this._checkRateLimit())return!1;try{const i={key:e,value:s,timestamp:Date.now(),ttl:r||this.config.defaultTTL,size:this.estimateSize(s)};return!1===this.ensureSpace(i.size)?(t.warn(`[WuCache] โš ๏ธ Cannot cache item: ${e} (too large)`),!1):(this.memoryCache.set(e,i),this.accessOrder.set(e,Date.now()),this.config.persistent&&this.saveToStorage(e,i),this.stats.sets++,this.stats.size+=i.size,!0)}catch(e){return t.warn("[WuCache] โš ๏ธ Failed to set cache:",e),!1}}delete(e){const t=this.memoryCache.get(e);t&&(this.stats.size-=t.size),this.memoryCache.delete(e),this.accessOrder.delete(e),this.config.persistent&&this.deleteFromStorage(e)}clear(){this.memoryCache.clear(),this.accessOrder.clear(),this.stats.size=0,this.config.persistent&&this.clearStorage(),t.debug("[WuCache] ๐Ÿงน Cache cleared")}isExpired(e){return!!e.ttl&&Date.now()-e.timestamp>e.ttl}estimateSize(e){if("string"==typeof e)return 2*e.length;if("object"==typeof e)try{return 2*JSON.stringify(e).length}catch{return 1e3}return 100}ensureSpace(e){const s=1024*this.config.maxSize*1024;if(e>s)return t.warn(`[WuCache] โš ๏ธ Item size (${e}) exceeds max cache size (${s}). Skipping.`),!1;const r=this.config.maxItems+10;let i=0;for(;(this.stats.size+e>s||this.memoryCache.size>=this.config.maxItems)&&i<r;){if(i++,0===this.memoryCache.size){t.warn("[WuCache] โš ๏ธ Cache empty but still no space. Breaking loop.");break}let e=null,s=1/0;for(const[t,r]of this.accessOrder)r<s&&(s=r,e=t);if(!e)break;t.debug(`[WuCache] ๐Ÿ—‘๏ธ Evicting LRU entry: ${e}`),this.delete(e),this.stats.evictions++}return i>=r&&console.error(`[WuCache] ๐Ÿšจ Max eviction iterations reached (${r}). Possible infinite loop prevented.`),!0}getFromStorage(e){try{const t=this.getStorage().getItem(`wu_cache_${e}`);if(t)return JSON.parse(t)}catch(e){t.warn("[WuCache] โš ๏ธ Failed to get from storage:",e)}return null}saveToStorage(e,s){const r=this.getStorage();try{r.setItem(`wu_cache_${e}`,JSON.stringify(s))}catch(i){t.warn("[WuCache] โš ๏ธ Storage full, cleaning old entries"),this.cleanOldStorageEntries();try{r.setItem(`wu_cache_${e}`,JSON.stringify(s))}catch{t.warn("[WuCache] โš ๏ธ Failed to save to storage after cleanup")}}}deleteFromStorage(e){try{this.getStorage().removeItem(`wu_cache_${e}`)}catch(e){t.warn("[WuCache] โš ๏ธ Failed to delete from storage:",e)}}clearStorage(){try{const e=this.getStorage();Object.keys(e).forEach(t=>{t.startsWith("wu_cache_")&&e.removeItem(t)})}catch(e){t.warn("[WuCache] โš ๏ธ Failed to clear storage:",e)}}cleanOldStorageEntries(){try{const e=this.getStorage(),s=Object.keys(e),r=[];s.forEach(t=>{if(t.startsWith("wu_cache_"))try{const s=JSON.parse(e.getItem(t));r.push({key:t,timestamp:s.timestamp})}catch{}}),r.sort((e,t)=>e.timestamp-t.timestamp);const i=Math.ceil(.25*r.length);for(let t=0;t<i;t++)e.removeItem(r[t].key);t.debug(`[WuCache] ๐Ÿงน Cleaned ${i} old storage entries`)}catch(e){t.warn("[WuCache] โš ๏ธ Failed to clean old storage entries:",e)}}getStorage(){return"localStorage"===this.config.storage?window.localStorage:"sessionStorage"===this.config.storage?window.sessionStorage:{getItem:()=>null,setItem:()=>{},removeItem:()=>{},clear:()=>{}}}getStats(){const e=this.stats.hits+this.stats.misses>0?(this.stats.hits/(this.stats.hits+this.stats.misses)*100).toFixed(2):0;return{...this.stats,hitRate:`${e}%`,items:this.memoryCache.size,sizeMB:(this.stats.size/1024/1024).toFixed(2)}}configure(e){this.config={...this.config,...e}}}class g{constructor(){this.listeners=new Map,this.history=[],this.authorizedApps=new Map,this.trustedEvents=new Set(["wu:*","system:*"]),this.config={maxHistory:100,enableReplay:!0,enableWildcards:!0,logEvents:!1,strictMode:!1,validateOrigin:!0},this.stats={emitted:0,subscriptions:0,rejected:0}}registerApp(e,t={}){const s=t.token||this._generateToken();return this.authorizedApps.set(e,{token:s,permissions:t.permissions||["*"],registeredAt:Date.now()}),s}unregisterApp(e){this.authorizedApps.delete(e)}_validateOrigin(e,t,s){if(this._isSystemEvent(e))return!0;if(!this.config.strictMode)return!0;const r=this.authorizedApps.get(t);return!!r&&((!s||r.token===s)&&this._hasPermission(r.permissions,e))}_hasPermission(e,t){return!!e.includes("*")||e.some(e=>e===t||!!e.includes("*")&&this.matchesWildcard(t,e))}_isSystemEvent(e){return e.startsWith("wu:")||e.startsWith("system:")||e.startsWith("app:")}_generateToken(){return`wu_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}emit(e,s,r={}){const i=r.appName||"unknown";if(this.config.validateOrigin&&this.config.strictMode&&!this._validateOrigin(e,i,r.token))return this.stats.rejected++,t.warn(`[WuEventBus] ๐Ÿšซ Event rejected: ${e} from ${i} (unauthorized)`),!1;const n={name:e,data:s,timestamp:r.timestamp||Date.now(),appName:i,meta:r.meta||{},verified:this.authorizedApps.has(i)};this.config.enableReplay&&this.addToHistory(n),this.config.logEvents&&t.debug(`[WuEventBus] ๐Ÿ“ข ${e}`,s);const o=this.listeners.get(e);return o&&o.forEach(t=>{try{t(n)}catch(t){console.error(`[WuEventBus] โŒ Error in listener for ${e}:`,t)}}),this.config.enableWildcards&&this.notifyWildcardListeners(e,n),this.stats.emitted++,!0}on(e,t){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t),this.stats.subscriptions++,()=>this.off(e,t)}off(e,t){const s=this.listeners.get(e);s&&(s.delete(t),0===s.size&&this.listeners.delete(e),this.stats.subscriptions--)}once(e,t){const s=r=>{t(r),this.off(e,s)};return this.on(e,s)}notifyWildcardListeners(e,t){for(const[s,r]of this.listeners)this.matchesWildcard(e,s)&&r.forEach(e=>{try{e(t)}catch(e){console.error(`[WuEventBus] โŒ Error in wildcard listener for ${s}:`,e)}})}matchesWildcard(e,t){if(!t.includes("*"))return!1;const s=t.replace(/\./g,"\\.").replace(/\*/g,".*");return new RegExp(`^${s}$`).test(e)}addToHistory(e){this.history.push(e),this.history.length>this.config.maxHistory&&this.history.shift()}replay(e,t){this.history.filter(t=>e.includes("*")?this.matchesWildcard(t.name,e):t.name===e).forEach(e=>{try{t(e)}catch(e){console.error("[WuEventBus] โŒ Error replaying event:",e)}})}clearHistory(e){this.history=e?this.history.filter(t=>e.includes("*")?!this.matchesWildcard(t.name,e):t.name!==e):[]}getStats(){return{...this.stats,activeListeners:this.listeners.size,historySize:this.history.length,authorizedApps:this.authorizedApps.size,listenersByEvent:Array.from(this.listeners.entries()).map(([e,t])=>({event:e,listeners:t.size}))}}configure(e){this.config={...this.config,...e}}enableStrictMode(){this.config.strictMode=!0}disableStrictMode(){this.config.strictMode=!1}removeAll(){this.listeners.clear(),this.stats.subscriptions=0}}class f{constructor(){this.metrics=new Map,this.measurements=[],this.marks=new Map,this.config={enabled:!0,maxMeasurements:1e3},this.thresholds={mount:3e3,unmount:1e3,load:5e3},t.debug("[WuPerformance] โšก Framework performance monitoring initialized")}startMeasure(e,s="global"){const r=`${s}:${e}:start`;this.marks.set(r,performance.now()),t.debug(`[WuPerformance] ๐Ÿ“Š Measure started: ${r}`)}endMeasure(e,s="global"){const r=`${s}:${e}:start`,i=this.marks.get(r);if(!i)return 0;const n=performance.now()-i;return this.marks.delete(r),this.recordMeasurement({name:e,appName:s,duration:n,timestamp:Date.now(),type:"duration"}),this.checkThreshold(e,n)&&t.warn(`[WuPerformance] โš ๏ธ Threshold exceeded for ${e}: ${n.toFixed(2)}ms`),t.debug(`[WuPerformance] โน๏ธ Measure ended: ${r} (${n.toFixed(2)}ms)`),n}recordMeasurement(e){this.measurements.push(e),this.measurements.length>this.config.maxMeasurements&&this.measurements.shift(),this.metrics.has(e.appName)||this.metrics.set(e.appName,{appName:e.appName,measurements:[],stats:{}});this.metrics.get(e.appName).measurements.push(e),this.calculateStats(e.appName)}calculateStats(e){const t=this.metrics.get(e);if(!t)return;const s=t.measurements;if(0===s.length)return;const r={};s.forEach(e=>{r[e.name]||(r[e.name]=[]),r[e.name].push(e.duration)}),t.stats={},Object.entries(r).forEach(([e,s])=>{t.stats[e]={count:s.length,avg:s.reduce((e,t)=>e+t,0)/s.length,min:Math.min(...s),max:Math.max(...s),last:s[s.length-1]}})}checkThreshold(e,t){const s=this.thresholds[e];return s&&t>s}generateReport(){const e={timestamp:Date.now(),totalMeasurements:this.measurements.length,apps:{}};for(const[t,s]of this.metrics)e.apps[t]={measurementCount:s.measurements.length,stats:s.stats};return e}getMetrics(e){return this.metrics.get(e)||null}getAllMetrics(){const e={};for(const[t,s]of this.metrics)e[t]=s;return e}clearMetrics(e){e?(this.metrics.delete(e),this.measurements=this.measurements.filter(t=>t.appName!==e)):(this.metrics.clear(),this.measurements=[]),t.debug("[WuPerformance] ๐Ÿงน Metrics cleared"+(e?` for ${e}`:""))}configure(e){this.config={...this.config,...e},e.thresholds&&(this.thresholds={...this.thresholds,...e.thresholds})}}class w{constructor(e){this._core=e,this.plugins=new Map,this.hooks=new Map,this.availableHooks=["beforeInit","afterInit","beforeMount","afterMount","beforeUnmount","afterUnmount","onError","onDestroy"],this.availablePermissions=["mount","events","store","apps","config","unsafe"],this.hookTimeout=5e3,this.availableHooks.forEach(e=>{this.hooks.set(e,[])})}_createSandboxedApi(e){const s={version:this._core.version,info:this._core.info,getAppInfo:e=>{const t=this._core.mounted.get(e);return t?{name:e,state:t.state,timestamp:t.timestamp}:null},getMountedApps:()=>Array.from(this._core.mounted.keys()),getStats:()=>this._core.getStats()};return(e.includes("events")||e.includes("unsafe"))&&(s.emit=(e,t)=>this._core.eventBus.emit(e,t,{appName:"plugin"}),s.on=(e,t)=>this._core.eventBus.on(e,t),s.off=(e,t)=>this._core.eventBus.off(e,t)),(e.includes("store")||e.includes("unsafe"))&&(s.getState=e=>this._core.store.get(e),s.setState=(e,t)=>this._core.store.set(e,t)),(e.includes("mount")||e.includes("unsafe"))&&(s.mount=(e,t)=>this._core.mount(e,t),s.unmount=e=>this._core.unmount(e)),(e.includes("config")||e.includes("unsafe"))&&(s.configure=e=>{const t=["debug","logLevel"],s={};for(const r of t)r in e&&(s[r]=e[r]);Object.assign(this._core,s)}),e.includes("unsafe")&&(s._unsafeCore=this._core,t.warn("[WuPlugin] โš ๏ธ Plugin has unsafe access to core!")),Object.freeze(s)}_validatePlugin(e){if(!e||"object"!=typeof e)throw new Error("[WuPlugin] Invalid plugin: must be an object");if(!e.name||"string"!=typeof e.name)throw new Error("[WuPlugin] Invalid plugin: must have a name (string)");if(e.name.length>50)throw new Error("[WuPlugin] Invalid plugin: name too long (max 50 chars)");for(const t of this.availableHooks)if(e[t]&&"function"!=typeof e[t])throw new Error(`[WuPlugin] Invalid plugin: ${t} must be a function`);if(e.permissions){if(!Array.isArray(e.permissions))throw new Error("[WuPlugin] Invalid plugin: permissions must be an array");for(const t of e.permissions)if(!this.availablePermissions.includes(t))throw new Error(`[WuPlugin] Invalid permission: ${t}`)}return!0}use(e,s={}){if("function"==typeof e&&(e=e(s)),this._validatePlugin(e),this.plugins.has(e.name))return void t.warn(`[WuPlugin] Plugin "${e.name}" already installed`);const r=e.permissions||["events"],i=this._createSandboxedApi(r);if(e.install)try{e.install(i,s)}catch(t){throw console.error(`[WuPlugin] Error installing "${e.name}":`,t),t}this.availableHooks.forEach(t=>{if("function"==typeof e[t]){const s=this._wrapHook(e[t].bind(e),e.name,t);this.registerHook(t,s)}}),this.plugins.set(e.name,{plugin:e,options:s,permissions:r,sandboxedApi:i,installedAt:Date.now()}),t.debug(`[WuPlugin] โœ… Plugin "${e.name}" installed (permissions: ${r.join(", ")})`)}_wrapHook(e,t,s){return async r=>{const i=new Promise((e,r)=>{setTimeout(()=>{r(new Error(`Plugin "${t}" hook "${s}" timed out after ${this.hookTimeout}ms`))},this.hookTimeout)});try{return await Promise.race([e(r),i])}catch(e){return void console.error(`[WuPlugin] Error in ${t}.${s}:`,e)}}}registerHook(e,s){this.hooks.has(e)?this.hooks.get(e).push(s):t.warn(`[WuPlugin] Unknown hook: ${e}`)}async callHook(e,t){const s=this.hooks.get(e)||[];for(const r of s)try{if(!1===await r(t))return!1}catch(t){console.error(`[WuPlugin] Error in hook ${e}:`,t)}return!0}uninstall(e){const s=this.plugins.get(e);if(!s)return void t.warn(`[WuPlugin] Plugin "${e}" not found`);const{plugin:r,sandboxedApi:i}=s;if(r.uninstall)try{r.uninstall(i)}catch(t){console.error(`[WuPlugin] Error uninstalling "${e}":`,t)}this.plugins.delete(e),t.debug(`[WuPlugin] โœ… Plugin "${e}" uninstalled`)}getPlugin(e){return this.plugins.get(e)?.plugin}getStats(){return{totalPlugins:this.plugins.size,plugins:Array.from(this.plugins.entries()).map(([e,t])=>({name:e,permissions:t.permissions,installedAt:t.installedAt})),hooks:Array.from(this.hooks.entries()).map(([e,t])=>({name:e,callbacks:t.length}))}}cleanup(){for(const[e]of this.plugins)this.uninstall(e)}}class y{constructor(e){this.core=e,this.strategies=new Map,this.loadingQueue=[],this.isIdle=!1,this.registerDefaultStrategies(),this.setupIdleCallback(),t.debug("[WuStrategies] ๐ŸŽฏ Loading strategies initialized")}registerDefaultStrategies(){this.register("lazy",{shouldPreload:!1,load:async(e,s)=>{t.debug(`[Strategy:Lazy] Loading ${e} on demand (no preload)`)}}),this.register("eager",{shouldPreload:!0,priority:"high",load:async(e,s)=>{t.debug(`[Strategy:Eager] Preloading ${e} immediately`);const r=this.core.apps.get(e);if(r){const s=await this.core.resolveModulePath(r);await import(s),t.debug(`[Strategy:Eager] โœ… ${e} preloaded`)}}}),this.register("preload",{shouldPreload:!0,priority:"medium",load:async(e,s)=>{t.debug(`[Strategy:Preload] Using resource hints for ${e}`);const r=this.core.apps.get(e);if(r){const s=await this.core.resolveModulePath(r),i=document.createElement("link");i.rel="prefetch",i.href=s,i.as="script",document.head.appendChild(i),t.debug(`[Strategy:Preload] โœ… Resource hint added for ${e}`)}}}),this.register("speculate",{shouldPreload:!0,priority:"medium",load:async(e,t)=>{this.core.prefetcher&&await this.core.prefetcher.prefetch(e,{eagerness:t.eagerness||"moderate"})}}),this.register("idle",{shouldPreload:!1,load:async(e,s)=>(t.debug(`[Strategy:Idle] Queueing ${e} for idle loading`),new Promise(t=>{this.loadingQueue.push({appName:e,config:s,resolve:t}),this.isIdle&&this.processIdleQueue()}))})}register(e,s){if(!s.load||"function"!=typeof s.load)throw new Error("[WuStrategies] Strategy must have a load function");this.strategies.set(e,{name:e,shouldPreload:s.shouldPreload||!1,priority:s.priority||"low",load:s.load}),t.debug(`[WuStrategies] Strategy "${e}" registered`)}async load(e,s){const r=s.strategy||"lazy",i=this.strategies.get(r);return i?await i.load(e,s):(t.warn(`[WuStrategies] Strategy "${r}" not found, using lazy`),await this.strategies.get("lazy").load(e,s))}async preload(e){const s=e.filter(e=>this.strategies.get(e.strategy||"lazy").shouldPreload);s.sort((e,t)=>{const s={high:0,medium:1,low:2},r=this.strategies.get(e.strategy)?.priority||"low",i=this.strategies.get(t.strategy)?.priority||"low";return s[r]-s[i]}),t.debug(`[WuStrategies] Preloading ${s.length} apps`);for(const e of s)try{await this.load(e.name,e)}catch(t){console.error(`[WuStrategies] Failed to preload ${e.name}:`,t)}}setupIdleCallback(){if("requestIdleCallback"in window){const e=t=>{this.isIdle=!0,this.processIdleQueue(t),requestIdleCallback(e)};requestIdleCallback(e)}else setTimeout(()=>{this.isIdle=!0,this.processIdleQueue()},2e3)}async processIdleQueue(e){for(;this.loadingQueue.length>0&&!(e&&e.timeRemaining()<=0);){const e=this.loadingQueue.shift();try{const s=this.core.apps.get(e.appName);if(s){const r=await this.core.resolveModulePath(s);await import(r),t.debug(`[Strategy:Idle] โœ… ${e.appName} loaded during idle time`),e.resolve(!0)}else e.resolve(null)}catch(t){console.error(`[Strategy:Idle] Failed to load ${e.appName}:`,t),e.resolve(null)}}}getStats(){return{totalStrategies:this.strategies.size,strategies:Array.from(this.strategies.keys()),idleQueueSize:this.loadingQueue.length,isIdle:this.isIdle}}cleanup(){this.loadingQueue=[],t.debug("[WuStrategies] ๐Ÿงน Strategies cleaned up")}}class _{constructor(e){this.core=e,this.handlers=[],this.errorLog=[],this.maxErrorLog=100,this.config={maxRetries:3,retryDelay:1e3,showErrorUI:!0},this.registerDefaultHandlers(),t.debug("[WuErrorBoundary] ๐Ÿ›ก๏ธ Error boundary initialized")}registerDefaultHandlers(){this.register({name:"network",canHandle:e=>"TypeError"===e.name&&(e.message.includes("fetch")||e.message.includes("network")),handle:async(e,s)=>{if(t.debug("[ErrorHandler:Network] Handling network error"),s.retryCount<this.config.maxRetries){const e=this.config.retryDelay*Math.pow(2,s.retryCount);return t.debug(`[ErrorHandler:Network] Retrying in ${e}ms...`),await new Promise(t=>setTimeout(t,e)),{recovered:!0,action:"retry",retryCount:s.retryCount+1}}return{recovered:!1,action:"fallback",message:"Network error: Please check your connection"}}}),this.register({name:"script-load",canHandle:e=>"Error"===e.name&&(e.message.includes("Loading")||e.message.includes("Failed to fetch")),handle:async(e,s)=>(t.debug("[ErrorHandler:ScriptLoad] Handling script load error"),s.fallbackUrl?(t.debug("[ErrorHandler:ScriptLoad] Trying fallback URL"),{recovered:!0,action:"use-fallback-url",url:s.fallbackUrl}):{recovered:!1,action:"fallback",message:"Failed to load microfrontend"})}),this.register({name:"mount",canHandle:e=>e.message&&e.message.includes("mount"),handle:async(e,s)=>{if(t.debug("[ErrorHandler:Mount] Handling mount error"),s.retryCount<2){t.debug("[ErrorHandler:Mount] Cleaning up and retrying...");try{await this.core.unmount(s.appName)}catch(e){t.warn("[ErrorHandler:Mount] Cleanup failed:",e)}return await new Promise(e=>setTimeout(e,500)),{recovered:!0,action:"retry",retryCount:s.retryCount+1}}return{recovered:!1,action:"fallback",message:"Failed to mount application"}}}),this.register({name:"timeout",canHandle:e=>"TimeoutError"===e.name||e.message.includes("timeout"),handle:async(e,s)=>(t.debug("[ErrorHandler:Timeout] Handling timeout error"),s.retryCount<2?{recovered:!0,action:"retry-with-longer-timeout",timeout:2*(s.timeout||5e3),retryCount:s.retryCount+1}:{recovered:!1,action:"fallback",message:"Operation timed out"})}),this.register({name:"generic",canHandle:()=>!0,handle:async(e,s)=>(t.debug("[ErrorHandler:Generic] Handling generic error"),{recovered:!1,action:"fallback",message:e.message||"An unexpected error occurred"})})}register(e){if(!e.name||!e.canHandle||!e.handle)throw new Error("[WuErrorBoundary] Handler must have name, canHandle, and handle");this.handlers.push(e),t.debug(`[WuErrorBoundary] Handler "${e.name}" registered`)}async handle(e,s={}){s={retryCount:0,timestamp:Date.now(),...s},this.logError(e,s);for(const r of this.handlers)try{if(r.canHandle(e,s)){t.debug(`[WuErrorBoundary] Using handler: ${r.name}`);const i=await r.handle(e,s);return i.recovered?(t.debug(`[WuErrorBoundary] โœ… Error recovered by ${r.name}`),i):("fallback"===i.action&&this.config.showErrorUI&&this.renderFallback(s,i),i)}}catch(e){console.error(`[WuErrorBoundary] Handler "${r.name}" failed:`,e)}return console.error("[WuErrorBoundary] โŒ No handler could handle the error"),{recovered:!1,action:"unhandled",message:"Unhandled error"}}renderFallback(e,s){if(!e.container)return void t.warn("[WuErrorBoundary] No container to render fallback");const r="string"==typeof e.container?document.querySelector(e.container):e.container;if(!r)return;r.innerHTML="";const i=document.createElement("div");i.className="wu-error-boundary",Object.assign(i.style,{padding:"2rem",borderRadius:"8px",background:"#fff3cd",border:"1px solid #ffc107",color:"#856404",fontFamily:"system-ui, -apple-system, sans-serif",textAlign:"center"});const n=document.createElement("div");n.textContent="โš ๏ธ",n.style.fontSize="3rem",n.style.marginBottom="1rem";const o=document.createElement("h3");o.textContent="Application Error",o.style.margin="0 0 0.5rem 0";const a=document.createElement("p");a.textContent=s.message||"An error occurred",a.style.margin="0 0 1rem 0";const c=document.createElement("button");c.textContent="๐Ÿ”„ Reload",Object.assign(c.style,{padding:"0.5rem 1rem",background:"#ffc107",border:"none",borderRadius:"4px",cursor:"pointer",fontWeight:"bold",color:"#000"}),c.addEventListener("click",()=>window.location.reload()),i.appendChild(n),i.appendChild(o),i.appendChild(a),i.appendChild(c),r.appendChild(i)}logError(e,t){const s={error:{name:e.name,message:e.message,stack:e.stack},context:t,timestamp:Date.now()};this.errorLog.push(s),this.errorLog.length>this.maxErrorLog&&this.errorLog.shift()}getErrorLog(e=10){return this.errorLog.slice(-e)}getStats(){const e={};return this.errorLog.forEach(t=>{const s=t.error.name||"Unknown";e[s]=(e[s]||0)+1}),{totalErrors:this.errorLog.length,handlers:this.handlers.length,errorsByType:e,recentErrors:this.getErrorLog(5)}}configure(e){this.config={...this.config,...e}}cleanup(){this.errorLog=[],t.debug("[WuErrorBoundary] ๐Ÿงน Error boundary cleaned up")}}class v{constructor(e){this.core=e,this.hooks=new Map,this.executionLog=[],this.maxLogSize=100,this.lifecyclePhases=["beforeInit","afterInit","beforeLoad","afterLoad","beforeMount","afterMount","beforeUnmount","afterUnmount","beforeDestroy","afterDestroy"],this.lifecyclePhases.forEach(e=>{this.hooks.set(e,[])}),t.debug("[WuHooks] ๐Ÿช Lifecycle hooks initialized")}use(e,s,r={}){if(!this.hooks.has(e))throw new Error(`[WuHooks] Unknown lifecycle phase: ${e}`);if("function"!=typeof s)throw new Error("[WuHooks] Middleware must be a function");const i={middleware:s,name:r.name||`hook_${Date.now()}`,priority:r.priority||0,registeredAt:Date.now()},n=this.hooks.get(e);return n.push(i),n.sort((e,t)=>t.priority-e.priority),t.debug(`[WuHooks] Hook "${i.name}" registered for ${e} (priority: ${i.priority})`),()=>this.remove(e,i.name)}remove(e,s){if(!this.hooks.has(e))return;const r=this.hooks.get(e),i=r.findIndex(e=>e.name===s);i>-1&&(r.splice(i,1),t.debug(`[WuHooks] Hook "${s}" removed from ${e}`))}async execute(e,s={}){const r=this.hooks.get(e);if(!r||0===r.length)return s;t.debug(`[WuHooks] Executing ${r.length} hooks for ${e}`);const i={phase:e,timestamp:Date.now(),hooksCount:r.length,hookNames:r.map(e=>e.name)};let n={...s},o=!1;const a=async e=>{if(e>=r.length)return n;const s=r[e],i=Date.now();try{let r=!1;const c=async t=>(r=!0,void 0!==t&&(n={...n,...t}),await a(e+1));if(await s.middleware(n,c),!r)return t.debug(`[WuHooks] Hook "${s.name}" cancelled execution`),o=!0,{cancelled:!0};const l=Date.now()-i;t.debug(`[WuHooks] Hook "${s.name}" executed in ${l}ms`)}catch(t){return console.error(`[WuHooks] Error in hook "${s.name}":`,t),await a(e+1)}return n},c=await a(0);return i.duration=Date.now()-i.timestamp,i.cancelled=o,i.success=!o,this.executionLog.push(i),this.executionLog.length>this.maxLogSize&&this.executionLog.shift(),c}useMultiple(e,t,s={}){const r=e.map(e=>this.use(e,t,{...s,name:`${s.name}_${e}`}));return()=>r.forEach(e=>e())}getHooks(e){if(e)return this.hooks.get(e)||[];const t={};return this.hooks.forEach((e,s)=>{t[s]=e.map(e=>({name:e.name,priority:e.priority,registeredAt:e.registeredAt}))}),t}getStats(){const e=Array.from(this.hooks.values()).reduce((e,t)=>e+t.length,0),t={};this.executionLog.forEach(e=>{t[e.phase]=(t[e.phase]||0)+1});const s=this.executionLog.length>0?this.executionLog.reduce((e,t)=>e+t.duration,0)/this.executionLog.length:0,r=this.executionLog.filter(e=>e.cancelled).length;return{totalHooks:e,totalExecutions:this.executionLog.length,executionsByPhase:t,avgDuration:Math.round(s),cancelledCount:r,recentExecutions:this.executionLog.slice(-10)}}cleanup(e){e?(this.hooks.set(e,[]),t.debug(`[WuHooks] Hooks cleaned for ${e}`)):(this.lifecyclePhases.forEach(e=>{this.hooks.set(e,[])}),this.executionLog=[],t.debug("[WuHooks] ๐Ÿงน All hooks cleaned"))}}class b{constructor(){this._cache=new Map}async fetchHtml(e,s){t.wuDebug(`[HtmlParser] Fetching HTML for ${s} from ${e}`);const r=await fetch(e,{method:"GET",headers:{Accept:"text/html,application/xhtml+xml,*/*"}});if(!r.ok)throw new Error(`[HtmlParser] Failed to fetch ${e}: HTTP ${r.status}`);const i=await r.text();if(!i||!i.trim())throw new Error(`[HtmlParser] Empty HTML response from ${e}`);return t.wuDebug(`[HtmlParser] Fetched ${i.length} chars for ${s}`),i}parse(e,s,r){const i=`${s}:${e.length}`;if(this._cache.has(i))return this._cache.get(i);const n=document.createElement("div");n.innerHTML=e;const o=[],a=[],c=[],l=[];this._extractResources(n,{inlineScripts:o,externalScripts:a,inlineStyles:c,externalStyles:l,baseUrl:r});const u={dom:n.innerHTML,scripts:{inline:o,external:a},styles:{inline:c,external:l}};return this._cache.set(i,u),t.wuDebug(`[HtmlParser] ${s}: ${o.length} inline scripts, ${a.length} external scripts, ${c.length+l.length} styles`),u}async fetchAndParse(e,t){const s=await this.fetchHtml(e,t);return this.parse(s,t,e)}_extractResources(e,t){const s=Array.from(e.children);for(const e of s){const s=e.nodeName.toLowerCase();if("script"!==s){if("style"===s){const s=e.textContent?.trim();s&&t.inlineStyles.push(s),e.replaceWith(document.createComment("wu:style"));continue}if("link"===s){const s=e.getAttribute("rel"),r=e.getAttribute("href");if("stylesheet"===s&&r){t.externalStyles.push(this._resolveUrl(r,t.baseUrl)),e.replaceWith(document.createComment("wu:link"));continue}}e.children.length>0&&this._extractResources(e,t)}else this._extractScript(e,t),e.replaceWith(document.createComment("wu:script"))}}_extractScript(e,s){const r=e.getAttribute("type")||"",i=e.getAttribute("src");if("module"!==r)if(i)s.externalScripts.push(this._resolveUrl(i,s.baseUrl));else{const t=e.textContent?.trim();t&&s.inlineScripts.push(t)}else t.wuDebug('[HtmlParser] Skipping type="module" script (use sandbox: "module" for ES modules)')}_resolveUrl(e,t){if(e.startsWith("http://")||e.startsWith("https://"))return e;if(e.startsWith("//"))return`https:${e}`;try{return new URL(e,t).href}catch{const s=t.replace(/\/$/,"");return e.startsWith("/")?s+e:`${s}/${e}`}}clearCache(){this._cache.clear()}}class x{execute(e,s,r,i={}){const{strictGlobal:n=!0,sourceUrl:o=""}=i;if(!e||!e.trim())return;const a=o?`\n//# sourceURL=wu-sandbox:///${s}/${o}\n`:"";let c;c=n?`;(function(window, self, globalThis, top, parent) {\n with(window) {\n ;${e}${a}\n }\n}).call(proxy, proxy, proxy, proxy, proxy, proxy);`:`;(function(window, self, globalThis, top, parent) {\n ;${e}${a}\n}).call(proxy, proxy, proxy, proxy, proxy, proxy);`;try{return new Function("proxy",c)(r)}catch(o){if(n)return t.wuWarn(`[ScriptExecutor] strictGlobal failed for ${s}, retrying without with(): ${o.message}`),this.execute(e,s,r,{...i,strictGlobal:!1});throw t.wuError(`[ScriptExecutor] Execution failed for ${s}:`,o),o}}async fetchScript(e){const t=await fetch(e);if(!t.ok)throw new Error(`Failed to fetch script ${e}: HTTP ${t.status}`);return t.text()}async executeAll(e,s,r,i={}){for(const n of e){let e=n.content;!e&&n.src&&(t.wuDebug(`[ScriptExecutor] Fetching external script: ${n.src}`),e=await this.fetchScript(n.src)),e&&e.trim()&&this.execute(e,s,r,{...i,sourceUrl:n.src||i.sourceUrl||""})}t.wuDebug(`[ScriptExecutor] Executed ${e.length} scripts for ${s}`)}}class S{constructor(e){this.appName=e,this.iframe=null,this._active=!1,this._timers=new Set,this._intervals=new Set,this._rafs=new Set,this._listeners=[]}activate(e,s,r){if(this._active)return this.iframe.contentWindow;const i=document.createElement("iframe");i.setAttribute("data-wu-sandbox",this.appName),i.style.cssText="display:none !important;position:absolute;width:0;height:0;border:0;",document.body.appendChild(i),this.iframe=i;const n=e.replace(/\/$/,""),o=i.contentWindow,a=o.document;return a.open(),a.write(`<!DOCTYPE html><html><head><base href="${n}/"></head><body></body></html>`),a.close(),o.wu=window.wu,this._patchDocument(o,s,r),this._patchTimers(o),this._active=!0,t.wuDebug(`[IframeSandbox] Activated for ${this.appName} (base: ${n})`),o}importModule(e,s=3e4){if(!this._active)throw new Error(`[IframeSandbox] Not active for ${this.appName}`);return new Promise((r,i)=>{const n=`wu_${this.appName}_${Date.now()}`,o=e=>{e.data?.channelId===n&&(c(),e.data.error?i(new Error(e.data.error)):r())},a=setTimeout(()=>{c(),i(new Error(`[IframeSandbox] import() timed out for ${this.appName}: ${e}`))},s),c=()=>{window.removeEventListener("message",o),clearTimeout(a)};window.addEventListener("message",o);const l=this.iframe.contentWindow.document,u=l.createElement("script");u.type="module",u.textContent=`import("${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}").then(() => parent.postMessage({ channelId: "${n}", success: true }, '*')).catch(e => parent.postMessage({ channelId: "${n}", error: e.message || String(e) }, '*'));`,l.head.appendChild(u),t.wuDebug(`[IframeSandbox] Importing module: ${e}`)})}_patchDocument(e,s,r){const i=e.document,n=r||s,o=document;i.createElement=(e,t)=>o.createElement(e,t),i.createElementNS=(e,t,s)=>o.createElementNS(e,t,s),i.createTextNode=e=>o.createTextNode(e),i.createComment=e=>o.createComment(e),i.createDocumentFragment=()=>o.createDocumentFragment(),i.querySelector=e=>n.querySelector(e),i.querySelectorAll=e=>n.querySelectorAll(e),i.getElementById=e=>n.querySelector(`#${e}`),i.getElementsByClassName=e=>n.querySelectorAll(`.${e}`),i.getElementsByTagName=e=>n.querySelectorAll(e);try{Object.defineProperty(i,"body",{get:()=>s,configurable:!0})}catch{t.wuDebug("[IframeSandbox] Could not redefine document.body")}const a=i.addEventListener.bind(i),c=i.removeEventListener.bind(i);i.addEventListener=(e,t,s)=>{this._listeners.push({target:i,event:e,handler:t,options:s}),a(e,t,s)},i.removeEventListener=(e,t,s)=>{this._listeners=this._listeners.filter(s=>!(s.target===i&&s.event===e&&s.handler===t)),c(e,t,s)},t.wuDebug(`[IframeSandbox] Document patched for ${this.appName}`)}_patchTimers(e){const s=e.setTimeout.bind(e),r=e.clearTimeout.bind(e),i=e.setInterval.bind(e),n=e.clearInterval.bind(e);if(e.setTimeout=(e,t,...r)=>{const i=s((...t)=>{this._timers.delete(i),"function"==typeof e&&e(...t)},t,...r);return this._timers.add(i),i},e.clearTimeout=e=>{this._timers.delete(e),r(e)},e.setInterval=(e,t,...s)=>{const r=i(e,t,...s);return this._intervals.add(r),r},e.clearInterval=e=>{this._intervals.delete(e),n(e)},e.requestAnimationFrame){const t=e.requestAnimationFrame.bind(e),s=e.cancelAnimationFrame.bind(e);e.requestAnimationFrame=e=>{const s=t((...t)=>{this._rafs.delete(s),e(...t)});return this._rafs.add(s),s},e.cancelAnimationFrame=e=>{this._rafs.delete(e),s(e)}}t.wuDebug(`[IframeSandbox] Timer tracking active for ${this.appName}`)}destroy(){if(this._active){this._active=!1;for(const e of this._timers)try{clearTimeout(e)}catch{}for(const e of this._intervals)try{clearInterval(e)}catch{}for(const e of this._rafs)try{cancelAnimationFrame(e)}catch{}this._timers.clear(),this._intervals.clear(),this._rafs.clear();for(const{target:e,event:t,handler:s,options:r}of this._listeners)try{e.removeEventListener(t,s,r)}catch{}if(this._listeners=[],this.iframe){try{const e=this.iframe.contentDocument;e&&(e.open(),e.write(""),e.close())}catch{}this.iframe.parentNode&&this.iframe.parentNode.removeChild(this.iframe),this.iframe=null}t.wuDebug(`[IframeSandbox] Destroyed for ${this.appName}`)}}isActive(){return this._active}}class ${constructor(e){this.core=e,this.prefetched=new Set,this._observers=new Map,this._listeners=[],this._speculationScript=null,this._speculationRules={prefetch:[],prerender:[]},this.supportsSpeculationRules=this._detectSpeculationRules(),this.supportsModulePreload=this._detectModulePreload(),t.wuDebug(`[WuPrefetch] Initialized โ€” Speculation Rules: ${this.supportsSpeculationRules?"yes":"no"}, Module Preload: `+(this.supportsModulePreload?"yes":"no"))}_detectSpeculationRules(){return"undefined"!=typeof HTMLScriptElement&&(HTMLScriptElement.supports?.("speculationrules")??!1)}_detectModulePreload(){if("undefined"==typeof document)return!1;const e=document.createElement("link");return e.relList?.supports?.("modulepreload")??!1}async prefetch(e,s={}){const r=Array.isArray(e)?e:[e],i=s.on||"immediate";switch(i){case"immediate":return this._prefetchImmediate(r,s);case"hover":return this._prefetchOnHover(r,s);case"visible":return this._prefetchOnVisible(r,s);case"idle":return this._prefetchOnIdle(r,s);default:return t.wuWarn(`[WuPrefetch] Unknown trigger "${i}", using immediate`),this._prefetchImmediate(r,s)}}async _prefetchImmediate(e,t){const s=await this._resolveAppUrls(e);0!==s.length&&(s.forEach(({name:e})=>this.prefetched.add(e)),this.supportsSpeculationRules?this._addSpeculationRules(s,t.eagerness||"moderate"):this.supportsModulePreload?s.forEach(({url:e})=>this._injectModulePreload(e)):s.forEach(({url:e})=>this._injectPrefetch(e)))}_prefetchOnHover(e,s){const r=this._resolveTarget(s.target);if(!r)return t.wuWarn("[WuPrefetch] hover trigger requires a target element or selector"),()=>{};let i=!1;const n=()=>{i||(i=!0,this._prefetchImmediate(e,s),r.removeEventListener("mouseenter",n),r.removeEventListener("focusin",n))};r.addEventListener("mouseenter",n,{passive:!0}),r.addEventListener("focusin",n,{passive:!0});const o=()=>{r.removeEventListener("mouseenter",n),r.removeEventListener("focusin",n)};return this._listeners.push(o),o}_prefetchOnVisible(e,s){const r=this._resolveTarget(s.target);if(!r)return t.wuWarn("[WuPrefetch] visible trigger requires a target element or selector"),()=>{};if("undefined"==typeof IntersectionObserver)return this._prefetchImmediate(e,s),()=>{};const i=new IntersectionObserver(t=>{for(const n of t)if(n.isIntersecting){this._prefetchImmediate(e,s),i.disconnect(),this._observers.delete(r);break}},{rootMargin:"200px"});i.observe(r),this._observers.set(r,i);return()=>{i.disconnect(),this._observers.delete(r)}}_prefetchOnIdle(e,t){const s=()=>this._prefetchImmediate(e,t);if("requestIdleCallback"in window){const e=requestIdleCallback(s,{timeout:3e3}),t=()=>cancelIdleCallback(e);return this._listeners.push(t),t}const r=setTimeout(s,2e3),i=()=>clearTimeout(r);return this._listeners.push(i),i}_addSpeculationRules(e,s){const r=e.filter(({name:e})=>!this.prefetched.has(e));if(0===r.length)return;r.forEach(({name:e})=>this.prefetched.add(e));const i=r.map(({url:e})=>e);this._speculationRules.prefetch.push({source:"list",urls:i,eagerness:s}),this._updateSpeculationScript(),t.wuDebug(`[WuPrefetch] Speculation Rules: prefetch ${r.map(e=>e.name).join(", ")} (eagerness: ${s})`)}_updateSpeculationScript(){this._speculationScript&&this._speculationScript.remove();const e=document.createElement("script");e.type="speculationrules",e.textContent=JSON.stringify(this._speculationRules),document.head.appendChild(e),this._speculationScript=e}_injectModulePreload(e){if(this.prefetched.has(e))return;this.prefetched.add(e);const s=document.createElement("link");s.rel="modulepreload",s.href=e,document.head.appendChild(s),t.wuDebug(`[WuPrefetch] modulepreload: ${e}`)}_injectPrefetch(e){if(this.prefetched.has(e))return;this.prefetched.add(e);const s=document.createElement("link");s.rel="prefetch",s.href=e,s.as="script",document.head.appendChild(s),t.wuDebug(`[WuPrefetch] prefetch: ${e}`)}async _resolveAppUrls(e){const s=[];for(const r of e){if(this.prefetched.has(r)){t.wuDebug(`[WuPrefetch] ${r} already prefetched, skipping`);continue}if(this.core.mounted.has(r)){t.wuDebug(`[WuPrefetch] ${r} already mounted, skipping`);continue}if(this.core.definitions.has(r)){t.wuDebug(`[WuPrefetch] ${r} already defined, skipping`);continue}const e=this.core.apps.get(r);if(e)try{const t=await this.core.resolveModulePath(e);s.push({name:r,url:t})}catch(e){t.wuWarn(`[WuPrefetch] Failed to resolve URL for "${r}":`,e.message)}else t.wuWarn(`[WuPrefetch] App "${r}" not registered, cannot prefetch`)}return s}_resolveTarget(e){return e?"string"==typeof e?document.querySelector(e):e instanceof Element?e:null:null}async prefetchAll(e={}){const s=[];for(const[e]of this.core.apps)this.core.mounted.has(e)||this.prefetched.has(e)||s.push(e);if(0!==s.length)return t.wuDebug(`[WuPrefetch] Prefetching all: ${s.join(", ")}`),this.prefetch(s,e);t.wuDebug("[WuPrefetch] No apps to prefetch")}getStats(){return{prefetched:[...this.prefetched],activeObservers:this._observers.size,activeListeners:this._listeners.length,speculationRulesSupported:this.supportsSpeculationRules,modulePreloadSupported:this.supportsModulePreload,speculationRules:this._speculationRules}}cleanup(){for(const[,e]of this._observers)e.disconnect();this._observers.clear();for(const e of this._listeners)e();this._listeners=[],this._speculationScript&&(this._speculationScript.remove(),this._speculationScript=null),this._speculationRules={prefetch:[],prerender:[]},this.prefetched.clear(),t.wuDebug("[WuPrefetch] Cleaned up")}}const k="wu-override:";class E{constructor(e={}){this._overrides=new Map,this._allowedDomains=e.allowedDomains||[],this._showIndicator=e.showIndicator??!0,this._indicatorElement=null,void 0!==e.enabled?this._enabled=e.enabled:this._enabled=this._isDevEnvironment(),this._enabled&&this._parseFromCookies()}_isDevEnvironment(){if("undefined"==typeof window)return!1;const e=window.location?.hostname||"",t=window.location?.port||"";return"localhost"===e||"127.0.0.1"===e||"0.0.0.0"===e||e.endsWith(".local")||""!==t&&"80"!==t&&"443"!==t}_isDomainAllowed(e){if(0===this._allowedDomains.length)return!0;const t=this._extractHostname(e);if(!t)return!1;for(const e of this._allowedDomains)if(this._matchDomain(t,e))return!0;return!1}_extractHostname(e){try{if(/^localhost(:\d+)?/.test(e))return"localhost";const t=e.startsWith("//")?`https:${e}`:e;return new URL(t).hostname}catch{return null}}_matchDomain(e,t){if(e===t)return!0;if(t.startsWith("*.")){const s=t.substring(2);return e===s||e.endsWith("."+s)}return!1}_parseFromCookies(){if(this._overrides.clear(),"undefined"==typeof document)return this._overrides;if(!this._enabled)return t.wuDebug("[WuOverrides] Overrides disabled โ€” skipping cookie parse"),this._overrides;const e=document.cookie;if(!e)return this._overrides;const s=e.split(";");for(const e of s){const s=e.trim();if(!s.startsWith(k))continue;const r=s.indexOf("=");if(-1===r)continue;const i=s.substring(12,r).trim(),n=s.substring(r+1).trim();i&&n&&(this._isValidUrl(n)?this._isDomainAllowed(n)?(this._overrides.set(i,n),t.wuDebug(`[WuOverrides] Parsed override: ${i} โ†’ ${n}`)):t.wuWarn(`[WuOverrides] BLOCKED: "${i}" override to "${n}" โ€” domain not in allowedDomains. Allowed: [${this._allowedDomains.join(", ")}]`):t.wuWarn(`[WuOverrides] Invalid override URL for "${i}": ${n}`))}return this._overrides.size>0&&t.wuInfo(`[WuOverrides] ${this._overrides.size} active override(s): `+[...this._overrides.keys()].join(", ")),this._overrides}applyToApps(e){if(!this._enabled||0===this._overrides.size)return e;for(const s of e){const e=this._overrides.get(s.name);e&&(s._originalUrl=s.url,s.url=e,t.wuInfo(`[WuOverrides] "${s.name}" overridden: ${s._originalUrl} โ†’ ${e}`))}return this._showIndicator&&this._overrides.size>0&&this._showOverrideIndicator(),e}getOverrideFor(e){return this._overrides.get(e)||null}set(e,s,r={}){if(!e||!s)throw new Error("[WuOverrides] appName and url are required");if(!this._enabled)throw new Error("[WuOverrides] Overrides are disabled in this environment. Enable with wu.init({ overrides: { enabled: true } })");if(!this._isValidUrl(s))throw new Error(`[WuOverrides] Invalid URL: ${s}`);if(!this._isDomainAllowed(s))throw new Error(`[WuOverrides] Domain not allowed: "${this._extractHostname(s)}". Allowed: [${this._allowedDomains.join(", ")}]`);const i=r.maxAge??86400,n=r.path??"/";"undefined"!=typeof document&&(document.cookie=`${k}${e}=${s}; path=${n}; max-age=${i}; SameSite=Lax`),this._overrides.set(e,s),this._showIndicator&&this._showOverrideIndicator(),t.wuInfo(`[WuOverrides] Override set: ${e} โ†’ ${s} (expires in ${i}s)`)}remove(e){"undefined"!=typeof document&&(document.cookie=`${k}${e}=; path=/; max-age=0`),this._overrides.delete(e),this._showIndicator&&(0===this._overrides.size?this._removeOverrideIndicator():this._showOverrideIndicator()),t.wuInfo(`[WuOverrides] Override removed: ${e}`)}clearAll(){for(const e of[...this._overrides.keys()])this.remove(e);this._removeOverrideIndicator(),t.wuInfo("[WuOverrides] All overrides cleared")}getAll(){return Object.fromEntries(this._overrides)}hasOverrides(){return this._overrides.size>0}isEnabled(){return this._enabled}configure(e={}){void 0!==e.enabled&&(this._enabled=e.enabled),e.allowedDomains&&(this._allowedDomains=e.allowedDomains),void 0!==e.showIndicator&&(this._showIndicator=e.showIndicator),this._enabled&&this._parseFromCookies()}refresh(){this._parseFromCookies()}_showOverrideIndicator(){if("undefined"==typeof document)return;this._removeOverrideIndicator();const e=document.createElement("div");e.id="wu-override-indicator";const t=[...this._overrides.entries()].map(([e,t])=>`${e} โ†’ ${t}`).join(" | ");e.textContent=`WU OVERRIDE ACTIVE: ${t}`,e.style.cssText=["position: fixed","bottom: 0","left: 0","right: 0","z-index: 2147483647","background: #f59e0b","color: #000","font-family: monospace","font-size: 12px","font-weight: bold","padding: 6px 12px","text-align: center","cursor: pointer","user-select: none","box-shadow: 0 -2px 8px rgba(0,0,0,0.2)"].join(";"),e.addEventListener("click",()=>{e.style.display="none"}),e.addEventListener("dblclick",e=>{e.preventDefault(),this.clearAll()}),e.title="Click to hide | Double-click to clear all overrides",document.body.appendChild(e),this._indicatorElement=e}_removeOverrideIndicator(){if(this._indicatorElement&&(this._indicatorElement.remove(),this._indicatorElement=null),"undefined"!=typeof document){const e=document.getElementById("wu-override-indicator");e&&e.remove()}}_isValidUrl(e){return!!(e.startsWith("http://")||e.startsWith("https://")||e.startsWith("//"))||!!/^localhost(:\d+)?/.test(e)}getStats(){return{enabled:this._enabled,activeOverrides:this._overrides.size,overrides:this.getAll(),allowedDomains:this._allowedDomains,showIndicator:this._showIndicator,environment:this._isDevEnvironment()?"development":"production"}}}class A{constructor(e={}){this.apps=new Map,this.definitions=new Map,this.manifests=new Map,this.mounted=new Map,this.hidden=new Map,this._pendingUnmounts=new Map,this._mountingPromises=new Map,this.loader=new n,this.sandbox=new l,this.manifest=new u,this.store=h,this.htmlParser=new b,this.scriptExecutor=new x,this.cache=new m({storage:"localStorage",maxSize:100}),this.eventBus=new g,this.performance=new f,this.pluginSystem=new w(this),this.strategies=new y(this),this.errorBoundary=new _(this),this.hooks=new v(this),this.prefetcher=new $(this),this.overrides=new E,this.isInitialized=!1,t.wuInfo("Wu Framework initialized - Universal Microfrontends")}async init(e){if(this.isInitialized)t.wuWarn("Framework already initialized");else{this._sandboxMode=e.sandbox||"module",t.wuDebug(`Initializing (sandbox: ${this._sandboxMode}) with apps:`,e.apps?.map(e=>e.name));try{if((await this.hooks.execute("beforeInit",{config:e})).cancelled)return void t.wuWarn("Initialization cancelled by beforeInit hook");await this.pluginSystem.callHook("beforeInit",{config:e}),e.overrides&&this.overrides.configure(e.overrides);const s=e.apps||[];this.overrides.refresh(),this.overrides.applyToApps(s);for(const e of s)await this.registerApp(e);await this.strategies.preload(e.apps||[]),this.isInitialized=!0,await this.hooks.execute("afterInit",{config:e}),await this.pluginSystem.callHook("afterInit",{config:e}),t.wuInfo("Framework initialized successfully")}catch(e){throw t.wuError("Initialization failed:",e),await this.pluginSystem.callHook("onError",{phase:"init",error:e}),e}}}async registerApp(e){const{name:s,url:r}=e;try{t.wuDebug(`Registering app: ${s} from ${r}`);const i=await this.manifest.load(r);this.manifests.set(s,i),this.apps.set(s,{...e,manifest:i,status:"registered"}),t.wuDebug(`App ${s} registered successfully`)}catch(e){throw t.wuError(`Failed to register app ${s}:`,e),e}}define(e,s){if(!s.mount)throw new Error(`[Wu] Mount function required for app: ${e}`);this.definitions.set(e,s);const r=new CustomEvent("wu:app:ready",{detail:{appName:e,timestamp:Date.now()}});window.dispatchEvent(r),t.wuDebug(`Lifecycle defined for: ${e}`)}async mount(e,s){if(this._pendingUnmounts.has(e)&&(clearTimeout(this._pendingUnmounts.get(e)),this._pendingUnmounts.delete(e),t.wuDebug(`${e} deferred unmount cancelled by remount`)),this.mounted.has(e)){if(this.mounted.get(e).containerSelector===s)return void t.wuDebug(`${e} already mounted in ${s}`)}if(this._mountingPromises.has(e))return t.wuDebug(`${e} mount already in progress, deduplicating`),await this._mountingPromises.get(e);const r=this.hidden.get(e);if(r){if(r.containerSelector===s)return await this.show(e);await this._destroyHidden(e)}const i=this.mountWithRecovery(e,s,0);this._mountingPromises.set(e,i);try{return await i}finally{this._mountingPromises.delete(e)}}async mountWithRecovery(e,s,r=0){try{this.performance.startMeasure("mount",e),t.wuDebug(`Mounting ${e} in ${s} (attempt ${r+1})`);if((await this.hooks.execute("beforeLoad",{appName:e,containerSelector:s,attempt:r})).cancelled)return void t.wuWarn("Mount cancelled by beforeLoad hook");if(!1===await this.pluginSystem.callHook("beforeMount",{appName:e,containerSelector:s}))return void t.wuWarn("Mount cancelled by plugin beforeMount hook");const i=this.apps.get(e);if(!i)throw new Error(`App ${e} not registered. Call wu.init() first.`);const n=document.querySelector(s);if(!n)throw new Error(`Container not found: ${s}`);const o=this.sandbox.create(e,n,{manifest:i.manifest,styleMode:i.manifest?.styleMode,appUrl:i.url});await this.hooks.execute("afterLoad",{appName:e,containerSelector:s,sandbox:o});let a=this.definitions.get(e);if(!a&&(await this.loadAndMountRemoteApp(i,o),a=this.definitions.get(e),!a))throw new Error(`App ${e} did not register with wu.define()`);if((await this.hooks.execute("beforeMount",{appName:e,containerSelector:s,sandbox:o,lifecycle:a})).cancelled)return void t.wuWarn("Mount cancelled by beforeMount hook");o.stylesReady&&(t.wuDebug(`Waiting for styles to be ready for ${e}...`),await o.stylesReady,t.wuDebug(`Styles ready for ${e}`)),await a.mount(o.container),this.mounted.set(e,{app:i,sandbox:o,lifecycle:a,container:o.container,hostContainer:n,containerSelector:s,timestamp:Date.now(),state:"stable"});const c=this.performance.endMeasure("mount",e);await this.hooks.execute("afterMount",{appName:e,containerSelector:s,sandbox:o,mountTime:c}),await this.pluginSystem.callHook("afterMount",{appName:e,containerSelector:s,mountTime:c}),this.eventBus.emit("app:mounted",{appName:e,mountTime:c,attempt:r},{appName:e}),t.wuInfo(`${e} mounted successfully in ${c.toFixed(2)}ms`)}catch(i){t.wuError(`Mount attempt ${r+1} failed for ${e}:`,i);const n=await this.errorBoundary.handle(i,{appName:e,containerSelector:s,retryCount:r,container:s});if(n.recovered)return void t.wuDebug("Error recovered by error boundary");if(r<2&&"retry"===n.action)return t.wuDebug("Initiating recovery protocol..."),await this.appStateCleanup(e,s),await new Promise(e=>setTimeout(e,1e3*(r+1))),await this.mountWithRecovery(e,s,r+1);throw await this.pluginSystem.callHook("onError",{phase:"mount",error:i,appName:e}),i}}async appStateCleanup(e,s){try{if(t.wuDebug(`Starting app state cleanup for ${e}...`),this.hidden.has(e))try{await this._destroyHidden(e)}catch(e){t.wuWarn("Hidden app cleanup failed:",e)}if(this.mounted.has(e))try{await this.unmount(e,{force:!0})}catch(e){t.wuWarn("Unmount failed during cleanup:",e)}const r=document.querySelector(s);if(r){if(r.shadowRoot)try{Array.from(r.shadowRoot.children).forEach(e=>{try{e.remove()}catch(e){t.wuWarn("Failed to remove shadow child:",e)}})}catch(e){t.wuWarn("Shadow root cleanup failed:",e)}if(!r.shadowRoot&&r.children.length>0)try{r.innerHTML=""}catch(e){t.wuWarn("Container innerHTML cleanup failed:",e)}r.removeAttribute("data-wu-app"),r.removeAttribute("data-quantum-state"),r.removeAttribute("wu-debug")}this.definitions.delete(e),this.sandbox&&this.sandbox.sandboxes&&this.sandbox.sandboxes.delete(e),t.wuDebug(`App state cleaned successfully for ${e}`)}catch(r){t.wuWarn(`App cleanup partial failure for ${e}:`,r);try{const e=document.querySelector(s);e&&(e.style.display="none",setTimeout(()=>{e&&(e.style.display="")},100))}catch(e){t.wuError("Emergency cleanup failed:",e)}}}async loadAndMountRemoteApp(e,t){const s=e.sandbox||this._sandboxMode||"module";"strict"===s?await this._loadStrict(e,t):"eval"===s?await this._loadEval(e,t):await this._loadModule(e,t)}async _loadModule(e,s){const r=await this.resolveModulePath(e);t.wuDebug(`[module] Loading ES module: ${r}`);const i=s.jsSandbox;i?.patchWindow&&i.patchWindow();try{await this.moduleLoader(r,e.name),t.wuDebug(`[module] ES module loaded: ${e.name}`)}catch(e){throw t.wuError(`[module] Failed to load ${r}:`,e),e}finally{i?.unpatchWindow&&i.unpatchWindow()}}async _loadStrict(e,s){t.wuDebug(`[strict] Loading ${e.name} via iframe sandbox`);const r=new S(e.name);r.activate(e.url,s.container,s.shadowRoot),s.iframeSandbox=r;try{const s=await this.resolveModulePath(e);t.wuDebug(`[strict] Importing module in iframe: ${s}`),await r.importModule(s),t.wuDebug(`[strict] Module imported for ${e.name}`)}catch(i){return t.wuWarn(`[strict] iframe import failed for ${e.name}: ${i.message}\nFalling back to eval mode (fetch + parse + execute with proxy).\nTo fix: ensure the app's dev server sets Access-Control-Allow-Origin: * headers,\nor use sandbox: 'eval' explicitly for UMD/IIFE bundles.`),r.destroy(),s.iframeSandbox=null,void await this._loadEval(e,s)}await this._waitForDefine(e.name,"strict"),t.wuDebug(`[strict] ${e.name} loaded and registered via iframe`)}async _loadEval(e,s){t.wuDebug(`[eval] Loading ${e.name} from ${e.url}`);const r=s.jsSandbox.getProxy();if(!r)throw new Error(`[eval] No active proxy for ${e.name}. Sandbox must be activated first.`);const i=await this.htmlParser.fetchAndParse(e.url,e.name);i.dom&&(s.container.innerHTML=i.dom);const n=s.shadowRoot||s.container;for(const e of i.styles.inline){const t=document.createElement("style");t.textContent=e,n.appendChild(t)}for(const e of i.styles.external){const t=document.createElement("link");t.rel="stylesheet",t.href=e,n.appendChild(t)}const o=[];for(const e of i.scripts.inline)o.push({content:e});for(const e of i.scripts.external)o.push({src:e});await this.scriptExecutor.executeAll(o,e.name,r),t.wuDebug(`[eval] Scripts executed for ${e.name}`),await this._waitForDefine(e.name,"eval"),t.wuDebug(`[eval] ${e.name} loaded and registered`)}async _waitForDefine(e,t){const s=Date.now();for(;!this.definitions.has(e);){if(Date.now()-s>=1e4)throw new Error(`[${t}] App '${e}' loaded but wu.define() was not called within 10000ms.\nMake sure your app calls: window.wu.define('${e}', { mount, unmount })`);await new Promise(e=>setTimeout(e,50))}}async resolveModulePath(e){let s=e.manifest?.entry||"main.js";const r=e.url.replace(/\/$/,"");if(/^(src|dist|public|build|assets|lib|es)\//.test(s)){t.wuDebug(`Entry already has folder prefix: ${s}`);const e=`${r}/${s}`;return t.wuDebug(`Using direct path: ${e}`),e}const i=[`${r}/src/${s}`,`${r}/${s}`,`${r}/dist/${s}`,`${r}/public/${s}`,`${r}/build/${s}`,`${r}/assets/${s}`,`${r}/lib/${s}`,`${r}/es/${s}`];t.wuDebug(`Attempting path resolution for ${e.name}...`);for(let e=0;e<i.length;e++){const s=i[e];try{t.wuDebug(`Testing path candidate ${e+1}/${i.length}: ${s}`);if(await this.validatePath(s))return t.wuDebug(`Path resolved successfully: ${s}`),s;t.wuDebug(`Path candidate ${e+1} failed validation: ${s}`)}catch(r){t.wuDebug(`Path candidate ${e+1} threw error: ${s} - ${r.message}`);continue}}const n=i[0];return t.wuWarn(`All path candidates failed, using fallback: ${n}`),n}async validatePath(e){try{t.wuDebug(`Testing path: ${e}`);const s=await fetch(e,{method:"GET",cache:"no-cache",signal:AbortSignal.timeout(2e3)});if(!s.ok)return t.wuDebug(`Path validation failed - HTTP ${s.status}: ${e}`),!1;const r=s.headers.get("content-type")||"";if(!(r.includes("javascript")||r.includes("module")||r.includes("text/plain")||e.endsWith(".js")||e.endsWith(".mjs")))return t.wuDebug(`Path validation failed - Invalid content type '${r}': ${e}`),!1;const i=await s.text(),n=i.trim().toLowerCase();if(n.startsWith("<!doctype")||n.startsWith("<html")||n.startsWith("<head")||n.startsWith("<body")||n.startsWith("<!-"))return t.wuDebug(`Path validation failed - Server returned HTML fallback page: ${e}`),!1;return i.includes("export")||i.includes("import")||i.includes("wu.define")||i.includes("module.exports")||i.includes("console.log")||i.includes("function")&&i.length>10?(t.wuDebug(`Path validation successful: ${e} (${i.length} chars)`),!0):(t.wuDebug(`Path validation failed - No valid module content: ${e}`),t.wuDebug(`Content preview: ${i.substring(0,100)}...`),!1)}catch(s){return t.wuDebug(`Path validation failed for ${e}: ${s.message}`),!1}}async moduleLoader(e,s){if(this.definitions.has(s))return void t.wuDebug(`App ${s} already registered`);t.wuDebug(`Using event-based registration for ${s}`);try{await import(e)}catch(s){throw t.wuError(`Failed to import module ${e}:`,s),s}const r=Date.now();for(;!this.definitions.has(s);){if(Date.now()-r>=1e4)throw new Error(`App '${s}' module loaded but wu.define() was not called within 10000ms.\n\nMake sure your module calls:\n wu.define('${s}', { mount, unmount })\n\nOr using window.wu:\n window.wu.define('${s}', { mount, unmount })`);await new Promise(e=>setTimeout(e,50))}t.wuDebug(`App ${s} loaded and registered (verified in definitions)`)}async unmount(e,s={}){t.wuDebug(`Unmounting ${e}`);const r=this.mounted.get(e);if(!r)return s.force&&this.hidden.has(e)?await this._destroyHidden(e):void t.wuWarn(`App ${e} not mounted`);return!s.force&&(s.keepAlive??r.app?.keepAlive??!1)?await this.hide(e):s.force?await this._executeUnmount(e,r):(this._pendingUnmounts.has(e)&&clearTimeout(this._pendingUnmounts.get(e)),void this._pendingUnmounts.set(e,setTimeout(async()=>{if(this._pendingUnmounts.delete(e),this.mounted.has(e)&&this.mounted.get(e)===r)try{await this._executeUnmount(e,r)}catch(s){t.wuError(`Deferred unmount failed for ${e}:`,s)}},60)))}async _executeUnmount(e,s){try{if((await this.hooks.execute("beforeUnmount",{appName:e,mounted:s})).cancelled)return void t.wuWarn("Unmount cancelled by beforeUnmount hook");if(!1===await this.pluginSystem.callHook("beforeUnmount",{appName:e}))return void t.wuWarn("Unmount cancelled by plugin beforeUnmount hook");s.lifecycle?.unmount&&await s.lifecycle.unmount(s.container),s.sandbox.iframeSandbox&&(s.sandbox.iframeSandbox.destroy(),s.sandbox.iframeSandbox=null),this.sandbox.cleanup(s.sandbox),this.mounted.delete(e),await this.hooks.execute("afterUnmount",{appName:e}),await this.pluginSystem.callHook("afterUnmount",{appName:e}),this.eventBus.emit("app:unmounted",{appName:e},{appName:e}),t.wuDebug(`${e} unmounted successfully`)}catch(s){throw t.wuError(`Failed to unmount ${e}:`,s),await this.pluginSystem.callHook("onError",{phase:"unmount",error:s,appName:e}),this.eventBus.emit("app:error",{appName:e,error:s.message},{appName:e}),s}}async hide(e){const s=this.mounted.get(e);if(s){if(t.wuDebug(`Hiding ${e} (keep-alive)`),s.lifecycle?.deactivate)try{await s.lifecycle.deactivate(s.container)}catch(s){t.wuWarn(`deactivate() failed for ${e}:`,s)}await this.hooks.execute("beforeUnmount",{appName:e,mounted:s,keepAlive:!0}),await this.pluginSystem.callHook("beforeUnmount",{appName:e,keepAlive:!0}),s.hostContainer.style.display="none",s.state="hidden",s.hiddenAt=Date.now(),this.hidden.set(e,s),this.mounted.delete(e),await this.hooks.execute("afterUnmount",{appName:e,keepAlive:!0}),await this.pluginSystem.callHook("afterUnmount",{appName:e,keepAlive:!0}),this.eventBus.emit("app:hidden",{appName:e},{appName:e}),t.wuInfo(`${e} hidden (keep-alive) โ€” state preserved`)}else t.wuWarn(`Cannot hide ${e}: not mounted`)}async show(e){const s=this.hidden.get(e);if(!s)return void t.wuWarn(`Cannot show ${e}: not in keep-alive state`);if(this.performance.startMeasure("show",e),t.wuDebug(`Showing ${e} from keep-alive`),await this.hooks.execute("beforeMount",{appName:e,containerSelector:s.containerSelector,sandbox:s.sandbox,lifecycle:s.lifecycle,keepAlive:!0}),await this.pluginSystem.callHook("beforeMount",{appName:e,containerSelector:s.containerSelector,keepAlive:!0}),s.hostContainer.style.display="",s.state="stable",delete s.hiddenAt,this.mounted.set(e,s),this.hidden.delete(e),s.lifecycle?.activate)try{await s.lifecycle.activate(s.container)}catch(s){t.wuWarn(`activate() failed for ${e}:`,s)}const r=this.performance.endMeasure("show",e);await this.hooks.execute("afterMount",{appName:e,containerSelector:s.containerSelector,sandbox:s.sandbox,mountTime:r,keepAlive:!0}),await this.pluginSystem.callHook("afterMount",{appName:e,containerSelector:s.containerSelector,mountTime:r,keepAlive:!0}),this.eventBus.emit("app:shown",{appName:e,showTime:r},{appName:e}),t.wuInfo(`${e} shown from keep-alive in ${r.toFixed(2)}ms`)}async _destroyHidden(e){const s=this.hidden.get(e);s&&(t.wuDebug(`Force-destroying hidden app: ${e}`),s.hostContainer.style.display="",s.state="stable",this.mounted.set(e,s),this.hidden.delete(e),await this.unmount(e,{force:!0}))}isHidden(e){return this.hidden.has(e)}async use(e){const[t,s]=e.split(".");if(!t||!s)throw new Error(`Invalid component path: ${e}. Use format "app.component"`);const r=this.apps.get(t);if(!r)throw new Error(`App ${t} not registered`);const i=this.manifests.get(t),n=i?.wu?.exports?.[s];if(!n)throw new Error(`Component ${s} not exported by ${t}`);return await this.loader.loadComponent(r.url,n)}getAppInfo(e){return{registered:this.apps.get(e),manifest:this.manifests.get(e),mounted:this.mounted.get(e),definition:this.definitions.get(e)}}getStats(){return{registered:this.apps.size,defined:this.definitions.size,mounted:this.mounted.size,hidden:this.hidden.size,apps:Array.from(this.apps.keys())}}getState(e){return this.store.get(e)}setState(e,t){return this.store.set(e,t)}onStateChange(e,t){return this.store.on(e,t)}batchState(e){return this.store.batch(e)}getStoreMetrics(){return this.store.getMetrics()}clearState(){this.store.clear()}override(e,t,s){this.overrides.set(e,t,s)}removeOverride(e){this.overrides.remove(e)}getOverrides(){return this.overrides.getAll()}clearOverrides(){this.overrides.clearAll()}prefetch(e,t){return this.prefetcher.prefetch(e,t)}prefetchAll(e){return this.prefetcher.prefetchAll(e)}app(e,t){return new p(e,t,this)}async destroy(){t.wuDebug("Destroying framework...");try{await this.hooks.execute("beforeDestroy",{}),await this.pluginSystem.callHook("onDestroy",{});for(const e of this._pendingUnmounts.values())clearTimeout(e);this._pendingUnmounts.clear(),this._mountingPromises.clear();for(const e of[...this.hidden.keys()])await this._destroyHidden(e);for(const e of[...this.mounted.keys()])await this.unmount(e,{force:!0});this.cache.clear(),this.eventBus.removeAll(),this.eventBus.clearHistory(),this.performance.clearMetrics(),this.pluginSystem.cleanup(),this.strategies.cleanup(),this.errorBoundary.cleanup(),this.hooks.cleanup(),this.prefetcher.cleanup(),this.apps.clear(),this.definitions.clear(),this.manifests.clear(),this.mounted.clear(),this.hidden.clear(),this.store.clear(),this.isInitialized=!1,await this.hooks.execute("afterDestroy",{}),t.wuDebug("Framework destroyed")}catch(e){throw t.wuError("Error during destroy:",e),e}}}class D{constructor(e={}){this.model=e.model||""}formatRequest(){throw new Error("Adapter must implement formatRequest()")}parseResponse(){throw new Error("Adapter must implement parseResponse()")}parseStreamChunk(){throw new Error("Adapter must implement parseStreamChunk()")}getHeaders(){return{"Content-Type":"application/json"}}}class C extends D{constructor(e){super(e),this.model=e.model||"claude-sonnet-4-5-20250929"}getHeaders(e){const t={"Content-Type":"application/json"};return e.apiKey&&(t["x-api-key"]=e.apiKey,t["anthropic-version"]="2023-06-01"),t}formatRequest(e,t={}){const s=e.filter(e=>"system"===e.role),r=e.filter(e=>"system"!==e.role),i={model:t.model||this.model,max_tokens:t.maxTokens||4096,messages:r.map(e=>"tool"===e.role?{role:"user",content:[{type:"tool_result",tool_use_id:e.tool_call_id,content:e.content}]}:e.tool_calls?{role:"assistant",content:e.tool_calls.map(e=>({type:"tool_use",id:e.id,name:e.name,input:e.arguments}))}:{role:e.role,content:e.content})};if(s.length&&(i.system=s.map(e=>e.content).join("\n\n")),t.responseFormat){const e=t.responseFormat,s="\n\nYou MUST respond with valid JSON only. No markdown, no explanation.";if("json"===e||"json_object"===e?.type)i.system=(i.system||"")+s;else if("json_schema"===e?.type){const t=JSON.stringify(e.schema,null,2);i.system=(i.system||"")+s+`\n\nYour response MUST conform to this JSON schema:\n${t}`}i.messages.push({role:"assistant",content:"{"})}return t.tools?.length&&(i.tools=t.tools.map(e=>({name:e.name,description:e.description,input_schema:e.parameters}))),void 0!==t.temperature&&(i.temperature=t.temperature),t.stream&&(i.stream=!0),i}parseResponse(e){const t=(e.content||[]).filter(e=>"text"===e.type),s=(e.content||[]).filter(e=>"tool_use"===e.type),r=t.map(e=>e.text).join(""),i=s.map(e=>({id:e.id,name:e.name,arguments:e.input||{}}));return{content:r,tool_calls:i.length>0?i:void 0,usage:e.usage?{prompt_tokens:e.usage.input_tokens,completion_tokens:e.usage.output_tokens}:void 0}}parseStreamChunk(e){if(!e.startsWith("data: "))return null;const t=e.slice(6).trim();try{const e=JSON.parse(t);if("content_block_delta"===e.type){if("text_delta"===e.delta?.type)return{type:"text",content:e.delta.text};if("input_json_delta"===e.delta?.type)return{type:"tool_call_delta",argumentsDelta:e.delta.partial_json||""}}return"content_block_start"===e.type&&"tool_use"===e.content_block?.type?{type:"tool_call_start",id:e.content_block.id,name:e.content_block.name}:"message_delta"===e.type&&e.usage?{type:"usage",usage:{prompt_tokens:e.usage.input_tokens,completion_tokens:e.usage.output_tokens}}:"message_stop"===e.type?{type:"done"}:null}catch{return null}}}class L extends D{constructor(e){super(e),this._sendFn=e.send||null,this._streamFn=e.stream||null}get isCustom(){return!0}}const P={openai:class extends D{constructor(e){super(e),this.model=e.model||"gpt-4o"}getHeaders(e){const t={"Content-Type":"application/json"};return e.apiKey&&(t.Authorization=`Bearer ${e.apiKey}`),t}formatRequest(e,t={}){const s={model:t.model||this.model,messages:e.map(e=>{const t={role:e.role,content:e.content};return e.tool_call_id&&(t.tool_call_id=e.tool_call_id),e.tool_calls&&(t.tool_calls=e.tool_calls.map(e=>({id:e.id,type:"function",function:{name:e.name,arguments:JSON.stringify(e.arguments)}}))),t})};if(t.tools?.length&&(s.tools=t.tools.map(e=>({type:"function",function:{name:e.name,description:e.description,parameters:e.parameters}}))),void 0!==t.temperature&&(s.temperature=t.temperature),t.maxTokens&&(s.max_tokens=t.maxTokens),t.stream&&(s.stream=!0),t.responseFormat){const e=t.responseFormat;"json"===e||"json_object"===e?.type?s.response_format={type:"json_object"}:"json_schema"===e?.type&&(s.response_format={type:"json_schema",json_schema:{name:e.name||"response",schema:e.schema,strict:!1!==e.strict}})}return s}parseResponse(e){const t=e.choices?.[0];if(!t)return{content:"",tool_calls:[],usage:e.usage};const s=t.message||{},r=(s.tool_calls||[]).map(e=>({id:e.id,name:e.function?.name,arguments:this._safeParseArgs(e.function?.arguments)}));return{content:s.content||"",tool_calls:r.length>0?r:void 0,usage:e.usage?{prompt_tokens:e.usage.prompt_tokens,completion_tokens:e.usage.completion_tokens}:void 0}}parseStreamChunk(e){if(!e.startsWith("data: "))return null;const t=e.slice(6).trim();if("[DONE]"===t)return{type:"done"};try{const e=JSON.parse(t),s=e.choices?.[0]?.delta;if(!s)return null;if(s.tool_calls?.length){const e=s.tool_calls[0];return{type:"tool_call_delta",index:e.index,id:e.id,name:e.function?.name,argumentsDelta:e.function?.arguments||""}}return s.content?{type:"text",content:s.content}:e.usage?{type:"usage",usage:e.usage}:null}catch{return null}}_safeParseArgs(e){if(!e)return{};try{return JSON.parse(e)}catch{return{}}}},anthropic:C,ollama:class extends D{constructor(e){super(e),this.model=e.model||"llama3"}getHeaders(){return{"Content-Type":"application/json"}}formatRequest(e,t={}){const s={model:t.model||this.model,messages:e.map(e=>({role:e.role,content:e.content}))};if(t.tools?.length&&(s.tools=t.tools.map(e=>({type:"function",function:{name:e.name,description:e.description,parameters:e.parameters}}))),void 0!==t.temperature&&(s.options={temperature:t.temperature}),void 0!==t.stream&&(s.stream=t.stream),t.responseFormat){const e=t.responseFormat;"json"===e||"json_object"===e?.type?s.format="json":"json_schema"===e?.type&&(s.format=e.schema)}return s}parseResponse(e){const t=e.message||{},s=(t.tool_calls||[]).map((e,t)=>({id:`ollama_${t}_${Date.now()}`,name:e.function?.name,arguments:e.function?.arguments||{}}));return{content:t.content||"",tool_calls:s.length>0?s:void 0,usage:e.eval_count?{prompt_tokens:e.prompt_eval_count||0,completion_tokens:e.eval_count||0}:void 0}}parseStreamChunk(e){try{const t=JSON.parse(e);return t.done?{type:"done"}:t.message?.content?{type:"text",content:t.message.content}:null}catch{return null}}}};class W{constructor(){this._providers=new Map,this._active=null,this._activeName=null,this._activeConfig={},this._retryConfig={maxRetries:3,baseDelayMs:1e3}}register(e,s={}){const r=s.adapter||e,i=P[r];let n;if(s.send||s.stream)n=new L(s);else{if(!i)throw new Error(`[wu-ai] Unknown adapter '${r}'. Available: ${Object.keys(P).join(", ")}, or provide custom send/stream.`);n=new i(s)}this._providers.set(e,{adapter:n,config:s}),this._active&&!1===s.active||(this._active=n,this._activeName=e,this._activeConfig=s),t.wuInfo(`[wu-ai] Provider registered: '${e}' (adapter: ${r})`)}use(e){const t=this._providers.get(e);if(!t)throw new Error(`[wu-ai] Provider '${e}' not registered`);this._active=t.adapter,this._activeName=e,this._activeConfig=t.config}async send(e,s={}){const{adapter:r,config:i}=this._resolveProvider(s.provider);if(r.isCustom&&r._sendFn)return r._sendFn(e,s);const n=i.endpoint||i.baseUrl;if(!n)throw new Error("[wu-ai] No endpoint configured. Set config.endpoint or config.baseUrl.");const o=this._resolveUrl(n),a=r.formatRequest(e,{...s,stream:!1}),c=r.getHeaders(i),l=await this._fetchWithRetry(o,{method:"POST",headers:c,body:JSON.stringify(a),signal:s.signal}),u=await l.json(),d=r.parseResponse(u);if(r instanceof C&&s.responseFormat&&d.content&&(d.content="{"+d.content),s.responseFormat&&d.content)try{d.parsed=JSON.parse(d.content)}catch{d.parseError="Response is not valid JSON",t.wuDebug("[wu-ai] responseFormat requested but LLM returned invalid JSON")}return d}async*stream(e,t={}){const{adapter:s,config:r}=this._resolveProvider(t.provider);if(s.isCustom&&s._streamFn)return void(yield*s._streamFn(e,t));const i=r.endpoint||r.baseUrl;if(!i)throw new Error("[wu-ai] No endpoint configured. Set config.endpoint or config.baseUrl.");const n=this._resolveUrl(i),o=s.formatRequest(e,{...t,stream:!0}),a=s.getHeaders(r),c=await fetch(n,{method:"POST",headers:a,body:JSON.stringify(o),signal:t.signal});if(!c.ok)throw new Error(`[wu-ai] Stream request failed: ${c.status} ${c.statusText}`);const l=c.body.getReader(),u=new TextDecoder;let d="",h=s instanceof C&&!!t.responseFormat;try{for(;;){const{done:e,value:t}=await l.read();if(e)break;d+=u.decode(t,{stream:!0});const r=d.split("\n");d=r.pop()||"";for(const e of r){const t=e.trim();if(!t)continue;const r=s.parseStreamChunk(t);if(r&&(h&&"text"===r.type&&(r.content="{"+r.content,h=!1),yield r),"done"===r?.type)return}}if(d.trim()){const e=s.parseStreamChunk(d.trim());e&&(yield e)}}finally{l.releaseLock()}}async _fetchWithRetry(e,s){let r;for(let i=0;i<=this._retryConfig.maxRetries;i++)try{const n=await fetch(e,s);if(n.ok)return n;if((429===n.status||n.status>=500)&&(r=new Error(`HTTP ${n.status}: ${n.statusText}`),i<this._retryConfig.maxRetries)){const e=this._retryConfig.baseDelayMs*Math.pow(2,i);t.wuDebug(`[wu-ai] Retry ${i+1}/${this._retryConfig.maxRetries} in ${e}ms (${n.status})`),await new Promise(t=>setTimeout(t,e));continue}const o=new Error(`[wu-ai] Request failed: ${n.status} ${n.statusText}`);throw o._noRetry=!0,o}catch(e){if("AbortError"===e.name)throw e;if(e._noRetry)throw e;if(r=e,i<this._retryConfig.maxRetries){const e=this._retryConfig.baseDelayMs*Math.pow(2,i);await new Promise(t=>setTimeout(t,e));continue}}throw r}_resolveUrl(e){return e.startsWith("/")&&"undefined"!=typeof window?`${window.location.origin}${e}`:e}_resolveProvider(e){if(e){const t=this._providers.get(e);if(!t)throw new Error(`[wu-ai] Provider '${e}' not registered. Available: ${[...this._providers.keys()].join(", ")}`);return{adapter:t.adapter,config:t.config}}return this._ensureActive(),{adapter:this._active,config:this._activeConfig}}_ensureActive(){if(!this._active)throw new Error('[wu-ai] No provider configured. Call wu.ai.provider("name", { endpoint, adapter }) first.')}configureRetry(e){void 0!==e.maxRetries&&(this._retryConfig.maxRetries=e.maxRetries),void 0!==e.baseDelayMs&&(this._retryConfig.baseDelayMs=e.baseDelayMs)}getActiveProvider(){return this._activeName}getStats(){return{activeProvider:this._activeName,registeredProviders:[...this._providers.keys()]}}}const M={readStore:!0,writeStore:!1,emitEvents:!0,readDOM:!1,modifyDOM:!1,executeActions:!0,allowDirectKey:!1},I="closed",T="open",N="half-open";class R{constructor(e={}){this._maxPerMinute=e.requestsPerMinute??20,this._maxPerMinutePerNs=e.requestsPerMinutePerNs??10,this._maxConcurrent=e.maxConcurrent??3,this._globalTimestamps=[],this._nsTimestamps=new Map,this._concurrent=0}configure(e){void 0!==e.requestsPerMinute&&(this._maxPerMinute=e.requestsPerMinute),void 0!==e.requestsPerMinutePerNs&&(this._maxPerMinutePerNs=e.requestsPerMinutePerNs),void 0!==e.maxConcurrent&&(this._maxConcurrent=e.maxConcurrent)}canSend(e="default"){if(this._pruneOld(),this._concurrent>=this._maxConcurrent)return{allowed:!1,reason:`Max concurrent (${this._maxConcurrent}) reached`};if(this._globalTimestamps.length>=this._maxPerMinute)return{allowed:!1,reason:`Global rate limit (${this._maxPerMinute}/min) exceeded`};return(this._nsTimestamps.get(e)||[]).length>=this._maxPerMinutePerNs?{allowed:!1,reason:`Namespace '${e}' rate limit (${this._maxPerMinutePerNs}/min) exceeded`}:{allowed:!0}}recordStart(e="default"){const t=Date.now();this._globalTimestamps.push(t),this._nsTimestamps.has(e)||this._nsTimestamps.set(e,[]),this._nsTimestamps.get(e).push(t),this._concurrent++}recordEnd(){this._concurrent=Math.max(0,this._concurrent-1)}_pruneOld(){const e=Date.now()-6e4;this._globalTimestamps=this._globalTimestamps.filter(t=>t>e);for(const[t,s]of this._nsTimestamps){const r=s.filter(t=>t>e);0===r.length?this._nsTimestamps.delete(t):this._nsTimestamps.set(t,r)}}getStats(){return this._pruneOld(),{globalRequestsLastMinute:this._globalTimestamps.length,concurrent:this._concurrent,maxPerMinute:this._maxPerMinute,maxConcurrent:this._maxConcurrent}}}class O{constructor(e={}){this._state=I,this._failureCount=0,this._maxFailures=e.maxFailures??3,this._cooldownMs=e.cooldownMs??3e4,this._openedAt=0,this._rapidFireThreshold=e.rapidFireThreshold??5,this._rapidFireWindowMs=e.rapidFireWindowMs??2e3,this._recentRequests=[]}configure(e){void 0!==e.maxFailures&&(this._maxFailures=e.maxFailures),void 0!==e.cooldownMs&&(this._cooldownMs=e.cooldownMs)}canPass(){if(this._state===I)return{allowed:!0};if(this._state===T){if(Date.now()-this._openedAt>=this._cooldownMs)return this._state=N,t.wuDebug("[wu-ai] Circuit breaker โ†’ HALF-OPEN (testing)"),{allowed:!0};const e=this._cooldownMs-(Date.now()-this._openedAt);return{allowed:!1,reason:`Circuit breaker OPEN (${Math.ceil(e/1e3)}s remaining)`}}return{allowed:!0}}recordSuccess(){this._state===N?(this._state=I,this._failureCount=0,t.wuInfo("[wu-ai] Circuit breaker โ†’ CLOSED (recovered)")):this._failureCount=0,this._recordRequest()}recordFailure(){this._failureCount++,this._recordRequest(),this._state!==N?this._failureCount>=this._maxFailures&&this._tripOpen(`${this._failureCount} consecutive failures`):this._tripOpen("Failed during half-open test")}_recordRequest(){const e=Date.now();this._recentRequests.push(e),this._recentRequests=this._recentRequests.filter(t=>e-t<this._rapidFireWindowMs),this._state===I&&this._recentRequests.length>=this._rapidFireThreshold&&this._tripOpen(`${this._recentRequests.length} requests in ${this._rapidFireWindowMs}ms (rapid fire)`)}_tripOpen(e){this._state=T,this._openedAt=Date.now(),t.wuWarn(`[wu-ai] Circuit breaker โ†’ OPEN: ${e}. Cooldown: ${this._cooldownMs/1e3}s`)}getState(){return this._state}getStats(){return{state:this._state,failureCount:this._failureCount,maxFailures:this._maxFailures,cooldownMs:this._cooldownMs,openedAt:this._openedAt}}reset(){this._state=I,this._failureCount=0,this._openedAt=0,this._recentRequests=[]}}class j{constructor(e={}){this._maxDepth=e.maxDepth??3,this._activeTraces=new Map,this._traceLog=[],this._maxTraceLog=50}configure(e){void 0!==e.maxDepth&&(this._maxDepth=e.maxDepth)}canProceed(e,t){if(e>this._maxDepth)return{allowed:!1,reason:`Max AI depth (${this._maxDepth}) exceeded at depth ${e}`};if(t){const e=(this._activeTraces.get(t)||0)+1;if(e>this._maxDepth)return{allowed:!1,reason:`Causal chain '${t}' looped ${e} times (max ${this._maxDepth})`}}return{allowed:!0}}enter(e){if(!e)return;const t=(this._activeTraces.get(e)||0)+1;this._activeTraces.set(e,t),this._traceLog.push({traceId:e,count:t,timestamp:Date.now()}),this._traceLog.length>this._maxTraceLog&&this._traceLog.shift()}exit(e){if(!e)return;const t=(this._activeTraces.get(e)||0)-1;t<=0?this._activeTraces.delete(e):this._activeTraces.set(e,t)}createTraceId(){return`t_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,8)}`}getTraces(){return[...this._traceLog]}getStats(){return{maxDepth:this._maxDepth,activeTraces:this._activeTraces.size,traceLogSize:this._traceLog.length}}}class F{constructor(e={}){this._permissions={...M},this.rateLimiter=new R(e.rateLimit),this.circuitBreaker=new O(e.circuitBreaker),this.loopProtection=new j(e.loopProtection),this._allowedDomains=e.allowedDomains||[],e.permissions&&this.configure(e.permissions)}configure(e){Object.assign(this._permissions,e),this._isProduction()&&this._permissions.allowDirectKey&&(t.wuWarn("[wu-ai] allowDirectKey FORCED to false in production"),this._permissions.allowDirectKey=!1)}check(e){return!0===this._permissions[e]}getPermissions(){return{...this._permissions}}setAllowedDomains(e){this._allowedDomains=e}isDomainAllowed(e){if(0===this._allowedDomains.length)return!0;try{const t=new URL(e).hostname;return this._allowedDomains.some(e=>{if(e.startsWith("*.")){const s=e.slice(2);return t===s||t.endsWith("."+s)}return t===e})}catch{return!1}}preflight(e={}){const t=this.circuitBreaker.canPass();if(!t.allowed)return t;const s=this.rateLimiter.canSend(e.namespace);if(!s.allowed)return s;const r=this.loopProtection.canProceed(e.depth||0,e.traceId);return r.allowed?{allowed:!0}:r}getStats(){return{permissions:{...this._permissions},rateLimiter:this.rateLimiter.getStats(),circuitBreaker:this.circuitBreaker.getStats(),loopProtection:this.loopProtection.getStats(),allowedDomains:[...this._allowedDomains]}}_isProduction(){if("undefined"!=typeof process&&"production"===process.env?.NODE_ENV)return!0;if("undefined"!=typeof window){const e=window.location?.hostname||"";return"localhost"!==e&&"127.0.0.1"!==e&&"0.0.0.0"!==e&&!e.endsWith(".local")}return!1}}const B=["password","token","apiKey","secret","credential","authorization","cookie","session"];function z(e,t=2e3){if(null==e)return"null";if("function"==typeof e)return"[Function]";if("symbol"==typeof e)return"[Symbol]";if("string"==typeof e){return`<user_data>${e.length>t?e.slice(0,t)+"...[truncated]":e}</user_data>`}if("number"==typeof e||"boolean"==typeof e)return String(e);if("object"==typeof e){const s=H(e),r=JSON.stringify(s);return r.length>t?`<user_data>${r.slice(0,t)}...[truncated]</user_data>`:`<user_data>${r}</user_data>`}return String(e).slice(0,t)}function H(e,t=0){if(t>10)return"[MAX_DEPTH]";if(null==e)return e;if("object"!=typeof e)return e;if(Array.isArray(e))return e.map(e=>H(e,t+1));const s={};for(const[r,i]of Object.entries(e)){const e=r.toLowerCase();B.some(t=>e.includes(t.toLowerCase()))?s[r]="[REDACTED]":s[r]=H(i,t+1)}return s}function q(e,t){return e.replace(/\{\{(\w+(?:\.\w+)*)\}\}/g,(e,s)=>{const r=s.split(".").reduce((e,t)=>e?.[t],t);return null==r?"":"object"==typeof r?z(r):String(r)})}function U(e){const t=[];for(const[s,r]of e)t.push({name:s,description:r.description||`Execute action: ${s}`,parameters:J(r.parameters)});return t}function J(e){if(!e||"object"!=typeof e)return{type:"object",properties:{},required:[]};if("object"===e.type&&e.properties)return e;const t={},s=[];for(const[r,i]of Object.entries(e))if("string"==typeof i)t[r]={type:i};else if("object"==typeof i){const{required:e,...n}=i;t[r]=n.type?n:{type:"string",...n},e&&s.push(r)}return{type:"object",properties:t,required:s}}function K(e,t){const s=[];if(!t||!t.properties)return{valid:!0,errors:s};for(const r of t.required||[])void 0!==e[r]&&null!==e[r]||s.push(`'${r}' is required`);for(const[r,i]of Object.entries(t.properties)){const t=e[r];if(null!=t){if(i.type&&"any"!==i.type){const e=Array.isArray(t)?"array":typeof t;"integer"===i.type?"number"==typeof t&&Number.isInteger(t)||s.push(`'${r}' must be integer, got ${e}`):i.type!==e&&s.push(`'${r}' must be ${i.type}, got ${e}`)}i.enum&&!i.enum.includes(t)&&s.push(`'${r}' must be one of [${i.enum.join(", ")}], got '${t}'`)}}return{valid:0===s.length,errors:s}}class G{constructor({store:e,eventBus:t,core:s}){this._store=e,this._eventBus=t,this._core=s,this._config={budget:4e3,charRatio:4,sources:{store:{include:[],priority:"high"},events:{include:[],lastN:10,priority:"medium"},custom:[]}},this._collectors=new Map,this._lastSnapshot=null}configure(e){void 0!==e.budget&&(this._config.budget=e.budget),void 0!==e.charRatio&&(this._config.charRatio=e.charRatio),e.sources&&(e.sources.store&&Object.assign(this._config.sources.store,e.sources.store),e.sources.events&&Object.assign(this._config.sources.events,e.sources.events),e.sources.custom&&(this._config.sources.custom=e.sources.custom))}register(e,s){this._collectors.set(e,{collector:s.collector,priority:s.priority||"medium"}),t.wuDebug(`[wu-ai] Context collector registered: '${e}' (${s.priority||"medium"})`)}async collect(){const e={_timestamp:Date.now(),_mountedApps:this._getMountedApps()},s=this._collectStore();s&&Object.keys(s).length>0&&(e._store=s);const r=this._collectEvents();r.length>0&&(e._events=r);for(const s of this._config.sources.custom)try{const t="function"==typeof s.value?await s.value():s.value;e[s.key]=t}catch(e){t.wuDebug(`[wu-ai] Custom collector '${s.key}' failed: ${e.message}`)}for(const[s,r]of this._collectors)try{const t=await r.collector();e[s]=t}catch(e){t.wuDebug(`[wu-ai] Collector '${s}' failed: ${e.message}`)}return this._lastSnapshot=e,e}toSystemPrompt(e={}){const t=this._lastSnapshot;if(!t)return this._baseSystemPrompt(e);const s=[];s.push("You are an AI assistant connected to a live web application via Wu Framework.","You can observe application state and execute actions when appropriate.",""),t._mountedApps?.length&&s.push(`MOUNTED APPS: ${t._mountedApps.join(", ")}`,"");const r=this._config.budget*this._config.charRatio;let i=s.join("\n").length;const n=this._prioritizeSections(t);for(const e of n){const t=e.text;if(i+t.length>r){if("high"===e.priority){const e=r-i;e>100&&(s.push(t.slice(0,e)+"\n...[truncated]"),i+=e)}}else s.push(t),i+=t.length}if(e.tools?.length){s.push("","AVAILABLE TOOLS:");for(const t of e.tools)s.push(`- ${t.name}: ${t.description}`)}return s.join("\n")}getSnapshot(){return this._lastSnapshot}getInterpolationContext(){if(!this._lastSnapshot)return{};const{_timestamp:e,_mountedApps:t,_store:s,_events:r,...i}=this._lastSnapshot;return{apps:t,store:s,events:r,...i}}_collectStore(){if(!this._store)return{};const{include:e}=this._config.sources.store;if(!e||0===e.length)return{};const t={};for(const s of e)try{const e=this._store.get(s);void 0!==e&&(t[s]=H(e))}catch{}return t}_collectEvents(){if(!this._eventBus)return[];const{include:e,lastN:t}=this._config.sources.events;if(!e||0===e.length)return[];return(this._eventBus.history||[]).filter(t=>e.some(e=>this._matchPattern(t.name||t.event,e))).slice(-(t||10)).map(e=>({event:e.name||e.event,data:H(e.data),timestamp:e.timestamp}))}_getMountedApps(){if(!this._core)return[];try{if(this._core.mounted instanceof Map)return[...this._core.mounted.keys()];const e=this._core.getStats?.();return e?.apps||e?.mounted||[]}catch{return[]}}_prioritizeSections(e){const t=[],s=this._config.sources.store.priority||"high",r=this._config.sources.events.priority||"medium";if(e._store&&Object.keys(e._store).length>0&&t.push({priority:s,text:`APPLICATION STATE:\n${JSON.stringify(e._store,null,2)}`}),e._events?.length){const s=e._events.map(e=>` [${e.event}] ${JSON.stringify(e.data)}`).join("\n");t.push({priority:r,text:`RECENT EVENTS:\n${s}`})}for(const[s,r]of this._collectors)void 0!==e[s]&&t.push({priority:r.priority,text:`${s.toUpperCase()}:\n${JSON.stringify(e[s],null,2)}`});for(const s of this._config.sources.custom)void 0!==e[s.key]&&t.push({priority:s.priority||"low",text:`${s.key}: ${JSON.stringify(e[s.key])}`});const i={high:0,medium:1,low:2};return t.sort((e,t)=>(i[e.priority]??1)-(i[t.priority]??1)),t}_baseSystemPrompt(e={}){let t="You are an AI assistant connected to a web application via Wu Framework.";return e.tools?.length&&(t+="\n\nAVAILABLE TOOLS:\n"+e.tools.map(e=>`- ${e.name}: ${e.description}`).join("\n")),t}_matchPattern(e,t){if(!e||!t)return!1;if("*"===t)return!0;if(!t.includes("*"))return e===t;return new RegExp("^"+t.replace(/\*/g,"[^:]*")+"$").test(e)}getStats(){return{budget:this._config.budget,collectors:[...this._collectors.keys()],storePaths:this._config.sources.store.include,eventPatterns:this._config.sources.events.include,lastCollected:this._lastSnapshot?._timestamp||null}}}class V{constructor({eventBus:e,store:t,permissions:s}){this._eventBus=e,this._store=t,this._permissions=s,this._actions=new Map,this._executionLog=[],this._maxLogSize=100,this._pendingConfirms=new Map}register(e,s){if(!s.handler||"function"!=typeof s.handler)throw new Error(`[wu-ai] Action '${e}' must have a handler function`);this._actions.set(e,{description:s.description||`Execute: ${e}`,parameters:J(s.parameters),handler:s.handler,confirm:s.confirm||!1,permissions:s.permissions||[],dangerous:s.dangerous||!1}),t.wuDebug(`[wu-ai] Action registered: '${e}'${s.dangerous?" [DANGEROUS]":""}`)}unregister(e){this._actions.delete(e)}async execute(e,s,r={}){const i=this._actions.get(e);if(!i)return{success:!1,reason:`Action '${e}' not registered`};for(const t of i.permissions)if(!this._permissions.check(t))return this._emitDenied(e,s,`Missing permission: ${t}`),{success:!1,reason:`Permission denied: ${t}`};const n=K(s||{},i.parameters);if(!n.valid)return{success:!1,reason:`Invalid params: ${n.errors.join(", ")}`};if(i.confirm){if(!await this._requestConfirmation(e,s,r.callId))return{success:!1,reason:"User denied action"}}try{i.dangerous&&t.wuWarn(`[wu-ai] Executing DANGEROUS action: '${e}' with params: ${JSON.stringify(s)}`);const n=this._createSandboxedApi(i.permissions),o=await i.handler(s,n);return this._log(e,s,o,r),this._eventBus.emit("ai:action:executed",{action:e,params:s,result:o,traceId:r.traceId},{appName:"wu-ai"}),{success:!0,result:o}}catch(t){return this._eventBus.emit("ai:action:error",{action:e,params:s,error:t.message,traceId:r.traceId},{appName:"wu-ai"}),{success:!1,reason:t.message}}}getToolSchemas(){return U(this._actions)}has(e){return this._actions.has(e)}getNames(){return[...this._actions.keys()]}getLog(){return[...this._executionLog]}confirmTool(e){const t=this._pendingConfirms.get(e);t&&(clearTimeout(t.timeout),this._pendingConfirms.delete(e),t.resolve(!0))}rejectTool(e){const t=this._pendingConfirms.get(e);t&&(clearTimeout(t.timeout),this._pendingConfirms.delete(e),t.resolve(!1))}_createSandboxedApi(e){const t={},s=new Set(e);return this._permissions.check("readStore")&&(t.getState=e=>this._store.get(e)),this._permissions.check("writeStore")&&s.has("writeStore")&&(t.setState=(e,t)=>this._store.set(e,t)),this._permissions.check("emitEvents")&&(t.emit=(e,t)=>this._eventBus.emit(e,t,{appName:"wu-ai"})),t}_requestConfirmation(e,s,r){const i=r||`confirm_${Date.now()}_${Math.random().toString(36).slice(2,6)}`;return new Promise(r=>{const n=setTimeout(()=>{this._pendingConfirms.delete(i),r(!1),t.wuDebug(`[wu-ai] Confirmation timeout for action '${e}'`)},3e4);this._pendingConfirms.set(i,{resolve:r,timeout:n}),this._eventBus.emit("ai:tool:confirm",{callId:i,action:e,params:s,message:`AI wants to execute: ${e}`},{appName:"wu-ai"})})}_log(e,t,s,r){this._executionLog.push({action:e,params:t,result:"object"==typeof s?{...s}:s,timestamp:Date.now(),traceId:r.traceId}),this._executionLog.length>this._maxLogSize&&this._executionLog.shift()}_emitDenied(e,s,r){this._eventBus.emit("ai:action:denied",{action:e,params:s,reason:r},{appName:"wu-ai"}),t.wuWarn(`[wu-ai] Action denied: '${e}' โ€” ${r}`)}getStats(){return{registeredActions:[...this._actions.keys()],executionLogSize:this._executionLog.length,pendingConfirmations:this._pendingConfirms.size}}}const Q={maxHistoryMessages:50,maxToolRounds:5,defaultNamespace:"default",systemPrompt:null,temperature:void 0,maxTokens:void 0,namespaceTTL:18e5,gcInterval:3e5};class Y{constructor(e){this.name=e,this.messages=[],this.createdAt=Date.now(),this.lastActivity=Date.now(),this._abortController=null}addMessage(e){this.messages.push({...e,_ts:Date.now()}),this.lastActivity=Date.now()}getMessages(){return this.messages.map(({_ts:e,...t})=>t)}truncate(e){if(this.messages.length<=e)return;const t=this.messages.filter(e=>"system"===e.role),s=this.messages.filter(e=>"system"!==e.role).slice(-e);this.messages=[...t,...s]}clear(){this.messages=[],this.lastActivity=Date.now()}abort(){this._abortController&&(this._abortController.abort(),this._abortController=null)}createAbortController(){return this.abort(),this._abortController=new AbortController,this._abortController}}class X{constructor({provider:e,actions:t,context:s,permissions:r,eventBus:i}){this._provider=e,this._actions=t,this._context=s,this._permissions=r,this._eventBus=i,this._config={...Q},this._namespaces=new Map,this._activeRequests=new Map,this._lastGcRun=Date.now()}configure(e){Object.assign(this._config,e)}async send(e,s={}){const r=this._getOrCreateNamespace(s.namespace),i=this._permissions.loopProtection.createTraceId(),n={namespace:r.name,depth:0,traceId:i},o=this._permissions.preflight(n);if(!o.allowed)return{content:`[blocked] ${o.reason}`,namespace:r.name};const a=await this._buildSystemPrompt(s);this._setSystemMessage(r,a);const c=this._processMessage(e,s.templateVars);r.addMessage({role:"user",content:c}),r.truncate(this._config.maxHistoryMessages);const l=r.createAbortController(),u=this._mergeSignals(l.signal,s.signal);this._permissions.rateLimiter.recordStart(r.name);try{const e=[];let n=0;const o=this._config.maxToolRounds;for(;n<=o;){const a=this._actions.getToolSchemas(),c=await this._provider.send(r.getMessages(),{tools:a.length>0?a:void 0,temperature:s.temperature??this._config.temperature,maxTokens:s.maxTokens??this._config.maxTokens,responseFormat:s.responseFormat,provider:s.provider,signal:u}),l={role:"assistant",content:c.content||""};if(c.tool_calls&&(l.tool_calls=c.tool_calls),r.addMessage(l),!c.tool_calls||0===c.tool_calls.length)return this._permissions.circuitBreaker.recordSuccess(),this._eventBus.emit("ai:response",{namespace:r.name,content:c.content,toolResults:e.length>0?e:void 0,usage:c.usage,traceId:i},{appName:"wu-ai"}),{content:c.content||"",tool_results:e.length>0?e:void 0,usage:c.usage,namespace:r.name};if(n++,n>o){const s=`[wu-ai] Tool call loop limit (${o}) reached in namespace '${r.name}'`;return t.wuWarn(s),r.addMessage({role:"assistant",content:s}),{content:s,tool_results:e,namespace:r.name}}this._permissions.loopProtection.enter(i);for(const t of c.tool_calls){const s=await this._actions.execute(t.name,t.arguments,{traceId:i,depth:n,callId:t.id});e.push({tool:t.name,params:t.arguments,result:s.result,success:s.success}),r.addMessage({role:"tool",content:JSON.stringify(s.success?s.result:{error:s.reason}),tool_call_id:t.id})}this._permissions.loopProtection.exit(i)}return{content:"",tool_results:e,namespace:r.name}}catch(e){if(this._permissions.circuitBreaker.recordFailure(),"AbortError"===e.name)return{content:"[aborted]",namespace:r.name};throw this._eventBus.emit("ai:error",{namespace:r.name,error:e.message,traceId:i},{appName:"wu-ai"}),e}finally{this._permissions.rateLimiter.recordEnd(),r._abortController=null}}async*stream(e,s={}){const r=this._getOrCreateNamespace(s.namespace),i=this._permissions.loopProtection.createTraceId(),n={namespace:r.name,depth:0,traceId:i},o=this._permissions.preflight(n);if(!o.allowed)return void(yield{type:"error",error:o.reason});const a=await this._buildSystemPrompt(s);this._setSystemMessage(r,a);const c=this._processMessage(e,s.templateVars);r.addMessage({role:"user",content:c}),r.truncate(this._config.maxHistoryMessages);const l=r.createAbortController(),u=this._mergeSignals(l.signal,s.signal);this._permissions.rateLimiter.recordStart(r.name);try{let e=0;const n=this._config.maxToolRounds;for(;e<=n;){const o=this._actions.getToolSchemas();let a="";const c=new Map;let l=!1;for await(const e of this._provider.stream(r.getMessages(),{tools:o.length>0?o:void 0,temperature:s.temperature??this._config.temperature,maxTokens:s.maxTokens??this._config.maxTokens,responseFormat:s.responseFormat,provider:s.provider,signal:u}))if("text"===e.type)a+=e.content,yield e;else if("tool_call_start"===e.type)c.set(c.size,{id:e.id,name:e.name,args:""});else if("tool_call_delta"===e.type){const t=e.index??c.size-1,s=c.get(t);s?(e.id&&(s.id=e.id),e.name&&(s.name=e.name),s.args+=e.argumentsDelta||""):c.set(t,{id:e.id||`tc_${t}`,name:e.name||"",args:e.argumentsDelta||""})}else{if("done"===e.type){l=!0;break}("usage"===e.type||"error"===e.type)&&(yield e)}if(0===c.size)return a&&r.addMessage({role:"assistant",content:a}),this._permissions.circuitBreaker.recordSuccess(),void(yield{type:"done"});if(e++,e>n){const e=`[wu-ai] Tool call loop limit (${n}) reached in streaming namespace '${r.name}'`;return t.wuWarn(e),yield{type:"error",error:e},void(yield{type:"done"})}const d=[];for(const[,e]of c){let t={};try{t=JSON.parse(e.args)}catch{}d.push({id:e.id,name:e.name,arguments:t})}r.addMessage({role:"assistant",content:a,tool_calls:d}),this._permissions.loopProtection.enter(i);for(const t of d){const s=await this._actions.execute(t.name,t.arguments,{traceId:i,depth:e,callId:t.id});yield{type:"tool_result",tool:t.name,result:s.success?s.result:{error:s.reason},success:s.success},r.addMessage({role:"tool",content:JSON.stringify(s.success?s.result:{error:s.reason}),tool_call_id:t.id})}this._permissions.loopProtection.exit(i),yield{type:"tool_calls_done",count:d.length}}}catch(e){if(this._permissions.circuitBreaker.recordFailure(),"AbortError"===e.name)return void(yield{type:"error",error:"aborted"});yield{type:"error",error:e.message},this._eventBus.emit("ai:error",{namespace:r.name,error:e.message,traceId:i},{appName:"wu-ai"})}finally{this._permissions.rateLimiter.recordEnd(),r._abortController=null}}inject(e,t,s={}){this._getOrCreateNamespace(s.namespace).addMessage({role:e,content:t})}getHistory(e){const t=this._namespaces.get(e||this._config.defaultNamespace);return t?t.getMessages():[]}clear(e){const t=this._namespaces.get(e||this._config.defaultNamespace);t&&t.clear()}clearAll(){for(const e of this._namespaces.values())e.clear()}abort(e){const t=this._namespaces.get(e||this._config.defaultNamespace);t&&t.abort()}abortAll(){for(const e of this._namespaces.values())e.abort()}getNamespaces(){return[...this._namespaces.keys()]}deleteNamespace(e){const t=this._namespaces.get(e);t&&(t.abort(),this._namespaces.delete(e))}_getOrCreateNamespace(e){const t=e||this._config.defaultNamespace;this._maybeGcSweep(),this._namespaces.has(t)||this._namespaces.set(t,new Y(t));const s=this._namespaces.get(t);return s.lastActivity=Date.now(),s}_maybeGcSweep(){const e=this._config.namespaceTTL,s=this._config.gcInterval;if(!e||e<=0)return;const r=Date.now();if(r-this._lastGcRun<s)return;this._lastGcRun=r;const i=r-e,n=[];for(const[e,t]of this._namespaces)e!==this._config.defaultNamespace&&(t._abortController||t.lastActivity<i&&n.push(e));for(const e of n)this._namespaces.delete(e);n.length>0&&t.wuDebug(`[wu-ai] GC sweep: removed ${n.length} expired namespace(s): ${n.join(", ")}`)}async _buildSystemPrompt(e){if(e.systemPrompt)return"function"==typeof e.systemPrompt?await e.systemPrompt():e.systemPrompt;if(this._config.systemPrompt)return"function"==typeof this._config.systemPrompt?await this._config.systemPrompt():this._config.systemPrompt;if(this._context){await this._context.collect();const e=this._actions.getToolSchemas();return this._context.toSystemPrompt({tools:e})}return"You are an AI assistant connected to a web application via Wu Framework."}_setSystemMessage(e,t){e.messages.length>0&&"system"===e.messages[0].role?(e.messages[0].content=t,e.messages[0]._ts=Date.now()):e.messages.unshift({role:"system",content:t,_ts:Date.now()})}_processMessage(e,t){if(!t)return e;try{return q(e,{...this._context?.getInterpolationContext()||{},...t})}catch{return e}}_mergeSignals(e,t){if(!t)return e;if("undefined"!=typeof AbortSignal&&AbortSignal.any)return AbortSignal.any([e,t]);const s=new AbortController,r=()=>s.abort();return e.addEventListener("abort",r,{once:!0}),t.addEventListener("abort",r,{once:!0}),s.signal}getStats(){const e={};for(const[t,s]of this._namespaces)e[t]={messageCount:s.messages.length,lastActivity:s.lastActivity,hasActiveRequest:!!s._abortController};return{namespaces:e,config:{...this._config}}}}const Z={enabled:!0,maxActiveTriggers:20,defaultDebounceMs:1e3,batchIntervalMs:2e3};class ee{constructor(e,t){this.name=e,this.pattern=t.pattern,this.prompt=t.prompt,this.condition=t.condition||null,this.debounceMs=t.debounce??Z.defaultDebounceMs,this.priority=t.priority||"medium",this.namespace=t.namespace||`trigger:${e}`,this.systemPrompt=t.systemPrompt||null,this.onResult=t.onResult||null,this.enabled=!1!==t.enabled,this.maxTokens=t.maxTokens||void 0,this.temperature=t.temperature||void 0,this._debounceTimer=null,this._lastFired=0,this._fireCount=0,this._pendingEvent=null}matches(e){if(!this.pattern)return!1;if("*"===this.pattern)return!0;if(!this.pattern.includes("*"))return e===this.pattern;return new RegExp("^"+this.pattern.replace(/\*/g,"[^:]*")+"$").test(e)}buildPrompt(e){return"function"==typeof this.prompt?this.prompt(e):q(this.prompt,{event:e,data:e?.data,timestamp:Date.now()})}async checkCondition(e){if(!this.condition)return!0;try{const t=this.condition(e);return t instanceof Promise?await t:t}catch(e){return t.wuDebug(`[wu-ai] Trigger '${this.name}' condition error: ${e.message}`),!1}}}class te{constructor({eventBus:e,conversation:t,permissions:s}){this._eventBus=e,this._conversation=t,this._permissions=s,this._config={...Z},this._triggers=new Map,this._listeners=new Map,this._batchQueue=[],this._batchTimer=null,this._stats={totalFired:0,totalSkipped:0,totalErrors:0}}configure(e){Object.assign(this._config,e)}register(e,s){if(this._triggers.size>=this._config.maxActiveTriggers)return void t.wuWarn(`[wu-ai] Max triggers (${this._config.maxActiveTriggers}) reached. Cannot register '${e}'.`);this._triggers.has(e)&&this.unregister(e);const r=new ee(e,s);this._triggers.set(e,r);const i=this._eventBus.on(r.pattern,t=>this._handleEvent(e,t));this._listeners.set(e,i),t.wuDebug(`[wu-ai] Trigger registered: '${e}' โ†’ pattern '${r.pattern}' (${r.priority})`)}unregister(e){const t=this._triggers.get(e);t&&t._debounceTimer&&clearTimeout(t._debounceTimer);const s=this._listeners.get(e);"function"==typeof s&&s(),this._triggers.delete(e),this._listeners.delete(e)}setEnabled(e,t){const s=this._triggers.get(e);s&&(s.enabled=t)}setAllEnabled(e){this._config.enabled=e;for(const t of this._triggers.values())t.enabled=e}async fire(e,s={}){const r=this._triggers.get(e);return r?this._executeTrigger(r,s):(t.wuWarn(`[wu-ai] Trigger '${e}' not found`),null)}getNames(){return[...this._triggers.keys()]}getTrigger(e){const t=this._triggers.get(e);return t?{name:t.name,pattern:t.pattern,priority:t.priority,namespace:t.namespace,enabled:t.enabled,fireCount:t._fireCount,lastFired:t._lastFired}:null}destroy(){for(const e of[...this._triggers.keys()])this.unregister(e);this._batchTimer&&(clearTimeout(this._batchTimer),this._batchTimer=null),this._batchQueue=[]}async _handleEvent(e,t){if(!this._config.enabled)return;const s=this._triggers.get(e);if(!s||!s.enabled)return;await s.checkCondition(t)?"high"===s.priority?this._debouncedFire(s,t):"low"===s.priority?(this._batchQueue.push({trigger:s,eventData:t}),this._scheduleBatch()):this._debouncedFire(s,t):this._stats.totalSkipped++}_debouncedFire(e,t){e._pendingEvent=t,e._debounceTimer&&clearTimeout(e._debounceTimer),e.debounceMs<=0?this._executeTrigger(e,t):e._debounceTimer=setTimeout(()=>{e._debounceTimer=null;const t=e._pendingEvent;e._pendingEvent=null,t&&this._executeTrigger(e,t)},e.debounceMs)}_scheduleBatch(){this._batchTimer||(this._batchTimer=setTimeout(()=>{this._batchTimer=null,this._processBatch()},this._config.batchIntervalMs))}async _processBatch(){const e=[...this._batchQueue];this._batchQueue=[];const t=new Map;for(const{trigger:s,eventData:r}of e)t.set(s.name,{trigger:s,eventData:r});for(const{trigger:e,eventData:s}of t.values())await this._executeTrigger(e,s)}async _executeTrigger(e,s){try{const r=e.buildPrompt(s);if(!r)return this._stats.totalSkipped++,null;t.wuDebug(`[wu-ai] Trigger '${e.name}' firing with prompt: ${r.slice(0,100)}...`);const i=await this._conversation.send(r,{namespace:e.namespace,systemPrompt:e.systemPrompt,temperature:e.temperature,maxTokens:e.maxTokens});if(e._fireCount++,e._lastFired=Date.now(),this._stats.totalFired++,this._eventBus.emit("ai:trigger:result",{trigger:e.name,pattern:e.pattern,result:i},{appName:"wu-ai"}),e.onResult)try{await e.onResult(i,s)}catch(s){t.wuDebug(`[wu-ai] Trigger '${e.name}' onResult error: ${s.message}`)}return i}catch(s){return this._stats.totalErrors++,t.wuWarn(`[wu-ai] Trigger '${e.name}' error: ${s.message}`),this._eventBus.emit("ai:trigger:error",{trigger:e.name,error:s.message},{appName:"wu-ai"}),null}}getStats(){const e={};for(const[t,s]of this._triggers)e[t]={pattern:s.pattern,priority:s.priority,enabled:s.enabled,fireCount:s._fireCount,lastFired:s._lastFired};return{...this._stats,triggerCount:this._triggers.size,batchQueueSize:this._batchQueue.length,triggers:e}}}const se="[DONE]",re="agent:";class ie{constructor({conversation:e,actions:t,context:s,permissions:r,eventBus:i}){this._conversation=e,this._actions=t,this._context=s,this._permissions=r,this._eventBus=i,this._config={maxSteps:10,systemPrompt:null},this._activeRuns=new Map,this._stats={totalRuns:0,totalSteps:0,completedRuns:0,abortedRuns:0,errorRuns:0}}configure(e){void 0!==e.maxSteps&&(this._config.maxSteps=e.maxSteps),void 0!==e.systemPrompt&&(this._config.systemPrompt=e.systemPrompt)}async*run(e,s={}){const r=s.maxSteps??this._config.maxSteps,i=s.namespace||this._generateNamespace(),n=this._generateRunId(),o=new AbortController;this._activeRuns.set(n,o),s.signal&&(s.signal.aborted?o.abort():s.signal.addEventListener("abort",()=>o.abort(),{once:!0})),this._stats.totalRuns++;const a=await this._buildAgentSystemPrompt(e,s);this._eventBus.emit("ai:agent:start",{runId:n,goal:e,namespace:i,maxSteps:r},{appName:"wu-ai"}),t.wuInfo(`[wu-ai] Agent run started: "${e.slice(0,80)}${e.length>80?"...":""}" (max ${r} steps)`);let c=0,l=!1,u="max_steps";try{for(;c<r;){c++;const t=Date.now();if(o.signal.aborted){const e=this._buildStepResult(c,"aborted",{reason:"Aborted by caller",elapsed:Date.now()-t});return this._stats.abortedRuns++,u="aborted",this._emitStep(n,e),void(yield e)}const r=this._permissions.loopProtection.createTraceId(),d=this._permissions.preflight({namespace:i,depth:c,traceId:r});if(!d.allowed){const e=this._buildStepResult(c,"blocked",{reason:d.reason,elapsed:Date.now()-t});return u="blocked",this._emitStep(n,e),void(yield e)}const h=1===c?e:"Continue working toward the goal. If you are done, include [DONE] in your response.";let p;try{p=await this._conversation.send(h,{namespace:i,systemPrompt:a,provider:s.provider,temperature:s.temperature,maxTokens:s.maxTokens,signal:o.signal})}catch(e){if("AbortError"===e.name||o.signal.aborted){const e=this._buildStepResult(c,"aborted",{reason:"Aborted during LLM call",elapsed:Date.now()-t});return this._stats.abortedRuns++,u="aborted",this._emitStep(n,e),void(yield e)}throw e}const m=Date.now()-t;this._stats.totalSteps++;const g=p.tool_results&&p.tool_results.length>0,f=p.content||"";if(f.includes(se)){const e=this._buildStepResult(c,"done",{content:f.replace(se,"").trim(),toolResults:p.tool_results,usage:p.usage,reason:"Goal completed (DONE marker)",elapsed:m});return u="done",this._stats.completedRuns++,this._emitStep(n,e),s.onStep&&await this._safeCallback(s.onStep,e),void(yield e)}const w=g;if(l&&!w){const e=this._buildStepResult(c,"done",{content:f,toolResults:p.tool_results,usage:p.usage,reason:"Goal completed (no further tool calls)",elapsed:m});return u="done",this._stats.completedRuns++,this._emitStep(n,e),s.onStep&&await this._safeCallback(s.onStep,e),void(yield e)}l=w;const y=g?"tool_call":"thinking",_=this._buildStepResult(c,y,{content:f,toolResults:p.tool_results,usage:p.usage,elapsed:m});if(this._emitStep(n,_),s.onStep&&await this._safeCallback(s.onStep,_),yield _,s.shouldContinue){let e;try{e=await s.shouldContinue(_)}catch{e=!1}if(!e){const e=this._buildStepResult(c,"interrupted",{content:f,reason:"Stopped by shouldContinue callback",elapsed:0});return u="interrupted",this._emitStep(n,e),void(yield e)}}}const t=this._buildStepResult(c,"done",{reason:`Max steps (${r}) reached`,elapsed:0});u="max_steps",yield t}catch(s){throw this._stats.errorRuns++,u="error",t.wuWarn(`[wu-ai] Agent run error: ${s.message}`),this._eventBus.emit("ai:agent:error",{runId:n,goal:e,namespace:i,step:c,error:s.message},{appName:"wu-ai"}),s}finally{this._activeRuns.delete(n),!s.namespace&&i.startsWith(re)&&this._conversation.deleteNamespace(i),this._eventBus.emit("ai:agent:done",{runId:n,goal:e,namespace:i,totalSteps:c,reason:u},{appName:"wu-ai"}),t.wuDebug(`[wu-ai] Agent run finished: ${u} after ${c} step(s)`)}}abort(e){const s=this._activeRuns.get(e);s&&(s.abort(),t.wuDebug(`[wu-ai] Agent run aborted: ${e}`))}abortAll(){for(const[e,t]of this._activeRuns)t.abort();this._activeRuns.clear()}getActiveRuns(){return[...this._activeRuns.keys()]}getStats(){return{...this._stats,activeRuns:this._activeRuns.size,config:{...this._config}}}destroy(){this.abortAll(),this._stats={totalRuns:0,totalSteps:0,completedRuns:0,abortedRuns:0,errorRuns:0}}async _buildAgentSystemPrompt(e,t){const s=t.systemPrompt??this._config.systemPrompt??null;if(s){return"function"==typeof s?await s(e):s}const r=[];if(r.push("You are an autonomous AI agent connected to a live web application via Wu Framework.","You have been given a goal and must work step-by-step to achieve it.","","PROTOCOL:",'- Each message you send is one "step" in your execution.',"- You may call tools to read or modify application state.","- After each step, you will be prompted to continue.","- When the goal is fully achieved, include the marker [DONE] in your response.","- If you determine the goal cannot be achieved, include [DONE] and explain why.","- Be concise. Each step should make meaningful progress.",""),this._context)try{await this._context.collect();const e=this._context.getSnapshot();e?._mountedApps?.length&&r.push(`MOUNTED APPS: ${e._mountedApps.join(", ")}`,""),e?._store&&Object.keys(e._store).length>0&&r.push(`APPLICATION STATE:\n${JSON.stringify(e._store,null,2)}`,"")}catch{}const i=this._actions.getToolSchemas();if(i.length>0){r.push("AVAILABLE TOOLS:");for(const e of i){const t=e.parameters?.properties?Object.keys(e.parameters.properties).join(", "):"none";r.push(`- ${e.name}(${t}): ${e.description}`)}r.push("")}return r.push(`GOAL: ${e}`),r.join("\n")}_buildStepResult(e,t,s={}){return{step:e,type:t,content:s.content??null,toolResults:s.toolResults??null,usage:s.usage??null,reason:s.reason??null,elapsed:s.elapsed??0}}_emitStep(e,t){this._eventBus.emit("ai:agent:step",{runId:e,...t},{appName:"wu-ai"})}async _safeCallback(e,...s){try{const t=e(...s);t&&"function"==typeof t.then&&await t}catch(e){t.wuDebug(`[wu-ai] Agent callback error: ${e.message}`)}}_generateNamespace(){return re+Date.now().toString(36)+"_"+Math.random().toString(36).slice(2,6)}_generateRunId(){return"run_"+Date.now().toString(36)+"_"+Math.random().toString(36).slice(2,8)}}const ne=[],oe=300,ae=[];let ce=!1;function le(){ce||(!function(){const e=window.fetch;window.fetch=async function(...t){const s=Date.now(),r=t[0],i="string"==typeof r?r:r?.url||"",n=(t[1]?.method||r?.method||"GET").toUpperCase();try{const r=await e.apply(window,t),o=parseInt(r.headers?.get("content-length")||"0",10);return ne.push({type:"fetch",method:n,url:i,status:r.status,statusText:r.statusText,duration:Date.now()-s,size:o,timestamp:s}),ne.length>oe&&ne.shift(),r}catch(e){throw ne.push({type:"fetch",method:n,url:i,status:0,error:e.message,duration:Date.now()-s,timestamp:s}),ne.length>oe&&ne.shift(),e}};const t=XMLHttpRequest.prototype.open,s=XMLHttpRequest.prototype.send;XMLHttpRequest.prototype.open=function(e,s,...r){return this._wuAi={method:(e||"GET").toUpperCase(),url:String(s)},t.call(this,e,s,...r)},XMLHttpRequest.prototype.send=function(...e){return this._wuAi&&(this._wuAi.start=Date.now(),this.addEventListener("loadend",()=>{ne.push({type:"xhr",method:this._wuAi.method,url:this._wuAi.url,status:this.status,statusText:this.statusText,duration:Date.now()-this._wuAi.start,size:parseInt(this.getResponseHeader("content-length")||"0",10),timestamp:this._wuAi.start}),ne.length>oe&&ne.shift()})),s.apply(this,e)}}(),function(){const e=["log","warn","error"];for(const t of e){const e=console[t];console[t]=(...s)=>{ae.push({level:t,message:s.map(e=>"object"==typeof e?JSON.stringify(e):String(e)).join(" "),timestamp:Date.now()}),ae.length>500&&ae.shift(),e.apply(console,s)}}}(),ce=!0)}function ue(e,t=0,s=5){if(t>s||!e)return"";const r=" ".repeat(t),i=e.tagName?.toLowerCase()||"",n=e.getAttribute?.("role")||"",o=e.getAttribute?.("aria-label")||"",a=1===e.childNodes?.length&&3===e.childNodes[0].nodeType?e.textContent?.trim().slice(0,80):"";let c=`${r}<${i}`;if(e.id&&(c+=` id="${e.id}"`),n&&(c+=` role="${n}"`),o&&(c+=` aria-label="${o}"`),e.className&&"string"==typeof e.className){const t=e.className.trim().slice(0,60);t&&(c+=` class="${t}"`)}c+=">",a&&(c+=` "${a}"`);let l=c+"\n";const u=(e.shadowRoot||e).children||[];for(let e=0;e<u.length&&e<50;e++)l+=ue(u[e],t+1,s);return l}function de(e,t){const s=["color","background","background-color","font-family","font-size","font-weight","border","border-radius","padding","margin","display","flex-direction","align-items","justify-content","gap","width","height","max-width","max-height","overflow","opacity","box-shadow","text-align","line-height","position","top","left","right","bottom","z-index","transform","visibility"];try{const r=window.getComputedStyle(e);for(const e of s){const s=r.getPropertyValue(e);s&&t.style?.setProperty(e,s)}}catch(e){}const r=e.children||[],i=t.children||[],n=Math.min(r.length,i.length,200);for(let e=0;e<n;e++)de(r[e],i[e])}async function he(e,t=.8){const s=e?document.querySelector(e):document.documentElement;if(!s)return{error:`Element not found: ${e}`};const r=s.getBoundingClientRect(),i=Math.ceil(Math.min(r.width||window.innerWidth,1920)),n=Math.ceil(Math.min(r.height||window.innerHeight,1080)),o=s.cloneNode(!0);de(s,o);const a=(new XMLSerializer).serializeToString(o),c=[`<svg xmlns="http://www.w3.org/2000/svg" width="${i}" height="${n}">`,'<foreignObject width="100%" height="100%">',`<div xmlns="http://www.w3.org/1999/xhtml" style="width:${i}px;height:${n}px;overflow:hidden;">`,a,"</div>","</foreignObject>","</svg>"].join(""),l=new Blob([c],{type:"image/svg+xml;charset=utf-8"}),u=URL.createObjectURL(l),d=await new Promise(e=>{const s=new Image;s.onload=()=>{const r=document.createElement("canvas");r.width=i,r.height=n;r.getContext("2d").drawImage(s,0,0),URL.revokeObjectURL(u),e(r.toDataURL("image/png",t))},s.onerror=()=>{URL.revokeObjectURL(u),e(null)},s.src=u});if(!d)return{error:"Canvas rendering failed"};const h=d.split(",")[1];return{width:i,height:n,format:"png",base64:h,sizeKB:Math.round(3*h.length/4/1024)}}function pe(e,t){let s=null;if(e&&(s=document.querySelector(e)),!s&&t){const e=document.querySelectorAll('button, a, [role="button"], input[type="submit"], input[type="button"], [data-click], label, [onclick]'),r=t.toLowerCase();for(const t of e)if(t.textContent?.trim().toLowerCase().includes(r)){s=t;break}}if(!s)return{error:`Element not found: ${e||`text="${t}"`}`};s.scrollIntoView({behavior:"instant",block:"center"}),s.click();const r=s.tagName?.toLowerCase();return{clicked:`${r}${s.id?`#${s.id}`:""}`,text:s.textContent?.trim().slice(0,100)||"",rect:s.getBoundingClientRect().toJSON?.()||null}}function me(e,t,{clear:s=!1,submit:r=!1}={}){if(!e)return{error:"selector is required"};if(void 0===t)return{error:"text is required"};const i=document.querySelector(e);if(!i)return{error:`Element not found: ${e}`};i.focus(),s&&(i.value="",i.dispatchEvent(new Event("input",{bubbles:!0})));const n=Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype,"value")?.set||Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype,"value")?.set,o=s?t:(i.value||"")+t;if(n?n.call(i,o):i.value=o,i.dispatchEvent(new Event("input",{bubbles:!0})),i.dispatchEvent(new Event("change",{bubbles:!0})),r){const e=i.closest("form");e?e.dispatchEvent(new Event("submit",{bubbles:!0,cancelable:!0})):i.dispatchEvent(new KeyboardEvent("keydown",{key:"Enter",code:"Enter",bubbles:!0}))}return{selector:e,typed:t,currentValue:i.value?.slice(0,200),submitted:!!r}}function ge(e,t,s=30){let r=ne;return e&&(r=r.filter(t=>t.method===e.toUpperCase())),t&&(r="error"===t?r.filter(e=>0===e.status||e.status>=400):r.filter(e=>String(e.status).startsWith(String(t)))),{requests:r.slice(-s),total:ne.length,showing:Math.min(r.length,s)}}function fe(e,t=30){const s=e&&"all"!==e?ae.filter(t=>t.level===e):ae;return{messages:s.slice(-t),total:ae.length,showing:Math.min(s.length,t)}}function we(e,t,s){switch(e.action){case"click":{const t=pe(e.selector,e.text);return t.error?{success:!1,error:t.error}:{success:!0,detail:`Clicked: ${e.selector||e.text}`}}case"type":{const t=me(e.selector,e.value,{clear:e.clear??!0,submit:e.submit??!1});return t.error?{success:!1,error:t.error}:{success:!0,detail:`Typed "${e.value}" into ${e.selector}`}}case"navigate":if(t&&e.section)return t.emit("nav:section",{section:e.section},{appName:"wu-ai"}),{success:!0,detail:`Navigated to section: ${e.section}`};if(e.selector){const t=pe(e.selector,e.text);return t.error?{success:!1,error:t.error}:{success:!0,detail:`Navigated via click: ${e.selector}`}}return{success:!1,error:'navigate requires "section" or "selector"'};case"wait":return{success:!0,detail:`Wait: ${e.ms||0}ms`};case"emit":return t?(t.emit(e.event,e.data||{},{appName:"wu-ai"}),{success:!0,detail:`Emitted: ${e.event}`}):{success:!1,error:"eventBus not available"};case"setState":return s?(s.set(e.path,e.value),{success:!0,detail:`Set state: ${e.path}`}):{success:!1,error:"store not available"};default:return{success:!1,error:`Unknown action: ${e.action}`}}}function ye(e,t=5e3){return new Promise(s=>{if(document.querySelector(e))return void s(!0);let r=0;const i=setInterval(()=>{r+=100,document.querySelector(e)?(clearInterval(i),s(!0)):r>=t&&(clearInterval(i),s(!1))},100)})}function _e(e){return new Promise(t=>setTimeout(t,e))}class ve{constructor({actions:e,conversation:t,context:s,permissions:r,eventBus:i,agent:n,store:o}){this._actions=e,this._conversation=t,this._context=s,this._permissions=r,this._eventBus=i,this._agent=n,this._store=o,this._capabilities=new Map,this._workflows=new Map,this._config={defaultProvider:null,defaultTemperature:.3},this._stats={totalIntents:0,resolvedIntents:0,failedIntents:0,workflowsRegistered:0,workflowsExecuted:0}}configure(e){void 0!==e.defaultProvider&&(this._config.defaultProvider=e.defaultProvider),void 0!==e.defaultTemperature&&(this._config.defaultTemperature=e.defaultTemperature)}register(e,s,r){if(!e||!s)throw new Error("[wu-ai] capability() requires both appName and actionName");if(!r||"function"!=typeof r.handler)throw new Error(`[wu-ai] capability '${e}:${s}' must have a handler function`);const i=`${e}:${s}`;this._capabilities.has(e)||this._capabilities.set(e,new Map),this._capabilities.get(e).set(s,{description:r.description||s,qualifiedName:i}),this._actions.register(i,{...r,description:`[${e}] ${r.description||s}`}),t.wuDebug(`[wu-ai] Capability registered: ${i}`)}unregister(e,t){const s=this._capabilities.get(e);if(!s)return;const r=`${e}:${t}`;s.delete(t),this._actions.unregister(r),0===s.size&&this._capabilities.delete(e)}removeApp(e){const s=this._capabilities.get(e);if(!s)return 0;let r=0;for(const[t]of s){const s=`${e}:${t}`;this._actions.unregister(s),r++}return this._capabilities.delete(e),t.wuDebug(`[wu-ai] All capabilities removed for app '${e}' (${r})`),this._eventBus.emit("ai:app:removed",{appName:e,capabilitiesRemoved:r},{appName:"wu-ai"}),r}getCapabilityMap(){const e={};for(const[t,s]of this._capabilities){e[t]=[];for(const[,r]of s)e[t].push({action:r.qualifiedName,description:r.description})}return e}getRegisteredApps(){return[...this._capabilities.keys()]}hasApp(e){return this._capabilities.has(e)}getTotalCapabilities(){let e=0;for(const t of this._capabilities.values())e+=t.size;return e}async resolve(e,t={}){if(!e||"string"!=typeof e)throw new Error("[wu-ai] intent() requires a description string");this._stats.totalIntents++;const s=this._generateNamespace();if(this._context)try{await this._context.collect()}catch{}const r=this._buildOrchestratorPrompt(t);this._eventBus.emit("ai:intent:start",{description:e.slice(0,200),namespace:s,capabilities:this.getTotalCapabilities()},{appName:"wu-ai"});try{const i=await this._conversation.send(e,{namespace:s,systemPrompt:r,provider:t.provider||this._config.defaultProvider,temperature:t.temperature??this._config.defaultTemperature,maxTokens:t.maxTokens,signal:t.signal,responseFormat:t.responseFormat}),n=i.tool_results||[],o=this._extractInvolvedApps(n),a=!!i.content;a?this._stats.resolvedIntents++:this._stats.failedIntents++;const c={content:i.content||"",tool_results:n,usage:i.usage||null,resolved:a,appsInvolved:o};return this._eventBus.emit("ai:intent:resolved",{description:e.slice(0,200),resolved:a,appsInvolved:o},{appName:"wu-ai"}),c}catch(t){throw this._stats.failedIntents++,this._eventBus.emit("ai:intent:error",{description:e.slice(0,200),error:t.message},{appName:"wu-ai"}),t}finally{this._conversation.deleteNamespace(s)}}buildOrchestratorPrompt(e={}){return this._buildOrchestratorPrompt(e)}_buildOrchestratorPrompt(e={}){const t=[];t.push("You are an AI orchestrator for a microfrontend application.","Multiple independent apps are mounted, each with specific capabilities.","Resolve cross-app requests by calling the right capabilities in the right order.","","RULES:","- Call capabilities (tools) to gather data or trigger actions.","- You may call multiple capabilities from different apps if needed.","- Synthesize results into a clear, actionable response.","- If a required app is not available or lacks a capability, explain what is missing.","");const s=this.getCapabilityMap(),r=Object.keys(s);if(r.length>0){t.push("CAPABILITY MAP:");for(const e of r){t.push(` ${e}:`);for(const r of s[e])t.push(` - ${r.action}: ${r.description}`)}t.push("")}else t.push("NOTE: No app capabilities are registered. Answer based on available context only.","");if(e.plan&&e.plan.length>0){t.push("SUGGESTED PLAN (follow this unless a better approach is evident):");for(let s=0;s<e.plan.length;s++)t.push(` ${s+1}. ${e.plan[s]}`);t.push("")}const i=this._context?.getSnapshot();return i?._mountedApps?.length&&t.push(`MOUNTED APPS: ${i._mountedApps.join(", ")}`,""),i?._store&&Object.keys(i._store).length>0&&t.push("CURRENT STATE:",JSON.stringify(i._store,null,2),""),t.join("\n")}registerWorkflow(e,s){if(!e)throw new Error("[wu-ai] workflow() requires a name");if(!s||!s.steps||!Array.isArray(s.steps)||0===s.steps.length)throw new Error(`[wu-ai] workflow '${e}' must have a non-empty steps array`);const r=s.mode||(s.steps.length>0&&"object"==typeof s.steps[0]&&s.steps[0].action?"deterministic":"ai");this._workflows.set(e,{description:s.description||e,steps:s.steps,mode:r,parameters:s.parameters||{},maxSteps:s.maxSteps??15,provider:s.provider||null,temperature:s.temperature??.2}),this._stats.workflowsRegistered++,t.wuDebug(`[wu-ai] Workflow registered: '${e}' (${s.steps.length} steps)`)}async*executeWorkflow(e,t={},s={}){const r=this._workflows.get(e);if(!r)throw new Error(`[wu-ai] Workflow '${e}' is not registered`);for(const[s,i]of Object.entries(r.parameters))if(i.required&&(void 0===t[s]||null===t[s]))throw new Error(`[wu-ai] Workflow '${e}' requires parameter '${s}'`);this._stats.workflowsExecuted++,"deterministic"===r.mode?yield*this._executeDeterministic(e,r,t,s):yield*this._executeWithAgent(e,r,t,s)}async*_executeWithAgent(e,t,s,r){if(!this._agent)throw new Error("[wu-ai] Agent module not available for workflow execution");const i=t.steps.map(e=>{let t=e;for(const[e,r]of Object.entries(s))t=t.replace(new RegExp(`\\{\\{${e}\\}\\}`,"g"),String(r));return t}),n=this._buildWorkflowGoal(t,i,s);this._eventBus.emit("ai:workflow:start",{workflow:e,mode:"ai",params:s,steps:i.length},{appName:"wu-ai"});let o=null;try{yield*this._agent.run(n,{maxSteps:t.maxSteps,provider:r.provider||t.provider||this._config.defaultProvider,temperature:t.temperature??.2,onStep:e=>{o=e,r.onStep&&r.onStep(e)},shouldContinue:r.shouldContinue,signal:r.signal})}finally{this._eventBus.emit("ai:workflow:done",{workflow:e,params:s,totalSteps:o?.step||0,result:o?.type||"unknown"},{appName:"wu-ai"})}}async*_executeDeterministic(e,t,s,r){const i=t.steps.map(e=>{const t={...e};for(const[e,r]of Object.entries(s)){const s=new RegExp(`\\{\\{${e}\\}\\}`,"g");for(const e of["value","selector","text","section","event","path"])"string"==typeof t[e]&&(t[e]=t[e].replace(s,String(r)))}return t});this._eventBus?.emit("ai:workflow:start",{workflow:e,mode:"deterministic",params:s,steps:i.length},{appName:"wu-ai"});let n=null;try{for(let e=0;e<i.length;e++){const t=i[e],s=e+1,o=Date.now();if(r.signal?.aborted){const e={step:s,type:"aborted",content:"Workflow aborted",reason:"Aborted by caller",elapsed:0};return n=e,void(yield e)}if("wait"===t.action){if(t.selector){const e=await ye(t.selector,t.timeout||5e3),i=Date.now()-o,a={step:s,type:e?"action":"error",content:e?`Waited for "${t.selector}" โ€” found`:`Timeout waiting for "${t.selector}"`,elapsed:i};if(n=a,r.onStep&&r.onStep(a),yield a,!e)return}else if(t.ms){await _e(t.ms);const e={step:s,type:"action",content:`Waited ${t.ms}ms`,elapsed:t.ms};n=e,r.onStep&&r.onStep(e),yield e}continue}const a=we(t,this._eventBus,this._store),c=Date.now()-o,l={step:s,type:a.success?"action":"error",content:a.success?a.detail:a.error,elapsed:c};if(n=l,r.onStep&&r.onStep(l),yield l,r.shouldContinue){let e;try{e=await r.shouldContinue(l)}catch{e=!1}if(!e){const e={step:s,type:"interrupted",content:"Stopped by user",reason:"shouldContinue returned false",elapsed:0};return n=e,void(yield e)}}if(!a.success)return;e<i.length-1&&await _e(t.delay??200)}const t={step:i.length,type:"done",content:`Workflow "${e}" completed (${i.length} steps)`,reason:"All steps executed",elapsed:0};n=t,r.onStep&&r.onStep(t),yield t}finally{this._eventBus?.emit("ai:workflow:done",{workflow:e,mode:"deterministic",params:s,totalSteps:n?.step||0,result:n?.type||"unknown"},{appName:"wu-ai"})}}hasWorkflow(e){return this._workflows.has(e)}getWorkflow(e){const t=this._workflows.get(e);return t?{description:t.description,steps:[...t.steps],mode:t.mode,parameters:{...t.parameters},maxSteps:t.maxSteps}:null}removeWorkflow(e){this._workflows.delete(e)}getWorkflowNames(){return[...this._workflows.keys()]}_buildWorkflowGoal(e,t,s){const r=[];r.push(`WORKFLOW: ${e.description}`,"","You must follow these steps IN ORDER. Use browser tools (screenshot, click, type)","to interact with the application. After each step, take a screenshot to verify.","","STEPS:");for(let e=0;e<t.length;e++)r.push(` ${e+1}. ${t[e]}`);r.push("","After completing all steps successfully, respond with [DONE].","If a step fails, explain what went wrong.");const i=this.getCapabilityMap(),n=Object.keys(i);if(n.length>0){r.push("","AVAILABLE APP CAPABILITIES:");for(const e of n)for(const t of i[e])r.push(` - ${t.action}: ${t.description}`)}return r.join("\n")}getStats(){return{...this._stats,registeredApps:this.getRegisteredApps(),totalCapabilities:this.getTotalCapabilities(),capabilityMap:this.getCapabilityMap(),workflows:this.getWorkflowNames(),config:{...this._config}}}destroy(){for(const[e,t]of this._capabilities)for(const[s]of t)this._actions.unregister(`${e}:${s}`);this._capabilities.clear(),this._workflows.clear(),this._stats={totalIntents:0,resolvedIntents:0,failedIntents:0,workflowsRegistered:0,workflowsExecuted:0}}_extractInvolvedApps(e){if(!e||!Array.isArray(e))return[];const t=new Set;for(const s of e){const e=s.name||s.tool||"",r=e.indexOf(":");r>0&&t.add(e.slice(0,r))}return[...t]}_generateNamespace(){return"intent:"+Date.now().toString(36)+"_"+Math.random().toString(36).slice(2,6)}}function be(e,t){le(),e.action("browser_screenshot",{description:"Take a screenshot of the current page or a specific element. Returns a base64 PNG image. Use this to SEE what the user sees.",parameters:{selector:{type:"string",description:"CSS selector of the element to capture. Empty = full visible page.",required:!1}},handler:async e=>he(e.selector),permissions:[]}),e.action("browser_click",{description:"Click an element on the page. Find by CSS selector or by visible text content. Use this to interact with buttons, links, tabs, etc.",parameters:{selector:{type:"string",description:'CSS selector (e.g. "#submit-btn", ".nav-link", "button[type=submit]")',required:!1},text:{type:"string",description:'Visible text to find and click (e.g. "Submit", "Next", "Guardar"). Searches buttons, links, and clickable elements.',required:!1}},handler:async(e,t)=>{const s=pe(e.selector,e.text);return s.error||t.emit?.("browser:clicked",{selector:e.selector,text:e.text}),s},permissions:["emitEvents"]}),e.action("browser_type",{description:"Type text into an input, textarea, or contenteditable element. Works with React, Vue, Angular, and other frameworks. Can optionally clear existing text first and submit the form.",parameters:{selector:{type:"string",description:'CSS selector of the input (e.g. "#email", "input[name=search]", "textarea.comment")',required:!0},text:{type:"string",description:"Text to type into the element",required:!0},clear:{type:"boolean",description:"Clear existing value before typing (default: false)",required:!1},submit:{type:"boolean",description:"Submit the form or press Enter after typing (default: false)",required:!1}},handler:async(e,t)=>{const s=me(e.selector,e.text,{clear:e.clear,submit:e.submit});return s.error||t.emit?.("browser:typed",{selector:e.selector,length:e.text.length}),s},permissions:["emitEvents"]}),e.action("browser_select",{description:"Select an option in a <select> dropdown or a custom dropdown component.",parameters:{selector:{type:"string",description:"CSS selector of the <select> element",required:!0},value:{type:"string",description:'The value attribute of the option to select. Use "text:" prefix to match by visible text (e.g. "text:Mexico")',required:!0}},handler:async(e,t)=>{const s=document.querySelector(e.selector);if(!s)return{error:`Element not found: ${e.selector}`};if("select"===s.tagName?.toLowerCase()){const r=Array.from(s.options);let i;if(e.value.startsWith("text:")){const t=e.value.slice(5).toLowerCase();i=r.find(e=>e.textContent.trim().toLowerCase().includes(t))}else i=r.find(t=>t.value===e.value);return i?(s.value=i.value,s.dispatchEvent(new Event("change",{bubbles:!0})),s.dispatchEvent(new Event("input",{bubbles:!0})),t.emit?.("browser:selected",{selector:e.selector,value:i.value}),{selected:i.value,text:i.textContent.trim()}):{error:`Option not found: ${e.value}`}}return s.click(),{clicked:e.selector,note:"Custom dropdown โ€” clicked trigger. Use browser_click to select an option from the opened menu."}},permissions:["emitEvents"]}),e.action("browser_scroll",{description:"Scroll the page or a specific element. Use to reveal content that is not visible.",parameters:{direction:{type:"string",description:'Direction: "up", "down", "top", "bottom"',required:!0},selector:{type:"string",description:"CSS selector of scrollable container (empty = page)",required:!1},amount:{type:"number",description:'Pixels to scroll (default: 500). Ignored for "top"/"bottom".',required:!1}},handler:async e=>{const t=e.selector?document.querySelector(e.selector):window,s=e.amount||500;if(e.selector&&!t)return{error:`Element not found: ${e.selector}`};const r=t===window?document.documentElement:t;switch(e.direction){case"up":r.scrollBy({top:-s,behavior:"smooth"});break;case"down":r.scrollBy({top:s,behavior:"smooth"});break;case"top":r.scrollTo({top:0,behavior:"smooth"});break;case"bottom":r.scrollTo({top:r.scrollHeight,behavior:"smooth"});break;default:return{error:`Invalid direction: ${e.direction}`}}return{scrolled:e.direction,amount:"top"===e.direction||"bottom"===e.direction?"max":s,currentScroll:r.scrollTop}},permissions:[]}),e.action("browser_snapshot",{description:"Get a text representation of the visible DOM structure (accessibility tree). Use this to understand what elements are on the page, their roles, IDs, and text content. Cheaper and faster than a screenshot.",parameters:{selector:{type:"string",description:'CSS selector to snapshot (empty = full page). Use "[data-wu-app=appName]" for a specific micro-app.',required:!1},depth:{type:"number",description:"Max depth to traverse (default: 5)",required:!1}},handler:async e=>{const t=e.selector?document.querySelector(e.selector):document.body;if(!t)return{error:`Element not found: ${e.selector}`};return{snapshot:ue(t,0,e.depth||5)}},permissions:[]}),e.action("browser_navigate",{description:"Navigate to a route within the SPA application. Emits a shell:navigate event and updates the store.",parameters:{route:{type:"string",description:'Route path (e.g. "/dashboard", "/users", "/pos/cotizador")',required:!0}},handler:async(e,t)=>(t.emit?.("shell:navigate",{route:e.route}),t.setState?.("currentPath",e.route),{navigated:e.route}),permissions:["emitEvents","writeStore"]}),e.action("browser_network",{description:"View captured HTTP network requests (fetch and XHR). Shows URL, method, status code, duration, and size. Use to debug API calls, check for errors, or monitor performance.",parameters:{method:{type:"string",description:"Filter by HTTP method: GET, POST, PUT, DELETE (empty = all)",required:!1},status:{type:"string",description:'Filter: "2" (2xx success), "4" (4xx errors), "5" (5xx errors), "error" (all failures)',required:!1},limit:{type:"number",description:"Max requests to return (default: 30)",required:!1}},handler:async e=>ge(e.method,e.status,e.limit),permissions:[]}),e.action("browser_console",{description:"View captured browser console messages (log, warn, error). Use to check for errors, warnings, or debug output.",parameters:{level:{type:"string",description:'Filter by level: "log", "warn", "error" (empty = all)',required:!1},limit:{type:"number",description:"Max messages to return (default: 30)",required:!1}},handler:async e=>fe(e.level,e.limit),permissions:[]}),e.action("browser_info",{description:"Get an overview of the current page state: URL, viewport size, mounted micro-apps, store keys, visible elements summary. Use this FIRST to understand the page before taking actions.",parameters:{},handler:async(e,s)=>{const r=[];if(t._apps)for(const[e,s]of Object.entries(t._apps))r.push({name:e,mounted:s.mounted||s.isMounted||!1,status:s.status||"unknown"});0===r.length&&document.querySelectorAll("[data-wu-app]").forEach(e=>{r.push({name:e.getAttribute("data-wu-app"),mounted:!0})});const i=s.getState?.("")||{},n="object"==typeof i?Object.keys(i):[];return{url:window.location.href,title:document.title,viewport:{width:window.innerWidth,height:window.innerHeight},apps:r,storeKeys:n,networkRequests:ne.length,consoleMessages:ae.length,consoleErrors:ae.filter(e=>"error"===e.level).length}},permissions:["readStore"]})}class xe{constructor({eventBus:e,store:t,core:s}){this._eventBus=e,this._store=t,this._core=s,this._initialized=!1,this._modules={}}init(e={}){return this._initialized?(this._reconfigure(e),this):(this._modules.permissions=new F({permissions:e.permissions,rateLimit:e.rateLimit,circuitBreaker:e.circuitBreaker,loopProtection:e.loopProtection,allowedDomains:e.allowedDomains}),this._modules.provider=new W,this._modules.context=new G({store:this._store,eventBus:this._eventBus,core:this._core}),e.context&&this._modules.context.configure(e.context),this._modules.actions=new V({eventBus:this._eventBus,store:this._store,permissions:this._modules.permissions}),this._modules.conversation=new X({provider:this._modules.provider,actions:this._modules.actions,context:this._modules.context,permissions:this._modules.permissions,eventBus:this._eventBus}),e.conversation&&this._modules.conversation.configure(e.conversation),this._modules.triggers=new te({eventBus:this._eventBus,conversation:this._modules.conversation,permissions:this._modules.permissions}),e.triggers&&this._modules.triggers.configure(e.triggers),this._modules.agent=new ie({conversation:this._modules.conversation,actions:this._modules.actions,context:this._modules.context,permissions:this._modules.permissions,eventBus:this._eventBus}),e.agent&&this._modules.agent.configure(e.agent),this._modules.orchestrate=new ve({actions:this._modules.actions,conversation:this._modules.conversation,context:this._modules.context,permissions:this._modules.permissions,eventBus:this._eventBus,agent:this._modules.agent,store:this._store}),e.orchestrate&&this._modules.orchestrate.configure(e.orchestrate),this._initialized=!0,t.wuInfo("[wu-ai] Initialized"),"undefined"!=typeof window&&(be(this,this._core),t.wuInfo("[wu-ai] Browser actions registered (10 tools)")),this._eventBus.emit("ai:initialized",{},{appName:"wu-ai"}),this)}provider(e,t){return this._ensureInit(),this._modules.provider.register(e,t),this}async send(e,t={}){return this._ensureInit(),this._modules.conversation.send(e,t)}async*stream(e,t={}){this._ensureInit(),yield*this._modules.conversation.stream(e,t)}async json(e,t={}){this._ensureInit();const{schema:s,schemaName:r,...i}=t;let n;n=s?{type:"json_schema",schema:s,name:r||"response"}:t.responseFormat||"json";const o=await this._modules.conversation.send(e,{...i,responseFormat:n});let a,c=null;if(void 0!==o.parsed)c=o.parsed;else if(o.content)try{c=JSON.parse(o.content)}catch{a="LLM response is not valid JSON"}return{data:c,raw:o.content||"",error:a||o.parseError,usage:o.usage,namespace:o.namespace}}abort(e){this._initialized&&(e?this._modules.conversation.abort(e):this._modules.conversation.abortAll())}action(e,t){return this._ensureInit(),this._modules.actions.register(e,t),this}async execute(e,t){this._ensureInit();const s=this._modules.permissions.loopProtection.createTraceId();return this._modules.actions.execute(e,t,{traceId:s,depth:0})}trigger(e,t){return this._ensureInit(),this._modules.triggers.register(e,t),this}async fireTrigger(e,t){return this._ensureInit(),this._modules.triggers.fire(e,t)}async*agent(e,t={}){this._ensureInit(),yield*this._modules.agent.run(e,t)}capability(e,t,s){return this._ensureInit(),this._modules.orchestrate.register(e,t,s),this}async intent(e,t={}){return this._ensureInit(),this._modules.orchestrate.resolve(e,t)}removeApp(e){return this._ensureInit(),this._modules.orchestrate.removeApp(e),this}workflow(e,t){return this._ensureInit(),this._modules.orchestrate.registerWorkflow(e,t),this}async*runWorkflow(e,t={},s={}){this._ensureInit(),yield*this._modules.orchestrate.executeWorkflow(e,t,s)}get context(){return this._ensureInit(),{configure:e=>this._modules.context.configure(e),register:(e,t)=>this._modules.context.register(e,t),collect:()=>this._modules.context.collect(),getSnapshot:()=>this._modules.context.getSnapshot()}}get conversation(){return this._ensureInit(),{getHistory:e=>this._modules.conversation.getHistory(e),clear:e=>this._modules.conversation.clear(e),clearAll:()=>this._modules.conversation.clearAll(),inject:(e,t,s)=>this._modules.conversation.inject(e,t,s),getNamespaces:()=>this._modules.conversation.getNamespaces(),deleteNamespace:e=>this._modules.conversation.deleteNamespace(e)}}get permissions(){return this._ensureInit(),{configure:e=>this._modules.permissions.configure(e),check:e=>this._modules.permissions.check(e),getPermissions:()=>this._modules.permissions.getPermissions(),setAllowedDomains:e=>this._modules.permissions.setAllowedDomains(e)}}tools(){return this._ensureInit(),this._modules.actions.getToolSchemas()}expose(){if(this._ensureInit(),"undefined"==typeof navigator||!navigator.modelContext)return t.wuDebug("[wu-ai] WebMCP not available (navigator.modelContext missing)"),!1;const e=this._modules.actions.getToolSchemas(),s=this._modules.actions.getNames();for(let r=0;r<e.length;r++){const i=e[r],n=s[r];try{navigator.modelContext.registerTool({name:i.name,description:i.description,inputSchema:i.parameters,handler:async e=>{const t=await this.execute(n,e);return t.success?t.result:{error:t.reason}}})}catch(e){t.wuDebug(`[wu-ai] WebMCP register failed for '${i.name}': ${e.message}`)}}return t.wuInfo(`[wu-ai] Exposed ${e.length} tools via WebMCP`),this._eventBus.emit("ai:webmcp:exposed",{toolCount:e.length,tools:e.map(e=>e.name)},{appName:"wu-ai"}),!0}confirmTool(e){this._initialized&&this._modules.actions.confirmTool(e)}rejectTool(e){this._initialized&&this._modules.actions.rejectTool(e)}getStats(){return this._initialized?{initialized:!0,provider:this._modules.provider.getStats(),permissions:this._modules.permissions.getStats(),context:this._modules.context.getStats(),actions:this._modules.actions.getStats(),conversation:this._modules.conversation.getStats(),triggers:this._modules.triggers.getStats(),agent:this._modules.agent.getStats(),orchestrate:this._modules.orchestrate.getStats()}:{initialized:!1}}destroy(){this._initialized&&(this._modules.orchestrate.destroy(),this._modules.agent.destroy(),this._modules.conversation.abortAll(),this._modules.triggers.destroy(),this._modules={},this._initialized=!1,t.wuInfo("[wu-ai] Destroyed"),this._eventBus.emit("ai:destroyed",{},{appName:"wu-ai"}))}_ensureInit(){this._initialized||this.init()}_reconfigure(e){e.permissions&&this._modules.permissions.configure(e.permissions),e.rateLimit&&this._modules.permissions.rateLimiter.configure(e.rateLimit),e.circuitBreaker&&this._modules.permissions.circuitBreaker.configure(e.circuitBreaker),e.loopProtection&&this._modules.permissions.loopProtection.configure(e.loopProtection),e.context&&this._modules.context.configure(e.context),e.conversation&&this._modules.conversation.configure(e.conversation),e.triggers&&this._modules.triggers.configure(e.triggers),e.agent&&this._modules.agent.configure(e.agent),e.orchestrate&&this._modules.orchestrate.configure(e.orchestrate)}}function Se(e){let s=null,r=null,i=0,n=!1,o=null;const a=[];function c(t){if(e.ai&&e.ai.permissions)return e.ai.permissions.check(t);return["readStore","executeActions"].includes(t)}function l(t,s,r){e.eventBus&&e.eventBus.emit("mcp:bridge:operation",{operation:t,params:s,result:r?.error?{error:r.error}:{success:!0},timestamp:Date.now()},{appName:"wu-mcp-bridge"})}e.eventBus&&e.eventBus.on("*",e=>{a.push({name:e.name,data:e.data,timestamp:e.timestamp||Date.now(),source:e.source||"unknown"}),a.length>200&&a.shift()}),le();const u={status:()=>({connected:!0,framework:"wu-framework",apps:g(),storeKeys:e.store?Object.keys(e.store.get("")||{}):[],actionsCount:e.ai?e.ai.tools().length:0,eventLogSize:a.length}),list_apps:()=>g(),list_events:({limit:e=20})=>a.slice(-e),list_actions(){if(!e.ai)return{actions:[],note:"wu.ai not initialized"};const t=e.ai.tools();return{actions:t,count:t.length}},snapshot({appName:e}){try{const t=e?document.querySelector(`[data-wu-app="${e}"]`)||document.querySelector(`#wu-app-${e}`):document.body;return t?{app:e||"(page)",snapshot:ue(t,0,5),timestamp:Date.now()}:{error:`App "${e}" not found in DOM`}}catch(e){return{error:e.message}}},console:({level:e="all",limit:t=50})=>fe(e,t),async screenshot({selector:e,quality:t=.8}){const s=await he(e,t);return s.error||(s.timestamp=Date.now()),s},network:({method:e,status:t,limit:s=50})=>ge(e,t,s),get_state({path:t}){if(!e.store)return{error:"wu.store not available"};if(!c("readStore"))return{error:"Permission denied: readStore is disabled"};return{path:t||"(root)",value:e.store.get(t||"")}},set_state:({path:t,value:s})=>e.store?t?c("writeStore")?(e.store.set(t,s),l("set_state",{path:t,value:s},{}),{path:t,value:s,updated:!0}):(l("set_state",{path:t},{error:"Permission denied"}),{error:"Permission denied: writeStore is disabled"}):{error:"path is required"}:{error:"wu.store not available"},emit_event:({event:t,data:s})=>e.eventBus?t?c("emitEvents")?(e.eventBus.emit(t,s,{appName:"wu-mcp-bridge"}),l("emit_event",{event:t,data:s},{}),{emitted:t,data:s}):(l("emit_event",{event:t},{error:"Permission denied"}),{error:"Permission denied: emitEvents is disabled"}):{error:"event name is required"}:{error:"wu.eventBus not available"},navigate:({route:t})=>t?c("emitEvents")?(e.eventBus&&e.eventBus.emit("shell:navigate",{route:t},{appName:"wu-mcp-bridge"}),e.store&&c("writeStore")&&e.store.set("currentPath",t),l("navigate",{route:t},{}),{navigated:t}):(l("navigate",{route:t},{error:"Permission denied: emitEvents"}),{error:"Permission denied: emitEvents is disabled"}):{error:"Route is required"},mount_app({appName:t,container:s}){if(!t)return{error:"appName is required"};if(!c("modifyDOM"))return l("mount_app",{appName:t},{error:"Permission denied"}),{error:"Permission denied: modifyDOM is disabled"};try{return e.mount?(e.mount(t,s),l("mount_app",{appName:t,container:s},{success:!0}),{mounted:t,container:s}):{error:"wu.mount not available"}}catch(e){return{error:e.message}}},unmount_app({appName:t}){if(!t)return{error:"appName is required"};if(!c("modifyDOM"))return l("unmount_app",{appName:t},{error:"Permission denied"}),{error:"Permission denied: modifyDOM is disabled"};try{return e.unmount?(e.unmount(t),l("unmount_app",{appName:t},{success:!0}),{unmounted:t}):{error:"wu.unmount not available"}}catch(e){return{error:e.message}}},click({selector:e,text:t}){if(!c("modifyDOM"))return{error:"Permission denied: modifyDOM is disabled"};const s=pe(e,t);return l("click",{selector:e,text:t},s),s},type({selector:e,text:t,clear:s=!1,submit:r=!1}){if(!c("modifyDOM"))return{error:"Permission denied: modifyDOM is disabled"};const i=me(e,t,{clear:s,submit:r});return l("type",{selector:e,textLength:t?.length},i),i},async execute_action({action:t,params:s}){if(!e.ai)return{error:"wu.ai not available"};if(!t)return{error:"action name is required"};try{return{action:t,...await e.ai.execute(t,s||{})}}catch(e){return{error:e.message}}}};function d(e="ws://localhost:19100",r={}){if(s&&s.readyState<=1)t.warn("[wu-mcp-bridge] Already connected or connecting");else{o=r.token||null,n=!o;try{s=new WebSocket(e),s.onopen=()=>{t.debug("[wu-mcp-bridge] Connected to wu-mcp-server"),i=0,o&&s.send(JSON.stringify({type:"auth",token:o}))},s.onmessage=async e=>{try{const s=JSON.parse(e.data);if("auth_result"===s.type)return n=!0===s.success,void(n?t.debug("[wu-mcp-bridge] Authenticated successfully"):(console.error("[wu-mcp-bridge] Authentication failed:",s.reason||"Invalid token"),h()));if(!n)return void(s.id&&p(s.id,null,"Not authenticated. Send auth token first."));const{id:r,command:i,params:o}=s;if(!r||!i)return void t.warn("[wu-mcp-bridge] Invalid message:",s);const a=u[i];if(!a)return void p(r,null,`Unknown command: ${i}`);try{p(r,await a(o||{}))}catch(e){p(r,null,e.message)}}catch(e){console.error("[wu-mcp-bridge] Failed to handle message:",e)}},s.onclose=()=>{t.debug("[wu-mcp-bridge] Disconnected"),s=null,n=!1,m(e,r)},s.onerror=()=>{}}catch(t){console.error("[wu-mcp-bridge] Connection failed:",t.message),m(e,r)}}}function h(){r&&(clearTimeout(r),r=null),i=10,s&&(s.close(),s=null),n=!1}function p(e,t,r){if(!s||1!==s.readyState)return;const i=r?{id:e,error:r}:{id:e,result:t};s.send(JSON.stringify(i))}function m(e,t){if(i>=10)return;i++;const s=2e3*Math.min(i,5);r=setTimeout(()=>d(e,t),s)}function g(){const t=[];if(e._apps)for(const[s,r]of Object.entries(e._apps))t.push({name:s,mounted:r.mounted||r.isMounted||!1,url:r.url||r.info?.url||"",status:r.status||r.info?.status||"unknown"});return 0===t.length&&document.querySelectorAll("[data-wu-app]").forEach(e=>{t.push({name:e.getAttribute("data-wu-app"),mounted:!0,container:`#${e.id||"(no-id)"}`})}),t}return{connect:d,disconnect:h,isConnected:function(){return null!==s&&1===s.readyState&&n}}}var $e=Object.freeze({__proto__:null,createMcpBridge:Se});if(exports.wu=void 0,"undefined"!=typeof window&&window.wu&&window.wu._isWuFramework?exports.wu=window.wu:(exports.wu=new A,exports.wu._isWuFramework=!0),"undefined"!=typeof window){if(window.wu=exports.wu,exports.wu.version||(exports.wu.version="1.1.8",exports.wu.info={name:"Wu Framework",description:"Universal Microfrontends",features:["Framework Agnostic","Zero Config","Shadow DOM Isolation","Runtime Loading"]}),exports.wu.emit||(exports.wu.emit=(e,t,s)=>exports.wu.eventBus.emit(e,t,s),exports.wu.on=(e,t)=>exports.wu.eventBus.on(e,t),exports.wu.once=(e,t)=>exports.wu.eventBus.once(e,t),exports.wu.off=(e,t)=>exports.wu.eventBus.off(e,t)),exports.wu.prefetch||(exports.wu.prefetch=(e,t)=>exports.wu.prefetcher.prefetch(e,t),exports.wu.prefetchAll=e=>exports.wu.prefetcher.prefetchAll(e)),exports.wu.override||(exports.wu.override=(e,t,s)=>exports.wu.overrides.set(e,t,s),exports.wu.removeOverride=e=>exports.wu.overrides.remove(e),exports.wu.getOverrides=()=>exports.wu.overrides.getAll(),exports.wu.clearOverrides=()=>exports.wu.overrides.clearAll()),exports.wu.silence||(exports.wu.silence=async()=>{const{silenceAllLogs:e}=await Promise.resolve().then(function(){return i});e()},exports.wu.verbose=async()=>{const{enableAllLogs:e}=await Promise.resolve().then(function(){return i});e()}),!exports.wu.ai){let e=null;Object.defineProperty(exports.wu,"ai",{get:()=>(e||(e=new xe({eventBus:exports.wu.eventBus,store:exports.wu.store,core:exports.wu})),e),configurable:!0})}if(!exports.wu.mcp){let e=null;exports.wu.mcp={async connect(t="ws://localhost:19100",s={}){if(!e){const{createMcpBridge:t}=await Promise.resolve().then(function(){return $e});e=t(exports.wu)}e.connect(t,s)},disconnect(){e?.disconnect()},isConnected:()=>e?.isConnected()||!1}}}var ke=exports.wu;exports.WuAI=xe,exports.WuAIActions=V,exports.WuAIAgent=ie,exports.WuAIContext=G,exports.WuAIConversation=X,exports.WuAIOrchestrate=ve,exports.WuAIPermissions=F,exports.WuAIProvider=W,exports.WuAITriggers=te,exports.WuApp=p,exports.WuCache=m,exports.WuCore=A,exports.WuErrorBoundary=_,exports.WuEventBus=g,exports.WuHtmlParser=b,exports.WuIframeSandbox=S,exports.WuLifecycleHooks=v,exports.WuLoader=n,exports.WuLoadingStrategy=y,exports.WuManifest=u,exports.WuOverrides=E,exports.WuPerformance=f,exports.WuPluginSystem=w,exports.WuPrefetch=$,exports.WuProxySandbox=a,exports.WuSandbox=l,exports.WuScriptExecutor=x,exports.WuSnapshotSandbox=c,exports.WuStore=d,exports.WuStyleBridge=o,exports.app=(e,t)=>exports.wu.app(e,t),exports.buildA11yTree=ue,exports.buildToolSchemas=U,exports.captureScreenshot=he,exports.clearOverrides=()=>exports.wu.clearOverrides(),exports.clickElement=pe,exports.createConditionalHook=(e,t)=>async(s,r)=>{await e(s)&&await t(s),await r()},exports.createGuardHook=e=>async(t,s)=>{await e(t)&&await s()},exports.createMcpBridge=Se,exports.createPlugin=e=>({name:e.name,permissions:e.permissions||["events"],install:e.install,uninstall:e.uninstall,beforeInit:e.beforeInit,afterInit:e.afterInit,beforeMount:e.beforeMount,afterMount:e.afterMount,beforeUnmount:e.beforeUnmount,afterUnmount:e.afterUnmount,onError:e.onError,onDestroy:e.onDestroy}),exports.createSimpleHook=e=>async(t,s)=>{await e(t),await s()},exports.createTimedHook=(e,t=5e3)=>async(s,r)=>{const i=new Promise((e,s)=>setTimeout(()=>s(new Error("Hook timeout")),t));try{await Promise.race([e(s),i]),await r()}catch(e){console.error("[WuHooks] Timed hook failed:",e),await r()}},exports.createTransformHook=e=>async(t,s)=>{const r=await e(t);await s(r)},exports.default=ke,exports.define=(e,t)=>exports.wu.define(e,t),exports.destroy=()=>exports.wu.destroy(),exports.emit=(e,t,s)=>exports.wu.eventBus.emit(e,t,s),exports.enableAllLogs=r,exports.endMeasure=(e,t)=>exports.wu.performance.endMeasure(e,t),exports.ensureInterceptors=le,exports.estimateTokens=function(e,t=4){return Math.ceil(e.length/t)},exports.generatePerformanceReport=()=>exports.wu.performance.generateReport(),exports.getFilteredConsole=fe,exports.getFilteredNetwork=ge,exports.getOverrides=()=>exports.wu.getOverrides(),exports.getState=e=>exports.wu.store.get(e),exports.hide=e=>exports.wu.hide(e),exports.init=e=>exports.wu.init({apps:e}),exports.interpolate=q,exports.isHidden=e=>exports.wu.isHidden(e),exports.mount=(e,t)=>exports.wu.mount(e,t),exports.normalizeParameters=J,exports.off=(e,t)=>exports.wu.eventBus.off(e,t),exports.on=(e,t)=>exports.wu.eventBus.on(e,t),exports.onStateChange=(e,t)=>exports.wu.store.on(e,t),exports.once=(e,t)=>exports.wu.eventBus.once(e,t),exports.override=(e,t,s)=>exports.wu.override(e,t,s),exports.prefetch=(e,t)=>exports.wu.prefetch(e,t),exports.prefetchAll=e=>exports.wu.prefetchAll(e),exports.redactSensitive=H,exports.registerBrowserActions=be,exports.removeOverride=e=>exports.wu.removeOverride(e),exports.sanitizeForPrompt=z,exports.setState=(e,t)=>exports.wu.store.set(e,t),exports.show=e=>exports.wu.show(e),exports.silenceAllLogs=s,exports.startMeasure=(e,t)=>exports.wu.performance.startMeasure(e,t),exports.store=h,exports.truncateToTokenBudget=function(e,t,s=4){const r=t*s;return e.length<=r?e:e.slice(0,r)+"\n...[truncated to fit token budget]"},exports.typeIntoElement=me,exports.unmount=(e,t)=>exports.wu.unmount(e,t),exports.useHook=(e,t,s)=>exports.wu.hooks.use(e,t,s),exports.usePlugin=(e,t)=>exports.wu.pluginSystem.use(e,t),exports.validateParams=K;
3
3
  //# sourceMappingURL=wu-framework.cjs.js.map