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: Submit webhook forms only once (#5979)

Oleg Isonen9fe63c75018e
diff --git a/apps/builder/app/shared/instance-utils/data.test.tsx b/apps/builder/app/shared/instance-utils/data.test.tsx
index aed425ada2..693a738e40 100644
--- a/apps/builder/app/shared/instance-utils/data.test.tsx
+++ b/apps/builder/app/shared/instance-utils/data.test.tsx
@@ -865,10 +865,7 @@ describe("data store helpers", () => {
upsertResult?.result.resourceId,
"resource id"
);
- const dataSourceId = expectGeneratedId(
- upsertResult?.result.dataSourceId,
- "resource data source id"
- );
+ expect(upsertResult?.result.dataSourceId).toBeUndefined();
const propId = upsertResult?.result.propIds[0];
expectGeneratedId(propId, "resource prop id");
@@ -880,15 +877,7 @@ describe("data store helpers", () => {
url: `"https://example.com/leads"`,
})
);
- expect($dataSources.get().get(dataSourceId)).toEqual(
- expect.objectContaining({
- id: dataSourceId,
- type: "resource",
- resourceId,
- name: "leadResponse",
- scopeInstanceId: "body",
- })
- );
+ expect($dataSources.get()).toEqual(new Map());
expect($props.get().get(propId ?? "")).toEqual(
expect.objectContaining({
instanceId: "body",
@@ -916,11 +905,7 @@ describe("data store helpers", () => {
url: `"https://example.com/customers"`,
})
);
- expect($dataSources.get().get(dataSourceId)).toEqual(
- expect.objectContaining({
- name: "customerLeadResponse",
- })
- );
+ expect($dataSources.get()).toEqual(new Map());
executeRuntimeMutation({
id: "resources.delete",
@@ -931,7 +916,7 @@ describe("data store helpers", () => {
});
expect($resources.get().has(resourceId)).toEqual(false);
- expect($dataSources.get().has(dataSourceId)).toEqual(false);
+ expect($dataSources.get()).toEqual(new Map());
expect($props.get().has(propId ?? "")).toEqual(false);
});
diff --git a/apps/builder/e2e/flows/generated-app.ts b/apps/builder/e2e/flows/generated-app.ts
index f9ac74f600..36be46e9f8 100644
--- a/apps/builder/e2e/flows/generated-app.ts
+++ b/apps/builder/e2e/flows/generated-app.ts
@@ -173,7 +173,7 @@ export const expectGeneratedAppBuild = async ({
}
};
-const withGeneratedPreview = async <Result>({
+export const withGeneratedPreview = async <Result>({
projectId,
callback,
}: {
diff --git a/apps/builder/e2e/tests/props-runtime.[shard-2].[shard-5].[shard-6].e2e.ts b/apps/builder/e2e/tests/props-runtime.[shard-2].[shard-5].[shard-6].e2e.ts
index fb199817bf..822e2cfeb3 100644
--- a/apps/builder/e2e/tests/props-runtime.[shard-2].[shard-5].[shard-6].e2e.ts
+++ b/apps/builder/e2e/tests/props-runtime.[shard-2].[shard-5].[shard-6].e2e.ts
@@ -1,3 +1,4 @@
+import { createServer } from "node:http";
import type { Page } from "playwright";
import { loadDevBuild } from "../db";
import { openProjectBuilder, waitForCanvasText } from "../flows/builder";
@@ -13,6 +14,7 @@ import {
waitForSyncStatus,
} from "../flows/sync-status";
import { createContentModeProject } from "../fixtures/content-mode-suite";
+import { withGeneratedPreview } from "../flows/generated-app";
import { newIsolatedPage, test } from "../harness";
import { measure } from "../perf";
@@ -93,7 +95,7 @@ const updateResourceActionUrl = async ({
await input.waitFor({ state: "visible", timeout: 10_000 });
await input.fill(url);
const save = waitForChangeToBeSaved({ page });
- await input.blur();
+ await input.press("Enter");
await save;
await waitForSyncStatus({ page, status: "idle" });
};
@@ -174,6 +176,10 @@ const expectPersistedActionResource = async ({
method: string;
url: string;
}>;
+ const dataSources = JSON.parse(build.dataSources) as Array<{
+ type: string;
+ resourceId?: string;
+ }>;
const resource = resources.find(
(resource) =>
resource.name === "action" &&
@@ -192,6 +198,51 @@ const expectPersistedActionResource = async ({
`Expected Webhook Form action prop to persist resource "${url}". Props: ${JSON.stringify(props)} Resources: ${JSON.stringify(resources)}`
);
}
+ if (
+ dataSources.some(
+ (dataSource) =>
+ dataSource.type === "resource" && dataSource.resourceId === resource.id
+ )
+ ) {
+ throw new Error(
+ `Expected Webhook Form action resource "${url}" not to load during rendering. Data sources: ${JSON.stringify(dataSources)}`
+ );
+ }
+};
+
+const startWebhookServer = async () => {
+ const requests: Array<{ method: string | undefined; body: unknown }> = [];
+ const server = createServer(async (request, response) => {
+ const chunks: Buffer[] = [];
+ for await (const chunk of request) {
+ chunks.push(Buffer.from(chunk));
+ }
+ const bodyText = Buffer.concat(chunks).toString("utf8");
+ requests.push({
+ method: request.method,
+ body: bodyText === "" ? undefined : JSON.parse(bodyText),
+ });
+ response.writeHead(200, {
+ "Access-Control-Allow-Origin": "*",
+ "Content-Type": "application/json",
+ });
+ response.end(JSON.stringify({ success: true }));
+ });
+ await new Promise<void>((resolve, reject) => {
+ server.once("error", reject);
+ server.listen(0, "127.0.0.1", resolve);
+ });
+ const address = server.address();
+ if (address === null || typeof address === "string") {
+ await new Promise<void>((resolve) => server.close(() => resolve()));
+ throw new Error("Expected a numeric webhook server port.");
+ }
+ return {
+ requests,
+ url: `http://127.0.0.1:${address.port}/submit`,
+ close: async () =>
+ await new Promise<void>((resolve) => server.close(() => resolve())),
+ };
};
const expectPersistedExpressionProp = async ({
@@ -336,7 +387,7 @@ const expectBooleanPropDeleted = async ({
}
};
-test("Props panel resource action persists after reload", async () => {
+test("Webhook Form action submits once and persists after reload", async () => {
const fixture = await createContentModeProject({
title: "Props Runtime",
@@ -345,8 +396,9 @@ test("Props panel resource action persists after reload", async () => {
builderToken: "props-runtime-builder-token",
});
const { page, close } = await newIsolatedPage();
+ const webhook = await startWebhookServer();
const text = "Initial content";
- const actionUrl = "/$resources/current-date";
+ const actionUrl = webhook.url;
try {
await measure("props runtime open builder", async () => {
@@ -387,7 +439,41 @@ test("Props panel resource action persists after reload", async () => {
projectId: fixture.projectId,
url: actionUrl,
});
+
+ await measure("props runtime submit generated webhook form", async () => {
+ await withGeneratedPreview({
+ projectId: fixture.projectId,
+ callback: async ({ url }) => {
+ await page.goto(url);
+ if (webhook.requests.length !== 0) {
+ throw new Error(
+ `Expected no webhook requests before submission, received ${JSON.stringify(webhook.requests)}`
+ );
+ }
+ await page.locator('input[name="name"]').fill("Ada");
+ await page.locator('input[name="email"]').fill("[email protected]");
+ await page.getByRole("button", { name: "Submit" }).click();
+ await page
+ .getByText("Thank you for getting in touch!", { exact: true })
+ .waitFor();
+ },
+ });
+ });
+ if (
+ JSON.stringify(webhook.requests) !==
+ JSON.stringify([
+ {
+ method: "POST",
+ body: { name: "Ada", email: "[email protected]" },
+ },
+ ])
+ ) {
+ throw new Error(
+ `Expected one populated webhook submission, received ${JSON.stringify(webhook.requests)}`
+ );
+ }
} finally {
+ await webhook.close();
await close();
}
});
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 694ddaee09..2a2e51b7ca 100644
--- a/packages/project-build/src/contracts/__generated__/runtime-operation-contracts.ts
+++ b/packages/project-build/src/contracts/__generated__/runtime-operation-contracts.ts
@@ -69773,7 +69773,7 @@ export const runtimeOperationContractData = [
},
},
},
- required: ["resourceId", "dataSourceId", "propIds"],
+ required: ["resourceId", "propIds"],
additionalProperties: {},
},
readNamespaces: [
diff --git a/packages/project-build/src/runtime/data.test.tsx b/packages/project-build/src/runtime/data.test.tsx
index 98a6f25026..478e5f6aac 100644
--- a/packages/project-build/src/runtime/data.test.tsx
+++ b/packages/project-build/src/runtime/data.test.tsx
@@ -2995,26 +2995,26 @@ describe("resource patch helpers", () => {
).toEqual({ resourceId: "resource-id", dataSourceId: "resource-id" });
});
- test("upserts resource and binds instance prop atomically", () => {
+ test("upserts a prop resource without exposing it as render-time data", () => {
const body: Instance = {
type: "instance",
id: "body",
component: "Body",
children: [{ type: "id", value: "box" }],
};
- const box: Instance = {
+ const form: Instance = {
type: "instance",
- id: "box",
- component: "Box",
+ id: "form",
+ component: "Form",
children: [],
};
- const ids = ["resource-id", "prop-id", "data-source-id"];
+ const ids = ["resource-id", "prop-id"];
const result = upsertResourceProp(
{
pages: createDefaultPages({ rootInstanceId: "body" }),
instances: new Map([
[body.id, body],
- [box.id, box],
+ [form.id, form],
]),
props: new Map(),
dataSources: new Map(),
@@ -3025,12 +3025,12 @@ describe("resource patch helpers", () => {
styles: new Map(),
},
{
- instanceId: "box",
- propName: "data",
+ instanceId: "form",
+ propName: "action",
resource: resourceFieldsInput.parse({
- name: "Users",
- method: "get",
- url: "https://example.com/users",
+ name: "Submit",
+ method: "post",
+ url: "https://example.com/submit",
headers: [],
}),
},
@@ -3039,9 +3039,12 @@ describe("resource patch helpers", () => {
expect(result.result).toEqual({
resourceId: "resource-id",
- dataSourceId: "data-source-id",
+ dataSourceId: undefined,
propIds: ["prop-id"],
});
+ expect(result.payload).not.toContainEqual(
+ expect.objectContaining({ namespace: "dataSources" })
+ );
expect(result.payload).toContainEqual({
namespace: "props",
patches: [
@@ -3050,8 +3053,8 @@ describe("resource patch helpers", () => {
path: ["prop-id"],
value: {
id: "prop-id",
- instanceId: "box",
- name: "data",
+ instanceId: "form",
+ name: "action",
type: "resource",
value: "resource-id",
required: undefined,
@@ -3067,10 +3070,10 @@ describe("resource patch helpers", () => {
path: ["resource-id"],
value: {
id: "resource-id",
- name: "Users",
+ name: "Submit",
control: undefined,
- method: "get",
- url: '"https://example.com/users"',
+ method: "post",
+ url: '"https://example.com/submit"',
searchParams: undefined,
headers: [],
body: undefined,
diff --git a/packages/project-build/src/runtime/data.ts b/packages/project-build/src/runtime/data.ts
index 206ad2bac2..0290c8462c 100644
--- a/packages/project-build/src/runtime/data.ts
+++ b/packages/project-build/src/runtime/data.ts
@@ -2943,10 +2943,6 @@ export const upsertResourceProp = (
headers: resourceInput.headers,
body: resourceInput.body,
});
- const dataSource = build.dataSources.find(
- (dataSource) =>
- dataSource.type === "resource" && dataSource.resourceId === resourceId
- );
const existingProp = findProp(build.props, input.instanceId, input.propName);
const nextProp = createValidatedPropValueFromInput(
{
@@ -2965,19 +2961,16 @@ export const upsertResourceProp = (
props: build.props,
nextProps: [nextProp.prop],
});
- const dataSourceId = dataSource?.id ?? context.createId();
return createRuntimeMutation({
payload: compactBuilderPatchPayload([
...createResourceUpsertPatchPayload({
build,
resource,
- dataSourceId,
- scopeInstanceId: input.scopeInstanceId ?? input.instanceId,
- dataSourceName: input.dataSourceName ?? resource.name,
+ exposeAsDataSource: false,
}),
...propPayload,
]),
- result: { resourceId, dataSourceId, propIds },
+ result: { resourceId, dataSourceId: undefined, propIds },
invalidatesNamespaces: [
"pages",
"instances",
diff --git a/packages/project-build/src/runtime/output-schemas.ts b/packages/project-build/src/runtime/output-schemas.ts
index 3e09883ec3..6015294890 100644
--- a/packages/project-build/src/runtime/output-schemas.ts
+++ b/packages/project-build/src/runtime/output-schemas.ts
@@ -625,7 +625,7 @@ export const runtimeOutputSchemas = {
"resources.upsert": looseObject({ resourceId: id, dataSourceId: id }),
"resources.upsertProp": looseObject({
resourceId: id,
- dataSourceId: id,
+ dataSourceId: id.optional(),
propIds: stringArray,
}),
"resources.delete": looseObject({
diff --git a/packages/sdk/src/resources-generator.test.tsx b/packages/sdk/src/resources-generator.test.tsx
index 8adae1255d..ee1e0950a4 100644
--- a/packages/sdk/src/resources-generator.test.tsx
+++ b/packages/sdk/src/resources-generator.test.tsx
@@ -418,7 +418,7 @@ test("prevent generating unused system variable", () => {
`);
});
-test("generate action resource", () => {
+test("generate action resource without loading a stale data source", () => {
expect(
generateResources({
scope: createScope(),
@@ -426,7 +426,15 @@ test("generate action resource", () => {
rootInstanceId: "body",
systemDataSourceId: "variableParamsId",
} as Page,
- dataSources: new Map(),
+ dataSources: toMap([
+ {
+ id: "resourceDataSourceId",
+ scopeInstanceId: "body",
+ type: "resource",
+ name: "resourceDataSource",
+ resourceId: "resourceId",
+ },
+ ]),
resources: toMap([
{
id: "resourceId",
diff --git a/packages/sdk/src/resources-generator.ts b/packages/sdk/src/resources-generator.ts
index c435b0aba9..4ff40c149f 100644
--- a/packages/sdk/src/resources-generator.ts
+++ b/packages/sdk/src/resources-generator.ts
@@ -103,11 +103,19 @@ export const generateResources = ({
generated += generatedVariables;
generated += generatedRequests;
+ const actionResourceIds = new Set<string>();
+ for (const prop of props.values()) {
+ if (prop.type === "resource" && generatedResourceIds.has(prop.value)) {
+ actionResourceIds.add(prop.value);
+ }
+ }
+
generated += ` const _data = new Map<string, ResourceRequest>([\n`;
for (const dataSource of dataSources.values()) {
if (
dataSource.type === "resource" &&
- generatedResourceIds.has(dataSource.resourceId)
+ generatedResourceIds.has(dataSource.resourceId) &&
+ actionResourceIds.has(dataSource.resourceId) === false
) {
const name = scope.getName(dataSource.resourceId, dataSource.name);
generated += ` ["${name}", ${name}],\n`;