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.

72.6 KB
Raw Blame
import { describe, test, expect } from "vitest";
import { http, HttpResponse } from "msw";
import {
  createTestServer,
  db,
  json,
  empty,
  testContext,
} from "@webstudio-is/postgrest/testing";
import type { AppContext } from "@webstudio-is/trpc-interface/index.server";
import { createDefaultCollectionConfig } from "@webstudio-is/content-engine";
import {
  deleteAssetUploadReservationWithClient,
  deleteAssetsWithClient,
  loadAssetUploadReservationsByProjectWithClient,
  loadAssetsByProjectWithClient,
  patchAssetsWithClient,
  updateAssetFilenameIfCurrentWithClient,
  updateAssetMetadataWithClient,
} from "./asset-patch-core";
import { AssetRepositoryNotFoundError } from "./asset-repository-errors";
import {
  deleteAssetFoldersWithClient,
  loadAssetFoldersByProjectWithClient,
  patchAssetFoldersWithClient,
  upsertAssetFolderWithClient,
} from "./folder-persistence";
import { patchAssets } from "./patch";
import type { AssetObjectReader } from "./client";
import type { Patch } from "immer";

const server = createTestServer();

const uid = () => `proj-${Math.random().toString(36).slice(2)}`;

const createContext = (): AppContext =>
  ({
    ...testContext,
    authorization: { type: "user", userId: "user-1" },
    getOwnerPlanFeatures: async () => ({}),
  }) as unknown as AppContext;

const unusedAssetStore: AssetObjectReader = {
  readFile: async () => {
    throw new Error("Unexpected asset content read");
  },
};

const createSourceAssetStore = (
  sources: Readonly<Record<string, string>>
): AssetObjectReader => ({
  readFile: async (name, range) => {
    const source = sources[name];
    if (source === undefined) {
      throw new Error(`Unexpected asset content read: ${name}`);
    }
    const offset = range?.offset ?? 0;
    const data =
      range?.length === undefined
        ? source.slice(offset)
        : source.slice(offset, offset + range.length);
    return {
      data: new Blob([data]).stream(),
      contentLength: data.length,
    };
  },
});

/** hasProjectPermit: direct ownership check — returns a row for any project */
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 editorPermitHandlers = (projectId: string) => [
  db.get("Project", ({ request }) => {
    const url = new URL(request.url);
    return url.searchParams.has("userId")
      ? json(null)
      : json({ id: projectId, userId: "owner-1" });
  }),
  db.get("WorkspaceProjectAuthorization", () =>
    json([{ relation: "editors" }])
  ),
];

describe("asset folder persistence", () => {
  test("validates and upserts one REST folder mutation", async () => {
    const projectId = uid();
    const folder = {
      id: "blog",
      projectId,
      name: "Blog",
      createdAt: "2026-01-01T00:00:00.000Z",
    };
    server.use(
      db.get("AssetFolder", () => json([])),
      db.post("AssetFolder", async ({ request }) => {
        expect(await request.json()).toEqual([{ ...folder, parentId: null }]);
        return json({ ...folder, parentId: null });
      })
    );

    await expect(
      upsertAssetFolderWithClient(
        { projectId, folder },
        testContext.postgrest.client
      )
    ).resolves.toEqual(folder);
  });

  test("rejects a REST folder with a missing parent before persistence", async () => {
    const projectId = uid();
    server.use(db.get("AssetFolder", () => json([])));

    await expect(
      upsertAssetFolderWithClient(
        {
          projectId,
          folder: {
            id: "blog",
            projectId,
            name: "Blog",
            parentId: "missing",
            createdAt: "2026-01-01T00:00:00.000Z",
          },
        },
        testContext.postgrest.client
      )
    ).rejects.toThrow("Parent folder must exist");
  });

  test("serializes concurrent folder updates before validating cycles", async () => {
    const projectId = uid();
    const createdAt = "2026-01-01T00:00:00.000Z";
    let folders: Array<{
      id: string;
      projectId: string;
      name: string;
      parentId: string | null;
      createdAt: string;
    }> = [
      { id: "a", projectId, name: "A", parentId: null, createdAt },
      { id: "b", projectId, name: "B", parentId: null, createdAt },
    ];
    let readCount = 0;
    let writeCount = 0;
    let startFirstWrite = () => {};
    const firstWriteStarted = new Promise<void>((resolve) => {
      startFirstWrite = resolve;
    });
    let releaseFirstWrite = () => {};
    const firstWriteCanFinish = new Promise<void>((resolve) => {
      releaseFirstWrite = resolve;
    });
    server.use(
      db.get("AssetFolder", () => {
        readCount += 1;
        return json(folders);
      }),
      db.post("AssetFolder", async ({ request }) => {
        writeCount += 1;
        if (writeCount === 1) {
          startFirstWrite();
          await firstWriteCanFinish;
        }
        const [folder] = (await request.json()) as typeof folders;
        folders = folders.map((current) =>
          current.id === folder.id ? folder : current
        );
        return json(folder);
      })
    );

    const moveA = upsertAssetFolderWithClient(
      {
        projectId,
        folder: {
          id: "a",
          projectId,
          name: "A",
          parentId: "b",
          createdAt,
        },
      },
      testContext.postgrest.client
    );
    await firstWriteStarted;
    const moveB = upsertAssetFolderWithClient(
      {
        projectId,
        folder: {
          id: "b",
          projectId,
          name: "B",
          parentId: "a",
          createdAt,
        },
      },
      testContext.postgrest.client
    );

    await Promise.resolve();
    expect(readCount).toBe(1);
    releaseFirstWrite();

    await expect(moveA).resolves.toMatchObject({ id: "a", parentId: "b" });
    await expect(moveB).rejects.toThrow("Folders can't contain cycles");
    expect(readCount).toBe(3);
    expect(writeCount).toBe(1);
  });

  test("repairs persisted cycles when folders are loaded", async () => {
    const projectId = uid();
    const createdAt = "2026-01-01T00:00:00.000Z";
    let folders: Array<{
      id: string;
      projectId: string;
      name: string;
      parentId: string | null;
      createdAt: string;
    }> = [
      { id: "a", projectId, name: "A", parentId: "b", createdAt },
      { id: "b", projectId, name: "B", parentId: "a", createdAt },
    ];
    server.use(
      db.get("AssetFolder", () => json(folders)),
      db.patch("AssetFolder", async ({ request }) => {
        expect(await request.json()).toEqual({ parentId: null });
        folders = folders.map((folder) =>
          folder.id === "b" ? { ...folder, parentId: null } : folder
        );
        return json([{ id: "b" }]);
      })
    );

    await expect(
      loadAssetFoldersByProjectWithClient(
        projectId,
        testContext.postgrest.client,
        ["a"]
      )
    ).resolves.toEqual([
      { id: "a", projectId, name: "A", parentId: "b", createdAt },
    ]);
    await expect(
      loadAssetFoldersByProjectWithClient(
        projectId,
        testContext.postgrest.client
      )
    ).resolves.toEqual([
      { id: "a", projectId, name: "A", parentId: "b", createdAt },
      { id: "b", projectId, name: "B", createdAt },
    ]);
  });

  test("reloads a cycle repair that loses a concurrent update", async () => {
    const projectId = uid();
    const createdAt = "2026-01-01T00:00:00.000Z";
    let folders: Array<{
      id: string;
      projectId: string;
      name: string;
      parentId: string | null;
      createdAt: string;
    }> = [
      { id: "a", projectId, name: "A", parentId: "b", createdAt },
      { id: "b", projectId, name: "B", parentId: "a", createdAt },
    ];
    let readCount = 0;
    server.use(
      db.get("AssetFolder", () => {
        readCount += 1;
        return json(folders);
      }),
      db.patch("AssetFolder", () => {
        folders = folders.map((folder) =>
          folder.id === "b" ? { ...folder, parentId: null } : folder
        );
        return json([]);
      })
    );

    await expect(
      loadAssetFoldersByProjectWithClient(
        projectId,
        testContext.postgrest.client
      )
    ).resolves.toEqual([
      { id: "a", projectId, name: "A", parentId: "b", createdAt },
      { id: "b", projectId, name: "B", createdAt },
    ]);
    expect(readCount).toBe(2);
  });

  test("reverts a move when a concurrent server creates a cycle", async () => {
    const projectId = uid();
    const createdAt = "2026-01-01T00:00:00.000Z";
    let folders: Array<{
      id: string;
      projectId: string;
      name: string;
      parentId: string | null;
      createdAt: string;
    }> = [
      { id: "a", projectId, name: "A", parentId: null, createdAt },
      { id: "b", projectId, name: "B", parentId: null, createdAt },
    ];
    let rollbackCount = 0;
    server.use(
      db.get("AssetFolder", () => json(folders)),
      db.post("AssetFolder", async ({ request }) => {
        const [folder] = (await request.json()) as typeof folders;
        folders = folders.map((current) =>
          current.id === folder.id ? folder : current
        );
        folders = folders.map((current) =>
          current.id === "b" ? { ...current, parentId: "a" } : current
        );
        return json(folder);
      }),
      db.patch("AssetFolder", async ({ request }) => {
        rollbackCount += 1;
        const values = (await request.json()) as {
          name: string;
          parentId: string | null;
        };
        expect(values).toEqual({ name: "A", parentId: null });
        folders = folders.map((folder) =>
          folder.id === "a" ? { ...folder, ...values } : folder
        );
        return json([{ id: "a" }]);
      })
    );

    await expect(
      upsertAssetFolderWithClient(
        {
          projectId,
          folder: {
            id: "a",
            projectId,
            name: "A",
            parentId: "b",
            createdAt,
          },
        },
        testContext.postgrest.client
      )
    ).rejects.toThrow("conflicted with another move and was reverted");
    expect(rollbackCount).toBe(1);
    expect(folders).toEqual([
      { id: "a", projectId, name: "A", parentId: null, createdAt },
      { id: "b", projectId, name: "B", parentId: "a", createdAt },
    ]);
  });

  test("inserts parents before children", async () => {
    const projectId = uid();
    let inserted: Array<{ id: string }> = [];
    server.use(
      db.get("AssetFolder", () => json([])),
      db.post("AssetFolder", async ({ request }) => {
        expect(request.headers.get("prefer")).not.toContain(
          "resolution=merge-duplicates"
        );
        inserted = (await request.json()) as Array<{ id: string }>;
        return json(inserted);
      })
    );

    await patchAssetFoldersWithClient(
      { projectId, client: testContext.postgrest.client },
      [
        {
          op: "add",
          path: ["child"],
          value: {
            id: "child",
            projectId,
            name: "Child",
            parentId: "parent",
            createdAt: "2026-01-01T00:00:00.000Z",
          },
        },
        {
          op: "add",
          path: ["parent"],
          value: {
            id: "parent",
            projectId,
            name: "Parent",
            createdAt: "2026-01-01T00:00:00.000Z",
          },
        },
      ]
    );

    expect(inserted.map(({ id }) => id)).toEqual(["parent", "child"]);
  });

  test("does not turn an added folder into an update after a concurrent save", async () => {
    const projectId = uid();
    const folder = {
      id: "folder",
      projectId,
      name: "Original",
      createdAt: "2026-01-01T00:00:00.000Z",
    };
    let folders = [{ ...folder, parentId: null }];
    let writes = 0;
    server.use(
      db.get("AssetFolder", () => json(folders)),
      db.post("AssetFolder", async ({ request }) => {
        writes += 1;
        folders = (await request.json()) as typeof folders;
        return json(folders);
      })
    );

    await expect(
      patchAssetFoldersWithClient(
        { projectId, client: testContext.postgrest.client },
        [
          {
            op: "add",
            path: [folder.id],
            value: { ...folder, name: "Overwritten" },
          },
        ]
      )
    ).rejects.toThrow("A different asset folder already uses this identifier");
    expect(folders).toEqual([{ ...folder, parentId: null }]);
    expect(writes).toBe(0);

    await expect(
      patchAssetFoldersWithClient(
        { projectId, client: testContext.postgrest.client },
        [{ op: "add", path: [folder.id], value: folder }]
      )
    ).resolves.toEqual([]);
    expect(writes).toBe(0);
  });

  test("can defer folder deletion until assets are moved", async () => {
    const projectId = uid();
    let deleteCount = 0;
    server.use(
      db.get("AssetFolder", () =>
        json([
          {
            id: "folder",
            projectId,
            name: "Folder",
            parentId: null,
            createdAt: "2026-01-01T00:00:00.000Z",
          },
        ])
      ),
      db.delete("AssetFolder", () => {
        deleteCount += 1;
        return json([{ id: "folder" }]);
      })
    );

    const ids = await patchAssetFoldersWithClient(
      { projectId, client: testContext.postgrest.client },
      [{ op: "remove", path: ["folder"] }],
      { deferDeletes: true }
    );
    expect(ids).toEqual(["folder"]);
    expect(deleteCount).toBe(0);

    await deleteAssetFoldersWithClient(
      { projectId, ids },
      testContext.postgrest.client
    );
    expect(deleteCount).toBe(1);
  });

  test("persists moving a nested folder to root as null", async () => {
    const projectId = uid();
    let updatedParentId: unknown = "not-updated";
    server.use(
      db.get("AssetFolder", () =>
        json([
          {
            id: "parent",
            projectId,
            name: "Parent",
            parentId: null,
            createdAt: "2026-01-01T00:00:00.000Z",
          },
          {
            id: "child",
            projectId,
            name: "Child",
            parentId: "parent",
            createdAt: "2026-01-01T00:00:00.000Z",
          },
        ])
      ),
      db.post("AssetFolder", async ({ request }) => {
        const [update] = (await request.json()) as Array<{
          id: string;
          name: string;
          parentId: unknown;
        }>;
        updatedParentId = update.parentId;
        return json([update]);
      })
    );

    await patchAssetFoldersWithClient(
      { projectId, client: testContext.postgrest.client },
      [{ op: "remove", path: ["child", "parentId"] }]
    );
    expect(updatedParentId).toBeNull();
  });

  test("rejects folders that claim another project", async () => {
    const projectId = uid();
    server.use(db.get("AssetFolder", () => json([])));

    await expect(
      patchAssetFoldersWithClient(
        { projectId, client: testContext.postgrest.client },
        [
          {
            op: "add",
            path: ["folder"],
            value: {
              id: "folder",
              projectId: "another-project",
              name: "Folder",
              createdAt: "2026-01-01T00:00:00.000Z",
            },
          },
        ]
      )
    ).rejects.toThrow("belongs to another project");
  });

  test("persists the normalized folder name returned by validation", async () => {
    const projectId = uid();
    let insertedName: string | undefined;
    server.use(
      db.get("AssetFolder", () => json([])),
      db.post("AssetFolder", async ({ request }) => {
        const rows = (await request.json()) as Array<{ name: string }>;
        insertedName = rows[0]?.name;
        return json(rows);
      })
    );

    await patchAssetFoldersWithClient(
      { projectId, client: testContext.postgrest.client },
      [
        {
          op: "add",
          path: ["folder"],
          value: {
            id: "folder",
            projectId,
            name: "  Media  ",
            createdAt: "2026-01-01T00:00:00.000Z",
          },
        },
      ]
    );

    expect(insertedName).toBe("Media");
  });
});

const assetRow = {
  assetId: "asset-1",
  projectId: "proj-1",
  filename: "photo.jpg",
  description: null,
  file: {
    name: "photo.jpg",
    format: "jpg",
    description: null,
    size: 1000,
    createdAt: "2024-01-01T00:00:00.000Z",
    meta: JSON.stringify({ width: 100, height: 100 }),
    status: "UPLOADED",
  },
};

describe("asset patch persistence", () => {
  test("sync saves an existing entry revision while a required field still needs repair", async () => {
    const projectId = uid();
    const sources = {
      "config.json": createDefaultCollectionConfig(),
      "template.mdx": "---\ndraft: true\n---\n",
      "old.mdx": "---\nslug: post\n---\nOld body.\n",
      "new.mdx": "---\nslug: post\n---\nRepaired body.\n",
    };
    const row = (
      assetId: string,
      filename: string,
      name: keyof typeof sources
    ) => ({
      ...assetRow,
      assetId,
      projectId,
      filename,
      folderId: "posts",
      file: {
        ...assetRow.file,
        name,
        format: name.endsWith("json") ? "json" : "mdx",
        meta: "{}",
        size: sources[name].length,
        isDeleted: false,
      },
    });
    const nextFile = row("entry", "post", "new.mdx").file;
    let swapped = false;
    server.use(
      ownershipHandler,
      db.get("Asset", () =>
        json([
          row("config", "collection", "config.json"),
          row("template", "template", "template.mdx"),
          row("entry", "post", "old.mdx"),
        ])
      ),
      db.get("File", () => json([nextFile])),
      db.patch("File", () => json({ name: nextFile.name })),
      db.patch("Asset", () => {
        swapped = true;
        return json({ id: "entry" });
      }),
      http.post("http://test-postgrest/rpc/swap_asset_file", () =>
        HttpResponse.json("invalid_revision")
      )
    );
    await expect(
      patchAssets(
        { projectId, assetStore: createSourceAssetStore(sources) },
        [{ op: "replace", path: ["entry", "name"], value: "new.mdx" }],
        createContext()
      )
    ).resolves.toBeUndefined();
    expect(swapped).toBe(true);
  });

  test("loads only requested assets", async () => {
    const projectId = uid();
    let idFilter: string | null = null;
    server.use(
      db.get("Asset", ({ request }) => {
        idFilter = new URL(request.url).searchParams.get("id");
        return json([{ ...assetRow, projectId }]);
      })
    );

    await expect(
      loadAssetsByProjectWithClient(projectId, testContext.postgrest.client, [
        "asset-1",
      ])
    ).resolves.toEqual([expect.objectContaining({ id: "asset-1" })]);
    expect(idFilter).toBe("in.(asset-1)");
  });

  test("does not query when no asset ids are requested", async () => {
    const projectId = uid();
    let requestCount = 0;
    server.use(
      db.get("Asset", () => {
        requestCount += 1;
        return json([]);
      })
    );

    await expect(
      loadAssetsByProjectWithClient(projectId, testContext.postgrest.client, [])
    ).resolves.toEqual([]);
    expect(requestCount).toBe(0);
  });

  test("loads incomplete upload reservations for conflict checks", async () => {
    const projectId = uid();
    server.use(
      db.get("Asset", ({ request }) => {
        const url = new URL(request.url);
        expect(url.searchParams.get("projectId")).toBe(`eq.${projectId}`);
        expect(url.searchParams.has("file.status")).toBe(false);
        return json([
          {
            id: "uploading-entry",
            projectId,
            filename: "hello-world",
            folderId: "posts",
            file: {
              name: "uploading-entry.mdx",
              status: "UPLOADING",
              isDeleted: false,
              createdAt: "2026-09-03T12:00:00.000Z",
              updatedAt: "2026-09-03T12:00:00.000Z",
            },
          },
          {
            id: "stale-entry",
            projectId,
            filename: "hello-world",
            folderId: "posts",
            file: {
              name: "stale-entry.mdx",
              status: "UPLOADING",
              isDeleted: false,
              createdAt: "2026-09-03T10:00:00.000Z",
              updatedAt: "2026-09-03T10:00:00.000Z",
            },
          },
        ]);
      })
    );

    await expect(
      loadAssetUploadReservationsByProjectWithClient(
        projectId,
        testContext.postgrest.client,
        new Date("2026-09-03T12:15:00.000Z")
      )
    ).resolves.toEqual([
      {
        id: "uploading-entry",
        name: "uploading-entry.mdx",
        filename: "hello-world",
        folderId: "posts",
        createdAt: "2026-09-03T12:00:00.000Z",
        status: "UPLOADING",
      },
    ]);
  });

  test("does not delete a file when the exact upload reservation is missing", async () => {
    const projectId = uid();
    let deletedFile = false;
    server.use(
      db.delete("Asset", () => json(null)),
      db.delete("File", () => {
        deletedFile = true;
        return empty({ status: 204 });
      })
    );

    await deleteAssetUploadReservationWithClient(
      { projectId, assetId: "missing", name: "reservation.mdx" },
      testContext.postgrest.client
    );

    expect(deletedFile).toBe(false);
  });

  test("chunks large requested asset id filters", async () => {
    const projectId = uid();
    const idFilters: string[] = [];
    server.use(
      db.get("Asset", ({ request }) => {
        const idFilter = new URL(request.url).searchParams.get("id");
        if (idFilter !== null) {
          idFilters.push(idFilter);
        }
        return json([]);
      })
    );
    const assetIds = Array.from(
      { length: 201 },
      (_, index) => `asset-${String(index).padStart(3, "0")}`
    );

    await expect(
      loadAssetsByProjectWithClient(
        projectId,
        testContext.postgrest.client,
        assetIds
      )
    ).resolves.toEqual([]);

    expect(idFilters).toHaveLength(3);
    const filteredIds = idFilters.flatMap((filter) =>
      filter.slice("in.(".length, -1).split(",")
    );
    expect(filteredIds).toEqual(assetIds);
    expect(
      idFilters.every(
        (filter) => filter.slice("in.(".length, -1).split(",").length <= 100
      )
    ).toBe(true);
  });

  test("rejects assets that are patched into another project", async () => {
    const projectId = uid();
    server.use(db.get("Asset", () => json([{ ...assetRow, projectId }])));

    await expect(
      patchAssetsWithClient(
        { projectId, client: testContext.postgrest.client },
        [
          {
            op: "replace",
            path: ["asset-1", "projectId"],
            value: "another-project",
          },
        ]
      )
    ).rejects.toThrow("belongs to another project");
  });

  test("preserves mutable file metadata in the validation snapshot", async () => {
    const projectId = uid();
    const fontRow = {
      ...assetRow,
      projectId,
      file: {
        ...assetRow.file,
        name: "font.woff2",
        format: "woff2",
        meta: JSON.stringify({
          family: "Inter",
          style: "normal",
          weight: 400,
        }),
      },
    };
    const nextMeta = {
      family: "Inter",
      style: "normal" as const,
      weight: 600,
    };
    let validatedMeta: unknown;
    server.use(
      db.get("Asset", () => json([fontRow])),
      db.patch("File", () => json({ meta: JSON.stringify(nextMeta) }))
    );

    await patchAssetsWithClient(
      { projectId, client: testContext.postgrest.client },
      [{ op: "replace", path: ["asset-1", "meta"], value: nextMeta }],
      {
        validate: async ({ next }) => {
          validatedMeta = next.get("asset-1")?.meta;
        },
      }
    );

    expect(validatedMeta).toEqual(nextMeta);
  });

  test("rejects invalid font metadata before persisting a raw asset patch", async () => {
    const projectId = uid();
    const fontRow = {
      ...assetRow,
      projectId,
      file: {
        ...assetRow.file,
        name: "font.woff2",
        format: "woff2",
        meta: JSON.stringify({
          family: "Inter",
          style: "normal",
          weight: 400,
        }),
      },
    };
    let persisted = false;
    server.use(
      db.get("Asset", () => json([fontRow])),
      db.patch("File", () => {
        persisted = true;
        return json({ meta: "{}" });
      })
    );

    await expect(
      patchAssetsWithClient(
        { projectId, client: testContext.postgrest.client },
        [
          {
            op: "replace",
            path: ["asset-1", "meta"],
            value: { family: "Inter", style: "normal" },
          },
        ]
      )
    ).rejects.toThrow();
    expect(persisted).toBe(false);
  });

  test("updates only supplied metadata and reloads only that asset", async () => {
    const projectId = uid();
    let update: unknown;
    let readIdFilter: string | null = null;
    server.use(
      db.patch("Asset", async ({ request }) => {
        update = await request.json();
        return json({ id: "asset-1" });
      }),
      db.get("Asset", ({ request }) => {
        readIdFilter = new URL(request.url).searchParams.get("id");
        return json([{ ...assetRow, projectId, description: null }]);
      })
    );

    await expect(
      updateAssetMetadataWithClient(
        {
          projectId,
          assetId: "asset-1",
          values: { description: null },
        },
        testContext.postgrest.client
      )
    ).resolves.toEqual(
      expect.objectContaining({ id: "asset-1", description: undefined })
    );
    expect(update).toEqual({ description: null });
    expect(readIdFilter).toBe("in.(asset-1)");
  });

  test("updates an asset filename only when the expected value is current", async () => {
    const projectId = uid();
    let updatedFilename: unknown;
    let expectedFilenameFilter: string | null = null;
    server.use(
      db.patch("Asset", async ({ request }) => {
        const url = new URL(request.url);
        expectedFilenameFilter = url.searchParams.get("filename");
        updatedFilename = ((await request.json()) as { filename?: unknown })
          .filename;
        return json({ id: "asset-1" });
      }),
      db.get("Asset", () =>
        json([{ ...assetRow, projectId, filename: "post-template" }])
      )
    );

    await expect(
      updateAssetFilenameIfCurrentWithClient(
        {
          projectId,
          assetId: "asset-1",
          expectedFilename: "template",
          filename: "post-template",
        },
        testContext.postgrest.client
      )
    ).resolves.toEqual(
      expect.objectContaining({ id: "asset-1", filename: "post-template" })
    );
    expect(expectedFilenameFilter).toBe("eq.template");
    expect(updatedFilename).toBe("post-template");
  });

  test("reports when a conditional filename update loses a race", async () => {
    const projectId = uid();
    let reloaded = false;
    server.use(
      db.patch("Asset", ({ request }) => {
        expect(new URL(request.url).searchParams.get("filename")).toBe(
          "is.null"
        );
        return json(null);
      }),
      db.get("Asset", () => {
        reloaded = true;
        return json([]);
      })
    );

    await expect(
      updateAssetFilenameIfCurrentWithClient(
        {
          projectId,
          assetId: "asset-1",
          expectedFilename: undefined,
          filename: "post-template",
        },
        testContext.postgrest.client
      )
    ).resolves.toBeUndefined();
    expect(reloaded).toBe(false);
  });

  test("reports a missing metadata update as a repository not-found error", async () => {
    const projectId = uid();
    server.use(db.patch("Asset", () => json(null)));

    await expect(
      updateAssetMetadataWithClient(
        {
          projectId,
          assetId: "missing",
          values: { description: "Missing" },
        },
        testContext.postgrest.client
      )
    ).rejects.toBeInstanceOf(AssetRepositoryNotFoundError);
  });

  test("reports a missing deletion as a repository not-found error", async () => {
    const projectId = uid();
    server.use(db.get("Asset", () => json([])));

    await expect(
      deleteAssetsWithClient(
        { projectId, ids: ["missing"] },
        testContext.postgrest.client
      )
    ).rejects.toBeInstanceOf(AssetRepositoryNotFoundError);
  });
});

describe("patchAssets (msw)", () => {
  test("throws when caller lacks edit access", async () => {
    const projectId = uid();
    server.use(
      db.get("Project", () => json(null)),
      db.get("WorkspaceProjectAuthorization", () => json([]))
    );

    await expect(
      patchAssets(
        { projectId, assetStore: unusedAssetStore },
        [],
        createContext()
      )
    ).rejects.toThrow("You don't have edit access");
  });

  test("no-op when patches are empty and no assets exist", async () => {
    const projectId = uid();
    server.use(
      ownershipHandler,
      db.get("Asset", () => json([]))
    );

    // Should complete without throwing
    await patchAssets(
      { projectId, assetStore: unusedAssetStore },
      [],
      createContext()
    );
  });

  test("updates asset description via patch", async () => {
    const projectId = uid();
    let localAssetRow: Omit<typeof assetRow, "description"> & {
      description: string | null;
    } = { ...assetRow, projectId };
    let updatedDescription: string | undefined;

    server.use(
      ownershipHandler,
      db.get("Asset", () => json([localAssetRow])),
      db.patch("Asset", async ({ request }) => {
        const body = (await request.json()) as { description?: string };
        updatedDescription = body.description ?? undefined;
        localAssetRow = {
          ...localAssetRow,
          description: body.description ?? localAssetRow.description,
        };
        return json({
          id: localAssetRow.assetId,
          filename: localAssetRow.filename,
          description: localAssetRow.description,
        });
      })
    );

    const patches: Patch[] = [
      {
        op: "replace",
        path: ["asset-1", "description"],
        value: "New description",
      },
    ];

    await patchAssets(
      { projectId, assetStore: unusedAssetStore },
      patches,
      createContext()
    );
    expect(updatedDescription).toBe("New description");
  });

  test("requires build access to patch collection configuration assets", async () => {
    const projectId = uid();
    const configSource = createDefaultCollectionConfig();
    const templateSource = "---\ndraft: true\n---\n\nStart writing.\n";
    const configRow = {
      ...assetRow,
      assetId: "config",
      projectId,
      filename: "collection",
      folderId: "posts",
      file: {
        ...assetRow.file,
        name: "config-storage.json",
        format: "json",
        size: configSource.length,
      },
    };
    const templateRow = {
      ...assetRow,
      assetId: "template",
      projectId,
      filename: "template",
      folderId: "posts",
      file: {
        ...assetRow.file,
        name: "template-storage.mdx",
        format: "mdx",
        size: templateSource.length,
      },
    };
    let metadataUpdated = false;
    server.use(
      db.get("Project", ({ request }) => {
        const url = new URL(request.url);
        return url.searchParams.has("userId")
          ? json(null)
          : json({ id: projectId, userId: "owner-1" });
      }),
      db.get("WorkspaceProjectAuthorization", () =>
        json([{ relation: "editors" }])
      ),
      db.get("Asset", () => json([configRow, templateRow])),
      db.patch("Asset", () => {
        metadataUpdated = true;
        return json({ id: "template" });
      })
    );

    await expect(
      patchAssets(
        {
          projectId,
          assetStore: createSourceAssetStore({
            [configRow.file.name]: configSource,
            [templateRow.file.name]: templateSource,
          }),
        },
        [
          {
            op: "replace",
            path: ["template", "description"],
            value: "Reserved",
          },
        ],
        createContext()
      )
    ).rejects.toThrow("permission to configure");
    expect(metadataUpdated).toBe(false);
  });

  test("rejects mismatched asset map keys before collection authorization", async () => {
    const projectId = uid();
    const configSource = createDefaultCollectionConfig();
    const templateSource = "---\ndraft: true\n---\n\nStart writing.\n";
    const configFile = {
      ...assetRow.file,
      name: "config-storage.json",
      format: "json",
      size: configSource.length,
      meta: "{}",
      updatedAt: "2026-09-03T00:00:00.000Z",
      isDeleted: true,
    };
    const templateRow = {
      ...assetRow,
      assetId: "template",
      projectId,
      filename: "template",
      folderId: "posts",
      file: {
        ...assetRow.file,
        name: "template-storage.mdx",
        format: "mdx",
        size: templateSource.length,
        meta: "{}",
      },
    };
    let inserted = false;
    server.use(
      ...editorPermitHandlers(projectId),
      db.get("Asset", () => json([templateRow])),
      db.get("File", () => json([configFile])),
      db.patch("File", () => empty({ status: 204 })),
      db.post("Asset", () => {
        inserted = true;
        return empty({ status: 201 });
      })
    );

    await expect(
      patchAssets(
        {
          projectId,
          assetStore: createSourceAssetStore({
            [configFile.name]: configSource,
            [templateRow.file.name]: templateSource,
          }),
        },
        [
          {
            op: "add",
            path: ["forged-map-key"],
            value: {
              id: "config",
              projectId,
              name: configFile.name,
              filename: "collection",
              folderId: "posts",
              type: "file",
              format: "json",
              size: configSource.length,
              description: null,
              createdAt: configFile.createdAt,
              meta: {},
            },
          },
        ],
        createContext()
      )
    ).rejects.toThrow("does not match its map key");
    expect(inserted).toBe(false);
  });

  test("validates collection moves with authoritative file metadata", async () => {
    const projectId = uid();
    const schema = JSON.parse(createDefaultCollectionConfig());
    schema["x-webstudio"].entries = ["*"];
    const configSource = JSON.stringify(schema);
    const templateSource = "---\ndraft: true\n---\n\nStart writing.\n";
    const entrySource =
      "---\ntitle: Hello world\nslug: hello-world\ndraft: true\n---\n\nBody.\n";
    const configRow = {
      ...assetRow,
      assetId: "config",
      projectId,
      filename: "collection",
      folderId: "posts",
      file: {
        ...assetRow.file,
        name: "config-storage.json",
        format: "json",
        size: configSource.length,
        meta: "{}",
      },
    };
    const templateRow = {
      ...assetRow,
      assetId: "template",
      projectId,
      filename: "template",
      folderId: "posts",
      file: {
        ...assetRow.file,
        name: "template-storage.mdx",
        format: "mdx",
        size: templateSource.length,
        meta: "{}",
      },
    };
    const textEntryRow = {
      ...assetRow,
      assetId: "entry",
      projectId,
      filename: "hello-world",
      folderId: null,
      file: {
        ...assetRow.file,
        name: "entry-storage.txt",
        format: "txt",
        size: entrySource.length,
        meta: "{}",
      },
    };
    let metadataUpdated = false;
    server.use(
      ownershipHandler,
      db.get("Asset", () => json([configRow, templateRow, textEntryRow])),
      db.patch("Asset", () => {
        metadataUpdated = true;
        return json({ id: "entry" });
      })
    );

    await expect(
      patchAssets(
        {
          projectId,
          assetStore: createSourceAssetStore({
            [configRow.file.name]: configSource,
            [templateRow.file.name]: templateSource,
            [textEntryRow.file.name]: entrySource,
          }),
        },
        [
          { op: "replace", path: ["entry", "format"], value: "mdx" },
          { op: "add", path: ["entry", "folderId"], value: "posts" },
        ],
        createContext()
      )
    ).rejects.toThrow('Collection entry "hello-world.txt" must be an MDX file');
    expect(metadataUpdated).toBe(false);
  });

  test("restores a valid collection entry through a sync patch", async () => {
    const projectId = uid();
    const configSource = createDefaultCollectionConfig();
    const templateSource = "---\ndraft: true\n---\n\nStart writing.\n";
    const entrySource =
      "---\ntitle: Hello world\nslug: hello-world\ndraft: true\n---\n\nBody.\n";
    const configRow = {
      ...assetRow,
      assetId: "config",
      projectId,
      filename: "collection",
      folderId: "posts",
      file: {
        ...assetRow.file,
        name: "config-storage.json",
        format: "json",
        size: configSource.length,
      },
    };
    const templateRow = {
      ...assetRow,
      assetId: "template",
      projectId,
      filename: "template",
      folderId: "posts",
      file: {
        ...assetRow.file,
        name: "template-storage.mdx",
        format: "mdx",
        size: templateSource.length,
      },
    };
    const entryFile = {
      ...assetRow.file,
      name: "entry-storage.mdx",
      format: "mdx",
      size: entrySource.length,
      meta: "{}",
      updatedAt: "2026-09-03T00:00:00.000Z",
    };
    const invalidEntryFile = {
      ...entryFile,
      name: "invalid-entry-storage.mdx",
    };
    let inserted = false;
    const entryPatch: Patch[] = [
      {
        op: "add",
        path: ["entry"],
        value: {
          id: "entry",
          projectId,
          name: "entry-storage.mdx",
          filename: "hello-world",
          folderId: "posts",
          type: "file",
          format: "mdx",
          size: entrySource.length,
          description: null,
          createdAt: "2026-09-03T00:00:00.000Z",
          meta: {},
        },
      },
    ];
    const invalidEntryPatch: Patch[] = [
      {
        op: "add",
        path: ["invalid-entry"],
        value: {
          id: "invalid-entry",
          projectId,
          name: "invalid-entry-storage.mdx",
          filename: "different-slug",
          folderId: "posts",
          type: "file",
          format: "mdx",
          size: entrySource.length,
          description: null,
          createdAt: "2026-09-03T00:00:00.000Z",
          meta: {},
        },
      },
    ];
    server.use(
      ...editorPermitHandlers(projectId),
      db.get("Asset", () => json([configRow, templateRow])),
      db.get("File", ({ request }) => {
        const url = new URL(request.url);
        expect(url.searchParams.get("status")).toBe("eq.UPLOADED");
        const filter = url.searchParams.get("name") ?? "";
        return json(
          [entryFile, invalidEntryFile].filter(({ name }) =>
            filter.includes(name)
          )
        );
      }),
      db.patch("File", () => empty({ status: 204 })),
      db.post("Asset", () => {
        inserted = true;
        return empty({ status: 201 });
      })
    );

    await expect(
      patchAssets(
        {
          projectId,
          assetStore: createSourceAssetStore({
            [configRow.file.name]: configSource,
            [templateRow.file.name]: templateSource,
            "entry-storage.mdx": entrySource,
            "invalid-entry-storage.mdx": entrySource,
          }),
        },
        invalidEntryPatch,
        createContext()
      )
    ).rejects.toThrow("slug must match the entry filename");
    expect(inserted).toBe(false);

    await expect(
      patchAssets(
        {
          projectId,
          assetStore: createSourceAssetStore({
            [configRow.file.name]: configSource,
            [templateRow.file.name]: templateSource,
            "entry-storage.mdx": entrySource,
          }),
        },
        entryPatch,
        createContext()
      )
    ).resolves.toBeUndefined();
    expect(inserted).toBe(true);
  });

  test("moves a valid entry back into its collection through a sync patch", async () => {
    const projectId = uid();
    const configSource = createDefaultCollectionConfig();
    const templateSource = "---\ndraft: true\n---\n\nStart writing.\n";
    const entrySource =
      "---\ntitle: Hello world\nslug: hello-world\ndraft: true\n---\n\nBody.\n";
    const configRow = {
      ...assetRow,
      assetId: "config",
      projectId,
      filename: "collection",
      folderId: "posts",
      file: {
        ...assetRow.file,
        name: "config-storage.json",
        format: "json",
        size: configSource.length,
      },
    };
    const templateRow = {
      ...assetRow,
      assetId: "template",
      projectId,
      filename: "template",
      folderId: "posts",
      file: {
        ...assetRow.file,
        name: "template-storage.mdx",
        format: "mdx",
        size: templateSource.length,
      },
    };
    const entryRow = {
      ...assetRow,
      assetId: "entry",
      projectId,
      filename: "hello-world",
      folderId: null,
      file: {
        ...assetRow.file,
        name: "entry-storage.mdx",
        format: "mdx",
        size: entrySource.length,
      },
    };
    let folderId: unknown;
    server.use(
      ...editorPermitHandlers(projectId),
      db.get("Asset", () => json([configRow, templateRow, entryRow])),
      db.patch("Asset", async ({ request }) => {
        folderId = ((await request.json()) as { folderId: unknown }).folderId;
        return json({ id: "entry" });
      })
    );

    await expect(
      patchAssets(
        {
          projectId,
          assetStore: createSourceAssetStore({
            [configRow.file.name]: configSource,
            [templateRow.file.name]: templateSource,
            [entryRow.file.name]: entrySource,
          }),
        },
        [{ op: "add", path: ["entry", "folderId"], value: "posts" }],
        createContext()
      )
    ).resolves.toBeUndefined();
    expect(folderId).toBe("posts");
  });

  test("allows invalid collection entries to be repaired one at a time", async () => {
    const projectId = uid();
    const configSource = createDefaultCollectionConfig();
    const templateSource = "---\ndraft: true\n---\n\nStart writing.\n";
    const invalidEntrySource = "---\nslug: missing-title\ndraft: true\n---\n";
    const configRow = {
      ...assetRow,
      assetId: "config",
      projectId,
      filename: "collection",
      folderId: "posts",
      file: {
        ...assetRow.file,
        name: "config-storage.json",
        format: "json",
        size: configSource.length,
      },
    };
    const templateRow = {
      ...assetRow,
      assetId: "template",
      projectId,
      filename: "template",
      folderId: "posts",
      file: {
        ...assetRow.file,
        name: "template-storage.mdx",
        format: "mdx",
        size: templateSource.length,
      },
    };
    const firstEntryRow = {
      ...assetRow,
      assetId: "first-entry",
      projectId,
      filename: "missing-title",
      folderId: "posts",
      file: {
        ...assetRow.file,
        name: "first-entry-storage.mdx",
        format: "mdx",
        size: invalidEntrySource.length,
      },
    };
    const secondEntryRow = {
      ...assetRow,
      assetId: "second-entry",
      projectId,
      filename: "also-missing-title",
      folderId: "posts",
      file: {
        ...assetRow.file,
        name: "second-entry-storage.mdx",
        format: "mdx",
        size: invalidEntrySource.length,
      },
    };
    let updatedFolderId: unknown = "not-updated";
    server.use(
      ownershipHandler,
      db.get("Asset", () =>
        json([configRow, templateRow, firstEntryRow, secondEntryRow])
      ),
      db.patch("Asset", async ({ request }) => {
        updatedFolderId = ((await request.json()) as { folderId: unknown })
          .folderId;
        return json({ id: "first-entry", folderId: null });
      })
    );

    await expect(
      patchAssets(
        {
          projectId,
          assetStore: createSourceAssetStore({
            [configRow.file.name]: configSource,
            [templateRow.file.name]: templateSource,
            [firstEntryRow.file.name]: invalidEntrySource,
            [secondEntryRow.file.name]: invalidEntrySource,
          }),
        },
        [{ op: "remove", path: ["first-entry", "folderId"] }],
        createContext()
      )
    ).resolves.toBeUndefined();
    expect(updatedFolderId).toBeNull();
  });

  test("renames supporting assets without validating unchanged entry content", async () => {
    const projectId = uid();
    const configSource = createDefaultCollectionConfig();
    const templateSource = "---\ndraft: true\n---\n";
    const row = (
      id: string,
      filename: string,
      format: string,
      source: string
    ) => ({
      ...assetRow,
      assetId: id,
      projectId,
      filename,
      folderId: "posts",
      file: {
        ...assetRow.file,
        name: `${id}.${format}`,
        format,
        size: source.length,
      },
    });
    const rows = [
      row("config", "collection", "json", configSource),
      row("template", "template", "mdx", templateSource),
      row("invalid", "invalid", "mdx", "missing frontmatter"),
      row("notes", "notes", "txt", "notes"),
    ];
    let filename: unknown;
    server.use(
      ownershipHandler,
      db.get("Asset", () => json(rows)),
      db.patch("Asset", async ({ request }) => {
        filename = ((await request.json()) as { filename: unknown }).filename;
        return json({ id: "notes" });
      })
    );
    const assetStore = createSourceAssetStore({
      "config.json": configSource,
      "template.mdx": templateSource,
      // Neither ordinary content nor unchanged entries should be read.
    });
    await patchAssets(
      { projectId, assetStore },
      [{ op: "replace", path: ["notes", "filename"], value: "renamed" }],
      createContext()
    );
    expect(filename).toBe("renamed");
    await expect(
      patchAssets(
        { projectId, assetStore },
        [
          {
            op: "replace",
            path: ["invalid", "filename"],
            value: "changed-entry",
          },
        ],
        createContext()
      )
    ).rejects.toThrow();
  });

  test("validates collection rules before persisting an asset patch", async () => {
    const projectId = uid();
    const schema = JSON.parse(createDefaultCollectionConfig());
    schema["x-webstudio"].entries = ["*"];
    const configSource = JSON.stringify(schema);
    const templateSource = "---\ndraft: true\n---\n\nStart writing.\n";
    const configRow = {
      ...assetRow,
      assetId: "config",
      projectId,
      filename: "collection",
      folderId: "posts",
      file: {
        ...assetRow.file,
        name: "config-storage.json",
        format: "json",
        size: configSource.length,
      },
    };
    const templateRow = {
      ...assetRow,
      assetId: "template",
      projectId,
      filename: "template",
      folderId: "posts",
      file: {
        ...assetRow.file,
        name: "template-storage.mdx",
        format: "mdx",
        size: templateSource.length,
      },
    };
    let inserted = false;
    server.use(
      ownershipHandler,
      db.get("Asset", () => json([])),
      db.get("File", () =>
        json([
          {
            ...configRow.file,
            meta: "{}",
            updatedAt: "2026-09-03T00:00:00.000Z",
          },
          {
            ...templateRow.file,
            meta: "{}",
            updatedAt: "2026-09-03T00:00:00.000Z",
          },
          {
            ...assetRow.file,
            name: "notes.txt",
            format: "txt",
            size: 5,
            meta: "{}",
            updatedAt: "2026-09-03T00:00:00.000Z",
          },
        ])
      ),
      db.post("Asset", () => {
        inserted = true;
        return empty({ status: 201 });
      })
    );

    await expect(
      patchAssets(
        {
          projectId,
          assetStore: createSourceAssetStore({
            [configRow.file.name]: configSource,
            [templateRow.file.name]: templateSource,
          }),
        },
        [
          {
            op: "add",
            path: ["config"],
            value: {
              id: "config",
              projectId,
              name: configRow.file.name,
              filename: "collection",
              folderId: "posts",
              type: "file",
              format: "json",
              size: configSource.length,
              description: null,
              createdAt: "2026-09-03T00:00:00.000Z",
              meta: {},
            },
          },
          {
            op: "add",
            path: ["template"],
            value: {
              id: "template",
              projectId,
              name: templateRow.file.name,
              filename: "template",
              folderId: "posts",
              type: "file",
              format: "mdx",
              size: templateSource.length,
              description: null,
              createdAt: "2026-09-03T00:00:00.000Z",
              meta: {},
            },
          },
          {
            op: "add",
            path: ["notes"],
            value: {
              id: "notes",
              projectId,
              name: "notes.txt",
              filename: "notes",
              folderId: "posts",
              type: "file",
              format: "txt",
              size: 5,
              description: null,
              createdAt: "2026-09-03T00:00:00.000Z",
              meta: {},
            },
          },
        ],
        createContext()
      )
    ).rejects.toThrow('Collection entry "notes.txt" must be an MDX file');
    expect(inserted).toBe(false);
  });

  test("persists legacy null-provenance asset metadata via patch", async () => {
    const projectId = uid();
    let localAssetRow = {
      ...assetRow,
      projectId,
      file: {
        ...assetRow.file,
        name: "font.woff2",
        format: "woff2",
        meta: JSON.stringify({
          family: "Rajdhani",
          style: "normal",
          weight: 400,
        }),
        uploaderProjectId: null,
      },
    };
    let updatedMeta: unknown;

    server.use(
      ownershipHandler,
      db.get("Asset", () => json([localAssetRow])),
      db.get("File", () => json([localAssetRow.file])),
      db.patch("File", async ({ request }) => {
        updatedMeta = ((await request.json()) as { meta: unknown }).meta;
        localAssetRow = {
          ...localAssetRow,
          file: { ...localAssetRow.file, meta: String(updatedMeta) },
        };
        return json({ meta: updatedMeta });
      })
    );

    await patchAssets(
      { projectId, assetStore: unusedAssetStore },
      [
        {
          op: "replace",
          path: ["asset-1", "meta"],
          value: { family: "Rajdhani", style: "normal", weight: 600 },
        },
      ],
      createContext()
    );

    expect(updatedMeta).toBe(
      JSON.stringify({ family: "Rajdhani", style: "normal", weight: 600 })
    );
    await expect(
      loadAssetsByProjectWithClient(projectId, testContext.postgrest.client)
    ).resolves.toEqual([
      expect.objectContaining({
        id: "asset-1",
        meta: { family: "Rajdhani", style: "normal", weight: 600 },
      }),
    ]);
  });

  test("updates asset filename via patch", async () => {
    const projectId = uid();
    let localAssetRow = { ...assetRow, projectId };
    let updatedFilename: string | undefined;

    server.use(
      ownershipHandler,
      db.get("Asset", () => json([localAssetRow])),
      db.get("AssetFileMetadata", () => json([])),
      db.patch("Asset", async ({ request }) => {
        const body = (await request.json()) as { filename?: string };
        updatedFilename = body.filename;
        localAssetRow = {
          ...localAssetRow,
          filename: body.filename ?? localAssetRow.filename,
        };
        return json({
          id: localAssetRow.assetId,
          filename: localAssetRow.filename,
          description: localAssetRow.description,
        });
      })
    );

    const patches: Patch[] = [
      {
        op: "replace",
        path: ["asset-1", "filename"],
        value: "renamed-photo.jpg",
      },
    ];

    await patchAssets(
      { projectId, assetStore: unusedAssetStore },
      patches,
      createContext()
    );
    expect(updatedFilename).toBe("renamed-photo.jpg");
    await expect(
      loadAssetsByProjectWithClient(projectId, testContext.postgrest.client)
    ).resolves.toEqual([
      expect.objectContaining({
        id: "asset-1",
        filename: "renamed-photo.jpg",
      }),
    ]);
  });

  test("atomically swaps an asset file while preserving its id", async () => {
    const projectId = uid();
    const localAssetRow = { ...assetRow, projectId };
    let swapInput: unknown;
    server.use(
      ownershipHandler,
      db.get("Asset", () => json([localAssetRow])),
      db.patch("Asset", () =>
        json({
          filename: localAssetRow.filename,
          description: localAssetRow.description,
          folderId: null,
        })
      ),
      http.post(
        "http://test-postgrest/rpc/swap_asset_file",
        async ({ request }) => {
          swapInput = await request.json();
          return HttpResponse.json("updated");
        }
      )
    );

    await patchAssetsWithClient(
      { projectId, client: testContext.postgrest.client },
      [
        {
          op: "replace",
          path: ["asset-1", "name"],
          value: "photo_revision.jpg",
        },
      ]
    );

    expect(swapInput).toEqual({
      project_id: projectId,
      asset_id: "asset-1",
      expected_name: "photo.jpg",
      replacement_name: "photo_revision.jpg",
    });
  });

  test("restores a shared clone file without requiring an owned revision", async () => {
    const projectId = uid();
    const sourceProjectId = uid();
    const authoritativeMeta = { width: 1200, height: 800 };
    const forgedMeta = { width: 9999, height: 9999 };
    const staleMeta = { width: 320, height: 200 };
    const sharedFile = {
      ...assetRow.file,
      name: "original_shared.jpg",
      format: "jpg",
      size: 2000,
      meta: JSON.stringify(authoritativeMeta),
      uploaderProjectId: sourceProjectId,
      contentHash: "a".repeat(64),
      isDeleted: false,
      updatedAt: "2026-09-06T00:00:00.000Z",
    };
    const currentFile = {
      ...sharedFile,
      name: "current_clone.jpg",
      size: 1000,
      meta: JSON.stringify(staleMeta),
      uploaderProjectId: projectId,
      contentHash: "f".repeat(64),
    };
    let persistedFile = currentFile;
    let persistedSharedMeta = sharedFile.meta;
    let fileMetadataUpdates = 0;
    const restoredFiles: string[] = [];
    const directSwapInputs: Array<Record<string, unknown>> = [];
    const swapInputs: Array<Record<string, unknown>> = [];
    server.use(
      ownershipHandler,
      db.get("Asset", () =>
        json([
          {
            ...assetRow,
            assetId: "entry",
            projectId,
            filename: "post",
            folderId: null,
            file: persistedFile,
          },
        ])
      ),
      db.get("File", ({ request }) => {
        const url = new URL(request.url);
        const nameFilter = url.searchParams.get("name") ?? "";
        if (nameFilter.includes(sharedFile.name)) {
          return json([{ ...sharedFile, meta: persistedSharedMeta }]);
        }
        return json([]);
      }),
      db.patch("File", async ({ request }) => {
        const url = new URL(request.url);
        const name = url.searchParams.get("name") ?? "";
        const input = (await request.json()) as Record<string, unknown>;
        if (Object.hasOwn(input, "isDeleted")) {
          expect(url.searchParams.get("status")).toBe("eq.UPLOADED");
          expect(input).toEqual({ isDeleted: false });
          restoredFiles.push(name);
          return json({ name: sharedFile.name });
        }
        if (typeof input.meta === "string") {
          fileMetadataUpdates += 1;
          persistedSharedMeta = input.meta;
          return json({ meta: input.meta });
        }
        return json(null);
      }),
      db.patch("Asset", async ({ request }) => {
        const url = new URL(request.url);
        expect(url.searchParams.get("id")).toBe("eq.entry");
        expect(url.searchParams.get("projectId")).toBe(`eq.${projectId}`);
        expect(url.searchParams.get("name")).toBe(`eq.${currentFile.name}`);
        const input = (await request.json()) as Record<string, unknown>;
        directSwapInputs.push(input);
        if (input.name !== sharedFile.name) {
          return json(null);
        }
        persistedFile = sharedFile;
        return json({ id: "entry" });
      }),
      http.post(
        "http://test-postgrest/rpc/swap_asset_file",
        async ({ request }) => {
          const input = (await request.json()) as Record<string, unknown>;
          swapInputs.push(input);
          return HttpResponse.json("invalid_revision");
        }
      )
    );
    const assetStore = {
      readFile: async () => {
        throw new Error("Unexpected asset content read");
      },
    };
    const patches: Patch[] = [
      {
        op: "replace",
        path: ["entry", "name"],
        value: sharedFile.name,
      },
      {
        op: "replace",
        path: ["entry", "meta"],
        value: authoritativeMeta,
      },
    ];

    await expect(
      patchAssets(
        { projectId, assetStore },
        [
          patches[0]!,
          {
            op: "replace",
            path: ["entry", "meta"],
            value: forgedMeta,
          },
        ],
        createContext()
      )
    ).rejects.toThrow("Shared asset metadata does not match its file");
    expect(restoredFiles).toEqual([]);
    expect(directSwapInputs).toEqual([]);
    expect(swapInputs).toEqual([]);
    expect(persistedSharedMeta).toBe(sharedFile.meta);
    expect(persistedFile).toEqual(currentFile);

    await patchAssets({ projectId, assetStore }, patches, createContext());
    await patchAssets({ projectId, assetStore }, patches, createContext());

    expect(restoredFiles).toEqual([`eq.${sharedFile.name}`]);
    expect(directSwapInputs).toEqual([
      {
        name: sharedFile.name,
      },
    ]);
    expect(swapInputs).toEqual([]);
    expect(persistedFile).toEqual(sharedFile);
    expect(persistedSharedMeta).toBe(sharedFile.meta);
    expect(fileMetadataUpdates).toBe(0);
  });

  test("persists moving an asset to root as null", async () => {
    const projectId = uid();
    let localAssetRow = {
      ...assetRow,
      projectId,
      filename: "post",
      folderId: "folder" as string | null,
      file: {
        ...assetRow.file,
        name: "stored.md",
        format: "md",
        size: 100,
        meta: "{}",
      },
    };
    let updatedFolderId: unknown = "not-updated";
    server.use(
      ownershipHandler,
      db.get("Asset", ({ request }) => {
        const url = new URL(request.url);
        if (url.searchParams.has("id")) {
          return json([{ ...localAssetRow, id: localAssetRow.assetId }]);
        }
        return json([localAssetRow]);
      }),
      db.patch("Asset", async ({ request }) => {
        updatedFolderId = ((await request.json()) as { folderId: unknown })
          .folderId;
        localAssetRow = { ...localAssetRow, folderId: null };
        return json({
          id: localAssetRow.assetId,
          filename: localAssetRow.filename,
          description: localAssetRow.description,
          folderId: null,
        });
      })
    );

    await patchAssets(
      { projectId, assetStore: unusedAssetStore },
      [{ op: "remove", path: ["asset-1", "folderId"] }],
      createContext()
    );
    expect(updatedFolderId).toBeNull();
  });

  test("does not update metadata when adding an existing asset", async () => {
    const projectId = uid();
    const localAssetRow = { ...assetRow, projectId };
    let updateCount = 0;

    server.use(
      ownershipHandler,
      db.get("Asset", () => json([localAssetRow])),
      db.patch("Asset", () => {
        updateCount += 1;
        return json({
          filename: localAssetRow.filename,
          description: localAssetRow.description,
        });
      })
    );

    const [asset] = await loadAssetsByProjectWithClient(
      projectId,
      testContext.postgrest.client
    );
    await patchAssets(
      { projectId, assetStore: unusedAssetStore },
      [{ op: "add", path: [asset.id], value: asset }],
      createContext()
    );

    expect(updateCount).toBe(0);
  });

  test("throws when an asset metadata update matches no database row", async () => {
    const projectId = uid();
    const localAssetRow = { ...assetRow, projectId };

    server.use(
      ownershipHandler,
      db.get("Asset", () => json([localAssetRow])),
      db.patch("Asset", () =>
        json(
          {
            code: "PGRST116",
            message: "The result contains 0 rows",
          },
          { status: 406 }
        )
      )
    );

    await expect(
      patchAssets(
        { projectId, assetStore: unusedAssetStore },
        [
          {
            op: "replace",
            path: ["asset-1", "filename"],
            value: "renamed-photo.jpg",
          },
        ],
        createContext()
      )
    ).rejects.toThrow();
  });

  test("adds new asset when patch inserts an entry", async () => {
    const projectId = uid();
    let insertedAssets: unknown;

    server.use(
      ownershipHandler,
      // loadAssetsByProject returns empty list — no existing assets
      db.get("Asset", ({ request }) => {
        const url = new URL(request.url);
        if (url.searchParams.get("projectId")) {
          return json([]);
        }
        return json([]);
      }),
      // File lookup for undo restore
      db.get("File", () =>
        json([
          {
            ...assetRow.file,
            name: "new.jpg",
            format: "jpg",
            size: 500,
            meta: JSON.stringify({ width: 50, height: 50 }),
            updatedAt: "2024-01-01T00:00:00.000Z",
          },
        ])
      ),
      // restore isDeleted=false
      db.patch("File", () => empty({ status: 204 })),
      // asset insert
      db.post("Asset", async ({ request }) => {
        insertedAssets = await request.json();
        return empty({ status: 201 });
      })
    );

    const patches: Patch[] = [
      {
        op: "add",
        path: ["asset-new"],
        value: {
          id: "asset-new",
          name: "new.jpg",
          type: "image",
          projectId,
          format: "jpg",
          size: 500,
          description: null,
          createdAt: "2024-01-01T00:00:00.000Z",
          path: "",
          meta: { width: 50, height: 50 },
        },
      },
    ];

    await patchAssets(
      { projectId, assetStore: unusedAssetStore },
      patches,
      createContext()
    );
    expect(insertedAssets).toBeDefined();
  });

  test("rejects an added asset whose file is unavailable", async () => {
    const projectId = uid();
    let restored = false;
    let inserted = false;
    server.use(
      db.get("Asset", () => json([])),
      db.get("File", () => json([])),
      db.patch("File", () => {
        restored = true;
        return empty({ status: 204 });
      }),
      db.post("Asset", () => {
        inserted = true;
        return empty({ status: 201 });
      })
    );

    await expect(
      patchAssetsWithClient(
        { projectId, client: testContext.postgrest.client },
        [
          {
            op: "add",
            path: ["missing"],
            value: {
              id: "missing",
              name: "missing.jpg",
              type: "image",
              projectId,
              format: "jpg",
              size: 1,
              description: null,
              createdAt: "2024-01-01T00:00:00.000Z",
              meta: { width: 1, height: 1 },
            },
          },
        ]
      )
    ).rejects.toThrow("Asset file not found for missing");
    expect(restored).toBe(false);
    expect(inserted).toBe(false);
  });

  test("rejects an added asset whose file is not fully uploaded", async () => {
    const projectId = uid();
    let restored = false;
    let inserted = false;
    server.use(
      ownershipHandler,
      db.get("Asset", () => json([])),
      db.get("File", ({ request }) => {
        expect(new URL(request.url).searchParams.get("status")).toBe(
          "eq.UPLOADED"
        );
        return json([
          {
            ...assetRow.file,
            name: "uploading.jpg",
            status: "UPLOADING",
          },
        ]);
      }),
      db.patch("File", () => {
        restored = true;
        return empty({ status: 204 });
      }),
      db.post("Asset", () => {
        inserted = true;
        return empty({ status: 201 });
      })
    );

    await expect(
      patchAssets(
        { projectId, assetStore: unusedAssetStore },
        [
          {
            op: "add",
            path: ["uploading"],
            value: {
              id: "uploading",
              name: "uploading.jpg",
              type: "image",
              projectId,
              format: "jpg",
              size: 1000,
              description: null,
              createdAt: "2024-01-01T00:00:00.000Z",
              meta: { width: 100, height: 100 },
            },
          },
        ],
        createContext()
      )
    ).rejects.toThrow("Asset file not found");
    expect(restored).toBe(false);
    expect(inserted).toBe(false);
  });

  test("chunks uploaded file lookups and restores by bounded filter size", async () => {
    const projectId = uid();
    const fileNames = Array.from(
      { length: 12 },
      (_, index) => `${String(index).padStart(2, "0")}-${"a".repeat(490)}.jpg`
    );
    const assetFileNames = [...fileNames, fileNames[0]!];
    const fileByName = new Map(
      fileNames.map((name) => [
        name,
        {
          ...assetRow.file,
          name,
          status: "UPLOADED",
        },
      ])
    );
    const readBatches: string[][] = [];
    const restoreBatches: string[][] = [];
    const getNames = (request: Request) => {
      const url = new URL(request.url);
      expect(url.search.length).toBeLessThan(4300);
      expect(url.searchParams.get("status")).toBe("eq.UPLOADED");
      const filter = url.searchParams.get("name");
      expect(filter?.startsWith("in.(")).toBe(true);
      return filter?.slice(4, -1).split(",") ?? [];
    };
    server.use(
      ownershipHandler,
      db.get("Asset", () => json([])),
      db.get("File", ({ request }) => {
        const names = getNames(request);
        readBatches.push(names);
        return json(
          names.flatMap((name) => {
            const file = fileByName.get(name);
            return file === undefined ? [] : [file];
          })
        );
      }),
      db.patch("File", ({ request }) => {
        restoreBatches.push(getNames(request));
        return empty({ status: 204 });
      }),
      db.post("Asset", () => empty({ status: 201 }))
    );

    await patchAssets(
      { projectId, assetStore: unusedAssetStore },
      assetFileNames.map((name, index) => ({
        op: "add" as const,
        path: [`asset-${index}`],
        value: {
          id: `asset-${index}`,
          name,
          type: "image" as const,
          projectId,
          format: "jpg",
          size: 1000,
          description: null,
          createdAt: "2024-01-01T00:00:00.000Z",
          meta: { width: 100, height: 100 },
        },
      })),
      createContext()
    );

    expect(readBatches.length).toBeGreaterThan(2);
    expect(restoreBatches.length).toBeGreaterThan(1);
    expect(readBatches.every((batch) => batch.length < fileNames.length)).toBe(
      true
    );
    expect(
      restoreBatches.every((batch) => batch.length < fileNames.length)
    ).toBe(true);
    expect(new Set(readBatches.flat())).toEqual(new Set(fileNames));
    expect(new Set(restoreBatches.flat())).toEqual(new Set(fileNames));
    expect(
      [...readBatches, ...restoreBatches].every(
        (batch) => new Set(batch).size === batch.length
      )
    ).toBe(true);
  });

  test("core helper deletes assets and marks unused files as deleted", async () => {
    const projectId = uid();
    const localAssetRow = { ...assetRow, projectId };
    let resetPreviewImage = false;
    let deletedAsset = false;
    let deletedFile = false;

    server.use(
      db.get("Asset", ({ request }) => {
        const url = new URL(request.url);
        if (url.searchParams.has("id")) {
          return json([
            {
              id: "asset-1",
              projectId,
              name: "photo.jpg",
              file: localAssetRow.file,
            },
          ]);
        }
        if (url.searchParams.has("name")) {
          return json([]);
        }
        return json([localAssetRow]);
      }),
      db.patch("Project", async ({ request }) => {
        const body = (await request.json()) as {
          previewImageAssetId?: string | null;
        };
        resetPreviewImage = body.previewImageAssetId === null;
        return empty({ status: 204 });
      }),
      db.delete("Asset", () => {
        deletedAsset = true;
        return empty({ status: 204 });
      }),
      db.patch("File", async ({ request }) => {
        const body = (await request.json()) as { isDeleted?: boolean };
        deletedFile = body.isDeleted === true;
        return empty({ status: 204 });
      })
    );

    const patches: Patch[] = [
      {
        op: "remove",
        path: ["asset-1"],
      },
    ];

    await patchAssetsWithClient(
      { projectId, client: testContext.postgrest.client },
      patches
    );

    expect(resetPreviewImage).toBe(true);
    expect(deletedAsset).toBe(true);
    expect(deletedFile).toBe(true);
  });

  test("core helper stops asset deletion when preview reset fails", async () => {
    const projectId = uid();
    const localAssetRow = { ...assetRow, projectId };
    let deletedAsset = false;

    server.use(
      db.get("Asset", ({ request }) => {
        const url = new URL(request.url);
        if (url.searchParams.has("id")) {
          return json([
            {
              id: "asset-1",
              projectId,
              name: "photo.jpg",
              file: localAssetRow.file,
            },
          ]);
        }
        return json([localAssetRow]);
      }),
      db.patch("Project", () => json({ message: "db error" }, { status: 500 })),
      db.delete("Asset", () => {
        deletedAsset = true;
        return empty({ status: 204 });
      })
    );

    const patches: Patch[] = [
      {
        op: "remove",
        path: ["asset-1"],
      },
    ];

    await expect(
      patchAssetsWithClient(
        { projectId, client: testContext.postgrest.client },
        patches
      )
    ).rejects.toThrow();

    expect(deletedAsset).toBe(false);
  });

  test("core helper stops file cleanup when asset delete fails", async () => {
    const projectId = uid();
    const localAssetRow = { ...assetRow, projectId };
    let deletedFile = false;

    server.use(
      db.get("Asset", ({ request }) => {
        const url = new URL(request.url);
        if (url.searchParams.has("id")) {
          return json([
            {
              id: "asset-1",
              projectId,
              name: "photo.jpg",
              file: localAssetRow.file,
            },
          ]);
        }
        if (url.searchParams.has("name")) {
          return json([]);
        }
        return json([localAssetRow]);
      }),
      db.patch("Project", () => empty({ status: 204 })),
      db.delete("Asset", () => json({ message: "db error" }, { status: 500 })),
      db.patch("File", () => {
        deletedFile = true;
        return empty({ status: 204 });
      })
    );

    const patches: Patch[] = [
      {
        op: "remove",
        path: ["asset-1"],
      },
    ];

    await expect(
      patchAssetsWithClient(
        { projectId, client: testContext.postgrest.client },
        patches
      )
    ).rejects.toThrow();

    expect(deletedFile).toBe(false);
  });

  test("core helper stops asset insert when file restore fails", async () => {
    const projectId = uid();
    let insertedAssets = false;

    server.use(
      db.get("Asset", () => json([])),
      db.get("File", () => json([{ name: "new.jpg" }])),
      db.patch("File", () => json({ message: "db error" }, { status: 500 })),
      db.post("Asset", () => {
        insertedAssets = true;
        return empty({ status: 201 });
      })
    );

    const patches: Patch[] = [
      {
        op: "add",
        path: ["asset-new"],
        value: {
          id: "asset-new",
          name: "new.jpg",
          type: "image",
          projectId,
          format: "jpg",
          size: 500,
          description: null,
          createdAt: "2024-01-01T00:00:00.000Z",
          path: "",
          meta: { width: 50, height: 50 },
        },
      },
    ];

    await expect(
      patchAssetsWithClient(
        { projectId, client: testContext.postgrest.client },
        patches
      )
    ).rejects.toThrow();

    expect(insertedAssets).toBe(false);
  });
});