mirror of
https://github.com/webstudio-is/webstudio.git
synced 2026-12-01 21:05:42 +09:00
fix: Resolve asset URLs in generated previews (#6724)
An embedded dashboard remained at its loader in session preview because its script used the published `/cgi/asset/<stored-name>` URL. The generated preview had downloaded the asset, but its URL table only matched the friendly asset path, so the script request returned 404 locally. Map a stored file’s CGI URL to the generated asset path when the generated URL differs. Keep canonical paths subject to their existing ambiguity rules, and add CGI aliases without overriding canonical paths. Deduplicate aliases that share a destination and omit conflicting aliases. Resizable images keep their separate image route. Screenshot errors also keep a safe JavaScript line number when Chrome does not provide a safe generated source path, preferring a later safe filename when available. - [x] Reproduced #6723 on its reported project. Before the fix, the embedded script returned 404 in local preview; the published URL returned 200. - [x] After the fix, the script loaded and the page reached its sign-in screen with no failed requests or browser errors. The preview does not import the app’s authenticated session. - [x] Add regression tests for generated file aliases, duplicate and conflicting paths, custom asset bases, image routing, HtmlEmbed rewriting, and screenshot location ordering. - [x] Run focused suites: asset URL (9), HTML Embed (18), and targeted CLI prebuild (1 passed, 152 skipped); project-build typecheck, lint, formatting, and diff checks. - [x] Address final review findings for canonical path precedence and ambiguity; the existing HTML Embed documentation already states the expected behavior. - [x] Regenerate the affected fixture output; a second build produced no further changes. - [x] All required checks pass for the latest commit. Ref #6723
This commit is contained in:
1 parent
57b20ee85b
commit
bf288341a3
9 files changed
+385
-122
No files matched your search
@@ -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"
|
||||
};
|
||||
|
||||
@@ -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,
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
}
|
||||
);
|
||||
@@ -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 }),
|
||||
|
||||
@@ -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");
|
||||
|
||||
@@ -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",
|
||||
});
|
||||
});
|
||||
@@ -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<string, string>();
|
||||
const canonicalPaths = new Set<string>();
|
||||
const cgiAliases = new Map<string, { id: string; path: string }>();
|
||||
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)!];
|
||||
|
||||
@@ -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(
|
||||
`<script src="/cgi/asset/test_hash.js"></script>`,
|
||||
assetUrlsByPath
|
||||
)
|
||||
).toBe(`<script src="/assets/test_hash.js"></script>`);
|
||||
});
|
||||
|
||||
test("rewrites asset attributes without reformatting embed markup", () => {
|
||||
const code = `<SCRIPT defer SRC='/test.js#ready'></SCRIPT>
|
||||
<link href=/site.css rel=stylesheet>
|
||||
|
||||
@@ -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
|
||||
);
|
||||
|
||||
@@ -451,7 +451,6 @@ const getJavascriptErrorLocation = (params: unknown) => {
|
||||
}
|
||||
const { url, lineNumber } = params as Record<string, unknown>;
|
||||
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;
|
||||
|
||||
Reference in new issue
Block a user