Drop in a screenshot and convert it to clean code (HTML/Tailwind/React/Vue)
Python
Move export packaging to the backend
Abi Raja4d33ee11fd51
diff --git a/backend/main.py b/backend/main.pyindex 245b0f27..45b8364f 100644--- a/backend/main.py+++ b/backend/main.py@@ -7,7 +7,7 @@ load_dotenv()from fastapi import FastAPIfrom fastapi.middleware.cors import CORSMiddlewarefrom config import IS_DEBUG_ENABLED-from routes import screenshot, generate_code, home, evals+from routes import screenshot, generate_code, home, evals, exportapp = FastAPI(openapi_url=None, docs_url=None, redoc_url=None)@@ -31,3 +31,4 @@ app.include_router(generate_code.router)app.include_router(screenshot.router)app.include_router(home.router)app.include_router(evals.router)+app.include_router(export.router)diff --git a/backend/routes/export.py b/backend/routes/export.pynew file mode 100644index 00000000..d9ec08cf--- /dev/null+++ b/backend/routes/export.py@@ -0,0 +1,415 @@+import asyncio+import base64+from dataclasses import dataclass+from io import BytesIO+import ipaddress+import re+import socket+from typing import Iterable+from urllib.parse import unquote_to_bytes, urljoin, urlparse+from zipfile import ZIP_DEFLATED, ZipFile++import httpx+from bs4 import BeautifulSoup+from bs4.element import Tag+from fastapi import APIRouter+from fastapi.responses import Response+from pydantic import BaseModel++router = APIRouter()++IMAGE_ATTRIBUTE_SELECTORS = [+ "img[src]",+ "img[srcset]",+ "source[srcset]",+ "image[href]",+ "image[xlink\\:href]",+ "link[rel~='icon'][href]",+ "link[rel='apple-touch-icon'][href]",+]++IMAGE_EXTENSIONS = {+ "apng",+ "avif",+ "gif",+ "jpeg",+ "jpg",+ "png",+ "svg",+ "webp",+}++MIME_EXTENSION_MAP = {+ "image/apng": "apng",+ "image/avif": "avif",+ "image/gif": "gif",+ "image/jpeg": "jpg",+ "image/jpg": "jpg",+ "image/png": "png",+ "image/svg+xml": "svg",+ "image/webp": "webp",+}++CSS_URL_RE = re.compile(r"url\(\s*(['\"]?)(.*?)\1\s*\)", re.IGNORECASE)+MAX_ASSETS = 50+MAX_ASSET_BYTES = 20 * 1024 * 1024+MAX_REDIRECTS = 5+++class ExportRequest(BaseModel):+ code: str+ baseUrl: str | None = None+++@dataclass(frozen=True)+class AssetCandidate:+ url: str+ extension_hint: str+++@dataclass(frozen=True)+class ExportedAsset:+ path: str+ content: bytes+++def is_skippable_asset_url(url: str) -> bool:+ trimmed = url.strip()+ return (+ trimmed == ""+ or trimmed.startswith("#")+ or trimmed.startswith("javascript:")+ or trimmed.startswith("mailto:")+ or trimmed.startswith("tel:")+ )+++def extension_from_mime_type(mime_type: str) -> str:+ return MIME_EXTENSION_MAP.get(mime_type.lower().split(";")[0], "bin")+++def extension_from_url(url: str) -> str:+ if url.startswith("data:"):+ match = re.match(r"^data:([^;,]+)", url, re.IGNORECASE)+ return extension_from_mime_type(match.group(1)) if match else "bin"++ path = urlparse(url).path or url.split("?", 1)[0].split("#", 1)[0]+ extension = path.rsplit(".", 1)[-1].lower() if "." in path else ""+ return extension if extension in IMAGE_EXTENSIONS else "bin"+++def is_fetchable_asset_reference(url: str) -> bool:+ trimmed = url.strip()+ if is_skippable_asset_url(trimmed):+ return False+ if trimmed.startswith("data:"):+ return re.match(r"^data:image/", trimmed, re.IGNORECASE) is not None+ if trimmed.startswith("blob:"):+ return False+ return True+++def parse_srcset(srcset: str) -> list[str]:+ return [+ part.strip().split()[0]+ for part in srcset.split(",")+ if part.strip().split()+ ]+++def extract_css_urls(css: str) -> list[str]:+ return [match.group(2) for match in CSS_URL_RE.finditer(css)]+++def tag_attr(tag: Tag, attribute_name: str) -> str | None:+ value = tag.get(attribute_name)+ return value if isinstance(value, str) else None+++def add_candidate(candidates: dict[str, AssetCandidate], raw_url: str) -> None:+ url = raw_url.strip()+ if not is_fetchable_asset_reference(url) or url in candidates:+ return+ candidates[url] = AssetCandidate(url=url, extension_hint=extension_from_url(url))+++def collect_asset_candidates(soup: BeautifulSoup) -> list[AssetCandidate]:+ candidates: dict[str, AssetCandidate] = {}++ for element in soup.select(",".join(IMAGE_ATTRIBUTE_SELECTORS)):+ if not isinstance(element, Tag):+ continue++ for attribute_name in ["src", "href", "xlink:href"]:+ value = tag_attr(element, attribute_name)+ if value:+ add_candidate(candidates, value)++ srcset = tag_attr(element, "srcset")+ if srcset:+ for url in parse_srcset(srcset):+ add_candidate(candidates, url)++ for style_element in soup.select("style"):+ for url in extract_css_urls(style_element.get_text()):+ add_candidate(candidates, url)++ for element in soup.select("[style]"):+ if not isinstance(element, Tag):+ continue+ style = tag_attr(element, "style")+ if style:+ for url in extract_css_urls(style):+ add_candidate(candidates, url)++ return list(candidates.values())[:MAX_ASSETS]+++def resolve_fetch_url(url: str, base_url: str | None) -> str | None:+ if url.startswith("data:"):+ return url+ if url.startswith("//"):+ scheme = urlparse(base_url or "").scheme or "https"+ return f"{scheme}:{url}"+ if urlparse(url).scheme in {"http", "https"}:+ return url+ if base_url:+ return urljoin(base_url, url)+ return None+++def is_private_ip(ip_address: str) -> bool:+ parsed_ip = ipaddress.ip_address(ip_address)+ return (+ parsed_ip.is_private+ or parsed_ip.is_loopback+ or parsed_ip.is_link_local+ or parsed_ip.is_multicast+ or parsed_ip.is_reserved+ or parsed_ip.is_unspecified+ )+++async def is_public_http_url(url: str) -> bool:+ parsed = urlparse(url)+ if parsed.scheme not in {"http", "https"} or not parsed.hostname:+ return False++ try:+ return not is_private_ip(parsed.hostname)+ except ValueError:+ pass++ try:+ addresses = await asyncio.to_thread(+ socket.getaddrinfo,+ parsed.hostname,+ parsed.port or 443,+ type=socket.SOCK_STREAM,+ )+ except socket.gaierror:+ return False++ for address in addresses:+ host = str(address[4][0])+ try:+ if is_private_ip(host):+ return False+ except ValueError:+ return False++ return True+++def decode_data_url(data_url: str) -> tuple[bytes, str] | None:+ try:+ header, payload = data_url.split(",", 1)+ except ValueError:+ return None++ mime_type = header[5:].split(";", 1)[0].lower()+ if not mime_type.startswith("image/"):+ return None++ if ";base64" in header.lower():+ content = base64.b64decode(payload, validate=True)+ else:+ content = unquote_to_bytes(payload)++ return content, extension_from_mime_type(mime_type)+++async def fetch_remote_asset(+ client: httpx.AsyncClient, fetch_url: str, extension_hint: str+) -> tuple[bytes, str] | None:+ current_url = fetch_url+ response: httpx.Response | None = None++ for _ in range(MAX_REDIRECTS + 1):+ if not await is_public_http_url(current_url):+ return None++ response = await client.get(current_url, follow_redirects=False)+ if not response.is_redirect:+ break++ location = response.headers.get("location")+ if not location:+ return None+ current_url = urljoin(current_url, location)++ if response is None or response.is_redirect:+ return None+ if not response.is_success:+ return None++ content = response.content+ if len(content) > MAX_ASSET_BYTES:+ return None++ content_type = response.headers.get("content-type", "")+ if (+ content_type+ and not content_type.lower().startswith("image/")+ and extension_hint == "bin"+ ):+ return None++ return content, extension_from_mime_type(content_type)+++async def fetch_asset(+ client: httpx.AsyncClient,+ candidate: AssetCandidate,+ asset_index: int,+ base_url: str | None,+) -> ExportedAsset | None:+ fetch_url = resolve_fetch_url(candidate.url, base_url)+ if not fetch_url:+ return None++ try:+ if fetch_url.startswith("data:"):+ decoded = decode_data_url(fetch_url)+ else:+ decoded = await fetch_remote_asset(+ client, fetch_url, candidate.extension_hint+ )+ except Exception:+ return None++ if not decoded:+ return None++ content, mime_extension = decoded+ extension = (+ candidate.extension_hint+ if candidate.extension_hint != "bin"+ else mime_extension+ )+ return ExportedAsset(+ path=f"assets/image-{asset_index + 1}.{extension}", content=content+ )+++def rewrite_srcset(srcset: str, asset_path_by_url: dict[str, str]) -> str:+ rewritten_parts: list[str] = []+ for part in srcset.split(","):+ trimmed = part.strip()+ tokens = trimmed.split()+ if not tokens:+ rewritten_parts.append(part)+ continue++ asset_path = asset_path_by_url.get(tokens[0])+ rewritten_parts.append(+ " ".join([asset_path, *tokens[1:]]) if asset_path else part+ )++ return ", ".join(rewritten_parts)+++def rewrite_css_urls(css: str, asset_path_by_url: dict[str, str]) -> str:+ def replace(match: re.Match[str]) -> str:+ quote = match.group(1)+ url = match.group(2).strip()+ asset_path = asset_path_by_url.get(url)+ if not asset_path:+ return match.group(0)+ return f"url({quote}{asset_path}{quote})"++ return CSS_URL_RE.sub(replace, css)+++def rewrite_html_assets(soup: BeautifulSoup, asset_path_by_url: dict[str, str]) -> None:+ for element in soup.select(",".join(IMAGE_ATTRIBUTE_SELECTORS)):+ if not isinstance(element, Tag):+ continue++ for attribute_name in ["src", "href", "xlink:href"]:+ value = tag_attr(element, attribute_name)+ if not value:+ continue+ asset_path = asset_path_by_url.get(value.strip())+ if asset_path:+ element[attribute_name] = asset_path++ srcset = tag_attr(element, "srcset")+ if srcset:+ element["srcset"] = rewrite_srcset(srcset, asset_path_by_url)++ for style_element in soup.select("style"):+ style_element.string = rewrite_css_urls(style_element.get_text(), asset_path_by_url)++ for element in soup.select("[style]"):+ if not isinstance(element, Tag):+ continue+ style = tag_attr(element, "style")+ if style:+ element["style"] = rewrite_css_urls(style, asset_path_by_url)+++def create_project_zip(index_html: str, assets: Iterable[ExportedAsset]) -> bytes:+ buffer = BytesIO()+ with ZipFile(buffer, "w", ZIP_DEFLATED) as zip_file:+ zip_file.writestr("index.html", index_html)+ for asset in assets:+ zip_file.writestr(asset.path, asset.content)++ return buffer.getvalue()++[email protected]("/api/export")+async def export_code(request: ExportRequest) -> Response:+ soup = BeautifulSoup(request.code, "html.parser")+ candidates = collect_asset_candidates(soup)++ async with httpx.AsyncClient(+ timeout=20,+ headers={"User-Agent": "screenshot-to-code-export/1.0"},+ ) as client:+ fetched_assets = await asyncio.gather(+ *[+ fetch_asset(client, candidate, index, request.baseUrl)+ for index, candidate in enumerate(candidates)+ ]+ )++ assets = [asset for asset in fetched_assets if asset is not None]+ asset_path_by_url = {+ candidates[index].url: asset.path+ for index, asset in enumerate(fetched_assets)+ if asset is not None+ }++ if asset_path_by_url:+ rewrite_html_assets(soup, asset_path_by_url)++ zip_content = create_project_zip(str(soup), assets)+ return Response(+ content=zip_content,+ media_type="application/zip",+ headers={+ "Content-Disposition": 'attachment; filename="screenshot-to-code-export.zip"'+ },+ )diff --git a/backend/tests/test_export.py b/backend/tests/test_export.pynew file mode 100644index 00000000..ccd310eb--- /dev/null+++ b/backend/tests/test_export.py@@ -0,0 +1,48 @@+from io import BytesIO+from zipfile import ZipFile++import pytest++from routes.export import ExportRequest, export_code+++async def test_export_code_rewrites_data_url_images_into_zip_assets() -> None:+ png_data_url = "data:image/png;base64,iVBORw0KGgo="+ svg_data_url = "data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%3E%3C/svg%3E"+ code = f"""+ <html>+ <head>+ <style>.hero {{ background-image: url("{svg_data_url}"); }}</style>+ </head>+ <body>+ <img src="{png_data_url}" />+ </body>+ </html>+ """++ response = await export_code(ExportRequest(code=code))++ with ZipFile(BytesIO(response.body)) as archive:+ assert sorted(archive.namelist()) == [+ "assets/image-1.png",+ "assets/image-2.svg",+ "index.html",+ ]++ index_html = archive.read("index.html").decode("utf-8")+ assert 'src="assets/image-1.png"' in index_html+ assert 'url("assets/image-2.svg")' in index_html+ assert archive.read("assets/image-1.png") == b"\x89PNG\r\n\x1a\n"+ assert archive.read("assets/image-2.svg").startswith(b"<svg")+++async def test_export_code_returns_zip_with_index_when_no_assets() -> None:+ response = await export_code(ExportRequest(code="<html><body>Hello</body></html>"))++ with ZipFile(BytesIO(response.body)) as archive:+ assert archive.namelist() == ["index.html"]+ assert archive.read("index.html").decode("utf-8") == (+ "<html><body>Hello</body></html>"+ )diff --git a/frontend/package.json b/frontend/package.jsonindex 90fc8c22..29dd9ed1 100644--- a/frontend/package.json+++ b/frontend/package.json@@ -37,7 +37,6 @@"clsx": "^2.0.0","codemirror": "^6.0.1","copy-to-clipboard": "^3.3.3",- "fflate": "^0.8.2","html2canvas": "^1.4.1","nanoid": "^5.0.7","react": "^18.2.0",diff --git a/frontend/pnpm-lock.yaml b/frontend/pnpm-lock.yamlindex 2d994657..9b06b97c 100644--- a/frontend/pnpm-lock.yaml+++ b/frontend/pnpm-lock.yaml@@ -77,9 +77,6 @@ importers:copy-to-clipboard:specifier: ^3.3.3version: 3.3.3- fflate:- specifier: ^0.8.2- version: 0.8.2html2canvas:specifier: ^1.4.1version: 1.4.1@@ -2376,9 +2373,6 @@ packages:picomatch:optional: true- resolution: {integrity: sha512-cPJU47OaAoCbg0pBvzsgpTPhmhqI5eJjh/JIu8tPj5q+T7iLvW/JAYUqmE7KOB4R1ZyEhzBaIQpQpardBF5z8A==}-resolution: {integrity: sha512-7Gps/XWymbLk2QLYK4NzpMOrYjMhdIxXuIvy2QBsLE6ljuodKvdkWs/cpyJJ3CVIVpH0Oi1Hvg1ovbMzLdFBBg==}engines: {node: ^10.12.0 || >=12.0.0}@@ -6436,8 +6430,6 @@ snapshots:optionalDependencies:picomatch: 4.0.4- [email protected]: {}-dependencies:flat-cache: 3.2.0diff --git a/frontend/src/components/preview/download.ts b/frontend/src/components/preview/download.tsindex 05152b95..3d87edd9 100644--- a/frontend/src/components/preview/download.ts+++ b/frontend/src/components/preview/download.ts@@ -1,46 +1,4 @@-import { strToU8, zipSync } from "fflate";--type AssetCandidate = {- url: string;- extensionHint: string;-};--type ExportedAsset = {- path: string;- blob: Blob;-};--const IMAGE_ATTRIBUTE_SELECTORS = [- "img[src]",- "img[srcset]",- "source[srcset]",- "image[href]",- "image[xlink\\:href]",- "link[rel~='icon'][href]",- "link[rel='apple-touch-icon'][href]",-];--const IMAGE_EXTENSIONS = new Set([- "apng",- "avif",- "gif",- "jpeg",- "jpg",- "png",- "svg",- "webp",-]);--const MIME_EXTENSION_MAP: Record<string, string> = {- "image/apng": "apng",- "image/avif": "avif",- "image/gif": "gif",- "image/jpeg": "jpg",- "image/jpg": "jpg",- "image/png": "png",- "image/svg+xml": "svg",- "image/webp": "webp",-};+import { HTTP_BACKEND_URL } from "../../config";function downloadBlob(blob: Blob, filename: string) {const url = URL.createObjectURL(blob);@@ -53,239 +11,35 @@ function downloadBlob(blob: Blob, filename: string) {URL.revokeObjectURL(url);}-function isSkippableAssetUrl(url: string) {- const trimmed = url.trim();- return (- trimmed === "" ||- trimmed.startsWith("#") ||- trimmed.startsWith("javascript:") ||- trimmed.startsWith("mailto:") ||- trimmed.startsWith("tel:")- );-}--function extensionFromMimeType(mimeType: string) {- return MIME_EXTENSION_MAP[mimeType.toLowerCase().split(";")[0]] ?? "bin";+function filenameFromContentDisposition(contentDisposition: string | null) {+ const match = contentDisposition?.match(/filename="?([^"]+)"?/i);+ return match?.[1] ?? "screenshot-to-code-export.zip";}-function extensionFromUrl(url: string) {- if (url.startsWith("data:")) {- const mimeType = url.match(/^data:([^;,]+)/i)?.[1];- return mimeType ? extensionFromMimeType(mimeType) : "bin";- }-+export const downloadCode = async (code: string) => {try {- const parsed = new URL(url, window.location.href);- const extension = parsed.pathname.split(".").pop()?.toLowerCase() ?? "";- return IMAGE_EXTENSIONS.has(extension) ? extension : "bin";- } catch {- const extension = url.split("?")[0].split("#")[0].split(".").pop()?.toLowerCase() ?? "";- return IMAGE_EXTENSIONS.has(extension) ? extension : "bin";- }-}--function isImageUrl(url: string) {- const trimmed = url.trim();- if (isSkippableAssetUrl(trimmed)) return false;- if (trimmed.startsWith("data:")) {- return /^data:image\//i.test(trimmed);- }- if (trimmed.startsWith("blob:")) return true;- return extensionFromUrl(trimmed) !== "bin";-}--function addCandidate(candidates: Map<string, AssetCandidate>, rawUrl: string) {- const url = rawUrl.trim();- if (!isImageUrl(url) || candidates.has(url)) return;- candidates.set(url, {- url,- extensionHint: extensionFromUrl(url),- });-}--function extractCssUrls(css: string) {- const urls: string[] = [];- const urlRegex = /url\(\s*(['"]?)(.*?)\1\s*\)/gi;- let match: RegExpExecArray | null;- while ((match = urlRegex.exec(css)) !== null) {- urls.push(match[2]);- }- return urls;-}--function parseSrcset(srcset: string) {- return srcset- .split(",")- .map((part) => part.trim().split(/\s+/)[0])- .filter(Boolean);-}--function collectAssetCandidates(doc: Document) {- const candidates = new Map<string, AssetCandidate>();-- doc.querySelectorAll(IMAGE_ATTRIBUTE_SELECTORS.join(",")).forEach((element) => {- ["src", "href", "xlink:href"].forEach((attributeName) => {- const value = element.getAttribute(attributeName);- if (value) addCandidate(candidates, value);+ const response = await fetch(`${HTTP_BACKEND_URL}/api/export`, {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ },+ body: JSON.stringify({+ code,+ baseUrl: window.location.href,+ }),});- const srcset = element.getAttribute("srcset");- if (srcset) {- parseSrcset(srcset).forEach((url) => addCandidate(candidates, url));+ if (!response.ok) {+ throw new Error(`Export failed with status ${response.status}`);}- });-- doc.querySelectorAll("style").forEach((styleElement) => {- extractCssUrls(styleElement.textContent ?? "").forEach((url) =>- addCandidate(candidates, url)- );- });-- doc.querySelectorAll<HTMLElement>("[style]").forEach((element) => {- extractCssUrls(element.getAttribute("style") ?? "").forEach((url) =>- addCandidate(candidates, url)- );- });-- return Array.from(candidates.values());-}--function resolveFetchUrl(url: string) {- if (url.startsWith("//")) {- return `${window.location.protocol}${url}`;- }- if (url.startsWith("data:") || url.startsWith("blob:")) {- return url;- }- return new URL(url, window.location.href).toString();-}--async function fetchAsset(candidate: AssetCandidate, assetIndex: number) {- try {- const response = await fetch(resolveFetchUrl(candidate.url));- if (!response.ok) return null;const blob = await response.blob();- const extension =- candidate.extensionHint !== "bin"- ? candidate.extensionHint- : extensionFromMimeType(blob.type);-- return {- path: `assets/image-${assetIndex + 1}.${extension}`,+ downloadBlob(blob,- };- } catch (error) {- console.warn("Skipping asset that could not be downloaded", candidate.url, error);- return null;- }-}--function rewriteSrcset(srcset: string, assetPathByUrl: Map<string, string>) {- return srcset- .split(",")- .map((part) => {- const trimmed = part.trim();- const [url, ...descriptors] = trimmed.split(/\s+/);- const assetPath = assetPathByUrl.get(url);- if (!assetPath) return part;- return [assetPath, ...descriptors].join(" ");- })- .join(", ");-}--function rewriteCssUrls(css: string, assetPathByUrl: Map<string, string>) {- return css.replace(/url\(\s*(['"]?)(.*?)\1\s*\)/gi, (match, quote, url) => {- const assetPath = assetPathByUrl.get(String(url).trim());- if (!assetPath) return match;- return `url(${quote}${assetPath}${quote})`;- });-}--function rewriteHtmlAssets(doc: Document, assetPathByUrl: Map<string, string>) {- doc.querySelectorAll(IMAGE_ATTRIBUTE_SELECTORS.join(",")).forEach((element) => {- ["src", "href", "xlink:href"].forEach((attributeName) => {- const value = element.getAttribute(attributeName);- if (!value) return;- const assetPath = assetPathByUrl.get(value.trim());- if (assetPath) element.setAttribute(attributeName, assetPath);- });-- const srcset = element.getAttribute("srcset");- if (srcset) {- element.setAttribute("srcset", rewriteSrcset(srcset, assetPathByUrl));- }- });-- doc.querySelectorAll("style").forEach((styleElement) => {- styleElement.textContent = rewriteCssUrls(- styleElement.textContent ?? "",- assetPathByUrl- );- });-- doc.querySelectorAll<HTMLElement>("[style]").forEach((element) => {- element.setAttribute(- "style",- rewriteCssUrls(element.getAttribute("style") ?? "", assetPathByUrl)+ filenameFromContentDisposition(response.headers.get("Content-Disposition")));- });-}--function serializeHtmlDocument(doc: Document) {- const doctype = doc.doctype ? "<!DOCTYPE html>\n" : "";- return `${doctype}${doc.documentElement.outerHTML}`;-}--function toArrayBuffer(bytes: Uint8Array) {- const buffer = new ArrayBuffer(bytes.byteLength);- new Uint8Array(buffer).set(bytes);- return buffer;-}--async function createProjectZip(indexHtml: string, assets: ExportedAsset[]) {- const files: Record<string, Uint8Array> = {- "index.html": strToU8(indexHtml),- };-- await Promise.all(- assets.map(async (asset) => {- files[asset.path] = new Uint8Array(await asset.blob.arrayBuffer());- })- );-- return new Blob([toArrayBuffer(zipSync(files))], {- type: "application/zip",- });-}--export const downloadCode = async (code: string) => {- const doc = new DOMParser().parseFromString(code, "text/html");- const candidates = collectAssetCandidates(doc);-- if (candidates.length === 0) {- downloadBlob(new Blob([code], { type: "text/html" }), "index.html");- return;- }-- const fetchedAssets = await Promise.all(- candidates.map((candidate, index) => fetchAsset(candidate, index))- );- const assetPathByUrl = new Map<string, string>();- const assets: ExportedAsset[] = [];-- fetchedAssets.forEach((asset, index) => {- if (!asset) return;- assetPathByUrl.set(candidates[index].url, asset.path);- assets.push(asset);- });-- if (assets.length === 0) {+ } catch (error) {+ console.warn("Falling back to downloading index.html", error);downloadBlob(new Blob([code], { type: "text/html" }), "index.html");- return;}-- rewriteHtmlAssets(doc, assetPathByUrl);- const zip = await createProjectZip(serializeHtmlDocument(doc), assets);- downloadBlob(zip, "screenshot-to-code-export.zip");};diff --git a/frontend/src/tests/qa.test.ts b/frontend/src/tests/qa.test.tsindex 1633cb00..c2c31868 100644--- a/frontend/src/tests/qa.test.ts+++ b/frontend/src/tests/qa.test.ts@@ -387,6 +387,20 @@ async function setupRequestInterception(});return;}+ if (url.endsWith("/api/export")) {+ request.respond({+ status: 200,+ contentType: "application/zip",+ headers: {+ "Access-Control-Allow-Origin": "*",+ "Access-Control-Allow-Headers": "*",+ "Content-Disposition":+ 'attachment; filename="screenshot-to-code-export.zip"',+ },+ body: "mock export",+ });+ return;+ }request.continue();});}@@ -430,7 +444,7 @@ async function installMockWebSocket(page: Page) {readyState = MockWebSocket.CONNECTING;url: string;- listeners: Record<string, Array<(event: any) => void>> = {};+ listeners: Record<string, Array<(event: unknown) => void>> = {};constructor(url: string) {this.url = url;@@ -440,14 +454,14 @@ async function installMockWebSocket(page: Page) {}, 10);}- addEventListener(type: string, listener: (event: any) => void) {+ addEventListener(type: string, listener: (event: unknown) => void) {if (!this.listeners[type]) {this.listeners[type] = [];}this.listeners[type].push(listener);}- removeEventListener(type: string, listener: (event: any) => void) {+ removeEventListener(type: string, listener: (event: unknown) => void) {if (!this.listeners[type]) return;this.listeners[type] = this.listeners[type].filter((existing) => existing !== listener@@ -489,7 +503,7 @@ async function installMockWebSocket(page: Page) {this.emit("close", { code, reason });}- emit(type: string, event: any) {+ emit(type: string, event: unknown) {(this.listeners[type] || []).forEach((listener) => {listener(event);});