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: validate projects before publishing (#5922)

Oleg Isonenbe906afb5b1f
diff --git a/apps/builder/app/builder/features/publish/publish.tsx b/apps/builder/app/builder/features/publish/publish.tsx
index d21b84c4cb..59f4bb080b 100644
--- a/apps/builder/app/builder/features/publish/publish.tsx
+++ b/apps/builder/app/builder/features/publish/publish.tsx
@@ -41,7 +41,10 @@ import {
SmallIconButton,
} from "@webstudio-is/design-system";
import { validateProjectDomain, type Project } from "@webstudio-is/project";
-import { selectInstance } from "~/shared/nano-states";
+import {
+ $registeredComponentMetas,
+ selectInstance,
+} from "~/shared/nano-states";
import { $selectedPageId } from "~/shared/nano-states";
import {
$authTokenPermissions,
@@ -91,10 +94,23 @@ import {
type RestrictedFeature,
} from "./restricted-features";
import {
- formatBuildIntegrityError,
- getBuildIntegrityIssues,
+ formatPrePublishAuditFinding,
+ runPrePublishAudit,
} from "@webstudio-is/project-build/runtime";
+const getPrePublishAuditError = () => {
+ const findings = runPrePublishAudit({
+ pages: $pages.get(),
+ instances: $instances.get(),
+ props: $props.get(),
+ dataSources: $dataSources.get(),
+ resources: $resources.get(),
+ metas: $registeredComponentMetas.get(),
+ });
+ const finding = findings.find(({ severity }) => severity === "error");
+ return finding && formatPrePublishAuditFinding(finding);
+};
+
type ChangeProjectDomainProps = {
project: Project;
projectState: "idle" | "submitting";
@@ -432,17 +448,10 @@ const Publish = ({
const handlePublish = async (formData: FormData) => {
setPublishError(undefined);
- const integrityIssues = getBuildIntegrityIssues({
- dataSources: $dataSources.get().values(),
- props: $props.get().values(),
- resources: $resources.get().values(),
- });
- const integrityError =
- integrityIssues[0] &&
- formatBuildIntegrityError(integrityIssues[0], "Cannot publish");
- if (integrityError !== undefined) {
- toast.error(integrityError);
- setPublishError(integrityError);
+ const auditError = getPrePublishAuditError();
+ if (auditError !== undefined) {
+ toast.error(auditError);
+ setPublishError(auditError);
return;
}
@@ -636,6 +645,7 @@ const PublishStatic = ({
}) => {
const project = useStore($project);
const [_, startTransition] = useTransition();
+ const [publishError, setPublishError] = useState<string>();
if (project == null) {
throw new Error("Project not found");
@@ -652,6 +662,7 @@ const PublishStatic = ({
return (
<Flex gap={2} shrink={false} direction={"column"}>
+ {publishError && <Text color="destructive">{publishError}</Text>}
{status === "FAILED" && <Text color="destructive">{statusText}</Text>}
<Tooltip
@@ -664,6 +675,14 @@ const PublishStatic = ({
onClick={() => {
startTransition(async () => {
try {
+ setPublishError(undefined);
+ const auditError = getPrePublishAuditError();
+ if (auditError !== undefined) {
+ toast.error(auditError);
+ setPublishError(auditError);
+ return;
+ }
+
setIsPendingOptimistic(true);
const result = await nativeClient.domain.publish.mutate({
diff --git a/fixtures/ssg-cloudflare-pages/package.json b/fixtures/ssg-cloudflare-pages/package.json
index 211cef7f7f..b87cb403bf 100644
--- a/fixtures/ssg-cloudflare-pages/package.json
+++ b/fixtures/ssg-cloudflare-pages/package.json
@@ -4,7 +4,7 @@
"description": "",
"scripts": {
"build": "vite build && vike prerender",
- "postbuild": "cd dist && oxfmt '**/*.html'",
+ "build:debug": "pnpm build && cd dist && oxfmt '**/*.html'",
"dev": "vite dev",
"typecheck": "tsc --noEmit",
"cli": "NODE_OPTIONS='--conditions=webstudio --import=tsx' webstudio",
diff --git a/fixtures/ssg-netlify-by-project-id/package.json b/fixtures/ssg-netlify-by-project-id/package.json
index 38f26001f8..ea76cd0ba8 100644
--- a/fixtures/ssg-netlify-by-project-id/package.json
+++ b/fixtures/ssg-netlify-by-project-id/package.json
@@ -4,7 +4,7 @@
"description": "",
"scripts": {
"build": "vite build && vike prerender",
- "postbuild": "cd dist && oxfmt '**/*.html'",
+ "build:debug": "pnpm build && cd dist && oxfmt '**/*.html'",
"dev": "vite dev",
"typecheck": "tsc --noEmit",
"cli": "NODE_OPTIONS='--conditions=webstudio --import=tsx' webstudio",
diff --git a/packages/project-build/src/runtime.ts b/packages/project-build/src/runtime.ts
index d1861055a7..da7842ba6f 100644
--- a/packages/project-build/src/runtime.ts
+++ b/packages/project-build/src/runtime.ts
@@ -11,6 +11,7 @@ export * from "./runtime/component-template";
export * from "./runtime/content-mode-copy-policy";
export * from "./runtime/content-mode-permissions";
export * from "./runtime/content-model";
+export * from "./runtime/pre-publish-audit";
export * from "./runtime/context";
export * from "./runtime/data";
export * from "./runtime/design-token-import";
diff --git a/packages/project-build/src/runtime/content-model.ts b/packages/project-build/src/runtime/content-model.ts
index 331c6b40bb..8ee4ca8bf9 100644
--- a/packages/project-build/src/runtime/content-model.ts
+++ b/packages/project-build/src/runtime/content-model.ts
@@ -305,7 +305,7 @@ export const isTreeSatisfyingContentModel = ({
metas: Metas;
instanceSelector: InstanceSelector;
htmlTagsByInstanceId?: HtmlTagsByInstanceId;
- onError?: (message: string) => void;
+ onError?: (message: string, instanceSelector: InstanceSelector) => void;
_allowedCategories?: string[];
_allowedAncestorCategories?: string[];
_allowedParentCategories?: string[];
@@ -352,10 +352,14 @@ export const isTreeSatisfyingContentModel = ({
}
if (parentTag) {
onError?.(
- `Placing <${tag}> element inside a <${parentTag}> violates HTML spec.`
+ `Placing <${tag}> element inside a <${parentTag}> violates HTML spec.`,
+ instanceSelector
);
} else {
- onError?.(`Placing <${tag}> element here violates HTML spec.`);
+ onError?.(
+ `Placing <${tag}> element here violates HTML spec.`,
+ instanceSelector
+ );
}
}
const isComponentSatisfying = isComponentSatisfyingContentModel({
@@ -374,10 +378,14 @@ export const isTreeSatisfyingContentModel = ({
}
if (parentName) {
onError?.(
- `Placing "${name}" element inside a "${parentName}" violates content model.`
+ `Placing "${name}" element inside a "${parentName}" violates content model.`,
+ instanceSelector
);
} else {
- onError?.(`Placing "${name}" element here violates content model.`);
+ onError?.(
+ `Placing "${name}" element here violates content model.`,
+ instanceSelector
+ );
}
}
let isSatisfying = isTagSatisfying && isComponentSatisfying;
diff --git a/packages/project-build/src/runtime/pre-publish-audit.test.tsx b/packages/project-build/src/runtime/pre-publish-audit.test.tsx
new file mode 100644
index 0000000000..68ac58149e
--- /dev/null
+++ b/packages/project-build/src/runtime/pre-publish-audit.test.tsx
@@ -0,0 +1,175 @@
+import { expect, test } from "vitest";
+import {
+ ROOT_FOLDER_ID,
+ type Folder,
+ type Page,
+ type Pages,
+} from "@webstudio-is/sdk";
+import { componentMetas } from "@webstudio-is/sdk-components-registry/metas";
+import { $, renderData } from "@webstudio-is/template";
+import {
+ formatPrePublishAuditFinding,
+ runPrePublishAudit,
+} from "./pre-publish-audit";
+
+const createPages = (page: Page): Pages => {
+ const rootFolder: Folder = {
+ id: ROOT_FOLDER_ID,
+ name: "Root",
+ slug: "",
+ children: [page.id],
+ };
+ return {
+ homePageId: page.id,
+ rootFolderId: rootFolder.id,
+ pages: new Map([[page.id, page]]),
+ folders: new Map([[rootFolder.id, rootFolder]]),
+ };
+};
+
+const marketEdgePage: Page = {
+ id: "marketedge",
+ name: "MarketEdge",
+ path: "/marketedge",
+ title: "MarketEdge",
+ rootInstanceId: "body",
+ meta: {},
+};
+
+const runAudit = ({
+ pages = createPages(marketEdgePage),
+ ...data
+}: {
+ pages?: Pages;
+ instances: Parameters<typeof runPrePublishAudit>[0]["instances"];
+ props: Parameters<typeof runPrePublishAudit>[0]["props"];
+}) =>
+ runPrePublishAudit({
+ pages,
+ ...data,
+ dataSources: new Map(),
+ resources: new Map(),
+ metas: componentMetas,
+ });
+
+test("returns a blocking finding with the page and instance identity", () => {
+ const { instances, props } = renderData(
+ <$.Body ws:id="body">
+ <$.Paragraph>
+ <$.Heading ws:id="heading" ws:tag="h2">
+ Analyze Global Markets
+ </$.Heading>
+ </$.Paragraph>
+ </$.Body>
+ );
+
+ const findings = runAudit({ instances, props });
+
+ expect(findings).toEqual([
+ {
+ ruleId: "html-content-model",
+ severity: "error",
+ message: "Placing <h2> element inside a <p> violates HTML spec.",
+ location: {
+ pageId: "marketedge",
+ pageName: "MarketEdge",
+ pagePath: "/marketedge",
+ instanceId: "heading",
+ },
+ },
+ ]);
+ expect(formatPrePublishAuditFinding(findings[0]!)).toBe(
+ 'Cannot publish "MarketEdge" (/marketedge): Placing <h2> element inside a <p> violates HTML spec.'
+ );
+});
+
+test("allows valid publishable pages and ignores invalid drafts", () => {
+ const { instances, props } = renderData(
+ <>
+ <$.Body ws:id="body">
+ <$.Paragraph>Valid paragraph</$.Paragraph>
+ </$.Body>
+ <$.Body ws:id="draft-body">
+ <$.Paragraph>
+ <$.Heading ws:tag="h2">Invalid draft heading</$.Heading>
+ </$.Paragraph>
+ </$.Body>
+ </>
+ );
+ const pages = createPages(marketEdgePage);
+ const draftPage: Page = {
+ ...marketEdgePage,
+ id: "draft",
+ name: "Draft",
+ path: "/draft",
+ rootInstanceId: "draft-body",
+ isDraft: true,
+ };
+ pages.pages.set(draftPage.id, draftPage);
+
+ expect(
+ runAudit({
+ pages,
+ instances,
+ props,
+ })
+ ).toEqual([]);
+});
+
+test("blocks publishing when required audit input is unavailable", () => {
+ const { instances, props } = renderData(<$.Body ws:id="body"></$.Body>);
+
+ const findings = runPrePublishAudit({
+ pages: undefined,
+ instances,
+ props,
+ dataSources: new Map(),
+ resources: new Map(),
+ metas: componentMetas,
+ });
+
+ expect(findings[0]).toMatchObject({
+ ruleId: "project-data",
+ severity: "error",
+ location: {},
+ });
+ expect(formatPrePublishAuditFinding(findings[0]!)).toBe(
+ "Cannot publish: Project pages are unavailable. Reload the Builder and try again."
+ );
+});
+
+test("includes existing resource integrity checks in the audit pipeline", () => {
+ const { instances, props } = renderData(<$.Body ws:id="body"></$.Body>);
+ const findings = runPrePublishAudit({
+ pages: createPages(marketEdgePage),
+ instances,
+ props,
+ dataSources: new Map([
+ [
+ "resource-variable",
+ {
+ id: "resource-variable",
+ scopeInstanceId: "body",
+ name: "Products",
+ type: "resource",
+ resourceId: "missing-resource",
+ },
+ ],
+ ]),
+ resources: new Map(),
+ metas: componentMetas,
+ });
+
+ expect(findings).toEqual([
+ {
+ ruleId: "resource-integrity",
+ severity: "error",
+ message:
+ 'resource variable "Products" (resource-variable) references missing resource "missing-resource".',
+ location: {
+ dataSourceId: "resource-variable",
+ resourceId: "missing-resource",
+ },
+ },
+ ]);
+});
diff --git a/packages/project-build/src/runtime/pre-publish-audit.ts b/packages/project-build/src/runtime/pre-publish-audit.ts
new file mode 100644
index 0000000000..20eabfcb42
--- /dev/null
+++ b/packages/project-build/src/runtime/pre-publish-audit.ts
@@ -0,0 +1,140 @@
+import {
+ getPagePath,
+ getPublishablePages,
+ type DataSources,
+ type Instances,
+ type Pages,
+ type Props,
+ type Resources,
+ type WsComponentMeta,
+} from "@webstudio-is/sdk";
+import {
+ formatBuildIntegrityIssue,
+ getBuildIntegrityIssues,
+} from "../build-integrity";
+import { isTreeSatisfyingContentModel } from "./content-model";
+
+export type PrePublishAuditFinding = {
+ ruleId: string;
+ severity: "error" | "warning" | "info";
+ message: string;
+ location: {
+ pageId?: string;
+ pageName?: string;
+ pagePath?: string;
+ instanceId?: string;
+ dataSourceId?: string;
+ propId?: string;
+ resourceId?: string;
+ };
+};
+
+type PrePublishAuditContext = {
+ pages: Pages;
+ instances: Instances;
+ props: Props;
+ dataSources: DataSources;
+ resources: Resources;
+ metas: Map<string, WsComponentMeta>;
+};
+
+type PrePublishAuditCheck = (
+ context: PrePublishAuditContext
+) => PrePublishAuditFinding[];
+
+const checkHtmlContentModel: PrePublishAuditCheck = ({
+ pages,
+ instances,
+ props,
+ metas,
+}) => {
+ const findings: PrePublishAuditFinding[] = [];
+
+ for (const page of getPublishablePages(pages)) {
+ let message: string | undefined;
+ let instanceId: string | undefined;
+ const isValid = isTreeSatisfyingContentModel({
+ instances,
+ props,
+ metas,
+ instanceSelector: [page.rootInstanceId],
+ onError: (error, instanceSelector) => {
+ message ??= error;
+ instanceId ??= instanceSelector[0];
+ },
+ });
+
+ if (isValid === false) {
+ findings.push({
+ ruleId: "html-content-model",
+ severity: "error",
+ message: message ?? "The page contains invalid element nesting.",
+ location: {
+ pageId: page.id,
+ pageName: page.name,
+ pagePath: getPagePath(page.id, pages) || "/",
+ instanceId,
+ },
+ });
+ }
+ }
+
+ return findings;
+};
+
+const checkResourceIntegrity: PrePublishAuditCheck = ({
+ dataSources,
+ props,
+ resources,
+}) =>
+ getBuildIntegrityIssues({
+ dataSources: dataSources.values(),
+ props: props.values(),
+ resources: resources.values(),
+ }).map((issue) => ({
+ ruleId: "resource-integrity",
+ severity: "error",
+ message: formatBuildIntegrityIssue(issue),
+ location: {
+ ...(issue.source === "dataSource"
+ ? { dataSourceId: issue.dataSourceId }
+ : { propId: issue.propId }),
+ resourceId: issue.resourceId,
+ },
+ }));
+
+const prePublishAuditChecks: PrePublishAuditCheck[] = [
+ checkHtmlContentModel,
+ checkResourceIntegrity,
+];
+
+export const runPrePublishAudit = ({
+ pages,
+ ...context
+}: Omit<PrePublishAuditContext, "pages"> & {
+ pages: Pages | undefined;
+}): PrePublishAuditFinding[] => {
+ if (pages === undefined) {
+ return [
+ {
+ ruleId: "project-data",
+ severity: "error",
+ message:
+ "Project pages are unavailable. Reload the Builder and try again.",
+ location: {},
+ },
+ ];
+ }
+
+ return prePublishAuditChecks.flatMap((check) => check({ ...context, pages }));
+};
+
+export const formatPrePublishAuditFinding = (
+ finding: PrePublishAuditFinding
+) => {
+ const { pageName, pagePath } = finding.location;
+ if (pageName === undefined || pagePath === undefined) {
+ return `Cannot publish: ${finding.message}`;
+ }
+ return `Cannot publish "${pageName}" (${pagePath}): ${finding.message}`;
+};