diff --git a/fixtures/webstudio-features/app/__generated__/$resources.assets.ts b/fixtures/webstudio-features/app/__generated__/$resources.assets.ts index 38ec702446..0729c53a73 100644 --- a/fixtures/webstudio-features/app/__generated__/$resources.assets.ts +++ b/fixtures/webstudio-features/app/__generated__/$resources.assets.ts @@ -138,6 +138,10 @@ "/cat_silhouette.png": "/assets/cat_silhouette_BDpTbUFSpVbfUWQZNxbBG.png", "/small-avif-kitty.webp": "/assets/small-avif-kitty_FnabJsioMWpBtXZSGf4DR.webp", "/video_QamtUWsD-ShifhzZLoNIv.mp4": "/assets/video_QamtUWsD-ShifhzZLoNIv_ald_1xtyEb3uHhFb7nCQa.mp4", - "/_937084ed-a798-49fe-8664-df93a2af605e.jpeg": "/assets/_937084ed-a798-49fe-8664-df93a2af605e_uiBk3o6UWdqolyakMvQJ9.jpeg" + "/_937084ed-a798-49fe-8664-df93a2af605e.jpeg": "/assets/_937084ed-a798-49fe-8664-df93a2af605e_uiBk3o6UWdqolyakMvQJ9.jpeg", + "/cgi/asset/e-mail-39993_vrxyjxQv3j67Krs62Vz7Y.mp3": "/assets/e-mail-39993_vrxyjxQv3j67Krs62Vz7Y.mp3", + "/cgi/asset/cabinsketch-bold_TLCbytfxf8ENHwZ6ze3Jj.ttf": "/assets/cabinsketch-bold_TLCbytfxf8ENHwZ6ze3Jj.ttf", + "/cgi/asset/webm-example_2r_6VmRBjhAy3ldaqz0gk.webm": "/assets/webm-example_2r_6VmRBjhAy3ldaqz0gk.webm", + "/cgi/asset/video_QamtUWsD-ShifhzZLoNIv_ald_1xtyEb3uHhFb7nCQa.mp4": "/assets/video_QamtUWsD-ShifhzZLoNIv_ald_1xtyEb3uHhFb7nCQa.mp4" }; \ No newline at end of file diff --git a/packages/cli/src/commands/mcp-preview.test.ts b/packages/cli/src/commands/mcp-preview.test.ts index 4751cb5431..bff16ddaa6 100644 --- a/packages/cli/src/commands/mcp-preview.test.ts +++ b/packages/cli/src/commands/mcp-preview.test.ts @@ -1940,69 +1940,80 @@ test("reports an interior route HTTP failure instead of a wrong-site error", asy }); }); -test("reports a safe script location and saved PNG through MCP error serialization", async () => { - const capturePage = vi.fn().mockResolvedValueOnce([ - { - output: "/tmp/builder.png", - navigation: { - generatedSiteRootPresent: true, - javascriptErrorPresent: true, - javascriptErrorLocation: { - pathname: "/assets/app.js", - line: 42, +test.each([ + { + name: "a safe script location", + navigation: { + javascriptErrorLocation: { pathname: "/assets/app.js", line: 42 }, + }, + message: + "The page reported a JavaScript error during screenshot capture at /assets/app.js:42.", + issue: { file: "/assets/app.js", line: 42 }, + }, + { + name: "a line without a safe script path", + navigation: { javascriptErrorLocation: { line: 42 } }, + message: "The page reported a JavaScript error during screenshot capture.", + issue: { line: 42 }, + }, +])( + "reports $name and saved PNG through MCP error serialization", + async ({ navigation, message, issue }) => { + const capturePage = vi.fn().mockResolvedValueOnce([ + { + output: "/tmp/builder.png", + navigation: { + generatedSiteRootPresent: true, + javascriptErrorPresent: true, + ...navigation, }, }, - }, - ]); - const handlers = createMcpPreviewHandlers({ - preview: { - status: vi.fn(() => ({ - url: "http://127.0.0.1:5173/", - running: true, - mode: "iterative" as const, - })), - startAndWait: vi.fn(), - resolveUrl: vi.fn(() => "http://127.0.0.1:5173/"), - }, - isStale: () => false, - createCaptureSession: vi.fn(() => ({ - capture: vi.fn(), - capturePage, - close: vi.fn(), - })) as never, - }); + ]); + const handlers = createMcpPreviewHandlers({ + preview: { + status: vi.fn(() => ({ + url: "http://127.0.0.1:5173/", + running: true, + mode: "iterative" as const, + })), + startAndWait: vi.fn(), + resolveUrl: vi.fn(() => "http://127.0.0.1:5173/"), + }, + isStale: () => false, + createCaptureSession: vi.fn(() => ({ + capture: vi.fn(), + capturePage, + close: vi.fn(), + })) as never, + }); - const input = [ - { - path: "/", - source: "session" as const, - viewport: { width: 1280, height: 720 }, - }, - ]; - const error = await handlers - .capturePageScreenshots(input) - .catch((error) => error); - const serialized = mcpTesting.createMcpSingleOpCallErrorPayload({ - error, - elapsedMs: 1, - }); - expect( - serialized.error.message.startsWith( - "The page reported a JavaScript error during screenshot capture at /assets/app.js:42." - ) - ).toBe(true); - expect(serialized).toMatchObject({ - error: { - code: "SCREENSHOT_JAVASCRIPT_ERROR", - issues: [ - { - code: "screenshot_javascript_error", - file: "/assets/app.js", - line: 42, - reference: "/tmp/builder.png", - constraint: "javascript_runtime_error", - }, - ], - }, - }); -}); + const input = [ + { + path: "/", + source: "session" as const, + viewport: { width: 1280, height: 720 }, + }, + ]; + const error = await handlers + .capturePageScreenshots(input) + .catch((error) => error); + const serialized = mcpTesting.createMcpSingleOpCallErrorPayload({ + error, + elapsedMs: 1, + }); + expect(serialized.error.message.startsWith(message)).toBe(true); + expect(serialized).toMatchObject({ + error: { + code: "SCREENSHOT_JAVASCRIPT_ERROR", + issues: [ + { + code: "screenshot_javascript_error", + reference: "/tmp/builder.png", + constraint: "javascript_runtime_error", + ...issue, + }, + ], + }, + }); + } +); diff --git a/packages/cli/src/commands/mcp-preview.ts b/packages/cli/src/commands/mcp-preview.ts index 4842839cd7..6fbc4759b9 100644 --- a/packages/cli/src/commands/mcp-preview.ts +++ b/packages/cli/src/commands/mcp-preview.ts @@ -565,7 +565,7 @@ export const createMcpPreviewHandlers = ({ } if (result.navigation?.javascriptErrorPresent === true) { const location = result.navigation.javascriptErrorLocation; - const message = location + const message = location?.pathname ? `The page reported a JavaScript error during screenshot capture at ${location.pathname}:${location.line}.` : "The page reported a JavaScript error during screenshot capture."; throw Object.assign(new Error(message), { @@ -576,9 +576,10 @@ export const createMcpPreviewHandlers = ({ path: [], message, constraint: "javascript_runtime_error", - ...(location === undefined + ...(location?.pathname === undefined ? {} - : { file: location.pathname, line: location.line }), + : { file: location.pathname }), + ...(location === undefined ? {} : { line: location.line }), ...(result.output === undefined ? {} : { reference: result.output }), diff --git a/packages/cli/src/prebuild.test.ts b/packages/cli/src/prebuild.test.ts index 2a5e520c85..de345fcf19 100644 --- a/packages/cli/src/prebuild.test.ts +++ b/packages/cli/src/prebuild.test.ts @@ -2759,7 +2759,10 @@ sitemap.map((page) => page.path);` expect(assetsModule).toContain('"url": "/assets/audio.mp3"'); expect(assetsModule).toContain("export const assetUrlsByPath"); expect(assetsModule).toContain('"/audio.mp3": "/assets/audio.mp3"'); - expect(assetsModule).not.toContain("/cgi/"); + expect(assetsModule).toContain( + '"/cgi/asset/audio.mp3": "/assets/audio.mp3"' + ); + expect(assetsModule).not.toContain('": "/cgi/'); const route = await readFile("app/routes/_index.tsx", "utf8"); expect(route).toContain("assetUrlsByPath"); diff --git a/packages/project-build/src/runtime/asset-urls.test.ts b/packages/project-build/src/runtime/asset-urls.test.ts index 4611d67527..64a8ba4349 100644 --- a/packages/project-build/src/runtime/asset-urls.test.ts +++ b/packages/project-build/src/runtime/asset-urls.test.ts @@ -7,11 +7,13 @@ const asset = ({ name, filename, folderId, + type = "file", }: { id: string; name: string; filename?: string; folderId?: string; + type?: Asset["type"]; }) => ({ id, @@ -19,7 +21,7 @@ const asset = ({ filename, folderId, projectId: "project", - type: "file", + type, size: 1, format: name.slice(name.lastIndexOf(".") + 1), createdAt: "2026-01-01T00:00:00.000Z", @@ -40,7 +42,12 @@ test("creates runtime URLs keyed by root-relative asset paths", () => { ], ]); const assets = [ - asset({ id: "hero", name: "hero_hash.png", filename: "Hero image" }), + asset({ + id: "hero", + name: "hero_hash.png", + filename: "Hero image", + type: "image", + }), asset({ id: "script", name: "test_hash.js", @@ -53,15 +60,153 @@ test("creates runtime URLs keyed by root-relative asset paths", () => { createAssetUrlsByPath({ assets, assetFolders: folders, - getUrl: (item) => `/cgi/asset/${item.name}`, + getUrl: (item) => + item.type === "image" + ? `/cgi/image/${item.name}?format=raw` + : `/cgi/asset/${item.name}?format=raw`, }) ).toEqual({ - "/Hero%20image.png": "/cgi/asset/hero_hash.png", - "/Custom%20scripts/test.js": "/cgi/asset/test_hash.js", + "/Hero%20image.png": "/cgi/image/hero_hash.png?format=raw", + "/Custom%20scripts/test.js": "/cgi/asset/test_hash.js?format=raw", }); }); -test("omits ambiguous asset paths", () => { +test("resolves published CGI asset URLs by the stored asset name", () => { + expect( + createAssetUrlsByPath({ + assets: [ + asset({ + id: "script", + name: "dashboard_hash.js", + filename: "dashboard", + }), + ], + assetFolders: new Map(), + getUrl: (item) => `/assets/${item.name}`, + }) + ).toMatchObject({ + "/cgi/asset/dashboard_hash.js": "/assets/dashboard_hash.js", + }); +}); + +test("maps video assets that use the CGI asset route", () => { + expect( + createAssetUrlsByPath({ + assets: [ + asset({ + id: "video", + name: "clip_hash.mp4", + filename: "clip", + type: "video", + }), + ], + assetFolders: new Map(), + getUrl: (item) => `/assets/${item.name}`, + }) + ).toMatchObject({ + "/cgi/asset/clip_hash.mp4": "/assets/clip_hash.mp4", + }); +}); + +test("keeps a CGI alias when a stored asset is duplicated", () => { + expect( + createAssetUrlsByPath({ + assets: [ + asset({ id: "first", name: "app_hash.js", filename: "app" }), + asset({ id: "copy", name: "app_hash.js", filename: "app copy" }), + ], + assetFolders: new Map(), + getUrl: (item) => `/assets/${item.name}`, + }) + ).toMatchObject({ + "/cgi/asset/app_hash.js": "/assets/app_hash.js", + }); +}); + +test("omits duplicate canonical paths even when their asset URLs match", () => { + expect( + createAssetUrlsByPath({ + assets: [ + asset({ id: "first", name: "app_hash.js", filename: "app" }), + asset({ id: "copy", name: "app_hash.js", filename: "app" }), + ], + assetFolders: new Map(), + getUrl: (item) => `/assets/${item.name}`, + }) + ).toEqual({ + "/cgi/asset/app_hash.js": "/assets/app_hash.js", + }); +}); + +test("rewrites CGI URLs for a custom generated asset base", () => { + expect( + createAssetUrlsByPath({ + assets: [asset({ id: "script", name: "app_hash.js", filename: "app" })], + assetFolders: new Map(), + getUrl: (item) => `/media/${item.name}`, + }) + ).toMatchObject({ + "/cgi/asset/app_hash.js": "/media/app_hash.js", + }); +}); + +test("keeps a canonical path when another asset's CGI alias matches it", () => { + const folders: AssetFolders = new Map([ + [ + "cgi", + { + id: "cgi", + projectId: "project", + name: "cgi", + createdAt: "2026-01-01T00:00:00.000Z", + }, + ], + [ + "asset", + { + id: "asset", + projectId: "project", + name: "asset", + parentId: "cgi", + createdAt: "2026-01-01T00:00:00.000Z", + }, + ], + ]); + + expect( + createAssetUrlsByPath({ + assets: [ + asset({ + id: "script", + name: "app_hash.js", + filename: "app_hash", + folderId: "asset", + }), + asset({ id: "other", name: "app_hash.js", filename: "other" }), + ], + assetFolders: folders, + getUrl: (item) => `/media/${item.id}/${item.name}`, + }) + ).toEqual({ + "/cgi/asset/app_hash.js": "/media/script/app_hash.js", + "/other.js": "/media/other/app_hash.js", + }); +}); + +test("omits a CGI path that points to different asset URLs", () => { + const assetUrlsByPath = createAssetUrlsByPath({ + assets: [ + asset({ id: "first", name: "app_hash.js", filename: "first" }), + asset({ id: "second", name: "app_hash.js", filename: "second" }), + ], + assetFolders: new Map(), + getUrl: (item) => `/${item.id}/${item.name}`, + }); + + expect(assetUrlsByPath).not.toHaveProperty("/cgi/asset/app_hash.js"); +}); + +test("omits ambiguous canonical paths but keeps unique CGI URLs", () => { const assets = [ asset({ id: "first", name: "first_hash.js", filename: "test" }), asset({ id: "second", name: "second_hash.js", filename: "test" }), @@ -73,5 +218,8 @@ test("omits ambiguous asset paths", () => { assetFolders: new Map(), getUrl: (item) => `/assets/${item.name}`, }) - ).toEqual({}); + ).toEqual({ + "/cgi/asset/first_hash.js": "/assets/first_hash.js", + "/cgi/asset/second_hash.js": "/assets/second_hash.js", + }); }); diff --git a/packages/project-build/src/runtime/asset-urls.ts b/packages/project-build/src/runtime/asset-urls.ts index 71619f1aae..a900b43f29 100644 --- a/packages/project-build/src/runtime/asset-urls.ts +++ b/packages/project-build/src/runtime/asset-urls.ts @@ -3,6 +3,7 @@ import { createCanonicalAssetPath } from "@webstudio-is/content-engine/mdx"; import { createAssetFolderHierarchy, formatAssetName, + isResizableImageFileName, type Asset, type AssetFolders, } from "@webstudio-is/sdk"; @@ -18,20 +19,43 @@ export const createAssetUrlsByPath = ({ }) => { const hierarchy = createAssetFolderHierarchy(assetFolders); const urlsById = new Map(); + const canonicalPaths = new Set(); + const cgiAliases = new Map(); const assetIdsByPath = createUniqueAssetIdsByPath( Array.from(assets, (asset) => { - urlsById.set(asset.id, getUrl(asset)); - return { - id: asset.id, - path: createCanonicalAssetPath({ - folderNames: hierarchy - .getPath(asset.folderId) - .map((folder) => folder.name), - name: formatAssetName(asset), - }), - }; + const url = getUrl(asset); + urlsById.set(asset.id, url); + const canonicalAssetPath = createCanonicalAssetPath({ + folderNames: hierarchy + .getPath(asset.folderId) + .map((folder) => folder.name), + name: formatAssetName(asset), + }); + canonicalPaths.add(canonicalAssetPath); + const cgiAssetPath = createCanonicalAssetPath({ + folderNames: ["cgi", "asset"], + name: asset.name, + }); + const targetUrl = new URL(url, "https://webstudio.invalid"); + if ( + isResizableImageFileName(asset.name) === false && + (targetUrl.pathname !== `/${cgiAssetPath}` || + targetUrl.origin !== "https://webstudio.invalid") + ) { + cgiAliases.set(`${cgiAssetPath}\0${url}`, { + id: asset.id, + path: cgiAssetPath, + }); + } + return { id: asset.id, path: canonicalAssetPath }; }) ); + for (const [path, id] of createUniqueAssetIdsByPath(cgiAliases.values())) { + // Ambiguous canonical paths still reserve the path. + if (canonicalPaths.has(path) === false) { + assetIdsByPath.set(path, id); + } + } return Object.fromEntries( Array.from(assetIdsByPath, ([path, assetId]) => { return [`/${path}`, urlsById.get(assetId)!]; diff --git a/packages/sdk-components-react/src/html-embed-assets.test.ts b/packages/sdk-components-react/src/html-embed-assets.test.ts index 0584fd167c..e742aac926 100644 --- a/packages/sdk-components-react/src/html-embed-assets.test.ts +++ b/packages/sdk-components-react/src/html-embed-assets.test.ts @@ -2,6 +2,7 @@ import { expect, test } from "vitest"; import { resolveHtmlEmbedAssetUrls } from "./html-embed-assets"; const assetUrlsByPath = { + "/cgi/asset/test_hash.js": "/assets/test_hash.js", "/test.js": "/cgi/asset/test_hash.js?format=raw", "/site.css": "/cgi/asset/site_hash.css?format=raw", "/hero.png": "/cgi/image/hero_hash.png?format=raw", @@ -10,6 +11,15 @@ const assetUrlsByPath = { "/hero%402x.png": "/cgi/image/hero_2x_hash.png?format=raw", }; +test("rewrites a published CGI asset URL to its generated preview URL", () => { + expect( + resolveHtmlEmbedAssetUrls( + ``, + assetUrlsByPath + ) + ).toBe(``); +}); + test("rewrites asset attributes without reformatting embed markup", () => { const code = ` diff --git a/packages/vision/src/screenshot-browser-cdp.test.ts b/packages/vision/src/screenshot-browser-cdp.test.ts index a3b0964d88..65aeb2ec43 100644 --- a/packages/vision/src/screenshot-browser-cdp.test.ts +++ b/packages/vision/src/screenshot-browser-cdp.test.ts @@ -64,6 +64,7 @@ class FakeWebSocket { readonly runtimeErrorScenario?: | "console-error" | "exception-error" + | "exception-error-with-late-safe-path" | "stale-outgoing-error" | "hash-navigation-error"; readonly exceptionUrl?: string; @@ -447,32 +448,43 @@ class FakeWebSocket { const shouldLogError = this.runtimeErrorScenario === "console-error" || this.runtimeErrorScenario === "exception-error" || + this.runtimeErrorScenario === "exception-error-with-late-safe-path" || ((this.runtimeErrorScenario === "stale-outgoing-error" || sameDocumentNavigation) && navigationNumber === 2); if (shouldLogError) { const isException = this.runtimeErrorScenario !== "console-error"; - this.emit("message", { - data: JSON.stringify({ - method: isException - ? "Runtime.exceptionThrown" - : "Runtime.consoleAPICalled", - params: isException - ? { - exceptionDetails: { - executionContextId: - this.runtimeErrorScenario === "exception-error" - ? executionContextId - : 1, - url: - this.exceptionUrl ?? - "https://user:pass@example.com/assets/exception.js?token=private#fragment", - lineNumber: 6, - }, - } - : { type: "error", executionContextId }, - }), - }); + const urls = + this.runtimeErrorScenario === "exception-error-with-late-safe-path" + ? [ + "https://example.com/private/customer-123.js", + "https://example.com/assets/app.js?token=private", + ] + : [ + this.exceptionUrl ?? + "https://user:pass@example.com/assets/exception.js?token=private#fragment", + ]; + for (const url of urls) { + this.emit("message", { + data: JSON.stringify({ + method: isException + ? "Runtime.exceptionThrown" + : "Runtime.consoleAPICalled", + params: isException + ? { + exceptionDetails: { + executionContextId: + this.runtimeErrorScenario === "exception-error" + ? executionContextId + : 1, + url, + lineNumber: 6, + }, + } + : { type: "error", executionContextId }, + }), + }); + } } for (const frameId of sameDocumentNavigation ? [] @@ -2645,6 +2657,37 @@ test("reports a page exception script path and one-based line without its URL qu expect(JSON.stringify(layout.navigation)).not.toContain("fragment"); }); +test("prefers a safe script path over an earlier line-only error", async () => { + const layout = await captureBrowserScreenshot( + { + url: "https://example.com", + output: "/tmp/page-exception.png", + width: 800, + height: 600, + browserPath: "/usr/bin/chromium", + waitUntil: "networkidle", + waitForTimeout: 0, + timeout: 1000, + }, + createDependencies({ + socket: new FakeWebSocket( + 200, + undefined, + undefined, + undefined, + ["main"], + false, + "exception-error-with-late-safe-path" + ), + }) + ); + + expect(layout.navigation?.javascriptErrorLocation).toEqual({ + pathname: "/assets/app.js", + line: 7, + }); +}); + test.each([ "https://example.com/private/customer-123.js?token=private", "https://example.com/assets/data.json", @@ -2675,7 +2718,7 @@ test.each([ ); expect(layout.navigation?.javascriptErrorPresent).toBe(true); - expect(layout.navigation?.javascriptErrorLocation).toBeUndefined(); + expect(layout.navigation?.javascriptErrorLocation).toEqual({ line: 7 }); expect(JSON.stringify(layout.navigation)).not.toContain( new URL(url).pathname ); diff --git a/packages/vision/src/screenshot-browser-cdp.ts b/packages/vision/src/screenshot-browser-cdp.ts index bd77d5beb0..db390686ee 100644 --- a/packages/vision/src/screenshot-browser-cdp.ts +++ b/packages/vision/src/screenshot-browser-cdp.ts @@ -451,7 +451,6 @@ const getJavascriptErrorLocation = (params: unknown) => { } const { url, lineNumber } = params as Record; if ( - typeof url !== "string" || typeof lineNumber !== "number" || Number.isSafeInteger(lineNumber) === false || lineNumber < 0 || @@ -459,19 +458,31 @@ const getJavascriptErrorLocation = (params: unknown) => { ) { return; } - try { - const scriptUrl = new URL(url); - if ( - (scriptUrl.protocol === "http:" || scriptUrl.protocol === "https:") && - isGeneratedStaticScriptPath(scriptUrl.pathname) - ) { - return { pathname: scriptUrl.pathname, line: lineNumber + 1 }; + const line = lineNumber + 1; + if (typeof url === "string") { + try { + const scriptUrl = new URL(url); + if ( + (scriptUrl.protocol === "http:" || scriptUrl.protocol === "https:") && + isGeneratedStaticScriptPath(scriptUrl.pathname) + ) { + return { pathname: scriptUrl.pathname, line }; + } + } catch { + // Keep a safe line number when the source URL cannot be exposed. } - } catch { - return; } + return { line }; }; +const preferJavascriptErrorLocation = ( + current: BrowserScreenshotNavigation["javascriptErrorLocation"], + next: BrowserScreenshotNavigation["javascriptErrorLocation"] +) => + current?.pathname === undefined && next?.pathname !== undefined + ? next + : (current ?? next); + const navigateAndWaitForLifecycle = async ( cdp: CdpSession, waitUntil: ScreenshotWaitUntil, @@ -821,7 +832,7 @@ export type BrowserScreenshotNavigation = { redirects: string[]; documentReadyState: string; javascriptErrorPresent?: boolean; - javascriptErrorLocation?: { pathname: string; line: number }; + javascriptErrorLocation?: { pathname?: string; line: number }; pageMetadata?: BrowserScreenshotPageMetadata; layoutStable: boolean; }; @@ -1768,11 +1779,17 @@ const capturePageWithBrowserRuntime = async ( if (navigationExecutionContextFrames !== undefined) { navigationErrorsByContextId.set( executionContextId, - navigationErrorsByContextId.get(executionContextId) ?? location + preferJavascriptErrorLocation( + navigationErrorsByContextId.get(executionContextId), + location + ) ); } else if (activeExecutionContextIds.has(executionContextId)) { javascriptErrorPresent = true; - javascriptErrorLocation ??= location; + javascriptErrorLocation = preferJavascriptErrorLocation( + javascriptErrorLocation, + location + ); } }; cdp.on("Runtime.executionContextCreated", (params) => { @@ -1931,8 +1948,10 @@ const capturePageWithBrowserRuntime = async ( for (const executionContextId of activeExecutionContextIds) { if (navigationErrorsByContextId.has(executionContextId)) { javascriptErrorPresent = true; - javascriptErrorLocation ??= - navigationErrorsByContextId.get(executionContextId); + javascriptErrorLocation = preferJavascriptErrorLocation( + javascriptErrorLocation, + navigationErrorsByContextId.get(executionContextId) + ); } } navigationExecutionContextFrames = undefined;