Spaces:
Running
Running
fix preview stuffs
Browse filesFiles changed (5)
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102import { NextRequest, NextResponse } from "next/server";import { RepoDesignation, listFiles, spaceInfo, downloadFile } from "@huggingface/hub";
import { isAuthenticated } from "@/lib/auth";import { Page } from "@/types";
export async function GET( req: NextRequest, { params }: { params: Promise<{ namespace: string; repoId: string; commitId: string; }> }) { const user = await isAuthenticated();
if (user instanceof NextResponse || !user) { return NextResponse.json({ message: "Unauthorized" }, { status: 401 }); }
const param = await params; const { namespace, repoId, commitId } = param;
try { const repo: RepoDesignation = { type: "space", name: `${namespace}/${repoId}`, };
const space = await spaceInfo({ name: `${namespace}/${repoId}`, accessToken: user.token as string, additionalFields: ["author"], });
if (!space || space.sdk !== "static") { return NextResponse.json( { ok: false, error: "Space is not a static space." }, { status: 404 } ); } if (space.author !== user.name) { return NextResponse.json( { ok: false, error: "Space does not belong to the authenticated user." }, { status: 403 } ); }
const pages: Page[] = []; for await (const fileInfo of listFiles({ repo, accessToken: user.token as string, revision: commitId, })) { const fileExtension = fileInfo.path.split('.').pop()?.toLowerCase(); if (fileInfo.path.endsWith(".html") || fileInfo.path.endsWith(".css") || fileInfo.path.endsWith(".js") || fileInfo.path.endsWith(".json")) { const blob = await downloadFile({ repo, accessToken: user.token as string, path: fileInfo.path, revision: commitId, raw: true }); const content = await blob?.text(); if (content) { if (fileInfo.path === "index.html") { pages.unshift({ path: fileInfo.path, html: content, }); } else { pages.push({ path: fileInfo.path, html: content, }); } } } } return NextResponse.json({ ok: true, pages, }); } catch (error: any) { console.error("Error fetching commit pages:", error); return NextResponse.json( { ok: false, error: error.message || "Failed to fetch commit pages", }, { status: 500 } ); }}
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547import { NextRequest, NextResponse } from "next/server";
export async function GET( req: NextRequest, { params }: { params: Promise<{ path: string[] }> }) { const pathParams = await params; const pathSegments = pathParams.path || []; // Get the target URL from query parameter const targetUrl = req.nextUrl.searchParams.get("url"); if (!targetUrl) { return NextResponse.json( { error: "Missing 'url' query parameter" }, { status: 400 } ); }
try { // Parse the target URL const url = new URL(targetUrl); // Only allow static.hf.space domains for security if (!url.hostname.endsWith(".static.hf.space")) { return NextResponse.json( { error: "Only static.hf.space domains are allowed" }, { status: 403 } ); }
// Construct the actual target URL // If path segments exist, use them; otherwise use "/" for root const targetPath = pathSegments.length > 0 ? "/" + pathSegments.join("/") : "/"; // Merge query parameters from the request URL with the target URL's search params const requestSearchParams = req.nextUrl.searchParams; const targetSearchParams = new URLSearchParams(url.search); // Copy all query params except 'url' to the target URL requestSearchParams.forEach((value, key) => { if (key !== "url") { targetSearchParams.set(key, value); } }); const searchString = targetSearchParams.toString(); const fullTargetUrl = `${url.protocol}//${url.hostname}${targetPath}${searchString ? `?${searchString}` : ""}`;
// Fetch the content from the target URL const response = await fetch(fullTargetUrl, { headers: { "User-Agent": "Mozilla/5.0 (compatible; DeepSite/1.0)", }, redirect: "follow", // Follow redirects automatically });
if (!response.ok) { return NextResponse.json( { error: `Failed to fetch: ${response.statusText}` }, { status: response.status } ); }
let contentType = response.headers.get("content-type") || ""; const content = await response.text();
// Detect content type from file extension if not properly set if (!contentType || contentType === "text/plain" || contentType === "application/octet-stream") { const fileExtension = pathSegments.length > 0 ? pathSegments[pathSegments.length - 1].split(".").pop()?.toLowerCase() : ""; if (fileExtension === "js") { contentType = "application/javascript"; } else if (fileExtension === "css") { contentType = "text/css"; } else if (fileExtension === "html" || fileExtension === "htm") { contentType = "text/html"; } else if (fileExtension === "json") { contentType = "application/json"; } }
// Get the base proxy URL // Extract the base path from the request URL const requestUrl = new URL(req.url); // Find where "/api/proxy" starts in the pathname const proxyIndex = requestUrl.pathname.indexOf("/api/proxy"); const basePath = proxyIndex > 0 ? requestUrl.pathname.substring(0, proxyIndex) : ""; const proxyBaseUrl = `${basePath}/api/proxy`; const targetUrlParam = `?url=${encodeURIComponent(`https://${url.hostname}`)}`;
// Rewrite URLs in HTML content let processedContent = content; if (contentType.includes("text/html")) { // Rewrite relative URLs and URLs pointing to the same domain processedContent = rewriteUrls( content, url.hostname, proxyBaseUrl, targetUrlParam, pathSegments ); // Inject script to intercept JavaScript-based navigation processedContent = injectNavigationInterceptor( processedContent, url.hostname, proxyBaseUrl, targetUrlParam ); } else if (contentType.includes("text/css")) { // Rewrite URLs in CSS processedContent = rewriteCssUrls( content, url.hostname, proxyBaseUrl, targetUrlParam ); } else if (contentType.includes("application/javascript") || contentType.includes("text/javascript")) { // For component files and most JavaScript, don't rewrite URLs // Only rewrite if needed (for fetch calls, etc.) // Most component JavaScript files don't need URL rewriting // Only rewrite if the file contains fetch calls with relative URLs if (content.includes("fetch(") && content.match(/fetch\(["'][^"']*[^\/]\./)) { processedContent = rewriteJsUrls( content, url.hostname, proxyBaseUrl, targetUrlParam ); } else { // Don't modify component JavaScript files - they should work as-is processedContent = content; } }
// Ensure JavaScript files have charset specified let finalContentType = contentType; if (contentType.includes("javascript") && !contentType.includes("charset")) { finalContentType = contentType.includes(";") ? contentType + "; charset=utf-8" : contentType + "; charset=utf-8"; }
// Return the processed content with appropriate headers return new NextResponse(processedContent, { status: 200, headers: { "Content-Type": finalContentType, "X-Content-Type-Options": "nosniff", // Don't set X-Frame-Options for JavaScript files - they need to execute ...(contentType.includes("text/html") && { "X-Frame-Options": "SAMEORIGIN" }), // Remove CORS restrictions since we're proxying "Access-Control-Allow-Origin": "*", "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, OPTIONS", "Access-Control-Allow-Headers": "Content-Type", }, }); } catch (error: any) { console.error("Proxy error:", error); return NextResponse.json( { error: error.message || "Proxy error occurred" }, { status: 500 } ); }}
function rewriteUrls( html: string, targetHost: string, proxyBaseUrl: string, targetUrlParam: string, currentPathSegments: string[] = []): string { let processed = html;
// Get the current directory path for resolving relative URLs const currentDir = currentPathSegments.length > 0 ? "/" + currentPathSegments.slice(0, -1).join("/") + "/" : "/";
// Rewrite relative URLs in href attributes processed = processed.replace( /href=["']([^"']+)["']/gi, (match, urlStr) => { if (urlStr.startsWith("http://") || urlStr.startsWith("https://")) { // Absolute URL - rewrite if it's the same domain try { const urlObj = new URL(urlStr); if (urlObj.hostname === targetHost) { const pathPart = urlObj.pathname === "/" ? "" : urlObj.pathname; const searchPart = urlObj.search ? `&${urlObj.search.substring(1)}` : ""; return `href="${proxyBaseUrl}${pathPart}${targetUrlParam}${searchPart}"`; } } catch { // Invalid URL, keep as is } return match; } else if (urlStr.startsWith("//")) { // Protocol-relative URL try { const urlObj = new URL(`https:${urlStr}`); if (urlObj.hostname === targetHost) { const pathPart = urlObj.pathname === "/" ? "" : urlObj.pathname; const searchPart = urlObj.search ? `&${urlObj.search.substring(1)}` : ""; return `href="${proxyBaseUrl}${pathPart}${targetUrlParam}${searchPart}"`; } } catch { // Invalid URL, keep as is } return match; } else if (urlStr.startsWith("#") || urlStr.startsWith("javascript:") || urlStr.startsWith("mailto:") || urlStr.startsWith("tel:")) { // Hash links, javascript:, mailto:, tel: - keep as is return match; } else { // Relative URL - resolve it properly let resolvedPath: string; if (urlStr.startsWith("/")) { // Absolute path relative to root resolvedPath = urlStr; } else if (urlStr.startsWith("components/") || urlStr.startsWith("images/") || urlStr.startsWith("videos/") || urlStr.startsWith("audio/")) { // Paths starting with known directories should be treated as absolute from root resolvedPath = "/" + urlStr; } else { // Relative path - resolve relative to current directory resolvedPath = currentDir + urlStr; // Normalize the path (remove ./ and ../) const parts = resolvedPath.split("/"); const normalized: string[] = []; for (const part of parts) { if (part === "..") { normalized.pop(); } else if (part !== "." && part !== "") { normalized.push(part); } } resolvedPath = "/" + normalized.join("/"); } const [path, search] = resolvedPath.split("?"); const pathPart = path === "/" ? "" : path; const searchPart = search ? `&${search}` : ""; return `href="${proxyBaseUrl}${pathPart}${targetUrlParam}${searchPart}"`; } } );
// Rewrite relative URLs in src attributes processed = processed.replace( /src=["']([^"']+)["']/gi, (match, urlStr) => { if (urlStr.startsWith("http://") || urlStr.startsWith("https://")) { try { const urlObj = new URL(urlStr); if (urlObj.hostname === targetHost) { const pathPart = urlObj.pathname === "/" ? "" : urlObj.pathname; const searchPart = urlObj.search ? `&${urlObj.search.substring(1)}` : ""; return `src="${proxyBaseUrl}${pathPart}${targetUrlParam}${searchPart}"`; } } catch { // Invalid URL, keep as is } return match; } else if (urlStr.startsWith("//")) { try { const urlObj = new URL(`https:${urlStr}`); if (urlObj.hostname === targetHost) { const pathPart = urlObj.pathname === "/" ? "" : urlObj.pathname; const searchPart = urlObj.search ? `&${urlObj.search.substring(1)}` : ""; return `src="${proxyBaseUrl}${pathPart}${targetUrlParam}${searchPart}"`; } } catch { // Invalid URL, keep as is } return match; } else if (urlStr.startsWith("data:") || urlStr.startsWith("blob:")) { // Data URLs and blob URLs - keep as is return match; } else { // Relative URL - resolve it properly let resolvedPath: string; if (urlStr.startsWith("/")) { // Absolute path relative to root resolvedPath = urlStr; } else if (urlStr.startsWith("components/") || urlStr.startsWith("images/") || urlStr.startsWith("videos/") || urlStr.startsWith("audio/")) { // Paths starting with known directories should be treated as absolute from root resolvedPath = "/" + urlStr; } else { // Relative path - resolve relative to current directory resolvedPath = currentDir + urlStr; // Normalize the path (remove ./ and ../) const parts = resolvedPath.split("/"); const normalized: string[] = []; for (const part of parts) { if (part === "..") { normalized.pop(); } else if (part !== "." && part !== "") { normalized.push(part); } } resolvedPath = "/" + normalized.join("/"); } const [path, search] = resolvedPath.split("?"); const pathPart = path === "/" ? "" : path; const searchPart = search ? `&${search}` : ""; return `src="${proxyBaseUrl}${pathPart}${targetUrlParam}${searchPart}"`; } } );
// Rewrite URLs in action attributes (forms) processed = processed.replace( /action=["']([^"']+)["']/gi, (match, urlStr) => { if (urlStr.startsWith("http://") || urlStr.startsWith("https://")) { try { const urlObj = new URL(urlStr); if (urlObj.hostname === targetHost) { const pathPart = urlObj.pathname === "/" ? "" : urlObj.pathname; const searchPart = urlObj.search ? `&${urlObj.search.substring(1)}` : ""; return `action="${proxyBaseUrl}${pathPart}${targetUrlParam}${searchPart}"`; } } catch { // Invalid URL, keep as is } return match; } else if (urlStr.startsWith("//")) { try { const urlObj = new URL(`https:${urlStr}`); if (urlObj.hostname === targetHost) { const pathPart = urlObj.pathname === "/" ? "" : urlObj.pathname; const searchPart = urlObj.search ? `&${urlObj.search.substring(1)}` : ""; return `action="${proxyBaseUrl}${pathPart}${targetUrlParam}${searchPart}"`; } } catch { // Invalid URL, keep as is } return match; } else { // Relative URL - rewrite to proxy const cleanUrl = urlStr.startsWith("/") ? urlStr : `/${urlStr}`; const [path, search] = cleanUrl.split("?"); const pathPart = path === "/" ? "" : path; const searchPart = search ? `&${search}` : ""; return `action="${proxyBaseUrl}${pathPart}${targetUrlParam}${searchPart}"`; } } );
// Rewrite URLs in CSS url() functions within style tags processed = processed.replace( /<style[^>]*>([\s\S]*?)<\/style>/gi, (match, cssContent) => { const rewrittenCss = rewriteCssUrls(cssContent, targetHost, proxyBaseUrl, targetUrlParam); return match.replace(cssContent, rewrittenCss); } );
return processed;}
function injectNavigationInterceptor( html: string, targetHost: string, proxyBaseUrl: string, targetUrlParam: string): string { // Escape strings for safe injection const escapeJs = (str: string) => { return str.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/'/g, "\\'").replace(/\n/g, "\\n").replace(/\r/g, "\\r"); }; const escapedProxyBaseUrl = escapeJs(proxyBaseUrl); const escapedTargetUrlParam = escapeJs(targetUrlParam); const escapedTargetHost = escapeJs(targetHost); const interceptorScript = ` <script> (function() { const proxyBaseUrl = "${escapedProxyBaseUrl}"; const targetUrlParam = "${escapedTargetUrlParam}"; const targetHost = "${escapedTargetHost}"; // Helper function to convert URL to proxy URL function convertToProxyUrl(url) { try { const urlObj = typeof url === 'string' ? new URL(url, window.location.href) : url; if (urlObj.hostname === targetHost || urlObj.hostname === window.location.hostname) { const pathPart = urlObj.pathname === "/" ? "" : urlObj.pathname; const searchPart = urlObj.search ? urlObj.search.substring(1) : ""; return proxyBaseUrl + pathPart + targetUrlParam + (searchPart ? "&" + searchPart : ""); } return typeof url === 'string' ? url : urlObj.href; } catch (e) { // Relative URL or invalid URL const urlStr = typeof url === 'string' ? url : url.href || ''; const pathPart = urlStr.startsWith("/") ? urlStr.split("?")[0] : "/" + urlStr.split("?")[0]; const searchPart = urlStr.includes("?") ? urlStr.split("?")[1] : ""; return proxyBaseUrl + pathPart + targetUrlParam + (searchPart ? "&" + searchPart : ""); } } // Intercept window.location.replace() const originalReplace = window.location.replace.bind(window.location); window.location.replace = function(url) { const proxyUrl = convertToProxyUrl(url); originalReplace(proxyUrl); }; // Intercept window.location.assign() const originalAssign = window.location.assign.bind(window.location); window.location.assign = function(url) { const proxyUrl = convertToProxyUrl(url); originalAssign(proxyUrl); }; // Intercept direct assignment to location.href using a proxy // Since we can't override window.location, we intercept href assignments // Try to intercept href setter, but handle gracefully if it's not configurable try { let locationHrefDescriptor = Object.getOwnPropertyDescriptor(window.location, 'href'); if (locationHrefDescriptor && locationHrefDescriptor.set && locationHrefDescriptor.configurable) { const originalHrefSetter = locationHrefDescriptor.set; Object.defineProperty(window.location, 'href', { get: locationHrefDescriptor.get, set: function(url) { const proxyUrl = convertToProxyUrl(url); originalHrefSetter.call(window.location, proxyUrl); }, configurable: true, enumerable: true }); } } catch (e) { // If we can't intercept href setter, that's okay - replace() and assign() are intercepted console.warn('Could not intercept location.href setter:', e); } })(); </script> `; // Inject script before closing </head> or before </body> if (html.includes("</head>")) { return html.replace("</head>", interceptorScript + "</head>"); } else if (html.includes("</body>")) { return html.replace("</body>", interceptorScript + "</body>"); } else { return interceptorScript + html; }}
function rewriteCssUrls( css: string, targetHost: string, proxyBaseUrl: string, targetUrlParam: string): string { return css.replace( /url\(["']?([^"')]+)["']?\)/gi, (match, urlStr) => { // Remove quotes if present const cleanUrl = urlStr.replace(/^["']|["']$/g, ""); if (cleanUrl.startsWith("http://") || cleanUrl.startsWith("https://")) { try { const urlObj = new URL(cleanUrl); if (urlObj.hostname === targetHost) { const pathPart = urlObj.pathname === "/" ? "" : urlObj.pathname; const searchPart = urlObj.search ? `&${urlObj.search.substring(1)}` : ""; return `url("${proxyBaseUrl}${pathPart}${targetUrlParam}${searchPart}")`; } } catch { // Invalid URL, keep as is } return match; } else if (cleanUrl.startsWith("//")) { try { const urlObj = new URL(`https:${cleanUrl}`); if (urlObj.hostname === targetHost) { const pathPart = urlObj.pathname === "/" ? "" : urlObj.pathname; const searchPart = urlObj.search ? `&${urlObj.search.substring(1)}` : ""; return `url("${proxyBaseUrl}${pathPart}${targetUrlParam}${searchPart}")`; } } catch { // Invalid URL, keep as is } return match; } else if (cleanUrl.startsWith("data:") || cleanUrl.startsWith("blob:")) { // Data URLs and blob URLs - keep as is return match; } else { // Relative URL - rewrite to proxy const cleanUrlPath = cleanUrl.startsWith("/") ? cleanUrl : `/${cleanUrl}`; const [path, search] = cleanUrlPath.split("?"); const pathPart = path === "/" ? "" : path; const searchPart = search ? `&${search}` : ""; return `url("${proxyBaseUrl}${pathPart}${targetUrlParam}${searchPart}")`; } } );}
function rewriteJsUrls( js: string, targetHost: string, proxyBaseUrl: string, targetUrlParam: string): string { // This is a basic implementation - JavaScript URL rewriting is complex // For now, we'll handle common patterns like fetch() and XMLHttpRequest let processed = js;
// Rewrite fetch() calls with relative URLs processed = processed.replace( /fetch\(["']([^"']+)["']\)/gi, (match, urlStr) => { if (urlStr.startsWith("http://") || urlStr.startsWith("https://")) { try { const urlObj = new URL(urlStr); if (urlObj.hostname === targetHost) { const pathPart = urlObj.pathname === "/" ? "" : urlObj.pathname; const searchPart = urlObj.search ? `&${urlObj.search.substring(1)}` : ""; return `fetch("${proxyBaseUrl}${pathPart}${targetUrlParam}${searchPart}")`; } } catch { // Invalid URL, keep as is } return match; } else if (!urlStr.startsWith("//") && !urlStr.startsWith("data:") && !urlStr.startsWith("blob:")) { // Relative URL - rewrite to proxy const cleanUrl = urlStr.startsWith("/") ? urlStr : `/${urlStr}`; const [path, search] = cleanUrl.split("?"); const pathPart = path === "/" ? "" : path; const searchPart = search ? `&${search}` : ""; return `fetch("${proxyBaseUrl}${pathPart}${targetUrlParam}${searchPart}")`; } return match; } );
return processed;}
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557import { NextRequest, NextResponse } from "next/server";
export async function GET(req: NextRequest) { // Get the target URL from query parameter const targetUrl = req.nextUrl.searchParams.get("url"); if (!targetUrl) { return NextResponse.json( { error: "Missing 'url' query parameter" }, { status: 400 } ); }
try { // Parse the target URL const url = new URL(targetUrl); // Only allow static.hf.space domains for security if (!url.hostname.endsWith(".static.hf.space")) { return NextResponse.json( { error: "Only static.hf.space domains are allowed" }, { status: 403 } ); }
// Use the pathname from the URL query param, or "/" for root const targetPath = url.pathname || "/"; // Merge query parameters from the request URL with the target URL's search params const requestSearchParams = req.nextUrl.searchParams; const targetSearchParams = new URLSearchParams(url.search); // Copy all query params except 'url' to the target URL requestSearchParams.forEach((value, key) => { if (key !== "url") { targetSearchParams.set(key, value); } }); const searchString = targetSearchParams.toString(); const fullTargetUrl = `${url.protocol}//${url.hostname}${targetPath}${searchString ? `?${searchString}` : ""}`;
// Fetch the content from the target URL const response = await fetch(fullTargetUrl, { headers: { "User-Agent": "Mozilla/5.0 (compatible; DeepSite/1.0)", }, redirect: "follow", // Follow redirects automatically });
if (!response.ok) { return NextResponse.json( { error: `Failed to fetch: ${response.statusText}` }, { status: response.status } ); }
let contentType = response.headers.get("content-type") || ""; const content = await response.text();
// Detect content type from URL path if not properly set if (!contentType || contentType === "text/plain" || contentType === "application/octet-stream") { const urlPath = url.pathname || ""; const fileExtension = urlPath.split(".").pop()?.toLowerCase(); if (fileExtension === "js") { contentType = "application/javascript"; } else if (fileExtension === "css") { contentType = "text/css"; } else if (fileExtension === "html" || fileExtension === "htm") { contentType = "text/html"; } else if (fileExtension === "json") { contentType = "application/json"; } }
// Get the base proxy URL const requestUrl = new URL(req.url); const proxyIndex = requestUrl.pathname.indexOf("/api/proxy"); const basePath = proxyIndex > 0 ? requestUrl.pathname.substring(0, proxyIndex) : ""; const proxyBaseUrl = `${basePath}/api/proxy`; // Build the base target URL with the path included const baseTargetUrl = `https://${url.hostname}${targetPath}`; const targetUrlParam = `?url=${encodeURIComponent(baseTargetUrl)}`;
// Rewrite URLs in HTML content let processedContent = content; if (contentType.includes("text/html")) { // Rewrite relative URLs and URLs pointing to the same domain processedContent = rewriteUrls( content, url.hostname, proxyBaseUrl, baseTargetUrl, [] // Empty path segments for root route ); // Inject script to intercept JavaScript-based navigation processedContent = injectNavigationInterceptor( processedContent, url.hostname, proxyBaseUrl, targetUrlParam ); } else if (contentType.includes("text/css")) { // Rewrite URLs in CSS processedContent = rewriteCssUrls( content, url.hostname, proxyBaseUrl, targetUrlParam ); } else if (contentType.includes("application/javascript") || contentType.includes("text/javascript")) { // For component files and most JavaScript, don't rewrite URLs // Only rewrite if needed (for fetch calls, etc.) // Most component JavaScript files don't need URL rewriting // Only rewrite if the file contains fetch calls with relative URLs if (content.includes("fetch(") && content.match(/fetch\(["'][^"']*[^\/]\./)) { processedContent = rewriteJsUrls( content, url.hostname, proxyBaseUrl, targetUrlParam ); } else { // Don't modify component JavaScript files - they should work as-is processedContent = content; } }
// Ensure JavaScript files have charset specified let finalContentType = contentType; if (contentType.includes("javascript") && !contentType.includes("charset")) { finalContentType = contentType.includes(";") ? contentType + "; charset=utf-8" : contentType + "; charset=utf-8"; }
// Return the processed content with appropriate headers return new NextResponse(processedContent, { status: 200, headers: { "Content-Type": finalContentType, "X-Content-Type-Options": "nosniff", // Don't set X-Frame-Options for JavaScript files - they need to execute ...(contentType.includes("text/html") && { "X-Frame-Options": "SAMEORIGIN" }), // Remove CORS restrictions since we're proxying "Access-Control-Allow-Origin": "*", "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, OPTIONS", "Access-Control-Allow-Headers": "Content-Type", }, }); } catch (error: any) { console.error("Proxy error:", error); return NextResponse.json( { error: error.message || "Proxy error occurred" }, { status: 500 } ); }}
// Import the helper functions from the catch-all route// We'll need to move these to a shared file or duplicate them here// For now, let's duplicate them to avoid refactoring
function rewriteUrls( html: string, targetHost: string, proxyBaseUrl: string, baseTargetUrl: string, currentPathSegments: string[] = []): string { let processed = html;
// Get the current directory path for resolving relative URLs const currentDir = currentPathSegments.length > 0 ? "/" + currentPathSegments.slice(0, -1).join("/") + "/" : "/";
// Helper function to build proxy URL with path in query parameter const buildProxyUrl = (path: string, search?: string) => { const fullTargetUrl = `https://${targetHost}${path}`; const encodedUrl = encodeURIComponent(fullTargetUrl); const searchPart = search ? `&${search}` : ""; return `${proxyBaseUrl}?url=${encodedUrl}${searchPart}`; };
// Rewrite relative URLs in href attributes processed = processed.replace( /href=["']([^"']+)["']/gi, (match, urlStr) => { if (urlStr.startsWith("http://") || urlStr.startsWith("https://")) { // Absolute URL - rewrite if it's the same domain try { const urlObj = new URL(urlStr); if (urlObj.hostname === targetHost) { const searchPart = urlObj.search ? urlObj.search.substring(1) : ""; return `href="${buildProxyUrl(urlObj.pathname, searchPart)}"`; } } catch { // Invalid URL, keep as is } return match; } else if (urlStr.startsWith("//")) { // Protocol-relative URL try { const urlObj = new URL(`https:${urlStr}`); if (urlObj.hostname === targetHost) { const searchPart = urlObj.search ? urlObj.search.substring(1) : ""; return `href="${buildProxyUrl(urlObj.pathname, searchPart)}"`; } } catch { // Invalid URL, keep as is } return match; } else if (urlStr.startsWith("#") || urlStr.startsWith("javascript:") || urlStr.startsWith("mailto:") || urlStr.startsWith("tel:")) { // Hash links, javascript:, mailto:, tel: - keep as is return match; } else { // Relative URL - resolve it properly let resolvedPath: string; if (urlStr.startsWith("/")) { // Absolute path relative to root resolvedPath = urlStr; } else if (urlStr.startsWith("components/") || urlStr.startsWith("images/") || urlStr.startsWith("videos/") || urlStr.startsWith("audio/")) { // Paths starting with known directories should be treated as absolute from root resolvedPath = "/" + urlStr; } else { // Relative path - resolve relative to current directory resolvedPath = currentDir + urlStr; // Normalize the path (remove ./ and ../) const parts = resolvedPath.split("/"); const normalized: string[] = []; for (const part of parts) { if (part === "..") { normalized.pop(); } else if (part !== "." && part !== "") { normalized.push(part); } } resolvedPath = "/" + normalized.join("/"); } const [path, search] = resolvedPath.split("?"); const normalizedPath = path === "/" ? "/" : path; return `href="${buildProxyUrl(normalizedPath, search)}"`; } } );
// Rewrite relative URLs in src attributes processed = processed.replace( /src=["']([^"']+)["']/gi, (match, urlStr) => { if (urlStr.startsWith("http://") || urlStr.startsWith("https://")) { try { const urlObj = new URL(urlStr); if (urlObj.hostname === targetHost) { const searchPart = urlObj.search ? urlObj.search.substring(1) : ""; return `src="${buildProxyUrl(urlObj.pathname, searchPart)}"`; } } catch { // Invalid URL, keep as is } return match; } else if (urlStr.startsWith("//")) { try { const urlObj = new URL(`https:${urlStr}`); if (urlObj.hostname === targetHost) { const searchPart = urlObj.search ? urlObj.search.substring(1) : ""; return `src="${buildProxyUrl(urlObj.pathname, searchPart)}"`; } } catch { // Invalid URL, keep as is } return match; } else if (urlStr.startsWith("data:") || urlStr.startsWith("blob:")) { // Data URLs and blob URLs - keep as is return match; } else { // Relative URL - resolve it properly let resolvedPath: string; if (urlStr.startsWith("/")) { // Absolute path relative to root resolvedPath = urlStr; } else if (urlStr.startsWith("components/") || urlStr.startsWith("images/") || urlStr.startsWith("videos/") || urlStr.startsWith("audio/")) { // Paths starting with known directories should be treated as absolute from root resolvedPath = "/" + urlStr; } else { // Relative path - resolve relative to current directory resolvedPath = currentDir + urlStr; // Normalize the path (remove ./ and ../) const parts = resolvedPath.split("/"); const normalized: string[] = []; for (const part of parts) { if (part === "..") { normalized.pop(); } else if (part !== "." && part !== "") { normalized.push(part); } } resolvedPath = "/" + normalized.join("/"); } const [path, search] = resolvedPath.split("?"); const normalizedPath = path === "/" ? "/" : path; return `src="${buildProxyUrl(normalizedPath, search)}"`; } } );
// Rewrite URLs in action attributes (forms) processed = processed.replace( /action=["']([^"']+)["']/gi, (match, urlStr) => { if (urlStr.startsWith("http://") || urlStr.startsWith("https://")) { try { const urlObj = new URL(urlStr); if (urlObj.hostname === targetHost) { const searchPart = urlObj.search ? urlObj.search.substring(1) : ""; return `action="${buildProxyUrl(urlObj.pathname, searchPart)}"`; } } catch { // Invalid URL, keep as is } return match; } else if (urlStr.startsWith("//")) { try { const urlObj = new URL(`https:${urlStr}`); if (urlObj.hostname === targetHost) { const searchPart = urlObj.search ? urlObj.search.substring(1) : ""; return `action="${buildProxyUrl(urlObj.pathname, searchPart)}"`; } } catch { // Invalid URL, keep as is } return match; } else { // Relative URL - resolve it properly let resolvedPath: string; if (urlStr.startsWith("/")) { resolvedPath = urlStr; } else if (urlStr.startsWith("components/") || urlStr.startsWith("images/") || urlStr.startsWith("videos/") || urlStr.startsWith("audio/")) { resolvedPath = "/" + urlStr; } else { resolvedPath = currentDir + urlStr; const parts = resolvedPath.split("/"); const normalized: string[] = []; for (const part of parts) { if (part === "..") { normalized.pop(); } else if (part !== "." && part !== "") { normalized.push(part); } } resolvedPath = "/" + normalized.join("/"); } const [path, search] = resolvedPath.split("?"); const normalizedPath = path === "/" ? "/" : path; return `action="${buildProxyUrl(normalizedPath, search)}"`; } } );
// Rewrite URLs in CSS url() functions within style tags processed = processed.replace( /<style[^>]*>([\s\S]*?)<\/style>/gi, (match, cssContent) => { const rewrittenCss = rewriteCssUrls(cssContent, targetHost, proxyBaseUrl, baseTargetUrl); return match.replace(cssContent, rewrittenCss); } );
return processed;}
function injectNavigationInterceptor( html: string, targetHost: string, proxyBaseUrl: string, targetUrlParam: string): string { // Escape strings for safe injection const escapeJs = (str: string) => { return str.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/'/g, "\\'").replace(/\n/g, "\\n").replace(/\r/g, "\\r"); }; const escapedProxyBaseUrl = escapeJs(proxyBaseUrl); const escapedTargetUrlParam = escapeJs(targetUrlParam); const escapedTargetHost = escapeJs(targetHost); const interceptorScript = ` <script> (function() { const proxyBaseUrl = "${escapedProxyBaseUrl}"; const targetUrlParam = "${escapedTargetUrlParam}"; const targetHost = "${escapedTargetHost}"; // Helper function to convert URL to proxy URL function convertToProxyUrl(url) { try { const urlObj = typeof url === 'string' ? new URL(url, window.location.href) : url; if (urlObj.hostname === targetHost || urlObj.hostname === window.location.hostname) { const pathPart = urlObj.pathname === "/" ? "" : urlObj.pathname; const searchPart = urlObj.search ? urlObj.search.substring(1) : ""; return proxyBaseUrl + pathPart + targetUrlParam + (searchPart ? "&" + searchPart : ""); } return typeof url === 'string' ? url : urlObj.href; } catch (e) { // Relative URL or invalid URL const urlStr = typeof url === 'string' ? url : url.href || ''; const pathPart = urlStr.startsWith("/") ? urlStr.split("?")[0] : "/" + urlStr.split("?")[0]; const searchPart = urlStr.includes("?") ? urlStr.split("?")[1] : ""; return proxyBaseUrl + pathPart + targetUrlParam + (searchPart ? "&" + searchPart : ""); } } // Intercept window.location.replace() const originalReplace = window.location.replace.bind(window.location); window.location.replace = function(url) { const proxyUrl = convertToProxyUrl(url); originalReplace(proxyUrl); }; // Intercept window.location.assign() const originalAssign = window.location.assign.bind(window.location); window.location.assign = function(url) { const proxyUrl = convertToProxyUrl(url); originalAssign(proxyUrl); }; // Intercept direct assignment to location.href using a proxy // Since we can't override window.location, we intercept href assignments // Try to intercept href setter, but handle gracefully if it's not configurable try { let locationHrefDescriptor = Object.getOwnPropertyDescriptor(window.location, 'href'); if (locationHrefDescriptor && locationHrefDescriptor.set && locationHrefDescriptor.configurable) { const originalHrefSetter = locationHrefDescriptor.set; Object.defineProperty(window.location, 'href', { get: locationHrefDescriptor.get, set: function(url) { const proxyUrl = convertToProxyUrl(url); originalHrefSetter.call(window.location, proxyUrl); }, configurable: true, enumerable: true }); } } catch (e) { // If we can't intercept href setter, that's okay - replace() and assign() are intercepted console.warn('Could not intercept location.href setter:', e); } })(); </script> `; // Inject script before closing </head> or before </body> if (html.includes("</head>")) { return html.replace("</head>", interceptorScript + "</head>"); } else if (html.includes("</body>")) { return html.replace("</body>", interceptorScript + "</body>"); } else { return interceptorScript + html; }}
function rewriteCssUrls( css: string, targetHost: string, proxyBaseUrl: string, targetUrlParam: string): string { return css.replace( /url\(["']?([^"')]+)["']?\)/gi, (match, urlStr) => { // Remove quotes if present const cleanUrl = urlStr.replace(/^["']|["']$/g, ""); if (cleanUrl.startsWith("http://") || cleanUrl.startsWith("https://")) { try { const urlObj = new URL(cleanUrl); if (urlObj.hostname === targetHost) { const pathPart = urlObj.pathname === "/" ? "" : urlObj.pathname; const searchPart = urlObj.search ? `&${urlObj.search.substring(1)}` : ""; return `url("${proxyBaseUrl}${pathPart}${targetUrlParam}${searchPart}")`; } } catch { // Invalid URL, keep as is } return match; } else if (cleanUrl.startsWith("//")) { try { const urlObj = new URL(`https:${cleanUrl}`); if (urlObj.hostname === targetHost) { const pathPart = urlObj.pathname === "/" ? "" : urlObj.pathname; const searchPart = urlObj.search ? `&${urlObj.search.substring(1)}` : ""; return `url("${proxyBaseUrl}${pathPart}${targetUrlParam}${searchPart}")`; } } catch { // Invalid URL, keep as is } return match; } else if (cleanUrl.startsWith("data:") || cleanUrl.startsWith("blob:")) { // Data URLs and blob URLs - keep as is return match; } else { // Relative URL - rewrite to proxy const cleanUrlPath = cleanUrl.startsWith("/") ? cleanUrl : `/${cleanUrl}`; const [path, search] = cleanUrlPath.split("?"); const pathPart = path === "/" ? "" : path; const searchPart = search ? `&${search}` : ""; return `url("${proxyBaseUrl}${pathPart}${targetUrlParam}${searchPart}")`; } } );}
function rewriteJsUrls( js: string, targetHost: string, proxyBaseUrl: string, targetUrlParam: string): string { // This is a basic implementation - JavaScript URL rewriting is complex // For now, we'll handle common patterns like fetch() and XMLHttpRequest let processed = js;
// Rewrite fetch() calls with relative URLs processed = processed.replace( /fetch\(["']([^"']+)["']\)/gi, (match, urlStr) => { if (urlStr.startsWith("http://") || urlStr.startsWith("https://")) { try { const urlObj = new URL(urlStr); if (urlObj.hostname === targetHost) { const pathPart = urlObj.pathname === "/" ? "" : urlObj.pathname; const searchPart = urlObj.search ? `&${urlObj.search.substring(1)}` : ""; return `fetch("${proxyBaseUrl}${pathPart}${targetUrlParam}${searchPart}")`; } } catch { // Invalid URL, keep as is } return match; } else if (!urlStr.startsWith("//") && !urlStr.startsWith("data:") && !urlStr.startsWith("blob:")) { // Relative URL - rewrite to proxy const cleanUrl = urlStr.startsWith("/") ? urlStr : `/${urlStr}`; const [path, search] = cleanUrl.split("?"); const pathPart = path === "/" ? "" : path; const searchPart = search ? `&${search}` : ""; return `fetch("${proxyBaseUrl}${pathPart}${targetUrlParam}${searchPart}")`; } return match; } );
return processed;}
154 unmodified lines155156157158159160161154 unmodified lines}}/></div><Preview isNew={isNew} /></main>{/* Save Changes Popup */}154 unmodified lines155156157158159160161154 unmodified lines}}/></div><Preview isNew={isNew} namespace={namespace} repoId={repoId} /></main>{/* Save Changes Popup */}
15 unmodified lines161718192021222328 unmodified lines5253545556575 unmodified lines6364656667686970717273747576777879808182838485868788899091929396 unmodified lines1901911921931941951961971982 unmodified lines2012022032042052062072082092102112122132142152162172182192202212222232242 unmodified lines2272282292302312323 unmodified lines2362372382392402412422 unmodified lines24524624724824925014 unmodified lines265266267268269270208 unmodified lines47948048148248348448551 unmodified lines5375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795806 unmodified lines5875885895905915925935945955965975981 unmodified line6006016026036046056061 unmodified line60860961061161261361461515 unmodified linesimport { api } from "@/lib/api";import { toast } from "sonner";import { RefreshCcw, TriangleAlert } from "lucide-react";export const Preview = ({ isNew }: { isNew: boolean }) => {const {project,device,28 unmodified linesconst [throttledHtml, setThrottledHtml] = useState<string>("");const lastUpdateTimeRef = useRef<number>(0);const [iframeKey, setIframeKey] = useState(0);useEffect(() => {if (!previewPage && pages.length > 0) {5 unmodified lines}}, [pages, previewPage]);const previewPageData = useMemo(() => {const found = pages.find((p) => {const normalizedPagePath = p.path.replace(/^\.?\//, "");const normalizedPreviewPage = previewPage.replace(/^\.?\//, "");return normalizedPagePath === normalizedPreviewPage;});return found || currentPageData;}, [pages, previewPage, currentPageData]);const injectAssetsIntoHtml = useCallback((html: string): string => {if (!html) return html;const cssFiles = pages.filter((p) => p.path.endsWith(".css") && p.path !== previewPageData?.path);const jsFiles = pages.filter((p) => p.path.endsWith(".js") && p.path !== previewPageData?.path);const jsonFiles = pages.filter((p) => p.path.endsWith(".json") && p.path !== previewPageData?.path);let modifiedHtml = html;// Inject all CSS filesif (cssFiles.length > 0) {const allCssContent = cssFiles96 unmodified lines});}return modifiedHtml;},[pages, previewPageData?.path]);useEffect(() => {2 unmodified linesconst timeSinceLastUpdate = now - lastUpdateTimeRef.current;if (lastUpdateTimeRef.current === 0 || timeSinceLastUpdate >= 3000) {const processedHtml = injectAssetsIntoHtml(previewPageData.html);setThrottledHtml(processedHtml);lastUpdateTimeRef.current = now;} else {const timeUntilNextUpdate = 3000 - timeSinceLastUpdate;const timer = setTimeout(() => {const processedHtml = injectAssetsIntoHtml(previewPageData.html);setThrottledHtml(processedHtml);lastUpdateTimeRef.current = Date.now();}, timeUntilNextUpdate);return () => clearTimeout(timer);}}}, [isNew, previewPageData?.html, injectAssetsIntoHtml]);useEffect(() => {if (!isAiWorking && !globalAiLoading && previewPageData?.html) {const processedHtml = injectAssetsIntoHtml(previewPageData.html);setStableHtml(processedHtml);}}, [2 unmodified linespreviewPageData?.html,injectAssetsIntoHtml,previewPage,]);useEffect(() => {3 unmodified lines!isAiWorking &&!globalAiLoading) {const processedHtml = injectAssetsIntoHtml(previewPageData.html);setStableHtml(processedHtml);}}, [2 unmodified linesisAiWorking,globalAiLoading,injectAssetsIntoHtml,]);const setupIframeListeners = () => {14 unmodified lines}};useEffect(() => {const cleanupListeners = () => {if (iframeRef?.current?.contentDocument) {208 unmodified linesnormalizedHref = normalizedHref + ".html";}const isPageExist = pages.some((page) => {const pagePath = page.path.replace(/^\.?\//, "");return pagePath === normalizedHref;});51 unmodified lines</div>) : (<>{!isNew && hasUnsavedChanges && !currentCommit && (<div className="top-0 left-0 right-0 z-20 bg-amber-500/90 backdrop-blur-sm border-b border-amber-600 px-4 py-2 flex items-center justify-between gap-3 text-sm w-full"><div className="flex items-center gap-2 flex-1"><TriangleAlert className="size-4 text-amber-900 flex-shrink-0" /><span className="text-amber-900 font-medium">Preview with unsaved changes. If you experience redirectionerrors, try refreshing the preview.</span></div><buttononClick={refreshIframe}className="px-3 py-1 bg-amber-900 hover:bg-amber-800 text-amber-50 rounded-md font-medium transition-colors whitespace-nowrap flex items-center gap-1.5"><RefreshCcw className="size-4 text-amber-50 flex-shrink-0" />Refresh</button></div>)}{!isNew &&!hasUnsavedChanges &&!currentCommit &&project?.private && (<div className="top-0 left-0 right-0 z-20 bg-amber-500/90 backdrop-blur-sm border-b border-amber-600 px-4 py-2 flex items-center justify-between gap-3 text-sm w-full"><div className="flex items-center gap-2 flex-1"><TriangleAlert className="size-4 text-amber-900 flex-shrink-0" /><span className="text-amber-900 font-medium">Private project preview. Some features may not work.</span></div><buttononClick={refreshIframe}className="px-3 py-1 bg-amber-900 hover:bg-amber-800 text-amber-50 rounded-md font-medium transition-colors whitespace-nowrap flex items-center gap-1.5"><RefreshCcw className="size-4 text-amber-50 flex-shrink-0" />Refresh</button></div>)}<iframekey={iframeKey}id="preview-iframe"6 unmodified lines})}src={currentCommit? `https://${project?.space_id?.replaceAll("/","-")}--rev-${currentCommit.slice(0, 7)}.static.hf.space`: !isNew && !hasUnsavedChanges && project?.space_id? `https://${project.space_id.replaceAll("/","-"1 unmodified line: undefined}srcDoc={!currentCommit && (isNew || hasUnsavedChanges || project?.private)? isNew? throttledHtml || defaultHTML: stableHtml1 unmodified line}onLoad={() => {if (!currentCommit &&(isNew || hasUnsavedChanges || project?.private)) {if (iframeRef?.current?.contentWindow?.document?.body) {iframeRef.current.contentWindow.document.body.scrollIntoView({15 unmodified lines161718192021222324252627282930313228 unmodified lines6162636465666768695 unmodified lines7576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226396 unmodified lines3603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913922 unmodified lines3953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264272 unmodified lines4304314324334344354363 unmodified lines4404414424434444454464474484492 unmodified lines45245345445545645745814 unmodified lines473474475476477478479480481482483484485486487488489208 unmodified lines69869970070170270370451 unmodified lines7567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887896 unmodified lines7967977987998008018028038048058061 unmodified line8088098108118128138148158168178181 unmodified line82082182282382482582682782882915 unmodified linesimport { api } from "@/lib/api";import { toast } from "sonner";import { RefreshCcw, TriangleAlert } from "lucide-react";import { Page } from "@/types";export const Preview = ({isNew,namespace,repoId,}: {isNew: boolean;namespace?: string;repoId?: string;}) => {const {project,device,28 unmodified linesconst [throttledHtml, setThrottledHtml] = useState<string>("");const lastUpdateTimeRef = useRef<number>(0);const [iframeKey, setIframeKey] = useState(0);const [commitPages, setCommitPages] = useState<Page[]>([]);const [isLoadingCommitPages, setIsLoadingCommitPages] = useState(false);const prevCommitRef = useRef<string | null>(null);useEffect(() => {if (!previewPage && pages.length > 0) {5 unmodified lines}}, [pages, previewPage]);const pagesToUse = currentCommit ? commitPages : pages;const previewPageData = useMemo(() => {const found = pagesToUse.find((p) => {const normalizedPagePath = p.path.replace(/^\.?\//, "");const normalizedPreviewPage = previewPage.replace(/^\.?\//, "");return normalizedPagePath === normalizedPreviewPage;});return found || (pagesToUse.length > 0 ? pagesToUse[0] : currentPageData);}, [pagesToUse, previewPage, currentPageData]);// Fetch commit pages when currentCommit changesuseEffect(() => {if (currentCommit && namespace && repoId) {setIsLoadingCommitPages(true);api.get(`/me/projects/${namespace}/${repoId}/commits/${currentCommit}`).then((res) => {if (res.data.ok) {setCommitPages(res.data.pages);// Set preview page to index.html if availableconst indexPage = res.data.pages.find((p: Page) =>p.path === "index.html" || p.path === "index" || p.path === "/");if (indexPage) {setPreviewPage(indexPage.path);}// Refresh iframe to show commit versionsetIframeKey((prev) => prev + 1);}}).catch((err) => {toast.error(err.response?.data?.error || "Failed to fetch commit pages");}).finally(() => {setIsLoadingCommitPages(false);});} else if (!currentCommit && prevCommitRef.current !== null) {// Only clear commitPages when transitioning from a commit to no commitsetCommitPages([]);}prevCommitRef.current = currentCommit;}, [currentCommit, namespace, repoId]);// Create navigation interception scriptconst createNavigationScript = useCallback((availablePages: Page[]) => {const pagePaths = availablePages.map((p) => p.path.replace(/^\.?\//, ""));return `(function() {const availablePages = ${JSON.stringify(pagePaths)};function normalizePath(path) {let normalized = path.replace(/^\.?\//, "");if (normalized === "" || normalized === "/") {normalized = "index.html";}const hashIndex = normalized.indexOf("#");if (hashIndex !== -1) {normalized = normalized.substring(0, hashIndex);}if (!normalized.includes(".")) {normalized = normalized + ".html";}return normalized;}function handleNavigation(url) {if (!url) return;// Handle hash-only navigationif (url.startsWith("#")) {const targetElement = document.querySelector(url);if (targetElement) {targetElement.scrollIntoView({ behavior: "smooth" });}// Search in shadow DOMconst searchInShadows = (root) => {const elements = root.querySelectorAll("*");for (const el of elements) {if (el.shadowRoot) {const found = el.shadowRoot.querySelector(url);if (found) {found.scrollIntoView({ behavior: "smooth" });return;}searchInShadows(el.shadowRoot);}}};searchInShadows(document);return;}// Handle external URLsif (url.startsWith("http://") || url.startsWith("https://") || url.startsWith("//")) {window.open(url, "_blank");return;}const normalizedPath = normalizePath(url);if (availablePages.includes(normalizedPath)) {// Dispatch custom event to notify parentwindow.parent.postMessage({ type: 'navigate', path: normalizedPath }, '*');} else {console.warn('Page not found:', normalizedPath);}}// Intercept window.location methodsconst originalAssign = window.location.assign;const originalReplace = window.location.replace;window.location.assign = function(url) {handleNavigation(url);};window.location.replace = function(url) {handleNavigation(url);};// Intercept window.location.href settertry {let currentHref = window.location.href;Object.defineProperty(window.location, 'href', {get: function() {return currentHref;},set: function(url) {handleNavigation(url);},configurable: true});} catch (e) {// Fallback: use proxy if defineProperty failsconsole.warn('Could not intercept location.href:', e);}// Intercept link clicksdocument.addEventListener('click', function(e) {const anchor = e.target.closest('a');if (anchor && anchor.href) {const href = anchor.getAttribute('href');if (href && !href.startsWith('http://') && !href.startsWith('https://') && !href.startsWith('//') && !href.startsWith('mailto:') && !href.startsWith('tel:')) {e.preventDefault();handleNavigation(href);}}}, true);// Intercept form submissionsdocument.addEventListener('submit', function(e) {const form = e.target;if (form.action && !form.action.startsWith('http://') && !form.action.startsWith('https://') && !form.action.startsWith('//')) {e.preventDefault();handleNavigation(form.action);}}, true);})();`;}, []);const injectAssetsIntoHtml = useCallback((html: string, pagesToUse: Page[] = pages): string => {if (!html) return html;const cssFiles = pagesToUse.filter((p) => p.path.endsWith(".css") && p.path !== previewPageData?.path);const jsFiles = pagesToUse.filter((p) => p.path.endsWith(".js") && p.path !== previewPageData?.path);const jsonFiles = pagesToUse.filter((p) => p.path.endsWith(".json") && p.path !== previewPageData?.path);let modifiedHtml = html;// Inject navigation script for srcDocconst navigationScript = createNavigationScript(pagesToUse);// Inject all CSS filesif (cssFiles.length > 0) {const allCssContent = cssFiles96 unmodified lines});}// Inject navigation script early in the documentif (navigationScript) {// Try to inject right after <head> or <body> opening tagif (modifiedHtml.includes("<head>")) {modifiedHtml = modifiedHtml.replace("<head>",`<head>\n<script>${navigationScript}</script>`);} else if (modifiedHtml.includes("<body>")) {modifiedHtml = modifiedHtml.replace("<body>",`<body>\n<script>${navigationScript}</script>`);} else if (modifiedHtml.includes("</body>")) {modifiedHtml = modifiedHtml.replace("</body>",`<script>${navigationScript}</script>\n</body>`);} else {modifiedHtml =`<script>${navigationScript}</script>\n` + modifiedHtml;}}return modifiedHtml;},[pages, previewPageData?.path, createNavigationScript]);useEffect(() => {2 unmodified linesconst timeSinceLastUpdate = now - lastUpdateTimeRef.current;if (lastUpdateTimeRef.current === 0 || timeSinceLastUpdate >= 3000) {const processedHtml = injectAssetsIntoHtml(previewPageData.html,pagesToUse);setThrottledHtml(processedHtml);lastUpdateTimeRef.current = now;} else {const timeUntilNextUpdate = 3000 - timeSinceLastUpdate;const timer = setTimeout(() => {const processedHtml = injectAssetsIntoHtml(previewPageData.html,pagesToUse);setThrottledHtml(processedHtml);lastUpdateTimeRef.current = Date.now();}, timeUntilNextUpdate);return () => clearTimeout(timer);}}}, [isNew, previewPageData?.html, injectAssetsIntoHtml, pagesToUse]);useEffect(() => {if (!isAiWorking && !globalAiLoading && previewPageData?.html) {const processedHtml = injectAssetsIntoHtml(previewPageData.html,pagesToUse);setStableHtml(processedHtml);}}, [2 unmodified linespreviewPageData?.html,injectAssetsIntoHtml,previewPage,pagesToUse,]);useEffect(() => {3 unmodified lines!isAiWorking &&!globalAiLoading) {const processedHtml = injectAssetsIntoHtml(previewPageData.html,pagesToUse);setStableHtml(processedHtml);}}, [2 unmodified linesisAiWorking,globalAiLoading,injectAssetsIntoHtml,pagesToUse,]);const setupIframeListeners = () => {14 unmodified lines}};// Listen for navigation messages from iframeuseEffect(() => {const handleMessage = (event: MessageEvent) => {if (event.data?.type === "navigate" && event.data?.path) {setPreviewPage(event.data.path);}};window.addEventListener("message", handleMessage);return () => window.removeEventListener("message", handleMessage);}, [setPreviewPage]);useEffect(() => {const cleanupListeners = () => {if (iframeRef?.current?.contentDocument) {208 unmodified linesnormalizedHref = normalizedHref + ".html";}const isPageExist = pagesToUse.some((page) => {const pagePath = page.path.replace(/^\.?\//, "");return pagePath === normalizedHref;});51 unmodified lines</div>) : (<>{isLoadingCommitPages && (<div className="top-0 left-0 right-0 z-20 bg-blue-500/90 backdrop-blur-sm border-b border-blue-600 px-4 py-2 flex items-center justify-center gap-3 text-sm w-full"><div className="flex items-center gap-2"><AiLoadingtext="Loading commit version..."className="flex-row"/></div></div>)}{!isNew && !currentCommit && (<div className="top-0 left-0 right-0 z-20 bg-amber-500/90 backdrop-blur-sm border-b border-amber-600 px-4 py-2 flex items-center justify-between gap-3 text-sm w-full"><div className="flex items-center gap-2 flex-1"><TriangleAlert className="size-4 text-amber-900 flex-shrink-0" /><span className="text-amber-900 font-medium">Preview version of the project. Try refreshing the preview ifyou experience any issues.</span></div><buttononClick={refreshIframe}className="cursor-pointer text-xs px-3 py-1 bg-amber-900 hover:bg-amber-800 text-amber-50 rounded-md font-medium transition-colors whitespace-nowrap flex items-center gap-1.5"><RefreshCcw className="size-3 text-amber-50 flex-shrink-0" />Refresh</button></div>)}<iframekey={iframeKey}id="preview-iframe"6 unmodified lines})}src={!currentCommit &&!isNew &&!hasUnsavedChanges &&project?.space_id &&!project?.private? `https://${project.space_id.replaceAll("/","-"1 unmodified line: undefined}srcDoc={currentCommit? commitPages.length > 0 && previewPageData?.html? injectAssetsIntoHtml(previewPageData.html, commitPages): defaultHTML: isNew || hasUnsavedChanges || project?.private? isNew? throttledHtml || defaultHTML: stableHtml1 unmodified line}onLoad={() => {if (currentCommit ||isNew ||hasUnsavedChanges ||project?.private) {if (iframeRef?.current?.contentWindow?.document?.body) {iframeRef.current.contentWindow.document.body.scrollIntoView({
app/api/me/projects/[namespace]/[repoId]/commits/[commitId]/route.tsAdded+102
app/api/proxy/[...path]/route.tsAdded+547
app/api/proxy/route.tsAdded+557
components/editor/index.tsx+1-1
components/editor/preview/index.tsx+264-50