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.

5.8 KB
Raw Blame
import {
  deleteAssetFoldersWithClient,
  patchAssetFoldersWithClient,
  patchAssets,
  loadAssetsByProjectWithClient,
  prepareAssetPatchWithClient,
  type AssetObjectReader,
} from "@webstudio-is/asset-uploader/server";
import type { Build, ProjectSettings } from "@webstudio-is/project-build";
import { parseConfig } from "@webstudio-is/project-build/persistence";
import { loadRawBuildById } from "@webstudio-is/project-build/server";
import type { Database } from "@webstudio-is/postgrest/index.server";
import type { AppContext } from "@webstudio-is/trpc-interface/index.server";
import type { Project } from "./project";
import { updatePreviewImage } from "./project";
import { validateProjectSettingsContactEmail } from "./project-settings-email";
import {
  createBuildPatchUpdate,
  singlePlayerVersionMismatchResult,
  type BuildPatchChange,
  type BuildPatchTransaction,
} from "./build-patch-core";

export type { BuildPatchChange, BuildPatchTransaction };

export type PatchBuildResult =
  | { status: "ok"; version: number }
  | { status: "version_mismatched"; errors: string }
  | { status: "error"; errors: string };

type PatchLoadedBuildResult =
  | {
      status: "ok";
      version: number;
      build: Database["public"]["Tables"]["Build"]["Row"];
    }
  | { status: "version_mismatched"; errors: string }
  | { status: "error"; errors: string };

export const patchLoadedBuild = async (
  {
    build,
    buildId,
    projectId,
    transactions,
    clientVersion,
    assetStore,
  }: {
    build: Database["public"]["Tables"]["Build"]["Row"];
    buildId: Build["id"];
    projectId: Project["id"];
    transactions: BuildPatchTransaction[];
    clientVersion: number;
    assetStore?: AssetObjectReader;
  },
  context: AppContext
): Promise<PatchLoadedBuildResult> => {
  const result = await createBuildPatchUpdate({
    build,
    clientVersion,
    transactions,
    loadAssets: async (ids, patches) => {
      const client = context.postgrest.client;
      if (patches.length === 0) {
        return {
          assets: await loadAssetsByProjectWithClient(projectId, client, ids),
          changedAssetIds: new Set(),
        };
      }
      const { assetsMap, canonicalAssets } = await prepareAssetPatchWithClient({
        projectId,
        client,
        patches,
      });
      const changedAssetIds = new Set<string>();
      for (const [id, asset] of canonicalAssets) {
        const previous = assetsMap.get(id);
        if (
          previous?.type !== asset.type ||
          previous?.format !== asset.format ||
          previous?.name !== asset.name
        ) {
          changedAssetIds.add(id);
        }
      }
      return { assets: [...canonicalAssets.values()], changedAssetIds };
    },
  });

  if (result.status !== "ok") {
    return result;
  }

  if (result.update === undefined) {
    return { status: "ok", version: result.nextVersion, build };
  }
  const buildUpdate = result.update;
  if (typeof buildUpdate.projectSettings === "string") {
    const nextSettings = parseConfig<ProjectSettings>(
      buildUpdate.projectSettings
    );
    const currentSettings = parseConfig<ProjectSettings>(build.projectSettings);
    const error = await validateProjectSettingsContactEmail({
      projectId,
      currentContactEmail: currentSettings.meta.contactEmail,
      nextContactEmail: nextSettings.meta.contactEmail,
      context,
    });
    if (error !== undefined) {
      return { status: "error", errors: error };
    }
  }
  if (result.assetPatches.length > 0 && assetStore === undefined) {
    throw new Error("Asset object storage is required to patch assets");
  }
  // build.patch does not have the worker's atomic Build+asset commit path.
  // Apply app-side asset mutations before marking the Build with
  // lastTransactionId so a failed asset mutation is not later treated as an
  // already-saved retry.
  const deletedAssetFolderIds =
    result.assetFolderPatches.length === 0
      ? []
      : await patchAssetFoldersWithClient(
          { projectId, client: context.postgrest.client },
          result.assetFolderPatches.flat(),
          { deferDeletes: true }
        );
  if (result.assetPatches.length > 0) {
    await patchAssets(
      { projectId, assetStore: assetStore! },
      result.assetPatches.flat(),
      context
    );
  }
  await deleteAssetFoldersWithClient(
    { projectId, ids: deletedAssetFolderIds },
    context.postgrest.client
  );

  const update = await context.postgrest.client
    .from("Build")
    .update(buildUpdate, { count: "exact" })
    .match({
      id: buildId,
      projectId,
      version: clientVersion,
    });

  if (update.error) {
    console.error(update.error);
    throw update.error;
  }
  if (update.count == null) {
    console.error("Update count is null");
    throw new Error("Update count is null");
  }

  if (update.count === 0) {
    return singlePlayerVersionMismatchResult;
  }

  if (result.previewImageAssetId !== undefined) {
    await updatePreviewImage(
      { assetId: result.previewImageAssetId, projectId },
      context
    );
  }

  return {
    status: "ok",
    version: result.nextVersion,
    build: { ...build, ...buildUpdate, version: result.nextVersion },
  };
};

export const patchBuild = async (
  {
    buildId,
    projectId,
    transactions,
    clientVersion,
    assetStore,
  }: {
    buildId: Build["id"];
    projectId: Project["id"];
    transactions: BuildPatchTransaction[];
    clientVersion: number;
    assetStore?: AssetObjectReader;
  },
  context: AppContext
): Promise<PatchBuildResult> => {
  const build = await loadRawBuildById(context, buildId);
  const result = await patchLoadedBuild(
    { build, buildId, projectId, transactions, clientVersion, assetStore },
    context
  );

  if (result.status !== "ok") {
    return result;
  }

  return { status: "ok", version: result.version };
};