wu-framework 2.1.0 → 2.1.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +39 -39
- package/README.md +570 -570
- package/dist/adapters/angular/index.d.ts +154 -154
- package/dist/adapters/angular/index.js.map +1 -1
- package/dist/adapters/angular.d.ts +3 -3
- package/dist/adapters/index.js.map +1 -1
- package/dist/adapters/lit/index.d.ts +120 -120
- package/dist/adapters/lit/index.js.map +1 -1
- package/dist/adapters/lit.d.ts +3 -3
- package/dist/adapters/preact/index.d.ts +108 -108
- package/dist/adapters/preact/index.js.map +1 -1
- package/dist/adapters/preact.d.ts +3 -3
- package/dist/adapters/qwik/index.js +1 -1
- package/dist/adapters/qwik/index.js.map +1 -1
- package/dist/adapters/react/index.d.ts +246 -246
- package/dist/adapters/react/index.js.map +1 -1
- package/dist/adapters/react.d.ts +3 -3
- package/dist/adapters/shared.js.map +1 -1
- package/dist/adapters/solid/index.d.ts +101 -101
- package/dist/adapters/solid/index.js.map +1 -1
- package/dist/adapters/solid.d.ts +3 -3
- package/dist/adapters/svelte/index.d.ts +166 -166
- package/dist/adapters/svelte/index.js.map +1 -1
- package/dist/adapters/svelte.d.ts +3 -3
- package/dist/adapters/vanilla/index.d.ts +179 -179
- package/dist/adapters/vanilla/index.js.map +1 -1
- package/dist/adapters/vanilla.d.ts +3 -3
- package/dist/adapters/vue/index.d.ts +299 -299
- package/dist/adapters/vue/index.js.map +1 -1
- package/dist/adapters/vue.d.ts +3 -3
- package/dist/ai/wu-ai.js.map +1 -1
- package/dist/core/wu-html-parser.js +2 -0
- package/dist/core/wu-html-parser.js.map +1 -0
- package/dist/core/wu-iframe-sandbox.js +2 -0
- package/dist/core/wu-iframe-sandbox.js.map +1 -0
- package/dist/core/wu-loader.js +2 -0
- package/dist/core/wu-loader.js.map +1 -0
- package/dist/core/wu-mcp-bridge.js.map +1 -1
- package/dist/core/wu-script-executor.js +2 -0
- package/dist/core/wu-script-executor.js.map +1 -0
- package/dist/wu-ai-browser-primitives-BDKXJlwc.js.map +1 -1
- package/dist/wu-framework.cjs.js +2 -2
- package/dist/wu-framework.cjs.js.map +1 -1
- package/dist/wu-framework.dev.js +8697 -9142
- package/dist/wu-framework.dev.js.map +1 -1
- package/dist/wu-framework.esm.js +2 -2
- package/dist/wu-framework.esm.js.map +1 -1
- package/dist/wu-framework.umd.js +2 -2
- package/dist/wu-framework.umd.js.map +1 -1
- package/dist/wu-logger-fJfUHBGA.js.map +1 -1
- package/integrations/astro/README.md +127 -127
- package/integrations/astro/WuApp.astro +63 -63
- package/integrations/astro/WuShell.astro +39 -39
- package/integrations/astro/index.js +68 -68
- package/integrations/astro/package.json +38 -38
- package/integrations/astro/types.d.ts +53 -53
- package/package.json +218 -218
- package/dist/wu-html-parser.js +0 -2
- package/dist/wu-html-parser.js.map +0 -1
- package/dist/wu-iframe-sandbox.js +0 -2
- package/dist/wu-iframe-sandbox.js.map +0 -1
- package/dist/wu-script-executor.js +0 -2
- package/dist/wu-script-executor.js.map +0 -1
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{l as e}from"./wu-logger-fJfUHBGA.js";class t{constructor(e){this.appName=e,this.iframe=null,this._active=!1,this._timers=new Set,this._intervals=new Set,this._rafs=new Set,this._listeners=[]}activate(t,r,n){if(this._active)return this.iframe.contentWindow;const i=document.createElement("iframe");i.setAttribute("data-wu-sandbox",this.appName),i.style.cssText="display:none !important;position:absolute;width:0;height:0;border:0;",document.body.appendChild(i),this.iframe=i;const a=t.replace(/\/$/,""),s=i.contentWindow,o=s.document;return o.open(),o.write(`<!DOCTYPE html><html><head><base href="${a}/"></head><body></body></html>`),o.close(),s.wu=this._buildRestrictedWu(window.wu),this._patchDocument(s,r,n),this._patchTimers(s),this._active=!0,e.wuDebug(`[IframeSandbox] Activated for ${this.appName} (base: ${a})`),s}_buildRestrictedWu(e){if(!e)return;const t=t=>"function"==typeof t?t.bind(e):t,r=e.store?Object.freeze({get:t(e.store.get),set:t(e.store.set),on:t(e.store.on),batch:t(e.store.batch)}):null,n=e.eventBus?Object.freeze({emit:t(e.eventBus.emit),on:t(e.eventBus.on),off:t(e.eventBus.off),once:t(e.eventBus.once),registerApp:t(e.eventBus.registerApp),unregisterApp:t(e.eventBus.unregisterApp)}):null,i={version:e.version,info:e.info,_isWuFramework:!0,define:t(e.define),mount:t(e.mount),unmount:t(e.unmount),app:t(e.app),hide:t(e.hide),show:t(e.show),isHidden:t(e.isHidden),store:r,eventBus:n,emit:t(e.emit),on:t(e.on),off:t(e.off),once:t(e.once),getState:t(e.getState),setState:t(e.setState),onStateChange:t(e.onStateChange),ai:e.ai,aiReady:t(e.aiReady),getStats:t(e.getStats),getSandboxInfo:t(e.getSandboxInfo),silence:t(e.silence),verbose:t(e.verbose)};return Object.freeze(i)}importModule(t,r=3e4){if(!this._active)throw new Error(`[IframeSandbox] Not active for ${this.appName}`);return new Promise((n,i)=>{const a=`wu_${this.appName}_${Date.now()}`,s=e=>{e.data?.channelId===a&&(c(),e.data.error?i(new Error(e.data.error)):n())},o=setTimeout(()=>{c(),i(new Error(`[IframeSandbox] import() timed out for ${this.appName}: ${t}`))},r),c=()=>{window.removeEventListener("message",s),clearTimeout(o)};window.addEventListener("message",s);const m=this.iframe.contentWindow.document,d=m.createElement("script");d.type="module",d.textContent=`import("${t.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}").then(() => parent.postMessage({ channelId: "${a}", success: true }, '*')).catch(e => parent.postMessage({ channelId: "${a}", error: e.message || String(e) }, '*'));`,m.head.appendChild(d),e.wuDebug(`[IframeSandbox] Importing module: ${t}`)})}_patchDocument(t,r,n){const i=t.document,a=n||r,s=document;i.createElement=(e,t)=>s.createElement(e,t),i.createElementNS=(e,t,r)=>s.createElementNS(e,t,r),i.createTextNode=e=>s.createTextNode(e),i.createComment=e=>s.createComment(e),i.createDocumentFragment=()=>s.createDocumentFragment(),i.querySelector=e=>a.querySelector(e),i.querySelectorAll=e=>a.querySelectorAll(e),i.getElementById=e=>a.querySelector(`#${e}`),i.getElementsByClassName=e=>a.querySelectorAll(`.${e}`),i.getElementsByTagName=e=>a.querySelectorAll(e);try{Object.defineProperty(i,"body",{get:()=>r,configurable:!0})}catch{e.wuDebug("[IframeSandbox] Could not redefine document.body")}const o=i.addEventListener.bind(i),c=i.removeEventListener.bind(i);i.addEventListener=(e,t,r)=>{this._listeners.push({target:i,event:e,handler:t,options:r}),o(e,t,r)},i.removeEventListener=(e,t,r)=>{this._listeners=this._listeners.filter(r=>!(r.target===i&&r.event===e&&r.handler===t)),c(e,t,r)},e.wuDebug(`[IframeSandbox] Document patched for ${this.appName}`)}_patchTimers(t){const r=t.setTimeout.bind(t),n=t.clearTimeout.bind(t),i=t.setInterval.bind(t),a=t.clearInterval.bind(t);if(t.setTimeout=(e,t,...n)=>{const i=r((...t)=>{this._timers.delete(i),"function"==typeof e&&e(...t)},t,...n);return this._timers.add(i),i},t.clearTimeout=e=>{this._timers.delete(e),n(e)},t.setInterval=(e,t,...r)=>{const n=i(e,t,...r);return this._intervals.add(n),n},t.clearInterval=e=>{this._intervals.delete(e),a(e)},t.requestAnimationFrame){const e=t.requestAnimationFrame.bind(t),r=t.cancelAnimationFrame.bind(t);t.requestAnimationFrame=t=>{const r=e((...e)=>{this._rafs.delete(r),t(...e)});return this._rafs.add(r),r},t.cancelAnimationFrame=e=>{this._rafs.delete(e),r(e)}}e.wuDebug(`[IframeSandbox] Timer tracking active for ${this.appName}`)}destroy(){if(this._active){this._active=!1;for(const e of this._timers)try{clearTimeout(e)}catch{}for(const e of this._intervals)try{clearInterval(e)}catch{}for(const e of this._rafs)try{cancelAnimationFrame(e)}catch{}this._timers.clear(),this._intervals.clear(),this._rafs.clear();for(const{target:e,event:t,handler:r,options:n}of this._listeners)try{e.removeEventListener(t,r,n)}catch{}if(this._listeners=[],this.iframe){try{const e=this.iframe.contentDocument;e&&(e.open(),e.write(""),e.close())}catch{}this.iframe.parentNode&&this.iframe.parentNode.removeChild(this.iframe),this.iframe=null}e.wuDebug(`[IframeSandbox] Destroyed for ${this.appName}`)}}isActive(){return this._active}}export{t as WuIframeSandbox};
|
|
2
|
-
//# sourceMappingURL=wu-iframe-sandbox.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"wu-iframe-sandbox.js","sources":["../src/core/wu-iframe-sandbox.js"],"sourcesContent":["/**\r\n * WU-IFRAME-SANDBOX: Real JS isolation using hidden iframes.\r\n *\r\n * Architecture:\r\n * ┌── Main Window ────────────────────────────────┐\r\n * │ ┌── Shadow DOM Container ──────────────────┐ │\r\n * │ │ App renders here (CSS isolated) │ │\r\n * │ └──────────────────────────────────────────┘ │\r\n * │ ┌── Hidden iframe ────────────────────────┐ │\r\n * │ │ import() runs here (REAL modules) │ │\r\n * │ │ window = iframe.contentWindow (ISOLATED)│ │\r\n * │ │ document patched → Shadow DOM │ │\r\n * │ └────────────────────────────────────────-─┘ │\r\n * └───────────────────────────────────────────────┘\r\n *\r\n * Why iframe?\r\n * - import() is REAL → tree shaking, source maps, HMR all work\r\n * - iframe has its own window → globals are isolated\r\n * - Destroying iframe kills all timers/listeners at once\r\n *\r\n * How it works:\r\n * 1. Create hidden iframe with <base href=\"appUrl\"> for URL resolution\r\n * 2. Patch iframe's document: createElement → main document (no ownerDocument issues),\r\n * querySelector/body → Shadow DOM container\r\n * 3. Track timers for guaranteed cleanup (some browsers don't kill iframe timers)\r\n * 4. import() the app module inside iframe → runs in isolated context\r\n * 5. App calls wu.define() → lifecycle registered on parent's WuCore\r\n * 6. On unmount: destroy iframe = nuclear cleanup\r\n *\r\n * Fallback:\r\n * If import() fails (CORS, module errors), wu-core falls back to eval mode\r\n * (fetch HTML + parse + execute with(proxy)).\r\n */\r\n\r\nimport { logger } from './wu-logger.js';\r\n\r\nexport class WuIframeSandbox {\r\n constructor(appName) {\r\n this.appName = appName;\r\n this.iframe = null;\r\n this._active = false;\r\n\r\n // Side-effect tracking for guaranteed cleanup\r\n this._timers = new Set();\r\n this._intervals = new Set();\r\n this._rafs = new Set();\r\n this._listeners = [];\r\n }\r\n\r\n /**\r\n * Create and activate the iframe sandbox.\r\n *\r\n * @param {string} appUrl - App's base URL (for <base href> and relative imports)\r\n * @param {HTMLElement} shadowContainer - Shadow DOM container for DOM redirection\r\n * @param {ShadowRoot|null} shadowRoot - Shadow root for query scoping\r\n * @returns {Window} The iframe's contentWindow (isolated execution context)\r\n */\r\n activate(appUrl, shadowContainer, shadowRoot) {\r\n if (this._active) return this.iframe.contentWindow;\r\n\r\n // 1. Create hidden iframe\r\n const iframe = document.createElement('iframe');\r\n iframe.setAttribute('data-wu-sandbox', this.appName);\r\n iframe.style.cssText = 'display:none !important;position:absolute;width:0;height:0;border:0;';\r\n\r\n // Must be in DOM before accessing contentWindow\r\n document.body.appendChild(iframe);\r\n this.iframe = iframe;\r\n\r\n // 2. Write base HTML with <base href> pointing to app URL.\r\n // This makes relative URL resolution work for fetch(), CSS url(), etc.\r\n // import() of full URLs works regardless of base.\r\n const baseUrl = appUrl.replace(/\\/$/, '');\r\n const iframeWin = iframe.contentWindow;\r\n const iframeDoc = iframeWin.document;\r\n\r\n iframeDoc.open();\r\n iframeDoc.write(\r\n `<!DOCTYPE html><html><head><base href=\"${baseUrl}/\"></head><body></body></html>`\r\n );\r\n iframeDoc.close();\r\n\r\n // 3. Expose a RESTRICTED wu inside the iframe.\r\n //\r\n // Pre-v2.1 we leaked the full `window.wu` — meaning sandboxed app code\r\n // could touch internals like wu.core, wu.cache, wu.errorBoundary,\r\n // wu.pluginSystem, etc. That defeats much of the iframe isolation.\r\n //\r\n // Now we expose only the public surface an app legitimately needs:\r\n // - lifecycle: define, mount, unmount, app, hide, show, isHidden\r\n // - communication: emit, on, off, once\r\n // - state: store (get/set/on), getState/setState/onStateChange\r\n // - AI: ai (lazy proxy, already locked down)\r\n // - meta: version, info, getStats, getSandboxInfo\r\n // - logger: silence, verbose\r\n iframeWin.wu = this._buildRestrictedWu(window.wu);\r\n\r\n // 4. Patch document: redirect DOM operations to Shadow DOM\r\n this._patchDocument(iframeWin, shadowContainer, shadowRoot);\r\n\r\n // 5. Track timers for guaranteed cleanup\r\n this._patchTimers(iframeWin);\r\n\r\n this._active = true;\r\n logger.wuDebug(`[IframeSandbox] Activated for ${this.appName} (base: ${baseUrl})`);\r\n return iframeWin;\r\n }\r\n\r\n /**\r\n * Build a Object.freeze'd, restricted view of `window.wu` for exposing\r\n * inside the iframe. Methods are bound so the app can call them naturally\r\n * (no need to `wu.emit.bind(wu)`); internals are hidden.\r\n *\r\n * @param {object} fullWu - The full framework instance (window.wu)\r\n * @returns {Readonly<object>} Frozen restricted facade\r\n * @private\r\n */\r\n _buildRestrictedWu(fullWu) {\r\n // Tests and SSR-like setups may have no global wu — keep the surface\r\n // optional rather than crashing during activate().\r\n if (!fullWu) return undefined;\r\n\r\n const bind = (fn) => (typeof fn === 'function' ? fn.bind(fullWu) : fn);\r\n\r\n // Wrap nested store so we don't expose its internals (ringbuffer, listeners Map)\r\n const storeFacade = fullWu.store ? Object.freeze({\r\n get: bind(fullWu.store.get),\r\n set: bind(fullWu.store.set),\r\n on: bind(fullWu.store.on),\r\n batch: bind(fullWu.store.batch),\r\n }) : null;\r\n\r\n // EventBus facade: expose pub/sub but not internals (authorizedApps, history, _internalTokens)\r\n const eventBusFacade = fullWu.eventBus ? Object.freeze({\r\n emit: bind(fullWu.eventBus.emit),\r\n on: bind(fullWu.eventBus.on),\r\n off: bind(fullWu.eventBus.off),\r\n once: bind(fullWu.eventBus.once),\r\n registerApp: bind(fullWu.eventBus.registerApp),\r\n unregisterApp: bind(fullWu.eventBus.unregisterApp),\r\n }) : null;\r\n\r\n const facade = {\r\n // Identity\r\n version: fullWu.version,\r\n info: fullWu.info,\r\n _isWuFramework: true,\r\n // Lifecycle the app needs to register itself\r\n define: bind(fullWu.define),\r\n mount: bind(fullWu.mount),\r\n unmount: bind(fullWu.unmount),\r\n app: bind(fullWu.app),\r\n hide: bind(fullWu.hide),\r\n show: bind(fullWu.show),\r\n isHidden: bind(fullWu.isHidden),\r\n // Sub-objects (restricted facades, not raw refs)\r\n store: storeFacade,\r\n eventBus: eventBusFacade,\r\n // Top-level pub/sub shortcuts\r\n emit: bind(fullWu.emit),\r\n on: bind(fullWu.on),\r\n off: bind(fullWu.off),\r\n once: bind(fullWu.once),\r\n // Store shortcuts (read/write only)\r\n getState: bind(fullWu.getState),\r\n setState: bind(fullWu.setState),\r\n onStateChange: bind(fullWu.onStateChange),\r\n // AI proxy is already lazy-loaded + restricted by setupLazyAi\r\n ai: fullWu.ai,\r\n aiReady: bind(fullWu.aiReady),\r\n // Meta\r\n getStats: bind(fullWu.getStats),\r\n getSandboxInfo: bind(fullWu.getSandboxInfo),\r\n // Logging control\r\n silence: bind(fullWu.silence),\r\n verbose: bind(fullWu.verbose),\r\n };\r\n\r\n return Object.freeze(facade);\r\n }\r\n\r\n /**\r\n * Import an ES module inside the iframe via real import().\r\n * Preserves tree shaking, source maps, and Vite HMR.\r\n *\r\n * @param {string} url - Full module URL to import\r\n * @param {number} [timeout=30000] - Max wait time in ms\r\n * @returns {Promise<void>}\r\n */\r\n importModule(url, timeout = 30000) {\r\n if (!this._active) {\r\n throw new Error(`[IframeSandbox] Not active for ${this.appName}`);\r\n }\r\n\r\n return new Promise((resolve, reject) => {\r\n const channelId = `wu_${this.appName}_${Date.now()}`;\r\n\r\n // Listen for import completion via postMessage\r\n const onMessage = (event) => {\r\n if (event.data?.channelId !== channelId) return;\r\n cleanup();\r\n if (event.data.error) {\r\n reject(new Error(event.data.error));\r\n } else {\r\n resolve();\r\n }\r\n };\r\n\r\n const timer = setTimeout(() => {\r\n cleanup();\r\n reject(new Error(\r\n `[IframeSandbox] import() timed out for ${this.appName}: ${url}`\r\n ));\r\n }, timeout);\r\n\r\n const cleanup = () => {\r\n window.removeEventListener('message', onMessage);\r\n clearTimeout(timer);\r\n };\r\n\r\n window.addEventListener('message', onMessage);\r\n\r\n // Inject module script into iframe\r\n const iframeDoc = this.iframe.contentWindow.document;\r\n const script = iframeDoc.createElement('script');\r\n script.type = 'module';\r\n script.textContent =\r\n `import(\"${url.replace(/\\\\/g, '\\\\\\\\').replace(/\"/g, '\\\\\"')}\")` +\r\n `.then(() => parent.postMessage({ channelId: \"${channelId}\", success: true }, '*'))` +\r\n `.catch(e => parent.postMessage({ channelId: \"${channelId}\", error: e.message || String(e) }, '*'));`;\r\n\r\n iframeDoc.head.appendChild(script);\r\n logger.wuDebug(`[IframeSandbox] Importing module: ${url}`);\r\n });\r\n }\r\n\r\n /**\r\n * Patch the iframe's document to redirect DOM operations.\r\n *\r\n * Critical patches:\r\n * - createElement/createTextNode → main document (avoids ownerDocument mismatch)\r\n * React/Vue create nodes and append to Shadow DOM container.\r\n * Nodes must belong to the main document to avoid cross-document adoption issues.\r\n *\r\n * - querySelector/body → Shadow DOM container\r\n * Libraries that query the document will find app elements in the Shadow DOM.\r\n *\r\n * - addEventListener → tracked for cleanup\r\n */\r\n _patchDocument(iframeWin, shadowContainer, shadowRoot) {\r\n const iframeDoc = iframeWin.document;\r\n const queryTarget = shadowRoot || shadowContainer;\r\n const mainDoc = document; // parent document\r\n\r\n // --- Node creation: use main document to avoid ownerDocument mismatch ---\r\n // React uses container.ownerDocument.createElement() internally,\r\n // but other code might use document.createElement() directly.\r\n // By redirecting to main document, all nodes belong to the same document tree.\r\n iframeDoc.createElement = (tag, options) => mainDoc.createElement(tag, options);\r\n iframeDoc.createElementNS = (ns, tag, options) => mainDoc.createElementNS(ns, tag, options);\r\n iframeDoc.createTextNode = (text) => mainDoc.createTextNode(text);\r\n iframeDoc.createComment = (text) => mainDoc.createComment(text);\r\n iframeDoc.createDocumentFragment = () => mainDoc.createDocumentFragment();\r\n\r\n // --- DOM queries: redirect to Shadow DOM ---\r\n iframeDoc.querySelector = (sel) => queryTarget.querySelector(sel);\r\n iframeDoc.querySelectorAll = (sel) => queryTarget.querySelectorAll(sel);\r\n iframeDoc.getElementById = (id) => queryTarget.querySelector(`#${id}`);\r\n iframeDoc.getElementsByClassName = (cls) => queryTarget.querySelectorAll(`.${cls}`);\r\n iframeDoc.getElementsByTagName = (tag) => queryTarget.querySelectorAll(tag);\r\n\r\n // --- document.body → shadow container ---\r\n // Frameworks that append to document.body (portals, modals) will target the Shadow DOM.\r\n try {\r\n Object.defineProperty(iframeDoc, 'body', {\r\n get: () => shadowContainer,\r\n configurable: true\r\n });\r\n } catch {\r\n // Some environments don't allow redefining body — not critical\r\n logger.wuDebug('[IframeSandbox] Could not redefine document.body');\r\n }\r\n\r\n // --- document.addEventListener: track for cleanup ---\r\n const origDocAdd = iframeDoc.addEventListener.bind(iframeDoc);\r\n const origDocRemove = iframeDoc.removeEventListener.bind(iframeDoc);\r\n\r\n iframeDoc.addEventListener = (event, handler, options) => {\r\n this._listeners.push({ target: iframeDoc, event, handler, options });\r\n origDocAdd(event, handler, options);\r\n };\r\n\r\n iframeDoc.removeEventListener = (event, handler, options) => {\r\n this._listeners = this._listeners.filter(\r\n l => !(l.target === iframeDoc && l.event === event && l.handler === handler)\r\n );\r\n origDocRemove(event, handler, options);\r\n };\r\n\r\n logger.wuDebug(`[IframeSandbox] Document patched for ${this.appName}`);\r\n }\r\n\r\n /**\r\n * Patch timers in the iframe for guaranteed cleanup.\r\n * Some browsers don't fully kill timers when an iframe is removed.\r\n * We track all IDs and clear them explicitly on destroy.\r\n */\r\n _patchTimers(iframeWin) {\r\n const origSetTimeout = iframeWin.setTimeout.bind(iframeWin);\r\n const origClearTimeout = iframeWin.clearTimeout.bind(iframeWin);\r\n const origSetInterval = iframeWin.setInterval.bind(iframeWin);\r\n const origClearInterval = iframeWin.clearInterval.bind(iframeWin);\r\n\r\n iframeWin.setTimeout = (fn, ms, ...args) => {\r\n const id = origSetTimeout((...a) => {\r\n this._timers.delete(id);\r\n if (typeof fn === 'function') fn(...a);\r\n }, ms, ...args);\r\n this._timers.add(id);\r\n return id;\r\n };\r\n\r\n iframeWin.clearTimeout = (id) => {\r\n this._timers.delete(id);\r\n origClearTimeout(id);\r\n };\r\n\r\n iframeWin.setInterval = (fn, ms, ...args) => {\r\n const id = origSetInterval(fn, ms, ...args);\r\n this._intervals.add(id);\r\n return id;\r\n };\r\n\r\n iframeWin.clearInterval = (id) => {\r\n this._intervals.delete(id);\r\n origClearInterval(id);\r\n };\r\n\r\n // requestAnimationFrame may not exist in all iframe contexts\r\n if (iframeWin.requestAnimationFrame) {\r\n const origRAF = iframeWin.requestAnimationFrame.bind(iframeWin);\r\n const origCancelRAF = iframeWin.cancelAnimationFrame.bind(iframeWin);\r\n\r\n iframeWin.requestAnimationFrame = (fn) => {\r\n const id = origRAF((...a) => {\r\n this._rafs.delete(id);\r\n fn(...a);\r\n });\r\n this._rafs.add(id);\r\n return id;\r\n };\r\n\r\n iframeWin.cancelAnimationFrame = (id) => {\r\n this._rafs.delete(id);\r\n origCancelRAF(id);\r\n };\r\n }\r\n\r\n logger.wuDebug(`[IframeSandbox] Timer tracking active for ${this.appName}`);\r\n }\r\n\r\n /**\r\n * Destroy the iframe and all side effects.\r\n * Nuclear cleanup: kills everything at once.\r\n */\r\n destroy() {\r\n if (!this._active) return;\r\n this._active = false;\r\n\r\n // 1. Clear all tracked timers\r\n for (const id of this._timers) { try { clearTimeout(id); } catch {} }\r\n for (const id of this._intervals) { try { clearInterval(id); } catch {} }\r\n for (const id of this._rafs) { try { cancelAnimationFrame(id); } catch {} }\r\n this._timers.clear();\r\n this._intervals.clear();\r\n this._rafs.clear();\r\n\r\n // 2. Remove all tracked event listeners\r\n for (const { target, event, handler, options } of this._listeners) {\r\n try { target.removeEventListener(event, handler, options); } catch {}\r\n }\r\n this._listeners = [];\r\n\r\n // 3. Wipe and remove iframe\r\n if (this.iframe) {\r\n try {\r\n const doc = this.iframe.contentDocument;\r\n if (doc) {\r\n doc.open();\r\n doc.write('');\r\n doc.close();\r\n }\r\n } catch {\r\n // Cross-origin or already detached — ignore\r\n }\r\n\r\n if (this.iframe.parentNode) {\r\n this.iframe.parentNode.removeChild(this.iframe);\r\n }\r\n this.iframe = null;\r\n }\r\n\r\n logger.wuDebug(`[IframeSandbox] Destroyed for ${this.appName}`);\r\n }\r\n\r\n /**\r\n * Check if this sandbox is active.\r\n * @returns {boolean}\r\n */\r\n isActive() {\r\n return this._active;\r\n }\r\n}\r\n"],"names":["WuIframeSandbox","constructor","appName","this","iframe","_active","_timers","Set","_intervals","_rafs","_listeners","activate","appUrl","shadowContainer","shadowRoot","contentWindow","document","createElement","setAttribute","style","cssText","body","appendChild","baseUrl","replace","iframeWin","iframeDoc","open","write","close","wu","_buildRestrictedWu","window","_patchDocument","_patchTimers","logger","wuDebug","fullWu","bind","fn","storeFacade","store","Object","freeze","get","set","on","batch","eventBusFacade","eventBus","emit","off","once","registerApp","unregisterApp","facade","version","info","_isWuFramework","define","mount","unmount","app","hide","show","isHidden","getState","setState","onStateChange","ai","aiReady","getStats","getSandboxInfo","silence","verbose","importModule","url","timeout","Error","Promise","resolve","reject","channelId","Date","now","onMessage","event","data","cleanup","error","timer","setTimeout","removeEventListener","clearTimeout","addEventListener","script","type","textContent","head","queryTarget","mainDoc","tag","options","createElementNS","ns","createTextNode","text","createComment","createDocumentFragment","querySelector","sel","querySelectorAll","getElementById","id","getElementsByClassName","cls","getElementsByTagName","defineProperty","configurable","origDocAdd","origDocRemove","handler","push","target","filter","l","origSetTimeout","origClearTimeout","origSetInterval","setInterval","origClearInterval","clearInterval","ms","args","a","delete","add","requestAnimationFrame","origRAF","origCancelRAF","cancelAnimationFrame","destroy","clear","doc","contentDocument","parentNode","removeChild","isActive"],"mappings":"4CAoCO,MAAMA,EACX,WAAAC,CAAYC,GACVC,KAAKD,QAAUA,EACfC,KAAKC,OAAS,KACdD,KAAKE,SAAU,EAGfF,KAAKG,QAAU,IAAIC,IACnBJ,KAAKK,WAAa,IAAID,IACtBJ,KAAKM,MAAQ,IAAIF,IACjBJ,KAAKO,WAAa,EACpB,CAUA,QAAAC,CAASC,EAAQC,EAAiBC,GAChC,GAAIX,KAAKE,QAAS,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c1B,GAElB,CAEA9E,EAAOC,QAAQ,6CAA6CjC,KAAKD,UACnE,CAMA,OAAA2I,GACE,GAAK1I,KAAKE,QAAV,CACAF,KAAKE,SAAU,EAGf,IAAK,MAAM4G,KAAM9G,KAAKG,QAAW,IAAMuF,aAAaoB,EAAK,CAAE,MAAO,CAClE,IAAK,MAAMA,KAAM9G,KAAKK,WAAc,IAAM2H,cAAclB,EAAK,CAAE,MAAO,CACtE,IAAK,MAAMA,KAAM9G,KAAKM,MAAS,IAAMmI,qBAAqB3B,EAAK,CAAE,MAAO,CACxE9G,KAAKG,QAAQwI,QACb3I,KAAKK,WAAWsI,QAChB3I,KAAKM,MAAMqI,QAGX,IAAK,MAAMnB,OAAEA,EAAMrC,MAAEA,EAAKmC,QAAEA,EAAOnB,QAAEA,KAAanG,KAAKO,WACrD,IAAMiH,EAAO/B,oBAAoBN,EAAOmC,EAASnB,EAAU,CAAE,MAAO,CAKtE,GAHAnG,KAAKO,WAAa,GAGdP,KAAKC,OAAQ,CACf,IACE,MAAM2I,EAAM5I,KAAKC,OAAO4I,gBACpBD,IACFA,EAAIpH,OACJoH,EAAInH,MAAM,IACVmH,EAAIlH,QAER,CAAE,MAEF,CAEI1B,KAAKC,OAAO6I,YACd9I,KAAKC,OAAO6I,WAAWC,YAAY/I,KAAKC,QAE1CD,KAAKC,OAAS,IAChB,CAEA+B,EAAOC,QAAQ,iCAAiCjC,KAAKD,UApClC,CAqCrB,CAMA,QAAAiJ,GACE,OAAOhJ,KAAKE,OACd"}
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{l as t}from"./wu-logger-fJfUHBGA.js";class r{static DANGEROUS_PATTERNS=[{pattern:/constructor\s*\[\s*['"`]constructor['"`]\s*\]/,label:"constructor chain access (sandbox escape)"},{pattern:/__proto__/,label:"__proto__ access (prototype pollution)"},{pattern:/Object\s*\.\s*getPrototypeOf\s*\(\s*proxy\s*\)/,label:"Object.getPrototypeOf(proxy) (sandbox escape)"},{pattern:/Function\s*\(\s*['"`]/,label:"Function() constructor (dynamic code generation)"},{pattern:/\beval\s*\(/,label:"eval() (dynamic code execution)"},{pattern:/\bimport\s*\(/,label:"import() (dynamic import escapes sandbox)"},{pattern:/document\s*\.\s*cookie/,label:"document.cookie (direct cookie access)"}];_validateScript(e,o){for(const{pattern:c,label:n}of r.DANGEROUS_PATTERNS)if(c.test(e)){const r=`[ScriptExecutor] Blocked dangerous pattern in "${o}": ${n}`;throw t.wuError(r),new Error(r)}}execute(r,e,o,c={}){const{strictGlobal:n=!0,sourceUrl:s=""}=c;if(!r||!r.trim())return;this._validateScript(r,e);const a=s?`\n//# sourceURL=wu-sandbox:///${e}/${s}\n`:"";let i;i=n?`;(function(window, self, globalThis, top, parent) {\n with(window) {\n ;${r}${a}\n }\n}).call(proxy, proxy, proxy, proxy, proxy, proxy);`:`;(function(window, self, globalThis, top, parent) {\n ;${r}${a}\n}).call(proxy, proxy, proxy, proxy, proxy, proxy);`;try{return new Function("proxy",i)(o)}catch(s){if(n)return t.wuWarn(`[ScriptExecutor] strictGlobal failed for ${e}, retrying without with(): ${s.message}`),this.execute(r,e,o,{...c,strictGlobal:!1});throw t.wuError(`[ScriptExecutor] Execution failed for ${e}:`,s),s}}async fetchScript(t){const r=await fetch(t);if(!r.ok)throw new Error(`Failed to fetch script ${t}: HTTP ${r.status}`);return r.text()}async executeAll(r,e,o,c={}){for(const n of r){let r=n.content;!r&&n.src&&(t.wuDebug(`[ScriptExecutor] Fetching external script: ${n.src}`),r=await this.fetchScript(n.src)),r&&r.trim()&&this.execute(r,e,o,{...c,sourceUrl:n.src||c.sourceUrl||""})}t.wuDebug(`[ScriptExecutor] Executed ${r.length} scripts for ${e}`)}}export{r as WuScriptExecutor};
|
|
2
|
-
//# sourceMappingURL=wu-script-executor.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"wu-script-executor.js","sources":["../src/core/wu-script-executor.js"],"sourcesContent":["/**\r\n * WU-SCRIPT-EXECUTOR: Execute scripts inside a Proxy sandbox.\r\n *\r\n * Two isolation levels:\r\n * - strictGlobal: true → with(proxy) { code } — all global access goes through proxy\r\n * - strictGlobal: false → (function(window){ code })(proxy) — only explicit window.xxx\r\n *\r\n * This is what makes the sandbox REAL instead of decorative.\r\n * Without this, import() runs code in global scope and the proxy is just a cleanup tracker.\r\n * With this, code receives the proxy as \"window\" and every setTimeout, addEventListener,\r\n * document.querySelector, localStorage access goes through the proxy's traps.\r\n */\r\n\r\nimport { logger } from './wu-logger.js';\r\n\r\nexport class WuScriptExecutor {\r\n\r\n /**\r\n * Dangerous patterns that indicate prototype pollution, sandbox escape,\r\n * or direct access to sensitive APIs. Each entry is a regex paired with\r\n * a human-readable label used in error messages.\r\n *\r\n * This is a tripwire, not a full parser. It catches the most common\r\n * attack vectors without the overhead of AST analysis.\r\n */\r\n static DANGEROUS_PATTERNS = [\r\n // Prototype pollution vectors\r\n { pattern: /constructor\\s*\\[\\s*['\"`]constructor['\"`]\\s*\\]/, label: 'constructor chain access (sandbox escape)' },\r\n { pattern: /__proto__/, label: '__proto__ access (prototype pollution)' },\r\n\r\n // Sandbox escape via proxy introspection\r\n { pattern: /Object\\s*\\.\\s*getPrototypeOf\\s*\\(\\s*proxy\\s*\\)/, label: 'Object.getPrototypeOf(proxy) (sandbox escape)' },\r\n\r\n // Dynamic code generation that bypasses the sandbox\r\n { pattern: /Function\\s*\\(\\s*['\"`]/, label: 'Function() constructor (dynamic code generation)' },\r\n { pattern: /\\beval\\s*\\(/, label: 'eval() (dynamic code execution)' },\r\n\r\n // Dynamic import escapes the sandbox entirely (runs in global scope)\r\n { pattern: /\\bimport\\s*\\(/, label: 'import() (dynamic import escapes sandbox)' },\r\n\r\n // Direct cookie access (should go through proxy traps, not raw document)\r\n { pattern: /document\\s*\\.\\s*cookie/, label: 'document.cookie (direct cookie access)' },\r\n ];\r\n\r\n /**\r\n * Validate script text against known dangerous patterns before execution.\r\n * Throws if any pattern matches. This is intentionally lightweight --\r\n * pattern detection only, not a full parse.\r\n *\r\n * @param {string} scriptText - The raw script to validate\r\n * @param {string} appName - App identifier (for error context)\r\n * @throws {Error} If a dangerous pattern is detected\r\n */\r\n _validateScript(scriptText, appName) {\r\n for (const { pattern, label } of WuScriptExecutor.DANGEROUS_PATTERNS) {\r\n if (pattern.test(scriptText)) {\r\n const msg = `[ScriptExecutor] Blocked dangerous pattern in \"${appName}\": ${label}`;\r\n logger.wuError(msg);\r\n throw new Error(msg);\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Execute a script string inside the proxy sandbox.\r\n *\r\n * @param {string} scriptText - JavaScript code to execute\r\n * @param {string} appName - App identifier (for logging)\r\n * @param {Proxy} proxy - The activated proxy sandbox\r\n * @param {Object} [options]\r\n * @param {boolean} [options.strictGlobal=true] - Use with(proxy) for maximum isolation\r\n * @param {string} [options.sourceUrl=''] - Source URL for devtools (//# sourceURL)\r\n * @returns {*} Return value of the executed code\r\n */\r\n execute(scriptText, appName, proxy, options = {}) {\r\n const { strictGlobal = true, sourceUrl = '' } = options;\r\n\r\n if (!scriptText || !scriptText.trim()) return;\r\n\r\n this._validateScript(scriptText, appName);\r\n\r\n const sourceComment = sourceUrl ? `\\n//# sourceURL=wu-sandbox:///${appName}/${sourceUrl}\\n` : '';\r\n\r\n let wrappedCode;\r\n\r\n if (strictGlobal) {\r\n // MAXIMUM ISOLATION\r\n // with(window) makes ALL unqualified identifiers (setTimeout, fetch, document, etc.)\r\n // resolve through the proxy's has/get traps, not the real window.\r\n // Note: 'use strict' inside the with block becomes a no-op string expression,\r\n // so bundled code with strict mode still works.\r\n wrappedCode = `;(function(window, self, globalThis, top, parent) {\r\n with(window) {\r\n ;${scriptText}${sourceComment}\r\n }\r\n}).call(proxy, proxy, proxy, proxy, proxy, proxy);`;\r\n } else {\r\n // IIFE ONLY — only explicit window.xxx goes through proxy\r\n wrappedCode = `;(function(window, self, globalThis, top, parent) {\r\n ;${scriptText}${sourceComment}\r\n}).call(proxy, proxy, proxy, proxy, proxy, proxy);`;\r\n }\r\n\r\n try {\r\n // new Function('proxy', code) creates a function with 'proxy' as the single param.\r\n // This avoids polluting scope — the only bridge to the sandbox is the proxy argument.\r\n const fn = new Function('proxy', wrappedCode);\r\n return fn(proxy);\r\n } catch (error) {\r\n // If strictGlobal failed (rare edge case with with-statement), retry without it\r\n if (strictGlobal) {\r\n logger.wuWarn(`[ScriptExecutor] strictGlobal failed for ${appName}, retrying without with(): ${error.message}`);\r\n return this.execute(scriptText, appName, proxy, { ...options, strictGlobal: false });\r\n }\r\n logger.wuError(`[ScriptExecutor] Execution failed for ${appName}:`, error);\r\n throw error;\r\n }\r\n }\r\n\r\n /**\r\n * Fetch script content from a URL.\r\n * @param {string} url - Script URL\r\n * @returns {Promise<string>} Script text\r\n */\r\n async fetchScript(url) {\r\n const response = await fetch(url);\r\n if (!response.ok) {\r\n throw new Error(`Failed to fetch script ${url}: HTTP ${response.status}`);\r\n }\r\n return response.text();\r\n }\r\n\r\n /**\r\n * Execute an array of scripts in sequence inside the proxy.\r\n * External scripts (with src) are fetched first.\r\n *\r\n * @param {Array<{content?: string, src?: string}>} scripts\r\n * @param {string} appName\r\n * @param {Proxy} proxy\r\n * @param {Object} [options]\r\n */\r\n async executeAll(scripts, appName, proxy, options = {}) {\r\n for (const script of scripts) {\r\n let text = script.content;\r\n\r\n if (!text && script.src) {\r\n logger.wuDebug(`[ScriptExecutor] Fetching external script: ${script.src}`);\r\n text = await this.fetchScript(script.src);\r\n }\r\n\r\n if (text && text.trim()) {\r\n this.execute(text, appName, proxy, {\r\n ...options,\r\n sourceUrl: script.src || options.sourceUrl || ''\r\n });\r\n }\r\n }\r\n\r\n logger.wuDebug(`[ScriptExecutor] Executed ${scripts.length} scripts for ${appName}`);\r\n }\r\n}\r\n"],"names":["WuScriptExecutor","static","pattern","label","_validateScript","scriptText","appName","DANGEROUS_PATTERNS","test","msg","logger","wuError","Error","execute","proxy","options","strictGlobal","sourceUrl","trim","this","sourceComment","wrappedCode","Function","fn","error","wuWarn","message","fetchScript","url","response","fetch","ok","status","text","executeAll","scripts","script","content","src","wuDebug","length"],"mappings":"4CAeO,MAAMA,EAUXC,0BAA4B,CAE1B,CAAEC,QAAS,gDAAiDC,MAAO,6CACnE,CAAED,QAAS,YAAaC,MAAO,0CAG/B,CAAED,QAAS,iDAAkDC,MAAO,iDAGpE,CAAED,QAAS,wBAAyBC,MAAO,oDAC3C,CAAED,QAAS,cAAeC,MAAO,mCAGjC,CAAED,QAAS,gBAAiBC,MAAO,6CAGnC,CAAED,QAAS,yBAA0BC,MAAO,2CAY9C,eAAAC,CAAgBC,EAAYC,GAC1B,IAAK,MAAMJ,QAAEA,EAAOC,MAAEA,KAAWH,EAAiBO,mBAChD,GAAIL,EAAQM,KAAKH,GAAa,CAC5B,MAAMI,EAAM,kDAAkDH,OAAaH,IAE3E,MADAO,EAAOC,QAAQF,GACT,IAAIG,MAAMH,EAClB,CAEJ,CAaA,OAAAI,CAAQR,EAAYC,EAASQ,EAAOC,EAAU,CAAA,GAC5C,MAAMC,aAAEA,GAAe,EAAIC,UAAEA,EAAY,IAAOF,EAEhD,IAAKV,IAAeA,EAAWa,OAAQ,OAEvCC,KAAKf,gBAAgBC,EAAYC,GAEjC,MAAMc,EAAgBH,EAAY,iCAAiCX,KAAWW,MAAgB,GAE9F,IAAII,EAQFA,EANEL,EAMY,+EAEbX,IAAae,6DAKA,2DACff,IAAae,wDAId,IAIE,OADW,IAAIE,SAAS,QAASD,EAC1BE,CAAGT,EACZ,CAAE,MAAOU,GAEP,GAAIR,EAEF,OADAN,EAAOe,OAAO,4CAA4CnB,+BAAqCkB,EAAME,WAC9FP,KAAKN,QAAQR,EAAYC,EAASQ,EAAO,IAAKC,EAASC,cAAc,IAG9E,MADAN,EAAOC,QAAQ,yCAAyCL,KAAYkB,GAC9DA,CACR,CACF,CAOA,iBAAMG,CAAYC,GAChB,MAAMC,QAAiBC,MAAMF,GAC7B,IAAKC,EAASE,GACZ,MAAM,IAAInB,MAAM,0BA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