import{a as k,t as M,i as C}from"./vendor-lit-BtHfzs80.js";class v{constructor(){this.logs=[],this.completionError=null,this.completed=!1}getData(){return{}}getDescription(){return""}getRuntime(){return e=>{window.__originalConsole||(window.__originalConsole={log:console.log.bind(console),error:console.error.bind(console),warn:console.warn.bind(console),info:console.info.bind(console)});const n=window.__originalConsole,r=[];["log","error","warn","info"].forEach(t=>{console[t]=(...a)=>{const c=a.map(l=>{try{return typeof l=="object"?JSON.stringify(l):String(l)}catch{return String(l)}}).join(" ");if(n[t].apply(console,a),window.sendRuntimeMessage){const l=window.sendRuntimeMessage({type:"console",method:t,text:c,args:a}).catch(()=>{});r.push(l)}}}),window.onCompleted&&window.onCompleted(async t=>{r.length>0&&await Promise.all(r)});let s=null;window.addEventListener("error",t=>{const a=`${t.error?.stack||t.message||String(t)} at line ${t.lineno||"?"}:${t.colno||"?"}`;s={message:t.error?.message||t.message||String(t),stack:t.error?.stack||a}}),window.addEventListener("unhandledrejection",t=>{const a=`Unhandled promise rejection: ${t.reason?.message||t.reason||"Unknown error"}`;s={message:t.reason?.message||String(t.reason)||"Unhandled promise rejection",stack:t.reason?.stack||a}});let o=!1;window.complete=async(t,a)=>{if(o)return;o=!0;const c=t||s;window.sendRuntimeMessage&&(c?await window.sendRuntimeMessage({type:"execution-error",error:c}):await window.sendRuntimeMessage({type:"execution-complete",returnValue:a}))}}}async handleMessage(e,n){e.type==="console"&&(this.logs.push({type:e.method==="error"?"error":e.method==="warn"?"warn":e.method==="info"?"info":"log",text:e.text,args:e.args}),n({success:!0}))}getLogs(){return this.logs}isCompleted(){return this.completed}getCompletionError(){return this.completionError}reset(){this.logs=[],this.completionError=null,this.completed=!1}}class h{static generateBridgeCode(e){return e.context==="sandbox-iframe"?h.generateSandboxBridge(e.sandboxId):h.generateUserScriptBridge(e.sandboxId)}static generateSandboxBridge(e){return`
window.__completionCallbacks = [];
window.sendRuntimeMessage = async (message) => {
    const messageId = 'msg_' + Date.now() + '_' + Math.random().toString(36).substring(2, 9);

    return new Promise((resolve, reject) => {
        const handler = (e) => {
            if (e.data.type === 'runtime-response' && e.data.messageId === messageId) {
                window.removeEventListener('message', handler);
                if (e.data.success) {
                    resolve(e.data);
                } else {
                    reject(new Error(e.data.error || 'Operation failed'));
                }
            }
        };

        window.addEventListener('message', handler);

        window.parent.postMessage({
            ...message,
            sandboxId: ${JSON.stringify(e)},
            messageId: messageId
        }, '*');

        // Timeout after 30s
        setTimeout(() => {
            window.removeEventListener('message', handler);
            reject(new Error('Runtime message timeout'));
        }, 30000);
    });
};
window.onCompleted = (callback) => {
    window.__completionCallbacks.push(callback);
};
`.trim()}static generateUserScriptBridge(e){return`
window.__completionCallbacks = [];
window.sendRuntimeMessage = async (message) => {
    return await chrome.runtime.sendMessage({
        ...message,
        sandboxId: ${JSON.stringify(e)}
    });
};
window.onCompleted = (callback) => {
    window.__completionCallbacks.push(callback);
};
`.trim()}}class _{constructor(){this.sandboxes=new Map,this.messageListener=null,this.userScriptMessageListener=null}registerSandbox(e,n,r){this.sandboxes.set(e,{sandboxId:e,iframe:null,providers:n,consumers:new Set(r)}),this.setupListener()}setSandboxIframe(e,n){const r=this.sandboxes.get(e);r&&(r.iframe=n)}unregisterSandbox(e){this.sandboxes.delete(e),this.sandboxes.size===0&&(this.messageListener&&(window.removeEventListener("message",this.messageListener),this.messageListener=null),this.userScriptMessageListener&&typeof chrome<"u"&&chrome.runtime?.onUserScriptMessage&&(chrome.runtime.onUserScriptMessage.removeListener(this.userScriptMessageListener),this.userScriptMessageListener=null))}addConsumer(e,n){const r=this.sandboxes.get(e);r&&r.consumers.add(n)}removeConsumer(e,n){const r=this.sandboxes.get(e);r&&r.consumers.delete(n)}setupListener(){if(this.messageListener||(this.messageListener=async e=>{const{sandboxId:n,messageId:r}=e.data;if(!n)return;const s=this.sandboxes.get(n);if(!s)return;const o=t=>{s.iframe?.contentWindow?.postMessage({type:"runtime-response",messageId:r,sandboxId:n,...t},"*")};for(const t of s.providers)t.handleMessage&&await t.handleMessage(e.data,o);for(const t of s.consumers)await t.handleMessage(e.data)},window.addEventListener("message",this.messageListener)),!this.userScriptMessageListener){if(typeof chrome>"u"||!chrome.runtime?.onUserScriptMessage)return;this.userScriptMessageListener=(e,n,r)=>{const{sandboxId:s}=e;if(!s)return!1;const o=this.sandboxes.get(s);if(!o)return!1;const t=a=>{r({...a,sandboxId:s})};return(async()=>{for(const a of o.providers)a.handleMessage&&await a.handleMessage(e,t);for(const a of o.consumers)await a.handleMessage(e)})(),!0},chrome.runtime.onUserScriptMessage.addListener(this.userScriptMessageListener)}}}const m=new _;var P=Object.defineProperty,U=Object.getOwnPropertyDescriptor,S=(i,e,n,r)=>{for(var s=r>1?void 0:r?U(e,n):e,o=i.length-1,t;o>=0;o--)(t=i[o])&&(s=(r?t(e,n,s):t(s))||s);return r&&s&&P(e,n,s),s};function H(i){return i.replace(/<\/script/gi,"<\\/script")}let b=class extends C{createRenderRoot(){return this}connectedCallback(){super.connectedCallback()}disconnectedCallback(){super.disconnectedCallback(),this.iframe?.remove()}loadContent(i,e,n=[],r=[]){try{m.unregisterSandbox(i)}catch{}n=[new v,...n],m.registerSandbox(i,n,r);const s=this.prepareHtmlDocument(i,e,n,{isHtmlArtifact:!0,isStandalone:!1}),o=this.validateHtml(s);if(o){console.error("HTML validation failed:",o),this.iframe?.remove(),this.iframe=document.createElement("iframe"),this.iframe.style.cssText="width: 100%; height: 100%; border: none;",this.iframe.srcdoc=`
				<html>
				<body style="font-family: monospace; padding: 20px; background: #fff; color: #000;">
					<h3 style="color: #c00;">HTML Validation Error</h3>
					<pre style="background: #f5f5f5; padding: 10px; border-radius: 4px; overflow-x: auto; white-space: pre-wrap;">${o}</pre>
				</body>
				</html>
			`,this.appendChild(this.iframe);return}this.iframe?.remove(),this.sandboxUrlProvider?this.loadViaSandboxUrl(i,s):this.loadViaSrcdoc(i,s)}loadViaSandboxUrl(i,e){this.iframe=document.createElement("iframe"),this.iframe.sandbox.add("allow-scripts"),this.iframe.sandbox.add("allow-modals"),this.iframe.style.width="100%",this.iframe.style.height="100%",this.iframe.style.border="none",this.iframe.src=this.sandboxUrlProvider(),m.setSandboxIframe(i,this.iframe);const n=o=>{if(o.data.type==="open-external-url"&&o.source===this.iframe?.contentWindow){const t=globalThis.chrome;t?.tabs?t.tabs.create({url:o.data.url}):window.open(o.data.url,"_blank")}};window.addEventListener("message",n);const r=o=>{o.data.type==="sandbox-ready"&&o.source===this.iframe?.contentWindow&&(window.removeEventListener("message",r),window.removeEventListener("message",s),this.iframe?.contentWindow?.postMessage({type:"sandbox-load",sandboxId:i,code:e},"*"))},s=o=>{o.data.type==="sandbox-error"&&o.source===this.iframe?.contentWindow&&(window.removeEventListener("message",r),window.removeEventListener("message",s),window.postMessage({sandboxId:i,type:"execution-error",error:{message:o.data.error,stack:o.data.stack}},"*"))};window.addEventListener("message",r),window.addEventListener("message",s),this.appendChild(this.iframe)}loadViaSrcdoc(i,e){this.iframe=document.createElement("iframe"),this.iframe.sandbox.add("allow-scripts"),this.iframe.sandbox.add("allow-modals"),this.iframe.style.width="100%",this.iframe.style.height="100%",this.iframe.style.border="none",this.iframe.srcdoc=e,m.setSandboxIframe(i,this.iframe);const n=r=>{r.data.type==="open-external-url"&&r.source===this.iframe?.contentWindow&&window.open(r.data.url,"_blank")};window.addEventListener("message",n),this.appendChild(this.iframe)}async execute(i,e,n=[],r=[],s,o=!1){if(s?.aborted)throw new Error("Execution aborted");const t=new v;n=[t,...n],m.registerSandbox(i,n,r);for(const l of n)l.onExecutionStart?.(i,s);const a=[];let c=!1;return new Promise((l,p)=>{const E={async handleMessage(d){d.type==="file-returned"?a.push({fileName:d.fileName,content:d.content,mimeType:d.mimeType}):d.type==="execution-complete"?(c=!0,u(),l({success:!0,console:t.getLogs(),files:a,returnValue:d.returnValue})):d.type==="execution-error"&&(c=!0,u(),l({success:!1,console:t.getLogs(),error:d.error,files:a}))}};m.addConsumer(i,E);const u=()=>{for(const d of n)d.onExecutionEnd?.(i);m.unregisterSandbox(i),s?.removeEventListener("abort",y),clearTimeout(L),this.iframe?.remove(),this.iframe=void 0},y=()=>{c||(c=!0,u(),p(new Error("Execution aborted")))};s&&s.addEventListener("abort",y);const L=setTimeout(()=>{c||(c=!0,u(),l({success:!1,console:t.getLogs(),error:{message:"Execution timeout (120s)",stack:""},files:a}))},12e4),w=this.prepareHtmlDocument(i,e,n,{isHtmlArtifact:o,isStandalone:!1}),x=this.validateHtml(w);if(x){p(new Error(`HTML validation failed: ${x}`));return}if(this.sandboxUrlProvider){this.iframe=document.createElement("iframe"),this.iframe.sandbox.add("allow-scripts","allow-modals"),this.iframe.style.cssText="width: 100%; height: 100%; border: none;",this.iframe.src=this.sandboxUrlProvider(),m.setSandboxIframe(i,this.iframe);const d=f=>{f.data.type==="sandbox-ready"&&f.source===this.iframe?.contentWindow&&(window.removeEventListener("message",d),window.removeEventListener("message",g),this.iframe?.contentWindow?.postMessage({type:"sandbox-load",sandboxId:i,code:w},"*"))},g=f=>{f.data.type==="sandbox-error"&&f.source===this.iframe?.contentWindow&&(window.removeEventListener("message",d),window.removeEventListener("message",g),window.postMessage({sandboxId:i,type:"execution-error",error:{message:f.data.error,stack:f.data.stack}},"*"))};window.addEventListener("message",d),window.addEventListener("message",g),this.appendChild(this.iframe)}else this.iframe=document.createElement("iframe"),this.iframe.sandbox.add("allow-scripts","allow-modals"),this.iframe.style.cssText="width: 100%; height: 100%; border: none; display: none;",this.iframe.srcdoc=w,m.setSandboxIframe(i,this.iframe),this.appendChild(this.iframe)})}validateHtml(i){try{const r=new DOMParser().parseFromString(i,"text/html").querySelector("parsererror");return r?r.textContent||"Unknown parse error":null}catch(e){return e.message||"Unknown validation error"}}prepareHtmlDocument(i,e,n=[],r){const s={isHtmlArtifact:!1,isStandalone:!1,...r},o=this.getRuntimeScript(i,n,s.isStandalone||!1);if(s.isHtmlArtifact){const t=e.match(/<head[^>]*>/i);if(t){const c=t.index+t[0].length;return e.slice(0,c)+o+e.slice(c)}const a=e.match(/<html[^>]*>/i);if(a){const c=a.index+a[0].length;return e.slice(0,c)+o+e.slice(c)}return o+e}else{const t=H(e);return`<!DOCTYPE html>
<html>
<head>
	${o}
</head>
<body>
	<script type="module">
		(async () => {
			try {
				// Wrap user code in async function to capture return value
				const userCodeFunc = async () => {
					${t}
				};

				const returnValue = await userCodeFunc();

				// Call completion callbacks before complete()
				if (window.__completionCallbacks && window.__completionCallbacks.length > 0) {
					try {
						await Promise.all(window.__completionCallbacks.map(cb => cb(true)));
					} catch (e) {
						console.error('Completion callback error:', e);
					}
				}

				await window.complete(null, returnValue);
			} catch (error) {

				// Call completion callbacks before complete() (error path)
				if (window.__completionCallbacks && window.__completionCallbacks.length > 0) {
					try {
						await Promise.all(window.__completionCallbacks.map(cb => cb(false)));
					} catch (e) {
						console.error('Completion callback error:', e);
					}
				}

				await window.complete({
					message: error?.message || String(error),
					stack: error?.stack || new Error().stack
				});
			}
		})();
	<\/script>
</body>
</html>`}}getRuntimeScript(i,e=[],n=!1){const r={};for(const c of e)Object.assign(r,c.getData());const s=n?"":h.generateBridgeCode({context:"sandbox-iframe",sandboxId:i}),o=[];for(const c of e)o.push(`(${c.getRuntime().toString()})(${JSON.stringify(i)});`);const t=Object.entries(r).map(([c,l])=>{const p=JSON.stringify(l).replace(/<\/script/gi,"<\\/script");return`window.${c} = ${p};`}).join(`
`),a=n?"":`
// Navigation interceptor: prevent all navigation and open externally
(function() {
	// Intercept link clicks
	document.addEventListener('click', function(e) {
		const link = e.target.closest('a');
		if (link && link.href) {
			// Check if it's an external link (not javascript: or #hash)
			if (link.href.startsWith('http://') || link.href.startsWith('https://')) {
				e.preventDefault();
				e.stopPropagation();
				window.parent.postMessage({ type: 'open-external-url', url: link.href }, '*');
			}
		}
	}, true);

	// Intercept form submissions
	document.addEventListener('submit', function(e) {
		const form = e.target;
		if (form && form.action) {
			e.preventDefault();
			e.stopPropagation();
			window.parent.postMessage({ type: 'open-external-url', url: form.action }, '*');
		}
	}, true);

	// Prevent window.location changes (only if not already redefined)
	try {
		const originalLocation = window.location;
		Object.defineProperty(window, 'location', {
			get: function() { return originalLocation; },
			set: function(url) {
				window.parent.postMessage({ type: 'open-external-url', url: url.toString() }, '*');
			}
		});
	} catch (e) {
		// Already defined, skip
	}
})();
`;return`<style>
html, body {
	font-size: initial;
}
</style>
<script>
window.sandboxId = ${JSON.stringify(i)};
${t}
${s}
${o.join(`
`)}
${a}
<\/script>`}};S([k({attribute:!1})],b.prototype,"sandboxUrlProvider",2);b=S([M("sandbox-iframe")],b);export{m as R,b as S};
