wu-framework 1.1.5 β 1.1.6
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.
- package/dist/wu-framework.cjs.js +1 -0
- package/dist/wu-framework.dev.js +8534 -0
- package/dist/wu-framework.dev.js.map +1 -0
- package/dist/wu-framework.hex.js +23 -0
- package/dist/wu-framework.min.js +1 -0
- package/dist/wu-framework.obf.js +1 -0
- package/dist/wu-framework.umd.js +1 -0
- package/package.json +1 -1
- package/dist/wu-framework.protected.js +0 -24
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});class WuLoader{constructor(){this.cache=new Map,this.loadingPromises=new Map,console.log("[WuLoader] π¦ Dynamic loader initialized")}async loadApp(e,t){const o=`${e}/${t?.entry||"index.js"}`;console.log(`[WuLoader] π₯ Loading app from: ${o}`);try{if(this.cache.has(o))return console.log(`[WuLoader] β‘ Cache hit for: ${o}`),this.cache.get(o);if(this.loadingPromises.has(o))return console.log(`[WuLoader] β³ Loading in progress for: ${o}`),await this.loadingPromises.get(o);const e=this.fetchCode(o);this.loadingPromises.set(o,e);const t=await e;return this.loadingPromises.delete(o),this.cache.set(o,t),console.log(`[WuLoader] β
App loaded successfully: ${o}`),t}catch(e){throw this.loadingPromises.delete(o),console.error(`[WuLoader] β Failed to load app: ${o}`,e),new Error(`Failed to load app from ${o}: ${e.message}`)}}async loadComponent(e,t){let o=t;o.startsWith("./")&&(o=o.substring(2)),o.endsWith(".js")||o.endsWith(".jsx")||(o+=".js");const s=`${e}/${o}`;console.log(`[WuLoader] π§© Loading component from: ${s}`);try{const e=await this.loadCode(s),o=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:{}},r=o(e=>(console.warn(`[WuLoader] Component ${t} requires ${e} - not supported yet`),{}),n,n.exports);return console.log(`[WuLoader] β
Component loaded: ${t}`),r}catch(e){throw console.error(`[WuLoader] β Failed to load component: ${t}`,e),new Error(`Failed to load component ${t}: ${e.message}`)}}async loadCode(e){if(this.cache.has(e))return this.cache.get(e);if(this.loadingPromises.has(e))return await this.loadingPromises.get(e);const t=this.fetchCode(e);this.loadingPromises.set(e,t);try{const o=await t;return this.loadingPromises.delete(e),this.cache.set(e,o),o}catch(t){throw this.loadingPromises.delete(e),t}}async fetchCode(e){const t=await fetch(e,{cache:"no-cache",headers:{Accept:"application/javascript, text/javascript, */*"}});if(!t.ok)throw new Error(`HTTP ${t.status}: ${t.statusText}`);const o=await t.text();if(!o.trim())throw new Error("Empty response");return o}async preload(e){console.log(`[WuLoader] π Preloading ${e.length} apps...`);const t=e.map(async e=>{try{await this.loadApp(e.url,e.manifest),console.log(`[WuLoader] β
Preloaded: ${e.name}`)}catch(t){console.warn(`[WuLoader] β οΈ Failed to preload ${e.name}:`,t.message)}});await Promise.allSettled(t),console.log("[WuLoader] π Preload completed")}async isAvailable(e){try{return(await fetch(e,{method:"HEAD"})).ok}catch{return!1}}async resolveDependencies(e,t){const o=new Map;for(const s of e||[]){const[e,n]=s.split(".");if(!e||!n){console.warn(`[WuLoader] Invalid import format: ${s}`);continue}const r=t.get(e);if(!r){console.warn(`[WuLoader] Import app not found: ${e}`);continue}const a=r.manifest,i=a?.wu?.exports?.[n];if(i)try{const e=await this.loadComponent(r.url,i);o.set(s,e),console.log(`[WuLoader] β
Resolved dependency: ${s}`)}catch(e){console.error(`[WuLoader] β Failed to resolve: ${s}`,e)}else console.warn(`[WuLoader] Export not found: ${s}`)}return o}clearCache(e){if(e){const t=new RegExp(e);for(const[e]of this.cache)t.test(e)&&(this.cache.delete(e),console.log(`[WuLoader] ποΈ Cleared cache for: ${e}`))}else this.cache.clear(),console.log("[WuLoader] ποΈ Cache cleared completely")}getStats(){return{cached:this.cache.size,loading:this.loadingPromises.size,cacheKeys:Array.from(this.cache.keys())}}}class WuStyleBridge{constructor(){this.sharedStyles=new Map,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},console.log("[WuStyleBridge] π¨ Style sharing system initialized")}registerFullyIsolatedApp(e,t){this.fullyIsolatedApps.set(e,t),console.log(`[WuStyleBridge] π‘οΈ Registered fully-isolated app: ${e} (${t})`)}isStyleFromFullyIsolatedApp(e){let t="";if("string"==typeof e?t=e:e&&"function"==typeof e.getAttribute?t=e.getAttribute("data-vite-dev-id")||e.href||"":e&&(e.href?t=e.href:e.viteId?t=e.viteId:e.element&&("function"==typeof e.element.getAttribute?t=e.element.getAttribute("data-vite-dev-id")||e.element.href||"":e.element.href&&(t=e.element.href))),!t||""===t.trim())return!1;const o=t.replace(/\\/g,"/").toLowerCase();for(const[e,t]of this.fullyIsolatedApps.entries()){const s=t.replace(/\\/g,"/").toLowerCase(),n=e.toLowerCase();if(s&&o.includes(s))return!0;if(new RegExp(`[/\\\\]${n}[/\\\\]`,"i").test(o))return!0}return!1}detectDocumentStyles(){const e=[];return document.querySelectorAll('link[rel="stylesheet"]').forEach(t=>{this.isStyleFromFullyIsolatedApp(t)||e.push({type:"link",href:t.href,element:t,library:this.extractLibraryName(t.href)})}),document.querySelectorAll("style").forEach((t,o)=>{if("true"===t.getAttribute("data-wu-shared"))return;const s=t.getAttribute("data-vite-dev-id"),n=t.textContent;this.isStyleFromFullyIsolatedApp(t)||s&&this.isStyleFromFullyIsolatedApp(s)?console.log(`[WuStyleBridge] π‘οΈ Filtered out style from fully-isolated app: ${s||"unknown"}`):n&&n.trim().length>0&&e.push({type:"inline",content:n,element:t,viteId:s,library:this.extractLibraryName(s||""),index:o})}),document.adoptedStyleSheets&&document.adoptedStyleSheets.length>0&&document.adoptedStyleSheets.forEach((t,o)=>{e.push({type:"adoptedStyleSheet",sheet:t,index:o})}),console.log(`[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 o=e.match(/\/node_modules\/(.+?)\/.*?\.css/);return o?o[1]:null}async injectStylesIntoShadow(e,t,o){if(!e)return console.warn("[WuStyleBridge] β οΈ No shadow root provided"),0;if("fully-isolated"===o)return console.log(`[WuStyleBridge] π‘οΈ Style mode "fully-isolated" for ${t}, skipping shared style injection`),0;if("isolated"===o)return console.log(`[WuStyleBridge] π Style mode "isolated" for ${t}, using native Shadow DOM encapsulation (no external styles)`),0;console.log(`[WuStyleBridge] π Style mode "shared" for ${t}, injecting all shared styles...`);const s=this.detectDocumentStyles();let n=0;for(const t of s)try{switch(t.type){case"link":await this.injectLinkStyle(e,t),n++;break;case"inline":this.injectInlineStyle(e,t),n++;break;case"adoptedStyleSheet":this.injectAdoptedStyleSheet(e,t),n++}}catch(e){console.warn("[WuStyleBridge] β οΈ Failed to inject style:",e)}return console.log(`[WuStyleBridge] β
Injected ${n} shared styles into ${t}`),n}async injectLinkStyle(e,t){if(e.querySelector(`link[href="${t.href}"]`))return void console.log(`[WuStyleBridge] βοΈ Style already exists: ${t.library||t.href}`);const o=document.createElement("link");o.rel="stylesheet",o.href=t.href,o.setAttribute("data-wu-shared","true"),o.setAttribute("data-wu-library",t.library||"unknown"),e.insertBefore(o,e.firstChild),console.log(`[WuStyleBridge] π Injected link: ${t.library||t.href}`)}injectInlineStyle(e,t){const o=t.viteId;if(o&&e.querySelector(`style[data-wu-vite-id="${o}"]`))return void console.log(`[WuStyleBridge] βοΈ Inline style already exists: ${o}`);const s=document.createElement("style");s.textContent=t.content,s.setAttribute("data-wu-shared","true"),s.setAttribute("data-wu-library",t.library||"unknown"),o&&s.setAttribute("data-wu-vite-id",o),e.insertBefore(s,e.firstChild),console.log(`[WuStyleBridge] π Injected inline style: ${t.library||o}`)}injectAdoptedStyleSheet(e,t){try{if(e.adoptedStyleSheets||(e.adoptedStyleSheets=[]),e.adoptedStyleSheets.includes(t.sheet))return void console.log("[WuStyleBridge] βοΈ Adopted stylesheet already exists");e.adoptedStyleSheets=[...e.adoptedStyleSheets,t.sheet],console.log("[WuStyleBridge] π Injected adopted stylesheet")}catch(e){console.warn("[WuStyleBridge] β οΈ Failed to inject adopted stylesheet:",e)}}observeStyleChanges(e){this.styleObserver&&this.styleObserver.disconnect(),this.styleObserver=new MutationObserver(t=>{let o=!1;for(const e of t)if("childList"===e.type&&Array.from(e.addedNodes).some(e=>"LINK"===e.tagName||"STYLE"===e.tagName)){o=!0;break}o&&e&&(console.log("[WuStyleBridge] π Style changes detected"),e())}),this.styleObserver.observe(document.head,{childList:!0,subtree:!0}),console.log("[WuStyleBridge] π Observing style changes")}configure(e){this.config={...this.config,...e},console.log("[WuStyleBridge] βοΈ Configuration updated:",this.config)}cleanup(){this.styleObserver&&(this.styleObserver.disconnect(),this.styleObserver=null),this.sharedStyles.clear(),console.log("[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 WuProxySandbox{constructor(e){this.appName=e,this.proxy=null,this.fakeWindow=Object.create(null),this.active=!1,this.modifiedKeys=new Set,console.log(`[WuProxySandbox] π‘οΈ Creating proxy sandbox for: ${e}`)}activate(){return this.active?(console.warn(`[WuProxySandbox] Sandbox already active for ${this.appName}`),this.proxy):(this.proxy=new Proxy(window,{get:(e,t)=>{if(t in this.fakeWindow)return this.fakeWindow[t];const o=e[t];return"function"!=typeof o||this.isConstructor(o)?o:o.bind(e)},set:(e,t,o)=>(this.fakeWindow[t]=o,this.modifiedKeys.add(t),console.log(`[WuProxySandbox] π ${this.appName} set: ${String(t)}`),!0),has:(e,t)=>t in this.fakeWindow||t in e,deleteProperty:(e,t)=>t in this.fakeWindow&&(delete this.fakeWindow[t],this.modifiedKeys.delete(t),!0)}),this.active=!0,console.log(`[WuProxySandbox] β
Proxy sandbox activated for ${this.appName}`),this.proxy)}deactivate(){this.active?(console.log(`[WuProxySandbox] π§Ή Deactivating sandbox for ${this.appName}`),this.fakeWindow=Object.create(null),this.modifiedKeys.clear(),this.proxy=null,this.active=!1,console.log(`[WuProxySandbox] β
Sandbox deactivated for ${this.appName}`)):console.warn(`[WuProxySandbox] Sandbox not active for ${this.appName}`)}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,modifiedKeys:Array.from(this.modifiedKeys),isolatedPropsCount:Object.keys(this.fakeWindow).length}}clearProperty(e){e in this.fakeWindow&&(delete this.fakeWindow[e],this.modifiedKeys.delete(e),console.log(`[WuProxySandbox] ποΈ Cleared property: ${String(e)}`))}getIsolatedProperties(){return{...this.fakeWindow}}}class WuSnapshotSandbox{constructor(e){this.appName=e,this.proxy=window,this.snapshot=new Map,this.modifiedKeys=new Set,this.active=!1,console.log(`[WuSnapshotSandbox] πΈ Creating snapshot sandbox for: ${e}`)}activate(){if(this.active)return console.warn(`[WuSnapshotSandbox] Sandbox already active for ${this.appName}`),this.proxy;console.log(`[WuSnapshotSandbox] πΈ Taking window snapshot for ${this.appName}...`),this.snapshot.clear(),this.modifiedKeys.clear();for(const e in window)try{this.snapshot.set(e,window[e])}catch(t){console.warn(`[WuSnapshotSandbox] β οΈ Could not snapshot property: ${e}`)}return this.active=!0,console.log(`[WuSnapshotSandbox] β
Snapshot captured with ${this.snapshot.size} properties`),this.proxy}deactivate(){if(!this.active)return void console.warn(`[WuSnapshotSandbox] Sandbox not active for ${this.appName}`);console.log(`[WuSnapshotSandbox] π Restoring window snapshot for ${this.appName}...`);let e=0,t=0;for(const o in window)try{const s=window[o],n=this.snapshot.get(o);if(s!==n)if(this.snapshot.has(o))window[o]=n,e++;else try{delete window[o],t++}catch(e){console.warn(`[WuSnapshotSandbox] β οΈ Could not delete: ${o}`)}}catch(e){console.warn(`[WuSnapshotSandbox] β οΈ Could not restore property: ${o}`)}this.snapshot.clear(),this.modifiedKeys.clear(),this.active=!1,console.log(`[WuSnapshotSandbox] β
Snapshot restored - ${e} restored, ${t} deleted`)}getProxy(){return this.active?this.proxy:null}isActive(){return this.active}getStats(){const e=[];if(this.active)for(const t in window)try{window[t]!==this.snapshot.get(t)&&e.push(t)}catch(e){}return{appName:this.appName,active:this.active,snapshotSize:this.snapshot.size,modifiedProperties:e,modifiedCount:e.length}}isPropertyModified(e){if(!this.active)return!1;try{return window[e]!==this.snapshot.get(e)}catch{return!1}}getModifiedProperties(){const e={};if(this.active)for(const t in window)try{this.isPropertyModified(t)&&(e[t]={original:this.snapshot.get(t),current:window[t]})}catch(e){}return e}}class WuScriptExecutor{constructor(){console.log("[WuScriptExecutor] π Script execution system initialized")}executeWithFunction(e,t,o){console.log(`[WuScriptExecutor] π Executing script for ${t} using Function`);try{window.__WU_PROXY_TEMP__=o;const s=new Function(`\n return ((window) => {\n ${e}\n return window['${t}'];\n })(window.__WU_PROXY_TEMP__);\n `)();return delete window.__WU_PROXY_TEMP__,console.log(`[WuScriptExecutor] β
Script executed successfully for ${t}`),s}catch(e){throw delete window.__WU_PROXY_TEMP__,console.error(`[WuScriptExecutor] β Script execution failed for ${t}:`,e),e}}executeWithEval(script,appName,globalProxy){console.log(`[WuScriptExecutor] π Executing script for ${appName} using eval`);try{window.__WU_PROXY_TEMP__=globalProxy;const scriptText=`\n ((window) => {\n ${script}\n return window['${appName}'];\n })(window.__WU_PROXY_TEMP__);\n `,result=eval(scriptText);return delete window.__WU_PROXY_TEMP__,console.log(`[WuScriptExecutor] β
Script executed successfully for ${appName}`),result}catch(e){throw delete window.__WU_PROXY_TEMP__,console.error(`[WuScriptExecutor] β Script execution failed for ${appName}:`,e),e}}execute(e,t,o,s="function"){if("eval"===s)return this.executeWithEval(e,t,o);if("function"===s||"auto"===s)try{return this.executeWithFunction(e,t,o)}catch(n){if("auto"===s)return console.warn("[WuScriptExecutor] β οΈ Function failed, falling back to eval"),this.executeWithEval(e,t,o);throw n}throw new Error(`Unknown execution strategy: ${s}`)}async executeMultiple(e,t,o,s="function"){console.log(`[WuScriptExecutor] π Executing ${e.length} scripts for ${t}`);const n=[];for(let r=0;r<e.length;r++){const a=e[r];console.log(`[WuScriptExecutor] π Executing script ${r+1}/${e.length}`);try{const e=this.execute(a,t,o,s);n.push({success:!0,result:e})}catch(e){console.error(`[WuScriptExecutor] β Script ${r+1} failed:`,e),n.push({success:!1,error:e})}}const r=n.filter(e=>e.success).length;return console.log(`[WuScriptExecutor] β
Executed ${r}/${e.length} scripts successfully`),n}validateScript(e){if(!e||"string"!=typeof e)return!1;if(0===e.trim().length)return!1;const t=[/__proto__/,/constructor.*prototype/,/document\.write/,/eval\(/,/new\s+Function\(/];for(const o of t)o.test(e)&&console.warn("[WuScriptExecutor] β οΈ Potentially dangerous code detected");return!0}getStats(){return{executor:"WuScriptExecutor",capabilities:["function","eval","auto"],defaultStrategy:"function",validation:!0}}}function executeScript(e,t,o,s="function"){return(new WuScriptExecutor).execute(e,t,o,s)}async function executeScripts(e,t,o,s="function"){const n=new WuScriptExecutor;return await n.executeMultiple(e,t,o,s)}class WuHtmlParser{constructor(){this.cache=new Map,console.log("[WuHtmlParser] π HTML parsing system initialized")}parse(e,t,o){console.log(`[WuHtmlParser] π Parsing HTML for ${t}`);const s=`${t}:${e.length}`;if(this.cache.has(s))return console.log(`[WuHtmlParser] β‘ Cache hit for ${t}`),this.cache.get(s);try{const n=document.createElement("div");n.innerHTML=e;const r=[],a=[],i=[],l=[];this.deepParse(n,{inlineScripts:r,externalScripts:a,inlineStyles:i,externalStyles:l,baseUrl:o,appName:t});const c={dom:n.innerHTML,scripts:{inline:r,external:a,all:[...r,...a]},styles:{inline:i,external:l,all:[...i,...l]}};return this.cache.set(s,c),console.log(`[WuHtmlParser] β
Parsed ${t}: ${r.length} inline scripts, ${a.length} external scripts`),c}catch(e){throw console.error(`[WuHtmlParser] β Failed to parse HTML for ${t}:`,e),e}}deepParse(e,t){const{inlineScripts:o,externalScripts:s,inlineStyles:n,externalStyles:r,baseUrl:a,appName:i}=t,l=Array.from(e.children);for(const e of l){const l=e.nodeName.toLowerCase();if("script"===l){this.parseScriptTag(e,o,s,a,i);const t=document.createComment(`Wu: script removed from ${i}`);e.parentElement?.replaceChild(t,e);continue}if("style"===l){const t=e.textContent||"";t.trim()&&(n.push(t),console.log(`[WuHtmlParser] π¨ Extracted inline style (${t.length} chars)`));const o=document.createComment(`Wu: style removed from ${i}`);e.parentElement?.replaceChild(o,e);continue}if("link"===l){const t=e.getAttribute("rel"),o=e.getAttribute("href");if("stylesheet"===t&&o){const t=this.resolveUrl(o,a);r.push(t),console.log(`[WuHtmlParser] π Extracted external style: ${t}`);const s=document.createComment(`Wu: link removed from ${i}`);e.parentElement?.replaceChild(s,e);continue}}e.children.length>0&&this.deepParse(e,t)}}parseScriptTag(e,t,o,s,n){const r=e.getAttribute("src");if("module"!==(e.getAttribute("type")||"text/javascript"))if(r){const e=this.resolveUrl(r,s);o.push(e),console.log(`[WuHtmlParser] π Extracted external script: ${e}`)}else{const o=e.textContent||"";o.trim()&&(t.push(o),console.log(`[WuHtmlParser] π Extracted inline script (${o.length} chars)`))}else console.log(`[WuHtmlParser] βοΈ Skipping module script for ${n}`)}resolveUrl(e,t){if(e.startsWith("http://")||e.startsWith("https://")||e.startsWith("//"))return e.startsWith("//")?`https:${e}`:e;const o=t.endsWith("/")?t:`${t}/`;if(e.startsWith("/")){const o=new URL(t);return`${o.protocol}//${o.host}${e}`}return`${o}${e}`}async fetchHtml(e,t){console.log(`[WuHtmlParser] π Fetching HTML for ${t} from ${e}`);try{const t=await fetch(e,{method:"GET",cache:"no-cache",headers:{Accept:"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"}});if(!t.ok)throw new Error(`HTTP ${t.status}: ${t.statusText}`);const o=await t.text();if(!o||0===o.trim().length)throw new Error("Empty HTML response");return console.log(`[WuHtmlParser] β
Fetched HTML (${o.length} chars)`),o}catch(t){throw console.error(`[WuHtmlParser] β Failed to fetch HTML from ${e}:`,t),t}}async parseFromUrl(e,t){const o=await this.fetchHtml(e,t);return this.parse(o,t,e)}clearCache(e){if(e){const t=new RegExp(e);for(const[e]of this.cache)t.test(e)&&(this.cache.delete(e),console.log(`[WuHtmlParser] ποΈ Cleared cache for: ${e}`))}else this.cache.clear(),console.log("[WuHtmlParser] ποΈ Cache cleared completely")}getStats(){return{cacheSize:this.cache.size,cacheKeys:Array.from(this.cache.keys())}}}function parseHtml(e,t,o){return(new WuHtmlParser).parse(e,t,o)}async function parseHtmlFromUrl(e,t){const o=new WuHtmlParser;return await o.parseFromUrl(e,t)}class WuSandbox{constructor(){this.sandboxes=new Map,this.globalState=new Map,this.styleBridge=new WuStyleBridge,this.jsSandboxes=new Map,this.scriptExecutor=new WuScriptExecutor,this.htmlParser=new WuHtmlParser,this.sandboxStrategy=this.detectSandboxStrategy(),console.log(`[WuSandbox] π‘οΈ Advanced isolation system initialized (strategy: ${this.sandboxStrategy})`)}detectSandboxStrategy(){if("undefined"!=typeof Proxy)try{return new Proxy({},{get:(e,t)=>e[t]}).test="value",console.log("[WuSandbox] β
Proxy available - using ProxySandbox strategy"),"proxy"}catch(e){return console.warn("[WuSandbox] β οΈ Proxy not working - falling back to SnapshotSandbox"),"snapshot"}return console.warn("[WuSandbox] β οΈ Proxy not available - using SnapshotSandbox strategy"),"snapshot"}create(e,t,o={}){console.log(`[WuSandbox] π¨ Creating sandbox for: ${e}`);try{if(!t.attachShadow)throw new Error("Shadow DOM not supported in this browser");let s;t.shadowRoot?(console.log("[WuSandbox] π Existing shadow root detected, performing cleanup..."),t.shadowRoot.innerHTML="",s=t.shadowRoot,console.log("[WuSandbox] β¨ Existing shadow root cleaned and reused")):(s=t.attachShadow({mode:"open",delegatesFocus:!0}),console.log("[WuSandbox] π New shadow root created"));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 r=document.createElement("style");r.textContent=this.generateSandboxStyles(e),s.appendChild(r),s.appendChild(n);const a=this.createJSScope(e),i=this.createAdvancedJSSandbox(e),l=i.activate(),c=o.styleMode||o.manifest?.styleMode,u={appName:e,shadowRoot:s,container:n,hostContainer:t,jsScope:a,jsSandbox:i,jsProxy:l,styles:r,styleMode:c,manifest:o.manifest,created:Date.now(),sandbox_state:"stable",recovery_count:0};if("isolated"===c)console.log(`[WuSandbox] π Style mode "isolated" for ${e}, using native Shadow DOM encapsulation`),u.stylesReady=Promise.resolve(0);else if("fully-isolated"===c){console.log(`[WuSandbox] π‘οΈ Style mode "fully-isolated" detected for ${e}, using enhanced style injection`);const t=o.appUrl||(o.manifest?.name?`/${o.manifest.name}/`:`/${e}/`);this.styleBridge.registerFullyIsolatedApp(e,t),u.appUrl=t;const n=this;u.stylesReady=new Promise(o=>{let r=!1;const a=async()=>{const a=await n.injectOwnStylesToShadow(s,e,t);return a>0&&(console.log(`[WuSandbox] π¨ Injected ${a} own styles for ${e} (fully-isolated)`),r||(r=!0,o(a))),a};console.log(`[WuSandbox] π Setting up style observer for ${e} (fully-isolated)`);const i=new MutationObserver(t=>{let o=0;for(const s of t)if("childList"===s.type)for(const t of s.addedNodes)if("STYLE"===t.nodeName||"LINK"===t.nodeName){o++;const s=t.getAttribute?t.getAttribute("data-vite-dev-id"):null;s&&s.toLowerCase().includes(e.toLowerCase())&&console.log(`[WuSandbox] π New ${e} style detected: ${s.split("/").pop()}`)}o>0&&(console.log(`[WuSandbox] π ${o} new styles detected in head, checking for ${e}...`),a())});i.observe(document.head,{childList:!0,subtree:!0}),u.styleObserver=i,setTimeout(async()=>{await a(),r||setTimeout(()=>{if(!r){console.warn(`[WuSandbox] β οΈ No own styles found for ${e} after timeout, using FALLBACK`);const t=n.injectAllStylesToShadow(s,e);console.log(`[WuSandbox] π¨ FALLBACK: Injected ${t} styles for ${e}`),r=!0,o(t)}},3e3)},50)})}else console.log(`[WuSandbox] π Style mode "shared" for ${e}, injecting all shared styles...`),u.stylesReady=this.styleBridge.injectStylesIntoShadow(s,e,c).then(t=>(console.log(`[WuSandbox] π¨ Shared ${t} styles with ${e}`),this.styleBridge.observeStyleChanges(()=>{console.log(`[WuSandbox] π Reinjecting styles for ${e} due to changes`),this.styleBridge.injectStylesIntoShadow(s,e,c).catch(e=>{console.warn("[WuSandbox] β οΈ Failed to reinject styles:",e)})}),t)).catch(e=>(console.warn("[WuSandbox] β οΈ Failed to inject styles:",e),0));return this.sandboxes.set(e,u),console.log(`[WuSandbox] β
Enhanced sandbox created for ${e}`),u}catch(o){if(console.error(`[WuSandbox] β Failed to create sandbox for ${e}:`,o),o.message.includes("Shadow root cannot be created"))return this.createFallbackSandbox(e,t);throw o}}createFallbackSandbox(e,t){console.log(`[WuSandbox] π§ Creating fallback sandbox for ${e}...`);try{t.shadowRoot&&(t.shadowRoot.innerHTML="");const o=document.createElement("div");o.id=`wu-app-${e}`,o.className="wu-app-root wu-fallback",o.style.cssText="\n width: 100%;\n height: 100%;\n isolation: isolate;\n contain: layout style paint;\n ",t.innerHTML="",t.appendChild(o);const s={appName:e,shadowRoot:null,container:o,hostContainer:t,jsScope:this.createJSScope(e),styles:null,created:Date.now(),sandbox_state:"fallback_mode",recovery_count:1,fallback_mode:!0};return this.sandboxes.set(e,s),console.log(`[WuSandbox] β¨ Fallback sandbox created successfully for ${e}`),s}catch(e){throw console.error("[WuSandbox] π₯ Fallback sandbox creation failed:",e),e}}generateSandboxStyles(e){return`\n /* Wu Framework - Shadow DOM Isolation Styles */\n :host {\n display: block;\n width: 100%;\n height: 100%;\n box-sizing: border-box;\n contain: layout style paint;\n --wu-sandbox-active: true;\n --wu-isolation-state: stable;\n }\n\n .wu-app-root {\n width: 100%;\n height: 100%;\n box-sizing: border-box;\n isolation: isolate;\n position: relative;\n overflow: hidden;\n }\n\n /* Loading animation for sandbox initialization */\n .wu-app-root[data-wu-loading="true"] {\n background: linear-gradient(45deg,\n rgba(74, 144, 226, 0.1) 0%,\n rgba(80, 227, 194, 0.1) 100%);\n animation: sandboxPulse 2s ease-in-out infinite;\n }\n\n @keyframes sandboxPulse {\n 0%, 100% { opacity: 0.8; }\n 50% { opacity: 1; }\n }\n\n /* CSS reset for shadow DOM stability */\n * {\n box-sizing: border-box;\n }\n\n /* CSS custom properties for sandbox */\n :host {\n --wu-app-name: "${e}";\n --wu-isolation: true;\n --wu-creation-timestamp: ${Date.now()};\n }\n\n /* π‘οΈ Debug mode enhancements */\n :host([wu-debug]) {\n border: 2px dashed #4a90e2;\n background: rgba(74, 144, 226, 0.05);\n box-shadow: 0 0 10px rgba(74, 144, 226, 0.3);\n }\n\n :host([wu-debug])::before {\n content: "Wu Framework: " attr(wu-app);\n position: absolute;\n top: 0;\n left: 0;\n background: linear-gradient(45deg, #4a90e2, #50e3c2);\n color: white;\n padding: 4px 8px;\n font-size: 11px;\n font-family: 'SF Mono', Monaco, 'Cascadia Code', 'Roboto Mono', Consolas, 'Courier New', monospace;\n z-index: 10000;\n border-radius: 0 0 4px 0;\n font-weight: 600;\n }\n\n /* Sandbox state indicators */\n :host([data-sandbox-state="stable"]) {\n --wu-isolation-state: stable;\n }\n\n :host([data-sandbox-state="healing"]) {\n --wu-dimensional-stability: healing;\n animation: sandboxHealing 1s ease-in-out infinite;\n }\n\n @keyframes sandboxHealing {\n 0%, 100% { filter: hue-rotate(0deg); }\n 50% { filter: hue-rotate(180deg); }\n }\n `}createAdvancedJSSandbox(e){let t;return"proxy"===this.sandboxStrategy?(t=new WuProxySandbox(e),console.log(`[WuSandbox] π‘οΈ Created ProxySandbox for ${e}`)):(t=new WuSnapshotSandbox(e),console.log(`[WuSandbox] πΈ Created SnapshotSandbox for ${e}`)),this.jsSandboxes.set(e,t),t}executeScript(e,t,o="function"){const s=this.sandboxes.get(t);if(!s||!s.jsProxy)throw new Error(`Sandbox not found for ${t}`);return console.log(`[WuSandbox] π Executing script for ${t}`),this.scriptExecutor.execute(e,t,s.jsProxy,o)}parseHtml(e,t,o){return console.log(`[WuSandbox] π Parsing HTML for ${t}`),this.htmlParser.parse(e,t,o)}async parseHtmlFromUrl(e,t){return console.log(`[WuSandbox] π Parsing HTML from URL for ${t}`),await this.htmlParser.parseFromUrl(e,t)}getBaseStyles(e){return`\n /* Wu Framework - Shadow DOM Base Styles */\n :host {\n display: block;\n width: 100%;\n height: 100%;\n box-sizing: border-box;\n contain: layout style paint;\n }\n\n .wu-app-root {\n width: 100%;\n height: 100%;\n box-sizing: border-box;\n isolation: isolate;\n }\n\n /* Reset bΓ‘sico para evitar conflictos */\n * {\n box-sizing: border-box;\n }\n\n /* Variables CSS aisladas para la app */\n :host {\n --wu-app-name: "${e}";\n --wu-isolation: true;\n }\n\n /* Prevenir scroll del host cuando no es necesario */\n :host([wu-no-scroll]) {\n overflow: hidden;\n }\n\n /* Estilos para debugging en desarrollo */\n :host([wu-debug]) {\n border: 2px dashed #ff6b6b;\n background: rgba(255, 107, 107, 0.1);\n }\n\n :host([wu-debug])::before {\n content: "Wu App: " attr(wu-app);\n position: absolute;\n top: 0;\n left: 0;\n background: #ff6b6b;\n color: white;\n padding: 2px 6px;\n font-size: 10px;\n font-family: monospace;\n z-index: 10000;\n }\n `}createJSScope(e){const t=Object.create(null);return new Proxy(window,{set(o,s,n){return this.isAppSpecific(s)?(t[s]=n,console.log(`[WuSandbox] π App ${e} set isolated global: ${String(s)}`),!0):this.isSafeGlobal(s)?(o[s]=n,!0):(t[s]=n,!0)},get:(e,o)=>o in t?t[o]:e[o],has:(e,o)=>o in t||o in e,ownKeys:e=>[...Object.keys(t),...Object.keys(e)],isAppSpecific:e=>[/^app[A-Z]/,/^[a-z]+App$/,/^__[a-zA-Z]/,/^_[A-Z]/].some(t=>t.test(String(e))),isSafeGlobal:e=>new Set(["console","setTimeout","setInterval","clearTimeout","clearInterval","fetch","URL","URLSearchParams","FormData","Blob","Date","Math","JSON","Promise","Array","Object","String","Number"]).has(String(e))})}addStyles(e,t){const o=this.sandboxes.get(e);if(!o)return void console.warn(`[WuSandbox] Sandbox not found for: ${e}`);const s=document.createElement("style");s.textContent=t,s.setAttribute("wu-custom-styles",""),o.shadowRoot.appendChild(s),console.log(`[WuSandbox] π¨ Custom styles added to ${e}`)}loadExternalStyles(e,t){const o=this.sandboxes.get(e);if(!o)return void console.warn(`[WuSandbox] Sandbox not found for: ${e}`);const s=document.createElement("link");s.rel="stylesheet",s.href=t,s.setAttribute("wu-external-styles",""),o.shadowRoot.appendChild(s),console.log(`[WuSandbox] π External styles loaded in ${e}: ${t}`)}setDebugMode(e,t=!0){const o=this.sandboxes.get(e);o?(t?(o.hostContainer.setAttribute("wu-debug",""),o.hostContainer.setAttribute("wu-app",e)):(o.hostContainer.removeAttribute("wu-debug"),o.hostContainer.removeAttribute("wu-app")),console.log(`[WuSandbox] π Debug mode ${t?"enabled":"disabled"} for ${e}`)):console.warn(`[WuSandbox] Sandbox not found for: ${e}`)}cleanup(e){if(!e)return;const{appName:t,shadowRoot:o,hostContainer:s,jsSandbox:n}=e;console.log(`[WuSandbox] π§Ή Cleaning up sandbox for: ${t}`);try{n&&n.isActive()&&(n.deactivate(),console.log(`[WuSandbox] π‘οΈ JS Sandbox deactivated for ${t}`)),this.cleanupEventListeners(e),o&&(o.innerHTML=""),s&&(s.removeAttribute("wu-debug"),s.removeAttribute("wu-app"),s.removeAttribute("wu-no-scroll")),this.sandboxes.delete(t),this.jsSandboxes.delete(t),console.log(`[WuSandbox] β
Sandbox cleaned up: ${t}`)}catch(e){console.error(`[WuSandbox] β Error cleaning up sandbox ${t}:`,e)}}cleanupEventListeners(e){const{shadowRoot:t}=e;t&&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()),htmlCacheSize:this.htmlParser.getStats().cacheSize,scriptExecutor:this.scriptExecutor.getStats(),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(){console.log(`[WuSandbox] π§Ή Cleaning up all ${this.sandboxes.size} sandboxes...`);for(const[e,t]of this.sandboxes)this.cleanup(t);this.globalState.clear(),this.styleBridge&&this.styleBridge.cleanup(),console.log("[WuSandbox] β
All sandboxes cleaned up")}configureStyleSharing(e){this.styleBridge&&(this.styleBridge.configure(e),console.log("[WuSandbox] π¨ StyleBridge configured"))}getStyleStats(){return this.styleBridge?this.styleBridge.getStats():null}async reinjectStyles(e){const t=this.sandboxes.get(e);if(!t||!t.shadowRoot)return void console.warn(`[WuSandbox] Cannot reinject styles for ${e}`);const o=t.styleMode;if("isolated"===o)return void console.log(`[WuSandbox] π Skipping reinject for ${e} (isolated mode - app manages own styles)`);if("fully-isolated"===o){console.log(`[WuSandbox] π Reinjecting OWN styles for ${e} (fully-isolated)...`);const o=t.appUrl||t.manifest?.name?`/${t.manifest.name}/`:`/${e}/`,s=await this.injectOwnStylesToShadow(t.shadowRoot,e,o);return void console.log(`[WuSandbox] β
Reinjected ${s} own styles for ${e}`)}console.log(`[WuSandbox] π Reinjecting shared styles for ${e}...`);const s=await this.styleBridge.injectStylesIntoShadow(t.shadowRoot,e,o);console.log(`[WuSandbox] β
Reinjected ${s} shared styles`)}async injectOwnStylesToShadow(e,t,o){if(!e)return 0;let s=0;const n=document.querySelectorAll("style"),r=t.toLowerCase(),a=[new RegExp(`packages[/\\\\]${r}[/\\\\]src[/\\\\]`,"i")];console.log(`[WuSandbox] π Searching own styles for ${t}, found ${n.length} style tags in head`);let i=0;for(const e of n)(e.getAttribute("data-vite-dev-id")||"").toLowerCase().includes(r)&&i++;i>0&&console.log(`[WuSandbox] π Found ${i} styles potentially matching ${t}`);for(const o of n){const n=o.getAttribute("data-vite-dev-id")||"",r=n.replace(/\\/g,"/").toLowerCase();let i=!1;if(n)for(const e of a)if(e instanceof RegExp){if(e.test(n)){i=!0;break}}else if(r.includes(e.toLowerCase())){i=!0;break}if(i&&!e.querySelector(`style[data-vite-dev-id="${n}"]`)){const r=o.cloneNode(!0);r.setAttribute("data-wu-injected","true"),e.insertBefore(r,e.firstChild),s++;const a=n.substring(n.lastIndexOf("/")+1)||n.substring(n.lastIndexOf("\\")+1);console.log(`[WuSandbox] β
Injected own style for ${t}: ${a}`)}}return console.log(`[WuSandbox] π¨ Total own styles injected for ${t}: ${s}`),s}injectAllStylesToShadow(e,t){if(!e)return 0;let o=0;const s=t.toLowerCase(),n=document.querySelectorAll("style");for(const t of n){const n=t.getAttribute("data-vite-dev-id")||"";if(!n.toLowerCase().includes(s))continue;if(e.querySelector(`style[data-vite-dev-id="${n}"]`))continue;const r=t.cloneNode(!0);r.setAttribute("data-wu-fallback","true"),e.insertBefore(r,e.firstChild),o++;const a=n.split("/").pop()||n.split("\\").pop();console.log(`[WuSandbox] π¦ FALLBACK injected: ${a}`)}return console.log(`[WuSandbox] π¨ FALLBACK: Total ${o} styles injected for ${t}`),o}}class WuManifest{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 t=`${e}/wu.json`;console.log(`[WuManifest] π₯ Loading manifest: ${t}`);try{if(this.cache.has(t))return console.log(`[WuManifest] β‘ Cache hit: ${t}`),this.cache.get(t);const o=await fetch(t,{cache:"no-cache",headers:{Accept:"application/json"}});if(!o.ok){if(404===o.status)return console.log(`[WuManifest] π No manifest found, creating default for: ${e}`),this.createDefaultManifest(e);throw new Error(`HTTP ${o.status}: ${o.statusText}`)}const s=await o.text();if(s.length>this.security.maxManifestSize)throw new Error(`Manifest too large (${s.length} bytes, max ${this.security.maxManifestSize})`);let n;try{n=JSON.parse(s)}catch(e){throw new Error(`Invalid JSON in manifest: ${e.message}`)}const r=this.validate(n);return this.cache.set(t,r),console.log(`[WuManifest] β
Manifest loaded: ${n.name}`),r}catch(o){console.error(`[WuManifest] β Failed to load manifest: ${t}`,o);try{return this.createDefaultManifest(e)}catch(e){throw new Error(`Failed to load manifest from ${t}: ${o.message}`)}}}createDefaultManifest(e){const t=this.extractAppNameFromUrl(e),o={name:t,entry:"index.js",wu:{exports:{},imports:[],routes:[],permissions:[]}};return console.log(`[WuManifest] π§ Created default manifest for: ${t}`),o}extractAppNameFromUrl(e){try{const t=new URL(e).pathname.split("/").filter(Boolean);return t[t.length-1]||"unknown-app"}catch{return e.replace(/[^a-zA-Z0-9-]/g,"")||"unknown-app"}}_sanitizeString(e){return"string"!=typeof e?"":e.replace(/[<>'"]/g,"").replace(/[\x00-\x1F\x7F]/g,"").trim()}_hasDangerousPatterns(e){return"string"==typeof e&&this.security.dangerousPatterns.some(t=>t.test(e))}_isUrlSafe(e){if("string"!=typeof e)return!1;if(this._hasDangerousPatterns(e))return!1;try{const t=new URL(e,"http://localhost");if(this.security.blockedDomains.some(e=>t.hostname.includes(e)))return!1}catch{if(this._hasDangerousPatterns(e))return!1}return!0}validate(e){const t=this.schemas.get("wu.json");if(!e||"object"!=typeof e||Array.isArray(e))throw new Error("Manifest must be a valid object");for(const o of t.required)if(!e[o])throw new Error(`Required field missing: ${o}`);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,o]of Object.entries(t.exports))if(!this._isUrlSafe(o))throw new Error(`Dangerous export path: ${e}`);if(t.imports&&!Array.isArray(t.imports))throw new Error("wu.imports must be an array");if(t.imports&&t.imports.length>this.security.maxImports)throw new Error(`Too many imports (max ${this.security.maxImports})`);if(t.routes&&!Array.isArray(t.routes))throw new Error("wu.routes must be an array");if(t.routes&&t.routes.length>this.security.maxRoutes)throw new Error(`Too many routes (max ${this.security.maxRoutes})`);if(t.permissions&&!Array.isArray(t.permissions))throw new Error("wu.permissions must be an array")}return this.normalize(e)}normalize(e){const t={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&&(t.styleMode=e.styleMode),e.version&&(t.version=e.version),e.folder&&(t.folder=e.folder),t.wu.exports){const e={};for(const[o,s]of Object.entries(t.wu.exports))e[o]=this.normalizeComponentPath(s);t.wu.exports=e}return t.wu.imports=t.wu.imports.filter(e=>!("string"!=typeof e||!e.includes("."))||(console.warn(`[WuManifest] Invalid import format: ${e}`),!1)),t}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 o={valid:[],invalid:[],missing:[]};for(const s of e){const[e,n]=s.split(".");if(!e||!n){o.invalid.push({import:s,reason:'Invalid format. Use "app.component"'});continue}const r=t.get(e);if(!r){o.missing.push({import:s,app:e,reason:"App not registered"});continue}const a=r.manifest,i=a?.wu?.exports?.[n];i?o.valid.push({import:s,app:e,component:n,path:i}):o.invalid.push({import:s,reason:`Component ${n} not exported by ${e}`})}return o}create(e,t={}){const o={name:e,entry:t.entry||"index.js",wu:{exports:t.exports||{},imports:t.imports||[],routes:t.routes||[],permissions:t.permissions||[]}};return this.normalize(o)}clearCache(e){if(e){const t=new RegExp(e);for(const[e]of this.cache)t.test(e)&&(this.cache.delete(e),console.log(`[WuManifest] ποΈ Cleared cache for: ${e}`))}else this.cache.clear(),console.log("[WuManifest] ποΈ Manifest cache cleared completely")}getStats(){return{cached:this.cache.size,schemas:this.schemas.size,cacheKeys:Array.from(this.cache.keys())}}}class WuLogger{constructor(){this.isDevelopment=this.detectEnvironment(),this.logLevel=this.isDevelopment?"warn":"error",this.levels={debug:0,info:1,warn:2,error:3,silent:4}}detectEnvironment(){return"localhost"===window.location.hostname||"127.0.0.1"===window.location.hostname||""!==window.location.port||"undefined"!=typeof process&&"development"===process.env?.NODE_ENV||new URLSearchParams(window.location.search).has("wu-debug")||!0===window.WU_DEBUG}setLevel(e){return this.logLevel=e,this}setDevelopment(e){return this.isDevelopment=e,this.logLevel=e?"debug":"error",this}shouldLog(e){return this.levels[e]>=this.levels[this.logLevel]}debug(...e){this.shouldLog("debug")&&console.log(...e)}info(...e){this.shouldLog("info")&&console.info(...e)}warn(...e){this.shouldLog("warn")&&console.warn(...e)}error(...e){this.shouldLog("error")&&console.error(...e)}wu(e,...t){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 logger=new WuLogger;function silenceAllLogs(){logger.setLevel("silent")}function enableAllLogs(){logger.setLevel("debug")}var wuLogger=Object.freeze({__proto__:null,WuLogger:WuLogger,enableAllLogs:enableAllLogs,logger:logger,silenceAllLogs:silenceAllLogs});class WuStore{constructor(e=256){this.bufferSize=this.nextPowerOfTwo(e),this.mask=this.bufferSize-1,this.buffer=new Array(this.bufferSize),this.cursor=0,this.state={},this.listeners=new Map,this.patternListeners=new Map,this.metrics={reads:0,writes:0,notifications:0};for(let e=0;e<this.bufferSize;e++)this.buffer[e]={path:null,value:null,timestamp:0}}get(e){return this.metrics.reads++,e?e.split(".").reduce((e,t)=>e?.[t],this.state):this.state}set(e,t){this.metrics.writes++;const o=this.cursor++,s=o&this.mask,n=this.buffer[s];return n.path=e,n.value=t,n.timestamp=performance.now(),this.updateState(e,t),queueMicrotask(()=>{this.notify(e,t),this.notifyPatterns(e,t)}),o}on(e,t){return e.includes("*")?(this.patternListeners.has(e)||this.patternListeners.set(e,new Set),this.patternListeners.get(e).add(t),()=>{const o=this.patternListeners.get(e);o&&(o.delete(t),0===o.size&&this.patternListeners.delete(e))}):(this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t),()=>{const o=this.listeners.get(e);o&&(o.delete(t),0===o.size&&this.listeners.delete(e))})}batch(e){const t=[];for(const[o,s]of Object.entries(e))t.push(this.set(o,s));return t}getMetrics(){return{...this.metrics,bufferUtilization:this.cursor%this.bufferSize/this.bufferSize,listenerCount:this.listeners.size+this.patternListeners.size}}nextPowerOfTwo(e){return Math.pow(2,Math.ceil(Math.log2(e)))}updateState(e,t){if(!e)return void(this.state=t);const o=e.split("."),s=o.pop();let n=this.state;for(const e of o)e in n&&"object"==typeof n[e]||(n[e]={}),n=n[e];n[s]=t}notify(e,t){this.metrics.notifications++;const o=this.listeners.get(e);o&&o.forEach(o=>{try{o(t,e)}catch(e){console.error("[WuStore] Listener error:",e)}});const s=e.split(".");for(let e=s.length-1;e>0;e--){const t=s.slice(0,e).join("."),o=this.listeners.get(t);if(o){const e=this.get(t);o.forEach(o=>{try{o(e,t)}catch(e){console.error("[WuStore] Parent listener error:",e)}})}}}notifyPatterns(e,t){for(const[o,s]of this.patternListeners)this.matchesPattern(e,o)&&s.forEach(o=>{try{o({path:e,value:t})}catch(e){console.error("[WuStore] Pattern listener error:",e)}})}matchesPattern(e,t){if("*"===t)return!0;const o=t.split(".").map(e=>"*"===e?"[^.]+":e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("\\.");return new RegExp(`^${o}$`).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 o=Math.max(0,this.cursor-e);o<this.cursor&&t.length<e;o++){const e=o&this.mask,s=this.buffer[e];s.path&&t.push({path:s.path,value:s.value,timestamp:s.timestamp})}return t.reverse()}}const store=new WuStore;class WuApp{constructor(e,t,o){this.name=e,this.url=t.url,this.container=t.container,this._wu=o,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,status:"registered"}),console.log(`π¦ 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.initialized||await this._wu.init({apps:[{name:this.name,url:this.url}]}),await this._wu.mount(this.name,t),this._mounted=!0,this}async unmount(){return this._mounted?(await this._wu.unmount(this.name),this._mounted=!1,this):(console.warn(`β οΈ App ${this.name} is not mounted`),this)}async remount(e){return await this.unmount(),await this.mount(e),this}get isMounted(){return this._mounted&&this._wu.mounted?.has(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 console.log(`π 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(),console.log(`β
App reloaded: ${this.name}`),this}async verify(){const e=document.querySelector(this.container),t=null!==e?.shadowRoot,o=(e?.shadowRoot?.children?.length||0)>0;return{name:this.name,mounted:this.isMounted,container:{found:!!e,selector:this.container,hasShadowDOM:t,hasContent:o},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(),this._wu.apps.delete(this.name),this._mounted=!1,console.log(`ποΈ App destroyed: ${this.name}`)}}class WuCache{constructor(e={}){this.config={maxSize:e.maxSize||50,maxItems:e.maxItems||100,defaultTTL:e.defaultTTL||36e5,persistent:!1!==e.persistent,storage:e.storage||"memory",compression:e.compression||!1},this.rateLimiting={enabled:!1!==e.rateLimiting,maxOpsPerSecond:e.maxOpsPerSecond||100,windowMs:1e3,cooldownMs:e.cooldownMs||5e3,operations:[],inCooldown:!1,cooldownUntil:0},this.memoryCache=new Map,this.accessOrder=new Map,this.stats={hits:0,misses:0,sets:0,evictions:0,size:0,rateLimited:0}}_checkRateLimit(){if(!this.rateLimiting.enabled)return!0;const e=Date.now();if(this.rateLimiting.inCooldown){if(e<this.rateLimiting.cooldownUntil)return this.stats.rateLimited++,!1;this.rateLimiting.inCooldown=!1,this.rateLimiting.operations=[]}const t=e-this.rateLimiting.windowMs;return this.rateLimiting.operations=this.rateLimiting.operations.filter(e=>e>t),this.rateLimiting.operations.length>=this.rateLimiting.maxOpsPerSecond?(this.rateLimiting.inCooldown=!0,this.rateLimiting.cooldownUntil=e+this.rateLimiting.cooldownMs,this.stats.rateLimited++,console.warn(`[WuCache] π« Rate limit exceeded. Cooldown for ${this.rateLimiting.cooldownMs}ms`),!1):(this.rateLimiting.operations.push(e),!0)}getRateLimitStatus(){const e=Date.now();return{enabled:this.rateLimiting.enabled,inCooldown:this.rateLimiting.inCooldown,cooldownRemaining:this.rateLimiting.inCooldown?Math.max(0,this.rateLimiting.cooldownUntil-e):0,currentOps:this.rateLimiting.operations.length,maxOps:this.rateLimiting.maxOpsPerSecond,rateLimited:this.stats.rateLimited}}get(e){if(!this._checkRateLimit())return null;if(this.memoryCache.has(e)){const t=this.memoryCache.get(e);return this.isExpired(t)?(this.delete(e),this.stats.misses++,null):(this.accessOrder.set(e,Date.now()),this.stats.hits++,t.value)}if(this.config.persistent){const t=this.getFromStorage(e);if(t)return this.memoryCache.set(e,t),this.accessOrder.set(e,Date.now()),this.stats.hits++,t.value}return this.stats.misses++,null}set(e,t,o){if(!this._checkRateLimit())return!1;try{const s={key:e,value:t,timestamp:Date.now(),ttl:o||this.config.defaultTTL,size:this.estimateSize(t)};return!1===this.ensureSpace(s.size)?(console.warn(`[WuCache] β οΈ Cannot cache item: ${e} (too large)`),!1):(this.memoryCache.set(e,s),this.accessOrder.set(e,Date.now()),this.config.persistent&&this.saveToStorage(e,s),this.stats.sets++,this.stats.size+=s.size,!0)}catch(e){return console.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(),console.log("[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 t=1024*this.config.maxSize*1024;if(e>t)return console.warn(`[WuCache] β οΈ Item size (${e}) exceeds max cache size (${t}). Skipping.`),!1;const o=this.config.maxItems+10;let s=0;for(;(this.stats.size+e>t||this.memoryCache.size>=this.config.maxItems)&&s<o;){if(s++,0===this.memoryCache.size){console.warn("[WuCache] β οΈ Cache empty but still no space. Breaking loop.");break}let e=null,t=1/0;for(const[o,s]of this.accessOrder)s<t&&(t=s,e=o);if(!e)break;console.log(`[WuCache] ποΈ Evicting LRU entry: ${e}`),this.delete(e),this.stats.evictions++}return s>=o&&console.error(`[WuCache] π¨ Max eviction iterations reached (${o}). Possible infinite loop prevented.`),!0}getFromStorage(e){try{const t=this.getStorage().getItem(`wu_cache_${e}`);if(t)return JSON.parse(t)}catch(e){console.warn("[WuCache] β οΈ Failed to get from storage:",e)}return null}saveToStorage(e,t){try{this.getStorage().setItem(`wu_cache_${e}`,JSON.stringify(t))}catch(o){console.warn("[WuCache] β οΈ Storage full, cleaning old entries"),this.cleanOldStorageEntries();try{storage.setItem(`wu_cache_${e}`,JSON.stringify(t))}catch{console.warn("[WuCache] β οΈ Failed to save to storage after cleanup")}}}deleteFromStorage(e){try{this.getStorage().removeItem(`wu_cache_${e}`)}catch(e){console.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){console.warn("[WuCache] β οΈ Failed to clear storage:",e)}}cleanOldStorageEntries(){try{const e=this.getStorage(),t=Object.keys(e),o=[];t.forEach(t=>{if(t.startsWith("wu_cache_"))try{const s=JSON.parse(e.getItem(t));o.push({key:t,timestamp:s.timestamp})}catch{}}),o.sort((e,t)=>e.timestamp-t.timestamp);const s=Math.ceil(.25*o.length);for(let t=0;t<s;t++)e.removeItem(o[t].key);console.log(`[WuCache] π§Ή Cleaned ${s} old storage entries`)}catch(e){console.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 WuEventBus{constructor(){this.listeners=new Map,this.history=[],this.authorizedApps=new Map,this.trustedEvents=new Set(["wu:*","system:*"]),this.config={maxHistory:100,enableReplay:!0,enableWildcards:!0,logEvents:!1,strictMode:!1,validateOrigin:!0},this.stats={emitted:0,subscriptions:0,rejected:0}}registerApp(e,t={}){const o=t.token||this._generateToken();return this.authorizedApps.set(e,{token:o,permissions:t.permissions||["*"],registeredAt:Date.now()}),o}unregisterApp(e){this.authorizedApps.delete(e)}_validateOrigin(e,t,o){if(this._isSystemEvent(e))return!0;if(!this.config.strictMode)return!0;const s=this.authorizedApps.get(t);return!!s&&(!o||s.token===o)&&this._hasPermission(s.permissions,e)}_hasPermission(e,t){return!!e.includes("*")||e.some(e=>e===t||!!e.includes("*")&&this.matchesWildcard(t,e))}_isSystemEvent(e){return e.startsWith("wu:")||e.startsWith("system:")||e.startsWith("app:")}_generateToken(){return`wu_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}emit(e,t,o={}){const s=o.appName||"unknown";if(this.config.validateOrigin&&this.config.strictMode&&!this._validateOrigin(e,s,o.token))return this.stats.rejected++,console.warn(`[WuEventBus] π« Event rejected: ${e} from ${s} (unauthorized)`),!1;const n={name:e,data:t,timestamp:o.timestamp||Date.now(),appName:s,meta:o.meta||{},verified:this.authorizedApps.has(s)};this.config.enableReplay&&this.addToHistory(n),this.config.logEvents&&console.log(`[WuEventBus] π’ ${e}`,t);const r=this.listeners.get(e);return r&&r.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 o=this.listeners.get(e);o&&(o.delete(t),0===o.size&&this.listeners.delete(e),this.stats.subscriptions--)}once(e,t){const o=s=>{t(s),this.off(e,o)};return this.on(e,o)}notifyWildcardListeners(e,t){for(const[o,s]of this.listeners)this.matchesWildcard(e,o)&&s.forEach(e=>{try{e(t)}catch(e){console.error(`[WuEventBus] β Error in wildcard listener for ${o}:`,e)}})}matchesWildcard(e,t){if(!t.includes("*"))return!1;const o=t.replace(/\./g,"\\.").replace(/\*/g,".*");return new RegExp(`^${o}$`).test(e)}addToHistory(e){this.history.push(e),this.history.length>this.config.maxHistory&&this.history.shift()}replay(e,t){this.history.filter(t=>e.includes("*")?this.matchesWildcard(t.name,e):t.name===e).forEach(e=>{try{t(e)}catch(e){console.error("[WuEventBus] β Error replaying event:",e)}})}clearHistory(e){this.history=e?this.history.filter(t=>e.includes("*")?!this.matchesWildcard(t.name,e):t.name!==e):[]}getStats(){return{...this.stats,activeListeners:this.listeners.size,historySize:this.history.length,authorizedApps:this.authorizedApps.size,listenersByEvent:Array.from(this.listeners.entries()).map(([e,t])=>({event:e,listeners:t.size}))}}configure(e){this.config={...this.config,...e}}enableStrictMode(){this.config.strictMode=!0}disableStrictMode(){this.config.strictMode=!1}removeAll(){this.listeners.clear(),this.stats.subscriptions=0}}class WuPerformance{constructor(){this.metrics=new Map,this.measurements=[],this.marks=new Map,this.config={enabled:!0,maxMeasurements:1e3},this.thresholds={mount:3e3,unmount:1e3,load:5e3},console.log("[WuPerformance] β‘ Framework performance monitoring initialized")}startMeasure(e,t="global"){const o=`${t}:${e}:start`;this.marks.set(o,performance.now()),console.log(`[WuPerformance] π Measure started: ${o}`)}endMeasure(e,t="global"){const o=`${t}:${e}:start`,s=this.marks.get(o);if(!s)return console.warn(`[WuPerformance] β οΈ No start mark found for: ${o}`),0;const n=performance.now()-s;return this.marks.delete(o),this.recordMeasurement({name:e,appName:t,duration:n,timestamp:Date.now(),type:"duration"}),this.checkThreshold(e,n)&&console.warn(`[WuPerformance] β οΈ Threshold exceeded for ${e}: ${n.toFixed(2)}ms`),console.log(`[WuPerformance] βΉοΈ Measure ended: ${o} (${n.toFixed(2)}ms)`),n}recordMeasurement(e){this.measurements.push(e),this.measurements.length>this.config.maxMeasurements&&this.measurements.shift(),this.metrics.has(e.appName)||this.metrics.set(e.appName,{appName:e.appName,measurements:[],stats:{}}),this.metrics.get(e.appName).measurements.push(e),this.calculateStats(e.appName)}calculateStats(e){const t=this.metrics.get(e);if(!t)return;const o=t.measurements;if(0===o.length)return;const s={};o.forEach(e=>{s[e.name]||(s[e.name]=[]),s[e.name].push(e.duration)}),t.stats={},Object.entries(s).forEach(([e,o])=>{t.stats[e]={count:o.length,avg:o.reduce((e,t)=>e+t,0)/o.length,min:Math.min(...o),max:Math.max(...o),last:o[o.length-1]}})}checkThreshold(e,t){const o=this.thresholds[e];return o&&t>o}generateReport(){const e={timestamp:Date.now(),totalMeasurements:this.measurements.length,apps:{}};for(const[t,o]of this.metrics)e.apps[t]={measurementCount:o.measurements.length,stats:o.stats};return e}getMetrics(e){return this.metrics.get(e)||null}getAllMetrics(){const e={};for(const[t,o]of this.metrics)e[t]=o;return e}clearMetrics(e){e?(this.metrics.delete(e),this.measurements=this.measurements.filter(t=>t.appName!==e)):(this.metrics.clear(),this.measurements=[]),console.log("[WuPerformance] π§Ή Metrics cleared"+(e?` for ${e}`:""))}configure(e){this.config={...this.config,...e},e.thresholds&&(this.thresholds={...this.thresholds,...e.thresholds})}}class WuPluginSystem{constructor(e){this._core=e,this.plugins=new Map,this.hooks=new Map,this.availableHooks=["beforeInit","afterInit","beforeMount","afterMount","beforeUnmount","afterUnmount","onError","onDestroy"],this.availablePermissions=["mount","events","store","apps","config","unsafe"],this.hookTimeout=5e3,this.availableHooks.forEach(e=>{this.hooks.set(e,[])})}_createSandboxedApi(e){const t={version:this._core.version,info:this._core.info,getAppInfo:e=>{const t=this._core.mounted.get(e);return t?{name:e,state:t.state,timestamp:t.timestamp}:null},getMountedApps:()=>Array.from(this._core.mounted.keys()),getStats:()=>this._core.getStats()};return(e.includes("events")||e.includes("unsafe"))&&(t.emit=(e,t)=>this._core.eventBus.emit(e,t,{appName:"plugin"}),t.on=(e,t)=>this._core.eventBus.on(e,t),t.off=(e,t)=>this._core.eventBus.off(e,t)),(e.includes("store")||e.includes("unsafe"))&&(t.getState=e=>this._core.store.get(e),t.setState=(e,t)=>this._core.store.set(e,t)),(e.includes("mount")||e.includes("unsafe"))&&(t.mount=(e,t)=>this._core.mount(e,t),t.unmount=e=>this._core.unmount(e)),(e.includes("config")||e.includes("unsafe"))&&(t.configure=e=>{const t=["debug","logLevel"],o={};for(const s of t)s in e&&(o[s]=e[s]);Object.assign(this._core,o)}),e.includes("unsafe")&&(t._unsafeCore=this._core,console.warn("[WuPlugin] β οΈ Plugin has unsafe access to core!")),Object.freeze(t)}_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,t={}){if("function"==typeof e&&(e=e(t)),this._validatePlugin(e),this.plugins.has(e.name))return void console.warn(`[WuPlugin] Plugin "${e.name}" already installed`);const o=e.permissions||["events"],s=this._createSandboxedApi(o);if(e.install)try{e.install(s,t)}catch(t){throw console.error(`[WuPlugin] Error installing "${e.name}":`,t),t}this.availableHooks.forEach(t=>{if("function"==typeof e[t]){const o=this._wrapHook(e[t].bind(e),e.name,t);this.registerHook(t,o)}}),this.plugins.set(e.name,{plugin:e,options:t,permissions:o,sandboxedApi:s,installedAt:Date.now()}),console.log(`[WuPlugin] β
Plugin "${e.name}" installed (permissions: ${o.join(", ")})`)}_wrapHook(e,t,o){return async s=>{const n=new Promise((e,s)=>{setTimeout(()=>{s(new Error(`Plugin "${t}" hook "${o}" timed out after ${this.hookTimeout}ms`))},this.hookTimeout)});try{return await Promise.race([e(s),n])}catch(e){return void console.error(`[WuPlugin] Error in ${t}.${o}:`,e)}}}registerHook(e,t){this.hooks.has(e)?this.hooks.get(e).push(t):console.warn(`[WuPlugin] Unknown hook: ${e}`)}async callHook(e,t){const o=this.hooks.get(e)||[];for(const s of o)try{if(!1===await s(t))return!1}catch(t){console.error(`[WuPlugin] Error in hook ${e}:`,t)}return!0}uninstall(e){const t=this.plugins.get(e);if(!t)return void console.warn(`[WuPlugin] Plugin "${e}" not found`);const{plugin:o,sandboxedApi:s}=t;if(o.uninstall)try{o.uninstall(s)}catch(t){console.error(`[WuPlugin] Error uninstalling "${e}":`,t)}this.plugins.delete(e),console.log(`[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 createPlugin=e=>({name:e.name,permissions:e.permissions||["events"],install:e.install,uninstall:e.uninstall,beforeMount:e.beforeMount,afterMount:e.afterMount,beforeUnmount:e.beforeUnmount,afterUnmount:e.afterUnmount,onError:e.onError});class WuLoadingStrategy{constructor(e){this.core=e,this.strategies=new Map,this.loadingQueue=[],this.isIdle=!1,this.registerDefaultStrategies(),this.setupIdleCallback(),console.log("[WuStrategies] π― Loading strategies initialized")}registerDefaultStrategies(){this.register("lazy",{shouldPreload:!1,load:async(e,t)=>{console.log(`[Strategy:Lazy] Loading ${e} on demand (no preload)`)}}),this.register("eager",{shouldPreload:!0,priority:"high",load:async(e,t)=>{console.log(`[Strategy:Eager] Preloading ${e} immediately`);const o=this.core.apps.get(e);if(o){const t=await this.core.resolveModulePath(o);await import(t),console.log(`[Strategy:Eager] β
${e} preloaded`)}}}),this.register("preload",{shouldPreload:!0,priority:"medium",load:async(e,t)=>{console.log(`[Strategy:Preload] Using resource hints for ${e}`);const o=this.core.apps.get(e);if(o){const t=await this.core.resolveModulePath(o),s=document.createElement("link");s.rel="prefetch",s.href=t,s.as="script",document.head.appendChild(s),console.log(`[Strategy:Preload] β
Resource hint added for ${e}`)}}}),this.register("idle",{shouldPreload:!1,load:async(e,t)=>(console.log(`[Strategy:Idle] Queueing ${e} for idle loading`),new Promise(o=>{this.loadingQueue.push({appName:e,config:t,resolve:o}),this.isIdle&&this.processIdleQueue()}))})}register(e,t){if(!t.load||"function"!=typeof t.load)throw new Error("[WuStrategies] Strategy must have a load function");this.strategies.set(e,{name:e,shouldPreload:t.shouldPreload||!1,priority:t.priority||"low",load:t.load}),console.log(`[WuStrategies] Strategy "${e}" registered`)}async load(e,t){const o=t.strategy||"lazy",s=this.strategies.get(o);return s?await s.load(e,t):(console.warn(`[WuStrategies] Strategy "${o}" not found, using lazy`),await this.strategies.get("lazy").load(e,t))}async preload(e){const t=e.filter(e=>this.strategies.get(e.strategy||"lazy").shouldPreload);t.sort((e,t)=>{const o={high:0,medium:1,low:2},s=this.strategies.get(e.strategy)?.priority||"low",n=this.strategies.get(t.strategy)?.priority||"low";return o[s]-o[n]}),console.log(`[WuStrategies] Preloading ${t.length} apps`);for(const e of t)try{await this.load(e.name,e)}catch(t){console.error(`[WuStrategies] Failed to preload ${e.name}:`,t)}}setupIdleCallback(){if("requestIdleCallback"in window){const e=t=>{this.isIdle=!0,this.processIdleQueue(t),requestIdleCallback(e)};requestIdleCallback(e)}else setTimeout(()=>{this.isIdle=!0,this.processIdleQueue()},2e3)}async processIdleQueue(e){for(;this.loadingQueue.length>0&&!(e&&e.timeRemaining()<=0);){const e=this.loadingQueue.shift();try{const t=this.core.apps.get(e.appName);if(t){const o=await this.core.resolveModulePath(t);await import(o),console.log(`[Strategy:Idle] β
${e.appName} loaded during idle time`),e.resolve(!0)}else e.resolve(null)}catch(t){console.error(`[Strategy:Idle] Failed to load ${e.appName}:`,t),e.resolve(null)}}}getStats(){return{totalStrategies:this.strategies.size,strategies:Array.from(this.strategies.keys()),idleQueueSize:this.loadingQueue.length,isIdle:this.isIdle}}cleanup(){this.loadingQueue=[],console.log("[WuStrategies] π§Ή Strategies cleaned up")}}class WuErrorBoundary{constructor(e){this.core=e,this.handlers=[],this.errorLog=[],this.maxErrorLog=100,this.config={maxRetries:3,retryDelay:1e3,showErrorUI:!0},this.registerDefaultHandlers(),console.log("[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,t)=>{if(console.log("[ErrorHandler:Network] Handling network error"),t.retryCount<this.config.maxRetries){const e=this.config.retryDelay*Math.pow(2,t.retryCount);return console.log(`[ErrorHandler:Network] Retrying in ${e}ms...`),await new Promise(t=>setTimeout(t,e)),{recovered:!0,action:"retry",retryCount:t.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,t)=>(console.log("[ErrorHandler:ScriptLoad] Handling script load error"),t.fallbackUrl?(console.log("[ErrorHandler:ScriptLoad] Trying fallback URL"),{recovered:!0,action:"use-fallback-url",url:t.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,t)=>{if(console.log("[ErrorHandler:Mount] Handling mount error"),t.retryCount<2){console.log("[ErrorHandler:Mount] Cleaning up and retrying...");try{await this.core.unmount(t.appName)}catch(e){console.warn("[ErrorHandler:Mount] Cleanup failed:",e)}return await new Promise(e=>setTimeout(e,500)),{recovered:!0,action:"retry",retryCount:t.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,t)=>(console.log("[ErrorHandler:Timeout] Handling timeout error"),t.retryCount<2?{recovered:!0,action:"retry-with-longer-timeout",timeout:2*(t.timeout||5e3),retryCount:t.retryCount+1}:{recovered:!1,action:"fallback",message:"Operation timed out"})}),this.register({name:"generic",canHandle:()=>!0,handle:async(e,t)=>(console.log("[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),console.log(`[WuErrorBoundary] Handler "${e.name}" registered`)}async handle(e,t={}){t={retryCount:0,timestamp:Date.now(),...t},this.logError(e,t);for(const o of this.handlers)try{if(o.canHandle(e,t)){console.log(`[WuErrorBoundary] Using handler: ${o.name}`);const s=await o.handle(e,t);return s.recovered?(console.log(`[WuErrorBoundary] β
Error recovered by ${o.name}`),s):("fallback"===s.action&&this.config.showErrorUI&&this.renderFallback(t,s),s)}}catch(e){console.error(`[WuErrorBoundary] Handler "${o.name}" failed:`,e)}return console.error("[WuErrorBoundary] β No handler could handle the error"),{recovered:!1,action:"unhandled",message:"Unhandled error"}}renderFallback(e,t){if(!e.container)return void console.warn("[WuErrorBoundary] No container to render fallback");const o="string"==typeof e.container?document.querySelector(e.container):e.container;if(!o)return;o.innerHTML="";const s=document.createElement("div");s.className="wu-error-boundary",Object.assign(s.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 r=document.createElement("h3");r.textContent="Application Error",r.style.margin="0 0 0.5rem 0";const a=document.createElement("p");a.textContent=t.message||"An error occurred",a.style.margin="0 0 1rem 0";const i=document.createElement("button");i.textContent="π Reload",Object.assign(i.style,{padding:"0.5rem 1rem",background:"#ffc107",border:"none",borderRadius:"4px",cursor:"pointer",fontWeight:"bold",color:"#000"}),i.addEventListener("click",()=>window.location.reload()),s.appendChild(n),s.appendChild(r),s.appendChild(a),s.appendChild(i),o.appendChild(s)}logError(e,t){const o={error:{name:e.name,message:e.message,stack:e.stack},context:t,timestamp:Date.now()};this.errorLog.push(o),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 o=t.error.name||"Unknown";e[o]=(e[o]||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=[],console.log("[WuErrorBoundary] π§Ή Error boundary cleaned up")}}class WuLifecycleHooks{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,[])}),console.log("[WuHooks] πͺ Lifecycle hooks initialized")}use(e,t,o={}){if(!this.hooks.has(e))throw new Error(`[WuHooks] Unknown lifecycle phase: ${e}`);if("function"!=typeof t)throw new Error("[WuHooks] Middleware must be a function");const s={middleware:t,name:o.name||`hook_${Date.now()}`,priority:o.priority||0,registeredAt:Date.now()},n=this.hooks.get(e);return n.push(s),n.sort((e,t)=>t.priority-e.priority),console.log(`[WuHooks] Hook "${s.name}" registered for ${e} (priority: ${s.priority})`),()=>this.remove(e,s.name)}remove(e,t){if(!this.hooks.has(e))return;const o=this.hooks.get(e),s=o.findIndex(e=>e.name===t);s>-1&&(o.splice(s,1),console.log(`[WuHooks] Hook "${t}" removed from ${e}`))}async execute(e,t={}){const o=this.hooks.get(e);if(!o||0===o.length)return t;console.log(`[WuHooks] Executing ${o.length} hooks for ${e}`);const s={phase:e,timestamp:Date.now(),hooksCount:o.length,hookNames:o.map(e=>e.name)};let n={...t},r=!1;const a=async e=>{if(e>=o.length)return n;const t=o[e],s=Date.now();try{let o=!1;const i=async t=>(o=!0,void 0!==t&&(n={...n,...t}),await a(e+1));if(await t.middleware(n,i),!o)return console.log(`[WuHooks] Hook "${t.name}" cancelled execution`),r=!0,{cancelled:!0};const l=Date.now()-s;console.log(`[WuHooks] Hook "${t.name}" executed in ${l}ms`)}catch(o){return console.error(`[WuHooks] Error in hook "${t.name}":`,o),await a(e+1)}return n},i=await a(0);return s.duration=Date.now()-s.timestamp,s.cancelled=r,s.success=!r,this.executionLog.push(s),this.executionLog.length>this.maxLogSize&&this.executionLog.shift(),i}useMultiple(e,t,o={}){const s=e.map(e=>this.use(e,t,{...o,name:`${o.name}_${e}`}));return()=>s.forEach(e=>e())}getHooks(e){if(e)return this.hooks.get(e)||[];const t={};return this.hooks.forEach((e,o)=>{t[o]=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 o=this.executionLog.length>0?this.executionLog.reduce((e,t)=>e+t.duration,0)/this.executionLog.length:0,s=this.executionLog.filter(e=>e.cancelled).length;return{totalHooks:e,totalExecutions:this.executionLog.length,executionsByPhase:t,avgDuration:Math.round(o),cancelledCount:s,recentExecutions:this.executionLog.slice(-10)}}cleanup(e){e?(this.hooks.set(e,[]),console.log(`[WuHooks] Hooks cleaned for ${e}`)):(this.lifecyclePhases.forEach(e=>{this.hooks.set(e,[])}),this.executionLog=[],console.log("[WuHooks] π§Ή All hooks cleaned"))}}const createSimpleHook=e=>async(t,o)=>{await e(t),await o()},createConditionalHook=(e,t)=>async(o,s)=>{await e(o)&&await t(o),await s()},createGuardHook=e=>async(t,o)=>{await e(t)&&await o()},createTransformHook=e=>async(t,o)=>{const s=await e(t);await o(s)},createTimedHook=(e,t=5e3)=>async(o,s)=>{const n=new Promise((e,o)=>setTimeout(()=>o(new Error("Hook timeout")),t));try{await Promise.race([e(o),n]),await s()}catch(e){console.error("[WuHooks] Timed hook failed:",e),await s()}};class WuSandboxPool{constructor(e){this.core=e,this.config={minSize:2,maxSize:10,idleTimeout:3e4,warmupOnInit:!0},this.available=[],this.inUse=new Map,this.totalCreated=0,this.totalReused=0,this.cleanupTimer=null,console.log("[WuSandboxPool] π Sandbox pool initialized")}async init(){this.config.warmupOnInit&&await this.warmup(),this.startCleanupTimer(),console.log("[WuSandboxPool] Pool ready")}async warmup(){console.log(`[WuSandboxPool] Warming up pool with ${this.config.minSize} sandboxes`);for(let e=0;e<this.config.minSize;e++){const e=this.createSandbox();this.available.push(e)}console.log(`[WuSandboxPool] β
Pool warmed up with ${this.available.length} sandboxes`)}createSandbox(){const e=document.createElement("div");e.className="wu-sandbox-container",e.style.display="none";const t=e.attachShadow({mode:"open"}),o=document.createElement("div");o.className="wu-mount-point",t.appendChild(o);const s={id:"sandbox_"+this.totalCreated++,container:e,shadowRoot:t,mountPoint:o,createdAt:Date.now(),lastUsed:Date.now(),timesUsed:0,currentApp:null};return console.log(`[WuSandboxPool] Created sandbox: ${s.id}`),s}acquire(e){if(this.inUse.has(e))return console.warn(`[WuSandboxPool] App "${e}" already has a sandbox`),this.inUse.get(e);let t;return this.available.length>0?(t=this.available.pop(),this.totalReused++,console.log(`[WuSandboxPool] β»οΈ Reusing sandbox ${t.id} for ${e}`)):this.inUse.size<this.config.maxSize?(t=this.createSandbox(),console.log(`[WuSandboxPool] π Creating new sandbox ${t.id} for ${e}`)):(t=this.createSandbox(),t.temporary=!0,console.warn(`[WuSandboxPool] β οΈ Pool exhausted, creating temporary sandbox for ${e}`)),this.prepareSandbox(t,e),t.currentApp=e,t.lastUsed=Date.now(),t.timesUsed++,this.inUse.set(e,t),t}release(e){const t=this.inUse.get(e);if(t){if(this.cleanSandbox(t),this.inUse.delete(e),t.currentApp=null,t.lastUsed=Date.now(),t.temporary)return this.destroySandbox(t),void console.log(`[WuSandboxPool] ποΈ Destroyed temporary sandbox ${t.id}`);this.available.length<this.config.maxSize?(this.available.push(t),console.log(`[WuSandboxPool] β
Released sandbox ${t.id} back to pool`)):(this.destroySandbox(t),console.log(`[WuSandboxPool] ποΈ Pool full, destroyed sandbox ${t.id}`))}else console.warn(`[WuSandboxPool] App "${e}" has no sandbox to release`)}prepareSandbox(e,t){e.container.style.display="block",e.container.setAttribute("data-wu-app",t),console.log(`[WuSandboxPool] Prepared sandbox ${e.id} for ${t}`)}cleanSandbox(e){e.mountPoint&&(e.mountPoint.innerHTML=""),e.shadowRoot&&e.shadowRoot.querySelectorAll("style").forEach(e=>e.remove()),e.container.style.display="none",e.container.removeAttribute("data-wu-app"),console.log(`[WuSandboxPool] Cleaned sandbox ${e.id}`)}destroySandbox(e){this.cleanSandbox(e),e.container.parentNode&&e.container.parentNode.removeChild(e.container),e.shadowRoot=null,e.mountPoint=null,e.container=null,console.log(`[WuSandboxPool] Destroyed sandbox ${e.id}`)}startCleanupTimer(){this.cleanupTimer&&clearInterval(this.cleanupTimer),this.cleanupTimer=setInterval(()=>{this.cleanupIdleSandboxes()},6e4)}cleanupIdleSandboxes(){const e=Date.now()-this.config.idleTimeout,t=[],o=[];if(this.available.forEach(s=>{s.lastUsed<e&&this.available.length>this.config.minSize?o.push(s):t.push(s)}),o.forEach(e=>{this.destroySandbox(e)}),this.available=t,o.length>0&&console.log(`[WuSandboxPool] π§Ή Cleaned up ${o.length} idle sandboxes`),this.available.length<this.config.minSize){const e=this.config.minSize-this.available.length;console.log(`[WuSandboxPool] Creating ${e} sandboxes to maintain minimum`);for(let t=0;t<e;t++)this.available.push(this.createSandbox())}}configure(e){const t=this.config.minSize;if(this.config={...this.config,...e},this.config.minSize>t){const e=this.config.minSize-this.available.length;if(e>0){console.log(`[WuSandboxPool] Creating ${e} sandboxes for new minSize`);for(let t=0;t<e;t++)this.available.push(this.createSandbox())}}if(this.available.length>this.config.maxSize){const e=this.available.length-this.config.maxSize;this.available.splice(this.config.maxSize,e).forEach(e=>this.destroySandbox(e)),console.log(`[WuSandboxPool] Destroyed ${e} excess sandboxes`)}console.log("[WuSandboxPool] Configuration updated:",this.config)}getStats(){const e=this.available.length+this.inUse.size,t=e>0?(this.inUse.size/e*100).toFixed(1):0,o=e>0?[...this.available,...this.inUse.values()].reduce((e,t)=>e+t.timesUsed,0)/e:0;return{available:this.available.length,inUse:this.inUse.size,totalSandboxes:e,utilization:`${t}%`,totalCreated:this.totalCreated,totalReused:this.totalReused,reuseRate:this.totalCreated>0?`${(this.totalReused/this.totalCreated*100).toFixed(1)}%`:"0%",avgTimesUsed:o.toFixed(1),config:this.config,appsInUse:Array.from(this.inUse.keys())}}cleanup(){this.cleanupTimer&&(clearInterval(this.cleanupTimer),this.cleanupTimer=null),this.available.forEach(e=>this.destroySandbox(e)),this.available=[],this.inUse.forEach((e,t)=>{console.warn(`[WuSandboxPool] Force destroying sandbox for active app: ${t}`),this.destroySandbox(e)}),this.inUse.clear(),console.log("[WuSandboxPool] π§Ή Pool cleaned up")}}class WuRegistry{constructor(){this.registeredApps=new Set,this._setupNotifyReady()}_setupNotifyReady(){const e=()=>{window.wu&&!window.wu.notifyReady&&(window.wu.notifyReady=e=>{const t=new CustomEvent("wu:app:ready",{detail:{appName:e,timestamp:Date.now()}});window.dispatchEvent(t)})};e(),window.wu||queueMicrotask(e)}markAsRegistered(e){this.registeredApps.add(e)}isRegistered(e){return this.registeredApps.has(e)}unregister(e){this.registeredApps.delete(e)}cleanup(){this.registeredApps.clear()}}class WuCore{constructor(e={}){this.apps=new Map,this.definitions=new Map,this.manifests=new Map,this.mounted=new Map,this.loader=new WuLoader,this.sandbox=new WuSandbox,this.manifest=new WuManifest,this.store=store,this.cache=new WuCache({storage:"localStorage",maxSize:100}),this.eventBus=new WuEventBus,this.performance=new WuPerformance,this.pluginSystem=new WuPluginSystem(this),this.strategies=new WuLoadingStrategy(this),this.errorBoundary=new WuErrorBoundary(this),this.hooks=new WuLifecycleHooks(this),this.sandboxPool=new WuSandboxPool(this),this.registry=new WuRegistry,this.healthConfig={enabled:!1!==e.healthMonitoring,autoHeal:!1!==e.autoHeal,agingThreshold:e.agingThreshold||1/0,checkInterval:e.healthCheckInterval||6e4},this.healthState={monitor:null,healingInProgress:new Set,systemStable:!0,lastHealthCheck:Date.now(),mutationObserver:null,mutationCheckTimeout:null},this.isInitialized=!1,this.healthConfig.enabled?(this.initializeHealthMonitoring(),logger.wuInfo("π Wu Framework initialized - Universal Microfrontends with Self-Healing")):logger.wuInfo("π Wu Framework initialized - Universal Microfrontends (Health Monitoring Disabled)")}initializeHealthMonitoring(){this.healthState.monitor=setInterval(()=>{this.performHealthCheck()},this.healthConfig.checkInterval),this.initializeMutationObserver(),this.healthConfig.autoHeal&&(window.addEventListener("error",e=>{this.handleErrorEvent(e)}),window.addEventListener("unhandledrejection",e=>{this.handleRejection(e)})),logger.wuInfo(`π Health monitoring initialized - Interval: ${this.healthConfig.checkInterval}ms, AutoHeal: ${this.healthConfig.autoHeal}`)}initializeMutationObserver(){window.MutationObserver&&(this.healthState.containerObservers=new Map,this.healthState.mutationCallback=(e,t)=>{let o=null;for(const t of e){if("childList"===t.type&&t.removedNodes.length>0)for(const[e,s]of this.mounted){const n=s.hostContainer||s.container;if(t.target===n||t.target.contains?.(n)){o=e;break}}if(o)break}o&&(clearTimeout(this.healthState.mutationCheckTimeout),this.healthState.mutationCheckTimeout=setTimeout(()=>{this.performHealthCheck()},1e3))},logger.wuDebug("π MutationObserver system initialized (lazy per-container)"))}observeContainer(e,t){if(!this.healthState.containerObservers||!t)return;if(this.healthState.containerObservers.has(e))return;const o=new MutationObserver(this.healthState.mutationCallback),s=t.parentElement||t;o.observe(s,{childList:!0,subtree:!1}),this.healthState.containerObservers.set(e,o),logger.wuDebug(`π Observing container for ${e}`)}unobserveContainer(e){if(!this.healthState.containerObservers)return;const t=this.healthState.containerObservers.get(e);t&&(t.disconnect(),this.healthState.containerObservers.delete(e),logger.wuDebug(`π Stopped observing container for ${e}`))}async performHealthCheck(){try{const e=Date.now(),t=[];for(const[o,s]of this.mounted){const n=e-s.timestamp,r=s.container;let a=!1;try{const e=document.contains(r),t=r.parentElement&&document.contains(r.parentElement),o=s.sandbox?.shadowRoot?.host,n=o&&document.contains(o),i=null!==r.parentElement||null!==r.parentNode;e||t||n||i||(a=!0)}catch(e){console.warn(`[Wu] β οΈ Container check failed for ${o}:`,e),a=!1}a&&t.push({type:"orphaned_container",appName:o,severity:"high"}),s.state&&"stable"!==s.state&&"refreshed"!==s.state&&t.push({type:"unstable_state",appName:o,severity:"medium"}),n>this.healthConfig.agingThreshold&&(t.push({type:"aging_app",appName:o,severity:"low",age:n}),console.log(`[Wu] β° App ${o} has been running for ${(n/1e3/60).toFixed(1)} minutes`))}t.length>0&&await this.processHealthIssues(t),this.healthState.lastHealthCheck=e}catch(e){console.warn("[Wu] β οΈ Health check failed:",e)}}async processHealthIssues(e){for(const t of e)if(!this.healthState.healingInProgress.has(t.appName))switch(console.log("[Wu] π©Ί Health issue detected:",t),t.type){case"orphaned_container":await this.healOrphanedContainer(t.appName);break;case"unstable_state":await this.stabilizeAppState(t.appName);break;case"aging_app":await this.refreshAgingApp(t.appName)}}async healOrphanedContainer(e){this.healthState.healingInProgress.add(e);try{console.log(`[Wu] π Healing orphaned container for ${e}`),await this.unmount(e);const t=[document.querySelector(`[data-wu-app="${e}"]`),document.querySelector(`#${e}-container`),document.querySelector(`.${e}-container`),document.querySelector(`[id*="${e}"]`)].filter(Boolean);if(t.length>0){const o=t[0],s=o.id?`#${o.id}`:`.${o.className.split(" ")[0]}`;s&&"#"!==s&&"."!==s?(await this.mount(e,s),console.log(`[Wu] β¨ Successfully healed orphaned ${e} in ${s}`)):console.warn(`[Wu] β οΈ Could not determine valid selector for ${e}`)}else console.warn(`[Wu] β οΈ No suitable container found for healing ${e}`)}catch(t){console.warn(`[Wu] β οΈ Failed to heal orphaned ${e}:`,t)}finally{this.healthState.healingInProgress.delete(e)}}async stabilizeAppState(e){this.healthState.healingInProgress.add(e);try{console.log(`[Wu] βοΈ Stabilizing app state for ${e}`);const t=this.mounted.get(e);t&&(t.state="stable",console.log(`[Wu] β¨ App state stabilized for ${e}`))}catch(t){console.warn(`[Wu] β οΈ Failed to stabilize ${e}:`,t)}finally{this.healthState.healingInProgress.delete(e)}}async refreshAgingApp(e){if(this.healthConfig.agingThreshold!==1/0){this.healthState.healingInProgress.add(e);try{console.log(`[Wu] π°οΈ Refreshing aging app for ${e}`);const t=this.mounted.get(e);t&&(t.timestamp=Date.now(),t.state="refreshed",t.lifecycle.refresh&&await t.lifecycle.refresh(t.container),console.log(`[Wu] β¨ App refreshed for ${e}`))}catch(t){console.warn(`[Wu] β οΈ Failed to refresh ${e}:`,t)}finally{this.healthState.healingInProgress.delete(e)}}else console.warn("[Wu] β οΈ refreshAgingApp called but agingThreshold is Infinity - skipping")}handleErrorEvent(e){console.log("[Wu] π₯ Error event detected:",e.error);for(const[t,o]of this.mounted)if(e.filename&&e.filename.includes(o.app.url)){console.log(`[Wu] π― Error traced to ${t}, initiating recovery...`),setTimeout(()=>{this.healOrphanedContainer(t)},1e3);break}}handleRejection(e){console.log("[Wu] π« Promise rejection detected:",e.reason),e.preventDefault(),this.healthState.systemStable=!1,setTimeout(()=>{this.healthState.systemStable=!0,console.log("[Wu] β¨ System stability restored")},5e3)}async init(e){if(this.isInitialized)console.warn("[Wu] Framework already initialized");else{logger.wuDebug("π§ Initializing with apps:",e.apps?.map(e=>e.name));try{if((await this.hooks.execute("beforeInit",{config:e})).cancelled)return void console.warn("[Wu] Initialization cancelled by beforeInit hook");await this.pluginSystem.callHook("beforeInit",{config:e}),await this.sandboxPool.init();for(const t of e.apps||[])await this.registerApp(t);await this.strategies.preload(e.apps||[]),this.isInitialized=!0,await this.hooks.execute("afterInit",{config:e}),await this.pluginSystem.callHook("afterInit",{config:e}),logger.wuInfo("β
Framework initialized successfully")}catch(e){throw console.error("[Wu] β Initialization failed:",e),await this.pluginSystem.callHook("onError",{phase:"init",error:e}),e}}}async registerApp(e){const{name:t,url:o}=e;try{logger.wuDebug(`π¦ Registering app: ${t} from ${o}`);const e=await this.manifest.load(o);this.manifests.set(t,e),this.apps.set(t,{name:t,url:o,manifest:e,status:"registered"}),logger.wuDebug(`β
App ${t} registered successfully`)}catch(e){throw console.error(`[Wu] β Failed to register app ${t}:`,e),e}}define(e,t){if(!t.mount)throw new Error(`[Wu] Mount function required for app: ${e}`);this.definitions.set(e,t),this.registry.markAsRegistered(e);const o=new CustomEvent("wu:app:ready",{detail:{appName:e,timestamp:Date.now()}});window.dispatchEvent(o),logger.wuDebug(`π Lifecycle defined for: ${e}`)}async mount(e,t){return await this.mountWithRecovery(e,t,0)}async mountWithRecovery(e,t,o=0){try{if(this.performance.startMeasure("mount",e),logger.wuDebug(`π Mounting ${e} in ${t} (attempt ${o+1})`),(await this.hooks.execute("beforeLoad",{appName:e,containerSelector:t,attempt:o})).cancelled)return void console.warn("[Wu] Mount cancelled by beforeLoad hook");if(!1===await this.pluginSystem.callHook("beforeMount",{appName:e,containerSelector:t}))return void console.warn("[Wu] Mount cancelled by plugin beforeMount hook");const s=this.apps.get(e);if(!s)throw new Error(`App ${e} not registered. Call wu.init() first.`);const n=document.querySelector(t);if(!n)throw new Error(`Container not found: ${t}`);const r=this.sandboxPool.acquire(e),a=this.sandbox.create(e,n,{manifest:s.manifest,styleMode:s.manifest?.styleMode,appUrl:s.url});await this.hooks.execute("afterLoad",{appName:e,containerSelector:t,sandbox:a});let i=this.definitions.get(e);if(!i&&(await this.loadAndMountRemoteApp(s,a),i=this.definitions.get(e),!i))throw new Error(`App ${e} did not register with wu.define()`);if((await this.hooks.execute("beforeMount",{appName:e,containerSelector:t,sandbox:a,lifecycle:i})).cancelled)return void console.warn("[Wu] Mount cancelled by beforeMount hook");a.stylesReady&&(console.log(`[Wu] β³ Waiting for styles to be ready for ${e}...`),await a.stylesReady,console.log(`[Wu] β
Styles ready for ${e}`)),await i.mount(a.container),this.mounted.set(e,{app:s,sandbox:a,poolSandbox:r,lifecycle:i,container:a.container,hostContainer:n,timestamp:Date.now(),state:"stable"}),this.observeContainer(e,n);const l=this.performance.endMeasure("mount",e);await this.hooks.execute("afterMount",{appName:e,containerSelector:t,sandbox:a,mountTime:l}),await this.pluginSystem.callHook("afterMount",{appName:e,containerSelector:t,mountTime:l}),this.eventBus.emit("app:mounted",{appName:e,mountTime:l,attempt:o},{appName:e}),logger.wuInfo(`β
${e} mounted successfully in ${l.toFixed(2)}ms`)}catch(s){console.error(`[Wu] β Mount attempt ${o+1} failed for ${e}:`,s);const n=await this.errorBoundary.handle(s,{appName:e,containerSelector:t,retryCount:o,container:t});if(n.recovered)return void console.log("[Wu] β¨ Error recovered by error boundary");if(o<2&&"retry"===n.action)return console.log("[Wu] π Initiating recovery protocol..."),await this.appStateCleanup(e,t),await new Promise(e=>setTimeout(e,1e3*(o+1))),await this.mountWithRecovery(e,t,o+1);throw await this.pluginSystem.callHook("onError",{phase:"mount",error:s,appName:e}),s}}async appStateCleanup(e,t){try{if(console.log(`[Wu] π§Ή Starting app state cleanup for ${e}...`),this.mounted.has(e))try{await this.unmount(e)}catch(e){console.warn("[Wu] β οΈ Unmount failed during cleanup:",e)}const o=document.querySelector(t);if(o){if(o.shadowRoot)try{Array.from(o.shadowRoot.children).forEach(e=>{try{e.remove()}catch(e){console.warn("[Wu] β οΈ Failed to remove shadow child:",e)}})}catch(e){console.warn("[Wu] β οΈ Shadow root cleanup failed:",e)}if(!o.shadowRoot&&o.children.length>0)try{o.innerHTML=""}catch(e){console.warn("[Wu] β οΈ Container innerHTML cleanup failed:",e)}o.removeAttribute("data-wu-app"),o.removeAttribute("data-quantum-state"),o.removeAttribute("wu-debug")}this.definitions.delete(e),this.sandbox&&this.sandbox.sandboxes&&this.sandbox.sandboxes.delete(e),console.log(`[Wu] β
App state cleaned successfully for ${e}`)}catch(o){console.warn(`[Wu] β οΈ App cleanup partial failure for ${e}:`,o);try{const e=document.querySelector(t);e&&(e.style.display="none",setTimeout(()=>{e&&(e.style.display="")},100))}catch(e){console.error("[Wu] π₯ Emergency cleanup failed:",e)}}}async renderErrorState(e,t,o){try{const s=document.querySelector(e);if(!s)return;s.innerHTML="";const n=document.createElement("div");n.className="quantum-error-state",Object.assign(n.style,{padding:"2rem",borderRadius:"12px",background:"linear-gradient(135deg, #1a1a2e, #16213e)",border:"2px solid #ff6b6b",color:"#fff",fontFamily:'"Courier New", monospace',textAlign:"center",boxShadow:"0 0 20px rgba(255, 107, 107, 0.3)"});const r=document.createElement("div");r.textContent="π",Object.assign(r.style,{fontSize:"3rem",marginBottom:"1rem"});const a=document.createElement("h3");a.textContent="MOUNT ERROR DETECTED",Object.assign(a.style,{color:"#ff6b6b",margin:"0 0 1rem 0"});const i=document.createElement("p");i.textContent=`App "${t}" failed to mount in the container`,Object.assign(i.style,{margin:"0 0 1rem 0",opacity:"0.8"});const l=document.createElement("details");Object.assign(l.style,{margin:"1rem 0",textAlign:"left"});const c=document.createElement("summary");c.textContent="π Debug Info",Object.assign(c.style,{cursor:"pointer",color:"#4ecdc4"});const u=document.createElement("pre");u.textContent=o.message,Object.assign(u.style,{background:"rgba(0,0,0,0.3)",padding:"1rem",borderRadius:"6px",marginTop:"0.5rem",overflow:"auto",fontSize:"0.8rem"});const h=document.createElement("button");h.textContent="π Reload Page",Object.assign(h.style,{background:"linear-gradient(45deg, #4ecdc4, #44a08d)",border:"none",padding:"0.8rem 1.5rem",borderRadius:"6px",color:"white",cursor:"pointer",fontWeight:"bold",transition:"transform 0.2s"}),h.addEventListener("click",()=>window.location.reload()),h.addEventListener("mouseenter",()=>h.style.transform="scale(1.05)"),h.addEventListener("mouseleave",()=>h.style.transform="scale(1)"),l.appendChild(c),l.appendChild(u),n.appendChild(r),n.appendChild(a),n.appendChild(i),n.appendChild(l),n.appendChild(h),s.appendChild(n)}catch(e){console.error("[Wu] π₯ Failed to render error state:",e)}}async loadAndMountRemoteApp(e,t){const o=await this.resolveModulePath(e);console.log(`[Wu] π¦ Loading ES module: ${o}`);try{await this.moduleLoader(o,e.name),console.log(`[Wu] β
ES module loaded: ${e.name}`)}catch(e){throw console.error(`[Wu] β Failed to load ES module ${o}:`,e),e}}async resolveModulePath(e){let t=e.manifest?.entry||"main.js";const o=e.url.replace(/\/$/,"");if(/^(src|dist|public|build|assets|lib|es)\//.test(t)){console.log(`[Wu] π§ Entry already has folder prefix: ${t}`);const e=`${o}/${t}`;return console.log(`[Wu] π― Using direct path: ${e}`),e}const s=[`${o}/src/${t}`,`${o}/${t}`,`${o}/dist/${t}`,`${o}/public/${t}`,`${o}/build/${t}`,`${o}/assets/${t}`,`${o}/lib/${t}`,`${o}/es/${t}`];console.log(`[Wu] π Attempting path resolution for ${e.name}...`);for(let e=0;e<s.length;e++){const t=s[e];try{if(console.log(`[Wu] π― Testing path candidate ${e+1}/${s.length}: ${t}`),await this.validatePath(t))return console.log(`[Wu] β
Path resolved successfully: ${t}`),t;console.log(`[Wu] β Path candidate ${e+1} failed validation: ${t}`)}catch(o){console.log(`[Wu] β οΈ Path candidate ${e+1} threw error: ${t} - ${o.message}`);continue}}const n=s[0];return console.warn(`[Wu] π¨ All path candidates failed, using fallback: ${n}`),n}async validatePath(e){try{console.log(`[Wu] π Testing path: ${e}`);const t=await fetch(e,{method:"GET",cache:"no-cache",signal:AbortSignal.timeout(2e3)});if(!t.ok)return console.log(`[Wu] β Path validation failed - HTTP ${t.status}: ${e}`),!1;const o=t.headers.get("content-type")||"";if(!(o.includes("javascript")||o.includes("module")||o.includes("text/plain")||e.endsWith(".js")||e.endsWith(".mjs")))return console.log(`[Wu] β Path validation failed - Invalid content type '${o}': ${e}`),!1;const s=await t.text(),n=s.trim().toLowerCase();return n.startsWith("<!doctype")||n.startsWith("<html")||n.startsWith("<head")||n.startsWith("<body")||n.startsWith("<!-")?(console.log(`[Wu] β Path validation failed - Server returned HTML fallback page: ${e}`),!1):s.includes("export")||s.includes("import")||s.includes("wu.define")||s.includes("module.exports")||s.includes("console.log")||s.includes("function")&&s.length>10?(console.log(`[Wu] β
Path validation successful: ${e} (${s.length} chars)`),!0):(console.log(`[Wu] β Path validation failed - No valid module content: ${e}`),console.log(`[Wu] π Content preview: ${s.substring(0,100)}...`),!1)}catch(t){return console.log(`[Wu] β Path validation failed for ${e}: ${t.message}`),!1}}async moduleLoader(e,t){if(this.definitions.has(t))return void console.log(`[Wu] β‘ App ${t} already registered`);console.log(`[Wu] π‘ Using event-based registration for ${t}`);try{await import(e)}catch(t){throw console.error(`[Wu] β Failed to import module ${e}:`,t),t}const o=Date.now();for(;!this.definitions.has(t);){if(Date.now()-o>=1e4)throw new Error(`App '${t}' module loaded but wu.define() was not called within 10000ms.\n\nMake sure your module calls:\n wu.define('${t}', { mount, unmount })\n\nOr using window.wu:\n window.wu.define('${t}', { mount, unmount })`);await new Promise(e=>setTimeout(e,50))}console.log(`[Wu] β
App ${t} loaded and registered (verified in definitions)`)}async unmount(e){try{console.log(`[Wu] ποΈ Unmounting ${e}`);const t=this.mounted.get(e);if(!t)return void console.warn(`[Wu] App ${e} not mounted`);if((await this.hooks.execute("beforeUnmount",{appName:e,mounted:t})).cancelled)return void console.warn("[Wu] Unmount cancelled by beforeUnmount hook");if(!1===await this.pluginSystem.callHook("beforeUnmount",{appName:e}))return void console.warn("[Wu] Unmount cancelled by plugin beforeUnmount hook");t.lifecycle?.unmount&&await t.lifecycle.unmount(t.container),this.sandbox.cleanup(t.sandbox),t.poolSandbox&&this.sandboxPool.release(e),this.unobserveContainer(e),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}),console.log(`[Wu] β
${e} unmounted successfully`)}catch(t){throw console.error(`[Wu] β Failed to unmount ${e}:`,t),await this.pluginSystem.callHook("onError",{phase:"unmount",error:t,appName:e}),this.eventBus.emit("app:error",{appName:e,error:t.message},{appName:e}),t}}async use(e){const[t,o]=e.split(".");if(!t||!o)throw new Error(`Invalid component path: ${e}. Use format "app.component"`);const s=this.apps.get(t);if(!s)throw new Error(`App ${t} not registered`);const n=this.manifests.get(t),r=n?.wu?.exports?.[o];if(!r)throw new Error(`Component ${o} not exported by ${t}`);return await this.loader.loadComponent(s.url,r)}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,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()}app(e,t){return new WuApp(e,t,this)}async destroy(){console.log("[Wu] π§Ή Destroying framework...");try{if(await this.hooks.execute("beforeDestroy",{}),await this.pluginSystem.callHook("onDestroy",{}),this.healthState.monitor&&(clearInterval(this.healthState.monitor),this.healthState.monitor=null),this.healthState.containerObservers){for(const[e,t]of this.healthState.containerObservers)t.disconnect();this.healthState.containerObservers.clear()}this.healthState.mutationCheckTimeout&&clearTimeout(this.healthState.mutationCheckTimeout);for(const e of this.mounted.keys())await this.unmount(e);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.sandboxPool.cleanup(),this.registry.cleanup(),this.apps.clear(),this.definitions.clear(),this.manifests.clear(),this.mounted.clear(),this.store.clear(),this.isInitialized=!1,await this.hooks.execute("afterDestroy",{}),console.log("[Wu] β
Framework destroyed")}catch(e){throw console.error("[Wu] β Error during destroy:",e),e}}}exports.wu=void 0,"undefined"!=typeof window&&window.wu&&window.wu._isWuFramework?(exports.wu=window.wu,console.log("π Wu Framework - Reusing existing instance from host")):(exports.wu=new WuCore({healthMonitoring:!0,autoHeal:!0,agingThreshold:1/0,healthCheckInterval:6e4}),exports.wu._isWuFramework=!0),"undefined"!=typeof window&&(window.wu=exports.wu,exports.wu.version||(exports.wu.version="1.0.6",console.log("π Wu Framework loaded - Universal Microfrontends ready"),exports.wu.info={name:"Wu Framework",description:"Universal Microfrontends",features:["Framework Agnostic","Zero Config","Shadow DOM Isolation","Runtime Loading","Component Sharing"]}),exports.wu.emit||(exports.wu.emit=(e,t,o)=>exports.wu.eventBus.emit(e,t,o),exports.wu.on=(e,t)=>exports.wu.eventBus.on(e,t),exports.wu.once=(e,t)=>exports.wu.eventBus.once(e,t),exports.wu.off=(e,t)=>exports.wu.eventBus.off(e,t)),exports.wu.silence||(exports.wu.silence=async()=>{const{silenceAllLogs:e}=await Promise.resolve().then(function(){return wuLogger});e()},exports.wu.verbose=async()=>{const{enableAllLogs:e}=await Promise.resolve().then(function(){return wuLogger});e()}));var wu_default=exports.wu;const init=async e=>await exports.wu.init({apps:e}),mount=async(e,t)=>await exports.wu.mount(e,t),define=(e,t)=>exports.wu.define(e,t),unmount=async e=>await exports.wu.unmount(e),app=(e,t)=>exports.wu.app(e,t),use=async e=>await exports.wu.use(e),getAppInfo=e=>exports.wu.getAppInfo(e),getStats=()=>exports.wu.getStats(),getState=e=>exports.wu.getState(e),setState=(e,t)=>exports.wu.setState(e,t),onStateChange=(e,t)=>exports.wu.onStateChange(e,t),batchState=e=>exports.wu.batchState(e),getStoreMetrics=()=>exports.wu.getStoreMetrics(),clearState=()=>{exports.wu.clearState()},destroy=async()=>await exports.wu.destroy(),configureStyleSharing=e=>exports.wu.sandbox.configureStyleSharing(e),reinjectStyles=async e=>await exports.wu.sandbox.reinjectStyles(e),getStyleStats=()=>exports.wu.sandbox.getStyleStats(),emit=(e,t,o)=>{exports.wu.eventBus.emit(e,t,o)},on=(e,t)=>exports.wu.eventBus.on(e,t),once=(e,t)=>exports.wu.eventBus.once(e,t),off=(e,t)=>{exports.wu.eventBus.off(e,t)},replayEvents=(e,t)=>{exports.wu.eventBus.replay(e,t)},getEventBusStats=()=>exports.wu.eventBus.getStats(),startMeasure=(e,t)=>{exports.wu.performance.startMeasure(e,t)},endMeasure=(e,t)=>exports.wu.performance.endMeasure(e,t),getPerformanceMetrics=e=>exports.wu.performance.getMetrics(e),getAllPerformanceMetrics=()=>exports.wu.performance.getAllMetrics(),generatePerformanceReport=()=>exports.wu.performance.generateReport(),clearPerformanceMetrics=e=>{exports.wu.performance.clearMetrics(e)},usePlugin=(e,t)=>{exports.wu.pluginSystem.use(e,t)},uninstallPlugin=e=>{exports.wu.pluginSystem.uninstall(e)},getPluginStats=()=>exports.wu.pluginSystem.getStats(),useHook=(e,t,o)=>exports.wu.hooks.use(e,t,o),removeHook=(e,t)=>{exports.wu.hooks.remove(e,t)},getHookStats=()=>exports.wu.hooks.getStats(),registerStrategy=(e,t)=>{exports.wu.strategies.register(e,t)},getStrategyStats=()=>exports.wu.strategies.getStats(),registerErrorHandler=e=>{exports.wu.errorBoundary.register(e)},configureErrorBoundary=e=>{exports.wu.errorBoundary.configure(e)},getErrorLog=e=>exports.wu.errorBoundary.getErrorLog(e),getErrorBoundaryStats=()=>exports.wu.errorBoundary.getStats(),configureSandboxPool=e=>{exports.wu.sandboxPool.configure(e)},getSandboxPoolStats=()=>exports.wu.sandboxPool.getStats(),presets={development:e=>{const t=e.map(e=>({...e,url:e.url||`http://localhost:${e.port||3001}`}));return{apps:t,debug:!0,hotReload:!0}},production:e=>({apps:e,debug:!1,cache:!0,preload:!0}),spa:e=>({apps:[{name:"main",url:e.url||window.location.origin,container:e.container||"#app"}]})},dev={enableDebug:()=>{exports.wu.debug=!0,console.log("π Wu Framework debug mode enabled")},disableDebug:()=>{exports.wu.debug=!1,console.log("π Wu Framework debug mode disabled")},inspect:()=>({version:exports.wu.version,stats:exports.wu.getStats(),apps:Array.from(exports.wu.apps.keys()).map(e=>exports.wu.getAppInfo(e))}),reload:async e=>{console.log(`π Reloading app: ${e}`),await exports.wu.unmount(e),exports.wu.loader.clearCache(e),exports.wu.manifest.clearCache(e),await exports.wu.mount(e),console.log(`β
App reloaded: ${e}`)}},events={onAppMounted:e=>{document.addEventListener("wu:app:mounted",e)},onAppUnmounted:e=>{document.addEventListener("wu:app:unmounted",e)},onAppError:e=>{document.addEventListener("wu:app:error",e)},onFrameworkReady:e=>{document.addEventListener("wu:framework:ready",e)}};exports.WuApp=WuApp,exports.WuCache=WuCache,exports.WuCore=WuCore,exports.WuErrorBoundary=WuErrorBoundary,exports.WuEventBus=WuEventBus,exports.WuHtmlParser=WuHtmlParser,exports.WuLifecycleHooks=WuLifecycleHooks,exports.WuLoader=WuLoader,exports.WuLoadingStrategy=WuLoadingStrategy,exports.WuManifest=WuManifest,exports.WuPerformance=WuPerformance,exports.WuPluginSystem=WuPluginSystem,exports.WuProxySandbox=WuProxySandbox,exports.WuRegistry=WuRegistry,exports.WuSandbox=WuSandbox,exports.WuSandboxPool=WuSandboxPool,exports.WuScriptExecutor=WuScriptExecutor,exports.WuSnapshotSandbox=WuSnapshotSandbox,exports.WuStore=WuStore,exports.WuStyleBridge=WuStyleBridge,exports.app=app,exports.batchState=batchState,exports.clearPerformanceMetrics=clearPerformanceMetrics,exports.clearState=clearState,exports.configureErrorBoundary=configureErrorBoundary,exports.configureSandboxPool=configureSandboxPool,exports.configureStyleSharing=configureStyleSharing,exports.createConditionalHook=createConditionalHook,exports.createGuardHook=createGuardHook,exports.createPlugin=createPlugin,exports.createSimpleHook=createSimpleHook,exports.createTimedHook=createTimedHook,exports.createTransformHook=createTransformHook,exports.default=wu_default,exports.define=define,exports.destroy=destroy,exports.dev=dev,exports.emit=emit,exports.enableAllLogs=enableAllLogs,exports.endMeasure=endMeasure,exports.events=events,exports.executeScript=executeScript,exports.executeScripts=executeScripts,exports.generatePerformanceReport=generatePerformanceReport,exports.getAllPerformanceMetrics=getAllPerformanceMetrics,exports.getAppInfo=getAppInfo,exports.getErrorBoundaryStats=getErrorBoundaryStats,exports.getErrorLog=getErrorLog,exports.getEventBusStats=getEventBusStats,exports.getHookStats=getHookStats,exports.getPerformanceMetrics=getPerformanceMetrics,exports.getPluginStats=getPluginStats,exports.getSandboxPoolStats=getSandboxPoolStats,exports.getState=getState,exports.getStats=getStats,exports.getStoreMetrics=getStoreMetrics,exports.getStrategyStats=getStrategyStats,exports.getStyleStats=getStyleStats,exports.init=init,exports.mount=mount,exports.off=off,exports.on=on,exports.onStateChange=onStateChange,exports.once=once,exports.parseHtml=parseHtml,exports.parseHtmlFromUrl=parseHtmlFromUrl,exports.presets=presets,exports.registerErrorHandler=registerErrorHandler,exports.registerStrategy=registerStrategy,exports.reinjectStyles=reinjectStyles,exports.removeHook=removeHook,exports.replayEvents=replayEvents,exports.setState=setState,exports.silenceAllLogs=silenceAllLogs,exports.startMeasure=startMeasure,exports.store=store,exports.uninstallPlugin=uninstallPlugin,exports.unmount=unmount,exports.use=use,exports.useHook=useHook,exports.usePlugin=usePlugin;
|