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
feat: When asset is deleted or uploaded - refresh asset resource (#5568)
Oleg Isonen905103c739c6
diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.mdindex 9ab8bd49f3..41156f0e8d 100644--- a/.github/copilot-instructions.md+++ b/.github/copilot-instructions.md@@ -39,21 +39,93 @@## Testing-- Test utilities, not components- Every bug fix must have a test to prevent regression+- Write tests for pure functions - avoid mocking whenever possible+- Extract testable pure logic from side-effect code (I/O, network, DOM, React hooks)+- **CRITICAL: Never define functions in test files that belong in implementation code**+- If a test requires a pure function, that function must be exported from the implementation and imported in the test-### Exporting Utilities for Testing+### When to Test-When testing internal utilities, export via `__testing__`:+**DO test:**++- Complex business logic with edge cases+- Pure functions with non-trivial computation (algorithms, parsing, calculations)+- Functions with multiple branches or conditions+- Bug fixes (regression prevention)++**DON'T test:**++- Trivial wrappers around library/language features (e.g., `map.delete()`)+- Simple data transformations with no logic+- Coordination code that only orchestrates side effects+- Direct framework integrations (DOM/React/hooks)++### Writing Testable Code++**WRONG** - Never define implementation logic in tests:```typescript-export const __testing__ = { internalUtility };+// ❌ BAD: Function defined in test file+const computeKey = (props: { assetId?: string }) => {+ return props.assetId ?? "default";+};++test("computes key", () => {+ expect(computeKey({ assetId: "123" })).toBe("123");+});```-Import in tests:+**CORRECT** - Extract to implementation, export, and test:```typescript-const { internalUtility } = __testing__;+// implementation.ts+export const computeKey = (props: {+ assetId?: string;+ src?: string;+ defaultValue?: unknown;+}) => {+ return (+ props.assetId?.toString() ??+ (props.defaultValue != null ? String(props.defaultValue) : undefined) ??+ (props.src != null ? String(props.src) : undefined)+ );+};++// implementation.test.ts+import { computeKey } from "./implementation";++test("computes key", () => {+ expect(computeKey({ assetId: "123" })).toBe("123");+});+```++This ensures:++- Implementation code is reusable and in the right place+- Tests verify actual production code, not duplicates+- No logic duplication between implementation and tests++### Exporting for Tests++**If the function is ALREADY used in production code:**++- Use regular export: `export const utilityFn = ...`+- The function has real production value beyond testing++**If the function is ONLY needed for tests (internal utility not used elsewhere):**++- Use `__testing__` export to signal it's for testing only:++```typescript+// implementation.ts+const internalHelper = (x: number) => x * 2;++export const __testing__ = { internalHelper };++// implementation.test.ts+import { __testing__ } from "./implementation";+const { internalHelper } = __testing__;```Don't create separate utility files just for testing.diff --git a/apps/builder/app/builder/shared/assets/delete-assets.ts b/apps/builder/app/builder/shared/assets/delete-assets.tsindex 6bd9ac814a..be31edd7d1 100644--- a/apps/builder/app/builder/shared/assets/delete-assets.ts+++ b/apps/builder/app/builder/shared/assets/delete-assets.ts@@ -1,6 +1,8 @@import type { Asset } from "@webstudio-is/sdk";import { $assets } from "~/shared/nano-states";import { serverSyncStore } from "~/shared/sync/sync-stores";+import { onNextTransactionComplete } from "~/shared/sync/project-queue";+import { invalidateAssets } from "~/shared/resources";export const deleteAssets = (assetIds: Asset["id"][]) => {serverSyncStore.createTransaction([$assets], (assets) => {@@ -8,4 +10,9 @@ export const deleteAssets = (assetIds: Asset["id"][]) => {assets.delete(assetId);}});++ // Wait for server to confirm transaction, then invalidate cache+ onNextTransactionComplete(() => {+ invalidateAssets();+ });};diff --git a/apps/builder/app/builder/shared/assets/upload-assets.tsx b/apps/builder/app/builder/shared/assets/upload-assets.tsxindex 4b01e3eb7f..245bd7f13f 100644--- a/apps/builder/app/builder/shared/assets/upload-assets.tsx+++ b/apps/builder/app/builder/shared/assets/upload-assets.tsx@@ -16,6 +16,8 @@ import {type UploadingFileData,} from "~/shared/nano-states";import { serverSyncStore } from "~/shared/sync/sync-stores";+import { onNextTransactionComplete } from "~/shared/sync/project-queue";+import { invalidateAssets } from "~/shared/resources";import {formatAssetName,getFileName,@@ -38,6 +40,10 @@ const safeDeleteAssets = (assetIds: Asset["id"][], projectId: string) => {assets.delete(assetId);}});++ onNextTransactionComplete(() => {+ invalidateAssets();+ });};const safeSetAsset = (asset: Asset, projectId: string) => {@@ -52,6 +58,10 @@ const safeSetAsset = (asset: Asset, projectId: string) => {serverSyncStore.createTransaction([$assets], (assets) => {assets.set(asset.id, asset);});++ onNextTransactionComplete(() => {+ invalidateAssets();+ });};const getFilesData = async <T extends File | URL>(diff --git a/apps/builder/app/canvas/features/webstudio-component/webstudio-component.test.tsx b/apps/builder/app/canvas/features/webstudio-component/webstudio-component.test.tsxnew file mode 100644index 0000000000..b41d7fe341--- /dev/null+++ b/apps/builder/app/canvas/features/webstudio-component/webstudio-component.test.tsx@@ -0,0 +1,81 @@+/**+ * @vitest-environment jsdom+ */+import { describe, test, expect } from "vitest";+import { __testing__ } from "./webstudio-component";++const { computeComponentKey } = __testing__;++describe("computeComponentKey - key generation logic", () => {+ test("prioritizes assetId over other props", () => {+ expect(+ computeComponentKey({+ $webstudio$canvasOnly$assetId: "asset-123",+ src: "/image.jpg",+ defaultValue: "default",+ })+ ).toBe("asset-123");+ });++ test("falls back to defaultValue when no assetId", () => {+ expect(+ computeComponentKey({+ src: "/image.jpg",+ defaultValue: "default-value",+ })+ ).toBe("default-value");+ });++ test("uses src when no assetId or defaultValue", () => {+ expect(+ computeComponentKey({+ src: "/path/to/video.mp4",+ })+ ).toBe("/path/to/video.mp4");+ });++ test("returns undefined when no relevant props", () => {+ expect(computeComponentKey({})).toBeUndefined();+ });++ test("handles null and undefined values", () => {+ expect(+ computeComponentKey({+ src: null,+ defaultValue: undefined,+ })+ ).toBeUndefined();+ });++ test("coerces defaultValue to string", () => {+ expect(computeComponentKey({ defaultValue: 42 })).toBe("42");+ expect(computeComponentKey({ defaultValue: true })).toBe("true");+ expect(computeComponentKey({ defaultValue: 0 })).toBe("0");+ });++ test("coerces src to string", () => {+ expect(computeComponentKey({ src: "string-src" })).toBe("string-src");+ expect(computeComponentKey({ src: 123 })).toBe("123");+ expect(computeComponentKey({ src: undefined })).toBeUndefined();+ });++ test("different assetIds produce different keys", () => {+ const key1 = computeComponentKey({+ $webstudio$canvasOnly$assetId: "asset-123",+ src: "/image.jpg",+ });+ const key2 = computeComponentKey({+ $webstudio$canvasOnly$assetId: "asset-456",+ src: "/image.jpg",+ });++ expect(key1).not.toBe(key2);+ });++ test("different src values produce different keys", () => {+ const key1 = computeComponentKey({ src: "/assets/video1.mp4" });+ const key2 = computeComponentKey({ src: "/assets/video2.mp4" });++ expect(key1).not.toBe(key2);+ });+});diff --git a/apps/builder/app/canvas/features/webstudio-component/webstudio-component.tsx b/apps/builder/app/canvas/features/webstudio-component/webstudio-component.tsxindex 2e38bdc72a..dedbdcb35b 100644--- a/apps/builder/app/canvas/features/webstudio-component/webstudio-component.tsx+++ b/apps/builder/app/canvas/features/webstudio-component/webstudio-component.tsx@@ -41,6 +41,21 @@ import {} from "@webstudio-is/react-sdk";import { rawTheme } from "@webstudio-is/design-system";import { Input, Select, Textarea } from "@webstudio-is/sdk-components-react";++const computeComponentKey = (props: Record<string, unknown>) => {+ const assetId = props.$webstudio$canvasOnly$assetId;+ const src = props.src;+ const defaultValue = props.defaultValue;++ return (+ (typeof assetId === "string" ? assetId : undefined) ??+ (defaultValue != null ? String(defaultValue) : undefined) ??+ (src != null ? String(src) : undefined)+ );+};++export const __testing__ = { computeComponentKey };+import {$propValuesByInstanceSelectorWithMemoryProps,getIndexedInstanceId,@@ -557,8 +572,9 @@ export const WebstudioComponentCanvas = forwardRef<// React ignores defaultValue changes after first render.// Key prop forces re-creation to reflect updates on canvas.- const key =- props.defaultValue != null ? props.defaultValue.toString() : undefined;+ // Also use assetId to recreate component when asset changes (e.g., deleted, replaced)+ // For expressions that resolve to asset URLs (via assets resource), use the src value itself+ const key = computeComponentKey(props);const instanceElement = (<>diff --git a/apps/builder/app/shared/resource-utils.ts b/apps/builder/app/shared/resource-utils.tsnew file mode 100644index 0000000000..5b71714842--- /dev/null+++ b/apps/builder/app/shared/resource-utils.ts@@ -0,0 +1,21 @@+import hash from "@emotion/hash";+import type { ResourceRequest } from "@webstudio-is/sdk";++export const getResourceKey = (resource: ResourceRequest) => {+ try {+ return hash(+ JSON.stringify([+ // explicitly list all fields to keep hash stable+ resource.name,+ resource.method,+ resource.url,+ resource.searchParams,+ resource.headers,+ resource.body,+ ])+ );+ } catch {+ // guard from invalid resources+ return "";+ }+};diff --git a/apps/builder/app/shared/resources.test.ts b/apps/builder/app/shared/resources.test.tsnew file mode 100644index 0000000000..de436d3097--- /dev/null+++ b/apps/builder/app/shared/resources.test.ts@@ -0,0 +1,212 @@+import { describe, test, expect } from "vitest";+import { getResourceKey } from "./resource-utils";+import type { ResourceRequest } from "@webstudio-is/sdk";++describe("getResourceKey - pure function tests", () => {+ test("generates consistent hash for same resource", () => {+ const resource: ResourceRequest = {+ name: "test",+ method: "get",+ url: "/api/test",+ searchParams: [],+ headers: [],+ };++ const key1 = getResourceKey(resource);+ const key2 = getResourceKey(resource);++ expect(key1).toBe(key2);+ expect(key1).toBeTruthy();+ expect(typeof key1).toBe("string");+ });++ test("generates different hashes for different resources", () => {+ const resource1: ResourceRequest = {+ name: "test1",+ method: "get",+ url: "/api/test1",+ searchParams: [],+ headers: [],+ };++ const resource2: ResourceRequest = {+ name: "test2",+ method: "get",+ url: "/api/test2",+ searchParams: [],+ headers: [],+ };++ const key1 = getResourceKey(resource1);+ const key2 = getResourceKey(resource2);++ expect(key1).not.toBe(key2);+ });++ test("different URLs produce different keys", () => {+ const base: ResourceRequest = {+ name: "api",+ method: "get",+ url: "/api/v1/users",+ searchParams: [],+ headers: [],+ };++ const modified: ResourceRequest = {+ ...base,+ url: "/api/v2/users",+ };++ expect(getResourceKey(base)).not.toBe(getResourceKey(modified));+ });++ test("different methods produce different keys", () => {+ const base: ResourceRequest = {+ name: "api",+ method: "get",+ url: "/api/users",+ searchParams: [],+ headers: [],+ };++ const modified: ResourceRequest = {+ ...base,+ method: "post",+ };++ expect(getResourceKey(base)).not.toBe(getResourceKey(modified));+ });++ test("search params affect the key", () => {+ const withoutParams: ResourceRequest = {+ name: "api",+ method: "get",+ url: "/api/users",+ searchParams: [],+ headers: [],+ };++ const withParams: ResourceRequest = {+ ...withoutParams,+ searchParams: [{ name: "page", value: "1" }],+ };++ expect(getResourceKey(withoutParams)).not.toBe(getResourceKey(withParams));+ });++ test("headers affect the key", () => {+ const withoutHeaders: ResourceRequest = {+ name: "api",+ method: "get",+ url: "/api/users",+ searchParams: [],+ headers: [],+ };++ const withHeaders: ResourceRequest = {+ ...withoutHeaders,+ headers: [{ name: "Authorization", value: "Bearer token" }],+ };++ expect(getResourceKey(withoutHeaders)).not.toBe(+ getResourceKey(withHeaders)+ );+ });++ test("body affects the key", () => {+ const withoutBody: ResourceRequest = {+ name: "api",+ method: "post",+ url: "/api/users",+ searchParams: [],+ headers: [],+ };++ const withBody: ResourceRequest = {+ ...withoutBody,+ body: JSON.stringify({ name: "John" }),+ };++ expect(getResourceKey(withoutBody)).not.toBe(getResourceKey(withBody));+ });++ test("handles resources with complex nested data", () => {+ const resource: ResourceRequest = {+ name: "complex",+ method: "post",+ url: "/api/test",+ searchParams: [+ { name: "filter", value: "active" },+ { name: "sort", value: "desc" },+ ],+ headers: [+ { name: "Content-Type", value: "application/json" },+ { name: "Authorization", value: "Bearer xyz" },+ ],+ body: JSON.stringify({ data: { nested: { value: true } } }),+ };++ const key = getResourceKey(resource);+ expect(key).toBeTruthy();+ expect(typeof key).toBe("string");+ });++ test("order of search params matters", () => {+ const resource1: ResourceRequest = {+ name: "api",+ method: "get",+ url: "/api/test",+ searchParams: [+ { name: "a", value: "1" },+ { name: "b", value: "2" },+ ],+ headers: [],+ };++ const resource2: ResourceRequest = {+ name: "api",+ method: "get",+ url: "/api/test",+ searchParams: [+ { name: "b", value: "2" },+ { name: "a", value: "1" },+ ],+ headers: [],+ };++ // Order matters because we serialize the array as-is+ expect(getResourceKey(resource1)).not.toBe(getResourceKey(resource2));+ });++ test("returns empty string for invalid resource with circular reference", () => {+ const invalidResource = {+ name: "test",+ method: "get" as const,+ url: "/api/test",+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ get searchParams(): any {+ return [this];+ },+ headers: [],+ };++ const key = getResourceKey(invalidResource);+ expect(key).toBe("");+ });++ test("assets system resource produces consistent key", () => {+ const assetsResource: ResourceRequest = {+ name: "assets",+ method: "get",+ url: "/$resources/assets",+ searchParams: [],+ headers: [],+ };++ const key1 = getResourceKey(assetsResource);+ const key2 = getResourceKey(assetsResource);++ expect(key1).toBe(key2);+ expect(key1).toBeTruthy();+ });+});diff --git a/apps/builder/app/shared/resources.ts b/apps/builder/app/shared/resources.tsindex 3f4078eb6f..90310e0883 100644--- a/apps/builder/app/shared/resources.ts+++ b/apps/builder/app/shared/resources.ts@@ -1,30 +1,13 @@import { atom, computed } from "nanostores";-import hash from "@emotion/hash";import type { DataSource, Resource, ResourceRequest } from "@webstudio-is/sdk";import { restResourcesLoader } from "./router-utils";import { computeExpression } from "./data-variables";import { fetch } from "./fetch.client";+import { getResourceKey } from "./resource-utils";const MAX_PENDING_RESOURCES = 5;-export const getResourceKey = (resource: ResourceRequest) => {- try {- return hash(- JSON.stringify([- // explicitly list all fields to keep hash stable- resource.name,- resource.method,- resource.url,- resource.searchParams,- resource.headers,- resource.body,- ])- );- } catch {- // guard from invalid resources- return "";- }-};+export { getResourceKey };const queue = new Map<string, ResourceRequest>();const pending = new Map<string, ResourceRequest>();@@ -102,6 +85,23 @@ export const invalidateResource = (resource: ResourceRequest) => {preloadResource(resource);};+/**+ * Invalidate the assets system resource.+ * Call this when assets are uploaded, deleted, or modified to refresh expressions using assets.+ */+export const invalidateAssets = () => {+ const url = "/$resources/assets";+ // System resources always use GET with no params/headers/body+ const systemResourceRequest: ResourceRequest = {+ name: "assets",+ method: "get",+ url,+ searchParams: [],+ headers: [],+ };+ invalidateResource(systemResourceRequest);+};+export const computeResourceRequest = (resource: Resource,values: Map<DataSource["id"], unknown>diff --git a/apps/builder/app/shared/sync/project-queue.ts b/apps/builder/app/shared/sync/project-queue.tsindex 613573b5d8..0614ced425 100644--- a/apps/builder/app/shared/sync/project-queue.ts+++ b/apps/builder/app/shared/sync/project-queue.ts@@ -42,6 +42,55 @@ export type QueueStatus =export const $queueStatus = atom<QueueStatus>({ status: "idle" });+// Transaction completion tracking+type TransactionCompleteCallback = (success: boolean) => void;+const transactionCallbacks = new Map<string, TransactionCompleteCallback[]>();++// Atom to communicate transaction IDs from sendTransaction to user code+export const $lastTransactionId = atom<string | undefined>(undefined);++/**+ * Register a callback to be called when a specific transaction is confirmed by the server.+ * The callback receives true if the transaction was successfully persisted, false otherwise.+ */+export const onTransactionComplete = (+ transactionId: string,+ callback: TransactionCompleteCallback+) => {+ const callbacks = transactionCallbacks.get(transactionId) ?? [];+ callbacks.push(callback);+ transactionCallbacks.set(transactionId, callbacks);++ // Cleanup after timeout to prevent memory leaks+ setTimeout(() => {+ transactionCallbacks.delete(transactionId);+ }, 60000); // 1 minute timeout+};++/**+ * Register a callback to be called when the next transaction is confirmed by the server.+ * Use this right after calling serverSyncStore.createTransaction().+ */+export const onNextTransactionComplete = (callback: () => void) => {+ let unsubscribe: (() => void) | undefined;+ // eslint-disable-next-line prefer-const+ unsubscribe = $lastTransactionId.subscribe((transactionId) => {+ if (transactionId) {+ onTransactionComplete(transactionId, (success) => {+ if (success) {+ callback();+ }+ });+ unsubscribe?.();+ }+ });++ // Cleanup after timeout to prevent memory leak if transaction never gets an ID+ setTimeout(() => {+ unsubscribe?.();+ }, 60000);+};+const getRandomBetween = (a: number, b: number) => {return Math.random() * (b - a) + a;};@@ -256,6 +305,18 @@ const pollQueue = async (signal: AbortSignal) => {const result = (await response.json()) as any;if (result.status === "ok") {details.version += 1;++ // Notify all transaction completion callbacks+ for (const transaction of transactions) {+ const callbacks = transactionCallbacks.get(transaction.id);+ if (callbacks) {+ for (const callback of callbacks) {+ callback(true);+ }+ transactionCallbacks.delete(transaction.id);+ }+ }+// stop retrying and wait next transactionscontinue polling;}@@ -335,6 +396,7 @@ export class ServerSyncStorage implements SyncStorage {sendTransaction(transaction: Transaction<Change[]>) {if (transaction.object === "server") {+ $lastTransactionId.set(transaction.id);commandQueue.enqueue({type: "transactions",transactions: [transaction],