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
Changes to enable forms submission in saas (#1568)
Roman Pominovfa6aba1f8b0c
diff --git a/apps/builder/app/routes/rest.project.$projectId.tsx b/apps/builder/app/routes/rest.project.$projectId.tsxindex 1f1de934db..471a60b6ec 100644--- a/apps/builder/app/routes/rest.project.$projectId.tsx+++ b/apps/builder/app/routes/rest.project.$projectId.tsx@@ -1,13 +1,17 @@import { json, type LoaderArgs } from "@remix-run/node";import type { Data } from "@webstudio-is/react-sdk";+import { db as projectDb } from "@webstudio-is/project/index.server";import { sentryException } from "~/shared/sentry";import { loadProductionCanvasData } from "~/shared/db";import { createContext } from "~/shared/context.server";+import { getUserById, type User } from "~/shared/db/user.server";export const loader = async ({params,request,-}: LoaderArgs): Promise<Data> => {+}: LoaderArgs): Promise<+ Data & { user: { email: User["email"] } | undefined }+> => {try {const projectId = params.projectId ?? undefined;@@ -22,7 +26,20 @@ export const loader = async ({context);- return pagesCanvasData;+ const project = await projectDb.project.loadByParams(+ { projectId },+ context+ );++ const user =+ project === null || project.userId === null+ ? undefined+ : await getUserById(project.userId);++ return {+ ...pagesCanvasData,+ user: user ? { email: user.email } : undefined,+ };} catch (error) {// If a Response is thrown, we're rethrowing it for Remix to handle.// https://remix.run/docs/en/v1/api/conventions#throwing-responses-in-loadersdiff --git a/packages/form-handlers-mailchannels-test/src/index.ts b/packages/form-handlers-mailchannels-test/src/index.tsindex a01b66052d..78621c2211 100644--- a/packages/form-handlers-mailchannels-test/src/index.ts+++ b/packages/form-handlers-mailchannels-test/src/index.ts@@ -13,13 +13,18 @@ export default {}const formData = new FormData();+ formData.append("ws--form-id", "test-form");formData.append("name", "Bob");formData.append("time", new Date().toLocaleString("en-US"));const result = await mailchannelsHandler({- senderEmail: "[email protected]",- recipientEmail: to,- formData,+ formInfo: {+ formData,+ projectId: "test-project",+ pageUrl: "https://example.com/some-page",+ toEmail: to,+ fromEmail: "[email protected]",+ },});if (result.success) {diff --git a/packages/form-handlers/src/index.ts b/packages/form-handlers/src/index.tsindex 9c7f15af24..15f395324a 100644--- a/packages/form-handlers/src/index.ts+++ b/packages/form-handlers/src/index.ts@@ -1,3 +1,8 @@-export { formDataToEmailContent } from "./shared";+export {+ formToEmail,+ formIdFieldName,+ type EmailInfo,+ type FormInfo,+} from "./shared";export { mailchannelsHandler } from "./mailchanels";export { n8nHandler } from "./n8n";diff --git a/packages/form-handlers/src/mailchanels.ts b/packages/form-handlers/src/mailchanels.tsindex 04175dc11c..f19e090d23 100644--- a/packages/form-handlers/src/mailchanels.ts+++ b/packages/form-handlers/src/mailchanels.ts@@ -4,7 +4,13 @@//// To test see `packages/form-handlers-mailchannels-test`-import { formDataToEmailContent } from "./shared";+import {+ type FormInfo,+ type Result,+ formToEmail,+ getErrors,+ getResponseBody,+} from "./shared";type EmailAddress = {email: string;@@ -38,47 +44,44 @@ type SendEmailPayload = {headers?: Record<string, string>;};-type SendEmailResult = { success: true } | { success: false; errors: string[] };--const sendEmail = async (- payload: SendEmailPayload-): Promise<SendEmailResult> => {- const response = await fetch("https://api.mailchannels.net/tx/v1/send", {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify(payload),- });+const sendEmail = async (payload: SendEmailPayload): Promise<Result> => {+ let response: Response;+ try {+ response = await fetch("https://api.mailchannels.net/tx/v1/send", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify(payload),+ });+ } catch (error) {+ return { success: false, errors: [(error as Error).message] };+ }- if (response.status === 202) {+ if (response.status >= 200 && response.status < 300) {return { success: true };}- try {- const { errors } = await response.json();- return { success: false, errors };- } catch {- return { success: false, errors: [response.statusText] };- }+ const { text, json } = await getResponseBody(response);++ return { success: false, errors: getErrors(json) ?? [text] };};export const mailchannelsHandler = async ({- formData,- recipientEmail,- senderEmail,+ formInfo,}: {- formData: FormData;- recipientEmail: string;- senderEmail: string;+ formInfo: FormInfo;}) => {- const { plainText, html, subject } = formDataToEmailContent({ formData });+ const email = formToEmail(formInfo);return sendEmail({- personalizations: [{ to: [{ email: recipientEmail }] }],- from: { email: senderEmail },- subject: subject,+ personalizations: [{ to: [{ email: email.to }] }],+ from: { email: email.from },+ subject: email.subject,content: [- { type: "text/plain", value: plainText },- { type: "text/html", value: html },+ { type: "text/plain", value: email.txt },+ {+ type: "text/html",+ value: `<!DOCTYPE html><html><body>${email.html}</body></html>`,+ },],});};diff --git a/packages/form-handlers/src/n8n.ts b/packages/form-handlers/src/n8n.tsindex a74806405d..6889c5eb35 100644--- a/packages/form-handlers/src/n8n.ts+++ b/packages/form-handlers/src/n8n.ts@@ -1,62 +1,80 @@-import { formDataToEmailContent } from "./shared";+import {+ type FormInfo,+ type Result,+ formToEmail,+ getFormEntries,+ getErrors,+ getResponseBody,+ getFormId,+} from "./shared";++const getAuth = (hookUrl: string) => {+ const url = new URL(hookUrl);+ const { username, password } = url;+ url.username = "";+ url.password = "";+ const urlWithoutAuth = url.toString();+ return {+ username,+ password,+ urlWithoutAuth,+ };+};export const n8nHandler = async ({- formData,- recipientEmail,- senderEmail,+ formInfo,hookUrl,- authentication,}: {- formData: FormData;- recipientEmail: string;- senderEmail: string;+ formInfo: FormInfo;+ /** May containt basic authentication credentials,+ * e.g. https://user:[email protected]/webhook/... */hookUrl: string;- // @todo: add support for other authentication types- authentication?: { type: "basic"; username: string; password: string };-}) => {- const { plainText, html, subject } = formDataToEmailContent({ formData });-+}): Promise<Result> => {const headers: HeadersInit = { "Content-Type": "application/json" };- if (authentication?.type === "basic") {- headers["Authorization"] = `Basic ${Buffer.from(- `${authentication.username}:${authentication.password}`- ).toString("base64")}`;+ const { username, password, urlWithoutAuth } = getAuth(hookUrl);++ if (username !== "" && password !== "") {+ // using btoa() instead of Buffer.from().toString("base64")+ // because Buffer is not available in Cloudflare workers+ headers["Authorization"] = `Basic ${btoa([username, password].join(":"))}`;+ }++ const formId = getFormId(formInfo.formData);++ if (formId === undefined) {+ return { success: false, errors: ["No form id in FormData"] };}const payload = {- email: {- to: recipientEmail,- from: senderEmail,- subject,- plainText,- html,- },- formData: Object.fromEntries(formData),+ email: formToEmail(formInfo),+ // globally unique form id (can be used for unsubscribing)+ formId: [formInfo.projectId, formId].join("--"),+ formData: Object.fromEntries(getFormEntries(formInfo.formData)),};- const response = await fetch(hookUrl, {- method: "POST",- headers,- body: JSON.stringify(payload),- });-+ let response: Response;try {- const data = await response.json();-- if (response.status === 200 && data.success === true) {- return { success: true };- }+ response = await fetch(urlWithoutAuth, {+ method: "POST",+ headers,+ body: JSON.stringify(payload),+ });+ } catch (error) {+ return { success: false, errors: [(error as Error).message] };+ }- if (typeof data.error === "string") {- return { success: false, errors: [data.error] };- }+ const { text, json } = await getResponseBody(response);- if (typeof data.message === "string") {- return { success: false, errors: [data.message] };- }- // eslint-disable-next-line no-empty- } catch {}+ if (+ response.status >= 200 &&+ response.status < 300 &&+ // It's difficult to control status code at n8n side.+ // Data is easier to control, so we use data to determine success.+ json?.success === true+ ) {+ return { success: true };+ }- return { success: false, errors: [response.statusText || "Unknown error"] };+ return { success: false, errors: getErrors(json) ?? [text] };};diff --git a/packages/form-handlers/src/shared.ts b/packages/form-handlers/src/shared.tsindex da003ed89b..edd8120f21 100644--- a/packages/form-handlers/src/shared.ts+++ b/packages/form-handlers/src/shared.ts@@ -1,34 +1,101 @@-export type EmailContent = {- plainText: string;+export const formIdFieldName = "ws--form-id";++// Input data common for all handlers+export type FormInfo = {+ projectId: string;+ pageUrl: string;+ formData: FormData;+ toEmail: string;+ fromEmail: string;+};++export type EmailInfo = {+ from: string;+ to: string;+ txt: string;+ /** Only the body content, requers wrapping into `<!DOCTYPE html><html><body>...</body></html>` */html: string;subject: string;};-export const formDataToEmailContent = ({+export type Result = { success: true } | { success: false; errors: string[] };++export const getFormEntries = (formData: FormData) =>+ [...formData.entries()].filter(([key]) => key !== formIdFieldName);++export const getFormId = (formData: FormData) => {+ for (const [key, value] of formData.entries()) {+ if (key === formIdFieldName) {+ return value;+ }+ }+};++const getDomain = (url: string) => {+ try {+ return new URL(url).hostname;+ } catch {+ return;+ }+};++export const formToEmail = ({formData,- prefix = "There has been a new submission of your form:",- subject = "New form submission",-}: {- formData: FormData;- prefix?: string;- subject?: string;-}): EmailContent => {- const entries = [...formData.entries()];-- const htmlRows = entries- .map(- ([key, value]) =>- `<tr><td><strong>${key}:</strong></td><td>${value}</td></tr>`- )- .join("");-- const plainTextRows = entries- .map(([key, value]) => `${key}: ${value}`)- .join("\n");+ pageUrl,+ toEmail,+ fromEmail,+}: FormInfo): EmailInfo => {+ let html = `<p>There has been a new submission of your form at <a href="${pageUrl}">${pageUrl}</a>:</p>`;+ let txt = `There has been a new submission of your form at ${pageUrl}:\n\n`;++ html += "<table><tbody>";++ for (const [key, value] of getFormEntries(formData)) {+ html += `<tr><td><strong>${key}:</strong></td><td>${value}</td></tr>`;+ txt += `${key}: ${value}\n`;+ }++ html += "</tbody></table>";return {- subject,- plainText: `${prefix}\n\n${plainTextRows}`,- html: `<!DOCTYPE html><html><body><p>${prefix}</p><table><tbody>${htmlRows}</tbody></table></body></html>`,+ from: fromEmail,+ to: toEmail,+ subject: `New form submission from ${getDomain(pageUrl) ?? pageUrl}`,+ txt,+ html,};};++export const getResponseBody = async (+ response: Response+): Promise<{ text: string; json?: Record<string, unknown> }> => {+ const text = await response.text();+ try {+ const json = JSON.parse(text);+ return typeof json === "object" && json !== null+ ? { json, text }+ : { text };+ } catch {+ return { text: text === "" ? response.statusText : text };+ }+};++export const getErrors = (+ json: Record<string, unknown> | undefined+): string[] | undefined => {+ if (json === undefined) {+ return;+ }+ if (typeof json.error === "string") {+ return [json.error];+ }+ if (typeof json.message === "string") {+ return [json.message];+ }+ if (+ Array.isArray(json.errors) &&+ json.errors.every((error) => typeof error === "string")+ ) {+ return json.errors;+ }+};diff --git a/packages/react-sdk/package.json b/packages/react-sdk/package.jsonindex a9348de947..2445e396ab 100644--- a/packages/react-sdk/package.json+++ b/packages/react-sdk/package.json@@ -52,6 +52,7 @@"@webstudio-is/image": "workspace:^","@webstudio-is/prisma-client": "workspace:^","@webstudio-is/project-build": "workspace:^",+ "@webstudio-is/form-handlers": "workspace:^","detect-font": "^0.1.5","html-tags": "^3.2.0","nanoevents": "^7.0.1",diff --git a/packages/react-sdk/src/app/custom-components/__generated__/form.props.ts b/packages/react-sdk/src/app/custom-components/__generated__/form.props.tsindex 03c5eeb7e5..1eaca1ac73 100644--- a/packages/react-sdk/src/app/custom-components/__generated__/form.props.ts+++ b/packages/react-sdk/src/app/custom-components/__generated__/form.props.ts@@ -5,10 +5,8 @@ export const props: Record<string, PropMeta> = {style: { required: false, control: "text", type: "string" },title: { required: false, control: "text", type: "string" },acceptCharset: { required: false, control: "text", type: "string" },- action: { required: false, control: "text", type: "string" },autoComplete: { required: false, control: "text", type: "string" },encType: { required: false, control: "text", type: "string" },- method: { required: false, control: "text", type: "string" },name: { required: false, control: "text", type: "string" },noValidate: { required: false, control: "boolean", type: "boolean" },target: { required: false, control: "text", type: "string" },@@ -452,6 +450,7 @@ export const props: Record<string, PropMeta> = {required: false,control: "radio",type: "string",+ defaultValue: "initial",options: ["initial", "success", "error"],},};diff --git a/packages/react-sdk/src/app/custom-components/form.tsx b/packages/react-sdk/src/app/custom-components/form.tsxindex 7bebc10a05..5a9abed391 100644--- a/packages/react-sdk/src/app/custom-components/form.tsx+++ b/packages/react-sdk/src/app/custom-components/form.tsx@@ -1,3 +1,5 @@+import { useFetcher } from "@remix-run/react";+import { formIdFieldName } from "@webstudio-is/form-handlers";import {Children,cloneElement,@@ -6,6 +8,7 @@ import {type ElementRef,type ComponentProps,} from "react";+import { getInstanceIdFromComponentProps } from "../../props";export const defaultTag = "form";@@ -78,17 +81,31 @@ const withoutMessages = (children: ReactNode) =>export const Form = forwardRef<ElementRef<typeof defaultTag>,- ComponentProps<typeof defaultTag> & {+ Omit<ComponentProps<typeof defaultTag>, "method" | "action"> & {initialState?: "initial" | "success" | "error";}->(({ children, initialState = "initial", ...props }, ref) => (- <form {...props} data-state={initialState} ref={ref}>- {initialState === "success"- ? onlySuccessMessage(children)- : initialState === "error"- ? onlyErrorMessage(children)- : withoutMessages(children)}- </form>-));+>(({ children, initialState = "initial", ...props }, ref) => {+ const fetcher = useFetcher();++ const state =+ fetcher.type === "done"+ ? fetcher.data?.success === true+ ? "success"+ : "error"+ : initialState;++ const instanceId = getInstanceIdFromComponentProps(props);++ return (+ <fetcher.Form {...props} method="post" data-state={state} ref={ref}>+ <input type="hidden" name={formIdFieldName} value={instanceId} />+ {state === "success"+ ? onlySuccessMessage(children)+ : state === "error"+ ? onlyErrorMessage(children)+ : withoutMessages(children)}+ </fetcher.Form>+ );+});Form.displayName = "Form";diff --git a/packages/sdk-size-test/package.json b/packages/sdk-size-test/package.jsonindex 42e1b08f6a..e8e85d9467 100644--- a/packages/sdk-size-test/package.json+++ b/packages/sdk-size-test/package.json@@ -15,7 +15,7 @@},{"path": "functions/*.js",- "limit": "240 kB",+ "limit": "242 kB","gzip": false}],diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 406f9a1392..fb84f3c83d 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -1190,6 +1190,9 @@ importers:'@webstudio-is/fonts':specifier: workspace:^version: link:../fonts+ '@webstudio-is/form-handlers':+ specifier: workspace:^+ version: link:../form-handlers'@webstudio-is/generate-arg-types':specifier: workspace:^version: link:../generate-arg-types