import{a as S,t as C,i as L}from"./vendor-lit-B2r-dKc0.js";import{av as d,aR as v,aS as _}from"./app-session-runtime-CeFJDILJ.js";var H=Object.defineProperty,P=Object.getOwnPropertyDescriptor,x=(e,r,o,a)=>{for(var n=a>1?void 0:a?P(r,o):r,t=e.length-1,i;t>=0;t--)(i=e[t])&&(n=(a?i(r,o,n):i(n))||n);return a&&n&&H(r,o,n),n};function M(e){return e.replace(/<\/script/gi,"<\\/script")}let g=class extends L{createRenderRoot(){return this}connectedCallback(){super.connectedCallback()}disconnectedCallback(){super.disconnectedCallback(),this.iframe?.remove()}loadContent(e,r,o=[],a=[]){try{d.unregisterSandbox(e)}catch{}o=[new v,...o],d.registerSandbox(e,o,a);const n=this.prepareHtmlDocument(e,r,o,{isHtmlArtifact:!0,isStandalone:!1}),t=this.validateHtml(n);if(t){console.error("HTML validation failed:",t),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;">${t}</pre>
				</body>
				</html>
			`,this.appendChild(this.iframe);return}this.iframe?.remove(),this.sandboxUrlProvider?this.loadViaSandboxUrl(e,n):this.loadViaSrcdoc(e,n)}loadViaSandboxUrl(e,r){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(),d.setSandboxIframe(e,this.iframe);const o=t=>{if(t.data.type==="open-external-url"&&t.source===this.iframe?.contentWindow){const i=globalThis.chrome;i?.tabs?i.tabs.create({url:t.data.url}):window.open(t.data.url,"_blank")}};window.addEventListener("message",o);const a=t=>{t.data.type==="sandbox-ready"&&t.source===this.iframe?.contentWindow&&(window.removeEventListener("message",a),window.removeEventListener("message",n),this.iframe?.contentWindow?.postMessage({type:"sandbox-load",sandboxId:e,code:r},"*"))},n=t=>{t.data.type==="sandbox-error"&&t.source===this.iframe?.contentWindow&&(window.removeEventListener("message",a),window.removeEventListener("message",n),window.postMessage({sandboxId:e,type:"execution-error",error:{message:t.data.error,stack:t.data.stack}},"*"))};window.addEventListener("message",a),window.addEventListener("message",n),this.appendChild(this.iframe)}loadViaSrcdoc(e,r){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=r,d.setSandboxIframe(e,this.iframe);const o=a=>{a.data.type==="open-external-url"&&a.source===this.iframe?.contentWindow&&window.open(a.data.url,"_blank")};window.addEventListener("message",o),this.appendChild(this.iframe)}async execute(e,r,o=[],a=[],n,t=!1){if(n?.aborted)throw new Error("Execution aborted");const i=new v;o=[i,...o],d.registerSandbox(e,o,a);for(const m of o)m.onExecutionStart?.(e,n);const l=[];let s=!1;return new Promise((m,p)=>{const E={async handleMessage(c){c.type==="file-returned"?l.push({fileName:c.fileName,content:c.content,mimeType:c.mimeType}):c.type==="execution-complete"?(s=!0,h(),m({success:!0,console:i.getLogs(),files:l,returnValue:c.returnValue})):c.type==="execution-error"&&(s=!0,h(),m({success:!1,console:i.getLogs(),error:c.error,files:l}))}};d.addConsumer(e,E);const h=()=>{for(const c of o)c.onExecutionEnd?.(e);d.unregisterSandbox(e),n?.removeEventListener("abort",b),clearTimeout(k),this.iframe?.remove(),this.iframe=void 0},b=()=>{s||(s=!0,h(),p(new Error("Execution aborted")))};n&&n.addEventListener("abort",b);const k=setTimeout(()=>{s||(s=!0,h(),m({success:!1,console:i.getLogs(),error:{message:"Execution timeout (120s)",stack:""},files:l}))},12e4),u=this.prepareHtmlDocument(e,r,o,{isHtmlArtifact:t,isStandalone:!1}),y=this.validateHtml(u);if(y){p(new Error(`HTML validation failed: ${y}`));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(),d.setSandboxIframe(e,this.iframe);const c=f=>{f.data.type==="sandbox-ready"&&f.source===this.iframe?.contentWindow&&(window.removeEventListener("message",c),window.removeEventListener("message",w),this.iframe?.contentWindow?.postMessage({type:"sandbox-load",sandboxId:e,code:u},"*"))},w=f=>{f.data.type==="sandbox-error"&&f.source===this.iframe?.contentWindow&&(window.removeEventListener("message",c),window.removeEventListener("message",w),window.postMessage({sandboxId:e,type:"execution-error",error:{message:f.data.error,stack:f.data.stack}},"*"))};window.addEventListener("message",c),window.addEventListener("message",w),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=u,d.setSandboxIframe(e,this.iframe),this.appendChild(this.iframe)})}validateHtml(e){try{const a=new DOMParser().parseFromString(e,"text/html").querySelector("parsererror");return a?a.textContent||"Unknown parse error":null}catch(r){return r.message||"Unknown validation error"}}prepareHtmlDocument(e,r,o=[],a){const n={isHtmlArtifact:!1,isStandalone:!1,...a},t=this.getRuntimeScript(e,o,n.isStandalone||!1);if(n.isHtmlArtifact){const i=r.match(/<head[^>]*>/i);if(i){const s=i.index+i[0].length;return r.slice(0,s)+t+r.slice(s)}const l=r.match(/<html[^>]*>/i);if(l){const s=l.index+l[0].length;return r.slice(0,s)+t+r.slice(s)}return t+r}else{const i=M(r);return`<!DOCTYPE html>
<html>
<head>
	${t}
</head>
<body>
	<script type="module">
		(async () => {
			try {
				// Wrap user code in async function to capture return value
				const userCodeFunc = async () => {
					${i}
				};

				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(e,r=[],o=!1){const a={};for(const s of r)Object.assign(a,s.getData());const n=o?"":_.generateBridgeCode({context:"sandbox-iframe",sandboxId:e}),t=[];for(const s of r)t.push(`(${s.getRuntime().toString()})(${JSON.stringify(e)});`);const i=Object.entries(a).map(([s,m])=>{const p=JSON.stringify(m).replace(/<\/script/gi,"<\\/script");return`window.${s} = ${p};`}).join(`
`),l=o?"":`
// 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(e)};
${i}
${n}
${t.join(`
`)}
${l}
<\/script>`}};x([S({attribute:!1})],g.prototype,"sandboxUrlProvider",2);g=x([C("sandbox-iframe")],g);export{g as S};
