Open source website builder and Webflow alternative. Webstudio is an advanced visual builder that connects to any headless CMS, supports all CSS properties, and can be hosted anywhere, including with us.
TypeScript accessibilityalternativecloudflarecloudflare-workersdesignfreefrontendopen-sourceradix-uireactremixweb-developmentwebflowwebsite-builderwebsite-developmentwebsiteswebstudio
chore: Refactor assets without any changes in functionality (#5560)
Oleg Isonena1b2123f6afe
diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.mdindex 56d8735441..96e03d9c27 100644--- a/.github/copilot-instructions.md+++ b/.github/copilot-instructions.md@@ -10,11 +10,15 @@- Never use arbitrary CSS number values, 99% of the time you need to use a value from the theme- Never use margin, always use gap or padding- Never use one-line if statements: `if (condition) something;`+- Never use the `function` keyword - always use arrow functions (`const name = () => {}`) or function expressions with arrow syntax- Functions must never have more than 3 parameters - use an object parameter instead+- Never alias the same type or variable to different names (e.g., `type AliasName = OriginalName`) - always use the original name consistently throughout the codebase## Running Checks-- When user says "run checks" or similar, always run both `pnpm eslint` and `pnpm typecheck` (not just `get_errors`)+- Before running any commands, always check `get_errors` tool first to see TypeScript and ESLint errors in the VS Code editor+- Only run `pnpm typecheck` and `pnpm eslint` when user explicitly says "run checks" or after completing substantial changes+- `pnpm typecheck` is slow - avoid running it unnecessarily during development- Fix all eslint and TypeScript errors before considering work complete## File Organization@@ -23,6 +27,15 @@- Never add functions, constants, or executable code to `types.ts` files- Place utility functions in `*-utils.ts` files, constants in `constants.ts`, etc.+### Function Placement Philosophy++- Functions belong close to where they are used+- If a function is used in one file only, it should be in that file+- If a function is used by multiple files in the same directory, place it in a `*-utils.ts` file in that directory+- Only create shared utility files when functions are used across different directories+- Files prefixed with `use-` contain React hooks and state management (e.g., `use-assets.tsx`)+- Separate pure utilities from side-effect code (React hooks, network calls, DOM operations)+## Testing- Test utilities, not componentsdiff --git a/apps/builder/app/builder/shared/asset-manager/asset-info.test.ts b/apps/builder/app/builder/shared/asset-manager/asset-info.test.tsnew file mode 100644index 0000000000..73f4214a75--- /dev/null+++ b/apps/builder/app/builder/shared/asset-manager/asset-info.test.ts@@ -0,0 +1,414 @@+import { describe, test, expect } from "vitest";+import type { Pages, Props, Styles } from "@webstudio-is/sdk";+import type { ImageValue, StyleValue } from "@webstudio-is/css-engine";+import { __testing__ } from "./asset-info";++const { traverseStyleValue, calculateUsagesByAssetId } = __testing__;++describe("asset-info", () => {+ describe("traverseStyleValue", () => {+ test("calls callback for image values", () => {+ const imageValue: ImageValue = {+ type: "image",+ value: { type: "asset", value: "asset-1" },+ };+ const results: ImageValue[] = [];+ traverseStyleValue(imageValue, (value) => results.push(value));+ expect(results).toEqual([imageValue]);+ });++ test("traverses tuple values", () => {+ const imageValue1: ImageValue = {+ type: "image",+ value: { type: "asset", value: "asset-1" },+ };+ const imageValue2: ImageValue = {+ type: "image",+ value: { type: "asset", value: "asset-2" },+ };+ const tupleValue: StyleValue = {+ type: "tuple",+ value: [imageValue1, imageValue2],+ };+ const results: ImageValue[] = [];+ traverseStyleValue(tupleValue, (value) => results.push(value));+ expect(results).toEqual([imageValue1, imageValue2]);+ });++ test("traverses layers values", () => {+ const imageValue1: ImageValue = {+ type: "image",+ value: { type: "asset", value: "asset-1" },+ };+ const imageValue2: ImageValue = {+ type: "image",+ value: { type: "asset", value: "asset-2" },+ };+ const layersValue: StyleValue = {+ type: "layers",+ value: [imageValue1, imageValue2],+ };+ const results: ImageValue[] = [];+ traverseStyleValue(layersValue, (value) => results.push(value));+ expect(results).toEqual([imageValue1, imageValue2]);+ });++ test("does not call callback for other value types", () => {+ const keywordValue: StyleValue = {+ type: "keyword",+ value: "auto",+ };+ const results: ImageValue[] = [];+ traverseStyleValue(keywordValue, (value) => results.push(value));+ expect(results).toEqual([]);+ });++ test("traverses nested tuple and layers", () => {+ const imageValue: ImageValue = {+ type: "image",+ value: { type: "asset", value: "asset-1" },+ };+ const nestedTuple: StyleValue = {+ type: "tuple",+ value: [imageValue],+ };+ const layersValue: StyleValue = {+ type: "layers",+ value: [nestedTuple],+ };+ const results: ImageValue[] = [];+ traverseStyleValue(layersValue, (value) => results.push(value));+ expect(results).toEqual([imageValue]);+ });+ });++ describe("calculateUsagesByAssetId", () => {+ test("tracks favicon asset usage", () => {+ const pages: Pages = {+ meta: { faviconAssetId: "favicon-asset" },+ homePage: {+ id: "home",+ name: "Home",+ path: "",+ title: "Home",+ meta: {},+ rootInstanceId: "root",+ },+ pages: [],+ folders: [],+ };+ const props: Props = new Map();+ const styles: Styles = new Map();++ const usages = calculateUsagesByAssetId({ pages, props, styles });++ expect(usages.get("favicon-asset")).toEqual([{ type: "favicon" }]);+ });++ test("tracks social image asset usage", () => {+ const pages: Pages = {+ meta: {},+ homePage: {+ id: "home",+ name: "Home",+ path: "",+ title: "Home",+ meta: { socialImageAssetId: "social-asset" },+ rootInstanceId: "root",+ },+ pages: [],+ folders: [],+ };+ const props: Props = new Map();+ const styles: Styles = new Map();++ const usages = calculateUsagesByAssetId({ pages, props, styles });++ expect(usages.get("social-asset")).toEqual([+ { type: "socialImage", pageId: "home" },+ ]);+ });++ test("tracks marketplace thumbnail asset usage", () => {+ const pages: Pages = {+ meta: {},+ homePage: {+ id: "home",+ name: "Home",+ path: "",+ title: "Home",+ meta: {},+ rootInstanceId: "root",+ },+ pages: [+ {+ id: "page-1",+ name: "Page 1",+ path: "/page-1",+ title: "Page 1",+ meta: {},+ rootInstanceId: "root-1",+ marketplace: { thumbnailAssetId: "thumbnail-asset" },+ },+ ],+ folders: [],+ };+ const props: Props = new Map();+ const styles: Styles = new Map();++ const usages = calculateUsagesByAssetId({ pages, props, styles });++ expect(usages.get("thumbnail-asset")).toEqual([+ { type: "marketplaceThumbnail", pageId: "page-1" },+ ]);+ });++ test("tracks prop asset usage", () => {+ const pages: Pages = {+ meta: {},+ homePage: {+ id: "home",+ name: "Home",+ path: "",+ title: "Home",+ meta: {},+ rootInstanceId: "root",+ },+ pages: [],+ folders: [],+ };+ const props: Props = new Map([+ [+ "prop-1",+ {+ id: "prop-1",+ instanceId: "instance-1",+ type: "asset",+ name: "src",+ value: "asset-1",+ },+ ],+ ]);+ const styles: Styles = new Map();++ const usages = calculateUsagesByAssetId({ pages, props, styles });++ expect(usages.get("asset-1")).toEqual([+ { type: "prop", propId: "prop-1" },+ ]);+ });++ test("ignores width and height props", () => {+ const pages: Pages = {+ meta: {},+ homePage: {+ id: "home",+ name: "Home",+ path: "",+ title: "Home",+ meta: {},+ rootInstanceId: "root",+ },+ pages: [],+ folders: [],+ };+ const props: Props = new Map([+ [+ "prop-width",+ {+ id: "prop-width",+ instanceId: "instance-1",+ type: "asset",+ name: "width",+ value: "asset-1",+ },+ ],+ [+ "prop-height",+ {+ id: "prop-height",+ instanceId: "instance-1",+ type: "asset",+ name: "height",+ value: "asset-1",+ },+ ],+ ]);+ const styles: Styles = new Map();++ const usages = calculateUsagesByAssetId({ pages, props, styles });++ expect(usages.get("asset-1")).toBeUndefined();+ });++ test("tracks image asset usage in styles", () => {+ const pages: Pages = {+ meta: {},+ homePage: {+ id: "home",+ name: "Home",+ path: "",+ title: "Home",+ meta: {},+ rootInstanceId: "root",+ },+ pages: [],+ folders: [],+ };+ const props: Props = new Map();+ const styles: Styles = new Map([+ [+ "style-1:breakpoint-1:property",+ {+ breakpointId: "breakpoint-1",+ styleSourceId: "style-1",+ property: "backgroundImage",+ value: {+ type: "image",+ value: { type: "asset", value: "asset-1" },+ },+ },+ ],+ ]);++ const usages = calculateUsagesByAssetId({ pages, props, styles });++ expect(usages.get("asset-1")).toEqual([+ { type: "style", styleDeclKey: "style-1:breakpoint-1:property" },+ ]);+ });++ test("returns empty map when no usages", () => {+ const pages: Pages = {+ meta: {},+ homePage: {+ id: "home",+ name: "Home",+ path: "",+ title: "Home",+ meta: {},+ rootInstanceId: "root",+ },+ pages: [],+ folders: [],+ };+ const props: Props = new Map();+ const styles: Styles = new Map();++ const usages = calculateUsagesByAssetId({ pages, props, styles });++ expect(usages.size).toBe(0);+ });++ test("aggregates multiple usages for same asset", () => {+ const pages: Pages = {+ meta: { faviconAssetId: "asset-1" },+ homePage: {+ id: "home",+ name: "Home",+ path: "",+ title: "Home",+ meta: { socialImageAssetId: "asset-1" },+ rootInstanceId: "root",+ },+ pages: [],+ folders: [],+ };+ const props: Props = new Map([+ [+ "prop-1",+ {+ id: "prop-1",+ instanceId: "instance-1",+ type: "asset",+ name: "src",+ value: "asset-1",+ },+ ],+ ]);+ const styles: Styles = new Map([+ [+ "style-1:breakpoint-1:property",+ {+ breakpointId: "breakpoint-1",+ styleSourceId: "style-1",+ property: "backgroundImage",+ value: {+ type: "image",+ value: { type: "asset", value: "asset-1" },+ },+ },+ ],+ ]);++ const usages = calculateUsagesByAssetId({ pages, props, styles });++ expect(usages.get("asset-1")).toHaveLength(4);+ expect(usages.get("asset-1")).toEqual([+ { type: "favicon" },+ { type: "socialImage", pageId: "home" },+ { type: "prop", propId: "prop-1" },+ { type: "style", styleDeclKey: "style-1:breakpoint-1:property" },+ ]);+ });++ test("handles undefined pages", () => {+ const pages = undefined;+ const props: Props = new Map();+ const styles: Styles = new Map();++ const usages = calculateUsagesByAssetId({ pages, props, styles });++ expect(usages.size).toBe(0);+ });++ test("tracks multiple assets in tuple style value", () => {+ const pages: Pages = {+ meta: {},+ homePage: {+ id: "home",+ name: "Home",+ path: "",+ title: "Home",+ meta: {},+ rootInstanceId: "root",+ },+ pages: [],+ folders: [],+ };+ const props: Props = new Map();+ const styles: Styles = new Map([+ [+ "style-1:breakpoint-1:property",+ {+ breakpointId: "breakpoint-1",+ styleSourceId: "style-1",+ property: "backgroundImage",+ value: {+ type: "tuple",+ value: [+ {+ type: "image",+ value: { type: "asset", value: "asset-1" },+ },+ {+ type: "image",+ value: { type: "asset", value: "asset-2" },+ },+ ],+ },+ },+ ],+ ]);++ const usages = calculateUsagesByAssetId({ pages, props, styles });++ expect(usages.get("asset-1")).toEqual([+ { type: "style", styleDeclKey: "style-1:breakpoint-1:property" },+ ]);+ expect(usages.get("asset-2")).toEqual([+ { type: "style", styleDeclKey: "style-1:breakpoint-1:property" },+ ]);+ });+ });+});diff --git a/apps/builder/app/builder/shared/asset-manager/asset-info.tsx b/apps/builder/app/builder/shared/asset-manager/asset-info.tsxindex 66ee92b557..7addf26b27 100644--- a/apps/builder/app/builder/shared/asset-manager/asset-info.tsx+++ b/apps/builder/app/builder/shared/asset-manager/asset-info.tsx@@ -2,8 +2,12 @@ import isValidFilename from "valid-filename";import { useEffect, useRef, useState } from "react";import { useDebouncedCallback } from "use-debounce";import prettyBytes from "pretty-bytes";+import { computed } from "nanostores";import { useStore } from "@nanostores/react";import { getMimeTypeByExtension } from "@webstudio-is/sdk";+import type { Asset, Pages, Props, Styles, Instance } from "@webstudio-is/sdk";+import type { ImageValue, StyleValue } from "@webstudio-is/css-engine";+import { mapGetOrInsert } from "~/shared/shim";import {Box,Button,@@ -40,7 +44,6 @@ import {PageIcon,TrashIcon,} from "@webstudio-is/icons";-import type { Asset, Instance } from "@webstudio-is/sdk";import { hyphenateProperty } from "@webstudio-is/css-engine";import {$assets,@@ -60,11 +63,7 @@ import {selectPage,} from "~/shared/awareness";import { updateWebstudioData } from "~/shared/instance-utils";-import {- deleteAssets,- $usagesByAssetId,- type AssetUsage,-} from "~/builder/shared/assets";+import { deleteAssets } from "~/builder/shared/assets";import {$activeInspectorPanel,setActiveSidebarPanel,@@ -77,6 +76,99 @@ import {import { getFormattedAspectRatio } from "./utils";import { CopyToClipboard } from "~/shared/copy-to-clipboard";+type AssetUsage =+ | { type: "favicon" }+ | { type: "socialImage"; pageId: string }+ | { type: "marketplaceThumbnail"; pageId: string }+ | { type: "prop"; propId: string }+ | { type: "style"; styleDeclKey: string };++const traverseStyleValue = (+ styleValue: StyleValue,+ callback: (value: ImageValue) => void+) => {+ if (styleValue.type === "image") {+ callback(styleValue);+ }+ if (styleValue.type === "tuple") {+ for (const item of styleValue.value) {+ traverseStyleValue(item, callback);+ }+ }+ if (styleValue.type === "layers") {+ for (const item of styleValue.value) {+ traverseStyleValue(item, callback);+ }+ }+};++const calculateUsagesByAssetId = ({+ pages,+ props,+ styles,+}: {+ pages: Pages | undefined;+ props: Props;+ styles: Styles;+}): Map<Asset["id"], AssetUsage[]> => {+ const usagesByAsset = new Map<Asset["id"], AssetUsage[]>();+ if (pages?.meta?.faviconAssetId) {+ const usages = mapGetOrInsert(usagesByAsset, pages.meta.faviconAssetId, []);+ usages.push({ type: "favicon" });+ }+ if (pages) {+ for (const page of [pages.homePage, ...pages.pages]) {+ if (page.meta.socialImageAssetId) {+ const usages = mapGetOrInsert(+ usagesByAsset,+ page.meta.socialImageAssetId,+ []+ );+ usages.push({ type: "socialImage", pageId: page.id });+ }+ if (page.marketplace?.thumbnailAssetId) {+ const usages = mapGetOrInsert(+ usagesByAsset,+ page.marketplace.thumbnailAssetId,+ []+ );+ usages.push({ type: "marketplaceThumbnail", pageId: page.id });+ }+ }+ }+ for (const prop of props.values()) {+ if (+ prop.type === "asset" &&+ // ignore width and height properties which are specific to size+ prop.name !== "width" &&+ prop.name !== "height"+ ) {+ const usages = mapGetOrInsert(usagesByAsset, prop.value, []);+ usages.push({ type: "prop", propId: prop.id });+ }+ }+ for (const [styleDeclKey, styleDecl] of styles) {+ traverseStyleValue(styleDecl.value, (imageValue) => {+ if (imageValue.value.type === "asset") {+ const usages = mapGetOrInsert(+ usagesByAsset,+ imageValue.value.value,+ []+ );+ usages.push({ type: "style", styleDeclKey });+ }+ });+ }+ return usagesByAsset;+};++const $usagesByAssetId = computed(+ [$pages, $props, $styles],+ (pages, props, styles) => {+ return calculateUsagesByAssetId({ pages, props, styles });+ }+);+const buttonLinkClass = css({all: "unset",cursor: "pointer",@@ -549,3 +641,8 @@ export const AssetInfo = ({ asset }: { asset: Asset }) => {</>);};++export const __testing__ = {+ traverseStyleValue,+ calculateUsagesByAssetId,+};diff --git a/apps/builder/app/builder/shared/asset-manager/utils.ts b/apps/builder/app/builder/shared/asset-manager/utils.tsindex e73c9f8ab6..1b558ea43b 100644--- a/apps/builder/app/builder/shared/asset-manager/utils.ts+++ b/apps/builder/app/builder/shared/asset-manager/utils.ts@@ -1,10 +1,9 @@import { matchSorter } from "match-sorter";-import type { AllowedFileExtension } from "@webstudio-is/sdk";+import type { AllowedFileExtension, Asset } from "@webstudio-is/sdk";import {acceptToMimePatterns,doesAssetMatchMimePatterns,} from "@webstudio-is/sdk";-import type { Asset } from "@webstudio-is/sdk";import type { AssetContainer } from "../assets";export type SortField = "name" | "size" | "createdAt";diff --git a/apps/builder/app/builder/shared/assets/asset-upload.tsx b/apps/builder/app/builder/shared/assets/asset-upload.tsxindex 6df06072b8..c43db29e71 100644--- a/apps/builder/app/builder/shared/assets/asset-upload.tsx+++ b/apps/builder/app/builder/shared/assets/asset-upload.tsx@@ -6,7 +6,7 @@ import { IMAGE_MIME_TYPES, detectAssetType } from "@webstudio-is/sdk";import { MAX_UPLOAD_SIZE, toBytes } from "@webstudio-is/asset-uploader";import type { AssetType } from "@webstudio-is/asset-uploader";import { FONT_MIME_TYPES } from "@webstudio-is/fonts";-import { uploadAssets } from "./use-assets";+import { uploadAssets } from "./upload-assets";import { $authPermit } from "~/shared/nano-states";const maxSize = toBytes(MAX_UPLOAD_SIZE);diff --git a/apps/builder/app/builder/shared/assets/assets-shell.tsx b/apps/builder/app/builder/shared/assets/assets-shell.tsxindex 389cbb0d32..8969f29800 100644--- a/apps/builder/app/builder/shared/assets/assets-shell.tsx+++ b/apps/builder/app/builder/shared/assets/assets-shell.tsx@@ -25,7 +25,7 @@ import {import { dropTargetForExternal } from "@atlaskit/pragmatic-drag-and-drop/external/adapter";import invariant from "tiny-invariant";import type { ContainsSource } from "@atlaskit/pragmatic-drag-and-drop/dist/types/public-utils/external/native-types";-import { uploadAssets } from "./use-assets";+import { uploadAssets } from "./upload-assets";import { UploadIcon } from "@webstudio-is/icons";import {IDLE,diff --git a/apps/builder/app/builder/shared/assets/delete-assets.ts b/apps/builder/app/builder/shared/assets/delete-assets.tsnew file mode 100644index 0000000000..6bd9ac814a--- /dev/null+++ b/apps/builder/app/builder/shared/assets/delete-assets.ts@@ -0,0 +1,11 @@+import type { Asset } from "@webstudio-is/sdk";+import { $assets } from "~/shared/nano-states";+import { serverSyncStore } from "~/shared/sync/sync-stores";++export const deleteAssets = (assetIds: Asset["id"][]) => {+ serverSyncStore.createTransaction([$assets], (assets) => {+ for (const assetId of assetIds) {+ assets.delete(assetId);+ }+ });+};diff --git a/apps/builder/app/builder/shared/assets/index.ts b/apps/builder/app/builder/shared/assets/index.tsindex e779eb8aef..4c7fef7695 100644--- a/apps/builder/app/builder/shared/assets/index.ts+++ b/apps/builder/app/builder/shared/assets/index.ts@@ -1,4 +1,6 @@-export * from "./use-assets";+export { useAssets } from "./use-assets";+export * from "./delete-assets";+export { uploadAssets } from "./upload-assets";export * from "./types";export * from "./separator";export * from "./assets-shell";diff --git a/apps/builder/app/builder/shared/assets/types.ts b/apps/builder/app/builder/shared/assets/types.tsindex c5b41b5d91..a9427a0705 100644--- a/apps/builder/app/builder/shared/assets/types.ts+++ b/apps/builder/app/builder/shared/assets/types.ts@@ -21,7 +21,7 @@ export type UploadingAssetContainer = {*/export type AssetContainer = UploadedAssetContainer | UploadingAssetContainer;-export type ActionData = {+export type AssetActionResponse = {uploadedAssets?: Array<Asset>;deletedAssets?: Array<Asset>;errors?: string;diff --git a/apps/builder/app/builder/shared/assets/upload-assets.test.ts b/apps/builder/app/builder/shared/assets/upload-assets.test.tsnew file mode 100644index 0000000000..97151a1393--- /dev/null+++ b/apps/builder/app/builder/shared/assets/upload-assets.test.ts@@ -0,0 +1,50 @@+import { describe, test, expect } from "vitest";+import { __testing__ } from "./upload-assets";++const { deduplicateAssetName } = __testing__;++describe("upload-assets", () => {+ describe("deduplicateAssetName", () => {+ test("returns original name when no duplicates exist", () => {+ const existingNames = new Set(["other-file.png", "another-file.jpg"]);+ const result = deduplicateAssetName("unique-file.png", existingNames);+ expect(result).toBe("unique-file.png");+ });++ test("adds suffix when duplicate exists", () => {+ const existingNames = new Set(["duplicate.png"]);+ const result = deduplicateAssetName("duplicate.png", existingNames);+ expect(result).toBe("duplicate_1.png");+ });++ test("increments suffix for multiple duplicates", () => {+ const existingNames = new Set(["file.png", "file_1.png", "file_2.png"]);+ const result = deduplicateAssetName("file.png", existingNames);+ expect(result).toBe("file_3.png");+ });++ test("handles names without extension", () => {+ const existingNames = new Set<string>();+ const result = deduplicateAssetName("no-extension", existingNames);+ expect(result).toBe("no-extension");+ });++ test("handles empty existing names set", () => {+ const existingNames = new Set<string>();+ const result = deduplicateAssetName("file.jpg", existingNames);+ expect(result).toBe("file.jpg");+ });++ test("handles complex file extensions", () => {+ const existingNames = new Set(["archive.tar.gz"]);+ const result = deduplicateAssetName("archive.tar.gz", existingNames);+ expect(result).toBe("archive.tar_1.gz");+ });++ test("finds first available suffix with gaps", () => {+ const existingNames = new Set(["file.png", "file_2.png", "file_3.png"]);+ const result = deduplicateAssetName("file.png", existingNames);+ expect(result).toBe("file_1.png");+ });+ });+});diff --git a/apps/builder/app/builder/shared/assets/upload-assets.tsx b/apps/builder/app/builder/shared/assets/upload-assets.tsxnew file mode 100644index 0000000000..4b01e3eb7f--- /dev/null+++ b/apps/builder/app/builder/shared/assets/upload-assets.tsx@@ -0,0 +1,399 @@+import warnOnce from "warn-once";+import invariant from "tiny-invariant";+import type { Asset } from "@webstudio-is/sdk";+import type { AssetType } from "@webstudio-is/asset-uploader";+import { Box, toast, css, theme } from "@webstudio-is/design-system";+import { sanitizeS3Key } from "@webstudio-is/asset-uploader";+import { Image, wsImageLoader } from "@webstudio-is/image";+import { restAssetsUploadPath, restAssetsPath } from "~/shared/router-utils";+import { fetch } from "~/shared/fetch.client";+import type { AssetActionResponse } from "~/builder/shared/assets";+import {+ $assets,+ $authToken,+ $project,+ $uploadingFilesDataStore,+ type UploadingFileData,+} from "~/shared/nano-states";+import { serverSyncStore } from "~/shared/sync/sync-stores";+import {+ formatAssetName,+ getFileName,+ getMimeType,+ getSha256Hash,+ getSha256HashOfFile,+} from "./asset-utils";++const safeDeleteAssets = (assetIds: Asset["id"][], projectId: string) => {+ const currentProjectId = $project.get()?.id;++ if (currentProjectId !== projectId) {+ toast.error("Project has been changed, files will not be uploaded");+ // Can cause data corruption+ return;+ }++ serverSyncStore.createTransaction([$assets], (assets) => {+ for (const assetId of assetIds) {+ assets.delete(assetId);+ }+ });+};++const safeSetAsset = (asset: Asset, projectId: string) => {+ const currentProjectId = $project.get()?.id;++ if (currentProjectId !== projectId) {+ toast.error("Project has been changed, files will not be uploaded");+ // Can cause data corrupiton+ return;+ }++ serverSyncStore.createTransaction([$assets], (assets) => {+ assets.set(asset.id, asset);+ });+};++const getFilesData = async <T extends File | URL>(+ type: AssetType,+ filesOrUrls: T[]+): Promise<UploadingFileData[]> => {+ const filesData: UploadingFileData[] = [];+ for (const fileOrUrl of filesOrUrls) {+ if (fileOrUrl instanceof File) {+ const assetId = await getSha256HashOfFile(fileOrUrl);+ filesData.push({+ source: "file" as const,+ assetId: assetId,+ type,+ file: fileOrUrl,+ objectURL: URL.createObjectURL(fileOrUrl),+ });+ continue;+ }++ const assetId = await getSha256Hash(fileOrUrl.href);+ filesData.push({+ source: "url" as const,+ assetId,+ type,+ url: fileOrUrl.href,+ objectURL: fileOrUrl.href,+ });+ }++ return filesData;+};++const addUploadingFilesData = (filesData: UploadingFileData[]) => {+ const uploadingFilesData = $uploadingFilesDataStore.get();+ $uploadingFilesDataStore.set([...uploadingFilesData, ...filesData]);+};++const deleteUploadingFileData = (id: UploadingFileData["assetId"]) => {+ const uploadingFilesData = $uploadingFilesDataStore.get();+ $uploadingFilesDataStore.set(+ uploadingFilesData.filter((fileData) => fileData.assetId !== id)+ );+};++const getVideoDimensions = async (file: File) => {+ return new Promise<{ width: number; height: number }>((resolve, reject) => {+ const url = URL.createObjectURL(file);+ const vid = document.createElement("video");+ vid.preload = "metadata";+ vid.src = url;++ vid.onloadedmetadata = () => {+ URL.revokeObjectURL(url);+ resolve({ width: vid.videoWidth, height: vid.videoHeight });+ };+ vid.onerror = () => {+ URL.revokeObjectURL(url);+ reject(new Error("Invalid video file"));+ };+ });+};++const deduplicateAssetName = (name: string, existingNames: Set<string>) => {+ // eslint-disable-next-line no-constant-condition+ for (let index = 0; true; index += 1) {+ const suffix = index === 0 ? "" : `_${index}`;+ const lastDotAt = name.lastIndexOf(".");+ if (lastDotAt === -1) {+ return name;+ }+ const basename = name.slice(0, lastDotAt);+ const ext = name.slice(lastDotAt);+ const nameWithSuffix = basename + suffix + ext;+ if (!existingNames.has(nameWithSuffix)) {+ return nameWithSuffix;+ }+ }+};++const uploadAsset = async ({+ authToken,+ projectId,+ fileOrUrl,+ assetType,+ onCompleted,+ onError,+}: {+ authToken: undefined | string;+ projectId: string;+ fileOrUrl: File | URL;+ assetType: AssetType;+ onCompleted: (data: AssetActionResponse) => void;+ onError: (error: string) => void;+}) => {+ try {+ const mimeType = getMimeType(fileOrUrl);+ const fileName = getFileName(fileOrUrl);++ const metaFormData = new FormData();+ metaFormData.append("projectId", projectId);+ metaFormData.append("type", assetType);+ // sanitizeS3Key here is just because of https://github.com/remix-run/remix/issues/4443+ // should be removed after fix+ const existingNames = new Set<string>();+ for (const asset of $assets.get().values()) {+ existingNames.add(formatAssetName(asset));+ }+ metaFormData.append(+ "filename",+ deduplicateAssetName(sanitizeS3Key(fileName), existingNames)+ );++ const authHeaders = new Headers();+ if (authToken !== undefined) {+ authHeaders.set("x-auth-token", authToken);+ }++ const metaResponse = await fetch(restAssetsPath(), {+ method: "POST",+ body: metaFormData,+ headers: authHeaders,+ });++ const metaData: { name: string } | { errors: string } =+ await metaResponse.json();++ if ("errors" in metaData) {+ throw Error(metaData.errors);+ }++ const body =+ fileOrUrl instanceof File+ ? fileOrUrl+ : JSON.stringify({ url: fileOrUrl.href });++ const headers = new Headers(authHeaders);++ if (fileOrUrl instanceof URL) {+ headers.set("Content-Type", "application/json");+ }++ let width = undefined;+ let height = undefined;++ if (mimeType.startsWith("video/") && fileOrUrl instanceof File) {+ const videoSize = await getVideoDimensions(fileOrUrl);+ width = videoSize.width;+ height = videoSize.height;+ }++ const uploadResponse = await fetch(+ restAssetsUploadPath({ name: metaData.name, width, height }),+ {+ method: "POST",+ body,+ headers,+ }+ );++ const uploadData: AssetActionResponse = await uploadResponse.json();++ if ("errors" in uploadData) {+ throw Error(uploadData.errors);+ }++ onCompleted(uploadData);+ } catch (error) {+ if (error instanceof Error) {+ onError(error.message);+ }+ }+};++const handleAfterSubmit = (+ assetId: string,+ data: AssetActionResponse,+ projectId: string+) => {+ warnOnce(+ data.uploadedAssets?.length !== 1,+ "Expected exactly 1 uploaded asset"+ );++ const uploadedAsset = data.uploadedAssets?.[0];++ if (uploadedAsset === undefined) {+ warnOnce(true, "An uploaded asset is undefined");+ toast.error("Could not upload an asset");+ safeDeleteAssets([assetId], projectId);+ return;+ }++ // update store with new asset and set current id+ safeSetAsset({ ...uploadedAsset, id: assetId }, projectId);+};++const imageWidth = css({+ maxWidth: "100%",+});++const ToastImageInfo = ({ objectURL }: { objectURL: string }) => {+ return (+ <Box css={{ width: theme.spacing[18] }}>+ <Image+ className={imageWidth()}+ src={objectURL}+ optimize={false}+ width={64}+ loader={wsImageLoader}+ />+ </Box>+ );+};++const processingQueue: [+ filesData: UploadingFileData[],+ projectId: string,+ authToken: string | undefined,+][] = [];++const processUpload = async (+ filesData: UploadingFileData[],+ projectId: string,+ authToken: string | undefined+) => {+ processingQueue.push([filesData, projectId, authToken]);++ if (processingQueue.length > 1) {+ return;+ }++ while (processingQueue.length > 0) {+ const [filesData, projectId, authToken] = processingQueue.shift()!;++ const currentProjectId = $project.get()?.id;+ if (currentProjectId !== projectId) {+ toast.error("Project has been changed, files will not be uploaded");+ // Can cause data corrupiton+ continue;+ }++ for (const fileData of filesData) {+ const assetId = fileData.assetId;++ if ($assets.get().has(assetId)) {+ toast.info("Asset already exists", {+ icon: <ToastImageInfo objectURL={fileData.objectURL} />,+ });++ deleteUploadingFileData(assetId);+ continue;+ }++ await uploadAsset({+ authToken,+ projectId,+ fileOrUrl:+ fileData.source === "file" ? fileData.file : new URL(fileData.url),+ assetType: fileData.type,+ onCompleted: (data) => {+ URL.revokeObjectURL(fileData.objectURL);+ deleteUploadingFileData(assetId);+ handleAfterSubmit(assetId, data, projectId);+ },+ onError: (error) => {+ deleteUploadingFileData(assetId);+ toast.error(error, {+ icon: <ToastImageInfo objectURL={fileData.objectURL} />,+ });++ safeDeleteAssets([assetId], projectId);+ },+ });+ }+ }+};++export const uploadAssets = async <T extends File | URL>(+ type: AssetType,+ filesOrUrls: T[]+): Promise<Map<T, string>> => {+ const projectId = $project.get()?.id;+ const authToken = $authToken.get();+ if (projectId === undefined) {+ return new Map();+ }++ const filesData = await getFilesData(type, filesOrUrls);++ // Filter out duplicates inside filesData+ const uniqFilesDataMap = new Map(+ filesData.map((fileData) => [fileData.assetId, fileData])+ );++ // Filter out duplicates existing in assets or uploading files+ const existingIds = [+ ...$assets.get().keys(),+ ...$uploadingFilesDataStore.get().map((fileData) => fileData.assetId),+ ];++ for (const existingAssetId of existingIds) {+ if (uniqFilesDataMap.has(existingAssetId)) {+ const fileData = uniqFilesDataMap.get(existingAssetId)!;+ uniqFilesDataMap.delete(existingAssetId);+ toast.info("Asset already exists", {+ icon: <ToastImageInfo objectURL={fileData.objectURL} />,+ });+ }+ }++ const uniqFilesData = [...uniqFilesDataMap.values()];++ addUploadingFilesData(uniqFilesData);++ processUpload(uniqFilesData, projectId, authToken);++ const res = new Map();++ for (let i = 0; i < filesData.length; ++i) {+ const fileOrUrl = filesOrUrls[i];+ const fileData = filesData[i];++ invariant(+ fileOrUrl instanceof URL ||+ (fileOrUrl instanceof File &&+ fileData.source === "file" &&+ fileData.file === fileOrUrl)+ );+ invariant(+ fileOrUrl instanceof File ||+ (fileOrUrl instanceof URL &&+ fileData.source === "url" &&+ fileData.url === fileOrUrl.href)+ );++ res.set(filesOrUrls[i], filesData[i].assetId);+ }++ return res;+};++export const __testing__ = {+ deduplicateAssetName,+};diff --git a/apps/builder/app/builder/shared/assets/use-assets.test.ts b/apps/builder/app/builder/shared/assets/use-assets.test.tsnew file mode 100644index 0000000000..f6bace1622--- /dev/null+++ b/apps/builder/app/builder/shared/assets/use-assets.test.ts@@ -0,0 +1,125 @@+import { describe, test, expect } from "vitest";+import type { AssetContainer, UploadedAssetContainer } from "./types";+import type { Asset } from "@webstudio-is/sdk";+import { __testing__ } from "./use-assets";++const { filterByType } = __testing__;++describe("use-assets", () => {+ describe("filterByType", () => {+ const createImageAsset = (): Asset => ({+ id: "image-id",+ type: "image",+ name: "image-name",+ format: "png",+ size: 1000,+ meta: { width: 100, height: 100 },+ createdAt: "2024-01-01",+ projectId: "project-id",+ });++ const createFontAsset = (): Asset => ({+ id: "font-id",+ type: "font",+ name: "font-name",+ format: "woff2",+ size: 1000,+ meta: { family: "TestFont", style: "normal", weight: 400 },+ createdAt: "2024-01-01",+ projectId: "project-id",+ });++ const createFileAsset = (): Asset => ({+ id: "file-id",+ type: "file",+ name: "file-name",+ format: "pdf",+ size: 1000,+ meta: {},+ createdAt: "2024-01-01",+ projectId: "project-id",+ });++ const createUploadedContainer = (asset: Asset): UploadedAssetContainer => ({+ status: "uploaded",+ asset,+ });++ test("returns all containers when type is undefined", () => {+ const containers: AssetContainer[] = [+ createUploadedContainer(createImageAsset()),+ createUploadedContainer(createFontAsset()),+ createUploadedContainer(createFileAsset()),+ ];++ const result = filterByType(containers, undefined);++ expect(result).toEqual(containers);+ expect(result).toHaveLength(3);+ });++ test("filters containers by image type", () => {+ const imageContainer = createUploadedContainer(createImageAsset());+ const fontContainer = createUploadedContainer(createFontAsset());+ const fileContainer = createUploadedContainer(createFileAsset());+ const containers: AssetContainer[] = [+ imageContainer,+ fontContainer,+ fileContainer,+ ];++ const result = filterByType(containers, "image");++ expect(result).toEqual([imageContainer]);+ expect(result).toHaveLength(1);+ });++ test("filters containers by font type", () => {+ const imageContainer = createUploadedContainer(createImageAsset());+ const fontContainer = createUploadedContainer(createFontAsset());+ const containers: AssetContainer[] = [imageContainer, fontContainer];++ const result = filterByType(containers, "font");++ expect(result).toEqual([fontContainer]);+ expect(result).toHaveLength(1);+ });++ test("returns empty array when no containers match type", () => {+ const imageContainer = createUploadedContainer(createImageAsset());+ const containers: AssetContainer[] = [imageContainer];++ const result = filterByType(containers, "font");++ expect(result).toEqual([]);+ expect(result).toHaveLength(0);+ });++ test("returns empty array when given empty array", () => {+ const result = filterByType([], "image");++ expect(result).toEqual([]);+ expect(result).toHaveLength(0);+ });++ test("filters multiple containers of same type", () => {+ const imageContainer1 = createUploadedContainer(createImageAsset());+ const imageAsset2: Asset = {+ ...createImageAsset(),+ id: "image-id-2",+ };+ const imageContainer2 = createUploadedContainer(imageAsset2);+ const fontContainer = createUploadedContainer(createFontAsset());+ const containers: AssetContainer[] = [+ imageContainer1,+ fontContainer,+ imageContainer2,+ ];++ const result = filterByType(containers, "image");++ expect(result).toHaveLength(2);+ expect(result).toEqual([imageContainer1, imageContainer2]);+ });+ });+});diff --git a/apps/builder/app/builder/shared/assets/use-assets.tsx b/apps/builder/app/builder/shared/assets/use-assets.tsxindex 44c81de455..08b999a533 100644--- a/apps/builder/app/builder/shared/assets/use-assets.tsx+++ b/apps/builder/app/builder/shared/assets/use-assets.tsx@@ -1,204 +1,14 @@import { useMemo } from "react";import { computed } from "nanostores";import { useStore } from "@nanostores/react";-import warnOnce from "warn-once";-import invariant from "tiny-invariant";-import type { Asset, Page } from "@webstudio-is/sdk";-import type { AssetType } from "@webstudio-is/asset-uploader";-import { Box, toast, css, theme } from "@webstudio-is/design-system";-import { sanitizeS3Key } from "@webstudio-is/asset-uploader";-import { Image, wsImageLoader } from "@webstudio-is/image";-import type { ImageValue, StyleValue } from "@webstudio-is/css-engine";-import { restAssetsUploadPath, restAssetsPath } from "~/shared/router-utils";-import { fetch } from "~/shared/fetch.client";-import type { ActionData } from "~/builder/shared/assets";-import {- $assets,- $authToken,- $pages,- $project,- $props,- $styles,- $uploadingFilesDataStore,- type UploadingFileData,-} from "~/shared/nano-states";-import { serverSyncStore } from "~/shared/sync/sync-stores";+import type { Asset } from "@webstudio-is/sdk";+import { $assets, $uploadingFilesDataStore } from "~/shared/nano-states";import type {AssetContainer,UploadedAssetContainer,UploadingAssetContainer,} from "./types";-import {- formatAssetName,- getFileName,- getMimeType,- getSha256Hash,- getSha256HashOfFile,- uploadingFileDataToAsset,-} from "./asset-utils";-import { mapGetOrInsert } from "~/shared/shim";--export type AssetUsage =- | { type: "favicon" }- | { type: "socialImage"; pageId: Page["id"] }- | { type: "marketplaceThumbnail"; pageId: Page["id"] }- | { type: "prop"; propId: string }- | { type: "style"; styleDeclKey: string };--const traverseStyleValue = (- styleValue: StyleValue,- callback: (value: ImageValue) => void-) => {- if (styleValue.type === "image") {- callback(styleValue);- }- if (styleValue.type === "tuple") {- for (const item of styleValue.value) {- traverseStyleValue(item, callback);- }- }- if (styleValue.type === "layers") {- for (const item of styleValue.value) {- traverseStyleValue(item, callback);- }- }-};--export const $usagesByAssetId = computed(- [$pages, $props, $styles],- (pages, props, styles) => {- const usagesByAsset = new Map<Asset["id"], AssetUsage[]>();- if (pages?.meta?.faviconAssetId) {- const usages = mapGetOrInsert(- usagesByAsset,- pages.meta.faviconAssetId,- []- );- usages.push({ type: "favicon" });- }- if (pages) {- for (const page of [pages.homePage, ...pages.pages]) {- if (page.meta.socialImageAssetId) {- const usages = mapGetOrInsert(- usagesByAsset,- page.meta.socialImageAssetId,- []- );- usages.push({ type: "socialImage", pageId: page.id });- }- if (page.marketplace?.thumbnailAssetId) {- const usages = mapGetOrInsert(- usagesByAsset,- page.marketplace.thumbnailAssetId,- []- );- usages.push({ type: "marketplaceThumbnail", pageId: page.id });- }- }- }- for (const prop of props.values()) {- if (- prop.type === "asset" &&- // ignore width and height properties which are specific to size- prop.name !== "width" &&- prop.name !== "height"- ) {- const usages = mapGetOrInsert(usagesByAsset, prop.value, []);- usages.push({ type: "prop", propId: prop.id });- }- }- for (const [styleDeclKey, styleDecl] of styles) {- traverseStyleValue(styleDecl.value, (imageValue) => {- if (imageValue.value.type === "asset") {- const usages = mapGetOrInsert(- usagesByAsset,- imageValue.value.value,- []- );- usages.push({ type: "style", styleDeclKey });- }- });- }- return usagesByAsset;- }-);--export const deleteAssets = (assetIds: Asset["id"][]) => {- serverSyncStore.createTransaction([$assets], (assets) => {- for (const assetId of assetIds) {- assets.delete(assetId);- }- });-};--const safeDeleteAssets = (assetIds: Asset["id"][], projectId: string) => {- const currentProjectId = $project.get()?.id;-- if (currentProjectId !== projectId) {- toast.error("Project has been changed, files will not be uploaded");- // Can cause data corruption- return;- }-- deleteAssets(assetIds);-};--const safeSetAsset = (asset: Asset, projectId: string) => {- const currentProjectId = $project.get()?.id;-- if (currentProjectId !== projectId) {- toast.error("Project has been changed, files will not be uploaded");- // Can cause data corrupiton- return;- }-- serverSyncStore.createTransaction([$assets], (assets) => {- assets.set(asset.id, asset);- });-};--const getFilesData = async (- type: AssetType,- filesOrUrls: File[] | URL[]-): Promise<UploadingFileData[]> => {- const filesData: UploadingFileData[] = [];- for (const fileOrUrl of filesOrUrls) {- if (fileOrUrl instanceof File) {- const assetId = await getSha256HashOfFile(fileOrUrl);- filesData.push({- source: "file" as const,- assetId: assetId,- type,- file: fileOrUrl,- objectURL: URL.createObjectURL(fileOrUrl),- });- continue;- }-- const assetId = await getSha256Hash(fileOrUrl.href);- filesData.push({- source: "url" as const,- assetId,- type,- url: fileOrUrl.href,- objectURL: fileOrUrl.href,- });- }-- return filesData;-};--const addUploadingFilesData = (filesData: UploadingFileData[]) => {- const uploadingFilesData = $uploadingFilesDataStore.get();- $uploadingFilesDataStore.set([...uploadingFilesData, ...filesData]);-};--const deleteUploadingFileData = (id: UploadingFileData["assetId"]) => {- const uploadingFilesData = $uploadingFilesDataStore.get();- $uploadingFilesDataStore.set(- uploadingFilesData.filter((fileData) => fileData.assetId !== id)- );-};+import { uploadingFileDataToAsset } from "./asset-utils";const $assetContainers = computed([$assets, $uploadingFilesDataStore],@@ -234,319 +44,6 @@ const $assetContainers = computed(});-export type UploadData = ActionData;--const getVideoDimensions = async (file: File) => {- return new Promise<{ width: number; height: number }>((resolve, reject) => {- const url = URL.createObjectURL(file);- const vid = document.createElement("video");- vid.preload = "metadata";- vid.src = url;-- vid.onloadedmetadata = () => {- URL.revokeObjectURL(url);- resolve({ width: vid.videoWidth, height: vid.videoHeight });- };- vid.onerror = () => {- URL.revokeObjectURL(url);- reject(new Error("Invalid video file"));- };- });-};--const deduplicateAssetName = (name: string) => {- const existingNames = new Set();- for (const asset of $assets.get().values()) {- existingNames.add(formatAssetName(asset));- }- // eslint-disable-next-line no-constant-condition- for (let index = 0; true; index += 1) {- const suffix = index === 0 ? "" : `_${index}`;- const lastDotAt = name.lastIndexOf(".");- if (lastDotAt === -1) {- return name;- }- const basename = name.slice(0, lastDotAt);- const ext = name.slice(lastDotAt);- const nameWithSuffix = basename + suffix + ext;- if (!existingNames.has(nameWithSuffix)) {- return nameWithSuffix;- }- }-};--const uploadAsset = async ({- authToken,- projectId,- fileOrUrl,- assetType,- onCompleted,- onError,-}: {- authToken: undefined | string;- projectId: string;- fileOrUrl: File | URL;- assetType: AssetType;- onCompleted: (data: UploadData) => void;- onError: (error: string) => void;-}) => {- try {- const mimeType = getMimeType(fileOrUrl);- const fileName = getFileName(fileOrUrl);-- const metaFormData = new FormData();- metaFormData.append("projectId", projectId);- metaFormData.append("type", assetType);- // sanitizeS3Key here is just because of https://github.com/remix-run/remix/issues/4443- // should be removed after fix- metaFormData.append(- "filename",- deduplicateAssetName(sanitizeS3Key(fileName))- );-- const authHeaders = new Headers();- if (authToken !== undefined) {- authHeaders.set("x-auth-token", authToken);- }-- const metaResponse = await fetch(restAssetsPath(), {- method: "POST",- body: metaFormData,- headers: authHeaders,- });-- const metaData: { name: string } | { errors: string } =- await metaResponse.json();-- if ("errors" in metaData) {- throw Error(metaData.errors);- }-- const body =- fileOrUrl instanceof File- ? fileOrUrl- : JSON.stringify({ url: fileOrUrl.href });-- const headers = new Headers(authHeaders);-- if (fileOrUrl instanceof URL) {- headers.set("Content-Type", "application/json");- }-- let width = undefined;- let height = undefined;-- if (mimeType.startsWith("video/") && fileOrUrl instanceof File) {- const videoSize = await getVideoDimensions(fileOrUrl);- width = videoSize.width;- height = videoSize.height;- }-- const uploadResponse = await fetch(- restAssetsUploadPath({ name: metaData.name, width, height }),- {- method: "POST",- body,- headers,- }- );-- const uploadData: UploadData = await uploadResponse.json();-- if ("errors" in uploadData) {- throw Error(uploadData.errors);- }-- onCompleted(uploadData);- } catch (error) {- if (error instanceof Error) {- onError(error.message);- }- }-};--const handleAfterSubmit = (- assetId: string,- data: UploadData,- projectId: string-) => {- warnOnce(- data.uploadedAssets?.length !== 1,- "Expected exactly 1 uploaded asset"- );-- const uploadedAsset = data.uploadedAssets?.[0];-- if (uploadedAsset === undefined) {- warnOnce(true, "An uploaded asset is undefined");- toast.error("Could not upload an asset");- safeDeleteAssets([assetId], projectId);- return;- }-- // update store with new asset and set current id- safeSetAsset({ ...uploadedAsset, id: assetId }, projectId);-};--const imageWidth = css({- maxWidth: "100%",-});--const ToastImageInfo = ({ objectURL }: { objectURL: string }) => {- return (- <Box css={{ width: theme.spacing[18] }}>- <Image- className={imageWidth()}- src={objectURL}- optimize={false}- width={64}- loader={wsImageLoader}- />- </Box>- );-};--const processingQueue: [- filesData: UploadingFileData[],- projectId: string,- authToken: string | undefined,-][] = [];--const processUpload = async (- filesData: UploadingFileData[],- projectId: string,- authToken: string | undefined-) => {- processingQueue.push([filesData, projectId, authToken]);-- if (processingQueue.length > 1) {- return;- }-- while (processingQueue.length > 0) {- const [filesData, projectId, authToken] = processingQueue.shift()!;-- const currentProjectId = $project.get()?.id;- if (currentProjectId !== projectId) {- toast.error("Project has been changed, files will not be uploaded");- // Can cause data corrupiton- continue;- }-- for (const fileData of filesData) {- const assetId = fileData.assetId;-- if ($assets.get().has(assetId)) {- toast.info("Asset already exists", {- icon: <ToastImageInfo objectURL={fileData.objectURL} />,- });-- deleteUploadingFileData(assetId);- continue;- }-- await uploadAsset({- authToken,- projectId,- fileOrUrl:- fileData.source === "file" ? fileData.file : new URL(fileData.url),- assetType: fileData.type,- onCompleted: (data) => {- URL.revokeObjectURL(fileData.objectURL);- deleteUploadingFileData(assetId);- handleAfterSubmit(assetId, data, projectId);- },- onError: (error) => {- deleteUploadingFileData(assetId);- toast.error(error, {- icon: <ToastImageInfo objectURL={fileData.objectURL} />,- });-- safeDeleteAssets([assetId], projectId);- },- });- }- }-};--export async function uploadAssets(- type: AssetType,- files: File[]-): Promise<Map<File, string>>;--export async function uploadAssets(- type: AssetType,- urls: URL[]-): Promise<Map<URL, string>>;--/**- * returns a list of asset ids that are being uploaded- */-// eslint-disable-next-line func-style-export async function uploadAssets(- type: AssetType,- filesOrUrls: File[] | URL[]-): Promise<Map<URL | File, string>> {- const projectId = $project.get()?.id;- const authToken = $authToken.get();- if (projectId === undefined) {- return new Map();- }-- const filesData = await getFilesData(type, filesOrUrls);-- // Filter out duplicates inside filesData- const uniqFilesDataMap = new Map(- filesData.map((fileData) => [fileData.assetId, fileData])- );-- // Filter out duplicates existing in assets or uploading files- const existingIds = [- ...$assets.get().keys(),- ...$uploadingFilesDataStore.get().map((fileData) => fileData.assetId),- ];-- for (const existingAssetId of existingIds) {- if (uniqFilesDataMap.has(existingAssetId)) {- const fileData = uniqFilesDataMap.get(existingAssetId)!;- uniqFilesDataMap.delete(existingAssetId);- toast.info("Asset already exists", {- icon: <ToastImageInfo objectURL={fileData.objectURL} />,- });- }- }-- const uniqFilesData = [...uniqFilesDataMap.values()];-- addUploadingFilesData(uniqFilesData);-- processUpload(uniqFilesData, projectId, authToken);-- const res = new Map();-- for (let i = 0; i < filesData.length; ++i) {- const fileOrUrl = filesOrUrls[i];- const fileData = filesData[i];-- invariant(- fileOrUrl instanceof URL ||- (fileOrUrl instanceof File &&- fileData.source === "file" &&- fileData.file === fileOrUrl)- );- invariant(- fileOrUrl instanceof File ||- (fileOrUrl instanceof URL &&- fileData.source === "url" &&- fileData.url === fileOrUrl.href)- );-- res.set(filesOrUrls[i], filesData[i].assetId);- }-- return res;-}-const filterByType = (assetContainers: AssetContainer[],type: Asset["type"] | undefined@@ -573,3 +70,7 @@ export const useAssets = (type?: Asset["type"]) => {assetContainers: assetsByType,};};++export const __testing__ = {+ filterByType,+};diff --git a/apps/builder/app/routes/rest.assets_.$name.tsx b/apps/builder/app/routes/rest.assets_.$name.tsxindex 65eca88ade..c7f348b8ed 100644--- a/apps/builder/app/routes/rest.assets_.$name.tsx+++ b/apps/builder/app/routes/rest.assets_.$name.tsx@@ -1,13 +1,12 @@import { z } from "zod";import type { ActionFunctionArgs } from "@remix-run/server-runtime";-import type { Asset } from "@webstudio-is/sdk";import { uploadFile } from "@webstudio-is/asset-uploader/index.server";import {isAllowedMimeCategory,IMAGE_MIME_TYPES,ALLOWED_FILE_TYPES,} from "@webstudio-is/sdk";-import type { ActionData } from "~/builder/shared/assets";+import type { AssetActionResponse } from "~/builder/shared/assets";import { createAssetClient } from "~/shared/asset-client";import { createContext } from "~/shared/context.server";import { preventCrossOriginCookie } from "~/services/no-cross-origin-cookie";@@ -20,7 +19,7 @@ const UrlBody = z.object({export const action = async (props: ActionFunctionArgs-): Promise<ActionData | Array<Asset> | undefined> => {+): Promise<AssetActionResponse> => {preventCrossOriginCookie(props.request);await checkCsrf(props.request);@@ -133,4 +132,8 @@ export const action = async (errors: parseError(error).message,};}++ return {+ errors: "Method not allowed",+ };};diff --git a/apps/builder/app/shared/builder-api.ts b/apps/builder/app/shared/builder-api.tsindex c502c929fe..2d54858ea4 100644--- a/apps/builder/app/shared/builder-api.ts+++ b/apps/builder/app/shared/builder-api.ts@@ -1,7 +1,7 @@import { createRecursiveProxy } from "@trpc/server/shared";import invariant from "tiny-invariant";import { toast } from "@webstudio-is/design-system";-import { uploadAssets } from "~/builder/shared/assets/use-assets";+import { uploadAssets } from "~/builder/shared/assets/upload-assets";import { showTokenConflictDialog } from "./token-conflict-dialog";const apiWindowNamespace = "__webstudio__$__builderApi";