Skip to content

Open source website builder and Webflow alternative. Webstudio is an advanced visual builder that connects to any headless CMS, supports all CSS properties, and can be hosted anywhere, including with us.

fix: resolve MCP-reported runtime and component issues (#6362)

Oleg Isonen39c290bfa799
diff --git a/apps/builder/app/routes/rest.assets.uploads_.$name.tsx b/apps/builder/app/routes/rest.assets.uploads_.$name.tsx
index a7832650ac..cd1776fbc8 100644
--- a/apps/builder/app/routes/rest.assets.uploads_.$name.tsx
+++ b/apps/builder/app/routes/rest.assets.uploads_.$name.tsx
@@ -7,6 +7,8 @@ import {
} from "@webstudio-is/asset-uploader/server";
import { isAssetFileName } from "@webstudio-is/protocol";
import {
+ assetDescriptionEncodingHeader,
+ assetDescriptionHeader,
assetResourceApiOperations,
type AssetUploadResult,
} from "@webstudio-is/protocol/asset-resource-api";
@@ -115,7 +117,8 @@ export const action = async (props: ActionFunctionArgs) => {
? undefined
: parseAssetRestIdentifier(folderIdValue);
const description = parseAssetRestDescription(
- request.headers.get("x-webstudio-asset-description")
+ request.headers.get(assetDescriptionHeader),
+ request.headers.get(assetDescriptionEncodingHeader)
);
if (assetType === undefined) {
throw new AssetRestRequestError("Asset type is invalid");
diff --git a/apps/builder/app/services/asset-rest.server.test.ts b/apps/builder/app/services/asset-rest.server.test.ts
index 9a7709b859..5e80ad7c50 100644
--- a/apps/builder/app/services/asset-rest.server.test.ts
+++ b/apps/builder/app/services/asset-rest.server.test.ts
@@ -198,6 +198,21 @@ describe("Assets REST responses", () => {
);
});
+ test("decodes UTF-8 asset descriptions carried in ASCII-safe headers", () => {
+ expect(
+ parseAssetRestDescription("QmFsa29uIG1pdCByb3RlbiBXw6RuZGVu", "base64url")
+ ).toBe("Balkon mit roten Wänden");
+ expect(parseAssetRestDescription("Legacy description")).toBe(
+ "Legacy description"
+ );
+ expect(() => parseAssetRestDescription("description", "unknown")).toThrow(
+ AssetRestRequestError
+ );
+ expect(() => parseAssetRestDescription("***", "base64url")).toThrow(
+ AssetRestRequestError
+ );
+ });
+
test("parses bounded multipart forms and rejects oversized forms", async () => {
const form = new FormData();
form.set("projectId", "project-1");
diff --git a/apps/builder/app/services/asset-rest.server.ts b/apps/builder/app/services/asset-rest.server.ts
index 298bd5b7fa..1d64aa5076 100644
--- a/apps/builder/app/services/asset-rest.server.ts
+++ b/apps/builder/app/services/asset-rest.server.ts
@@ -21,6 +21,7 @@ import type { ProjectPermit } from "@webstudio-is/trpc-interface/index.server";
import { assetFolderIssue } from "@webstudio-is/sdk";
import { assetResourceLimits } from "@webstudio-is/sdk/asset-resource-limits";
import { parseBuilderUrl } from "@webstudio-is/protocol";
+import { assetDescriptionEncoding } from "@webstudio-is/protocol/asset-resource-api";
import { ZodError } from "zod";
import { createAssetClient } from "~/shared/asset-client";
import { parseError } from "~/shared/error/error-parse";
@@ -121,15 +122,40 @@ export const parseAssetRestFilename = (value: string | undefined | null) =>
name: "filename",
});
-export const parseAssetRestDescription = (value: string | undefined | null) => {
- if (
- value !== undefined &&
- value !== null &&
- value.length > assetResourceLimits.assetDescriptionCharacters
- ) {
+export const parseAssetRestDescription = (
+ value: string | undefined | null,
+ encoding?: string | null
+) => {
+ if (value === undefined || value === null) {
+ return;
+ }
+ let description = value;
+ if (encoding !== undefined && encoding !== null) {
+ if (encoding !== assetDescriptionEncoding) {
+ throw new AssetRestRequestError(
+ "Assets API description encoding is invalid"
+ );
+ }
+ try {
+ const bytes = Buffer.from(value, "base64url");
+ if (
+ /^[A-Za-z0-9_-]*$/.test(value) === false ||
+ bytes.toString("base64url") !== value
+ ) {
+ throw new Error("Invalid base64url");
+ }
+ description = decodeUtf8(bytes);
+ } catch (cause) {
+ throw new AssetRestRequestError(
+ "Assets API description encoding is invalid",
+ { cause }
+ );
+ }
+ }
+ if (description.length > assetResourceLimits.assetDescriptionCharacters) {
throw new AssetRestRequestError("Assets API description is invalid");
}
- return value ?? undefined;
+ return description;
};
export const parseAssetRestMetadataHeader = (
diff --git a/packages/cli/evaluations/high-impact/fixture-api.test.ts b/packages/cli/evaluations/high-impact/fixture-api.test.ts
index 8a6734a95f..1a8401cb74 100644
--- a/packages/cli/evaluations/high-impact/fixture-api.test.ts
+++ b/packages/cli/evaluations/high-impact/fixture-api.test.ts
@@ -268,6 +268,7 @@ describe("high-impact fixture API", () => {
name,
type: "font",
format,
+ description: "Schriftgröße",
meta: fontAssetFixtureUploadMeta,
},
});
@@ -280,6 +281,9 @@ describe("high-impact fixture API", () => {
expect.objectContaining({ name: "upload-asset" }),
]);
expect(fixtureApi.getProject().assets).toHaveLength(2);
+ expect(
+ fixtureApi.getProject().assets.map((asset) => asset.description)
+ ).toEqual(["Schriftgröße", "Schriftgröße"]);
for (const asset of fixtureApi.getProject().assets) {
await run("update-asset", {
diff --git a/packages/cli/evaluations/high-impact/fixture-api.ts b/packages/cli/evaluations/high-impact/fixture-api.ts
index b31971c070..ef7c1427f3 100644
--- a/packages/cli/evaluations/high-impact/fixture-api.ts
+++ b/packages/cli/evaluations/high-impact/fixture-api.ts
@@ -20,6 +20,9 @@ import {
getAssetContentApiUrl,
} from "@webstudio-is/sdk/runtime";
import {
+ assetDescriptionEncoding,
+ assetDescriptionEncodingHeader,
+ assetDescriptionHeader,
assetContentDescriptorHeader,
serializeAssetContentDescriptor,
} from "@webstudio-is/protocol/asset-resource-api";
@@ -306,14 +309,21 @@ export const startHighImpactFixtureApi = async (
) {
throw new Error("Invalid asset upload request.");
}
- const description = request.headers["x-webstudio-asset-description"];
+ const descriptionHeader = request.headers[assetDescriptionHeader];
+ const description =
+ typeof descriptionHeader !== "string"
+ ? null
+ : request.headers[assetDescriptionEncodingHeader] ===
+ assetDescriptionEncoding
+ ? Buffer.from(descriptionHeader, "base64url").toString("utf8")
+ : descriptionHeader;
const folderId = url.searchParams.get("folderId") ?? undefined;
const assetBase = {
id: `evaluation-asset-${generatedId++}`,
projectId,
name,
filename: getFileNameParts(name).basename,
- description: typeof description === "string" ? description : null,
+ description,
size: body.byteLength,
...(folderId === undefined ? {} : { folderId }),
createdAt: "2026-01-01T00:00:00.000Z",
diff --git a/packages/css-data/src/shorthands.test.ts b/packages/css-data/src/shorthands.test.ts
index 76ba960034..4ad187e950 100644
--- a/packages/css-data/src/shorthands.test.ts
+++ b/packages/css-data/src/shorthands.test.ts
@@ -966,16 +966,28 @@ test("expand grid-area", () => {
["grid-row-start", "a"],
["grid-column-start", "b"],
["grid-row-end", "c"],
- ["grid-column-end", "auto"],
+ ["grid-column-end", "b"],
]);
expect(expandShorthands([["grid-area", "a / b"]])).toEqual([
["grid-row-start", "a"],
["grid-column-start", "b"],
- ["grid-row-end", "auto"],
- ["grid-column-end", "auto"],
+ ["grid-row-end", "a"],
+ ["grid-column-end", "b"],
]);
expect(expandShorthands([["grid-area", "a"]])).toEqual([
["grid-row-start", "a"],
+ ["grid-column-start", "a"],
+ ["grid-row-end", "a"],
+ ["grid-column-end", "a"],
+ ]);
+ expect(expandShorthands([["grid-area", "1 / area"]])).toEqual([
+ ["grid-row-start", "1"],
+ ["grid-column-start", "area"],
+ ["grid-row-end", "auto"],
+ ["grid-column-end", "area"],
+ ]);
+ expect(expandShorthands([["grid-area", "1"]])).toEqual([
+ ["grid-row-start", "1"],
["grid-column-start", "auto"],
["grid-row-end", "auto"],
["grid-column-end", "auto"],
diff --git a/packages/css-data/src/shorthands.ts b/packages/css-data/src/shorthands.ts
index 48bd664e11..7bb0179c69 100644
--- a/packages/css-data/src/shorthands.ts
+++ b/packages/css-data/src/shorthands.ts
@@ -83,6 +83,26 @@ const splitByOperator = (node: CssNode, operator: string) => {
.map((list) => createValueNode(list));
};
+const excludedGridLineIdentifiers = new Set([
+ ...cssWideKeywords,
+ "auto",
+ "span",
+ "default",
+]);
+
+const isGridLineCustomIdentifier = (value: CssNode | undefined) => {
+ if (value === undefined) {
+ return false;
+ }
+ const children = getValueList(value);
+ const child = children[0];
+ return (
+ children.length === 1 &&
+ child?.type === "Identifier" &&
+ excludedGridLineIdentifiers.has(child.name.toLowerCase()) === false
+ );
+};
+
const joinByOperator = (list: List<CssNode> | CssNode[], operator: string) => {
const joined: CssNode[] = [];
for (const node of list) {
@@ -1313,13 +1333,21 @@ const expandShorthand = function* (property: string, value: CssNode) {
value,
"/"
);
- yield ["grid-row-start", rowStart ?? createIdentifier("auto")] as const;
- yield [
- "grid-column-start",
- columnStart ?? createIdentifier("auto"),
- ] as const;
- yield ["grid-row-end", rowEnd ?? createIdentifier("auto")] as const;
- yield ["grid-column-end", columnEnd ?? createIdentifier("auto")] as const;
+ const auto = createIdentifier("auto");
+ const resolvedRowStart = rowStart ?? auto;
+ const resolvedColumnStart =
+ columnStart ?? (isGridLineCustomIdentifier(rowStart) ? rowStart : auto);
+ const resolvedRowEnd =
+ rowEnd ?? (isGridLineCustomIdentifier(rowStart) ? rowStart : auto);
+ const resolvedColumnEnd =
+ columnEnd ??
+ (isGridLineCustomIdentifier(resolvedColumnStart)
+ ? resolvedColumnStart
+ : auto);
+ yield ["grid-row-start", resolvedRowStart] as const;
+ yield ["grid-column-start", resolvedColumnStart] as const;
+ yield ["grid-row-end", resolvedRowEnd] as const;
+ yield ["grid-column-end", resolvedColumnEnd] as const;
break;
}
diff --git a/packages/http-client/src/index.test.ts b/packages/http-client/src/index.test.ts
index d950e69713..8db6a4617e 100644
--- a/packages/http-client/src/index.test.ts
+++ b/packages/http-client/src/index.test.ts
@@ -1149,7 +1149,7 @@ test("uploads assets as binary requests", async () => {
type: "image",
name: "image.png",
filename: "image.png",
- description: "Campaign photo",
+ description: "Balkon mit roten Wänden",
folderId: "campaign",
format: "png",
size: 3,
@@ -1170,8 +1170,11 @@ test("uploads assets as binary requests", async () => {
expect(init.headers).toBeInstanceOf(Headers);
expect((init.headers as Headers).get("x-auth-token")).toBe("token");
expect((init.headers as Headers).get("x-webstudio-asset-description")).toBe(
- "Campaign photo"
+ "QmFsa29uIG1pdCByb3RlbiBXw6RuZGVu"
);
+ expect(
+ (init.headers as Headers).get("x-webstudio-asset-description-encoding")
+ ).toBe("base64url");
expect((init.headers as Headers).get("content-type")).toBe(
"application/octet-stream"
);
diff --git a/packages/http-client/src/index.ts b/packages/http-client/src/index.ts
index 51a87f6a49..3c65ef5ff0 100644
--- a/packages/http-client/src/index.ts
+++ b/packages/http-client/src/index.ts
@@ -9,6 +9,9 @@ import {
import {
assetContentDescriptor,
assetContentDescriptorHeader,
+ assetDescriptionEncoding,
+ assetDescriptionEncodingHeader,
+ assetDescriptionHeader,
parseAssetContentDescriptor,
type AssetFolderUpdateRequest,
type AssetMetadataUpdate,
@@ -374,6 +377,12 @@ type AssetUploadBatchResult =
| { status: "rejected"; asset: Asset; index: number; error: unknown }
| { status: "ambiguous"; asset: Asset; index: number; error: unknown };
+const encodeAssetDescriptionHeader = (value: string) =>
+ btoa(String.fromCharCode(...new TextEncoder().encode(value)))
+ .replaceAll("+", "-")
+ .replaceAll("/", "_")
+ .replaceAll("=", "");
+
const formatError = (error: unknown) =>
error instanceof Error ? error.message : String(error);
@@ -436,6 +445,7 @@ export const uploadAsset = async (
}
): Promise<Asset[]> => {
const { authToken, headers, origin, projectId, upload } = params;
+ const description = upload.asset.description ?? undefined;
const result = await requestAssetRestJson<AssetUploadResult>(
fetchJsonResponse,
getAssetUploadUrl({
@@ -450,7 +460,12 @@ export const uploadAsset = async (
headers: createHeaders({
...headers,
"x-auth-token": authToken,
- "x-webstudio-asset-description": upload.asset.description ?? undefined,
+ [assetDescriptionHeader]:
+ description === undefined
+ ? undefined
+ : encodeAssetDescriptionHeader(description),
+ [assetDescriptionEncodingHeader]:
+ description === undefined ? undefined : assetDescriptionEncoding,
"x-webstudio-asset-meta": JSON.stringify(upload.asset.meta),
"content-type": "application/octet-stream",
}),
diff --git a/packages/project-build/src/build-integrity.test.ts b/packages/project-build/src/build-integrity.test.ts
index fbd68d587b..cb7c1f95a5 100644
--- a/packages/project-build/src/build-integrity.test.ts
+++ b/packages/project-build/src/build-integrity.test.ts
@@ -23,6 +23,37 @@ const resource: Resource = {
};
describe("getBuildIntegrityIssues", () => {
+ test("rejects a shared Slot inside Content Block Templates", () => {
+ const issues = getBuildIntegrityIssues({
+ dataSources: [],
+ props: [],
+ resources: [],
+ instances: [
+ {
+ type: "instance",
+ id: "templates",
+ component: "ws:block-template",
+ children: [{ type: "id", value: "slot" }],
+ },
+ {
+ type: "instance",
+ id: "slot",
+ component: "Slot",
+ children: [],
+ },
+ ],
+ });
+
+ expect(issues).toContainEqual({
+ type: "slotInContentBlockTemplates",
+ instanceId: "slot",
+ templatesInstanceId: "templates",
+ });
+ expect(formatBuildIntegrityIssue(issues[0])).toBe(
+ 'Shared Slot "slot" is inside Content Block Templates "templates". Duplicate the Slot content into a regular template instead.'
+ );
+ });
+
test("reports invalid Content Block source references", () => {
const block: Instance = {
type: "instance",
diff --git a/packages/project-build/src/build-integrity.ts b/packages/project-build/src/build-integrity.ts
index 97f86f7c57..3ffa561230 100644
--- a/packages/project-build/src/build-integrity.ts
+++ b/packages/project-build/src/build-integrity.ts
@@ -1,6 +1,9 @@
import {
+ blockTemplateComponent,
+ findTreeInstanceIds,
formatContentBlockSourceIntegrityIssue,
getContentBlockSourceIntegrityIssues,
+ portalComponent,
type Asset,
type ContentBlockSourceIntegrityIssue,
type DataSource,
@@ -24,6 +27,11 @@ export type BuildIntegrityIssue =
propName: string;
resourceId: string;
}
+ | {
+ type: "slotInContentBlockTemplates";
+ instanceId: string;
+ templatesInstanceId: string;
+ }
| ContentBlockSourceIntegrityIssue;
export const getBuildIntegrityIssues = ({
@@ -40,13 +48,31 @@ export const getBuildIntegrityIssues = ({
assets?: Iterable<Asset>;
}): BuildIntegrityIssue[] => {
const propsList = Array.from(props);
+ const instancesList = Array.from(instances);
const issues: BuildIntegrityIssue[] = [
...getContentBlockSourceIntegrityIssues({
- instances,
+ instances: instancesList,
props: propsList,
assets,
}),
];
+ const instancesById = new Map(
+ instancesList.map((instance) => [instance.id, instance])
+ );
+ for (const templates of instancesList) {
+ if (templates.component !== blockTemplateComponent) {
+ continue;
+ }
+ for (const instanceId of findTreeInstanceIds(instancesById, templates.id)) {
+ if (instancesById.get(instanceId)?.component === portalComponent) {
+ issues.push({
+ type: "slotInContentBlockTemplates",
+ instanceId,
+ templatesInstanceId: templates.id,
+ });
+ }
+ }
+ }
const resourceIds = new Set<string>();
for (const resource of resources) {
@@ -86,6 +112,9 @@ export const getBuildIntegrityIssues = ({
export const formatBuildIntegrityIssue = (
issue: BuildIntegrityIssue
): string => {
+ if (issue.type === "slotInContentBlockTemplates") {
+ return `Shared Slot "${issue.instanceId}" is inside Content Block Templates "${issue.templatesInstanceId}". Duplicate the Slot content into a regular template instead.`;
+ }
if (issue.type !== "missingResource") {
return formatContentBlockSourceIntegrityIssue(issue);
}
diff --git a/packages/project-build/src/contracts/__generated__/runtime-operation-contracts.ts b/packages/project-build/src/contracts/__generated__/runtime-operation-contracts.ts
index 571768e9f2..0f8ba9b206 100644
--- a/packages/project-build/src/contracts/__generated__/runtime-operation-contracts.ts
+++ b/packages/project-build/src/contracts/__generated__/runtime-operation-contracts.ts
@@ -38160,7 +38160,7 @@ export const runtimeOperationContractData = [
properties: {
scopes: {
description:
- "Audit scopes. Omit to run all standard scopes; Craft remains opt-in. accessibility errors: missing-alt, missing-image-input-alt, missing-iframe-title, missing-accessible-name, missing-form-label, invalid-aria-role, missing-required-aria-role-property, role-interactive-not-focusable, aria-hidden-focusable, invalid-aria-state, invalid-aria-number, autoplay-media-with-sound, invalid-label-reference, duplicate-id, and missing-aria-reference; warnings: missing-image-description, unsupported-aria-role-property, positive-tabindex, missing-page-heading, skipped-heading-level, missing-main-landmark, and multiple-main-landmarks. Documentation: https://www.w3.org/WAI/WCAG22/understanding/. security errors: non-get-resource-exposed-as-data-source; warning: target-blank-without-noopener. Documentation: https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Attributes/rel/noopener. seo errors: empty-page-title, invalid-json-ld, and json-ld-in-custom-metadata; warnings: missing-page-description, empty-page-description, invalid-page-language, missing-social-image-asset, duplicate-page-title, duplicate-page-description, missing-json-ld-context, unknown-schema-org-type, deprecated-schema-org-type, unknown-schema-org-property, deprecated-schema-org-property, unsupported-schema-org-property, and incompatible-schema-org-value. Documentation: https://developers.google.com/search/docs/fundamentals/seo-starter-guide. assets info: unused-asset. Documentation: https://docs.webstudio.is/university/foundations/anatomy-of-the-webstudio-builder. styles warnings: style-on-dom-transparent-component, invalid-style-state-selector, and orphan-style-breakpoint; info: unused-design-token, unused-css-variable, unused-local-style-source, unused-breakpoint, and duplicate-design-token-declarations. Documentation: https://docs.webstudio.is/university/foundations/design-tokens. performance info: atomic-css-disabled. Rendered checks add image loading/sizing, render-blocking resource, and legacy font-format evidence. Documentation: https://docs.webstudio.is/university/foundations/project-settings#atomic-css. craft is an opt-in, read-only compatibility check and is excluded when scopes are omitted. Documentation: https://docs.webstudio.is/university/craft.",
+ "Audit scopes. Omit to run all standard scopes; Craft remains opt-in. accessibility errors: missing-alt, missing-image-input-alt, missing-iframe-title, missing-accessible-name, missing-form-label, invalid-aria-role, missing-required-aria-role-property, role-interactive-not-focusable, aria-hidden-focusable, invalid-aria-state, invalid-aria-number, autoplay-media-with-sound, invalid-label-reference, duplicate-id, and missing-aria-reference; warnings: missing-image-description, unsupported-aria-role-property, positive-tabindex, missing-page-heading, skipped-heading-level, missing-main-landmark, and multiple-main-landmarks. Documentation: https://www.w3.org/WAI/WCAG22/understanding/. security errors: non-get-resource-exposed-as-data-source; warning: target-blank-without-noopener. Documentation: https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Attributes/rel/noopener. seo errors: empty-page-title, invalid-json-ld, and json-ld-in-custom-metadata; warnings: missing-page-description, empty-page-description, invalid-page-language, missing-social-image-asset, duplicate-page-title, duplicate-page-description, missing-json-ld-context, unknown-schema-org-type, deprecated-schema-org-type, unknown-schema-org-property, deprecated-schema-org-property, unsupported-schema-org-property, and incompatible-schema-org-value. Documentation: https://developers.google.com/search/docs/fundamentals/seo-starter-guide. assets info: unused-asset. When connected Content Blocks may hide MDX and nested Asset dependencies, unused-asset is skipped instead of returning unsafe false positives. Documentation: https://docs.webstudio.is/university/foundations/anatomy-of-the-webstudio-builder. styles warnings: style-on-dom-transparent-component, invalid-style-state-selector, and orphan-style-breakpoint; info: unused-design-token, unused-css-variable, unused-local-style-source, unused-breakpoint, and duplicate-design-token-declarations. Documentation: https://docs.webstudio.is/university/foundations/design-tokens. performance info: atomic-css-disabled. Rendered checks add image loading/sizing, render-blocking resource, and legacy font-format evidence. Documentation: https://docs.webstudio.is/university/foundations/project-settings#atomic-css. craft is an opt-in, read-only compatibility check and is excluded when scopes are omitted. Documentation: https://docs.webstudio.is/university/craft.",
minItems: 1,
type: "array",
items: {
@@ -44574,7 +44574,7 @@ export const runtimeOperationContractData = [
type: "string",
enum: ["ours", "theirs", "merge"],
description:
- 'How to resolve incoming design tokens that share a name with an existing token. "ours" keeps the existing token styles and id, "theirs" uses incoming styles, and "merge" combines both.',
+ 'Token conflicts: "ours" keeps, "theirs" replaces, and "merge" combines styles.',
},
contentMode: {
description:
@@ -54765,6 +54765,12 @@ export const runtimeOperationContractData = [
description:
"One structured repeated-item fragment. Descendant expressions may reference collectionItem and collectionItemKey.",
},
+ conflictResolution: {
+ type: "string",
+ enum: ["ours", "theirs", "merge"],
+ description:
+ 'Token conflicts: "ours" keeps, "theirs" replaces, and "merge" combines styles.',
+ },
mode: {
type: "string",
enum: ["append", "prepend", "replace"],
@@ -60668,7 +60674,7 @@ export const runtimeOperationContractData = [
type: "string",
enum: ["ours", "theirs", "merge"],
description:
- 'How to resolve incoming design tokens that share a name with an existing token. "ours" keeps the existing token styles and id, "theirs" uses incoming styles, and "merge" combines both.',
+ 'Token conflicts: "ours" keeps, "theirs" replaces, and "merge" combines styles.',
},
contentMode: {
description:
@@ -72714,6 +72720,7 @@ export const runtimeOperationContractData = [
properties: {
scopeInstanceId: {
type: "string",
+ description: 'Instance ID or ":root" for Global Root.',
},
name: {
type: "string",
@@ -72818,6 +72825,7 @@ export const runtimeOperationContractData = [
type: "object",
properties: {
scopeInstanceId: {
+ description: 'Instance ID or ":root" for Global Root.',
type: "string",
},
name: {
@@ -74224,6 +74232,7 @@ export const runtimeOperationContractData = [
},
scopeInstanceId: {
type: "string",
+ description: 'Instance ID or ":root" for Global Root.',
},
dataSourceName: {
type: "string",
@@ -74796,6 +74805,7 @@ export const runtimeOperationContractData = [
required: [],
},
scopeInstanceId: {
+ description: 'Instance ID or ":root" for Global Root.',
type: "string",
},
dataSourceName: {
@@ -75167,6 +75177,7 @@ export const runtimeOperationContractData = [
required: ["name", "method", "url", "headers"],
},
scopeInstanceId: {
+ description: 'Instance ID or ":root" for Global Root.',
type: "string",
},
dataSourceName: {
@@ -75426,6 +75437,7 @@ export const runtimeOperationContractData = [
type: "string",
},
scopeInstanceId: {
+ description: 'Instance ID or ":root" for Global Root.',
type: "string",
},
exposeAsDataSource: {
diff --git a/packages/project-build/src/runtime/asset-resources.ts b/packages/project-build/src/runtime/asset-resources.ts
index c9d6f437ec..7b7b7989cd 100644
--- a/packages/project-build/src/runtime/asset-resources.ts
+++ b/packages/project-build/src/runtime/asset-resources.ts
@@ -18,6 +18,8 @@ import type { BuilderRuntimeContext } from "./context";
import {
createResource,
normalizeResourceExpressionInput,
+ optionalResourceScopeInstanceIdInput,
+ resourceScopeInstanceIdInput,
unsetExpressionVariables,
updateResource,
} from "./data";
@@ -34,7 +36,7 @@ export const assetsResourceGetInput = z.object({ resourceId: z.string() });
export const assetsResourceCreateInput = z.object({
name: z.string().min(1),
query: assetQueryResourceConfigurationInput.optional(),
- scopeInstanceId: z.string(),
+ scopeInstanceId: resourceScopeInstanceIdInput,
dataSourceName: z.string().optional(),
});
@@ -48,7 +50,7 @@ export const assetsResourceUpdateInput = z.object({
.refine((values) => Object.keys(values).length > 0, {
error: "At least one Assets resource value is required.",
}),
- scopeInstanceId: z.string().optional(),
+ scopeInstanceId: optionalResourceScopeInstanceIdInput,
dataSourceName: z.string().optional(),
});
diff --git a/packages/project-build/src/runtime/audit.test.ts b/packages/project-build/src/runtime/audit.test.ts
index 383f4f6574..16365a8b3b 100644
--- a/packages/project-build/src/runtime/audit.test.ts
+++ b/packages/project-build/src/runtime/audit.test.ts
@@ -249,6 +249,44 @@ describe("project audit and analysis", () => {
).toThrow(/cursor does not match/i);
});
+ test("skips unsafe unused Asset findings for connected Content Blocks", () => {
+ const instances = new Map<string, Instance>(state.instances);
+ instances.set("content-block", {
+ type: "instance",
+ id: "content-block",
+ component: "ws:block",
+ children: [],
+ });
+ const props = new Map<string, Prop>(state.props);
+ props.set("content-block-source", {
+ id: "content-block-source",
+ instanceId: "content-block",
+ name: "src",
+ type: "asset",
+ value: "article-mdx",
+ });
+
+ const result = audit(
+ { ...state, instances, props },
+ { scopes: ["assets"], verbose: true, limit: 200 },
+ { projectVersion: 1 }
+ );
+
+ expect(result.findings).not.toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({ ruleId: "unused-asset" }),
+ ])
+ );
+ expect(result.skippedChecks).toContainEqual({
+ scope: "assets",
+ checkId: "content-asset-dependencies",
+ reason: "missing-build-data",
+ message:
+ "Unused Asset findings are skipped because connected Content Blocks can reference MDX files and nested Assets that are not visible in editable project data.",
+ location: {},
+ });
+ });
+
test("returns one finding for a CSS variable declared at multiple breakpoints", () => {
const styles = new Map<string, StyleDecl>(state.styles);
styles.set("local:base::--unused", {
diff --git a/packages/project-build/src/runtime/audit.ts b/packages/project-build/src/runtime/audit.ts
index a1b6d8d0cf..7a5525c615 100644
--- a/packages/project-build/src/runtime/audit.ts
+++ b/packages/project-build/src/runtime/audit.ts
@@ -1,4 +1,5 @@
import { isLiteralExpression } from "@webstudio-is/expression";
+import { getContentBlockSources } from "@webstudio-is/sdk";
import { z } from "zod";
import type { BuilderState } from "../state/builder-state";
import type { BuilderRuntimeContext } from "./context";
@@ -120,7 +121,7 @@ const auditScopeDescription = [
"accessibility errors: missing-alt, missing-image-input-alt, missing-iframe-title, missing-accessible-name, missing-form-label, invalid-aria-role, missing-required-aria-role-property, role-interactive-not-focusable, aria-hidden-focusable, invalid-aria-state, invalid-aria-number, autoplay-media-with-sound, invalid-label-reference, duplicate-id, and missing-aria-reference; warnings: missing-image-description, unsupported-aria-role-property, positive-tabindex, missing-page-heading, skipped-heading-level, missing-main-landmark, and multiple-main-landmarks. Documentation: https://www.w3.org/WAI/WCAG22/understanding/.",
"security errors: non-get-resource-exposed-as-data-source; warning: target-blank-without-noopener. Documentation: https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Attributes/rel/noopener.",
"seo errors: empty-page-title, invalid-json-ld, and json-ld-in-custom-metadata; warnings: missing-page-description, empty-page-description, invalid-page-language, missing-social-image-asset, duplicate-page-title, duplicate-page-description, missing-json-ld-context, unknown-schema-org-type, deprecated-schema-org-type, unknown-schema-org-property, deprecated-schema-org-property, unsupported-schema-org-property, and incompatible-schema-org-value. Documentation: https://developers.google.com/search/docs/fundamentals/seo-starter-guide.",
- "assets info: unused-asset. Documentation: https://docs.webstudio.is/university/foundations/anatomy-of-the-webstudio-builder.",
+ "assets info: unused-asset. When connected Content Blocks may hide MDX and nested Asset dependencies, unused-asset is skipped instead of returning unsafe false positives. Documentation: https://docs.webstudio.is/university/foundations/anatomy-of-the-webstudio-builder.",
"styles warnings: style-on-dom-transparent-component, invalid-style-state-selector, and orphan-style-breakpoint; info: unused-design-token, unused-css-variable, unused-local-style-source, unused-breakpoint, and duplicate-design-token-declarations. Documentation: https://docs.webstudio.is/university/foundations/design-tokens.",
"performance info: atomic-css-disabled. Rendered checks add image loading/sizing, render-blocking resource, and legacy font-format evidence. Documentation: https://docs.webstudio.is/university/foundations/project-settings#atomic-css.",
"craft is an opt-in, read-only compatibility check and is excluded when scopes are omitted. Documentation: https://docs.webstudio.is/university/craft.",
@@ -1213,6 +1214,23 @@ const getSkippedChecks = (
}
}
}
+ if (scopes.includes("assets")) {
+ if (
+ getContentBlockSources({
+ instances: state.instances?.values() ?? [],
+ props: state.props?.values() ?? [],
+ }).size > 0
+ ) {
+ checks.push({
+ scope: "assets",
+ checkId: "content-asset-dependencies",
+ reason: "missing-build-data",
+ message:
+ "Unused Asset findings are skipped because connected Content Blocks can reference MDX files and nested Assets that are not visible in editable project data.",
+ location: {},
+ });
+ }
+ }
return checks.sort(
(left, right) =>
left.scope.localeCompare(right.scope) ||
@@ -1277,6 +1295,7 @@ export function audit(
pageId: selectedPage?.id,
verbose: input.verbose === true,
});
+ const skippedChecks = getSkippedChecks(state, normalizedInput, scopes);
const standardScopes = scopes.filter((scope) => scope !== "craft");
const raw =
standardScopes.length === 0
@@ -1287,10 +1306,17 @@ export function audit(
pagePath: normalizedInput.pagePath,
limit: Number.MAX_SAFE_INTEGER,
});
+ const skipsUnusedAssetFindings = skippedChecks.some(
+ ({ checkId }) => checkId === "content-asset-dependencies"
+ );
const craftAnalysis = scopes.includes("craft")
? analyzeCraftProfile(state)
: undefined;
const normalizedFindings = [...raw.matches, ...(craftAnalysis?.matches ?? [])]
+ .filter(
+ (match) =>
+ skipsUnusedAssetFindings === false || match.issue !== "unused-asset"
+ )
.map(canonicalizeAuditMatchPagePaths)
.map(normalizeAuditFinding)
.sort(
@@ -1363,7 +1389,6 @@ export function audit(
),
};
}
- const skippedChecks = getSkippedChecks(state, normalizedInput, scopes);
const manualChecks = [
...(scopes.some((scope) =>
["accessibility", "styles", "performance"].includes(scope)
diff --git a/packages/project-build/src/runtime/collection.ts b/packages/project-build/src/runtime/collection.ts
index 9d209c1d59..c77ba52f72 100644
--- a/packages/project-build/src/runtime/collection.ts
+++ b/packages/project-build/src/runtime/collection.ts
@@ -30,6 +30,12 @@ const collectionDataInput = z.discriminatedUnion("type", [
}),
]);
+export const conflictResolutionInput = z
+ .enum(["ours", "theirs", "merge"])
+ .describe(
+ 'Token conflicts: "ours" keeps, "theirs" replaces, and "merge" combines styles.'
+ );
+
export const insertCollectionInput = z.object({
parentInstanceId: z.string(),
data: collectionDataInput.describe(
@@ -38,6 +44,7 @@ export const insertCollectionInput = z.object({
itemFragment: webstudioFragmentMutationInput.describe(
"One structured repeated-item fragment. Descendant expressions may reference collectionItem and collectionItemKey."
),
+ conflictResolution: conflictResolutionInput.optional(),
mode: instanceInsertModeInput.optional(),
insertIndex: insertIndexInput.optional(),
});
diff --git a/packages/project-build/src/runtime/components.test.ts b/packages/project-build/src/runtime/components.test.ts
index aef4d6c5b4..2bb037679a 100644
--- a/packages/project-build/src/runtime/components.test.ts
+++ b/packages/project-build/src/runtime/components.test.ts
@@ -71,6 +71,21 @@ const createState = (
assets: new Map(),
});
+const addFragmentStyles = (
+ state: WebstudioData,
+ fragment: Awaited<ReturnType<typeof parseWebstudioJsxFragment>>
+) => {
+ for (const styleSource of fragment.styleSources) {
+ state.styleSources.set(styleSource.id, styleSource);
+ }
+ for (const style of fragment.styles) {
+ state.styles.set(getStyleDeclKey(style), style);
+ }
+ for (const breakpoint of fragment.breakpoints) {
+ state.breakpoints.set(breakpoint.id, breakpoint);
+ }
+};
+
const createTemplateState = ({
root,
parent,
@@ -538,6 +553,56 @@ test("binds semantic Collection data to an HTTP resource result", async () => {
});
});
+test("requires and honors Collection item token conflict resolution", async () => {
+ const parent = createParent();
+ const state = createState(parent);
+ const existingFragment = await parseWebstudioJsxFragment(
+ `<ws.element ws:tag="div" ws:tokens={[token("brand", css\`color: blue;\`)]} />`
+ );
+ addFragmentStyles(state, existingFragment);
+ const itemFragment = await parseWebstudioJsxFragment(
+ `<ws.element ws:tag="article" ws:tokens={[token("brand", css\`color: red;\`)]}>Item</ws.element>`
+ );
+
+ expect(() =>
+ insertCollection(
+ state,
+ {
+ parentInstanceId: parent.id,
+ data: { type: "json", value: [] },
+ itemFragment,
+ },
+ { createId: createIdFactory(), projectId: "project-id" }
+ )
+ ).toThrow(/explicit conflictResolution.*brand/);
+
+ const mutation = insertCollection(
+ state,
+ {
+ parentInstanceId: parent.id,
+ data: { type: "json", value: [] },
+ itemFragment,
+ conflictResolution: "ours",
+ },
+ { createId: createIdFactory(), projectId: "project-id" }
+ );
+
+ expect(
+ getAddedValues<{ type: string; name: string }>(
+ mutation,
+ "styleSources"
+ ).filter((styleSource) => styleSource.type === "token")
+ ).toEqual([]);
+ expect(
+ getAddedValues<{ instanceId: string; values: string[] }>(
+ mutation,
+ "styleSourceSelections"
+ )
+ ).toContainEqual(
+ expect.objectContaining({ values: [existingFragment.styleSources[0]?.id] })
+ );
+});
+
test("binds object Collection keys to the generated itemKey parameter", async () => {
const parent = createParent();
const mutation = insertCollection(
@@ -1204,15 +1269,7 @@ test("honors fragment token conflict resolution", async () => {
const existingFragment = await parseWebstudioJsxFragment(
`<ws.element ws:tag="div" ws:tokens={[token("brand", css\`color: blue;\`)]} />`
);
- for (const styleSource of existingFragment.styleSources) {
- state.styleSources.set(styleSource.id, styleSource);
- }
- for (const style of existingFragment.styles) {
- state.styles.set(getStyleDeclKey(style), style);
- }
- for (const breakpoint of existingFragment.breakpoints) {
- state.breakpoints.set(breakpoint.id, breakpoint);
- }
+ addFragmentStyles(state, existingFragment);
const mutation = await insertFragment(
state,
@@ -1261,15 +1318,7 @@ test("requires an explicit fragment token conflict resolution", async () => {
const existingFragment = await parseWebstudioJsxFragment(
`<ws.element ws:tag="div" ws:tokens={[token("brand", css\`color: blue;\`)]} />`
);
- for (const styleSource of existingFragment.styleSources) {
- state.styleSources.set(styleSource.id, styleSource);
- }
- for (const style of existingFragment.styles) {
- state.styles.set(getStyleDeclKey(style), style);
- }
- for (const breakpoint of existingFragment.breakpoints) {
- state.breakpoints.set(breakpoint.id, breakpoint);
- }
+ addFragmentStyles(state, existingFragment);
const conflictingFragment = await parseWebstudioJsxFragment(
`<ws.element ws:tag="div" ws:tokens={[token("brand", css\`color: red;\`)]} />`
);
@@ -1332,15 +1381,7 @@ test("merges fragment token conflicts by replacing existing token styles", async
const existingFragment = await parseWebstudioJsxFragment(
`<ws.element ws:tag="div" ws:tokens={[token("brand", css\`color: blue; font-size: 16px;\`)]} />`
);
- for (const styleSource of existingFragment.styleSources) {
- state.styleSources.set(styleSource.id, styleSource);
- }
- for (const style of existingFragment.styles) {
- state.styles.set(getStyleDeclKey(style), style);
- }
- for (const breakpoint of existingFragment.breakpoints) {
- state.breakpoints.set(breakpoint.id, breakpoint);
- }
+ addFragmentStyles(state, existingFragment);
const mutation = await insertFragment(
state,
diff --git a/packages/project-build/src/runtime/components.ts b/packages/project-build/src/runtime/components.ts
index b5f1b313d0..cb2cb68175 100644
--- a/packages/project-build/src/runtime/components.ts
+++ b/packages/project-build/src/runtime/components.ts
@@ -44,6 +44,7 @@ import type {
} from "./component-insert-contract";
import {
createCollectionFragment,
+ conflictResolutionInput,
insertCollectionInput,
type InsertCollectionResult,
} from "./collection";
@@ -77,12 +78,6 @@ import { z } from "zod";
import { getBlockTemplateNameConfirmation } from "./block";
import { hasMdxComponentAdapter } from "./mdx-component-adapters";
-const conflictResolutionInput = z
- .enum(["ours", "theirs", "merge"])
- .describe(
- 'How to resolve incoming design tokens that share a name with an existing token. "ours" keeps the existing token styles and id, "theirs" uses incoming styles, and "merge" combines both.'
- );
-
export const insertComponentInput = z.object({
parentInstanceId: z.string(),
component: instanceComponent.describe(
@@ -1025,6 +1020,29 @@ const createInsertFragmentMutation = <
});
};
+const requireFragmentTokenConflictResolution = ({
+ fragment,
+ targetData,
+ conflictResolution,
+}: {
+ fragment: WebstudioFragment;
+ targetData: ReturnType<typeof getRequiredComponentInsertState>;
+ conflictResolution?: ConflictResolution;
+}) => {
+ if (conflictResolution !== undefined) {
+ return;
+ }
+ const conflicts = detectFragmentTokenConflicts({ fragment, targetData });
+ if (conflicts.length > 0) {
+ return throwBuilderRuntimeError(
+ "CONFLICT",
+ `Design token conflicts require an explicit conflictResolution (ours, theirs, or merge): ${conflicts
+ .map(({ tokenName }) => tokenName)
+ .join(", ")}`
+ );
+ }
+};
+
export const insertComponent = (
state: ComponentInsertState,
input: z.infer<typeof insertComponentInput>,
@@ -1176,6 +1194,11 @@ export const insertCollection = (
input,
templates,
});
+ requireFragmentTokenConflictResolution({
+ fragment: collection.fragment,
+ targetData: mutationState,
+ conflictResolution: input.conflictResolution,
+ });
const getMappedId = (ids: Map<string, string>, sourceId: string) => {
const id = ids.get(sourceId);
if (id === undefined) {
@@ -1195,6 +1218,7 @@ export const insertCollection = (
templates,
mode: input.mode,
insertIndex: input.insertIndex,
+ conflictResolution: input.conflictResolution,
additionalAvailableVariables: collection.parameterDataSources,
getResultDetails: ({ newInstanceIds, newDataSourceIds }) => ({
collectionInstanceId: getMappedId(
@@ -1265,20 +1289,11 @@ export const insertFragment = (
if (htmlEmbedError !== undefined) {
return throwBuilderRuntimeError("BAD_REQUEST", htmlEmbedError.message);
}
- if (input.conflictResolution === undefined) {
- const conflicts = detectFragmentTokenConflicts({
- fragment: input.fragment,
- targetData: getRequiredComponentInsertState(state),
- });
- if (conflicts.length > 0) {
- return throwBuilderRuntimeError(
- "CONFLICT",
- `Design token conflicts require an explicit conflictResolution (ours, theirs, or merge): ${conflicts
- .map(({ tokenName }) => tokenName)
- .join(", ")}`
- );
- }
- }
+ requireFragmentTokenConflictResolution({
+ fragment: input.fragment,
+ targetData: getRequiredComponentInsertState(state),
+ conflictResolution: input.conflictResolution,
+ });
if (input.fragment.children.length === 0) {
return createInsertTokenFragmentMutation({
state,
diff --git a/packages/project-build/src/runtime/content-block-application.test.ts b/packages/project-build/src/runtime/content-block-application.test.ts
index 6091d34b09..e8b1f2d97f 100644
--- a/packages/project-build/src/runtime/content-block-application.test.ts
+++ b/packages/project-build/src/runtime/content-block-application.test.ts
@@ -3,6 +3,7 @@ import {
blockBodyComponent,
blockComponent,
blockTemplateComponent,
+ encodeDataSourceVariable,
getContentBlockSource,
type Asset,
} from "@webstudio-is/sdk";
@@ -151,8 +152,8 @@ describe("createContentBlockApplication", () => {
});
test("inspects an Asset in each resolvable Content Block context", async () => {
const fixture = createFixture();
- fixture.state.dataSources?.set("selectedAsset", {
- id: "selectedAsset",
+ fixture.state.dataSources?.set("selectedAssetId", {
+ id: "selectedAssetId",
scopeInstanceId: "block",
name: "selectedAsset",
type: "variable",
@@ -329,6 +330,13 @@ describe("createContentBlockApplication", () => {
test("resolves a supplied Assets resource result", async () => {
const fixture = createFixture();
+ fixture.state.dataSources?.set("postDataSource", {
+ id: "postDataSource",
+ scopeInstanceId: "block",
+ name: "post",
+ type: "resource",
+ resourceId: "postResource",
+ });
const connected = await fixture.application.connect({
state: fixture.state,
@@ -348,7 +356,21 @@ describe("createContentBlockApplication", () => {
blockInstanceId: "block",
props: connectedState.props?.values() ?? [],
})
- ).toEqual({ type: "expression", value: "post.data.id" });
+ ).toEqual({
+ type: "expression",
+ value: `${encodeDataSourceVariable("postDataSource")}.data.id`,
+ });
+ await expect(
+ fixture.application.inspect({
+ state: connectedState,
+ blockInstanceId: "block",
+ renderScope: "page:/articles/example",
+ variables: { post: { data: { id: "asset" } } },
+ })
+ ).resolves.toMatchObject({
+ identity: { assetId: "asset" },
+ source: "# From file",
+ });
});
test("explains unresolved Assets resource expressions without exposing values", async () => {
diff --git a/packages/project-build/src/runtime/content-block-application.ts b/packages/project-build/src/runtime/content-block-application.ts
index bef3f00053..6699124c15 100644
--- a/packages/project-build/src/runtime/content-block-application.ts
+++ b/packages/project-build/src/runtime/content-block-application.ts
@@ -25,7 +25,8 @@ import {
getRequiredComponentInsertData,
} from "./components";
import { resolveContentBlockSourceAssetId } from "./block";
-import { computeExpression } from "./data";
+import { computeExpression, findAvailableVariables } from "./data";
+import { bindExpressionInput } from "./expression-scope";
import { throwBuilderRuntimeError } from "./errors";
import { materializeMdxSource } from "./mdx-source";
import {
@@ -41,6 +42,18 @@ const getData = (state: BuilderState): Omit<WebstudioData, "pages"> => ({
: { assetFolders: state.assetFolders }),
});
+const bindContentBlockSource = (
+ state: BuilderState,
+ blockInstanceId: string,
+ source: ContentBlockSource
+): ContentBlockSource =>
+ source.type === "expression"
+ ? {
+ ...source,
+ value: bindExpressionInput(state, blockInstanceId, source.value),
+ }
+ : source;
+
/** Finds every Content Block whose current source resolves to an MDX Asset. */
export const getMdxAssetSourceBlockInstanceIds = ({
assetId,
@@ -53,6 +66,7 @@ export const getMdxAssetSourceBlockInstanceIds = ({
for (const dataSource of state.dataSources?.values() ?? []) {
if (dataSource.type === "variable") {
values.set(dataSource.name, dataSource.value.value);
+ values.set(dataSource.id, dataSource.value.value);
}
}
return Array.from(
@@ -195,10 +209,12 @@ export const createContentBlockApplication = ({
const resolveSource = ({
source,
state,
+ blockInstanceId,
variables,
}: {
source: ContentBlockSource;
state: BuilderState;
+ blockInstanceId: string;
variables?: Readonly<Record<string, unknown>>;
}) => {
const resolved = resolveSourceAssetId?.({ source, state, variables });
@@ -208,15 +224,26 @@ export const createContentBlockApplication = ({
}
return resolved;
}
- const values = new Map<string, unknown>();
- for (const dataSource of state.dataSources?.values() ?? []) {
- if (dataSource.type === "variable") {
+ const values = new Map<string, unknown>(Object.entries(variables ?? {}));
+ const availableVariables =
+ state.instances === undefined || state.dataSources === undefined
+ ? []
+ : findAvailableVariables({
+ startingInstanceId: blockInstanceId,
+ instances: state.instances,
+ dataSources: state.dataSources,
+ });
+ for (const dataSource of availableVariables) {
+ const supplied =
+ variables !== undefined &&
+ Object.prototype.hasOwnProperty.call(variables, dataSource.name);
+ if (supplied) {
+ values.set(dataSource.id, variables?.[dataSource.name]);
+ } else if (dataSource.type === "variable") {
values.set(dataSource.name, dataSource.value.value);
+ values.set(dataSource.id, dataSource.value.value);
}
}
- for (const [name, value] of Object.entries(variables ?? {})) {
- values.set(name, value);
- }
const assetId = resolveContentBlockSourceAssetId({ source, values });
if (assetId !== undefined) {
return assetId;
@@ -274,6 +301,7 @@ export const createContentBlockApplication = ({
const assetId = resolveSource({
source,
state,
+ blockInstanceId,
variables,
});
const sessionState = await session.open(assetId);
@@ -370,7 +398,7 @@ export const createContentBlockApplication = ({
...prepareContentBlockConnect({
state,
blockInstanceId,
- source,
+ source: bindContentBlockSource(state, blockInstanceId, source),
}),
inspection,
};
@@ -394,7 +422,7 @@ export const createContentBlockApplication = ({
...prepareContentBlockSwitch({
state,
blockInstanceId,
- source,
+ source: bindContentBlockSource(state, blockInstanceId, source),
}),
inspection,
};
diff --git a/packages/project-build/src/runtime/data.test.tsx b/packages/project-build/src/runtime/data.test.tsx
index 956b4a3eed..c1d1c0bb6d 100644
--- a/packages/project-build/src/runtime/data.test.tsx
+++ b/packages/project-build/src/runtime/data.test.tsx
@@ -2674,6 +2674,69 @@ describe("resource patch helpers", () => {
).toThrow("Scope instance not found");
});
+ test("creates and updates render data scoped to Global Root", () => {
+ const state = createResourceState();
+ const ids = ["resource-id", "data-source-id"];
+ const created = createResource(
+ state,
+ {
+ resource: resourceFieldsInput.parse({
+ name: "Navigation",
+ method: "get",
+ url: "https://example.com/navigation",
+ headers: [],
+ }),
+ scopeInstanceId: ROOT_INSTANCE_ID,
+ },
+ { createId: () => ids.shift() ?? "unexpected-id" }
+ );
+
+ expect(created.result).toMatchObject({
+ resourceId: "resource-id",
+ dataSourceId: "data-source-id",
+ });
+ expect(created.payload).toContainEqual({
+ namespace: "dataSources",
+ patches: [
+ expect.objectContaining({
+ value: expect.objectContaining({
+ scopeInstanceId: ROOT_INSTANCE_ID,
+ resourceId: "resource-id",
+ }),
+ }),
+ ],
+ });
+
+ state.resources.set("resource-id", {
+ ...resource,
+ id: "resource-id",
+ name: "Navigation",
+ });
+ state.dataSources.set("data-source-id", {
+ id: "data-source-id",
+ scopeInstanceId: ROOT_INSTANCE_ID,
+ name: "navigation",
+ type: "resource",
+ resourceId: "resource-id",
+ });
+ const updated = updateResource(
+ state,
+ {
+ resourceId: "resource-id",
+ values: { name: "Main navigation" },
+ },
+ { createId: () => "unexpected-id" }
+ );
+
+ expect(updated.result).toMatchObject({
+ resourceId: "resource-id",
+ dataSourceId: "data-source-id",
+ });
+ expect(updated.payload).toContainEqual(
+ expect.objectContaining({ namespace: "resources" })
+ );
+ });
+
test("does not invalidate resources when text replacement finds no matches", () => {
const result = replaceResourceText(
{ resources: new Map([[resource.id, resource]]) },
diff --git a/packages/project-build/src/runtime/data.ts b/packages/project-build/src/runtime/data.ts
index a121da9081..aacb4b1eac 100644
--- a/packages/project-build/src/runtime/data.ts
+++ b/packages/project-build/src/runtime/data.ts
@@ -219,9 +219,18 @@ export const listDataVariables = (
export const dataVariableValueInput = dataSourceVariableValue;
+const resourceScopeInstanceIdDescription = `Instance ID or ${JSON.stringify(ROOT_INSTANCE_ID)} for Global Root.`;
+export const resourceScopeInstanceIdInput = z
+ .string()
+ .describe(resourceScopeInstanceIdDescription);
+export const optionalResourceScopeInstanceIdInput = z
+ .string()
+ .optional()
+ .describe(resourceScopeInstanceIdDescription);
+
export const dataVariableCreateInput = z.object({
dataSourceId: runtimeGeneratedIdInput,
- scopeInstanceId: z.string(),
+ scopeInstanceId: resourceScopeInstanceIdInput,
name: z.string().min(1),
value: dataVariableValueInput,
});
@@ -229,7 +238,7 @@ export const dataVariableCreateInput = z.object({
export const dataVariableUpdateInput = z.object({
dataSourceId: z.string(),
values: z.object({
- scopeInstanceId: z.string().optional(),
+ scopeInstanceId: optionalResourceScopeInstanceIdInput,
name: z.string().min(1).optional(),
value: dataVariableValueInput.optional(),
}),
@@ -1746,7 +1755,7 @@ export const resourceCreateInput = z
resourceId: runtimeGeneratedIdInput,
resource: resourceFieldsInput,
dataSourceId: runtimeGeneratedIdInput,
- scopeInstanceId: z.string().optional(),
+ scopeInstanceId: optionalResourceScopeInstanceIdInput,
dataSourceName: z.string().optional(),
exposeAsDataSource: exposeAsDataSourceInput,
})
@@ -1769,7 +1778,7 @@ export const resourceUpdateInput = z.object({
resourceId: z.string(),
values: resourceFieldsUpdateInput,
dataSourceName: z.string().optional(),
- scopeInstanceId: z.string().optional(),
+ scopeInstanceId: optionalResourceScopeInstanceIdInput,
exposeAsDataSource: exposeAsDataSourceInput,
});
@@ -2596,6 +2605,7 @@ export const createResource = (
(resourceInput.method === "get" && input.scopeInstanceId !== undefined);
if (
exposeAsDataSource &&
+ input.scopeInstanceId !== ROOT_INSTANCE_ID &&
build.instances.some(
(instance) => instance.id === input.scopeInstanceId
) === false
@@ -2730,6 +2740,7 @@ export const updateResource = (
}
if (
exposeAsDataSource &&
+ scopeInstanceId !== ROOT_INSTANCE_ID &&
build.instances.some((instance) => instance.id === scopeInstanceId) ===
false
) {
diff --git a/packages/project-build/src/runtime/pre-publish-audit.ts b/packages/project-build/src/runtime/pre-publish-audit.ts
index 0821164963..ce647deb0d 100644
--- a/packages/project-build/src/runtime/pre-publish-audit.ts
+++ b/packages/project-build/src/runtime/pre-publish-audit.ts
@@ -113,7 +113,9 @@ const checkBuildIntegrity: PrePublishAuditCheck = ({
ruleId:
issue.type === "missingResource"
? "resource-integrity"
- : "content-block-source-integrity",
+ : issue.type === "slotInContentBlockTemplates"
+ ? "content-block-template-integrity"
+ : "content-block-source-integrity",
severity: "error",
message: formatBuildIntegrityIssue(issue),
location: {
@@ -124,16 +126,18 @@ const checkBuildIntegrity: PrePublishAuditCheck = ({
: { propId: issue.propId }),
resourceId: issue.resourceId,
}
- : {
- instanceId: issue.blockInstanceId,
- ...(issue.type === "duplicateContentBlockSource"
- ? { propId: issue.propIds[0] }
- : { propId: issue.propId }),
- ...(issue.type === "missingContentBlockSourceAsset" ||
- issue.type === "incompatibleContentBlockSourceAsset"
- ? { assetId: issue.assetId }
- : {}),
- }),
+ : issue.type === "slotInContentBlockTemplates"
+ ? { instanceId: issue.instanceId }
+ : {
+ instanceId: issue.blockInstanceId,
+ ...(issue.type === "duplicateContentBlockSource"
+ ? { propId: issue.propIds[0] }
+ : { propId: issue.propId }),
+ ...(issue.type === "missingContentBlockSourceAsset" ||
+ issue.type === "incompatibleContentBlockSourceAsset"
+ ? { assetId: issue.assetId }
+ : {}),
+ }),
},
}));
diff --git a/packages/project-build/src/runtime/registry.test.ts b/packages/project-build/src/runtime/registry.test.ts
index 7a97d56a4b..c3f52f5158 100644
--- a/packages/project-build/src/runtime/registry.test.ts
+++ b/packages/project-build/src/runtime/registry.test.ts
@@ -1,6 +1,7 @@
import { describe, expect, test } from "vitest";
import {
getInputJsonSchemaMetadata,
+ ROOT_INSTANCE_ID,
toInputJsonSchemaObject,
type Assets,
type InputJsonSchema,
@@ -34,6 +35,7 @@ import { listFonts } from "./fonts";
import { listAssets } from "./assets";
import { bindProps, deleteProps, updateProps } from "./props";
import type { BuilderState } from "../state/builder-state";
+import { applyBuilderPatchTransactions } from "../state/patch";
import type { SemanticValidationIssue } from "./errors";
import {
context,
@@ -42,6 +44,7 @@ import {
} from "./runtime.test-fixtures";
import { createResourceCollectionIntegrationFixture } from "./runtime-ui.test-fixture";
import type { ContentBlockApplication } from "./content-block-application";
+import type { BuilderRuntimeMutation } from "./mutation";
const hasDirectInputProperty = (
schema: InputJsonSchema | undefined,
@@ -1981,6 +1984,58 @@ describe("builder runtime read families", () => {
).toContain('\\"/$resources/assets\\"');
});
+ test("creates and updates an Assets resource scoped to Global Root", () => {
+ const created = executeBuilderRuntimeOperation({
+ id: "assetsResources.create",
+ state,
+ input: {
+ name: "Global assets",
+ scopeInstanceId: ROOT_INSTANCE_ID,
+ },
+ context: {
+ ...context,
+ createId: (() => {
+ const ids = ["global-assets-resource", "global-assets-data-source"];
+ return () => ids.shift() ?? "id";
+ })(),
+ },
+ });
+
+ expect(created).toMatchObject({
+ result: {
+ resourceId: "global-assets-resource",
+ dataSourceId: "global-assets-data-source",
+ },
+ });
+ const createdState = applyBuilderPatchTransactions(state, [
+ {
+ id: "create-global-assets-resource",
+ payload: (created as BuilderRuntimeMutation).payload,
+ },
+ ]).state;
+ expect(createdState.dataSources?.get("global-assets-data-source")).toEqual(
+ expect.objectContaining({ scopeInstanceId: ROOT_INSTANCE_ID })
+ );
+
+ const updated = executeBuilderRuntimeOperation({
+ id: "assetsResources.update",
+ state: createdState,
+ input: {
+ resourceId: "global-assets-resource",
+ values: { name: "Updated global assets" },
+ },
+ context,
+ });
+
+ expect(updated).toMatchObject({
+ kind: "mutation",
+ result: {
+ resourceId: "global-assets-resource",
+ dataSourceId: "global-assets-data-source",
+ },
+ });
+ });
+
test("replaces bounded fixed resource URLs without changing expressions", () => {
const resource = state.resources.get("resource");
if (resource === undefined) {
diff --git a/packages/project-build/src/runtime/slot.test.ts b/packages/project-build/src/runtime/slot.test.ts
index 90482f3fda..8ceea3d0a7 100644
--- a/packages/project-build/src/runtime/slot.test.ts
+++ b/packages/project-build/src/runtime/slot.test.ts
@@ -1,5 +1,9 @@
import { describe, expect, test } from "vitest";
-import type { Instance, WebstudioData } from "@webstudio-is/sdk";
+import {
+ blockTemplateComponent,
+ type Instance,
+ type WebstudioData,
+} from "@webstudio-is/sdk";
import { applyBuilderPatchTransactions } from "../state/patch";
import {
attachSharedSlot,
@@ -80,6 +84,33 @@ describe("runtime slot utilities", () => {
]);
});
+ test("rejects a shared Slot inside Content Block Templates", () => {
+ const instances = new Map([
+ [
+ "source",
+ instance("source", "Slot", [{ type: "id", value: "fragment" }]),
+ ],
+ ["fragment", instance("fragment", "Fragment")],
+ [
+ "templates",
+ instance("templates", blockTemplateComponent, [
+ { type: "id", value: "template-section" },
+ ]),
+ ],
+ ["template-section", instance("template-section", "Box")],
+ ]);
+
+ expect(() =>
+ attachSharedSlot(
+ { instances, props: new Map() },
+ { sourceSlotId: "source", parentInstanceId: "template-section" },
+ { createId: () => "attached" }
+ )
+ ).toThrow(
+ "Shared Slots cannot be used inside Content Block Templates. Duplicate the Slot content into a regular template instead."
+ );
+ });
+
test("attaches a shared slot inside another slot content fragment", () => {
const instances = new Map([
["body", instance("body", "Body")],
diff --git a/packages/project-build/src/runtime/slot.ts b/packages/project-build/src/runtime/slot.ts
index 88bdda7d72..888f20952e 100644
--- a/packages/project-build/src/runtime/slot.ts
+++ b/packages/project-build/src/runtime/slot.ts
@@ -1,4 +1,6 @@
import {
+ blockTemplateComponent,
+ findParentInstanceReference,
findTreeInstanceIds,
portalComponent,
type Instance,
@@ -183,6 +185,22 @@ const assertValidSlotPlacement = ({
}
};
+const isInsideContentBlockTemplates = (
+ instances: Instances,
+ instanceId: Instance["id"]
+) => {
+ const visited = new Set<Instance["id"]>();
+ let instance = instances.get(instanceId);
+ while (instance !== undefined && visited.has(instance.id) === false) {
+ if (instance.component === blockTemplateComponent) {
+ return true;
+ }
+ visited.add(instance.id);
+ instance = findParentInstanceReference(instances, instance.id)?.instance;
+ }
+ return false;
+};
+
export const attachSharedSlot = (
state: Pick<BuilderState, "instances" | "props">,
input: z.infer<typeof attachSharedSlotInput>,
@@ -222,6 +240,12 @@ export const attachSharedSlot = (
if (parent === undefined) {
return throwBuilderRuntimeError("NOT_FOUND", "Target parent not found");
}
+ if (isInsideContentBlockTemplates(draft.instances, parent.id)) {
+ return throwBuilderRuntimeError(
+ "BAD_REQUEST",
+ "Shared Slots cannot be used inside Content Block Templates. Duplicate the Slot content into a regular template instead."
+ );
+ }
if (findTreeInstanceIds(draft.instances, fragmentId).has(parent.id)) {
return throwBuilderRuntimeError(
"BAD_REQUEST",
diff --git a/packages/protocol/src/asset-resource-api.test.ts b/packages/protocol/src/asset-resource-api.test.ts
index cc98b3763b..6cedafb7f4 100644
--- a/packages/protocol/src/asset-resource-api.test.ts
+++ b/packages/protocol/src/asset-resource-api.test.ts
@@ -320,6 +320,7 @@ describe("Assets OpenAPI description", () => {
"height",
"force",
"x-webstudio-asset-description",
+ "x-webstudio-asset-description-encoding",
"x-webstudio-asset-meta",
]);
expect(uploadContent.parameters[0].schema.maxLength).toBe(
diff --git a/packages/protocol/src/asset-resource-api.ts b/packages/protocol/src/asset-resource-api.ts
index e05324def1..a17026a8b8 100644
--- a/packages/protocol/src/asset-resource-api.ts
+++ b/packages/protocol/src/asset-resource-api.ts
@@ -37,6 +37,10 @@ const assetFolderItemApiPath = `${assetsFoldersApiUrl}/{folderId}`;
export const assetContentDescriptorHeader =
"x-webstudio-asset-content-descriptor";
+export const assetDescriptionHeader = "x-webstudio-asset-description";
+export const assetDescriptionEncodingHeader =
+ "x-webstudio-asset-description-encoding";
+export const assetDescriptionEncoding = "base64url";
export const assetContentDescriptor = z.object({
id: z.string(),
@@ -1030,14 +1034,19 @@ export const createAssetResourceOpenApi = ({
schema: { type: "boolean", default: false },
},
{
- name: "x-webstudio-asset-description",
+ name: assetDescriptionHeader,
in: "header",
required: false,
- description: "Asset description",
- schema: {
- type: "string",
- maxLength: assetResourceLimits.assetDescriptionCharacters,
- },
+ description: `Asset description, encoded according to ${assetDescriptionEncodingHeader}`,
+ schema: { type: "string" },
+ },
+ {
+ name: assetDescriptionEncodingHeader,
+ in: "header",
+ required: false,
+ description:
+ "Encoding used for the Asset description header. Omit for legacy ASCII descriptions.",
+ schema: { type: "string", enum: [assetDescriptionEncoding] },
},
{
name: "x-webstudio-asset-meta",
diff --git a/packages/sdk-components-react/src/__generated__/youtube.props.ts b/packages/sdk-components-react/src/__generated__/youtube.props.ts
index 17e40739cf..65b7373e1b 100644
--- a/packages/sdk-components-react/src/__generated__/youtube.props.ts
+++ b/packages/sdk-components-react/src/__generated__/youtube.props.ts
@@ -116,6 +116,13 @@ export const props: Record<string, PropMeta> = {
control: "text",
type: "string",
},
+ preconnect: {
+ description:
+ "Opens a connection to the YouTube player before playback.\nDisable this for consent-based click-to-load embeds.\nDefaults to false in Privacy Enhanced Mode and true otherwise.",
+ required: false,
+ control: "boolean",
+ type: "boolean",
+ },
privacyEnhancedMode: {
description:
"The Privacy Enhanced Mode of the YouTube embedded player prevents the use of views of embedded YouTube content from influencing the viewer’s browsing experience on YouTube.\nhttps://support.google.com/youtube/answer/171780?hl=en#zippy=%2Cturn-on-privacy-enhanced-mode",
diff --git a/packages/sdk-components-react/src/shared/video.ts b/packages/sdk-components-react/src/shared/video.ts
index 78a8551d8d..ced3f90130 100644
--- a/packages/sdk-components-react/src/shared/video.ts
+++ b/packages/sdk-components-react/src/shared/video.ts
@@ -1,5 +1,19 @@
import { createContext } from "react";
+const preconnectedOrigins = new Set<string>();
+
+export const preconnect = (url: string) => {
+ if (preconnectedOrigins.has(url)) {
+ return;
+ }
+ const link = document.createElement("link");
+ link.rel = "preconnect";
+ link.href = url;
+ link.crossOrigin = "true";
+ document.head.appendChild(link);
+ preconnectedOrigins.add(url);
+};
+
export const requestFullscreen = (element: HTMLIFrameElement) => {
const isTouchDevice = "ontouchstart" in window;
// Allows it to work on small screens on desktop too and makes it easy to test.
diff --git a/packages/sdk-components-react/src/vimeo.tsx b/packages/sdk-components-react/src/vimeo.tsx
index bac64c6f8c..8d81a382fa 100644
--- a/packages/sdk-components-react/src/vimeo.tsx
+++ b/packages/sdk-components-react/src/vimeo.tsx
@@ -17,6 +17,7 @@ import {
} from "react";
import { ReactSdkContext } from "@webstudio-is/react-sdk/runtime";
import {
+ preconnect,
requestFullscreen,
VideoContext,
type PlayerStatus,
@@ -130,16 +131,6 @@ const getVideoUrl = (options: VimeoOptions) => {
return url.toString();
};
-const preconnect = (url: string) => {
- const link = document.createElement("link");
- link.rel = "preconnect";
- link.href = url;
- link.crossOrigin = "true";
- document.head.appendChild(link);
-};
-
-let warmed = false;
-
// Host that Vimeo uses to serve JS needed by player
const PLAYER_CDN = "https://f.vimeocdn.com";
// The iframe document comes from player.vimeo.com
@@ -148,10 +139,6 @@ const IFRAME_CDN = "https://player.vimeo.com";
const IMAGE_CDN = "https://i.vimeocdn.com";
const warmConnections = () => {
- if (warmed) {
- return;
- }
-
if (window.matchMedia("(hover: none)").matches) {
// Useless on touch devices
return;
@@ -160,7 +147,6 @@ const warmConnections = () => {
preconnect(PLAYER_CDN);
preconnect(IFRAME_CDN);
preconnect(IMAGE_CDN);
- warmed = true;
};
const getVideoId = (url: string) => {
diff --git a/packages/sdk-components-react/src/youtube.browser.test.tsx b/packages/sdk-components-react/src/youtube.browser.test.tsx
new file mode 100644
index 0000000000..90c6741f57
--- /dev/null
+++ b/packages/sdk-components-react/src/youtube.browser.test.tsx
@@ -0,0 +1,68 @@
+import { afterEach, expect, test, vi } from "vitest";
+import { cleanup, render, waitFor } from "@testing-library/react";
+import type { ComponentProps } from "react";
+import { ReactSdkContext } from "@webstudio-is/react-sdk/runtime";
+import { YouTube } from "./youtube";
+
+const sdkContext = {
+ assetBaseUrl: "/assets/",
+ imageLoader: ({ src }: { src: string }) => src,
+ videoLoader: ({ src }: { src: string }) => src,
+ resources: {},
+ breakpoints: [],
+ onError: vi.fn(),
+ renderer: "preview" as const,
+};
+
+const getPreconnectOrigins = () =>
+ Array.from(
+ document.head.querySelectorAll<HTMLLinkElement>('link[rel="preconnect"]')
+ ).map((link) => new URL(link.href).origin);
+
+const renderYouTube = (props: ComponentProps<typeof YouTube>) => (
+ <ReactSdkContext.Provider value={sdkContext}>
+ <YouTube url="https://www.youtube.com/watch?v=dQw4w9WgXcQ" {...props} />
+ </ReactSdkContext.Provider>
+);
+
+afterEach(() => {
+ cleanup();
+ vi.restoreAllMocks();
+});
+
+test("preconnect is consent-aware and only warms the player", async () => {
+ vi.spyOn(window, "matchMedia").mockImplementation(
+ () => ({ matches: false }) as MediaQueryList
+ );
+
+ const { rerender } = render(
+ renderYouTube({
+ preconnect: false,
+ privacyEnhancedMode: false,
+ showPreview: true,
+ })
+ );
+
+ await Promise.resolve();
+ expect(getPreconnectOrigins()).toEqual([]);
+
+ rerender(renderYouTube({ privacyEnhancedMode: false, showPreview: false }));
+
+ await waitFor(() =>
+ expect(getPreconnectOrigins()).toContain("https://www.youtube.com")
+ );
+ expect(getPreconnectOrigins()).not.toContain("https://img.youtube.com");
+
+ rerender(
+ renderYouTube({
+ preconnect: true,
+ showPreview: true,
+ children: <div>Custom preview</div>,
+ })
+ );
+
+ await waitFor(() =>
+ expect(getPreconnectOrigins()).toContain("https://www.youtube-nocookie.com")
+ );
+ expect(getPreconnectOrigins()).not.toContain("https://img.youtube.com");
+});
diff --git a/packages/sdk-components-react/src/youtube.tsx b/packages/sdk-components-react/src/youtube.tsx
index 1c6e5d58a9..6228f68bc7 100644
--- a/packages/sdk-components-react/src/youtube.tsx
+++ b/packages/sdk-components-react/src/youtube.tsx
@@ -9,7 +9,7 @@ import {
useRef,
} from "react";
import { ReactSdkContext } from "@webstudio-is/react-sdk/runtime";
-import { VideoContext, requestFullscreen } from "./shared/video";
+import { preconnect, VideoContext, requestFullscreen } from "./shared/video";
/**
* Options for configuring the YouTube player parameters.
@@ -152,6 +152,12 @@ type YouTubePlayerOptions = {
/** The YouTube video URL or ID */
url?: string;
showPreview?: boolean;
+ /**
+ * Opens a connection to the YouTube player before playback.
+ * Disable this for consent-based click-to-load embeds.
+ * Defaults to false in Privacy Enhanced Mode and true otherwise.
+ */
+ preconnect?: boolean;
/**
* The Privacy Enhanced Mode of the YouTube embedded player prevents the use of views of embedded YouTube content from influencing the viewer’s browsing experience on YouTube.
* https://support.google.com/youtube/answer/171780?hl=en#zippy=%2Cturn-on-privacy-enhanced-mode
@@ -331,18 +337,8 @@ const getVideoUrl = (
return url.toString();
};
-const preconnect = (url: string) => {
- const link = document.createElement("link");
- link.rel = "preconnect";
- link.href = url;
- link.crossOrigin = "true";
- document.head.appendChild(link);
-};
-
-let warmed = false;
-
const warmConnections = (videoUrl: string) => {
- if (warmed || window.matchMedia("(hover: none)").matches) {
+ if (window.matchMedia("(hover: none)").matches) {
return;
}
@@ -353,9 +349,6 @@ const warmConnections = (videoUrl: string) => {
} catch {
// Ignore invalid URL
}
-
- preconnect(IMAGE_CDN);
- warmed = true;
};
const getPreviewImageUrl = (videoId: string) => {
@@ -408,12 +401,6 @@ const Player = ({
}
}, [autoplay, status, renderer, onStatusChange]);
- useEffect(() => {
- if (renderer !== "canvas") {
- warmConnections(videoUrl);
- }
- }, [renderer, videoUrl]);
-
useEffect(() => {
const videoId = getVideoId(videoUrl);
if (!videoId || !showPreview) {
@@ -480,6 +467,7 @@ export const YouTube = forwardRef<Ref, Props>(
loading = "lazy",
autoplay,
showPreview,
+ preconnect: preconnectConnections,
showAnnotations,
showCaptions,
showControls,
@@ -495,6 +483,8 @@ export const YouTube = forwardRef<Ref, Props>(
const [status, setStatus] = useState<PlayerStatus>("initial");
const [previewImageUrl, setPreviewImageUrl] = useState<URL>();
const { renderer } = useContext(ReactSdkContext);
+ const shouldPreconnect =
+ preconnectConnections ?? privacyEnhancedMode === false;
const videoUrlOrigin =
(privacyEnhancedMode ?? true)
@@ -517,6 +507,12 @@ export const YouTube = forwardRef<Ref, Props>(
videoUrlOrigin
);
+ useEffect(() => {
+ if (renderer !== "canvas" && shouldPreconnect && videoUrl) {
+ warmConnections(videoUrl);
+ }
+ }, [renderer, shouldPreconnect, videoUrl]);
+
return (
<VideoContext.Provider
value={{
diff --git a/packages/sdk-components-react/src/youtube.ws.ts b/packages/sdk-components-react/src/youtube.ws.ts
index 89e081a24b..67edaa21ce 100644
--- a/packages/sdk-components-react/src/youtube.ws.ts
+++ b/packages/sdk-components-react/src/youtube.ws.ts
@@ -10,6 +10,7 @@ const initialProps: Array<keyof ComponentProps<typeof YouTube>> = [
"className",
"url",
"privacyEnhancedMode",
+ "preconnect",
"title",
"loading",
"showPreview",
diff --git a/packages/vision/src/screenshot-browser-cdp.test.ts b/packages/vision/src/screenshot-browser-cdp.test.ts
index 3456cfc8f6..8ea6edb44f 100644
--- a/packages/vision/src/screenshot-browser-cdp.test.ts
+++ b/packages/vision/src/screenshot-browser-cdp.test.ts
@@ -609,6 +609,40 @@ test("captures through DevTools with lifecycle and selector waits", async () =>
});
});
+test("preserves a successful capture when Windows profile cleanup stays busy", async () => {
+ const browserProcess = new FakeBrowserProcess();
+ const socket = new FakeWebSocket();
+ const cleanupError = Object.assign(new Error("profile journal is busy"), {
+ code: "EBUSY",
+ });
+ const dependencies = createDependencies({ browserProcess, socket });
+ vi.mocked(dependencies.rm).mockRejectedValue(cleanupError);
+
+ await expect(
+ captureBrowserScreenshot(
+ {
+ url: "https://example.com",
+ output: "/tmp/current.png",
+ width: 800,
+ height: 600,
+ browserPath: "/usr/bin/chromium",
+ waitUntil: "networkidle",
+ waitForTimeout: 0,
+ timeout: 1000,
+ },
+ dependencies
+ )
+ ).resolves.toMatchObject({
+ viewportWidth: 800,
+ viewportHeight: 600,
+ });
+ expect(dependencies.rm).toHaveBeenCalledWith(
+ expect.any(String),
+ expect.objectContaining({ maxRetries: 3, retryDelay: 50 })
+ );
+ expect(browserProcess.kill).toHaveBeenCalledOnce();
+});
+
test("ignores lifecycle readiness from child frames", async () => {
const socket = new FakeWebSocket(200, undefined, undefined, undefined, [
"child",
diff --git a/packages/vision/src/screenshot-browser-cdp.ts b/packages/vision/src/screenshot-browser-cdp.ts
index 56e22b70e9..484110e011 100644
--- a/packages/vision/src/screenshot-browser-cdp.ts
+++ b/packages/vision/src/screenshot-browser-cdp.ts
@@ -1364,6 +1364,24 @@ const stopBrowserProcess = async ({
).catch(() => undefined);
};
+const removeBrowserProfile = async (
+ userDataDir: string,
+ dependencies: Pick<BrowserScreenshotDependencies, "rm">
+) => {
+ try {
+ await dependencies.rm(userDataDir, { recursive: true, force: true });
+ } catch {
+ await dependencies
+ .rm(userDataDir, {
+ recursive: true,
+ force: true,
+ maxRetries: 3,
+ retryDelay: 50,
+ })
+ .catch(() => undefined);
+ }
+};
+
const startBrowserRuntimeOnce = async (
options: BrowserScreenshotOptions,
dependencies: BrowserScreenshotDependencies
@@ -1385,9 +1403,7 @@ const startBrowserRuntimeOnce = async (
})
);
} catch (error) {
- await dependencies
- .rm(userDataDir, { recursive: true, force: true })
- .catch(() => undefined);
+ await removeBrowserProfile(userDataDir, dependencies);
throw error;
}
let startupOutput = "";
@@ -1451,10 +1467,7 @@ const startBrowserRuntimeOnce = async (
running,
gracePeriodMs: 2000,
});
- await dependencies.rm(userDataDir, {
- recursive: true,
- force: true,
- });
+ await removeBrowserProfile(userDataDir, dependencies);
})();
await closePromise;
},
@@ -1467,9 +1480,7 @@ const startBrowserRuntimeOnce = async (
running,
gracePeriodMs: Math.min(startupTimeout, 2000),
});
- await dependencies
- .rm(userDataDir, { recursive: true, force: true })
- .catch(() => undefined);
+ await removeBrowserProfile(userDataDir, dependencies);
throw error;
}
};