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.

commit missing stuff

Andras Bacsaic4abecddf4ef
diff --git a/packages/project/src/db/breakpoints.ts b/packages/project/src/db/breakpoints.ts
new file mode 100644
index 0000000000..b8b7d2781a
--- /dev/null
+++ b/packages/project/src/db/breakpoints.ts
@@ -0,0 +1,82 @@
+import {
+ initialBreakpoints,
+ type Tree,
+ type Breakpoint,
+ BreakpointsSchema,
+} from "@webstudio-is/react-sdk";
+import ObjectId from "bson-objectid";
+import { applyPatches, type Patch } from "immer";
+import { prisma, Project } from "@webstudio-is/prisma-client";
+
+export const load = async (treeId?: Tree["id"]) => {
+ if (typeof treeId !== "string") {
+ throw new Error("Tree ID required");
+ }
+
+ const breakpoint = await prisma.breakpoints.findUnique({
+ where: { treeId },
+ });
+
+ if (breakpoint === null) {
+ throw new Error("Breakpoint not found");
+ }
+ const values: Array<Breakpoint> = JSON.parse(breakpoint.values);
+ BreakpointsSchema.parse(values);
+ return {
+ ...breakpoint,
+ values,
+ };
+};
+
+export const getBreakpointsWithId = () =>
+ initialBreakpoints.map((breakpoint) => ({
+ ...breakpoint,
+ id: ObjectId().toString(),
+ }));
+
+export const create = async (
+ treeId: Project["id"],
+ values: Array<Breakpoint>
+) => {
+ BreakpointsSchema.parse(values);
+
+ const data = {
+ treeId,
+ values: JSON.stringify(values),
+ };
+ await prisma.breakpoints.create({ data });
+ return {
+ ...data,
+ breakpoints: values,
+ };
+};
+
+export const clone = async ({
+ previousTreeId,
+ nextTreeId,
+}: {
+ previousTreeId: Tree["id"];
+ nextTreeId: Tree["id"];
+}) => {
+ const breakpoints = await load(previousTreeId);
+ if (breakpoints === null) {
+ throw new Error(`Didn't find breakpoints with tree id "${previousTreeId}"`);
+ }
+ await create(nextTreeId, breakpoints.values);
+};
+
+export const patch = async (
+ { treeId }: { treeId: Tree["id"]; projectId: Project["id"] },
+ patches: Array<Patch>
+) => {
+ const breakpoints = await load(treeId);
+ if (breakpoints === null) return;
+ const nextValues = applyPatches(breakpoints.values, patches);
+
+ BreakpointsSchema.parse(nextValues);
+
+ await prisma.breakpoints.update({
+ where: { treeId },
+ data: { values: JSON.stringify(nextValues) },
+ });
+};
diff --git a/packages/project/src/db/index.ts b/packages/project/src/db/index.ts
new file mode 100644
index 0000000000..3c3ad21e48
--- /dev/null
+++ b/packages/project/src/db/index.ts
@@ -0,0 +1,5 @@
+import * as project from "./project";
+import * as tree from "./tree";
+import * as props from "./props";
+import * as breakpoints from "./breakpoints";
+export { project, tree, breakpoints, props };
diff --git a/packages/project/src/db/project.ts b/packages/project/src/db/project.ts
new file mode 100644
index 0000000000..e67c58fc71
--- /dev/null
+++ b/packages/project/src/db/project.ts
@@ -0,0 +1,205 @@
+import slugify from "slugify";
+import { nanoid } from "nanoid";
+import { z } from "zod";
+import {
+ User,
+ prisma,
+ Prisma,
+ Project as BaseProject,
+} from "@webstudio-is/prisma-client";
+import { formatAsset } from "@webstudio-is/asset-uploader";
+import * as db from "./index";
+import type { Project } from "../index";
+const TreeHistorySchema = z.array(z.string());
+
+const parseProject = (project: BaseProject): Project => {
+ const prodTreeIdHistory = JSON.parse(project.prodTreeIdHistory);
+ return {
+ ...project,
+ prodTreeIdHistory: TreeHistorySchema.parse(prodTreeIdHistory),
+ assets: project?.assets?.map(formatAsset),
+ };
+};
+
+export const loadById = async (projectId?: Project["id"]) => {
+ if (typeof projectId !== "string") {
+ throw new Error("Project ID required");
+ }
+
+ const project = await prisma.project.findUnique({
+ where: { id: projectId },
+ include: {
+ assets: {
+ orderBy: {
+ createdAt: "desc",
+ },
+ },
+ },
+ });
+
+ if (!project) return null;
+ return parseProject(project);
+};
+
+export const loadByDomain = async (domain: string): Promise<Project | null> => {
+ const project = await prisma.project.findUnique({
+ where: { domain },
+ include: {
+ assets: {
+ orderBy: {
+ createdAt: "desc",
+ },
+ },
+ },
+ });
+ if (!project) return null;
+
+ return parseProject(project);
+};
+
+export const loadManyByUserId = async (
+ userId: User["id"]
+): Promise<Array<Project>> => {
+ const projects = await prisma.project.findMany({
+ where: {
+ user: {
+ id: userId,
+ },
+ },
+ });
+
+ return projects.map(parseProject) as Project[];
+};
+
+const slugifyOptions = { lower: true, strict: true };
+
+const MIN_DOMAIN_LENGTH = 10;
+const MIN_TITLE_LENGTH = 2;
+
+const generateDomain = (title: string) => {
+ const slugifiedTitle = slugify(title, slugifyOptions);
+ const domain = `${slugifiedTitle}-${nanoid(
+ // If user entered a long title already, we just add 5 chars generated id
+ // Otherwise we add the amount of chars to satisfy min length
+ Math.max(MIN_DOMAIN_LENGTH - slugifiedTitle.length - 1, 5)
+ )}`;
+ return domain;
+};
+
+export const create = async ({
+ userId,
+ title,
+}: {
+ userId: string;
+ title: string;
+}) => {
+ if (title.length < MIN_TITLE_LENGTH) {
+ throw new Error(`Minimum ${MIN_TITLE_LENGTH} characters required`);
+ }
+
+ const domain = generateDomain(title);
+ const breakpoints = db.breakpoints.getBreakpointsWithId();
+ const tree = await db.tree.create(db.tree.createRootInstance(breakpoints));
+ const project = await prisma.project.create({
+ data: {
+ userId,
+ title,
+ domain,
+ devTreeId: tree.id,
+ },
+ });
+
+ await db.breakpoints.create(tree.id, breakpoints);
+
+ return parseProject(project);
+};
+
+export const clone = async (clonableDomain: string, userId: string) => {
+ const clonableProject = await loadByDomain(clonableDomain);
+ if (clonableProject === null) {
+ throw new Error(`Not found project "${clonableDomain}"`);
+ }
+ if (clonableProject.prodTreeId === null) {
+ throw new Error("Expected project to be published first");
+ }
+
+ const tree = await db.tree.clone(clonableProject.prodTreeId);
+ const domain = generateDomain(clonableProject.title);
+ const [project] = await Promise.all([
+ prisma.project.create({
+ data: {
+ userId: userId,
+ title: clonableProject.title,
+ domain,
+ devTreeId: tree.id,
+ },
+ include: {
+ assets: {
+ orderBy: {
+ createdAt: "desc",
+ },
+ },
+ },
+ }),
+ db.props.clone({
+ previousTreeId: clonableProject.prodTreeId,
+ nextTreeId: tree.id,
+ }),
+ db.breakpoints.clone({
+ previousTreeId: clonableProject.prodTreeId,
+ nextTreeId: tree.id,
+ }),
+ ]);
+
+ const parsedProject = parseProject(project);
+ if (parsedProject === null) {
+ throw new Error(`Not found project "${clonableDomain}"`);
+ }
+ return parsedProject;
+};
+
+export const update = async ({
+ id,
+ ...data
+}: {
+ id: string;
+ domain?: string;
+ prodTreeId?: string;
+ devTreeId?: string;
+ prodTreeIdHistory: Array<string>;
+}) => {
+ if (data.domain) {
+ data.domain = slugify(data.domain, slugifyOptions);
+ if (data.domain.length < MIN_DOMAIN_LENGTH) {
+ throw new Error(`Minimum ${MIN_DOMAIN_LENGTH} characters required`);
+ }
+ }
+
+ TreeHistorySchema.parse(data.prodTreeIdHistory);
+
+ try {
+ const project = await prisma.project.update({
+ data: {
+ ...data,
+ prodTreeIdHistory: JSON.stringify(data.prodTreeIdHistory),
+ },
+ where: { id },
+ include: {
+ assets: {
+ orderBy: {
+ createdAt: "desc",
+ },
+ },
+ },
+ });
+ return project;
+ } catch (error) {
+ if (
+ error instanceof Prisma.PrismaClientKnownRequestError &&
+ error.code === "P2002"
+ ) {
+ throw new Error(`Domain "${data.domain}" is already used`);
+ }
+ throw error;
+ }
+};
diff --git a/packages/project/src/db/props.ts b/packages/project/src/db/props.ts
new file mode 100644
index 0000000000..4f9bf09d0e
--- /dev/null
+++ b/packages/project/src/db/props.ts
@@ -0,0 +1,98 @@
+import {
+ type Tree,
+ type AllUserProps,
+ UserPropsSchema,
+} from "@webstudio-is/react-sdk";
+import { applyPatches, type Patch } from "immer";
+import { prisma } from "@webstudio-is/prisma-client";
+import type { Project } from "./types";
+
+export const loadByProject = async (
+ project: Project | null,
+ env: "production" | "development" = "development"
+) => {
+ if (project === null) {
+ throw new Error("Project required");
+ }
+
+ const treeId = env === "production" ? project.prodTreeId : project.devTreeId;
+
+ if (treeId === null) {
+ throw new Error("Site needs to be published, production tree ID is null.");
+ }
+
+ return loadByTreeId(treeId);
+};
+
+export const loadByTreeId = async (treeId: Tree["id"]) => {
+ const instancePropsEntries = await prisma.instanceProps.findMany({
+ where: { treeId },
+ });
+
+ return instancePropsEntries.map((instanceProps) => {
+ const props = JSON.parse(instanceProps.props);
+ UserPropsSchema.parse(props);
+ return {
+ ...instanceProps,
+ props,
+ };
+ });
+};
+
+export const clone = async ({
+ previousTreeId,
+ nextTreeId,
+}: {
+ previousTreeId: string;
+ nextTreeId: string;
+}) => {
+ const props = await prisma.instanceProps.findMany({
+ where: { treeId: previousTreeId },
+ });
+ if (props.length === 0) return;
+ const data = props.map(({ id: _id, treeId: _treeId, ...rest }) => ({
+ ...rest,
+ treeId: nextTreeId,
+ }));
+
+ await prisma.$transaction(
+ data.map((prop) =>
+ prisma.instanceProps.create({
+ data: prop,
+ })
+ )
+ );
+};
+
+export const patch = async (
+ { treeId }: { treeId: Tree["id"]; projectId: Project["id"] },
+ patches: Array<Patch>
+) => {
+ const allProps = await loadByTreeId(treeId);
+
+ // We should get rid of this by applying patches on the client to the original
+ // model instead of the instanceId map.
+ // The map is handy for accessing props, but probably should be just cached interface, not the main data structure.
+ const allPropsMapByInstanceId = allProps.reduce((acc, prop) => {
+ acc[prop.instanceId] = prop;
+ return acc;
+ }, {} as AllUserProps);
+ const nextProps = applyPatches<AllUserProps>(
+ allPropsMapByInstanceId,
+ patches
+ );
+
+ await Promise.all(
+ Object.values(nextProps).map(({ id, instanceId, treeId, props }) => {
+ UserPropsSchema.parse(props);
+ const propsString = JSON.stringify(props);
+ return prisma.instanceProps.upsert({
+ where: { id: id },
+ create: { id: id, instanceId, treeId, props: propsString },
+ update: {
+ props: propsString,
+ },
+ });
+ })
+ );
+};
diff --git a/packages/project/src/db/tree.ts b/packages/project/src/db/tree.ts
new file mode 100644
index 0000000000..f7f5a48141
--- /dev/null
+++ b/packages/project/src/db/tree.ts
@@ -0,0 +1,85 @@
+import {
+ type Instance,
+ type Breakpoint,
+ type Tree,
+ InstanceSchema,
+} from "@webstudio-is/react-sdk";
+import { applyPatches, type Patch } from "immer";
+import { prisma } from "@webstudio-is/prisma-client";
+import { Tree as DbTree } from "@prisma/client";
+import type { Project } from "../index";
+import { utils } from "../index";
+
+export const createRootInstance = (breakpoints: Array<Breakpoint>) => {
+ // Take the smallest breakpoint as default
+ const defaultBreakpoint = utils.breakpoints.sort(breakpoints)[0];
+ if (defaultBreakpoint === undefined) {
+ throw new Error("A breakpoint with minWidth 0 is required");
+ }
+ const instance = utils.tree.createInstance({ component: "Body" });
+ return utils.tree.populateInstance(instance, defaultBreakpoint.id);
+};
+
+export const create = async (root: Instance): Promise<DbTree> => {
+ InstanceSchema.parse(root);
+ const rootString = JSON.stringify(root);
+ return await prisma.tree.create({
+ data: { root: rootString },
+ });
+};
+
+export const loadById = async (treeId: string): Promise<Tree | null> => {
+ const tree = await prisma.tree.findUnique({
+ where: { id: treeId },
+ });
+
+ if (tree === null) return null;
+
+ const root = JSON.parse(tree.root);
+ InstanceSchema.parse(root);
+ return {
+ ...tree,
+ root,
+ };
+};
+
+export const loadByProject = async (
+ project: Project | null,
+ env: "production" | "development" = "development"
+) => {
+ if (project === null) {
+ throw new Error("Project required");
+ }
+
+ const treeId = env === "production" ? project.prodTreeId : project.devTreeId;
+
+ if (treeId === null) {
+ throw new Error("Site needs to be published, production tree ID is null.");
+ }
+
+ return await loadById(treeId);
+};
+
+export const clone = async (treeId: string) => {
+ const tree = await loadById(treeId);
+ if (tree === null) {
+ throw new Error(`Tree ${treeId} not found`);
+ }
+ return await create(tree.root);
+};
+
+export const patchRoot = async (
+ { treeId }: { treeId: Tree["id"] },
+ patches: Array<Patch>
+) => {
+ const tree = await loadById(treeId);
+ if (tree === null) {
+ throw new Error(`Tree ${treeId} not found`);
+ }
+ const root = applyPatches(tree.root, patches);
+ InstanceSchema.parse(root);
+ await prisma.tree.update({
+ data: { root: JSON.stringify(root) },
+ where: { id: treeId },
+ });
+};
diff --git a/packages/project/src/db/types.ts b/packages/project/src/db/types.ts
new file mode 100644
index 0000000000..1dd7e6d83d
--- /dev/null
+++ b/packages/project/src/db/types.ts
@@ -0,0 +1,9 @@
+import { z } from "zod";
+import { Project as BaseProject } from "@webstudio-is/prisma-client";
+import type { Asset } from "@webstudio-is/asset-uploader";
+const TreeHistorySchema = z.array(z.string());
+
+export type Project = Omit<BaseProject, "prodTreeIdHistory" | "assets"> & {
+ prodTreeIdHistory: z.infer<typeof TreeHistorySchema>;
+ assets?: Array<Asset>;
+};