wu-framework 2.1.0 โ†’ 2.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/LICENSE +39 -39
  2. package/README.md +570 -570
  3. package/dist/adapters/angular/index.d.ts +154 -154
  4. package/dist/adapters/angular/index.js.map +1 -1
  5. package/dist/adapters/angular.d.ts +3 -3
  6. package/dist/adapters/index.js.map +1 -1
  7. package/dist/adapters/lit/index.d.ts +120 -120
  8. package/dist/adapters/lit/index.js.map +1 -1
  9. package/dist/adapters/lit.d.ts +3 -3
  10. package/dist/adapters/preact/index.d.ts +108 -108
  11. package/dist/adapters/preact/index.js.map +1 -1
  12. package/dist/adapters/preact.d.ts +3 -3
  13. package/dist/adapters/qwik/index.js +1 -1
  14. package/dist/adapters/qwik/index.js.map +1 -1
  15. package/dist/adapters/react/index.d.ts +246 -246
  16. package/dist/adapters/react/index.js.map +1 -1
  17. package/dist/adapters/react.d.ts +3 -3
  18. package/dist/adapters/shared.js.map +1 -1
  19. package/dist/adapters/solid/index.d.ts +101 -101
  20. package/dist/adapters/solid/index.js.map +1 -1
  21. package/dist/adapters/solid.d.ts +3 -3
  22. package/dist/adapters/svelte/index.d.ts +166 -166
  23. package/dist/adapters/svelte/index.js.map +1 -1
  24. package/dist/adapters/svelte.d.ts +3 -3
  25. package/dist/adapters/vanilla/index.d.ts +179 -179
  26. package/dist/adapters/vanilla/index.js.map +1 -1
  27. package/dist/adapters/vanilla.d.ts +3 -3
  28. package/dist/adapters/vue/index.d.ts +299 -299
  29. package/dist/adapters/vue/index.js.map +1 -1
  30. package/dist/adapters/vue.d.ts +3 -3
  31. package/dist/ai/wu-ai.js.map +1 -1
  32. package/dist/core/wu-html-parser.js +2 -0
  33. package/dist/core/wu-html-parser.js.map +1 -0
  34. package/dist/core/wu-iframe-sandbox.js +2 -0
  35. package/dist/core/wu-iframe-sandbox.js.map +1 -0
  36. package/dist/core/wu-loader.js +2 -0
  37. package/dist/core/wu-loader.js.map +1 -0
  38. package/dist/core/wu-mcp-bridge.js.map +1 -1
  39. package/dist/core/wu-script-executor.js +2 -0
  40. package/dist/core/wu-script-executor.js.map +1 -0
  41. package/dist/wu-ai-browser-primitives-BDKXJlwc.js.map +1 -1
  42. package/dist/wu-framework.cjs.js +2 -2
  43. package/dist/wu-framework.cjs.js.map +1 -1
  44. package/dist/wu-framework.dev.js +8697 -9142
  45. package/dist/wu-framework.dev.js.map +1 -1
  46. package/dist/wu-framework.esm.js +2 -2
  47. package/dist/wu-framework.esm.js.map +1 -1
  48. package/dist/wu-framework.umd.js +2 -2
  49. package/dist/wu-framework.umd.js.map +1 -1
  50. package/dist/wu-logger-fJfUHBGA.js.map +1 -1
  51. package/integrations/astro/README.md +127 -127
  52. package/integrations/astro/WuApp.astro +63 -63
  53. package/integrations/astro/WuShell.astro +39 -39
  54. package/integrations/astro/index.js +68 -68
  55. package/integrations/astro/package.json +38 -38
  56. package/integrations/astro/types.d.ts +53 -53
  57. package/package.json +218 -218
  58. package/dist/wu-html-parser.js +0 -2
  59. package/dist/wu-html-parser.js.map +0 -1
  60. package/dist/wu-iframe-sandbox.js +0 -2
  61. package/dist/wu-iframe-sandbox.js.map +0 -1
  62. package/dist/wu-script-executor.js +0 -2
  63. package/dist/wu-script-executor.js.map +0 -1
@@ -1,3 +1,3 @@
1
- /*! wu-framework v2.1.0 | MIT License */
2
- 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(){if("undefined"!=typeof window&&!0===window.WU_DEBUG)return!0;if("undefined"!=typeof window&&!1===window.WU_DEBUG)return!1;if("undefined"!=typeof process&&"production"===process.env?.NODE_ENV)return!1;if("undefined"!=typeof process&&"development"===process.env?.NODE_ENV)return!0;if("undefined"!=typeof window&&window.location){const e=window.location.hostname;if("localhost"===e||"127.0.0.1"===e||"[::1]"===e)return!0;try{if(new URLSearchParams(window.location.search).has("wu-debug"))return!0}catch{}}return!1}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(e={}){this.maxCacheSize=e.maxCacheSize??50,this.cacheTTL=e.cacheTTL??18e5,this.cache=new Map,this.loadingPromises=new Map,t.debug("[WuLoader] Dynamic loader initialized")}_cacheGet(e){if(!this.cache.has(e))return;const s=this.cache.get(e),r=Date.now();return r-s.timestamp>this.cacheTTL?(this.cache.delete(e),void t.debug(`[WuLoader] Cache expired for: ${e}`)):(this.cache.delete(e),s.lastAccess=r,this.cache.set(e,s),s.code)}_cacheSet(e,t){this.cache.has(e)&&this.cache.delete(e),this._evictIfNeeded();const s=Date.now();this.cache.set(e,{code:t,timestamp:s,lastAccess:s})}_evictIfNeeded(){const e=Date.now();for(const[s,r]of this.cache)e-r.timestamp>this.cacheTTL&&(this.cache.delete(s),t.debug(`[WuLoader] Evicted expired entry: ${s}`));for(;this.cache.size>=this.maxCacheSize;){const e=this.cache.keys().next().value;this.cache.delete(e),t.debug(`[WuLoader] Evicted LRU entry: ${e}`)}}async loadApp(e,s){await this._ensureSentinelVerified();const r=`${e}/${s?.entry||"index.js"}`;t.debug(`[WuLoader] Loading app from: ${r}`);try{const e=this._cacheGet(r);if(void 0!==e)return t.debug(`[WuLoader] Cache hit for: ${r}`),e;if(this.loadingPromises.has(r))return t.debug(`[WuLoader] Loading in progress for: ${r}`),await this.loadingPromises.get(r);const s=this.fetchCode(r);this.loadingPromises.set(r,s);const i=await s;return this.loadingPromises.delete(r),this._cacheSet(r,i),t.debug(`[WuLoader] App loaded successfully: ${r}`),i}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){await this._ensureSentinelVerified();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){const t=this._cacheGet(e);if(void 0!==t)return t;if(this.loadingPromises.has(e))return await this.loadingPromises.get(e);const s=this.fetchCode(e);this.loadingPromises.set(e,s);try{const t=await s;return this.loadingPromises.delete(e),this._cacheSet(e,t),t}catch(t){throw this.loadingPromises.delete(e),t}}async fetchCode(e,t=3e4){const s=await fetch(e,{cache:"no-cache",headers:{Accept:"application/javascript, text/javascript, */*"},signal:AbortSignal.timeout(t)});if(!s.ok)throw new Error(`HTTP ${s.status}: ${s.statusText}`);const r=await s.text();if(!r.trim())throw new Error("Empty response");return r}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",signal:AbortSignal.timeout(5e3)})).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,l=a?.wu?.exports?.[n];if(l)try{const e=await this.loadComponent(o.url,l);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){let s;try{s=new RegExp(e)}catch(s){return void t.warn(`[WuLoader] Invalid clearCache pattern: ${e} (${s.message})`)}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,maxCacheSize:this.maxCacheSize,cacheTTL:this.cacheTTL,loading:this.loadingPromises.size,cacheKeys:Array.from(this.cache.keys())}}async _ensureSentinelVerified(){if("undefined"==typeof window)return;const e=window.location?.hostname||"";"localhost"!==e&&"127.0.0.1"!==e&&"0.0.0.0"!==e&&window.__wu_sentinel&&(window.__wu_sentinel.isVerified()||await new Promise((e,t)=>{if(window.__wu_sentinel.isVerified())return void e();const s=setTimeout(()=>{i(),t(new Error("[WuLoader] Sentinel verification timeout โ€” content blocked"))},1e4),r=()=>{i(),e()};function i(){clearTimeout(s),window.removeEventListener("wu:sentinel:verified",r)}window.addEventListener("wu:sentinel:verified",r);const n=setInterval(()=>{window.__wu_sentinel.isVerified()&&(clearInterval(n),i(),e())},100),o=i;i=function(){clearInterval(n),o()}}))}}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})`)}unregisterFullyIsolatedApp(e){this.fullyIsolatedApps.delete(e)&&t.debug(`[WuStyleBridge] ๐Ÿ›ก๏ธ Unregistered fully-isolated app: ${e}`)}isStyleFromFullyIsolatedApp(e){let t="",s=null;if("string"==typeof e?t=e:e&&"function"==typeof e.getAttribute?(s=e,t=e.getAttribute("data-vite-dev-id")||e.href||""):e&&(e.href?t=e.href:e.viteId?t=e.viteId:e.element&&(s=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))),s){const e=s.getAttribute("data-wu-app");if(e&&this.fullyIsolatedApps.has(e))return!0}if(!t||""===t.trim())return!1;const r=t.replace(/\\/g,"/").toLowerCase();for(const[e,t]of this.fullyIsolatedApps.entries()){const s=t.replace(/\\/g,"/").toLowerCase(),i=e.toLowerCase();if(s&&r.includes(s))return!0;if(new RegExp(`[/\\\\]${i}[/\\\\]`,"i").test(r))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){return"function"!=typeof e?()=>{}:(this._styleCallbacks||(this._styleCallbacks=new Set),this._styleCallbacks.add(e),this.styleObserver||(this.styleObserver=new MutationObserver(e=>{let s=!1;for(const t of e)if("childList"===t.type){if(Array.from(t.addedNodes).some(e=>"LINK"===e.tagName||"STYLE"===e.tagName)){s=!0;break}}if(s){t.debug("[WuStyleBridge] ๐Ÿ”„ Style changes detected");for(const e of this._styleCallbacks)try{e()}catch(e){t.warn("[WuStyleBridge] callback threw:",e)}}}),this.styleObserver.observe(document.head,{childList:!0,subtree:!0}),t.debug("[WuStyleBridge] ๐Ÿ‘€ Observing style changes (shared observer)")),()=>{this._styleCallbacks&&(this._styleCallbacks.delete(e),0===this._styleCallbacks.size&&this.styleObserver&&(this.styleObserver.disconnect(),this.styleObserver=null))})}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,t={}){this.appName=e,this.options=t,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}}}function l(e){return"none"===e?"isolated":"own-only"===e?"fully-isolated":e}class c{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(){return"proxy"}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(),u=l(r.styleMode||r.manifest?.styleMode),d={appName:e,shadowRoot:i,container:n,hostContainer:s,jsSandbox:a,jsProxy:c,styles:o,styleMode:u,manifest:r.manifest,created:Date.now(),sandbox_state:"stable",recovery_count:0};if("isolated"===u)t.wuDebug(`Style mode "isolated" for ${e}, using native Shadow DOM encapsulation`),d.stylesReady=Promise.resolve(0);else if("fully-isolated"===u){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),d.appUrl=s;const n=this;d.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 l=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){if(r++,!s.getAttribute)continue;const i=s.getAttribute("data-wu-app"),n=s.getAttribute("data-vite-dev-id");i===e?t.wuDebug(`New ${e} style (data-wu-app)`):n&&n.toLowerCase().includes(e.toLowerCase())&&t.wuDebug(`New ${e} style (vite): ${n.split("/").pop()}`)}r>0&&(t.wuDebug(`${r} new styles detected in head, checking for ${e}...`),a())});l.observe(document.head,{childList:!0,subtree:!0}),d.styleObserver=l,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...`),d.stylesReady=this.styleBridge.injectStylesIntoShadow(i,e,u).then(s=>(t.wuDebug(`Shared ${s} styles with ${e}`),d.unsubscribeStyleChanges=this.styleBridge.observeStyleChanges(()=>{t.wuDebug(`Reinjecting styles for ${e} due to changes`),this.styleBridge.injectStylesIntoShadow(i,e,u).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,d),t.wuDebug(`Enhanced sandbox created for ${e}`),d}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){const s=new a(e);return t.wuDebug(`Created ProxySandbox 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{if(n&&n.isActive()&&(n.deactivate(),t.wuDebug(`JS Sandbox deactivated for ${s}`)),e.styleObserver){try{e.styleObserver.disconnect()}catch(e){t.wuWarn(`Failed to disconnect styleObserver for ${s}: ${e}`)}e.styleObserver=null}if("function"==typeof e.unsubscribeStyleChanges){try{e.unsubscribeStyleChanges()}catch(e){t.wuWarn(`Failed to unsubscribe style changes for ${s}: ${e}`)}e.unsubscribeStyleChanges=null}this.styleBridge?.unregisterFullyIsolatedApp&&this.styleBridge.unregisterFullyIsolatedApp(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 l=0;for(const e of n){(e.getAttribute("data-vite-dev-id")||"").toLowerCase().includes(o)&&l++}l>0&&t.wuDebug(`Found ${l} styles potentially matching ${s}`);for(const r of n){const n=r.getAttribute("data-vite-dev-id")||"",o=n.replace(/\\/g,"/").toLowerCase();let l=!1;if(n)for(const e of a)if(e instanceof RegExp){if(e.test(n)){l=!0;break}}else if(o.includes(e.toLowerCase())){l=!0;break}if(l){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"},signal:AbortSignal.timeout(1e4)});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 s=this.schemas.get("wu.json");if(!e||"object"!=typeof e||Array.isArray(e))throw new Error("Manifest must be a valid object");for(const t of s.required)if(!e[t])throw new Error(`Required field missing: ${t}`);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")}if(void 0!==e.styleMode){const s=["shared","isolated","fully-isolated","none","own-only"];s.includes(e.styleMode)||(t.warn(`[WuManifest] Invalid styleMode "${e.styleMode}", defaulting to "shared". Valid: ${s.join(", ")}`),e.styleMode="shared")}if(void 0!==e.version&&"string"!=typeof e.version&&(t.warn("[WuManifest] version must be a string, ignoring"),delete e.version),void 0!==e.folder)if("string"!=typeof e.folder)t.warn("[WuManifest] folder must be a string, ignoring"),delete e.folder;else if(this._hasDangerousPatterns(e.folder))throw new Error("folder contains dangerous patterns");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){let s;try{s=new RegExp(e)}catch(s){return void t.warn(`[WuManifest] Invalid clearCache pattern: ${e} (${s.message})`)}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){if(this.metrics.reads++,!e)return this.state;const t=e.split(".");return t.every(d._isSafeKey)?t.reduce((e,t)=>e?.[t],this.state):void 0}set(e,t){if(this.metrics.writes++,e){const t=e.split(".");for(const s of t)if(!d._isSafeKey(s))throw new Error(`[WuStore] Unsafe key in path: "${s}" (path: "${e}")`)}const s=this.cursor;this.cursor=this.cursor+1;const 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(){const e=Math.min(1,this.cursor/this.bufferSize);return{...this.metrics,bufferUtilization:e,sequenceNumber:this.cursor,bufferSize:this.bufferSize,listenerCount:this.listeners.size+this.patternListeners.size}}static _isSafeKey(e){return"__proto__"!==e&&"constructor"!==e&&"prototype"!==e}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(".");if(!s.every(d._isSafeKey))return;const r=s.pop();let i=this.state;for(const e of s)Object.prototype.hasOwnProperty.call(i,e)&&"object"==typeof i[e]&&null!==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 m{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 p{constructor(e={}){this.config={maxSize:e.maxSize||50,maxItems:e.maxItems||100,defaultTTL:e.defaultTTL||36e5,persistent:!1!==e.persistent,storage:e.storage||"memory"};("localStorage"===this.config.storage||"sessionStorage"===this.config.storage)&&this.config.persistent&&this.config.maxSize>5&&t.wuWarn(`[WuCache] maxSize=${this.config.maxSize}MB configured with ${this.config.storage}, but browsers typically cap that backing at ~5MB per origin. In-memory LRU will evict before storage fills. Consider maxSize โ‰ค 5 or storage: 'memory' for a large in-memory cache.`),this.rateLimiting={enabled:!1!==e.rateLimiting,maxOpsPerSecond:e.maxOpsPerSecond||100,windowMs:1e3,cooldownMs:e.cooldownMs||5e3,operations:[],inCooldown:!1,cooldownUntil:0},this._rateLimitNotified=!1,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._rateLimitNotified=!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)}_onRateLimited(e,s){if(!this._rateLimitNotified){const r=Math.max(0,this.rateLimiting.cooldownUntil-Date.now());t.warn(`[WuCache] Rate limited: ${e} for key "${s}" rejected. ${r}ms remaining in cooldown.`),this._rateLimitNotified=!0}return{rateLimited:!0,operation:e,key:s}}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 this._onRateLimited("get",e),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 this._onRateLimited("set",e),!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 f{constructor(){this.listeners=new Map,this.history=[],this._wildcardCache=new Map,this.authorizedApps=new Map,this.trustedEvents=new Set(["wu:*","system:*"]),this.trustedApps=new Set(["wu-ai","wu-mcp-bridge","wu-core","plugin"]),this._internalTokens=new Map;for(const e of this.trustedApps)this._internalTokens.set(e,this._mintInternalToken());const e="undefined"!=typeof process&&"production"===process.env?.NODE_ENV;this.config={maxHistory:100,enableReplay:!0,enableWildcards:!0,logEvents:!1,strictMode:e,validateOrigin:!0},this._permissiveWarned=!1,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;if(this.trustedApps.has(t)){return s===this._internalTokens.get(t)}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:")}getInternalToken(e){return this.trustedApps.has(e)&&this._internalTokens.get(e)||null}_mintInternalToken(){if("undefined"!=typeof crypto&&"function"==typeof crypto.randomUUID)return`wu-int-${crypto.randomUUID()}`;const e=()=>Math.random().toString(36).slice(2,11);return`wu-int-${Date.now().toString(36)}-${e()}${e()}`}_generateToken(){if("undefined"!=typeof crypto&&"function"==typeof crypto.randomUUID)return`wu_${crypto.randomUUID()}`;const e=()=>Math.random().toString(36).slice(2,11);return`wu_${Date.now().toString(36)}_${e()}${e()}`}_warnPermissiveMode(){this._permissiveWarned||(this._permissiveWarned=!0,t.warn("[WuEventBus] strictMode is disabled. Events are emitted without authorization checks. Enable strictMode for production by calling enableStrictMode() or setting NODE_ENV=production."))}emit(e,s,r={}){const i=r.appName||"unknown";if(this.config.strictMode||this._warnPermissiveMode(),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;let s=this._wildcardCache.get(t);if(!s){const e=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");s=new RegExp(`^${e}$`),this._wildcardCache.set(t,s)}return 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}}const g="wu:",w="undefined"!=typeof performance&&"function"==typeof performance.mark&&"function"==typeof performance.measure;class y{constructor(){this.metrics=new Map,this.measurements=[],this.marks=new Map,this.config={enabled:!0,maxMeasurements:1e3,devtoolsTimeline:w},this.thresholds={mount:3e3,unmount:1e3,load:5e3},t.debug("[WuPerformance] โšก Framework performance monitoring initialized")}_entryName(e,t,s=""){return`${g}${e}:${t}${s}`}startMeasure(e,s="global"){const r=`${s}:${e}:start`;if(this.marks.set(r,performance.now()),this.config.devtoolsTimeline)try{performance.mark(this._entryName(s,e,":start"),{detail:{appName:s,name:e,source:"wu-framework",phase:"start"}})}catch{try{performance.mark(this._entryName(s,e,":start"))}catch{}}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(),o=n-i;if(this.marks.delete(r),this.config.devtoolsTimeline){const t=this._entryName(s,e),r=this._entryName(s,e,":start"),a=this._entryName(s,e,":end");try{performance.mark(a,{detail:{appName:s,name:e,source:"wu-framework",phase:"end",duration:o}}),performance.measure(t,{start:i,end:n,detail:{appName:s,name:e,source:"wu-framework",duration:o}})}catch{try{performance.mark(a),performance.measure(t,r,a)}catch{}}}return this.recordMeasurement({name:e,appName:s,duration:o,timestamp:Date.now(),type:"duration"}),this.checkThreshold(e,o)&&t.warn(`[WuPerformance] โš ๏ธ Threshold exceeded for ${e}: ${o.toFixed(2)}ms`),t.debug(`[WuPerformance] โน๏ธ Measure ended: ${r} (${o.toFixed(2)}ms)`),o}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}getDevToolsEntries(e={}){if(!w)return[];const{type:t="all",appName:s}=e,r=s?`${g}${s}:`:g,i=e=>e.name.startsWith(r),n=[];if("all"===t||"mark"===t)try{n.push(...performance.getEntriesByType("mark").filter(i))}catch{}if("all"===t||"measure"===t)try{n.push(...performance.getEntriesByType("measure").filter(i))}catch{}return n}observe(e,s={}){if("undefined"==typeof PerformanceObserver||"function"!=typeof e)return()=>{};const{type:r="measure"}=s,i="all"===r?["mark","measure"]:[r];let n;try{n=new PerformanceObserver(s=>{for(const r of s.getEntries())if(r.name.startsWith(g))try{e(r)}catch(e){t.warn(`[WuPerformance] observe callback threw: ${e?.message}`)}}),n.observe({entryTypes:i})}catch(e){return t.warn(`[WuPerformance] observe() unavailable: ${e?.message}`),()=>{}}return()=>{try{n.disconnect()}catch{}}}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=[]),this._clearTimelineEntries(e),t.debug("[WuPerformance] ๐Ÿงน Metrics cleared"+(e?` for ${e}`:""))}_clearTimelineEntries(e){if(!w)return;const t=e?`${g}${e}:`:g;try{for(const e of performance.getEntriesByType("mark"))e.name.startsWith(t)&&performance.clearMarks(e.name);for(const e of performance.getEntriesByType("measure"))e.name.startsWith(t)&&performance.clearMeasures(e.name)}catch{}}configure(e){this.config={...this.config,...e},e.thresholds&&(this.thresholds={...this.thresholds,...e.thresholds})}}class b{constructor(e,t={}){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=t.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()};if(e.includes("events")||e.includes("unsafe")){const e=this._core.eventBus.getInternalToken?.("plugin")||null;s.emit=(t,s)=>this._core.eventBus.emit(t,s,{appName:"plugin",token:e}),s.on=(e,t)=>this._core.eventBus.on(e,t),s.off=(e,t)=>this._core.eventBus.off(e,t)}return(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!")),b._deepFreeze(s)}static _deepFreeze(e,t){if(null==e)return e;if(!("object"==typeof e))return e;const s=Object.getPrototypeOf(e)===Object.prototype||null===Object.getPrototypeOf(e),r=Array.isArray(e);if(!s&&!r)return e;if(t||(t=new WeakSet),t.has(e))return e;t.add(e);const i=Object.keys(e);for(let s=0;s<i.length;s++){const r=e[i[s]];null!=r&&"object"==typeof r&&b._deepFreeze(r,t)}return Object.freeze(e)}_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)}}const v=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});class _{constructor(e){this.core=e,this.strategies=new Map,this.loadingQueue=[],this.isIdle=!1,this._idleHandle=null,this._idleFallback=null,this._destroyed=!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("undefined"!=typeof window)if("requestIdleCallback"in window){const e=t=>{this._destroyed||(this.isIdle=!0,this.processIdleQueue(t),this._idleHandle=requestIdleCallback(e))};this._idleHandle=requestIdleCallback(e)}else this._idleFallback=setTimeout(()=>{this._destroyed||(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._destroyed=!0,null!=this._idleHandle&&"function"==typeof cancelIdleCallback&&(cancelIdleCallback(this._idleHandle),this._idleHandle=null),null!=this._idleFallback&&(clearTimeout(this._idleFallback),this._idleFallback=null);for(const e of this.loadingQueue)try{e.resolve(null)}catch{}this.loadingQueue=[],t.debug("[WuStrategies] ๐Ÿงน Strategies cleaned up")}}class S{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 l=document.createElement("button");l.textContent="๐Ÿ”„ Reload",Object.assign(l.style,{padding:"0.5rem 1rem",background:"#ffc107",border:"none",borderRadius:"4px",cursor:"pointer",fontWeight:"bold",color:"#000"}),l.addEventListener("click",()=>window.location.reload()),i.appendChild(n),i.appendChild(o),i.appendChild(a),i.appendChild(l),r.appendChild(i)}logError(e,t){const s=e.stack?e.stack.split("\n").slice(0,5).join("\n"):"",r={};for(const e of Object.keys(t)){const s=t[e];r[e]="string"==typeof s||"number"==typeof s||"boolean"==typeof s||null===s?s:String(s)}const i={error:{name:e.name,message:e.message,stack:s},context:r,timestamp:Date.now()};this.errorLog.push(i),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=[],this.handlers=[],t.debug("[WuErrorBoundary] ๐Ÿงน Error boundary cleaned up")}}class ${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 l=async t=>(r=!0,void 0!==t&&(n={...n,...t}),await a(e+1));if(await s.middleware(n,l),!r)return t.debug(`[WuHooks] Hook "${s.name}" cancelled execution`),o=!0,{cancelled:!0};const c=Date.now()-i;t.debug(`[WuHooks] Hook "${s.name}" executed in ${c}ms`)}catch(t){return console.error(`[WuHooks] Error in hook "${s.name}":`,t),await a(e+1)}return n},l=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(),l}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"))}}const x=e=>async(t,s)=>{await e(t),await s()},k=(e,t)=>async(s,r)=>{await e(s)&&await t(s),await r()},E=e=>async(t,s)=>{await e(t)&&await s()},W=e=>async(t,s)=>{const r=await e(t);await s(r)},L=(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()}};class A{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=()=>{r.removeEventListener("mouseenter",o),r.removeEventListener("focusin",o);const e=this._listeners.indexOf(n);-1!==e&&this._listeners.splice(e,1)},o=()=>{i||(i=!0,this._prefetchImmediate(e,s),n())};return r.addEventListener("mouseenter",o,{passive:!0}),r.addEventListener("focusin",o,{passive:!0}),this._listeners.push(n),n}_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 r of t)if(r.isIntersecting){this._prefetchImmediate(e,s),n();break}},{rootMargin:"200px"});i.observe(r),this._observers.set(r,i);const n=()=>{i.disconnect(),this._observers.delete(r)};return n}_prefetchOnIdle(e,t){let s;const r=()=>{if(!s)return;const e=this._listeners.indexOf(s);-1!==e&&this._listeners.splice(e,1)},i=()=>{this._prefetchImmediate(e,t),r()};if("requestIdleCallback"in window){const e=requestIdleCallback(i,{timeout:3e3});s=()=>{cancelIdleCallback(e),r()}}else{const e=setTimeout(i,2e3);s=()=>{clearTimeout(e),r()}}return this._listeners.push(s),s}_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 D="wu-override:";class C{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(D))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=`${D}${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=`${D}${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 M{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._defineWaiters=new Map,this._resolvedPaths=new Map,this._mountRefs=new Map,this.loader=new n,this.sandbox=new c,this.manifest=new u,this.store=h,this.htmlParser=null,this.scriptExecutor=null,this._WuIframeSandbox=null,this.cache=new p({storage:"localStorage",maxSize:4}),this.eventBus=new f,this.performance=new y,this.pluginSystem=new b(this),this.strategies=new _(this),this.errorBoundary=new S(this),this.hooks=new $(this),this.prefetcher=new A(this),this.overrides=new C,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",this._strictFallback=!1!==e.strictFallback,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=this._defineWaiters.get(e);r&&(clearTimeout(r.timer),this._defineWaiters.delete(e),r.resolve());const i=new CustomEvent("wu:app:ready",{detail:{appName:e,timestamp:Date.now()}});window.dispatchEvent(i),t.wuDebug(`Lifecycle defined for: ${e}`)}async mount(e,s){const r=this._mountRefs.get(e)||0;if(this._mountRefs.set(e,r+1),t.wuDebug(`${e} mount refs: ${r} โ†’ ${r+1}`),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 i=this.hidden.get(e);if(i){if(i.containerSelector===s)return await this.show(e);await this._destroyHidden(e)}const n=this.mountWithRecovery(e,s,0);this._mountingPromises.set(e,n);try{return await n}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 l=this.performance.endMeasure("mount",e);await this.hooks.execute("afterMount",{appName:e,containerSelector:s,sandbox:o,mountTime:l}),await this.pluginSystem.callHook("afterMount",{appName:e,containerSelector:s,mountTime:l}),this.eventBus.emit("app:mounted",{appName:e,mountTime:l,attempt:r},{appName:e}),t.wuInfo(`${e} mounted successfully in ${l.toFixed(2)}ms`)}catch(i){t.wuError(`Mount attempt ${r+1} failed for ${e}:`,i);try{if(this.sandbox&&this.sandbox.sandboxes&&this.sandbox.sandboxes.has(e)){const s=this.sandbox.sandboxes.get(e);s&&s.proxySandbox&&s.proxySandbox.deactivate(),this.sandbox.sandboxes.delete(e),t.wuDebug(`Sandbox cleaned up after mount failure for ${e}`)}}catch(s){t.wuWarn(`Sandbox cleanup failed for ${e}:`,s)}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";t._requestedMode=s,t._actualMode=s,"strict"===s?await this._loadStrict(e,t):"eval"===s?await this._loadEval(e,t):await this._loadModule(e,t)}tagStyleAsApp(e,t){e&&"function"==typeof e.setAttribute&&t&&e.setAttribute("data-wu-app",t)}getSandboxInfo(e){const t=this.mounted.get(e)||this.hidden.get(e);if(!t)return null;const s=t.sandbox,r=s._actualMode||s._requestedMode||"module",i="strict"===r?"iframe":"eval"===r?"proxy-trap":"none";return{requestedMode:s._requestedMode||"module",actualMode:r,isolationLevel:i,mounted:this.mounted.has(e)}}async _ensureIframeSandboxClass(){if(this._WuIframeSandbox)return this._WuIframeSandbox;const e=await import("./core/wu-iframe-sandbox.js");return this._WuIframeSandbox=e.WuIframeSandbox,this._WuIframeSandbox}async _ensureEvalDeps(){if(!this.htmlParser){const{WuHtmlParser:e}=await import("./core/wu-html-parser.js");this.htmlParser=new e}if(!this.scriptExecutor){const{WuScriptExecutor:e}=await import("./core/wu-script-executor.js");this.scriptExecutor=new e}}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(await this._ensureIframeSandboxClass())(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){const n=e.strictFallback??this._strictFallback??!0;if(r.destroy(),s.iframeSandbox=null,!n)throw new Error(`[strict] iframe import failed for '${e.name}' and strictFallback is disabled.\nOriginal error: ${i.message}\nFix: ensure the app's dev server sets Access-Control-Allow-Origin headers,\nor explicitly allow degrade with { strictFallback: true } or sandbox: 'eval'.`);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.\nTo make this an error instead of a warning, set { strictFallback: false }.`),s._actualMode="eval",s._fellBackFromStrict=!0,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.`);await this._ensureEvalDeps();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`)}_waitForDefine(e,t,s=1e4){if(this.definitions.has(e))return Promise.resolve();const r=this._defineWaiters.get(e);if(r)return r.promise;let i,n;const o=new Promise((e,t)=>{i=e,n=t}),a=setTimeout(()=>{this._defineWaiters.delete(e)&&n(new Error(`[${t}] App '${e}' loaded but wu.define() was not called within ${s}ms.\nMake sure your app calls: window.wu.define('${e}', { mount, unmount })`))},s);return this._defineWaiters.set(e,{resolve:i,reject:n,timer:a,promise:o}),o}_cancelDefineWaiter(e){const t=this._defineWaiters.get(e);t&&(clearTimeout(t.timer),this._defineWaiters.delete(e))}async resolveModulePath(e){const s=e.manifest?.entry||"main.js",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}::${s}`,n=this._resolvedPaths.get(i);if(n)return t.wuDebug(`Using cached resolved path for ${e.name}: ${n}`),n;const o=[`${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(`Resolving path for ${e.name} (parallel HEAD probe)...`);const a=(await Promise.all(o.map(e=>this.validatePath(e).then(t=>t?e:null).catch(()=>null)))).find(e=>null!==e);if(a)return t.wuDebug(`Path resolved successfully: ${a}`),this._resolvedPaths.set(i,a),a;const l=o[0];return t.wuWarn(`All path candidates failed, using fallback: ${l}`),l}async validatePath(e){try{t.wuDebug(`Probing path: ${e}`);let s=await fetch(e,{method:"HEAD",cache:"no-cache",signal:AbortSignal.timeout(2e3)});if(405!==s.status&&501!==s.status||(t.wuDebug(`HEAD not supported (${s.status}), falling back to ranged GET: ${e}`),s=await fetch(e,{method:"GET",cache:"no-cache",headers:{Range:"bytes=0-255"},signal:AbortSignal.timeout(2e3)})),!s.ok&&206!==s.status)return t.wuDebug(`Path validation failed - HTTP ${s.status}: ${e}`),!1;const r=(s.headers.get("content-type")||"").toLowerCase();if(r.startsWith("text/html"))return t.wuDebug(`Path validation failed - HTML fallback detected: ${e}`),!1;return r.includes("javascript")||r.includes("module")||r.includes("text/plain")||""===r||e.endsWith(".js")||e.endsWith(".mjs")?(t.wuDebug(`Path validation successful: ${e}`),!0):(t.wuDebug(`Path validation failed - non-JS content-type '${r}': ${e}`),!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}`);const r=this._waitForDefine(s,"module");try{await import(e)}catch(r){throw this._cancelDefineWaiter(s),t.wuError(`Failed to import module ${e}:`,r),r}await r,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)?(this._mountRefs.delete(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(s.force)return this._mountRefs.delete(e),this._pendingUnmounts.has(e)&&(clearTimeout(this._pendingUnmounts.get(e)),this._pendingUnmounts.delete(e)),await this._executeUnmount(e,r);const i=this._mountRefs.get(e)||1,n=i-1;this._mountRefs.set(e,Math.max(0,n)),t.wuDebug(`${e} unmount refs: ${i} โ†’ ${n}`),n>0?t.wuDebug(`${e} unmount skipped: ${n} ref(s) still active`):(this._pendingUnmounts.has(e)&&clearTimeout(this._pendingUnmounts.get(e)),this._pendingUnmounts.set(e,setTimeout(async()=>{if(this._pendingUnmounts.delete(e),!((this._mountRefs.get(e)||0)>0)&&this.mounted.has(e)&&this.mounted.get(e)===r)try{await this._executeUnmount(e,r),this._mountRefs.delete(e)}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 m(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._defineWaiters)clearTimeout(e.timer),e.reject(new Error("Framework destroyed"));this._defineWaiters.clear(),this._resolvedPaths.clear(),this._mountRefs.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}}}const I=new Set(["provider","action","trigger","capability","workflow","removeApp","init"]),P=new Set(["context","conversation","permissions"]),T={tools:()=>[],expose:()=>!1,getStats:()=>({initialized:!1,lazy:!0})},O=new Set(["abort","destroy","confirmTool","rejectTool","fireTrigger"]),z=new Set(["stream","agent","runWorkflow"]);let j;if("undefined"!=typeof window&&window.wu&&window.wu._isWuFramework)j=window.wu;else if(j=new M,j._isWuFramework=!0,"undefined"!=typeof window){const e=Symbol.for("wu-framework");window[e]=j}if("undefined"!=typeof window&&(window.wu&&!window.wu._isWuFramework&&console.warn('[Wu Framework] window.wu already exists and is not a Wu Framework instance. Overwriting. Use Symbol.for("wu-framework") for collision-safe access.'),window.wu=j,j.version||(j.version="2.1.0",j.info={name:"Wu Framework",description:"Universal Microfrontends",features:["Framework Agnostic","Zero Config","Shadow DOM Isolation","Runtime Loading"]}),j.emit||(j.emit=(e,t,s)=>j.eventBus.emit(e,t,s),j.on=(e,t)=>j.eventBus.on(e,t),j.once=(e,t)=>j.eventBus.once(e,t),j.off=(e,t)=>j.eventBus.off(e,t)),j.prefetch||(j.prefetch=(e,t)=>j.prefetcher.prefetch(e,t),j.prefetchAll=e=>j.prefetcher.prefetchAll(e)),j.override||(j.override=(e,t,s)=>j.overrides.set(e,t,s),j.removeOverride=e=>j.overrides.remove(e),j.getOverrides=()=>j.overrides.getAll(),j.clearOverrides=()=>j.overrides.clearAll()),j.silence||(j.silence=async()=>{const{silenceAllLogs:e}=await Promise.resolve().then(function(){return i});e()},j.verbose=async()=>{const{enableAllLogs:e}=await Promise.resolve().then(function(){return i});e()}),j.ai||function(e){let t=null,s=null;const r=[],i=()=>t?Promise.resolve(t):s||(s=import("./ai/wu-ai.js").then(({WuAI:s})=>{t=new s({eventBus:e.eventBus,store:e.store,core:e,token:e.eventBus.getInternalToken?.("wu-ai")||null});for(const e of r)try{if("method"===e.kind)t[e.prop](...e.args);else if("sub"===e.kind){const s=t[e.parent];s&&"function"==typeof s[e.prop]&&s[e.prop](...e.args)}}catch(e){setTimeout(()=>{throw e},0)}return r.length=0,t}),s),n=new Proxy({},{get(e,s){if(t){const e=Reflect.get(t,s);return"function"==typeof e?e.bind(t):e}return"isLazy"===s||"isLoaded"!==s&&(P.has(s)?(o=s,new Proxy({},{get(e,s){if(t){const e=t[o],r=e?.[s];return"function"==typeof r?r.bind(e):r}return(...e)=>{r.push({kind:"sub",parent:o,prop:s,args:e}),i()}}})):I.has(s)?(...e)=>(r.push({kind:"method",prop:s,args:e}),i(),n):O.has(s)?(...e)=>{r.push({kind:"method",prop:s,args:e}),i()}:s in T?T[s]:z.has(s)?async function*(...e){const t=await i();yield*t[s](...e)}:(...e)=>i().then(t=>{const r=t[s];return"function"==typeof r?r.apply(t,e):r}));var o}});Object.defineProperty(e,"ai",{get:()=>t||n,configurable:!0}),e.aiReady=i}(j),!j.mcp)){let e=null;j.mcp={async connect(t="ws://localhost:19100",s={}){if(!e){const{createMcpBridge:t}=await import("./core/wu-mcp-bridge.js");e=t(j)}e.connect(t,s)},disconnect(){e?.disconnect()},isConnected:()=>e?.isConnected()||!1}}var N=j;const F=e=>j.init({apps:e}),R=(e,t)=>j.mount(e,t),H=(e,t)=>j.unmount(e,t),B=(e,t)=>j.define(e,t),U=(e,t)=>j.app(e,t),q=()=>j.destroy(),K=e=>j.hide(e),V=e=>j.show(e),J=e=>j.isHidden(e),Q=(e,t,s)=>j.eventBus.emit(e,t,s),G=(e,t)=>j.eventBus.on(e,t),Y=(e,t)=>j.eventBus.once(e,t),Z=(e,t)=>j.eventBus.off(e,t),X=e=>j.store.get(e),ee=(e,t)=>j.store.set(e,t),te=(e,t)=>j.store.on(e,t),se=(e,t)=>j.performance.startMeasure(e,t),re=(e,t)=>j.performance.endMeasure(e,t),ie=()=>j.performance.generateReport(),ne=(e,t)=>j.prefetch(e,t),oe=e=>j.prefetchAll(e),ae=(e,t,s)=>j.override(e,t,s),le=e=>j.removeOverride(e),ce=()=>j.getOverrides(),ue=()=>j.clearOverrides(),de=(e,t)=>j.pluginSystem.use(e,t),he=(e,t,s)=>j.hooks.use(e,t,s);export{m as WuApp,p as WuCache,M as WuCore,S as WuErrorBoundary,f as WuEventBus,$ as WuLifecycleHooks,n as WuLoader,_ as WuLoadingStrategy,u as WuManifest,C as WuOverrides,y as WuPerformance,b as WuPluginSystem,A as WuPrefetch,a as WuProxySandbox,c as WuSandbox,d as WuStore,o as WuStyleBridge,U as app,ue as clearOverrides,k as createConditionalHook,E as createGuardHook,v as createPlugin,x as createSimpleHook,L as createTimedHook,W as createTransformHook,N as default,B as define,q as destroy,Q as emit,r as enableAllLogs,re as endMeasure,ie as generatePerformanceReport,ce as getOverrides,X as getState,K as hide,F as init,J as isHidden,R as mount,l as normalizeStyleMode,Z as off,G as on,te as onStateChange,Y as once,ae as override,ne as prefetch,oe as prefetchAll,le as removeOverride,ee as setState,V as show,s as silenceAllLogs,se as startMeasure,h as store,H as unmount,he as useHook,de as usePlugin,j as wu};
1
+ /*! wu-framework v2.1.1 | MIT License */
2
+ export{WuLoader}from"./core/wu-loader.js";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(){if("undefined"!=typeof window&&!0===window.WU_DEBUG)return!0;if("undefined"!=typeof window&&!1===window.WU_DEBUG)return!1;if("undefined"!=typeof process&&"production"===process.env?.NODE_ENV)return!1;if("undefined"!=typeof process&&"development"===process.env?.NODE_ENV)return!0;if("undefined"!=typeof window&&window.location){const e=window.location.hostname;if("localhost"===e||"127.0.0.1"===e||"[::1]"===e)return!0;try{if(new URLSearchParams(window.location.search).has("wu-debug"))return!0}catch{}}return!1}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.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})`)}unregisterFullyIsolatedApp(e){this.fullyIsolatedApps.delete(e)&&t.debug(`[WuStyleBridge] ๐Ÿ›ก๏ธ Unregistered fully-isolated app: ${e}`)}isStyleFromFullyIsolatedApp(e){let t="",s=null;if("string"==typeof e?t=e:e&&"function"==typeof e.getAttribute?(s=e,t=e.getAttribute("data-vite-dev-id")||e.href||""):e&&(e.href?t=e.href:e.viteId?t=e.viteId:e.element&&(s=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))),s){const e=s.getAttribute("data-wu-app");if(e&&this.fullyIsolatedApps.has(e))return!0}if(!t||""===t.trim())return!1;const r=t.replace(/\\/g,"/").toLowerCase();for(const[e,t]of this.fullyIsolatedApps.entries()){const s=t.replace(/\\/g,"/").toLowerCase(),i=e.toLowerCase();if(s&&r.includes(s))return!0;if(new RegExp(`[/\\\\]${i}[/\\\\]`,"i").test(r))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){return"function"!=typeof e?()=>{}:(this._styleCallbacks||(this._styleCallbacks=new Set),this._styleCallbacks.add(e),this.styleObserver||(this.styleObserver=new MutationObserver(e=>{let s=!1;for(const t of e)if("childList"===t.type){if(Array.from(t.addedNodes).some(e=>"LINK"===e.tagName||"STYLE"===e.tagName)){s=!0;break}}if(s){t.debug("[WuStyleBridge] ๐Ÿ”„ Style changes detected");for(const e of this._styleCallbacks)try{e()}catch(e){t.warn("[WuStyleBridge] callback threw:",e)}}}),this.styleObserver.observe(document.head,{childList:!0,subtree:!0}),t.debug("[WuStyleBridge] ๐Ÿ‘€ Observing style changes (shared observer)")),()=>{this._styleCallbacks&&(this._styleCallbacks.delete(e),0===this._styleCallbacks.size&&this.styleObserver&&(this.styleObserver.disconnect(),this.styleObserver=null))})}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 o{constructor(e,t={}){this.appName=e,this.options=t,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}}}function a(e){return"none"===e?"isolated":"own-only"===e?"fully-isolated":e}class l{constructor(){this.sandboxes=new Map,this.styleBridge=new n,this.jsSandboxes=new Map,this.sandboxStrategy=this.detectSandboxStrategy(),t.wuDebug(`Advanced isolation system initialized (strategy: ${this.sandboxStrategy})`)}detectSandboxStrategy(){return"proxy"}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 l=this.createAdvancedJSSandbox(e);l.setContainer&&l.setContainer(n,i);const c=l.activate(),u=a(r.styleMode||r.manifest?.styleMode),d={appName:e,shadowRoot:i,container:n,hostContainer:s,jsSandbox:l,jsProxy:c,styles:o,styleMode:u,manifest:r.manifest,created:Date.now(),sandbox_state:"stable",recovery_count:0};if("isolated"===u)t.wuDebug(`Style mode "isolated" for ${e}, using native Shadow DOM encapsulation`),d.stylesReady=Promise.resolve(0);else if("fully-isolated"===u){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),d.appUrl=s;const n=this;d.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 l=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){if(r++,!s.getAttribute)continue;const i=s.getAttribute("data-wu-app"),n=s.getAttribute("data-vite-dev-id");i===e?t.wuDebug(`New ${e} style (data-wu-app)`):n&&n.toLowerCase().includes(e.toLowerCase())&&t.wuDebug(`New ${e} style (vite): ${n.split("/").pop()}`)}r>0&&(t.wuDebug(`${r} new styles detected in head, checking for ${e}...`),a())});l.observe(document.head,{childList:!0,subtree:!0}),d.styleObserver=l,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...`),d.stylesReady=this.styleBridge.injectStylesIntoShadow(i,e,u).then(s=>(t.wuDebug(`Shared ${s} styles with ${e}`),d.unsubscribeStyleChanges=this.styleBridge.observeStyleChanges(()=>{t.wuDebug(`Reinjecting styles for ${e} due to changes`),this.styleBridge.injectStylesIntoShadow(i,e,u).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,d),t.wuDebug(`Enhanced sandbox created for ${e}`),d}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){const s=new o(e);return t.wuDebug(`Created ProxySandbox 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{if(n&&n.isActive()&&(n.deactivate(),t.wuDebug(`JS Sandbox deactivated for ${s}`)),e.styleObserver){try{e.styleObserver.disconnect()}catch(e){t.wuWarn(`Failed to disconnect styleObserver for ${s}: ${e}`)}e.styleObserver=null}if("function"==typeof e.unsubscribeStyleChanges){try{e.unsubscribeStyleChanges()}catch(e){t.wuWarn(`Failed to unsubscribe style changes for ${s}: ${e}`)}e.unsubscribeStyleChanges=null}this.styleBridge?.unregisterFullyIsolatedApp&&this.styleBridge.unregisterFullyIsolatedApp(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 l=0;for(const e of n){(e.getAttribute("data-vite-dev-id")||"").toLowerCase().includes(o)&&l++}l>0&&t.wuDebug(`Found ${l} styles potentially matching ${s}`);for(const r of n){const n=r.getAttribute("data-vite-dev-id")||"",o=n.replace(/\\/g,"/").toLowerCase();let l=!1;if(n)for(const e of a)if(e instanceof RegExp){if(e.test(n)){l=!0;break}}else if(o.includes(e.toLowerCase())){l=!0;break}if(l){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 c{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"},signal:AbortSignal.timeout(1e4)});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 s=this.schemas.get("wu.json");if(!e||"object"!=typeof e||Array.isArray(e))throw new Error("Manifest must be a valid object");for(const t of s.required)if(!e[t])throw new Error(`Required field missing: ${t}`);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")}if(void 0!==e.styleMode){const s=["shared","isolated","fully-isolated","none","own-only"];s.includes(e.styleMode)||(t.warn(`[WuManifest] Invalid styleMode "${e.styleMode}", defaulting to "shared". Valid: ${s.join(", ")}`),e.styleMode="shared")}if(void 0!==e.version&&"string"!=typeof e.version&&(t.warn("[WuManifest] version must be a string, ignoring"),delete e.version),void 0!==e.folder)if("string"!=typeof e.folder)t.warn("[WuManifest] folder must be a string, ignoring"),delete e.folder;else if(this._hasDangerousPatterns(e.folder))throw new Error("folder contains dangerous patterns");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){let s;try{s=new RegExp(e)}catch(s){return void t.warn(`[WuManifest] Invalid clearCache pattern: ${e} (${s.message})`)}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 u{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){if(this.metrics.reads++,!e)return this.state;const t=e.split(".");return t.every(u._isSafeKey)?t.reduce((e,t)=>e?.[t],this.state):void 0}set(e,t){if(this.metrics.writes++,e){const t=e.split(".");for(const s of t)if(!u._isSafeKey(s))throw new Error(`[WuStore] Unsafe key in path: "${s}" (path: "${e}")`)}const s=this.cursor;this.cursor=this.cursor+1;const 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(){const e=Math.min(1,this.cursor/this.bufferSize);return{...this.metrics,bufferUtilization:e,sequenceNumber:this.cursor,bufferSize:this.bufferSize,listenerCount:this.listeners.size+this.patternListeners.size}}static _isSafeKey(e){return"__proto__"!==e&&"constructor"!==e&&"prototype"!==e}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(".");if(!s.every(u._isSafeKey))return;const r=s.pop();let i=this.state;for(const e of s)Object.prototype.hasOwnProperty.call(i,e)&&"object"==typeof i[e]&&null!==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 d=new u;class h{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"};("localStorage"===this.config.storage||"sessionStorage"===this.config.storage)&&this.config.persistent&&this.config.maxSize>5&&t.wuWarn(`[WuCache] maxSize=${this.config.maxSize}MB configured with ${this.config.storage}, but browsers typically cap that backing at ~5MB per origin. In-memory LRU will evict before storage fills. Consider maxSize โ‰ค 5 or storage: 'memory' for a large in-memory cache.`),this.rateLimiting={enabled:!1!==e.rateLimiting,maxOpsPerSecond:e.maxOpsPerSecond||100,windowMs:1e3,cooldownMs:e.cooldownMs||5e3,operations:[],inCooldown:!1,cooldownUntil:0},this._rateLimitNotified=!1,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._rateLimitNotified=!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)}_onRateLimited(e,s){if(!this._rateLimitNotified){const r=Math.max(0,this.rateLimiting.cooldownUntil-Date.now());t.warn(`[WuCache] Rate limited: ${e} for key "${s}" rejected. ${r}ms remaining in cooldown.`),this._rateLimitNotified=!0}return{rateLimited:!0,operation:e,key:s}}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 this._onRateLimited("get",e),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 this._onRateLimited("set",e),!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 p{constructor(){this.listeners=new Map,this.history=[],this._wildcardCache=new Map,this.authorizedApps=new Map,this.trustedEvents=new Set(["wu:*","system:*"]),this.trustedApps=new Set(["wu-ai","wu-mcp-bridge","wu-core","plugin"]),this._internalTokens=new Map;for(const e of this.trustedApps)this._internalTokens.set(e,this._mintInternalToken());const e="undefined"!=typeof process&&"production"===process.env?.NODE_ENV;this.config={maxHistory:100,enableReplay:!0,enableWildcards:!0,logEvents:!1,strictMode:e,validateOrigin:!0},this._permissiveWarned=!1,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;if(this.trustedApps.has(t)){return s===this._internalTokens.get(t)}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:")}getInternalToken(e){return this.trustedApps.has(e)&&this._internalTokens.get(e)||null}_mintInternalToken(){if("undefined"!=typeof crypto&&"function"==typeof crypto.randomUUID)return`wu-int-${crypto.randomUUID()}`;const e=()=>Math.random().toString(36).slice(2,11);return`wu-int-${Date.now().toString(36)}-${e()}${e()}`}_generateToken(){if("undefined"!=typeof crypto&&"function"==typeof crypto.randomUUID)return`wu_${crypto.randomUUID()}`;const e=()=>Math.random().toString(36).slice(2,11);return`wu_${Date.now().toString(36)}_${e()}${e()}`}_warnPermissiveMode(){this._permissiveWarned||(this._permissiveWarned=!0,t.warn("[WuEventBus] strictMode is disabled. Events are emitted without authorization checks. Enable strictMode for production by calling enableStrictMode() or setting NODE_ENV=production."))}emit(e,s,r={}){const i=r.appName||"unknown";if(this.config.strictMode||this._warnPermissiveMode(),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;let s=this._wildcardCache.get(t);if(!s){const e=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");s=new RegExp(`^${e}$`),this._wildcardCache.set(t,s)}return 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}}const f="wu:",g="undefined"!=typeof performance&&"function"==typeof performance.mark&&"function"==typeof performance.measure;class w{constructor(){this.metrics=new Map,this.measurements=[],this.marks=new Map,this.config={enabled:!0,maxMeasurements:1e3,devtoolsTimeline:g},this.thresholds={mount:3e3,unmount:1e3,load:5e3},t.debug("[WuPerformance] โšก Framework performance monitoring initialized")}_entryName(e,t,s=""){return`${f}${e}:${t}${s}`}startMeasure(e,s="global"){const r=`${s}:${e}:start`;if(this.marks.set(r,performance.now()),this.config.devtoolsTimeline)try{performance.mark(this._entryName(s,e,":start"),{detail:{appName:s,name:e,source:"wu-framework",phase:"start"}})}catch{try{performance.mark(this._entryName(s,e,":start"))}catch{}}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(),o=n-i;if(this.marks.delete(r),this.config.devtoolsTimeline){const t=this._entryName(s,e),r=this._entryName(s,e,":start"),a=this._entryName(s,e,":end");try{performance.mark(a,{detail:{appName:s,name:e,source:"wu-framework",phase:"end",duration:o}}),performance.measure(t,{start:i,end:n,detail:{appName:s,name:e,source:"wu-framework",duration:o}})}catch{try{performance.mark(a),performance.measure(t,r,a)}catch{}}}return this.recordMeasurement({name:e,appName:s,duration:o,timestamp:Date.now(),type:"duration"}),this.checkThreshold(e,o)&&t.warn(`[WuPerformance] โš ๏ธ Threshold exceeded for ${e}: ${o.toFixed(2)}ms`),t.debug(`[WuPerformance] โน๏ธ Measure ended: ${r} (${o.toFixed(2)}ms)`),o}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}getDevToolsEntries(e={}){if(!g)return[];const{type:t="all",appName:s}=e,r=s?`${f}${s}:`:f,i=e=>e.name.startsWith(r),n=[];if("all"===t||"mark"===t)try{n.push(...performance.getEntriesByType("mark").filter(i))}catch{}if("all"===t||"measure"===t)try{n.push(...performance.getEntriesByType("measure").filter(i))}catch{}return n}observe(e,s={}){if("undefined"==typeof PerformanceObserver||"function"!=typeof e)return()=>{};const{type:r="measure"}=s,i="all"===r?["mark","measure"]:[r];let n;try{n=new PerformanceObserver(s=>{for(const r of s.getEntries())if(r.name.startsWith(f))try{e(r)}catch(e){t.warn(`[WuPerformance] observe callback threw: ${e?.message}`)}}),n.observe({entryTypes:i})}catch(e){return t.warn(`[WuPerformance] observe() unavailable: ${e?.message}`),()=>{}}return()=>{try{n.disconnect()}catch{}}}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=[]),this._clearTimelineEntries(e),t.debug("[WuPerformance] ๐Ÿงน Metrics cleared"+(e?` for ${e}`:""))}_clearTimelineEntries(e){if(!g)return;const t=e?`${f}${e}:`:f;try{for(const e of performance.getEntriesByType("mark"))e.name.startsWith(t)&&performance.clearMarks(e.name);for(const e of performance.getEntriesByType("measure"))e.name.startsWith(t)&&performance.clearMeasures(e.name)}catch{}}configure(e){this.config={...this.config,...e},e.thresholds&&(this.thresholds={...this.thresholds,...e.thresholds})}}class y{constructor(e,t={}){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=t.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()};if(e.includes("events")||e.includes("unsafe")){const e=this._core.eventBus.getInternalToken?.("plugin")||null;s.emit=(t,s)=>this._core.eventBus.emit(t,s,{appName:"plugin",token:e}),s.on=(e,t)=>this._core.eventBus.on(e,t),s.off=(e,t)=>this._core.eventBus.off(e,t)}return(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!")),y._deepFreeze(s)}static _deepFreeze(e,t){if(null==e)return e;if(!("object"==typeof e))return e;const s=Object.getPrototypeOf(e)===Object.prototype||null===Object.getPrototypeOf(e),r=Array.isArray(e);if(!s&&!r)return e;if(t||(t=new WeakSet),t.has(e))return e;t.add(e);const i=Object.keys(e);for(let s=0;s<i.length;s++){const r=e[i[s]];null!=r&&"object"==typeof r&&y._deepFreeze(r,t)}return Object.freeze(e)}_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)}}const b=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});class v{constructor(e){this.core=e,this.strategies=new Map,this.loadingQueue=[],this.isIdle=!1,this._idleHandle=null,this._idleFallback=null,this._destroyed=!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("undefined"!=typeof window)if("requestIdleCallback"in window){const e=t=>{this._destroyed||(this.isIdle=!0,this.processIdleQueue(t),this._idleHandle=requestIdleCallback(e))};this._idleHandle=requestIdleCallback(e)}else this._idleFallback=setTimeout(()=>{this._destroyed||(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._destroyed=!0,null!=this._idleHandle&&"function"==typeof cancelIdleCallback&&(cancelIdleCallback(this._idleHandle),this._idleHandle=null),null!=this._idleFallback&&(clearTimeout(this._idleFallback),this._idleFallback=null);for(const e of this.loadingQueue)try{e.resolve(null)}catch{}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 l=document.createElement("button");l.textContent="๐Ÿ”„ Reload",Object.assign(l.style,{padding:"0.5rem 1rem",background:"#ffc107",border:"none",borderRadius:"4px",cursor:"pointer",fontWeight:"bold",color:"#000"}),l.addEventListener("click",()=>window.location.reload()),i.appendChild(n),i.appendChild(o),i.appendChild(a),i.appendChild(l),r.appendChild(i)}logError(e,t){const s=e.stack?e.stack.split("\n").slice(0,5).join("\n"):"",r={};for(const e of Object.keys(t)){const s=t[e];r[e]="string"==typeof s||"number"==typeof s||"boolean"==typeof s||null===s?s:String(s)}const i={error:{name:e.name,message:e.message,stack:s},context:r,timestamp:Date.now()};this.errorLog.push(i),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=[],this.handlers=[],t.debug("[WuErrorBoundary] ๐Ÿงน Error boundary cleaned up")}}class S{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 l=async t=>(r=!0,void 0!==t&&(n={...n,...t}),await a(e+1));if(await s.middleware(n,l),!r)return t.debug(`[WuHooks] Hook "${s.name}" cancelled execution`),o=!0,{cancelled:!0};const c=Date.now()-i;t.debug(`[WuHooks] Hook "${s.name}" executed in ${c}ms`)}catch(t){return console.error(`[WuHooks] Error in hook "${s.name}":`,t),await a(e+1)}return n},l=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(),l}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"))}}const $=e=>async(t,s)=>{await e(t),await s()},x=(e,t)=>async(s,r)=>{await e(s)&&await t(s),await r()},k=e=>async(t,s)=>{await e(t)&&await s()},E=e=>async(t,s)=>{const r=await e(t);await s(r)},W=(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()}};class A{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=()=>{r.removeEventListener("mouseenter",o),r.removeEventListener("focusin",o);const e=this._listeners.indexOf(n);-1!==e&&this._listeners.splice(e,1)},o=()=>{i||(i=!0,this._prefetchImmediate(e,s),n())};return r.addEventListener("mouseenter",o,{passive:!0}),r.addEventListener("focusin",o,{passive:!0}),this._listeners.push(n),n}_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 r of t)if(r.isIntersecting){this._prefetchImmediate(e,s),n();break}},{rootMargin:"200px"});i.observe(r),this._observers.set(r,i);const n=()=>{i.disconnect(),this._observers.delete(r)};return n}_prefetchOnIdle(e,t){let s;const r=()=>{if(!s)return;const e=this._listeners.indexOf(s);-1!==e&&this._listeners.splice(e,1)},i=()=>{this._prefetchImmediate(e,t),r()};if("requestIdleCallback"in window){const e=requestIdleCallback(i,{timeout:3e3});s=()=>{cancelIdleCallback(e),r()}}else{const e=setTimeout(i,2e3);s=()=>{clearTimeout(e),r()}}return this._listeners.push(s),s}_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 L="wu-override:";class D{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(L))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=`${L}${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=`${L}${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 M{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._defineWaiters=new Map,this._resolvedPaths=new Map,this._mountRefs=new Map,this.sandbox=new l,this.manifest=new c,this.store=d,this.htmlParser=null,this.scriptExecutor=null,this._WuIframeSandbox=null,this.loader=null,this.cache=new m({storage:"localStorage",maxSize:4}),this.eventBus=new p,this.performance=new w,this.pluginSystem=new y(this),this.strategies=new v(this),this.errorBoundary=new _(this),this.hooks=new S(this),this.prefetcher=new A(this),this.overrides=new D,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",this._strictFallback=!1!==e.strictFallback,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=this._defineWaiters.get(e);r&&(clearTimeout(r.timer),this._defineWaiters.delete(e),r.resolve());const i=new CustomEvent("wu:app:ready",{detail:{appName:e,timestamp:Date.now()}});window.dispatchEvent(i),t.wuDebug(`Lifecycle defined for: ${e}`)}async mount(e,s){const r=this._mountRefs.get(e)||0;if(this._mountRefs.set(e,r+1),t.wuDebug(`${e} mount refs: ${r} โ†’ ${r+1}`),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 i=this.hidden.get(e);if(i){if(i.containerSelector===s)return await this.show(e);await this._destroyHidden(e)}const n=this.mountWithRecovery(e,s,0);this._mountingPromises.set(e,n);try{return await n}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 l=this.performance.endMeasure("mount",e);await this.hooks.execute("afterMount",{appName:e,containerSelector:s,sandbox:o,mountTime:l}),await this.pluginSystem.callHook("afterMount",{appName:e,containerSelector:s,mountTime:l}),this.eventBus.emit("app:mounted",{appName:e,mountTime:l,attempt:r},{appName:e}),t.wuInfo(`${e} mounted successfully in ${l.toFixed(2)}ms`)}catch(i){t.wuError(`Mount attempt ${r+1} failed for ${e}:`,i);try{if(this.sandbox&&this.sandbox.sandboxes&&this.sandbox.sandboxes.has(e)){const s=this.sandbox.sandboxes.get(e);s&&s.proxySandbox&&s.proxySandbox.deactivate(),this.sandbox.sandboxes.delete(e),t.wuDebug(`Sandbox cleaned up after mount failure for ${e}`)}}catch(s){t.wuWarn(`Sandbox cleanup failed for ${e}:`,s)}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";t._requestedMode=s,t._actualMode=s,"strict"===s?await this._loadStrict(e,t):"eval"===s?await this._loadEval(e,t):await this._loadModule(e,t)}tagStyleAsApp(e,t){e&&"function"==typeof e.setAttribute&&t&&e.setAttribute("data-wu-app",t)}getSandboxInfo(e){const t=this.mounted.get(e)||this.hidden.get(e);if(!t)return null;const s=t.sandbox,r=s._actualMode||s._requestedMode||"module",i="strict"===r?"iframe":"eval"===r?"proxy-trap":"none";return{requestedMode:s._requestedMode||"module",actualMode:r,isolationLevel:i,mounted:this.mounted.has(e)}}async _ensureIframeSandboxClass(){if(this._WuIframeSandbox)return this._WuIframeSandbox;const e=await import("./core/wu-iframe-sandbox.js");return this._WuIframeSandbox=e.WuIframeSandbox,this._WuIframeSandbox}async _ensureEvalDeps(){if(!this.htmlParser){const{WuHtmlParser:e}=await import("./core/wu-html-parser.js");this.htmlParser=new e}if(!this.scriptExecutor){const{WuScriptExecutor:e}=await import("./core/wu-script-executor.js");this.scriptExecutor=new e}}async _ensureLoader(){if(!this.loader){const{WuLoader:e}=await import("./core/wu-loader.js");this.loader=new e}}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(await this._ensureIframeSandboxClass())(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){const n=e.strictFallback??this._strictFallback??!0;if(r.destroy(),s.iframeSandbox=null,!n)throw new Error(`[strict] iframe import failed for '${e.name}' and strictFallback is disabled.\nOriginal error: ${i.message}\nFix: ensure the app's dev server sets Access-Control-Allow-Origin headers,\nor explicitly allow degrade with { strictFallback: true } or sandbox: 'eval'.`);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.\nTo make this an error instead of a warning, set { strictFallback: false }.`),s._actualMode="eval",s._fellBackFromStrict=!0,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.`);await this._ensureEvalDeps();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`)}_waitForDefine(e,t,s=1e4){if(this.definitions.has(e))return Promise.resolve();const r=this._defineWaiters.get(e);if(r)return r.promise;let i,n;const o=new Promise((e,t)=>{i=e,n=t}),a=setTimeout(()=>{this._defineWaiters.delete(e)&&n(new Error(`[${t}] App '${e}' loaded but wu.define() was not called within ${s}ms.\nMake sure your app calls: window.wu.define('${e}', { mount, unmount })`))},s);return this._defineWaiters.set(e,{resolve:i,reject:n,timer:a,promise:o}),o}_cancelDefineWaiter(e){const t=this._defineWaiters.get(e);t&&(clearTimeout(t.timer),this._defineWaiters.delete(e))}async resolveModulePath(e){const s=e.manifest?.entry||"main.js",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}::${s}`,n=this._resolvedPaths.get(i);if(n)return t.wuDebug(`Using cached resolved path for ${e.name}: ${n}`),n;const o=[`${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(`Resolving path for ${e.name} (parallel HEAD probe)...`);const a=(await Promise.all(o.map(e=>this.validatePath(e).then(t=>t?e:null).catch(()=>null)))).find(e=>null!==e);if(a)return t.wuDebug(`Path resolved successfully: ${a}`),this._resolvedPaths.set(i,a),a;const l=o[0];return t.wuWarn(`All path candidates failed, using fallback: ${l}`),l}async validatePath(e){try{t.wuDebug(`Probing path: ${e}`);let s=await fetch(e,{method:"HEAD",cache:"no-cache",signal:AbortSignal.timeout(2e3)});if(405!==s.status&&501!==s.status||(t.wuDebug(`HEAD not supported (${s.status}), falling back to ranged GET: ${e}`),s=await fetch(e,{method:"GET",cache:"no-cache",headers:{Range:"bytes=0-255"},signal:AbortSignal.timeout(2e3)})),!s.ok&&206!==s.status)return t.wuDebug(`Path validation failed - HTTP ${s.status}: ${e}`),!1;const r=(s.headers.get("content-type")||"").toLowerCase();if(r.startsWith("text/html"))return t.wuDebug(`Path validation failed - HTML fallback detected: ${e}`),!1;return r.includes("javascript")||r.includes("module")||r.includes("text/plain")||""===r||e.endsWith(".js")||e.endsWith(".mjs")?(t.wuDebug(`Path validation successful: ${e}`),!0):(t.wuDebug(`Path validation failed - non-JS content-type '${r}': ${e}`),!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}`);const r=this._waitForDefine(s,"module");try{await import(e)}catch(r){throw this._cancelDefineWaiter(s),t.wuError(`Failed to import module ${e}:`,r),r}await r,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)?(this._mountRefs.delete(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(s.force)return this._mountRefs.delete(e),this._pendingUnmounts.has(e)&&(clearTimeout(this._pendingUnmounts.get(e)),this._pendingUnmounts.delete(e)),await this._executeUnmount(e,r);const i=this._mountRefs.get(e)||1,n=i-1;this._mountRefs.set(e,Math.max(0,n)),t.wuDebug(`${e} unmount refs: ${i} โ†’ ${n}`),n>0?t.wuDebug(`${e} unmount skipped: ${n} ref(s) still active`):(this._pendingUnmounts.has(e)&&clearTimeout(this._pendingUnmounts.get(e)),this._pendingUnmounts.set(e,setTimeout(async()=>{if(this._pendingUnmounts.delete(e),!((this._mountRefs.get(e)||0)>0)&&this.mounted.has(e)&&this.mounted.get(e)===r)try{await this._executeUnmount(e,r),this._mountRefs.delete(e)}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._ensureLoader(),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 h(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._defineWaiters)clearTimeout(e.timer),e.reject(new Error("Framework destroyed"));this._defineWaiters.clear(),this._resolvedPaths.clear(),this._mountRefs.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}}}const I=new Set(["provider","action","trigger","capability","workflow","removeApp","init"]),C=new Set(["context","conversation","permissions"]),P={tools:()=>[],expose:()=>!1,getStats:()=>({initialized:!1,lazy:!0})},O=new Set(["abort","destroy","confirmTool","rejectTool","fireTrigger"]),T=new Set(["stream","agent","runWorkflow"]);let N;if("undefined"!=typeof window&&window.wu&&window.wu._isWuFramework)N=window.wu;else if(N=new M,N._isWuFramework=!0,"undefined"!=typeof window){const e=Symbol.for("wu-framework");window[e]=N}if("undefined"!=typeof window&&(window.wu&&!window.wu._isWuFramework&&console.warn('[Wu Framework] window.wu already exists and is not a Wu Framework instance. Overwriting. Use Symbol.for("wu-framework") for collision-safe access.'),window.wu=N,N.version||(N.version="2.1.1",N.info={name:"Wu Framework",description:"Universal Microfrontends",features:["Framework Agnostic","Zero Config","Shadow DOM Isolation","Runtime Loading"]}),N.emit||(N.emit=(e,t,s)=>N.eventBus.emit(e,t,s),N.on=(e,t)=>N.eventBus.on(e,t),N.once=(e,t)=>N.eventBus.once(e,t),N.off=(e,t)=>N.eventBus.off(e,t)),N.prefetch||(N.prefetch=(e,t)=>N.prefetcher.prefetch(e,t),N.prefetchAll=e=>N.prefetcher.prefetchAll(e)),N.override||(N.override=(e,t,s)=>N.overrides.set(e,t,s),N.removeOverride=e=>N.overrides.remove(e),N.getOverrides=()=>N.overrides.getAll(),N.clearOverrides=()=>N.overrides.clearAll()),N.silence||(N.silence=async()=>{const{silenceAllLogs:e}=await Promise.resolve().then(function(){return i});e()},N.verbose=async()=>{const{enableAllLogs:e}=await Promise.resolve().then(function(){return i});e()}),N.ai||function(e){let t=null,s=null;const r=[],i=()=>t?Promise.resolve(t):s||(s=import("./ai/wu-ai.js").then(({WuAI:s})=>{t=new s({eventBus:e.eventBus,store:e.store,core:e,token:e.eventBus.getInternalToken?.("wu-ai")||null});for(const e of r)try{if("method"===e.kind)t[e.prop](...e.args);else if("sub"===e.kind){const s=t[e.parent];s&&"function"==typeof s[e.prop]&&s[e.prop](...e.args)}}catch(e){setTimeout(()=>{throw e},0)}return r.length=0,t}),s),n=new Proxy({},{get(e,s){if(t){const e=Reflect.get(t,s);return"function"==typeof e?e.bind(t):e}return"isLazy"===s||"isLoaded"!==s&&(C.has(s)?(o=s,new Proxy({},{get(e,s){if(t){const e=t[o],r=e?.[s];return"function"==typeof r?r.bind(e):r}return(...e)=>{r.push({kind:"sub",parent:o,prop:s,args:e}),i()}}})):I.has(s)?(...e)=>(r.push({kind:"method",prop:s,args:e}),i(),n):O.has(s)?(...e)=>{r.push({kind:"method",prop:s,args:e}),i()}:s in P?P[s]:T.has(s)?async function*(...e){const t=await i();yield*t[s](...e)}:(...e)=>i().then(t=>{const r=t[s];return"function"==typeof r?r.apply(t,e):r}));var o}});Object.defineProperty(e,"ai",{get:()=>t||n,configurable:!0}),e.aiReady=i}(N),!N.mcp)){let e=null;N.mcp={async connect(t="ws://localhost:19100",s={}){if(!e){const{createMcpBridge:t}=await import("./core/wu-mcp-bridge.js");e=t(N)}e.connect(t,s)},disconnect(){e?.disconnect()},isConnected:()=>e?.isConnected()||!1}}var z=N;const j=e=>N.init({apps:e}),F=(e,t)=>N.mount(e,t),R=(e,t)=>N.unmount(e,t),H=(e,t)=>N.define(e,t),B=(e,t)=>N.app(e,t),U=()=>N.destroy(),q=e=>N.hide(e),K=e=>N.show(e),J=e=>N.isHidden(e),Q=(e,t,s)=>N.eventBus.emit(e,t,s),V=(e,t)=>N.eventBus.on(e,t),G=(e,t)=>N.eventBus.once(e,t),Y=(e,t)=>N.eventBus.off(e,t),Z=e=>N.store.get(e),X=(e,t)=>N.store.set(e,t),ee=(e,t)=>N.store.on(e,t),te=(e,t)=>N.performance.startMeasure(e,t),se=(e,t)=>N.performance.endMeasure(e,t),re=()=>N.performance.generateReport(),ie=(e,t)=>N.prefetch(e,t),ne=e=>N.prefetchAll(e),oe=(e,t,s)=>N.override(e,t,s),ae=e=>N.removeOverride(e),le=()=>N.getOverrides(),ce=()=>N.clearOverrides(),ue=(e,t)=>N.pluginSystem.use(e,t),de=(e,t,s)=>N.hooks.use(e,t,s);export{h as WuApp,m as WuCache,M as WuCore,_ as WuErrorBoundary,p as WuEventBus,S as WuLifecycleHooks,v as WuLoadingStrategy,c as WuManifest,D as WuOverrides,w as WuPerformance,y as WuPluginSystem,A as WuPrefetch,o as WuProxySandbox,l as WuSandbox,u as WuStore,n as WuStyleBridge,B as app,ce as clearOverrides,x as createConditionalHook,k as createGuardHook,b as createPlugin,$ as createSimpleHook,W as createTimedHook,E as createTransformHook,z as default,H as define,U as destroy,Q as emit,r as enableAllLogs,se as endMeasure,re as generatePerformanceReport,le as getOverrides,Z as getState,q as hide,j as init,J as isHidden,F as mount,a as normalizeStyleMode,Y as off,V as on,ee as onStateChange,G as once,oe as override,ie as prefetch,ne as prefetchAll,ae as removeOverride,X as setState,K as show,s as silenceAllLogs,te as startMeasure,d as store,R as unmount,de as useHook,ue as usePlugin,N as wu};
3
3
  //# sourceMappingURL=wu-framework.esm.js.map