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.
TypeScript accessibilityalternativecloudflarecloudflare-workersdesignfreefrontendopen-sourceradix-uireactremixweb-developmentwebflowwebsite-builderwebsite-developmentwebsiteswebstudio
import { describe, expect, test } from "vitest";
import type { Asset, Prop } from "@webstudio-is/sdk";
import {
createTestServer,
db,
empty,
json,
testContext,
} from "@webstudio-is/postgrest/testing";
import type { AppContext } from "@webstudio-is/trpc-interface/index.server";
import { defaultPlanFeatures } from "@webstudio-is/plans";
import {
parseInstanceData,
parsePages,
} from "@webstudio-is/project-build/persistence";
import {
patchBuild,
patchLoadedBuild,
type BuildPatchTransaction,
} from "./build-patch";
import {
createBuildPatchUpdate,
singlePlayerVersionMismatchResult,
} from "./build-patch-core";
const server = createTestServer();
const createContext = (): AppContext =>
({
...testContext,
authorization: { type: "user", userId: "user-1" },
planFeatures: { ...defaultPlanFeatures, maxContactEmailsPerProject: 5 },
getOwnerPlanFeatures: async () => ({}),
}) as unknown as AppContext;
const ownershipHandler = db.get("Project", ({ request }) => {
const url = new URL(request.url);
if (url.searchParams.has("userId")) {
return json({ id: url.searchParams.get("id")?.replace("eq.", "") });
}
return json(null);
});
const buildRow = {
id: "build-1",
projectId: "project-1",
version: 3,
lastTransactionId: "previous-tx",
isCleaned: null,
publishStatus: "PUBLISHED" as const,
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
pages: JSON.stringify({
meta: {},
homePage: {
id: "page-1",
name: "Home",
path: "",
title: "Home",
meta: {},
rootInstanceId: "body-1",
},
pages: [],
folders: [{ id: "root", name: "Root", slug: "", children: [] }],
}),
breakpoints: JSON.stringify([]),
styles: JSON.stringify([]),
styleSources: JSON.stringify([]),
styleSourceSelections: JSON.stringify([]),
props: JSON.stringify([
{
id: "prop-1",
instanceId: "body-1",
name: "title",
type: "string",
value: "Old title",
},
]),
dataSources: JSON.stringify([]),
resources: JSON.stringify([]),
instances: JSON.stringify([
{ id: "body-1", type: "instance", component: "Body", children: [] },
]),
deployment: null,
marketplaceProduct: JSON.stringify({}),
projectSettings: JSON.stringify({ meta: {}, compiler: {} }),
};
const transaction = (
overrides: Partial<BuildPatchTransaction> = {}
): BuildPatchTransaction => ({
id: "tx-1",
payload: [
{
namespace: "props",
patches: [
{ op: "replace", path: ["prop-1", "value"], value: "New title" },
],
},
],
...overrides,
});
test("a pages-only save persists marked modern Form as ResourceForm with pages", async () => {
const markedPages = {
...JSON.parse(buildRow.pages),
formComponentIdentityVersion: 1,
};
const build = {
...buildRow,
pages: JSON.stringify(markedPages),
instances: JSON.stringify([
{
id: "body-1",
type: "instance",
component: "Body",
children: [{ type: "id", value: "form-1" }],
},
{
id: "form-1",
type: "instance",
component: "Form",
children: [{ type: "text", value: "Keep me" }],
},
]),
};
const result = await createBuildPatchUpdate({
loadAssets: async () => ({ assets: [], changedAssetIds: new Set() }),
build,
clientVersion: 3,
transactions: [
transaction({
payload: [
{
namespace: "pages",
patches: [
{ op: "add", path: ["meta", "siteName"], value: "Updated" },
],
},
],
}),
],
});
expect(result.status).toBe("ok");
if (result.status !== "ok" || result.update === undefined) {
return;
}
expect(result.update.pages).toBeDefined();
expect(result.update.instances).toBeDefined();
expect(JSON.parse(result.update.pages ?? "{}")).not.toHaveProperty(
"formComponentIdentityVersion"
);
const reloadedPages = parsePages(result.update.pages ?? "{}");
const reloadedInstances = parseInstanceData(result.update.instances ?? "[]");
expect(reloadedPages.meta?.siteName).toBe("Updated");
expect(reloadedInstances.get("form-1")).toEqual({
id: "form-1",
type: "instance",
component: "ResourceForm",
children: [{ type: "text", value: "Keep me" }],
});
});
test("marked modern Form patches persist as ResourceForm without changing WebhookForm", async () => {
const result = await createBuildPatchUpdate({
loadAssets: async () => ({ assets: [], changedAssetIds: new Set() }),
build: {
...buildRow,
pages: JSON.stringify({
...JSON.parse(buildRow.pages),
formComponentIdentityVersion: 1,
}),
instances: JSON.stringify([
{ id: "body-1", type: "instance", component: "Body", children: [] },
{
id: "webhook-1",
type: "instance",
component: "WebhookForm",
children: [],
},
]),
},
clientVersion: 3,
transactions: [
transaction({
payload: [
{
namespace: "instances",
patches: [
{
op: "add",
path: ["form-1"],
value: {
id: "form-1",
type: "instance",
component: "Form",
children: [],
},
},
{
op: "replace",
path: ["webhook-1", "component"],
value: "Form",
},
],
},
],
}),
],
});
expect(result.status).toBe("ok");
if (result.status !== "ok" || result.update === undefined) {
return;
}
expect(result.update.pages).toBeDefined();
expect(JSON.parse(result.update.pages ?? "{}")).not.toHaveProperty(
"formComponentIdentityVersion"
);
const reloadedInstances = parseInstanceData(result.update.instances ?? "[]");
expect(reloadedInstances.get("form-1")?.component).toBe("ResourceForm");
expect(reloadedInstances.get("webhook-1")?.component).toBe("WebhookForm");
});
test("historical Form instances retain WebhookForm identity after a stale patch", async () => {
const result = await createBuildPatchUpdate({
loadAssets: async () => ({ assets: [], changedAssetIds: new Set() }),
build: {
...buildRow,
instances: JSON.stringify([
{ id: "body-1", type: "instance", component: "Body", children: [] },
{ id: "form-1", type: "instance", component: "Form", children: [] },
]),
},
clientVersion: 3,
transactions: [
transaction({
payload: [
{
namespace: "instances",
patches: [
{ op: "replace", path: ["form-1", "component"], value: "Form" },
],
},
],
}),
],
});
expect(result.status).toBe("ok");
if (result.status !== "ok" || result.update === undefined) {
return;
}
const reloadedInstances = parseInstanceData(result.update.instances ?? "[]");
expect(reloadedInstances.get("form-1")?.component).toBe("WebhookForm");
});
test("a Form patch from the previous Builder persists as ResourceForm after marker removal", async () => {
const result = await createBuildPatchUpdate({
loadAssets: async () => ({ assets: [], changedAssetIds: new Set() }),
build: buildRow,
clientVersion: 3,
transactions: [
transaction({
payload: [
{
namespace: "instances",
patches: [
{
op: "add",
path: ["form-1"],
value: {
id: "form-1",
type: "instance",
component: "Form",
children: [],
},
},
],
},
],
}),
],
});
expect(result.status).toBe("ok");
if (result.status !== "ok" || result.update === undefined) {
return;
}
const reloadedInstances = parseInstanceData(result.update.instances ?? "[]");
expect(reloadedInstances.get("form-1")?.component).toBe("ResourceForm");
});
describe("patchBuild", () => {
test.each([true, false])(
"asset-only saves validate changed file types, not unchanged legacy references: %s",
async (changesFile) => {
const source: Prop = {
id: "src",
instanceId: "body-1",
name: "src",
type: "asset",
value: "asset",
};
const build = {
...buildRow,
instances: JSON.stringify([
{ id: "body-1", type: "instance", component: "Image", children: [] },
]),
props: JSON.stringify([source]),
};
const patches: BuildPatchTransaction["payload"][number]["patches"] = [
{
op: "replace",
path: ["asset", changesFile ? "name" : "description"],
value: changesFile ? "new.png" : "Description",
},
];
const loadedPatches: unknown[] = [];
const result = await createBuildPatchUpdate({
build,
clientVersion: 3,
transactions: [
transaction({ payload: [{ namespace: "assets", patches }] }),
],
loadAssets: async (ids, incoming) => {
expect(ids).toEqual(["asset"]);
loadedPatches.push(incoming);
const base = {
id: "asset",
projectId: "project-1",
size: 10,
createdAt: "",
};
return {
changedAssetIds: new Set(changesFile ? ["asset"] : []),
assets: [
changesFile
? {
...base,
type: "image",
name: "new.png",
format: "png",
meta: { width: 120, height: 80 },
}
: {
...base,
type: "file",
name: "old.txt",
format: "txt",
meta: {} as Record<string, never>,
},
],
};
},
});
expect(result.status).toBe("ok");
expect(loadedPatches).toEqual([patches]);
if (result.status === "ok") {
expect(result.update?.props).toBeUndefined();
expect(result.assetPatches).toEqual([patches]);
}
}
);
test.each(["restore", "replace", "asset-only"] as const)(
"rejects a %s that claims a text file is an image before any writes",
async (kind) => {
const source: Prop = {
id: "src",
instanceId: "body-1",
name: "src",
type: "asset",
value: "asset",
};
const image: Asset = {
id: "asset",
projectId: "project-1",
type: "image",
name: "old.png",
format: "png",
size: 10,
createdAt: buildRow.createdAt,
meta: { width: 120, height: 80 },
};
const file = {
name: "actual.txt",
format: "txt",
size: 10,
createdAt: buildRow.createdAt,
updatedAt: buildRow.updatedAt,
description: null,
meta: "{}",
status: "UPLOADED",
};
let didWrite = false;
server.use(
db.get("Asset", () =>
json(
kind === "restore"
? []
: [
{
assetId: image.id,
projectId: image.projectId,
filename: null,
description: null,
file: {
...file,
name: image.name,
format: image.format,
meta: JSON.stringify(image.meta),
},
},
]
)
),
db.get("File", () => json([file])),
db.patch("Build", () => {
didWrite = true;
return empty({ headers: { "Content-Range": "*/1" } });
}),
db.patch("Asset", () => {
didWrite = true;
return empty();
}),
db.post("Asset", () => {
didWrite = true;
return empty();
}),
db.post("AssetFolder", () => {
didWrite = true;
return empty();
})
);
const payload: BuildPatchTransaction["payload"] = [
{
namespace: "assets",
patches: [
{
op: kind === "restore" ? "add" : "replace",
path: [image.id],
value: { ...image, name: file.name },
},
],
},
{
namespace: "assetFolders",
patches: [
{
op: "add",
path: ["folder"],
value: {
id: "folder",
projectId: "project-1",
name: "Folder",
createdAt: buildRow.createdAt,
},
},
],
},
];
if (kind !== "asset-only") {
payload.push({
namespace: "props",
patches: [{ op: "add", path: [source.id], value: source }],
});
}
const result = await patchLoadedBuild(
{
build: {
...buildRow,
instances: JSON.stringify([
{
id: "body-1",
type: "instance",
component: "Image",
children: [],
},
]),
props: JSON.stringify(kind === "asset-only" ? [source] : []),
},
buildId: buildRow.id,
projectId: buildRow.projectId,
clientVersion: 3,
transactions: [transaction({ payload })],
assetStore: {
readFile: async () => {
throw new Error("Unexpected file download");
},
},
},
createContext()
);
expect(result).toEqual({
status: "error",
errors: "This asset type is not allowed for this property.",
});
expect(didWrite).toBe(false);
}
);
test.each(["src", "width", "height", "alt"])(
"rejects incompatible Image %s assets before any database write",
async (name) => {
let didWrite = false;
let assetQuery: URL | undefined;
server.use(
db.get("Asset", ({ request }) => {
assetQuery = new URL(request.url);
return json([
{
assetId: "text-asset",
projectId: "project-1",
filename: null,
description: null,
file: {
name: "file.txt",
format: "txt",
size: 10,
createdAt: buildRow.createdAt,
updatedAt: buildRow.updatedAt,
description: null,
meta: "{}",
},
},
]);
}),
db.patch("Build", () => {
didWrite = true;
return empty({ headers: { "Content-Range": "*/1" } });
})
);
const result = await patchLoadedBuild(
{
build: {
...buildRow,
instances: JSON.stringify([
{
id: "body-1",
type: "instance",
component: "Image",
children: [],
},
]),
},
buildId: buildRow.id,
projectId: buildRow.projectId,
clientVersion: 3,
transactions: [
transaction({
payload: [
{
namespace: "props",
patches: [
{
op: "add",
path: [name],
value: {
id: name,
instanceId: "body-1",
name,
type: "asset",
value: "text-asset",
},
},
],
},
],
}),
],
},
createContext()
);
expect(result).toEqual({
status: "error",
errors: "This asset type is not allowed for this property.",
});
expect(didWrite).toBe(false);
expect(assetQuery?.searchParams.get("projectId")).toBe("eq.project-1");
expect(assetQuery?.searchParams.get("id")).toBe("in.(text-asset)");
}
);
test.each([
"record",
"field",
"map",
"component",
"repaired",
"unrelated",
"retry",
] as const)(
"validates final asset references for %s patches",
async (kind) => {
const source: Prop = {
id: "src",
instanceId: "body-1",
name: "src",
type: "asset",
value: "text-asset",
};
const build = {
...buildRow,
instances: JSON.stringify([
{
id: "body-1",
type: "instance",
component: kind === "component" ? "Box" : "Image",
children: [],
},
]),
props: JSON.stringify([...JSON.parse(buildRow.props), source]),
};
const before = structuredClone(build);
const payload: BuildPatchTransaction["payload"] =
kind === "component"
? [
{
namespace: "instances",
patches: [
{
op: "replace",
path: ["body-1", "component"],
value: "Image",
},
],
},
]
: kind === "unrelated"
? transaction().payload
: [
{
namespace: "props",
patches:
kind === "map"
? [
{
op: "replace",
path: [],
value: new Map([[source.id, source]]),
},
]
: kind === "record"
? [{ op: "replace", path: [source.id], value: source }]
: [
{
op: "replace",
path: [source.id, "value"],
value: source.value,
},
],
},
];
if (kind === "repaired") {
payload.push({
namespace: "props",
patches: [
{
op: "replace",
path: [source.id],
value: { ...source, type: "string", value: "/image.png" },
},
],
});
}
const loaded: string[][] = [];
const result = await createBuildPatchUpdate({
build,
clientVersion: kind === "retry" ? 2 : 3,
transactions: [
transaction({
id: kind === "retry" ? build.lastTransactionId : "new",
payload,
}),
],
loadAssets: async (ids) => {
loaded.push(ids);
return {
changedAssetIds: new Set(),
assets: [
{
id: source.value,
projectId: "project-1",
name: "file.txt",
type: "file",
format: "txt",
size: 10,
createdAt: "",
meta: {},
} satisfies Asset,
],
};
},
});
const allowed = ["repaired", "unrelated", "retry"].includes(kind);
expect(result.status).toBe(allowed ? "ok" : "error");
expect(loaded).toEqual(allowed ? [] : [[source.value]]);
if (result.status === "ok" && kind === "repaired") {
expect(JSON.parse(result.update!.props!)).toContainEqual({
...source,
type: "string",
value: "/image.png",
});
}
expect(build).toEqual(before);
}
);
test.each(["image", "missing"])(
"persists %s asset sources and linked metadata",
async (kind) => {
const savedProps: Prop[] = ["src", "width", "height", "alt"].map(
(name) => ({
id: name,
instanceId: "body-1",
name,
type: "asset",
value: "asset",
})
);
const requests: string[][] = [];
const result = await createBuildPatchUpdate({
build: {
...buildRow,
instances: JSON.stringify([
{
id: "body-1",
type: "instance",
component: "Image",
children: [],
},
]),
},
clientVersion: 3,
transactions: [
transaction({
payload: [
{
namespace: "props",
patches: savedProps.map((prop) => ({
op: "add",
path: [prop.id],
value: prop,
})),
},
],
}),
],
loadAssets: async (ids) => {
requests.push(ids);
return {
changedAssetIds: new Set(),
assets:
kind === "missing"
? []
: [
{
id: "asset",
projectId: "project-1",
type: "image",
name: "image.png",
format: "png",
meta: { width: 120, height: 80 },
size: 10,
createdAt: "",
},
],
};
},
});
expect(result.status).toBe("ok");
expect(requests).toEqual([["asset"]]);
if (result.status === "ok") {
expect(JSON.parse(result.update!.props!)).toEqual([
...JSON.parse(buildRow.props),
...savedProps,
]);
}
}
);
test("rejects an over-limit Contact email raw patch before persistence", async () => {
let didUpdateBuild = false;
server.use(
db.get("Project", () => json({ userId: "owner-1" })),
db.patch("Build", () => {
didUpdateBuild = true;
return empty({ headers: { "Content-Range": "*/1" } });
})
);
const result = await patchLoadedBuild(
{
build: buildRow,
buildId: "build-1",
projectId: "project-1",
clientVersion: 3,
transactions: [
transaction({
payload: [
{
namespace: "projectSettings",
patches: [
{
op: "add",
path: ["meta", "contactEmail"],
value: "[email protected]",
},
],
},
],
}),
],
},
{
...createContext(),
getOwnerPlanFeatures: async () => defaultPlanFeatures,
} as AppContext
);
expect(result).toMatchObject({
status: "error",
errors: "Upgrade to PRO to customize the contact email.",
});
expect(didUpdateBuild).toBe(false);
});
test("allows unrelated settings edits after a plan downgrade", async () => {
const existingBuild = {
...buildRow,
projectSettings: JSON.stringify({
meta: { contactEmail: "[email protected]" },
compiler: {},
}),
};
server.use(
db.patch("Build", () => empty({ headers: { "Content-Range": "*/1" } }))
);
const result = await patchLoadedBuild(
{
build: existingBuild,
buildId: "build-1",
projectId: "project-1",
clientVersion: 3,
transactions: [
transaction({
payload: [
{
namespace: "projectSettings",
patches: [
{ op: "add", path: ["meta", "siteName"], value: "Site" },
],
},
],
}),
],
},
{
...createContext(),
getOwnerPlanFeatures: async () => defaultPlanFeatures,
} as AppContext
);
expect(result.status).toBe("ok");
});
test("patches an already loaded build and returns the updated build row", async () => {
let didLoadBuild = false;
server.use(
db.get("Build", () => {
didLoadBuild = true;
return json([buildRow]);
}),
db.patch("Build", () => empty({ headers: { "Content-Range": "*/1" } }))
);
const result = await patchLoadedBuild(
{
build: buildRow,
buildId: "build-1",
projectId: "project-1",
clientVersion: 3,
transactions: [transaction()],
},
createContext()
);
expect(result.status).toBe("ok");
if (result.status === "ok") {
expect(result.version).toBe(4);
expect(result.build.version).toBe(4);
expect(JSON.parse(result.build.props)).toEqual([
{
id: "prop-1",
instanceId: "body-1",
name: "title",
type: "string",
value: "New title",
},
]);
}
expect(didLoadBuild).toBe(false);
});
test("persists asset-folder namespace changes before accepting the build transaction", async () => {
let insertedFolders: unknown;
server.use(
db.get("AssetFolder", () => json([])),
db.post("AssetFolder", async ({ request }) => {
insertedFolders = await request.json();
return json(insertedFolders as never);
}),
db.patch("Build", () => empty({ headers: { "Content-Range": "*/1" } }))
);
const result = await patchLoadedBuild(
{
build: buildRow,
buildId: "build-1",
projectId: "project-1",
clientVersion: 3,
transactions: [
transaction({
payload: [
{
namespace: "assetFolders",
patches: [
{
op: "add",
path: ["folder-1"],
value: {
id: "folder-1",
projectId: "project-1",
name: "Images",
createdAt: "2026-01-01T00:00:00.000Z",
},
},
],
},
],
}),
],
},
createContext()
);
expect(result.status).toBe("ok");
expect(insertedFolders).toEqual([
{
id: "folder-1",
projectId: "project-1",
name: "Images",
parentId: null,
createdAt: "2026-01-01T00:00:00.000Z",
},
]);
});
test("deletes folder assets before deleting the folder", async () => {
const calls: string[] = [];
const assetRow = {
assetId: "asset-1",
projectId: "project-1",
filename: null,
description: null,
folderId: "folder-1",
file: {
name: "asset.pdf",
format: "pdf",
description: null,
size: 1,
createdAt: "2026-01-01T00:00:00.000Z",
meta: "{}",
status: "UPLOADED",
},
};
server.use(
ownershipHandler,
db.get("AssetFolder", () =>
json([
{
id: "folder-1",
projectId: "project-1",
name: "Folder",
parentId: null,
createdAt: "2026-01-01T00:00:00.000Z",
},
])
),
db.get("Asset", ({ request }) => {
const url = new URL(request.url);
if (url.searchParams.has("name")) {
return json([]);
}
if (url.searchParams.has("id")) {
return json([
{
id: "asset-1",
projectId: "project-1",
name: "asset.pdf",
file: assetRow.file,
},
]);
}
return json([assetRow]);
}),
db.patch("Project", () => empty({ status: 204 })),
db.delete("Asset", () => {
calls.push("asset-delete");
return empty({ status: 204 });
}),
db.patch("File", () => empty({ status: 204 })),
db.delete("AssetFolder", () => {
calls.push("folder-delete");
return json([{ id: "folder-1" }]);
}),
db.patch("Build", () => {
calls.push("build-update");
return empty({ headers: { "Content-Range": "*/1" } });
})
);
const result = await patchLoadedBuild(
{
build: buildRow,
buildId: "build-1",
projectId: "project-1",
clientVersion: 3,
assetStore: {
readFile: async () => {
throw new Error("Unexpected asset content read");
},
},
transactions: [
transaction({
payload: [
{
namespace: "assetFolders",
patches: [{ op: "remove", path: ["folder-1"] }],
},
{
namespace: "assets",
patches: [{ op: "remove", path: ["asset-1"] }],
},
],
}),
],
},
createContext()
);
expect(result.status).toBe("ok");
expect(calls).toEqual(["asset-delete", "folder-delete", "build-update"]);
});
test("applies transactions, validates data, and updates build with optimistic version guard", async () => {
let updatedBuild: unknown;
server.use(
db.get("Build", () => json([buildRow])),
db.patch("Build", async ({ request }) => {
updatedBuild = await request.json();
return empty({ headers: { "Content-Range": "*/1" } });
})
);
const result = await patchBuild(
{
buildId: "build-1",
projectId: "project-1",
clientVersion: 3,
transactions: [transaction()],
},
createContext()
);
expect(result).toEqual({ status: "ok", version: 4 });
expect(updatedBuild).toMatchObject({
version: 4,
lastTransactionId: "tx-1",
});
expect(JSON.parse((updatedBuild as { props: string }).props)).toEqual([
{
id: "prop-1",
instanceId: "body-1",
name: "title",
type: "string",
value: "New title",
},
]);
});
test("applies page path changes from normalized page id patches", async () => {
let updatedBuild: unknown;
server.use(
db.get("Build", () =>
json([
{
...buildRow,
pages: JSON.stringify({
meta: {},
homePageId: "page-1",
rootFolderId: "root",
pages: [
{
id: "page-1",
name: "Home",
path: "",
title: "Home",
meta: {},
rootInstanceId: "body-1",
},
{
id: "page-2",
name: "About",
path: "/about",
title: "About",
meta: {},
rootInstanceId: "body-1",
},
],
folders: [
{
id: "root",
name: "Root",
slug: "",
children: ["page-1", "page-2"],
},
],
}),
},
])
),
db.patch("Build", async ({ request }) => {
updatedBuild = await request.json();
return empty({ headers: { "Content-Range": "*/1" } });
})
);
const result = await patchBuild(
{
buildId: "build-1",
projectId: "project-1",
clientVersion: 3,
transactions: [
transaction({
payload: [
{
namespace: "pages",
patches: [
{
op: "replace",
path: ["pages", "page-2", "path"],
value: "/company",
},
],
},
],
}),
],
},
createContext()
);
expect(result).toEqual({ status: "ok", version: 4 });
expect(
JSON.parse((updatedBuild as { pages: string }).pages).pages.find(
(page: { id: string }) => page.id === "page-2"
)?.path
).toBe("/company");
});
test("persists folder index paths for page updates and duplicates", async () => {
const buildWithFolder = {
...buildRow,
pages: JSON.stringify({
meta: {},
homePage: {
id: "page-1",
name: "Home",
path: "",
title: "Home",
meta: {},
rootInstanceId: "body-1",
},
pages: [
{
id: "page-2",
name: "Landing",
path: "/landing",
title: "Landing",
meta: {},
rootInstanceId: "body-2",
},
],
folders: [
{
id: "root",
name: "Root",
slug: "",
children: ["page-1", "folder-1"],
},
{
id: "folder-1",
name: "Folder",
slug: "folder",
children: ["page-2"],
},
],
}),
};
const updated = await createBuildPatchUpdate({
loadAssets: async () => ({ assets: [], changedAssetIds: new Set() }),
build: buildWithFolder,
clientVersion: 3,
transactions: [
transaction({
payload: [
{
namespace: "pages",
patches: [
{
op: "replace",
path: ["pages", "page-2", "path"],
value: "",
},
],
},
],
}),
],
});
expect(updated.status).toBe("ok");
const duplicated = await createBuildPatchUpdate({
loadAssets: async () => ({ assets: [], changedAssetIds: new Set() }),
build: buildWithFolder,
clientVersion: 3,
transactions: [
transaction({
payload: [
{
namespace: "pages",
patches: [
{
op: "add",
path: ["pages", "page-copy"],
value: {
id: "page-copy",
name: "Copy",
path: "",
title: "Copy",
meta: {},
rootInstanceId: "body-copy",
},
},
{
op: "add",
path: ["folders", "folder-1", "children", 1],
value: "page-copy",
},
],
},
],
}),
],
});
expect(duplicated.status).toBe("ok");
});
test("applies data source variable additions", async () => {
const result = await createBuildPatchUpdate({
loadAssets: async () => ({ assets: [], changedAssetIds: new Set() }),
build: buildRow,
clientVersion: 3,
transactions: [
transaction({
payload: [
{
namespace: "dataSources",
patches: [
{
op: "add",
path: ["variable-1"],
value: {
id: "variable-1",
scopeInstanceId: "body-1",
name: "title",
type: "variable",
value: { type: "string", value: "" },
},
},
],
},
],
}),
],
});
expect(result).toMatchObject({
status: "ok",
nextVersion: 4,
update: {
lastTransactionId: "tx-1",
version: 4,
},
});
if (result.status === "ok") {
expect(JSON.parse(result.update?.dataSources ?? "")).toEqual([
{
id: "variable-1",
scopeInstanceId: "body-1",
name: "title",
type: "variable",
value: { type: "string", value: "" },
},
]);
}
});
test("persists project settings without modifying pages storage", async () => {
const result = await createBuildPatchUpdate({
loadAssets: async () => ({ assets: [], changedAssetIds: new Set() }),
build: buildRow,
clientVersion: 3,
transactions: [
transaction({
payload: [
{
namespace: "projectSettings",
patches: [
{
op: "add",
path: ["meta", "agentInstructions"],
value: "Use existing components.",
},
],
},
],
}),
],
});
expect(result.status).toBe("ok");
if (result.status === "ok") {
expect(result.update).toBeDefined();
if (result.update === undefined) {
throw new Error("Expected project settings update");
}
expect(result.update.pages).toBeUndefined();
expect(
JSON.parse(result.update.projectSettings as string).meta
).toMatchObject({
agentInstructions: "Use existing components.",
});
}
});
test("persists an explicitly cleared marketplace product", async () => {
const result = await createBuildPatchUpdate({
loadAssets: async () => ({ assets: [], changedAssetIds: new Set() }),
build: {
...buildRow,
marketplaceProduct: JSON.stringify({
category: "sectionTemplates",
name: "Example section",
thumbnailAssetId: "thumbnail",
author: "Webstudio",
email: "[email protected]",
website: "",
issues: "",
description: "Example marketplace product",
}),
},
clientVersion: 3,
transactions: [
transaction({
payload: [
{
namespace: "marketplaceProduct",
patches: [{ op: "replace", path: [], value: undefined }],
},
],
}),
],
});
expect(result.status).toBe("ok");
if (result.status === "ok") {
expect(JSON.parse(result.update?.marketplaceProduct ?? "null")).toEqual(
{}
);
}
});
test("validates only touched props while preserving untouched props", async () => {
const buildWithInvalidUntouchedProp = {
...buildRow,
props: JSON.stringify([
{
id: "prop-1",
instanceId: "body-1",
name: "title",
type: "string",
value: "Old title",
},
{
id: "prop-invalid",
instanceId: "body-1",
name: "count",
type: "number",
value: "invalid number",
},
]),
};
const result = await createBuildPatchUpdate({
loadAssets: async () => ({ assets: [], changedAssetIds: new Set() }),
build: buildWithInvalidUntouchedProp,
clientVersion: 3,
transactions: [transaction()],
});
expect(result.status).toBe("ok");
if (result.status === "ok") {
expect(JSON.parse(result.update?.props ?? "")).toEqual([
{
id: "prop-1",
instanceId: "body-1",
name: "title",
type: "string",
value: "New title",
},
{
id: "prop-invalid",
instanceId: "body-1",
name: "count",
type: "number",
value: "invalid number",
},
]);
}
});
test("rejects invalid touched props", async () => {
await expect(
createBuildPatchUpdate({
loadAssets: async () => ({ assets: [], changedAssetIds: new Set() }),
build: buildRow,
clientVersion: 3,
transactions: [
transaction({
payload: [
{
namespace: "props",
patches: [
{
op: "replace",
path: ["prop-1", "value"],
value: 123,
},
],
},
],
}),
],
})
).rejects.toThrow();
});
test("rejects touched props set to undefined", async () => {
await expect(
createBuildPatchUpdate({
loadAssets: async () => ({ assets: [], changedAssetIds: new Set() }),
build: buildRow,
clientVersion: 3,
transactions: [
transaction({
payload: [
{
namespace: "props",
patches: [
{
op: "replace",
path: ["prop-1"],
value: undefined,
},
],
},
],
}),
],
})
).rejects.toThrow();
});
test("validates all props when patch replaces the props map", async () => {
await expect(
createBuildPatchUpdate({
loadAssets: async () => ({ assets: [], changedAssetIds: new Set() }),
build: buildRow,
clientVersion: 3,
transactions: [
transaction({
payload: [
{
namespace: "props",
patches: [
{
op: "replace",
path: [],
value: new Map([
[
"prop-invalid",
{
id: "prop-invalid",
instanceId: "body-1",
name: "count",
type: "number",
value: "invalid number",
},
],
]),
},
],
},
],
}),
],
})
).rejects.toThrow();
});
test("rejects touched styles set to undefined", async () => {
const style = {
styleSourceId: "style-source-1",
breakpointId: "breakpoint-1",
property: "width",
value: { type: "unit", value: 10, unit: "px" },
};
const buildWithStyle = {
...buildRow,
styles: JSON.stringify([style]),
};
const styleKey = "style-source-1:breakpoint-1:width:";
await expect(
createBuildPatchUpdate({
loadAssets: async () => ({ assets: [], changedAssetIds: new Set() }),
build: buildWithStyle,
clientVersion: 3,
transactions: [
transaction({
payload: [
{
namespace: "styles",
patches: [
{
op: "replace",
path: [styleKey],
value: undefined,
},
],
},
],
}),
],
})
).rejects.toThrow();
});
test("validates only touched instances while preserving untouched instances", async () => {
const buildWithInvalidUntouchedInstance = {
...buildRow,
instances: JSON.stringify([
{
id: "body-1",
type: "instance",
component: "Body",
children: [],
},
{
id: "instance-invalid",
type: "instance",
children: [],
},
]),
};
const result = await createBuildPatchUpdate({
loadAssets: async () => ({ assets: [], changedAssetIds: new Set() }),
build: buildWithInvalidUntouchedInstance,
clientVersion: 3,
transactions: [
transaction({
payload: [
{
namespace: "instances",
patches: [
{
op: "add",
path: ["body-1", "label"],
value: "Body label",
},
],
},
],
}),
],
});
expect(result.status).toBe("ok");
if (result.status === "ok") {
expect(JSON.parse(result.update?.instances ?? "")).toEqual([
{
id: "body-1",
type: "instance",
component: "Body",
label: "Body label",
children: [],
},
{
id: "instance-invalid",
type: "instance",
children: [],
},
]);
}
});
test("rejects invalid touched instances", async () => {
await expect(
createBuildPatchUpdate({
loadAssets: async () => ({ assets: [], changedAssetIds: new Set() }),
build: buildRow,
clientVersion: 3,
transactions: [
transaction({
payload: [
{
namespace: "instances",
patches: [
{
op: "remove",
path: ["body-1", "component"],
},
],
},
],
}),
],
})
).rejects.toThrow();
});
test("returns ok when retrying a transaction already saved by the server", async () => {
let didPatch = false;
server.use(
db.get("Build", () =>
json([{ ...buildRow, version: 4, lastTransactionId: "tx-1" }])
),
db.patch("Build", () => {
didPatch = true;
return empty({ headers: { "Content-Range": "*/1" } });
})
);
const result = await patchBuild(
{
buildId: "build-1",
projectId: "project-1",
clientVersion: 3,
transactions: [transaction()],
},
createContext()
);
expect(result).toEqual({ status: "ok", version: 4 });
expect(didPatch).toBe(false);
});
test("returns version_mismatched when loaded build version differs", async () => {
server.use(db.get("Build", () => json([{ ...buildRow, version: 4 }])));
const result = await patchBuild(
{
buildId: "build-1",
projectId: "project-1",
clientVersion: 3,
transactions: [transaction()],
},
createContext()
);
expect(result).toEqual(singlePlayerVersionMismatchResult);
});
test("returns version_mismatched when optimistic update affects no rows", async () => {
server.use(
db.get("Build", () => json([buildRow])),
db.patch("Build", () => empty({ headers: { "Content-Range": "*/0" } }))
);
const result = await patchBuild(
{
buildId: "build-1",
projectId: "project-1",
clientVersion: 3,
transactions: [transaction()],
},
createContext()
);
expect(result).toEqual(singlePlayerVersionMismatchResult);
});
test("rejects unknown namespaces", async () => {
let didPatch = false;
server.use(
db.get("Build", () => json([buildRow])),
db.patch("Build", () => {
didPatch = true;
return empty({ headers: { "Content-Range": "*/1" } });
})
);
const result = await patchBuild(
{
buildId: "build-1",
projectId: "project-1",
clientVersion: 3,
transactions: [
transaction({
payload: [
{
namespace: "unknown",
patches: [{ op: "add", path: [], value: null }],
},
],
}),
],
},
createContext()
);
expect(result).toEqual({
status: "error",
errors: 'Unknown namespace "unknown"',
});
expect(didPatch).toBe(false);
});
test("core patch helper is decoupled from asset app logic", async () => {
const assetPatch = { op: "add" as const, path: ["asset-1"], value: {} };
const result = await createBuildPatchUpdate({
loadAssets: async () => ({ assets: [], changedAssetIds: new Set() }),
build: buildRow,
clientVersion: 3,
transactions: [
transaction({
payload: [
{
namespace: "assets",
patches: [assetPatch],
},
],
}),
],
});
expect(result).toMatchObject({
status: "ok",
assetPatches: [[assetPatch]],
nextVersion: 4,
update: {
lastTransactionId: "tx-1",
version: 4,
},
});
});
test("does not mark build as saved when asset patching fails", async () => {
let didPatchBuild = false;
server.use(
ownershipHandler,
db.get("Build", () => json([buildRow])),
db.get("Asset", () => json([])),
db.patch("Build", () => {
didPatchBuild = true;
return empty({ headers: { "Content-Range": "*/1" } });
})
);
await expect(
patchBuild(
{
buildId: "build-1",
projectId: "project-1",
clientVersion: 3,
transactions: [
transaction({
payload: [
{
namespace: "assets",
patches: [
{
op: "add",
path: ["asset-invalid"],
value: {
id: "asset-invalid",
name: "invalid.jpg",
},
},
],
},
],
}),
],
},
createContext()
)
).rejects.toThrow();
expect(didPatchBuild).toBe(false);
});
});